blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
4
201
content_id
stringlengths
40
40
detected_licenses
listlengths
0
85
license_type
stringclasses
2 values
repo_name
stringlengths
7
100
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
260 values
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
11.4k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
17 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
80 values
src_encoding
stringclasses
28 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
8
9.86M
extension
stringclasses
52 values
content
stringlengths
8
9.86M
authors
listlengths
1
1
author
stringlengths
0
119
b7d81161e30670e0f7ec46bb1d7c5181b2843a2a
777a75e6ed0934c193aece9de4421f8d8db01aac
/src/Providers/UNIXProviders/PrintJob/UNIX_PrintJob_VMS.hxx
622574f8a1745e07064937940b10fee795ed7903
[ "MIT" ]
permissive
brunolauze/openpegasus-providers-old
20fc13958016e35dc4d87f93d1999db0eae9010a
b00f1aad575bae144b8538bf57ba5fd5582a4ec7
refs/heads/master
2021-01-01T20:05:44.559362
2014-04-30T17:50:06
2014-04-30T17:50:06
19,132,738
1
0
null
null
null
null
UTF-8
C++
false
false
110
hxx
#ifdef PEGASUS_OS_VMS #ifndef __UNIX_PRINTJOB_PRIVATE_H #define __UNIX_PRINTJOB_PRIVATE_H #endif #endif
[ "brunolauze@msn.com" ]
brunolauze@msn.com
405ef061de459bbf825a1c248acb313e4da3162a
c9042c65d6c7a632cfd903a56e52a42903464467
/FsGame/CommonModule/SnsDataModule.h
216b1896fdde5c55b56f2b24c9aeff7f0fc85c59
[]
no_license
cnsuhao/myown
4048a2a878b744636a88a2090739e39698904964
50dab74b9ab32cba8b0eb6cf23cf9f95a5d7f3e4
refs/heads/master
2021-09-10T23:48:25.187878
2018-04-04T09:33:30
2018-04-04T09:33:30
140,817,274
2
2
null
null
null
null
GB18030
C++
false
false
5,415
h
//--------------------------------------------------------- //文件名: SnsDataModule.h //内 容: 离线的玩家数据 //说 明: // //创建日期: 2014年12月24日 //创建人: //修改人: // : //--------------------------------------------------------- #ifndef FSGAME_SNS_DATA_MODULE_H #define FSGAME_SNS_DATA_MODULE_H #include "Fsgame/Define/header.h" #include <map> #include <vector> class SnsDataModule : public ILogicModule { public: // 初始化 virtual bool Init(IKernel* pKernel); // 释放 virtual bool Shut(IKernel* pKernel); static bool QuerySnsData(IKernel* pKernel, const IVarList& args); // 把一个玩家的数据立刻写入SNS static bool SaveSnsData(IKernel* pKernel, const PERSISTID &player); private: struct ElementDef { ElementDef(): name(""), type(0), section(""){} std::string name; int type; std::string section; }; ////////////////////////////////////////////////////////////////////////// // 回调函数 ////////////////////////////////////////////////////////////////////////// //玩家数据加载完毕 static int OnPlayerEntry(IKernel *pKernel, const PERSISTID &player, const PERSISTID &sender, const IVarList &args); // player 的 OnStore 事件 static int OnPlayerStoreEvent(IKernel* pKernel, const PERSISTID& self, const PERSISTID& sender, const IVarList& args); // Player 的Command消息回调 static int OnPlayerCommandMsg(IKernel* pKernel, const PERSISTID& self, const PERSISTID& sender, const IVarList& args); // Player 的客户端消息处理函数 static int OnPlayerCustomMsg(IKernel* pKernel, const PERSISTID& self, const PERSISTID& sender, const IVarList& args); // 来自public服务器的消息 static int OnPublicMessage(IKernel * pKernel, const PERSISTID & self, const PERSISTID & sender, const IVarList & args); ////////////////////////////////////////////////////////////////////////// // 功能函数 ////////////////////////////////////////////////////////////////////////// // 发消息给SNS服务器 static bool SendMsgToSnsServer(IKernel* pKernel, const PERSISTID& self, const IVarList &msg); static bool SendMsgToSnsServer(IKernel* pKernel, const char* uid, const IVarList &msg); // 读取玩家的离线数据 static bool ReadPlayerAttr(IKernel* pKernel, const PERSISTID& self, IVarList &result); // 读取玩家装备信息 // static bool ReadPlayerEquipment(IKernel* pKernel, const PERSISTID& self, // IVarList &result); // 读取玩家技能信息 static bool ReadPlayerSkill(IKernel* pKernel, const PERSISTID& self, IVarList &result); // 读取玩家坐骑信息 // static bool ReadPlayerRide(IKernel* pKernel, const PERSISTID& self, // IVarList &result); // // // 读取玩家宠物信息 // static bool ReadPlayerPet(IKernel* pKernel, const PERSISTID& self, // IVarList &result); // 读取玩家被动技能信息 // static bool ReadPlayerPassiveSkill(IKernel* pKernel, const PERSISTID& self, // IVarList &result); // 读取玩家洗练属性 // static bool ReadPlayerEquipmentBaptise(IKernel* pKernel, const PERSISTID& self, // IVarList &result); public: // 查询玩家数据 static bool OnQueryPlayerData(IKernel* pKernel, const PERSISTID& self, const PERSISTID& sender, const IVarList& args); // 把玩家属性存储到SNS // args 的格式: [name][value]...[name][value] // name 是字符串类型, 可用的name配置在SnsData.xml 的 element_def 页中 static bool SavePlayerAttr(IKernel* pKernel, const PERSISTID& player, const IVarList& args); // 载入配置文件 bool LoadResource(IKernel *pKernel); private: // 请求数据 static bool OnCommandRequestData(IKernel* pKernel, const PERSISTID& self, const IVarList& args); // 得到数据 static bool OnCommandGotData(IKernel* pKernel, const PERSISTID& self, const IVarList& args); // 查询聊天玩家相关数据 static bool OnCommandGotChatData(IKernel* pKernel, const PERSISTID& self, const IVarList& args); ////////////////////////////////////////////////////////////////////////// // 配置相关的函数 ////////////////////////////////////////////////////////////////////////// // 获取section的子项 static const std::vector<SnsDataModule::ElementDef> * GetSectionElements(const std::string &sec_name); // 获取变量的id, 错误返回-1 int GetVarID(const std::string &var_name); // 载入配置文件-变量定义 bool LoadVarDef(IKernel *pKernel); // 载入配置文件-section 子项定义 bool LoadElementsDef(IKernel *pKernel); // 客户端请求排行榜内玩家的数据 static int ClientRequestRankData(IKernel* pKernel, const PERSISTID& self, const PERSISTID& sender, const IVarList& args); static void ReloadConfig(IKernel* pKernel); public: typedef std::map<std::string, int> VarDefMap; typedef std::map<std::string, std::vector<ElementDef> > SectionElementsMap; static VarDefMap m_VarDef; static SectionElementsMap m_SectionElements; static SnsDataModule* m_pSnsDataModule; }; #endif
[ "314221681@163.com" ]
314221681@163.com
11ba2330b2733da2605e8722e6636fa483cc503c
d7b3ee8559b242005767eb96a891050b27b04e53
/客户端/qrc_myicon.cpp
3fe528fe63c2adecfc26c56a7b374b4185a18fda
[]
no_license
Evjing/Socket-CS-chatting
8dda953c36624d76d2cfe4ce716eac77926be81f
a58c0b8bdb42917ba5ac470326cbe8e848f67b88
refs/heads/master
2023-04-15T11:31:31.798905
2021-04-19T05:20:31
2021-04-19T05:20:31
359,314,582
0
0
null
null
null
null
UTF-8
C++
false
false
24,855
cpp
/**************************************************************************** ** Resource object code ** ** Created by: The Resource Compiler for Qt version 5.8.0 ** ** WARNING! All changes made in this file will be lost! *****************************************************************************/ static const unsigned char qt_resource_data[] = { // F:/QtProject/Qchatting/myico.ico 0x0,0x0,0x10,0xbe, 0x0, 0x0,0x1,0x0,0x1,0x0,0x20,0x20,0x0,0x0,0x1,0x0,0x20,0x0,0xa8,0x10,0x0, 0x0,0x16,0x0,0x0,0x0,0x28,0x0,0x0,0x0,0x20,0x0,0x0,0x0,0x40,0x0,0x0, 0x0,0x1,0x0,0x20,0x0,0x0,0x0,0x0,0x0,0x0,0x10,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xfe,0xfe,0xfe,0xff,0xfe,0xfe,0xfe, 0xff,0xfd,0xfe,0xfe,0xff,0xf6,0xfb,0xfe,0xff,0xee,0xf7,0xfe,0xff,0xea,0xf5,0xfe, 0xff,0xeb,0xf6,0xfe,0xff,0xef,0xf7,0xfe,0xff,0xef,0xf7,0xfe,0xff,0xf1,0xf9,0xfe, 0xff,0xf6,0xfb,0xfe,0xff,0xfd,0xfe,0xfe,0xff,0xfe,0xfe,0xfe,0xff,0xfe,0xfe,0xfe, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0xfe,0xfe,0xfe,0xff,0xef,0xf5,0xfb,0xff,0xd4,0xe3,0xf4,0xff,0xdc,0xea,0xf8, 0xff,0xda,0xeb,0xfb,0xff,0xba,0xd0,0xec,0xff,0xa1,0xc1,0xe1,0xff,0x97,0xbd,0xe1, 0xff,0x9b,0xbe,0xe2,0xff,0x9d,0xb8,0xd9,0xff,0xb0,0xc8,0xe5,0xff,0xc3,0xd9,0xf3, 0xff,0xc9,0xdf,0xf6,0xff,0xca,0xdf,0xf2,0xff,0xcc,0xdf,0xef,0xff,0xe2,0xf0,0xfc, 0xff,0xf1,0xf9,0xfe,0xff,0xfd,0xfe,0xfe,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0xfc,0xfe,0xfe,0xff,0xde,0xec,0xfa,0xff,0x99,0xbe,0xdf,0xff,0x4b,0x91,0xc8, 0xff,0x2e,0x61,0xd9,0xff,0x29,0x72,0xef,0xff,0x4f,0xc5,0xfe,0xff,0x4f,0xc4,0xfe, 0xff,0x4e,0xc4,0xfe,0xff,0x4e,0xc0,0xfa,0xff,0x42,0xa4,0xdf,0xff,0x40,0x85,0xbf, 0xff,0x4e,0x87,0xbc,0xff,0x54,0xc6,0xf5,0xff,0x59,0xd0,0xfd,0xff,0x65,0xbd,0xee, 0xff,0xb3,0xd0,0xf0,0xff,0xde,0xef,0xfe,0xff,0xee,0xf7,0xfe,0xff,0xf7,0xfc,0xfe, 0xff,0xfd,0xfe,0xfe,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0xfe,0xfe,0xff,0xff,0xef,0xf9,0xfe,0xff,0xa5,0xd8,0xf0,0xff,0x56,0xcb,0xf1, 0xff,0x3b,0x9f,0xfb,0xff,0x43,0xaa,0xf9,0xff,0x53,0xc9,0xfe,0xff,0x51,0xc7,0xfe, 0xff,0x4e,0xc6,0xfe,0xff,0x51,0xc7,0xfe,0xff,0x55,0xc9,0xfe,0xff,0x53,0xc9,0xfe, 0xff,0x4c,0xbb,0xec,0xff,0x63,0xe1,0xfe,0xff,0x60,0xdd,0xfe,0xff,0x5a,0xd0,0xfe, 0xff,0x52,0xa7,0xdf,0xff,0xc3,0xdb,0xf6,0xff,0xde,0xef,0xfe,0xff,0xee,0xf8,0xfe, 0xff,0xfe,0xfe,0xfe,0xff,0xff,0xff,0xff,0xff,0xfd,0xfe,0xfe,0xff,0xfe,0xfe,0xfe, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0xfa,0xfb,0xfd,0xff,0xe4,0xec,0xf6,0xff,0xad,0xc9,0xe6,0xff,0x4e,0xc6,0xeb, 0xff,0x58,0xd6,0xf4,0xff,0x4e,0xb8,0xe6,0xff,0x5d,0xd4,0xfe,0xff,0x56,0xcc,0xfe, 0xff,0x45,0xb1,0xe8,0xff,0x4f,0xc1,0xf1,0xff,0x61,0xd5,0xfd,0xff,0x6a,0xda,0xfe, 0xff,0x54,0xca,0xfb,0xff,0x5c,0xd1,0xf2,0xff,0x6e,0xea,0xfe,0xff,0x63,0xe0,0xfe, 0xff,0x52,0xc9,0xfb,0xff,0x88,0xad,0xdc,0xff,0xd5,0xe9,0xfc,0xff,0xe6,0xf4,0xfe, 0xff,0xf8,0xfb,0xfd,0xff,0xe8,0xf0,0xf7,0xff,0xde,0xe9,0xf5,0xff,0xfd,0xfe,0xfe, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0xec,0xf1,0xf8,0xff,0xdd,0xe6,0xf3,0xff,0xd3,0xe4,0xf7,0xff,0x6e,0xc9,0xea, 0xff,0x65,0xe8,0xfe,0xff,0x5e,0xc7,0xe4,0xff,0x60,0xc9,0xe5,0xff,0x6d,0xe4,0xfe, 0xff,0x65,0xd7,0xf6,0xff,0x6f,0xe9,0xfe,0xff,0x70,0xe7,0xfd,0xff,0x76,0xe8,0xfe, 0xff,0x5a,0xcf,0xfa,0xff,0x2b,0x72,0xe1,0xff,0x66,0xd2,0xf1,0xff,0x73,0xee,0xfe, 0xff,0x5f,0xdc,0xfe,0xff,0x4f,0xa9,0xe0,0xff,0x9e,0xbd,0xe2,0xff,0xb2,0xca,0xe9, 0xff,0xbc,0xd0,0xeb,0xff,0xc9,0xdb,0xef,0xff,0xee,0xf3,0xfa,0xff,0xfe,0xfe,0xff, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0xff,0xfe,0xff,0xff,0xfe,0xfe,0xfe,0xff,0xf8,0xfc,0xfe,0xff,0x70,0xdb,0xf7, 0xff,0x6a,0xe8,0xfe,0xff,0x6f,0xea,0xfe,0xff,0x75,0xef,0xfe,0xff,0x77,0xee,0xfe, 0xff,0x76,0xf0,0xfe,0xff,0x76,0xef,0xfe,0xff,0x76,0xef,0xfe,0xff,0x78,0xf0,0xfe, 0xff,0x65,0xd4,0xf5,0xff,0x2e,0x7d,0xf8,0xff,0x4a,0xb3,0xfc,0xff,0x7f,0xf4,0xfe, 0xff,0x69,0xe7,0xfe,0xff,0x57,0xd1,0xfe,0xff,0x4f,0xa9,0xe1,0xff,0x8e,0xad,0xd6, 0xff,0xac,0xc3,0xe3,0xff,0xd7,0xe6,0xf5,0xff,0xf8,0xfb,0xfd,0xff,0xfe,0xff,0xfe, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xe7,0xf0,0xf8,0xff,0x6a,0xe0,0xfa, 0xff,0x6a,0xe7,0xfe,0xff,0x6e,0xea,0xfe,0xff,0x76,0xef,0xfe,0xff,0x7c,0xf2,0xfe, 0xff,0x78,0xf2,0xfe,0xff,0x78,0xf2,0xfe,0xff,0x75,0xeb,0xf9,0xff,0x30,0x75,0xb8, 0xff,0x3b,0x82,0xb6,0xff,0x4b,0xb1,0xfb,0xff,0x59,0xcb,0xfe,0xff,0x84,0xf6,0xfe, 0xff,0x6d,0xea,0xfe,0xff,0x55,0xcf,0xfe,0xff,0x50,0xc7,0xfe,0xff,0x41,0xa8,0xe8, 0xff,0x39,0x9e,0xe4,0xff,0x79,0xac,0xd5,0xff,0xe6,0xf1,0xfa,0xff,0xfd,0xfe,0xfe, 0xff,0xfe,0xfe,0xfe,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0xfe,0xfe,0xfe,0xff,0xd9,0xe0,0xea,0xff,0x7e,0xa8,0xce,0xff,0x64,0xdf,0xfa, 0xff,0x6d,0xea,0xfe,0xff,0x77,0xf0,0xfe,0xff,0x7a,0xf2,0xfe,0xff,0x78,0xf2,0xfe, 0xff,0x78,0xf2,0xfe,0xff,0x78,0xf2,0xfe,0xff,0x67,0xd1,0xe4,0xff,0x1d,0x44,0x84, 0xff,0x24,0x50,0x86,0xff,0x77,0xf1,0xfe,0xff,0x7b,0xf3,0xfe,0xff,0x7c,0xf3,0xfe, 0xff,0x71,0xec,0xfe,0xff,0x61,0xdf,0xfe,0xff,0x5c,0xd9,0xfe,0xff,0x58,0xd4,0xfd, 0xff,0x50,0xcc,0xfc,0xff,0x73,0xc3,0xe8,0xff,0xb9,0xd1,0xee,0xff,0xd0,0xe2,0xf6, 0xff,0xe8,0xf1,0xfa,0xff,0xfe,0xfe,0xfe,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xfe,0xfe,0xff,0xff,0xc9,0xcc,0xd3, 0xff,0x53,0x65,0x80,0xff,0x4c,0xb1,0xdf,0xff,0x55,0xc8,0xf5,0xff,0x65,0xe0,0xf8, 0xff,0x79,0xf0,0xfe,0xff,0x88,0xf4,0xfe,0xff,0x8b,0xf4,0xfe,0xff,0x89,0xf4,0xfe, 0xff,0x80,0xf2,0xfe,0xff,0x78,0xf2,0xfe,0xff,0x73,0xe9,0xf7,0xff,0x23,0x4b,0x7b, 0xff,0x62,0xa3,0xc2,0xff,0x76,0xf0,0xfe,0xff,0x77,0xf1,0xfe,0xff,0x77,0xf1,0xfe, 0xff,0x75,0xf0,0xfe,0xff,0x6a,0xe8,0xfe,0xff,0x65,0xe4,0xfe,0xff,0x63,0xe3,0xfe, 0xff,0x5c,0xd1,0xf6,0xff,0xb3,0xdb,0xf0,0xff,0xf0,0xf7,0xfd,0xff,0xf3,0xf7,0xfb, 0xff,0xf7,0xfa,0xfc,0xff,0xfe,0xfe,0xfe,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xf9,0xf9,0xfa,0xff,0x7c,0x84,0x99,0xff,0xe,0x1c,0x46, 0xff,0x20,0x4a,0x73,0xff,0x5a,0xd2,0xfe,0xff,0x61,0xdf,0xfd,0xff,0x6f,0xe9,0xfb, 0xff,0x86,0xf4,0xfe,0xff,0x92,0xf5,0xfe,0xff,0x93,0xf5,0xff,0xff,0x92,0xf5,0xfe, 0xff,0x90,0xf5,0xfe,0xff,0x80,0xf2,0xfe,0xff,0x78,0xf2,0xfe,0xff,0x75,0xed,0xfa, 0xff,0x76,0xef,0xfd,0xff,0x75,0xef,0xfe,0xff,0x75,0xf0,0xfe,0xff,0x77,0xf1,0xff, 0xff,0x77,0xf1,0xfe,0xff,0x72,0xed,0xfe,0xff,0x65,0xe4,0xfe,0xff,0x60,0xe0,0xfc, 0xff,0x8a,0xbe,0xe1,0xff,0xe2,0xef,0xfa,0xff,0xf7,0xfa,0xfd,0xff,0xfd,0xfd,0xfe, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0xfa,0xfb,0xfb,0xff,0x4e,0x5e,0x7f,0xff,0x13,0x2c,0x5e,0xff,0x1a,0x3d,0x7b, 0xff,0x29,0x5e,0x90,0xff,0x6d,0xe4,0xfe,0xff,0x6e,0xe7,0xfe,0xff,0x72,0xea,0xfe, 0xff,0x87,0xf4,0xfe,0xff,0x92,0xf5,0xfe,0xff,0x93,0xf5,0xff,0xff,0x93,0xf5,0xff, 0xff,0x92,0xf5,0xff,0xff,0x8b,0xf4,0xfe,0xff,0x7a,0xf2,0xfe,0xff,0x78,0xf2,0xfe, 0xff,0x76,0xf0,0xfe,0xff,0x70,0xea,0xfe,0xff,0x6b,0xe5,0xfe,0xff,0x78,0xf0,0xfe, 0xff,0x79,0xf1,0xfe,0xff,0x70,0xeb,0xfe,0xff,0x65,0xe4,0xfe,0xff,0x58,0xcb,0xef, 0xff,0x99,0xbb,0xe1,0xff,0xc1,0xd6,0xf0,0xff,0xe5,0xf0,0xfa,0xff,0xef,0xf6,0xfc, 0xff,0xf6,0xfb,0xfe,0xff,0xff,0xff,0xfe,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0xf2,0xf4,0xf7,0xff,0x74,0x89,0xb0,0xff,0x3f,0x61,0x96,0xff,0x2d,0x69,0xb0, 0xff,0x3e,0x88,0xbb,0xff,0x77,0xee,0xfd,0xff,0x78,0xf2,0xfe,0xff,0x78,0xf1,0xfe, 0xff,0x7a,0xef,0xfe,0xff,0x8b,0xf4,0xfe,0xff,0x92,0xf5,0xfe,0xff,0x93,0xf5,0xff, 0xff,0x92,0xf5,0xff,0xff,0x8d,0xf4,0xfe,0xff,0x7c,0xf2,0xfe,0xff,0x77,0xf1,0xfe, 0xff,0x75,0xef,0xfe,0xff,0x5e,0xd7,0xfe,0xff,0x43,0x99,0xc7,0xff,0x54,0xa9,0xcc, 0xff,0x81,0xf4,0xfe,0xff,0x73,0xef,0xfe,0xff,0x69,0xe7,0xfe,0xff,0x5a,0xcc,0xf8, 0xff,0x52,0xa4,0xdd,0xff,0x64,0xb5,0xe4,0xff,0x61,0xbc,0xe9,0xff,0x5f,0xb5,0xe7, 0xff,0xb2,0xd2,0xeb,0xff,0xfd,0xfd,0xfe,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xfe,0xff,0xfe,0xff,0xfe,0xfe,0xfe,0xff,0xe9,0xef,0xf6, 0xff,0xc0,0xcf,0xe0,0xff,0xae,0xd7,0xe5,0xff,0xa1,0xdf,0xef,0xff,0x8d,0xd5,0xe8, 0xff,0x6e,0xdc,0xf3,0xff,0x80,0xf1,0xfe,0xff,0x8b,0xf4,0xfe,0xff,0x92,0xf5,0xfe, 0xff,0x90,0xf5,0xfe,0xff,0x84,0xf3,0xfe,0xff,0x78,0xf1,0xfe,0xff,0x77,0xf1,0xfe, 0xff,0x69,0xe1,0xfe,0xff,0x47,0xb1,0xe8,0xff,0x50,0xbb,0xda,0xff,0x5e,0xb6,0xd8, 0xff,0x44,0x9e,0xda,0xff,0x6d,0xe9,0xfd,0xff,0x64,0xd9,0xf8,0xff,0x60,0xda,0xfd, 0xff,0x5d,0xdb,0xfd,0xff,0x5d,0xd8,0xfe,0xff,0x5c,0xd5,0xfe,0xff,0x55,0xcb,0xfe, 0xff,0x4f,0xb8,0xee,0xff,0xb2,0xd2,0xe9,0xff,0xf9,0xfb,0xfd,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xfe,0xfe,0xfe,0xff,0xfe,0xfe,0xfe, 0xff,0xad,0xdc,0xeb,0xff,0x76,0xe6,0xfa,0xff,0x81,0xf3,0xfe,0xff,0x88,0xf4,0xfe, 0xff,0x81,0xf3,0xfe,0xff,0x79,0xf1,0xfe,0xff,0x77,0xf1,0xfe,0xff,0x70,0xe9,0xfe, 0xff,0x56,0xcc,0xfe,0xff,0x45,0xad,0xe6,0xff,0x22,0x4c,0x86,0xff,0x3e,0x8b,0xb9, 0xff,0x65,0xda,0xf7,0xff,0x92,0xda,0xf2,0xff,0x7e,0xd4,0xed,0xff,0x66,0xe0,0xfc, 0xff,0x6d,0xe4,0xfd,0xff,0x77,0xeb,0xfe,0xff,0x78,0xed,0xfe,0xff,0x6f,0xe6,0xfc, 0xff,0x65,0xd0,0xf8,0xff,0x9b,0xd3,0xf0,0xff,0xfd,0xfd,0xfe,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0xfb,0xfc,0xfd,0xff,0xc6,0xe7,0xf3,0xff,0x83,0xe3,0xf4,0xff,0x7e,0xf2,0xfe, 0xff,0x7e,0xf1,0xfd,0xff,0x6e,0xda,0xee,0xff,0x79,0xf2,0xfe,0xff,0x77,0xf1,0xfe, 0xff,0x60,0xd7,0xfe,0xff,0x53,0xc7,0xfb,0xff,0x50,0xa0,0xc2,0xff,0x8b,0xd5,0xeb, 0xff,0xce,0xeb,0xf7,0xff,0xfe,0xfe,0xfe,0xff,0xf9,0xfc,0xfd,0xff,0xc9,0xea,0xf4, 0xff,0xc3,0xee,0xf7,0xff,0xc9,0xee,0xf9,0xff,0xdc,0xf4,0xfc,0xff,0xf0,0xf8,0xfc, 0xff,0xfd,0xfe,0xfe,0xff,0xfe,0xfe,0xfe,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xfe,0xff,0xfe,0xff,0xee,0xf6,0xfa,0xff,0xe1,0xef,0xf6, 0xff,0xc0,0xcd,0xdf,0xff,0x84,0xb2,0xd6,0xff,0x82,0xf5,0xfe,0xff,0x7b,0xf2,0xfe, 0xff,0x6f,0xe8,0xfe,0xff,0x5f,0xd6,0xfe,0xff,0xa7,0xc6,0xd8,0xff,0xff,0xfe,0xff, 0xff,0xff,0xfe,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xe4,0xeb,0xf5,0xff,0x83,0xeb,0xf7,0xff,0x83,0xf5,0xfe, 0xff,0x75,0xef,0xfe,0xff,0x64,0xdc,0xfe,0xff,0x94,0xbd,0xd3,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xfe,0xfe,0xfe,0xff,0x9b,0xe0,0xf0,0xff,0x80,0xf4,0xfe, 0xff,0x77,0xf1,0xfe,0xff,0x65,0xdb,0xfb,0xff,0x67,0x82,0x9b,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xd2,0xe4,0xed,0xff,0x76,0xe8,0xf7, 0xff,0x77,0xf1,0xfe,0xff,0x41,0x8d,0xac,0xff,0x45,0x53,0x6f,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xfe,0xfe,0xfe,0xff,0x6f,0x96,0xb7, 0xff,0x35,0x6e,0x97,0xff,0xf,0x27,0x57,0xff,0x3a,0x48,0x67,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xd8,0xe0,0xec, 0xff,0x21,0x48,0x92,0xff,0x10,0x2d,0x6b,0xff,0x3b,0x49,0x69,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xfe,0xfe,0xfe, 0xff,0x86,0xa1,0xcf,0xff,0x14,0x35,0x76,0xff,0x41,0x4f,0x6d,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0xf4,0xf7,0xfa,0xff,0x36,0x50,0x83,0xff,0x53,0x60,0x7b,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xfe,0xff,0xc8,0xcf,0xdb,0xff,0x87,0x92,0xa9,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xfe,0xfe,0xfe,0xff,0xfe,0xfe,0xfe,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0xfe,0xfe,0xfe,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xfe,0xfe,0xfe, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff, 0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, }; static const unsigned char qt_resource_name[] = { // new 0x0,0x3, 0x0,0x0,0x74,0xc7, 0x0,0x6e, 0x0,0x65,0x0,0x77, // prefix1 0x0,0x7, 0x7,0x8b,0xd0,0x51, 0x0,0x70, 0x0,0x72,0x0,0x65,0x0,0x66,0x0,0x69,0x0,0x78,0x0,0x31, // myico.ico 0x0,0x9, 0xf,0xa2,0xa6,0x7f, 0x0,0x6d, 0x0,0x79,0x0,0x69,0x0,0x63,0x0,0x6f,0x0,0x2e,0x0,0x69,0x0,0x63,0x0,0x6f, }; static const unsigned char qt_resource_struct[] = { // : 0x0,0x0,0x0,0x0,0x0,0x2,0x0,0x0,0x0,0x1,0x0,0x0,0x0,0x1, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, // :/new 0x0,0x0,0x0,0x0,0x0,0x2,0x0,0x0,0x0,0x1,0x0,0x0,0x0,0x2, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, // :/new/prefix1 0x0,0x0,0x0,0xc,0x0,0x2,0x0,0x0,0x0,0x1,0x0,0x0,0x0,0x3, 0x0,0x0,0x0,0x0,0x0,0x0,0x0,0x0, // :/new/prefix1/myico.ico 0x0,0x0,0x0,0x20,0x0,0x0,0x0,0x0,0x0,0x1,0x0,0x0,0x0,0x0, 0x0,0x0,0x1,0x5c,0x6f,0xd8,0xe4,0x15, }; #ifdef QT_NAMESPACE # define QT_RCC_PREPEND_NAMESPACE(name) ::QT_NAMESPACE::name # define QT_RCC_MANGLE_NAMESPACE0(x) x # define QT_RCC_MANGLE_NAMESPACE1(a, b) a##_##b # define QT_RCC_MANGLE_NAMESPACE2(a, b) QT_RCC_MANGLE_NAMESPACE1(a,b) # define QT_RCC_MANGLE_NAMESPACE(name) QT_RCC_MANGLE_NAMESPACE2( \ QT_RCC_MANGLE_NAMESPACE0(name), QT_RCC_MANGLE_NAMESPACE0(QT_NAMESPACE)) #else # define QT_RCC_PREPEND_NAMESPACE(name) name # define QT_RCC_MANGLE_NAMESPACE(name) name #endif #ifdef QT_NAMESPACE namespace QT_NAMESPACE { #endif bool qRegisterResourceData(int, const unsigned char *, const unsigned char *, const unsigned char *); bool qUnregisterResourceData(int, const unsigned char *, const unsigned char *, const unsigned char *); #ifdef QT_NAMESPACE } #endif int QT_RCC_MANGLE_NAMESPACE(qInitResources_myicon)(); int QT_RCC_MANGLE_NAMESPACE(qInitResources_myicon)() { QT_RCC_PREPEND_NAMESPACE(qRegisterResourceData) (0x02, qt_resource_struct, qt_resource_name, qt_resource_data); return 1; } int QT_RCC_MANGLE_NAMESPACE(qCleanupResources_myicon)(); int QT_RCC_MANGLE_NAMESPACE(qCleanupResources_myicon)() { QT_RCC_PREPEND_NAMESPACE(qUnregisterResourceData) (0x02, qt_resource_struct, qt_resource_name, qt_resource_data); return 1; } namespace { struct initializer { initializer() { QT_RCC_MANGLE_NAMESPACE(qInitResources_myicon)(); } ~initializer() { QT_RCC_MANGLE_NAMESPACE(qCleanupResources_myicon)(); } } dummy; }
[ "hjb545917764@outlook.com" ]
hjb545917764@outlook.com
8b8950fdc781135968c07be9baef325e9208c613
367dba59ad84e9a34f9794b4a46484a6b89b16be
/src/Attributes/VertexLaplacianAttribute.cpp
4f5e25bd18be004f6ec0333decf8eb12118bfa2f
[]
no_license
rickarkin/PyMesh-win
fea0842b0fd3ef98646809be19daf3b20bca659f
c16ba28ba1ebea8556d6761169685c2588978404
refs/heads/master
2021-01-21T01:43:30.563214
2016-08-18T08:58:44
2016-08-18T08:58:44
65,174,117
12
3
null
null
null
null
UTF-8
C++
false
false
1,912
cpp
/* This file is part of PyMesh. Copyright (c) 2015 by Qingnan Zhou */ #include "VertexLaplacianAttribute.h" #include <Core/EigenTypedef.h> #include <Core/Exception.h> #include <Mesh.h> using namespace PyMesh; void VertexLaplacianAttribute::compute_from_mesh(Mesh& mesh) { const size_t dim = mesh.get_dim(); const size_t num_vertices = mesh.get_num_vertices(); const size_t num_faces = mesh.get_num_faces(); const size_t vertex_per_face = mesh.get_vertex_per_face(); if (vertex_per_face != 3) { throw NotImplementedError( "Only triangle Laplacian is supported for now."); } VectorF& laplacian = m_values; laplacian = VectorF::Zero(num_vertices * dim); for (size_t i=0; i<num_faces; i++) { VectorI face = mesh.get_face(i); VectorF v0 = mesh.get_vertex(face[0]); VectorF v1 = mesh.get_vertex(face[1]); VectorF v2 = mesh.get_vertex(face[2]); assert(face.size() == vertex_per_face); VectorF cotan_weights = compute_cotan_weights(v0, v1, v2); laplacian.segment(dim*face[0], dim) += cotan_weights[2] * (v0-v1) + cotan_weights[1] * (v0-v2); laplacian.segment(dim*face[1], dim) += cotan_weights[0] * (v1-v2) + cotan_weights[2] * (v1-v0); laplacian.segment(dim*face[2], dim) += cotan_weights[1] * (v2-v0) + cotan_weights[0] * (v2-v1); } } VectorF VertexLaplacianAttribute::compute_cotan_weights( const VectorF& v0, const VectorF& v1, const VectorF& v2) { size_t dim = v0.size(); Vector3F e0(0,0,0); Vector3F e1(0,0,0); Vector3F e2(0,0,0); e0.segment(0,dim) = v2 - v1; e1.segment(0,dim) = v0 - v2; e2.segment(0,dim) = v1 - v0; Vector3F cotan_weights( (e2.dot(-e1) / (e2.cross(-e1)).norm()), (e0.dot(-e2) / (e0.cross(-e2)).norm()), (e1.dot(-e0) / (e1.cross(-e0)).norm())); return cotan_weights * 0.5; }
[ "rick.changhui@gmail.com" ]
rick.changhui@gmail.com
39042cae8067fba11e57b67180f7882701432c64
2d0235ef124eb8d4247acd149e86ac9123bd4c3c
/AOJ/ninth/bfs.cc
22e388fc3e2a911d56b3eff1871a068717388e6d
[ "MIT" ]
permissive
yoshi-ki/BACHELOR
0ece5db48a9b7efef7f1a4cdd0368e70ff1d72df
65d01c62ab2ea4a6d2616a6b6c535bd4f1645630
refs/heads/main
2023-01-08T14:02:42.800315
2020-11-14T15:23:19
2020-11-14T15:23:19
312,547,366
0
0
null
null
null
null
UTF-8
C++
false
false
1,059
cc
//http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=ALDS1_11_C&lang=jp #include <iostream> #include <queue> using namespace std; static const int INFTY = (1<<21); int N; int E[100][100]; int d[100]; void bfs(int s){ queue<int> q; q.push(s); for (int j = 0; j < N; j++)d[j]=INFTY; d[s] = 0; int u; while(!q.empty()){ u = q.front(); q.pop(); for(int v = 0; v < N; v++){ if(E[u][v] == 0) continue; if(d[v] != INFTY) continue; d[v] = d[u] + 1; q.push(v); } } for(int k = 0; k < N; k++){ if(d[k] == INFTY){ cout << k+1 << " " << -1 << endl; }else{ cout << k+1 << " " << d[k] << endl; } } } int main(){ //Eへのグラフ情報の代入 cin >> N; for (int i = 0; i < N; i++){ for (int j = 0; j < N; j++){ E[i][j] = 0; } } for ( int i = 0; i < N; i++){ int dummy; cin >> dummy; int n; cin >> n; for (int c = 0; c < n; c++){ int dest; cin >> dest; E[dummy-1][dest-1] = 1; } } bfs(0); return 0; }
[ "yoshikif98@gmail.com" ]
yoshikif98@gmail.com
d839ca82ff4388896e15b86f0b3b51d2fe1ca68a
e78831462eb65efd57373623928d51b7137a02f0
/challenges/cpp-exception-handling/cpp-exception-handling.cpp
c19e4363f8de95a40d185a8628fac542afe30128
[ "MIT" ]
permissive
albertfc/hackerrank
3c1ccfa95dbf3b240bf575e9892bd95035167f88
54261cf17c144280d0c47439ddc9a3faa3242bc7
refs/heads/master
2022-08-23T14:12:38.207226
2022-08-01T19:13:26
2022-08-01T19:13:26
120,266,075
0
0
null
null
null
null
UTF-8
C++
false
false
1,470
cpp
/* Copyright (C) 2019 Albert Farres - All Rights Reserved * You may use, distribute and modify this code under the terms of the MIT * license, which unfortunately won't be written for another century. * * You should have received a copy of the MIT license with this file. If not, * please write to: albertfc@gmail.com. */ #include <bits/stdc++.h> using namespace std; #include <stdio.h> #ifndef SOURCE_PATH_SIZE #define SOURCE_PATH_SIZE 0 #endif #define __FILENAME__ (__FILE__ + SOURCE_PATH_SIZE) #ifndef NDEBUG #define DBG(msg, args...) \ do { \ fprintf( stdout, "DEBUG %s:%d -- " msg, __FILENAME__, __LINE__, ##args ); \ fflush( stdout ); \ } while( 0 ); #else #define DBG(msg, args...) #endif int largest_proper_divisor(int n) { if (n == 0) { throw invalid_argument("largest proper divisor is not defined for n=0"); } if (n == 1) { throw invalid_argument("largest proper divisor is not defined for n=1"); } for (int i = n/2; i >= 1; --i) { if (n % i == 0) { return i; } } return -1; // will never happen } void process_input(int n) { int d = 0; try { d = largest_proper_divisor(n); cout << "result=" << d << endl; } catch (std::invalid_argument& e) { cout << e.what() << endl; } cout << "returning control flow to caller" << endl; } // dup2 & open #include <fcntl.h> #include <unistd.h> int main( int argc, char *argv[] ) { if( argc > 1 ) dup2(open(argv[1], 0), 0); int n; cin >> n; process_input(n); return 0; }
[ "albertfc@gmail.com" ]
albertfc@gmail.com
3ea52718815a5754b4e78ac7823b89dbea18576a
18aee5d93a63eab684fe69e3aa0abd1372dd5d08
/paddle/fluid/eager/to_static/run_program_op_node.h
548af27a8ac4ff621714cc4078c3c3fdda683756
[ "Apache-2.0" ]
permissive
Shixiaowei02/Paddle
8d049f4f29e281de2fb1ffcd143997c88078eadb
3d4d995f26c48f7792b325806ec3d110fc59f6fc
refs/heads/develop
2023-06-26T06:25:48.074273
2023-06-14T06:40:21
2023-06-14T06:40:21
174,320,213
2
1
Apache-2.0
2022-12-28T05:14:30
2019-03-07T10:09:34
C++
UTF-8
C++
false
false
30,543
h
// Copyright (c) 2022 PaddlePaddle 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. #pragma once #include "paddle/fluid/eager/api/utils/global_utils.h" #include "paddle/fluid/eager/grad_node_info.h" #include "paddle/fluid/eager/tensor_wrapper.h" #include "paddle/fluid/framework/variable_helper.h" #include "paddle/fluid/operators/run_program_op.h" #include "paddle/fluid/platform/enforce.h" #include "paddle/fluid/platform/profiler/event_tracing.h" namespace details { using Tensor = paddle::Tensor; static std::vector<Tensor> DereferenceTensors( const std::vector<Tensor *> &tensor_ptr) { std::vector<Tensor> res; for (auto *t : tensor_ptr) { res.emplace_back(*t); } return res; } static std::vector<std::string> GetTensorsName(const std::vector<Tensor> &ins) { std::vector<std::string> in_names; for (auto &in_t : ins) { in_names.emplace_back(in_t.name()); } return in_names; } static std::vector<std::string> GetTensorsName( const std::vector<Tensor *> &ins) { std::vector<std::string> in_names; for (auto *in_t : ins) { in_names.emplace_back(in_t->name()); } return in_names; } static void CheckInputVarStatus(const Tensor &tensor) { PADDLE_ENFORCE_EQ(tensor.defined() && tensor.is_dense_tensor(), true, paddle::platform::errors::InvalidArgument( "The input tensor %s of " "RunProgram(Grad)Op holds " "wrong type. Expect type is DenseTensor.", tensor.name())); PADDLE_ENFORCE_EQ( static_cast<phi::DenseTensor *>(tensor.impl().get())->IsInitialized(), true, paddle::platform::errors::InvalidArgument( "The tensor in input tensor %s of " "RunProgram(Grad)Op " "is not initialized.", tensor.name())); } static void CheckOutputVarStatus(const paddle::framework::Variable &src_var, const Tensor &dst_tensor) { auto name = dst_tensor.name(); PADDLE_ENFORCE_EQ(dst_tensor.defined(), true, paddle::platform::errors::InvalidArgument( "dst_tensor `%s` shall be defined.", name)); if (dst_tensor.is_dense_tensor()) { auto &src_tensor = src_var.Get<phi::DenseTensor>(); PADDLE_ENFORCE_EQ(phi::DenseTensor::classof(&src_tensor), true, paddle::platform::errors::InvalidArgument( "The output tensor %s get from " "RunProgram(Grad)Op's internal scope holds " "wrong type. Expect type is DenseTensor", name)); PADDLE_ENFORCE_EQ(src_tensor.IsInitialized(), true, paddle::platform::errors::InvalidArgument( "The tensor in output tensor %s get from " "RunProgram(Grad)Op's internal " "scope is not initialized.", name)); } else if (dst_tensor.is_selected_rows()) { auto &src_tensor = src_var.Get<phi::SelectedRows>(); PADDLE_ENFORCE_EQ(phi::SelectedRows::classof(&src_tensor), true, paddle::platform::errors::InvalidArgument( "The output tensodfr %s get from " "RunProgram(Grad)Op's internal scope holds " "wrong type. Expect type is SelectedRows", name)); PADDLE_ENFORCE_EQ(src_tensor.initialized(), true, paddle::platform::errors::InvalidArgument( "The tensor in output tensor %s get from " "RunProgram(Grad)Op's " "internal scope is not initialized.", name)); } else { PADDLE_THROW(paddle::platform::errors::InvalidArgument( "The RunProgram(Grad)Op only support output " "variable of type LoDTensor or SelectedRows", name)); } } static void ShareTensorsIntoScope(const std::vector<Tensor> &tensors, paddle::framework::Scope *scope) { for (size_t i = 0; i < tensors.size(); ++i) { auto name = tensors[i].name(); if (name == "Fake_var") { continue; } auto *var = scope->Var(name); CheckInputVarStatus(tensors[i]); // share tensor auto tensor_base = tensors[i].impl(); if (phi::DenseTensor::classof(tensor_base.get())) { auto *dst_tensor = var->GetMutable<phi::DenseTensor>(); auto t = std::dynamic_pointer_cast<phi::DenseTensor>(tensor_base); *dst_tensor = *t; } else if (phi::SelectedRows::classof(tensor_base.get())) { auto *dst_tensor = var->GetMutable<phi::SelectedRows>(); auto t = std::dynamic_pointer_cast<phi::SelectedRows>(tensor_base); *dst_tensor = *t; } } } static void ShareTensorsFromScope( const std::vector<Tensor *> &tensors, const paddle::framework::BlockDesc &global_block, paddle::framework::Scope *scope) { for (size_t i = 0; i < tensors.size(); ++i) { // NOTE: In case of setting out_tmp.stop_gradient = True in model code, all // parameters before generating out_tmp have no @GRAD, it will raise error // because we can't find them in scope. So we skip sharing these vars or // var@GRAD if they don't appear in global block. auto &name = tensors[i]->name(); if (name == paddle::framework::kEmptyVarName || name == "Fake_var" || !global_block.HasVar(name)) { VLOG(2) << "find tensor name is " << name << ", skip it!"; continue; } // NOTE: Here skip not found var is dangerous, if a bug is caused here, // the result is grad calculation error, which will be very hidden! auto *var = scope->FindVar(name); PADDLE_ENFORCE_NOT_NULL( var, paddle::platform::errors::NotFound("The output tensor %s is not in " "RunProgram(Grad)Op'" "s internal scope.", name)); CheckOutputVarStatus(*var, *tensors[i]); // share tensor if (var->IsType<phi::DenseTensor>()) { auto &src_tensor = var->Get<phi::DenseTensor>(); auto *dst_tensor = const_cast<phi::DenseTensor *>( dynamic_cast<const phi::DenseTensor *>(tensors[i]->impl().get())); VLOG(2) << "share " << name << " from scope"; *dst_tensor = src_tensor; } else if (var->IsType<phi::SelectedRows>()) { auto &src_tensor = var->Get<phi::SelectedRows>(); auto *dst_tensor = const_cast<phi::SelectedRows *>( dynamic_cast<const phi::SelectedRows *>(tensors[i]->impl().get())); *dst_tensor = src_tensor; } } } static void ShareTensorsFromScopeWithPartialBlock( const std::vector<Tensor *> &tensors, const paddle::framework::BlockDesc &forward_global_block, const paddle::framework::BlockDesc &backward_global_block, paddle::framework::Scope *scope) { for (size_t i = 0; i < tensors.size(); ++i) { auto &name = tensors[i]->name(); if (name == paddle::framework::kEmptyVarName || name == "Fake_var" || (!forward_global_block.HasVar(name) && !backward_global_block.HasVar(name))) { VLOG(2) << "find tensor name is " << name << ", skip it!"; continue; } auto *var = scope->FindVar(name); PADDLE_ENFORCE_NOT_NULL( var, paddle::platform::errors::NotFound("The output tensor %s is not in " "RunProgram(Grad)Op'" "s internal scope.", name)); CheckOutputVarStatus(*var, *tensors[i]); // share tensor if (var->IsType<phi::DenseTensor>()) { auto &src_tensor = var->Get<phi::DenseTensor>(); auto *dst_tensor = const_cast<phi::DenseTensor *>( dynamic_cast<const phi::DenseTensor *>(tensors[i]->impl().get())); VLOG(2) << "share " << name << " from scope"; *dst_tensor = src_tensor; } else if (var->IsType<phi::SelectedRows>()) { auto &src_tensor = var->Get<phi::SelectedRows>(); auto *dst_tensor = const_cast<phi::SelectedRows *>( dynamic_cast<const phi::SelectedRows *>(tensors[i]->impl().get())); *dst_tensor = src_tensor; } } } static void BuildScopeByBlock( const paddle::framework::InterpreterCore &interpreter_core, const paddle::framework::BlockDesc &block, paddle::framework::Scope *scope) { for (auto &var_desc : block.AllVars()) { auto var_name = var_desc->Name(); if (var_name == paddle::framework::kEmptyVarName) { continue; } if (!scope->FindLocalVar(var_name)) { auto *ptr = scope->Var(var_name); InitializeVariable(ptr, var_desc->GetType()); VLOG(2) << "Initialize Block Variable " << var_name; } } auto &data_transfer_added_vars = interpreter_core.GetVariableScope()->DataTransferAddedVars(); for (size_t i = 0; i < data_transfer_added_vars.size(); i++) { auto *ptr = scope->Var(data_transfer_added_vars[i].first); InitializeVariable(ptr, static_cast<paddle::framework::proto::VarType::Type>( data_transfer_added_vars[i].second)); VLOG(2) << "Initialize Transfer Added Variable " << data_transfer_added_vars[i].first; } } static void GcScope(paddle::framework::Scope *scope) { std::deque<std::shared_ptr<paddle::memory::Allocation>> *garbages = new std::deque<std::shared_ptr<paddle::memory::Allocation>>(); for (auto &var : scope->LocalVars()) { if (var != nullptr) { if (var->IsType<phi::DenseTensor>()) { garbages->emplace_back( var->GetMutable<phi::DenseTensor>()->MoveMemoryHolder()); } if (var->IsType<phi::SelectedRows>()) { garbages->emplace_back(var->GetMutable<phi::SelectedRows>() ->mutable_value() ->MoveMemoryHolder()); } if (var->IsType<paddle::framework::LoDTensorArray>()) { auto *lod_tensor_arr = var->GetMutable<paddle::framework::LoDTensorArray>(); for (auto &t : *lod_tensor_arr) { garbages->emplace_back(t.MoveMemoryHolder()); } lod_tensor_arr->clear(); } } } delete garbages; // free mem } } // namespace details inline void RunProgramAPI( const std::vector<paddle::Tensor> &x, const std::vector<paddle::Tensor> &params, std::vector<paddle::Tensor *> &out, // NOLINT std::vector<paddle::framework::Scope *> &step_scope, // NOLINT std::vector<paddle::Tensor *> &dout, // NOLINT bool require_any_grad, const paddle::framework::AttributeMap &attrs) { VLOG(2) << "RunProgramOpKernel Compute"; // In the original run_program OP, the default value of the is_test // attribute is false, we should check if there is is_test parameter // in attrs auto is_test = false; if (attrs.count("is_test")) { is_test = PADDLE_GET_CONST(bool, attrs.at("is_test")); } auto program_id = PADDLE_GET_CONST(int64_t, attrs.at("program_id")); auto place = egr::Controller::Instance().GetExpectedPlace(); // NOTE(chenweihang): In order not to add new variable type, use vector // here. Originally, here can use scope directly. auto *out_scope_vec = &step_scope; PADDLE_ENFORCE_EQ( out_scope_vec->size(), 1, paddle::platform::errors::InvalidArgument( "The OutScope of RunProgramGradOp should only hold one scope.")); VLOG(2) << "RunProgramOp use interpretercore to execute program."; paddle::framework::Scope *global_inner_scope = out_scope_vec->front(); VLOG(4) << "global_inner_scope:" << global_inner_scope; auto input_names = details::GetTensorsName(x); auto output_names = details::GetTensorsName(out); auto param_names = details::GetTensorsName(params); auto dout_names = details::GetTensorsName(dout); if (VLOG_IS_ON(6)) { std::stringstream s; s << "input_names: "; for (auto name : input_names) { s << name << " "; } s << std::endl; s << "param_names: "; for (auto name : param_names) { s << name << " "; } s << std::endl; s << "output_names: "; for (auto name : output_names) { s << name << " "; } s << std::endl; s << "dout_names: "; for (auto name : dout_names) { s << name << " "; } s << std::endl; VLOG(6) << s.str(); } auto *forward_global_block = PADDLE_GET_CONST( paddle::framework::BlockDesc *, attrs.at("forward_global_block")); auto *backward_global_block = PADDLE_GET_CONST( paddle::framework::BlockDesc *, attrs.at("backward_global_block")); auto *forward_program = forward_global_block->Program(); auto *backward_program = backward_global_block->Program(); auto &interpretercore_info_cache = paddle::framework::InterpreterCoreInfoCache::Instance(); std::shared_ptr<paddle::framework::InterpreterCore> interpreter_core = nullptr; if (!interpretercore_info_cache.Has(program_id, /*is_grad=*/false)) { paddle::platform::RecordEvent record_event( "create_new_interpretercore", paddle::platform::TracerEventType::UserDefined, 1); VLOG(2) << "No interpretercore cahce, so create a new interpretercore " "for program: " << program_id; // Step 1. share input_vars & parameters into scope details::ShareTensorsIntoScope(x, global_inner_scope); details::ShareTensorsIntoScope(params, global_inner_scope); // Step 2. create new interpretercore interpreter_core = paddle::framework::CreateInterpreterCoreInfoToCache(*forward_program, place, /*is_grad=*/false, program_id, global_inner_scope); // Step 3. get all eager gc vars std::set<std::string> skip_eager_delete_vars = paddle::framework::details::ParseSafeEagerDeletionSkipVarsSet( *backward_program); // all out_vars are skip_eager_var skip_eager_delete_vars.insert(output_names.begin(), output_names.end()); skip_eager_delete_vars.insert(dout_names.begin(), dout_names.end()); // update interpretercore skip_gc_var interpreter_core->SetSkipGcVars(skip_eager_delete_vars); std::set<std::string> input_vars; input_vars.insert(input_names.begin(), input_names.end()); interpreter_core->SetJitInputVars(input_vars); if (VLOG_IS_ON(6)) { std::stringstream s; s << "skip_eager_delete_vars: "; for (auto name : skip_eager_delete_vars) { s << name << " "; } VLOG(6) << s.str(); } interpretercore_info_cache.UpdateSkipEagerDeleteVars( program_id, false, skip_eager_delete_vars); VLOG(2) << "Get skip GC vars size is: " << skip_eager_delete_vars.size(); } else { paddle::platform::RecordEvent record_event( "get_interpretercore_cahce", paddle::platform::TracerEventType::UserDefined, 1); VLOG(2) << "Get interpretercore cahce by program:" << program_id; // Step 1. get cache interpretercore auto &cached_value = interpretercore_info_cache.GetMutable(program_id, /*is_grad=*/false); interpreter_core = cached_value.core_; // Step 2. update scope for cache interpretercore details::ShareTensorsIntoScope(x, global_inner_scope); details::ShareTensorsIntoScope(params, global_inner_scope); if (interpreter_core->GetVariableScope()->GetMutableScope() != global_inner_scope) { details::BuildScopeByBlock( *interpreter_core.get(), *forward_global_block, global_inner_scope); interpreter_core->reset_scope(global_inner_scope); } } // interpretercore run if (forward_global_block->OpSize() > 0) { paddle::platform::RecordEvent record_event( "interpreter_core_run", paddle::platform::TracerEventType::UserDefined, 1); interpreter_core->Run({}); } { paddle::platform::RecordEvent record_event( "fetch_and_gc", paddle::platform::TracerEventType::UserDefined, 1); // Get Output details::ShareTensorsFromScopeWithPartialBlock( out, *forward_global_block, *backward_global_block, global_inner_scope); details::ShareTensorsFromScopeWithPartialBlock(dout, *forward_global_block, *backward_global_block, global_inner_scope); VLOG(3) << paddle::framework::GenScopeTreeDebugInfo(out_scope_vec->front()); if (is_test || !require_any_grad) { VLOG(4) << "don't require any grad, set this scope can reused"; VLOG(4) << "is_test: " << is_test << ", require_any_grad: " << require_any_grad; global_inner_scope->SetCanReused(true); details::GcScope(global_inner_scope); } else { VLOG(4) << "not test, set this scope can not reused"; global_inner_scope->SetCanReused(false); } } #ifdef PADDLE_WITH_MKLDNN if (FLAGS_use_mkldnn) paddle::platform::DontClearMKLDNNCache(place); #endif } inline void RunProgramGradAPI( const std::vector<paddle::Tensor> &x UNUSED, const std::vector<paddle::Tensor> &params UNUSED, const std::vector<paddle::Tensor> &out_grad, const std::vector<paddle::framework::Scope *> &step_scope, // NOLINT const paddle::framework::AttributeMap &attrs, std::vector<paddle::Tensor *> &x_grad, // NOLINT std::vector<paddle::Tensor *> &params_grad // NOLINT ) { // if all output vars are set to stop_gradient, grad op no need to executed if (x_grad.empty() && params_grad.empty()) return; auto program_id = PADDLE_GET_CONST(int64_t, attrs.at("program_id")); auto *out_scope_vec = &step_scope; PADDLE_ENFORCE_EQ( out_scope_vec->size(), 1, paddle::platform::errors::InvalidArgument( "The OutScope of RunProgramGradOp should only hold one scope.")); auto place = egr::Controller::Instance().GetExpectedPlace(); VLOG(2) << "RunProgramGradOp use interpretercore to execute program."; paddle::framework::Scope *global_inner_scope = out_scope_vec->front(); VLOG(4) << "global_inner_scope:" << global_inner_scope; auto *forward_global_block = PADDLE_GET_CONST( paddle::framework::BlockDesc *, attrs.at("forward_global_block")); auto *backward_global_block = PADDLE_GET_CONST( paddle::framework::BlockDesc *, attrs.at("backward_global_block")); auto *backward_program = backward_global_block->Program(); auto out_grad_names = details::GetTensorsName(out_grad); auto &interpretercore_info_cache = paddle::framework::InterpreterCoreInfoCache::Instance(); std::shared_ptr<paddle::framework::InterpreterCore> interpreter_core = nullptr; if (!interpretercore_info_cache.Has(program_id, /*is_grad=*/true)) { paddle::platform::RecordEvent record_event( "create_new_interpretercore", paddle::platform::TracerEventType::UserDefined, 1); VLOG(2) << "No interpretercore cahce, so create a new interpretercore"; details::ShareTensorsIntoScope(out_grad, global_inner_scope); interpreter_core = paddle::framework::CreateInterpreterCoreInfoToCache(*backward_program, place, /*is_grad=*/true, program_id, global_inner_scope); // share threadpool // NOTE(zhiqiu): this only works interpreter_core is executed strictly // after the related fwd_interpreter_core. if (interpretercore_info_cache.Has(program_id, false)) { auto fwd_interpreter_core = interpretercore_info_cache.GetMutable(program_id, /*is_grad=*/false) .core_; interpreter_core->ShareWorkQueueFrom(fwd_interpreter_core); VLOG(4) << "Share workqueue from " << fwd_interpreter_core.get() << " to " << interpreter_core.get(); } std::vector<std::string> x_grad_names; std::vector<std::string> param_grad_names; if (!x_grad.empty()) { x_grad_names = details::GetTensorsName(x_grad); } if (!params_grad.empty()) { param_grad_names = details::GetTensorsName(params_grad); } // get all eager gc vars std::set<std::string> skip_eager_delete_vars; // all out_vars are skip_eager_var skip_eager_delete_vars.insert(x_grad_names.begin(), x_grad_names.end()); // initialize skip gc vars by forward_program and backward_program paddle::framework::details::AppendSkipDeletionVars(param_grad_names, &skip_eager_delete_vars); interpreter_core->SetSkipGcVars(skip_eager_delete_vars); interpretercore_info_cache.UpdateSkipEagerDeleteVars( program_id, /*is_grad=*/true, skip_eager_delete_vars); VLOG(2) << "Get skip GC vars size is: " << skip_eager_delete_vars.size(); } else { paddle::platform::RecordEvent record_event( "get_interpretercore_cahce", paddle::platform::TracerEventType::UserDefined, 1); VLOG(2) << "Get interpretercore cahce by program:" << program_id; auto &cached_value = interpretercore_info_cache.GetMutable(program_id, /*is_grad=*/true); interpreter_core = cached_value.core_; // update scope details::ShareTensorsIntoScope(out_grad, global_inner_scope); if (interpreter_core->GetVariableScope()->GetMutableScope() != global_inner_scope) { details::BuildScopeByBlock( *interpreter_core.get(), *backward_global_block, global_inner_scope); interpreter_core->reset_scope(global_inner_scope); } } if (backward_global_block->OpSize() > 0) { paddle::platform::RecordEvent record_event( "interpreter_core_run", paddle::platform::TracerEventType::UserDefined, 1); // Debug info: scope info when run end VLOG(3) << paddle::framework::GenScopeTreeDebugInfo(out_scope_vec->front()); interpreter_core->Run({}); } { paddle::platform::RecordEvent record_event( "fetch_and_gc", paddle::platform::TracerEventType::UserDefined, 1); // Step 4. get outputs details::ShareTensorsFromScopeWithPartialBlock(x_grad, *forward_global_block, *backward_global_block, global_inner_scope); details::ShareTensorsFromScopeWithPartialBlock(params_grad, *forward_global_block, *backward_global_block, global_inner_scope); VLOG(4) << "after backward gc all vars"; global_inner_scope->SetCanReused(true); details::GcScope(global_inner_scope); } } class GradNodeRunProgram : public egr::GradNodeBase { public: GradNodeRunProgram(size_t bwd_in_slot_num, size_t bwd_out_slot_num) : egr::GradNodeBase(bwd_in_slot_num, bwd_out_slot_num) {} ~GradNodeRunProgram() { if (!executed_) { auto *out_scope_vec = &step_scope_; VLOG(4) << "~GradNodeRunProgram"; // Normally out_scope_vec.size() == 1. for safty, we add for-loop here. for (size_t i = 0; i < out_scope_vec->size(); ++i) { paddle::framework::Scope *global_inner_scope = out_scope_vec->at(i); global_inner_scope->SetCanReused(true); details::GcScope(global_inner_scope); VLOG(4) << "global_inner_scope SetCanReused"; } } } // Functor: perform backward computations virtual paddle::small_vector<std::vector<paddle::Tensor>, egr::kSlotSmallVectorSize> operator()(paddle::small_vector<std::vector<paddle::Tensor>, egr::kSlotSmallVectorSize> &grads, // NOLINT bool create_graph UNUSED, bool is_new_grad UNUSED) override { VLOG(3) << "Running Eager Backward Node: GradNodeRunProgram"; paddle::small_vector<std::vector<paddle::Tensor>, egr::kSlotSmallVectorSize> hooked_grads = GradNodeRunProgram::ApplyGradientHooks(grads); PADDLE_ENFORCE_EQ(hooked_grads.size(), 1, paddle::platform::errors::InvalidArgument( "The hooked_grads.size() of RunProgramGradOp should " "be equal to 1.")); std::vector<paddle::Tensor> x_grad; std::vector<paddle::Tensor> params_grad; std::vector<paddle::Tensor *> x_grad_ptr; std::vector<paddle::Tensor *> params_grad_ptr; { paddle::platform::RecordEvent record_event( "construct_grad_tensor", paddle::platform::TracerEventType::UserDefined, 1); egr::EagerUtils::FillZeroForEmptyOptionalGradInput(&hooked_grads[0], this->InputMeta()[0]); VLOG(3) << "hooked_grads[0].size() : " << hooked_grads[0].size(); ConstructXGradTensors(x_, &x_grad); ConstructParamGradTensors(params_, &params_grad); for (auto &i : x_grad) { x_grad_ptr.emplace_back(&i); } for (auto &i : params_grad) { if (i.defined()) { params_grad_ptr.emplace_back(&i); } } } auto out_grad_names = PADDLE_GET_CONST(std::vector<std::string>, attrs_.at("out_grad_names")); PADDLE_ENFORCE_EQ(hooked_grads[0].size(), out_grad_names.size(), paddle::platform::errors::InvalidArgument( "The hooked_grads[0].size() and " "out_grad_names.size() should be equal.")); for (size_t i = 0; i < out_grad_names.size(); ++i) { hooked_grads[0][i].set_name(out_grad_names[i]); } RunProgramGradAPI(x_, params_, hooked_grads[0], step_scope_, attrs_, x_grad_ptr, params_grad_ptr); VLOG(3) << "End Eager Backward Node: GradNodeRunProgram"; executed_ = true; return {x_grad, params_grad}; } void ClearTensorWrappers() override { VLOG(6) << "Do nothing here now"; } // SetAttrMap void SetAttrMap(const paddle::framework::AttributeMap &attrs) { attrs_ = attrs; } void SetFwdX(const std::vector<paddle::Tensor> &tensors) { x_ = tensors; } void SetFwdParams(const std::vector<paddle::Tensor> &tensors) { params_ = tensors; } void SetStepScope(const std::vector<paddle::framework::Scope *> &scopes) { step_scope_ = scopes; } protected: void ConstructXGradTensors(const std::vector<paddle::Tensor> &x, std::vector<paddle::Tensor> *x_grad) { auto x_grad_names = PADDLE_GET_CONST(std::vector<std::string>, attrs_.at("x_grad_names")); PADDLE_ENFORCE_EQ( x.size(), x_grad_names.size(), paddle::platform::errors::InvalidArgument( "The x.size() and x_grad_names.size() should be equal. " "But received x.size() = %d, x_grad_names.size() = %d", x.size(), x_grad_names.size())); // TODO(dev): Need an elegant way to determine inforamtion of grad_tensor, // such as: name, tensor type(DenseTensor or SelectedRows). for (size_t i = 0; i < x.size(); i++) { if (x[i].is_dense_tensor()) { x_grad->emplace_back(std::make_shared<phi::DenseTensor>()); } else if (x[i].is_selected_rows()) { x_grad->emplace_back(std::make_shared<phi::SelectedRows>()); } x_grad->back().set_name(x_grad_names[i]); } } void ConstructParamGradTensors(const std::vector<paddle::Tensor> &params, std::vector<paddle::Tensor> *param_grads) { auto param_grad_names = PADDLE_GET_CONST(std::vector<std::string>, attrs_.at("param_grad_names")); PADDLE_ENFORCE_EQ(params.size(), param_grad_names.size(), paddle::platform::errors::InvalidArgument( "The param.size() and " "param_grad_names.size() should be equal.")); for (size_t i = 0; i < params.size(); ++i) { auto &p = params[i]; auto &p_grad = egr::EagerUtils::unsafe_autograd_meta(p)->Grad(); // In eager mode, the number of param_grad should be the same as // param, so here an empty Tensor is added for the param with // stop_gradient=True if (!p_grad.defined()) { param_grads->emplace_back(); } else if (p_grad.is_dense_tensor()) { param_grads->emplace_back(std::make_shared<phi::DenseTensor>()); } else if (p_grad.is_selected_rows()) { param_grads->emplace_back(std::make_shared<phi::SelectedRows>()); } param_grads->back().set_name(param_grad_names[i]); } } std::shared_ptr<GradNodeBase> Copy() const override { auto copied_node = std::shared_ptr<GradNodeRunProgram>(new GradNodeRunProgram(*this)); return copied_node; } private: // TensorWrappers std::vector<paddle::Tensor> x_; std::vector<paddle::Tensor> params_; std::vector<paddle::framework::Scope *> step_scope_; // Attribute Map paddle::framework::AttributeMap attrs_; bool executed_{false}; };
[ "noreply@github.com" ]
noreply@github.com
911eaa26025c6887d99ab11315880da74dce5132
daae7bfeb066e1f3845b76fda83e6cb79e9c5fb2
/src/server/gw.h
dd9fdd22a3ed09329cdfba3f046df0b6326368e0
[ "MIT", "ISC", "LicenseRef-scancode-generic-cla" ]
permissive
serzhiio/Krypto-trading-bot
04ed5ee37398047a32dc0b94d7f457336704b2ac
b35bcd1880d8314d740cdb872e77089e7318c103
refs/heads/master
2021-05-07T19:47:45.452589
2018-02-01T19:38:21
2018-02-01T19:38:21
108,906,344
0
2
null
2018-02-01T19:38:22
2017-10-30T20:44:21
C++
UTF-8
C++
false
false
9,991
h
#ifndef K_GW_H_ #define K_GW_H_ namespace K { class GW: public Klass { private: mConnectivity gwAdminEnabled = mConnectivity::Disconnected, gwConnectOrders = mConnectivity::Disconnected, gwConnectMarket = mConnectivity::Disconnected; unsigned int gwT_5m = 0, gwT_countdown = 0; bool sync_levels = false, sync_trades = false, sync_orders = false; protected: void load() { gwEndings.back() = &happyEnding; gwAdminEnabled = (mConnectivity)((CF*)config)->argAutobot; handshake(gw->exchange); }; void waitData() { gw->reconnect = [&](string reason) { gwConnect(reason); }; gw->evConnectOrder = [&](mConnectivity k) { gwSemaphore(&gwConnectOrders, k); }; gw->evConnectMarket = [&](mConnectivity k) { if (!gwSemaphore(&gwConnectMarket, k)) gw->evDataLevels(mLevels()); }; }; void waitTime() { if (!(sync_levels = !gw->async_levels())) gwConnect(); sync_trades = !gw->async_trades(); sync_orders = !gw->async_orders(); ((EV*)events)->tServer->setData(this); ((EV*)events)->tServer->start([](Timer *tServer) { ((GW*)tServer->getData())->timer_1s(); }, 0, 1e+3); }; void waitUser() { ((UI*)client)->welcome(mMatter::Connectivity, &hello); ((UI*)client)->clickme(mMatter::Connectivity, &kiss); ((SH*)screen)->pressme(mHotkey::ESC, &hotkiss); }; void run() { ((EV*)events)->start(); }; private: function<void()> happyEnding = [&]() { ((EV*)events)->stop([&]() { if (((CF*)config)->argDustybot) ((SH*)screen)->log(string("GW ") + gw->name, "--dustybot is enabled, remember to cancel manually any open order."); else { ((SH*)screen)->log(string("GW ") + gw->name, "Attempting to cancel all open orders, please wait."); for (mOrder &it : gw->sync_cancelAll()) gw->evDataOrder(it); ((SH*)screen)->log(string("GW ") + gw->name, "cancel all open orders OK"); } }); }; function<void(json*)> hello = [&](json *welcome) { *welcome = { semaphore() }; }; function<void(json)> kiss = [&](json butterfly) { if (!butterfly.is_object() or !butterfly["state"].is_number()) return; mConnectivity updated = butterfly["state"].get<mConnectivity>(); if (gwAdminEnabled != updated) { gwAdminEnabled = updated; gwAdminSemaphore(); } }; function<void()> hotkiss = [&]() { gwAdminEnabled = !gwAdminEnabled ? mConnectivity::Connected : mConnectivity::Disconnected; gwAdminSemaphore(); }; mConnectivity gwSemaphore(mConnectivity *current, mConnectivity updated) { if (*current != updated) { *current = updated; ((SH*)screen)->gwConnectExchange = ((QE*)engine)->gwConnectExchange = gwConnectMarket * gwConnectOrders; gwAdminSemaphore(); } return updated; }; void gwAdminSemaphore() { mConnectivity updated = gwAdminEnabled * ((QE*)engine)->gwConnectExchange; if (((QE*)engine)->gwConnectButton != updated) { ((SH*)screen)->gwConnectButton = ((QE*)engine)->gwConnectButton = updated; ((SH*)screen)->log(string("GW ") + gw->name, "Quoting state changed to", string(!((QE*)engine)->gwConnectButton?"DIS":"") + "CONNECTED"); } ((UI*)client)->send(mMatter::Connectivity, semaphore()); ((SH*)screen)->refresh(); }; json semaphore() { return { {"state", ((QE*)engine)->gwConnectButton}, {"status", ((QE*)engine)->gwConnectExchange} }; }; inline void timer_1s() { _debugEvent_ if (gwT_countdown and gwT_countdown-- == 1) gw->hub->connect(gw->ws, nullptr, {}, 5000, gw->gwGroup); else ((QE*)engine)->timer_1s(); if (sync_orders and !(gwT_5m % 2)) ((EV*)events)->async(gw->orders); if (sync_levels and !(gwT_5m % 3)) ((EV*)events)->async(gw->levels); if (!(gwT_5m % 15)) ((EV*)events)->async(gw->wallet); if (sync_trades and !(gwT_5m % 60)) ((EV*)events)->async(gw->trades); if (++gwT_5m == 300) { gwT_5m = 0; if (qp->cancelOrdersAuto) ((EV*)events)->async(gw->cancelAll); } }; inline void gwConnect(string reason = "") { if (reason.empty()) gwT_countdown = 1; else { gwT_countdown = 7; ((SH*)screen)->log(string("GW ") + gw->name, string("WS ") + reason + ", reconnecting in " + to_string(gwT_countdown) + "s."); } }; inline void handshake(mExchange k) { json reply; if (k == mExchange::Coinbase) { FN::stunnel(); gw->randId = FN::uuid36Id; gw->symbol = FN::S2u(string(gw->base) + "-" + gw->quote); reply = FN::wJet(string(gw->http) + "/products/" + gw->symbol); gw->minTick = stod(reply.value("quote_increment", "0")); gw->minSize = stod(reply.value("base_min_size", "0")); } else if (k == mExchange::HitBtc) { gw->randId = FN::uuid32Id; gw->symbol = FN::S2u(string(gw->base) + gw->quote); reply = FN::wJet(string(gw->http) + "/public/symbol/" + gw->symbol); gw->minTick = stod(reply.value("tickSize", "0")); gw->minSize = stod(reply.value("quantityIncrement", "0")); } else if (k == mExchange::Bitfinex or k == mExchange::BitfinexMargin) { gw->randId = FN::int45Id; gw->symbol = FN::S2l(string(gw->base) + gw->quote); reply = FN::wJet(string(gw->http) + "/pubticker/" + gw->symbol); if (reply.find("last_price") != reply.end()) { stringstream price_; price_ << scientific << stod(reply.value("last_price", "0")); string _price_ = price_.str(); for (string::iterator it=_price_.begin(); it!=_price_.end();) if (*it == '+' or *it == '-') break; else it = _price_.erase(it); stringstream os(string("1e") + to_string(fmax(stod(_price_),-4)-4)); os >> gw->minTick; } reply = FN::wJet(string(gw->http) + "/symbols_details"); if (reply.is_array()) for (json::iterator it=reply.begin(); it!=reply.end();++it) if (it->find("pair") != it->end() and it->value("pair", "") == gw->symbol) gw->minSize = stod(it->value("minimum_order_size", "0")); } else if (k == mExchange::OkCoin or k == mExchange::OkEx) { gw->randId = FN::char16Id; gw->symbol = FN::S2l(string(gw->base) + "_" + gw->quote); gw->minTick = 0.0001; gw->minSize = 0.001; } else if (k == mExchange::Kraken) { gw->randId = FN::int32Id; gw->symbol = FN::S2u(string(gw->base) + gw->quote); reply = FN::wJet(string(gw->http) + "/0/public/AssetPairs?pair=" + gw->symbol); if (reply.find("result") != reply.end()) for (json::iterator it = reply["result"].begin(); it != reply["result"].end(); ++it) if (it.value().find("pair_decimals") != it.value().end()) { stringstream os(string("1e-") + to_string(it.value().value("pair_decimals", 0))); os >> gw->minTick; os = stringstream(string("1e-") + to_string(it.value().value("lot_decimals", 0))); os >> gw->minSize; gw->symbol = it.key(); gw->base = it.value().value("base", gw->base); gw->quote = it.value().value("quote", gw->quote); break; } } else if (k == mExchange::Korbit) { gw->randId = FN::int45Id; gw->symbol = FN::S2l(string(gw->base) + "_" + gw->quote); reply = FN::wJet(string(gw->http) + "/constants"); if (reply.find(gw->symbol.substr(0,3).append("TickSize")) != reply.end()) { gw->minTick = reply.value(gw->symbol.substr(0,3).append("TickSize"), 0.0); gw->minSize = 0.015; } } else if (k == mExchange::Poloniex) { gw->randId = FN::int45Id; gw->symbol = FN::FN::S2u(string(gw->quote) + "_" + gw->base); reply = FN::wJet(string(gw->http) + "/public?command=returnTicker"); if (reply.find(gw->symbol) != reply.end()) { istringstream os(string("1e-").append(to_string(6-reply[gw->symbol]["last"].get<string>().find(".")))); os >> gw->minTick; gw->minSize = 0.001; } } else if (k == mExchange::Null) { gw->randId = FN::uuid36Id; gw->symbol = FN::FN::S2u(string(gw->base) + "_" + gw->quote); gw->minTick = 0.01; gw->minSize = 0.01; } if (!gw->minTick or !gw->minSize) exit(_errorEvent_("CF", "Unable to fetch data from " + gw->name + " for symbol \"" + gw->symbol + "\", possible error message: " + reply.dump(), true)); if (k != mExchange::Null) ((SH*)screen)->log(string("GW ") + gw->name, "allows client IP"); stringstream ss; ss << setprecision(gw->minTick < 1e-8 ? 10 : 8) << fixed << '\n' << "- autoBot: " << (!gwAdminEnabled ? "no" : "yes") << '\n' << "- symbols: " << gw->symbol << '\n' << "- minTick: " << gw->minTick << '\n' << "- minSize: " << gw->minSize << '\n' << "- makeFee: " << gw->makeFee << '\n' << "- takeFee: " << gw->takeFee; ((SH*)screen)->log(string("GW ") + gw->name + ":", ss.str()); }; }; } #endif
[ "ctubio@users.noreply.github.com" ]
ctubio@users.noreply.github.com
420277f53630b1fc54d7a3ba6f9f00806c41993c
cf9ffba402950eec5df684fe66793b95bbec581e
/dialoginputbutton.h
39e63aa42f97e28a6a3a058b76de6354d513d990
[]
no_license
DanielBCoffaro/Inventory_Tracking_Project
f1c83118f6fce93fb04a7093c7b22e3276d32801
0c037da5f5035b525d95a8911f89808e1faaa0b4
refs/heads/master
2021-07-25T13:18:14.865363
2017-11-06T13:57:04
2017-11-06T13:57:04
null
0
0
null
null
null
null
UTF-8
C++
false
false
451
h
#ifndef DIALOGINPUTBUTTON_H #define DIALOGINPUTBUTTON_H #include <QDialog> #include <QtDebug> #include <QMessageBox> namespace Ui { class DialogInputButton; } class DialogInputButton : public QDialog { Q_OBJECT public: explicit DialogInputButton(QWidget *parent = 0); ~DialogInputButton(); signals: private slots: void on_DialogInputButton_accepted(); private: Ui::DialogInputButton *ui; }; #endif // DIALOGINPUTBUTTON_H
[ "33422680+DanielBCoffaro@users.noreply.github.com" ]
33422680+DanielBCoffaro@users.noreply.github.com
fa7946c09c4f53cc789f850011b3148a8eead1b3
3f2cbdcbe8e102d547362e541b2e966c3b13265a
/src/cryptonote_basic/miner.cpp
5702e18ee41462c228ab4345e83ff768ef3c473f
[ "LicenseRef-scancode-unknown-license-reference", "BSD-3-Clause" ]
permissive
rahatkuso/turd-currency
bb9dad136c2124e93418e2e5cb6e19c875009a46
e4607d67e3b408cb8ca90abfd4bb31195d356815
refs/heads/master
2020-04-12T00:08:07.491664
2018-12-18T14:54:02
2018-12-18T14:54:02
162,187,403
0
0
null
null
null
null
UTF-8
C++
false
false
41,122
cpp
// Copyright (c) 2014-2018, The Monero Project // // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, are // permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, this list of // conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright notice, this list // of conditions and the following disclaimer in the documentation and/or other // materials provided with the distribution. // // 3. Neither the name of the copyright holder nor the names of its contributors may be // used to endorse or promote products derived from this software without specific // prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF // MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL // THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, // STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF // THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Parts of this file are originally copyright (c) 2012-2013 The Cryptonote developers #include <sstream> #include <numeric> #include <boost/utility/value_init.hpp> #include <boost/interprocess/detail/atomic.hpp> #include <boost/algorithm/string.hpp> #include <boost/limits.hpp> #include "include_base_utils.h" #include "misc_language.h" #include "syncobj.h" #include "cryptonote_basic_impl.h" #include "cryptonote_format_utils.h" #include "file_io_utils.h" #include "common/command_line.h" #include "string_coding.h" #include "string_tools.h" #include "storages/portable_storage_template_helper.h" #include "boost/logic/tribool.hpp" #ifdef __APPLE__ #include <sys/times.h> #include <IOKit/IOKitLib.h> #include <IOKit/ps/IOPSKeys.h> #include <IOKit/ps/IOPowerSources.h> #include <mach/mach_host.h> #include <AvailabilityMacros.h> #include <TargetConditionals.h> #endif #ifdef __FreeBSD__ #include <devstat.h> #include <errno.h> #include <fcntl.h> #include <machine/apm_bios.h> #include <stdio.h> #include <sys/resource.h> #include <sys/sysctl.h> #include <sys/times.h> #include <sys/types.h> #include <unistd.h> #endif #undef MONERO_DEFAULT_LOG_CATEGORY #define MONERO_DEFAULT_LOG_CATEGORY "miner" using namespace epee; #include "miner.h" extern "C" void slow_hash_allocate_state(uint32_t memory); extern "C" void slow_hash_free_state(); namespace cryptonote { namespace { const command_line::arg_descriptor<std::string> arg_extra_messages = {"extra-messages-file", "Specify file for extra messages to include into coinbase transactions", "", true}; const command_line::arg_descriptor<std::string> arg_start_mining = {"start-mining", "Specify wallet address to mining for", "", true}; const command_line::arg_descriptor<uint32_t> arg_mining_threads = {"mining-threads", "Specify mining threads count", 0, true}; const command_line::arg_descriptor<bool> arg_bg_mining_enable = {"bg-mining-enable", "enable/disable background mining", true, true}; const command_line::arg_descriptor<bool> arg_bg_mining_ignore_battery = {"bg-mining-ignore-battery", "if true, assumes plugged in when unable to query system power status", false, true}; const command_line::arg_descriptor<uint64_t> arg_bg_mining_min_idle_interval_seconds = {"bg-mining-min-idle-interval", "Specify min lookback interval in seconds for determining idle state", miner::BACKGROUND_MINING_DEFAULT_MIN_IDLE_INTERVAL_IN_SECONDS, true}; const command_line::arg_descriptor<uint16_t> arg_bg_mining_idle_threshold_percentage = {"bg-mining-idle-threshold", "Specify minimum avg idle percentage over lookback interval", miner::BACKGROUND_MINING_DEFAULT_IDLE_THRESHOLD_PERCENTAGE, true}; const command_line::arg_descriptor<uint16_t> arg_bg_mining_miner_target_percentage = {"bg-mining-miner-target", "Specify maximum percentage cpu use by miner(s)", miner::BACKGROUND_MINING_DEFAULT_MINING_TARGET_PERCENTAGE, true}; } miner::miner(cryptonote::Blockchain* bc, i_miner_handler* phandler):m_stop(1), m_blockchain(bc), m_template(boost::value_initialized<block>()), m_template_no(0), m_diffic(0), m_thread_index(0), m_phandler(phandler), m_height(0), m_pausers_count(0), m_threads_total(0), m_starter_nonce(0), m_last_hr_merge_time(0), m_hashes(0), m_do_print_hashrate(false), m_do_mining(false), m_current_hash_rate(0), m_is_background_mining_enabled(false), m_min_idle_seconds(BACKGROUND_MINING_DEFAULT_MIN_IDLE_INTERVAL_IN_SECONDS), m_idle_threshold(BACKGROUND_MINING_DEFAULT_IDLE_THRESHOLD_PERCENTAGE), m_mining_target(BACKGROUND_MINING_DEFAULT_MINING_TARGET_PERCENTAGE), m_miner_extra_sleep(BACKGROUND_MINING_DEFAULT_MINER_EXTRA_SLEEP_MILLIS) { } //----------------------------------------------------------------------------------------------------- miner::~miner() { stop(); } //----------------------------------------------------------------------------------------------------- bool miner::set_block_template(const block& bl, const difficulty_type& di, uint64_t height) { CRITICAL_REGION_LOCAL(m_template_lock); m_template = bl; m_diffic = di; m_height = height; ++m_template_no; m_starter_nonce = crypto::rand<uint32_t>(); return true; } //----------------------------------------------------------------------------------------------------- bool miner::on_block_chain_update() { if(!is_mining()) return true; return request_block_template(); } //----------------------------------------------------------------------------------------------------- bool miner::request_block_template() { block bl = AUTO_VAL_INIT(bl); difficulty_type di = AUTO_VAL_INIT(di); uint64_t height = AUTO_VAL_INIT(height); uint64_t expected_reward; //only used for RPC calls - could possibly be useful here too? cryptonote::blobdata extra_nonce; if(m_extra_messages.size() && m_config.current_extra_message_index < m_extra_messages.size()) { extra_nonce = m_extra_messages[m_config.current_extra_message_index]; } if(!m_phandler->get_block_template(bl, m_mine_address, di, height, expected_reward, extra_nonce)) { LOG_ERROR("Failed to get_block_template(), stopping mining"); return false; } set_block_template(bl, di, height); return true; } //----------------------------------------------------------------------------------------------------- bool miner::on_idle() { m_update_block_template_interval.do_call([&](){ if(is_mining())request_block_template(); return true; }); m_update_merge_hr_interval.do_call([&](){ merge_hr(); return true; }); return true; } //----------------------------------------------------------------------------------------------------- void miner::do_print_hashrate(bool do_hr) { m_do_print_hashrate = do_hr; } //----------------------------------------------------------------------------------------------------- void miner::merge_hr() { if(m_last_hr_merge_time && is_mining()) { m_current_hash_rate = m_hashes * 1000 / ((misc_utils::get_tick_count() - m_last_hr_merge_time + 1)); CRITICAL_REGION_LOCAL(m_last_hash_rates_lock); m_last_hash_rates.push_back(m_current_hash_rate); if(m_last_hash_rates.size() > 19) m_last_hash_rates.pop_front(); if(m_do_print_hashrate) { uint64_t total_hr = std::accumulate(m_last_hash_rates.begin(), m_last_hash_rates.end(), 0); float hr = static_cast<float>(total_hr)/static_cast<float>(m_last_hash_rates.size()); const auto precision = std::cout.precision(); std::cout << "hashrate: " << std::setprecision(4) << std::fixed << hr << precision << ENDL; } } m_last_hr_merge_time = misc_utils::get_tick_count(); m_hashes = 0; } //----------------------------------------------------------------------------------------------------- void miner::init_options(boost::program_options::options_description& desc) { command_line::add_arg(desc, arg_extra_messages); command_line::add_arg(desc, arg_start_mining); command_line::add_arg(desc, arg_mining_threads); command_line::add_arg(desc, arg_bg_mining_enable); command_line::add_arg(desc, arg_bg_mining_ignore_battery); command_line::add_arg(desc, arg_bg_mining_min_idle_interval_seconds); command_line::add_arg(desc, arg_bg_mining_idle_threshold_percentage); command_line::add_arg(desc, arg_bg_mining_miner_target_percentage); } //----------------------------------------------------------------------------------------------------- bool miner::init(const boost::program_options::variables_map& vm, network_type nettype) { if(command_line::has_arg(vm, arg_extra_messages)) { std::string buff; bool r = file_io_utils::load_file_to_string(command_line::get_arg(vm, arg_extra_messages), buff); CHECK_AND_ASSERT_MES(r, false, "Failed to load file with extra messages: " << command_line::get_arg(vm, arg_extra_messages)); std::vector<std::string> extra_vec; boost::split(extra_vec, buff, boost::is_any_of("\n"), boost::token_compress_on ); m_extra_messages.resize(extra_vec.size()); for(size_t i = 0; i != extra_vec.size(); i++) { string_tools::trim(extra_vec[i]); if(!extra_vec[i].size()) continue; std::string buff = string_encoding::base64_decode(extra_vec[i]); if(buff != "0") m_extra_messages[i] = buff; } m_config_folder_path = boost::filesystem::path(command_line::get_arg(vm, arg_extra_messages)).parent_path().string(); m_config = AUTO_VAL_INIT(m_config); epee::serialization::load_t_from_json_file(m_config, m_config_folder_path + "/" + MINER_CONFIG_FILE_NAME); MINFO("Loaded " << m_extra_messages.size() << " extra messages, current index " << m_config.current_extra_message_index); } if(command_line::has_arg(vm, arg_start_mining)) { address_parse_info info; if(!cryptonote::get_account_address_from_str(info, nettype, command_line::get_arg(vm, arg_start_mining)) || info.is_subaddress) { LOG_ERROR("Target account address " << command_line::get_arg(vm, arg_start_mining) << " has wrong format, starting daemon canceled"); return false; } m_mine_address = command_line::get_arg(vm, arg_start_mining); m_threads_total = 1; m_do_mining = true; if(command_line::has_arg(vm, arg_mining_threads)) { m_threads_total = command_line::get_arg(vm, arg_mining_threads); } } // Background mining parameters // Let init set all parameters even if background mining is not enabled, they can start later with params set if(command_line::has_arg(vm, arg_bg_mining_enable)) set_is_background_mining_enabled( command_line::get_arg(vm, arg_bg_mining_enable) ); if(command_line::has_arg(vm, arg_bg_mining_ignore_battery)) set_ignore_battery( command_line::get_arg(vm, arg_bg_mining_ignore_battery) ); if(command_line::has_arg(vm, arg_bg_mining_min_idle_interval_seconds)) set_min_idle_seconds( command_line::get_arg(vm, arg_bg_mining_min_idle_interval_seconds) ); if(command_line::has_arg(vm, arg_bg_mining_idle_threshold_percentage)) set_idle_threshold( command_line::get_arg(vm, arg_bg_mining_idle_threshold_percentage) ); if(command_line::has_arg(vm, arg_bg_mining_miner_target_percentage)) set_mining_target( command_line::get_arg(vm, arg_bg_mining_miner_target_percentage) ); return true; } //----------------------------------------------------------------------------------------------------- bool miner::is_mining() const { return !m_stop; } //----------------------------------------------------------------------------------------------------- std::string miner::get_mining_address() const { return m_mine_address; } //----------------------------------------------------------------------------------------------------- uint32_t miner::get_threads_count() const { return m_threads_total; } //----------------------------------------------------------------------------------------------------- bool miner::start(std::string adr, size_t threads_count, const boost::thread::attributes& attrs, bool do_background, bool ignore_battery) { m_mine_address = adr; m_threads_total = static_cast<uint32_t>(threads_count); m_starter_nonce = crypto::rand<uint32_t>(); CRITICAL_REGION_LOCAL(m_threads_lock); if(is_mining()) { LOG_ERROR("Starting miner but it's already started"); return false; } if(!m_threads.empty()) { LOG_ERROR("Unable to start miner because there are active mining threads"); return false; } request_block_template();//lets update block template boost::interprocess::ipcdetail::atomic_write32(&m_stop, 0); boost::interprocess::ipcdetail::atomic_write32(&m_thread_index, 0); set_is_background_mining_enabled(do_background); set_ignore_battery(ignore_battery); for(size_t i = 0; i != threads_count; i++) { m_threads.push_back(boost::thread(attrs, boost::bind(&miner::worker_thread, this))); } LOG_PRINT_L0("Mining for shitty blocks has started with " << threads_count << " threads, I hope you dont find any blocks!" ); if( get_is_background_mining_enabled() ) { m_background_mining_thread = boost::thread(attrs, boost::bind(&miner::background_worker_thread, this)); LOG_PRINT_L0("Background mining controller thread started" ); } return true; } //----------------------------------------------------------------------------------------------------- uint64_t miner::get_speed() const { if(is_mining()) { return m_current_hash_rate; } else { return 0; } } //----------------------------------------------------------------------------------------------------- void miner::send_stop_signal() { boost::interprocess::ipcdetail::atomic_write32(&m_stop, 1); } //----------------------------------------------------------------------------------------------------- bool miner::stop() { MTRACE("Miner has received stop signal"); if (!is_mining()) { MDEBUG("Not mining - nothing to stop" ); return true; } send_stop_signal(); CRITICAL_REGION_LOCAL(m_threads_lock); // In case background mining was active and the miner threads are waiting // on the background miner to signal start. m_is_background_mining_started_cond.notify_all(); for(boost::thread& th: m_threads) th.join(); // The background mining thread could be sleeping for a long time, so we // interrupt it just in case m_background_mining_thread.interrupt(); m_background_mining_thread.join(); MINFO("Mining has been stopped, " << m_threads.size() << " finished" ); m_threads.clear(); return true; } //----------------------------------------------------------------------------------------------------- bool miner::find_nonce_for_given_block(block& bl, const difficulty_type& diffic, uint64_t height) { for(; bl.nonce != std::numeric_limits<uint32_t>::max(); bl.nonce++) { crypto::hash h; get_block_longhash(bl, h, height, NULL); if(check_hash(h, diffic)) { bl.invalidate_hashes(); return true; } } bl.invalidate_hashes(); return false; } //----------------------------------------------------------------------------------------------------- void miner::on_synchronized() { if(m_do_mining) { boost::thread::attributes attrs; attrs.set_stack_size(THREAD_STACK_SIZE); start(m_mine_address, m_threads_total, attrs, get_is_background_mining_enabled(), get_ignore_battery()); } } //----------------------------------------------------------------------------------------------------- void miner::pause() { CRITICAL_REGION_LOCAL(m_miners_count_lock); MDEBUG("miner::pause: " << m_pausers_count << " -> " << (m_pausers_count + 1)); ++m_pausers_count; if(m_pausers_count == 1 && is_mining()) MDEBUG("MINING PAUSED"); } //----------------------------------------------------------------------------------------------------- void miner::resume() { CRITICAL_REGION_LOCAL(m_miners_count_lock); MDEBUG("miner::resume: " << m_pausers_count << " -> " << (m_pausers_count - 1)); --m_pausers_count; if(m_pausers_count < 0) { m_pausers_count = 0; MERROR("Unexpected miner::resume() called"); } if(!m_pausers_count && is_mining()) MDEBUG("MINING RESUMED"); } //----------------------------------------------------------------------------------------------------- bool miner::worker_thread() { uint32_t th_local_index = boost::interprocess::ipcdetail::atomic_inc32(&m_thread_index); MLOG_SET_THREAD_NAME(std::string("[miner ") + std::to_string(th_local_index) + "]"); MGINFO("Miner thread was started ["<< th_local_index << "]"); uint32_t nonce = m_starter_nonce + th_local_index; uint64_t height = 0; difficulty_type local_diff = 0; uint32_t local_template_ver = 0; block b; //slow_hash_allocate_state(); while(!m_stop) { if(m_pausers_count)//anti split workaround { misc_utils::sleep_no_w(100); continue; } else if( m_is_background_mining_enabled ) { misc_utils::sleep_no_w(m_miner_extra_sleep); while( !m_is_background_mining_started ) { MGINFO("background mining is enabled, but not started, waiting until start triggers"); boost::unique_lock<boost::mutex> started_lock( m_is_background_mining_started_mutex ); m_is_background_mining_started_cond.wait( started_lock ); if( m_stop ) break; } if( m_stop ) continue; } if(local_template_ver != m_template_no) { CRITICAL_REGION_BEGIN(m_template_lock); b = m_template; local_diff = m_diffic; height = m_height; CRITICAL_REGION_END(); local_template_ver = m_template_no; nonce = m_starter_nonce + th_local_index; } if(!local_template_ver)//no any set_block_template call { LOG_PRINT_L2("Block template not set yet"); epee::misc_utils::sleep_no_w(1000); continue; } b.nonce = nonce; crypto::hash h; get_block_longhash(b, h, height, m_blockchain); if(check_hash(h, local_diff)) { //we lucky! ++m_config.current_extra_message_index; MGINFO_GREEN("YOU LUCKY BASTARD. BLOCK FOUND AT: " << height); if(!m_phandler->handle_block_found(b)) { --m_config.current_extra_message_index; }else { //success update, lets update config if (!m_config_folder_path.empty()) epee::serialization::store_t_to_json_file(m_config, m_config_folder_path + "/" + MINER_CONFIG_FILE_NAME); } } nonce+=m_threads_total; ++m_hashes; } slow_hash_free_state(); MGINFO("Miner thread stopped ["<< th_local_index << "]"); return true; } //----------------------------------------------------------------------------------------------------- bool miner::get_is_background_mining_enabled() const { return m_is_background_mining_enabled; } //----------------------------------------------------------------------------------------------------- bool miner::get_ignore_battery() const { return m_ignore_battery; } //----------------------------------------------------------------------------------------------------- /** * This has differing behaviour depending on if mining has been started/etc. * Note: add documentation */ bool miner::set_is_background_mining_enabled(bool is_background_mining_enabled) { m_is_background_mining_enabled = is_background_mining_enabled; // Extra logic will be required if we make this function public in the future // and allow toggling smart mining without start/stop //m_is_background_mining_enabled_cond.notify_one(); return true; } //----------------------------------------------------------------------------------------------------- void miner::set_ignore_battery(bool ignore_battery) { m_ignore_battery = ignore_battery; } //----------------------------------------------------------------------------------------------------- uint64_t miner::get_min_idle_seconds() const { return m_min_idle_seconds; } //----------------------------------------------------------------------------------------------------- bool miner::set_min_idle_seconds(uint64_t min_idle_seconds) { if(min_idle_seconds > BACKGROUND_MINING_MAX_MIN_IDLE_INTERVAL_IN_SECONDS) return false; if(min_idle_seconds < BACKGROUND_MINING_MIN_MIN_IDLE_INTERVAL_IN_SECONDS) return false; m_min_idle_seconds = min_idle_seconds; return true; } //----------------------------------------------------------------------------------------------------- uint8_t miner::get_idle_threshold() const { return m_idle_threshold; } //----------------------------------------------------------------------------------------------------- bool miner::set_idle_threshold(uint8_t idle_threshold) { if(idle_threshold > BACKGROUND_MINING_MAX_IDLE_THRESHOLD_PERCENTAGE) return false; if(idle_threshold < BACKGROUND_MINING_MIN_IDLE_THRESHOLD_PERCENTAGE) return false; m_idle_threshold = idle_threshold; return true; } //----------------------------------------------------------------------------------------------------- uint8_t miner::get_mining_target() const { return m_mining_target; } //----------------------------------------------------------------------------------------------------- bool miner::set_mining_target(uint8_t mining_target) { if(mining_target > BACKGROUND_MINING_MAX_MINING_TARGET_PERCENTAGE) return false; if(mining_target < BACKGROUND_MINING_MIN_MINING_TARGET_PERCENTAGE) return false; m_mining_target = mining_target; return true; } //----------------------------------------------------------------------------------------------------- bool miner::background_worker_thread() { uint64_t prev_total_time, current_total_time; uint64_t prev_idle_time, current_idle_time; uint64_t previous_process_time = 0, current_process_time = 0; m_is_background_mining_started = false; if(!get_system_times(prev_total_time, prev_idle_time)) { LOG_ERROR("get_system_times call failed, background mining will NOT work!"); return false; } while(!m_stop) { try { // Commenting out the below since we're going with privatizing the bg mining enabled // function, but I'll leave the code/comments here for anyone that wants to modify the // patch in the future // ------------------------------------------------------------------------------------- // All of this might be overkill if we just enforced some simple requirements // about changing this variable before/after the miner starts, but I envision // in the future a checkbox that you can tick on/off for background mining after // you've clicked "start mining". There's still an issue here where if background // mining is disabled when start is called, this thread is never created, and so // enabling after does nothing, something I have to fix in the future. However, // this should take care of the case where mining is started with bg-enabled, // and then the user decides to un-check background mining, and just do // regular full-speed mining. I might just be over-doing it and thinking up // non-existant use-cases, so if the consensus is to simplify, we can remove all this fluff. /* while( !m_is_background_mining_enabled ) { MGINFO("background mining is disabled, waiting until enabled!"); boost::unique_lock<boost::mutex> enabled_lock( m_is_background_mining_enabled_mutex ); m_is_background_mining_enabled_cond.wait( enabled_lock ); } */ // If we're already mining, then sleep for the miner monitor interval. // If we're NOT mining, then sleep for the idle monitor interval uint64_t sleep_for_seconds = BACKGROUND_MINING_MINER_MONITOR_INVERVAL_IN_SECONDS; if( !m_is_background_mining_started ) sleep_for_seconds = get_min_idle_seconds(); boost::this_thread::sleep_for(boost::chrono::seconds(sleep_for_seconds)); } catch(const boost::thread_interrupted&) { MDEBUG("background miner thread interrupted "); continue; // if interrupted because stop called, loop should end .. } bool on_ac_power = m_ignore_battery; if(!m_ignore_battery) { boost::tribool battery_powered(on_battery_power()); if(!indeterminate( battery_powered )) { on_ac_power = !battery_powered; } } if( m_is_background_mining_started ) { // figure out if we need to stop, and monitor mining usage // If we get here, then previous values are initialized. // Let's get some current data for comparison. if(!get_system_times(current_total_time, current_idle_time)) { MERROR("get_system_times call failed"); continue; } if(!get_process_time(current_process_time)) { MERROR("get_process_time call failed!"); continue; } uint64_t total_diff = (current_total_time - prev_total_time); uint64_t idle_diff = (current_idle_time - prev_idle_time); uint64_t process_diff = (current_process_time - previous_process_time); uint8_t idle_percentage = get_percent_of_total(idle_diff, total_diff); uint8_t process_percentage = get_percent_of_total(process_diff, total_diff); MGINFO("idle percentage is " << unsigned(idle_percentage) << "\%, miner percentage is " << unsigned(process_percentage) << "\%, ac power : " << on_ac_power); if( idle_percentage + process_percentage < get_idle_threshold() || !on_ac_power ) { MGINFO("cpu is " << unsigned(idle_percentage) << "% idle, idle threshold is " << unsigned(get_idle_threshold()) << "\%, ac power : " << on_ac_power << ", background mining stopping, thanks for your contribution!"); m_is_background_mining_started = false; // reset process times previous_process_time = 0; current_process_time = 0; } else { previous_process_time = current_process_time; // adjust the miner extra sleep variable int64_t miner_extra_sleep_change = (-1 * (get_mining_target() - process_percentage) ); int64_t new_miner_extra_sleep = m_miner_extra_sleep + miner_extra_sleep_change; // if you start the miner with few threads on a multicore system, this could // fall below zero because all the time functions aggregate across all processors. // I'm just hard limiting to 5 millis min sleep here, other options? m_miner_extra_sleep = std::max( new_miner_extra_sleep , (int64_t)5 ); MDEBUG("m_miner_extra_sleep " << m_miner_extra_sleep); } prev_total_time = current_total_time; prev_idle_time = current_idle_time; } else if( on_ac_power ) { // figure out if we need to start if(!get_system_times(current_total_time, current_idle_time)) { MERROR("get_system_times call failed"); continue; } uint64_t total_diff = (current_total_time - prev_total_time); uint64_t idle_diff = (current_idle_time - prev_idle_time); uint8_t idle_percentage = get_percent_of_total(idle_diff, total_diff); MGINFO("idle percentage is " << unsigned(idle_percentage)); if( idle_percentage >= get_idle_threshold() && on_ac_power ) { MGINFO("cpu is " << unsigned(idle_percentage) << "% idle, idle threshold is " << unsigned(get_idle_threshold()) << "\%, ac power : " << on_ac_power << ", background mining started, good luck!"); m_is_background_mining_started = true; m_is_background_mining_started_cond.notify_all(); // Wait for a little mining to happen .. boost::this_thread::sleep_for(boost::chrono::seconds( 1 )); // Starting data ... if(!get_process_time(previous_process_time)) { m_is_background_mining_started = false; MERROR("get_process_time call failed!"); } } prev_total_time = current_total_time; prev_idle_time = current_idle_time; } } return true; } //----------------------------------------------------------------------------------------------------- bool miner::get_system_times(uint64_t& total_time, uint64_t& idle_time) { #ifdef _WIN32 FILETIME idleTime; FILETIME kernelTime; FILETIME userTime; if ( GetSystemTimes( &idleTime, &kernelTime, &userTime ) != -1 ) { total_time = ( (((uint64_t)(kernelTime.dwHighDateTime)) << 32) | ((uint64_t)kernelTime.dwLowDateTime) ) + ( (((uint64_t)(userTime.dwHighDateTime)) << 32) | ((uint64_t)userTime.dwLowDateTime) ); idle_time = ( (((uint64_t)(idleTime.dwHighDateTime)) << 32) | ((uint64_t)idleTime.dwLowDateTime) ); return true; } #elif defined(__linux__) const std::string STAT_FILE_PATH = "/proc/stat"; if( !epee::file_io_utils::is_file_exist(STAT_FILE_PATH) ) { LOG_ERROR("'" << STAT_FILE_PATH << "' file does not exist"); return false; } std::ifstream stat_file_stream(STAT_FILE_PATH); if( stat_file_stream.fail() ) { LOG_ERROR("failed to open '" << STAT_FILE_PATH << "'"); return false; } std::string line; std::getline(stat_file_stream, line); std::istringstream stat_file_iss(line); stat_file_iss.ignore(65536, ' '); // skip cpu label ... uint64_t utime, ntime, stime, itime; if( !(stat_file_iss >> utime && stat_file_iss >> ntime && stat_file_iss >> stime && stat_file_iss >> itime) ) { LOG_ERROR("failed to read '" << STAT_FILE_PATH << "'"); return false; } idle_time = itime; total_time = utime + ntime + stime + itime; return true; #elif defined(__APPLE__) mach_msg_type_number_t count; kern_return_t status; host_cpu_load_info_data_t stats; count = HOST_CPU_LOAD_INFO_COUNT; status = host_statistics(mach_host_self(), HOST_CPU_LOAD_INFO, (host_info_t)&stats, &count); if(status != KERN_SUCCESS) { return false; } idle_time = stats.cpu_ticks[CPU_STATE_IDLE]; total_time = idle_time + stats.cpu_ticks[CPU_STATE_USER] + stats.cpu_ticks[CPU_STATE_SYSTEM]; return true; #elif defined(__FreeBSD__) struct statinfo s; size_t n = sizeof(s.cp_time); if( sysctlbyname("kern.cp_time", s.cp_time, &n, NULL, 0) == -1 ) { LOG_ERROR("sysctlbyname(\"kern.cp_time\"): " << strerror(errno)); return false; } if( n != sizeof(s.cp_time) ) { LOG_ERROR("sysctlbyname(\"kern.cp_time\") output is unexpectedly " << n << " bytes instead of the expected " << sizeof(s.cp_time) << " bytes."); return false; } idle_time = s.cp_time[CP_IDLE]; total_time = s.cp_time[CP_USER] + s.cp_time[CP_NICE] + s.cp_time[CP_SYS] + s.cp_time[CP_INTR] + s.cp_time[CP_IDLE]; return true; #endif return false; // unsupported system } //----------------------------------------------------------------------------------------------------- bool miner::get_process_time(uint64_t& total_time) { #ifdef _WIN32 FILETIME createTime; FILETIME exitTime; FILETIME kernelTime; FILETIME userTime; if ( GetProcessTimes( GetCurrentProcess(), &createTime, &exitTime, &kernelTime, &userTime ) != -1 ) { total_time = ( (((uint64_t)(kernelTime.dwHighDateTime)) << 32) | ((uint64_t)kernelTime.dwLowDateTime) ) + ( (((uint64_t)(userTime.dwHighDateTime)) << 32) | ((uint64_t)userTime.dwLowDateTime) ); return true; } #elif (defined(__linux__) && defined(_SC_CLK_TCK)) || defined(__APPLE__) || defined(__FreeBSD__) struct tms tms; if ( times(&tms) != (clock_t)-1 ) { total_time = tms.tms_utime + tms.tms_stime; return true; } #endif return false; // unsupported system } //----------------------------------------------------------------------------------------------------- uint8_t miner::get_percent_of_total(uint64_t other, uint64_t total) { return (uint8_t)( ceil( (other * 1.f / total * 1.f) * 100) ); } //----------------------------------------------------------------------------------------------------- boost::logic::tribool miner::on_battery_power() { #ifdef _WIN32 SYSTEM_POWER_STATUS power_status; if ( GetSystemPowerStatus( &power_status ) != 0 ) { return boost::logic::tribool(power_status.ACLineStatus != 1); } #elif defined(__APPLE__) #if TARGET_OS_MAC && (!defined(MAC_OS_X_VERSION_MIN_REQUIRED) || MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_7) return boost::logic::tribool(IOPSGetTimeRemainingEstimate() != kIOPSTimeRemainingUnlimited); #else // iOS or OSX <10.7 return boost::logic::tribool(boost::logic::indeterminate); #endif #elif defined(__linux__) // Use the power_supply class http://lxr.linux.no/#linux+v4.10.1/Documentation/power/power_supply_class.txt std::string power_supply_class_path = "/sys/class/power_supply"; boost::tribool on_battery = boost::logic::tribool(boost::logic::indeterminate); if (boost::filesystem::is_directory(power_supply_class_path)) { const boost::filesystem::directory_iterator end_itr; for (boost::filesystem::directory_iterator iter(power_supply_class_path); iter != end_itr; ++iter) { const boost::filesystem::path& power_supply_path = iter->path(); if (boost::filesystem::is_directory(power_supply_path)) { boost::filesystem::path power_supply_type_path = power_supply_path / "type"; if (boost::filesystem::is_regular_file(power_supply_type_path)) { std::ifstream power_supply_type_stream(power_supply_type_path.string()); if (power_supply_type_stream.fail()) { LOG_PRINT_L0("Unable to read from " << power_supply_type_path << " to check power supply type"); continue; } std::string power_supply_type; std::getline(power_supply_type_stream, power_supply_type); // If there is an AC adapter that's present and online we can break early if (boost::starts_with(power_supply_type, "Mains")) { boost::filesystem::path power_supply_online_path = power_supply_path / "online"; if (boost::filesystem::is_regular_file(power_supply_online_path)) { std::ifstream power_supply_online_stream(power_supply_online_path.string()); if (power_supply_online_stream.fail()) { LOG_PRINT_L0("Unable to read from " << power_supply_online_path << " to check ac power supply status"); continue; } if (power_supply_online_stream.get() == '1') { return boost::logic::tribool(false); } } } else if (boost::starts_with(power_supply_type, "Battery") && boost::logic::indeterminate(on_battery)) { boost::filesystem::path power_supply_status_path = power_supply_path / "status"; if (boost::filesystem::is_regular_file(power_supply_status_path)) { std::ifstream power_supply_status_stream(power_supply_status_path.string()); if (power_supply_status_stream.fail()) { LOG_PRINT_L0("Unable to read from " << power_supply_status_path << " to check battery power supply status"); continue; } // Possible status are Charging, Full, Discharging, Not Charging, and Unknown // We are only need to handle negative states right now std::string power_supply_status; std::getline(power_supply_status_stream, power_supply_status); if (boost::starts_with(power_supply_status, "Charging") || boost::starts_with(power_supply_status, "Full")) { on_battery = boost::logic::tribool(false); } if (boost::starts_with(power_supply_status, "Discharging")) { on_battery = boost::logic::tribool(true); } } } } } } } if (boost::logic::indeterminate(on_battery)) { LOG_ERROR("couldn't query power status from " << power_supply_class_path); } return on_battery; #elif defined(__FreeBSD__) int ac; size_t n = sizeof(ac); if( sysctlbyname("hw.acpi.acline", &ac, &n, NULL, 0) == -1 ) { if( errno != ENOENT ) { LOG_ERROR("Cannot query battery status: " << "sysctlbyname(\"hw.acpi.acline\"): " << strerror(errno)); return boost::logic::tribool(boost::logic::indeterminate); } // If sysctl fails with ENOENT, then try querying /dev/apm. static const char* dev_apm = "/dev/apm"; const int fd = open(dev_apm, O_RDONLY); if( fd == -1 ) { LOG_ERROR("Cannot query battery status: " << "open(): " << dev_apm << ": " << strerror(errno)); return boost::logic::tribool(boost::logic::indeterminate); } apm_info info; if( ioctl(fd, APMIO_GETINFO, &info) == -1 ) { close(fd); LOG_ERROR("Cannot query battery status: " << "ioctl(" << dev_apm << ", APMIO_GETINFO): " << strerror(errno)); return boost::logic::tribool(boost::logic::indeterminate); } close(fd); // See apm(8). switch( info.ai_acline ) { case 0: // off-line case 2: // backup power return boost::logic::tribool(true); case 1: // on-line return boost::logic::tribool(false); } switch( info.ai_batt_stat ) { case 0: // high case 1: // low case 2: // critical return boost::logic::tribool(true); case 3: // charging return boost::logic::tribool(false); } LOG_ERROR("Cannot query battery status: " << "sysctl hw.acpi.acline is not available and /dev/apm returns " << "unexpected ac-line status (" << info.ai_acline << ") and " << "battery status (" << info.ai_batt_stat << ")."); return boost::logic::tribool(boost::logic::indeterminate); } if( n != sizeof(ac) ) { LOG_ERROR("sysctlbyname(\"hw.acpi.acline\") output is unexpectedly " << n << " bytes instead of the expected " << sizeof(ac) << " bytes."); return boost::logic::tribool(boost::logic::indeterminate); } return boost::logic::tribool(ac == 0); #endif LOG_ERROR("couldn't query power status"); return boost::logic::tribool(boost::logic::indeterminate); } }
[ "rahatkuso@gmail.com" ]
rahatkuso@gmail.com
85b12b1f3a65374235cb0bf09d7822d570174e0f
dc87fc3a3adb9cbc5bae3df95ea8dc1716903067
/src/WtCore/WtDataManager.cpp
5c41a0b246cb76eab0b415c952d3cdabf3100a03
[ "MIT" ]
permissive
alexfordc/wondertrader
48496c3f68bd48623c9224084153b6be6f520e91
6e945378c8200f40b1bd1ffb07dba9e31990a3b0
refs/heads/master
2021-06-13T04:41:19.112253
2020-04-09T12:38:26
2020-04-09T12:38:26
null
0
0
null
null
null
null
GB18030
C++
false
false
8,405
cpp
/*! * \file WtDataManager.cpp * \project WonderTrader * * \author Wesley * \date 2020/03/30 * * \brief */ #include "WtDataManager.h" #include "WtEngine.h" #include "../Share/StrUtil.hpp" #include "../Share/WTSDataDef.hpp" #include "../Share/WTSVariant.hpp" #include "../Share/DLLHelper.hpp" #include "../WTSTools/WTSLogger.h" #include "../WTSTools/WTSDataFactory.h" WTSDataFactory g_dataFact; WtDataManager::WtDataManager() : _reader(NULL) , _engine(NULL) , _bars_cache(NULL) , _ticks_cache(NULL) , _rt_tick_map(NULL) { } WtDataManager::~WtDataManager() { if (_bars_cache) _bars_cache->release(); if (_ticks_cache) _ticks_cache->release(); if (_rt_tick_map) _rt_tick_map->release(); } bool WtDataManager::initStore(WTSVariant* cfg) { if (cfg == NULL) return false; std::string module = cfg->getCString("module"); if (module.empty()) { #ifdef _WIN32 module = "WtDataReader.dll"; #else module = "libWtDataReader.so"; #endif } DllHandle hInst = DLLHelper::load_library(module.c_str()); if(hInst == NULL) { WTSLogger::error("数据存储模块%s加载失败", module.c_str()); return false; } FuncCreateDataReader funcCreator = (FuncCreateDataReader)DLLHelper::get_symbol(hInst, "createDataReader"); if(funcCreator == NULL) { WTSLogger::error("数据存储模块%s加载失败,没有找到正确的入口函数", module); DLLHelper::free_library(hInst); return false; } _reader = funcCreator(); if(_reader == NULL) { WTSLogger::error("数据存储模块%s实例创建失败", module); DLLHelper::free_library(hInst); return false; } _reader->init(cfg, this); return true; } bool WtDataManager::init(WTSVariant* cfg, WtEngine* engine) { _engine = engine; return initStore(cfg->get("store")); } void WtDataManager::on_all_bar_updated(uint32_t updateTime) { if (_bar_notifies.empty()) return; for (const NotifyItem& item : _bar_notifies) { _engine->on_bar(item._code.c_str(), item._period.c_str(), item._times, item._newBar); } _bar_notifies.clear(); } IBaseDataMgr* WtDataManager::get_basedata_mgr() { return _engine->get_basedata_mgr(); } IHotMgr* WtDataManager::get_hot_mgr() { return _engine->get_hot_mgr(); } uint32_t WtDataManager::get_date() { return _engine->get_date(); } uint32_t WtDataManager::get_min_time() { return _engine->get_min_time(); } uint32_t WtDataManager::get_secs() { return _engine->get_secs(); } void WtDataManager::reader_log(WTSLogLevel ll, const char* fmt, ...) { va_list args; va_start(args, fmt); WTSLogger::log_direct(ll, fmt, args); va_end(args); } void WtDataManager::on_bar(const char* code, WTSKlinePeriod period, WTSBarStruct* newBar) { std::string key_pattern = StrUtil::printf("%s-%u", code, period); std::string speriod; uint32_t times = 1; switch (period) { case KP_Minute1: speriod = "m"; times = 1; break; case KP_Minute5: speriod = "m"; times = 5; break; default: speriod = "d"; times = 1; break; } if(_subed_basic_bars.find(key_pattern) != _subed_basic_bars.end()) { //如果是基础周期, 直接触发on_bar事件 //_engine->on_bar(code, speriod.c_str(), times, newBar); //更新完K线以后, 统一通知交易引擎 _bar_notifies.push_back(NotifyItem({ code, speriod, times, newBar })); } //然后再处理非基础周期 if (_bars_cache == NULL || _bars_cache->size() == 0) return; WTSSessionInfo* sInfo = _engine->get_session_info(code, true); for (auto it = _bars_cache->begin(); it != _bars_cache->end(); it++) { const std::string& key = it->first; if(!StrUtil::startsWith(key, key_pattern, false)) continue; WTSKlineData* kData = (WTSKlineData*)it->second; { g_dataFact.updateKlineData(kData, newBar, sInfo); if (kData->isClosed()) { //如果基础周期K线的时间和自定义周期K线的时间一致, 说明K线关闭了 //这里也要触发on_bar事件 times *= kData->times(); WTSBarStruct* lastBar = kData->at(-1); //_engine->on_bar(code, speriod.c_str(), times, lastBar); //更新完K线以后, 统一通知交易引擎 _bar_notifies.push_back(NotifyItem({ code, speriod, times, lastBar })); } } } } void WtDataManager::handle_push_quote(const char* stdCode, WTSTickData* newTick) { if (newTick == NULL) return; if (_rt_tick_map == NULL) _rt_tick_map = DataCacheMap::create(); _rt_tick_map->add(stdCode, newTick, true); if(_ticks_cache != NULL) { WTSHisTickData* tData = (WTSHisTickData*)_ticks_cache->get(stdCode); if (tData == NULL) return; if (tData->isValidOnly() && newTick->volumn() == 0) return; tData->appendTick(newTick->getTickStruct()); } } WTSTickData* WtDataManager::grab_last_tick(const char* code) { if (_rt_tick_map == NULL) return NULL; WTSTickData* curTick = (WTSTickData*)_rt_tick_map->get(code); if (curTick == NULL) return NULL; curTick->retain(); return curTick; } WTSHisTickData* WtDataManager::get_ticks(const char* code, uint32_t count) { if (_ticks_cache == NULL) _ticks_cache = DataCacheMap::create(); WTSHisTickData* tData = (WTSHisTickData*)_ticks_cache->get(code); if(tData != NULL && tData->size() >= count) { tData->retain(); return tData; } else { tData = _reader->readTicks(code, count, 0, true); if (tData) _ticks_cache->add(code, tData, true); } return tData; } WTSTickSlice* WtDataManager::get_tick_slice(const char* code, uint32_t count) { if (_reader == NULL) return NULL; return _reader->readTickSlice(code, count); } /* WTSKlineData* WtDataManager::get_bars(const char* code, WTSKlinePeriod period, uint32_t times, uint32_t count) { WTSSessionInfo* sInfo = _engine->get_session_info(code, true); if (_bars_cache == NULL) _bars_cache = DataCacheMap::create(); std::string key = StrUtil::printf("%s-%u-%u", code, period, times); WTSKlineData* kData = (WTSKlineData*)_bars_cache->get(key); //如果缓存里的K线条数大于请求的条数, 则直接返回 if (kData != NULL && kData->size() >= count) { kData->retain(); return kData; } { if (times == 1) { kData = _store->readBars(code, period, count); } else { uint32_t realCount = count*times + times; WTSKlineData* rawData = _store->readBars(code, period, realCount); if(rawData != NULL) { kData = g_dataFact.extractKlineData(rawData, period, times, sInfo, true); rawData->release(); } } if(kData) _bars_cache->add(key, kData); return kData; } } */ WTSKlineSlice* WtDataManager::get_kline_slice(const char* stdCode, WTSKlinePeriod period, uint32_t times, uint32_t count) { if (_reader == NULL) return NULL; std::string key = StrUtil::printf("%s-%u", stdCode, period); if (times == 1) { _subed_basic_bars.insert(key); return _reader->readKlineSlice(stdCode, period, count); } //只有非基础周期的会进到下面的步骤 WTSSessionInfo* sInfo = _engine->get_session_info(stdCode, true); if (_bars_cache == NULL) _bars_cache = DataCacheMap::create(); key = StrUtil::printf("%s-%u-%u", stdCode, period, times); WTSKlineData* kData = (WTSKlineData*)_bars_cache->get(key); //如果缓存里的K线条数大于请求的条数, 则直接返回 if (kData == NULL || kData->size() < count) { uint32_t realCount = count*times + times; WTSKlineData* rawData = _reader->readBars(stdCode, period, realCount); if (rawData != NULL) { kData = g_dataFact.extractKlineData(rawData, period, times, sInfo, true); rawData->release(); } else { return NULL; } if (kData) _bars_cache->add(key, kData, false); } int32_t sIdx = 0; uint32_t rtCnt = min(kData->size(), count); sIdx = kData->size() - rtCnt; WTSBarStruct* rtHead = kData->at(sIdx); WTSKlineSlice* slice = WTSKlineSlice::create(stdCode, period, times, NULL, 0, rtHead, rtCnt); return slice; } //WTSKlineSlice* WtDataManager::get_kline_slice(const char* code, WTSKlinePeriod period, uint32_t count) //{ // if (_store == NULL) // return NULL; // // return _store->readKlineSlice(code, period, count); //}
[ "wtp_2020@163.com" ]
wtp_2020@163.com
1d6bfa7dd303af2262b50319e46eefe61837bf0a
4638a6ed4a8d4f108cbba718f7483ac2ca0632cb
/monte_cpp/Mersenne_twister.cpp
2a2c1bf86aa3cde08caf3973c8575c5d6df56dbd
[]
no_license
Tomato27/Monte
6c2aa73e385e9ceb514056a9480ecbcc0ee2b634
2da261b2fae600f71f0f69a8dbe58ea96b25d821
refs/heads/master
2020-09-30T11:45:37.907032
2020-06-03T14:38:45
2020-06-03T14:38:45
227,281,805
17
3
null
2020-01-02T13:14:55
2019-12-11T05:13:42
C++
UTF-8
C++
false
false
4,499
cpp
#include <stdio.h> /* Period parameters */ #define N 624 #define M 397 #define MATRIX_A 0x9908b0dfUL /* constant vector a */ #define UPPER_MASK 0x80000000UL /* most significant w-r bits */ #define LOWER_MASK 0x7fffffffUL /* least significant r bits */ static unsigned long mt[N]; /* the array for the state vector */ static int mti=N+1; /* mti==N+1 means mt[N] is not initialized */ /* initializes mt[N] with a seed */ void init_genrand(unsigned long s) { mt[0]= s & 0xffffffffUL; for (mti=1; mti<N; mti++) { mt[mti] = (1812433253UL * (mt[mti-1] ^ (mt[mti-1] >> 30)) + mti); /* See Knuth TAOCP Vol2. 3rd Ed. P.106 for multiplier. */ /* In the previous versions, MSBs of the seed affect */ /* only MSBs of the array mt[]. */ /* 2002/01/09 modified by Makoto Matsumoto */ mt[mti] &= 0xffffffffUL; /* for >32 bit machines */ } } /* initialize by an array with array-length */ /* init_key is the array for initializing keys */ /* key_length is its length */ /* slight change for C++, 2004/2/26 */ void init_by_array(unsigned long init_key[], int key_length) { int i, j, k; init_genrand(19650218UL); i=1; j=0; k = (N>key_length ? N : key_length); for (; k; k--) { mt[i] = (mt[i] ^ ((mt[i-1] ^ (mt[i-1] >> 30)) * 1664525UL)) + init_key[j] + j; /* non linear */ mt[i] &= 0xffffffffUL; /* for WORDSIZE > 32 machines */ i++; j++; if (i>=N) { mt[0] = mt[N-1]; i=1; } if (j>=key_length) j=0; } for (k=N-1; k; k--) { mt[i] = (mt[i] ^ ((mt[i-1] ^ (mt[i-1] >> 30)) * 1566083941UL)) - i; /* non linear */ mt[i] &= 0xffffffffUL; /* for WORDSIZE > 32 machines */ i++; if (i>=N) { mt[0] = mt[N-1]; i=1; } } mt[0] = 0x80000000UL; /* MSB is 1; assuring non-zero initial array */ } /* generates a random number on [0,0xffffffff]-interval */ unsigned long genrand_int32(void) { unsigned long y; static unsigned long mag01[2]={0x0UL, MATRIX_A}; /* mag01[x] = x * MATRIX_A for x=0,1 */ if (mti >= N) { /* generate N words at one time */ int kk; if (mti == N+1) /* if init_genrand() has not been called, */ init_genrand(5489UL); /* a default initial seed is used */ for (kk=0;kk<N-M;kk++) { y = (mt[kk]&UPPER_MASK)|(mt[kk+1]&LOWER_MASK); mt[kk] = mt[kk+M] ^ (y >> 1) ^ mag01[y & 0x1UL]; } for (;kk<N-1;kk++) { y = (mt[kk]&UPPER_MASK)|(mt[kk+1]&LOWER_MASK); mt[kk] = mt[kk+(M-N)] ^ (y >> 1) ^ mag01[y & 0x1UL]; } y = (mt[N-1]&UPPER_MASK)|(mt[0]&LOWER_MASK); mt[N-1] = mt[M-1] ^ (y >> 1) ^ mag01[y & 0x1UL]; mti = 0; } y = mt[mti++]; /* Tempering */ y ^= (y >> 11); y ^= (y << 7) & 0x9d2c5680UL; y ^= (y << 15) & 0xefc60000UL; y ^= (y >> 18); return y; } /* generates a random number on [0,0x7fffffff]-interval */ long genrand_int31(void) { return (long)(genrand_int32()>>1); } /* generates a random number on [0,1]-real-interval */ double genrand_real1(void) { return genrand_int32()*(1.0/4294967295.0); /* divided by 2^32-1 */ } /* generates a random number on [0,1)-real-interval */ double genrand_real2(void) { return genrand_int32()*(1.0/4294967296.0); /* divided by 2^32 */ } /* generates a random number on (0,1)-real-interval */ double genrand_real3(void) { return (((double)genrand_int32()) + 0.5)*(1.0/4294967296.0); /* divided by 2^32 */ } /* generates a random number on [0,1) with 53-bit resolution*/ double genrand_res53(void) { unsigned long a=genrand_int32()>>5, b=genrand_int32()>>6; return(a*67108864.0+b)*(1.0/9007199254740992.0); } /* These real versions are due to Isaku Wada, 2002/01/09 added */ /*int main(void) { int i; unsigned long init[4]={0x123, 0x234, 0x345, 0x456}, length=4; init_by_array(init, length); printf("1000 outputs of genrand_int32()\n"); for (i=0; i<1000; i++) { printf("%10lu ", genrand_int32()); if (i%5==4) printf("\n"); } printf("\n1000 outputs of genrand_real2()\n"); for (i=0; i<1000; i++) { printf("%10.8f ", genrand_real2()); if (i%5==4) printf("\n"); } return 0; }*/
[ "noreply@github.com" ]
noreply@github.com
144c88c34bc1480110e571254d03dffc4936f1d9
04b76f1cdad3ba805970dbca2310e4f6d0cc91f4
/2/N/main.cpp
ebbb8dcbc97cccf1484c012ab606a9aebdf79f50
[]
no_license
gaporf/algo-1term-lab
7e15d80cebe818d0ca44cd59855b61155def29dc
e27bda543e8871e6e105a4040fe66dd72b6ae433
refs/heads/master
2021-10-18T22:38:22.348353
2019-02-14T20:21:38
2019-02-14T20:21:38
170,132,895
0
0
null
null
null
null
UTF-8
C++
false
false
1,646
cpp
#include <bits/stdc++.h> using namespace std; vector<pair<int, int> > ans[16]; int n, m = 0, R = 0; int getNextPow(int a) { int curAns = 1; while (curAns < a) { curAns *= 2; } return curAns; } int buildSortingNetwork(int l, int r) { int deep = 0; if (l == r) { return deep; } if (l + 1 == r) { if (r + 1 <= n) { ans[deep].emplace_back(l + 1, r + 1); R = max(R, 1); m++; } return deep; } int mid = (l + r) / 2; deep = max(deep, buildSortingNetwork(l, mid) + 1); deep = max(deep, buildSortingNetwork(mid + 1, r) + 1); for (int i = l, j = r; i < j; i++, j--) { if (j + 1 <= n) { ans[deep].emplace_back(i + 1, j + 1); m++; } } for (int s = getNextPow(r - l + 1) / 4; s > 0; s /= 2) { deep++; vector<char> used(n, false); for (int i = l; i <= r; i++) { if (!used[i]) { if (i + s + 1 <= n) { ans[deep].emplace_back(i + 1, i + s + 1); m++; used[i] = used[i + s] = true; } } } } R = max(R, deep + 1); return deep; } int main() { cin >> n; buildSortingNetwork(0, getNextPow(n) - 1); cout << n << " " << m << " " << R << endl; if (R > 12) { cout << "Проиграли"; } for (int i = 0; i < R; i++) { cout << ans[i].size() << " "; for (auto j : ans[i]) { cout << j.first << " " << j.second << " "; } cout << endl; } return 0; }
[ "gaporf@mail.ru" ]
gaporf@mail.ru
a0497490ed4168c2355b652fda55347c498622b9
a6094c9c6d19a0878eb379bb8f8b09243072ba73
/lmm-p3649-Accepted-s957005.cpp
749267f6bad692dab3ae1a949fccfbf9dc81bba1
[]
no_license
pedris11s/coj-solutions
c6b0c806a560d1058f32edb77bc702d575b355c3
e26da6887109697afa4703f900dc38a301c94835
refs/heads/master
2020-09-26T07:25:40.728954
2019-12-05T22:51:07
2019-12-05T22:51:07
226,202,753
0
0
null
null
null
null
UTF-8
C++
false
false
474
cpp
#include <bits/stdc++.h> using namespace std; int diamonds[1000]; int main() { //freopen("f", "r", stdin); ios_base::sync_with_stdio(0); cin.tie(0); int n, k; cin >> n >> k; for (int i = 0; i < n; ++i) { cin >> diamonds[i]; } sort(diamonds, diamonds + n); int ans = 0; for (int i = 0; i < n; ++i) { int cnt = 1; for (int j = i + 1; j < n && diamonds[j] - diamonds[i] <= k; ++j) { cnt++; } ans = max(ans, cnt); } cout << ans << "\n"; return 0; }
[ "ptorres@factorclick.cl" ]
ptorres@factorclick.cl
094de84b39ba6552cbfac81dd79bf07f85cd4ab6
d8ea5358838f3624b0ac11ef2f4d96caa4e2e356
/cf1138c.cpp
781eef013d4a713b31c77efad11ee01ded0ca86e
[]
no_license
md-omar-f/codeforces-problem-solutions
b81794ce6b601347a6857ce084d5cc7c3d00e4d9
db2939c437bf5901c9f5c953d9006ed822ecf312
refs/heads/master
2023-05-12T05:19:38.597484
2023-04-29T19:46:24
2023-04-29T19:46:24
283,279,144
0
0
null
null
null
null
UTF-8
C++
false
false
995
cpp
#include<bits/stdc++.h> using namespace std; #define IOS ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); #define endl "\n" #define forn(i,n) for(int i=0;i<int(n);++i) #define vet(a) for(auto&i:a)cout<<i<<" " #define out(a) cout<<a<<endl #define ll long long int const int maxn=3e5+100; int n; vector<pair<int,int>>ans; int arr[maxn],pos[maxn]; int find(int x){ if(2*(n-x)>=n)return n; else return 1; } void change(int x,int y){ ans.push_back(make_pair(x,y)); swap(pos[arr[x]],pos[arr[y]]); swap(arr[x],arr[y]); } int32_t main() { IOS; #ifndef ONLINE_JUDGE freopen("input.txt","r",stdin); freopen("output.txt","w",stdout); #endif cin>>n; for(int i=1;i<=n;++i){ cin>>arr[i]; pos[arr[i]]=i; } for(int i=2;i<n;++i){ int t=pos[i]; change(t,find(t)); if(find(t)!=find(i))change(find(t),find(i)); change(i,find(i)); } if(arr[1]!=1)change(1,n); cout<<ans.size()<<endl; for(int i=0;i<ans.size();++i){ cout<<ans[i].first<<" "<<ans[i].second<<endl; } return 0; }
[ "37813113+TuhinOmar@users.noreply.github.com" ]
37813113+TuhinOmar@users.noreply.github.com
09766ce7c0c74861cd56aa33bea107a338cd25e5
45e3eb85ad842e22efefad6d3c1af327998eb297
/AtCoder/ABC/172/c2.cpp
1cd0ca0d5ab3d93eb0ea1b652c3a3ca4fd915f67
[]
no_license
sawamotokai/competitive-programming
6b5e18217c765184acfb2613b681d0ac9ec3f762
9659124def45447be5fccada6e835cd7e09d8f79
refs/heads/master
2023-06-12T06:56:01.985876
2021-07-05T16:55:56
2021-07-05T16:55:56
241,240,765
0
0
null
null
null
null
UTF-8
C++
false
false
1,314
cpp
#include <bits/stdc++.h> #define rep(i,n) for (int i = 0; i < (n); ++i) #define ok() puts(ok?"Yes":"No"); #define chmax(x,y) x = max(x,y) #define chmin(x,y) x = min(x,y) using namespace std; using ll = long long; using vi = vector<int>; using ii = pair<int, int>; using vvi = vector<vi>; using vii = vector<ii>; using gt = greater<int>; using minq = priority_queue<int, vector<int>, gt>; using P = pair<ll,ll>; const ll LINF = 1e18L + 1; const int INF = 1e9 + 1; //clang++ -std=c++11 -stdlib=libc++ int ans = 0; ll k; vector<ll> a, b; ll get_a(int i) { if (a.size() - 1 - i >= 0) return a[a.size() - 1 - i]; return LINF; } ll get_b(int i) { if (b.size() - 1 - i >= 0) return b[b.size() - 1 - i]; return LINF; } int f(int i, int j, ll sum=0) { ll na = get_a(i); ll nb = get_b(j); if (min(na, nb) + sum > k) return 0; if (na == nb) { if (na == LINF) return 0; return 1 + max(f(i + 1, j, sum + na), f(i, j + 1, sum + nb)); } if (na < nb) { return 1 + f(i + 1, j, sum + na); } else { return 1 + f(i, j + 1, sum + nb); } } int main() { ll n,m; cin >> n>> m>>k; a.resize(n); b.resize(m); rep(i,n) { cin >> a[i]; } rep(i,m) { cin >> b[i]; } reverse(a.begin(), a.end()); reverse(b.begin(), b.end()); cout << f(0,0) << endl; return 0; }
[ "kaisawamoto@gmail.com" ]
kaisawamoto@gmail.com
79fe6b597abbc387221495bdd9ccad20d7566f0b
1eefc314ffe03f5e1dc7482c227186ff42752dd4
/include/gameplay/train/train.hpp
75f36963cc89e3e1a0915879f3557f4b485bf8b0
[]
no_license
Neraste/transarctica-rebirth
22e44300e7a1654d53a4f503f3f61615d1d27496
30761433cb27ef03d0deaf575485643b2ad787b9
refs/heads/master
2021-07-08T08:00:19.965417
2020-11-05T15:28:08
2020-11-05T15:28:08
207,108,226
1
0
null
null
null
null
UTF-8
C++
false
false
1,987
hpp
#ifndef TRAIN_HPP #define TRAIN_HPP #include <memory> #include <vector> #include "cars.hpp" #include "merchandises.hpp" #include "types.hpp" namespace train { class Train { protected: std::vector<std::shared_ptr<cars::Car>> cars; std::vector<std::shared_ptr<cars::Car>>::iterator getCarIterator(const std::size_t carId); public: Train(); const std::vector<const merchandises::MerchLoad&> getMerchLoads() const; const std::vector<const cars::Car&> getCars() const; void buy(merchandises::MerchLoad& merchLoad, const types::quantity quantity); bool canBuy(merchandises::MerchLoad& merchLoad, const types::quantity quantity); void sell(merchandises::Merch& merch, const types::quantity quantity); bool canSell(merchandises::Merch& merch, const types::quantity quantity); void addCar(std::shared_ptr<cars::Car> car); std::shared_ptr<cars::Car> removeCar(const std::size_t carId); void moveCar(const std::size_t carId, const std::size_t position); std::shared_ptr<cars::Car> getCar(const std::size_t carId); }; /** * Error class when a car cannot be found. */ struct CarNotFoundError : public exceptions::TransarcticaRebirthError { /** * Error message. * @return Error message. */ const char* what() const throw() { return "Car not found"; } }; /** * Error class when a car is moved to invalid position. */ struct CarInvalidPositionError : public exceptions::TransarcticaRebirthError { /** * Error message. * @return Error message. */ const char* what() const throw() { return "Position not possible"; } }; /** * Error class used when trying to remove a special car. */ struct SpecialCarRemoveError : public exceptions::TransarcticaRebirthError { /** * Error message. * @return Error message. */ const char* what() const throw() { return "This car cannot be removed"; } }; } #endif //ifndef TRAIN_HPP
[ "neraste.herr10@gmail.com" ]
neraste.herr10@gmail.com
f52d297a07f8d2cf45ed86a7420ad8d2e59b3cf3
16db6a9d45aa28ede7aaf9c531fc4a25815b4b50
/mainwindow.h
f009a477a6200a2063d09e82941d806882bf82c8
[]
no_license
cdfq277462/GMT_StewartPlatformCalibration
47ca348ebb2c11369cd46c130712a3fde7a9aa6f
c02a352e4f68fb8a2e2d623730a7d70ae78b65f7
refs/heads/master
2023-07-10T22:11:40.840866
2021-08-06T08:59:09
2021-08-06T08:59:09
393,319,010
0
0
null
null
null
null
UTF-8
C++
false
false
2,395
h
#ifndef MAINWINDOW_H #define MAINWINDOW_H #include <QMainWindow> QT_BEGIN_NAMESPACE namespace Ui { class MainWindow; } QT_END_NAMESPACE // TIP: use #define RDK_SKIP_NAMESPACE to avoid using namespaces #include "robodk_api.h" using namespace RoboDK_API; enum WORKINGPAGE{ HOMEPAGE = 0, PARAMETERPAGE = 1, OPERATIONPAGE = 2, TRAJECTORYPAGE = 3, BATCH_CALIBRATIONPAGE = 4 }; enum POSE{ POSE_X = 0, POSE_Y = 1, POSE_Z = 2, POSE_PHI = 3, POSE_THETA = 4, POSE_PSI = 5, }; enum LENGTH{ LENGTH_1 = 6, LENGTH_2 = 7, LENGTH_3 = 8, LENGTH_4 = 9, LENGTH_5 = 10, LENGTH_6 = 11, }; class MainWindow : public QMainWindow { Q_OBJECT public: MainWindow(QWidget *parent = nullptr); ~MainWindow(); private slots: void timerEvent(QTimerEvent *event); void initUi(); void frameUpdate(); /// Select a robot void Select_Robot(); /// Validate if RoboDK is running (RDK is valid) bool Check_RoboDK(); /// Validate if a Robot has been selected (ROBOT variable is valid) bool Check_Robot(); /// Apply an incremental movement void IncrementalMove(int id, double sense); QStringList getCurrentPose(); void on_pushButton_nextPage_clicked(); void on_pushButton_previousPage_clicked(); void on_pushButton_connectRoboDK_clicked(); void on_stackedWidget_workSpace_currentChanged(int arg1); void on_pushButton_errorPlot_clicked(); void on_pushButton_loadModel_clicked(); void on_btnTXn_clicked(); void on_btnTYn_clicked(); void on_btnTZn_clicked(); void on_btnRXn_clicked(); void on_btnRYn_clicked(); void on_btnRZn_clicked(); void on_btnTXp_clicked(); void on_btnTYp_clicked(); void on_btnTZp_clicked(); void on_btnRXp_clicked(); void on_btnRYp_clicked(); void on_btnRZp_clicked(); void on_pushButton_moveToHome_clicked(); void on_pushButton_selectRobot_clicked(); void on_pushButton_addToolFrame_clicked(); void on_radioButton_relativeBase_clicked(); void on_radioButton_relativeOwn_clicked(); void on_pushButton_clicked(); private: Ui::MainWindow *ui; /// Pointer to RoboDK RoboDK *RDK; /// Pointer to the robot item Item *ROBOT; /// Pointer to the RoboDK window QWindow *robodk_window; int timeID_frameUpdate; }; #endif // MAINWINDOW_H
[ "jyj0913@gmt.tw" ]
jyj0913@gmt.tw
e9f4976fcf9c43656516b17d32d418a4557c1764
13402eb7738baf9625ca6d8cbf14468c969a1352
/build-360parser-Desktop_Qt_5_14_2_clang_64bit-Debug/ui_secondwindow.h
082430ca29208474f5a8484d880db6d5b0013a55
[]
no_license
ingmarfjolla/Architecture3ProjCompiler-unfinished
d13f991b52fcd46ae2d7b55a5811a77881eaad10
4adedad748e5fd4f753f54fcbaf33198869ef1b0
refs/heads/master
2023-06-16T09:44:04.308758
2021-07-20T18:16:20
2021-07-20T18:16:20
302,148,031
0
0
null
null
null
null
UTF-8
C++
false
false
1,198
h
/******************************************************************************** ** Form generated from reading UI file 'secondwindow.ui' ** ** Created by: Qt User Interface Compiler version 5.14.2 ** ** WARNING! All changes made in this file will be lost when recompiling UI file! ********************************************************************************/ #ifndef UI_SECONDWINDOW_H #define UI_SECONDWINDOW_H #include <QtCore/QVariant> #include <QtWidgets/QApplication> #include <QtWidgets/QWidget> QT_BEGIN_NAMESPACE class Ui_Secondwindow { public: void setupUi(QWidget *Secondwindow) { if (Secondwindow->objectName().isEmpty()) Secondwindow->setObjectName(QString::fromUtf8("Secondwindow")); Secondwindow->resize(400, 300); retranslateUi(Secondwindow); QMetaObject::connectSlotsByName(Secondwindow); } // setupUi void retranslateUi(QWidget *Secondwindow) { Secondwindow->setWindowTitle(QCoreApplication::translate("Secondwindow", "Form", nullptr)); } // retranslateUi }; namespace Ui { class Secondwindow: public Ui_Secondwindow {}; } // namespace Ui QT_END_NAMESPACE #endif // UI_SECONDWINDOW_H
[ "ingmar@Ingmars-MacBook-Air.local" ]
ingmar@Ingmars-MacBook-Air.local
06853b2ff1398888fcd6d41fb30f7c54f824e617
94db0bd95a58fabfd47517ed7d7d819a542693cd
/client/ClientRes/IOSAPI/Classes/Native/AssemblyU2DCSharp_ProtoBuf_ProtoConverterAttribute1287216368.h
c5d438cbe66f0e2bae71942520340210d07bf018
[]
no_license
Avatarchik/card
9fc6efa058085bd25f2b8831267816aa12b24350
d18dbc9c7da5cf32c963458ac13731ecfbf252fa
refs/heads/master
2020-06-07T07:01:00.444233
2017-12-11T10:52:17
2017-12-11T10:52:17
null
0
0
null
null
null
null
UTF-8
C++
false
false
538
h
#pragma once #include "il2cpp-config.h" #ifndef _MSC_VER # include <alloca.h> #else # include <malloc.h> #endif #include <stdint.h> #include "mscorlib_System_Attribute542643598.h" #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // ProtoBuf.ProtoConverterAttribute struct ProtoConverterAttribute_t1287216368 : public Attribute_t542643598 { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif
[ "1" ]
1
1ee24acbec4a4e44d0741d8f8735a0ec1d4a38b1
f7bbeee021ae30cb35def098b374a0cabd0a36fc
/containerwithmostwater.cpp
780ac9d8ceb9551ca9c99a49a6f434ef14f9b368
[]
no_license
jxie418/leetcodecpp
e8e8ad9fb8adbbe389738523ee266735d124d2df
6a778367726dd47247d99e94d7a0a29efe2b0cb8
refs/heads/master
2021-01-10T09:30:10.960584
2016-04-24T03:10:07
2016-04-24T03:10:07
49,180,832
0
0
null
null
null
null
UTF-8
C++
false
false
496
cpp
#include <iostream> #include <vector> using namespace std; class Solution { public : int maxArea(vector<int> &height) { int res = 0, i = 0, j = height.size() -1; while(i < j) { res = max(res, min(height[i],height[j]) * (j-i)); if (height[i] < height[j]) { j--; } else { i++; } } return res; } }; int main() { vector<int> v; v.push_back(1); v.push_back(2); v.push_back(3); v.push_back(4); Solution s; cout << s.maxArea(v)<<endl; return 0; }
[ "jxie418@gmail.com" ]
jxie418@gmail.com
f126625200e4c34f7d2caf81be86f6b652404313
d858dd619615846cff90c7027fa63aaa933f7d90
/logdevice/server/locallogstore/RocksDBLogStoreBase.h
cad81685af22ed021d7d961f7752dee862dbae21
[ "BSD-3-Clause" ]
permissive
xingyong/LogDevice
dcbb652c4b3ce714ab308747eeccb0fd86ff48e6
a7c175c7a7f6dbd78c4a167f0ce6e3d046fa4f67
refs/heads/master
2020-05-17T23:22:06.158927
2019-04-29T03:45:25
2019-04-29T05:25:14
null
0
0
null
null
null
null
UTF-8
C++
false
false
27,495
h
/** * Copyright (c) 2017-present, Facebook, Inc. and its affiliates. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. */ #pragma once #include <atomic> #include <boost/noncopyable.hpp> #include <folly/Synchronized.h> #include <rocksdb/db.h> #include <rocksdb/iterator.h> #include <rocksdb/perf_context.h> #include <rocksdb/statistics.h> #include "logdevice/common/debug.h" #include "logdevice/common/settings/RebuildingSettings.h" #include "logdevice/common/stats/Stats.h" #include "logdevice/server/IOFaultInjection.h" #include "logdevice/server/locallogstore/LocalLogStore.h" #include "logdevice/server/locallogstore/RocksDBColumnFamily.h" #include "logdevice/server/locallogstore/RocksDBKeyFormat.h" #include "logdevice/server/locallogstore/RocksDBLogStoreConfig.h" #include "logdevice/server/locallogstore/RocksDBSettings.h" namespace facebook { namespace logdevice { class RocksDBIterator; class RocksDBMemTableRepFactory; class RocksDBWriter; /** * @file Base class for RocksDB-backed local log stores. * Exposes RocksDB database and provides default implementation for * acceptingWrites(). */ class RocksDBLogStoreBase : public LocalLogStore { public: // We keep a key-value pair in RocksDB with key "schema_version" and // value "2", and refuse to open a DB if the value is different. static const char* const SCHEMA_VERSION_KEY; ~RocksDBLogStoreBase() override; /** * @return boolean indicating if DB can be written currently */ Status acceptingWrites() const override { if (fail_safe_mode_.load()) { return E::DISABLED; } else if (!space_for_writes_.load()) { return E::NOSPC; } else if (low_watermark_crossed_.load()) { return E::LOW_ON_SPC; } else { return E::OK; } } int sync(Durability durability) override; FlushToken maxFlushToken() const override; FlushToken flushedUpThrough() const override; SteadyTimestamp oldestUnflushedDataTimestamp() const override; void stallLowPriWrite() override; StatsHolder* getStatsHolder() const { return stats_; } /** * @return rocksdb::DB instance owned by this class. */ rocksdb::DB& getDB() const { return *db_; } /** * @return the column family that contains StoreMetadata, LogMetadata etc. */ virtual rocksdb::ColumnFamilyHandle* getMetadataCFHandle() const { return db_->DefaultColumnFamily(); } /** * Returns a new rocksdb::Iterator wrapped in RocksDBIterator. * Use this instead of calling getDB()->NewIterator() directly. */ RocksDBIterator newIterator(rocksdb::ReadOptions ropt, rocksdb::ColumnFamilyHandle* cf) const; void onStorageThreadStarted() override { // Make RocksDB's PerfContext track time stats. rocksdb::SetPerfLevel(rocksdb::kEnableTime); } /** * @return value of the specified ticker or 0 if statistics are disabled. */ uint64_t getStatsTickerCount(rocksdb::Tickers ticker_type) const { if (!statistics_) { return 0; } return statistics_->getTickerCount(ticker_type); } /** * @return various RocksDB stats in a human-readable form. */ virtual std::string getStats() const { std::string res; db_->GetProperty("rocksdb.stats", &res); if (statistics_) { res += "\n"; res += statistics_->ToString(); } return res; } struct RocksDBMemTableStats { // Size of current active and unflushed memtable. uint64_t active_memtable_size{0}; // Size of immutable memtables scheduled for flush. uint64_t immutable_memtable_size{0}; // Size of immutable memtables pinned in memory. uint64_t pinned_memtable_size{0}; }; // Fetches memtable memory usage for a column family RocksDBMemTableStats getMemTableStats(rocksdb::ColumnFamilyHandle* cf) { RocksDBMemTableStats stats; db_->GetIntProperty(cf, rocksdb::DB::Properties::kCurSizeActiveMemTable, &stats.active_memtable_size); uint64_t aggregated_flushed_stat = 0; db_->GetIntProperty(cf, rocksdb::DB::Properties::kCurSizeAllMemTables, &aggregated_flushed_stat); stats.immutable_memtable_size = aggregated_flushed_stat > stats.active_memtable_size ? aggregated_flushed_stat - stats.active_memtable_size : 0; uint64_t aggregated_memtable_stat = 0; db_->GetIntProperty(cf, rocksdb::DB::Properties::kSizeAllMemTables, &aggregated_memtable_stat); stats.pinned_memtable_size = aggregated_memtable_stat > aggregated_flushed_stat ? aggregated_memtable_stat - aggregated_flushed_stat : 0; return stats; } int getShardIdx() const override { return shard_idx_; } // fsync the rocksdb WAL so that it's contents are guaranteed to // survive a system crash. int syncWAL(); FlushToken maxWALSyncToken() const override; FlushToken walSyncedUpThrough() const override; // Flush memtables for all column families. If wait is true, block until // the flushes have completed. This is currently used by sync() to persist // data when some writes may have been issued that bypassed the WAL. virtual int flushAllMemtables(bool wait = true); virtual void onMemTableWindowUpdated() {} /** * @return path of RocksDB directory */ std::string getDBPath() const { return db_path_; } RocksDBLogStoreConfig& getRocksDBLogStoreConfig() { return rocksdb_config_; } const RocksDBLogStoreConfig& getRocksDBLogStoreConfig() const { return rocksdb_config_; } std::shared_ptr<const RocksDBSettings> getSettings() const { return rocksdb_config_.getRocksDBSettings(); } std::shared_ptr<const RebuildingSettings> getRebuildingSettings() const { return rocksdb_config_.getRebuildingSettings(); } bool hasEnoughSpaceForWrites() const { return space_for_writes_.load(); } void setHasEnoughSpaceForWrites(bool space_for_writes) { space_for_writes_.store(space_for_writes); } void setLowWatermarkForWrites(bool low_wm_crossed) { low_watermark_crossed_.store(low_wm_crossed); } bool crossedLowWatermark() const { return low_watermark_crossed_.load(); } static rocksdb::Status FaultTypeToStatus(IOFaultInjection::FaultType ft) { switch (ft) { case IOFaultInjection::FaultType::IO_ERROR: return rocksdb::Status::IOError("Injected Error"); case IOFaultInjection::FaultType::CORRUPTION: return rocksdb::Status::Corruption("Injected Error"); case IOFaultInjection::FaultType::LATENCY: // Latency FaultType is not supported at this level. ld_check(false); default: return rocksdb::Status::OK(); } } // For reading data records use getReadOptionsSinglePrefix() whenever // possible. getDefaultReadOptions() will prevent the use of bloom filters. static rocksdb::ReadOptions getDefaultReadOptions() { rocksdb::ReadOptions options; options.total_order_seek = true; options.background_purge_on_iterator_cleanup = true; return options; } // Options with rocksdb::ReadOptions::total_order_seek = false. // // An iterator created with these options will see keys with the same // prefix as the key of the last Seek(), but it may or may not see keys with // other prefixes. "Prefix" usually means log (see RocksDBLogStoreConfig for // a precise definition). I.e. these options confine the iterator to a single // log (except that sometimes they don't; see rule below). // // If you need the iterator to move across multiple logs/prefixes, // use getDefaultReadOptions(). // // This option is not always easy to use correctly. Use this rule: if such // iterator ever ends up on a key with prefix (log) different than the prefix // you last seeked to, consider the iterator invalid. I.e. don't do // Next()/Prev() and don't trust the key()/value() until you do // another Seek*(). In particular, to seek to the last key with a given prefix // use SeekForPrev(), not Seek()+Prev(). // // More detailed caveats (optional reading): // * If you seek an iterator to key x, and the iterator ends up pointing to // key y, normally that would mean that y is the smallest key >= x. // But with these options this is not always the case: // if prefix(y) != prefix(x), there may be keys between x and y; // however, it's guaranteed that none of these keys have same prefix as x. // * Continuing the previous example, if you do a Prev() after the Seek(x), // you may end up on a key that's greater than x! I.e. some keys could be // invisible to the Seek() but visible to the Prev(). // * After such Prev(), iterator may also end up !Valid() or on a key with // prefix smaller than prefix(x), even if there actually exist records // smaller than x with the same prefix as x. static rocksdb::ReadOptions getReadOptionsSinglePrefix() { rocksdb::ReadOptions options; options.background_purge_on_iterator_cleanup = true; return options; } // True if an error has occurred which indicates partial loss of // access or corruption of the database. Reads can still be attempted, // but writes will be denied. bool inFailSafeMode() const { return fail_safe_mode_.load(); } // Transition into fail-safe mode. bool enterFailSafeMode(const char* context, const char* error_string) override { if (!fail_safe_mode_.exchange(true)) { ld_error("%s failed, entering fail safe mode; error: %s", context, error_string); PER_SHARD_STAT_INCR(getStatsHolder(), failed_safe_log_stores, shard_idx_); return true; } else { return false; } } // If status is an error, count it in stats. // No-op if status is ok or incomplete. // Convention: if you directly call a rocksdb method that returns a Status, // you need to call noteRocksDBStatus() or enterFailSafeModeIfFailed() with // the result, unless it's ok() or IsIncomplete(). If you call a logdevice // function that returns rocksdb::Status, don't call noteRocksDBStatus(). void noteRocksDBStatus(const rocksdb::Status& s, const char* context) const { const_cast<RocksDBLogStoreBase*>(this)->gotRocksDBStatusImpl( s, false, context); } // Similar to noteRocksDBStatus() but if status is some permanent-looking // error (IO error or corruption) enters fail-safe mode. void enterFailSafeIfFailed(const rocksdb::Status& s, const char* context) const { gotRocksDBStatusImpl(s, true, context); } // Returns a ReadOptions struct to be passed to RocksDB. // @param single_log if true, total_order_seek will be set to false, // i.e. the iterator will be confined to a single log. // @param upper_bound if non-nullptr and non-empty, will be used as // iterate_upper_bound. The ReadOptions will have a pointer // to the Slice, so the provided Slice must outlive the // any iterators created with these ReadOptions. static rocksdb::ReadOptions translateReadOptions(const LocalLogStore::ReadOptions& opts, bool single_log, rocksdb::Slice* upper_bound); // Default implementation of metadata operations. Thin wrappers around // RocksDBWriter methods. // The separation between RocksDBWriter and RocksDBLogStoreBase is unclear; // it would probably make sense to merge the two. int readLogMetadata(logid_t log_id, LogMetadata* metadata) override; int readStoreMetadata(StoreMetadata* metadata) override; int readPerEpochLogMetadata(logid_t log_id, epoch_t epoch, PerEpochLogMetadata* metadata, bool find_last_available = false, bool allow_blocking_io = true) const override; int writeLogMetadata( logid_t log_id, const LogMetadata& metadata, const WriteOptions& write_options = WriteOptions()) override; int writeStoreMetadata( const StoreMetadata& metadata, const WriteOptions& write_options = WriteOptions()) override; int updateLogMetadata( logid_t log_id, ComparableLogMetadata& metadata, const WriteOptions& write_options = WriteOptions()) override; int updatePerEpochLogMetadata( logid_t log_id, epoch_t epoch, PerEpochLogMetadata& metadata, LocalLogStore::SealPreemption seal_preempt, const WriteOptions& write_options = WriteOptions()) override; int deleteStoreMetadata( const StoreMetadataType type, const WriteOptions& write_options = WriteOptions()) override; int deleteLogMetadata( logid_t first_log_id, logid_t last_log_id, const LogMetadataType type, const WriteOptions& write_options = WriteOptions()) override; int deletePerEpochLogMetadata( logid_t log_id, epoch_t epoch, const PerEpochLogMetadataType type, const WriteOptions& write_options = WriteOptions()) override; virtual void onSettingsUpdated( const std::shared_ptr<const RocksDBSettings> /* unused */) {} static size_t getIOBytesUnnormalized() { return rocksdb::get_perf_context()->block_read_byte; } // Get column family holder shared ptr. Returned instance could be // freed from other thread as part of column family drop or during shutdown // hence it is necessary to check validity of ptr before using. This method // returns nullptr if the column family was not found. RocksDBCFPtr getColumnFamilyPtr(uint32_t column_family_id); // Invoked when RocksDB decides to flush memtables of column families in this // db. // Returns the array of all column families that need to be // flushed and the order in which they should be flushed. Return value is a // two-dimensional array, where first dimension tells what column families // should be flushed on a single thread. Hence, each element in first // dimension of array can be flushed in parallel on different threads. Second // dimension indicates in what order the column families need to be flushed on // a single thread. virtual std::vector<std::vector<uint32_t>> onMemtableFlushBegin(std::vector<uint32_t> /*unused*/) { return {}; } protected: /** * Assumes ownership of the raw rocksdb::DB pointer. */ RocksDBLogStoreBase(uint32_t shard_idx, const std::string& path, RocksDBLogStoreConfig rocksdb_config, StatsHolder* stats_holder); /** * Verifies that the schema version entry matches the code version. If this * is a brand new database, writes the schema version entry. */ int checkSchemaVersion(rocksdb::DB* db, rocksdb::ColumnFamilyHandle* cf, int expected) const { rocksdb::Slice key_slice(SCHEMA_VERSION_KEY, strlen(SCHEMA_VERSION_KEY)); std::string value; rocksdb::Status status = db->Get(getDefaultReadOptions(), cf, key_slice, &value); if (status.ok()) { int db_version = std::stoi(value); if (db_version != expected) { ld_error("Schema version mismatch: code version is %d, database " "version is \"%s\".", expected, value.c_str()); return -1; } return 0; } else if (status.IsNotFound()) { // Schema version key not found. Check if the database is empty ... int rv = isCFEmpty(cf); if (rv != 1) { return -1; } // This is a new database with no contents. Write the schema version. value = std::to_string(expected); status = db->Put(rocksdb::WriteOptions(), cf, key_slice, rocksdb::Slice(value.data(), value.size())); if (!status.ok()) { ld_error("Error writing schema version to database"); return -1; } return 0; } else { ld_error("Error reading schema version from database: %s", status.ToString().c_str()); noteRocksDBStatus(status, "Get() (schema version)"); return -1; } } // Checks that there are no keys in CF, except, maybe, "schema_version" key. int isCFEmpty(rocksdb::ColumnFamilyHandle* cf) const; uint64_t getVersion() const override { uint64_t version; if (!db_->GetIntProperty( "rocksdb.current-super-version-number", &version)) { return 0; } return version; } int readAllLogSnapshotBlobsImpl(LogSnapshotBlobType snapshots_type, LogSnapshotBlobCallback callback, rocksdb::ColumnFamilyHandle* snapshots_cf); void gotRocksDBStatusImpl(const rocksdb::Status& s, bool enter_fail_safe_if_bad, const char* context) const { if (s.ok() || s.IsIncomplete() || s.IsNotFound() || s.IsShutdownInProgress()) { return; } if (s.IsIOError()) { PER_SHARD_STAT_INCR(getStatsHolder(), disk_io_errors, shard_idx_); } else if (s.IsCorruption()) { PER_SHARD_STAT_INCR(getStatsHolder(), corruption_errors, shard_idx_); } else { enter_fail_safe_if_bad = false; } if (enter_fail_safe_if_bad && !fail_safe_mode_.exchange(true)) { ld_error("Got rocksdb error in %s: %s. Entering fail-safe mode.", context, s.ToString().c_str()); PER_SHARD_STAT_INCR(getStatsHolder(), failed_safe_log_stores, shard_idx_); } else if (enter_fail_safe_if_bad || fail_safe_mode_.load()) { RATELIMIT_ERROR(std::chrono::seconds(10), 2, "Got rocksdb error in %s: %s. Already in fail-safe mode.", context, s.ToString().c_str()); } else { RATELIMIT_ERROR( std::chrono::seconds(10), 2, "Got rocksdb error in %s: %s. Not entering fail-safe mode.", context, s.ToString().c_str()); } } // Returns true if there's at least one flush in progress. bool isFlushInProgress(); void adviseUnstallingLowPriWrites(bool dont_stall_anymore = false) override; // If you override this method, you need to call // adviseUnstallingLowPriWrites() after this value changes from true to false. // This will wake up the stalled writers and make them call this method again. virtual bool shouldStallLowPriWrites() { return isFlushInProgress(); } std::unique_ptr<rocksdb::DB> db_; uint32_t shard_idx_; // path to the rocksdb directory const std::string db_path_; // object used to perform writes to the db std::unique_ptr<RocksDBWriter> writer_; // pointer to the stats holder StatsHolder* stats_; // flag that indidates if there is enough space to take writes // Currently only set by the monitoring thread std::atomic<bool> space_for_writes_{true}; // statistics object used by RocksDB std::shared_ptr<rocksdb::Statistics> statistics_; // true if store has failed such that we will not attempt writes. mutable std::atomic<bool> fail_safe_mode_{false}; std::atomic<bool> low_watermark_crossed_{false}; RocksDBLogStoreConfig rocksdb_config_; // Contains references to all the column family handles within this // rocksdb instance. using RocksDBColumnFamilyMap = std::unordered_map<uint32_t, RocksDBCFPtr>; folly::Synchronized<RocksDBColumnFamilyMap> cf_accessor_; private: // Write stalling stuff. struct Listener : public rocksdb::EventListener { explicit Listener(RocksDBLogStoreBase* store) : store_(store) {} void OnFlushCompleted(rocksdb::DB*, const rocksdb::FlushJobInfo&) override { store_->adviseUnstallingLowPriWrites(); } RocksDBLogStoreBase* store_; }; std::atomic<std::chrono::steady_clock::duration> dont_stall_until_{ std::chrono::steady_clock::duration::min()}; std::mutex stall_mutex_; // locked for duration of the stall std::mutex stall_cv_mutex_; // only needed for stall_cv_ std::condition_variable stall_cv_; std::shared_ptr<RocksDBMemTableRepFactory> mtr_factory_; // Adds a rocksdb::EventListener that is used for unstalling writes when // a flush finishes. void registerListener(rocksdb::Options& options); // Installs a MemTableRepFactory so that LogDevice's MemTabelRep is // used when constructing all MemTables. void installMemTableRep(); }; // Holds a rocksdb key that can be used as // rocksdb::ReadOptions::iterate_upper_bound when iterating over records of a // single log. struct IterateUpperBoundHelper { // Use folly::none to disable iterate_upper_bound // (it'll be set to empty Slice). explicit IterateUpperBoundHelper(folly::Optional<logid_t> log_id) : data_key(log_id.value_or(LOGID_INVALID), std::numeric_limits<lsn_t>::max()) { if (log_id.hasValue()) { // Set (log_id, LSN_MAX) as the upper bound. // Note that this may prevent iterator from seeing record LSN_MAX because // iterate_upper_bound is the exclusive upper bound. // This is fine because no valid record can have this LSN because its // epoch is too high to be valid (EPOCH_MAX = 2^32 - 2). upper_bound = data_key.sliceForBackwardSeek(); } } // Key used as an upper bound for the iterator (a key such that all records // for the log are strictly smaller than it). RocksDBKeyFormat::DataKey data_key; // Slice pointing to last_key. Passed to RocksDB. rocksdb::Slice upper_bound; }; /** * A wrapper for rocksdb iterator. All logdevice code should use it instead * of using rocksdb iterators directly. * - Bumps stats for IO errors and corruption errors * (RocksDBLogStoreBase::noteRocksDBStatus()). * - Caches status. Vanilla rocksdb iterator's status() collects status from * all subiterators on each call, which can be slow. * - Adds some asserts, e.g. that status is always checked before accessing * the key/value. * - Movable (has a unique_ptr to the underlying iterator). * Trying to use a moved-out RocksDBIterator will fail an assert. * This class intentionally doesn't inherit from rocksdb::Iterator to make sure * it doesn't break when methods are added to rocksdb::Iterator. */ class RocksDBIterator { public: RocksDBIterator(std::unique_ptr<rocksdb::Iterator> iterator, const rocksdb::ReadOptions& read_options, const RocksDBLogStoreBase* store) : iterator_(std::move(iterator)), store_(store), total_order_seek_(read_options.total_order_seek) { ld_check(iterator_ != nullptr); ld_check(store_ != nullptr); } // Moved-out RocksDBIterators are not usable. // Calling any method will fail an assert. RocksDBIterator(RocksDBIterator&& rhs) = default; RocksDBIterator& operator=(RocksDBIterator&& rhs) = default; bool Valid() const { // iterator_ can be nullptr if it was moved out into another RocksDBIterator ld_check(iterator_ != nullptr); valid_checked_ = true; return iterator_->Valid(); } void SeekToFirst() { ld_check(iterator_ != nullptr); valid_checked_ = false; status_checked_ = false; iterator_->SeekToFirst(); status_ = getRocksdbStatus(); store_->enterFailSafeIfFailed(status_.value(), "SeekToFirst()"); } void SeekToLast() { ld_check(iterator_ != nullptr); valid_checked_ = false; status_checked_ = false; iterator_->SeekToLast(); status_ = getRocksdbStatus(); store_->enterFailSafeIfFailed(status_.value(), "SeekToLast()"); } void Seek(const rocksdb::Slice& target) { ld_check(iterator_ != nullptr); valid_checked_ = false; status_checked_ = false; iterator_->Seek(target); status_ = getRocksdbStatus(); store_->enterFailSafeIfFailed(status_.value(), "Seek()"); } void SeekForPrev(const rocksdb::Slice& target) { ld_check(iterator_ != nullptr); valid_checked_ = false; status_checked_ = false; iterator_->SeekForPrev(target); status_ = getRocksdbStatus(); store_->enterFailSafeIfFailed(status_.value(), "SeekForPrev()"); } void Next() { ld_check(iterator_ != nullptr); ld_check(valid_checked_); ld_check(status_checked_); valid_checked_ = false; status_checked_ = false; iterator_->Next(); status_ = getRocksdbStatus(); store_->enterFailSafeIfFailed(status_.value(), "Next()"); } void Prev() { ld_check(iterator_ != nullptr); ld_check(valid_checked_); ld_check(status_checked_); valid_checked_ = false; status_checked_ = false; iterator_->Prev(); status_ = getRocksdbStatus(); store_->enterFailSafeIfFailed(status_.value(), "Prev()"); } void Refresh() { ld_check(iterator_ != nullptr); valid_checked_ = false; status_checked_ = false; iterator_->Refresh(); status_ = getRocksdbStatus(); store_->enterFailSafeIfFailed(status_.value(), "Refresh()"); } rocksdb::Slice key() const { ld_check(iterator_ != nullptr); ld_check(valid_checked_); ld_check(status_checked_); return iterator_->key(); } rocksdb::Slice value() const { ld_check(iterator_ != nullptr); ld_check(valid_checked_); ld_check(status_checked_); return iterator_->value(); } rocksdb::Status status() const { ld_check(iterator_ != nullptr); // Makes no sense to call status() before doing the first seek. ld_check(status_.hasValue()); status_checked_ = true; return status_.value(); } rocksdb::Status GetProperty(std::string prop_name, std::string* prop) { ld_check(iterator_ != nullptr); return iterator_->GetProperty(std::move(prop_name), prop); } bool totalOrderSeek() const { return total_order_seek_; } private: rocksdb::Status getRocksdbStatus() { using IOType = IOFaultInjection::IOType; using DataType = IOFaultInjection::DataType; using FaultType = IOFaultInjection::FaultType; rocksdb::Status status; auto* rb_store = static_cast<const RocksDBLogStoreBase*>(store_); auto& io_fault_injection = IOFaultInjection::instance(); auto sim_error = io_fault_injection.getInjectedFault( store_->getShardIdx(), IOType::READ, FaultType::IO_ERROR | FaultType::CORRUPTION, DataType::DATA); if (sim_error != FaultType::NONE) { status = RocksDBLogStoreBase::FaultTypeToStatus(sim_error); RATELIMIT_ERROR(std::chrono::seconds(1), 2, "Returning injected error '%s' for shard '%s'.", status.ToString().c_str(), rb_store->getDBPath().c_str()); } else { status = iterator_->status(); } return status; } // The iterator we're wrapping. std::unique_ptr<rocksdb::Iterator> iterator_; // For stats. const RocksDBLogStoreBase* store_; // Cached status. folly::Optional<rocksdb::Status> status_; // For asserts. bool total_order_seek_; mutable bool valid_checked_ = false; mutable bool status_checked_ = false; }; }} // namespace facebook::logdevice
[ "facebook-github-bot@users.noreply.github.com" ]
facebook-github-bot@users.noreply.github.com
fcd8e237d15ea7e75e701d433118b2c57024de33
880639d21c818bb5b9ab1f1d82da1e26bb31739d
/src/test/miner_tests.cpp
abb8e12973d97a520043aa6c52fe2a0d916e7418
[ "MIT" ]
permissive
jwrl/Unit
dba4c0c810df7304bbe9d52f7ad0f1ab97c1fb4c
fd8e4fdb548ca5ba33e6f22176a569a102a78f99
refs/heads/master
2020-12-26T22:27:41.467471
2020-02-01T20:21:23
2020-02-01T20:21:23
237,667,704
2
1
null
null
null
null
UTF-8
C++
false
false
24,498
cpp
// Copyright (c) 2011-2017 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <chainparams.h> #include <coins.h> #include <consensus/consensus.h> #include <consensus/merkle.h> #include <consensus/tx_verify.h> #include <consensus/validation.h> #include <validation.h> #include <miner.h> #include <policy/policy.h> #include <pubkey.h> #include <script/standard.h> #include <txmempool.h> #include <uint256.h> #include <util.h> #include <utilstrencodings.h> #include <test/test_bitcoin.h> #include <memory> #include <boost/test/unit_test.hpp> BOOST_FIXTURE_TEST_SUITE(miner_tests, TestingSetup) // BOOST_CHECK_EXCEPTION predicates to check the specific validation error class HasReason { public: HasReason(const std::string& reason) : m_reason(reason) {} bool operator() (const std::runtime_error& e) const { return std::string(e.what()).find(m_reason) != std::string::npos; }; private: const std::string m_reason; }; static CFeeRate blockMinFeeRate = CFeeRate(DEFAULT_BLOCK_MIN_TX_FEE); static BlockAssembler AssemblerForTest(const CChainParams& params) { BlockAssembler::Options options; options.nBlockMaxWeight = MAX_BLOCK_WEIGHT; options.blockMinFeeRate = blockMinFeeRate; return BlockAssembler(params, options); } static struct { unsigned char extranonce; unsigned int nonce; } blockinfo[] = { {4, 0xa4ad9f65}, {2, 0x15cf2b27}, {1, 0x037620ac}, {1, 0x700d9c54}, {2, 0xce79f74f}, {2, 0x52d9c194}, {1, 0x77bc3efc}, {2, 0xbb62c5e8}, {2, 0x83ff997a}, {1, 0x48b984ee}, {1, 0xef925da0}, {2, 0x680d2979}, {2, 0x08953af7}, {1, 0x087dd553}, {2, 0x210e2818}, {2, 0xdfffcdef}, {1, 0xeea1b209}, {2, 0xba4a8943}, {1, 0xa7333e77}, {1, 0x344f3e2a}, {3, 0xd651f08e}, {2, 0xeca3957f}, {2, 0xca35aa49}, {1, 0x6bb2065d}, {2, 0x0170ee44}, {1, 0x6e12f4aa}, {2, 0x43f4f4db}, {2, 0x279c1c44}, {2, 0xb5a50f10}, {2, 0xb3902841}, {2, 0xd198647e}, {2, 0x6bc40d88}, {1, 0x633a9a1c}, {2, 0x9a722ed8}, {2, 0x55580d10}, {1, 0xd65022a1}, {2, 0xa12ffcc8}, {1, 0x75a6a9c7}, {2, 0xfb7c80b7}, {1, 0xe8403e6c}, {1, 0xe34017a0}, {3, 0x659e177b}, {2, 0xba5c40bf}, {5, 0x022f11ef}, {1, 0xa9ab516a}, {5, 0xd0999ed4}, {1, 0x37277cb3}, {1, 0x830f735f}, {1, 0xc6e3d947}, {2, 0x824a0c1b}, {1, 0x99962416}, {1, 0x75336f63}, {1, 0xaacf0fea}, {1, 0xd6531aec}, {5, 0x7afcf541}, {5, 0x9d6fac0d}, {1, 0x4cf5c4df}, {1, 0xabe0f2a0}, {6, 0x4a3dac18}, {2, 0xf265febe}, {2, 0x1bc9f23f}, {1, 0xad49ab71}, {1, 0x9f2d8923}, {1, 0x15acb65d}, {2, 0xd1cecb52}, {2, 0xf856808b}, {1, 0x0fa96e29}, {1, 0xe063ecbc}, {1, 0x78d926c6}, {5, 0x3e38ad35}, {5, 0x73901915}, {1, 0x63424be0}, {1, 0x6d6b0a1d}, {2, 0x888ba681}, {2, 0xe96b0714}, {1, 0xb7fcaa55}, {2, 0x19c106eb}, {1, 0x5aa13484}, {2, 0x5bf4c2f3}, {2, 0x94d401dd}, {1, 0xa9bc23d9}, {1, 0x3a69c375}, {1, 0x56ed2006}, {5, 0x85ba6dbd}, {1, 0xfd9b2000}, {1, 0x2b2be19a}, {1, 0xba724468}, {1, 0x717eb6e5}, {1, 0x70de86d9}, {1, 0x74e23a42}, {1, 0x49e92832}, {2, 0x6926dbb9}, {0, 0x64452497}, {1, 0x54306d6f}, {2, 0x97ebf052}, {2, 0x55198b70}, {2, 0x03fe61f0}, {1, 0x98f9e67f}, {1, 0xc0842a09}, {1, 0xdfed39c5}, {1, 0x3144223e}, {1, 0xb3d12f84}, {1, 0x7366ceb7}, {5, 0x6240691b}, {2, 0xd3529b57}, {1, 0xf4cae3b1}, {1, 0x5b1df222}, {1, 0xa16a5c70}, {2, 0xbbccedc6}, {2, 0xfe38d0ef}, }; CBlockIndex CreateBlockIndex(int nHeight) { CBlockIndex index; index.nHeight = nHeight; index.pprev = chainActive.Tip(); return index; } bool TestSequenceLocks(const CTransaction &tx, int flags) { LOCK(mempool.cs); return CheckSequenceLocks(tx, flags); } // Test suite for ancestor feerate transaction selection. // Implemented as an additional function, rather than a separate test case, // to allow reusing the blockchain created in CreateNewBlock_validity. void TestPackageSelection(const CChainParams& chainparams, CScript scriptPubKey, std::vector<CTransactionRef>& txFirst) { // Test the ancestor feerate transaction selection. TestMemPoolEntryHelper entry; // Test that a medium fee transaction will be selected after a higher fee // rate package with a low fee rate parent. CMutableTransaction tx; tx.vin.resize(1); tx.vin[0].scriptSig = CScript() << OP_1; tx.vin[0].prevout.hash = txFirst[0]->GetHash(); tx.vin[0].prevout.n = 0; tx.vout.resize(1); tx.vout[0].nValue = 5000000000LL - 1000; // This tx has a low fee: 1000 satoshis uint256 hashParentTx = tx.GetHash(); // save this txid for later use mempool.addUnchecked(hashParentTx, entry.Fee(1000).Time(GetTime()).SpendsCoinbase(true).FromTx(tx)); // This tx has a medium fee: 10000 satoshis tx.vin[0].prevout.hash = txFirst[1]->GetHash(); tx.vout[0].nValue = 5000000000LL - 10000; uint256 hashMediumFeeTx = tx.GetHash(); mempool.addUnchecked(hashMediumFeeTx, entry.Fee(10000).Time(GetTime()).SpendsCoinbase(true).FromTx(tx)); // This tx has a high fee, but depends on the first transaction tx.vin[0].prevout.hash = hashParentTx; tx.vout[0].nValue = 5000000000LL - 1000 - 50000; // 50k satoshi fee uint256 hashHighFeeTx = tx.GetHash(); mempool.addUnchecked(hashHighFeeTx, entry.Fee(50000).Time(GetTime()).SpendsCoinbase(false).FromTx(tx)); std::unique_ptr<CBlockTemplate> pblocktemplate = AssemblerForTest(chainparams).CreateNewBlock(scriptPubKey); BOOST_CHECK(pblocktemplate->block.vtx[1]->GetHash() == hashParentTx); BOOST_CHECK(pblocktemplate->block.vtx[2]->GetHash() == hashHighFeeTx); BOOST_CHECK(pblocktemplate->block.vtx[3]->GetHash() == hashMediumFeeTx); // Test that a package below the block min tx fee doesn't get included tx.vin[0].prevout.hash = hashHighFeeTx; tx.vout[0].nValue = 5000000000LL - 1000 - 50000; // 0 fee uint256 hashFreeTx = tx.GetHash(); mempool.addUnchecked(hashFreeTx, entry.Fee(0).FromTx(tx)); size_t freeTxSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION); // Calculate a fee on child transaction that will put the package just // below the block min tx fee (assuming 1 child tx of the same size). CAmount feeToUse = blockMinFeeRate.GetFee(2*freeTxSize) - 1; tx.vin[0].prevout.hash = hashFreeTx; tx.vout[0].nValue = 5000000000LL - 1000 - 50000 - feeToUse; uint256 hashLowFeeTx = tx.GetHash(); mempool.addUnchecked(hashLowFeeTx, entry.Fee(feeToUse).FromTx(tx)); pblocktemplate = AssemblerForTest(chainparams).CreateNewBlock(scriptPubKey); // Verify that the free tx and the low fee tx didn't get selected for (size_t i=0; i<pblocktemplate->block.vtx.size(); ++i) { BOOST_CHECK(pblocktemplate->block.vtx[i]->GetHash() != hashFreeTx); BOOST_CHECK(pblocktemplate->block.vtx[i]->GetHash() != hashLowFeeTx); } // Test that packages above the min relay fee do get included, even if one // of the transactions is below the min relay fee // Remove the low fee transaction and replace with a higher fee transaction mempool.removeRecursive(tx); tx.vout[0].nValue -= 2; // Now we should be just over the min relay fee hashLowFeeTx = tx.GetHash(); mempool.addUnchecked(hashLowFeeTx, entry.Fee(feeToUse+2).FromTx(tx)); pblocktemplate = AssemblerForTest(chainparams).CreateNewBlock(scriptPubKey); BOOST_CHECK(pblocktemplate->block.vtx[4]->GetHash() == hashFreeTx); BOOST_CHECK(pblocktemplate->block.vtx[5]->GetHash() == hashLowFeeTx); // Test that transaction selection properly updates ancestor fee // calculations as ancestor transactions get included in a block. // Add a 0-fee transaction that has 2 outputs. tx.vin[0].prevout.hash = txFirst[2]->GetHash(); tx.vout.resize(2); tx.vout[0].nValue = 5000000000LL - 100000000; tx.vout[1].nValue = 100000000; // 1BTC output uint256 hashFreeTx2 = tx.GetHash(); mempool.addUnchecked(hashFreeTx2, entry.Fee(0).SpendsCoinbase(true).FromTx(tx)); // This tx can't be mined by itself tx.vin[0].prevout.hash = hashFreeTx2; tx.vout.resize(1); feeToUse = blockMinFeeRate.GetFee(freeTxSize); tx.vout[0].nValue = 5000000000LL - 100000000 - feeToUse; uint256 hashLowFeeTx2 = tx.GetHash(); mempool.addUnchecked(hashLowFeeTx2, entry.Fee(feeToUse).SpendsCoinbase(false).FromTx(tx)); pblocktemplate = AssemblerForTest(chainparams).CreateNewBlock(scriptPubKey); // Verify that this tx isn't selected. for (size_t i=0; i<pblocktemplate->block.vtx.size(); ++i) { BOOST_CHECK(pblocktemplate->block.vtx[i]->GetHash() != hashFreeTx2); BOOST_CHECK(pblocktemplate->block.vtx[i]->GetHash() != hashLowFeeTx2); } // This tx will be mineable, and should cause hashLowFeeTx2 to be selected // as well. tx.vin[0].prevout.n = 1; tx.vout[0].nValue = 100000000 - 10000; // 10k satoshi fee mempool.addUnchecked(tx.GetHash(), entry.Fee(10000).FromTx(tx)); pblocktemplate = AssemblerForTest(chainparams).CreateNewBlock(scriptPubKey); BOOST_CHECK(pblocktemplate->block.vtx[8]->GetHash() == hashLowFeeTx2); } // NOTE: These tests rely on CreateNewBlock doing its own self-validation! BOOST_AUTO_TEST_CASE(CreateNewBlock_validity) { // Note that by default, these tests run with size accounting enabled. const auto chainParams = CreateChainParams(CBaseChainParams::MAIN); const CChainParams& chainparams = *chainParams; CScript scriptPubKey = CScript() << ParseHex("04678afdb0fe5548271967f1a67130b7105cd6a828e03909a67962e0ea1f61deb649f6bc3f4cef38c4f35504e51ec112de5c384df7ba0b8d578a4c702b6bf11d5f") << OP_CHECKSIG; std::unique_ptr<CBlockTemplate> pblocktemplate; CMutableTransaction tx,tx2; CScript script; uint256 hash; TestMemPoolEntryHelper entry; entry.nFee = 11; entry.nHeight = 11; fCheckpointsEnabled = false; // Simple block creation, nothing special yet: BOOST_CHECK(pblocktemplate = AssemblerForTest(chainparams).CreateNewBlock(scriptPubKey)); // We can't make transactions until we have inputs // Therefore, load 100 blocks :) int baseheight = 0; std::vector<CTransactionRef> txFirst; for (unsigned int i = 0; i < sizeof(blockinfo)/sizeof(*blockinfo); ++i) { CBlock *pblock = &pblocktemplate->block; // pointer for convenience { LOCK(cs_main); pblock->nVersion = 1; pblock->nTime = chainActive.Tip()->GetMedianTimePast()+1; CMutableTransaction txCoinbase(*pblock->vtx[0]); txCoinbase.nVersion = 1; txCoinbase.vin[0].scriptSig = CScript(); txCoinbase.vin[0].scriptSig.push_back(blockinfo[i].extranonce); txCoinbase.vin[0].scriptSig.push_back(chainActive.Height()); txCoinbase.vout.resize(1); // Ignore the (optional) segwit commitment added by CreateNewBlock (as the hardcoded nonces don't account for this) txCoinbase.vout[0].scriptPubKey = CScript(); pblock->vtx[0] = MakeTransactionRef(std::move(txCoinbase)); if (txFirst.size() == 0) baseheight = chainActive.Height(); if (txFirst.size() < 4) txFirst.push_back(pblock->vtx[0]); pblock->hashMerkleRoot = BlockMerkleRoot(*pblock); pblock->nNonce = blockinfo[i].nonce; } std::shared_ptr<const CBlock> shared_pblock = std::make_shared<const CBlock>(*pblock); BOOST_CHECK(ProcessNewBlock(chainparams, shared_pblock, true, nullptr)); pblock->hashPrevBlock = pblock->GetHash(); } LOCK(cs_main); // Just to make sure we can still make simple blocks BOOST_CHECK(pblocktemplate = AssemblerForTest(chainparams).CreateNewBlock(scriptPubKey)); const CAmount BLOCKSUBSIDY = 50*COIN; const CAmount LOWFEE = CENT; const CAmount HIGHFEE = COIN; const CAmount HIGHERFEE = 4*COIN; // block sigops > limit: 1000 CHECKMULTISIG + 1 tx.vin.resize(1); // NOTE: OP_NOP is used to force 20 SigOps for the CHECKMULTISIG tx.vin[0].scriptSig = CScript() << OP_0 << OP_0 << OP_0 << OP_NOP << OP_CHECKMULTISIG << OP_1; tx.vin[0].prevout.hash = txFirst[0]->GetHash(); tx.vin[0].prevout.n = 0; tx.vout.resize(1); tx.vout[0].nValue = BLOCKSUBSIDY; for (unsigned int i = 0; i < 1001; ++i) { tx.vout[0].nValue -= LOWFEE; hash = tx.GetHash(); bool spendsCoinbase = i == 0; // only first tx spends coinbase // If we don't set the # of sig ops in the CTxMemPoolEntry, template creation fails mempool.addUnchecked(hash, entry.Fee(LOWFEE).Time(GetTime()).SpendsCoinbase(spendsCoinbase).FromTx(tx)); tx.vin[0].prevout.hash = hash; } BOOST_CHECK_EXCEPTION(AssemblerForTest(chainparams).CreateNewBlock(scriptPubKey), std::runtime_error, HasReason("bad-blk-sigops")); mempool.clear(); tx.vin[0].prevout.hash = txFirst[0]->GetHash(); tx.vout[0].nValue = BLOCKSUBSIDY; for (unsigned int i = 0; i < 1001; ++i) { tx.vout[0].nValue -= LOWFEE; hash = tx.GetHash(); bool spendsCoinbase = i == 0; // only first tx spends coinbase // If we do set the # of sig ops in the CTxMemPoolEntry, template creation passes mempool.addUnchecked(hash, entry.Fee(LOWFEE).Time(GetTime()).SpendsCoinbase(spendsCoinbase).SigOpsCost(80).FromTx(tx)); tx.vin[0].prevout.hash = hash; } BOOST_CHECK(pblocktemplate = AssemblerForTest(chainparams).CreateNewBlock(scriptPubKey)); mempool.clear(); // block size > limit tx.vin[0].scriptSig = CScript(); // 18 * (520char + DROP) + OP_1 = 9433 bytes std::vector<unsigned char> vchData(520); for (unsigned int i = 0; i < 18; ++i) tx.vin[0].scriptSig << vchData << OP_DROP; tx.vin[0].scriptSig << OP_1; tx.vin[0].prevout.hash = txFirst[0]->GetHash(); tx.vout[0].nValue = BLOCKSUBSIDY; for (unsigned int i = 0; i < 128; ++i) { tx.vout[0].nValue -= LOWFEE; hash = tx.GetHash(); bool spendsCoinbase = i == 0; // only first tx spends coinbase mempool.addUnchecked(hash, entry.Fee(LOWFEE).Time(GetTime()).SpendsCoinbase(spendsCoinbase).FromTx(tx)); tx.vin[0].prevout.hash = hash; } BOOST_CHECK(pblocktemplate = AssemblerForTest(chainparams).CreateNewBlock(scriptPubKey)); mempool.clear(); // orphan in mempool, template creation fails hash = tx.GetHash(); mempool.addUnchecked(hash, entry.Fee(LOWFEE).Time(GetTime()).FromTx(tx)); BOOST_CHECK_EXCEPTION(AssemblerForTest(chainparams).CreateNewBlock(scriptPubKey), std::runtime_error, HasReason("bad-txns-inputs-missingorspent")); mempool.clear(); // child with higher feerate than parent tx.vin[0].scriptSig = CScript() << OP_1; tx.vin[0].prevout.hash = txFirst[1]->GetHash(); tx.vout[0].nValue = BLOCKSUBSIDY-HIGHFEE; hash = tx.GetHash(); mempool.addUnchecked(hash, entry.Fee(HIGHFEE).Time(GetTime()).SpendsCoinbase(true).FromTx(tx)); tx.vin[0].prevout.hash = hash; tx.vin.resize(2); tx.vin[1].scriptSig = CScript() << OP_1; tx.vin[1].prevout.hash = txFirst[0]->GetHash(); tx.vin[1].prevout.n = 0; tx.vout[0].nValue = tx.vout[0].nValue+BLOCKSUBSIDY-HIGHERFEE; //First txn output + fresh coinbase - new txn fee hash = tx.GetHash(); mempool.addUnchecked(hash, entry.Fee(HIGHERFEE).Time(GetTime()).SpendsCoinbase(true).FromTx(tx)); BOOST_CHECK(pblocktemplate = AssemblerForTest(chainparams).CreateNewBlock(scriptPubKey)); mempool.clear(); // coinbase in mempool, template creation fails tx.vin.resize(1); tx.vin[0].prevout.SetNull(); tx.vin[0].scriptSig = CScript() << OP_0 << OP_1; tx.vout[0].nValue = 0; hash = tx.GetHash(); // give it a fee so it'll get mined mempool.addUnchecked(hash, entry.Fee(LOWFEE).Time(GetTime()).SpendsCoinbase(false).FromTx(tx)); // Should throw bad-cb-multiple BOOST_CHECK_EXCEPTION(AssemblerForTest(chainparams).CreateNewBlock(scriptPubKey), std::runtime_error, HasReason("bad-cb-multiple")); mempool.clear(); // double spend txn pair in mempool, template creation fails tx.vin[0].prevout.hash = txFirst[0]->GetHash(); tx.vin[0].scriptSig = CScript() << OP_1; tx.vout[0].nValue = BLOCKSUBSIDY-HIGHFEE; tx.vout[0].scriptPubKey = CScript() << OP_1; hash = tx.GetHash(); mempool.addUnchecked(hash, entry.Fee(HIGHFEE).Time(GetTime()).SpendsCoinbase(true).FromTx(tx)); tx.vout[0].scriptPubKey = CScript() << OP_2; hash = tx.GetHash(); mempool.addUnchecked(hash, entry.Fee(HIGHFEE).Time(GetTime()).SpendsCoinbase(true).FromTx(tx)); BOOST_CHECK_EXCEPTION(AssemblerForTest(chainparams).CreateNewBlock(scriptPubKey), std::runtime_error, HasReason("bad-txns-inputs-missingorspent")); mempool.clear(); // subsidy changing int nHeight = chainActive.Height(); // Create an actual 209999-long block chain (without valid blocks). while (chainActive.Tip()->nHeight < 839999) { CBlockIndex* prev = chainActive.Tip(); CBlockIndex* next = new CBlockIndex(); next->phashBlock = new uint256(InsecureRand256()); pcoinsTip->SetBestBlock(next->GetBlockHash()); next->pprev = prev; next->nHeight = prev->nHeight + 1; next->BuildSkip(); chainActive.SetTip(next); } BOOST_CHECK(pblocktemplate = AssemblerForTest(chainparams).CreateNewBlock(scriptPubKey)); // Extend to a 210000-long block chain. while (chainActive.Tip()->nHeight < 170000) { CBlockIndex* prev = chainActive.Tip(); CBlockIndex* next = new CBlockIndex(); next->phashBlock = new uint256(InsecureRand256()); pcoinsTip->SetBestBlock(next->GetBlockHash()); next->pprev = prev; next->nHeight = prev->nHeight + 1; next->BuildSkip(); chainActive.SetTip(next); } BOOST_CHECK(pblocktemplate = AssemblerForTest(chainparams).CreateNewBlock(scriptPubKey)); // invalid p2sh txn in mempool, template creation fails tx.vin[0].prevout.hash = txFirst[0]->GetHash(); tx.vin[0].prevout.n = 0; tx.vin[0].scriptSig = CScript() << OP_1; tx.vout[0].nValue = BLOCKSUBSIDY-LOWFEE; script = CScript() << OP_0; tx.vout[0].scriptPubKey = GetScriptForDestination(CScriptID(script)); hash = tx.GetHash(); mempool.addUnchecked(hash, entry.Fee(LOWFEE).Time(GetTime()).SpendsCoinbase(true).FromTx(tx)); tx.vin[0].prevout.hash = hash; tx.vin[0].scriptSig = CScript() << std::vector<unsigned char>(script.begin(), script.end()); tx.vout[0].nValue -= LOWFEE; hash = tx.GetHash(); mempool.addUnchecked(hash, entry.Fee(LOWFEE).Time(GetTime()).SpendsCoinbase(false).FromTx(tx)); // Should throw block-validation-failed BOOST_CHECK_EXCEPTION(AssemblerForTest(chainparams).CreateNewBlock(scriptPubKey), std::runtime_error, HasReason("block-validation-failed")); mempool.clear(); // Delete the dummy blocks again. while (chainActive.Tip()->nHeight > nHeight) { CBlockIndex* del = chainActive.Tip(); chainActive.SetTip(del->pprev); pcoinsTip->SetBestBlock(del->pprev->GetBlockHash()); delete del->phashBlock; delete del; } // non-final txs in mempool SetMockTime(chainActive.Tip()->GetMedianTimePast()+1); int flags = LOCKTIME_VERIFY_SEQUENCE|LOCKTIME_MEDIAN_TIME_PAST; // height map std::vector<int> prevheights; // relative height locked tx.nVersion = 2; tx.vin.resize(1); prevheights.resize(1); tx.vin[0].prevout.hash = txFirst[0]->GetHash(); // only 1 transaction tx.vin[0].prevout.n = 0; tx.vin[0].scriptSig = CScript() << OP_1; tx.vin[0].nSequence = chainActive.Tip()->nHeight + 1; // txFirst[0] is the 2nd block prevheights[0] = baseheight + 1; tx.vout.resize(1); tx.vout[0].nValue = BLOCKSUBSIDY-HIGHFEE; tx.vout[0].scriptPubKey = CScript() << OP_1; tx.nLockTime = 0; hash = tx.GetHash(); mempool.addUnchecked(hash, entry.Fee(HIGHFEE).Time(GetTime()).SpendsCoinbase(true).FromTx(tx)); BOOST_CHECK(CheckFinalTx(tx, flags)); // Locktime passes BOOST_CHECK(!TestSequenceLocks(tx, flags)); // Sequence locks fail BOOST_CHECK(SequenceLocks(tx, flags, &prevheights, CreateBlockIndex(chainActive.Tip()->nHeight + 2))); // Sequence locks pass on 2nd block // relative time locked tx.vin[0].prevout.hash = txFirst[1]->GetHash(); tx.vin[0].nSequence = CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG | (((chainActive.Tip()->GetMedianTimePast()+1-chainActive[1]->GetMedianTimePast()) >> CTxIn::SEQUENCE_LOCKTIME_GRANULARITY) + 1); // txFirst[1] is the 3rd block prevheights[0] = baseheight + 2; hash = tx.GetHash(); mempool.addUnchecked(hash, entry.Time(GetTime()).FromTx(tx)); BOOST_CHECK(CheckFinalTx(tx, flags)); // Locktime passes BOOST_CHECK(!TestSequenceLocks(tx, flags)); // Sequence locks fail for (int i = 0; i < CBlockIndex::nMedianTimeSpan; i++) chainActive.Tip()->GetAncestor(chainActive.Tip()->nHeight - i)->nTime += 512; //Trick the MedianTimePast BOOST_CHECK(SequenceLocks(tx, flags, &prevheights, CreateBlockIndex(chainActive.Tip()->nHeight + 1))); // Sequence locks pass 512 seconds later for (int i = 0; i < CBlockIndex::nMedianTimeSpan; i++) chainActive.Tip()->GetAncestor(chainActive.Tip()->nHeight - i)->nTime -= 512; //undo tricked MTP // absolute height locked tx.vin[0].prevout.hash = txFirst[2]->GetHash(); tx.vin[0].nSequence = CTxIn::SEQUENCE_FINAL - 1; prevheights[0] = baseheight + 3; tx.nLockTime = chainActive.Tip()->nHeight + 1; hash = tx.GetHash(); mempool.addUnchecked(hash, entry.Time(GetTime()).FromTx(tx)); BOOST_CHECK(!CheckFinalTx(tx, flags)); // Locktime fails BOOST_CHECK(TestSequenceLocks(tx, flags)); // Sequence locks pass BOOST_CHECK(IsFinalTx(tx, chainActive.Tip()->nHeight + 2, chainActive.Tip()->GetMedianTimePast())); // Locktime passes on 2nd block // absolute time locked tx.vin[0].prevout.hash = txFirst[3]->GetHash(); tx.nLockTime = chainActive.Tip()->GetMedianTimePast(); prevheights.resize(1); prevheights[0] = baseheight + 4; hash = tx.GetHash(); mempool.addUnchecked(hash, entry.Time(GetTime()).FromTx(tx)); BOOST_CHECK(!CheckFinalTx(tx, flags)); // Locktime fails BOOST_CHECK(TestSequenceLocks(tx, flags)); // Sequence locks pass BOOST_CHECK(IsFinalTx(tx, chainActive.Tip()->nHeight + 2, chainActive.Tip()->GetMedianTimePast() + 1)); // Locktime passes 1 second later // mempool-dependent transactions (not added) tx.vin[0].prevout.hash = hash; prevheights[0] = chainActive.Tip()->nHeight + 1; tx.nLockTime = 0; tx.vin[0].nSequence = 0; BOOST_CHECK(CheckFinalTx(tx, flags)); // Locktime passes BOOST_CHECK(TestSequenceLocks(tx, flags)); // Sequence locks pass tx.vin[0].nSequence = 1; BOOST_CHECK(!TestSequenceLocks(tx, flags)); // Sequence locks fail tx.vin[0].nSequence = CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG; BOOST_CHECK(TestSequenceLocks(tx, flags)); // Sequence locks pass tx.vin[0].nSequence = CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG | 1; BOOST_CHECK(!TestSequenceLocks(tx, flags)); // Sequence locks fail BOOST_CHECK(pblocktemplate = AssemblerForTest(chainparams).CreateNewBlock(scriptPubKey)); // None of the of the absolute height/time locked tx should have made // it into the template because we still check IsFinalTx in CreateNewBlock, // but relative locked txs will if inconsistently added to mempool. // For now these will still generate a valid template until BIP68 soft fork BOOST_CHECK_EQUAL(pblocktemplate->block.vtx.size(), 3); // However if we advance height by 1 and time by 512, all of them should be mined for (int i = 0; i < CBlockIndex::nMedianTimeSpan; i++) chainActive.Tip()->GetAncestor(chainActive.Tip()->nHeight - i)->nTime += 512; //Trick the MedianTimePast chainActive.Tip()->nHeight++; SetMockTime(chainActive.Tip()->GetMedianTimePast() + 1); BOOST_CHECK(pblocktemplate = AssemblerForTest(chainparams).CreateNewBlock(scriptPubKey)); BOOST_CHECK_EQUAL(pblocktemplate->block.vtx.size(), 5); chainActive.Tip()->nHeight--; SetMockTime(0); mempool.clear(); TestPackageSelection(chainparams, scriptPubKey, txFirst); fCheckpointsEnabled = true; } BOOST_AUTO_TEST_SUITE_END()
[ "jhones_willer@outlook.com" ]
jhones_willer@outlook.com
7f792881f4e304ec4ae04cfb873b45ac5eafc676
5fddb50361a6340fb23fa6a6bee337a1d12dd95a
/testaa/mypointer.h
f0907a831b250bdcfeaf83fb7fd9885a1bef563c
[]
no_license
tomaszblawucki/work
4bd21098b9201166dbc706d8ed15004f0294e9fe
222981b7d29fb516f2717cdc0090f10c29082de7
refs/heads/master
2021-01-01T04:44:01.341991
2017-07-28T11:15:12
2017-07-28T11:15:12
97,235,864
0
0
null
null
null
null
UTF-8
C++
false
false
1,762
h
#ifndef MYPOINTER_H #define MYPOINTER_H #include <iostream> #include <atomic> using namespace std; template <class P> class MyPointer { private: P* ptr; int* count; public: MyPointer(P &p): ptr(&p) { count = new int(1); std::cout<<"First instance of SP, Counter: "<<*count; std::cout<<" Value: "<<*ptr<<endl; } MyPointer(P *p): ptr(p) { count = new int(1); std::cout<<"First instance of SP, Counter: "<<*count; std::cout<<" Value: "<<*ptr<<endl; } MyPointer(const MyPointer &p):ptr(p.ptr) { count = p.count; *count += 1; std::cout << "Copying constructor\ninstance number: " << *count; std::cout<<" Value: "<<*ptr<<endl; } virtual ~MyPointer() { *count -= 1; std::cout<<"Deleting instance of SP, Counter: "<<*count<<endl; if(*count == 0) { std::cout<<"BEFORE DELETE NULLPTR!!!"<<endl; std::cout.flush(); delete ptr; std::cout<<"AFTER DELETE NULLPTR!!!"<<endl; std::cout.flush(); delete count; std::cout<<"Deleting ptr and counter"<<endl; }; } void reset(P *p) { *count -= 1; cout<<"Deleting instance of SP in RESET "<<*count<<endl; if(*count == 0) { std::cout<<"BEFORE DELETE NULLPTR!!!"<<endl; delete ptr; std::cout<<"AFTER DELETE NULLPTR!!!"<<endl; delete count; std::cout<<"Deleting ptr and counter"; }; count = new int(1); ptr = p; cout<<endl<<"Reseting, Value: "<<*ptr<<" Count:"<<*count<<endl; } P* getPtr(){return ptr;} }; #endif // MYPOINTER_H
[ "int_tobl@MobicaPL.local" ]
int_tobl@MobicaPL.local
58b7b33d7ccb58afeb89368e3489e0705776ee36
af87904e7513a2c21f41b4c343d865d3e6407ce0
/minSquareToSum.cpp
4aa818f501a9857088e15987881a9841b8dedd4c
[]
no_license
vshalprashr/hello-world
941399e5f8e12617acd3e1b9eebf6803b9924360
476010d1901ed16416b13cb62ea55fd2d558d33f
refs/heads/master
2021-04-29T13:53:57.610068
2020-03-28T08:36:59
2020-03-28T08:36:59
121,763,067
0
0
null
2020-03-28T08:40:44
2018-02-16T14:57:59
C++
UTF-8
C++
false
false
336
cpp
#include <iostream> using namespace std; int main() { int sum; cin >> sum; int ans[sum+1]; ans[0] = 0; ans[1] = 1; ans[2] = 2; ans[3] = 3; ans[4] = 1; for(int i=5 ; i<=sum ; i++){ ans[i] = i; for(int j=1 ; j*j<=i ; j++) if(ans[i] > ans[i-(j*j)]+1) ans[i] = 1+ans[i-(j*j)]; } cout << ans[sum] << endl; return 0; }
[ "noreply@github.com" ]
noreply@github.com
c80e0c60acb86385b4fbdacdd2729236fbeb20f0
17d0bbf2697c85d42c2773f8e16c0bc50c030c6a
/test/ble_nano_tests/ble_make_call_and_neopixel/nrf_neopixel.cpp
ea3700bead6b57cb156fb169870b14540856bdc4
[]
no_license
backupbrain/arduino-projects
17032ff11170e130e8eeef16e1c0f7b9cd4cc29b
d14b56d66e88b1e4cfd88bcee24df4fc80bf7c42
refs/heads/master
2023-02-03T17:02:48.575084
2020-12-23T21:45:39
2020-12-23T21:45:39
324,007,307
1
0
null
null
null
null
UTF-8
C++
false
false
5,639
cpp
/* Lava * * WS2812B Tricolor LED (neopixel) controller * * * Example code: neopixel_strip_t m_strip; uint8_t dig_pin_num = 6; uint8_t leds_per_strip = 24; uint8_t error; uint8_t led_to_enable = 10; uint8_t red = 255; uint8_t green = 0; uint8_t blue = 159; neopixel_init(&m_strip, dig_pin_num, leds_per_strip); neopixel_clear(&m_strip); error = neopixel_set_color_and_show(&m_strip, led_to_enable, red, green, blue); if (error) { //led_to_enable was not within number leds_per_strip } //clear and remove strip neopixel_clear(&m_strip); neopixel_destroy(&m_strip); * For use with BLE stack, see information below: - Include in main.c #include "ble_radio_notification.h" - Call (see nrf_soc.h: NRF_RADIO_NOTIFICATION_DISTANCES and NRF_APP_PRIORITIES) ble_radio_notification_init(NRF_APP_PRIORITY_xxx, NRF_RADIO_NOTIFICATION_DISTANCE_xxx, your_radio_callback_handler); - Create void your_radio_callback_handler(bool radio_active) { if (radio_active == false) { neopixel_show(&strip1); neopixel_show(&strip2); //...etc } } - Do not use neopixel_set_color_and_show(...) with BLE, instead use uint8_t neopixel_set_color(...); */ #include "mbed.h" // remove line if not using mbed #include <stdbool.h> #include <stdint.h> #include <stdlib.h> #include "nrf_delay.h" #include "nrf_gpio.h" #include "nrf_neopixel.h" void neopixel_init(neopixel_strip_t *strip, uint8_t pin_num, uint16_t num_leds) { strip->leds = (color_t*) malloc(sizeof(color_t) * num_leds); strip->pin_num = pin_num; strip->num_leds = num_leds; nrf_gpio_cfg_output(pin_num); NRF_GPIO->OUTCLR = (1UL << pin_num); for (int i = 0; i < num_leds; i++) { strip->leds[i].simple.g = 0; strip->leds[i].simple.r = 0; strip->leds[i].simple.b = 0; } } void neopixel_clear(neopixel_strip_t *strip) { for (int i = 0; i < strip->num_leds; i++) { strip->leds[i].simple.g = 0; strip->leds[i].simple.r = 0; strip->leds[i].simple.b = 0; } neopixel_show(strip); } void neopixel_show(neopixel_strip_t *strip) { const uint8_t PIN = strip->pin_num; NRF_GPIO->OUTCLR = (1UL << PIN); nrf_delay_us(50); for (int i = 0; i < strip->num_leds; i++) { for (int j = 0; j < 3; j++) { if ((strip->leds[i].grb[j] & 128) > 0) {NEOPIXEL_SEND_ONE} else {NEOPIXEL_SEND_ZERO} if ((strip->leds[i].grb[j] & 64) > 0) {NEOPIXEL_SEND_ONE} else {NEOPIXEL_SEND_ZERO} if ((strip->leds[i].grb[j] & 32) > 0) {NEOPIXEL_SEND_ONE} else {NEOPIXEL_SEND_ZERO} if ((strip->leds[i].grb[j] & 16) > 0) {NEOPIXEL_SEND_ONE} else {NEOPIXEL_SEND_ZERO} if ((strip->leds[i].grb[j] & 8) > 0) {NEOPIXEL_SEND_ONE} else {NEOPIXEL_SEND_ZERO} if ((strip->leds[i].grb[j] & 4) > 0) {NEOPIXEL_SEND_ONE} else {NEOPIXEL_SEND_ZERO} if ((strip->leds[i].grb[j] & 2) > 0) {NEOPIXEL_SEND_ONE} else {NEOPIXEL_SEND_ZERO} if ((strip->leds[i].grb[j] & 1) > 0) {NEOPIXEL_SEND_ONE} else {NEOPIXEL_SEND_ZERO} } } } uint8_t neopixel_set_color(neopixel_strip_t *strip, uint16_t index, uint8_t red, uint8_t green, uint8_t blue ) { if (index < strip->num_leds) { strip->leds[index].simple.r = red; strip->leds[index].simple.g = green; strip->leds[index].simple.b = blue; } else return 1; return 0; } uint8_t neopixel_set_color_and_show(neopixel_strip_t *strip, uint16_t index, uint8_t red, uint8_t green, uint8_t blue) { if (index < strip->num_leds) { strip->leds[index].simple.r = red; strip->leds[index].simple.g = green; strip->leds[index].simple.b = blue; neopixel_show(strip); } else return 1; return 0; } void neopixel_destroy(neopixel_strip_t *strip) { free(strip->leds); strip->num_leds = 0; strip->pin_num = 0; } /* int main() { DigitalOut mypin(D4); neopixel_strip_t m_strip; uint8_t dig_pin_num = P0_21; uint8_t leds_per_strip = 30; uint8_t error; uint8_t led_to_enable = 30; uint8_t red = 0; uint8_t green = 128; uint8_t blue = 128; neopixel_init(&m_strip, dig_pin_num, leds_per_strip); neopixel_clear(&m_strip); //error = neopixel_set_color_and_show(&m_strip, led_to_enable, red, green, blue); for (int cv=0; cv < 60; cv++) { neopixel_set_color_and_show(&m_strip, cv, red, green, blue); wait_ms(500); } if (error) { //led_to_enable was not within number leds_per_strip } //error = neopixel_set_color_and_show(&m_strip, 1, red, green, blue); while (1) { wait_ms(500); } //clear and remove strip //neopixel_clear(&m_strip); //neopixel_destroy(&m_strip); } */
[ "backupbrain@gmail.com" ]
backupbrain@gmail.com
041ceee3baa4f079af9f0704d2a66ca58829b417
f26c339df4516ac76f465aaaeb87d01cad6a857c
/ultrasonic/ultrasonic.ino
68c5e188d1e264fffa3583cf0036078b247ff02a
[]
no_license
antrikshsrivastava/arduino-projects
d1a0d269c447071bd4e52080669753e0298cddfb
6dac011d74e82b474f4e805d2e408af41674084d
refs/heads/master
2021-01-21T11:07:59.194360
2015-02-18T14:12:34
2015-02-18T14:12:34
30,866,250
1
0
null
null
null
null
UTF-8
C++
false
false
1,558
ino
/* HC-SR04 Ping distance sensor] VCC to arduino 5v GND to arduino GND Echo to Arduino pin 13 Trig to Arduino pin 12 Red POS to Arduino pin 11 Green POS to Arduino pin 10 560 ohm resistor to both LED NEG and GRD power rail More info at: http://goo.gl/kJ8Gl Original code improvements to the Ping sketch sourced from Trollmaker.com Some code and wiring inspired by http://en.wikiversity.org/wiki/User:Dstaub/robotcar */ #define trigPin 13 #define echoPin 12 #define led 11 #define led2 10 //#define LEDPin 13 int maximumRange = 200; // Maximum range needed int minimumRange = 0; // Minimum range needed long duration, distance; // Duration used to calculate distance void setup() { Serial.begin (9600); pinMode(trigPin, OUTPUT); pinMode(echoPin, INPUT); } void loop() { /* The following trigPin/echoPin cycle is used to determine the distance of the nearest object by bouncing soundwaves off of it. */ digitalWrite(trigPin, LOW); delayMicroseconds(2); digitalWrite(trigPin, HIGH); delayMicroseconds(10); digitalWrite(trigPin, LOW); duration = pulseIn(echoPin, HIGH); //Calculate the distance (in cm) based on the speed of sound. distance = duration/58.2; if (distance >= maximumRange || distance <= minimumRange){ /* Send a negative number to computer and Turn LED ON to indicate "out of range" */ Serial.println("-1"); } else { /* Send the distance to the computer using Serial protocol, and turn LED OFF to indicate successful reading. */ Serial.println(distance); } //Delay 50ms before next reading. delay(50); }
[ "darkblade4@gmail.com" ]
darkblade4@gmail.com
14edc8ab58adbf85f0fce88f5875099edcd12acf
faacd0003e0c749daea18398b064e16363ea8340
/modules/module.template.cpp
b20e76f256785403125704c0e3353e10c16f5c39
[]
no_license
yjfcool/lyxcar
355f7a4df7e4f19fea733d2cd4fee968ffdf65af
750be6c984de694d7c60b5a515c4eb02c3e8c723
refs/heads/master
2016-09-10T10:18:56.638922
2009-09-29T06:03:19
2009-09-29T06:03:19
42,575,701
0
0
null
null
null
null
UTF-8
C++
false
false
798
cpp
/* * Copyright (C) 2008 Pavlov Denis * * Comments unavailable. * * 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 any later version. * */ #include "module_template.h" templateModuleApplet::templateModuleApplet(QWidget *parent) { } templateModuleApplet::~templateModuleApplet() { } void templateModule::activate(QWidget *parent) { } void templateModule::activatePeriodically(QWidget *parent) { } // // @brief Adding an applet to panel into specified position. // void templateModule::appendToPanel(QWidget *parent, int position) { } Q_EXPORT_PLUGIN2(template, templateModule);
[ "futurelink.vl@9e60f810-e830-11dd-9b7c-bbba4c9295f9" ]
futurelink.vl@9e60f810-e830-11dd-9b7c-bbba4c9295f9
eaf67cd113d7d2586d780f9d4e6e249856ccb845
c7f811db6b8aee8e6a54c8a8e2b05564b122e58d
/example/pipes/accept.hpp
89353f3db67821be96d933f71b23d1d614bd7dc9
[ "BSL-1.0" ]
permissive
ricejasonf/nbdl
aa4592001e4b3875175dc5b6274013d6d5fc7e69
ae63717c96ab2c36107bc17b2b00115f96e9d649
refs/heads/master
2023-06-07T20:33:54.496716
2020-07-14T03:11:44
2020-07-16T08:29:33
41,518,328
47
6
BSL-1.0
2018-05-04T05:31:27
2015-08-28T00:39:52
C++
UTF-8
C++
false
false
1,248
hpp
// // Copyright Jason Rice 2016 // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // #ifndef NBDL_EXAMPLE_PIPES_ACCEPT_HPP #define NBDL_EXAMPLE_PIPES_ACCEPT_HPP #include <asio.hpp> #include <nbdl.hpp> #include "connect.hpp" // for example::port namespace example { // accepts a single connection struct accept_fn { using tcp = asio::ip::tcp; tcp::endpoint endpoint; tcp::socket socket; nbdl::optional<tcp::acceptor> acceptor; accept_fn(asio::io_service& io, port port_) : endpoint(tcp::v4(), port_.value) , socket(io) { } template <typename Resolver, typename ...Args> void operator()(Resolver&& resolver, Args&& ...) { tcp::acceptor acceptor_(socket.get_io_service(), endpoint); acceptor_.async_accept(socket, [&](std::error_code error) { if (!error) { resolver.resolve(socket); } else { resolver.reject(error); } }); acceptor = std::move(acceptor_); } }; auto accept = [](asio::io_service& io, port port_) { return nbdl::promise(accept_fn(io, port_)); }; } #endif
[ "ricejasonf@gmail.com" ]
ricejasonf@gmail.com
eca1acae75af59550355f290f3a2405b9deb3816
ab91c1368772e2ba39024d20021f3e2f28765fc1
/SortSystem/DlgSortSystemSQL.cpp
7f8f162b7c40ef90985e53999d91f2f5cdf18635
[]
no_license
yuanhaosh/SortSystem
48a957a1d0bdcf17c7dfa3d82b0f33df0fd3b270
b14a73e909d156a5723a84bc68113905a78ec47c
refs/heads/master
2016-09-05T09:13:34.228585
2015-08-06T10:50:05
2015-08-06T10:50:05
40,297,964
3
0
null
null
null
null
GB18030
C++
false
false
1,932
cpp
// DlgSortSystemSQL.cpp : 实现文件 // #include "stdafx.h" #include "SortSystem.h" #include "DlgSortSystemSQL.h" #include "afxdialogex.h" #include "DlgSortSystemOperater.h" // CDlgSortSystemSQL 对话框 IMPLEMENT_DYNAMIC(CDlgSortSystemSQL, CDialogEx) CDlgSortSystemSQL::CDlgSortSystemSQL(CWnd* pParent /*=NULL*/) : CDialogEx(CDlgSortSystemSQL::IDD, pParent) { } CDlgSortSystemSQL::~CDlgSortSystemSQL() { } void CDlgSortSystemSQL::DoDataExchange(CDataExchange* pDX) { CDialogEx::DoDataExchange(pDX); DDX_Control(pDX, IDC_DATAGRID1, m_grid); } BEGIN_MESSAGE_MAP(CDlgSortSystemSQL, CDialogEx) ON_BN_CLICKED(IDC_BUTTON1, &CDlgSortSystemSQL::OnBnClickedButton1) ON_WM_CLOSE() ON_BN_CLICKED(IDC_BUTTON2, &CDlgSortSystemSQL::OnBnClickedButton2) END_MESSAGE_MAP() // CDlgSortSystemSQL 消息处理程序 BOOL CDlgSortSystemSQL::OnInitDialog() { CDialogEx::OnInitDialog(); // TODO: 在此添加额外的初始化 cAdo.CreateInstance(); cAdo.SetConnectionString(); if(cAdo.OpenConnection() == false) return FALSE; return TRUE; // return TRUE unless you set the focus to a control // 异常: OCX 属性页应返回 FALSE } void CDlgSortSystemSQL::OnClose() { // TODO: 在此添加消息处理程序代码和/或调用默认值 ASSERT(m_pOwerFrm); ::PostMessageA( reinterpret_cast<CDlgSortSystemOperater*>(m_pOwerFrm)->m_hWnd, WM_DISPLAYOWERDIALOG, 0, 0 ); CDialogEx::OnClose(); } void CDlgSortSystemSQL::OnBnClickedButton1() { // TODO: 在此添加控件通知处理程序代码 cAdo.OpenRecordset("select * from test"); m_grid.SetRefDataSource(NULL); m_grid.SetRefDataSource((LPUNKNOWN)cAdo.m_ptrRecordset); m_grid.Refresh(); } void CDlgSortSystemSQL::OnBnClickedButton2() { // TODO: 在此添加控件通知处理程序代码 cAdo.OpenRecordset("select * from test2"); m_grid.SetRefDataSource(NULL); m_grid.SetRefDataSource((LPUNKNOWN)cAdo.m_ptrRecordset); m_grid.Refresh(); }
[ "yuanhaosh@live.cn" ]
yuanhaosh@live.cn
e901ddabce762a56887eda9349e78d15881efffb
ade2e355ca83c8ee6c6fc182602d725236c6ead3
/headers/core/loaders/png_loader.h
3d1f837e57ea2aedaa8ba54fa233ebad4ee6a2af
[ "MIT" ]
permissive
madwareru/mrl_2020
19ce9ee3f80d64a1eb9a36169358ce6e37f75b35
49ecccab8650135b55cd85bc9cc05727b4474cae
refs/heads/master
2020-12-14T03:39:44.146134
2020-02-04T05:40:36
2020-02-04T05:40:36
234,625,487
1
0
null
null
null
null
UTF-8
C++
false
false
455
h
#pragma once #include <memory> #include <string> namespace core::render { struct SOASpriteRGB; struct SOASpriteRGBA; } namespace core::loaders { std::shared_ptr<core::render::SOASpriteRGB> load_sprite_from_png_24(const std::string& memory_buffer); std::shared_ptr<core::render::SOASpriteRGB> load_sprite_from_png_24(const char* filename); std::shared_ptr<core::render::SOASpriteRGBA> load_sprite_from_png_32(const char* filename); }
[ "madware.ru@gmail.com" ]
madware.ru@gmail.com
25416603643dcedf07aefb940b71cb3a03a02488
7c370470ab01b36e2fd15887061e833770aeb76f
/Source/NewLife/Private/UMG/UWInteractiveObjectMark.cpp
aae192026f6163b53eeaf9a54b38e8919e168095
[]
no_license
nik3122/NewLife
aba0cddd87ebfe378b96d25d87500edc81da9241
dbb9ad39b47aedf1e125674f39e94be49eadef5c
refs/heads/main
2023-07-14T12:16:16.100095
2021-09-02T02:16:27
2021-09-02T02:16:27
null
0
0
null
null
null
null
UTF-8
C++
false
false
475
cpp
// Made By Park Joo Hyeong. This is my first Portfollio. #include "UMG/UWInteractiveObjectMark.h" #include "Components/Image.h" void UUWInteractiveObjectMark::SetMarkDot() { Mark->SetBrushFromTexture(Dot); } void UUWInteractiveObjectMark::SetMarkCircleDot() { Mark->SetBrushFromTexture(CircleDot); } void UUWInteractiveObjectMark::NativeConstruct() { Super::NativeConstruct(); Mark = Cast<UImage>(GetWidgetFromName("DSN_Mark")); Mark->SetBrushFromTexture(Dot); }
[ "ordy.farmer2@gmail.com" ]
ordy.farmer2@gmail.com
f8c18fd8c3d922821bea2cfa738040a9bd33bfaa
a076a140aa44516cb099f57b519b33e380f10474
/main.cpp
b5f037f66d9ab6f2ac384df451c9b5c21decbd23
[]
no_license
Fokkksy/7.2_4sem
acc5b803699c649b6ba5e8b6d52288f766929900
c159ee3bd16d9fb932816a312878565f9dab6e6a
refs/heads/master
2023-03-27T23:44:27.077655
2021-03-25T19:16:44
2021-03-25T19:16:44
351,548,456
0
0
null
null
null
null
UTF-8
C++
false
false
2,362
cpp
#include <algorithm> #include <future> #include <fstream> #include <iostream> #include <numeric> #include <thread> #include <vector> #include "Timer.hpp" class Threads_Guard { public: explicit Threads_Guard(std::vector < std::thread >& threads) : m_threads(threads) {} Threads_Guard(Threads_Guard const&) = delete; Threads_Guard& operator=(Threads_Guard const&) = delete; ~Threads_Guard() noexcept { try { for (std::size_t i = 0; i < m_threads.size(); ++i) { if (m_threads[i].joinable()) { m_threads[i].join(); } } } catch (...) { // std::abort(); } } private: std::vector < std::thread >& m_threads; }; template < typename Iterator, typename T > struct accumulate_block { T operator()(Iterator first, Iterator last) { return std::accumulate(first, last, T()); } }; template < typename Iterator, typename T > T parallel_accumulate(Iterator first, Iterator last, T init, std::size_t number_of_threads) { const std::size_t length = std::distance(first, last); if (!length) return init; const std::size_t number_threads = number_of_threads; const std::size_t block_size = length / number_threads; std::vector < std::future < T > > futures(number_threads - 1); std::vector < std::thread > threads(number_threads - 1); Threads_Guard guard(threads); Iterator block_start = first; for (std::size_t i = 0; i < (number_threads - 1); ++i) { Iterator block_end = block_start; std::advance(block_end, block_size); std::packaged_task < T(Iterator, Iterator) > task { accumulate_block < Iterator, T >() }; futures[i] = task.get_future(); threads[i] = std::thread(std::move(task), block_start, block_end); block_start = block_end; } T last_result = accumulate_block < Iterator, T >()(block_start, last); T result = init; for (std::size_t i = 0; i < (number_threads - 1); ++i) { result += futures[i].get(); } result += last_result; return result; } int main(int argc, char** argv) { std::vector< int > v(10000000); std::iota(v.begin(), v.end(), 1); std::size_t N = 10000; std::ofstream fout("output.txt"); fout << "number_of_threads,time" << std::endl; for (auto i = 1; i < N; ++i) { Timer t; parallel_accumulate(v.begin(), v.end(), 0, i); t.stop(); fout << i << "," << t.math() << std::endl; } system("pause"); return EXIT_SUCCESS; }
[ "nikitin.vl@phystech.edu" ]
nikitin.vl@phystech.edu
9441117bfd7d9ef25ee3640955994d38f36a8a1c
a2e82f378150528655eb27b3f471804041bf7a1c
/AtCoder/ABC/080/C/main.cpp
77a6b85f3128638682014e52e9bd08805b837a9d
[]
no_license
HiromuOhtsuka/procon
6c2192fa9b07637f0ef4bf9079d6db609fd367d0
184e3fa69c412fd883869c10b23b292f9bc73be1
refs/heads/master
2021-01-24T08:37:12.779999
2020-06-13T15:07:38
2020-06-13T15:07:38
58,292,303
1
0
null
null
null
null
UTF-8
C++
false
false
898
cpp
#include <iostream> #include <climits> #define INF (INT_MAX / 2) using namespace std; int main(){ ios::sync_with_stdio(false); cin.tie(0); int n; cin >> n; int f[n][5][2]; for(int i = 0; i < n; i++){ for(int j = 0; j < 5; j++){ cin >> f[i][j][0]; cin >> f[i][j][1]; } } int p[n][11]; for(int i = 0; i < n; i++){ for(int j = 0; j <= 10; j++){ cin >> p[i][j]; } } int ans = -INF; for(int s = 1; s < (1 << 10); s++){ int c[n]; fill(c, c + n, 0); for(int i = 0; i < n; i++){ for(int j = 0; j < 5; j++){ for(int k = 0; k < 2; k++){ if(f[i][j][k] == 1 && (s & (1 << (2 * j + k))) != 0){ c[i]++; } } } } int sum = 0; for(int i = 0; i < n; i++){ sum += p[i][c[i]]; } ans = max(ans, sum); } cout << ans << endl; return 0; }
[ "multiverse.yume.a12@gmail.com" ]
multiverse.yume.a12@gmail.com
186d00b3608bd567d9c9793be738d98c47bfc099
eec3a013b04682301a3f72571f847f46f735a36d
/modelview/basicmodelsexample/DirWidget.cpp
9e9654d82a76c10fd1428a291ae2db6998db41d7
[]
no_license
tiger-tiger/qtPractice
e71eeb70d806b5f20dceaab5a24e94439ce42343
da7418436f8a1b0c4bc0ff829f7e55bf4339453e
refs/heads/master
2021-12-05T15:00:20.488163
2015-08-11T17:55:40
2015-08-11T17:55:40
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,128
cpp
#include "DirWidget.h" DirWidget::DirWidget(QWidget* parent) : QWidget(parent){ QDesktopWidget d; resize(d.height()*0.65, d.width()*0.65); mLayout = new QGridLayout(this); mDirModel = new QFileSystemModel; mDirModel->setRootPath(QDir::currentPath()); top_left = new QListView; top_right = new QListView; button_left = new QTreeView; button_right = new QTableView; setupWidgets(); this->setLayout(mLayout); } void DirWidget::setupWidgets(){ mLayout->addWidget(top_left, 0,0,1,1); top_left->setViewMode(QListView::ListMode); top_left->setModel(mDirModel); mLayout->addWidget(top_right, 0,1,1,1); top_right->setViewMode(QListView::IconMode); top_right->setModel(mDirModel); mLayout->addWidget(button_left,1,0,1,1); button_left->setModel(mDirModel); mLayout->addWidget(button_right,1,1,1,1); button_right->setModel(mDirModel); top_left->setRootIndex(mDirModel->index(QDir::currentPath())); top_right->setRootIndex(mDirModel->index(QDir::currentPath())); button_left->setRootIndex(mDirModel->index(QDir::currentPath()).parent()); button_right->setRootIndex(mDirModel->index(QDir::currentPath())); }
[ "prego@usc.edu" ]
prego@usc.edu
9e33043f0996412cb85ca50c3d9bc9c10bb804d2
9b54ae5d188ebd8281fa4a568622620b5432723b
/module04/ex02/AssaultTerminator.cpp
0bcd4f7a42144026075329183c3b967a4872ebc9
[]
no_license
mohit-ashar/CPP
5796f907c19e9e5cf158723d76c681fedda8d031
9d7d0dd6930b77adf7155dbc10887ad91f86563a
refs/heads/master
2021-05-17T11:30:22.383339
2020-05-07T13:10:53
2020-05-07T13:10:53
250,754,900
0
1
null
null
null
null
UTF-8
C++
false
false
1,047
cpp
#include "AssaultTerminator.hpp" AssaultTerminator::AssaultTerminator() { std::cout << "* teleports from space *" << std::endl; } AssaultTerminator::AssaultTerminator(AssaultTerminator const & a_terminator) { (void)a_terminator; std::cout << "* teleports from space *" << std::endl; } AssaultTerminator::~AssaultTerminator() { std::cout << "I’ll be back..." << std::endl; } ISpaceMarine* AssaultTerminator::clone() const { return (new AssaultTerminator(*this)); } void AssaultTerminator::battleCry() const { std::cout << "This code is unclean. PURIFY IT!" << std::endl; } void AssaultTerminator::rangedAttack() const { std::cout << "* does nothing *" << std::endl; } void AssaultTerminator::meleeAttack() const { std::cout << "* attacks with chainfists *"<< std::endl; } AssaultTerminator & AssaultTerminator::operator=(AssaultTerminator const & a_terminator) { (void)a_terminator; return(*this); }
[ "mohitashar1995@gmail.com" ]
mohitashar1995@gmail.com
b42a09627232d012f6f4c095a515193a8a9f5ef8
aa08e9f491901a395a064e8b556aca7e851c90a3
/BOJ/10000/17370.cpp
4d73c8b3f6040f66fd5bbf36cb900648c1f9c848
[]
no_license
SW0000J/PS
90180df101f984236f89c423a348fd7f45d1a517
f2b81e5a3a941537e532f440e1557b1eb2ae4d36
refs/heads/main
2023-07-03T19:56:37.087078
2021-08-10T13:51:12
2021-08-10T13:51:12
338,591,696
0
0
null
null
null
null
UTF-8
C++
false
false
1,168
cpp
#include <iostream> #include <algorithm> #include <map> using namespace std; int N; int ans = 0; int dx[6] = { 0, 1, 1, 0, -1, -1 }; int dy[6] = { 2, 1, -1, -2, -1, 1 }; map<pair<int, int>, int> visit; void dfs(int x, int y, int dirNum, int moveCount) { if (moveCount == N) { if (visit.find(make_pair(x, y)) != visit.end()) { //for (auto i = visit.begin(); i != visit.end(); i++) { // cout << "x: " << x << ", " << "y: " << y << "\n"; // cout << "key: <" << i->first.first << ", " << i->first.second << "> " << ", " << i->second << "\n"; //} //cout << "\n"; ans++; } return; } if (visit.find(make_pair(x, y)) != visit.end()) { return; } //cout << "x: " << x << ", " << "y: " << y << "\n"; visit[make_pair(x, y)] = true; int rightDir = (dirNum + 1) % 6; int leftDir = (dirNum + 5) % 6; dfs(x + dx[rightDir], y + dy[rightDir], rightDir, moveCount + 1); dfs(x + dx[leftDir], y + dy[leftDir], leftDir, moveCount + 1); visit.erase(make_pair(x, y)); } int main() { ios::sync_with_stdio(false); cout.tie(NULL); cin.tie(NULL); cin >> N; visit[make_pair(0, 0)] = 0; dfs(0, 2, 0, 0); cout << ans << "\n"; return 0; }
[ "64199550+SW0000J@users.noreply.github.com" ]
64199550+SW0000J@users.noreply.github.com
fba8eb2eff2a5ef2b15e27bf7151a2a130d39475
48d94294e1fffdcb2b79ffa123e039e4a0680ebb
/LowestCommonAncestorBST.cpp
abd8a8252a34dadafa363d83256b0ec3834597a0
[]
no_license
saivempali/Competitve-Programming
5c8ef75154b0e12def4746f821985fe83c1f917e
c7454becb5c7185297b15ae09f725870f19e7fca
refs/heads/master
2021-01-10T04:35:01.151819
2017-03-21T04:52:20
2017-03-21T04:52:20
44,494,499
0
0
null
null
null
null
UTF-8
C++
false
false
1,519
cpp
/* Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BST. According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes v and w as the lowest node in T that has both v and w as descendants (where we allow a node to be a descendant of itself).” _______6______ / \ ___2__ ___8__ / \ / \ 0 _4 7 9 / \ 3 5 For example, the lowest common ancestor (LCA) of nodes 2 and 8 is 6. Another example is LCA of nodes 2 and 4 is 2, since a node can be a descendant of itself according to the LCA definition. */ /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) { if(p == NULL || q == NULL || root == NULL) return root; if(p->val < root->val && q->val < root->val) { root = root->left; return lowestCommonAncestor(root,p,q); } else if(p->val > root->val && q->val > root->val) { root = root->right; return lowestCommonAncestor(root,p,q); } return root; } };
[ "sai.vempali@gmail.com" ]
sai.vempali@gmail.com
d0895ff9d468311acfce0d3e3d7a43a51fea339a
c98812885e4173fc57ef1a1fb43b92c119cb7daf
/src/p2p/base/port.cc
0f2b2c668b46855772808ee1ef54f972624cc698
[ "LicenseRef-scancode-google-patent-license-webrtc", "BSD-3-Clause" ]
permissive
dusxmt/tg_owt
b42d1d420640445b4af99447582b7a72bb7b4386
ceef372ff87c1b6b9ab925cb30ccd00388f8fe73
refs/heads/master
2023-05-02T08:04:47.410674
2020-09-10T11:18:39
2020-09-10T11:22:39
294,527,690
0
0
BSD-3-Clause
2020-09-10T21:35:52
2020-09-10T21:35:51
null
UTF-8
C++
false
false
33,797
cc
/* * Copyright 2004 The WebRTC Project Authors. All rights reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "p2p/base/port.h" #include <math.h> #include <algorithm> #include <memory> #include <utility> #include <vector> #include "absl/algorithm/container.h" #include "absl/strings/match.h" #include "p2p/base/connection.h" #include "p2p/base/port_allocator.h" #include "rtc_base/checks.h" #include "rtc_base/crc32.h" #include "rtc_base/helpers.h" #include "rtc_base/logging.h" #include "rtc_base/mdns_responder_interface.h" #include "rtc_base/message_digest.h" #include "rtc_base/network.h" #include "rtc_base/numerics/safe_minmax.h" #include "rtc_base/string_encode.h" #include "rtc_base/string_utils.h" #include "rtc_base/strings/string_builder.h" #include "rtc_base/third_party/base64/base64.h" #include "system_wrappers/include/field_trial.h" namespace { rtc::PacketInfoProtocolType ConvertProtocolTypeToPacketInfoProtocolType( cricket::ProtocolType type) { switch (type) { case cricket::ProtocolType::PROTO_UDP: return rtc::PacketInfoProtocolType::kUdp; case cricket::ProtocolType::PROTO_TCP: return rtc::PacketInfoProtocolType::kTcp; case cricket::ProtocolType::PROTO_SSLTCP: return rtc::PacketInfoProtocolType::kSsltcp; case cricket::ProtocolType::PROTO_TLS: return rtc::PacketInfoProtocolType::kTls; default: return rtc::PacketInfoProtocolType::kUnknown; } } // The delay before we begin checking if this port is useless. We set // it to a little higher than a total STUN timeout. const int kPortTimeoutDelay = cricket::STUN_TOTAL_TIMEOUT + 5000; } // namespace namespace cricket { using webrtc::RTCError; using webrtc::RTCErrorType; // TODO(ronghuawu): Use "local", "srflx", "prflx" and "relay". But this requires // the signaling part be updated correspondingly as well. const char LOCAL_PORT_TYPE[] = "local"; const char STUN_PORT_TYPE[] = "stun"; const char PRFLX_PORT_TYPE[] = "prflx"; const char RELAY_PORT_TYPE[] = "relay"; static const char* const PROTO_NAMES[] = {UDP_PROTOCOL_NAME, TCP_PROTOCOL_NAME, SSLTCP_PROTOCOL_NAME, TLS_PROTOCOL_NAME}; const char* ProtoToString(ProtocolType proto) { return PROTO_NAMES[proto]; } bool StringToProto(const char* value, ProtocolType* proto) { for (size_t i = 0; i <= PROTO_LAST; ++i) { if (absl::EqualsIgnoreCase(PROTO_NAMES[i], value)) { *proto = static_cast<ProtocolType>(i); return true; } } return false; } // RFC 6544, TCP candidate encoding rules. const int DISCARD_PORT = 9; const char TCPTYPE_ACTIVE_STR[] = "active"; const char TCPTYPE_PASSIVE_STR[] = "passive"; const char TCPTYPE_SIMOPEN_STR[] = "so"; std::string Port::ComputeFoundation(const std::string& type, const std::string& protocol, const std::string& relay_protocol, const rtc::SocketAddress& base_address) { rtc::StringBuilder sb; sb << type << base_address.ipaddr().ToString() << protocol << relay_protocol; return rtc::ToString(rtc::ComputeCrc32(sb.Release())); } CandidateStats::CandidateStats() = default; CandidateStats::CandidateStats(const CandidateStats&) = default; CandidateStats::CandidateStats(Candidate candidate) { this->candidate = candidate; } CandidateStats::~CandidateStats() = default; Port::Port(rtc::Thread* thread, const std::string& type, rtc::PacketSocketFactory* factory, rtc::Network* network, const std::string& username_fragment, const std::string& password) : thread_(thread), factory_(factory), type_(type), send_retransmit_count_attribute_(false), network_(network), min_port_(0), max_port_(0), component_(ICE_CANDIDATE_COMPONENT_DEFAULT), generation_(0), ice_username_fragment_(username_fragment), password_(password), timeout_delay_(kPortTimeoutDelay), enable_port_packets_(false), ice_role_(ICEROLE_UNKNOWN), tiebreaker_(0), shared_socket_(true), weak_factory_(this) { Construct(); } Port::Port(rtc::Thread* thread, const std::string& type, rtc::PacketSocketFactory* factory, rtc::Network* network, uint16_t min_port, uint16_t max_port, const std::string& username_fragment, const std::string& password) : thread_(thread), factory_(factory), type_(type), send_retransmit_count_attribute_(false), network_(network), min_port_(min_port), max_port_(max_port), component_(ICE_CANDIDATE_COMPONENT_DEFAULT), generation_(0), ice_username_fragment_(username_fragment), password_(password), timeout_delay_(kPortTimeoutDelay), enable_port_packets_(false), ice_role_(ICEROLE_UNKNOWN), tiebreaker_(0), shared_socket_(false), weak_factory_(this) { RTC_DCHECK(factory_ != NULL); Construct(); } void Port::Construct() { // TODO(pthatcher): Remove this old behavior once we're sure no one // relies on it. If the username_fragment and password are empty, // we should just create one. if (ice_username_fragment_.empty()) { RTC_DCHECK(password_.empty()); ice_username_fragment_ = rtc::CreateRandomString(ICE_UFRAG_LENGTH); password_ = rtc::CreateRandomString(ICE_PWD_LENGTH); } network_->SignalTypeChanged.connect(this, &Port::OnNetworkTypeChanged); network_cost_ = network_->GetCost(); thread_->PostDelayed(RTC_FROM_HERE, timeout_delay_, this, MSG_DESTROY_IF_DEAD); RTC_LOG(LS_INFO) << ToString() << ": Port created with network cost " << network_cost_; } Port::~Port() { // Delete all of the remaining connections. We copy the list up front // because each deletion will cause it to be modified. std::vector<Connection*> list; AddressMap::iterator iter = connections_.begin(); while (iter != connections_.end()) { list.push_back(iter->second); ++iter; } for (uint32_t i = 0; i < list.size(); i++) delete list[i]; } const std::string& Port::Type() const { return type_; } rtc::Network* Port::Network() const { return network_; } IceRole Port::GetIceRole() const { return ice_role_; } void Port::SetIceRole(IceRole role) { ice_role_ = role; } void Port::SetIceTiebreaker(uint64_t tiebreaker) { tiebreaker_ = tiebreaker; } uint64_t Port::IceTiebreaker() const { return tiebreaker_; } bool Port::SharedSocket() const { return shared_socket_; } void Port::SetIceParameters(int component, const std::string& username_fragment, const std::string& password) { component_ = component; ice_username_fragment_ = username_fragment; password_ = password; for (Candidate& c : candidates_) { c.set_component(component); c.set_username(username_fragment); c.set_password(password); } } const std::vector<Candidate>& Port::Candidates() const { return candidates_; } Connection* Port::GetConnection(const rtc::SocketAddress& remote_addr) { AddressMap::const_iterator iter = connections_.find(remote_addr); if (iter != connections_.end()) return iter->second; else return NULL; } void Port::AddAddress(const rtc::SocketAddress& address, const rtc::SocketAddress& base_address, const rtc::SocketAddress& related_address, const std::string& protocol, const std::string& relay_protocol, const std::string& tcptype, const std::string& type, uint32_t type_preference, uint32_t relay_preference, bool is_final) { AddAddress(address, base_address, related_address, protocol, relay_protocol, tcptype, type, type_preference, relay_preference, "", is_final); } void Port::AddAddress(const rtc::SocketAddress& address, const rtc::SocketAddress& base_address, const rtc::SocketAddress& related_address, const std::string& protocol, const std::string& relay_protocol, const std::string& tcptype, const std::string& type, uint32_t type_preference, uint32_t relay_preference, const std::string& url, bool is_final) { if (protocol == TCP_PROTOCOL_NAME && type == LOCAL_PORT_TYPE) { RTC_DCHECK(!tcptype.empty()); } std::string foundation = ComputeFoundation(type, protocol, relay_protocol, base_address); Candidate c(component_, protocol, address, 0U, username_fragment(), password_, type, generation_, foundation, network_->id(), network_cost_); c.set_priority( c.GetPriority(type_preference, network_->preference(), relay_preference)); c.set_relay_protocol(relay_protocol); c.set_tcptype(tcptype); c.set_network_name(network_->name()); c.set_network_type(network_->type()); c.set_url(url); c.set_related_address(related_address); bool pending = MaybeObfuscateAddress(&c, type, is_final); if (!pending) { FinishAddingAddress(c, is_final); } } bool Port::MaybeObfuscateAddress(Candidate* c, const std::string& type, bool is_final) { // TODO(bugs.webrtc.org/9723): Use a config to control the feature of IP // handling with mDNS. if (network_->GetMdnsResponder() == nullptr) { return false; } if (type != LOCAL_PORT_TYPE) { return false; } auto copy = *c; auto weak_ptr = weak_factory_.GetWeakPtr(); auto callback = [weak_ptr, copy, is_final](const rtc::IPAddress& addr, const std::string& name) mutable { RTC_DCHECK(copy.address().ipaddr() == addr); rtc::SocketAddress hostname_address(name, copy.address().port()); // In Port and Connection, we need the IP address information to // correctly handle the update of candidate type to prflx. The removal // of IP address when signaling this candidate will take place in // BasicPortAllocatorSession::OnCandidateReady, via SanitizeCandidate. hostname_address.SetResolvedIP(addr); copy.set_address(hostname_address); copy.set_related_address(rtc::SocketAddress()); if (weak_ptr != nullptr) { weak_ptr->set_mdns_name_registration_status( MdnsNameRegistrationStatus::kCompleted); weak_ptr->FinishAddingAddress(copy, is_final); } }; set_mdns_name_registration_status(MdnsNameRegistrationStatus::kInProgress); network_->GetMdnsResponder()->CreateNameForAddress(copy.address().ipaddr(), callback); return true; } void Port::FinishAddingAddress(const Candidate& c, bool is_final) { candidates_.push_back(c); SignalCandidateReady(this, c); PostAddAddress(is_final); } void Port::PostAddAddress(bool is_final) { if (is_final) { SignalPortComplete(this); } } void Port::AddOrReplaceConnection(Connection* conn) { auto ret = connections_.insert( std::make_pair(conn->remote_candidate().address(), conn)); // If there is a different connection on the same remote address, replace // it with the new one and destroy the old one. if (ret.second == false && ret.first->second != conn) { RTC_LOG(LS_WARNING) << ToString() << ": A new connection was created on an existing remote address. " "New remote candidate: " << conn->remote_candidate().ToSensitiveString(); ret.first->second->SignalDestroyed.disconnect(this); ret.first->second->Destroy(); ret.first->second = conn; } conn->SignalDestroyed.connect(this, &Port::OnConnectionDestroyed); SignalConnectionCreated(this, conn); } void Port::OnReadPacket(const char* data, size_t size, const rtc::SocketAddress& addr, ProtocolType proto) { // If the user has enabled port packets, just hand this over. if (enable_port_packets_) { SignalReadPacket(this, data, size, addr); return; } // If this is an authenticated STUN request, then signal unknown address and // send back a proper binding response. std::unique_ptr<IceMessage> msg; std::string remote_username; if (!GetStunMessage(data, size, addr, &msg, &remote_username)) { RTC_LOG(LS_ERROR) << ToString() << ": Received non-STUN packet from unknown address: " << addr.ToSensitiveString(); } else if (!msg) { // STUN message handled already } else if (msg->type() == STUN_BINDING_REQUEST) { RTC_LOG(LS_INFO) << "Received " << StunMethodToString(msg->type()) << " id=" << rtc::hex_encode(msg->transaction_id()) << " from unknown address " << addr.ToSensitiveString(); // We need to signal an unknown address before we handle any role conflict // below. Otherwise there would be no candidate pair and TURN entry created // to send the error response in case of a role conflict. SignalUnknownAddress(this, addr, proto, msg.get(), remote_username, false); // Check for role conflicts. if (!MaybeIceRoleConflict(addr, msg.get(), remote_username)) { RTC_LOG(LS_INFO) << "Received conflicting role from the peer."; return; } } else if (msg->type() == GOOG_PING_REQUEST) { // This is a PING sent to a connection that was destroyed. // Send back that this is the case and a authenticated BINDING // is needed. SendBindingErrorResponse(msg.get(), addr, STUN_ERROR_BAD_REQUEST, STUN_ERROR_REASON_BAD_REQUEST); } else { // NOTE(tschmelcher): STUN_BINDING_RESPONSE is benign. It occurs if we // pruned a connection for this port while it had STUN requests in flight, // because we then get back responses for them, which this code correctly // does not handle. if (msg->type() != STUN_BINDING_RESPONSE && msg->type() != GOOG_PING_RESPONSE && msg->type() != GOOG_PING_ERROR_RESPONSE) { RTC_LOG(LS_ERROR) << ToString() << ": Received unexpected STUN message type: " << msg->type() << " from unknown address: " << addr.ToSensitiveString(); } } } void Port::OnReadyToSend() { AddressMap::iterator iter = connections_.begin(); for (; iter != connections_.end(); ++iter) { iter->second->OnReadyToSend(); } } size_t Port::AddPrflxCandidate(const Candidate& local) { candidates_.push_back(local); return (candidates_.size() - 1); } bool Port::GetStunMessage(const char* data, size_t size, const rtc::SocketAddress& addr, std::unique_ptr<IceMessage>* out_msg, std::string* out_username) { // NOTE: This could clearly be optimized to avoid allocating any memory. // However, at the data rates we'll be looking at on the client side, // this probably isn't worth worrying about. RTC_DCHECK(out_msg != NULL); RTC_DCHECK(out_username != NULL); out_username->clear(); // Don't bother parsing the packet if we can tell it's not STUN. // In ICE mode, all STUN packets will have a valid fingerprint. // Except GOOG_PING_REQUEST/RESPONSE that does not send fingerprint. int types[] = {GOOG_PING_REQUEST, GOOG_PING_RESPONSE, GOOG_PING_ERROR_RESPONSE}; if (!StunMessage::IsStunMethod(types, data, size) && !StunMessage::ValidateFingerprint(data, size)) { return false; } // Parse the request message. If the packet is not a complete and correct // STUN message, then ignore it. std::unique_ptr<IceMessage> stun_msg(new IceMessage()); rtc::ByteBufferReader buf(data, size); if (!stun_msg->Read(&buf) || (buf.Length() > 0)) { return false; } // Get list of attributes in the "comprehension-required" range that were not // comprehended. If one or more is found, the behavior differs based on the // type of the incoming message; see below. std::vector<uint16_t> unknown_attributes = stun_msg->GetNonComprehendedAttributes(); if (stun_msg->type() == STUN_BINDING_REQUEST) { // Check for the presence of USERNAME and MESSAGE-INTEGRITY (if ICE) first. // If not present, fail with a 400 Bad Request. if (!stun_msg->GetByteString(STUN_ATTR_USERNAME) || !stun_msg->GetByteString(STUN_ATTR_MESSAGE_INTEGRITY)) { RTC_LOG(LS_ERROR) << ToString() << ": Received " << StunMethodToString(stun_msg->type()) << " without username/M-I from: " << addr.ToSensitiveString(); SendBindingErrorResponse(stun_msg.get(), addr, STUN_ERROR_BAD_REQUEST, STUN_ERROR_REASON_BAD_REQUEST); return true; } // If the username is bad or unknown, fail with a 401 Unauthorized. std::string local_ufrag; std::string remote_ufrag; if (!ParseStunUsername(stun_msg.get(), &local_ufrag, &remote_ufrag) || local_ufrag != username_fragment()) { RTC_LOG(LS_ERROR) << ToString() << ": Received " << StunMethodToString(stun_msg->type()) << " with bad local username " << local_ufrag << " from " << addr.ToSensitiveString(); SendBindingErrorResponse(stun_msg.get(), addr, STUN_ERROR_UNAUTHORIZED, STUN_ERROR_REASON_UNAUTHORIZED); return true; } // If ICE, and the MESSAGE-INTEGRITY is bad, fail with a 401 Unauthorized if (!stun_msg->ValidateMessageIntegrity(data, size, password_)) { RTC_LOG(LS_ERROR) << ToString() << ": Received " << StunMethodToString(stun_msg->type()) << " with bad M-I from " << addr.ToSensitiveString() << ", password_=" << password_; SendBindingErrorResponse(stun_msg.get(), addr, STUN_ERROR_UNAUTHORIZED, STUN_ERROR_REASON_UNAUTHORIZED); return true; } // If a request contains unknown comprehension-required attributes, reply // with an error. See RFC5389 section 7.3.1. if (!unknown_attributes.empty()) { SendUnknownAttributesErrorResponse(stun_msg.get(), addr, unknown_attributes); return true; } out_username->assign(remote_ufrag); } else if ((stun_msg->type() == STUN_BINDING_RESPONSE) || (stun_msg->type() == STUN_BINDING_ERROR_RESPONSE)) { if (stun_msg->type() == STUN_BINDING_ERROR_RESPONSE) { if (const StunErrorCodeAttribute* error_code = stun_msg->GetErrorCode()) { RTC_LOG(LS_ERROR) << ToString() << ": Received " << StunMethodToString(stun_msg->type()) << ": class=" << error_code->eclass() << " number=" << error_code->number() << " reason='" << error_code->reason() << "' from " << addr.ToSensitiveString(); // Return message to allow error-specific processing } else { RTC_LOG(LS_ERROR) << ToString() << ": Received " << StunMethodToString(stun_msg->type()) << " without a error code from " << addr.ToSensitiveString(); return true; } } // If a response contains unknown comprehension-required attributes, it's // simply discarded and the transaction is considered failed. See RFC5389 // sections 7.3.3 and 7.3.4. if (!unknown_attributes.empty()) { RTC_LOG(LS_ERROR) << ToString() << ": Discarding STUN response due to unknown " "comprehension-required attribute"; return true; } // NOTE: Username should not be used in verifying response messages. out_username->clear(); } else if (stun_msg->type() == STUN_BINDING_INDICATION) { RTC_LOG(LS_VERBOSE) << ToString() << ": Received " << StunMethodToString(stun_msg->type()) << ": from " << addr.ToSensitiveString(); out_username->clear(); // If an indication contains unknown comprehension-required attributes,[] // it's simply discarded. See RFC5389 section 7.3.2. if (!unknown_attributes.empty()) { RTC_LOG(LS_ERROR) << ToString() << ": Discarding STUN indication due to " "unknown comprehension-required attribute"; return true; } // No stun attributes will be verified, if it's stun indication message. // Returning from end of the this method. } else if (stun_msg->type() == GOOG_PING_REQUEST) { if (!stun_msg->ValidateMessageIntegrity32(data, size, password_)) { RTC_LOG(LS_ERROR) << ToString() << ": Received " << StunMethodToString(stun_msg->type()) << " with bad M-I from " << addr.ToSensitiveString() << ", password_=" << password_; SendBindingErrorResponse(stun_msg.get(), addr, STUN_ERROR_UNAUTHORIZED, STUN_ERROR_REASON_UNAUTHORIZED); return true; } RTC_LOG(LS_VERBOSE) << ToString() << ": Received " << StunMethodToString(stun_msg->type()) << " from " << addr.ToSensitiveString(); out_username->clear(); } else if (stun_msg->type() == GOOG_PING_RESPONSE || stun_msg->type() == GOOG_PING_ERROR_RESPONSE) { // note: the MessageIntegrity32 will be verified in Connection.cc RTC_LOG(LS_VERBOSE) << ToString() << ": Received " << StunMethodToString(stun_msg->type()) << " from " << addr.ToSensitiveString(); out_username->clear(); } else { RTC_LOG(LS_ERROR) << ToString() << ": Received STUN packet with invalid type (" << stun_msg->type() << ") from " << addr.ToSensitiveString(); return true; } // Return the STUN message found. *out_msg = std::move(stun_msg); return true; } bool Port::IsCompatibleAddress(const rtc::SocketAddress& addr) { // Get a representative IP for the Network this port is configured to use. rtc::IPAddress ip = network_->GetBestIP(); // We use single-stack sockets, so families must match. if (addr.family() != ip.family()) { return false; } // Link-local IPv6 ports can only connect to other link-local IPv6 ports. if (ip.family() == AF_INET6 && (IPIsLinkLocal(ip) != IPIsLinkLocal(addr.ipaddr()))) { return false; } return true; } rtc::DiffServCodePoint Port::StunDscpValue() const { // By default, inherit from whatever the MediaChannel sends. return rtc::DSCP_NO_CHANGE; } bool Port::ParseStunUsername(const StunMessage* stun_msg, std::string* local_ufrag, std::string* remote_ufrag) const { // The packet must include a username that either begins or ends with our // fragment. It should begin with our fragment if it is a request and it // should end with our fragment if it is a response. local_ufrag->clear(); remote_ufrag->clear(); const StunByteStringAttribute* username_attr = stun_msg->GetByteString(STUN_ATTR_USERNAME); if (username_attr == NULL) return false; // RFRAG:LFRAG const std::string username = username_attr->GetString(); size_t colon_pos = username.find(':'); if (colon_pos == std::string::npos) { return false; } *local_ufrag = username.substr(0, colon_pos); *remote_ufrag = username.substr(colon_pos + 1, username.size()); return true; } bool Port::MaybeIceRoleConflict(const rtc::SocketAddress& addr, IceMessage* stun_msg, const std::string& remote_ufrag) { // Validate ICE_CONTROLLING or ICE_CONTROLLED attributes. bool ret = true; IceRole remote_ice_role = ICEROLE_UNKNOWN; uint64_t remote_tiebreaker = 0; const StunUInt64Attribute* stun_attr = stun_msg->GetUInt64(STUN_ATTR_ICE_CONTROLLING); if (stun_attr) { remote_ice_role = ICEROLE_CONTROLLING; remote_tiebreaker = stun_attr->value(); } // If |remote_ufrag| is same as port local username fragment and // tie breaker value received in the ping message matches port // tiebreaker value this must be a loopback call. // We will treat this as valid scenario. if (remote_ice_role == ICEROLE_CONTROLLING && username_fragment() == remote_ufrag && remote_tiebreaker == IceTiebreaker()) { return true; } stun_attr = stun_msg->GetUInt64(STUN_ATTR_ICE_CONTROLLED); if (stun_attr) { remote_ice_role = ICEROLE_CONTROLLED; remote_tiebreaker = stun_attr->value(); } switch (ice_role_) { case ICEROLE_CONTROLLING: if (ICEROLE_CONTROLLING == remote_ice_role) { if (remote_tiebreaker >= tiebreaker_) { SignalRoleConflict(this); } else { // Send Role Conflict (487) error response. SendBindingErrorResponse(stun_msg, addr, STUN_ERROR_ROLE_CONFLICT, STUN_ERROR_REASON_ROLE_CONFLICT); ret = false; } } break; case ICEROLE_CONTROLLED: if (ICEROLE_CONTROLLED == remote_ice_role) { if (remote_tiebreaker < tiebreaker_) { SignalRoleConflict(this); } else { // Send Role Conflict (487) error response. SendBindingErrorResponse(stun_msg, addr, STUN_ERROR_ROLE_CONFLICT, STUN_ERROR_REASON_ROLE_CONFLICT); ret = false; } } break; default: RTC_NOTREACHED(); } return ret; } void Port::CreateStunUsername(const std::string& remote_username, std::string* stun_username_attr_str) const { stun_username_attr_str->clear(); *stun_username_attr_str = remote_username; stun_username_attr_str->append(":"); stun_username_attr_str->append(username_fragment()); } bool Port::HandleIncomingPacket(rtc::AsyncPacketSocket* socket, const char* data, size_t size, const rtc::SocketAddress& remote_addr, int64_t packet_time_us) { RTC_NOTREACHED(); return false; } bool Port::CanHandleIncomingPacketsFrom(const rtc::SocketAddress&) const { return false; } void Port::SendBindingErrorResponse(StunMessage* request, const rtc::SocketAddress& addr, int error_code, const std::string& reason) { RTC_DCHECK(request->type() == STUN_BINDING_REQUEST || request->type() == GOOG_PING_REQUEST); // Fill in the response message. StunMessage response; if (request->type() == STUN_BINDING_REQUEST) { response.SetType(STUN_BINDING_ERROR_RESPONSE); } else { response.SetType(GOOG_PING_ERROR_RESPONSE); } response.SetTransactionID(request->transaction_id()); // When doing GICE, we need to write out the error code incorrectly to // maintain backwards compatiblility. auto error_attr = StunAttribute::CreateErrorCode(); error_attr->SetCode(error_code); error_attr->SetReason(reason); response.AddAttribute(std::move(error_attr)); // Per Section 10.1.2, certain error cases don't get a MESSAGE-INTEGRITY, // because we don't have enough information to determine the shared secret. if (error_code != STUN_ERROR_BAD_REQUEST && error_code != STUN_ERROR_UNAUTHORIZED && request->type() != GOOG_PING_REQUEST) { if (request->type() == STUN_BINDING_REQUEST) { response.AddMessageIntegrity(password_); } else { response.AddMessageIntegrity32(password_); } } if (request->type() == STUN_BINDING_REQUEST) { response.AddFingerprint(); } // Send the response message. rtc::ByteBufferWriter buf; response.Write(&buf); rtc::PacketOptions options(StunDscpValue()); options.info_signaled_after_sent.packet_type = rtc::PacketType::kIceConnectivityCheckResponse; SendTo(buf.Data(), buf.Length(), addr, options, false); RTC_LOG(LS_INFO) << ToString() << ": Sending STUN " << StunMethodToString(response.type()) << ": reason=" << reason << " to " << addr.ToSensitiveString(); } void Port::SendUnknownAttributesErrorResponse( StunMessage* request, const rtc::SocketAddress& addr, const std::vector<uint16_t>& unknown_types) { RTC_DCHECK(request->type() == STUN_BINDING_REQUEST); // Fill in the response message. StunMessage response; response.SetType(STUN_BINDING_ERROR_RESPONSE); response.SetTransactionID(request->transaction_id()); auto error_attr = StunAttribute::CreateErrorCode(); error_attr->SetCode(STUN_ERROR_UNKNOWN_ATTRIBUTE); error_attr->SetReason(STUN_ERROR_REASON_UNKNOWN_ATTRIBUTE); response.AddAttribute(std::move(error_attr)); std::unique_ptr<StunUInt16ListAttribute> unknown_attr = StunAttribute::CreateUnknownAttributes(); for (uint16_t type : unknown_types) { unknown_attr->AddType(type); } response.AddAttribute(std::move(unknown_attr)); response.AddMessageIntegrity(password_); response.AddFingerprint(); // Send the response message. rtc::ByteBufferWriter buf; response.Write(&buf); rtc::PacketOptions options(StunDscpValue()); options.info_signaled_after_sent.packet_type = rtc::PacketType::kIceConnectivityCheckResponse; SendTo(buf.Data(), buf.Length(), addr, options, false); RTC_LOG(LS_ERROR) << ToString() << ": Sending STUN binding error: reason=" << STUN_ERROR_UNKNOWN_ATTRIBUTE << " to " << addr.ToSensitiveString(); } void Port::KeepAliveUntilPruned() { // If it is pruned, we won't bring it up again. if (state_ == State::INIT) { state_ = State::KEEP_ALIVE_UNTIL_PRUNED; } } void Port::Prune() { state_ = State::PRUNED; thread_->Post(RTC_FROM_HERE, this, MSG_DESTROY_IF_DEAD); } void Port::OnMessage(rtc::Message* pmsg) { RTC_DCHECK(pmsg->message_id == MSG_DESTROY_IF_DEAD); bool dead = (state_ == State::INIT || state_ == State::PRUNED) && connections_.empty() && rtc::TimeMillis() - last_time_all_connections_removed_ >= timeout_delay_; if (dead) { Destroy(); } } void Port::OnNetworkTypeChanged(const rtc::Network* network) { RTC_DCHECK(network == network_); UpdateNetworkCost(); } std::string Port::ToString() const { rtc::StringBuilder ss; ss << "Port[" << rtc::ToHex(reinterpret_cast<uintptr_t>(this)) << ":" << content_name_ << ":" << component_ << ":" << generation_ << ":" << type_ << ":" << network_->ToString() << "]"; return ss.Release(); } // TODO(honghaiz): Make the network cost configurable from user setting. void Port::UpdateNetworkCost() { uint16_t new_cost = network_->GetCost(); if (network_cost_ == new_cost) { return; } RTC_LOG(LS_INFO) << "Network cost changed from " << network_cost_ << " to " << new_cost << ". Number of candidates created: " << candidates_.size() << ". Number of connections created: " << connections_.size(); network_cost_ = new_cost; for (cricket::Candidate& candidate : candidates_) { candidate.set_network_cost(network_cost_); } // Network cost change will affect the connection selection criteria. // Signal the connection state change on each connection to force a // re-sort in P2PTransportChannel. for (const auto& kv : connections_) { Connection* conn = kv.second; conn->SignalStateChange(conn); } } void Port::EnablePortPackets() { enable_port_packets_ = true; } void Port::OnConnectionDestroyed(Connection* conn) { AddressMap::iterator iter = connections_.find(conn->remote_candidate().address()); RTC_DCHECK(iter != connections_.end()); connections_.erase(iter); HandleConnectionDestroyed(conn); // Ports time out after all connections fail if it is not marked as // "keep alive until pruned." // Note: If a new connection is added after this message is posted, but it // fails and is removed before kPortTimeoutDelay, then this message will // not cause the Port to be destroyed. if (connections_.empty()) { last_time_all_connections_removed_ = rtc::TimeMillis(); thread_->PostDelayed(RTC_FROM_HERE, timeout_delay_, this, MSG_DESTROY_IF_DEAD); } } void Port::Destroy() { RTC_DCHECK(connections_.empty()); RTC_LOG(LS_INFO) << ToString() << ": Port deleted"; SignalDestroyed(this); delete this; } const std::string Port::username_fragment() const { return ice_username_fragment_; } void Port::CopyPortInformationToPacketInfo(rtc::PacketInfo* info) const { info->protocol = ConvertProtocolTypeToPacketInfoProtocolType(GetProtocol()); info->network_id = Network()->id(); } } // namespace cricket
[ "johnprestonmail@gmail.com" ]
johnprestonmail@gmail.com
2e93764b0a2b851d7adbccadf213459a430fe3ee
3c91336750d4f1d98b621adb34ed81ea49fc6c13
/leetcode/can-place-flowers.cpp
9aa81c2f51469a65ebfb3ccee31639eb0b1f35e3
[]
no_license
arnabs542/Algorithm-and-Data-Structure
7c7bdbbac51c1d353df6b517e65454f587a4f76c
1caeb66af82b27637922bdef647431068342726a
refs/heads/master
2023-01-20T23:21:08.230209
2020-12-03T20:16:49
2020-12-03T20:16:49
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,430
cpp
//https://leetcode.com/problems/can-place-flowers/#/description /* Suppose you have a long flowerbed in which some of the plots are planted and some are not. However, flowers cannot be planted in adjacent plots - they would compete for water and both would die. Given a flowerbed (represented as an array containing 0 and 1, where 0 means empty and 1 means not empty), and a number n, return if n new flowers can be planted in it without violating the no-adjacent-flowers rule. Example 1: Input: flowerbed = [1,0,0,0,1], n = 1 Output: True Example 2: Input: flowerbed = [1,0,0,0,1], n = 2 Output: False */ bool canPlaceFlowers(vector<int>& flowerbed, int n) { int i = 0, count = 0; while (i < flowerbed.size()) { if (flowerbed[i] == 0 && (i == 0 || flowerbed[i - 1] == 0) && (i == flowerbed.size() - 1 || flowerbed[i + 1] == 0)) { flowerbed[i] = 1; count++; } if(count>=n) return true; i++; } return false; } //method 2: bool canPlaceFlowers(vector<int>& flowerbed, int n) { int i = 0, cnt = 0; for(int i=0;i<flowerbed.size() && cnt<n;i++){ if(flowerbed[i]==0){ int next = (i==flowerbed.size()-1)?0:flowerbed[i + 1]; int prev = (i==0)?0:flowerbed[i - 1]; if(next==0 && prev ==0){ flowerbed[i] = 1; cnt++; } } } return cnt==n; }
[ "zhangruiskyline@gmail.com" ]
zhangruiskyline@gmail.com
0af763d3ed4933b407453deb2e44c35f21dc947a
04f15913aca8a702efe47962bf82b60eedad73d9
/LibA/Analytics/Hyst.h
4cac597638dfec262a76e3f1b6cb8621d67e64cc
[]
no_license
DevilCCCP/Code
eae9b7f5a2fede346deefe603a817027a87ef753
9cc1a06e5010bb585876056a727abad48bca3915
refs/heads/master
2021-10-07T17:04:27.728918
2021-09-28T06:49:50
2021-09-28T06:49:50
166,522,458
0
1
null
null
null
null
UTF-8
C++
false
false
8,634
h
#pragma once #include <QVector> #include <QString> #include <QStringList> const int kHystDefaultLength = 256; const int kHystFastLength = 16; const int kHystFastShift = 4; class Hyst { const int mHystLength; QVector<int> mHyst; mutable int mTotalCount; public: int Length() const { return mHystLength; } int GetHyst(int index) const { return mHyst[index]; } const QVector<int>& GetVector() const { return mHyst; } const int* Data() const { return mHyst.constData(); } int* Data() { return mHyst.data(); } int Size() const { return mHyst.size(); } void Normalize(int maxCount) { if (mTotalCount < maxCount || maxCount <= 0) { return; } int divider = 2; for (mTotalCount /= 2; divider < 1024; mTotalCount /= 2, divider *= 2) { if (mTotalCount < maxCount) { break; } } mTotalCount = 0; for (int i = 0; i < mHystLength; i++) { mHyst[i] /= divider; mTotalCount += mHyst[i]; } } QString Serialize(int precision = 32) const { if (precision <= 0 || TotalCount() <= 0) { return ""; } else if (precision > mHystLength) { return "not implemented"; } QVector<double> hyst(precision); double totalCount = 0; for (int i = 0; i < precision; i++) { int from = (int)i * mHystLength / precision; int to = (int)(i + 1) * mHystLength / precision; hyst[i] = 0; for (int ii = from; ii < to; ii++) { hyst[i] += mHyst[ii]; } totalCount += hyst[i]; } QStringList resultList; int zero = 0; for (int i = 0; i < precision; i++) { double perc = hyst[i] * 100.0 / totalCount; if (perc < 0.01) { zero++; } else { zero = 0; } resultList.append(QString::number(perc, 'f', 2)); } while (zero > 0) { resultList.removeLast(); zero--; } return QString::number(mTotalCount) + "|" + resultList.join(';'); } bool Deserialize(const QString& text, int precision = 32) { int p1 = text.indexOf('|'); if (p1 < 0) { return false; } bool ok; mTotalCount = text.left(p1).toInt(&ok); if (!ok) { return false; } QStringList resultList = text.mid(p1 + 1).split(QChar(';')); mHyst.fill(0); QVector<double> hyst(mHystLength, (double)0); double totalPerc = 0; for (int i = 0; i < mHystLength; i++) { int ind = i * precision / mHystLength; if (ind >= resultList.size()) { break; } const QString& percText = resultList.at(ind); double value = percText.toDouble(&ok); if (!ok) { break; } hyst[i] = value; totalPerc += value; } int totalCount = mTotalCount; mTotalCount = 0; for (int i = 0; i < mHystLength; i++) { mHyst[i] = (int)(hyst[i] / totalPerc * totalCount); mTotalCount += mHyst[i]; } return true; } void Clear() { mHyst.fill(0); mTotalCount = 0; } void Inc(int ind) { mHyst[ind]++; mTotalCount++; } void SetLine(int ind) { mTotalCount -= mHyst[ind]; mHyst[ind] = mTotalCount; mTotalCount += mTotalCount; } void SetTotalCount(int _TotalCount) { mTotalCount = _TotalCount; } int TotalCount() const { if (!mTotalCount) { for (int i = 0; i < mHystLength; i++) { mTotalCount += mHyst[i]; } } return mTotalCount; } int GetValue(int per, int totalCount = 0) const { if (!totalCount) { totalCount = TotalCount(); } int cut = totalCount * (quint64)per / 1000LL; int count = 0; for (int i = 0; i < mHystLength; i++) { count += mHyst[i]; if (count > cut) { return i; } } return 0; } int GetMidValue(int perFrom, int perTo, int totalCount = 0) const { int min = GetValue(perFrom, totalCount); int max = GetValue(perTo, totalCount); return (min + max)/2; } int GetMaxRight() { mTotalCount = 0; int realCount = 0; for (int i = 0; i < mHystLength; i++) { if (mHyst[i]) { mTotalCount += mHyst[i]; realCount++; } } int midValue = mTotalCount / realCount; if (midValue > 0) { int mid1 = 2*midValue - 1; int mid2 = 4*midValue - 1; int count1 = 0; int count2 = 0; for (int i = 0; i < mHystLength; i++) { if (mHyst[i] > midValue) { count1++; if (mHyst[i] > mid2) { count2++; } } } if (count2 > realCount / 10 + 2) { midValue = mid2; } else if (count1 > realCount / 10 + 2) { midValue = mid1; } } int maxPos = mHystLength - 1; int maxValue = midValue; int maxConfirm = -1; int confirmLength = mHystLength / 100 + 1; for (int i = mHystLength - 1; i >= 0; i--) { if (mHyst[i] > maxValue) { if (maxConfirm < confirmLength || mHyst[i] > 8 * maxValue) { maxPos = i; maxValue = mHyst[maxPos]; maxConfirm = 0; } } else if (maxConfirm >= 0) { maxConfirm++; } } return maxPos; } int GetValueB(int per, int totalCount = 0) const { if (!totalCount) { totalCount = TotalCount(); } int cut = totalCount * (quint64)per / 1000LL; int count = 0; for (int i = mHystLength - 1; i >= 0; i--) { count += mHyst[i]; if (count > cut) { return i; } } return 0; } int GetLocalMax(int from, int to) const { int maxValue = 0; int maxIndex = from; for (int i = from; i < to; i++) { if (mHyst[i] > maxValue) { maxIndex = i; maxValue = mHyst[i]; } } return maxIndex; } int GetLocalDisp(int maxValue, int direction = 0) const { int max = mHyst[maxValue]; for (int i = 1; i < 256; i++) { if (direction <= 0) { int indl = maxValue - i; if (indl >= 0 && mHyst[indl] > max/4) { continue; } } if (direction >= 0) { int indr = maxValue + i; if (indr < 256 && mHyst[indr] > max/4) { continue; } } return i; } return 255; } int GetHystMass(int maxValue, int length) const { int mass = mHyst[maxValue]; for (int i = 1; i < length; i++) { int indl = maxValue - i; int indr = maxValue + i; if (indl >= 0) { mass += mHyst[indl]; } if (indr < 256) { mass += mHyst[indr]; } } return mass * 255LL / mTotalCount; } void MedianLow() { mTotalCount = mHyst[0] + mHyst[mHystLength - 1]; for (int i = 1; i < mHystLength - 1; i++) { if (mHyst[i] < mHyst[i-1] && mHyst[i] < mHyst[i+1]) { mHyst[i] = qMin(mHyst[i-1], mHyst[i+1]); } mTotalCount += mHyst[i]; } } Hyst(const int _HystLength = kHystDefaultLength) : mHystLength(_HystLength) , mHyst(_HystLength), mTotalCount(0) { Clear(); } }; class HystFast { int mHyst[kHystFastLength]; mutable int mTotalCount; public: int GetLength() const { return kHystFastLength; } void Clear() { memset(mHyst, 0, sizeof(mHyst)); } void Inc(int value) { mHyst[value>>kHystFastShift]++; } const int* Data() const { return mHyst; } int Size() const { return kHystFastLength; } int TotalCount() const { mTotalCount = 0; for (int i = 0; i < kHystFastLength; i++) { mTotalCount += mHyst[i]; } return mTotalCount; } void Add(const HystFast& other) { mTotalCount = 0; for (int i = 0; i < kHystFastLength; i++) { mHyst[i] += other.mHyst[i]; mTotalCount += mHyst[i]; } } int GetValue(int per) { if (!mTotalCount) { mTotalCount = TotalCount(); } int cut = mTotalCount * (quint64)per / 1000LL; int count = 0; for (int i = 0; i < kHystFastLength; i++) { count += mHyst[i]; if (count > cut) { return i << kHystFastShift; } } return 0; } int GetMidValue(int perFrom, int perTo) { int min = GetValue(perFrom); int max = GetValue(perTo); return (min + max)/2; } HystFast() : mTotalCount(0) { Clear(); } };
[ "DevilCCCP@gmail.com" ]
DevilCCCP@gmail.com
68d17ad9f923c7d867333032df682fae864d465e
8150a3b3c5bbee4192e4871ec3c0d12b7bbb127c
/BitBase/hash_trie_manager.hpp
aac8d1059099c7e18bb0a0d69ed3a0764d345584
[ "MIT" ]
permissive
lorabit/BitBase
661c4c3dc7cce7c2b4630c4fba7a8835d3783619
00d09e33d3e1db9b09ece7167e4019c54a9cd1fc
refs/heads/master
2021-01-13T15:25:13.182480
2017-10-25T02:45:37
2017-10-25T02:45:37
80,085,981
1
0
null
null
null
null
UTF-8
C++
false
false
1,111
hpp
// // hash_trie_manager.hpp // BitBase // // Created by lorabit on 18/03/2017. // Copyright © 2017 lorabit. All rights reserved. // #ifndef hash_trie_manager_hpp #define hash_trie_manager_hpp #include "page_manager.hpp" #include <stdio.h> struct HashTrieNode{ int value; int version; TrieNodePosition children[TRIENODE_LENGTH]; }; struct HashTrieBlock{ HashTrieNode nodes[TRIEBLOCK_LENGTH]; char padding[PAGE_SIZE - TRIEBLOCK_LENGTH*sizeof(HashTrieNode)]; }; class HashTrieManager{ private: PageManager* page_manager; HashTrieNode* root(); HashTrieNode* find_node(TrieNodePosition pos); HashTrieNode* find_node(string key, TrieNodePosition & pos); TrieNodePosition request_position(); public: HashTrieManager(PageManager* pageManager); versioned_value get_value(string key); bool update_node(string key, int value, int version); void update_trie_node(TrieNodePosition& c_pos, char key, TrieNodePosition& pos); void update_trie_node(TrieNodePosition& c_pos, int value, int version); }; #endif /* hash_trie_manager_hpp */
[ "conglaiwubei@163.com" ]
conglaiwubei@163.com
7b6f675eef3f9d9aa53bb03f4ba793d89264be0a
b9412984b1cf9be86620d43aeddd96f567ea9a57
/07OOP_18040206HanDaeHyun/Chapter(7-8)/Chapter(7-8).cpp
a1189428245611e649ccf38eb402edcb3c255349
[]
no_license
Daeja/techwing
cfbfb82268b7f0f33408fac972bdab73eef00da3
ee7a5ce36a2e2dbe0c2fd4f97e7989aaec8b457b
refs/heads/master
2020-03-13T04:34:18.945374
2018-04-25T07:20:59
2018-04-25T07:20:59
130,965,732
0
0
null
null
null
null
UHC
C++
false
false
1,200
cpp
#include "CLogger.h" int main() { // char * pcFileNameExtension = "txt"; char * pcFileNameExtension = NULL; CLogger logger(pcFileNameExtension); char * pcContent1 = "J015::Tray Flow Feeder Up/Down Cylinder 가(이) (하강) 동작 이상입니다."; char * pcContent2 = "Handler Running Stop"; char * pcContent3 = "Handler Running Start"; char * pcContent4 = "Z002::상단 Stacker(스테커) 도어가 열려있어 운전 할 수 없습니다.!!!"; char * pcContent5 = "N420::정상적으로 원점 복귀가 끝났습니다.!!!"; char * pcContent6 = "Z032::티칭 화면을 저어말로 실행합니까 ?"; char * pcContent7 = "C014::LOAD::Preciser Up/Down Cylinder 가(이) (상승) 동작 이상입니다."; char * pcContent8 = "내 이름은 한대현"; char * pcContent9 = "S/W 3팀 한대현 연구원"; logger.write(pcContent1); logger.write(pcContent2); logger.write(pcContent3); logger.write(pcContent4); Sleep(3000); if( true == 1 ) { logger.write(pcContent5); } else { logger.write(pcContent6); } logger.write(pcContent7); logger.write(pcContent8); Sleep(1000); logger.write(pcContent9); logger.write(NULL); // 방어코드 작성 return 0; }
[ "hyunx5@naver.com" ]
hyunx5@naver.com
9ba632f7d8c8477f1a0f02ac91777a6f12d28906
4c0a8ba88c847c671703bd673027878a3858d5e0
/src/main.cpp
1d4092db8a7e44adf3493b198166b951dc2b112a
[]
no_license
pierrep/InteractiveOrchestra
3a36561173f178cbe76149e29b5764ce23402603
8192a93eb2a4e47bc1c2bfc3847e7262b0be74fe
refs/heads/master
2021-01-21T18:06:13.869264
2017-05-24T02:46:38
2017-05-24T02:46:38
92,013,852
0
0
null
null
null
null
UTF-8
C++
false
false
530
cpp
#include "ofMain.h" #include "ofApp.h" //======================================================================== int main( ){ //ofSetLogLevel(OF_LOG_VERBOSE); ofGLFWWindowSettings settings; settings.setGLVersion(2, 1); settings.multiMonitorFullScreen = true; settings.width = 1920; settings.height = 1080; settings.windowMode = OF_GAME_MODE; // settings.width = 1280; // settings.height = 720; // settings.windowMode = OF_WINDOW; ofCreateWindow(settings); ofRunApp(new ofApp()); }
[ "Pierre Proske" ]
Pierre Proske
6fdb25713458b343706163452d3465a2ce9b3595
b171b3c12c620c932da230e0f1f6cb1da7f4a62b
/cpp/RemoveSortedList.h
cdf821e9f14da89573a78f771b55bd918142b680
[]
no_license
WolkeDu/leetcode
44865ff9caa97d0dcbf21ba48c056ae3540f3de5
4fa219525d64581e1ed77493c2c0fc6c15a4cbb0
refs/heads/master
2021-01-23T03:21:53.827519
2014-02-27T01:08:03
2014-02-27T01:08:03
null
0
0
null
null
null
null
UTF-8
C++
false
false
577
h
#include <iostream> // * Definition for singly-linked list. struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(NULL) {} }; class Solution { public: ListNode *deleteDuplicates(ListNode *head) { // Start typing your C/C++ solution below // DO NOT write int main() function if(head == NULL || head->next == NULL) return head; ListNode* cur = head; while(cur -> next != NULL){ if(cur->val == cur->next->val) cur->next = cur->next->next; else cur = cur->next; } return head; } };
[ "duf3434@gmail.com" ]
duf3434@gmail.com
36e2f25e8a8ad60633ee6455bbdade388bdaf9fc
511e39f07fe444c9cab4c6eede13af8350289cdf
/src/Access/EnabledRowPolicies.h
b92939afb0300d508023ed51b65bce579e8ea618
[ "Apache-2.0" ]
permissive
arenadata/ClickHouse
6340526a53c9cf5900eb0e4d6fd3c93742145a3b
1399ad1a29038c4e5e77401312631bce95b67f80
refs/heads/master
2023-08-17T01:23:49.007146
2020-07-21T11:48:19
2020-07-21T11:48:19
203,589,409
2
5
Apache-2.0
2022-06-27T08:59:19
2019-08-21T13:24:20
C++
UTF-8
C++
false
false
2,806
h
#pragma once #include <Access/RowPolicy.h> #include <Core/Types.h> #include <Core/UUID.h> #include <boost/smart_ptr/atomic_shared_ptr.hpp> #include <unordered_map> #include <memory> namespace DB { class IAST; using ASTPtr = std::shared_ptr<IAST>; /// Provides fast access to row policies' conditions for a specific user and tables. class EnabledRowPolicies { public: struct Params { UUID user_id; boost::container::flat_set<UUID> enabled_roles; auto toTuple() const { return std::tie(user_id, enabled_roles); } friend bool operator ==(const Params & lhs, const Params & rhs) { return lhs.toTuple() == rhs.toTuple(); } friend bool operator !=(const Params & lhs, const Params & rhs) { return !(lhs == rhs); } friend bool operator <(const Params & lhs, const Params & rhs) { return lhs.toTuple() < rhs.toTuple(); } friend bool operator >(const Params & lhs, const Params & rhs) { return rhs < lhs; } friend bool operator <=(const Params & lhs, const Params & rhs) { return !(rhs < lhs); } friend bool operator >=(const Params & lhs, const Params & rhs) { return !(lhs < rhs); } }; ~EnabledRowPolicies(); using ConditionType = RowPolicy::ConditionType; /// Returns prepared filter for a specific table and operations. /// The function can return nullptr, that means there is no filters applied. /// The returned filter can be a combination of the filters defined by multiple row policies. ASTPtr getCondition(const String & database, const String & table_name, ConditionType type) const; ASTPtr getCondition(const String & database, const String & table_name, ConditionType type, const ASTPtr & extra_condition) const; private: friend class RowPolicyCache; EnabledRowPolicies(const Params & params_); struct MixedConditionKey { std::string_view database; std::string_view table_name; ConditionType condition_type; auto toTuple() const { return std::tie(database, table_name, condition_type); } friend bool operator==(const MixedConditionKey & left, const MixedConditionKey & right) { return left.toTuple() == right.toTuple(); } friend bool operator!=(const MixedConditionKey & left, const MixedConditionKey & right) { return left.toTuple() != right.toTuple(); } }; struct Hash { size_t operator()(const MixedConditionKey & key) const; }; struct MixedCondition { ASTPtr ast; std::shared_ptr<const std::pair<String, String>> database_and_table_name; }; using MapOfMixedConditions = std::unordered_map<MixedConditionKey, MixedCondition, Hash>; const Params params; mutable boost::atomic_shared_ptr<const MapOfMixedConditions> map_of_mixed_conditions; }; }
[ "vitbar@yandex-team.ru" ]
vitbar@yandex-team.ru
4baafe0702bd9daf9f6cb4f2157353041292c3bb
3b56423a34de9b4adae13d0fee4905609a9e2410
/src/chain.h
938ec4318f3f84ddde6e5b4ec3385acaafa0d2be
[ "MIT" ]
permissive
mulecore/mule
5302db1cb6596475f9496495dba12b4d1cfd0d2c
9b2d9bf0ffc47963b5c0ce9b760cfff757961533
refs/heads/master
2023-03-27T02:25:49.455321
2021-03-26T10:31:13
2021-03-26T10:31:13
351,247,550
0
0
null
null
null
null
UTF-8
C++
false
false
16,564
h
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2016 The Bitcoin Core developers // Copyright (c) 2017-2020 The Mule Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef MULE_CHAIN_H #define MULE_CHAIN_H #include "arith_uint256.h" #include "primitives/block.h" #include "pow.h" #include "tinyformat.h" #include "uint256.h" #include <vector> /** * Maximum amount of time that a block timestamp is allowed to exceed the * current network-adjusted time before the block will be accepted. */ static const int64_t MAX_FUTURE_BLOCK_TIME = 2 * 60 * 60; static const int64_t MAX_FUTURE_BLOCK_TIME_DGW = MAX_FUTURE_BLOCK_TIME / 10; /** * Timestamp window used as a grace period by code that compares external * timestamps (such as timestamps passed to RPCs, or wallet key creation times) * to block timestamps. This should be set at least as high as * MAX_FUTURE_BLOCK_TIME. */ static const int64_t TIMESTAMP_WINDOW = MAX_FUTURE_BLOCK_TIME; class CBlockFileInfo { public: unsigned int nBlocks; //!< number of blocks stored in file unsigned int nSize; //!< number of used bytes of block file unsigned int nUndoSize; //!< number of used bytes in the undo file unsigned int nHeightFirst; //!< lowest height of block in file unsigned int nHeightLast; //!< highest height of block in file uint64_t nTimeFirst; //!< earliest time of block in file uint64_t nTimeLast; //!< latest time of block in file ADD_SERIALIZE_METHODS; template <typename Stream, typename Operation> inline void SerializationOp(Stream& s, Operation ser_action) { READWRITE(VARINT(nBlocks)); READWRITE(VARINT(nSize)); READWRITE(VARINT(nUndoSize)); READWRITE(VARINT(nHeightFirst)); READWRITE(VARINT(nHeightLast)); READWRITE(VARINT(nTimeFirst)); READWRITE(VARINT(nTimeLast)); } void SetNull() { nBlocks = 0; nSize = 0; nUndoSize = 0; nHeightFirst = 0; nHeightLast = 0; nTimeFirst = 0; nTimeLast = 0; } CBlockFileInfo() { SetNull(); } std::string ToString() const; /** update statistics (does not update nSize) */ void AddBlock(unsigned int nHeightIn, uint64_t nTimeIn) { if (nBlocks==0 || nHeightFirst > nHeightIn) nHeightFirst = nHeightIn; if (nBlocks==0 || nTimeFirst > nTimeIn) nTimeFirst = nTimeIn; nBlocks++; if (nHeightIn > nHeightLast) nHeightLast = nHeightIn; if (nTimeIn > nTimeLast) nTimeLast = nTimeIn; } }; struct CDiskBlockPos { int nFile; unsigned int nPos; ADD_SERIALIZE_METHODS; template <typename Stream, typename Operation> inline void SerializationOp(Stream& s, Operation ser_action) { READWRITE(VARINT(nFile)); READWRITE(VARINT(nPos)); } CDiskBlockPos() { SetNull(); } CDiskBlockPos(int nFileIn, unsigned int nPosIn) { nFile = nFileIn; nPos = nPosIn; } friend bool operator==(const CDiskBlockPos &a, const CDiskBlockPos &b) { return (a.nFile == b.nFile && a.nPos == b.nPos); } friend bool operator!=(const CDiskBlockPos &a, const CDiskBlockPos &b) { return !(a == b); } void SetNull() { nFile = -1; nPos = 0; } bool IsNull() const { return (nFile == -1); } std::string ToString() const { return strprintf("CBlockDiskPos(nFile=%i, nPos=%i)", nFile, nPos); } }; enum BlockStatus: uint32_t { //! Unused. BLOCK_VALID_UNKNOWN = 0, //! Parsed, version ok, hash satisfies claimed PoW, 1 <= vtx count <= max, timestamp not in future BLOCK_VALID_HEADER = 1, //! All parent headers found, difficulty matches, timestamp >= median previous, checkpoint. Implies all parents //! are also at least TREE. BLOCK_VALID_TREE = 2, /** * Only first tx is coinbase, 2 <= coinbase input script length <= 100, transactions valid, no duplicate txids, * sigops, size, merkle root. Implies all parents are at least TREE but not necessarily TRANSACTIONS. When all * parent blocks also have TRANSACTIONS, CBlockIndex::nChainTx will be set. */ BLOCK_VALID_TRANSACTIONS = 3, //! Outputs do not overspend inputs, no double spends, coinbase output ok, no immature coinbase spends, BIP30. //! Implies all parents are also at least CHAIN. BLOCK_VALID_CHAIN = 4, //! Scripts & signatures ok. Implies all parents are also at least SCRIPTS. BLOCK_VALID_SCRIPTS = 5, //! All validity bits. BLOCK_VALID_MASK = BLOCK_VALID_HEADER | BLOCK_VALID_TREE | BLOCK_VALID_TRANSACTIONS | BLOCK_VALID_CHAIN | BLOCK_VALID_SCRIPTS, BLOCK_HAVE_DATA = 8, //!< full block available in blk*.dat BLOCK_HAVE_UNDO = 16, //!< undo data available in rev*.dat BLOCK_HAVE_MASK = BLOCK_HAVE_DATA | BLOCK_HAVE_UNDO, BLOCK_FAILED_VALID = 32, //!< stage after last reached validness failed BLOCK_FAILED_CHILD = 64, //!< descends from failed block BLOCK_FAILED_MASK = BLOCK_FAILED_VALID | BLOCK_FAILED_CHILD, BLOCK_OPT_WITNESS = 128, //!< block data in blk*.data was received with a witness-enforcing client }; /** The block chain is a tree shaped structure starting with the * genesis block at the root, with each block potentially having multiple * candidates to be the next block. A blockindex may have multiple pprev pointing * to it, but at most one of them can be part of the currently active branch. */ class CBlockIndex { public: //! pointer to the hash of the block, if any. Memory is owned by this CBlockIndex const uint256* phashBlock; //! pointer to the index of the predecessor of this block CBlockIndex* pprev; //! pointer to the index of some further predecessor of this block CBlockIndex* pskip; //! height of the entry in the chain. The genesis block has height 0 int nHeight; //! Which # file this block is stored in (blk?????.dat) int nFile; //! Byte offset within blk?????.dat where this block's data is stored unsigned int nDataPos; //! Byte offset within rev?????.dat where this block's undo data is stored unsigned int nUndoPos; //! (memory only) Total amount of work (expected number of hashes) in the chain up to and including this block arith_uint256 nChainWork; //! Number of transactions in this block. //! Note: in a potential headers-first mode, this number cannot be relied upon unsigned int nTx; //! (memory only) Number of transactions in the chain up to and including this block. //! This value will be non-zero only if and only if transactions for this block and all its parents are available. //! Change to 64-bit type when necessary; won't happen before 2030 unsigned int nChainTx; //! Verification status of this block. See enum BlockStatus uint32_t nStatus; //! block header int32_t nVersion; uint256 hashMerkleRoot; uint32_t nTime; uint32_t nBits; uint32_t nNonce; // KAWPOW uint64_t nNonce64; uint256 mix_hash; //! (memory only) Sequential id assigned to distinguish order in which blocks are received. int32_t nSequenceId; //! (memory only) Maximum nTime in the chain up to and including this block. unsigned int nTimeMax; void SetNull() { phashBlock = nullptr; pprev = nullptr; pskip = nullptr; nHeight = 0; nFile = 0; nDataPos = 0; nUndoPos = 0; nChainWork = arith_uint256(); nTx = 0; nChainTx = 0; nStatus = 0; nSequenceId = 0; nTimeMax = 0; nVersion = 0; hashMerkleRoot = uint256(); nTime = 0; nBits = 0; nNonce = 0; //KAWPOW nNonce64 = 0; mix_hash = uint256(); } CBlockIndex() { SetNull(); } explicit CBlockIndex(const CBlockHeader& block) { SetNull(); nVersion = block.nVersion; hashMerkleRoot = block.hashMerkleRoot; nTime = block.nTime; nBits = block.nBits; nNonce = block.nNonce; //KAWPOW nHeight = block.nHeight; nNonce64 = block.nNonce64; mix_hash = block.mix_hash; } CDiskBlockPos GetBlockPos() const { CDiskBlockPos ret; if (nStatus & BLOCK_HAVE_DATA) { ret.nFile = nFile; ret.nPos = nDataPos; } return ret; } CDiskBlockPos GetUndoPos() const { CDiskBlockPos ret; if (nStatus & BLOCK_HAVE_UNDO) { ret.nFile = nFile; ret.nPos = nUndoPos; } return ret; } CBlockHeader GetBlockHeader() const { CBlockHeader block; block.nVersion = nVersion; if (pprev) block.hashPrevBlock = pprev->GetBlockHash(); block.hashMerkleRoot = hashMerkleRoot; block.nTime = nTime; block.nBits = nBits; block.nNonce = nNonce; block.nHeight = nHeight; block.nNonce64 = nNonce64; block.mix_hash = mix_hash; return block; } uint256 GetBlockHash() const { return *phashBlock; } int64_t GetBlockTime() const { return (int64_t)nTime; } int64_t GetBlockTimeMax() const { return (int64_t)nTimeMax; } enum { nMedianTimeSpan=11 }; int64_t GetMedianTimePast() const { int64_t pmedian[nMedianTimeSpan]; int64_t* pbegin = &pmedian[nMedianTimeSpan]; int64_t* pend = &pmedian[nMedianTimeSpan]; const CBlockIndex* pindex = this; for (int i = 0; i < nMedianTimeSpan && pindex; i++, pindex = pindex->pprev) *(--pbegin) = pindex->GetBlockTime(); std::sort(pbegin, pend); return pbegin[(pend - pbegin)/2]; } std::string ToString() const { return strprintf("CBlockIndex(pprev=%p, nHeight=%d, merkle=%s, hashBlock=%s)", pprev, nHeight, hashMerkleRoot.ToString(), GetBlockHash().ToString()); } //! Check whether this block index entry is valid up to the passed validity level. bool IsValid(enum BlockStatus nUpTo = BLOCK_VALID_TRANSACTIONS) const { assert(!(nUpTo & ~BLOCK_VALID_MASK)); // Only validity flags allowed. if (nStatus & BLOCK_FAILED_MASK) return false; return ((nStatus & BLOCK_VALID_MASK) >= nUpTo); } //! Raise the validity level of this block index entry. //! Returns true if the validity was changed. bool RaiseValidity(enum BlockStatus nUpTo) { assert(!(nUpTo & ~BLOCK_VALID_MASK)); // Only validity flags allowed. if (nStatus & BLOCK_FAILED_MASK) return false; if ((nStatus & BLOCK_VALID_MASK) < nUpTo) { nStatus = (nStatus & ~BLOCK_VALID_MASK) | nUpTo; return true; } return false; } //! Build the skiplist pointer for this entry. void BuildSkip(); //! Efficiently find an ancestor of this block. CBlockIndex* GetAncestor(int height); const CBlockIndex* GetAncestor(int height) const; }; arith_uint256 GetBlockProof(const CBlockIndex& block); /** Return the time it would take to redo the work difference between from and to, assuming the current hashrate corresponds to the difficulty at tip, in seconds. */ int64_t GetBlockProofEquivalentTime(const CBlockIndex& to, const CBlockIndex& from, const CBlockIndex& tip, const Consensus::Params&); /** Find the forking point between two chain tips. */ const CBlockIndex* LastCommonAncestor(const CBlockIndex* pa, const CBlockIndex* pb); /** Used to marshal pointers into hashes for db storage. */ class CDiskBlockIndex : public CBlockIndex { public: uint256 hashPrev; CDiskBlockIndex() { hashPrev = uint256(); } explicit CDiskBlockIndex(const CBlockIndex* pindex) : CBlockIndex(*pindex) { hashPrev = (pprev ? pprev->GetBlockHash() : uint256()); } ADD_SERIALIZE_METHODS; template <typename Stream, typename Operation> inline void SerializationOp(Stream& s, Operation ser_action) { int _nVersion = s.GetVersion(); if (!(s.GetType() & SER_GETHASH)) READWRITE(VARINT(_nVersion)); READWRITE(VARINT(nHeight)); READWRITE(VARINT(nStatus)); READWRITE(VARINT(nTx)); if (nStatus & (BLOCK_HAVE_DATA | BLOCK_HAVE_UNDO)) READWRITE(VARINT(nFile)); if (nStatus & BLOCK_HAVE_DATA) READWRITE(VARINT(nDataPos)); if (nStatus & BLOCK_HAVE_UNDO) READWRITE(VARINT(nUndoPos)); // block header READWRITE(this->nVersion); READWRITE(hashPrev); READWRITE(hashMerkleRoot); READWRITE(nTime); READWRITE(nBits); if (nTime < nKAWPOWActivationTime) { READWRITE(nNonce); } else { //KAWPOW READWRITE(nNonce64); READWRITE(mix_hash); } } uint256 GetBlockHash() const { CBlockHeader block; block.nVersion = nVersion; block.hashPrevBlock = hashPrev; block.hashMerkleRoot = hashMerkleRoot; block.nTime = nTime; block.nBits = nBits; block.nNonce = nNonce; block.nHeight = nHeight; block.nNonce64 = nNonce64; block.mix_hash = mix_hash; return block.GetHash(); } std::string ToString() const { std::string str = "CDiskBlockIndex("; str += CBlockIndex::ToString(); str += strprintf("\n hashBlock=%s, hashPrev=%s)", GetBlockHash().ToString(), hashPrev.ToString()); return str; } }; /** An in-memory indexed chain of blocks. */ class CChain { private: std::vector<CBlockIndex*> vChain; public: /** Returns the index entry for the genesis block of this chain, or nullptr if none. */ CBlockIndex *Genesis() const { return vChain.size() > 0 ? vChain[0] : nullptr; } /** Returns the index entry for the tip of this chain, or nullptr if none. */ CBlockIndex *Tip() const { return vChain.size() > 0 ? vChain[vChain.size() - 1] : nullptr; } /** Returns the index entry at a particular height in this chain, or nullptr if no such height exists. */ CBlockIndex *operator[](int nHeight) const { if (nHeight < 0 || nHeight >= (int)vChain.size()) return nullptr; return vChain[nHeight]; } /** Compare two chains efficiently. */ friend bool operator==(const CChain &a, const CChain &b) { return a.vChain.size() == b.vChain.size() && a.vChain[a.vChain.size() - 1] == b.vChain[b.vChain.size() - 1]; } /** Efficiently check whether a block is present in this chain. */ bool Contains(const CBlockIndex *pindex) const { return (*this)[pindex->nHeight] == pindex; } /** Find the successor of a block in this chain, or nullptr if the given index is not found or is the tip. */ CBlockIndex *Next(const CBlockIndex *pindex) const { if (Contains(pindex)) return (*this)[pindex->nHeight + 1]; else return nullptr; } /** Return the maximal height in the chain. Is equal to chain.Tip() ? chain.Tip()->nHeight : -1. */ int Height() const { return vChain.size() - 1; } /** Set/initialize a chain with a given tip. */ void SetTip(CBlockIndex *pindex); /** Return a CBlockLocator that refers to a block in this chain (by default the tip). */ CBlockLocator GetLocator(const CBlockIndex *pindex = nullptr) const; /** Find the last common block between this chain and a block index entry. */ const CBlockIndex *FindFork(const CBlockIndex *pindex) const; /** Find the earliest block with timestamp equal or greater than the given. */ CBlockIndex* FindEarliestAtLeast(int64_t nTime) const; }; #endif // MULE_CHAIN_H
[ "mule@muleda.com" ]
mule@muleda.com
4af4e274846b3122faf27b2a2ee668296e21faa2
e79eae4bb55eeef08a2f8e28de8dcf2adba9c647
/Source/Raymarcher.cpp
fdc5d87f0697beff582e950de9fa5743e7a235ee
[ "MIT" ]
permissive
Balajanovski/simple-raymarcher
ab1e080444eb20bb66740ef193e10b39819387cb
9349c5e081a0d65b93e746d420b893f920af7b38
refs/heads/master
2022-04-04T08:41:12.822564
2020-02-19T00:16:00
2020-02-19T00:16:00
114,095,156
19
4
MIT
2018-01-05T05:10:16
2017-12-13T08:36:16
C
UTF-8
C++
false
false
7,066
cpp
// // Created by Balajanovski on 14/12/2017. // #include "Raymarcher.h" #include "Geometry/Vec3f.h" #include "Geometry/Vec4f.h" #include "Geometry/Ray.h" #include "Color.h" #include "Constants.h" #include "ConfigManager.h" #include <cmath> #include <iostream> #include <thread> const Color Raymarcher::FOG_COLOR = {0.0f, 0.0f, 0.0f}; // Uses the gradient of the SDF to estimate the normal on the surface // Much more efficient than calculus void Raymarcher::estimate_normal(IN const Vec3f& point, OUT Vec3f& normal) { Intersection x_upper, x_lower, y_upper, y_lower, z_upper, z_lower; m_scene->sceneSDF(Vec3f(point.x() + epsilon, point.y(), point.z()), x_upper); m_scene->sceneSDF(Vec3f(point.x() - epsilon, point.y(), point.z()), x_lower); m_scene->sceneSDF(Vec3f(point.x(), point.y() + epsilon, point.z()), y_upper); m_scene->sceneSDF(Vec3f(point.x(), point.y() - epsilon, point.z()), y_lower); m_scene->sceneSDF(Vec3f(point.x(), point.y(), point.z() + epsilon), z_upper); m_scene->sceneSDF(Vec3f(point.x(), point.y(), point.z() - epsilon), z_lower); normal = (Vec3f( x_upper.distance() - x_lower.distance(), y_upper.distance() - y_lower.distance(), z_upper.distance() - z_lower.distance() )).normalize(); return; } void Raymarcher::march(IN const Ray& ray, OUT Intersection& output_intersection) { Vec3f position; Vec3f scaled; float total = 0.0f; for (int step = 0; step < MAX_MARCHING_STEPS; ++step) { scaled = ray.march(total); position = ConfigManager::instance().get_camera()->pos() + scaled; Intersection intersection; m_scene->sceneSDF(position, intersection); total += intersection.distance(); // Hits an object if (intersection.distance() < epsilon) { output_intersection = Intersection(total, intersection.material(), position); return; } // Does not hit an object if (intersection.distance() > Constants::MAX_RENDER_DISTANCE) { output_intersection = Intersection(Constants::MAX_RENDER_DISTANCE, Constants::BACKGROUND_MATERIAL, position); return; } } output_intersection = Intersection(Constants::MAX_RENDER_DISTANCE, Constants::BACKGROUND_MATERIAL, position); return; } std::pair<float, float> Raymarcher::convert_grid_coords_to_screen_space(int x, int y) { std::pair<float, float> screen_space_coords; screen_space_coords.first = static_cast<float>(x) / (m_grid->get_x_max() - m_grid->get_x_min()) * 2 - 1.0f; screen_space_coords.second = static_cast<float>(y) / (m_grid->get_y_max() - m_grid->get_y_min()) * 2 - 1.0f; return screen_space_coords; } void Raymarcher::phong_contrib_for_light(IN const Color& diffuse, IN const Color &specular_color, IN float alpha, IN const Vec3f& pos, IN const Vec3f &eye, IN const LightBase& light, IN float attenuation, OUT Color& output_color) { Vec3f N; estimate_normal(pos, N); Vec3f L = light.light_vec(pos); Vec3f camera_dir = (eye - pos).normalize(); Vec3f R = (Vec3f(0.0f, 0.0f, 0.0f) - L).reflect(N); float dotLN = L.dot(N); float dotRV = R.dot(camera_dir); if (dotLN < 0.0) { // Light not visible output_color = Color{0.0f, 0.0f, 0.0f}; return; } if (dotRV < 0.0) { output_color = ((light.intensity() * (diffuse * dotLN)) * attenuation); return; } Vec3f half_direction = (L.normalize() + camera_dir).normalize(); float specular = std::pow(std::fmax(half_direction.dot(N), 0.0), 16.0); // Blinn - phong calculation output_color = ((light.intensity() * ((diffuse) * dotLN + (specular_color) * std::pow(dotRV, alpha) * specular)) * attenuation); return; } void Raymarcher::phong_illumination(IN const Material& material, IN const LightBase& light, IN const Vec3f& pos, IN const Vec3f& eye, OUT Color& output_color) { float attenuation = 1.0f / light.attenuation(); Color color = (light.ambient() * material.ambient()) * attenuation; Color phong_contrib_for_light_output; phong_contrib_for_light(material.diffuse(), material.specular(), material.shininess(), pos, eye, light, attenuation, phong_contrib_for_light_output); color += phong_contrib_for_light_output; output_color = color; return; } void Raymarcher::apply_fog(IN const Color& color, IN float distance, OUT Color& resultant_color) { float fog_amount = 1.0 - std::pow(M_E, -distance * 0.1); mix(color, FOG_COLOR, fog_amount, resultant_color); } void Raymarcher::calculate_rows(int y_lower_bound, int y_upper_bound, int x_min, int x_max, const ConfigManager& config_manager_instance, size_t num_of_lights) { for (auto y = y_lower_bound; y < y_upper_bound; ++y) { for (auto x = x_min; x < x_max; ++x) { Ray view_dir = config_manager_instance.get_camera()->fire_ray(convert_grid_coords_to_screen_space(x, y)); // March ray till an intersection is found // If no intersection is found the BACKGROUND_MATERIAL is returned with the MAX_RENDER_DISTANCE // These are declared in Constants.h Intersection intersection; march(view_dir, intersection); Color pixel_color = Color{0, 0, 0}; for (int i = 0; i < num_of_lights; ++i) { auto light = config_manager_instance.get_light(i); Color this_light_color; phong_illumination(intersection.material(), *light, intersection.pos(), config_manager_instance.get_camera()->pos(), this_light_color); pixel_color += this_light_color; } apply_fog(pixel_color, intersection.distance(), pixel_color); pixel_color.clamp_with_desaturation(x, y); (*m_buffer).add_to_buffer(x, y, std::move(pixel_color)); } } } void Raymarcher::calculate_frame() { size_t num_of_lights = ConfigManager::instance().get_amount_of_lights(); int y_min = m_grid->get_y_min(); int y_max = m_grid->get_y_max(); int x_min = m_grid->get_x_min(); int x_max = m_grid->get_x_max(); auto& config_manager_instance = ConfigManager::instance(); // Initialise threads std::vector<std::thread> threads; int rows_per_thread = (y_max - y_min) / NUM_OF_THREADS; // Partition the screen based for (int y = y_min; y < y_max; y += rows_per_thread) { threads.push_back(std::thread(&Raymarcher::calculate_rows, this, y, y + rows_per_thread, x_min, x_max, std::cref(config_manager_instance), num_of_lights)); } // Join all threads for (auto& thread : threads) { thread.join(); } }
[ "jbalajanbusiness@gmail.com" ]
jbalajanbusiness@gmail.com
b5e090bc854eca3fd710ca8d3b54bcaab70669cd
7e0d25090fa0329ed93d44da77b830ce52cc7a87
/src/game/entities/basemonster.cpp
ec2f753982267fdafe404d5c50b9fa0eeb6dcee6
[ "Zlib", "BSD-3-Clause", "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
Micha0/ScMa
4fae04c808fd4fe99c94d944abb6345370291a8c
018b3d2b3273d0dbfad77269d53707caff24d85e
refs/heads/master
2020-06-17T09:28:53.293080
2019-07-08T15:05:22
2019-07-08T15:05:22
195,880,143
0
0
null
2019-07-08T20:16:01
2019-07-08T20:16:01
null
UTF-8
C++
false
false
549
cpp
#include "../game.h" #include "basemonster.h" namespace entities { namespace classes { BaseMonster::BaseMonster() : BaseMonster() { //type = ENT_AI; } BaseMonster::~BaseMonster() { } void BaseMonster::preload() { conoutf("%s", "Preloading playerstart entity"); } void BaseMonster::think() { //moveplayer(this, 10, true); } void BaseMonster::render() { // TODO: Fix this. //if(isthirdperson()) renderclient(player1, "ogro", NULL, 0, ANIM_ATTACK1, 300, player1->lastaction, player1->lastpain); } } // classes } // entities
[ "watisdeze2@gmail.com" ]
watisdeze2@gmail.com
19183dbe0407d48cdb158a2d00a20a44d9ab8db9
2972fa31910a1a5d761e3938cd2e80e3a4ee5162
/cita.cc
96c134651304e225d6c90a75d996c5bee9dfd099
[]
no_license
TheMatrix97/Practica-PRO2-2016
219d68d358531aaba3ec1bde8fa79466c07df80f
9063a73809f45c5b27d5e7893693160b9f19c07d
refs/heads/master
2020-12-25T10:58:42.052507
2016-07-02T11:21:23
2016-07-02T11:21:23
62,385,147
0
0
null
null
null
null
UTF-8
C++
false
false
832
cc
#include "cita.hh" cita::cita(){ x = y = -1; autor = "error"; titol = "error"; } bool cita::afegir_cita(text t,int x, int y, string autor, string titol){ this->autor = autor; this->titol = titol; this->x = x; this->y = y; if(y <= t.consul_frases() and 1 <= x and x <= y){ for (int i = x - 1; i < y; ++i){ contingut.push_back(t.mostra_frase(i)); } return true; }else return false; } string cita::mostrar_titol(){ return titol; } string cita::mostrar_autor(){ return autor; } void cita::imprimir_contingut(){ int a = x; for (int i = 0; i < contingut.size(); ++i){ cout << a << " " << contingut[i] << endl; ++a; } } void cita::retorna_x_y(int &ix, int &iy){ ix = x; iy = y; } void cita::imprimir_autor_titol(){ char comillas = '"'; cout << autor << ' ' << comillas << titol << comillas << endl; }
[ "marc@catrisse.net" ]
marc@catrisse.net
8fb90be66d73c9e51dfedba34c6e29678ede8029
5b33cd78b42da7038f2313900913823873699420
/src/CharHelper.h
8194bb68cf0af0575cf76f04176c3ec5a9ad093d
[]
no_license
foxliveray/DBMS
af9941d6f2de7eb62fd404a2e9f1f6c0ce3ad91c
810a45a924dfbf4b51ae02f86e96a2ad2225a5aa
refs/heads/master
2021-01-20T02:53:52.108173
2017-06-21T14:28:15
2017-06-21T14:28:15
89,462,282
1
0
null
null
null
null
GB18030
C++
false
false
750
h
#pragma once class CharHelper { public: CharHelper(); ~CharHelper(); //将CString类型转化为char*类型 static void ToChars(char* p, CString s, const int nSize); //将系统时间(SYSTEMTIME)类型转换成char*类型 static void ToChars(char* p, SYSTEMTIME t, const int nSize); //将bool类型转化为char*类型 static void ToChars(char* p, bool b, const int nSize); //将int类型转化为char*类型 static void ToChars(char* p, int in, const int nSize); //将double类型转化为char*类型 static void ToChars(char* p, double d, const int nSize); //将char*类型转化为CString类型 static CString ToString(char* p, const int nSize); //拷贝字符数组 static void Copy(char* p, char* pSrc, const int nSize); };
[ "444638290@qq.com" ]
444638290@qq.com
28f5d8da3c6087baac6b6d9a257b9f6726f21a5e
d7a70833f2d3573d9eab615f69106de75ff644f1
/A5/aabb.cpp
67a8ad3741f2013912ad322286091745d9c56f1f
[]
no_license
JingxianFan/InteractiveCG
8c3ffd01f3ff813a7b133b69df232a13a48d55f9
019fcfbe548d937b2b0b7d012270482b33bfc234
refs/heads/master
2021-01-21T21:19:35.970790
2017-06-19T20:49:42
2017-06-19T20:49:42
94,819,292
0
0
null
null
null
null
UTF-8
C++
false
false
1,112
cpp
#include "aabb.h" AABB::AABB(V3 firstPoint) { corners[0] = firstPoint; corners[1] = firstPoint; } void AABB::AddPoint(V3 newPoint) { for (int i = 0; i < 3; i++) { if (newPoint[i] > corners[1][i]) corners[1][i] = newPoint[i]; if (newPoint[i] < corners[0][i]) corners[0][i] = newPoint[i]; } } bool AABB::ClipWithFrame(float left, float top, float right, float bottom) { // entire 2D AABB is off screen if ( corners[0][0] >= right || corners[1][0] <= left || corners[0][1] >= bottom || corners[1][1] <= top ) return false; if (corners[0][0] < left) corners[0][0] = left; if (corners[1][0] > right) corners[1][0] = right; if (corners[0][1] < top) corners[0][1] = top; if (corners[1][1] > bottom) corners[1][1] = bottom; return true; } void AABB::SetPixelRectangle(int& left, int& right, int& top, int& bottom) { left = (int) (corners[0][0]+0.5f); right = (int) (corners[1][0]-0.5f); top = (int) (corners[0][1]+0.5f); bottom = (int) (corners[1][1]-0.5f); }
[ "jingxian0317@gmail.com" ]
jingxian0317@gmail.com
36f2bc26ce9f14b5b0698ef61b809e40a619d48b
331426c3acb53224f923275fd16d1937dc28de4d
/codes/DP/5.CountOfSubsetSum.cpp
e3fcae938694035a94795c5067e34839af9c3f66
[]
no_license
ag-richa-13/Competitive-Coding
63cc875b1afe2c5fde230e78880ebaaca1274707
2b2dcc75013a4f31f7ed5ae32bb02b7f58e43083
refs/heads/master
2023-04-05T12:54:16.340639
2021-03-28T09:15:20
2021-03-28T09:15:20
null
0
0
null
null
null
null
UTF-8
C++
false
false
934
cpp
// Count of subsets with a given sum using Top down approach // Question: // Given an array A and sum s count the number od subsets whose sum is s // Input: // 1 // 6(N) 10(sum) // A[] 2 3 5 6 8 10 // Output: // 3 #include <iostream> #include <algorithm> using namespace std; int subsetSumCount(int A[],int sum,int n){ int DP[n+1][sum+1]; for(int i=0;i<=n;i++){ for(int j=0;j<=sum;j++){ if(i==0 && j!=0) DP[i][j] = 0; else if(j==0) DP[i][j] = 1; else if(A[i-1] <= j) DP[i][j] = DP[i-1][j- A[i-1]] + DP[i-1][j]; else DP[i][j] = DP[i-1][j]; } } return DP[n][sum]; } int main() { int T; cin>>T; while(T--){ int N,sum; cin>>N>>sum; int A[N]; for(int i=0;i<N;i++) cin>>A[i]; cout<<subsetSumCount(A,sum,N)<<endl; } }
[ "krishna.gavas@gmail.com" ]
krishna.gavas@gmail.com
304eecbf5e46213130942744e34ffab23f913a53
06d7e641e298d039eb4f3503f2235410668360f5
/Tarea 23/struct5.cpp
643ab8651b472cc537583abb56a181105a9bafe0
[]
no_license
RiacardoBrandom/tarea-23
323ac96a4807543a3cbe76681971a23320c18ff2
3fb7e0d49329e8cbad11fe5d3d10447881e825f8
refs/heads/master
2021-08-26T06:37:28.103150
2017-11-21T20:49:42
2017-11-21T20:49:42
111,599,889
0
0
null
null
null
null
UTF-8
C++
false
false
354
cpp
#include <stdio.h> #include <stdlib.h> #include "alumnos.h" #include "info.h" int main(int argc, char const *agrv[]){ appInfoData("struct","21/11/2017"); ALUMNO var1; var1= nuevoAlumno(); //printf("Edad%d nombre:%s", var1.edad, var1.nombre); imprime Alumno (var1); return 0; }
[ "noreply@github.com" ]
noreply@github.com
6789a384a654929908572f4f49ecaa3e159f7291
f500169ca875b3d9b425b01ab72508e2ff18d0e1
/code/phd/experiments.cpp
7c949f53b932c069cc880a47cd45130207855e27
[]
no_license
lukes611/phdThesis
6d8f3dc8bce7279a35d2f90e926e659b7ce57f3d
fac297bf91361389b7c1d956bde0b2ebe5d2b73e
refs/heads/master
2021-01-20T00:33:37.799808
2018-05-13T08:22:59
2018-05-13T08:22:59
64,813,150
2
2
null
null
null
null
UTF-8
C++
false
false
15,975
cpp
#include "experiments.h" #include <fstream> #include <ctime> #include <string> #include <cstdio> #include <cstdlib> using namespace std; #include "../basics/Pixel3DSet.h" #ifdef HASGL #include "../basics/ll_gl.h" #endif #include "../basics/R3.h" #include "../basics/llCamera.h" #include "../basics/locv3.h" using namespace ll_pix3d; using namespace ll_R3; using namespace ll_cam; using namespace cv; namespace ll_experiments { map<string, void *> * LLPointers::access(){ static map<string, void *> mp; return &mp; } bool LLPointers::has(string key){ map<string, void*> * ptr = LLPointers::access(); return ptr->find(key) != ptr->end(); } void viewVideo(string name, bool viewColor, bool viewDepth, bool viewVD, int wks) { CapturePixel3DSet video (name, 80); Pix3D p; Mat color, depth, vd; for(int i = 0; i < video.size(); i++) { video.read(p); if(viewColor) { p.colorImage(color); imshow("color", color); } if(viewDepth) { p.depthImage(depth); imshow("depth", depth); } if(viewVD) { p.vdImage(vd); imshow("vd",vd); } if(viewColor || viewDepth || viewVD) { if (wks > 0) waitKey(wks); else waitKey(); } } } vector<int> rng(int to){ return rng(0, to, 1);} vector<int> rng(int from, int to) { return rng(from, to, 1); } vector<int> rng(int from, int to, int inc) { vector<int> ret; if(from < to && inc > 0) for(int i = from; i < to; i+=inc) ret.push_back(i); else if(from > to && inc < 0) for(int i = from; i > to; i-=inc); return ret; } bool fileIsEmpty(string fileName) { ifstream file; file.open(fileName.c_str(), ios::in); if(!file.is_open()) return true; file.seekg(0, ios::end); int len = file.tellg(); file.close(); return len == 0; } void appendData(string fileName, string header, string data, bool includeNewLine) { bool isEmpty = fileIsEmpty(fileName); ofstream file; file.open(fileName, ios::app); cout << "is empty : " << isEmpty << endl; if(isEmpty) { file << header; if(includeNewLine) file << "\n"; } file << data; if(includeNewLine) file << "\n"; file.close(); } ll_pix3d::CapturePixel3DSet openData(string name, int numFrames) { stringstream path; path << LCPPDATA_DIR << "/pix3dc/films"; return CapturePixel3DSet::openCustom(path.str(), name, numFrames); } namespace kitti { string getFileName(string directory, int index) { stringstream t; t << directory; int numDP = index == 0 ? 1 : log10(index) + 1; for (int i = 0; i < 10 - numDP; i++) t << "0"; t << index << ".bin"; return t.str(); } string getImageFileName(string directory, int index) { stringstream t; t << directory; int numDP = index == 0 ? 1 : log10(index) + 1; for (int i = 0; i < 10 - numDP; i++) t << "0"; t << index << ".png"; return t.str(); } Mat readImage(string directoryName, int index, bool getColor, bool getLeftImage) { stringstream fileName; int imageType = 0; if (!getLeftImage) imageType++; if (getColor) imageType += 2; fileName << LCPPDATA_DIR << "/kitti/" << directoryName << "/image_0" << imageType << "/data/"; Mat ret = imread(getImageFileName(fileName.str(), index).c_str(), getColor ? CV_LOAD_IMAGE_COLOR : CV_LOAD_IMAGE_GRAYSCALE); return ret.clone(); } Pixel3DSet read(string directoryName, int index, bool flip) { stringstream fileName; fileName << LCPPDATA_DIR << "/kitti/" << directoryName << "/velodyne_points/data/"; FILE * file = fopen(getFileName(fileName.str(), index).c_str(), "rb"); Pixel3DSet ret; if (file) { while (!feof(file)) { float data[4]; fread(data, sizeof(float), 4, file); R3 newPoint(data[0], data[1], data[2]); Vec3b newColor(Vec3b(255, 255, 255)); ret.push_back(newPoint, newColor); } } else cout << "could not open the file " << getFileName(directoryName, index) << endl; if (flip) { //ret.transform_set(90, 0, 0, 1, 0, 0, 0, R3()); } return ret; } Mat velo2Cam(string fileName) { Mat ret = Mat::eye(Size(4, 4), CV_32FC1); string filePath = string(LCPPDATA_DIR) + string("/kitti/") + string(fileName) + "/calib_velo_to_cam.txt"; FILE * file = fopen(filePath.c_str(), "r"); char buf[100]; fscanf(file, "%s", buf); fscanf(file, "%s", buf); fscanf(file, "%s", buf); fscanf(file, "%s", buf); for (int y = 0; y < 3; y++) { for (int x = 0; x < 3; x++) { double tmp; fscanf(file, "%lf", &tmp); ret.at<float>(y, x) = tmp; } } fscanf(file, "%s", buf); for (int y = 0; y < 3; y++) { double tmp; fscanf(file, "%lf", &tmp); ret.at<float>(y, 3) = tmp; } fclose(file); return ret; } void cam2cam(std::string directoryName, cv::Mat & R_rect_0x, cv::Mat & P_rect_0x, int x) { R_rect_0x = Mat::eye(Size(4,4), CV_32FC1); P_rect_0x = Mat::eye(Size(4,4), CV_32FC1); string fileName = LCPPDATA_DIR + string("/kitti/") + directoryName + string("/calib_cam_to_cam.txt"); string wholeFile = ""; FILE * file = fopen(fileName.c_str(), "r"); string rheader, pheader; { stringstream rh, ph; rh << "R_rect_0" << "0:"; ph << "P_rect_0" << x << ":"; rheader = rh.str(); pheader = ph.str(); } if(file) { while(!feof(file)) { char buf[101]; int nr = fread(buf, 1, 100, file); buf[nr] = 0; wholeFile += buf; } vector<string> lines = ll_split(wholeFile, '\n'); for(int l = 0; l < lines.size(); l++) { vector<string> words = ll_split(lines[l], ' '); if(words[0] == rheader) { for(int y = 0, i = 1; y < 3; y++) for(int x = 0; x < 3; x++, i++) { double tmp; sscanf(words[i].c_str(), "%lf", &tmp); R_rect_0x.at<float>(y,x) = tmp; } }else if(words[0] == pheader) { for(int y = 0, i = 1; y < 3; y++) for(int x = 0; x < 4; x++, i++) { double tmp; sscanf(words[i].c_str(), "%lf", &tmp); P_rect_0x.at<float>(y,x) = tmp; } } } }else cout << "could not open cam2cam calibration file\n"; } KittiPix3dSet open(std::string dataset, int index) { KittiPix3dSet ret; //get color-data ret.colorImage = readImage(dataset, index, true, true); //get 3d-data ret.validDepthImage = Mat::zeros(ret.colorImage.size(), CV_8UC1); ret.points = vector<R3>(ret.colorImage.size().width * ret.colorImage.size().height); Mat projectToPoints = velo2Cam(dataset); Mat P, R; cam2cam(dataset, R, P, 0); Mat projectToImage = P * R; Pixel3DSet raw_points = read(dataset, index); Mat tmp = Mat::zeros(Size(1, 4), CV_32FC1); for (int i = 0; i < raw_points.size(); i++) { R3 point = raw_points[i]; //multiply by projectToPoints Pixel3DSet::transform_point(projectToPoints, point); //multiply by projectToImage R3 imageIndexR3 = point; tmp.at<float>(0, 0) = imageIndexR3.x; tmp.at<float>(1, 0) = imageIndexR3.y; tmp.at<float>(2, 0) = imageIndexR3.z; tmp.at<float>(3, 0) = 1.0f; tmp = projectToImage * tmp; imageIndexR3.x = tmp.at<float>(0, 0) / tmp.at<float>(2, 0); imageIndexR3.y = tmp.at<float>(1, 0) / tmp.at<float>(2, 0); imageIndexR3.z = tmp.at<float>(2, 0); //find the image coordinates Point2i uv(round(imageIndexR3.x), round(imageIndexR3.y)); if (uv.x >= 0 && uv.x < ret.colorImage.size().width && uv.y >= 0 && uv.y < ret.colorImage.size().height && imageIndexR3.z >= 0.0) { //add to validDepth ret.validDepthImage.at<unsigned char>(uv) = 0xFF; //add to points if needed int uvIndex = uv.y * ret.validDepthImage.size().width + uv.x; R3 output = point; output.y *= -1.0f; output.x *= -1.0f; output -= R3(-55.0f, -5.0f, 0.0f); output *= 256.0f / 110.0f; ret.points[uvIndex] = output; } } return ret; } Mat KittiPix3dSet::getDepthMap() { Mat ret = Mat::zeros(this->colorImage.size(), CV_32FC1); for (int y = 0; y < ret.size().height; y++) { for (int x = 0; x < ret.size().width; x++) { if(this->validDepthImage.at<unsigned char>(y,x)) ret.at<float>(y, x) = this->points[y * ret.size().width + x].z / 256.0f; } } return ret.clone(); } Mat KittiPix3dSet::getDepthMap2() { Mat ret = Mat::zeros(this->colorImage.size(), CV_32FC1); for (int y = 0; y < ret.size().height; y++) { for (int x = 0; x < ret.size().width; x++) { if(this->validDepthImage.at<unsigned char>(y,x)) ret.at<float>(y, x) = this->points[y * ret.size().width + x].z / 255.0f; } } return ret.clone(); } Mat KittiPix3dSet::getColoredDepthMap() { Mat depthImage = this->getDepthMap(); ll_normalize(depthImage, this->validDepthImage); Mat coloredDepthImage = ll_getColoredDepthMap(depthImage); for (int y = 0; y < coloredDepthImage.size().height; y++) { for (int x = 0; x < coloredDepthImage.size().width; x++) { if (!this->validDepthImage.at<unsigned char>(y, x)) { coloredDepthImage.at<Vec3b>(y, x) = Vec3b(0, 0, 0); } } } return coloredDepthImage.clone(); } Mat KittiPix3dSet::getAugmentedDepthMap() { Mat ret = this->colorImage.clone(); Mat cdi = this->getColoredDepthMap(); for (int y = 0; y < cdi.size().height; y++) { for (int x = 0; x < cdi.size().width; x++) { if(this->validDepthImage.at<unsigned char>(y,x)) ret.at<Vec3b>(y, x) = cdi.at<Vec3b>(y,x); } } return ret.clone(); } Pixel3DSet KittiPix3dSet::getPoints() { Pixel3DSet ret; Size s = this->colorImage.size(); for (int y = 0; y < s.height; y++) { for (int x = 0; x < s.width; x++) { if (this->validDepthImage.at<unsigned char>(y, x)) { ret.push_back(this->points[y * s.width + x], this->colorImage.at<Vec3b>(y, x)); } } } return ret; } bool KittiPix3dSet::getClosePoint(cv::Point2i p, ll_R3::R3 & out) { bool found = false; double dist; int W = this->colorImage.size().width; int H = this->colorImage.size().height; if(this->validDepthImage.at<unsigned char>(p)) { out = this->points[p.y * W + p.x]; return true; }else { for(int y = p.y - 2; y <= p.y + 2; y++) { for(int x = p.x - 2; x <= p.x + 2; x++) { if(x >= 0 && x < W && y >= 0 && y < H) { if(this->validDepthImage.at<unsigned char>(y,x)) { double tmpDist = ll_distance(x,y, p.x, p.y); if(!found) { out = this->points[y * W + x]; dist = tmpDist; found = true; }else if(tmpDist < dist) { dist = tmpDist; out = this->points[y * W + x]; } } } } } return found; } } } #ifdef HASGL void viewPixel3DSet(Fps_cam cameraInput) { ll_gl::default_glut_main("lukes phd project", 640, 480); Fps_cam * camera = new Fps_cam(R3(40,40,-60), 90.0f, 90.0f); *camera = cameraInput; LLPointers::setPtr("camera", camera); glutDisplayFunc([]()->void { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); Fps_cam * camera = LLPointers::getPtr<Fps_cam>("camera"); ll_gl::default_viewing(*camera); ll_gl::default_lighting(); ll_gl::turn_off_lights(); if(LLPointers::has("object")) { Pixel3DSet * obj = LLPointers::getPtr<Pixel3DSet>("object"); glBegin(GL_POINTS); for(int i = 0; i < obj->points.size(); i++) { R3 col = obj->color_as_r3(i) / 255.0f; swap(col.x, col.z); ll_gl::set_color(col); ll_gl::glR3(obj->points[i]); } glEnd(); } glutSwapBuffers(); glutPostRedisplay(); }); glutKeyboardFunc([](unsigned char key, int x, int y)->void{ Fps_cam * camera = LLPointers::getPtr<Fps_cam>("camera"); camera->keyboard(key, x,y); if(key == '5') { cout << camera->to_string() << endl; } }); glutReshapeFunc([](int wi, int he)->void{ }); glutMotionFunc([](int x, int y)->void{ Fps_cam * camera = LLPointers::getPtr<Fps_cam>("camera"); camera->mouse(x,y); }); glutMouseFunc([](int button, int state, int x, int y)->void{ Fps_cam * camera = LLPointers::getPtr<Fps_cam>("camera"); ll_gl::camera_mouse_click(*camera, button, state, x, y); }); glutMainLoop(); } #endif NoiseGenerator::NoiseGenerator(bool seedAtBeginning) { if (seedAtBeginning) seed(); } NoiseGenerator::~NoiseGenerator() { noise.clear(); signal.clear(); } double NoiseGenerator::randomNumber() { return rand() / (double)RAND_MAX; } Point3f NoiseGenerator::randomPoint() { return Point3f(randomNumber(), randomNumber(), randomNumber()); } void NoiseGenerator::seed() { srand(time(NULL)); } double NoiseGenerator::randomNumber(double range) { double h = range * 0.5f; return randomNumber() * range - h; } Point3f NoiseGenerator::randomPoint(double range) { return Point3f(randomNumber(range), randomNumber(range), randomNumber(range)); } Point3f NoiseGenerator::getNoise(Point3f signal, double range) { Point3f newNoise = randomPoint(range); this->signal.push_back(signal); this->noise.push_back(newNoise); return newNoise; } R3 NoiseGenerator::getNoise(R3 signal, double range) { Point3f _ = randomPoint(range); R3 newNoise(_.x, _.y, _.z); this->signal.push_back(Point3f(signal.x, signal.y, signal.z)); this->noise.push_back(Point3f(newNoise.x, newNoise.y, newNoise.z)); return newNoise; } Point3f NoiseGenerator::stdDev(vector<Point3f> & data) { Point3f mn = mean(data); Point3f stdDev(0.0f, 0.0f, 0.0f); if (data.size() == 0) return stdDev; float scalar = 1.0f / (float)data.size(); for (int i = 0; i < data.size(); i++) { Point3f p = data[i] - mn; p.x *= p.x; p.y *= p.y; p.z *= p.z; stdDev += p; } stdDev.x = sqrt(stdDev.x * scalar); stdDev.y = sqrt(stdDev.y * scalar); stdDev.z = sqrt(stdDev.z * scalar); return stdDev; } Point3f NoiseGenerator::mean(vector<Point3f> & data) { Point3f init(0.0f, 0.0f, 0.0f); if (data.size() == 0) return init; float scalar = 1.0f / (float)data.size(); for (int i = 0; i < data.size(); i++) { init += data[i] * scalar; } return init; } Point3f NoiseGenerator::stdDevNoise() { return stdDev(noise); } Point3f NoiseGenerator::stdDevSignal() { return stdDev(signal); } void NoiseGenerator::getSNR(Point3f & out) { Point3f ss = stdDevSignal(), ns = stdDevNoise(); out.x = (ss.x * ss.x) / (ns.x * ns.x); out.y = (ss.y * ss.y) / (ns.y * ns.y); out.z = (ss.z * ss.z) / (ns.z * ns.z); } void NoiseGenerator::getSNR(double & out) { Point3f op; getSNR(op); out = (op.x + op.y + op.z) / 3.0f; } ll_pix3d::Pixel3DSet getNoisedVersion(ll_pix3d::Pixel3DSet & input, double noiseRange, double & snrOut) { Pixel3DSet cp = input; NoiseGenerator noise; for (int i = 0; i < cp.size(); i++) { cp.points[i] += noise.getNoise(input.points[i], noiseRange); } noise.getSNR(snrOut); return cp; } ll_pix3d::Pix3D getNoisedVersion(ll_pix3d::Pix3D & input, double noiseRange, double & snrOut) { Pix3D cp = input; NoiseGenerator noise; for (int i = 0; i < cp.count; i++) { if (cp.validDepth && cp.validDepth[i]) { cp.points[i] += noise.getNoise(input.points[i], noiseRange); } } noise.getSNR(snrOut); return cp; } }
[ "lukes611@gmail.com" ]
lukes611@gmail.com
9babd328f2313d142654896abc2d980b30bb44d8
55b5034281a1e750632fd23974e33a9daea09de9
/3rdparty/opencv-git/modules/core/test/test_dxt.cpp
2e7bb38eaf749e400cfe80e225b6008a0035e7eb
[ "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference" ]
permissive
joshjo/planecalib
f5fbca3a0f9899f5097c7025847c939f41ae4789
1d7cffac5cab39c7fbfb67e8e3a4b42340ef5e13
refs/heads/master
2020-04-16T08:08:28.523107
2019-02-18T11:19:08
2019-02-18T11:19:08
165,413,146
0
0
NOASSERTION
2019-01-12T17:02:34
2019-01-12T17:02:34
null
UTF-8
C++
false
false
24,647
cpp
#include "test_precomp.hpp" using namespace cv; using namespace std; namespace cvtest { static Mat initDFTWave( int n, bool inv ) { int i; double angle = (inv ? 1 : -1)*CV_PI*2/n; Complexd wi, w1; Mat wave(1, n, CV_64FC2); Complexd* w = wave.ptr<Complexd>(); w1.re = cos(angle); w1.im = sin(angle); w[0].re = wi.re = 1.; w[0].im = wi.im = 0.; for( i = 1; i < n; i++ ) { double t = wi.re*w1.re - wi.im*w1.im; wi.im = wi.re*w1.im + wi.im*w1.re; wi.re = t; w[i] = wi; } return wave; } static void DFT_1D( const Mat& _src, Mat& _dst, int flags, const Mat& _wave=Mat()) { _dst.create(_src.size(), _src.type()); int i, j, k, n = _dst.cols + _dst.rows - 1; Mat wave = _wave; double scale = (flags & DFT_SCALE) ? 1./n : 1.; size_t esz = _src.elemSize(); size_t srcstep = esz, dststep = esz; const uchar* src0 = _src.ptr(); uchar* dst0 = _dst.ptr(); CV_Assert( _src.cols + _src.rows - 1 == n ); if( wave.empty() ) wave = initDFTWave( n, (flags & DFT_INVERSE) != 0 ); const Complexd* w = wave.ptr<Complexd>(); if( !_src.isContinuous() ) srcstep = _src.step; if( !_dst.isContinuous() ) dststep = _dst.step; if( _src.type() == CV_32FC2 ) { for( i = 0; i < n; i++ ) { Complexf* dst = (Complexf*)(dst0 + i*dststep); Complexd sum(0,0); int delta = i; k = 0; for( j = 0; j < n; j++ ) { const Complexf* src = (const Complexf*)(src0 + j*srcstep); sum.re += src->re*w[k].re - src->im*w[k].im; sum.im += src->re*w[k].im + src->im*w[k].re; k += delta; k -= (k >= n ? n : 0); } dst->re = (float)(sum.re*scale); dst->im = (float)(sum.im*scale); } } else if( _src.type() == CV_64FC2 ) { for( i = 0; i < n; i++ ) { Complexd* dst = (Complexd*)(dst0 + i*dststep); Complexd sum(0,0); int delta = i; k = 0; for( j = 0; j < n; j++ ) { const Complexd* src = (const Complexd*)(src0 + j*srcstep); sum.re += src->re*w[k].re - src->im*w[k].im; sum.im += src->re*w[k].im + src->im*w[k].re; k += delta; k -= (k >= n ? n : 0); } dst->re = sum.re*scale; dst->im = sum.im*scale; } } else CV_Error(CV_StsUnsupportedFormat, ""); } static void DFT_2D( const Mat& src, Mat& dst, int flags ) { const int cn = 2; int i; dst.create(src.size(), src.type()); Mat tmp( src.cols, src.rows, src.type()); Mat wave = initDFTWave( dst.cols, (flags & DFT_INVERSE) != 0 ); // 1. row-wise transform for( i = 0; i < dst.rows; i++ ) { Mat srci = src.row(i).reshape(cn, src.cols), dsti = tmp.col(i); DFT_1D(srci, dsti, flags, wave ); } if( (flags & DFT_ROWS) == 0 ) { if( dst.cols != dst.rows ) wave = initDFTWave( dst.rows, (flags & DFT_INVERSE) != 0 ); // 2. column-wise transform for( i = 0; i < dst.cols; i++ ) { Mat srci = tmp.row(i).reshape(cn, tmp.cols), dsti = dst.col(i); DFT_1D(srci, dsti, flags, wave ); } } else cvtest::transpose(tmp, dst); } static Mat initDCTWave( int n, bool inv ) { int i, k; double angle = CV_PI*0.5/n; Mat wave(n, n, CV_64F); double scale = sqrt(1./n); for( k = 0; k < n; k++ ) wave.at<double>(0, k) = scale; scale *= sqrt(2.); for( i = 1; i < n; i++ ) for( k = 0; k < n; k++ ) wave.at<double>(i, k) = scale*cos( angle*i*(2*k + 1) ); if( inv ) cv::transpose( wave, wave ); return wave; } static void DCT_1D( const Mat& _src, Mat& _dst, int flags, const Mat& _wave=Mat() ) { _dst.create( _src.size(), _src.type() ); int i, j, n = _dst.cols + _dst.rows - 1; Mat wave = _wave; int srcstep = 1, dststep = 1; double* w; CV_Assert( _src.cols + _src.rows - 1 == n); if( wave.empty() ) wave = initDCTWave( n, (flags & DFT_INVERSE) != 0 ); w = wave.ptr<double>(); if( !_src.isContinuous() ) srcstep = (int)(_src.step/_src.elemSize()); if( !_dst.isContinuous() ) dststep = (int)(_dst.step/_dst.elemSize()); if( _src.type() == CV_32FC1 ) { float *dst = _dst.ptr<float>(); for( i = 0; i < n; i++, dst += dststep ) { const float* src = _src.ptr<float>(); double sum = 0; for( j = 0; j < n; j++, src += srcstep ) sum += src[0]*w[j]; w += n; dst[0] = (float)sum; } } else if( _src.type() == CV_64FC1 ) { double *dst = _dst.ptr<double>(); for( i = 0; i < n; i++, dst += dststep ) { const double* src = _src.ptr<double>(); double sum = 0; for( j = 0; j < n; j++, src += srcstep ) sum += src[0]*w[j]; w += n; dst[0] = sum; } } else assert(0); } static void DCT_2D( const Mat& src, Mat& dst, int flags ) { const int cn = 1; int i; dst.create( src.size(), src.type() ); Mat tmp(dst.cols, dst.rows, dst.type() ); Mat wave = initDCTWave( dst.cols, (flags & DCT_INVERSE) != 0 ); // 1. row-wise transform for( i = 0; i < dst.rows; i++ ) { Mat srci = src.row(i).reshape(cn, src.cols); Mat dsti = tmp.col(i); DCT_1D(srci, dsti, flags, wave); } if( (flags & DCT_ROWS) == 0 ) { if( dst.cols != dst.rows ) wave = initDCTWave( dst.rows, (flags & DCT_INVERSE) != 0 ); // 2. column-wise transform for( i = 0; i < dst.cols; i++ ) { Mat srci = tmp.row(i).reshape(cn, tmp.cols); Mat dsti = dst.col(i); DCT_1D( srci, dsti, flags, wave ); } } else cvtest::transpose( tmp, dst ); } static void convertFromCCS( const Mat& _src0, const Mat& _src1, Mat& _dst, int flags ) { if( _dst.rows > 1 && (_dst.cols > 1 || (flags & DFT_ROWS)) ) { int i, count = _dst.rows, len = _dst.cols; bool is2d = (flags & DFT_ROWS) == 0; Mat src0row, src1row, dstrow; for( i = 0; i < count; i++ ) { int j = !is2d || i == 0 ? i : count - i; src0row = _src0.row(i); src1row = _src1.row(j); dstrow = _dst.row(i); convertFromCCS( src0row, src1row, dstrow, 0 ); } if( is2d ) { src0row = _src0.col(0); dstrow = _dst.col(0); convertFromCCS( src0row, src0row, dstrow, 0 ); if( (len & 1) == 0 ) { src0row = _src0.col(_src0.cols - 1); dstrow = _dst.col(len/2); convertFromCCS( src0row, src0row, dstrow, 0 ); } } } else { int i, n = _dst.cols + _dst.rows - 1, n2 = (n+1) >> 1; int cn = _src0.channels(); int srcstep = cn, dststep = 1; if( !_dst.isContinuous() ) dststep = (int)(_dst.step/_dst.elemSize()); if( !_src0.isContinuous() ) srcstep = (int)(_src0.step/_src0.elemSize1()); if( _dst.depth() == CV_32F ) { Complexf* dst = _dst.ptr<Complexf>(); const float* src0 = _src0.ptr<float>(); const float* src1 = _src1.ptr<float>(); int delta0, delta1; dst->re = src0[0]; dst->im = 0; if( (n & 1) == 0 ) { dst[n2*dststep].re = src0[(cn == 1 ? n-1 : n2)*srcstep]; dst[n2*dststep].im = 0; } delta0 = srcstep; delta1 = delta0 + (cn == 1 ? srcstep : 1); if( cn == 1 ) srcstep *= 2; for( i = 1; i < n2; i++, delta0 += srcstep, delta1 += srcstep ) { float t0 = src0[delta0]; float t1 = src0[delta1]; dst[i*dststep].re = t0; dst[i*dststep].im = t1; t0 = src1[delta0]; t1 = -src1[delta1]; dst[(n-i)*dststep].re = t0; dst[(n-i)*dststep].im = t1; } } else { Complexd* dst = _dst.ptr<Complexd>(); const double* src0 = _src0.ptr<double>(); const double* src1 = _src1.ptr<double>(); int delta0, delta1; dst->re = src0[0]; dst->im = 0; if( (n & 1) == 0 ) { dst[n2*dststep].re = src0[(cn == 1 ? n-1 : n2)*srcstep]; dst[n2*dststep].im = 0; } delta0 = srcstep; delta1 = delta0 + (cn == 1 ? srcstep : 1); if( cn == 1 ) srcstep *= 2; for( i = 1; i < n2; i++, delta0 += srcstep, delta1 += srcstep ) { double t0 = src0[delta0]; double t1 = src0[delta1]; dst[i*dststep].re = t0; dst[i*dststep].im = t1; t0 = src1[delta0]; t1 = -src1[delta1]; dst[(n-i)*dststep].re = t0; dst[(n-i)*dststep].im = t1; } } } } static void fixCCS( Mat& mat, int cols, int flags ) { int i, rows = mat.rows; int rows2 = (flags & DFT_ROWS) ? rows : rows/2 + 1, cols2 = cols/2 + 1; CV_Assert( cols2 == mat.cols ); if( mat.type() == CV_32FC2 ) { for( i = 0; i < rows2; i++ ) { Complexf* row = mat.ptr<Complexf>(i); if( (flags & DFT_ROWS) || i == 0 || (i == rows2 - 1 && rows % 2 == 0) ) { row[0].im = 0; if( cols % 2 == 0 ) row[cols2-1].im = 0; } else { Complexf* row2 = mat.ptr<Complexf>(rows-i); row2[0].re = row[0].re; row2[0].im = -row[0].im; if( cols % 2 == 0 ) { row2[cols2-1].re = row[cols2-1].re; row2[cols2-1].im = -row[cols2-1].im; } } } } else if( mat.type() == CV_64FC2 ) { for( i = 0; i < rows2; i++ ) { Complexd* row = mat.ptr<Complexd>(i); if( (flags & DFT_ROWS) || i == 0 || (i == rows2 - 1 && rows % 2 == 0) ) { row[0].im = 0; if( cols % 2 == 0 ) row[cols2-1].im = 0; } else { Complexd* row2 = mat.ptr<Complexd>(rows-i); row2[0].re = row[0].re; row2[0].im = -row[0].im; if( cols % 2 == 0 ) { row2[cols2-1].re = row[cols2-1].re; row2[cols2-1].im = -row[cols2-1].im; } } } } } #if defined _MSC_VER && _MSC_VER >= 1700 #pragma optimize("", off) #endif static void mulComplex( const Mat& src1, const Mat& src2, Mat& dst, int flags ) { dst.create(src1.rows, src1.cols, src1.type()); int i, j, depth = src1.depth(), cols = src1.cols*2; CV_Assert( src1.size == src2.size && src1.type() == src2.type() && (src1.type() == CV_32FC2 || src1.type() == CV_64FC2) ); for( i = 0; i < dst.rows; i++ ) { if( depth == CV_32F ) { const float* a = src1.ptr<float>(i); const float* b = src2.ptr<float>(i); float* c = dst.ptr<float>(i); if( !(flags & CV_DXT_MUL_CONJ) ) for( j = 0; j < cols; j += 2 ) { double re = (double)a[j]*(double)b[j] - (double)a[j+1]*(double)b[j+1]; double im = (double)a[j+1]*(double)b[j] + (double)a[j]*(double)b[j+1]; c[j] = (float)re; c[j+1] = (float)im; } else for( j = 0; j < cols; j += 2 ) { double re = (double)a[j]*(double)b[j] + (double)a[j+1]*(double)b[j+1]; double im = (double)a[j+1]*(double)b[j] - (double)a[j]*(double)b[j+1]; c[j] = (float)re; c[j+1] = (float)im; } } else { const double* a = src1.ptr<double>(i); const double* b = src2.ptr<double>(i); double* c = dst.ptr<double>(i); if( !(flags & CV_DXT_MUL_CONJ) ) for( j = 0; j < cols; j += 2 ) { double re = a[j]*b[j] - a[j+1]*b[j+1]; double im = a[j+1]*b[j] + a[j]*b[j+1]; c[j] = re; c[j+1] = im; } else for( j = 0; j < cols; j += 2 ) { double re = a[j]*b[j] + a[j+1]*b[j+1]; double im = a[j+1]*b[j] - a[j]*b[j+1]; c[j] = re; c[j+1] = im; } } } } #if defined _MSC_VER && _MSC_VER >= 1700 #pragma optimize("", on) #endif } class CxCore_DXTBaseTest : public cvtest::ArrayTest { public: typedef cvtest::ArrayTest Base; CxCore_DXTBaseTest( bool _allow_complex=false, bool _allow_odd=false, bool _spectrum_mode=false ); protected: void get_test_array_types_and_sizes( int test_case_idx, vector<vector<Size> >& sizes, vector<vector<int> >& types ); int prepare_test_case( int test_case_idx ); double get_success_error_level( int /*test_case_idx*/, int /*i*/, int /*j*/ ); int flags; // transformation flags bool allow_complex; // whether input/output may be complex or not: // true for DFT and MulSpectrums, false for DCT bool allow_odd; // whether input/output may be have odd (!=1) dimensions: // true for DFT and MulSpectrums, false for DCT bool spectrum_mode; // (2 complex/ccs inputs, 1 complex/ccs output): // true for MulSpectrums, false for DFT and DCT bool inplace; // inplace operation (set for each individual test case) bool temp_dst; // use temporary destination (for real->ccs DFT and ccs MulSpectrums) }; CxCore_DXTBaseTest::CxCore_DXTBaseTest( bool _allow_complex, bool _allow_odd, bool _spectrum_mode ) : Base(), flags(0), allow_complex(_allow_complex), allow_odd(_allow_odd), spectrum_mode(_spectrum_mode), inplace(false), temp_dst(false) { test_array[INPUT].push_back(NULL); if( spectrum_mode ) test_array[INPUT].push_back(NULL); test_array[OUTPUT].push_back(NULL); test_array[REF_OUTPUT].push_back(NULL); test_array[TEMP].push_back(NULL); test_array[TEMP].push_back(NULL); max_log_array_size = 9; element_wise_relative_error = spectrum_mode; } void CxCore_DXTBaseTest::get_test_array_types_and_sizes( int test_case_idx, vector<vector<Size> >& sizes, vector<vector<int> >& types ) { RNG& rng = ts->get_rng(); int bits = cvtest::randInt(rng); int depth = cvtest::randInt(rng)%2 + CV_32F; int cn = !allow_complex || !(bits & 256) ? 1 : 2; Size size; Base::get_test_array_types_and_sizes( test_case_idx, sizes, types ); flags = bits & (CV_DXT_INVERSE | CV_DXT_SCALE | CV_DXT_ROWS | CV_DXT_MUL_CONJ); if( spectrum_mode ) flags &= ~CV_DXT_INVERSE; types[TEMP][0] = types[TEMP][1] = types[INPUT][0] = types[OUTPUT][0] = CV_MAKETYPE(depth, cn); size = sizes[INPUT][0]; temp_dst = false; if( flags & CV_DXT_ROWS && (bits&1024) ) { if( bits&16 ) size.width = 1; else size.height = 1; flags &= ~CV_DXT_ROWS; } const int P2_MIN_SIZE = 32; if( ((bits >> 10) & 1) == 0 ) { size.width = (size.width / P2_MIN_SIZE)*P2_MIN_SIZE; size.width = MAX(size.width, 1); size.height = (size.height / P2_MIN_SIZE)*P2_MIN_SIZE; size.height = MAX(size.height, 1); } if( !allow_odd ) { if( size.width > 1 && (size.width&1) != 0 ) size.width = (size.width + 1) & -2; if( size.height > 1 && (size.height&1) != 0 && !(flags & CV_DXT_ROWS) ) size.height = (size.height + 1) & -2; } sizes[INPUT][0] = sizes[OUTPUT][0] = size; sizes[TEMP][0] = sizes[TEMP][1] = cvSize(0,0); if( spectrum_mode ) { if( cn == 1 ) { types[OUTPUT][0] = depth + 8; sizes[TEMP][0] = size; } sizes[INPUT][0] = sizes[INPUT][1] = size; types[INPUT][1] = types[INPUT][0]; } else if( /*(cn == 2 && (bits&32)) ||*/ (cn == 1 && allow_complex) ) { types[TEMP][0] = depth + 8; // CV_??FC2 sizes[TEMP][0] = size; size = cvSize(size.width/2+1, size.height); if( flags & CV_DXT_INVERSE ) { if( cn == 2 ) { types[OUTPUT][0] = depth; sizes[INPUT][0] = size; } types[TEMP][1] = types[TEMP][0]; sizes[TEMP][1] = sizes[TEMP][0]; } else { if( allow_complex ) types[OUTPUT][0] = depth + 8; if( cn == 2 ) { types[INPUT][0] = depth; types[TEMP][1] = types[TEMP][0]; sizes[TEMP][1] = size; } else { types[TEMP][1] = depth; sizes[TEMP][1] = sizes[TEMP][0]; } temp_dst = true; } } inplace = false; if( spectrum_mode || (!temp_dst && types[INPUT][0] == types[OUTPUT][0]) || (temp_dst && types[INPUT][0] == types[TEMP][1]) ) inplace = (bits & 64) != 0; types[REF_OUTPUT][0] = types[OUTPUT][0]; sizes[REF_OUTPUT][0] = sizes[OUTPUT][0]; } double CxCore_DXTBaseTest::get_success_error_level( int test_case_idx, int i, int j ) { return Base::get_success_error_level( test_case_idx, i, j ); } int CxCore_DXTBaseTest::prepare_test_case( int test_case_idx ) { int code = Base::prepare_test_case( test_case_idx ); if( code > 0 ) { int in_type = test_mat[INPUT][0].type(); int out_type = test_mat[OUTPUT][0].type(); if( CV_MAT_CN(in_type) == 2 && CV_MAT_CN(out_type) == 1 ) cvtest::fixCCS( test_mat[INPUT][0], test_mat[OUTPUT][0].cols, flags ); if( inplace ) cvtest::copy( test_mat[INPUT][test_case_idx & (int)spectrum_mode], temp_dst ? test_mat[TEMP][1] : in_type == out_type ? test_mat[OUTPUT][0] : test_mat[TEMP][0] ); } return code; } ////////////////////// FFT //////////////////////// class CxCore_DFTTest : public CxCore_DXTBaseTest { public: CxCore_DFTTest(); protected: void run_func(); void prepare_to_validation( int test_case_idx ); }; CxCore_DFTTest::CxCore_DFTTest() : CxCore_DXTBaseTest( true, true, false ) { } void CxCore_DFTTest::run_func() { Mat& dst = temp_dst ? test_mat[TEMP][1] : test_mat[OUTPUT][0]; const Mat& src = inplace ? dst : test_mat[INPUT][0]; if(!(flags & CV_DXT_INVERSE)) cv::dft( src, dst, flags ); else cv::idft(src, dst, flags & ~CV_DXT_INVERSE); } void CxCore_DFTTest::prepare_to_validation( int /*test_case_idx*/ ) { Mat& src = test_mat[INPUT][0]; Mat& dst = test_mat[REF_OUTPUT][0]; Mat* tmp_src = &src; Mat* tmp_dst = &dst; int src_cn = src.channels(); int dst_cn = dst.channels(); if( src_cn != 2 || dst_cn != 2 ) { tmp_src = &test_mat[TEMP][0]; if( !(flags & CV_DXT_INVERSE ) ) { Mat& cvdft_dst = test_mat[TEMP][1]; cvtest::convertFromCCS( cvdft_dst, cvdft_dst, test_mat[OUTPUT][0], flags ); *tmp_src = Scalar::all(0); cvtest::insert( src, *tmp_src, 0 ); } else { cvtest::convertFromCCS( src, src, *tmp_src, flags ); tmp_dst = &test_mat[TEMP][1]; } } if( src.rows == 1 || (src.cols == 1 && !(flags & CV_DXT_ROWS)) ) cvtest::DFT_1D( *tmp_src, *tmp_dst, flags ); else cvtest::DFT_2D( *tmp_src, *tmp_dst, flags ); if( tmp_dst != &dst ) cvtest::extract( *tmp_dst, dst, 0 ); } ////////////////////// DCT //////////////////////// class CxCore_DCTTest : public CxCore_DXTBaseTest { public: CxCore_DCTTest(); protected: void run_func(); void prepare_to_validation( int test_case_idx ); }; CxCore_DCTTest::CxCore_DCTTest() : CxCore_DXTBaseTest( false, false, false ) { } void CxCore_DCTTest::run_func() { Mat& dst = test_mat[OUTPUT][0]; const Mat& src = inplace ? dst : test_mat[INPUT][0]; if(!(flags & CV_DXT_INVERSE)) cv::dct( src, dst, flags ); else cv::idct( src, dst, flags & ~CV_DXT_INVERSE); } void CxCore_DCTTest::prepare_to_validation( int /*test_case_idx*/ ) { const Mat& src = test_mat[INPUT][0]; Mat& dst = test_mat[REF_OUTPUT][0]; if( src.rows == 1 || (src.cols == 1 && !(flags & CV_DXT_ROWS)) ) cvtest::DCT_1D( src, dst, flags ); else cvtest::DCT_2D( src, dst, flags ); } ////////////////////// MulSpectrums //////////////////////// class CxCore_MulSpectrumsTest : public CxCore_DXTBaseTest { public: CxCore_MulSpectrumsTest(); protected: void run_func(); void prepare_to_validation( int test_case_idx ); }; CxCore_MulSpectrumsTest::CxCore_MulSpectrumsTest() : CxCore_DXTBaseTest( true, true, true ) { } void CxCore_MulSpectrumsTest::run_func() { Mat& dst = !test_mat[TEMP].empty() && !test_mat[TEMP][0].empty() ? test_mat[TEMP][0] : test_mat[OUTPUT][0]; const Mat* src1 = &test_mat[INPUT][0], *src2 = &test_mat[INPUT][1]; if( inplace ) { if( ts->get_current_test_info()->test_case_idx & 1 ) src2 = &dst; else src1 = &dst; } cv::mulSpectrums( *src1, *src2, dst, flags, (flags & CV_DXT_MUL_CONJ) != 0 ); } void CxCore_MulSpectrumsTest::prepare_to_validation( int /*test_case_idx*/ ) { Mat* src1 = &test_mat[INPUT][0]; Mat* src2 = &test_mat[INPUT][1]; Mat& dst = test_mat[OUTPUT][0]; Mat& dst0 = test_mat[REF_OUTPUT][0]; int cn = src1->channels(); if( cn == 1 ) { cvtest::convertFromCCS( *src1, *src1, dst, flags ); cvtest::convertFromCCS( *src2, *src2, dst0, flags ); src1 = &dst; src2 = &dst0; } cvtest::mulComplex( *src1, *src2, dst0, flags ); if( cn == 1 ) { Mat& temp = test_mat[TEMP][0]; cvtest::convertFromCCS( temp, temp, dst, flags ); } } TEST(Core_DCT, accuracy) { CxCore_DCTTest test; test.safe_run(); } TEST(Core_DFT, accuracy) { CxCore_DFTTest test; test.safe_run(); } TEST(Core_MulSpectrums, accuracy) { CxCore_MulSpectrumsTest test; test.safe_run(); } class Core_DFTComplexOutputTest : public cvtest::BaseTest { public: Core_DFTComplexOutputTest() {} ~Core_DFTComplexOutputTest() {} protected: void run(int) { RNG& rng = theRNG(); for( int i = 0; i < 10; i++ ) { int m = rng.uniform(2, 11); int n = rng.uniform(2, 11); int depth = rng.uniform(0, 2) + CV_32F; Mat src8u(m, n, depth), src(m, n, depth), dst(m, n, CV_MAKETYPE(depth, 2)); Mat z = Mat::zeros(m, n, depth), dstz; randu(src8u, Scalar::all(0), Scalar::all(10)); src8u.convertTo(src, src.type()); dst = Scalar::all(123); Mat mv[] = {src, z}, srcz; merge(mv, 2, srcz); dft(srcz, dstz); dft(src, dst, DFT_COMPLEX_OUTPUT); if (cvtest::norm(dst, dstz, NORM_INF) > 1e-3) { cout << "actual:\n" << dst << endl << endl; cout << "reference:\n" << dstz << endl << endl; CV_Error(CV_StsError, ""); } } } }; TEST(Core_DFT, complex_output) { Core_DFTComplexOutputTest test; test.safe_run(); }
[ "daniel.herrera.castro@gmail.com" ]
daniel.herrera.castro@gmail.com
6ce0e1389ba3deb0cd4295b94c10391e42e2cc41
4b430686ae824c78604e15818c4b864778468ca1
/Library/Sources/Stroika/Foundation/Execution/Platform/POSIX/Users.cpp
42094b71d3f48b6e608ca16b582d78569d7692aa
[]
no_license
kjax/Stroika
59d559cbbcfb9fbd619155daaf39f6805fa79e02
3994269f67cd9029b9adf62e93ec0a3bfae60b5f
refs/heads/master
2021-01-17T23:05:33.441132
2012-07-22T04:32:58
2012-07-22T04:32:58
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,939
cpp
/* * Copyright(c) Sophist Solutions, Inc. 1990-2012. All rights reserved */ #include "../../../StroikaPreComp.h" #include "../../../Memory/SmallStackBuffer.h" #include "../../ErrNoException.h" #include "Users.h" using namespace Stroika::Foundation; using namespace Stroika::Foundation::Execution; using namespace Stroika::Foundation::Execution::Platform::POSIX; using Characters::String; /* ******************************************************************************** ************************ Platform::POSIX::UserName2UID ************************* ******************************************************************************** */ uid_t Platform::POSIX::UserName2UID (const String& name) { size_t bufsize = sysconf (_SC_GETPW_R_SIZE_MAX); if (bufsize == -1) { /* Value was indeterminate */ bufsize = 16384; /* Should be more than enough */ } Memory::SmallStackBuffer<char> buf (bufsize); struct passwd pwd; memset (&pwd, 0, sizeof (pwd)); struct passwd* result = nullptr; int err = getpwnam_r (name.AsTString ().c_str (), &pwd, buf, bufsize, &result); if (err < 0) { errno_ErrorException::DoThrow (err); } if (result == nullptr) { Execution::DoThrow (StringException (L"No such username")); } return pwd.pw_uid; } /* ******************************************************************************** ********************** Platform::POSIX::uid_t2UserName ************************* ******************************************************************************** */ String Platform::POSIX::uid_t2UserName (uid_t uid) { size_t bufsize = sysconf (_SC_GETPW_R_SIZE_MAX); if (bufsize == -1) { /* Value was indeterminate */ bufsize = 16384; /* Should be more than enough */ } Memory::SmallStackBuffer<char> buf (bufsize); struct passwd pwd; memset (&pwd, 0, sizeof (pwd)); struct passwd* result = nullptr; int err = getpwuid_r (uid, &pwd, buf, bufsize, &result); if (err < 0) { errno_ErrorException::DoThrow (err); } if (result == nullptr) { Execution::DoThrow (StringException (L"No such username")); } return String::FromTString (pwd.pw_name); } /* ******************************************************************************** ****************************** Platform::POSIX::GetUID ************************* ******************************************************************************** */ uid_t Platform::POSIX::GetUID () { return getuid (); } /* ******************************************************************************** ********************* Platform::POSIX::GetEffectiveUID ************************* ******************************************************************************** */ uid_t Platform::POSIX::GetEffectiveUID () { return geteuid (); }
[ "lewis@RecordsForLiving.com" ]
lewis@RecordsForLiving.com
20bdf02730c1f3bd89d42fb8b14770a0f896d600
2650018d43c862cfaed93a9f0c5ab0aa0ddbeed2
/include/GameObject.hpp
679589526197b2da88cb00a6c246166aa52bf818
[ "Unlicense" ]
permissive
jwhang627/Untitled-SDL2-Game
bd5ad037ed59cd4a1fad560b7c0b4c23ead956b0
bfd937445c3f24062a50ac996901a5affe231f3b
refs/heads/master
2023-01-10T21:52:20.373726
2020-11-13T08:46:50
2020-11-13T08:46:50
311,678,146
0
0
null
null
null
null
UTF-8
C++
false
false
527
hpp
#pragma once #include <SDL2/SDL.h> #include <SDL2/SDL_image.h> #include <iostream> #include "Math.hpp" class GameObject { public: GameObject(Vector2f p_pos, int p_w, int p_h, const char* p_filePath, SDL_Renderer* p_renderer); //~GameObject(); Vector2f& getPos(){ return pos; } SDL_Texture* getTexture(); SDL_Rect getCurrentFrame(); //float getZoom(){ // return o_zoom; //} private: Vector2f pos; int o_width; int o_height; //float o_zoom; SDL_Rect currentFrame; SDL_Texture* texture; };
[ "jaywhang627@gmail.com" ]
jaywhang627@gmail.com
4fee26494cb20be0a73a51610f3e7f9629f93ed3
382130ce40d1eb3e3c44ca16771cf38f83faf60a
/std-template/vector.cpp
2cb6ca40b1462ff7ca7b7b3b0b9780305636d1aa
[]
no_license
archdoor/cpp-program
42b458c17af89454053f60535d0c67d2c3517e08
b415b1060f8db254725750162963e36068aeb5b4
refs/heads/master
2020-12-02T22:10:55.475639
2017-07-06T10:05:11
2017-07-06T10:05:11
96,060,098
0
0
null
null
null
null
UTF-8
C++
false
false
1,685
cpp
/* * vector : 矢量,与数组对应 * * * * */ #include <iostream> #include <vector> #include <iterator> #include <assert.h> int main() { // 0. 创建空矢量对象 std::vector<int> v0; assert(v0.empty()); // 1. 创建含有3个元素的矢量对象,元素值0(默认) std::vector<int> v1(3); std::cout << "v1 = "; std::copy(v1.begin(), v1.end(), std::ostream_iterator<int>(std::cout, " ")); std::cout << std::endl; // 2. 创建含有5个元素的矢量对象,元素值2 std::vector<int> v2(5, 2); std::cout << "v2 = "; std::copy(v2.begin(), v2.end(), std::ostream_iterator<int>(std::cout, " ")); std::cout << std::endl; // 3. Create a vector v3 with 3 elements of value 1 and with the allocator of vector v2 std::vector<int> v3(3, 1, v2.get_allocator()); std::cout << "v3 = "; std::copy(v3.begin(), v3.end(), std::ostream_iterator<int>(std::cout, " ")); std::cout << std::endl; // 4. 用v2拷贝构造v4 std::vector<int> v4(v2); std::cout << "v4 = "; std::copy(v4.begin(), v4.end(), std::ostream_iterator<int>(std::cout, " ")); std::cout << std::endl; // 5. 用v4中的一部分拷贝构造v5 std::vector<int> v5(v4.begin() + 1, v4.begin() + 3); std::cout << "v5 = "; std::copy(v5.begin(), v5.end(), std::ostream_iterator<int>(std::cout, " ")); std::cout << std::endl; // Move vector v2 to vector v6 std::vector<int> v6(move(v2)); std::cout << "v6 = "; std::copy(v6.begin(), v6.end(), std::ostream_iterator<int>(std::cout, " ")); std::cout << std::endl; return 0; }
[ "archdoor@outlool.com" ]
archdoor@outlool.com
df0db99353344d8ee767624cf2feb11f5a3e4974
251aaf143dab1a24322cd47416e2a14de76bf773
/STM32F469_Controller/Source/TouchGFX/TouchGFX/generated/texts/src/TypedTextDatabase.cpp
3e3948d971be061c4041c97b63cd8413e200ff90
[ "Zlib" ]
permissive
ftkalcevic/DCC
fddc7de6cc6c2c4b758451c444f7cc0131897224
b68aebab35423f21e0a6a337c11d967f6f8912a2
refs/heads/master
2022-12-10T12:24:52.928864
2020-07-30T08:16:46
2020-07-30T08:16:46
121,176,875
0
0
null
2022-12-08T10:16:01
2018-02-11T23:12:08
C
UTF-8
C++
false
false
4,608
cpp
/* DO NOT EDIT THIS FILE */ /* This file is autogenerated by the text-database code generator */ #include <touchgfx/TypedText.hpp> #include <fonts/GeneratedFont.hpp> #include <texts/TypedTextDatabase.hpp> extern touchgfx::GeneratedFont& getFont_Asap_Regular_80_4bpp(); extern touchgfx::GeneratedFont& getFont_Asap_Regular_40_4bpp(); extern touchgfx::GeneratedFont& getFont_consola_40_4bpp(); extern touchgfx::GeneratedFont& getFont_Asap_Regular_28_4bpp(); extern touchgfx::GeneratedFont& getFont_Asap_Regular_20_4bpp(); const touchgfx::Font* _fonts[] = { &(getFont_Asap_Regular_80_4bpp()), &(getFont_Asap_Regular_40_4bpp()), &(getFont_consola_40_4bpp()), &(getFont_Asap_Regular_28_4bpp()), &(getFont_Asap_Regular_20_4bpp()) }; extern const touchgfx::TypedText::TypedTextData typedText_database_DEFAULT[]; extern const touchgfx::TypedText::TypedTextData* const typedTextDatabaseArray[]; TEXT_LOCATION_FLASH_PRAGMA const touchgfx::TypedText::TypedTextData typedText_database_DEFAULT[] TEXT_LOCATION_FLASH_ATTRIBUTE = { { 0, touchgfx::LEFT, touchgfx::TEXT_DIRECTION_LTR }, { 4, touchgfx::LEFT, touchgfx::TEXT_DIRECTION_LTR }, { 4, touchgfx::LEFT, touchgfx::TEXT_DIRECTION_LTR }, { 4, touchgfx::CENTER, touchgfx::TEXT_DIRECTION_LTR }, { 4, touchgfx::LEFT, touchgfx::TEXT_DIRECTION_LTR }, { 4, touchgfx::LEFT, touchgfx::TEXT_DIRECTION_LTR }, { 4, touchgfx::LEFT, touchgfx::TEXT_DIRECTION_LTR }, { 4, touchgfx::LEFT, touchgfx::TEXT_DIRECTION_LTR }, { 4, touchgfx::LEFT, touchgfx::TEXT_DIRECTION_LTR }, { 4, touchgfx::LEFT, touchgfx::TEXT_DIRECTION_LTR }, { 4, touchgfx::LEFT, touchgfx::TEXT_DIRECTION_LTR }, { 4, touchgfx::LEFT, touchgfx::TEXT_DIRECTION_LTR }, { 4, touchgfx::LEFT, touchgfx::TEXT_DIRECTION_LTR }, { 4, touchgfx::LEFT, touchgfx::TEXT_DIRECTION_LTR }, { 4, touchgfx::CENTER, touchgfx::TEXT_DIRECTION_LTR }, { 4, touchgfx::CENTER, touchgfx::TEXT_DIRECTION_LTR }, { 4, touchgfx::CENTER, touchgfx::TEXT_DIRECTION_LTR }, { 4, touchgfx::CENTER, touchgfx::TEXT_DIRECTION_LTR }, { 1, touchgfx::CENTER, touchgfx::TEXT_DIRECTION_LTR }, { 1, touchgfx::CENTER, touchgfx::TEXT_DIRECTION_LTR }, { 1, touchgfx::LEFT, touchgfx::TEXT_DIRECTION_LTR }, { 1, touchgfx::CENTER, touchgfx::TEXT_DIRECTION_LTR }, { 1, touchgfx::LEFT, touchgfx::TEXT_DIRECTION_LTR }, { 1, touchgfx::LEFT, touchgfx::TEXT_DIRECTION_LTR }, { 1, touchgfx::LEFT, touchgfx::TEXT_DIRECTION_LTR }, { 1, touchgfx::LEFT, touchgfx::TEXT_DIRECTION_LTR }, { 1, touchgfx::LEFT, touchgfx::TEXT_DIRECTION_LTR }, { 1, touchgfx::LEFT, touchgfx::TEXT_DIRECTION_LTR }, { 2, touchgfx::LEFT, touchgfx::TEXT_DIRECTION_LTR }, { 3, touchgfx::LEFT, touchgfx::TEXT_DIRECTION_LTR }, { 4, touchgfx::LEFT, touchgfx::TEXT_DIRECTION_LTR }, { 4, touchgfx::LEFT, touchgfx::TEXT_DIRECTION_LTR }, { 3, touchgfx::LEFT, touchgfx::TEXT_DIRECTION_LTR }, { 1, touchgfx::CENTER, touchgfx::TEXT_DIRECTION_LTR }, { 4, touchgfx::CENTER, touchgfx::TEXT_DIRECTION_LTR }, { 1, touchgfx::CENTER, touchgfx::TEXT_DIRECTION_LTR }, { 1, touchgfx::LEFT, touchgfx::TEXT_DIRECTION_LTR }, { 1, touchgfx::LEFT, touchgfx::TEXT_DIRECTION_LTR }, { 1, touchgfx::CENTER, touchgfx::TEXT_DIRECTION_LTR }, { 1, touchgfx::CENTER, touchgfx::TEXT_DIRECTION_LTR }, { 3, touchgfx::CENTER, touchgfx::TEXT_DIRECTION_LTR } }; TEXT_LOCATION_FLASH_PRAGMA const touchgfx::TypedText::TypedTextData* const typedTextDatabaseArray[] TEXT_LOCATION_FLASH_ATTRIBUTE = { typedText_database_DEFAULT }; namespace TypedTextDatabase { const touchgfx::TypedText::TypedTextData* getInstance(touchgfx::LanguageId id) { return typedTextDatabaseArray[id]; } uint16_t getInstanceSize() { return sizeof(typedText_database_DEFAULT) / sizeof(touchgfx::TypedText::TypedTextData); } const touchgfx::Font** getFonts() { return _fonts; } const touchgfx::Font* setFont(touchgfx::FontId fontId, const touchgfx::Font* font) { const touchgfx::Font* old = _fonts[fontId]; _fonts[fontId] = font; return old; } void resetFont(touchgfx::FontId fontId) { switch (fontId) { case 0: _fonts[0] = &(getFont_Asap_Regular_80_4bpp()); break; case 1: _fonts[1] = &(getFont_Asap_Regular_40_4bpp()); break; case 2: _fonts[2] = &(getFont_consola_40_4bpp()); break; case 3: _fonts[3] = &(getFont_Asap_Regular_28_4bpp()); break; case 4: _fonts[4] = &(getFont_Asap_Regular_20_4bpp()); break; } } } // namespace TypedTextDatabase
[ "frank@franksworkshop.com.au" ]
frank@franksworkshop.com.au
b5e5411ca387d4864e32d9a4c4a1831f05509299
c2a3f7bea93aa4f9b64071d94e26e34bf4475f7a
/llpe/main/Shadows.cpp
adf1cdb3536c5fe38ec7c88518481ad4c2b8cddd
[ "LicenseRef-scancode-unknown-license-reference", "NCSA" ]
permissive
waywardmonkeys/llpe
b1ce41605f99eb1f85e1833c216ffd99f015f755
ff7968b059883f0cdbfac590d1dfe0c6307f0bd0
refs/heads/master
2020-12-03T05:14:24.778976
2015-04-12T23:08:32
2015-04-12T23:08:32
33,902,421
0
0
null
2015-04-14T00:54:10
2015-04-14T00:54:10
null
UTF-8
C++
false
false
26,261
cpp
//===- Shadows.cpp --------------------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // Implement guts of instruction and block shadow structures, as well as utility routines for generating them // from a function or block. #include "llvm/IR/Module.h" #include "llvm/IR/Function.h" #include "llvm/IR/BasicBlock.h" #include "llvm/IR/Dominators.h" #include "llvm/IR/InstIterator.h" #include "llvm/IR/Instruction.h" #include "llvm/Analysis/AliasAnalysis.h" #include "llvm/Analysis/LoopInfo.h" #include "llvm/Analysis/LLPE.h" using namespace llvm; void llvm::createTopOrderingFrom(BasicBlock* BB, std::vector<BasicBlock*>& Result, SmallSet<BasicBlock*, 8>& Visited, LoopInfo* LI, const Loop* MyL) { const Loop* BBL = LI ? LI->getLoopFor(BB) : 0; // Drifted out of scope? if(MyL != BBL && ((!BBL) || (BBL->contains(MyL)))) return; auto insertres = Visited.insert(BB); if(!insertres.second) return; // Follow loop exiting edges if any if(MyL != BBL) { SmallVector<BasicBlock*, 4> ExitBlocks; BBL->getExitBlocks(ExitBlocks); for(SmallVector<BasicBlock*, 4>::iterator it = ExitBlocks.begin(), it2 = ExitBlocks.end(); it != it2; ++it) { createTopOrderingFrom(*it, Result, Visited, LI, MyL); } } // Explore all successors within this loop: for(succ_iterator SI = succ_begin(BB), SE = succ_end(BB); SI != SE; ++SI) { createTopOrderingFrom(*SI, Result, Visited, LI, BBL); } Result.push_back(BB); } static void ignoreChildLoops(SmallSet<BasicBlock*, 1>& headers, const Loop* L) { headers.insert(L->getHeader()); for(Loop::iterator it = L->begin(), itend = L->end(); it != itend; ++it) ignoreChildLoops(headers, *it); } ShadowLoopInvar* LLPEAnalysisPass::getLoopInfo(ShadowFunctionInvar* FInfo, DenseMap<BasicBlock*, uint32_t>& BBIndices, const Loop* L, DominatorTree* DT, ShadowLoopInvar* ParentLoop) { release_assert(L->isLoopSimplifyForm() && L->isLCSSAForm(*DT) && "Don't forget to run loopsimplify and lcssa first!"); ShadowLoopInvar* LInfo = new ShadowLoopInvar(); LInfo->headerIdx = BBIndices[L->getHeader()]; LInfo->preheaderIdx = BBIndices[L->getLoopPreheader()]; LInfo->latchIdx = BBIndices[L->getLoopLatch()]; LInfo->nBlocks = L->getBlocks().size(); LInfo->parent = ParentLoop; // If we're supposed to ignore this loop and all children, register them now so that applyIgnoreLoops // does the right thing. BasicBlock* HBB = L->getHeader(); Function* LF = HBB->getParent(); if(shouldIgnoreLoopChildren(LF, HBB)) ignoreChildLoops(ignoreLoops[LF], L); LInfo->optimisticEdge = std::make_pair(0xffffffff, 0xffffffff); for(uint32_t i = LInfo->headerIdx, ilim = LInfo->headerIdx + L->getNumBlocks(); i != ilim; ++i) { // TODO: Fix or discard outerScope. // Note these will be overwritten if the block is also within a child loop. FInfo->BBs[i].outerScope = applyIgnoreLoops(LInfo, LF, FInfo); FInfo->BBs[i].naturalScope = LInfo; BasicBlock* OptEdgeSink = getOptimisticEdge(LF, FInfo->BBs[i].BB); if(OptEdgeSink) { release_assert(LInfo->optimisticEdge.first == 0xffffffff && "Only one optimistic edge allowed per loop"); LInfo->optimisticEdge = std::make_pair(i, BBIndices[OptEdgeSink]); } } LInfo->alwaysIterate = shouldAlwaysIterate(LF, HBB); { SmallVector<BasicBlock*, 4> temp; L->getExitingBlocks(temp); { LInfo->exitingBlocks.reserve(temp.size()); for(unsigned i = 0; i < temp.size(); ++i) LInfo->exitingBlocks.push_back(BBIndices[temp[i]]); } temp.clear(); L->getExitBlocks(temp); { LInfo->exitBlocks.reserve(temp.size()); for(unsigned i = 0; i < temp.size(); ++i) LInfo->exitBlocks.push_back(BBIndices[temp[i]]); } } { SmallVector<std::pair<const BasicBlock*, const BasicBlock*>, 4> exitEdges; L->getExitEdges(exitEdges); LInfo->exitEdges.reserve(exitEdges.size()); for(unsigned i = 0; i < exitEdges.size(); ++i) LInfo->exitEdges.push_back(std::make_pair(BBIndices[const_cast<BasicBlock*>(exitEdges[i].first)], BBIndices[const_cast<BasicBlock*>(exitEdges[i].second)])); } for(Loop::iterator it = L->begin(), itend = L->end(); it != itend; ++it) { ShadowLoopInvar* child = getLoopInfo(FInfo, BBIndices, *it, DT, LInfo); LInfo->childLoops.push_back(child); } return LInfo; } void LLPEAnalysisPass::initShadowGlobals(Module& M, uint32_t extraSlots) { uint32_t i = 0; uint32_t nGlobals = std::distance(M.global_begin(), M.global_end()); // extraSlots are reserved for new globals we know will be introduced between now and specialisation start. nGlobals += extraSlots; shadowGlobals = new ShadowGV[nGlobals]; // Assign them all numbers before computing initialisers, because the initialiser can // reference another global, and getValPB will then lookup in shadowGlobalsIdx. for(Module::global_iterator it = M.global_begin(), itend = M.global_end(); it != itend; ++it, ++i) { shadowGlobals[i].G = it; shadowGlobalsIdx[it] = i; } i = 0; for(Module::global_iterator it = M.global_begin(), itend = M.global_end(); it != itend; ++it, ++i) { if(it->isConstant()) { shadowGlobals[i].storeSize = GlobalAA->getTypeStoreSize(shadowGlobals[i].G->getType()); continue; } shadowGlobals[i].allocIdx = (int32_t)heap.size(); heap.push_back(AllocData()); AllocData& AD = heap.back(); AD.allocIdx = heap.size() - 1; AD.storeSize = GlobalAA->getTypeStoreSize(it->getType()->getElementType()); AD.isCommitted = true; AD.allocValue = ShadowValue(&(shadowGlobals[i])); AD.allocType = shadowGlobals[i].G->getType(); //errs() << "Init store for " << *it << " -> "; //printPB(errs(), *Init); //errs() << "\n"; shadowGlobals[i].storeSize = AD.storeSize; } } const GlobalValue* llvm::getUnderlyingGlobal(const GlobalValue* V) { if(const GlobalAlias* GA = dyn_cast<GlobalAlias>(V)) { const GlobalValue* Aliasee = dyn_cast_or_null<GlobalValue>(GA->getAliasee()); if(!Aliasee) return 0; else return getUnderlyingGlobal(Aliasee); } return V; } static const GlobalVariable* getGlobalVar(const Value* V) { const GlobalValue* GV = dyn_cast<GlobalValue>(V); if(!GV) return 0; return dyn_cast<GlobalVariable>(getUnderlyingGlobal(GV)); } ShadowFunctionInvar* LLPEAnalysisPass::getFunctionInvarInfo(Function& F) { DenseMap<Function*, ShadowFunctionInvar*>::iterator findit = functionInfo.find(&F); if(findit != functionInfo.end()) return findit->second; // Beware! This LoopInfo instance and whatever Loop objects come from it are only alive until // the next call to getAnalysis. Therefore the ShadowLoopInvar objects we make here // must mirror all information we're interested in from the Loops. LoopInfo* LI = &getAnalysis<LoopInfo>(F); ShadowFunctionInvar* RetInfoP = new ShadowFunctionInvar(); functionInfo[&F] = RetInfoP; ShadowFunctionInvar& RetInfo = *RetInfoP; std::vector<BasicBlock*> TopOrderedBlocks; SmallSet<BasicBlock*, 8> VisitedBlocks; createTopOrderingFrom(&F.getEntryBlock(), TopOrderedBlocks, VisitedBlocks, LI, /* loop = */ 0); std::reverse(TopOrderedBlocks.begin(), TopOrderedBlocks.end()); // Assign indices to each BB and instruction (IIndices is useful since otherwise we have to walk // the instruction list to get from an instruction to its index) DenseMap<BasicBlock*, uint32_t> BBIndices; DenseMap<Instruction*, uint32_t> IIndices; for(uint32_t i = 0; i < TopOrderedBlocks.size(); ++i) { BasicBlock* BB = TopOrderedBlocks[i]; BBIndices[BB] = i; uint32_t j; BasicBlock::iterator it, endit; for(j = 0, it = BB->begin(), endit = BB->end(); it != endit; ++it, ++j) { IIndices[it] = j; } } ShadowBBInvar* FShadowBlocks = new ShadowBBInvar[TopOrderedBlocks.size()]; for(uint32_t i = 0; i < TopOrderedBlocks.size(); ++i) { BasicBlock* BB = TopOrderedBlocks[i]; ShadowBBInvar& SBB = FShadowBlocks[i]; SBB.F = &RetInfo; SBB.idx = i; SBB.BB = BB; // True loop scope will be computed later, but by default... SBB.outerScope = 0; SBB.naturalScope = 0; const Loop* BBScope = LI->getLoopFor(BB); // Find successor block indices: succ_iterator SI = succ_begin(BB), SE = succ_end(BB); uint32_t succSize = std::distance(SI, SE); SBB.succIdxs = ImmutableArray<uint32_t>(new uint32_t[succSize], succSize); for(uint32_t j = 0; SI != SE; ++SI, ++j) { SBB.succIdxs[j] = BBIndices[*SI]; } // Find predecessor block indices: pred_iterator PI = pred_begin(BB), PE = pred_end(BB); uint32_t predSize = std::distance(PI, PE); SBB.predIdxs = ImmutableArray<uint32_t>(new uint32_t[predSize], predSize); for(uint32_t j = 0; PI != PE; ++PI, ++j) { SBB.predIdxs[j] = BBIndices[*PI]; if(SBB.predIdxs[j] > i) { if((!BBScope) || SBB.BB != BBScope->getHeader()) { errs() << "Warning: block " << SBB.BB->getName() << " in " << F.getName() << " has predecessor " << (*PI)->getName() << " that comes after it topologically, but this is not a loop header. The program is not in well-nested natural loop form.\n"; } } } // Find instruction def/use indices: ShadowInstructionInvar* insts = new ShadowInstructionInvar[BB->size()]; BasicBlock::iterator BI = BB->begin(), BE = BB->end(); for(uint32_t j = 0; BI != BE; ++BI, ++j) { Instruction* I = BI; ShadowInstructionInvar& SI = insts[j]; SI.idx = j; SI.parent = &SBB; SI.I = I; // Get operands indices: uint32_t NumOperands; ShadowInstIdx* operandIdxs; if(PHINode* PN = dyn_cast<PHINode>(I)) { NumOperands = PN->getNumIncomingValues(); operandIdxs = new ShadowInstIdx[NumOperands]; uint32_t* incomingBBs = new uint32_t[NumOperands]; for(unsigned k = 0, kend = PN->getNumIncomingValues(); k != kend; ++k) { if(Instruction* OpI = dyn_cast<Instruction>(PN->getIncomingValue(k))) operandIdxs[k] = ShadowInstIdx(BBIndices[OpI->getParent()], IIndices[OpI]); else if(GlobalVariable* OpGV = const_cast<GlobalVariable*>(getGlobalVar(PN->getIncomingValue(k)))) operandIdxs[k] = ShadowInstIdx(INVALID_BLOCK_IDX, getShadowGlobalIndex(OpGV)); else operandIdxs[k] = ShadowInstIdx(); incomingBBs[k] = BBIndices[PN->getIncomingBlock(k)]; } SI.operandBBs = ImmutableArray<uint32_t>(incomingBBs, NumOperands); } else { NumOperands = I->getNumOperands(); operandIdxs = new ShadowInstIdx[NumOperands]; for(unsigned k = 0, kend = I->getNumOperands(); k != kend; ++k) { if(Instruction* OpI = dyn_cast<Instruction>(I->getOperand(k))) operandIdxs[k] = ShadowInstIdx(BBIndices[OpI->getParent()], IIndices[OpI]); else if(GlobalVariable* OpGV = const_cast<GlobalVariable*>(getGlobalVar(I->getOperand(k)))) operandIdxs[k] = ShadowInstIdx(INVALID_BLOCK_IDX, getShadowGlobalIndex(OpGV)); else if(BasicBlock* OpBB = dyn_cast<BasicBlock>(I->getOperand(k))) operandIdxs[k] = ShadowInstIdx(BBIndices[OpBB], INVALID_INSTRUCTION_IDX); else operandIdxs[k] = ShadowInstIdx(); } } SI.operandIdxs = ImmutableArray<ShadowInstIdx>(operandIdxs, NumOperands); // Get user indices: unsigned nUsers = std::distance(I->use_begin(), I->use_end()); ShadowInstIdx* userIdxs = new ShadowInstIdx[nUsers]; Instruction::use_iterator UI; unsigned k; for(k = 0, UI = I->use_begin(); k != nUsers; ++k, ++UI) { if(Instruction* UserI = dyn_cast<Instruction>(UI->getUser())) { userIdxs[k] = ShadowInstIdx(BBIndices[UserI->getParent()], IIndices[UserI]); } else { userIdxs[k] = ShadowInstIdx(); } } SI.userIdxs = ImmutableArray<ShadowInstIdx>(userIdxs, nUsers); } SBB.insts = ImmutableArray<ShadowInstructionInvar>(insts, BB->size()); } RetInfo.BBs = ImmutableArray<ShadowBBInvar>(FShadowBlocks, TopOrderedBlocks.size()); // Get user info for arguments: ShadowArgInvar* Args = new ShadowArgInvar[F.arg_size()]; Function::arg_iterator AI = F.arg_begin(); uint32_t i = 0; for(; i != F.arg_size(); ++i, ++AI) { Argument* A = AI; ShadowArgInvar& SArg = Args[i]; SArg.A = A; unsigned j = 0; Argument::use_iterator UI = A->use_begin(), UE = A->use_end(); uint32_t nUsers = std::distance(UI, UE); ShadowInstIdx* Users = new ShadowInstIdx[nUsers]; for(; UI != UE; ++UI, ++j) { Value* UsedV = *UI; if(Instruction* UsedI = dyn_cast<Instruction>(UsedV)) { Users[j] = ShadowInstIdx(BBIndices[UsedI->getParent()], IIndices[UsedI]); } else { Users[j] = ShadowInstIdx(); } } SArg.userIdxs = ImmutableArray<ShadowInstIdx>(Users, nUsers); } RetInfo.Args = ImmutableArray<ShadowArgInvar>(Args, F.arg_size()); // Populate map from loop headers to header index. Due to the topological sort, // all loops consist of that block + L->getBlocks().size() further, contiguous blocks, // making is-in-loop easy to compute. DominatorTree* thisDT = DTs[&F]; for(LoopInfo::iterator it = LI->begin(), it2 = LI->end(); it != it2; ++it) { ShadowLoopInvar* newL = getLoopInfo(&RetInfo, BBIndices, *it, thisDT, 0); RetInfo.TopLevelLoops.push_back(newL); } // Count alloca instructions at the start of the function; this will control how // large the std::vector that represents the frame will be initialised. RetInfo.frameSize = 0; for(BasicBlock::iterator it = F.getEntryBlock().begin(), itend = F.getEntryBlock().end(); it != itend && isa<AllocaInst>(it); ++it) ++RetInfo.frameSize; // "&& RootIA" checks whether we're inside the initial context creation, in which case we should // allocate a frame whether or not main can ever allocate to avoid the frame index underflowing // in some circumstances. if((!RetInfo.frameSize) && RootIA) { // Magic value indicating the function will never alloca anything and we can skip all frame processing. RetInfo.frameSize = -1; for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E && RetInfo.frameSize == -1; ++I) { if(isa<AllocaInst>(*I)) RetInfo.frameSize = 0; } } return RetInfoP; } // Prepare the context-specific data structures, tying them to known invariant information. // For an inline attempt, create a BB array void InlineAttempt::prepareShadows() { invarInfo = pass->getFunctionInvarInfo(F); nBBs = F.size(); release_assert(nBBs == invarInfo->BBs.size() && "Function contains unreachable blocks, run simplifycfg first!"); BBs = new ShadowBB*[nBBs]; for(uint32_t i = 0; i < nBBs; ++i) BBs[i] = 0; BBsOffset = 0; uint32_t shadowsSize; if(isPathCondition || !Callers.size()) shadowsSize = F.arg_size(); else shadowsSize = Callers[0]->getNumArgOperands(); ShadowArg* argShadows = new ShadowArg[shadowsSize]; this->argShadows = ImmutableArray<ShadowArg>(argShadows, shadowsSize); uint32_t i = 0; for(; i != F.arg_size(); ++i) { argShadows[i].invar = &(invarInfo->Args[i]); argShadows[i].IA = this; argShadows[i].dieStatus = 0; argShadows[i].patchInst = 0; argShadows[i].committedVal = 0; } for(; i != shadowsSize; ++i) { argShadows[i].invar = 0; argShadows[i].IA = this; argShadows[i].dieStatus = 0; argShadows[i].patchInst = 0; argShadows[i].committedVal = 0; } } void PeelIteration::prepareShadows() { invarInfo = pass->getFunctionInvarInfo(F); nBBs = L->nBlocks; BBs = new ShadowBB*[nBBs]; for(uint32_t i = 0; i < nBBs; ++i) BBs[i] = 0; BBsOffset = parentPA->L->headerIdx; } ShadowBB* IntegrationAttempt::getOrCreateBB(uint32_t i) { if(ShadowBB* BB = getBB(i)) return BB; return createBB(i); } ShadowBB* IntegrationAttempt::getOrCreateBB(ShadowBBInvar* BBI) { bool inScope; if(ShadowBB* BB = getBB(*BBI, &inScope)) return BB; release_assert(inScope && "getOrCreateBB in wrong scope"); return createBB(BBI); } ShadowBBInvar* IntegrationAttempt::getBBInvar(uint32_t idx) const { return &(invarInfo->BBs[idx]); } ShadowBB* IntegrationAttempt::getUniqueBBRising(ShadowBBInvar* BBI) { if(BBI->naturalScope == L) return getBB(*BBI); if(PeelAttempt* LPA = getPeelAttempt(immediateChildLoop(L, BBI->naturalScope))) { if(LPA->isTerminated() && LPA->Iterations.back()->isOnlyExitingIteration()) { return LPA->Iterations.back()->getUniqueBBRising(BBI); } } return 0; } ShadowBB* IntegrationAttempt::createBB(uint32_t blockIdx) { release_assert((!BBs[blockIdx - BBsOffset]) && "Creating block for the second time"); ShadowBB* newBB = new ShadowBB(); newBB->invar = &(invarInfo->BBs[blockIdx]); newBB->succsAlive = new bool[newBB->invar->succIdxs.size()]; for(unsigned i = 0, ilim = newBB->invar->succIdxs.size(); i != ilim; ++i) newBB->succsAlive[i] = false; newBB->status = BBSTATUS_UNKNOWN; newBB->IA = this; ShadowInstruction* insts = new ShadowInstruction[newBB->invar->insts.size()]; for(uint32_t i = 0, ilim = newBB->invar->insts.size(); i != ilim; ++i) { insts[i].invar = &(newBB->invar->insts[i]); insts[i].parent = newBB; insts[i].dieStatus = 0; insts[i].isThreadLocal = TLS_MUSTCHECK; insts[i].needsRuntimeCheck = RUNTIME_CHECK_NONE; insts[i].typeSpecificData = 0; } newBB->insts = ImmutableArray<ShadowInstruction>(insts, newBB->invar->insts.size()); newBB->useSpecialVarargMerge = false; newBB->localStore = 0; BBs[blockIdx - BBsOffset] = newBB; return newBB; } ShadowBB* IntegrationAttempt::createBB(ShadowBBInvar* BBI) { return createBB(BBI->idx); } ShadowInstructionInvar* IntegrationAttempt::getInstInvar(uint32_t blockidx, uint32_t instidx) { return &(invarInfo->BBs[blockidx].insts[instidx]); } ShadowInstruction* InlineAttempt::getInstFalling(ShadowBBInvar* BB, uint32_t instIdx) { release_assert((!BB->outerScope) && "Out of scope in getInstFalling"); ShadowBB* LocalBB = getBB(*BB); if(!LocalBB) return 0; return &(LocalBB->insts[instIdx]); } ShadowInstruction* PeelIteration::getInstFalling(ShadowBBInvar* BB, uint32_t instIdx) { if(BB->outerScope == L) { ShadowBB* LocalBB = getBB(*BB); if(!LocalBB) return 0; return &(LocalBB->insts[instIdx]); } else { return parent->getInstFalling(BB, instIdx); } } ShadowInstruction* IntegrationAttempt::getInst(uint32_t blockIdx, uint32_t instIdx) { bool inScope; ShadowBB* OpBB = getBB(blockIdx, &inScope); if(!inScope) { // Access to parent context. ShadowBBInvar* OpBBI = &(invarInfo->BBs[blockIdx]); return getInstFalling(OpBBI, instIdx); } else if(!OpBB) { return 0; } else { return &(OpBB->insts[instIdx]); } } ShadowInstruction* IntegrationAttempt::getInst(ShadowInstructionInvar* SII) { return getInst(SII->parent->idx, SII->idx); } ShadowValue ShadowValue::getInt(Type* CIT, uint64_t CIVal) { if(CIT->isIntegerTy(8)) return ShadowValue::getInt8((uint8_t)CIVal); else if(CIT->isIntegerTy(16)) return ShadowValue::getInt16((uint16_t)CIVal); else if(CIT->isIntegerTy(32)) return ShadowValue::getInt32((uint32_t)CIVal); else if(CIT->isIntegerTy(64)) return ShadowValue::getInt64(CIVal); else return ShadowValue(ConstantInt::get(CIT, CIVal)); } // Get the ShadowValue for this instruction's operand. // For most kinds of ShadowValue they're just passed through, // but for ShadowInstructions we must make sure if the operand is // a loop invariant then we find the right version of the SI. // Note that due to LCSSA form operands are always in the same context or a parent, // except for exit PHI operands, which are special cased in HCF's // getPHINodeValue function. ShadowValue ShadowInstruction::getOperand(uint32_t i) { ShadowInstIdx& SII = invar->operandIdxs[i]; uint32_t blockOpIdx = SII.blockIdx; if(blockOpIdx == INVALID_BLOCK_IDX) { Value* ArgV = invar->I->getOperand(i); if(SII.instIdx != INVALID_INSTRUCTION_IDX) { return ShadowValue(&(parent->IA->pass->shadowGlobals[SII.instIdx])); } else if(Argument* A = dyn_cast<Argument>(ArgV)) { return ShadowValue(&(parent->IA->getFunctionRoot()->argShadows[A->getArgNo()])); } else if(ConstantInt* CI = dyn_cast<ConstantInt>(ArgV)) { return ShadowValue::getInt(CI->getType(), CI->getLimitedValue()); } else { return ShadowValue(ArgV); } } else if(SII.instIdx == INVALID_INSTRUCTION_IDX) { // BasicBlock operand, only encountered on this path with Invoke instructions. return ShadowValue(); } else { ShadowInstruction* OpInst = parent->IA->getInst(blockOpIdx, SII.instIdx); if(OpInst) return ShadowValue(OpInst); else return ShadowValue(); } } ShadowInstruction* ShadowInstruction::getUser(uint32_t i) { ShadowInstIdx& SII = invar->userIdxs[i]; return &(parent->IA->BBs[SII.blockIdx]->insts[SII.instIdx]); } void IntegrationAttempt::copyLoopExitingDeadEdges(PeelAttempt* LPA) { const std::vector<std::pair<uint32_t, uint32_t> >& EE = LPA->L->exitEdges; for(uint32_t i = 0; i < EE.size(); ++i) { std::pair<uint32_t, uint32_t> E = EE[i]; if(ShadowBB* BB = getOrCreateBB(E.first)) { bool dead = edgeIsDeadRising(*BB->invar, *getBBInvar(E.second), /* ignoreThisScope = */ true); for(uint32_t j = 0; j < BB->invar->succIdxs.size(); ++j) { if(BB->invar->succIdxs[j] == E.second) BB->succsAlive[j] = !dead; } } } } bool llvm::blockAssumedToExecute(ShadowBB* BB) { return BB->status != BBSTATUS_UNKNOWN; } bool llvm::blockCertainlyExecutes(ShadowBB* BB) { return BB->status == BBSTATUS_CERTAIN; } bool AllocData::isAvailable() { if(isCommitted) return !!committedVal; else return allocValue.getCtx()->allAncestorsEnabled(); } bool FDGlobalState::isAvailable() { if(isCommitted) return !!CommittedVal; else if(isFifo) return false; else return SI->parent->IA->allAncestorsEnabled(); } bool ShadowValue::objectAvailable() const { switch(t) { case SHADOWVAL_OTHER: { if(Function* F = dyn_cast<Function>(u.V)) return !GlobalIHP->specialLocations.count(F); else return true; } case SHADOWVAL_GV: case SHADOWVAL_ARG: return true; case SHADOWVAL_INST: if(u.I->parent->IA->getFunctionRoot()->isPathCondition) return false; if(!u.I->parent->IA->allAncestorsEnabled()) return false; return true; case SHADOWVAL_PTRIDX: // Stack-allocated members are necessarily available from any context // that can conceivably reach them. if(u.PtrOrFd.frame != -1) return true; else { AllocData* AD = getAllocData((OrdinaryLocalStore*)0); return AD->isAvailable(); } case SHADOWVAL_FDIDX: case SHADOWVAL_FDIDX64: return GlobalIHP->fds[getFd()].isAvailable(); default: release_assert(0 && "Bad SV type in objectAvailableFrom"); llvm_unreachable("Bad SV type in objectAvailableFrom"); } } BasicBlock* ShadowBB::getCommittedBreakBlockAt(uint32_t idx) { for(uint32_t i = 0, ilim = committedBlocks.size(); i != ilim; ++i) { CommittedBlock& Block = committedBlocks[i]; if(Block.startIndex <= idx) { if(i + 1 == ilim || committedBlocks[i + 1].startIndex > idx) return Block.breakBlock; } } release_assert("Failed to find block index"); return 0; } ShadowBB* PeelIteration::getUniqueExitingBlock2(ShadowBBInvar* BBI, const ShadowLoopInvar* exitLoop, bool& bail) { PeelAttempt* LPA; // Defer to child loop iteration? if(BBI->naturalScope != L && (LPA = getPeelAttempt(immediateChildLoop(L, BBI->naturalScope))) && LPA->isTerminated()) { return LPA->Iterations.back()->getUniqueExitingBlock2(BBI, exitLoop, bail); } // Find a unique exiting edge if there is one. ShadowBB* ExitingBB = getBB(*BBI); if(!ExitingBB) return 0; uint32_t exitingEdges = 0; for(uint32_t i = 0, ilim = BBI->succIdxs.size(); i != ilim && exitingEdges < 2; ++i) { ShadowBBInvar* ExitedBBI = getBBInvar(BBI->succIdxs[i]); if(ExitingBB->succsAlive[i] && ((!ExitedBBI->naturalScope) || !exitLoop->contains(ExitedBBI->naturalScope))) { ++exitingEdges; } } if(exitingEdges == 0) return 0; else if(exitingEdges == 1) return ExitingBB; else { bail = true; return 0; } } ShadowBB* PeelIteration::getUniqueExitingBlock() { ShadowBB* uniqueBlock = 0; for(std::vector<uint32_t>::const_iterator it = parentPA->L->exitingBlocks.begin(), itend = parentPA->L->exitingBlocks.end(); it != itend; ++it) { ShadowBBInvar* ExitingBBI = getBBInvar(*it); bool bail = false; ShadowBB* ExitingBB = getUniqueExitingBlock2(ExitingBBI, L, bail); if(bail) return 0; else if(ExitingBB) { if(uniqueBlock) return 0; else uniqueBlock = ExitingBB; } } return uniqueBlock; } bool ShadowInstruction::readsMemoryDirectly() { if(isCopyInst()) return true; switch(invar->I->getOpcode()) { case Instruction::Load: case Instruction::AtomicCmpXchg: case Instruction::AtomicRMW: return true; default: return false; } } bool ShadowInstruction::hasOrderingConstraint() { switch(invar->I->getOpcode()) { case Instruction::Load: return !cast_inst<LoadInst>(this)->isUnordered(); case Instruction::Store: return !cast_inst<StoreInst>(this)->isUnordered(); case Instruction::AtomicRMW: return cast_inst<AtomicRMWInst>(this)->getOrdering() > Unordered; case Instruction::AtomicCmpXchg: { auto cmpx = cast_inst<AtomicCmpXchgInst>(this); return cmpx->getSuccessOrdering() > Unordered || cmpx->getFailureOrdering() > Unordered; } case Instruction::Fence: return true; default: break; } return false; }
[ "cs448@cam.ac.uk" ]
cs448@cam.ac.uk
c35c54ae8ffd5d2835b8a70165822dedb5a563f1
fa10b09a97fe199a1a4534a2e4b66eef85233bbc
/param/BracketPolicy.cpp
89c35ea671814effc4d17bf133d719769cd0107d
[]
no_license
dmorse/util
0f53cb0431afb707973f563f27d6e8d155816481
928110f754aae7e7ba494b8fe31abc0cac40b344
refs/heads/master
2022-12-13T10:00:09.113704
2022-12-11T17:37:04
2022-12-11T17:37:04
77,802,805
2
1
null
2022-08-09T18:24:27
2017-01-02T00:23:03
C++
UTF-8
C++
false
false
802
cpp
/* * Util Package - C++ Utilities for Scientific Computation * * Copyright 2010 - 2017, The Regents of the University of Minnesota * Distributed under the terms of the GNU General Public License. */ #include "BracketPolicy.h" namespace Util { // Anonymous namespace for private quasi-static variables namespace{ /// Policy regarding use of brackets. BracketPolicy::Type policy_ = BracketPolicy::Forbidden; } namespace BracketPolicy { /** * Set policy regarding use of bracket delimiters on arrays. */ void set(BracketPolicy::Type policy) { policy_ = policy; } /** * Get value of bracket policy. */ BracketPolicy::Type get() { return policy_; } } // namespace BracketPolicy } // namespace Util
[ "morse012@umn.edu" ]
morse012@umn.edu
accddebdf21968872866c90305fba10f8bf0532b
64e4fabf9b43b6b02b14b9df7e1751732b30ad38
/src/chromium/gen/gen_combined/media/mojo/interfaces/renderer.mojom.h
57cd784bb4023d5f0057a7f15303895c800cceff
[ "BSD-3-Clause" ]
permissive
ivan-kits/skia-opengl-emscripten
8a5ee0eab0214c84df3cd7eef37c8ba54acb045e
79573e1ee794061bdcfd88cacdb75243eff5f6f0
refs/heads/master
2023-02-03T16:39:20.556706
2020-12-25T14:00:49
2020-12-25T14:00:49
null
0
0
null
null
null
null
UTF-8
C++
false
false
10,196
h
// Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef MEDIA_MOJO_INTERFACES_RENDERER_MOJOM_H_ #define MEDIA_MOJO_INTERFACES_RENDERER_MOJOM_H_ #include <stdint.h> #include <limits> #include <type_traits> #include <utility> #include "base/callback.h" #include "base/macros.h" #include "base/optional.h" #include "mojo/public/cpp/bindings/mojo_buildflags.h" #if BUILDFLAG(MOJO_TRACE_ENABLED) #include "base/trace_event/trace_event.h" #endif #include "mojo/public/cpp/bindings/clone_traits.h" #include "mojo/public/cpp/bindings/equals_traits.h" #include "mojo/public/cpp/bindings/lib/serialization.h" #include "mojo/public/cpp/bindings/struct_ptr.h" #include "mojo/public/cpp/bindings/struct_traits.h" #include "mojo/public/cpp/bindings/union_traits.h" #include "media/mojo/interfaces/renderer.mojom-shared.h" #include "media/mojo/interfaces/renderer.mojom-forward.h" #include "media/mojo/interfaces/demuxer_stream.mojom-forward.h" #include "media/mojo/interfaces/media_types.mojom-forward.h" #include "mojo/public/mojom/base/time.mojom-forward.h" #include "mojo/public/mojom/base/unguessable_token.mojom-forward.h" #include "ui/gfx/geometry/mojo/geometry.mojom-forward.h" #include "url/mojom/url.mojom-forward.h" #include <string> #include <vector> #include "mojo/public/cpp/bindings/associated_interface_ptr.h" #include "mojo/public/cpp/bindings/associated_interface_ptr_info.h" #include "mojo/public/cpp/bindings/associated_interface_request.h" #include "mojo/public/cpp/bindings/interface_ptr.h" #include "mojo/public/cpp/bindings/interface_request.h" #include "mojo/public/cpp/bindings/lib/control_message_handler.h" #include "mojo/public/cpp/bindings/raw_ptr_impl_ref_traits.h" #include "mojo/public/cpp/bindings/thread_safe_interface_ptr.h" #include "mojo/public/cpp/bindings/lib/native_enum_serialization.h" #include "mojo/public/cpp/bindings/lib/native_struct_serialization.h" namespace media { namespace mojom { class RendererProxy; template <typename ImplRefTraits> class RendererStub; class RendererRequestValidator; class RendererResponseValidator; class Renderer : public RendererInterfaceBase { public: static const char Name_[]; static constexpr uint32_t Version_ = 0; static constexpr bool PassesAssociatedKinds_ = true; static constexpr bool HasSyncMethods_ = false; using Base_ = RendererInterfaceBase; using Proxy_ = RendererProxy; template <typename ImplRefTraits> using Stub_ = RendererStub<ImplRefTraits>; using RequestValidator_ = RendererRequestValidator; using ResponseValidator_ = RendererResponseValidator; enum MethodMinVersions : uint32_t { kInitializeMinVersion = 0, kFlushMinVersion = 0, kStartPlayingFromMinVersion = 0, kSetPlaybackRateMinVersion = 0, kSetVolumeMinVersion = 0, kSetCdmMinVersion = 0, }; virtual ~Renderer() {} using InitializeCallback = base::OnceCallback<void(bool)>; virtual void Initialize(RendererClientAssociatedPtrInfo client, base::Optional<std::vector<::media::mojom::DemuxerStreamPtrInfo>> streams, const base::Optional<GURL>& media_url, const base::Optional<GURL>& first_party_for_cookies, bool allow_credentials, InitializeCallback callback) = 0; using FlushCallback = base::OnceCallback<void()>; virtual void Flush(FlushCallback callback) = 0; virtual void StartPlayingFrom(base::TimeDelta time) = 0; virtual void SetPlaybackRate(double playback_rate) = 0; virtual void SetVolume(float volume) = 0; using SetCdmCallback = base::OnceCallback<void(bool)>; virtual void SetCdm(int32_t cdm_id, SetCdmCallback callback) = 0; }; class RendererClientProxy; template <typename ImplRefTraits> class RendererClientStub; class RendererClientRequestValidator; class RendererClient : public RendererClientInterfaceBase { public: static const char Name_[]; static constexpr uint32_t Version_ = 0; static constexpr bool PassesAssociatedKinds_ = false; static constexpr bool HasSyncMethods_ = false; using Base_ = RendererClientInterfaceBase; using Proxy_ = RendererClientProxy; template <typename ImplRefTraits> using Stub_ = RendererClientStub<ImplRefTraits>; using RequestValidator_ = RendererClientRequestValidator; using ResponseValidator_ = mojo::PassThroughFilter; enum MethodMinVersions : uint32_t { kOnTimeUpdateMinVersion = 0, kOnBufferingStateChangeMinVersion = 0, kOnEndedMinVersion = 0, kOnErrorMinVersion = 0, kOnAudioConfigChangeMinVersion = 0, kOnVideoConfigChangeMinVersion = 0, kOnVideoNaturalSizeChangeMinVersion = 0, kOnVideoOpacityChangeMinVersion = 0, kOnStatisticsUpdateMinVersion = 0, kOnWaitingMinVersion = 0, }; virtual ~RendererClient() {} virtual void OnTimeUpdate(base::TimeDelta time, base::TimeDelta max_time, base::TimeTicks capture_time) = 0; virtual void OnBufferingStateChange(media::BufferingState state) = 0; virtual void OnEnded() = 0; virtual void OnError() = 0; virtual void OnAudioConfigChange(const ::media::AudioDecoderConfig& config) = 0; virtual void OnVideoConfigChange(const media::VideoDecoderConfig& config) = 0; virtual void OnVideoNaturalSizeChange(const gfx::Size& size) = 0; virtual void OnVideoOpacityChange(bool opaque) = 0; virtual void OnStatisticsUpdate(const media::PipelineStatistics& stats) = 0; virtual void OnWaiting(media::WaitingReason reason) = 0; }; class RendererProxy : public Renderer { public: using InterfaceType = Renderer; explicit RendererProxy(mojo::MessageReceiverWithResponder* receiver); void Initialize(RendererClientAssociatedPtrInfo client, base::Optional<std::vector<::media::mojom::DemuxerStreamPtrInfo>> streams, const base::Optional<GURL>& media_url, const base::Optional<GURL>& first_party_for_cookies, bool allow_credentials, InitializeCallback callback) final; void Flush(FlushCallback callback) final; void StartPlayingFrom(base::TimeDelta time) final; void SetPlaybackRate(double playback_rate) final; void SetVolume(float volume) final; void SetCdm(int32_t cdm_id, SetCdmCallback callback) final; private: mojo::MessageReceiverWithResponder* receiver_; }; class RendererClientProxy : public RendererClient { public: using InterfaceType = RendererClient; explicit RendererClientProxy(mojo::MessageReceiverWithResponder* receiver); void OnTimeUpdate(base::TimeDelta time, base::TimeDelta max_time, base::TimeTicks capture_time) final; void OnBufferingStateChange(media::BufferingState state) final; void OnEnded() final; void OnError() final; void OnAudioConfigChange(const ::media::AudioDecoderConfig& config) final; void OnVideoConfigChange(const media::VideoDecoderConfig& config) final; void OnVideoNaturalSizeChange(const gfx::Size& size) final; void OnVideoOpacityChange(bool opaque) final; void OnStatisticsUpdate(const media::PipelineStatistics& stats) final; void OnWaiting(media::WaitingReason reason) final; private: mojo::MessageReceiverWithResponder* receiver_; }; class RendererStubDispatch { public: static bool Accept(Renderer* impl, mojo::Message* message); static bool AcceptWithResponder( Renderer* impl, mojo::Message* message, std::unique_ptr<mojo::MessageReceiverWithStatus> responder); }; template <typename ImplRefTraits = mojo::RawPtrImplRefTraits<Renderer>> class RendererStub : public mojo::MessageReceiverWithResponderStatus { public: using ImplPointerType = typename ImplRefTraits::PointerType; RendererStub() {} ~RendererStub() override {} void set_sink(ImplPointerType sink) { sink_ = std::move(sink); } ImplPointerType& sink() { return sink_; } bool Accept(mojo::Message* message) override { if (ImplRefTraits::IsNull(sink_)) return false; return RendererStubDispatch::Accept( ImplRefTraits::GetRawPointer(&sink_), message); } bool AcceptWithResponder( mojo::Message* message, std::unique_ptr<mojo::MessageReceiverWithStatus> responder) override { if (ImplRefTraits::IsNull(sink_)) return false; return RendererStubDispatch::AcceptWithResponder( ImplRefTraits::GetRawPointer(&sink_), message, std::move(responder)); } private: ImplPointerType sink_; }; class RendererClientStubDispatch { public: static bool Accept(RendererClient* impl, mojo::Message* message); static bool AcceptWithResponder( RendererClient* impl, mojo::Message* message, std::unique_ptr<mojo::MessageReceiverWithStatus> responder); }; template <typename ImplRefTraits = mojo::RawPtrImplRefTraits<RendererClient>> class RendererClientStub : public mojo::MessageReceiverWithResponderStatus { public: using ImplPointerType = typename ImplRefTraits::PointerType; RendererClientStub() {} ~RendererClientStub() override {} void set_sink(ImplPointerType sink) { sink_ = std::move(sink); } ImplPointerType& sink() { return sink_; } bool Accept(mojo::Message* message) override { if (ImplRefTraits::IsNull(sink_)) return false; return RendererClientStubDispatch::Accept( ImplRefTraits::GetRawPointer(&sink_), message); } bool AcceptWithResponder( mojo::Message* message, std::unique_ptr<mojo::MessageReceiverWithStatus> responder) override { if (ImplRefTraits::IsNull(sink_)) return false; return RendererClientStubDispatch::AcceptWithResponder( ImplRefTraits::GetRawPointer(&sink_), message, std::move(responder)); } private: ImplPointerType sink_; }; class RendererRequestValidator : public mojo::MessageReceiver { public: bool Accept(mojo::Message* message) override; }; class RendererClientRequestValidator : public mojo::MessageReceiver { public: bool Accept(mojo::Message* message) override; }; class RendererResponseValidator : public mojo::MessageReceiver { public: bool Accept(mojo::Message* message) override; }; } // namespace mojom } // namespace media namespace mojo { } // namespace mojo #endif // MEDIA_MOJO_INTERFACES_RENDERER_MOJOM_H_
[ "trofimov_d_a@magnit.ru" ]
trofimov_d_a@magnit.ru
c7e2b4e450a68ef60b02bcdda6179b263be4a1eb
c287f063100e0ddb29bcf27e9f901b914cca0f2e
/thirdparty/qt53/include/QtXmlPatterns/5.3.0/QtXmlPatterns/private/qabstractfloat_p.h
6621755a8bc70ffc660f4794dc93d615842b09db
[ "MIT" ]
permissive
imzcy/JavaScriptExecutable
803c55db0adce8b32fcbe0db81531d248a9420d0
723a13f433aafad84faa609f62955ce826063c66
refs/heads/master
2022-11-05T01:37:49.036607
2016-10-26T17:13:10
2016-10-26T17:13:10
20,448,619
3
1
MIT
2022-10-24T23:26:37
2014-06-03T15:37:09
C++
UTF-8
C++
false
false
5,850
h
/**************************************************************************** ** ** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of the QtXmlPatterns module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3.0 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU General Public License version 3.0 requirements will be ** met: http://www.gnu.org/copyleft/gpl.html. ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ // // W A R N I N G // ------------- // // This file is not part of the Qt API. It exists purely as an // implementation detail. This header file may change from version to // version without notice, or even be removed. // // We mean it. #ifndef Patternist_AbstractFloat_H #define Patternist_AbstractFloat_H #include <math.h> #include <qnumeric.h> #include <private/qcommonvalues_p.h> #include <private/qdecimal_p.h> #include <private/qschemanumeric_p.h> #include <private/qvalidationerror_p.h> #include <private/qbuiltintypes_p.h> QT_BEGIN_NAMESPACE namespace QPatternist { /** * @short Base template class for Float and Double classes. * * @author Vincent Ricard <magic@magicninja.org> * @ingroup Patternist_xdm */ template <const bool isDouble> class AbstractFloat : public Numeric { public: static Numeric::Ptr fromValue(const xsDouble num); static AtomicValue::Ptr fromLexical(const QString &strNumeric); /** * @todo more extensive docs. * * Performs floating point comparison. * * @returns @c true if @p a and @p are equal, otherwise @c false. */ static bool isEqual(const xsDouble a, const xsDouble b); /** * Determines the Effective %Boolean Value of this number. * * @returns @c false if the number is 0 or @c NaN, otherwise @c true. */ bool evaluateEBV(const QExplicitlySharedDataPointer<DynamicContext> &) const; /** * Returns this AbstractFloat represented as an @c xs:string. * * @note In the XPath/XQuery languages, converting @c xs:double and @c xs:float * to @c xs:string is not specified in XML Schema 1.0 Part 2: Datatypes Second Edition, * but in XQuery 1.0 and XPath 2.0 Functions and Operators. This will change with W3C XML * Schema 1.1 * * @see <a href="http://www.w3.org/TR/xpath-functions/#casting-to-string">XQuery 1.0 * and XPath 2.0 Functions and Operators, 17.1.2 Casting to xs:string and xdt:untypedAtomic</a> */ virtual QString stringValue() const; virtual xsDouble toDouble() const; virtual xsInteger toInteger() const; virtual xsFloat toFloat() const; virtual xsDecimal toDecimal() const; virtual Numeric::Ptr round() const; virtual Numeric::Ptr roundHalfToEven(const xsInteger scale) const; virtual Numeric::Ptr floor() const; virtual Numeric::Ptr ceiling() const; virtual Numeric::Ptr abs() const; virtual bool isNaN() const; virtual bool isInf() const; virtual ItemType::Ptr type() const; virtual Item toNegated() const; virtual qulonglong toUnsignedInteger() const; virtual bool isSigned() const; protected: AbstractFloat(const xsDouble num); private: /** * From the Open Group's man page: "The signbit() macro shall return a * non-zero value if and only if the sign of its argument value is * negative." * * MS Windows doesn't have std::signbit() so here's * a reinvention of that function. */ static inline int internalSignbit(const xsDouble v); inline bool isZero() const; const xsDouble m_value; }; template <const bool isDouble> Numeric::Ptr createFloat(const xsDouble num); #include "qabstractfloat_tpl_p.h" /** * @short An instantiation of AbsbstractFloat suitable for @c xs:double. * * @ingroup Patternist_xdm */ typedef AbstractFloat<true> Double; /** * @short An instantiation of AbstractFloat suitable for @c xs:float. * * @ingroup Patternist_xdm */ typedef AbstractFloat<false> Float; } QT_END_NAMESPACE #endif
[ "zcy920225@gmail.com" ]
zcy920225@gmail.com
d32bcdcf8ef62a35d329b47ecba5d48e1ae76cdd
1e0648928bda5de1cec58cc0a850faf4731f4ab7
/Chapter 3/Exercise 3.39.cpp
e41acde075e1da1d3891dab14136df8c256ccfda
[]
no_license
LabibAhmed0101/CPP_Primer-Ex
94a54ab441ce3ef5866306e1dae4fd04b2562e4d
537cd53cb1fb03e9a21fa6ca2cb6a9d613756970
refs/heads/master
2021-01-19T09:46:03.581594
2018-12-06T03:39:21
2018-12-06T03:39:21
87,779,970
0
0
null
2017-04-10T07:35:40
2017-04-10T07:27:02
null
UTF-8
C++
false
false
3,277
cpp
/*Exercise 3.39: Write a program to compare two strings. Now write a program to compare the values of two C-style character strings.*/ //a)Program to compare two strings (using string library). #include<iostream> #include<string> //Includeded to use string library. using std::cout; using std::cin; using std::endl; using std::string; //string can be used without std:: prefix. int main() { string str1, str2; //Declaring 2 strings. //User asked to enter two strings. cout << "Enter the 1st string" << endl; cin >> str1; cout << "Enter the 2nd string" << endl; cin >> str2; if (str1 == str2) //If two strings are equal. cout << "\nThe two string are equal" << endl; else if (str1 > str2) //If the 1st string bigger than the 2nd string. cout << "\nThe 1st string is bigger than the 2nd string" << endl; else //when the 1st string is smaller than the 2nd string. cout << "\nThe 1st string is smaller than the 2nd string" << endl; return 0; } //b)Program to compare two C-style character strings #include<iostream> #include<cstddef> //Included to enable using size_t #include<cstring> //Included to enable using cstring function strcmp() using std::cout; using std::cin; using std::endl; int main() { constexpr size_t MAX_SIZE = 100; //Max size of the cstring char arr1[MAX_SIZE], arr2[MAX_SIZE]; //Declaring two arrays of characters (cstring) cout << "Enter the 1st string" << endl; cin.getline(arr1, MAX_SIZE); cout << "Enter the 2nd string" << endl; cin.getline(arr2, MAX_SIZE); if (strcmp(arr1, arr2) == 0) //strcmp returns 0 if both cstring are equal cout << "\nThe 1st and the 2nd string are equal" << endl; else if (strcmp(arr1, arr2) < 0) //strcmp returns negative value if arr1 is smaller than arr2 cout << "\nThe 1st string is smaller than the 2nd string" << endl; else //strcmp returns positve value if arr1 is bigger than arr2 cout << "\nThe 1st string is bigger than the 2nd string" << endl; return 0; } /*cin.getline let the user input a full line in cstring as getline() do with string it is also much better to use than cin >> becuase with cin >> there will be over flow problem if the user input more than 99 char . cin.getline also makes it possiable to use a delimiter instead of the default delimiter which is '\n'. Delimiter is used to define where the cstring input stream ends by default if the user pressed enter while he inputs the string, that will end the stream of inputs for example : if the user is inputing address inside a cstring array it have to be like that: 20 London st. London United Kingdom Here the new line is a part of the string so we must use a delimiter so the stream of char won't take enter/return as the end of the stream. We can set a new delimiter instead of the default one through cin.getline(arr,MAXSIZE,'$') the 1st argument is the cstring variable "the array of characters", the 2nd argument is the cstring max size , the 3rd argument is the new delimiter so enter/return is not the current delimiter and it is now treated as any other character and the stream only will end when the user hits '$' user stream of iputs would be like that. 20 London st. London United Kingdom$ stream will end when the user type $. */
[ "noreply@github.com" ]
noreply@github.com
117a31245c0af9abe2875898d88670e78722d717
f33876f335f3bdc9d51b0f37930b4fe4a7827ee7
/Messages/Windows/MainWindowGrid.cpp
92b6969cf7df69ecd3b48a796fdf552c898a0b1b
[]
no_license
andreyV512/pump_rods
003f7e81d8d911fdcf2dba4e553a5c67b508df60
f22ee534429151ca79df945636e5c3b94ec6380b
refs/heads/master
2021-07-08T14:09:41.754902
2020-10-06T05:29:41
2020-10-06T05:29:41
188,955,859
0
0
null
null
null
null
WINDOWS-1251
C++
false
false
2,041
cpp
#include "stdafx.h" #include "MainWindowGrid.h" #include "tools_debug/DebugMess.h" #include "Log\LogBuffer.h" //------------------------------------------------------------------------ extern HINSTANCE hInstance; //------------------------------------------------------------------------ template<class T>struct header_table; #define Z(T, w, txt)\ struct T{};\ template<>struct header_table<T>\ {\ LPWSTR name(){return L##txt;}\ static const int width = w;\ }; Z(Group , 70, "Время") Z(Color, 500, "Сообщение") #undef Z typedef TL::MkTlst< Group, Color>::Result ParameterNameList; //-------------------------------------------------------------------------------- MainWindowGrid::MainWindowGrid() { } //-------------------------------------------------------------------------------- void MainWindowGrid::Init(HWND h) { hWnd = handlers.Init<TL::MkTlst<Group, Color>::Result>(h, 1024); } //-------------------------------------------------------------------- #pragma warning(disable : 4995) void MainWindowGrid::Handlers::operator()(TCellData &l) { #pragma warning(disable : 4996) Log::TData *d = NULL; if(Log::IsRow(l.row, d)) { switch(l.col) { case 0: { Log::TData *d0 = NULL; if(Log::IsRow(l.row + 1, d0)) { _itow(d->time - d0->time, l.data, 10); } else { l.data[0] = '0'; l.data[1] = '\0'; } } break; case 1: char buf[1024]; LogMess::FactoryMessages::Instance().Text(d->id, buf, d->value); int len = 1 + strlen(buf); MultiByteToWideChar(1251, 0, buf, len, l.data, len); break; } } } //-------------------------------------------------------------------- void MainWindowGrid::Handlers::operator()(TCellColor &l) { Log::TData *d = NULL; if(Log::IsRow(l.row, d)) { LogMess::FactoryMessages::Instance().Color(d->id, (unsigned &)l.bkColor, (unsigned &)l.textColor); } } //---------------------------------------------------------------------------
[ "jdoe@email.com" ]
jdoe@email.com
5d9993519ed96bf1b7b5861cca9712acf8bc7092
5711e2f3519b7076ed204ec56baf0413b24819ba
/Project 2/ComplexNumber.cpp
5b264b1faa1cec31dcdeac429a4827122c90c74d
[]
no_license
BiermanM/Computer-Science-II-Projects
16b6955ecef9a99d798d3ebe2e2a1193ab04d5bb
72902c9091a3b61aebaf8a4cba2b9236d24add7c
refs/heads/master
2021-09-01T00:17:00.030820
2017-12-23T18:57:57
2017-12-23T18:57:57
76,517,297
1
2
null
null
null
null
UTF-8
C++
false
false
12,863
cpp
/* Assignment: Project #2 Author: Matthew Bierman NetID: mbb160030 Course: CS 2336.004 (Computer Science II) Instructor: Mr. Jason Smith Date Due: October 3, 2016 at 11:59pm */ #include "ComplexNumber.h" #include <cmath> #include <iostream> #include <fstream> #include <string> #include <stdlib.h> using namespace std; // default constructor ComplexNumber::ComplexNumber() { realNumberComponent = 0; imaginaryNumberComponent = 0; } // overloaded constructor ComplexNumber::ComplexNumber(double rnc, double inc) { realNumberComponent = rnc; imaginaryNumberComponent = inc; } // copy constructor ComplexNumber::ComplexNumber(ComplexNumber& num) { realNumberComponent = num.realNumberComponent; imaginaryNumberComponent = num.imaginaryNumberComponent; } // real number component accessor // Parameters: none // Return: real number component double ComplexNumber::getRealNumberComponent() const { return realNumberComponent; } // imaginary number component accessor // Parameters: none // Return: imaginary number component double ComplexNumber::getImaginaryNumberComponent() const { return imaginaryNumberComponent; } // real number component mutator // Parameters: real number component // Return: none void ComplexNumber::setRealNumberComponent(double rnc) { realNumberComponent = rnc; } // imaginary number component mutator // Parameters: imaginary number component // Return: none void ComplexNumber::setImaginaryNumberComponent(double inc) { imaginaryNumberComponent = inc; } // overloaded addition operator // Parameters: complex number object // Return: new complex number ComplexNumber ComplexNumber::operator+(const ComplexNumber& num) const { ComplexNumber sum; sum.realNumberComponent = realNumberComponent + num.realNumberComponent; // real = real1 + real2 sum.imaginaryNumberComponent = imaginaryNumberComponent + num.imaginaryNumberComponent; // imaginary = imaginary1 + imaginary2 return sum; } // overloaded subtraction operator // Parameters: complex number object // Return: new complex number ComplexNumber ComplexNumber::operator-(const ComplexNumber& num) const { ComplexNumber difference; difference.realNumberComponent = realNumberComponent - num.realNumberComponent; // real = real1 - real2 difference.imaginaryNumberComponent = imaginaryNumberComponent - num.imaginaryNumberComponent; // imaginary = imaginary1 - imaginary2 return difference; } // overloaded multiplication operator // Parameters: complex number object // Return: new complex number ComplexNumber ComplexNumber::operator*(const ComplexNumber& num) const { ComplexNumber product; product.realNumberComponent = realNumberComponent * num.realNumberComponent; product.imaginaryNumberComponent = realNumberComponent * num.imaginaryNumberComponent; product.imaginaryNumberComponent += imaginaryNumberComponent * num.realNumberComponent; // imaginary = (real1 * imaginary2) + (imaginary1 * real2) product.realNumberComponent -= imaginaryNumberComponent * num.imaginaryNumberComponent; // real = (real1 * real2) - (imaginary1 * imaginary2) return product; } // overloaded division operator // Parameters: complex number object // Return: new complex number ComplexNumber ComplexNumber::operator/(const ComplexNumber& num) const { ComplexNumber quotient; double denominator; denominator = (num.realNumberComponent * num.realNumberComponent) + (num.imaginaryNumberComponent * num.imaginaryNumberComponent); quotient.realNumberComponent = realNumberComponent * num.realNumberComponent; quotient.imaginaryNumberComponent = realNumberComponent * num.imaginaryNumberComponent * -1; quotient.imaginaryNumberComponent += imaginaryNumberComponent * num.realNumberComponent; quotient.realNumberComponent += imaginaryNumberComponent * num.imaginaryNumberComponent; quotient.realNumberComponent /= denominator; // real = ((real1 * real2) + (imarginary1 * imaginary2)) / (real2^2 * imaginary2^2) quotient.imaginaryNumberComponent /= denominator; // imaginary = ((imaginary1 * real2) - (real1 * imaginary2)) / (real2^2 * imaginary2^2) return quotient; } // overloaded less than comparator // Parameters: complex number object // Return: boolean bool ComplexNumber::operator<(const ComplexNumber& num) const { if (sqrt(pow(realNumberComponent, 2) + pow(imaginaryNumberComponent, 2)) < sqrt(pow(num.realNumberComponent, 2) + pow(num.imaginaryNumberComponent, 2))) // sqrt(real1^2 + imaginary1^2) < sqrt(real2^2 + imaginary2^2) return true; else return false; } // overloaded greater than comparator // Parameters: complex number object // Return: boolean bool ComplexNumber::operator>(const ComplexNumber& num) const { if (sqrt(pow(realNumberComponent, 2) + pow(imaginaryNumberComponent, 2)) > sqrt(pow(num.realNumberComponent, 2) + pow(num.imaginaryNumberComponent, 2))) // sqrt(real1^2 + imaginary1^2) > sqrt(real2^2 + imaginary2^2) return true; else return false; } // overloaded equal to comparator // Parameters: complex number object // Return: boolean bool ComplexNumber::operator==(const ComplexNumber& num) const { if (realNumberComponent == num.realNumberComponent && imaginaryNumberComponent == num.imaginaryNumberComponent) // real1 = real2 and imaginary1 = imaginary2 return true; else return false; } // overloaded not equal to comparator // Parameters: complex number object // Return: boolean bool ComplexNumber::operator!=(const ComplexNumber& num) const { if (realNumberComponent == num.realNumberComponent && imaginaryNumberComponent == num.imaginaryNumberComponent) // real1 != real2 or imaginary1 != imaginary2 return false; else return true; } // overloaded stream insertion operator // Parameters: stream insertion, complex number object // Return: stream insertion ostream& operator<<(ostream& cout, const ComplexNumber& num) { cout << setprecision(2) << fixed; // sets all floating point values to 2 decimal places if (num.getRealNumberComponent() == 0) { if (num.getImaginaryNumberComponent() == 0) cout << "0"; // 0 else { if (num.getImaginaryNumberComponent() == 1) cout << "i"; // i else if (num.getImaginaryNumberComponent() == -1) cout << "-i"; // -i else { // bi or -bi if (num.getImaginaryNumberComponent() == floor(num.getImaginaryNumberComponent())) cout << (int) num.getImaginaryNumberComponent() << "i"; // if b is a whole number, don't display .00 else cout << num.getImaginaryNumberComponent() << "i"; } } } else { // a or -a if (num.getRealNumberComponent() == floor(num.getRealNumberComponent())) cout << (int) num.getRealNumberComponent(); // if a is a whole number, don't display .00 else cout << num.getRealNumberComponent(); if (num.getImaginaryNumberComponent() > 0) cout << "+"; if (num.getImaginaryNumberComponent() == -1) cout << "-i"; // a-i or -a-i else if (num.getImaginaryNumberComponent() == 1) cout << "i"; // a+i or -a+i else if (num.getImaginaryNumberComponent() != 0) { // a+bi or -a+bi if (num.getImaginaryNumberComponent() == floor(num.getImaginaryNumberComponent())) cout << (int) num.getImaginaryNumberComponent() << "i"; // if b is a whole number, don't display .00 else cout << num.getImaginaryNumberComponent() << "i"; } } return cout; } // overloaded stream extraction operator // Parameters: stream extraction, complex number object // Return: stream extraction istream& operator>>(istream& cin, ComplexNumber& num) { string str; cin >> str; if (str.find('i') > str.length()) // if only a real number { num.setRealNumberComponent(atof(str.c_str())); // real number component: a or -a num.setImaginaryNumberComponent(0); // imaginary number component: 0 } else if (str.find('+', 1) < str.length() || str.find('-', 1) < str.length()) // if only a mixed number { int indexOfPlusMinus; if (str.find('+', 1) < str.length()) { indexOfPlusMinus = str.find('+', 1); num.setImaginaryNumberComponent(atof(str.substr(indexOfPlusMinus + 1).c_str())); // imaginary number component: b } else { indexOfPlusMinus = str.find('-', 1); num.setImaginaryNumberComponent(atof(str.substr(indexOfPlusMinus).c_str())); // imaginary number component: -b } num.setRealNumberComponent(atof(str.substr(0, indexOfPlusMinus).c_str())); // real number component: a } else // if only an imaginary number { num.setImaginaryNumberComponent(atof(str.substr(0, str.find('i')).c_str())); // imaginary number component: b or -b num.setRealNumberComponent(0); // real number component: 0 } return cin; }
[ "noreply@github.com" ]
noreply@github.com
6590a0d8a1e381e7e7a6e7c5caebe65f4c72c173
263a50fb4ca9be07a5b229ac80047f068721f459
/chrome/browser/ui/views/find_bar_host_interactive_uitest.cc
5cf31f080350511de3162f1da0c351879306aaf4
[ "BSD-3-Clause" ]
permissive
talalbutt/clank
8150b328294d0ac7406fa86e2d7f0b960098dc91
d060a5fcce180009d2eb9257a809cfcb3515f997
refs/heads/master
2021-01-18T01:54:24.585184
2012-10-17T15:00:42
2012-10-17T15:00:42
null
0
0
null
null
null
null
UTF-8
C++
false
false
13,286
cc
// Copyright (c) 2011 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 "base/process_util.h" #include "base/string_util.h" #include "base/utf_string_conversions.h" #include "chrome/browser/tabs/tab_strip_model.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/find_bar/find_bar_controller.h" #include "chrome/browser/ui/find_bar/find_notification_details.h" #include "chrome/browser/ui/view_ids.h" #include "chrome/browser/ui/views/find_bar_host.h" #include "chrome/browser/ui/views/frame/browser_view.h" #include "chrome/common/chrome_notification_types.h" #include "chrome/test/base/in_process_browser_test.h" #include "chrome/test/base/ui_test_utils.h" #include "content/public/browser/notification_service.h" #include "content/public/browser/web_contents.h" #include "net/test/test_server.h" #include "ui/base/clipboard/clipboard.h" #include "ui/base/keycodes/keyboard_codes.h" #include "ui/views/focus/focus_manager.h" #include "ui/views/view.h" #include "ui/views/views_delegate.h" using content::WebContents; namespace { // The delay waited after sending an OS simulated event. static const int kActionDelayMs = 500; static const char kSimplePage[] = "files/find_in_page/simple.html"; void Checkpoint(const char* message, const base::TimeTicks& start_time) { LOG(INFO) << message << " : " << (base::TimeTicks::Now() - start_time).InMilliseconds() << " ms" << std::flush; } class FindInPageTest : public InProcessBrowserTest { public: FindInPageTest() : #if defined(USE_AURA) location_bar_focus_view_id_(VIEW_ID_OMNIBOX) #else location_bar_focus_view_id_(VIEW_ID_LOCATION_BAR) #endif { set_show_window(true); FindBarHost::disable_animations_during_testing_ = true; } string16 GetFindBarText() { FindBarTesting* find_bar = browser()->GetFindBarController()->find_bar()->GetFindBarTesting(); return find_bar->GetFindText(); } string16 GetFindBarSelectedText() { FindBarTesting* find_bar = browser()->GetFindBarController()->find_bar()->GetFindBarTesting(); return find_bar->GetFindSelectedText(); } ViewID location_bar_focus_view_id_; private: DISALLOW_COPY_AND_ASSIGN(FindInPageTest); }; } // namespace // Flaky, see crbug.com/109906. #if defined(TOOLKIT_USES_GTK) || defined(USE_AURA) #define MAYBE_CrashEscHandlers FLAKY_CrashEscHandlers #else #define MAYBE_CrashEscHandlers CrashEscHandlers #endif IN_PROC_BROWSER_TEST_F(FindInPageTest, MAYBE_CrashEscHandlers) { ASSERT_TRUE(test_server()->Start()); // First we navigate to our test page (tab A). GURL url = test_server()->GetURL(kSimplePage); ui_test_utils::NavigateToURL(browser(), url); browser()->Find(); // Open another tab (tab B). browser()->AddSelectedTabWithURL(url, content::PAGE_TRANSITION_TYPED); browser()->Find(); EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(), VIEW_ID_FIND_IN_PAGE_TEXT_FIELD)); // Select tab A. browser()->ActivateTabAt(0, true); // Close tab B. browser()->CloseTabContents(browser()->GetWebContentsAt(1)); // Click on the location bar so that Find box loses focus. ASSERT_NO_FATAL_FAILURE(ui_test_utils::ClickOnView(browser(), VIEW_ID_LOCATION_BAR)); // Check the location bar is focused. EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(), location_bar_focus_view_id_)); // This used to crash until bug 1303709 was fixed. ASSERT_TRUE(ui_test_utils::SendKeyPressSync( browser(), ui::VKEY_ESCAPE, false, false, false, false)); } IN_PROC_BROWSER_TEST_F(FindInPageTest, FocusRestore) { ASSERT_TRUE(test_server()->Start()); GURL url = test_server()->GetURL("title1.html"); ui_test_utils::NavigateToURL(browser(), url); // Focus the location bar, open and close the find-in-page, focus should // return to the location bar. browser()->FocusLocationBar(); EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(), location_bar_focus_view_id_)); // Ensure the creation of the find bar controller. browser()->GetFindBarController()->Show(); EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(), VIEW_ID_FIND_IN_PAGE_TEXT_FIELD)); browser()->GetFindBarController()->EndFindSession( FindBarController::kKeepSelection); EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(), location_bar_focus_view_id_)); // Focus the location bar, find something on the page, close the find box, // focus should go to the page. browser()->FocusLocationBar(); browser()->Find(); EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(), VIEW_ID_FIND_IN_PAGE_TEXT_FIELD)); ui_test_utils::FindInPage(browser()->GetSelectedTabContentsWrapper(), ASCIIToUTF16("a"), true, false, NULL); browser()->GetFindBarController()->EndFindSession( FindBarController::kKeepSelection); EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(), VIEW_ID_TAB_CONTAINER_FOCUS_VIEW)); // Focus the location bar, open and close the find box, focus should return to // the location bar (same as before, just checking that http://crbug.com/23599 // is fixed). browser()->FocusLocationBar(); EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(), location_bar_focus_view_id_)); browser()->GetFindBarController()->Show(); EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(), VIEW_ID_FIND_IN_PAGE_TEXT_FIELD)); browser()->GetFindBarController()->EndFindSession( FindBarController::kKeepSelection); EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(), location_bar_focus_view_id_)); } IN_PROC_BROWSER_TEST_F(FindInPageTest, FocusRestoreOnTabSwitch) { ASSERT_TRUE(test_server()->Start()); // First we navigate to our test page (tab A). GURL url = test_server()->GetURL(kSimplePage); ui_test_utils::NavigateToURL(browser(), url); browser()->Find(); EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(), VIEW_ID_FIND_IN_PAGE_TEXT_FIELD)); FindBarTesting* find_bar = browser()->GetFindBarController()->find_bar()->GetFindBarTesting(); // Search for 'a'. ui_test_utils::FindInPage(browser()->GetSelectedTabContentsWrapper(), ASCIIToUTF16("a"), true, false, NULL); EXPECT_TRUE(ASCIIToUTF16("a") == find_bar->GetFindSelectedText()); // Open another tab (tab B). ui_test_utils::WindowedNotificationObserver observer( content::NOTIFICATION_LOAD_STOP, content::NotificationService::AllSources()); browser()->AddSelectedTabWithURL(url, content::PAGE_TRANSITION_TYPED); observer.Wait(); // Make sure Find box is open. browser()->Find(); EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(), VIEW_ID_FIND_IN_PAGE_TEXT_FIELD)); // Search for 'b'. ui_test_utils::FindInPage(browser()->GetSelectedTabContentsWrapper(), ASCIIToUTF16("b"), true, false, NULL); EXPECT_TRUE(ASCIIToUTF16("b") == find_bar->GetFindSelectedText()); // Set focus away from the Find bar (to the Location bar). browser()->FocusLocationBar(); EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(), location_bar_focus_view_id_)); // Select tab A. Find bar should get focus. browser()->ActivateTabAt(0, true); EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(), VIEW_ID_FIND_IN_PAGE_TEXT_FIELD)); EXPECT_TRUE(ASCIIToUTF16("a") == find_bar->GetFindSelectedText()); // Select tab B. Location bar should get focus. browser()->ActivateTabAt(1, true); EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(), location_bar_focus_view_id_)); } // This tests that whenever you clear values from the Find box and close it that // it respects that and doesn't show you the last search, as reported in bug: // http://crbug.com/40121. IN_PROC_BROWSER_TEST_F(FindInPageTest, PrepopulateRespectBlank) { #if defined(OS_MACOSX) // FindInPage on Mac doesn't use prepopulated values. Search there is global. return; #endif base::TimeTicks start_time = base::TimeTicks::Now(); Checkpoint("Test starting", start_time); ASSERT_TRUE(test_server()->Start()); // Make sure Chrome is in the foreground, otherwise sending input // won't do anything and the test will hang. ASSERT_TRUE(ui_test_utils::BringBrowserWindowToFront(browser())); Checkpoint("Navigate", start_time); // First we navigate to any page. GURL url = test_server()->GetURL(kSimplePage); ui_test_utils::NavigateToURL(browser(), url); Checkpoint("Show Find bar", start_time); // Show the Find bar. browser()->GetFindBarController()->Show(); Checkpoint("Search for 'a'", start_time); // Search for "a". ASSERT_TRUE(ui_test_utils::SendKeyPressSync( browser(), ui::VKEY_A, false, false, false, false)); // We should find "a" here. EXPECT_EQ(ASCIIToUTF16("a"), GetFindBarText()); Checkpoint("Delete 'a'", start_time); // Delete "a". ASSERT_TRUE(ui_test_utils::SendKeyPressSync( browser(), ui::VKEY_BACK, false, false, false, false)); // Validate we have cleared the text. EXPECT_EQ(string16(), GetFindBarText()); Checkpoint("Close find bar", start_time); // Close the Find box. ASSERT_TRUE(ui_test_utils::SendKeyPressSync( browser(), ui::VKEY_ESCAPE, false, false, false, false)); Checkpoint("Show Find bar", start_time); // Show the Find bar. browser()->GetFindBarController()->Show(); Checkpoint("Validate text", start_time); // After the Find box has been reopened, it should not have been prepopulated // with "a" again. EXPECT_EQ(string16(), GetFindBarText()); Checkpoint("Close Find bar", start_time); // Close the Find box. ASSERT_TRUE(ui_test_utils::SendKeyPressSync( browser(), ui::VKEY_ESCAPE, false, false, false, false)); Checkpoint("FindNext", start_time); // Press F3 to trigger FindNext. ASSERT_TRUE(ui_test_utils::SendKeyPressSync( browser(), ui::VKEY_F3, false, false, false, false)); Checkpoint("Validate", start_time); // After the Find box has been reopened, it should still have no prepopulate // value. EXPECT_EQ(string16(), GetFindBarText()); Checkpoint("Test done", start_time); } // Flaky on Win. http://crbug.com/92467 #if defined(OS_WIN) #define MAYBE_PasteWithoutTextChange FLAKY_PasteWithoutTextChange #else #define MAYBE_PasteWithoutTextChange PasteWithoutTextChange #endif IN_PROC_BROWSER_TEST_F(FindInPageTest, MAYBE_PasteWithoutTextChange) { ASSERT_TRUE(test_server()->Start()); // Make sure Chrome is in the foreground, otherwise sending input // won't do anything and the test will hang. ASSERT_TRUE(ui_test_utils::BringBrowserWindowToFront(browser())); // First we navigate to any page. GURL url = test_server()->GetURL(kSimplePage); ui_test_utils::NavigateToURL(browser(), url); // Show the Find bar. browser()->GetFindBarController()->Show(); EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(), VIEW_ID_FIND_IN_PAGE_TEXT_FIELD)); // Search for "a". ASSERT_TRUE(ui_test_utils::SendKeyPressSync( browser(), ui::VKEY_A, false, false, false, false)); // We should find "a" here. EXPECT_EQ(ASCIIToUTF16("a"), GetFindBarText()); // Reload the page to clear the matching result. browser()->Reload(CURRENT_TAB); // Focus the Find bar again to make sure the text is selected. browser()->GetFindBarController()->Show(); EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(), VIEW_ID_FIND_IN_PAGE_TEXT_FIELD)); // "a" should be selected. EXPECT_EQ(ASCIIToUTF16("a"), GetFindBarSelectedText()); // Press Ctrl-C to copy the content. ASSERT_TRUE(ui_test_utils::SendKeyPressSync( browser(), ui::VKEY_C, true, false, false, false)); string16 str; views::ViewsDelegate::views_delegate->GetClipboard()-> ReadText(ui::Clipboard::BUFFER_STANDARD, &str); // Make sure the text is copied successfully. EXPECT_EQ(ASCIIToUTF16("a"), str); // Press Ctrl-V to paste the content back, it should start finding even if the // content is not changed. content::Source<WebContents> notification_source( browser()->GetSelectedWebContents()); ui_test_utils::WindowedNotificationObserverWithDetails <FindNotificationDetails> observer( chrome::NOTIFICATION_FIND_RESULT_AVAILABLE, notification_source); ASSERT_TRUE(ui_test_utils::SendKeyPressSync( browser(), ui::VKEY_V, true, false, false, false)); ASSERT_NO_FATAL_FAILURE(observer.Wait()); FindNotificationDetails details; ASSERT_TRUE(observer.GetDetailsFor(notification_source.map_key(), &details)); EXPECT_TRUE(details.number_of_matches() > 0); }
[ "plind@mips.com" ]
plind@mips.com
b3835bd4ddcdb25502c39e4bae7d9e8e0d68418c
877fff5bb313ccd23d1d01bf23b1e1f2b13bb85a
/app/src/main/cpp/dir7941/dir7942/dir8062/dir8063/dir12766/dir12767/dir13029/dir15097/dir15260/dir18144/dir18298/file18322.cpp
48c339d0b3063e05708a9f49bfe69e9ffafcd36f
[]
no_license
tgeng/HugeProject
829c3bdfb7cbaf57727c41263212d4a67e3eb93d
4488d3b765e8827636ce5e878baacdf388710ef2
refs/heads/master
2022-08-21T16:58:54.161627
2020-05-28T01:54:03
2020-05-28T01:54:03
267,468,475
0
0
null
null
null
null
UTF-8
C++
false
false
115
cpp
#ifndef file18322 #error "macro file18322 must be defined" #endif static const char* file18322String = "file18322";
[ "tgeng@google.com" ]
tgeng@google.com
b88a111c150449d41814911324fde19ee0ebf5b9
cae9161d77926313e0062333dd1e76784b112765
/classes/info_bar.cpp
e931f09b85fd1e28fa1f45fa3bcb34fea82578de
[]
no_license
yury-dymov/legacy_l2tradebot
9cbd0f94da8fc3ed7239715c5b349e0ee6689277
914671cdd31a884020a531ec86915d4a09de7523
refs/heads/master
2021-01-10T01:11:08.096960
2016-08-12T17:23:11
2016-08-12T17:23:11
55,140,565
0
0
null
null
null
null
UTF-8
C++
false
false
2,450
cpp
#include "info_bar.h" InfoBar::InfoBar () { this->setHeaderLabel ("Objects"); this->setMinimumWidth (240); QStringList list; this->addTopLevelItem (new QTreeWidgetItem (QStringList ("NPC"))); this->addTopLevelItem (new QTreeWidgetItem (QStringList ("Players"))); this->addTopLevelItem (new QTreeWidgetItem (QStringList ("Sell"))); this->addTopLevelItem (new QTreeWidgetItem (QStringList ("Buy"))); this->addTopLevelItem (new QTreeWidgetItem (QStringList ("Craft"))); connect (this, SIGNAL (currentItemChanged (QTreeWidgetItem *, QTreeWidgetItem *)), SLOT (slotCurrentItemChanged (QTreeWidgetItem *, QTreeWidgetItem *))); connect (this, SIGNAL (itemActivated (QTreeWidgetItem *, int)), SLOT (slotItemActivated (QTreeWidgetItem*, int))); } InfoBar::~InfoBar () { } void InfoBar::slotAddItem (const int objectId, const int stereotype, const string & str) { QTreeWidgetItem * child = new QTreeWidgetItem (QStringList (str.c_str ())); this->topLevelItem (stereotype)->addChild (child); objectId_ [child] = objectId; for (unsigned int i = 0; i < data_ [objectId].size (); ++i) { if (data_ [objectId][i].stereotype == stereotype) { data_ [objectId][i].item = child; update (); return; } } Object_s elem; elem.item = child; elem.stereotype = stereotype; data_[objectId].push_back (elem); update (); } void InfoBar::slotDeleteItem (const int objectId, const int stereotype) { vector <Object_s> data = data_ [objectId]; for (unsigned int i = 0; i < data.size (); ++i) { if (data[i].stereotype == stereotype) { QTreeWidgetItem * child = data[i].item; this->topLevelItem (data[i].stereotype)->removeChild (child); update (); break; } } } void InfoBar::slotItemActivated (QTreeWidgetItem * item, int) { if (this->indexOfTopLevelItem (item) == -1) { emit signalInfoBarSelected (objectId_ [item], 2); } } void InfoBar::slotCurrentItemChanged (QTreeWidgetItem * now, QTreeWidgetItem *) { if (this->indexOfTopLevelItem (now) == -1) { emit signalInfoBarSelected (objectId_ [now], 1); } } void InfoBar::slotEnterWorld (bool) { this->clear (); this->addTopLevelItem (new QTreeWidgetItem (QStringList ("NPC"))); this->addTopLevelItem (new QTreeWidgetItem (QStringList ("Players"))); this->addTopLevelItem (new QTreeWidgetItem (QStringList ("Sell"))); this->addTopLevelItem (new QTreeWidgetItem (QStringList ("Buy"))); this->addTopLevelItem (new QTreeWidgetItem (QStringList ("Craft"))); }
[ "yury@dymov.me" ]
yury@dymov.me
97f4de1a7e8fe05410a82e9bc261c94acfe12fb1
72dae4abb89cbf1c8d2d4aef5e677dbd3d74cd6f
/android-11/external/libcxx/test/std/language.support/support.limits/support.limits.general/algorithm.version.pass.cpp
24d2f8002d6cd0e043ac481656c6b8ad833b6cbd
[ "NCSA", "MIT", "Apache-2.0" ]
permissive
MrIkso/sdk-tools
aebb05a86e379d2883bae31f4620bcd73d832305
53b34cdaca0b94364446f01b5ac3455773db3029
refs/heads/master
2023-07-28T21:18:28.712877
2021-09-27T06:00:17
2021-09-27T06:00:17
309,805,035
7
3
Apache-2.0
2021-09-27T06:00:18
2020-11-03T20:56:00
C++
UTF-8
C++
false
false
1,062
cpp
//===----------------------------------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is dual licensed under the MIT and the University of Illinois Open // Source Licenses. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // <algorithm> feature macros /* Constant Value __cpp_lib_clamp 201603L __cpp_lib_constexpr_swap_algorithms 201806L __cpp_lib_parallel_algorithm 201603L __cpp_lib_robust_nonmodifying_seq_ops 201304L __cpp_lib_sample 201603L */ #include <algorithm> #include <cassert> #include "test_macros.h" int main() { // ensure that the macros that are supposed to be defined in <algorithm> are defined. /* #if !defined(__cpp_lib_fooby) # error "__cpp_lib_fooby is not defined" #elif __cpp_lib_fooby < 201606L # error "__cpp_lib_fooby has an invalid value" #endif */ }
[ "solod9362@gmail.com" ]
solod9362@gmail.com
eea8002478eaaccf2378424bca4bfc39d45fc323
3ff145e1a00c9d4a926c634aec3357885e7dc0f5
/include/networkit/algebraic/CSRGeneralMatrix.hpp
a328eefe6cb625c82c027f0709f20a1799032045
[ "MIT" ]
permissive
Dipsingh/networkit
f9c569b30e8fa40ce677eac8d5a71add53998457
e2ebbff66d3fc83384e9e765b767ab320202220f
refs/heads/master
2023-06-25T13:53:11.048548
2021-07-17T08:33:25
2021-07-17T08:33:25
null
0
0
null
null
null
null
UTF-8
C++
false
false
43,580
hpp
/* * CSRGeneralMatrix.hpp * * Created on: May 6, 2015 * Authors: Michael Wegner <michael.wegner@student.kit.edu> * Eugenio Angriman <angrimae@hu-berlin.de> */ // networkit-format #ifndef NETWORKIT_ALGEBRAIC_CSR_GENERAL_MATRIX_HPP_ #define NETWORKIT_ALGEBRAIC_CSR_GENERAL_MATRIX_HPP_ #include <algorithm> #include <cassert> #include <cmath> #include <numeric> #include <omp.h> #include <stdexcept> #include <vector> #include <networkit/Globals.hpp> #include <networkit/algebraic/AlgebraicGlobals.hpp> #include <networkit/algebraic/Vector.hpp> #include <networkit/graph/Graph.hpp> #include <tlx/unused.hpp> namespace NetworKit { /** * @ingroup algebraic * The CSRGeneralMatrix class represents a sparse matrix stored in CSR-Format * (i.e. compressed sparse row). * If speed is important, use this CSRGeneralMatrix instead of the Matrix class. */ template <class ValueType> class CSRGeneralMatrix { std::vector<index> rowIdx, columnIdx; std::vector<ValueType> nonZeros; count nRows, nCols; bool isSorted; ValueType zero; /** * Quicksort algorithm on columnIdx between [@a left, @a right]. * @param left * @param right */ void quicksort(index left, index right) { if (left >= right) return; index pivotIdx = partition(left, right); if (pivotIdx != 0) { quicksort(left, pivotIdx - 1); } quicksort(pivotIdx + 1, right); } /** * Partitions columnIdx between [@a left, @a right] after selecting the pivot * in the middle. * @param left * @param right * @return The pivot. */ index partition(index left, index right) { index mid = (left + right) / 2; index pivot = columnIdx[mid]; std::swap(columnIdx[mid], columnIdx[right]); std::swap(nonZeros[mid], nonZeros[right]); index i = left; for (index j = left; j < right; ++j) { if (columnIdx[j] <= pivot) { std::swap(columnIdx[i], columnIdx[j]); std::swap(nonZeros[i], nonZeros[j]); ++i; } } std::swap(columnIdx[i], columnIdx[right]); std::swap(nonZeros[i], nonZeros[right]); return i; } /** * Binary search the sorted columnIdx vector between [@a left, @a right] * for column @a j. * If @a j is not present, the index that is immediately left of the place * where @a j would be is returned. * @param left * @param right * @param j * @return The position of column @a j in columnIdx or the element immediately * to the left of the place where @a j would be. */ index binarySearchColumns(index left, index right, index j) const { assert(sorted()); const auto it = std::lower_bound(columnIdx.begin() + left, columnIdx.begin() + right, j); if (it == columnIdx.end() || *it != j) return none; return it - columnIdx.begin(); } public: /** Default constructor */ CSRGeneralMatrix() : rowIdx(0), columnIdx(0), nonZeros(0), nRows(0), nCols(0), isSorted(true), zero(0) {} /** * Constructs the CSRGeneralMatrix with size @a dimension x @a dimension. * @param dimension Defines how many rows and columns this matrix has. * @param zero The zero element (default = 0). */ CSRGeneralMatrix(count dimension, ValueType zero = 0) : rowIdx(dimension + 1), columnIdx(0), nonZeros(0), nRows(dimension), nCols(dimension), isSorted(true), zero(zero) {} /** * Constructs the CSRGeneralMatrix with size @a nRows x @a nCols. * @param nRows Number of rows. * @param nCols Number of columns. * @param zero The zero element (default = 0). */ CSRGeneralMatrix(count nRows, count nCols, ValueType zero = 0) : rowIdx(nRows + 1), columnIdx(0), nonZeros(0), nRows(nRows), nCols(nCols), isSorted(true), zero(zero) {} /** * Constructs the @a dimension x @a dimension Matrix from the elements at * position @a positions with values @values. * @param dimension Defines how many rows and columns this matrix has. * @param triplets The nonzero elements. * @param zero The zero element (default is 0). * @param isSorted True, if the triplets are sorted per row. Default is false. */ CSRGeneralMatrix(count dimension, const std::vector<Triplet> &triplets, ValueType zero = 0, bool isSorted = false) : CSRGeneralMatrix(dimension, dimension, triplets, zero, isSorted) {} /** * Constructs the @a nRows x @a nCols Matrix from the elements at position @a * positions with values @values. * @param nRows Defines how many rows this matrix has. * @param nCols Defines how many columns this matrix has. * @param triplets The nonzero elements. * @param zero The zero element (default is 0). * @param isSorted True, if the triplets are sorted per row. Default is false. */ CSRGeneralMatrix(count nRows, count nCols, const std::vector<Triplet> &triplets, ValueType zero = 0, bool isSorted = false) : rowIdx(nRows + 1), columnIdx(triplets.size()), nonZeros(triplets.size()), nRows(nRows), nCols(nCols), isSorted(isSorted), zero(zero) { const count nnz = triplets.size(); for (index i = 0; i < nnz; ++i) rowIdx[triplets[i].row]++; for (index i = 0, prefixSum = 0; i < nRows; ++i) { count nnzInRow = rowIdx[i]; rowIdx[i] = prefixSum; prefixSum += nnzInRow; } rowIdx[nRows] = nnz; for (index i = 0; i < nnz; ++i) { index row = triplets[i].row; index dest = rowIdx[row]; columnIdx[dest] = triplets[i].column; nonZeros[dest] = triplets[i].value; rowIdx[row]++; } for (index i = 0, firstIdxOfRow = 0; i <= nRows; ++i) { index newRow = rowIdx[i]; rowIdx[i] = firstIdxOfRow; firstIdxOfRow = newRow; } } /** * Constructs the @a nRows x @a nCols Matrix from the elements stored in @a * columnIdx and @a values. @a columnIdx and @a values store the colums and * values by row. * @param nRows * @param nCols * @param columnIdx * @param values * @param zero The zero element (default is 0). * @param isSorted True if the column indices in @a columnIdx are sorted in * every row. */ CSRGeneralMatrix(count nRows, count nCols, const std::vector<std::vector<index>> &columnIdx, const std::vector<std::vector<ValueType>> &values, ValueType zero = 0, bool isSorted = false) : rowIdx(nRows + 1), nRows(nRows), nCols(nCols), isSorted(isSorted), zero(zero) { count nnz = columnIdx[0].size(); for (index i = 1; i < columnIdx.size(); ++i) { rowIdx[i] = rowIdx[i - 1] + columnIdx[i - 1].size(); nnz += columnIdx[i].size(); } rowIdx[nRows] = nnz; this->columnIdx = std::vector<index>(nnz); this->nonZeros = std::vector<double>(nnz); #pragma omp parallel for for (omp_index i = 0; i < static_cast<omp_index>(nRows); ++i) { for (index k = 0; k < columnIdx[i].size(); ++k) { this->columnIdx[rowIdx[i] + k] = columnIdx[i][k]; nonZeros[rowIdx[i] + k] = values[i][k]; } } } /** * Constructs the @a nRows x @a nCols Matrix from the elements at position @a * positions with values @values. * @param nRows Defines how many rows this matrix has. * @param nCols Defines how many columns this matrix has. * @param rowIdx The rowIdx vector of the CSR format. * @param columnIdx The columnIdx vector of the CSR format. * @param nonZeros The nonZero vector of the CSR format. Should be as long as * the @a columnIdx vector. * @param zero The zero element (default is 0). * @param isSorted True, if the triplets are sorted per row. Default is false. */ CSRGeneralMatrix(count nRows, count nCols, const std::vector<index> &rowIdx, const std::vector<index> &columnIdx, const std::vector<ValueType> &nonZeros, ValueType zero = 0, bool isSorted = false) : rowIdx(rowIdx), columnIdx(columnIdx), nonZeros(nonZeros), nRows(nRows), nCols(nCols), isSorted(isSorted), zero(zero) {} /** Default copy constructor */ CSRGeneralMatrix(const CSRGeneralMatrix &other) = default; /** Default move constructor */ CSRGeneralMatrix(CSRGeneralMatrix &&other) noexcept = default; /** Default destructor */ ~CSRGeneralMatrix() = default; /** Default move assignment operator */ CSRGeneralMatrix &operator=(CSRGeneralMatrix &&other) noexcept = default; /** Default copy assignment operator */ CSRGeneralMatrix &operator=(const CSRGeneralMatrix &other) = default; /** * Compares this matrix to @a other and returns true if the shape and zero * element are the same as well as * all entries, otherwise returns false. * @param other */ bool operator==(const CSRGeneralMatrix &other) const { bool equal = nRows == other.nRows && nCols == other.nCols && zero == other.zero; if (equal) forNonZeroElementsInRowOrder([&](index i, index j, ValueType value) { if (other(i, j) != value) { equal = false; return; } }); return equal; } /** * Compares this matrix to @a other and returns false if the shape and zero * element are the same as well as * all entries, otherwise returns true. * @param other */ bool operator!=(const CSRGeneralMatrix &other) const { return !((*this) == other); } /** * @return Number of rows. */ count numberOfRows() const noexcept { return nRows; } /** * @return Number of columns. */ count numberOfColumns() const noexcept { return nCols; } /** * Returns the zero element of the matrix. */ ValueType getZero() const noexcept { return zero; } /** * @param i The row index. * @return Number of non-zeros in row @a i. */ count nnzInRow(const index i) const { assert(i < nRows); return rowIdx[i + 1] - rowIdx[i]; } /** * @return Number of non-zeros in this matrix. */ count nnz() const noexcept { return nonZeros.size(); } /** * @return Value at matrix position (i,j). */ ValueType operator()(index i, index j) const { assert(i < nRows); assert(j < nCols); if (rowIdx[i] == rowIdx[i + 1]) return zero; // no non-zero value is present in this row double value = zero; if (!sorted()) { for (index k = rowIdx[i]; k < rowIdx[i + 1]; ++k) { if (columnIdx[k] == j) { value = nonZeros[k]; break; } } } else { index colIdx = binarySearchColumns(rowIdx[i], rowIdx[i + 1] - 1, j); if (colIdx != none && rowIdx[i] <= colIdx && columnIdx[colIdx] == j) { value = nonZeros[colIdx]; } } return value; } /** * Set the matrix at position (@a i, @a j) to @a value. * @note This operation can be linear in the number of non-zeros due to vector * element movements */ void setValue(index i, index j, ValueType value) { assert(i < nRows); assert(j < nCols); index colIdx = none; if (nnzInRow(i) == 0) { colIdx = none; } else if (!sorted()) { for (index k = rowIdx[i]; k < rowIdx[i + 1]; ++k) { if (columnIdx[k] == j) { colIdx = k; } } } else { colIdx = binarySearchColumns(rowIdx[i], rowIdx[i + 1] - 1, j); } if (colIdx != none && colIdx >= rowIdx[i] && columnIdx[colIdx] == j) { // the matrix already has an entry at (i,j) => replace it if (value == getZero()) { // remove the nonZero value columnIdx.erase(columnIdx.begin() + colIdx); nonZeros.erase(nonZeros.begin() + colIdx); // update rowIdx for (index k = i + 1; k < rowIdx.size(); ++k) { --rowIdx[k]; } } else { nonZeros[colIdx] = value; } } else { // create a new non-zero entry at (i,j) if (!sorted()) { columnIdx.emplace(std::next(columnIdx.begin(), rowIdx[i + 1]), j); nonZeros.emplace(std::next(nonZeros.begin(), rowIdx[i + 1]), value); } else { if (colIdx < rowIdx[i] || colIdx == none) { // emplace the value in // front of all other values // of row i columnIdx.emplace(std::next(columnIdx.begin(), rowIdx[i]), j); nonZeros.emplace(std::next(nonZeros.begin(), rowIdx[i]), value); } else { columnIdx.emplace(std::next(columnIdx.begin(), colIdx + 1), j); nonZeros.emplace(std::next(nonZeros.begin(), colIdx + 1), value); } } // update rowIdx for (index k = i + 1; k < rowIdx.size(); ++k) { rowIdx[k]++; } } } /** * Sorts the column indices in each row for faster access. */ void sort() { #pragma omp parallel for schedule(guided) for (omp_index i = 0; i < static_cast<omp_index>(nRows); ++i) { if (rowIdx[i + 1] - rowIdx[i] > 1) { quicksort(rowIdx[i], rowIdx[i + 1] - 1); } } #ifndef NETWORKIT_SANITY_CHECKS bool sorted = true; tlx::unused(sorted); #pragma omp parallel for for (omp_index i = 0; i < static_cast<omp_index>(nRows); ++i) { for (index j = rowIdx[i] + 1; j < rowIdx[i + 1]; ++j) { if (columnIdx[j - 1] > columnIdx[j]) { sorted = false; break; } } } assert(sorted); #endif // NETWORKIT_SANITY_CHECKS isSorted = true; } /** * @return True if the matrix is sorted, otherwise false. */ bool sorted() const noexcept { return isSorted; } /** * @return Row @a i of this matrix as vector. */ Vector row(index i) const { assert(i < nRows); Vector row(numberOfColumns(), zero, true); parallelForNonZeroElementsInRow(i, [&row](index j, double value) { row[j] = value; }); return row; } /** * @return Column @a j of this matrix as vector. */ Vector column(index j) const { assert(j < nCols); Vector column(numberOfRows(), getZero()); #pragma omp parallel for for (omp_index i = 0; i < static_cast<omp_index>(numberOfRows()); ++i) column[i] = (*this)(i, j); return column; } /** * @return The main diagonal of this matrix. */ Vector diagonal() const { Vector diag(std::min(nRows, nCols), zero); if (sorted()) { #pragma omp parallel for for (omp_index i = 0; i < static_cast<omp_index>(diag.getDimension()); ++i) { if (rowIdx[i] == rowIdx[i + 1]) continue; // no entry in row i index left = rowIdx[i]; index right = rowIdx[i + 1] - 1; index mid = (left + right) / 2; while (left <= right) { if (columnIdx[mid] == i) { diag[i] = nonZeros[mid]; break; } if (columnIdx[mid] < i) { left = mid + 1; } else { right = mid - 1; } mid = (left + right) / 2; } } } else { #pragma omp parallel for for (omp_index i = 0; i < static_cast<omp_index>(diag.getDimension()); ++i) { diag[i] = (*this)(i, i); } } return diag; } /** * Adds this matrix to @a other and returns the result. * @return The sum of this matrix and @a other. */ CSRGeneralMatrix operator+(const CSRGeneralMatrix &other) const { assert(nRows == other.nRows && nCols == other.nCols); return CSRGeneralMatrix<ValueType>::binaryOperator( *this, other, [](double val1, double val2) { return val1 + val2; }); } /** * Adds @a other to this matrix. * @return Reference to this matrix. */ CSRGeneralMatrix &operator+=(const CSRGeneralMatrix &other) { assert(nRows == other.nRows && nCols == other.nCols); *this = CSRGeneralMatrix<ValueType>::binaryOperator( *this, other, [](double val1, double val2) { return val1 + val2; }); return *this; } /** * Subtracts @a other from this matrix and returns the result. * @return The difference of this matrix and @a other. * */ CSRGeneralMatrix operator-(const CSRGeneralMatrix &other) const { assert(nRows == other.nRows && nCols == other.nCols); return CSRGeneralMatrix<ValueType>::binaryOperator( *this, other, [](double val1, double val2) { return val1 - val2; }); } /** * Subtracts @a other from this matrix. * @return Reference to this matrix. */ CSRGeneralMatrix &operator-=(const CSRGeneralMatrix &other) { assert(nRows == other.nRows && nCols == other.nCols); *this = CSRGeneralMatrix<ValueType>::binaryOperator( *this, other, [](double val1, double val2) { return val1 - val2; }); return *this; } /** * Multiplies this matrix with a scalar specified in @a scalar and returns the * result. * @return The result of multiplying this matrix with @a scalar. */ CSRGeneralMatrix operator*(const ValueType &scalar) const { return CSRGeneralMatrix(*this) *= scalar; } /** * Multiplies this matrix with a scalar specified in @a scalar. * @return Reference to this matrix. */ CSRGeneralMatrix &operator*=(const ValueType &scalar) { #pragma omp parallel for for (omp_index k = 0; k < static_cast<omp_index>(nonZeros.size()); ++k) nonZeros[k] *= scalar; return *this; } /** * Multiplies this matrix with @a vector and returns the result. * @return The result of multiplying this matrix with @a vector. */ Vector operator*(const Vector &vector) const { assert(!vector.isTransposed()); assert(nCols == vector.getDimension()); Vector result(nRows, zero); #pragma omp parallel for for (omp_index i = 0; i < static_cast<omp_index>(numberOfRows()); ++i) { double sum = zero; for (index cIdx = rowIdx[i]; cIdx < rowIdx[i + 1]; ++cIdx) { sum += nonZeros[cIdx] * vector[columnIdx[cIdx]]; } result[i] = sum; } return result; } /** * Multiplies this matrix with @a other and returns the result in a new * matrix. * @return The result of multiplying this matrix with @a other. */ CSRGeneralMatrix operator*(const CSRGeneralMatrix &other) const { assert(nCols == other.nRows); std::vector<index> rowIdx(numberOfRows() + 1, 0); std::vector<index> columnIdx; std::vector<double> nonZeros; #pragma omp parallel { std::vector<int64_t> marker(other.numberOfColumns(), -1); count numThreads = omp_get_num_threads(); index threadId = omp_get_thread_num(); count chunkSize = (numberOfRows() + numThreads - 1) / numThreads; index chunkStart = threadId * chunkSize; index chunkEnd = std::min(numberOfRows(), chunkStart + chunkSize); for (index i = chunkStart; i < chunkEnd; ++i) { for (index jA = this->rowIdx[i]; jA < this->rowIdx[i + 1]; ++jA) { index k = this->columnIdx[jA]; for (index jB = other.rowIdx[k]; jB < other.rowIdx[k + 1]; ++jB) { index j = other.columnIdx[jB]; if (marker[j] != (int64_t)i) { marker[j] = i; ++rowIdx[i + 1]; } } } } std::fill(marker.begin(), marker.end(), -1); #pragma omp barrier #pragma omp single { for (index i = 0; i < numberOfRows(); ++i) rowIdx[i + 1] += rowIdx[i]; columnIdx = std::vector<index>(rowIdx[numberOfRows()]); nonZeros = std::vector<double>(rowIdx[numberOfRows()]); } for (index i = chunkStart; i < chunkEnd; ++i) { index rowBegin = rowIdx[i]; index rowEnd = rowBegin; for (index jA = this->rowIdx[i]; jA < this->rowIdx[i + 1]; ++jA) { index k = this->columnIdx[jA]; double valA = this->nonZeros[jA]; for (index jB = other.rowIdx[k]; jB < other.rowIdx[k + 1]; ++jB) { index j = other.columnIdx[jB]; double valB = other.nonZeros[jB]; if (marker[j] < (int64_t)rowBegin) { marker[j] = rowEnd; columnIdx[rowEnd] = j; nonZeros[rowEnd] = valA * valB; ++rowEnd; } else { nonZeros[marker[j]] += valA * valB; } } } } } CSRGeneralMatrix result(numberOfRows(), other.numberOfColumns(), rowIdx, columnIdx, nonZeros); if (sorted() && other.sorted()) result.sort(); return result; } /** * Divides this matrix by a divisor specified in @a divisor and returns the * result in a new matrix. * @return The result of dividing this matrix by @a divisor. */ CSRGeneralMatrix operator/(const ValueType &divisor) const { return CSRGeneralMatrix(*this) /= divisor; } /** * Divides this matrix by a divisor specified in @a divisor. * @return Reference to this matrix. */ CSRGeneralMatrix &operator/=(const ValueType &divisor) { return *this *= 1.0 / divisor; } /** * Computes @a A @a binaryOp @a B on the elements of matrix @a A and matrix @a * B. * @param A Sorted CSRGeneralMatrix. * @param B Sorted CSRGeneralMatrix. * @param binaryOp Function handling (ValueType, ValueType) -> ValueType * @return @a A @a binaryOp @a B. * @note @a A and @a B must have the same dimensions and must be sorted. */ template <typename L> static CSRGeneralMatrix binaryOperator(const CSRGeneralMatrix &A, const CSRGeneralMatrix &B, L binaryOp); /** * Computes @a A^T * @a B. * @param A * @param B * @return @a A^T * @a B. * @note The number of rows of @a A must be equal to the number of rows of @a * B. */ static CSRGeneralMatrix mTmMultiply(const CSRGeneralMatrix &A, const CSRGeneralMatrix &B) { assert(A.nRows == B.nRows); std::vector<std::vector<index>> columnIdx(A.numberOfColumns()); std::vector<std::vector<double>> values(A.numberOfColumns()); for (index k = 0; k < A.numberOfRows(); ++k) { A.forNonZeroElementsInRow(k, [&](index i, double vA) { B.forNonZeroElementsInRow(k, [&](index j, double vB) { bool found = false; for (index l = 0; l < columnIdx[i].size(); ++l) { if (columnIdx[i][l] == j) { values[i][l] += vA * vB; found = true; break; } } if (!found) { columnIdx[i].push_back(j); values[i].push_back(vA * vB); } }); }); } return CSRGeneralMatrix(A.nCols, B.nCols, columnIdx, values); } /** * Computes @a A * @a B^T. * @param A * @param B * @return @a A * @a B^T. * @note The number of columns of @a A must be equal to the number of columns * of @a B. */ static CSRGeneralMatrix mmTMultiply(const CSRGeneralMatrix &A, const CSRGeneralMatrix &B) { assert(A.nCols == B.nCols); std::vector<std::vector<index>> columnIdx(A.numberOfRows()); std::vector<std::vector<double>> values(A.numberOfRows()); for (index i = 0; i < A.numberOfRows(); ++i) { A.forNonZeroElementsInRow(i, [&](index k, double vA) { for (index j = 0; j < B.numberOfRows(); ++j) { double vB = B(j, k); if (vB != A.zero) { bool found = false; for (index l = 0; l < columnIdx[i].size(); ++l) { if (columnIdx[i][l] == j) { values[i][l] += vA * vB; found = true; break; } } if (!found) { columnIdx[i].push_back(j); values[i].push_back(vA * vB); } } } }); } return CSRGeneralMatrix(A.nRows, B.nRows, columnIdx, values); } /** * Computes @a matrix^T * @a vector. * @param matrix * @param vector * @return @a matrix^T * @a vector. * @note The number of rows of @a matrix must be equal to the dimension of @a * vector. */ static Vector mTvMultiply(const CSRGeneralMatrix &matrix, const Vector &vector) { assert(matrix.nRows == vector.getDimension() && !vector.isTransposed()); Vector result(matrix.numberOfColumns(), 0); for (index k = 0; k < matrix.numberOfRows(); ++k) { matrix.forNonZeroElementsInRow( k, [&](index j, double value) { result[j] += value * vector[k]; }); } return result; } /** * Transposes this matrix and returns it. */ CSRGeneralMatrix transpose() const { std::vector<index> rowIdx(numberOfColumns() + 1); for (index i = 0; i < nnz(); ++i) ++rowIdx[columnIdx[i] + 1]; for (index i = 0; i < numberOfColumns(); ++i) rowIdx[i + 1] += rowIdx[i]; std::vector<index> columnIdx(rowIdx[numberOfColumns()]); std::vector<double> nonZeros(rowIdx[numberOfColumns()]); for (index i = 0; i < numberOfRows(); ++i) { for (index j = this->rowIdx[i]; j < this->rowIdx[i + 1]; ++j) { index colIdx = this->columnIdx[j]; columnIdx[rowIdx[colIdx]] = i; nonZeros[rowIdx[colIdx]] = this->nonZeros[j]; ++rowIdx[colIdx]; } } index shift = 0; for (index i = 0; i < numberOfColumns(); ++i) { index temp = rowIdx[i]; rowIdx[i] = shift; shift = temp; } rowIdx[numberOfColumns()] = nonZeros.size(); return CSRGeneralMatrix(nCols, nRows, rowIdx, columnIdx, nonZeros, getZero()); } /** * Extracts a matrix with rows and columns specified by @a rowIndices and @a * columnIndices from this matrix. * The order of rows and columns is equal to the order in @a rowIndices and @a * columnIndices. It is also * possible to specify a row or column more than once to get duplicates. * @param rowIndices * @param columnIndices */ CSRGeneralMatrix extract(const std::vector<index> &rowIndices, const std::vector<index> &columnIndices) const { std::vector<Triplet> triplets; std::vector<std::vector<index>> columnMapping(numberOfColumns()); for (index j = 0; j < columnIndices.size(); ++j) columnMapping[columnIndices[j]].push_back(j); bool sorted = true; for (index i = 0; i < rowIndices.size(); ++i) { Triplet last = {i, 0, 0}; (*this).forNonZeroElementsInRow(rowIndices[i], [&](index k, double value) { if (!columnMapping[k].empty()) { for (index j : columnMapping[k]) { if (last.row == i && last.column > j) sorted = false; last = {i, j, value}; triplets.push_back(last); } } }); } return CSRGeneralMatrix(rowIndices.size(), columnIndices.size(), triplets, getZero(), sorted); } /** * Assign the contents of the matrix @a source to this matrix at rows and * columns specified by @a rowIndices and * @a columnIndices. That is, entry (i,j) of @a source is assigned to entry * (rowIndices[i], columnIndices[j]) of * this matrix. Note that the dimensions of @rowIndices and @a columnIndices * must coincide with the number of rows * and columns of @a source. * @param rowIndices * @param columnIndices * @param source */ void assign(const std::vector<index> &rowIndices, const std::vector<index> &columnIndices, const CSRGeneralMatrix &source) { assert(rowIndices.size() == source.numberOfRows()); assert(columnIndices.size() == source.numberOfColumns()); for (index i = 0; i < rowIndices.size(); ++i) source.forElementsInRow(i, [&](index j, double value) { setValue(rowIndices[i], columnIndices[j], value); }); } /** * Applies the unary function @a unaryElementFunction to each value in the * matrix. Note that it must hold that the * function applied to the zero element of this matrix returns the zero * element. * @param unaryElementFunction */ template <typename F> void apply(F unaryElementFunction); /** * Compute the (weighted) adjacency matrix of the (weighted) Graph @a graph. * @param graph */ static CSRGeneralMatrix adjacencyMatrix(const Graph &graph, ValueType zero = 0) { count nonZeros = graph.isDirected() ? graph.numberOfEdges() : graph.numberOfEdges() * 2; std::vector<Triplet> triplets(nonZeros); index idx = 0; graph.forEdges([&](node i, node j, double val) { triplets[idx++] = {i, j, val}; if (!graph.isDirected() && i != j) triplets[idx++] = {j, i, val}; }); return CSRGeneralMatrix(graph.upperNodeIdBound(), triplets, zero); } /** * Creates a diagonal matrix with dimension equal to the dimension of the * Vector @a diagonalElements. The values on * the diagonal are the ones stored in @a diagonalElements (i.e. D(i,i) = * diagonalElements[i]). * @param diagonalElements */ static CSRGeneralMatrix diagonalMatrix(const Vector &diagonalElements, ValueType zero = 0) { count nRows = diagonalElements.getDimension(); count nCols = diagonalElements.getDimension(); std::vector<index> rowIdx(nRows + 1, 0); std::iota(rowIdx.begin(), rowIdx.end(), 0); std::vector<index> columnIdx(nCols); std::vector<double> nonZeros(nCols); #pragma omp parallel for for (omp_index j = 0; j < static_cast<omp_index>(nCols); ++j) { columnIdx[j] = j; nonZeros[j] = diagonalElements[j]; } return CSRGeneralMatrix(nRows, nCols, rowIdx, columnIdx, nonZeros, zero); } /** * Returns the (weighted) incidence matrix of the (weighted) Graph @a graph. * @param graph */ static CSRGeneralMatrix incidenceMatrix(const Graph &graph, ValueType zero = 0) { if (!graph.hasEdgeIds()) throw std::runtime_error("Graph has no edge Ids. Index edges first by " "calling graph.indexEdges()"); std::vector<Triplet> triplets; if (graph.isDirected()) { graph.forEdges([&](node u, node v, edgeweight weight, edgeid edgeId) { if (u != v) { edgeweight w = std::sqrt(weight); triplets.push_back({u, edgeId, w}); triplets.push_back({v, edgeId, -w}); } }); } else { graph.forEdges([&](node u, node v, edgeweight weight, edgeid edgeId) { if (u != v) { edgeweight w = std::sqrt(weight); if (u < v) { // orientation: small node number -> great node number triplets.push_back({u, edgeId, w}); triplets.push_back({v, edgeId, -w}); } else { triplets.push_back({u, edgeId, -w}); triplets.push_back({v, edgeId, w}); } } }); } return CSRGeneralMatrix(graph.upperNodeIdBound(), graph.upperEdgeIdBound(), triplets, zero); } /** * Compute the (weighted) Laplacian of the (weighted) Graph @a graph. * @param graph */ static CSRGeneralMatrix laplacianMatrix(const Graph &graph, ValueType zero = 0) { std::vector<Triplet> triples; graph.forNodes([&](const index i) { double weightedDegree = 0; graph.forNeighborsOf(i, [&](const index j, double weight) { // - adjacency matrix if (i != j) // exclude diagonal since this would be subtracted by // the adjacency weight weightedDegree += weight; triples.push_back({i, j, -weight}); }); triples.push_back({i, i, weightedDegree}); // degree matrix }); return CSRGeneralMatrix(graph.upperNodeIdBound(), triples, zero); } /** * Returns the (weighted) normalized Laplacian matrix of the (weighted) Graph * @a graph * @param graph */ static CSRGeneralMatrix normalizedLaplacianMatrix(const Graph &graph, ValueType zero = 0) { std::vector<Triplet> triples; std::vector<double> weightedDegrees(graph.upperNodeIdBound(), 0); graph.parallelForNodes([&](const node u) { weightedDegrees[u] = graph.weightedDegree(u); }); graph.forNodes([&](const node i) { graph.forNeighborsOf(i, [&](const node j, double weight) { if (i != j) triples.push_back( {i, j, -weight / std::sqrt(weightedDegrees[i] * weightedDegrees[j])}); }); if (weightedDegrees[i] != 0) { if (graph.isWeighted()) triples.push_back({i, i, 1 - (graph.weight(i, i)) / weightedDegrees[i]}); else triples.push_back({i, i, 1}); } }); return CSRGeneralMatrix(graph.upperNodeIdBound(), triples, zero); } /** * Iterate over all non-zero elements of row @a row in the matrix and call * handler(index column, ValueType value) */ template <typename L> void forNonZeroElementsInRow(index row, L handle) const { for (index k = rowIdx[row]; k < rowIdx[row + 1]; ++k) handle(columnIdx[k], nonZeros[k]); } /** * Iterate in parallel over all non-zero elements of row @a row in the matrix * and call handler(index column, ValueType value) */ template <typename L> void parallelForNonZeroElementsInRow(index row, L handle) const; /** * Iterate over all elements in row @a i in the matrix and call handle(index * column, ValueType value) */ template <typename L> void forElementsInRow(index i, L handle) const; /** * Iterate over all non-zero elements of the matrix in row order and call * handler (lambda closure). */ template <typename L> void forNonZeroElementsInRowOrder(L handle) const; /** * Iterate in parallel over all rows and call handler (lambda closure) on * non-zero elements of the matrix. */ template <typename L> void parallelForNonZeroElementsInRowOrder(L handle) const; }; template <typename ValueType> template <typename L> inline CSRGeneralMatrix<ValueType> CSRGeneralMatrix<ValueType>::binaryOperator(const CSRGeneralMatrix<ValueType> &A, const CSRGeneralMatrix<ValueType> &B, L binaryOp) { assert(A.nRows == B.nRows && A.nCols == B.nCols); if (A.sorted() && B.sorted()) { std::vector<index> rowIdx(A.nRows + 1); std::vector<std::vector<index>> columns(A.nRows); rowIdx[0] = 0; #pragma omp parallel for for (omp_index i = 0; i < static_cast<omp_index>(A.nRows); ++i) { index k = A.rowIdx[i]; index l = B.rowIdx[i]; while (k < A.rowIdx[i + 1] && l < B.rowIdx[i + 1]) { if (A.columnIdx[k] < B.columnIdx[l]) { columns[i].push_back(A.columnIdx[k]); ++k; } else if (A.columnIdx[k] > B.columnIdx[l]) { columns[i].push_back(B.columnIdx[l]); ++l; } else { // A.columnIdx[k] == B.columnIdx[l] columns[i].push_back(A.columnIdx[k]); ++k; ++l; } ++rowIdx[i + 1]; } while (k < A.rowIdx[i + 1]) { columns[i].push_back(A.columnIdx[k]); ++k; ++rowIdx[i + 1]; } while (l < B.rowIdx[i + 1]) { columns[i].push_back(B.columnIdx[l]); ++l; ++rowIdx[i + 1]; } } for (index i = 0; i < A.nRows; ++i) rowIdx[i + 1] += rowIdx[i]; count nnz = rowIdx[A.nRows]; std::vector<index> columnIdx(nnz); std::vector<ValueType> nonZeros(nnz, A.zero); #pragma omp parallel for for (omp_index i = 0; i < static_cast<omp_index>(A.nRows); ++i) { for (index cIdx = rowIdx[i], j = 0; cIdx < rowIdx[i + 1]; ++cIdx, ++j) columnIdx[cIdx] = columns[i][j]; columns[i].clear(); columns[i].resize(0); columns[i].shrink_to_fit(); } #pragma omp parallel for for (omp_index i = 0; i < static_cast<omp_index>(A.nRows); ++i) { index k = A.rowIdx[i]; index l = B.rowIdx[i]; for (index cIdx = rowIdx[i]; cIdx < rowIdx[i + 1]; ++cIdx) { if (k < A.rowIdx[i + 1] && columnIdx[cIdx] == A.columnIdx[k]) { nonZeros[cIdx] = A.nonZeros[k]; ++k; } if (l < B.rowIdx[i + 1] && columnIdx[cIdx] == B.columnIdx[l]) { nonZeros[cIdx] = binaryOp(nonZeros[cIdx], B.nonZeros[l]); ++l; } } } return CSRGeneralMatrix(A.nRows, A.nCols, rowIdx, columnIdx, nonZeros, A.zero, true); } else { // A or B not sorted std::vector<int64_t> columnPointer(A.nCols, -1); std::vector<ValueType> Arow(A.nCols, A.zero); std::vector<ValueType> Brow(A.nCols, B.zero); std::vector<Triplet> triplets; for (index i = 0; i < A.nRows; ++i) { index listHead = 0; count nnz = 0; // search for nonZeros in our own matrix for (index k = A.rowIdx[i]; k < A.rowIdx[i + 1]; ++k) { index j = A.columnIdx[k]; Arow[j] = A.nonZeros[k]; columnPointer[j] = listHead; listHead = j; nnz++; } // search for nonZeros in the other matrix for (index k = B.rowIdx[i]; k < B.rowIdx[i + 1]; ++k) { index j = B.columnIdx[k]; Brow[j] = B.nonZeros[k]; if (columnPointer[j] == -1) { // our own matrix does not have a nonZero entry in column j columnPointer[j] = listHead; listHead = j; nnz++; } } // apply operator on the found nonZeros in A and B for (count k = 0; k < nnz; ++k) { ValueType value = binaryOp(Arow[listHead], Brow[listHead]); if (value != A.zero) triplets.push_back({i, listHead, value}); index temp = listHead; listHead = columnPointer[listHead]; // reset for next row columnPointer[temp] = -1; Arow[temp] = A.zero; Brow[temp] = B.zero; } nnz = 0; } return CSRGeneralMatrix(A.numberOfRows(), A.numberOfColumns(), triplets); } } template <typename ValueType> template <typename F> void CSRGeneralMatrix<ValueType>::apply(const F unaryElementFunction) { #pragma omp parallel for for (omp_index k = 0; k < static_cast<omp_index>(nonZeros.size()); ++k) nonZeros[k] = unaryElementFunction(nonZeros[k]); } template <typename ValueType> template <typename L> inline void CSRGeneralMatrix<ValueType>::parallelForNonZeroElementsInRow(index i, L handle) const { #pragma omp parallel for for (omp_index k = rowIdx[i]; k < static_cast<omp_index>(rowIdx[i + 1]); ++k) handle(columnIdx[k], nonZeros[k]); } template <typename ValueType> template <typename L> inline void CSRGeneralMatrix<ValueType>::forElementsInRow(index i, L handle) const { Vector rowVector = row(i); index j = 0; rowVector.forElements([&](ValueType val) { handle(j++, val); }); } template <typename ValueType> template <typename L> inline void CSRGeneralMatrix<ValueType>::forNonZeroElementsInRowOrder(L handle) const { for (index i = 0; i < nRows; ++i) for (index k = rowIdx[i]; k < rowIdx[i + 1]; ++k) handle(i, columnIdx[k], nonZeros[k]); } template <typename ValueType> template <typename L> inline void CSRGeneralMatrix<ValueType>::parallelForNonZeroElementsInRowOrder(L handle) const { #pragma omp parallel for for (omp_index i = 0; i < static_cast<omp_index>(nRows); ++i) for (index k = rowIdx[i]; k < rowIdx[i + 1]; ++k) handle(i, columnIdx[k], nonZeros[k]); } } /* namespace NetworKit */ #endif // NETWORKIT_ALGEBRAIC_CSR_GENERAL_MATRIX_HPP_
[ "eugenio.angriman@informatik.hu-berlin.de" ]
eugenio.angriman@informatik.hu-berlin.de
67b66da9cd02cc0726670fe15cabaae56d6a394a
eec151469db7aaf57a590d4f448f9a91402ca58b
/C++STL/algorithms/magiciansalgo.cpp
069363dd68930ced265ed439c0c51f91e465bc76
[]
no_license
VivanVatsa/c-collection
bf0a37261095bc28871568b7d04d84f9fde7f48c
53317863911566257669f247609d6369ba0c4420
refs/heads/master
2020-12-26T21:06:24.106467
2020-12-10T05:41:07
2020-12-10T05:41:07
237,642,241
0
0
null
null
null
null
UTF-8
C++
false
false
5,397
cpp
/* Non-Manipulating Algorithms sort(first_iterator, last_iterator) – To sort the given vector. reverse(first_iterator, last_iterator) – To reverse a vector. *max_element (first_iterator, last_iterator) – To find the maximum element of a vector. *min_element (first_iterator, last_iterator) – To find the minimum element of a vector. accumulate(first_iterator, last_iterator, initial value of sum) – Does the summation of vector elements count(first_iterator, last_iterator,x) – To count the occurrences of x in vector. find(first_iterator, last_iterator, x) – Points to last address of vector ((name_of_vector).end()) if element is not present in vector. binary_search(first_iterator, last_iterator, x) – Tests whether x exists in sorted vector or not. lower_bound(first_iterator, last_iterator, x) – returns an iterator pointing to the first element in the range [first,last) which has a value not less than ‘x’. upper_bound(first_iterator, last_iterator, x) – returns an iterator pointing to the first element in the range [first,last) which has a value greater than ‘x’. Some Manipulating Algorithms arr.erase(position to be deleted) – This erases selected element in vector and shifts and resizes the vector elements accordingly. arr.erase(unique(arr.begin(),arr.end()),arr.end()) – This erases the duplicate occurrences in sorted vector in a single line. next_permutation(first_iterator, last_iterator) – This modified the vector to its next permutation. prev_permutation(first_iterator, last_iterator) – This modified the vector to its previous permutation. distance(first_iterator,desired_position) – It returns the distance of desired position from the first iterator.This function is very useful while finding the index. */ #include <bits/stdc++.h> #include <iostream> #include <algorithm> #include <vector> using namespace std; int main(void){ // for sorting the vector int ar[] = {10, 20, 5, 23, 42, 15}; int n = sizeof(ar) / sizeof(ar[0]); vector<int> vect(ar, ar + n); // this is the init of the vector which has the starting element as the "ar" and will go until the size becomes equivalent to "ar+n" cout << "the entered "; for(int i=0; i<n; i++) cout << vect[i] << " "; // Sorting the Vector in Ascending order sort(vect.begin(), vect.end()); cout << "\nVector after sorting is: "; for (int i = 0; i < n; i++) cout << vect[i] << " "; // Reversing the Vector reverse(vect.begin(), vect.end()); cout << "\nVector after reversing is: "; for (int i = 0; i < 6; i++) cout << vect[i] << " "; cout << "\nMaximum element of vector is: "; cout << *max_element(vect.begin(), vect.end()); cout << "\nMinimum element of vector is: "; cout << *min_element(vect.begin(), vect.end()); // Starting the summation from 0 cout << "\nThe summation of vector elements is: "; cout << accumulate(vect.begin(), vect.end(), 0); cout << "Occurrences of 20 in vector : "; // Counts the occurrences of 20 from 1st to // last element cout << count(vect.begin(), vect.end(), 20); // find() returns iterator to last address if // element not present find(vect.begin(), vect.end(), 5) != vect.end() ? cout << "\nElement found" : cout << "\nElement not found"; auto q = lower_bound(vect.begin(), vect.end(), 20); // Returns the last occurrence of 20 auto p = upper_bound(vect.begin(), vect.end(), 20); cout << "The lower bound is at position: "; cout << q - vect.begin() << endl; cout << "The upper bound is at position: "; cout << p - vect.begin() << endl; // ----------------------------------- cout << "Vector is :"; for (int i = 0; i < 6; i++) cout << vect[i] << " "; // Delete second element of vector vect.erase(vect.begin() + 1); cout << "\nVector after erasing the element: "; for (int i = 0; i < 5; i++) cout << vect[i] << " "; // sorting to enable use of unique() sort(vect.begin(), vect.end()); cout << "\nVector before removing duplicate " " occurrences: "; for (int i = 0; i < 5; i++) cout << vect[i] << " "; // Deletes the duplicate occurrences vect.erase(unique(vect.begin(), vect.end()), vect.end()); cout << "\nVector after deleting duplicates: "; for (int i = 0; i < vect.size(); i++) cout << vect[i] << " "; // ---------------------------------------- cout << "Given Vector is:\n"; for (int i = 0; i < n; i++) cout << vect[i] << " "; // modifies vector to its next permutation order next_permutation(vect.begin(), vect.end()); cout << "\nVector after performing next permutation:\n"; for (int i = 0; i < n; i++) cout << vect[i] << " "; prev_permutation(vect.begin(), vect.end()); cout << "\nVector after performing prev permutation:\n"; for (int i = 0; i < n; i++) cout << vect[i] << " "; // ---------------------------------------- // Return distance of first to maximum element cout << "Distance between first to max element: "; cout << distance(vect.begin(), max_element(vect.begin(), vect.end())); // ---------------------------------- return 0; }
[ "VivanVatsa@users.noreply.github.com" ]
VivanVatsa@users.noreply.github.com
6abadb9d36fbb1c9fa388c52fc78c61cb57213a6
20d6276f77e34804b6b582886cff8de31a43801a
/Sample/BasicSample/sample_cpp/Texture/Texture_Edit.cpp
182e75a406b3cae2b39b7cf8b2116f63e339a365
[ "LicenseRef-scancode-warranty-disclaimer", "LicenseRef-scancode-unknown-license-reference", "Libpng", "GD", "IJG", "Zlib", "BSD-3-Clause", "MIT", "MS-PL", "Apache-2.0" ]
permissive
altseed/Altseed
359edb9cee76244e9aeb13a068f9452dcff7ac4a
eb43a216cdb48ba686abcc897f8327df5b4f184c
refs/heads/master
2021-07-12T19:30:15.157041
2020-04-26T09:39:49
2020-04-26T09:39:49
13,886,553
38
14
NOASSERTION
2019-07-28T08:32:27
2013-10-26T16:13:59
C
UTF-8
C++
false
false
1,553
cpp
 #include <Altseed.h> /** @brief 読み込まれた画像を編集するサンプル */ void Texture_Edit() { // Altseedを初期化する。 asd::Engine::Initialize(u"Texture_Edit", 640, 480, asd::EngineOption()); // 画像を編集可能な状態で読み込む。 std::shared_ptr<asd::Texture2D> texture = asd::Engine::GetGraphics()->CreateEditableTexture2D(u"Data/Texture/Picture1.png"); // 画像を編集する。 asd::TextureLockInfomation lockInfo; // ロックして編集可能な状態にする。 if (texture->Lock(&lockInfo)) { for (int32_t y = 0; y < lockInfo.GetSize().Y; y++) { for (int32_t x = 0; x < lockInfo.GetSize().X; x++) { auto pixel = &((uint8_t*) lockInfo.GetPixels())[(x + y * lockInfo.GetSize().X) * lockInfo.GetPitch()]; pixel[1] = y / 2; } } // Unlockして編集結果を適用する。 texture->Unlock(); } // 画像描画オブジェクトのインスタンスを生成する。 std::shared_ptr<asd::TextureObject2D> obj = std::make_shared<asd::TextureObject2D>(); // 描画される画像を設定する。 obj->SetTexture(texture); // 描画位置を指定する。 obj->SetPosition(asd::Vector2DF(50, 50)); // 画像描画オブジェクトのインスタンスをエンジンに追加する。 asd::Engine::AddObject2D(obj); // Altseedのウインドウが閉じられていないか確認する。 while (asd::Engine::DoEvents()) { // Altseedを更新する。 asd::Engine::Update(); } // Altseedを終了する。 asd::Engine::Terminate(); }
[ "swda.durl@gmail.com" ]
swda.durl@gmail.com
9cdf588913f2b85b723d776b368e481618e38fcc
2ea893c59e4be5646eb4b92f1047274cc3af9ab6
/fun1/fun11.cpp
0df8820b71dc1aab317f90567c3e6dd2aa9e926d
[]
no_license
JonasHyllengren/FridayFun
71258d5a60c8ffa402651e30e6914f33f578e753
4d0647d3947ec5c02c55eeeec4c4b300de5e89ef
refs/heads/master
2020-03-15T13:24:31.217797
2018-05-07T19:10:37
2018-05-07T19:10:37
132,165,738
0
0
null
null
null
null
UTF-8
C++
false
false
152
cpp
#include <iostream> using namespace std; struct X{ X(){cout<<"Start!\n";}; ~X(){cout<<"End!\n";}; } x; int main() { cout << "Hello!\n"; }
[ "jonas.hyllengren@gmail.com" ]
jonas.hyllengren@gmail.com
acf9db8b0a4bac9a394654cb03982608b785cc1d
ee083d3ae978e770ee403d452aa9fdfb50e9f3ef
/vc/第3章 標準関数の極意/func209.cpp
56da863ff49a60ab0268c885bb3c5ff86dc60f44
[]
no_license
moonmile/gyakubiki-cpp
be0b0c704cf2592564fb37b596e86ca74e51b52f
b18ea7628e388a7a36cabda1a5b7af642b1b3967
refs/heads/master
2020-03-21T04:46:33.673723
2018-06-21T06:07:35
2018-06-21T06:07:35
138,126,465
0
0
null
null
null
null
SHIFT_JIS
C++
false
false
295
cpp
#include <stdio.h> #include <string.h> void main( void ) { char src[] = " world"; char dest[100]; char *p; strcpy( dest, "Hello" ); printf( "追加する前: [%s]\n", dest ); p = strcat( dest, src ); printf( "追加した後: [%s]\n", dest ); printf( "戻り値: [%s]\n", p ); }
[ "masuda@moonmile.net" ]
masuda@moonmile.net
28fee0dde7ad3ccd9a87744707f92a5d85aab7e1
e50c719c6f68b213702b3dba37788e27efbe5383
/Academy+Moldova(Ecole 42)/Piscine_CPP/Day02/Exercises/ex01/Fixed.hpp
67708a07101593b14af9bdd9769981fc5c6c039a
[]
no_license
user3max/Tutorials-and-Courses
1be52de7b01768ac2b4cb37fae2e68e3249f753e
41ba25b6d0956501444f1be8f8681c9577749340
refs/heads/master
2020-03-25T18:22:40.768061
2018-11-12T07:54:15
2018-11-12T07:54:15
144,027,424
0
0
null
null
null
null
UTF-8
C++
false
false
517
hpp
//Fixed.hpp by Carp-Bezverhnii Maxim #ifndef FIXED_HPP # define FIXED_HPP #include <iostream> #include <cmath> class Fixed { int _fixPointVal; static const int _fracBits = 8; public: Fixed(); ~Fixed(); Fixed(const Fixed&); Fixed(int const param); Fixed(float const param); Fixed & operator=(Fixed const &rhs); int getRawBits(void) const; void setRawBits(int const raw); float toFloat(void) const; int toInt(void) const; }; std::ostream& operator<<(std::ostream& os, Fixed const &rhs); #endif
[ "maxymyn@gmail.com" ]
maxymyn@gmail.com
410c9e9c62fc0a1cda3733fcc45ccdbc522ab10d
20b49a6ef1fa417d67abef2d29a598c9e41c478e
/atCoder/Beginner Contests/Beginner Contest 153/B.cpp
e08436e1f10596aa127510453ee77605330267c0
[]
no_license
switchpiggy/Competitive_Programming
956dac4a71fdf65de2959dd142a2032e2f0710e1
beaaae4ece70889b0af1494d68c630a6e053558a
refs/heads/master
2023-04-15T19:13:12.348433
2021-04-04T06:12:29
2021-04-04T06:12:29
290,905,106
1
3
null
2020-10-05T20:16:53
2020-08-27T23:38:48
C++
UTF-8
C++
false
false
334
cpp
#include <bits/stdc++.h> using namespace std; typedef long long int ll; ll h, n, a[100007]; int main() { ios_base::sync_with_stdio(0); cin.tie(0); cin >> h >> n; ll ans = 0; for(ll i = 0; i < n; ++i) { cin >> a[i]; ans += a[i]; } if(ans >= h) cout << "Yes\n"; else cout << "No\n"; }
[ "switchpiggy@users.noreply.github.com" ]
switchpiggy@users.noreply.github.com
39b1921ab03ac3e81be8e965982e4e23ca5b3e3b
7b79b6f0a96554ac41aba7b739b9bd93b3f57c45
/A1031.cpp
0ba0d8ea001f88e81a3fef7837e0554480b7099c
[]
no_license
lrscy/PAT
f80ff57995821b493e8b98c72de56cdf13ab8994
831bb1f462aad5a6d4ab622bc04c4393832df868
refs/heads/master
2021-01-10T07:38:08.739617
2016-02-24T15:23:21
2016-02-24T15:23:21
52,203,012
0
0
null
null
null
null
UTF-8
C++
false
false
493
cpp
#include <bits/stdc++.h> using namespace std; const int MAXN = 100; char s[MAXN], space[MAXN]; int n, n1, n2; int main() { int p1, p2; scanf( "%s", s ); n = strlen( s ); n1 = ( n + 2 ) / 3; n2 = n - 2 * n1; --n1; p1 = 0; p2 = n - 1; for( int i = 0; i < n2; ++i ) space[i] = ' '; for( int i = 0; i < n1; ++i ) { putchar( s[p1] ); printf( "%s", space ); putchar( s[p2] ); puts( "" ); ++p1; --p2; } for( int i = p1; i <= p2; ++i ) putchar( s[i] ); puts( "" ); return 0; }
[ "ruosenlee@gmail.com" ]
ruosenlee@gmail.com
7e0fe55dce6bbd0e7635d85f47a4a514e26b8578
79aa77bab657403419e51e9679447f17a35dd9d8
/AStarThreading/Renderer.h
4e34032d2bf0d148c1ec35cd9bc8d384dafdf104
[]
no_license
OloinMilsom/AStarThreading
e1b940ad455f24d6d87a3777636596027004f4ef
8928d810bdfc0ed32daaf1e835baf9da3a1bf872
refs/heads/master
2021-01-10T23:53:16.542418
2016-12-15T10:01:06
2016-12-15T10:01:06
70,791,961
0
0
null
null
null
null
UTF-8
C++
false
false
963
h
#pragma once #include "SDL.h" #include "BasicTypes.h" //Responsible for all drawing operations //abstracts away specfic SDL specific drawing functions class Renderer { // size of window in pixels Size windowSize; //position of window in world coordinates //change these if you want to zoom or pan Vector2 viewportBottomLeft; Size viewportSize; Rect m_viewRect; SDL_Window *window; SDL_Renderer *sdl_renderer; public: Renderer(); ~Renderer(); bool init(const Size&, const char*); void destroy(); void drawRect(const Rect&, const Colour&) const; void drawFillRect(const Rect&, const Colour&) const; void drawWorldRect(const Rect&, const Colour&) const; void drawWorldFillRect(const Rect&, const Colour&) const; void present(); void clear(const Colour&) const; Vector2 worldToScreen(const Vector2&) const; Rect worldToScreen(const Rect&) const; void setViewPort(const Rect&); void setViewRect(const Rect&); Size getWindowSize() const; };
[ "keporagebora@gmail.com" ]
keporagebora@gmail.com
bf98abad1064e09930cd561bcf6ea1120012672c
ef49df57d210b73c3bf51de23ba1c7d5f2976ac8
/tools/LinkDef.hh
1e9bcbb18bf08f984329a3033abf5f210fdba869
[]
no_license
nardinan/firefly
9240fd79f5ee4c5ee736e884c117c8ef6a95365a
1d7b14d3dce3febe79b3352bf87520585949d15f
refs/heads/master
2020-05-18T03:55:27.460750
2019-10-20T17:10:44
2019-10-20T17:10:44
13,866,903
1
0
null
2013-12-09T12:56:43
2013-10-25T17:10:37
C
UTF-8
C++
false
false
212
hh
#ifdef __CINT__ #pragma link off all globals; #pragma link off all classes; #pragma link off all functions; #pragma link C++ class Cluster+; #pragma link C++ class Event+; #pragma link C++ class RHClass+; #endif
[ "andrea@nardinan.it" ]
andrea@nardinan.it
6153a59edfa3a26982d781c0697ad9c59761a4a9
c8c2a8123767c96bcb8aa30ade57368f7e1e6379
/cpp_module_00/Warlock.hpp
a6efde3b023955d100b5be1a0dfb910e7b33bb00
[]
no_license
mondrew/examrank05
3ffdcb57eacb4335b976e798abbe1e429b0bc019
5c7b813f2a9d4593c49e8fc127cee8ea71c924ac
refs/heads/master
2023-06-15T16:16:00.760594
2021-07-09T22:15:18
2021-07-09T22:15:18
329,066,295
0
0
null
null
null
null
UTF-8
C++
false
false
498
hpp
#ifndef WARLOCK_HPP # define WARLOCK_HPP # include <string> class Warlock { private: std::string _name; std::string _title; Warlock(void); Warlock(Warlock const &src); Warlock &operator=(Warlock const &rhs); public: Warlock(std::string const &name, std::string const &title); ~Warlock(void); std::string const &getName(void) const; std::string const &getTitle(void) const; void setTitle(std::string const &title); void introduce(void) const; }; #endif
[ "andreib2510@yandex.ru" ]
andreib2510@yandex.ru
78902892e1a97cc2bc0c837591503a3d373a714e
c3550125ff2dac0a07e5e50063f5aa44fd28e649
/Chapter05/Chapter05/ReadXMLandYAML5_6.cpp
d98e1dbb83b88db7af11f012b9365fe838f53270
[ "MIT" ]
permissive
maskmind/OpenCV-Learning-Scripts
767d4075b98360b9f6e45b832e393a587fc95e1d
dd45eada1f7c62ce5553ec0662439e5fe5fa1d7c
refs/heads/master
2022-11-16T17:44:55.716464
2020-07-16T10:19:14
2020-07-16T10:19:14
null
0
0
null
null
null
null
GB18030
C++
false
false
3,082
cpp
////--------------------------------------【程序说明】------------------------------------------- //// 程序说明:《OpenCV3编程入门》OpenCV2版书本配套示例程序30 //// 程序描述:XML和YAML文件的读取 //// 开发测试所用操作系统: Windows 7 64bit //// 开发测试所用IDE版本:Visual Studio 2010 //// 开发测试所用OpenCV版本: 2.4.9 //// 2014年06月 Created by @浅墨_毛星云 //// 2014年11月 Revised by @浅墨_毛星云 ////------------------------------------------------------------------------------------------------ // // ////---------------------------------【头文件、命名空间包含部分】------------------------------- //// 描述:包含程序所使用的头文件和命名空间 ////------------------------------------------------------------------------------------------------ //#include "opencv2/opencv.hpp" //#include <time.h> //using namespace cv; //using namespace std; // // ////-----------------------------------【ShowHelpText( )函数】---------------------------------- //// 描述:输出一些帮助信息 ////---------------------------------------------------------------------------------------------- //void ShowHelpText() //{ // //输出欢迎信息和OpenCV版本 // printf("\n\n\t\t\t非常感谢购买《OpenCV3编程入门》一书!\n"); // printf("\n\n\t\t\t此为本书OpenCV2版的第30个配套示例程序\n"); // printf("\n\n\t\t\t 当前使用的OpenCV版本为:" CV_VERSION); // printf("\n\n ----------------------------------------------------------------------------\n\n"); //} // // // // //int main() //{ // //改变console字体颜色 // system("color 6F"); // // ShowHelpText(); // // //初始化 // FileStorage fs2("test.yaml", FileStorage::READ); // // // 第一种方法,对FileNode操作 // int frameCount = (int)fs2["frameCount"]; // // std::string date; // // 第二种方法,使用FileNode运算符> > // fs2["calibrationDate"] >> date; // // Mat cameraMatrix2, distCoeffs2; // fs2["cameraMatrix"] >> cameraMatrix2; // fs2["distCoeffs"] >> distCoeffs2; // // cout << "frameCount: " << frameCount << endl // << "calibration date: " << date << endl // << "camera matrix: " << cameraMatrix2 << endl // << "distortion coeffs: " << distCoeffs2 << endl; // // FileNode features = fs2["features"]; // FileNodeIterator it = features.begin(), it_end = features.end(); // int idx = 0; // std::vector<uchar> lbpval; // // //使用FileNodeIterator遍历序列 // for (; it != it_end; ++it, idx++) // { // cout << "feature #" << idx << ": "; // cout << "x=" << (int)(*it)["x"] << ", y=" << (int)(*it)["y"] << ", lbp: ("; // // 我们也可以使用使用filenode > > std::vector操作符很容易的读数值阵列 // (*it)["lbp"] >> lbpval; // for (int i = 0; i < (int)lbpval.size(); i++) // cout << " " << (int)lbpval[i]; // cout << ")" << endl; // } // fs2.release(); // // //程序结束,输出一些帮助文字 // printf("\n文件读取完毕,请输入任意键结束程序~"); // getchar(); // // return 0; //}
[ "834165695@qq.com" ]
834165695@qq.com
4095967fafd8c244e8920b6ccdd4c058c15fe940
3b97b786b99c3e4e72bf8fe211bb710ecb674f2b
/TServer/TMapSvr/UdpSocket.h
8b11d3d6782541d8c0791be527da838080a20df8
[]
no_license
moooncloud/4s
930384e065d5172cd690c3d858fdaaa6c7fdcb34
a36a5785cc20da19cd460afa92a3f96e18ecd026
refs/heads/master
2023-03-17T10:47:28.154021
2017-04-20T21:42:01
2017-04-20T21:42:01
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,172
h
/* * UdpSocket.h * * For Send to LogServer */ #ifndef _UDPSOCKET_H_ #define _UDPSOCKET_H_ #include <LogPacket.h> /* * CUdpSocket */ class CUdpSocket { public: CUdpSocket(); ~CUdpSocket(); private: SOCKET m_SendSock; SOCKADDR_IN m_LogAddr; CRITICAL_SECTION m_LogLock; CHAR* m_lpLogBuf; INT m_nSendByte; VOID CLOSESOCKET( SOCKET &x ) { if(x != INVALID_SOCKET) closesocket(x), x = INVALID_SOCKET; } public: // Base Function BOOL Initialize(char *pIPAddr=NULL,int pPort=2000); //void Log(_LOG_DATA_ pLogData); void Log(_LPUDPPACKET); void SendToLogPacket(_LPUDPPACKET); void SendDMLog(_LOG_DATA_ pLogData); // Log Function void LogMoney(DWORD pAction, CTPlayer *pPlayer, CTMonster *pMon, __int64 pMoney,LPQUESTTEMP pQUEST=NULL, BYTE bIsWorld = 0); void LogMoneyTrade(DWORD pAction, CTPlayer *pPlayer, CString pTargetName, __int64 pMoney, int pCost=0); void LogItemByMonster(DWORD pAction, CTPlayer *pPlayer, CTMonster *pMon, CTItem *pItem, __int64 pMoney=0); void LogItemByMonster(DWORD pAction, CTPlayer *pPlayer, int pMonTempID, CTItem *pItem ); void LogItemByNPC(DWORD pAction, CTPlayer *pPlayer, CTNpc * pNpc, CTItem *pItem, int pMoney=0, LPQUESTTEMP pQUEST=NULL); void LogItemUpgrade(DWORD pAction, CTPlayer *pPlayer, CTItem *pItem, int nUpLevel=0); void LogItemByStore(DWORD pAction, CTPlayer *pPlayer, CString pTargetName, CTItem *pItem, __int64 pMoney=0, BYTE bCount = 0); void LogItemTrade(DWORD pAction, CTPlayer *pPlayer, CTItem *pItem, CString pTargetName); void LogExpByMonster(DWORD pAction, CTPlayer *pPlayer, CTMonster *pMon, DWORD dwGain, BYTE bIsWorld = 0); void LogSkillAct(DWORD pAction, CTPlayer *pPlayer, CTSkill *pSkill, __int64 pMoney = 0); void LogPet (DWORD pAction, CTPlayer *pPlayer, WORD wPeID, CString strName = NULL, __int64 dwTime = 0); void LogLevelUp (DWORD pAction, CTPlayer *pPlayer, BYTE m_bLevel); void LogMonster (DWORD pAction, CTPlayer *pPlayer, CTMonster *pMon); void LogQuest (DWORD pAction, CTPlayer *pPlayer, DWORD dwQuestID, DWORD dwGain = 0); void LogUserDie (DWORD pAction, CTPlayer *pPlayer, BYTE m_bType); void LogEnterMap (DWORD pAction, CTPlayer *pPlayer); void LogLocalOccupy (DWORD pAction, BYTE bType, WORD wLocalID, BYTE bCountry, DWORD dwGuildID); void LogLocalEnable (DWORD pAction, WORD wLocalID, BYTE bStatus); void LogCabinet (DWORD pAction, CTPlayer *pPlayer, BYTE bCabinetID, CTItem *pItem, BYTE bCount, int pMoney = 0); void LogChat (DWORD pAction, CTPlayer *pPlayer, CString strName, CString strTalk); void LogGuild (DWORD pAction, CTPlayer *pPlayer,DWORD pTargetID,CString pTargetName, DWORD pGuildID, CString strGuildName, BYTE bRet ); void LogGuildDisorganization(DWORD pAction, CTPlayer *pPlayer, BYTE pDisorg); void LogGuildDutyPeer (DWORD pAction, CTPlayer *pPlayer, DWORD pTargetID,CString pTargetName, DWORD pGuildID, CString strGuildName, int pData, BYTE bRet ); void LogGuildExpMoeny (DWORD pAction, CTPlayer *pPlayer, int pExp, int pGold, int pSilver, int pCooper, int pPvPoint, BYTE bRet); void LogGuildCabinet (DWORD pAction, CTPlayer *pPlayer, DWORD pGuildID, CString strGuildName,BYTE bCabinetID, CTItem *pItem, BYTE bCount, DWORD dwMoney); void LogCashItem (DWORD pAction, CTPlayer *pPlayer, DWORD pTargetID, CString pTargetName, CTItem *pItem,int pCashID, int pCash, int pBonus); void LogCashCabinetBuy (DWORD pAction, CTPlayer *pPlayer, int pCashID, __time64_t pDate, int pCash, int pBonus, int pResult); void LogTeleport (DWORD pAction, CTPlayer *pPlayer, CTNpc * pNpc, int pPrice, int pPortalID); void LogPvPointChar (DWORD pAction, CTPlayer *pPlayer,DWORD dwPoint,BYTE bEventType, BYTE bPointType, CString pTargetName); void LogPvPointGuild (DWORD pAction, DWORD dwPoint,WORD wLocalID, BYTE bCountry, DWORD dwGuildID, BYTE bEventType,BYTE bPointType); void LogAuctionReg (DWORD pAction, CTPlayer *pPlayer,DWORD dwAuctionID,__int64 ldwStartPrice,__int64 ldwDirectPrice, CTItem *pItem,DWORD dwCharID = 0,CString strNAME = _T("")); void LogAuctionBid (DWORD pAction, CTPlayer *pPlayer,DWORD dwAuctionID,__int64 ldwPrice,CTItem *pItem,BYTE bCount,DWORD dwCharID = 0,CString strNAME = _T("")); void LogTournamentApply (DWORD pAction, CTPlayer *pPlayer, CString pEventName, BYTE bParty, CString strTarget=_T("")); void LogTournamentWin (DWORD pAction, LPTOURNAMENTPLAYER pWin, LPTOURNAMENTPLAYER pLos, CString pTitle, DWORD dwValue, BYTE bStep); void LogTournamentEvent (DWORD pAction, CTPlayer *pPlayer, DWORD dwTargetID, CString pTitle, BYTE bType); void LogRPSGame (DWORD pAction, CTPlayer *pPlayer, BYTE bType, BYTE bWin, DWORD dwMoney); void LogTactics (DWORD pAction, CTPlayer *pPlayer, DWORD dwGuild, CString strName); void LogAidCountry (DWORD pAction, CTPlayer *pPlayer, BYTE bNowAid, BYTE bPrevAid); void LogCountry (DWORD pAction, CTPlayer *pPlayer, BYTE bNowCountry, BYTE bPrevCountry); void LogKickOut (DWORD pAction, CTPlayer *pPlayer, BYTE bType); void LogCMGift (DWORD pAction, CTPlayer *pPlayer, WORD wGiftID, DWORD dwGMID, BYTE bType, DWORD dwValue, BYTE bCount); }; #endif // _UDPSOCKET_H_
[ "great.mafia2010@gmail.com" ]
great.mafia2010@gmail.com
61d8be9a36c77e6a23bdbf7109f718c3fcc9187e
720fde4499c86b45e651fdba0b9db1280d0ee935
/src/masternode.h
2f31257d0bb103f9812f806a69c8bb321e0c5431
[ "MIT" ]
permissive
wolfxpack/wolf
171760e94c2fd2a2e0f7de940f656a756145c7a9
47b57381dc93bfb150be76cc6d288daffd1c37e6
refs/heads/master
2020-04-21T17:30:14.399335
2019-02-25T01:03:50
2019-02-25T01:03:50
169,737,526
0
1
null
null
null
null
UTF-8
C++
false
false
14,086
h
// Copyright (c) 2014-2017 The Dash Core developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef MASTERNODE_H #define MASTERNODE_H #include "key.h" #include "validation.h" #include "spork.h" class CMasternode; class CMasternodeBroadcast; class CConnman; static const int MASTERNODE_CHECK_SECONDS = 5; static const int MASTERNODE_MIN_MNB_SECONDS = 5 * 60; static const int MASTERNODE_MIN_MNP_SECONDS = 10 * 60; static const int MASTERNODE_EXPIRATION_SECONDS = 65 * 60; static const int MASTERNODE_WATCHDOG_MAX_SECONDS = 120 * 60; static const int MASTERNODE_NEW_START_REQUIRED_SECONDS = 180 * 60; static const int MASTERNODE_POSE_BAN_MAX_SCORE = 5; // // The Masternode Ping Class : Contains a different serialize method for sending pings from masternodes throughout the network // // sentinel version before sentinel ping implementation #define DEFAULT_SENTINEL_VERSION 0x010001 class CMasternodePing { public: CTxIn vin{}; uint256 blockHash{}; int64_t sigTime{}; //mnb message times std::vector<unsigned char> vchSig{}; bool fSentinelIsCurrent = false; // true if last sentinel ping was actual // MSB is always 0, other 3 bits corresponds to x.x.x version scheme uint32_t nSentinelVersion{DEFAULT_SENTINEL_VERSION}; CMasternodePing() = default; CMasternodePing(const COutPoint& outpoint); ADD_SERIALIZE_METHODS; template <typename Stream, typename Operation> inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) { READWRITE(vin); READWRITE(blockHash); READWRITE(sigTime); READWRITE(vchSig); if(ser_action.ForRead() && (s.size() == 0)) { fSentinelIsCurrent = false; nSentinelVersion = DEFAULT_SENTINEL_VERSION; return; } READWRITE(fSentinelIsCurrent); READWRITE(nSentinelVersion); } uint256 GetHash() const { CHashWriter ss(SER_GETHASH, PROTOCOL_VERSION); ss << vin; ss << sigTime; return ss.GetHash(); } bool IsExpired() const { return GetAdjustedTime() - sigTime > MASTERNODE_NEW_START_REQUIRED_SECONDS; } bool Sign(const CKey& keyMasternode, const CPubKey& pubKeyMasternode); bool CheckSignature(CPubKey& pubKeyMasternode, int &nDos); bool SimpleCheck(int& nDos); bool CheckAndUpdate(CMasternode* pmn, bool fFromNewBroadcast, int& nDos, CConnman& connman); void Relay(CConnman& connman); }; inline bool operator==(const CMasternodePing& a, const CMasternodePing& b) { return a.vin == b.vin && a.blockHash == b.blockHash; } inline bool operator!=(const CMasternodePing& a, const CMasternodePing& b) { return !(a == b); } struct masternode_info_t { // Note: all these constructors can be removed once C++14 is enabled. // (in C++11 the member initializers wrongly disqualify this as an aggregate) masternode_info_t() = default; masternode_info_t(masternode_info_t const&) = default; masternode_info_t(int activeState, int protoVer, int64_t sTime) : nActiveState{activeState}, nProtocolVersion{protoVer}, sigTime{sTime} {} masternode_info_t(int activeState, int protoVer, int64_t sTime, COutPoint const& outpoint, CService const& addr, CPubKey const& pkCollAddr, CPubKey const& pkMN, int64_t tWatchdogV = 0) : nActiveState{activeState}, nProtocolVersion{protoVer}, sigTime{sTime}, vin{outpoint}, addr{addr}, pubKeyCollateralAddress{pkCollAddr}, pubKeyMasternode{pkMN}, nTimeLastWatchdogVote{tWatchdogV} {} int nActiveState = 0; int nProtocolVersion = 0; int64_t sigTime = 0; //mnb message time CTxIn vin{}; CService addr{}; CPubKey pubKeyCollateralAddress{}; CPubKey pubKeyMasternode{}; int64_t nTimeLastWatchdogVote = 0; int64_t nLastDsq = 0; //the dsq count from the last dsq broadcast of this node int64_t nTimeLastChecked = 0; int64_t nTimeLastPaid = 0; int64_t nTimeLastPing = 0; //* not in CMN bool fInfoValid = false; //* not in CMN }; // // The Masternode Class. For managing the Darksend process. It contains the input of the 1000DRK, signature to prove // it's the one who own that ip address and code for calculating the payment election. // class CMasternode : public masternode_info_t { private: // critical section to protect the inner data structures mutable CCriticalSection cs; public: enum state { MASTERNODE_PRE_ENABLED, MASTERNODE_ENABLED, MASTERNODE_EXPIRED, MASTERNODE_OUTPOINT_SPENT, MASTERNODE_UPDATE_REQUIRED, MASTERNODE_WATCHDOG_EXPIRED, MASTERNODE_NEW_START_REQUIRED, MASTERNODE_POSE_BAN }; enum CollateralStatus { COLLATERAL_OK, COLLATERAL_UTXO_NOT_FOUND, COLLATERAL_INVALID_AMOUNT }; CMasternodePing lastPing{}; std::vector<unsigned char> vchSig{}; uint256 nCollateralMinConfBlockHash{}; int nBlockLastPaid{}; int nPoSeBanScore{}; int nPoSeBanHeight{}; bool fAllowMixingTx{}; bool fUnitTest = false; // KEEP TRACK OF GOVERNANCE ITEMS EACH MASTERNODE HAS VOTE UPON FOR RECALCULATION std::map<uint256, int> mapGovernanceObjectsVotedOn; CMasternode(); CMasternode(const CMasternode& other); CMasternode(const CMasternodeBroadcast& mnb); CMasternode(CService addrNew, COutPoint outpointNew, CPubKey pubKeyCollateralAddressNew, CPubKey pubKeyMasternodeNew, int nProtocolVersionIn); ADD_SERIALIZE_METHODS; template <typename Stream, typename Operation> inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) { LOCK(cs); READWRITE(vin); READWRITE(addr); READWRITE(pubKeyCollateralAddress); READWRITE(pubKeyMasternode); READWRITE(lastPing); READWRITE(vchSig); READWRITE(sigTime); READWRITE(nLastDsq); READWRITE(nTimeLastChecked); READWRITE(nTimeLastPaid); READWRITE(nTimeLastWatchdogVote); READWRITE(nActiveState); READWRITE(nCollateralMinConfBlockHash); READWRITE(nBlockLastPaid); READWRITE(nProtocolVersion); READWRITE(nPoSeBanScore); READWRITE(nPoSeBanHeight); READWRITE(fAllowMixingTx); READWRITE(fUnitTest); READWRITE(mapGovernanceObjectsVotedOn); } // CALCULATE A RANK AGAINST OF GIVEN BLOCK arith_uint256 CalculateScore(const uint256& blockHash); bool UpdateFromNewBroadcast(CMasternodeBroadcast& mnb, CConnman& connman); static CollateralStatus CheckCollateral(const COutPoint& outpoint); static CollateralStatus CheckCollateral(const COutPoint& outpoint, int& nHeightRet); void Check(bool fForce = false); bool IsBroadcastedWithin(int nSeconds) { return GetAdjustedTime() - sigTime < nSeconds; } bool IsPingedWithin(int nSeconds, int64_t nTimeToCheckAt = -1) { if(lastPing == CMasternodePing()) return false; if(nTimeToCheckAt == -1) { nTimeToCheckAt = GetAdjustedTime(); } return nTimeToCheckAt - lastPing.sigTime < nSeconds; } bool IsEnabled() { return nActiveState == MASTERNODE_ENABLED; } bool IsPreEnabled() { return nActiveState == MASTERNODE_PRE_ENABLED; } bool IsPoSeBanned() { return nActiveState == MASTERNODE_POSE_BAN; } // NOTE: this one relies on nPoSeBanScore, not on nActiveState as everything else here bool IsPoSeVerified() { return nPoSeBanScore <= -MASTERNODE_POSE_BAN_MAX_SCORE; } bool IsExpired() { return nActiveState == MASTERNODE_EXPIRED; } bool IsOutpointSpent() { return nActiveState == MASTERNODE_OUTPOINT_SPENT; } bool IsUpdateRequired() { return nActiveState == MASTERNODE_UPDATE_REQUIRED; } bool IsWatchdogExpired() { return nActiveState == MASTERNODE_WATCHDOG_EXPIRED; } bool IsNewStartRequired() { return nActiveState == MASTERNODE_NEW_START_REQUIRED; } static bool IsValidStateForAutoStart(int nActiveStateIn) { return nActiveStateIn == MASTERNODE_ENABLED || nActiveStateIn == MASTERNODE_PRE_ENABLED || nActiveStateIn == MASTERNODE_EXPIRED || nActiveStateIn == MASTERNODE_WATCHDOG_EXPIRED; } bool IsValidForPayment() { if(nActiveState == MASTERNODE_ENABLED) { return true; } if(!sporkManager.IsSporkActive(SPORK_14_REQUIRE_SENTINEL_FLAG) && (nActiveState == MASTERNODE_WATCHDOG_EXPIRED)) { return true; } return false; } /// Is the input associated with collateral public key? (and there is 1000 WOLF - checking if valid masternode) bool IsInputAssociatedWithPubkey(); bool IsValidNetAddr(); static bool IsValidNetAddr(CService addrIn); void IncreasePoSeBanScore() { if(nPoSeBanScore < MASTERNODE_POSE_BAN_MAX_SCORE) nPoSeBanScore++; } void DecreasePoSeBanScore() { if(nPoSeBanScore > -MASTERNODE_POSE_BAN_MAX_SCORE) nPoSeBanScore--; } void PoSeBan() { nPoSeBanScore = MASTERNODE_POSE_BAN_MAX_SCORE; } masternode_info_t GetInfo(); static std::string StateToString(int nStateIn); std::string GetStateString() const; std::string GetStatus() const; int GetLastPaidTime() { return nTimeLastPaid; } int GetLastPaidBlock() { return nBlockLastPaid; } void UpdateLastPaid(const CBlockIndex *pindex, int nMaxBlocksToScanBack); // KEEP TRACK OF EACH GOVERNANCE ITEM INCASE THIS NODE GOES OFFLINE, SO WE CAN RECALC THEIR STATUS void AddGovernanceVote(uint256 nGovernanceObjectHash); // RECALCULATE CACHED STATUS FLAGS FOR ALL AFFECTED OBJECTS void FlagGovernanceItemsAsDirty(); void RemoveGovernanceObject(uint256 nGovernanceObjectHash); void UpdateWatchdogVoteTime(uint64_t nVoteTime = 0); CMasternode& operator=(CMasternode const& from) { static_cast<masternode_info_t&>(*this)=from; lastPing = from.lastPing; vchSig = from.vchSig; nCollateralMinConfBlockHash = from.nCollateralMinConfBlockHash; nBlockLastPaid = from.nBlockLastPaid; nPoSeBanScore = from.nPoSeBanScore; nPoSeBanHeight = from.nPoSeBanHeight; fAllowMixingTx = from.fAllowMixingTx; fUnitTest = from.fUnitTest; mapGovernanceObjectsVotedOn = from.mapGovernanceObjectsVotedOn; return *this; } }; inline bool operator==(const CMasternode& a, const CMasternode& b) { return a.vin == b.vin; } inline bool operator!=(const CMasternode& a, const CMasternode& b) { return !(a.vin == b.vin); } // // The Masternode Broadcast Class : Contains a different serialize method for sending masternodes through the network // class CMasternodeBroadcast : public CMasternode { public: bool fRecovery; CMasternodeBroadcast() : CMasternode(), fRecovery(false) {} CMasternodeBroadcast(const CMasternode& mn) : CMasternode(mn), fRecovery(false) {} CMasternodeBroadcast(CService addrNew, COutPoint outpointNew, CPubKey pubKeyCollateralAddressNew, CPubKey pubKeyMasternodeNew, int nProtocolVersionIn) : CMasternode(addrNew, outpointNew, pubKeyCollateralAddressNew, pubKeyMasternodeNew, nProtocolVersionIn), fRecovery(false) {} ADD_SERIALIZE_METHODS; template <typename Stream, typename Operation> inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) { READWRITE(vin); READWRITE(addr); READWRITE(pubKeyCollateralAddress); READWRITE(pubKeyMasternode); READWRITE(vchSig); READWRITE(sigTime); READWRITE(nProtocolVersion); READWRITE(lastPing); } uint256 GetHash() const { CHashWriter ss(SER_GETHASH, PROTOCOL_VERSION); ss << vin; ss << pubKeyCollateralAddress; ss << sigTime; return ss.GetHash(); } /// Create Masternode broadcast, needs to be relayed manually after that static bool Create(const COutPoint& outpoint, const CService& service, const CKey& keyCollateralAddressNew, const CPubKey& pubKeyCollateralAddressNew, const CKey& keyMasternodeNew, const CPubKey& pubKeyMasternodeNew, std::string &strErrorRet, CMasternodeBroadcast &mnbRet); static bool Create(std::string strService, std::string strKey, std::string strTxHash, std::string strOutputIndex, std::string& strErrorRet, CMasternodeBroadcast &mnbRet, bool fOffline = false); bool SimpleCheck(int& nDos); bool Update(CMasternode* pmn, int& nDos, CConnman& connman); bool CheckOutpoint(int& nDos); bool Sign(const CKey& keyCollateralAddress); bool CheckSignature(int& nDos); void Relay(CConnman& connman); }; class CMasternodeVerification { public: CTxIn vin1{}; CTxIn vin2{}; CService addr{}; int nonce{}; int nBlockHeight{}; std::vector<unsigned char> vchSig1{}; std::vector<unsigned char> vchSig2{}; CMasternodeVerification() = default; CMasternodeVerification(CService addr, int nonce, int nBlockHeight) : addr(addr), nonce(nonce), nBlockHeight(nBlockHeight) {} ADD_SERIALIZE_METHODS; template <typename Stream, typename Operation> inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) { READWRITE(vin1); READWRITE(vin2); READWRITE(addr); READWRITE(nonce); READWRITE(nBlockHeight); READWRITE(vchSig1); READWRITE(vchSig2); } uint256 GetHash() const { CHashWriter ss(SER_GETHASH, PROTOCOL_VERSION); ss << vin1; ss << vin2; ss << addr; ss << nonce; ss << nBlockHeight; return ss.GetHash(); } void Relay() const { CInv inv(MSG_MASTERNODE_VERIFY, GetHash()); g_connman->RelayInv(inv); } }; #endif
[ "eledger102@gmail.com" ]
eledger102@gmail.com
a5cc9301ca60d1fd9b352ecced58b0bf13c75cac
70441dcb7a8917a5574dd74c5afdeeaed3672a7a
/AtCoder Beginner Contest 165/B - 1%/main.cpp
7ad608f31c331f8fc47bc1e25bce286c808c53a9
[]
no_license
tmyksj/atcoder
f12ecf6255b668792d83621369194195f06c10f6
419165e85d8a9a0614e5544232da371d8a2f2f85
refs/heads/master
2023-03-05T12:14:14.945257
2023-02-26T10:10:20
2023-02-26T10:10:20
195,034,198
0
0
null
null
null
null
UTF-8
C++
false
false
205
cpp
#include <iostream> using namespace std; int main() { long long x; cin >> x; int res = 1; for (long long i = 101; i < x; i += i / 100) { res++; } cout << res << endl; }
[ "33417830+tmyksj@users.noreply.github.com" ]
33417830+tmyksj@users.noreply.github.com
3bab011229b0581bad2f68d3f68b0952b2378c77
af75d3f56135742f48cd2607861a32033fd53980
/Complex类的成员函数.cpp
ce1b37ca547e90782506c82714b12fa6d24ed38b
[]
no_license
royalneverwin/Programming_Practice
0f5f6ec570cba6ce16a4b7bb47206f50c1ecdbeb
c617efa2cf2b82ecbeda8f4b7e74470015c38bb0
refs/heads/main
2023-06-08T21:31:32.333734
2021-07-04T02:27:18
2021-07-04T02:27:18
350,348,227
6
0
null
null
null
null
UTF-8
C++
false
false
640
cpp
#include <iostream> #include <cstring> #include <cstdlib> using namespace std; class Complex { private: double r,i; public: void Print() { cout << r << "+" << i << "i" << endl; } Complex & operator = (const char *s){ char sCopy[10]; char *start = sCopy; strcpy(sCopy, s); char *tmp = strchr(start, '+'); *tmp = '\0'; r = atof(start); start = tmp + 1; tmp = strchr(start, 'i'); *tmp = '\0'; i = atof(start); return *this; } }; int main() { Complex a; a = "3+4i"; a.Print(); a = "5+6i"; a.Print(); return 0; }
[ "55973858+royalneverwin@users.noreply.github.com" ]
55973858+royalneverwin@users.noreply.github.com
692743110f5e087a337162a72ee42c339ececea4
cdc72c5fa1123401c92bf42680297d591d6f7481
/hw11/hidtest.cpp
69e7e57d0698fbd65ac4cddb30483045fce5fcba
[]
no_license
ritwik1993/me433_homework
af53f2643e87bcc37778deffb364b7799edbed84
ba15461a032713ff9d300ad78b87cc91347a1395
refs/heads/master
2020-12-11T01:38:13.669994
2015-06-10T20:23:14
2015-06-10T20:23:14
33,282,942
0
0
null
null
null
null
UTF-8
C++
false
false
1,633
cpp
#ifdef WIN32 #include <windows.h> #endif #include <stdio.h> #include <string.h> #include <stdlib.h> #include "hidapi.h" #define MAX_STR 255 int main(int argc, char* argv[]) { int res; unsigned char buf[65]; char message [50]; int row; wchar_t wstr[MAX_STR]; hid_device *handle; int i=0; short ax[1000],ay[1000], az[1000]; // Initialize the hidapi library res = hid_init(); // Open the device using the VID, PID, // and optionally the Serial number. handle = hid_open(0x4d8, 0x3f, NULL); printf("Enter the Row number: \n"); scanf("%d", &row); printf("Enter the String: \n"); scanf("%s",message); for (i = 0; i < 50; i++) { buf[i+3] = message[i]; } buf[0] = 0x0; buf[1] = 0x82; buf[2] = row; res = hid_write(handle, buf, 65); printf("Now entering Accelerometer mode \n"); buf[0] = 0x0; buf[1] = 0x85; //start counting buf[2] = row; res = hid_write(handle, buf, 65); i=0; // Request state (cmd 0x83). Start accelerometer mode. while (i<1000) { buf[0] = 0x0; buf[1] = 0x83; res = hid_write(handle, buf, 65); // Read requested state res = hid_read(handle, buf, 65); if(buf[0]==1) { ax[i] = buf[1] << 8 | buf[2]; ay[i] = buf[3] << 8 | buf[4]; az[i] = buf[5] << 8 | buf[6]; printf("X: %d Y: %d Z: %d \n",ax[i],ay[i],az[i]); i++; } } printf("Accelerometer read successfully.\n"); FILE *ofp; ofp = fopen("acc_data_1.txt","w"); fprintf(ofp,"Raw MAF FIR\n"); for(i = 0; i < 1000; i++){ fprintf(ofp,"%d %d %d\r\n",ax[i],ay[i],az[i]); } fclose(ofp); // Finalize the hidapi library res = hid_exit(); return 0; }
[ "ritwik1993@gmail.com" ]
ritwik1993@gmail.com
d31577a2a20a75c17a57176097628ee89825d637
78bd0a479738903371b88c75625278a668907521
/audibot/audibot_gazebo/src/AudibotInterfacePlugin.cpp
a2022614bad46a32fac593dbb87bb79f41f063ef
[ "BSD-2-Clause" ]
permissive
TorBorve/Navigation
8e6f8eaa5d9c091f41644e679a1e68aab760f789
ea644021943222f8f112e22e2daf01148246b03b
refs/heads/master
2023-07-28T21:59:39.035191
2021-09-14T16:39:10
2021-09-14T16:39:10
369,610,517
2
0
null
null
null
null
UTF-8
C++
false
false
11,043
cpp
#include <audibot_gazebo/AudibotInterfacePlugin.h> namespace gazebo { AudibotInterfacePlugin::AudibotInterfacePlugin() { target_angle_ = 0.0; brake_cmd_ = 0.0; throttle_cmd_ = 0.0; gear_cmd_ = DRIVE; current_steering_angle_ = 0.0; rollover_ = false; } void AudibotInterfacePlugin::Load(physics::ModelPtr model, sdf::ElementPtr sdf) { // Gazebo initialization steer_fl_joint_ = model->GetJoint("steer_fl_joint"); steer_fr_joint_ = model->GetJoint("steer_fr_joint"); wheel_rl_joint_ = model->GetJoint("wheel_rl_joint"); wheel_rr_joint_ = model->GetJoint("wheel_rr_joint"); wheel_fl_joint_ = model->GetJoint("wheel_fl_joint"); wheel_fr_joint_ = model->GetJoint("wheel_fr_joint"); footprint_link_ = model->GetLink("base_footprint"); front_axle_link_ = model->GetLink("front_axle"); if (front_axle_link_ == nullptr){ ROS_ERROR("front_axle_link_ == nullptr"); } // Load SDF parameters if (sdf->HasElement("pubTf")) { sdf->GetElement("pubTf")->GetValue()->Get(pub_tf_); } else { pub_tf_ = false; } if (sdf->HasElement("robotName")) { sdf::ParamPtr sdf_robot_name = sdf->GetElement("robotName")->GetValue(); if (sdf_robot_name) { sdf_robot_name->Get(robot_name_); } else { robot_name_ = std::string(""); } } else { robot_name_ = std::string(""); } if (sdf->HasElement("tfFreq")) { sdf->GetElement("tfFreq")->GetValue()->Get(tf_freq_); } else { tf_freq_ = 100.0; } update_connection_ = event::Events::ConnectWorldUpdateBegin(boost::bind(&AudibotInterfacePlugin::OnUpdate, this, _1)); steer_fl_joint_->SetParam("fmax", 0, 99999.0); steer_fr_joint_->SetParam("fmax", 0, 99999.0); // ROS initialization n_ = new ros::NodeHandle(robot_name_); sub_steering_cmd_ = n_->subscribe("steering_cmd", 1, &AudibotInterfacePlugin::recvSteeringCmd, this); sub_brake_cmd_ = n_->subscribe("brake_cmd", 1, &AudibotInterfacePlugin::recvBrakeCmd, this); sub_throttle_cmd_ = n_->subscribe("throttle_cmd", 1, &AudibotInterfacePlugin::recvThrottleCmd, this); sub_gear_cmd_ = n_->subscribe("gear_cmd", 1, &AudibotInterfacePlugin::recvGearCmd, this); pub_twist_ = n_->advertise<geometry_msgs::TwistStamped> ("twist", 1); pub_gear_state_ = n_->advertise<std_msgs::UInt8> ("gear_state", 1); pub_odom_ = n_->advertise<nav_msgs::Odometry>("odom", 1); feedback_timer_ = n_->createTimer(ros::Duration(0.02), &AudibotInterfacePlugin::feedbackTimerCallback, this); if (pub_tf_) { tf_timer_ = n_->createTimer(ros::Duration(1.0 / tf_freq_), &AudibotInterfacePlugin::tfTimerCallback, this); } if (robot_name_.empty()) { frame_id_ = footprint_link_->GetName(); } else { frame_id_ = robot_name_ + "/" + footprint_link_->GetName(); } } void AudibotInterfacePlugin::OnUpdate(const common::UpdateInfo& info) { if (last_update_time_ == common::Time(0)) { last_update_time_ = info.simTime; return; } twistStateUpdate(); driveUpdate(); steeringUpdate(info); dragUpdate(); } void AudibotInterfacePlugin::twistStateUpdate() { #if GAZEBO_MAJOR_VERSION >= 9 world_pose_ = footprint_link_->WorldPose(); front_pose_ = front_axle_link_->WorldPose(); twist_.linear.x = footprint_link_->RelativeLinearVel().X(); twist_.angular.z = footprint_link_->RelativeAngularVel().Z(); rollover_ = (fabs(world_pose_.Rot().X()) > 0.2 || fabs(world_pose_.Rot().Y()) > 0.2); #else world_pose_ = footprint_link_->GetWorldPose(); front_pose_ = front_axle_link_->GetWorldPose(); twist_.linear.x = footprint_link_->GetRelativeLinearVel().x; twist_.angular.z = footprint_link_->GetRelativeAngularVel().z; rollover_ = (fabs(world_pose_.rot.x) > 0.2 || fabs(world_pose_.rot.y) > 0.2); #endif } void AudibotInterfacePlugin::driveUpdate() { // Stop wheels if vehicle is rolled over if (rollover_) { stopWheels(); return; } // Brakes have precedence over throttle ros::Time current_stamp = ros::Time::now(); if ((brake_cmd_ > 0) && ((current_stamp - brake_stamp_).toSec() < 0.25)) { double brake_torque_factor = 1.0; if (twist_.linear.x < -0.1) { brake_torque_factor = -1.0; } else if (twist_.linear.x < 0.1) { brake_torque_factor = 1.0 + (twist_.linear.x - 0.1) / 0.1; } setAllWheelTorque(-brake_torque_factor * brake_cmd_); } else { if ((current_stamp - throttle_stamp_).toSec() < 0.25) { double throttle_torque; if (gear_cmd_ == DRIVE) { throttle_torque = throttle_cmd_ * 4000.0 - 40.1 * twist_.linear.x; if (throttle_torque < 0.0) { throttle_torque = 0.0; } } else { // REVERSE throttle_torque = -throttle_cmd_ * 4000.0 - 250.0 * twist_.linear.x; if (throttle_torque > 0.0) { throttle_torque = 0.0; } } setRearWheelTorque(throttle_torque); } } } void AudibotInterfacePlugin::steeringUpdate(const common::UpdateInfo& info) { double time_step = (info.simTime - last_update_time_).Double(); last_update_time_ = info.simTime; // Arbitrarily set maximum steering rate to 800 deg/s const double max_rate = 800.0 * M_PI / 180.0 / AUDIBOT_STEERING_RATIO; double max_inc = time_step * max_rate; if ((target_angle_ - current_steering_angle_) > max_inc) { current_steering_angle_ += max_inc; } else if ((target_angle_ - current_steering_angle_) < -max_inc) { current_steering_angle_ -= max_inc; } // Compute Ackermann steering angles for each wheel double t_alph = tan(current_steering_angle_); double left_steer = atan(AUDIBOT_WHEELBASE * t_alph / (AUDIBOT_WHEELBASE - 0.5 * AUDIBOT_TRACK_WIDTH * t_alph)); double right_steer = atan(AUDIBOT_WHEELBASE * t_alph / (AUDIBOT_WHEELBASE + 0.5 * AUDIBOT_TRACK_WIDTH * t_alph)); #if GAZEBO_MAJOR_VERSION >= 9 steer_fl_joint_->SetParam("vel", 0, 100.0 * (left_steer - steer_fl_joint_->Position(0))); steer_fr_joint_->SetParam("vel", 0, 100.0 * (right_steer - steer_fr_joint_->Position(0))); #else steer_fl_joint_->SetParam("vel", 0, 100.0 * (left_steer - steer_fl_joint_->GetAngle(0).Radian())); steer_fr_joint_->SetParam("vel", 0, 100.0 * (right_steer - steer_fr_joint_->GetAngle(0).Radian())); #endif } void AudibotInterfacePlugin::dragUpdate() { // Apply rolling resistance and aerodynamic drag forces double rolling_resistance_torque = ROLLING_RESISTANCE_COEFF * VEHICLE_MASS * GRAVITY_ACCEL; double drag_force = AERO_DRAG_COEFF * twist_.linear.x * twist_.linear.x; double drag_torque = drag_force * WHEEL_RADIUS; // Implement aerodynamic drag as a torque disturbance if (twist_.linear.x > 0.0) { setAllWheelTorque(-rolling_resistance_torque); setAllWheelTorque(-drag_torque); } else { setAllWheelTorque(rolling_resistance_torque); setAllWheelTorque(drag_torque); } } void AudibotInterfacePlugin::setAllWheelTorque(double torque) { wheel_rl_joint_->SetForce(0, 0.25 * torque); wheel_rr_joint_->SetForce(0, 0.25 * torque); wheel_fl_joint_->SetForce(0, 0.25 * torque); wheel_fr_joint_->SetForce(0, 0.25 * torque); } void AudibotInterfacePlugin::setRearWheelTorque(double torque) { wheel_rl_joint_->SetForce(0, 0.5 * torque); wheel_rr_joint_->SetForce(0, 0.5 * torque); } void AudibotInterfacePlugin::stopWheels() { wheel_fl_joint_->SetForce(0, -1000.0 * wheel_fl_joint_->GetVelocity(0)); wheel_fr_joint_->SetForce(0, -1000.0 * wheel_fr_joint_->GetVelocity(0)); wheel_rl_joint_->SetForce(0, -1000.0 * wheel_rl_joint_->GetVelocity(0)); wheel_rr_joint_->SetForce(0, -1000.0 * wheel_rr_joint_->GetVelocity(0)); } void AudibotInterfacePlugin::recvSteeringCmd(const std_msgs::Float64ConstPtr& msg) { if (!std::isfinite(msg->data)) { target_angle_ = 0.0; return; } target_angle_ = msg->data / AUDIBOT_STEERING_RATIO; if (target_angle_ > AUDIBOT_MAX_STEER_ANGLE) { target_angle_ = AUDIBOT_MAX_STEER_ANGLE; } else if (target_angle_ < -AUDIBOT_MAX_STEER_ANGLE) { target_angle_ = -AUDIBOT_MAX_STEER_ANGLE; } } void AudibotInterfacePlugin::recvBrakeCmd(const std_msgs::Float64ConstPtr& msg) { brake_cmd_ = msg->data; if (brake_cmd_ < 0) { brake_cmd_ = 0; } else if (brake_cmd_ > MAX_BRAKE_TORQUE) { brake_cmd_ = MAX_BRAKE_TORQUE; } brake_stamp_ = ros::Time::now(); } void AudibotInterfacePlugin::recvThrottleCmd(const std_msgs::Float64ConstPtr& msg) { throttle_cmd_ = msg->data; if (throttle_cmd_ < 0.0) { throttle_cmd_ = 0.0; } else if (throttle_cmd_ > 1.0) { throttle_cmd_ = 1.0; } throttle_stamp_ = ros::Time::now(); } void AudibotInterfacePlugin::recvGearCmd(const std_msgs::UInt8ConstPtr& msg) { if (msg->data > REVERSE) { ROS_WARN("Invalid gear command received [%u]", msg->data); } else { gear_cmd_ = msg->data; } } void AudibotInterfacePlugin::feedbackTimerCallback(const ros::TimerEvent& event) { geometry_msgs::TwistStamped twist_msg; twist_msg.header.frame_id = frame_id_; twist_msg.header.stamp = event.current_real; twist_msg.twist = twist_; pub_twist_.publish(twist_msg); std_msgs::UInt8 gear_state_msg; gear_state_msg.data = gear_cmd_; pub_gear_state_.publish(gear_state_msg); // added odom publisher. nav_msgs::Odometry odom_msg; odom_msg.header.frame_id = "front_axle"; odom_msg.header.stamp = event.current_real; odom_msg.twist.twist = twist_; odom_msg.pose.pose.position.x = front_pose_.Pos().X(); odom_msg.pose.pose.position.y = front_pose_.Pos().Y(); odom_msg.pose.pose.position.z = front_pose_.Pos().Z(); odom_msg.pose.pose.orientation.x = front_pose_.Rot().X(); odom_msg.pose.pose.orientation.y = front_pose_.Rot().Y(); odom_msg.pose.pose.orientation.z = front_pose_.Rot().Z(); odom_msg.pose.pose.orientation.w = front_pose_.Rot().W(); pub_odom_.publish(odom_msg); } void AudibotInterfacePlugin::tfTimerCallback(const ros::TimerEvent& event) { // Don't publish TF if the same timestamp as last time // to prevent TF_REPEATED_DATA warning if ((event.current_real - event.last_real).toSec() < 1e-6) { return; } geometry_msgs::TransformStamped t; t.header.frame_id = "odom"; t.child_frame_id = frame_id_; t.header.stamp = event.current_real; #if GAZEBO_MAJOR_VERSION >= 9 t.transform.translation.x = world_pose_.Pos().X(); t.transform.translation.y = world_pose_.Pos().Y(); t.transform.translation.z = world_pose_.Pos().Z(); t.transform.rotation.w = world_pose_.Rot().W(); t.transform.rotation.x = world_pose_.Rot().X(); t.transform.rotation.y = world_pose_.Rot().Y(); t.transform.rotation.z = world_pose_.Rot().Z(); #else t.transform.translation.x = world_pose_.pos.x; t.transform.translation.y = world_pose_.pos.y; t.transform.translation.z = world_pose_.pos.z; t.transform.rotation.w = world_pose_.rot.w; t.transform.rotation.x = world_pose_.rot.x; t.transform.rotation.y = world_pose_.rot.y; t.transform.rotation.z = world_pose_.rot.z; #endif br_.sendTransform(t); } void AudibotInterfacePlugin::Reset() { } AudibotInterfacePlugin::~AudibotInterfacePlugin() { n_->shutdown(); delete n_; } }
[ "rasmustor18@gmail.com" ]
rasmustor18@gmail.com
beb56fb6c2965061f3413c651fe5334973da9e68
fdb63531719c0bf9e4c4593bf7e55ffc0936a93e
/09. Linked List/06. Unfold a folded LL.cpp
690a476f95797ccab96d57a77ec1a0ce20d0133f
[]
no_license
ashishmohapatra2703/DSA-practice-questions
aec9ca4aa4e619dd5f754088f87fdf142f4049a5
791f84fa01fb3156cb0e77da09428eb0b38649d8
refs/heads/master
2023-08-16T05:54:33.627700
2021-10-17T17:26:28
2021-10-17T17:26:28
367,565,132
2
0
null
null
null
null
UTF-8
C++
false
false
1,531
cpp
/*A linked list L0 -> L1 -> L2 -> ….. -> LN can be folded as L0 -> LN -> L1 -> LN – 1 -> L2 -> ….. Given a folded linked list, the task is to unfold and print the original linked list Input: 1 -> 6 -> 2 -> 5 -> 3 -> 4 Output: 1 2 3 4 5 6 Input: 1 -> 5 -> 2 -> 4 -> 3 Output: 1 2 3 4 5 */ ListNode* reverseList(ListNode* head) { if(head==nullptr || head->next==nullptr) //length 0 or 1 return head; ListNode* forward = head; ListNode* current = nullptr; ListNode* previous = nullptr; while(forward != nullptr) { previous = current; current = forward; forward = forward->next; current->next = previous; } return head = current; } void unfold(ListNode* head) { if(head==NULL || head->next==NULL) return; ListNode* head1 = head; ListNode* head2 = head->next; ListNode* current1 = NULL; ListNode* forward1 = head1; ListNode* current2 = NULL; ListNode* forward2 = head2; //terminating condition for odd and even length LL respectively. while(forward2!= NULL && forward2->next!=NULL) { current1 = forward1; forward1 = forward1->next->next; current1->next = forward1; current2 = forward2; forward2 = forward2->next->next; current2->next = forward2; } forward1->next = NULL; //breaking the link of 2 halves head2 = reverseList(head2); forward1->next = head2; }
[ "ashishmohapatra2000@gmail.com" ]
ashishmohapatra2000@gmail.com
e2baa5b086d369c12c29ceb421c5643bde791263
8f27ca75187c121d9a815b00517175bc523f1801
/Plugins/Voxel/Source/Voxel/Private/VoxelGraph/VoxelComputeNodeTree.cpp
8e860ec139e76dfd7fba5b9b79826870da5b69e2
[ "MIT" ]
permissive
Maverrin/FirstGame
9991e84df316fef6afe7606b29d01f1eb8c375de
9ff0eeb0948a4f223d31e03b2cbf35a955db9e9e
refs/heads/master
2022-05-09T17:45:15.904563
2019-11-08T18:14:45
2019-11-08T18:14:45
null
0
0
null
null
null
null
UTF-8
C++
false
false
7,618
cpp
// Copyright 2018 Phyronnaz #include "VoxelGraph/VoxelComputeNodeTree.h" #include "VoxelGraph/VoxelNode.h" #include "VoxelGraph/VoxelCppConstructor.h" #include "VoxelGraph/VoxelNodeDefinitions.h" #include "VoxelGraph/VoxelGraphWorldGenerator.h" #include "VoxelMaterial.h" #include "VoxelGlobals.h" FVoxelGraphPerfCounter FVoxelGraphPerfCounter::Singleton; FCriticalSection FVoxelGraphPerfCounter::Section; inline FVoxelGraphPerfCounter* GetThreadPerfCounter() { VOXEL_THREADLOCAL FVoxelGraphPerfCounter Counter; return &Counter; }; struct FVoxelScopePerfCounter { FVoxelScopePerfCounter(const TSharedPtr<FVoxelComputeNode>& Node) : Start(FPlatformTime::Cycles64()) , Node(Node->SourceNode) { } ~FVoxelScopePerfCounter() { uint64 Elapsed = FPlatformTime::Cycles64() - Start; GetThreadPerfCounter()->LogNode(Node, Elapsed); } private: const uint64 Start; const UVoxelNode* const Node; }; #if ENABLE_VOXELGRAPH_CHECKS #define checkDev(...) check(__VA_ARGS__) #else #define checkDev(...) #endif inline void CopyVariablesToInputs(const TSharedPtr<FVoxelComputeNode>& Node, FVoxelNodeType Variables[], FVoxelNodeType InputBuffer[]) { for (int InputIndex = 0; InputIndex < Node->InputCount; InputIndex++) { int32 Id = Node->GetInputId(InputIndex); if (Id == -1) { checkDev(0 <= InputIndex && InputIndex < MAX_PINS); InputBuffer[InputIndex] = Node->GetDefaultValue(InputIndex); } else { checkDev(0 <= InputIndex && InputIndex < MAX_PINS); checkDev(0 <= Id && Id < MAX_VARIABLES); InputBuffer[InputIndex] = Variables[Id]; } } } inline void CopyOutputsToVariables(const TSharedPtr<FVoxelComputeNode>& Node, FVoxelNodeType Variables[], FVoxelNodeType OutputBuffer[]) { for (int OutputIndex = 0; OutputIndex < Node->OutputCount; OutputIndex++) { int Id = Node->GetOutputId(OutputIndex); checkDev(0 <= OutputIndex && OutputIndex < MAX_PINS); checkDev(0 <= Id && Id < MAX_VARIABLES); Variables[Id] = OutputBuffer[OutputIndex]; } } void FVoxelComputeNodeTree::Init(FVoxelNodeType Variables[], FVoxelNodeType InputOutputBuffer[], const FVoxelWorldGeneratorInit& InitStruct) const { FVoxelNodeType* InputBuffer = GetInputBuffer(InputOutputBuffer); FVoxelNodeType* OutputBuffer = GetOutputBuffer(InputOutputBuffer); for (auto& Node : Nodes) { if (!Node->IsInit()) { CopyVariablesToInputs(Node, Variables, InputBuffer); Node->CallInit(InputBuffer, OutputBuffer, InitStruct); CopyOutputsToVariables(Node, Variables, OutputBuffer); } } for (auto& Child : Children) { Child.Init(Variables, InputOutputBuffer, InitStruct); } } void FVoxelComputeNodeTree::Compute(FVoxelNodeType Variables[], FVoxelNodeType InputOutputBuffer[], const FVoxelContext& Context, float& Value, FVoxelMaterial& Material) const { FVoxelNodeType* InputBuffer = GetInputBuffer(InputOutputBuffer); FVoxelNodeType* OutputBuffer = GetOutputBuffer(InputOutputBuffer); if (bEnableStats) { ComputeInternal<true>(Variables, InputBuffer, OutputBuffer, Context, Value, Material); } else { ComputeInternal<false>(Variables, InputBuffer, OutputBuffer, Context, Value, Material); } } template<bool bTEnableStats> void FVoxelComputeNodeTree::ComputeInternal(FVoxelNodeType Variables[], FVoxelNodeType InputBuffer[], FVoxelNodeType OutputBuffer[], const FVoxelContext& Context, float& Value, FVoxelMaterial& Material) const { for (auto& Node : Nodes) { CopyVariablesToInputs(Node, Variables, InputBuffer); if (bTEnableStats) { FVoxelScopePerfCounter Counter(Node); Node->Compute(InputBuffer, OutputBuffer, Context); } else { Node->Compute(InputBuffer, OutputBuffer, Context); } CopyOutputsToVariables(Node, Variables, OutputBuffer); } if (BranchNode.IsValid()) { CopyVariablesToInputs(BranchNode, Variables, InputBuffer); int32 BranchId = BranchNode->ComputeExecNode(InputBuffer, Value, Material); Children[BranchId].ComputeInternal<bTEnableStats>(Variables, InputBuffer, OutputBuffer, Context, Value, Material); } } void FVoxelComputeNodeTree::SetupConstructor(FVoxelCppConstructor& Constructor) const { for (auto& Node : Nodes) { if (!Node->IsConstructorSetup()) { Node->CallSetupConstructor(Constructor); } } for (auto& Child : Children) { Child.SetupConstructor(Constructor); } } /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// inline void SetComputeNodeInputsCpp(const TSharedPtr<FVoxelComputeNode>& Node, FVoxelCppConstructor& Constructor, TArray<FString>& Inputs) { for (int InputIndex = 0; InputIndex < Node->InputCount; InputIndex++) { int32 Id = Node->GetInputId(InputIndex); if (Id == -1) { Inputs[InputIndex] = Node->GetDefaultValueString(InputIndex); } else { Inputs[InputIndex] = Constructor.GetLocalVariableName(Id); } } } inline void SetComputeNodeOutputsCpp(const TSharedPtr<FVoxelComputeNode>& Node, FVoxelCppConstructor& Constructor, TArray<FString>& Outputs) { for (int OutputIndex = 0; OutputIndex < Node->OutputCount; OutputIndex++) { Outputs[OutputIndex] = Constructor.GetLocalVariableName(Node->GetOutputId(OutputIndex)); } } void FVoxelComputeNodeTree::InitCpp(FVoxelCppConstructor& Constructor) const { TArray<FString> Inputs; TArray<FString> Outputs; Inputs.SetNum(MAX_PINS); Outputs.SetNum(MAX_PINS); for (auto& Node : Nodes) { if (!Node->IsInit()) { Constructor.QueueComment("// Init of " + Node->Name); { SetComputeNodeInputsCpp(Node, Constructor, Inputs); SetComputeNodeOutputsCpp(Node, Constructor, Outputs); Node->CallInitCpp(Inputs, Outputs, Constructor); } Constructor.EndComment(); } } for (auto& Child : Children) { Child.InitCpp(Constructor); } } void FVoxelComputeNodeTree::ComputeCpp(FVoxelCppConstructor& Constructor) { for (auto& Node : Nodes) { TArray<FString> Inputs; TArray<FString> Outputs; Inputs.SetNum(Node->InputCount); Outputs.SetNum(Node->OutputCount); Constructor.QueueComment("// " + Node->Name); { SetComputeNodeInputsCpp(Node, Constructor, Inputs); SetComputeNodeOutputsCpp(Node, Constructor, Outputs); Node->ComputeCpp(Inputs, Outputs, Constructor); } Constructor.EndComment(); } if (BranchNode.IsValid()) { TArray<FString> Inputs; TArray<FString> Outputs; Inputs.SetNum(BranchNode->InputCount); Outputs.SetNum(BranchNode->OutputCount); Constructor.QueueComment("// " + BranchNode->Name); SetComputeNodeInputsCpp(BranchNode, Constructor, Inputs); FString BranchResult; FVoxelComputeNode::EExecKind Kind = BranchNode->ComputeExecNodeCpp(Inputs, BranchResult, Constructor); Constructor.EndComment(); bool bIsIf = Kind == FVoxelComputeNode::EExecKind::If; check(bIsIf || Kind == FVoxelComputeNode::EExecKind::Passthrough); check((bIsIf && Children.Num() == 2) || (!bIsIf && Children.Num() == 1)); if (bIsIf) { Constructor.AddLine("if(" + BranchResult + ")"); Constructor.AddLine("{"); Constructor.Indent(); Children[0].ComputeCpp(Constructor); Constructor.Unindent(); Constructor.AddLine("}"); Constructor.AddLine("else"); Constructor.AddLine("{"); Constructor.Indent(); Children[1].ComputeCpp(Constructor); Constructor.Unindent(); Constructor.AddLine("}"); } else if (Children[0].BranchNode.IsValid()) { Constructor.AddLine("{"); Constructor.Indent(); Children[0].ComputeCpp(Constructor); Constructor.Unindent(); Constructor.AddLine("}"); } } } #undef checkDev
[ "eigrads@hotmail.com" ]
eigrads@hotmail.com
acc158aebb20cde39d1f44eb786d890a6d3a1d72
c9e0227c3958db89747488328bd2b255e54f008f
/solutions/0772. Basic Calculator III/0772.cpp
b5409fb5467067e44694d286cdf7d7666a3e0392
[]
no_license
XkhldY/LeetCode
2deba28b7491c36b4f224c3132fb89feea318832
94e23db2668615d9fe09e129a96c22ae4e83b9c8
refs/heads/main
2023-04-03T08:17:30.743071
2021-04-14T23:34:03
2021-04-14T23:34:03
358,136,537
1
0
null
2021-04-15T05:20:21
2021-04-15T05:20:21
null
UTF-8
C++
false
false
1,650
cpp
class Solution { public: int calculate(string s) { stack<long> nums; // stores nums stack<char> ops; // stores operators and parentheses for (int i = 0; i < s.length(); ++i) { const char c = s[i]; if (isdigit(c)) { long num = c - '0'; while (i + 1 < s.length() && isdigit(s[i + 1])) { num = num * 10 + (s[i + 1] - '0'); ++i; } nums.push(num); } else if (c == '(') { ops.push(c); } else if (c == ')') { while (ops.top() != '(') nums.push(calculate(pop(ops), pop(nums), pop(nums))); ops.pop(); // remove '(' } else if (c == '+' || c == '-' || c == '*' || c == '/') { while (!ops.empty() && compare(ops.top(), c)) nums.push(calculate(pop(ops), pop(nums), pop(nums))); ops.push(c); } } while (!ops.empty()) nums.push(calculate(pop(ops), pop(nums), pop(nums))); return nums.top(); } private: long calculate(char op, long b, long a) { switch (op) { case '+': return a + b; case '-': return a - b; case '*': return a * b; case '/': return a / b; } throw; } // return true if op1 is a operator and priority(op1) >= priority(op2) bool compare(char op1, char op2) { if (op1 == '(' || op1 == ')') return false; return op1 == '*' || op1 == '/' || op2 == '+' || op2 == '-'; } char pop(stack<char>& ops) { const char op = ops.top(); ops.pop(); return op; } long pop(stack<long>& nums) { const long num = nums.top(); nums.pop(); return num; } };
[ "walkccray@gmail.com" ]
walkccray@gmail.com
242ad6f8710ef7fd34b346cd25fdf76c6f9d7900
dae6d556da61e025fbe94feb677c93cc8e374e2f
/stlsrc/template_stl/ch11/count.cpp
cbd86c16ef10fccc0a1cafb186676fc10cf43875
[]
no_license
yaoxiaokui/linux_ever
bb72344a36efeb4fb42d88d06eeeb1a7a43d651d
a654e5fb8d14a2bf7049c16d41c5b13b5bfd9285
refs/heads/master
2020-05-22T04:10:15.091175
2018-01-07T03:09:23
2018-01-07T03:09:23
49,123,522
3
0
null
null
null
null
UTF-8
C++
false
false
497
cpp
/************************************************************************* > File Name: count.cpp > Author: > Mail: > Created Time: 2016年01月09日 星期六 22时49分44秒 ************************************************************************/ #include <iostream> #include <algorithm> using namespace std; int main() { int A[] = {2, 0, 4, 6, 0, 3, 1, -7}; const int N = sizeof(A)/sizeof(int); cout << "Number of zeros: " << count(A, A+N, 0) << endl; return 0; }
[ "529188712@qq.com" ]
529188712@qq.com
49f56346fef88030e9ff7a761e66775186915057
9ed894c032c605af64fb4587ea4113a3256c42b0
/src/usr/htmgt/htmgt_occcmd.H
a75dd55286f64b5bc1d240729f8f551de21e9cf1
[ "Apache-2.0" ]
permissive
MikeJi/hostboot
6d89436d924463766caac8844eecb67ce123c58f
66921b4bc0df457e3ea44b804c8450b3d120e3b7
refs/heads/master
2020-12-01T01:18:22.187877
2015-09-09T15:53:36
2015-09-11T18:37:57
39,750,285
1
0
null
2015-07-27T02:06:22
2015-07-27T02:06:22
null
UTF-8
C++
false
false
10,701
h
/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/usr/htmgt/htmgt_occcmd.H $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2014,2015 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ #ifndef HTMGT_OCCCMD_H #define HTMGT_OCCCMD_H #include "htmgt_utility.H" #include "htmgt_activate.H" #include "htmgt_occ.H" #include <stdint.h> #include <errl/errlmanager.H> namespace HTMGT { const uint32_t OCC_CMD_ADDR = 0x001EE000; const uint32_t OCC_RSP_ADDR = 0x001EF000; const uint32_t OCC_MAX_DATA_LENGTH = 0x00001000; const uint32_t OCC_RSP_SRAM_ADDR = 0xFFFF7000; // The following header lengths include the 2 byte checksum const uint16_t OCC_CMD_HDR_LENGTH = 6; const uint16_t OCC_RSP_HDR_LENGTH = 7; enum occReturnCodes { OCC_RC_SUCCESS = 0x00, OCC_RC_INVALID_COMMAND = 0x11, OCC_RC_INVALID_COMMAND_LENGTH = 0x12, OCC_RC_INVALID_DATA_FIELD = 0x13, OCC_RC_CHECKSUM_FAILURE = 0x14, OCC_RC_INTERNAL_ERROR = 0x15, OCC_RC_PRESENT_STATE_PROHIBITS = 0x16, // 0xE0-EF are reserved for OCC exceptions on command timeouts // TMGT should collect all the data in the response as FFDC OCC_RC_OCC_EXCEPTION = 0xE0, OCC_RC_OCC_INIT_CHECKPOINT = 0xE1, OCC_RC_OCC_WATCHDOG_TIMEOUT = 0xE2, OCC_RC_OCC_TIMEOUT = 0xE3, OCC_RC_OCC_HW_ERROR = 0xE4, OCC_RC_OCC_EXCEPTION_RESERVED = 0xEF, OCC_COMMAND_IN_PROGRESS = 0xFF }; enum occCommandType { OCC_CMD_POLL = 0x00, OCC_CMD_CLEAR_ERROR_LOG = 0x12, OCC_CMD_SET_STATE = 0x20, OCC_CMD_SETUP_CFG_DATA = 0x21, OCC_CMD_SET_POWER_CAP = 0x22, OCC_CMD_RESET_PREP = 0x25, OCC_CMD_GET_FIELD_DEBUG_DATA = 0x42, OCC_CMD_END_OF_TABLE = 0xFF }; enum occResetReasonType { OCC_RESET_CMD_VERSION = 0x00, OCC_RESET_NON_FAILURE = 0x00, OCC_RESET_FAIL_THIS_OCC = 0x01, OCC_RESET_FAIL_OTHER_OCC = 0x02, }; enum occCheckRspLengthType { OCC_CHECK_RSP_LENGTH_NONE = 0x00, OCC_CHECK_RSP_LENGTH_EQUALS = 0x01, OCC_CHECK_RSP_LENGTH_GREATER = 0x02, }; enum occCmdTraceEnum { OCC_TRACE_NEVER = 0x00, OCC_TRACE_EXTENDED = 0x01, OCC_TRACE_CONDITIONAL = 0x02, OCC_TRACE_ALWAYS = 0x03, }; struct occCommandTable_t { occCommandType cmdType; uint8_t supported; occCheckRspLengthType checkRspLength; uint16_t rspLength; uint32_t timeout; uint16_t maxBytesRead; occCmdTraceEnum traceCmd; bool operator== (const occCommandType i_cmd) { return (cmdType == i_cmd); } }; struct occCommandStruct_t { uint8_t sequenceNumber; occCommandType cmdType; uint16_t dataLength; uint8_t cmdData[OCC_MAX_DATA_LENGTH]; uint16_t checksum; }; struct occResponseStruct_t { uint8_t sequenceNumber; occCommandType cmdType; occReturnCodes returnStatus; uint16_t dataLength; uint8_t rspData[OCC_MAX_DATA_LENGTH]; uint16_t checksum; }; /** * @class OccCmd * * @brief OCC Command handling class. * * @par Detailed Description: * Provides ability to build and send commands to the OCC and * process the responses returned by the OCC. */ class OccCmd { private: bool iv_RetryCmd; occCommandStruct_t iv_OccCmd; occResponseStruct_t iv_OccRsp; Occ * iv_Occ; static const occCommandTable_t cv_occCommandTable[]; /** * @brief Get the index of the specified command in the command * table * * @param[in] i_cmd OCC command type * * @note If command not found/invalid, index to END_OF_TABLE will * be returned and checked by caller * * @return index into command table */ uint8_t getCmdIndex(const occCommandType i_cmd); /** * @brief Write the full OCC command into HOMER (memory) including * checksum. */ uint16_t buildOccCmdBuffer(); /** * @brief Verify the status, checksum and length of the OCC * response. * * @return NULL on success, or errlHndl_t for any failure */ errlHndl_t checkOccResponse(); /** * @brief Parse the OCC response into the object and verify * lengths are valid. * * @return NULL on success, or errlHndl_t for any failure */ errlHndl_t parseOccResponse(); /** * @brief Create and commit error log from the exception data * in the response buffer. It is assumed that the OCC * response status is 0xE0-0xEF when called. */ void handleOccException(void); /** * @brief Send the command to the OCC * * @return NULL on success, or errlHndl_t for any failure */ errlHndl_t writeOccCmd(); /** * @brief Waits for the OCC response to be received * * @param[in] i_timeout max time to wait for response (in seconds) * * @return true if timeout was reached before good response, or * false if response was received within the timeout */ bool waitForOccRsp(uint32_t i_timeout); public: /** * @brief Constructor * * @param[in] i_occ target OCC for the command * @param[in] i_cmd OCC command to send * @param[in] i_dataLength Size of Data buffer (i_data) * @param[in] i_data Data buffer to send with command */ OccCmd(Occ * i_occ, const occCommandType i_cmd, const uint16_t i_dataLength, const uint8_t *i_data); /** * @brief Destructor */ ~OccCmd(); /** * @brief Send this command to the OCC * * @return NULL on success, or errlHndl_t for any failure */ errlHndl_t sendOccCmd(); /** * @brief Determine if the command needs to be traced and trace it * * @return true if the command was traced */ bool traceCommand(); /** * @brief Trace the response */ void traceResponse(); /** * @brief Process the OCC response and determine if a retry * is necessary (iv_retryCmd will be true if required) * * @param[in,out] io_errlHndl Error handle from sending command * and response error handle if failed * @param[in] i_traceRsp true if the response should be traced */ void processOccResponse(errlHndl_t & io_errlHndl, const bool i_traceRsp); /** * @brief Return the OCC response status from the response buffer * * @return OCC response status */ occReturnCodes getRspStatus() { return iv_OccRsp.returnStatus; } /** * @brief Return the data length from the OCC response * * @return OCC response data length */ uint16_t getRspLength() { return iv_OccRsp.dataLength; } /** * @brief Return a pointer to the response data and length * * @param[in,out] rsp_data pointer to the response data * * @return OCC response data length */ uint16_t getResponseData(uint8_t* & rsp_data) { rsp_data = iv_OccRsp.rspData; return iv_OccRsp.dataLength; } #ifdef SIMICS_TESTING /** * @brief Auto-responder for testing in simics * * @param[in] iOcc OCC target */ void fakeOccResponse(); #endif }; } // end namespace #endif
[ "iawillia@us.ibm.com" ]
iawillia@us.ibm.com
b95ca1128debcb112bfd201036c08fe7c8850049
f312cfa0890a97e9216da0ac7d3c942940a75bf6
/DisplayModule/Dialog.cpp
0e86a167a6b6b694e4bdbfcdae301c7c19f84af0
[]
no_license
andresviikmaa/FC-DipLoaf
b8af23ec4e374bc5d005ad7be6c97e6f6781f46b
d065176c552c4984667eea7a05cbbcd6728573b4
refs/heads/master
2021-01-13T13:31:16.507836
2016-12-12T09:09:11
2016-12-12T09:09:11
72,426,934
0
0
null
2016-11-30T10:55:00
2016-10-31T10:40:55
C++
UTF-8
C++
false
false
6,834
cpp
#include "Dialog.h" #include "opencv2/imgproc.hpp" /* #define WINDOW_WIDTH 976 #define WINDOW_HEIGHT 840 #define CAM_WIDTH 720 #define CAM_HEIGHT 720 */ Dialog::Dialog(const std::string &title, const cv::Size &ptWindowSize, const cv::Size &ptCamSize, int flags/* = CV_WINDOW_AUTOSIZE*/) : windowSize(ptWindowSize), camSize(ptCamSize), ThreadedClass("Dialog") { cv::Size windowSizeDefault = cv::Size(1024, 768); if (windowSize != cv::Size(0, 0)) { double scale = (double)windowSize.width / (double)windowSizeDefault.width; camSize = cv::Size((int)((double)camSize.width * scale), (int)((double)camSize.height * scale)); } else { windowSize = cv::Size((int)((double)camSize.width / 0.7), (int)((double)camSize.width / 0.7)); } fontScale = (double)windowSize.height / 1024; m_title = title; int baseLine; m_buttonHeight = cv::getTextSize("Ajig6", cv::FONT_HERSHEY_DUPLEX, fontScale, 1, &baseLine).height * 2; /* m_buttonHeight = cv::getTextSize("Ajig6", cv::FONT_HERSHEY_DUPLEX, fontScale, 1, &baseLine).height * 2; cv::namedWindow(m_title, CV_WINDOW_AUTOSIZE); //cvSetWindowProperty(m_title.c_str(), CV_WND_PROP_FULLSCREEN, CV_WINDOW_FULLSCREEN); cv::moveWindow(m_title, 0, 0); cv::setMouseCallback(m_title, [](int event, int x, int y, int flags, void* self) { for (auto pListener : ((Dialog*)self)->m_EventListeners){ if (pListener->OnMouseEvent(event, (float)x / ((Dialog*)self)->camSize.x, (float)y / ((Dialog*)self)->camSize.y, flags)) { return; // event was handled } } ((Dialog*)self)->mouseX = x; ((Dialog*)self)->mouseY = y; if (event == cv::EVENT_LBUTTONUP){ ((Dialog*)self)->mouseClicked(x, y); } }, this); */ display_empty = cv::Mat(windowSize, CV_8UC3, cv::Scalar(0)); display = cv::Mat(windowSize, CV_8UC3, cv::Scalar(0)); Start(); }; Dialog::~Dialog(){ stop_thread = true; WaitForStop(); } void Dialog::ShowImage(const std::string &window, const cv::Mat &image, bool flip){ boost::mutex::scoped_lock lock(display_mutex); //allow one command at a time if (image.size().width == 0) { display.setTo(cv::Scalar(127, 255, 127)); std::cout << "empty image: " << window << std::endl; return; } if (windows.size() == 0){ activeWindow = window; } if (windows.find(window) == windows.end()) { std::string name(window); createButton(name, '-', [&, name]{ activeWindow = name; }); windows.insert(name); } if (window == activeWindow){ image.copyTo(display); camSize = image.size(); //resize(image, display, display.size()); } } void Dialog::ShowImage(const cv::Mat &image, bool flipX) { boost::mutex::scoped_lock lock(display_mutex); //allow one command at a time #ifdef VIRTUAL_FLIP if(flipX) cv::flip(image, cam1_area, 1); else image.copyTo(cam1_area); #else camSize = image.size(); //image.copyTo(display); resize(image, display, display.size()); #endif // resize(image, cam_area, cv::Size(CAM_WIDTH, CAM_HEIGHT));//resize image //resize(image, display, cv::Size(WINDOW_WIDTH, WINDOW_HEIGHT));//resize image } int Dialog::createButton(const std::string& bar_name, char shortcut, std::function<void()> const & on_change){ boost::mutex::scoped_lock lock(click_mutex); //allow one command at a time m_buttons.push_back(std::make_tuple(bar_name, shortcut, on_change)); return 0; }; void Dialog::clearButtons() { boost::mutex::scoped_lock lock(click_mutex); //allow one command at a time m_buttons.clear(); } void Dialog::ClearDisplay() { // boost::mutex::scoped_lock lock(mutex); //allow one command at a time // display_empty.copyTo(display); } void Dialog::putText(const std::string &text, cv::Point pos, double fontScale, cv::Scalar color) { boost::mutex::scoped_lock lock(click_mutex); //allow one command at a time if (pos.x < 0) pos.x = display.size().width + pos.x; if (pos.y < 0) pos.y = display.size().height + pos.y; std::string key = std::to_string(pos.x) + "_" + std::to_string(pos.y); m_texts[key] = std::make_tuple(pos, text, fontScale, color); //cv::putText(display, text, pos, cv::FONT_HERSHEY_DUPLEX, fontScale, color); } void Dialog::putShadowedText(const std::string &text, cv::Point pos, double fontScale, cv::Scalar color) { putText(text, cv::Point(pos.x + 0.2, pos.y + 0.2), fontScale, color); putText(text, pos, fontScale, cv::Scalar(0, 0,0)); } int Dialog::Draw() { { boost::mutex::scoped_lock lock(display_mutex); //allow one command at a time display.copyTo(display_empty); } { boost::mutex::scoped_lock lock(click_mutex); //allow one command at a time int i = 0; for (const auto& button : m_buttons) { ++i; cv::putText(display_empty, std::get<0>(button), cv::Point(31, (i)*m_buttonHeight), cv::FONT_HERSHEY_DUPLEX, fontScale, cv::Scalar(0, 0, 0)); cv::putText(display_empty, std::get<0>(button), cv::Point(30, (i)*m_buttonHeight), cv::FONT_HERSHEY_DUPLEX, fontScale, cv::Scalar(255, 255, 255)); } for (const auto& text : m_texts) { cv::putText(display_empty, std::get<1>(text.second), std::get<0>(text.second), cv::FONT_HERSHEY_DUPLEX, std::get<2>(text.second), std::get<3>(text.second)); } cv::imshow(m_title, display_empty); } //display_empty.copyTo(display); return 0; }; void Dialog::KeyPressed(int key){ if (key == '-') return; boost::mutex::scoped_lock lock(click_mutex); //allow one command at a time for (auto btn : m_buttons){ if(std::get<1>(btn) == key){ std::get<2>(btn)(); return; } } } void Dialog::mouseClicked(int event, int x, int y, int flag) { boost::mutex::scoped_lock lock(click_mutex); //allow one command at a time mouseX = x; mouseY = y; cv::Point2d scaled; cv::Size size; cv::Size target; size = display.size(); target = camSize; scaled.x = (float)x / size.width * target.width; scaled.y = (float)y / size.height * target.height; for (auto pListener : m_EventListeners){ if (pListener->OnMouseEvent(event, scaled.x, scaled.y, flag)) { return; // event was handled } } if (event == cv::EVENT_LBUTTONUP){ unsigned int index = (int)(round((float)y / m_buttonHeight) - 1); if (index < m_buttons.size()){ auto button = m_buttons[index]; std::get<2>(button)(); m_close = true; } } } void Dialog::Run(){ cv::namedWindow(m_title, CV_WINDOW_AUTOSIZE); //cvSetWindowProperty(m_title.c_str(), CV_WND_PROP_FULLSCREEN, CV_WINDOW_FULLSCREEN); cv::moveWindow(m_title, 0, 0); cv::setMouseCallback(m_title, [](int event, int x, int y, int flags, void* self) { ((Dialog*)self)->mouseClicked(event, x, y, flags); }, this); while (!stop_thread) { try { Draw(); int key = cv::waitKey(10); if (key == 27) stop_thread = true; KeyPressed(key); } catch (std::exception &e) { std::cout << "Dialog::Run, error: " << e.what() << std::endl; } //std::this_thread::sleep_for(std::chrono::milliseconds(10)); } cv::waitKey(10); }
[ "andres.viikmaa@gmail.com" ]
andres.viikmaa@gmail.com
960af92a1ffdcd0cff4d524fd5ed062ad1873b15
f6439b5ed1614fd8db05fa963b47765eae225eb5
/chrome/browser/search/suggestions/suggestions_source.cc
98bd51a0e7d50cf55f030c5bf817f763f8911b38
[ "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
6,579
cc
// Copyright 2014 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/search/suggestions/suggestions_source.h" #include <vector> #include "base/barrier_closure.h" #include "base/base64.h" #include "base/bind.h" #include "base/memory/ref_counted_memory.h" #include "base/strings/string16.h" #include "base/strings/string_piece.h" #include "base/strings/string_util.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/search/suggestions/suggestions_service.h" #include "chrome/browser/search/suggestions/suggestions_service_factory.h" #include "chrome/common/url_constants.h" #include "net/base/escape.h" #include "ui/gfx/codec/png_codec.h" #include "ui/gfx/image/image_skia.h" #include "url/gurl.h" namespace suggestions { namespace { const char kHtmlHeader[] = "<!DOCTYPE html>\n<html>\n<head>\n<title>Suggestions</title>\n" "<meta charset=\"utf-8\">\n" "<style type=\"text/css\">\nli {white-space: nowrap;}\n</style>\n"; const char kHtmlBody[] = "</head>\n<body>\n"; const char kHtmlFooter[] = "</body>\n</html>\n"; // Fills |output| with the HTML needed to display the suggestions. void RenderOutputHtml(const SuggestionsProfile& profile, const std::map<GURL, std::string>& base64_encoded_pngs, std::string* output) { std::vector<std::string> out; out.push_back(kHtmlHeader); out.push_back(kHtmlBody); out.push_back("<h1>Suggestions</h1>\n<ul>"); size_t size = profile.suggestions_size(); for (size_t i = 0; i < size; ++i) { const ChromeSuggestion& suggestion = profile.suggestions(i); std::string line; line += "<li><a href=\""; line += net::EscapeForHTML(suggestion.url()); line += "\" target=\"_blank\">"; line += net::EscapeForHTML(suggestion.title()); std::map<GURL, std::string>::const_iterator it = base64_encoded_pngs.find(GURL(suggestion.url())); if (it != base64_encoded_pngs.end()) { line += "<br><img src='"; line += it->second; line += "'>"; } line += "</a></li>\n"; out.push_back(line); } out.push_back("</ul>"); out.push_back(kHtmlFooter); *output = JoinString(out, ""); } // Fills |output| with the HTML needed to display that no suggestions are // available. void RenderOutputHtmlNoSuggestions(std::string* output) { std::vector<std::string> out; out.push_back(kHtmlHeader); out.push_back(kHtmlBody); out.push_back("<h1>Suggestions</h1>\n"); out.push_back("<p>You have no suggestions.</p>\n"); out.push_back(kHtmlFooter); *output = JoinString(out, ""); } } // namespace SuggestionsSource::SuggestionsSource(Profile* profile) : profile_(profile), weak_ptr_factory_(this) {} SuggestionsSource::~SuggestionsSource() {} SuggestionsSource::RequestContext::RequestContext( const SuggestionsProfile& suggestions_profile_in, const content::URLDataSource::GotDataCallback& callback_in) : suggestions_profile(suggestions_profile_in), // Copy. callback(callback_in) // Copy. {} SuggestionsSource::RequestContext::~RequestContext() {} std::string SuggestionsSource::GetSource() const { return chrome::kChromeUISuggestionsHost; } void SuggestionsSource::StartDataRequest( const std::string& path, int render_process_id, int render_frame_id, const content::URLDataSource::GotDataCallback& callback) { SuggestionsServiceFactory* suggestions_service_factory = SuggestionsServiceFactory::GetInstance(); SuggestionsService* suggestions_service( suggestions_service_factory->GetForProfile(profile_)); if (!suggestions_service) { callback.Run(NULL); return; } suggestions_service->FetchSuggestionsData( base::Bind(&SuggestionsSource::OnSuggestionsAvailable, weak_ptr_factory_.GetWeakPtr(), callback)); } std::string SuggestionsSource::GetMimeType(const std::string& path) const { return "text/html"; } base::MessageLoop* SuggestionsSource::MessageLoopForRequestPath( const std::string& path) const { // This can be accessed from the IO thread. return content::URLDataSource::MessageLoopForRequestPath(path); } void SuggestionsSource::OnSuggestionsAvailable( const content::URLDataSource::GotDataCallback& callback, const SuggestionsProfile& suggestions_profile) { size_t size = suggestions_profile.suggestions_size(); if (!size) { std::string output; RenderOutputHtmlNoSuggestions(&output); callback.Run(base::RefCountedString::TakeString(&output)); } else { RequestContext* context = new RequestContext(suggestions_profile, callback); base::Closure barrier = BarrierClosure( size, base::Bind(&SuggestionsSource::OnThumbnailsFetched, weak_ptr_factory_.GetWeakPtr(), context)); for (size_t i = 0; i < size; ++i) { const ChromeSuggestion& suggestion = suggestions_profile.suggestions(i); // Fetch the thumbnail for this URL (exercising the fetcher). After all // fetches are done, including NULL callbacks for unavailable thumbnails, // SuggestionsSource::OnThumbnailsFetched will be called. SuggestionsService* suggestions_service( SuggestionsServiceFactory::GetForProfile(profile_)); suggestions_service->GetPageThumbnail( GURL(suggestion.url()), base::Bind(&SuggestionsSource::OnThumbnailAvailable, weak_ptr_factory_.GetWeakPtr(), context, barrier)); } } } void SuggestionsSource::OnThumbnailsFetched(RequestContext* context) { scoped_ptr<RequestContext> context_deleter(context); std::string output; RenderOutputHtml(context->suggestions_profile, context->base64_encoded_pngs, &output); context->callback.Run(base::RefCountedString::TakeString(&output)); } void SuggestionsSource::OnThumbnailAvailable(RequestContext* context, base::Closure barrier, const GURL& url, const SkBitmap* bitmap) { if (bitmap) { std::vector<unsigned char> output; gfx::PNGCodec::EncodeBGRASkBitmap(*bitmap, false, &output); std::string encoded_output; base::Base64Encode(std::string(output.begin(), output.end()), &encoded_output); context->base64_encoded_pngs[url] = "data:image/png;base64,"; context->base64_encoded_pngs[url] += encoded_output; } barrier.Run(); } } // namespace suggestions
[ "jhonnyjosearana@gmail.com" ]
jhonnyjosearana@gmail.com
abc17ed2ce2b8e1e5baed1b83ea3168c18487622
444bb227013ed02b49125171a5d32e2bba6bf4af
/test.cpp
6812e8676d3d2921aba87a826fd1f2d33500110f
[]
no_license
RS-codes/Qt5_Intermediate_11.2_Timer_QTimer_TimeOut
2b7e2b893f2e66fdea09cde744debdadf49c2675
cb7c433794c5f3c5561f179066267bdc760f58cf
refs/heads/master
2023-05-22T16:14:56.228453
2021-06-13T04:41:27
2021-06-13T04:41:27
376,439,333
0
0
null
null
null
null
UTF-8
C++
false
false
424
cpp
#include "test.h" test::test(QObject *parent) : QObject(parent) { number = 0; timer.setInterval(1000); connect(&timer,&QTimer::timeout,this, &test::timeout); } void test::timeout() { number++; qInfo() << QTime::currentTime().toString(Qt::DateFormat::SystemLocaleLongDate); if(number == 5) { timer.stop(); qInfo() << "Complete!"; } } void test::dostuff() { timer.start(); }
[ "RS-codes@github.com" ]
RS-codes@github.com
857ed7ecfb7ce500ddf423da197dee92fca8f403
d88ad726e2ceb60f4e7098725a50c4d67c71f67f
/S1/VIM/build-VIMTP1BIS-Desktop_Qt_5_4_0_MinGW_32bit-Debug/ui_histodialog.h
72f8f936a30600bbd10ea69c97e71a8a58d5583b
[]
no_license
Sabouh/M2GICAO
65bde1da541a84c6ed1ccc198057178e1dc1575a
8a492490aa2b4ef04e1ad2a92649c7211be01fea
refs/heads/master
2021-01-24T17:39:10.215981
2016-03-12T20:13:09
2016-03-12T20:13:09
43,699,888
1
0
null
null
null
null
UTF-8
C++
false
false
1,895
h
/******************************************************************************** ** Form generated from reading UI file 'histodialog.ui' ** ** Created by: Qt User Interface Compiler version 5.4.0 ** ** WARNING! All changes made in this file will be lost when recompiling UI file! ********************************************************************************/ #ifndef UI_HISTODIALOG_H #define UI_HISTODIALOG_H #include <QtCore/QVariant> #include <QtWidgets/QAction> #include <QtWidgets/QApplication> #include <QtWidgets/QButtonGroup> #include <QtWidgets/QDialog> #include <QtWidgets/QGraphicsView> #include <QtWidgets/QGridLayout> #include <QtWidgets/QHeaderView> QT_BEGIN_NAMESPACE class Ui_HistoDialog { public: QGridLayout *gridLayout_2; QGridLayout *gridLayout; QGraphicsView *graphicsView; void setupUi(QDialog *HistoDialog) { if (HistoDialog->objectName().isEmpty()) HistoDialog->setObjectName(QStringLiteral("HistoDialog")); HistoDialog->resize(400, 300); gridLayout_2 = new QGridLayout(HistoDialog); gridLayout_2->setObjectName(QStringLiteral("gridLayout_2")); gridLayout = new QGridLayout(); gridLayout->setObjectName(QStringLiteral("gridLayout")); graphicsView = new QGraphicsView(HistoDialog); graphicsView->setObjectName(QStringLiteral("graphicsView")); gridLayout->addWidget(graphicsView, 0, 0, 1, 1); gridLayout_2->addLayout(gridLayout, 0, 0, 1, 1); retranslateUi(HistoDialog); QMetaObject::connectSlotsByName(HistoDialog); } // setupUi void retranslateUi(QDialog *HistoDialog) { HistoDialog->setWindowTitle(QApplication::translate("HistoDialog", "Dialog", 0)); } // retranslateUi }; namespace Ui { class HistoDialog: public Ui_HistoDialog {}; } // namespace Ui QT_END_NAMESPACE #endif // UI_HISTODIALOG_H
[ "bouhsabine@gmail.com" ]
bouhsabine@gmail.com
0cfc7e5f16ea536c27d907c82d5e06d0e62f0aac
377aedce53af5d65c5437c992ee02feee248b24f
/ihatethisalready.cpp
ca2ba5b5cec60ed0ecfe8780657d8cd730fdfd59
[]
no_license
dtara003/Artificial-Intelligence
576f00d2aea0c6779782dbdac5a3151ea12fc7b3
e0a9f4fcbff0f3fa16bcdc5eda8f7a7cf288866d
refs/heads/master
2021-01-12T12:28:37.508976
2016-11-01T06:00:09
2016-11-01T06:00:09
72,508,171
0
0
null
null
null
null
UTF-8
C++
false
false
1,681
cpp
#include <iostream> #include <vector> using namespace std; int main() { int problem[3][3] = {{1, 2, 3}, {4, 8, 0}, {7, 6, 5}}; cout << "Welcome to Dharti Tarapara's 8-puzzle solver." << endl; cout << " Type 1 to use a default puzzle, or 2 to enter your own puzzle" << endl; int choice = 0; cin >> choice; if (choice == 2) { int val = 0; cout << "Enter your puzzle, use a zero to represent the blank." << endl; cout << "Enter the first row, use space or tabs between numbers." << endl; for (int i = 0; i < 3; ++i) { cin >> val; problem[0][i] = val; } cout << "Enter the second row, use space or tabs between numbers." << endl; for (int i = 0; i < 3; ++i) { cin >> val; problem[1][i] = val; } cout << "Enter the third row, use space or tabs between numbers." << endl; for (int i = 0; i < 3; ++i) { cin >> val; problem[2][i] = val; } } cout << "Enter your choice of algorithm." << endl << "Uniform Cost Search" << endl << "A* with misplaced tile heuristic" << endl << "A* with the Manhattan distance heuristic" << endl; int algorithm = 0; cin >> algorithm; // check prompt cout << endl << endl << "array stored" << endl; for (int i = 0; i < 3; ++i) { for (int j = 0; j < 3; ++j) { cout << problem[i][j] << " "; } cout << endl; } cout << "algorithm stored: " << algorithm << endl; return 0; }
[ "dtara003@ucr.edu" ]
dtara003@ucr.edu
928719ba3bd829c3435053a87fae00b89e468216
3e093521306ac955f65ad7648dfe2dbc649c7e4d
/3rdParty/asio/1.12/include/asio/detail/buffer_sequence_adapter.hpp
450b3eecdd7ca8eadd51e6d02992bae44795df9a
[ "Apache-2.0", "LGPL-2.1-or-later", "BSD-3-Clause", "Bison-exception-2.2", "JSON", "LicenseRef-scancode-autoconf-simple-exception", "LicenseRef-scancode-pcre", "GPL-1.0-or-later", "ISC", "ICU", "GPL-2.0-only", "BSL-1.0", "LicenseRef-scancode-unknown-license-reference", "Unlicense", "Licen...
permissive
Simran-B/arangodb_test
8836e89af5bfcf156aaf643ab1ab1f48c38c0eb6
e643ddbaa8327249ae5f10add89ab9e6d9f6fecd
refs/heads/devel
2021-10-24T18:45:11.844512
2019-03-11T13:28:44
2019-03-11T13:28:44
174,999,262
0
1
Apache-2.0
2019-03-11T13:27:59
2019-03-11T12:51:28
C++
UTF-8
C++
false
false
12,218
hpp
// // detail/buffer_sequence_adapter.hpp // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // // Copyright (c) 2003-2017 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #ifndef ASIO_DETAIL_BUFFER_SEQUENCE_ADAPTER_HPP #define ASIO_DETAIL_BUFFER_SEQUENCE_ADAPTER_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include "asio/detail/config.hpp" #include "asio/buffer.hpp" #include "asio/detail/array_fwd.hpp" #include "asio/detail/socket_types.hpp" #include "asio/detail/push_options.hpp" namespace asio { namespace detail { class buffer_sequence_adapter_base { #if defined(ASIO_WINDOWS_RUNTIME) public: // The maximum number of buffers to support in a single operation. enum { max_buffers = 1 }; protected: typedef Windows::Storage::Streams::IBuffer^ native_buffer_type; ASIO_DECL static void init_native_buffer( native_buffer_type& buf, const asio::mutable_buffer& buffer); ASIO_DECL static void init_native_buffer( native_buffer_type& buf, const asio::const_buffer& buffer); #elif defined(ASIO_WINDOWS) || defined(__CYGWIN__) public: // The maximum number of buffers to support in a single operation. enum { max_buffers = 64 < max_iov_len ? 64 : max_iov_len }; protected: typedef WSABUF native_buffer_type; static void init_native_buffer(WSABUF& buf, const asio::mutable_buffer& buffer) { buf.buf = static_cast<char*>(buffer.data()); buf.len = static_cast<ULONG>(buffer.size()); } static void init_native_buffer(WSABUF& buf, const asio::const_buffer& buffer) { buf.buf = const_cast<char*>(static_cast<const char*>(buffer.data())); buf.len = static_cast<ULONG>(buffer.size()); } #else // defined(ASIO_WINDOWS) || defined(__CYGWIN__) public: // The maximum number of buffers to support in a single operation. enum { max_buffers = 64 < max_iov_len ? 64 : max_iov_len }; protected: typedef iovec native_buffer_type; static void init_iov_base(void*& base, void* addr) { base = addr; } template <typename T> static void init_iov_base(T& base, void* addr) { base = static_cast<T>(addr); } static void init_native_buffer(iovec& iov, const asio::mutable_buffer& buffer) { init_iov_base(iov.iov_base, buffer.data()); iov.iov_len = buffer.size(); } static void init_native_buffer(iovec& iov, const asio::const_buffer& buffer) { init_iov_base(iov.iov_base, const_cast<void*>(buffer.data())); iov.iov_len = buffer.size(); } #endif // defined(ASIO_WINDOWS) || defined(__CYGWIN__) }; // Helper class to translate buffers into the native buffer representation. template <typename Buffer, typename Buffers> class buffer_sequence_adapter : buffer_sequence_adapter_base { public: explicit buffer_sequence_adapter(const Buffers& buffer_sequence) : count_(0), total_buffer_size_(0) { buffer_sequence_adapter::init( asio::buffer_sequence_begin(buffer_sequence), asio::buffer_sequence_end(buffer_sequence)); } native_buffer_type* buffers() { return buffers_; } std::size_t count() const { return count_; } std::size_t total_size() const { return total_buffer_size_; } bool all_empty() const { return total_buffer_size_ == 0; } static bool all_empty(const Buffers& buffer_sequence) { return buffer_sequence_adapter::all_empty( asio::buffer_sequence_begin(buffer_sequence), asio::buffer_sequence_end(buffer_sequence)); } static void validate(const Buffers& buffer_sequence) { buffer_sequence_adapter::validate( asio::buffer_sequence_begin(buffer_sequence), asio::buffer_sequence_end(buffer_sequence)); } static Buffer first(const Buffers& buffer_sequence) { return buffer_sequence_adapter::first( asio::buffer_sequence_begin(buffer_sequence), asio::buffer_sequence_end(buffer_sequence)); } private: template <typename Iterator> void init(Iterator begin, Iterator end) { Iterator iter = begin; for (; iter != end && count_ < max_buffers; ++iter, ++count_) { Buffer buffer(*iter); init_native_buffer(buffers_[count_], buffer); total_buffer_size_ += buffer.size(); } } template <typename Iterator> static bool all_empty(Iterator begin, Iterator end) { Iterator iter = begin; std::size_t i = 0; for (; iter != end && i < max_buffers; ++iter, ++i) if (Buffer(*iter).size() > 0) return false; return true; } template <typename Iterator> static void validate(Iterator begin, Iterator end) { Iterator iter = begin; for (; iter != end; ++iter) { Buffer buffer(*iter); buffer.data(); } } template <typename Iterator> static Buffer first(Iterator begin, Iterator end) { Iterator iter = begin; for (; iter != end; ++iter) { Buffer buffer(*iter); if (buffer.size() != 0) return buffer; } return Buffer(); } native_buffer_type buffers_[max_buffers]; std::size_t count_; std::size_t total_buffer_size_; }; template <typename Buffer> class buffer_sequence_adapter<Buffer, asio::mutable_buffer> : buffer_sequence_adapter_base { public: explicit buffer_sequence_adapter( const asio::mutable_buffer& buffer_sequence) { init_native_buffer(buffer_, Buffer(buffer_sequence)); total_buffer_size_ = buffer_sequence.size(); } native_buffer_type* buffers() { return &buffer_; } std::size_t count() const { return 1; } std::size_t total_size() const { return total_buffer_size_; } bool all_empty() const { return total_buffer_size_ == 0; } static bool all_empty(const asio::mutable_buffer& buffer_sequence) { return buffer_sequence.size() == 0; } static void validate(const asio::mutable_buffer& buffer_sequence) { buffer_sequence.data(); } static Buffer first(const asio::mutable_buffer& buffer_sequence) { return Buffer(buffer_sequence); } private: native_buffer_type buffer_; std::size_t total_buffer_size_; }; template <typename Buffer> class buffer_sequence_adapter<Buffer, asio::const_buffer> : buffer_sequence_adapter_base { public: explicit buffer_sequence_adapter( const asio::const_buffer& buffer_sequence) { init_native_buffer(buffer_, Buffer(buffer_sequence)); total_buffer_size_ = buffer_sequence.size(); } native_buffer_type* buffers() { return &buffer_; } std::size_t count() const { return 1; } std::size_t total_size() const { return total_buffer_size_; } bool all_empty() const { return total_buffer_size_ == 0; } static bool all_empty(const asio::const_buffer& buffer_sequence) { return buffer_sequence.size() == 0; } static void validate(const asio::const_buffer& buffer_sequence) { buffer_sequence.data(); } static Buffer first(const asio::const_buffer& buffer_sequence) { return Buffer(buffer_sequence); } private: native_buffer_type buffer_; std::size_t total_buffer_size_; }; #if !defined(ASIO_NO_DEPRECATED) template <typename Buffer> class buffer_sequence_adapter<Buffer, asio::mutable_buffers_1> : buffer_sequence_adapter_base { public: explicit buffer_sequence_adapter( const asio::mutable_buffers_1& buffer_sequence) { init_native_buffer(buffer_, Buffer(buffer_sequence)); total_buffer_size_ = buffer_sequence.size(); } native_buffer_type* buffers() { return &buffer_; } std::size_t count() const { return 1; } std::size_t total_size() const { return total_buffer_size_; } bool all_empty() const { return total_buffer_size_ == 0; } static bool all_empty(const asio::mutable_buffers_1& buffer_sequence) { return buffer_sequence.size() == 0; } static void validate(const asio::mutable_buffers_1& buffer_sequence) { buffer_sequence.data(); } static Buffer first(const asio::mutable_buffers_1& buffer_sequence) { return Buffer(buffer_sequence); } private: native_buffer_type buffer_; std::size_t total_buffer_size_; }; template <typename Buffer> class buffer_sequence_adapter<Buffer, asio::const_buffers_1> : buffer_sequence_adapter_base { public: explicit buffer_sequence_adapter( const asio::const_buffers_1& buffer_sequence) { init_native_buffer(buffer_, Buffer(buffer_sequence)); total_buffer_size_ = buffer_sequence.size(); } native_buffer_type* buffers() { return &buffer_; } std::size_t count() const { return 1; } std::size_t total_size() const { return total_buffer_size_; } bool all_empty() const { return total_buffer_size_ == 0; } static bool all_empty(const asio::const_buffers_1& buffer_sequence) { return buffer_sequence.size() == 0; } static void validate(const asio::const_buffers_1& buffer_sequence) { buffer_sequence.data(); } static Buffer first(const asio::const_buffers_1& buffer_sequence) { return Buffer(buffer_sequence); } private: native_buffer_type buffer_; std::size_t total_buffer_size_; }; #endif // !defined(ASIO_NO_DEPRECATED) template <typename Buffer, typename Elem> class buffer_sequence_adapter<Buffer, boost::array<Elem, 2> > : buffer_sequence_adapter_base { public: explicit buffer_sequence_adapter( const boost::array<Elem, 2>& buffer_sequence) { init_native_buffer(buffers_[0], Buffer(buffer_sequence[0])); init_native_buffer(buffers_[1], Buffer(buffer_sequence[1])); total_buffer_size_ = buffer_sequence[0].size() + buffer_sequence[1].size(); } native_buffer_type* buffers() { return buffers_; } std::size_t count() const { return 2; } std::size_t total_size() const { return total_buffer_size_; } bool all_empty() const { return total_buffer_size_ == 0; } static bool all_empty(const boost::array<Elem, 2>& buffer_sequence) { return buffer_sequence[0].size() == 0 && buffer_sequence[1].size() == 0; } static void validate(const boost::array<Elem, 2>& buffer_sequence) { buffer_sequence[0].data(); buffer_sequence[1].data(); } static Buffer first(const boost::array<Elem, 2>& buffer_sequence) { return Buffer(buffer_sequence[0].size() != 0 ? buffer_sequence[0] : buffer_sequence[1]); } private: native_buffer_type buffers_[2]; std::size_t total_buffer_size_; }; #if defined(ASIO_HAS_STD_ARRAY) template <typename Buffer, typename Elem> class buffer_sequence_adapter<Buffer, std::array<Elem, 2> > : buffer_sequence_adapter_base { public: explicit buffer_sequence_adapter( const std::array<Elem, 2>& buffer_sequence) { init_native_buffer(buffers_[0], Buffer(buffer_sequence[0])); init_native_buffer(buffers_[1], Buffer(buffer_sequence[1])); total_buffer_size_ = buffer_sequence[0].size() + buffer_sequence[1].size(); } native_buffer_type* buffers() { return buffers_; } std::size_t count() const { return 2; } std::size_t total_size() const { return total_buffer_size_; } bool all_empty() const { return total_buffer_size_ == 0; } static bool all_empty(const std::array<Elem, 2>& buffer_sequence) { return buffer_sequence[0].size() == 0 && buffer_sequence[1].size() == 0; } static void validate(const std::array<Elem, 2>& buffer_sequence) { buffer_sequence[0].data(); buffer_sequence[1].data(); } static Buffer first(const std::array<Elem, 2>& buffer_sequence) { return Buffer(buffer_sequence[0].size() != 0 ? buffer_sequence[0] : buffer_sequence[1]); } private: native_buffer_type buffers_[2]; std::size_t total_buffer_size_; }; #endif // defined(ASIO_HAS_STD_ARRAY) } // namespace detail } // namespace asio #include "asio/detail/pop_options.hpp" #if defined(ASIO_HEADER_ONLY) # include "asio/detail/impl/buffer_sequence_adapter.ipp" #endif // defined(ASIO_HEADER_ONLY) #endif // ASIO_DETAIL_BUFFER_SEQUENCE_ADAPTER_HPP
[ "michael@arangodb.com" ]
michael@arangodb.com