blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
3
264
content_id
stringlengths
40
40
detected_licenses
listlengths
0
85
license_type
stringclasses
2 values
repo_name
stringlengths
5
140
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
986 values
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
3.89k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
23 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
145 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
3
10.4M
extension
stringclasses
122 values
content
stringlengths
3
10.4M
authors
listlengths
1
1
author_id
stringlengths
0
158
f2f6b4c0816245156c43bd39258350d000472ccd
cc27e4e9de21a4b6eae1ae80c886e08532a47b8f
/Lib/include/OpenMesh_o/Core/Geometry/Plane3d.hh
df07c5aa2dbdbd0963a40887ba3356a7faa317e4
[]
no_license
misop/diplomovka
3eacc5cab7a07b496f33a2eaa0388bfe2c0d67c9
fa8c1e1d0fd9d085d767977ad2715a464ced8934
refs/heads/master
2020-12-25T18:22:34.237634
2014-07-25T09:12:56
2014-07-25T09:12:56
8,234,555
2
1
null
null
null
null
UTF-8
C++
false
false
4,747
hh
/*===========================================================================*\ * * * OpenMesh * * Copyright (C) 2001-2011 by Computer Graphics Group, RWTH Aachen * * www.openmesh.org * * * *---------------------------------------------------------------------------* * This file is part of OpenMesh. * * * * OpenMesh is free software: you can redistribute it and/or modify * * it under the terms of the GNU Lesser General Public License as * * published by the Free Software Foundation, either version 3 of * * the License, or (at your option) any later version with the * * following exceptions: * * * * If other files instantiate templates or use macros * * or inline functions from this file, or you compile this file and * * link it with other files to produce an executable, this file does * * not by itself cause the resulting executable to be covered by the * * GNU Lesser General Public License. This exception does not however * * invalidate any other reasons why the executable file might be * * covered by the GNU Lesser General Public License. * * * * OpenMesh is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU Lesser General Public License for more details. * * * * You should have received a copy of the GNU LesserGeneral Public * * License along with OpenMesh. If not, * * see <http://www.gnu.org/licenses/>. * * * \*===========================================================================*/ /*===========================================================================*\ * * * $Revision: 362 $ * * $Date: 2011-01-26 10:21:12 +0100 (Wed, 26 Jan 2011) $ * * * \*===========================================================================*/ //============================================================================= // // CLASS Plane3D // //============================================================================= #ifndef OPENMESH_PLANE3D_HH #define OPENMESH_PLANE3D_HH //== INCLUDES ================================================================= #include <OpenMesh/Core/Geometry/VectorT.hh> //== FORWARDDECLARATIONS ====================================================== //== NAMESPACES =============================================================== namespace OpenMesh { namespace VDPM { //== CLASS DEFINITION ========================================================= /** \class Plane3d Plane3d.hh <OpenMesh/Tools/VDPM/Plane3d.hh> ax + by + cz + d = 0 */ class Plane3d { public: typedef OpenMesh::Vec3f vector_type; typedef vector_type::value_type value_type; public: Plane3d() : d_(0) { } Plane3d(const vector_type &_dir, const vector_type &_pnt) : n_(_dir), d_(0) { n_.normalize(); d_ = -dot(n_,_pnt); } value_type signed_distance(const OpenMesh::Vec3f &_p) { return dot(n_ , _p) + d_; } // back compatibility value_type singed_distance(const OpenMesh::Vec3f &point) { return signed_distance( point ); } public: vector_type n_; value_type d_; }; //============================================================================= } // namespace VDPM } // namespace OpenMesh //============================================================================= #endif // OPENMESH_PLANE3D_HH defined //=============================================================================
[ "michal.piovarci@gmail.com" ]
michal.piovarci@gmail.com
2035add443fdad13d7caf221da2c0b27d931ce69
5815fbec19ef1649fb229dbb3bb79318d76ed62c
/src/checkpoints.h
ece67935274b12bca2fe24311ac3bd8487ee9cb6
[ "MIT" ]
permissive
luxmicoin/Luxmi
a646c239cbb012d778f4953fc7407b3c7cf5ffa3
3eec7accdd8954006813d97d4dacc871173f341e
refs/heads/master
2021-05-07T17:50:12.239987
2017-10-29T10:48:54
2017-10-29T10:48:54
106,904,680
0
0
null
null
null
null
UTF-8
C++
false
false
3,916
h
// Copyright (c) 2009-2012 The Bitcoin developers // Copyright (c) 2017 The Luxmi developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef BITCOIN_CHECKPOINT_H #define BITCOIN_CHECKPOINT_H #include <map> #include "net.h" #include "util.h" #ifdef WIN32 #undef STRICT #undef PERMISSIVE #undef ADVISORY #endif class uint256; class CBlockIndex; class CSyncCheckpoint; /** Block-chain checkpoints are compiled-in sanity checks. * They are updated every release or three. */ namespace Checkpoints { /** Checkpointing mode */ enum CPMode { // Scrict checkpoints policy, perform conflicts verification and resolve conflicts STRICT = 0, // Advisory checkpoints policy, perform conflicts verification but don't try to resolve them ADVISORY = 1, // Permissive checkpoints policy, don't perform any checking PERMISSIVE = 2 }; // Returns true if block passes checkpoint checks bool CheckHardened(int nHeight, const uint256& hash); // Return conservative estimate of total number of blocks, 0 if unknown int GetTotalBlocksEstimate(); // Returns last CBlockIndex* in mapBlockIndex that is a checkpoint CBlockIndex* GetLastCheckpoint(const std::map<uint256, CBlockIndex*>& mapBlockIndex); extern uint256 hashSyncCheckpoint; extern CSyncCheckpoint checkpointMessage; extern uint256 hashInvalidCheckpoint; extern CCriticalSection cs_hashSyncCheckpoint; CBlockIndex* GetLastSyncCheckpoint(); bool WriteSyncCheckpoint(const uint256& hashCheckpoint); bool AcceptPendingSyncCheckpoint(); uint256 AutoSelectSyncCheckpoint(); bool CheckSync(const uint256& hashBlock, const CBlockIndex* pindexPrev); bool WantedByPendingSyncCheckpoint(uint256 hashBlock); bool ResetSyncCheckpoint(); void AskForPendingSyncCheckpoint(CNode* pfrom); bool SetCheckpointPrivKey(std::string strPrivKey); bool SendSyncCheckpoint(uint256 hashCheckpoint); bool IsMatureSyncCheckpoint(); } // Luxmi: synchronized checkpoint class CUnsignedSyncCheckpoint { public: int nVersion; uint256 hashCheckpoint; // checkpoint block IMPLEMENT_SERIALIZE ( READWRITE(this->nVersion); nVersion = this->nVersion; READWRITE(hashCheckpoint); ) void SetNull() { nVersion = 1; hashCheckpoint = 0; } std::string ToString() const { return strprintf( "CSyncCheckpoint(\n" " nVersion = %d\n" " hashCheckpoint = %s\n" ")\n", nVersion, hashCheckpoint.ToString().c_str()); } void print() const { printf("%s", ToString().c_str()); } }; class CSyncCheckpoint : public CUnsignedSyncCheckpoint { public: static const std::string strMasterPubKey; static std::string strMasterPrivKey; std::vector<unsigned char> vchMsg; std::vector<unsigned char> vchSig; CSyncCheckpoint() { SetNull(); } IMPLEMENT_SERIALIZE ( READWRITE(vchMsg); READWRITE(vchSig); ) void SetNull() { CUnsignedSyncCheckpoint::SetNull(); vchMsg.clear(); vchSig.clear(); } bool IsNull() const { return (hashCheckpoint == 0); } uint256 GetHash() const { return SerializeHash(*this); } bool RelayTo(CNode* pnode) const { // returns true if wasn't already sent if (pnode->hashCheckpointKnown != hashCheckpoint) { pnode->hashCheckpointKnown = hashCheckpoint; pnode->PushMessage("checkpoint", *this); return true; } return false; } bool CheckSignature(); bool ProcessSyncCheckpoint(CNode* pfrom); }; #endif
[ "luxmicoin@gmail.com" ]
luxmicoin@gmail.com
b3ae448f40741c1b3efacabaaa12cb6c5a676aae
98414c2d3346ba59ea98877da905c0232090a4a9
/RG2R_Engine/SoundManager.h
c05f4145504407f2fe72b9fcd47843fb45254060
[]
no_license
akfakf0509/Digital_Contest
e33acfc22f7de0a8c58e09a8ad7ccdd18b2d62e5
c458faf036a62c6ce6a20d862927ba9560f9f1e6
refs/heads/master
2021-07-15T04:13:06.105597
2020-10-29T03:22:16
2020-10-29T03:22:16
213,971,961
0
0
null
null
null
null
UTF-8
C++
false
false
1,459
h
#pragma once #include <map> using namespace std; using namespace std::experimental::filesystem; typedef int SoundCode; #define BUFSIZE 1048576*60 enum SoundType { ST_Wave, ST_Ogg, }; struct SoundOptions { float pitch = 1; float volume = 1; float dir = 0; bool isLoop = false; bool autoDelete = true; bool isMute = false; }; struct SoundResource { SoundType type; LPDIRECTSOUNDBUFFER buffer; }; struct WaveSoundResource : public SoundResource { DWORD dwSize; BYTE* pData; WAVEFORMATEX format; }; struct Sound { SoundType type; SoundResource* source; LPDIRECTSOUNDBUFFER buffer; SoundOptions options; int id; bool isPause = false; DWORD lastPos = 0; Sound(SoundType type) : type(type) {} Sound(SoundType type, SoundOptions options) : type(type), options(options) {} ~Sound() { buffer->Release(); } }; class SoundManager { private: std::map<const path, SoundResource*> soundSources; list<Sound*> sounds; LPDIRECTSOUND8 dsound_ = nullptr; OggVorbis_File oggVorbisFile_; bool UpdateSound(Sound*); public: SoundManager(); ~SoundManager(); void Update(); SoundCode Play(const path&); SoundCode Play(const path&, SoundOptions); SoundResource* Load(const path& filePath); Sound* GetSound(SoundCode); bool IsPlaying(SoundCode); bool IsPlaying(Sound*); void SetOptions(SoundCode, SoundOptions); void Pause(SoundCode); void Start(SoundCode); void Stop(SoundCode); void Delete(SoundCode); void Clear(); };
[ "50164284+akfakf0509@users.noreply.github.com" ]
50164284+akfakf0509@users.noreply.github.com
a95def315886963b5a740821bb2a3d9782ed03c3
93c66e44e6ae7e654aefc42cad10706a44aa2377
/concurrency/collection_of_threads.cpp
5eecc79c0f80fb11820aefb405e6def23ecb1fd6
[]
no_license
dcampora/cpp11
11a61227522baa5d83a8f0d81300c84553a923ca
db3e2830d2eed370134e6d25193d0f22e8dbd605
refs/heads/master
2020-05-17T18:38:38.325947
2016-01-20T08:47:41
2016-01-20T08:47:41
32,726,789
0
0
null
null
null
null
UTF-8
C++
false
false
726
cpp
#include <iostream> // cout, endl #include <thread> // thread #include <unordered_map> // unordered_map #include <cstdint> // intmax_t #include <vector> using std::cout; using std::endl; using INT = std::intmax_t; INT fib(INT n) { return n<2 ? 1 : fib(n-1) + fib(n-2); } std::unordered_map<INT, INT> fibs; int main() { INT min = 32; INT max = min + 10; std::vector<std::thread> threads; threads.reserve(max - min); // Your code goes here // :) for (INT i=min; i<max; ++i){ threads.emplace_back(std::thread([](INT n){ fibs[n] = fib(n); }, i)); } // :) for (auto& t : threads) t.join(); for (auto& pair : fibs) cout << pair.first << " " << pair.second << endl; }
[ "danielcampora@gmail.com" ]
danielcampora@gmail.com
f35e42949230ca65d464d9c205e8115b34b2ec3e
4e8a367ed7424890b7394d94f6f04a48cf03b5e8
/Arrays/3SumClosest.cpp
74f04cd64b7225499d2e2c60f24e8b32459726e9
[]
no_license
swapnilkant11/leetcode-problem-solutions-in-cpp
9087807206e10a9bd56729657983253b1dd76560
4328d8623230a9c687f912a8b7f8598ea4cda6a3
refs/heads/master
2022-12-01T04:10:41.689161
2020-08-20T18:25:52
2020-08-20T18:25:52
262,617,301
1
0
null
null
null
null
UTF-8
C++
false
false
1,192
cpp
// Given an array nums of n integers and an integer target, find three integers in nums such that the sum is closest to target. //Return the sum of the three integers. You may assume that each input would have exactly one solution. // created by Swapnil Kant // on 10-05-2020 int closestthreesum(int arr[], int n, int target){ int maxsum = INT_MAX; int sum = 0; for(int i = 0; i < n; i++){ // get the starting element as the next of current element. int startpointer = i + 1; // get the final element as the last element of the array. int endpointer = n - 1; // check for non intersecting element. if(startpointer < endpointer){ sum = arr[i] + arr[startpointer] + arr[endpointer]; // if current closest sum found update the variable maxsum. if(abs(1LL*target - sum) < abs(*1LLtarget - maxsum)) maxsum = sum; } // if sum is greater than target proceed to left of array. if(sum > target) endpointer--; // else proceed right. else startpointer++; } return maxsum; } // the time complexity of the above solution will be O(n). // the space complexity of the above algorithm is O(1).
[ "swapnilkant11@gmail.com" ]
swapnilkant11@gmail.com
87d5efe6f3b45fec5b232bb953f9a5a4ca1efc51
54e6cdf04c19da9815c3d939be2fea408cc82cc7
/game_logic/src/game_boolean_parameter.cpp
f14a7bb94c8017733472c2b8dad96649d15d8da5
[]
no_license
andyprowl/snake-overflow
0ef73f799e6c2ade25af7c9936da94ea3fa36b29
027b64ccb2562b5253e89df29bd42b61185b9145
refs/heads/master
2021-01-13T02:08:34.352229
2015-04-15T21:28:21
2015-04-15T21:28:21
32,992,332
3
0
null
null
null
null
UTF-8
C++
false
false
620
cpp
#include "stdafx.hpp" #include "snake_overflow/game_boolean_parameter.hpp" #include "snake_overflow/game_over_flag.hpp" namespace snake_overflow { game_boolean_parameter::game_boolean_parameter(bool const value, game_over_flag& game_over) : value{value} , game_over{game_over} { } game_boolean_parameter& game_boolean_parameter::operator = (bool const value) { if (this->game_over) { throw game_over_exception{}; } this->value = value; return *this; } game_boolean_parameter::operator bool () const { return this->value; } }
[ "andy.prowl@gmail.com" ]
andy.prowl@gmail.com
fd40eb5f198d799d2dd5c6e41f0c67d4dc4211bf
35a5b7c537945d5aacaafed3b1bd971dd3ce6e39
/LearnCpp3/main.cpp
d923b086da3e4476617bfb21151363f37e076c4c
[]
no_license
hebin1016/LearnCpp3
b5c56092dde1280bc76a2aa04d4e3e3fab420871
fb3a27bc02268fad64744ba5a53f9e68850d1533
refs/heads/master
2021-01-19T20:15:56.774925
2017-03-03T02:00:25
2017-03-03T02:00:25
83,745,570
0
0
null
null
null
null
UTF-8
C++
false
false
8,619
cpp
// // main.cpp // LearnCpp3 // // Created by hebin on 2017/2/10. // Copyright © 2017年 hebin. All rights reserved. // #include <iostream> using namespace std; /* //继承 //代码的重用 class Car{ public: void run(){ cout<<"行驶"<<endl; } protected: char* card; char* color; }; // class Truck:public Car{ private: int speed; public: void cargo(){ cout<<"拉货"<<endl; } }; void drive(Car& c){ c.run(); } int main(int argc, const char * argv[]) { Truck truck; drive(truck); //父类类型的引用或指针 Car* car=&truck; car->run(); Car& car2=truck; drive(car2); //子类对象初始化父类类型的对象 Car car3=truck; return 0; } */ /* //向父类构造方法传参 class Car{ public: Car(char* card,char* color){ this->card=card; this->color=color; } void run(){ cout<<"行驶"<<endl; } protected: char* card; char* color; }; //子类 class Truck:public Car{ private: int speed; Car car; public: //给父类构造方法传参同时给属性对象赋值 Truck(int speend,char* s_card,char* s_color,char* c_card,char* c_color):Car(s_card,s_color),car(s_card,s_color){ this->speed=speed; } void cargo(){ cout<<"拉货"<<endl; } }; int main(){ Truck truck(200,"9527","紫色","10086","黑色"); return 0; } */ /* //构造函数和析构函数的调用顺序 //Car构造函数 //Truck构造函数 //Truck析构函数 //Car析构函数 class Car{ public: Car(char* card,char* color){ this->card=card; this->color=color; cout<<"Car构造函数"<<endl; } ~Car(){ cout<<"Car析构函数"<<endl; } void run(){ cout<<"行驶"<<endl; } protected: char* card; char* color; }; //子类 class Truck:public Car{ private: int speed; public: //给父类构造方法传参同时给属性对象赋值 Truck(int speend,char* s_card,char* s_color):Car(s_card,s_color){ this->speed=speed; cout<<"Truck构造函数"<<endl; } ~Truck(){ cout<<"Truck析构函数"<<endl; } void cargo(){ cout<<"拉货"<<endl; } }; void func(){ //父类的构造函数先调用,子类的析构函数先调用 Truck truck(200,"9527","紫色"); } int main(){ func(); return 0; } */ /* //子类调用父类的成员 class Car{ public: Car(char* card,char* color){ this->card=card; this->color=color; } void run(){ cout<<"行驶"<<endl; } protected: char* card; char* color; }; //子类 class Truck:public Car{ private: int speed; public: //给父类构造方法传参同时给属性对象赋值 Truck(int speend,char* s_card,char* s_color):Car(s_card,s_color){ this->speed=speed; } void cargo(){ cout<<"拉货"<<endl; } void run(){ cout<<"拉货"<<endl; } }; int main(){ Truck t(200,"9527","白色"); //是覆盖,并非多态,调不到子类的方法 Car car=t; car.run(); //出了子类调父类的方法,或者赋值 Truck t2=t; t2.Car::run(); return 0; } */ /* //多继承 //鸟 class Bird{ }; //飞鸟 class Fly_bird{ }; //布谷鸟 class Bugu_bird:public Bird,public Fly_bird{ }; int main(){ return 0; } */ /* //继承的访问修饰符 class Car{ public: Car(char* card,char* color){ this->card=card; this->color=color; } void run(){ cout<<"行驶"<<endl; } private: char* card; char* color; }; //子类 class Truck:protected Car{ private: int speed; public: //给父类构造方法传参同时给属性对象赋值 Truck(int speend,char* s_card,char* s_color):Car(s_card,s_color){ this->speed=speed; } void cargo(){ cout<<"拉货"<<endl; this->run(); } void run(){ cout<<"拉货"<<endl; } }; int main(){ Truck t(300,"9527","aaaa"); //t.Car::run(); return 0; } */ /* //多继承的问题 //继承的二义性 //虚继承,不同路径继承来的同名成员只有一份拷贝,解决了不明确的问题 class A{ public: char *name; }; class A1:virtual public A{ }; class A2:virtual public A{ }; class B:public A1,public A2{ }; int main(){ B b; b.name="1111"; //指定父类显示调用 // b.A1::name="200"; // b.A2::name="300"; } */ /* //虚函数 //多态(程序的扩展性) //动态多态:程序运行过程中,觉得哪个函数被调用 //静态多态:重载 //发生动态多态的条件 //1.继承 //2.父类的引用指向子类的对象 //3.函数的重写 #include "Plane.h" #include "Jet.h" #include "Copter.h" //业务函数 void bizPlay(Plane& p){ p.fly(); p.land(); } int main(){ Plane p1; bizPlay(p1); Jet p2; bizPlay(p2); Copter p3; bizPlay(p3); return 0; } */ /* //纯虚函数(抽象类) //1.当一个类具有一个纯虚函数,这个类就是抽象类 //2.抽象类不能实例化 //3.子类继承抽象类,必须要实现纯虚函数,如果没有,子类也是抽象类 //抽象类的作用:为了继承约束,根本不知道未来的实现 class Shape{ //纯虚函数 virtual void sayArea()=0; }; class Circle:public Shape{ public: Circle(int r){ this->r=r; } void sayArea(){ cout<<"园的面积"<<endl; } private: int r; }; int main(){ Circle r(10); return 0; } */ /* //接口(只是逻辑上的划分,语法上和抽象类的写法没有区别) //可以当做一个接口 class Drawable{ virtual void draw()=0; }; */ /* //模板函数(泛型) //这两个函数业务逻辑一样,数据类型不一样 template <typename T> void my_swap(T& a,T& b) { T tmp=a; a=b; b=tmp; } int main(){ int a=10; int b=20; my_swap(a,b); cout<<a<<","<<b<<endl; char c='c';char d='d'; my_swap(c,d); cout<<c<<","<<d<<endl; return 0; } */ /* //模板类 template<class T> class A{ public: A(T a){ this->a=a; } protected: T a; }; //普通类模板类 class B:public A<int>{ public: B(int a,int b):A<int>(a){ this->b=b; } private: int b; }; //模板类继承模板类 template<class T> class C:public A<T>{ public: C(T a,T c):A<T>(a){ this->c=c; } private: T c; }; int main(){ //模板类对象 C<int> c(10,12); A<int> a(5); return 0; } */ /* //c++异常处理,根据抛出的异常数据类型,进入到相应的catch块中 int main(){ try{ int age=2000; if(age>300){ throw 9.9; } }catch(int a){ cout<<a<<endl; }catch(char *str){ cout<<str<<endl; }catch(...){ cout<<"未知异常"<<endl; } return 0; } */ /* //throw抛出函数外 void func(int x,int y){ if(y==0){ throw 10; } } int main(){ try{ func(10,0); }catch(int e){ cout<<e<<endl; } return 0; } */ /* //抛出异常 //异常类 class MyException{ }; void func1(int a,int b){ if(b==0){ //throw new MyException; //不要抛出异常指针 throw MyException(); } } int main(){ try{ func1(20,0); }catch(MyException &e){ cout<<"收到异常"<<endl; }catch(MyException *e1){ cout<<"收到异常指针"<<endl; delete e1; } return 0; } */ /* //声明函数会抛出的异常类型 void func1(int a,int b) throw(int){ if(b==0){ throw 0; } } */ /* //标准异常(类似java默认的那些异常) #include <stdexcept> class NullPointException:public exception{ public: NullPointException(char* msg):exception(){ } }; void func1(int a,int b){ if(b>20){ throw out_of_range("超出范围"); }else if(b==NULL){ throw NullPointException("为空"); }else if(b==0){ throw invalid_argument("参数不合法"); } } int main(){ try{ func1(10,NULL); }catch(out_of_range msg){ cout<<msg.what()<<endl; // }catch(invalid_argument msg){ // cout<<msg.what()<<endl; }catch(NullPointException& msg){ cout<<"为空"<<endl; } return 0; } */ /* //外部类异常 class Err{ public: class Exception{ }; }; void funp(){ throw Err::Exception(); } */
[ "hb494974108@gmail.com" ]
hb494974108@gmail.com
df629e16f2479b45cf4c888bb023703a60915ef6
b656dc19dcd1cbd76ef4d88c879e7f6fa2e885e4
/include/lishaderprogram.h
6cb61b0c31497034ce7286cbb57491b26f214240
[]
no_license
setrunk/LiCore
53b19b6c82b1129d10679c9b33c87fb276e00b51
b372688732901bbb6fd45dc0b21b99f8be5e935f
refs/heads/master
2020-05-20T01:16:20.121067
2019-11-19T14:02:46
2019-11-19T14:02:46
185,304,772
1
2
null
null
null
null
UTF-8
C++
false
false
12,109
h
#ifndef LISHADERPROGRAM_H #define LISHADERPROGRAM_H #include "linode.h" class LiShader; class LiShaderProgramPrivate; /** * @brief * LiShaderProgram是渲染模块的核心类,负责gpu渲染的方式,一般情况下由VertexShader和FragmentShader组成。 */ class LICORE_EXPORT LiShaderProgram : public LiNode { Q_OBJECT Q_PROPERTY(LiShader* vertexShader READ vertexShader WRITE setVertexShader NOTIFY vertexShaderChanged) Q_PROPERTY(LiShader* tessellationControlShader READ tessellationControlShader WRITE setTessellationControlShader NOTIFY tessellationControlShaderChanged) Q_PROPERTY(LiShader* tessellationEvaluationShader READ tessellationEvaluationShader WRITE setTessellationEvaluationShader NOTIFY tessellationEvaluationShaderChanged) Q_PROPERTY(LiShader* geometryShader READ geometryShader WRITE setGeometryShader NOTIFY geometryShaderChanged) Q_PROPERTY(LiShader* fragmentShader READ fragmentShader WRITE setFragmentShader NOTIFY fragmentShaderChanged) Q_PROPERTY(LiShader* computeShader READ computeShader WRITE setComputeShader NOTIFY computeShaderChanged) Q_PROPERTY(QByteArray vertexShaderCode READ vertexShaderCode WRITE setVertexShaderCode NOTIFY vertexShaderCodeChanged) Q_PROPERTY(QByteArray tessellationControlShaderCode READ tessellationControlShaderCode WRITE setTessellationControlShaderCode NOTIFY tessellationControlShaderCodeChanged) Q_PROPERTY(QByteArray tessellationEvaluationShaderCode READ tessellationEvaluationShaderCode WRITE setTessellationEvaluationShaderCode NOTIFY tessellationEvaluationShaderCodeChanged) Q_PROPERTY(QByteArray geometryShaderCode READ geometryShaderCode WRITE setGeometryShaderCode NOTIFY geometryShaderCodeChanged) Q_PROPERTY(QByteArray fragmentShaderCode READ fragmentShaderCode WRITE setFragmentShaderCode NOTIFY fragmentShaderCodeChanged) Q_PROPERTY(QByteArray computeShaderCode READ computeShaderCode WRITE setComputeShaderCode NOTIFY computeShaderCodeChanged) public: /** * @brief * Shader类型 */ enum ShaderType { Vertex = 0, Fragment, TessellationControl, TessellationEvaluation, Geometry, Compute }; Q_ENUM(ShaderType) // LCOV_EXCL_LINE /** * @brief * 内部标识 */ enum Flag { Lit = (1 << 0), DiffuseMap = (1 << 1), NormalMap = (1 << 2), Reflection = (1 << 3), TextureArray = (1 << 4), AlphaTest = (1 << 5), BatchTable = (1 << 6), Instanced = (1 << 7), ClipPlanes = (1 << 8), ClipVolumes = (1 << 9), ShadowPass = (1 << 10), DepthPass = (1 << 11), GBufferPass = (1 << 12) }; /** * @brief * 标准Shader类型,可通过类型创建内置标准Shader */ enum StandardShader { UnlitColor = 0, UnlitTexture, UnlitTextureAlpha, UnlitTextureArray, UnlitTextureArrayAlpha, LitColor, LitTexture, LitTextureAlpha, LitTextureArray, LitTextureArrayAlpha }; Q_ENUM(StandardShader) // LCOV_EXCL_LINE /** * @brief * 构造函数 * @param parent */ explicit LiShaderProgram(LiNode *parent = 0); /** * @brief * 构造函数 * @param vs * 顶点处理Shader * @param fs * 像素处理Shader * @param parent */ LiShaderProgram(LiShader *vs, LiShader *fs, LiNode *parent = 0); /** * @brief * 析构函数 */ virtual ~LiShaderProgram(); /** * @brief * 返回顶点Shader对象 * @return LiShader */ LiShader* vertexShader() const; /** * @brief * 返回像素Shader对象 * @return LiShader */ LiShader* fragmentShader() const; /** * @brief * 返回tessellationControlShader对象 * @return LiShader */ LiShader* tessellationControlShader() const; /** * @brief * 返回tessellationEvaluationShader对象 * @return LiShader */ LiShader* tessellationEvaluationShader() const; /** * @brief * 返回几何Shader对象 * @return LiShader */ LiShader* geometryShader() const; /** * @brief * 返回计算Shader对象 * @return LiShader */ LiShader* computeShader() const; /** * @brief * 返回顶点Shader的源码 * @return QByteArray */ QByteArray vertexShaderCode() const; /** * @brief * 返回像素Shader的源码 * @return QByteArray */ QByteArray fragmentShaderCode() const; /** * @brief * 返回tessellationControlShader的源码 * @return QByteArray */ QByteArray tessellationControlShaderCode() const; /** * @brief * 返回tessellationEvaluationShader的源码 * @return QByteArray */ QByteArray tessellationEvaluationShaderCode() const; /** * @brief * 返回几何Shader的源码 * @return QByteArray */ QByteArray geometryShaderCode() const; /** * @brief * 返回计算Shader的源码 * @return QByteArray */ QByteArray computeShaderCode() const; /** * @brief * 内部函数,外部不要调用 * @return LiNodeChangeBasePtr */ LiNodeChangeBasePtr createChangePtr() const Q_DECL_OVERRIDE; /** * @brief * 通过路径和宏定义创建LiShaderProgram对象 * @param vsUrl * 顶点Shader的文件路径 * @param fsUrl * 像素Shader的文件路径 * @param defines * 预编译的宏定义 * @return LiShaderProgram */ static LiShaderProgram *create(const QUrl &vsUrl, const QUrl &fsUrl, const QStringList &defines = QStringList()); /** * @brief * 通过路径和宏定义创建计算ShaderProgram对象 * @param url * 计算Shader的文件路径 * @param defines * 预编译的宏定义 * @return LiShaderProgram */ static LiShaderProgram *createCompute(const QUrl &url, const QStringList &defines = QStringList()); /** * @brief * 通过源码创建LiShaderProgram对象 * @param vs * 顶点Shader的源码 * @param fs * 像素Shader的源码 * @return LiShaderProgram */ static LiShaderProgram *createFromText(const QByteArray &vs, const QByteArray &fs); /** * @brief * 通过文件路径创建全屏处理ShaderProgram对象 * @param url * 全屏像素处理Shader的文件路径 * @param defines * 预编译的宏定义 * @return LiShaderProgram */ static LiShaderProgram *createViewportQuadShader(const QUrl &url, const QStringList &defines = QStringList()); /** * @brief * 创建内置标准的LiShaderProgram对象 * @param type * ShaderProgram的内置类型 * @return LiShaderProgram */ static LiShaderProgram *fromType(StandardShader type); /** * @brief * 通过标识创建内置标准的LiShaderProgram对象 * @param flags * ShaderProgram的内置标识 * @return LiShaderProgram */ static LiShaderProgram *fromFlags(uint flags); /** * @brief * 返回之前缓存的关键字key的LiShaderProgram对象 * @param key * 缓存关键字 * @return LiShaderProgram */ static LiShaderProgram *fromCache(const QString &key); /** * @brief * 缓存关键字key的LiShaderProgram对象 * @param key * 缓存关键字 * @param shaderProgram */ static void cacheShaderProgram(const QString &key, LiShaderProgram *shaderProgram); public Q_SLOTS: /** * @brief * 设置顶点Shader对象 * @param shader */ void setVertexShader(LiShader *shader); /** * @brief * 设置像素Shader对象 * @param shader */ void setFragmentShader(LiShader *shader); /** * @brief * 设置TessellationControlShader对象 * @param shader */ void setTessellationControlShader(LiShader *shader); /** * @brief * 设置TessellationEvaluationShader对象 * @param shader */ void setTessellationEvaluationShader(LiShader *shader); /** * @brief * 设置几何Shader对象 * @param shader */ void setGeometryShader(LiShader *shader); /** * @brief * 设置计算Shader对象 * @param shader */ void setComputeShader(LiShader *shader); /** * @brief * 设置顶点Shader源码 * @param vertexShaderCode */ void setVertexShaderCode(const QByteArray &vertexShaderCode); /** * @brief * 设置像素Shader源码 * @param fragmentShaderCode */ void setFragmentShaderCode(const QByteArray &fragmentShaderCode); /** * @brief * 设置TessellationControlShader源码 * @param tessellationControlShaderCode */ void setTessellationControlShaderCode(const QByteArray &tessellationControlShaderCode); /** * @brief * 设置TessellationEvaluationShader源码 * @param tessellationEvaluationShaderCode */ void setTessellationEvaluationShaderCode(const QByteArray &tessellationEvaluationShaderCode); /** * @brief * 设置几何Shader源码 * @param geometryShaderCode */ void setGeometryShaderCode(const QByteArray &geometryShaderCode); /** * @brief * 设置计算Shader源码 * @param computeShaderCode */ void setComputeShaderCode(const QByteArray &computeShaderCode); Q_INVOKABLE static QByteArray loadSource(const QUrl &sourceUrl); signals: /** * @brief * 顶点Shader对象改变时,发出该信号 * @param shader */ void vertexShaderChanged(LiShader *shader); /** * @brief * 像素Shader对象改变时,发出该信号 * @param shader */ void fragmentShaderChanged(LiShader *shader); /** * @brief * tessellationControlShader对象改变时,发出该信号 * @param shader */ void tessellationControlShaderChanged(LiShader *shader); /** * @brief * tessellationEvaluationShader对象改变时,发出该信号 * @param shader */ void tessellationEvaluationShaderChanged(LiShader *shader); /** * @brief * 几何Shader对象改变时,发出该信号 * @param shader */ void geometryShaderChanged(LiShader *shader); /** * @brief * 计算Shader对象改变时,发出该信号 * @param shader */ void computeShaderChanged(LiShader *shader); /** * @brief * 顶点Shader源码改变时,发出该信号 * @param vertexShaderCode */ void vertexShaderCodeChanged(const QByteArray &vertexShaderCode); /** * @brief * 像素Shader源码改变时,发出该信号 * @param fragmentShaderCode */ void fragmentShaderCodeChanged(const QByteArray &fragmentShaderCode); /** * @brief * tessellationControlShader源码改变时,发出该信号 * @param tessellationControlShaderCode */ void tessellationControlShaderCodeChanged(const QByteArray &tessellationControlShaderCode); /** * @brief * tessellationEvaluationShader源码改变时,发出该信号 * @param tessellationEvaluationShaderCode */ void tessellationEvaluationShaderCodeChanged(const QByteArray &tessellationEvaluationShaderCode); /** * @brief * 几何Shader源码改变时,发出该信号 * @param geometryShaderCode */ void geometryShaderCodeChanged(const QByteArray &geometryShaderCode); /** * @brief * 计算Shader源码改变时,发出该信号 * @param computeShaderCode */ void computeShaderCodeChanged(const QByteArray &computeShaderCode); private: Q_DECLARE_PRIVATE(LiShaderProgram) }; #endif // LISHADERPROGRAM_H
[ "setrunk@163.com" ]
setrunk@163.com
3baa93403c13e158ecca4514e05d787d0cc5f977
6a4d287c4ef8fbef960c37bfaca135f0f3278f7a
/20170716/d.h
d9472a6bcdd63ef470ae52d7362738fa2bd66ebd
[]
no_license
harryhare/leetcode
df9c93b5caee4d5697f7fc6b50c48a9b01aafd52
03f21ceaf3ec0bfb67d30371e31b8dcd865741f8
refs/heads/master
2023-06-08T14:10:47.462552
2023-05-28T05:27:46
2023-05-28T05:27:46
100,129,079
1
0
null
null
null
null
UTF-8
C++
false
false
68
h
#include<vector> #include<string> #include<map> using namespace std;
[ "harryhare@163.com" ]
harryhare@163.com
76b6a00d529b31fdecf190a979dd4e06991657b1
be93b9ffb49ec6f73d2558cedd02cd50a4060858
/Online judge solutions/Spoj/FOXLINGS.cpp
ce77e3bfd528398cda31160826b0b9c033fd8cf2
[]
no_license
salonimohta/competitive-programming
ceec3c2c87eb8078b051166654c3faac5ce27d0b
2639a14acf4beb453bb9277779ad5d705c6fa97a
refs/heads/master
2020-08-09T02:12:27.005619
2019-10-14T08:07:46
2019-10-14T08:07:46
213,975,049
2
0
null
2019-10-09T16:59:36
2019-10-09T16:59:36
null
UTF-8
C++
false
false
2,758
cpp
/* AARUSH JUNEJA @vivace IIT(ISM),Dhanbad */ #include<bits/stdc++.h> using namespace std; typedef double lf; typedef long long ll; typedef long double ld; typedef unsigned long long ull; typedef set<ll> sll; typedef vector<ll> vll; typedef map<string,ll> msl; typedef pair<ll,ll> ii; typedef vector<ii > vpll; typedef map<ll,ll> mll; typedef vector<vll > vvll; typedef list<ll> lll; typedef vector<lll > vlll; typedef pair<ll,ii> iii; #define rtn return #define gc getchar #define pb push_back #define ff first #define ss second #define mp(x,y) make_pair(x,y) #define all(a) a.begin(),a.end() #define allr(a) a.rbegin(),a.rend() #define lp(i,a,b) for(ll i = ll(a); i<=ll(b) ; i++) #define lpit(it,a) for(__typeof(a.begin()) it = a.begin(); it != a.end(); ++it) #define mid(s,e) (s+(e-s)/2) ll ip(){ ll x = 0; bool isNeg = false; char c; c = gc(); if(c == '-') isNeg = true , c = gc(); for( ; c >= '0' && c <= '9' ; c = gc()); x = (x << 1) + (x << 3) + c - '0'; if(isNeg) x *= -1; return x; } inline ll ncr(ll n,ll r){ ll ans = 1 ; if(r > n-r) r = n-r; lp(i,0,r){ans*=(n-i) ; ans/=(i+1); } rtn ans; } inline ll gcd(ll a,ll b){if(!a) rtn b; rtn gcd(b%a,a); } inline ll fme(ll x,ll n,ll mod){ll ans=1;x%=mod;while(n>0){if(n&1){ ans*=x;ans%=mod;} x*=x;x%=mod;n>>=1;}rtn ans%mod;} inline bool isPalin(string &s){ int len = s.size()-1;lp(i,0,(len/2)+1){if(!(s[i]==s[len-i])) rtn false;} rtn true;} inline ll lcm(ll a,ll b){rtn (a*b)/gcd(a,b); } inline ll fmm(ll a,ll b,ll m) {ll r=0;a%=m;b%=m;while(b>0){if(b&1){r+=a;r%=m;}a+=a;a%=m;b>>=1;}rtn r%m;} inline ll sfme(ll a,ll b,ll m) {ll r=1;a%=m;while(b>0){if(b&1)r=fmm(r,a,m);a=fmm(a,a,m);b>>=1;}rtn r%m;} //--------------------------------TEMPLATE ENDS HERE--------------------------------------------------// #define MOD 1000000007 map<ll,ll> par,sz; ll find(ll i){ while( i != par[i] ){ par[i] = par[par[i]]; // path compression i = par[i]; } return i; } bool merge(ll u,ll v){ ll a = find(u); ll b = find(v); if(a==b) return false; // union by rank/size if( sz[a] < sz[b] ) { par[a] = b; sz[b]++; } else { par[b] = a; sz[a]++; } return true; } inline int in(){ int NR=0; register char c=gc(); while( c < 48 || c > 57 ){ c=gc(); } while(c>47 && c< 58){ NR = (NR << 3) + (NR << 1) + (c - 48); c=gc(); } return NR; } int main(){ ios::sync_with_stdio(false); cin.tie(0); cout.tie(0); ll t,n,m,e,a,b,k; //ll p,q,curr,c; ///////////// START FROM HERE //////////////////// n = in() ; m = in(); ll ans = n; lp(i,1,m){ a = in() ; b = in(); if(!par[a]){ par[a] = a; sz[a] = 1; } if(!par[b]){ par[b] = b; sz[b] = 1; } if(merge(a,b)){ ans--; } } cout << ans << "\n"; return 0; }
[ "avijuneja.cs@gmail.com" ]
avijuneja.cs@gmail.com
312dbb0bd0c3a1cb38b1b27bffc56ed44f7c0161
de7e771699065ec21a340ada1060a3cf0bec3091
/core/src/java/org/apache/lucene/analysis/TokenFilter.cpp
cad8924c9b5393cc4cb43c29fdf95c2ac7071cf7
[]
no_license
sraihan73/Lucene-
0d7290bacba05c33b8d5762e0a2a30c1ec8cf110
1fe2b48428dcbd1feb3e10202ec991a5ca0d54f3
refs/heads/master
2020-03-31T07:23:46.505891
2018-12-08T14:57:54
2018-12-08T14:57:54
152,020,180
7
0
null
null
null
null
UTF-8
C++
false
false
373
cpp
using namespace std; #include "TokenFilter.h" namespace org::apache::lucene::analysis { TokenFilter::TokenFilter(shared_ptr<TokenStream> input) : TokenStream(input), input(input) { } void TokenFilter::end() { input->end(); } TokenFilter::~TokenFilter() { delete input; } void TokenFilter::reset() { input->reset(); } } // namespace org::apache::lucene::analysis
[ "smamunr@fedora.localdomain" ]
smamunr@fedora.localdomain
8e6507913996cba7a24161d91499ff118e274826
55478ef22190e0901a1e2d8b62d031453c1ee4e7
/Verilog.cc
b3ee91bcdde4fba81f48fbb657dc86499e0b4bb0
[]
no_license
DTharun/verilog2cpp
d72bdae0cc6a3faea831b126801a469fae926061
03f7292e1c87ce90dd9d728c51eb8885762573a8
refs/heads/master
2022-01-13T19:24:35.266490
2019-05-24T09:10:18
2019-05-24T09:10:18
119,534,992
4
0
null
null
null
null
UTF-8
C++
false
false
88,423
cc
/* * Copyright (C) 2000-2003 moe * * This source code is free software; you can redistribute it * and/or modify it in source code form 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA */ #include "Verilog.hh" FILE* verilog_input; string verilog_file; string verilog_comment; moe::Verilog* source_; namespace moe { static char* opName_[] = { "ArithmeticAdd", "ArithmeticMinus", "ArithmeticMultiply", "ArithmeticDivide", "ArithmeticModulus", "ArithmeticLeftShift", "ArithmeticRightShift", "ArithmeticPower", "LeftShift", "RightShift", "LessThan", "GreaterThan", "LessEqual", "GreaterEqual", "CaseEquality", "CaseInequality", "LogicalNegation", "LogicalAND", "LogicalOR", "LogicalEquality", "LogicalInequality", "BitwiseAND", "BitwiseOR", "BitwiseNOR", "BitwiseNXOR", "BitwiseXOR", "BitwiseNegation", "ReductionAND", "ReductionNAND", "ReductionNOR", "ReductionNXOR", "ReductionXOR", "ReductionOR", "CastUnsigned", "CastSigned" }; static char* opToken_[] = { "+", // ArithmeticAdd, "-", // ArithmeticMinus, "*", // ArithmeticMultiply, "/", // ArithmeticDivide, "%%", // ArithmeticModulus, "<<<", // ArithmeticLeftShift, ">>>", // ArithmeticRightShift, "**", // ArithmeticPower, "<<", // LeftShift, ">>", // RightShift, "<", // LessThan, ">", // GreaterThan, "<=", // LessEqual, ">=", // GreaterEqual, "===", // CaseEquality, "!==", // CaseInequality, "!", // LogicalNegation, "&&", // LogicalAND, "||", // LogicalOR, "==", // LogicalEquality, "!=", // LogicalInequality, "&", // BitwiseAND, "|", // BitwiseOR, "~|", // BitwiseNOR, "~^", // BitwiseNXOR, "^", // BitwiseXOR, "~", // BitwiseNegation, "&", // ReductionAND, "~&", // ReductionNAND, "~|", // ReductionNOR, "~^", // ReductionNXOR, "^", // ReductionXOR, "|", // ReductionOR, "$unsigned", // CastUnsigned, "$signed", // CastSigned }; static void printName(ostream& ostr,const string& name) { ostr << name; if( name.c_str()[0]=='\\' ) ostr << ' '; } //////////////////////////////////////////////////////////////////////// // Verilog::String //////////////////////////////////// Verilog::String::String(const char* text): text_(text) { } void Verilog::String::toXML(std::ostream& ostr) const { ostr << '"' << text_ << '"'; } void Verilog::String::toVerilog(std::ostream& ostr) const { ostr << '"' << text_ << '"'; } void Verilog::String::link(const map<string,Net*>& net,Module* mod,const string& scope) { } void Verilog::String::callback(Callback& cb) const { cb.trap( this ); } //////////////////////////////////////////////////////////////////////// // Verilog::Number //////////////////////////////////// Verilog::Number::Number(const char* text): text_(text) { static char* BIN_NUM ="01XZ"; static char* OCT_NUM ="01234567XZ"; static char* HEX_NUM ="0123456789ABCDEFXZ"; vector<char> bits; const char* ptr; int base; unsigned int width; ptr =strchr(text,'\''); if( ptr!=NULL ) { ptr =text; width =0; for( ;*ptr!='\'';ptr++ ) if( isdigit(*ptr) ) { width *=10; width +=int(*ptr-'0'); } if( width==0 ) width =32; ptr++; if( *ptr!=0 ) { if( *ptr=='b' || *ptr=='B' ) base =2; else if( *ptr=='o' || *ptr=='O' ) base =8; else if( *ptr=='h' || *ptr=='H' ) base =16; else base =10; } else base =10; } else { width =32; base =10; ptr =text; } int i; unsigned long val; if( base==10 ) { val =0; for( ;*ptr!=0;ptr++ ) if( isdigit(*ptr) ) { val *=10; val +=int(*ptr-'0'); } for(i=0;i<width;i++) bits.push_back( ((val>>i)&1) ? '1' : '0' ); } else { i =0; char* idx; ptr =text+strlen(text)-1; for( ;*ptr!='\'';ptr-- ) { switch( base ) { case 2: //idx = index(BIN_NUM,toupper(*ptr)); IITH idx = strchr(BIN_NUM,toupper(*ptr)); if( idx!=NULL ) if( bits.size()<width ) bits.push_back( *idx ); break; case 8: //idx = index(OCT_NUM,toupper(*ptr)); IITH idx = strchr(OCT_NUM,toupper(*ptr)); if( idx!=NULL ) { val =int(idx-OCT_NUM); if( val < 8 ) for( i=0;i<3;i++ ) if( bits.size()<width ) bits.push_back( ((val>>i)&1) ? '1' : '0' ); else for( i=0;i<3;i++ ) if( bits.size()<width ) bits.push_back( *idx ); } break; case 16: //idx =index(HEX_NUM,toupper(*ptr)); IITH idx = strchr(HEX_NUM,toupper(*ptr)); if( idx!=NULL ) { val =int(idx-HEX_NUM); if( val < 16 ) for( i=0;i<4;i++ ) if( bits.size()<width ) bits.push_back( ((val>>i)&1) ? '1' : '0' ); else for( i=0;i<4;i++ ) if( bits.size()<width ) bits.push_back( *idx ); } break; } if( ptr==text ) break; } } for( i=bits.size();i<width;i++ ) bits.push_back( '0' ); for( i=width-1;i>=0;i-- ) bitset_ +=bits[i]; if( isPartial() ) { string::iterator i; string tmp =bitset_; for( i=tmp.begin();i!=tmp.end();++i ) if( ((*i)=='X') || ((*i)=='Z') || ((*i)=='?') ) (*i) ='0'; value_ =tmp; tmp =bitset_; for( i=tmp.begin();i!=tmp.end();++i ) if( ((*i)=='1') || ((*i)=='0') ) (*i) ='1'; else (*i) ='0'; mask_ =tmp; } else { value_ =bitset_; } width_ =bitset_.size(); } bool Verilog::Number::isPartial() const { if( bitset_.find('X')!=string::npos ) return( true ); if( bitset_.find('?')!=string::npos ) return( true ); if( bitset_.find('Z')!=string::npos ) return( true ); return( false ); } signed Verilog::Number::calcConstant() const { signed ret =0; int i; for( i=0;i<bitset_.size();i++ ) { ret =ret<<1; if( bitset_[i]=='1' ) ret |=1; } return ret; } void Verilog::Number::toXML(std::ostream& ostr) const { ostr << bitset_; } void Verilog::Number::toVerilog(std::ostream& ostr) const { ostr << text_; } void Verilog::Number::link(const map<string,Net*>& net,Module* mod,const string& scope) { /** string tmp =bitset_; string::iterator i; { for( i=tmp.begin();i!=tmp.end();++i ) if( ((*i)=='X') ||((*i)=='Z') ) (*i)='0'; value_ =mod->newNet(tmp.c_str(),Net::CONSTANT,width()-1,0,Net::PRIVATE,0,0); } if( isPartial() ) { tmp =bitset_; for( i=tmp.begin();i!=tmp.end();++i ) if( ((*i)=='1') ||((*i)=='0') ) (*i)='1'; else if( ((*i)=='X') ||((*i)=='Z') ) (*i)='0'; mask_ =mod->newNet(tmp.c_str(),Net::MASK,width()-1,0,Net::PRIVATE,0,0); } **/ } void Verilog::Number::callback(Callback& cb) const { cb.trap( this ); } //////////////////////////////////////////////////////////////////////// // Verilog::Identifier //////////////////////////////////// Verilog::Identifier::~Identifier() { delete msb_; delete lsb_; delete idx_; } void Verilog::Identifier::toXML(std::ostream& ostr) const { ostr << name_; if( idx_!=NULL ) { ostr << '['; idx_->toXML(ostr); ostr << ']'; } else if( msb_!=NULL && lsb_!=NULL ) { ostr << '['; msb_->toXML(ostr); ostr << ':'; lsb_->toXML(ostr); ostr << ']'; } } void Verilog::Identifier::toVerilog(std::ostream& ostr) const { printName( ostr,name_ ); if( idx_!=NULL ) { ostr << '['; idx_->toVerilog(ostr); ostr << ']'; } else if( msb_!=NULL && lsb_!=NULL ) { ostr << '['; msb_->toVerilog(ostr); ostr << ':'; lsb_->toVerilog(ostr); ostr << ']'; } } bool Verilog::Identifier::isPartial() const { if( idx_!=NULL ) { return true; } else if( msb_!=NULL && lsb_!=NULL ) { if( net_!=NULL ) { if( net_->msb()!=NULL && net_->lsb()!=NULL ) { if( (msb_->calcConstant()==net_->msb()->calcConstant()) && (lsb_->calcConstant()==net_->lsb()->calcConstant()) ) return false; else return true; } else { return true; } } else { std::cerr << " can't estimate. " << name_ << " is not linked.\n"; return true; } } else return false; } unsigned int Verilog::Identifier::width() const { if( idx_!=NULL ) { if( net_->isArray() ) return net_->width(); else return 1; } else if( msb_!=NULL && lsb_!=NULL ) { return (msb_->calcConstant()-lsb_->calcConstant()+1); } else { return net_->width(); } } void Verilog::Identifier::link(const map<string,Net*>& net,Module* mod,const string& scope) { if( msb_!=NULL ) msb_->link(net,mod,scope); if( lsb_!=NULL ) lsb_->link(net,mod,scope); if( idx_!=NULL ) idx_->link(net,mod,scope); // HIDENTIFIER // DIDENTIFIER bool hie=false; if( (name_.c_str()[0]!='\\')&& (name_.c_str()[0]!='`') ) if( name_.find(".")!=string::npos ) { hie =true; name_ ='\\' + name_; } { int i; while( (i=name_.find(".\\"))!=string::npos ) name_.replace(i,2,"."); } map<string,Net*>::const_iterator i; if( name_.c_str()[0]=='\\' ) { i =net.find( scope + '.' + name_.substr(name_.rfind(".")+1) ); if( i!=net.end() ) { net_ =i->second; return; } } i =net.find( scope + '.' + name_ ); if( i!=net.end() ) { net_ =i->second; return; } i =net.find(name_); if( i!=net.end() ) { net_ =i->second; return; } if( name_.c_str()[0]=='`' ) { std::cerr << "not defined identifier : " << name_ << std::endl; return; } if( !hie ) { // cout << scope << ' ' << name_ << ' ' // << string(scope + '.' + name_.substr(name_.rfind(".")+1)) // << endl; std::cerr << "implicit identifier : " << name_ << std::endl; net_ =mod->newNet( name_.c_str(),Verilog::Net::IMPLICIT ); return; } } Verilog::Expression* Verilog::Identifier::clone(const string& hname) const { Verilog::Identifier* ret =new Identifier(); if( name_.c_str()[0]=='`' ) // global defined name ret->name_ =name_; else ret->name_ =hname + name_; ret->msb_ =(msb_!=NULL) ? msb_->clone(hname) : NULL; ret->lsb_ =(lsb_!=NULL) ? lsb_->clone(hname) : NULL; ret->idx_ =(idx_!=NULL) ? idx_->clone(hname) : NULL; return ret; } Verilog::Expression* Verilog::Identifier::clone() const { Verilog::Identifier* ret =new Identifier(); ret->name_ =name_; ret->msb_ =(msb_!=NULL) ? msb_->clone() : NULL; ret->lsb_ =(lsb_!=NULL) ? lsb_->clone() : NULL; ret->idx_ =(idx_!=NULL) ? idx_->clone() : NULL; return ret; } void Verilog::Identifier::chain(set<const Net*>& ev) const { if( net_!=NULL ) ev.insert(net_); if( msb_!=NULL ) msb_->chain(ev); if( lsb_!=NULL ) lsb_->chain(ev); if( idx_!=NULL ) idx_->chain(ev); } void Verilog::Identifier::chain(set<const Expression*>& ev) const { ev.insert((Expression*)this); if( msb_!=NULL ) msb_->chain(ev); if( lsb_!=NULL ) lsb_->chain(ev); if( idx_!=NULL ) idx_->chain(ev); } void Verilog::Identifier::callback(Callback& cb) const { cb.trap( this ); } //////////////////////////////////////////////////////////////////////// // Verilog::Concat //////////////////////////////////// Verilog::Concat::~Concat() { vector<Expression*>::iterator i; for( i=list_.begin();i!=list_.end();++i ) { delete *i; } } void Verilog::Concat::toXML(std::ostream& ostr) const { if( repeat_!=NULL ) { ostr << '{'; repeat_->toXML(ostr); } ostr << '{'; vector<Expression*>::const_iterator i; for( i=list_.begin();i!=list_.end();++i ) { if( i!=list_.begin() ) ostr << ','; (*i)->toXML(ostr); } ostr << '}'; if( repeat_!=NULL ) ostr << '}'; } void Verilog::Concat::toVerilog(std::ostream& ostr) const { if( repeat_!=NULL ) { ostr << '{'; repeat_->toVerilog(ostr); } ostr << '{'; vector<Expression*>::const_iterator i; for( i=list_.begin();i!=list_.end();++i ) { if( i!=list_.begin() ) ostr << ','; (*i)->toVerilog(ostr); } ostr << '}'; if( repeat_!=NULL ) ostr << '}'; } void Verilog::Concat::link(const map<string,Net*>& net,Module* mod,const string& scope) { if( repeat_!=NULL ) repeat_->link(net,mod,scope); vector<Expression*>::iterator i; for( i=list_.begin();i!=list_.end();++i ) (*i)->link(net,mod,scope); } unsigned int Verilog::Concat::width() const { unsigned int ret=0; vector<Expression*>::const_iterator i; for( i=list_.begin();i!=list_.end();++i ) ret +=(*i)->width(); if( repeat_!=NULL ) ret *=repeat_->calcConstant(); return ret; } Verilog::Expression* Verilog::Concat::clone(const string& hname) const { Verilog::Concat* ret =new Verilog::Concat; if( repeat_!=NULL ) ret->repeat_ =repeat_->clone(hname); vector<Expression*>::const_iterator i; for( i=list_.begin();i!=list_.end();++i ) ret->list_.push_back( (*i)->clone(hname) ); return ret; } Verilog::Expression* Verilog::Concat::clone() const { Verilog::Concat* ret =new Verilog::Concat; if( repeat_!=NULL ) ret->repeat_ =repeat_->clone(); vector<Expression*>::const_iterator i; for( i=list_.begin();i!=list_.end();++i ) ret->list_.push_back( (*i)->clone() ); return ret; } void Verilog::Concat::chain(set<const Net*>& ev) const { if( repeat_!=NULL ) repeat_->chain(ev); vector<Expression*>::const_iterator i; for( i=list_.begin();i!=list_.end();++i ) (*i)->chain(ev); } void Verilog::Concat::chain(set<const Expression*>& ev) const { ev.insert((Expression*)this); if( repeat_!=NULL ) repeat_->chain(ev); vector<Expression*>::const_iterator i; for( i=list_.begin();i!=list_.end();++i ) (*i)->chain(ev); } void Verilog::Concat::callback(Callback& cb) const { cb.trap( this ); } //////////////////////////////////////////////////////////////////////// // Verilog::Event //////////////////////////////////// Verilog::Event::~Event() { delete expr_; } void Verilog::Event::toXML(std::ostream& ostr) const { switch( type_ ) { case POSEDGE: ostr << "posedge "; break; case NEGEDGE: ostr << "negedge "; break; } expr_->toXML(ostr); } void Verilog::Event::toVerilog(std::ostream& ostr) const { switch( type_ ) { case POSEDGE: ostr << "posedge "; break; case NEGEDGE: ostr << "negedge "; break; } expr_->toVerilog(ostr); } void Verilog::Event::link(const map<string,Net*>& net,Module* mod,const string& scope) { expr_->link(net,mod,scope); } Verilog::Expression* Verilog::Event::clone(const string& hname) const { return new Verilog::Event(type_, (expr_!=NULL) ? expr_->clone(hname) : NULL ); } Verilog::Expression* Verilog::Event::clone() const { return new Verilog::Event(type_, (expr_!=NULL) ? expr_->clone() : NULL ); } void Verilog::Event::chain(set<const Net*>& ev) const { if( expr_!=NULL ) expr_->chain(ev); } void Verilog::Event::chain(set<const Expression*>& ev) const { ev.insert((Expression*)this); if( expr_!=NULL ) expr_->chain(ev); } void Verilog::Event::callback(Callback& cb) const { cb.trap( this ); } //////////////////////////////////////////////////////////////////////// // Verilog::Unary //////////////////////////////////// Verilog::Unary::~Unary() { delete expr_; } unsigned int Verilog::Unary::width() const { unsigned int w =expr_->width(); switch( op_ ) { case Expression::ArithmeticMinus: w =expr_->width(); break; case Expression::BitwiseNegation: w =expr_->width(); break; case Expression::LogicalNegation: case Expression::ReductionAND: case Expression::ReductionOR: case Expression::ReductionXOR: case Expression::ReductionNAND: case Expression::ReductionNOR: case Expression::ReductionNXOR: w =1; break; case Expression::CastSigned: case Expression::CastUnsigned: w =expr_->width(); break; default: w =1; break; } return w; } signed Verilog::Unary::calcConstant() const { int ret; switch( op_ ) { case ArithmeticMinus: ret =-expr_->calcConstant(); break; default: ret =expr_->calcConstant(); break; } return ret; } void Verilog::Unary::toXML(std::ostream& ostr) const { ostr << opToken_[op_]; ostr << '('; expr_->toXML(ostr); ostr << ')'; } void Verilog::Unary::toVerilog(std::ostream& ostr) const { switch( op_ ) { case Expression::CastSigned: case Expression::CastUnsigned: ostr << opToken_[op_]; ostr << '('; break; default: ostr << '('; ostr << opToken_[op_]; break; } expr_->toVerilog(ostr); ostr << ')'; } const char* Verilog::Unary::opToken() const { return opToken_[op_]; } const char* Verilog::Unary::opName() const { return opName_[op_]; } void Verilog::Unary::link(const map<string,Net*>& net,Module* mod,const string& scope) { expr_->link(net,mod,scope); } Verilog::Expression* Verilog::Unary::clone(const string& hname) const { return new Verilog::Unary(op_, (expr_!=NULL) ? expr_->clone(hname) : NULL ); } Verilog::Expression* Verilog::Unary::clone() const { return new Verilog::Unary(op_, (expr_!=NULL) ? expr_->clone() : NULL ); } void Verilog::Unary::chain(set<const Net*>& ev) const { if( expr_!=NULL ) expr_->chain(ev); } void Verilog::Unary::chain(set<const Expression*>& ev) const { ev.insert((Expression*)this); if( expr_!=NULL ) expr_->chain(ev); } void Verilog::Unary::callback(Callback& cb) const { cb.trap( this ); } //////////////////////////////////////////////////////////////////////// // Verilog::Binary //////////////////////////////////// Verilog::Binary::~Binary() { delete left_; delete right_; } unsigned int Verilog::Binary::width() const { unsigned int w; switch( op_ ) { case ArithmeticMultiply: w =left_->width()+right_->width(); break; case ArithmeticDivide: w =max( left_->width(),right_->width() ); break; case ArithmeticModulus: w =max( left_->width(),right_->width() ); break; case ArithmeticAdd: w =max( left_->width(),right_->width() )+1; break; case ArithmeticMinus: // w =max( left_->width(),right_->width() ); ?? w =max( left_->width(),right_->width() )+1; break; case ArithmeticLeftShift: w =max( left_->width(),right_->width() ); break; case ArithmeticRightShift: w =max( left_->width(),right_->width() ); break; case ArithmeticPower: w =left_->width()*right_->width(); break; case BitwiseAND: case BitwiseOR: case BitwiseNOR: case BitwiseNXOR: case BitwiseXOR: w =max( left_->width(),right_->width() ); break; case LeftShift: case RightShift: w =left_->width(); break; case LogicalEquality: case CaseEquality: case LessEqual: case GreaterEqual: case LogicalInequality: case CaseInequality: case LogicalOR: case LogicalAND: case LessThan: case GreaterThan: w =1; break; default: w =0; break; } return w; } signed Verilog::Binary::calcConstant() const { int ret; switch( op_ ) { case BitwiseXOR: ret =left_->calcConstant() ^ right_->calcConstant(); break; case ArithmeticMultiply: ret =left_->calcConstant() * right_->calcConstant(); break; case ArithmeticDivide: ret =left_->calcConstant() / right_->calcConstant(); break; case ArithmeticModulus: ret =left_->calcConstant() % right_->calcConstant(); break; case ArithmeticAdd: ret =left_->calcConstant() + right_->calcConstant(); break; case ArithmeticMinus: ret =left_->calcConstant() - right_->calcConstant(); break; case ArithmeticLeftShift: ret =left_->calcConstant() << right_->calcConstant(); break; case ArithmeticRightShift: ret =left_->calcConstant() >> right_->calcConstant(); break; case ArithmeticPower: ret =(int)pow((double)left_->calcConstant(),(double)right_->calcConstant()); break; case BitwiseAND: ret =left_->calcConstant() & right_->calcConstant(); break; case BitwiseOR: ret =left_->calcConstant() | right_->calcConstant(); break; case BitwiseNOR: ret =~(left_->calcConstant() | right_->calcConstant()); break; case BitwiseNXOR: ret =~(left_->calcConstant() ^ right_->calcConstant()); break; case LessThan: ret =left_->calcConstant() < right_->calcConstant(); break; case GreaterThan: ret =left_->calcConstant() > right_->calcConstant(); break; case LeftShift: ret =left_->calcConstant() << right_->calcConstant(); break; case RightShift: ret =left_->calcConstant() >> right_->calcConstant(); break; case LogicalEquality: ret =left_->calcConstant() == right_->calcConstant(); break; case CaseEquality: ret =left_->calcConstant() == right_->calcConstant(); break; case LessEqual: ret =left_->calcConstant() <= right_->calcConstant(); break; case GreaterEqual: ret =left_->calcConstant() >= right_->calcConstant(); break; case LogicalInequality: ret =left_->calcConstant() != right_->calcConstant(); break; case CaseInequality: ret =left_->calcConstant() != right_->calcConstant(); break; case LogicalOR: ret =left_->calcConstant() || right_->calcConstant(); break; case LogicalAND: ret =left_->calcConstant() && right_->calcConstant(); break; default: ret =0; break; } return ret; } void Verilog::Binary::toXML(std::ostream& ostr) const { ostr << '('; left_->toXML(ostr); ostr << opToken_[op_]; right_->toXML(ostr); ostr << ')'; } void Verilog::Binary::toVerilog(std::ostream& ostr) const { ostr << '('; left_->toVerilog(ostr); ostr << opToken_[op_]; right_->toVerilog(ostr); ostr << ')'; } const char* Verilog::Binary::opToken() const { return opToken_[op_]; } const char* Verilog::Binary::opName() const { return opName_[op_]; } void Verilog::Binary::link(const map<string,Net*>& net,Module* mod,const string& scope) { left_->link(net,mod,scope); right_->link(net,mod,scope); } Verilog::Expression* Verilog::Binary::clone(const string& hname) const { return new Verilog::Binary( op_, (left_!=NULL) ? left_->clone(hname) : NULL, (right_!=NULL) ? right_->clone(hname) : NULL ); } Verilog::Expression* Verilog::Binary::clone() const { return new Verilog::Binary( op_, (left_!=NULL) ? left_->clone() : NULL, (right_!=NULL) ? right_->clone() : NULL ); } void Verilog::Binary::chain(set<const Net*>& ev) const { if( left_!=NULL ) left_->chain(ev); if( right_!=NULL ) right_->chain(ev); } void Verilog::Binary::chain(set<const Expression*>& ev) const { ev.insert((Expression*)this); if( left_!=NULL ) left_->chain(ev); if( right_!=NULL ) right_->chain(ev); } void Verilog::Binary::callback(Callback& cb) const { cb.trap( this ); } //////////////////////////////////////////////////////////////////////// // Verilog::Ternary //////////////////////////////////// Verilog::Ternary::~Ternary() { delete expr_; delete true_; delete false_; } void Verilog::Ternary::toXML(std::ostream& ostr) const { expr_->toXML(ostr); ostr << " ? ("; true_->toXML(ostr); ostr << ") : ("; false_->toXML(ostr); ostr << ')'; } void Verilog::Ternary::toVerilog(std::ostream& ostr) const { ostr << '('; expr_->toVerilog(ostr); ostr << " ? "; true_->toVerilog(ostr); ostr << " : "; false_->toVerilog(ostr); ostr << ')'; } void Verilog::Ternary::link(const map<string,Net*>& net,Module* mod,const string& scope) { expr_->link(net,mod,scope); true_->link(net,mod,scope); if( false_!=NULL ) false_->link(net,mod,scope); } Verilog::Expression* Verilog::Ternary::clone(const string& hname) const { return new Verilog::Ternary( expr_->clone(hname), (true_!=NULL) ? true_->clone(hname) : NULL, (false_!=NULL) ? false_->clone(hname) : NULL ); } Verilog::Expression* Verilog::Ternary::clone() const { return new Verilog::Ternary( expr_->clone(), (true_!=NULL) ? true_->clone() : NULL, (false_!=NULL) ? false_->clone() : NULL ); } void Verilog::Ternary::chain(set<const Net*>& ev) const { if( expr_!=NULL ) expr_->chain(ev); if( true_!=NULL ) true_->chain(ev); if( false_!=NULL ) false_->chain(ev); } void Verilog::Ternary::chain(set<const Expression*>& ev) const { ev.insert((Expression*)this); if( expr_!=NULL ) expr_->chain(ev); if( true_!=NULL ) true_->chain(ev); if( false_!=NULL ) false_->chain(ev); } void Verilog::Ternary::callback(Callback& cb) const { cb.trap( this ); } //////////////////////////////////////////////////////////////////////// // Verilog::CallFunction //////////////////////////////////// Verilog::CallFunction::~CallFunction() { vector<Expression*>::iterator i; for( i=parms_.begin();i!=parms_.end();++i ) { delete (*i); } } void Verilog::CallFunction::toXML(std::ostream& ostr) const { ostr << name_ << '('; vector<Expression*>::const_iterator i; for( i=parms_.begin();i!=parms_.end();++i ) { if( i!=parms_.begin() ) ostr << ','; (*i)->toXML(ostr); } ostr << ')'; } void Verilog::CallFunction::toVerilog(std::ostream& ostr) const { printName( ostr,name_ ); ostr << '('; vector<Expression*>::const_iterator i; for( i=parms_.begin();i!=parms_.end();++i ) { if( i!=parms_.begin() ) ostr << ','; (*i)->toVerilog(ostr); } ostr << ')'; } void Verilog::CallFunction::link(const map<string,Net*>& net,Module* mod,const string& scope) { { vector<Expression*>::iterator i; for( i=parms_.begin();i!=parms_.end();++i ) (*i)->link(net,mod,scope); } { map<string,Function*>::const_iterator i =mod->function().find(name_); if( i!=mod->function().end() ) { func_ =i->second; map<string,Net*>::const_iterator ii =func_->net().find(name_); if( ii!=func_->net().end() ) net_ =ii->second; else std::cerr << "can't link port of function : " << name_ << std::endl; } else std::cerr << "can't link function : " << name_ << std::endl; } } Verilog::Expression* Verilog::CallFunction::clone(const string& hname) const { Verilog::CallFunction* ret =new Verilog::CallFunction(); ret->name_ =hname + name_; vector<Expression*>::const_iterator i; for( i=parms_.begin();i!=parms_.end();++i ) ret->parms_.push_back( (*i)->clone(hname) ); return ret; } Verilog::Expression* Verilog::CallFunction::clone() const { Verilog::CallFunction* ret =new Verilog::CallFunction(); ret->name_ =name_; vector<Expression*>::const_iterator i; for( i=parms_.begin();i!=parms_.end();++i ) ret->parms_.push_back( (*i)->clone() ); return ret; } void Verilog::CallFunction::chain(set<const Net*>& ev) const { vector<Expression*>::const_iterator i; for( i=parms_.begin();i!=parms_.end();++i ) (*i)->chain(ev); } void Verilog::CallFunction::chain(set<const Expression*>& ev) const { ev.insert((Expression*)this); vector<Expression*>::const_iterator i; for( i=parms_.begin();i!=parms_.end();++i ) (*i)->chain(ev); } void Verilog::CallFunction::callback(Callback& cb) const { cb.trap( this ); } //////////////////////////////////////////////////////////////////////// // Verilog::Net //////////////////////////////////// void Verilog::Net::toXML(std::ostream& ostr,const string& name,int indent) const { ostr << std::setw(indent) << "" << "<net name=\"" << name << "\" "; if( (msb_!=NULL)&&(lsb_!=NULL) ) { ostr << "bitrange=\""; msb_->toXML(ostr); ostr << ' '; lsb_->toXML(ostr); ostr << "\" "; } if( (sa_!=NULL)&&(ea_!=NULL) ) { ostr << "addressrange=\""; sa_->toXML(ostr); ostr << ' '; ea_->toXML(ostr); ostr << "\" "; } ostr << "type=\""; switch( type_ ) { case IMPLICIT: ostr << "implicit";break; case WIRE: ostr << "wire";break; case TRI: ostr << "tri";break; case TRI1: ostr << "tri1";break; case SUPPLY0: ostr << "supply0";break; case WAND: ostr << "wand";break; case TRIAND: ostr << "triand";break; case TRI0: ostr << "tri0";break; case SUPPLY1: ostr << "supply1";break; case WOR: ostr << "wor";break; case TRIOR: ostr << "trior";break; case REG: ostr << "reg";break; case INTEGER: ostr << "integer";break; case REAL: ostr << "real";break; // case PARAMETER: // ostr << "parameter";break; } ostr << "\" "; ostr << "interface=\""; switch( interface_ ) { case PRIVATE: ostr << "private";break; case INPUT: ostr << "input";break; case OUTPUT: ostr << "output";break; case INOUT: ostr << "inout";break; } ostr << "\" "; ostr << "/>\n"; } void Verilog::Net::toVerilog(std::ostream& ostr,const string& name, int indent,bool namedblock) const { if( interface_!=PRIVATE ) { ostr << std::setw(indent) << ""; switch( interface_ ) { case INPUT: ostr << "input";break; case OUTPUT: { if( type_==FUNCTION ) ostr << "function"; else ostr << "output"; } break; case INOUT: ostr << "inout";break; } if( (msb_!=NULL)&&(lsb_!=NULL) ) { ostr << ' ' << '['; msb_->toVerilog(ostr); ostr << ':'; lsb_->toVerilog(ostr); ostr << ']'; } ostr << ' '; printName( ostr,name ); ostr << ";\n"; } switch( type_ ) { case NAMEDBLOCK_REG: if( namedblock ) { ostr << std::setw(indent) << ""; ostr << "reg"; if( sign_ ) ostr << " signed"; if( (msb_!=NULL)&&(lsb_!=NULL) ) { ostr << ' ' << '['; msb_->toVerilog(ostr); ostr << ':'; lsb_->toVerilog(ostr); ostr << ']'; } ostr << ' '; printName( ostr,name ); if( (sa_!=NULL)&&(ea_!=NULL) ) { ostr << '['; sa_->toVerilog(ostr); ostr << ':'; ea_->toVerilog(ostr); ostr << ']'; } ostr << ";\n"; } break; case IMPLICIT: if( interface_!=PRIVATE ) break; case WIRE: case PARAMETER: case TRI: case TRI1: case SUPPLY0: case WAND: case TRIAND: case TRI0: case SUPPLY1: case WOR: case TRIOR: case REG: case INTEGER: ostr << std::setw(indent) << ""; switch( type_ ) { case IMPLICIT: ostr << "wire";break; case WIRE: ostr << "wire";break; case PARAMETER: ostr << "parameter";break; case TRI: ostr << "tri";break; case TRI1: ostr << "tri1";break; case SUPPLY0: ostr << "supply0";break; case WAND: ostr << "wand";break; case TRIAND: ostr << "triand";break; case TRI0: ostr << "tri0";break; case SUPPLY1: ostr << "supply1";break; case WOR: ostr << "wor";break; case TRIOR: ostr << "trior";break; case REG: ostr << "reg";break; case INTEGER: ostr << "integer";break; } if( sign_ ) ostr << " signed"; if( (msb_!=NULL)&&(lsb_!=NULL) ) { ostr << ' ' << '['; msb_->toVerilog(ostr); ostr << ':'; lsb_->toVerilog(ostr); ostr << ']'; } ostr << ' '; printName( ostr,name ); if( (sa_!=NULL)&&(ea_!=NULL) ) { ostr << '['; sa_->toVerilog(ostr); ostr << ':'; ea_->toVerilog(ostr); ostr << ']'; } ostr << ";\n"; break; } } void Verilog::Net::link(const map<string,Net*>& net,Module* mod,const string& scope) { if( msb_!=NULL ) msb_->link(net,mod,scope); if( lsb_!=NULL ) lsb_->link(net,mod,scope); if( sa_!=NULL ) sa_->link(net,mod,scope); if( ea_!=NULL ) ea_->link(net,mod,scope); ////////////////// if( type_==PARAMETER ) { vector<Process*>::const_iterator i; for( i=mod->process().begin();i!=mod->process().end();++i ) if( (*i)->type()==Process::PARAMETER ) if( typeid(*(*i)->statement())==typeid(Verilog::Assign) ) { Assign* param =(Verilog::Assign*)(*i)->statement(); if( typeid(*(param->leftValue()))==typeid(Verilog::Identifier) ) { Identifier* id =(Verilog::Identifier*)param->leftValue(); if( id->net()==this ) { rval_ =param->rightValue(); return; } } } } } Verilog::Net* Verilog::Net::clone(const string& hname) const { Verilog::Net* ret =new Net ( type_, ((msb_!=NULL) ? msb_->clone(hname) : NULL), ((lsb_!=NULL) ? lsb_->clone(hname) : NULL), interface_, ((sa_!=NULL) ? sa_->clone(hname) : NULL), ((ea_!=NULL) ? ea_->clone(hname) : NULL), sign_ ); return ret; } Verilog::Net* Verilog::Net::clone() const { Verilog::Net* ret =new Net ( type_, ((msb_!=NULL) ? msb_->clone() : NULL), ((lsb_!=NULL) ? lsb_->clone() : NULL), interface_, ((sa_!=NULL) ? sa_->clone() : NULL), ((ea_!=NULL) ? ea_->clone() : NULL), sign_ ); return ret; } void Verilog::Net::callback(Callback& cb) const { cb.trap( this ); } //////////////////////////////////////////////////////////////////////// // Verilog::Block //////////////////////////////////// Verilog::Block::~Block() { vector<Statement*>::iterator i; for( i=list_.begin();i!=list_.end();++i ) { delete *i; } } void Verilog::Block::toXML(std::ostream& ostr,int indent) const { ostr << std::setw(indent++) << "" << "<block>\n"; vector<Statement*>::const_iterator i; for( i=list_.begin();i!=list_.end();++i ) (*i)->toXML(ostr,indent); ostr << std::setw(--indent) << "" << "</block>\n"; } void Verilog::Block::toVerilog(std::ostream& ostr,int indent) const { ostr << std::setw(indent++) << "" << "begin"; if( name_.empty() ) ostr << '\n'; else // named block { ostr << " : " << name_ << '\n'; if( module_!=NULL ) { map<string,Net*>::const_iterator i; for( i=module_->net().begin();i!=module_->net().end();++i ) { if( i->first.find(name_)==0 ) { i->second->toVerilog(ostr, i->first.substr(i->first.rfind('.')+1), indent,true); } } } } vector<Statement*>::const_iterator i; for( i=list_.begin();i!=list_.end();++i ) (*i)->toVerilog(ostr,indent); ostr << std::setw(--indent) << "" << "end\n"; } void Verilog::Block::link(const map<string,Net*>& net,Module* mod,const string& scope) { // cout << scope << ' ' << name_ << endl; vector<Statement*>::iterator i; for( i=list_.begin();i!=list_.end();++i ) (*i)->link(net,mod,((name_.length()<scope.length()) ? scope : name_) ); } Verilog::Statement* Verilog::Block::clone(const string& hname) const { Verilog::Block* ret =new Verilog::Block(type_); ret->name_ =hname + name_; { vector<Statement*>::const_iterator i; for( i=list_.begin();i!=list_.end();++i ) ret->list_.push_back( (*i)->clone(hname) ); } return ret; } void Verilog::Block::chain(set<const Statement*>& ss) const { ss.insert((Statement*)this); vector<Statement*>::const_iterator i; for( i=list_.begin();i!=list_.end();++i ) (*i)->chain(ss); } void Verilog::Block::callback(Callback& cb) const { cb.trap( this ); } //////////////////////////////////////////////////////////////////////// // Verilog::Case::Item //////////////////////////////////// Verilog::Case::Item::~Item() { vector<Expression*>::iterator i; for( i=expr_.begin();i!=expr_.end();++i ) { delete *i; } } void Verilog::Case::Item::toXML(std::ostream& ostr,int indent) const { ostr << std::setw(indent++) << "" << "<item "; ostr << "condition=\""; vector<Expression*>::const_iterator i; for( i=expr_.begin();i!=expr_.end();++i ) { if( i!=expr_.begin() ) ostr << ','; (*i)->toXML(ostr); } ostr << "\""; ostr << ">\n"; stat_->toXML(ostr,indent); ostr << std::setw(--indent) << "" << "</item>\n"; } void Verilog::Case::Item::toVerilog(std::ostream& ostr,int indent) const { ostr << std::setw(indent) << ""; if( expr_.empty() ) { ostr << "default"; } else { vector<Expression*>::const_iterator i; for( i=expr_.begin();i!=expr_.end();++i ) { if( i!=expr_.begin() ) { ostr << ",\n"; ostr << std::setw(indent) << ""; } (*i)->toVerilog(ostr); } } ostr << " :"; if( typeid(*stat_)==typeid(Verilog::Assign) ) indent =1; else { ostr << '\n'; indent++; } stat_->toVerilog(ostr,indent); } void Verilog::Case::Item::link(const map<string,Net*>& net,Module* mod,const string& scope) { vector<Expression*>::iterator i; for( i=expr_.begin();i!=expr_.end();++i ) (*i)->link(net,mod,scope); stat_->link(net,mod,scope); } Verilog::Case::Item* Verilog::Case::Item::clone(const string& hname) const { Verilog::Case::Item* ret =new Verilog::Case::Item(); vector<Expression*>::const_iterator i; for( i=expr_.begin();i!=expr_.end();++i ) ret->expr_.push_back( (*i)->clone(hname) ); ret->stat_ =(stat_!=NULL) ? stat_->clone(hname) : NULL; return ret; } void Verilog::Case::Item::chain(set<const Statement*>& ss) const { ss.insert((Statement*)this); if( stat_!=NULL ) stat_->chain(ss); } void Verilog::Case::Item::callback(Callback& cb) const { cb.trap( this ); } //////////////////////////////////////////////////////////////////////// // Verilog::Case //////////////////////////////////// Verilog::Case::~Case() { delete expr_; vector<Item*>::iterator i; for( i=items_.begin();i!=items_.end();++i ) { delete *i; } } void Verilog::Case::toXML(std::ostream& ostr,int indent) const { ostr << std::setw(indent++) << "" << "<case type=\""; switch( type_ ) { case CASE: ostr << "case"; break; case CASEX: ostr << "casex"; break; case CASEZ: ostr << "casez"; break; } ostr << "\">\n"; vector<Item*>::const_iterator i; for( i=items_.begin();i!=items_.end();++i ) (*i)->toXML(ostr,indent); ostr << std::setw(--indent) << "" << "</case>\n"; } void Verilog::Case::toVerilog(std::ostream& ostr,int indent) const { switch( type_ ) { case CASE: ostr << std::setw(indent) << "" << "case("; break; case CASEX: ostr << std::setw(indent) << "" << "casex("; break; case CASEZ: ostr << std::setw(indent) << "" << "casez("; break; } expr_->toVerilog(ostr); ostr << ")\n"; indent++; vector<Item*>::const_iterator i; for( i=items_.begin();i!=items_.end();++i ) (*i)->toVerilog(ostr,indent); ostr << std::setw(--indent) << "" << "endcase\n"; } void Verilog::Case::link(const map<string,Net*>& net,Module* mod,const string& scope) { expr_->link(net,mod,scope); vector<Item*>::iterator i; for( i=items_.begin();i!=items_.end();++i ) (*i)->link(net,mod,scope); } Verilog::Statement* Verilog::Case::clone(const string& hname) const { Verilog::Case* ret =new Verilog::Case(); ret->type_ =type_; ret->expr_ =(expr_!=NULL) ? expr_->clone(hname) : NULL; vector<Item*>::const_iterator i; for( i=items_.begin();i!=items_.end();++i ) ret->items_.push_back( (*i)->clone(hname) ); return ret; } void Verilog::Case::chain(set<const Statement*>& ss) const { ss.insert((Statement*)this); vector<Item*>::const_iterator i; for( i=items_.begin();i!=items_.end();++i ) (*i)->chain(ss); } void Verilog::Case::callback(Callback& cb) const { cb.trap( this ); } //////////////////////////////////////////////////////////////////////// // Verilog::Condition //////////////////////////////////// Verilog::Condition::~Condition() { delete expr_; delete true_; delete false_; } void Verilog::Condition::toXML(std::ostream& ostr,int indent) const { ostr << std::setw(indent++) << "" << "<condition when=\""; expr_->toXML(ostr); ostr << "\">\n"; ostr << std::setw(indent++) << "" << "<true>\n"; true_->toXML(ostr,indent); ostr << std::setw(--indent) << "" << "</true>\n"; if( false_!=NULL ) { ostr << std::setw(indent++) << "" << "<false>\n"; false_->toXML(ostr,indent); ostr << std::setw(--indent) << "" << "</false>\n"; } ostr << std::setw(--indent) << "" << "</condition>\n"; } void Verilog::Condition::toVerilog(std::ostream& ostr,int indent) const { if( indent<0 ) indent =-indent; else ostr << std::setw(indent) << ""; ostr << "if("; expr_->toVerilog(ostr); ostr << ")\n"; true_->toVerilog(ostr,indent+1); if( false_!=NULL ) { ostr << std::setw(indent) << "" << "else"; if( typeid(*false_)==typeid(Verilog::Condition) ) { ostr << ' '; false_->toVerilog(ostr,-indent); } else { ostr << '\n'; false_->toVerilog(ostr,indent+1); } } } void Verilog::Condition::link(const map<string,Net*>& net,Module* mod,const string& scope) { expr_->link(net,mod,scope); true_->link(net,mod,scope); if( false_!=NULL ) false_->link(net,mod,scope); } Verilog::Statement* Verilog::Condition::clone(const string& hname) const { Verilog::Condition* ret =new Verilog::Condition(); ret->expr_ =(expr_!=NULL) ? expr_->clone(hname) : NULL; ret->true_ =(true_!=NULL) ? true_->clone(hname) : NULL; ret->false_ =(false_!=NULL) ? false_->clone(hname) : NULL; return ret; } void Verilog::Condition::chain(set<const Statement*>& ss) const { ss.insert((Statement*)this); true_->chain(ss); if( false_!=NULL ) false_->chain(ss); } void Verilog::Condition::callback(Callback& cb) const { cb.trap( this ); } //////////////////////////////////////////////////////////////////////// // Verilog::EventStatement //////////////////////////////////// Verilog::EventStatement::~EventStatement() { delete stat_; vector<Event*>::iterator i; for( i=event_.begin();i!=event_.end();++i ) { delete *i; } } void Verilog::EventStatement::toXML(std::ostream& ostr,int indent) const { ostr << std::setw(indent++) << "" << "<event when=\""; vector<Event*>::const_iterator i; for( i=event_.begin();i!=event_.end();++i ) { if( i!=event_.begin() ) ostr << " or "; (*i)->toXML(ostr); } ostr << "\">\n"; if( stat_!=NULL ) stat_->toXML(ostr,indent); ostr << std::setw(--indent) << "" << "</event>\n"; } void Verilog::EventStatement::toVerilog(std::ostream& ostr,int indent) const { ostr << std::setw(indent) << "" << "@("; vector<Event*>::const_iterator i; for( i=event_.begin();i!=event_.end();++i ) { if( i!=event_.begin() ) ostr << " or "; (*i)->toVerilog(ostr); } ostr << ")\n"; if( stat_!=NULL ) stat_->toVerilog(ostr,indent+1); } void Verilog::EventStatement::link(const map<string,Net*>& net,Module* mod,const string& scope) { vector<Event*>::iterator i; for( i=event_.begin();i!=event_.end();++i ) (*i)->link(net,mod,scope); stat_->link(net,mod,scope); { // Verilog-2000 enhancements if( event_.empty() ) { set<const Net*> chain; RightNetChainCB rnccb( chain ); stat_->callback( rnccb ); set<const Net*> lchain; LeftNetChainCB lnccb( lchain ); stat_->callback( lnccb ); set<const Net*>::const_iterator i; for( i=chain.begin();i!=chain.end();++i ) { if( lchain.find(*i)==lchain.end() ) { event_.push_back( new Event(Event::ANYEDGE, new Identifier(mod->findName(*i))) ); event_.back()->link(net,mod,scope); } } } } } Verilog::Statement* Verilog::EventStatement::clone(const string& hname) const { Verilog::EventStatement* ret =new Verilog::EventStatement(); vector<Event*>::const_iterator i; for( i=event_.begin();i!=event_.end();++i ) ret->event_.push_back( (Event*)(*i)->clone(hname) ); ret->stat_ =stat_->clone(hname); return ret; } void Verilog::EventStatement::chain(set<const Statement*>& ss) const { ss.insert((Statement*)this); if( stat_!=NULL ) stat_->chain(ss); } bool Verilog::EventStatement::isEdge() const { vector<Event*>::const_iterator i; for( i=event_.begin();i!=event_.end();++i ) if( ( (*i)->type()!=Event::POSEDGE )&& ( (*i)->type()!=Event::NEGEDGE ) ) return false; return true; } bool Verilog::EventStatement::isLevel() const { vector<Event*>::const_iterator i; for( i=event_.begin();i!=event_.end();++i ) if( (*i)->type()!=Event::ANYEDGE ) return false; return true; } void Verilog::EventStatement::callback(Callback& cb) const { cb.trap( this ); } //////////////////////////////////////////////////////////////////////// // Verilog::Assign //////////////////////////////////// Verilog::Assign::~Assign() { delete lval_; delete rval_; } void Verilog::Assign::toXML(std::ostream& ostr,int indent) const { ostr << std::setw(indent++) << "" << "<assign type=\""; switch( type_ ) { case BLOCKING: ostr << "blocking\">\n"; break; case NONBLOCKING: ostr << "nonblocking\">\n"; break; } set<const Net*> lc; lval_->chain(lc); ostr << std::setw(indent+1) << "" << "<left chain=\"" << lc.size() << "\">"; lval_->toXML(ostr); ostr << "</left>\n"; set<const Net*> rc; rval_->chain(rc); ostr << std::setw(indent+1) << "" << "<right chain=\"" << rc.size() << "\">"; rval_->toXML(ostr); ostr << "</right>\n"; ostr << std::setw(--indent) << "" << "</assign>\n"; } void Verilog::Assign::toVerilog(std::ostream& ostr,int indent) const { ostr << std::setw(indent) << ""; lval_->toVerilog(ostr); switch( type_ ) { case BLOCKING: ostr << " ="; break; case NONBLOCKING: ostr << " <="; if( source_->dec_tpd_ ) ostr << "`TPD "; break; } rval_->toVerilog(ostr); ostr << ";\n"; } void Verilog::Assign::link(const map<string,Net*>& net,Module* mod,const string& scope) { lval_->link(net,mod,scope); rval_->link(net,mod,scope); } Verilog::Statement* Verilog::Assign::clone(const string& hname) const { return new Verilog::Assign( type_, (lval_!=NULL) ? lval_->clone(hname) : NULL, (rval_!=NULL) ? rval_->clone(hname) : NULL ); } bool Verilog::Assign::isSimpleLeft() const { if( (typeid(*lval_)==typeid(Verilog::Identifier)) ) { Verilog::Identifier* l=(Verilog::Identifier*)lval_; if( (l->msb()==NULL)&& (l->lsb()==NULL)&& (l->idx()==NULL) ) return true; } return false; } bool Verilog::Assign::isSimpleRight() const { if( (typeid(*rval_)==typeid(Verilog::Identifier)) ) { Verilog::Identifier* r=(Verilog::Identifier*)rval_; if( (r->msb()==NULL)&& (r->lsb()==NULL)&& (r->idx()==NULL) ) return true; } return false; } bool Verilog::Assign::isSimple() const { return (isSimpleLeft()&&isSimpleRight()); } void Verilog::Assign::chain(set<const Statement*>& ss) const { ss.insert((Statement*)this); } void Verilog::Assign::callback(Callback& cb) const { cb.trap( this ); } //////////////////////////////////////////////////////////////////////// // Verilog::For //////////////////////////////////// Verilog::For::For(Identifier* i1,Expression* e1, Expression* e2, Identifier* i2,Expression* e3, Statement* s) { { ita_ =i1; begin_ =e1; cond_ =e2; reach_ =e3; stat_ =s; } //std::cerr << "can't support a complexed expression in for-loop\n"; } Verilog::For::~For() { delete ita_; delete begin_; delete cond_; delete reach_; delete stat_; } void Verilog::For::toXML(std::ostream& ostr,int indent) const { ostr << std::setw(indent++) << "" << "<for "; ostr << "iterator=\"";ita_->toXML(ostr);ostr << "\" "; ostr << "begin=\"";begin_->toXML(ostr);ostr << "\" "; ostr << "condition=\""; cond_->toXML(ostr);ostr << "\" "; ostr << "reach=\"";reach_->toXML(ostr);ostr << "\" "; ostr << ">\n"; stat_->toXML(ostr,indent); ostr << std::setw(--indent) << "" << "</for>\n"; } void Verilog::For::toVerilog(std::ostream& ostr,int indent) const { if( indent<0 ) indent =-indent; else ostr << std::setw(indent) << ""; ostr << "for("; ita_->toVerilog(ostr);ostr << "=";begin_->toVerilog(ostr);ostr << ";"; cond_->toVerilog(ostr);ostr << ";"; ita_->toVerilog(ostr);ostr << "=";reach_->toVerilog(ostr); ostr << ")\n"; stat_->toVerilog(ostr,indent+1); } void Verilog::For::link(const map<string,Net*>& net,Module* mod,const string& scope) { ita_->link(net,mod,scope); begin_->link(net,mod,scope); cond_->link(net,mod,scope); reach_->link(net,mod,scope); stat_->link(net,mod,scope); } Verilog::Statement* Verilog::For::clone(const string& hname) const { Verilog::For* ret =new Verilog::For(); ret->ita_ =(Verilog::Identifier*)ita_->clone(hname); ret->begin_ =begin_->clone(hname); ret->cond_ =cond_->clone(hname); ret->reach_ =reach_->clone(hname); ret->stat_ =stat_->clone(hname); return ret; } void Verilog::For::chain(set<const Statement*>& ss) const { ss.insert((Statement*)this); // stat_->chain(ss); // } void Verilog::For::callback(Callback& cb) const { cb.trap( this ); } //////////////////////////////////////////////////////////////////////// // Verilog::CallTask //////////////////////////////////// void Verilog::CallTask::toXML(std::ostream& ostr,int indent) const { ostr << std::setw(indent++) << "" << "<callTask "; ostr << "name=\"" << name_ << "\" "; ostr << ">\n"; ostr << std::setw(--indent) << "" << "</callTask>\n"; } void Verilog::CallTask::toVerilog(std::ostream& ostr,int indent) const { if( indent<0 ) indent =-indent; else ostr << std::setw(indent) << ""; ostr << name_ << "("; vector<Expression*>::const_iterator i; for( i=args_.begin();i!=args_.end();++i ) { if( i!=args_.begin() ) ostr << ','; (*i)->toVerilog(ostr); } ostr << ");\n"; } void Verilog::CallTask::link(const map<string,Net*>& net,Module* mod,const string& scope) { vector<Expression*>::iterator i; for( i=args_.begin();i!=args_.end();++i ) (*i)->link(net,mod,scope); } Verilog::Statement* Verilog::CallTask::clone(const string& hname) const { Verilog::CallTask* ret =new Verilog::CallTask(); ret->name_ =name_; // only system task ? vector<Expression*>::const_iterator i; for( i=args_.begin();i!=args_.end();++i ) ret->args_.push_back( (*i)->clone(hname) ); return ret; } void Verilog::CallTask::chain(set<const Statement*>& ss) const { ss.insert((Statement*)this); } void Verilog::CallTask::callback(Callback& cb) const { cb.trap( this ); } //////////////////////////////////////////////////////////////////////// // Verilog::Function //////////////////////////////////// Verilog::Function::~Function() { map<string,Net*>::iterator i; for( i=net_.begin();i!=net_.end();++i ) { delete i->second; } delete stat_; } void Verilog::Function::addNet(const char* name,Verilog::Net* net) { port_.push_back(name); pair<map<string,Net*>::iterator,bool> ret =net_.insert( pair<string,Net*>(name,net) ); if( !ret.second ) { if( ret.first->second->interface()==Net::PRIVATE ) ret.first->second->setInterface( net->interface() ); if( ret.first->second->type()==Net::IMPLICIT ) ret.first->second->setType( net->type() ); } } void Verilog::Function::toXML(std::ostream& ostr,int indent) const { } void Verilog::Function::toVerilog(std::ostream& ostr,int indent) const { vector<string>::const_iterator i; for( i=port_.begin();i!=port_.end();++i ) { net_.find(*i)->second->toVerilog(ostr,*i,indent); if( i==port_.begin() ) indent++; } stat_->toVerilog(ostr,indent--); ostr << std::setw(indent) << "" << "endfunction\n"; } void Verilog::Function::link(Module* mod) { stat_->link(net_,mod,string("")); } Verilog::Function* Verilog::Function::clone(const string& hname) const { string tmp; Verilog::Function* ret =new Verilog::Function(); map<string,Net*>::const_iterator i; for( i=net_.begin();i!=net_.end();++i ) { tmp =hname + i->first; ret->port_.push_back(tmp); ret->net_[tmp] =i->second->clone(hname); } ret->stat_ =(stat_!=NULL) ? stat_->clone(hname) : NULL; return ret; } void Verilog::Function::callback(Callback& cb) const { cb.trap( this ); } //////////////////////////////////////////////////////////////////////// //Verilog::Process //////////////////////////////////// Verilog::Process::~Process() { delete stat_; } void Verilog::Process::toXML(std::ostream& ostr,int indent) const { ostr << std::setw(indent) << "" << "<process type=\""; switch( type_ ) { case INITIAL: ostr << "initial"; break; case ALWAYS: ostr << "always"; break; case TASK: ostr << "task\" name=\""<< name_; break; case ASSIGN: ostr << "assign"; break; } ostr << "\">\n"; stat_->toXML(ostr,indent+1); ostr << std::setw(indent) << "" << "</process>\n"; } void Verilog::Process::toVerilog(std::ostream& ostr,int indent) const { ostr << std::setw(indent) << ""; switch( type_ ) { case INITIAL: ostr << "initial\n"; stat_->toVerilog(ostr,indent+1); break; case ALWAYS: ostr << "always\n"; stat_->toVerilog(ostr,indent+1); break; case TASK: ostr << "task "; printName( ostr,name_ ); ostr << ";\n"; stat_->toVerilog(ostr,indent+1); ostr << std::setw(indent) << "endtask\n"; break; case ASSIGN: ostr << "assign "; stat_->toVerilog(ostr,0); break; case PARAMETER: ostr << "parameter "; stat_->toVerilog(ostr,0); break; } } void Verilog::Process::link(Module* mod) { stat_->link(mod->net(),mod,string("")); stat_->chain(statChain_); { EventNetChainCB cb(eventChain_); stat_->callback( cb ); } { LeftNetChainCB cb(leftChain_); stat_->callback( cb ); } { RightNetChainCB cb(rightChain_); stat_->callback( cb ); } // { NetChainCB cb(nbLeftChain_, nbRightChain_, bLeftChain_, bRightChain_); stat_->callback( cb ); } } Verilog::Process* Verilog::Process::clone(const string& hname) const { Verilog::Process* ret =new Verilog::Process(); ret->type_ =type_; ret->stat_ =(stat_!=NULL) ? stat_->clone(hname) : NULL; ret->name_ =hname + name_; return ret; } bool Verilog::Process::isEdge() const { if( typeid( *stat_ )==typeid( Assign ) ) return false; else if( typeid( *stat_ )==typeid( EventStatement ) ) return ((EventStatement*)(stat_))->isEdge(); return true; } bool Verilog::Process::isLevel() const { if( typeid( *stat_ )==typeid( Assign ) ) return true; else if( typeid( *stat_ )==typeid( EventStatement ) ) return ((EventStatement*)(stat_))->isLevel(); return false; } bool Verilog::Process::isStorage() const { if( typeid( *stat_ )==typeid( Assign ) ) return false; else if( typeid( *stat_ )==typeid( EventStatement ) ) { set<const Net*>::const_iterator i; for( i=rightChain_.begin();i!=rightChain_.end();++i ) if( eventChain_.find(*i)==eventChain_.end() ) return true; } return false; } const Verilog::Statement* Verilog::Process::queryStatement(int type,const Net* src) const { if( (typeid(*stat_)==typeid(EventStatement)) ) { EventStatement* es =(EventStatement*)stat_; vector<Event*>::const_iterator iii; for( iii=es->event().begin();iii!=es->event().end();++iii ) { if( (*iii)->type()==type ) if( (typeid(*(*iii)->expression())==typeid(Identifier)) ) if( ((Identifier*)((*iii)->expression()))->net()==src ) { if( es->event().size()==1 ) { if( eventChain_.find((Net*)src)!=eventChain_.end() ) return es->statement(); } else if( es->event().size()>1 ) { Condition* c; set<const Statement*>::const_iterator i; set<const Net*>::const_iterator ii; for( i=statChain_.begin();i!=statChain_.end();++i ) if( typeid(*(*i))==typeid(Condition) ) { c =((Condition*)(*i)); set<const Net*> n; c->expression()->chain(n); ii =search( eventChain_.begin(),eventChain_.end(),n.begin(),n.end() ); if( ii!=eventChain_.end() ) { if( (*ii)==src ) return c->trueStatement(); else return c->falseStatement(); } } } } } } return NULL; } void Verilog::Process::callback(Callback& cb) const { cb.trap( this ); } //////////////////////////////////////////////////////////////////////// // Verilog::Gate //////////////////////////////////// Verilog::Gate::~Gate() { vector<Expression*>::iterator i; for( i=pin_.begin();i!=pin_.end();++i ) { delete *i; } } void Verilog::Gate::callback(Callback& cb) const { cb.trap( this ); } //////////////////////////////////////////////////////////////////////// // Verilog::Instance::Port //////////////////////////////////// Verilog::Instance::Port::~Port() { // delete con_; } void Verilog::Instance::Port::toXML(std::ostream& ostr,int indent) const { ostr << std::setw(indent) << "" << "<port "; if( ref_!="" ) ostr << "reference=\"" << ref_ << "\" "; if( con_!=NULL ) { ostr << "connect=\"";con_->toXML(ostr); ostr << "\""; } ostr << "/>\n"; } void Verilog::Instance::Port::toVerilog(std::ostream& ostr,int indent) const { ostr << std::setw(indent) << ""; if( ref_!="" ) ostr << '.' << ref_ << '('; if( con_!=NULL ) con_->toVerilog(ostr); if( ref_!="" ) ostr << ')'; } void Verilog::Instance::Port::link(const map<string,Net*>& net,Module* mod,const string& scope,Module* rmod,int idx) { if( con_!=NULL ) con_->link(net,mod,string("")); if( rmod!=NULL ) { if( ref_.empty() ) { if( idx<rmod->port().size() ) ref_ =rmod->port()[idx]; } map<string,Net*>::const_iterator i =rmod->net().find(ref_); if( i!=rmod->net().end() ) net_ =i->second; else std::cerr << "can't link port of instance : " << ref_ << std::endl; } } void Verilog::Instance::Port::ungroup(Verilog::Module* mod, const string& cname,const string& sname) { if( ref_!="" && con_!=NULL ) { string tmp =sname + ref_; if( net_->interface()==Verilog::Net::INPUT ) { mod->addAssign(new Verilog::Identifier(tmp.c_str()),con_->clone(cname)); } else if( net_->interface()==Verilog::Net::OUTPUT ) { mod->addAssign(con_->clone(cname),new Verilog::Identifier(tmp.c_str())); } else { std::cerr << "can't connect type : " << "INOUT" << std::endl; } } } Verilog::Instance::Port* Verilog::Instance::Port::clone(const string& hname) const { return new Verilog::Instance::Port(ref_.c_str(),con_->clone(hname)); } void Verilog::Instance::Port::callback(Callback& cb) const { cb.trap( this ); } //////////////////////////////////////////////////////////////////////// // Verilog::Instance //////////////////////////////////// Verilog::Instance::~Instance() { vector<Port*>::iterator i; for( i=port_.begin();i!=port_.end();++i ) { delete *i; } } void Verilog::Instance::addPort(Port* p) { port_.push_back(p); } void Verilog::Instance::toXML(std::ostream& ostr,const string& name,int indent) const { ostr << std::setw(indent++) << "" << "<instance name=\"" << name << "\" type=\"" << type_ << "\">\n"; vector<Port*>::const_iterator i; for( i=port_.begin();i!=port_.end();++i ) (*i)->toXML(ostr,indent); ostr << std::setw(--indent) << "" << "</instance>\n"; } void Verilog::Instance::toVerilog(std::ostream& ostr,const string& name,int indent) const { ostr << std::setw(indent++) << "" << type_ << ' '; if( params_.size()!=0 ) { ostr << "#("; multimap<string,Expression*>::const_iterator i; for( i=params_.begin();i!=params_.end();++i ) { if( i!=params_.begin() ) ostr << ','; if( (i->first).length()!=0 ) ostr << '.' << i->first << '('; i->second->toVerilog(ostr); if( (i->first).length()!=0 ) ostr << ')'; } ostr << ") "; } printName( ostr,name ); ostr << '\n'; ostr << std::setw(indent++) << "" << "(\n"; vector<Port*>::const_iterator i; for( i=port_.begin();i!=port_.end();++i ) { if( i!=port_.begin() ) ostr << ',' << std::endl; (*i)->toVerilog(ostr,indent); } ostr << std::endl; ostr << std::setw(--indent) << "" << ");\n"; } void Verilog::Instance::link(Verilog* veri,const map<string,Net*>& net, const string& scope,Module* mod) { { map<string,Module*>::const_iterator i =veri->module().find(type_); if( i!=veri->module().end() ) module_ =i->second; else std::cerr << "can't link module : " << type_ << std::endl; } { int idx=0; vector<Port*>::iterator i; for( i=port_.begin();i!=port_.end();++i ) (*i)->link(net,mod,scope,module_,idx++); } } Verilog::Instance* Verilog::Instance::clone(const string& hname) const { Verilog::Instance* ret =new Verilog::Instance(); ret->type_ =type_; vector<Port*>::const_iterator i; for( i=port_.begin();i!=port_.end();++i ) ret->addPort( (*i)->clone(hname) ); return ret; } void Verilog::Instance::ungroup(Verilog::Module* mod,const string& cname,const string& sname) { module_->ungroup(mod,sname,params_); vector<Port*>::iterator i; for( i=port_.begin();i!=port_.end();++i ) (*i)->ungroup(mod,cname,sname); } void Verilog::Instance::callback(Callback& cb) const { cb.trap( this ); } //////////////////////////////////////////////////////////////////////// // Verilog::Module //////////////////////////////////// Verilog::Module::~Module() { { map<string,Net*>::iterator i; for( i=net_.begin();i!=net_.end();++i ) { delete i->second; } } { vector<Process*>::iterator i; for( i=process_.begin();i!=process_.end();++i ) { delete *i; } } { map<string,Function*>::iterator i; for( i=function_.begin();i!=function_.end();++i ) { delete i->second; } } { map<string,Instance*>::iterator i; for( i=instance_.begin();i!=instance_.end();++i ) { delete i->second; } } } void Verilog::Module::addPort(const char* name) { port_.push_back(name); } void Verilog::Module::addNet(const char* name,Verilog::Net* net) { pair<map<string,Net*>::iterator,bool> ret =net_.insert( pair<string,Net*>(name,net)); } Verilog::Net* Verilog::Module::newNet(const char* name, int type, Expression* msb,Expression* lsb, int inter, Expression* sa,Expression* ea, bool sign) { Verilog::Net* ret =NULL; map<string,Net*>::iterator i =net_.find(name); if( i==net_.end() ) { ret =new Verilog::Net(type,msb,lsb,inter,sa,ea,sign); net_.insert( pair<string,Net*>(name,ret)); } else { ret =i->second; if( ret->interface()==Net::PRIVATE ) ret->setInterface( inter ); if( ret->type()==Net::IMPLICIT ) ret->setType( type ); } return ret; } void Verilog::Module::addAssign(Expression* l,Expression* r) { moe::Verilog::Statement* stat =new moe::Verilog::Assign(moe::Verilog::Assign::BLOCKING,l,r); moe::Verilog::Process* proc =new moe::Verilog::Process(moe::Verilog::Process::ASSIGN,stat); process_.push_back(proc); } void Verilog::Module::addParameter(Expression* l,Expression* r) { moe::Verilog::Statement* stat =new moe::Verilog::Assign(moe::Verilog::Assign::BLOCKING,l,r); moe::Verilog::Process* proc =new moe::Verilog::Process(moe::Verilog::Process::PARAMETER,stat); process_.push_back(proc); } Verilog::Instance* Verilog::Module::newInstance(const char* name) { moe::Verilog::Instance* inst =new moe::Verilog::Instance; pair<map<string,Instance*>::iterator,bool> ret =instance_.insert( pair<string,Instance*>(name,inst)); if( !ret.second ) { std::cerr << "instance name repetition error : " << name << "\n"; delete inst; } return ret.first->second; } void Verilog::Module::addProcess(Process* proc) { process_.push_back(proc); } Verilog::Function* Verilog::Module::newFunction(const char* name) { Verilog::Function* func =new Function; pair<map<string,Function*>::iterator,bool> ret =function_.insert( pair<string,Function*>(name,func) ); if( !ret.second ) { std::cerr << "function name repetition error : " << name << "\n"; delete func; } return ret.first->second; } void Verilog::Module::addFunction(const char* name,Verilog::Function* func) { pair<map<string,Function*>::iterator,bool> ret =function_.insert( pair<string,Function*>(name,func) ); if( !ret.second ) { std::cerr << "function name repetition error : " << name << "\n"; delete func; } } void Verilog::Module::addInstance(const char* name,moe::Verilog::Instance* inst) { pair<map<string,Instance*>::iterator,bool> ret =instance_.insert( pair<string,Instance*>(name,inst)); if( !ret.second ) { std::cerr << "instance name repetition error : " << name << "\n"; delete inst; } } void Verilog::Module::toXML( std::ostream& ostr,const string& name,int indent ) const { ostr << std::setw(indent++) << "" << "<module name=\"" << name << "\">\n"; { ostr << std::setw(indent++) << "" << "<port_order>\n"; vector<string>::const_iterator i; for( i=port_.begin();i!=port_.end();++i ) ostr << std::setw(indent) << "" << *i << std::endl; ostr << std::setw(--indent) << "" << "</port_order>\n"; } { map<string,Net*>::const_iterator i; for( i=net_.begin();i!=net_.end();++i ) i->second->toXML(ostr,i->first,indent); } { map<string,Function*>::const_iterator i; for( i=function_.begin();i!=function_.end();++i ) i->second->toXML(ostr,indent); } { map<string,Instance*>::const_iterator i; for( i=instance_.begin();i!=instance_.end();++i ) i->second->toXML(ostr,i->first,indent); } { vector<Process*>::const_iterator i; for( i=process_.begin();i!=process_.end();++i ) (*i)->toXML(ostr,indent); } ostr << std::setw(--indent) << "" << "</module>\n"; } void Verilog::Module::toVerilog( std::ostream& ostr,const string& name,int indent ) const { ostr << std::setw(indent++) << "" << "module "; printName( ostr,name ); ostr << std::endl; ostr << std::setw(indent++) << "" << "(\n"; vector<string>::const_iterator i; for( i=port_.begin();i!=port_.end();++i ) { if( i!=port_.begin() ) ostr << ",\n"; ostr << std::setw(indent) << "" << *i; } ostr << std::endl; ostr << std::setw(--indent) << "" << ");\n"; // parameter { vector<Process*>::const_iterator i; for( i=process_.begin();i!=process_.end();++i ) if( (*i)->type()==Process::PARAMETER ) (*i)->toVerilog(ostr,indent); } // net::public { vector<string>::const_iterator i; map<string,Net*>::const_iterator ii; for( i=port_.begin();i!=port_.end();++i ) { ii =net_.find(*i); if( ii!=net_.end() ) ii->second->toVerilog(ostr,ii->first,indent); } } // net::private { map<string,Net*>::const_iterator i; for( i=net_.begin();i!=net_.end();++i ) { if( i->second->interface()==Net::PRIVATE ) if( i->second->type()!=Net::PARAMETER ) i->second->toVerilog(ostr,i->first,indent); } } // function { map<string,Function*>::const_iterator i; for( i=function_.begin();i!=function_.end();++i ) i->second->toVerilog(ostr,indent); } // instance { map<string,Instance*>::const_iterator i; for( i=instance_.begin();i!=instance_.end();++i ) i->second->toVerilog(ostr,i->first,indent); } // process { vector<Process*>::const_iterator i; for( i=process_.begin();i!=process_.end();++i ) if( (*i)->type()!=Process::PARAMETER ) (*i)->toVerilog(ostr,indent); } // defparam { multimap<string,Expression*>::const_iterator i; for( i=defparams_.begin();i!=defparams_.end();++i ) { ostr << std::setw(indent) << "" << "defparam "; ostr << i->first << " ="; i->second->toVerilog(ostr); ostr << ";\n"; } } ostr << std::setw(--indent) << "" << "endmodule\n"; } void Verilog::Module::link(Verilog* veri) { if( source_->debug() ) std::cerr << "link...\n"; name_ =std::string(veri->findName(this)); { map<string,Function*>::iterator i; for( i=function_.begin();i!=function_.end();++i ) { if( source_->debug() ) std::cerr << " function : " << i->first << std::endl; i->second->link(this); } } { map<string,Instance*>::iterator i; for( i=instance_.begin();i!=instance_.end();++i ) { if( source_->debug() ) std::cerr << " instance : " << i->first << std::endl; i->second->link(veri,net_,string(""),this); } } { vector<Process*>::iterator i; for( i=process_.begin();i!=process_.end();++i ) { if( source_->debug() ) { std::cerr << " process : " ; (*i)->toVerilog(std::cerr,0); } (*i)->link(this); } } // { map<string,Net*>::iterator i; for( i=net_.begin();i!=net_.end();++i ) { if( source_->debug() ) std::cerr << " net : " << i->first << std::endl; i->second->link(net_,this,string("")); } } } void Verilog::Module::ungroup(Verilog::Module* mod,const string& name,const multimap<string,Expression*>& params) { if( source_->debug() ) std::cerr << "ungroup..."<< name << std::endl; string hname; { Verilog::Net* net; map<string,Net*>::iterator i; for( i=net_.begin();i!=net_.end();++i ) { hname =name + i->first; net =i->second->clone(name); // if( i->second->type()==Net::PARAMETER ) // net->setInterface(Verilog::Net::INPUT); // else net->setInterface(Verilog::Net::PRIVATE); net->setType( i->second->type() ); mod->addNet(hname.c_str(),net); } } { Verilog::Function* func; map<string,Function*>::iterator i; for( i=function_.begin();i!=function_.end();++i ) { hname =name + i->first; mod->addFunction(hname.c_str(),i->second->clone(name)); } } { map<string,Expression*>::const_iterator i; for( i=defparams_.begin();i!=defparams_.end();++i ) { mod->addDefparam(name+i->first,i->second->clone(name)); } } { map<string,Instance*>::iterator i; for( i=instance_.begin();i!=instance_.end();++i ) { if( i->second->module()!=NULL ) { hname =name + i->first + '.'; i->second->ungroup(mod,name,hname); } else { hname =name + i->first; mod->addInstance( hname.c_str(),i->second->clone(name) ); } } } { multimap<string,Expression*>::const_iterator p; p=params.begin(); // vector<Process*>::iterator i; for( i=process_.begin();i!=process_.end();++i ) { Process* proc =(*i)->clone(name.c_str()); if( (*i)->type()==Process::PARAMETER ) { if( params.size()!=0 ) { if( (params.begin()->first).length()==0 ) // parameter_list { for( ;p!=params.end();++p ) { if( typeid(*(*i)->statement())==typeid(Verilog::Assign) ) { Assign* param =(Verilog::Assign*)proc->statement(); param->setRightValue(p->second); ++p; break; } } } else // parameter_byname_list { if( typeid(*(*i)->statement())==typeid(Verilog::Assign) ) { Assign* param =(Verilog::Assign*)(*i)->statement(); if( typeid(*(param->leftValue()))==typeid(Verilog::Identifier) ) { Identifier* id =(Verilog::Identifier*)param->leftValue(); multimap<string,Expression*>::const_iterator p; p =params.find(id->name()); if( p!=params.end() ) { Assign* clonedparam =(Verilog::Assign*)proc->statement(); clonedparam->setRightValue(p->second); } } } } } } mod->addProcess(proc); } } } void Verilog::Module::ungroup() { { string hname; map<string,Instance*>::iterator i; for( i=instance_.begin();i!=instance_.end();++i ) { if( i->second->module()!=NULL ) { hname ='\\' + i->first + '.'; i->second->ungroup(this,string(""),hname); delete i->second; instance_.erase(i->first); } } } { map<string,Expression*>::const_iterator i; for( i=defparams_.begin();i!=defparams_.end();++i ) { if( i->first.c_str()[0]!='\\' ) if( i->first.find(".")!=string::npos ) { string hname ='\\' + i->first; Expression* e=i->second->clone(); defparams_.erase(i->first); addDefparam(hname,e); } } } } void Verilog::Module::link() { { map<string,Function*>::iterator i; for( i=function_.begin();i!=function_.end();++i ) i->second->link(this); } { vector<Process*>::iterator i; for( i=process_.begin();i!=process_.end();++i ) (*i)->link(this); } { vector<Process*>::const_iterator i; for( i=process_.begin();i!=process_.end();++i ) if( (*i)->type()==Process::PARAMETER ) if( typeid(*(*i)->statement())==typeid(Verilog::Assign) ) { Assign* param =(Verilog::Assign*)(*i)->statement(); if( typeid(*(param->leftValue()))==typeid(Verilog::Identifier) ) { Identifier* id =(Verilog::Identifier*)param->leftValue(); { map<string,Expression*>::const_iterator defp; defp =defparams_.find(id->name()); if( defp!=defparams_.end() ) { param->setRightValue(defp->second); } } } } } { map<string,Net*>::iterator i; for( i=net_.begin();i!=net_.end();++i ) i->second->link(net_,this,string("")); } } void Verilog::Module::callback(Callback& cb) const { cb.trap( this ); } //////////////////////////////////////////////////////////////////////// // Verilog //////////////////////////////////// Verilog::~Verilog() { map<string,Module*>::iterator i; for( i=module_.begin();i!=module_.end();++i ) { delete i->second; } } int Verilog::parse(const char* filename) { source_ =this; verilog_input =::fopen( filename,"r" ); verilog_file =filename; int ret =verilog_parse(); ::fclose( verilog_input ); return ret; } int Verilog::parse(FILE* fp) { source_ =this; verilog_input =fp; return ::verilog_parse(); } Verilog::Module* Verilog::addModule(const char* name) { Verilog::Module* mod =new Verilog::Module; pair<map<string,Module*>::iterator,bool> ret =module_.insert( pair<string,Module*>(name,mod) ); if( !ret.second ) { std::cerr << "module name repetition error : " << name << "\n"; delete mod; } return ret.first->second; } void Verilog::toXML(std::ostream& ostr,int indent) const { ostr << std::setw(indent++) << "" << "<verilog>\n"; { map<string,Module*>::const_iterator i; for( i=module_.begin();i!=module_.end();++i ) i->second->toXML( ostr,i->first,indent ); } ostr << std::setw(--indent) << "" << "</verilog>\n"; } void Verilog::toVerilog(std::ostream& ostr,int indent) const { map<string,Module*>::const_iterator i; for( i=module_.begin();i!=module_.end();++i ) i->second->toVerilog( ostr,i->first,indent ); } void Verilog::link() { map<string,Module*>::iterator i; for( i=module_.begin();i!=module_.end();++i ) { std::cerr << "link..." << i->first << std::endl; i->second->link( this ); } } void Verilog::ungroup(Verilog::Module* top) { string hname; map<string,Instance*>::const_iterator i; for( i=top->instance().begin();i!=top->instance().end();++i ) { if( i->second->module()!=NULL ) { hname ='\\' + i->first + '.'; i->second->ungroup(top,string(""),hname); } delete i->second; } top->instance().clear(); } void Verilog::callback(Callback& cb) const { cb.trap( this ); } //////////////////////////////////////////////////////////////////////// // Verilog::LeftNetChainCB //////////////////////////////////// void Verilog::LeftNetChainCB::trap(const Process* self) { self->statement()->callback( *this ); } ////////////////// void Verilog::LeftNetChainCB::trap(const Block* self) { vector<Statement*>::const_iterator i; for( i=self->list().begin();i!=self->list().end();++i ) (*i)->callback( *this ); } void Verilog::LeftNetChainCB::trap(const Case* self) { vector<Case::Item*>::const_iterator i; for( i=self->items().begin();i!=self->items().end();++i ) (*i)->callback( *this ); } void Verilog::LeftNetChainCB::trap(const Case::Item* self) { self->statement()->callback( *this ); } void Verilog::LeftNetChainCB::trap(const Condition* self) { self->trueStatement()->callback( *this ); if( self->falseStatement()!=NULL ) self->falseStatement()->callback( *this ); } void Verilog::LeftNetChainCB::trap(const EventStatement* self) { self->statement()->callback( *this ); } void Verilog::LeftNetChainCB::trap(const Assign* self) { self->leftValue()->callback( *this ); } ////////////////// void Verilog::LeftNetChainCB::trap(const Identifier* self) { if( self->net()!=NULL ) self->net()->callback( *this ); } void Verilog::LeftNetChainCB::trap(const Concat* self) { vector<Expression*>::const_iterator i; for( i=self->list().begin();i!=self->list().end();++i ) (*i)->callback( *this ); } ////////////////// void Verilog::LeftNetChainCB::trap(const Net* self) { chain_.insert( self ); } //////////////////////////////////////////////////////////////////////// // Verilog::RightNetChainCB //////////////////////////////////// void Verilog::RightNetChainCB::trap(const Process* self) { self->statement()->callback( *this ); } ////////////////// void Verilog::RightNetChainCB::trap(const Block* self) { vector<Statement*>::const_iterator i; for( i=self->list().begin();i!=self->list().end();++i ) (*i)->callback( *this ); } void Verilog::RightNetChainCB::trap(const Case* self) { self->expression()->callback( *this ); vector<Case::Item*>::const_iterator i; for( i=self->items().begin();i!=self->items().end();++i ) (*i)->callback( *this ); } void Verilog::RightNetChainCB::trap(const Case::Item* self) { vector<Expression*>::const_iterator i; for( i=self->expression().begin();i!=self->expression().end();++i ) (*i)->callback( *this ); self->statement()->callback( *this ); } void Verilog::RightNetChainCB::trap(const Condition* self) { self->expression()->callback( *this ); self->trueStatement()->callback( *this ); if( self->falseStatement()!=NULL ) self->falseStatement()->callback( *this ); } void Verilog::RightNetChainCB::trap(const EventStatement* self) { self->statement()->callback( *this ); } void Verilog::RightNetChainCB::trap(const Assign* self) { left_=true; self->leftValue()->callback( *this ); left_=false; self->rightValue()->callback( *this ); } ////////////////// void Verilog::RightNetChainCB::trap(const Identifier* self) { if( left_ ) { if( self->msb()!=NULL ) self->msb()->callback( *this ); if( self->lsb()!=NULL ) self->lsb()->callback( *this ); if( self->idx()!=NULL ) self->idx()->callback( *this ); } else { if( self->net()!=NULL ) self->net()->callback( *this ); { if( self->msb()!=NULL ) self->msb()->callback( *this ); if( self->lsb()!=NULL ) self->lsb()->callback( *this ); if( self->idx()!=NULL ) self->idx()->callback( *this ); } } } void Verilog::RightNetChainCB::trap(const Concat* self) { vector<Expression*>::const_iterator i; for( i=self->list().begin();i!=self->list().end();++i ) (*i)->callback( *this ); } void Verilog::RightNetChainCB::trap(const Binary* self) { self->left()->callback( *this ); self->right()->callback( *this ); } void Verilog::RightNetChainCB::trap(const CallFunction* self) { vector<Expression*>::const_iterator i; for( i=self->parameter().begin();i!=self->parameter().end();++i ) (*i)->callback( *this ); } void Verilog::RightNetChainCB::trap(const Ternary* self) { self->condition()->callback( *this ); self->trueValue()->callback( *this ); self->falseValue()->callback( *this ); } void Verilog::RightNetChainCB::trap(const Unary* self) { self->value()->callback( *this ); } ////////////////// void Verilog::RightNetChainCB::trap(const Net* self) { chain_.insert( self ); } //////////////////////////////////////////////////////////////////////// void Verilog::EventNetChainCB::trap(const Process* self) { self->statement()->callback( *this ); } void Verilog::EventNetChainCB::trap(const EventStatement* self) { vector<Event*>::const_iterator i; for( i=self->event().begin();i!=self->event().end();++i ) (*i)->callback( *this ); } void Verilog::EventNetChainCB::trap(const Event* self) { self->expression()->callback( *this ); } void Verilog::EventNetChainCB::trap(const Identifier* self) { self->net()->callback( *this ); } void Verilog::EventNetChainCB::trap(const Net* self) { chain_.insert( self ); } //////////////////////////////////////////////////////////////////////// // Verilog::NetChainCB //////////////////////////////////// void Verilog::NetChainCB::trap(const Process* self) { self->statement()->callback( *this ); } ////////////////// void Verilog::NetChainCB::trap(const Block* self) { vector<Statement*>::const_iterator i; for( i=self->list().begin();i!=self->list().end();++i ) (*i)->callback( *this ); } void Verilog::NetChainCB::trap(const Case* self) { left_ =false; self->expression()->callback( *this ); vector<Case::Item*>::const_iterator i; for( i=self->items().begin();i!=self->items().end();++i ) (*i)->callback( *this ); } void Verilog::NetChainCB::trap(const Case::Item* self) { left_ =false; vector<Expression*>::const_iterator i; for( i=self->expression().begin();i!=self->expression().end();++i ) (*i)->callback( *this ); self->statement()->callback( *this ); } void Verilog::NetChainCB::trap(const Condition* self) { left_ =false; self->expression()->callback( *this ); self->trueStatement()->callback( *this ); if( self->falseStatement()!=NULL ) self->falseStatement()->callback( *this ); } void Verilog::NetChainCB::trap(const EventStatement* self) { self->statement()->callback( *this ); } void Verilog::NetChainCB::trap(const Assign* self) { if( self->type()==Verilog::Assign::BLOCKING ) blocking_ =true; else blocking_ =false; // left_=true; self->leftValue()->callback( *this ); left_=false; self->rightValue()->callback( *this ); } ////////////////// void Verilog::NetChainCB::trap(const Identifier* self) { if( left_ ) { left_ =false; if( self->msb()!=NULL ) self->msb()->callback( *this ); if( self->lsb()!=NULL ) self->lsb()->callback( *this ); if( self->idx()!=NULL ) self->idx()->callback( *this ); left_ =true; if( self->net()!=NULL ) self->net()->callback( *this ); } else { if( self->net()!=NULL ) self->net()->callback( *this ); { if( self->msb()!=NULL ) self->msb()->callback( *this ); if( self->lsb()!=NULL ) self->lsb()->callback( *this ); if( self->idx()!=NULL ) self->idx()->callback( *this ); } } } void Verilog::NetChainCB::trap(const Concat* self) { vector<Expression*>::const_iterator i; for( i=self->list().begin();i!=self->list().end();++i ) (*i)->callback( *this ); } void Verilog::NetChainCB::trap(const Binary* self) { self->left()->callback( *this ); self->right()->callback( *this ); } void Verilog::NetChainCB::trap(const CallFunction* self) { vector<Expression*>::const_iterator i; for( i=self->parameter().begin();i!=self->parameter().end();++i ) (*i)->callback( *this ); } void Verilog::NetChainCB::trap(const Ternary* self) { self->condition()->callback( *this ); self->trueValue()->callback( *this ); self->falseValue()->callback( *this ); } void Verilog::NetChainCB::trap(const Unary* self) { self->value()->callback( *this ); } ////////////////// void Verilog::NetChainCB::trap(const Net* self) { if( blocking_ ) if( left_ ) bLeftChain_.insert( self ); else bRightChain_.insert( self ); else if( left_ ) nbLeftChain_.insert( self ); else nbRightChain_.insert( self ); } //////////////////////////////////////////////////////////////////////// }
[ "cs15mtech11002@iith.ac.in" ]
cs15mtech11002@iith.ac.in
81c2df7b5fe26e0fd0b5e37dc9b5e49735ee4b55
7bd86eea32ca45d0af07ff71d66a5842cb64b1f9
/InterfaceEDT/annee.h
75287832e606b206f2e25afbe89ece4df03d47c1
[]
no_license
DanielLeThug/CalendrierCpp
ba718309deeebf4cf282cde12a37078fc7b03b65
4ba807255d9737f24eb301ead3c004ce7072c096
refs/heads/master
2021-01-11T10:24:51.187672
2017-01-11T14:15:31
2017-01-11T14:15:31
76,236,850
0
0
null
null
null
null
UTF-8
C++
false
false
480
h
#ifndef ANNEE_H #define ANNEE_H #include "Semaine.h" #include <vector> using std::vector; class Annee { public: Annee(const vector<Semaine*>& semainesAnnee); vector<Semaine*> getSemainesAnnee() const; void setSemainesAnnee(const vector<Semaine*>& semainesAnnee); void addSemaine(Semaine* semaine, int numero); private: vector<Semaine*> d_semainesAnnee; }; bool operator==(const Annee& annee, const Annee& autreAnnee); #endif
[ "goldennoob68@gmail.com" ]
goldennoob68@gmail.com
267792d795a3de522661970c799a15c2b7cc0931
d7fa103fb1cf3f9329086e993a1d12b71f2b0794
/TP1/Sources/widget.h
fcda5b8e078faa335364991406a0bd06671c64ef
[]
no_license
danielRL24/DesignPatterns_TPs_15-16
6feac0359d8953bf11f18250d11907fbef419ef4
84646f814c5b115b3d5984fa0dff9d6213e0a186
refs/heads/master
2021-01-01T03:48:52.465675
2016-05-27T08:35:19
2016-05-27T08:35:19
57,148,998
0
0
null
null
null
null
UTF-8
C++
false
false
1,040
h
#ifndef WIDGET_H #define WIDGET_H #include "fractal.h" #include <QtWidgets> #include <QDialog> class Widget : public QGraphicsView { Q_OBJECT public: Widget(int _deepness, QWidget *parent = 0); ~Widget(); QAction *getSwitchToEditionOrDisplay() const; protected: void mousePressEvent(QMouseEvent *); void mouseMoveEvent(QMouseEvent *); void mouseReleaseEvent(QMouseEvent *); void wheelEvent(QWheelEvent *); private: //Zoom double scaleFactor; double zoomStep; void restoreOriginalZoom(); //Explore/Edition mode bool editionMode; QGraphicsLineItem *tempLineEdition; QPointF startLogic; QPointF endLogic; //Général QGraphicsScene *scene; QPen *pen; Fractal *fractal; int deepness; QList<QLineF> editionLines; public slots: void changeMode(); void redraw(int newDeepness); signals: void scaleFactorChanged(double zoom); void zoomLimitReached(bool isMaxZoom); void switchMode(bool toEditionMode); }; #endif // WIDGET_H
[ "daniel.24.rodrigues@gmail.com" ]
daniel.24.rodrigues@gmail.com
09cfd0d638c7342c5f0d3696dca389e688d66474
bb7374de2b32fa0574f4f7355259af94fd1666c0
/gdroga.h
8b76a8f733bce840f2fed227318ef37a29dff657
[]
no_license
bkr4/city
4f2e7ff0a5ebf2cf6fce5f3e7f357846bfb7a5cf
ad9c61f0648507a03c3efff77de1d56c2347814f
refs/heads/main
2023-06-15T20:35:54.850535
2021-07-12T10:10:02
2021-07-12T10:10:02
385,201,604
0
0
null
null
null
null
UTF-8
C++
false
false
360
h
#ifndef GDROGA_H #define GDROGA_H //#include "droga.h" #include <QGraphicsItem> class Gdroga : public QGraphicsItem { public: Gdroga(QLineF linia); void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget = Q_NULLPTR) override; private: QLineF droga; QRectF boundingRect() const override; }; #endif // GDROGA_H
[ "87307553+bkr4@users.noreply.github.com" ]
87307553+bkr4@users.noreply.github.com
cea07d8660e52e3ea1b7bf91bd356367b411d98f
1cc07d0215e8b0de8cc7396cbb32ddfef8acf98d
/94. Binary Tree Inorder Traversal(M)/tt.cpp
cc812bcdbb4cd5ac80ec8d79ce852462442114c9
[]
no_license
SamongZ/LeetCode
fb2af94814b406d7977e17f7bead918152ffae5c
ac6d0835c453439843de8336bb19471c2fb56ece
refs/heads/master
2021-01-20T12:28:07.814290
2017-08-15T15:02:50
2017-08-15T15:02:50
90,366,913
0
0
null
null
null
null
UTF-8
C++
false
false
1,463
cpp
/* Given a binary tree, return the inorder traversal of its nodes' values. For example: Given binary tree [1,null,2,3], 1 \ 2 / 3 return [1,3,2]. Note: Recursive solution is trivial, could you do it iteratively? */ /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ // Recursive solution class Solution1 { public: vector<int> inorderTraversal(TreeNode* root) { vector<int> result; result = inorder(result, root); return result; } vector<int> inorder(vector<int> &vec, TreeNode *root) { if (root != nullptr) { inorder(vec, root -> left); vec.push_back(root -> val); inorder(vec, root -> right); } return vec; } }; // iterative class Solution2 { public: vector<int> inorderTraversal(TreeNode* root) { stack<TreeNode*> temp; vector<int> result; TreeNode *pNode = root; while (!temp.empty() || pNode != nullptr) { if (pNode != nullptr) { temp.push(pNode); pNode = pNode -> left; } else { TreeNode *p = temp.top(); result.push_back(p -> val); pNode = p -> right; temp.pop(); } } return result; } };
[ "zhang_zh1010@163.com" ]
zhang_zh1010@163.com
cb90c0742ec72bc631cc04a13e2e81cce789a245
784883785e9bfdb7eb8031b1311321f2901e13bd
/C++ Codes/vector-erase.cpp
e14766ba05d279b03285d598cf5f2f78c51bc395
[]
no_license
jaimittal1998/Competitive-Programming
3a6cea7ce56ab3fae0dedd00212df84ec7212b9d
d2387e6de4c3e029ec7b87b6b98fb6607400a150
refs/heads/master
2022-11-10T03:44:49.209525
2020-06-22T12:40:36
2020-06-22T12:40:36
118,754,177
2
2
null
2018-10-06T17:27:40
2018-01-24T11:08:38
C++
UTF-8
C++
false
false
450
cpp
#include<bits/stdc++.h> using namespace std; int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); int N; int x,a,b; cin>>N; vector<int> V; for(int i=0;i<N;i++) { int temp; cin>>temp; V.push_back(temp); } cin>>x; V.erase(V.begin()+x-1); cin>>a>>b; V.erase(V.begin()+a-1,V.begin()+b-1); cout<<V.size()<<endl; vector<int>::iterator itr; for(itr=V.begin();itr!=V.end();itr++) cout<<*itr<<" "; }
[ "30296016+jaimittal1998@users.noreply.github.com" ]
30296016+jaimittal1998@users.noreply.github.com
57d761a48462f4762294b2ebd94123b95dff6b76
79ac6b70443f0cf6259a3e1d94cf64de26aa9aec
/ClientServerHybrid/ClientServerHybrid/Interface/IHybrid.cpp
a08bdd340cfe4385222419e601e4498f66d87e74
[]
no_license
kirillovmr/client_server_app
def126927f7432401b6344f1dac3df9aa4985401
fac48da60be15c86f67ea9e4af11dd2f1c1d63e1
refs/heads/master
2020-08-29T22:27:11.047767
2019-12-22T13:41:36
2019-12-22T13:41:36
218,189,859
0
0
null
null
null
null
UTF-8
C++
false
false
3,123
cpp
// // IHybrid.cpp // ClientServerHybrid // // Created by Viktor Kirillov on 11/4/19. // Copyright © 2019 Viktor Kirillov. All rights reserved. // #include "IHybrid.hpp" using namespace std; using namespace boost; IHybrid::IHybrid(unsigned char num_of_threads): sessionCounter(0) { m_work.reset(new boost::asio::io_service::work(m_ios)); for (unsigned char i = 0; i < num_of_threads; i++) { std::unique_ptr<std::thread> th( new std::thread([this](){ m_ios.run(); })); m_thread_pool.push_back(std::move(th)); } } void IHybrid::onRequestComplete(std::shared_ptr<Session> session) { boost::system::error_code ignored_ec, ec; session->getSocket().shutdown(asio::ip::tcp::socket::shutdown_both, ignored_ec); // Remove session form the map of active sessions. std::unique_lock<std::mutex> lock(m_active_sessions_guard); auto it = m_active_sessions.find(session->getId()); if (it != m_active_sessions.end()) m_active_sessions.erase(it); lock.unlock(); if (m_debug) cout << "Session " << session->getId() << " was removed from list.\n"; if (!session->m_ec && session->m_was_cancelled.load()) ec = asio::error::operation_aborted; else ec = session->m_ec; // Call the callback provided by the user. session->m_callback(session->getId(), session->m_response, ec); }; void IHybrid::callOnRequestComplete(unsigned int session_id) { std::unique_lock<std::mutex> lock(m_active_sessions_guard); auto it = m_active_sessions.find(session_id); lock.unlock(); if (it != m_active_sessions.end()) onRequestComplete(it->second); } void IHybrid::write(unsigned int session_id, std::string &data) { std::unique_lock<std::mutex> lock(m_active_sessions_guard); auto it = m_active_sessions.find(session_id); lock.unlock(); if (it != m_active_sessions.end()) it->second->write(data); else cout << "Session " << session_id << " was not found\n"; } void IHybrid::disconnectAll() { for (auto &s: m_active_sessions) { disconnect(s.second->getId()); } } void IHybrid::disconnect(unsigned int session_id) { std::unique_lock<std::mutex> lock(m_active_sessions_guard); auto it = m_active_sessions.find(session_id); lock.unlock(); if (it != m_active_sessions.end()) { if (m_instanceType == InstanceType::ServerInstance) if (!it->second->connected.load()) return; std::unique_lock<std::mutex> cancel_lock(it->second->m_cancel_guard); it->second->m_was_cancelled.store(true); it->second->getSocket().cancel(); if (m_debug) cout << "Session " << session_id << " was manually disconnected.\n"; } } IHybrid::~IHybrid() { // Destroy work object. I/O threads exit the event loop // when there are no more pending asynchronous operations. m_work.reset(NULL); // Waiting for the I/O threads to exit. for (auto &thread : m_thread_pool) thread->join(); }
[ "mr.kirillov@icloud.com" ]
mr.kirillov@icloud.com
ed1d4cda44d4bb6095ff0c5b9581bd5f0f720ca5
402060870b2da94387f69a086b4a78c0733b8af5
/src/ast.cpp
ac8b830e4f54c4283aa3573d2bf6c3149b5524fb
[]
no_license
itiB/minimalCCompiler
b4e2b74a684d2cc7fb7477169bca9bded7d5ef35
726a910465bb98dfd4f1f0f5371f1654e0a1d886
refs/heads/master
2022-12-06T18:51:40.489952
2020-08-26T17:23:10
2020-08-27T02:51:34
287,526,098
1
0
null
null
null
null
UTF-8
C++
false
false
1,723
cpp
#include "ast.hpp" TranslationUnitAST::~TranslationUnitAST() { // プロトタイプの数分 for (int i = 0; i < Prototypes.size(); i++) { SAFE_DELETE(Prototypes[i]); } Prototypes.clear(); for (int i = 0; i < Functions.size(); i++) { SAFE_DELETE(Functions[i]); } Functions.clear(); } /// PrototypeAST(関数宣言追加メソッド) /// @param VariableDeclAST /// @retirm true bool TranslationUnitAST::addPrototype(PrototypeAST *proto) { Prototypes.push_back(proto); return true; } /// FunctionAST(関数定義追加)メソッド /// @param VariableDeclAST /// @return true bool TranslationUnitAST::addFunction(FunctionAST *func) { Functions.push_back(func); return true; } bool TranslationUnitAST::empty() { if (Prototypes.size() == 0 && Functions.size() == 0) { return true; } else { return false; } } /// デストラクタ FunctionAST::~FunctionAST(){ SAFE_DELETE(Proto); SAFE_DELETE(Body); } /// デストラクタ FunctionStmtAST::~FunctionStmtAST() { // delete variable declaration for (int i = 0; i < VariableDecls.size(); i++) { SAFE_DELETE(VariableDecls[i]); } VariableDecls.clear(); // delete statements for (int i = 0; i < StmtLists.size(); i++) { SAFE_DELETE(StmtLists[i]); } StmtLists.clear(); } /// VariableDeclAST(変数宣言追加)メソッド /// @param VariableDeclAST /// @return true bool FunctionStmtAST::addVariableDeclaration(VariableDeclAST *vdecl) { VariableDecls.push_back(vdecl); return true; } /// デストラクタ CallExprAST::~CallExprAST() { for (int i = 0; i < Args.size(); i++) { SAFE_DELETE(Args[i]); } }
[ "is0312vx@ed.ritsumei.ac.jp" ]
is0312vx@ed.ritsumei.ac.jp
35bd509c77739e294136f29df73b81f23486925f
7c92c6e4202aa422911b2f28f0a0f9c87beb4584
/src/TrackerHit.cc
9ce5d36fb195dc2ad9bbb9e8827fda3910634359
[]
no_license
hanswenzel/CaTS_legacy
581072f5c21d94fcb9d4252b2f2c47010c7750d9
b9de90f73c4532793919564e15709915e5b87d1f
refs/heads/master
2023-08-02T10:29:35.095980
2021-10-07T21:52:50
2021-10-07T21:52:50
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,766
cc
// // ******************************************************************** // * License and Disclaimer * // * * // * The Geant4 software is copyright of the Copyright Holders of * // * the Geant4 Collaboration. It is provided under the terms and * // * conditions of the Geant4 Software License, included in the file * // * LICENSE and available at http://cern.ch/geant4/license . These * // * include a list of copyright holders. * // * * // * Neither the authors of this software system, nor their employing * // * institutes,nor the agencies providing financial support for this * // * work make any representation or warranty, express or implied, * // * regarding this software system or assume any liability for its * // * use. Please see the license in the file LICENSE and URL above * // * for the full disclaimer and the limitation of liability. * // * * // * This code implementation is the result of the scientific and * // * technical work of the GEANT4 collaboration. * // * By using, copying, modifying or distributing the software (or * // * any work based on the software) you agree to acknowledge its * // * use in resulting scientific publications, and indicate your * // * acceptance of all terms of the Geant4 Software license. * // ******************************************************************** // //--------------------------------------------------------------------- //* |\___/| * //* ) ( * //* =\ /= * //* )===( * //* / \ CaTS: Calorimeter and Tracker Simulation * //* | | is a flexible and extend-able framework * //* / \ for the simulation of various detector * //* \ / systems * //* \__ _/ https://github.com/hanswenzel/CaTS * //* ( ( * //* ) ) * //* (_( * //* CaTS also serves as an example that demonstrates how to use * //* opticks from within Geant4 for the creation and propagation of * //* optical photons. * //* see https://bitbucket.org/simoncblyth/opticks.git). * //* Ascii Art by Joan Stark: https://www.asciiworld.com/-Cats-2-.html * //--------------------------------------------------------------------- // #include "TrackerHit.hh" //#include "G4UnitsTable.hh" #include "G4VVisManager.hh" #include "G4Circle.hh" #include "G4Colour.hh" #include "G4VisAttributes.hh" G4ThreadLocal G4Allocator<TrackerHit>* TrackerHitAllocator = nullptr; //....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo...... TrackerHit::TrackerHit() : G4VHit() {} TrackerHit::TrackerHit(G4double iedep, G4ThreeVector iposition, G4double itime) : G4VHit() { fEdep = iedep; fposition = iposition; ftime = itime; } //....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo...... TrackerHit::~TrackerHit() {} //....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo...... TrackerHit::TrackerHit(const TrackerHit& right) : G4VHit() { fEdep = right.fEdep; fposition = right.fposition; ftime = right.ftime; } //....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo...... const TrackerHit& TrackerHit::operator=(const TrackerHit& right) { fEdep = right.fEdep; fposition = right.fposition; ftime = right.ftime; return *this; } //....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo...... G4bool TrackerHit::operator==(const TrackerHit& right) const { return (this == &right) ? true : false; } //....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo...... void TrackerHit::Draw() { G4VVisManager* pVVisManager = G4VVisManager::GetConcreteInstance(); if(pVVisManager) { G4Circle circle(fposition); circle.SetScreenSize(2.); circle.SetFillStyle(G4Circle::filled); G4Colour colour(1., 0., 0.); G4VisAttributes attribs(colour); circle.SetVisAttributes(attribs); pVVisManager->Draw(circle); } }
[ "wenzel@fnal.gov" ]
wenzel@fnal.gov
e96bb2eda1bf2d1af5955bdf14174de5e0e4b716
d6249a6c85101170b3e0dd548ca6982bc8a94fbd
/Chef/JULY17/CHEFSIGN.cpp
72a795a7e9e1f1d7490879200f80bf856dbe1a2f
[]
no_license
anshumanv/Competitive
bb5c387168095f3716cabc6c591c3b7697da64da
828d07ad5217de06736ae538f54524092ec99af4
refs/heads/master
2021-08-19T08:35:30.019660
2017-11-25T14:38:38
2017-11-25T14:38:38
81,228,891
0
0
null
null
null
null
UTF-8
C++
false
false
625
cpp
#include<bits/stdc++.h> #define newl "\n" #define MODULO 1000000007 using namespace std; int main(){ std::ios::sync_with_stdio(false); int t; cin >> t; while(t--){ string s; cin >> s; int mx = 0, cm = 0; char cur = s[0]; for(int i = 0; i < s.length(); i++) { if(s[i] == '=') continue; if(s[i] == cur) cm++; else if(s[i] != cur) { cur = s[i]; cm = 1; } mx = max(mx, cm); } cout << mx + 1 << newl; } return 0; }
[ "anshu.av97@gmail.com" ]
anshu.av97@gmail.com
2921204dc91fbb418c191be83dcd1b4811fc13a0
2dc292f902891a58f67664a4ef27c982ff47da93
/src/Corrade/Utility/Resource.h
82c0c3ec7ce3d0a771cd6ce81c276b1c0a381123
[ "MIT" ]
permissive
njlr/corrade
7945757bc77ecb24946566759240f6711472e118
462b6184f97218886cc1baef9e044e46ae1b661b
refs/heads/master
2021-01-22T02:58:20.710246
2017-02-05T20:51:15
2017-02-05T23:41:04
null
0
0
null
null
null
null
UTF-8
C++
false
false
8,420
h
#ifndef Corrade_Utility_Resource_h #define Corrade_Utility_Resource_h /* This file is part of Corrade. Copyright © 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014, 2015, 2016 Vladimír Vondruš <mosra@centrum.cz> 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. */ /** @file * @brief Class @ref Corrade::Utility::Resource */ #include <map> #include <string> #include <utility> #include <vector> #include "Corrade/Containers/ArrayView.h" #include "Corrade/Utility/visibility.h" namespace Corrade { namespace Utility { /** @brief Data resource management This class provides support for compiled-in data resources - both compiling and reading. Resources can be differentiated into more groups, every resource in given group has unique filename. See @ref resource-management for brief introduction and example usage. Standalone resource compiler executable is implemented in @ref rc.cpp. ## Resource configuration file Function @ref compileFrom() takes configuration file as parameter. The file allows you to specify filenames and filename aliases of resource files instead of passing the data manually to @ref compile(). The file is used when compiling resources using @ref corrade-cmake-add-resource "corrade_add_resource()" via CMake. The file can be also used when overriding compiled-in resources with live data using @ref overrideGroup(). All filenames are expected to be in UTF-8. Example file: group=myGroup [file] filename=../resources/intro-new-final.ogg alias=intro.ogg [file] filename=license.txt [file] filename=levels-insane.conf alias=levels-easy.conf @todo Ad-hoc resources @todo Test data unregistering */ class CORRADE_UTILITY_EXPORT Resource { public: /** * @brief Compile data resource file * @param name Resource name (see @ref CORRADE_RESOURCE_INITIALIZE()) * @param group Group name * @param files Files (pairs of filename, file data) * * Produces C++ file with hexadecimal data representation. */ static std::string compile(const std::string& name, const std::string& group, const std::vector<std::pair<std::string, std::string>>& files); /** * @brief Compile data resource file using configuration file * @param name Resource name (see @ref CORRADE_RESOURCE_INITIALIZE()) * @param configurationFile Filename of configuration file * * Produces C++ file with hexadecimal data representation. See class * documentation for configuration file syntax overview. The filenames * are taken relative to configuration file path. */ static std::string compileFrom(const std::string& name, const std::string& configurationFile); /** * @brief Override group * @param group Group name * @param configurationFile Filename of configuration file. Empty * string will discard the override. * * Overrides compiled-in resources of given group with live data * specified in given configuration file, useful during development and * debugging. Subsequently created Resource instances with the same * group will take data from live filesystem instead and fallback to * compiled-in resources only for not found files. */ static void overrideGroup(const std::string& group, const std::string& configurationFile); /** @brief Whether given group exists */ static bool hasGroup(const std::string& group); /** * @brief Constructor * @param group Group name * * The group must exist. * @see @ref hasGroup() */ explicit Resource(const std::string& group); ~Resource(); /** * @brief List of all resources in the group * * Note that the list contains only list of compiled-in files, no * additional filenames from overriden group are incluuded. */ std::vector<std::string> list() const; /** * @brief Get pointer to raw resource data * @param filename Filename in UTF-8 * * Returns reference to data of given file in the group. The file must * exist. If the file is empty, returns `nullptr`. */ Containers::ArrayView<const char> getRaw(const std::string& filename) const; /** * @brief Get data resource * @param filename Filename in UTF-8 * * Returns data of given file in the group. The file must exist. */ std::string get(const std::string& filename) const; #ifdef DOXYGEN_GENERATING_OUTPUT private: #endif /* Internal use only. */ static void registerData(const char* group, unsigned int count, const unsigned char* positions, const unsigned char* filenames, const unsigned char* data); static void unregisterData(const char* group); private: struct CORRADE_UTILITY_LOCAL GroupData { explicit GroupData(); ~GroupData(); std::string overrideGroup; std::map<std::string, Containers::ArrayView<const char>> resources; }; struct OverrideData; /* Accessed through function to overcome "static initialization order fiasco" which I think currently fails only in static build */ CORRADE_UTILITY_LOCAL static std::map<std::string, GroupData>& resources(); std::map<std::string, GroupData>::const_iterator _group; OverrideData* _overrideGroup; }; /** @brief Initialize resource If a resource is compiled into dynamic library or directly into executable, it will be initialized automatically thanks to @ref CORRADE_AUTOMATIC_INITIALIZER() macros. However, if the resource is compiled into static library, it must be explicitly initialized via this macro, e.g. at the beginning of `main()`. You can also wrap these macro calls into another function (which will then be compiled into dynamic library or main executable) and use @ref CORRADE_AUTOMATIC_INITIALIZER() macro for automatic call. @attention This macro should be called outside of any namespace. If you are running into linker errors with `resourceInitializer_*`, this could be the problem. If you are in a namespace and cannot call this macro from `main()`, try this: @code static void initialize() { CORRADE_RESOURCE_INITIALIZE(res) } namespace Foo { void bar() { initialize(); //... } } @endcode @see @ref CORRADE_RESOURCE_FINALIZE() */ #define CORRADE_RESOURCE_INITIALIZE(name) \ extern int resourceInitializer_##name(); \ resourceInitializer_##name(); /** @brief Cleanup resource Cleans up resource previously (even automatically) initialized via @ref CORRADE_RESOURCE_INITIALIZE(). @attention This macro should be called outside of any namespace. See @ref CORRADE_RESOURCE_INITIALIZE() documentation for more information. */ #define CORRADE_RESOURCE_FINALIZE(name) \ extern int resourceFinalizer_##name(); \ resourceFinalizer_##name(); }} #endif
[ "mosra@centrum.cz" ]
mosra@centrum.cz
afd84e3ea6dfb9b70acfa6eec3c545e388614e94
574dce1edfa0c9e832f5651b12357faf81f15465
/Source/CVCBase.h
2bab0266c60d5b3fcb7a0639e75b66f8499d57c5
[ "Apache-2.0" ]
permissive
friolator/OpenCV-C
a47702eb6196926570eff52b5fde73b09590e436
e5cbad86c0daa9f32f9602398dd216c81db348cf
refs/heads/main
2023-06-09T08:06:13.462214
2021-06-24T14:28:14
2021-06-24T14:28:14
366,834,372
7
1
null
null
null
null
UTF-8
C++
false
false
5,070
h
// // CVCBase.h // OpenCV-C // // Created by Gerrit Goossen on 5/12/21. // Copyright (c) 2021 Gamma Ray Digital, Inc. All rights reserved. // #ifndef CVCBASE_H #define CVCBASE_H //#include <climits> //#include <algorithm> /* namespace Error { //! error codes enum Code { StsOk = 0, //!< everything is ok StsBackTrace = -1, //!< pseudo error for back trace StsError = -2, //!< unknown /unspecified error StsInternal = -3, //!< internal error (bad state) StsNoMem = -4, //!< insufficient memory StsBadArg = -5, //!< function arg/param is bad StsBadFunc = -6, //!< unsupported function StsNoConv = -7, //!< iteration didn't converge StsAutoTrace = -8, //!< tracing HeaderIsNull = -9, //!< image header is NULL BadImageSize = -10, //!< image size is invalid BadOffset = -11, //!< offset is invalid BadDataPtr = -12, //!< BadStep = -13, //!< image step is wrong, this may happen for a non-continuous matrix. BadModelOrChSeq = -14, //!< BadNumChannels = -15, //!< bad number of channels, for example, some functions accept only single channel matrices. BadNumChannel1U = -16, //!< BadDepth = -17, //!< input image depth is not supported by the function BadAlphaChannel = -18, //!< BadOrder = -19, //!< number of dimensions is out of range BadOrigin = -20, //!< incorrect input origin BadAlign = -21, //!< incorrect input align BadCallBack = -22, //!< BadTileSize = -23, //!< BadCOI = -24, //!< input COI is not supported BadROISize = -25, //!< incorrect input roi MaskIsTiled = -26, //!< StsNullPtr = -27, //!< null pointer StsVecLengthErr = -28, //!< incorrect vector length StsFilterStructContentErr = -29, //!< incorrect filter structure content StsKernelStructContentErr = -30, //!< incorrect transform kernel content StsFilterOffsetErr = -31, //!< incorrect filter offset value StsBadSize = -201, //!< the input/output structure size is incorrect StsDivByZero = -202, //!< division by zero StsInplaceNotSupported = -203, //!< in-place operation is not supported StsObjectNotFound = -204, //!< request can't be completed StsUnmatchedFormats = -205, //!< formats of input/output arrays differ StsBadFlag = -206, //!< flag is wrong or not supported StsBadPoint = -207, //!< bad CvPoint StsBadMask = -208, //!< bad format of mask (neither 8uC1 nor 8sC1) StsUnmatchedSizes = -209, //!< sizes of input/output structures do not match StsUnsupportedFormat = -210, //!< the data format/type is not supported by the function StsOutOfRange = -211, //!< some of parameters are out of range StsParseError = -212, //!< invalid syntax/structure of the parsed file StsNotImplemented = -213, //!< the requested function/feature is not implemented StsBadMemBlock = -214, //!< an allocated block has been corrupted StsAssert = -215, //!< assertion failed GpuNotSupported = -216, //!< no CUDA support GpuApiCallError = -217, //!< GPU API call error OpenGlNotSupported = -218, //!< no OpenGL support OpenGlApiCallError = -219, //!< OpenGL API call error OpenCLApiCallError = -220, //!< OpenCL API call error OpenCLDoubleNotSupported = -221, OpenCLInitError = -222, //!< OpenCL initialization error OpenCLNoAMDBlasFft = -223 }; }; */ enum CVCDecompTypes { CVC_DECOMP_LU = 0, CVC_DECOMP_SVD = 1, CVC_DECOMP_EIG = 2, CVC_DECOMP_CHOLESKY = 3, CVC_DECOMP_QR = 4, CVC_DECOMP_NORMAL = 16 }; enum CVCNormTypes { CVC_NORM_INF = 1, CVC_NORM_L1 = 2, CVC_NORM_L2 = 4, CVC_NORM_L2SQR = 5, CVC_NORM_HAMMING = 6, CVC_NORM_HAMMING2 = 7, CVC_NORM_TYPE_MASK = 7, CVC_NORM_RELATIVE = 8, CVC_NORM_MINMAX = 32 }; enum CVCCmpTypes { CVC_CMP_EQ = 0, CVC_CMP_GT = 1, CVC_CMP_GE = 2, CVC_CMP_LT = 3, CVC_CMP_LE = 4, CVC_CMP_NE = 5 }; enum CVCGemmFlags { CVC_GEMM_1_T = 1, CVC_GEMM_2_T = 2, CVC_GEMM_3_T = 4 }; enum CVCDftFlags { CVC_DFT_INVERSE = 1, CVC_DFT_SCALE = 2, CVC_DFT_ROWS = 4, CVC_DFT_COMPLEX_OUTPUT = 16, CVC_DFT_REAL_OUTPUT = 32, CVC_DFT_COMPLEX_INPUT = 64, CVC_DCT_INVERSE = CVC_DFT_INVERSE, CVC_DCT_ROWS = CVC_DFT_ROWS }; enum CVCBorderTypes { CVC_BORDER_CONSTANT = 0, CVC_BORDER_REPLICATE = 1, CVC_BORDER_REFLECT = 2, CVC_BORDER_WRAP = 3, CVC_BORDER_REFLECT_101 = 4, CVC_BORDER_TRANSPARENT = 5, CVC_BORDER_REFLECT101 = CVC_BORDER_REFLECT_101, CVC_BORDER_DEFAULT = CVC_BORDER_REFLECT_101, CVC_BORDER_ISOLATED = 16 }; #endif /* CVCBASE_H */
[ "developer@gerrit.email" ]
developer@gerrit.email
c68e6632d0a1d0e63ead414f8ccee738657b39e5
317649dde4c3ca8b185d98eda59aff11c3276c88
/analysis/read_02.cpp
65b7502d5614dc0f82b3b661b29a235baddf0e2c
[]
no_license
freejiebao/generator
8b5019cdf53be70006405a4d9547d693f813d9bd
8e658a44e69d770ac57e6bc9d13a66bcebcab07a
refs/heads/master
2021-06-16T14:31:10.174653
2021-05-19T08:13:41
2021-05-19T08:13:41
203,158,169
1
2
null
null
null
null
UTF-8
C++
false
false
15,594
cpp
// c++ -o read_02 `root-config --glibs --cflags` CfgParser.cc LHEF.cc -lm read_02.cpp /* apply basic VBS selections http://govoni.web.cern.ch/govoni/tesi/docs/Alessandro_Tarabini_Tesi.pdf */ #include "LHEF.h" //#include "LHEF_joint.h" #include <iomanip> #include <vector> #include <map> #include <iostream> #include <string> #include <sstream> #include <iterator> #include <cstdlib> #include <cassert> #include <fstream> #include <algorithm> #include "TH1.h" #include "TH2.h" #include "TFile.h" #include "TLorentzVector.h" #include "CfgParser.h" using namespace std ; // all histograms of a single sample struct histos { TString m_name ; // name of the sample double m_XS ; // cross-section of the sample (in fb) double m_lumi ; // integrated luminosity (in /fb) map<string, TH1F *> m_histograms ; // integral of the events collected, // needed for the histograms normalisation double m_norm ; histos (TString name, double XS, double lumi = 1.) : m_name (name), m_XS (XS), m_lumi (lumi), m_norm (0.) { makeHisto ("m_mjj","m_{jj}[GeV]","a.u.", 40,0,2000) ; makeHisto ("m_mll","m_{ll}[GeV]","a.u.", 40,0,400) ; makeHisto ("m_ptl1","p_{t}^{l1}[GeV]","a.u.", 40,0,400) ; makeHisto ("m_ptl2","p_{t}^{l2}[GeV]","a.u.", 40,0,400) ; makeHisto ("m_ptj1","p_{t}^{j1}[GeV]","a.u.", 40,0,400) ; makeHisto ("m_ptj2","p_{t}^{j2}[GeV]","a.u.", 40,0,400) ; makeHisto ("m_met","p_{t}^{miss}[GeV]","a.u.", 40,0,400) ; makeHisto ("m_detajj","#Delta#eta_{jj}[GeV]","a.u.", 15,2.5,10) ; makeHisto ("m_mlvlv","m_{lvlv}[GeV]","a.u.", 15,250,400) ; makeHisto ("costheta1","cos#theta1","a.u.", 10,-1,1) ; makeHisto ("costheta2","cos#theta2","a.u.", 10,-1,1) ; makeHisto ("costheta11","cos#theta1","a.u.", 10,-1,1) ; makeHisto ("costheta22","cos#theta2","a.u.", 10,-1,1) ; } double increaseNorm (double step = 1.) { m_norm += step ; return m_norm ; } // simplify histogram creation TH1F * makeHisto (const TString & varname, const TString & x_axis,const TString & y_axis, int nBins, float min, float max) { TH1F * histo = new TH1F (varname + TString ("_") + m_name, varname + TString ("_") + m_name+TString(";")+x_axis+TString(";")+y_axis, nBins, min, max) ; histo->Sumw2 () ; if (m_histograms.find (varname.Data ()) != m_histograms.end ()) { cout << "WARNING histogram " << varname << " defined twice" << endl ; return histo ; } m_histograms[varname.Data ()] = histo ; return histo ; } // fill the histograms through the map void fill (string varname, double value, double weight = 1.) { if (m_histograms.find (varname) == m_histograms.end ()) { cout << "WARNING histogram " << varname << " does not exist" << endl ; return ; } m_histograms[varname]->Fill (value, weight) ; return ; } // normalise histograms to the integrated cross-section void norm (/* double inputIntegral = 0*/) { // double factor = m_lumi * m_XS / fabs (m_histograms.begin ()->second->Integral ()) ; // if (inputIntegral != 0) factor = m_lumi * m_XS / inputIntegral ; double factor = m_lumi * m_XS / m_norm ; for (map<string, TH1F *>::iterator it = m_histograms.begin () ; it != m_histograms.end () ; ++it) it->second->Scale (factor) ; } ~histos () { // this being empty is not very nice, to be replaced with the unique_ptr or auto_ptr thing // for the histogram pointers, but I need to find a smart way to do it // w/o need for implementing it for each histogram I add } void save (TFile & outfile) { outfile.cd () ; for (map<string, TH1F *>::iterator it = m_histograms.begin () ; it != m_histograms.end () ; ++it) it->second->Write () ; } } ; // ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- TLorentzVector buildLP (LHEF::Reader & reader, int iPart) { TLorentzVector tlv ( reader.hepeup.PUP.at (iPart).at (0), //PG px reader.hepeup.PUP.at (iPart).at (1), //PG py reader.hepeup.PUP.at (iPart).at (2), //PG pz reader.hepeup.PUP.at (iPart).at (3) //PG E ) ; return tlv ; } // ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- inline float zetaStar (float etaq1, float etaq2, float eta) { return (eta - 0.5 * (etaq1 + etaq2)) / fabs (etaq1 - etaq2) ; } // ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- // Fill the histograms for a single sample // histograms will not get normalised, since the same sample // could be split in several LHE files and this function // may get called several times, one for each LHE file. // Therefore, the normalisation will have to be called afterwards double fillHistos (LHEF::Reader & reader, histos & Histos, int max = -1) { int events = 0 ; //PG loop over input events while (reader.readEvent ()) { // if ( reader.outsideBlock.length() ) std::cout << reader.outsideBlock; if (events++ % 10000 == 0) cout << " reading event in file: " << events << endl ; vector<TLorentzVector> v_f_Ws ; vector<TLorentzVector> v_f_quarks ; vector<TLorentzVector> v_f_leptons ; vector<TLorentzVector> v_f_electrons ; vector<TLorentzVector> v_f_muons ; vector<TLorentzVector> v_f_neutrinos ; vector<TLorentzVector> v_f_electron_neutrinos ; vector<TLorentzVector> v_f_muon_neutrinos ; vector<TLorentzVector> lepton_mother_vector ; vector<int> v_pdgId_leptons; // loop over particles in the event for (int iPart = 2 ; iPart < reader.hepeup.IDUP.size (); ++iPart) { // weight info map<string, int>::iterator iter; auto _map=reader.heprup.weightmap; auto _weights=reader.hepeup.weights; iter=_map.begin(); while(iter!=_map.end()){ cout<<iter->first<<"\t"<<iter->second<<"\t"<<_weights->at(iter->second)<<endl; iter++; } // outgoing particles if (reader.hepeup.ISTUP.at (iPart) == 1) { TLorentzVector dummy = buildLP (reader, iPart) ; // quarks if (abs (reader.hepeup.IDUP.at (iPart)) < 6 || abs (reader.hepeup.IDUP.at (iPart))==21) { v_f_quarks.push_back (dummy) ; } // quarks else if (abs (reader.hepeup.IDUP.at (iPart)) == 11){ v_f_electrons.push_back (dummy) ; } else if (abs (reader.hepeup.IDUP.at (iPart)) == 13){ v_f_muons.push_back (dummy) ; } else if (abs (reader.hepeup.IDUP.at (iPart)) == 12){ v_f_electron_neutrinos.push_back (dummy) ; } else if (abs (reader.hepeup.IDUP.at (iPart)) == 14){ v_f_muon_neutrinos.push_back (dummy) ; } /* else if (abs (reader.hepeup.IDUP.at (iPart)) == 11 || abs (reader.hepeup.IDUP.at (iPart)) == 13 || abs (reader.hepeup.IDUP.at (iPart)) == 15) { v_f_leptons.push_back (dummy) ; v_pdgId_leptons.push_back(reader.hepeup.IDUP.at (iPart)); //TLorentzVector mother_W = buildLP (reader, reader.hepeup.MOTHUP.at (iPart).second) ; //lepton_mother_vector.push_back(mother_W); } else if (abs (reader.hepeup.IDUP.at (iPart)) == 12 || abs (reader.hepeup.IDUP.at (iPart)) == 14 || abs (reader.hepeup.IDUP.at (iPart)) == 16) { v_f_neutrinos.push_back (dummy) ; } */ } // outgoing particles } // loop over particles in the event int warnNum = 0 ; if (v_f_quarks.size () < 2) { cout << "warning, not enough quarks" << endl ; ++warnNum ; } if (v_f_electrons.size () < 1 || v_f_muons.size()<1) { //cout << "warning, not enough leptons" << endl ; ++warnNum ; } if (v_f_electron_neutrinos.size () < 1 || v_f_muon_neutrinos.size()<1) { //cout << "warning, not enough neutrinos" << endl ; ++warnNum ; } if (warnNum > 0) continue ; auto l1=v_f_electrons.at(0); auto l2=v_f_muons.at(0); auto n1=v_f_electron_neutrinos.at(0); auto n2=v_f_muon_neutrinos.at(0); auto j1=v_f_quarks.at(0); auto j2=v_f_quarks.at(1); if (l1.DrEtaPhi(l2)<0.3 || l1.DrEtaPhi(j1)<0.3 || l1.DrEtaPhi(j2)<0.3 || l2.DrEtaPhi(j1)<0.3 || l2.DrEtaPhi(j1)<0.3){ cout << "warning, leptons are not clean from jets" << endl ; continue; } //PG apply basic selections //PG ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- float weight = reader.hepeup.XWGTUP ; Histos.increaseNorm (weight) ; if (l1.Pt () < 20) continue ; if (l2.Pt () < 20) continue ; if (abs(l1.Eta ()) > 2.5) continue ; if (abs(l2.Eta ()) > 2.5) continue ; auto ME = n1+ n2; if (ME.Pt () < 40) continue ; if (j1.Pt () < 30) continue ; if (j2.Pt () < 30) continue ; if (abs(j1.Eta ()) > 4.5) continue ; if (abs(j2.Eta ()) > 4.5) continue ; TLorentzVector v_jj = j1 + j2 ; if (fabs (j1.Eta () - j2.Eta ()) < 2.5 ) continue ; if (v_jj.M () < 500) continue ; TLorentzVector v_ll = l1 + l2 ; //if (v_ll.M () < 20) continue ; TLorentzVector v_lvlv = l1+n1+l2+n2; if (v_lvlv.M () < 250) continue ; //if (fabs (zetaStar (v_f_quarks.at (0).Eta (), v_f_quarks.at (1).Eta (), v_f_leptons.at (0).Eta ())) > 0.75) continue ; //if (fabs (zetaStar (v_f_quarks.at (0).Eta (), v_f_quarks.at (1).Eta (), v_f_leptons.at (1).Eta ())) > 0.75) continue ; //PG fill histograms //PG ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- // Histos.m_mjj->Fill (v_jj.M (), reader.hepeup.XWGTUP) ; // Histos.m_mll->Fill (v_ll.M (), reader.hepeup.XWGTUP) ; Histos.fill ("m_mjj", v_jj.M (), weight) ; Histos.fill ("m_mll", v_ll.M (), weight) ; float ptl1 = l1.Pt () ; float ptl2 = l2.Pt () ; //if (ptl1 < ptl2) swap (ptl1, ptl2) ; Histos.fill ("m_ptl1", ptl1, weight) ; Histos.fill ("m_ptl2", ptl2, weight) ; Histos.fill ("m_mlvlv", v_lvlv.M(), weight) ; float ptj1 = j1.Pt () ; float ptj2 = j2.Pt () ; //if (ptj1 < ptj2) swap (ptj1, ptj2) ; Histos.fill ("m_ptj1", ptj1, weight) ; Histos.fill ("m_ptj2", ptj2, weight) ; Histos.fill ("m_detajj", abs(j1.Eta()-j2.Eta()), weight) ; Histos.fill ("m_met", ME.Pt (), weight) ; /* auto mother_W0_1=lepton_mother_vector.at(0); auto mother_W1_1=lepton_mother_vector.at(1); auto mother_W0_2=lepton_mother_vector.at(0); auto mother_W1_2=lepton_mother_vector.at(1); auto lepton0_1=v_f_leptons.at(0); auto lepton1_1=v_f_leptons.at(1); auto lepton0_2=v_f_leptons.at(0); auto lepton1_2=v_f_leptons.at(1); TVector3 b1(mother_W0_1.BoostVector()); mother_W1_1.Boost(-b1); lepton0_1.Boost(-b1); float costheta1=cos(lepton0_1.Angle(-mother_W1_1.Vect())); TVector3 b2(mother_W1_2.BoostVector()); mother_W0_2.Boost(-b2); lepton1_2.Boost(-b2); float costheta2=cos(lepton1_2.Angle(-mother_W0_2.Vect())); */ auto l1_1=l1; auto l2_1=l2; auto l1_2=l1; auto l2_2=l2; auto w1_1=l1+n1; auto w2_1=l2+n2; auto w1_2=l1+n1; auto w2_2=l2+n2; auto wboost1_1=w1_1.BoostVector(); auto wboost2_1=w2_1.BoostVector(); auto wboost1_2=w1_2.BoostVector(); auto wboost2_2=w2_2.BoostVector(); l1_1.Boost(-wboost1_1); w1_1.Boost(-wboost1_1); w2_1.Boost(-wboost1_1); l2_2.Boost(-wboost2_2); w2_2.Boost(-wboost2_2); w1_2.Boost(-wboost2_2); Histos.fill ("costheta1", TMath::Cos(l1_1.Vect().Angle(w1_1.Vect())), weight) ; Histos.fill ("costheta2", TMath::Cos(l2_2.Vect().Angle(w2_2.Vect())), weight) ; Histos.fill ("costheta11", cos(l1_1.Angle(-w2_1.Vect())), weight) ; Histos.fill ("costheta22", cos(l2_2.Angle(-w1_2.Vect())), weight) ; if (max > 0 && max < events) { cout << max << " events reached, exiting" << endl ; break ; } } //PG loop over input events return events ; } // ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- struct inputInfo { double mass ; string mg_file ; double mg_xs ; string ph_file ; double ph_xs ; void print () { cout << "----------------------------\n" ; cout << "mass : " << mass << "\n" ; cout << "mg_file : " << mg_file << "\n" ; cout << "mg_xs : " << mg_xs << "\n" ; cout << "ph_file : " << ph_file << "\n" ; cout << "ph_xs : " << ph_xs << "\n" ; cout << "----------------------------\n" ; } } ; // ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- int main (int argc, char ** argv) { if (argc < 2) { cerr << "Forgot to put the cfg file --> exit " << endl ; return 1 ; } int maxEventsPerSample = -1 ; if (argc >= 3) { maxEventsPerSample = atoi (argv[2]) ; } cout << "reading " << maxEventsPerSample << " events per sample" << endl ; CfgParser * gConfigParser = new CfgParser (argv[1]) ; //PG get the samples to be analised, //PG including collection of LHE files and the relative XS vector<string> collections = gConfigParser->readStringListOpt ("general::samples") ; map<string, pair<float, vector<string> > > samples ; // loop over samples for (int i = 0 ; i < collections.size () ; ++i) { float XS = gConfigParser->readFloatOpt (collections.at (i) + "::XS") ; vector<string> inputfiles = gConfigParser->readStringListOpt (collections.at (i) + "::files") ; samples[collections.at (i)] = pair<float, vector<string> > (XS, inputfiles) ; } // loop over samples //PG prepare the histogram structs to be filled, //PG fill the histograms looping on LHE events // loop over samples map<string, pair<float, vector<string> > >::iterator it ; vector<histos> Histos ; for (it = samples.begin () ; it != samples.end () ; ++it) { cout << "sample: " << it->first << endl ; Histos.push_back (histos (it->first, it->second.first)) ; // loop over files int events = 0 ; for (int ifile = 0 ; ifile < it->second.second.size () ; ++ifile) { cout << " reading: " << it->second.second.at (ifile) << endl ; std::ifstream ifs (it->second.second.at (ifile).c_str ()) ; LHEF::Reader reader (ifs) ; events += fillHistos (reader, Histos.back (), maxEventsPerSample) ; if (maxEventsPerSample > 0 && events >= maxEventsPerSample) break ; cout << " read: " << events << " events" << endl ; } // loop over files Histos.back ().norm () ; } // loop over samples //PG save histograms string outfilename = gConfigParser->readStringOpt ("general::outputFile") ; TFile outFile (outfilename.c_str (), "recreate") ; for (int i = 0 ; i < Histos.size () ; ++i) Histos.at (i).save (outFile) ; outFile.Close () ; return 0 ; }
[ "jiexiao@pku.edu.cn" ]
jiexiao@pku.edu.cn
111bd1840363661737efc3df016d8937b0e75b33
123fd2a7f70913fa0103ceb14d812507dd5b27b6
/A1.cpp
c671119ce205f6b1eeb57b2bde286dad68ad00b2
[]
no_license
PeterSo123/A1
2ce82d990ef805ea3e6222d8e31235fb1e9542df
c06b465e0949bd9d50f21a7c9620c7b68e914847
refs/heads/master
2021-01-25T14:26:59.091686
2018-03-08T18:14:12
2018-03-08T18:14:12
123,699,557
0
0
null
null
null
null
UTF-8
C++
false
false
3,651
cpp
// CCN2042 Assignment 1 // Program template file: A1Template.cpp #include <iostream> #include <iomanip> #include <cmath> using namespace std; void showInfo() { // Insert your codes to display your personal particulars here cout << "Name : So Man Lung" << endl; cout << "Student ID: 17180545A" << endl; cout << "Class : 202C" << endl; } void Q1() { // Insert your codes for Question 1 here double a, A; // a is store the side input A is store angle input const double PI = 3.1416; // define the pi value and calculate another side cin >> A; cin >> a; if ((A < 0 || A > 90) || a <= 0) // check the A is it less than 0 or lager than 90 and a is it less than 0 { cout << endl << "Error" << endl; /* if the statement is ture it will output "Error" message to notice user input worng value */ } else { cout << fixed << setprecision(3); // set the all the value output is correct to 3 d.p.() cout << a << endl; cout << a / tan(A * PI / 180) << endl; // calculate and output the side b cout << a / sin(A * PI / 180) << endl; // calculate and output the side c cout << A << "°" << endl; cout << 180 - (A + 90) << "°" << endl; // calculate and output the angle B } return; } void Q2() { int num, sum = 0, count = 0; do { count++; cin >> num; if (count == 1 && num == 0) { cout << "Error" << endl; count = 0; } else if () { break; } else if (count % 2 == 0) { sum = sum + pow(num, 3); } else { sum = sum - pow(num, 3); } } while (count < 9 || cin.eof()); cout << sum << endl; return; } void Q3() { // Insert your codes for Question 3 here int size; do { cout << endl; cin >> size; // let user to input the size value to print the suitable bottle if (size < 2 || size > 6) // check user input size is it correct { cout << "Error" << endl; cin >> size; } } while (size < 2 || size > 6); // loop when user input size isn't correct and input angain until input correct for (int space = 0; space < 1; space++) // loop of drawing the bottle { cout << setw(3); for (int repeat = 2; repeat > 0; repeat--) //loop of drawing the bottle of the top { cout << setw(3); for (int top = 0; size > top; top++) { cout << "#"; } cout << endl; } for (int gap = 0; (size - 2) > gap; gap++) // loop of print endl; when the size - 2 is larger than 0 { cout << setw(3) << "#" << setw(size - 1) << "#" << endl; } cout << setw(2) << "#" << setw(size + 1) << "#" << endl; // print out the bridge cout << "#" << setw(size + 3) << "#" << endl; // print out the bridge for (int gap = 0; (size + 4) > gap; gap++) // loop of print endl; when the size + 4 is larger than 0 { for (int down = 0; (size + 4) > down; down++) // drawing the bottom of the bottle { cout << "#"; } cout << endl; } } return; } // GIVEN CODES, DO NOT MODIFY // BEGIN int main() { int prog_choice; showInfo(); do { cout << endl; cout << "Assignment One - Program Selection Menu" << endl; cout << "---------------------------------------" << endl; cout << "(1) Program One" << endl; cout << "(2) Program Two" << endl; cout << "(3) Program Three" << endl; cout << "(4) Exit" << endl; cout << "Enter the choice: "; cin >> prog_choice; switch (prog_choice) { case 1: Q1(); break; case 2: Q2(); break; case 3: Q3(); break; case 4: break; default: cout << "Please enter choice 1 - 4 only." << endl; break; } } while (prog_choice != 4); cout << "Program terminates. Good bye!" << endl; return 0; } // END
[ "noreply@github.com" ]
PeterSo123.noreply@github.com
b13fd7ce2bb7c03c28f496ea6936dfca22048fd0
789e0754f2480c6d04dbd3c8056f8c76076c95a2
/ads01spi.ino
fd7e2d4ae2017e3502624cc02f8077f9d69bf658
[]
no_license
RodolfoLemes/ads01spi
c21fb76e7f45dd18b5d74ecb8bbe87a1eae25efe
450e4a7b87dcccd87c44745f0a434ee3c00ed133
refs/heads/master
2023-01-22T08:29:15.049976
2020-12-01T19:33:25
2020-12-01T19:33:25
314,567,162
0
0
null
null
null
null
UTF-8
C++
false
false
2,356
ino
/* * ADS01SPI * Acquisition and interpretation of signals with ADC Sigma-Delta and communication protocol SPI * * Authors: * Rodolfo Lemes Saraiva * Leonardo Garbuggio Armelin * * Project made for the discipline "Projeto de Microcontroladores" * State University of Maringá (UEM) * Professor: Rubens Sakiyama * * ----------------------------------------------------------- * ADC AD7322 * 13 - SCLK * 12 - MISO / DIN * 11 - MOSI / DOUT * 9 - SS / CS */ #include <SPI.h> // include the SPI library #include <digitalWriteFast.h> // from http://code.google.com/p/digitalwritefast/downloads/list #define SLAVESELECT 9 // Variables long result = 0; byte sig = 0; // sign bit byte d, e; float v = 0; byte samples[1700]; // 850 samples short cont = 0; short serialCont = 0; // Timer1 function ISR(TIMER1_COMPA_vect){ // Set SS/CS to LOW digitalWriteFast(SLAVESELECT,LOW); // Transfer and receive 2 bytes samples[cont] = SPI.transfer(0); samples[cont+1] = SPI.transfer(0); cont = cont + 2; if(cont >= 1700) cont = 0; // Set SS/CS to HIGH digitalWriteFast(SLAVESELECT,HIGH); } void setup() { cli(); // stop interrupts // TIMER 1 for interrupt frequency 150 kHz: TCCR1A = 0; TCCR1B = 0; TCNT1 = 0; OCR1A = 105; // = 16000000 / (1 * 150k) - 1 (must be <65536) TCCR1B |= (1 << WGM12); TCCR1B |= (0 << CS12) | (0 << CS11) | (1 << CS10); TIMSK1 |= (1 << OCIE1A); // Serial in 57600 bytes per second Serial.begin(57600); // set up serial comm to PC at this baud rate pinMode(SLAVESELECT, OUTPUT); // SPI in 16 MHz, MSBFIRST, clock down SPI.begin(); SPI.beginTransaction(SPISettings(16000000, MSBFIRST, SPI_MODE0)); sei(); // allow interrupts } void loop() { // Receive the stored bytes in buffer samples d = samples[serialCont]; e = samples[serialCont+1]; // Byte Handling with bitwise operators sig = (d & 0x10) == 0x10; d = d & 0xf; result = d; result = result << 8; result |= e; if (sig) { result = result - 1; result = ~result; result = result & 0b111111111111; result = result*(-1); } // Resulting voltage v = result; v = (v* 5 / 4096)*8; Serial.print(v); Serial.print(','); //Serial.print(cont); //Serial.print(','); //Serial.println(serialCont); serialCont = serialCont + 2; if(serialCont >= 1700) serialCont = 0; }
[ "rodolfo_fero@hotmail.com" ]
rodolfo_fero@hotmail.com
8ef8e786430cc0eea4ed91aa9093dc59ddcf5aee
cbb6b7b9c575f85570d7a025739bf43436814b64
/SFrame/Zgamma/src/TagSelector.cxx
65104ee21acaf875abbdc47999e95dd454f7bb8a
[]
no_license
stahlman/Higgs4l
37df3e264d6be3720808a6eedb11f927df6ad58b
a530357fff2f790540ea3cfcfb80c318e4e8516d
refs/heads/master
2021-01-01T15:59:22.096275
2015-02-10T23:28:08
2015-02-10T23:28:08
30,620,561
0
0
null
null
null
null
UTF-8
C++
false
false
7,240
cxx
// $Id: TagSelector.cxx 18120 2012-09-16 14:35:37Z sheim $ // Local include(s): #include "../include/TagSelector.h" #include "../include/TriggerSelector.h" #include <math.h> // AtlasSFrameUtils #include "CycleMacros.h" #include "Electron.h" #include "Muon.h" #include "ParticleElementBuilder.h" //Common Tools #include "EnergyRescalerTool.h" #include "IDTool.h" //RootCore //#include "egammaAnalysisUtils/MultiLeptonDefs.h" #include "egammaEvent/egammaPIDdefs.h" #include "egammaAnalysisUtils/IsEMPlusPlusDefs.h" const float M_MU = 105.658367; const float GeV = 1000.0; ClassImp( TagSelector ); TagSelector::TagSelector(SCycleBase* parent, const char* name) : ToolBase( parent, name ), cf_preselect(0), cf_author(0), cf_electronid(0), cf_eta(0), cf_et(0), cf_oq(0), cf_z0(0), cf_trigger(0) { DeclareProperty( "DoSmear", m_doSmear ); DeclareProperty( "DoCalibration", m_doCalibration ); DeclareProperty( "VetoCrack", m_vetoCrack ); DeclareProperty( "DoLikelihood", m_doLikelihood ); DeclareProperty( "LikelihoodOP", m_likelihoodOP = "Loose");//LikeEnum::Loose); DeclareProperty( "PTCutLikelihood", m_ptcutLikelihood ); DeclareProperty( "DoTruthMatchEleZ", m_doTruthMatchEleZ ); //m_likelihoodtool = new ElectronLikelihoodTool("RootCore/egammaAnalysisUtils/share/PDFs_2012_august25_update_1.root NO! "); //m_likelihoodtool = new ElectronLikelihoodToolLocal("config/other/PDFs_2012_august29_lowetbin.root NO! "); //m_likelihoodtool = new ElectronLikelihoodToolLocal("config/other/PDFs_2012_sig_tagInBarrelAtLowEt.root"); return; } TagSelector::~TagSelector() { return; } void TagSelector::BeginMasterInputData( const SInputData& ) throw( SError ){ return; } void TagSelector::EndMasterInputData( const SInputData& ) throw( SError ){ //print cut flow and fill cut flow histo. m_logger << ALWAYS <<" Zgamma Tag Cut Flow"<<SLogger::endmsg; m_logger << ALWAYS <<"============================"<<"============================"<<SLogger::endmsg; m_logger << ALWAYS <<"Cut........................:"<<"Number of electrons passed"<<SLogger::endmsg; m_logger << ALWAYS <<"============================"<<"============================"<<SLogger::endmsg; m_logger << ALWAYS <<"Electrons Before Cuts..........:"<<cf_preselect <<SLogger::endmsg; m_logger << ALWAYS <<"Electrons After Author.........:"<<cf_author <<" ("<<((double)cf_author)/((double)cf_preselect)*100 <<"%)" <<" ("<<((double)cf_author)/((double)cf_preselect)*100 <<"%)" <<SLogger::endmsg; m_logger << ALWAYS <<"Electrons After Electron ID....:"<<cf_electronid <<" ("<<((double)cf_electronid)/((double)cf_author)*100 <<"%)" <<" ("<<((double)cf_electronid)/((double)cf_preselect)*100 <<"%)" <<SLogger::endmsg; m_logger << ALWAYS <<"Electrons After Eta............:"<<cf_eta <<" ("<<((double)cf_eta)/((double)cf_electronid)*100 <<"%)" <<" ("<<((double)cf_eta)/((double)cf_preselect)*100 <<"%)" <<SLogger::endmsg; m_logger << ALWAYS <<"Electrons After Et.............:"<<cf_et <<" ("<<((double)cf_et)/((double)cf_eta)*100 <<"%)" <<" ("<<((double)cf_et)/((double)cf_preselect)*100 <<"%)" <<SLogger::endmsg; m_logger << ALWAYS <<"Electrons After Object Quality.:"<<cf_oq <<" ("<<((double)cf_oq)/((double)cf_et)*100 <<"%)" <<" ("<<((double)cf_oq)/((double)cf_preselect)*100 <<"%)" <<SLogger::endmsg; m_logger << ALWAYS <<"Electrons After Z0.............:"<<cf_z0 <<" ("<<((double)cf_z0)/((double)cf_oq)*100 <<"%)" <<" ("<<((double)cf_z0)/((double)cf_preselect)*100 <<"%)" <<SLogger::endmsg; m_logger << ALWAYS <<"Electrons After trigger........:"<<cf_trigger <<" ("<<((double)cf_trigger)/((double)cf_z0)*100 <<"%)" <<" ("<<((double)cf_trigger)/((double)cf_preselect)*100 <<"%)" <<SLogger::endmsg; m_logger << ALWAYS <<"============================"<<"============================"<<SLogger::endmsg; return; } void TagSelector::SelectElectrons( std::vector<Electron*> &sel_electrons, const D3PDReader::ElectronD3PDObject* m_electron_d3pdobject, const D3PDReader::EventInfoD3PDObject* m_event_d3pdobject, int n_vertices ) { //electron selection m_logger << ::DEBUG << "Electron Selection " << SLogger::endmsg; std::vector<Electron> all_eles; ParticleElementBuilder::build( all_eles, (*m_electron_d3pdobject) ); m_logger << ::DEBUG << "Number of electrons in event: " << all_eles.size() << SLogger::endmsg; for(std::vector<Electron>::iterator itr = all_eles.begin(); itr != all_eles.end(); ++itr) { //truthmatch //if(m_doTruthMatchEleZ && !(fabs((*itr).truth_type()) == 11 && (*itr).truth_matched() && (*itr).truth_mothertype() == 23) ) { if(!is_data() && m_doTruthMatchEleZ && !((*itr).truth_matched() == 1 && (((*itr).type() == 2 && (*itr).origin() == 13) || ((*itr).type() == 4 && ((*itr).originbkg() == 13 || (*itr).originbkg() == 40))))){ continue; } if(!is_data()) m_logger << ::DEBUG << "truthtype: " << fabs((*itr).truth_type()) << ", truthmatched: " <<(*itr).truth_matched() << ", truthmothertype: " << (*itr).truth_mothertype()<< SLogger::endmsg; cf_preselect++; //author m_logger << ::DEBUG << "Author cut" << SLogger::endmsg; if(!((*itr).author() == 1 || (*itr).author() == 3)) continue; cf_author++; //ID GET_TOOL(id, IDTool, "IDTool"); if(!(id->passPlusPlus((*itr),"tight"))) continue; cf_electronid++; //calibrate energy afterwards if (m_doSmear || m_doCalibration) { GET_TOOL(energy_rescaler, EnergyRescalerTool, "EnergyRescalerTool"); energy_rescaler->ApplyEnergyRescaler( (*itr), m_event_d3pdobject->EventNumber(), m_event_d3pdobject->RunNumber()); } //eta cuts, tag should eb out of crack m_logger << ::DEBUG << "Eta cut" << SLogger::endmsg; if(!(fabs((*itr).cl_eta()) < 2.47)) continue; if(fabs((*itr).cl_eta())<1.52 && fabs((*itr).cl_eta())>1.37) continue; cf_eta++; //et cut 25 GeV m_logger << ::DEBUG << "Et cut" << SLogger::endmsg; if(!((*itr).cl_Et() > 25000.)) continue; if(m_ptcutLikelihood && ((*itr).cl_Et() < 10000.)) continue; cf_et++; //object quality m_logger << ::DEBUG << "OQ cut" << SLogger::endmsg; if(!(((*itr).OQ()&1446) == 0)) continue; cf_oq++; //z0 cut --- leave out for now m_logger << ::DEBUG << "Z0 cut" << SLogger::endmsg; //if(!(fabs((*itr).trackz0pvunbiased()) < 10.)) continue; cf_z0++; //Trigger match m_logger << ::DEBUG << "Trigger match cut" << SLogger::endmsg; GET_TOOL(trig_select, TriggerSelector, "TriggerSelector"); bool trigger_pass = trig_select->MatchTriggers( (*itr) ); if (!trigger_pass) continue; cf_trigger++; sel_electrons.push_back( new Electron(*itr)); } m_logger << ::DEBUG << "Number of selected electrons in event: " << sel_electrons.size() << SLogger::endmsg; return; } double TagSelector::DeltaR(double eta1, double phi1, double eta2, double phi2) { double delta_phi = (fabs(phi1 - phi2) > TMath::Pi()) ? 2*TMath::Pi()-fabs(phi1 - phi2) : fabs(phi1 - phi2); double delta_eta = eta1 - eta2; return sqrt(delta_eta*delta_eta + delta_phi*delta_phi); }
[ "jonstahlman@gmail.com" ]
jonstahlman@gmail.com
a41cde0567c8ad6711aabbb545bda180930d6f95
08b8cf38e1936e8cec27f84af0d3727321cec9c4
/data/crawl/squid/old_hunk_7356.cpp
2e8e0bb179e021bcf0968d9b8122f36d58cc95b5
[]
no_license
ccdxc/logSurvey
eaf28e9c2d6307140b17986d5c05106d1fd8e943
6b80226e1667c1e0760ab39160893ee19b0e9fb1
refs/heads/master
2022-01-07T21:31:55.446839
2018-04-21T14:12:43
2018-04-21T14:12:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,314
cpp
va_end(args); } /* add directory to swap disk */ static int storeAddSwapDisk(const char *path) { char **tmp = NULL; int i; if (strlen(path) > (SQUID_MAXPATHLEN - 32)) fatal_dump("cache_dir pathname is too long"); if (CacheDirs == NULL) { CacheDirsAllocated = 4; CacheDirs = xcalloc(CacheDirsAllocated, sizeof(char *)); } if (CacheDirsAllocated == ncache_dirs) { CacheDirsAllocated <<= 1; tmp = xcalloc(CacheDirsAllocated, sizeof(char *)); for (i = 0; i < ncache_dirs; i++) *(tmp + i) = *(CacheDirs + i); xfree(CacheDirs); CacheDirs = tmp; } *(CacheDirs + ncache_dirs) = xstrdup(path); return ++ncache_dirs; } /* return the nth swap directory */ const char * swappath(int n) { return *(CacheDirs + (n % ncache_dirs)); } /* return full name to swapfile */ static char * storeSwapFullPath(int fn, char *fullpath) { LOCAL_ARRAY(char, fullfilename, SQUID_MAXPATHLEN); if (!fullpath) fullpath = fullfilename; fullpath[0] = '\0'; sprintf(fullpath, "%s/%02X/%02X/%08X", swappath(fn), (fn / ncache_dirs) % Config.levelOneDirs, (fn / ncache_dirs) / Config.levelOneDirs % Config.levelTwoDirs, fn); return fullpath; } /* swapping in handle */ static int storeSwapInHandle(int fd_notused, const char *buf, int len, int flag, StoreEntry * e)
[ "993273596@qq.com" ]
993273596@qq.com
5abfaef7b5777326941e1f697ee0ccfc62367410
7901e09d4f0827e0590fa6a7f038e7d9363e903b
/cpp_stl/iter/assoiter.h
36f91e837b03699abefe29563edb324dc3578bdf
[]
no_license
jiesoul/c_cpp_learn
32298fa21d159d3fc9a6c0c2711700548db9e4a2
cd4e411f73222dd26d22c1110ce0af4ecc60f051
refs/heads/main
2023-03-16T15:54:54.553175
2022-06-14T05:30:51
2022-06-14T05:30:51
204,853,153
0
0
null
null
null
null
UTF-8
C++
false
false
1,006
h
// // Created by jiesoul on 2019/10/16. // #ifndef C_CPP_LEARN_SRC_CPP_STL_ITER_ASSOITER_H_ #define C_CPP_LEARN_SRC_CPP_STL_ITER_ASSOITER_H_ #include <iterator> template <typename Container> class asso_insert_iterator : public std::iterator <std::output_iterator_tag, typename Container::value_type> { protected: Container& container; public: explicit asso_insert_iterator (Container& c) : container(c) {} asso_insert_iterator<Container>& operator= (const typename Container::value_type& value) { container.insert(value); return *this; } asso_insert_iterator<Container>&operator* () { return *this; } asso_insert_iterator<Container>&operator++ () { return *this; } asso_insert_iterator<Container>&operator++ (int) { return *this; } }; template <typename Container> inline asso_insert_iterator<Container> asso_inserter (Container& c) { return asso_insert_iterator<Container>(c); } #endif //C_CPP_LEARN_SRC_CPP_STL_ITER_ASSOITER_H_
[ "jiesoul@gmail.com" ]
jiesoul@gmail.com
4c6b162a22e7bd6510df07444a4d307e55b173e3
26690127f0fd138a3f0109702d71adc372831dd5
/Library/Maths/LinearAlgebra/matrix_inverse.cpp
ed78b9f9f360f2346fb1614702bb1e84e33a5651
[]
no_license
Mohammad-Yasser/CompetitiveProgramming
4bc2c14c54e9bc7be90bb684689c9340614d9d17
a48b744b1dedb2f4ad3d642f5e5899cf48d637d4
refs/heads/master
2023-04-09T02:48:27.066875
2021-04-24T11:41:18
2021-04-24T11:41:18
32,478,674
2
1
null
2020-06-05T04:13:21
2015-03-18T19:06:09
C++
UTF-8
C++
false
false
1,845
cpp
typedef double Double; typedef vector<Double> Row; typedef vector<Row> Matrix; void printMatrix(const Matrix& mat) { int n = mat.size(); int m = mat[0].size(); for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { cout << mat[i][j] << " "; } cout << endl; } } Matrix getEmptyMatrix(int n, int m) { return Matrix(n, Row(m, 0)); } Matrix inverseOfMatrix(const Matrix& matrix) { int n = matrix.size(); // Create the augmented matrix // Add the identity matrix // of order at the end of original matrix. int m = 2 * n; Matrix augmented = getEmptyMatrix(n, m); for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (j < n) { augmented[i][j] = matrix[i][j]; } else { if (j == (i + n)) { augmented[i][j] = 1; } } } } // Interchange the row of matrix, // interchanging of row will start from the last row for (int i = n - 1; i > 0; i--) { if (augmented[i - 1][0] < augmented[i][0]) { swap(augmented[i], augmented[i - 1]); } } // Replace a row by sum of itself and a // constant multiple of another row of the matrix for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (j != i) { Double temp = augmented[j][i] / augmented[i][i]; for (int k = 0; k < 2 * n; k++) { augmented[j][k] -= augmented[i][k] * temp; } } } } // Multiply each row by a nonzero integer. // Divide row element by the diagonal element for (int i = 0; i < n; i++) { Double temp = augmented[i][i]; for (int j = 0; j < 2 * n; j++) { augmented[i][j] /= temp; } } Matrix result = getEmptyMatrix(n, n); for (int i = 0; i < n; ++i) { for (int j = 0; j < n; ++j) { result[i][j] = augmented[i][j + n]; } } return result; }
[ "mohammadyasser3@gmail.com" ]
mohammadyasser3@gmail.com
fe7cd26aec2a530f470ed31b138d5ff4e3c056f6
6d51efbb264ef5920a99c54e2e436bc2f0a4ec40
/C++-Practise/BSTMinMaxDepth.cpp
72ee2a7bd3b8e87e71cb040c336e4b8ae4a39ce5
[]
no_license
Sarvesh1990/Coding-Practise
db3adc0d4fca25ddee6ea5c99ad6a26baac917de
6c64219f058d89c3fb76cc86ece4ec14dffd286e
refs/heads/master
2021-01-10T15:33:56.291896
2016-01-09T11:37:01
2016-01-09T11:37:01
47,115,152
0
0
null
null
null
null
UTF-8
C++
false
false
1,682
cpp
#include <iostream> #include <string> using namespace std; struct Node { int value; Node * left; Node * right; }; Node * newNode(int number) { Node * myNode = new Node(); myNode->value = number; myNode->left=myNode->right=NULL; return myNode; }; int MinDepth (Node * node) { int dl=0; int dr=0; if(node==NULL) { return 0; } dl = MinDepth(node->left); dr = MinDepth(node->right); if(dl<=dr) return ++dl; else return ++dr; }; int MaxDepth (Node * node) { int dl=0; int dr=0; if(node==NULL) { return 0; } dl = MaxDepth(node->left); dr = MaxDepth(node->right); if(dl>=dr) return ++dl; else return ++dr; }; int main() { //Create BST Node * root = newNode(25); root->left=newNode(14); root->left->left=newNode(10); root->left->right=newNode(18); root->left->right->left=newNode(17); root->left->right->right=newNode(20); root->right=newNode(35); root->right->left=newNode(30); root->right->right=newNode(45); root->right->right->right=newNode(55); root->right->right->right->left=newNode(50); root->right->right->right->right=newNode(60); root->right->right->right->left->right=newNode(53); root->right->right->right->left->left=newNode(48); root->right->right->left=newNode(40); root->right->right->left->right=newNode(43); root->right->right->left->right->left=newNode(42); root->right->right->left->right->right=newNode(44); int min = MinDepth(root); int max = MaxDepth(root); cout<<"Min depth is "<<min<<" and max depth is "<<max<<endl; }
[ "sarvesh@Sarveshs-MacBook-Air.local" ]
sarvesh@Sarveshs-MacBook-Air.local
aa6bbdb4d4a71e09f1b276b2f940c70db1c6aa35
af0aa93c55cbf9fcd8589cd0f764f9c348db8c9f
/Engine/Components/ComponentBase.h
d1e5dd2eb771fd1a496c7b9a0d40f7d04e851871
[]
no_license
Kickass-Global/Checkered
c758ad2ebd963fc8b07949c58e5f225eb486de06
399e1e666a16b4b35740ae6c46f339f9c7514b67
refs/heads/master
2020-12-06T07:03:43.419680
2020-04-20T17:29:45
2020-04-20T17:29:45
232,375,415
5
1
null
2020-04-20T16:27:50
2020-01-07T17:11:52
C++
UTF-8
C++
false
false
1,205
h
// // Created by root on 15/1/20. // #pragma once #ifndef ENGINE_COMPONENTBASE_H #define ENGINE_COMPONENTBASE_H #include <any> #include <unordered_map> #include <typeindex> #include <memory> #include <algorithm> #include "ComponentInterface.h" #include "Node.hpp" #include "Engine.h" namespace Component { class ComponentBase : public ComponentInterface { friend class ::EngineStore; protected: virtual ~ComponentBase() = default; Node children; // this hack is here because this is the easiest way. Engine::EngineSystem *enginePtr = Engine::current; public: ComponentId id = ++ ++next_id; [[nodiscard]] struct Node &getChildren() override { return children; } [[nodiscard]] ComponentId getId() const override { return id; } Engine::EngineSystem *getEngine() { return enginePtr; } struct Node &getStore() { return children; } ComponentBase &operator=(const ComponentBase &other) { if (this == &other)return *this; children = other.children; //id = other.id; // don't change it return *this; } }; } #endif //ENGINE_COMPONENTBASE_H
[ "jacksoncougar@gmail.com" ]
jacksoncougar@gmail.com
3513d2cc9938cbdd79d0702f8546abda983c04a3
cb2fb6bf31062869e319971a9d83e43d7909741f
/inorganic_DD/boundary_conditions.cpp
90ada04fe24a9621476394c5ad0e05d8f1cfaf29
[]
no_license
xiaoxianliu/drift_diffusion_fem
f71759a71b5519ba07da50aa39d171cf5fd32b6e
e6cdfddaf08d2d50656a0f357157302bcd2573ee
refs/heads/master
2016-09-05T23:11:02.851427
2013-10-07T00:52:34
2013-10-07T00:52:34
13,372,112
2
0
null
null
null
null
UTF-8
C++
false
false
1,135
cpp
#include <iostream> #include <cmath> #include <armadillo> #include "../triangle/mesh.hpp" #include "parameters.hpp" // Dirichlet boundary conditions for n, p, and psi arma::vec n_D_Vec(arma::vec C) {using parameters::delta_squared; arma::vec n_D(C.n_rows); for (int i=0; i<C.n_rows; i++) { double c = C(i); n_D(i) = 0.5*(c + sqrt(c*c + 4*delta_squared*delta_squared)); } return n_D; } arma::vec p_D_Vec(arma::vec C) {using parameters::delta_squared; arma::vec p_D(C.n_rows); for (int i=0; i<C.n_rows; i++) { double c = C(i); p_D(i) = 0.5*(-c+ sqrt(c*c + 4*delta_squared*delta_squared)); } return p_D; } arma::vec psi_D_Vec( const my_mesh::MeshData &mesh, const arma::vec &psi_bi, double psi_applied) { using parameters::delta_squared; arma::vec psi_D; psi_D = psi_bi; for (int i=0; i<mesh.num_nodes; i++) { std::vector<int> neigh_eles = mesh.topology0to2[i]; int marker = 1; for (int j=0; j<neigh_eles.size(); j++) { int t = neigh_eles[j]; if (mesh.element_markers[t]==2) { marker = 2; break; } } if (marker==1) psi_D(i) += psi_applied; } return psi_D; }
[ "liuxiaox@sas.upenn.edu" ]
liuxiaox@sas.upenn.edu
59828261ab114d5342c57cb47be4fc1f9ff7aca8
5750449c57fb5d3fad62c28b58239d7c55d1e4e6
/zmkv/src/MuxerPrivate.cpp
b33c686a83eb7f60b656b1ad0808d0be3f6294a1
[ "MIT" ]
permissive
voximplant/zmkv
0b4274bdb21234bf664d03adf9ac9a0f8d126ad8
5797db4fa97d795e794255bb6b304dd5b03423de
refs/heads/master
2021-01-10T01:31:25.070707
2015-11-20T07:33:33
2015-11-20T07:33:33
46,543,071
17
6
null
null
null
null
UTF-8
C++
false
false
4,727
cpp
// // Created by Andrey Syvrachev on 23.07.15. // asyvrachev@zingaya.com // www.voximplant.com // #include "MuxerPrivate.h" #include <ebml/EbmlHead.h> using namespace libebml; using namespace libmatroska; using namespace ZMKV; const auto cMaxSeekHeadSizeOctets = 3000; const auto cMaxTracksSizeOctets = 300; const unsigned long long cTimecodeScale = 1000000; const auto cbWithDefault = true; MuxerPrivate::MuxerPrivate(IOCallback &file) : file(file), max_ts(0), kaxDuration(NULL), renderedClustersSize(0) { InitFileHeader(); this->segmentSize = this->segment.WriteHead(this->file, 5, cbWithDefault); // reserve some space for the Meta Seek written at the end this->dummySeekHead.SetSize(cMaxSeekHeadSizeOctets); this->dummySeekHead.Render(this->file); InitSegmentInfo(); this->tracks = &GetChild<KaxTracks>(this->segment); // reserve space for track information written at the end this->dummyTracks.SetSize(cMaxTracksSizeOctets); this->dummyTracks.Render(this->file); this->cues.SetGlobalTimecodeScale(cTimecodeScale); CreateNewCluster(0); } MuxerPrivate::~MuxerPrivate() { CloseCurrentCluster(); filepos_t cueSize = this->cues.Render(this->file, false); this->seekHead.IndexThis(this->cues, this->segment); uint64 TrackSize = 0; if (this->tracks->GetElementList().size() > 0){ TrackSize = this->dummyTracks.ReplaceWith(*this->tracks, this->file); assert(TrackSize); } filepos_t seekHeadSize = dummySeekHead.ReplaceWith(this->seekHead, this->file); assert(seekHeadSize); // TODO: think about very big files!, must have workaround! UpdateDuration(); if (this->segment.ForceSize(this->segmentSize - this->segment.HeadSize() + seekHeadSize + TrackSize + this->renderedClustersSize + cueSize + this->segmentInfoSize)) { this->segment.OverwriteHead(this->file); } file.close(); } void MuxerPrivate::InitFileHeader() { EbmlHead FileHead; // EBML_SET(FileHead,EDocType,EbmlString,"webm"); // EBML_SET(FileHead,EDocTypeVersion,EbmlUInteger,MATROSKA_VERSION); // EBML_SET(FileHead,EDocTypeReadVersion,EbmlUInteger,MATROSKA_VERSION); FileHead.Render(this->file, cbWithDefault); } void MuxerPrivate::InitSegmentInfo() { // update duration KaxInfo &segmentInfo = GetChild<KaxInfo>(this->segment); EBML_SET(segmentInfo, KaxTimecodeScale, EbmlUInteger, cTimecodeScale); this->kaxDuration = &GetChild<KaxDuration>(segmentInfo); *(static_cast<EbmlFloat *>(this->kaxDuration)) = 0; EBML_SET(segmentInfo, KaxMuxingApp, EbmlUnicodeString, L"Zingaya RTP MKV"); EBML_SET(segmentInfo, KaxWritingApp, EbmlUnicodeString, L"Voximplant Media Server"); this->segmentInfoSize = segmentInfo.Render(this->file); } void MuxerPrivate::CreateNewCluster(unsigned long long ts) { // printf("CreateNewCluster(ts = %llu)\n", ts); this->currentCluster.reset(new KaxCluster); this->currentCluster->SetParent(this->segment); this->currentCluster->InitTimecode(ts / cTimecodeScale, cTimecodeScale); this->currentCluster->SetGlobalTimecodeScale(cTimecodeScale); this->currentCluster->EnableChecksum(); EBML_SET(*this->currentCluster, KaxClusterTimecode, EbmlUInteger, 0); } void MuxerPrivate::CloseCurrentCluster() { // printf("Render cluster timecode = %llu ...\n", this->currentCluster->GlobalTimecode()); this->renderedClustersSize += this->currentCluster->Render(this->file, this->cues); this->currentCluster->ReleaseFrames(); this->seekHead.IndexThis(*this->currentCluster, segment); this->currentCluster.reset(); // free Cluster object here } void MuxerPrivate::ProcessClusters(bool , bool , unsigned long long ts) { int64 delta = ts - this->max_ts; if (delta > 0) { this->max_ts = ts; } assert(this->currentCluster); int64 TimecodeDelay = (int64(ts) - int64(this->currentCluster->GlobalTimecode())) / cTimecodeScale; if (TimecodeDelay > 32767) { CloseCurrentCluster(); CreateNewCluster(ts); } } void MuxerPrivate::UpdateDuration() { assert(this->kaxDuration); uint64 kaxDurationPos = this->kaxDuration->GetElementPosition(); uint64 prev = this->file.getFilePointer(); this->file.setFilePointer(kaxDurationPos, seek_beginning); float duration = this->max_ts / cTimecodeScale; *(static_cast<EbmlFloat *>(this->kaxDuration)) = duration; this->kaxDuration->Render(this->file, false, true); this->file.setFilePointer(prev, seek_beginning); }
[ "asyvrachev@zingaya.com" ]
asyvrachev@zingaya.com
317e6a002eb2c1f62031597212a3664972a071e1
7b1213d2de5a720e208f7d7ca6ed7f0fa92c2622
/Model/Mpd/mpd.cpp
e240948769d03642c01aa6b94e0d8ab6732f289e
[]
no_license
martakuzak/MP4_2
cfd3474f1e4c68d4b40931bfe2665eaf2f18ee98
661dc380087c9c5d9bb680daa2398a12e9c1f063
refs/heads/master
2021-01-21T04:37:43.259965
2016-01-17T23:22:29
2016-01-17T23:22:29
15,295,860
0
0
null
null
null
null
UTF-8
C++
false
false
16,575
cpp
#include "mpd.h" ProgramInformation::ProgramInformation() { lang = ""; moreInformationURL = ""; title = ""; source = ""; copyright = ""; } /////////////////////////////////////////////////////////////////////////////////////////// QString ProgramInformation::getLang() const { return lang; } /////////////////////////////////////////////////////////////////////////////////////////// void ProgramInformation::setLang(const QString &value) { lang = value; } /////////////////////////////////////////////////////////////////////////////////////////// QString ProgramInformation::getCopyright() const { return copyright; } /////////////////////////////////////////////////////////////////////////////////////////// void ProgramInformation::setCopyright(const QString &value) { copyright = value; } /////////////////////////////////////////////////////////////////////////////////////////// QString ProgramInformation::getSource() const{ return source; } /////////////////////////////////////////////////////////////////////////////////////////// void ProgramInformation::setSource(const QString &value){ source = value; } /////////////////////////////////////////////////////////////////////////////////////////// QString ProgramInformation::getTitle() const { return title; } /////////////////////////////////////////////////////////////////////////////////////////// void ProgramInformation::setTitle(const QString &value) { title = value; } /////////////////////////////////////////////////////////////////////////////////////////// QString ProgramInformation::getMoreInformationURL() const { return moreInformationURL; } /////////////////////////////////////////////////////////////////////////////////////////// void ProgramInformation::setMoreInformationURL(const QString &value){ moreInformationURL = value; } /////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////// MPD::MPD() { type = ""; xmlns = ""; minBufferTime = ""; mediaPresentationDuration = ""; profiles = ""; baseURL = NULL; } ////////////////////////////////////////////////////////////////////////////////////////// BaseURL *MPD::getBaseURL() const { return baseURL; } ////////////////////////////////////////////////////////////////////////////////////////// void MPD::setBaseURL(const QString& url){ baseURL = new BaseURL(); baseURL->setContent(url); } /////////////////////////////////////////////////////////////////////////////////////////// void MPD::addPeriod() { Period *period = new Period(); period->setStart(QString("PT0S")); periods.append(period); } /////////////////////////////////////////////////////////////////////////////////////////// void MPD::addPeriod(Period *period) { periods.append(period); } /////////////////////////////////////////////////////////////////////////////////////////// QString MPD::getProfiles() const { return profiles; } /////////////////////////////////////////////////////////////////////////////////////////// void MPD::setProfiles(const QString &value) { profiles = value; } /////////////////////////////////////////////////////////////////////////////////////////// QString MPD::getMediaPresentationDuration() const { return mediaPresentationDuration; } /////////////////////////////////////////////////////////////////////////////////////////// void MPD::setMediaPresentationDuration(const QString &value) { mediaPresentationDuration = value; } /////////////////////////////////////////////////////////////////////////////////////////// QString MPD::getMinBufferTime() const { return minBufferTime; } /////////////////////////////////////////////////////////////////////////////////////////// void MPD::setMinBufferTime(const QString &value) { minBufferTime = value; } /////////////////////////////////////////////////////////////////////////////////////////// QString MPD::getXmlns() const { return xmlns; } /////////////////////////////////////////////////////////////////////////////////////////// void MPD::setXmlns(const QString &value) { xmlns = value; } /////////////////////////////////////////////////////////////////////////////////////////// QString MPD::getType() const { return type; } /////////////////////////////////////////////////////////////////////////////////////////// void MPD::setType(const QString &value) { type = value; } //////////// QList<Period *> MPD::getPeriods() const{ return periods; } void MPD::setPeriods(const QList<Period*> &value){ periods = value; } /////////////////////////////////////////////////////////////////////////////////////////// void MPD::write(QXmlStreamWriter *stream ) { stream->writeStartElement("MPD"); if(type.size()) stream->writeAttribute("type", type); if(xmlns.size()) stream->writeAttribute("xmlns", xmlns); if(minBufferTime.size()) stream->writeAttribute("minBufferTime", minBufferTime); if(profiles.size()) stream->writeAttribute("profiles", profiles); if(mediaPresentationDuration.size()) stream->writeAttribute("mediaPresentationDuration", mediaPresentationDuration); if(baseURL != NULL) baseURL->write(stream); if(periods.size()) { int size = periods.size(); for(int i = 0; i < size; ++i) { periods.at(i)->write(stream); } } stream->writeEndElement(); } /////////////////////////////////////////////////////////////////////////////////////////// QString MPDWriter::getDuration() { QList<std::shared_ptr <Box> > mvhds = originalModel->getBoxes("mvhd"); if(mvhds.empty()) return QString(""); MovieHeaderBox *mvhd = dynamic_cast <MovieHeaderBox*> (mvhds.back().get()); unsigned long int timescale = mvhd->getTimeScale(); unsigned long int duration = mvhd->getDuration(); return getHMSFormat(duration/timescale); } /////////////////////////////////////////////////////////////////////////////////////////// unsigned int *MPDWriter::getDimensions() { unsigned int *ret = new unsigned int[2]; QList<std::shared_ptr <Box> > visualEntries = originalModel->getBoxes("avc1"); if(visualEntries.empty()) { visualEntries = originalModel->getBoxes("mp4v"); if(visualEntries.empty()) { QList<std::shared_ptr <Box> > a = originalModel->getBoxes("ftyp"); ret[0] = 0; ret[1] = 0; return ret; } } std::shared_ptr <Box> visualEntry = visualEntries.at(0); VisualSampleEntry *as = dynamic_cast <VisualSampleEntry*> (visualEntries.at(0).get()); ret[0] = as->getHeight(); ret[1] = as->getWidth(); return ret; } /////////////////////////////////////////////////////////////////////////////////////////// QString MPDWriter::getHMSFormat(const double& value) { double durationInSec = value; unsigned int hours = durationInSec/3600; durationInSec -= 3600*hours; unsigned int minutes = durationInSec/60; durationInSec -= 60*minutes; return QString("PT" + QString::number(hours) + "H" + QString::number(minutes) + "M" + QString::number(durationInSec) + "S"); } /////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////// MPDWriter::MPDWriter() { dashPath = ""; dashModel = NULL; originalModel = NULL; originalFileName = ""; mpd = NULL; } /////////////////////////////////////////////////////////////////////////////////////////// void MPDWriter::init(bool oneFile) { if(oneFile) { FileService *fileService = new FileService(dashPath + "/dash_" + originalFileName); dashModel = new TreeModel(fileService); return; } FileService *fileService = new FileService(dashPath + "/dash_init_" + originalFileName); dashModel = new TreeModel(fileService); } /////////////////////////////////////////////////////////////////////////////////////////// void MPDWriter::setMPD(const QString &url) { //MPD mpd = new MPD(); //mpd->setId(unisgned int); //nieobowiazkowe, poza tym bedzie jedno mpd, wiec bez tego mpd->setProfiles(QString("urn:mpeg:dash:profile:full:2011")); //obowiązkowe; urn:mpeg:dash:profil:isoff-main:2011? mpd->setType("static"); //static jest domyślne, dynamic (MPD może być zmieniane); typowo dynamic przy live streamach //mpd->setAvailibilityStartTime(); //obowiazkowe przy dynamic //mpd->setAvailibilityEndTime(); //nieobowiazkowe mpd->setMediaPresentationDuration(getDuration()); //obowiazkowe dla static //mpd->setMinimumUpdatePeriod(); //w static zakazane mpd->setMinBufferTime("PT1.500000S"); //obowiązkowe - jak to ustawić? //mpd->getTimeShitBufferDepth(); //w staticu zbędne //mpd->getSuggestedPresentationDelay();//w staticu ignorowane //mpd->getMaxSegmentDuration(); //nieobowiązkowe //mpd->getMaxSubsegmentDuration(); //nieobowiązkowe mpd->addPeriod(setPeriod()); mpd->setBaseURL(url); } /////////////////////////////////////////////////////////////////////////////////////////// void MPDWriter::writeMPD(const QString &url) { QString mpdName = originalFileName; mpdName.replace(".mp4", ".mpd"); QFile *mpdFile = new QFile(dashPath + "/" + mpdName); if(mpdFile->open(QIODevice::ReadWrite)) { setMPD(url); QXmlStreamWriter *stream = new QXmlStreamWriter(mpdFile); stream->setAutoFormatting(true); stream->writeStartDocument(); mpd->write(stream); stream->writeEndDocument(); } mpdFile->close(); } /////////////////////////////////////////////////////////////////////////////////////////// AdaptationSet *MPDWriter::setAdaptationSet() { AdaptationSet *adapt = new AdaptationSet(); adapt->addRepresentations(representations); return adapt; } /////////////////////////////////////////////////////////////////////////////////////////// Period *MPDWriter::setPeriod() { Period *period = new Period(); period->setStart(QString("PT0S")); period->setDuration(getDuration()); period->addAdaptationSet(setAdaptationSet()); return period; } //////////////////////////////////////////////////////////////////////////////////////////// QString MPDWriter::getOriginalFileName() const { return originalFileName; } /////////////////////////////////////////////////////////////////////////////////////////// void MPDWriter::setOriginalFileName(const QString &value) { originalFileName = value; } /////////////////////////////////////////////////////////////////////////////////////////// void MPDWriter::addRepresentation(const QString& path, const QString& fn, const bool& oneFile) { FileService *fileService = new FileService(path + fn); //Analyzer *an = new Analyzer(fileService); originalModel = new TreeModel(fileService); Representation *repr = new Representation(); QString dashName; if(oneFile) dashName = "dash_" + fn; else dashName = "dash_init_" + fn; BaseURL *baseURL = new BaseURL(); baseURL->setContent(dashPath + "/" + dashName); //repr->setBaseurl(baseURL); //if(!segmentList) { SegmentBase *segmentBase = new SegmentBase(); Initialization *init = new Initialization(); QList< std::shared_ptr<Box> > sidxs = dashModel->getBoxes("sidx"); if(oneFile) { init->setRange(QString::number(0) + "-" + QString::number(sidxs.back()->getOffset() - 1)); init->setSourceURL(dashName); segmentBase->setInitialization(init); } else { init->setSourceURL(dashName); //setting initalization segmentBase->setInitialization(init); } repr->setSegmentBase(segmentBase); //} SegmentList *slist = setSegmentList(oneFile, dashName); repr->setBandwidth(getRepBandwidth(oneFile, slist)); repr->setSegmentList(slist); unsigned int *dim = getDimensions(); repr->setHeight(dim[0]); repr->setWidth(dim[1]); repr->setMimeType("video/mp4"); repr->setStartWithSAP(1); representations.append(repr); } /////////////////////////////////////////////////////////////////////////////////////////// void MPDWriter::setDashPath(const QString &dPath) { dashPath = dPath; } /////////////////////////////////////////////////////////////////////////////////////////// unsigned int MPDWriter::getRepBandwidth(bool oneFile, /*const QString &dashName, */SegmentList *slist) { unsigned int mediaSize = 0; QList<std::shared_ptr<Box>> mvhds = originalModel->getBoxes("mvhd"); MovieHeaderBox *mvhd = dynamic_cast <MovieHeaderBox*> (mvhds.back().get()); unsigned long int duration = mvhd->getDuration(); unsigned long int timescale = mvhd->getTimeScale(); unsigned long time = duration/timescale; if(oneFile) { SegmentURL *first = slist->getSegmentURL(0); SegmentURL *last = slist->getSegmentURL(-1); QString firstRange = first->getMediaRange(); QString lastRange = last->getMediaRange(); int flast = firstRange.lastIndexOf("-"); unsigned int firstID = firstRange.mid(0, flast).toInt(); int llast = lastRange.lastIndexOf("-"); unsigned int lastID = lastRange.mid(llast + 1).toInt(); mediaSize = lastID - firstID; } else { unsigned int index = 0; QString str("dash_" + QString::number(index) + "_" + originalFileName + "s"); while(QFile(dashPath + "/" + str).exists()) {//setting SegmentList QFile *segment = new QFile(dashPath + "/" +str); mediaSize += segment->size(); ++ index; str = QString("dash_" + QString::number(index) + "_" + originalFileName + "s"); } } if(duration == 0) return 0; return (8*mediaSize)/time; } /////////////////////////////////////////////////////////////////////////////////////////// SegmentList *MPDWriter::setSegmentList(bool oneFile, const QString& dashName) { SegmentList *slist = new SegmentList(); Initialization *init = new Initialization(); if(oneFile) { QList< std::shared_ptr<Box> > mdats = dashModel->getBoxes("mdat"); QList< std::shared_ptr<Box> > sidxs = dashModel->getBoxes("sidx"); init->setRange(QString::number(0) + "-" + QString::number(sidxs.back()->getOffset() - 1)); init->setSourceURL(dashName); slist->setInitialization(init); while(!sidxs.empty()) { if(sidxs.size() == 1) { std::shared_ptr<Box> sidx = sidxs.back(); std::shared_ptr<Box> mdat = mdats.front(); unsigned int firstMediaRange = sidx->getOffset(); unsigned int secondMediaRange = mdat->getOffset() + mdat->getSize() - 1; QString mediaRange(QString::number(firstMediaRange) + "-" + QString::number(secondMediaRange)); unsigned int secondIndexRange = sidx->getOffset() + sidx->getSize() - 1; QString indexRange(QString::number(firstMediaRange) + "-" + QString::number(secondIndexRange)); slist->addSegmentURL(mediaRange, indexRange, dashName); sidxs.pop_back(); } else { std::shared_ptr<Box> sidx1 = sidxs.back(); sidxs.pop_back(); std::shared_ptr<Box> sidx2 = sidxs.back(); unsigned int firstMediaRange = sidx1->getOffset(); unsigned int secondMediaRange = sidx2->getOffset() - 1; QString mediaRange(QString::number(firstMediaRange) + "-" + QString::number(secondMediaRange)); unsigned int secondIndexRange = sidx1->getOffset() + sidx1->getSize() - 1; QString indexRange(QString::number(firstMediaRange) + "-" + QString::number(secondIndexRange)); slist->addSegmentURL(mediaRange, indexRange, dashName); } } } else { init->setSourceURL(dashName); //setting initalization slist->setInitialization(init); unsigned int index = 0; QString str("dash_" + QString::number(index) + "_" + originalFileName + "s"); while(QFile(dashPath + "/" + str).exists()) {//setting SegmentList slist->addSegmentURL(str); ++ index; str = QString("dash_" + QString::number(index) + "_" + originalFileName + "s"); } } return slist; }
[ "marta.kuzak@gmail.com" ]
marta.kuzak@gmail.com
40863568d24809bbea83069bf9e1ec92bda3664a
aacb4d5ee82ac6ef7f57806bfdc26d6a2fb17c29
/benchmark/src/msgpack11-unpack.cpp
deb628d44bb0206b59a2a98f726472a764f97fca
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
ar90n/msgpack11
891bf944b2c7e769bc41edbb9678279b291b44d3
aa0cc8a00ddb7752b9455b25e47db9b0fab7fd60
refs/heads/master
2023-01-19T16:56:19.614451
2023-01-08T03:04:51
2023-01-08T03:04:51
66,201,217
122
32
MIT
2023-01-08T03:04:52
2016-08-21T13:51:19
C++
UTF-8
C++
false
false
4,763
cpp
/* * Copyright (c) 2016 Nicholas Fraser * * 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 "benchmark.h" #include "msgpack11.hpp" #include <algorithm> #include <iostream> static char* file_data; static size_t file_size; static uint32_t hash_object(const msgpack11::MsgPack& pack, uint32_t hash) { switch (pack.type()) { case msgpack11::MsgPack::NUL: return hash_nil(hash); case msgpack11::MsgPack::BOOL: return hash_bool(hash, pack.bool_value()); case msgpack11::MsgPack::FLOAT32: return hash_double(hash, pack.float32_value()); case msgpack11::MsgPack::FLOAT64: return hash_double(hash, pack.float64_value()); case msgpack11::MsgPack::INT8: return hash_i64(hash, pack.int8_value()); case msgpack11::MsgPack::INT16: return hash_i64(hash, pack.int16_value()); case msgpack11::MsgPack::INT32: return hash_i64(hash, pack.int32_value()); case msgpack11::MsgPack::INT64: return hash_i64(hash, pack.int64_value()); case msgpack11::MsgPack::UINT8: return hash_u64(hash, pack.uint8_value()); case msgpack11::MsgPack::UINT16: return hash_u64(hash, pack.uint16_value()); case msgpack11::MsgPack::UINT32: return hash_u64(hash, pack.uint32_value()); case msgpack11::MsgPack::UINT64: return hash_u64(hash, pack.uint64_value()); case msgpack11::MsgPack::STRING: { std::string const& str = pack.string_value(); return hash_str(hash, str.c_str(), str.size()); } case msgpack11::MsgPack::ARRAY: { msgpack11::MsgPack::array const& items = pack.array_items(); std::for_each(items.begin(), items.end(), [&hash](msgpack11::MsgPack const& item) { hash = hash_object( item, hash ); }); return hash_u32(hash, items.size()); } case msgpack11::MsgPack::OBJECT: { msgpack11::MsgPack::object const& items = pack.object_items(); std::for_each(items.begin(), items.end(), [&hash]( std::pair< msgpack11::MsgPack, msgpack11::MsgPack > const& item) { msgpack11::MsgPack const& key = item.first; msgpack11::MsgPack const& value = item.second; assert(key.type() == msgpack11::MsgPack::STRING); std::string const& key_str = key.string_value(); hash = hash_str(hash, key_str.c_str(), key_str.size()); hash = hash_object(value, hash); }); return hash_u32(hash, items.size()); } default: break; } throw std::runtime_error(""); } bool run_test(uint32_t* hash_out) { char* data = benchmark_in_situ_copy(file_data, file_size); if (!data) return false; try { std::string err; msgpack11::MsgPack pack = msgpack11::MsgPack::parse(data, file_size, err); *hash_out = hash_object(pack, *hash_out); } catch (...) { benchmark_in_situ_free(data); return false; } benchmark_in_situ_free(data); return true; } bool setup_test(size_t object_size) { file_data = load_data_file(BENCHMARK_FORMAT_MESSAGEPACK, object_size, &file_size); if (!file_data) return false; return true; } void teardown_test(void) { free(file_data); } bool is_benchmark(void) { return true; } const char* test_version(void) { return "0.0.9"; } const char* test_language(void) { return BENCHMARK_LANGUAGE_CXX; } const char* test_format(void) { return "MessagePack"; } const char* test_filename(void) { return __FILE__; }
[ "argon.argon.argon@gmail.com" ]
argon.argon.argon@gmail.com
3ef4fe04632aae9c53dd0402f2fe0ead697e6fa8
39b8aecb95c505ae2a39f0736812d4f8b40f2638
/done/8182.cpp
370d7e343685d4a7d34aadfacdeae1bacbfb591b
[]
no_license
koosaga/BOJ-spj
8c6109eb0010144b272ab05a613fa897253275e8
9fa561f1bd4270102df5a2cbfb3c627f21b54f10
refs/heads/master
2020-04-02T16:49:39.728270
2018-10-25T07:51:23
2018-10-25T07:51:23
154,630,508
1
1
null
2018-10-25T07:46:16
2018-10-25T07:46:15
null
WINDOWS-1250
C++
false
false
1,821
cpp
/************************************************************************* * * * XVI Olimpiada Informatyczna * * * * Zadanie: Wyspa (WYS) * * Plik: wyschk.cpp * * Autor: Pawel Parys * * Opis: Sprawdzarka poprawnosci wyjsc. * * * *************************************************************************/ #include <assert.h> #include <cstdio> #include <cctype> #include <cstdlib> #include <cmath> #include <cstring> #include <algorithm> #define REP(a,n) for (int a=0; a<(n); ++a) #define FOR(a,b,c) for (int a=(b); a<=(c); ++a) using namespace std; void error(const char *str) { assert(0); printf("WRONG (line 1): %s\n", str); exit(1); } int main(int argc, char **argv) { if (argc!=4) { fprintf(stderr, "Potrzebuję trzech argumentów!!!\n"); return -1; } FILE *fin = fopen(argv[1], "r"); FILE *foutgr = fopen(argv[3], "r"); FILE *foutok = fopen(argv[2], "r"); if (fin==NULL || foutgr==NULL || foutok==NULL) { fprintf(stderr, "Nie umiem otworzyć plików!!!\n"); return -2; } double wyn_ok, wyn_gr; fscanf(foutok, "%lf", &wyn_ok); int ile = fscanf(foutgr, "%lf ", &wyn_gr); if (ile<1) error("Brak liczby"); ile = fscanf(foutgr, "%*c"); // zwraca -1 jak koniec pliku, wpp. 0 (wczesniej wczytalismy spacje i \n) if (ile>=0) error("Smieci na koncu pliku"); if (fabs(wyn_ok-wyn_gr)>=0.00001) error("Nieprawidlowy wynik"); printf("OK\n"); }
[ "koosaga@gmail.com" ]
koosaga@gmail.com
ee9a2b99dadd846788c0c0afc95bbb99a8d5db71
e2c6101d2f7ff6ff07b3b33cb3581841db8b04e7
/TestBed/Src/Demos/Demo.h
4ca45a05c7ac012bc93ffe89efc4d72aa3d4fc3b
[]
no_license
PC88/Testbed
566e7d541690b92bc99371d9a532de481947db24
5012a18ed25cb1203c05239d895e970040da4658
refs/heads/master
2020-05-31T02:36:59.306178
2019-08-22T08:13:13
2019-08-22T08:13:13
190,069,218
0
0
null
null
null
null
UTF-8
C++
false
false
873
h
#pragma once #include "Demos\DemoSettings.h" class Demo { public: Demo(); virtual ~Demo(); // methods are not pure virtual as they are intended to be non-necessity. virtual void ImGuiRender() {}; // Interface for rendering UI on each of the demos virtual void Update(double interval) {}; // typical update method pattern. virtual void Render() {}; // Rendering call for non UI elements virtual void Step(Settings* settings) {}; // this is a method emulated from B2D`s architecture serving to allow separate settings for each Demo virtual void Box2DStart() {}; // deals with box2D construction on a per demo basis virtual void Box2DEnd() {}; // deals with destruction on a per demo basis Settings m_settings; // the settings for each demo };
[ "32823980+PC88@users.noreply.github.com" ]
32823980+PC88@users.noreply.github.com
a9f9b70b52ef03ef35fdb67d87e0c2927646767b
5a05acb4caae7d8eb6ab4731dcda528e2696b093
/ThirdParty/luabind/luabind/detail/link_compatibility.hpp
e57eea229e0b1111720509226e4b276f0a3c3895
[]
no_license
andreparker/spiralengine
aea8b22491aaae4c14f1cdb20f5407a4fb725922
36a4942045f49a7255004ec968b188f8088758f4
refs/heads/master
2021-01-22T12:12:39.066832
2010-05-07T00:02:31
2010-05-07T00:02:31
33,547,546
0
0
null
null
null
null
UTF-8
C++
false
false
1,990
hpp
// Copyright (c) 2003 Daniel Wallin and Arvid Norberg // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF // ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED // TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A // PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT // SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR // ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN // ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE // OR OTHER DEALINGS IN THE SOFTWARE. #ifndef LUABIND_LINK_COMPATIBILITY_HPP_INCLUDED #define LUABIND_LINK_COMPATIBILITY_HPP_INCLUDED #include <luabind/config.hpp> namespace luabind { namespace detail { #ifdef LUABIND_NOT_THREADSAFE LUABIND_API void not_threadsafe_defined_conflict(); #else LUABIND_API void not_threadsafe_not_defined_conflict(); #endif #ifdef LUABIND_NO_ERROR_CHECKING LUABIND_API void no_error_checking_defined_conflict(); #else LUABIND_API void no_error_checking_not_defined_conflict(); #endif inline void check_link_compatibility() { #ifdef LUABIND_NOT_THREADSAFE not_threadsafe_defined_conflict(); #else not_threadsafe_not_defined_conflict(); #endif #ifdef LUABIND_NO_ERROR_CHECKING no_error_checking_defined_conflict(); #else no_error_checking_not_defined_conflict(); #endif } } } #endif
[ "DreLnBrown@e933ee44-1dc6-11de-9e56-bf19dc6c588e" ]
DreLnBrown@e933ee44-1dc6-11de-9e56-bf19dc6c588e
1d7147476094a4c24106d6411bb419b1fa60dd5d
ea986ad1a730e3542f1b96f94243f004f579521c
/DbTables/inc/ValGroupLists.hh
c48a3e0d112a53408bc61413349bd9701049e2b8
[ "Apache-2.0" ]
permissive
ryuwd/Offline
563bae791323433cae9a18a365c8f7e8515c47f6
92957f111425910274df61dbcbd2bad76885f993
refs/heads/master
2021-12-26T03:29:04.037885
2021-08-19T16:18:39
2021-08-19T16:18:39
219,497,442
0
0
Apache-2.0
2021-08-19T19:26:45
2019-11-04T12:33:46
C++
UTF-8
C++
false
false
1,330
hh
#ifndef DbTables_ValGroupLists_hh #define DbTables_ValGroupLists_hh #include <string> #include <iomanip> #include <sstream> #include <map> #include "Offline/DbTables/inc/DbTable.hh" namespace mu2e { class ValGroupLists : public DbTable { public: class Row { public: Row(int gid, int iid): _gid(gid),_iid(iid) {} int gid() const { return _gid;} int iid() const { return _iid;} private: int _gid; int _iid; }; constexpr static const char* cxname = "ValGroupLists"; ValGroupLists():DbTable(cxname,"val.grouplists","gid,iid") {} const Row& rowAt(const std::size_t index) const { return _rows.at(index);} std::vector<Row> const& rows() const {return _rows;} std::size_t nrow() const override { return _rows.size(); }; size_t size() const override { return baseSize() + sizeof(this) + nrow()*8; }; void addRow(const std::vector<std::string>& columns) override { _rows.emplace_back(std::stoi(columns[0]),std::stoi(columns[1])); } void rowToCsv(std::ostringstream& sstream, std::size_t irow) const override { Row const& r = _rows.at(irow); sstream << r.gid()<<","; sstream << r.iid(); } virtual void clear() override { baseClear(); _rows.clear(); } private: std::vector<Row> _rows; }; }; #endif
[ "rlc@fnal.gov" ]
rlc@fnal.gov
79a46434136ff5b66efc69b04877d5e7fb774ab7
d3bf068ac90138457dd23649736f95a8793c33ae
/AutoPFA/dlgpipemodel.cpp
dadbb368c845e9a92f8ea34ca8928f3db50d1834
[]
no_license
xxxmen/uesoft-AutoPFA
cab49bfaadf716de56fef8e9411c070a4b1585bc
f9169e203d3dc3f2fd77cde39c0bb9b4bdf350a6
refs/heads/master
2020-03-13T03:38:50.244880
2013-11-12T05:52:34
2013-11-12T05:52:34
130,947,910
1
2
null
null
null
null
GB18030
C++
false
false
11,713
cpp
// dlgpipemodel.cpp : implementation file // #pragma once #include "stdafx.h" #include "autopfa.h" #include "dlgpipemodel.h" #include "ComponentManager.h" #include "MainFrm.h" #include "ChildFrm.h" #include "ADOConnection.h" #include "GetPropertyofMaterial2.h" #include "Fuild.h" #include "ResourcePathManager.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // DlgPipeModel dialog DlgPipeModel::DlgPipeModel(UnitSubSystem &UnitSys,ComponentManager &manager,CWnd* pParent /*=NULL*/) : BaseDlg(DlgPipeModel::IDD, pParent) ,m_UnitSys(UnitSys) ,m_manager(manager) ,m_cmbLenUnit(&m_EditLen) ,m_cmbWaveUnit(&m_EditWave) ,m_cmbElaticity(&m_EditElastic) ,m_cmbInDiaUnit(&m_EditInDia) ,m_cmbThick(&m_EditThick) ,m_cmbFriction(&m_EditFriction) { //{{AFX_DATA_INIT(DlgPipeModel) m_strInDiaUnit = _T(""); m_strLenUnit = _T(""); m_strWaveUnit = _T(""); m_strInDia = _T(""); m_strLen = _T(""); m_strWave = _T(""); m_strElasticityUnit = _T(""); m_strThickUnit = _T(""); m_strType = _T(""); m_strC1 = _T(""); m_strElasticity = _T(""); m_strFrictionUnit = _T(""); m_strFriction = _T(""); m_strInDiaReduce = _T(""); m_strPossionRatio = _T(""); m_strThick = _T(""); m_bCalcWave = 0; m_strMaterial = _T(""); m_strSize = _T(""); //}}AFX_DATA_INIT m_support = 1; m_frictionModel = 0; } void DlgPipeModel::DoDataExchange(CDataExchange* pDX) { BaseDlg::DoDataExchange(pDX); //{{AFX_DATA_MAP(DlgPipeModel) DDX_Control(pDX, IDC_EFRICTION, m_EditFriction); DDX_Control(pDX, IDC_EELASTICITY, m_EditElastic); DDX_Control(pDX, IDC_EINDIA, m_EditInDia); DDX_Control(pDX, IDC_ELEN, m_EditLen); DDX_Control(pDX, IDC_EPOISSONRATIO, m_EditPossion); DDX_Control(pDX, IDC_ETHICK, m_EditThick); DDX_Control(pDX, IDC_EWAVE, m_EditWave); DDX_Control(pDX, IDC_EC1, m_EditC1); DDX_Control(pDX, IDC_CMBLOSSTYPE, m_cmbLossType); DDX_Control(pDX, IDC_CMBTYPE, m_cmbType); DDX_Control(pDX, IDC_CMBTHICK, m_cmbThick); DDX_Control(pDX, IDC_CMBSUPPORT, m_cmbSupport); DDX_Control(pDX, IDC_CMBSIZE, m_cmbSize); DDX_Control(pDX, IDC_CMBMATIRAIL, m_cmbMaterail); DDX_Control(pDX, IDC_CMBFRICTIONUNIT, m_cmbFriction); DDX_Control(pDX, IDC_CMBELASTICITY, m_cmbElaticity); DDX_Control(pDX, IDC_CMBWAVEUNIT, m_cmbWaveUnit); DDX_Control(pDX, IDC_CMBLENUNIT, m_cmbLenUnit); DDX_Control(pDX, IDC_CMBINDIAUNIT, m_cmbInDiaUnit); DDX_CBString(pDX, IDC_CMBINDIAUNIT, m_strInDiaUnit); DDX_CBString(pDX, IDC_CMBLENUNIT, m_strLenUnit); DDX_CBString(pDX, IDC_CMBWAVEUNIT, m_strWaveUnit); DDX_Text(pDX, IDC_EINDIA, m_strInDia); DDX_Text(pDX, IDC_ELEN, m_strLen); DDX_Text(pDX, IDC_EWAVE, m_strWave); DDX_CBString(pDX, IDC_CMBELASTICITY, m_strElasticityUnit); DDX_CBString(pDX, IDC_CMBTHICK, m_strThickUnit); DDX_CBString(pDX, IDC_CMBTYPE, m_strType); DDX_Text(pDX, IDC_EC1, m_strC1); DDX_Text(pDX, IDC_EELASTICITY, m_strElasticity); DDX_CBString(pDX, IDC_CMBFRICTIONUNIT, m_strFrictionUnit); DDX_Text(pDX, IDC_EFRICTION, m_strFriction); DDX_Text(pDX, IDC_EIDREDUCE, m_strInDiaReduce); DDX_Text(pDX, IDC_EPOISSONRATIO, m_strPossionRatio); DDX_Text(pDX, IDC_ETHICK, m_strThick); DDX_Radio(pDX, IDC_RADIOASSIGN, m_bCalcWave); DDX_CBString(pDX, IDC_CMBMATIRAIL, m_strMaterial); DDX_CBString(pDX, IDC_CMBSIZE, m_strSize); //}}AFX_DATA_MAP DDX_Control(pDX, IDC_STATIC1, m_ThickControl); DDX_Control(pDX, IDC_STATIC2, m_ElasticityControl); DDX_Control(pDX, IDC_STATIC3, m_PossinControl); } BEGIN_MESSAGE_MAP(DlgPipeModel, BaseDlg) //{{AFX_MSG_MAP(DlgPipeModel) ON_BN_CLICKED(IDC_RADIOASSIGN, OnRadioAssign) ON_BN_CLICKED(IDC_RADIOCALC, OnRadioCalc) ON_CBN_SELCHANGE(IDC_CMBSUPPORT, OnSelchangeSupport) ON_CBN_SELCHANGE(IDC_CMBLOSSTYPE, OnSelchangeLoss) ON_CBN_SELCHANGE(IDC_CMBMATIRAIL, OnSelchangeMatirail) ON_EN_CHANGE(IDC_EC1, OnChangeC1) //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // DlgPipeModel message handlers GetPropertyofMaterial material; void DlgPipeModel::Init() { ADOConnection m_ado; ADORecordSetPtr pRs; _RecordsetPtr _pRs; CString strFile,strSql; strSql = "SELECT Material FROM MaterialNameText"; strFile = ResourcePathManager::Instance().GetOldSoftShareDbPath(); if( strFile.IsEmpty() ) return ; strFile.TrimRight( _T( "\\" ) ); strFile += _T("\\MaterialName.mdb"); m_ado.Open(strFile); pRs = m_ado.ExecuteSelectSQL(strSql); for ( pRs->MoveFirst(); !pRs->IsEOF(); pRs->MoveNext() ) { CString strname = pRs->GetString(_T("Material")); m_cmbMaterail.AddString(strname); } strFile.Empty(); strSql.Empty(); m_strMaterial = Pipe::ms_Material.GetValue(); m_strSize = Pipe::ms_Size.GetValue(); m_strType = Pipe::ms_PipeType.GetValue(); InitNum(m_strInDia,m_strInDiaUnit,Pipe::ms_InDia); InitNum(m_strThick,m_strThickUnit,Pipe::ms_Thick); InitNum(m_strElasticity,m_strElasticityUnit,Pipe::ms_Elasticity); m_strPossionRatio = Pipe::ms_PossionRatio.GetValue(); m_strInDiaReduce = Pipe::ms_InDiaReduce.GetValue(); InitNum(m_strLen,m_strLenUnit,Pipe::ms_Len); InitNum(m_strWave,m_strWaveUnit,Pipe::ms_WaveSpeed); m_bCalcWave = Pipe::ms_CalcWave.GetnValue(); m_support = Pipe::ms_SupportType.GetnValue(); m_strC1 = Pipe::ms_C1.GetValue(); m_frictionModel = Pipe::ms_LossType.GetnValue(); InitNum(m_strFriction,m_strFrictionUnit,Pipe::ms_Friction); InitDataCmb(Pipe::ms_supportTypeArray,8,m_cmbSupport,m_support); InitDataCmb(Pipe::ms_frictionModel,8,m_cmbLossType,m_frictionModel); SetControlStatus(); SetLossStatus(); UpdateData(FALSE); } void DlgPipeModel::UpData() { UpdateData(TRUE); Pipe::ms_Material.SetValue(m_strMaterial); Pipe::ms_Size.SetValue(m_strSize); Pipe::ms_PipeType.SetValue(m_strType); SetNum(m_strInDia,m_strInDiaUnit,Pipe::ms_InDia); SetNum(m_strThick,m_strThickUnit,Pipe::ms_Thick); SetNum(m_strElasticity,m_strElasticityUnit,Pipe::ms_Elasticity); Pipe::ms_PossionRatio.SetValue(m_strPossionRatio); Pipe::ms_InDiaReduce.SetValue(m_strInDiaReduce); SetNum(m_strLen,m_strLenUnit,Pipe::ms_Len); Pipe::ms_CalcWave.SetValue(m_bCalcWave); Pipe::ms_SupportType.SetValue(m_support); Pipe::ms_C1.SetValue(m_strC1); SetNum(m_strWave,m_strWaveUnit,Pipe::ms_WaveSpeed); Pipe::ms_LossType.SetValue(m_frictionModel); if(m_frictionModel != 0) m_strFrictionUnit.Empty(); SetNum(m_strFriction,m_strFrictionUnit,Pipe::ms_Friction); UpdateData(TRUE); } BOOL DlgPipeModel::OnInitDialog() { BaseDlg::OnInitDialog(); // TODO: Add extra initialization here InitUnitCbo(m_UnitSys,Diameter,m_cmbInDiaUnit,m_strInDiaUnit); InitUnitCbo(m_UnitSys,Diameter,m_cmbThick,m_strThickUnit); InitUnitCbo(m_UnitSys,Pressure,m_cmbElaticity,m_strElasticityUnit); InitUnitCbo(m_UnitSys,Length,m_cmbLenUnit,m_strLenUnit); InitUnitCbo(m_UnitSys,Velocity,m_cmbWaveUnit,m_strWaveUnit); InitUnitCbo(m_UnitSys,Diameter,m_cmbFriction,m_strFrictionUnit); //CMainFrame* pMainFrame = NULL; //pMainFrame = (CMainFrame*)AfxGetApp()->m_pMainWnd; //CMenu* pMenu = ((CWnd*)pMainFrame)->GetMenu(); //if( (pMenu->GetMenuState(ID_STEADYANALYSIS,MF_BYCOMMAND) == MF_CHECKED) ) //{ // if( (_ttoi(m_strWave) == 0) ) // { // m_strWave = _T( "1400" ); // m_strWaveUnit = _T( "meters/sec" ); // } // m_bCalcWave = 0; //} //SetControlStatus(); //SetLossStatus(); //UpdateData(FALSE); return TRUE; // return TRUE unless you set the focus to a control // EXCEPTION: OCX Property Pages should return FALSE } void DlgPipeModel::OnRadioAssign() { // TODO: Add your control notification handler code here // UpdateData(FALSE); m_bCalcWave = 0; SetControlStatus(); // m_cmbMaterail.GetLBText(m_cmbMaterail.GetCurSel(),m_strMaterial); UpdateData(TRUE); UpdateData(FALSE); } void DlgPipeModel::OnRadioCalc() { // TODO: Add your control notification handler code here // UpdateData(FALSE); m_bCalcWave = 1; OnSelchangeMatirail(); // CalcWaveSpeed(); SetControlStatus(); UpdateData(TRUE); UpdateData(FALSE); } void DlgPipeModel::SetControlStatus() { CEdit *pEdit = NULL; m_EditC1.SetReadOnly(!m_bCalcWave||m_support!=0); GetDlgItem(IDC_CMBSUPPORT)->EnableWindow(m_bCalcWave); m_EditWave.SetReadOnly(m_bCalcWave); m_EditThick.EnableWindow(m_bCalcWave); m_EditElastic.EnableWindow(m_bCalcWave); m_EditPossion.EnableWindow(m_bCalcWave); m_cmbElaticity.EnableWindow(m_bCalcWave); m_cmbThick.EnableWindow(m_bCalcWave); m_PossinControl.EnableWindow(m_bCalcWave); m_ElasticityControl.EnableWindow(m_bCalcWave); m_ThickControl.EnableWindow(m_bCalcWave); //m_cmbInDiaUnit.EnableWindow(m_bCalcWave); } void DlgPipeModel::OnSelchangeSupport() { // TODO: Add your control notification handler code here int Index = m_cmbSupport.GetCurSel(); if(CB_ERR == Index) return; m_support = m_cmbSupport.GetItemData(Index); m_EditC1.SetReadOnly(m_support!=0); CalcWaveSpeed(); m_strWave = Pipe::ms_WaveSpeed.GetValue(); } void DlgPipeModel::OnSelchangeLoss() { // TODO: Add your control notification handler code here int Index = m_cmbLossType.GetCurSel(); if(CB_ERR == Index) return; m_frictionModel = m_cmbLossType.GetItemData(Index); SetLossStatus(); } void DlgPipeModel::OnSelchangeMatirail() { UpdateData(TRUE); if (m_bCalcWave == 1) { ADOConnection m_ado; CString strFile,strsql,materialname; Fuild *fluid; double Et = 0; double m_temp = 0; double fPoissons = 0; strFile = ResourcePathManager::Instance().GetOldSoftShareDbPath(); if( strFile.IsEmpty() ) return ; strFile.TrimRight( _T( "\\" ) ); strFile += _T("\\Material.mdb"); //str = "E:\\AutoPDMS2.0\\开发文档\\数据库模板\\Material.mdb"; m_ado.Open(strFile); m_ado.GetConnectionptr( material.m_pMaterialCon ); fluid = m_manager.SysProperty().GetFuild(); m_temp = fluid->ms_Temperature.GetfValue(); int Index = m_cmbMaterail.GetCurSel(); if (CB_ERR == Index) return; m_cmbMaterail.GetLBText(m_cmbMaterail.GetCurSel(),materialname); m_strMaterial = materialname; Et = material.GetMaterialEt(materialname,m_temp,0); Et = Et * 1000; fPoissons = material.GetMaterialPoissons(materialname); m_strPossionRatio.Format(_T("%f"),fPoissons); m_strElasticity.Format(_T("%f"),Et); m_strElasticityUnit = _T("MPa"); } else return; UpdateData(FALSE); } BOOL DlgPipeModel::PreTranslateMessage(MSG* pMsg) { // TODO: Add your specialized code here and/or call the base class //屏蔽对话框的“按ESC和Enter键退出" if(WM_KEYDOWN == pMsg->message) { int nKey = (int) pMsg->wParam; if(VK_ESCAPE == nKey||VK_RETURN == nKey) return TRUE; } return BaseDlg::PreTranslateMessage(pMsg); } void DlgPipeModel::SetLossStatus() { switch(m_frictionModel) { case 0: m_cmbFriction.ShowWindow(SW_SHOW); m_EditFriction.ShowWindow(SW_SHOW); break; case 1: case 3: case 4: m_cmbFriction.ShowWindow(SW_HIDE); m_EditFriction.ShowWindow(SW_SHOW); m_strFrictionUnit.Empty(); break; default: m_cmbFriction.ShowWindow(SW_HIDE); m_EditFriction.ShowWindow(SW_HIDE); m_strFrictionUnit.Empty(); break; } InitUnitCbo(m_UnitSys,Diameter,m_cmbFriction,m_strFrictionUnit); } void DlgPipeModel::CalcWaveSpeed() { UpData(); Pipe::CalcWaveSpeed(m_manager.SysProperty().Density(),m_manager.SysProperty().BulkModulus()); Init(); } void DlgPipeModel::OnChangeC1() { // TODO: If this is a RICHEDIT control, the control will not // send this notification unless you override the CDialog::OnInitDialog() // function and call CRichEditCtrl().SetEventMask() // with the ENM_CHANGE flag ORed into the mask. // TODO: Add your control notification handler code here CalcWaveSpeed(); }
[ "uesoft@163.com" ]
uesoft@163.com
c1c0220b9e42475fa35d7fd758e9c082daaa4bdc
907fae0bf5de8ad40a1bb0b5da466fda0286be81
/src/runtime/vm/translator/hopt/ir.h
4ffa0de039bc7964b20a78ae9049377e04e7801e
[ "PHP-3.01", "Zend-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
Cutler-Mamba/hiphop-php
0f94a83c2a1a226b42cd50f4b6335c0073d13434
640cf62584bbd4a4ed2a581c8df37b8cd16ea69d
refs/heads/master
2021-05-27T19:25:48.425339
2012-10-10T23:45:15
2013-01-11T17:40:08
null
0
0
null
null
null
null
UTF-8
C++
false
false
52,470
h
/* +----------------------------------------------------------------------+ | HipHop for PHP | +----------------------------------------------------------------------+ | Copyright (c) 2010- Facebook, Inc. (http://www.facebook.com) | +----------------------------------------------------------------------+ | This source file is subject to version 3.01 of the PHP license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.php.net/license/3_01.txt | | If you did not receive a copy of the PHP license and are unable to | | obtain it through the world-wide-web, please send a note to | | license@php.net so we can mail you a copy immediately. | +----------------------------------------------------------------------+ */ #ifndef incl_HPHP_VM_IR_H_ #define incl_HPHP_VM_IR_H_ #include <algorithm> #include <cstdarg> #include <cinttypes> #include <iostream> #include <vector> #include <stack> #include <list> #include <cassert> #include <boost/noncopyable.hpp> #include <boost/checked_delete.hpp> #include "util/asm-x64.h" #include "runtime/ext/ext_continuation.h" #include "runtime/vm/translator/physreg.h" #include "runtime/vm/translator/abi-x64.h" #include "runtime/vm/translator/types.h" #include "runtime/vm/translator/runtime-type.h" #include "runtime/base/types.h" #include "runtime/vm/func.h" #include "runtime/vm/class.h" namespace HPHP { // forward declaration class StringData; namespace VM { namespace JIT { using namespace HPHP::VM::Transl; class FailedIRGen : public std::exception { public: const char* file; const int line; const char* func; FailedIRGen(const char* _file, int _line, const char* _func) : file(_file), line(_line), func(_func) { } }; // Flags to identify if a branch should go to a patchable jmp in astubs // happens when instructions have been moved off the main trace to the exit path. static const TCA kIRDirectJmpInactive = NULL; // Fixup Jcc;Jmp branches out of trace using REQ_BIND_JMPCC_FIRST/SECOND static const TCA kIRDirectJccJmpActive = (TCA)0x01; // Optimize Jcc exit from trace when fall through path stays in trace static const TCA kIRDirectJccActive = (TCA)0x02; // Optimize guard exit from beginning of trace static const TCA kIRDirectGuardActive = (TCA)0x03; #define PUNT(instr) do { \ throw FailedIRGen(__FILE__, __LINE__, #instr); \ } while(0) // XXX TODO: define another namespace for opcodes // TODO: Make sure the MayModRefs column is correct... (MayRaiseError too...) /* * Flags on opcodes. See ir.specification for details on the meaning * of these flags. */ enum OpcodeFlag : uint64_t { HasDest = 0x0001, CanCSE = 0x0002, Essential = 0x0004, MemEffects = 0x0008, CallsNative = 0x0010, ConsumesRC = 0x0020, ProducesRC = 0x0040, MayModifyRefs = 0x0080, Rematerializable = 0x0100, // TODO: implies HasDest MayRaiseError = 0x0200, }; #define IR_OPCODES \ /* checks */ \ OPC(GuardType, (HasDest|CanCSE|Essential)) \ OPC(GuardLoc, (Essential)) \ OPC(GuardStk, (Essential)) \ OPC(GuardRefs, (CanCSE|Essential)) \ \ /* arith ops (integer) */ \ OPC(OpAdd, (HasDest|CanCSE)) \ OPC(OpSub, (HasDest|CanCSE)) \ OPC(OpAnd, (HasDest|CanCSE)) \ OPC(OpOr, (HasDest|CanCSE)) \ OPC(OpXor, (HasDest|CanCSE)) \ OPC(OpMul, (HasDest|CanCSE)) \ \ /* convert from src operand's type to destination type */ \ OPC(Conv, (HasDest|CanCSE|CallsNative)) \ \ /* query operators returning bool */ \ /* comparisons (binary) */ \ OPC(OpGt, (HasDest|CanCSE)) \ OPC(OpGte, (HasDest|CanCSE)) \ OPC(OpLt, (HasDest|CanCSE)) \ OPC(OpLte, (HasDest|CanCSE)) \ OPC(OpEq, (HasDest|CanCSE)) \ OPC(OpNeq, (HasDest|CanCSE)) \ /* XXX validate that we don't call helpers with side effects */ \ /* and ref count consumption/production for any of these query */ \ /* operations and their corresponding conditional branches */ \ OPC(OpSame, (HasDest|CanCSE|CallsNative)) \ OPC(OpNSame, (HasDest|CanCSE|CallsNative)) \ \ /* XXX TODO check instanceof's hasEffects, isNative, RefCount, MayReenter */ \ OPC(InstanceOfD, (HasDest|CanCSE)) \ OPC(NInstanceOfD, (HasDest|CanCSE)) \ \ /* isset, empty, and istype queries (unary) */ \ OPC(IsSet, (HasDest|CanCSE)) \ OPC(IsType, (HasDest|CanCSE)) \ OPC(IsNSet, (HasDest|CanCSE)) \ OPC(IsNType, (HasDest|CanCSE)) \ \ /* conditional branches & jump */ \ /* there is a conditional branch for each of the above query */ \ /* operators to enable generating efficieng comparison-and-branch */ \ /* instruction sequences */ \ OPC(JmpGt, (HasDest|Essential)) \ OPC(JmpGte, (HasDest|Essential)) \ OPC(JmpLt, (HasDest|Essential)) \ OPC(JmpLte, (HasDest|Essential)) \ OPC(JmpEq, (HasDest|Essential)) \ OPC(JmpNeq, (HasDest|Essential)) \ OPC(JmpZero, (HasDest|Essential)) \ OPC(JmpNZero, (HasDest|Essential)) \ OPC(JmpSame, (HasDest|Essential)) \ OPC(JmpNSame, (HasDest|Essential)) \ /* keep preceeding conditional branches contiguous */ \ OPC(JmpInstanceOfD, (HasDest|Essential)) \ OPC(JmpNInstanceOfD, (HasDest|Essential)) \ OPC(JmpIsSet, (HasDest|Essential)) \ OPC(JmpIsType, (HasDest|Essential)) \ OPC(JmpIsNSet, (HasDest|Essential)) \ OPC(JmpIsNType, (HasDest|Essential)) \ OPC(Jmp_, (HasDest|Essential)) \ OPC(ExitWhenSurprised, (Essential)) \ OPC(ExitOnVarEnv, (Essential)) \ OPC(ReleaseVVOrExit, (Essential)) \ OPC(CheckUninit, (Essential)) \ \ OPC(Unbox, (HasDest|ProducesRC)) \ OPC(Box, (HasDest|Essential|MemEffects| \ CallsNative|ConsumesRC| \ ProducesRC)) \ OPC(UnboxPtr, (HasDest)) \ \ /* loads */ \ OPC(LdStack, (HasDest|ProducesRC)) \ OPC(LdLoc, (HasDest)) \ OPC(LdStackAddr, (HasDest|CanCSE)) \ OPC(LdLocAddr, (HasDest|CanCSE)) \ OPC(LdMemNR, (HasDest)) \ OPC(LdPropNR, (HasDest)) \ OPC(LdRefNR, (HasDest)) \ OPC(LdThis, (HasDest|CanCSE|Essential| \ Rematerializable)) \ /* LdThisNc avoids check */ \ OPC(LdThisNc, (HasDest|CanCSE|Rematerializable)) \ OPC(LdRetAddr, (HasDest)) \ OPC(LdHome, (HasDest|CanCSE)) \ OPC(LdConst, (HasDest|CanCSE|Rematerializable)) \ OPC(DefConst, (HasDest|CanCSE)) \ OPC(LdCls, (HasDest|CanCSE|MayModifyRefs| \ Rematerializable|MayRaiseError)) \ /* XXX cg doesn't support the version without a label*/ \ OPC(LdClsCns, (HasDest|CanCSE)) \ OPC(LdClsMethodCache, (HasDest|CanCSE| \ Rematerializable|MayRaiseError)) \ OPC(LdClsMethod, (HasDest|CanCSE)) \ /* XXX TODO Create version of LdClsPropAddr that doesn't check */ \ OPC(LdPropAddr, (HasDest|CanCSE)) \ OPC(LdClsPropAddr, (HasDest|CanCSE|Essential| \ Rematerializable|MayRaiseError)) \ /* helper call to MethodCache::Lookup */ \ OPC(LdObjMethod, (HasDest|CanCSE|Essential| \ CallsNative|MayModifyRefs| \ MayRaiseError)) \ OPC(LdObjClass, (HasDest|CanCSE)) \ OPC(LdCachedClass, (HasDest|CanCSE|Rematerializable)) \ /* helper call to FuncCache::lookup */ \ OPC(LdFunc, (HasDest|Essential|CallsNative| \ ConsumesRC|MayRaiseError)) \ /* helper call for FPushFuncD(FixedFuncCache::lookup) */ \ OPC(LdFixedFunc, (HasDest|CanCSE|Essential| \ MayRaiseError)) \ OPC(LdCurFuncPtr, (HasDest|CanCSE|Rematerializable)) \ OPC(LdARFuncPtr, (HasDest|CanCSE)) \ OPC(LdFuncCls, (HasDest|CanCSE|Rematerializable)) \ OPC(NewObj, (HasDest|Essential|MemEffects| \ CallsNative|ProducesRC)) \ OPC(NewArray, (HasDest|Essential|MemEffects| \ CallsNative|ProducesRC)) \ OPC(NewTuple, (HasDest|Essential|MemEffects| \ CallsNative|ConsumesRC|ProducesRC)) \ OPC(LdRaw, (HasDest)) \ /* XXX: why does AllocActRec consume rc? */ \ OPC(AllocActRec, (HasDest|MemEffects|ConsumesRC)) \ OPC(FreeActRec, (HasDest|MemEffects)) \ OPC(Call, (HasDest|Essential|MemEffects| \ ConsumesRC|MayModifyRefs)) \ OPC(NativeImpl, (Essential|MemEffects|CallsNative| \ MayModifyRefs)) \ OPC(RetCtrl, (Essential|MemEffects)) \ OPC(RetVal, (Essential|MemEffects|ConsumesRC)) \ OPC(RetAdjustStack, (HasDest|Essential)) \ /* stores */ \ OPC(StMem, (Essential|MemEffects|ConsumesRC| \ MayModifyRefs)) \ OPC(StMemNT, (Essential|MemEffects|ConsumesRC)) \ OPC(StProp, (Essential|MemEffects|ConsumesRC| \ MayModifyRefs)) \ OPC(StPropNT, (Essential|MemEffects|ConsumesRC)) \ OPC(StLoc, (Essential|MemEffects|ConsumesRC)) \ OPC(StLocNT, (Essential|MemEffects|ConsumesRC)) \ OPC(StRef, (HasDest|Essential|MemEffects| \ ConsumesRC|MayModifyRefs)) \ OPC(StRefNT, (HasDest|Essential|MemEffects| \ ConsumesRC)) \ OPC(StRaw, (Essential|MemEffects)) \ OPC(SpillStack, (HasDest|Essential|MemEffects| \ ConsumesRC)) \ OPC(SpillStackAllocAR, (HasDest|Essential|MemEffects| \ ConsumesRC)) \ /* Update ExitTrace entries in sync with ExitType below */ \ OPC(ExitTrace, (Essential)) \ OPC(ExitTraceCc, (Essential)) \ OPC(ExitSlow, (Essential)) \ OPC(ExitSlowNoProgress,(Essential)) \ OPC(ExitGuardFailure, (Essential)) \ /* */ \ OPC(Mov, (HasDest|CanCSE)) \ OPC(IncRef, (HasDest|MemEffects|ProducesRC)) \ OPC(DecRefLoc, (Essential|MemEffects|MayModifyRefs)) \ OPC(DecRefStack, (Essential|MemEffects|MayModifyRefs)) \ OPC(DecRefThis, (Essential|MemEffects|MayModifyRefs)) \ OPC(GenericRetDecRefs, (HasDest|Essential|MemEffects|CallsNative| \ MayModifyRefs)) \ OPC(DecRef, (Essential|MemEffects|ConsumesRC| \ MayModifyRefs)) \ /* DecRefNZ only decrements the ref count, and doesn't modify Refs. */ \ /* DecRefNZ also doesn't run dtor, so we don't mark it essential. */ \ OPC(DecRefNZ, (MemEffects|ConsumesRC)) \ OPC(DefLabel, (Essential)) \ OPC(Marker, (Essential)) \ OPC(DefFP, (HasDest|Essential)) \ OPC(DefSP, (HasDest|Essential)) \ \ /* runtime helpers */ \ /* XXX check consume ref count */ \ OPC(RaiseUninitWarning,(Essential|MemEffects|CallsNative| \ MayModifyRefs|MayRaiseError)) \ OPC(Print, (Essential|MemEffects|CallsNative| \ ConsumesRC)) \ OPC(AddElem, (HasDest|MemEffects|CallsNative| \ ConsumesRC|ProducesRC|MayModifyRefs)) \ OPC(AddNewElem, (HasDest|MemEffects|CallsNative| \ ConsumesRC|ProducesRC)) \ OPC(DefCns, (HasDest|CanCSE|Essential| \ MemEffects|CallsNative)) \ OPC(Concat, (HasDest|MemEffects|CallsNative| \ ConsumesRC|ProducesRC|MayModifyRefs)) \ OPC(ArrayAdd, (HasDest|MemEffects|CallsNative| \ ConsumesRC|ProducesRC)) \ OPC(DefCls, (CanCSE|Essential|CallsNative)) \ OPC(DefFunc, (CanCSE|Essential|CallsNative)) \ OPC(InterpOne, (HasDest|Essential|MemEffects| \ CallsNative|MayModifyRefs| \ MayRaiseError)) \ \ /* for register allocation */ \ OPC(Spill, (HasDest|MemEffects)) \ OPC(Reload, (HasDest|MemEffects)) \ OPC(AllocSpill, (Essential|MemEffects)) \ OPC(FreeSpill, (Essential|MemEffects)) \ /* continuation support */ \ OPC(CreateCont, (HasDest|Essential|MemEffects| \ CallsNative|ProducesRC)) \ OPC(FillContLocals, (Essential|MemEffects|CallsNative)) \ OPC(FillContThis, (Essential|MemEffects)) \ OPC(UnlinkContVarEnv, (Essential|MemEffects|CallsNative)) \ OPC(LinkContVarEnv, (Essential|MemEffects|CallsNative)) \ OPC(ContRaiseCheck, (Essential)) \ OPC(ContPreNext, (Essential|MemEffects)) \ OPC(ContStartedCheck, (Essential)) \ \ OPC(IncStat, (Essential|MemEffects)) \ OPC(AssertRefCount, (Essential)) \ /* */ enum Opcode { #define OPC(name, flags) name, IR_OPCODES #undef OPC IR_NUM_OPCODES }; static inline bool isCmpOp(Opcode opc) { return (opc >= OpGt && opc <= NInstanceOfD); } static inline Opcode cmpToJmpOp(Opcode opc) { ASSERT(isCmpOp(opc)); return (Opcode)(JmpGt + (opc - OpGt)); } static inline bool isQueryOp(Opcode opc) { return (opc >= OpGt && opc <= IsNType); } static inline bool isTypeQueryOp(Opcode opc) { return (opc == IsType || opc == IsNType); } static inline Opcode queryToJmpOp(Opcode opc) { ASSERT(isQueryOp(opc)); return (Opcode)(JmpGt + (opc - OpGt)); } extern Opcode queryNegateTable[]; static inline Opcode negateQueryOp(Opcode opc) { ASSERT(isQueryOp(opc)); return queryNegateTable[opc - OpGt]; } extern Opcode queryCommuteTable[]; static inline Opcode commuteQueryOp(Opcode opc) { ASSERT(opc >= OpGt && opc <= OpNSame); return queryCommuteTable[opc - OpGt]; } namespace TraceExitType { // Must update in sync with ExitTrace entries in OPC table above enum ExitType { Normal, NormalCc, Slow, SlowNoProgress, GuardFailure }; } extern TraceExitType::ExitType getExitType(Opcode opc); extern Opcode getExitOpcode(TraceExitType::ExitType); const char* opcodeName(Opcode opcode); bool opcodeHasFlags(Opcode opcode, uint64_t flag); class Type { public: // This mostly parallels the DataType enum in runtime/base/types.h, but it's // not the same as DataType. See typeToDataType below. // type name, debug string #define IR_TYPES \ IRT(None, "Void") /* Corresponds to HPHP::TypeOfInvalid */ \ IRT(Uninit, "Unin") \ IRT(Null, "Null") \ IRT(Bool, "Bool") \ IRT(Int, "Int") /* HPHP::DataType::KindOfInt64 */ \ IRT(Dbl, "Dbl") \ IRT(Placeholder, "ERROR") /* Nothing in VM types enum at this position */ \ IRT(StaticStr, "Sstr") \ IRT(UncountedInit, "UncountedInit") /* One of {Null,Bool,Int,Dbl,SStr} */\ IRT(Uncounted, "Uncounted") /* 1 of: {Unin,Null,Bool,Int,Dbl,SStr} */\ IRT(Str, "Str") \ IRT(Arr, "Arr") \ IRT(Obj, "Obj") \ IRT(Cell, "Cell") /* any type above, but statically unknown */ \ /* Variant types */ \ IRT(BoxedUninit, "Unin&") /* Unused */ \ IRT(BoxedNull, "Null&") \ IRT(BoxedBool, "Bool&") \ IRT(BoxedInt, "Int&") /* HPHP::DataType::KindOfInt64 */ \ IRT(BoxedDbl, "Dbl&") \ IRT(BoxedPlaceholder,"ERROR") /* Nothing in VM types enum at this position */ \ IRT(BoxedStaticStr, "SStr&") \ IRT(BoxedStr, "Str&") \ IRT(BoxedArr, "Arr&") \ IRT(BoxedObj, "Obj&") \ IRT(BoxedCell, "Cell&") /* any Boxed* types but statically unknown */ \ IRT(Gen, "Gen") /* Generic type value, (cell or variant but statically unknown) */ \ IRT(PtrToCell, "Cell*") \ IRT(PtrToGen, "Gen*") \ IRT(Home, "Home") /* HPHP::DataType defines this as -2 */ \ /* runtime metadata */ \ IRT(ClassRef, "Cls&") \ IRT(FuncRef, "Func&") \ IRT(VarEnvRef, "VarEnv&")\ IRT(FuncClassRef, "FuncClass&") /* this has both a Func& and a Class& */\ IRT(RetAddr, "RetAddr") /* Return address */ \ IRT(SP, "StkP") /* any pointer into VM stack: VmSP or VmFP */\ IRT(TCA, "TCA") \ enum Tag { #define IRT(type, name) type, IR_TYPES #undef IRT TAG_ENUM_COUNT }; static const Tag RefCountThreshold = Uncounted; static inline bool isBoxed(Tag t) { return (t > Cell && t < Gen); } static inline bool isUnboxed(Tag t) { return (t <= Type::Cell && t != Type::None); } static inline bool isRefCounted(Tag t) { return (t > RefCountThreshold && t <= Gen); } static inline bool isStaticallyKnown(Tag t) { return (t != Cell && t != Gen && t != Uncounted && t != UncountedInit); } static inline bool isStaticallyKnownUnboxed(Tag t) { return isStaticallyKnown(t) && isUnboxed(t); } static inline bool needsStaticBitCheck(Tag t) { return (t == Cell || t == Gen || t == Str || t == Arr); } // returns true if definitely not uninitialized static inline bool isInit(Tag t) { return ((t != Uninit && isStaticallyKnown(t)) || isBoxed(t)); } static inline bool mayBeUninit(Tag t) { return (t == Uninit || t == Uncounted || t == Cell || t == Gen); } // returns true if t1 is a more refined that t2 static inline bool isMoreRefined(Tag t1, Tag t2) { return ((t2 == Gen && t1 < Gen) || (t2 == Cell && t1 < Cell) || (t2 == BoxedCell && t1 < BoxedCell && t1 > Cell) || (t2 == Str && t1 == StaticStr) || (t2 == BoxedStr && t1 == BoxedStaticStr) || (t2 == Uncounted && t1 < Uncounted) || (t2 == UncountedInit && t1 < UncountedInit && t1 > Uninit)); } static inline bool isString(Tag t) { return (t == Str || t == StaticStr); } static inline bool isNull(Tag t) { return (t == Null || t == Uninit); } static inline Tag getInnerType(Tag t) { ASSERT(isBoxed(t)); switch (t) { case BoxedUninit : return Uninit; case BoxedNull : return Null; case BoxedBool : return Bool; case BoxedInt : return Int; case BoxedDbl : return Dbl; case BoxedStaticStr : return StaticStr; case BoxedStr : return Str; case BoxedArr : return Arr; case BoxedObj : return Obj; case BoxedCell : return Cell; default : not_reached(); } } static inline Tag getBoxedType(Tag t) { if (t == None) { // translator-x64 sometimes gives us an inner type of KindOfInvalid and // an outer type of KindOfRef return BoxedCell; } if (t == Uninit) { return BoxedNull; } ASSERT(isUnboxed(t)); switch (t) { case Uninit : return BoxedUninit; case Null : return BoxedNull; case Bool : return BoxedBool; case Int : return BoxedInt; case Dbl : return BoxedDbl; case StaticStr : return BoxedStaticStr; case Str : return BoxedStr; case Arr : return BoxedArr; case Obj : return BoxedObj; case Cell : return BoxedCell; default : not_reached(); } } static inline Tag getValueType(Tag t) { if (isBoxed(t)) { return getInnerType(t); } return t; } static const char* Strings[]; // translates a compiler Type::Type to a HPHP::DataType static inline DataType toDataType(Tag type) { switch (type) { case None : return KindOfInvalid; case Uninit : return KindOfUninit; case Null : return KindOfNull; case Bool : return KindOfBoolean; case Int : return KindOfInt64; case Dbl : return KindOfDouble; case StaticStr : return KindOfStaticString; case Str : return KindOfString; case Arr : return KindOfArray; case Obj : return KindOfObject; case ClassRef : return KindOfClass; case UncountedInit : return KindOfUncountedInit; case Uncounted : return KindOfUncounted; case Gen : return KindOfAny; default: { ASSERT(isBoxed(type)); return KindOfRef; } } } static inline Tag fromDataType(DataType outerType, DataType innerType) { switch (outerType) { case KindOfInvalid : return None; case KindOfUninit : return Uninit; case KindOfNull : return Null; case KindOfBoolean : return Bool; case KindOfInt64 : return Int; case KindOfDouble : return Dbl; case KindOfStaticString : return StaticStr; case KindOfString : return Str; case KindOfArray : return Arr; case KindOfObject : return Obj; case KindOfClass : return ClassRef; case KindOfUncountedInit : return UncountedInit; case KindOfUncounted : return Uncounted; case KindOfAny : return Gen; case KindOfRef : return getBoxedType(fromDataType(innerType, KindOfInvalid)); default : not_reached(); } } static inline Tag fromRuntimeType(const Transl::RuntimeType& rtt) { return fromDataType(rtt.outerType(), rtt.innerType()); } static inline bool canRunDtor(Type::Tag t) { return (t == Obj || t == BoxedObj || t == Arr || t == BoxedArr || t == Cell || t == BoxedCell || t == Gen); } }; // class Type class RawMemSlot { public: enum Kind { ContLabel, ContDone, ContShouldThrow, ContRunning, StrLen, FuncNumParams, FuncRefBitVec, MaxKind }; static RawMemSlot& Get(Kind k) { switch (k) { case ContLabel: return GetContLabel(); case ContDone: return GetContDone(); case ContShouldThrow: return GetContShouldThrow(); case ContRunning: return GetContRunning(); case StrLen: return GetStrLen(); case FuncNumParams: return GetFuncNumParams(); case FuncRefBitVec: return GetFuncRefBitVec(); default: not_reached(); } } int64 getOffset() { return m_offset; } int32 getSize() { return m_size; } Type::Tag getType() { return m_type; } private: RawMemSlot(int64 offset, int32 size, Type::Tag type) : m_offset(offset), m_size(size), m_type(type) { } static RawMemSlot& GetContLabel() { static RawMemSlot m(CONTOFF(m_label), sz::qword, Type::Int); return m; } static RawMemSlot& GetContDone() { static RawMemSlot m(CONTOFF(m_done), sz::byte, Type::Bool); return m; } static RawMemSlot& GetContShouldThrow() { static RawMemSlot m(CONTOFF(m_should_throw), sz::byte, Type::Bool); return m; } static RawMemSlot& GetContRunning() { static RawMemSlot m(CONTOFF(m_running), sz::byte, Type::Bool); return m; } static RawMemSlot& GetStrLen() { static RawMemSlot m(StringData::sizeOffset(), sz::dword, Type::Int); return m; } static RawMemSlot& GetFuncNumParams() { static RawMemSlot m(Func::numParamsOff(), sz::qword, Type::Int); return m; } static RawMemSlot& GetFuncRefBitVec() { static RawMemSlot m(Func::refBitVecOff(), sz::qword, Type::Int); return m; } int64 m_offset; int32 m_size; Type::Tag m_type; }; struct Local { explicit Local(uint32_t id) : m_id(id) {} uint32_t getId() const { return m_id; } void print(std::ostream& os) const { os << "h" << m_id; } private: const uint32_t m_id; }; class SSATmp; class Trace; class CodeGenerator; class IRFactory; class Simplifier; bool isRefCounted(SSATmp* opnd); const unsigned NUM_FIXED_SRCS = 2; class LabelInstruction; // All IRInstruction subclasses must be arena-allocatable. // (Destructors are not called.) class IRInstruction { public: Opcode getOpcode() const { return (Opcode)m_op; } void setOpcode(Opcode newOpc) { m_op = newOpc; } Type::Tag getType() const { return (Type::Tag)m_type; } void setType(Type::Tag t) { m_type = t; } uint32 getNumSrcs() const { return m_numSrcs; } uint32 getNumExtendedSrcs() const{ return (m_numSrcs <= NUM_FIXED_SRCS ? 0 : m_numSrcs - NUM_FIXED_SRCS); } SSATmp* getSrc(uint32 i) const; void setSrc(uint32 i, SSATmp* newSrc); SSATmp* getDst() const { return m_dst; } void setDst(SSATmp* newDst) { m_dst = newDst; } TCA getTCA() const { return m_tca; } void setTCA(TCA newTCA) { m_tca = newTCA; } uint32 getId() const { return m_id; } void setId(uint32 newId) { m_id = newId; } void setAsmAddr(void* addr) { m_asmAddr = addr; } void* getAsmAddr() const { return m_asmAddr; } RegSet getLiveOutRegs() const { return m_liveOutRegs; } void setLiveOutRegs(RegSet s) { m_liveOutRegs = s; } bool isDefConst() const { return (m_op == DefConst || m_op == LdHome); } Trace* getParent() const { return m_parent; } void setParent(Trace* parentTrace) { m_parent = parentTrace; } void setLabel(LabelInstruction* l) { m_label = l; } LabelInstruction* getLabel() const { return m_label; } bool isControlFlowInstruction() const { return m_label != NULL; } virtual bool isConstInstruction() const { return false; } virtual bool equals(IRInstruction* inst) const; virtual uint32 hash(); virtual SSATmp* simplify(Simplifier*); virtual void print(std::ostream& ostream); void print(); virtual IRInstruction* clone(IRFactory* factory); typedef std::list<IRInstruction*> List; typedef std::list<IRInstruction*>::iterator Iterator; typedef std::list<IRInstruction*>::reverse_iterator ReverseIterator; /* * Helper accessors for the OpcodeFlag bits for this instruction. * * Note that these wrappers may have additional logic beyond just * checking the corresponding flags bit. */ bool canCSE() const; bool hasDst() const; bool hasMemEffects() const; bool isRematerializable() const; bool isNative() const; bool consumesReferences() const; bool consumesReference(int srcNo) const; bool producesReference() const; bool mayModifyRefs() const; void printDst(std::ostream& ostream); void printSrc(std::ostream& ostream, uint32 srcIndex); void printOpcode(std::ostream& ostream); void printSrcs(std::ostream& ostream); protected: friend class IRFactory; friend class TraceBuilder; friend class HhbcTranslator; public: IRInstruction(Opcode o, Type::Tag t, LabelInstruction *l = NULL) : m_op(o), m_type(t), m_id(0), m_numSrcs(0), m_dst(NULL), m_asmAddr(NULL), m_label(l), m_parent(NULL), m_tca(NULL) { m_srcs[0] = m_srcs[1] = NULL; } IRInstruction(Opcode o, Type::Tag t, SSATmp* src, LabelInstruction *l = NULL) : m_op(o), m_type(t), m_id(0), m_numSrcs(1), m_dst(NULL), m_asmAddr(NULL), m_label(l), m_parent(NULL), m_tca(NULL) { m_srcs[0] = src; m_srcs[1] = NULL; } IRInstruction(Opcode o, Type::Tag t, SSATmp* src0, SSATmp* src1, LabelInstruction *l = NULL) : m_op(o), m_type(t), m_id(0), m_numSrcs(2), m_dst(NULL), m_asmAddr(NULL), m_label(l), m_parent(NULL), m_tca(NULL) { m_srcs[0] = src0; m_srcs[1] = src1; } IRInstruction(IRInstruction* inst) : m_op(inst->m_op), m_type(inst->m_type), m_id(0), m_numSrcs(inst->m_numSrcs), m_dst(NULL), m_asmAddr(NULL), m_label(inst->m_label), m_parent(NULL), m_tca(NULL) { m_srcs[0] = inst->m_srcs[0]; m_srcs[1] = inst->m_srcs[1]; } virtual SSATmp* getExtendedSrc(uint32 i) const; virtual void setExtendedSrc(uint32 i, SSATmp* newSrc); // fields Opcode m_op; Type::Tag m_type; uint32 m_id; uint16 m_numSrcs; RegSet m_liveOutRegs; SSATmp* m_srcs[NUM_FIXED_SRCS]; SSATmp* m_dst; void* m_asmAddr; LabelInstruction* m_label; Trace* m_parent; TCA m_tca; }; class ExtendedInstruction : public IRInstruction { public: virtual SSATmp* simplify(Simplifier*); virtual IRInstruction* clone(IRFactory* factory); virtual SSATmp* getExtendedSrc(uint32 i) const; virtual void setExtendedSrc(uint32 i, SSATmp* newSrc); void appendExtendedSrc(IRFactory& irFactory, SSATmp* src); virtual SSATmp** getExtendedSrcs() { return m_extendedSrcs; } protected: friend class IRFactory; friend class TraceBuilder; ExtendedInstruction(IRFactory& irFactory, Opcode o, Type::Tag t, uint32 nOpnds, SSATmp** opnds, LabelInstruction* l = NULL) : IRInstruction(o, t, l) { initExtendedSrcs(irFactory, nOpnds, opnds); } ExtendedInstruction(IRFactory& irFactory, Opcode o, Type::Tag t, SSATmp* src, uint32 nOpnds, SSATmp** opnds, LabelInstruction* l = NULL) : IRInstruction(o, t, src, l) { initExtendedSrcs(irFactory, nOpnds, opnds); } ExtendedInstruction(IRFactory& irFactory, Opcode o, Type::Tag t, SSATmp* src1, SSATmp* src2, uint32 nOpnds, SSATmp** opnds, LabelInstruction* l = NULL) : IRInstruction(o, t, src1, src2, l) { initExtendedSrcs(irFactory, nOpnds, opnds); } ExtendedInstruction(IRFactory& irFactory, Opcode o, Type::Tag t, SSATmp* src1, SSATmp* src2, SSATmp* src3, uint32 nOpnds, SSATmp** opnds, LabelInstruction* l = NULL) : IRInstruction(o, t, src1, src2, l) { initExtendedSrcs(irFactory, src3, nOpnds, opnds); } ExtendedInstruction(IRFactory& irFactory, ExtendedInstruction* inst) : IRInstruction(inst) { if (m_numSrcs < NUM_FIXED_SRCS) { return; } uint32 nOpnds = m_numSrcs - NUM_FIXED_SRCS; m_numSrcs = NUM_FIXED_SRCS; // will be incremented in initExtendedSrcs // Only operands after NUM_FIXED_SRCS are kept in inst->extendedSrcs initExtendedSrcs(irFactory, nOpnds, inst->m_extendedSrcs); } void initExtendedSrcs(IRFactory&, uint32 nOpnds, SSATmp** opnds); void initExtendedSrcs(IRFactory&, SSATmp* src, uint32 nOpnds, SSATmp** opnds); SSATmp** m_extendedSrcs; }; class TypeInstruction : public IRInstruction { public: Type::Tag getSrcType() { return m_srcType; } virtual void print(std::ostream& ostream); virtual bool equals(IRInstruction* inst) const; virtual uint32 hash(); virtual SSATmp* simplify(Simplifier*); virtual IRInstruction* clone(IRFactory* factory); protected: friend class IRFactory; friend class TraceBuilder; TypeInstruction(Opcode o, Type::Tag typ, Type::Tag dstType, SSATmp* src) : IRInstruction(o, dstType, src), m_srcType(typ) { } TypeInstruction(TypeInstruction* inst) : IRInstruction(inst), m_srcType(inst->m_srcType) { } Type::Tag m_srcType; }; class ConstInstruction : public IRInstruction { public: bool getValAsBool() const { ASSERT(m_type == Type::Bool); return m_boolVal; } int64 getValAsInt() const { ASSERT(m_type == Type::Int); return m_intVal; } int64 getValAsRawInt() const { return m_intVal; } double getValAsDbl() const { ASSERT(m_type == Type::Dbl); return m_dblVal; } const StringData* getValAsStr() const { ASSERT(m_type == Type::StaticStr); return m_strVal; } const ArrayData* getValAsArr() const { ASSERT(m_type == Type::Arr); return m_arrVal; } const Func* getValAsFunc() const { ASSERT(m_type == Type::FuncRef); return m_func; } const Class* getValAsClass() const { ASSERT(m_type == Type::ClassRef); return m_clss; } const VarEnv* getValAsVarEnv() const { ASSERT(m_type == Type::VarEnvRef); return m_varEnv; } TCA getValAsTCA() const { ASSERT(m_type == Type::TCA); return m_tca; } bool isEmptyArray() const { return m_arrVal == HphpArray::GetStaticEmptyArray(); } Local getLocal() const { ASSERT(m_type == Type::Home); return m_local; } uintptr_t getValAsBits() const { return m_bits; } void printConst(std::ostream& ostream) const; virtual bool isConstInstruction() const {return true;} virtual void print(std::ostream& ostream); virtual bool equals(IRInstruction* inst) const; virtual uint32 hash(); virtual IRInstruction* clone(IRFactory* factory); protected: friend class IRFactory; friend class TraceBuilder; friend class LinearScan; ConstInstruction(Opcode opc, Type::Tag type, int64 val) : IRInstruction(opc, type) { ASSERT(opc == DefConst || opc == LdConst); ASSERT(type <= Type::StaticStr); m_intVal = val; } ConstInstruction(Opcode opc, Type::Tag t) : IRInstruction(opc, t) { ASSERT(opc == DefConst || opc == LdConst); m_intVal = 0; } ConstInstruction(Opcode opc, int64 val) : IRInstruction(opc, Type::Int) { ASSERT(opc == DefConst || opc == LdConst); m_intVal = val; } ConstInstruction(Opcode opc, double val) : IRInstruction(opc, Type::Dbl) { ASSERT(opc == DefConst || opc == LdConst); m_dblVal = val; } ConstInstruction(Opcode opc, const StringData* val) : IRInstruction(opc, Type::StaticStr) { ASSERT(opc == DefConst || opc == LdConst); m_strVal = val; } ConstInstruction(Opcode opc, const ArrayData* val) : IRInstruction(opc, Type::Arr) { ASSERT(opc == DefConst || opc == LdConst); m_arrVal = val; } ConstInstruction(Opcode opc, bool val) : IRInstruction(opc, Type::Bool) { ASSERT(opc == DefConst || opc == LdConst); m_intVal = 0; m_boolVal = val; } ConstInstruction(SSATmp* src, Local l) : IRInstruction(LdHome, Type::Home, src) { new (&m_local) Local(l); } ConstInstruction(Opcode opc, const Func* f) : IRInstruction(opc, Type::FuncRef) { ASSERT(opc == DefConst || opc == LdConst); m_func = f; } ConstInstruction(Opcode opc, const Class* f) : IRInstruction(opc, Type::ClassRef) { ASSERT(opc == DefConst || opc == LdConst); m_clss = f; } ConstInstruction(ConstInstruction* inst) : IRInstruction(inst), m_strVal(inst->m_strVal) { } private: union { uintptr_t m_bits; bool m_boolVal; int64 m_intVal; double m_dblVal; const StringData* m_strVal; const ArrayData* m_arrVal; Local m_local; // for LdHome opcode const Func* m_func; const Class* m_clss; const VarEnv* m_varEnv; const TCA m_tca; }; friend class CodeGenerator; void setValAsRawInt(int64 intVal) { m_intVal = intVal; } }; class LabelInstruction : public IRInstruction { public: Trace* getTrace() const { return m_trace; } void setTrace(Trace* t) { m_trace = t; } uint32 getLabelId() const { return m_labelId; } int32 getStackOff() const { return m_stackOff; } const Func* getFunc() const { return m_func; } virtual void print(std::ostream& ostream); virtual bool equals(IRInstruction* inst) const; virtual uint32 hash(); virtual SSATmp* simplify(Simplifier*); virtual IRInstruction* clone(IRFactory* factory); void prependPatchAddr(TCA addr); void* getPatchAddr(); protected: friend class IRFactory; friend class TraceBuilder; friend class CodeGenerator; LabelInstruction(uint32 id) : IRInstruction(DefLabel, Type::None), m_labelId(id), m_stackOff(0), m_patchAddr(0), m_trace(NULL) { } LabelInstruction(Opcode opc, uint32 id) : IRInstruction(opc,Type::None), m_labelId(id), m_stackOff(0), m_patchAddr(0), m_trace(NULL) { } LabelInstruction(Opcode opc, uint32 bcOff, const Func* f, int32 spOff) : IRInstruction(opc,Type::None), m_labelId(bcOff), m_stackOff(spOff), m_patchAddr(0), m_func(f) { } LabelInstruction(LabelInstruction* inst) : IRInstruction(inst), m_labelId(inst->m_labelId), m_stackOff(inst->m_stackOff), m_patchAddr(0), m_trace(inst->m_trace) // copies func also { } uint32 m_labelId; // for Marker instructions: the bytecode offset in unit int32 m_stackOff; // for Marker instructions: stack off from start of trace void* m_patchAddr; // Support patching forward jumps union { Trace* m_trace; // for DefLabel instructions const Func* m_func; // for Marker instructions }; }; struct SpillInfo { enum Type { MMX, Memory }; explicit SpillInfo(RegNumber r) : m_type(MMX), m_val(int(r)) {} explicit SpillInfo(uint32_t v) : m_type(Memory), m_val(v) {} Type type() const { return m_type; } RegNumber mmx() const { return RegNumber(m_val); } uint32_t mem() const { return m_val; } private: Type m_type : 1; uint32_t m_val : 31; }; inline std::ostream& operator<<(std::ostream& os, SpillInfo si) { switch (si.type()) { case SpillInfo::MMX: os << "mmx" << reg::regname(RegXMM(int(si.mmx()))); break; case SpillInfo::Memory: os << "spill[" << si.mem() << "]"; break; } return os; } class SSATmp { public: uint32 getId() const { return m_id; } IRInstruction* getInstruction() const { return m_inst; } void setInstruction(IRInstruction* i) { m_inst = i; } Type::Tag getType() const { return m_inst->getType(); } uint32 getLastUseId() { return m_lastUseId; } void setLastUseId(uint32 newId) { m_lastUseId = newId; } uint32 getUseCount() { return m_useCount; } void setUseCount(uint32 count) { m_useCount = count; } void incUseCount() { m_useCount++; } uint32 decUseCount() { return --m_useCount; } bool isConst() const { return m_inst->isConstInstruction(); } bool getConstValAsBool() const; int64 getConstValAsInt() const; int64 getConstValAsRawInt() const; double getConstValAsDbl() const; const StringData* getConstValAsStr() const; const ArrayData* getConstValAsArr() const; const Func* getConstValAsFunc() const; const Class* getConstValAsClass() const; uintptr_t getConstValAsBits() const; void print(std::ostream& ostream, bool printLastUse = false); void print(); // Used for Jcc to Jmp elimination void setTCA(TCA tca); TCA getTCA() const; /* * Returns whether or not a given register index is allocated to a * register, or returns false if it is spilled. * * Right now, we only spill both at the same time and only Spill and * Reload instructions need to deal with SSATmps that are spilled. */ bool hasReg(uint32 i) const { return !m_isSpilled && m_regs[i] != reg::noreg; } /* * The maximum number of registers this SSATmp may need allocated. * This is based on the type of the temporary (some types never have * regs, some have two, etc). */ int numNeededRegs() const; /* * The number of regs actually allocated to this SSATmp. This might * end up fewer than numNeededRegs if the SSATmp isn't really * being used. */ int numAllocatedRegs() const; /* * Access to allocated registers. * * Returns InvalidReg for slots that aren't allocated. */ PhysReg getReg() { ASSERT(!m_isSpilled); return m_regs[0]; } PhysReg getReg(uint32 i) { ASSERT(!m_isSpilled); return m_regs[i]; } void setReg(PhysReg reg, uint32 i) { m_regs[i] = reg; } /* * Returns information about how to spill/fill a SSATmp. * * These functions are only valid if this SSATmp is being spilled or * filled. In all normal instructions (i.e. other than Spill and * Reload), SSATmps are assigned registers instead of spill * locations. */ void setSpillInfo(int idx, SpillInfo si) { m_spillInfo[idx] = si; m_isSpilled = true; } SpillInfo getSpillInfo(int idx) const { ASSERT(m_isSpilled); return m_spillInfo[idx]; } /* * During register allocation, this is used to track spill locations * that are assigned to specific SSATmps. A value of -1 is used to * indicate no spill slot has been assigned. * * After register allocation, use getSpillInfo to access information * about where we've decided to spill/fill a given SSATmp from. * This value doesn't have any meaning outside of the linearscan * pass. */ int32_t getSpillSlot() const { return m_spillSlot; } void setSpillSlot(int32_t val) { m_spillSlot = val; } private: friend class IRFactory; friend class TraceBuilder; // May only be created via IRFactory. Note that this class is never // destructed, so don't add complex members. SSATmp(uint32 opndId, IRInstruction* i) : m_inst(i) , m_id(opndId) , m_lastUseId(0) , m_useCount(0) , m_isSpilled(false) , m_spillSlot(-1) { m_regs[0] = m_regs[1] = InvalidReg; } SSATmp(const SSATmp&); SSATmp& operator=(const SSATmp&); IRInstruction* m_inst; const uint32 m_id; uint32 m_lastUseId; uint16 m_useCount; bool m_isSpilled : 1; int32_t m_spillSlot : 31; /* * m_regs[0] is always the value of this SSATmp. * * Cell or Gen types use two registers: m_regs[1] is the runtime * type. */ static const int kMaxNumRegs = 2; union { PhysReg m_regs[kMaxNumRegs]; SpillInfo m_spillInfo[kMaxNumRegs]; }; }; class Trace : boost::noncopyable { public: explicit Trace(LabelInstruction* label, uint32 bcOff, bool isMain) { appendInstruction(label); label->setTrace(this); m_bcOff = bcOff; m_lastAsmAddress = NULL; m_firstAsmAddress = NULL; m_firstAstubsAddress = NULL; m_isMain = isMain; } ~Trace() { std::for_each(m_exitTraces.begin(), m_exitTraces.end(), boost::checked_deleter<Trace>()); } IRInstruction::List& getInstructionList() { return m_instructionList; } LabelInstruction* getLabel() const { return (LabelInstruction*)*m_instructionList.begin(); } IRInstruction* prependInstruction(IRInstruction* inst) { // jump over the trace's label std::list<IRInstruction*>::iterator it = m_instructionList.begin(); ++it; m_instructionList.insert(it, inst); inst->setParent(this); return inst; } IRInstruction* appendInstruction(IRInstruction* inst) { m_instructionList.push_back(inst); inst->setParent(this); return inst; } uint32 getBcOff() { return m_bcOff; } void setLastAsmAddress(uint8* addr) { m_lastAsmAddress = addr; } void setFirstAsmAddress(uint8* addr) { m_firstAsmAddress = addr; } void setFirstAstubsAddress(uint8* addr) { m_firstAstubsAddress = addr; } uint8* getLastAsmAddress() { return m_lastAsmAddress; } uint8* getFirstAsmAddress() { return m_firstAsmAddress; } Trace* addExitTrace(Trace* exit) { m_exitTraces.push_back(exit); return exit; } bool isMain() const { return m_isMain; } typedef std::list<Trace*> List; typedef std::list<Trace*>::iterator Iterator; List& getExitTraces() { return m_exitTraces; } void print(std::ostream& ostream, bool printAsm, bool isExit = false); void print(); // default to std::cout and printAsm == true private: // offset of the first bytecode in this trace; 0 if this trace doesn't // represent a bytecode boundary. uint32 m_bcOff; // instructions in main trace starting with a label std::list<IRInstruction*> m_instructionList; // traces to which this trace exits List m_exitTraces; uint8* m_firstAsmAddress; uint8* m_firstAstubsAddress; uint8* m_lastAsmAddress; bool m_isMain; }; void optimizeTrace(Trace*, IRFactory* irFactory); void numberInstructions(Trace*); uint32 numberInstructions(Trace* trace, uint32 nextId, bool followControlFlow = true); /* * Clears the IRInstructions' ids, and the SSATmps' use count and last use id. */ void resetIds(Trace* trace); int getLocalIdFromHomeOpnd(SSATmp* srcHome); static inline bool isConvIntOrPtrToBool(IRInstruction* instr) { if (!(instr->getOpcode() == Conv && instr->getType() == Type::Bool)) { return false; } switch (instr->getSrc(0)->getType()) { case Type::Int : case Type::FuncRef : case Type::ClassRef : case Type::FuncClassRef : case Type::VarEnvRef : case Type::TCA : return true; default: return false; } } }}} #endif
[ "sgolemon@fb.com" ]
sgolemon@fb.com
4623ed5a1f0a8ea7482dec3b2a9c3d6abf530c48
abdd0dcf68914e1547ac23b14fd1d7847dc9ce83
/fileSys/src/.history/node_20200428213329.cpp
35045105f8e79b6eb3295aedeba6a5e3ffd3bbb9
[]
no_license
SnowflyLXF/Distributed-Systems-UMN
d290e2fdd2f07309fc62dffbe377443be6c34f3f
bd834f8cb2100836a67143ccdaeb79495cb74e18
refs/heads/master
2023-08-01T09:29:56.350535
2021-09-26T04:05:17
2021-09-26T04:05:17
410,444,689
0
0
null
null
null
null
UTF-8
C++
false
false
13,844
cpp
#include "node.hpp" using namespace std; uint32_t checksum(std::ifstream& file) { uint32_t sum = 0; uint32_t word = 0; while (file.read(reinterpret_cast<char*>(&word), sizeof(word))) { sum += word; } if (file.gcount()) { word &= (~0U >> ((sizeof(uint32_t) - file.gcount()) * 8)); sum += word; } return sum; } string Node::checkip() { char ip_address[15]; int fd; struct ifreq ifr; /*AF_INET - to define network interface IPv4*/ /*Creating soket for it.*/ fd = socket(AF_INET, SOCK_DGRAM, 0); /*AF_INET - to define IPv4 Address type.*/ ifr.ifr_addr.sa_family = AF_INET; /*eth0 - define the ifr_name - port name where network attached.*/ memcpy(ifr.ifr_name, "eno1", IFNAMSIZ - 1); /*Accessing network interface information by passing address using ioctl.*/ ioctl(fd, SIOCGIFADDR, &ifr); /*closing fd*/ close(fd); /*Extract IP Address*/ strcpy(ip_address, inet_ntoa(((struct sockaddr_in *)&ifr.ifr_addr)->sin_addr)); printf("System IP Address is: %s\n", ip_address); string s(ip_address); return s; } Node ::Node(int Port, int OnPort) { num_up = 0; load = 0; _port = Port; _onListenPort = OnPort; _slen = sizeof(_node_addr); max_port = OnPort+1; node_ip = checkip(); dirname = "node" + to_string(_port); memset((char *)&_node_addr, 0, sizeof(_node_addr)); _node_addr.sin_family = AF_INET; _node_addr.sin_addr.s_addr = htonl(INADDR_ANY); _node_addr.sin_port = htons(_port); _node_socket_fd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); if (::bind(_node_socket_fd, (struct sockaddr *)&_node_addr, sizeof(_node_addr)) == -1) { cout << "Bind failed!" << endl; } thread onLis(&Node::onListen, this); onLis.detach(); } string Node::listen2() { char _buf2[BUFLEN]; memset(_buf2, ' ', BUFLEN); int recvLen = recvfrom(_onlisten_fd, _buf2, BUFLEN, 0, (struct sockaddr *)&_tmp_addr, reinterpret_cast<socklen_t *>(&_slen)); char msg[recvLen + 1]; // cout<<_buf<<endl; strncpy(msg, _buf2, recvLen); // string s(msg); msg[recvLen] = '\0'; string s(msg); // cout << s << endl; return s; } void Node::onListen() { memset((char *)&_onlisten_addr, 0, sizeof(_onlisten_addr)); memset((char *)&_tmp_addr, 0, sizeof(_tmp_addr)); _onlisten_addr.sin_family = AF_INET; _onlisten_addr.sin_addr.s_addr = htonl(INADDR_ANY); _onlisten_addr.sin_port = htons(_onListenPort); _onlisten_fd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); if (::bind(_onlisten_fd, (struct sockaddr *)&_onlisten_addr, sizeof(_onlisten_addr)) == -1) { cout << "Bind failed!" << endl; } string m; while(1) { m = listen2(); if(strcmp(m.c_str(), "GetLoad")==0) { char msg[BUFLEN] = {0}; int len = sizeof(to_string(load).c_str()); snprintf(msg, len, to_string(load).c_str()); sendto(_onlisten_fd, msg, len, 0, (struct sockaddr *)&_tmp_addr, _slen); } else if (strcmp(m.c_str(), "Download")==0) { string dIP = listen2(); int dport = stoi(listen2()); string file = listen2(); cout << dIP << ":" << dport << ", "<< file << endl; handleUpload(dIP, dport, file); } } } int Node::Connect() { char msg[BUFLEN] = {0}; int len = sizeof("Connect"); snprintf(msg, len, "Connect"); int n = sendall(msg, &len); return n; } int Node::SetServer(string serverIP, int serverPort) { memset((char *)&_server_addr, 0, sizeof(_server_addr)); _server_addr.sin_family = AF_INET; _server_addr.sin_addr.s_addr = inet_addr(serverIP.c_str()); _server_addr.sin_port = htons(serverPort); } string Node::listen() { memset(_buf, ' ', BUFLEN); int recvLen = recvfrom(_node_socket_fd, _buf, BUFLEN, 0, (struct sockaddr *)&_server_addr, reinterpret_cast<socklen_t *>(&_slen)); char msg[recvLen + 1]; // cout<<_buf<<endl; strncpy(msg, _buf, recvLen); // string s(msg); msg[recvLen] = '\0'; string s(msg); return s; } int Node ::sendall(char *msg, int *len) { // cout<<msg.c_str()<<endl; int bytesLeft = *len; int sentLen = 0; int n; while (sentLen < *len) { n = sendto(_node_socket_fd, msg + sentLen, bytesLeft, 0, (struct sockaddr *)&_server_addr, _slen); if (n == -1) { break; } sentLen += n; bytesLeft -= n; } *len = sentLen; return n == -1 ? -1 : 0; } Node::names Node::getFileList() { names files; DIR *dir; struct dirent *ptr; if ((dir = opendir(dirname.c_str())) == NULL) { perror("Open dir error..."); exit(1); } while ((ptr = readdir(dir)) != NULL) { if (strcmp(ptr->d_name, ".") == 0 || strcmp(ptr->d_name, "..") == 0) ///current dir OR parrent dir continue; else if (ptr->d_type == 8) files.push_back(ptr->d_name); } closedir(dir); return files; } int Node::FileList() { char msg[BUFLEN] = {0}; int len = sizeof("FileList"); snprintf(msg, len, "FileList"); int n = sendall(msg, &len); len = sizeof(to_string(_onListenPort)); snprintf(msg, len, to_string(_onListenPort).c_str()); n = sendall(msg, &len); names files = getFileList(); int fsize = files.size(); len = sizeof(to_string(fsize)); snprintf(msg, len, to_string(fsize).c_str()); n = sendall(msg, &len); for(int i = 0;i<fsize;i++) { len = sizeof(files[i]); snprintf(msg, len, files[i].c_str()); n = sendall(msg, &len); } } int Node::Update() { char msg[BUFLEN] = {0}; int len = sizeof("Update"); snprintf(msg, len, "Update"); int n = sendall(msg, &len); names files = getFileList(); int fsize = files.size(); len = sizeof(to_string(fsize)); snprintf(msg, len, to_string(fsize).c_str()); n = sendall(msg, &len); for (int i = 0; i < fsize; i++) { len = sizeof(files[i]); snprintf(msg, len, files[i].c_str()); n = sendall(msg, &len); } } Node::names Node::Find(string filename) { names tmpnodes; char msg[BUFLEN] = {0}; int len = sizeof("Find"); snprintf(msg, len, "Find"); int n = sendall(msg, &len); len = sizeof(filename.c_str()); snprintf(msg, len+1, filename.c_str()); n = sendall(msg, &len); string inmsg; inmsg = listen(); int nodecount = stoi(inmsg); for (int i = 0; i < nodecount; i++) { inmsg = listen(); tmpnodes.push_back(inmsg); cout<<inmsg<<endl; } // GetLoad(tmpnodes[0]); // GetLoad(tmpnodes[1]); return tmpnodes; } int Node::GetLoad(string c) { char *p; char *strs = new char[c.length() + 1]; strcpy(strs,c.c_str()); p = strtok(strs, ":"); string IP(p); p = strtok(NULL, ":"); int p2 = atoi(p); // cout<<p2<<endl; struct sockaddr_in _c_addr; memset((char *)&_c_addr, 0, sizeof(_c_addr)); _c_addr.sin_family = AF_INET; _c_addr.sin_addr.s_addr = inet_addr(IP.c_str()); _c_addr.sin_port = htons(p2); char msg[BUFLEN] = {0}; int len = sizeof("GetLoad"); snprintf(msg, len, "GetLoad"); sendto(_node_socket_fd, msg, len, 0, (struct sockaddr *)&_c_addr, _slen); string m = listen(); // cout<<m<<endl; // len = sizeof("Download"); // snprintf(msg, len, "Download"); // sendto(_node_socket_fd, msg, len, 0, (struct sockaddr *)&_c_addr, _slen); // len = sizeof("127.0.0.1"); // snprintf(msg, len, "127.0.0.1"); // sendto(_node_socket_fd, msg, len, 0, (struct sockaddr *)&_c_addr, _slen); // len = sizeof("6001"); // snprintf(msg, len, "6001"); // sendto(_node_socket_fd, msg, len, 0, (struct sockaddr *)&_c_addr, _slen); // len = sizeof("cnm.txt"); // snprintf(msg, len, "cnm.txt"); // sendto(_node_socket_fd, msg, len, 0, (struct sockaddr *)&_c_addr, _slen); // m = listen(); // cout<<m<<endl; // m = listen(); // cout << m << endl; return stoi(m); } int Node::Download(string file) { Node::names upers = Find(file); string uper = upers.front(); int minload = GetLoad(uper); for(int i=1; i<upers.size(); i++){ int l = GetLoad(upers.at(i)); if(l < minload) { uper = l; minload = GetLoad(uper); } } load++; thread onDownload(&Node::handleDownload, this, uper, file); onDownload.detach(); // cout<<m<<endl; } int Node::handleDownload(string uper, string file){ int this_port = max_port++; cout<<"Download from "<<uper<<endl; struct sockaddr_in down_node_addr, up_node_addr; memset((char *)&down_node_addr, 0, sizeof(down_node_addr)); down_node_addr.sin_family = AF_INET; down_node_addr.sin_addr.s_addr = htonl(INADDR_ANY); down_node_addr.sin_port = htons(this_port); int down_node_socket_fd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); if (::bind(down_node_socket_fd, (struct sockaddr *)&down_node_addr, sizeof(down_node_addr)) == -1) { cout << "Bind failed!" << endl; } int pos = uper.find(":"); string upip = uper.substr(0,pos); string p = uper.substr(pos+1, uper.length()+1); int upport = stoi(p); memset((char *)&up_node_addr, 0, sizeof(up_node_addr)); up_node_addr.sin_family = AF_INET; up_node_addr.sin_addr.s_addr = inet_addr(upip.c_str()); up_node_addr.sin_port = htons(upport); char msg[BUFLEN] = {0}; int len = sizeof("Download"); snprintf(msg, len, "Download"); sendto(down_node_socket_fd, msg, len, 0, (struct sockaddr *)&up_node_addr, _slen); len = sizeof("127.0.0.1"); snprintf(msg, len, "127.0.0.1"); sendto(down_node_socket_fd, msg, len, 0, (struct sockaddr *)&up_node_addr, _slen); string this_port_c = to_string(this_port); len = sizeof(this_port_c); snprintf(msg, len, this_port_c.c_str()); sendto(down_node_socket_fd, msg, len, 0, (struct sockaddr *)&up_node_addr, _slen); len = sizeof(file); snprintf(msg, len, file.c_str()); sendto(down_node_socket_fd, msg, len, 0, (struct sockaddr *)&up_node_addr, _slen); char _bufd[BUFLEN]; int recvLen = recvfrom(down_node_socket_fd, _bufd, BUFLEN, 0, (struct sockaddr *)&_tmp_addr, reinterpret_cast<socklen_t *>(&_slen)); char filed[recvLen + 1]; strncpy(filed, _bufd, recvLen); filed[recvLen] = '\0'; cout << "downloader received:" << filed << endl; int flen = stoi(filed); recvLen = recvfrom(down_node_socket_fd, _bufd, flen, 0, (struct sockaddr *)&_tmp_addr, reinterpret_cast<socklen_t *>(&_slen)); FILE * pfile; pfile = fopen((dirname + "/tmp/" + file).c_str(), "wb"); filed[recvLen + 1]; strncpy(filed, _bufd, recvLen); filed[recvLen] = '\0'; cout << "content: " << filed << endl; fwrite(filed, flen*sizeof(char), 1, pfile); fclose(pfile); ifstream f; int cksum; f.open((dirname + "/tmp/" + file).c_str(), ios_base::in); if (f.is_open()) cksum = checksum(f); recvLen = recvfrom(down_node_socket_fd, _bufd, BUFLEN, 0, (struct sockaddr *)&_tmp_addr, reinterpret_cast<socklen_t *>(&_slen)); filed[recvLen + 1]; strncpy(filed, _bufd, recvLen); filed[recvLen] = '\0'; cout << filed<<endl; if (strcmp(filed, to_string(cksum).c_str()) == 0) { cout<<"match"<<endl; } } int Node::handleUpload(string dip, int dport, string file) { thread uplder(&Node::Uploader, this, dip, dport, file); uplder.detach(); num_up ++; } void Node::Uploader(string dip, int dport, string file) { char msg[BUFLEN] = {0}; int len; load++; struct sockaddr_in downloader_addr; int uploader_socket_fd; memset((char *)&downloader_addr, 0, sizeof(downloader_addr)); downloader_addr.sin_family = AF_INET; downloader_addr.sin_addr.s_addr = inet_addr(dip.c_str()); downloader_addr.sin_port = htons(dport); uploader_socket_fd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); DIR *dir; struct dirent *ptr; FILE *fp; if ((dir = opendir(dirname.c_str())) == NULL) { perror("Open dir error..."); exit(1); } while ((ptr = readdir(dir)) != NULL) { if (strcmp(ptr->d_name, ".") == 0 || strcmp(ptr->d_name, "..") == 0) ///current dir OR parrent dir continue; else if (ptr->d_type == 8) { if(strcmp(ptr->d_name, file.c_str()) == 0) { fp = fopen((dirname +"/"+ file).c_str(), "rb"); if (fp == NULL) { cerr << "File Open Error"; } struct stat st; stat((dirname + "/" + file).c_str(), &st); size_t fsize = st.st_size; len = sizeof(fsize); snprintf(msg, len, "%d", fsize); sendto(uploader_socket_fd, msg, len, 0, (struct sockaddr *)&downloader_addr, _slen); fread(msg, 1, fsize, fp); sendto(uploader_socket_fd, msg, fsize, 0, (struct sockaddr *)&downloader_addr, _slen); ifstream f; int cksum; f.open((dirname + "/" + file).c_str(), ios_base::in); if (f.is_open()) cksum = checksum(f); cout<<cksum<<endl; len = sizeof(cksum); snprintf(msg, len, "%d", cksum); sendto(uploader_socket_fd, msg, len, 0, (struct sockaddr *)&downloader_addr, _slen); fclose(fp); } } } closedir(dir); load--; }
[ "lixuefei9679@gmail.com" ]
lixuefei9679@gmail.com
bdbe70c31a05fc1f05fff56b46e0c2b67a9f41d2
ff80e04350e0dec61088cc88bddd4e886eee55fe
/src/common/unique-ptr-cast.hpp
25f09f322f400515940a6ad6f3accee670593fda
[ "MIT" ]
permissive
NGIOproject/NORNS
543d732ab54e5e1662551abb106a61acf59532f9
4fd2d181019eceadb8b1b04a94e3756476326239
refs/heads/master
2020-05-27T23:32:49.920135
2019-07-01T13:22:22
2019-07-01T13:22:22
188,820,209
2
0
null
null
null
null
UTF-8
C++
false
false
3,841
hpp
/************************************************************************* * Copyright (C) 2017-2019 Barcelona Supercomputing Center * * Centro Nacional de Supercomputacion * * All rights reserved. * * * * This file is part of NORNS, a service that allows other programs to * * start, track and manage asynchronous transfers of data resources * * between different storage backends. * * * * See AUTHORS file in the top level directory for information regarding * * developers and contributors. * * * * This software was developed as part of the EC H2020 funded project * * NEXTGenIO (Project ID: 671951). * * www.nextgenio.eu * * * * 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 <memory> #ifndef __UNIQUE_PTR_CAST_HPP__ #define __UNIQUE_PTR_CAST_HPP__ namespace norns { namespace utils { template<typename Derived, typename Base, typename Del> std::unique_ptr<Derived, Del> static_unique_ptr_cast( std::unique_ptr<Base, Del>&& p ) { auto d = static_cast<Derived *>(p.release()); return std::unique_ptr<Derived, Del>(d, std::move(p.get_deleter())); } template<typename Derived, typename Base, typename Del> std::unique_ptr<Derived, Del> static_unique_ptr_cast(const std::unique_ptr<Base, Del>&& p ) { return static_unique_ptr_cast<Derived, Base, Del>( std::move(const_cast<std::unique_ptr<Base, Del>&>(p))); } template<typename Derived, typename Base, typename Del> std::unique_ptr<Derived, Del> dynamic_unique_ptr_cast( std::unique_ptr<Base, Del>&& p ) { if(Derived *result = dynamic_cast<Derived *>(p.get())) { p.release(); return std::unique_ptr<Derived, Del>(result, std::move(p.get_deleter())); } return std::unique_ptr<Derived, Del>(nullptr, p.get_deleter()); } } // namespace utils } // namespace norns #endif /* __UNIQUE_PTR_CAST_HPP__ */
[ "alberto.miranda@bsc.es" ]
alberto.miranda@bsc.es
c0f631172be207337f1513663e53de192acb25f9
76ce5c0ee753b9516c6114f2eb114cfe726dc7d5
/Stockfish/search.h
a2a02edac3ed2c63217808aee07c23b459a4abab
[]
no_license
tranhoangduong1994/iot-chess
583e473f8e030eea955cfed28f8e81f73d7efa36
9208eada0bbf3bda6923facfbf44ae183304e371
refs/heads/master
2021-09-03T08:27:58.579149
2018-01-07T14:34:23
2018-01-07T14:34:23
108,617,989
1
0
null
null
null
null
UTF-8
C++
false
false
3,182
h
/* Stockfish, a UCI chess playing engine derived from Glaurung 2.1 Copyright (C) 2004-2008 Tord Romstad (Glaurung author) Copyright (C) 2008-2015 Marco Costalba, Joona Kiiski, Tord Romstad Copyright (C) 2015-2017 Marco Costalba, Joona Kiiski, Gary Linscott, Tord Romstad Stockfish is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Stockfish is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef SEARCH_H_INCLUDED #define SEARCH_H_INCLUDED #include <vector> #include "misc.h" #include "movepick.h" #include "types.h" class Position; namespace Search { /// Stack struct keeps track of the information we need to remember from nodes /// shallower and deeper in the tree during the search. Each search thread has /// its own array of Stack objects, indexed by the current ply. struct Stack { Move* pv; PieceToHistory* history; int ply; Move currentMove; Move excludedMove; Move killers[2]; Value staticEval; int statScore; int moveCount; }; /// RootMove struct is used for moves at the root of the tree. For each root move /// we store a score and a PV (really a refutation in the case of moves which /// fail low). Score is normally set at -VALUE_INFINITE for all non-pv moves. struct RootMove { explicit RootMove(Move m) : pv(1, m) {} bool extract_ponder_from_tt(Position& pos); bool operator==(const Move& m) const { return pv[0] == m; } bool operator<(const RootMove& m) const { // Sort in descending order return m.score != score ? m.score < score : m.previousScore < previousScore; } Value score = -VALUE_INFINITE; Value previousScore = -VALUE_INFINITE; int selDepth = 0; std::vector<Move> pv; }; typedef std::vector<RootMove> RootMoves; /// LimitsType struct stores information sent by GUI about available time to /// search the current move, maximum depth/time, if we are in analysis mode or /// if we have to ponder while it's our opponent's turn to move. struct LimitsType { LimitsType() { // Init explicitly due to broken value-initialization of non POD in MSVC nodes = time[WHITE] = time[BLACK] = inc[WHITE] = inc[BLACK] = npmsec = movestogo = depth = movetime = mate = infinite = ponder = 0; } bool use_time_management() const { return !(mate | movetime | depth | nodes | infinite); } std::vector<Move> searchmoves; int time[COLOR_NB], inc[COLOR_NB], npmsec, movestogo, depth, movetime, mate, infinite, ponder; int64_t nodes; TimePoint startTime; }; extern LimitsType Limits; void init(); void clear(); template<bool Root = true> uint64_t perft(Position& pos, Depth depth); } // namespace Search #endif // #ifndef SEARCH_H_INCLUDED
[ "tranhoangduong110@gmail.com" ]
tranhoangduong110@gmail.com
6f46d4e6638d5c7cb5efcaae3d35b54bda7084d2
f9a3f11ee028cdb73b22b7fa18648c0abb5f425d
/HackerRank/IceCreamParlor_map.cpp
6725f892c4936e9e978a487ecd55da32e62bc936
[]
no_license
pearldarkk/C-Cplusplus
431e17343ca6a1859aca1dc1b8a353afa7d23a87
43b5f656c9e7dd0a7866f50c69a0c49ad115c2f1
refs/heads/main
2023-08-22T05:43:32.770939
2021-10-26T13:36:18
2021-10-26T13:36:18
null
0
0
null
null
null
null
UTF-8
C++
false
false
593
cpp
#define M 1000000007 #include <bits/stdc++.h> using namespace std; typedef long long ll; typedef unsigned long long ull; typedef pair <int, int> ii; typedef vector <int> vi; typedef vector <ii> vii; int main() { int t; cin >> t; while (t--) { int m, n; cin >> m >> n; vi v(n); map <int, int> mp; for (int i = 0; i != n; ++i) { cin >> v[i]; if (mp.find(v[i]) != mp.end()) cout << mp[v[i]] + 1 << ' ' << i + 1 << endl; mp[m - v[i]] = i; } } return 0; }
[ "ng.ahn.pd@gmail.com" ]
ng.ahn.pd@gmail.com
cdfdefaac1f00c3ca68d1f30b9b3d90c6c39c902
abef0d6249dd3bb75ecb755f7ce185d369350353
/codeforces/1203/D1.cpp
89a988b93aa6f26b4af893b7618e7ea0aafa358a
[]
no_license
ipaljak/oj
01009947d9df0b9986bd542dd340566b4697fa7d
dce61d8c4e3a3efd1c6abea6f6891294800cd1c4
refs/heads/master
2023-05-11T06:31:40.164892
2021-06-04T14:37:00
2021-06-06T17:31:35
327,563,559
2
0
null
null
null
null
UTF-8
C++
false
false
1,290
cpp
#include <bits/stdc++.h> using namespace std; #define TRACE(x) cerr << #x << " " << x << endl #define FOR(i, a, b) for (int i = (a); i < int(b); ++i) #define REP(i, n) FOR(i, 0, n) #define _ << " " << typedef long long llint; const int MOD = 1e9 + 7; const int MAXN = 2e5 + 10; int ns, nt; char s[MAXN], t[MAXN]; int pref[MAXN], suff[MAXN]; int main(void) { scanf("%s%s", s, t); ns = strlen(s); nt = strlen(t); pref[0] = s[0] == t[0]; for (int i = 1; i < ns; ++i) { pref[i] = pref[i - 1]; if (pref[i] == nt) continue; if (s[i] == t[pref[i]]) ++pref[i]; } suff[ns - 1] = s[ns - 1] == t[nt - 1]; for (int i = ns - 2; i >= 0; --i) { suff[i] = suff[i + 1]; if (suff[i] == nt) continue; if (s[i] == t[nt - suff[i] - 1]) ++suff[i]; } //for (int i = 0; i < ns; ++i) printf("%d ", pref[i]); printf("\n"); //for (int i = 0; i < ns; ++i) printf("%d ", suff[i]); printf("\n"); //TRACE(pref[ns - 1]); assert(pref[ns - 1] == nt); assert(suff[0] == nt); int hi = 0, sol = 0; for (int lo = 0; lo < ns; ++lo) { while (hi < ns && pref[lo] + suff[hi] >= nt) ++hi; sol = max(sol, hi - lo - 2); if (pref[lo] == nt) sol = max(sol, ns - lo - 1); if (suff[lo] == nt) sol = max(sol, lo); } printf("%d\n", sol); return 0; }
[ "ipaljak@gmail.com" ]
ipaljak@gmail.com
282b151b80f9d45139cbbadc6b581f8e93beef5a
b825e6c1d570d9939c3b0da95549a865922c09a1
/include/phan/phan.hpp
adf11ea4a7dc0b55e8a97b1ef6e9c75f51d24ab7
[ "Apache-2.0" ]
permissive
phiwen96/phan
12dc378dbc99e806c2dc9760d777c62ab8853a73
61bd47d57dc6d0e7a92c6e9db676f5d76ed8edb4
refs/heads/main
2023-08-23T14:54:35.903000
2021-11-03T15:45:34
2021-11-03T15:45:34
345,117,517
3
1
null
null
null
null
UTF-8
C++
false
false
251
hpp
#pragma once #include <vector> #include <tuple> /// \brief Accumulate a vector to produce the mean and the first moment of the distribution. /// /// This computes the mean and the first moment of a vector of double values. /// #define KUKEN hej
[ "38218064+phiwen96@users.noreply.github.com" ]
38218064+phiwen96@users.noreply.github.com
cd50e10034d22a8ae0bd4e74a243b1b544e220ba
01b761a0eb1494ab9e798c64e28e53095d87c502
/chapter_five/5_2VoidFunction.cpp
cd2ba295950c33e06254ba4e686145c171519653
[]
no_license
Ryoung27/C-Intro-Course
6ae6360bbc21e55ad6b39a66569a9f6a744e0372
086bf5c10945af874555a7302fc137b193fa10e2
refs/heads/master
2023-01-24T18:47:57.420522
2020-12-03T01:05:27
2020-12-03T01:05:27
287,614,637
0
0
null
null
null
null
UTF-8
C++
false
false
1,320
cpp
//Program to convert a Fahrenheit temperature to a Celsius temperature. #include <iostream> void initializeScreen(); //Separates current output from //the output of the previously run program. double celsius(double fahrenheit); //Converts a Fahrenheit temperature //to a Celsius temperature. void showResults(double fDegrees, double cDegrees); //Displays output. Assumes that cDegrees //Celsius is equivalaent to fDegrees Fahrenheit. int main() { using namespace std; double fTemperature, cTemperature; initializeScreen(); cout << "I will convert a Fahrenheit temperature" << " to Celsius.\n" << "Enter a temperature in Fahrenheit: "; cin >> fTemperature; cTemperature = celsius(fTemperature); showResults(fTemperature, cTemperature); return 0; } //Definition uses iostream; void initializeScreen() { using namespace std; cout << endl; return; } double celsius(double fahrenheit) { return ((5.0/9.0)*(fahrenheit -32)); } //Definition uses iostream; void showResults(double fDegrees, double cDegrees) { using namespace std; cout.setf(ios::fixed); cout.setf(ios::showpoint); cout.precision(1); cout << fDegrees << " degrees Fahrenheit is equivalent to\n" << cDegrees << " degrees Celsius.\n"; return ; }
[ "RRYoung89@gmail.com" ]
RRYoung89@gmail.com
d86f69d877441b16c8c557c693f071e34976d100
f38ea1c549ecd682a6975752897351c317a8bd22
/2018/10/03/[U41568]Agent1.cpp
23c0903124ff34be81f2f1e995d539cbd128fa93
[ "Unlicense" ]
permissive
skylayer/OiCodeRepo
d7911e462f3c20c156138d9d0b9de7b177962764
c386efbd790ace5d39db6741b8ae9ec954e3cfc1
refs/heads/master
2021-10-08T04:11:16.126102
2021-10-07T12:57:05
2021-10-07T12:57:05
149,401,444
1
0
null
null
null
null
UTF-8
C++
false
false
450
cpp
#include<bits/stdc++.h> using namespace std; const int inv2=500000004; const int p=1e9+7; int n; inline int fpow(int index) { long long base=2,ans=1; while(index) { if(index&1) ans=ans*base%p; base=base*base%p; index>>=1; } return ans; } long long ans; long long bot,top; int main() { // cout<<fpow(p-2)<<endl; scanf("%d",&n); cout<<((long long)n*fpow(n-1)-fpow(n)+1)%p; return 0; }
[ "1262500438@qq.com" ]
1262500438@qq.com
ab6e1b7dd823bc2d569cce8338c95ad493b94744
f80af86cad57bf091d27e89052214ca29d3b3a16
/3rd Year/2nd Semester/Computação Gráfica/Trabalho Prático/Fase 3/Motor/rotacao.cpp
2ef1fc71cb39cdb10041650ef4b58415f8da70ef
[]
no_license
diogoesnog/MIEI
44719dce30177ae877b2bdb90ec73a606e64ce63
322b03a561937be91af7158be888227bae75f5c4
refs/heads/master
2022-08-20T14:34:37.136699
2022-07-27T22:08:23
2022-07-27T22:08:23
249,830,783
6
0
null
null
null
null
ISO-8859-1
C++
false
false
1,132
cpp
#include <stdlib.h> #include <GL/glew.h> #include <GL/glut.h> #include "rotacao.h" // Inserção de uma nova rotação. Rotacao inserirRotacao(float periodo, float angulo, float x, float y, float z, Rotacao rotacoes){ Rotacao rotacao=NULL, novasRotacoes=rotacoes; // Criamos uma nova rotação com os valores passados como parâmetro. rotacao = (Rotacao) malloc(sizeof(TRotacao)); rotacao->x = x; rotacao->y = y; rotacao->z = z; if(periodo==0){ rotacao->angulo=angulo; rotacao->periodo=0; } else{ rotacao->periodo = periodo*1000; rotacao->angulo=0; } rotacao->proximo=NULL; if(!rotacoes) return rotacao; while(rotacoes->proximo) rotacoes=rotacoes->proximo; rotacoes->proximo = rotacao; return novasRotacoes; } // Reprodução das rotações. Rotacao reproduzirRotacao(Rotacao rotacao, long tempoAtual){ if(rotacao->periodo!=0) glRotatef(360*(tempoAtual%rotacao->periodo)/ rotacao->periodo, rotacao->x, rotacao->y, rotacao->z); else glRotatef(rotacao->angulo, rotacao->x, rotacao->y, rotacao->z); return rotacao->proximo; }
[ "34174814+diogoesnog@users.noreply.github.com" ]
34174814+diogoesnog@users.noreply.github.com
ca6b89554b1177c0df836e1c29297b971f0e4111
14a9c15033ada6562220569b8b79fa4ce7a10c1c
/fhq-jury-ad/src/checker/service_checker_thread.cpp
2876efed9e7267076e8028c62d5bb7c4bead4667
[ "MIT" ]
permissive
nhthongDfVn/Attack-Defense-PTIT
a677418ec8575eed941aa94e6a711bb583a97e24
82cc83e8de05d56097ffedfd9d5072715769c571
refs/heads/master
2022-04-12T08:48:37.298288
2020-04-10T20:56:40
2020-04-10T20:56:40
null
0
0
null
null
null
null
UTF-8
C++
false
false
10,667
cpp
#include "service_checker_thread.h" #include <unistd.h> #include <dorunchecker.h> #include <iostream> #include <sstream> #include <wsjcpp_core.h> #include <chrono> #include <thread> #include <sys/types.h> #include <sys/wait.h> #include <sys/select.h> #include <sys/time.h> #include <sys/types.h> #include <unistd.h> #include <signal.h> #include <wsjcpp_core.h> int ServiceCheckerThread::CHECKER_CODE_UP = 101; int ServiceCheckerThread::CHECKER_CODE_CORRUPT = 102; int ServiceCheckerThread::CHECKER_CODE_MUMBLE = 103; int ServiceCheckerThread::CHECKER_CODE_DOWN = 104; int ServiceCheckerThread::CHECKER_CODE_SHIT = 400; // --------------------------------------------------------------------- ServiceCheckerThread::ServiceCheckerThread(Config *pConfig, const Team &teamConf, const Service &service) { m_pConfig = pConfig; m_teamConf = teamConf; m_serviceConf = service; TAG = "Checker: " + m_teamConf.id() + std::string( 15 - m_teamConf.id().length(), ' ') + m_serviceConf.id() + " "; WsjcppLog::info(TAG, "Created thread"); } // ---------------------------------------------------------------------- // newRequest void* newServiceCheckerThread(void *arg) { // Log::info("newRequest", ""); ServiceCheckerThread *pServerThread = (ServiceCheckerThread *)arg; pthread_detach(pthread_self()); pServerThread->run(); return 0; } // ---------------------------------------------------------------------- void ServiceCheckerThread::start() { pthread_create(&m_checkerThread, NULL, &newServiceCheckerThread, (void *)this); } // --------------------------------------------------------------------- int ServiceCheckerThread::runChecker(Flag &flag, const std::string &sCommand) { if (sCommand != "put" && sCommand != "check") { WsjcppLog::err(TAG, "runChecker - sCommand must be 'put' or 'check' "); return ServiceCheckerThread::CHECKER_CODE_SHIT; } // Used code from here // https://stackoverflow.com/questions/478898/how-to-execute-a-command-and-get-output-of-command-within-c-using-posix std::string sShellCommand = m_serviceConf.scriptPath() + " " + m_teamConf.ipAddress() + " " + sCommand + " " + flag.id() + " " + flag.value(); WsjcppLog::info(TAG, "Start script " + sShellCommand); DoRunChecker process(m_serviceConf.scriptDir(), m_serviceConf.scriptPath(), m_teamConf.ipAddress(), sCommand, flag.id(), flag.value()); process.start(m_serviceConf.scriptWaitInSec()*1000); if (process.isTimeout()) { return ServiceCheckerThread::CHECKER_CODE_MUMBLE; } if (process.hasError()) { WsjcppLog::err(TAG, "Checker is shit"); WsjcppLog::err(TAG, "Error on run script service: " + process.outputString()); return ServiceCheckerThread::CHECKER_CODE_SHIT; } int nExitCode = process.exitCode(); if (nExitCode != ServiceCheckerThread::CHECKER_CODE_UP && nExitCode != ServiceCheckerThread::CHECKER_CODE_MUMBLE && nExitCode != ServiceCheckerThread::CHECKER_CODE_CORRUPT && nExitCode != ServiceCheckerThread::CHECKER_CODE_DOWN) { WsjcppLog::err(TAG, " Wrong checker exit code...\n" "\n" + process.outputString()); return ServiceCheckerThread::CHECKER_CODE_SHIT; } return nExitCode; } // --------------------------------------------------------------------- void ServiceCheckerThread::run() { // TODO: BUG: so here can be problem with mysql connection after 7-8 hours (terminate connection on MySQL side) // SOLUTION migrate to PostgreSQL // TODO check if game ended WsjcppLog::info(TAG, "Starting thread..."); /*if (QString::fromStdString(m_teamConf.ipAddress()).isEmpty()) { WsjcppLog::err(TAG, "User IP Address is empty!!!"); return; }*/ std::string sScriptPath = m_serviceConf.scriptPath(); /* // already checked on start if (!Wsjcpp::fileExists(sScriptPath)) { WsjcppLog::err(TAG, "FAIL: Script Path to checker not found '" + sScriptPath + "'"); // TODO shit status return; }*/ while(1) { int nCurrentTime = WsjcppCore::currentTime_seconds(); if ( m_pConfig->gameHasCoffeeBreak() && nCurrentTime > m_pConfig->gameCoffeeBreakStartUTCInSec() && nCurrentTime < m_pConfig->gameCoffeeBreakEndUTCInSec() ) { WsjcppLog::info(TAG, "Game on coffeebreak"); m_pConfig->scoreboard()->setServiceStatus(m_teamConf.id(), m_serviceConf.id(), ServiceStatusCell::SERVICE_COFFEEBREAK); return; } if (nCurrentTime > m_pConfig->gameEndUTCInSec()) { WsjcppLog::warn(TAG, "Game ended (current time: " + std::to_string(nCurrentTime) + ")"); return; }; if (nCurrentTime < m_pConfig->gameStartUTCInSec()) { WsjcppLog::warn(TAG, "Game started after: " + std::to_string(m_pConfig->gameStartUTCInSec() - nCurrentTime) + " seconds"); m_pConfig->scoreboard()->setServiceStatus(m_teamConf.id(), m_serviceConf.id(), ServiceStatusCell::SERVICE_WAIT); std::this_thread::sleep_for(std::chrono::milliseconds(1000)); continue; }; std::chrono::time_point<std::chrono::system_clock> start, end; start = std::chrono::system_clock::now(); // If there is more time left before the end of the game than the life of the flag, // then we establish a flag if (nCurrentTime < (m_pConfig->gameEndUTCInSec() - m_pConfig->flagTimeliveInMin()*60)) { Flag flag; flag.generateRandomFlag(m_pConfig->flagTimeliveInMin(), m_teamConf.id(), m_serviceConf.id()); // int nExitCode2 = // WsjcppLog::ok(TAG, " runChecker: " + std::to_string(nExitCode)); int nExitCode = this->runChecker(flag, "put"); if (nExitCode == ServiceCheckerThread::CHECKER_CODE_UP) { // >>>>>>>>>>> service is UP <<<<<<<<<<<<<< WsjcppLog::ok(TAG, " => service is up"); m_pConfig->scoreboard()->incrementFlagsPuttedAndServiceUp(flag); } else if (nExitCode == ServiceCheckerThread::CHECKER_CODE_CORRUPT) { // >>>>>>>>>>> service is CORRUPT <<<<<<<<<<<<<< WsjcppLog::warn(TAG, " => service is corrupt "); m_pConfig->scoreboard()->insertFlagPutFail(flag, ServiceStatusCell::SERVICE_CORRUPT, "corrupt"); // m_pConfig->scoreboard()->setServiceStatus(m_teamConf.id(), m_serviceConf.id(), ServiceStatusCell::SERVICE_CORRUPT); // m_pConfig->scoreboard()->updateScore(flag.teamId(), flag.serviceId()); } else if (nExitCode == ServiceCheckerThread::CHECKER_CODE_MUMBLE) { // >>>>>>>>>>> service is MUMBLE <<<<<<<<<<<<<< // m_pConfig->storage()->insertFlagPutFail(flag, "mumble_1"); WsjcppLog::warn(TAG, " => service is mumble (1) "); m_pConfig->scoreboard()->insertFlagPutFail(flag, ServiceStatusCell::SERVICE_MUMBLE, "mumble_1"); // m_pConfig->scoreboard()->setServiceStatus(m_teamConf.id(), m_serviceConf.id(), ServiceStatusCell::SERVICE_MUMBLE); // m_pConfig->scoreboard()->updateScore(flag.teamId(), flag.serviceId()); } else if (nExitCode == ServiceCheckerThread::CHECKER_CODE_DOWN) { // >>>>>>>>>>> service is DOWN <<<<<<<<<<<<<< m_pConfig->scoreboard()->insertFlagPutFail(flag, ServiceStatusCell::SERVICE_DOWN, "down"); WsjcppLog::warn(TAG, " => service is down "); // m_pConfig->scoreboard()->setServiceStatus(m_teamConf.id(), m_serviceConf.id(), ServiceStatusCell::SERVICE_DOWN); // m_pConfig->scoreboard()->updateScore(flag.teamId(), flag.serviceId()); } else if (nExitCode == ServiceCheckerThread::CHECKER_CODE_SHIT) { // >>>>>>>>>>> checker is SHIT <<<<<<<<<<<<<< m_pConfig->scoreboard()->insertFlagPutFail(flag, ServiceStatusCell::SERVICE_SHIT, "shit"); WsjcppLog::err(TAG, " => checker is shit "); // m_pConfig->scoreboard()->setServiceStatus(m_teamConf.id(), m_serviceConf.id(), ServiceStatusCell::SERVICE_SHIT); // m_pConfig->scoreboard()->updateScore(flag.teamId(), flag.serviceId()); } else { m_pConfig->scoreboard()->insertFlagPutFail(flag, ServiceStatusCell::SERVICE_SHIT, "internal_error"); // m_pConfig->storage()->insertFlagPutFail(flag, "internal_error"); WsjcppLog::err(TAG, " => runChecker - wrong code return"); // m_pConfig->scoreboard()->updateScore(flag.teamId(), flag.serviceId()); } } else { WsjcppLog::info(TAG, "Game ended after: " + std::to_string(m_pConfig->gameEndUTCInSec() - nCurrentTime) + " sec"); // check some service status or just update to UP (Ha-Ha I'm the real evil!) } std::vector<Flag> vEndedFlags = m_pConfig->scoreboard()->outdatedFlagsLive(m_teamConf.id(), m_serviceConf.id()); for (unsigned int i = 0; i < vEndedFlags.size(); i++) { Flag outdatedFlag = vEndedFlags[i]; m_pConfig->scoreboard()->removeFlagLive(outdatedFlag); if (outdatedFlag.teamStole() != "") { continue; } else { // nobody stole outdatedFlag int nCheckExitCode = this->runChecker(outdatedFlag, "check"); if (nCheckExitCode != ServiceCheckerThread::CHECKER_CODE_UP) { // service is not up m_pConfig->storage()->insertFlagCheckFail(outdatedFlag, "code_" + std::to_string(nCheckExitCode)); } else { // service is up // TODO: only if last time (== flag time live) was up if (!m_pConfig->storage()->isSomebodyStole(outdatedFlag)) { m_pConfig->scoreboard()->incrementDefenceScore(outdatedFlag); } } } } // TODO just update SLA ? end = std::chrono::system_clock::now(); int elapsed_milliseconds = std::chrono::duration_cast<std::chrono::milliseconds>(end-start).count(); int ms_sleep = m_serviceConf.timeSleepBetweenRunScriptsInSec()*1000; WsjcppLog::info(TAG, "Elapsed milliseconds: " + std::to_string(elapsed_milliseconds) + "ms"); std::this_thread::sleep_for(std::chrono::milliseconds(ms_sleep - elapsed_milliseconds)); } }
[ "mrseakg@gmail.com" ]
mrseakg@gmail.com
9f8e311397f22f80ed30af7f4f640e4730e86ebe
067690553cf7fa81b5911e8dd4fb405baa96b5b7
/11383/11383.cpp
e5d2f7bfccafc48334f83e2641d3efca4c60af32
[ "MIT" ]
permissive
isac322/BOJ
4c79aab453c884cb253e7567002fc00e605bc69a
35959dd1a63d75ebca9ed606051f7a649d5c0c7b
refs/heads/master
2021-04-18T22:30:05.273182
2019-02-21T11:36:58
2019-02-21T11:36:58
43,806,421
14
9
null
null
null
null
UTF-8
C++
false
false
545
cpp
#include <cstdio> #include <iostream> #include <algorithm> #include <string> using namespace std; string str[10], cmp; int main() { int n, m; scanf("%d %d", &n, &m); for (int i = 0; i < n; i++) cin >> str[i]; bool re = true; for (int i = 0; i < n; i++) { cin >> cmp; bool check = true; if (cmp.size() == (str[i].size() << 1)) { for (int j = 0; j < cmp.size(); j++) { if (str[i][j >> 1] != cmp[j]) { check = false; break; } } } else check = false; re &= check; } puts(re ? "Eyfa" : "Not Eyfa"); }
[ "isac322@naver.com" ]
isac322@naver.com
90bbc890def8efaf3f83c29852db82ef74d2007c
b4a537160bc8aee055534280b8564992d05d4245
/01000/01026.cpp
766df2c3648ecff761b62080fc36d1ac378291c7
[]
no_license
kadragon/acmicpc
c90d8658969d9bcbecd7ac45a188ac1ad4ad1dd3
b76bb7b545256631212ea0a2010d2c485dbd3e40
refs/heads/master
2021-07-13T01:45:03.963267
2021-04-18T07:33:08
2021-04-18T07:33:08
244,813,052
0
0
null
null
null
null
UTF-8
C++
false
false
479
cpp
// // Created by kangdonguk on 2020/04/20. // // https://www.acmicpc.net/problem/1026 // 보물 #include <stdio.h> #include <algorithm> int a[51], b[51]; int main() { int n, ans = 0; scanf("%d", &n); for (int i = 0; i < n; i++) scanf("%d", &a[i]); for (int i = 0; i < n; i++) scanf("%d", &b[i]); std::sort(a, a + n); std::sort(b, b + n); for (int i = 0; i < n; i++) ans += a[i] * b[n - 1 - i]; printf("%d", ans); }
[ "kangdongouk@gmail.com" ]
kangdongouk@gmail.com
087a5d9596483a0a61458db8363d9f4652e8179a
72a34695ac04f09f4412b2a71b4385115ab36ddf
/scene/3d/immediate_geometry.cpp
1459f2c36275eb1736ca1ca8badf353b1a06716a
[ "MIT" ]
permissive
seraph526/godot-se
62c642010b4cd29befde53feba4c99debfc12143
b5f95845fe87dcc0e7ae796006588fa368f8bb3e
refs/heads/master
2021-01-21T01:27:24.785362
2015-05-06T07:34:03
2015-05-06T07:34:03
21,894,625
6
1
null
null
null
null
UTF-8
C++
false
false
2,461
cpp
#include "immediate_geometry.h" void ImmediateGeometry::begin(Mesh::PrimitiveType p_primitive,const Ref<Texture>& p_texture) { VS::get_singleton()->immediate_begin(im,(VS::PrimitiveType)p_primitive,p_texture.is_valid()?p_texture->get_rid():RID()); if (p_texture.is_valid()) cached_textures.push_back(p_texture); } void ImmediateGeometry::set_normal(const Vector3& p_normal){ VS::get_singleton()->immediate_normal(im,p_normal); } void ImmediateGeometry::set_tangent(const Plane& p_tangent){ VS::get_singleton()->immediate_tangent(im,p_tangent); } void ImmediateGeometry::set_color(const Color& p_color){ VS::get_singleton()->immediate_color(im,p_color); } void ImmediateGeometry::set_uv(const Vector2& p_uv){ VS::get_singleton()->immediate_uv(im,p_uv); } void ImmediateGeometry::set_uv2(const Vector2& p_uv2){ VS::get_singleton()->immediate_uv2(im,p_uv2); } void ImmediateGeometry::add_vertex(const Vector3& p_vertex){ VS::get_singleton()->immediate_vertex(im,p_vertex); if (empty) { aabb.pos=p_vertex; aabb.size=Vector3(); } else { aabb.expand_to(p_vertex); } } void ImmediateGeometry::end(){ VS::get_singleton()->immediate_end(im); } void ImmediateGeometry::clear(){ VS::get_singleton()->immediate_clear(im); empty=true; cached_textures.clear(); } AABB ImmediateGeometry::get_aabb() const { return aabb; } DVector<Face3> ImmediateGeometry::get_faces(uint32_t p_usage_flags) const { return DVector<Face3>(); } void ImmediateGeometry::_bind_methods() { ObjectTypeDB::bind_method(_MD("begin","primitive","texture:Texture"),&ImmediateGeometry::begin); ObjectTypeDB::bind_method(_MD("set_normal","normal"),&ImmediateGeometry::set_normal); ObjectTypeDB::bind_method(_MD("set_tangent","tangent"),&ImmediateGeometry::set_tangent); ObjectTypeDB::bind_method(_MD("set_color","color"),&ImmediateGeometry::set_color); ObjectTypeDB::bind_method(_MD("set_uv","uv"),&ImmediateGeometry::set_uv); ObjectTypeDB::bind_method(_MD("set_uv2","uv"),&ImmediateGeometry::set_uv2); ObjectTypeDB::bind_method(_MD("add_vertex","color"),&ImmediateGeometry::add_vertex); ObjectTypeDB::bind_method(_MD("end"),&ImmediateGeometry::end); ObjectTypeDB::bind_method(_MD("clear"),&ImmediateGeometry::clear); } ImmediateGeometry::ImmediateGeometry() { im = VisualServer::get_singleton()->immediate_create(); set_base(im); empty=true; } ImmediateGeometry::~ImmediateGeometry() { VisualServer::get_singleton()->free(im); }
[ "reduzio@gmail.com" ]
reduzio@gmail.com
b92144b0aa11bf0d78a2d29c4ab4458dd8cf1226
f6439b5ed1614fd8db05fa963b47765eae225eb5
/chrome/browser/safe_browsing/safe_browsing_service.cc
277b910f3c6e7adc7dfc099a4d34b64503dc8b4e
[ "BSD-3-Clause" ]
permissive
aranajhonny/chromium
b8a3c975211e1ea2f15b83647b4d8eb45252f1be
caf5bcb822f79b8997720e589334266551a50a13
refs/heads/master
2021-05-11T00:20:34.020261
2018-01-21T03:31:45
2018-01-21T03:31:45
118,301,142
2
0
null
null
null
null
UTF-8
C++
false
false
18,377
cc
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/safe_browsing/safe_browsing_service.h" #include <vector> #include "base/bind.h" #include "base/bind_helpers.h" #include "base/callback.h" #include "base/command_line.h" #include "base/debug/leak_tracker.h" #include "base/lazy_instance.h" #include "base/path_service.h" #include "base/prefs/pref_change_registrar.h" #include "base/prefs/pref_service.h" #include "base/stl_util.h" #include "base/strings/string_util.h" #include "base/threading/thread.h" #include "base/threading/thread_restrictions.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/chrome_notification_types.h" #include "chrome/browser/prefs/tracked/tracked_preference_validation_delegate.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/profiles/profile_manager.h" #include "chrome/browser/safe_browsing/client_side_detection_service.h" #include "chrome/browser/safe_browsing/database_manager.h" #include "chrome/browser/safe_browsing/download_protection_service.h" #include "chrome/browser/safe_browsing/incident_reporting_service.h" #include "chrome/browser/safe_browsing/malware_details.h" #include "chrome/browser/safe_browsing/ping_manager.h" #include "chrome/browser/safe_browsing/protocol_manager.h" #include "chrome/browser/safe_browsing/safe_browsing_database.h" #include "chrome/browser/safe_browsing/ui_manager.h" #include "chrome/common/chrome_constants.h" #include "chrome/common/chrome_paths.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/pref_names.h" #include "chrome/common/url_constants.h" #include "components/metrics/metrics_service.h" #include "components/startup_metric_utils/startup_metric_utils.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/cookie_crypto_delegate.h" #include "content/public/browser/cookie_store_factory.h" #include "content/public/browser/notification_service.h" #include "net/cookies/cookie_monster.h" #include "net/url_request/url_request_context.h" #include "net/url_request/url_request_context_getter.h" #if defined(OS_WIN) #include "chrome/installer/util/browser_distribution.h" #endif #if defined(OS_ANDROID) #include <string> #include "base/metrics/field_trial.h" #endif using content::BrowserThread; namespace { // Filename suffix for the cookie database. const base::FilePath::CharType kCookiesFile[] = FILE_PATH_LITERAL(" Cookies"); // The default URL prefix where browser fetches chunk updates, hashes, // and reports safe browsing hits and malware details. const char* const kSbDefaultURLPrefix = "https://safebrowsing.google.com/safebrowsing"; // The backup URL prefix used when there are issues establishing a connection // with the server at the primary URL. const char* const kSbBackupConnectErrorURLPrefix = "https://alt1-safebrowsing.google.com/safebrowsing"; // The backup URL prefix used when there are HTTP-specific issues with the // server at the primary URL. const char* const kSbBackupHttpErrorURLPrefix = "https://alt2-safebrowsing.google.com/safebrowsing"; // The backup URL prefix used when there are local network specific issues. const char* const kSbBackupNetworkErrorURLPrefix = "https://alt3-safebrowsing.google.com/safebrowsing"; base::FilePath CookieFilePath() { return base::FilePath( SafeBrowsingService::GetBaseFilename().value() + kCookiesFile); } #if defined(FULL_SAFE_BROWSING) // Returns true if the incident reporting service is enabled via a field trial. bool IsIncidentReportingServiceEnabled() { const std::string group_name = base::FieldTrialList::FindFullName( "SafeBrowsingIncidentReportingService"); return group_name == "Enabled"; } #endif // defined(FULL_SAFE_BROWSING) } // namespace class SafeBrowsingURLRequestContextGetter : public net::URLRequestContextGetter { public: explicit SafeBrowsingURLRequestContextGetter( SafeBrowsingService* sb_service_); // Implementation for net::UrlRequestContextGetter. virtual net::URLRequestContext* GetURLRequestContext() OVERRIDE; virtual scoped_refptr<base::SingleThreadTaskRunner> GetNetworkTaskRunner() const OVERRIDE; protected: virtual ~SafeBrowsingURLRequestContextGetter(); private: SafeBrowsingService* const sb_service_; // Owned by BrowserProcess. scoped_refptr<base::SingleThreadTaskRunner> network_task_runner_; base::debug::LeakTracker<SafeBrowsingURLRequestContextGetter> leak_tracker_; }; SafeBrowsingURLRequestContextGetter::SafeBrowsingURLRequestContextGetter( SafeBrowsingService* sb_service) : sb_service_(sb_service), network_task_runner_( BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO)) { } SafeBrowsingURLRequestContextGetter::~SafeBrowsingURLRequestContextGetter() {} net::URLRequestContext* SafeBrowsingURLRequestContextGetter::GetURLRequestContext() { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); DCHECK(sb_service_->url_request_context_.get()); return sb_service_->url_request_context_.get(); } scoped_refptr<base::SingleThreadTaskRunner> SafeBrowsingURLRequestContextGetter::GetNetworkTaskRunner() const { return network_task_runner_; } // static SafeBrowsingServiceFactory* SafeBrowsingService::factory_ = NULL; // The default SafeBrowsingServiceFactory. Global, made a singleton so we // don't leak it. class SafeBrowsingServiceFactoryImpl : public SafeBrowsingServiceFactory { public: virtual SafeBrowsingService* CreateSafeBrowsingService() OVERRIDE { return new SafeBrowsingService(); } private: friend struct base::DefaultLazyInstanceTraits<SafeBrowsingServiceFactoryImpl>; SafeBrowsingServiceFactoryImpl() { } DISALLOW_COPY_AND_ASSIGN(SafeBrowsingServiceFactoryImpl); }; static base::LazyInstance<SafeBrowsingServiceFactoryImpl>::Leaky g_safe_browsing_service_factory_impl = LAZY_INSTANCE_INITIALIZER; // static base::FilePath SafeBrowsingService::GetCookieFilePathForTesting() { return CookieFilePath(); } // static base::FilePath SafeBrowsingService::GetBaseFilename() { base::FilePath path; bool result = PathService::Get(chrome::DIR_USER_DATA, &path); DCHECK(result); return path.Append(chrome::kSafeBrowsingBaseFilename); } // static SafeBrowsingService* SafeBrowsingService::CreateSafeBrowsingService() { if (!factory_) factory_ = g_safe_browsing_service_factory_impl.Pointer(); return factory_->CreateSafeBrowsingService(); } #if defined(OS_ANDROID) && defined(FULL_SAFE_BROWSING) // static bool SafeBrowsingService::IsEnabledByFieldTrial() { const std::string experiment_name = base::FieldTrialList::FindFullName("SafeBrowsingAndroid"); return experiment_name == "Enabled"; } #endif SafeBrowsingService::SafeBrowsingService() : protocol_manager_(NULL), ping_manager_(NULL), enabled_(false) { } SafeBrowsingService::~SafeBrowsingService() { // We should have already been shut down. If we're still enabled, then the // database isn't going to be closed properly, which could lead to corruption. DCHECK(!enabled_); } void SafeBrowsingService::Initialize() { startup_metric_utils::ScopedSlowStartupUMA scoped_timer("Startup.SlowStartupSafeBrowsingServiceInitialize"); url_request_context_getter_ = new SafeBrowsingURLRequestContextGetter(this); ui_manager_ = CreateUIManager(); database_manager_ = CreateDatabaseManager(); BrowserThread::PostTask( BrowserThread::IO, FROM_HERE, base::Bind( &SafeBrowsingService::InitURLRequestContextOnIOThread, this, make_scoped_refptr(g_browser_process->system_request_context()))); #if defined(FULL_SAFE_BROWSING) #if !defined(OS_ANDROID) if (!CommandLine::ForCurrentProcess()->HasSwitch( switches::kDisableClientSidePhishingDetection)) { csd_service_.reset(safe_browsing::ClientSideDetectionService::Create( url_request_context_getter_.get())); } download_service_.reset(new safe_browsing::DownloadProtectionService( this, url_request_context_getter_.get())); #endif if (IsIncidentReportingServiceEnabled()) { incident_service_.reset(new safe_browsing::IncidentReportingService( this, url_request_context_getter_)); } #endif // Track the safe browsing preference of existing profiles. // The SafeBrowsingService will be started if any existing profile has the // preference enabled. It will also listen for updates to the preferences. ProfileManager* profile_manager = g_browser_process->profile_manager(); if (profile_manager) { std::vector<Profile*> profiles = profile_manager->GetLoadedProfiles(); for (size_t i = 0; i < profiles.size(); ++i) { if (profiles[i]->IsOffTheRecord()) continue; AddPrefService(profiles[i]->GetPrefs()); } } // Track profile creation and destruction. prefs_registrar_.Add(this, chrome::NOTIFICATION_PROFILE_CREATED, content::NotificationService::AllSources()); prefs_registrar_.Add(this, chrome::NOTIFICATION_PROFILE_DESTROYED, content::NotificationService::AllSources()); } void SafeBrowsingService::ShutDown() { // Deletes the PrefChangeRegistrars, whose dtors also unregister |this| as an // observer of the preferences. STLDeleteValues(&prefs_map_); // Remove Profile creation/destruction observers. prefs_registrar_.RemoveAll(); Stop(true); // The IO thread is going away, so make sure the ClientSideDetectionService // dtor executes now since it may call the dtor of URLFetcher which relies // on it. csd_service_.reset(); download_service_.reset(); incident_service_.reset(); url_request_context_getter_ = NULL; BrowserThread::PostNonNestableTask( BrowserThread::IO, FROM_HERE, base::Bind(&SafeBrowsingService::DestroyURLRequestContextOnIOThread, this)); } // Binhash verification is only enabled for UMA users for now. bool SafeBrowsingService::DownloadBinHashNeeded() const { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); #if defined(FULL_SAFE_BROWSING) return (database_manager_->download_protection_enabled() && ui_manager_->CanReportStats()) || (download_protection_service() && download_protection_service()->enabled()); #else return false; #endif } net::URLRequestContextGetter* SafeBrowsingService::url_request_context() { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); return url_request_context_getter_.get(); } const scoped_refptr<SafeBrowsingUIManager>& SafeBrowsingService::ui_manager() const { return ui_manager_; } const scoped_refptr<SafeBrowsingDatabaseManager>& SafeBrowsingService::database_manager() const { return database_manager_; } SafeBrowsingProtocolManager* SafeBrowsingService::protocol_manager() const { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); return protocol_manager_; } SafeBrowsingPingManager* SafeBrowsingService::ping_manager() const { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); return ping_manager_; } scoped_ptr<TrackedPreferenceValidationDelegate> SafeBrowsingService::CreatePreferenceValidationDelegate( Profile* profile) const { #if defined(FULL_SAFE_BROWSING) if (incident_service_) return incident_service_->CreatePreferenceValidationDelegate(profile); #endif return scoped_ptr<TrackedPreferenceValidationDelegate>(); } SafeBrowsingUIManager* SafeBrowsingService::CreateUIManager() { return new SafeBrowsingUIManager(this); } SafeBrowsingDatabaseManager* SafeBrowsingService::CreateDatabaseManager() { #if defined(FULL_SAFE_BROWSING) return new SafeBrowsingDatabaseManager(this); #else return NULL; #endif } void SafeBrowsingService::InitURLRequestContextOnIOThread( net::URLRequestContextGetter* system_url_request_context_getter) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); DCHECK(!url_request_context_.get()); scoped_refptr<net::CookieStore> cookie_store( content::CreateCookieStore( content::CookieStoreConfig( CookieFilePath(), content::CookieStoreConfig::EPHEMERAL_SESSION_COOKIES, NULL, NULL))); url_request_context_.reset(new net::URLRequestContext); // |system_url_request_context_getter| may be NULL during tests. if (system_url_request_context_getter) { url_request_context_->CopyFrom( system_url_request_context_getter->GetURLRequestContext()); } url_request_context_->set_cookie_store(cookie_store.get()); } void SafeBrowsingService::DestroyURLRequestContextOnIOThread() { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); url_request_context_->AssertNoURLRequests(); // Need to do the CheckForLeaks on IOThread instead of in ShutDown where // url_request_context_getter_ is cleared, since the URLRequestContextGetter // will PostTask to IOTread to delete itself. using base::debug::LeakTracker; LeakTracker<SafeBrowsingURLRequestContextGetter>::CheckForLeaks(); url_request_context_.reset(); } SafeBrowsingProtocolConfig SafeBrowsingService::GetProtocolConfig() const { SafeBrowsingProtocolConfig config; // On Windows, get the safe browsing client name from the browser // distribution classes in installer util. These classes don't yet have // an analog on non-Windows builds so just keep the name specified here. #if defined(OS_WIN) BrowserDistribution* dist = BrowserDistribution::GetDistribution(); config.client_name = dist->GetSafeBrowsingName(); #else #if defined(GOOGLE_CHROME_BUILD) config.client_name = "googlechrome"; #else config.client_name = "chromium"; #endif // Mark client string to allow server to differentiate mobile. #if defined(OS_ANDROID) config.client_name.append("-a"); #elif defined(OS_IOS) config.client_name.append("-i"); #endif #endif // defined(OS_WIN) CommandLine* cmdline = CommandLine::ForCurrentProcess(); config.disable_auto_update = cmdline->HasSwitch(switches::kSbDisableAutoUpdate) || cmdline->HasSwitch(switches::kDisableBackgroundNetworking); config.url_prefix = kSbDefaultURLPrefix; config.backup_connect_error_url_prefix = kSbBackupConnectErrorURLPrefix; config.backup_http_error_url_prefix = kSbBackupHttpErrorURLPrefix; config.backup_network_error_url_prefix = kSbBackupNetworkErrorURLPrefix; return config; } void SafeBrowsingService::StartOnIOThread( net::URLRequestContextGetter* url_request_context_getter) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); if (enabled_) return; enabled_ = true; SafeBrowsingProtocolConfig config = GetProtocolConfig(); #if defined(FULL_SAFE_BROWSING) DCHECK(database_manager_.get()); database_manager_->StartOnIOThread(); DCHECK(!protocol_manager_); protocol_manager_ = SafeBrowsingProtocolManager::Create( database_manager_.get(), url_request_context_getter, config); protocol_manager_->Initialize(); #endif DCHECK(!ping_manager_); ping_manager_ = SafeBrowsingPingManager::Create( url_request_context_getter, config); } void SafeBrowsingService::StopOnIOThread(bool shutdown) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); #if defined(FULL_SAFE_BROWSING) database_manager_->StopOnIOThread(shutdown); #endif ui_manager_->StopOnIOThread(shutdown); if (enabled_) { enabled_ = false; #if defined(FULL_SAFE_BROWSING) // This cancels all in-flight GetHash requests. Note that database_manager_ // relies on the protocol_manager_ so if the latter is destroyed, the // former must be stopped. delete protocol_manager_; protocol_manager_ = NULL; #endif delete ping_manager_; ping_manager_ = NULL; } } void SafeBrowsingService::Start() { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); BrowserThread::PostTask( BrowserThread::IO, FROM_HERE, base::Bind(&SafeBrowsingService::StartOnIOThread, this, url_request_context_getter_)); } void SafeBrowsingService::Stop(bool shutdown) { BrowserThread::PostTask( BrowserThread::IO, FROM_HERE, base::Bind(&SafeBrowsingService::StopOnIOThread, this, shutdown)); } void SafeBrowsingService::Observe(int type, const content::NotificationSource& source, const content::NotificationDetails& details) { switch (type) { case chrome::NOTIFICATION_PROFILE_CREATED: { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); Profile* profile = content::Source<Profile>(source).ptr(); if (!profile->IsOffTheRecord()) AddPrefService(profile->GetPrefs()); break; } case chrome::NOTIFICATION_PROFILE_DESTROYED: { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); Profile* profile = content::Source<Profile>(source).ptr(); if (!profile->IsOffTheRecord()) RemovePrefService(profile->GetPrefs()); break; } default: NOTREACHED(); } } void SafeBrowsingService::AddPrefService(PrefService* pref_service) { DCHECK(prefs_map_.find(pref_service) == prefs_map_.end()); PrefChangeRegistrar* registrar = new PrefChangeRegistrar(); registrar->Init(pref_service); registrar->Add(prefs::kSafeBrowsingEnabled, base::Bind(&SafeBrowsingService::RefreshState, base::Unretained(this))); prefs_map_[pref_service] = registrar; RefreshState(); } void SafeBrowsingService::RemovePrefService(PrefService* pref_service) { if (prefs_map_.find(pref_service) != prefs_map_.end()) { delete prefs_map_[pref_service]; prefs_map_.erase(pref_service); RefreshState(); } else { NOTREACHED(); } } void SafeBrowsingService::RefreshState() { // Check if any profile requires the service to be active. bool enable = false; std::map<PrefService*, PrefChangeRegistrar*>::iterator iter; for (iter = prefs_map_.begin(); iter != prefs_map_.end(); ++iter) { if (iter->first->GetBoolean(prefs::kSafeBrowsingEnabled)) { enable = true; break; } } if (enable) Start(); else Stop(false); #if defined(FULL_SAFE_BROWSING) if (csd_service_) csd_service_->SetEnabledAndRefreshState(enable); if (download_service_) download_service_->SetEnabled(enable); #endif }
[ "jhonnyjosearana@gmail.com" ]
jhonnyjosearana@gmail.com
5052e6fcd14725aeb65999d4debdf12400e42f93
0c360ce74a4b3f08457dd354a6d1ed70a80a7265
/src/components/application_manager/include/application_manager/commands/mobile/delete_file_request.h
adaf2686bc3c2be906450e8759910ecccb5605cf
[]
permissive
APCVSRepo/sdl_implementation_reference
917ef886c7d053b344740ac4fc3d65f91b474b42
19be0eea481a8c05530048c960cce7266a39ccd0
refs/heads/master
2021-01-24T07:43:52.766347
2017-10-22T14:31:21
2017-10-22T14:31:21
93,353,314
4
3
BSD-3-Clause
2022-10-09T06:51:42
2017-06-05T01:34:12
C++
UTF-8
C++
false
false
2,678
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_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_COMMANDS_DELETE_FILE_REQUEST_H_ #define SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_COMMANDS_DELETE_FILE_REQUEST_H_ #include "application_manager/commands/command_request_impl.h" #include "utils/macro.h" namespace application_manager { struct AppFile; namespace commands { /** * @brief DeleteFileRequest command class **/ class DeleteFileRequest : public CommandRequestImpl { public: /** * @brief DeleteFileRequest class constructor * * @param message Incoming SmartObject message **/ DeleteFileRequest(const MessageSharedPtr& message, ApplicationManager& application_manager); /** * @brief DeleteFileRequest class destructor **/ virtual ~DeleteFileRequest(); /** * @brief Execute command **/ virtual void Run(); private: DISALLOW_COPY_AND_ASSIGN(DeleteFileRequest); void SendFileRemovedNotification(const AppFile* file) const; }; } // namespace commands } // namespace application_manager #endif // SRC_COMPONENTS_APPLICATION_MANAGER_INCLUDE_APPLICATION_MANAGER_COMMANDS_DELETE_FILE_REQUEST_H_
[ "luwanjia@aliyun.com" ]
luwanjia@aliyun.com
d919868f6d663ca7e4613872faa17caaf4c0c25a
bf42d70a79cc2721ad528d8a9c9c9aea2711d91a
/chrome/browser/background_fetch/background_fetch_delegate_impl.cc
b64adcb71a4b706cb82e4bcaee5e805cd1f5b70f
[ "BSD-3-Clause" ]
permissive
aikuimail/chromium
d2a630e7877c7ae4176cec3aff3f98426e68fc77
3964dbae965aa9bcc02c78aaa3fbbca98d8d51ec
refs/heads/master
2023-03-17T22:41:57.541727
2018-07-26T23:05:22
2018-07-26T23:05:22
141,418,907
0
0
null
2018-07-18T10:22:04
2018-07-18T10:22:03
null
UTF-8
C++
false
false
19,685
cc
// Copyright 2017 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/background_fetch/background_fetch_delegate_impl.h" #include <utility> #include "base/bind.h" #include "base/guid.h" #include "base/logging.h" #include "base/strings/string_util.h" #include "base/strings/stringprintf.h" #include "build/build_config.h" #include "chrome/browser/download/download_service_factory.h" #include "chrome/browser/offline_items_collection/offline_content_aggregator_factory.h" #include "chrome/browser/profiles/profile.h" #include "components/download/public/background_service/download_params.h" #include "components/download/public/background_service/download_service.h" #include "components/offline_items_collection/core/offline_content_aggregator.h" #include "components/offline_items_collection/core/offline_item.h" #include "content/public/browser/background_fetch_description.h" #include "content/public/browser/background_fetch_response.h" #include "content/public/browser/browser_thread.h" #include "third_party/skia/include/core/SkBitmap.h" #include "ui/gfx/geometry/size.h" #include "ui/gfx/image/image_skia.h" BackgroundFetchDelegateImpl::BackgroundFetchDelegateImpl(Profile* profile) : download_service_( DownloadServiceFactory::GetInstance()->GetForBrowserContext(profile)), offline_content_aggregator_( OfflineContentAggregatorFactory::GetForBrowserContext(profile)), weak_ptr_factory_(this) { offline_content_aggregator_->RegisterProvider("background_fetch", this); } BackgroundFetchDelegateImpl::~BackgroundFetchDelegateImpl() {} void BackgroundFetchDelegateImpl::Shutdown() { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); if (client()) { client()->OnDelegateShutdown(); } } BackgroundFetchDelegateImpl::JobDetails::JobDetails(JobDetails&&) = default; BackgroundFetchDelegateImpl::JobDetails::JobDetails( std::unique_ptr<content::BackgroundFetchDescription> fetch_description) : cancelled(false), offline_item(offline_items_collection::ContentId( "background_fetch", fetch_description->job_unique_id)), fetch_description(std::move(fetch_description)) { UpdateOfflineItem(); } BackgroundFetchDelegateImpl::JobDetails::~JobDetails() = default; void BackgroundFetchDelegateImpl::JobDetails::UpdateOfflineItem() { DCHECK_GT(fetch_description->total_parts, 0); if (ShouldReportProgressBySize()) { offline_item.progress.value = fetch_description->completed_parts_size; // If we have completed all downloads, update progress max to // completed_parts_size in case total_parts_size was set too high. This // avoid unnecessary jumping in the progress bar. offline_item.progress.max = (fetch_description->completed_parts == fetch_description->total_parts) ? fetch_description->completed_parts_size : fetch_description->total_parts_size; } else { offline_item.progress.value = fetch_description->completed_parts; offline_item.progress.max = fetch_description->total_parts; } offline_item.progress.unit = offline_items_collection::OfflineItemProgressUnit::PERCENTAGE; if (fetch_description->title.empty()) { offline_item.title = fetch_description->origin.Serialize(); } else { // TODO(crbug.com/774612): Make sure that the origin is displayed completely // in all cases so that long titles cannot obscure it. offline_item.title = base::StringPrintf("%s (%s)", fetch_description->title.c_str(), fetch_description->origin.Serialize().c_str()); } // TODO(delphick): Figure out what to put in offline_item.description. offline_item.is_transient = true; using OfflineItemState = offline_items_collection::OfflineItemState; if (cancelled) { offline_item.state = OfflineItemState::CANCELLED; } else if (fetch_description->completed_parts == fetch_description->total_parts) { // This includes cases when the download failed, or completed but the // response was an HTTP error, e.g. 404. offline_item.state = OfflineItemState::COMPLETE; offline_item.is_openable = true; } else { offline_item.state = OfflineItemState::IN_PROGRESS; } // TODO(crbug.com/865063): Update the icon. } bool BackgroundFetchDelegateImpl::JobDetails::ShouldReportProgressBySize() { if (!fetch_description->total_parts_size) { // total_parts_size was not set. Cannot report by size. return false; } if (fetch_description->completed_parts < fetch_description->total_parts && fetch_description->completed_parts_size > fetch_description->total_parts_size) { // total_parts_size was set too low. return false; } return true; } void BackgroundFetchDelegateImpl::GetIconDisplaySize( BackgroundFetchDelegate::GetIconDisplaySizeCallback callback) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); // If Android, return 192x192, else return 0x0. 0x0 means not loading an // icon at all, which is returned for all non-Android platforms as the // icons can't be displayed on the UI yet. // TODO(nator): Move this logic to OfflineItemsCollection, and return icon // size based on display. gfx::Size display_size; #if defined(OS_ANDROID) display_size = gfx::Size(192, 192); #endif std::move(callback).Run(display_size); } void BackgroundFetchDelegateImpl::CreateDownloadJob( std::unique_ptr<content::BackgroundFetchDescription> fetch_description) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); std::string job_unique_id = fetch_description->job_unique_id; DCHECK(!job_details_map_.count(job_unique_id)); auto emplace_result = job_details_map_.emplace( job_unique_id, JobDetails(std::move(fetch_description))); const JobDetails& details = emplace_result.first->second; for (const auto& download_guid : details.fetch_description->current_guids) { DCHECK(!download_job_unique_id_map_.count(download_guid)); download_job_unique_id_map_.emplace(download_guid, job_unique_id); download_service_->ResumeDownload(download_guid); } for (auto* observer : observers_) { observer->OnItemsAdded({details.offline_item}); } } void BackgroundFetchDelegateImpl::DownloadUrl( const std::string& job_unique_id, const std::string& download_guid, const std::string& method, const GURL& url, const net::NetworkTrafficAnnotationTag& traffic_annotation, const net::HttpRequestHeaders& headers) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); DCHECK(job_details_map_.count(job_unique_id)); DCHECK(!download_job_unique_id_map_.count(download_guid)); JobDetails& job_details = job_details_map_.find(job_unique_id)->second; job_details.current_download_guids.insert(download_guid); download_job_unique_id_map_.emplace(download_guid, job_unique_id); download::DownloadParams params; params.guid = download_guid; params.client = download::DownloadClient::BACKGROUND_FETCH; params.request_params.method = method; params.request_params.url = url; params.request_params.request_headers = headers; params.callback = base::Bind(&BackgroundFetchDelegateImpl::OnDownloadReceived, weak_ptr_factory_.GetWeakPtr()); params.traffic_annotation = net::MutableNetworkTrafficAnnotationTag(traffic_annotation); download_service_->StartDownload(params); } void BackgroundFetchDelegateImpl::Abort(const std::string& job_unique_id) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); auto job_details_iter = job_details_map_.find(job_unique_id); if (job_details_iter == job_details_map_.end()) return; JobDetails& job_details = job_details_iter->second; job_details.cancelled = true; for (const auto& download_guid : job_details.current_download_guids) { download_service_->CancelDownload(download_guid); download_job_unique_id_map_.erase(download_guid); } UpdateOfflineItemAndUpdateObservers(&job_details); job_details_map_.erase(job_details_iter); } void BackgroundFetchDelegateImpl::UpdateUI( const std::string& job_unique_id, const base::Optional<std::string>& title, const base::Optional<SkBitmap>& icon) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); DCHECK(title || icon); // One of the UI options must be updatable. DCHECK(!icon || !icon->isNull()); // The |icon|, if provided, is not null. auto job_details_iter = job_details_map_.find(job_unique_id); if (job_details_iter == job_details_map_.end()) return; JobDetails& job_details = job_details_iter->second; // Update the title, if it's different. if (title && job_details.fetch_description->title != *title) job_details.fetch_description->title = *title; if (icon) job_details.fetch_description->icon = *icon; UpdateOfflineItemAndUpdateObservers(&job_details); } void BackgroundFetchDelegateImpl::OnDownloadStarted( const std::string& download_guid, std::unique_ptr<content::BackgroundFetchResponse> response) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); auto download_job_unique_id_iter = download_job_unique_id_map_.find(download_guid); // TODO(crbug.com/779012): When DownloadService fixes cancelled jobs calling // OnDownload* methods, then this can be a DCHECK. if (download_job_unique_id_iter == download_job_unique_id_map_.end()) return; const std::string& job_unique_id = download_job_unique_id_iter->second; if (client()) { client()->OnDownloadStarted(job_unique_id, download_guid, std::move(response)); } } void BackgroundFetchDelegateImpl::OnDownloadUpdated( const std::string& download_guid, uint64_t bytes_downloaded) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); auto download_job_unique_id_iter = download_job_unique_id_map_.find(download_guid); // TODO(crbug.com/779012): When DownloadService fixes cancelled jobs calling // OnDownload* methods, then this can be a DCHECK. if (download_job_unique_id_iter == download_job_unique_id_map_.end()) return; const std::string& job_unique_id = download_job_unique_id_iter->second; // This will update the progress bar. DCHECK(job_details_map_.count(job_unique_id)); JobDetails& job_details = job_details_map_.find(job_unique_id)->second; job_details.fetch_description->completed_parts_size = bytes_downloaded; if (job_details.fetch_description->total_parts_size && job_details.fetch_description->total_parts_size < job_details.fetch_description->completed_parts_size) { // Fail the fetch if total download size was set too low. // We only do this if total download size is specified. If not specified, // this check is skipped. This is to allow for situations when the // total download size cannot be known when invoking fetch. FailFetch(job_unique_id); return; } UpdateOfflineItemAndUpdateObservers(&job_details); if (client()) client()->OnDownloadUpdated(job_unique_id, download_guid, bytes_downloaded); } void BackgroundFetchDelegateImpl::OnDownloadFailed( const std::string& download_guid, download::Client::FailureReason reason) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); using FailureReason = content::BackgroundFetchResult::FailureReason; FailureReason failure_reason; auto download_job_unique_id_iter = download_job_unique_id_map_.find(download_guid); // TODO(crbug.com/779012): When DownloadService fixes cancelled jobs // potentially calling OnDownloadFailed with a reason other than // CANCELLED/ABORTED, we should add a DCHECK here. if (download_job_unique_id_iter == download_job_unique_id_map_.end()) return; const std::string& job_unique_id = download_job_unique_id_iter->second; JobDetails& job_details = job_details_map_.find(job_unique_id)->second; ++job_details.fetch_description->completed_parts; UpdateOfflineItemAndUpdateObservers(&job_details); switch (reason) { case download::Client::FailureReason::NETWORK: failure_reason = FailureReason::NETWORK; break; case download::Client::FailureReason::TIMEDOUT: failure_reason = FailureReason::TIMEDOUT; break; case download::Client::FailureReason::UNKNOWN: failure_reason = FailureReason::UNKNOWN; break; case download::Client::FailureReason::ABORTED: case download::Client::FailureReason::CANCELLED: // The client cancelled or aborted it so no need to notify it. return; default: NOTREACHED(); return; } // TODO(delphick): consider calling OnItemUpdated here as well if for instance // the download actually happened but 404ed. if (client()) { client()->OnDownloadComplete( job_unique_id, download_guid, std::make_unique<content::BackgroundFetchResult>(base::Time::Now(), failure_reason)); } job_details.current_download_guids.erase( job_details.current_download_guids.find(download_guid)); download_job_unique_id_map_.erase(download_guid); } void BackgroundFetchDelegateImpl::OnDownloadSucceeded( const std::string& download_guid, const base::FilePath& path, uint64_t size) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); auto download_job_unique_id_iter = download_job_unique_id_map_.find(download_guid); // TODO(crbug.com/779012): When DownloadService fixes cancelled jobs calling // OnDownload* methods, then this can be a DCHECK. if (download_job_unique_id_iter == download_job_unique_id_map_.end()) return; const std::string& job_unique_id = download_job_unique_id_iter->second; JobDetails& job_details = job_details_map_.find(job_unique_id)->second; ++job_details.fetch_description->completed_parts; job_details.fetch_description->completed_parts_size = size; UpdateOfflineItemAndUpdateObservers(&job_details); if (client()) { client()->OnDownloadComplete( job_unique_id, download_guid, std::make_unique<content::BackgroundFetchResult>( base::Time::Now(), path, base::nullopt /* blob_handle */, size)); } job_details.current_download_guids.erase( job_details.current_download_guids.find(download_guid)); download_job_unique_id_map_.erase(download_guid); } void BackgroundFetchDelegateImpl::OnDownloadReceived( const std::string& download_guid, download::DownloadParams::StartResult result) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); using StartResult = download::DownloadParams::StartResult; switch (result) { case StartResult::ACCEPTED: // Nothing to do. break; case StartResult::BACKOFF: // TODO(delphick): try again later? NOTREACHED(); break; case StartResult::UNEXPECTED_CLIENT: // This really should never happen since we're supplying the // DownloadClient. NOTREACHED(); break; case StartResult::UNEXPECTED_GUID: // TODO(delphick): try again with a different GUID. NOTREACHED(); break; case StartResult::CLIENT_CANCELLED: // TODO(delphick): do we need to do anything here, since we will have // cancelled it? break; case StartResult::INTERNAL_ERROR: // TODO(delphick): We need to handle this gracefully. NOTREACHED(); break; case StartResult::COUNT: NOTREACHED(); break; } } // Much of the code in offline_item_collection is not re-entrant, so this should // not be called from any of the OfflineContentProvider-inherited methods. void BackgroundFetchDelegateImpl::UpdateOfflineItemAndUpdateObservers( JobDetails* job_details) { job_details->UpdateOfflineItem(); for (auto* observer : observers_) observer->OnItemUpdated(job_details->offline_item); } void BackgroundFetchDelegateImpl::OpenItem( const offline_items_collection::ContentId& id) { if (client()) client()->OnUIActivated(id.id); } void BackgroundFetchDelegateImpl::RemoveItem( const offline_items_collection::ContentId& id) { // TODO(delphick): Support removing items. (Not sure when this would actually // get called though). NOTIMPLEMENTED(); } void BackgroundFetchDelegateImpl::FailFetch(const std::string& job_unique_id) { // Save a copy before Abort() deletes the reference. const std::string unique_id = job_unique_id; Abort(job_unique_id); if (client()) { client()->OnJobCancelled( unique_id, content::BackgroundFetchReasonToAbort::TOTAL_DOWNLOAD_SIZE_EXCEEDED); } } void BackgroundFetchDelegateImpl::CancelDownload( const offline_items_collection::ContentId& id) { Abort(id.id); if (client()) { client()->OnJobCancelled( id.id, content::BackgroundFetchReasonToAbort::CANCELLED_FROM_UI); } } void BackgroundFetchDelegateImpl::PauseDownload( const offline_items_collection::ContentId& id) { auto job_details_iter = job_details_map_.find(id.id); if (job_details_iter == job_details_map_.end()) return; JobDetails& job_details = job_details_iter->second; for (auto& download_guid : job_details.current_download_guids) download_service_->PauseDownload(download_guid); // TODO(delphick): Mark overall download job as paused so that future // downloads are not started until resume. (Initially not a worry because only // one download will be scheduled at a time). } void BackgroundFetchDelegateImpl::ResumeDownload( const offline_items_collection::ContentId& id, bool has_user_gesture) { auto job_details_iter = job_details_map_.find(id.id); if (job_details_iter == job_details_map_.end()) return; JobDetails& job_details = job_details_iter->second; for (auto& download_guid : job_details.current_download_guids) download_service_->ResumeDownload(download_guid); // TODO(delphick): Start new downloads that weren't started because of pause. } void BackgroundFetchDelegateImpl::GetItemById( const offline_items_collection::ContentId& id, SingleItemCallback callback) { auto it = job_details_map_.find(id.id); base::Optional<offline_items_collection::OfflineItem> offline_item; if (it != job_details_map_.end()) offline_item = it->second.offline_item; base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::BindOnce(std::move(callback), offline_item)); } void BackgroundFetchDelegateImpl::GetAllItems(MultipleItemCallback callback) { OfflineItemList item_list; for (auto& entry : job_details_map_) item_list.push_back(entry.second.offline_item); base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::BindOnce(std::move(callback), item_list)); } void BackgroundFetchDelegateImpl::GetVisualsForItem( const offline_items_collection::ContentId& id, const VisualsCallback& callback) { // GetVisualsForItem mustn't be called directly since offline_items_collection // is not re-entrant and it must be called even if there are no visuals. auto visuals = std::make_unique<offline_items_collection::OfflineItemVisuals>(); auto it = job_details_map_.find(id.id); if (it != job_details_map_.end()) { visuals->icon = gfx::Image::CreateFrom1xBitmap(it->second.fetch_description->icon); } base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::BindOnce(callback, id, std::move(visuals))); } void BackgroundFetchDelegateImpl::AddObserver(Observer* observer) { DCHECK(!observers_.count(observer)); observers_.insert(observer); } void BackgroundFetchDelegateImpl::RemoveObserver(Observer* observer) { observers_.erase(observer); }
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
f24454fd9eb700c15df3d5c4fba01967933f6cef
86313bc995d91a485592990d0e7b1aff7f49de1a
/anrobot/src/inv_kinematics.cpp
d784cf5ec72edd7c20544f2a4831136e5a337191
[]
no_license
mingless/ANRO
3265648694531a19f634310eaac244f3d3dafc7d
0e5ea0feb14a10bc401909e29a4f0804680d9247
refs/heads/master
2021-01-11T01:23:40.890287
2017-01-13T10:44:57
2017-01-13T10:44:57
70,685,784
0
2
null
null
null
null
UTF-8
C++
false
false
2,572
cpp
#include <ros/ros.h> #include <sensor_msgs/JointState.h> #include <geometry_msgs/Point.h> #include <anrobot/InvKinematics.h> #include <anrobot/SetTarget.h> #include <math.h> class States { private: ros::NodeHandle n; ros::Publisher target_pub; ros::ServiceServer inv_kin, set_end_target; public: States() { inv_kin = n.advertiseService("inv_kinematics", &States::get_states, this); set_end_target = n.advertiseService("set_end_target", &States::set_target, this); target_pub = n.advertise<geometry_msgs::Point>("target_end", 1); } bool get_states(anrobot::InvKinematics::Request &req, anrobot::InvKinematics::Response &res) { res.success = false; sensor_msgs::JointState state; state.name.push_back("joint1"); state.name.push_back("joint2"); state.name.push_back("joint3"); for (int i = 0; i < 3; ++i) { state.effort.push_back(0); state.velocity.push_back(0); } double x = req.point.x; double y = req.point.y; double z = req.point.z; double a = 2; double b = 1; double eq = 1 - pow((x*x + y*y - a*a - b*b) / (2*a*b), 2); if(!is_valid(req.point)) { ROS_ERROR_STREAM_THROTTLE(5, "Invalid target position\n" << x << " " << y << " " << z <<"\n"); return false; } else { ROS_INFO_STREAM("Target set to: [" << x << ", " << y << ", " << z << "]."); } double theta2 = atan2(sqrt(eq),(x*x + y*y - a*a - b*b) / (2*a*b)); double theta1 = atan2(y,x) - atan2(b*sin(theta2), a + b*cos(theta2)); double d3 = -z; state.position.push_back(theta1); state.position.push_back(theta2); state.position.push_back(d3); res.states = state; res.success = true; return true; } bool is_valid(const geometry_msgs::Point &t) { // target_position double a = 2, b = 1; double eq = 1 - pow((t.x*t.x + t.y*t.y - a*a - b*b) / (2*a*b), 2); if(t.z < -3. || t.z > -0.3 || eq < 0) { return false; } return true; } bool set_target(anrobot::SetTarget::Request &req, anrobot::SetTarget::Response &res) { res.success = false; target_pub.publish(req.point); res.success = true; return true; } }; int main(int argc, char** argv) { ros::init(argc, argv, "inv_kinematics"); States state; ros::spin(); return 0; }
[ "mateusz.dziwulski@gmail.com" ]
mateusz.dziwulski@gmail.com
9a90e437445fba142c90e75cc90cebbf3ece9c50
e77875e7b17ff555b1b2eb67fb708ec9015c1a37
/CSE_CSUSB/cse520/project/pokemon_bkp.cpp
a7f238d83ead0bf96a34a7b30592ccc26fa19c02
[]
no_license
AndyGaming/Andrew_Repo
5380070104c203a5100b7d5a5502aea0dae21097
8bce29982a31197b9c39f785098d9dbd34def6a2
refs/heads/master
2021-01-21T12:15:30.182902
2018-02-23T01:41:29
2018-02-23T01:41:29
102,053,193
0
0
null
null
null
null
UTF-8
C++
false
false
18,695
cpp
/******************************************************************************************** Matching Pokemon game Programmer: Yazhuo Liu Samuel Moreno This program used a template program. The template program is the simpletex.cpp program wrote by Dr. T.L.Yu (2009). ********************************************************************************************/ #include <stdlib.h> #include <stdio.h> #include <string.h> #include <fcntl.h> #include <sys/types.h> #include <unistd.h> #include <vector> #include <iostream> #define GLEW_STATIC 1 #include <GL/glew.h> #include <GL/glu.h> #include <GL/glut.h> #include "imageio.h" using namespace std; GLuint programObject = 0; GLuint vertexShaderObject = 0; GLuint fragmentShaderObject = 0; static GLint window = 0; int right_lower= 0, right_upper = 0, left_lower = 0, left_upper = 0; //check1 = 0, check2 = 0; int win, start_game, count; int objectType = 0; GLuint texName1, texName2, texNameB, texNameW, texNameS; GLuint timeParam; vector<int> v; int iWidth = 64, iHeight = 64; /* static GLubyte checkImage[iHeight][iWidth][3]; void makeCheckImage(void) { int i, j, c; for (i = 0; i < iWidth; i++) { for (j = 0; j < iHeight; j++) { c = ((((i&0x8)==0)^((j&0x8))==0))*255; checkImage[i][j][0] = (GLubyte) c; checkImage[i][j][1] = (GLubyte) c; checkImage[i][j][2] = (GLubyte) c; } } } */ GLubyte* makeTexImage( char *loadfile ) { int i, j, c, width, height; GLubyte *texImage; texImage = loadImageRGBA( (char *) loadfile, &width, &height); iWidth = width; iHeight = height; return texImage; } void init2DTexture() { // makeCheckImage(); //char filename[100]; //printf("Enter png file name: "); //scanf ("%s", filename ); //GLubyte *texImage = makeTexImage( "front.png" ); //GLubyte *texImage = makeTexImage( filename ); GLubyte *texImage_1 = makeTexImage( "pic1.png" ); /* if ( !texImage ) { printf("\nError reading %s \n", filename ); exit(1); } */ glGenTextures(1, &texName1); glBindTexture(GL_TEXTURE_2D, texName1); //now we work on texName glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexImage2D( GL_TEXTURE_2D, 0, GL_RGBA, iWidth, iHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, texImage_1); GLubyte *texImage_2 = makeTexImage( "pic2.png" ); glGenTextures(1, &texName2); glBindTexture(GL_TEXTURE_2D, texName2); //now we work on texName glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexImage2D( GL_TEXTURE_2D, 0, GL_RGBA, iWidth, iHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, texImage_2); GLubyte *texImage_back = makeTexImage( "back.png" ); glGenTextures(1, &texNameB); glBindTexture(GL_TEXTURE_2D, texNameB); //now we work on texName glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexImage2D( GL_TEXTURE_2D, 0, GL_RGBA, iWidth, iHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, texImage_back); GLubyte *texImage_win = makeTexImage( "win.png" ); glGenTextures(1, &texNameW); glBindTexture(GL_TEXTURE_2D, texNameW); //now we work on texName glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexImage2D( GL_TEXTURE_2D, 0, GL_RGBA, iWidth, iHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, texImage_win); GLubyte *texImage_suck = makeTexImage( "suck.png" ); glGenTextures(1, &texNameS); glBindTexture(GL_TEXTURE_2D, texNameS); //now we work on texName glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexImage2D( GL_TEXTURE_2D, 0, GL_RGBA, iWidth, iHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, texImage_suck); delete texImage_1; delete texImage_2; delete texImage_back; delete texImage_win; delete texImage_suck; } int readShaderSource(char *fileName, GLchar **shader ) { // Allocate memory to hold the source of our shaders. FILE *fp; int count, pos, shaderSize; fp = fopen( fileName, "r"); if ( !fp ) return 0; pos = (int) ftell ( fp ); fseek ( fp, 0, SEEK_END ); //move to end shaderSize = ( int ) ftell ( fp ) - pos; //calculates file size fseek ( fp, 0, SEEK_SET ); //rewind to beginning if ( shaderSize <= 0 ){ printf("Shader %s empty\n", fileName); return 0; } *shader = (GLchar *) malloc( shaderSize + 1); // Read the source code count = (int) fread(*shader, 1, shaderSize, fp); (*shader)[count] = '\0'; if (ferror(fp)) count = 0; fclose(fp); return 1; } // public int installShaders(const GLchar *vertex, const GLchar *fragment) { GLint vertCompiled, fragCompiled; // status values GLint linked; // Create a vertex shader object and a fragment shader object vertexShaderObject = glCreateShader(GL_VERTEX_SHADER); fragmentShaderObject = glCreateShader(GL_FRAGMENT_SHADER); // Load source code strings into shaders, compile and link glShaderSource(vertexShaderObject, 1, &vertex, NULL); glShaderSource(fragmentShaderObject, 1, &fragment, NULL); glCompileShader(vertexShaderObject); glGetShaderiv(vertexShaderObject, GL_COMPILE_STATUS, &vertCompiled); glCompileShader( fragmentShaderObject ); glGetShaderiv( fragmentShaderObject, GL_COMPILE_STATUS, &fragCompiled); if (!vertCompiled || !fragCompiled) return 0; // Create a program object and attach the two compiled shaders programObject = glCreateProgram(); glAttachShader( programObject, vertexShaderObject); glAttachShader( programObject, fragmentShaderObject); // Link the program object glLinkProgram(programObject); glGetProgramiv(programObject, GL_LINK_STATUS, &linked); if (!linked) return 0; // Install program object as part of current state glUseProgram(programObject); // Set up initial uniform values glUniform3f(glGetUniformLocation(programObject, "LightPosition"), 2.0, 2.0, 4.0); glUniform1i(glGetUniformLocation(programObject, "texHandle"), 0); return 1; } void print( float x, float y, char *st) { int l,i; l = strlen( st ); glRasterPos2f( x, y ); for(i = 0; i < l; i++) glutBitmapCharacter(GLUT_BITMAP_TIMES_ROMAN_24, st[i]); } /* void init_game(void) { //SDL_Delay(2000); win = 0; //SDL_Delay(2000); start_game = 1; //SDL_Delay(2000); //show = 1; //print(-0.5, 0, "GAME STARTED"); //right_lower = right_upper = left_lower = left_upper = 0; } */ int check_win(vector<int> & v) { //int count = 0; if (left_lower != 0 && left_upper != 0 && right_lower != 0 && right_upper != 0) { //sleep(1); return 1; } if (v.size() < 2) return 0; //if (count == 2) return 1; else { if (v[0] == v[1]) { while (v.size() > 0) v.pop_back(); //v.pop_back(); //v.pop_back(); //count++; return 0; } if (v[0] != v[1]) { while (v.size() > 0) v.pop_back(); //v.pop_back(); //v.pop_back(); start_game = 0; return 2; } } //if (count == 1) return 1; //if (v.size() == 0) return 1; //if (left_lower == 1 && left_upper == 1 && right_lower == 1 && right_upper == 1) return 1; /* if (a != b && (a==1 || a==2) && (b==1 || b==2)) { start_game = 0; return 2; } else if (a == b) a = b = 0; return 0; */ } int init(void) { const char *version; GLchar *VertexShaderSource, *FragmentShaderSource; int loadstatus = 0; version = (const char *) glGetString(GL_VERSION); if (version[0] < '2' || version[1] != '.') { printf("This program requires OpenGL >= 2.x, found %s\n", version); exit(1); } glDepthFunc(GL_LESS); glEnable(GL_DEPTH_TEST); glClearColor(1.0f, 1.0f, 1.0f, 1.0f); win = start_game = count = 0; readShaderSource("pokemon.vert", &VertexShaderSource ); readShaderSource("pokemon.frag", &FragmentShaderSource ); loadstatus = installShaders(VertexShaderSource, FragmentShaderSource); timeParam = glGetUniformLocation ( programObject, "time" ); //radiusParam = glGetUniformLocation ( programObject, "radius" ); init2DTexture(); return loadstatus; } /* void show_card() { if (start_game == 0) right_lower = right_upper = left_lower = left_upper = 0; else right_lower = right_upper = left_lower = left_upper = 1; } */ void Timer(int t) { //init_game(); //right_lower = right_upper = left_lower = left_upper = 0; if (count == 0) //show_card(); right_lower = right_upper = left_lower = left_upper = 0; glutPostRedisplay(); glutTimerFunc(2000, Timer, 0); } /* void delay(int milliseconds) { long pause; clock_t now,then; pause = milliseconds*(CLOCKS_PER_SEC/1000); now = then = clock(); while( (now-then) < pause ) now = clock(); } */ static void Reshape(int w, int h) { float vp = 0.8f; float aspect = (float) w / (float) h; glViewport(0, 0, w, h); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glViewport(0, 0, w, h); glMatrixMode(GL_PROJECTION); glLoadIdentity(); // glOrtho(-1.0, 1.0, -1.0, 1.0, -10.0, 10.0); glFrustum(-vp, vp, -vp / aspect, vp / aspect, 3, 10.0); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glTranslatef(0.0, 0.0, -5.0); } void CleanUp(void) { glDeleteShader(vertexShaderObject); glDeleteShader(fragmentShaderObject); glDeleteProgram(programObject); glutDestroyWindow(window); } static void Idle(void) { glUniform1f( timeParam, glutGet ( GLUT_ELAPSED_TIME ) ); //glUniform1f( radiusParam, radius ); glutPostRedisplay(); } /* void reset_game() { while (v.size() > 0) v.pop_back; right_lower = right_upper = left_lower = left_upper = start_game = win = count= 0; } */ static void Key(unsigned char key, int x, int y) { switch(key) { case 27: CleanUp(); exit(0); break; case 'd': if (start_game == 1) { if (right_lower == 0) right_lower++; //if (check1 == 0) check1 = 1; if (win == 0) { v.push_back(1); win = check_win(v); if (win == 1) start_game = 0; } count++; } break; case 'w': if (start_game == 1) { if (right_upper == 0) right_upper++; //if (check2 == 0) check2 = 2; if (win == 0) { v.push_back(2); win = check_win(v); if (win == 1) start_game = 0; } count++; } break; case 'q': if (start_game == 1) { if (left_upper == 0) left_upper++; //if (check1 == 0) check1 = 1; if (win == 0) { v.push_back(1); win = check_win(v); if (win == 1) start_game = 0; } count++; } break; case 's': if (start_game == 1) { if (left_lower == 0) left_lower++; //if (check2 == 0) check2 = 2; if (win == 0) { v.push_back(2); win = check_win(v); if (win == 1) start_game = 0; } count++; } break; case 'r': if (start_game == 0 /* && (win == 1 || win == 2)*/) { //reset_game(); right_lower = right_upper = left_lower = left_upper = start_game = win = count = 0; //while (v.size() > 0) v.pop_back; } break; case 'p': if (start_game == 0 && win == 0) { //init_game(); //show = 1; //right_lower = right_upper = left_lower = left_upper = 0; start_game = 1; //count = 0; //delay(2000); right_lower = right_upper = left_lower = left_upper = 1; } //SDL_Delay(2000); /* if (start_game == 1 && win == 0) { //SDL_Delay(2000); //sleep(2); //delay(2000); right_lower = right_upper = left_lower = left_upper = 0; } */ break; } glutPostRedisplay(); } void display(void) { GLfloat vec[4]; glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glClearColor( 0.439216, 0.858824, 0.576471, 0.0 ); //background color glActiveTexture(GL_TEXTURE0); print(-0.42, 1.22, "MATCHING POKEMON"); print(-1.1, 1.13, "Use q, w, s, d, to flip each card"); print(-1.1, 1.04, "p = start game r = reset game Esc = exit game"); if (start_game == 1) print(-0.34, -1.3, "GAME STARTED!"); //float p = glGetAttribLocation (programObject, "zoomp"); //float n = glGetAttribLocation (programObject, "zoomn"); if (win == 1) { //print(-0.2, -0.13, "YOU WIN!"); glPushMatrix(); //sleep(1); glBindTexture(GL_TEXTURE_2D, texNameW); /* glBegin ( GL_QUADS ); glTexCoord2f (0,0); glVertex3f (-1.5,-1.5,0); glTexCoord2f (1,0); glVertex3f (1.5,-1.5,0); glTexCoord2f (1,1); glVertex3f (1.5,1.5,0); glTexCoord2f (0,1); glVertex3f (-1.5,1.5,0); glEnd(); */ glBegin ( GL_QUADS ); glTexCoord2f (0,0); glVertex3f (-0.4,-0.2,0); glTexCoord2f (1,0); glVertex3f (0.4,-0.2,0); glTexCoord2f (1,1); glVertex3f (0.4,0,0); glTexCoord2f (0,1); glVertex3f (-0.4,0,0); glEnd(); glPopMatrix(); } if (win == 2) { //print(-0.2, -0.13, "YOU SUCK!"); glPushMatrix(); glBindTexture(GL_TEXTURE_2D, texNameS); glBegin ( GL_QUADS ); glTexCoord2f (0,0); glVertex3f (-0.35,-0.55,0); glTexCoord2f (1,0); glVertex3f (0.35,-0.55,0); glTexCoord2f (1,1); glVertex3f (0.35,0.35,0); glTexCoord2f (0,1); glVertex3f (-0.35,0.35,0); glEnd(); glPopMatrix(); } //float spin = glGetAttribLocation (programObject, "angle"); //right upper card glPushMatrix(); /* if (show == 1) { glBindTexture(GL_TEXTURE_2D, texName1); //sleep(2); //glBindTexture(GL_TEXTURE_2D, texNameB); } */ if (right_upper == 0) glBindTexture(GL_TEXTURE_2D, texNameB); else glBindTexture(GL_TEXTURE_2D, texName1); //else { /*if (right_upper == 1) glBindTexture(GL_TEXTURE_2D, texName1); */ //if (win == 1) glRotatef(spin, 0, 0, 1); glBegin ( GL_QUADS ); glTexCoord2f (0,0); glVertex3f (0.1,0,0); glTexCoord2f (1,0); glVertex3f (1.1,0,0); glTexCoord2f (1,1); glVertex3f (1.1,1,0); glTexCoord2f (0,1); glVertex3f (0.1,1,0); glEnd(); glPopMatrix(); //right lower card glPushMatrix(); if (right_lower == 0) glBindTexture(GL_TEXTURE_2D, texNameB); else glBindTexture(GL_TEXTURE_2D, texName2); glBegin ( GL_QUADS ); glTexCoord2f (0,1); glVertex3f (0.1,-0.2,0); glTexCoord2f (0,0); glVertex3f (0.1,-1.2,0); glTexCoord2f (1,0); glVertex3f (1.1,-1.2,0); glTexCoord2f (1,1); glVertex3f (1.1,-0.2,0); glEnd(); glPopMatrix(); //left upper card glPushMatrix(); if (left_upper == 0) glBindTexture(GL_TEXTURE_2D, texNameB); else glBindTexture(GL_TEXTURE_2D, texName2); glBegin ( GL_QUADS ); glTexCoord2f (1,0); glVertex3f (-0.1,0,0); glTexCoord2f (1,1); glVertex3f (-0.1,1,0); glTexCoord2f (0,1); glVertex3f (-1.1,1,0); glTexCoord2f (0,0); glVertex3f (-1.1,0,0); glEnd(); glPopMatrix(); //left lower card glPushMatrix(); if (left_lower == 0) glBindTexture(GL_TEXTURE_2D, texNameB); else glBindTexture(GL_TEXTURE_2D, texName1); glBegin ( GL_QUADS ); glTexCoord2f (1,1); glVertex3f (-0.1,-0.2,0); glTexCoord2f (0,1); glVertex3f (-1.1,-0.2,0); glTexCoord2f (0,0); glVertex3f (-1.1,-1.2,0); glTexCoord2f (1,0); glVertex3f (-0.1,-1.2,0); glEnd(); glPopMatrix(); //float r = glGetAttribLocation( programObject, "radius" ); //radius = glGetAttribLocation( programObject, "radius" ); //cout << radius << endl; //gluDisk( qobj, 0, 1, 5, 10); /* float a = 2 * 3.14159265 / 5; //angle subtended by one side float a1 = 0; glBegin ( GL_POLYGON ); glTexCoord2f ( -0.7, -1.0 ); glVertex2f (cos (a1 ), sin (a1) ); a1 += a; glTexCoord2f ( -1.0, 0.3 ); glVertex2f (cos (a1 ), sin (a1) ); a1 += a; glTexCoord2f ( 0.0, 1.0 ); glVertex2f (cos (a1 ), sin (a1) ); a1 += a; glTexCoord2f ( 1.0, 0.3 ); glVertex2f (cos (a1 ), sin (a1) ); a1 += a; glTexCoord2f ( 0.7, -1.0 ); glVertex2f (cos (a1 ), sin (a1) ); a1 += a; glEnd(); /* if ( objectType == 0 ) gluSphere(qobj,0.6,32,32); else if ( objectType == 1 ) { glTranslatef( 0, 0.6, 0 ); glRotatef( 90, 1, 0, 0 ); gluCylinder(qobj, 0.5, 0.5, 1.2, 32, 32); //top, base height } else if ( objectType == 2 ) glutSolidTeapot(0.6f); //has texture coordinates else { gluDisk( qobj, 0, 1, 5, 10); } */ // gluDeleteQuadric(qobj); //glPopMatrix(); glutSwapBuffers(); glFlush(); } int main(int argc, char *argv[]) { int success = 0; glutInit(&argc, argv); glutInitWindowPosition(50, 0); glutInitWindowSize(800, 800); glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE | GLUT_DEPTH); window = glutCreateWindow("MATCHING POKEMON"); glutReshapeFunc(Reshape); glutKeyboardFunc(Key); glutDisplayFunc(display); glutIdleFunc(Idle); glutTimerFunc(2000, Timer, 0); // Initialize the "OpenGL Extension Wrangler" library glewInit(); success = init(); if ( success ) glutMainLoop(); return 0; }
[ "u1089896@ad.utah.edu" ]
u1089896@ad.utah.edu
7e60887f97b5672d776ba4d70ad16f36d2063645
d402b9a7cf1aa4a7c4b56897050988e8158ba9f6
/mbed/hal/common/SPI.cpp
d3feefe3817c0c502a1fe8762f5b1a31193bc154
[]
no_license
kgoba/DroneSTM
e968e60515fd8bb5b7a09c1a853ef6872e6b1089
17b007315927c9b4e01bc901768a078f9b8bdf0e
refs/heads/master
2021-01-19T02:25:05.992556
2016-11-05T15:19:34
2016-11-05T15:19:34
61,637,938
1
0
null
null
null
null
UTF-8
C++
false
false
5,022
cpp
/* mbed Microcontroller Library * Copyright (c) 2006-2013 ARM Limited * * 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 "SPI.h" #include "critical.h" #if DEVICE_SPI namespace mbed { #if DEVICE_SPI_ASYNCH && TRANSACTION_QUEUE_SIZE_SPI CircularBuffer<Transaction<SPI>, TRANSACTION_QUEUE_SIZE_SPI> SPI::_transaction_buffer; #endif SPI::SPI(PinName mosi, PinName miso, PinName sclk, PinName ssel) : _spi(), #if DEVICE_SPI_ASYNCH _irq(this), _usage(DMA_USAGE_NEVER), #endif _bits(8), _mode(0), _hz(1000000) { // No lock needed in the constructor spi_init(&_spi, mosi, miso, sclk, ssel); aquire(); } void SPI::format(int bits, int mode) { lock(); _bits = bits; _mode = mode; SPI::_owner = NULL; // Not that elegant, but works. rmeyer aquire(); unlock(); } void SPI::frequency(int hz) { lock(); _hz = hz; SPI::_owner = NULL; // Not that elegant, but works. rmeyer aquire(); unlock(); } SPI* SPI::_owner = NULL; // ignore the fact there are multiple physical spis, and always update if it wasnt us last void SPI::aquire() { lock(); if (_owner != this) { spi_format(&_spi, _bits, _mode, 0); spi_frequency(&_spi, _hz); _owner = this; } unlock(); } int SPI::write(int value) { lock(); aquire(); int ret = spi_master_write(&_spi, value); unlock(); return ret; } void SPI::lock() { _mutex.lock(); } void SPI::unlock() { _mutex.unlock(); } #if DEVICE_SPI_ASYNCH int SPI::transfer(const void *tx_buffer, int tx_length, void *rx_buffer, int rx_length, unsigned char bit_width, const event_callback_t& callback, int event) { if (spi_active(&_spi)) { return queue_transfer(tx_buffer, tx_length, rx_buffer, rx_length, bit_width, callback, event); } start_transfer(tx_buffer, tx_length, rx_buffer, rx_length, bit_width, callback, event); return 0; } void SPI::abort_transfer() { spi_abort_asynch(&_spi); #if TRANSACTION_QUEUE_SIZE_SPI dequeue_transaction(); #endif } void SPI::clear_transfer_buffer() { #if TRANSACTION_QUEUE_SIZE_SPI _transaction_buffer.reset(); #endif } void SPI::abort_all_transfers() { clear_transfer_buffer(); abort_transfer(); } int SPI::set_dma_usage(DMAUsage usage) { if (spi_active(&_spi)) { return -1; } _usage = usage; return 0; } int SPI::queue_transfer(const void *tx_buffer, int tx_length, void *rx_buffer, int rx_length, unsigned char bit_width, const event_callback_t& callback, int event) { #if TRANSACTION_QUEUE_SIZE_SPI transaction_t t; t.tx_buffer = const_cast<void *>(tx_buffer); t.tx_length = tx_length; t.rx_buffer = rx_buffer; t.rx_length = rx_length; t.event = event; t.callback = callback; t.width = bit_width; Transaction<SPI> transaction(this, t); if (_transaction_buffer.full()) { return -1; // the buffer is full } else { core_util_critical_section_enter(); _transaction_buffer.push(transaction); if (!spi_active(&_spi)) { dequeue_transaction(); } core_util_critical_section_exit(); return 0; } #else return -1; #endif } void SPI::start_transfer(const void *tx_buffer, int tx_length, void *rx_buffer, int rx_length, unsigned char bit_width, const event_callback_t& callback, int event) { aquire(); _callback = callback; _irq.callback(&SPI::irq_handler_asynch); spi_master_transfer(&_spi, tx_buffer, tx_length, rx_buffer, rx_length, bit_width, _irq.entry(), event , _usage); } #if TRANSACTION_QUEUE_SIZE_SPI void SPI::start_transaction(transaction_t *data) { start_transfer(data->tx_buffer, data->tx_length, data->rx_buffer, data->rx_length, data->width, data->callback, data->event); } void SPI::dequeue_transaction() { Transaction<SPI> t; if (_transaction_buffer.pop(t)) { SPI* obj = t.get_object(); transaction_t* data = t.get_transaction(); obj->start_transaction(data); } } #endif void SPI::irq_handler_asynch(void) { int event = spi_irq_handler_asynch(&_spi); if (_callback && (event & SPI_EVENT_ALL)) { _callback.call(event & SPI_EVENT_ALL); } #if TRANSACTION_QUEUE_SIZE_SPI if (event & (SPI_EVENT_ALL | SPI_EVENT_INTERNAL_TRANSFER_COMPLETE)) { // SPI peripheral is free (event happend), dequeue transaction dequeue_transaction(); } #endif } #endif } // namespace mbed #endif
[ "karlis.goba@gmail.com" ]
karlis.goba@gmail.com
9873d30a3aa0759b2cdf103b23498de53a733587
260e5dec446d12a7dd3f32e331c1fde8157e5cea
/Indi/SDK/Indi_SentrySabre_AnimBP_functions.cpp
a3cb6749ccefd73d97fe635c90e90a93e1b60c42
[]
no_license
jfmherokiller/TheOuterWorldsSdkDump
6e140fde4fcd1cade94ce0d7ea69f8a3f769e1c0
18a8c6b1f5d87bb1ad4334be4a9f22c52897f640
refs/heads/main
2023-08-30T09:27:17.723265
2021-09-17T00:24:52
2021-09-17T00:24:52
407,437,218
0
0
null
null
null
null
UTF-8
C++
false
false
1,221
cpp
// TheOuterWorlds SDK #ifdef _MSC_VER #pragma pack(push, 0x8) #endif #include "Indi_SentrySabre_AnimBP_parameters.hpp" namespace SDK { //--------------------------------------------------------------------------- //Functions //--------------------------------------------------------------------------- // Function SentrySabre_AnimBP.SentrySabre_AnimBP_C.ExecuteUbergraph_SentrySabre_AnimBP // (Final, RequiredAPI, BlueprintAuthorityOnly, BlueprintCosmetic, Net, NetReliable, NetRequest, Exec, Native, Event, NetResponse, Static, NetMulticast) // Parameters: // int EntryPoint (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData) void USentrySabre_AnimBP_C::STATIC_ExecuteUbergraph_SentrySabre_AnimBP(int EntryPoint) { static auto fn = UObject::FindObject<UFunction>("Function SentrySabre_AnimBP.SentrySabre_AnimBP_C.ExecuteUbergraph_SentrySabre_AnimBP"); USentrySabre_AnimBP_C_ExecuteUbergraph_SentrySabre_AnimBP_Params params; params.EntryPoint = EntryPoint; auto flags = fn->FunctionFlags; fn->FunctionFlags |= 0x400; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } } #ifdef _MSC_VER #pragma pack(pop) #endif
[ "peterpan0413@live.com" ]
peterpan0413@live.com
79cea84da0fff4598037b92ad5ccf766b3ef3c97
c094d381422c2788d67a3402cff047b464bf207b
/c++_primer_plus/c++_primer_plus/p675vector类.cpp
2e90a0d0851aedda017c52fed862a0e206caa7d2
[]
no_license
liuxuanhai/C-code
cba822c099fd4541f31001f73ccda0f75c6d9734
8bfeab60ee2f8133593e6aabfeefaf048357a897
refs/heads/master
2020-04-18T04:26:33.246444
2016-09-05T08:32:33
2016-09-05T08:32:33
67,192,848
1
0
null
null
null
null
WINDOWS-1252
C++
false
false
731
cpp
#include <iostream> #include <string> #include <vector> const int NUM = 5; int main(void) { using std::vector; using std::string; using std::cin; using std::cout; vector<int> ratings(NUM); // int ¹æ·¶ vector<string> titles(NUM); // string ¹æ·¶ cout << "You will do exactly as told. You will enter\n" << NUM << " book titles and your ratings (0-10).\n";; int i; for (i = 0; i < NUM; i++) { cout << "Enter title #" << i + 1 << ": "; getline(cin, titles[i]); cout << "Enter your rating(0-10): "; cin >> ratings[i]; cin.get(); } cout << "Thank you. You entered the following:\n" << "Rating\tBook\n"; for (i = 0; i < NUM; i++) cout << ratings[i] << "\t" << titles[i] << std::endl; return 0; }
[ "heabking@gmail.com" ]
heabking@gmail.com
4c04f30f14270ca1ced8a14c6db2350c8265a25c
6e3b592de89cb3e7d594993c784e7059bdb2a9ae
/Source/AllProjects/CQCIntf/CQCIntfEd/CQCIntfEd_ErrList.cpp
54bda4b9583b3e5a6c8c259063731c392d5bc14b
[ "MIT" ]
permissive
jjzhang166/CQC
9aae1b5ffeddde2c87fafc3bb4bd6e3c7a98a1c2
8933efb5d51b3c0cb43afe1220cdc86187389f93
refs/heads/master
2023-08-28T04:13:32.013199
2021-04-16T14:41:21
2021-04-16T14:41:21
null
0
0
null
null
null
null
UTF-8
C++
false
false
8,836
cpp
// // FILE NAME: CQCIntfEd_ErrList.cpp // // AUTHOR: Dean Roddey // // CREATED: 03/28/2016 // // COPYRIGHT: Charmed Quark Systems, Ltd @ 2020 // // This software is copyrighted by 'Charmed Quark Systems, Ltd' and // the author (Dean Roddey.) It is licensed under the MIT Open Source // license: // // https://opensource.org/licenses/MIT // // DESCRIPTION: // // This file implements the error list window. // // CAVEATS/GOTCHAS: // // LOG: // // $Log$ // // --------------------------------------------------------------------------- // Includes // --------------------------------------------------------------------------- #include "CQCIntfEd_.hpp" // --------------------------------------------------------------------------- // Magic macros // --------------------------------------------------------------------------- RTTIDecls(TIntfErrListTopic, TObject) RTTIDecls(TIntfErrListWnd,TGenericWnd) // --------------------------------------------------------------------------- // CLASS: TIntfErrListWnd // PREFIX: wnd // --------------------------------------------------------------------------- // --------------------------------------------------------------------------- // TIntfErrListWnd: Constructors and Destructor // --------------------------------------------------------------------------- TIntfErrListWnd::TIntfErrListWnd() : m_pwndList(nullptr) , m_pwndTitle(nullptr) , m_strType_Error(L"Error") , m_strType_Warning(L"Warning") { } TIntfErrListWnd::~TIntfErrListWnd() { } // ------------------------------------------------------------------- // TIntfErrListWnd: Public, inherited methods // ------------------------------------------------------------------- // // If our list window gets the focus, send a selection event so that the editor can get // the focus back on the offending widget, if it still exists. // tCIDLib::TVoid TIntfErrListWnd::ChildFocusChange( const TWindow& wndParent , const tCIDCtrls::TWndId widChild , const tCIDLib::TBoolean bGotFocus) { if (wndParent.bIsThisWindow(*this) && (widChild == kCQCIntfEd::ridDlg_ErrList_Errs)) { if (bGotFocus) { const tCIDLib::TCard4 c4ListInd = m_pwndList->c4CurItem(); if (c4ListInd != kCIDLib::c4MaxCard) SendErrNot(tCIDCtrls::EListEvents::SelChanged, c4ListInd); } } } // ------------------------------------------------------------------- // TIntfErrListWnd: Public, non-virtual methods // ------------------------------------------------------------------- // // If no errors to load, this is called to clear the list. But we add an empty one back // and select it so that we have a focus indicator // tCIDLib::TVoid TIntfErrListWnd::ClearList() { m_pwndList->RemoveAll(); } tCIDLib::TVoid TIntfErrListWnd::CreateErrList(const TWindow& wndParent, const tCIDCtrls::TWndId widToUse) { // Create our publish topic m_strPublishTopic = L"/CQC/IntfEng/ErrList/"; m_strPublishTopic.AppendFormatted(facCIDLib().c4NextId()); m_pstopErrs = TPubSubTopic::pstopCreateTopic ( m_strPublishTopic, TIntfErrListTopic::clsThis() ); // // Load the dialog description so we can create ourself the same size as the // content initially. This way our parent's auto-sizing code will keep the correct // relationship to the content. // TDlgDesc dlgdChildren; facCQCIntfEd().bCreateDlgDesc(kCQCIntfEd::ridDlg_ErrList, dlgdChildren); TArea areaInit(dlgdChildren.areaPos()); areaInit.ZeroOrg(); CreateGenWnd ( wndParent , areaInit , tCIDCtrls::EWndStyles::ClippingVisChild , tCIDCtrls::EExWndStyles::ControlParent , widToUse ); } // // The editor calls us here to load up the errors he's found. We don't do an initial // selection, because we don't want to force the selection away from whatever widget(s) // the user currently has selected. This way, we only do anything if they actively select // an item. // tCIDLib::TVoid TIntfErrListWnd::LoadErrors(const tCQCIntfEng::TErrList& colErrs) { // Stop redrawing while we do this TWndPaintJanitor janErrs(m_pwndList); // Remove any existing errors m_pwndList->RemoveAll(); // // Store the list for later use. We have to do this before we start loading the list // because that will generate events that will reference this list. // m_colErrs = colErrs; // Load up the new ones tCIDLib::TStrList colCols(3); colCols.objAdd(TString::strEmpty()); colCols.objAdd(TString::strEmpty()); colCols.objAdd(TString::strEmpty()); const tCIDLib::TCard4 c4Count = colErrs.c4ElemCount(); for (tCIDLib::TCard4 c4Index = 0; c4Index < c4Count; c4Index++) { const TCQCIntfValErrInfo& veiCur = colErrs[c4Index]; if (veiCur.bWarning()) colCols[0] = m_strType_Warning; else colCols[0] = m_strType_Error; colCols[1] = veiCur.strWidgetId(); colCols[2] = veiCur.strErrText(); // Set the error's unique error id as the row id m_pwndList->c4AddItem(colCols, veiCur.c4ErrId(), kCIDLib::c4MaxCard, kCIDLib::False); } } // ------------------------------------------------------------------- // TIntfErrListWnd: Protected, inherited methods // ------------------------------------------------------------------- tCIDLib::TBoolean TIntfErrListWnd::bCreated() { TParent::bCreated(); // Load our dialog description and create our children TDlgDesc dlgdChildren; facCQCIntfEd().bCreateDlgDesc(kCQCIntfEd::ridDlg_ErrList, dlgdChildren); tCIDLib::TCard4 c4InitFocus; PopulateFromDlg(dlgdChildren, c4InitFocus); // Set our bgn to standard window background color SetBgnColor(facCIDCtrls().rgbSysClr(tCIDCtrls::ESysColors::Window)); // Get any child controls we need to interact with CastChildWnd(*this, kCQCIntfEd::ridDlg_ErrList_Errs, m_pwndList); CastChildWnd(*this, kCQCIntfEd::ridDlg_ErrList_Title, m_pwndTitle); // Initially set the title text to indicate no focus // m_pwndTitle->SetTextColor(facCIDGraphDev().rgbDarkGrey); // Set up the columns on the list window tCIDLib::TStrList colCols(3); colCols.objAdd(L"Type "); colCols.objAdd(L"Widget Id "); colCols.objAdd(L"Error Message"); m_pwndList->SetColumns(colCols); m_pwndList->AutoSizeCol(0, kCIDLib::True); m_pwndList->AutoSizeCol(1, kCIDLib::True); // We need to react to list selection/invocation m_pwndList->pnothRegisterHandler(this, &TIntfErrListWnd::eLBHandler); // Indicate we want to see child focus changes bWantsChildFocusNot(kCIDLib::True); return kCIDLib::True; } // ------------------------------------------------------------------- // TIntfErrListWnd: Private, non-virtual methods // ------------------------------------------------------------------- // // We respond to selection and invocation events, and publish the appropriate // message. // tCIDCtrls::EEvResponses TIntfErrListWnd::eLBHandler(TListChangeInfo& wnotEvent) { SendErrNot(wnotEvent.eEvent(), wnotEvent.c4Index()); return tCIDCtrls::EEvResponses::Handled; } // // Finds the error for the selected list window row and sends teh appropriate notification // to any registered handlers. // tCIDLib::TVoid TIntfErrListWnd::SendErrNot(const tCIDCtrls::EListEvents eEvent , const tCIDLib::TCard4 c4Index) { tCIDLib::TInt4 i4Code = 0; if ((eEvent == tCIDCtrls::EListEvents::SelChanged) || (eEvent == tCIDCtrls::EListEvents::Invoked)) { // // The list window row id is the unique error id, so we have to look through the // list and find it in order to find the right error. // const tCIDLib::TCard4 c4ErrId = m_pwndList->c4IndexToId(c4Index); const tCIDLib::TCard4 c4Count = m_colErrs.c4ElemCount(); tCIDLib::TCard4 c4ListInd = 0; for (; c4ListInd < c4Count; c4ListInd++) { if (m_colErrs[c4ListInd].c4ErrId() == c4ErrId) break; } // Shouldn't happen but just in case make sure we found it if (c4ListInd != c4Count) { const TCQCIntfValErrInfo& veiCur = m_colErrs[c4ListInd]; const tCIDLib::TCard4 c4WidgetId = veiCur.c4WidgetId(); m_pstopErrs.Publish ( new TIntfErrListTopic(eEvent, c4WidgetId) ); // Ok, let's remove this one from the list if an invoke if (eEvent == tCIDCtrls::EListEvents::Invoked) m_pwndList->RemoveAt(c4Index); } } }
[ "droddey@charmedquark.com" ]
droddey@charmedquark.com
423b7baa79798ef359bcfbf1ac10061d1ed3188e
e0e8164032260be6f6a9042e4bcf945bfc1dd227
/list08/Exercise02/src/House.cpp
cd11971233b0727ee87b005c350904582386aabe
[]
no_license
claudiomarpda/lab_lp1
0494970a76478f4f3ba27828f189991847071c25
2d3ec5bbf3d1c6381ff296a6e748ef72e9953118
refs/heads/master
2020-02-26T14:24:29.484175
2017-05-04T14:34:29
2017-05-04T14:34:29
83,693,884
0
0
null
null
null
null
UTF-8
C++
false
false
854
cpp
#include <iomanip> #include <sstream> #include "House.h" House::House(const Address &address, int numberOfFloors, int numberOfRooms, double landArea, double builtArea) : Immobile(address), numberOfFloors(numberOfFloors), numberOfRooms(numberOfRooms), landArea(landArea), builtArea(builtArea) {} const string &House::getDescription() const { stringstream landStream, builtStream; landStream << fixed << setprecision(2) << landArea; builtStream << fixed << setprecision(2) << builtArea; // static string s = ""; static string s = ""; s = "House description\n" + getAddress().getAddressString(); s += "\nNumber of Floors: " + to_string(numberOfFloors) + "; Number of rooms: " + to_string(numberOfRooms) + "; Land area: " + landStream.str() + "; Built area: " + builtStream.str(); return s; }
[ "claudiomarpda@gmail.com" ]
claudiomarpda@gmail.com
e82ff716fca4995a311e1c58d129a39a53ba001c
d971d68ba43f4797fc8769ccec028943441cc9f6
/client/chat_client.cpp
648551c7818d5fec8e2aac9712c3e4c081e091aa
[]
no_license
teemoking/welchat
228b6d63f317b5b113684923eae164fe597b5c9d
0572f2469564c5eb27c972a9a13393f63aacc5ce
refs/heads/master
2020-04-25T22:00:26.879163
2019-02-28T11:17:24
2019-02-28T11:17:24
173,097,797
0
0
null
null
null
null
UTF-8
C++
false
false
571
cpp
/* #*********************************************** # # Filename: chat_client.cpp # Author:teemo_king # Email: Mp - AK1028430241@gmail.com # Description: --- # Create: 2018-04-21 00:05:05 # Last Modified: 2018-04-21 00:05:05 #*********************************************** */ #include "client.h" #include "login.h" int main() { //用户界面,选择登录,注册 int sockfd = create_socket(); assert(sockfd != -1); //连接服务器 init(sockfd); //聊天,发送文件或者发送离线消息, //用户退出 exit(0); }
[ "AK1028430241@gmail.com" ]
AK1028430241@gmail.com
3858bf724b200eb2fa61536f4542827ee4ccad18
e49a52783c0ac3cde973fee8d4d4dd390cb48305
/alg_prim_kruskal/tests/test_case_grafo.hpp
307078709c4fc38d9624fd93656f87f329b973e4
[ "MIT" ]
permissive
rmmariano/trabalho_alg_prim_kruskal
7e3d32ccd0b42aa91bfd75ce41ca6e3bd77f1b52
d0bb02dbdf0de212fb3757c1515d524e573e858a
refs/heads/master
2020-12-30T15:54:13.223798
2017-05-23T22:38:33
2017-05-23T22:38:33
91,179,992
0
3
null
2017-05-23T22:38:34
2017-05-13T14:30:03
C++
UTF-8
C++
false
false
1,968
hpp
#ifndef TEST_CASE_GRAFO_H #define TEST_CASE_GRAFO_H #include "../algorithms/graph.hpp" void teste_grafo(){ Graph g(true); //grafo orientado //Insere vertices cout << "================================ Insere vertices ================================"<< endl; Vertice v0("A"); int idvA = g.insereVertice(v0); cout << "id A: " << idvA << endl; Vertice v1("B"); int idvB = g.insereVertice(v1); cout << "id B: " << idvB << endl; Vertice v2("C"); int idvC = g.insereVertice(v2); cout << "id C: " << idvC << endl; Vertice v3("D"); int idvD = g.insereVertice(v3); cout << "id D: " << idvD << endl; Vertice v4("E"); int idvE = g.insereVertice(v4); cout << "id E: " << idvE << endl; //Insere arestas cout << "\n================================ Insere arestas ================================"<< endl; g.insereAresta(idvA, idvB, 2); //insere aresta de A para B com peso 2 g.insereAresta(idvA, idvC, 8); g.insereAresta(idvA, idvD, 3); g.insereAresta(idvA, idvE, 5); g.insereAresta(idvE, idvD, 5); g.insereAresta(idvB, idvE, 1); g.imprime(); //Verifica aresta cout << "\n================================ Verifica aresta ================================"<< endl; Aresta *a = g.verificaAresta(idvA, idvD); if(a != nullptr) cout << g.vertices[a->de].nome << " -> " << g.vertices[a->para].nome << "\tPeso: " << a->peso << endl; else cout << "Aresta nao encontrada" << endl; //Remove aresta cout << "\n================================ Remove aresta ================================"<< endl; g.removeAresta(idvA, idvB); cout << "Removeu A -> B" << endl; g.imprime(); //Remove vertice cout << "\n================================ Remove vertice ================================"<< endl; g.removeVertice(idvA); cout << "Removeu vertice A" << endl; g.imprime(); } #endif // TEST_CASE_GRAFO_H
[ "rhuan_ecc@hotmail.com" ]
rhuan_ecc@hotmail.com
86bf8556fd98cc01791b0ba4ebdb3db22577b13c
35bbda72564710e4705c6edde813e9e3f512749a
/Code/CocoMake7_TouchMIDI_ONE_velocity_RENAMED/CocoMake7_TouchMIDI_ONE_velocity_RENAMED.ino
78f71b119856a36ccc79f974e744b5bc2599ee19
[]
no_license
HackEduca/Getting-Started
fb246afaefbd4475779d03e121f726f2f7bd63fb
1299e3d1342cf20bbcbff115cdb6d79fa68f19cd
refs/heads/master
2020-06-12T20:18:10.097588
2017-03-03T09:13:08
2017-03-03T09:13:08
194,413,388
0
0
null
2019-06-29T14:19:08
2019-06-29T14:17:26
C++
UTF-8
C++
false
false
4,212
ino
#define USE_MIDI #define USE_VELO #ifdef USE_MIDI #include <CocoMidi.h> MIDIMessage midimsg; #endif #ifdef USE_KEYBOARD #include <CocoKeyboard.h> #endif #include <CocoTouch.h> #include "CocoTouchFilterSetting.h" char key[] = {'C','O','C','O','M','A','K','E','7',' ','O','N','E','!',' '}; //TeenyTouchDusjagr test2; // ATMEL ATTINY85 // // +-\/-+ // PB5 1| |8 VCC //ref ADC3/PB3 2| |7 PB2/ADC1 //capsens ADC2/PB4 3| |6 PB1* // GND 4| |5 PB0* // +----+ // // * indicates PWM port // int value[8] = {0,0,0,0,0,0,0,0}; #ifdef USE_VELO int prevValue[8] = {0,0,0,0,0,0,0,0}; int velocityValue[8] = {0,0,0,0,0,0,0,0}; #endif uint8_t note_off[8] = {1,1,1,1,1,1,1,1}; uint16_t offset_adc[8] = {0,0,0,0,0,0,0,0}; //filter settings CocoTouchFilterSetting CocoFilter[8]; int filtered_value = 0; uint8_t pin_queue = 0; uint8_t multiplexer_mapping[8] = {6,7,4,4,3,0,1,2}; //remap multiplexer pin unsigned long previousMillis = 0; // will store last time LED was updated int keyCount = -1; int keyTotal = 15; int ledPin = PB0; #define PIN_SELECT 0 #define NUM_CHANNEL 3 #define ADC_REF_PIN PB2 #define ADC_SENSE_PIN PB4 void usb_poll() { usbPoll(); } void setup() { #ifdef USE_MIDI CocoMidi.init(); #endif #ifdef USE_KEYBOARD CocoKeyboard.update(); #endif CocoTouch.begin(); CocoTouch.setAdcSpeed(4); CocoTouch.delay = 4; //TeenyTouchDusjagr.delay_cb = &delay; CocoTouch.usb_poll = &usb_poll; offset_adc[0] = CocoTouch.sense(ADC_SENSE_PIN,ADC_REF_PIN, 8 ); //offset_adc[0] = 0; #ifdef USE_MIDI CocoMidi.delay(100); #endif pinMode(ledPin, OUTPUT); digitalWrite(ledPin, HIGH); CocoMidi.delay(100); digitalWrite(ledPin, LOW); CocoMidi.delay(100); digitalWrite(ledPin, HIGH); CocoMidi.delay(100); digitalWrite(ledPin, LOW); CocoMidi.delay(100); } void loop() { if (millis()-previousMillis >= 5) // 0% data loss { //CocoMidi.sendCCHires(value, 1); filtered_value = CocoTouchFilter_get(&CocoFilter[0]); velocityValue[0] = filtered_value - prevValue[0]; prevValue[0] = filtered_value; if (filtered_value <= 30) {digitalWrite(ledPin, LOW);} if (filtered_value >= 100) {digitalWrite(ledPin, HIGH);} if (filtered_value <= 0) {filtered_value = 0;} if (filtered_value >= 1023) {filtered_value = 1023; digitalWrite(ledPin, HIGH); } //CocoMidi.send(MIDI_NOTEON,0, filtered_value); CocoMidi.sendCCHires(filtered_value, (4*1)+1); CocoMidi.sendCCHires(velocityValue[0]+500, (4*0)+1); CocoMidi.sendCCHires(value[0], (4*2)+1); if (filtered_value >= 10) { if (note_off[0] == 1) { #ifdef USE_MIDI // CocoMidi.send(MIDI_NOTEON,0, filtered_value ); #endif #ifdef USE_KEYBOARD keyCount++; if (keyCount == keyTotal){keyCount = 0;} digitalWrite(ledPin, HIGH); CocoKeyboard.print(key[keyCount]); #endif note_off[0] = 0; } } else { digitalWrite(ledPin, LOW); if (note_off[0] == 0) { #ifdef USE_MIDI //CocoMidi.send(MIDI_NOTEOFF,0,127); #endif note_off[0] = 1; } } previousMillis = millis(); } value[0] = CocoTouch.sense(ADC_SENSE_PIN,ADC_REF_PIN, 7 ) - offset_adc[0]; if (value[0] > 0) CocoTouchFilter_put(&CocoFilter[0], value[0]); #ifdef USE_MIDI CocoMidi.update(); #endif #ifdef USE_MIDI CocoMidi.delay(1); #endif #ifdef USE_KEYBOARD //CocoKeyboard.update(); CocoKeyboard.delay(1); #endif //velocityValue[0] = value[0]-prevValue[0]; //prevValue[0] = value[0]; }
[ "marc@dusseiller.ch" ]
marc@dusseiller.ch
b332280ae890f377464e578c9cba710ac6a3b423
59c47e1f8b2738fc2b824462e31c1c713b0bdcd7
/006-All_Test_Demo/CgiTcpServer/wificommunication.h
4b8e90cffa3574af759a921b1f9caf804d144484
[]
no_license
casterbn/Qt_project
8efcc46e75e2bbe03dc4aeaafeb9e175fb7b04ab
03115674eb3612e9dc65d4fd7bcbca9ba27f691c
refs/heads/master
2021-10-19T07:27:24.550519
2019-02-19T05:26:22
2019-02-19T05:26:22
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,016
h
#ifndef WIFICOMMUNICATION_H #define WIFICOMMUNICATION_H #include <QObject> #include <QByteArray> #include <QTimer> #include <QString> #include <QCoreApplication> #include <QJsonDocument> #include <QJsonArray> #include <QJsonValue> #include <QJsonParseError> #include <QJsonObject> #include <QVariantMap> #include "tcpmodule.h" typedef enum { ERROR = -1, HEARTBEAT, LOGIN, GETALLPARA, SETPARA, UPDATE }WIFICMDS; typedef enum ID_FRAME { ID_HEART = 0x01, /* heartBeat */ ID_LOGIN = 0x02, /* login */ ID_GETPARA = 0x03, /* getallparameter */ ID_SENDPARA = 0x04, /* sendallparameter */ ID_UPDATEFINISH = 0x05, /* appupdateFinished */ ID_SENDFILE = 0x06, /* sendFile */ ID_REBOOT = 0x07, /* reboot */ }ID_FRAME; class WifiCommunication : public QObject { Q_OBJECT public: explicit WifiCommunication(int port = 60001, QObject *parent = 0); /******************JSON start***************************/ bool jsonFormatIsRight(const QByteArray& byteArray); void parserJsonFormat(const QByteArray& byteArray); void parseBuffer(QByteArray buffer); QByteArray& generateBuffer(QByteArray& buffer); char getCrcVerify(QByteArray msg, int length); bool judgeArrayIsEmpty(const QByteArray& buffer); QByteArray& convertJsonToByteArray(QJsonObject& msg); void sltloginResult(bool flag); int writeMsgToClient(QByteArray msg, int length); void sendHeartBeat(); int startWifi(); int stopWifi(); void replyDownLoadFile(bool flag); void unZipStatus(QString str); /******************JSON ended**************************/ /******************TcpSocket start***************************/ /* * 当MyTcpSocket数据到达时,MyTcpSocket通知MyTcpServer服务器对数据进行处理, * 例如检查json格式是否正确等.组合生成需要回复的QJson字符串,调用MyTcpSocket write数据给Client */ /******************TcpSocket ended**************************/ /******************Json format dealwith start***************************/ private: void login(QJsonValue &InfoMap); void getAllParameter(); void setParameter(QJsonValue &InfoMap); void appUpdateFinished(QJsonValue &InfoMap); void heartBeatFrame(QJsonValue &InfoMap); void sendFile(QJsonValue &InfoMap); void updateProgress(QJsonValue &InfoMap); void rebootMachine(QJsonValue &InfoMap); void downLoadFile(QJsonValue &InfoMap); void replySendFile(bool flag); void webUpload(QJsonValue &InfoMap); bool fileExist(QString fileName); void webShowUploadFileMessage(QJsonValue &InfoMap); // Ui will show Transfer unzip file.... /******************Json format dealwith end***************************/ signals: // void sigMsgArrive(QByteArray msg, int length); void sigDeviceConnected(); void sigDeviceDisconnected(); void sigLogin(QString ssid, QString passwd); void sigParameterSetUp(QString key, QVariant value); void sigGetAllParametere(); void sigUpdateFinished(bool flag); void sigSendFile(bool flag, QString fileName); void sigUploadProgress(int percent); void sigDownLoad(bool flag, QString fileName); void sigSizeChange(int sizeNum); void sigRebootMachine(bool flag); void sigWebUpload(QString fileName); void sigShowUploadFileMessage(bool pShowFlag); // void sigCloseSocket(); public slots: /*-----------------ftp start------------------------*/ void removeFile(QString path); /*-----------------ftp enede------------------------*/ void onHeartBeatTimeOut(); void onDeviceDisconnected(); private: MyTcpServer* mMyTcpServer; QTimer mHeartBeatTimer; QByteArray mSendBufferFrame; QByteArray mRecvBufferFrame; QByteArray mJsonByte; bool mHeartBeatFlag; int mUnableHeartBeatCounts; QJsonDocument mJsonDoc; int mPort; }; #endif // WIFICOMMUNICATION_H
[ "1343726739@qq.com" ]
1343726739@qq.com
6d952f182b799def26b645c124306f7dcf2aba17
e94bdcc7f716117d34af2442096dd3be1331e5e1
/Classes/Analysis/BalloonAnalysis.cpp
1a531307439117095ffcf2f54d7948159f74d8e7
[]
no_license
sosoayaen/PokeBalloon
a451188c92ec85c94568a63a300cf30ca3c2a8a9
494af56f900bfc029ff9827920191536d99a499e
refs/heads/master
2016-09-06T13:08:48.120159
2014-09-22T07:21:26
2014-09-22T07:21:26
null
0
0
null
null
null
null
UTF-8
C++
false
false
13,017
cpp
/* * ===================================================================================== * * Filename: BalloonAnalysis.cpp * * Description: * * Version: 1.0 * Created: 06/13/2014 01:09:16 * Revision: none * Compiler: gcc * * Author: Jason Tou (), sosoayaen@gmail.com * Organization: * * ===================================================================================== */ #include "BalloonAnalysis.h" #include "CCJSONConverter.h" #include "bailinUtil.h" USING_NS_CC; USING_NS_BAILIN_UTIL; void BalloonAnalysis::initData() { memset(&m_AnalysisData, 0, sizeof(BalloonAnalysisData)); } void BalloonAnalysis::handleColorType(Balloon* pBalloon) { struct tagBalloonColorAnalysisData& colorData = m_AnalysisData.colorData; switch(pBalloon->getBalloonColor()) { case kBalloonColorGreen: colorData.green++; break; case kBalloonColorBlack: colorData.black++; break; case kBalloonColorOrange: colorData.orange++; break; case kBalloonColorRed: colorData.red++; break; case kBalloonColorBlue: colorData.blue++; break; case kBalloonColorYellow: colorData.yellow++; break; case kBalloonColorBrown: colorData.brown++; break; case kBalloonColorPink: colorData.pink++; break; default: break; } } void BalloonAnalysis::handleNormalData(Balloon* pBalloon) { struct tagBalloonNormalAnalysisData& normalData = m_AnalysisData.normalData; // 判断对应的正负分数 if (pBalloon->getBalloonScore() > 0) normalData.normal_positive++; else if (pBalloon->getBalloonScore() < 0) normalData.normal_negative++; else normalData.normal_zero++; } void BalloonAnalysis::handleItemData(Balloon* pBalloon) { struct tagBalloonItemAnalysisData& itemData = m_AnalysisData.itemData; // 根据道具类型分配 switch(pBalloon->getBalloonType()) { case kBalloonTypeMulti: itemData.multi++; break; case kBalloonTypeBoom: itemData.boom++; break; case kBalloonTypeAddTime: itemData.time++; break; case kBalloonTypePump: itemData.pump++; break; case kBalloonTypeAddBalloon: break; case kBalloonTypeFrozen: itemData.frozen++; break; case kBalloonTypeGiant: itemData.giant++; break; case kBalloonTypeHurricane: break; case kBalloonTypeReverse: itemData.reverse++; break; default: break; } } void BalloonAnalysis::handleBalloonData(Balloon* pBalloon) { // 先判断是道具还是普通气球 BalloonType eType = pBalloon->getBalloonType(); if (eType == kBalloonTypeNormal) { handleNormalData(pBalloon); } else { handleItemData(pBalloon); } } void BalloonAnalysis::countWithBalloonObject(Balloon* pBalloon) { // 先区分颜色 handleColorType(pBalloon); // 处理普通气球或者道具 handleBalloonData(pBalloon); // 增体请求个数+1 m_AnalysisData.total++; } const BalloonAnalysisData& BalloonAnalysis::getAnalysisData() const { return m_AnalysisData; } long long BalloonAnalysis::getTotalBalloonCounts() const { return m_AnalysisData.total; } long long BalloonAnalysis::getNormalBalloonCounts() const { const struct tagBalloonNormalAnalysisData normalData = m_AnalysisData.normalData; long long llSumData = 0; const long long* pData = (long long*)&normalData; int nLen = sizeof(normalData)/sizeof(long long); for (int idx = 0; idx < nLen; ++idx) { llSumData += *pData; pData++; } return llSumData; } long long BalloonAnalysis::getItemBalloonCounts() const { const struct tagBalloonItemAnalysisData itemData = m_AnalysisData.itemData; long long llSumData = 0; const long long* pData = (long long*)&itemData; int nLen = sizeof(itemData)/sizeof(long long); for (int idx = 0; idx < nLen; ++idx) { llSumData += *pData; pData++; } return llSumData; } void BalloonAnalysis::merge(const BalloonAnalysis &analysisData) { const long long* pData = (long long*)&analysisData.getAnalysisData(); long long* pDestData = (long long*)&m_AnalysisData; // 得到数据结构内数据个数 int nLen = sizeof(BalloonAnalysisData)/sizeof(long long); while (nLen-- > 0) { // 逐个累加数据 *pDestData++ += *pData++; } } std::string BalloonAnalysis::dumpDebugInfo() const { #if COCOS2D_DEBUG > 0 // 输出统计调试信息 std::stringstream stream; stream << "=======>debug info<=======\n"; // 总点破气球数目 stream << "total break: " << m_AnalysisData.total << "\n"; // 各个颜色的统计 stream << "color red: " << m_AnalysisData.colorData.red << "\n"; stream << "color brown: " << m_AnalysisData.colorData.brown << "\n"; stream << "color black: " << m_AnalysisData.colorData.black << "\n"; stream << "color orange: " << m_AnalysisData.colorData.orange << "\n"; stream << "color blue: " << m_AnalysisData.colorData.blue << "\n"; stream << "color yellow: " << m_AnalysisData.colorData.yellow << "\n"; stream << "color pink: " << m_AnalysisData.colorData.pink << "\n"; stream << "color green: " << m_AnalysisData.colorData.green << "\n"; // 普通气球总数 stream << "+ normal total: " << getNormalBalloonCounts() << "\n"; // 正分气球点破个数 stream << " - normal positive: " << m_AnalysisData.normalData.normal_positive << "\n"; // 负分气球点破个数 stream << " - normal negative: " << m_AnalysisData.normalData.normal_negative << "\n"; // 零分气球个数 stream << " - normal zero: " << m_AnalysisData.normalData.normal_zero << "\n"; // 道具气球总数 stream << "+ item total: " << getItemBalloonCounts() << "\n"; // 打气筒 stream << " - pump: " << m_AnalysisData.itemData.pump << "\n"; // 乘2气球数目 stream << " - multi: " << m_AnalysisData.itemData.multi << "\n"; // 炸弹气球数目 stream << " - boom: " << m_AnalysisData.itemData.boom << "\n"; // 翻转气球数目 stream << " - reverse: " << m_AnalysisData.itemData.reverse << "\n"; // 巨人气球数目 stream << " - giant: " << m_AnalysisData.itemData.giant << "\n"; // 霜冻球数目 stream << " - frozen: " << m_AnalysisData.itemData.frozen << "\n"; // 增加时间气球数目 stream << " - time: " << m_AnalysisData.itemData.time << "\n"; return stream.str(); #else return ""; #endif } ////////////////////////////////////////////////////////////////////////////////// // 全局数据类实现 #define KEY_ITEM_DATA "itemData" // 数据字典中道具数据的key #define KEY_COLOR_DATA "colorData" // 数据字典中颜色数据的key #define KEY_NORMAL_DATA "normalData" // 数据字典中普通计分数据的key #define ARCHIVEMENT_FILE_NAME "analysisArchivement" // 存放数据的文件名 #define XOR_KEY "wardrums_20140419" // XOR BalloonGlobalAnalysis* g_sharedGlobalAnalysis = NULL; BalloonGlobalAnalysis* BalloonGlobalAnalysis::sharedGlobalAnalysis() { if (!g_sharedGlobalAnalysis) { g_sharedGlobalAnalysis = new BalloonGlobalAnalysis; CCAssert(g_sharedGlobalAnalysis, "g_sharedGlobalAnalysis malloc failed!"); g_sharedGlobalAnalysis->initData(); g_sharedGlobalAnalysis->loadData(); } return g_sharedGlobalAnalysis; } void BalloonGlobalAnalysis::purgeGlobalAnalysis() { if (g_sharedGlobalAnalysis) { delete g_sharedGlobalAnalysis; g_sharedGlobalAnalysis = NULL; } } // 加速书写过程的宏定义 #define getColorData(color) m_AnalysisData.colorData.color = atoll(pDictColor->valueForKey(#color)->getCString()) #define getNormalData(data) m_AnalysisData.normalData.data = atoll(pDictNormal->valueForKey(#data)->getCString()) #define getItemData(data) m_AnalysisData.itemData.data = atoll(pDictItem->valueForKey(#data)->getCString()) void BalloonGlobalAnalysis::setDataWithDictionary(cocos2d::CCDictionary *pDict) { // 得到总数 m_AnalysisData.total = atoll(pDict->valueForKey("total")->getCString()); // 设置颜色数据 CCDictionary* pDictColor = dynamic_cast<CCDictionary*>(pDict->objectForKey(KEY_COLOR_DATA)); if (pDictColor) { // m_AnalysisData.colorData.red = atoll(pDictColor->valueForKey("red")->getCString()); getColorData(red); getColorData(black); getColorData(yellow); getColorData(green); getColorData(pink); getColorData(blue); getColorData(brown); getColorData(orange); } // 设置普通气球数据 CCDictionary* pDictNormal = dynamic_cast<CCDictionary*>(pDict->objectForKey(KEY_NORMAL_DATA)); if (pDictNormal) { getNormalData(normal_positive); getNormalData(normal_negative); getNormalData(normal_zero); } // 设置道具气球数据 CCDictionary* pDictItem = dynamic_cast<CCDictionary*>(pDict->objectForKey(KEY_ITEM_DATA)); if (pDictItem) { getItemData(boom); getItemData(frozen); getItemData(giant); getItemData(multi); getItemData(reverse); getItemData(pump); getItemData(time); } } void BalloonGlobalAnalysis::loadData() { // 从磁盘中把数据读入,如果没有,则跳过 std::string strPath = CCFileUtils::sharedFileUtils()->getWritablePath() + ARCHIVEMENT_FILE_NAME; if (CCFileUtils::sharedFileUtils()->isFileExist(strPath)) { // 载入数据 unsigned long nSize = 0; const unsigned char* pData = CCFileUtils::sharedFileUtils()->getFileData(strPath.c_str(), "rb", &nSize); if (pData && nSize > 0) { unsigned int nBufferLen = 0; const char* pszJSONData = (const char*)crypto::BlowfishDecode(pData, nSize, nBufferLen); // CCLog("%s", pszJSONData); CCDictionary* pDict = CCJSONConverter::sharedConverter()->dictionaryFrom(pszJSONData); // 转换数据到结构体 setDataWithDictionary(pDict); // 释放数据 delete pData; delete pszJSONData; } } } // 加速书写过程的宏定义 #define setColorData(color) pDictColor->setObject(CCString::createWithFormat("%lld", m_AnalysisData.colorData.color), #color) #define setNormalData(data) pDictNormal->setObject(CCString::createWithFormat("%lld", m_AnalysisData.normalData.data), #data) #define setItemData(data) pDictItem->setObject(CCString::createWithFormat("%lld", m_AnalysisData.itemData.data), #data) CCDictionary* BalloonGlobalAnalysis::dictionayFromData() { CCDictionary* pDict = CCDictionary::create(); pDict->removeAllObjects(); // 从数据中得到总数 pDict->setObject(CCString::createWithFormat("%lld", m_AnalysisData.total), "total"); // 处理颜色数据 CCDictionary* pDictColor = CCDictionary::create(); // pDictColor->setObject(CCString::createWithFormat("%lld", colorData.red), "red"); setColorData(red); setColorData(blue); setColorData(black); setColorData(orange); setColorData(pink); setColorData(green); setColorData(brown); setColorData(yellow); pDict->setObject(pDictColor, KEY_COLOR_DATA); // 处理分数气球 CCDictionary* pDictNormal = CCDictionary::create(); // pDictNormal->setObject(CCString::createWithFormat("%lld", m_AnalysisData.normalData.normal_positive), "normal_positive"); setNormalData(normal_positive); setNormalData(normal_negative); setNormalData(normal_zero); pDict->setObject(pDictNormal, KEY_NORMAL_DATA); // 处理道具气球 CCDictionary* pDictItem = CCDictionary::create(); setItemData(pump); setItemData(boom); setItemData(giant); setItemData(multi); setItemData(reverse); setItemData(frozen); setItemData(time); pDict->setObject(pDictItem, KEY_ITEM_DATA); return pDict; } bool BalloonGlobalAnalysis::saveData() { // 把数据结构转换成CCDictionary对象 CCDictionary* pDict = dictionayFromData(); if (!pDict) return false; const char* pszJSON = CCJSONConverter::sharedConverter()->strFrom(pDict); // 转换成JSON数据 std::string strJSON = pszJSON; free((void*)pszJSON); // 加密JSON数据 unsigned int nBuffLen = 0; unsigned char* pBufferData = crypto::BlowfishEncode((const unsigned char*)strJSON.c_str(), strJSON.length(), nBuffLen); // 保存数据到磁盘 std::string strPath = CCFileUtils::sharedFileUtils()->getWritablePath() + ARCHIVEMENT_FILE_NAME; FILE* file = fopen(strPath.c_str(), "wb"); CCAssert(file, "archivement file open failed..."); if (file) { fwrite(pBufferData, 1, nBuffLen, file); fflush(file); fclose(file); } // 删除加密生成的零时数据 delete pBufferData; return true; }
[ "sosoayaen@gmail.com" ]
sosoayaen@gmail.com
b8237907f2562337623db8a1ae5d6317c36bc7f7
d8efaf8e35f7d203d50cb4f87bc7313187d9f6e1
/build/Android/Preview/MyFirstFuseProject/app/src/main/include/Fuse.Controls.Native.Android.Button.h
ed58f4c9fb0ff7fe5144500f55fce134af44119c
[]
no_license
eddzmaciel/fproject_fp
fe33dc03b82047e88fad9e82959ee92d6da49025
2760ddb66c749651f163c3c1a3bc7b6820fbebae
refs/heads/master
2020-12-04T12:38:37.955298
2016-09-02T02:23:31
2016-09-02T02:23:31
67,182,558
0
0
null
null
null
null
UTF-8
C++
false
false
1,405
h
// This file was generated based on C:\ProgramData\Uno\Packages\Fuse.Controls.Native\0.33.5\Android\$.uno. // WARNING: Changes might be lost if you edit this file directly. #pragma once #include <Fuse.Controls.Native.Android.LeafView.h> #include <Fuse.Controls.Native.ILabelView.h> #include <Fuse.Controls.Native.ILeafView.h> #include <Fuse.Controls.Native.IView.h> #include <Uno.IDisposable.h> namespace g{namespace Fuse{namespace Controls{namespace Native{namespace Android{struct Button;}}}}} namespace g{namespace Java{struct Object;}} namespace g{ namespace Fuse{ namespace Controls{ namespace Native{ namespace Android{ // public sealed extern class Button :11 // { struct Button_type : ::g::Fuse::Controls::Native::Android::LeafView_type { ::g::Fuse::Controls::Native::ILabelView interface3; }; Button_type* Button_typeof(); void Button__ctor_2_fn(Button* __this); void Button__Create_fn(::g::Java::Object** __retval); void Button__New1_fn(Button** __retval); void Button__SetText_fn(::g::Java::Object* handle, uString* text); void Button__set_Text_fn(Button* __this, uString* value); struct Button : ::g::Fuse::Controls::Native::Android::LeafView { void ctor_2(); void Text(uString* value); static ::g::Java::Object* Create(); static Button* New1(); static void SetText(::g::Java::Object* handle, uString* text); }; // } }}}}} // ::g::Fuse::Controls::Native::Android
[ "Edson Maciel" ]
Edson Maciel
6c6c634948ed90b33db759163c4ca861359c6fa4
0c8d32541c551becff64126f10a408ebc16e5479
/数据结构实践教程徐慧源码/8_ ˜/Thread/InThreading/Base.cpp
99ee9c7242d8dfb839124fa6482adf0e5990eac6
[]
no_license
nlpcvai/datastructure
ba9c55f7af94f9c440169273d2cbc5b48eb9846c
693c770cd5be0f638a3d871a53b5178e03909e93
refs/heads/master
2020-04-21T11:29:43.910876
2019-06-08T02:44:20
2019-06-08T02:44:20
169,527,465
0
0
null
2019-02-07T07:06:16
2019-02-07T06:12:20
C++
GB18030
C++
false
false
2,769
cpp
#include<iostream> #include "windows.h" using namespace std; //定义线索二叉树的结点类型 template <class T> struct BiThrNode { T data; //数据域 int lflag; //左标志域 int rflag; //右标志域 BiThrNode<T> *lchild; //左指针域 BiThrNode<T> *rchild; //右指针域 }; //-------------------------------------------------------------------------------- //基类 template <class T> class CThr { public: BiThrNode<T>*BT; //二叉树的根结点指针 CThr(){BT=NULL;}; //构造函数,对二叉链表进行初始化 ~CThr(); //析构函数,释放结点占用的空间 void DeleteNode(){Clear(BT,0);} //释放结点空间 void Clear(BiThrNode<T>*bt,int flag); void CreateBiTree(T end); //创建二叉链表 void create(BiThrNode<T>*p,int flag,T end); BiThrNode<T>* GetRoot() { return BT; } }; //-------------------------------------------------------------------------------- template <class T> CThr<T>::~CThr() { DeleteNode(); BT=NULL; } //------------------------------------------------------------------------------ template <class T> void CThr<T>::Clear(BiThrNode<T>*bt,int flag) { if(bt&&flag!=1) { Clear(bt->lchild,bt->lflag);//释放左子树的结点 Clear(bt->rchild,bt->rflag);//释放右子树的结点 cout<<bt->data<<" :释放了指针 "<<bt<<" 所指向的空间。"<<endl; delete bt; //释放当前访问的结点 } } //-------------------------------------------------------------------------------- template <class T> void CThr<T>::CreateBiTree(T end) {//创建二叉链表,创建好的二叉树还没有线索化。 cout<<"按先序序列输入二叉树结点值,-1未结束标志: "; BiThrNode<T>*p; T x; cin>>x; if(x!=end) //线索二叉树不为空 { p=new BiThrNode<T>; p->data=x; p->lchild=NULL; p->rchild=NULL; p->lflag=0; p->rflag=0; BT=p; //p作为二叉线索树的根结点 create(p,1,end); //创建左子树 create(p,2,end); //创建右子树 } } //-------------------------------------------------------------------------------- template <class T> void CThr<T>::create(BiThrNode<T>*p,int flag,T end) { //创建一棵二叉树,flag为1时创建左子树,2时创建右子树,end为结束的标志 BiThrNode<T>*q; T x; cin>>x; //输入结点的值 if(x!=end) { q=new BiThrNode<T>; //申请二叉链表结点 q->data=x; q->lchild = NULL; q->rchild = NULL; q->lflag = 0; q->rflag = 0; if(flag==1)p->lchild=q; //链接到左子树 if(flag==2)p->rchild=q; //链接到右子树 create(q,1,end); //创建左子树 create(q,2,end); //创建右子树 } }
[ "mason@Masons-MacBook-Pro.local" ]
mason@Masons-MacBook-Pro.local
171fcff5f853ed3aa3c85ff70fb97b0ca85ae07a
78702fe7939d3d4a245148172825c70c1c181ae0
/le_style_initializer.hpp
3b2b1be019b69e497cddfe40d68052be07d5009b
[]
no_license
chrisdjscott/pspectre-cuda
54a7cb6745a00c1a95f30c24a643418ca16728a1
685c3cc87b709984b3783f310a6a6b0da0c1d4e3
refs/heads/master
2021-01-20T11:51:39.416184
2016-11-22T22:28:31
2016-11-22T22:28:31
75,973,104
0
0
null
2016-12-08T20:35:44
2016-12-08T20:35:44
null
UTF-8
C++
false
false
2,468
hpp
/* * SpectRE - A Spectral Code for Reheating * Copyright (C) 2009-2010 Hal Finkel, Nathaniel Roth and Richard Easther * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED ``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 AUTHORS 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. */ /** * @file * @brief LatticeEasy-style initialization. */ #ifndef LE_STYLE_INITIALIZER_HPP #define LE_STYLE_INITIALIZER_HPP #include "field_size.hpp" #include "model_params.hpp" #include "field.hpp" #include "initializer.hpp" #include <cmath> #include <cufftw.h> template <typename R> class le_style_initializer : public initializer<R> { public: le_style_initializer(field_size &fs_, field<R> &phi_, field<R> &phidot_, field<R> &chi_, field<R> &chidot_, R adot_, R len0) : fs(fs_), phi(phi_), phidot(phidot_), chi(chi_), chidot(chidot_), adot(adot_) { using namespace std; fluctuation_amplitude = RESCALE_A * RESCALE_B * fs_.total_gridpoints / (pow(MP_LEN/len0, (R) 1.5) * sqrt(2.)); } public: virtual void initialize(); protected: void set_mode(fftw_complex *fld, fftw_complex *flddot, R m_fld_eff, int px, int py, int pz, int idx, bool real = false); void initialize_field(field<R> &fld, field<R> &flddot, R m_fld_eff); protected: field_size &fs; field<R> &phi, &phidot; field<R> &chi, &chidot; R adot; R fluctuation_amplitude; }; #endif // LE_STYLE_INITIALIZER_HPP
[ "cliu712@aucklanduni.ac.nz" ]
cliu712@aucklanduni.ac.nz
9a88648ca7e1794565d77b8d65ad05a4b713292d
f281d0d6431c1b45c6e5ebfff5856c374af4b130
/DAY200~299/DAY223-programmers-길 찾기 게임/joohyuk.cpp
3c80b275e9f6c5b68e863d189de2fc99538086eb
[]
no_license
tachyon83/code-rhino
ec802dc91dce20980fac401b26165a487494adb4
b1af000f5798cd12ecdab36aeb9c7a36f91c1101
refs/heads/master
2022-08-13T09:10:16.369287
2022-07-30T11:27:34
2022-07-30T11:27:34
292,142,812
5
6
null
null
null
null
UTF-8
C++
false
false
2,450
cpp
#include <iostream> #include <algorithm> #include <vector> #define endl '\n' using namespace std; vector<pair<int, pair<int, int>>> coords; vector<pair<int,int>>coordMap; struct Tree{ int n,root,previous; vector<int>parent; vector<int>lc,rc; vector<vector<int>>ret; vector<int>pre; vector<int>post; Tree():n(0){} Tree(int num):n(num){ root=0; parent.resize(n); lc.resize(n,0); rc.resize(n,0); } void preOrder(int root){ pre.push_back(root); if(lc[root]) preOrder(lc[root]); if(rc[root]) preOrder(rc[root]); } void postOrder(int root){ if(lc[root]) postOrder(lc[root]); if(rc[root]) postOrder(rc[root]); post.push_back(root); } void addOrders(){ ret.push_back(pre); ret.push_back(post); } void makeTree(vector<pair<int, pair<int, int>>> coords){ int i=0; if(!root)root=coords[i].first; while(i<(int)coords.size()){ i++; if(i==(int)coords.size())break; auto currNum=coords[i].first; auto currCoord=coords[i].second; auto p=root; while(1){ if(currCoord.first<coordMap[p].first){ if(!lc[p]){ lc[p]=currNum; parent[currNum]=p; break; }else p=lc[p]; }else{ if(!rc[p]){ rc[p]=currNum; parent[currNum]=p; break; }else p=rc[p]; } } } } }; bool cmp(const pair<int, pair<int, int>> &a, const pair<int, pair<int, int>> &b) { if (a.second.second < b.second.second) return 0; if (a.second.second > b.second.second) return 1; if (a.second.first > b.second.first) return 0; return 1; } vector<vector<int>> solution(vector<vector<int>> nodeinfo) { Tree T((int)nodeinfo.size()+1); coordMap.resize((int)nodeinfo.size()+1); for (int i = 0; i < nodeinfo.size(); ++i) { coords.push_back({i + 1, {nodeinfo[i][0], nodeinfo[i][1]}}); coordMap[i+1]={nodeinfo[i][0], nodeinfo[i][1]}; } sort(coords.begin(), coords.end(), cmp); T.makeTree(coords); T.preOrder(T.root); T.postOrder(T.root); T.addOrders(); return T.ret; }
[ "noreply@github.com" ]
tachyon83.noreply@github.com
aacdf91f0d6c087b3102f25c8bc4c9e0f725666a
7f8671aba692d8af83a4bc2d252d01a101b534c6
/Animal.cpp
6b1a169568f858d283306a957934483508df4a6c
[]
no_license
KonstantinaTodorova/Week12task1
51d5016a61a11f6200a7651d78ae748e6128f589
51ea0da7bbc95a755d868e63469bcc8ca82a5a9e
refs/heads/master
2020-07-23T07:36:23.311347
2017-06-14T17:06:37
2017-06-14T17:06:37
94,353,095
0
0
null
null
null
null
UTF-8
C++
false
false
98
cpp
#include "Animal.h" Animal::Animal() { //ctor } Animal::~Animal() { //dtor }
[ "noreply@github.com" ]
KonstantinaTodorova.noreply@github.com
63cc7afc5d082b9ad6c9321b0a789fbacb686930
831ec03d2c55693fe95dd4dcbcbebb7c4853dea9
/sdl02_text/Shader.h
99aacb29a70537199fb627ace0508a94e3d4ea4f
[]
no_license
FrankEndriss/opengltest
f0f4842e6be849c9da876c0d1e3fd8fb669ba39a
e038c625514b140042e181402980c4cf8508cad9
refs/heads/master
2021-09-01T15:03:07.219661
2017-12-27T15:37:18
2017-12-27T15:37:18
112,651,243
0
0
null
null
null
null
UTF-8
C++
false
false
730
h
#ifndef SHADER_H_ #define SHADER_H_ #include "gl_include.h" #include <ostream> #include <string> /** Shader-Compiler interface. */ class Shader { public: /** @param type GL_FRAGMENT_SHADER or GL_VERTEX_SHADER */; Shader(GLenum type); virtual ~Shader(); /** Frontend to compile(source...) * @param path to source of shader */ GLint compileFile(const std::string& path); /** @param source lines of sourcecode * @param lineCount number of lines, each one null terminated * @return true for SUCCESS, else dumpCompileInfo will contain useful info */ GLint compile(char** sourceLines, int lineCount); void dumpCompileInfo(); GLuint shader; private: GLint compileInfoAvailable=0; }; #endif /* SHADER_H_ */
[ "Frank.Endriss@bancos.com" ]
Frank.Endriss@bancos.com
4058e3e835df346b9ca755ee730041c09e21d812
70e0667e2281db6f67ac44a179164474a588dd3c
/cyber/transport/qos/qos_profile_conf.h
94c07d33f308dc1a834543e2a65197445cee6c9c
[ "Apache-2.0" ]
permissive
L-Net-1992/apollo_windows
dd06bfaf648179c9334b87d1aa8dc11878a78a83
78db2493b7356f012ec5342c27c11ff592c664c5
refs/heads/master
2023-03-17T15:13:11.221761
2020-05-04T13:41:37
2020-05-04T14:28:08
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,210
h
/****************************************************************************** * Copyright 2018 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #ifndef CYBER_TRANSPORT_QOS_QOS_PROFILE_CONF_H_ #define CYBER_TRANSPORT_QOS_QOS_PROFILE_CONF_H_ #include <cstdint> #include "cyber/proto/qos_profile.pb.h" #include "cyber/platform/macros.h" namespace apollo { namespace cyber { namespace transport { using cyber::proto::QosDurabilityPolicy; using cyber::proto::QosHistoryPolicy; using cyber::proto::QosProfile; using cyber::proto::QosReliabilityPolicy; class CYBER_API QosProfileConf { public: QosProfileConf(); virtual ~QosProfileConf(); static QosProfile CreateQosProfile(const QosHistoryPolicy& history, uint32_t depth, uint32_t mps, const QosReliabilityPolicy& reliability, const QosDurabilityPolicy& durability); static const uint32_t QOS_HISTORY_DEPTH_SYSTEM_DEFAULT; static const uint32_t QOS_MPS_SYSTEM_DEFAULT; static const QosProfile QOS_PROFILE_DEFAULT; static const QosProfile QOS_PROFILE_SENSOR_DATA; static const QosProfile QOS_PROFILE_PARAMETERS; static const QosProfile QOS_PROFILE_SERVICES_DEFAULT; static const QosProfile QOS_PROFILE_PARAM_EVENT; static const QosProfile QOS_PROFILE_SYSTEM_DEFAULT; static const QosProfile QOS_PROFILE_TF_STATIC; static const QosProfile QOS_PROFILE_TOPO_CHANGE; }; } // namespace transport } // namespace cyber } // namespace apollo #endif // CYBER_TRANSPORT_QOS_QOS_PROFILE_CONF_H_
[ "mjopenglsdl@gmail.com" ]
mjopenglsdl@gmail.com
d0f17d4977ef18c45c10dc55c28358f1e2cbe48d
c02e6a950d0bf2ee8c875c70ad707df8b074bb8e
/build/Android/Release/bimcast/app/src/main/include/Uno.Threading.FutureState.h
37a04d7fac167e26bdb084197903fe0a0904745a
[]
no_license
BIMCast/bimcast-landing-ui
38c51ad5f997348f8c97051386552509ff4e3faf
a9c7ff963d32d625dfb0237a8a5d1933c7009516
refs/heads/master
2021-05-03T10:51:50.705052
2016-10-04T12:18:22
2016-10-04T12:18:22
69,959,209
0
0
null
null
null
null
UTF-8
C++
false
false
337
h
// This file was generated based on C:\ProgramData\Uno\Packages\Uno.Threading\0.35.8\$.uno. // WARNING: Changes might be lost if you edit this file directly. #pragma once #include <Uno.Int.h> namespace g{ namespace Uno{ namespace Threading{ // public enum FutureState :185 uEnumType* FutureState_typeof(); }}} // ::g::Uno::Threading
[ "mabu@itechhub.co.za" ]
mabu@itechhub.co.za
998f4f025a735f011df64dafc3c3ef6ba1f17835
bb34d131b3afdf3b30d9ddde92eb10b62dc35c93
/Original/Ball.cpp
ae626af60059d765882d961e02b5733588f02e8d
[]
no_license
SKY-Crew/libraries
f92739783ccd3538667912f4d72081ee32fc07a9
4b5b8c662fefec602a5265fe590cc280f2844445
refs/heads/master
2020-04-13T08:45:16.913876
2019-09-07T10:53:44
2019-09-07T10:53:44
163,091,118
4
0
null
null
null
null
UTF-8
C++
false
false
4,200
cpp
#include "Ball.h" Ball::Ball(uint8_t QTY, uint8_t *PORT, uint8_t MEASURING_COUNT, uint16_t THRE_WEAK, double CHANGE_RATE, double CHANGE_RATE_T, double PLUS_T, uint8_t SIZE_THRE_DIST, double *THRE_DIST, uint8_t SIZE_DIR, double **DIR, double **PLUS_DIR, uint8_t P_CATCH, uint16_t THRE_CATCH, uint16_t MAX_C_CATCH, uint16_t MAX_C_MAY_KICK) { // copy this->QTY = QTY; this->PORT = new uint8_t[QTY]; copyArray(this->PORT, PORT, QTY); COS_IR = new double[QTY]; SIN_IR = new double[QTY]; for(int i = 0; i < QTY; i ++) { COS_IR[i] = cos(toRadians(i * 360.0 / QTY)); SIN_IR[i] = sin(toRadians(i * 360.0 / QTY)); } this->MEASURING_COUNT = MEASURING_COUNT; this->THRE_WEAK = THRE_WEAK; this->CHANGE_RATE = CHANGE_RATE; this->CHANGE_RATE_T = CHANGE_RATE_T; this->PLUS_T = PLUS_T; this->SIZE_THRE_DIST = SIZE_THRE_DIST; this->THRE_DIST = new double[SIZE_THRE_DIST]; copyArray(this->THRE_DIST, THRE_DIST, SIZE_THRE_DIST); this->SIZE_DIR = SIZE_DIR; this->DIR = new double*[SIZE_THRE_DIST]; copyArray(this->DIR, DIR, SIZE_THRE_DIST); this->PLUS_DIR = new double*[SIZE_THRE_DIST]; copyArray(this->PLUS_DIR, PLUS_DIR, SIZE_THRE_DIST); val = new uint16_t[QTY]; weak = new uint16_t[QTY]; prv = new uint16_t[QTY]; crt = new uint16_t[QTY]; this->P_CATCH = P_CATCH; this->THRE_CATCH = THRE_CATCH; // init for(uint8_t numBall = 0; numBall < QTY; numBall ++) { prv[numBall] = 0; } for(uint8_t numBall = 0; numBall < QTY; numBall ++) { pinMode(PORT[numBall], INPUT); } cCatch.set_MAX(MAX_C_CATCH); cCatch.set_COUNT_UP(false); cMayKick.set_MAX(MAX_C_MAY_KICK); } vectorRT_t Ball::get() { vectorRT_t vRT = {0, 0}; bool findingBall = true; // 初期化 for(int numBall = 0; numBall < QTY; numBall ++) { val[numBall] = 0; } // 計測 uint64_t time = micros(); uint16_t countMax = 0; while(micros() - time < CYCLE * MEASURING_COUNT) { countMax ++; for(uint8_t numBall = 0; numBall < QTY; numBall ++) { val[numBall] += !digitalRead(PORT[numBall]); } } // 比率化 for(uint8_t numBall = 0; numBall < QTY; numBall ++) { val[numBall] *= 1000.0 / (double) countMax; } for(uint8_t numBall = 0; numBall < QTY; numBall ++) { if(val[numBall] > 0) { findingBall = false; // 平均値計算 if(prv[numBall] > 0) { val[numBall] = filter(val[numBall], prv[numBall], CHANGE_RATE); } } // 平均値保存 prv[numBall] = val[numBall]; } // 距離計算 vRT.r = mean(val, QTY); // 弱反応切り捨て bool isAllWeak = true; for(uint8_t numBall = 0; numBall < QTY; numBall ++) { if(val[numBall] > THRE_WEAK) { isAllWeak = false; break; } } for(uint8_t numBall = 0; numBall < QTY; numBall ++) { weak[numBall] = isAllWeak ? val[numBall] : max(val[numBall] - THRE_WEAK, 0); } // ベクトル合成 vectorXY_t vXY = {0, 0}; for(uint8_t numBall = 0; numBall < QTY; numBall ++) { vXY.x += weak[numBall] * COS_IR[numBall]; vXY.y += weak[numBall] * SIN_IR[numBall]; } vRT.t = toDegrees(atan2(vXY.y, vXY.x)); // null判定 if(findingBall) { vRT.t = false; }else { vRT.t += PLUS_T; } vRT.r *= map(double(abs(vRT.t)), 0, 180, 2.5, 4.9); vRT.r = filter(vRT.r, prvBall.r, CHANGE_RATE_T); prvBall = vRT; trace(2) { Serial.println("Ball:"+str(val,QTY)); } return vRT; } uint16_t *Ball::getVal() { for(int numBall = 0; numBall < QTY; numBall ++) { crt[numBall] = val[numBall]; } return crt; } uint8_t Ball::getQTY() { return QTY; } uint16_t Ball::getForward() { return val[0]; } Angle Ball::getDir(vectorRT_t ball) { Angle dir = ball.t; if(bool(ball.t)) { double plusDir[SIZE_THRE_DIST]; for(uint8_t distIndex = 0; distIndex < SIZE_THRE_DIST; distIndex ++) { plusDir[distIndex] = polyLine(double(dir), DIR[distIndex], PLUS_DIR[distIndex], SIZE_DIR); } dir += polyLine(ball.r, THRE_DIST, plusDir, SIZE_THRE_DIST); } return dir; } bool Ball::getCatch() { valCatch = analogRead(P_CATCH); cCatch.increase(valCatch < THRE_CATCH); return bool(cCatch); } bool Ball::getMayKick() { cMayKick.increase(valCatch < THRE_CATCH); return bool(cMayKick); } bool Ball::compareCatch(double rate) { return cCatch.compare(rate); } uint16_t Ball::getValCatch() { return valCatch; }
[ "43493783+SKY-Crew@users.noreply.github.com" ]
43493783+SKY-Crew@users.noreply.github.com
90afa82c6cd206b5c9a9fd8e14b043a99351de81
d01c898d2fe3acccb7ab5307af74b0a43605ff7c
/SerialCom/ATCommandResponsePacket.h
5d17343a14423987d6eb7c10705046245354e249
[]
no_license
roelstorms/zigbeeWSN
66a6dcf6abe7f9df7e7679001ec19d4ab757c3b3
de08d3005fc4982ae3e70ce8bbb50ed1e77e08da
refs/heads/master
2020-04-15T19:00:06.571864
2013-04-12T09:20:42
2013-04-12T09:20:42
8,478,209
1
0
null
null
null
null
UTF-8
C++
false
false
954
h
#ifndef ATCOMMANDRESPONSEPACKET_H #define ATCOMMANDRESPONSEPACKET_H #include <string> #include <stdio.h> /* Standard input/output definitions */ #include <iostream> #include "packet.h" class ATCommandResponsePacket : public Packet { private: unsigned char frameID, commandStatus; std::vector <unsigned char> ATCommand, data; public: ATCommandResponsePacket(); ATCommandResponsePacket(const Packet& aPacket); ATCommandResponsePacket(unsigned char aChecksum, unsigned char aType, unsigned char aSizeLSB, unsigned char aSizeMSB,std::vector<unsigned char> aEncodedPacket, unsigned char aFrameID, unsigned char aCommandStatus, std::vector <unsigned char>aATCommand, std::vector<unsigned char> aData); ~ATCommandResponsePacket(); void setFrameID(unsigned char aFrameID); void setCommandStatus(unsigned char aCommandStatus); void setATCommand(std::vector<unsigned char> aATCommand); void setData(std::vector<unsigned char> adata); }; #endif
[ "roelstorms@hotmail.com" ]
roelstorms@hotmail.com
bf827c52bf02b5f40885688e384030e5e2e6fb0a
fca4a88a76d9f255cb975395bb49c87ef2af0f66
/src/common/GlobalParameters.cc
a32d76fe891661e8d30baaa02ba723b33b50c0ec
[]
no_license
aarizaq/Oversim-20121206
110d57b1f171221fd1d72ee70acaa883f5778fb6
84124b18033c9beb24e4826aa85485683ce75b2a
refs/heads/master
2021-05-04T10:42:37.041454
2017-01-30T19:08:17
2017-01-30T19:08:17
8,455,640
2
4
null
null
null
null
UTF-8
C++
false
false
1,209
cc
// // Copyright (C) 2007 Institut fuer Telematik, Universitaet Karlsruhe (TH) // // 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. // /** * @file GlobalParameters.cc * @author IngmarBaumgart */ #include <omnetpp.h> #include <OverlayKey.h> #include "GlobalParameters.h" Define_Module(GlobalParameters); void GlobalParameters::initialize() { printStateToStdOut = par("printStateToStdOut"); if (!ev.isDisabled()) { ev.getOStream().setf(std::ios::fixed, std::ios::floatfield); ev.getOStream().precision(3); } }
[ "aarizaq_m@hotmail.com" ]
aarizaq_m@hotmail.com
7114709a508fe4d6aa8e3c3e28d101731058da97
e39117e739995759b9407a400846e5786e5b5f5d
/include/dish2/genome/KinGroupEpochStamps.hpp
7cd6fe69be5d0c6a056d1f0eb58406ebad6168fb
[ "MIT" ]
permissive
perryk12/dishtiny
5f18c5df1d97a49e58697ec7317773ae5c756ef6
4177f09eed90f3b73f952858677fc4001ac6175a
refs/heads/master
2023-03-28T14:06:56.626589
2021-03-25T05:34:50
2021-03-25T05:36:10
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,293
hpp
#pragma once #ifndef DISH2_GENOME_KINGROUPEPOCHSTAMPS_HPP_INCLUDE #define DISH2_GENOME_KINGROUPEPOCHSTAMPS_HPP_INCLUDE #include <algorithm> #include <utility> #include "../../../third-party/cereal/include/cereal/cereal.hpp" #include "../../../third-party/cereal/include/cereal/types/array.hpp" #include "../../../third-party/Empirical/include/emp/base/array.hpp" #include "../../../third-party/signalgp-lite/include/sgpl/utility/ThreadLocalRandom.hpp" namespace dish2 { template<typename Spec> struct KinGroupEpochStamps { using buffer_t = emp::array< size_t, Spec::NLEV >; buffer_t data{}; KinGroupEpochStamps() = default; bool operator==(const KinGroupEpochStamps& other) const { return data == other.data; } bool operator<(const KinGroupEpochStamps& other) const { return data < other.data; } void ApplyInheritance( const size_t rep_lev, const size_t epoch ) { emp_assert( rep_lev <= Spec::NLEV ); std::fill( std::begin( data ), std::next( std::begin( data ), rep_lev ), epoch ); } const buffer_t& GetBuffer() const { return data; } template <class Archive> void serialize( Archive & ar ) { ar( CEREAL_NVP( data ) ); } }; } // namespace dish2 #endif // #ifndef DISH2_GENOME_KINGROUPEPOCHSTAMPS_HPP_INCLUDE
[ "mmore500.login+git@gmail.com" ]
mmore500.login+git@gmail.com
df3b93d33ac085d7ef0c58c2a971702e05817261
77dfa98a9cc290158c2d1c19629fe42446df821f
/core/lib/AFE-APIs/AFE-API .cpp
7118aa235524976ad03710d73c1d687b11815ff5
[ "MIT" ]
permissive
tandrejko/AFE-Firmware
30289c7d873e0c54104f5c49d4481056c4890928
3ee680e210412a933dc3512185dc7db34ac8027a
refs/heads/master
2022-12-19T18:31:10.140768
2020-10-13T14:23:45
2020-10-13T14:23:45
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,156
cpp
/* AFE Firmware for smart home devices, Website: https://afe.smartnydom.pl/ */ #include "AFE-API.h" AFEAPI::AFEAPI(){}; #ifdef AFE_CONFIG_HARDWARE_LED void AFEAPI::begin(AFEDataAccess *Data, AFEDevice *Device, AFELED *Led) { _Data = Data; _Device = Device; _Led = Led; if (_Device->configuration.api.mqtt) { Mqtt.begin(Data, Device->configuration.name, Led); } enabled = true; } #else void AFEAPI::begin(AFEDataAccess *Data, AFEDevice *Device) { _Data = Data; _Device = Device; if (_Device->configuration.api.mqtt) { Mqtt.begin(Data, Device->configuration.name); } enabled = true; } #endif // AFE_CONFIG_HARDWARE_LED #ifdef AFE_CONFIG_HARDWARE_RELAY void AFEAPI::addClass(AFERelay *Relay) { for (uint8_t i = 0; i < _Device->configuration.noOfRelays; i++) { _Relay[i] = Relay + i; #ifdef DEBUG Serial << endl << F("INFO: The reference to the relay: ") << i + 1 << F(" added"); #endif } } #endif // AFE_CONFIG_HARDWARE_RELAY #ifdef AFE_CONFIG_HARDWARE_SWITCH void AFEAPI::addClass(AFESwitch *Switch) { for (uint8_t i = 0; i < _Device->configuration.noOfSwitches; i++) { _Switch[i] = Switch + i; #ifdef DEBUG Serial << endl << F("INFO: The reference to the switch: ") << i + 1 << F(" added"); #endif } } #endif // AFE_CONFIG_HARDWARE_SWITCH #ifdef AFE_CONFIG_HARDWARE_ADC_VCC void AFEAPI::addClass(AFEAnalogInput *Analog) { _AnalogInput = Analog; #ifdef DEBUG Serial << endl << F("INFO: The reference to the ADC added"); #endif } #endif // AFE_CONFIG_HARDWARE_ADC_VCC #ifdef AFE_CONFIG_HARDWARE_BMEX80 void AFEAPI::addClass(AFESensorBMEX80 *Sensor) { for (uint8_t i = 0; i < _Device->configuration.noOfBMEX80s; i++) { _BMx80Sensor[i] = Sensor + i; } #ifdef DEBUG Serial << endl << F("INFO: The reference to the BMEX80 added"); #endif } #endif // AFE_CONFIG_HARDWARE_BMEX80 #ifdef AFE_CONFIG_HARDWARE_HPMA115S0 void AFEAPI::addClass(AFESensorHPMA115S0 *Sensor) { for (uint8_t i = 0; i < _Device->configuration.noOfHPMA115S0s; i++) { _HPMA115S0Sensor[i] = Sensor + i; } #ifdef DEBUG Serial << endl << F("INFO: The reference to the HPMA115S0 added"); #endif } #endif // AFE_CONFIG_HARDWARE_HPMA115S0 #ifdef AFE_CONFIG_HARDWARE_BH1750 void AFEAPI::addClass(AFESensorBH1750 *Sensor) { for (uint8_t i = 0; i < _Device->configuration.noOfBH1750s; i++) { _BH1750Sensor[i] = Sensor + i; } #ifdef DEBUG Serial << endl << F("INFO: The reference to the BH1750 added"); #endif } #endif // AFE_CONFIG_HARDWARE_BH1750 #ifdef AFE_CONFIG_HARDWARE_AS3935 void AFEAPI::addClass(AFESensorAS3935 *Sensor) { for (uint8_t i = 0; i < _Device->configuration.noOfAS3935s; i++) { _AS3935Sensor[i] = Sensor + i; } #ifdef DEBUG Serial << endl << F("INFO: The reference to the AS3935 added"); #endif } #endif // AFE_CONFIG_HARDWARE_AS3935 #ifdef AFE_CONFIG_HARDWARE_ANEMOMETER_SENSOR void AFEAPI::addClass(AFESensorAnemometer *AnemometerSensor) { _AnemometerSensor = AnemometerSensor; #ifdef DEBUG Serial << endl << F("INFO: The reference to the Anemometer added"); #endif } #endif // AFE_CONFIG_HARDWARE_ANEMOMETER_SENSOR #ifdef AFE_CONFIG_HARDWARE_RAINMETER_SENSOR void AFEAPI::addClass(AFESensorRainmeter *RainmeterSensor) { _RainmeterSensor = RainmeterSensor; #ifdef DEBUG Serial << endl << F("INFO: The reference to the Rain added"); #endif } #endif // AFE_CONFIG_HARDWARE_RAINMETER_SENSOR #ifdef AFE_CONFIG_HARDWARE_GATE void AFEAPI::addClass(AFEGate *Item) { for (uint8_t i = 0; i < _Device->configuration.noOfGates; i++) { _Gate[i] = Item + i; #ifdef DEBUG Serial << endl << F("INFO: The reference to the Gate: ") << i + 1 << F(" added"); #endif } } #endif // AFE_CONFIG_HARDWARE_GATE #ifdef AFE_CONFIG_HARDWARE_CONTACTRON void AFEAPI::addClass(AFEContactron *Item) { for (uint8_t i = 0; i < _Device->configuration.noOfContactrons; i++) { _Contactron[i] = Item + i; #ifdef DEBUG Serial << endl << F("INFO: The reference to the Contactron: ") << i + 1 << F(" added"); #endif } } #endif // AFE_CONFIG_HARDWARE_CONTACTRON #ifdef AFE_CONFIG_HARDWARE_DS18B20 void AFEAPI::addClass(AFESensorDS18B20 *Sensor) { for (uint8_t i = 0; i < _Device->configuration.noOfDS18B20s; i++) { _DS18B20Sensor[i] = Sensor + i; } #ifdef DEBUG Serial << endl << F("INFO: The reference to the DS18B20 added"); #endif } #endif // AFE_CONFIG_HARDWARE_DS18B20 #ifdef AFE_CONFIG_FUNCTIONALITY_REGULATOR void AFEAPI::addClass(AFERegulator *Regulator) { for (uint8_t i = 0; i < _Device->configuration.noOfRegulators; i++) { _Regulator[i] = Regulator + i; } #ifdef DEBUG Serial << endl << F("INFO: The reference to the Regulator added"); #endif } #endif // AFE_CONFIG_FUNCTIONALITY_REGULATOR #ifdef AFE_CONFIG_FUNCTIONALITY_THERMAL_PROTECTOR void AFEAPI::addClass(AFEThermalProtector *Protector) { for (uint8_t i = 0; i < _Device->configuration.noOfThermalProtectors; i++) { _ThermalProtector[i] = Protector + i; } #ifdef DEBUG Serial << endl << F("INFO: The reference to the Thermal Protector added"); #endif } #endif // AFE_CONFIG_FUNCTIONALITY_THERMAL_PROTECTOR
[ "github@adrian.czabanowski.com" ]
github@adrian.czabanowski.com
dfab78a729cf84d70b0262340d27c5d3c0505b37
7537ec24921bb5451ded39f6e1a7172b901bd2a7
/Tutorial4/from2Dto3D/src/from2Dto3D.cpp
5136b733f4856297369eefd9e9388334a5d8cebe
[]
no_license
chjYuan/Robocupathome
f2a80f8e9ea2790c73fc35ecffbb113d79b2593d
ab5724fc9fd71e839abb4cbb7128556f3038c0e7
refs/heads/master
2022-11-25T12:47:07.836592
2020-07-19T17:57:48
2020-07-19T17:57:48
280,920,965
3
1
null
null
null
null
UTF-8
C++
false
false
265
cpp
#include <from2Dto3D/from2Dto3D.h> int main(int argc, char** argv) { ros::init(argc, argv, "from2Dto3D"); ros::NodeHandle nh; ROS_INFO("Node from2Dto3D starting"); From2Dto3D node(nh); //ros::Rate r(60); ros::spin(); return 0; }
[ "jerrycj@gmail.com" ]
jerrycj@gmail.com
ca7f66005a04bf81ad735ff2bccc84cd282329e4
5886af31cfcb72f3d1a806b4f8a693addf448a9f
/ft_container/list/node.hpp
11d57225e8e504169bc831ec66395fd7601d5ee8
[]
no_license
qmarow/ft_container
15be3f159aea8bf5e4bbc245a8b12e8b41f808ff
5f2e7732cec437f9abcfdc968c7edff971cffcd1
refs/heads/main
2023-04-16T16:19:29.021221
2021-05-04T11:16:23
2021-05-04T11:16:23
364,230,123
0
0
null
null
null
null
UTF-8
C++
false
false
424
hpp
#ifndef NODE_HPP #define NODE_HPP template<typename T> class _node { public: _node *prev; _node *next; T elem; _node(T _elem = T()): prev(0), next(0), elem(_elem) {}; _node():prev(0), next(0) {}; _node(_node *_prev, _node *_next, T _elem = T()): elem(_elem), prev(_prev), next(_next) {}; _node(const _node &other) { this->next = other.next; this->elem = other.elem; this->prev = other.prev; } }; #endif
[ "noreply@github.com" ]
qmarow.noreply@github.com
f765117833d3de90cdff2048bfd518195eaa24a0
5c7a078cbf0b528ba9529e03cfb98d6bda6d57ec
/Level_03/03/Account.cpp
4e2fe89784244b19614c8fc6d27c61c3acc032a3
[]
no_license
LeeJunJae/MyStudy
383bfd9c2d68a374c43f22a5dc65fa11f81ed046
759b13de6ac3ee7b7b9f71c56256353510f696e5
refs/heads/master
2020-03-26T07:59:47.658829
2018-12-18T06:18:49
2018-12-18T06:18:49
144,605,544
0
0
null
null
null
null
UHC
C++
false
false
690
cpp
#include "Account.h" void Account::WithDraw(int money) { this->money += money; } void Account::Deposit(int money) { this->money -= money; } void Account::PrintInfo() { std::cout << "이름 : " << this->name << std::endl; std::cout << "계좌번호 : " << this->account_num << std::endl; std::cout << "잔액 : " << this->money << std::endl; } void Account::SetName(char * name) { this->name = new char[strlen(name)]; strcpy(this->name, name); } void Account::SetNum(int num) { this->account_num = num; } int Account::getNum() { return this->account_num; } Account::Account() { this->name = NULL; this->money = 0; this->account_num = NULL; } Account::~Account() { }
[ "wnswo158@gmail.com" ]
wnswo158@gmail.com
1519d5642b480ed2603dc9ec285d37fc171abeb9
c0aed0f338afb5c98f8c3acc777189936ab58cad
/hefur/hefur.cc
4921a9ea8ae06abb06b40e28e969b0ce763c2044
[ "MIT" ]
permissive
Lense/hefur
36b0e01e0570acccdd84a329cb737e958616d8fa
52f6cd25040cd954ab9e7a9172ac4624036a96d9
refs/heads/master
2021-01-20T03:21:21.501637
2020-12-02T02:25:45
2020-12-02T02:25:45
89,526,075
1
4
null
2017-04-26T20:59:20
2017-04-26T20:59:19
null
UTF-8
C++
false
false
1,071
cc
#include <cstring> #include <cerrno> #include "options.hh" #include "log.hh" #include "hefur.hh" #include "fs-tree-white-list.hh" namespace hefur { Hefur::Hefur() : tdb_(new TorrentDb) { instance_ = this; if (!TORRENT_DIR.empty()) wl_.reset(new FsTreeWhiteList(TORRENT_DIR, SCAN_INTERVAL * m::second)); if (UDP_PORT != 0) { udp_server_.reset(new UdpServer); udp_server_->start(UDP_PORT, IPV6); } if (HTTP_PORT != 0) { http_server_.reset(new HttpServer); http_server_->start(HTTP_PORT, IPV6, "", ""); } if (HTTPS_PORT != 0 && !CERT.empty() && !KEY.empty()) { https_server_.reset(new HttpServer); https_server_->start(HTTP_PORT, IPV6, CERT, KEY); } #ifdef HEFUR_CONTROL_INTERFACE if (!CONTROL_SOCKET.empty()) { control_server_ = new ControlServer; control_server_->start(CONTROL_SOCKET); } #endif } Hefur::~Hefur() { stop_.get(); } void Hefur::run() { stop_.get(); } void Hefur::stop() { stop_.set(true); } }
[ "bique.alexandre@gmail.com" ]
bique.alexandre@gmail.com
34bf2e5739b8285faafa47a964c028a3a979bb3e
9cd85e1feba3f899277ea72123b3a28af99674e7
/changeCasse.cpp
dcc0acfaf917797bc69cac0ed664a1db358fb947
[]
no_license
BenoitLedet/casse
0187089b3c5559f9b78d77b3425ac294112d65de
dc7dc64d69955f75d97600cc2cfff36acaef8a97
refs/heads/master
2021-03-31T01:43:21.264996
2018-03-08T10:24:50
2018-03-08T10:24:50
124,372,496
0
0
null
null
null
null
UTF-8
C++
false
false
539
cpp
// changeCasse.cpp // g++ -std=c++11 -Wall -Wextra -o changeCasse.out changeCasse.cpp #include <cctype> #include <iostream> int main() { std::string texte; while(std::getline(std::cin, texte)){ // change les minuscules par des majuscules et réciproquement for (char & c : texte) { if (std::islower(c)) std::cout << char(std::toupper(c)); else if (std::isupper(c)) std::cout << char(std::tolower(c)); else std::cout << c; } } return 0; }
[ "benouille62@live.fr" ]
benouille62@live.fr
014da2e5599ca01c033ba40dca57f0ff68a3e7df
0fbbc463454928ed51e5f7efcab637c0d924c757
/src/Socket/UdpSocket/UdpSocket/tests/src/UdpSocketTests.cpp
a145a8a7515c3dc989bb3d325aee8ff0ab2b3ae4
[]
no_license
zvoronz/unet
b9be18f389234da41434bb15f364b9db31f31ad7
d2522d5a49911f16681b91ae4b56e7d2829d0f0b
refs/heads/master
2020-06-25T05:37:46.617226
2014-08-14T11:41:47
2014-08-14T11:41:47
null
0
0
null
null
null
null
UTF-8
C++
false
false
391
cpp
#include <gtest/gtest.h> #include <Unet/UdpSocket.hpp> TEST ( UdpSocket , DoesNotThrowWhileDefaultConstruction ) { ASSERT_NO_THROW(Unet::UdpSocket()); } TEST ( UdpSocket , DoesNotThrowWhileOpening ) { Unet::UdpSocket udpSocket; ASSERT_NO_THROW(udpSocket.open()); } int main ( int argc , char** argv ) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
[ "oleynikovny@mail.ru" ]
oleynikovny@mail.ru
26861540ea5ea4b167ac58b44231d49ece6a4765
fa6dd038bee545feb0512e864488e370a4e50461
/src/ioacas_dll/interface242.cpp
ade2800f4b71c16f8aefd98b186323733ffc852a
[]
no_license
cnfntrvlnss/serv242_09
65a4a110e38cb4b74f2725dbc860488fef3e89b8
06a9e6aadfbc5658775e01c89d8d230484c8150d
refs/heads/master
2021-01-22T04:34:08.401576
2017-03-04T07:08:07
2017-03-04T07:08:07
81,557,878
0
0
null
null
null
null
UTF-8
C++
false
false
5,743
cpp
/************************************************************************* > File Name: interface242.cpp > Author: > Mail: > Created Time: Thu 09 Feb 2017 01:15:46 AM EST ************************************************************************/ #include "interface242.h" #include <sys/types.h> #include <dirent.h> #include <cstdio> #include <string> #include<iostream> #include "globalfunc.h" #include "../audiz/audizcli_p.h" //#include "log4z.h" using namespace std; static bool g_bInitialized = false; static unsigned int g_iModuleID; static SessionStruct *g_AudizSess; static ReceiveResult g_ReportResult; //static const char g_AudizPath[] = "ioacases/recogMain"; static string g_AudizPath = (string)"ioacases/" + AZ_DATACENTER; static int audiz_reportResult(Audiz_Result *pResult) { CDLLResult res; WavDataUnit data; res.m_pDataUnit[0] = &data; data.m_iDataLen = 0; data.m_pData = NULL; data.m_pPCB = NULL; data.m_iPCBID = pResult->m_iPCBID; res.m_iTargetID = pResult->m_iTargetID; res.m_iAlarmType = pResult->m_iAlarmType; res.m_iHarmLevel = pResult->m_iHarmLevel; res.m_fLikely = pResult->m_fLikely; LOGFMT_DEBUG(g_logger, "report target... PID=%lu TargetType=%u TargetID=%u.", res.m_pDataUnit[0]->m_iPCBID, res.m_iAlarmType, res.m_iTargetID); return g_ReportResult(g_iModuleID, &res); } static int audiz_getAllMdls(SpkMdlSt **pMdls) { return 0; } static string g_SmpDir = "SpkModel"; class SpkMdlStVecImpl: public SpkMdlStVec, SpkMdlStVec::iterator { public: ~SpkMdlStVecImpl(){ closedp(); } SpkMdlStVecImpl* iter(){ closedp(); if(g_SmpDir[g_SmpDir.size() - 1] != '/'){ g_SmpDir += "/"; } dp = opendir(g_SmpDir.c_str()); if(dp == NULL){ LOGFMT_ERROR(g_logger, "SpkMdlStVecImpl:iter failed to open dir %s.", g_SmpDir.c_str()); return NULL; } LOGFMT_DEBUG(g_logger, "SpkMdlStVecImpl::iter invoked."); return this; } SpkMdlSt* next(){ LOGFMT_DEBUG(g_logger, "SpkMdlStVecImpl::next invoked."); struct dirent *dirp = NULL; while(true){ dirp = readdir(dp); if(dirp == NULL){ closedp(); return NULL; } char *filename = dirp->d_name; if(strcmp(filename, ".") == 0) continue; if(strcmp(filename, ".") == 0) continue; int t1, t2, t3; if(sscanf(filename, "%d_%x_%d.", &t1, &t2, &t3) != 3){ continue; } strncpy(mdl.head, filename, SPKMDL_HDLEN-1); string filepath = g_SmpDir + mdl.head; FILE *fp = fopen(filepath.c_str(), "rb"); if(fp == NULL){ LOGFMT_ERROR(g_logger, "SpkMdlStVecImpl::next failed to open file %s.", filepath.c_str()); continue; } fseek(fp, 0, SEEK_END); mdl.len = ftell(fp); g_TmpData.resize(mdl.len); fseek(fp, 0, SEEK_SET); mdl.buf = const_cast<char*>(g_TmpData.c_str()); fread(mdl.buf, 1, mdl.len, fp); fclose(fp); return &mdl; } } private: void closedp(){ if(dp != NULL){ closedir(dp); dp = NULL; } } DIR *dp = NULL; SpkMdlSt mdl; string g_TmpData; }; static SpkMdlStVecImpl g_AllSmpVec; int InitDLL(int iPriority, int iThreadNum, int *pThreadCPUID, ReceiveResult func, int iDataUnitBufSize, char *path, unsigned int iModuleID) { if(g_bInitialized) { LOGE("InitDLL ioacas module has been already initialized."); return 0; } g_iModuleID = iModuleID; g_ReportResult = func; g_AudizSess = new SessionStruct(g_AudizPath.c_str(), audiz_reportResult, &g_AllSmpVec); g_bInitialized = true; g_AudizSess->feedAllSamples(); LOGI("InitDLL ioacas module is initialized successfully."); return 0; } int AddCfg(unsigned int id, const char *strName, const char *strConfigFile, int iType, int iHarmLevel) { return 0; } int AddCfgByBuf(const char *pData, int iDataBytes, unsigned int id, int iType, int iHarmLevel) { return 0; } int AddCfgByDir(int iType, const char *strDir) { return 0; } int RemoveAllCfg(int iType) { return 0; } int RemoveCfgByID(unsigned int id, int iType, int iHarmLevel) { return 0; } bool SetRecord(int iType, bool bRecord) { return 0; } int SendData2DLL(WavDataUnit *p) { clockoutput_start("SendData2DLL"); Audiz_WaveUnit unit; unit.m_iPCBID = p->m_iPCBID; unit.m_iDataLen = p->m_iDataLen; unit.m_pData = p->m_pData; unit.m_pPCB = p->m_pPCB; g_AudizSess->writeData(&unit); string output = clockoutput_end(); LOGFMT_TRACE(g_logger, output.c_str()); return 0; } int GetDLLVersion(char *p, int &length) { char strVersion[100]; strcpy(strVersion, "ioacas/lang v0.1.0"); length = strlen(strVersion); strncpy(p, strVersion, length); return 1; } int GetDataNum4Process(int iType[], int num[]) { return 0; } int CloseDLL() { delete g_AudizSess; return 0; } extern "C" void notifyProjFinish(unsigned long pid) { Audiz_WaveUnit unit; unit.m_iPCBID = pid; unit.m_iDataLen = 0; unit.m_pData = NULL; unit.m_pPCB = NULL; g_AudizSess->writeData(&unit); } extern "C" bool isAllFinished() { unsigned retm = g_AudizSess->queryUnfinishedProjNum(); if(retm != 0){ return false; } return true; } extern "C" bool isConn2Server() { return g_AudizSess->isConnected(); }
[ "zhengshurui@live.com" ]
zhengshurui@live.com
41b45e2310d7780176e804d8348759948c487c68
d94e3f62574489a2674dd83fa8c5f60eb8926d50
/elepheye/lib/Handles.cpp
648ad513bb7d10b2d12853f2adbfe12d46e7a17f
[ "MIT" ]
permissive
zbalkan/Elepheye
1118e6133413cf4e11fbdb893473ee4b37e95fc4
99455c478af8895657f08ba00bc88e7c7ae5c23e
refs/heads/master
2022-09-01T07:51:39.001576
2020-05-25T20:58:23
2020-05-25T20:58:23
266,878,541
0
0
null
null
null
null
UTF-8
C++
false
false
6,248
cpp
/* * Elepheye * * Copyright (c) 2009 Michito Kaji * * 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 <elepheye/ExceptionProxy.hpp> #include <elepheye/lib/Handles.hpp> namespace elepheye { namespace lib { Handles::BackupRead::BackupRead() throw() : Handle(0), file_(INVALID_HANDLE_VALUE) { } Handles::BackupRead::~BackupRead() throw() { if (INVALID_HANDLE_VALUE != file_ && get()) { if (!::BackupRead(file_, 0, 0, 0, TRUE, FALSE, &get())) { const ::DWORD error = ::GetLastError(); Exception e; e.setContext(getName()); e.setIssue(ELEPHEYE_RESOURCE_IDS_ISSUE_CLOSE_HANDLE); e.setWin32(error); e.setSource(_T(__FILE__), __LINE__); ExceptionProxy::log(e); } } } const ::HANDLE& Handles::BackupRead::getFile() const throw() { return file_; } ::HANDLE& Handles::BackupRead::getFile() throw() { return file_; } Handles::CloseHandle::CloseHandle() throw() : Handle(INVALID_HANDLE_VALUE) { } Handles::CloseHandle::~CloseHandle() throw() { if (INVALID_HANDLE_VALUE != get()) { if (!::CloseHandle(get())) { const ::DWORD error = ::GetLastError(); Exception e; e.setContext(getName()); e.setIssue(ELEPHEYE_RESOURCE_IDS_ISSUE_CLOSE_HANDLE); e.setWin32(error); e.setSource(_T(__FILE__), __LINE__); ExceptionProxy::log(e); } } } Handles::CryptDestroyHash::CryptDestroyHash() throw() : Handle(0) { } Handles::CryptDestroyHash::~CryptDestroyHash() throw() { if (get()) { if (!::CryptDestroyHash(get())) { const ::DWORD error = ::GetLastError(); Exception e; e.setContext(getName()); e.setIssue(ELEPHEYE_RESOURCE_IDS_ISSUE_CLOSE_HANDLE); e.setWin32(error); e.setSource(_T(__FILE__), __LINE__); ExceptionProxy::log(e); } } } Handles::CryptReleaseContext::CryptReleaseContext() throw() : Handle(0) { } Handles::CryptReleaseContext::~CryptReleaseContext() throw() { if (get()) { if (!::CryptReleaseContext(get(), 0)) { const ::DWORD error = ::GetLastError(); Exception e; e.setContext(getName()); e.setIssue(ELEPHEYE_RESOURCE_IDS_ISSUE_CLOSE_HANDLE); e.setWin32(error); e.setSource(_T(__FILE__), __LINE__); ExceptionProxy::log(e); } } } Handles::FindClose::FindClose() throw() : Handle(INVALID_HANDLE_VALUE) { } Handles::FindClose::~FindClose() throw() { if (INVALID_HANDLE_VALUE != get()) { if (!::FindClose(get())) { const ::DWORD error = ::GetLastError(); Exception e; e.setContext(getName()); e.setIssue(ELEPHEYE_RESOURCE_IDS_ISSUE_CLOSE_HANDLE); e.setWin32(error); e.setSource(_T(__FILE__), __LINE__); ExceptionProxy::log(e); } } } Handles::LocalFree::LocalFree() throw() : Handle(0) { } Handles::LocalFree::~LocalFree() throw() { if (get()) { if (::LocalFree(get())) { const ::DWORD error = ::GetLastError(); Exception e; e.setContext(getName()); e.setIssue(ELEPHEYE_RESOURCE_IDS_ISSUE_CLOSE_HANDLE); e.setWin32(error); e.setSource(_T(__FILE__), __LINE__); ExceptionProxy::log(e); } } } Handles::RegCloseKey::RegCloseKey() throw() : Handle(0) { } Handles::RegCloseKey::~RegCloseKey() throw() { if (get()) { const ::LONG error = ::RegCloseKey(get()); if (error) { Exception e; e.setContext(getName()); e.setIssue(ELEPHEYE_RESOURCE_IDS_ISSUE_CLOSE_HANDLE); e.setWin32(error); e.setSource(_T(__FILE__), __LINE__); ExceptionProxy::log(e); } } } Handles::SafeArrayDestroy::SafeArrayDestroy() throw() : Handle(0) { } Handles::SafeArrayDestroy::~SafeArrayDestroy() throw() { if (get()) { const ::HRESULT hr = ::SafeArrayDestroy(get()); if (FAILED(hr)) { Exception e; e.setContext(getName()); e.setIssue(ELEPHEYE_RESOURCE_IDS_ISSUE_CLOSE_HANDLE); e.setHresult(hr); e.setSource(_T(__FILE__), __LINE__); ExceptionProxy::log(e); } } } Handles::SafeArrayUnaccessData::SafeArrayUnaccessData() throw() : Handle(0) { } Handles::SafeArrayUnaccessData::~SafeArrayUnaccessData() throw() { if (get()) { const ::HRESULT hr = ::SafeArrayUnaccessData(get()); if (FAILED(hr)) { Exception e; e.setContext(getName()); e.setIssue(ELEPHEYE_RESOURCE_IDS_ISSUE_CLOSE_HANDLE); e.setHresult(hr); e.setSource(_T(__FILE__), __LINE__); ExceptionProxy::log(e); } } } } }
[ "zafer@zaferbalkan.com" ]
zafer@zaferbalkan.com
7f16b13e51c73ef0c2c2147ca3eae53683dabb17
ba8b8f21c24009749dbf1145d0dd6169929e3173
/src/xtopcom/xdata/src/xprovecert.cpp
782d0b9d809e8b52e80ea50c83d56510f6f18190
[]
no_license
Alipipe/TOP-chain
8acbc370738af887ebf4a3d1ccee52b2813d3511
d88c18893bfa88ead5752b74874693819cdf406f
refs/heads/main
2023-07-02T22:37:07.787601
2021-02-11T06:50:46
2021-02-11T06:50:46
357,528,232
0
0
null
2021-04-13T11:29:16
2021-04-13T11:29:15
null
UTF-8
C++
false
false
4,005
cpp
// Copyright (c) 2017-2018 Telos Foundation & contributors // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <string> #include "xbasic/xversion.h" #include "xbasic/xdataobj_base.hpp" #include "xbase/xvblock.h" #include "xbase/xvledger.h" #include "xdata/xprovecert.h" namespace top { namespace data { xprove_cert_t::xprove_cert_t(base::xvqcert_t* prove_cert, xprove_cert_class_t _class, xprove_cert_type_t _type, const xmerkle_path_256_t & _path) { m_prove_cert = prove_cert; m_prove_cert->add_ref(); set_prove_class(_class); set_prove_type(_type); set_prove_path(_path); } xprove_cert_t::xprove_cert_t(base::xvqcert_t* prove_cert, xprove_cert_class_t _class, xprove_cert_type_t _type, const std::string & _path) { m_prove_cert = prove_cert; m_prove_cert->add_ref(); set_prove_class(_class); set_prove_type(_type); m_prove_path = _path; } xprove_cert_t::~xprove_cert_t() { if (m_prove_cert != nullptr) { m_prove_cert->release_ref(); } } int32_t xprove_cert_t::do_write(base::xstream_t & stream) { KEEP_SIZE(); std::string prove_cert_bin; xassert(m_prove_cert != nullptr); m_prove_cert->serialize_to_string(prove_cert_bin); xassert(!prove_cert_bin.empty()); stream << prove_cert_bin; stream << m_prove_type; stream << m_prove_path; return CALC_LEN(); } int32_t xprove_cert_t::do_read(base::xstream_t & stream) { KEEP_SIZE(); std::string cert_bin; stream >> cert_bin; m_prove_cert = base::xvblockstore_t::create_qcert_object(cert_bin); if (m_prove_cert == nullptr) { xassert(0); return -1; } stream >> m_prove_type; stream >> m_prove_path; return CALC_LEN(); } void xprove_cert_t::set_prove_path(const xmerkle_path_256_t & path) { base::xstream_t stream2(base::xcontext_t::instance()); path.serialize_to(stream2); m_prove_path = std::string((char *)stream2.data(), stream2.size()); xassert(!m_prove_path.empty()); } bool xprove_cert_t::is_valid(const std::string & prove_object) { if (m_prove_cert == nullptr) { xerror("xprove_cert_t::is_valid prove cert null."); return false; } xprove_cert_type_t cert_type = get_prove_type(); if (cert_type != xprove_cert_type_output_root && cert_type != xprove_cert_type_justify_cert) { xerror("xprove_cert_t::is_valid prove type not valid. type=%d", cert_type); return false; } xprove_cert_class_t cert_class = get_prove_class(); if (cert_class != xprove_cert_class_self_cert && cert_class != xprove_cert_class_parent_cert) { xerror("xprove_cert_t::is_valid prove class not valid. class=%d", cert_class); return false; } std::string root_hash; if (cert_type == xprove_cert_type_output_root) { root_hash = m_prove_cert->get_output_root_hash(); } else if (cert_type == xprove_cert_type_justify_cert) { root_hash = m_prove_cert->get_justify_cert_hash(); } else { xassert(0); } if (!m_prove_path.empty()) { xmerkle_path_256_t path; base::xstream_t _stream(base::xcontext_t::instance(), (uint8_t *)m_prove_path.data(), (uint32_t)m_prove_path.size()); int32_t ret = path.serialize_from(_stream); if (ret <= 0) { xerror("xprove_cert_t::is_valid deserialize merkle path fail. ret=%d", ret); return false; } xmerkle_t<utl::xsha2_256_t, uint256_t> merkle; if (!merkle.validate_path(prove_object, root_hash, path.m_levels)) { xerror("xprove_cert_t::is_valid check merkle path fail."); return false; } } else { if (prove_object != root_hash) { xerror("xprove_cert_t::is_valid check prove object not equal with root fail"); return false; } } return true; } } // namespace data } // namespace top
[ "zql0114@gmail.com" ]
zql0114@gmail.com
7aceca0c87a44a276f319194b39ef3359270ba23
079a4dca0c358482f54eb57cb7d10546e1311a72
/BinarySearchTreeC++/Node.h
50bc2175b9d54d064a0dc08779cff41b82e3681a
[]
no_license
MatheusSchaly/--Old--Cplusplus-Binary-Search-Tree-Implementation
35767ed149dbe52b282f5c7e21326589dadbf2f3
e793d289cf4a3703866b09b813b2780ffd292dc7
refs/heads/master
2021-10-03T10:26:51.126516
2018-12-02T17:52:16
2018-12-02T17:52:16
null
0
0
null
null
null
null
UTF-8
C++
false
false
430
h
/* * Node.h * * Author: Matheus Schaly * Created on: Aug 14, 2017 * Description: Declares the Node object */ #ifndef NODE_H_ #define NODE_H_ #include <iostream> using namespace std; class Node { int data; Node *right, *left; public: Node(int data); void setData(int data); int getData(); void setRight(Node *right); Node* getRight(); void setLeft(Node *left); Node* getLeft(); }; #endif /* NODE_H_ */
[ "matheusmhs@hotmail.com" ]
matheusmhs@hotmail.com
1d145ab21a7a94d4175b4f7c723484b340631968
2d5c658987f1dd53fd044c5cd10a4ccf5c2d79ce
/be/src/runtime/small_file_mgr.cpp
eed5eea22c9eec807fa4de8bb8a926a920efff3b
[ "BSD-3-Clause", "bzip2-1.0.6", "PSF-2.0", "Apache-2.0", "LicenseRef-scancode-public-domain", "dtoa", "MIT" ]
permissive
liuchengshishabi/incubator-doris
c0225888e7aeb2d99b716ba2054014d9f9931931
12961806ac3bbe8199f5a4cb646a1817722c3f01
refs/heads/master
2020-06-02T10:05:11.191731
2019-06-10T08:28:50
2019-06-10T08:28:50
191,121,795
1
0
Apache-2.0
2019-06-10T07:47:57
2019-06-10T07:47:57
null
UTF-8
C++
false
false
7,321
cpp
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. #include "runtime/small_file_mgr.h" #include <stdint.h> #include <stdio.h> #include <sstream> #include "common/status.h" #include "http/http_client.h" #include "runtime/exec_env.h" #include "util/file_utils.h" #include "util/md5.h" #include <boost/algorithm/string/split.hpp> // boost::split #include <boost/algorithm/string/predicate.hpp> // boost::algorithm::starts_with #include <boost/algorithm/string/classification.hpp> // boost::is_any_of #include "gen_cpp/HeartbeatService.h" namespace doris { SmallFileMgr::SmallFileMgr( ExecEnv* env, const std::string& local_path) : _exec_env(env), _local_path(local_path) { } SmallFileMgr::~SmallFileMgr() { } Status SmallFileMgr::init() { RETURN_IF_ERROR(_load_local_files()); return Status::OK; } Status SmallFileMgr::_load_local_files() { RETURN_IF_ERROR(FileUtils::create_dir(_local_path)); auto scan_cb = [this] (const std::string& dir, const std::string& file) { auto st = _load_single_file(dir, file); if (!st.ok()) { LOG(WARNING) << "load small file failed: " << st.get_error_msg(); } return true; }; RETURN_IF_ERROR(FileUtils::scan_dir(_local_path, scan_cb)); return Status::OK; } Status SmallFileMgr::_load_single_file( const std::string& path, const std::string& file_name) { // file name format should be like: // file_id.md5 std::vector<std::string> parts; boost::split(parts, file_name, boost::is_any_of(".")); if (parts.size() != 2) { return Status("Not a valid file name: " + file_name); } int64_t file_id = std::stol(parts[0]); std::string md5 = parts[1]; if (_file_cache.find(file_id) != _file_cache.end()) { return Status("File with same id is already been loaded: " + file_id); } std::string file_md5; RETURN_IF_ERROR(FileUtils::md5sum(path + "/" + file_name, &file_md5)); if (file_md5 != md5) { return Status("Invalid md5 of file: " + file_name); } CacheEntry entry; entry.path = path + "/" + file_name; entry.md5 = file_md5; _file_cache.emplace(file_id, entry); return Status::OK; } Status SmallFileMgr::get_file( int64_t file_id, const std::string& md5, std::string* file_path) { std::unique_lock<std::mutex> l(_lock); // find in cache auto it = _file_cache.find(file_id); if (it != _file_cache.end()) { // find the cached file, check it CacheEntry& entry = it->second; Status st = _check_file(entry, md5); if (!st.ok()) { // check file failed, we should remove this cache and download it from FE again if (remove(entry.path.c_str()) != 0) { std::stringstream ss; ss << "failed to remove file: " << file_id << ", err: "<< std::strerror(errno); return Status(ss.str()); } _file_cache.erase(it); } else { // check ok, return the path *file_path = entry.path; return Status::OK; } } // file not found in cache. download it from FE RETURN_IF_ERROR(_download_file(file_id, md5, file_path)); return Status::OK; } Status SmallFileMgr::_check_file(const CacheEntry& entry, const std::string& md5) { if (!FileUtils::check_exist(entry.path)) { return Status("file not exist"); } if (!boost::iequals(md5, entry.md5)) { return Status("invalid MD5"); } return Status::OK; } Status SmallFileMgr::_download_file( int64_t file_id, const std::string& md5, std::string* file_path) { std::stringstream ss; ss << _local_path << "/" << file_id << ".tmp"; std::string tmp_file = ss.str(); bool should_delete = true; auto fp_closer = [&tmp_file, &should_delete] (FILE* fp) { fclose(fp); if (should_delete) remove(tmp_file.c_str()); }; std::unique_ptr<FILE, decltype(fp_closer)> fp(fopen(tmp_file.c_str(), "w"), fp_closer); if (fp == nullptr) { LOG(WARNING) << "fail to open file, file=" << tmp_file; return Status("fail to open file"); } HttpClient client; std::stringstream url_ss; #ifndef BE_TEST TMasterInfo* master_info = _exec_env->master_info(); url_ss << master_info->network_address.hostname << ":" << master_info->http_port << "/api/get_small_file?" << "file_id=" << file_id << "&token=" << master_info->token; #else url_ss << "127.0.0.1:29997/api/get_small_file?file_id=" << file_id; #endif std::string url = url_ss.str(); LOG(INFO) << "download file from: " << url; RETURN_IF_ERROR(client.init(url)); Status status; Md5Digest digest; auto download_cb = [&status, &tmp_file, &fp, &digest] (const void* data, size_t length) { digest.update(data, length); auto res = fwrite(data, length, 1, fp.get()); if (res != 1) { LOG(WARNING) << "fail to write data to file, file=" << tmp_file << ", error=" << ferror(fp.get()); status = Status("fail to write data when download"); return false; } return true; }; RETURN_IF_ERROR(client.execute(download_cb)); RETURN_IF_ERROR(status); digest.digest(); if (!boost::iequals(digest.hex(), md5)) { LOG(WARNING) << "file's checksum is not equal, download: " << digest.hex() << ", expected: " << md5 << ", file: " << file_id; return Status("download with invalid md5"); } // close this file should_delete = false; fp.reset(); // rename temporary file to library file std::stringstream real_ss; real_ss << _local_path << "/" << file_id << "." << md5; std::string real_file_path = real_ss.str(); auto ret = rename(tmp_file.c_str(), real_file_path.c_str()); if (ret != 0) { char buf[64]; LOG(WARNING) << "fail to rename file from=" << tmp_file << ", to=" << real_file_path << ", errno=" << errno << ", errmsg=" << strerror_r(errno, buf, 64); remove(tmp_file.c_str()); remove(real_file_path.c_str()); return Status("fail to rename file"); } // add to file cache CacheEntry entry; entry.path = real_file_path; entry.md5 = md5; _file_cache.emplace(file_id, entry); *file_path = real_file_path; LOG(INFO) << "finished to download file: " << file_path; return Status::OK; } } // end namespace doris
[ "buaa.zhaoc@gmail.com" ]
buaa.zhaoc@gmail.com
db40a47c56d5e713f69f67891a3a2088f8de30a5
4340fb3b11fde32aa232782bd3640c8c1e412b33
/include/Option.hpp
a56fffc5805236277fa412e511e91e08c97859fb
[]
no_license
Geiiko/rtype
60dbb4727a11bc97b9500494c5a5262a911909b3
17fb9ae0f6f10a089cb353e6660771b578fa41d0
refs/heads/master
2021-07-15T06:12:35.634316
2017-10-11T15:14:17
2017-10-11T15:14:17
106,570,871
0
0
null
null
null
null
UTF-8
C++
false
false
976
hpp
// // Option.hpp for Option in /home/plasko_a/projet/cplusplus/cpp_spider // // Made by Antoine Plaskowski // Login <antoine.plaskowski@epitech.eu> // // Started on Sat Oct 24 15:43:06 2015 Antoine Plaskowski // Last update Thu Dec 24 07:24:27 2015 Antoine Plaskowski // #ifndef OPTION_HPP_ # define OPTION_HPP_ # include <string> # include <tuple> # include <list> class Option { public: Option(void); ~Option(void); std::string const &get_opt(std::string const &name) const; std::list<std::string> const &get_pos_opt(void) const; void add_opt(std::string const &name, std::string const &description = "", std::string const &value = ""); void sup_opt(std::string const &name); void parse_opt(int argc, char **argv); std::string const &get_zero(void) const; private: using m_opt = std::tuple<std::string, std::string, std::string>; std::list<m_opt> m_opts; std::list<std::string> m_pos_opts; std::string m_zero; }; #endif /* !OPTION_HPP_ */
[ "alaric.degand@epitech.eu" ]
alaric.degand@epitech.eu
7e1dbf0db838b5529edcdf47838d573aa026674a
56f1b6b7eff222994b01c324f4ce5c30b06f2d9a
/emilia/net/sslsocket.cc
af65821fad9fbe33dff195bbdb4249def3fef212
[]
no_license
xxhhww/ema
0075fc72d78c568d84cdbed8ad56350ef9707e55
23067621dd1757201ffd6e7a6ed2e0c060c77eaa
refs/heads/main
2023-05-06T08:08:45.283174
2021-06-03T14:18:06
2021-06-03T14:18:06
325,328,766
0
0
null
null
null
null
UTF-8
C++
false
false
5,984
cc
#include "sslsocket.h" #include "emilia/base/scheduler.h" #include "emilia/log/logmarco.h" #include <sys/fcntl.h> using namespace emilia::base; namespace emilia{ namespace net{ struct _SSLInit { _SSLInit() { SSL_library_init(); SSL_load_error_strings(); OpenSSL_add_all_algorithms(); } }; //初始化 static _SSLInit s_init; Socket::ptr SSLSocket::CreateAcceptV4(IPAddress::ptr serveAddr){ SSLSocket::ptr acceptSock(new SSLSocket(AF_INET, SOCK_STREAM, 0)); if(!acceptSock->initSocket()) return nullptr; acceptSock->setNoBlock(); if(!acceptSock->bind(serveAddr)) return nullptr; if(!acceptSock->listen()) return nullptr; return std::dynamic_pointer_cast<Socket>(acceptSock); } Socket::ptr SSLSocket::CreateAcceptV6(IPAddress::ptr serveAddr){ SSLSocket::ptr acceptSock(new SSLSocket(AF_INET6, SOCK_STREAM, 0)); if(!acceptSock->initSocket()) return nullptr; acceptSock->setNoBlock(); if(!acceptSock->bind(serveAddr)) return nullptr; if(!acceptSock->listen()) return nullptr; return std::dynamic_pointer_cast<Socket>(acceptSock); } Socket::ptr SSLSocket::CreateTcpV4(){ SSLSocket::ptr clientSock(new SSLSocket(AF_INET, SOCK_STREAM, 0)); if(!clientSock->initSocket()) return nullptr; return std::dynamic_pointer_cast<Socket>(clientSock); } Socket::ptr SSLSocket::CreateTcpV6(){ SSLSocket::ptr clientSock(new SSLSocket(AF_INET6, SOCK_STREAM, 0)); if(!clientSock->initSocket()) return nullptr; return std::dynamic_pointer_cast<Socket>(clientSock); } SSLSocket::SSLSocket(int family, int type, int protocol) :Socket(family, type, protocol){} //接受字节数组数据(Tcp) //0客户端关闭连接 -1系统错误 -2读超时 >0 接收的字节 int SSLSocket::recv(void* buffer, size_t length){ //如果可读超时不是0就向Scheduler中加入定时器 Timer::ptr timer = nullptr; if(m_rdTimeOut){ timer = Scheduler::GetThis()->addTimer(m_rdTimeOut, std::bind(&SSLSocket::TimeOutCb, this, 1)); } //设置可读事件 Scheduler::GetThis()->addReadEvent(m_sock, Fiber::GetThis(), m_rdTimeOut); //挂起等待可读事件 Fiber::YieldToPend(); //被唤醒 //判断是因为超时被唤醒还是因为可读事件触发被唤醒 retry: //因为超时被唤醒返回-2 if(m_hasDelay){ return -2; } //因为可读事件触发被唤醒 int rt = ::SSL_read(m_ssl.get(), buffer, length); //读事件被系统中断,重新读 while(rt == -1 && errno == EINTR){ rt = ::SSL_read(m_ssl.get(), buffer, length); } //EAGAIN 重新尝试 if(rt == -1 && errno == EAGAIN){ //重新设置定时器 timer->refresh(); Scheduler::GetThis()->addReadEvent(m_sock, Fiber::GetThis(), m_rdTimeOut); Fiber::YieldToPend(); goto retry; } //其他错误 if(rt == -1){ EMILIA_LOG_ERROR("system") << "Recv Fail: recv Error: " << strerror(errno); } //其他错误和没有错误都要将定时器删除 if(timer != nullptr) timer->cancel(); return rt; } //发送字节数组数据(Tcp) //0客户端关闭连接 -1系统错误 -2写超时 >0 发送的字节 int SSLSocket::send(const void* buffer, size_t length){ Timer::ptr timer = nullptr; retry: if(m_hasDelay){ return -2; } int rt = ::SSL_write(m_ssl.get(), buffer, length); //发送操作被系统中断 while(rt == -1 && errno == EINTR){ //继续尝试发送 rt = ::SSL_write(m_ssl.get(), buffer, length); } //重新尝试 if(rt == -1 && errno == EAGAIN) { if(m_wrTimeOut) timer = Scheduler::GetThis()->addTimer(m_wrTimeOut, std::bind(&SSLSocket::TimeOutCb, this, 2)); Scheduler::GetThis()->addWriteEvent(m_sock, Fiber::GetThis()); Fiber::YieldToPend(); goto retry; } if(rt == -1){ EMILIA_LOG_ERROR("system") << "Send Fail: ::send Error: " << strerror(errno); } if(timer != nullptr) timer->cancel(); return rt; } //连接远端地址 bool SSLSocket::connect(const IPAddress::ptr reAddr, uint64_t timeout){ EMILIA_LOG_DEBUG("test") << "SSL connect"; bool v = Socket::connect(reAddr, timeout); if(v) { m_ctx.reset(SSL_CTX_new(SSLv23_client_method()), SSL_CTX_free); m_ssl.reset(SSL_new(m_ctx.get()), SSL_free); SSL_set_fd(m_ssl.get(), m_sock); v = (SSL_connect(m_ssl.get()) == 1); } return v; } //获得连接套接字 Socket::ptr SSLSocket::accept(){ Scheduler::GetThis()->addReadEvent(m_sock, Fiber::GetThis(), 0); Fiber::YieldToPend(); //两个变量,描述客户端的ip地址 sockaddr addr; socklen_t addrLen= sizeof(addr); int rt = ::accept(m_sock,(sockaddr*)&addr, &addrLen); //系统中断 while(rt == -1 && errno == EINTR){ //重新尝试 rt = ::accept(m_sock, (sockaddr*)&addr, &addrLen); } //系统出错 if(rt == -1){ EMILIA_LOG_ERROR("system") << "Accept Fail: accept Error: " << strerror(errno); return nullptr; } //远端地址信息 const IPAddress::ptr reAddr = IPAddress::CreateBySockaddress((const sockaddr*)&addr, sizeof(struct sockaddr)); SSLSocket::ptr connSocket(new SSLSocket(m_family, m_type, m_protocol)); //设置为非阻塞 int flags = fcntl(rt, F_GETFL, 0); fcntl(rt, F_SETFL, flags | O_NONBLOCK); connSocket->m_ssl.reset(SSL_new(connSocket->m_ctx.get()), SSL_free); SSL_set_fd(connSocket->m_ssl.get(), rt); SSL_accept(connSocket->m_ssl.get()); //设置connSocket的成员变量 connSocket->setConnFd(rt); connSocket->setLoAddr(m_localAddr); connSocket->setReAddr(reAddr); connSocket->setRDTimeOut(m_rdTimeOut); connSocket->setWRTimeOut(m_wrTimeOut); return std::dynamic_pointer_cast<Socket>(connSocket); } } }
[ "2908903586@qq.com" ]
2908903586@qq.com
1a016ba82e131b939b1f8d8cdbb30dff7b9e850d
618ac76f0288fcc10405d284ff573c43ff305291
/stdafx.h
19f1a9bd458942c33d03089cb8feed60897a2d9b
[]
no_license
YuriKircovich/U235
d81ad5a6a48f6d4f196d3a82c90bcdbfec720054
c3ca16375e6201dd7ac11297acd45666675967fb
refs/heads/master
2021-01-10T14:38:58.909673
2015-11-08T15:28:13
2015-11-08T15:28:13
45,785,975
1
0
null
null
null
null
UTF-8
C++
false
false
734
h
// stdafx.h : include file for standard system include files, // or project specific include files that are used frequently, but // are changed infrequently // #pragma once #include "targetver.h" #include <stdio.h> #include <tchar.h> #include <iostream> #include <Windows.h> #include <string> #include <map> #include <algorithm> static HANDLE hstdout = GetStdHandle(STD_OUTPUT_HANDLE); static CONSOLE_SCREEN_BUFFER_INFO csbi; //Used in consoleColors.cpp void printColor(std::string args, int color); void getConsoleAttri(); //Used in inputField.cpp void inputField(); bool string_is_valid(const std::string &str); bool string_is_digit(const std::string &str); // TODO: reference additional headers your program requires here
[ "yurikircovich@gmail.com" ]
yurikircovich@gmail.com
bbbae511cdc0c4f9d8be866b16d6b401a20c06e1
a46c6f283538e6f8cdb53e91b445d61e67ac8d3a
/a5_heuristic.cpp
d25f3f9d8271e37c4688e6f49405c7adbe94365e
[]
no_license
MingXXI/AI-Connect-Four
ff6bc1ead323250abac4ed7715cc28a9206461bc
3a7006838d197ee9b28c3449c427691eca6b7b85
refs/heads/master
2020-07-30T14:22:10.160457
2019-09-23T04:12:52
2019-09-23T04:12:52
210,262,280
5
0
null
null
null
null
UTF-8
C++
false
false
24,704
cpp
// Heuristic and class structure refers to: https://github.com/RobertSzkutak/SUNY-Fredonia/blob/696a39a00df3e775c8d40be73bfb4159c2aeda98/CSIT461-Intro-To-AI-Engineering/Connect4 #include <iostream> #include <ctime> using namespace std; #define ROWS 6 #define COLUMNS 7 class Connect4{ private: public: Connect4(); ~Connect4(); void display(); void player_move(int player); int check_win(); void setChip(int set) { chip = set; } void dropChip(int col, int val); void removeChip(int col); void agentMove(); int board[ROWS][COLUMNS] = {0}; int chip = 1; }; Connect4::Connect4(){ } Connect4::~Connect4(){ } void Connect4::dropChip(int col, int val){ for(int i = 5; i >= 0; i--){ if(board[i][col] == 0){ board[i][col] = val; break; } } } void Connect4::removeChip(int col){ for(int i = 0; i < ROWS; i++){ if(board[i][col] > 0){ board[i][col] = 0; break; } } } void Connect4::agentMove(){ //check if any move can win. for(int i = 0; i < COLUMNS; i++){ if(board[0][i] == 0){ //no need to test if column full dropChip(i, chip); if(check_win() == chip) return; removeChip(i); } } // prevent opponent win int oppchip = 0;//This represents the value of the opoonents chip if(chip == 1) oppchip = 2; if(chip == 2) oppchip = 1; for(int i = 0; i < COLUMNS; i++){ if(board[0][i] == 0){ //no need to test if column full dropChip(i, oppchip); if(check_win() == oppchip){ removeChip(i); dropChip(i, chip); return; } removeChip(i); } } int priority[COLUMNS]; //List of score a move can earn //Test each column, assign a value according to how good of a move it is for(int i = 0; i < COLUMNS; i++){ priority[i] = 0; if(board[0][i] == 0){ //no need to test if column full dropChip(i, chip); //Make sure the opponent can't win after this move for(int j = 0; j < COLUMNS; j++){ if(board[0][j] == 0){ //no need to test if column full dropChip(j, oppchip); if(check_win() == oppchip){ priority[i] = -1; // score -1 if the move let opponent win } removeChip(j); } } //Calculate how good is this move if(priority[i] == 0){ for(int j = 0; j < COLUMNS; j++){ if(board[0][j] == 0){ dropChip(j, chip); if(check_win() == chip) priority[i] += 2; // if a move can lead to a win in 1 more step, earn 2 scores else{ for(int h = 0; h < COLUMNS; h++){ if(board[0][h] == 0){ dropChip(h, chip); if(check_win() == chip) priority[i]++; removeChip(h); } } } removeChip(j); } } } removeChip(i); } else priority[i] = -2; //if it definate a win of opponent } //Which column has the highest priority int maxPriority = INT_MIN; // initialize max score int index = 0; for(int i = 0; i < COLUMNS; i++){ if(priority[i] > maxPriority){ maxPriority = priority[i]; index = i; } } dropChip(index, chip); } int Connect4::check_win() { //Vertical ||| for(int column = 0; column < COLUMNS; column++) for(int row = 0; row+3 < ROWS; row++) if(board[row][column] > 0 && board[row][column] == board[row+1][column] && board[row+1][column] == board[row+2][column] && board[row+2][column] == board[row+3][column]) return board[row][column]; //Horizontal --- for(int row = 0; row < ROWS; row++) for(int column = 0; column+3 < COLUMNS; column++) if(board[row][column] > 0 && board[row][column] == board[row][column+1] && board[row][column+1] == board[row][column+2] && board[row][column+2] == board[row][column+3]) return board[row][column]; //diagonal\\\ upper part for(int row = 0; row+3 < ROWS; row++) for(int column = 0; column+3 < COLUMNS; column++) if(board[row][column] > 0 && board[row][column] == board[row+1][column+1] && board[row+1][column+1] == board[row+2][column+2] && board[row+2][column+2] == board[row+3][column+3]) return board[row][column]; //diagonal /// upper part // for(int row = 0; row < 4; row++) // for (int col = 6; col > 2; col++) // if(board[row][col] > 0 && board[row][col] == board[row+1][col-1] && board[row+1][col-1] == board[row+2][col-2] // && board[row+2][col-2] == board[row+3][col-3]) // return board[row][col]; // for(int row = ROWS-1; row >= 3; row--) for(int column = 0; column+3 < COLUMNS; column++) if(board[row][column] > 0 && board[row][column] == board[row-1][column+1] && board[row-1][column+1] == board[row-2][column+2] && board[row-2][column+2] == board[row-3][column+3]) return board[row][column]; //diagonal /// lower part for(int row = 0; row+3 < ROWS; row++) for(int column = COLUMNS-1; column >= 3; column--) if(board[row][column] > 0 && board[row][column] == board[row+1][column-1] && board[row+1][column-1] == board[row+2][column-2] && board[row+2][column-2] == board[row+3][column-3]) return board[row][column]; // //diagonal \\\ lower part // for(int row = 0; row < 4; row++){ // for (int col = 0; col < 4; col++){ // if (board[row][col] > 0 && board[row][col] == board[row+1][col+1] && board[row+1][col+1] == board[row+2][col+2] // && board[row+2][col+2] == board[row+3][col+3]){ // return board[row][col]; // } // } // } // // for(int row = ROWS-1; row <= 3; row--) for(int column = COLUMNS-1; column > 3; column--) if(board[row][column] > 0 && board[row][column] == board[row-1][column-1] && board[row-1][column-1] == board[row-2][column-2] && board[row-2][column-2] == board[row-3][column-3]) return board[row][column]; // //Check for a tie for(int i = 0; i < ROWS; i++) for(int j = 0; j < COLUMNS; j++) if(board[i][j] == 0) return 0; else if(i == ROWS-1 && j == COLUMNS-1) return 3; return 0; } void Connect4::display(){ cout << "\n 1 2 3 4 5 6 7 \n"; for (int i = 0; i < 6; i++){ for (int j = 0; j < 7; j++){ if (board[i][j] == 0){ cout << "| " << " " << " "; } else if (board[i][j] == 1){ cout << "| " << "O" << " "; } else{ cout << "| " << "X" << " "; } } cout << "|\n-----------------------------\n"; } } void Connect4::player_move(int player){ if(chip == player){ agentMove(); return; } int column = 0; while(true){ cout << endl << "Choose a column 1 - 7: "; cin >> column; column -= 1; if(column >=0 && column < COLUMNS) if(board[0][column] == 0) break; else cout << endl << "That column is full. Please choose a different column."; else cout << endl << "That is an invalid column. Please choose a valid column."; } dropChip(column, player); } int main(){ Connect4 connect4; int win = 0, mode = 0; int player[2] = {2,1}; int position; int turn = 0; int player_position = 1; cout << "Welcome to Our Connect 4 Game!!\n"; mode = 1; // player counter computer only if(mode == 1){ cout << endl << "If you wish to make the first move, please enter 1, else enter 2: "; cin >> position; if(position == 1){ player_position = 1; connect4.setChip(1); }else{ player_position = 2; connect4.setChip(2); } } while(!win){ connect4.display(); cout << "To make a move, please enter the number on top of game board that corresponds to your move!!\n"; connect4.player_move(player[turn % 2]); turn += 1; win = connect4.check_win(); } connect4.display(); if(win == 3){ cout << endl << "Draw! Practice More!"; }else{ if (mode == 1){ if (win != player_position){ cout << endl << "You Beat the Computer! Congratulations" << endl; }else{ cout << endl << "Computer Wins! You Losser!" << endl; } }else{ cout << endl << "Player " << win << " wins!" << endl; } } } //First try //#include <iostream> //#include <stdlib.h> //#include <utility> //#include <vector> //#include <iterator> //#include <time.h> //#include <algorithm> //#include <cstring> //#include <string.h> //#include <limits> // // // // //using namespace std; //int N = 15000; // // //bool comp(int a, int b){ // return (a < b); //} // // // //class connect4{ //private: //public: // int board[6][7] = {0}; // int empty[7] = {5,5,5,5,5,5,5}; // int sim[6][7] = {0}; // int sim_empty[7] = {5,5,5,5,5,5,5}; // int total = 42; // int empty1; // // connect4(); // ~connect4(); // // // int move_first(); // // void display(); // // int player_move(); // // int check_win(int arr[6][7], int height[7], int last_move_index); // // vector<int> legal_move(int arr[7]); // // int next_move(int arr[6][7]); // //}; // // //connect4::connect4(){ //} // //connect4::~connect4(){ //} // //void connect4::display(){ // cout << "\n 1 2 3 4 5 6 7 \n"; // for (int i = 0; i < 6; i++){ // for (int j = 0; j < 7; j++){ // if (board[i][j] == 0){ // cout << "| " << " " << " "; // } // else if (board[i][j] == 1){ // cout << "| " << "O" << " "; // } // else{ // cout << "| " << "X" << " "; // } // } // cout << "|\n-----------------------------\n"; // } //} // //int connect4::move_first(){ // cout << "Now, if you wish to make the first move, please enter 1, else enter 2: " << flush; // int choice; // while (!(cin >> choice) || (choice != 1 && choice != 2)){ // cout << "Error: Please enter 1 or 2 to declare your position: "; // cin.clear(); // cin.ignore(123,'\n'); // } // // cout << "Please enter 1 to move first or 2 to move second: "; // // cin >> choice; // // while (choice != 1 && choice != 2){ // // cout << "Error: Please enter 1 or 2 to choose your positon: "; // // cin >> choice; // // } // return choice; //} // // //int connect4::player_move(){ // // int move; // cout << "Please enter your move: " << flush; // while (!(cin >> move) || (move > 7 || move < 1)){ // cout << "Error: Please enter a number between 1~7: "; // cin.clear(); // cin.ignore(123,'\n'); // } // total -= 1; // return move - 1; // //} // //int connect4::check_win(int arr[6][7], int height[7], int last_move_index){ // // "arr" is the board // // "last_move_index" indicate whichever column changed since last move // // "height" is array of height of each column // // int last_height_index = height[last_move_index]; // height[last_move_index] -= 1; // // // check row ---- // int leftend = max(0, last_move_index-3); // int rightend = min(3, last_move_index); // // for(int i = leftend; i<=rightend; i++){ // // cout <<"check row: "<< i << endl; // if(arr[last_height_index][i] == arr[last_height_index][i+1] && arr[last_height_index][i+1] == arr[last_height_index][i+2] && arr[last_height_index][i+2] == arr[last_height_index][i+3]){ // return arr[last_height_index][last_move_index]; // } // } // // // check c0lumn |||| // if (last_height_index < 3){ // // cout << "check column" << last_height_index << endl; // if(arr[last_height_index][last_move_index]==arr[last_height_index+1][last_move_index] && arr[last_height_index+1][last_move_index]==arr[last_height_index+2][last_move_index] && arr[last_height_index+2][last_move_index]==arr[last_height_index+3][last_move_index]) // return arr[last_height_index][last_move_index]; // } // // // int i = last_height_index; // int j = last_move_index; // // // check diagnal // // for (int check_index = 3; check_index >= 0; check_index--){ // // cout << "diagnal1:" << check_index << endl; // if(i-check_index >= 0 && j-check_index >= 0 && i+(3-check_index) <= 5 && j+(3-check_index) <= 6){ // if(arr[i-check_index][j-check_index] == arr[i-check_index+1][j-check_index+1] && arr[i-check_index+1][j-check_index+1] == arr[i-check_index+2][j-check_index+2] && arr[i-check_index+2][j-check_index+2] == arr[i-check_index+3][j-check_index+3]){ // return arr[i][j]; // } // } // } // // // for (int check_index2 = 3; check_index2 >= 0; check_index2--){ // // cout << "diagnal2:" << check_index2 << endl; // if(i+check_index2 <= 5 && j-check_index2 >= 0 && i-(3-check_index2) >= 0 && j+(3-check_index2) <= 6){ // if(arr[i+check_index2][j-check_index2] == arr[i+check_index2-1][j-check_index2+1] && arr[i+check_index2-1][j-check_index2+1] == arr[i+check_index2-2][j-check_index2+2] && arr[i+check_index2-2][j-check_index2+2] == arr[i+check_index2-3][j-check_index2+3]){ // return arr[i][j]; // } // } // } // // // // for (i=0; i<7; i++){ // if top row is not full, game is in progress // if (!arr[0][i]){ // return -1; // } // } // return 0; //} // //vector<int> connect4::legal_move(int arr[7]){ // vector<int> move; // for (int i=0; i<7; i++){ // if (arr[i] != -1){ // move.push_back(i); // } // } // return move; //} // //int connect4::next_move(int arr[6][7]){ // int playout = 15000; // int win; // int index; // int outcome; // int i; // int j; // bool player; // int cpy_total; // int flag = 0; // int col; // int row; // // vector<int> moves = legal_move(empty); // legal moves of original board // vector<int> moves2; // vector<int>::iterator itr; // vector<int>::iterator itr2; // // vector<int> score; // vector<int> sim_moves; // // for(itr = moves.begin(); itr != moves.end(); itr++){ // for each legal move //// cout << "yoyo" << endl; // board[empty[*itr]][*itr] = 1; // //// cout << "yoyo" << endl; // if (check_win(board, empty, *itr)==1){ // computer win after first move //// cout << "yoyo" << endl; // empty[*itr]++; //// cout << "yoyo" << endl; // return *itr; // } // moves2 = legal_move(empty); // for(itr2 = moves2.begin(); itr2 != moves2.end(); itr2++){ // board[empty[*itr2]][*itr2] = 2; // if (check_win(board, empty, *itr2)==2){ // computer win after first move // flag = 1; // empty[*itr2] ++; // board[empty[*itr2]][*itr2] = 0; // break; // } // empty[*itr2]++; // board[empty[*itr2]][*itr2] = 0; // } // if(flag == 0){ // row = empty[*itr]; // col = *itr; // // // } // } // empty[*itr] ++; // board[empty[*itr]][*itr] = 0; // return 0; //} //int connect4::next_move(int arr[6][7]){ // bool player = false; // int *empty1 = nullptr; // int *empty2 = nullptr; // int *empty3 = nullptr; // int *empty4 = nullptr; // int flag = 0; // int win; // int cpy_total; // int index; // int i,j, outcome; // vector<int> moves1; // legal moves of original board // vector<int> moves2; // vector<int> moves3; // vector<int> moves4; // vector<int>::iterator itr1; // vector<int>::iterator itr2; // vector<int>::iterator itr3; //// vector<int>::iterator itr4; // // vector<int> score; // vector<int> sim_moves; // // memcpy(empty1, empty, 28); //// memcpy(board1, board, 168); // moves1 = legal_move(empty1); // // for(itr1 = moves1.begin(); itr1 != moves1.end(); itr1++){ // for each legal move // cpy_total = total; // board[empty1[*itr1]][*itr1] = 1; // cpy_total --; // if (check_win(board, empty1, *itr1)==1){ // computer win after first move // empty1[*itr1]++; // return *itr1; // } // // player = !player; // // memcpy(empty2, empty1, 28); // moves2 = legal_move(empty2); // // win = 0; // // for(itr2 = moves2.begin(); itr2 != moves2.end(); itr2++){ // board[empty2[*itr2]][*itr2] = 2; // if (check_win(board, empty2, *itr2)==2){ // computer win after first move // flag = 1; // empty2[*itr2] ++; // board[empty2[*itr2]][*itr2] = 0; // break; // } // empty2++; // board[empty2[*itr2]][*itr2] = 0; // } // // if (flag == 1){ // flag = 0; // score.push_back(INT_MIN); // continue; // } else{ // for(itr2 = moves2.begin(); itr2 != moves2.end(); itr2++){ // board[empty2[*itr2]][*itr2] = 2; // cpy_total --; // memcpy(empty3, empty2, 28); // moves3 = legal_move(empty3); // for(itr3 = moves3.begin(); itr3 != moves3.end(); itr3++){ // board[empty3[*itr3]][*itr3] = 1; // cpy_total --; // if (check_win(board, empty3, *itr3)==1){ // computer win after first move // empty3[*itr3]++; // win += cpy_total; // } // empty3[*itr3]++; // // for (int k=0; k<N; k++){ // simulate n times n=playout // player = true; // memcpy(empty4, empty3, 28); // moves4 = legal_move(empty4); // // while(moves4.size() != 0){ // index = rand() % moves4.size(); // j = moves4[index]; // i = empty4[j]; // board[i][j] = player? 2:1; // cpy_total -= 1; // // player = !player; // // outcome = check_win(sim, empty4, j); // // moves4 = legal_move(empty4); // // if (outcome == 1){ // computer win // board[i][j] = 0; // win += cpy_total; // break; // } // else if (outcome == 2){ // board[i][j] = 0; // win -= 2*cpy_total ; // break; // } // cpy_total += 1; // board[i][j] = 0; // } // }// end of later random // board[empty3[*itr3]][*itr3] = 0; // cpy_total ++; // }// end of step 3 // cpy_total ++; // } // end of step 2 // } // empty1[*itr1] ++; // board[empty1[*itr1]][*itr1] = 0; // // } // end of step 1 // for (i=0; i<score.size(); i++){ // cout<< score[i] << " "; // } // cout << "\n"; // return moves1[max_element(score.begin(),score.end())-score.begin()]; // return the best move //} // //int main() //{ // // cout << "Welcome to Connect 4 Game!!!" << endl; // // connect4 * test = new connect4(); // // test->display(test->board); // // // // srand((unsigned)time(NULL)); // rng // // int move; // int win; // connect4 * game = new connect4(); // cout << "Welcome to Our Connect 4 Game!!\n"; // cout << "To make a move, please enter the number on top of game board that corresponds to your move!!\n"; // game->display(); // // // // cout << "To make a move, please enter the number on top of game board that corresponds to your move\n\n"; // // cout << "Now, if you wish to make the first move, please enter 1, else enter 2: " << flush; // // // // while (!(cin >> first) || (first != 1 && first != 2)){ // // cout << "Error: Please enter 1 or 2: "; // // cin.clear(); // // cin.ignore(123,'\n'); // // } // // // if (game->move_first() == 1){ // move = game->player_move(); // game->board[5][move] = 2; // game->empty[move]--; // game->display(); // } // // do{ // move = game->next_move(game->board); // move by computer // cout << "\nComputer made move at: " << move+1<< endl; // game->board[game->empty[move]][move] = 1; // // game->display(); // win = game->check_win(game->board, game->empty, move); // if (win != -1){ // game over // if (win == 1){ // cout << "Computer Wins! You Loser!" << endl; // }else{ // cout << "You Beat the Computer! Congratulations" << endl; // } // break; // } // // while (1){ // get a valid player move // move = game->player_move(); // if (game->board[0][move]){ // cout << "please enter a valid move where the location of move is empty" << endl; // }else{ // break; // } // } // // game->board[game->empty[move]][move] = 2; // move by player // win = game->check_win(game->board, game->empty, move); // if (win!=-1){ // game over // game->display(); // if (win == 1){ // cout << "Computer Wins! You Losser!" << endl; // }else if (win == 2){ // cout << "You Beat the Computer! Congratulations" << endl; // } else{ // cout << "Draw! Practice More!" << endl; // } // break; // } // // } // while (game->legal_move(game->empty).size()>0); // // // return 0; // // int computer = 2; // // cout << "First, please decide what position you want to take!" << endl; // // int player = move_first(); // // if (player == computer){ // // computer = 1; // // } // // // // // //// display(board); // // cout << move_first() << endl; // // cout << player_move() << endl; //} // //
[ "bowenw@sfu.ca" ]
bowenw@sfu.ca
7b6482ff6894cb4c2643304f7e54b77416eb8ac3
24d856d98c85a319d53be2768ccc176a50873fa3
/eglibc-2.15/argp/argp-namefrob.h
2dc426a4f0e463a04e1425d27ef2d7195ac4bf53
[ "LGPL-2.1-only", "GPL-2.0-only", "LicenseRef-scancode-inner-net-2.0", "BSD-3-Clause", "LGPL-2.1-or-later", "HPND", "LicenseRef-scancode-other-copyleft", "CMU-Mach", "LicenseRef-scancode-other-permissive", "BSD-2-Clause" ]
permissive
dozenow/shortcut
a4803b59c95e72a01d73bb30acaae45cf76b0367
b140082a44c58f05af3495259c1beaaa9a63560b
refs/heads/jumpstart-php
2020-06-29T11:41:05.842760
2019-03-28T17:28:56
2019-03-28T17:28:56
200,405,626
2
2
BSD-2-Clause
2019-08-03T19:45:44
2019-08-03T17:57:58
C
UTF-8
C++
false
false
5,485
h
/* Name frobnication for compiling argp outside of glibc Copyright (C) 1997, 2003 Free Software Foundation, Inc. This file is part of the GNU C Library. Written by Miles Bader <miles@gnu.ai.mit.edu>. The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. The GNU C Library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the GNU C Library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. */ #if !_LIBC /* This code is written for inclusion in gnu-libc, and uses names in the namespace reserved for libc. If we're not compiling in libc, define those names to be the normal ones instead. */ /* argp-parse functions */ #undef __argp_parse #define __argp_parse argp_parse #undef __option_is_end #define __option_is_end _option_is_end #undef __option_is_short #define __option_is_short _option_is_short #undef __argp_input #define __argp_input _argp_input /* argp-help functions */ #undef __argp_help #define __argp_help argp_help #undef __argp_error #define __argp_error argp_error #undef __argp_failure #define __argp_failure argp_failure #undef __argp_state_help #define __argp_state_help argp_state_help #undef __argp_usage #define __argp_usage argp_usage /* argp-fmtstream functions */ #undef __argp_make_fmtstream #define __argp_make_fmtstream argp_make_fmtstream #undef __argp_fmtstream_free #define __argp_fmtstream_free argp_fmtstream_free #undef __argp_fmtstream_putc #define __argp_fmtstream_putc argp_fmtstream_putc #undef __argp_fmtstream_puts #define __argp_fmtstream_puts argp_fmtstream_puts #undef __argp_fmtstream_write #define __argp_fmtstream_write argp_fmtstream_write #undef __argp_fmtstream_printf #define __argp_fmtstream_printf argp_fmtstream_printf #undef __argp_fmtstream_set_lmargin #define __argp_fmtstream_set_lmargin argp_fmtstream_set_lmargin #undef __argp_fmtstream_set_rmargin #define __argp_fmtstream_set_rmargin argp_fmtstream_set_rmargin #undef __argp_fmtstream_set_wmargin #define __argp_fmtstream_set_wmargin argp_fmtstream_set_wmargin #undef __argp_fmtstream_point #define __argp_fmtstream_point argp_fmtstream_point #undef __argp_fmtstream_update #define __argp_fmtstream_update _argp_fmtstream_update #undef __argp_fmtstream_ensure #define __argp_fmtstream_ensure _argp_fmtstream_ensure #undef __argp_fmtstream_lmargin #define __argp_fmtstream_lmargin argp_fmtstream_lmargin #undef __argp_fmtstream_rmargin #define __argp_fmtstream_rmargin argp_fmtstream_rmargin #undef __argp_fmtstream_wmargin #define __argp_fmtstream_wmargin argp_fmtstream_wmargin #if 0 #include "mempcpy.h" #include "strcase.h" #include "strchrnul.h" #include "strndup.h" #endif /* normal libc functions we call */ #undef __flockfile #define __flockfile flockfile #undef __funlockfile #define __funlockfile funlockfile #undef __mempcpy #define __mempcpy mempcpy #undef __sleep #define __sleep sleep #undef __strcasecmp #define __strcasecmp strcasecmp #undef __strchrnul #define __strchrnul strchrnul #undef __strerror_r #define __strerror_r strerror_r #undef __strndup #define __strndup strndup #undef __vsnprintf #define __vsnprintf vsnprintf #if defined(HAVE_DECL_CLEARERR_UNLOCKED) && !HAVE_DECL_CLEARERR_UNLOCKED # define clearerr_unlocked(x) clearerr (x) #endif #if defined(HAVE_DECL_FEOF_UNLOCKED) && !HAVE_DECL_FEOF_UNLOCKED # define feof_unlocked(x) feof (x) # endif #if defined(HAVE_DECL_FERROR_UNLOCKED) && !HAVE_DECL_FERROR_UNLOCKED # define ferror_unlocked(x) ferror (x) # endif #if defined(HAVE_DECL_FFLUSH_UNLOCKED) && !HAVE_DECL_FFLUSH_UNLOCKED # define fflush_unlocked(x) fflush (x) # endif #if defined(HAVE_DECL_FGETS_UNLOCKED) && !HAVE_DECL_FGETS_UNLOCKED # define fgets_unlocked(x,y,z) fgets (x,y,z) # endif #if defined(HAVE_DECL_FPUTC_UNLOCKED) && !HAVE_DECL_FPUTC_UNLOCKED # define fputc_unlocked(x,y) fputc (x,y) # endif #if defined(HAVE_DECL_FPUTS_UNLOCKED) && !HAVE_DECL_FPUTS_UNLOCKED # define fputs_unlocked(x,y) fputs (x,y) # endif #if defined(HAVE_DECL_FREAD_UNLOCKED) && !HAVE_DECL_FREAD_UNLOCKED # define fread_unlocked(w,x,y,z) fread (w,x,y,z) # endif #if defined(HAVE_DECL_FWRITE_UNLOCKED) && !HAVE_DECL_FWRITE_UNLOCKED # define fwrite_unlocked(w,x,y,z) fwrite (w,x,y,z) # endif #if defined(HAVE_DECL_GETC_UNLOCKED) && !HAVE_DECL_GETC_UNLOCKED # define getc_unlocked(x) getc (x) # endif #if defined(HAVE_DECL_GETCHAR_UNLOCKED) && !HAVE_DECL_GETCHAR_UNLOCKED # define getchar_unlocked() getchar () # endif #if defined(HAVE_DECL_PUTC_UNLOCKED) && !HAVE_DECL_PUTC_UNLOCKED # define putc_unlocked(x,y) putc (x,y) # endif #if defined(HAVE_DECL_PUTCHAR_UNLOCKED) && !HAVE_DECL_PUTCHAR_UNLOCKED # define putchar_unlocked(x) putchar (x) # endif extern char *__argp_basename (char *name); #endif /* !_LIBC */ #ifndef __set_errno #define __set_errno(e) (errno = (e)) #endif #if defined _LIBC || HAVE_DECL_PROGRAM_INVOCATION_SHORT_NAME # define __argp_short_program_name() (program_invocation_short_name) #else extern char *__argp_short_program_name (void); #endif
[ "jflinn" ]
jflinn
2d84cecdd0896eb5a0544732b63032cd8d8f32fa
b27a0ef18ffe42f4e601da55e1ba6b61cc0deccf
/brush/BrushInterface.cpp
fe649aa75a37aaac4e12d9b07d89e3de1b55836a
[]
no_license
cogle/Computer-Graphics-CSE_452-
8c8b0782f2e413b8c5f7fd472f1158262da92b76
8555d8ca92fec60bf2b46b145b995cb62cbd8270
refs/heads/master
2021-01-01T05:41:30.953004
2015-04-20T04:03:21
2015-04-20T04:03:21
29,278,761
0
2
null
null
null
null
UTF-8
C++
false
false
6,267
cpp
// generated by Fast Light User Interface Designer (fluid) version 1.0107 #include "BrushInterface.h" void BrushInterface::cb_Constant_i(Fl_Menu_*, void*) { myBrush.changedBrush(); } void BrushInterface::cb_Constant(Fl_Menu_* o, void* v) { ((BrushInterface*)(o->parent()->user_data()))->cb_Constant_i(o,v); } void BrushInterface::cb_Linear_i(Fl_Menu_*, void*) { myBrush.changedBrush(); } void BrushInterface::cb_Linear(Fl_Menu_* o, void* v) { ((BrushInterface*)(o->parent()->user_data()))->cb_Linear_i(o,v); } void BrushInterface::cb_Quadratic_i(Fl_Menu_*, void*) { myBrush.changedBrush(); } void BrushInterface::cb_Quadratic(Fl_Menu_* o, void* v) { ((BrushInterface*)(o->parent()->user_data()))->cb_Quadratic_i(o,v); } void BrushInterface::cb_Gaussian_i(Fl_Menu_*, void*) { myBrush.changedBrush(); } void BrushInterface::cb_Gaussian(Fl_Menu_* o, void* v) { ((BrushInterface*)(o->parent()->user_data()))->cb_Gaussian_i(o,v); } Fl_Menu_Item BrushInterface::menu_m_iBrushType[] = { {"Constant", 0, (Fl_Callback*)BrushInterface::cb_Constant, 0, 4, FL_NORMAL_LABEL, 0, 14, 0}, {"Linear", 0, (Fl_Callback*)BrushInterface::cb_Linear, 0, 0, FL_NORMAL_LABEL, 0, 14, 0}, {"Quadratic", 0, (Fl_Callback*)BrushInterface::cb_Quadratic, 0, 0, FL_NORMAL_LABEL, 0, 14, 0}, {"Gaussian", 0, (Fl_Callback*)BrushInterface::cb_Gaussian, 0, 0, FL_NORMAL_LABEL, 0, 14, 0}, {0,0,0,0,0,0,0,0,0} }; void BrushInterface::cb_m_iRadius_i(Fl_Value_Slider*, void*) { myBrush.changedBrush( ); } void BrushInterface::cb_m_iRadius(Fl_Value_Slider* o, void* v) { ((BrushInterface*)(o->parent()->user_data()))->cb_m_iRadius_i(o,v); } Fl_Menu_Item BrushInterface::menu_m_iToolType[] = { {"Brush", 0, 0, 0, 4, FL_NORMAL_LABEL, 0, 14, 0}, {"Line", 0, 0, 0, 4, FL_NORMAL_LABEL, 0, 14, 0}, {"Circle", 0, 0, 0, 4, FL_NORMAL_LABEL, 0, 14, 0}, {"Polygon", 0, 0, 0, 4, FL_NORMAL_LABEL, 0, 14, 0}, {"Filter", 0, 0, 0, 4, FL_NORMAL_LABEL, 0, 14, 0}, {0,0,0,0,0,0,0,0,0} }; Fl_Menu_Item BrushInterface::menu_m_iFilterType[] = { {"Blur", 0, 0, 0, 4, FL_NORMAL_LABEL, 0, 14, 0}, {"Sharpen", 0, 0, 0, 4, FL_NORMAL_LABEL, 0, 14, 0}, {"Edge", 0, 0, 0, 4, FL_NORMAL_LABEL, 0, 14, 0}, {0,0,0,0,0,0,0,0,0} }; void BrushInterface::cb_m_dRed_i(Fl_Value_Slider*, void*) { SetPreview(); } void BrushInterface::cb_m_dRed(Fl_Value_Slider* o, void* v) { ((BrushInterface*)(o->parent()->user_data()))->cb_m_dRed_i(o,v); } void BrushInterface::cb_m_dGreen_i(Fl_Value_Slider*, void*) { SetPreview(); } void BrushInterface::cb_m_dGreen(Fl_Value_Slider* o, void* v) { ((BrushInterface*)(o->parent()->user_data()))->cb_m_dGreen_i(o,v); } void BrushInterface::cb_m_dBlue_i(Fl_Value_Slider*, void*) { SetPreview(); } void BrushInterface::cb_m_dBlue(Fl_Value_Slider* o, void* v) { ((BrushInterface*)(o->parent()->user_data()))->cb_m_dBlue_i(o,v); } Fl_Double_Window* BrushInterface::make_window() { Fl_Double_Window* w; { Fl_Double_Window* o = m_brushWindow = new Fl_Double_Window(480, 220, "Brush UI"); w = o; o->user_data((void*)(this)); { Fl_Choice* o = m_iBrushType = new Fl_Choice(5, 25, 180, 30, "Brush Type"); o->down_box(FL_BORDER_BOX); o->align(FL_ALIGN_TOP_LEFT); o->menu(menu_m_iBrushType); } { Fl_Value_Slider* o = m_iRadius = new Fl_Value_Slider(5, 78, 180, 30, "Radius"); o->type(5); o->minimum(1); o->maximum(64); o->step(1); o->value(4); o->callback((Fl_Callback*)cb_m_iRadius); o->align(FL_ALIGN_TOP_LEFT); } { Fl_Value_Slider* o = m_dPixelFlow = new Fl_Value_Slider(5, 132, 180, 30, "Pixel flow"); o->type(5); o->value(0.5); o->align(FL_ALIGN_TOP_LEFT); } { Fl_Choice* o = m_iToolType = new Fl_Choice(5, 185, 180, 30, "Tool"); o->down_box(FL_BORDER_BOX); o->align(FL_ALIGN_TOP_LEFT); o->menu(menu_m_iToolType); } { Fl_Choice* o = m_iFilterType = new Fl_Choice(205, 185, 180, 30, "Filter"); o->down_box(FL_BORDER_BOX); o->align(FL_ALIGN_TOP_LEFT); o->menu(menu_m_iFilterType); } { Fl_Value_Slider* o = m_dRed = new Fl_Value_Slider(205, 25, 35, 140, "R"); o->type(4); o->box(FL_BORDER_BOX); o->value(0.5); o->callback((Fl_Callback*)cb_m_dRed); o->align(FL_ALIGN_TOP); } { Fl_Value_Slider* o = m_dGreen = new Fl_Value_Slider(256, 25, 35, 140, "G"); o->type(4); o->box(FL_BORDER_BOX); o->value(0.5); o->callback((Fl_Callback*)cb_m_dGreen); o->align(FL_ALIGN_TOP); } { Fl_Value_Slider* o = m_dBlue = new Fl_Value_Slider(308, 25, 35, 140, "B"); o->type(4); o->box(FL_BORDER_BOX); o->value(0.5); o->callback((Fl_Callback*)cb_m_dBlue); o->align(FL_ALIGN_TOP); } { Fl_Box* o = m_boxPreview = new Fl_Box(360, 45, 115, 120, "Preview"); o->box(FL_DOWN_BOX); o->color((Fl_Color)80); o->align(FL_ALIGN_TOP); } o->end(); o->resizable(o); } return w; } BrushInterface::BrushInterface() { m_brushWindow = make_window(); myBrush.setUI( this ); myBrush.changedBrush(); SetPreview(); } void BrushInterface::SetPreview() { Fl_Color c = fl_rgb_color( (unsigned char) (255.0 * m_dRed->value()), (unsigned char) (255.0 * m_dGreen->value()), (unsigned char) (255.0 * m_dBlue->value()) ); m_boxPreview->color( c ); m_boxPreview->redraw(); } MyBrush::BrushType BrushInterface::getBrushType() const { return (MyBrush::BrushType) m_iBrushType->value(); } MyBrush::FilterType BrushInterface::getFilterType() const { return (MyBrush::FilterType) m_iFilterType->value(); } int BrushInterface::getRadius() const { return (int) m_iRadius->value(); } MyBrush::ToolType BrushInterface::getToolType() const { return (MyBrush::ToolType) m_iToolType->value(); } Color BrushInterface::getColor() const { return Color( static_cast<float>(m_dRed->value()), static_cast<float>(m_dGreen->value()), static_cast<float>(m_dBlue->value()) ); } float BrushInterface::getFlow() const { return (float) m_dPixelFlow->value(); } void BrushInterface::loadImage( Fl_Image *image ) { myBrush.loadImage(image); } UIInterface * BrushInterface::getUI() { return &myBrush; }
[ "thecogle@gmail.com" ]
thecogle@gmail.com