blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
3
264
content_id
stringlengths
40
40
detected_licenses
listlengths
0
85
license_type
stringclasses
2 values
repo_name
stringlengths
5
140
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
986 values
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
3.89k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
23 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
145 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
3
10.4M
extension
stringclasses
122 values
content
stringlengths
3
10.4M
authors
listlengths
1
1
author_id
stringlengths
0
158
bdff174d6932bfe8d17a3678c9bdbae015316d31
b4cf51e23c8bfb31f8a2c2e3de94f25e1b7a3109
/include/afina/Executor.h
dba7c5388e945d311c48a46de005858739c0e5bc
[]
no_license
OlegKafanov/afina
4d77fccaacb2b6b34e379e67a770c198b3584fd1
999549aadbe7d01dc8dd44133e2fc90f4bda2113
refs/heads/master
2021-09-05T10:37:46.443781
2018-01-26T13:38:45
2018-01-26T13:38:45
104,130,309
1
0
null
2017-09-19T21:24:26
2017-09-19T21:24:26
null
UTF-8
C++
false
false
2,775
h
#ifndef AFINA_THREADPOOL_H #define AFINA_THREADPOOL_H #include <condition_variable> #include <functional> #include <memory> #include <mutex> #include <queue> #include <string> #include <thread> namespace Afina { /** * # Thread pool */ class Executor { enum class State { // Threadpool is fully operational, tasks could be added and get executed kRun, // Threadpool is on the way to be shutdown, no ned task could be added, but existing will be // completed as requested kStopping, // Threadppol is stopped kStopped }; Executor(std::string name, int size); ~Executor(); /** * Signal thread pool to stop, it will stop accepting new jobs and close threads just after each become * free. All enqueued jobs will be complete. * * In case if await flag is true, call won't return until all background jobs are done and all threads are stopped */ void Stop(bool await = false); /** * Add function to be executed on the threadpool. Method returns true in case if task has been placed * onto execution queue, i.e scheduled for execution and false otherwise. * * That function doesn't wait for function result. Function could always be written in a way to notify caller about * execution finished by itself */ template <typename F, typename... Types> bool Execute(F &&func, Types... args) { // Prepare "task" auto exec = std::bind(std::forward<F>(func), std::forward<Types>(args)...); std::unique_lock<std::mutex> lock(this->mutex); if (state != State::kRun) { return false; } // Enqueue new task tasks.push_back(exec); empty_condition.notify_one(); return true; } private: // No copy/move/assign allowed Executor(const Executor &); // = delete; Executor(Executor &&); // = delete; Executor &operator=(const Executor &); // = delete; Executor &operator=(Executor &&); // = delete; /** * Main function that all pool threads are running. It polls internal task queue and execute tasks */ friend void perform(Executor *executor); /** * Mutex to protect state below from concurrent modification */ std::mutex mutex; /** * Conditional variable to await new data in case of empty queue */ std::condition_variable empty_condition; /** * Vector of actual threads that perorm execution */ std::vector<std::thread> threads; /** * Task queue */ std::deque<std::function<void()>> tasks; /** * Flag to stop bg threads */ State state; }; } // namespace Afina #endif // AFINA_THREADPOOL_H
[ "ph.andronov@corp.mail.ru" ]
ph.andronov@corp.mail.ru
aec2dc05e56c69e0980256a383fe9fed2b0134d5
6ed471f36e5188f77dc61cca24daa41496a6d4a0
/SDK/PrimalItemConsumable_Kibble_BoaEgg_parameters.h
3a727f17af9ca4be647c885e83ee850a99a66337
[]
no_license
zH4x-SDK/zARKSotF-SDK
77bfaf9b4b9b6a41951ee18db88f826dd720c367
714730f4bb79c07d065181caf360d168761223f6
refs/heads/main
2023-07-16T22:33:15.140456
2021-08-27T13:40:06
2021-08-27T13:40:06
400,521,086
0
0
null
null
null
null
UTF-8
C++
false
false
751
h
#pragma once #include "../SDK.h" // Name: ARKSotF, Version: 178.8.0 #ifdef _MSC_VER #pragma pack(push, 0x8) #endif namespace SDK { //--------------------------------------------------------------------------- // Parameters //--------------------------------------------------------------------------- // Function PrimalItemConsumable_Kibble_BoaEgg.PrimalItemConsumable_Kibble_BoaEgg_C.ExecuteUbergraph_PrimalItemConsumable_Kibble_BoaEgg struct UPrimalItemConsumable_Kibble_BoaEgg_C_ExecuteUbergraph_PrimalItemConsumable_Kibble_BoaEgg_Params { int EntryPoint; // (Parm, ZeroConstructor, IsPlainOldData) }; } #ifdef _MSC_VER #pragma pack(pop) #endif
[ "zp2kshield@gmail.com" ]
zp2kshield@gmail.com
9ea73474ab4f505e4e5929aa6869c1f97eceed3a
ee491a9c89b82b0c2732a357e13cbffa6954bdf2
/src/config.h
6495c812f55ec939f429d4e9e849b89c11ab3bf4
[ "MIT" ]
permissive
maxhodak/neat
9a1da908ab55ffa30f096345e1dc097fe7f4cec9
3f844173828eb22009cc8d36c28e75a22adfbae8
refs/heads/master
2021-01-02T08:51:37.479731
2010-02-14T03:23:44
2010-02-14T03:23:44
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,480
h
#ifndef __CONFIG_H #define __CONFIG_H /******BEGIN LICENSE BLOCK******* * The MIT License * * Copyright (c) 2009 Max Hodak * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. ********END LICENSE BLOCK*********/ #include <iostream> #include <string> #include <vector> #include "lua/include/lua.hpp" using namespace std; struct NeatConf { vector<string> monitor_paths; vector<string> sorted_paths; int inter_sort_interval; // seconds }; #endif
[ "maxhodak@gmail.com" ]
maxhodak@gmail.com
430818d690cd563f4429ee7b3dfa63776df05920
0e5ea03c2455b34a2f416c6c94c1669d7fe26e37
/_2018_03_20 BattleShip 1/WhiteMtrl.h
5a31740c520b0f99867c4cc7e9cd95328c4ecfcb
[]
no_license
Arroria/__old_project
8682652fac9a95898b41eff5b4fdfab023cda699
efb655b2356bd95744ba19093f25ab266a625722
refs/heads/master
2020-09-05T08:02:44.806509
2019-11-06T18:01:23
2019-11-06T18:01:23
220,033,980
1
1
null
null
null
null
UTF-8
C++
false
false
252
h
#pragma once #include "Singleton.h" class WhiteMtrl : public Singleton<WhiteMtrl> { private: D3DMATERIAL9 m_mtrl; public: D3DMATERIAL9 GetMtrl(); public: WhiteMtrl(); ~WhiteMtrl(); }; #define WHITEMTRL (SingletonInstance(WhiteMtrl)->GetMtrl())
[ "mermerkwon@naver.com" ]
mermerkwon@naver.com
7fca6015b98a46de8c88ad9670f2c30b424d1ce2
41ce1bb8f39f17d3500e3d3eece7723948e4ad87
/First term/changingPartsOfArray/stdafx.cpp
ddc6d60c2c7048ff13245c96c3c30a97c37f6c5e
[]
no_license
KanaevaEkaterina/Projects.2012-1
6e5c6edc6c6eaca7dcc115fe418985d69163d6cc
69c32b4021a8b3b7f0c8edbe4fbf54514d1c6f14
refs/heads/master
2021-01-10T18:38:12.555013
2013-05-29T08:16:27
2013-05-29T08:16:27
3,605,254
1
0
null
null
null
null
WINDOWS-1251
C++
false
false
575
cpp
// stdafx.cpp: исходный файл, содержащий только стандартные включаемые модули // homework1.5.pch будет предкомпилированным заголовком // stdafx.obj будет содержать предварительно откомпилированные сведения о типе #include "stdafx.h" // TODO: Установите ссылки на любые требующиеся дополнительные заголовки в файле STDAFX.H // , а не в данном файле
[ "kanaeva.katerina6@gmail.com" ]
kanaeva.katerina6@gmail.com
fb422b294af9b2d6f1cd6a45ba80e502efa6f39f
980f03e45ac8bfb9f0e2bb78673337f8e7db20e6
/src/InputManager.h
0a50dd499b6236669d2385cd65ff5e0de9f514d1
[]
no_license
synystro/lux2Dengine
699fe1d0ec4ed3fdd012c736203465028e560559
8c5810209cea1539867af58c9f9a96ae6e09b24e
refs/heads/master
2023-04-04T11:26:11.943089
2021-03-30T17:23:51
2021-03-30T17:23:51
353,074,834
0
0
null
null
null
null
UTF-8
C++
false
false
698
h
#pragma once #include <vector> #include <algorithm> #include "./Controls.h" class InputManager { private: std::vector<int> keysPressed; public: bool CheckKeyPressed(int key) { if(std::find(keysPressed.begin(), keysPressed.end(), key) != keysPressed.end()) { return true; } keysPressed.push_back(key); return false; } void SetKeyReleased(int key) { if(std::find(keysPressed.begin(), keysPressed.end(), key) != keysPressed.end()) { keysPressed.erase(std::remove(keysPressed.begin(), keysPressed.end(), key), keysPressed.end()); } } };
[ "pedro_araujo@live.com" ]
pedro_araujo@live.com
7ea2d204374e67e137dc9b0d02e0873fd66a21d1
d5550f431e946e009a88020287966b6813c72053
/数据结构课程设计/迷宫优化/迷宫优化.cpp
335b3105d2dca39d7b69bdefffbaf998fcc39e14
[]
no_license
ZZLZHAO/Data-Structure-Course-Design
e4e486dc4025a1e13db564c7327cd3b0b08462d7
205d2f333b3ccb9c7494715b0ef42813deb0149b
refs/heads/main
2023-05-26T13:32:09.019377
2021-06-04T14:13:47
2021-06-04T14:13:47
null
0
0
null
null
null
null
GB18030
C++
false
false
7,930
cpp
#include<iostream> #include<algorithm> #include<string> #include<vector> #include<cmath> #include<queue> #include <Windows.h> #include <time.h> #include <iomanip> #define N 40 // 棋盘/迷宫 的阶数 #define M 20 // 棋盘/迷宫 的阶数 using namespace std; class Node { public: int x, y; // 节点所在位置 int F, G, H; // G:从起点开始,沿着产的路径,移动到网格上指定方格的移动耗费。 // H:从网格上那个方格移动到终点B的预估移动耗费,使用曼哈顿距离。 // F = G + H Node(int a, int b) :x(a), y(b) {} // 重载操作符,使优先队列以F值大小为标准维持堆 bool operator < (const Node& a) const { return F > a.F; } }; // 定义八个方向 int dir[4][2] = { {-1, 0}, {0, -1}, {0, 1}, {1, 0} }; // 优先队列,就相当于open表 priority_queue<Node>que; // 棋盘 int qp[N][M] = { {0, 1, 0, 1, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 1, 0, 1, 1, 1, 1} , {0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 1, 0, 0, 0, 1, 1}, {0, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1}, {0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 1}, {1, 1, 1, 1, 0, 1, 0, 0, 1, 1, 1, 0, 0, 1, 1, 1, 0, 0, 1, 1}, {0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 1, 1, 1, 1, 0, 1, 1, 0, 0, 1}, {0, 1, 0, 1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 1, 0, 1, 1}, {1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 0, 0, 1}, {0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 0, 1}, {0, 1, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 1, 1, 0, 1, 0}, {0, 0, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 1}, {0, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 1, 1}, {0, 1, 1, 1, 0, 1, 0, 1, 0, 0, 1, 1, 1, 0, 0, 1, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 0, 0, 1}, {1, 1, 0, 1, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1}, {0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1}, {0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0}, {0, 1, 0, 0, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, {1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 1, 0}, {0, 0, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 1, 0}, {0, 1, 0, 1, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 1, 0, 1, 1, 1, 1} , {0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 1, 0, 0, 0, 1, 1}, {0, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1}, {0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 1, 1}, {1, 1, 1, 1, 0, 1, 0, 0, 1, 1, 1, 0, 0, 1, 1, 1, 0, 0, 1, 1}, {0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 1, 1, 1, 1, 0, 1, 1, 0, 0, 1}, {0, 1, 0, 1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 1, 0, 1, 1}, {1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 1, 1, 0, 0, 1}, {0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 1, 0, 1}, {0, 1, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 1, 1, 0, 1, 0}, {0, 0, 1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 1}, {0, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 1, 1}, {0, 1, 1, 1, 0, 1, 0, 1, 0, 0, 1, 1, 1, 0, 0, 1, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 0, 0, 1}, {1, 1, 0, 1, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1}, {0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1}, {0, 1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0}, {0, 1, 0, 0, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, {1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 1, 0}, {0, 0, 1, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 1, 0} }; bool visit[N][M]; // 访问情况记录,close表 int valF[N][M]; // 记录每个节点对应的F值 int path[N][M][2]; // 存储每个节点的父节点 int Manhuattan(int x, int y, int x1, int y1); // 计算曼哈顿距离 bool NodeIsLegal(int x, int y, int xx, int yy); // 判断位置合法性 void A_start(int x0, int y0, int x1, int y1); // A*算法 void PrintPath(int x1, int y1); // 打印路径 /* ----------------主函数------------------- */ int main() { fill(visit[0], visit[0] + N * M, false); // 将visit数组赋初值false fill(valF[0], valF[0] + N * M, 0); // 初始化F全为0 fill(path[0][0], path[0][0] + N * M * 2, -1); // 路径同样赋初值-1 // // 起点 // 终点 int x0, y0, x1, y1; cout << "输入起点:"; cin >> x0 >> y0; cout << "输入终点:"; cin >> x1 >> y1; x0--; y0--; x1--; y1--; if (!NodeIsLegal(x0, y0, x0, y0)) { cout << "非法起点!" << endl; return 0; } double run_time; LARGE_INTEGER time_start; //开始时间 LARGE_INTEGER time_over; //结束时间 double dqFreq; //计时器频率 LARGE_INTEGER f; //计时器频率 QueryPerformanceFrequency(&f); dqFreq = (double)f.QuadPart; QueryPerformanceCounter(&time_start); //计时开始 A_start(x0, y0, x1, y1); // A*算法 QueryPerformanceCounter(&time_over); //计时结束 run_time = 1000000 * (time_over.QuadPart - time_start.QuadPart) / dqFreq; //乘以1000000把单位由秒化为微秒,精度为1000000/(cpu主频)微秒 cout << "所用时间: " << run_time << endl; PrintPath(x1, y1); // 打印路径 } /* ----------------自定义函数------------------ */ void A_start(int x0, int y0, int x1, int y1) { // 初始化起点 Node node(x0, y0); node.G = 0; node.H = Manhuattan(x0, y0, x1, y1); node.F = node.G + node.H; valF[x0][y0] = node.F; // 起点加入open表 que.push(node); while (!que.empty()) { Node node_top = que.top(); que.pop(); visit[node_top.x][node_top.y] = true; // 访问该点,加入closed表 if (node_top.x == x1 && node_top.y == y1) // 到达终点 break; // 遍历node_top周围的8个位置 for (int i = 0; i < 4; i++) { Node node_next(node_top.x + dir[i][0], node_top.y + dir[i][1]); // 创建一个node_top周围的节点 // 该节点坐标合法 且 未加入close表 if (NodeIsLegal(node_next.x, node_next.y, node_top.x, node_top.y) && !visit[node_next.x][node_next.y]) { // 计算从起点并经过node_top节点到达该节点所花费的代价 node_next.G = int(abs(node_next.x - x0) + abs(node_next.y - y0)); // 计算该节点到终点的曼哈顿距离 node_next.H = Manhuattan(node_next.x, node_next.y, x1, y1); // 从起点经过node_top和该节点到达终点的估计代价 node_next.F = node_next.G + node_next.H; // node_next.F < valF[node_next.x][node_next.y] 说明找到了更优的路径,则进行更新 // valF[node_next.x][node_next.y] == 0 说明该节点还未加入open表中,则加入 if (node_next.F < valF[node_next.x][node_next.y] || valF[node_next.x][node_next.y] == 0) { // 保存该节点的父节点 path[node_next.x][node_next.y][0] = node_top.x; path[node_next.x][node_next.y][1] = node_top.y; valF[node_next.x][node_next.y] = node_next.F; // 修改该节点对应的valF值 que.push(node_next); // 加入open表 } } } } } void PrintPath(int x1, int y1) { if (path[x1][y1][0] == -1 || path[x1][y1][1] == -1) { cout << "没有可行路径!" << endl; return; } int x = x1, y = y1; int a, b; while (x != -1 || y != -1) { qp[x][y] = 2; // 将可行路径上的节点赋值为2 a = path[x][y][0]; b = path[x][y][1]; x = a; y = b; } // □表示未经过的节点, █表示障碍物, ☆表示可行节点 string s[3] = { "□", "█", "☆" }; for (int i = 0; i < N; i++) { for (int j = 0; j < M; j++) cout << s[qp[i][j]]; cout << endl; } } int Manhuattan(int x, int y, int x1, int y1) { //return (abs(x - x1) + abs(y - y1)) * 10; return pow(x - x1, 2) + pow(y - y1, 2); } bool NodeIsLegal(int x, int y, int xx, int yy) { if (x < 0 || x >= N || y < 0 || y >= M) return false; // 判断边界 if (qp[x][y] == 1) return false; // 判断障碍物 // 两节点成对角型且它们的公共相邻节点存在障碍物 if (x != xx && y != yy && (qp[x][yy] == 1 || qp[xx][y] == 1)) return false; return true; }
[ "1072117118@qq.com" ]
1072117118@qq.com
2d028c03717ec52a818ab78a4a19ff8cea66829d
09e3925e225e2d3ea40245d48e8588dcf7ae3c07
/NeighbouringEnemy.cpp
0b2b3d5313e69064ef747fdf2a5d6f3d8d660165
[]
no_license
frankenstein32/Dynamic-Programming
f5e12e176184ff4c5efcdeb534ae6285bc3216c7
b81a2cdd65d19bd27ce9815d8b0bef8a688b9357
refs/heads/master
2021-10-10T12:03:00.238303
2021-10-01T09:08:19
2021-10-01T09:08:19
211,931,412
0
2
null
2020-10-06T13:34:35
2019-09-30T18:47:56
Java
UTF-8
C++
false
false
3,611
cpp
#include "algorithm" #include "iostream" #include "numeric" #include "iomanip" #include "cstring" #include "math.h" #include "bitset" #include "string" #include "vector" #include "ctime" #include "queue" #include "stack" #include "map" #include "set" #include "ext/pb_ds/assoc_container.hpp" // Common file #include "ext/pb_ds/tree_policy.hpp" // Including tree_order_statistics_node_update #include "ext/pb_ds/detail/standard_policies.hpp" using namespace std; using namespace __gnu_pbds; #define f first #define lgn 25 #define endl '\n' #define sc second #define pb push_back #define N (int)2e5+5 #define PI acos(-1.0) #define int long long #define vi vector<int> #define mod 1000000007 #define ld long double #define eb emplace_back #define mii map<int,int> #define vpii vector<pii> #define pii pair<int,int> #define pq priority_queue #define BLOCK (int)sqrt(N) #define test(x) while(x--) #define all(x) begin(x),end(x) #define allr(x) rbegin(x),rend(x) #define fo(i,a,n) for(int i=a;i<n;i++) #define rfo(i,n,a) for(int i=n;i>=a;i--) #define FAST ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); #define time() cerr << "Time : " << (double)clock() / (double)CLOCKS_PER_SEC << "s\n" #define bug(...) __f (#__VA_ARGS__, __VA_ARGS__) typedef tree< int, null_type, less<int>, rb_tree_tag, tree_order_statistics_node_update > OS ; template <typename Arg1> void __f (const char* name, Arg1&& arg1) { cout << name << " : " << arg1 << endl; } template <typename Arg1, typename... Args> void __f (const char* names, Arg1&& arg1, Args&&... args) { const char* comma = strchr (names + 1, ','); cout.write (names, comma - names) << " : " << arg1 << " | "; __f (comma + 1, args...); } const int inf = 0x3f3f3f3f; const int INF = 0x3f3f3f3f3f3f3f3f; int n,m,k,q; string s; vi adj[N]; int a[N] , dp[N][2]; // dp[i][0] -> maximum sum not taking ith // dp[i][1] -> maximum sum taking ith void go() { cin >> n; fo(i,1,n+1) cin >> a[i]; sort( a + 1 , a + 1 + n ); // so that next element will always greater or previous + 1 dp[1][1] = a[1]; // taken 1st dp[1][0] = 0; // not taken int pre = a[1]; fo(i,2,n+1) { if( a[i] == pre ) // same as previous { dp[i][1] = dp[i-1][1] + a[i]; // previoud taken + now taken dp[i][0] = dp[i-1][0]; // not taken as of previous } else if( a[i] == pre + 1 ) { dp[i][1] = dp[i-1][0] + a[i]; // if taking this one then now sum will be previous not taken + now a[i] dp[i][0] = max( dp[i-1][0] , dp[i-1][1] ); // if not taking this one , update not taking till now as maximum of not taking of previous and taking of previous } else { dp[i][1] = max( dp[i-1][1] + a[i] , dp[i-1][0] + a[i] ); // here element is greater than previous + 1 -> can make answer with both maximum sum of previously taken and not taken dp[i][0] = max( dp[i-1][0] , dp[i-1][1] );//// if not taking this one , update not taking till now as maximum of not taking of previous and taking of previous } pre = a[i]; } int ans = max( dp[n][0] , dp[n][1] ); // maximum of taking last or not cout << ans << endl; } int32_t main() { FAST; int t=1; // cin>>t; test(t) go(); }
[ "noreply@github.com" ]
frankenstein32.noreply@github.com
88e78929c23e138486ca606abc87344660912868
dc37fe84633264f6c829d69d3f41b64760584a64
/OpenGLConfig/indexbuffer.cpp
e1d41267973ac43a7da8d1aa3a8b8da48c0657c5
[]
no_license
Hyperionlucky/SuperGis
fa958be38ed369ab659d9ad778c5e04f4b9f29c6
99fb4ca20a68328745d4c2d6440cdf424154720d
refs/heads/master
2020-12-27T14:30:12.030399
2020-02-03T10:29:50
2020-02-03T10:29:50
237,936,106
0
0
null
null
null
null
UTF-8
C++
false
false
716
cpp
#include "indexbuffer.h" #include "glcall.h" IndexBuffer::IndexBuffer(const unsigned int* data, unsigned int count, unsigned int modeIn) : count(count), mode(modeIn) { ASSERT(sizeof(unsigned int) == sizeof(GLuint)); GLCall(glGenBuffers(1, &rendererID)); GLCall(glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, rendererID)); GLCall(glBufferData(GL_ELEMENT_ARRAY_BUFFER, count * sizeof(unsigned int), data, GL_STATIC_DRAW)); } IndexBuffer::~IndexBuffer() { GLCall(glDeleteBuffers(1, &rendererID)); } void IndexBuffer::Bind() const { GLCall(glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, rendererID)); } void IndexBuffer::Unbind() const { GLCall(glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0)); }
[ "1943414735@qq.com" ]
1943414735@qq.com
e3fed17e4f134d3a4586de28c294c9e74c534a9c
4d42762ddb5034b84585170ca320f9903024fa7f
/build/iOS/Debug/include/Fuse.Controls.Panel.h
a25e469abcbeea3d347648186595632321b46bf9
[]
no_license
nikitph/omkareshwar-ios
536def600f378946b95362e2e2f98f8f52b588e0
852a1d802b76dbc61c2c45164f180004b7d667e6
refs/heads/master
2021-01-01T18:58:16.397969
2017-08-01T18:53:20
2017-08-01T18:53:20
98,473,502
0
0
null
null
null
null
UTF-8
C++
false
false
4,656
h
// This file was generated based on '/Users/Omkareshwar/Library/Application Support/Fusetools/Packages/Fuse.Controls.Panels/1.1.1/$.uno'. // WARNING: Changes might be lost if you edit this file directly. #pragma once #include <Fuse.Animations.IResize.h> #include <Fuse.Binding.h> #include <Fuse.Controls.LayoutControl.h> #include <Fuse.Drawing.ISurfaceDrawable.h> #include <Fuse.IActualPlacement.h> #include <Fuse.INotifyUnrooted.h> #include <Fuse.IProperties.h> #include <Fuse.Node.h> #include <Fuse.Scripting.IScriptObject.h> #include <Fuse.Triggers.Actions.ICollapse.h> #include <Fuse.Triggers.Actions.IHide.h> #include <Fuse.Triggers.Actions.IShow.h> #include <Uno.Collections.ICollection-1.h> #include <Uno.Collections.IEnumerable-1.h> #include <Uno.Collections.IList-1.h> #include <Uno.Float2.h> #include <Uno.UX.IPropertyListener.h> namespace g{namespace Fuse{namespace Controls{struct Panel;}}} namespace g{namespace Fuse{namespace Drawing{struct Surface;}}} namespace g{namespace Fuse{namespace Triggers{struct BusyTask;}}} namespace g{namespace Fuse{struct DrawContext;}} namespace g{namespace Fuse{struct LayoutParams;}} namespace g{namespace Fuse{struct VisualBounds;}} namespace g{namespace Uno{namespace Graphics{struct Framebuffer;}}} namespace g{namespace Uno{namespace UX{struct Selector;}}} namespace g{namespace Uno{struct Float4;}} namespace g{ namespace Fuse{ namespace Controls{ // public partial class Panel :1941 // { struct Panel_type : ::g::Fuse::Controls::Control_type { ::g::Fuse::Drawing::ISurfaceDrawable interface15; }; Panel_type* Panel_typeof(); void Panel__ctor_6_fn(Panel* __this); void Panel__ArrangePaddingBox_fn(Panel* __this, ::g::Fuse::LayoutParams* lp); void Panel__CleanupBuffer_fn(Panel* __this); void Panel__CleanupListener_fn(Panel* __this, bool* nextFrame); void Panel__get_Color_fn(Panel* __this, ::g::Uno::Float4* __retval); void Panel__set_Color_fn(Panel* __this, ::g::Uno::Float4* value); void Panel__get_DeferFreeze_fn(Panel* __this, int* __retval); void Panel__set_DeferFreeze_fn(Panel* __this, int* value); void Panel__Draw_fn(Panel* __this, ::g::Fuse::DrawContext* dc); void Panel__EndBusy_fn(Panel* __this); void Panel__FastTrackDrawWithOpacity_fn(Panel* __this, ::g::Fuse::DrawContext* dc, bool* __retval); void Panel__FreezeRooted_fn(Panel* __this); void Panel__FreezeUnrooted_fn(Panel* __this); void Panel__FuseDrawingISurfaceDrawableDraw_fn(Panel* __this, ::g::Fuse::Drawing::Surface* surface); void Panel__FuseDrawingISurfaceDrawableget_ElementSize_fn(Panel* __this, ::g::Uno::Float2* __retval); void Panel__GetContentSize_fn(Panel* __this, ::g::Fuse::LayoutParams* lp, ::g::Uno::Float2* __retval); void Panel__get_HasFreezePrepared_fn(Panel* __this, bool* __retval); void Panel__get_IsFrozen_fn(Panel* __this, bool* __retval); void Panel__set_IsFrozen_fn(Panel* __this, bool* value); void Panel__get_IsLayoutRoot_fn(Panel* __this, bool* __retval); void Panel__get_LocalRenderBounds_fn(Panel* __this, ::g::Fuse::VisualBounds** __retval); void Panel__New3_fn(Panel** __retval); void Panel__OnColorChanged_fn(Panel* __this, ::g::Uno::Float4* value, uObject* origin); void Panel__OnPrepared_fn(Panel* __this, ::g::Fuse::DrawContext* dc); void Panel__OnRooted_fn(Panel* __this); void Panel__OnUnrooted_fn(Panel* __this); void Panel__get_Scale_fn(Panel* __this, ::g::Uno::Float2* __retval); void Panel__SetColor_fn(Panel* __this, ::g::Uno::Float4* value, uObject* origin); void Panel__SetupListener_fn(Panel* __this); struct Panel : ::g::Fuse::Controls::LayoutControl { int _deferFreeze; bool _freezeAwaitPrepared; uStrong< ::g::Fuse::Triggers::BusyTask*> _freezeBusyTask; ::g::Uno::Float2 _frozenActualSize; uStrong< ::g::Uno::Graphics::Framebuffer*> _frozenBuffer; uStrong< ::g::Fuse::VisualBounds*> _frozenRenderBounds; bool _isFrozen; static ::g::Uno::UX::Selector ColorPropertyName_; static ::g::Uno::UX::Selector& ColorPropertyName() { return Panel_typeof()->Init(), ColorPropertyName_; } void ctor_6(); void CleanupBuffer(); void CleanupListener(bool nextFrame); ::g::Uno::Float4 Color(); void Color(::g::Uno::Float4 value); int DeferFreeze(); void DeferFreeze(int value); void EndBusy(); void FreezeRooted(); void FreezeUnrooted(); bool HasFreezePrepared(); bool IsFrozen(); void IsFrozen(bool value); void OnColorChanged(::g::Uno::Float4 value, uObject* origin); void OnPrepared(::g::Fuse::DrawContext* dc); ::g::Uno::Float2 Scale(); void SetColor(::g::Uno::Float4 value, uObject* origin); void SetupListener(); static Panel* New3(); }; // } }}} // ::g::Fuse::Controls
[ "nikitph@gmail.com" ]
nikitph@gmail.com
b6c07b2b3d14df4bf3e34a36d9e0800e65fbd560
a7764174fb0351ea666faa9f3b5dfe304390a011
/inc/StepElement_ElementAspect.hxx
92c10c2938acecb17b7ca6b21960d351454af9ff
[]
no_license
uel-dataexchange/Opencascade_uel
f7123943e9d8124f4fa67579e3cd3f85cfe52d91
06ec93d238d3e3ea2881ff44ba8c21cf870435cd
refs/heads/master
2022-11-16T07:40:30.837854
2020-07-08T01:56:37
2020-07-08T01:56:37
276,290,778
0
0
null
null
null
null
UTF-8
C++
false
false
5,151
hxx
// This file is generated by WOK (CPPExt). // Please do not edit this file; modify original file instead. // The copyright and license terms as defined for the original file apply to // this header file considered to be the "object code" form of the original source. #ifndef _StepElement_ElementAspect_HeaderFile #define _StepElement_ElementAspect_HeaderFile #ifndef _Standard_HeaderFile #include <Standard.hxx> #endif #ifndef _Standard_Macro_HeaderFile #include <Standard_Macro.hxx> #endif #ifndef _StepData_SelectType_HeaderFile #include <StepData_SelectType.hxx> #endif #ifndef _Standard_Integer_HeaderFile #include <Standard_Integer.hxx> #endif #ifndef _Handle_Standard_Transient_HeaderFile #include <Handle_Standard_Transient.hxx> #endif #ifndef _Handle_StepData_SelectMember_HeaderFile #include <Handle_StepData_SelectMember.hxx> #endif #ifndef _StepElement_ElementVolume_HeaderFile #include <StepElement_ElementVolume.hxx> #endif #ifndef _StepElement_CurveEdge_HeaderFile #include <StepElement_CurveEdge.hxx> #endif class Standard_Transient; class StepData_SelectMember; //! Representation of STEP SELECT type ElementAspect <br> class StepElement_ElementAspect : public StepData_SelectType { public: void* operator new(size_t,void* anAddress) { return anAddress; } void* operator new(size_t size) { return Standard::Allocate(size); } void operator delete(void *anAddress) { if (anAddress) Standard::Free((Standard_Address&)anAddress); } //! Empty constructor <br> Standard_EXPORT StepElement_ElementAspect(); //! Recognizes a kind of ElementAspect select type <br> //! return 0 <br> Standard_EXPORT Standard_Integer CaseNum(const Handle(Standard_Transient)& ent) const; //! Recognizes a items of select member ElementAspectMember <br> //! 1 -> ElementVolume <br> //! 2 -> Volume3dFace <br> //! 3 -> Volume2dFace <br> //! 4 -> Volume3dEdge <br> //! 5 -> Volume2dEdge <br> //! 6 -> Surface3dFace <br> //! 7 -> Surface2dFace <br> //! 8 -> Surface3dEdge <br> //! 9 -> Surface2dEdge <br> //! 10 -> CurveEdge <br> //! 0 else <br> Standard_EXPORT virtual Standard_Integer CaseMem(const Handle(StepData_SelectMember)& ent) const; //! Returns a new select member the type ElementAspectMember <br> Standard_EXPORT virtual Handle_StepData_SelectMember NewMember() const; //! Set Value for ElementVolume <br> Standard_EXPORT void SetElementVolume(const StepElement_ElementVolume aVal) ; //! Returns Value as ElementVolume (or Null if another type) <br> Standard_EXPORT StepElement_ElementVolume ElementVolume() const; //! Set Value for Volume3dFace <br> Standard_EXPORT void SetVolume3dFace(const Standard_Integer aVal) ; //! Returns Value as Volume3dFace (or Null if another type) <br> Standard_EXPORT Standard_Integer Volume3dFace() const; //! Set Value for Volume2dFace <br> Standard_EXPORT void SetVolume2dFace(const Standard_Integer aVal) ; //! Returns Value as Volume2dFace (or Null if another type) <br> Standard_EXPORT Standard_Integer Volume2dFace() const; //! Set Value for Volume3dEdge <br> Standard_EXPORT void SetVolume3dEdge(const Standard_Integer aVal) ; //! Returns Value as Volume3dEdge (or Null if another type) <br> Standard_EXPORT Standard_Integer Volume3dEdge() const; //! Set Value for Volume2dEdge <br> Standard_EXPORT void SetVolume2dEdge(const Standard_Integer aVal) ; //! Returns Value as Volume2dEdge (or Null if another type) <br> Standard_EXPORT Standard_Integer Volume2dEdge() const; //! Set Value for Surface3dFace <br> Standard_EXPORT void SetSurface3dFace(const Standard_Integer aVal) ; //! Returns Value as Surface3dFace (or Null if another type) <br> Standard_EXPORT Standard_Integer Surface3dFace() const; //! Set Value for Surface2dFace <br> Standard_EXPORT void SetSurface2dFace(const Standard_Integer aVal) ; //! Returns Value as Surface2dFace (or Null if another type) <br> Standard_EXPORT Standard_Integer Surface2dFace() const; //! Set Value for Surface3dEdge <br> Standard_EXPORT void SetSurface3dEdge(const Standard_Integer aVal) ; //! Returns Value as Surface3dEdge (or Null if another type) <br> Standard_EXPORT Standard_Integer Surface3dEdge() const; //! Set Value for Surface2dEdge <br> Standard_EXPORT void SetSurface2dEdge(const Standard_Integer aVal) ; //! Returns Value as Surface2dEdge (or Null if another type) <br> Standard_EXPORT Standard_Integer Surface2dEdge() const; //! Set Value for CurveEdge <br> Standard_EXPORT void SetCurveEdge(const StepElement_CurveEdge aVal) ; //! Returns Value as CurveEdge (or Null if another type) <br> Standard_EXPORT StepElement_CurveEdge CurveEdge() const; protected: private: }; // other Inline functions and methods (like "C++: function call" methods) #endif
[ "shoka.sho2@excel.co.jp" ]
shoka.sho2@excel.co.jp
2cf5faa0ac801941a562ffef5740446db93e309a
d022883d70d769802dc9f22a5a34759558e06193
/src/network/Server.h
af1cada8ebd3809e63abaf11cd66232ed6eec22d
[]
no_license
sokyu-project/sokyu-node
1599e9859a4b08ec29bba8b1f14230807bed8d3a
c3c3b2968d237e8067ac11bafd142d734c6006da
refs/heads/main
2023-03-02T01:48:24.014655
2021-01-28T05:24:58
2021-01-28T05:24:58
333,637,977
0
0
null
null
null
null
UTF-8
C++
false
false
904
h
#ifndef SERVER_H #define SERVER_H #include <sys/types.h> #include <sys/socket.h> #include <arpa/inet.h> #include <netinet/in.h> #include <thread> #include <atomic> #include <mutex> #include "NetworkHandler.h" // Simple TCP server we will use to communicate with other nodes and respond to requests typedef unsigned char byte; class Server { public: Server(int port); virtual ~Server(); bool init(); bool run(std::unique_ptr<NetworkHandler>& handler); void shutdown(); std::atomic<bool> shouldStop; void addSocket(int newSocket); protected: private: int port; int sockfd; byte buffer[2048]; fd_set clientFds; std::mutex socketsMutex; int clientSockets[50]; int maxClients = 50; struct sockaddr_in servaddr; std::thread sThread; }; #endif // SERVER_H
[ "nnemo288@gmail.com" ]
nnemo288@gmail.com
6a24f7c5cc162449b7a66a56e4492725553bb643
404fb17c7661b6fd0085234decd66618722a93b6
/Scripts/BDT/neutral_bdt_train.cxx
962935aa83173805778d1b089413742b4213756f
[]
no_license
ionic-corinthian/Analysis
3485c0be13dfbe531b8cc3029905f0920bfaa991
439d238e313a0441cc0665ec4fb47d7dabdbcae9
refs/heads/master
2020-03-17T17:25:58.236033
2018-05-17T10:11:55
2018-05-17T10:11:55
133,788,080
0
0
null
2018-05-17T09:26:14
2018-05-17T09:08:29
C++
UTF-8
C++
false
false
6,128
cxx
#include <cstdlib> #include <iostream> #include <map> #include <string> #include "TChain.h" #include "TFile.h" #include "TTree.h" #include "TString.h" #include "TObjString.h" #include "TSystem.h" #include "TROOT.h" #include "TMVA/Factory.h" // #include "TMVA/DataLoader.h" #include "TMVA/Tools.h" #include "TMVA/TMVAGui.h" #include "myDecay.cxx" void neutral_bdt_train(const char* TupleName, int year, const char* mag, const char* charge, bool all_mc=false, bool all_data=false) { //=====================// //=== Prepare files ===// //=====================// //=== Setup TMVA ===// TMVA::Tools::Instance(); //=== Open a new file to save the BDT output ===// TFile* outputFile = TFile::Open(Form("/data/lhcb/users/colmmurphy/ReducedTrees/%i/Mag%s/%sCharge/neut_BDT_Output_%s.root", year, mag, charge, TupleName), "RECREATE"); //=== Get instance of TMVA factory to use for training ===// TString fac_name; if (all_mc && !all_data) fac_name = Form("AllMC_%s_%i_Mag%s_%sCharge", TupleName, year, mag, charge); else if (!all_mc && all_data) fac_name = Form("%s_AllDataYears_Mag%s_%sCharge", TupleName, mag, charge); else if (all_mc && all_data ) fac_name = Form("AllMC_%s_AllDataYears_Mag%s_%sCharge", TupleName, mag, charge); else fac_name = Form("%s_%i_Mag%s_%sCharge", TupleName, year, mag, charge); TMVA::Factory *factory = new TMVA::Factory((TString)("neut"+fac_name), outputFile, "V:!Silent:Color:Transformations=I:DrawProgressBar:AnalysisType=Classification"); //=== Weights ===// double signalWeight = 1.0; double backgroundWeight = 1.0; //=== Read in signal tree (MC which has been precut on truth matching info) ===// // if year is set to 999, then read in all MC! TChain* sigTree = new TChain("DecayTree"); if (all_mc) { sigTree->Add(Form("~/TruthMatchedTrees/2011/Mag%s/%sCharge/TM_%s_MC.root", mag, charge, TupleName)); sigTree->Add(Form("~/TruthMatchedTrees/2012/Mag%s/%sCharge/TM_%s_MC.root", mag, charge, TupleName)); sigTree->Add(Form("~/TruthMatchedTrees/2015/Mag%s/%sCharge/TM_%s_MC.root", mag, charge, TupleName)); sigTree->Add(Form("~/TruthMatchedTrees/2016/Mag%s/%sCharge/TM_%s_MC.root", mag, charge, TupleName)); } else sigTree->Add(Form("~/TruthMatchedTrees/%i/Mag%s/%sCharge/TM_%s_MC.root", year, mag, charge, TupleName)); //=== TChain data TTrees together (for mag up and mag down) ===// TChain* dataTree = new TChain("DecayTree"); if (all_data) { dataTree->Add(Form("/data/lhcb/users/colmmurphy/BDT_Output/2011/Mag%s/%sCharge/bkgcut_%s.root", mag, charge, TupleName)); dataTree->Add(Form("/data/lhcb/users/colmmurphy/BDT_Output/2012/Mag%s/%sCharge/bkgcut_%s.root", mag, charge, TupleName)); dataTree->Add(Form("/data/lhcb/users/colmmurphy/BDT_Output/2015/Mag%s/%sCharge/bkgcut_%s.root", mag, charge, TupleName)); dataTree->Add(Form("/data/lhcb/users/colmmurphy/BDT_Output/2016/Mag%s/%sCharge/bkgcut_%s.root", mag, charge, TupleName)); dataTree->Add(Form("/data/lhcb/users/colmmurphy/BDT_Output/2017/Mag%s/%sCharge/bkgcut_%s.root", mag, charge, TupleName)); } else dataTree->Add(Form("/data/lhcb/users/colmmurphy/BDT_Output/%i/Mag%s/%sCharge/bkgcut_%s.root", year, mag, charge, TupleName)); //=== Add the signal and background (i.e. real data) to the BDT trainer ===// factory->AddSignalTree(sigTree, signalWeight); factory->AddBackgroundTree(dataTree, backgroundWeight); std::cout << "--- ADDED TREES SUCCESSFULLY!" << std::endl; //=== Signal has been previously truth matched. Background cut to be in upper B mass sideband ===// //=== Additional cuts are to ensure negative values are not logged! ===// TCut sigcut = ""; TCut bkgcut = ""; //Bu_M>5900. && D0_MIPCHI2_PV<0. && Bach_MIPCHI2_PV<0. && K0_MIPCHI2_PV<0. && P0_MIPCHI2_PV<0. && Bu_FDCHI2_OWNPV<0. && D0_FDCHI2_OWNPV<0. && Bu_DIRA_BPV>1. && D0_DIRA_BPV>1. //=========================================// //=== Add NTuple variables for training ===// //=========================================// //=== Particle momenta ===// factory->AddVariable("Pi0_PT", 'F'); factory->AddVariable("Gamma1_PT", 'F'); factory->AddVariable("Gamma2_PT", 'F'); // factory->AddVariable("Pi0_P", 'F'); // factory->AddVariable("Pi0_PE", 'F'); // factory->AddVariable("Pi0_PX", 'F'); // factory->AddVariable("Pi0_PY", 'F'); // factory->AddVariable("Pi0_PZ", 'F'); //=== Neutral particle variables ===// factory->AddVariable("Gamma1_CL", 'F'); factory->AddVariable("Gamma2_CL", 'F'); // factory->AddVariable("Pi0_ptasy_1.50", 'F'); // factory->AddVariable("Gamma1_ptasy_1.50", 'F'); // factory->AddVariable("Gamma2_ptasy_1.50", 'F'); factory->AddVariable("Gamma1_PP_IsNotE", 'F'); factory->AddVariable("Gamma2_PP_IsNotE", 'F'); std::cout << "--- ADDED VARIABLES SUCCESSFULLY!" << std::endl; //====================================// //=== Run the BDT training/testing ===// //====================================// factory->PrepareTrainingAndTestTree(sigcut,bkgcut,"random"); //=== Add different MVA methods to test here! ===// factory->BookMethod(TMVA::Types::kBDT,"BDT","NTrees=600:MaxDepth=4"); // factory->BookMethod(TMVA::Types::kBDT,"More_Depth","NTrees=400:MaxDepth=8"); // factory->BookMethod(TMVA::Types::kBDT,"More_Trees","NTrees=800:MaxDepth=4"); // factory->BookMethod(TMVA::Types::kBDT,"More_Depth_and_Trees","NTrees=800:MaxDepth=8"); // factory->BookMethod( TMVA::Types::kBDT, "BDTG","!H:!V:NTrees=1000:BoostType=Grad:Shrinkage=0.30:UseBaggedGrad:\GradBaggingFraction=0.6:SeparationType=GiniIndex:nCuts=20:\PruneMethod=CostComplexity:PruneStrength=50:NNodesMax=5" ); std::cout << "--- ABOUT TO TRAIN METHODS!" << std::endl; //=== Train, test, then evaluate all methods ===// factory->TrainAllMethods(); factory->TestAllMethods(); factory->EvaluateAllMethods(); outputFile->Close(); }
[ "colmmurphy@pplxint8.physics.ox.ac.uk" ]
colmmurphy@pplxint8.physics.ox.ac.uk
845243c8f6b344556cccc35b4fa50e25132b9b5b
4f81df57bea3c8689e0ddc2b2315d2a0d1528d0d
/CK3toEU4/Source/Mappers/CultureMapper/CultureMapper.cpp
f2c3225567dc56923c5edd0870890766c90d964a
[ "MIT" ]
permissive
AquosPoke206/CK3toEU4
25e04b50eced45ba769287764ada6f82897749e5
27f1c28281a0f560ffaf2136b1f4c8332257943c
refs/heads/master
2023-01-03T09:32:53.256805
2020-10-22T09:24:14
2020-10-22T09:24:14
300,824,830
0
0
MIT
2020-10-22T09:24:15
2020-10-03T07:41:51
null
UTF-8
C++
false
false
2,842
cpp
#include "CultureMapper.h" #include "Log.h" #include "ParserHelpers.h" mappers::CultureMapper::CultureMapper(std::istream& theStream) { registerKeys(); parseStream(theStream); clearRegisteredKeywords(); } mappers::CultureMapper::CultureMapper() { LOG(LogLevel::Info) << "-> Parsing culture mappings."; registerKeys(); parseFile("configurables/culture_map.txt"); clearRegisteredKeywords(); LOG(LogLevel::Info) << "<> Loaded " << cultureMapRules.size() << " cultural links."; } void mappers::CultureMapper::loadRegionMapper(const std::shared_ptr<RegionMapper>& theRegionMapper) { for (auto& rule: cultureMapRules) rule.insertRegionMapper(theRegionMapper); } void mappers::CultureMapper::registerKeys() { registerKeyword("link", [this](const std::string& unused, std::istream& theStream) { const CultureMappingRule rule(theStream); cultureMapRules.push_back(rule); }); registerRegex(commonItems::catchallRegex, commonItems::ignoreItem); } std::optional<std::string> mappers::CultureMapper::cultureMatch(const std::string& ck3culture, const std::string& eu4religion, int eu4Province, const std::string& eu4ownerTag) const { for (const auto& cultureMappingRule: cultureMapRules) { const auto& possibleMatch = cultureMappingRule.cultureMatch(ck3culture, eu4religion, eu4Province, eu4ownerTag); if (possibleMatch) return *possibleMatch; } return std::nullopt; } std::optional<std::string> mappers::CultureMapper::cultureRegionalMatch(const std::string& ck3culture, const std::string& eu4religion, int eu4Province, const std::string& eu4ownerTag) const { for (const auto& cultureMappingRule: cultureMapRules) { const auto& possibleMatch = cultureMappingRule.cultureRegionalMatch(ck3culture, eu4religion, eu4Province, eu4ownerTag); if (possibleMatch) return *possibleMatch; } return std::nullopt; } std::optional<std::string> mappers::CultureMapper::cultureNonRegionalNonReligiousMatch(const std::string& ck3culture, const std::string& eu4religion, int eu4Province, const std::string& eu4ownerTag) const { for (const auto& cultureMappingRule: cultureMapRules) { const auto& possibleMatch = cultureMappingRule.cultureNonRegionalNonReligiousMatch(ck3culture, eu4religion, eu4Province, eu4ownerTag); if (possibleMatch) return *possibleMatch; } return std::nullopt; } std::optional<std::string> mappers::CultureMapper::getTechGroup(const std::string& incEU4Culture) const { for (const auto& mapping: cultureMapRules) if (mapping.getTechGroup(incEU4Culture)) return mapping.getTechGroup(incEU4Culture); return std::nullopt; } std::optional<std::string> mappers::CultureMapper::getGFX(const std::string& incEU4Culture) const { for (const auto& mapping: cultureMapRules) if (mapping.getGFX(incEU4Culture)) return mapping.getGFX(incEU4Culture); return std::nullopt; }
[ "noreply@github.com" ]
AquosPoke206.noreply@github.com
6b51fa81ff2a0ee1a387dbfc4d14a0869712166b
8bef7aa0c6c24b6897c407450052aecb357399c0
/spoj/PT07Y.cpp
46a500bb73ad2ef5f96902af0250527169b3c134
[]
no_license
faishol01/cp-solution
05792f507298b1317fe093a5614c2d976b00d75d
8a3c5984630019c48180d6d46ffcfae7a1bf228e
refs/heads/master
2018-10-08T10:26:41.518706
2018-06-24T23:40:03
2018-06-24T23:40:03
77,578,760
1
1
null
null
null
null
UTF-8
C++
false
false
847
cpp
#include <bits/stdc++.h> using namespace std; #define ll long long #define ull unsigned long long /* 5 4 1 2 2 3 3 1 4 5 */ ll n,m; bool stt=true; vector < vector<int> > adjList; vector <bool> visit; void DFS(int node){ visit[node]=1; for(int i=0;i<adjList[node].size();i++){ int x = adjList[node][i]; if(!visit[x]){ DFS(x); } } } int main(){ cin >> n >> m; if(n-m != 1) stt = false; adjList.resize(n); visit.resize(n,0); for(int i=0;i<m;i++){ int a,b; cin >> a >> b; adjList[a-1].push_back(b-1); adjList[b-1].push_back(a-1); if(a == b) stt = false; } if(stt){ DFS(0); for(int i=0;i<n;i++){ if(visit[i]==0){ cout << "NO\n"; return 0; } } cout << "YES\n"; }else{ cout << "NO\n"; } return 0; }
[ "noreply@github.com" ]
faishol01.noreply@github.com
7acdde4794f58997746ce847d49b42d872517820
d8ae6672046671d5fbdb33c81d557e6384d85731
/src/wallet.cpp
985d588a2bf87931eb4d6533a28d5880eebb8345
[ "GPL-3.0-only", "LicenseRef-scancode-free-unknown", "MIT" ]
permissive
Phikzel2/haroldcoin-main-23-may
74862be1e864e8397c7c0fa6e4b9216ed7d9cdbe
f617bb8aa7dbcce1310312f0062a1caf6ebf268c
refs/heads/main
2023-05-05T08:27:37.573453
2021-05-26T19:32:49
2021-05-26T19:32:49
371,049,557
0
0
MIT
2021-05-26T13:46:30
2021-05-26T13:46:29
null
UTF-8
C++
false
false
132,273
cpp
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2014 The Bitcoin developers // Copyright (c) 2014-2015 The Dash developers // Copyright (c) 2015-2017 The PIVX developers // Copyright (c) 2017-2018 The haroldcoin developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "wallet.h" #include "base58.h" #include "checkpoints.h" #include "coincontrol.h" #include "kernel.h" #include "masternode-budget.h" #include "net.h" #include "script/script.h" #include "script/sign.h" #include "spork.h" #include "swifttx.h" #include "timedata.h" #include "util.h" #include "utilmoneystr.h" #include <assert.h> #include <boost/algorithm/string/replace.hpp> #include <boost/thread.hpp> using namespace std; /** * Settings */ CFeeRate payTxFee(DEFAULT_TRANSACTION_FEE); CAmount maxTxFee = DEFAULT_TRANSACTION_MAXFEE; unsigned int nTxConfirmTarget = 1; bool bSpendZeroConfChange = true; bool fSendFreeTransactions = false; bool fPayAtLeastCustomFee = true; /** * Fees smaller than this (in duffs) are considered zero fee (for transaction creation) * We are ~100 times smaller then bitcoin now (2015-06-23), set minTxFee 10 times higher * so it's still 10 times lower comparing to bitcoin. * Override with -mintxfee */ CFeeRate CWallet::minTxFee = CFeeRate(10000); /** @defgroup mapWallet * * @{ */ struct CompareValueOnly { bool operator()(const pair<CAmount, pair<const CWalletTx*, unsigned int> >& t1, const pair<CAmount, pair<const CWalletTx*, unsigned int> >& t2) const { return t1.first < t2.first; } }; std::string COutput::ToString() const { return strprintf("COutput(%s, %d, %d) [%s]", tx->GetHash().ToString(), i, nDepth, FormatMoney(tx->vout[i].nValue)); } const CWalletTx* CWallet::GetWalletTx(const uint256& hash) const { LOCK(cs_wallet); std::map<uint256, CWalletTx>::const_iterator it = mapWallet.find(hash); if (it == mapWallet.end()) return NULL; return &(it->second); } CPubKey CWallet::GenerateNewKey() { AssertLockHeld(cs_wallet); // mapKeyMetadata bool fCompressed = CanSupportFeature(FEATURE_COMPRPUBKEY); // default to compressed public keys if we want 0.6.0 wallets RandAddSeedPerfmon(); CKey secret; secret.MakeNewKey(fCompressed); // Compressed public keys were introduced in version 0.6.0 if (fCompressed) SetMinVersion(FEATURE_COMPRPUBKEY); CPubKey pubkey = secret.GetPubKey(); assert(secret.VerifyPubKey(pubkey)); // Create new metadata int64_t nCreationTime = GetTime(); mapKeyMetadata[pubkey.GetID()] = CKeyMetadata(nCreationTime); if (!nTimeFirstKey || nCreationTime < nTimeFirstKey) nTimeFirstKey = nCreationTime; if (!AddKeyPubKey(secret, pubkey)) throw std::runtime_error("CWallet::GenerateNewKey() : AddKey failed"); return pubkey; } bool CWallet::AddKeyPubKey(const CKey& secret, const CPubKey& pubkey) { AssertLockHeld(cs_wallet); // mapKeyMetadata if (!CCryptoKeyStore::AddKeyPubKey(secret, pubkey)) return false; // check if we need to remove from watch-only CScript script; script = GetScriptForDestination(pubkey.GetID()); if (HaveWatchOnly(script)) RemoveWatchOnly(script); if (!fFileBacked) return true; if (!IsCrypted()) { return CWalletDB(strWalletFile).WriteKey(pubkey, secret.GetPrivKey(), mapKeyMetadata[pubkey.GetID()]); } return true; } bool CWallet::AddCryptedKey(const CPubKey& vchPubKey, const vector<unsigned char>& vchCryptedSecret) { if (!CCryptoKeyStore::AddCryptedKey(vchPubKey, vchCryptedSecret)) return false; if (!fFileBacked) return true; { LOCK(cs_wallet); if (pwalletdbEncryption) return pwalletdbEncryption->WriteCryptedKey(vchPubKey, vchCryptedSecret, mapKeyMetadata[vchPubKey.GetID()]); else return CWalletDB(strWalletFile).WriteCryptedKey(vchPubKey, vchCryptedSecret, mapKeyMetadata[vchPubKey.GetID()]); } return false; } bool CWallet::LoadKeyMetadata(const CPubKey& pubkey, const CKeyMetadata& meta) { AssertLockHeld(cs_wallet); // mapKeyMetadata if (meta.nCreateTime && (!nTimeFirstKey || meta.nCreateTime < nTimeFirstKey)) nTimeFirstKey = meta.nCreateTime; mapKeyMetadata[pubkey.GetID()] = meta; return true; } bool CWallet::LoadCryptedKey(const CPubKey& vchPubKey, const std::vector<unsigned char>& vchCryptedSecret) { return CCryptoKeyStore::AddCryptedKey(vchPubKey, vchCryptedSecret); } bool CWallet::AddCScript(const CScript& redeemScript) { if (!CCryptoKeyStore::AddCScript(redeemScript)) return false; if (!fFileBacked) return true; return CWalletDB(strWalletFile).WriteCScript(Hash160(redeemScript), redeemScript); } bool CWallet::LoadCScript(const CScript& redeemScript) { /* A sanity check was added in pull #3843 to avoid adding redeemScripts * that never can be redeemed. However, old wallets may still contain * these. Do not add them to the wallet and warn. */ if (redeemScript.size() > MAX_SCRIPT_ELEMENT_SIZE) { std::string strAddr = CBitcoinAddress(CScriptID(redeemScript)).ToString(); LogPrintf("%s: Warning: This wallet contains a redeemScript of size %i which exceeds maximum size %i thus can never be redeemed. Do not use address %s.\n", __func__, redeemScript.size(), MAX_SCRIPT_ELEMENT_SIZE, strAddr); return true; } return CCryptoKeyStore::AddCScript(redeemScript); } bool CWallet::AddWatchOnly(const CScript& dest) { if (!CCryptoKeyStore::AddWatchOnly(dest)) return false; nTimeFirstKey = 1; // No birthday information for watch-only keys. NotifyWatchonlyChanged(true); if (!fFileBacked) return true; return CWalletDB(strWalletFile).WriteWatchOnly(dest); } bool CWallet::RemoveWatchOnly(const CScript& dest) { AssertLockHeld(cs_wallet); if (!CCryptoKeyStore::RemoveWatchOnly(dest)) return false; if (!HaveWatchOnly()) NotifyWatchonlyChanged(false); if (fFileBacked) if (!CWalletDB(strWalletFile).EraseWatchOnly(dest)) return false; return true; } bool CWallet::LoadWatchOnly(const CScript& dest) { return CCryptoKeyStore::AddWatchOnly(dest); } bool CWallet::AddMultiSig(const CScript& dest) { if (!CCryptoKeyStore::AddMultiSig(dest)) return false; nTimeFirstKey = 1; // No birthday information NotifyMultiSigChanged(true); if (!fFileBacked) return true; return CWalletDB(strWalletFile).WriteMultiSig(dest); } bool CWallet::RemoveMultiSig(const CScript& dest) { AssertLockHeld(cs_wallet); if (!CCryptoKeyStore::RemoveMultiSig(dest)) return false; if (!HaveMultiSig()) NotifyMultiSigChanged(false); if (fFileBacked) if (!CWalletDB(strWalletFile).EraseMultiSig(dest)) return false; return true; } bool CWallet::LoadMultiSig(const CScript& dest) { return CCryptoKeyStore::AddMultiSig(dest); } bool CWallet::Unlock(const SecureString& strWalletPassphrase, bool anonymizeOnly) { SecureString strWalletPassphraseFinal; if (!IsLocked()) { fWalletUnlockAnonymizeOnly = anonymizeOnly; return true; } strWalletPassphraseFinal = strWalletPassphrase; CCrypter crypter; CKeyingMaterial vMasterKey; { LOCK(cs_wallet); BOOST_FOREACH (const MasterKeyMap::value_type& pMasterKey, mapMasterKeys) { if (!crypter.SetKeyFromPassphrase(strWalletPassphraseFinal, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod)) return false; if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, vMasterKey)) continue; // try another master key if (CCryptoKeyStore::Unlock(vMasterKey)) { fWalletUnlockAnonymizeOnly = anonymizeOnly; return true; } } } return false; } bool CWallet::ChangeWalletPassphrase(const SecureString& strOldWalletPassphrase, const SecureString& strNewWalletPassphrase) { bool fWasLocked = IsLocked(); SecureString strOldWalletPassphraseFinal = strOldWalletPassphrase; { LOCK(cs_wallet); Lock(); CCrypter crypter; CKeyingMaterial vMasterKey; BOOST_FOREACH (MasterKeyMap::value_type& pMasterKey, mapMasterKeys) { if (!crypter.SetKeyFromPassphrase(strOldWalletPassphraseFinal, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod)) return false; if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, vMasterKey)) return false; if (CCryptoKeyStore::Unlock(vMasterKey)) { int64_t nStartTime = GetTimeMillis(); crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod); pMasterKey.second.nDeriveIterations = pMasterKey.second.nDeriveIterations * (100 / ((double)(GetTimeMillis() - nStartTime))); nStartTime = GetTimeMillis(); crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod); pMasterKey.second.nDeriveIterations = (pMasterKey.second.nDeriveIterations + pMasterKey.second.nDeriveIterations * 100 / ((double)(GetTimeMillis() - nStartTime))) / 2; if (pMasterKey.second.nDeriveIterations < 25000) pMasterKey.second.nDeriveIterations = 25000; LogPrintf("Wallet passphrase changed to an nDeriveIterations of %i\n", pMasterKey.second.nDeriveIterations); if (!crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod)) return false; if (!crypter.Encrypt(vMasterKey, pMasterKey.second.vchCryptedKey)) return false; CWalletDB(strWalletFile).WriteMasterKey(pMasterKey.first, pMasterKey.second); if (fWasLocked) Lock(); return true; } } } return false; } void CWallet::SetBestChain(const CBlockLocator& loc) { CWalletDB walletdb(strWalletFile); walletdb.WriteBestBlock(loc); } bool CWallet::SetMinVersion(enum WalletFeature nVersion, CWalletDB* pwalletdbIn, bool fExplicit) { LOCK(cs_wallet); // nWalletVersion if (nWalletVersion >= nVersion) return true; // when doing an explicit upgrade, if we pass the max version permitted, upgrade all the way if (fExplicit && nVersion > nWalletMaxVersion) nVersion = FEATURE_LATEST; nWalletVersion = nVersion; if (nVersion > nWalletMaxVersion) nWalletMaxVersion = nVersion; if (fFileBacked) { CWalletDB* pwalletdb = pwalletdbIn ? pwalletdbIn : new CWalletDB(strWalletFile); if (nWalletVersion > 40000) pwalletdb->WriteMinVersion(nWalletVersion); if (!pwalletdbIn) delete pwalletdb; } return true; } bool CWallet::SetMaxVersion(int nVersion) { LOCK(cs_wallet); // nWalletVersion, nWalletMaxVersion // cannot downgrade below current version if (nWalletVersion > nVersion) return false; nWalletMaxVersion = nVersion; return true; } set<uint256> CWallet::GetConflicts(const uint256& txid) const { set<uint256> result; AssertLockHeld(cs_wallet); std::map<uint256, CWalletTx>::const_iterator it = mapWallet.find(txid); if (it == mapWallet.end()) return result; const CWalletTx& wtx = it->second; std::pair<TxSpends::const_iterator, TxSpends::const_iterator> range; BOOST_FOREACH (const CTxIn& txin, wtx.vin) { if (mapTxSpends.count(txin.prevout) <= 1) continue; // No conflict if zero or one spends range = mapTxSpends.equal_range(txin.prevout); for (TxSpends::const_iterator it = range.first; it != range.second; ++it) result.insert(it->second); } return result; } void CWallet::SyncMetaData(pair<TxSpends::iterator, TxSpends::iterator> range) { // We want all the wallet transactions in range to have the same metadata as // the oldest (smallest nOrderPos). // So: find smallest nOrderPos: int nMinOrderPos = std::numeric_limits<int>::max(); const CWalletTx* copyFrom = NULL; for (TxSpends::iterator it = range.first; it != range.second; ++it) { const uint256& hash = it->second; int n = mapWallet[hash].nOrderPos; if (n < nMinOrderPos) { nMinOrderPos = n; copyFrom = &mapWallet[hash]; } } // Now copy data from copyFrom to rest: for (TxSpends::iterator it = range.first; it != range.second; ++it) { const uint256& hash = it->second; CWalletTx* copyTo = &mapWallet[hash]; if (copyFrom == copyTo) continue; copyTo->mapValue = copyFrom->mapValue; copyTo->vOrderForm = copyFrom->vOrderForm; // fTimeReceivedIsTxTime not copied on purpose // nTimeReceived not copied on purpose copyTo->nTimeSmart = copyFrom->nTimeSmart; copyTo->fFromMe = copyFrom->fFromMe; copyTo->strFromAccount = copyFrom->strFromAccount; // nOrderPos not copied on purpose // cached members not copied on purpose } } /** * Outpoint is spent if any non-conflicted transaction * spends it: */ bool CWallet::IsSpent(const uint256& hash, unsigned int n) const { const COutPoint outpoint(hash, n); pair<TxSpends::const_iterator, TxSpends::const_iterator> range; range = mapTxSpends.equal_range(outpoint); for (TxSpends::const_iterator it = range.first; it != range.second; ++it) { const uint256& wtxid = it->second; std::map<uint256, CWalletTx>::const_iterator mit = mapWallet.find(wtxid); if (mit != mapWallet.end() && mit->second.GetDepthInMainChain() >= 0) return true; // Spent } return false; } void CWallet::AddToSpends(const COutPoint& outpoint, const uint256& wtxid) { mapTxSpends.insert(make_pair(outpoint, wtxid)); pair<TxSpends::iterator, TxSpends::iterator> range; range = mapTxSpends.equal_range(outpoint); SyncMetaData(range); } void CWallet::AddToSpends(const uint256& wtxid) { assert(mapWallet.count(wtxid)); CWalletTx& thisTx = mapWallet[wtxid]; if (thisTx.IsCoinBase()) // Coinbases don't spend anything! return; BOOST_FOREACH (const CTxIn& txin, thisTx.vin) AddToSpends(txin.prevout, wtxid); } bool CWallet::GetMasternodeVinAndKeys(CTxIn& txinRet, CPubKey& pubKeyRet, CKey& keyRet, std::string strTxHash, std::string strOutputIndex) { // wait for reindex and/or import to finish if (fImporting || fReindex) return false; // Find possible candidates std::vector<COutput> vPossibleCoins; AvailableCoins(vPossibleCoins, true, NULL, false, ONLY_10000); if (vPossibleCoins.empty()) { LogPrintf("CWallet::GetMasternodeVinAndKeys -- Could not locate any valid masternode vin\n"); return false; } if (strTxHash.empty()) // No output specified, select the first one return GetVinAndKeysFromOutput(vPossibleCoins[0], txinRet, pubKeyRet, keyRet); // Find specific vin uint256 txHash = uint256S(strTxHash); int nOutputIndex; try { nOutputIndex = std::stoi(strOutputIndex.c_str()); } catch (const std::exception& e) { LogPrintf("%s: %s on strOutputIndex\n", __func__, e.what()); return false; } BOOST_FOREACH (COutput& out, vPossibleCoins) if (out.tx->GetHash() == txHash && out.i == nOutputIndex) // found it! return GetVinAndKeysFromOutput(out, txinRet, pubKeyRet, keyRet); LogPrintf("CWallet::GetMasternodeVinAndKeys -- Could not locate specified masternode vin\n"); return false; } bool CWallet::GetVinAndKeysFromOutput(COutput out, CTxIn& txinRet, CPubKey& pubKeyRet, CKey& keyRet) { // wait for reindex and/or import to finish if (fImporting || fReindex) return false; CScript pubScript; txinRet = CTxIn(out.tx->GetHash(), out.i); pubScript = out.tx->vout[out.i].scriptPubKey; // the inputs PubKey CTxDestination address1; ExtractDestination(pubScript, address1); CBitcoinAddress address2(address1); CKeyID keyID; if (!address2.GetKeyID(keyID)) { LogPrintf("CWallet::GetVinAndKeysFromOutput -- Address does not refer to a key\n"); return false; } if (!GetKey(keyID, keyRet)) { LogPrintf("CWallet::GetVinAndKeysFromOutput -- Private key for address is not known\n"); return false; } pubKeyRet = keyRet.GetPubKey(); return true; } bool CWallet::EncryptWallet(const SecureString& strWalletPassphrase) { if (IsCrypted()) return false; CKeyingMaterial vMasterKey; RandAddSeedPerfmon(); vMasterKey.resize(WALLET_CRYPTO_KEY_SIZE); GetRandBytes(&vMasterKey[0], WALLET_CRYPTO_KEY_SIZE); CMasterKey kMasterKey; RandAddSeedPerfmon(); kMasterKey.vchSalt.resize(WALLET_CRYPTO_SALT_SIZE); GetRandBytes(&kMasterKey.vchSalt[0], WALLET_CRYPTO_SALT_SIZE); CCrypter crypter; int64_t nStartTime = GetTimeMillis(); crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, 25000, kMasterKey.nDerivationMethod); kMasterKey.nDeriveIterations = 2500000 / ((double)(GetTimeMillis() - nStartTime)); nStartTime = GetTimeMillis(); crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod); kMasterKey.nDeriveIterations = (kMasterKey.nDeriveIterations + kMasterKey.nDeriveIterations * 100 / ((double)(GetTimeMillis() - nStartTime))) / 2; if (kMasterKey.nDeriveIterations < 25000) kMasterKey.nDeriveIterations = 25000; LogPrintf("Encrypting Wallet with an nDeriveIterations of %i\n", kMasterKey.nDeriveIterations); if (!crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod)) return false; if (!crypter.Encrypt(vMasterKey, kMasterKey.vchCryptedKey)) return false; { LOCK(cs_wallet); mapMasterKeys[++nMasterKeyMaxID] = kMasterKey; if (fFileBacked) { assert(!pwalletdbEncryption); pwalletdbEncryption = new CWalletDB(strWalletFile); if (!pwalletdbEncryption->TxnBegin()) { delete pwalletdbEncryption; pwalletdbEncryption = NULL; return false; } pwalletdbEncryption->WriteMasterKey(nMasterKeyMaxID, kMasterKey); } if (!EncryptKeys(vMasterKey)) { if (fFileBacked) { pwalletdbEncryption->TxnAbort(); delete pwalletdbEncryption; } // We now probably have half of our keys encrypted in memory, and half not... // die and let the user reload their unencrypted wallet. assert(false); } // Encryption was introduced in version 0.4.0 SetMinVersion(FEATURE_WALLETCRYPT, pwalletdbEncryption, true); if (fFileBacked) { if (!pwalletdbEncryption->TxnCommit()) { delete pwalletdbEncryption; // We now have keys encrypted in memory, but not on disk... // die to avoid confusion and let the user reload their unencrypted wallet. assert(false); } delete pwalletdbEncryption; pwalletdbEncryption = NULL; } Lock(); Unlock(strWalletPassphrase); NewKeyPool(); Lock(); // Need to completely rewrite the wallet file; if we don't, bdb might keep // bits of the unencrypted private key in slack space in the database file. CDB::Rewrite(strWalletFile); } NotifyStatusChanged(this); return true; } int64_t CWallet::IncOrderPosNext(CWalletDB* pwalletdb) { AssertLockHeld(cs_wallet); // nOrderPosNext int64_t nRet = nOrderPosNext++; if (pwalletdb) { pwalletdb->WriteOrderPosNext(nOrderPosNext); } else { CWalletDB(strWalletFile).WriteOrderPosNext(nOrderPosNext); } return nRet; } CWallet::TxItems CWallet::OrderedTxItems(std::list<CAccountingEntry>& acentries, std::string strAccount) { AssertLockHeld(cs_wallet); // mapWallet CWalletDB walletdb(strWalletFile); // First: get all CWalletTx and CAccountingEntry into a sorted-by-order multimap. TxItems txOrdered; // Note: maintaining indices in the database of (account,time) --> txid and (account, time) --> acentry // would make this much faster for applications that do this a lot. for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) { CWalletTx* wtx = &((*it).second); txOrdered.insert(make_pair(wtx->nOrderPos, TxPair(wtx, (CAccountingEntry*)0))); } acentries.clear(); walletdb.ListAccountCreditDebit(strAccount, acentries); BOOST_FOREACH (CAccountingEntry& entry, acentries) { txOrdered.insert(make_pair(entry.nOrderPos, TxPair((CWalletTx*)0, &entry))); } return txOrdered; } void CWallet::MarkDirty() { { LOCK(cs_wallet); BOOST_FOREACH (PAIRTYPE(const uint256, CWalletTx) & item, mapWallet) item.second.MarkDirty(); } } bool CWallet::AddToWallet(const CWalletTx& wtxIn, bool fFromLoadWallet) { uint256 hash = wtxIn.GetHash(); if (fFromLoadWallet) { mapWallet[hash] = wtxIn; mapWallet[hash].BindWallet(this); AddToSpends(hash); } else { LOCK(cs_wallet); // Inserts only if not already there, returns tx inserted or tx found pair<map<uint256, CWalletTx>::iterator, bool> ret = mapWallet.insert(make_pair(hash, wtxIn)); CWalletTx& wtx = (*ret.first).second; wtx.BindWallet(this); bool fInsertedNew = ret.second; if (fInsertedNew) { wtx.nTimeReceived = GetAdjustedTime(); wtx.nOrderPos = IncOrderPosNext(); wtx.nTimeSmart = wtx.nTimeReceived; if (wtxIn.hashBlock != 0) { if (mapBlockIndex.count(wtxIn.hashBlock)) { int64_t latestNow = wtx.nTimeReceived; int64_t latestEntry = 0; { // Tolerate times up to the last timestamp in the wallet not more than 5 minutes into the future int64_t latestTolerated = latestNow + 300; std::list<CAccountingEntry> acentries; TxItems txOrdered = OrderedTxItems(acentries); for (TxItems::reverse_iterator it = txOrdered.rbegin(); it != txOrdered.rend(); ++it) { CWalletTx* const pwtx = (*it).second.first; if (pwtx == &wtx) continue; CAccountingEntry* const pacentry = (*it).second.second; int64_t nSmartTime; if (pwtx) { nSmartTime = pwtx->nTimeSmart; if (!nSmartTime) nSmartTime = pwtx->nTimeReceived; } else nSmartTime = pacentry->nTime; if (nSmartTime <= latestTolerated) { latestEntry = nSmartTime; if (nSmartTime > latestNow) latestNow = nSmartTime; break; } } } int64_t blocktime = mapBlockIndex[wtxIn.hashBlock]->GetBlockTime(); wtx.nTimeSmart = std::max(latestEntry, std::min(blocktime, latestNow)); } else LogPrintf("AddToWallet() : found %s in block %s not in index\n", wtxIn.GetHash().ToString(), wtxIn.hashBlock.ToString()); } AddToSpends(hash); } bool fUpdated = false; if (!fInsertedNew) { // Merge if (wtxIn.hashBlock != 0 && wtxIn.hashBlock != wtx.hashBlock) { wtx.hashBlock = wtxIn.hashBlock; fUpdated = true; } if (wtxIn.nIndex != -1 && (wtxIn.vMerkleBranch != wtx.vMerkleBranch || wtxIn.nIndex != wtx.nIndex)) { wtx.vMerkleBranch = wtxIn.vMerkleBranch; wtx.nIndex = wtxIn.nIndex; fUpdated = true; } if (wtxIn.fFromMe && wtxIn.fFromMe != wtx.fFromMe) { wtx.fFromMe = wtxIn.fFromMe; fUpdated = true; } } //// debug print LogPrintf("AddToWallet %s %s%s\n", wtxIn.GetHash().ToString(), (fInsertedNew ? "new" : ""), (fUpdated ? "update" : "")); // Write to disk if (fInsertedNew || fUpdated) if (!wtx.WriteToDisk()) return false; // Break debit/credit balance caches: wtx.MarkDirty(); // Notify UI of new or updated transaction NotifyTransactionChanged(this, hash, fInsertedNew ? CT_NEW : CT_UPDATED); // notify an external script when a wallet transaction comes in or is updated std::string strCmd = GetArg("-walletnotify", ""); if (!strCmd.empty()) { boost::replace_all(strCmd, "%s", wtxIn.GetHash().GetHex()); boost::thread t(runCommand, strCmd); // thread runs free } } return true; } /** * Add a transaction to the wallet, or update it. * pblock is optional, but should be provided if the transaction is known to be in a block. * If fUpdate is true, existing transactions will be updated. */ bool CWallet::AddToWalletIfInvolvingMe(const CTransaction& tx, const CBlock* pblock, bool fUpdate) { { AssertLockHeld(cs_wallet); bool fExisted = mapWallet.count(tx.GetHash()) != 0; if (fExisted && !fUpdate) return false; if (fExisted || IsMine(tx) || IsFromMe(tx)) { CWalletTx wtx(this, tx); // Get merkle branch if transaction was found in a block if (pblock) wtx.SetMerkleBranch(*pblock); return AddToWallet(wtx); } } return false; } void CWallet::SyncTransaction(const CTransaction& tx, const CBlock* pblock) { LOCK2(cs_main, cs_wallet); if (!AddToWalletIfInvolvingMe(tx, pblock, true)) return; // Not one of ours // If a transaction changes 'conflicted' state, that changes the balance // available of the outputs it spends. So force those to be // recomputed, also: BOOST_FOREACH (const CTxIn& txin, tx.vin) { if (mapWallet.count(txin.prevout.hash)) mapWallet[txin.prevout.hash].MarkDirty(); } } void CWallet::EraseFromWallet(const uint256& hash) { if (!fFileBacked) return; { LOCK(cs_wallet); if (mapWallet.erase(hash)) CWalletDB(strWalletFile).EraseTx(hash); } return; } isminetype CWallet::IsMine(const CTxIn& txin) const { { LOCK(cs_wallet); map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash); if (mi != mapWallet.end()) { const CWalletTx& prev = (*mi).second; if (txin.prevout.n < prev.vout.size()) return IsMine(prev.vout[txin.prevout.n]); } } return ISMINE_NO; } CAmount CWallet::GetDebit(const CTxIn& txin, const isminefilter& filter) const { { LOCK(cs_wallet); map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash); if (mi != mapWallet.end()) { const CWalletTx& prev = (*mi).second; if (txin.prevout.n < prev.vout.size()) if (IsMine(prev.vout[txin.prevout.n]) & filter) return prev.vout[txin.prevout.n].nValue; } } return 0; } // Recursively determine the rounds of a given input (How deep is the Obfuscation chain for a given input) int CWallet::GetRealInputObfuscationRounds(CTxIn in, int rounds) const { static std::map<uint256, CMutableTransaction> mDenomWtxes; if (rounds >= 16) return 15; // 16 rounds max uint256 hash = in.prevout.hash; unsigned int nout = in.prevout.n; const CWalletTx* wtx = GetWalletTx(hash); if (wtx != NULL) { std::map<uint256, CMutableTransaction>::const_iterator mdwi = mDenomWtxes.find(hash); // not known yet, let's add it if (mdwi == mDenomWtxes.end()) { LogPrint("obfuscation", "GetInputObfuscationRounds INSERTING %s\n", hash.ToString()); mDenomWtxes[hash] = CMutableTransaction(*wtx); } // found and it's not an initial value, just return it else if (mDenomWtxes[hash].vout[nout].nRounds != -10) { return mDenomWtxes[hash].vout[nout].nRounds; } // bounds check if (nout >= wtx->vout.size()) { // should never actually hit this LogPrint("obfuscation", "GetInputObfuscationRounds UPDATED %s %3d %3d\n", hash.ToString(), nout, -4); return -4; } if (pwalletMain->IsCollateralAmount(wtx->vout[nout].nValue)) { mDenomWtxes[hash].vout[nout].nRounds = -3; LogPrint("obfuscation", "GetInputObfuscationRounds UPDATED %s %3d %3d\n", hash.ToString(), nout, mDenomWtxes[hash].vout[nout].nRounds); return mDenomWtxes[hash].vout[nout].nRounds; } //make sure the final output is non-denominate if (/*rounds == 0 && */ !IsDenominatedAmount(wtx->vout[nout].nValue)) //NOT DENOM { mDenomWtxes[hash].vout[nout].nRounds = -2; LogPrint("obfuscation", "GetInputObfuscationRounds UPDATED %s %3d %3d\n", hash.ToString(), nout, mDenomWtxes[hash].vout[nout].nRounds); return mDenomWtxes[hash].vout[nout].nRounds; } bool fAllDenoms = true; BOOST_FOREACH (CTxOut out, wtx->vout) { fAllDenoms = fAllDenoms && IsDenominatedAmount(out.nValue); } // this one is denominated but there is another non-denominated output found in the same tx if (!fAllDenoms) { mDenomWtxes[hash].vout[nout].nRounds = 0; LogPrint("obfuscation", "GetInputObfuscationRounds UPDATED %s %3d %3d\n", hash.ToString(), nout, mDenomWtxes[hash].vout[nout].nRounds); return mDenomWtxes[hash].vout[nout].nRounds; } int nShortest = -10; // an initial value, should be no way to get this by calculations bool fDenomFound = false; // only denoms here so let's look up BOOST_FOREACH (CTxIn in2, wtx->vin) { if (IsMine(in2)) { int n = GetRealInputObfuscationRounds(in2, rounds + 1); // denom found, find the shortest chain or initially assign nShortest with the first found value if (n >= 0 && (n < nShortest || nShortest == -10)) { nShortest = n; fDenomFound = true; } } } mDenomWtxes[hash].vout[nout].nRounds = fDenomFound ? (nShortest >= 15 ? 16 : nShortest + 1) // good, we a +1 to the shortest one but only 16 rounds max allowed : 0; // too bad, we are the fist one in that chain LogPrint("obfuscation", "GetInputObfuscationRounds UPDATED %s %3d %3d\n", hash.ToString(), nout, mDenomWtxes[hash].vout[nout].nRounds); return mDenomWtxes[hash].vout[nout].nRounds; } return rounds - 1; } // respect current settings int CWallet::GetInputObfuscationRounds(CTxIn in) const { LOCK(cs_wallet); int realObfuscationRounds = GetRealInputObfuscationRounds(in, 0); return realObfuscationRounds > nObfuscationRounds ? nObfuscationRounds : realObfuscationRounds; } bool CWallet::IsDenominated(const CTxIn& txin) const { { LOCK(cs_wallet); map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash); if (mi != mapWallet.end()) { const CWalletTx& prev = (*mi).second; if (txin.prevout.n < prev.vout.size()) return IsDenominatedAmount(prev.vout[txin.prevout.n].nValue); } } return false; } bool CWallet::IsDenominated(const CTransaction& tx) const { /* Return false if ANY inputs are non-denom */ bool ret = true; BOOST_FOREACH (const CTxIn& txin, tx.vin) { if (!IsDenominated(txin)) { ret = false; } } return ret; } bool CWallet::IsDenominatedAmount(CAmount nInputAmount) const { BOOST_FOREACH (CAmount d, obfuScationDenominations) if (nInputAmount == d) return true; return false; } bool CWallet::IsChange(const CTxOut& txout) const { // TODO: fix handling of 'change' outputs. The assumption is that any // payment to a script that is ours, but is not in the address book // is change. That assumption is likely to break when we implement multisignature // wallets that return change back into a multi-signature-protected address; // a better way of identifying which outputs are 'the send' and which are // 'the change' will need to be implemented (maybe extend CWalletTx to remember // which output, if any, was change). if (::IsMine(*this, txout.scriptPubKey)) { CTxDestination address; if (!ExtractDestination(txout.scriptPubKey, address)) return true; LOCK(cs_wallet); if (!mapAddressBook.count(address)) return true; } return false; } int64_t CWalletTx::GetTxTime() const { int64_t n = nTimeSmart; return n ? n : nTimeReceived; } int CWalletTx::GetRequestCount() const { // Returns -1 if it wasn't being tracked int nRequests = -1; { LOCK(pwallet->cs_wallet); if (IsCoinBase()) { // Generated block if (hashBlock != 0) { map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock); if (mi != pwallet->mapRequestCount.end()) nRequests = (*mi).second; } } else { // Did anyone request this transaction? map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(GetHash()); if (mi != pwallet->mapRequestCount.end()) { nRequests = (*mi).second; // How about the block it's in? if (nRequests == 0 && hashBlock != 0) { map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock); if (mi != pwallet->mapRequestCount.end()) nRequests = (*mi).second; else nRequests = 1; // If it's in someone else's block it must have got out } } } } return nRequests; } void CWalletTx::GetAmounts(list<COutputEntry>& listReceived, list<COutputEntry>& listSent, CAmount& nFee, string& strSentAccount, const isminefilter& filter) const { nFee = 0; listReceived.clear(); listSent.clear(); strSentAccount = strFromAccount; // Compute fee: CAmount nDebit = GetDebit(filter); if (nDebit > 0) // debit>0 means we signed/sent this transaction { CAmount nValueOut = GetValueOut(); nFee = nDebit - nValueOut; } // Sent/received. for (unsigned int i = 0; i < vout.size(); ++i) { const CTxOut& txout = vout[i]; isminetype fIsMine = pwallet->IsMine(txout); // Only need to handle txouts if AT LEAST one of these is true: // 1) they debit from us (sent) // 2) the output is to us (received) if (nDebit > 0) { // Don't report 'change' txouts if (pwallet->IsChange(txout)) continue; } else if (!(fIsMine & filter)) continue; // In either case, we need to get the destination address CTxDestination address; if (!ExtractDestination(txout.scriptPubKey, address)) { LogPrintf("CWalletTx::GetAmounts: Unknown transaction type found, txid %s\n", this->GetHash().ToString()); address = CNoDestination(); } COutputEntry output = {address, txout.nValue, (int)i}; // If we are debited by the transaction, add the output as a "sent" entry if (nDebit > 0) listSent.push_back(output); // If we are receiving the output, add it as a "received" entry if (fIsMine & filter) listReceived.push_back(output); } } void CWalletTx::GetAccountAmounts(const string& strAccount, CAmount& nReceived, CAmount& nSent, CAmount& nFee, const isminefilter& filter) const { nReceived = nSent = nFee = 0; CAmount allFee; string strSentAccount; list<COutputEntry> listReceived; list<COutputEntry> listSent; GetAmounts(listReceived, listSent, allFee, strSentAccount, filter); if (strAccount == strSentAccount) { BOOST_FOREACH (const COutputEntry& s, listSent) nSent += s.amount; nFee = allFee; } { LOCK(pwallet->cs_wallet); BOOST_FOREACH (const COutputEntry& r, listReceived) { if (pwallet->mapAddressBook.count(r.destination)) { map<CTxDestination, CAddressBookData>::const_iterator mi = pwallet->mapAddressBook.find(r.destination); if (mi != pwallet->mapAddressBook.end() && (*mi).second.name == strAccount) nReceived += r.amount; } else if (strAccount.empty()) { nReceived += r.amount; } } } } bool CWalletTx::WriteToDisk() { return CWalletDB(pwallet->strWalletFile).WriteTx(GetHash(), *this); } /** * Scan the block chain (starting in pindexStart) for transactions * from or to us. If fUpdate is true, found transactions that already * exist in the wallet will be updated. */ int CWallet::ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate) { int ret = 0; int64_t nNow = GetTime(); CBlockIndex* pindex = pindexStart; { LOCK2(cs_main, cs_wallet); // no need to read and scan block, if block was created before // our wallet birthday (as adjusted for block time variability) while (pindex && nTimeFirstKey && (pindex->GetBlockTime() < (nTimeFirstKey - 7200))) pindex = chainActive.Next(pindex); ShowProgress(_("Rescanning..."), 0); // show rescan progress in GUI as dialog or on splashscreen, if -rescan on startup double dProgressStart = Checkpoints::GuessVerificationProgress(pindex, false); double dProgressTip = Checkpoints::GuessVerificationProgress(chainActive.Tip(), false); while (pindex) { if (pindex->nHeight % 100 == 0 && dProgressTip - dProgressStart > 0.0) ShowProgress(_("Rescanning..."), std::max(1, std::min(99, (int)((Checkpoints::GuessVerificationProgress(pindex, false) - dProgressStart) / (dProgressTip - dProgressStart) * 100)))); CBlock block; ReadBlockFromDisk(block, pindex); BOOST_FOREACH (CTransaction& tx, block.vtx) { if (AddToWalletIfInvolvingMe(tx, &block, fUpdate)) ret++; } pindex = chainActive.Next(pindex); if (GetTime() >= nNow + 60) { nNow = GetTime(); LogPrintf("Still rescanning. At block %d. Progress=%f\n", pindex->nHeight, Checkpoints::GuessVerificationProgress(pindex)); } } ShowProgress(_("Rescanning..."), 100); // hide progress dialog in GUI } return ret; } void CWallet::ReacceptWalletTransactions() { LOCK2(cs_main, cs_wallet); BOOST_FOREACH (PAIRTYPE(const uint256, CWalletTx) & item, mapWallet) { const uint256& wtxid = item.first; CWalletTx& wtx = item.second; assert(wtx.GetHash() == wtxid); int nDepth = wtx.GetDepthInMainChain(); if (!wtx.IsCoinBase() && nDepth < 0) { // Try to add to memory pool LOCK(mempool.cs); wtx.AcceptToMemoryPool(false); } } } bool CWalletTx::InMempool() const { LOCK(mempool.cs); if (mempool.exists(GetHash())) { return true; } return false; } void CWalletTx::RelayWalletTransaction(std::string strCommand) { if (!IsCoinBase()) { if (GetDepthInMainChain() == 0) { uint256 hash = GetHash(); LogPrintf("Relaying wtx %s\n", hash.ToString()); if (strCommand == "ix") { mapTxLockReq.insert(make_pair(hash, (CTransaction) * this)); CreateNewLock(((CTransaction) * this)); RelayTransactionLockReq((CTransaction) * this, true); } else { RelayTransaction((CTransaction) * this); } } } } set<uint256> CWalletTx::GetConflicts() const { set<uint256> result; if (pwallet != NULL) { uint256 myHash = GetHash(); result = pwallet->GetConflicts(myHash); result.erase(myHash); } return result; } void CWallet::ResendWalletTransactions() { // Do this infrequently and randomly to avoid giving away // that these are our transactions. if (GetTime() < nNextResend) return; bool fFirst = (nNextResend == 0); nNextResend = GetTime() + GetRand(30 * 60); if (fFirst) return; // Only do it if there's been a new block since last time if (nTimeBestReceived < nLastResend) return; nLastResend = GetTime(); // Rebroadcast any of our txes that aren't in a block yet LogPrintf("ResendWalletTransactions()\n"); { LOCK(cs_wallet); // Sort them in chronological order multimap<unsigned int, CWalletTx*> mapSorted; BOOST_FOREACH (PAIRTYPE(const uint256, CWalletTx) & item, mapWallet) { CWalletTx& wtx = item.second; // Don't rebroadcast until it's had plenty of time that // it should have gotten in already by now. if (nTimeBestReceived - (int64_t)wtx.nTimeReceived > 5 * 60) mapSorted.insert(make_pair(wtx.nTimeReceived, &wtx)); } BOOST_FOREACH (PAIRTYPE(const unsigned int, CWalletTx*) & item, mapSorted) { CWalletTx& wtx = *item.second; wtx.RelayWalletTransaction(); } } } /** @} */ // end of mapWallet /** @defgroup Actions * * @{ */ CAmount CWallet::GetBalance() const { CAmount nTotal = 0; { LOCK2(cs_main, cs_wallet); for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) { const CWalletTx* pcoin = &(*it).second; if (pcoin->IsTrusted()) nTotal += pcoin->GetAvailableCredit(); } } return nTotal; } CAmount CWallet::GetAnonymizableBalance() const { if (fLiteMode) return 0; CAmount nTotal = 0; { LOCK2(cs_main, cs_wallet); for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) { const CWalletTx* pcoin = &(*it).second; if (pcoin->IsTrusted()) nTotal += pcoin->GetAnonymizableCredit(); } } return nTotal; } CAmount CWallet::GetAnonymizedBalance() const { if (fLiteMode) return 0; CAmount nTotal = 0; { LOCK2(cs_main, cs_wallet); for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) { const CWalletTx* pcoin = &(*it).second; if (pcoin->IsTrusted()) nTotal += pcoin->GetAnonymizedCredit(); } } return nTotal; } // Note: calculated including unconfirmed, // that's ok as long as we use it for informational purposes only double CWallet::GetAverageAnonymizedRounds() const { if (fLiteMode) return 0; double fTotal = 0; double fCount = 0; { LOCK2(cs_main, cs_wallet); for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) { const CWalletTx* pcoin = &(*it).second; uint256 hash = (*it).first; for (unsigned int i = 0; i < pcoin->vout.size(); i++) { CTxIn vin = CTxIn(hash, i); if (IsSpent(hash, i) || IsMine(pcoin->vout[i]) != ISMINE_SPENDABLE || !IsDenominated(vin)) continue; int rounds = GetInputObfuscationRounds(vin); fTotal += (float)rounds; fCount += 1; } } } if (fCount == 0) return 0; return fTotal / fCount; } // Note: calculated including unconfirmed, // that's ok as long as we use it for informational purposes only CAmount CWallet::GetNormalizedAnonymizedBalance() const { if (fLiteMode) return 0; CAmount nTotal = 0; { LOCK2(cs_main, cs_wallet); for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) { const CWalletTx* pcoin = &(*it).second; uint256 hash = (*it).first; for (unsigned int i = 0; i < pcoin->vout.size(); i++) { CTxIn vin = CTxIn(hash, i); if (IsSpent(hash, i) || IsMine(pcoin->vout[i]) != ISMINE_SPENDABLE || !IsDenominated(vin)) continue; if (pcoin->GetDepthInMainChain() < 0) continue; int rounds = GetInputObfuscationRounds(vin); nTotal += pcoin->vout[i].nValue * rounds / nObfuscationRounds; } } } return nTotal; } CAmount CWallet::GetDenominatedBalance(bool unconfirmed) const { if (fLiteMode) return 0; CAmount nTotal = 0; { LOCK2(cs_main, cs_wallet); for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) { const CWalletTx* pcoin = &(*it).second; nTotal += pcoin->GetDenominatedCredit(unconfirmed); } } return nTotal; } CAmount CWallet::GetUnconfirmedBalance() const { CAmount nTotal = 0; { LOCK2(cs_main, cs_wallet); for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) { const CWalletTx* pcoin = &(*it).second; if (!IsFinalTx(*pcoin) || (!pcoin->IsTrusted() && pcoin->GetDepthInMainChain() == 0)) nTotal += pcoin->GetAvailableCredit(); } } return nTotal; } CAmount CWallet::GetImmatureBalance() const { CAmount nTotal = 0; { LOCK2(cs_main, cs_wallet); for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) { const CWalletTx* pcoin = &(*it).second; nTotal += pcoin->GetImmatureCredit(); } } return nTotal; } CAmount CWallet::GetWatchOnlyBalance() const { CAmount nTotal = 0; { LOCK2(cs_main, cs_wallet); for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) { const CWalletTx* pcoin = &(*it).second; if (pcoin->IsTrusted()) nTotal += pcoin->GetAvailableWatchOnlyCredit(); } } return nTotal; } CAmount CWallet::GetUnconfirmedWatchOnlyBalance() const { CAmount nTotal = 0; { LOCK2(cs_main, cs_wallet); for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) { const CWalletTx* pcoin = &(*it).second; if (!IsFinalTx(*pcoin) || (!pcoin->IsTrusted() && pcoin->GetDepthInMainChain() == 0)) nTotal += pcoin->GetAvailableWatchOnlyCredit(); } } return nTotal; } CAmount CWallet::GetImmatureWatchOnlyBalance() const { CAmount nTotal = 0; { LOCK2(cs_main, cs_wallet); for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) { const CWalletTx* pcoin = &(*it).second; nTotal += pcoin->GetImmatureWatchOnlyCredit(); } } return nTotal; } /** * populate vCoins with vector of available COutputs. */ void CWallet::AvailableCoins(vector<COutput>& vCoins, bool fOnlyConfirmed, const CCoinControl* coinControl, bool fIncludeZeroValue, AvailableCoinsType nCoinType, bool fUseIX) const { vCoins.clear(); { LOCK2(cs_main, cs_wallet); for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) { const uint256& wtxid = it->first; const CWalletTx* pcoin = &(*it).second; if (!CheckFinalTx(*pcoin)) continue; if (fOnlyConfirmed && !pcoin->IsTrusted()) continue; if ((pcoin->IsCoinBase() || pcoin->IsCoinStake()) && pcoin->GetBlocksToMaturity() > 0) continue; int nDepth = pcoin->GetDepthInMainChain(false); // do not use IX for inputs that have less then 6 blockchain confirmations if (fUseIX && nDepth < 6) continue; // We should not consider coins which aren't at least in our mempool // It's possible for these to be conflicted via ancestors which we may never be able to detect if (nDepth == 0 && !pcoin->InMempool()) continue; for (unsigned int i = 0; i < pcoin->vout.size(); i++) { bool found = false; if (nCoinType == ONLY_DENOMINATED) { found = IsDenominatedAmount(pcoin->vout[i].nValue); } else if (nCoinType == ONLY_NOT10000IFMN) { found = !(fMasterNode && pcoin->vout[i].nValue == 50000 * COIN); } else if (nCoinType == ONLY_NONDENOMINATED_NOT10000IFMN) { if (IsCollateralAmount(pcoin->vout[i].nValue)) continue; // do not use collateral amounts found = !IsDenominatedAmount(pcoin->vout[i].nValue); if (found && fMasterNode) found = pcoin->vout[i].nValue != 50000 * COIN; // do not use Hot MN funds } else if (nCoinType == ONLY_10000) { found = pcoin->vout[i].nValue == 50000 * COIN; } else { found = true; } if (!found) continue; isminetype mine = IsMine(pcoin->vout[i]); if (IsSpent(wtxid, i)) continue; if (mine == ISMINE_NO) continue; if (mine == ISMINE_WATCH_ONLY) continue; if (IsLockedCoin((*it).first, i) && nCoinType != ONLY_10000) continue; if (pcoin->vout[i].nValue <= 0 && !fIncludeZeroValue) continue; if (coinControl && coinControl->HasSelected() && !coinControl->fAllowOtherInputs && !coinControl->IsSelected((*it).first, i)) continue; bool fIsSpendable = false; if ((mine & ISMINE_SPENDABLE) != ISMINE_NO) fIsSpendable = true; if ((mine & ISMINE_MULTISIG) != ISMINE_NO) fIsSpendable = true; vCoins.emplace_back(COutput(pcoin, i, nDepth, fIsSpendable)); } } } } map<CBitcoinAddress, vector<COutput> > CWallet::AvailableCoinsByAddress(bool fConfirmed, CAmount maxCoinValue) { vector<COutput> vCoins; AvailableCoins(vCoins, fConfirmed); map<CBitcoinAddress, vector<COutput> > mapCoins; BOOST_FOREACH (COutput out, vCoins) { if (maxCoinValue > 0 && out.tx->vout[out.i].nValue > maxCoinValue) continue; CTxDestination address; if (!ExtractDestination(out.tx->vout[out.i].scriptPubKey, address)) continue; mapCoins[CBitcoinAddress(address)].push_back(out); } return mapCoins; } static void ApproximateBestSubset(vector<pair<CAmount, pair<const CWalletTx*, unsigned int> > > vValue, const CAmount& nTotalLower, const CAmount& nTargetValue, vector<char>& vfBest, CAmount& nBest, int iterations = 1000) { vector<char> vfIncluded; vfBest.assign(vValue.size(), true); nBest = nTotalLower; seed_insecure_rand(); for (int nRep = 0; nRep < iterations && nBest != nTargetValue; nRep++) { vfIncluded.assign(vValue.size(), false); CAmount nTotal = 0; bool fReachedTarget = false; for (int nPass = 0; nPass < 2 && !fReachedTarget; nPass++) { for (unsigned int i = 0; i < vValue.size(); i++) { //The solver here uses a randomized algorithm, //the randomness serves no real security purpose but is just //needed to prevent degenerate behavior and it is important //that the rng is fast. We do not use a constant random sequence, //because there may be some privacy improvement by making //the selection random. if (nPass == 0 ? insecure_rand() & 1 : !vfIncluded[i]) { nTotal += vValue[i].first; vfIncluded[i] = true; if (nTotal >= nTargetValue) { fReachedTarget = true; if (nTotal < nBest) { nBest = nTotal; vfBest = vfIncluded; } nTotal -= vValue[i].first; vfIncluded[i] = false; } } } } } } // TODO: find appropriate place for this sort function // move denoms down bool less_then_denom(const COutput& out1, const COutput& out2) { const CWalletTx* pcoin1 = out1.tx; const CWalletTx* pcoin2 = out2.tx; bool found1 = false; bool found2 = false; BOOST_FOREACH (CAmount d, obfuScationDenominations) // loop through predefined denoms { if (pcoin1->vout[out1.i].nValue == d) found1 = true; if (pcoin2->vout[out2.i].nValue == d) found2 = true; } return (!found1 && found2); } bool CWallet::SelectStakeCoins(std::set<std::pair<const CWalletTx*, unsigned int> >& setCoins, CAmount nTargetAmount) const { vector<COutput> vCoins; AvailableCoins(vCoins, true); int64_t nAmountSelected = 0; BOOST_FOREACH (const COutput& out, vCoins) { //make sure not to outrun target amount if (nAmountSelected + out.tx->vout[out.i].nValue > nTargetAmount) continue; //check for min age if (GetTime() - out.tx->GetTxTime() < nStakeMinAge) continue; //check that it is matured if (out.nDepth < (out.tx->IsCoinStake() ? Params().COINBASE_MATURITY() : 10)) continue; //add to our stake set setCoins.insert(make_pair(out.tx, out.i)); nAmountSelected += out.tx->vout[out.i].nValue; } return true; } bool CWallet::MintableCoins() { CAmount nBalance = GetBalance(); if (mapArgs.count("-reservebalance") && !ParseMoney(mapArgs["-reservebalance"], nReserveBalance)) return error("MintableCoins() : invalid reserve balance amount"); if (nBalance <= nReserveBalance) return false; vector<COutput> vCoins; AvailableCoins(vCoins, true); BOOST_FOREACH (const COutput& out, vCoins) { if (GetTime() - out.tx->GetTxTime() > nStakeMinAge) return true; } return false; } bool CWallet::SelectCoinsMinConf(const CAmount& nTargetValue, int nConfMine, int nConfTheirs, vector<COutput> vCoins, set<pair<const CWalletTx*, unsigned int> >& setCoinsRet, CAmount& nValueRet) const { setCoinsRet.clear(); nValueRet = 0; // List of values less than target pair<CAmount, pair<const CWalletTx*, unsigned int> > coinLowestLarger; coinLowestLarger.first = std::numeric_limits<CAmount>::max(); coinLowestLarger.second.first = NULL; vector<pair<CAmount, pair<const CWalletTx*, unsigned int> > > vValue; CAmount nTotalLower = 0; random_shuffle(vCoins.begin(), vCoins.end(), GetRandInt); // move denoms down on the list sort(vCoins.begin(), vCoins.end(), less_then_denom); // try to find nondenom first to prevent unneeded spending of mixed coins for (unsigned int tryDenom = 0; tryDenom < 2; tryDenom++) { if (fDebug) LogPrint("selectcoins", "tryDenom: %d\n", tryDenom); vValue.clear(); nTotalLower = 0; BOOST_FOREACH (const COutput& output, vCoins) { if (!output.fSpendable) continue; const CWalletTx* pcoin = output.tx; // if (fDebug) LogPrint("selectcoins", "value %s confirms %d\n", FormatMoney(pcoin->vout[output.i].nValue), output.nDepth); if (output.nDepth < (pcoin->IsFromMe(ISMINE_ALL) ? nConfMine : nConfTheirs)) continue; int i = output.i; CAmount n = pcoin->vout[i].nValue; if (tryDenom == 0 && IsDenominatedAmount(n)) continue; // we don't want denom values on first run pair<CAmount, pair<const CWalletTx*, unsigned int> > coin = make_pair(n, make_pair(pcoin, i)); if (n == nTargetValue) { setCoinsRet.insert(coin.second); nValueRet += coin.first; return true; } else if (n < nTargetValue + CENT) { vValue.push_back(coin); nTotalLower += n; } else if (n < coinLowestLarger.first) { coinLowestLarger = coin; } } if (nTotalLower == nTargetValue) { for (unsigned int i = 0; i < vValue.size(); ++i) { setCoinsRet.insert(vValue[i].second); nValueRet += vValue[i].first; } return true; } if (nTotalLower < nTargetValue) { if (coinLowestLarger.second.first == NULL) // there is no input larger than nTargetValue { if (tryDenom == 0) // we didn't look at denom yet, let's do it continue; else // we looked at everything possible and didn't find anything, no luck return false; } setCoinsRet.insert(coinLowestLarger.second); nValueRet += coinLowestLarger.first; return true; } // nTotalLower > nTargetValue break; } // Solve subset sum by stochastic approximation sort(vValue.rbegin(), vValue.rend(), CompareValueOnly()); vector<char> vfBest; CAmount nBest; ApproximateBestSubset(vValue, nTotalLower, nTargetValue, vfBest, nBest, 1000); if (nBest != nTargetValue && nTotalLower >= nTargetValue + CENT) ApproximateBestSubset(vValue, nTotalLower, nTargetValue + CENT, vfBest, nBest, 1000); // If we have a bigger coin and (either the stochastic approximation didn't find a good solution, // or the next bigger coin is closer), return the bigger coin if (coinLowestLarger.second.first && ((nBest != nTargetValue && nBest < nTargetValue + CENT) || coinLowestLarger.first <= nBest)) { setCoinsRet.insert(coinLowestLarger.second); nValueRet += coinLowestLarger.first; } else { string s = "CWallet::SelectCoinsMinConf best subset: "; for (unsigned int i = 0; i < vValue.size(); i++) { if (vfBest[i]) { setCoinsRet.insert(vValue[i].second); nValueRet += vValue[i].first; s += FormatMoney(vValue[i].first) + " "; } } LogPrintf("%s - total %s\n", s, FormatMoney(nBest)); } return true; } bool CWallet::SelectCoins(const CAmount& nTargetValue, set<pair<const CWalletTx*, unsigned int> >& setCoinsRet, CAmount& nValueRet, const CCoinControl* coinControl, AvailableCoinsType coin_type, bool useIX) const { // Note: this function should never be used for "always free" tx types like dstx vector<COutput> vCoins; AvailableCoins(vCoins, true, coinControl, false, coin_type, useIX); // coin control -> return all selected outputs (we want all selected to go into the transaction for sure) if (coinControl && coinControl->HasSelected()) { BOOST_FOREACH (const COutput& out, vCoins) { if (!out.fSpendable) continue; if (coin_type == ONLY_DENOMINATED) { CTxIn vin = CTxIn(out.tx->GetHash(), out.i); int rounds = GetInputObfuscationRounds(vin); // make sure it's actually anonymized if (rounds < nObfuscationRounds) continue; } nValueRet += out.tx->vout[out.i].nValue; setCoinsRet.insert(make_pair(out.tx, out.i)); } return (nValueRet >= nTargetValue); } //if we're doing only denominated, we need to round up to the nearest .1 HRLD if (coin_type == ONLY_DENOMINATED) { // Make outputs by looping through denominations, from large to small BOOST_FOREACH (CAmount v, obfuScationDenominations) { BOOST_FOREACH (const COutput& out, vCoins) { if (out.tx->vout[out.i].nValue == v //make sure it's the denom we're looking for && nValueRet + out.tx->vout[out.i].nValue < nTargetValue + (0.1 * COIN) + 100 //round the amount up to .1 HRLD over ) { CTxIn vin = CTxIn(out.tx->GetHash(), out.i); int rounds = GetInputObfuscationRounds(vin); // make sure it's actually anonymized if (rounds < nObfuscationRounds) continue; nValueRet += out.tx->vout[out.i].nValue; setCoinsRet.insert(make_pair(out.tx, out.i)); } } } return (nValueRet >= nTargetValue); } return (SelectCoinsMinConf(nTargetValue, 1, 6, vCoins, setCoinsRet, nValueRet) || SelectCoinsMinConf(nTargetValue, 1, 1, vCoins, setCoinsRet, nValueRet) || (bSpendZeroConfChange && SelectCoinsMinConf(nTargetValue, 0, 1, vCoins, setCoinsRet, nValueRet))); } struct CompareByPriority { bool operator()(const COutput& t1, const COutput& t2) const { return t1.Priority() > t2.Priority(); } }; bool CWallet::SelectCoinsByDenominations(int nDenom, CAmount nValueMin, CAmount nValueMax, std::vector<CTxIn>& vCoinsRet, std::vector<COutput>& vCoinsRet2, CAmount& nValueRet, int nObfuscationRoundsMin, int nObfuscationRoundsMax) { vCoinsRet.clear(); nValueRet = 0; vCoinsRet2.clear(); vector<COutput> vCoins; AvailableCoins(vCoins, true, NULL, ONLY_DENOMINATED); std::random_shuffle(vCoins.rbegin(), vCoins.rend()); //keep track of each denomination that we have bool fFound10000 = false; bool fFound1000 = false; bool fFound100 = false; bool fFound10 = false; bool fFound1 = false; bool fFoundDot1 = false; //Check to see if any of the denomination are off, in that case mark them as fulfilled if (!(nDenom & (1 << 0))) fFound10000 = true; if (!(nDenom & (1 << 1))) fFound1000 = true; if (!(nDenom & (1 << 2))) fFound100 = true; if (!(nDenom & (1 << 3))) fFound10 = true; if (!(nDenom & (1 << 4))) fFound1 = true; if (!(nDenom & (1 << 5))) fFoundDot1 = true; BOOST_FOREACH (const COutput& out, vCoins) { // masternode-like input should not be selected by AvailableCoins now anyway //if(out.tx->vout[out.i].nValue == 10000*COIN) continue; if (nValueRet + out.tx->vout[out.i].nValue <= nValueMax) { bool fAccepted = false; // Function returns as follows: // // bit 0 - 10000 HRLD+1 ( bit on if present ) // bit 1 - 1000 HRLD+1 // bit 2 - 100 HRLD+1 // bit 3 - 10 HRLD+1 // bit 4 - 1 HRLD+1 // bit 5 - .1 HRLD+1 CTxIn vin = CTxIn(out.tx->GetHash(), out.i); int rounds = GetInputObfuscationRounds(vin); if (rounds >= nObfuscationRoundsMax) continue; if (rounds < nObfuscationRoundsMin) continue; if (fFound10000 && fFound1000 && fFound100 && fFound10 && fFound1 && fFoundDot1) { //if fulfilled //we can return this for submission if (nValueRet >= nValueMin) { //random reduce the max amount we'll submit for anonymity nValueMax -= (rand() % (nValueMax / 5)); //on average use 50% of the inputs or less int r = (rand() % (int)vCoins.size()); if ((int)vCoinsRet.size() > r) return true; } //Denomination criterion has been met, we can take any matching denominations if ((nDenom & (1 << 0)) && out.tx->vout[out.i].nValue == ((10000 * COIN) + 10000000)) { fAccepted = true; } else if ((nDenom & (1 << 1)) && out.tx->vout[out.i].nValue == ((1000 * COIN) + 1000000)) { fAccepted = true; } else if ((nDenom & (1 << 2)) && out.tx->vout[out.i].nValue == ((100 * COIN) + 100000)) { fAccepted = true; } else if ((nDenom & (1 << 3)) && out.tx->vout[out.i].nValue == ((10 * COIN) + 10000)) { fAccepted = true; } else if ((nDenom & (1 << 4)) && out.tx->vout[out.i].nValue == ((1 * COIN) + 1000)) { fAccepted = true; } else if ((nDenom & (1 << 5)) && out.tx->vout[out.i].nValue == ((.1 * COIN) + 100)) { fAccepted = true; } } else { //Criterion has not been satisfied, we will only take 1 of each until it is. if ((nDenom & (1 << 0)) && out.tx->vout[out.i].nValue == ((10000 * COIN) + 10000000)) { fAccepted = true; fFound10000 = true; } else if ((nDenom & (1 << 1)) && out.tx->vout[out.i].nValue == ((1000 * COIN) + 1000000)) { fAccepted = true; fFound1000 = true; } else if ((nDenom & (1 << 2)) && out.tx->vout[out.i].nValue == ((100 * COIN) + 100000)) { fAccepted = true; fFound100 = true; } else if ((nDenom & (1 << 3)) && out.tx->vout[out.i].nValue == ((10 * COIN) + 10000)) { fAccepted = true; fFound10 = true; } else if ((nDenom & (1 << 4)) && out.tx->vout[out.i].nValue == ((1 * COIN) + 1000)) { fAccepted = true; fFound1 = true; } else if ((nDenom & (1 << 5)) && out.tx->vout[out.i].nValue == ((.1 * COIN) + 100)) { fAccepted = true; fFoundDot1 = true; } } if (!fAccepted) continue; vin.prevPubKey = out.tx->vout[out.i].scriptPubKey; // the inputs PubKey nValueRet += out.tx->vout[out.i].nValue; vCoinsRet.push_back(vin); vCoinsRet2.push_back(out); } } return (nValueRet >= nValueMin && fFound10000 && fFound1000 && fFound100 && fFound10 && fFound1 && fFoundDot1); } bool CWallet::SelectCoinsDark(CAmount nValueMin, CAmount nValueMax, std::vector<CTxIn>& setCoinsRet, CAmount& nValueRet, int nObfuscationRoundsMin, int nObfuscationRoundsMax) const { CCoinControl* coinControl = NULL; setCoinsRet.clear(); nValueRet = 0; vector<COutput> vCoins; AvailableCoins(vCoins, true, coinControl, nObfuscationRoundsMin < 0 ? ONLY_NONDENOMINATED_NOT10000IFMN : ONLY_DENOMINATED); set<pair<const CWalletTx*, unsigned int> > setCoinsRet2; //order the array so largest nondenom are first, then denominations, then very small inputs. sort(vCoins.rbegin(), vCoins.rend(), CompareByPriority()); BOOST_FOREACH (const COutput& out, vCoins) { //do not allow inputs less than 1 CENT if (out.tx->vout[out.i].nValue < CENT) continue; //do not allow collaterals to be selected if (IsCollateralAmount(out.tx->vout[out.i].nValue)) continue; if (fMasterNode && out.tx->vout[out.i].nValue == 50000 * COIN) continue; //masternode input if (nValueRet + out.tx->vout[out.i].nValue <= nValueMax) { CTxIn vin = CTxIn(out.tx->GetHash(), out.i); int rounds = GetInputObfuscationRounds(vin); if (rounds >= nObfuscationRoundsMax) continue; if (rounds < nObfuscationRoundsMin) continue; vin.prevPubKey = out.tx->vout[out.i].scriptPubKey; // the inputs PubKey nValueRet += out.tx->vout[out.i].nValue; setCoinsRet.push_back(vin); setCoinsRet2.insert(make_pair(out.tx, out.i)); } } // if it's more than min, we're good to return if (nValueRet >= nValueMin) return true; return false; } bool CWallet::SelectCoinsCollateral(std::vector<CTxIn>& setCoinsRet, CAmount& nValueRet) const { vector<COutput> vCoins; //LogPrintf(" selecting coins for collateral\n"); AvailableCoins(vCoins); //LogPrintf("found coins %d\n", (int)vCoins.size()); set<pair<const CWalletTx*, unsigned int> > setCoinsRet2; BOOST_FOREACH (const COutput& out, vCoins) { // collateral inputs will always be a multiple of DARSEND_COLLATERAL, up to five if (IsCollateralAmount(out.tx->vout[out.i].nValue)) { CTxIn vin = CTxIn(out.tx->GetHash(), out.i); vin.prevPubKey = out.tx->vout[out.i].scriptPubKey; // the inputs PubKey nValueRet += out.tx->vout[out.i].nValue; setCoinsRet.push_back(vin); setCoinsRet2.insert(make_pair(out.tx, out.i)); return true; } } return false; } int CWallet::CountInputsWithAmount(CAmount nInputAmount) { int64_t nTotal = 0; { LOCK(cs_wallet); for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) { const CWalletTx* pcoin = &(*it).second; if (pcoin->IsTrusted()) { int nDepth = pcoin->GetDepthInMainChain(false); for (unsigned int i = 0; i < pcoin->vout.size(); i++) { COutput out = COutput(pcoin, i, nDepth, true); CTxIn vin = CTxIn(out.tx->GetHash(), out.i); if (out.tx->vout[out.i].nValue != nInputAmount) continue; if (!IsDenominatedAmount(pcoin->vout[i].nValue)) continue; if (IsSpent(out.tx->GetHash(), i) || IsMine(pcoin->vout[i]) != ISMINE_SPENDABLE || !IsDenominated(vin)) continue; nTotal++; } } } } return nTotal; } bool CWallet::HasCollateralInputs(bool fOnlyConfirmed) const { vector<COutput> vCoins; AvailableCoins(vCoins, fOnlyConfirmed); int nFound = 0; BOOST_FOREACH (const COutput& out, vCoins) if (IsCollateralAmount(out.tx->vout[out.i].nValue)) nFound++; return nFound > 0; } bool CWallet::IsCollateralAmount(CAmount nInputAmount) const { return nInputAmount != 0 && nInputAmount % OBFUSCATION_COLLATERAL == 0 && nInputAmount < OBFUSCATION_COLLATERAL * 5 && nInputAmount > OBFUSCATION_COLLATERAL; } bool CWallet::CreateCollateralTransaction(CMutableTransaction& txCollateral, std::string& strReason) { /* To doublespend a collateral transaction, it will require a fee higher than this. So there's still a significant cost. */ CAmount nFeeRet = 1 * COIN; txCollateral.vin.clear(); txCollateral.vout.clear(); CReserveKey reservekey(this); CAmount nValueIn2 = 0; std::vector<CTxIn> vCoinsCollateral; if (!SelectCoinsCollateral(vCoinsCollateral, nValueIn2)) { strReason = "Error: Obfuscation requires a collateral transaction and could not locate an acceptable input!"; return false; } // make our change address CScript scriptChange; CPubKey vchPubKey; assert(reservekey.GetReservedKey(vchPubKey)); // should never fail, as we just unlocked scriptChange = GetScriptForDestination(vchPubKey.GetID()); reservekey.KeepKey(); BOOST_FOREACH (CTxIn v, vCoinsCollateral) txCollateral.vin.push_back(v); if (nValueIn2 - OBFUSCATION_COLLATERAL - nFeeRet > 0) { //pay collateral charge in fees CTxOut vout3 = CTxOut(nValueIn2 - OBFUSCATION_COLLATERAL, scriptChange); txCollateral.vout.push_back(vout3); } int vinNumber = 0; BOOST_FOREACH (CTxIn v, txCollateral.vin) { if (!SignSignature(*this, v.prevPubKey, txCollateral, vinNumber, int(SIGHASH_ALL | SIGHASH_ANYONECANPAY))) { BOOST_FOREACH (CTxIn v, vCoinsCollateral) UnlockCoin(v.prevout); strReason = "CObfuscationPool::Sign - Unable to sign collateral transaction! \n"; return false; } vinNumber++; } return true; } bool CWallet::GetBudgetSystemCollateralTX(CTransaction& tx, uint256 hash, bool useIX) { CWalletTx wtx; if (GetBudgetSystemCollateralTX(wtx, hash, useIX)) { tx = (CTransaction)wtx; return true; } return false; } bool CWallet::GetBudgetSystemCollateralTX(CWalletTx& tx, uint256 hash, bool useIX) { // make our change address CReserveKey reservekey(pwalletMain); CScript scriptChange; scriptChange << OP_RETURN << ToByteVector(hash); CAmount nFeeRet = 0; std::string strFail = ""; vector<pair<CScript, CAmount> > vecSend; vecSend.push_back(make_pair(scriptChange, BUDGET_FEE_TX)); CCoinControl* coinControl = NULL; bool success = CreateTransaction(vecSend, tx, reservekey, nFeeRet, strFail, coinControl, ALL_COINS, useIX, (CAmount)0); if (!success) { LogPrintf("GetBudgetSystemCollateralTX: Error - %s\n", strFail); return false; } return true; } bool CWallet::ConvertList(std::vector<CTxIn> vCoins, std::vector<CAmount>& vecAmounts) { BOOST_FOREACH (CTxIn i, vCoins) { if (mapWallet.count(i.prevout.hash)) { CWalletTx& wtx = mapWallet[i.prevout.hash]; if (i.prevout.n < wtx.vout.size()) { vecAmounts.push_back(wtx.vout[i.prevout.n].nValue); } } else { LogPrintf("ConvertList -- Couldn't find transaction\n"); } } return true; } bool CWallet::CreateTransaction(const vector<pair<CScript, CAmount> >& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, CAmount& nFeeRet, std::string& strFailReason, const CCoinControl* coinControl, AvailableCoinsType coin_type, bool useIX, CAmount nFeePay) { if (useIX && nFeePay < CENT) nFeePay = CENT; CAmount nValue = 0; BOOST_FOREACH (const PAIRTYPE(CScript, CAmount) & s, vecSend) { if (nValue < 0) { strFailReason = _("Transaction amounts must be positive"); return false; } nValue += s.second; } if (vecSend.empty() || nValue < 0) { strFailReason = _("Transaction amounts must be positive"); return false; } wtxNew.fTimeReceivedIsTxTime = true; wtxNew.BindWallet(this); CMutableTransaction txNew; { LOCK2(cs_main, cs_wallet); { nFeeRet = 0; if (nFeePay > 0) nFeeRet = nFeePay; while (true) { txNew.vin.clear(); txNew.vout.clear(); wtxNew.fFromMe = true; CAmount nTotalValue = nValue + nFeeRet; double dPriority = 0; // vouts to the payees if (coinControl && !coinControl->fSplitBlock) { BOOST_FOREACH (const PAIRTYPE(CScript, CAmount) & s, vecSend) { CTxOut txout(s.second, s.first); if (txout.IsDust(::minRelayTxFee)) { strFailReason = _("Transaction amount too small"); return false; } txNew.vout.push_back(txout); } } else //UTXO Splitter Transaction { int nSplitBlock; if (coinControl) nSplitBlock = coinControl->nSplitBlock; else nSplitBlock = 1; BOOST_FOREACH (const PAIRTYPE(CScript, CAmount) & s, vecSend) { for (int i = 0; i < nSplitBlock; i++) { if (i == nSplitBlock - 1) { uint64_t nRemainder = s.second % nSplitBlock; txNew.vout.push_back(CTxOut((s.second / nSplitBlock) + nRemainder, s.first)); } else txNew.vout.push_back(CTxOut(s.second / nSplitBlock, s.first)); } } } // Choose coins to use set<pair<const CWalletTx*, unsigned int> > setCoins; CAmount nValueIn = 0; if (!SelectCoins(nTotalValue, setCoins, nValueIn, coinControl, coin_type, useIX)) { if (coin_type == ALL_COINS) { strFailReason = _("Insufficient funds."); } else if (coin_type == ONLY_NOT10000IFMN) { strFailReason = _("Unable to locate enough funds for this transaction that are not equal 10000 HRLD."); } else if (coin_type == ONLY_NONDENOMINATED_NOT10000IFMN) { strFailReason = _("Unable to locate enough Obfuscation non-denominated funds for this transaction that are not equal 10000 HRLD."); } else { strFailReason = _("Unable to locate enough Obfuscation denominated funds for this transaction."); strFailReason += " " + _("Obfuscation uses exact denominated amounts to send funds, you might simply need to anonymize some more coins."); } if (useIX) { strFailReason += " " + _("SwiftTX requires inputs with at least 6 confirmations, you might need to wait a few minutes and try again."); } return false; } BOOST_FOREACH (PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins) { CAmount nCredit = pcoin.first->vout[pcoin.second].nValue; //The coin age after the next block (depth+1) is used instead of the current, //reflecting an assumption the user would accept a bit more delay for //a chance at a free transaction. //But mempool inputs might still be in the mempool, so their age stays 0 int age = pcoin.first->GetDepthInMainChain(); if (age != 0) age += 1; dPriority += (double)nCredit * age; } CAmount nChange = nValueIn - nValue - nFeeRet; //over pay for denominated transactions if (coin_type == ONLY_DENOMINATED) { nFeeRet += nChange; nChange = 0; wtxNew.mapValue["DS"] = "1"; } if (nChange > 0) { // Fill a vout to ourself // TODO: pass in scriptChange instead of reservekey so // change transaction isn't always pay-to-haroldcoin-address CScript scriptChange; // coin control: send change to custom address if (coinControl && !boost::get<CNoDestination>(&coinControl->destChange)) scriptChange = GetScriptForDestination(coinControl->destChange); // no coin control: send change to newly generated address else { // Note: We use a new key here to keep it from being obvious which side is the change. // The drawback is that by not reusing a previous key, the change may be lost if a // backup is restored, if the backup doesn't have the new private key for the change. // If we reused the old key, it would be possible to add code to look for and // rediscover unknown transactions that were written with keys of ours to recover // post-backup change. // Reserve a new key pair from key pool CPubKey vchPubKey; bool ret; ret = reservekey.GetReservedKey(vchPubKey); assert(ret); // should never fail, as we just unlocked scriptChange = GetScriptForDestination(vchPubKey.GetID()); } CTxOut newTxOut(nChange, scriptChange); // Never create dust outputs; if we would, just // add the dust to the fee. if (newTxOut.IsDust(::minRelayTxFee)) { nFeeRet += nChange; nChange = 0; reservekey.ReturnKey(); } else { // Insert change txn at random position: vector<CTxOut>::iterator position = txNew.vout.begin() + GetRandInt(txNew.vout.size() + 1); txNew.vout.insert(position, newTxOut); } } else reservekey.ReturnKey(); // Fill vin BOOST_FOREACH (const PAIRTYPE(const CWalletTx*, unsigned int) & coin, setCoins) txNew.vin.push_back(CTxIn(coin.first->GetHash(), coin.second)); // Sign int nIn = 0; BOOST_FOREACH (const PAIRTYPE(const CWalletTx*, unsigned int) & coin, setCoins) if (!SignSignature(*this, *coin.first, txNew, nIn++)) { strFailReason = _("Signing transaction failed"); return false; } // Embed the constructed transaction data in wtxNew. *static_cast<CTransaction*>(&wtxNew) = CTransaction(txNew); // Limit size unsigned int nBytes = ::GetSerializeSize(*(CTransaction*)&wtxNew, SER_NETWORK, PROTOCOL_VERSION); if (nBytes >= MAX_STANDARD_TX_SIZE) { strFailReason = _("Transaction too large"); return false; } dPriority = wtxNew.ComputePriority(dPriority, nBytes); // Can we complete this as a free transaction? if (fSendFreeTransactions && nBytes <= MAX_FREE_TRANSACTION_CREATE_SIZE) { // Not enough fee: enough priority? double dPriorityNeeded = mempool.estimatePriority(nTxConfirmTarget); // Not enough mempool history to estimate: use hard-coded AllowFree. if (dPriorityNeeded <= 0 && AllowFree(dPriority)) break; // Small enough, and priority high enough, to send for free if (dPriorityNeeded > 0 && dPriority >= dPriorityNeeded) break; } CAmount nFeeNeeded = max(nFeePay, GetMinimumFee(nBytes, nTxConfirmTarget, mempool)); // If we made it here and we aren't even able to meet the relay fee on the next pass, give up // because we must be at the maximum allowed fee. if (nFeeNeeded < ::minRelayTxFee.GetFee(nBytes)) { strFailReason = _("Transaction too large for fee policy"); return false; } if (nFeeRet >= nFeeNeeded) // Done, enough fee included break; // Include more fee and try again. nFeeRet = nFeeNeeded; continue; } } } return true; } bool CWallet::CreateTransaction(CScript scriptPubKey, const CAmount& nValue, CWalletTx& wtxNew, CReserveKey& reservekey, CAmount& nFeeRet, std::string& strFailReason, const CCoinControl* coinControl, AvailableCoinsType coin_type, bool useIX, CAmount nFeePay) { vector<pair<CScript, CAmount> > vecSend; vecSend.push_back(make_pair(scriptPubKey, nValue)); return CreateTransaction(vecSend, wtxNew, reservekey, nFeeRet, strFailReason, coinControl, coin_type, useIX, nFeePay); } // ppcoin: create coin stake transaction bool CWallet::CreateCoinStake(const CKeyStore& keystore, unsigned int nBits, int64_t nSearchInterval, CMutableTransaction& txNew, unsigned int& nTxNewTime) { // The following split & combine thresholds are important to security // Should not be adjusted if you don't understand the consequences //int64_t nCombineThreshold = 0; txNew.vin.clear(); txNew.vout.clear(); // Mark coin stake transaction CScript scriptEmpty; scriptEmpty.clear(); txNew.vout.push_back(CTxOut(0, scriptEmpty)); // Choose coins to use CAmount nBalance = GetBalance(); if (mapArgs.count("-reservebalance") && !ParseMoney(mapArgs["-reservebalance"], nReserveBalance)) return error("CreateCoinStake : invalid reserve balance amount"); if (nBalance <= nReserveBalance) return false; // presstab HyperStake - Initialize as static and don't update the set on every run of CreateCoinStake() in order to lighten resource use static std::set<pair<const CWalletTx*, unsigned int> > setStakeCoins; static int nLastStakeSetUpdate = 0; if (GetTime() - nLastStakeSetUpdate > nStakeSetUpdateTime) { setStakeCoins.clear(); if (!SelectStakeCoins(setStakeCoins, nBalance - nReserveBalance)) return false; nLastStakeSetUpdate = GetTime(); } if (setStakeCoins.empty()) return false; vector<const CWalletTx*> vwtxPrev; CAmount nCredit = 0; CScript scriptPubKeyKernel; //prevent staking a time that won't be accepted if (GetAdjustedTime() <= chainActive.Tip()->nTime) MilliSleep(10000); BOOST_FOREACH (PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setStakeCoins) { //make sure that enough time has elapsed between CBlockIndex* pindex = NULL; BlockMap::iterator it = mapBlockIndex.find(pcoin.first->hashBlock); if (it != mapBlockIndex.end()) pindex = it->second; else { if (fDebug) LogPrintf("CreateCoinStake() failed to find block index \n"); continue; } // Read block header CBlockHeader block = pindex->GetBlockHeader(); bool fKernelFound = false; uint256 hashProofOfStake = 0; COutPoint prevoutStake = COutPoint(pcoin.first->GetHash(), pcoin.second); nTxNewTime = GetAdjustedTime(); //iterates each utxo inside of CheckStakeKernelHash() if (CheckStakeKernelHash(nBits, block, *pcoin.first, prevoutStake, nTxNewTime, nHashDrift, false, hashProofOfStake, true)) { //Double check that this will pass time requirements if (nTxNewTime <= chainActive.Tip()->GetMedianTimePast()) { LogPrintf("CreateCoinStake() : kernel found, but it is too far in the past \n"); continue; } // Found a kernel if (fDebug && GetBoolArg("-printcoinstake", false)) LogPrintf("CreateCoinStake : kernel found\n"); vector<valtype> vSolutions; txnouttype whichType; CScript scriptPubKeyOut; scriptPubKeyKernel = pcoin.first->vout[pcoin.second].scriptPubKey; if (!Solver(scriptPubKeyKernel, whichType, vSolutions)) { LogPrintf("CreateCoinStake : failed to parse kernel\n"); break; } if (fDebug && GetBoolArg("-printcoinstake", false)) LogPrintf("CreateCoinStake : parsed kernel type=%d\n", whichType); if (whichType != TX_PUBKEY && whichType != TX_PUBKEYHASH) { if (fDebug && GetBoolArg("-printcoinstake", false)) LogPrintf("CreateCoinStake : no support for kernel type=%d\n", whichType); break; // only support pay to public key and pay to address } if (whichType == TX_PUBKEYHASH) // pay to address type { //convert to pay to public key type CKey key; if (!keystore.GetKey(uint160(vSolutions[0]), key)) { if (fDebug && GetBoolArg("-printcoinstake", false)) LogPrintf("CreateCoinStake : failed to get key for kernel type=%d\n", whichType); break; // unable to find corresponding public key } scriptPubKeyOut << key.GetPubKey() << OP_CHECKSIG; } else scriptPubKeyOut = scriptPubKeyKernel; txNew.vin.push_back(CTxIn(pcoin.first->GetHash(), pcoin.second)); nCredit += pcoin.first->vout[pcoin.second].nValue; vwtxPrev.push_back(pcoin.first); txNew.vout.push_back(CTxOut(0, scriptPubKeyOut)); //presstab HyperStake - calculate the total size of our new output including the stake reward so that we can use it to decide whether to split the stake outputs const CBlockIndex* pIndex0 = chainActive.Tip(); uint64_t nTotalSize = pcoin.first->vout[pcoin.second].nValue + GetBlockValue(pIndex0->nHeight); //presstab HyperStake - if MultiSend is set to send in coinstake we will add our outputs here (values asigned further down) if (nTotalSize / 2 > nStakeSplitThreshold * COIN) txNew.vout.push_back(CTxOut(0, scriptPubKeyOut)); //split stake if (fDebug && GetBoolArg("-printcoinstake", false)) LogPrintf("CreateCoinStake : added kernel type=%d\n", whichType); fKernelFound = true; break; } if (fKernelFound) break; // if kernel is found stop searching } if (nCredit == 0 || nCredit > nBalance - nReserveBalance) return false; // Calculate reward CAmount nReward; const CBlockIndex* pIndex0 = chainActive.Tip(); nReward = GetBlockValue(pIndex0->nHeight); nCredit += nReward; CAmount nMinFee = 0; while (true) { // Set output amount if (txNew.vout.size() == 3) { txNew.vout[1].nValue = ((nCredit - nMinFee) / 2 / CENT) * CENT; txNew.vout[2].nValue = nCredit - nMinFee - txNew.vout[1].nValue; } else txNew.vout[1].nValue = nCredit - nMinFee; // Limit size unsigned int nBytes = ::GetSerializeSize(txNew, SER_NETWORK, PROTOCOL_VERSION); if (nBytes >= DEFAULT_BLOCK_MAX_SIZE / 5) return error("CreateCoinStake : exceeded coinstake size limit"); CAmount nFeeNeeded = GetMinimumFee(nBytes, nTxConfirmTarget, mempool); // Check enough fee is paid if (nMinFee < nFeeNeeded) { nMinFee = nFeeNeeded; continue; // try signing again } else { if (fDebug) LogPrintf("CreateCoinStake : fee for coinstake %s\n", FormatMoney(nMinFee).c_str()); break; } } //Masternode payment FillBlockPayee(txNew, nMinFee, true); // Sign int nIn = 0; BOOST_FOREACH (const CWalletTx* pcoin, vwtxPrev) { if (!SignSignature(*this, *pcoin, txNew, nIn++)) return error("CreateCoinStake : failed to sign coinstake"); } // Successfully generated coinstake nLastStakeSetUpdate = 0; //this will trigger stake set to repopulate next round return true; } /** * Call after CreateTransaction unless you want to abort */ bool CWallet::CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey, std::string strCommand) { { LOCK2(cs_main, cs_wallet); LogPrintf("CommitTransaction:\n%s", wtxNew.ToString()); { // This is only to keep the database open to defeat the auto-flush for the // duration of this scope. This is the only place where this optimization // maybe makes sense; please don't do it anywhere else. CWalletDB* pwalletdb = fFileBacked ? new CWalletDB(strWalletFile, "r") : NULL; // Take key pair from key pool so it won't be used again reservekey.KeepKey(); // Add tx to wallet, because if it has change it's also ours, // otherwise just for transaction history. AddToWallet(wtxNew); // Notify that old coins are spent set<uint256> updated_hahes; BOOST_FOREACH (const CTxIn& txin, wtxNew.vin) { // notify only once if (updated_hahes.find(txin.prevout.hash) != updated_hahes.end()) continue; CWalletTx& coin = mapWallet[txin.prevout.hash]; coin.BindWallet(this); NotifyTransactionChanged(this, txin.prevout.hash, CT_UPDATED); updated_hahes.insert(txin.prevout.hash); } if (fFileBacked) delete pwalletdb; } // Track how many getdata requests our transaction gets mapRequestCount[wtxNew.GetHash()] = 0; // Broadcast if (!wtxNew.AcceptToMemoryPool(false)) { // This must not fail. The transaction has already been signed and recorded. LogPrintf("CommitTransaction() : Error: Transaction not valid\n"); return false; } wtxNew.RelayWalletTransaction(strCommand); } return true; } CAmount CWallet::GetMinimumFee(unsigned int nTxBytes, unsigned int nConfirmTarget, const CTxMemPool& pool) { // payTxFee is user-set "I want to pay this much" CAmount nFeeNeeded = payTxFee.GetFee(nTxBytes); // user selected total at least (default=true) if (fPayAtLeastCustomFee && nFeeNeeded > 0 && nFeeNeeded < payTxFee.GetFeePerK()) nFeeNeeded = payTxFee.GetFeePerK(); // User didn't set: use -txconfirmtarget to estimate... if (nFeeNeeded == 0) nFeeNeeded = pool.estimateFee(nConfirmTarget).GetFee(nTxBytes); // ... unless we don't have enough mempool data, in which case fall // back to a hard-coded fee if (nFeeNeeded == 0) nFeeNeeded = minTxFee.GetFee(nTxBytes); // prevent user from paying a non-sense fee (like 1 satoshi): 0 < fee < minRelayFee if (nFeeNeeded < ::minRelayTxFee.GetFee(nTxBytes)) nFeeNeeded = ::minRelayTxFee.GetFee(nTxBytes); // But always obey the maximum if (nFeeNeeded > maxTxFee) nFeeNeeded = maxTxFee; return nFeeNeeded; } CAmount CWallet::GetTotalValue(std::vector<CTxIn> vCoins) { CAmount nTotalValue = 0; CWalletTx wtx; BOOST_FOREACH (CTxIn i, vCoins) { if (mapWallet.count(i.prevout.hash)) { CWalletTx& wtx = mapWallet[i.prevout.hash]; if (i.prevout.n < wtx.vout.size()) { nTotalValue += wtx.vout[i.prevout.n].nValue; } } else { LogPrintf("GetTotalValue -- Couldn't find transaction\n"); } } return nTotalValue; } string CWallet::PrepareObfuscationDenominate(int minRounds, int maxRounds) { if (IsLocked()) return _("Error: Wallet locked, unable to create transaction!"); if (obfuScationPool.GetState() != POOL_STATUS_ERROR && obfuScationPool.GetState() != POOL_STATUS_SUCCESS) if (obfuScationPool.GetEntriesCount() > 0) return _("Error: You already have pending entries in the Obfuscation pool"); // ** find the coins we'll use std::vector<CTxIn> vCoins; std::vector<CTxIn> vCoinsResult; std::vector<COutput> vCoins2; CAmount nValueIn = 0; CReserveKey reservekey(this); /* Select the coins we'll use if minRounds >= 0 it means only denominated inputs are going in and coming out */ if (minRounds >= 0) { if (!SelectCoinsByDenominations(obfuScationPool.sessionDenom, 0.1 * COIN, OBFUSCATION_POOL_MAX, vCoins, vCoins2, nValueIn, minRounds, maxRounds)) return _("Error: Can't select current denominated inputs"); } LogPrintf("PrepareObfuscationDenominate - preparing obfuscation denominate . Got: %d \n", nValueIn); { LOCK(cs_wallet); BOOST_FOREACH (CTxIn v, vCoins) LockCoin(v.prevout); } CAmount nValueLeft = nValueIn; std::vector<CTxOut> vOut; /* TODO: Front load with needed denominations (e.g. .1, 1 ) */ // Make outputs by looping through denominations: try to add every needed denomination, repeat up to 5-10 times. // This way we can be pretty sure that it should have at least one of each needed denomination. // NOTE: No need to randomize order of inputs because they were // initially shuffled in CWallet::SelectCoinsByDenominations already. int nStep = 0; int nStepsMax = 5 + GetRandInt(5); while (nStep < nStepsMax) { BOOST_FOREACH (CAmount v, obfuScationDenominations) { // only use the ones that are approved bool fAccepted = false; if ((obfuScationPool.sessionDenom & (1 << 0)) && v == ((10000 * COIN) + 10000000)) { fAccepted = true; } else if ((obfuScationPool.sessionDenom & (1 << 1)) && v == ((1000 * COIN) + 1000000)) { fAccepted = true; } else if ((obfuScationPool.sessionDenom & (1 << 2)) && v == ((100 * COIN) + 100000)) { fAccepted = true; } else if ((obfuScationPool.sessionDenom & (1 << 3)) && v == ((10 * COIN) + 10000)) { fAccepted = true; } else if ((obfuScationPool.sessionDenom & (1 << 4)) && v == ((1 * COIN) + 1000)) { fAccepted = true; } else if ((obfuScationPool.sessionDenom & (1 << 5)) && v == ((.1 * COIN) + 100)) { fAccepted = true; } if (!fAccepted) continue; // try to add it if (nValueLeft - v >= 0) { // Note: this relies on a fact that both vectors MUST have same size std::vector<CTxIn>::iterator it = vCoins.begin(); std::vector<COutput>::iterator it2 = vCoins2.begin(); while (it2 != vCoins2.end()) { // we have matching inputs if ((*it2).tx->vout[(*it2).i].nValue == v) { // add new input in resulting vector vCoinsResult.push_back(*it); // remove corresponting items from initial vectors vCoins.erase(it); vCoins2.erase(it2); CScript scriptChange; CPubKey vchPubKey; // use a unique change address assert(reservekey.GetReservedKey(vchPubKey)); // should never fail, as we just unlocked scriptChange = GetScriptForDestination(vchPubKey.GetID()); reservekey.KeepKey(); // add new output CTxOut o(v, scriptChange); vOut.push_back(o); // subtract denomination amount nValueLeft -= v; break; } ++it; ++it2; } } } nStep++; if (nValueLeft == 0) break; } { // unlock unused coins LOCK(cs_wallet); BOOST_FOREACH (CTxIn v, vCoins) UnlockCoin(v.prevout); } if (obfuScationPool.GetDenominations(vOut) != obfuScationPool.sessionDenom) { // unlock used coins on failure LOCK(cs_wallet); BOOST_FOREACH (CTxIn v, vCoinsResult) UnlockCoin(v.prevout); return "Error: can't make current denominated outputs"; } // randomize the output order std::random_shuffle(vOut.begin(), vOut.end()); // We also do not care about full amount as long as we have right denominations, just pass what we found obfuScationPool.SendObfuscationDenominate(vCoinsResult, vOut, nValueIn - nValueLeft); return ""; } DBErrors CWallet::LoadWallet(bool& fFirstRunRet) { if (!fFileBacked) return DB_LOAD_OK; fFirstRunRet = false; DBErrors nLoadWalletRet = CWalletDB(strWalletFile, "cr+").LoadWallet(this); if (nLoadWalletRet == DB_NEED_REWRITE) { if (CDB::Rewrite(strWalletFile, "\x04pool")) { LOCK(cs_wallet); setKeyPool.clear(); // Note: can't top-up keypool here, because wallet is locked. // User will be prompted to unlock wallet the next operation // the requires a new key. } } if (nLoadWalletRet != DB_LOAD_OK) return nLoadWalletRet; fFirstRunRet = !vchDefaultKey.IsValid(); uiInterface.LoadWallet(this); return DB_LOAD_OK; } DBErrors CWallet::ZapWalletTx(std::vector<CWalletTx>& vWtx) { if (!fFileBacked) return DB_LOAD_OK; DBErrors nZapWalletTxRet = CWalletDB(strWalletFile, "cr+").ZapWalletTx(this, vWtx); if (nZapWalletTxRet == DB_NEED_REWRITE) { if (CDB::Rewrite(strWalletFile, "\x04pool")) { LOCK(cs_wallet); setKeyPool.clear(); // Note: can't top-up keypool here, because wallet is locked. // User will be prompted to unlock wallet the next operation // that requires a new key. } } if (nZapWalletTxRet != DB_LOAD_OK) return nZapWalletTxRet; return DB_LOAD_OK; } bool CWallet::SetAddressBook(const CTxDestination& address, const string& strName, const string& strPurpose) { bool fUpdated = false; { LOCK(cs_wallet); // mapAddressBook std::map<CTxDestination, CAddressBookData>::iterator mi = mapAddressBook.find(address); fUpdated = mi != mapAddressBook.end(); mapAddressBook[address].name = strName; if (!strPurpose.empty()) /* update purpose only if requested */ mapAddressBook[address].purpose = strPurpose; } NotifyAddressBookChanged(this, address, strName, ::IsMine(*this, address) != ISMINE_NO, strPurpose, (fUpdated ? CT_UPDATED : CT_NEW)); if (!fFileBacked) return false; if (!strPurpose.empty() && !CWalletDB(strWalletFile).WritePurpose(CBitcoinAddress(address).ToString(), strPurpose)) return false; return CWalletDB(strWalletFile).WriteName(CBitcoinAddress(address).ToString(), strName); } bool CWallet::DelAddressBook(const CTxDestination& address) { { LOCK(cs_wallet); // mapAddressBook if (fFileBacked) { // Delete destdata tuples associated with address std::string strAddress = CBitcoinAddress(address).ToString(); BOOST_FOREACH (const PAIRTYPE(string, string) & item, mapAddressBook[address].destdata) { CWalletDB(strWalletFile).EraseDestData(strAddress, item.first); } } mapAddressBook.erase(address); } NotifyAddressBookChanged(this, address, "", ::IsMine(*this, address) != ISMINE_NO, "", CT_DELETED); if (!fFileBacked) return false; CWalletDB(strWalletFile).ErasePurpose(CBitcoinAddress(address).ToString()); return CWalletDB(strWalletFile).EraseName(CBitcoinAddress(address).ToString()); } bool CWallet::SetDefaultKey(const CPubKey& vchPubKey) { if (fFileBacked) { if (!CWalletDB(strWalletFile).WriteDefaultKey(vchPubKey)) return false; } vchDefaultKey = vchPubKey; return true; } /** * Mark old keypool keys as used, * and generate all new keys */ bool CWallet::NewKeyPool() { { LOCK(cs_wallet); CWalletDB walletdb(strWalletFile); BOOST_FOREACH (int64_t nIndex, setKeyPool) walletdb.ErasePool(nIndex); setKeyPool.clear(); if (IsLocked()) return false; int64_t nKeys = max(GetArg("-keypool", 1000), (int64_t)0); for (int i = 0; i < nKeys; i++) { int64_t nIndex = i + 1; walletdb.WritePool(nIndex, CKeyPool(GenerateNewKey())); setKeyPool.insert(nIndex); } LogPrintf("CWallet::NewKeyPool wrote %d new keys\n", nKeys); } return true; } bool CWallet::TopUpKeyPool(unsigned int kpSize) { { LOCK(cs_wallet); if (IsLocked()) return false; CWalletDB walletdb(strWalletFile); // Top up key pool unsigned int nTargetSize; if (kpSize > 0) nTargetSize = kpSize; else nTargetSize = max(GetArg("-keypool", 1000), (int64_t)0); while (setKeyPool.size() < (nTargetSize + 1)) { int64_t nEnd = 1; if (!setKeyPool.empty()) nEnd = *(--setKeyPool.end()) + 1; if (!walletdb.WritePool(nEnd, CKeyPool(GenerateNewKey()))) throw runtime_error("TopUpKeyPool() : writing generated key failed"); setKeyPool.insert(nEnd); LogPrintf("keypool added key %d, size=%u\n", nEnd, setKeyPool.size()); double dProgress = 100.f * nEnd / (nTargetSize + 1); std::string strMsg = strprintf(_("Loading wallet... (%3.2f %%)"), dProgress); uiInterface.InitMessage(strMsg); } } return true; } void CWallet::ReserveKeyFromKeyPool(int64_t& nIndex, CKeyPool& keypool) { nIndex = -1; keypool.vchPubKey = CPubKey(); { LOCK(cs_wallet); if (!IsLocked()) TopUpKeyPool(); // Get the oldest key if (setKeyPool.empty()) return; CWalletDB walletdb(strWalletFile); nIndex = *(setKeyPool.begin()); setKeyPool.erase(setKeyPool.begin()); if (!walletdb.ReadPool(nIndex, keypool)) throw runtime_error("ReserveKeyFromKeyPool() : read failed"); if (!HaveKey(keypool.vchPubKey.GetID())) throw runtime_error("ReserveKeyFromKeyPool() : unknown key in key pool"); assert(keypool.vchPubKey.IsValid()); LogPrintf("keypool reserve %d\n", nIndex); } } void CWallet::KeepKey(int64_t nIndex) { // Remove from key pool if (fFileBacked) { CWalletDB walletdb(strWalletFile); walletdb.ErasePool(nIndex); } LogPrintf("keypool keep %d\n", nIndex); } void CWallet::ReturnKey(int64_t nIndex) { // Return to key pool { LOCK(cs_wallet); setKeyPool.insert(nIndex); } LogPrintf("keypool return %d\n", nIndex); } bool CWallet::GetKeyFromPool(CPubKey& result) { int64_t nIndex = 0; CKeyPool keypool; { LOCK(cs_wallet); ReserveKeyFromKeyPool(nIndex, keypool); if (nIndex == -1) { if (IsLocked()) return false; result = GenerateNewKey(); return true; } KeepKey(nIndex); result = keypool.vchPubKey; } return true; } int64_t CWallet::GetOldestKeyPoolTime() { int64_t nIndex = 0; CKeyPool keypool; ReserveKeyFromKeyPool(nIndex, keypool); if (nIndex == -1) return GetTime(); ReturnKey(nIndex); return keypool.nTime; } std::map<CTxDestination, CAmount> CWallet::GetAddressBalances() { map<CTxDestination, CAmount> balances; { LOCK(cs_wallet); BOOST_FOREACH (PAIRTYPE(uint256, CWalletTx) walletEntry, mapWallet) { CWalletTx* pcoin = &walletEntry.second; if (!IsFinalTx(*pcoin) || !pcoin->IsTrusted()) continue; if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0) continue; int nDepth = pcoin->GetDepthInMainChain(); if (nDepth < (pcoin->IsFromMe(ISMINE_ALL) ? 0 : 1)) continue; for (unsigned int i = 0; i < pcoin->vout.size(); i++) { CTxDestination addr; if (!IsMine(pcoin->vout[i])) continue; if (!ExtractDestination(pcoin->vout[i].scriptPubKey, addr)) continue; CAmount n = IsSpent(walletEntry.first, i) ? 0 : pcoin->vout[i].nValue; if (!balances.count(addr)) balances[addr] = 0; balances[addr] += n; } } } return balances; } set<set<CTxDestination> > CWallet::GetAddressGroupings() { AssertLockHeld(cs_wallet); // mapWallet set<set<CTxDestination> > groupings; set<CTxDestination> grouping; BOOST_FOREACH (PAIRTYPE(uint256, CWalletTx) walletEntry, mapWallet) { CWalletTx* pcoin = &walletEntry.second; if (pcoin->vin.size() > 0) { bool any_mine = false; // group all input addresses with each other BOOST_FOREACH (CTxIn txin, pcoin->vin) { CTxDestination address; if (!IsMine(txin)) /* If this input isn't mine, ignore it */ continue; if (!ExtractDestination(mapWallet[txin.prevout.hash].vout[txin.prevout.n].scriptPubKey, address)) continue; grouping.insert(address); any_mine = true; } // group change with input addresses if (any_mine) { BOOST_FOREACH (CTxOut txout, pcoin->vout) if (IsChange(txout)) { CTxDestination txoutAddr; if (!ExtractDestination(txout.scriptPubKey, txoutAddr)) continue; grouping.insert(txoutAddr); } } if (grouping.size() > 0) { groupings.insert(grouping); grouping.clear(); } } // group lone addrs by themselves for (unsigned int i = 0; i < pcoin->vout.size(); i++) if (IsMine(pcoin->vout[i])) { CTxDestination address; if (!ExtractDestination(pcoin->vout[i].scriptPubKey, address)) continue; grouping.insert(address); groupings.insert(grouping); grouping.clear(); } } set<set<CTxDestination>*> uniqueGroupings; // a set of pointers to groups of addresses map<CTxDestination, set<CTxDestination>*> setmap; // map addresses to the unique group containing it BOOST_FOREACH (set<CTxDestination> grouping, groupings) { // make a set of all the groups hit by this new group set<set<CTxDestination>*> hits; map<CTxDestination, set<CTxDestination>*>::iterator it; BOOST_FOREACH (CTxDestination address, grouping) if ((it = setmap.find(address)) != setmap.end()) hits.insert((*it).second); // merge all hit groups into a new single group and delete old groups set<CTxDestination>* merged = new set<CTxDestination>(grouping); BOOST_FOREACH (set<CTxDestination>* hit, hits) { merged->insert(hit->begin(), hit->end()); uniqueGroupings.erase(hit); delete hit; } uniqueGroupings.insert(merged); // update setmap BOOST_FOREACH (CTxDestination element, *merged) setmap[element] = merged; } set<set<CTxDestination> > ret; BOOST_FOREACH (set<CTxDestination>* uniqueGrouping, uniqueGroupings) { ret.insert(*uniqueGrouping); delete uniqueGrouping; } return ret; } set<CTxDestination> CWallet::GetAccountAddresses(string strAccount) const { LOCK(cs_wallet); set<CTxDestination> result; BOOST_FOREACH (const PAIRTYPE(CTxDestination, CAddressBookData) & item, mapAddressBook) { const CTxDestination& address = item.first; const string& strName = item.second.name; if (strName == strAccount) result.insert(address); } return result; } bool CReserveKey::GetReservedKey(CPubKey& pubkey) { if (nIndex == -1) { CKeyPool keypool; pwallet->ReserveKeyFromKeyPool(nIndex, keypool); if (nIndex != -1) vchPubKey = keypool.vchPubKey; else { return false; } } assert(vchPubKey.IsValid()); pubkey = vchPubKey; return true; } void CReserveKey::KeepKey() { if (nIndex != -1) pwallet->KeepKey(nIndex); nIndex = -1; vchPubKey = CPubKey(); } void CReserveKey::ReturnKey() { if (nIndex != -1) pwallet->ReturnKey(nIndex); nIndex = -1; vchPubKey = CPubKey(); } void CWallet::GetAllReserveKeys(set<CKeyID>& setAddress) const { setAddress.clear(); CWalletDB walletdb(strWalletFile); LOCK2(cs_main, cs_wallet); BOOST_FOREACH (const int64_t& id, setKeyPool) { CKeyPool keypool; if (!walletdb.ReadPool(id, keypool)) throw runtime_error("GetAllReserveKeyHashes() : read failed"); assert(keypool.vchPubKey.IsValid()); CKeyID keyID = keypool.vchPubKey.GetID(); if (!HaveKey(keyID)) throw runtime_error("GetAllReserveKeyHashes() : unknown key in key pool"); setAddress.insert(keyID); } } bool CWallet::UpdatedTransaction(const uint256& hashTx) { { LOCK(cs_wallet); // Only notify UI if this transaction is in this wallet map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(hashTx); if (mi != mapWallet.end()) { NotifyTransactionChanged(this, hashTx, CT_UPDATED); return true; } } return false; } void CWallet::LockCoin(COutPoint& output) { AssertLockHeld(cs_wallet); // setLockedCoins setLockedCoins.insert(output); } void CWallet::UnlockCoin(COutPoint& output) { AssertLockHeld(cs_wallet); // setLockedCoins setLockedCoins.erase(output); } void CWallet::UnlockAllCoins() { AssertLockHeld(cs_wallet); // setLockedCoins setLockedCoins.clear(); } bool CWallet::IsLockedCoin(uint256 hash, unsigned int n) const { AssertLockHeld(cs_wallet); // setLockedCoins COutPoint outpt(hash, n); return (setLockedCoins.count(outpt) > 0); } void CWallet::ListLockedCoins(std::vector<COutPoint>& vOutpts) { AssertLockHeld(cs_wallet); // setLockedCoins for (std::set<COutPoint>::iterator it = setLockedCoins.begin(); it != setLockedCoins.end(); it++) { COutPoint outpt = (*it); vOutpts.push_back(outpt); } } /** @} */ // end of Actions class CAffectedKeysVisitor : public boost::static_visitor<void> { private: const CKeyStore& keystore; std::vector<CKeyID>& vKeys; public: CAffectedKeysVisitor(const CKeyStore& keystoreIn, std::vector<CKeyID>& vKeysIn) : keystore(keystoreIn), vKeys(vKeysIn) {} void Process(const CScript& script) { txnouttype type; std::vector<CTxDestination> vDest; int nRequired; if (ExtractDestinations(script, type, vDest, nRequired)) { BOOST_FOREACH (const CTxDestination& dest, vDest) boost::apply_visitor(*this, dest); } } void operator()(const CKeyID& keyId) { if (keystore.HaveKey(keyId)) vKeys.push_back(keyId); } void operator()(const CScriptID& scriptId) { CScript script; if (keystore.GetCScript(scriptId, script)) Process(script); } void operator()(const CNoDestination& none) {} }; void CWallet::GetKeyBirthTimes(std::map<CKeyID, int64_t>& mapKeyBirth) const { AssertLockHeld(cs_wallet); // mapKeyMetadata mapKeyBirth.clear(); // get birth times for keys with metadata for (std::map<CKeyID, CKeyMetadata>::const_iterator it = mapKeyMetadata.begin(); it != mapKeyMetadata.end(); it++) if (it->second.nCreateTime) mapKeyBirth[it->first] = it->second.nCreateTime; // map in which we'll infer heights of other keys CBlockIndex* pindexMax = chainActive[std::max(0, chainActive.Height() - 144)]; // the tip can be reorganised; use a 144-block safety margin std::map<CKeyID, CBlockIndex*> mapKeyFirstBlock; std::set<CKeyID> setKeys; GetKeys(setKeys); BOOST_FOREACH (const CKeyID& keyid, setKeys) { if (mapKeyBirth.count(keyid) == 0) mapKeyFirstBlock[keyid] = pindexMax; } setKeys.clear(); // if there are no such keys, we're done if (mapKeyFirstBlock.empty()) return; // find first block that affects those keys, if there are any left std::vector<CKeyID> vAffected; for (std::map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); it++) { // iterate over all wallet transactions... const CWalletTx& wtx = (*it).second; BlockMap::const_iterator blit = mapBlockIndex.find(wtx.hashBlock); if (blit != mapBlockIndex.end() && chainActive.Contains(blit->second)) { // ... which are already in a block int nHeight = blit->second->nHeight; BOOST_FOREACH (const CTxOut& txout, wtx.vout) { // iterate over all their outputs CAffectedKeysVisitor(*this, vAffected).Process(txout.scriptPubKey); BOOST_FOREACH (const CKeyID& keyid, vAffected) { // ... and all their affected keys std::map<CKeyID, CBlockIndex*>::iterator rit = mapKeyFirstBlock.find(keyid); if (rit != mapKeyFirstBlock.end() && nHeight < rit->second->nHeight) rit->second = blit->second; } vAffected.clear(); } } } // Extract block timestamps for those keys for (std::map<CKeyID, CBlockIndex*>::const_iterator it = mapKeyFirstBlock.begin(); it != mapKeyFirstBlock.end(); it++) mapKeyBirth[it->first] = it->second->GetBlockTime() - 7200; // block times can be 2h off } bool CWallet::AddDestData(const CTxDestination& dest, const std::string& key, const std::string& value) { if (boost::get<CNoDestination>(&dest)) return false; mapAddressBook[dest].destdata.insert(std::make_pair(key, value)); if (!fFileBacked) return true; return CWalletDB(strWalletFile).WriteDestData(CBitcoinAddress(dest).ToString(), key, value); } bool CWallet::EraseDestData(const CTxDestination& dest, const std::string& key) { if (!mapAddressBook[dest].destdata.erase(key)) return false; if (!fFileBacked) return true; return CWalletDB(strWalletFile).EraseDestData(CBitcoinAddress(dest).ToString(), key); } bool CWallet::LoadDestData(const CTxDestination& dest, const std::string& key, const std::string& value) { mapAddressBook[dest].destdata.insert(std::make_pair(key, value)); return true; } bool CWallet::GetDestData(const CTxDestination& dest, const std::string& key, std::string* value) const { std::map<CTxDestination, CAddressBookData>::const_iterator i = mapAddressBook.find(dest); if (i != mapAddressBook.end()) { CAddressBookData::StringMap::const_iterator j = i->second.destdata.find(key); if (j != i->second.destdata.end()) { if (value) *value = j->second; return true; } } return false; } void CWallet::AutoCombineDust() { if (IsInitialBlockDownload() || IsLocked()) { return; } map<CBitcoinAddress, vector<COutput> > mapCoinsByAddress = AvailableCoinsByAddress(true, 0); //coins are sectioned by address. This combination code only wants to combine inputs that belong to the same address for (map<CBitcoinAddress, vector<COutput> >::iterator it = mapCoinsByAddress.begin(); it != mapCoinsByAddress.end(); it++) { vector<COutput> vCoins, vRewardCoins; vCoins = it->second; //find masternode rewards that need to be combined CCoinControl* coinControl = new CCoinControl(); CAmount nTotalRewardsValue = 0; BOOST_FOREACH (const COutput& out, vCoins) { //no coins should get this far if they dont have proper maturity, this is double checking if (out.tx->IsCoinStake() && out.tx->GetDepthInMainChain() < COINBASE_MATURITY + 1) continue; if (out.Value() > nAutoCombineThreshold * COIN) continue; COutPoint outpt(out.tx->GetHash(), out.i); coinControl->Select(outpt); vRewardCoins.push_back(out); nTotalRewardsValue += out.Value(); } //if no inputs found then return if (!coinControl->HasSelected()) continue; //we cannot combine one coin with itself if (vRewardCoins.size() <= 1) continue; vector<pair<CScript, CAmount> > vecSend; CScript scriptPubKey = GetScriptForDestination(it->first.Get()); vecSend.push_back(make_pair(scriptPubKey, nTotalRewardsValue)); // Create the transaction and commit it to the network CWalletTx wtx; CReserveKey keyChange(this); // this change address does not end up being used, because change is returned with coin control switch string strErr; CAmount nFeeRet = 0; //get the fee amount CWalletTx wtxdummy; CreateTransaction(vecSend, wtxdummy, keyChange, nFeeRet, strErr, coinControl, ALL_COINS, false, CAmount(0)); vecSend[0].second = nTotalRewardsValue - nFeeRet - 500; if (!CreateTransaction(vecSend, wtx, keyChange, nFeeRet, strErr, coinControl, ALL_COINS, false, CAmount(0))) { LogPrintf("AutoCombineDust createtransaction failed, reason: %s\n", strErr); continue; } if (!CommitTransaction(wtx, keyChange)) { LogPrintf("AutoCombineDust transaction commit failed\n"); continue; } LogPrintf("AutoCombineDust sent transaction\n"); delete coinControl; } } bool CWallet::MultiSend() { if (IsInitialBlockDownload() || IsLocked()) { return false; } if (chainActive.Tip()->nHeight <= nLastMultiSendHeight) { LogPrintf("Multisend: lastmultisendheight is higher than current best height\n"); return false; } std::vector<COutput> vCoins; AvailableCoins(vCoins); int stakeSent = 0; int mnSent = 0; BOOST_FOREACH (const COutput& out, vCoins) { //need output with precise confirm count - this is how we identify which is the output to send if (out.tx->GetDepthInMainChain() != COINBASE_MATURITY + 1) continue; COutPoint outpoint(out.tx->GetHash(), out.i); bool sendMSonMNReward = fMultiSendMasternodeReward && outpoint.IsMasternodeReward(out.tx); bool sendMSOnStake = fMultiSendStake && out.tx->IsCoinStake() && !sendMSonMNReward; //output is either mnreward or stake reward, not both if (!(sendMSOnStake || sendMSonMNReward)) continue; CTxDestination destMyAddress; if (!ExtractDestination(out.tx->vout[out.i].scriptPubKey, destMyAddress)) { LogPrintf("Multisend: failed to extract destination\n"); continue; } //Disabled Addresses won't send MultiSend transactions if (vDisabledAddresses.size() > 0) { for (unsigned int i = 0; i < vDisabledAddresses.size(); i++) { if (vDisabledAddresses[i] == CBitcoinAddress(destMyAddress).ToString()) { LogPrintf("Multisend: disabled address preventing multisend\n"); return false; } } } // create new coin control, populate it with the selected utxo, create sending vector CCoinControl* cControl = new CCoinControl(); COutPoint outpt(out.tx->GetHash(), out.i); cControl->Select(outpt); cControl->destChange = destMyAddress; CWalletTx wtx; CReserveKey keyChange(this); // this change address does not end up being used, because change is returned with coin control switch CAmount nFeeRet = 0; vector<pair<CScript, CAmount> > vecSend; // loop through multisend vector and add amounts and addresses to the sending vector const isminefilter filter = ISMINE_SPENDABLE; CAmount nAmount = 0; for (unsigned int i = 0; i < vMultiSend.size(); i++) { // MultiSend vector is a pair of 1)Address as a std::string 2) Percent of stake to send as an int nAmount = ((out.tx->GetCredit(filter) - out.tx->GetDebit(filter)) * vMultiSend[i].second) / 100; CBitcoinAddress strAddSend(vMultiSend[i].first); CScript scriptPubKey; scriptPubKey = GetScriptForDestination(strAddSend.Get()); vecSend.push_back(make_pair(scriptPubKey, nAmount)); } //get the fee amount CWalletTx wtxdummy; string strErr; CreateTransaction(vecSend, wtxdummy, keyChange, nFeeRet, strErr, cControl, ALL_COINS, false, CAmount(0)); CAmount nLastSendAmount = vecSend[vecSend.size() - 1].second; if (nLastSendAmount < nFeeRet + 500) { LogPrintf("%s: fee of %s is too large to insert into last output\n"); return false; } vecSend[vecSend.size() - 1].second = nLastSendAmount - nFeeRet - 500; // Create the transaction and commit it to the network if (!CreateTransaction(vecSend, wtx, keyChange, nFeeRet, strErr, cControl, ALL_COINS, false, CAmount(0))) { LogPrintf("MultiSend createtransaction failed\n"); return false; } if (!CommitTransaction(wtx, keyChange)) { LogPrintf("MultiSend transaction commit failed\n"); return false; } else fMultiSendNotify = true; delete cControl; //write nLastMultiSendHeight to DB CWalletDB walletdb(strWalletFile); nLastMultiSendHeight = chainActive.Tip()->nHeight; if (!walletdb.WriteMSettings(fMultiSendStake, fMultiSendMasternodeReward, nLastMultiSendHeight)) LogPrintf("Failed to write MultiSend setting to DB\n"); LogPrintf("MultiSend successfully sent\n"); if (sendMSOnStake) stakeSent++; else mnSent++; //stop iterating if we are done if (mnSent > 0 && stakeSent > 0) return true; if (stakeSent > 0 && !fMultiSendMasternodeReward) return true; if (mnSent > 0 && !fMultiSendStake) return true; } return true; } CKeyPool::CKeyPool() { nTime = GetTime(); } CKeyPool::CKeyPool(const CPubKey& vchPubKeyIn) { nTime = GetTime(); vchPubKey = vchPubKeyIn; } CWalletKey::CWalletKey(int64_t nExpires) { nTimeCreated = (nExpires ? GetTime() : 0); nTimeExpires = nExpires; } int CMerkleTx::SetMerkleBranch(const CBlock& block) { AssertLockHeld(cs_main); CBlock blockTmp; // Update the tx's hashBlock hashBlock = block.GetHash(); // Locate the transaction for (nIndex = 0; nIndex < (int)block.vtx.size(); nIndex++) if (block.vtx[nIndex] == *(CTransaction*)this) break; if (nIndex == (int)block.vtx.size()) { vMerkleBranch.clear(); nIndex = -1; LogPrintf("ERROR: SetMerkleBranch() : couldn't find tx in block\n"); return 0; } // Fill in merkle branch vMerkleBranch = block.GetMerkleBranch(nIndex); // Is the tx in a block that's in the main chain BlockMap::iterator mi = mapBlockIndex.find(hashBlock); if (mi == mapBlockIndex.end()) return 0; const CBlockIndex* pindex = (*mi).second; if (!pindex || !chainActive.Contains(pindex)) return 0; return chainActive.Height() - pindex->nHeight + 1; } int CMerkleTx::GetDepthInMainChainINTERNAL(const CBlockIndex*& pindexRet) const { if (hashBlock == 0 || nIndex == -1) return 0; AssertLockHeld(cs_main); // Find the block it claims to be in BlockMap::iterator mi = mapBlockIndex.find(hashBlock); if (mi == mapBlockIndex.end()) return 0; CBlockIndex* pindex = (*mi).second; if (!pindex || !chainActive.Contains(pindex)) return 0; // Make sure the merkle branch connects to this block if (!fMerkleVerified) { if (CBlock::CheckMerkleBranch(GetHash(), vMerkleBranch, nIndex) != pindex->hashMerkleRoot) return 0; fMerkleVerified = true; } pindexRet = pindex; return chainActive.Height() - pindex->nHeight + 1; } int CMerkleTx::GetDepthInMainChain(const CBlockIndex*& pindexRet, bool enableIX) const { AssertLockHeld(cs_main); int nResult = GetDepthInMainChainINTERNAL(pindexRet); if (nResult == 0 && !mempool.exists(GetHash())) return -1; // Not in chain, not in mempool if (enableIX) { if (nResult < 6) { int signatures = GetTransactionLockSignatures(); if (signatures >= SWIFTTX_SIGNATURES_REQUIRED) { return nSwiftTXDepth + nResult; } } } return nResult; } int CMerkleTx::GetBlocksToMaturity() const { if (!(IsCoinBase() || IsCoinStake())) return 0; return max(0, (Params().COINBASE_MATURITY() + 1) - GetDepthInMainChain()); } bool CMerkleTx::AcceptToMemoryPool(bool fLimitFree, bool fRejectInsaneFee, bool ignoreFees) { CValidationState state; return ::AcceptToMemoryPool(mempool, state, *this, fLimitFree, NULL, fRejectInsaneFee, ignoreFees); } int CMerkleTx::GetTransactionLockSignatures() const { if (fLargeWorkForkFound || fLargeWorkInvalidChainFound) return -2; if (!IsSporkActive(SPORK_2_SWIFTTX)) return -3; if (!fEnableSwiftTX) return -1; //compile consessus vote std::map<uint256, CTransactionLock>::iterator i = mapTxLocks.find(GetHash()); if (i != mapTxLocks.end()) { return (*i).second.CountSignatures(); } return -1; } bool CMerkleTx::IsTransactionLockTimedOut() const { if (!fEnableSwiftTX) return 0; //compile consessus vote std::map<uint256, CTransactionLock>::iterator i = mapTxLocks.find(GetHash()); if (i != mapTxLocks.end()) { return GetTime() > (*i).second.nTimeout; } return false; }
[ "76849967+Harold-Coin@users.noreply.github.com" ]
76849967+Harold-Coin@users.noreply.github.com
a3f94b9ce35b5cecaea905cf604056a5b4504af0
f6d9ab3fc22d6e7bd95f330ec35bd1bfca81332e
/rotation.cpp
aba791bbd3eb4ff5ffb971adac0f8d4b55f692fc
[]
no_license
P-dot/C-_Fundamentals
a920fd992a0daff3ab9751675130c596517a5d6d
90463c058ef4c774c2289f44a373b46a4cbaa8b7
refs/heads/master
2020-07-23T13:46:05.731295
2019-09-10T14:14:21
2019-09-10T14:14:21
207,578,574
0
0
null
null
null
null
UTF-8
C++
false
false
610
cpp
//This function performs left and right rotations unsigned char rol(unsigned char val) { int hightbit; if(val & 0x80) // 0x80 is the high bit only highbit = 1; else highbit = 0; // Left shift (bottom bit becomes 0): val <<= 1 // Rotate the high bit onto the bottom: // val |= highbit; return val; } unsigned char ror(unsigned char val) { int lowbit; if(val & 1) // check the low bit lowbit = 1; else lowbit = 0; val >>= 1; // Right shift by one position // Rotate the low bit onto the top val |= (lowbit << 7); return val; }
[ "usuario@kali" ]
usuario@kali
0dfdf6692287a2c1b6e1c11e873984180d2b9a73
f50da5dfb1d27cf737825705ce5e286bde578820
/Temp/il2cppOutput/il2cppOutput/mscorlib_System_Security_Cryptography_ToBase64Tran1303874555.h
011abe010d6265397ddf81fd268be9da64bab834
[]
no_license
magonicolas/OXpecker
03f0ea81d0dedd030d892bfa2afa4e787e855f70
f08475118dc8f29fc9c89aafea5628ab20c173f7
refs/heads/master
2020-07-05T11:07:21.694986
2016-09-12T16:20:33
2016-09-12T16:20:33
67,150,904
0
0
null
null
null
null
UTF-8
C++
false
false
993
h
#pragma once #include "il2cpp-config.h" #ifndef _MSC_VER # include <alloca.h> #else # include <malloc.h> #endif #include <stdint.h> #include "mscorlib_System_Object837106420.h" #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Security.Cryptography.ToBase64Transform struct ToBase64Transform_t1303874555 : public Il2CppObject { public: // System.Boolean System.Security.Cryptography.ToBase64Transform::m_disposed bool ___m_disposed_2; public: inline static int32_t get_offset_of_m_disposed_2() { return static_cast<int32_t>(offsetof(ToBase64Transform_t1303874555, ___m_disposed_2)); } inline bool get_m_disposed_2() const { return ___m_disposed_2; } inline bool* get_address_of_m_disposed_2() { return &___m_disposed_2; } inline void set_m_disposed_2(bool value) { ___m_disposed_2 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif
[ "magonicolas@gmail.com" ]
magonicolas@gmail.com
de2e689593c81e0de74f074407886ba0dc1da58b
07110f30a6a30a1a6cce260509c60fb16f0dbf92
/src/include/concore/as_sender.hpp
80553983ded23ce830886b02a4aa0648165bfc21
[ "MIT" ]
permissive
Watch-Later/concore
8d65fe2409684a247f869d8df3952053f32b8149
579d2f84039bbf2d9ebe245096b63867702613c9
refs/heads/master
2023-06-20T02:03:28.396841
2021-06-01T15:23:20
2021-06-01T15:23:20
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,269
hpp
/** * @file as_sender.hpp * @brief Definition of @ref concore::v1::as_sender "as_sender" * * @see @ref concore::v1::as_sender "as_sender" */ #pragma once #include <concore/as_operation.hpp> #include <utility> namespace concore { inline namespace v1 { /** * @brief Wrapper that transforms a receiver into a functor * * @tparam R The type of the receiver * * @details * * The receiver should model `receiver_of<>`. * * This will store a reference to the receiver; the receiver must not get out of scope. * * When this functor is called set_value() will be called on the receiver. If an exception is * thrown, the set_error() function is called. * * If the functor is never called, the destructor of this object will call set_done(). * * This types models the @ref sender concept. * * @see sender, receiver_of, as_operation */ template <typename E> struct as_sender { //! The value types that defines the values that this sender sends to receivers template <template <typename...> class Tuple, template <typename...> class Variant> using value_types = Variant<Tuple<>>; //! The type of error that this sender sends to receiver template <template <typename...> class Variant> using error_types = Variant<std::exception_ptr>; //! Indicates that this sender never sends a done signal static constexpr bool sends_done = false; //! Constructor explicit as_sender(E e) noexcept : ex_((E &&) e) { #if CONCORE_CXX_HAS_CONCEPTS static_assert(executor<E>, "Type needs to match executor concept"); #endif } //! The connect CPO that returns an operation state object template <typename R> as_operation<E, R> connect(R&& r) && { #if CONCORE_CXX_HAS_CONCEPTS static_assert(receiver_of<R>, "Type needs to match receiver_of concept"); #endif return as_operation<E, R>((E &&) ex_, (R &&) r); } //! @overload template <typename R> as_operation<E, R> connect(R&& r) const& { #if CONCORE_CXX_HAS_CONCEPTS static_assert(receiver_of<R>, "Type needs to match receiver_of concept"); #endif return as_operation<E, R>(ex_, (R &&) r); } private: //! The wrapped executor E ex_; }; } // namespace v1 } // namespace concore
[ "lucteo@lucteo.ro" ]
lucteo@lucteo.ro
10bb48703bf3fe5c5c52641938f81b08f8905809
164e709dcf03ce4769c3ba8f874da0666c35bc03
/RtTpsRenderLibrary/operation/tps_rl_updatesetupcrosshairoperation.cpp
c15ce66f67d5231cd93f285b515bf44896daa172
[]
no_license
liq07lzucn/tps
b343894bcfd59a71be48bd47d6eff6e010464457
a3be6dc50c5f9a2ff448ecff3f5df1956e26ad4f
refs/heads/master
2021-06-23T16:35:01.349523
2017-08-30T08:09:02
2017-08-30T08:09:02
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,113
cpp
//////////////////////////////////////////////////////////////// /// Copyright (c) Shanghai United Imaging Healthcare Inc., 2013 /// All rights reserved. /// /// \author Miao Chenfeng chenfeng.miao@united-imaging.com /// /// \file tps_rl_updatesetupcrosshairoperation.cpp /// /// \brief class TpsUpdateSetUpCrosshairOPeration /// /// \version 1.0 /// /// \date 2014/4/10 //////////////////////////////////////////////////////////////// #include "StdAfx.h" #include "RtTpsRenderLibrary/tps_rl_updatesetupcrosshairoperation.h" #include "RtTpsRenderLibrary/tps_rl_editsetuppoigraphicobject.h" #include "RtTpsFramework/tps_fw_modelwarehouse.h" #include "RtTpsRenderLibrary/tps_rl_graphicobjecttypedefines.h" #include "RtTpsFramework/tps_fw_graphicobjectconverterbase.h" #include "RtTpsFramework/tps_fw_arithmeticconverter.h" #include "RtTpsFramework/tps_fw_graphicobjecttypehelper.h" TPS_BEGIN_NAMESPACE TpsUpdateSetUpCrosshairOperation::TpsUpdateSetUpCrosshairOperation(const std::string &imageuid, const Mcsf::Point2f &mousePosition, bool isVisible, FIRST_POSTFIX_COMPONENT section) : mImageuid(imageuid), mMousePosition(mousePosition),mIsVisible(isVisible),mSectionType(section) { } TpsUpdateSetUpCrosshairOperation::~TpsUpdateSetUpCrosshairOperation() { } bool TpsUpdateSetUpCrosshairOperation::ModifyGraphicObject() const { if(mSectionType != AXIAL && mSectionType != EASYPLAN_IMAGE_SECTION) { return true; } auto setupCrossHairGo = mModelWarehouse->GetModelObject( mImageuid + "|" + GOTypeHelper::ToString(GO_TYPE_SETUP_POI)); if(nullptr == setupCrossHairGo) { TPS_LOG_DEV_ERROR<<"Failed to get set up poi"<<mImageuid; return false; } auto setupGo = dynamic_pointer_cast<EditSetupPtGraphicObject>(setupCrossHairGo); if(nullptr == setupGo) { TPS_LOG_DEV_ERROR<<"Failed to convert set up go!"; return false; } setupGo->SetVisible(mIsVisible); setupGo->SetPosition(TpsArithmeticConverter::ConvertToPoint2D(mMousePosition)); setupGo->SetDirty(true); return true; } TPS_END_NAMESPACE
[ "genius52@qq.com" ]
genius52@qq.com
3a50b59a5f8d9255b10e625074da9695fb631217
21e2d8b4300bf4eca4a2aa47731ee947af6c5ddf
/Iterativos/Abadias/Source.cpp
2a342e394c45a834012a25b49407a6f2fa153880
[]
no_license
AdriPanG/EDA
0ecbb97ad895ab5f99382ed2f9804f2ff6182910
2e6d6c5a269114674e5f05fddc3d5b22779b3f62
refs/heads/master
2020-07-10T12:44:22.822964
2017-09-09T12:09:01
2017-09-09T12:09:01
74,014,498
0
1
null
null
null
null
UTF-8
C++
false
false
789
cpp
#include <iostream> using namespace std; //Precondicion: 0<=n<=long(v) and Paratodo i : 0<=i<n : v[i] >= 0 //Postcondicion: #k : 0<=k<n : Paratodo j : k < j < n : a[k] > numero(v,j) //numero(v,k) = max(Paratodo l : k<l<n : v[l]) int calculaAbadias(int v[], int n, int &abadias) { abadias = 0; int numero = 0; for (int i = n; i > 0; i--) { if ((v[i-1] > v[i] && v[i-1] > numero) || i == n) { numero = v[i-1]; abadias++; } } return abadias; } bool resuelve() { int n; int v[100000]; cin >> n; if (n == 0) return false; for (int i = 0; i < n; i++) { cin >> v[i]; } int abadias; calculaAbadias(v, n, abadias); cout << abadias << endl; return true; } int main() { while (resuelve()) { ; } return 0; }
[ "adripana@ucm.es" ]
adripana@ucm.es
89471ed679263c6b644a3babef3631839cd58f8e
c03ca89bc6256e8948eeb2ae171a2e746188fb1b
/GeneralKnowledgeBook.h
e589a71fac9b30b0dbf4ff34a232cf654f13da7f
[]
no_license
ChangeXuan/BookLib-Cpp
45463907e50b48ab9c220b42ffcac60f0128f71b
58549ebe8272f4c92ec68bbb967605fe1403302a
refs/heads/master
2021-01-20T03:34:27.319050
2017-04-27T04:54:42
2017-04-27T04:54:42
89,556,807
0
0
null
null
null
null
UTF-8
C++
false
false
1,306
h
// // Created by Day on 2017/4/25. // #ifndef BOOKLIB_GENERALKNOWLEDGEBOOK_H #define BOOKLIB_GENERALKNOWLEDGEBOOK_H #include <iostream> #include <cstring> #include "Book.h" using namespace std; class GeneralKnowledgeBooks: public Book { private: string typeName; public: GeneralKnowledgeBooks(); ~GeneralKnowledgeBooks(); enum bookType {NOVEL,MAGAZINE,THOUGHT}; void setBookType(const int type); string &getBookType(); void showGeneralKnowledgeBooks(); }; GeneralKnowledgeBooks::GeneralKnowledgeBooks() { } GeneralKnowledgeBooks::~GeneralKnowledgeBooks() { } void GeneralKnowledgeBooks::setBookType(const int type) { switch (type) { case 0: typeName = "Novel"; break; case 1: typeName = "Magazine"; break; case 2: typeName = "Thought"; break; } } string &GeneralKnowledgeBooks::getBookType() { return typeName; } void GeneralKnowledgeBooks::showGeneralKnowledgeBooks() { string name = getName(); int pages = getPages(); float price = getPrice(); cout << "type:" << typeName << endl; cout << "name:" << name << endl; cout << "pages:" << pages << endl; cout << "price:" << price << endl; } #endif //BOOKLIB_GENERALKNOWLEDGEBOOK_H
[ "YourEmailAddress" ]
YourEmailAddress
39013a60b41c5ed40342738692c2520bf62421fd
c28515164119e13a9fb4ac10e955d4d0838e7572
/adapters/omnetpp/seed/applications/seed_onoff_client_message_m.h
ba0a8d36f881eecb881c898edaea7496e4278d79
[ "BSD-2-Clause" ]
permissive
kit-tm/seed
ba23bf10f941d462842c2efb6aae307fabefee88
c6d4eaffbe25615b396aeabeae7305b724260d92
refs/heads/master
2021-08-31T18:11:43.488896
2017-12-21T12:48:54
2017-12-21T12:48:54
115,101,138
0
0
null
null
null
null
UTF-8
C++
false
false
2,647
h
// // Generated file, do not edit! Created by nedtool 4.6 from seed_onoff_client_message.msg. // #ifndef _SEED_ONOFF_CLIENT_MESSAGE_M_H_ #define _SEED_ONOFF_CLIENT_MESSAGE_M_H_ #include <omnetpp.h> // nedtool version check #define MSGC_VERSION 0x0406 #if (MSGC_VERSION!=OMNETPP_VERSION) # error Version mismatch! Probably this file was generated by an earlier version of nedtool: 'make clean' should help. #endif /** * Class generated from <tt>seed_onoff_client_message.msg:2</tt> by nedtool. * <pre> * message OnOffMessage * { * int connId; * } * </pre> */ class OnOffMessage : public ::cMessage { protected: int connId_var; private: void copy(const OnOffMessage& other); protected: // protected and unimplemented operator==(), to prevent accidental usage bool operator==(const OnOffMessage&); public: OnOffMessage(const char *name=NULL, int kind=0); OnOffMessage(const OnOffMessage& other); virtual ~OnOffMessage(); OnOffMessage& operator=(const OnOffMessage& other); virtual OnOffMessage *dup() const {return new OnOffMessage(*this);} virtual void parsimPack(cCommBuffer *b); virtual void parsimUnpack(cCommBuffer *b); // field getter/setter methods virtual int getConnId() const; virtual void setConnId(int connId); }; inline void doPacking(cCommBuffer *b, OnOffMessage& obj) {obj.parsimPack(b);} inline void doUnpacking(cCommBuffer *b, OnOffMessage& obj) {obj.parsimUnpack(b);} /** * Class generated from <tt>seed_onoff_client_message.msg:7</tt> by nedtool. * <pre> * message SendPacketMessage * { * int connId; * } * </pre> */ class SendPacketMessage : public ::cMessage { protected: int connId_var; private: void copy(const SendPacketMessage& other); protected: // protected and unimplemented operator==(), to prevent accidental usage bool operator==(const SendPacketMessage&); public: SendPacketMessage(const char *name=NULL, int kind=0); SendPacketMessage(const SendPacketMessage& other); virtual ~SendPacketMessage(); SendPacketMessage& operator=(const SendPacketMessage& other); virtual SendPacketMessage *dup() const {return new SendPacketMessage(*this);} virtual void parsimPack(cCommBuffer *b); virtual void parsimUnpack(cCommBuffer *b); // field getter/setter methods virtual int getConnId() const; virtual void setConnId(int connId); }; inline void doPacking(cCommBuffer *b, SendPacketMessage& obj) {obj.parsimPack(b);} inline void doUnpacking(cCommBuffer *b, SendPacketMessage& obj) {obj.parsimUnpack(b);} #endif // ifndef _SEED_ONOFF_CLIENT_MESSAGE_M_H_
[ "addis.dittebrandt@gmail.com" ]
addis.dittebrandt@gmail.com
5e841693158c2fbef4bc7dd0009fa0f337b1769a
9ef7ae27f57d24b7fa194ed9fc22d95a2ea2f4fa
/Algorithms/prefixSortUsingRandom.cpp
59a4fe6cccca64d6a7a997df89e8b7df7cc5027a
[]
no_license
Rahul365/Coding_Practice
e093b745da5e0d589b57d31ff8d4d5bdae46c583
4430401991defdd79522da229f040c5e48718487
refs/heads/master
2022-07-30T19:59:21.839107
2022-07-02T08:10:50
2022-07-02T08:10:50
241,954,353
1
1
null
null
null
null
UTF-8
C++
false
false
1,498
cpp
#include<bits/stdc++.h> #define seed srand(time(NULL)) using namespace std; int pow(int x,int y){ int r =1; while(y){ if(y&1) r*=x; x = x*x; y>>=1; } return r; } bool sorted(int arr[],int n){ for(int i=1 ;i<n;i++) if(arr[i-1] > arr[i]) return false; return true; } void reverse(int arr[],int n){ int i = 0; int j = n; while(i < j) swap(arr[i],arr[j]),++i,--j; } void prefixSortUsingRandom(int arr[],int n){ while(!sorted(arr,n)){ int index = rand()%n; reverse(arr,index); } } void prefixSort(int arr[],int n){ //find the index of max element //reverse arr[0..index] //reverse arr[0..n-1] int s = n; while(s > 1){ int maxindex = s-1; for(int i= 0;i<=s-1;i++){ if(arr[maxindex] < arr[i]){ maxindex = i; } } //find the index of max element in arr[0..s-1] //then reverse the arr from 0 to maxindex reverse(arr,maxindex);//after this max element is at the front of the array reverse(arr,s-1);//now reverse the array from 0 to s-1 //so that the max element is position at the end here //now reduce the number of elements to sort by 1 --s; } } int main(){ seed; int arr[] = {3,23,1,1,12,1,224,435,34,5234,5}; int n = sizeof(arr)/sizeof(arr[0]); prefixSort(arr,n); for(int i =0;i<n;i++) cout<<arr[i]<<" "; cout<<"\n"; return 0; }
[ "rahul.dhiman365@gmail.com" ]
rahul.dhiman365@gmail.com
f13090370ca4d4379e2ad49eebd5360fe2357af9
66949a25a8764ff303887253f5dc3725b026336e
/HelloWorld/datasheet.h
79654e66aaa2797b2e059636c9ea69e7f8ebb0d2
[]
no_license
juniorprincewang/MRL
7526ef76a1c564b7e8b4314e55e46e68faa944bb
b76fa14749e6241ea493d49dbd7b462dbdb5c66e
refs/heads/master
2021-01-18T22:29:30.866122
2017-05-16T01:02:10
2017-05-16T01:02:10
72,534,367
0
0
null
null
null
null
UTF-8
C++
false
false
3,205
h
#pragma execution_character_set("utf-8") #ifndef DATASHEET_H #define DATASHEET_H #include <QLabel> #include <QTableWidget> #include <QLineEdit> #include <QTableWidgetItem> #include <QAction> #include <QItemDelegate> #include <QTableWidgetItem> #include <QString> //#include <QtWidgets> #include <QObject> #include "publicdata.h" class DataSheet : public QWidget { Q_OBJECT public: DataSheet(int rows, int cols, QStringList headers, QWidget *parent = 0); DataSheet(int rows, int cols, QWidget *parent = 0); QVector<double> updateAcuteContents(AssessData *data); QVector<double> updateChronicContents(AssessData *data); void setHeader(QStringList headers); public slots: void updateColor(QTableWidgetItem *item); void returnPressed(); void selectColor(); void selectFont(); void clear(); void actionSum(); void actionAdd(); void actionSubtract(); void actionMultiply(); void actionDivide(); protected: void setupContents(); void createActions(); void actionMath_helper(const QString &title, const QString &op); bool runInputDialog(const QString &title, const QString &c1Text, const QString &c2Text, const QString &opText, const QString &outText, QString *cell1, QString *cell2, QString *outCell); private: QAction *colorAction; QAction *fontAction; QAction *firstSeparator; QAction *cell_sumAction; QAction *cell_addAction; QAction *cell_subAction; QAction *cell_mulAction; QAction *cell_divAction; QAction *secondSeparator; QAction *clearAction; QAction *printAction; QTableWidget *table; }; void decode_position(const QString &pos, int *row, int *col); QString encode_position(int row, int col); enum Columns { COL_NAME, COL_FI, COL_STMR, COL_SOURCE, COL_NEDI, COL_ALL, COL_PERCENT }; class DataSheetItem : public QTableWidgetItem { public: DataSheetItem(); DataSheetItem(const QString &text); QTableWidgetItem *clone() const override; QVariant data(int role) const override; void setData(int role, const QVariant &value) override; QVariant display() const; inline QString formula() const { return QTableWidgetItem::data(Qt::DisplayRole).toString(); } static QVariant computeFormula(const QString &formula, const QTableWidget *widget, const QTableWidgetItem *self = 0); private: mutable bool isResolving; }; class DataSheetDelegate : public QItemDelegate { Q_OBJECT public: DataSheetDelegate(QObject *parent = 0); QWidget *createEditor(QWidget *parent, const QStyleOptionViewItem &, const QModelIndex &index) const override; void setEditorData(QWidget *editor, const QModelIndex &index) const override; void setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const override; private slots: void commitAndCloseEditor(); void comboBoxChanged(); }; #endif // DATASHEET_H
[ "15201615161@163.com" ]
15201615161@163.com
8c19b48befe5dfb1f1fb01abd44266be61a0078b
85e7114ea63a080c1b9b0579e66c7a2d126cffec
/SDK/SoT_BP_LegendaryTavern_functions.cpp
e8d85971f204ded3e5d4ab3f3d6bb60e453c67eb
[]
no_license
EO-Zanzo/SeaOfThieves-Hack
97094307d943c2b8e2af071ba777a000cf1369c2
d8e2a77b1553154e1d911a3e0c4e68ff1c02ee51
refs/heads/master
2020-04-02T14:18:24.844616
2018-10-24T15:02:43
2018-10-24T15:02:43
154,519,316
0
2
null
null
null
null
UTF-8
C++
false
false
774
cpp
// Sea of Thieves (1.2.6) SDK #ifdef _MSC_VER #pragma pack(push, 0x8) #endif #include "SoT_BP_LegendaryTavern_parameters.hpp" namespace SDK { //--------------------------------------------------------------------------- //Functions //--------------------------------------------------------------------------- // Function BP_LegendaryTavern.BP_LegendaryTavern_C.UserConstructionScript // (Event, Public, BlueprintCallable, BlueprintEvent) void ABP_LegendaryTavern_C::UserConstructionScript() { static auto fn = UObject::FindObject<UFunction>("Function BP_LegendaryTavern.BP_LegendaryTavern_C.UserConstructionScript"); ABP_LegendaryTavern_C_UserConstructionScript_Params params; UObject::ProcessEvent(fn, &params); } } #ifdef _MSC_VER #pragma pack(pop) #endif
[ "zp2kshield@gmail.com" ]
zp2kshield@gmail.com
e2013904b1a32822b7b4040eeb04826211e6c0c1
5b6268310d80a288f1c5248b2b99f0bc697fcbe4
/linux/ftpServer/FTPServer.cpp
9cc36fb861278055429cf1903a579c935256ef15
[]
no_license
shanlihou/cppDemo
9b9a6a2a90b66d043067b7adf7c8abb9068c811d
2058b6c06cada10c82a25500b33afb8594f35203
refs/heads/master
2021-08-27T22:00:42.649146
2017-12-10T12:47:14
2017-12-10T12:47:14
113,749,151
0
0
null
null
null
null
UTF-8
C++
false
false
69
cpp
#include "myEpoll.h" int main() { MyEpoll::getInstance()->run(); }
[ "shanlihou@gmail.com" ]
shanlihou@gmail.com
66aae1da02de6d2e81a45a2d4ce97e839abf6ad6
39924b397975b36d8bb0c685d1fdcf604f14caf5
/IProjectProblem2/Problem2_test/Graph.h
3abe0cbde6035a1d0801115771829d64aa1e7393
[]
no_license
mengcz13/oop2016
519a1d8048212ddeef0f2f15428dd71f3a26296b
2e3d557927d2f5eaa1e361e370255629bf733c78
refs/heads/master
2021-01-21T13:41:35.544044
2016-05-18T04:02:38
2016-05-18T04:02:38
52,948,605
0
0
null
null
null
null
UTF-8
C++
false
false
1,259
h
#ifndef GRAPH_H #define GRAPH_H #include <vector> #include <queue> #include <cmath> struct Point { double x; double y; Point():x(0), y(0) {} Point(double x1, double y1):x(x1), y(y1) {} }; struct Edge { int start; int end; double length; Edge():start(0), end(0), length(0) {} Edge(int s, int e, double l):start(s), end(e), length(l) {} }; struct EdgeGreater { bool operator() (const Edge& e1, const Edge& e2) { return (e1.length > e2.length); } }; struct UnionFind { int* parent; int* setsize; int size; UnionFind(int s): size(s) { parent = new int[size]; setsize = new int[size]; for (int i = 0; i < size; ++i) { parent[i] = -1; setsize[i] = 1; } } ~UnionFind() { delete []parent; delete []setsize; } void connect(int x, int y); int findset(int x); bool isconnected(int x, int y); }; class Graph { public: Graph(std::vector<Point> pv, std::vector<Edge> ev) : pointvec(pv), edgeheap(EdgeGreater(), ev), uf(pv.size()), total_weight(0) {} void MST_Kruskal(); void print(char*); const double get_total_weight() { return total_weight; } private: std::vector<Point> pointvec; std::priority_queue<Edge, std::vector<Edge>, EdgeGreater> edgeheap; std::vector<Edge> mstedge; UnionFind uf; double total_weight; }; #endif
[ "mengcz13@163.com" ]
mengcz13@163.com
c9cc7f1ea25916502778ec8c171ae4600ddfbd8a
3054ded5d75ec90aac29ca5d601e726cf835f76c
/Contests/Others/RPC/2016/10th Contest/E.cpp
baed34b78fa2a59f8bbbc0f0145ca5e4ae00d7f6
[]
no_license
Yefri97/Competitive-Programming
ef8c5806881bee797deeb2ef12416eee83c03add
2b267ded55d94c819e720281805fb75696bed311
refs/heads/master
2022-11-09T20:19:00.983516
2022-04-29T21:29:45
2022-04-29T21:29:45
60,136,956
10
0
null
null
null
null
UTF-8
C++
false
false
464
cpp
/* * RPC 10-th Contest 2016 * Problem E: Laser Mirrors * Status: Accepted */ #include <bits/stdc++.h> using namespace std; int eulerPhi(int n) { int ans = n; for (int p = 2; p * p <= n; p++) { if (n % p == 0) ans -= ans / p; while (n % p == 0) n /= p; } if (n != 1) ans -= ans / n; return ans; } int main() { int t; cin >> t; while (t--) { int n; cin >> n; int ans = eulerPhi(n); cout << ans << endl; } return 0; }
[ "yefri.gaitan97@gmail.com" ]
yefri.gaitan97@gmail.com
6c2c6e53a56e0496fb51c9253d272373e37865dc
3fc56bb274d5040a87f63372796412413c7690d6
/source stephan/sensor_geometry.cc
03503c353c9d5ed7024bed3a49c39b6ea407bc51
[]
no_license
dangerousHans/SEPT
b2f7b6badc32c887549dce61d83a9b9b9c4d037c
4feca9c51b59018dfd8ab95ac36d75e848a2a419
refs/heads/master
2021-01-10T12:42:42.121856
2015-11-24T18:00:24
2015-11-24T18:00:24
46,416,501
1
2
null
2015-11-24T10:52:25
2015-11-18T12:12:48
C++
UTF-8
C++
false
false
16,087
cc
/* half sensor geometry adapted from ExN02 for Stereo Impact SEPT $Id: sensor_geometry.cc,v 1.18 2008/02/08 11:52:04 bottcher Exp $ Copyright (c) 2002 Stephan Boettcher <boettcher@physik.uni-kiel.de> */ #include "sensor_geometry.hh" #include "detector_geometry.hh" #include "magnet_geometry.hh" #include "apperture_geometry.hh" #include <G4Region.hh> #include <G4RegionStore.hh> #include <G4ProductionCuts.hh> #include <G4VisAttributes.hh> #include <G4Material.hh> #include <G4Box.hh> #include <G4Tubs.hh> #include <G4PVPlacement.hh> #include <ETUserLimits.hh> #define dG4cerr if (0) G4cerr const double sensor_geometry::infinity = 200.0*mm; // w/o conn., pin-puller const double sensor_geometry::X_width = 52.0*mm; // w/o conn., pin-puller const double sensor_geometry::Y_height = 82.0*mm; // w/o doors const double sensor_geometry::Z_depth = 68.0*mm; // w/o conn., doors, ... const double sensor_geometry::det_X = X_width/2 - 20.0*mm; const double sensor_geometry::det_Y = 9.5*mm; const double sensor_geometry::det_Z = 13.05*mm; const double sensor_geometry::foil_sep = 4.1*mm; // from pips surface // FIXME: The apperture z dimensions are still for 0.6*mm pips_separation const double sensor_geometry::foil_apperture_distance = 20.7*mm; // from pips surface const double sensor_geometry::foil_apperture_depth = 15.4*mm; const double sensor_geometry::foil_apperture_rout = 18.6*mm / 2; const double sensor_geometry::foil_apperture_ropen = 12.4*mm / 2; const int sensor_geometry::foil_apperture_rings = 5; const double sensor_geometry::mag_apperture_distance = 29.3*mm; // from pips surface const double sensor_geometry::mag_apperture_depth = 7.6*mm; const double sensor_geometry::mag_apperture_rout = 23.6*mm / 2; const double sensor_geometry::mag_apperture_ropen = 20.4*mm / 2; const int sensor_geometry::mag_apperture_rings = 3; const double sensor_geometry::house_thickness = 3*mm; const double sensor_geometry::slack = 1*nanometer; const double sensor_geometry::mag_delrin_thickness = 1.2*mm; const double sensor_geometry::foil_delrin_thickness = 0.7*mm; const char *sensor_geometry::space = "Space"; const double sensor_geometry::source_window = 0; // 0.0064*mm; char const * sensor_geometry::source_window_mat = "PET"; sensor_geometry::~sensor_geometry() { } // inline functions inline double sensor_geometry::mag_pips_z() { return det_Z + detector_geometry::pips_z - detector_geometry::pips_separation/2 - detector_geometry::pips_height ; } inline double sensor_geometry::foil_pips_z() { return det_Z + detector_geometry::pips_z + detector_geometry::pips_separation/2 + detector_geometry::pips_height ; } inline double sensor_geometry::mag_det_z() { return det_Z - detector_geometry::stack_height/2 ; } inline double sensor_geometry::foil_det_z() { return det_Z + detector_geometry::stack_height/2 ; } // ------------------------------------- Constructor // ------------------------------------------------- sensor_geometry::sensor_geometry() : G4LogicalVolume(new G4Box("sensor", 2*infinity, 2*infinity, 2*infinity), G4Material::GetMaterial(sensor_geometry::space), "sensor") { SetVisAttributes(G4VisAttributes::Invisible); //-------------------------------------------------------------------- // New logical volume "halfsensor" with region "SensorRegion" //<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< G4LogicalVolume *halfsensor = new G4LogicalVolume(new G4Box("halfsensor", infinity, infinity, infinity), G4Material::GetMaterial(sensor_geometry::space), "halfsensor"); halfsensor -> SetVisAttributes (G4VisAttributes::Invisible); G4Region *Sensor_Region = new G4Region("The Sensor Region"); Sensor_Region->AddRootLogicalVolume(halfsensor); // Limits "sensorcuts" for SensorRegion of halfsensor G4UserLimits *sensorcuts = new ETUserLimits("/geometry/sept/limits/sensor", 1*mm, // step max DBL_MAX, // track max DBL_MAX, // Time max 0*keV, // Ekin min 0*mm ); // Range min Sensor_Region->SetUserLimits(sensorcuts); // Place halfsensor in this (world) volume new G4PVPlacement(0, // no rotation G4ThreeVector(-det_X, -det_Y, -det_Z), halfsensor, // its logical volume "halfsensor", // its name this, // its mother volume false, // no boolean operations -1); // no particular field //>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> // Limits for world ? G4UserLimits *spacecuts = new ETUserLimits("/geometry/sept/limits/space", 1*mm, // step max DBL_MAX, // track max DBL_MAX, // Time max 0*keV, // Ekin min 0*mm ); // Range min SetUserLimits(spacecuts); //-------------------------------------------------------------------- // New logical volume "detector" with region "Det-Region" //<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< G4UserLimits *siliconcuts = new ETUserLimits("/geometry/sept/limits/detector", 0.2*mm, // step max DBL_MAX, // track max DBL_MAX, // Time max 0*keV, // Ekin min 0*mm ); // Range min G4Region *Det_Region = new G4Region("Solid State Detector Region"); Det_Region->SetProductionCuts(new G4ProductionCuts); Det_Region->GetProductionCuts()->SetProductionCut(0.01*mm); Det_Region->GetProductionCuts()->SetProductionCut(0.3*mm, "gamma"); Det_Region->SetUserLimits(siliconcuts); // Create detector "volume" with region "Det_Region" and "siliconcuts" G4LogicalVolume* detector = new detector_geometry; Det_Region->AddRootLogicalVolume(detector); //Place detector in halfsensor new G4PVPlacement(0, // no rotation G4ThreeVector(det_X, det_Y, det_Z), detector, // its logical volume "detector", // its name halfsensor, // its mother volume false, // no boolean operations -1); // no particular field //>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> //-------------------------------------------------------------------- // New logical volume "foil" //<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< G4LogicalVolume* foil = new foil_geometry; new G4PVPlacement(0, // no rotation G4ThreeVector(det_X, det_Y, foil_pips_z() + foil_sep), foil, // its logical volume "foil", // its name halfsensor, // its mother volume false, // no boolean operations 0); // no particular field //>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> //-------------------------------------------------------------------- // New magnet_geometry "magnet" //<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< magnet_geometry* magnet = new magnet_geometry; static const double mag_Y = (magnet->size_Y + magnet->gap)/2; //Place first magnet new G4PVPlacement(0, // no rotation G4ThreeVector(det_X, det_Y-mag_Y, 0), magnet, // its logical volume "magnet1", // its name halfsensor, // its mother volume false, // no boolean operations 0); // no particular field //Place second magnet new G4PVPlacement(0, // no rotation G4ThreeVector(det_X, det_Y+mag_Y, 0), magnet, // its logical volume "magnet2", // its name halfsensor, // its mother volume false, // no boolean operations 1); // no particular field //>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> //-------------------------------------------------------------------- // New apperture_geometry "mag_app" //<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< apperture_geometry *mag_app = new apperture_geometry("magnet_apperture", mag_apperture_rout, mag_apperture_ropen, mag_apperture_rings, mag_apperture_distance, mag_apperture_depth ); double magapp_z = mag_pips_z() - mag_apperture_distance + mag_apperture_depth/2; // Rotation matrix for placement G4RotationMatrix *mirror = new G4RotationMatrix; mirror->rotateX(M_PI); new G4PVPlacement(mirror, G4ThreeVector(det_X, det_Y, magapp_z), mag_app, "magnet_apperture", halfsensor, false, 0); //>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> //-------------------------------------------------------------------- // New apperture_geometry "foil_app" //<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< apperture_geometry *foil_app = new apperture_geometry("foil_apperture", foil_apperture_rout, foil_apperture_ropen, foil_apperture_rings, foil_apperture_distance, foil_apperture_depth ); double foilapp_z = foil_pips_z() + foil_apperture_distance - foil_apperture_depth/2 ; new G4PVPlacement(0, G4ThreeVector(det_X, det_Y, foilapp_z), foil_app, "foil_apperture", halfsensor, false, 0); //>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> if (source_window > 0) { G4LogicalVolume *win = new G4LogicalVolume (new G4Tubs("win", 0, foil_apperture_ropen, source_window/2, 0, 2*M_PI ), G4Material::GetMaterial(source_window_mat), "win" ); new G4PVPlacement(0, G4ThreeVector(det_X, det_Y, foilapp_z + foil_apperture_depth/2 + source_window/2+slack), win, "win", halfsensor, false, 0); win->SetVisAttributes(new G4VisAttributes(G4Colour(1, 1, 0))); } //-------------------------------------------------------------------- // here goes all the sensor housings, magnet yoke, ... // Those 3mm vertical bars at each side of the magnets, the outer // one being part of the housing frame, and the inner one being part // of the center/magnet separator. //-------------------------------------------------------------------- G4LogicalVolume *house = new G4LogicalVolume(new G4Box("house", house_thickness/2 - slack, magnet->gap/2 + magnet->size_Y - slack, magnet->size_Z/2 - slack), G4Material::GetMaterial("Al"), "house"); G4VisAttributes *va = new G4VisAttributes(G4Colour(0.2, 0.2, 0.2)); va->SetVisibility(true); house->SetVisAttributes(va); new G4PVPlacement(0, G4ThreeVector(det_X - magnet->size_X/2 - house_thickness/2, det_Y, 0), house, "house_V1", halfsensor, false, 1 ); new G4PVPlacement(0, G4ThreeVector(det_X + magnet->size_X/2 + house_thickness/2, det_Y, 0), house, "house_V2", halfsensor, false, 2 ); //-------------------------------------------------------------------- // Wrap the detector in Aluminum const double delrin_diameter = detector_geometry::stack_diameter; G4LogicalVolume *mag_delrin = new G4LogicalVolume(new G4Tubs("mag_delrin", detector_geometry::hole_diameter/2 + slack, delrin_diameter/2 - slack, mag_delrin_thickness/2 - slack, 0, 2*M_PI ), G4Material::GetMaterial("Al"), "mag_delrin" ); mag_delrin->SetVisAttributes(va); new G4PVPlacement(0, G4ThreeVector(det_X, det_Y, mag_det_z()-mag_delrin_thickness/2), mag_delrin, "mag_delrin", halfsensor, false, 0 ); dG4cerr << "mag Delrin " << mag_delrin_thickness/mm << "mm at z=" << (mag_det_z()-mag_delrin_thickness/2)/mm << "mm" << G4endl ; //-------------------------------------------------------------------- G4LogicalVolume *foil_delrin = new G4LogicalVolume(new G4Tubs("foil_delrin", detector_geometry::hole_diameter/2 + slack, delrin_diameter/2 - slack, foil_delrin_thickness/2 - slack, 0, 2*M_PI ), G4Material::GetMaterial("Al"), "foil_delrin" ); foil_delrin->SetVisAttributes(va); new G4PVPlacement(0, G4ThreeVector(det_X, det_Y, foil_det_z()+foil_delrin_thickness/2), foil_delrin, "foil_delrin", halfsensor, false, 0 ); dG4cerr << "foil Delrin " << foil_delrin_thickness/mm << "mm at z=" << (foil_det_z()+foil_delrin_thickness/2)/mm << "mm" << G4endl ; //-------------------------------------------------------------------- // CLose the Z-gaps with aluminum plates const double plate_diameter = detector_geometry::stack_diameter; const double plate_hole = magnet_geometry::size_X + 1*mm; const double mag_app_plate_thickness = sensor_geometry::mag_apperture_distance - sensor_geometry::mag_apperture_depth - mag_pips_z() - magnet_geometry::size_Z/2 ; G4LogicalVolume *mag_app_plate = new G4LogicalVolume(new G4Tubs("mag_app_plate", plate_hole/2 + slack, plate_diameter/2 - slack, mag_app_plate_thickness/2 - slack, 0, 2*M_PI ), G4Material::GetMaterial("Al"), "mag_app_plate" ); mag_app_plate->SetVisAttributes(va); new G4PVPlacement(0, G4ThreeVector(det_X, det_Y, - magnet_geometry::size_Z/2 - mag_app_plate_thickness/2), mag_app_plate, "mag_app_plate", halfsensor, false, 0 ); dG4cerr << "Magnet App plate " << mag_app_plate_thickness/mm << "mm at z=" << (- magnet_geometry::size_Z/2 - mag_app_plate_thickness/2)/mm << "mm" << G4endl ; //-------------------------------------------------------------------- const double mag_det_plate_thickness = mag_det_z() - magnet_geometry::size_Z/2 - mag_delrin_thickness ; G4LogicalVolume *mag_det_plate = new G4LogicalVolume(new G4Tubs("mag_det_plate", detector_geometry::hole_diameter/2 + slack, plate_diameter/2 - slack, mag_det_plate_thickness/2 - slack, 0, 2*M_PI ), G4Material::GetMaterial("Al"), "mag_det_plate" ); mag_det_plate->SetVisAttributes(va); new G4PVPlacement(0, G4ThreeVector(det_X, det_Y, magnet_geometry::size_Z/2 + mag_det_plate_thickness/2), mag_det_plate, "mag_det_plate", halfsensor, false, 0 ); dG4cerr << "Magnet Det plate " << mag_det_plate_thickness/mm << "mm at z=" << (magnet_geometry::size_Z/2 + mag_det_plate_thickness/2)/mm << "mm" << G4endl ; //-------------------------------------------------------------------- const double foil_det_plate_thickness = foil_pips_z() + sensor_geometry::foil_apperture_distance - sensor_geometry::foil_apperture_depth - foil_det_z() - foil_delrin_thickness ; G4LogicalVolume *foil_det_plate = new G4LogicalVolume(new G4Tubs("foil_det_plate", detector_geometry::hole_diameter/2 + slack, plate_diameter/2 - slack, foil_det_plate_thickness/2 - slack, 0, 2*M_PI ), G4Material::GetMaterial("Al"), "foil_det_plate" ); foil_det_plate->SetVisAttributes(va); new G4PVPlacement(0, G4ThreeVector(det_X, det_Y, foil_det_z() + foil_delrin_thickness + foil_det_plate_thickness/2), foil_det_plate, "foil_det_plate", halfsensor, false, 0 ); dG4cerr << "Foil Det plate " << foil_det_plate_thickness/mm << "mm at z=" << (foil_det_z() + foil_delrin_thickness + foil_det_plate_thickness/2)/mm << "mm" << G4endl ; //-------------------------------------------------------------------- }
[ "08Merlin@web.de" ]
08Merlin@web.de
e4c69a49bb4706081376982f89aff57b1a8a5347
4f58cc74e6270729a7d5dbc171455624d98807b4
/inc/rtspvideocapturer.h
a4e3c941bc56a53fb35bec922cce4053fdfd05b8
[ "Unlicense" ]
permissive
InsZVA/webrtc-streamer
5175776a8591472e5491c13f4dc5ba1aa3f867a8
10ab5dca8e8efc301c86b976ebf1472706eed89b
refs/heads/master
2021-01-12T17:37:10.775369
2016-10-09T10:54:03
2016-10-09T10:54:03
71,618,828
1
0
null
2016-10-22T05:28:05
2016-10-22T05:28:04
null
UTF-8
C++
false
false
10,734
h
/* --------------------------------------------------------------------------- ** This software is in the public domain, furnished "as is", without technical ** support, and with no warranty, express or implied, as to its usefulness for ** any purpose. ** ** rtspvideocapturer.h ** ** -------------------------------------------------------------------------*/ #ifndef RTSPVIDEOCAPTURER_H_ #define RTSPVIDEOCAPTURER_H_ #include <string.h> #include <vector> #include "webrtc/media/base/videocapturer.h" #include "webrtc/base/timeutils.h" #include "liveMedia.hh" #include "BasicUsageEnvironment.hh" #define RTSP_CALLBACK(uri, resultCode, resultString) \ static void continueAfter ## uri(RTSPClient* rtspClient, int resultCode, char* resultString) { static_cast<RTSPConnection*>(rtspClient)->continueAfter ## uri(resultCode, resultString); } \ void continueAfter ## uri (int resultCode, char* resultString); \ /**/ class Environment : public BasicUsageEnvironment { public: Environment(); ~Environment(); void mainloop() { this->taskScheduler().doEventLoop(&m_stop); } void stop() { m_stop = 1; }; protected: char m_stop; }; /* --------------------------------------------------------------------------- ** RTSP client connection interface ** -------------------------------------------------------------------------*/ class RTSPConnection : public RTSPClient { public: /* --------------------------------------------------------------------------- ** RTSP client callback interface ** -------------------------------------------------------------------------*/ class Callback { public: virtual bool onNewSession(const char* media, const char* codec) = 0; virtual bool onData(unsigned char* buffer, ssize_t size) = 0; virtual ssize_t onNewBuffer(unsigned char* buffer, ssize_t size) { return 0; }; }; protected: /* --------------------------------------------------------------------------- ** RTSP client Sink ** -------------------------------------------------------------------------*/ class SessionSink: public MediaSink { public: static SessionSink* createNew(UsageEnvironment& env, Callback* callback) { return new SessionSink(env, callback); } private: SessionSink(UsageEnvironment& env, Callback* callback); virtual ~SessionSink(); void allocate(ssize_t bufferSize); static void afterGettingFrame(void* clientData, unsigned frameSize, unsigned numTruncatedBytes, struct timeval presentationTime, unsigned durationInMicroseconds) { static_cast<SessionSink*>(clientData)->afterGettingFrame(frameSize, numTruncatedBytes, presentationTime, durationInMicroseconds); } void afterGettingFrame(unsigned frameSize, unsigned numTruncatedBytes, struct timeval presentationTime, unsigned durationInMicroseconds); virtual Boolean continuePlaying(); private: size_t m_bufferSize; u_int8_t* m_buffer; Callback* m_callback; ssize_t m_markerSize; }; public: RTSPConnection(UsageEnvironment& env, Callback* callback, const std::string & rtspURL, int verbosityLevel = 255); virtual ~RTSPConnection(); protected: void sendNextCommand(); RTSP_CALLBACK(DESCRIBE,resultCode,resultString); RTSP_CALLBACK(SETUP,resultCode,resultString); RTSP_CALLBACK(PLAY,resultCode,resultString); protected: MediaSession* m_session; MediaSubsession* m_subSession; MediaSubsessionIterator* m_subSessionIter; Callback* m_callback; }; Environment::Environment() : BasicUsageEnvironment(*BasicTaskScheduler::createNew()), m_stop(0) { } Environment::~Environment() { TaskScheduler* scheduler = &this->taskScheduler(); this->reclaim(); delete scheduler; } RTSPConnection::SessionSink::SessionSink(UsageEnvironment& env, Callback* callback) : MediaSink(env) , m_bufferSize(0) , m_buffer(NULL) , m_callback(callback) , m_markerSize(0) { allocate(1024*1024); } RTSPConnection::SessionSink::~SessionSink() { delete [] m_buffer; } void RTSPConnection::SessionSink::allocate(ssize_t bufferSize) { m_bufferSize = bufferSize; m_buffer = new u_int8_t[m_bufferSize]; if (m_callback) { m_markerSize = m_callback->onNewBuffer(m_buffer, m_bufferSize); LOG(INFO) << "markerSize:" << m_markerSize; } } void RTSPConnection::SessionSink::afterGettingFrame(unsigned frameSize, unsigned numTruncatedBytes, struct timeval presentationTime, unsigned durationInMicroseconds) { LOG(LS_VERBOSE) << "NOTIFY size:" << frameSize; if (numTruncatedBytes != 0) { delete [] m_buffer; LOG(INFO) << "buffer too small " << m_bufferSize << " allocate bigger one\n"; allocate(m_bufferSize*2); } else if (m_callback) { if (!m_callback->onData(m_buffer, frameSize+m_markerSize)) { LOG(WARNING) << "NOTIFY failed"; } } this->continuePlaying(); } Boolean RTSPConnection::SessionSink::continuePlaying() { Boolean ret = False; if (source() != NULL) { source()->getNextFrame(m_buffer+m_markerSize, m_bufferSize-m_markerSize, afterGettingFrame, this, onSourceClosure, this); ret = True; } return ret; } RTSPConnection::RTSPConnection(UsageEnvironment& env, Callback* callback, const std::string & rtspURL, int verbosityLevel) : RTSPClient(env, rtspURL.c_str(), verbosityLevel, NULL, 0 #if LIVEMEDIA_LIBRARY_VERSION_INT > 1371168000 ,-1 #endif ) , m_session(NULL) , m_subSessionIter(NULL) , m_callback(callback) { // initiate connection process this->sendNextCommand(); } RTSPConnection::~RTSPConnection() { delete m_subSessionIter; Medium::close(m_session); } void RTSPConnection::sendNextCommand() { if (m_subSessionIter == NULL) { // no SDP, send DESCRIBE this->sendDescribeCommand(continueAfterDESCRIBE); } else { m_subSession = m_subSessionIter->next(); if (m_subSession != NULL) { // still subsession to SETUP if (!m_subSession->initiate()) { LOG(WARNING) << "Failed to initiate " << m_subSession->mediumName() << "/" << m_subSession->codecName() << " subsession: " << envir().getResultMsg(); this->sendNextCommand(); } else { LOG(INFO) << "Initiated " << m_subSession->mediumName() << "/" << m_subSession->codecName() << " subsession"; } this->sendSetupCommand(*m_subSession, continueAfterSETUP); } else { // no more subsession to SETUP, send PLAY this->sendPlayCommand(*m_session, continueAfterPLAY); } } } void RTSPConnection::continueAfterDESCRIBE(int resultCode, char* resultString) { if (resultCode != 0) { LOG(WARNING) << "Failed to DESCRIBE: " << resultString; } else { LOG(INFO) << "Got SDP:\n" << resultString; m_session = MediaSession::createNew(envir(), resultString); m_subSessionIter = new MediaSubsessionIterator(*m_session); this->sendNextCommand(); } delete[] resultString; } void RTSPConnection::continueAfterSETUP(int resultCode, char* resultString) { if (resultCode != 0) { LOG(WARNING) << "Failed to SETUP: " << resultString; } else { m_subSession->sink = SessionSink::createNew(envir(), m_callback); if (m_subSession->sink == NULL) { LOG(WARNING) << "Failed to create a data sink for " << m_subSession->mediumName() << "/" << m_subSession->codecName() << " subsession: " << envir().getResultMsg() << "\n"; } else if (m_callback->onNewSession(m_subSession->mediumName(), m_subSession->codecName())) { LOG(WARNING) << "Created a data sink for the \"" << m_subSession->mediumName() << "/" << m_subSession->codecName() << "\" subsession"; m_subSession->sink->startPlaying(*(m_subSession->readSource()), NULL, NULL); } } delete[] resultString; this->sendNextCommand(); } void RTSPConnection::continueAfterPLAY(int resultCode, char* resultString) { if (resultCode != 0) { LOG(WARNING) << "Failed to PLAY: " << resultString; } else { LOG(INFO) << "PLAY OK"; } delete[] resultString; } #include "webrtc/base/optional.h" #include "webrtc/common_video/h264/sps_parser.h" class RTSPVideoCapturer : public cricket::VideoCapturer, public RTSPConnection::Callback, public rtc::Thread { public: RTSPVideoCapturer(const std::string & uri) : m_connection(m_env,this,uri.c_str()) { LOG(INFO) << "===========================RTSPVideoCapturer" << uri ; } virtual ~RTSPVideoCapturer() { } virtual bool onNewSession(const char* media, const char* codec) { LOG(INFO) << "===========================onNewSession" << media << "/" << codec; bool success = false; if ( (strcmp(media, "video") == 0) && (strcmp(codec, "H264") == 0) ) { success = true; } return success; } virtual bool onData(unsigned char* buffer, ssize_t size) { std::cout << "===========================onData" << size << std::endl; if (!IsRunning()) { return false; } if (!GetCaptureFormat()) { rtc::Optional<webrtc::SpsParser::SpsState> sps = webrtc::SpsParser::ParseSps(buffer, size); if (!sps) { std::cout << "cannot parse sps" << std::endl; } else { std::cout << "add new format " << sps->width << "x" << sps->height << std::endl; std::vector<cricket::VideoFormat> formats; formats.push_back(cricket::VideoFormat(sps->width, sps->height, cricket::VideoFormat::FpsToInterval(25), cricket::FOURCC_H264)); SetSupportedFormats(formats); } } if (!GetCaptureFormat()) { return false; } cricket::CapturedFrame frame; frame.width = GetCaptureFormat()->width; frame.height = GetCaptureFormat()->height; frame.fourcc = GetCaptureFormat()->fourcc; frame.data_size = size; std::unique_ptr<char[]> data(new char[size]); frame.data = data.get(); memcpy(frame.data, buffer, size); SignalFrameCaptured(this, &frame); return true; } virtual cricket::CaptureState Start(const cricket::VideoFormat& format) { SetCaptureFormat(&format); SetCaptureState(cricket::CS_RUNNING); rtc::Thread::Start(); return cricket::CS_RUNNING; } virtual void Stop() { m_env.stop(); rtc::Thread::Stop(); SetCaptureFormat(NULL); SetCaptureState(cricket::CS_STOPPED); } void Run() { m_env.mainloop(); } virtual bool GetPreferredFourccs(std::vector<unsigned int>* fourccs) { fourccs->push_back(cricket::FOURCC_H264); return true; } virtual bool IsScreencast() const { return false; }; virtual bool IsRunning() { return this->capture_state() == cricket::CS_RUNNING; } private: Environment m_env; RTSPConnection m_connection; }; #endif
[ "michel.promonet@free.fr" ]
michel.promonet@free.fr
a052284e3d310e4510f3a1e13d2c297858e01c51
5c56bb3fd918c7d267a5f8dc24470379ea1a3271
/PandaChatServer/mysqlapi/DatabaseMysql.cpp
5c419e6491903210e7bb6257532728b00e256abf
[]
no_license
eric8068/PandaChatProject
8009f267733f5290bedf051f3f6aa0a9216956f0
e374c4ee8446a0c779e426f8542485278b229e89
refs/heads/master
2023-03-18T17:12:22.296316
2020-08-31T05:11:58
2020-08-31T05:11:58
null
0
0
null
null
null
null
UTF-8
C++
false
false
9,010
cpp
#include "DatabaseMysql.h" #include <fstream> #include <stdarg.h> #include <string.h> //#include "../base/AsyncLog.h" CDatabaseMysql::CDatabaseMysql(void) { //m_Mysql = new MYSQL; m_Mysql = NULL; m_bInit = false; } CDatabaseMysql::~CDatabaseMysql(void) { if (m_Mysql != NULL) { if (m_bInit) { mysql_close(m_Mysql); } //delete m_Mysql; } } bool CDatabaseMysql::initialize(const std::string& host, const std::string& user, const std::string& pwd, const std::string& dbname) { //LOGI << "CDatabaseMysql::Initialize, begin..."; //ClearStoredResults(); if (m_bInit) { mysql_close(m_Mysql); } m_Mysql = mysql_init(m_Mysql); m_Mysql = mysql_real_connect(m_Mysql, host.c_str(), user.c_str(), pwd.c_str(), dbname.c_str(), 0, NULL, 0); //ClearStoredResults(); //LOGI << "mysql info: host=" << host << ", user=" << user << ", password=" << pwd << ", dbname=" << dbname; m_DBInfo.strDBName = dbname; m_DBInfo.strHost = host; m_DBInfo.strUser = user; m_DBInfo.strPwd = pwd; if (m_Mysql) { //LOGI << "m_Mysql address " << (long)m_Mysql; //LOGI << "CDatabaseMysql::Initialize, set names utf8"; mysql_query(m_Mysql, "set names utf8"); //mysql_query(m_Mysql, "set names latin1"); m_bInit = true; return true; } else { //LOGE << "Could not connect to MySQL database at " << host.c_str() // << ", " << mysql_error(m_Mysql); mysql_close(m_Mysql); return false; } //LOGI << "CDatabaseMysql::Initialize, init failed!"; return false; } //TODO: 这个函数要区分一下空数据集和出错两种情况 QueryResult* CDatabaseMysql::query(const char* sql) { if (!m_Mysql) { //LOGI << "CDatabaseMysql::Query, mysql is disconnected!"; if (false == initialize(m_DBInfo.strHost, m_DBInfo.strUser, m_DBInfo.strPwd, m_DBInfo.strDBName)) { return NULL; } } if (!m_Mysql) return 0; MYSQL_RES* result = 0; uint64_t rowCount = 0; uint32_t fieldCount = 0; { //LOGI << sql; int iTempRet = mysql_real_query(m_Mysql, sql, strlen(sql)); if (iTempRet) { unsigned int uErrno = mysql_errno(m_Mysql); //LOGI << "CDatabaseMysql::Query, mysql is abnormal, errno : " << uErrno; if (CR_SERVER_GONE_ERROR == uErrno) { //LOGI << "CDatabaseMysql::Query, mysql is disconnected!"; if (false == initialize(m_DBInfo.strHost, m_DBInfo.strUser, m_DBInfo.strPwd, m_DBInfo.strDBName)) { return NULL; } //LOGI << sql; iTempRet = mysql_real_query(m_Mysql, sql, strlen(sql)); if (iTempRet) { //LOGE << "SQL: " << sql ; //LOGE << "query ERROR: " << mysql_error(m_Mysql); } } else { //LOGE << "SQL: " << sql ; //LOGE << "query ERROR: " << mysql_error(m_Mysql); return NULL; } } //LOGI << "call mysql_store_result"; result = mysql_store_result(m_Mysql); rowCount = mysql_affected_rows(m_Mysql); fieldCount = mysql_field_count(m_Mysql); // end guarded block } if (!result) return NULL; // if (!rowCount) // { //LOGI << "call mysql_free_result"; // mysql_free_result(result); // return NULL; // } QueryResult* queryResult = new QueryResult(result, rowCount, fieldCount); queryResult->nextRow(); return queryResult; } QueryResult* CDatabaseMysql::pquery(const char* format, ...) { if (!format) return NULL; va_list ap; char szQuery[MAX_QUERY_LEN]; va_start(ap, format); int res = vsnprintf(szQuery, MAX_QUERY_LEN, format, ap); va_end(ap); if (res == -1) { //LOGE << "SQL Query truncated (and not execute) for format: " << format; return NULL; } return query(szQuery); } bool CDatabaseMysql::execute(const char* sql) { if (!m_Mysql) return false; { int iTempRet = mysql_query(m_Mysql, sql); if (iTempRet) { unsigned int uErrno = mysql_errno(m_Mysql); //LOGI << "CDatabaseMysql::Query, mysql is abnormal, errno : " << uErrno; if (CR_SERVER_GONE_ERROR == uErrno) { //LOGI << "CDatabaseMysql::Query, mysql is disconnected!"; if (false == initialize(m_DBInfo.strHost, m_DBInfo.strUser, m_DBInfo.strPwd, m_DBInfo.strDBName)) { return false; } //LOGI << sql; iTempRet = mysql_real_query(m_Mysql, sql, strlen(sql)); if (iTempRet) { // LOGE("sql error: %s, sql: %s", mysql_error(m_Mysql), sql); //LOGE << "query ERROR: " << mysql_error(m_Mysql); } } else { //LOGE << "SQL: " << sql; //LOGE << "query ERROR: " << mysql_error(m_Mysql); //LOGE("sql error: %s, sql: %s", mysql_error(m_Mysql), sql); } return false; } } return true; } bool CDatabaseMysql::execute(const char* sql, uint32_t& uAffectedCount, int& nErrno) { if (!m_Mysql) return false; { int iTempRet = mysql_query(m_Mysql, sql); if (iTempRet) { unsigned int uErrno = mysql_errno(m_Mysql); //LOGE << "CDatabaseMysql::Query, mysql is abnormal, errno : " << uErrno; if (CR_SERVER_GONE_ERROR == uErrno) { //LOGE << "CDatabaseMysql::Query, mysql is disconnected!"; if (false == initialize(m_DBInfo.strHost, m_DBInfo.strUser, m_DBInfo.strPwd, m_DBInfo.strDBName)) { return false; } //LOGI << sql; iTempRet = mysql_query(m_Mysql, sql); nErrno = iTempRet; if (iTempRet) { //LOGE << "SQL: " << sql; //LOGE << "query ERROR: " << mysql_error(m_Mysql); } } else { //LOGE << "SQL: " << sql; //LOGE << "query ERROR: " << mysql_error(m_Mysql); } return false; } uAffectedCount = static_cast<uint32_t>(mysql_affected_rows(m_Mysql)); } return true; } bool CDatabaseMysql::pexecute(const char* format, ...) { if (!format) return false; va_list ap; char szQuery[MAX_QUERY_LEN]; va_start(ap, format); int res = vsnprintf(szQuery, MAX_QUERY_LEN, format, ap); va_end(ap); if (res == -1) { //LOGE << "SQL Query truncated (and not execute) for format: " << format; return false; } if (!m_Mysql) return false; { int iTempRet = mysql_query(m_Mysql, szQuery); if (iTempRet) { unsigned int uErrno = mysql_errno(m_Mysql); //LOGE << "CDatabaseMysql::Query, mysql is abnormal, errno : " << uErrno; if (CR_SERVER_GONE_ERROR == uErrno) { //LOGE << "CDatabaseMysql::Query, mysql is disconnected!"; if (false == initialize(m_DBInfo.strHost, m_DBInfo.strUser, m_DBInfo.strPwd, m_DBInfo.strDBName)) { return false; } //LOGI << szQuery; iTempRet = mysql_query(m_Mysql, szQuery); if (iTempRet) { //LOGE << "SQL: " << szQuery; //LOGE << "query ERROR: " << mysql_error(m_Mysql); } } else { //LOGE << "SQL: " << szQuery; //LOGE << "query ERROR: " << mysql_error(m_Mysql); } return false; } } return true; } void CDatabaseMysql::clearStoredResults() { if (!m_Mysql) { return; } MYSQL_RES* result = NULL; while (!mysql_next_result(m_Mysql)) { if ((result = mysql_store_result(m_Mysql)) != NULL) { mysql_free_result(result); } } } uint32_t CDatabaseMysql::getInsertID() { return (uint32_t)mysql_insert_id(m_Mysql); } int32_t CDatabaseMysql::escapeString(char* szDst, const char* szSrc, uint32_t uSize) { if (m_Mysql == NULL) { return 0; } if (szDst == NULL || szSrc == NULL) { return 0; } return mysql_real_escape_string(m_Mysql, szDst, szSrc, uSize); }
[ "405126907@qq.com" ]
405126907@qq.com
db183aadd494908d01dfa0ea5e0f5fae234ee239
a76a2581d5d3c1ec2f9529ab4d1db9f9828341d8
/Common/src/Common/String.h
d0adeb2adebc3c722db8a8ba6246b87ff7cfdd4e
[]
no_license
YanChernikov/IntroToAI
b16f9f08b448db97cf940b299b2a2769b61c9408
9b242862616588c4baf048f07d898083cb5f7caf
refs/heads/master
2021-01-18T21:18:47.738424
2016-05-20T05:08:54
2016-05-20T05:08:54
54,003,690
1
1
null
null
null
null
UTF-8
C++
false
false
1,067
h
#pragma once #include <string> #include <vector> // A series of string manipulation functions that proved useful for parsing // the input text file typedef std::string String; typedef std::vector<String> StringList; String ReadStringFromFile(const String& path); StringList ReadLinesFromFile(const String& path); void WriteStringToFile(const String& string, const String& path); StringList SplitString(const String& string, const String& delimiters); StringList SplitString(const String& string, const char delimiter); StringList Tokenize(const String& string); StringList GetLines(const String& string); const char* FindToken(const char* str, const String& token); const char* FindToken(const String& string, const String& token); String GetBlock(const char* str, const char** outPosition = nullptr); String GetBlock(const String& string, int offset = 0); String GetStatement(const char* str, const char** outPosition = nullptr); bool StartsWith(const String& string, const String& start); int NextInt(const String& string);
[ "yan@tracnode.com" ]
yan@tracnode.com
72805e7b770675576f4f275adbe9da7d0f925757
514128d3338709b7d38e1dab8535392f71409435
/reconstruction/src/timer/Timer.cpp
154a818f4cdfca16457bdcc03e9c8ace5d3605a5
[]
no_license
fukamikentaro/HeteroEdge
2ba0a1bca7d0b696de60501afa6a133aece73845
39511607c5451076cae6b9fa4979496775b46ec6
refs/heads/master
2022-10-27T09:18:19.751146
2019-07-14T01:11:10
2019-07-14T01:11:10
null
0
0
null
null
null
null
UTF-8
C++
false
false
507
cpp
/* * timer.cpp * * Created on: Jan 3, 2018 * Author: wuyang */ #include "Timer.h" Timer::Timer() { timeUse = 0.f; } Timer::~Timer() { // TODO Auto-generated destructor stub } void Timer::start() { gettimeofday(&tpstart, NULL); } void Timer::end() { gettimeofday(&tpend, NULL); countElapseTime(); } inline void Timer::countElapseTime(){ timeUse = 1000 * (tpend.tv_sec - tpstart.tv_sec) + (tpend.tv_usec - tpstart.tv_usec) / 1000; } long Timer::getTimeUse(){ return timeUse; }
[ "you@example.com" ]
you@example.com
a0019ab5724902395ba484bf15ce3aa4c7b32816
402e5a36be25d49f913da94a71647dc28a0ef359
/1.ARDUINO PROJECT/28.lcd 16x2/LCD_12c/counter/counter.ino
af4cb10e64b1a0c04fa4678a0f53eeac0c71a77a
[]
no_license
indrabhekti/Arduino-Project-Code
7b74324dab4361ce6de2d8cc669ac93e72e8d741
17f3266ba4f48bdc968ad81a67a813be1eb10aed
refs/heads/main
2023-05-29T01:53:04.504412
2021-06-04T07:27:42
2021-06-04T07:27:42
373,754,838
0
0
null
null
null
null
UTF-8
C++
false
false
772
ino
#include <Wire.h> // Library untuk komunikasi I2C (harus install library) #include <LiquidCrystal_I2C.h> // Library LCD(harus intall library) // SDA pin di A4 and SCL pin di A5. // Connect LCD via I2C, default address 0x27 (default addres harus di cari dulu)(A0-A2 tidak di jumper) LiquidCrystal_I2C lcd = LiquidCrystal_I2C(0x27, 16, 2); // (default addres,panjang kolom lcd,lebar kolom lcd)(0x27,16,2) 0x27 untuk addres ,16x2 LCD. int count = 0; void setup() { lcd.init(); lcd.backlight(); lcd.backlight(); int temp = 10; lcd.clear(); } void loop() { lcd.clear(); lcd.setCursor(0, 0); // lcd.print( "4bit binary"); // isi kata lcd.setCursor(2, 1); // lcd.print( count); count++; if ( count >= 15) count = 0; delay(2000); }
[ "indrabhektiutomo@gmail.com" ]
indrabhektiutomo@gmail.com
dc03bf262efcda0b2a12a8583efa75a41cab189e
6f714dbab92f0507f13aa582fa992277e42c1777
/Plugin/syslog/SysLogMgr.h
f872d871aa9a2f530b9d72310c134748e29784d1
[]
no_license
sinzuo/bluedon-soc
90d72b966ace8d49b470dab791bd65f0d56d520e
809b59888de2f94b345b36ae33afacdbe103a1dd
refs/heads/master
2020-09-20T17:54:20.882559
2019-11-28T02:27:16
2019-11-28T02:27:16
224,552,658
0
1
null
null
null
null
UTF-8
C++
false
false
5,189
h
/** ************************************************ * COPYRIGHT NOTICE * Copyright (c) 2017, BLUEDON * All rights reserved. * * @file SysLogMgr.h * @brief * * * @version 1.0 * @author xxx * @date 2017年08月03日 * * 修订说明:最初版本 **************************************************/ #ifndef _SYSLOG_MGR_H_ #define _SYSLOG_MGR_H_ #include <log4cxx/logger.h> #include <log4cxx/logstring.h> #include <log4cxx/propertyconfigurator.h> #include "common/BDScModuleBase.h" #include "SysLogUdp.h" #include "SysLogTcp.h" #include "config/BDOptions.h" #include "Poco/Mutex.h" #include <vector> #include <set> #include <list> #include <string> //log4xx宏定义 #define SYSLOG_INFO_V(str) LOG4CXX_INFO(log4cxx::Logger::getLogger("SYSLOG"), str); #define SYSLOG_DEBUG_V(str) LOG4CXX_DEBUG(log4cxx::Logger::getLogger("SYSLOG"), str); #define SYSLOG_WARN_V(str) LOG4CXX_WARN(log4cxx::Logger::getLogger("SYSLOG"), str); #define SYSLOG_ERROR_V(str) LOG4CXX_ERROR(log4cxx::Logger::getLogger("SYSLOG"), str); #define SYSLOG_INFO_S(str) LOG4CXX_INFO(log4cxx::Logger::getLogger("SYSLOG"), #str); #define SYSLOG_DEBUG_S(str) LOG4CXX_DEBUG(log4cxx::Logger::getLogger("SYSLOG"), #str); #define SYSLOG_WARN_S(str) LOG4CXX_WARN(log4cxx::Logger::getLogger("SYSLOG"), #str); #define SYSLOG_ERROR_S(str) LOG4CXX_ERROR(log4cxx::Logger::getLogger("SYSLOG"), #str); typedef struct BDSyslogConfigEx { char chLog4File[100]; int nModuleId; char chModuleName[20]; UInt16 wModuleVersion; int nListenPort; char chRecordSep[2]; //记录分隔符 char chFieldSep[2]; //字段分隔符 char chDelimiter[20]; //分割字符串 bool bUseUdpRecv; //是否用udp接收(默认true) unsigned int nListCtrl; //队列长度控制 unsigned int nBreakCtrl; //report跳出控制 unsigned int nSleepTimeMs; //睡眠时间(毫秒) bool nSendtoKafka; //是否直接发送到kafka }tag_syslog_config_t; //udp,tcp方式相同数据变量 class ShareData { public: static Poco::Mutex m_inputMutex; static std::list<std::string> m_strLogList; static string m_strDelimiter; static long list_num; }; class CSysLogMgr:public CScModuleBase { public: CSysLogMgr(const string &strConfigName); virtual ~CSysLogMgr(void); virtual bool Init(void); //初始化数据,先于Start被调用 virtual bool Start(void); //启动模块 virtual bool Stop(void); //停止模块 virtual bool IsRunning(void); //检查模块是否处于运行状态 virtual UInt32 GetModuleId(void); //获取模块id virtual UInt16 GetModuleVersion(void);//获取模块版本 virtual string GetModuleName(void);//获取模块名称 virtual bool StartTask(const PModIntfDataType pDataType,const void * pData); //开始(下发)任务 virtual bool StopTask(const PModIntfDataType pDataType,const void * pData); //停止(取消)任务 virtual bool SetData(const PModIntfDataType pDataType,const void * pData,Poco::UInt32 dwLength);//调用方下发数据 virtual void* GetData(const PModIntfDataType pDataType,Poco::UInt32& dwRetLen); //调用方获取数据 virtual void FreeData(void * pData); //调用方释放获取到的内存 virtual void SetReportData(pFunc_ReportData pCbReport); //设置上报数据调用指针 virtual void SetFetchData(pFunc_FetchData pCbFetch); //设置获取数据调用指针 protected: bool LoadConfig(void); //加载配置文件 void printConfig(); //打印配置信息 bool Load(void); //加载业务数据 bool ReportData(const PModIntfDataType pDataType,const void * pData,Poco::UInt32 dwLength); //上报数据(主要为监控日志) const char* FetchData(const PModIntfDataType pDataType,Poco::UInt32& dwRetLen); //获取客户端系统参数 private: static string fromBase64(const std::string &source); static void* OnSatrtUdpServer(void *arg); //开启UDP监听以及I/O事件检测 static void* OnSatrtTcpServer(void *arg); //开启TCP监听以及I/O事件检测 static void* OnFetchHandle(void *arg); //Fetch Data 事件线程处理函数 static void* OnReportHandle(void *arg); //Report Data 事件线程处理函数 private: pFunc_ReportData m_pFuncReportData; pFunc_FetchData m_pFuncFetchData; std::string m_strConfigName; //pthread_t p_thread_fetch; //Poco::Mutex m_mutex_fetch; //m_setFetch 队列互斥锁 //list<modintf_datatype_t> m_listFetch; //Fetch 数据任务队列 Poco::FastMutex m_ModMutex; pthread_t p_thread_report; pthread_t p_thread_server; //Poco::Mutex m_mutex_report; UdpClientService* pServer; TcpClientAcceptor* pTcpServer; //add in 2017.04.25 bool m_bIsRunning; bool m_bServerState; //m_bUdpServerState std::set<std::string> m_setPolicy; public: tag_syslog_config_t m_sysLogConfig; }; #endif //_SYSLOG_MGR_H_
[ "1586706912@qq.com" ]
1586706912@qq.com
e0a16bd4317247939e2026b017b5bf9962a9e026
e3b588ac490d4ac67a691a618102ef6126096d19
/solution2.cpp
445b4dd9f96ac01851e1dadbd22e363e3759ea9d
[]
no_license
oooooome/LeetCode-cmake
c82d28da56ff12fb40b6b0eeaafc0d5d809b3072
38299c8f4aefd36c235a5bb20ea660c114a4c2e7
refs/heads/master
2023-08-31T04:52:21.098309
2021-10-26T14:06:04
2021-10-26T14:06:04
403,633,759
0
0
null
null
null
null
UTF-8
C++
false
false
1,726
cpp
#include <iostream> //Definition for singly-linked list. struct ListNode { int val; ListNode* next; ListNode() : val(0), next(nullptr) {} ListNode(int x) : val(x), next(nullptr) {} ListNode(int x, ListNode* next) : val(x), next(next) {} }; class Solution2 { public: ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { ListNode* res = new ListNode((l1->val + l2->val) % 10); addNode(l1->next, l2->next, (l1->val + l2->val) / 10, res); return res; } void addNode(ListNode* l1, ListNode* l2, int i, ListNode* forwardNode) { ListNode l1o; ListNode l2o; if (l1 != nullptr) { l1o.val = l1->val; l1o.next = l1->next; }else if(i == 0) { forwardNode->next = l2; return; } if (l2 != nullptr) { l2o.val = l2->val; l2o.next = l2->next; }else if(i == 0) { forwardNode->next = l1; return; } int One = (l1o.val + l2o.val + i) % 10; int Ten = (l1o.val + l2o.val + i) / 10; ListNode* res = new ListNode(One); forwardNode->next = res; if (One == 0 && Ten == 0 && l1->next == nullptr && l2->next == nullptr) { return; } else { addNode(l1o.next, l2o.next, Ten, res); } } }; int main() { ListNode l11{ 1, nullptr }; ListNode l12{ 6, &l11 }; ListNode l13{ 0, &l12 }; ListNode l14{ 3, &l13 }; ListNode l15{ 3, &l14 }; /*[1, 6, 0, 3, 3, 6, 7, 2, 0, 1] [6, 3, 0, 8, 9, 6, 6, 9, 6, 1]*/ ListNode l21{ 6, nullptr }; ListNode l22{ 3, &l21 }; ListNode l23{ 0, &l22 }; ListNode l24{ 8, &l23 }; ListNode l25{ 9, &l24 }; ListNode* l1 = &l15; ListNode* l2 = &l25; Solution2 s{}; auto res = s.addTwoNumbers(l1, l2); for (;;) { if (res == nullptr) { break;; } std::cout << res->val; res = res->next; } return 0; }
[ "liruijie@ebupt.com" ]
liruijie@ebupt.com
db09a88804601d12b545a70315ebab227ff0e4bd
68ed77e9af79655e78f8a61594cc1b12bd278f59
/src/gps/UtcTime.cpp
0ed86c1efcf7d0bcab88d0b230120c02f2a1938a
[ "MIT" ]
permissive
havardhellvik/sensors-and-senders
4ef79205124471d1add5f4ddae14ed004360a2bf
9323457a91e0fcdddfbfe3ffea5fba5a7ed7591d
refs/heads/master
2023-08-16T01:03:28.533747
2021-10-04T10:00:45
2021-10-04T10:02:58
418,494,603
0
0
null
null
null
null
UTF-8
C++
false
false
613
cpp
#include "UtcTime.hpp" #include <cmath> UtcTime::UtcTime() : _start(std::chrono::system_clock::now()) { } double UtcTime::time() const { const auto now = std::chrono::system_clock::now(); std::chrono::duration<double> time_since_start = now - _start; const auto seconds_since_start = time_since_start.count(); const auto hours = std::floor(seconds_since_start / 3600.0); const auto minutes = std::floor(seconds_since_start / 60.0) - hours * 60; const auto seconds = seconds_since_start - hours * 3600 - minutes * 60; return hours * 10000 + minutes * 100 + seconds; }
[ "thomas.evang@km.kongsberg.com" ]
thomas.evang@km.kongsberg.com
ce3ad0b0714892a4dc1c23c65849ea6482fedec0
bb0efbc98574362ec2a769ba5d3c746a761a9d6a
/branches/avilanova/plugins/stable/GpuGlyphs/GPUGlyphs/vtkGlyphMapper.h
edf52951c6b12151c8fb3a7abb7b7c3d101a497d
[]
no_license
BackupTheBerlios/viste-tool-svn
4a19d5c5b9e2148b272d02c82fda8e6a9d041298
9692cff93e5a1b6dcbd47cad189618b556ec65bb
refs/heads/master
2021-01-23T11:07:25.738114
2014-02-06T18:38:54
2014-02-06T18:38:54
40,748,200
0
0
null
null
null
null
UTF-8
C++
false
false
3,500
h
/** * vtkGlyphMapper.h * by Tim Peeters * * 2008-02-27 Tim Peeters * - First version */ #ifndef bmia_vtkGlyphMapper_h #define bmia_vtkGlyphMapper_h #include <vtkVolumeMapper.h> class vtkPointSet; namespace bmia { class vtkMyShaderProgram; class vtkUniformFloat; class vtkUniformIvec3; class vtkUniformVec3; class vtkFBO; class vtkUniformSampler; class vtkUniformBool; /** * Superclass for GPU-based glyph rendering methods. * Volume data is stored in GPU memory using 3D textures. */ class vtkGlyphMapper : public vtkVolumeMapper { public: virtual void Render(vtkRenderer *ren, vtkVolume *vol); /** * Set/Get the PointSet that defines the seed points * for the glyphs to render. */ void SetSeedPoints(vtkPointSet* points); vtkGetObjectMacro(SeedPoints, vtkPointSet); /** * Set/Get the maximum radius of the glyphs in any direction. * This is used for constructing the bounding boxes around the * glyphs in DrawPoints. */ void SetMaxGlyphRadius(float r); vtkGetMacro(MaxGlyphRadius, float); void SetNegateX(bool negate); void SetNegateY(bool negate); void SetNegateZ(bool negate); bool GetNegateX(); bool GetNegateY(); bool GetNegateZ(); void PrintNumberOfSeedPoints(); void SetGlyphScaling(float scale); vtkGetMacro(GlyphScaling, float); protected: vtkGlyphMapper(); ~vtkGlyphMapper(); /** * To be called in subclasses after the shader programs have * been set-up. */ virtual void SetupShaderUniforms(); /** * Check for the needed OpenGL extensions and load them. * When done, set this->Initialized. */ void Initialize(); /** * Load all needed textures. * This function can call LoadTexture(...). */ virtual void LoadTextures() = 0; /** * Load texture and bind it to index texture_index. * The texture data comes from the input ImageData in array * with name array_name. */ void LoadTexture(int texture_index, const char* array_name); /** * Draw the points of the input data. * This method draws bounding boxes around the points such that * the glyphs, with maximum radius MaxGlyphRadius will always fit * in. In some cases (e.g. with lines), this function can be * overridden to use a more restricted bounding box. */ virtual void DrawPoints(); /** * Shader program for rendering to depth buffer. * No lighting calculations need to be done here. */ vtkMyShaderProgram* SPDepth; /** * Shader program for rendering the final scene to the screen. */ vtkMyShaderProgram* SPLight; /** * Call this after activating the shader program! */ virtual void SetTextureLocations() {}; void SetTextureLocation(vtkMyShaderProgram* sp, vtkUniformSampler* sampler); //, const char* texture_name); /** * Draw screen-filling quad ;) */ // void DrawScreenFillingQuad(int width, int height); void DrawScreenFillingQuad(int viewport[4]); private: double GlyphScaling; double MaxGlyphRadius; vtkPointSet* SeedPoints; vtkUniformVec3* UEyePosition; vtkUniformVec3* ULightPosition; vtkUniformIvec3* UTextureDimensions; vtkUniformVec3* UTextureSpacing; vtkUniformFloat* UMaxGlyphRadius; vtkUniformFloat* UGlyphScaling; // vtkShadowMappingHelper* ShadowMappingHelper; vtkFBO* FBODepth; vtkFBO* FBOShadow; bool Initialized; vtkUniformBool* UNegateX; vtkUniformBool* UNegateY; vtkUniformBool* UNegateZ; }; // class vtkGlyphMapper } // namespace bmia #endif // bmia_vtkGlyphMapper_h
[ "viste-tue@ae44682b-4238-4e27-a57b-dd11a28b3479" ]
viste-tue@ae44682b-4238-4e27-a57b-dd11a28b3479
f0ec0194df9b99c11bbc6fdc134d75f78aec32d9
51e993226766d8a38a8cbdcb16ef2eb34695349c
/sim/rcp.h
d2c71a6ff2ee5078d83b09b55c33e768531d98fe
[]
no_license
sandyhouse/htsimMPTCP
927d0ef54bf95af3567d103816c78a4cb5d875bf
3f89d904530d28d40891edb172fb972ea7926973
refs/heads/master
2020-03-09T22:25:27.753968
2014-01-30T19:54:45
2014-01-30T19:54:45
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,279
h
#ifndef RCP_H #define RCP_H /* * An RCP source and sink */ #include <list> #include "config.h" #include "network.h" #include "rcppacket.h" #include "eventlist.h" class RcpSink; class RcpSrc : public PacketSink, public EventSource { friend class RcpSink; public: RcpSrc(RcpLogger* logger, TrafficLogger* pktlogger, EventList &eventlist); void connect(route_t& routeout, route_t& routeback, RcpSink& sink, simtime_picosec startTime); void startflow(); void doNextEvent() { startflow(); } void receivePacket(Packet& pkt); void rtx_timer_hook(simtime_picosec now); // should really be private, but loggers want to see: uint32_t _highest_sent; //seqno is in bytes uint32_t _cwnd; uint32_t _maxcwnd; uint32_t _last_acked; uint32_t _ssthresh; uint16_t _dupacks; uint16_t _mss; uint32_t _unacked; // an estimate of the amount of unacked data WE WANT TO HAVE in the network uint32_t _effcwnd; // an estimate of our current transmission rate, expressed as a cwnd uint32_t _recoverq; bool _in_fast_recovery; private: // Housekeeping RcpLogger* _logger; TrafficLogger* _pktlogger; // Connectivity PacketFlow _flow; RcpSink* _sink; route_t* _route; // Mechanism void inflate_window(); void send_packets(); void retransmit_packet(); simtime_picosec _rtt; simtime_picosec _last_sent_time; }; class RcpSink : public PacketSink, public Logged { friend class RcpSrc; public: RcpSink(); void receivePacket(Packet& pkt); private: // Connectivity void connect(RcpSrc& src, route_t& route); route_t* _route; RcpSrc* _src; // Mechanism void send_ack(); RcpAck::seq_t _cumulative_ack; // the packet we have cumulatively acked list<RcpAck::seq_t> _received; // list of packets above a hole, that we've received }; class RcpRtxTimerScanner : public EventSource { public: RcpRtxTimerScanner::RcpRtxTimerScanner(simtime_picosec scanPeriod, EventList& eventlist); void doNextEvent(); void registerRcp(RcpSrc &rcpsrc); private: simtime_picosec _scanPeriod; typedef list<RcpSrc*> rcps_t; rcps_t _rcps; }; #endif
[ "sdyy1990@gmail.com" ]
sdyy1990@gmail.com
dfc2457ca777ca78eca77efe41d509e79378cb51
a904c42a45b99c6de6c95cf52ba88001740765e4
/Sources/Maths/Visual/DriverSinwave.cpp
22bd4315cb8b37cbd430c5a84d3bad3b2b2f4ce3
[ "MIT" ]
permissive
lineCode/Acid
0cc31acf1060f0d55631b3cbe31e540e89a44a31
573ca8ea9191f62eaab8ef89c34bf15e70e0c1e4
refs/heads/master
2020-03-28T14:29:58.922933
2018-09-12T06:35:25
2018-09-12T06:35:25
null
0
0
null
null
null
null
UTF-8
C++
false
false
356
cpp
#include "DriverSinwave.hpp" namespace acid { DriverSinwave::DriverSinwave(const float &min, const float &max, const float &length) : IDriver(length), m_min(min), m_amplitude(max - min) { } float DriverSinwave::Calculate(const float &time) { float value = 0.5f + std::sin(2.0f * PI * time) * 0.5f; return m_min + value * m_amplitude; } }
[ "mattparks5855@gmail.com" ]
mattparks5855@gmail.com
3f6952e87996315fdd0a52a5ac5945977fcf7e85
1bbabc787f6353aff92a8386252055f24bebb7da
/Lecture.cpp
2707194e96c9066413f63a6cf0aa97f0f05160fb
[]
no_license
Sukarnapaul1893/Codeforces---Problems-Solved
5fde83464994f98a6aab6b07037f8a431105f004
b30cfa3f62cd616668a69a41f23ec402557e3646
refs/heads/master
2022-02-06T08:25:06.386688
2017-12-13T16:04:06
2017-12-13T16:04:06
114,139,699
0
0
null
null
null
null
UTF-8
C++
false
false
477
cpp
#include<iostream> #include<string.h> using namespace std; int main(){ int a,b,i,j,k; cin>>a; cin>>b; string s1[b]; string s2[b]; string s3[a]; for(i=0;i<b;i++){ cin>>s1[i]; cin>>s2[i]; } for(j=0;j<a;j++){ cin>>s3[j]; } for(j=0;j<a;j++){ for(k=0;k<b;k++){ if(s3[j]==s1[k]){ if(s1[k].length() <= s2[k].length()){ cout<<s1[k]<<" "; } else{ cout<<s2[k]<<" "; } } } } return 0; }
[ "noreply@github.com" ]
Sukarnapaul1893.noreply@github.com
dd545f02defc260c0984699e2ea0ed24a7d7b9a7
12d3908fc4a374e056041df306e383d95d8ff047
/Programs/prog18.cpp
4358fff151f3f9f7bfa8d3e05c54ddf03421d705
[ "MIT" ]
permissive
rux616/c201
aca5898c506aeb1792aa8b1f9dcf3d797a1cd888
d8509e8d49e52e7326486249ad8d567560bf4ad4
refs/heads/master
2021-01-01T16:14:44.747670
2017-07-20T05:14:24
2017-07-20T05:14:24
97,792,948
0
0
null
null
null
null
UTF-8
C++
false
false
1,991
cpp
/* Prog18.cpp This is a variation of prog17 that demonstrates some struct pointer syntax. ----------------------------------------------------------------------*/ #include <iostream> #include <string> using namespace std; void main (void) { struct StudentRecord { char Name[32]; long IDnumber; int NumberOfExams; int ExamScore[5]; }; StudentRecord Student; StudentRecord *Ptr; // A pointer to a StudentRecord struct strcpy (Student.Name, "John Smith"); Student.IDnumber = 1234321; Student.NumberOfExams = 0; cout << "Student.Name = " << Student.Name << endl; cout << "Student.IDnumber = " << Student.IDnumber << endl; cout << "Student.NumberOfExams = " << Student.NumberOfExams << "\n\n"; Ptr = &Student; cout << "(*Ptr).IDnumber = " << (*Ptr).IDnumber << endl; cout << " Ptr->IDnumber = " << Ptr->IDnumber << endl; } /*-------------------- Program Output ------------------------------ Student.Name = John Smith Student.IDnumber = 1234321 Student.NumberOfExams = 0 (*Ptr).IDnumber = 1234321 Ptr->IDnumber = 1234321 ===================== Program Comments =========================== 1) The assignment statement "Ptr = &Student;" assigns the address of the variable Student to the pointer variable Ptr, i.e. "points" Ptr at Student. 2) Since Ptr holds the address of Student, *Ptr is an alias (another name) for Student. To reference the fields of Student in this way, parentheses are needed around "*Ptr" since the "." operator has very high precedence. This means that the rather awkward reference "(*Ptr).IDnumber)" must be made to access the field IDnumber. Fortunately, C provides another notation that can be used with pointers to record structures. In the example above, "Ptr->IDnumber" is used. */
[ "dan.cassidy.1983@gmail.com" ]
dan.cassidy.1983@gmail.com
76b6f91e9e202c51a2401e040291496d6ae60a08
24acf54ec9b57c0450732a0051ea1e4ae91a7190
/Library/Platinum/ThirdParty/Neptune/Source/Data/TLS/Base/NptTlsTrustAnchor_Base_0012.cpp
56aa239b888ec40894ef73f2ee78baa7b4922a51
[ "LicenseRef-scancode-generic-cla" ]
no_license
shawnji2060/KEFWireless-DLNA
c12ac384bba4a80a43234c909cd6c791069ee3b8
98b6886f9ae54571cca66e32ecf1197533a5488b
refs/heads/master
2021-01-18T16:37:50.320261
2017-08-16T08:14:14
2017-08-16T08:14:14
100,464,539
0
1
null
null
null
null
UTF-8
C++
false
false
7,056
cpp
/***************************************************************** | | Neptune - Trust Anchors | | This file is automatically generated by a script, do not edit! | | Copyright (c) 2002-2010, Axiomatic Systems, LLC. | All rights reserved. | | Redistribution and use in source and binary forms, with or without | modification, are permitted provided that the following conditions are met: | * Redistributions of source code must retain the above copyright | notice, this list of conditions and the following disclaimer. | * Redistributions in binary form must reproduce the above copyright | notice, this list of conditions and the following disclaimer in the | documentation and/or other materials provided with the distribution. | * Neither the name of Axiomatic Systems 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 AXIOMATIC SYSTEMS ''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 AXIOMATIC SYSTEMS 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. | ****************************************************************/ #if defined(NPT_CONFIG_ENABLE_TLS) /* Digital Signature Trust Co. Global CA 4 */ const unsigned char NptTlsTrustAnchor_Base_0012_Data[988] = { 0x30,0x82,0x03,0xd8,0x30,0x82,0x02,0xc0 ,0x02,0x11,0x00,0xd0,0x1e,0x40,0x8b,0x00 ,0x00,0x77,0x6d,0x00,0x00,0x00,0x01,0x00 ,0x00,0x00,0x04,0x30,0x0d,0x06,0x09,0x2a ,0x86,0x48,0x86,0xf7,0x0d,0x01,0x01,0x05 ,0x05,0x00,0x30,0x81,0xa9,0x31,0x0b,0x30 ,0x09,0x06,0x03,0x55,0x04,0x06,0x13,0x02 ,0x75,0x73,0x31,0x0d,0x30,0x0b,0x06,0x03 ,0x55,0x04,0x08,0x13,0x04,0x55,0x74,0x61 ,0x68,0x31,0x17,0x30,0x15,0x06,0x03,0x55 ,0x04,0x07,0x13,0x0e,0x53,0x61,0x6c,0x74 ,0x20,0x4c,0x61,0x6b,0x65,0x20,0x43,0x69 ,0x74,0x79,0x31,0x24,0x30,0x22,0x06,0x03 ,0x55,0x04,0x0a,0x13,0x1b,0x44,0x69,0x67 ,0x69,0x74,0x61,0x6c,0x20,0x53,0x69,0x67 ,0x6e,0x61,0x74,0x75,0x72,0x65,0x20,0x54 ,0x72,0x75,0x73,0x74,0x20,0x43,0x6f,0x2e ,0x31,0x11,0x30,0x0f,0x06,0x03,0x55,0x04 ,0x0b,0x13,0x08,0x44,0x53,0x54,0x43,0x41 ,0x20,0x58,0x32,0x31,0x16,0x30,0x14,0x06 ,0x03,0x55,0x04,0x03,0x13,0x0d,0x44,0x53 ,0x54,0x20,0x52,0x6f,0x6f,0x74,0x43,0x41 ,0x20,0x58,0x32,0x31,0x21,0x30,0x1f,0x06 ,0x09,0x2a,0x86,0x48,0x86,0xf7,0x0d,0x01 ,0x09,0x01,0x16,0x12,0x63,0x61,0x40,0x64 ,0x69,0x67,0x73,0x69,0x67,0x74,0x72,0x75 ,0x73,0x74,0x2e,0x63,0x6f,0x6d,0x30,0x1e ,0x17,0x0d,0x39,0x38,0x31,0x31,0x33,0x30 ,0x32,0x32,0x34,0x36,0x31,0x36,0x5a,0x17 ,0x0d,0x30,0x38,0x31,0x31,0x32,0x37,0x32 ,0x32,0x34,0x36,0x31,0x36,0x5a,0x30,0x81 ,0xa9,0x31,0x0b,0x30,0x09,0x06,0x03,0x55 ,0x04,0x06,0x13,0x02,0x75,0x73,0x31,0x0d ,0x30,0x0b,0x06,0x03,0x55,0x04,0x08,0x13 ,0x04,0x55,0x74,0x61,0x68,0x31,0x17,0x30 ,0x15,0x06,0x03,0x55,0x04,0x07,0x13,0x0e ,0x53,0x61,0x6c,0x74,0x20,0x4c,0x61,0x6b ,0x65,0x20,0x43,0x69,0x74,0x79,0x31,0x24 ,0x30,0x22,0x06,0x03,0x55,0x04,0x0a,0x13 ,0x1b,0x44,0x69,0x67,0x69,0x74,0x61,0x6c ,0x20,0x53,0x69,0x67,0x6e,0x61,0x74,0x75 ,0x72,0x65,0x20,0x54,0x72,0x75,0x73,0x74 ,0x20,0x43,0x6f,0x2e,0x31,0x11,0x30,0x0f ,0x06,0x03,0x55,0x04,0x0b,0x13,0x08,0x44 ,0x53,0x54,0x43,0x41,0x20,0x58,0x32,0x31 ,0x16,0x30,0x14,0x06,0x03,0x55,0x04,0x03 ,0x13,0x0d,0x44,0x53,0x54,0x20,0x52,0x6f ,0x6f,0x74,0x43,0x41,0x20,0x58,0x32,0x31 ,0x21,0x30,0x1f,0x06,0x09,0x2a,0x86,0x48 ,0x86,0xf7,0x0d,0x01,0x09,0x01,0x16,0x12 ,0x63,0x61,0x40,0x64,0x69,0x67,0x73,0x69 ,0x67,0x74,0x72,0x75,0x73,0x74,0x2e,0x63 ,0x6f,0x6d,0x30,0x82,0x01,0x22,0x30,0x0d ,0x06,0x09,0x2a,0x86,0x48,0x86,0xf7,0x0d ,0x01,0x01,0x01,0x05,0x00,0x03,0x82,0x01 ,0x0f,0x00,0x30,0x82,0x01,0x0a,0x02,0x82 ,0x01,0x01,0x00,0xdc,0x75,0xf0,0x8c,0xc0 ,0x75,0x96,0x9a,0xc0,0x62,0x1f,0x26,0xf7 ,0xc4,0xe1,0x9a,0xea,0xe0,0x56,0x73,0x5b ,0x99,0xcd,0x01,0x44,0xa8,0x08,0xb6,0xd5 ,0xa7,0xda,0x1a,0x04,0x18,0x39,0x92,0x4a ,0x78,0xa3,0x81,0xc2,0xf5,0x77,0x7a,0x50 ,0xb4,0x70,0xff,0x9a,0xab,0xc6,0xc7,0xca ,0x6e,0x83,0x4f,0x42,0x98,0xfb,0x26,0x0b ,0xda,0xdc,0x6d,0xd6,0xa9,0x99,0x55,0x52 ,0x67,0xe9,0x28,0x03,0x92,0xdc,0xe5,0xb0 ,0x05,0x9a,0x0f,0x15,0xf9,0x6b,0x59,0x72 ,0x56,0xf2,0xfa,0x39,0xfc,0xaa,0x68,0xee ,0x0f,0x1f,0x10,0x83,0x2f,0xfc,0x9d,0xfa ,0x17,0x96,0xdd,0x82,0xe3,0xe6,0x45,0x7d ,0xc0,0x4b,0x80,0x44,0x1f,0xed,0x2c,0xe0 ,0x84,0xfd,0x91,0x5c,0x92,0x54,0x69,0x25 ,0xe5,0x62,0x69,0xdc,0xe5,0xee,0x00,0x52 ,0xbd,0x33,0x0b,0xad,0x75,0x02,0x85,0xa7 ,0x64,0x50,0x2d,0xc5,0x19,0x19,0x30,0xc0 ,0x26,0xdb,0xc9,0xd3,0xfd,0x2e,0x99,0xad ,0x59,0xb5,0x0b,0x4d,0xd4,0x41,0xae,0x85 ,0x48,0x43,0x59,0xdc,0xb7,0xa8,0xe2,0xa2 ,0xde,0xc3,0x8f,0xd7,0xb8,0xa1,0x62,0xa6 ,0x68,0x50,0x52,0xe4,0xcf,0x31,0xa7,0x94 ,0x85,0xda,0x9f,0x46,0x32,0x17,0x56,0xe5 ,0xf2,0xeb,0x66,0x3d,0x12,0xff,0x43,0xdb ,0x98,0xef,0x77,0xcf,0xcb,0x81,0x8d,0x34 ,0xb1,0xc6,0x50,0x4a,0x26,0xd1,0xe4,0x3e ,0x41,0x50,0xaf,0x6c,0xae,0x22,0x34,0x2e ,0xd5,0x6b,0x6e,0x83,0xba,0x79,0xb8,0x76 ,0x65,0x48,0xda,0x09,0x29,0x64,0x63,0x22 ,0xb9,0xfb,0x47,0x76,0x85,0x8c,0x86,0x44 ,0xcb,0x09,0xdb,0x02,0x03,0x01,0x00,0x01 ,0x30,0x0d,0x06,0x09,0x2a,0x86,0x48,0x86 ,0xf7,0x0d,0x01,0x01,0x05,0x05,0x00,0x03 ,0x82,0x01,0x01,0x00,0xb5,0x36,0x0e,0x5d ,0xe1,0x61,0x28,0x5a,0x11,0x65,0xc0,0x3f ,0x83,0x03,0x79,0x4d,0xbe,0x28,0xa6,0x0b ,0x07,0x02,0x52,0x85,0xcd,0xf8,0x91,0xd0 ,0x10,0x6c,0xb5,0x6a,0x20,0x5b,0x1c,0x90 ,0xd9,0x30,0x3c,0xc6,0x48,0x9e,0x8a,0x5e ,0x64,0xf9,0xa1,0x71,0x77,0xef,0x04,0x27 ,0x1f,0x07,0xeb,0xe4,0x26,0xf7,0x73,0x74 ,0xc9,0x44,0x18,0x1a,0x66,0xd3,0xe0,0x43 ,0xaf,0x91,0x3b,0xd1,0xcb,0x2c,0xd8,0x74 ,0x54,0x3a,0x1c,0x4d,0xca,0xd4,0x68,0xcd ,0x23,0x7c,0x1d,0x10,0x9e,0x45,0xe9,0xf6 ,0x00,0x6e,0xa6,0xcd,0x19,0xff,0x4f,0x2c ,0x29,0x8f,0x57,0x4d,0xc4,0x77,0x92,0xbe ,0xe0,0x4c,0x09,0xfb,0x5d,0x44,0x86,0x66 ,0x21,0xa8,0xb9,0x32,0xa2,0x56,0xd5,0xe9 ,0x8c,0x83,0x7c,0x59,0x3f,0xc4,0xf1,0x0b ,0xe7,0x9d,0xec,0x9e,0xbd,0x9c,0x18,0x0e ,0x3e,0xc2,0x39,0x79,0x28,0xb7,0x03,0x0d ,0x08,0xcb,0xc6,0xe7,0xd9,0x01,0x37,0x50 ,0x10,0xec,0xcc,0x61,0x16,0x40,0xd4,0xaf ,0x31,0x74,0x7b,0xfc,0x3f,0x31,0xa7,0xd0 ,0x47,0x73,0x33,0x39,0x1b,0xcc,0x4e,0x6a ,0xd7,0x49,0x83,0x11,0x06,0xfe,0xeb,0x82 ,0x58,0x33,0x32,0x4c,0xf0,0x56,0xac,0x1e ,0x9c,0x2f,0x56,0x9a,0x7b,0xc1,0x4a,0x1c ,0xa5,0xfd,0x55,0x36,0xce,0xfc,0x96,0x4d ,0xf4,0xb0,0xf0,0xec,0xb7,0x6c,0x82,0xed ,0x2f,0x31,0x99,0x42,0x4c,0xa9,0xb2,0x0d ,0xb8,0x15,0x5d,0xf1,0xdf,0xba,0xc9,0xb5 ,0x4a,0xd4,0x64,0x98,0xb3,0x26,0xa9,0x30 ,0xc8,0xfd,0xa6,0xec,0xab,0x96,0x21,0xad ,0x7f,0xc2,0x78,0xb6}; const unsigned int NptTlsTrustAnchor_Base_0012_Size = 988; #endif
[ "shawnji2060@gmail.com" ]
shawnji2060@gmail.com
21bc86e731c4fd214730de842586689cbb419144
4e8fb3672f0c561bf85bd8230c5492e4457f33d1
/dev/include/core/PostEffect_GaussianBlur.h
a5769a04b678da8956ee6d478ebfc6ce5676d0c1
[]
no_license
lythm/ld3d
877abefefcea9b39734857714fe1974a8320fe6c
91de1cca7cca77c1f8eae8e8a9423abc34f9b38f
refs/heads/master
2020-12-24T15:23:29.766231
2014-07-11T04:42:49
2014-07-11T04:42:49
null
0
0
null
null
null
null
UTF-8
C++
false
false
591
h
#pragma once #include "core/PostEffect.h" namespace ld3d { class _DLL_CLASS PostEffect_GaussianBlur : public PostEffect { public: PostEffect_GaussianBlur(void); virtual ~PostEffect_GaussianBlur(void); bool Initialize(RenderManagerPtr pRenderManager); void Render(RenderManagerPtr pRenderer, RenderTexturePtr pInput, RenderTexturePtr pOutput); void Release(); private: MaterialPtr m_pMaterial; RenderManagerPtr m_pRenderManager; MaterialParameterPtr m_pParamInputTex; MaterialParameterPtr m_pParamInputSize; }; }
[ "lythm780522@gmail.com" ]
lythm780522@gmail.com
fdee6265ba93e9aec0bb2a1e5dec08f513608f2e
69304e6e01ae66df5cec81ece86c44a9c7c53aba
/widget.h
16f294a799dc6a9f924e068236232a4e958070ae
[]
no_license
Lwxiang/MyTrip
55acd5cda63c4b61b3ecab2eaabbe68f7a4109fa
a11dcfa1f020ed9889258234f050c01f53569923
refs/heads/master
2021-01-10T16:58:10.671888
2016-02-29T05:50:35
2016-02-29T05:50:35
52,767,269
0
0
null
null
null
null
UTF-8
C++
false
false
846
h
#ifndef WIDGET_H #define WIDGET_H #include "titlebar.h" #include "toolbar.h" #include "statubar.h" #include "contentwidget.h" #include <QWidget> #include <QRect> #include <QBitmap> #include <QPainter> #include <QFrame> #include <QLabel> #include <QPoint> #include <QMouseEvent> #include <QPushButton> #include <QToolButton> #include <QVBoxLayout> #include <QHBoxLayout> namespace Ui { class Widget; } class Widget : public QFrame { Q_OBJECT public: explicit Widget(QFrame *parent = 0); TitleBar *titlebar; ToolBar *toolbar; ContentWidget *contentwidget; StatuBar *statubar; ~Widget(); protected: void mousePressEvent(QMouseEvent *); void mouseMoveEvent(QMouseEvent *); void mouseReleaseEvent(QMouseEvent *); private: QPoint oldPos; bool mouseDown; Ui::Widget *ui; }; #endif // WIDGET_H
[ "XUN Lwxiang" ]
XUN Lwxiang
64ee64c7c84f209d271be303584ac184cd24faea
ba9322f7db02d797f6984298d892f74768193dcf
/ccc/src/model/GetJobStatusByCallIdRequest.cc
d4d551444671d8680d407ca30da4de44aa90a7d2
[ "Apache-2.0" ]
permissive
sdk-team/aliyun-openapi-cpp-sdk
e27f91996b3bad9226c86f74475b5a1a91806861
a27fc0000a2b061cd10df09cbe4fff9db4a7c707
refs/heads/master
2022-08-21T18:25:53.080066
2022-07-25T10:01:05
2022-07-25T10:01:05
183,356,893
3
0
null
2019-04-25T04:34:29
2019-04-25T04:34:28
null
UTF-8
C++
false
false
1,418
cc
/* * Copyright 2009-2017 Alibaba Cloud All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <alibabacloud/ccc/model/GetJobStatusByCallIdRequest.h> using AlibabaCloud::CCC::Model::GetJobStatusByCallIdRequest; GetJobStatusByCallIdRequest::GetJobStatusByCallIdRequest() : RpcServiceRequest("ccc", "2017-07-05", "GetJobStatusByCallId") {} GetJobStatusByCallIdRequest::~GetJobStatusByCallIdRequest() {} std::string GetJobStatusByCallIdRequest::getCallId()const { return callId_; } void GetJobStatusByCallIdRequest::setCallId(const std::string& callId) { callId_ = callId; setParameter("CallId", callId); } std::string GetJobStatusByCallIdRequest::getInstanceId()const { return instanceId_; } void GetJobStatusByCallIdRequest::setInstanceId(const std::string& instanceId) { instanceId_ = instanceId; setParameter("InstanceId", instanceId); }
[ "yixiong.jxy@alibaba-inc.com" ]
yixiong.jxy@alibaba-inc.com
a0e13fc1f3440a1af96eba344ae7d4744b1b5418
af009200519ba7d572acf07b9a4fc90e03aceb1f
/src/lassen/Input.hh
e18b0caeac758175723ea6c37a9f1970438aa8df
[ "LicenseRef-scancode-public-domain" ]
permissive
OpenSpeedShop/openspeedshop-test-suite
1d2c050c66f839d25e350a9edddeff4ada47d722
02df4abf2c164722170de9961b8764b8d2b2611f
refs/heads/master
2021-05-01T20:34:12.215991
2020-08-24T18:20:37
2020-08-24T18:20:37
57,010,138
1
0
null
null
null
null
UTF-8
C++
false
false
1,159
hh
#ifndef INPUT_H #define INPUT_H #include "Lassen.hh" namespace Lassen { class MeshConstructor { public: static void MakeRegularMesh( Mesh * mesh, int ndim, int *numGlobal, // total number of zones in each dimension int *globalStart, // global start index in each dimension int *numZones, // number of zone to create in each dimension Real *zoneSize); // size of each zone in each dimension // Create a single domain, which is part of a larger mesh static void MakeRegularDomain( Domain *domain, int ndim, int domainId, // domainID of the domain to create int *numDomain, // number of domains in each dimension int *numGlobalZones, // number of global zones in each dimension Real *zoneSize); // size of each zone in each dimension }; }; #endif
[ "jeg@krellinst.org" ]
jeg@krellinst.org
fdc5500c87d13f8d60be9b26ca89150695bd8845
fba0dfdd038e38d0539910ca869052b6559d2496
/DX11RenderApp/DX11RenderApp/Vertex.cpp
b432c5ee40c1bdee9f077259ed79f94818ec25d9
[]
no_license
shankkkyyy/GFXPROJECT
9c1d82702a9bc3a84a1efbf2e1b21054880696b8
4f537bb7c8d8bde99abcb6088e4a07ed5641b778
refs/heads/master
2021-07-01T16:30:10.020322
2017-09-22T02:01:44
2017-09-22T02:01:44
99,033,428
0
0
null
null
null
null
UTF-8
C++
false
false
2,415
cpp
#include "Vertex.h" const D3D11_INPUT_ELEMENT_DESC InputLayoutDesc::IDPosSize[2] = { { "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 }, { "SIZE", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 12, D3D11_INPUT_PER_VERTEX_DATA, 0 } }; const D3D11_INPUT_ELEMENT_DESC InputLayoutDesc::IDPos[1] = { { "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 } }; const D3D11_INPUT_ELEMENT_DESC InputLayoutDesc::IDPosNor[2] = { { "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 }, { "NORMAL", 0, DXGI_FORMAT_R32G32B32_FLOAT , 0, 12, D3D11_INPUT_PER_VERTEX_DATA, 0 } }; const D3D11_INPUT_ELEMENT_DESC InputLayoutDesc::IDBasic32[3] = { {"POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT , 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0}, {"NORMAL" , 0, DXGI_FORMAT_R32G32B32_FLOAT , 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0}, {"UV" , 0, DXGI_FORMAT_R32G32_FLOAT , 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0} }; const D3D11_INPUT_ELEMENT_DESC InputLayoutDesc::IDBasic32Inst[7] = { { "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT , 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 }, { "NORMAL" , 0, DXGI_FORMAT_R32G32B32_FLOAT , 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 }, { "UV" , 0, DXGI_FORMAT_R32G32_FLOAT , 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 }, { "WORLD", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 1, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_INSTANCE_DATA, 1 }, { "WORLD", 1, DXGI_FORMAT_R32G32B32A32_FLOAT, 1, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_INSTANCE_DATA, 1 }, { "WORLD", 2, DXGI_FORMAT_R32G32B32A32_FLOAT, 1, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_INSTANCE_DATA, 1 }, { "WORLD", 3, DXGI_FORMAT_R32G32B32A32_FLOAT, 1, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_INSTANCE_DATA, 1 } }; const D3D11_INPUT_ELEMENT_DESC InputLayoutDesc::IDTerrian[2] = { { "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT , 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 }, { "UV" , 0, DXGI_FORMAT_R32G32_FLOAT , 0, D3D11_APPEND_ALIGNED_ELEMENT, D3D11_INPUT_PER_VERTEX_DATA, 0 } }; Vertex & Vertex::operator=(const Vertex & _other) { // TODO: insert return statement here pos = _other.pos; nor = _other.nor; uv = _other.uv; return *this; }
[ "dushiweic2@hotmail.com" ]
dushiweic2@hotmail.com
dbb853a7b1d52cb9bc73dbffd74ec3a21b941d5a
3e4fd5153015d03f147e0f105db08e4cf6589d36
/Cpp/SDK/io_intro_wall_blacksmith_01_bp_classes.h
797e2a16a504acc64ba736001d5b36af0580526a
[]
no_license
zH4x-SDK/zTorchlight3-SDK
a96f50b84e6b59ccc351634c5cea48caa0d74075
24135ee60874de5fd3f412e60ddc9018de32a95c
refs/heads/main
2023-07-20T12:17:14.732705
2021-08-27T13:59:21
2021-08-27T13:59:21
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,613
h
#pragma once // Name: Torchlight3, Version: 1.0.0 /*!!DEFINE!!*/ /*!!HELPER_DEF!!*/ /*!!HELPER_INC!!*/ #ifdef _MSC_VER #pragma pack(push, 0x01) #endif namespace CG { //--------------------------------------------------------------------------- // Classes //--------------------------------------------------------------------------- // BlueprintGeneratedClass io_intro_wall_blacksmith_01_bp.io_intro_wall_blacksmith_01_bp_C // 0x0018 (FullSize[0x0280] - InheritedSize[0x0268]) class Aio_intro_wall_blacksmith_01_bp_C : public ABaseStaticObject_C { public: class UBoxComponent* Box2; // 0x0268(0x0008) (BlueprintVisible, ZeroConstructor, InstancedReference, IsPlainOldData, NonTransactional, NoDestructor, UObjectWrapper, HasGetValueTypeHash) class UBoxComponent* Box1; // 0x0270(0x0008) (BlueprintVisible, ZeroConstructor, InstancedReference, IsPlainOldData, NonTransactional, NoDestructor, UObjectWrapper, HasGetValueTypeHash) class UBoxComponent* Box; // 0x0278(0x0008) (BlueprintVisible, ZeroConstructor, InstancedReference, IsPlainOldData, NonTransactional, NoDestructor, UObjectWrapper, HasGetValueTypeHash) static UClass* StaticClass() { static auto ptr = UObject::FindClass("BlueprintGeneratedClass io_intro_wall_blacksmith_01_bp.io_intro_wall_blacksmith_01_bp_C"); return ptr; } }; } #ifdef _MSC_VER #pragma pack(pop) #endif
[ "zp2kshield@gmail.com" ]
zp2kshield@gmail.com
de2bd2cbf33c6efe91c3f714de15a82e63a7c231
b3be27b4bf494270c5c953cf711088a10f79de81
/src/catalog/plx/unicode/utf16_from_utf8.h
65dd0c243257578e7faf7d3d53be2bde10422e74
[]
no_license
cpizano/Plex
2973b606933eb14198e337eeb45e725201799e7a
b5ab6224ddb1a1ca0aa59b6f585ec601c913cb15
refs/heads/master
2016-09-05T18:42:34.431460
2016-01-03T21:56:09
2016-01-03T21:56:09
6,571,011
0
0
null
null
null
null
UTF-8
C++
false
false
935
h
//#~def plx::UTF16FromUTF8 /////////////////////////////////////////////////////////////////////////////// // plx::UTF16FromUTF8 namespace plx { std::wstring UTF16FromUTF8(const plx::Range<const uint8_t>& utf8, bool strict) { if (utf8.empty()) return std::wstring(); // Get length and validate string. const int utf16_len = ::MultiByteToWideChar( CP_UTF8, strict ? MB_ERR_INVALID_CHARS : 0, reinterpret_cast<const char*>(utf8.start()), plx::To<int>(utf8.size()), NULL, 0); if (utf16_len == 0) { throw plx::CodecException(__LINE__, nullptr); } std::wstring utf16; utf16.resize(utf16_len); // Now do the conversion without validation. if (!::MultiByteToWideChar( CP_UTF8, 0, reinterpret_cast<const char*>(utf8.start()), plx::To<int>(utf8.size()), &utf16[0], utf16_len)) { throw plx::CodecException(__LINE__, nullptr); } return utf16; } }
[ "cpu@chromium.org" ]
cpu@chromium.org
9b37404d4e67f28f37600f501272933fd8b24bce
a71b70de1877959b73f7e78ee62e9138ec5a2585
/PKU/2400-2499/P2480.cpp
f0fa36690eb374f3e49966f76b425baac6e71551
[]
no_license
HJWAJ/acm_codes
38d32c6d12837b07584198c40ce916546085f636
5fa3ee82cb5114eb3cfe4e6fa2baba0f476f6434
refs/heads/master
2022-01-24T03:00:51.737372
2022-01-14T10:04:05
2022-01-14T10:04:05
151,313,977
0
0
null
null
null
null
UTF-8
C++
false
false
2,154
cpp
#include <cstdlib> #include <cctype> #include <cstring> #include <cstdio> #include <cmath> #include <algorithm> #include <vector> #include <string> #include <iostream> #include <sstream> #include <map> #include <set> #include <queue> #include <stack> #include <fstream> #include <numeric> #include <iomanip> #include <bitset> #include <list> #include <stdexcept> #include <functional> #include <utility> #include <ctime> #include <memory.h> using namespace std; __int64 divi[100005]; __int64 prime[50000]; bool bo[50001]; __int64 p[100005],a[100005]; int prime_table() { int i,j,flag=0; memset(bo,0,sizeof(bo)); bo[0]=bo[1]=1; for(i=2;i<=50000;i++) if(!bo[i]) { prime[flag++]=i; j=i+i; for(;j<=50000;j+=i)bo[j]=1; } return flag; } int divided(__int64 n,__int64 p[],__int64 a[]) { __int64 sq=(__int64)(sqrt(double(n))); int flag=0,num=0; while(1) { if(n==1)break; if(prime[flag]>sq) { p[num]=n; a[num++]=1; break; } if(n%prime[flag]!=0) { flag++; continue; } p[num]=prime[flag]; a[num++]=1; n/=prime[flag]; while(n%prime[flag]==0) { n/=prime[flag]; a[num-1]++; } flag++; } return num; } __int64 divide(__int64 n) { __int64 i,flag=0; for(i=1;i*i<n;i++) { if(n%i==0) { divi[flag++]=i; divi[flag++]=n/i; } } if(i*i==n)divi[flag++]=i; return flag; } __int64 eular(__int64 n) { if(n==1)return 1; int flag=divided(n,p,a),i; //for(i=0;i<flag;i++)cout<<p[i]<<' '<<a[i]<<endl; for(i=0;i<flag;i++) { n/=p[i]; n*=(p[i]-1); } return n; } int main() { __int64 n,ans,flag,i; prime_table(); while(scanf("%I64d",&n)!=EOF) { flag=divide(n); ans=0; for(i=0;i<flag;i++) { //cout<<divi[i]<<endl; ans+=divi[i]*eular(n/divi[i]); } printf("%I64d\n",ans); } return 0; }
[ "jiawei.hua@dianping.com" ]
jiawei.hua@dianping.com
ff7180be40da434378ae43575c243b24b9546ffc
03c42ab1f77bf7371869c7ee34d3551b6f13a0ef
/tlm_vppnoc_lib/vpp_noc_core_v1.0/protocol_data_unit/vppnoc_pdu.h
8e4ba26a5c528195ccc5da9517fc0b94787d5d24
[]
no_license
Hosseinabady/norc
4c654c40012a60d74777d349d20dfb79445e7fb3
c0aa6d77c60b1b88c4ba3526e3e4246c7da6fb00
refs/heads/master
2021-01-13T13:39:13.715637
2016-12-14T01:41:29
2016-12-14T01:41:29
76,404,087
0
0
null
null
null
null
UTF-8
C++
false
false
2,391
h
#ifndef NOC_GENERIC_PAYLOAD_ #define NOC_GENERIC_PAYLOAD_ #include <systemc> #include "protocol_data_unit/vppnoc_pdu_base.h" namespace vppnoc { template <typename HEADER, typename BODY = bool, int size = 10> class vppnoc_pdu : public vppnoc_pdu_base { public: vppnoc_pdu(): vppnoc_pdu_base(), stream_tail(0), stream_head(0) { } friend vppnoc_pdu<HEADER, BODY, size>& operator<< (vppnoc_pdu& left, const vppnoc_pdu& right); friend vppnoc_pdu<HEADER, BODY, size>& operator>> (vppnoc_pdu& left, const vppnoc_pdu& right); public: enum {pci_size = sizeof(HEADER)}; enum {sdu_size = size * sizeof(BODY)}; enum {pdu_size = sizeof(HEADER) + size * sizeof(BODY)}; void reset() { stream_tail = 0; stream_head = 0; } union { struct { HEADER hdr; BODY body[size]; } pdu; bool stream[pdu_size]; } view_as; unsigned int stream_tail; unsigned int stream_head; }; template <typename HEADER, typename BODY, int size, typename HEADER2, typename BODY2, int size2> vppnoc_pdu<HEADER, BODY, size>& operator<< (vppnoc_pdu<HEADER, BODY, size>& left,const vppnoc_pdu<HEADER2, BODY2, size2>& right) { unsigned int free_space = left.pdu_size - left.stream_head; unsigned int fill_capacity = right.sdu_size; unsigned int nbytes = free_space > fill_capacity ? fill_capacity : free_space; memcpy(&(left.view_as.stream[left.stream_head]), (char*)(right.view_as.pdu.body), nbytes); left.stream_head += nbytes; if (left.stream_head == left.pdu_size) { left.stream_head = 0; vppnoc_pdu<HEADER, BODY, size>* tmp = 0; return *tmp; } else { return left; } } template <typename HEADER, typename BODY, int size, typename HEADER2, typename BODY2, int size2> vppnoc_pdu<HEADER, BODY, size>& operator>> (vppnoc_pdu<HEADER, BODY, size>& left,const vppnoc_pdu<HEADER2, BODY2, size2>& right) { unsigned int free_space = right.sdu_size; unsigned int fill_capacity = left.pdu_size - left.stream_tail; unsigned int nbytes = ((free_space > fill_capacity) ? fill_capacity : free_space); memcpy((char*)(right.view_as.pdu.body),&(left.view_as.stream[left.stream_tail]),nbytes); left.stream_tail += nbytes; if (left.stream_tail == left.pdu_size) { left.stream_tail = -1; vppnoc_pdu<HEADER, BODY, size>* tmp = 0; return *tmp; } else { return left; } } } #endif /*NOC_GENERIC_PAYLOAD_*/
[ "mohamamd@hosseinabady.com" ]
mohamamd@hosseinabady.com
b4c5fffc627e73f3115b63c4b310e5799138cf08
a3fb0091facc6f33be957eba61d7281737aa258e
/ATMView/ATMView/Business/CameraReader.cpp
feae74b7ce8f8a93f6522a569b0e9b1e8a3b10a8
[]
no_license
barry-ran/AEyeAboutPro
b5c7b46c8145423d7456e1ef6d40d82c54ba2faf
830de73c48af1cd1a2d72ff6485e31f7b7d52d45
refs/heads/master
2022-01-18T03:01:44.502618
2019-09-02T03:52:27
2019-09-02T03:52:27
null
0
0
null
null
null
null
GB18030
C++
false
false
3,801
cpp
/*********************************************************************************** * CameraReader.cpp * * Copyright(C): 智慧眼科技股份有限公司 * * Author: YCL * * Date: 2019-06 * * Description: 用于摄像头初始化、打开、设置、采集 ***********************************************************************************/ #include "CameraReader.h" #include "GlogManager.h" #include "ThreadManager.h" CameraReader* CameraReader::m_pInstance = NULL; CameraReader::CameraReader(QObject *parent) : QObject(parent) { moveToThread(ThreadManager::getAgentThread()); ThreadManager::getAgentThread()->start(); } CameraReader::~CameraReader() { } CameraReader* CameraReader::instance() { if (m_pInstance == NULL) { m_pInstance = new CameraReader; } return m_pInstance; } void _stdcall CameraReader::faceCallback( int msgType, const char* msg, void* userData ) { CameraReader* pThis = (CameraReader*)userData; CameraData cameraData; QString msgData = QString::fromLocal8Bit(msg); ParserMsg(msgData, cameraData); switch (msgType) { case STATUS_CHANGED: pThis->emit onMsgReceived(cameraData.subId, cameraData.desMsg); break; case COLLECT_FINISHED: if (cameraData.subId == 0) { pThis->emit onCollectFinished(cameraData); } else { pThis->emit onMsgReceived(cameraData.subId, cameraData.desMsg); } break; } } bool CameraReader::InitSDK(WId winId) { //初始化 int ret = AEFaceColl_Init(&m_collHandle); if (ret != 0) { LOG(INFO)<<"初始化相机SDK失败!!!"; return false; } LOG(INFO)<<"初始化相机SDK成功!!!"; //设置回调 AEFaceColl_SetCallback(m_collHandle, faceCallback, this); //设置预览窗口 AEFaceColl_SetPreviewWindow(m_collHandle, (void*)winId); //设置参数 char params[] = "{\"scenario\":10, \"capture.imageNumber\":1, \"capture.timeout\":30}"; AEFaceColl_SetParameters(m_collHandle, params); return true; } bool CameraReader::openCamera() { if (openCameraModule(0)) { openCameraModule(1); return true; } return false; } bool CameraReader::openCameraModule( int cameraType ) { QString cameraText = (cameraType == 0) ? QStringLiteral("可见光") : QStringLiteral("近红外"); int ret = AEFaceColl_OpenCamera(m_collHandle, cameraType); if (ret != 0) { LOG(INFO)<<"打开"<<cameraText.toLocal8Bit().data()<<"相机失败!!!"; return false; } LOG(INFO)<<"打开"<<cameraText.toLocal8Bit().data()<<"相机成功!!!"; return true; } void CameraReader::closeCamera() { int ret = AEFaceColl_CloseCamera(m_collHandle); if (ret != 0) { emit onMsgReceived(-1, QStringLiteral("关闭摄像头失败")); return; } } void CameraReader::startCollect() { int ret = AEFaceColl_StartCollect(m_collHandle); if (ret != 0) { emit onMsgReceived(-1, QStringLiteral("图像采集失败")); return; } } void CameraReader::ParserMsg( QString msgJson, CameraData& cameraData ) { QScriptEngine engine; QScriptValue sc = engine.evaluate("value=" + msgJson); cameraData.subId = sc.property("subId").toInt32(); cameraData.desMsg = sc.property("description").toString(); if (sc.property("visImageDatas").isArray()) { QScriptValueIterator it(sc.property("visImageDatas")); while (it.hasNext()) { it.next(); CameraData::ImageData imageData; imageData.imageData = it.value().property("image").toString(); QFile file("d:\\test.jpeg"); file.open(QIODevice::ReadWrite | QIODevice::Append); file.write(imageData.imageData.toLocal8Bit(), imageData.imageData.length()); file.waitForBytesWritten(3000); file.flush(); file.close(); if (imageData.imageData.isEmpty()) { continue; } imageData.faceRect = it.value().property("faceRect").toString(); cameraData.imageInfoData.append(imageData); } } }
[ "ycldream815@gmail.com" ]
ycldream815@gmail.com
961d2a9d6be822239d0e465931331522e4598690
cc47ba1d94ea53c8afb944d280bdf1e6197f8e3d
/C++/CodeForces/CR694A.cpp
f9444cd8fef37d24cf804a285014e3456aa5eae0
[]
no_license
Pranshu-Tripathi/Programming
60180f9b0c5f879b2a8bf85c3db14afe1fdb45ba
ae7234b293b307a0f38af6f5a7894747f22c5d45
refs/heads/master
2023-06-26T08:17:07.184679
2021-07-28T02:52:43
2021-07-28T02:52:43
226,936,580
0
0
null
null
null
null
UTF-8
C++
false
false
605
cpp
#include<bits/stdc++.h> using namespace std; #define ll long long void _run() { ll n,x; cin >> n >> x; ll arr[n]; ll s1 = 0, s2 = 0; for(int i =0 ; i < n ; i++) { cin >> arr[i]; s1 += arr[i] / x; if(arr[i] % x) { s1 ++; } s2 += arr[i]; } ll ans=0; if(s2%x) { ans++; } s2 = s2/x; s2 += ans; cout<<s2<<" "<<s1<<endl; return; } int main() { ios::sync_with_stdio(false); cin.tie(NULL); int test; cin >> test; while(test--) _run(); return 0; }
[ "mtpranshu2001@gmail.com" ]
mtpranshu2001@gmail.com
02a951e53ee244aff6ebf0b4797f409435be68c6
6375d90b2a0211053b93e7c65b3b4e67037e74c5
/bookmanager/bookmanager-tests/01_dbConnectTest.cpp
b3dbcb60c69c82068efad9c248dc322d5c215e90
[]
no_license
df-wilson/book-manager-cpp
86fc0c1d45ccf01ae6bd768828da3e58cff80d42
f255b56bdd6cdec7caee7c02d3f8ce1933362a2e
refs/heads/master
2021-01-19T10:36:45.023083
2020-02-08T20:38:35
2020-02-08T20:38:35
87,882,611
0
0
null
null
null
null
UTF-8
C++
false
false
2,260
cpp
#include "catch.hpp" #include "dbConnect.h" #include <SQLiteCpp/SQLiteCpp.h> #include <iostream> #include <string> using namespace dw; using namespace std; TEST_CASE("dbConnect - Test getting initial connection.") { SQLite::Database* connection = db_getConnection(); REQUIRE(connection->getFilename() == "/home/dean/Programming/Cpp/web/Projects/build/bookmanager/bookmanager-tests/db.sqlite"); REQUIRE(db_numAvailableConnections() == 0); REQUIRE(connection->tableExists("books")); SQLite::Statement* query = new SQLite::Statement(*connection, "SELECT * FROM books WHERE user_id = :userId"); query->bind(":userId", 1); //while (query->executeStep()) //{ // std::cout << query->getColumn(1) << std::endl; // std::cout << query->getColumn(2) << std::endl; // std::cout << query->getColumn(3) << std::endl; //} query->executeStep(); REQUIRE(query->getColumn(0).getInt() == 1); REQUIRE(query->getColumn(1).getInt() == 1); REQUIRE(query->getColumn(2).getString() == "Sorcerer's Daughter"); REQUIRE(query->getColumn(3).getString() == "Terry Brooks"); delete query; REQUIRE(db_numAvailableConnections() == 0); db_returnConnection(connection); REQUIRE(db_numAvailableConnections() == 1); db_shutdown(); REQUIRE(db_numAvailableConnections() == 0); } TEST_CASE("dbConnect - Test reusing connection") { SQLite::Database* connection = db_getConnection(); REQUIRE(connection != nullptr); REQUIRE(connection->getFilename() == "/home/dean/Programming/Cpp/web/Projects/build/bookmanager/bookmanager-tests/db.sqlite"); REQUIRE(connection->tableExists("books")); REQUIRE(db_numAvailableConnections() == 0); db_returnConnection(connection); REQUIRE(db_numAvailableConnections() == 1); SQLite::Database* connection2 = db_getConnection(); REQUIRE(db_numAvailableConnections() == 0); REQUIRE(connection != nullptr); REQUIRE(connection->getFilename() == "/home/dean/Programming/Cpp/web/Projects/build/bookmanager/bookmanager-tests/db.sqlite"); REQUIRE(connection->tableExists("books")); db_returnConnection(connection2); REQUIRE(db_numAvailableConnections() == 1); db_shutdown(); REQUIRE(db_numAvailableConnections() == 0); }
[ "deanwilsonbc@gmail.com" ]
deanwilsonbc@gmail.com
485d3f688c1f241e5b724d4749d9be4789902d41
f712d2e44d1de06496d23b69e3a9bd53d46f794a
/net-p2p/dnotes/files/patch-src__net.cpp
9d3d551f526551595cca8fd70a2b11267d5c642d
[ "BSD-2-Clause" ]
permissive
tuaris/FreeBSD-Coin-Ports
931da8f274b3f229efb6a79b4f34ffb2036d4786
330d9f5a10cf7dc1cddc3566b897bd4e6e265d9f
refs/heads/master
2021-06-18T20:21:05.001837
2021-01-20T21:26:44
2021-01-20T21:26:44
21,374,280
4
6
BSD-2-Clause
2018-01-26T09:22:30
2014-07-01T03:40:30
Makefile
UTF-8
C++
false
false
379
cpp
--- src/net.cpp.orig 2014-08-31 15:33:55 UTC +++ src/net.cpp @@ -58,7 +58,7 @@ static bool vfReachable[NET_MAX] = {}; static bool vfLimited[NET_MAX] = {}; static CNode* pnodeLocalHost = NULL; uint64 nLocalHostNonce = 0; -array<int, THREAD_MAX> vnThreadsRunning; +boost::array<int, THREAD_MAX> vnThreadsRunning; static std::vector<SOCKET> vhListenSocket; CAddrMan addrman;
[ "daniel@morante.net" ]
daniel@morante.net
f74d082cf319a429b6adbcc470737b197634733c
4b590410d4042c156cfd3d4e874f3a329390a72b
/src/uscxml/messages/MMIMessages.cpp
35e8b66a66fbd995383e58498ac34996a1ad0751
[ "BSD-2-Clause" ]
permissive
su6838354/uscxml
37b93aef528996d2dd66d348f9e1f31b6734ab57
81aa1c79dd158aa7bc76876552e4b1d05ecea656
refs/heads/master
2020-04-06T05:29:54.201412
2015-04-02T11:44:48
2015-04-02T11:44:48
38,090,859
1
0
null
2015-06-26T04:37:32
2015-06-26T04:37:32
null
UTF-8
C++
false
false
18,827
cpp
/** * @file * @author 2012-2013 Stefan Radomski (stefan.radomski@cs.tu-darmstadt.de) * @copyright Simplified BSD * * @cond * This program is free software: you can redistribute it and/or modify * it under the terms of the FreeBSD license as published by the FreeBSD * project. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * * You should have received a copy of the FreeBSD license along with this * program. If not, see <http://www.opensource.org/licenses/bsd-license>. * @endcond */ #include <string> // MSVC will croak with operator+ on strings if this is not first #include "MMIMessages.h" #include <DOM/Simple/DOMImplementation.hpp> #include <DOM/io/Stream.hpp> #include <DOM/SAX2DOM/SAX2DOM.hpp> #include <SAX/helpers/InputSourceResolver.hpp> #include <uscxml/DOMUtils.h> #include <boost/algorithm/string.hpp> #define TO_EVENT_OPERATOR(type, name, base)\ type::operator Event() const { \ Event ev = base::operator Event();\ ev.setName(name);\ if (representation == MMI_AS_XML) \ ev.setDOM(toXML());\ return ev;\ } #define FIND_MSG_ELEM(elem, doc) \ Element<std::string> elem; \ if (encapsulateInMMI) { \ elem = Element<std::string>(doc.getDocumentElement().getFirstChild()); \ } else { \ elem = Element<std::string>(doc.getDocumentElement()); \ } #define FROM_XML(clazz, enumType, base) \ clazz clazz::fromXML(Arabica::DOM::Node<std::string> node, InterpreterImpl* interpreter) { \ clazz event = base::fromXML(node, interpreter); \ event.type = enumType; \ return event; \ } #define STRING_ATTR_OR_EXPR(element, name)\ (element.hasAttributeNS(nameSpace, "name##Expr") && interpreter ? \ interpreter->getDataModel().evalAsString(element.getAttributeNS(nameSpace, "name##Expr")) : \ (element.hasAttributeNS(nameSpace, #name) ? element.getAttributeNS(nameSpace, #name) : "") \ ) #define FIND_EVENT_NODE(node)\ if (node.getNodeType() == Node_base::DOCUMENT_NODE) \ node = node.getFirstChild(); \ while (node) {\ if (node.getNodeType() == Node_base::ELEMENT_NODE) {\ if (boost::iequals(node.getLocalName(), "MMI")) {\ node = node.getFirstChild();\ continue;\ } else {\ break;\ }\ }\ node = node.getNextSibling();\ }\ namespace uscxml { using namespace Arabica::DOM; std::string MMIEvent::nameSpace = "http://www.w3.org/2008/04/mmi-arch"; MMIEvent::Type MMIEvent::getType(Arabica::DOM::Node<std::string> node) { if (!node || node.getNodeType() != Arabica::DOM::Node_base::ELEMENT_NODE) return INVALID; // MMI container? if (boost::iequals(node.getLocalName(), "MMI")) { node = node.getFirstChild(); if (!node) return INVALID; while(node.getNodeType() != Arabica::DOM::Node_base::ELEMENT_NODE) { node = node.getNextSibling(); if (!node) return INVALID; } } if (boost::iequals(node.getLocalName(), "NEWCONTEXTREQUEST")) return NEWCONTEXTREQUEST; if (boost::iequals(node.getLocalName(), "NEWCONTEXTRESPONSE")) return NEWCONTEXTRESPONSE; if (boost::iequals(node.getLocalName(), "PREPAREREQUEST")) return PREPAREREQUEST; if (boost::iequals(node.getLocalName(), "PREPARERESPONSE")) return PREPARERESPONSE; if (boost::iequals(node.getLocalName(), "STARTREQUEST")) return STARTREQUEST; if (boost::iequals(node.getLocalName(), "STARTRESPONSE")) return STARTRESPONSE; if (boost::iequals(node.getLocalName(), "DONENOTIFICATION")) return DONENOTIFICATION; if (boost::iequals(node.getLocalName(), "CANCELREQUEST")) return CANCELREQUEST; if (boost::iequals(node.getLocalName(), "CANCELRESPONSE")) return CANCELRESPONSE; if (boost::iequals(node.getLocalName(), "PAUSEREQUEST")) return PAUSEREQUEST; if (boost::iequals(node.getLocalName(), "PAUSERESPONSE")) return PAUSERESPONSE; if (boost::iequals(node.getLocalName(), "RESUMEREQUEST")) return RESUMEREQUEST; if (boost::iequals(node.getLocalName(), "RESUMERESPONSE")) return RESUMERESPONSE; if (boost::iequals(node.getLocalName(), "EXTENSIONNOTIFICATION")) return EXTENSIONNOTIFICATION; if (boost::iequals(node.getLocalName(), "CLEARCONTEXTREQUEST")) return CLEARCONTEXTREQUEST; if (boost::iequals(node.getLocalName(), "CLEARCONTEXTRESPONSE")) return CLEARCONTEXTRESPONSE; if (boost::iequals(node.getLocalName(), "STATUSREQUEST")) return STATUSREQUEST; if (boost::iequals(node.getLocalName(), "STATUSRESPONSE")) return STATUSRESPONSE; return INVALID; } Arabica::DOM::Document<std::string> MMIEvent::toXML(bool encapsulateInMMI) const { Arabica::DOM::DOMImplementation<std::string> domFactory = Arabica::SimpleDOM::DOMImplementation<std::string>::getDOMImplementation(); Document<std::string> doc = domFactory.createDocument(nameSpace, "", 0); Element<std::string> msgElem = doc.createElementNS(nameSpace, tagName); msgElem.setAttributeNS(nameSpace, "Source", source); msgElem.setAttributeNS(nameSpace, "Target", target); msgElem.setAttributeNS(nameSpace, "RequestID", requestId); if (dataDOM) { Element<std::string> dataElem = doc.createElementNS(nameSpace, "Data"); Node<std::string> importNode = doc.importNode(dataDOM, true); dataElem.appendChild(importNode); msgElem.appendChild(dataElem); } else if (data.size() > 0) { Element<std::string> dataElem = doc.createElementNS(nameSpace, "Data"); Text<std::string> textElem = doc.createTextNode(data); dataElem.appendChild(textElem); msgElem.appendChild(dataElem); } if (encapsulateInMMI) { Element<std::string> mmiElem = doc.createElementNS(nameSpace, "mmi"); mmiElem.appendChild(msgElem); doc.appendChild(mmiElem); } else { doc.appendChild(msgElem); } return doc; } Arabica::DOM::Document<std::string> ContentRequest::toXML(bool encapsulateInMMI) const { Document<std::string> doc = ContextualizedRequest::toXML(encapsulateInMMI); FIND_MSG_ELEM(msgElem, doc); if (contentURL.href.size() > 0) { Element<std::string> contentURLElem = doc.createElementNS(nameSpace, "ContentURL"); contentURLElem.setAttributeNS(nameSpace, "href", contentURL.href); contentURLElem.setAttributeNS(nameSpace, "fetchtimeout", contentURL.fetchTimeout); contentURLElem.setAttributeNS(nameSpace, "max-age", contentURL.maxAge); msgElem.appendChild(contentURLElem); } else if (contentDOM) { Element<std::string> contentElem = doc.createElementNS(nameSpace, "Content"); Node<std::string> importNode = doc.importNode(contentDOM, true); contentElem.appendChild(importNode); msgElem.appendChild(contentElem); } else if (content.size() > 0) { Element<std::string> contentElem = doc.createElementNS(nameSpace, "Content"); Text<std::string> textElem = doc.createTextNode(content); contentElem.appendChild(textElem); msgElem.appendChild(contentElem); } return doc; } Arabica::DOM::Document<std::string> ContextualizedRequest::toXML(bool encapsulateInMMI) const { Document<std::string> doc = MMIEvent::toXML(encapsulateInMMI); FIND_MSG_ELEM(msgElem, doc); msgElem.setAttributeNS(nameSpace, "Context", context); return doc; } Arabica::DOM::Document<std::string> ExtensionNotification::toXML(bool encapsulateInMMI) const { Document<std::string> doc = ContextualizedRequest::toXML(encapsulateInMMI); FIND_MSG_ELEM(msgElem, doc); msgElem.setAttributeNS(nameSpace, "Name", name); return doc; } Arabica::DOM::Document<std::string> StatusResponse::toXML(bool encapsulateInMMI) const { Document<std::string> doc = ContextualizedRequest::toXML(encapsulateInMMI); FIND_MSG_ELEM(msgElem, doc); if (status == ALIVE) { msgElem.setAttributeNS(nameSpace, "Status", "alive"); } else if(status == DEAD) { msgElem.setAttributeNS(nameSpace, "Status", "dead"); } else if(status == FAILURE) { msgElem.setAttributeNS(nameSpace, "Status", "failure"); } else if(status == SUCCESS) { msgElem.setAttributeNS(nameSpace, "Status", "success"); } return doc; } Arabica::DOM::Document<std::string> StatusInfoResponse::toXML(bool encapsulateInMMI) const { Document<std::string> doc = StatusResponse::toXML(encapsulateInMMI); FIND_MSG_ELEM(msgElem, doc); Element<std::string> statusInfoElem = doc.createElementNS(nameSpace, "StatusInfo"); Text<std::string> statusInfoText = doc.createTextNode(statusInfo); statusInfoElem.appendChild(statusInfoText); msgElem.appendChild(statusInfoElem); return doc; } Arabica::DOM::Document<std::string> StatusRequest::toXML(bool encapsulateInMMI) const { Document<std::string> doc = ContextualizedRequest::toXML(encapsulateInMMI); FIND_MSG_ELEM(msgElem, doc); if (automaticUpdate) { msgElem.setAttributeNS(nameSpace, "RequestAutomaticUpdate", "true"); } else { msgElem.setAttributeNS(nameSpace, "RequestAutomaticUpdate", "false"); } return doc; } MMIEvent MMIEvent::fromXML(Arabica::DOM::Node<std::string> node, InterpreterImpl* interpreter) { MMIEvent msg; FIND_EVENT_NODE(node); Element<std::string> msgElem(node); msg.source = STRING_ATTR_OR_EXPR(msgElem, Source); msg.target = STRING_ATTR_OR_EXPR(msgElem, Target); msg.requestId = STRING_ATTR_OR_EXPR(msgElem, RequestID); msg.tagName = msgElem.getLocalName(); Element<std::string> dataElem; // search for data element node = msgElem.getFirstChild(); while (node) { if (node.getNodeType() == Node_base::ELEMENT_NODE) dataElem = Element<std::string>(node); if (dataElem && boost::iequals(dataElem.getLocalName(), "data")) break; node = node.getNextSibling(); } if (dataElem && boost::iequals(dataElem.getLocalName(), "data") && dataElem.getFirstChild()) { Arabica::DOM::Node<std::string> dataChild = dataElem.getFirstChild(); std::stringstream ss; while (dataChild) { if (dataChild.getNodeType() == Arabica::DOM::Node_base::ELEMENT_NODE) msg.dataDOM = dataChild; ss << dataChild; dataChild = dataChild.getNextSibling(); } msg.data = ss.str(); } return msg; } FROM_XML(NewContextRequest, NEWCONTEXTREQUEST, MMIEvent) FROM_XML(PauseRequest, PAUSEREQUEST, ContextualizedRequest) FROM_XML(ResumeRequest, RESUMEREQUEST, ContextualizedRequest) FROM_XML(ClearContextRequest, CLEARCONTEXTREQUEST, ContextualizedRequest) FROM_XML(CancelRequest, CANCELREQUEST, ContextualizedRequest) FROM_XML(PrepareRequest, PREPAREREQUEST, ContentRequest) FROM_XML(StartRequest, STARTREQUEST, ContentRequest) FROM_XML(PrepareResponse, PREPARERESPONSE, StatusInfoResponse) FROM_XML(StartResponse, STARTRESPONSE, StatusInfoResponse) FROM_XML(CancelResponse, CANCELRESPONSE, StatusInfoResponse) FROM_XML(PauseResponse, PAUSERESPONSE, StatusInfoResponse) FROM_XML(ResumeResponse, RESUMERESPONSE, StatusInfoResponse) FROM_XML(ClearContextResponse, CLEARCONTEXTRESPONSE, StatusInfoResponse) FROM_XML(NewContextResponse, NEWCONTEXTRESPONSE, StatusInfoResponse) FROM_XML(DoneNotification, DONENOTIFICATION, StatusInfoResponse) ContextualizedRequest ContextualizedRequest::fromXML(Arabica::DOM::Node<std::string> node, InterpreterImpl* interpreter) { ContextualizedRequest msg(MMIEvent::fromXML(node, interpreter)); FIND_EVENT_NODE(node); Element<std::string> msgElem(node); msg.context = STRING_ATTR_OR_EXPR(msgElem, Context); return msg; } ExtensionNotification ExtensionNotification::fromXML(Arabica::DOM::Node<std::string> node, InterpreterImpl* interpreter) { ExtensionNotification msg(ContextualizedRequest::fromXML(node, interpreter)); FIND_EVENT_NODE(node); Element<std::string> msgElem(node); msg.name = STRING_ATTR_OR_EXPR(msgElem, Name); msg.type = EXTENSIONNOTIFICATION; return msg; } ContentRequest ContentRequest::fromXML(Arabica::DOM::Node<std::string> node, InterpreterImpl* interpreter) { ContentRequest msg(ContextualizedRequest::fromXML(node, interpreter)); FIND_EVENT_NODE(node); Element<std::string> msgElem(node); Element<std::string> contentElem; node = msgElem.getFirstChild(); while (node) { if (node.getNodeType() == Node_base::ELEMENT_NODE) { contentElem = Element<std::string>(node); if (boost::iequals(contentElem.getLocalName(), "content") || boost::iequals(contentElem.getLocalName(), "contentURL")) break; } node = node.getNextSibling(); } if (contentElem) { if(boost::iequals(contentElem.getLocalName(), "content")) { Arabica::DOM::Node<std::string> contentChild = contentElem.getFirstChild(); std::stringstream ss; while (contentChild) { if (contentChild.getNodeType() == Arabica::DOM::Node_base::ELEMENT_NODE) msg.contentDOM = contentChild; ss << contentChild; contentChild = contentChild.getNextSibling(); } msg.content = ss.str(); } else if(boost::iequals(contentElem.getLocalName(), "contentURL")) { msg.contentURL.href = STRING_ATTR_OR_EXPR(contentElem, href); msg.contentURL.maxAge = STRING_ATTR_OR_EXPR(contentElem, max-age); msg.contentURL.fetchTimeout = STRING_ATTR_OR_EXPR(contentElem, fetchtimeout); } } //msg.content = msgElem.getAttributeNS(nameSpace, "Context"); return msg; } StatusResponse StatusResponse::fromXML(Arabica::DOM::Node<std::string> node, InterpreterImpl* interpreter) { StatusResponse msg(ContextualizedRequest::fromXML(node, interpreter)); FIND_EVENT_NODE(node); Element<std::string> msgElem(node); std::string status = STRING_ATTR_OR_EXPR(msgElem, Status); if (boost::iequals(status, "ALIVE")) { msg.status = ALIVE; } else if(boost::iequals(status, "DEAD")) { msg.status = DEAD; } else if(boost::iequals(status, "FAILURE")) { msg.status = FAILURE; } else if(boost::iequals(status, "SUCCESS")) { msg.status = SUCCESS; } else { msg.status = INVALID; } msg.type = STATUSRESPONSE; return msg; } StatusInfoResponse StatusInfoResponse::fromXML(Arabica::DOM::Node<std::string> node, InterpreterImpl* interpreter) { StatusInfoResponse msg(StatusResponse::fromXML(node, interpreter)); FIND_EVENT_NODE(node); Element<std::string> msgElem(node); Element<std::string> statusInfoElem; node = msgElem.getFirstChild(); while (node) { if (node.getNodeType() == Node_base::ELEMENT_NODE) { statusInfoElem = Element<std::string>(node); if (statusInfoElem && boost::iequals(statusInfoElem.getLocalName(), "statusInfo")) break; } node = node.getNextSibling(); } if (statusInfoElem && boost::iequals(statusInfoElem.getLocalName(), "statusInfo")) { node = statusInfoElem.getFirstChild(); while (node) { if (node.getNodeType() == Node_base::TEXT_NODE) { msg.statusInfo = node.getNodeValue(); break; } node = node.getNextSibling(); } } return msg; } StatusRequest StatusRequest::fromXML(Arabica::DOM::Node<std::string> node, InterpreterImpl* interpreter) { StatusRequest msg(ContextualizedRequest::fromXML(node, interpreter)); FIND_EVENT_NODE(node); Element<std::string> msgElem(node); std::string autoUpdate = STRING_ATTR_OR_EXPR(msgElem, RequestAutomaticUpdate); if (boost::iequals(autoUpdate, "true")) { msg.automaticUpdate = true; } else if(boost::iequals(autoUpdate, "on")) { msg.automaticUpdate = true; } else if(boost::iequals(autoUpdate, "yes")) { msg.automaticUpdate = true; } else if(boost::iequals(autoUpdate, "1")) { msg.automaticUpdate = true; } else { msg.automaticUpdate = false; } msg.type = STATUSREQUEST; return msg; } #ifdef MMI_WITH_OPERATOR_EVENT TO_EVENT_OPERATOR(NewContextRequest, "mmi.request.newcontext", MMIEvent); TO_EVENT_OPERATOR(PauseRequest, "mmi.request.pause", ContextualizedRequest); TO_EVENT_OPERATOR(ResumeRequest, "mmi.request.resume", ContextualizedRequest); TO_EVENT_OPERATOR(CancelRequest, "mmi.request.cancel", ContextualizedRequest); TO_EVENT_OPERATOR(ClearContextRequest, "mmi.request.clearcontext", ContextualizedRequest); TO_EVENT_OPERATOR(StatusRequest, "mmi.request.status", ContextualizedRequest); TO_EVENT_OPERATOR(PrepareRequest, "mmi.request.prepare", ContentRequest); TO_EVENT_OPERATOR(StartRequest, "mmi.request.start", ContentRequest); TO_EVENT_OPERATOR(PrepareResponse, "mmi.response.prepare", StatusInfoResponse); TO_EVENT_OPERATOR(StartResponse, "mmi.response.start", StatusInfoResponse); TO_EVENT_OPERATOR(CancelResponse, "mmi.response.cancel", StatusInfoResponse); TO_EVENT_OPERATOR(PauseResponse, "mmi.response.pause", StatusInfoResponse); TO_EVENT_OPERATOR(ResumeResponse, "mmi.response.resume", StatusInfoResponse); TO_EVENT_OPERATOR(ClearContextResponse, "mmi.response.clearcontext", StatusInfoResponse); TO_EVENT_OPERATOR(NewContextResponse, "mmi.response.newcontext", StatusInfoResponse); TO_EVENT_OPERATOR(DoneNotification, "mmi.notification.done", StatusInfoResponse); MMIEvent::operator Event() const { Event ev; ev.setOriginType("mmi.event"); ev.setOrigin(source); if (representation == MMI_AS_DATA) { if (dataDOM) { ev.data.node = dataDOM; } else { ev.data = Data::fromJSON(data); if (ev.data.empty()) { ev.content = data; } } } return ev; } ContextualizedRequest::operator Event() const { Event ev = MMIEvent::operator Event(); // do we want to represent the context? It's the interpreters name already return ev; } ExtensionNotification::operator Event() const { Event ev = ContextualizedRequest::operator Event(); if (name.length() > 0) { ev.setName(name); } else { ev.setName("mmi.notification.extension"); } return ev; } ContentRequest::operator Event() const { Event ev = ContextualizedRequest::operator Event(); if (representation == MMI_AS_DATA) { if (content.length() > 0) ev.data.compound["content"] = Data(content, Data::VERBATIM); if (contentURL.fetchTimeout.length() > 0) ev.data.compound["contentURL"].compound["fetchTimeout"] = Data(contentURL.fetchTimeout, Data::VERBATIM); if (contentURL.href.length() > 0) ev.data.compound["contentURL"].compound["href"] = Data(contentURL.href, Data::VERBATIM); if (contentURL.maxAge.length() > 0) ev.data.compound["contentURL"].compound["maxAge"] = Data(contentURL.maxAge, Data::VERBATIM); } return ev; } StatusResponse::operator Event() const { Event ev = ContextualizedRequest::operator Event(); ev.setName("mmi.response.status"); if (representation == MMI_AS_DATA) { switch (status) { case ALIVE: ev.data.compound["status"] = Data("alive", Data::VERBATIM); break; case DEAD: ev.data.compound["status"] = Data("dead", Data::VERBATIM); break; case SUCCESS: ev.data.compound["status"] = Data("success", Data::VERBATIM); break; case FAILURE: ev.data.compound["status"] = Data("failure", Data::VERBATIM); break; default: ev.data.compound["status"] = Data("invalid", Data::VERBATIM); } } else { ev.dom = toXML(); } return ev; } #endif }
[ "radomski@tk.informatik.tu-darmstadt.de" ]
radomski@tk.informatik.tu-darmstadt.de
2b660c8e1bc3675f02e1dd3508f1d7f1999aaf09
2e83b09998113da74795e196f2cf8719212c9928
/GeeksforGeeks/Arrays/longestEvenOddSubArray_efficient.cpp
34a0aed641a6977a9a978bbd56938500e5ee2fe1
[]
no_license
KarmveerK/Data-Structures-And-Algorithms
a27163944f7d505fc5c5fdf97fb9cda3f8ae2fa4
43c4717729f6bfa33bd82b25c6a98a851d405816
refs/heads/main
2023-05-31T15:30:25.555822
2021-06-13T14:35:10
2021-06-13T14:35:10
374,896,576
0
0
null
null
null
null
UTF-8
C++
false
false
591
cpp
#include<iostream> using namespace std; //BASED ON KADANES ALGORITHM int evenOddSubarray(int a[], int size){ int count = 1; int maxCount = 1; for(int i=1; i<size; i++){ if((a[i] - a[i-1])%2 != 0){ count++; maxCount = max(maxCount, count); } else{ count = 1; } } return maxCount; } int main(){ int a[] = {5, 10, 20, 6, 3, 8}; //int a[] = {7, 10, 13, 14}; //int a[] = {10, 20, 30, 40}; int size = sizeof(a) / sizeof(a[0]); cout<<evenOddSubarray(a, size); }
[ "noreply@github.com" ]
KarmveerK.noreply@github.com
6d1ab11b46cc3924f1cba4403d729f1936a81d35
6b3e36e68ae34f85d5d27166687e3479e5333bb4
/Sources/Elastos/Packages/Apps/Dialer/inc/elastos/droid/incallui/CCallButtonFragment.h
4854b7999e46983e4921576b3b6493bf0cb23813
[ "Apache-2.0" ]
permissive
jiawangyu/Elastos5
66bec21d7d364ecb223c75b3ad48258aa05b1540
1aa6fe7e60eaf055a9948154242124b04eae3a02
refs/heads/master
2020-12-11T07:22:13.469074
2016-08-23T09:42:42
2016-08-23T09:42:57
null
0
0
null
null
null
null
UTF-8
C++
false
false
7,897
h
#ifndef __ELASTOS_DROID_INCALLUI_CCALLBUTTONFRAGMENT_H__ #define __ELASTOS_DROID_INCALLUI_CCALLBUTTONFRAGMENT_H__ #include "Elastos.Droid.Content.h" #include "Elastos.Droid.Os.h" #include "Elastos.Droid.View.h" #include "Elastos.Droid.Widget.h" #include "_Elastos_Droid_InCallUI_CCallButtonFragment.h" #include "elastos/droid/incallui/BaseFragment.h" using Elastos::Droid::Content::IContext; using Elastos::Droid::Os::IBundle; using Elastos::Droid::View::ILayoutInflater; using Elastos::Droid::View::IMenuItem; using Elastos::Droid::View::IView; using Elastos::Droid::View::IViewOnClickListener; using Elastos::Droid::View::IViewGroup; using Elastos::Droid::Widget::ICompoundButton; using Elastos::Droid::Widget::ICompoundButtonOnCheckedChangeListener; using Elastos::Droid::Widget::IImageButton; using Elastos::Droid::Widget::IPopupMenu; using Elastos::Droid::Widget::IPopupMenuOnDismissListener; using Elastos::Droid::Widget::IPopupMenuOnMenuItemClickListener; namespace Elastos { namespace Droid { namespace InCallUI { CarClass(CCallButtonFragment) , public BaseFragment , public IPopupMenuOnMenuItemClickListener , public IPopupMenuOnDismissListener , public IViewOnClickListener , public ICompoundButtonOnCheckedChangeListener , public IUi , public ICallButtonUi , public ICallButtonFragment { private: class OverflowPopupOnMenuItemClickListener : public Object , public IPopupMenuOnMenuItemClickListener { public: OverflowPopupOnMenuItemClickListener( /* [in] */ CCallButtonFragment* host) : mHost(host) {} CAR_INTERFACE_DECL(); // @Override CARAPI OnMenuItemClick( /* [in] */ IMenuItem* item, /* [out] */ Boolean* result); private: CCallButtonFragment* mHost; }; class OverflowPopupOnDismissListener : public Object , public IPopupMenuOnDismissListener { public: OverflowPopupOnDismissListener( /* [in] */ CCallButtonFragment* host) : mHost(host) {} CAR_INTERFACE_DECL(); // @Override CARAPI OnDismiss( /* [in] */ IPopupMenu* popupMenu); private: CCallButtonFragment* mHost; }; public: CAR_INTERFACE_DECL(); CAR_OBJECT_DECL(); CCallButtonFragment(); CARAPI constructor(); // @Override CARAPI_(AutoPtr<IPresenter>) CreatePresenter(); // @Override CARAPI_(AutoPtr<IUi>) GetUi(); // @Override CARAPI OnCreate( /* [in] */ IBundle* savedInstanceState); // @Override CARAPI OnCreateView( /* [in] */ ILayoutInflater* inflater, /* [in] */ IViewGroup* container, /* [in] */ IBundle* savedInstanceState, /* [out] */ IView** view); // @Override CARAPI OnActivityCreated( /* [in] */ IBundle* savedInstanceState); // @Override CARAPI OnResume(); // @Override CARAPI OnCheckedChanged( /* [in] */ ICompoundButton* buttonView, /* [in] */ Boolean isChecked); // @Override CARAPI OnClick( /* [in] */ IView* view); // @Override CARAPI SetEnabled( /* [in] */ Boolean isEnabled); // @Override CARAPI SetMute( /* [in] */ Boolean value); // @Override CARAPI ShowAudioButton( /* [in] */ Boolean show); // @Override CARAPI ShowChangeToVoiceButton( /* [in] */ Boolean show); // @Override CARAPI EnableMute( /* [in] */ Boolean enabled); // @Override CARAPI ShowDialpadButton( /* [in] */ Boolean show); // @Override CARAPI SetHold( /* [in] */ Boolean value); // @Override CARAPI ShowHoldButton( /* [in] */ Boolean show); // @Override CARAPI EnableHold( /* [in] */ Boolean enabled); // @Override CARAPI ShowSwapButton( /* [in] */ Boolean show); // @Override CARAPI ShowChangeToVideoButton( /* [in] */ Boolean show); // @Override CARAPI ShowSwitchCameraButton( /* [in] */ Boolean show); // @Override CARAPI SetSwitchCameraButton( /* [in] */ Boolean isBackFacingCamera); // @Override CARAPI ShowAddCallButton( /* [in] */ Boolean show); // @Override CARAPI ShowMergeButton( /* [in] */ Boolean show); // @Override CARAPI ShowPauseVideoButton( /* [in] */ Boolean show); // @Override CARAPI SetPauseVideoButton( /* [in] */ Boolean isPaused); // @Override CARAPI ShowOverflowButton( /* [in] */ Boolean show); // @Override CARAPI ConfigureOverflowMenu( /* [in] */ Boolean showMergeMenuOption, /* [in] */ Boolean showAddMenuOption, /* [in] */ Boolean showHoldMenuOption, /* [in] */ Boolean showSwapMenuOption); // @Override CARAPI SetAudio( /* [in] */ Int32 mode); // @Override CARAPI SetSupportedAudio( /* [in] */ Int32 modeMask); // @Override CARAPI OnMenuItemClick( /* [in] */ IMenuItem* item, /* [out] */ Boolean* result); // PopupMenu.OnDismissListener implementation; see showAudioModePopup(). // This gets called when the PopupMenu gets dismissed for *any* reason, like // the user tapping outside its bounds, or pressing Back, or selecting one // of the menu items. // @Override CARAPI OnDismiss( /* [in] */ IPopupMenu* menu); /** * Refreshes the "Audio mode" popup if it's visible. This is useful * (for example) when a wired headset is plugged or unplugged, * since we need to switch back and forth between the "earpiece" * and "wired headset" items. * * This is safe to call even if the popup is already dismissed, or even if * you never called showAudioModePopup() in the first place. */ CARAPI_(void) RefreshAudioModePopup(); // @Override CARAPI DisplayDialpad( /* [in] */ Boolean value, /* [in] */ Boolean animate); // @Override CARAPI IsDialpadVisible( /* [out] */ Boolean* visible); // @Override CARAPI GetContext( /* [out] */ IContext** context); private: /** * Checks for supporting modes. If bluetooth is supported, it uses the audio * pop up menu. Otherwise, it toggles the speakerphone. */ CARAPI_(void) OnAudioButtonClicked(); /** * Updates the audio button so that the appriopriate visual layers * are visible based on the supported audio formats. */ CARAPI_(void) UpdateAudioButtons( /* [in] */ Int32 supportedModes); CARAPI_(void) ShowAudioModePopup(); CARAPI_(Boolean) IsSupported( /* [in] */ Int32 mode); CARAPI_(Boolean) IsAudio( /* [in] */ Int32 mode); CARAPI_(void) MaybeSendAccessibilityEvent( /* [in] */ IView* view, /* [in] */ Int32 stringId); private: AutoPtr<IImageButton> mAudioButton; AutoPtr<IImageButton> mChangeToVoiceButton; AutoPtr<IImageButton> mMuteButton; AutoPtr<IImageButton> mShowDialpadButton; AutoPtr<IImageButton> mHoldButton; AutoPtr<IImageButton> mSwapButton; AutoPtr<IImageButton> mChangeToVideoButton; AutoPtr<IImageButton> mSwitchCameraButton; AutoPtr<IImageButton> mAddCallButton; AutoPtr<IImageButton> mMergeButton; AutoPtr<IImageButton> mPauseVideoButton; AutoPtr<IImageButton> mOverflowButton; AutoPtr<IPopupMenu> mAudioModePopup; Boolean mAudioModePopupVisible; AutoPtr<IPopupMenu> mOverflowPopup; Int32 mPrevAudioMode; // Constants for Drawable.setAlpha() static const Int32 HIDDEN; static const Int32 VISIBLE; Boolean mIsEnabled; }; } // namespace InCallUI } // namespace Droid } // namespace Elastos #endif // __ELASTOS_DROID_INCALLUI_CCALLBUTTONFRAGMENT_H__
[ "cao.jing@kortide.com" ]
cao.jing@kortide.com
dd1621aa7af8c321977c985708ed216de5ba6610
19f039b593be9401d479b15f97ecb191ef478f46
/RSA-SW/PSME/agent/storage/src/iscsi/config/tgt_config.cpp
e20293c1ae1a22dca3b16b48510705681006cbea
[ "MIT", "BSD-3-Clause", "Apache-2.0" ]
permissive
isabella232/IntelRackScaleArchitecture
9a28e34a7f7cdc21402791f24dad842ac74d07b6
1206d2316e1bd1889b10a1c4f4a39f71bdfa88d3
refs/heads/master
2021-06-04T08:33:27.191735
2016-09-29T09:18:10
2016-09-29T09:18:10
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,813
cpp
/*! * @section LICENSE * * @copyright * Copyright (c) 2015 Intel Corporation * * @copyright * 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 * * @copyright * http://www.apache.org/licenses/LICENSE-2.0 * * @copyright * 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. * * @section DESCRIPTION */ #include "iscsi/tgt/config/tgt_config.hpp" #include "iscsi/tgt/config/tgt_target_config.hpp" #include "agent-framework/module/target.hpp" #include "logger/logger_factory.hpp" #include <stdexcept> #include <iostream> #include <fstream> #include <cstring> using namespace agent::storage::iscsi::tgt::config; using namespace agent_framework::generic; using namespace std; constexpr const char* TGT_TARGET_CONF_EXTENSION = ".conf"; constexpr const char* TGT_TARGET_CONF_PATH = "/etc/tgt/conf.d/"; void TgtConfig::add_target(const Target::TargetSharedPtr& target) const { TgtTargetConfig tgtTargetConfig(target); auto target_conf_file_name = get_target_conf_file_name(target->get_target_id()); log_info(GET_LOGGER("tgt"), "Add TGT target config file: " + target_conf_file_name); ofstream targetConfigFile; const auto& content = tgtTargetConfig.to_string(); targetConfigFile.open(target_conf_file_name.c_str(), ios_base::out); if (targetConfigFile.is_open()) { targetConfigFile << content; targetConfigFile.close(); } else { throw runtime_error("Error opening file for writing: " + target_conf_file_name); } } void TgtConfig::remove_target(const int32_t target_id) const { auto target_conf_file_name = get_target_conf_file_name(target_id); log_info(GET_LOGGER("tgt"), "Remove TGT target config file: " + target_conf_file_name); if (0 != remove(target_conf_file_name.c_str())) { throw runtime_error("Error removing file: " + target_conf_file_name); } } string TgtConfig::get_target_conf_file_name(const int32_t target_id) const { string configuration_path = m_configuration_path; if (configuration_path.empty()) { log_warning(GET_LOGGER("tgt"), "TGT conf-path is empty. Using default path: " << TGT_TARGET_CONF_PATH); configuration_path = TGT_TARGET_CONF_PATH; } if ('/' != configuration_path.at(configuration_path.size() - 1)) { configuration_path += '/'; } return configuration_path + to_string(target_id) + TGT_TARGET_CONF_EXTENSION; }
[ "chester.kuo@gmail.com" ]
chester.kuo@gmail.com
6cb5c10f324394fef04691711c46dd16709d5123
c7e65a70caf87041afd27441fe45eac85e8cd1e4
/apps/coreir_examples/conv_bw_valid/pipeline.cpp
d686745a8ab708ae8328047c43e4358c65053328
[ "MIT" ]
permissive
jeffsetter/Halide_CoreIR
adb8d9c4bc91b11d55e07a67e86643a0515e0ee6
f2f5307f423a6040beb25a1f63a8f7ae8a93d108
refs/heads/master
2020-05-23T18:06:27.007413
2018-10-02T22:09:02
2018-10-02T22:09:02
84,777,366
7
1
NOASSERTION
2018-11-05T15:05:11
2017-03-13T02:50:55
C++
UTF-8
C++
false
false
4,233
cpp
#include "Halide.h" #include <string.h> using namespace Halide; using std::string; Var x("x"), y("y"); Var xo("xo"), xi("xi"), yi("yi"), yo("yo"); class MyPipeline { public: ImageParam input; Param<uint16_t> bias; Func kernel; Func clamped; Func conv1; Func output; Func hw_output; std::vector<Argument> args; RDom win; MyPipeline() : input(UInt(8), 2, "input"), bias("bias"), kernel("kernel"), conv1("conv1"), output("output"), hw_output("hw_output"), win(0, 3, 0, 3) { // Define the kernel kernel(x,y) = 0; kernel(0,0) = 11; kernel(0,1) = 12; kernel(0,2) = 13; kernel(1,0) = 14; kernel(1,1) = 0; kernel(1,2) = 16; kernel(2,0) = 17; kernel(2,1) = 18; kernel(2,2) = 19; // define the algorithm clamped(x,y) = input(x,y); conv1(x, y) += clamped(x+win.x, y+win.y) * kernel(win.x, win.y); // unroll the reduction conv1.update(0).unroll(win.x).unroll(win.y); hw_output(x,y) = cast<uint8_t>(conv1(x,y)); output(x, y) = hw_output(x, y); args.push_back(input); args.push_back(bias); } void compile_cpu() { std::cout << "\ncompiling cpu code..." << std::endl; output.tile(x, y, xo, yo, xi, yi, 62,62); output.fuse(xo, yo, xo).parallel(xo); output.vectorize(xi, 8); conv1.compute_at(output, xo).vectorize(x, 8); //output.print_loop_nest(); output.compile_to_lowered_stmt("pipeline_native.ir.html", args, HTML); output.compile_to_header("pipeline_native.h", args, "pipeline_native"); output.compile_to_object("pipeline_native.o", args, "pipeline_native"); } void compile_gpu() { std::cout << "\ncompiling gpu code..." << std::endl; output.compute_root().reorder(x, y).gpu_tile(x, y, 16, 16); conv1.compute_root().reorder(x, y).gpu_tile(x, y, 16, 16); //conv1.compute_at(output, Var::gpu_blocks()).gpu_threads(x, y); //output.print_loop_nest(); Target target = get_target_from_environment(); target.set_feature(Target::CUDA); output.compile_to_lowered_stmt("pipeline_cuda.ir.html", args, HTML, target); output.compile_to_header("pipeline_cuda.h", args, "pipeline_cuda", target); output.compile_to_object("pipeline_cuda.o", args, "pipeline_cuda", target); } void compile_hls() { std::cout << "\ncompiling HLS code..." << std::endl; clamped.compute_root(); // prepare the input for the whole image // HLS schedule: make a hw pipeline producing 'hw_output', taking // inputs of 'clamped', buffering intermediates at (output, xo) loop // level hw_output.compute_root(); //hw_output.tile(x, y, xo, yo, xi, yi, 1920, 1080).reorder(xi, yi, xo, yo); hw_output.tile(x, y, xo, yo, xi, yi, 62,62).reorder(xi, yi, xo, yo); //hw_output.unroll(xi, 2); hw_output.accelerate({clamped}, xi, xo, {}); // define the inputs and the output conv1.linebuffer(); // conv1.unroll(x).unroll(y); output.print_loop_nest(); Target hls_target = get_target_from_environment(); hls_target.set_feature(Target::CPlusPlusMangling); output.compile_to_lowered_stmt("pipeline_hls.ir.html", args, HTML, hls_target); output.compile_to_hls("pipeline_hls.cpp", args, "pipeline_hls", hls_target); output.compile_to_header("pipeline_hls.h", args, "pipeline_hls", hls_target); } void compile_coreir() { std::cout << "\ncompiling CoreIR code..." << std::endl; clamped.compute_root(); hw_output.compute_root(); conv1.linebuffer(); hw_output.tile(x, y, xo, yo, xi, yi, 62,62).reorder(xi,yi,xo,yo); hw_output.accelerate({clamped}, xi, xo, {}); Target coreir_target = get_target_from_environment(); coreir_target.set_feature(Target::CPlusPlusMangling); coreir_target.set_feature(Target::CoreIRValid); output.compile_to_lowered_stmt("pipeline_coreir.ir.html", args, HTML, coreir_target); output.compile_to_coreir("pipeline_coreir.cpp", args, "pipeline_coreir", coreir_target); } }; int main(int argc, char **argv) { MyPipeline p1; p1.compile_cpu(); MyPipeline p2; p2.compile_hls(); MyPipeline p4; p4.compile_coreir(); // MyPipeline p3; //p3.compile_gpu(); return 0; }
[ "setter@stanford.edu" ]
setter@stanford.edu
fb7f8a2e574eb401570d5b2ae62bd318d8dbd84a
4f460d4984c9e934978bbc89eb10654fa3b618a8
/WifiWebServer/WifiWebServer.ino
5834dbd2c8baa0ac329b814e0f3292e7afe81bc3
[]
no_license
davidaronson13/PowerBiker
eaea512bc690801d4fbe050bd731eaab8445349d
3757549a823981b980a7817008cee68d5b86b03d
refs/heads/master
2020-03-31T00:57:05.928520
2014-05-27T14:56:22
2014-05-27T14:56:22
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,119
ino
/* WiFi Web Server A simple web server that shows the value of the analog input pins. using a WiFi shield. This example is written for a network using WPA encryption. For WEP or WPA, change the Wifi.begin() call accordingly. Circuit: * WiFi shield attached * Analog inputs attached to pins A0 through A5 (optional) created 13 July 2010 by dlf (Metodo2 srl) modified 31 May 2012 by Tom Igoe */ #include <SPI.h> #include <WiFi.h> char ssid[] = "bikeMind"; // your network SSID (name) char pass[] = "secretPassword"; // your network password int keyIndex = 0; // your network key Index number (needed only for WEP) int status = WL_IDLE_STATUS; WiFiServer server(80); void setup() { //Initialize serial and wait for port to open: Serial.begin(9600); while (!Serial) { ; // wait for serial port to connect. Needed for Leonardo only } // check for the presence of the shield: if (WiFi.status() == WL_NO_SHIELD) { Serial.println("WiFi shield not present"); // don't continue: while(true); } // attempt to connect to Wifi network: while ( status != WL_CONNECTED) { Serial.print("Attempting to connect to SSID: "); Serial.println(ssid); // Connect to WPA/WPA2 network. Change this line if using open or WEP network: status = WiFi.begin(ssid); // wait 10 seconds for connection: delay(10000); } server.begin(); // you're connected now, so print out the status: printWifiStatus(); } void loop() { // listen for incoming clients WiFiClient client = server.available(); if (client) { Serial.println("new client"); // an http request ends with a blank line boolean currentLineIsBlank = true; while (client.connected()) { if (client.available()) { char c = client.read(); Serial.write(c); // if you've gotten to the end of the line (received a newline // character) and the line is blank, the http request has ended, // so you can send a reply if (c == '\n' && currentLineIsBlank) { // send a standard http response header client.println("HTTP/1.1 200 OK"); client.println("Content-Type: text/html"); client.println("Connection: close"); client.println(); client.println("<!DOCTYPE HTML>"); client.println("<html>"); // add a meta refresh tag, so the browser pulls again every 5 seconds: client.println("<meta http-equiv=\"refresh\" content=\"5\">"); //add meta for full screen client.println("<meta name=\"apple-mobile-web-app-capable\" content=\"yes\">"); client.println("<body style=\"background-color:#000; font-size:64px;color:#0F0; \">"); // output the value of each analog input pin for (int analogChannel = 0; analogChannel < 6; analogChannel++) { int sensorReading = analogRead(analogChannel); client.print("analog input "); client.print(analogChannel); client.print(" is "); client.print(sensorReading); client.println("<br />"); } client.println("</body></html>"); break; } if (c == '\n') { // you're starting a new line currentLineIsBlank = true; } else if (c != '\r') { // you've gotten a character on the current line currentLineIsBlank = false; } } } // give the web browser time to receive the data delay(1); // close the connection: client.stop(); Serial.println("client disonnected"); } } void printWifiStatus() { // print the SSID of the network you're attached to: Serial.print("SSID: "); Serial.println(WiFi.SSID()); // print your WiFi shield's IP address: IPAddress ip = WiFi.localIP(); Serial.print("IP Address: "); Serial.println(ip); // print the received signal strength: long rssi = WiFi.RSSI(); Serial.print("signal strength (RSSI):"); Serial.print(rssi); Serial.println(" dBm"); }
[ "davidaronson13@gmail.com" ]
davidaronson13@gmail.com
231994a748f60ae6cd2eca98aa9ce320dca8dc26
7fae79369bffd6fe98a8d517ce15d93935ac104c
/main.cpp
1dc659e33f33c9c0a168eaa3dfe140f323de221d
[]
no_license
ArielAleksandrus/compilador
a5109d09f6a90c9f0b7964e6b495223ad50d75cf
1a4c5fe2349b8de1b0b5b0a58ac5253e29d9ea80
refs/heads/master
2020-05-21T10:14:56.407885
2016-07-29T17:31:16
2016-07-29T17:31:16
54,926,554
0
0
null
null
null
null
UTF-8
C++
false
false
2,212
cpp
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /* * File: main.cpp * Author: aleksandrus * * Created on March 18, 2016, 11:06 AM */ #include <iostream> #include <cstdlib> #include "circular_dep.h" #include "FileReader.h" #include "Parser.h" #include "Tree.h" using namespace std; typedef struct Options{ char fileName[256]; bool printTokens; bool printTree; bool printGlobals; bool printFunctions; bool terminate; }Options; Options* handleArgs(int argc, char** argv){ Options* o = (Options*) calloc(1, sizeof(Options)); strncpy(o->fileName, argv[1], 256); for(int i = 2; i <= argc; i++){ if(strcmp(argv[i - 1], "-h") == 0){ cout << "Usage:\n"; cout << "First argument should be source file's path or -h alone.\n"; cout << "\t-h\t\tPrint available options.\n"; cout << "\t-pto\t\tPrint recognized tokens.\n"; cout << "\t-ptr\t\tPrint elements's tree.\n"; cout << "\t-pg\t\tPrint global variables.\n"; cout << "\t-pf\t\tPrint functions.\n"; cout << "\t-pa\t\tPrint all.\n"; o->terminate = true; } if(strcmp(argv[i - 1], "-pto") == 0){ o->printTokens = true; } if(strcmp(argv[i - 1], "-ptr") == 0){ o->printTree = true; } if(strcmp(argv[i - 1], "-pg") == 0){ o->printGlobals = true; } if(strcmp(argv[i - 1], "-pf") == 0){ o->printFunctions = true; } if(strcmp(argv[i - 1], "-pa") == 0){ o->printTokens = true; o->printTree = true; o->printGlobals = true; o->printFunctions = true; } } return o; } int main(int argc, char** argv) { if(argc < 2){ cout << "Missing file as argument" << endl; exit(1); } Options* o = handleArgs(argc, argv); if(o->terminate) return 0; FileReader* fr = new FileReader(argv[1]); if(o->printTokens) fr->printTokens(); Utils u; u.out.open("a.out"); Tree* t = new Tree(&u); Parser* p = new Parser(fr->getTokens(), t); if(o->printTree) t->printTree(); else { if(o->printGlobals) t->printGlobalVariables(); if(o->printFunctions) t->printFunctions(); } t->semanticAnalysis(); u.out.close(); return 0; }
[ "arielaleksandrus@hotmail.com" ]
arielaleksandrus@hotmail.com
5f3f225665cff48a5ebe83a2e45e807507cf52fe
9b8708ad7ffb5d344eba46451cabc3da8c0b645b
/Moteur/SceneGraph/meshmanager.h
8dac8630f554c425dde04c6aa8c74babb287882d
[]
no_license
VisualPi/GameEngine
8830037305ff2268866f0e2c254e6f74901dd18d
03c60c571ab3a95b8eaf2c560aa3e4c9486a77c3
refs/heads/master
2021-07-08T18:13:28.459930
2017-10-08T12:05:05
2017-10-08T12:05:05
null
0
0
null
null
null
null
UTF-8
C++
false
false
517
h
#pragma once #include <vector> #include "../Transfer/bufferfactory.h" #include "ModelImporter/mesh.h" #include "../Vulkan/buffer.h" #include "drawcommand.h" class MeshManager { public: MeshManager(BufferFactory &bufferFactory); DrawCmd addMesh(const std::vector<Mesh> &meshes); private: BufferFactory &mBufferFactory; // uint32_t Buffer mStagingBuffer; // the uint32_t size means the total offset used std::vector<std::tuple<uint32_t, Buffer>> mIbos; std::vector<std::tuple<uint32_t, Buffer>> mVbos; };
[ "antoine.morrier@outlook.fr" ]
antoine.morrier@outlook.fr
1de9ef5dcb8c8c43a4263bb59f4ff89c9f384fa0
ba34acc11d45cf644d7ce462c5694ce9662c34c2
/Classes/geometry/recognizer/GeometricRecognizerNode.h
3028df38c0157db3078645fbfef72c495c46046e
[]
no_license
mspenn/Sketch2D
acce625c4631313ba2ef47a5c8f8eadcd332719b
ae7d9f00814ac68fbd8e3fcb39dfac34edfc9883
refs/heads/master
2021-01-12T13:26:35.864853
2019-01-09T12:45:11
2019-01-09T12:45:11
69,162,221
8
7
null
null
null
null
UTF-8
C++
false
false
2,980
h
#ifndef __GEOMETRIC_RECOGNIZER_NODE_H__ #define __GEOMETRIC_RECOGNIZER_NODE_H__ #include "cocos2d.h" #include "gesture\GeometricRecognizer.h" // event #define EVENT_LOADING_TEMPLATE "onLoadingTemplate" #define EVENT_LOADED_TEMPLATE "onLoadedTemplate" /** * Load Template Data for Update Feedback Event */ struct LoadTemplateData { // Constructor LoadTemplateData(int progress, const std::string& hint) { _progress = progress; _hint = hint; } int _progress; // current progress volunm std::string _hint; // hint content/message }; /** * Geometric Recognizer Node * It can be attached to a game scene, and used everywhere in the scene * @see cocos2d::Node */ class GeometricRecognizerNode :public cocos2d::Node { public: /** * Call when Geometric Recognizer Node is initialized, override * @see cocos2d::Node::init * @return true if initialize successfully, false otherwise */ virtual bool init(); /** * Load template as multiply stroke * @param name template name * @param path template path in file system * @param multiStrokeGesture a empty MultiStrokeGesture object * will be fill in template data after call * @return reference to a existing MultiStrokeGesture object */ DollarRecognizer::MultiStrokeGesture& loadTemplate( std::string name, const char* path, DollarRecognizer::MultiStrokeGesture& multiStrokeGesture); /** * Store multiply stroke as template file * @param multiStrokeGesture a reference to existing MultiStrokeGesture object * @param path template path in file system */ void storeAsTemplate( const DollarRecognizer::MultiStrokeGesture& multiStrokeGesture, const char* path); /** * Get GeometricRecognizer object * @return pointer to GeometricRecognizer instance */ inline DollarRecognizer::GeometricRecognizer* getGeometricRecognizer() { return &_geometricRecognizer; } /** * Scan Gesture Samples by specified gesture name * @param gestureName specified gesture name, such as Cycle, Rectangle, etc * @param multiStrokeGesture a empty MultiStrokeGesture object to store data * @param mgestureList sample file detail names, such as Cycle::1, Cycle::2, etc */ void scanGestureSamples( const string& gestureName, DollarRecognizer::MultiStrokeGesture& multiStrokeGesture, vector<string>& mgestureList); /** * Feedback loading template progress * send EVENT_LOADING_TEMPLATE event */ void loadProgressFeedBack(); /** * Feedback when loading progress is active * send EVENT_LOADING_TEMPLATE event */ void loadProgressActiveFeedBack(); /** * Feedback when loading progress is done * send EVENT_LOADED_TEMPLATE event */ void loadProgressDoneFeedBack(); /** * Static factory to create GeometricRecognizerNode object */ CREATE_FUNC(GeometricRecognizerNode); private: DollarRecognizer::GeometricRecognizer _geometricRecognizer; // dollar recognizer instance }; #endif /* __GEOMETRIC_RECOGNIZER_NODE_H__ */
[ "microsmadio@hotmail.com" ]
microsmadio@hotmail.com
c8f9f07944e3f28b7cc24f46ddd2fb4374d2b62c
fbb664ae602ecf0c1679dbb998f1cfb296a63b17
/tests/catch_malloc.h
3e49d293466a8b0026ae2896fdf18a41287e5bfd
[]
no_license
ADVRHumanoids/RealtimeSvd
82368c56609b1999d972140d64203e58b7111bee
71987b17fb0f71d6b0b906849a5ea0021b00a013
refs/heads/master
2021-07-06T13:08:39.747407
2018-10-22T18:41:56
2018-10-22T18:41:56
153,766,252
1
1
null
2020-07-31T08:47:03
2018-10-19T10:29:06
CMake
UTF-8
C++
false
false
4,556
h
#ifndef __CATCH_MALLOC_H__ #define __CATCH_MALLOC_H__ #include <malloc.h> #include <exception> #include <iostream> #include <functional> namespace XBot { namespace Utils { class MallocFinder { public: static void SetThrowOnMalloc(bool throw_on_malloc) { _throw_on_malloc = throw_on_malloc; } static bool ThrowsOnMalloc() { return _throw_on_malloc; } static void SetThrowOnFree(bool throw_on_free) { _throw_on_free = throw_on_free; } static bool ThrowsOnFree() { return _throw_on_free; } static void Enable() { _is_enabled = true; } static void Disable() { _is_enabled = false; } static bool IsEnabled() { return _is_enabled; } static void OnMalloc() { _f_malloc(); } static void OnFree() { _f_free(); } static void SetOnMalloc(std::function<void(void)> f) { _f_malloc = f; } static void SetOnFree(std::function<void(void)> f) { _f_free = f; } private: static bool _is_enabled; static bool _throw_on_malloc; static bool _throw_on_free; static std::function<void(void)> _f_malloc; static std::function<void(void)> _f_free; }; bool MallocFinder::_is_enabled = false; bool MallocFinder::_throw_on_malloc = false; bool MallocFinder::_throw_on_free = false; std::function<void(void)> MallocFinder::_f_malloc = [](){ printf("Malloc was called!\n");}; std::function<void(void)> MallocFinder::_f_free = [](){ printf("Free was called!\n");}; } } /* Declare a function pointer into which we will store the default malloc */ static void * (* prev_malloc_hook)(size_t, const void *); static void (* prev_free_hook)(void *, const void *); /* Ignore deprecated __malloc_hook */ #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wdeprecated-declarations" static void * testing_malloc(size_t size, const void * caller); static void testing_free(void * addr, const void * caller); class MallocHookGuard { public: MallocHookGuard() { __malloc_hook = prev_malloc_hook; __free_hook = prev_free_hook; } ~MallocHookGuard() { __malloc_hook = testing_malloc; __free_hook = testing_free; } }; /* Custom malloc */ static void * testing_malloc(size_t size, const void * caller) { (void)caller; /* Set the malloc implementation to the default malloc hook so that we can call it * (otherwise, infinite recursion) */ MallocHookGuard hook_guard; if (XBot::Utils::MallocFinder::IsEnabled()) { XBot::Utils::MallocFinder::OnMalloc(); if(XBot::Utils::MallocFinder::ThrowsOnMalloc()) { throw std::runtime_error("ThrowOnMalloc is enabled"); } } // Execute the requested malloc. void * mem = malloc(size); // Set the malloc hook back to this function, so that we can intercept future mallocs. return mem; } /* Custom free */ static void testing_free(void * addr, const void * caller) { (void)caller; /* Set the malloc implementation to the default malloc hook so that we can call it * (otherwise, infinite recursion) */ __free_hook = prev_free_hook; if (XBot::Utils::MallocFinder::IsEnabled()) { XBot::Utils::MallocFinder::OnFree(); if(XBot::Utils::MallocFinder::ThrowsOnFree()) { throw std::runtime_error("ThrowOnFree is enabled"); } } // Execute the requested malloc. free(addr); // Set the malloc hook back to this function, so that we can intercept future mallocs. __free_hook = testing_free; } /// Function to be called when the malloc hook is initialized. void init_malloc_hook() { // Store the default malloc. prev_malloc_hook = __malloc_hook; prev_free_hook = __free_hook; // Set our custom malloc to the malloc hook. __malloc_hook = testing_malloc; __free_hook = testing_free; } #pragma GCC diagnostic pop /// Set the hook for malloc initialize so that init_malloc_hook gets called. void(*volatile __malloc_initialize_hook)(void) = init_malloc_hook; #endif
[ "arturo.laurenzi@iit.it" ]
arturo.laurenzi@iit.it
f002df229d9b91f81d10fa6b6f78a41843ef53d4
e157690a1cbf4ba86a61f873ea8cadcb8dd39f10
/src/matrix.cxx
2b1fc463bf29e7ae3365cb7638bd7fe2c73e4cff
[]
no_license
mollios/clustering
8792920705f958a014143d92e33920bf20a1169e
5af88d45a8465858980f44e6fa7c50913242ae87
refs/heads/master
2021-07-12T15:46:34.810127
2021-04-15T10:39:05
2021-04-15T10:39:05
243,174,558
0
0
null
null
null
null
UTF-8
C++
false
false
9,088
cxx
#include<iostream> #include<cstdlib> #include<cmath> #include"vector.h" #include"matrix.h" Matrix::Matrix(int rows, int cols) try : Rows(rows), Element(new Vector[Rows]){ for(int i=0;i<Rows;i++){ Element[i]=Vector(cols); } } catch(std::bad_alloc){ std::cerr << "Out of Memory" << std::endl; throw; } Matrix::Matrix(int dim, const char *s) try : Rows(dim), Element(new Vector[Rows]){ if(strcmp(s, "I")!=0){ std::cerr << "Invalid string parameter" << std::endl; exit(1); } for(int i=0;i<Rows;i++){ Element[i]=Vector(dim); } for(int i=0;i<Rows;i++){ for(int j=0;j<Rows;j++){ Element[i][j]=0.0; } Element[i][i]=1.0; } } catch(std::bad_alloc){ std::cerr << "Out of Memory" << std::endl; throw; } Matrix::Matrix(const Vector &arg, const char *s) try : Rows(arg.size()), Element(new Vector[Rows]){ if(strcmp(s, "diag")!=0){ std::cerr << "Invalid string parameter" << std::endl; exit(1); } for(int i=0;i<Rows;i++){ Element[i]=Vector(Rows); } for(int i=0;i<Rows;i++){ for(int j=0;j<Rows;j++){ Element[i][j]=0.0; } Element[i][i]=arg[i]; } } catch(std::bad_alloc){ std::cerr << "Out of Memory" << std::endl; throw; } Matrix::~Matrix(void){ delete []Element; } Matrix::Matrix(const Matrix &arg) try : Rows(arg.Rows), Element(new Vector[Rows]){ for(int i=0;i<Rows;i++){ Element[i]=arg.Element[i]; } } catch(std::bad_alloc){ std::cerr << "Out of Memory" << std::endl; throw; } Matrix::Matrix(Matrix &&arg) : Rows(arg.Rows), Element(arg.Element){ arg.Rows=0; arg.Element=nullptr; } Matrix &Matrix::operator=(Matrix &&arg){ if(this==&arg){ return *this; } else{ Rows=arg.Rows; Element=arg.Element; arg.Rows=0; arg.Element=nullptr; return *this; } } Matrix &Matrix::operator=(const Matrix &arg){ if(this==&arg) return *this; //Rows=arg.Rows;ここではRowsを更新してはいけない if(this->Rows != arg.Rows || this->cols() != arg.cols()){ Rows=arg.Rows; delete []Element; try{ Element=new Vector[Rows]; } catch(std::bad_alloc){ std::cerr << "Out of Memory" << std::endl; throw; } } for(int i=0;i<Rows;i++){ Element[i]=arg.Element[i]; } return *this; } int Matrix::rows(void) const{ return Rows; } int Matrix::cols(void) const{ return Element[0].size(); } Vector Matrix::operator[](int index) const{ return Element[index]; } Vector &Matrix::operator[](int index){ return Element[index]; } Matrix Matrix::operator+(void) const{ return *this; } Matrix Matrix::operator-(void) const{ Matrix result=*this; for(int i=0;i<result.Rows;i++){ result[i]=-1.0*result[i]; } return result; } Matrix &Matrix::operator+=(const Matrix &rhs){ if(rhs.Rows==0){ std::cout << "Rows 0" << std::endl; exit(1); } else if(Rows!=rhs.Rows){ std::cout << "Rows Unmatched" << std::endl; exit(1); } else{ for(int i=0;i<Rows;i++){ Element[i]+=rhs[i]; } } return *this; } Matrix &Matrix::operator-=(const Matrix &rhs){ if(rhs.Rows==0){ std::cout << "Rows 0" << std::endl; exit(1); } else if(Rows!=rhs.Rows){ std::cout << "Rows Unmatched" << std::endl; exit(1); } else{ for(int i=0;i<Rows;i++){ Element[i]-=rhs[i]; } } return *this; } Matrix operator+(const Matrix &lhs, const Matrix &rhs){ Matrix result=lhs; return result+=rhs; } Matrix operator-(const Matrix &lhs, const Matrix &rhs){ Matrix result=lhs; return result-=rhs; } Matrix operator*(double lhs, const Matrix &rhs){ if(rhs.rows()==0){ std::cout << "Rows 0" << std::endl; exit(1); } Matrix result=rhs; for(int i=0;i<result.rows();i++){ result[i]=lhs*result[i]; } return result; } Matrix &Matrix::operator/=(double rhs){ for(int i=0;i<Rows;i++){ Element[i]/=rhs; } return *this; } Matrix operator/(const Matrix &lhs, double rhs){ Matrix result(lhs); return result/=rhs; } std::ostream &operator<<(std::ostream &os, const Matrix &rhs){ os << "("; if(rhs.rows()>0){ for(int i=0;;i++){ os << rhs[i]; if(i>=rhs.rows()-1) break; os << "\n"; } } os << ')'; return os; } bool operator==(const Matrix &lhs, const Matrix &rhs){ if(lhs.rows()!=rhs.rows()) return false; for(int i=0;i<lhs.rows();i++){ if(lhs[i]!=rhs[i]) return false; } return true; } double abssum(const Vector &arg){ double result=fabs(arg[0]); for(int i=1;i<arg.size();i++){ result+=fabs(arg[i]); } return result; } double max_norm(const Matrix &arg){ if(arg.rows()<1){ std::cout << "Can't calculate norm for 0-sized vector" << std::endl; exit(1); } double result=abssum(arg[0]); for(int i=1;i<arg.rows();i++){ double tmp=abssum(arg[i]); if(result<tmp) result=tmp; } return result; } double frobenius_norm(const Matrix &arg){ double result=0.0; for(int i=0;i<arg.rows();i++){ for(int j=0;j<arg.cols();j++){ result+=arg[i][j]*arg[i][j]; }} return sqrt(result); } Vector operator*(const Matrix &lhs, const Vector &rhs){ if(lhs.rows()<1 || lhs.cols()<1 || rhs.size()<1 || lhs.cols()!=rhs.size()){ std::cout << "operator*(const Matrix &, const Vector &):"; std::cout << "Can't calculate innerproduct "; std::cout << "for 0-sized vector "; std::cout << "or for different sized vector:"; std::cout << "lhs.Cols=" << lhs.cols() << ", "; std::cout << "lhs.Rows=" << lhs.rows() << ", "; std::cout << "rhs.Size=" << rhs.size(); std::cout << std::endl; exit(1); } Vector result(lhs.rows()); for(int i=0;i<lhs.rows();i++){ result[i]=lhs[i]*rhs; } return result; } Matrix operator*(const Matrix &lhs, const Matrix &rhs){ if(lhs.rows()<1 || rhs.cols()<1 || lhs.cols()!=rhs.rows()){ std::cout << "Can't calculate innerproduct"; std::cout << "for 0-sized vector"; std::cout << "or for different sized vector"; std::cout << std::endl; exit(1); } Matrix result(lhs.rows(), rhs.cols()); for(int i=0;i<result.rows();i++){ for(int j=0;j<result.cols();j++){ result[i][j]=0.0; for(int k=0;k<lhs.cols();k++){ result[i][j]+=lhs[i][k]*rhs[k][j]; } }} return result; } Matrix Matrix::sub(int row_begin, int row_end, int col_begin, int col_end) const{ if(row_end<row_begin || col_end<col_begin){ std::cerr << "Matrix::sub:invalid parameter" << std::endl; std::cerr << "row_begin:" << row_begin << std::endl; std::cerr << "row_end:" << row_end << std::endl; std::cerr << "col_begin:" << col_begin << std::endl; std::cerr << "col_end:" << col_end << std::endl; exit(1); } if(row_end>=this->rows() || col_end>=this->cols()){ std::cerr << "Matrix::sub:invalid parameter" << std::endl; std::cerr << "row_end:" << row_end << std::endl; std::cerr << "Rows:" << this->rows() << std::endl; std::cerr << "col_end:" << col_end << std::endl; std::cerr << "Cols:" << this->cols() << std::endl; exit(1); } if(row_begin<0 || col_begin<0){ std::cerr << "Matrix::sub:invalid parameter" << std::endl; std::cerr << "row_begin:" << row_begin << std::endl; std::cerr << "col_begin:" << col_begin << std::endl; exit(1); } Matrix result(row_end-row_begin+1, col_end-col_begin+1); for(int i=0;i<result.rows();i++){ for(int j=0;j<result.cols();j++){ result[i][j]=Element[i+row_begin][j+col_begin]; }} return result; } void Matrix::set_sub(int row_begin, int row_end, int col_begin, int col_end, const Matrix &arg){ if(row_end<row_begin || col_end<col_begin){ std::cerr << "Matrix::sub:invalid parameter" << std::endl; exit(1); } for(int i=row_begin;i<=row_end;i++){ for(int j=col_begin;j<=col_end;j++){ Element[i][j]=arg[i-row_begin][j-col_begin]; }} return; } Matrix transpose(const Matrix &arg){ Matrix result(arg.cols(), arg.rows()); for(int i=0;i<result.rows();i++){ for(int j=0;j<result.cols();j++){ result[i][j]=arg[j][i]; }} return result; } Vector diag(const Matrix &arg){ if(arg.rows()!=arg.cols()){ std::cerr << "No Diag" << std::endl; exit(1); } Vector result(arg.rows()); for(int i=0;i<result.size();i++){ result[i]=arg[i][i]; } return result; } Matrix pow(const Matrix &arg, double power){ Matrix result(arg); for(int i=0;i<result.rows();i++){ for(int j=0;j<result.cols();j++){ result[i][j]=pow(result[i][j],power); }} return result; } Matrix transpose(const Vector &arg){ Matrix result(1, arg.size()); for(int j=0;j<result.cols();j++){ result[0][j]=arg[j]; } return result; } Matrix operator*(const Vector &lhs, const Matrix &rhs){ if(rhs.rows()!=1){ std::cerr << "Size unmatched for Vector*Matrix:" << rhs.rows() << ":" << rhs.cols() << std::endl; exit(1); } Matrix result(lhs.size(), rhs.cols()); for(int i=0;i<result.rows();i++){ for(int j=0;j<result.cols();j++){ result[i][j]=lhs[i]*rhs[0][j]; }} return result; }
[ "ma20096@shibaura-it.ac.jp" ]
ma20096@shibaura-it.ac.jp
7aea823a59b8765db5fc58b47d9e74c6fa74ccef
d6c08c1fad41043734f592a5f3e3cca77ff37de3
/src/Token.cpp
82e16243c75b78057240877d7d765731bcf02004
[]
no_license
hstowasser/CompilerProjectV2
c2b547056f3b96dbe70cfa84361619aa78d13225
efe1bbd8c656312a8ff3a1439ff083e1632fee1a
refs/heads/main
2023-03-25T14:10:37.753968
2021-03-28T17:09:02
2021-03-28T17:09:02
340,529,656
0
0
null
null
null
null
UTF-8
C++
false
false
6,055
cpp
#include "Token.hpp" #include <stdio.h> const char * token_type_to_string(token_type_e token_type) { switch (token_type){ case T_IDENTIFIER: return "T_IDENTIFIER"; case T_EOF: return "T_EOF"; case T_SYM_LPAREN: return "T_SYM_LPAREN"; case T_SYM_RPAREN: return "T_SYM_RPAREN"; case T_SYM_LBRACE: return "T_SYM_LBRACE"; case T_SYM_RBRACE: return "T_SYM_RBRACE"; case T_SYM_LBRACKET: return "T_SYM_LBRACKET"; case T_SYM_RBRACKET: return "T_SYM_RBRACKET"; case T_SYM_SEMICOLON: return "T_SYM_SEMICOLON"; case T_SYM_COLON: return "T_SYM_COLON"; case T_SYM_PERIOD: return "T_SYM_PERIOD"; case T_SYM_COMMA: return "T_SYM_COMMA"; case T_OP_BITW_AND: return "T_OP_BITW_AND"; case T_OP_BITW_OR: return "T_OP_BITW_OR"; // case T_OP_BITW_NOT: // return "T_OP_BITW_NOT"; case T_OP_ASIGN_EQUALS: return "T_OP_ASIGN_EQUALS"; case T_OP_TERM_MULTIPLY: return "T_OP_TERM_MULTIPLY"; case T_OP_TERM_DIVIDE: return "T_OP_TERM_DIVIDE"; case T_OP_REL_GREATER: return "T_OP_REL_GREATER"; case T_OP_REL_LESS: return "T_OP_REL_LESS"; case T_OP_REL_GREATER_EQUAL: return "T_OP_REL_GREATER_EQUAL"; case T_OP_REL_LESS_EQUAL: return "T_OP_REL_LESS_EQUAL"; case T_OP_REL_EQUAL: return "T_OP_REL_EQUAL"; case T_OP_REL_NOT_EQUAL: return "T_OP_REL_NOT_EQUAL"; case T_OP_ARITH_PLUS: return "T_OP_ARITH_PLUS"; case T_OP_ARITH_MINUS: return "T_OP_ARITH_MINUS"; case T_CONST_INTEGER: return "T_CONST_INTEGER"; case T_CONST_FLOAT: return "T_CONST_FLOAT"; case T_CONST_STRING: return "T_CONST_STRING"; case T_RW_PROGRAM: return "T_RW_PROGRAM"; case T_RW_IS: return "T_RW_IS"; case T_RW_BEGIN: return "T_RW_BEGIN"; case T_RW_END: return "T_RW_END"; case T_RW_GLOBAL: return "T_RW_GLOBAL"; case T_RW_INTEGER: return "T_RW_INTEGER"; case T_RW_FLOAT: return "T_RW_FLOAT"; case T_RW_STRING: return "T_RW_STRING"; case T_RW_BOOL: return "T_RW_BOOL"; //case T_RW_ENUM: // return "T_RW_ENUM"; case T_RW_PROCEDURE: return "T_RW_PROCEDURE"; case T_RW_VARIABLE: return "T_RW_VARIABLE"; case T_RW_IF: return "T_RW_IF"; case T_RW_THEN: return "T_RW_THEN"; case T_RW_ELSE: return "T_RW_ELSE"; case T_RW_FOR: return "T_RW_FOR"; case T_RW_RETURN: return "T_RW_RETURN"; case T_RW_NOT: return "T_RW_NOT"; // case T_RW_TYPE: // return "T_RW_TYPE"; case T_RW_TRUE: return "T_RW_TRUE"; case T_RW_FALSE: return "T_RW_FALSE"; default: return "T_UNKNOWN"; } } void print_token(token_t token) { printf("Type: %s Line: %d ", token_type_to_string(token.type), token.line_num); if ( token.type == T_IDENTIFIER || token.type == T_CONST_STRING){ printf("value: %s", token.getStringValue()->c_str()); }else if ( token.type == T_CONST_INTEGER) { printf("integer value: %d", token.getIntValue()); }else if ( token.type == T_CONST_FLOAT) { printf("float value: %f", token.getFloatValue()); } printf("\n"); } token_t::token_t() { this->line_num = 0; this->type = T_UNKNOWN; this->_value = NULL; this->tag = NULL; this->value_type = NONE; } token_t::~token_t() { } void token_t::destroy() { if ( this->value_type == INT || this->value_type == FLOAT){ free(this->_value); }else if ( this->value_type == STRING){ delete (std::string*)(this->_value); } } void token_t::setValue(std::string value) { if ( this->_value == NULL){ this->_value = (void*) new std::string(value); this->value_type = STRING; this->tag = (void*)this; } } void token_t::setValue(int value) { if ( this->_value == NULL){ this->_value = malloc(sizeof(int)); if ( this->_value != NULL){ *((int*)this->_value) = value; this->value_type = INT; this->tag = (void*)this; } } } void token_t::setValue(float value) { if ( this->_value == NULL){ this->_value = malloc(sizeof(float)); if ( this->_value != NULL){ *((float*)this->_value) = value; this->value_type = FLOAT; this->tag = (void*)this; } } } std::string* token_t::getStringValue() { if (this->value_type == STRING){ return (std::string*)this->_value; }else{ //return ""; // Error return NULL; } } int token_t::getIntValue() { if (this->value_type == INT){ return *((int*)this->_value); }else{ return 0; // Error } } float token_t::getFloatValue() { if (this->value_type == FLOAT){ return *((float*)this->_value); }else{ return 0; // Error } }
[ "stowasserheiko@gmail.com" ]
stowasserheiko@gmail.com
e7a5585209c4f2428ca85fc55d59feb8a1c0482b
b844c8d51fac1148363967993fb3299dcb47164d
/Individual.h
5a62f53dfb18aee3e2d92b348acae672317871fa
[]
no_license
patyhaizer/brkga
1470fcbc39187ce0b52a1ed2692c7bcb3a840601
3642fc64dbe72e920461d2929b143ea7df54e05c
refs/heads/master
2021-01-15T17:41:26.636794
2015-08-31T23:39:38
2015-08-31T23:39:38
37,101,820
0
0
null
null
null
null
UTF-8
C++
false
false
371
h
#ifndef INDIVIDUAL_H #define INDIVIDUAL_H class Individual { private: Individual(); Individual(const Individual& other); Individual operator=(const Individual& other); public: explicit Individual(unsigned chromossomeSize); ~Individual(); double * m_chromossome; double m_fitness; unsigned m_chromossomeSize; }; #endif // INDIVIDUAL_H
[ "paty.haizer@gmail.com" ]
paty.haizer@gmail.com
eeec16e423dba54c128128d875387601b6b39188
6c78ebd8f7a91957f84e260bf4640e76b8d665e7
/src/threading/WindowsThread.cpp
45dde2fb69e46ff5d3a9573a11d524049d861332
[ "MIT" ]
permissive
TheCoderRaman/nCine
b74728783e34151b4276e2fb303d605602ca78ba
a35f9898cc754a9c1f3c82d8e505160571cb4cf6
refs/heads/master
2023-08-28T14:57:43.613194
2019-05-30T19:16:32
2019-06-14T16:31:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,843
cpp
#include "common_macros.h" #include "Thread.h" namespace ncine { /////////////////////////////////////////////////////////// // PUBLIC FUNCTIONS /////////////////////////////////////////////////////////// void ThreadAffinityMask::zero() { affinityMask_ = 0LL; } void ThreadAffinityMask::set(int cpuNum) { affinityMask_ |= 1LL << cpuNum; } void ThreadAffinityMask::clear(int cpuNum) { affinityMask_ &= ~(1LL << cpuNum); } bool ThreadAffinityMask::isSet(int cpuNum) { return ((affinityMask_ >> cpuNum) & 1LL) != 0; } /////////////////////////////////////////////////////////// // CONSTRUCTORS and DESTRUCTOR /////////////////////////////////////////////////////////// Thread::Thread() : handle_(0) { } Thread::Thread(ThreadFunctionPtr startFunction, void *arg) : handle_(0) { run(startFunction, arg); } /////////////////////////////////////////////////////////// // PUBLIC FUNCTIONS /////////////////////////////////////////////////////////// unsigned int Thread::numProcessors() { unsigned int numProcs = 0; SYSTEM_INFO si; GetSystemInfo(&si); numProcs = si.dwNumberOfProcessors; return numProcs; } void Thread::run(ThreadFunctionPtr startFunction, void *arg) { if (handle_ == 0) { threadInfo_.startFunction = startFunction; threadInfo_.threadArg = arg; handle_ = reinterpret_cast<HANDLE>(_beginthreadex(nullptr, 0, wrapperFunction, &threadInfo_, 0, nullptr)); FATAL_ASSERT_MSG(handle_, "Error in _beginthreadex()"); } else LOGW_X("Thread %u is already running", handle_); } void *Thread::join() { WaitForSingleObject(handle_, INFINITE); return nullptr; } long int Thread::self() { return GetCurrentThreadId(); } void Thread::exit(void *retVal) { _endthreadex(0); *static_cast<unsigned int *>(retVal) = 0; } void Thread::yieldExecution() { Sleep(0); } void Thread::cancel() { TerminateThread(handle_, 0); } ThreadAffinityMask Thread::affinityMask() const { ThreadAffinityMask affinityMask; if (handle_ != 0) { // A neutral value for the temporary mask DWORD_PTR allCpus = ~(allCpus & 0); affinityMask.affinityMask_ = SetThreadAffinityMask(handle_, allCpus); SetThreadAffinityMask(handle_, affinityMask.affinityMask_); } else LOGW("Cannot get the affinity for a thread that has not been created yet"); return affinityMask; } void Thread::setAffinityMask(ThreadAffinityMask affinityMask) { if (handle_ != 0) SetThreadAffinityMask(handle_, affinityMask.affinityMask_); else LOGW("Cannot set the affinity mask for a not yet created thread"); } /////////////////////////////////////////////////////////// // PRIVATE FUNCTIONS /////////////////////////////////////////////////////////// unsigned int Thread::wrapperFunction(void *arg) { ThreadInfo *threadInfo = static_cast<ThreadInfo *>(arg); threadInfo->startFunction(threadInfo->threadArg); return 0; } }
[ "encelo@gmail.com" ]
encelo@gmail.com
803302ab96bf04ea0b55a8ff90a18dbb73c20a72
8b552e2a83aefe6546a8d492b101cea675c05a63
/assignment9(glut)/parser.h
14724c75ce7bd9a915f78faab22c7dacce22237e
[]
no_license
Dream4Leo/6.837-MIT04Fall-Assignments
4d1c416f452286282b8922b2ee3afdc7176ae72a
68f945b2f0be83d367b053f4c128c7c74d5ffed8
refs/heads/master
2020-06-16T22:07:28.352960
2019-10-05T02:40:49
2019-10-05T02:40:49
195,717,287
1
0
null
null
null
null
UTF-8
C++
false
false
9,279
h
#ifndef _PARSER_H_ #define _PARSER_H_ #include <assert.h> #include "vectors.h" #include "system.h" #include "generator.h" #include "integrator.h" #include "forcefield.h" // ==================================================================== // ==================================================================== #define MAX_PARSER_TOKEN_LENGTH 100 class System; class Generator; class Integrator; class ForceField; // ==================================================================== // ==================================================================== // parse the particle system file class Parser { public: // CONSTRUCTOR & DESTRUCTOR Parser(const char *file); ~Parser(); // ACCESSORS int getNumSystems() { return num_systems; } System* getSystem(int i) { assert (i >= 0 && i < num_systems); return systems[i]; } private: // don't use this constructor Parser() { assert(0); } // HELPER FUNCTIONS System* ParseSystem(); Generator* ParseGenerator(); Integrator* ParseIntegrator(); ForceField* ParseForceField(); // UTILITY FUNCTIONS int getToken(char token[MAX_PARSER_TOKEN_LENGTH]); Vec3f readVec3f(); Vec2f readVec2f(); float readFloat(); int readInt(); // REPRESENTATION int num_systems; System **systems; FILE *file; }; // ==================================================================== // ==================================================================== Parser::Parser(const char *filename) { // open the file for reading assert (filename != NULL); file = fopen(filename,"r"); assert (file != NULL); char token[MAX_PARSER_TOKEN_LENGTH]; // read in the number of particles in this file getToken(token); assert (!strcmp(token,"num_systems")); num_systems = readInt(); systems = new (System*)[num_systems]; // read the systems for (int i = 0; i < num_systems; i++) { System *s = ParseSystem(); assert (s != NULL); systems[i] = s; } fclose(file); } Parser::~Parser() { // cleanup for (int i = 0; i < num_systems; i++) { delete systems[i]; } delete [] systems; } // ==================================================================== System* Parser::ParseSystem() { char token[MAX_PARSER_TOKEN_LENGTH]; getToken(token); assert (!strcmp(token,"system")); Generator *generator = ParseGenerator(); Integrator *integrator = ParseIntegrator(); ForceField *forcefield = ParseForceField(); return new System(generator, integrator, forcefield); } // ==================================================================== // ==================================================================== // ==================================================================== Generator* Parser::ParseGenerator() { // read the generator type char type[MAX_PARSER_TOKEN_LENGTH]; getToken(type); // generator variable defaults Vec3f position = Vec3f(0,0,0); float position_randomness = 0; Vec3f velocity = Vec3f(0,0,0); float velocity_randomness = 0; Vec3f color = Vec3f(1,1,1); Vec3f dead_color = Vec3f(1,1,1); float color_randomness = 0; float mass = 1; float mass_randomness = 0; float lifespan = 10; float lifespan_randomness = 0; int desired_num_particles = 1000; int grid = 10; float ring_velocity = 1; // read the provided values char token[MAX_PARSER_TOKEN_LENGTH]; getToken(token); assert (!strcmp(token,"{")); while (1) { getToken(token); if (!strcmp(token,"position")) { position = readVec3f(); } else if (!strcmp(token,"position_randomness")) { position_randomness = readFloat(); } else if (!strcmp(token,"velocity")) { velocity = readVec3f(); } else if (!strcmp(token,"velocity_randomness")) { velocity_randomness = readFloat(); } else if (!strcmp(token,"color")) { color = readVec3f(); dead_color = color; } else if (!strcmp(token,"dead_color")) { dead_color = readVec3f(); } else if (!strcmp(token,"color_randomness")) { color_randomness = readFloat(); } else if (!strcmp(token,"mass")) { mass = readFloat(); } else if (!strcmp(token,"mass_randomness")) { mass_randomness = readFloat(); } else if (!strcmp(token,"lifespan")) { lifespan = readFloat(); } else if (!strcmp(token,"lifespan_randomness")) { lifespan_randomness = readFloat(); } else if (!strcmp(token,"desired_num_particles")) { desired_num_particles = readInt(); } else if (strcmp(token,"}")) { printf ("ERROR unknown generator token %s\n", token); assert(0); } else { break; } } // create the appropriate generator Generator *answer = NULL; if (!strcmp(type,"hose_generator")) { answer = new HoseGenerator(position,position_randomness, velocity,velocity_randomness); } else if (!strcmp(type,"ring_generator")) { answer = new RingGenerator(position_randomness,velocity,velocity_randomness); } else { printf ("WARNING: unknown generator type '%s'\n", type); printf ("WARNING: unknown generator type '%s'\n", type); } // set the common generator parameters assert (answer != NULL); answer->SetColors(color,dead_color,color_randomness); answer->SetMass(mass,mass_randomness); answer->SetLifespan(lifespan,lifespan_randomness,desired_num_particles); return answer; } // ==================================================================== // ==================================================================== // ==================================================================== Integrator* Parser::ParseIntegrator() { // read the integrator type char type[MAX_PARSER_TOKEN_LENGTH]; getToken(type); // there are no variables char token[MAX_PARSER_TOKEN_LENGTH]; getToken(token); assert(!strcmp(token,"{")); getToken(token); assert(!strcmp(token,"}")); // create the appropriate integrator Integrator *answer = NULL; if (!strcmp(type,"euler_integrator")) { answer = new EulerIntegrator(); } else if (!strcmp(type,"midpoint_integrator")) { answer = new MidpointIntegrator(); } else if (!strcmp(type,"rungekutta_integrator")) { answer = new RungeKuttaIntegrator(); } else { printf ("WARNING: unknown integrator type '%s'\n", type); } assert (answer != NULL); return answer; } // ==================================================================== // ==================================================================== // ==================================================================== ForceField* Parser::ParseForceField() { // read the forcefield type char type[MAX_PARSER_TOKEN_LENGTH]; getToken(type); // forcefield variable defaults Vec3f gravity = Vec3f(0,0,0); Vec3f force = Vec3f(0,0,0); float magnitude = 1; // read the provided values char token[MAX_PARSER_TOKEN_LENGTH]; getToken(token); assert (!strcmp(token,"{")); while (1) { getToken(token); if (!strcmp(token,"gravity")) { gravity = readVec3f(); } else if (!strcmp(token,"force")) { force = readVec3f(); } else if (!strcmp(token,"magnitude")) { magnitude = readFloat(); } else if (strcmp(token,"}")) { printf ("ERROR unknown gravity token %s\n", token); assert(0); } else { break; } } // create the appropriate force field ForceField *answer = NULL; if (!strcmp(type,"gravity_forcefield")) { answer = new GravityForceField(gravity); } else if (!strcmp(type,"constant_forcefield")) { answer = new ConstantForceField(force); } else if (!strcmp(type,"radial_forcefield")) { answer = new RadialForceField(magnitude); } else if (!strcmp(type,"vertical_forcefield")) { answer = new VerticalForceField(magnitude); } else if (!strcmp(type,"wind_forcefield")) { answer = new WindForceField(magnitude); } else { printf ("WARNING: unknown forcefield type '%s'\n", type); } assert (answer != NULL); return answer; } // ==================================================================== // ==================================================================== // HELPER FUNCTIONS int Parser::getToken(char token[MAX_PARSER_TOKEN_LENGTH]) { // for simplicity, tokens must be separated by whitespace assert (file != NULL); int success = fscanf(file,"%s ",token); if (success == EOF) { token[0] = '\0'; return 0; } return 1; } Vec3f Parser::readVec3f() { float x,y,z; int count = fscanf(file,"%f %f %f",&x,&y,&z); if (count != 3) { printf ("Error trying to read 3 floats to make a Vec3f\n"); assert (0); } return Vec3f(x,y,z); } Vec2f Parser::readVec2f() { float u,v; int count = fscanf(file,"%f %f",&u,&v); if (count != 2) { printf ("Error trying to read 2 floats to make a Vec2f\n"); assert (0); } return Vec2f(u,v); } float Parser::readFloat() { float answer; int count = fscanf(file,"%f",&answer); if (count != 1) { printf ("Error trying to read 1 float\n"); assert (0); } return answer; } int Parser::readInt() { int answer; int count = fscanf(file,"%d",&answer); if (count != 1) { printf ("Error trying to read 1 int\n"); assert (0); } return answer; } // ==================================================================== #endif
[ "3180102688@zju.edu.cn" ]
3180102688@zju.edu.cn
1598acb4f2925e3f8f70581afd8be1be06b2a311
cb53a0cff7733bc8f5c70597009580287543bb72
/AutoSave/2010/inc/acuiComboBox.h
b73077f95c7fa1dd09d6d02a53c6872ec10c9048
[ "MIT" ]
permissive
15831944/AllDemo
d23b900f15fe4b786577f60d03a7b72b8dc8bf09
fe4f56ce91afc09e034ddc80769adf9cc5daef81
refs/heads/master
2023-03-15T20:49:15.385750
2014-08-27T07:42:24
2014-08-27T07:42:24
null
0
0
null
null
null
null
UTF-8
C++
false
false
30,606
h
////////////////////////////////////////////////////////////////////////////// // // (C) Copyright 1994-2009 by Autodesk, Inc. // // Permission to use, copy, modify, and distribute this software in // object code form for any purpose and without fee is hereby granted, // provided that the above copyright notice appears in all copies and // that both that copyright notice and the limited warranty and // restricted rights notice below appear in all supporting // documentation. // // AUTODESK PROVIDES THIS PROGRAM "AS IS" AND WITH ALL FAULTS. // AUTODESK SPECIFICALLY DISCLAIMS ANY IMPLIED WARRANTY OF // MERCHANTABILITY OR FITNESS FOR A PARTICULAR USE. AUTODESK, INC. // DOES NOT WARRANT THAT THE OPERATION OF THE PROGRAM WILL BE // UNINTERRUPTED OR ERROR FREE. // // Use, duplication, or disclosure by the U.S. Government is subject to // restrictions set forth in FAR 52.227-19 (Commercial Computer // Software - Restricted Rights) and DFAR 252.227-7013(c)(1)(ii) // (Rights in Technical Data and Computer Software), as applicable. // ////////////////////////////////////////////////////////////////////////////// #ifndef _acuiComboBox_h #define _acuiComboBox_h #pragma pack (push, 8) #if _MSC_VER >= 1000 #pragma once #endif // _MSC_VER >= 1000 //prevent the MS header "use_ansi.h" from outputing //its linker directives, we expect clients to specify //what flavor (debug/release) of the C++ runtime they want to //link against. #pragma push_macro("_USE_ANSI_CPP") #define _USE_ANSI_CPP #include <map> #pragma pop_macro("_USE_ANSI_CPP") typedef std::map<int, AcCmColor*> AcCmColorTable; ///////////////////////////////////////////////////////////////////////////// // CAcUiComboBox window class ACUI_PORT CAcUiComboBox : public CAdUiComboBox { DECLARE_DYNAMIC(CAcUiComboBox); public: CAcUiComboBox (); virtual ~CAcUiComboBox (); // Subclassed EditBox and Validation public: CAcUiEdit *AcUiEditBox (); BOOL Validate (); ACUI_ERROR_CODE ValidateData (CString& x); void Convert (); BOOL ConvertData (CString& x); void SetRange (double vMin, double vMax); // ClassWizard-controlled public: //{{AFX_VIRTUAL(CAcUiComboBox) //}}AFX_VIRTUAL protected: //{{AFX_MSG(CAcUiComboBox) //}}AFX_MSG DECLARE_MESSAGE_MAP() }; ///////////////////////////////////////////////////////////////////////////// // CAcUiAngleComboBox window // // ComboBox with the persistent CAcUiAngleEdit control for the Edit box class ACUI_PORT CAcUiAngleComboBox : public CAcUiComboBox { DECLARE_DYNAMIC(CAcUiAngleComboBox); public: CAcUiAngleComboBox (); virtual ~CAcUiAngleComboBox (); // ClassWizard-controlled public: //{{AFX_VIRTUAL(CAcUiAngleComboBox) //}}AFX_VIRTUAL protected: //{{AFX_MSG(CAcUiAngleComboBox) //}}AFX_MSG DECLARE_MESSAGE_MAP() }; ///////////////////////////////////////////////////////////////////////////// // CAcUiNumericComboBox window // // ComboBox with the persistent CAcUiNumericEdit control for the Edit box class ACUI_PORT CAcUiNumericComboBox : public CAcUiComboBox { DECLARE_DYNAMIC(CAcUiNumericComboBox); public: CAcUiNumericComboBox (); virtual ~CAcUiNumericComboBox (); // ClassWizard-controlled public: //{{AFX_VIRTUAL(CAcUiNumericComboBox) //}}AFX_VIRTUAL protected: //{{AFX_MSG(CAcUiNumericComboBox) //}}AFX_MSG DECLARE_MESSAGE_MAP() }; ///////////////////////////////////////////////////////////////////////////// // CAcUiStringComboBox window // // ComboBox with the persistent CAcUiStringEdit control for the Edit box class ACUI_PORT CAcUiStringComboBox : public CAcUiComboBox { DECLARE_DYNAMIC(CAcUiStringComboBox); public: CAcUiStringComboBox (); virtual ~CAcUiStringComboBox (); // ClassWizard-controlled public: //{{AFX_VIRTUAL(CAcUiStringComboBox) //}}AFX_VIRTUAL protected: //{{AFX_MSG(CAcUiStringComboBox) //}}AFX_MSG DECLARE_MESSAGE_MAP() }; ///////////////////////////////////////////////////////////////////////////// // CAcUiSymbolComboBox window // // ComboBox with the persistent CAcUiSymbolEdit control for the Edit box class ACUI_PORT CAcUiSymbolComboBox : public CAcUiComboBox { DECLARE_DYNAMIC(CAcUiSymbolComboBox); public: CAcUiSymbolComboBox (); virtual ~CAcUiSymbolComboBox (); // ClassWizard-controlled public: //{{AFX_VIRTUAL(CAcUiSymbolComboBox) //}}AFX_VIRTUAL protected: //{{AFX_MSG(CAcUiSymbolComboBox) //}}AFX_MSG DECLARE_MESSAGE_MAP() }; ////////////////////////////////////////////////////////////////////////////// // MRU Prototypes #define ACUI_MAX_COMBOBOX_MRU 6 #define ACUI_MAX_TRUECOLOR_COMBOBOX_MRU 16 class ACUI_PORT CAcUiMRUComboBox; class ACUI_PORT CAcUiMRUListBox; typedef enum { kAcUiMRUCargo_Last = -106, // Make sure this is the last entry kAcUiMRUCargo_Option2 = -105, kAcUiMRUCargo_Option1 = -104, kAcUiMRUCargo_Other2 = -103, kAcUiMRUCargo_Other1 = -102, kAcUiMRUCargo_None = -101 } ACUI_MRU_CARGO; ////////////////////////////////////////////////////////////////////////////// // ComboLBox for MRU ComboBox - Provides DrawTip support class ACUI_PORT CAcUiMRUListBox : public CAcUiListBox { public: CAcUiMRUListBox (); virtual ~CAcUiMRUListBox (); // Misc. public: virtual void GetContentExtent ( int item, LPCTSTR text, int& width, int& height ); // AdUi message handler protected: virtual BOOL OnGetTipRect (CRect& r); // MRU control protected: int ExtraWidth (); CAcUiMRUComboBox *MRUComboBox (); // ClassWizard-controlled public: //{{AFX_VIRTUAL(CAcUiMRUListBox) //}}AFX_VIRTUAL protected: //{{AFX_MSG(CAcUiMRUListBox) //}}AFX_MSG DECLARE_MESSAGE_MAP() }; ////////////////////////////////////////////////////////////////////////////// // MRU ComboBox class ACUI_PORT CAcUiMRUComboBox : public CAcUiComboBox { public: CAcUiMRUComboBox (); virtual ~CAcUiMRUComboBox (); // Misc. virtual void GetContentExtent (LPCTSTR text, int& width, int& height); virtual BOOL GetItemColors(DRAWITEMSTRUCT& dis, COLORREF& fgColor, COLORREF& bgColor, COLORREF& fillColor); // AdUi message handler protected: virtual BOOL OnGetTipRect (CRect& r); // MRU control protected: BOOL m_bIsDynamicCreation : 1; // TRUE if Create() is used, else FALSE. BOOL m_bUseOption1 : 1; BOOL m_bUseOption2 : 1; BOOL m_bUseOther1 : 1; BOOL m_bUseOther2 : 1; BOOL m_bOther1Selected : 1; BOOL m_bOther2Selected : 1; int m_cargoOption1; int m_cargoOption2; LOGPALETTE* m_logPalette; HPALETTE m_hPalette; CPalette* m_pOldPalette; int m_itemHeight; int m_lastSelection; int m_mruCargo[ACUI_MAX_COMBOBOX_MRU]; int m_mruLen; CString m_mruName[ACUI_MAX_COMBOBOX_MRU]; virtual int CalcItemHeight (); // The methods below are subfunctions to support the virtual DrawItem(..) // method which is called via message handler OnDrawItem(..). Derived // classes may override the DrawItem(..) method and use these subfunctions // to customize the way DrawItemImage(..) is called. For example, the linetype // control does not use the cargo value as an index, thus it must replace // the cargo parameter of DrawItemImage(..) to instead pass the index of the // selection being drawn, then it's derived DrawItemImage(..) must resolve // that index to the object id of the linetype virtual void DrawItemImage (CDC& dc, CRect& r, INT_PTR cargo); void DrawItemImageFromCargo(CDC* dc, CRect& r, int i); void DrawTextAndFocusRect(LPDRAWITEMSTRUCT lpDrawItemStruct, CDC* dc, CRect& rItem, int i, COLORREF& fgColor, COLORREF& bgColor); void CreateAndSelectPalette (LPDRAWITEMSTRUCT lpDrawItemStruct, CDC* dc); void SetupForImageDraw(LPDRAWITEMSTRUCT lpDrawItemStruct, CDC* dc, CRect& rItem, CRect& rImage, COLORREF& fgColor, COLORREF& bgColor); void ResetAndRestorePalette(CDC* dc, int savedState); // end DrawItem(..) supporting methods BOOL FindCargoInMRU (int cargo); int GenerateCargoFromMRU (int seed); virtual BOOL GetOptionName (BOOL isOption2, CString& name); virtual BOOL GetOtherName (BOOL isOther2, CString& name); virtual void OnAddItems (); virtual void OnComboBoxInit (); virtual BOOL OnSelectOther (BOOL isOther2, int curSel, int& newSel); void SelectOther (BOOL isOther2); public: int AddItemToList (LPCTSTR name, INT_PTR cargo); int AddItemToMRU (LPCTSTR name, int cargo); // Returns item index (or -1). void AddItems (); virtual BOOL Create (DWORD dwStyle, const RECT& rect, CWnd* pParentWnd, UINT nID); virtual int ExtraWidth (); int FindItemByCargo (INT_PTR cargo); // Get corresponding item index. int GetCargoOption1 (); int GetCargoOption2 (); INT_PTR GetCurrentItemCargo (); // Get current item's cargo (or -1). INT_PTR GetItemCargo (int item); // Get item's cargo (or -1). LOGPALETTE *GetLogPalette (); HPALETTE GetPalette (); BOOL GetUseOption1 (); BOOL GetUseOption2 (); BOOL GetUseOther1 (); BOOL GetUseOther2 (); virtual int ImageWidth (); int InsertItemInList (int index, LPCTSTR name, INT_PTR cargo); int ItemHeight (); void RecalcHeight (); void RemoveItemFromMRU (int cargo); void SetCargoOption1 (int cargo); void SetCargoOption2 (int cargo); void SetLastSelection (int sel); void SetLogPalette (LOGPALETTE *logPalette); void SetPalette (HPALETTE hPalette); void SetUseOption1 (BOOL use); void SetUseOption2 (BOOL use); void SetUseOther1 (BOOL use); void SetUseOther2 (BOOL use); // Aliases for OptionX and OtherX public: BOOL GetUseByBlock (); BOOL GetUseByLayer (); BOOL GetUseOther (); BOOL GetUseWindows (); void SetUseByBlock (BOOL use); void SetUseByLayer (BOOL use); void SetUseOther (BOOL use); void SetUseWindows (BOOL use); // ClassWizard-controlled public: //{{AFX_VIRTUAL(CAcUiMRUComboBox) public: virtual void DrawItem(LPDRAWITEMSTRUCT lpDrawItemStruct); virtual void MeasureItem(LPMEASUREITEMSTRUCT lpMeasureItemStruct); protected: virtual void PreSubclassWindow(); virtual LRESULT WindowProc(UINT message, WPARAM wParam, LPARAM lParam); //}}AFX_VIRTUAL protected: //{{AFX_MSG(CAcUiMRUComboBox) afx_msg BOOL OnCloseUp(); afx_msg int OnCreate(LPCREATESTRUCT lpCreateStruct); afx_msg BOOL OnDropDown(); afx_msg BOOL OnSelEndOk(); //}}AFX_MSG DECLARE_MESSAGE_MAP() }; ////////////////////////////////////////////////////////////////////////////// class CAcUiLTypeRecord : public CObject { public: CString & ltypeName(); void setLTypeName(CString sName); AcDbObjectId objectId(); void setObjectId(AcDbObjectId id); BOOL isDependent(); void setIsDependent(BOOL bValue); private: CString m_strLTypeName; AcDbObjectId m_idObjectId; BOOL m_bIsDependent; }; ///////////////////////////////////////////////////////////////////////////// // Inlines for CAcUiLTypeRecord ///////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// inline CString& CAcUiLTypeRecord::ltypeName() { return m_strLTypeName; } inline void CAcUiLTypeRecord::setLTypeName(CString sName) { m_strLTypeName = sName; } inline AcDbObjectId CAcUiLTypeRecord::objectId() { return m_idObjectId; } inline void CAcUiLTypeRecord::setObjectId(AcDbObjectId id) { m_idObjectId = id; } inline BOOL CAcUiLTypeRecord::isDependent() { return m_bIsDependent; } inline void CAcUiLTypeRecord::setIsDependent(BOOL bValue) { m_bIsDependent = bValue; } ////////////////////////////////////////////////////////////////////////////// class ACUI_PORT CAcUiLineTypeComboBox : public CAcUiMRUComboBox { public: CAcUiLineTypeComboBox (); virtual ~CAcUiLineTypeComboBox (); virtual void OnComboBoxInit (); void AddItems (); // Get/Set AcDbObjectId of current selection AcDbObjectId getOIDSel(int sel); AcDbObjectId getOIDCurSel(); void setCurSelByOID(const AcDbObjectId& oidCurSel); bool isOtherSelected(); void forceSelectOther (BOOL isOther2); int getLastSelection(); bool getDbReload(); void setDbReload(bool bReload); void emptyLTypeLocalList(); protected: virtual void DrawItemImage (CDC& dc, CRect& r, INT_PTR cargo); virtual void OnAddItems (); virtual BOOL OnSelectOther (BOOL isOther2, int curSel, int& newSel); INT_PTR GetItemCargo (int item); // Cargo for this class is just the // combobox item index. That needs to // be resolved to the item data pointer // which is actually a CAcUiLTypeRecord // pointer, not an integer int FindItemByCargo (AcDbObjectId cargo); void LoadContentsFromDatabase(); void ShowLTypes(bool bForceReloadDB = false); int AddLTypeToControl(CAcUiLTypeRecord * pLTypeRecord); CAcUiLTypeRecord* CreateLTRecord(CString& cstrLTName, AcDbObjectId& oidLT); virtual int ImageWidth(); // Get/Set current DB pointer AcDbDatabase* getLTLocalMapDB(); void setLTLocalMapDB(AcDbDatabase* pDb); // Member data CObList m_LTypeLocalList; AcDbDatabase* m_pLTLocalMapDB; bool m_bDbReload; public: // ClassWizard-controlled public: //{{AFX_VIRTUAL(CAcUiLineTypeComboBox) virtual void DrawItem(LPDRAWITEMSTRUCT lpDrawItemStruct); //}}AFX_VIRTUAL protected: //{{AFX_MSG(CAcUiLineTypeComboBox) //}}AFX_MSG DECLARE_MESSAGE_MAP() }; // Test for and set whether to reload from the db or not inline bool CAcUiLineTypeComboBox::getDbReload() { return m_bDbReload; } inline void CAcUiLineTypeComboBox::setDbReload(bool bReload) { m_bDbReload = bReload; } // Test for the "Other" selection of the linetype combo inline void CAcUiLineTypeComboBox::forceSelectOther (BOOL isOther2) { SelectOther(isOther2); } inline int CAcUiLineTypeComboBox::getLastSelection() { return m_lastSelection; } inline bool CAcUiLineTypeComboBox::isOtherSelected() { CString otherName; CString curSelName; GetOtherName (false, otherName); GetLBText(GetCurSel(), curSelName); return curSelName == otherName; } // Get/Set AcDbObjectId of given selection inline AcDbObjectId CAcUiLineTypeComboBox::getOIDSel(int sel) { AcDbObjectId oidLT; CAcUiLTypeRecord* pLTRec = (CAcUiLTypeRecord*)(GetItemDataPtr(sel)); if (NULL != pLTRec) oidLT = pLTRec->objectId(); return oidLT; } // Get/Set AcDbObjectId of current selection inline AcDbObjectId CAcUiLineTypeComboBox::getOIDCurSel() { return getOIDSel(GetCurSel()); } inline void CAcUiLineTypeComboBox::setCurSelByOID(const AcDbObjectId& oidCurSel) { int i = FindItemByCargo(oidCurSel); SetCurSel(i >= 0 ? i : m_lastSelection); if (i >= 0) m_lastSelection = i; } ////////////////////////////////////////////////////////////////////////////// class ACUI_PORT CAcUiColorComboBox : public CAcUiMRUComboBox { public: CAcUiColorComboBox (); virtual ~CAcUiColorComboBox (); // MRU control protected: virtual void DrawItemImage (CDC& dc, CRect& r, INT_PTR cargo); virtual void OnAddItems (); virtual BOOL OnSelectOther (BOOL isOther2, int curSel, int& newSel); // Color control protected: int m_blockColorIndex; virtual BOOL GetOtherColorIndex ( int defaultColorIndex, int layerColorIndex, BOOL enableMetaColors, int& colorIndex ); virtual BOOL GetWindowsColor (COLORREF& color); virtual BOOL GetOtherName (BOOL isOther2, CString& name); void RGBFill (CDC& dc, CRect& rFill); public: int AddColorToMRU (int colorIndex); // Returns item index (or -1). int FindItemByColorIndex (int colorIndex); // Get corresponding item index. int GetBlockColorIndex (); virtual COLORREF GetColorFromIndex (int colorIndex); // Returns corresponding color. virtual int GetColorIndex (COLORREF color); // Returns color index (or -1). int GetCurrentItemColorIndex (); // Get current item's color index (or -1). virtual int GetCurrentLayerColorIndex (); int GetItemColorIndex (int item); // Get item's color index (or -1). virtual COLORREF LookupColor ( // Returns corresponding raw color. int colorIndex, LOGPALETTE *logPalette ); void SetBlockColorIndex (int colorIndex); // ClassWizard-controlled public: //{{AFX_VIRTUAL(CAcUiColorComboBox) //}}AFX_VIRTUAL protected: //{{AFX_MSG(CAcUiColorComboBox) //}}AFX_MSG DECLARE_MESSAGE_MAP() }; ////////////////////////////////////////////////////////////////////////////// #define ACUI_TRUECOLOR_COMBOBOX_TABLE_SIZE ACUI_MAX_TRUECOLOR_COMBOBOX_MRU + 9 class ACUI_PORT CAcUiTrueColorComboBox : public CAcUiMRUComboBox { public: enum ColorTableIndex { kCargoOption1 = 0, // index of byLayer kCargoOption2 = 1, // index of byBlock kCargoStockItem1 = 2, // index of Red kCargoStockItem2 = 3, // index of Yellow kCargoStockItem3 = 4, // index of Green kCargoStockItem4 = 5, // index of Cyan kCargoStockItem5 = 6, // index of Blue kCargoStockItem6 = 7, // index of Magenta kCargoStockItem7 = 8, // index of White kIndexOfFirstMRUItem = 9, // default newt table index kCargoOther1 = -1, // place holder for select color dialog kCargoOther2 = -2, // place holder for windows dialog kLastIndex = ACUI_TRUECOLOR_COMBOBOX_TABLE_SIZE-1 // last index in table }; CAcUiTrueColorComboBox (); virtual ~CAcUiTrueColorComboBox (); // MRU List void AddItems (); int AddItemToList (LPCTSTR name, int index, INT_PTR cargo); int AddItemToMRU (LPCTSTR name, int cargo); // INTERNAL USE ONLY - Override to sort correctly int AddColorToMRU (const AcCmColor& color); // Drop down list int FindItemByColor (const AcCmColor& color); void GetCurrentItemColor (AcCmColor& color); DWORD getColorByCargo (int cargo); // Members const AcCmColor& GetBlockColor (); void SetBlockColor (const AcCmColor& color); virtual COLORREF GetColorFromIndex (int colorIndex); DWORD getColorData (AcCmColor color); int GetColorIndex (COLORREF color); protected: // Color Control int m_cargoOther1; int m_cargoOther2; AcCmColor m_blockColor; virtual void DrawItemImage (CDC& dc, CRect& r, INT_PTR cargo); virtual void OnAddItems (); // Color Pickers virtual BOOL OnSelectOther (BOOL isOther2,int curSel,int& newSel); BOOL GetOtherColor (AcCmColor& defaultColor, const AcCmColor& layerColor, BOOL enableMetaColors); BOOL GetWindowsColor (AcCmColor& color); virtual BOOL GetOtherName (BOOL isOther2, CString& name); // AcCmColor Table AcCmColor * m_AcCmColorTable[ACUI_TRUECOLOR_COMBOBOX_TABLE_SIZE]; int m_nextAcCmColorTableIndex; void initAcCmColorTable (void); // Color Utilities void RGBFill (CDC& dc, CRect& rFill); bool GetCurrentLayerColor (AcCmColor& color); virtual COLORREF LookupColor (int colorIndex, LOGPALETTE *logPalette); afx_msg void OnDrawItem (int nIDCtl, LPDRAWITEMSTRUCT lpDrawItemStruct); // ClassWizard-controlled public: //{{AFX_VIRTUAL(CAcUiTrueColorComboBox) //}}AFX_VIRTUAL protected: //{{AFX_MSG(CAcUiTrueColorComboBox) //}}AFX_MSG DECLARE_MESSAGE_MAP() }; ////////////////////////////////////////////////////////////////////////////// class ACUI_PORT CAcUiLineWeightComboBox : public CAcUiMRUComboBox { public: CAcUiLineWeightComboBox (); virtual ~CAcUiLineWeightComboBox (); // MRU control protected: virtual void DrawItemImage (CDC& dc, CRect& r, INT_PTR cargo); virtual void OnAddItems (); // LineWeight control protected: double m_lineWeightScale; public: int FindItemByLineWeight (int lw); // Get corresponding item index. int GetCurrentItemLineWeight (); // Get current item's LW (or -1). int GetCurrentLayerLineWeight (); int GetItemLineWeight (int item); // Get item's LW (or -1). double GetLineWeightScale (); void SetLineWeightScale (double scale); void SetUseDefault(BOOL b); virtual int ImageWidth (); private: BOOL m_bUseDefault; // ClassWizard-controlled public: //{{AFX_VIRTUAL(CAcUiLineWeightComboBox) //}}AFX_VIRTUAL protected: //{{AFX_MSG(CAcUiLineWeightComboBox) //}}AFX_MSG DECLARE_MESSAGE_MAP() }; ////////////////////////////////////////////////////////////////////////////// class ACUI_PORT CAcUiArrowHeadComboBox : public CAcUiMRUComboBox { public: CAcUiArrowHeadComboBox (); virtual ~CAcUiArrowHeadComboBox (); // MRU control protected: virtual void DrawItemImage (CDC& dc, CRect& r, INT_PTR cargo); virtual int CalcItemHeight (); virtual BOOL GetOtherName (BOOL isOther2, CString& name); virtual void OnAddItems (); virtual void OnComboBoxInit (); // Aliases for Option2 public: BOOL GetUseOrigin2 (); void SetUseOrigin2 (BOOL use); // ArrowHead control private: CBitmap m_arrowBitmap; int m_arrowCount; // Number of images in bitmap int m_arrowSize; // Image height and width in pixels BOOL m_bUseOrigin2; public: int AddArrowHeadToMRU (LPCTSTR name); // Returns item index (or -1). // ClassWizard-controlled public: //{{AFX_VIRTUAL(CAcUiArrowHeadComboBox) //}}AFX_VIRTUAL protected: //{{AFX_MSG(CAcUiArrowHeadComboBox) //}}AFX_MSG DECLARE_MESSAGE_MAP() }; ////////////////////////////////////////////////////////////////////////////// class ACUI_PORT CAcUiPlotStyleTablesComboBox : public CAcUiMRUComboBox { public: CAcUiPlotStyleTablesComboBox (); CAcUiPlotStyleTablesComboBox (BOOL bInitialize); virtual ~CAcUiPlotStyleTablesComboBox (); // NOTE: to show color style tables, set both currentDrawing and named to false void SetFileType(bool currentDrawing, bool named); int AddMissingStyleTable(LPCTSTR fullFileName, bool bMissing = true); bool IsMissing(int index); virtual int ImageWidth (); // Override to allow setting of 0 image width. INTERNAL USE ONLY // override getLBText to account for the (missing) string thing void GetLBText(int nIndex, CString& rString) const; // INTERNAL USE ONLY // Override to sort correctly. // INTERNAL USE ONLY int AddItemToList (LPCTSTR name, INT_PTR cargo); // MRU control protected: virtual void DrawItemImage (CDC& dc, CRect& r, INT_PTR cargo); // INTERNAL USE ONLY virtual int CalcItemHeight (); // INTERNAL USE ONLY virtual void OnAddItems (); virtual void OnComboBoxInit (); // INTERNAL USE ONLY // ArrowHead control private: CBitmap m_plotStyleTablesBitmap; int m_plotStyleTableBitmapSize; // Image height and width in pixels BOOL m_bImageDisplayed; // TRUE if image is displayed in the list. bool m_bCurrentDrawing; // Which kind of style table to populate the list with. bool m_bNamed; BOOL m_bInitialize; // TRUE to initialize the contents at create time. // ClassWizard-controlled public: //{{AFX_VIRTUAL(CAcUiPlotStyleTablesComboBox) virtual BOOL OnChildNotify(UINT, WPARAM, LPARAM, LRESULT*); //}}AFX_VIRTUAL protected: //{{AFX_MSG(CAcUiPlotStyleTablesComboBox) afx_msg BOOL OnDropDown(); //}}AFX_MSG DECLARE_MESSAGE_MAP() private: BOOL AdjustDropDownListWidth(void); }; ////////////////////////////////////////////////////////////////////////////// class ACUI_PORT CAcUiPlotStyleNamesComboBox : public CAcUiMRUComboBox { public: CAcUiPlotStyleNamesComboBox (); virtual ~CAcUiPlotStyleNamesComboBox (); virtual int ImageWidth (); // Override to allow setting of 0 image width. INTERNAL USE ONLY void OtherRunsSelectPlotStyle() {m_whatOtherDoes = 0; } void OtherRunsCurrentPlotStyle() {m_whatOtherDoes = 1; } void OtherRunsDefault() {m_whatOtherDoes = -1;} void SetAllowByLayerByBlock(BOOL bAllow) {m_bAllowByLayerByBlock = bAllow;} void SetColorDependentMode(); void SetNamedMode(); protected: virtual void OnAddItems (); virtual BOOL OnSelectOther (BOOL isOther2, int curSel, int& newSel); // INTERNAL USE ONLY virtual void OnComboBoxInit (); // INTERNAL USE ONLY private: // -1 to leave up to control, 0 to run select plot style, 1 to run curent plot style. int m_whatOtherDoes; // TRUE if this control is in color depedent mode. BOOL m_bColorDependentMode; // If TRUE the following allows the selection of ByLayer/ByBlock in // the "Other..." dialog. BOOL m_bAllowByLayerByBlock; // Save the last set named mode settings for using ByBlock, ByLayer // and Other... when switched to color dependent mode. BOOL m_bLastByBlock; BOOL m_bLastByLayer; BOOL m_bLastUseOther; // ClassWizard-controlled public: //{{AFX_VIRTUAL(CAcUiPlotStyleNamesComboBox) //}}AFX_VIRTUAL protected: //{{AFX_MSG(CAcUiPlotStyleNamesComboBox) //}}AFX_MSG DECLARE_MESSAGE_MAP() }; ////////////////////////////////////////////////////////////////////////////// class ACUI_PORT CAcUiPredefBlockComboBox : public CAcUiMRUComboBox { public: CAcUiPredefBlockComboBox (); virtual ~CAcUiPredefBlockComboBox (); // MRU control protected: virtual void DrawItemImage (CDC& dc, CRect& r, INT_PTR cargo); virtual int CalcItemHeight (); virtual BOOL GetOtherName (BOOL isOther2, CString& name); virtual void OnAddItems (); virtual void OnComboBoxInit (); // PredefBlock control private: CBitmap m_blockBitmap; int m_blockCount; // Number of images in bitmap int m_blockSize; // Image height and width in pixels public: int AddPredefBlockToMRU (LPCTSTR name); // Returns item index (or -1). // ClassWizard-controlled public: //{{AFX_VIRTUAL(CAcUiPredefBlockComboBox) //}}AFX_VIRTUAL protected: //{{AFX_MSG(CAcUiPredefBlockComboBox) //}}AFX_MSG DECLARE_MESSAGE_MAP() }; ///////////////////////////////////////////////////////////////////////////// //{{AFX_INSERT_LOCATION}} // Microsoft Developer Studio will insert additional declarations immediately before the previous line. #pragma pack (pop) #endif /////////////////////////////////////////////////////////////////////////////
[ "lixiaolei2005-12@163.com" ]
lixiaolei2005-12@163.com
96e02b98864cd843b05390a05f3981034c584682
3ee0d3519f444e8ac3dd8c4731c9bbe751dd7595
/FrameData/Shader.h
aa051b160fdd17249ad87ae79c6469ba788ef4bf
[ "MIT" ]
permissive
ousttrue/FunnelPipe
77f4941fde22353eea2c1e51a1b891e69cc4572f
380b52a7d41b4128b287ec02280bb703ed6b5d66
refs/heads/master
2023-08-23T08:40:56.895419
2021-09-08T12:57:41
2021-09-08T12:57:41
250,489,380
0
0
null
null
null
null
UTF-8
C++
false
false
2,914
h
#pragma once #include <wrl/client.h> #include <d3dcompiler.h> #include <string> #include <vector> #include <memory> #include <span> #include "ShaderConstantVariable.h" namespace framedata { class Shader { protected: template <typename T> using ComPtr = Microsoft::WRL::ComPtr<T>; Shader(const Shader &) = delete; Shader &operator=(const Shader &) = delete; std::string m_name; ComPtr<ID3DBlob> m_compiled; std::vector<ConstantBuffer> m_cblist; void GetConstants(const ComPtr<ID3D12ShaderReflection> &pReflection, const std::string &source); public: Shader(const std::string &name) : m_name(name) {} const std::string &Name() const { return m_name; } virtual bool Compile(const std::string &source, const std::string &entrypoint, const D3D_SHADER_MACRO *define) = 0; std::tuple<LPVOID, UINT> ByteCode() const { return std::make_pair(m_compiled->GetBufferPointer(), static_cast<UINT>(m_compiled->GetBufferSize())); } // register(b0), register(b1), register(b2)... const ConstantBuffer *CB(int reg) const { for (auto &cb : m_cblist) { if (cb.reg == reg) { return &cb; } } return nullptr; } }; using ShaderPtr = std::shared_ptr<Shader>; class PixelShader : public Shader { public: using Shader::Shader; bool Compile(const std::string &source, const std::string &entrypoint, const D3D_SHADER_MACRO *define) override; }; using PixelShaderPtr = std::shared_ptr<PixelShader>; class VertexShader : public Shader { template <typename T> using ComPtr = Microsoft::WRL::ComPtr<T>; // keep semantic strings enum INPUT_CLASSIFICATION { INPUT_CLASSIFICATION_PER_VERTEX_DATA = 0, INPUT_CLASSIFICATION_PER_INSTANCE_DATA = 1 }; struct InputLayoutElement { LPCSTR SemanticName; UINT SemanticIndex; DXGI_FORMAT Format; UINT InputSlot; UINT AlignedByteOffset; INPUT_CLASSIFICATION InputSlotClass; UINT InstanceDataStepRate; }; std::vector<std::string> m_semantics; std::vector<InputLayoutElement> m_layout; bool InputLayoutFromReflection(const ComPtr<ID3D12ShaderReflection> &reflection); public: using Shader::Shader; bool Compile(const std::string &source, const std::string &entrypoint, const D3D_SHADER_MACRO *define) override; // same with D3D11_INPUT_ELEMENT_DESC or D3D12_INPUT_ELEMENT_DESC std::span<const InputLayoutElement> InputLayout() const { return m_layout; } }; using VertexShaderPtr = std::shared_ptr<VertexShader>; } // namespace framedata
[ "ousttrue@gmail.com" ]
ousttrue@gmail.com
193a0b07ff81166f34390d3d2b2da8da69aba6e0
313e686e0f0aa3b2535bc94c68644ca2ea7b8e61
/src/server/scripts/Outland/CoilfangReservoir/TheUnderbog/instance_the_underbog.cpp
a56c9db1291598f7bf13e38cc2a5fa4a3fdac638
[]
no_license
mysql1/TournamentCore
cf03d44094257a5348bd6c509357d512fb03a338
571238d0ec49078fb13f1965ce7b91c24f2ea262
refs/heads/master
2020-12-03T00:29:21.203000
2015-05-12T07:30:42
2015-05-12T07:30:42
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,627
cpp
/* * Copyright (C) 2014-2015 TournamentCore * Copyright (C) 2008-2015 TrinityCore <http://www.trinitycore.org/> * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation; either version 2 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. */ /* This placeholder for the instance is needed for dungeon finding to be able to give credit after the boss defined in lastEncounterDungeon is killed. Without it, the party doing random dungeon won't get satchel of spoils and gets instead the deserter debuff. */ #include "ScriptMgr.h" #include "InstanceScript.h" class instance_the_underbog : public InstanceMapScript { public: instance_the_underbog() : InstanceMapScript("instance_the_underbog", 546) { } InstanceScript* GetInstanceScript(InstanceMap* map) const override { return new instance_the_underbog_InstanceMapScript(map); } struct instance_the_underbog_InstanceMapScript : public InstanceScript { instance_the_underbog_InstanceMapScript(Map* map) : InstanceScript(map) { } }; }; void AddSC_instance_the_underbog() { new instance_the_underbog(); }
[ "TournamentCore@gmail.com" ]
TournamentCore@gmail.com
d4de29e4aee6f69182086c6dbedaa871b2f5fae2
37fd355d5d0b9a60e6c5799b029ef95eac749afe
/src/scheduler/grouper/GreedyGrouper.hpp
e76fc49886d8dd16152ff025f17cddc8cf8382d6
[]
no_license
freiheitsnetz/openwns-library
7a903aff2ad9d120d53195076d900bd020367980
eb98600df8b0baca1d90907b5dd2c80c64ab9ffa
refs/heads/master
2021-01-18T05:07:32.803956
2014-03-26T16:16:19
2014-03-26T16:16:30
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,983
hpp
/******************************************************************************* * This file is part of openWNS (open Wireless Network Simulator) * _____________________________________________________________________________ * * Copyright (C) 2004-2009 * Chair of Communication Networks (ComNets) * Kopernikusstr. 5, D-52074 Aachen, Germany * phone: ++49-241-80-27910, * fax: ++49-241-80-22242 * email: info@openwns.org * www: http://www.openwns.org * _____________________________________________________________________________ * * openWNS is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License version 2 as published by the * Free Software Foundation; * * openWNS is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR * A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * ******************************************************************************/ #ifndef WNS_SCHEDULER_GROUPER_GREEDYGROUPER_HPP #define WNS_SCHEDULER_GROUPER_GREEDYGROUPER_HPP #include <WNS/scheduler/grouper/AllPossibleGroupsGrouper.hpp> namespace wns { namespace scheduler { namespace grouper { class GreedyGrouper : public AllPossibleGroupsGrouper { public: // inherit everything from AllPossibleGroupsGrouper except for makeGrouping GreedyGrouper(const wns::pyconfig::View& config); ~GreedyGrouper() {}; protected: virtual Partition makeGrouping(int maxBeams, unsigned int noOfStations); private: class BeamCmp { public: bool operator() (const Beams&, const Beams&) const; }; int MonteCarloGreedyProbe; }; }}} // namespace wns::scheduler::grouper #endif // WNS_SCHEDULER_GROUPER_GREEDYGROUPER_HPP
[ "aku@comnets.rwth-aachen.de" ]
aku@comnets.rwth-aachen.de
77dc64e38297f4a999095ebb5929fc38fbf7b897
7e288ad3bcaca2e00e04113ebd251331b5ea300c
/starviewer/src/core/screen.cpp
ed500cb92125679f69914ef74a8e86dada3d0e72
[]
no_license
idvr/starviewer
b7fb2eb38e8cce6f6cd9b4b10371a071565ae4fc
94bf98803e4face8f81ff68447cf52a686571ad7
refs/heads/master
2020-12-02T17:46:13.018426
2014-12-02T11:29:38
2014-12-02T11:31:28
null
0
0
null
null
null
null
IBM852
C++
false
false
6,161
cpp
#include "screen.h" #include <QString> namespace udg { const int Screen::NullScreenID = -1; const int Screen::MaximumDistanceInBetween = 5; Screen::Screen() { initializeValues(); } Screen::Screen(const QRect &geometry, const QRect &availableGeometry) { initializeValues(); setGeometry(geometry); setAvailableGeometry(availableGeometry); } Screen::~Screen() { } void Screen::setGeometry(const QRect &geometry) { m_geometry = geometry; } QRect Screen::getGeometry() const { return m_geometry; } void Screen::setAvailableGeometry(const QRect &geometry) { m_availableGeometry = geometry; } QRect Screen::getAvailableGeometry() const { return m_availableGeometry; } void Screen::setAsPrimary(bool isPrimary) { m_isPrimary = isPrimary; } bool Screen::isPrimary() const { return m_isPrimary; } void Screen::setID(int ID) { m_ID = ID; } int Screen::getID() const { return m_ID; } QString Screen::toString() const { QString string; string = QString("Is Primary: %1\n").arg(m_isPrimary); string += QString("ID: %1\n").arg(m_ID); string += QString("Geometry: %1, %2, %3, %4\n").arg(m_geometry.x()).arg(m_geometry.y()).arg(m_geometry.width()).arg(m_geometry.height()); string += QString("Available Geometry: %1, %2, %3, %4").arg(m_availableGeometry.x()).arg(m_availableGeometry.y()).arg(m_availableGeometry.width()).arg(m_availableGeometry.height()); return string; } bool Screen::isHigher(const Screen &screen) { if (m_geometry.top() < screen.getGeometry().top()) { return true; } return false; } bool Screen::isLower(const Screen &screen) { if (m_geometry.top() > screen.getGeometry().top()) { return true; } return false; } bool Screen::isMoreToTheLeft(const Screen &screen) { if (m_geometry.left() < screen.getGeometry().left()) { return true; } return false; } bool Screen::isMoreToTheRight(const Screen &screen) { if (m_geometry.right() > screen.getGeometry().right()) { return true; } return false; } bool Screen::isOver(const Screen &screen) const { if (m_geometry.bottom() <= screen.getGeometry().top()) { return true; } return false; } bool Screen::isUnder(const Screen &screen) const { if (m_geometry.top() >= screen.getGeometry().bottom()) { return true; } return false; } bool Screen::isOnLeft(const Screen &screen) const { if (m_geometry.right() <= screen.getGeometry().left()) { return true; } return false; } bool Screen::isOnRight(const Screen &screen) const { if (m_geometry.left() >= screen.getGeometry().right()) { return true; } return false; } bool Screen::isTop(const Screen &screen) const { // Esta posat a sobre if (abs(m_geometry.bottom() - screen.getGeometry().top()) < MaximumDistanceInBetween) { // Te la mateixa alšada int leftPart = abs(m_geometry.left() - screen.getGeometry().left()); int rightPart = abs(m_geometry.right() - screen.getGeometry().right()); if (leftPart + rightPart < MaximumDistanceInBetween) { return true; } } return false; } bool Screen::isBottom(const Screen &screen) const { // Esta posat a sota if (abs(m_geometry.top() - screen.getGeometry().bottom()) < MaximumDistanceInBetween) { // Te la mateixa alšada int leftPart = abs(m_geometry.left() - screen.getGeometry().left()); int rightPart = abs(m_geometry.right() - screen.getGeometry().right()); if (leftPart + rightPart < MaximumDistanceInBetween) { return true; } } return false; } bool Screen::isLeft(const Screen &screen) const { // Esta posat a l'esquerra if (abs(m_geometry.right() - screen.getGeometry().left()) < MaximumDistanceInBetween) { // Te la mateixa alšada int topPart = abs(m_geometry.top() - screen.getGeometry().top()); int bottomPart = abs(m_geometry.bottom() - screen.getGeometry().bottom()); if (topPart + bottomPart < MaximumDistanceInBetween) { return true; } } return false; } bool Screen::isRight(const Screen &screen) const { // Esta posat a l'esquerra if (abs(m_geometry.left() - screen.getGeometry().right()) < MaximumDistanceInBetween) { // Te la mateixa alšada int topPart = abs(m_geometry.top() - screen.getGeometry().top()); int bottomPart = abs(m_geometry.bottom() - screen.getGeometry().bottom()); if (topPart + bottomPart < MaximumDistanceInBetween) { return true; } } return false; } bool Screen::isTopLeft(const Screen &screen) const { QPoint distancePoint = m_geometry.bottomRight() - screen.getGeometry().topLeft(); if (distancePoint.manhattanLength() < MaximumDistanceInBetween) { return true; } return false; } bool Screen::isTopRight(const Screen &screen) const { QPoint distancePoint = m_geometry.bottomLeft() - screen.getGeometry().topRight(); if (distancePoint.manhattanLength() < MaximumDistanceInBetween) { return true; } return false; } bool Screen::isBottomLeft(const Screen &screen) const { QPoint distancePoint = m_geometry.topRight() - screen.getGeometry().bottomLeft(); if (distancePoint.manhattanLength() < MaximumDistanceInBetween) { return true; } return false; } bool Screen::isBottomRight(const Screen &screen) const { QPoint distancePoint = m_geometry.topLeft() - screen.getGeometry().bottomRight(); if (distancePoint.manhattanLength() < MaximumDistanceInBetween) { return true; } return false; } bool Screen::operator==(const Screen &screen) const { return m_isPrimary == screen.m_isPrimary && m_ID == screen.m_ID && m_geometry == screen.m_geometry && m_availableGeometry == screen.m_availableGeometry; } void Screen::initializeValues() { m_isPrimary = false; m_ID = NullScreenID; } } // End namespace udg
[ "jspinola@gmail.com" ]
jspinola@gmail.com
652cede466fa4be421ae6aab8fde796d3599f151
19742122229f417a418158630f279f81c1c503a6
/repo/daemon/identifier_collector.cc
477305ef779a520d6ebdc61ed68e032f14a4713e
[ "BSD-3-Clause" ]
permissive
rosstex/replex
20bbb0829aef4f868fafb34c2a16172d6455ec6f
2a4499ebc81622985c59647839e7f517869f8c14
refs/heads/master
2020-03-17T16:26:10.767096
2018-05-17T02:41:23
2018-05-17T02:41:23
133,748,573
0
0
null
null
null
null
UTF-8
C++
false
false
3,176
cc
// Copyright (c) 2013-2014, Cornell University // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of HyperDex 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 OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. // STL #include <algorithm> // e #include <e/atomic.h> // HyperDex #include "daemon/identifier_collector.h" using hyperdex::identifier_collector; using hyperdex::region_id; const region_id identifier_collector::defaultri; identifier_collector :: identifier_collector(e::garbage_collector* gc) : m_gc(gc) , m_collectors() { } identifier_collector :: ~identifier_collector() throw () { } void identifier_collector :: bump(const region_id& ri, uint64_t lb) { e::compat::shared_ptr<e::seqno_collector> sc; if (!m_collectors.get(ri, &sc)) { abort(); } sc->collect_up_to(lb); } void identifier_collector :: collect(const region_id& ri, uint64_t seqno) { e::compat::shared_ptr<e::seqno_collector> sc; if (!m_collectors.get(ri, &sc)) { abort(); } sc->collect(seqno); } uint64_t identifier_collector :: lower_bound(const region_id& ri) { e::compat::shared_ptr<e::seqno_collector> sc; if (!m_collectors.get(ri, &sc)) { abort(); } uint64_t lb; sc->lower_bound(&lb); return lb; } void identifier_collector :: adopt(region_id* ris, size_t ris_sz) { collector_map_t new_collectors; for (size_t i = 0; i < ris_sz; ++i) { e::compat::shared_ptr<e::seqno_collector> sc; if (!m_collectors.get(ris[i], &sc)) { sc = e::compat::shared_ptr<e::seqno_collector>(new e::seqno_collector(m_gc)); sc->collect(0); } assert(sc); new_collectors.put(ris[i], sc); } m_collectors.swap(&new_collectors); }
[ "rapt@cs.princeton.edu" ]
rapt@cs.princeton.edu
fb77f5d0df4b2b3046c15b939e0295fcb42487f0
7f1ef34214ee4a25429fce694f66826316672b1b
/Lab 5/Linked.h
b82718f85ff0e3682de5729675ca2402b9843d73
[]
no_license
Neel1997/CPlusPlus_Labs_Projects
ca39b201d77c0491ae953f8fb1b3a8c20186c506
d631c5c9df217e1e2fd8d9528d596f86d6ccec53
refs/heads/main
2023-06-30T00:25:36.101943
2021-07-28T20:38:31
2021-07-28T20:38:31
390,493,464
0
0
null
null
null
null
UTF-8
C++
false
false
295
h
#ifndef LINKED_H #define LINKED_H #include <cstdlib> class Linked { private: struct node { int data; node *next; }; node *top; int size; public: Linked(); ~Linked(); void display(); int getSize(); void push(int); void pop(); }; #endif
[ "noreply@github.com" ]
Neel1997.noreply@github.com
3fc78a06a548c887ef3d79d551062efae5e49c88
bad319e286793086efef5f1998f9494ff45a3ad8
/Source/SimpleShooter/ShooterPlayerController.h
1569ee56f9f4bd888d1fcb68c3fc28095ec08e8f
[]
no_license
SharkyZg/SimpleShooter
e8b982bc032c94cd07aa7e2c61b15e0d81b57e88
0ae518d2a5b03992ecdc7dd3e94f2dbf66037e64
refs/heads/master
2023-01-20T22:59:14.402966
2020-11-26T16:46:07
2020-11-26T16:46:07
312,320,583
0
0
null
null
null
null
UTF-8
C++
false
false
835
h
// Fill out your copyright notice in the Description page of Project Settings. #pragma once #include "CoreMinimal.h" #include "GameFramework/PlayerController.h" #include "ShooterPlayerController.generated.h" /** * */ UCLASS() class SIMPLESHOOTER_API AShooterPlayerController : public APlayerController { GENERATED_BODY() public: virtual void GameHasEnded(class AActor *EndGameFocus = nullptr, bool bIsWinner = false) override; private: UPROPERTY(EditAnywhere) TSubclassOf<class UUserWidget> LoseScreenClass; UPROPERTY(EditAnywhere) TSubclassOf<class UUserWidget> WinScreenClass; UPROPERTY(EditAnywhere) TSubclassOf<class UUserWidget> CrossairClass; UPROPERTY(EditAnywhere) float RestartDelay = 5; FTimerHandle RestartTimer; UPROPERTY() UUserWidget *Crossair; protected: virtual void BeginPlay() override; };
[ "marko.sarkanj@gmail.com" ]
marko.sarkanj@gmail.com
dc9e13f445eced52b3c0f582db2a4eb419c8f257
19a6f3b91067868ce488f6cc296c616dac1efef7
/linthurst_IO.cpp
9dbd4a3d51d605fac778c7ff7393f1ae2b9dbe9c
[]
no_license
deerchomp/datastructures
4472414e2de61fb2514bff783792baa1a91af108
d07997f197e1de93e6200eeb5cced9929fc6c847
refs/heads/master
2021-06-10T14:57:30.941732
2017-02-05T12:39:23
2017-02-05T12:39:23
null
0
0
null
null
null
null
UTF-8
C++
false
false
474
cpp
/* IO Brendon Linthurst 659223 CS41 */ #include <iostream> #include <string> using namespace std; int main() { float a; char s[] = "Hello world there are 3.5 items"; char *parse; parse = strtok(s," "); while(parse != NULL) { if(atof(parse) != 0) { a = atof(parse); cout << a * 2 << endl; parse = strtok(NULL, " "); } else { cout << parse << endl; parse = strtok(NULL, " "); } } system("PAUSE"); return 0; }
[ "noreply@github.com" ]
deerchomp.noreply@github.com
14abfaf9a69be7d5d038eb24a03fb4c3e253b9c4
f52dfc8918cb8ab0028980dd06ebdaeda31d1aed
/Arduino/SerialLighthouse_constant_broadcast/SerialLighthouse_constant_broadcast.ino
e568dbf4b9cefa423514c757fe0aafec7d07611d
[]
no_license
l-henri/lightning-lighthouse
47dfe58e52069da944d7ab90bcec8311fdb591b7
f15ca907794ab36f67ab216427b474a6173f5121
refs/heads/master
2020-05-15T05:01:30.656389
2019-05-20T07:43:01
2019-05-20T07:43:01
182,098,919
0
0
null
null
null
null
UTF-8
C++
false
false
10,804
ino
/* This is an example of how simple driving a Neopixel can be This code is optimized for understandability and changability rather than raw speed More info at http://wp.josh.com/2014/05/11/ws2812-neopixels-made-easy/ */ #include <SoftwareSerial.h> #include <avr/pgmspace.h> #define PIXELS 16 // Number of pixels in the string // These values depend on which pin your string is connected to and what board you are using // More info on how to find these at http://www.arduino.cc/en/Reference/PortManipulation // These values are for digital pin 8 on an Arduino Yun or digital pin 12 on a DueMilinove/UNO // Note that you could also include the DigitalWriteFast header file to not need to to this lookup. #define PIXEL_PORT PORTD // Port of the pin the pixels are connected to #define PIXEL_DDR DDRD // Port of the pin the pixels are connected to #define PIXEL_BIT 3 // Bit of the pin the pixels are connected to // These are the timing constraints taken mostly from the WS2812 datasheets // These are chosen to be conservative and avoid problems rather than for maximum throughput #define T1H 900 // Width of a 1 bit in ns #define T1L 600 // Width of a 1 bit in ns #define T0H 400 // Width of a 0 bit in ns #define T0L 900 // Width of a 0 bit in ns #define RES 6000 // Width of the low gap between bits to cause a frame to latch // Here are some convience defines for using nanoseconds specs to generate actual CPU delays #define NS_PER_SEC (1000000000L) // Note that this has to be SIGNED since we want to be able to check for negative values of derivatives #define CYCLES_PER_SEC (F_CPU) #define NS_PER_CYCLE ( NS_PER_SEC / CYCLES_PER_SEC ) #define NS_TO_CYCLES(n) ( (n) / NS_PER_CYCLE ) String messageString = "hello wallace"; int messageTimerMs = 300; int signalIntensity = 60; void setup() { pinMode(LED_BUILTIN, OUTPUT); ledsetup(); cli(); for(int i=0;i<PIXELS;i++) { sendPixel(0,0,0); } sei(); show(); delay(messageTimerMs); Serial.begin(9600); } void loop() { if (Serial.available()) { //Serial.println("Jai vu un message"); delay(1); messageString = ""; while(Serial.available()) { char c = Serial.read(); messageString += c; delay(2); } String codeToSend = ""; for (int k = 0; k < messageString.length(); k++) { // Converting letter to Morse code codeToSend = morseDictionnary(messageString[k]); // Sending morse code to display sendMorseLetter(codeToSend); delay(2*messageTimerMs); } Serial.println("OK"); } String codeToSend = ""; for (int k = 0; k < messageString.length(); k++) { if (Serial.available()) { break;} // Converting letter to Morse code codeToSend = morseDictionnary(messageString[k]); // Sending morse code to display sendMorseLetter(codeToSend); delay(2*messageTimerMs); } delay(10000); } /* Signal sender */ void sendMorseLetter(String codeToSend) { // On vérifie si il s'agit d'un espace if (codeToSend == ' ') { delay(5*messageTimerMs); return; } // On parcours le code for (int j = 0; j < codeToSend.length(); j++) { int timeToDelay = messageTimerMs; if (codeToSend[j] == '1') { timeToDelay = 3* timeToDelay; } else if (codeToSend[j] == '0') {;} else {continue;} //Serial.println(codeToSend[j]); turnLedsOn(); delay(timeToDelay); turnLedsOff(); delay(messageTimerMs); } } void turnLedsOff() { delay(10); // On eteind les lumieres cli(); for(int i=0;i<PIXELS;i++) { sendPixel(0,0,0); } sei(); show(); digitalWrite(LED_BUILTIN, LOW); } void turnLedsOn() { // On eteind les lumieres cli(); for(int i=0;i<PIXELS;i++) { sendPixel(signalIntensity,signalIntensity,signalIntensity); } sei(); show(); digitalWrite(LED_BUILTIN, HIGH); } /* Morse dictionnary */ String morseDictionnary(char letter) { String code = ""; switch (letter ) { case 'a': code = "01"; break; case 'b': code = "1000"; break; case 'c': code = "1010"; break; case 'd': code = "100"; break; case 'e': code = "0"; break; case 'f': code = "0010"; break; case 'g': code = "110"; break; case 'h': code = "0000"; break; case 'i': code = "00"; break; case 'j': code = "0111"; break; case 'k': code = "1010"; break; case 'l': code = "0100"; break; case 'm': code = "11"; break; case 'n': code = "10"; break; case 'o': code = "111"; break; case 'p': code = "0110"; break; case 'q': code = "1101"; break; case 'r': code = "010"; break; case 's': code = "000"; break; case 't': code = "1"; break; case 'u': code = "001"; break; case 'v': code = "0001"; break; case 'w': code = "011"; break; case 'x': code = "1001"; break; case 'y': code = "1011"; break; case 'z': code = "1100"; break; case '0': code = "11111"; break; case '1': code = "01111"; break; case '2': code = "00111"; break; case '3': code = "00011"; break; case '4': code = "00001"; break; case '5': code = "00000"; break; case '6': code = "10000"; break; case '7': code = "11000"; break; case '8': code = "11100"; break; case '9': code = "11110"; break; case ' ': code = " "; break; } return code; } /* LED Strip library */ // Actually send a bit to the string. We must to drop to asm to enusre that the complier does // not reorder things and make it so the delay happens in the wrong place. void sendBit( bool bitVal ) { if ( bitVal ) { // 0 bit asm volatile ( "sbi %[port], %[bit] \n\t" // Set the output bit ".rept %[onCycles] \n\t" // Execute NOPs to delay exactly the specified number of cycles "nop \n\t" ".endr \n\t" "cbi %[port], %[bit] \n\t" // Clear the output bit ".rept %[offCycles] \n\t" // Execute NOPs to delay exactly the specified number of cycles "nop \n\t" ".endr \n\t" :: [port] "I" (_SFR_IO_ADDR(PIXEL_PORT)), [bit] "I" (PIXEL_BIT), [onCycles] "I" (NS_TO_CYCLES(T1H) - 2), // 1-bit width less overhead for the actual bit setting, note that this delay could be longer and everything would still work [offCycles] "I" (NS_TO_CYCLES(T1L) - 2) // Minimum interbit delay. Note that we probably don't need this at all since the loop overhead will be enough, but here for correctness ); } else { // 1 bit // ************************************************************************** // This line is really the only tight goldilocks timing in the whole program! // ************************************************************************** asm volatile ( "sbi %[port], %[bit] \n\t" // Set the output bit ".rept %[onCycles] \n\t" // Now timing actually matters. The 0-bit must be long enough to be detected but not too long or it will be a 1-bit "nop \n\t" // Execute NOPs to delay exactly the specified number of cycles ".endr \n\t" "cbi %[port], %[bit] \n\t" // Clear the output bit ".rept %[offCycles] \n\t" // Execute NOPs to delay exactly the specified number of cycles "nop \n\t" ".endr \n\t" :: [port] "I" (_SFR_IO_ADDR(PIXEL_PORT)), [bit] "I" (PIXEL_BIT), [onCycles] "I" (NS_TO_CYCLES(T0H) - 2), [offCycles] "I" (NS_TO_CYCLES(T0L) - 2) ); } // Note that the inter-bit gap can be as long as you want as long as it doesn't exceed the 5us reset timeout (which is A long time) // Here I have been generous and not tried to squeeze the gap tight but instead erred on the side of lots of extra time. // This has thenice side effect of avoid glitches on very long strings becuase } void sendByte( unsigned char byte ) { for( unsigned char bit = 0 ; bit < 8 ; bit++ ) { sendBit( bitRead( byte , 7 ) ); // Neopixel wants bit in highest-to-lowest order // so send highest bit (bit #7 in an 8-bit byte since they start at 0) byte <<= 1; // and then shift left so bit 6 moves into 7, 5 moves into 6, etc } } /* The following three functions are the public API: ledSetup() - set up the pin that is connected to the string. Call once at the begining of the program. sendPixel( r g , b ) - send a single pixel to the string. Call this once for each pixel in a frame. show() - show the recently sent pixel on the LEDs . Call once per frame. */ // Set the specified pin up as digital out void ledsetup() { bitSet( PIXEL_DDR , PIXEL_BIT ); } void sendPixel( unsigned char r, unsigned char g , unsigned char b ) { sendByte(g); // Neopixel wants colors in green then red then blue order sendByte(r); sendByte(b); } // Just wait long enough without sending any bots to cause the pixels to latch and display the last sent frame void show() { _delay_us( (RES / 1000UL) + 1); // Round up since the delay must be _at_least_ this long (too short might not work, too long not a problem) } /* That is the whole API. What follows are some demo functions rewriten from the AdaFruit strandtest code... https://github.com/adafruit/Adafruit_NeoPixel/blob/master/examples/strandtest/strandtest.ino Note that we always turn off interrupts while we are sending pixels becuase an interupt could happen just when we were in the middle of somehting time sensitive. If we wanted to minimize the time interrupts were off, we could instead could get away with only turning off interrupts just for the very brief moment when we are actually sending a 0 bit (~1us), as long as we were sure that the total time taken by any interrupts + the time in our pixel generation code never exceeded the reset time (5us). */
[ "Henri.lieutaud@gmail.com" ]
Henri.lieutaud@gmail.com
ee447d1259521fe5626a8ca0c351c47080340796
dd80a584130ef1a0333429ba76c1cee0eb40df73
/external/chromium_org/chrome/browser/ui/views/apps/chrome_shell_window_delegate_views_win.cc
9ef69f376d2f18bba1c3fe4ba610e119990b680a
[ "BSD-3-Clause", "MIT" ]
permissive
karunmatharu/Android-4.4-Pay-by-Data
466f4e169ede13c5835424c78e8c30ce58f885c1
fcb778e92d4aad525ef7a995660580f948d40bc9
refs/heads/master
2021-03-24T13:33:01.721868
2017-02-18T17:48:49
2017-02-18T17:48:49
81,847,777
0
2
MIT
2020-03-09T00:02:12
2017-02-13T16:47:00
null
UTF-8
C++
false
false
602
cc
// 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. #include "chrome/browser/ui/apps/chrome_shell_window_delegate.h" #include "chrome/browser/ui/views/apps/native_app_window_views_win.h" // static apps::NativeAppWindow* ChromeShellWindowDelegate::CreateNativeAppWindowImpl( apps::ShellWindow* shell_window, const apps::ShellWindow::CreateParams& params) { NativeAppWindowViewsWin* window = new NativeAppWindowViewsWin; window->Init(shell_window, params); return window; }
[ "karun.matharu@gmail.com" ]
karun.matharu@gmail.com
e8cc0241f395c14e3cefdc0ba2d999382d65ce49
f81124e4a52878ceeb3e4b85afca44431ce68af2
/re20_2/processor0/45/U
75746fc545ff35b0f35f409eaa3169b303e43943
[]
no_license
chaseguy15/coe-of2
7f47a72987638e60fd7491ee1310ee6a153a5c10
dc09e8d5f172489eaa32610e08e1ee7fc665068c
refs/heads/master
2023-03-29T16:59:14.421456
2021-04-06T23:26:52
2021-04-06T23:26:52
355,040,336
0
1
null
null
null
null
UTF-8
C++
false
false
16,606
/*--------------------------------*- C++ -*----------------------------------*\ ========= | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox \\ / O peration | Website: https://openfoam.org \\ / A nd | Version: 7 \\/ M anipulation | \*---------------------------------------------------------------------------*/ FoamFile { version 2.0; format ascii; class volVectorField; location "45"; object U; } // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // dimensions [0 1 -1 0 0 0 0]; internalField nonuniform List<vector> 392 ( (0.993942 0.0185084 0) (0.99449 0.01981 0) (0.995082 0.0210212 0) (0.995699 0.0221266 0) (0.996324 0.0230905 0) (0.996942 0.0239042 0) (0.997547 0.0245686 0) (0.998131 0.0250858 0) (0.998693 0.0254588 3.34829e-27) (0.999231 0.0256923 -3.34829e-27) (0.999742 0.0257922 -5.55775e-11) (1.00023 0.0257655 5.55775e-11) (1.00069 0.0256199 -2.40849e-27) (1.00112 0.0253635 2.40849e-27) (1.00153 0.0250047 3.05979e-27) (1.00192 0.0245519 -3.05979e-27) (1.00228 0.0240132 0) (1.00262 0.0233965 0) (1.00294 0.0227094 0) (1.00323 0.0219588 0) (1.0035 0.0211513 0) (1.00375 0.020293 0) (1.00398 0.0193894 -2.09155e-27) (1.00418 0.0184456 2.09155e-27) (1.00437 0.0174662 -9.14829e-11) (1.00455 0.0164555 9.14829e-11) (1.0047 0.0154171 -2.00024e-27) (1.00484 0.0143546 2.00024e-27) (1.00496 0.013271 0) (1.00507 0.0121691 0) (1.00516 0.0110514 -4.3269e-11) (1.00524 0.00992014 4.3269e-11) (1.00532 0.00877731 0) (1.00538 0.00762474 0) (1.00543 0.00646409 0) (1.00547 0.00529685 0) (1.0055 0.00412434 0) (1.00552 0.00294772 0) (1.00554 0.00176835 0) (1.00555 0.000589101 0) (0.997273 0.00992818 0) (0.997488 0.0107168 0) (0.997716 0.0114506 0) (0.997955 0.0121145 0) (0.998203 0.0126952 0) (0.998454 0.0131909 0) (0.998707 0.0136038 0) (0.998958 0.0139359 0) (0.999206 0.01419 0) (0.999448 0.0143688 0) (0.999682 0.0144757 0) (0.999906 0.0145138 0) (1.00012 0.0144866 1.65077e-27) (1.00032 0.0143975 -1.65077e-27) (1.0005 0.0142501 -2.33441e-27) (1.00067 0.0140477 2.33441e-27) (1.00083 0.0137938 0) (1.00097 0.0134918 0) (1.0011 0.0131451 4.99542e-11) (1.00121 0.012757 -4.99542e-11) (1.00132 0.0123307 0) (1.00141 0.0118695 0) (1.00149 0.0113762 0) (1.00156 0.010854 0) (1.00162 0.0103055 -4.6595e-11) (1.00167 0.00973334 4.6595e-11) (1.00171 0.00914006 0) (1.00175 0.00852797 0) (1.00179 0.00789922 -2.61239e-27) (1.00181 0.0072558 2.61239e-27) (1.00184 0.00659957 0) (1.00186 0.00593222 0) (1.00188 0.00525531 0) (1.00189 0.00457028 0) (1.0019 0.00387845 0) (1.00191 0.00318104 0) (1.00192 0.00247923 -1.3149e-27) (1.00192 0.00177414 1.3149e-27) (1.00192 0.00106643 -2.49645e-27) (1.00193 0.000355979 2.52524e-27) (1.00029 0.00348313 0) (1.00028 0.00373891 0) (1.00027 0.00397569 0) (1.00025 0.00419215 0) (1.00024 0.0043825 0) (1.00022 0.00454528 0) (1.00021 0.00468054 0) (1.00019 0.0047885 0) (1.00017 0.00486954 0) (1.00015 0.00492424 0) (1.00013 0.00495345 0) (1.00011 0.00495821 0) (1.00009 0.00493972 0) (1.00008 0.00489932 0) (1.00006 0.00483845 0) (1.00005 0.00475857 0) (1.00004 0.0046612 0) (1.00002 0.00454781 0) (1.00002 0.00441985 4.9729e-11) (1.00001 0.00427871 -4.9729e-11) (1 0.00412569 0) (0.999999 0.00396202 0) (0.999996 0.00378883 0) (0.999995 0.00360718 0) (0.999994 0.00341803 -2.0763e-27) (0.999994 0.00322224 2.0763e-27) (0.999995 0.00302061 2.03716e-27) (0.999997 0.00281384 -2.03716e-27) (0.999999 0.00260259 -2.78436e-28) (1 0.00238744 2.78436e-28) (1 0.00216891 0) (1.00001 0.00194746 0) (1.00001 0.00172352 0) (1.00001 0.00149748 0) (1.00001 0.00126969 0) (1.00001 0.00104045 0) (1.00001 0.000810059 1.92231e-27) (1.00002 0.000578679 -1.92231e-27) (1.00002 0.000346636 0) (1.00002 0.000115257 0) (0.993624 0.0173706 -8.94342e-22) (0.997144 0.00929003 3.83074e-22) (1.0003 0.00325923 -2.34083e-22) (0.99348 0.016684 3.01059e-21) (0.997085 0.00891788 4.668e-21) (1.0003 0.00312802 1.16809e-21) (0.993356 0.0159743 -7.25954e-21) (0.997035 0.00853591 -1.95949e-20) (1.00031 0.00299285 2.24631e-21) (0.993246 0.0152665 -3.09077e-22) (0.996991 0.00815402 1.17623e-20) (1.00032 0.00285733 -1.53128e-21) (0.99315 0.0145549 -4.57234e-21) (0.996952 0.00776993 3.93013e-21) (1.00033 0.00272111 4.25049e-21) (0.993066 0.0138364 1.19652e-20) (0.996918 0.00738289 -1.07605e-20) (1.00033 0.00258396 -7.99003e-21) (0.992992 0.0131117 -2.06438e-22) (0.996888 0.00699345 2.17744e-20) (1.00034 0.00244605 1.37909e-20) (0.992927 0.012382 9.58943e-21) (0.99686 0.00660181 -1.71986e-20) (1.00035 0.00230756 -2.23565e-20) (0.99287 0.0116479 5.06317e-21) (0.996836 0.00620825 1.01282e-20) (1.00036 0.00216862 1.87731e-20) (0.992819 0.0109095 -2.04303e-20) (0.996814 0.00581309 -8.12217e-21) (1.00037 0.00202935 -1.985e-20) (0.992775 0.010167 2.11272e-20) (0.996794 0.00541661 -1.74363e-20) (1.00038 0.00188981 3.31073e-20) (0.992735 0.00942233 -7.23498e-21) (0.996776 0.00501898 1.40318e-20) (1.00039 0.00175009 -4.18836e-20) (0.992701 0.0086767 9.63114e-21) (0.99676 0.00462038 1.88096e-20) (1.0004 0.00161023 2.76811e-20) (0.99267 0.00792861 -8.22478e-21) (0.996746 0.00422095 -2.84376e-20) (1.00041 0.00147027 -1.10653e-20) (0.992644 0.00717812 1.13303e-20) (0.996733 0.0038208 8.47345e-21) (1.00041 0.00133026 1.17558e-20) (0.992621 0.00642595 -1.30952e-20) (0.996721 0.00342005 1.22685e-20) (1.00042 0.00119021 -1.36696e-20) (0.992601 0.00567251 -1.26183e-20) (0.996711 0.00301878 -1.28613e-20) (1.00043 0.00105015 -9.87992e-21) (0.992584 0.00491802 3.13444e-20) (0.996703 0.00261708 -9.77873e-21) (1.00043 0.000910087 9.05945e-22) (0.992569 0.00416269 -8.75327e-21) (0.996695 0.00221503 4.11708e-21) (1.00044 0.000770035 2.13457e-20) (0.992558 0.00340668 -1.69679e-20) (0.996689 0.00181268 7.63832e-21) (1.00044 0.000629996 -1.42949e-20) (0.981546 0.00406517 8.45237e-21) (0.992548 0.00265014 5.10691e-21) (0.996684 0.0014101 2.40221e-21) (1.00045 0.000489975 2.87195e-21) (0.981524 0.00290492 -7.28816e-21) (0.992542 0.00189322 4.48287e-21) (0.996681 0.00100734 -7.793e-21) (1.00045 0.000349969 4.41568e-21) (0.981509 0.00174344 -7.67602e-22) (0.992537 0.00113604 7.32762e-22) (0.996678 0.000604451 3.23088e-21) (1.00045 0.000209976 -6.76394e-22) (0.981502 0.000581227 7.08887e-22) (0.992535 0.000378696 -7.30375e-22) (0.996677 0.000201492 6.70597e-22) (1.00045 6.9991e-05 8.56725e-22) (0.981502 -0.000581227 1.09217e-21) (0.992535 -0.000378696 -1.07349e-21) (0.996677 -0.000201492 6.81391e-22) (1.00045 -6.9991e-05 8.44084e-22) (0.981509 -0.00174344 -4.40705e-22) (0.992537 -0.00113604 3.0322e-22) (0.996678 -0.000604451 3.84378e-21) (1.00045 -0.000209976 -8.18634e-22) (0.981524 -0.00290492 -8.05769e-21) (0.992542 -0.00189322 4.94762e-21) (0.996681 -0.00100734 -7.72734e-21) (1.00045 -0.000349969 3.74938e-21) (0.981546 -0.00406517 6.29397e-21) (0.992548 -0.00265014 4.78101e-21) (0.996684 -0.0014101 1.91306e-21) (1.00045 -0.000489975 2.80494e-21) (0.992558 -0.00340668 -1.70358e-20) (0.996689 -0.00181268 8.8129e-21) (1.00044 -0.000629996 -1.46678e-20) (0.992569 -0.00416269 -1.23782e-20) (0.996695 -0.00221503 6.79776e-21) (1.00044 -0.000770035 2.08444e-20) (0.992584 -0.00491802 3.58609e-20) (0.996703 -0.00261708 -1.2234e-20) (1.00043 -0.000910087 1.45799e-21) (0.992601 -0.00567251 -9.68769e-21) (0.996711 -0.00301878 -1.2266e-20) (1.00043 -0.00105015 -1.03634e-20) (0.992621 -0.00642595 -1.30224e-20) (0.996721 -0.00342005 1.34721e-20) (1.00042 -0.00119021 -1.34254e-20) (0.992644 -0.00717812 1.34252e-20) (0.996733 -0.0038208 1.05953e-20) (1.00041 -0.00133026 1.20745e-20) (0.99267 -0.00792861 -1.06257e-20) (0.996746 -0.00422094 -2.97277e-20) (1.00041 -0.00147027 -9.98847e-21) (0.992701 -0.0086767 4.59558e-21) (0.99676 -0.00462038 1.95441e-20) (1.0004 -0.00161023 2.85618e-20) (0.992735 -0.00942233 -7.43188e-21) (0.996776 -0.00501898 1.70148e-20) (1.00039 -0.00175009 -4.10919e-20) (0.992775 -0.010167 1.27766e-20) (0.996794 -0.00541661 -1.61058e-20) (1.00038 -0.00188981 3.12847e-20) (0.992819 -0.0109095 -2.3024e-20) (0.996814 -0.00581309 -4.32266e-21) (1.00037 -0.00202935 -2.17791e-20) (0.99287 -0.0116479 -6.77727e-21) (0.996836 -0.00620825 1.22032e-20) (1.00036 -0.00216862 1.78632e-20) (0.992927 -0.012382 1.51376e-20) (0.99686 -0.00660181 -1.78496e-20) (1.00035 -0.00230756 -2.17533e-20) (0.992992 -0.0131117 -4.37308e-21) (0.996888 -0.00699345 2.86948e-20) (1.00034 -0.00244605 1.13349e-20) (0.993066 -0.0138364 8.86959e-21) (0.996918 -0.00738289 -9.80719e-21) (1.00033 -0.00258396 -8.45481e-21) (0.99315 -0.0145549 1.17602e-21) (0.996952 -0.00776993 9.87122e-22) (1.00033 -0.00272111 4.14821e-21) (0.993246 -0.0152665 3.61284e-21) (0.996991 -0.00815402 9.19387e-21) (1.00032 -0.00285733 -1.48146e-21) (0.993356 -0.0159743 -2.00816e-20) (0.997035 -0.00853591 -1.44065e-20) (1.00031 -0.00299285 8.50256e-22) (0.99348 -0.016684 4.56701e-21) (0.997085 -0.00891788 -1.42091e-21) (1.0003 -0.00312802 5.81324e-21) (0.993624 -0.0173706 7.34243e-22) (0.997144 -0.00929003 7.83593e-21) (1.0003 -0.00325923 -2.38701e-21) (0.993942 -0.0185084 0) (0.997273 -0.00992818 0) (1.00029 -0.00348313 0) (0.99449 -0.01981 0) (0.997488 -0.0107168 0) (1.00028 -0.00373891 0) (0.995082 -0.0210212 0) (0.997716 -0.0114506 0) (1.00027 -0.00397569 0) (0.995699 -0.0221266 0) (0.997955 -0.0121145 0) (1.00025 -0.00419215 0) (0.996324 -0.0230905 0) (0.998203 -0.0126952 0) (1.00024 -0.0043825 0) (0.996942 -0.0239042 0) (0.998454 -0.0131909 0) (1.00022 -0.00454528 0) (0.997547 -0.0245686 0) (0.998707 -0.0136038 0) (1.00021 -0.00468054 0) (0.998131 -0.0250858 0) (0.998958 -0.0139359 0) (1.00019 -0.0047885 0) (0.998693 -0.0254588 3.34829e-27) (0.999206 -0.01419 -2.52586e-27) (1.00017 -0.00486954 0) (0.999231 -0.0256923 -3.34829e-27) (0.999448 -0.0143688 2.52586e-27) (1.00015 -0.00492424 0) (0.999742 -0.0257922 0) (0.999682 -0.0144757 0) (1.00013 -0.00495345 0) (1.00023 -0.0257655 0) (0.999906 -0.0145138 0) (1.00011 -0.00495821 0) (1.00069 -0.0256199 0) (1.00012 -0.0144866 0) (1.00009 -0.00493972 0) (1.00112 -0.0253635 0) (1.00032 -0.0143975 0) (1.00008 -0.00489932 0) (1.00153 -0.0250047 0) (1.0005 -0.0142501 0) (1.00006 -0.00483845 0) (1.00192 -0.0245519 0) (1.00067 -0.0140477 0) (1.00005 -0.00475857 0) (1.00228 -0.0240132 0) (1.00083 -0.0137938 0) (1.00004 -0.0046612 0) (1.00262 -0.0233965 0) (1.00097 -0.0134918 0) (1.00002 -0.00454781 0) (1.00294 -0.0227094 0) (1.0011 -0.0131451 2.90598e-27) (1.00002 -0.00441985 0) (1.00323 -0.0219588 0) (1.00121 -0.012757 -2.90598e-27) (1.00001 -0.00427871 0) (1.0035 -0.0211513 0) (1.00132 -0.0123307 0) (1 -0.00412569 0) (1.00375 -0.020293 0) (1.00141 -0.0118695 0) (0.999999 -0.00396202 0) (1.00398 -0.0193894 0) (1.00149 -0.0113762 0) (0.999996 -0.00378883 0) (1.00418 -0.0184456 0) (1.00156 -0.010854 0) (0.999995 -0.00360718 0) (1.00437 -0.0174662 2.04302e-27) (1.00162 -0.0103055 -1.42322e-27) (0.999994 -0.00341803 0) (1.00455 -0.0164555 -2.04302e-27) (1.00167 -0.00973334 1.42322e-27) (0.999994 -0.00322224 0) (1.0047 -0.0154171 2.00024e-27) (1.00171 -0.00914006 -1.39562e-27) (0.999995 -0.00302061 0) (1.00484 -0.0143546 -2.00024e-27) (1.00175 -0.00852797 1.39562e-27) (0.999997 -0.00281384 0) (1.00496 -0.013271 3.17788e-27) (1.00179 -0.00789922 0) (0.999999 -0.00260259 -3.24222e-27) (1.00507 -0.0121691 -3.17788e-27) (1.00181 -0.0072558 0) (1 -0.00238744 3.24222e-27) (1.00516 -0.0110514 0) (1.00184 -0.00659957 0) (1 -0.00216891 0) (1.00524 -0.00992014 0) (1.00186 -0.00593222 0) (1.00001 -0.00194746 0) (1.00532 -0.00877731 0) (1.00188 -0.00525531 0) (1.00001 -0.00172352 0) (1.00538 -0.00762474 0) (1.00189 -0.00457028 0) (1.00001 -0.00149748 0) (1.00543 -0.00646409 0) (1.0019 -0.00387845 0) (1.00001 -0.00126969 0) (1.00547 -0.00529685 0) (1.00191 -0.00318104 0) (1.00001 -0.00104045 0) (1.0055 -0.00412434 -1.87696e-27) (1.00192 -0.00247923 1.3149e-27) (1.00001 -0.000810059 0) (1.00552 -0.00294772 1.87696e-27) (1.00192 -0.00177414 -1.3149e-27) (1.00002 -0.000578679 0) (1.00554 -0.00176835 0) (1.00192 -0.00106643 0) (1.00002 -0.000346636 0) (1.00555 -0.000589101 0) (1.00193 -0.000355979 0) (1.00002 -0.000115257 0) ) ; boundaryField { inlet { type uniformFixedValue; uniformValue constant (1 0 0); value uniform (1 0 0); } outlet { type pressureInletOutletVelocity; value nonuniform 0(); } cylinder { type fixedValue; value nonuniform 0(); } top { type symmetryPlane; } bottom { type symmetryPlane; } defaultFaces { type empty; } procBoundary0to1 { type processor; value nonuniform List<vector> 130 ( (0.98512 0.0278504 0) (0.986342 0.0297895 0) (0.987678 0.0315773 0) (0.989095 0.0331661 0) (0.990564 0.0345135 0) (0.992055 0.0356197 0) (0.993546 0.0364962 0) (0.995018 0.0371539 0) (0.996453 0.0376042 -5.73654e-11) (0.997838 0.0378583 5.73654e-11) (0.999162 0.0379281 -5.5397e-11) (1.00041 0.0378249 5.5397e-11) (1.00159 0.03756 0) (1.00268 0.0371441 0) (1.00369 0.0365879 0) (1.00461 0.0359018 0) (1.00546 0.0350959 -4.99681e-11) (1.00622 0.03418 4.99681e-11) (1.00691 0.0331639 3.49782e-27) (1.00753 0.0320566 -3.49782e-27) (1.00808 0.0308673 0) (1.00857 0.0296043 0) (1.009 0.0282756 2.03774e-27) (1.00938 0.0268886 -2.03774e-27) (1.00972 0.0254504 -4.44566e-11) (1.01001 0.0239671 4.44566e-11) (1.01027 0.0224448 1.94003e-27) (1.01049 0.0208885 -1.94003e-27) (1.01069 0.019303 0) (1.01085 0.0176926 0) (1.01099 0.0160609 -8.36695e-11) (1.01111 0.0144114 8.36695e-11) (1.01121 0.0127468 0) (1.0113 0.01107 0) (1.01137 0.00938296 0) (1.01142 0.00768787 0) (1.01146 0.00598651 0) (1.01149 0.00428054 0) (1.01151 0.00257098 2.91954e-27) (1.01152 0.000857684 -2.95321e-27) (0.984414 0.0262044 6.17985e-22) (0.984084 0.0251839 2.87151e-22) (0.983788 0.0241303 -1.45979e-20) (0.983521 0.0230832 1.48013e-20) (0.98328 0.0220294 6.46613e-21) (0.983061 0.0209629 8.521e-21) (0.982863 0.0198851 1.11604e-21) (0.982685 0.0187976 -6.72142e-21) (0.982523 0.0177012 -2.92738e-20) (0.982378 0.0165966 1.89973e-20) (0.982247 0.0154845 -1.64887e-20) (0.98213 0.0143653 1.47339e-20) (0.982024 0.0132397 -7.56669e-22) (0.981931 0.0121082 1.71537e-20) (0.981848 0.0109712 -7.19565e-21) (0.981776 0.00982943 -5.52363e-22) (0.981713 0.00868326 -5.6856e-21) (0.981658 0.00753322 -2.06461e-20) (0.981613 0.00637985 2.39657e-20) (0.981575 0.00522365 -6.94937e-21) (0.981575 0.00522365 -6.94937e-21) (0.970268 0.00604286 4.95557e-21) (0.970212 0.00431668 2.85935e-21) (0.970175 0.00259014 4.04696e-22) (0.970157 0.000863403 -1.93058e-21) (0.970157 -0.000863403 -2.27406e-21) (0.970175 -0.00259014 4.48749e-22) (0.970212 -0.00431668 3.03334e-21) (0.970268 -0.00604286 8.29662e-21) (0.981575 -0.00522365 -8.89822e-21) (0.981575 -0.00522365 -8.89822e-21) (0.981613 -0.00637985 2.08151e-20) (0.981658 -0.00753322 -2.01591e-20) (0.981713 -0.00868326 -4.05838e-21) (0.981776 -0.00982943 3.86048e-21) (0.981848 -0.0109712 -2.3102e-21) (0.981931 -0.0121082 8.50688e-21) (0.982024 -0.0132397 1.81647e-21) (0.98213 -0.0143653 1.80954e-20) (0.982247 -0.0154845 -2.68838e-20) (0.982378 -0.0165966 2.84086e-20) (0.982523 -0.0177012 -3.15879e-20) (0.982685 -0.0187976 1.30966e-21) (0.982863 -0.0198851 -1.47013e-21) (0.983061 -0.0209629 3.64076e-21) (0.98328 -0.0220294 2.66858e-21) (0.983521 -0.0230832 2.58624e-20) (0.983788 -0.0241303 -2.57028e-20) (0.984084 -0.0251839 3.30482e-21) (0.984414 -0.0262044 5.2985e-21) (0.98512 -0.0278504 0) (0.986342 -0.0297895 0) (0.987678 -0.0315773 0) (0.989095 -0.0331661 0) (0.990564 -0.0345135 0) (0.992055 -0.0356197 0) (0.993546 -0.0364962 0) (0.995018 -0.0371539 0) (0.996453 -0.0376042 0) (0.997838 -0.0378583 0) (0.999162 -0.0379281 0) (1.00041 -0.0378249 0) (1.00159 -0.03756 0) (1.00268 -0.0371441 0) (1.00369 -0.0365879 0) (1.00461 -0.0359018 0) (1.00546 -0.0350959 0) (1.00622 -0.03418 0) (1.00691 -0.0331639 -3.49782e-27) (1.00753 -0.0320566 3.49782e-27) (1.00808 -0.0308673 0) (1.00857 -0.0296043 0) (1.009 -0.0282755 0) (1.00938 -0.0268886 0) (1.00972 -0.0254504 0) (1.01001 -0.0239671 0) (1.01027 -0.0224448 0) (1.01049 -0.0208885 0) (1.01069 -0.019303 0) (1.01085 -0.0176926 0) (1.01099 -0.0160609 0) (1.01111 -0.0144114 0) (1.01121 -0.0127468 0) (1.0113 -0.01107 0) (1.01137 -0.00938296 0) (1.01142 -0.00768787 0) (1.01146 -0.00598651 1.81026e-27) (1.01149 -0.00428054 -1.81026e-27) (1.01151 -0.00257098 0) (1.01152 -0.000857684 0) ) ; } } // ************************************************************************* //
[ "chaseh13@login4.stampede2.tacc.utexas.edu" ]
chaseh13@login4.stampede2.tacc.utexas.edu
f94fea4e83ee4e11b69da28aa3b4b010f9cf6840
92c4eb7b4e66e82fda6684d7c98a6a66203d930a
/src/FW/actors/Terminal.cc
4499fbb1537bd104cef108d4a6dd991bc3ff99bd
[]
no_license
grouptheory/SEAN
5ea2ab3606898d842b36d5c4941a5685cda529d9
6aa7d7a81a6f71a5f2a4f52f15d8e50b863f05b4
refs/heads/master
2020-03-16T23:15:51.392537
2018-05-11T17:49:18
2018-05-11T17:49:18
133,071,079
0
0
null
null
null
null
UTF-8
C++
false
false
1,945
cc
// -*- C++ -*- // +++++++++++++++ // S E A N --- Signalling Entity for ATM Networks --- // +++++++++++++++ // Version: 1.0.1 // // Copyright (c) 1998 // Naval Research Laboratory (NRL/CCS) // and the // Defense Advanced Research Projects Agency (DARPA) // // All Rights Reserved. // // Permission to use, copy, and modify this software and its // documentation is hereby granted, provided that both the copyright notice and // this permission notice appear in all copies of the software, derivative // works or modified versions, and any portions thereof, and that both notices // appear in supporting documentation. // // NRL AND DARPA ALLOW FREE USE OF THIS SOFTWARE IN ITS "AS IS" CONDITION AND // DISCLAIM ANY LIABILITY OF ANY KIND FOR ANY DAMAGES WHATSOEVER RESULTING FROM // THE USE OF THIS SOFTWARE. // // NRL and DARPA request users of this software to return modifications, // improvements or extensions that they make to: // // sean-dev@cmf.nrl.navy.mil // -or- // Naval Research Laboratory, Code 5590 // Center for Computation Science // Washington, D.C. 20375 // // and grant NRL and DARPA the rights to redistribute these changes in // future upgrades. // // -*- C++ -*- #ifndef LINT static char const _Terminal_cc_rcsid_[] = "$Id: Terminal.cc,v 1.1 1999/01/13 19:12:11 mountcas Exp $"; #endif #include <common/cprototypes.h> #include <FW/basics/Conduit.h> #include <FW/actors/Terminal.h> #include <FW/basics/Visitor.h> #include <FW/behaviors/Behavior.h> void Terminal::Inject(Visitor * v) { Conduit * c = 0; Behavior * b = _behavior; assert(v && b); // This allows derived terminals to record events like call submission InjectionNotification(v); v->SetLast(b->GetOwner()); // this also puts birth in the log if (c = b->OwnerSideA()) c->Accept(v); else v->Suicide(); }
[ "grouptheory@gmail.com" ]
grouptheory@gmail.com
5215a1051ccadd7a8229f481cb7134cf17d68564
525b6ab973b23d8333fad39dcd530c217e14741f
/stop_variables/mt2w.cc
47e35f0e46147889803b3f0efec15535d6ff1933
[]
no_license
mialiu149/AnalysisLoopers2015
2aa4ec86d6bd75a1510231813b7dc5e11acd1bd6
718c8b33243042f330cbc872af1f805106d4143e
refs/heads/master
2020-12-15T04:08:49.690916
2019-01-17T20:45:50
2019-01-17T20:45:50
44,395,757
1
0
null
null
null
null
UTF-8
C++
false
false
8,677
cc
#include "mt2w.h" // //-------------------------------------------------------------------- // original 8 TeV function double calculateMT2w(vector<LorentzVector>& jets, vector<bool>& btag, LorentzVector& lep, float met, float metphi){ // I am asumming that jets is sorted by Pt assert ( jets.size() == btag.size() ); // require at least 2 jets if ( jets.size()<2 ) return -999.; // First we count the number of b-tagged jets, and separate those non b-tagged std::vector<int> bjets; std::vector<int> non_bjets; for( unsigned int i = 0 ; i < jets.size() ; i++ ){ if( btag.at(i) ) { bjets.push_back(i); } else { non_bjets.push_back(i); } } int n_btag = (int) bjets.size(); // cout << "n_btag = " << n_btag << endl; // We do different things depending on the number of b-tagged jets // arXiv:1203.4813 recipe int nMax=-1; if(jets.size()<=3) nMax=non_bjets.size(); else nMax=3; if (n_btag == 0){ // 0 b-tags // If no b-jets select the minimum of the mt2w from all combinations with // the three leading jets float min_mt2w = 9999; for (int i=0; i<nMax; i++) for (int j=0; j<nMax; j++){ if (i == j) continue; float c_mt2w = mt2wWrapper(lep, jets[non_bjets[i]], jets[non_bjets[j]], met, metphi); if (c_mt2w < min_mt2w) min_mt2w = c_mt2w; } return min_mt2w; } else if (n_btag == 1 ){ // 1 b-tags // if only one b-jet choose the three non-b leading jets and choose the smaller float min_mt2w = 9999; for (int i=0; i<nMax; i++){ float c_mt2w = mt2wWrapper(lep, jets[bjets[0]], jets[non_bjets[i]], met, metphi); if (c_mt2w < min_mt2w) min_mt2w = c_mt2w; } for (int i=0; i<nMax; i++){ float c_mt2w = mt2wWrapper(lep, jets[non_bjets[i]], jets[bjets[0]], met, metphi); if (c_mt2w < min_mt2w) min_mt2w = c_mt2w; } return min_mt2w; } else if (n_btag >= 2) { // >=2 b-tags // if 3 or more b-jets the paper says ignore b-tag and do like 0-bjets // but we are going to make the combinations with the b-jets float min_mt2w = 9999; for (int i=0; i<n_btag; i++) for (int j=0; j<n_btag; j++){ if (i == j) continue; float c_mt2w = mt2wWrapper(lep, jets[bjets[i]], jets[bjets[j]], met, metphi); if (c_mt2w < min_mt2w) min_mt2w = c_mt2w; } return min_mt2w; } return -1.; } // This funcion is a wrapper for mt2w_bisect etc that takes LorentzVectors instead of doubles // original 8 TeV function double mt2wWrapper(LorentzVector& lep, LorentzVector& jet_o, LorentzVector& jet_b, float met, float metphi){ // same for all MT2x variables double metx = met * cos( metphi ); double mety = met * sin( metphi ); double pl[4]; // Visible lepton double pb1[4]; // bottom on the same side as the visible lepton double pb2[4]; // other bottom, paired with the invisible W double pmiss[3]; // <unused>, pmx, pmy missing pT int mydigit = 3; pl[0] = JetUtil::round(lep.E(), mydigit); pl[1] = JetUtil::round(lep.Px(), mydigit); pl[2] = JetUtil::round(lep.Py(), mydigit); pl[3] = JetUtil::round(lep.Pz(), mydigit); pb1[1] = JetUtil::round(jet_o.Px(),mydigit); pb1[2] = JetUtil::round(jet_o.Py(),mydigit); pb1[3] = JetUtil::round(jet_o.Pz(),mydigit); pb2[1] = JetUtil::round(jet_b.Px(),mydigit); pb2[2] = JetUtil::round(jet_b.Py(),mydigit); pb2[3] = JetUtil::round(jet_b.Pz(),mydigit); pmiss[0] = JetUtil::round(0., mydigit); pmiss[1] = JetUtil::round(metx, mydigit); pmiss[2] = JetUtil::round(mety, mydigit); pb1[0] = JetUtil::round(jet_o.E(), mydigit); pb2[0] = JetUtil::round(jet_b.E(), mydigit); mt2w_bisect::mt2w mt2w_event; mt2w_event.set_momenta(pl, pb1, pb2, pmiss); return mt2w_event.get_mt2w(); } //new MT2W function (gives btag values, and has additional functionality) // deprecated //allows for non-massive bjets (not tested) //addnjets: if <2 b-jets, add non-bjets up to total addnjets 'b-jets' (default = 3, recommended = 1,2) //addjets: ==1: add additional jets according to highest b-tag discriminant, ==2: add additional jets according to highest jet-pt /*float CalculateMT2w_(vector<LorentzVector> jets, vector<float> btag, float btagdiscr, LorentzVector lep, float met, float metphi, unsigned int addnjets, int addjets){ if(jets.size()!=btag.size()) return -99.; vector<LorentzVector> bjet = JetUtil::BJetSelector(jets,btag,btagdiscr,2,addnjets,addjets); if(bjet.size()<2) return -999.; float min_mt2w = 9999; for (unsigned int i=0; i<bjet.size(); ++i){ for (unsigned int j=0; j<bjet.size(); ++j){ if (i == j) continue; float c_mt2w = mt2wWrapper(lep, bjet[i], bjet[j], met, metphi); if (c_mt2w < min_mt2w) min_mt2w = c_mt2w; } } return min_mt2w; }*/ //new MT2W function (gives btag values, and has additional functionality) // deprecated //see CalculateMT2w_ //uses LorentzVector for MET /*float CalculateMT2w(vector<LorentzVector> jets, vector<float> btag, float btagdiscr, LorentzVector lep, LorentzVector metlv, unsigned int addnjets, int addjets){ float met = metlv.Pt(); float metphi = metlv.Phi(); return CalculateMT2w_(jets,btag,btagdiscr,lep,met,metphi,addnjets,addjets); }*/ //new MT2W function (give directly bjets, and has additional functionality) // deprecated //allows for non-massive bjets (not tested) /*float CalculateMT2W_(vector<LorentzVector> bjet, LorentzVector lep, float met, float metphi){ if(bjet.size()<2) return -999.; float min_mt2w = 9999; for (unsigned int i=0; i<bjet.size(); ++i){ for (unsigned int j=0; j<bjet.size(); ++j){ if (i == j) continue; float c_mt2w = mt2wWrapper(lep, bjet[i], bjet[j], met, metphi); if (c_mt2w < min_mt2w) min_mt2w = c_mt2w; } } return min_mt2w; }*/ //new MT2W function (give directly bjets, and has additional functionality) // deprecated //see CalculateMT2W_ //uses LorentzVector for MET /*float CalculateMT2W(vector<LorentzVector> bjet, LorentzVector lep, LorentzVector metlv){ float met = metlv.Pt(); float metphi = metlv.Phi(); return CalculateMT2W_(bjet,lep,met,metphi); }*/ // 13 TeV implementation - full calculation needs JetUtil CSV ordering, see looper float CalcMT2W(vector<LorentzVector> bjets, vector<LorentzVector> addjets, LorentzVector lep, LorentzVector metlv){ float met = metlv.Pt(); float metphi = metlv.Phi(); return CalcMT2W_(bjets,addjets,lep,met,metphi); } // 13 TeV implementation - full calculation needs JetUtil CSV ordering, see looper float CalcMT2W_(vector<LorentzVector> bjets, vector<LorentzVector> addjets, LorentzVector lep, float met, float metphi){ if((bjets.size()+addjets.size())<2) return -999.; float min_mt2w = 9999; for (unsigned int i=0; i<bjets.size(); ++i){ for (unsigned int j=i+1; j<bjets.size(); ++j){ float c_mt2w = mt2wWrapper(lep, bjets[i], bjets[j], met, metphi); if (c_mt2w < min_mt2w) min_mt2w = c_mt2w; //cout << "MT2W " << c_mt2w << " for b1 " << bjets[i].Pt() << " and b2 " << bjets[j].Pt() << endl; c_mt2w = mt2wWrapper(lep, bjets[j], bjets[i], met, metphi); if (c_mt2w < min_mt2w) min_mt2w = c_mt2w; //cout << "MT2W " << c_mt2w << " for b1 " << bjets[j].Pt() << " and b2 " << bjets[i].Pt() << endl; } for (unsigned int j=0; j<addjets.size(); ++j){ float c_mt2w = mt2wWrapper(lep, bjets[i], addjets[j], met, metphi); if (c_mt2w < min_mt2w) min_mt2w = c_mt2w; //cout << "MT2W " << c_mt2w << " for b1 " << bjets[i].Pt() << " and a2 " << addjets[j].Pt() << endl; c_mt2w = mt2wWrapper(lep, addjets[j], bjets[i], met, metphi); if (c_mt2w < min_mt2w) min_mt2w = c_mt2w; //cout << "MT2W " << c_mt2w << " for a1 " << addjets[j].Pt() << " and b2 " << bjets[i].Pt() << endl; } } if(bjets.size()==0){ for (unsigned int j=1; j<addjets.size(); ++j){ float c_mt2w = mt2wWrapper(lep, addjets[0], addjets[j], met, metphi); if (c_mt2w < min_mt2w) min_mt2w = c_mt2w; c_mt2w = mt2wWrapper(lep, addjets[j], addjets[0], met, metphi); if (c_mt2w < min_mt2w) min_mt2w = c_mt2w; } } return min_mt2w; }
[ "miaoyuan.liu0@gmail.com" ]
miaoyuan.liu0@gmail.com
14bf65a3e4a854cda2e6f5212fbf4ccc8554ca50
64443c653af8246bf56f7630da7645136363bfcd
/graph.h
10bfe05fa6c3c6fb7e9edf5f445ac0a2bfcbfecb
[]
no_license
tallisson/fluxo_carga
4bb9e438973ee2dab2722f4710adb22897a9a33b
b0adb0508bc3003a68dc3e7ac4c529d30b9a8283
refs/heads/master
2020-07-21T01:58:32.210617
2016-11-14T19:28:46
2016-11-14T19:28:46
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,018
h
#ifndef GRAPH_H_ #define GRAPH_H_ #include "branch.h" #include "bus.h" #include "ns3/ptr.h" #include "ns3/object.h" #include "ns3/type-id.h" #include <string> #include <map> namespace ns3 { class Graph : public Object { private: uint32_t m_numBus; uint32_t m_numBranch; uint32_t m_numPQ; uint32_t m_numPV; uint32_t m_numSlack; uint32_t m_posSlack; //uint32_t m_noSlack; std::map<uint32_t, Ptr<Bus> > m_buses; std::vector<Ptr<Branch> > m_branches; public: Graph(); virtual ~Graph(); static TypeId GetTypeId (void); void AddBus(Ptr<Bus> bus); void Assoc(Ptr<Branch> branch); uint32_t GetPosSlack(void) const; void SetPosSlack (uint32_t posSlack); std::map<uint32_t, Ptr<Bus> > GetBuses() const; Ptr<Bus> GetBus(uint32_t idBus); std::vector<Ptr<Branch> > GetBranches() const; uint32_t GetNumBus() const; uint32_t GetNumBranch() const; uint32_t GetNumPQ() const; void SetNumPQ (uint32_t numPQ); void SetNumPV (uint32_t numPV); uint32_t GetNumPV() const; }; } #endif // GRAPH_H_
[ "allissonribeiro02@gmail.com" ]
allissonribeiro02@gmail.com
8f4b13baa0b3d61774802cc93660f787f697799e
87a522ab62ce1dc073579bf8acf400e87fe4eb71
/ros_ws/devel/include/stdr_msgs/DeleteRobotFeedback.h
1c20d854b955ebbdc862c66cf717c6c2665bdd7f
[]
no_license
ElchananHaas/mdas-backup
410ed0798c2a0f3b069bb4141e706aab03cd0de7
e37e0a9cdbc3f22b8762640cc91a4a3f3e8a4f54
refs/heads/master
2021-09-17T23:32:17.228338
2018-07-06T19:28:35
2018-07-06T19:28:35
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,178
h
// Generated by gencpp from file stdr_msgs/DeleteRobotFeedback.msg // DO NOT EDIT! #ifndef STDR_MSGS_MESSAGE_DELETEROBOTFEEDBACK_H #define STDR_MSGS_MESSAGE_DELETEROBOTFEEDBACK_H #include <string> #include <vector> #include <map> #include <ros/types.h> #include <ros/serialization.h> #include <ros/builtin_message_traits.h> #include <ros/message_operations.h> namespace stdr_msgs { template <class ContainerAllocator> struct DeleteRobotFeedback_ { typedef DeleteRobotFeedback_<ContainerAllocator> Type; DeleteRobotFeedback_() { } DeleteRobotFeedback_(const ContainerAllocator& _alloc) { (void)_alloc; } typedef boost::shared_ptr< ::stdr_msgs::DeleteRobotFeedback_<ContainerAllocator> > Ptr; typedef boost::shared_ptr< ::stdr_msgs::DeleteRobotFeedback_<ContainerAllocator> const> ConstPtr; }; // struct DeleteRobotFeedback_ typedef ::stdr_msgs::DeleteRobotFeedback_<std::allocator<void> > DeleteRobotFeedback; typedef boost::shared_ptr< ::stdr_msgs::DeleteRobotFeedback > DeleteRobotFeedbackPtr; typedef boost::shared_ptr< ::stdr_msgs::DeleteRobotFeedback const> DeleteRobotFeedbackConstPtr; // constants requiring out of line definition template<typename ContainerAllocator> std::ostream& operator<<(std::ostream& s, const ::stdr_msgs::DeleteRobotFeedback_<ContainerAllocator> & v) { ros::message_operations::Printer< ::stdr_msgs::DeleteRobotFeedback_<ContainerAllocator> >::stream(s, "", v); return s; } } // namespace stdr_msgs namespace ros { namespace message_traits { // BOOLTRAITS {'IsFixedSize': True, 'IsMessage': True, 'HasHeader': False} // {'nav_msgs': ['/opt/ros/indigo/share/nav_msgs/cmake/../msg'], 'geometry_msgs': ['/opt/ros/indigo/share/geometry_msgs/cmake/../msg'], 'actionlib_msgs': ['/opt/ros/indigo/share/actionlib_msgs/cmake/../msg'], 'std_msgs': ['/opt/ros/indigo/share/std_msgs/cmake/../msg'], 'stdr_msgs': ['/home/mdas/ros_ws/src/stdr_simulator/stdr_msgs/msg', '/home/mdas/ros_ws/devel/share/stdr_msgs/msg']} // !!!!!!!!!!! ['__class__', '__delattr__', '__dict__', '__doc__', '__eq__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_parsed_fields', 'constants', 'fields', 'full_name', 'has_header', 'header_present', 'names', 'package', 'parsed_fields', 'short_name', 'text', 'types'] template <class ContainerAllocator> struct IsFixedSize< ::stdr_msgs::DeleteRobotFeedback_<ContainerAllocator> > : TrueType { }; template <class ContainerAllocator> struct IsFixedSize< ::stdr_msgs::DeleteRobotFeedback_<ContainerAllocator> const> : TrueType { }; template <class ContainerAllocator> struct IsMessage< ::stdr_msgs::DeleteRobotFeedback_<ContainerAllocator> > : TrueType { }; template <class ContainerAllocator> struct IsMessage< ::stdr_msgs::DeleteRobotFeedback_<ContainerAllocator> const> : TrueType { }; template <class ContainerAllocator> struct HasHeader< ::stdr_msgs::DeleteRobotFeedback_<ContainerAllocator> > : FalseType { }; template <class ContainerAllocator> struct HasHeader< ::stdr_msgs::DeleteRobotFeedback_<ContainerAllocator> const> : FalseType { }; template<class ContainerAllocator> struct MD5Sum< ::stdr_msgs::DeleteRobotFeedback_<ContainerAllocator> > { static const char* value() { return "d41d8cd98f00b204e9800998ecf8427e"; } static const char* value(const ::stdr_msgs::DeleteRobotFeedback_<ContainerAllocator>&) { return value(); } static const uint64_t static_value1 = 0xd41d8cd98f00b204ULL; static const uint64_t static_value2 = 0xe9800998ecf8427eULL; }; template<class ContainerAllocator> struct DataType< ::stdr_msgs::DeleteRobotFeedback_<ContainerAllocator> > { static const char* value() { return "stdr_msgs/DeleteRobotFeedback"; } static const char* value(const ::stdr_msgs::DeleteRobotFeedback_<ContainerAllocator>&) { return value(); } }; template<class ContainerAllocator> struct Definition< ::stdr_msgs::DeleteRobotFeedback_<ContainerAllocator> > { static const char* value() { return "# ====== DO NOT MODIFY! AUTOGENERATED FROM AN ACTION DEFINITION ======\n\ #feedback\n\ \n\ "; } static const char* value(const ::stdr_msgs::DeleteRobotFeedback_<ContainerAllocator>&) { return value(); } }; } // namespace message_traits } // namespace ros namespace ros { namespace serialization { template<class ContainerAllocator> struct Serializer< ::stdr_msgs::DeleteRobotFeedback_<ContainerAllocator> > { template<typename Stream, typename T> inline static void allInOne(Stream&, T) {} ROS_DECLARE_ALLINONE_SERIALIZER }; // struct DeleteRobotFeedback_ } // namespace serialization } // namespace ros namespace ros { namespace message_operations { template<class ContainerAllocator> struct Printer< ::stdr_msgs::DeleteRobotFeedback_<ContainerAllocator> > { template<typename Stream> static void stream(Stream&, const std::string&, const ::stdr_msgs::DeleteRobotFeedback_<ContainerAllocator>&) {} }; } // namespace message_operations } // namespace ros #endif // STDR_MSGS_MESSAGE_DELETEROBOTFEEDBACK_H
[ "cxy231@case.edu" ]
cxy231@case.edu
ee44fb7c2ad56cab13e4bdeddf3d0b93bf1b2ce9
eda9f799bfb03649423aab3438f4fab339c6287c
/products/cardframes/framecardoptions.cpp
0711323c9057750994bb1ac97c6c6cf12ab80d66
[]
no_license
MaratHmit/shopadmin_qt
0dc56e90c74927b139183135cd8e9e6158509227
d9345c5f20d7d2e6bac42d28901207f85fef29a8
refs/heads/master
2020-12-22T04:14:04.213302
2020-01-28T05:50:17
2020-01-28T05:50:17
236,667,356
0
0
null
null
null
null
UTF-8
C++
false
false
7,046
cpp
#include "framecardoptions.h" #include "ui_framecardoptions.h" #include "formoptionsparams.h" #include "formproducts.h" FrameCardOptions::FrameCardOptions(QWidget *parent, DataProduct *item, const int &typeDialog) : QDialog(parent), ui(new Ui::FrameCardOptions) { ui->setupUi(this); product = item; mTypeDialog = typeDialog; mOptions = item->listOptions(); mListPages = new QList<WidgetPageOptions *>(); mIsFilled = false; ui->widgetOrder->hide(); if (typeDialog) { setWindowFlags(Qt::Window); connect(ui->buttonOK, &QPushButton::clicked, this, &FrameCardOptions::onOk); connect(ui->buttonCancel, &QPushButton::clicked, this, &QDialog::reject); if (typeDialog == 2) { ui->widgetButtons->hide(); ui->tabWidget->setTabsClosable(false); ui->widgetOrder->show(); ui->lineEditName->setText(item->getName()); ui->lineEditPrice->setText(item->priceTitle()); } } else { setWindowFlags(Qt::Widget); ui->buttonOK->hide(); ui->buttonCancel->hide(); } initSignals(); } FrameCardOptions::~FrameCardOptions() { delete ui; delete mListPages; } bool FrameCardOptions::isAddOptions() const { return false; } void FrameCardOptions::fillControls() { if (mIsFilled) return; initOptions(); mOptions->setUnModified(); mIsFilled = true; } void FrameCardOptions::onAddOptions() { FormOptionsParams formParams(this, true); if (mOptions->size()) { ListOptions list; for (int i = 0; i < mOptions->size(); i++) list.append(mOptions->at(i)); formParams.setExludingOptions(&list); } if (formParams.exec() == QDialog::Accepted) { for (int i = 0; i < formParams.selectedList()->size(); i++) addPage(formParams.selectedList()->at(i), true); } } void FrameCardOptions::onCopyFromOtherProduct() { FormProducts *form = new FormProducts(this, false); if (form->exec() == QDialog::Accepted && form->getSelectedProducts()->size()) { DataProduct *cProduct = new DataProduct(form->getSelectedProducts()->at(0)); setCursor(Qt::WaitCursor); if (ApiAdapter::getApi()->getInfoProduct(cProduct)) { for (int i = 0; i < cProduct->listOptions()->size(); ++i) product->listOptions()->append(new DataOption(cProduct->listOptions()->at(i)), false); mIsFilled = false; fillControls(); product->listOptions()->setModified(); emit modified(); } delete cProduct; setCursor(Qt::ArrowCursor); } delete form; } void FrameCardOptions::onRemoveOption(const int &index) { WidgetPageOptions *page = 0; for (int i = 0; i < mListPages->size(); i++) if (ui->tabWidget->indexOf(mListPages->at(i)) == index) { page = mListPages->takeAt(i); break; } if (page) { ui->tabWidget->removeTab(index); mOptions->deleteItem(page->optionInfo()); } emit modified(); } void FrameCardOptions::onChecked() { QString originalName = product->getName(); QString nameOptions = QString(); qreal basePrice = product->price(); qreal price = 0; for (int i = 0; i < product->listOptions()->size(); i++) { DataOption *option = product->listOptions()->at(i); int type = option->property("type").toInt(); int typePrice = option->property("typePrice").toInt(); QString optionValue = QString(); for (int j = 0; j < option->optionValues()->size(); j++) { if (option->optionValues()->at(j)->getIsChecked()) { if (!optionValue.isEmpty()) optionValue = optionValue + ", "; optionValue = optionValue + option->optionValues()->at(j)->getName(); int count = 1; if (option->optionValues()->at(j)->count() > 1) count = option->optionValues()->at(j)->count(); if (typePrice == 0) price += option->optionValues()->at(j)->price() * count; else price += basePrice * option->optionValues()->at(j)->price() / 100; if (type != 2) break; } } if (!optionValue.isEmpty()) { if (!nameOptions.isEmpty()) nameOptions = nameOptions + "; "; nameOptions = nameOptions + option->getName() + ": " + optionValue; } } if (!nameOptions.isEmpty()) { ui->lineEditName->setText(originalName + " (" + nameOptions + ")"); price += basePrice; ui->lineEditPrice->setText(QString::number(price, 'f', 2)); } else { ui->lineEditName->setText(originalName); ui->lineEditPrice->setText(QString::number(basePrice, 'f', 2)); } } void FrameCardOptions::onOk() { product->setName(ui->lineEditName->text()); product->setPrice(ui->lineEditPrice->text().toDouble()); accept(); } void FrameCardOptions::addPage(DataOption *option, const bool &isNew) { if (WidgetPageOptions *page = getPageById(option->getId())) { ui->tabWidget->addTab(page, option->getName()); if (!option->property("position").isNull()) page->setPosition(option->property("position").toInt()); for (int i = 0; i < mOptions->size(); i++) if (mOptions->at(i)->getId() == option->getId()) { mOptions->at(i)->setIsChecked(true); break; } return; } DataOption *newOption; if (isNew) { newOption = new DataOption(option); mOptions->append(newOption); } else newOption = option; WidgetPageOptions *page = new WidgetPageOptions(this, newOption, mTypeDialog == 2); if (!newOption->property("position").isNull()) page->setPosition(newOption->property("position").toInt()); connect(page, SIGNAL(modified()), SIGNAL(modified())); if (mTypeDialog == 2) connect(page, SIGNAL(checked()), SLOT(onChecked())); ui->tabWidget->addTab(page, newOption->getName()); mListPages->push_back(page); } WidgetPageOptions *FrameCardOptions::getPageById(const QString &id) const { for (int i = 0; i < mListPages->size(); i++) { if (mListPages->at(i)->optionInfo()->getId() == id) return mListPages->at(i); } return 0; } void FrameCardOptions::initOptions() { if (!mOptions) return; for (int i = 0; i < mOptions->size(); i++) { mOptions->at(i)->setIsChecked(true); mOptions->at(i)->setUnModified(); addPage(mOptions->at(i)); } } void FrameCardOptions::initSignals() { connect(ui->toolButtonAddOption, SIGNAL(clicked()), SLOT(onAddOptions())); connect(ui->tabWidget, &QTabWidget::tabCloseRequested, this, &FrameCardOptions::onRemoveOption); connect(ui->toolButtonCopy, SIGNAL(clicked(bool)), SLOT(onCopyFromOtherProduct())); }
[ "hmm19792@gmail.com" ]
hmm19792@gmail.com
61cdc9adbcaec9e25f91357127d62b47bab6af6a
dd92b8cc9a2bca3a1b3d5ebf36fc00493a39dc2f
/src/tool/hpcrun/sample-sources/blame-shift/blame-map.c
5d8b5767e754302f617a64685f485075f8d4c1cb
[]
no_license
tjovanovic996/hpctoolkit-tracing
effb19b34430eea9df02f19e906b846782b52fa4
f93e17149985cc93a3c6c4654e2a6e472f681189
refs/heads/master
2020-07-09T19:58:55.783806
2019-08-23T21:09:23
2019-08-23T21:09:23
204,068,692
0
1
null
null
null
null
UTF-8
C++
false
false
7,394
c
// -*-Mode: C++;-*- // technically C99 // * BeginRiceCopyright ***************************************************** // // $HeadURL: $ // $Id$ // // -------------------------------------------------------------------------- // Part of HPCToolkit (hpctoolkit.org) // // Information about sources of support for research and development of // HPCToolkit is at 'hpctoolkit.org' and in 'README.Acknowledgments'. // -------------------------------------------------------------------------- // // Copyright ((c)) 2002-2019, Rice University // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // * Neither the name of Rice University (RICE) 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 RICE 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 RICE 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. // // ******************************************************* EndRiceCopyright * // // directed blame shifting for locks, critical sections, ... // /****************************************************************************** * system includes *****************************************************************************/ #include <assert.h> /****************************************************************************** * local includes *****************************************************************************/ #include "blame-map.h" #include <hpcrun/messages/messages.h> #include <lib/prof-lean/stdatomic.h> #include <memory/hpcrun-malloc.h> /****************************************************************************** * macros *****************************************************************************/ #define N (128*1024) #define INDEX_MASK ((N)-1) #define LOSSLESS_BLAME #ifdef BLAME_MAP_LOCKING #define do_lock() \ { \ for(;;) { \ if (fetch_and_store_i64(&thelock, 1) == 0) break; \ while (thelock == 1); \ } \ } #define do_unlock() thelock = 0 #else #define do_lock() #define do_unlock() #endif /****************************************************************************** * data type *****************************************************************************/ typedef struct { uint32_t obj_id; uint32_t blame; } blame_parts_t; typedef union { uint_fast64_t combined; blame_parts_t parts; } blame_all_t; union blame_entry_t { atomic_uint_fast64_t value; }; /*************************************************************************** * private data ***************************************************************************/ static uint64_t volatile thelock; /*************************************************************************** * private operations ***************************************************************************/ uint32_t blame_entry_obj_id(uint_fast64_t value) { blame_all_t entry; entry.combined = value; return entry.parts.obj_id; } uint32_t blame_entry_blame(uint_fast64_t value) { blame_all_t entry; entry.combined = value; return entry.parts.blame; } uint32_t blame_map_obj_id(uint64_t obj) { return ((uint32_t) ((uint64_t)obj) >> 2); } uint32_t blame_map_hash(uint64_t obj) { return ((uint32_t)((blame_map_obj_id(obj)) & INDEX_MASK)); } uint_fast64_t blame_map_entry(uint64_t obj, uint32_t metric_value) { blame_all_t be; be.parts.obj_id = blame_map_obj_id(obj); be.parts.blame = metric_value; return be.combined; } /*************************************************************************** * interface operations ***************************************************************************/ blame_entry_t* blame_map_new(void) { blame_entry_t* rv = hpcrun_malloc(N * sizeof(blame_entry_t)); blame_map_init(rv); return rv; } void blame_map_init(blame_entry_t table[]) { int i; for(i = 0; i < N; i++) { atomic_store(&table[i].value, 0); } } void blame_map_add_blame(blame_entry_t table[], uint64_t obj, uint32_t metric_value) { uint32_t obj_id = blame_map_obj_id(obj); uint32_t index = blame_map_hash(obj); assert(index >= 0 && index < N); do_lock(); uint_fast64_t oldval = atomic_load(&table[index].value); for(;;) { blame_all_t newval; newval.combined = oldval; newval.parts.blame += metric_value; uint32_t obj_at_index = newval.parts.obj_id; if(obj_at_index == obj_id) { #ifdef LOSSLESS_BLAME if (atomic_compare_exchange_strong_explicit(&table[index].value, &oldval, newval.combined, memory_order_relaxed, memory_order_relaxed)) break; #else // the atomicity is not needed here, but it is the easiest way to write this atomic_store(&table[index].value, newval.combined); break; #endif } else { if(newval.parts.obj_id == 0) { newval.combined = blame_map_entry(obj, metric_value); #ifdef LOSSLESS_BLAME if ((atomic_compare_exchange_strong_explicit(&table[index].value, &oldval, newval.combined, memory_order_relaxed, memory_order_relaxed))) break; // otherwise, try again #else // the atomicity is not needed here, but it is the easiest way to write this atomic_store(&table[index].value, newval.combined); break; #endif } else { EMSG("leaked blame %d\n", metric_value); // entry in use for another object's blame // in this case, since it isn't easy to shift // our blame efficiently, we simply drop it. break; } } } do_unlock(); } uint64_t blame_map_get_blame(blame_entry_t table[], uint64_t obj) { static uint64_t zero = 0; uint64_t val = 0; uint32_t obj_id = blame_map_obj_id(obj); uint32_t index = blame_map_hash(obj); assert(index >= 0 && index < N); do_lock(); for(;;) { uint_fast64_t oldval = atomic_load(&table[index].value); uint32_t entry_obj_id = blame_entry_obj_id(oldval); if(entry_obj_id == obj_id) { #ifdef LOSSLESS_BLAME if (!atomic_compare_exchange_strong_explicit(&table[index].value, &oldval, zero, memory_order_relaxed, memory_order_relaxed)) continue; // try again on failure #else table[index].all = 0; #endif val = (uint64_t) blame_entry_blame(oldval); } break; } do_unlock(); return val; }
[ "ax4@gpu.cs.rice.edu" ]
ax4@gpu.cs.rice.edu
2a13231b8e63dc0fca1b03ac00bd3d7017a32ccc
4b5ea843b81b17626fff180dac3b3bec82e8110e
/Plugins/BIPlugin/Source/BIPlugin/Private/PathPredictionEntry.cpp
c738e6cd3cb88bddc0cd82922ef78d8bbc500a10
[]
no_license
TeraNaidja/UE4BlueprintPlugin
75452e0302fcba5e3ff99b5838ea3b8f46ecb1c2
16784cf63b688c2fb451f728ee5f40a8e5d4e9d9
refs/heads/master
2016-09-03T03:49:17.131454
2015-09-22T11:29:19
2015-09-22T11:29:19
33,359,265
1
0
null
null
null
null
UTF-8
C++
false
false
683
cpp
#include "BIPluginPrivatePCH.h" #include "PathPredictionEntry.h" PathPredictionEntry::PathPredictionEntry() : m_NumUses(0) { } PathPredictionEntry::~PathPredictionEntry() { } bool PathPredictionEntry::CompareExcludingUses(const PathPredictionEntry& a_Other) const { return m_AnchorVertex == a_Other.m_AnchorVertex && m_PredictionVertex == a_Other.m_PredictionVertex && m_ContextPath == a_Other.m_ContextPath; } FArchive& operator << (FArchive& a_Archive, PathPredictionEntry& a_Value) { int32 direction = (int32)a_Value.m_Direction; return a_Archive << direction << a_Value.m_PredictionVertex << a_Value.m_AnchorVertex << a_Value.m_ContextPath << a_Value.m_NumUses; }
[ "phildegroot5@gmail.com" ]
phildegroot5@gmail.com
6615bbd13750a2da07b1f2389c80b3a1f2e3b0f4
4d603466d7abe1d9dced9bd4530cd6dffd6b9e17
/external/Box2d/Testbed/Tests/Breakable.h
bcb2927c438ec196c21f7e358ef47254c0b4696f
[ "MIT", "Zlib" ]
permissive
tearsofphoenix/TauEngine
92debd43f046ddc4b3e46952eb7046695d5513dc
61407d83b3167362631634bb75d975a77ee00acb
refs/heads/master
2021-01-09T05:36:28.708356
2012-10-31T02:07:07
2012-10-31T02:07:07
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,688
h
/* * Copyright (c) 2008-2009 Erin Catto http://www.box2d.org * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages * arising from the use of this software. * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely, subject to the following restrictions: * 1. The origin of this software must not be misrepresented; you must not * claim that you wrote the original software. If you use this software * in a product, an acknowledgment in the product documentation would be * appreciated but is not required. * 2. Altered source versions must be plainly marked as such, and must not be * misrepresented as being the original software. * 3. This notice may not be removed or altered from any source distribution. */ #ifndef BREAKABLE_TEST_H #define BREAKABLE_TEST_H // This is used to test sensor shapes. class Breakable : public Test { public: enum { e_count = 7 }; Breakable() { // Ground body { b2BodyDef bd; b2Body* ground = m_world->CreateBody(&bd); b2EdgeShape shape; shape.Set(b2Vec2(-40.0f, 0.0f), b2Vec2(40.0f, 0.0f)); ground->CreateFixture(&shape, 0.0f); } // Breakable dynamic body { b2BodyDef bd; bd.type = b2_dynamicBody; bd.position.Set(0.0f, 40.0f); bd.angle = 0.25f * b2_pi; m_body1 = m_world->CreateBody(&bd); m_shape1.SetAsBox(0.5f, 0.5f, b2Vec2(-0.5f, 0.0f), 0.0f); m_piece1 = m_body1->CreateFixture(&m_shape1, 1.0f); m_shape2.SetAsBox(0.5f, 0.5f, b2Vec2(0.5f, 0.0f), 0.0f); m_piece2 = m_body1->CreateFixture(&m_shape2, 1.0f); } m_break = false; m_broke = false; } virtual void PostSolve(b2Contact* contact, const b2ContactImpulse* impulse) { if (m_broke) { // The body already broke. return; } // Should the body break? int32 count = contact->GetManifold()->pointCount; float32 maxImpulse = 0.0f; for (int32 i = 0; i < count; ++i) { maxImpulse = b2Max(maxImpulse, impulse->normalImpulses[i]); } if (maxImpulse > 40.0f) { // Flag the body for breaking. m_break = true; } } void Break() { // Create two bodies from one. b2Body* body1 = m_piece1->GetBody(); b2Vec2 center = body1->GetWorldCenter(); body1->DestroyFixture(m_piece2); m_piece2 = NULL; b2BodyDef bd; bd.type = b2_dynamicBody; bd.position = body1->GetPosition(); bd.angle = body1->GetAngle(); b2Body* body2 = m_world->CreateBody(&bd); m_piece2 = body2->CreateFixture(&m_shape2, 1.0f); // Compute consistent velocities for new bodies based on // cached velocity. b2Vec2 center1 = body1->GetWorldCenter(); b2Vec2 center2 = body2->GetWorldCenter(); b2Vec2 velocity1 = m_velocity + b2Cross(m_angularVelocity, center1 - center); b2Vec2 velocity2 = m_velocity + b2Cross(m_angularVelocity, center2 - center); body1->SetAngularVelocity(m_angularVelocity); body1->SetLinearVelocity(velocity1); body2->SetAngularVelocity(m_angularVelocity); body2->SetLinearVelocity(velocity2); } void Step(Settings* settings) { if (m_break) { Break(); m_broke = true; m_break = false; } // Cache velocities to improve movement on breakage. if (m_broke == false) { m_velocity = m_body1->GetLinearVelocity(); m_angularVelocity = m_body1->GetAngularVelocity(); } Test::Step(settings); } static Test* Create() { return new Breakable; } b2Body* m_body1; b2Vec2 m_velocity; float32 m_angularVelocity; b2PolygonShape m_shape1; b2PolygonShape m_shape2; b2Fixture* m_piece1; b2Fixture* m_piece2; bool m_broke; bool m_break; }; #endif
[ "tearsofphoenix@yahoo.cn" ]
tearsofphoenix@yahoo.cn
5ebbfce2147b6f43a4a78934618f28350b3a597f
6b2a8dd202fdce77c971c412717e305e1caaac51
/solutions_5639104758808576_0/C++/Biigbang/p1.cpp
172bdebce242acbff444a988777c7cc8929189b9
[]
no_license
alexandraback/datacollection
0bc67a9ace00abbc843f4912562f3a064992e0e9
076a7bc7693f3abf07bfdbdac838cb4ef65ccfcf
refs/heads/master
2021-01-24T18:27:24.417992
2017-05-23T09:23:38
2017-05-23T09:23:38
84,313,442
2
4
null
null
null
null
UTF-8
C++
false
false
550
cpp
#include <stdio.h> const int maxs = 1001; char shy[maxs]; int T, S; int main() { int c, a; scanf("%d", &T); for(int t = 1; t <= T; ++t) { scanf("%d%s", &S, shy); c = a = 0; for(int i = 0; i <= S; ++i) { if (shy[i] > '0') { if (c >= i) { c += shy[i] - '0'; } else { a += i - c; c += shy[i] - '0' + a; } } } printf("Case #%d: %d\n", t, a); } return 0; }
[ "eewestman@gmail.com" ]
eewestman@gmail.com
c391aa1b2e300dec6ab17d9e4ab3adbd081bfbde
20252f132d754859b668d1fcbad36adc2b46a364
/classNonInherit.cpp
b48fd6d09b84c44d22b4331b651284b71ff64086
[]
no_license
weiwang1996/code-store
da341904000055bb14d78da2bb1c3dcfd8d80144
0bf7ad6858d3109be49a051820858ea8c0981a5f
refs/heads/master
2021-01-01T18:35:46.109755
2017-08-27T16:14:20
2017-08-27T16:14:20
98,372,348
0
0
null
null
null
null
GB18030
C++
false
false
1,077
cpp
#include<iostream> using namespace std; //第一种方法,封装构造函数,给出static接口,在继承的时候, //派生类构造函数的初始化列表上调基类的构造函数,调不到 //从而防止继承,但是这种方法只能在堆上产生对象,不能再栈上产生对象,有弊端 //class NonInherit //{ //public: // static NonInherit* GetObj(int a) // { // return new NonInherit(a); // } //private: // NonInherit(int a) // :_a(a) // {} // ~NonInherit() // {} // int _a; //}; //class B :public NonInherit //{ //public : // B() // :_b(0) // {} //private: // int _b; //}; //int main() //{ // NonInherit* p=NonInherit::GetObj(5); // return 0; //} //虚拟继承 template<typename T> class Makesealed { friend T; private: Makesealed(){} ~Makesealed(){} }; class SealedClass : virtual public Makesealed<SealedClass> { public: SealedClass(){} ~SealedClass(){} }; class Try:public SealedClass { public: Try(){} ~Try(){} }; int main() { SealedClass sea; Try try; return 0; }
[ "noreply@github.com" ]
weiwang1996.noreply@github.com
2097518b46463e03be06944097ad41cc42d2a386
a5b7a83c1aa0d6b98542f3862f5f39f697396233
/GameEnd.h
561ee3e32f58e10a7ac5e014dfe43e2e1c38e99c
[]
no_license
kang-hyungoo/PixeelGameEngine_Portfolio
51f3dd8fd4ad4ae03950151b348e937a0cc1a0f1
4f9d19aa26e4eb2a9afa4b76033f332e6f7b3909
refs/heads/main
2023-04-03T13:07:27.807824
2021-04-07T13:14:01
2021-04-07T13:14:01
345,810,893
0
0
null
null
null
null
UTF-8
C++
false
false
419
h
#pragma once #include <iostream> using namespace std; class cCircleShootor; class cGameEnd { private: string mGameScore; string mStart; bool mDisyplay = true; float mBlinkTime = 0.0f; public: void CreateTitle(cCircleShootor* tpCircle, int tScore); void UpdateTitle(float fElapsedTime, cCircleShootor* tpCircle); void DisplayTitle(cCircleShootor* tpCircle); void DestroyTitle(); };
[ "noreply@github.com" ]
kang-hyungoo.noreply@github.com
5a15cc8fdeb4ecd5ed92e6ff251da804e3db1cc4
d9432b3c1895a1c9a264c1d96dbf5e0dc12a9641
/UVa/volume-129/12938.cpp
54b486afd4d259c447d41152987e2eb3e84d01b9
[]
no_license
TheMartian0x48/CP
4ad21f41c71681a76c388690bacd876ab1d1848a
fd8492d59fc5410c6894ffa74b9c30b1b7ac2118
refs/heads/master
2023-06-28T08:04:22.659100
2021-07-22T07:49:15
2021-07-22T07:49:15
293,585,912
0
0
null
null
null
null
UTF-8
C++
false
false
1,201
cpp
/* * TheMartian0x48 * UVa 12938 */ #include <bits/stdc++.h> using namespace std; // clang-format off #define rep(i, a, b) for (int i = a; i < (b); ++i) #define per(i, a, b) for (int i = a; i >= (b); --i) #define trav(a, x) for (auto &a : x) #define all(x) x.begin(), x.end() #define rll(x) x.rbegin(), x.rend() #define sz(x) (int)x.size() using ll = long long; using ull = unsigned long long; using pii = pair<int, int>; using vi = vector<int>; using vii = vector<long long>; // (* read and write *) template <class T> void re(vector<T> &v, int n) {v.resize(n); for (auto &e : v) cin >> e;} template <class T> void re(vector<T> &v){for (auto &e : v) cin >> e;} // clang-format on void solve() { string s; cin >> s; int res = 0; for (int i = 0; i < 4; i++) { string t = s; for (char j = i ? '0' : '1'; j <= '9'; j++) { t[i] = j; if(t == s) continue; int n = stoi(t); int r = sqrt(n); res += r * r == n; } } cout << res << "\n"; } int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); int test; int testcase = 1; cin >> test; while (test--) { cout << "Case " << testcase++ << ": "; solve(); } }
[ "cr7.aditya.cs@gmail.com" ]
cr7.aditya.cs@gmail.com
e90761666534f3d1a02260f75faf0273fd6a6f6b
64cba1f3f335b6c7a53a3cc7011ad314cc261d56
/insertionSort.cpp
af322380b1671f9aaefa99e4510b0f3bdd2b5772
[]
no_license
AniruddhSringeri/1BM18CS015-ADA
0b68d8ba16609e5b575c4f06346cd63db241989a
9d7c1e33dd71ea7599f26ca1c70c6e32fe76f0b7
refs/heads/master
2020-12-29T13:50:52.706397
2020-05-09T04:47:56
2020-05-09T04:47:56
238,627,809
0
0
null
null
null
null
UTF-8
C++
false
false
713
cpp
#include<iostream> #include<ctime> #include<algorithm> int main() { clock_t t; int *a, n, temp; std::cout << "Enter the number of elements\n"; std::cin >> n; a = new int[n]; for(int i = 0; i < n; i++) { a[i] = rand() / 10; } t = clock(); for(int i = 1; i < n; i++) { int j = i - 1; temp = a[i]; while(j >= 0 && a[j] > temp) { a[j+1] = a[j]; j--; } a[j+1] = temp; } t = clock()- t; std::cout << "The sorted array is\n"; for(int i = 0; i < n; i++) { std::cout << a[i] << " "; } std::cout << "\nSorting time is: " << t << "\n"; return 0; }
[ "noreply@github.com" ]
AniruddhSringeri.noreply@github.com
f813dcb17b351f08c8ad0f141d8f1e7497c36864
522c65b867a502894dfb73b3525bde3d58d087a5
/C++/Leetcode/354.cpp
44e5fa59410ee25791ffb051ce871ce613a3fb7f
[]
no_license
QiuBiuBiu/LeetCode
57f34a4a2850151edaa7b84fb66ea485a3a5fc7e
dc14ef27dfee8379e8b5ec7f1518ba4a24c9c01e
refs/heads/master
2023-04-09T04:10:53.709832
2023-03-30T11:50:33
2023-03-30T11:50:33
148,468,830
1
0
null
null
null
null
UTF-8
C++
false
false
2,941
cpp
/* 354. 俄罗斯套娃信封问题 给你一个二维整数数组 envelopes ,其中 envelopes[i] = [wi, hi] ,表示第 i 个信封的宽度和高度。 当另一个信封的宽度和高度都比这个信封大的时候,这个信封就可以放进另一个信封里,如同俄罗斯套娃一样。 请计算 最多能有多少个 信封能组成一组“俄罗斯套娃”信封(即可以把一个信封放到另一个信封里面)。 */ /* PS:此题是300题的二维扩展,由于此题数据量较大,所以动态规划方法TLE 1)动态规划,T=O(n^2),S=O(n) 记f[i]为以i封信为最外层信封的最多信封序列。因为信封一开始是无序的,所以我们需要对其排序。 */ class Solution { public: int maxEnvelopes(vector<vector<int>>& envelopes) { sort(envelopes.begin(), envelopes.end(), [](vector<int>& a, vector<int>& b){ if (a[0] == b[0]) return a[1] < b[1]; return a[0] < b[0]; }); int res = 1; vector<int> f(envelopes.size(), 1); for (int i = 0; i < envelopes.size(); i++) { for (int j = 0; j < envelopes.size(); j++) { if (envelopes[i][0] > envelopes[j][0] && envelopes[i][1] > envelopes[j][1]) { f[i] = max(f[i], f[j] + 1); } } res = max(res, f[i]); } return res; } }; /* 2)二分法,T=O(nlogn),S=O(n) */ class Solution { public: int maxEnvelopes(vector<vector<int>>& envelopes) { sort(envelopes.begin(), envelopes.end(), [](vector<int>& a, vector<int>& b){ if (a[0] == b[0]) return a[1] > b[1]; // 注意这里,我们排序时,当宽度一致时,我们把高度按从大到小排序,而不是从小大到排(因为如果高度从小大到排序,可能导致高度一致的两封信封却被塞进了一起) return a[0] < b[0]; }); int k = -1; vector<int> cpy(envelopes.size()); // 因为宽度已经按照从小大到排好了,后面的信封的宽度一定大于等于前面的信封,所以我们只用考虑高度的情况来做二分 for (int i = 0; i < envelopes.size(); i++) { if (i == 0) cpy[++k] = envelopes[i][1]; else { if (envelopes[i][1] > cpy[k]) { cpy[++k] = envelopes[i][1]; } else { int le = 0, ri = k; while (le != ri) { int mid = (ri - le) / 2 + le; if (envelopes[i][1] > cpy[mid]) le = mid + 1; else ri = mid; } cpy[le] = envelopes[i][1]; } } } return k + 1; } };
[ "yongjie.qiu@qq.com" ]
yongjie.qiu@qq.com
0ccd18e9b840f733d23cbdf894ee218a84289bbe
7c5343b302eda9b52e1c34723fc9578c893d8fcf
/Userland/DevTools/HackStudio/LanguageServers/Cpp/CppComprehensionEngine.cpp
acfab18d8e447e8458106b5f5159ef52612a02d5
[ "BSD-2-Clause" ]
permissive
1player/serenity
7ac6e70cf6616f27b7d2c658f4494d8113210852
b639bf64f283d4ffc8d6d8ccc44c599acd08683e
refs/heads/master
2023-05-13T06:35:09.138089
2021-06-09T22:28:59
2021-06-09T22:46:37
375,615,810
1
0
BSD-2-Clause
2021-06-10T07:52:11
2021-06-10T07:52:11
null
UTF-8
C++
false
false
26,563
cpp
/* * Copyright (c) 2021, Itamar S. <itamar8910@gmail.com> * * SPDX-License-Identifier: BSD-2-Clause */ #include "CppComprehensionEngine.h" #include <AK/Assertions.h> #include <AK/HashTable.h> #include <AK/OwnPtr.h> #include <LibCore/DirIterator.h> #include <LibCore/File.h> #include <LibCpp/AST.h> #include <LibCpp/Lexer.h> #include <LibCpp/Parser.h> #include <LibCpp/Preprocessor.h> #include <LibRegex/Regex.h> #include <Userland/DevTools/HackStudio/LanguageServers/ClientConnection.h> namespace LanguageServers::Cpp { CppComprehensionEngine::CppComprehensionEngine(const FileDB& filedb) : CodeComprehensionEngine(filedb, true) { } const CppComprehensionEngine::DocumentData* CppComprehensionEngine::get_or_create_document_data(const String& file) { auto absolute_path = filedb().to_absolute_path(file); if (!m_documents.contains(absolute_path)) { set_document_data(absolute_path, create_document_data_for(absolute_path)); } return get_document_data(absolute_path); } const CppComprehensionEngine::DocumentData* CppComprehensionEngine::get_document_data(const String& file) const { auto absolute_path = filedb().to_absolute_path(file); auto document_data = m_documents.get(absolute_path); if (!document_data.has_value()) return nullptr; return document_data.value(); } OwnPtr<CppComprehensionEngine::DocumentData> CppComprehensionEngine::create_document_data_for(const String& file) { auto document = filedb().get_or_create_from_filesystem(file); if (!document) return {}; return create_document_data(document->text(), file); } void CppComprehensionEngine::set_document_data(const String& file, OwnPtr<DocumentData>&& data) { m_documents.set(filedb().to_absolute_path(file), move(data)); } Vector<GUI::AutocompleteProvider::Entry> CppComprehensionEngine::get_suggestions(const String& file, const GUI::TextPosition& autocomplete_position) { Cpp::Position position { autocomplete_position.line(), autocomplete_position.column() > 0 ? autocomplete_position.column() - 1 : 0 }; dbgln_if(CPP_LANGUAGE_SERVER_DEBUG, "CppComprehensionEngine position {}:{}", position.line, position.column); const auto* document_ptr = get_or_create_document_data(file); if (!document_ptr) return {}; const auto& document = *document_ptr; auto containing_token = document.parser().token_at(position); if (containing_token.has_value() && containing_token->type() == Token::Type::IncludePath) { auto results = try_autocomplete_include(document, containing_token.value()); if (results.has_value()) return results.value(); } auto node = document.parser().node_at(position); if (!node) { dbgln_if(CPP_LANGUAGE_SERVER_DEBUG, "no node at position {}:{}", position.line, position.column); return {}; } if (node->parent() && node->parent()->parent()) dbgln_if(CPP_LANGUAGE_SERVER_DEBUG, "node: {}, parent: {}, grandparent: {}", node->class_name(), node->parent()->class_name(), node->parent()->parent()->class_name()); if (!node->parent()) return {}; auto results = try_autocomplete_property(document, *node, containing_token); if (results.has_value()) return results.value(); results = try_autocomplete_name(document, *node, containing_token); if (results.has_value()) return results.value(); return {}; } Optional<Vector<GUI::AutocompleteProvider::Entry>> CppComprehensionEngine::try_autocomplete_name(const DocumentData& document, const ASTNode& node, Optional<Token> containing_token) const { auto partial_text = String::empty(); if (containing_token.has_value() && containing_token.value().type() != Token::Type::ColonColon) { partial_text = containing_token.value().text(); } return autocomplete_name(document, node, partial_text); } Optional<Vector<GUI::AutocompleteProvider::Entry>> CppComprehensionEngine::try_autocomplete_property(const DocumentData& document, const ASTNode& node, Optional<Token> containing_token) const { if (!containing_token.has_value()) return {}; if (!node.parent()->is_member_expression()) return {}; const auto& parent = static_cast<const MemberExpression&>(*node.parent()); auto partial_text = String::empty(); if (containing_token.value().type() != Token::Type::Dot) { if (&node != parent.m_property) return {}; partial_text = containing_token.value().text(); } return autocomplete_property(document, parent, partial_text); } Vector<GUI::AutocompleteProvider::Entry> CppComprehensionEngine::autocomplete_name(const DocumentData& document, const ASTNode& node, const String& partial_text) const { auto reference_scope = scope_of_reference_to_symbol(node); auto current_scope = scope_of_node(node); auto symbol_matches = [&](const Symbol& symbol) { if (!is_symbol_available(symbol, current_scope, reference_scope)) { return false; } if (!symbol.name.name.starts_with(partial_text)) return false; if (symbol.is_local) { // If this symbol was declared bellow us in a function, it's not available to us. bool is_unavailable = symbol.is_local && symbol.declaration->start().line > node.start().line; if (is_unavailable) return false; } return true; }; Vector<Symbol> matches; for_each_available_symbol(document, [&](const Symbol& symbol) { if (symbol_matches(symbol)) { matches.append(symbol); } return IterationDecision::Continue; }); Vector<GUI::AutocompleteProvider::Entry> suggestions; for (auto& symbol : matches) { suggestions.append({ symbol.name.name, partial_text.length(), GUI::AutocompleteProvider::CompletionKind::Identifier }); } if (reference_scope.is_empty()) { for (auto& preprocessor_name : document.parser().preprocessor_definitions().keys()) { if (preprocessor_name.starts_with(partial_text)) { suggestions.append({ preprocessor_name.to_string(), partial_text.length(), GUI::AutocompleteProvider::CompletionKind::PreprocessorDefinition }); } } } return suggestions; } Vector<StringView> CppComprehensionEngine::scope_of_reference_to_symbol(const ASTNode& node) const { const Name* name = nullptr; if (node.is_name()) { name = reinterpret_cast<const Name*>(&node); } else if (node.is_identifier()) { auto* parent = node.parent(); if (!(parent && parent->is_name())) return {}; name = reinterpret_cast<const Name*>(parent); } else { return {}; } VERIFY(name->is_name()); Vector<StringView> scope_parts; for (auto& scope_part : name->m_scope) { scope_parts.append(scope_part.m_name); } return scope_parts; } Vector<GUI::AutocompleteProvider::Entry> CppComprehensionEngine::autocomplete_property(const DocumentData& document, const MemberExpression& parent, const String partial_text) const { auto type = type_of(document, *parent.m_object); if (type.is_null()) { dbgln_if(CPP_LANGUAGE_SERVER_DEBUG, "Could not infer type of object"); return {}; } Vector<GUI::AutocompleteProvider::Entry> suggestions; for (auto& prop : properties_of_type(document, type)) { if (prop.name.starts_with(partial_text)) { suggestions.append({ prop.name, partial_text.length(), GUI::AutocompleteProvider::CompletionKind::Identifier }); } } return suggestions; } bool CppComprehensionEngine::is_property(const ASTNode& node) const { if (!node.parent()->is_member_expression()) return false; auto& parent = (MemberExpression&)(*node.parent()); return parent.m_property.ptr() == &node; } String CppComprehensionEngine::type_of_property(const DocumentData& document, const Identifier& identifier) const { auto& parent = (const MemberExpression&)(*identifier.parent()); auto properties = properties_of_type(document, type_of(document, *parent.m_object)); for (auto& prop : properties) { if (prop.name == identifier.m_name) return prop.type->m_name->full_name(); } return {}; } String CppComprehensionEngine::type_of_variable(const Identifier& identifier) const { const ASTNode* current = &identifier; while (current) { for (auto& decl : current->declarations()) { if (decl.is_variable_or_parameter_declaration()) { auto& var_or_param = (VariableOrParameterDeclaration&)decl; if (var_or_param.m_name == identifier.m_name) { return var_or_param.m_type->m_name->full_name(); } } } current = current->parent(); } return {}; } String CppComprehensionEngine::type_of(const DocumentData& document, const Expression& expression) const { if (expression.is_member_expression()) { auto& member_expression = (const MemberExpression&)expression; if (member_expression.m_property->is_identifier()) return type_of_property(document, static_cast<const Identifier&>(*member_expression.m_property)); return {}; } const Identifier* identifier { nullptr }; if (expression.is_name()) { identifier = static_cast<const Name&>(expression).m_name.ptr(); } else if (expression.is_identifier()) { identifier = &static_cast<const Identifier&>(expression); } else { dbgln("expected identifier or name, got: {}", expression.class_name()); VERIFY_NOT_REACHED(); // TODO } VERIFY(identifier); if (is_property(*identifier)) return type_of_property(document, *identifier); return type_of_variable(*identifier); } Vector<CppComprehensionEngine::PropertyInfo> CppComprehensionEngine::properties_of_type(const DocumentData& document, const String& type) const { auto decl = find_declaration_of(document, SymbolName::create(type, {})); if (!decl) { dbgln("Couldn't find declaration of type: {}", type); return {}; } if (!decl->is_struct_or_class()) { dbgln("Expected declaration of type: {} to be struct or class", type); return {}; } auto& struct_or_class = (StructOrClassDeclaration&)*decl; VERIFY(struct_or_class.m_name == type); // FIXME: this won't work with scoped types Vector<PropertyInfo> properties; for (auto& member : struct_or_class.m_members) { if (!member.is_variable_declaration()) continue; properties.append({ member.m_name, ((VariableDeclaration&)member).m_type }); } return properties; } CppComprehensionEngine::Symbol CppComprehensionEngine::Symbol::create(StringView name, const Vector<StringView>& scope, NonnullRefPtr<Declaration> declaration, IsLocal is_local) { return { { name, scope }, move(declaration), is_local == IsLocal::Yes }; } Vector<CppComprehensionEngine::Symbol> CppComprehensionEngine::get_child_symbols(const ASTNode& node) const { return get_child_symbols(node, {}, Symbol::IsLocal::No); } Vector<CppComprehensionEngine::Symbol> CppComprehensionEngine::get_child_symbols(const ASTNode& node, const Vector<StringView>& scope, Symbol::IsLocal is_local) const { Vector<Symbol> symbols; for (auto& decl : node.declarations()) { symbols.append(Symbol::create(decl.name(), scope, decl, is_local)); bool should_recurse = decl.is_namespace() || decl.is_struct_or_class() || decl.is_function(); bool are_child_symbols_local = decl.is_function(); if (!should_recurse) continue; auto new_scope = scope; new_scope.append(decl.name()); symbols.append(get_child_symbols(decl, new_scope, are_child_symbols_local ? Symbol::IsLocal::Yes : is_local)); } return symbols; } String CppComprehensionEngine::document_path_from_include_path(const StringView& include_path) const { static Regex<PosixExtended> library_include("<(.+)>"); static Regex<PosixExtended> user_defined_include("\"(.+)\""); auto document_path_for_library_include = [&](const StringView& include_path) -> String { RegexResult result; if (!library_include.search(include_path, result)) return {}; auto path = result.capture_group_matches.at(0).at(0).view.u8view(); return String::formatted("/usr/include/{}", path); }; auto document_path_for_user_defined_include = [&](const StringView& include_path) -> String { RegexResult result; if (!user_defined_include.search(include_path, result)) return {}; return result.capture_group_matches.at(0).at(0).view.u8view(); }; auto result = document_path_for_library_include(include_path); if (result.is_null()) result = document_path_for_user_defined_include(include_path); return result; } void CppComprehensionEngine::on_edit(const String& file) { set_document_data(file, create_document_data_for(file)); } void CppComprehensionEngine::file_opened([[maybe_unused]] const String& file) { get_or_create_document_data(file); } Optional<GUI::AutocompleteProvider::ProjectLocation> CppComprehensionEngine::find_declaration_of(const String& filename, const GUI::TextPosition& identifier_position) { const auto* document_ptr = get_or_create_document_data(filename); if (!document_ptr) return {}; const auto& document = *document_ptr; auto node = document.parser().node_at(Cpp::Position { identifier_position.line(), identifier_position.column() }); if (!node) { dbgln_if(CPP_LANGUAGE_SERVER_DEBUG, "no node at position {}:{}", identifier_position.line(), identifier_position.column()); return {}; } auto decl = find_declaration_of(document, *node); if (decl) return GUI::AutocompleteProvider::ProjectLocation { decl->filename(), decl->start().line, decl->start().column }; return find_preprocessor_definition(document, identifier_position); } Optional<GUI::AutocompleteProvider::ProjectLocation> CppComprehensionEngine::find_preprocessor_definition(const DocumentData& document, const GUI::TextPosition& text_position) { Position cpp_position { text_position.line(), text_position.column() }; // Search for a replaced preprocessor token that intersects with text_position for (auto& replaced_token : document.parser().replaced_preprocessor_tokens()) { if (replaced_token.token.start() > cpp_position) continue; if (replaced_token.token.end() < cpp_position) continue; return GUI::AutocompleteProvider::ProjectLocation { replaced_token.preprocessor_value.filename, replaced_token.preprocessor_value.line, replaced_token.preprocessor_value.column }; } return {}; } struct TargetDeclaration { enum Type { Variable, Type, Function, Property } type; String name; }; static Optional<TargetDeclaration> get_target_declaration(const ASTNode& node) { if (!node.is_identifier()) { dbgln_if(CPP_LANGUAGE_SERVER_DEBUG, "node is not an identifier"); return {}; } String name = static_cast<const Identifier&>(node).m_name; if ((node.parent() && node.parent()->is_function_call()) || (node.parent()->is_name() && node.parent()->parent() && node.parent()->parent()->is_function_call())) { return TargetDeclaration { TargetDeclaration::Type::Function, name }; } if ((node.parent() && node.parent()->is_type()) || (node.parent()->is_name() && node.parent()->parent() && node.parent()->parent()->is_type())) return TargetDeclaration { TargetDeclaration::Type::Type, name }; if ((node.parent() && node.parent()->is_member_expression())) return TargetDeclaration { TargetDeclaration::Type::Property, name }; return TargetDeclaration { TargetDeclaration::Type::Variable, name }; } RefPtr<Declaration> CppComprehensionEngine::find_declaration_of(const DocumentData& document_data, const ASTNode& node) const { dbgln_if(CPP_LANGUAGE_SERVER_DEBUG, "find_declaration_of: {} ({})", document_data.parser().text_of_node(node), node.class_name()); if (!node.is_identifier()) { dbgln("node is not an identifier, can't find declaration"); } auto target_decl = get_target_declaration(node); if (!target_decl.has_value()) return {}; auto reference_scope = scope_of_reference_to_symbol(node); auto current_scope = scope_of_node(node); auto symbol_matches = [&](const Symbol& symbol) { bool match_function = target_decl.value().type == TargetDeclaration::Function && symbol.declaration->is_function(); bool match_variable = target_decl.value().type == TargetDeclaration::Variable && symbol.declaration->is_variable_declaration(); bool match_type = target_decl.value().type == TargetDeclaration::Type && symbol.declaration->is_struct_or_class(); bool match_property = target_decl.value().type == TargetDeclaration::Property && symbol.declaration->parent()->is_declaration() && ((Declaration*)symbol.declaration->parent())->is_struct_or_class(); bool match_parameter = target_decl.value().type == TargetDeclaration::Variable && symbol.declaration->is_parameter(); if (match_property) { // FIXME: This is not really correct, we also need to check that the type of the struct/class matches (not just the property name) if (symbol.name.name == target_decl.value().name) { return true; } } if (!is_symbol_available(symbol, current_scope, reference_scope)) { return false; } if (match_function || match_type) { if (symbol.name.name == target_decl->name) return true; } if (match_variable || match_parameter) { // If this symbol was declared bellow us in a function, it's not available to us. bool is_unavailable = symbol.is_local && symbol.declaration->start().line > node.start().line; if (!is_unavailable && (symbol.name.name == target_decl->name)) { return true; } } return false; }; Optional<Symbol> match; for_each_available_symbol(document_data, [&](const Symbol& symbol) { if (symbol_matches(symbol)) { match = symbol; return IterationDecision::Break; } return IterationDecision::Continue; }); if (!match.has_value()) return {}; return match->declaration; } void CppComprehensionEngine::update_declared_symbols(DocumentData& document) { for (auto& symbol : get_child_symbols(*document.parser().root_node())) { document.m_symbols.set(symbol.name, move(symbol)); } Vector<GUI::AutocompleteProvider::Declaration> declarations; for (auto& symbol_entry : document.m_symbols) { auto& symbol = symbol_entry.value; declarations.append({ symbol.name.name, { document.filename(), symbol.declaration->start().line, symbol.declaration->start().column }, type_of_declaration(symbol.declaration), symbol.name.scope_as_string() }); } for (auto& definition : document.preprocessor().definitions()) { declarations.append({ definition.key, { document.filename(), definition.value.line, definition.value.column }, GUI::AutocompleteProvider::DeclarationType::PreprocessorDefinition, {} }); } set_declarations_of_document(document.filename(), move(declarations)); } GUI::AutocompleteProvider::DeclarationType CppComprehensionEngine::type_of_declaration(const Declaration& decl) { if (decl.is_struct()) return GUI::AutocompleteProvider::DeclarationType::Struct; if (decl.is_class()) return GUI::AutocompleteProvider::DeclarationType::Class; if (decl.is_function()) return GUI::AutocompleteProvider::DeclarationType::Function; if (decl.is_variable_declaration()) return GUI::AutocompleteProvider::DeclarationType::Variable; if (decl.is_namespace()) return GUI::AutocompleteProvider::DeclarationType::Namespace; if (decl.is_member()) return GUI::AutocompleteProvider::DeclarationType::Member; return GUI::AutocompleteProvider::DeclarationType::Variable; } OwnPtr<CppComprehensionEngine::DocumentData> CppComprehensionEngine::create_document_data(String&& text, const String& filename) { auto document_data = make<DocumentData>(); document_data->m_filename = filename; document_data->m_text = move(text); document_data->m_preprocessor = make<Preprocessor>(document_data->m_filename, document_data->text()); document_data->preprocessor().set_ignore_unsupported_keywords(true); document_data->preprocessor().set_keep_include_statements(true); document_data->preprocessor().process(); Preprocessor::Definitions preprocessor_definitions; for (auto item : document_data->preprocessor().definitions()) preprocessor_definitions.set(move(item.key), move(item.value)); for (auto include_path : document_data->preprocessor().included_paths()) { auto include_fullpath = document_path_from_include_path(include_path); auto included_document = get_or_create_document_data(include_fullpath); if (!included_document) continue; document_data->m_available_headers.set(include_fullpath); for (auto& header : included_document->m_available_headers) document_data->m_available_headers.set(header); for (auto item : included_document->parser().preprocessor_definitions()) preprocessor_definitions.set(move(item.key), move(item.value)); } document_data->m_parser = make<Parser>(document_data->preprocessor().processed_text(), filename, move(preprocessor_definitions)); auto root = document_data->parser().parse(); if constexpr (CPP_LANGUAGE_SERVER_DEBUG) root->dump(); update_declared_symbols(*document_data); return document_data; } Vector<StringView> CppComprehensionEngine::scope_of_node(const ASTNode& node) const { auto parent = node.parent(); if (!parent) return {}; auto parent_scope = scope_of_node(*parent); if (!parent->is_declaration()) return parent_scope; auto& parent_decl = static_cast<Declaration&>(*parent); StringView containing_scope; if (parent_decl.is_namespace()) containing_scope = static_cast<NamespaceDeclaration&>(parent_decl).m_name; if (parent_decl.is_struct_or_class()) containing_scope = static_cast<StructOrClassDeclaration&>(parent_decl).name(); if (parent_decl.is_function()) containing_scope = static_cast<FunctionDeclaration&>(parent_decl).name(); parent_scope.append(containing_scope); return parent_scope; } Optional<Vector<GUI::AutocompleteProvider::Entry>> CppComprehensionEngine::try_autocomplete_include(const DocumentData&, Token include_path_token) { VERIFY(include_path_token.type() == Token::Type::IncludePath); auto partial_include = include_path_token.text().trim_whitespace(); String include_root; auto include_type = GUI::AutocompleteProvider::CompletionKind::ProjectInclude; if (partial_include.starts_with("<")) { include_root = "/usr/include/"; include_type = GUI::AutocompleteProvider::CompletionKind::SystemInclude; } else if (partial_include.starts_with("\"")) { include_root = filedb().project_root(); } else return {}; auto last_slash = partial_include.find_last_of("/"); auto include_dir = String::empty(); auto partial_basename = partial_include.substring_view((last_slash.has_value() ? last_slash.value() : 0) + 1); if (last_slash.has_value()) { include_dir = partial_include.substring_view(1, last_slash.value()); } auto full_dir = String::formatted("{}{}", include_root, include_dir); dbgln_if(CPP_LANGUAGE_SERVER_DEBUG, "searching path: {}, partial_basename: {}", full_dir, partial_basename); Core::DirIterator it(full_dir, Core::DirIterator::Flags::SkipDots); Vector<GUI::AutocompleteProvider::Entry> options; while (it.has_next()) { auto path = it.next_path(); if (!(path.ends_with(".h") || Core::File::is_directory(LexicalPath::join(full_dir, path).string()))) continue; if (path.starts_with(partial_basename)) { options.append({ path, partial_basename.length(), include_type, GUI::AutocompleteProvider::Language::Cpp }); } } return options; } RefPtr<Declaration> CppComprehensionEngine::find_declaration_of(const CppComprehensionEngine::DocumentData& document, const CppComprehensionEngine::SymbolName& target_symbol_name) const { RefPtr<Declaration> target_declaration; for_each_available_symbol(document, [&](const Symbol& symbol) { if (symbol.name == target_symbol_name) { target_declaration = symbol.declaration; return IterationDecision::Break; } return IterationDecision::Continue; }); return target_declaration; } String CppComprehensionEngine::SymbolName::scope_as_string() const { if (scope.is_empty()) return String::empty(); StringBuilder builder; for (size_t i = 0; i < scope.size() - 1; ++i) { builder.appendff("{}::", scope[i]); } builder.append(scope.last()); return builder.to_string(); } CppComprehensionEngine::SymbolName CppComprehensionEngine::SymbolName::create(StringView name, Vector<StringView>&& scope) { return { name, move(scope) }; } String CppComprehensionEngine::SymbolName::to_string() const { if (scope.is_empty()) return name; return String::formatted("{}::{}", scope_as_string(), name); } bool CppComprehensionEngine::is_symbol_available(const Symbol& symbol, const Vector<StringView>& current_scope, const Vector<StringView>& reference_scope) { if (!reference_scope.is_empty()) { return reference_scope == symbol.name.scope; } // FIXME: Consider "using namespace ..." // Check if current_scope starts with symbol's scope if (symbol.name.scope.size() > current_scope.size()) return false; for (size_t i = 0; i < symbol.name.scope.size(); ++i) { if (current_scope[i] != symbol.name.scope[i]) return false; } return true; } }
[ "kling@serenityos.org" ]
kling@serenityos.org
5c1dd35e3bfda706384f93b103612e726a81b8c0
3ff1fe3888e34cd3576d91319bf0f08ca955940f
/redis/src/v20180412/model/DescribeSSLStatusRequest.cpp
d924b045df8cca49880bc6a7eca3304c3feb2ec9
[ "Apache-2.0" ]
permissive
TencentCloud/tencentcloud-sdk-cpp
9f5df8220eaaf72f7eaee07b2ede94f89313651f
42a76b812b81d1b52ec6a217fafc8faa135e06ca
refs/heads/master
2023-08-30T03:22:45.269556
2023-08-30T00:45:39
2023-08-30T00:45:39
188,991,963
55
37
Apache-2.0
2023-08-17T03:13:20
2019-05-28T08:56:08
C++
UTF-8
C++
false
false
2,004
cpp
/* * Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <tencentcloud/redis/v20180412/model/DescribeSSLStatusRequest.h> #include <tencentcloud/core/utils/rapidjson/document.h> #include <tencentcloud/core/utils/rapidjson/writer.h> #include <tencentcloud/core/utils/rapidjson/stringbuffer.h> using namespace TencentCloud::Redis::V20180412::Model; using namespace std; DescribeSSLStatusRequest::DescribeSSLStatusRequest() : m_instanceIdHasBeenSet(false) { } string DescribeSSLStatusRequest::ToJsonString() const { rapidjson::Document d; d.SetObject(); rapidjson::Document::AllocatorType& allocator = d.GetAllocator(); if (m_instanceIdHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "InstanceId"; iKey.SetString(key.c_str(), allocator); d.AddMember(iKey, rapidjson::Value(m_instanceId.c_str(), allocator).Move(), allocator); } rapidjson::StringBuffer buffer; rapidjson::Writer<rapidjson::StringBuffer> writer(buffer); d.Accept(writer); return buffer.GetString(); } string DescribeSSLStatusRequest::GetInstanceId() const { return m_instanceId; } void DescribeSSLStatusRequest::SetInstanceId(const string& _instanceId) { m_instanceId = _instanceId; m_instanceIdHasBeenSet = true; } bool DescribeSSLStatusRequest::InstanceIdHasBeenSet() const { return m_instanceIdHasBeenSet; }
[ "tencentcloudapi@tencent.com" ]
tencentcloudapi@tencent.com