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
905 values
visit_date
timestamp[us]date
2015-08-09 11:21:18
2023-09-06 10:45:07
revision_date
timestamp[us]date
1997-09-14 05:04:47
2023-09-17 19:19:19
committer_date
timestamp[us]date
1997-09-14 05:04:47
2023-09-06 06:22:19
github_id
int64
3.89k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
22 values
gha_event_created_at
timestamp[us]date
2012-06-07 00:51:45
2023-09-14 21:58:39
gha_created_at
timestamp[us]date
2008-03-27 23:40:48
2023-08-21 23:17:38
gha_language
stringclasses
141 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
115 values
content
stringlengths
3
10.4M
authors
listlengths
1
1
author_id
stringlengths
0
158
827040609f79969bbb0e634e890d56ab12d3d28c
a77cae61867e4fb947f88acb4e11603d9cd0f6d1
/LeetCode/Leetcode2115_做菜.cpp
80de632cbf7fccb2bd1f65c099857cc480cfe7af
[]
no_license
CHOcho-quan/OJ-Journey
cbad32f7ab52e59218ce4741097d6fa0ac9b462f
a9618891b5e14790ba65914783e26f8a7aa03497
refs/heads/master
2023-06-09T15:35:27.418405
2023-06-01T00:57:11
2023-06-01T00:57:11
166,665,271
1
0
null
null
null
null
UTF-8
C++
false
false
1,559
cpp
class Solution { public: vector<string> findAllRecipes(vector<string>& recipes, vector<vector<string>>& ingredients, vector<string>& supplies) { vector<string> res; auto supply_set = set<string>(supplies.begin(), supplies.end()); auto recipe_set = set<string>(recipes.begin(), recipes.end()); unordered_map<string, set<string>> needed_recipes; unordered_map<string, int> indegree; queue<string> q; for (int i = 0; i < ingredients.size(); ++i) { bool flag = true; for (int j = 0; j < ingredients[i].size(); ++j) { if (supply_set.find(ingredients[i][j]) == supply_set.end()) { flag = false; needed_recipes[recipes[i]].insert(ingredients[i][j]); ++indegree[recipes[i]]; } } if (flag) { supply_set.insert(recipes[i]); indegree[recipes[i]] = 0; q.push(recipes[i]); res.push_back(recipes[i]); } } while (!q.empty()) { auto cur = q.front(); q.pop(); for (auto& iter : needed_recipes) { // founded if (iter.second.find(cur) != iter.second.end()) { if (!(--indegree[iter.first])) { q.push(iter.first); res.push_back(iter.first); } } } } return res; } };
[ "574166505@qq.com" ]
574166505@qq.com
2f30e7c9f661717ce37a83cccae7d2e5cd1269ac
dc488c23c45561e359e6397f3debd94990f49f5f
/Baby shark(2).cpp
05b9c67380c2eb6d74bfe3c0eef4bcdeb44bc3fb
[]
no_license
hs-krispy/BOJ
418fb91baa7598c8ca710d3f9e08adf271f512c0
60921938c551f7f5e98b0ffc884feeaf6394c36f
refs/heads/master
2021-07-18T06:11:07.704323
2021-02-26T16:19:39
2021-02-26T16:19:39
233,381,056
0
0
null
null
null
null
UTF-8
C++
false
false
1,437
cpp
// // Created by 0864h on 2020-09-01. // #include<iostream> #include<queue> #include<vector> #include<climits> using namespace std; int dx[] = {-1, 1, 0, 0, -1, -1, 1, 1}; int dy[] = {0, 0, -1, 1, -1, 1, 1, -1}; int N, M, space[51][51], ans[51][51], Max = 0; vector<pair<int, int>> v; int main() { cin >> N >> M; for(int i = 1; i <= N; i++) { for(int j = 1; j <= M; j++) { cin >> space[i][j]; ans[i][j] = INT_MAX; if(space[i][j] == 1) { v.emplace_back(i, j); ans[i][j] = 0; } } } queue<pair<int, int>> q; for(int i = 0; i < v.size(); i++) { q.push({v[i].first, v[i].second}); while(!q.empty()) { int x = q.front().first; int y = q.front().second; q.pop(); for(int i = 0; i < 8; i++) { int nx = x + dx[i]; int ny = y + dy[i]; if(nx >= 1 && ny >= 1 && nx <= N && ny <= M && space[nx][ny] == 0 && ans[nx][ny] > ans[x][y] + 1) { ans[nx][ny] = ans[x][y] + 1; q.push({nx, ny}); } } } } for(int i = 1; i <= N; i++) { for(int j = 1; j <= M; j++) { if(Max < ans[i][j]) Max = ans[i][j]; } } cout << Max; }
[ "0864hs@naver.com" ]
0864hs@naver.com
89aa50c7a036fe32f8ac3f102fc7b250455635af
b4b4e324cbc6159a02597aa66f52cb8e1bc43bc1
/C++ code/Taiwan Olympiad in Informatics/2016模擬測驗一/Farm.cpp
2ebb0f0362f4c0032ac798410a7f62173c1ecd90
[]
no_license
fsps60312/old-C-code
5d0ffa0796dde5ab04c839e1dc786267b67de902
b4be562c873afe9eacb45ab14f61c15b7115fc07
refs/heads/master
2022-11-30T10:55:25.587197
2017-06-03T16:23:03
2017-06-03T16:23:03
null
0
0
null
null
null
null
UTF-8
C++
false
false
575
cpp
#include<cstdio> #include<cassert> #include<vector> #include<algorithm> using namespace std; typedef long long LL; struct Farm { int x1,y1,x2,y2; }F[100000]; int W,H,N; LL ANS; int main() { // freopen("inB.txt","r",stdin); while(scanf("%d%d",&W,&H)==2) { scanf("%d",&N); for(int i=0;i<N;i++) { scanf("%d%d%d%d",&F[i].x1,&F[i].y1,&F[i].x2,&F[i].y2); F[i].x1++,F[i].y1++; } ANS=0; for(int i=0;i<N;i++)for(int j=i+1;j<N;j++) { if(F[i].x2>=F[j].x1&&F[i].x1<=F[j].x2&&F[i].y2>=F[j].y1&&F[i].y1<=F[j].y2)ANS++; } printf("%lld\n",ANS); } return 0; }
[ "fsps60312@yahoo.com.tw" ]
fsps60312@yahoo.com.tw
293192af5aa2f46b4624409025d98917cc35aecb
4910c0f3d03935fc8ee03f1e9dc20dfdb2c7c04b
/Recien traducido/Geometria/PythagoreanTriplets.cpp
03af9f1e0150120bf2404975d2930fcbd14e445f
[]
no_license
roca12/gpccodes
ab15eeedc0cadc0735651262887b44f1c2e65b93
aa034a3014c6fb879ec5392c51f9714bdc5b50c2
refs/heads/master
2023-02-01T13:49:27.563662
2023-01-19T22:50:58
2023-01-19T22:50:58
270,723,328
3
5
null
null
null
null
UTF-8
C++
false
false
465
cpp
#include <bits/stdc++.h> void pythagoreanTriplets(int limit) { int a, b, c = 0; int m = 2; while (c < limit) { for (int n = 1; n < m; ++n) { a = m * m - n * n; b = 2 * m * n; c = m * m + n * n; if (c > limit) break; printf("%d %d %d\n", a, b, c); } m++; } } int main() { int limit = 20; pythagoreanTriplets(limit); return 0; }
[ "44822667+roca12@users.noreply.github.com" ]
44822667+roca12@users.noreply.github.com
8180ae57112c501728597f95571df8a0f845a266
5181e2dd87941613b74be655fd621c13c1032d31
/1. Nhap mon lap trinh_chuong03_mang mot chieu/bai076.cpp
df11573c1af103ac3304e3aac59afbe13e2aa12c
[]
no_license
my-hoang-huu/My-hh
36c57bcc0ff2a6f09d1404af502a63c94dfd7b92
176a0ec629438260ef1a44db82fe1a99a59c809f
refs/heads/main
2023-06-05T03:03:18.421699
2021-05-07T00:36:26
2021-05-07T00:36:26
342,750,649
0
0
null
2021-05-07T00:36:27
2021-02-27T02:18:47
C++
UTF-8
C++
false
false
1,014
cpp
#include<iostream> #include<iomanip> using namespace std; void Nhap(float[], int&); void Xuat(float[], int); float KhoangCach(float, float); void Gan(float[], int, float); int main() { float a[100]; int n; Nhap(a, n); Xuat(a, n); int x; cout << "\nNhap x: "; cin >> x; Gan(a, n, x); return 1; } void Nhap(float a[], int& n) { cout << "Nhap so phan tu mang: "; cin >> n; srand(time(NULL)); for (int i = 0; i < n; i++) a[i] = rand() * 1.0 / RAND_MAX * 200.0 - 100.0; } void Xuat(float a[], int n) { for (int i = 0; i < n; i++) { cout << a[i] << setw(10); } cout << endl; } float KhoangCach(float a, float x) { float kc = abs(a - x); return kc; } void Gan(float a[], int n, float x) { float lc = KhoangCach(a[0], x); for (int i = 0; i < n; i++) { if (KhoangCach(a[i], x) < lc) { lc = KhoangCach(a[i], x); } } for (int i = 0; i < n; i++) { if (lc == KhoangCach(a[i], x)) { cout << "Gia tri co Khoang cach gan " << x << " nhat: " << a[i] << setw(10); break; } } }
[ "hhmy1995@gmail.com" ]
hhmy1995@gmail.com
423f49dfc798a02e367543f2c1a60a675e5085a4
1fa788bb9bcae02b4e78d15cde2139122a4ed87d
/catkin_ws/devel/include/ros_pololu_servo/MotorCommand.h
4747df8140fe1c9f514607b74072ffd096bc2e92
[]
no_license
Zaaler/csci4302_FinalProject
b9af3f17d8cec1327c52a10da5b7ad6f3d4bf730
bb38f901a501459ce260b230f4bc63a2dbb027b9
refs/heads/master
2021-05-09T16:16:20.678745
2017-05-10T23:25:00
2017-05-10T23:25:00
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,581
h
// Generated by gencpp from file ros_pololu_servo/MotorCommand.msg // DO NOT EDIT! #ifndef ROS_POLOLU_SERVO_MESSAGE_MOTORCOMMAND_H #define ROS_POLOLU_SERVO_MESSAGE_MOTORCOMMAND_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 ros_pololu_servo { template <class ContainerAllocator> struct MotorCommand_ { typedef MotorCommand_<ContainerAllocator> Type; MotorCommand_() : joint_name() , position(0.0) , speed(0.0) , acceleration(0.0) { } MotorCommand_(const ContainerAllocator& _alloc) : joint_name(_alloc) , position(0.0) , speed(0.0) , acceleration(0.0) { (void)_alloc; } typedef std::basic_string<char, std::char_traits<char>, typename ContainerAllocator::template rebind<char>::other > _joint_name_type; _joint_name_type joint_name; typedef double _position_type; _position_type position; typedef float _speed_type; _speed_type speed; typedef float _acceleration_type; _acceleration_type acceleration; typedef boost::shared_ptr< ::ros_pololu_servo::MotorCommand_<ContainerAllocator> > Ptr; typedef boost::shared_ptr< ::ros_pololu_servo::MotorCommand_<ContainerAllocator> const> ConstPtr; }; // struct MotorCommand_ typedef ::ros_pololu_servo::MotorCommand_<std::allocator<void> > MotorCommand; typedef boost::shared_ptr< ::ros_pololu_servo::MotorCommand > MotorCommandPtr; typedef boost::shared_ptr< ::ros_pololu_servo::MotorCommand const> MotorCommandConstPtr; // constants requiring out of line definition template<typename ContainerAllocator> std::ostream& operator<<(std::ostream& s, const ::ros_pololu_servo::MotorCommand_<ContainerAllocator> & v) { ros::message_operations::Printer< ::ros_pololu_servo::MotorCommand_<ContainerAllocator> >::stream(s, "", v); return s; } } // namespace ros_pololu_servo namespace ros { namespace message_traits { // BOOLTRAITS {'IsFixedSize': False, 'IsMessage': True, 'HasHeader': False} // {'std_msgs': ['/opt/ros/kinetic/share/std_msgs/cmake/../msg'], 'actionlib_msgs': ['/opt/ros/kinetic/share/actionlib_msgs/cmake/../msg'], 'trajectory_msgs': ['/opt/ros/kinetic/share/trajectory_msgs/cmake/../msg'], 'ros_pololu_servo': ['/home/odroid/Documents/csci4302_FinalProject/catkin_ws/src/ros_pololu_servo/msg', '/home/odroid/Documents/csci4302_FinalProject/catkin_ws/devel/share/ros_pololu_servo/msg'], 'geometry_msgs': ['/opt/ros/kinetic/share/geometry_msgs/cmake/../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< ::ros_pololu_servo::MotorCommand_<ContainerAllocator> > : FalseType { }; template <class ContainerAllocator> struct IsFixedSize< ::ros_pololu_servo::MotorCommand_<ContainerAllocator> const> : FalseType { }; template <class ContainerAllocator> struct IsMessage< ::ros_pololu_servo::MotorCommand_<ContainerAllocator> > : TrueType { }; template <class ContainerAllocator> struct IsMessage< ::ros_pololu_servo::MotorCommand_<ContainerAllocator> const> : TrueType { }; template <class ContainerAllocator> struct HasHeader< ::ros_pololu_servo::MotorCommand_<ContainerAllocator> > : FalseType { }; template <class ContainerAllocator> struct HasHeader< ::ros_pololu_servo::MotorCommand_<ContainerAllocator> const> : FalseType { }; template<class ContainerAllocator> struct MD5Sum< ::ros_pololu_servo::MotorCommand_<ContainerAllocator> > { static const char* value() { return "c357daac337dac3f7e4bb73a055e6e8c"; } static const char* value(const ::ros_pololu_servo::MotorCommand_<ContainerAllocator>&) { return value(); } static const uint64_t static_value1 = 0xc357daac337dac3fULL; static const uint64_t static_value2 = 0x7e4bb73a055e6e8cULL; }; template<class ContainerAllocator> struct DataType< ::ros_pololu_servo::MotorCommand_<ContainerAllocator> > { static const char* value() { return "ros_pololu_servo/MotorCommand"; } static const char* value(const ::ros_pololu_servo::MotorCommand_<ContainerAllocator>&) { return value(); } }; template<class ContainerAllocator> struct Definition< ::ros_pololu_servo::MotorCommand_<ContainerAllocator> > { static const char* value() { return "string joint_name # Name of the joint (specified in the yaml file), or motor_id for default calibration\n\ float64 position # Position to move to in radians\n\ float32 speed # Speed to move at (0.0 - 1.0)\n\ float32 acceleration # Acceleration to move at (0.0 - 1.0)\n\ "; } static const char* value(const ::ros_pololu_servo::MotorCommand_<ContainerAllocator>&) { return value(); } }; } // namespace message_traits } // namespace ros namespace ros { namespace serialization { template<class ContainerAllocator> struct Serializer< ::ros_pololu_servo::MotorCommand_<ContainerAllocator> > { template<typename Stream, typename T> inline static void allInOne(Stream& stream, T m) { stream.next(m.joint_name); stream.next(m.position); stream.next(m.speed); stream.next(m.acceleration); } ROS_DECLARE_ALLINONE_SERIALIZER }; // struct MotorCommand_ } // namespace serialization } // namespace ros namespace ros { namespace message_operations { template<class ContainerAllocator> struct Printer< ::ros_pololu_servo::MotorCommand_<ContainerAllocator> > { template<typename Stream> static void stream(Stream& s, const std::string& indent, const ::ros_pololu_servo::MotorCommand_<ContainerAllocator>& v) { s << indent << "joint_name: "; Printer<std::basic_string<char, std::char_traits<char>, typename ContainerAllocator::template rebind<char>::other > >::stream(s, indent + " ", v.joint_name); s << indent << "position: "; Printer<double>::stream(s, indent + " ", v.position); s << indent << "speed: "; Printer<float>::stream(s, indent + " ", v.speed); s << indent << "acceleration: "; Printer<float>::stream(s, indent + " ", v.acceleration); } }; } // namespace message_operations } // namespace ros #endif // ROS_POLOLU_SERVO_MESSAGE_MOTORCOMMAND_H
[ "odroid@odroid.com" ]
odroid@odroid.com
43ed56e2e59c942126cf2db595f0cc8633369798
45c59e5f456f11f1714b2ddf976b62dfebecfa7d
/Case10/0/cz_solid_12/epsilon
06d82de63f0c8288f208a157f2e3f9f41bd0b489
[]
no_license
JoelWright24/Masters-Thesis-in-OpenFOAM
9224f71cdb38e96a378996996c5c86235db9ee13
b6c420b5054494a26a7d65a34835b27be9e0da4a
refs/heads/main
2023-02-20T17:18:13.067439
2021-01-22T19:30:36
2021-01-22T19:30:36
332,039,823
0
0
null
null
null
null
UTF-8
C++
false
false
896
/*--------------------------------*- C++ -*----------------------------------*\ ========= | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox \\ / O peration | Website: https://openfoam.org \\ / A nd | Version: 6 \\/ M anipulation | \*---------------------------------------------------------------------------*/ FoamFile { version 2.0; format ascii; class volScalarField; location "0/cz_solid_12"; object epsilon; } // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // dimensions [0 2 -3 0 0 0 0]; internalField uniform 97.4848; boundaryField { cz_solid_12_to_fluid { type calculated; value uniform 0; } } // ************************************************************************* //
[ "67100764+JoelWright24@users.noreply.github.com" ]
67100764+JoelWright24@users.noreply.github.com
112479992746c128ede72b6445c7d4276e01e888
a5e05718b6f8b402141e6cfd963b340c613200bc
/Submodules/mxml/src/mxml/parsing/GenericNode.cpp
09058552a055078c6941ced99d162965cf7b707b
[ "MIT" ]
permissive
yk81708090/musitkit
8617699d49da9ddea0dc28897c0f6a0895fac9de
7d57e4dd3a21df2dc82f6725accdd89a8560d7d2
refs/heads/master
2022-04-07T08:23:46.894850
2019-12-20T19:25:29
2019-12-20T19:25:29
null
0
0
null
null
null
null
UTF-8
C++
false
false
918
cpp
// Copyright © 2016 Venture Media Labs. // // This file is part of mxml. The full mxml copyright notice, including // terms governing use, modification, and redistribution, is contained in the // file LICENSE at the root of the source code distribution tree. #include "GenericNode.h" namespace mxml { namespace parsing { dom::Optional<std::string> GenericNode::attribute(const std::string& string) const { auto it = _attributes.find(string); if (it != _attributes.end()) return it->second; return dom::Optional<std::string>(); } void GenericNode::setAttribute(const std::string& name, const std::string& value) { _attributes[name] = value; } const GenericNode* GenericNode::child(const std::string& name) const { for (auto& child : _children) { if (child->name() == name) return child.get(); } return nullptr; } } // namespace parsing } // namespace mxml
[ "zhangpengcheng.zpc@bytedance.com" ]
zhangpengcheng.zpc@bytedance.com
d6ab420b1e94ff5c0a5cd67c6252c7853b4a7f1e
c6def4876d8b21c64105975992f2a8d9c909f724
/Chapter16/16_50.cpp
c56d51bd973226a9b054d0b039c4e9989435551e
[]
no_license
Aaricis/Cpp_primer
e08ebdab8510b4b4973a83a876a00cc6d9287cd1
e5848bce1897b0e807eadaeb27039d0d3d74f426
refs/heads/master
2023-03-14T18:25:10.488315
2021-03-22T14:16:37
2021-03-22T14:16:37
298,735,772
0
0
null
null
null
null
UTF-8
C++
false
false
515
cpp
#include<iostream> #include<string> template <typename T> void f(T t) { std::cout << "void f(T t)" << std::endl; } template <typename T> void f(const T * t) { std::cout << "void f(const T * t)" << std::endl; } template <typename T> void g(T t) { std::cout << "void g(T t)" << std::endl; } template <typename T> void g(T * t) { std::cout << "void g(T * t)" << std::endl; } int main() { int i = 42, *p = &i; const int ci = 0, *p2 = &ci; g(42); g(p); g(ci); g(p2); f(42); f(p); f(ci); f(p2); return 0; }
[ "947165603@qq.com" ]
947165603@qq.com
2b3f9a07e0abb6b5a719153486cd479411c4e5e0
22fd3f2330e48e5d5c22b88d2dd6d7659a114b20
/thewayback/src/GameObject.h
4f72c4886128946564c17b05c2dddcafc406a179
[]
no_license
didimoner/thewayback
824a1fdc0827cca54ba13c045e235d9b90ae3490
0c326e1508ade003c2870ca8a4bcffd63d71baa1
refs/heads/master
2023-02-05T15:51:52.143464
2020-12-29T17:59:38
2020-12-29T17:59:38
282,609,025
0
0
null
null
null
null
UTF-8
C++
false
false
753
h
#pragma once #include "pch.h" #include "Vector2f.h" #include "Drawable.h" #include "Entity.h" class GameObject : public Entity, public Drawable { public: struct InitParams { float_t x = 0; float_t y = 0; uint32_t width = 0; uint32_t height = 0; int32_t zIndex = 1; }; protected: Vector2f m_velocity; Vector2f m_acceleration; public: void init(const InitParams& initParams) { m_position = { initParams.x, initParams.y }; m_width = initParams.width; m_height = initParams.height; m_zIndex = initParams.zIndex; } void update() override { m_velocity += m_acceleration; m_position += m_velocity; } virtual void clean() = 0; };
[ "didimoner@gmail.com" ]
didimoner@gmail.com
76219811176d98a57076b1cc42cfd99a20783a62
773169c73bfa09c49046997b6aa92df68fec2b4e
/11_Segment_Trees/03_Problems/01_GSS1_SPOJ.cc
56f06fa9b3342a61465390d2f79f91bd1c64c4c1
[]
no_license
the-stranded-alien/Competitive_Programming_CPP
a9995869bf34cc55ce55fa31da7f7b3b9aadb65d
65dac7953fc1cfa8315f7fe40017abae7515d82f
refs/heads/master
2022-12-22T06:39:12.240658
2020-09-16T12:57:28
2020-09-16T12:57:28
270,649,612
0
0
null
null
null
null
UTF-8
C++
false
false
1,971
cc
#include<iostream> #include<climits> using namespace std; #define MAX 54000 #define INT_MIN -22121 struct treeNode { int prefixSum; int suffixSum; int totalSum; int maxSum; }; int arr[MAX + 1]; treeNode tree[(3 * MAX) + 1]; void makeSegmentTree(int idx, int ss, int se) { if(ss == se) tree[idx] = ((treeNode) {arr[ss], arr[ss], arr[ss], arr[ss]}); else { int mid = (ss + se) / 2; makeSegmentTree(((idx * 2) + 1), ss, mid); makeSegmentTree(((idx * 2) + 2), (mid + 1), se); treeNode left = tree[(idx * 2) + 1]; treeNode right = tree[(idx * 2) + 2]; tree[idx].prefixSum = max(left.prefixSum, (left.totalSum + right.prefixSum)); tree[idx].suffixSum = max(right.suffixSum, (left.suffixSum + right.totalSum)); tree[idx].totalSum = (left.totalSum + right.totalSum); tree[idx].maxSum = max((left.suffixSum + right.prefixSum), max(left.maxSum, right.maxSum)); } return; } treeNode maxSumQuery(int idx, int ss, int se, int qs, int qe) { if((ss >= qs) && (se <= qe)) return tree[idx]; if((qs > se) || (qe < ss)) return ((treeNode) {INT_MIN, INT_MIN, INT_MIN, INT_MIN}); int mid = (ss + se) / 2; treeNode left = maxSumQuery(((2 * idx) + 1), ss, mid, qs, qe); treeNode right = maxSumQuery(((2 * idx) + 2), (mid + 1), se, qs, qe); treeNode temp; temp.prefixSum = max(left.prefixSum, (left.totalSum + right.prefixSum)); temp.suffixSum = max(right.suffixSum, (right.totalSum + left.suffixSum)); temp.totalSum = (left.totalSum + right.totalSum); temp.maxSum = max((left.suffixSum + right.prefixSum), max(left.maxSum, right.maxSum)); return temp; } int main() { int n, q, t, x, y, i; cin >> n; for(int i = 0; i < n; i++) cin >> arr[i]; makeSegmentTree(0, 0, (n - 1)); cin >> q; while(q--) { cin >> x >> y; cout << maxSumQuery(0, 0, (n - 1), (x - 1), (y - 1)).maxSum << endl; } return 0; }
[ "thestrandedalien.mysticdark@gmail.com" ]
thestrandedalien.mysticdark@gmail.com
d4e40894fee6d601e16d4a4a44489102282fddb5
1483544d8af9b148b73da046afdbcc8492769490
/src/AxisAlignedBoundingBox.cpp
a2f9eb88f29ff8d815dffe84c9a89fb467a7875f
[]
no_license
domtsoi/raytracer-domtsoi
a6156cd6887aadf956f2862810b49c64955df29a
33e662ea07db085be68985545b80b50655d619fb
refs/heads/master
2020-03-09T14:47:42.665116
2018-06-15T21:23:16
2018-06-15T21:23:16
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,472
cpp
// // AxisAlignedBoundingBox.cpp // raytrace // // Created by Dominic Tsoi on 6/1/18. // #include "AxisAlignedBoundingBox.hpp" #include <glm/glm.hpp> #include <vector> #include "Triangle.hpp" #include "Sphere.hpp" #include "Box.hpp" #include "Object.hpp" void AABB::createBox(Object * curObject) { if (curObject->type == "Triangle") { Triangle * tri = static_cast<Triangle*>(curObject); Reset(tri->vertA); AddPoint(tri->vertB); AddPoint(tri->vertC); } else if (curObject->type == "Sphere") { Sphere * sphere = static_cast<Sphere *>(curObject); Reset(sphere->center - glm::vec3(sphere->radius)); AddPoint(sphere->center + glm::vec3(sphere->radius)); } else if (curObject->type == "Box") { Box * box = static_cast<Box *>(curObject); Reset(box->min); max = box->max; } } std::vector<glm::vec3> AABB::initVerts() { std::vector<glm::vec3> verts; verts.push_back(glm::vec3(min.x, min.y, min.z)); verts.push_back(glm::vec3(max.x, min.y, min.z)); verts.push_back(glm::vec3(min.x, max.y, min.z)); verts.push_back(glm::vec3(max.x, max.y, min.z)); verts.push_back(glm::vec3(min.x, min.y, max.z)); verts.push_back(glm::vec3(max.x, min.y, max.z)); verts.push_back(glm::vec3(min.x, max.y, max.z)); verts.push_back(glm::vec3(max.x, max.y, max.z)); return verts; } void AABB::applyTransform(glm::mat4 modelMatrix) { std::vector<glm::vec3> verts = initVerts(); for (int i = 0; i < verts.size(); i++) { verts[i] = glm::vec3(modelMatrix * glm::vec4(verts[i], 1.0f)); } Reset(verts[0]); for (int i = 1; i < 8; i++) { AddPoint(verts[i]); } } float AABB::checkIntersect(const Ray ray) { float smallestMax = std::numeric_limits<float>::max(); float largestMin = -(std::numeric_limits<float>::max()); // if (glm::epsilonEqual(ray->direction.x, 0.0f, EPSILON)) // { // if (ray->origin.x < min.x || ray->origin.x > max.x) // { // return -1; // } // } // if (glm::epsilonEqual(ray->direction.y, 0.0f, EPSILON)) // { // if (ray->origin.y < min.y || ray->origin.y > max.y) // { // return -1; // } // } // if (glm::epsilonEqual(ray->direction.z, 0.0f, EPSILON)) // { // if (ray->origin.z < min.z || ray->origin.z > max.z) // { // return -1; // } // } float tXMin = (min.x - ray.origin.x) / ray.direction.x; float tXMax = (max.x - ray.origin.x) / ray.direction.x; float tYMin = (min.y - ray.origin.y) / ray.direction.y; float tYMax = (max.y - ray.origin.y) / ray.direction.y; float tZMin = (min.z - ray.origin.z) / ray.direction.z; float tZMax = (max.z - ray.origin.z) / ray.direction.z; if (tXMin > tXMax) { std::swap(tXMin, tXMax); } if (tYMin > tYMax) { std::swap(tYMin, tYMax); } if (tZMin > tZMax) { std::swap(tZMin, tZMax); } smallestMax = std::min(std::min(tXMax, tYMax), tZMax); largestMin = std::max(std::max(tXMin, tYMin), tZMin); if (smallestMax < largestMin || smallestMax < 0) { return -1; } if (largestMin > 0) { return largestMin; } else { return smallestMax; } }
[ "dominictsoi@yahoo.com" ]
dominictsoi@yahoo.com
9e86550a83f61bfc4c1864150ffef9e7da109388
a2e9c6ce15319bc8ac16ab263f8c411105373938
/include/layers/layer.h
42bf2f3a44c89523569eea946182c5e8161b7a2b
[ "Apache-2.0" ]
permissive
wzzju/caffe_inference
4081de0c4d6f828dd89e3a8d6faa3fcbe7863484
d358489727d5cc775e78a85caace4057b0949f9e
refs/heads/master
2021-03-27T18:53:35.672647
2017-12-30T16:11:50
2017-12-30T16:11:50
115,787,578
0
1
null
null
null
null
UTF-8
C++
false
false
424
h
// // Created by yuchen on 17-12-29. // #ifndef CAFFE_REF_LAYER_H #define CAFFE_REF_LAYER_H typedef enum { LAYER_TYPE_UNKNOWN = 0, LAYER_TYPE_CONV, LAYER_TYPE_FULLY_CONNECTED, LAYER_TYPE_POOL, LAYER_TYPE_ACTIVATION, LAYER_TYPE_SOFTMAX, } layer_type; class layer { public: virtual void forward(float *input, float *fced_res = nullptr)=0; layer_type type; }; #endif //CAFFE_REF_LAYER_H
[ "wzzju@mail.ustc.edu.cn" ]
wzzju@mail.ustc.edu.cn
052a98488aa2bb78b30bcb9e5590e109fb696f3b
3593844fd237df13b8f1839beab949f57de27307
/Codeforces/Brazilian2018/10/test.cpp
452bc854aca1c17227eee43e24f89b4656c042d1
[]
no_license
juniorandrade1/Competitive-Programming
d1330cdde646e770c423abf474c0bfc7ef04c4c0
75c11dcfef38088e2367508acfe507f85cfbd36b
refs/heads/master
2021-01-10T09:32:17.051979
2018-05-27T20:06:26
2018-05-27T20:06:26
51,162,932
1
3
null
null
null
null
UTF-8
C++
false
false
2,057
cpp
#include <bits/stdc++.h> using namespace std; typedef long long ll; typedef long double ld; typedef pair<int,int> ii; typedef vector<int> vi; typedef vector< ii > vii; #define INF 0x3F3F3F3F #define LINF 0x3F3F3F3F3F3F3F3FLL #define pb push_back #define mp make_pair #define pq priority_queue #define LSONE(s) ((s)&(-s)) //LASTBIT #define EPS 1e-7 #define PI 3.1415926535897932384626433832795028841971693993 #define DEG_to_RAD(X) (X * PI / 180) #define F first #define S second #ifdef ONLINE_JUDGE #define debug(args...) #else #define debug(args...) fprintf(stderr,args) #endif ////////////////////// int dx[] = {1,-1,0,0}; int dy[] = {0,0,-1,1}; ////////////////////// typedef long long CHType; #define CHINF LINF struct Line { CHType m, b; Line(){}; Line(CHType _m, CHType _b) { m = _m; b = _b; } bool operator < (Line other) const { if(m != other.m) return m > other.m; return b > other.b; } CHType getVal(CHType x) { return m * x + b; } }; struct ConvexHullTrick { vector< Line > st; bool badLine(Line s, Line t, Line u) { if(t.m == u.m) return true; return 1.0 * (t.b - s.b) * (s.m - u.m) >= 1.0 * (u.b - s.b) * (s.m - t.m); //don't forget 1.0 } void addLine(Line l) { while(st.size() >= 2 && badLine(st[st.size() - 2], st[st.size() - 1], l)) st.pop_back(); st.push_back(l); } CHType query(CHType x) { if(st.size() == 0) return CHINF; int lo = 0, hi = st.size() - 1; while(lo < hi) { int md = (lo + hi) >> 1; if(st[md].getVal(x) <= st[md + 1].getVal(x)) hi = md; else lo = md + 1; } return st[lo].getVal(x); } }; const int N = 1000010; ConvexHullTrick s; ll a[N],b[N],pd[N]; ll n; int main() { //ios::sync_with_stdio(0); scanf("%lld",&n); for(int i=0;i<n;++i) scanf("%lld",a+i); for(int i=0;i<n;++i) scanf("%lld",b+i); pd[0] = 0; s.addLine(Line(b[0],pd[0])); for(int i=1;i<n;++i) { pd[i] = s.query(a[i]); s.addLine(Line(b[i],pd[i])); } printf("%lld\n",pd[n-1]); return 0; }
[ "junior.andrade.cco@gmail.com" ]
junior.andrade.cco@gmail.com
c4f9b8308791355eb0137d4a9f518d6c7ff4dfe9
e2108cf56b1a0f3fb18f250a881634a1be21c4fc
/app/src/main/cpp/AudioChannel.cpp
7c31ae8a48682e311e2f9aab9274f5909b6db614
[]
no_license
yizhongliu/NativePlayer
c17276b4718fe7694c9123aad0dea90b10ef8d47
ad901eba1bc5610f20a1e8925755799c291241e8
refs/heads/master
2020-07-14T16:59:39.998234
2019-09-16T09:47:35
2019-09-16T09:47:35
205,358,182
0
0
null
null
null
null
UTF-8
C++
false
false
11,550
cpp
// // Created by llm on 19-8-29. // #include "AudioChannel.h" #include "macro.h" extern "C" { #include <libswresample/swresample.h> }; AudioChannel::AudioChannel(int id, AVCodecContext *avCodecContext, AVRational time_base, JavaCallHelper *javaCallHelper) : BaseChannel(id, avCodecContext, time_base, javaCallHelper) { //缓冲区大小如何定 // ? out_channels = av_get_channel_layout_nb_channels(AV_CH_LAYOUT_STEREO); out_sampleSize = av_get_bytes_per_sample(AV_SAMPLE_FMT_S16); out_sampleRate = 44100; // 2(通道数) * 2(16bit=2字节)*44100(采样率) out_buffers_size = out_channels * out_sampleSize * out_sampleRate; out_buffers = static_cast<uint8_t *>(malloc(out_buffers_size)); memset(out_buffers, 0, out_buffers_size); swrContext = swr_alloc_set_opts(0, AV_CH_LAYOUT_STEREO, AV_SAMPLE_FMT_S16, out_sampleRate, codecContext->channel_layout, codecContext->sample_fmt, codecContext->sample_rate, 0, 0); //初始化重采样上下文 swr_init(swrContext); } AudioChannel::~AudioChannel() { if (swrContext) { swr_free(&swrContext); swrContext = 0; } DELETE(out_buffers); } void *task_audio_decode(void *args) { AudioChannel *audioChannel = static_cast<AudioChannel *>(args); audioChannel->audio_decode(); return 0;//一定一定一定要返回0!!! } void *task_audio_play(void *args) { AudioChannel *audioChannel = static_cast<AudioChannel *>(args); audioChannel->audio_play(); return 0;//一定一定一定要返回0!!! } void bqPlayerCallback(SLAndroidSimpleBufferQueueItf bq, void *context) { AudioChannel *audioChannel = static_cast<AudioChannel *>(context); int pcm_size = audioChannel->getPCM(); if (pcm_size > 0) { (*bq)->Enqueue(bq, audioChannel->out_buffers, pcm_size); } } void AudioChannel::start() { isPlaying = true; packets.setWork(1); frames.setWork(1); //解码 pthread_create(&pid_audio_decode, 0, task_audio_decode, this); //播放 pthread_create(&pid_audio_play, 0, task_audio_play, this); } void AudioChannel::stop() { isPlaying = 0; javaCallHelper = 0; packets.setWork(0); frames.setWork(0); pthread_join(pid_audio_decode, 0); pthread_join(pid_audio_play, 0); /** * 7、释放 */ //7.1 设置播放器状态为停止状态 if (bqPlayerPlay) { (*bqPlayerPlay)->SetPlayState(bqPlayerPlay, SL_PLAYSTATE_STOPPED); } //7.2 销毁播放器 if (bqPlayerObject) { (*bqPlayerObject)->Destroy(bqPlayerObject); bqPlayerObject = 0; bqPlayerBufferQueue = 0; } //7.3 销毁混音器 if (outputMixObject) { (*outputMixObject)->Destroy(outputMixObject); outputMixObject = 0; } //7.4 销毁引擎 if (engineObject) { (*engineObject)->Destroy(engineObject); engineObject = 0; engineInterface = 0; } } /** * 音频解码与视频一样 */ void AudioChannel::audio_decode() { AVPacket *packet = 0; int ret; while (isPlaying) { ret = packets.pop(packet); if (!isPlaying) { //如果停止播放了,跳出循环 释放packet break; } if (!ret) { //取数据包失败 continue; } //拿到了视频数据包(编码压缩了的),需要把数据包给解码器进行解码 ret = avcodec_send_packet(codecContext, packet); // releaseAVPacket(&packet);//? if (ret) { //往解码器发送数据包失败,跳出循环 break; } releaseAVPacket(&packet);//释放packet,后面不需要了 AVFrame *frame = av_frame_alloc(); ret = avcodec_receive_frame(codecContext, frame); if (ret == AVERROR(EAGAIN)) { //重来 continue; } else if (ret != 0) { break; } //ret == 0 数据收发正常,成功获取到了解码后的视频原始数据包 AVFrame ,格式是 yuv //对frame进行处理(渲染播放)直接写? /** * 内存泄漏点2 * 控制 frames 队列 */ while (isPlaying && frames.size() > 100) { av_usleep(10 * 1000); continue; } frames.push(frame);// PCM数据 }//end while releaseAVPacket(&packet); } void AudioChannel::audio_play() { /** * 1、创建引擎并获取引擎接口 */ SLresult result; // 1.1 创建引擎对象:SLObjectItf engineObject result = slCreateEngine(&engineObject, 0, NULL, 0, NULL, NULL); if (SL_RESULT_SUCCESS != result) { return; } // 1.2 初始化引擎 result = (*engineObject)->Realize(engineObject, SL_BOOLEAN_FALSE); if (SL_RESULT_SUCCESS != result) { return; } // 1.3 获取引擎接口 SLEngineItf engineInterface result = (*engineObject)->GetInterface(engineObject, SL_IID_ENGINE, &engineInterface); if (SL_RESULT_SUCCESS != result) { return; } /** * 2、设置混音器 */ // 2.1 创建混音器:SLObjectItf outputMixObject result = (*engineInterface)->CreateOutputMix(engineInterface, &outputMixObject, 0, 0, 0); if (SL_RESULT_SUCCESS != result) { return; } // 2.2 初始化混音器 result = (*outputMixObject)->Realize(outputMixObject, SL_BOOLEAN_FALSE); if (SL_RESULT_SUCCESS != result) { return; } /** * 3、创建播放器 */ //3.1 配置输入声音信息 //创建buffer缓冲类型的队列 2个队列 SLDataLocator_AndroidSimpleBufferQueue loc_bufq = {SL_DATALOCATOR_ANDROIDSIMPLEBUFFERQUEUE, 2}; //pcm数据格式 //SL_DATAFORMAT_PCM:数据格式为pcm格式 //2:双声道 //SL_SAMPLINGRATE_44_1:采样率为44100 //SL_PCMSAMPLEFORMAT_FIXED_16:采样格式为16bit //SL_PCMSAMPLEFORMAT_FIXED_16:数据大小为16bit //SL_SPEAKER_FRONT_LEFT | SL_SPEAKER_FRONT_RIGHT:左右声道(双声道) //SL_BYTEORDER_LITTLEENDIAN:小端模式 SLDataFormat_PCM format_pcm = {SL_DATAFORMAT_PCM, 2, SL_SAMPLINGRATE_44_1, SL_PCMSAMPLEFORMAT_FIXED_16, SL_PCMSAMPLEFORMAT_FIXED_16, SL_SPEAKER_FRONT_LEFT | SL_SPEAKER_FRONT_RIGHT, SL_BYTEORDER_LITTLEENDIAN}; //数据源 将上述配置信息放到这个数据源中 SLDataSource audioSrc = {&loc_bufq, &format_pcm}; //3.2 配置音轨(输出) //设置混音器 SLDataLocator_OutputMix loc_outmix = {SL_DATALOCATOR_OUTPUTMIX, outputMixObject}; SLDataSink audioSnk = {&loc_outmix, NULL}; //需要的接口 操作队列的接口 const SLInterfaceID ids[1] = {SL_IID_BUFFERQUEUE}; const SLboolean req[1] = {SL_BOOLEAN_TRUE}; //3.3 创建播放器 result = (*engineInterface)->CreateAudioPlayer(engineInterface, &bqPlayerObject, &audioSrc, &audioSnk, 1, ids, req); if (SL_RESULT_SUCCESS != result) { return; } //3.4 初始化播放器:SLObjectItf bqPlayerObject result = (*bqPlayerObject)->Realize(bqPlayerObject, SL_BOOLEAN_FALSE); if (SL_RESULT_SUCCESS != result) { return; } //3.5 获取播放器接口:SLPlayItf bqPlayerPlay result = (*bqPlayerObject)->GetInterface(bqPlayerObject, SL_IID_PLAY, &bqPlayerPlay); if (SL_RESULT_SUCCESS != result) { return; } /** * 4、设置播放回调函数 */ //4.1 获取播放器队列接口:SLAndroidSimpleBufferQueueItf bqPlayerBufferQueue (*bqPlayerObject)->GetInterface(bqPlayerObject, SL_IID_BUFFERQUEUE, &bqPlayerBufferQueue); //4.2 设置回调 void bqPlayerCallback(SLAndroidSimpleBufferQueueItf bq, void *context) (*bqPlayerBufferQueue)->RegisterCallback(bqPlayerBufferQueue, bqPlayerCallback, this); /** * 5、设置播放器状态为播放状态 */ (*bqPlayerPlay)->SetPlayState(bqPlayerPlay, SL_PLAYSTATE_PLAYING); /** * 6、手动激活回调函数 */ bqPlayerCallback(bqPlayerBufferQueue, this); } /** * 获取pcm数据 * @return 数据大小 */ int AudioChannel::getPCM() { int pcm_data_size = 0; AVFrame *frame = 0; int64_t running_time; int64_t clock_time_diff; while (isPlaying) { int ret = frames.pop(frame); if (!isPlaying) { //如果停止播放了,跳出循环 释放packet break; } if (!ret) { //取数据包失败 continue; } //pcm数据在 frame中 //这里获得的解码后pcm格式的音频原始数据,有可能与创建的播放器中设置的pcm格式不一样 //重采样?example:resample //假设输入10个数据,有可能这次转换只转换了8个,还剩2个数据(delay) //断点:1024 * 48000 //swr_get_delay: 下一个输入数据与下下个输入数据之间的时间间隔 int64_t delay = swr_get_delay(swrContext, frame->sample_rate); //a * b / c //AV_ROUND_UP:向上取整 int64_t out_max_samples = av_rescale_rnd(frame->nb_samples + delay, frame->sample_rate, out_sampleRate, AV_ROUND_UP); //上下文 //输出缓冲区 //输出缓冲区能容纳的最大数据量 //输入数据 //输入数据量 int out_samples = swr_convert(swrContext, &out_buffers, out_max_samples, (const uint8_t **) (frame->data), frame->nb_samples); // 获取swr_convert转换后 out_samples个 *2 (16位)*2(双声道) pcm_data_size = out_samples * out_sampleSize * out_channels; //获取音频时间 audio_time需要被VideoChannel获取 audio_time = frame->best_effort_timestamp * av_q2d(time_base); LOGE("audio_time &lf", audio_time); if (clockTime) { if (frame->best_effort_timestamp == 0) { int64_t basetime = clockTime->getClockTime(); clockTime->setClockBasetime(basetime); } else { running_time = clockTime->getClockTime() - clockTime->getClockBasetime(); clock_time_diff = (int64_t) (audio_time * 1000000) - running_time; LOGE("clock_time_diff: %ld", clock_time_diff); if (clock_time_diff > 0) { if (clock_time_diff > 1000000) { av_usleep((delay * 2) * 1000000); } else { av_usleep(((delay * 1000000) + clock_time_diff)); } } else if (clock_time_diff < 0) { if (abs(clock_time_diff) >= 50000) { frames.sync(); continue; } } } } if (javaCallHelper) { javaCallHelper->onProgress(THREAD_CHILD, audio_time); } break; }//end while releaseAVFrame(&frame); return pcm_data_size; }
[ "liuliming@iviewdisplays.com" ]
liuliming@iviewdisplays.com
d8bf190939fcf24bb5421ef262885e70f901e64c
887a7ff30a1496e29622ddc9867a8b9a7e686a6d
/HoG/hog_opencv.cpp
9d1aa4f9d7bcc65eda3a33ce24ad6ba3e9729dd3
[]
no_license
DanyEle/SPD_19
906d6f2f4c22b41562615d0df5aa3871329c9de6
557e808372ed40843535bb3e2a20845e000a3753
refs/heads/master
2020-04-25T22:35:59.771327
2019-06-12T15:11:27
2019-06-12T15:11:27
173,116,473
0
1
null
null
null
null
UTF-8
C++
false
false
2,232
cpp
//Daniele Gadler //University of Pisa //Department of Computer Science //Course: Programming Tools for Parallel and Distributed Systems //Year: 2019 //Inspired from the guide at: https://www.learnopencv.com/histogram-of-oriented-gradients/ #include "opencv2/imgproc/imgproc.hpp" #include "opencv2/opencv.hpp" #include <iostream> using namespace cv; int main( int argc, char** argv ) { cv::Mat inputImage; //Requirement: input image has aspect ratio 1:2 inputImage = cv::imread("bolt.jpg" , CV_LOAD_IMAGE_COLOR); cv::Mat imageResized; //1. step: resize the input image Size size(64,128); cv::resize(inputImage, imageResized, size); //2. step: gradient calculation for the x and y axes cv::Mat imageReColored; imageResized.convertTo(imageReColored, CV_32F, 1/255.0); //3. step: Apply the sobel filter to compute gradients over the X and Y axes //The gradient on the X and Y axes removed 'smooth' areas of the image, where //no abrupt change is present cv::Mat imgGradX, imgGradY; cv::Sobel(imageReColored, imgGradX, CV_32F, 1, 0, 1); cv::Sobel(imageReColored, imgGradY, CV_32F, 1, 0, 1); //4. step: Find the magnitude and direction of the gradient //The magnitude of gradient at a pixel is the maximum of the //magnitude of gradients of the three channels, and the //angle is the angle corresponding to the maximum gradient. cv::Mat imgMagnitude, imgAngle; cv::cartToPolar(imgGradY, imgGradY, imgMagnitude, imgAngle, 1); //5. Step: Compute the Histogram of Oriented Gradients //Need to divide the image into 8x8 cells to capture interesting features //in the input image (ex: face, top of head, etc..) for (int y = 0 ; y < imgAngle.rows ; y++) { for (int x = 0 ;x < imgAngle.cols ; x++) { if(y % 8 == 0 && x % 8 == 0) { std:: cout << imgAngle.at<Vec3b>(x,y); } } } //now process the input image if(! inputImage.data ) { std::cout << "Could not open or find the image" << std::endl ; return -1; } cv::namedWindow( "Display window", cv::WINDOW_AUTOSIZE ); //cv::imshow( "Display window", imgMagnitude); //cv::imshow( "Display window", imgAngle); //cv::waitKey(0); return 0; }
[ "daniele.gadler@yahoo.it" ]
daniele.gadler@yahoo.it
f58de0834e284256ed948ecb6d0908d58dae6e31
a89e4164878026b6db880d5a1d089775bb195824
/expensive_calculator/expensive_calculator/expensive_calculator.cpp
0bb4cb1354a645afb97dcc8d4b30c39493a8ac6b
[]
no_license
SierraOffline/CodeLib_Textbook
e3605a599bcaff604c3cee92579e861ba49e00db
219e69acf28a139a387540f5836aa8dc039375a3
refs/heads/master
2016-09-06T17:54:32.521214
2013-07-04T16:15:50
2013-07-04T16:15:50
null
0
0
null
null
null
null
UTF-8
C++
false
false
369
cpp
//Expensive Calculator //Demonstrates built-in arithmetic operators #include <iostream> using namespace std; int main() { cout<<"7+3="<<7+3<<endl; cout<<"7-3="<<7-3<<endl; cout<<"7*3="<<7*3<<endl; cout<<"7/3="<<7/3<<endl; cout<<"7.0/3.0="<<7.0/3.0<<endl; cout<<"7%3="<<7%3<<endl; cout<<"7+3*5="<<7+3*5<<endl; cout<<"(7+3)*5="<<(7+3)*5=<<endl; return 0; }
[ "laine.nooney@gmail.com" ]
laine.nooney@gmail.com
0acadf1bcd98cd4f0c7e4e1f8a9afcd95e625f1c
d6b4bdf418ae6ab89b721a79f198de812311c783
/ciam/include/tencentcloud/ciam/v20210420/model/ListUserGroupsResponse.h
5500cbca6318e1761e51e64cd1a6031c4b6490eb
[ "Apache-2.0" ]
permissive
TencentCloud/tencentcloud-sdk-cpp-intl-en
d0781d461e84eb81775c2145bacae13084561c15
d403a6b1cf3456322bbdfb462b63e77b1e71f3dc
refs/heads/master
2023-08-21T12:29:54.125071
2023-08-21T01:12:39
2023-08-21T01:12:39
277,769,407
2
0
null
null
null
null
UTF-8
C++
false
false
4,368
h
/* * 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. */ #ifndef TENCENTCLOUD_CIAM_V20210420_MODEL_LISTUSERGROUPSRESPONSE_H_ #define TENCENTCLOUD_CIAM_V20210420_MODEL_LISTUSERGROUPSRESPONSE_H_ #include <string> #include <vector> #include <map> #include <tencentcloud/core/AbstractModel.h> #include <tencentcloud/ciam/v20210420/model/UserGroup.h> #include <tencentcloud/ciam/v20210420/model/Pageable.h> namespace TencentCloud { namespace Ciam { namespace V20210420 { namespace Model { /** * ListUserGroups response structure. */ class ListUserGroupsResponse : public AbstractModel { public: ListUserGroupsResponse(); ~ListUserGroupsResponse() = default; CoreInternalOutcome Deserialize(const std::string &payload); std::string ToJsonString() const; /** * 获取User group list Note: this field may return null, indicating that no valid values can be obtained. * @return Content User group list Note: this field may return null, indicating that no valid values can be obtained. * */ std::vector<UserGroup> GetContent() const; /** * 判断参数 Content 是否已赋值 * @return Content 是否已赋值 * */ bool ContentHasBeenSet() const; /** * 获取Total number Note: this field may return null, indicating that no valid values can be obtained. * @return Total Total number Note: this field may return null, indicating that no valid values can be obtained. * */ int64_t GetTotal() const; /** * 判断参数 Total 是否已赋值 * @return Total 是否已赋值 * */ bool TotalHasBeenSet() const; /** * 获取Pagination Note: this field may return null, indicating that no valid values can be obtained. * @return Pageable Pagination Note: this field may return null, indicating that no valid values can be obtained. * */ Pageable GetPageable() const; /** * 判断参数 Pageable 是否已赋值 * @return Pageable 是否已赋值 * */ bool PageableHasBeenSet() const; private: /** * User group list Note: this field may return null, indicating that no valid values can be obtained. */ std::vector<UserGroup> m_content; bool m_contentHasBeenSet; /** * Total number Note: this field may return null, indicating that no valid values can be obtained. */ int64_t m_total; bool m_totalHasBeenSet; /** * Pagination Note: this field may return null, indicating that no valid values can be obtained. */ Pageable m_pageable; bool m_pageableHasBeenSet; }; } } } } #endif // !TENCENTCLOUD_CIAM_V20210420_MODEL_LISTUSERGROUPSRESPONSE_H_
[ "tencentcloudapi@tencent.com" ]
tencentcloudapi@tencent.com
a3b6d1467c8e4248055849093b375d76692137d1
9508e47b9471a614e367d3e1277d477f1e1a3843
/sys-prog/aup2ex/ux/uxposixipc.cpp
1159f0baf786ad7e073f2492af35ef04886a5b8e
[ "LicenseRef-scancode-unknown-license-reference", "BSD-3-Clause" ]
permissive
rkks/refer
f4dd8e4a0b8fc00c189a1a0aa05359445d36aed4
ae118ce7d4888b5a9bdb43aaaff2569af791f334
refs/heads/master
2022-09-29T08:32:56.961875
2022-09-19T07:30:59
2022-09-19T07:30:59
127,179,189
6
1
NOASSERTION
2022-04-06T03:31:16
2018-03-28T18:04:47
C
UTF-8
C++
false
false
6,212
cpp
/* Copyright 2003 by Marc J. Rochkind. All rights reserved. May be copied only for purposes and under conditions described on the Web page www.basepath.com/aup/copyright.htm. The Example Files are provided "as is," without any warranty; without even the implied warranty of merchantability or fitness for a particular purpose. The author and his publisher are not responsible for any damages, direct or incidental, resulting from the use or non-use of these Example Files. The Example Files may contain defects, and some contain deliberate coding mistakes that were included for educational reasons. You are responsible for determining if and how the Example Files are to be used. */ #include "ux.hpp" using namespace Ux; /** Calls mq_open. */ void PosixMsg::open(const char *name, int flags, mode_t perms, struct mq_attr *attr) { #if _POSIX_MESSAGE_PASSING > 0 if ((mqd = ::mq_open(name, flags, perms, attr)) == (mqd_t)-1) throw Error(errno); #else throw Error(ENOSYS); #endif } /** Calls mq_close. */ void PosixMsg::close(void) { #if _POSIX_MESSAGE_PASSING > 0 if (::mq_close(mqd) == -1) throw Error(errno); #else throw Error(ENOSYS); #endif } /** Calls mq_unlink. Could be static, as it doesn't refer to the mqd. */ void PosixMsg::unlink(const char *name) { #if _POSIX_MESSAGE_PASSING > 0 if (::mq_unlink(name) == -1) throw Error(errno); #else throw Error(ENOSYS); #endif } /** Calls mq_send. */ void PosixMsg::send(const char *msg, size_t msgsize, unsigned priority) { #if _POSIX_MESSAGE_PASSING > 0 if (::mq_send(mqd, msg, msgsize, priority) == -1) throw Error(errno); #else throw Error(ENOSYS); #endif } /** Calls mq_receive. */ ssize_t PosixMsg::receive(char *msg, size_t msgsize, unsigned *priorityp) { #if _POSIX_MESSAGE_PASSING > 0 ssize_t n; if ((n = ::mq_receive(mqd, msg, msgsize, priorityp)) == -1) throw Error(errno); return n; #else throw Error(ENOSYS); #endif } /** Calls mq_timedsend. */ void PosixMsg::timedsend(const char *msg, size_t msgsize, unsigned priority, const struct timespec *tmout) { #if _POSIX_MESSAGE_PASSING > 0 && _POSIX_TIMEOUTS > 0 if (::mq_timedsend(mqd, msg, msgsize, priority, tmout) == -1) throw Error(errno); #else throw Error(ENOSYS); #endif } /** Calls mq_timedreceive. */ ssize_t PosixMsg::timedreceive(char *msg, size_t msgsize, unsigned *priorityp, const struct timespec *tmout) { #if _POSIX_MESSAGE_PASSING > 0 && _POSIX_TIMEOUTS > 0 ssize_t n; if ((n = ::mq_timedreceive(mqd, msg, msgsize, priorityp, tmout)) == -1) throw Error(errno); return n; #else throw Error(ENOSYS); #endif } /** Calls mq_notify. */ void PosixMsg::notify(const struct sigevent *ep) { #if _POSIX_MESSAGE_PASSING > 0 if (::mq_notify(mqd, ep) == -1) throw Error(errno); #else throw Error(ENOSYS); #endif } /** Calls mq_getattr. */ void PosixMsg::getattr(struct mq_attr *attr) { #if _POSIX_MESSAGE_PASSING > 0 if (::mq_getattr(mqd, attr) == -1) throw Error(errno); #else throw Error(ENOSYS); #endif } /** Calls mq_setattr. */ void PosixMsg::setattr(const struct mq_attr *attr, struct mq_attr *oldattr) { #if _POSIX_MESSAGE_PASSING > 0 if (::mq_setattr(mqd, attr, oldattr) == -1) throw Error(errno); #else throw Error(ENOSYS); #endif } /** Calls shm_open. */ void PosixShm::open(const char *name, int flags, mode_t perms) { #if _POSIX_SHARED_MEMORY_OBJECTS > 0 && !defined(LINUXs) if ((fd = ::shm_open(name, flags, perms)) == -1) throw Error(errno); #else throw Error(ENOSYS); #endif } /** Calls shm_unlink. Could be static, as it doesn't refer to the fd. */ void PosixShm::unlink(const char *name) { #if _POSIX_SHARED_MEMORY_OBJECTS > 0 && !defined(LINUXs) if (::shm_unlink(name) == -1) throw Error(errno); #else throw Error(ENOSYS); #endif } /** Calls mmap. Arguments are in a different order to take advantage of defaults, and fd argument comes from the class. */ void *PosixShm::mmap(size_t len, void *addr, int prot, int flags, off_t off) { void *p; if ((p = ::mmap(addr, len, prot, flags, fd, off)) == MAP_FAILED) throw Error(errno); return p; } /** Calls munmap. Could be static, as it doesn't refer to the fd. */ void PosixShm::munmap(void *addr, size_t len) { if (::munmap(addr, len) == -1) throw Error(errno); } /** Calls sem_open. */ void PosixSem::open(const char *name, int flags, mode_t perms, unsigned value) { #if _POSIX_SEMAPHORES > 0 if ((sem = ::sem_open(name, flags, perms, value)) == SEM_FAILED) throw Error(errno); #else throw Error(ENOSYS); #endif } /** Calls sem_close. */ void PosixSem::close(void) { #if _POSIX_SEMAPHORES > 0 if (::sem_close(sem) == -1) throw Error(errno); #else throw Error(ENOSYS); #endif } /** Calls sem_destroy. */ void PosixSem::destroy(void) { #if _POSIX_SEMAPHORES > 0 if (::sem_destroy(sem) == -1) throw Error(errno); #else throw Error(ENOSYS); #endif } /** Calls sem_getvalue. */ void PosixSem::getvalue(int *valuep) { #if _POSIX_SEMAPHORES > 0 if (::sem_getvalue(sem, valuep) == -1) throw Error(errno); #else throw Error(ENOSYS); #endif } /** Calls sem_init. */ void PosixSem::init(int pshared, unsigned value) { #if _POSIX_SEMAPHORES > 0 if (::sem_init(sem, pshared, value) == -1) throw Error(errno); #else throw Error(ENOSYS); #endif } /** Calls sem_post. */ void PosixSem::post(void) { #if _POSIX_SEMAPHORES > 0 if (::sem_post(sem) == -1) throw Error(errno); #else throw Error(ENOSYS); #endif } /** Calls sem_timedwait. */ void PosixSem::timedwait(const struct timespec *time) { #if _POSIX_SEMAPHORES > 0 && _POSIX_TIMEOUTS > 0 if (::sem_timedwait(sem, time) == -1) throw Error(errno); #else throw Error(ENOSYS); #endif } /** Calls sem_trywait. */ void PosixSem::trywait(void) { #if _POSIX_SEMAPHORES > 0 if (::sem_trywait(sem) == -1) throw Error(errno); #else throw Error(ENOSYS); #endif } /** Calls sem_unlink. Could be static, as it doesn't use sem. */ void PosixSem::unlink(const char *name) { #if _POSIX_SEMAPHORES > 0 if (::sem_unlink(name) == -1) throw Error(errno); #else throw Error(ENOSYS); #endif } /** Calls sem_wait. */ void PosixSem::wait(void) { #if _POSIX_SEMAPHORES > 0 if (::sem_wait(sem) == -1) throw Error(errno); #else throw Error(ENOSYS); #endif }
[ "ravikirandotks@gmail.com" ]
ravikirandotks@gmail.com
6e154fdbbc0dafc218d19f6c7867c240dd400caf
8d31659116e04c50e43ac62abc7b1c2b74a9e97b
/FileWithExpense.cpp
68a580f2f381eb0ac6d88f61c9743393eb279830
[]
no_license
Vallu89/BalanceManager
12d39ee2284286dd5f3b09b3bcec1b9533ef83b8
590880cfd93bbde55abe035b71871ce419eff555
refs/heads/master
2021-05-25T12:51:56.253493
2020-04-07T19:48:09
2020-04-07T19:48:09
253,761,655
0
0
null
null
null
null
UTF-8
C++
false
false
722
cpp
#include "FileWithExpense.h" void FileWithExpense::writeExpensesIntoFile( Expense expense ) { bool isFileExist = true; xml.Load(FILE_NAME); if (!xml.FindElem("Expenses")) { xml.SetDoc("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n"); xml.AddElem("Expenses"); isFileExist = false; } xml.IntoElem(); xml.AddElem("Expense"); xml.IntoElem(); xml.AddElem("UserId",expense.getUserId()); xml.AddElem("ExpenseId",expense.getExpenseId()); xml.AddElem("Date",expense.getDate()); xml.AddElem("DateAsInt",expense.getDateAsInt()); xml.AddElem("Item",expense.getItem()); xml.AddElem("Amount",to_string(expense.getAmount())); xml.Save(FILE_NAME); }
[ "rafal.zborowski.dev@gmail.com" ]
rafal.zborowski.dev@gmail.com
385e00e42f01fb7abfe0821a0cff0b4d993a9c35
7c33c6f77b135b38f1781346f69c672a8c87f449
/src/share/manipulator/manipulators/post_event_to_virtual_devices/post_event_to_virtual_devices.hpp
fcee72c2be0c0dd65140632be8756a18d7a18ec2
[ "Unlicense" ]
permissive
erikolofsson/Karabiner-Elements
9d75d6340bedf240e61e937b9576783ce051ca8e
88839a6c326c710b7ad9e1a0916e6bf1f04d8c8f
refs/heads/master
2023-01-20T00:48:51.221890
2020-11-28T08:39:39
2020-11-28T08:39:39
null
0
0
null
null
null
null
UTF-8
C++
false
false
16,559
hpp
#pragma once #include "../../types.hpp" #include "../base.hpp" #include "console_user_server_client.hpp" #include "key_event_dispatcher.hpp" #include "keyboard_repeat_detector.hpp" #include "krbn_notification_center.hpp" #include "mouse_key_handler.hpp" #include "queue.hpp" #include "types.hpp" #include <pqrs/karabiner/driverkit/virtual_hid_device_service.hpp> namespace krbn { namespace manipulator { namespace manipulators { namespace post_event_to_virtual_devices { class post_event_to_virtual_devices final : public base, public pqrs::dispatcher::extra::dispatcher_client { public: post_event_to_virtual_devices(std::weak_ptr<console_user_server_client> weak_console_user_server_client) : base(), dispatcher_client(), weak_console_user_server_client_(weak_console_user_server_client) { mouse_key_handler_ = std::make_unique<mouse_key_handler>(queue_); } virtual ~post_event_to_virtual_devices(void) { detach_from_dispatcher([this] { mouse_key_handler_ = nullptr; }); } virtual bool already_manipulated(const event_queue::entry& front_input_event) { return false; } virtual manipulate_result manipulate(event_queue::entry& front_input_event, const event_queue::queue& input_event_queue, std::shared_ptr<event_queue::queue> output_event_queue, absolute_time_point now) { if (output_event_queue) { if (!front_input_event.get_valid()) { return manipulate_result::passed; } output_event_queue->push_back_entry(front_input_event); front_input_event.set_valid(false); // Dispatch modifier key event only when front_input_event is key_down or modifier key. bool dispatch_modifier_key_event = false; bool dispatch_modifier_key_event_before = false; { std::optional<modifier_flag> m; if (auto key_code = front_input_event.get_event().get_key_code()) { m = make_modifier_flag(*key_code); } if (m) { // front_input_event is modifier key event. if (!front_input_event.get_lazy()) { dispatch_modifier_key_event = true; dispatch_modifier_key_event_before = false; } } else { if (front_input_event.get_event_type() == event_type::key_down) { dispatch_modifier_key_event = true; dispatch_modifier_key_event_before = true; } else if (front_input_event.get_event().get_type() == event_queue::event::type::pointing_motion) { // We should not dispatch modifier key events while key repeating. // (See comments in `handle_pointing_device_event_from_event_tap` for details.) if (!queue_.get_keyboard_repeat_detector().is_repeating() && pressed_buttons_.empty() && !mouse_key_handler_->active()) { dispatch_modifier_key_event = true; dispatch_modifier_key_event_before = true; } } } } if (dispatch_modifier_key_event && dispatch_modifier_key_event_before) { key_event_dispatcher_.dispatch_modifier_key_event(output_event_queue->get_modifier_flag_manager(), queue_, front_input_event.get_event_time_stamp().get_time_stamp()); } switch (front_input_event.get_event().get_type()) { case event_queue::event::type::key_code: case event_queue::event::type::consumer_key_code: case event_queue::event::type::apple_vendor_keyboard_key_code: case event_queue::event::type::apple_vendor_top_case_key_code: if (auto e = front_input_event.get_event().make_momentary_switch_event()) { if (!e->modifier_flag()) { if (auto usage_pair = e->make_usage_pair()) { switch (front_input_event.get_event_type()) { case event_type::key_down: key_event_dispatcher_.dispatch_key_down_event(front_input_event.get_device_id(), usage_pair->get_usage_page(), usage_pair->get_usage(), queue_, front_input_event.get_event_time_stamp().get_time_stamp()); break; case event_type::key_up: key_event_dispatcher_.dispatch_key_up_event(usage_pair->get_usage_page(), usage_pair->get_usage(), queue_, front_input_event.get_event_time_stamp().get_time_stamp()); break; case event_type::single: break; } } } } break; case event_queue::event::type::pointing_button: case event_queue::event::type::pointing_motion: post_pointing_input_report(front_input_event, output_event_queue); break; case event_queue::event::type::shell_command: if (auto shell_command = front_input_event.get_event().get_shell_command()) { if (front_input_event.get_event_type() == event_type::key_down) { queue_.push_back_shell_command_event(*shell_command, front_input_event.get_event_time_stamp().get_time_stamp()); } } break; case event_queue::event::type::select_input_source: if (auto input_source_specifiers = front_input_event.get_event().get_input_source_specifiers()) { if (front_input_event.get_event_type() == event_type::key_down) { queue_.push_back_select_input_source_event(*input_source_specifiers, front_input_event.get_event_time_stamp().get_time_stamp()); } } break; case event_queue::event::type::mouse_key: if (auto mouse_key = front_input_event.get_event().get_mouse_key()) { if (front_input_event.get_event_type() == event_type::key_down) { mouse_key_handler_->push_back_mouse_key(front_input_event.get_device_id(), *mouse_key, output_event_queue, front_input_event.get_event_time_stamp().get_time_stamp()); } else { mouse_key_handler_->erase_mouse_key(front_input_event.get_device_id(), *mouse_key, output_event_queue, front_input_event.get_event_time_stamp().get_time_stamp()); } } break; case event_queue::event::type::stop_keyboard_repeat: if (auto key = queue_.get_keyboard_repeat_detector().get_repeating_key()) { key_event_dispatcher_.dispatch_key_up_event(key->first, key->second, queue_, front_input_event.get_event_time_stamp().get_time_stamp()); } break; case event_queue::event::type::system_preferences_properties_changed: if (auto properties = front_input_event.get_event().get_if<pqrs::osx::system_preferences::properties>()) { mouse_key_handler_->set_system_preferences_properties(*properties); } break; case event_queue::event::type::virtual_hid_keyboard_configuration_changed: if (auto c = front_input_event.get_event().get_if<core_configuration::details::virtual_hid_keyboard>()) { mouse_key_handler_->set_virtual_hid_keyboard_configuration(*c); } break; case event_queue::event::type::none: case event_queue::event::type::set_variable: case event_queue::event::type::device_keys_and_pointing_buttons_are_released: case event_queue::event::type::device_grabbed: case event_queue::event::type::device_ungrabbed: case event_queue::event::type::caps_lock_state_changed: case event_queue::event::type::pointing_device_event_from_event_tap: case event_queue::event::type::frontmost_application_changed: case event_queue::event::type::input_source_changed: // Do nothing break; } if (dispatch_modifier_key_event && !dispatch_modifier_key_event_before) { key_event_dispatcher_.dispatch_modifier_key_event(output_event_queue->get_modifier_flag_manager(), queue_, front_input_event.get_event_time_stamp().get_time_stamp()); } } return manipulate_result::passed; } virtual bool active(void) const { return !queue_.empty(); } virtual bool needs_virtual_hid_pointing(void) const { return false; } virtual void handle_device_keys_and_pointing_buttons_are_released_event(const event_queue::entry& front_input_event, event_queue::queue& output_event_queue) { // modifier flags key_event_dispatcher_.dispatch_modifier_key_event(output_event_queue.get_modifier_flag_manager(), queue_, front_input_event.get_event_time_stamp().get_time_stamp()); // pointing buttons { auto buttons = output_event_queue.get_pointing_button_manager().make_hid_report_buttons(); if (pressed_buttons_ != buttons) { pqrs::karabiner::driverkit::virtual_hid_device_driver::hid_report::pointing_input report; report.buttons = buttons; queue_.emplace_back_pointing_input(report, event_type::key_up, front_input_event.get_event_time_stamp().get_time_stamp()); // Save buttons for `handle_device_ungrabbed_event`. pressed_buttons_ = buttons; } } // mouse keys mouse_key_handler_->erase_mouse_keys_by_device_id(front_input_event.get_device_id(), front_input_event.get_event_time_stamp().get_time_stamp()); } virtual void handle_device_ungrabbed_event(device_id device_id, const event_queue::queue& output_event_queue, absolute_time_point time_stamp) { // Release pressed keys key_event_dispatcher_.dispatch_key_up_events_by_device_id(device_id, queue_, time_stamp); // Release buttons { auto buttons = output_event_queue.get_pointing_button_manager().make_hid_report_buttons(); if (pressed_buttons_ != buttons) { pqrs::karabiner::driverkit::virtual_hid_device_driver::hid_report::pointing_input report; report.buttons = buttons; queue_.emplace_back_pointing_input(report, event_type::key_up, time_stamp); pressed_buttons_ = buttons; } } // Release modifiers key_event_dispatcher_.dispatch_modifier_key_event(output_event_queue.get_modifier_flag_manager(), queue_, time_stamp); // Release mouse_key_handler_ mouse_key_handler_->erase_mouse_keys_by_device_id(device_id, time_stamp); } virtual void handle_pointing_device_event_from_event_tap(const event_queue::entry& front_input_event, event_queue::queue& output_event_queue) { // We should not dispatch modifier key events while key repeating. // // macOS does not ignore the modifier state change while key repeating. // If you enabled `control-f -> right_arrow` configuration, // apps will catch control-right_arrow event if release the lazy modifier here while right_arrow key is repeating. // We should not dispatch modifier key events while mouse keys active. // // For example, we should not restore right_shift by physical mouse movement when we use "change right_shift+r to scroll", // because the right_shift key_up event interrupt scroll event. // We should not dispatch modifier key events while mouse buttons are pressed. // If you enabled `option-f -> button1` configuration, // apps will catch option-button1 event if release the lazy modifier here while button1 is pressed. switch (front_input_event.get_event_type()) { case event_type::key_down: case event_type::single: if (!queue_.get_keyboard_repeat_detector().is_repeating() && pressed_buttons_.empty() && !mouse_key_handler_->active()) { key_event_dispatcher_.dispatch_modifier_key_event(output_event_queue.get_modifier_flag_manager(), queue_, front_input_event.get_event_time_stamp().get_time_stamp()); } break; case event_type::key_up: break; } } virtual void set_valid(bool value) { // This manipulator is always valid. } void async_post_events(std::weak_ptr<pqrs::karabiner::driverkit::virtual_hid_device_service::client> weak_virtual_hid_device_service_client) { enqueue_to_dispatcher( [this, weak_virtual_hid_device_service_client] { queue_.async_post_events(weak_virtual_hid_device_service_client, weak_console_user_server_client_); }); } const queue& get_queue(void) const { return queue_; } void clear_queue(void) { return queue_.clear(); } const key_event_dispatcher& get_key_event_dispatcher(void) const { return key_event_dispatcher_; } private: void post_pointing_input_report(event_queue::entry& front_input_event, std::shared_ptr<event_queue::queue> output_event_queue) { pqrs::karabiner::driverkit::virtual_hid_device_driver::hid_report::pointing_input report; report.buttons = output_event_queue->get_pointing_button_manager().make_hid_report_buttons(); if (auto pointing_motion = front_input_event.get_event().get_pointing_motion()) { report.x = pointing_motion->get_x(); report.y = pointing_motion->get_y(); report.vertical_wheel = pointing_motion->get_vertical_wheel(); report.horizontal_wheel = pointing_motion->get_horizontal_wheel(); } queue_.emplace_back_pointing_input(report, front_input_event.get_event_type(), front_input_event.get_event_time_stamp().get_time_stamp()); // Save buttons for `handle_device_ungrabbed_event`. pressed_buttons_ = report.buttons; } std::weak_ptr<console_user_server_client> weak_console_user_server_client_; queue queue_; key_event_dispatcher key_event_dispatcher_; std::unique_ptr<mouse_key_handler> mouse_key_handler_; std::unordered_set<modifier_flag> pressed_modifier_flags_; pqrs::karabiner::driverkit::virtual_hid_device_driver::hid_report::buttons pressed_buttons_; }; } // namespace post_event_to_virtual_devices } // namespace manipulators } // namespace manipulator } // namespace krbn
[ "tekezo@pqrs.org" ]
tekezo@pqrs.org
d59685a9aa712818848739fab86605bd878f3090
92754bb891a128687f3fbc48a312aded752b6bcd
/Algorithms/C++/941-Valid_Mountain_Array.cpp
15fd2c98ca596c6075f962d5b1a0ccb52a0ea473
[]
no_license
daidai21/Leetcode
ddecaf0ffbc66604a464c3c9751f35f3abe5e7e5
eb726b3411ed11e2bd00fee02dc41b77f35f2632
refs/heads/master
2023-03-24T21:13:31.128127
2023-03-08T16:11:43
2023-03-08T16:11:43
167,968,602
8
3
null
null
null
null
UTF-8
C++
false
false
1,497
cpp
// 941. Valid Mountain Array // Runtime: 32 ms, faster than 25.11% of C++ online submissions for Valid Mountain Array. // Memory Usage: 22.5 MB, less than 37.99% of C++ online submissions for Valid Mountain Array. class Solution { public: bool validMountainArray(vector<int>& arr) { if (arr.size() < 3) return false; int max_idx = 0; for (; max_idx < arr.size(); ++max_idx) { // max val in front if (max_idx == 0 && arr[max_idx] >= arr[max_idx + 1]) { return false; } else if (arr[max_idx] > arr[max_idx + 1]) { break; // val same } else if (arr[max_idx] == arr[max_idx + 1]) { return false; } } // max val in end if (max_idx == arr.size() - 1) return false; for (; max_idx < arr.size() - 1; ++max_idx) { if (arr[max_idx] <= arr[max_idx + 1]) return false; } return true; } }; // Runtime: 20 ms, faster than 96.65% of C++ online submissions for Valid Mountain Array. // Memory Usage: 22.4 MB, less than 37.99% of C++ online submissions for Valid Mountain Array. class Solution { public: bool validMountainArray(vector<int>& arr) { int i = 0; while (i + 1 < arr.size() && arr[i] < arr[i + 1]) i++; if (i == 0 || i == arr.size() - 1) return false; while (i + 1 < arr.size() && arr[i] > arr[i + 1]) i++; return i == arr.size() - 1; } };
[ "hu.fwh@alibaba-inc.com" ]
hu.fwh@alibaba-inc.com
c480f8ec3e07210f55216cf6ce68390f684d4486
c25631ab35cf0798593f2d56b199ee5d48487a75
/Cuphead/Game.cpp
2600111965e32eff7b7f7a75d56fe888b425b3da
[]
no_license
lkjfrf/Cuphead
a4eeb7c597129d24780c5ef650e51acabcbbe91b
11f174a4c53efd889edb99f775ff3203ba485258
refs/heads/main
2023-06-20T12:00:01.923871
2021-07-13T21:02:50
2021-07-13T21:02:50
385,734,634
1
0
null
null
null
null
UHC
C++
false
false
30,895
cpp
#pragma once #include "framework.h"128 #include "Game.h" // include 순서 잘해야됨 #include <cstdlib> //랜덤함수 #include <ctime> //시간으로랜덤함수 seed역할 Game::Game() { } Game::~Game() { } void Game::InitAll() { m_Scene = Introing; m_StageNum = INTRO; m_uIntro.bTrigger = true; m_nScore = 0; m_nHeroHit = 0; m_nHeroHealth = HEROHEALTH; InitBG(m_uIntro); InitBG(m_uStage1[0]); InitBG(m_uStage1[1]); InitBG(m_uStage1[2]); InitBG(m_uStage1[3]); InitHero(m_uHero[IdleRight]); InitHero(m_uHero[IdleLeft]); InitHero(m_uHero[RunRight]); InitHero(m_uHero[RunLeft]); InitHero(m_uHero[JumpRight]); InitHero(m_uHero[JumpLeft]); InitHero(m_uHero[HitRight]); InitHero(m_uHero[HitLeft]); InitHero(m_uHero[ShootRight]); InitHero(m_uHero[ShootLeft]); //Enemy1 InitEnemy1(m_uEnemy1[Enemy1_Intro]); InitEnemy1(m_uEnemy1[Enemy1_Attack]); InitEnemy1(m_uEnemy1[Enemy1_Death]); InitHeroBullet(); InitHeroBulletExplode(); InitEnemy1BulletExplode(); InitEnemy1Bullet(); //Enemy2 InitEnemy2(m_uEnemy2[Enemy2_Intro]); InitEnemy2(m_uEnemy2[Enemy2_Attack]); InitEnemy2(m_uEnemy2[Enemy2_Death]); //InitEnemy2BulletExplode(); //InitEnemy2Bullet(); m_Alpha[0].bf.SourceConstantAlpha = 255; m_Alpha[1].bf.SourceConstantAlpha = 255; m_Fade.bf.SourceConstantAlpha = 255; m_FX.bf.SourceConstantAlpha = 120; } void Game::InitResource(HDC hdc) { // 베이스 기본버퍼 m_Base.hbmp = (HBITMAP)LoadImage(NULL, L"image//base.bmp", IMAGE_BITMAP, 0, 0, LR_LOADFROMFILE); // base.bmp 저장할때 24비트 비트맵으로 저장해야됨 GetObject(m_Base.hbmp, sizeof(BITMAP), &m_Base.bit); // bit에 비트맵정보가 들어감 m_Base.dc = CreateCompatibleDC(hdc); // 윈도우화면과 호환되는 DC를 만들기 m_Base.holdbmp = (HBITMAP)SelectObject(m_Base.dc, m_Base.hbmp); // 현재상황이 여기에 저장됨 //Intro MakeResource(m_Intro, m_Base, L"image//Intro.bmp", m_uIntro, 6, 1280); //BG1 MakeResource(m_Stage1[0], m_Base, L"image//BG//stage1//0.bmp",m_uStage1[0],4,1280); MakeResource(m_Stage1[1], m_Base, L"image//BG//stage1//1.bmp",m_uStage1[1],1,1280); MakeResource(m_Stage1[2], m_Base, L"image//BG//stage1//2.bmp",m_uStage1[2],1,1280); MakeResource(m_Stage1[3], m_Base, L"image//BG//stage1//3.bmp",m_uStage1[3],1,1280); //Hero MakeResource(m_Hero[IdleRight], m_Base, L"image//Hero//Idle//IdleRight//1.bmp",m_uHero[IdleRight],5,100); MakeResource(m_Hero[IdleLeft], m_Base, L"image//Hero//Idle//IdleLeft//1.bmp", m_uHero[IdleLeft],5,100); MakeResource(m_Hero[RunRight], m_Base, L"image//Hero//Run//RunRIght//1.bmp",m_uHero[RunRight],16,100); MakeResource(m_Hero[RunLeft], m_Base, L"image//Hero//Run//RunLeft//1.bmp", m_uHero[RunLeft],16,100); MakeResource(m_Hero[JumpRight], m_Base, L"image//Hero//Jump//JumpRight//1.bmp"); MakeResource(m_Hero[JumpLeft], m_Base, L"image//Hero//Jump//JumpLeft//1.bmp"); MakeResource(m_Hero[HitRight], m_Base, L"image//Hero//Hit//HitRight//1.bmp"); MakeResource(m_Hero[HitLeft], m_Base, L"image//Hero//Hit//HitLeft//1.bmp"); MakeResource(m_Hero[ShootRight], m_Base, L"image//Hero//Shoot//ShootRight//1.bmp",m_uHero[ShootRight],6, 100); MakeResource(m_Hero[ShootLeft], m_Base, L"image//Hero//Shoot//ShootLeft//1.bmp", m_uHero[ShootLeft], 6, 100); //Enemy1 MakeResource(m_Enemy1[Enemy1_Intro], m_Base, L"image//Enemy1//Attack.bmp", m_uEnemy1[Enemy1_Intro], 22, Enemy1XSIZE); MakeResource(m_Enemy1[Enemy1_Attack], m_Base, L"image//Enemy1//Attack.bmp", m_uEnemy1[Enemy1_Attack],22, Enemy1XSIZE); MakeResource(m_Enemy1[Enemy1_Death], m_Base, L"image//Enemy1//Attack.bmp", m_uEnemy1[Enemy1_Death], 22, Enemy1XSIZE); //Enemy2 MakeResource(m_Enemy2[Enemy2_Intro], m_Base, L"image//Enemy2//1.bmp", m_uEnemy2[Enemy2_Intro], 17, Enemy2XSIZE); MakeResource(m_Enemy2[Enemy2_Attack], m_Base, L"image//Enemy2//1.bmp", m_uEnemy2[Enemy2_Attack], 17, Enemy2XSIZE); MakeResource(m_Enemy2[Enemy2_Death], m_Base, L"image//Enemy2//1.bmp", m_uEnemy2[Enemy2_Death], 17, Enemy2XSIZE); //HeroBullet MakeResource(m_HeroBullet, m_Base, L"image//HeroBullet//HeroBullet.bmp",m_uHeroBullet[0],5,45); //EnemyBullet for (int i = 0; i < ENEMYBULLETNUM; i++) { MakeResource(m_Enemy1Bullet, m_Base, L"image//EnemyBullet//Enemy1Bullet.bmp", m_uEnemy1Bullet[i], 3, 61); //총알 } //HeroBulletExplode MakeResource(m_HeroBulletExplode[0], m_Base, L"image//HeroBullet//1.bmp", m_uHeroBulletExplode,3,240); //Enemy1BulletExplode MakeResource(m_Enemy1BulletExplode, m_Base, L"image//EnemyBullet//Enemy1Explode.bmp", m_uEnemy1BulletExplode[0],6,153); MakeResource(m_Enemy1BulletExplode, m_Base, L"image//EnemyBullet//Enemy1Explode.bmp", m_uEnemy1BulletExplode[1],6,153); //Alpha m_Alpha[0].hbmp = (HBITMAP)LoadImage(NULL, L"image//base.bmp", IMAGE_BITMAP, 0, 0, LR_LOADFROMFILE); GetObject(m_Alpha[0].hbmp, sizeof(BITMAP), &m_Base.bit); m_Alpha[0].dc = CreateCompatibleDC(hdc); m_Alpha[0].holdbmp = (HBITMAP)SelectObject(m_Alpha[0].dc, m_Alpha[0].hbmp); m_Alpha[0].bf.AlphaFormat = 0; m_Alpha[0].bf.BlendFlags = 0; m_Alpha[0].bf.BlendOp = 0; m_Alpha[0].bf.SourceConstantAlpha = 127; //0~255 127은 반투명임 m_Alpha[1].hbmp = (HBITMAP)LoadImage(NULL, L"image//base.bmp", IMAGE_BITMAP, 0, 0, LR_LOADFROMFILE); // base.bmp 저장할때 24비트 비트맵으로 저장해야됨 GetObject(m_Alpha[1].hbmp, sizeof(BITMAP), &m_Base.bit); // bit에 비트맵정보가 들어감 m_Alpha[1].dc = CreateCompatibleDC(hdc); // 윈도우화면과 호환되는 DC를 만들기 m_Alpha[1].holdbmp = (HBITMAP)SelectObject(m_Alpha[1].dc, m_Alpha[1].hbmp); m_Alpha[1].bf.AlphaFormat = 0; m_Alpha[1].bf.BlendFlags = 0; m_Alpha[1].bf.BlendOp = 0; m_Alpha[1].bf.SourceConstantAlpha = 127; //0~255 127은 반투명임 //Fade m_Fade.hbmp = (HBITMAP)LoadImage(NULL,L"image//Ready//RW.bmp", IMAGE_BITMAP,0, 0, LR_LOADFROMFILE); GetObject(m_Fade.hbmp, sizeof(BITMAP), &m_Fade.bit); m_Fade.dc = CreateCompatibleDC(m_Base.dc); m_Fade.holdbmp = (HBITMAP)SelectObject(m_Fade.dc, m_Fade.hbmp); m_Fade.bf.AlphaFormat = 0; m_Fade.bf.BlendFlags = 0; m_Fade.bf.BlendOp = 0; m_Fade.bf.SourceConstantAlpha = 255; m_uFade.frame = 0; m_uFade.MaxFrame = 22 - 1; m_uFade.size = 1280; //FX m_FX.hbmp = (HBITMAP)LoadImage(NULL, L"image//FrontFX//1.bmp", IMAGE_BITMAP, 0, 0, LR_LOADFROMFILE); GetObject(m_FX.hbmp, sizeof(BITMAP), &m_FX.bit); m_FX.dc = CreateCompatibleDC(m_Base.dc); m_FX.holdbmp = (HBITMAP)SelectObject(m_FX.dc, m_FX.hbmp); m_FX.bf.AlphaFormat = 0; m_FX.bf.BlendFlags = 0; m_FX.bf.BlendOp = 0; m_FX.bf.SourceConstantAlpha = 255; m_uFX.frame = 0; m_uFX.MaxFrame = 24 - 1; m_uFX.size = 1280; //SCORE MakeResource(m_Score, m_Base, L"image//HeroHealth//score.bmp", m_uScore, 4, 90); //CLEAR MakeResource(m_Clear, m_Base, L"image//Clear.bmp", m_uClear, 1, 1280); //GAMEOVER MakeResource(m_Gameover, m_Base, L"image//GameOver.bmp", m_uGameOver, 1, 1280); } void Game::InitBG(UPDATE& update) { update.pt.x = 0; update.pt.y = 0; //update.aEndTick = update.aStartTick = GetTickCount(); } void Game::InitHero(UPDATE & update) { update.rt.left = 1280/2-HEROXSIZE/2; update.rt.top = YRES - HEROYSIZE - 20; update.rt.right = update.rt.left + HEROXSIZE; update.rt.bottom = update.rt.top + HEROYSIZE; m_HeroState = IdleRight; } void Game::InitHeroBullet() { for (int i = 0; i < HEROBULLETNUM; i++) { m_uHeroBullet[i].rt.left = m_Hero[0].rt.left + 45 / 2; //총알 45x45 m_uHeroBullet[i].rt.top = m_Hero[0].rt.top; m_uHeroBullet[i].rt.right = m_uHeroBullet[i].rt.left + 45; m_uHeroBullet[i].rt.bottom = m_uHeroBullet[i].rt.top + 45; } } void Game::InitHeroBullet(int i) { m_uHeroBullet[i].rt.left = m_uHero[0].rt.left + 45 / 2; //총알 x : 80 m_uHeroBullet[i].rt.top = m_uHero[0].rt.top; m_uHeroBullet[i].rt.right = m_uHeroBullet[i].rt.left + 45; m_uHeroBullet[i].rt.bottom = m_uHeroBullet[i].rt.top + 45; } void Game::InitEnemy1Bullet() { srand((unsigned int)time(NULL)); for (int i = 0; i < ENEMYBULLETNUM; i++) { m_uEnemy1Bullet[i].rt.left = rand() % XFILE; m_uEnemy1Bullet[i].rt.right = m_uEnemy1Bullet[i].rt.left + 61; m_uEnemy1Bullet[i].rt.top = 0-rand() % YFILE; m_uEnemy1Bullet[i].rt.bottom = m_uEnemy1Bullet[i].rt.top + 105; } } void Game::InitEnemy1Bullet(int i) { //srand((unsigned int)time(NULL)); // 총알2개가 동시에(같은시간)에 초기화되면 무한루프 m_uEnemy1Bullet[i].rt.left = ((XRES + 1) / 61)*(rand() % 61 + 1); //61배수의 랜덤수 m_uEnemy1Bullet[i].rt.right = m_uEnemy1Bullet[i].rt.left + 61; m_uEnemy1Bullet[i].rt.top = 0 - (YRES / 105) * (rand() % 105 +1); //105배수의 랜덤수 m_uEnemy1Bullet[i].rt.bottom = m_uEnemy1Bullet[i].rt.top + 105; if (InitOverLap(i)) // x,y 좌표가 겹친다면 다시좌표초기화 { return; } else { InitEnemy1Bullet(i); } } bool Game::InitOverLap(int i) //x좌표가 서로같은게 있다면 false, 아니면 true { for (int j = 0; j < i ; j++) { if (m_uEnemy1Bullet[i].rt.left == m_uEnemy1Bullet[j].rt.left) return false; else true; } for (int j = i + 1; j < ENEMYBULLETNUM; j++) { if (m_uEnemy1Bullet[i].rt.left == m_uEnemy1Bullet[j].rt.left) return false; else true; } } void Game::InitEnemy1(UPDATE & update) { update.rt.left = 1280 / 2 - Enemy1XSIZE /2; update.rt.top = -Enemy1YSIZE+500; update.rt.right = update.rt.left + Enemy1XSIZE; update.rt.bottom = update.rt.top + Enemy1YSIZE; m_EnemyState = Enemy1_Attack; } void Game::InitEnemy2(UPDATE & update) { update.rt.left = 1280 / 2 - Enemy2XSIZE / 2; update.rt.top = -Enemy2YSIZE+500; update.rt.right = update.rt.left + Enemy2XSIZE; update.rt.bottom = update.rt.top + Enemy2YSIZE; //m_EnemyState = Enemy2_Attack; } void Game::ReleaseResource() { SelectObject(m_Base.dc, m_Base.holdbmp); DeleteDC(m_Base.dc); //m_Base.dc = CreateCompatibleDC(hdc); 이걸로 만들어진걸 delete } void Game::GameLoop(HDC hdc) { UpdateAll(); DrawAll(hdc); } void Game::SetClient() { m_rtClient = { 0, 0, 1280, 720 }; } RECT Game::GetClient() { return m_rtClient; } bool Game::KeyCheck() { if (m_StageNum == INTRO) // 인트로라면 { m_StageNum = STAGE1; // 레디화면 보이게 return true; } return false; } void Game::MakeResource(HANDLES & dest, HANDLES base, const WCHAR * w) { // TODO: 여기에 구현 코드 추가. dest.hbmp = (HBITMAP)LoadImage(NULL, w, IMAGE_BITMAP, 0, 0, LR_LOADFROMFILE); GetObject(dest.hbmp, sizeof(BITMAP), &dest.bit); //!!!!여기서부턴베이스에호환되는 dc 를 만든다 dest.dc = CreateCompatibleDC(base.dc); dest.holdbmp = (HBITMAP)SelectObject(dest.dc, dest.hbmp); } void Game::MakeResource(HANDLES & dest, HANDLES base, const WCHAR * w, UPDATE & update, int MaxFrame, int size) { // TODO: 여기에 구현 코드 추가. dest.hbmp = (HBITMAP)LoadImage(NULL, w, IMAGE_BITMAP, 0, 0, LR_LOADFROMFILE); GetObject(dest.hbmp, sizeof(BITMAP), &dest.bit); //!!!!여기서부턴베이스에호환되는 dc 를 만든다 dest.dc = CreateCompatibleDC(base.dc); dest.holdbmp = (HBITMAP)SelectObject(dest.dc, dest.hbmp); update.frame = 0; update.MaxFrame = MaxFrame-1; update.size = size; } void Game::InitHeroBulletExplode() { m_uHeroBulletExplode.aEndTick = m_uHeroBulletExplode.aStartTick = GetTickCount(); m_uHeroBulletExplode.bTrigger = FALSE; //적에 부딫히면 true } void Game::InitEnemy1BulletExplode() { m_uEnemy1BulletExplode[0].aEndTick = m_uEnemy1BulletExplode[0].aStartTick = GetTickCount(); m_uEnemy1BulletExplode[1].aEndTick = m_uEnemy1BulletExplode[1].aStartTick = GetTickCount(); m_uEnemy1BulletExplode[0].bTrigger = FALSE; //적에 부딫히면 true m_uEnemy1BulletExplode[1].bTrigger = FALSE; //적에 부딫히면 true m_uEnemy1BulletExplode[0].test = 0; m_uEnemy1BulletExplode[1].test = 0; } void Game::DrawAll(HDC hdc) { switch (m_StageNum) { case INTRO: DrawIntro(); DrawFX(); break; case STAGE1: DrawBG(); DrawEnemy1(hdc); DrawBG2(); DrawHeroBullet(hdc); DrawHero(hdc); DrawHeroBulletExplode(); DrawEnemy1Bullet(); DrawEnemy1BulletExplode(); DrawBG3(); DrawScore(hdc); DrawFade(); DrawFX(); break; case STAGE2: DrawBG(); DrawEnemy2(hdc); DrawBG2(); DrawHeroBullet(hdc); DrawHero(hdc); DrawHeroBulletExplode(); DrawEnemy1Bullet(); DrawEnemy1BulletExplode(); DrawBG3(); DrawScore(hdc); DrawFade(); DrawFX(); break; case CLEAR: DrawClear(); DrawFX(); break; case GAME_OVER: DrawGameover(); DrawFX(); break; default: break; } DrawDebug(hdc); BitBlt(hdc, 0, 0, m_Base.bit.bmWidth, m_Base.bit.bmHeight, m_Base.dc, 0, 0, SRCCOPY);//윈도우 화면에 베이스 찍기 } void Game::DrawAlpha() { BitBlt(m_Alpha[0].dc, 0, 0, XRES, YRES, m_Base.dc, 0, 0, SRCCOPY); } void Game::DrawFade() { BitBlt(m_Alpha[0].dc, 0, 0, XRES, YRES, m_Fade.dc, m_uFade.frame * 1280, 0, SRCCOPY); AlphaBlend(m_Base.dc, 0, 0, XRES, YRES, m_Alpha[0].dc, 0, 0, XRES, YRES, m_Fade.bf); } void Game::DrawFX() { BitBlt(m_Alpha[1].dc, 0, 0, XRES, YRES, m_FX.dc, m_uFX.frame * 1280, 0, SRCCOPY); AlphaBlend(m_Base.dc, 0, 0, XRES, YRES, m_Alpha[1].dc, 0, 0, XRES, YRES, m_FX.bf); } void Game::DrawHero(HDC hdc) { TransparentBlt(m_Base.dc, m_uHero[m_HeroState].rt.left, //그리기 시작위치 x m_uHero[m_HeroState].rt.top, //그리기 시작위치 y HEROXSIZE, //그릴 길이 HEROYSIZE, //그릴 높이 m_Hero[m_HeroState].dc, //소스의 dc m_uHero[m_HeroState].frame* HEROXSIZE, //소스의 x위치 0, HEROXSIZE, HEROYSIZE, RGB(255, 255, 255)); for (int i = 0; i < 12; i++) { //MaxMinXBG(m_uEnemy1[i]); if(m_Scene == Playing) MoveKey(m_uHero[i], 1, 10); //중요 } } void Game::DrawHeroBullet(HDC hdc) { for (int i = 0; i < HEROBULLETNUM; i++) { if (m_uHeroBullet[i].bTrigger == TRUE) { TransparentBlt(m_Base.dc, m_uHeroBullet[i].rt.left, m_uHeroBullet[i].rt.top, 45, 45, m_HeroBullet.dc, 0, //소스의 x위치 0, 45, 45, RGB(255, 255, 255)); } } } void Game::DrawEnemy1(HDC hdc) { TransparentBlt(m_Base.dc, m_uEnemy1[m_EnemyState].rt.left, //그리기 시작위치 x m_uEnemy1[m_EnemyState].rt.top, //그리기 시작위치 y Enemy1XSIZE, //그릴 길이 Enemy1YSIZE, //그릴 높이 m_Enemy1[m_EnemyState].dc, //소스의 dc m_uEnemy1[m_EnemyState].frame* m_uEnemy1[m_EnemyState].size, //소스의 x위치 0, Enemy1XSIZE, //그릴 길이 Enemy1YSIZE, RGB(0, 128, 128)); //for (int i = 0; i < 10; i++) //{ // //MaxMinXBG(m_uEnemy1[i]); // MoveKey(m_uEnemy1[i], 1, 10); //} } void Game::DrawEnemy1Bullet() { for (int i = 0; i < ENEMYBULLETNUM; i++) { TransparentBlt(m_Base.dc, m_uEnemy1Bullet[i].rt.left, m_uEnemy1Bullet[i].rt.top, 61, 105, m_Enemy1Bullet.dc, m_uEnemy1Bullet[i].frame * m_uEnemy1Bullet[i].size, 0, 61, 105, RGB(0, 128, 128)); } } void Game::DrawEnemy2(HDC hdc) { TransparentBlt(m_Base.dc, m_uEnemy2[m_EnemyState].rt.left, //그리기 시작위치 x m_uEnemy2[m_EnemyState].rt.top, //그리기 시작위치 y Enemy2XSIZE, //그릴 길이 Enemy2YSIZE, //그릴 높이 m_Enemy2[m_EnemyState].dc, //소스의 dc m_uEnemy2[m_EnemyState].frame* m_uEnemy2[m_EnemyState].size, //소스의 x위치 0, Enemy2XSIZE, //그릴 길이 Enemy2YSIZE, RGB(0, 128, 128)); } void Game::DrawIntro() { TransparentBlt(m_Base.dc, 0, 0, XRES, YRES, m_Intro.dc, m_uIntro.frame* m_uIntro.size, m_uIntro.pt.y, XRES, YRES, RGB(1, 2, 3)); } void Game::DrawBG() { TransparentBlt(m_Base.dc, 0, 0, XRES, YRES, m_Stage1[0].dc, m_uStage1[0].pt.x, 0, XRES, YRES, RGB(255, 0, 255)); TransparentBlt(m_Base.dc, 0, 0, XRES, YRES, m_Stage1[1].dc, 0, 0, XRES, YRES, RGB(255, 255, 255)); } void Game::DrawBG2() { TransparentBlt(m_Base.dc, 0, 0, XRES, YRES, m_Stage1[2].dc, m_uStage1[2].pt.x, 0, XRES, YRES, RGB(255, 255, 255)); } void Game::DrawBG3() { TransparentBlt(m_Base.dc, 0, 0, XRES, YRES, m_Stage1[3].dc, m_uStage1[3].pt.x, 0, XRES, YRES, RGB(255, 255, 255)); } void Game::DrawClear() { TransparentBlt(m_Base.dc, 0, 0, XRES, YRES, m_Clear.dc, 0, 0, XRES, YRES, RGB(1, 1, 1)); } void Game::DrawGameover() { TransparentBlt(m_Base.dc, 0, 0, XRES, YRES, m_Gameover.dc, 0, 0, XRES, YRES, RGB(1, 1, 1)); } void Game::DrawHeroBulletExplode() { if (m_uHeroBulletExplode.bTrigger == FALSE) return; POINT pt; if (m_StageNum == STAGE1) { pt.x = m_Enemy1[0].rt.left + 500; pt.y = m_Enemy1[0].rt.top + (m_uEnemy1[0].size - 240) / 2; } else if(m_StageNum == STAGE2) { pt.x = m_Enemy2[0].rt.left + 500; pt.y = m_Enemy2[0].rt.top + (m_uEnemy2[0].size - 240) / 2 + 300; } TransparentBlt(m_Base.dc, pt.x, pt.y, 240, 240, m_HeroBulletExplode[m_uHeroBulletExplode.frame].dc, 240 * m_uHeroBulletExplode.frame, 0, 240, 240, RGB(0, 128, 128)); } void Game::DrawEnemy1BulletExplode() { //if (m_uEnemy1BulletExplode.bTrigger == FALSE) return; if (m_uEnemy1BulletExplode[0].bTrigger == FALSE) return; POINT pt; pt.x = m_uEnemy1BulletExplode[0].rt.left; pt.y = m_uEnemy1BulletExplode[0].rt.top; TransparentBlt(m_Base.dc, pt.x, pt.y, 153, 116, //m_Enemy1BulletExplode[m_uEnemy1BulletExplode.frame].dc, m_Enemy1BulletExplode.dc, 153 * m_uEnemy1BulletExplode[0].frame, //153, 0, 153, 116, RGB(0, 128, 128)); } void Game::DrawDebug(HDC hdc) { if (m_bDebug == FALSE) return; Rectangle(hdc, m_uHeroBullet[0].rt.left, m_uHeroBullet[0].rt.top, m_uHeroBullet[0].rt.right, m_uHeroBullet[0].rt.bottom); Rectangle(hdc, m_uHero[0].rt.left, m_uHero[0].rt.top, m_uHero[0].rt.right, m_uHero[0].rt.bottom); Rectangle(hdc, m_uEnemy1[1].rt.left, m_uEnemy1[1].rt.top, m_uEnemy1[1].rt.right, m_uEnemy1[1].rt.bottom-200 ); WCHAR ttt[100]; // TODO: 여기에 구현 코드 추가. //wsprintf(ttt, L"FPS : %d", m_Debug.FrameRate); wsprintf(ttt, L"FPS : %d", m_uEnemy2[1].rt.top); size_t size; StringCchLength(ttt, 100, &size); SetBkMode(m_Base.dc, TRANSPARENT); SetTextColor(m_Base.dc, RGB(0, 0, 0)); TextOut(m_Base.dc, 30, 50, ttt, (int)size); SetTextColor(m_Base.dc, RGB(255, 255, 255)); TextOut(m_Base.dc, 25, 45, ttt, (int)size); for (int i = 0; i < ENEMYBULLETNUM; i++) { Rectangle(hdc, m_uEnemy1Bullet[i].rt.left, m_uEnemy1Bullet[i].rt.top, m_uEnemy1Bullet[i].rt.right, m_uEnemy1Bullet[i].rt.bottom); } for (int i = 0; i < ENEMYBULLETNUM; i++) { wsprintf(ttt, L"[%d]위치 : [%d,%d]", i, m_uEnemy1Bullet[i].rt.left, m_uEnemy1Bullet[i].rt.right ); //wsprintf(ttt, L"%d,%d,%d,%d", // m_uHero[i].rt.left, m_uHero[i].rt.top, m_uHero[i].rt.right, m_uHero[i].rt.bottom); StringCchLength(ttt, 100, &size); SetTextColor(m_Base.dc, RGB(0, 0, 0)); TextOut(m_Base.dc, 80, 80 + i * 20, ttt, (int)size); } } void Game::DrawScore(HDC hdc) { WCHAR ttt[100]; size_t size; wsprintf(ttt, L"SCORE : %d", m_nScore); StringCchLength(ttt, 100, &size); SetBkMode(m_Base.dc, TRANSPARENT); SetTextColor(m_Base.dc, RGB(0, 0, 0)); TextOut(m_Base.dc, 10, 10, ttt, (int)size); SetTextColor(m_Base.dc, RGB(255, 255, 255)); TextOut(m_Base.dc, 9, 9, ttt, (int)size); if (m_nHeroHealth == 4) { TransparentBlt(m_Base.dc, 50, YRES - 100, 90, 35, m_Score.dc, 90 * 0, 0, 90, 35, RGB(255, 255, 255)); } else if (m_nHeroHealth == 3) { TransparentBlt(m_Base.dc, 50, YRES - 100, 90, 35, m_Score.dc, 90 * 1, 0, 90, 35, RGB(255, 255, 255)); } else if (m_nHeroHealth == 2) { TransparentBlt(m_Base.dc, 50, YRES - 100, 90, 35, m_Score.dc, 90 * 2, 0, 90, 35, RGB(255, 255, 255)); } else if (m_nHeroHealth == 1) { TransparentBlt(m_Base.dc, 50, YRES - 100, 90, 35, m_Score.dc, 90 * 3, 0, 90, 35, RGB(255, 255, 255)); } } void Game::UpdateAll() { switch (m_StageNum) { case INTRO: //UpdatePress(); UpdateIntro(); break; case STAGE1: UpdateFade(); if (m_Scene == Playing) { UpdateEnemy1(); UpdateHeroBullet(); UpdateStage1(); MoveHeroBullet(); UpdateHero(); UpdateHeroBulletExplode(); UpdateEnemy1Bullet(); UpdateEnemy1BulletExplode(); MoveEnemy1Bullet(); } break; case STAGE2: UpdateFade(); //if (m_Scene == Playing) { UpdateEnemy2(); UpdateHeroBullet(); UpdateStage1(); MoveHeroBullet(); UpdateHero(); UpdateHeroBulletExplode(); UpdateEnemy1Bullet(); UpdateEnemy1BulletExplode(); MoveEnemy1Bullet(); } break; case CLEAR: break; case GAME_OVER: break; default: break; } //UpdateDebug(); UpdateFX(); } void Game::UpdateHero() { FramePlus(m_uHero[m_HeroState], 100); //MoveKey(m_uHero[m_HeroState], 50, 10); } void Game::UpdateHeroBullet() { for (int i = 0; i < HEROBULLETNUM; i++) { FramePlus(m_uHeroBullet[i], 100); } } void Game::MoveHeroBullet() { for (int i = 0; i < HEROBULLETNUM; i++) { m_uHeroBullet[i].aEndTick = GetTickCount(); // 프로그램실행훈 1000분에 1초로 tick을 세고있음 if (m_uHeroBullet[i].aEndTick - m_uHeroBullet[i].aStartTick > 10) // (프로그램실행부터 현재까지의 tick - 새로운 tick) 이 100보다 크다면 { m_uHeroBullet[i].aStartTick = m_uHeroBullet[i].aEndTick; // 새로운 tick if (m_uHeroBullet[i].bTrigger == true) { m_uHeroBullet[i].rt.top -= 10; m_uHeroBullet[i].rt.bottom -= 10; AttariCheck(); } if (m_uHeroBullet[i].rt.bottom < 0)//화면을벗어나는순간 { InitHeroBullet(i); //초기화 m_uHeroBullet[i].bTrigger = FALSE; //안쏜걸로 세팅 //DrawEnemy1BulletExplode(m_uHeroBullet[i].rt.left, m_uHeroBullet[i].rt.top); DrawEnemy1BulletExplode(); //m_uHeroBullet[i].test++; } } } } void Game::UpdateEnemy1() { FramePlus(m_uEnemy1[m_EnemyState], 103); } void Game::UpdateEnemy2() { FramePlus(m_uEnemy2[m_EnemyState], 103); } void Game::UpdateHeroBulletExplode() { if (m_uHeroBulletExplode.bTrigger == FALSE) return; FramePlus(m_uHeroBulletExplode, 100); if (UpdateCheck(m_uHeroBulletExplode, 150) == TRUE) { m_uHeroBulletExplode.frame++; if (m_uHeroBulletExplode.frame > m_uHeroBulletExplode.MaxFrame) { m_uHeroBulletExplode.frame = 0; m_uHeroBulletExplode.bTrigger = FALSE; } } } void Game::UpdateEnemy1BulletExplode() { //if (m_uEnemy1BulletExplode.bTrigger == FALSE) return; FramePlus(m_uEnemy1BulletExplode[0], 100); if (UpdateCheck(m_uEnemy1BulletExplode[0], 150) == TRUE) { m_uEnemy1BulletExplode[0].frame++; if (m_uEnemy1BulletExplode[0].frame > m_uEnemy1BulletExplode[0].MaxFrame) { m_uEnemy1BulletExplode[0].frame = 0; m_uEnemy1BulletExplode[0].bTrigger = FALSE; //m_uEnemy1BulletExplode[0].test++; } } } void Game::UpdateEnemy1Bullet() { for (int i = 0; i < ENEMYBULLETNUM; i++) { m_uEnemy1Bullet[i].aEndTick = GetTickCount(); if (m_uEnemy1Bullet[i].aEndTick - m_uEnemy1Bullet[i].aStartTick > 100) { m_uEnemy1Bullet[i].aStartTick = m_uEnemy1Bullet[i].aEndTick; m_uEnemy1Bullet[i].frame++; if (m_uEnemy1Bullet[i].frame >= m_uEnemy1Bullet[i].MaxFrame) { m_uEnemy1Bullet[i].frame = 0; } } } } void Game::MoveEnemy1Bullet() { for (int i = 0; i < ENEMYBULLETNUM; i++) { m_uEnemy1Bullet[i].bEndTick = GetTickCount(); // 프로그램실행훈 1000분에 1초로 tick을 세고있음 if (m_uEnemy1Bullet[i].bEndTick - m_uEnemy1Bullet[i].bStartTick > 30) // (프로그램실행부터 현재까지의 tick - 새로운 tick) 이 100보다 크다면 { m_uEnemy1Bullet[i].bStartTick = m_uEnemy1Bullet[i].bEndTick; // 새로운 tick m_uEnemy1Bullet[i].rt.top += 10; m_uEnemy1Bullet[i].rt.bottom += 10; AttariCheck(); if (m_uEnemy1Bullet[i].rt.top > YRES)//화면을벗어나는순간 { InitEnemy1Bullet(i); //초기화 m_uEnemy1Bullet[i].bTrigger = FALSE; //안쏜걸로 세팅 } } } } void Game::UpdateIntro() { FramePlus(m_uIntro,120); } void Game::UpdateStage1() { xPlus(m_uStage1[0], 1,1); //sFramePlus(m_uStage1[0],10); } void Game::UpdateFade() { FramePlus(m_uFade, 125); if (m_Fade.bf.SourceConstantAlpha > 0) { if (UpdateCheck(m_uFade, 10) == TRUE) { m_Fade.bf.SourceConstantAlpha -=1; if (m_Fade.bf.SourceConstantAlpha == 0) m_Scene = Playing; return; //m_Fade.bf.SourceConstantAlpha = 0; } } } void Game::UpdateFX() { FramePlus(m_uFX, 125); //if (m_FX.bf.SourceConstantAlpha > 0) //{ // if (UpdateCheck(m_uFX, 10) == TRUE) // { // m_FX.bf.SourceConstantAlpha -= 1; // if (m_FX.bf.SourceConstantAlpha == 0) // m_Scene = Playing; // return; // } //} } void Game::AttariCheck() { POINT pt; for (int i = 0; i < HEROBULLETNUM; i++) //히어로총알 vs 적 { pt.x = m_uHeroBullet[i].rt.left; pt.y = m_uHeroBullet[i].rt.top+200; //피격됨 if (PtInRect(&m_uEnemy1[0].rt, pt) != FALSE) { InitHeroBullet(i);//총알초기화 m_uHeroBullet[i].bTrigger = FALSE; m_nScore += 100; m_uHeroBulletExplode.bTrigger = TRUE; //폭발 이펙트 활성화 if (m_nScore >= Enemy1_HEALTH) { m_StageNum = STAGE2; m_EnemyState = Enemy2_Intro; m_uClear.aEndTick = GetTickCount(); m_uClear.aStartTick = m_uClear.aEndTick; //스테이지끝나면 초기화 해야될것 은 updateclear에서 } if (m_nScore >= Enemy2_HEALTH) { m_StageNum = CLEAR; } } } for (int i = 0; i < ENEMYBULLETNUM; i++) //적총알 vs 히어로 { RECT rcTemp; //피격됨 //if (PtInRect(&m_uHero[0].rt, pt) != FALSE) if (IntersectRect(&rcTemp, &m_uHero[0].rt, &m_uEnemy1Bullet[i].rt) != FALSE) { m_uEnemy1BulletExplode[0].bTrigger = TRUE; //폭발 이펙트 활성화 m_uEnemy1BulletExplode[0].rt.left = m_uEnemy1Bullet[i].rt.left; m_uEnemy1BulletExplode[0].rt.top = m_uEnemy1Bullet[i].rt.top; m_nHeroHit += 1; m_nHeroHealth -= 1; m_uEnemy1BulletExplode[0].test++; //DrawEnemy1BulletExplode(m_uEnemy1Bullet[i].rt.left, m_uEnemy1Bullet[i].rt.top); //DrawEnemy1BulletExplode(m_uHero[0].rt.left, m_uHero[0].rt.top); DrawEnemy1BulletExplode(); m_uHeroBullet[i].rt.top += 10; m_uHeroBullet[i].rt.bottom += 10; if (UpdateCheck(m_uHeroBullet[i], 1000) == true) { m_uHeroBullet[i].rt.top -= 10; m_uHeroBullet[i].rt.bottom -= 10; } if (m_nHeroHealth < 1) { m_StageNum = GAME_OVER; //스테이지끝나면 초기화 해야될것 은 updateclear에서 } InitEnemy1Bullet(i);//총알초기화 } } } void Game::UpdatePress() { m_uPress.mEndTick = GetTickCount(); if (m_uPress.mEndTick - m_uPress.mStartTick > 500) { m_uPress.mStartTick = m_uPress.mEndTick; m_uPress.bTrigger = !m_uPress.bTrigger; // true, false 반복되도록 } } bool Game::UpdateCheck(UPDATE & up, unsigned int tick) { up.aEndTick = GetTickCount(); if (up.aEndTick - up.aStartTick > tick) { up.aStartTick = up.aEndTick; return true; } return false; } void Game::FramePlus(UPDATE& update,int tick) { update.mEndTick = GetTickCount(); if (update.mEndTick - update.mStartTick > tick) { update.mStartTick = update.mEndTick; update.frame++; if (update.frame > update.MaxFrame) { update.frame = 0; } } } void Game::xPlus(UPDATE & update, int tick, int n) { update.mEndTick = GetTickCount(); if (update.mEndTick - update.mStartTick > tick) { update.mStartTick = update.mEndTick; update.pt.x += n; if (update.pt.x > XFILE) { update.pt.x = 0; } } } void Game::MoveKey(UPDATE & update, int tick, int n) { if ((GetAsyncKeyState(VK_RIGHT) & 0x8000)&& m_uHero[0].rt.right <= XRES) { m_HeroState = RunRight; xPlusAni(update, tick, n); /*m_uHeroBullet[0].bEndTick = GetTickCount(); if (m_uHeroBullet[0].bEndTick - m_uHeroBullet[0].bStartTick > 10) { m_uHeroBullet[0].bStartTick = m_uHeroBullet[0].bEndTick; m_uStage1[2].pt.x += 1; }*/ } else if (m_HeroState == RunRight) { m_HeroState = IdleRight; } if ((GetAsyncKeyState(VK_LEFT) & 0x8000) && m_uHero[0].rt.left > 0) { m_HeroState = RunLeft; xPlusAni(update, tick, -n); /*m_uHeroBullet[0].bEndTick = GetTickCount(); if (m_uHeroBullet[0].bEndTick - m_uHeroBullet[0].bStartTick > 10) { m_uHeroBullet[0].bStartTick = m_uHeroBullet[0].bEndTick; m_uStage1[2].pt.x -= 1; }*/ } else if (m_HeroState == RunLeft) { m_HeroState = IdleLeft; } if (GetAsyncKeyState(VK_SPACE) & 0x8001 && ((m_HeroState == IdleRight) || (m_HeroState == RunRight) || (m_HeroState == ShootRight))) { m_HeroState = ShootRight; m_uHeroBullet[0].bEndTick = GetTickCount(); if (m_uHeroBullet[0].bEndTick - m_uHeroBullet[0].bStartTick > tick) { m_uHeroBullet[0].bStartTick = m_uHeroBullet[0].bEndTick; for (int i = 0; i < HEROBULLETNUM; i++) { if (m_uHeroBullet[i].bTrigger == FALSE) { InitHeroBullet(i); m_uHeroBullet[i].bTrigger = TRUE; break; } } } } if (GetAsyncKeyState(VK_SPACE) & 0x8001 && ((m_HeroState == IdleLeft) || (m_HeroState == RunLeft) || (m_HeroState == ShootLeft))) { m_HeroState = ShootLeft; m_uHeroBullet[0].aEndTick = GetTickCount(); if (m_uHeroBullet[0].aEndTick - m_uHeroBullet[0].aStartTick > tick) { m_uHeroBullet[0].aStartTick = m_uHeroBullet[0].aEndTick; for (int i = 0; i < HEROBULLETNUM; i++) { if (m_uHeroBullet[i].bTrigger == FALSE) { InitHeroBullet(i); m_uHeroBullet[i].bTrigger = TRUE; break; } } } } //else if (m_HeroState == ShootRight) //{ // m_HeroState = IdleRight; //} /*if (GetAsyncKeyState(VK_SPACE) & 0x8000 && ((m_HeroState == IdleLeft) || (m_HeroState == RunLeft))) { m_uPress.mEndTick = GetTickCount(); if (m_uPress.mEndTick - m_uPress.mStartTick > 500) { m_uPress.mStartTick = m_uPress.mEndTick; m_HeroState = ShootLeft; for (int i = 0; i < HEROBULLETNUM; i++) { if (m_uHeroBullet[i].bTrigger == false) { InitHeroBullet(i); m_uHeroBullet[i].bTrigger = true; break; } } } }*/ //else if (m_HeroState == ShootLeft) //{ // m_HeroState = IdleLeft; //} } void Game::xPlusAni(UPDATE & update, int tick, int n) { update.aEndTick = GetTickCount(); if (update.aEndTick - update.aStartTick > tick) { update.aStartTick = update.aEndTick; update.rt.left += n; update.rt.right += n; if (update.frame > update.MaxFrame) { update.frame = 0; } } } void Game::PlusBullet(UPDATE & update, int tick, int n) { update.aEndTick = GetTickCount(); if (update.aEndTick - update.aStartTick > tick) { update.aStartTick = update.aEndTick; for (int i = 0; i < HEROBULLETNUM; i++) { if (update.bTrigger == false) { InitHeroBullet(i); update.bTrigger = true; break; } } } } void Game::SetDebug() { // TODO: 여기에 구현 코드 추가. m_bDebug = !m_bDebug; }
[ "lkjfrf@naver.com" ]
lkjfrf@naver.com
e6de4d58137a789b304677b460e2e4b16602ba68
14541a9f2cef091b474677fb9c3baf4ef3a315d0
/ewsclient/ewsattendee.h
54c8d2b47852e208edde15a88ac6b140ed983f01
[]
no_license
StefanBruens/akonadi-ews
45f5b75445c16b9e3a26cd35900212a41663acb4
05ce7e24547fbdb559de55dabda86d337716cfba
refs/heads/master
2021-01-21T23:23:27.304824
2017-10-04T07:52:29
2017-10-04T07:52:29
95,236,655
0
0
null
2017-06-23T16:20:49
2017-06-23T16:20:49
null
UTF-8
C++
false
false
1,736
h
/* This file is part of Akonadi EWS Resource Copyright (C) 2015-2016 Krzysztof Nowicki <krissn@op.pl> This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef EWSATTENDEE_H #define EWSATTENDEE_H #include <QDateTime> #include <QMetaType> #include <QSharedDataPointer> #include "ewstypes.h" class EwsAttendeePrivate; class EwsMailbox; class QXmlStreamReader; class EwsAttendee { public: typedef QList<EwsAttendee> List; EwsAttendee(); explicit EwsAttendee(QXmlStreamReader &reader); EwsAttendee(const EwsAttendee &other); EwsAttendee(EwsAttendee &&other); virtual ~EwsAttendee(); EwsAttendee& operator=(const EwsAttendee &other); EwsAttendee& operator=(EwsAttendee &&other); bool isValid() const; const EwsMailbox &mailbox() const; EwsEventResponseType response() const; QDateTime responseTime() const; protected: QSharedDataPointer<EwsAttendeePrivate> d; }; Q_DECLARE_METATYPE(EwsAttendee) Q_DECLARE_METATYPE(EwsAttendee::List) #endif
[ "krissn@op.pl" ]
krissn@op.pl
2b7699f5dc9246e549ac38dde785259dbc4661e4
44e7a328c6927be55370afe1b72baa3d00a59706
/LightningUI/GUI/Media/SndPlayer.h
f98e54f326ca39c3b6d71620cc349a2a6ae884f2
[]
no_license
layerfsd/lightningUI
0c8ad327112f232483f80dc5e94cb59776fc787f
1495cfa270d7f6cc7fa44bd46c85961047d4b8b5
refs/heads/master
2020-03-28T15:14:47.114756
2017-07-22T04:14:17
2017-07-22T04:14:17
148,571,261
1
0
null
2018-09-13T02:37:07
2018-09-13T02:37:07
null
UTF-8
C++
false
false
695
h
#pragma once #include "../../stdafx.h" #include "../Common/ui_common.h" #include <CSRMedia.h> class CSndPlayer { public: CSndPlayer(HINSTANCE hIns, ICSRMedia* media, const wchar_t *filename, BOOL bLoop, DWORD dwWaveId, DWORD dwVol); ~CSndPlayer(void); void start(); void stop(); private: static DWORD playThreadPro(LPVOID lpParam); static LRESULT CALLBACK notifyWndProc(HWND, UINT, WPARAM, LPARAM); HRESULT OnPlayerMsg(WPARAM wParam, LPARAM lParam); private: HWND m_hNotifyWnd; ICSRMedia* m_pCSRMedia ; ICSRPlayer* m_pPlayer ; ICSREventSource* m_pEvent ; ICSRWaveoutAudio* m_pAudio; BOOL m_bPlaying; BOOL m_bLoop; DWORD m_dwVol; DWORD m_dwWavID; CM_String m_strFile; };
[ "949926851@qq.com" ]
949926851@qq.com
9834f7f55e9f468647c55651af840af9f9744e0f
cc63948f2d200ac454d210d2f156f7b4885c62f7
/scheduler/fork/test_2/testdir_5/test_5.cpp
b5275e8055f83daa583ff6881f782f5eef3f905f
[]
no_license
Top-jia/http_file_server
8d42a0c0d7340a1f977e4fe0c1e04c699e041caf
b0ca68fa28dd762142991d3e3031d796b38128ee
refs/heads/master
2021-06-13T06:00:36.295477
2021-02-25T18:30:28
2021-02-25T18:30:28
137,880,764
0
0
null
null
null
null
UTF-8
C++
false
false
11,622
cpp
#include<iostream> #include<string.h> #include<stdio.h> #include<assert.h> #include<unistd.h> #include<stdlib.h> #include<sys/types.h> #include<sys/socket.h> #include<arpa/inet.h> #include<netinet/in.h> #include<errno.h> #include<sys/wait.h> #include<fcntl.h> #include<sys/stat.h> #include<stdbool.h> #include<libgen.h> #include<signal.h> #include<bits/signum.h> #include<bits/sigset.h> #include<sys/epoll.h> #define BUFF_SIZE 127 #define MAX_EVENT_NUM 1024 /*父进程用于和父进程信号通信的文件描述符*/ int parent_sig_read_fd = 0; int parent_sig_write_fd = 0; int user_count = 0; #define MAX_PROCCESS 5 /*创建socket协议族 */ int create_socket(){ const char *ip = "127.0.0.1"; const int port = 7900; struct sockaddr_in server; bzero(&server, sizeof(server)); server.sin_family = AF_INET; inet_pton(AF_INET, ip, &server.sin_addr); server.sin_port = htons(port); int sockfd = socket(AF_INET, SOCK_STREAM, 0); if(sockfd == -1){ fprintf(stderr, "create_socket() failure errno = %d str_err = %s\n", errno, strerror(errno)); exit(EXIT_FAILURE); } int reuse = -1; int err = setsockopt(sockfd, SOCK_STREAM, SO_REUSEADDR, &reuse, sizeof(reuse)); if(err == -1){ fprintf(stderr, "setsockopt() failure errno = %d, str_err = %s\n", errno, strerror(errno)); exit(EXIT_FAILURE); } int binder = bind(sockfd, (struct sockaddr*)&server, sizeof(struct sockaddr_in)); if(binder == -1){ fprintf(stderr, "bind() failure errno = %d, str_err = %s\n", errno, strerror(errno)); exit(EXIT_FAILURE); } binder = listen(sockfd, 5); if(binder == -1){ fprintf(stderr, "listen() failure errno = %d std_err = %s\n", errno, strerror(errno)); exit(EXIT_FAILURE); } return sockfd; } /*设置信号处理函数, 给管道中写入每一个信号值*/ void sig_handler(int signum){ int err = errno; int msg = signum; printf("pid = %d catch signum = %d, str_sig = %s\n", getpid(), signum, strsignal(signum)); send(parent_sig_write_fd, (char*)&msg, 1, 0); if(errno == EBADF){ printf("子进程pid = %d, send--fd failure\n", getpid()); } errno = err; } /*设置对信号处理的类*/ class Signal{ int *sockpair; public: /*构造信号类, 并创建双端管道用于, 将信号事件作为统一事件源的一种来处理*/ Signal():sockpair(NULL){ sockpair = new int[2]; int err = socketpair(PF_UNIX, SOCK_STREAM, 0, sockpair); if(err == -1){ fprintf(stderr, "socketpair() failure errno = %d std_err = %s\n", errno, strerror(errno)); exit(EXIT_FAILURE); } } /*释放创建管道文件的描述符*/ ~Signal(){ delete[] sockpair; } /*对于描述符分为读端和写端, sockpair[0]作为写端, sockpair[1]作为读端*/ int getsockpair_read(){ return sockpair[1]; } /*对于描述符分为读端和写端, sockpair[0]作为写端, sockpair[1]作为读端*/ int getsockpair_write(){ return sockpair[0]; } /*增加信号,(就是对一些信号处理函数进行按照自己的方式重写) * 例如 SIGINT ctrl+C来进行控制的. * */ void addsig(int signum){ struct sigaction sa; memset(&sa, '\0', sizeof(sa)); sa.sa_handler = sig_handler; sa.sa_flags |= SA_RESTART; //支持阻塞的系统调用, 被信号中断后, 可以重新恢复 int err = sigfillset(&sa.sa_mask); if(err == -1){ fprintf(stderr, "Signal::addsig()--sigfillset() failure errno = %d, str_err = %s", errno, strerror(errno)); exit(EXIT_FAILURE); } err = sigaction(signum, &sa, NULL); if(err == -1){ fprintf(stderr, "Signal::addsig()--sigaction() failure errno = %d, str_err = %s", errno, strerror(errno)); exit(EXIT_FAILURE); } } /* * 对于某个信号恢复其默认值(默认行为) * */ void delsig(int signum){ struct sigaction sa; memset(&sa, '\0', sizeof(sa)); //sa.sa_flags |= SA_RESTART; sa.sa_handler = SIG_DFL; int err = sigfillset(&sa.sa_mask); if(err == -1){ fprintf(stderr, "Signal::delsig()--sigfillset() failure errno = %d, str_err = %s", errno, strerror(errno)); } err = sigaction(signum, &sa, NULL); if(err == -1){ fprintf(stderr, "Signal::addsig()--sigaction() failure errno = %d, str_err = %s", errno, strerror(errno)); exit(EXIT_FAILURE); } } }; /*封装Epoll来处理事件*/ class Epoll{ int epoll_fd; public: /*初始化Epoll构造函数*/ Epoll(){ epoll_fd = epoll_create(5); if(epoll_fd == -1){ fprintf(stderr, "Epoll::Epoll()--epoll_create() failure errno = %d, str_err = %s", errno, strerror(errno)); exit(EXIT_FAILURE); } } /*析构函数*/ ~Epoll(){ } /*设置非阻塞模式*/ static void setnonblocking(int fd){ if(fd <= 0){ fprintf(stderr, "Epoll:setnonblocking() failure in args"); exit(EXIT_FAILURE); } int old_option = fcntl(fd, F_GETFL); if(old_option == -1){ fprintf(stderr, "Epoll::setnonblocking() failure errno = %d, str_err = %s", errno, strerror(errno)); exit(EXIT_FAILURE); } int new_option = old_option | O_NONBLOCK; int err = fcntl(fd, F_SETFL, new_option); if(err == -1){ fprintf(stderr, "Epoll::setnonblocking() failure errno = %d, str_er = %s", errno, strerror(errno)); exit(EXIT_FAILURE); } } /*增加文件描述符*/ void addfd(int fd, struct epoll_event *event = NULL){ if(fd <= 0){ fprintf(stderr, "Epoll::addfd() failure in args"); exit(EXIT_FAILURE); } if(event == NULL){ struct epoll_event event; bzero(&event, sizeof(struct epoll_event)); event.data.fd = fd; event.events = EPOLLIN | EPOLLRDHUP; int err = epoll_ctl(epoll_fd, EPOLL_CTL_ADD, fd, &event); if(err == -1){ fprintf(stderr, "Epoll::addfd()--epoll_ctl() failure errno = %d, str_err = %s", errno, strerror(errno)); exit(EXIT_FAILURE); } } else{ int err = epoll_ctl(epoll_fd, EPOLL_CTL_ADD, fd, event); if(err == -1){ fprintf(stderr, "Epoll::addfd()--epoll_ctl() failure errno = %d, str_err = %s", errno, strerror(errno)); exit(EXIT_FAILURE); } } } /*修改描述符fd*/ void modfd(int fd, struct epoll_event *event){ if(fd <= 0 || event == NULL){ fprintf(stderr, "Epoll::modfd() failure in args"); exit(EXIT_FAILURE); } int err = epoll_ctl(epoll_fd, EPOLL_CTL_MOD, fd, event); if(err == -1){ fprintf(stderr, "Epoll::modfd() failure errno = %d str_err = %s", errno, strerror(errno)); exit(EXIT_FAILURE); } } /*删除描述符fd*/ void delfd(int fd){ if(fd <= 0){ fprintf(stderr, "Epoll::delfd() failure in args"); exit(EXIT_FAILURE); } int err = epoll_ctl(epoll_fd, EPOLL_CTL_DEL, fd, NULL); if(err == -1){ fprintf(stderr, "Epoll::delfd()--epoll_ctl() failure in args"); exit(EXIT_FAILURE); } } /*获得epoll_fd内核事件文件描述符的fd*/ int getfd(){ return epoll_fd; } }; /*设置处理信号的类, 并且为处理数据 * 接口留下, 先完成信号的测试 * */ class Pdata{ Epoll &epoll_info; int sockfd; int parent_sig_read_fd; struct epoll_event events[MAX_EVENT_NUM]; public: /*初始化相关的数据和结构*/ Pdata(Epoll &epollinfo, int _sockfd, int sig_pipe):\ epoll_info(epollinfo), sockfd(_sockfd), parent_sig_read_fd(sig_pipe){ bzero(&events, sizeof(struct epoll_event) * MAX_EVENT_NUM); } /*主要运行的函数*/ void run(){ while(true){ int epoll_return = epoll_wait(epoll_info.getfd(), events, MAX_EVENT_NUM, -1); if(epoll_return <= 0 && errno != EINTR){ fprintf(stderr, "Pdata::run()--epoll_wait() failure errno = %d str_err = %s", errno, strerror(errno)); exit(EXIT_FAILURE); } else{ for(int i = 0; i < epoll_return; i++){ int fd = events[i].data.fd; /*有请求连接的事件到来*/ if(fd == sockfd){ accept_link(fd); } /*监控信号的事件文件描述符, 有事件触发*/ else if(fd == parent_sig_read_fd){ deal_sig_pipe(fd); } else{ printf("otherthing happened\n"); continue; } } } } } /*有连接事件到来*/ void accept_link(int fd){ if(fd <= 0){ fprintf(stderr, "Pdata::accept_link() failure in args"); exit(EXIT_FAILURE); } struct sockaddr_in client; socklen_t socklen = sizeof(client); bzero(&client, socklen); int accept_fd = accept(fd, (struct sockaddr*)&client, &socklen); if(accept_fd == -1){ fprintf(stderr, "Pdata::accept_link()--accept() failure errno = %d str_err = %s", errno, strerror(errno)); exit(EXIT_FAILURE); } /*如果连接用户过多的情况下*/ if(user_count >= MAX_PROCCESS){ const char *info = "too many users\n"; printf("%s", info); send(accept_fd, info, strlen(info), 0); close(accept_fd); return; } pid_t pid = fork(); if(pid < 0){ close(accept_fd); return; } /*子进程*/ else if(pid == 0){ epoll_info.~Epoll(); close(sockfd); close(parent_sig_read_fd); close(parent_sig_write_fd); run_child(accept_fd); exit(EXIT_SUCCESS); } /*父进程*/ else{ return; } } /*运行子进程的函数*/ void run_child(int fd){ if(fd <= 0){ fprintf(stderr, "Pdata::run_child() failure in args"); exit(EXIT_FAILURE); } char buffer[BUFF_SIZE]; Epoll::setnonblocking(fd); while(true){ memset(buffer, '\0', sizeof(char) * BUFF_SIZE); int recv_len = recv(fd, buffer, BUFF_SIZE, 0); if(recv_len == -1 && (errno != EAGAIN || errno != EWOULDBLOCK)){ printf("pid = %d Pdata::run_child()--recv() failure errno = %d str_err = %s\n", getpid(), errno, strerror(errno)); exit(EXIT_FAILURE); } else{ if(strlen(buffer) == 0){ continue; } printf("pid = %d recv_data = %s\n", getpid(), buffer); if(strncmp("end", buffer, 3) == 0){ close(fd); exit(EXIT_FAILURE); } send(fd, buffer, strlen(buffer), 0); memset(buffer, '\0', strlen(buffer)); } } } /*处理管道中的信号事件*/ void deal_sig_pipe(int sig_pipe_fd){ if(sig_pipe_fd <= 0){ fprintf(stderr, "Pdata::deal_sig_pipe() failure in args"); exit(EXIT_FAILURE); } char signal[BUFF_SIZE]; bzero(&signal, sizeof(char) * BUFF_SIZE); /*读取管道中触发了那些信号值*/ int ret = recv(sig_pipe_fd, signal, BUFF_SIZE - 1, 0); if(ret <= 0){ fprintf(stderr, "Pdata::deal_sig_pipe()--recv() failure errno = %d str_err = %s", errno, strerror(errno)); } else{ for(int i = 0; i < ret; i++){ switch(signal[i]){ case SIGCHLD: printf("SIGCHLD is trigger\n"); break; case SIGHUP: printf("SIGHUP is trigger\n"); break; case SIGQUIT: printf("SIGQUIT is trigger\n"); break; case SIGINT: printf("SIGINT is trigger\n"); break; case SIGTERM: printf("SIGTERM is trigger\n"); break; default : printf("default sig handler\n"); break; } } } } }; /*主函数*/ int main(){ int sockfd = create_socket(); Signal signal_set; parent_sig_read_fd = signal_set.getsockpair_read(); parent_sig_write_fd = signal_set.getsockpair_write(); Epoll epoll_info; epoll_info.setnonblocking(parent_sig_read_fd); epoll_info.addfd(parent_sig_read_fd); epoll_info.setnonblocking(sockfd); epoll_info.addfd(sockfd); /* * 对那些信号进行重新设计其回调函数 * strsignal(signum); //回复信号的字符串 * * SIGINT ctrl+c(中断进程) * SIGQUIT ctrl+\(键盘输入使进程退出) * SIGHUP ctrl+z(控制终端挂起) * SIGTERM kill杀死进程 * SIGCHLD 子进程状态发生变化 * */ signal_set.addsig(SIGINT); signal_set.addsig(SIGQUIT); signal_set.addsig(SIGHUP); signal_set.addsig(SIGTERM); signal_set.addsig(SIGCHLD); Pdata ddata(epoll_info, sockfd, parent_sig_read_fd); ddata.run(); return 0; }
[ "904957684@qq.com" ]
904957684@qq.com
da006877618d04939fa2d7c93ab59ecedc352bcb
d0848bcbdbd7764db256868b989b2e8cdb347cc3
/src/MiniTTHReader_MarkOwen_All_Classes/MiniTTHReader_MarkOwen_ZDD_all_ttDD_HFOR_COR_AvPTll_ttData_P0_0.0015.cxx
044df51582310881d3897cc11b6d479512ee26ee
[]
no_license
ampereira/lipminianalysis
361625f21e4fbb06955bfd4c9daa96f24a9f633d
3a1489274aa154e9c954a391da0ec5a5f5281b0c
refs/heads/master
2020-04-05T23:39:52.035515
2014-05-19T14:49:31
2014-05-19T14:49:31
null
0
0
null
null
null
null
UTF-8
C++
false
false
31,021
cxx
// ################################################################################# // // _ _ __ __ _ _ _ _ // | | (_) | \/ (_) (_) /\ | | (_) // | | _ _ __ | \ / |_ _ __ _ / \ _ __ __ _| |_ _ ___ _ ___ // | | | | '_ \ | |\/| | | '_ \| | / /\ \ | '_ \ / _` | | | | / __| / __| // | |____| | |_) | | | | | | | | | | / ____ \| | | | (_| | | |_| \__ \ \__ \ // |______|_| .__/ |_| |_|_|_| |_|_| /_/ \_\_| |_|\__,_|_|\__, |___/_|___/ // | | __/ | // |_| |___/ // // ################################################################################# // // TopD3PDMaker \ | | / | / | | || // '-___-+-+' |_/ | | | // by Antonio Onofre `--___-++--^'| | | /| // (antonio.onofre@cern.ch) || | | |' | // date: 23.Nov.2012 --___ || | | _/| | // ==---:-++___ | ___--+' | | // '--_'|'---'+--___ | | | // '+-_ | '-+__ | | // ._. ._. ._____ // | | | | | ___ \ // | |_. | | | .___/ // |___| |_| |_| // // Note: this code was built from classes developed by // Nuno Castro (nfcastro@lipc.fis.uc.pt) and // Filipe Veloso (fveloso@lipc.fis.uc.pt) // // // ################################################################################# #define MiniTTHReader_cxx #include "MiniTTHReader.h" #include <iostream> #include <iomanip> #include <fstream> #include <vector> #include <cmath> using std::cout ; using std::endl ; // ############################################################################# MiniTTHReader::MiniTTHReader(int i_isData) { // ############################################################################# // // Purpose: parameters and tools setting // // authors: fveloso // first version: 21.fev.2007 // // last change: 10.Nov.2012 // by: A.Onofre // // ############################################################################# // ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: // parameters // ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: FillPhotons = false; FillElectrons = true; FillJets = true; FillMuons = true; //i_isdata = 1, mc = 0, af2 = -1 if (i_isData == -1) { isData = 0; isAF2 = 1; } else { isData = i_isData; isAF2 = 0; } // AO 19 Nov 2012 ==== Make sure you are reading the right TChain (in this case a mini ntuple) tree = new TChain("mini"); // ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: // tool initialisation: // ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! // !!!!!!!! No tools are initialized in this class !!!!!!!!!!!!! // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! Init(); } // ############################################################################# MiniTTHReader::~MiniTTHReader() { // ############################################################################# // // Purpose: delete variables and make sure things are properly handled // // authors: fveloso // first version: 21.fev.2007 // // last change: 10.Nov.2012 // by: A.Onofre // // ############################################################################# delete tree; } // ############################################################################# void MiniTTHReader::Init() { // ############################################################################# // // Purpose: The Init() function is called when the selector needs to initialize // a new tree or chain. Typically here the branch addresses and branch // pointers of the tree will be set. // It is normaly not necessary to make changes to the generated // code, but the routine can be extended by the user if needed. // Init() will be called many times when running on PROOF // (once per file to be processed). // // authors: fveloso // first version: 21.fev.2007 // // last change: 10.Nov.2012 // by: A.Onofre // // ############################################################################# // Set object pointer // ======================================== // -- samor 9.Nov.2012 (following lines) -- // -- mini-ntuples leafs and branches -- // ======================================== // #include "Mini_MarkOwen_set_pointers.h" // #include "Mini_MarkOwen_TRCR12_01_07_set_pointers.h" #include "Mini_MarkOwen_TRCR14_00_03_set_pointers.h" // ======================================== // -- samor 9.Nov.2012 (above lines) -- // ======================================== // Set branch addresses and branch pointers if (!tree) return; fChain = tree; fCurrent = -1; fChain->SetMakeClass(1); // ======================================== // -- samor 9.Nov.2012 (following lines) -- // -- mini-ntuples leafs and branches -- // ======================================== // #include "Mini_MarkOwen_fChains.h" // #include "Mini_MarkOwen_TRCR12_01_07_fChains.h" #include "Mini_MarkOwen_TRCR14_00_03_fChains.h" // ======================================== // -- samor 9.Nov.2012 (above lines) -- // ======================================== Notify(); } // ############################################################################# void MiniTTHReader::Input(char *file){ // ############################################################################# // // purpose: open nTuple files // // authors: fveloso // first version: 21.fev.2007 // // last change: 10.Nov.2012 // by: A.Onofre // // ############################################################################# tree->Add(file); } // ############################################################################# Int_t MiniTTHReader::Isub() { // ############################################################################# // // Purpose: return data Run number or MC process number // // authors: fveloso // first version: 21.fev.2007 // // last change: 10.Nov.2012 // by: A.Onofre // // ############################################################################# if (isData) return runNumber; else return channelNumber; } // ############################################################################# Int_t MiniTTHReader::LumiBlock() { // ############################################################################# // // Purpose: return lumi block // // authors: fveloso // first version: 21.fev.2007 // // last change: 10.Nov.2012 // by: A.Onofre // // ############################################################################# int myLumi = -999; return myLumi; } // ############################################################################# Int_t MiniTTHReader::RunNumber() { // ############################################################################# // // Purpose: return run number // // authors: A.Onofre // first version: 14.nov.2012 // // last change: 14.Nov.2012 // by: A.Onofre // // ############################################################################# return runNumber; } // ############################################################################# Int_t MiniTTHReader::EveNumber() { // ############################################################################# // // Purpose: return event number // // authors: A.Onofre // first version: 14.nov.2012 // // last change: 14.Nov.2012 // by: A.Onofre // // ############################################################################# return eventNumber; } // ############################################################################# Int_t MiniTTHReader::TruthEleNumber() { // ############################################################################# // // Purpose: return number of TRUTH electrons // // authors: A.Onofre // first version: 14.nov.2012 // // last change: 14.Nov.2012 // by: A.Onofre // // ############################################################################# return truE; } // ############################################################################# Int_t MiniTTHReader::TruthMuonNumber() { // ############################################################################# // // Purpose: return number of TRUTH muons // // authors: A.Onofre // first version: 14.nov.2012 // // last change: 14.Nov.2012 // by: A.Onofre // // ############################################################################# return truM; } // ############################################################################# Int_t MiniTTHReader::ElectronTrigger() { // ############################################################################# // // Purpose: return electron trigger // // authors: fveloso // first version: 21.fev.2007 // // last change: 10.Nov.2012 // by: A.Onofre // // ############################################################################# int myTrigE = 0; if ( trigE != 0 ) myTrigE = 1; return myTrigE; } // ############################################################################# Int_t MiniTTHReader::MuonTrigger() { // ############################################################################# // // Purpose: return muon trigger // // authors: fveloso // first version: 21.fev.2007 // // last change: 10.Nov.2012 // by: A.Onofre // // ############################################################################# int myTrigM = 0; if ( trigM != 0 ) myTrigM = 1; return myTrigM; } // ############################################################################# Int_t MiniTTHReader::Cosmic() { // ############################################################################# // // Purpose: verify if event is a cosmic ray // ( Cosmic = 0, it IS NOT a cosmic event) // // authors: fveloso // first version: 21.fev.2007 // // last change: 10.Nov.2012 // by: A.Onofre // // ############################################################################# int isCosmic = 0; if ( cosmicEvent ) isCosmic = 1; return isCosmic; } // ############################################################################# Int_t MiniTTHReader::HforFlag() { // ############################################################################# // // Purpose: veto (special) events in case HF==4 // // authors: A.Onofre // first version: 21.Dec.2012 // // last change: 27.Dec.2012 // by: A.Onofre // // ############################################################################# return hfor; } // ############################################################################# Double_t MiniTTHReader::Ht_Mini() { // ############################################################################# // // Purpose: get Ht from Minintuple // // authors: A.Onofre // first version: 21.Dec.2012 // // last change: 30.Dec.2012 // by: A.Onofre // // ############################################################################# return ht; } // ############################################################################# Double_t MiniTTHReader::massInv_LL_Mini() { // ############################################################################# // // Purpose: get mLL from Minintuple // // authors: A.Onofre // first version: 21.Dec.2012 // // last change: 30.Dec.2012 // by: A.Onofre // // ############################################################################# return massInv_LL; } // ############################################################################# Int_t MiniTTHReader::jet_n_Mini() { // ############################################################################# // // Purpose: get number of jets from Minintuple // // authors: A.Onofre // first version: 21.Dec.2012 // // last change: 30.Dec.2012 // by: A.Onofre // // ############################################################################# return jet_n; } // ############################################################################# Int_t MiniTTHReader::EleMuoOverlap() { // ############################################################################# // // Purpose: check electron-muon overlap // ( EleMuoOverlap = 0, it is OK, no overlap) // // authors: fveloso // first version: 21.fev.2007 // // last change: 10.Nov.2012 // by: A.Onofre // // ############################################################################# int isEleMuoOverlap = 0; return isEleMuoOverlap; } // ############################################################################# Int_t MiniTTHReader::GoodRL() { // ############################################################################# // // Purpose: check event passed a goodrunlist // ( GoodRL = 1, it is OK) // // authors: A.Onofre // first version: 11.Nov.2012 // // last change: 11.Nov.2012 // by: A.Onofre // // ############################################################################# int myPassGRL = 0; if ( passGRL ) myPassGRL = 1; return myPassGRL; } // ############################################################################# Double_t MiniTTHReader::GeV() { // ############################################################################# double myGeV = 1000; return myGeV; } // ############################################################################# Double_t MiniTTHReader::MissPx() { // ############################################################################# // // Purpose: calculate missing Px // // authors: fveloso // first version: 21.fev.2007 // // last change: 10.Nov.2012 // by: A.Onofre // // ############################################################################# return met_et * cos(met_phi) / GeV(); } // ############################################################################# Double_t MiniTTHReader::MissPy() { // ############################################################################# // // Purpose: calculate missing Py // // authors: fveloso // first version: 21.fev.2007 // // last change: 10.Nov.2012 // by: A.Onofre // // ############################################################################# return met_et * sin(met_phi) / GeV(); } // ############################################################################# Double_t MiniTTHReader::MissPt() { // ############################################################################# // // Purpose: calculate missing Pt // // authors: fveloso // first version: 21.fev.2007 // // last change: 10.Nov.2012 // by: A.Onofre // // ############################################################################# return met_et; } // ############################################################################# Double_t MiniTTHReader::Sphericity() { // ############################################################################# return 0.; } // ############################################################################# Double_t MiniTTHReader::Aplanarity() { // ############################################################################# return 0.; } // ############################################################################# Double_t MiniTTHReader::Planarity() { // ############################################################################# return 0.; } // ############################################################################# Double_t MiniTTHReader::Weight() { // ############################################################################# // // Purpose: evaluate event weight. Implement here all scale factors // // authors: fveloso // first version: 21.fev.2007 // // last change: 10.Nov.2012 // by: A.Onofre // // ############################################################################# // ======================================== // Include Scale Factors Initializations // ======================================== // Z Scale Factors Applied #include "HforScale_FDS12GeV_3dist_OS_DD_Zee__Init_Built_Code.C" // Mass Scale Factors for |ll.M()-91|< 12GeV #include "PtScale_FDS12GeV_3dist_Zdata_fitLINE_OS_CONTROL_DD_Zee__Init_Built_Code.C" // pT Scale Factors for |ll.M()-91|< 12GeV // ttbar Scale Factors Applied #include "HforScale_FDS12GeV_OS_ttDD_ee__Init_Built_Code.C" // Rate Scale Factors (Data/Alpgen) #include "P0_0.0015/PtScale_ttData_AvPTll_fitLINE_OS_DD_ttee__Init_Built_Code.C" // Pt Scale Factors double myWeight = 0; if (isData) { myWeight = 1.; } else { // myWeight = mcWeight; // For MiniData Challenge ONLY // myWeight = eventWeight_PRETAG; // Use eventWeight_PRETAG if b-tag is NOT applied (assuming you trust b-tag scale factors) myWeight = eventWeight_BTAG; // Use eventWeight_BTAG if b-tag is applied (trusting b-tag scale factors) // ==================================================================== // ==================================================================== // Include Scale Factors Corrections // ==================================================================== // ==================================================================== // ---------------------------------------- // Z Boson Scale Factors // ---------------------------------------- if ( ( channelNumber >= 107650 && channelNumber <= 107655 ) || ( channelNumber >= 107660 && channelNumber <= 107665 ) || ( channelNumber >= 109300 && channelNumber <= 109308 ) || ( channelNumber >= 126414 && channelNumber <= 126421 ) ){ // Mass scale factors #include "HforScale_FDS12GeV_3dist_OS_DD_Zee__Fill_Built_Code.C" // Mass Scale Factors for |ll.M()-91|< 12GeV #include "HforScale_FDS12GeV_3dist_OS_DD_Zmm__Fill_Built_Code.C" // Pt scale factors #include "PtScale_FDS12GeV_3dist_Zdata_fitLINE_OS_CONTROL_DD_Zee__Fill_Built_Code.C" // pT Scale Factors for |ll.M()-91|< 12GeV #include "PtScale_FDS12GeV_3dist_Zdata_fitLINE_OS_CONTROL_DD_Zmm__Fill_Built_Code.C" } // ---------------------------------------- // ttbar Scale Factors // ---------------------------------------- if ( ( channelNumber >= 164440 && channelNumber <= 164443 ) || ( channelNumber >= 116108 && channelNumber <= 116109 ) ){ // ttbar Rate Scale Factors (Powheg/Alpgen) #include "HforScale_FDS12GeV_OS_ttDD_ee__Fill_Built_Code.C" #include "HforScale_FDS12GeV_OS_ttDD_em__Fill_Built_Code.C" #include "HforScale_FDS12GeV_OS_ttDD_mm__Fill_Built_Code.C" // ttbar Pt scale factors (Data/Alpgen) #include "P0_0.0015/PtScale_ttData_AvPTll_fitLINE_OS_DD_ttee__Fill_Built_Code.C" #include "P0_0.0015/PtScale_ttData_AvPTll_fitLINE_OS_DD_ttem__Fill_Built_Code.C" #include "P0_0.0015/PtScale_ttData_AvPTll_fitLINE_OS_DD_ttmm__Fill_Built_Code.C" } } return myWeight; } // ############################################################################# void MiniTTHReader::FillTruthVec(){ // ############################################################################# // // purpose: fill vectors of TLorentzVectors-with-index for truth particles // // authors: nfcastro, fveloso // first version: 30.???.?? // // last change: 10.Nov.2012 // by: A.Onofre // // ############################################################################# Truth0_El_N = 0; Truth0_Mu_N = 0; Truth0_Tau_N = 0; Truth0_nuEl_N = 0; Truth0_nuMu_N = 0; Truth0_nuTau_N = 0; Truth0_lepTau_N = 0; Truth0_elTau_N = 0; Truth0_muTau_N = 0; Truth0_Nu_El_N = 0; Truth0_Nu_Mu_N = 0; Truth0_Nu_Tau_N = 0; Truth0_El_k=-1; Truth0_Mu_k=-1; Truth0_Tau_k=-1; // ===== AO 8 Oct 2010 ===================== below ========= Int_t IST=0; //...particle status code //.................t ITQ=0; //...line for top quark IQ1=0; //...counter for top quark t.SetPtEtaPhiM(0., 0., 0., 0.); //.................tbar ITB=0; //...line for anti top quark IQ2=0; //...counter for anti top quark tb.SetPtEtaPhiM(0., 0., 0., 0.); //.................W+ IWP=0; //...line for W+ IW1=0; //...counter for W+ Wp.SetPtEtaPhiM(0., 0., 0., 0.); //.................W- IWN=0; //...line for W- IW2=0; //...counter for W- Wn.SetPtEtaPhiM(0., 0., 0., 0.); //.................b IBQ=0; //...line for b IB1=0; //...counter for bb b.SetPtEtaPhiM(0., 0., 0., 0.); //.................bb IBB=0; //...line for bb IB2=0; //...counter for bb bb.SetPtEtaPhiM(0., 0., 0., 0.); //.................s from t ISQ=0; //...line for s IS1=0; //...counter for s s.SetPtEtaPhiM(0., 0., 0., 0.); //.................sb from tbar ISB=0; //...line for sb IS2=0; //...counter for sb sb.SetPtEtaPhiM(0., 0., 0., 0.); //.................dw from t IDWQ=0; //...line for down IDW1=0; //...counter for down dw.SetPtEtaPhiM(0., 0., 0., 0.); //.................dwb from tbar IDWB=0; //...line for down bar IDW2=0; //...counter for down bar dwb.SetPtEtaPhiM(0., 0., 0., 0.); //.................W+->f1f2 IWPf1=0; //...line for f1 IWPf2=0; //...line for f2 IWPf1_Coun=0; //...counter for f1 IWPf2_Coun=0; //...counter for f2 IWPtau_Neu=0; //...counter for Tau Neutrinos IWPtau_elNeu=0; //...counter for ele Neutrinos (from tau decay) IWPtau_muNeu=0; //...counter for muo Neutrino (from tau decay) Wpf1.SetPtEtaPhiM(0., 0., 0., 0.); Wpf2.SetPtEtaPhiM(0., 0., 0., 0.); pdgID_Wp_dw=0; //...Code of 1st W+ Daughter pdgID_Wp_up=0; //...Code of 2nd W+ Daughter //.................W-->f1f2 IWNf1=0; //...line for f1 IWNf2=0; //...line for f2 IWNf1_Coun=0; //...counter for f1 IWNf2_Coun=0; //...counter for f2 IWNtau_Neu=0; //...counter for Tau Neutrinos IWNtau_elNeu=0; //...counter for ele Neutrinos (from tau decay) IWNtau_muNeu=0; //...counter for muo Neutrino (from tau decay) Wnf1.SetPtEtaPhiM(0., 0., 0., 0.); Wnf2.SetPtEtaPhiM(0., 0., 0., 0.); pdgID_Wn_dw=0; //...Code of 1st W- Daughter pdgID_Wn_up=0; //...Code of 2nd W- Daughter //.................Tau->lep // tru_id_leptauWp = 0; //...line of tau(W+)->mu+(e+) tru_id_leptauWn = 0; //...line of tau(W-)->mu-(e-) // // ===== AO 8 Oct 2010 ===================== above ========= TruthVec->clear(); } // ############################################################################# void MiniTTHReader::FillObjects() { // ############################################################################# // // WARNING: READ THE FOLLOWING LINES!!!!!! // purpose: although formelly this function was used to fill the // electrons and muons vectors, due to pratical reasons it is the // only function called: it fills (in this order) the electrons, // jets and muons vectors // // authors: nfcastro, fveloso // first version: ??.???.?? // // last change: 10.Nov.2012 // by: A.Onofre // // ############################################################################# // ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: // RecoType // ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: //RecoType = i_RecoType; PhRecoType = RecoType - RecoType/100*100; PhIsoCut = RecoType/100 - RecoType/10000*100; SystID = RecoType/10000 - RecoType/1000000*100; // reset output use_Photon_Vec.clear(); use_Electron_Vec.clear(); use_Muon_Vec.clear(); use_Jet_Vec.clear(); LeptonVec->clear(); JetVec->clear(); Vtx->clear(); // usefull variables jets25inevent=0; // auxiliar stuff Int_t kf = 0; TLorentzVector Good; Float_t etaCl; // :::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: // photons // :::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: // Loop over all photons, if any!!!! if (FillPhotons) { // for the moment do nothing!!! minintuples do not have information } // :::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: // electrons // :::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: //For 2011: https://twiki.cern.ch/twiki/bin/viewauth/AtlasProtected/TopCommonObjects2011#Electrons Double_t elpT, elEta, elPhi, elEne; Int_t elTruthMatch, elTrigMatch; //cout << " " << endl; // Loop over all electrons. if (FillElectrons) for (Int_t k=0; k<lep_n; ++k){ // ------------------------------check it is an electron if ( fabs(lep_type[k]) != 11 ) continue; // ------------------------------accept electron elpT = lep_pt[k]; elEta = lep_eta[k]; elPhi = lep_phi[k]; elEne = lep_E[k]; Good.SetPtEtaPhiE(elpT, elEta, elPhi, elEne); if ( lep_charge[k]>0 ) kf = -11; else kf = 11; // truth and trigger match elTruthMatch = 0; if ( lep_truthMatched[k] != 0 ) elTruthMatch = 1 ; elTrigMatch = 0; if ( lep_trigMatched[k] != 0 ) elTrigMatch = 1 ; // creat TLorentzWFlags vector TLorentzVectorWFlags GoodWFlags(Good, k, kf, 999., elTruthMatch, elTrigMatch); use_Electron_Vec.push_back(GoodWFlags); //cout << "%%%%%%% MiniTTHReader_MarkOwen %%%%%%% elTrigMatch " << elTrigMatch << " lep_type[k]: " << lep_type[k] << " lep_pt[k]: " << lep_pt[k] << endl; } // Fill Electrons done // :::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: // take vertex z information (assumed to be ok) // :::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: if( hasGoodVertex == 1 ){ // ------------------------------accept vertex TVector3 v( -999., -999., vxp_z); Vtx->push_back(v); } // :::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: // jets // :::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: // for jet energy scale and resolution uncertainties: Double_t jetET, jetpT, jetEta, jetPhi, jetEne; Int_t jetTruthMatch; // Loop over all jets if (FillJets) for (Int_t k=0; k<jet_n; ++k) { // ------------------------------if jets have MV1>0.795 if ( BTagCut != 999 && jet_MV1[k] > BTagCut ) kf = 5; else kf = 1; // ------------------------------accept jet jetpT = jet_pt[k]; jetEta = jet_eta[k]; jetPhi = jet_phi[k]; jetEne = jet_E[k]; Good.SetPtEtaPhiE(jetpT, jetEta, jetPhi, jetEne ); // truth and trigger match jetTruthMatch = 0; if ( jet_truthMatched[k] != 0 ) jetTruthMatch = 1 ; // creat TLorentzWFlags vector TLorentzVectorWFlags GoodWFlags(Good, k, kf, 999., jetTruthMatch, -1); use_Jet_Vec.push_back(GoodWFlags); } // Fill jets done // :::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: // muons // :::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: Double_t mupT, muEta, muPhi, muEne; Int_t muTruthMatch, muTrigMatch; // loop over all muons if (FillMuons) for (Int_t k=0; k<lep_n; ++k){ // ------------------------------check it is an electron if ( fabs(lep_type[k]) != 13 ) continue; // ------------------------------accept muon mupT = lep_pt[k]; muEta = lep_eta[k]; muPhi = lep_phi[k]; muEne = lep_E[k]; if ( lep_charge[k]>0 ) kf = -13; else kf = 13; Good.SetPtEtaPhiE(mupT, muEta, muPhi, muEne); // truth and trigger match muTruthMatch = 0; if ( lep_truthMatched[k] != 0 ) muTruthMatch = 1 ; muTrigMatch = 0; if ( lep_trigMatched[k] != 0 ) muTrigMatch = 1 ; // creat TLorentzWFlags vector TLorentzVectorWFlags GoodWFlags(Good, k, kf, 999., muTruthMatch, muTrigMatch); use_Muon_Vec.push_back(GoodWFlags); //cout << "%%%%%%% MiniTTHReader_MarkOwen %%%%%%% muTrigMatch " << muTrigMatch << " lep_type[k]: " << lep_type[k] << " lep_pt[k]: " << lep_pt[k] << endl; } // Fill muons done // :::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: // Fill objects // :::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: // Fill jets for (Int_t k=0; k< use_Jet_Vec.size(); ++k) { JetVec->push_back(use_Jet_Vec[k]); if ( use_Jet_Vec[k].Pt() > 25*GeV() ) jets25inevent++; } // Fill electrons for (Int_t k=0; k< use_Electron_Vec.size(); ++k) { LeptonVec->push_back(use_Electron_Vec[k]); } // Fill muons for (Int_t k=0; k< use_Muon_Vec.size(); ++k) { LeptonVec->push_back(use_Muon_Vec[k]); } /* for (Int_t k=0; k<lep_n; ++k){ cout << "%%%%%%% MiniTTHReader_MarkOwen --- lep_n --- lep_type[k]: " << lep_type[k] << " lep_trigMatched[k] " << lep_trigMatched[k] << " lep_pt[k]: " << lep_pt[k] << endl; } */ }
[ "lazeroth89@gmail.com" ]
lazeroth89@gmail.com
62387081c38c1536c4124c5aefb4733b6cb7864b
177a1cf48eb6f44dc3eabc640024d53bfea65033
/SevenWonders.cpp
cfd4bf944229a96cc37b84b9a048caf5d751a03d
[]
no_license
JakobKallestad/CKattis
7be3d14e8f8ac11786b24a3a8c8b2482de9d0f73
e96671d8784b3b8e2b8f92e9543f51b58e1f85b2
refs/heads/master
2020-05-27T18:11:01.746300
2019-07-07T17:16:24
2019-07-07T17:16:24
188,737,604
0
0
null
null
null
null
UTF-8
C++
false
false
463
cpp
// // Created by Jakob Kallestad on 2019-05-26. // #include <iostream> #include <string> using namespace std; int main() { string inp; cin >> inp; int t=0, c=0, g=0; for (auto i : inp) { if (i == 'T') { t++; } if (i == 'C') { c++; } if (i == 'G') { g++; } } int sum = (t*t) + (c*c) + (g*g) + min(t, min(g, c))*7; cout << sum << endl; return 0; }
[ "Jakob.Kallestad@student.uib.no" ]
Jakob.Kallestad@student.uib.no
d95bf6dac8eb5549e5c18a71dcf8c706be044bb8
a86b3ea1b273801eba8b5de7ecf145fb337807c3
/day03/Claim.h
cf536ccd17d473ef40528968fdda72e7d82bdfa1
[]
no_license
ahbonsu/advent-of-code
43f0b2e2fc0bb06e36088267de4501a59b59f68b
92ee497d9d4cda3731f5194800e7d0fd584ac0f3
refs/heads/master
2020-04-09T02:09:50.847398
2018-12-03T18:45:55
2018-12-03T18:45:55
159,930,685
0
0
null
null
null
null
UTF-8
C++
false
false
1,190
h
#ifndef CLAIM_H_INCLUDED #define CLAIM_H_INCLUDED class Claim { private: int _claim_id; int _x_offset; int _y_offset; int _x_length; int _y_length; public: Claim(int claim_id, int x_offset, int y_offset, int x_length, int y_length) { _claim_id = claim_id; _x_offset = x_offset; _y_offset = y_offset; _x_length = x_length; _y_length = y_length; } int get_claim_id() { return _claim_id; } int get_x_offset() { return _x_offset; } int get_y_offset() { return _y_offset; } int get_x_length() { return _x_length; } int get_y_length() { return _y_length; } }; std::ostream& operator<<(std::ostream &os, Claim& claim) { os << "id: " << claim.get_claim_id() << "; X-Offset: " << claim.get_x_offset() << "; Y-Offset: " << claim.get_y_offset() << "; X-Length: " << claim.get_x_length() << "; Y-Length: " << claim.get_y_length(); return os; } #endif // CLAIM_H_INCLUDED
[ "me@0x6168.ch" ]
me@0x6168.ch
47549794e0242403bac4aca18c4bcbf5f82affdb
f954dd8c0073f138b805bd1bd23d7839236d1514
/trunk/V300/369.cpp
3cd6dc866be5f2396f8c9a80846984c261968e35
[]
no_license
BGCX262/zwsoj-svn-to-git
4c68f0aaea879181e671c10a25ef471b57932bec
7d8f3e87db548d497147b594e789ec1882b08652
refs/heads/master
2021-01-22T09:20:25.466080
2015-08-23T06:54:09
2015-08-23T06:54:09
41,244,883
0
0
null
null
null
null
WINDOWS-1252
C++
false
false
671
cpp
/* @JUDGE_ID: 13160EW 369 C++ */ // nCr ªº°ÝÃD //@BEGIN_OF_SOURCE_CODE #include <iostream> using namespace std; typedef unsigned long ULONG; const int size = 300; ULONG board[size]; ULONG find(ULONG m,ULONG n) { ULONG i,j; if( n==0 ) return 1; if( n==1) return m; for(i=0;i<=n;i++) board[i] = 1; for(i=0;i<m-n;i++) { for(j=1;j<=n;j++) board[j] = board[j]+board[j-1]; } return board[n]; } int main() { long int m,n; while(1) { cin >> m >> n; if( m == 0 && n==0 ) break; cout << m << " things taken " << n << " at a time is " << find(m,n) << " exactly." << endl; } return 0; } //@END_OF_SOURCE_CODE
[ "you@example.com" ]
you@example.com
c91a81b8642a3827165cb3ce1c8ea332bad23160
7c9a37a4175759be24ba998bd8dfcb844adc39df
/LaRinascenteApp/src/Main/SettingsManager.h
8ae3a8e3892c48afb686c292123097df76fd9ce3
[ "MIT" ]
permissive
ImanolGo/LaRinascente
5a0840e95b6fc879f07c30f7b2cc5ae74d528f6d
6086c51bbc6402e647f94090bef70816b2056657
refs/heads/master
2021-08-20T03:33:45.497326
2017-11-28T04:46:28
2017-11-28T04:46:28
111,727,687
0
0
null
null
null
null
UTF-8
C++
false
false
3,270
h
/* * SettingsManager.h * LaRinascenteApp * * Created by Imanol Gomez on 22/11/17. * */ #pragma once #include "Manager.h" //========================== class SettingsManager ============================== //============================================================================ /** \class SettingsManager SettingsManager.h * \brief Class managing the whole settings of the application * \details it reads from an xml settings file and provides access to the information */ typedef map<string,string> ResourcesPathMap; ///< defines a map of path attached to the resources name class SettingsManager: public Manager { public: static const string APPLICATION_SETTINGS_FILE_NAME; //! Destructor ~SettingsManager(); //! Constructor SettingsManager(); //! Compares two transition objects void setup(); const ResourcesPathMap& getTextureResourcesPath() const {return m_texturesPath;} const ResourcesPathMap& getSvgResourcesPath() const {return m_svgResourcesPath;} const ResourcesPathMap& getVideoResourcesPath() const {return m_videoResourcesPath;} ofColor getColor(const string& colorName); float getAppWidth() const {return m_appWidth;} float getAppHeight() const {return m_appHeight;} string getIpAddress() const {return m_ipAddress;} int getOscPortReceive() const {return m_portOscReceive;} int getOscPortSend() const {return m_portOscSend;} private: //! Loads the settings file bool loadSettingsFile(); //! Loads all the settings void loadAllSettings(); //! Sets all the debug properties void setDebugProperties(); //! Sets all the network properties void setNetworkProperties(); //! Sets all the window properties void setWindowProperties(); //! Loads all the app colors void loadColors(); //! Loads all the textures settings void loadTextureSettings(); //! Loads all the svg images settings void loadSvgSettings(); //! Loads all the video settings void loadVideoSettings(); private: typedef map< string, ofPtr<ofColor> > ColorMap; ///< Defines a map of colors attached to a name ofXml m_xml; ///< instance of the xml parser ResourcesPathMap m_texturesPath; ///< stores the texture paths ResourcesPathMap m_svgResourcesPath; ///< stores the resources paths ResourcesPathMap m_videoResourcesPath; ///< stores the video paths ColorMap m_colors; ///< stores all the application's colors float m_appWidth; ///< stores the applications width float m_appHeight; ///< stores the applications height int m_portOscReceive; ///< stores the port to receive OSC messages from int m_portOscSend; ///< stores the port to send OSC messages to string m_ipAddress; ///< stores the Ip Address used for the Network communications };
[ "yo@imanolgomez.net" ]
yo@imanolgomez.net
1790d85978fba7ebf9da46635e855012f7e920b7
d84e689d4b587263f62e353e1da559d906056473
/subsecventaCaractere.cpp
3b99feb7a6db7b21ff053376773637cb179a494d
[]
no_license
cosminvoicu/LearnAlgoritms
2c4bc44d01edaae9a2851d39eef6d1e79068a215
1f71641d56d171c6d2943d33c770e15a86f10e52
refs/heads/master
2021-06-24T06:22:58.956608
2020-11-12T05:11:59
2020-11-12T05:11:59
156,120,051
0
0
null
null
null
null
UTF-8
C++
false
false
905
cpp
#include<iostream> #include<string> using namespace std; int main() { char s1[102],s2[102]; char * p; cin.getline(s1,101); cin.getline(s2,101); int lungimeS2 = 0, primulCaracter[1001], caractereConsecutive[1001], caractereC, iterator, validare = 0; for (int i = 0; s2[i]; ++i) { ++lungimeS2; } int j = -1; for ( int i = 0; s1[i]; ++i ) { if (s2[0] == s1[i]) primulCaracter[++j] = i; } for ( int k = 0; k<=j; ++k ) { caractereC = 0; iterator = 0; for ( int i = primulCaracter[k]; s1[i]; ++i) { if ( s2[iterator] == s1[i] ) { ++caractereC; } else { break; } ++iterator; } caractereConsecutive[k] = caractereC; } for ( int i = 0; i<=j; ++i) { if ( caractereConsecutive[i] == lungimeS2 ) { validare = 1; } } if ( validare ) { cout<<"DA"; } else { cout<<"NU"; } return 0; }
[ "voicu_cosmin95@yahoo.com" ]
voicu_cosmin95@yahoo.com
62f358874ac31f691a53781ca92208aa95148c4b
6f06a153a9f2ecaa8dd9b48ebc147508dee79829
/Postboxes/main.cpp
02dcfa543dcd24cf2b5e25e6a32ee6fae6b2b48a
[]
no_license
isobelm/Vision-postboxes
9e0cf074e465836612868bb80887abead39d67b4
a48297c47da45549bd37b53bc2d189d47f3edcba
refs/heads/master
2023-01-23T02:18:23.890831
2020-11-22T18:27:20
2020-11-22T18:27:20
314,039,039
0
0
null
null
null
null
WINDOWS-1252
C++
false
false
2,300
cpp
/* * This code is provided as part of "A Practical Introduction to Computer Vision with OpenCV" * by Kenneth Dawson-Howe © Wiley & Sons Inc. 2014. All rights reserved. */ #include "Utilities.h" #include <iostream> #include <fstream> #include <list> VideoCapture* postbox_video; int main(int argc, const char** argv) { Mat* image = new Mat(); string filename_img("Media/home.jpg"); *image = imread(filename_img, -1); if (image->empty()) { cout << "Could not open " << filename_img << endl; return -1; } const char* video_file = "Media/PostboxesWithLines.avi"; VideoCapture* postbox_video = new VideoCapture; string filename_vid(video_file); postbox_video->open(filename_vid); if (!postbox_video->isOpened()) { cout << "Cannot open video file: " << filename_vid << endl; // return -1; } //// Load Haar Cascade(s) //vector<CascadeClassifier> cascades; //char* cascade_files[] = { // "haarcascades/haarcascade_frontalface_alt.xml" }; //int number_of_cascades = sizeof(cascade_files) / sizeof(cascade_files[0]); //for (int cascade_file_no = 0; (cascade_file_no < number_of_cascades); cascade_file_no++) //{ // CascadeClassifier cascade; // string filename(file_location); // filename.append(cascade_files[cascade_file_no]); // if (!cascade.load(filename)) // { // cout << "Cannot load cascade file: " << filename << endl; // return -1; // } // else cascades.push_back(cascade); //} int line_step = 13; Point location(7, 13); Scalar colour(0, 0, 0); Mat default_image = ComputeDefaultImage(*image); putText(default_image, "OpenCV demonstration system from:", location, FONT_HERSHEY_SIMPLEX, 0.4, colour); location.y += line_step * 3 / 2; putText(default_image, "m. My Application", location, FONT_HERSHEY_SIMPLEX, 0.4, colour); location.y += line_step; putText(default_image, "X. eXit", location, FONT_HERSHEY_SIMPLEX, 0.4, colour); //Mat imageROI; //imageROI = default_image(cv::Rect(0, 0, default_image.cols, 245)); //addWeighted(imageROI, 2.5, imageROI, 0.0, 0.0, imageROI); int choice; do { imshow("Welcome", default_image); choice = cv::waitKey(); cv::destroyAllWindows(); switch (choice) { case 'm': MyApplication(*postbox_video); break; default: break; } } while ((choice != 'x') && (choice != 'X')); }
[ "isobel.mahon@gmail.com" ]
isobel.mahon@gmail.com
e01ed44cfd8645d12d8ee7fa1e149738496fc982
b40c7be7981f8dc0183792c5946c19e3c6fee8b9
/sql/common/ComDistribution.cpp
10910a9b642bcaee845f96446f3c7f33b962a708
[ "Apache-2.0" ]
permissive
jmhsieh/core
763530f55d41538ef7c0198e8bd1cc569f4a66e5
a13345b44f9bd9edae73cc8a2410f087ce3a75eb
refs/heads/master
2021-01-15T21:24:15.162737
2014-06-13T22:16:03
2014-06-13T22:16:03
null
0
0
null
null
null
null
UTF-8
C++
false
false
12,182
cpp
/********************************************************************** // @@@ START COPYRIGHT @@@ // // (C) Copyright 2003-2014 Hewlett-Packard Development Company, L.P. // // 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. // // @@@ END COPYRIGHT @@@ **********************************************************************/ /* -*-C++-*- ***************************************************************************** * * File: ComDistribution.cpp * Description: Supports distributed databases. * * Created: 5/23/2003 * Language: C++ * * * * ***************************************************************************** */ #include "Platform.h" #include "ComCextdecs.h" /***************************************************************************** Function ComCheckPartitionAvailability (char * partName, AvailabilityErrorCode *errorCode) From the IS: - It checks that the partition name passed as an input parameter is a valid fully qualified Guardian name in external file format. - It calls FILE_GETINFOLISTBYNAME_ to check to see if the partition exists and can be accessed, i.e., that there are no errors retrieving information about the partition, and the corrupt and rollforwardneeded flags are not set in the label. - If FILE_GETINFOLISTBYNAME_ does not return any errors, ComCheckPartitionAvailability returns TRUE, indicating that the partition is available. - If FILE_GETINFOLISTBYNAME_ does return an error, ComCheckPartitionAvailability returns FALSE, indicating that the partition is not available. Also has some debug-only support for testing, using env vars. Set the env vars to make ComCheckPartitionAvailability return FALSE. A helper function ComCheckPartAvailabilityFromEnvVars provides this functionality. DIST_UNAVAIL_NODE_<nodename> #no volumes avail on this node DIST_UNAVAIL_NODEVOL_<nodename>_<vol> #specific vol unavail on this node DIST_UNAVAIL_PART_<nodename>_<vol>_<subvol>_<part> #specific part unavail on this node For example: export DIST_UNAVAIL_NODE_TEXMEX #note that the value doesn't matter unset DIST_UNAVAIL_NODE_TEXMEX export DIST_UNAVAIL_NODE_TEXMEX_DATA14 #note no dollar sign on the vol. unset DIST_UNAVAIL_NODE_TEXMEX_DATA14 export DIST_UNAVAIL_PART_TEXMEX_DATA14_ZSD1GTBD_F7DZMV00 unset DIST_UNAVAIL_PART_TEXMEX_DATA14_ZSD1GTBD_F7DZMV00 In addition to this, an error code is returned that indicates the type of availability error. ******************************************************************************/ #include "NABoolean.h" #include "NAStdlib.h" #include "NAString.h" #include "ComDistribution.h" #include "ComASSERT.h" #include "ExpError.h" #include "csconvert.h" #include "NLSConversion.h" // ----------------------------------------------------------------------- // ANSI SQL Name Conversion helpers // // returned error code described in w:/common/csconvert.h // // MBCS stands for the default ANSI name variable-length/width Multi-Byte // Character Set (i.e., the UTF8 character set). // ----------------------------------------------------------------------- Int32 ComAnsiNameToUTF8 ( const NAWchar * inAnsiNameInUCS2 // in - valid ANSI SQL name in UCS2 , char * outBuf4AnsiNameInMBCS // out - out buffer , const Int32 outBufSizeInBytes // in - out buffer max len in bytes ) { if (outBuf4AnsiNameInMBCS == NULL || outBufSizeInBytes <= 0) return -2; // CNV_ERR_BUFFER_OVERRUN - No output buffer or not big enough if (inAnsiNameInUCS2 == NULL) return -3; // CNV_ERR_NOINPUT - No input buffer or input cnt <= 0 else if (NAWstrlen(inAnsiNameInUCS2) == 0) { outBuf4AnsiNameInMBCS[0] = 0; return 0; // success } const Int32 inAnsiNameInBytes = NAWstrlen(inAnsiNameInUCS2) * BYTES_PER_NAWCHAR; Int32 ansiNameCharSet = (Int32)ComGetNameInterfaceCharSet(); Int32 convAnsiNameCS = (Int32)/*cnv_charset*/convertCharsetEnum (ansiNameCharSet); char * pFirstByteOfTheUntranslatedChar = NULL; UInt32 iOutStrLenInBytesIncludingNull = 0; UInt32 iNumTranslatedChars = 0; Int32 iConvErrorCode = UTF16ToLocale ( cnv_version1 // in - const enum cnv_version , (const char *) inAnsiNameInUCS2 // in - const char * in_bufr , (Int32) inAnsiNameInBytes // in - const Int32 in_len_in_bytes , (const char *) outBuf4AnsiNameInMBCS // in/out - const char * out_bufr , (Int32) outBufSizeInBytes // in - const Int32 out_bufr_max_len_in bytes , (cnv_charset) convAnsiNameCS // in - enum cnv_charset conv_charset , pFirstByteOfTheUntranslatedChar // out - char * & first_untranslated_char , &iOutStrLenInBytesIncludingNull // out - UInt32 * output_data_len_p , 0 // in - const Int32 conv_flags , (Int32) TRUE // in - const Int32 add_null_at_end_Flag , (Int32) FALSE // in - const int32 allow_invalids , &iNumTranslatedChars // out - UInt32 * translated_char_cnt_p , (const char *) NULL /* i.e. "?" */ // in - const char * substitution_char = NULL ); return iConvErrorCode; } // returned error code described in w:/common/csconvert.h Int32 ComAnsiNameToUCS2 ( const char * inAnsiNameInMBCS // in - valid name in default ANSI name char set , NAWchar * outBuf4AnsiNameInUCS2 // out - out buffer , const Int32 outBufSizeInNAWchars // in - out buffer max len in NAWchars , const NABoolean padWithSpaces // in - default is FALSE ) { if (outBuf4AnsiNameInUCS2 == NULL || outBufSizeInNAWchars <= 0) return -2; // CNV_ERR_BUFFER_OVERRUN - No output buffer or not big enough if (inAnsiNameInMBCS == NULL) return -3; // CNV_ERR_NOINPUT - No input buffer or input cnt <= 0 else if (strlen(inAnsiNameInMBCS) == 0) { outBuf4AnsiNameInUCS2[0] = 0; return 0; // success } Int32 inAnsiNameLenInBytes = (Int32)strlen(inAnsiNameInMBCS); Int32 outBufSizeInBytes = outBufSizeInNAWchars * BYTES_PER_NAWCHAR; Int32 ansiNameCharSet = (Int32)ComGetNameInterfaceCharSet(); Int32 convAnsiNameCS = (Int32)/*cnv_charset*/convertCharsetEnum (ansiNameCharSet); char * pFirstByteOfTheUntranslatedChar = NULL; UInt32 iTranslatedStrLenInBytes = 0; UInt32 iNumberOfTranslatedChars = 0; Int32 iConvErrorCode = LocaleToUTF16 ( cnv_version1 // in - const enum cnv_version version , inAnsiNameInMBCS // in - const char * in_bufr , (Int32) inAnsiNameLenInBytes // in - const Int32 in_len_in_bytes , (const char *) outBuf4AnsiNameInUCS2 // out - const char * out_bufr , (Int32)(outBufSizeInBytes - BYTES_PER_NAWCHAR) // in - const Int32 out_bufr_max_len_in_bytes , (cnv_charset) convAnsiNameCS // in - enum cnv_charset conv_charset , pFirstByteOfTheUntranslatedChar // out - char * & first_untranslated_char , &iTranslatedStrLenInBytes // out - UInt32 * output_data_len_p , (Int32) 0 // in - const Int32 conv_flags , (Int32) FALSE // in - const Int32 addNullAtEnd_flag , &iNumberOfTranslatedChars // out - UInt32 * translated_char_cnt_p // , 0xffffffff // in - UInt32 max_chars_to_convert = 0xffffffff ); Int32 outStrLenInNAWchars = iTranslatedStrLenInBytes / BYTES_PER_NAWCHAR; outBuf4AnsiNameInUCS2[outStrLenInNAWchars] = 0; // Append the NULL terminator if (iConvErrorCode == 0 && padWithSpaces) { wc_str_pad ( (NAWchar *) &outBuf4AnsiNameInUCS2[outStrLenInNAWchars] // out - NAWchar *str , outBufSizeInNAWchars - outStrLenInNAWchars - 1 // in - Int32 length , unicode_char_set::SPACE // in - NAWchar padchar = unicode_char_set::SPACE ); outBuf4AnsiNameInUCS2[outBufSizeInNAWchars-1] = 0; // Append the NULL terminator } return iConvErrorCode; } // ----------------------------------------------------------------------- // Meatadata Distribution // ----------------------------------------------------------------------- //---------------------------------------------------------------------- // // Build an ANSI schema name from its individual parts // void ComBuildSchemaName ( const char * catalogName, // in, catalog name (internal format) const char * schemaName, // in, schema name (internal format) char * ansiSchemaName, // out, ANSI schema name (external format) const Int32 ansiSchNameBufSize) // in, ANSI schema name output buffer size in bytes { size_t actualLength; char * ptr = ansiSchemaName; // Convert the catalog name to external format ToAnsiIdentifier3 (catalogName, strlen(catalogName), ptr, ansiSchNameBufSize, &actualLength); ComASSERT (actualLength); ptr[actualLength] = '.'; ptr += (actualLength + 1); // Convert the schema name to external format ToAnsiIdentifier3 (schemaName, strlen(schemaName), ptr, ansiSchNameBufSize - actualLength - 1, // remaining available space in ouput buffer &actualLength); ComASSERT (actualLength); } //---------------------------------------------------------------------- // // Build an ANSI name from its individual parts // void ComBuildANSIName ( const char * catalogName, // in, catalog name (internal format) const char * schemaName, // in, schema name (internal format) const char * objectName, // in, object name (internal format) char * ansiName, // out, ANSI name (external format) const Int32 ansiNameOutBufSize) // in, ANSI name output buffer size in bytes { ComBuildSchemaName (catalogName, schemaName, ansiName, ansiNameOutBufSize); size_t actualLength = strlen(ansiName); char * ptr = ansiName; ptr[actualLength] = '.'; ptr += (actualLength + 1); ComASSERT (actualLength); } // General enum to literal translation void enumToLiteral ( const literalAndEnumStruct * conversionTable, const Int32 noOfElements, const Int32 enumValue, char * literal, NABoolean & found) { for (Int32 i = 0;i < noOfElements; i++) { const literalAndEnumStruct & elem = conversionTable[i]; if (elem.enum_ == enumValue) { strcpy (literal, elem.literal_); found = TRUE; return; } } // Didn't find it in the table - bummer! found = FALSE; } // General literal to enum translation Int32 literalToEnum (const literalAndEnumStruct * conversionTable, const Int32 noOfElements, const char * literal, NABoolean & found) { for (Int32 i = 0;i < noOfElements; i++) { const literalAndEnumStruct & elem = conversionTable[i]; if (!strcmp (elem.literal_, literal)) { found = TRUE; return elem.enum_; } } // Didn't find it in the table - bummer! found = FALSE; return 0; }
[ "steve.varnau@hp.com" ]
steve.varnau@hp.com
4917aac5a171ab8661b0d75ebf53493648d2f708
99f1775d340becb82225a6903733deb3ddc16868
/app/deprecated/profile_para_single_query_top_m_search_hierarchy_merge.cpp
ec13eb997c393cdeba98a47f5770c81268ad140e
[ "GPL-3.0-only" ]
permissive
johnpzh/parallel_ANNS
55910553b403b91505b00c41cc4f3f886422d14f
2116d7bf9207fc62c9a11b1919212506cc5a6447
refs/heads/master
2022-11-16T06:54:19.724830
2022-11-12T20:26:22
2022-11-12T20:26:22
221,076,233
7
2
MIT
2022-11-12T20:26:23
2019-11-11T21:48:05
C++
UTF-8
C++
false
false
12,084
cpp
// // Created by Zhen Peng on 7/29/2020. // #include <iostream> #include <cstdio> #include <vector> #include <chrono> #include <clocale> #include <omp.h> //#include "../include/papi_panns.h" //#include "../core/Searching.202002101535.reorganization.h" //#include "../core/Searching.201912161559.set_for_queue.h" //#include "../core/Searching.201912091448.map_for_queries_ids.h" //#include "../core/Searching.h" //#include "../include/utils.h" //#include "../include/efanna2e/index_nsg.h" //#include "../core/Searching.202002141745.critical_omp_top_m.h" //#include "../core/Searching.202002181409.local_queue_and_merge.h" //#include "../core/Searching.202002201424.parallel_merge_local_queues.h" //#include "../core/Searching.202003021000.profile_para_top_m_search.h" //#include "../core/Searching.202004131634.better_merge.h" //#include "../core/Searching.202005271122.choosing_m.h" //#include "../core/Searching.202006191549.nested_parallel.h" //#include "../core/Searching.202006222053.subsearch.h" //#include "../core/Searching.202007271719.gather_top_m.subsearch.profile.h" //#include "../core/Searching.202007281116.only_gather_top_m.profile.h" //#include "../core/Searching.202007281234.only_gather_top_m.h" //#include "../core/Searching.202007291720.hierarchy.h" #include "../core/Searching.202008061153.less_sync.h" void usage(char *argv[]) { fprintf(stderr, "Usage: %s <data_file> <query_file> <nsg_path> <L> <K> <result_file> <M_max> <true_NN_file> <num_threads> <M_middle> <local_L> <local_master_L> <full_merge_freq>\n", argv[0]); } int main(int argc, char **argv) { if (argc != 14) { usage(argv); exit(EXIT_FAILURE); } setbuf(stdout, nullptr); // Remove stdout buffer. setlocale(LC_NUMERIC, ""); // For comma number format PANNS::Searching engine; engine.load_data_load(argv[1]); engine.load_queries_load(argv[2]); engine.load_nsg_graph(argv[3]); // engine.build_opt_graph(); unsigned L = strtoull(argv[4], nullptr, 0); unsigned K = strtoull(argv[5], nullptr, 0); unsigned M_max = strtoull(argv[7], nullptr, 0); if (L < K) { fprintf(stderr, "Error: search_L %u is smaller than search_K %u\n.", L, K); exit(EXIT_FAILURE); } // if (K < M_max) { //// fprintf(stderr, "Error: search_K %u is smaller than value_M %u.\n", K, M_max); //// exit(EXIT_FAILURE); // fprintf(stderr, "Warning: search_K %u is smaller than value_M %u.\n", K, M_max); // } std::vector< std::vector<PANNS::idi> > true_nn_list; engine.load_true_NN( argv[8], true_nn_list); unsigned data_dimension = engine.dimension_; unsigned points_num = engine.num_v_; unsigned query_num = engine.num_queries_; // int num_threads_max = strtoull(argv[9], nullptr, 0); // int num_threads_max = 20; // for (int num_threads = 1; num_threads < num_threads_max + 1; num_threads *= 2) { int num_threads = strtoull(argv[9], nullptr, 0); engine.num_threads_ = num_threads; // engine.num_threads_intra_query_ = num_threads; omp_set_num_threads(num_threads); // omp_set_nested(1); omp_set_max_active_levels(2); unsigned M_middle = strtoull(argv[10], nullptr, 0); unsigned local_queue_capacity = strtoull(argv[11], nullptr, 0); unsigned local_master_queue_capacity = strtoull(argv[12], nullptr, 0); unsigned full_merge_freq = strtoull(argv[13], nullptr, 0); // int warmup_max = 1; // const PANNS::idi local_queue_length = L; // for (unsigned value_M = 2; value_M <= M_max; value_M *= 2) { // for (unsigned local_queue_length = 0; local_queue_length <= 3 * L; local_queue_length += L/10) { // unsigned local_queue_length = 1; // unsigned local_queue_length = L; // unsigned local_queue_length = L / num_threads; // unsigned local_queue_length = M_max * engine.width_; // unsigned base_set_L = (num_threads - 1) * local_queue_length; // if (!local_queue_length) { // local_queue_length = 1; // } const unsigned group_size = 4; const unsigned num_groups = (num_threads - 1) / group_size + 1; unsigned value_M = M_max; unsigned warmup_max = 1; for (unsigned warmup = 0; warmup < warmup_max; ++warmup) { std::vector<std::vector<PANNS::idi> > set_K_list(query_num); for (unsigned i = 0; i < query_num; i++) set_K_list[i].resize(K); std::vector<PANNS::idi> init_ids(L); // std::vector<uint8_t> is_visited(points_num, 0); boost::dynamic_bitset<> is_visited(points_num); std::vector<PANNS::Candidate> set_L( (num_groups - 1) * ((group_size - 1) * local_queue_capacity + local_master_queue_capacity) + (group_size - 1) * local_queue_capacity + L); std::vector<PANNS::idi> local_queues_sizes(num_threads, 0); std::vector<PANNS::idi> local_queues_starts(num_threads); for (int q_i = 0; q_i < num_threads; ++q_i) { unsigned group_id = q_i / group_size; unsigned g_sub = q_i % group_size; unsigned group_base = group_id * ((group_size - 1) * local_queue_capacity + local_master_queue_capacity); local_queues_starts[q_i] = group_base + g_sub * local_queue_capacity; } // std::vector<PANNS::idi> top_m_candidates(value_M); // std::vector< std::vector<PANNS::idi> > top_m_candidates_list(num_groups, // std::vector<PANNS::idi>(value_M)); std::vector<PANNS::idi> top_m_candidates(num_groups * value_M); std::vector<PANNS::idi> top_m_candidates_starts(num_groups); for (unsigned g_i = 0; g_i < num_groups; ++g_i) { top_m_candidates_starts[g_i] = g_i * value_M; } std::vector<PANNS::idi> top_m_candidates_sizes(num_groups, 0); auto s = std::chrono::high_resolution_clock::now(); engine.prepare_init_ids(init_ids, L); //#pragma omp parallel for for (unsigned q_i = 0; q_i < query_num; ++q_i) { engine.para_search_with_top_m_hierarchy_merge_v0( M_middle, value_M, q_i, K, L, set_L, init_ids, set_K_list[q_i], local_queue_capacity, local_master_queue_capacity, local_queues_starts, local_queues_sizes, top_m_candidates, top_m_candidates_starts, top_m_candidates_sizes, is_visited, group_size, full_merge_freq); } auto e = std::chrono::high_resolution_clock::now(); std::chrono::duration<double> diff = e - s; std::unordered_map<unsigned, double> recalls; { // Recall values engine.get_recall_for_all_queries( true_nn_list, set_K_list, recalls); // printf("P@1: %f " // "P@5: %f " // "P@10: %f " // "P@20: %f " // "P@50: %f " // "P@100: %f\n", // recalls[1], // recalls[5], // recalls[10], // recalls[20], // recalls[50], // recalls[100]); // printf("num_threads: %u " // "M: %u " // "L: %u " // "searching_time(s.): %f " // "P@100: %f\n", //// "count_distance_computation: %'lu\n", // num_threads_max, // value_M, // L, // diff.count(), // recalls[100]); //// engine.count_distance_computation); //// engine.count_distance_computation = 0; // for (PANNS::idi q_i = 0; q_i < query_num; ++q_i) { // std::sort(set_K_list[q_i].begin(), set_K_list[q_i].end()); // std::sort(true_nn_list[q_i].begin(), true_nn_list[q_i].end()); // for (unsigned t_i = 0; t_i < 100; ++t_i) { // if (set_K_list[q_i][t_i] == true_nn_list[q_i][t_i]) { // continue; // } // printf("q_i: %u " // "set_K[%u]: %u " // "true[%u]: %u\n", // q_i, // t_i, set_K_list[q_i][t_i], // t_i, true_nn_list[q_i][t_i]); // } // } } {// Basic output printf( // "local_queue_length: %u " "num_threads: %d " "M: %u " "L: %u " "runtime(s.): %f " "computation: %lu " "K: %u " "Volume: %u " "Dimension: %u " "query_num: %u " "query_per_sec: %f " "avg_latency(ms.): %f " "P@100: %f " "P@1: %f " "G/s: %f " "GFLOPS: %f " "local_L: %u " "local_master_L: %u " "M_middle: %u " "Freq: %u \n", // "merge_time(s.): %f\n", // "num_local_elements: %lu\n", // local_queue_length, num_threads, value_M, L, diff.count(), engine.count_distance_computation_, K, points_num, data_dimension, query_num, query_num / diff.count(), diff.count() * 1000 / query_num, recalls[100], recalls[1], data_dimension * 4.0 * engine.count_distance_computation_ / (1U << 30U) / diff.count(), data_dimension * (1.0 + 1.0 + 1.0) * engine.count_distance_computation_ / (1U << 30U) / diff.count(), local_queue_capacity, local_master_queue_capacity, M_middle, full_merge_freq); // engine.time_merge_); // engine.number_local_elements_); engine.count_distance_computation_ = 0; // engine.time_merge_ = 0; // engine.number_local_elements_ = 0; // cache_miss_rate.print(); } // { // Percentage of Sharing // unsigned num_measure_quries = strtoull(argv[10], nullptr, 0); // for (unsigned q_i = 0; q_i < num_measure_quries; q_i += 2) { // double pcnt_has_shared_iterations; // double avg_pcnt_shared_top_m; // get_percentage_of_sharing_in_top_m( // queries_top_m_list[q_i], // queries_top_m_list[q_i + 1], // pcnt_has_shared_iterations, // avg_pcnt_shared_top_m); // printf("%u-%u pcnt_has_shared_iterations: %f avg_pcnt_shared_top_m: %f\n", // q_i, q_i + 1, pcnt_has_shared_iterations, avg_pcnt_shared_top_m); // } // } PANNS::DiskIO::save_result(argv[6], set_K_list); } // } // } // } return 0; }
[ "hi.pengzhen@gmail.com" ]
hi.pengzhen@gmail.com
8604c25712f6e672dcf7bddad947463fe81fb546
e50228ccbb1cac957c258c86dba45ac2a5f6695b
/ArchiveSupport/Merge7z/PipeIPC.cpp
7cc113a9504b665d10cca02e585e105ecc34ce06
[]
no_license
lilixiong/winmerge-v2
395e5c1a0929de1d86babeecf0fdb6e8cb771f81
0766f433fac08c1850091fea31309ecdca81d68a
refs/heads/master
2020-04-06T07:09:42.365269
2015-03-22T12:00:29
2015-03-22T12:00:29
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,767
cpp
#include <windows.h> #include <string.h> #include <tchar.h> #include <fcntl.h> #include <io.h> #include "PipeIPC.h" static bool popen2(const String & cmdline, FILE **inWrite, FILE **outRead) { TCHAR *pcmdline = _tcsdup(cmdline.c_str()); HANDLE hOutReadTmp = NULL, hOutRead = NULL, hOutWrite = NULL; HANDLE hInWriteTmp = NULL, hInRead = NULL, hInWrite = NULL; HANDLE hErrWrite = NULL; HANDLE hCurProc = GetCurrentProcess(); SECURITY_ATTRIBUTES sa = {0}; PROCESS_INFORMATION pi = {0}; STARTUPINFO si = {0}; sa.nLength = sizeof(SECURITY_ATTRIBUTES); sa.bInheritHandle = TRUE; if (!CreatePipe(&hOutReadTmp, &hOutWrite, &sa, 0)) goto ERR; if (!DuplicateHandle(hCurProc, hOutWrite, hCurProc, &hErrWrite, 0, TRUE, DUPLICATE_SAME_ACCESS)) goto ERR; if (!CreatePipe(&hInRead, &hInWriteTmp, &sa, 0)) goto ERR; if (!DuplicateHandle(hCurProc, hOutReadTmp, hCurProc, &hOutRead, 0, FALSE, DUPLICATE_SAME_ACCESS)) goto ERR; if (!DuplicateHandle(hCurProc, hInWriteTmp, hCurProc, &hInWrite, 0, FALSE, DUPLICATE_SAME_ACCESS)) goto ERR; si.cb = sizeof(STARTUPINFO); si.wShowWindow = SW_HIDE; si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW; si.hStdOutput = hOutWrite; si.hStdInput = hInRead; si.hStdError = hErrWrite; if (!CreateProcess(NULL, pcmdline, NULL, NULL, TRUE, 0, NULL, NULL, &si, &pi)) goto ERR; *inWrite = _fdopen(_open_osfhandle((int)hInWrite, _O_TEXT), "w"); *outRead = _fdopen(_open_osfhandle((int)hOutRead, _O_TEXT | _O_RDONLY), "r"); setvbuf(*inWrite, NULL, _IONBF, 0); setvbuf(*outRead, NULL, _IONBF, 0); CloseHandle(pi.hThread); CloseHandle(pi.hProcess); CloseHandle(hOutWrite); CloseHandle(hInRead); CloseHandle(hErrWrite); CloseHandle(hOutReadTmp); CloseHandle(hInWriteTmp); free(pcmdline); return true; ERR: if (hInWriteTmp) CloseHandle(hInWriteTmp); if (hInRead) CloseHandle(hInRead); if (hInWrite) CloseHandle(hInWrite); if (hErrWrite) CloseHandle(hErrWrite); if (hOutReadTmp) CloseHandle(hOutReadTmp); if (hOutRead) CloseHandle(hOutRead); if (hOutWrite) CloseHandle(hOutWrite); free(pcmdline); return false; } PipeIPC::PipeIPC(const String & cmdline) : m_inWrite(NULL), m_outRead(NULL) { popen2(cmdline, &m_inWrite, &m_outRead); } PipeIPC::~PipeIPC() { if (m_inWrite) fclose(m_inWrite); if (m_outRead) fclose(m_outRead); } std::string PipeIPC::readLineStdout() { if (!m_outRead) return ""; std::string line; char buf[512]; while (fgets(buf, sizeof(buf), m_outRead)) { line += buf; if (strchr(buf, '\n') != NULL) break; } return line; } char PipeIPC::readCharStdout() { if (!m_outRead) return EOF; return fgetc(m_outRead); } size_t PipeIPC::writeStdin(const std::string & str) { return fwrite(str.c_str(), str.length(), 1, m_inWrite); }
[ "none@none" ]
none@none
cca6372b6b19ce48718991abcb685ec152fff07d
b7f86821efae61d0ee2571f147c8531b6133e0ae
/QT-ToDoList-Tests/taskmanagertest.cpp
139ba2ff10dd93cba94143f35c33d5dc67883121
[]
no_license
kevix01/QT-ToDoList
3ded3cd49fbb3ec56dc9b4c39e3b51e38135638e
740ab63cee85b282dc7a0314722799e1686265dd
refs/heads/master
2023-06-23T09:32:09.574769
2021-07-22T13:14:45
2021-07-22T13:14:45
377,795,116
0
0
null
null
null
null
UTF-8
C++
false
false
7,946
cpp
#include "taskmanagertest.h" #include "ui_taskmanager.h" TaskManagerTest::~TaskManagerTest(){ if(a) delete a; } void TaskManagerTest::taskLoadingTest() { TaskManager dlg(QString("Task Managing - Testing")); dlg.setModal(true); dlg.setOrigin(m); dlg.show(); dlg.ui->comboBox->addItem(QString::fromStdString("Test List 1")); dlg.ui->comboBox->addItem(QString::fromStdString("Test List 2")); dlg.ui->comboBox->addItem(QString::fromStdString("Test List 3")); dlg.ui->comboBox->addItem(QString::fromStdString("Test List 4")); dlg.ui->comboBox->addItem(QString::fromStdString("Test List 5")); //importing data of first task trough loadData() method dlg.loadData(m->table->item(0, 2)->text().toUtf8().constData(), m->table->item(0, 3)->text().toUtf8().constData(), m->table->item(0, 4)->text().toUtf8().constData(), m->table->item(0, 5)->text().toUtf8().constData(), m->table->item(0, 0)->text().toUtf8().constData()); //cheking dialog's components QVERIFY2(dlg.ui->savebtn, "'Save' button not created."); QVERIFY2(dlg.ui->savebtn->isEnabled(), "'Save' button not enabled (it should be)."); QVERIFY2(dlg.ui->deletebtn, "'Delete' button not created."); QVERIFY2(dlg.ui->deletebtn->isVisible(), "'Delete' button not visible (it should be)."); QVERIFY2(dlg.ui->datepicker, "'Date picker' component not created."); QVERIFY2(dlg.ui->title_et, "'Title' textbox not created."); QVERIFY2(dlg.ui->description_ed, "'Description' textbox not created."); QVERIFY2(dlg.ui->slider, "'Slider' component not created."); //verifing the correctness of data imported in the dialog QCOMPARE(dlg.ui->datepicker->date(), QDate(2023,06,19)); QCOMPARE(dlg.ui->title_et->text(), "Testing title 1"); QCOMPARE(dlg.ui->description_ed->toPlainText(), "Description test of task 1"); QCOMPARE(dlg.ui->slider->value(), 25); QCOMPARE(dlg.ui->comboBox->currentText(), "Test List 1"); //testing checkFields() integrity on description data change dlg.ui->description_ed->clear(); QVERIFY2(!dlg.ui->savebtn->isEnabled(), "'Modify' button is enabled (should be disabled)."); //repopulating description textbox dlg.ui->description_ed->setPlainText(m->table->item(0, 4)->text().toUtf8().constData()); QVERIFY2(dlg.ui->savebtn->isEnabled(), "'Modify' button is disabled (should be enabled)."); //testing checkFields() integrity on title data change dlg.ui->title_et->clear(); QVERIFY2(!dlg.ui->savebtn->isEnabled(), "'Modify' button is enabled (should be disabled)."); //closing dlg dlg.hide(); QVERIFY2(dlg.close(), "Error during dialog close."); } void TaskManagerTest::taskAddingTest(){ TaskManager dlg(QString("Adding Tasks - Testing")); dlg.setModal(true); dlg.setOrigin(m); dlg.loadLists(); //checking if savebutton (Add task) is disabled QVERIFY2(!dlg.ui->savebtn->isEnabled(), "'Add task' button is enabled (it should be disabled)."); //Check if the lists have been loaded correctly in the combobox QCOMPARE(dlg.ui->comboBox->itemText(0), QString::fromStdString("Test List 1")); QCOMPARE(dlg.ui->comboBox->itemText(1), QString::fromStdString("Test List 2")); QCOMPARE(dlg.ui->comboBox->itemText(2), QString::fromStdString("Test List 3")); //Check if counter of undone tasks of list 3 ('Test List 3') is zero QCOMPARE(dlg.origin->l3->getUndoneTasks(), 0); //Adding task 1 //Set current index on the one where is found the lists' name dlg.ui->comboBox->setCurrentIndex(dlg.ui->comboBox->findText(QString::fromStdString("Test List 3"))); //Check if current index of combobox is the respective one of 'Test List 3' QCOMPARE(dlg.ui->comboBox->currentIndex(), 2); //Adding test to the title texbox and checking if savebtn is still disabled dlg.ui->title_et->setText(QString("Testing title text 1")); QVERIFY2(!dlg.ui->savebtn->isEnabled(), "'Add task' button is enabled (it should be disabled)."); //Adding test to the description textbox and checking if savebtn is now enabled dlg.ui->description_ed->setPlainText(QString("Testing description text 1")); QVERIFY2(dlg.ui->savebtn->isEnabled(), "'Add task' button is disabled (it should be enabled)."); //Set value of complete percent slider to 100 and compare the value dlg.ui->slider->setValue(50); QCOMPARE(dlg.ui->slider->value(), 50); //Simulate save button click QTest::mouseClick(dlg.ui->savebtn, Qt::LeftButton); //Check if counter of undone of list 3 ('Test List 3') has been incremented successfully QCOMPARE(dlg.origin->l3->getUndoneTasks(), 1); //Adding task 2 //Set current index on the one where is found the lists' name dlg.ui->comboBox->setCurrentIndex(dlg.ui->comboBox->findText(QString::fromStdString("Test List 3"))); //Check if current index of combobox is the respective one of 'Test List 3' QCOMPARE(dlg.ui->comboBox->currentIndex(), 2); //Adding test to the title texbox and checking if savebtn is still disabled dlg.ui->title_et->setText(QString("Testing title text 2")); //Adding test to the description textbox and checking if savebtn is now enabled dlg.ui->description_ed->setPlainText(QString("Testing description text 2")); QVERIFY2(dlg.ui->savebtn->isEnabled(), "'Add task' button is disabled (it should be enabled)."); //Set value of complete percent slider to 100 and compare the value dlg.ui->slider->setValue(100); QCOMPARE(dlg.ui->slider->value(), 100); //Simulate save button click QTest::mouseClick(dlg.ui->savebtn, Qt::LeftButton); //Check if counter of undone of list 3 ('Test List 3') has not been incremented QCOMPARE(dlg.origin->l3->getUndoneTasks(), 1); //Adding task 3 //Set current index on the one where is found the lists' name dlg.ui->comboBox->setCurrentIndex(dlg.ui->comboBox->findText(QString::fromStdString("Test List 3"))); //Check if current index of combobox is the respective one of 'Test List 3' QCOMPARE(dlg.ui->comboBox->currentIndex(), 2); //Adding test to the title texbox and checking if savebtn is still disabled dlg.ui->title_et->setText(QString("Testing title text 2")); //Adding test to the description textbox and checking if savebtn is now enabled dlg.ui->description_ed->setPlainText(QString("Testing description text 2")); QVERIFY2(dlg.ui->savebtn->isEnabled(), "'Add task' button is disabled (it should be enabled)."); //Set value of complete percent slider to 100 and compare the value dlg.ui->slider->setValue(90); QCOMPARE(dlg.ui->slider->value(), 90); //Simulate save button click QTest::mouseClick(dlg.ui->savebtn, Qt::LeftButton); //Check if counter of undone of list 3 ('Test List 3') has been incremented successfully QCOMPARE(dlg.origin->l3->getUndoneTasks(), 2); //Modify task 1 of List 3 dlg.loadData(m->table->item(3, 2)->text().toUtf8().constData(), m->table->item(3, 3)->text().toUtf8().constData(), m->table->item(3, 4)->text().toUtf8().constData(), m->table->item(3, 5)->text().toUtf8().constData(), m->table->item(3, 0)->text().toUtf8().constData()); //verifing the correctness of data imported in the dialog QCOMPARE(dlg.ui->title_et->text(), "Testing title text 1"); QCOMPARE(dlg.ui->description_ed->toPlainText(), "Testing description text 1"); QCOMPARE(dlg.ui->slider->value(), 50); QCOMPARE(dlg.ui->comboBox->currentText(), "Test List 3"); //Set value of complete percent slider to 100 and compare the value dlg.ui->slider->setValue(100); QCOMPARE(dlg.ui->slider->value(), 100); //Simulate save button click QTest::mouseClick(dlg.ui->savebtn, Qt::LeftButton); //Check if counter of undone of list 3 ('Test List 3') has been decremented successfully QCOMPARE(dlg.origin->l3->getUndoneTasks(), 1); }
[ "kevin.madrigali@stud.unifi.it" ]
kevin.madrigali@stud.unifi.it
d06d246bbda4a72d23a58d737a2614030033c114
24cd93a27b4b8bf66002747e04717b09a8a076a1
/D03/ex04/SuperTrap.cpp
6827ce9c32bc07ae1013907ed21f3b335087d00c
[]
no_license
ygarrot/PiscineCpp
d4a8895bb7817a49aa017e09a0941a9985d024b6
50b061bf65c08aca72ae17b9d469302317467633
refs/heads/master
2021-10-11T04:16:11.622207
2019-01-21T20:18:05
2019-01-21T20:18:05
166,874,429
0
0
null
null
null
null
UTF-8
C++
false
false
2,520
cpp
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* SuperTrap.cpp :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: ygarrot <marvin@42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/01/10 21:26:49 by ygarrot #+# #+# */ /* Updated: 2019/01/11 22:42:31 by ygarrot ### ########.fr */ /* */ /* ************************************************************************** */ #include "SuperTrap.hpp" const std::string SuperTrap::dieQuotes[8] = {"I'll stop talking when I'm dead!","I'll die the way I lived: annoying!", "Come back here! I'll gnaw your legs off!","This could've gone better!", "You look like something a skag barfed up!","What's that smell? Oh wait, it's just you!", "Yo momma's so dumb, she couldn't think of a good ending for this 'yo momma' joke!", "You're one screw short of a screw!"}; const std::string SuperTrap::startQuotes[11] = {"Step right up, to the Bulletnator 9000!", "I am a tornado of death and bullets!", "Stop me before I kill again, except don't!", "Hehehehe, mwaa ha ha ha, MWAA HA HA HA!", "I'm on a roll!", "Unts unts unts unts!", "Ha ha ha! Fall before your robot overlord!", "Can't touch this!", "Ha! Keep 'em coming!", "There is no way this ends badly!", "This is why I was built!"}; void SuperTrap::selfPrint(void) { std::cout << "[SuperTrap] " << this->name << ": "; } SuperTrap::SuperTrap(SuperTrap const & src) : NinjaTrap(src), FragTrap(src), level(1) { *this = src; return; } SuperTrap::SuperTrap(void) : NinjaTrap(), FragTrap(), level(1) { this->selfPrint(); std::cout << this->startQuotes[rand()%10] << " (new)" << std::endl; return ; } SuperTrap::SuperTrap(std::string name) : NinjaTrap(name), FragTrap(name) { this->selfPrint(); std::cout << this->startQuotes[rand()%10] << " (new)" << std::endl; return ; } SuperTrap & SuperTrap::operator=(SuperTrap const & src) { (void)src; return *this; } SuperTrap::~SuperTrap(void) { this->selfPrint(); std::cout << this->dieQuotes[rand()%5] << " (death) " << std::endl; }
[ "garrot.yoan1@gmail.com" ]
garrot.yoan1@gmail.com
cc22e6d772e8833ab1f15e74a92fded5e7d33b58
de69bc4d515ad056e8da223e945b96c0dc2bc94e
/comprehension/slice2.cxx
87c6943ad5ff30eee981ae0939d516128bdbce3f
[]
no_license
seanbaxter/circle
b7d9f7e25734f005d91b20b3f91ea68fa3cb9e34
f260a80b4279ef7276edeef3b9a3f5f4a0ca6e7c
refs/heads/master
2023-08-28T15:55:22.091193
2023-05-02T19:05:14
2023-05-02T19:05:14
170,960,160
1,992
76
null
2023-08-19T21:54:34
2019-02-16T03:55:15
C++
UTF-8
C++
false
false
1,621
cxx
#include <iostream> template<int... x, typename... types_t> void func1(types_t... args) { std::cout<< "Expansion expression of static parameter pack:\n"; std::cout<< " Non-type template parameters:\n"; std::cout<< " "<< x<<"\n" ...; std::cout<< " Type template parameters:\n"; std::cout<< " "<< @type_string(types_t)<< "\n" ...; std::cout<< " Function template parameters:\n"; std::cout<< " "<< args<< "\n" ...; } template<int... x, typename... types_t> void func2(types_t... args) { std::cout<< "\nReverse-order direct pack indexing with ...[index]:\n"; std::cout<< " Non-type template parameters:\n"; @meta for(int i = sizeof...(x) - 1; i >= 0; --i) std::cout<< " "<< x...[i]<<"\n"; std::cout<< " Type template parameters:\n"; @meta for(int i = sizeof...(x) - 1; i >= 0; --i) std::cout<< " "<< @type_string(types_t...[i])<< "\n"; std::cout<< " Function template parameters:\n"; @meta for(int i = sizeof...(x) - 1; i >= 0; --i) std::cout<< " "<< args...[i]<< "\n"; } template<int... x, typename... types_t> void func3(types_t... args) { std::cout<< "\nReverse-order pack slices with ...[begin:end:step]:\n"; std::cout<< " Non-type template parameters:\n"; std::cout<< " "<< x...[::-1]<<"\n" ...; std::cout<< " Type template parameters:\n"; std::cout<< " "<< @type_string(types_t...[::-1])<< "\n" ...; std::cout<< " Function template parameters:\n"; std::cout<< " "<< args...[::-1]<< "\n" ...; } int main() { func1<100, 200, 300>(4, 5l, 6ll); func2<100, 200, 300>(4, 5l, 6ll); func3<100, 200, 300>(4, 5l, 6ll); }
[ "lightborn@gmail.com" ]
lightborn@gmail.com
b31910cc0958510c74ce9c1b87cd266a5549ebcb
0a3b6a06bb980eeaf7afffecf5233ec0fc6c9cc2
/MCCD/src/deformingNow.cpp
9b0c448d10bbf149fe27fbb9a53560a9089d457a
[]
no_license
desaic/DAC
9e7fa375e49af0dfa1104e7ea48a32f06e063da0
0bc329633bd7a485494421ed2fd5c4bc3d0ca674
refs/heads/master
2021-09-14T14:30:43.176929
2018-05-15T04:40:40
2018-05-15T04:40:40
103,591,873
3
1
null
null
null
null
UTF-8
C++
false
false
3,205
cpp
/*************************************************************************\ Copyright 2012 The University of North Carolina at Chapel Hill. All Rights Reserved. Permission to use, copy, modify and distribute this software and its documentation for educational, research and non-profit purposes, without fee, and without a written agreement is hereby granted, provided that the above copyright notice and the following three paragraphs appear in all copies. IN NO EVENT SHALL THE UNIVERSITY OF NORTH CAROLINA AT CHAPEL HILL BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF NORTH CAROLINA HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. THE UNIVERSITY OF NORTH CAROLINA SPECIFICALLY DISCLAIM ANY WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS ON AN "AS IS" BASIS, AND THE UNIVERSITY OF NORTH CAROLINA HAS NO OBLIGATIONS TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. The authors may be contacted via: US Mail: GAMMA Research Group at UNC Department of Computer Science Sitterson Hall, CB #3175 University of N. Carolina Chapel Hill, NC 27599-3175 Phone: (919)962-1749 EMail: geom@cs.unc.edu; tang_m@zju.edu.cn \**************************************************************************/ // Author: Tang, Min tang_m@zju.edu.cn #include "DeformModel.h" #include <stdio.h> #include "timing.h" CBVHTimer tm; #define frand48() ((((float) rand()) / ((float) RAND_MAX))) static DeformModel *mdl; void initModel(double * verts0, double * verts1, int nv, int * trigs, int nt, int num_frame, bool ccd) { TIMING_BEGIN mdl = new DeformModel(verts0, nv, trigs, nt, 1.0f); TIMING_END("Load models") TIMING_BEGIN mdl->Decompose(); TIMING_END("Decompose") TIMING_BEGIN mdl->BuildBVH(ccd); TIMING_END("Build BVH") } void quitModel() { delete mdl; } void drawModel(int level, bool upper) { mdl->Display(); mdl->DisplayBVH(level, upper); } void dynamicModel_AABB(int t, int circle, bool refit, bool ccd) { tm.startTiming(9); tm.startTiming(10); mdl->RebuildBVH(ccd); tm.endTiming(10); tm.endTiming(9); mdl->ResetCounter(); tm.startTiming(0); mdl->SelfCollide(ccd); mdl->UpdateCollide(); tm.endTiming(0); tm.incRecord(mdl->NumBoxTest(), mdl->NumVFTest(), mdl->NumEETest(), mdl->NumVFTrue(), mdl->NumEETrue()); } extern bool *pb; static double g_total = 0; //extern void endCapture(); void dynamicModel(bool refit, bool ccd, bool obb) { double ttmp = omp_get_wtime(); mdl->Deform(); tm.updatTiming(); dynamicModel_AABB(0, 1, refit, ccd); g_total += omp_get_wtime() - ttmp; printf("total: %g seconds\n", g_total); tm.report(); //endCapture(); }
[ "desaicwtf@gmail.com" ]
desaicwtf@gmail.com
c725dcdb881e6105abaffd990033c46edb246837
cc61c589f924c0f00d17ca61e98dc70e2b356629
/src/Boosting/BaseContainer.cpp
7e81b900faf303bb502d6b4f600e041a14cbd0d3
[]
no_license
PadawanZH/SM_MVTO
ef82b678382541a86f7b455e4369085533a4a274
199426f8b8f26d3dd732ca7fa608729374a1cd07
refs/heads/master
2021-08-24T06:07:59.628010
2017-12-08T18:14:22
2017-12-08T18:14:22
null
0
0
null
null
null
null
UTF-8
C++
false
false
177
cpp
// // Created by zhangan on 17-11-17. // #include "BaseContainer.h" BaseContainer::BaseContainer (char* name) { this->name = name; } BaseContainer::~BaseContainer () { }
[ "zhangan19940520@gmail.com" ]
zhangan19940520@gmail.com
61c45ae734efe8a2a1b21d8ea48b36a281ee6149
87bfee4d038939bd682df9a7629268bcffa2be9b
/leetcode/0472-concatenated-words/concatenated-words/trie.h
6a0b3196ec3c3512db0fa62fcec5341bfb4c7a18
[]
no_license
tmlishuai2/Algorithms
e70393f327a07f66eaaeac97437074a70087d596
5f233e60a7ca140ae2f0053e2ca65315aafdc4a5
refs/heads/master
2021-09-01T14:14:34.129352
2017-12-27T11:43:52
2017-12-27T11:43:52
107,866,579
0
2
null
2017-11-04T13:42:22
2017-10-22T13:06:29
C++
UTF-8
C++
false
false
120
h
#pragma once #include <string> #include <vector> #include <unordered_map> #include <unordered_set> #include <algorithm>
[ "tmlishuai2@hotmail.com" ]
tmlishuai2@hotmail.com
5a49167567ccd0a7d3c88da8c9395c3103875956
2f10f807d3307b83293a521da600c02623cdda82
/deps/boost/win/debug/include/boost/fusion/include/swap.hpp
4c3e00bc9ec807b0a8e704d129588657b4a2dd7f
[]
no_license
xpierrohk/dpt-rp1-cpp
2ca4e377628363c3e9d41f88c8cbccc0fc2f1a1e
643d053983fce3e6b099e2d3c9ab8387d0ea5a75
refs/heads/master
2021-05-23T08:19:48.823198
2019-07-26T17:35:28
2019-07-26T17:35:28
null
0
0
null
null
null
null
UTF-8
C++
false
false
128
hpp
version https://git-lfs.github.com/spec/v1 oid sha256:5989c8b5b268b3d1f6c6f052212bfa76cdbe5ba6691f8bb89596c55387ea0dde size 526
[ "YLiLarry@gmail.com" ]
YLiLarry@gmail.com
5dd8472a3506d40d10d6b5c5efcba148eb33dab0
e278a4680ef10e8dcd62071691701dfc6baa6513
/HealthProfile.h
d881898c59e5038ffb88d83bd553fca07789d222
[]
no_license
OBOT-PATRICIA/Assignment2
e659bf107689da0eae3f69556c8146786e5d144b
91553310b3a85cf9db460948b420fba85eecc1f3
refs/heads/master
2016-08-12T15:37:06.872410
2015-06-03T01:14:25
2015-06-03T01:14:25
36,772,973
0
0
null
null
null
null
UTF-8
C++
false
false
2,468
h
/* * HealthProfile.h * HealthProfile class definition. This file represents HealthProfile's public * interface without revealing implementations of HealthProfile's member * functions, which are defined in HealthProfile.cpp * * Stub file for Programming Assignment #2 * * Name: OBOT PATRICIA PETER * Department: DEPARTMENT OF COMPUTER SCIENCE * Matric. No: 45015352GA * */ #include <string> // uses C++ string class using namespace std; // HealthProfile class definition class HealthProfile { // public interface public: HealthProfile( string, string, string, int, int, int, int, double, int, int, int ); // constructor that initializes patient information int getAge(); // function to get patients age in years double getBMI(); // function to calculate and return BMI int getMaximumHeartRate(); // function to calculate and return maximum heart rate double getTargetHeartRate(); // function to calculate and return target heart rate void getInformation(); // function to print object information // TODO: Provide get and set function prototypes of each class attribute // Function prototypes for the constructor, getAge(), getBMI(), getMaximumHeartRate() // getTargetHeartRate() and getInformation() has alrady been provided string getFirstName(); string getGender(); int getMonth(); void setYear(int); void setWeight(int); int getWeight(); int getDay(); int getYear(); double getHeight(); void setLastName(string); void setDay(int); void setFirstName(string); void setGender(string); string getLastName(); void setMonth(int); void setHeight(double); // private interface private: string firstName; // variable to hold firstname string lastName; // variable to hold lastname string gender; // variable to hold gender int month; // variable to hold month int day; // variable to hold day int year; // variable to hold year double height; // variable to hold height int weight; // variable to hold weight int age; // variable to hold age }; // end class HealthProfile
[ "obotpatricia2015@gmail.com" ]
obotpatricia2015@gmail.com
4d79349e5edcc079232fa4a486a97f4e504d12a1
0ab07c413623efbae4e4d941a862b38dae810039
/src/Curve2D.cpp
4f10c972efdd9577936e04cccc987da8d337a7a6
[ "MIT" ]
permissive
Konishi2911/csv2obj
18a9dba75b3caf1094f092cc677189151d1f246d
2191c56bb53962c758360ca2cc58010deb04d827
refs/heads/main
2023-03-19T13:44:32.379817
2021-02-22T06:22:20
2021-02-22T06:22:20
338,977,381
0
0
null
null
null
null
UTF-8
C++
false
false
557
cpp
#include "Curve2D.hpp" STool::Curve2D::Curve2D(const CTool::DoubleSV& csv, bool close): name_(csv.name()), verts_() { auto nPoints = csv.nRows(); for (auto i = 0; i < nPoints; ++i) { this->verts_.emplace_back(csv.lineAt(i)[0], csv.lineAt(i)[1]); } if (close) this->close(); } // - Manipulate curve bool STool::Curve2D::isClosed() const { return *this->verts_.begin() == *this->verts_.end(); } void STool::Curve2D::close() { if (!this->isClosed()) { this->verts_.push_back(*this->verts_.begin()); } }
[ "konishi2911@icloud.com" ]
konishi2911@icloud.com
71ed0ca274d9f434f60ccd343dee275ef362eead
f31c4bc9ccc2a575911f994ab9a9a8b7713e0e24
/cpu.cpp
a45a98396bb15224ff363497d8ac9eb6833c63ad
[]
no_license
greylord1996/PDP-11
372d76cbf7b051524f94e310b39dc371c4cc8d43
215501d20d8c6790d25dbf891b0de92949bd0792
refs/heads/master
2021-08-14T13:41:13.180343
2017-11-15T21:36:29
2017-11-15T21:36:29
109,535,608
0
0
null
null
null
null
UTF-8
C++
false
false
676
cpp
#include <cpu.h> void CPU::SetRegisterByNum(int numOfReg, uint16_t val) { this->reg[numOfReg] = val; } void CPU::IncRegisterByX(int numOfReg, int x) { this->reg[numOfReg] += x; } void CPU::DecRegisterByX(int numOfReg, int x) { this->reg[numOfReg] -= x; } uint16_t CPU::GetValFromRegisterByNum(int numOfReg) { return this->reg[numOfReg]; } RAM *CPU::GetRam() { return this->ram; } CPU::CPU() { } CPU::~CPU() { } void CPU::ProcessInstruction(uint16_t instr, CPU *cpu) { InstructionHandler instruction_handler(instr, cpu); //std::cout << cpu->GetValFromRegisterByNum(0) << std::endl; return instruction_handler.HandleInstruction(); }
[ "emchinov@bk.ru" ]
emchinov@bk.ru
73a1010ca25c7c3adba40089e63030df09ace659
a397e0ccaa45324bbeebf172fca41f8c0347d1b7
/Client/AdvancedATM/Dialogs.hpp
fc43fbeeafecbd03fdac447189040b5d04800668
[]
no_license
Haizanjs/RPFramework_AdvancedBanking_Module
e6617c83cd96387a8ec98a37e4826a17d173f4fd
25d3ceb00865ccabf30fb90841ba35b381461bb4
refs/heads/master
2021-09-07T20:40:46.400475
2018-02-28T18:38:26
2018-02-28T18:38:26
123,007,952
0
1
null
null
null
null
UTF-8
C++
false
false
6,924
hpp
class AdvancedATM { idd = 10015; class controls { class RscText_1000: RscText { idc = 1000; x = 0.314375 * safezoneW + safezoneX; y = 0.225 * safezoneH + safezoneY; w = 0.180469 * safezoneW; h = 0.418 * safezoneH; colorBackground[] = {0,0,0,0.8}; }; class RscButton_1600: RscButton { idc = 1600; text = "1"; //--- ToDo: Localize; x = 0.335 * safezoneW + safezoneX; y = 0.313 * safezoneH + safezoneY; w = 0.04125 * safezoneW; h = 0.066 * safezoneH; colorBackground[] = {0,0,0,0.8}; }; class RscButton_1601: RscButton { idc = 1601; text = "2"; //--- ToDo: Localize; x = 0.381406 * safezoneW + safezoneX; y = 0.313 * safezoneH + safezoneY; w = 0.04125 * safezoneW; h = 0.066 * safezoneH; colorBackground[] = {0,0,0,0.8}; }; class RscButton_1602: RscButton { idc = 1602; text = "3"; //--- ToDo: Localize; x = 0.427812 * safezoneW + safezoneX; y = 0.313 * safezoneH + safezoneY; w = 0.04125 * safezoneW; h = 0.066 * safezoneH; colorBackground[] = {0,0,0,0.8}; }; class RscButton_1603: RscButton { idc = 1603; text = "4"; //--- ToDo: Localize; x = 0.335 * safezoneW + safezoneX; y = 0.39 * safezoneH + safezoneY; w = 0.04125 * safezoneW; h = 0.066 * safezoneH; colorBackground[] = {0,0,0,0.8}; }; class RscButton_1604: RscButton { idc = 1604; text = "5"; //--- ToDo: Localize; x = 0.381406 * safezoneW + safezoneX; y = 0.39 * safezoneH + safezoneY; w = 0.04125 * safezoneW; h = 0.066 * safezoneH; colorBackground[] = {0,0,0,0.8}; }; class RscButton_1605: RscButton { idc = 1605; text = "6"; //--- ToDo: Localize; x = 0.427812 * safezoneW + safezoneX; y = 0.39 * safezoneH + safezoneY; w = 0.04125 * safezoneW; h = 0.066 * safezoneH; colorBackground[] = {0,0,0,0.8}; }; class RscButton_1606: RscButton { idc = 1606; text = "7"; //--- ToDo: Localize; x = 0.335 * safezoneW + safezoneX; y = 0.467 * safezoneH + safezoneY; w = 0.04125 * safezoneW; h = 0.066 * safezoneH; colorBackground[] = {0,0,0,0.8}; }; class RscButton_1607: RscButton { idc = 1607; text = "8"; //--- ToDo: Localize; x = 0.381406 * safezoneW + safezoneX; y = 0.467 * safezoneH + safezoneY; w = 0.04125 * safezoneW; h = 0.066 * safezoneH; colorBackground[] = {0,0,0,0.8}; }; class RscButton_1608: RscButton { idc = 1608; text = "9"; //--- ToDo: Localize; x = 0.427812 * safezoneW + safezoneX; y = 0.467 * safezoneH + safezoneY; w = 0.04125 * safezoneW; h = 0.066 * safezoneH; colorBackground[] = {0,0,0,0.8}; }; class RscButton_1609: RscButton { idc = 1609; text = "10"; //--- ToDo: Localize; x = 0.381406 * safezoneW + safezoneX; y = 0.555 * safezoneH + safezoneY; w = 0.04125 * safezoneW; h = 0.066 * safezoneH; colorBackground[] = {0,0,0,0.8}; }; class RscEdit_1400: RscEdit { idc = 1400; text = "pindisplay"; //--- ToDo: Localize; x = 0.335 * safezoneW + safezoneX; y = 0.247 * safezoneH + safezoneY; w = 0.139219 * safezoneW; h = 0.055 * safezoneH; colorBackground[] = {0,0,0,0.8}; }; class transactionHistory: RscListbox { idc = 1500; x = 0.675312 * safezoneW + safezoneX; y = 0.269 * safezoneH + safezoneY; w = 0.185625 * safezoneW; h = 0.352 * safezoneH; colorBackground[] = {0,0,0,0.8}; }; class RscText_1001: RscText { idc = 1001; text = "Pin Enter"; //--- ToDo: Localize; x = 0.314375 * safezoneW + safezoneX; y = 0.203 * safezoneH + safezoneY; w = 0.180469 * safezoneW; h = 0.022 * safezoneH; colorBackground[] = {0.969,0.608,0.133,1}; }; class RscText_1002: RscText { idc = 1002; x = 0.505156 * safezoneW + safezoneX; y = 0.225 * safezoneH + safezoneY; w = 0.366094 * safezoneW; h = 0.418 * safezoneH; colorBackground[] = {0,0,0,0.8}; }; class RscText_1003: RscText { idc = 1003; text = "Banking Union"; //--- ToDo: Localize; x = 0.505156 * safezoneW + safezoneX; y = 0.203 * safezoneH + safezoneY; w = 0.366094 * safezoneW; h = 0.022 * safezoneH; colorBackground[] = {0.969,0.608,0.133,1}; }; class editbox: RscEdit { idc = 1401; text = "Cash"; //--- ToDo: Localize; x = 0.515469 * safezoneW + safezoneX; y = 0.313 * safezoneH + safezoneY; w = 0.149531 * safezoneW; h = 0.033 * safezoneH; colorBackground[] = {0,0,0,0.8}; }; class RscButton_1610: RscButton { idc = 1610; text = "Withdraw"; //--- ToDo: Localize; x = 0.515469 * safezoneW + safezoneX; y = 0.401 * safezoneH + safezoneY; w = 0.149531 * safezoneW; h = 0.033 * safezoneH; colorBackground[] = {0,0,0,0.8}; }; class RscButton_1611: RscButton { idc = 1611; text = "Deposit"; //--- ToDo: Localize; x = 0.515469 * safezoneW + safezoneX; y = 0.445 * safezoneH + safezoneY; w = 0.149531 * safezoneW; h = 0.033 * safezoneH; colorBackground[] = {0,0,0,0.8}; }; class RscText_1004: RscText { idc = 1004; text = "Transactions"; //--- ToDo: Localize; x = 0.675312 * safezoneW + safezoneX; y = 0.247 * safezoneH + safezoneY; w = 0.185625 * safezoneW; h = 0.022 * safezoneH; colorBackground[] = {0,0,0,0.8}; }; class RscText_1005: RscText { idc = 1005; x = 0.675312 * safezoneW + safezoneX; y = 0.269 * safezoneH + safezoneY; w = 0.185625 * safezoneW; h = 0.352 * safezoneH; colorBackground[] = {0,0,0,0.75}; }; class RscText_1006: RscText { idc = 1006; text = "Balance: $999 999 9"; //--- ToDo: Localize; x = 0.515469 * safezoneW + safezoneX; y = 0.247 * safezoneH + safezoneY; w = 0.149531 * safezoneW; h = 0.055 * safezoneH; colorBackground[] = {0,0,0,0.8}; }; class RscButton_1612: RscButton { idc = 1612; text = "Transfer Funds"; //--- ToDo: Localize; x = 0.515469 * safezoneW + safezoneX; y = 0.489 * safezoneH + safezoneY; w = 0.149531 * safezoneW; h = 0.033 * safezoneH; colorBackground[] = {0,0,0,0.8}; }; class RscEdit_1402: RscEdit { idc = 1402; text = "SortNumber"; //--- ToDo: Localize; x = 0.515469 * safezoneW + safezoneX; y = 0.357 * safezoneH + safezoneY; w = 0.149531 * safezoneW; h = 0.033 * safezoneH; colorBackground[] = {0,0,0,0.8}; tooltip = "SortNumber"; //--- ToDo: Localize; }; class RscButton_1613: RscButton { idc = 1613; text = "Change PIN"; //--- ToDo: Localize; x = 0.515469 * safezoneW + safezoneX; y = 0.533 * safezoneH + safezoneY; w = 0.149531 * safezoneW; h = 0.033 * safezoneH; colorBackground[] = {0,0,0,0.8}; }; class RscButton_1614: RscButton { idc = 1614; text = "Freeze Funds"; //--- ToDo: Localize; x = 0.515469 * safezoneW + safezoneX; y = 0.577 * safezoneH + safezoneY; w = 0.149531 * safezoneW; h = 0.033 * safezoneH; colorBackground[] = {0,0,0,0.8}; }; }; };
[ "jackmichaelsimons59@gmail.com" ]
jackmichaelsimons59@gmail.com
f7ff6401b6084915e2743772a0409f9baa08ccd4
43ee3cc213125c09205195a30fce171ff9ed44c4
/test/tests/libcxx/set/emplace.pass.cpp
e3ac729ecbae794382e38b0b67ffd95b31d419c6
[ "MIT", "NCSA" ]
permissive
asidorov95/momo
820356ae130fc97d60e26e50fc380a9826e1c89d
ebede4ba210ac1fa614bb2571a526e7591a92b56
refs/heads/master
2020-10-01T18:26:23.841911
2019-12-12T12:04:05
2019-12-12T12:04:05
155,053,265
0
0
null
2018-10-28T09:14:16
2018-10-28T09:14:16
null
UTF-8
C++
false
false
2,714
cpp
//===----------------------------------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is dual licensed under the MIT and the University of Illinois Open // Source Licenses. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // <set> // class set // template <class... Args> // pair<iterator, bool> emplace(Args&&... args); //#include <set> //#include <cassert> //#include "../../Emplaceable.h" //#include "DefaultOnly.h" //#include "min_allocator.h" void main() { #ifndef _LIBCPP_HAS_NO_RVALUE_REFERENCES #ifdef LIBCPP_HAS_BAD_NEWS_FOR_MOMO { typedef set<DefaultOnly> M; typedef std::pair<M::iterator, bool> R; M m; assert(DefaultOnly::count == 0); R r = m.emplace(); assert(r.second); assert(r.first == m.begin()); assert(m.size() == 1); assert(*m.begin() == DefaultOnly()); assert(DefaultOnly::count == 1); r = m.emplace(); assert(!r.second); assert(r.first == m.begin()); assert(m.size() == 1); assert(*m.begin() == DefaultOnly()); assert(DefaultOnly::count == 1); } assert(DefaultOnly::count == 0); #endif { typedef set<Emplaceable> M; typedef std::pair<M::iterator, bool> R; M m; R r = m.emplace(); assert(r.second); assert(r.first == m.begin()); assert(m.size() == 1); assert(*m.begin() == Emplaceable()); r = m.emplace(2, 3.5); assert(r.second); assert(r.first == next(m.begin())); assert(m.size() == 2); assert(*r.first == Emplaceable(2, 3.5)); r = m.emplace(2, 3.5); assert(!r.second); assert(r.first == next(m.begin())); assert(m.size() == 2); assert(*r.first == Emplaceable(2, 3.5)); } { typedef set<int> M; typedef std::pair<M::iterator, bool> R; M m; R r = m.emplace(M::value_type(2)); assert(r.second); assert(r.first == m.begin()); assert(m.size() == 1); assert(*r.first == 2); } //#if __cplusplus >= 201103L #ifdef LIBCPP_TEST_MIN_ALLOCATOR { typedef set<int, std::less<int>, min_allocator<int>> M; typedef std::pair<M::iterator, bool> R; M m; R r = m.emplace(M::value_type(2)); assert(r.second); assert(r.first == m.begin()); assert(m.size() == 1); assert(*r.first == 2); } #endif #endif // _LIBCPP_HAS_NO_RVALUE_REFERENCES }
[ "morzhovets@gmail.com" ]
morzhovets@gmail.com
6b00e947f7576cb9fb50a7dd0bbf2ecf29f78356
b494c362dd9a3c2ea0629c4e9bb841c1bdd05b6e
/SDK/SCUM_UI_ItemStatusWidget_parameters.hpp
4d085990355e33b8cb3669bd83b24114b5c12138
[]
no_license
a-ahmed/SCUM_SDK
6b55076b4aeb5973c4a1a3770c470fccce898100
cd5e5089507a638f130cc95a003e0000918a1ec7
refs/heads/master
2022-05-20T17:28:10.940288
2020-04-03T18:48:52
2020-04-03T18:48:52
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,253
hpp
#pragma once // SCUM (Dumped by Hinnie) SDK #ifdef _MSC_VER #pragma pack(push, 0x8) #endif #include "../SDK.hpp" namespace SDK { //--------------------------------------------------------------------------- //Parameters //--------------------------------------------------------------------------- // Function UI_ItemStatusWidget.UI_ItemStatusWidget_C.UpdateVisibility struct UUI_ItemStatusWidget_C_UpdateVisibility_Params { }; // Function UI_ItemStatusWidget.UI_ItemStatusWidget_C.Construct struct UUI_ItemStatusWidget_C_Construct_Params { }; // Function UI_ItemStatusWidget.UI_ItemStatusWidget_C.SetNameText struct UUI_ItemStatusWidget_C_SetNameText_Params { struct FString* Text; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor) }; // Function UI_ItemStatusWidget.UI_ItemStatusWidget_C.ExecuteUbergraph_UI_ItemStatusWidget struct UUI_ItemStatusWidget_C_ExecuteUbergraph_UI_ItemStatusWidget_Params { int EntryPoint; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData) }; } #ifdef _MSC_VER #pragma pack(pop) #endif
[ "hsibma02@gmail.com" ]
hsibma02@gmail.com
9b6ba5dac67ad7d7e2ed5f37b171991acd69fd3c
f93133123b5f7fffc562c023d1255600024a7b10
/Counter Test For CHEFSUM/main.cpp
e3802dc8d91d18cb69499e8d5651964484840abe
[]
no_license
Bunnynegi/Competitive-Coding
85415d3649420bd6851e674003d47238398d8cff
11a3ca975d4ddd4729716f267da9b9bed49c2c12
refs/heads/master
2022-04-02T23:16:50.388043
2020-01-17T14:33:53
2020-01-17T14:33:53
105,656,141
0
0
null
null
null
null
UTF-8
C++
false
false
591
cpp
// #include<bits/stdc++.h> #define fast ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); #define F first #define S second #define PB push_back #define MP make_pair #define REP(i,a,b) for (int i = a; i < b; i++) #define endll "\n" using namespace std; typedef long long ll; int main() { fast; ll t; cin>>t; while(t--) { ll n; cin>>n; ll a[n]={0}; ll first=4294967295/(n+1); ll cycle=4294967295%(n+1); a[0]=first+cycle/2+1; cout<<a[0]<<" "; REP(i,1,n)cout<<first<<" "; cout<<endll; } return 0; }
[ "cmsn123@gmail.comz" ]
cmsn123@gmail.comz
9bf6b2d2223daa0057c7e25c89922e53e40ee09b
bf3125318772616d741a1e70204eda63680598ea
/patterns/null.h
d0f7ee9fe41a4651213688e38fe580b082f15cea
[]
no_license
cheyxx/algorithm
79cd3a8b7164e90accdae6642c25ce10a52fb527
de7f7e131d8b7974e407616f35265421e93ba1f0
refs/heads/master
2020-03-18T14:59:18.214277
2019-07-04T05:27:41
2019-07-04T05:27:41
134,879,640
0
0
null
null
null
null
UTF-8
C++
false
false
790
h
/* Copyright (c) 2019 The Design Pattern Authors. All rights reserved. */ #ifndef PATTERNS_NULL_H_ #define PATTERNS_NULL_H_ #include <iostream> #include <memory> #include <vector> class AbstractCustomer { public: virtual std::string GetName() = 0; virtual bool isNull() = 0; }; class Customer : public AbstractCustomer { public: Customer(std::string name); std::string GetName(); bool isNull(); private: std::string name_; }; class NullCustomer : public AbstractCustomer{ public: std::string GetName(); bool isNull(); }; class CustomerFactory { private: std::vector<std::string> data_base_ = {"bob", "tom"}; public: std::shared_ptr<AbstractCustomer> GetCustomer(std::string name); }; #endif // PATTERNS_NULL_H_
[ "fun.colin.he@gmail.com" ]
fun.colin.he@gmail.com
417bc1ecec5eba0d94a60f21162b19c974bba23a
60d718b01b6c1adbab2ec072836e5826c3985f3a
/QxOrm/inl/QxDao/QxSqlQueryHelper_Update.inl
ac1f418c609c866b2af41744b0a03d82b8fbf3cb
[]
no_license
jpush/jchat-windows
1084127d0ce39ad00a344661f265e5d65389c186
e782268c8d04ffad5d6e9a69308fad30b583603e
refs/heads/master
2022-01-14T06:35:47.571133
2019-05-14T05:32:42
2019-05-14T05:42:19
106,393,361
19
4
null
null
null
null
UTF-8
C++
false
false
3,279
inl
/**************************************************************************** ** ** http://www.qxorm.com/ ** Copyright (C) 2013 Lionel Marty (contact@qxorm.com) ** ** This file is part of the QxOrm library ** ** 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 ** ** Commercial Usage ** Licensees holding valid commercial QxOrm licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Lionel Marty ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3.0 as published by the Free Software ** Foundation and appearing in the file 'license.gpl3.txt' included in the ** packaging of this file. Please review the following information to ** ensure the GNU General Public License version 3.0 requirements will be ** met : http://www.gnu.org/copyleft/gpl.html ** ** If you are unsure which license is appropriate for your use, or ** if you have questions regarding the use of this file, please contact : ** contact@qxorm.com ** ****************************************************************************/ namespace qx { namespace dao { namespace detail { template <class T> struct QxSqlQueryHelper_Update { static void sql(QString & sql, qx::IxSqlQueryBuilder & builder) { static_assert(qx::trait::is_qx_registered<T>::value, "qx::trait::is_qx_registered<T>::value"); qx::IxSqlQueryBuilder::sql_Update(sql, builder); } static void resolveInput(T & t, QSqlQuery & query, qx::IxSqlQueryBuilder & builder) { static_assert(qx::trait::is_qx_registered<T>::value, "qx::trait::is_qx_registered<T>::value"); qx::IxSqlQueryBuilder::resolveInput_Update((& t), query, builder); } static void resolveOutput(T & t, QSqlQuery & query, qx::IxSqlQueryBuilder & builder) { Q_UNUSED(t); Q_UNUSED(query); Q_UNUSED(builder); } static void sql(QString & sql, qx::IxSqlQueryBuilder & builder, const QStringList & columns) { if ((columns.count() <= 0) || (columns.at(0) == "*")) { QxSqlQueryHelper_Update<T>::sql(sql, builder); return; } static_assert(qx::trait::is_qx_registered<T>::value, "qx::trait::is_qx_registered<T>::value"); qx::IxSqlQueryBuilder::sql_Update(sql, builder, columns); } static void resolveInput(T & t, QSqlQuery & query, qx::IxSqlQueryBuilder & builder, const QStringList & columns) { if ((columns.count() <= 0) || (columns.at(0) == "*")) { QxSqlQueryHelper_Update<T>::resolveInput(t, query, builder); return; } static_assert(qx::trait::is_qx_registered<T>::value, "qx::trait::is_qx_registered<T>::value"); qx::IxSqlQueryBuilder::resolveInput_Update((& t), query, builder, columns); } static void resolveOutput(T & t, QSqlQuery & query, qx::IxSqlQueryBuilder & builder, const QStringList & columns) { if ((columns.count() <= 0) || (columns.at(0) == "*")) { QxSqlQueryHelper_Update<T>::resolveOutput(t, query, builder); return; } } }; } // namespace detail } // namespace dao } // namespace qx
[ "wangshun@jiguang.cn" ]
wangshun@jiguang.cn
e7d6b1e07d4a9c215bc5caeaabbcbec99a1c3b98
b9d7a0e3748c9b7d648446761971a92c7b483e12
/ASCII_Game/WindowHandler.hpp
2639d566ab7edaa6703c94ee59222d585c96c8e8
[]
no_license
kgarbacinski/ASCII-Game
91823986e89c3eae46de03d63bb67dcbe8c27d92
c8544b3ea3b4af430ecf144c35a6824c61748496
refs/heads/master
2023-01-09T09:35:49.947968
2020-10-24T20:15:42
2020-10-24T20:15:42
278,919,222
3
0
null
null
null
null
UTF-8
C++
false
false
387
hpp
#include <windows.h> #include <string> #include <thread> #include <mutex> #include <iostream> #include <conio.h> enum Colours { NONE = 0, DARK_RED = 4, RED = 12, LIGHT_BLUE = 11, WHITE = 15, LIGHT_GREEN = 10, GRAY = 7, PURPLE = 13 }; #pragma once class WindowHandler { protected: void gotoxy(int x, int y); void changeColor(int nameNumber); virtual ~WindowHandler() {} };
[ "chlubakarol@gmail.com" ]
chlubakarol@gmail.com
97b31457a6dd8960f9c78441c1fa076069e826bd
af7977991477325ddc604b6d3e2ac3cb4aa29337
/FlappyBirdGame3D3.0/Temp/il2cppOutput/il2cppOutput/mscorlib_System_Collections_Generic_KeyValuePair_22971303333.h
7f0798979e61090ad3184074e03693a4f89129c3
[]
no_license
jpf2141/FlappyBird3D
b824cf5fac6ca3c5739afc342b659af1f2836ab9
fe4e9c421ec8dc26a7befd620f9deaf3c6361de5
refs/heads/master
2021-01-21T13:53:25.062470
2016-05-06T02:39:28
2016-05-06T02:39:28
55,712,365
3
1
null
null
null
null
UTF-8
C++
false
false
1,576
h
#pragma once #include "il2cpp-config.h" #ifndef _MSC_VER # include <alloca.h> #else # include <malloc.h> #endif #include <stdint.h> // System.String struct String_t; #include "mscorlib_System_ValueType4014882752.h" #include "Vuforia_UnityExtensions_Vuforia_WebCamProfile_Prof1845074131.h" #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Collections.Generic.KeyValuePair`2<System.String,Vuforia.WebCamProfile/ProfileData> struct KeyValuePair_2_t2971303333 { public: // TKey System.Collections.Generic.KeyValuePair`2::key String_t* ___key_0; // TValue System.Collections.Generic.KeyValuePair`2::value ProfileData_t1845074131 ___value_1; public: inline static int32_t get_offset_of_key_0() { return static_cast<int32_t>(offsetof(KeyValuePair_2_t2971303333, ___key_0)); } inline String_t* get_key_0() const { return ___key_0; } inline String_t** get_address_of_key_0() { return &___key_0; } inline void set_key_0(String_t* value) { ___key_0 = value; Il2CppCodeGenWriteBarrier(&___key_0, value); } inline static int32_t get_offset_of_value_1() { return static_cast<int32_t>(offsetof(KeyValuePair_2_t2971303333, ___value_1)); } inline ProfileData_t1845074131 get_value_1() const { return ___value_1; } inline ProfileData_t1845074131 * get_address_of_value_1() { return &___value_1; } inline void set_value_1(ProfileData_t1845074131 value) { ___value_1 = value; } }; #ifdef __clang__ #pragma clang diagnostic pop #endif
[ "kdj2109@columbia.edu" ]
kdj2109@columbia.edu
4931045e7bd4e6bfc5471c5751b1a8f549c8a607
f7da959df493043193aaad51bffdbafa08d1d6b9
/courses/T-414-AFLV/2-data-structures-and-libraries/where_is_my_internet.cpp
e9da80901d4159e1a66f4047ff8bfa0382004082
[]
no_license
dkiswanto/competitive-programming-exercise
1b3143448a0c448db8f55a1d8415a4bbbb3d2c53
8dcb6cbe9a395e005609a0dfba5b3d5fc3f16386
refs/heads/master
2021-10-23T22:17:56.879188
2019-03-20T13:13:14
2019-03-20T13:13:14
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,412
cpp
#include <bits/stdc++.h> using namespace std; struct union_find { vector<int> parent; union_find(int n) { parent = vector<int>(n); for (int i = 0; i < n; i++) { parent[i] = i; } } int find(int x) { if (parent[x] == x) { return x; } else { parent[x] = find(parent[x]); return parent[x]; } } void unite(int x, int y) { parent[find(x)] = find(y); } }; int main() { int n; // number of house int m; // network already deployed cin >> n >> m; union_find houses(n); for (int i = 0; i < m; i++) { int house1, house2; cin >> house1 >> house2; houses.unite(house1-1, house2-1); } bool connected = true; for (int j = 1; j < n; j++) { // DEBUG // cout << "1 & " << j + 1 << " status : " << (houses.find(0) != houses.find(j)) << endl; if(houses.find(0) != houses.find(j)){ cout << j + 1 << endl; connected = false; } } if (connected) cout << "Connected" << endl; return 0; } // [Union Find Disjoint Sets] // * index vector as element, // * value vector as return a representative // // union_find(6) // -> vector<int> = { 0,1,2,3,4,5,6 } // // .find(3) // -> 3 // // .unite(1,3) // -> vector[1] = 3 // -> vector = [0,3,2,3,4,5,6] // // .find(1) // -> 3
[ "kiswanto.d21@gmail.com" ]
kiswanto.d21@gmail.com
e9170829d6e34d8176a3819b32c4bccf4be351f3
9aad69fea204dfa2fe0b16e1d8cf8b8b84e30bad
/src/alloy/test/test_unpack.cc
2af4b0ef0a7f1c3bd8cf41c0bb356c7b35e8df85
[]
no_license
inlandyears/xenia
cc65084e62b37a19bf977519906b1b460d42dc8f
9fcffcf86648c58b390bda8d91fa77a9d006f37d
refs/heads/master
2021-01-21T02:24:09.378373
2014-09-10T03:45:14
2014-09-10T03:45:14
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,759
cc
/** ****************************************************************************** * Xenia : Xbox 360 Emulator Research Project * ****************************************************************************** * Copyright 2014 Ben Vanik. All rights reserved. * * Released under the BSD license - see LICENSE in the root for more details. * ****************************************************************************** */ #include <tools/alloy-test/util.h> using namespace alloy; using namespace alloy::hir; using namespace alloy::runtime; using namespace alloy::test; using alloy::frontend::ppc::PPCContext; TEST_CASE("UNPACK_D3DCOLOR", "[instr]") { TestFunction test([](hir::HIRBuilder& b) { StoreVR(b, 3, b.Unpack(LoadVR(b, 4), PACK_TYPE_D3DCOLOR)); b.Return(); }); test.Run([](PPCContext* ctx) { uint32_t value = 0; ctx->v[4] = vec128i(0, 0, 0, value); }, [](PPCContext* ctx) { auto result = ctx->v[3]; REQUIRE(result == vec128f(1.0f, 1.0f, 1.0f, 1.0f)); }); test.Run([](PPCContext* ctx) { uint32_t value = 0x80506070; ctx->v[4] = vec128i(0, 0, 0, value); }, [](PPCContext* ctx) { auto result = ctx->v[3]; REQUIRE(result == vec128i(0x3F800050, 0x3F800060, 0x3F800070, 0x3F800080)); }); } TEST_CASE("UNPACK_FLOAT16_2", "[instr]") { TestFunction test([](hir::HIRBuilder& b) { StoreVR(b, 3, b.Unpack(LoadVR(b, 4), PACK_TYPE_FLOAT16_2)); b.Return(); }); test.Run([](PPCContext* ctx) { ctx->v[4] = vec128i(0); }, [](PPCContext* ctx) { auto result = ctx->v[3]; REQUIRE(result == vec128i(0, 0, 0, 0x3F800000)); }); test.Run([](PPCContext* ctx) { ctx->v[4] = vec128i(0, 0, 0, 0x7FFFFFFF); }, [](PPCContext* ctx) { auto result = ctx->v[3]; REQUIRE(result == vec128i(0x47FFE000, 0xC7FFE000, 0x00000000, 0x3F800000)); }); test.Run([](PPCContext* ctx) { ctx->v[4] = vec128i(0, 0, 0, 0x55556666); }, [](PPCContext* ctx) { auto result = ctx->v[3]; REQUIRE(result == vec128i(0x42AAA000, 0x44CCC000, 0x00000000, 0x3F800000)); }); } TEST_CASE("UNPACK_FLOAT16_4", "[instr]") { TestFunction test([](hir::HIRBuilder& b) { StoreVR(b, 3, b.Unpack(LoadVR(b, 4), PACK_TYPE_FLOAT16_4)); b.Return(); }); test.Run([](PPCContext* ctx) { ctx->v[4] = vec128i(0); }, [](PPCContext* ctx) { auto result = ctx->v[3]; REQUIRE(result == vec128i(0)); }); test.Run([](PPCContext* ctx) { ctx->v[4] = vec128s(0, 0, 0, 0, 0x64D2, 0x6D8B, 0x4881, 0x4491); }, [](PPCContext* ctx) { auto result = ctx->v[3]; REQUIRE(result == vec128i(0x449A4000, 0x45B16000, 0x41102000, 0x40922000)); }); } TEST_CASE("UNPACK_SHORT_2", "[instr]") { TestFunction test([](hir::HIRBuilder& b) { StoreVR(b, 3, b.Unpack(LoadVR(b, 4), PACK_TYPE_SHORT_2)); b.Return(); }); test.Run([](PPCContext* ctx) { ctx->v[4] = vec128i(0); }, [](PPCContext* ctx) { auto result = ctx->v[3]; REQUIRE(result == vec128i(0x40400000, 0x40400000, 0x00000000, 0x3F800000)); }); test.Run([](PPCContext* ctx) { ctx->v[4] = vec128i(0x7004FD60, 0x8201C990, 0x00000000, 0x7FFF8001); }, [](PPCContext* ctx) { auto result = ctx->v[3]; REQUIRE(result == vec128i(0x40407FFF, 0x403F8001, 0x00000000, 0x3F800000)); }); test.Run([](PPCContext* ctx) { ctx->v[4] = vec128i(0, 0, 0, (0x1234u << 16) | 0x5678u); }, [](PPCContext* ctx) { auto result = ctx->v[3]; REQUIRE(result == vec128i(0x40401234, 0x40405678, 0x00000000, 0x3F800000)); }); } // TEST_CASE("UNPACK_S8_IN_16_LO", "[instr]") { // TestFunction test([](hir::HIRBuilder& b) { // StoreVR(b, 3, b.Unpack(LoadVR(b, 4), PACK_TYPE_S8_IN_16_LO)); // b.Return(); // }); // test.Run([](PPCContext* ctx) { ctx->v[4] = vec128b(0); }, // [](PPCContext* ctx) { // auto result = ctx->v[3]; // REQUIRE(result == vec128b(0)); // }); //} // // TEST_CASE("UNPACK_S8_IN_16_HI", "[instr]") { // TestFunction test([](hir::HIRBuilder& b) { // StoreVR(b, 3, b.Unpack(LoadVR(b, 4), PACK_TYPE_S8_IN_16_HI)); // b.Return(); // }); // test.Run([](PPCContext* ctx) { ctx->v[4] = vec128b(0); }, // [](PPCContext* ctx) { // auto result = ctx->v[3]; // REQUIRE(result == vec128b(0)); // }); //} // // TEST_CASE("UNPACK_S16_IN_32_LO", "[instr]") { // TestFunction test([](hir::HIRBuilder& b) { // StoreVR(b, 3, b.Unpack(LoadVR(b, 4), PACK_TYPE_S16_IN_32_LO)); // b.Return(); // }); // test.Run([](PPCContext* ctx) { ctx->v[4] = vec128b(0); }, // [](PPCContext* ctx) { // auto result = ctx->v[3]; // REQUIRE(result == vec128b(0)); // }); //} // // TEST_CASE("UNPACK_S16_IN_32_HI", "[instr]") { // TestFunction test([](hir::HIRBuilder& b) { // StoreVR(b, 3, b.Unpack(LoadVR(b, 4), PACK_TYPE_S16_IN_32_HI)); // b.Return(); // }); // test.Run([](PPCContext* ctx) { ctx->v[4] = vec128b(0); }, // [](PPCContext* ctx) { // auto result = ctx->v[3]; // REQUIRE(result == vec128b(0)); // }); //}
[ "ben.vanik@gmail.com" ]
ben.vanik@gmail.com
bc2fddc4eb11d3786f545cae73ff373444b56e70
3bc95589dbd26f2857ebe9ffbfa3d07cd490defa
/src/test/allocator_tests.cpp
da42637aecf0abf439280094d11cd86e8c51fde1
[ "MIT" ]
permissive
perfectcoincore/perfectcoin
5e840973b09081845c38e26e0c6d95e95fae3389
32dcbae0df2798921a9752a1a1371141831f1adc
refs/heads/master
2020-03-21T13:30:48.489603
2018-06-27T06:07:32
2018-06-27T06:07:32
138,610,004
2
0
null
null
null
null
UTF-8
C++
false
false
7,402
cpp
// Copyright (c) 2012-2016 The Bitcoin Core developers // Copyright (c) 2017 The Pigeon Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "util.h" #include "support/allocators/secure.h" #include "test/test_perfectcoin.h" #include <boost/test/unit_test.hpp> BOOST_FIXTURE_TEST_SUITE(allocator_tests, BasicTestingSetup) BOOST_AUTO_TEST_CASE(arena_tests) { // Fake memory base address for testing // without actually using memory. void *synth_base = reinterpret_cast<void*>(0x08000000); const size_t synth_size = 1024*1024; Arena b(synth_base, synth_size, 16); void *chunk = b.alloc(1000); #ifdef ARENA_DEBUG b.walk(); #endif BOOST_CHECK(chunk != nullptr); BOOST_CHECK(b.stats().used == 1008); // Aligned to 16 BOOST_CHECK(b.stats().total == synth_size); // Nothing has disappeared? b.free(chunk); #ifdef ARENA_DEBUG b.walk(); #endif BOOST_CHECK(b.stats().used == 0); BOOST_CHECK(b.stats().free == synth_size); try { // Test exception on double-free b.free(chunk); BOOST_CHECK(0); } catch(std::runtime_error &) { } void *a0 = b.alloc(128); void *a1 = b.alloc(256); void *a2 = b.alloc(512); BOOST_CHECK(b.stats().used == 896); BOOST_CHECK(b.stats().total == synth_size); #ifdef ARENA_DEBUG b.walk(); #endif b.free(a0); #ifdef ARENA_DEBUG b.walk(); #endif BOOST_CHECK(b.stats().used == 768); b.free(a1); BOOST_CHECK(b.stats().used == 512); void *a3 = b.alloc(128); #ifdef ARENA_DEBUG b.walk(); #endif BOOST_CHECK(b.stats().used == 640); b.free(a2); BOOST_CHECK(b.stats().used == 128); b.free(a3); BOOST_CHECK(b.stats().used == 0); BOOST_CHECK_EQUAL(b.stats().chunks_used, 0); BOOST_CHECK(b.stats().total == synth_size); BOOST_CHECK(b.stats().free == synth_size); BOOST_CHECK_EQUAL(b.stats().chunks_free, 1); std::vector<void*> addr; BOOST_CHECK(b.alloc(0) == nullptr); // allocating 0 always returns nullptr #ifdef ARENA_DEBUG b.walk(); #endif // Sweeping allocate all memory for (int x=0; x<1024; ++x) addr.push_back(b.alloc(1024)); BOOST_CHECK(b.stats().free == 0); BOOST_CHECK(b.alloc(1024) == nullptr); // memory is full, this must return nullptr BOOST_CHECK(b.alloc(0) == nullptr); for (int x=0; x<1024; ++x) b.free(addr[x]); addr.clear(); BOOST_CHECK(b.stats().total == synth_size); BOOST_CHECK(b.stats().free == synth_size); // Now in the other direction... for (int x=0; x<1024; ++x) addr.push_back(b.alloc(1024)); for (int x=0; x<1024; ++x) b.free(addr[1023-x]); addr.clear(); // Now allocate in smaller unequal chunks, then deallocate haphazardly // Not all the chunks will succeed allocating, but freeing nullptr is // allowed so that is no problem. for (int x=0; x<2048; ++x) addr.push_back(b.alloc(x+1)); for (int x=0; x<2048; ++x) b.free(addr[((x*23)%2048)^242]); addr.clear(); // Go entirely wild: free and alloc interleaved, // generate targets and sizes using pseudo-randomness. for (int x=0; x<2048; ++x) addr.push_back(0); uint32_t s = 0x12345678; for (int x=0; x<5000; ++x) { int idx = s & (addr.size()-1); if (s & 0x80000000) { b.free(addr[idx]); addr[idx] = 0; } else if(!addr[idx]) { addr[idx] = b.alloc((s >> 16) & 2047); } bool lsb = s & 1; s >>= 1; if (lsb) s ^= 0xf00f00f0; // LFSR period 0xf7ffffe0 } for (void *ptr: addr) b.free(ptr); addr.clear(); BOOST_CHECK(b.stats().total == synth_size); BOOST_CHECK(b.stats().free == synth_size); } /** Mock LockedPageAllocator for testing */ class TestLockedPageAllocator: public LockedPageAllocator { public: TestLockedPageAllocator(int count_in, int lockedcount_in): count(count_in), lockedcount(lockedcount_in) {} void* AllocateLocked(size_t len, bool *lockingSuccess) override { *lockingSuccess = false; if (count > 0) { --count; if (lockedcount > 0) { --lockedcount; *lockingSuccess = true; } return reinterpret_cast<void*>(0x08000000 + (count<<24)); // Fake address, do not actually use this memory } return 0; } void FreeLocked(void* addr, size_t len) override { } size_t GetLimit() override { return std::numeric_limits<size_t>::max(); } private: int count; int lockedcount; }; BOOST_AUTO_TEST_CASE(lockedpool_tests_mock) { // Test over three virtual arenas, of which one will succeed being locked std::unique_ptr<LockedPageAllocator> x(new TestLockedPageAllocator(3, 1)); LockedPool pool(std::move(x)); BOOST_CHECK(pool.stats().total == 0); BOOST_CHECK(pool.stats().locked == 0); // Ensure unreasonable requests are refused without allocating anything void *invalid_toosmall = pool.alloc(0); BOOST_CHECK(invalid_toosmall == nullptr); BOOST_CHECK(pool.stats().used == 0); BOOST_CHECK(pool.stats().free == 0); void *invalid_toobig = pool.alloc(LockedPool::ARENA_SIZE+1); BOOST_CHECK(invalid_toobig == nullptr); BOOST_CHECK(pool.stats().used == 0); BOOST_CHECK(pool.stats().free == 0); void *a0 = pool.alloc(LockedPool::ARENA_SIZE / 2); BOOST_CHECK(a0); BOOST_CHECK(pool.stats().locked == LockedPool::ARENA_SIZE); void *a1 = pool.alloc(LockedPool::ARENA_SIZE / 2); BOOST_CHECK(a1); void *a2 = pool.alloc(LockedPool::ARENA_SIZE / 2); BOOST_CHECK(a2); void *a3 = pool.alloc(LockedPool::ARENA_SIZE / 2); BOOST_CHECK(a3); void *a4 = pool.alloc(LockedPool::ARENA_SIZE / 2); BOOST_CHECK(a4); void *a5 = pool.alloc(LockedPool::ARENA_SIZE / 2); BOOST_CHECK(a5); // We've passed a count of three arenas, so this allocation should fail void *a6 = pool.alloc(16); BOOST_CHECK(!a6); pool.free(a0); pool.free(a2); pool.free(a4); pool.free(a1); pool.free(a3); pool.free(a5); BOOST_CHECK(pool.stats().total == 3*LockedPool::ARENA_SIZE); BOOST_CHECK(pool.stats().locked == LockedPool::ARENA_SIZE); BOOST_CHECK(pool.stats().used == 0); } // These tests used the live LockedPoolManager object, this is also used // by other tests so the conditions are somewhat less controllable and thus the // tests are somewhat more error-prone. BOOST_AUTO_TEST_CASE(lockedpool_tests_live) { LockedPoolManager &pool = LockedPoolManager::Instance(); LockedPool::Stats initial = pool.stats(); void *a0 = pool.alloc(16); BOOST_CHECK(a0); // Test reading and writing the allocated memory *((uint32_t*)a0) = 0x1234; BOOST_CHECK(*((uint32_t*)a0) == 0x1234); pool.free(a0); try { // Test exception on double-free pool.free(a0); BOOST_CHECK(0); } catch(std::runtime_error &) { } // If more than one new arena was allocated for the above tests, something is wrong BOOST_CHECK(pool.stats().total <= (initial.total + LockedPool::ARENA_SIZE)); // Usage must be back to where it started BOOST_CHECK(pool.stats().used == initial.used); } BOOST_AUTO_TEST_SUITE_END()
[ "webframes@gmail.com" ]
webframes@gmail.com
a56cae9531aea5a3474b0e558a5d90feee8ad0b4
e74ec3c0a5479a657ab34aa5905b797eeeddc59c
/ddf/src/cuda/ddf_add_faster_cuda.cpp
5fa1af41c1b22e4d3bdf4cffceebc66235f065a2
[ "MIT" ]
permissive
OutBreak-hui/ddfnet
33a106f010f906640f335c868cf7da2e85474bd4
65f67692352a2c083b5d7e003e320629a86e8460
refs/heads/main
2023-05-31T20:41:21.803800
2021-06-24T06:37:50
2021-06-24T06:37:50
380,129,330
1
0
MIT
2021-06-25T05:03:59
2021-06-25T05:03:58
null
UTF-8
C++
false
false
1,722
cpp
#include <ATen/ATen.h> #include <torch/extension.h> #include <cmath> #include <vector> int DDFAddFasterForwardLauncher( const at::Tensor features, const at::Tensor channel_filter, const at::Tensor spatial_filter, const int kernel_size, const int dilation, const int stride, const int batch_size,const int channels, const int bottom_height, const int bottom_width, const int top_height, const int top_width, at::Tensor output); #define CHECK_CUDA(x) TORCH_CHECK(x.device().is_cuda(), #x, " must be a CUDA tensor ") #define CHECK_CONTIGUOUS(x) \ TORCH_CHECK(x.is_contiguous(), #x, " must be contiguous ") #define CHECK_INPUT(x) \ CHECK_CUDA(x); \ CHECK_CONTIGUOUS(x) int ddf_add_faster_forward_cuda( at::Tensor features,at::Tensor channel_filter, at::Tensor spatial_filter, int kernel_size, int dilation, int stride, int head, at::Tensor output){ CHECK_INPUT(features); CHECK_INPUT(channel_filter); CHECK_INPUT(spatial_filter); CHECK_INPUT(output); at::DeviceGuard guard(features.device()); const int batch_size = features.size(0); const int channels = features.size(1); const int bottom_height = features.size(2); const int bottom_width = features.size(3); const int top_height = output.size(2); const int top_width = output.size(3); //TODO: use head DDFAddFasterForwardLauncher(features, channel_filter, spatial_filter, kernel_size, dilation, stride, batch_size, channels, bottom_height, bottom_width, top_height, top_width, output); return 1; }
[ "1252693592@qq.com" ]
1252693592@qq.com
d94d4c9cc1d357c50325a5e0602219f4927c9f9b
64e4fabf9b43b6b02b14b9df7e1751732b30ad38
/src/chromium/gen/gen_combined/third_party/blink/renderer/bindings/modules/v8/v8_usb.h
c0a3337c9c112005c00ca4c7e8d24ae8e7f2b380
[ "BSD-3-Clause" ]
permissive
ivan-kits/skia-opengl-emscripten
8a5ee0eab0214c84df3cd7eef37c8ba54acb045e
79573e1ee794061bdcfd88cacdb75243eff5f6f0
refs/heads/master
2023-02-03T16:39:20.556706
2020-12-25T14:00:49
2020-12-25T14:00:49
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,647
h
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // This file has been auto-generated from the Jinja2 template // third_party/blink/renderer/bindings/templates/interface.h.tmpl // by the script code_generator_v8.py. // DO NOT MODIFY! // clang-format off #ifndef THIRD_PARTY_BLINK_RENDERER_BINDINGS_MODULES_V8_V8_USB_H_ #define THIRD_PARTY_BLINK_RENDERER_BINDINGS_MODULES_V8_V8_USB_H_ #include "third_party/blink/renderer/bindings/core/v8/generated_code_helper.h" #include "third_party/blink/renderer/bindings/core/v8/native_value_traits.h" #include "third_party/blink/renderer/bindings/core/v8/to_v8_for_core.h" #include "third_party/blink/renderer/bindings/core/v8/v8_binding_for_core.h" #include "third_party/blink/renderer/bindings/core/v8/v8_event_target.h" #include "third_party/blink/renderer/modules/modules_export.h" #include "third_party/blink/renderer/modules/webusb/usb.h" #include "third_party/blink/renderer/platform/bindings/script_wrappable.h" #include "third_party/blink/renderer/platform/bindings/v8_dom_wrapper.h" #include "third_party/blink/renderer/platform/bindings/wrapper_type_info.h" #include "third_party/blink/renderer/platform/heap/handle.h" namespace blink { MODULES_EXPORT extern const WrapperTypeInfo v8_usb_wrapper_type_info; class V8USB { STATIC_ONLY(V8USB); public: MODULES_EXPORT static bool HasInstance(v8::Local<v8::Value>, v8::Isolate*); static v8::Local<v8::Object> FindInstanceInPrototypeChain(v8::Local<v8::Value>, v8::Isolate*); MODULES_EXPORT static v8::Local<v8::FunctionTemplate> DomTemplate(v8::Isolate*, const DOMWrapperWorld&); static USB* ToImpl(v8::Local<v8::Object> object) { return ToScriptWrappable(object)->ToImpl<USB>(); } MODULES_EXPORT static USB* ToImplWithTypeCheck(v8::Isolate*, v8::Local<v8::Value>); MODULES_EXPORT static constexpr const WrapperTypeInfo* GetWrapperTypeInfo() { return &v8_usb_wrapper_type_info; } static constexpr int kInternalFieldCount = kV8DefaultWrapperInternalFieldCount; MODULES_EXPORT static void InstallConditionalFeatures( v8::Local<v8::Context>, const DOMWrapperWorld&, v8::Local<v8::Object> instance_object, v8::Local<v8::Object> prototype_object, v8::Local<v8::Function> interface_object, v8::Local<v8::FunctionTemplate> interface_template); // Callback functions MODULES_EXPORT static void OnconnectAttributeGetterCallback(const v8::FunctionCallbackInfo<v8::Value>&); MODULES_EXPORT static void OnconnectAttributeSetterCallback(const v8::FunctionCallbackInfo<v8::Value>&); MODULES_EXPORT static void OndisconnectAttributeGetterCallback(const v8::FunctionCallbackInfo<v8::Value>&); MODULES_EXPORT static void OndisconnectAttributeSetterCallback(const v8::FunctionCallbackInfo<v8::Value>&); MODULES_EXPORT static void GetDevicesMethodCallback(const v8::FunctionCallbackInfo<v8::Value>&); MODULES_EXPORT static void RequestDeviceMethodCallback(const v8::FunctionCallbackInfo<v8::Value>&); static void InstallRuntimeEnabledFeaturesOnTemplate( v8::Isolate*, const DOMWrapperWorld&, v8::Local<v8::FunctionTemplate> interface_template); }; template <> struct NativeValueTraits<USB> : public NativeValueTraitsBase<USB> { MODULES_EXPORT static USB* NativeValue(v8::Isolate*, v8::Local<v8::Value>, ExceptionState&); MODULES_EXPORT static USB* NullValue() { return nullptr; } }; template <> struct V8TypeOf<USB> { typedef V8USB Type; }; } // namespace blink #endif // THIRD_PARTY_BLINK_RENDERER_BINDINGS_MODULES_V8_V8_USB_H_
[ "trofimov_d_a@magnit.ru" ]
trofimov_d_a@magnit.ru
4cff98c04eb736fd0d1d255ce629706ca1f973fa
8f8ede2d240cafa0b17f135c553a2ae64e6ea1bd
/voice/voicerecog/voicerecoglib/dialogengine/suntec/src/VR_DummyMediaPlayer.cpp
bb1da353f5a8ff47f5622366e9e043b15969c228
[]
no_license
hyCpp/MyDemo
176d86b720fbc9619807c2497fadb781f5dc4295
150c77ebe54fe7b7f60063e6488319d804a07d03
refs/heads/master
2020-03-18T05:33:37.338743
2019-03-10T04:21:01
2019-03-10T04:21:01
134,348,743
0
0
null
null
null
null
UTF-8
C++
false
false
3,340
cpp
/** * Copyright @ 2015 - 2016 Suntec Software(Shanghai) Co., Ltd. * All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are NOT permitted except as agreed by * Suntec Software(Shanghai) Co., Ltd. * * 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. */ #include "VR_DummyMediaPlayer.h" #include "VR_Log.h" std::shared_ptr<VR_DummyMediaPlayer> VR_DummyMediaPlayer::create( std::shared_ptr<avsCommon::sdkInterfaces::HTTPContentFetcherInterfaceFactoryInterface> contentFetcherFactory, SpeakerInterface::Type type) { std::shared_ptr<VR_DummyMediaPlayer> mediaPlayer(new VR_DummyMediaPlayer(contentFetcherFactory, type)); return mediaPlayer; }; VR_DummyMediaPlayer::~VR_DummyMediaPlayer() { } VR_DummyMediaPlayer::SourceId VR_DummyMediaPlayer::setSource(std::shared_ptr<avsCommon::avs::attachment::AttachmentReader> reader) { ACSDK_DEBUG9(LX("setSourceCalled").d("sourceType", "AttachmentReader")); std::promise<VR_DummyMediaPlayer::SourceId> promise; auto future = promise.get_future(); return future.get(); } VR_DummyMediaPlayer::SourceId VR_DummyMediaPlayer::setSource(std::shared_ptr<std::istream> stream, bool repeat) { ACSDK_DEBUG9(LX("setSourceCalled").d("sourceType", "istream")); std::promise<VR_DummyMediaPlayer::SourceId> promise; auto future = promise.get_future(); return future.get(); } VR_DummyMediaPlayer::SourceId VR_DummyMediaPlayer::setSource(const std::string& url) { ACSDK_DEBUG9(LX("setSourceForUrlCalled").sensitive("url", url)); std::promise<VR_DummyMediaPlayer::SourceId> promise; auto future = promise.get_future(); return future.get(); } bool VR_DummyMediaPlayer::play(VR_DummyMediaPlayer::SourceId id) { return false; } bool VR_DummyMediaPlayer::stop(VR_DummyMediaPlayer::SourceId id) { return false; } bool VR_DummyMediaPlayer::pause(VR_DummyMediaPlayer::SourceId id) { return false; } bool VR_DummyMediaPlayer::resume(VR_DummyMediaPlayer::SourceId id) { return false; } std::chrono::milliseconds VR_DummyMediaPlayer::getOffset(VR_DummyMediaPlayer::SourceId id) { std::chrono::milliseconds promise; return promise; } bool VR_DummyMediaPlayer::setOffset(VR_DummyMediaPlayer::SourceId id, std::chrono::milliseconds offset) { return false; } void VR_DummyMediaPlayer::setObserver(std::shared_ptr<avsCommon::utils::mediaPlayer::MediaPlayerObserverInterface> observer) { return; } bool VR_DummyMediaPlayer::setVolume(int8_t volume) { return false; } bool VR_DummyMediaPlayer::adjustVolume(int8_t delta) { return false; } bool VR_DummyMediaPlayer::setMute(bool mute) { return false; } bool VR_DummyMediaPlayer::getSpeakerSettings(SpeakerInterface::SpeakerSettings* settings) { return false; } avsCommon::sdkInterfaces::SpeakerInterface::Type VR_DummyMediaPlayer::getSpeakerType() { return avsCommon::sdkInterfaces::SpeakerInterface::Type::AVS_SYNCED; } VR_DummyMediaPlayer::VR_DummyMediaPlayer( std::shared_ptr<avsCommon::sdkInterfaces::HTTPContentFetcherInterfaceFactoryInterface> contentFetcherFactory, SpeakerInterface::Type type) { } /* EOF */
[ "huyang@192.168.124.5" ]
huyang@192.168.124.5
f594952d9218c49a9d4147f2f9697a65a7f889c5
14338b7167f1971917cc034a9dec9c147709b0e2
/serenity/src/filter/OutputFilter.cc
646e5760c2fa2de170c67256942c1f6476c6e403
[ "MIT", "BSD-3-Clause" ]
permissive
adonig/stappler
655511b8acd88b2b91daa1ac145bda4c28fc3241
4326bffc1883e56ce331ffd6a6b3207750230e86
refs/heads/master
2020-04-05T16:54:55.506700
2018-10-16T14:12:48
2018-11-05T11:25:52
null
0
0
null
null
null
null
UTF-8
C++
false
false
12,290
cc
// This is an open source non-commercial project. Dear PVS-Studio, please check it. // PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com /** Copyright (c) 2016 Roman Katuntsev <sbkarr@stappler.org> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. **/ #include "Define.h" #include "OutputFilter.h" #include "SPData.h" #include "Output.h" #include "Tools.h" NS_SA_BEGIN static apr_status_t filterFunc(ap_filter_t *f, apr_bucket_brigade *bb); static int filterInit(ap_filter_t *f); void OutputFilter::filterRegister() { ap_register_output_filter_protocol("Serenity::OutputFilter", &(filterFunc), &(filterInit), (ap_filter_type)(AP_FTYPE_PROTOCOL), AP_FILTER_PROTO_CHANGE | AP_FILTER_PROTO_CHANGE_LENGTH); } void OutputFilter::insert(const Request &r) { apr::pool::perform([&] () { auto f = new (r.request()->pool) OutputFilter(r); ap_add_output_filter("Serenity::OutputFilter", (void *)f, r, r.connection()); }, r.request()); } apr_status_t filterFunc(ap_filter_t *f, apr_bucket_brigade *bb) { return apr::pool::perform([&] () -> apr_status_t { if (APR_BRIGADE_EMPTY(bb)) { return APR_SUCCESS; } if (f->ctx) { OutputFilter *filter = (OutputFilter *) f->ctx; return filter->func(f, bb); } else { return ap_pass_brigade(f->next,bb); } }, f->r); } int filterInit(ap_filter_t *f) { return apr::pool::perform([&] () -> apr_status_t { if (f->ctx) { OutputFilter *filter = (OutputFilter *) f->ctx; return filter->init(f); } else { return OK; } }, f->r); } OutputFilter::OutputFilter(const Request &rctx) : _nameBuffer(64), _buffer(255) { _tmpBB = NULL; _seenEOS = false; _request = rctx; _char = 0; _buf = 0; _isWhiteSpace = true; } int OutputFilter::init(ap_filter_t* f) { _seenEOS = false; _skipFilter = false; return OK; } apr_status_t OutputFilter::func(ap_filter_t *f, apr_bucket_brigade *bb) { if (_seenEOS) { return APR_SUCCESS; } if (_skipFilter || _state == State::Body || f->r->proto_num == 9) { return ap_pass_brigade(f->next, bb); } apr_bucket *e; const char *data = NULL; size_t len = 0; apr_status_t rv; if (!_tmpBB) { _tmpBB = apr_brigade_create(f->c->pool, f->c->bucket_alloc); } apr_read_type_e mode = APR_NONBLOCK_READ; while ((e = APR_BRIGADE_FIRST(bb)) != APR_BRIGADE_SENTINEL(bb)) { if (APR_BUCKET_IS_EOS(e)) { _seenEOS = true; APR_BUCKET_REMOVE(e); APR_BRIGADE_INSERT_TAIL(_tmpBB,e); break; } if (APR_BUCKET_IS_METADATA(e)) { APR_BUCKET_REMOVE(e); APR_BRIGADE_INSERT_TAIL(_tmpBB, e); continue; } if (_responseCode < 400 && _state == State::Body) { _skipFilter = true; APR_BUCKET_REMOVE(e); APR_BRIGADE_INSERT_TAIL(_tmpBB, e); break; } rv = apr_bucket_read(e, &data, &len, mode); if (rv == APR_EAGAIN && mode == APR_NONBLOCK_READ) { /* Pass down a brigade containing a flush bucket: */ APR_BRIGADE_INSERT_TAIL(_tmpBB, apr_bucket_flush_create(_tmpBB->bucket_alloc)); rv = ap_pass_brigade(f->next, _tmpBB); apr_brigade_cleanup(_tmpBB); if (rv != APR_SUCCESS) return rv; /* Retry, using a blocking read. */ mode = APR_BLOCK_READ; continue; } else if (rv != APR_SUCCESS) { return rv; } if (rv == APR_SUCCESS) { rv = process(f, e, data, len); if (rv != APR_SUCCESS) { return rv; } } /* Remove bucket e from bb. */ APR_BUCKET_REMOVE(e); /* Pass brigade downstream. */ rv = ap_pass_brigade(f->next, _tmpBB); apr_brigade_cleanup(_tmpBB); if (rv != APR_SUCCESS) return rv; mode = APR_NONBLOCK_READ; if (_state == State::Body) { break; } } if (!APR_BRIGADE_EMPTY(_tmpBB)) { rv = ap_pass_brigade(f->next, _tmpBB); apr_brigade_cleanup(_tmpBB); if (rv != APR_SUCCESS) return rv; } if (!APR_BRIGADE_EMPTY(bb)) { rv = ap_pass_brigade(f->next, bb); if (rv != APR_SUCCESS) return rv; } return APR_SUCCESS; } apr_status_t OutputFilter::process(ap_filter_t* f, apr_bucket *e, const char *data, size_t len) { apr_status_t rv = APR_SUCCESS; if (len > 0 && _state != State::Body) { Reader reader(data, len); if (_state == State::FirstLine) { if (readRequestLine(reader)) { _responseLine = _buffer.str(); _buffer.clear(); _nameBuffer.clear(); } } if (_state == State::Headers) { if (readHeaders(reader)) { rv = outputHeaders(f, e, data, len); if (rv != APR_SUCCESS) { return rv; } } } if (_state == State::Body) { if (!reader.empty()) { APR_BRIGADE_INSERT_TAIL(_tmpBB, apr_bucket_transient_create( reader.data(), reader.size(), _tmpBB->bucket_alloc)); } } } return rv; } size_t OutputFilter::calcHeaderSize() const { auto len = _responseLine.size() + 2; for (auto &it : _headers) { len += strlen(it.key) + strlen(it.val) + 4; } auto &cookies = _request.getResponseCookies(); for (auto &it : cookies) { if ((_responseCode < 400 && (it.second.flags & CookieFlags::SetOnSuccess) != 0) || (_responseCode >= 400 && (it.second.flags & CookieFlags::SetOnError) != 0)) { len += "Set-Cookie: "_len + it.first.size() + 1 + it.second.data.size() + ";Path=/;Version=1"_len + 4; if (it.second.data.empty() || it.second.maxAge) { len += ";Max-Age="_len + 10; } if ((it.second.flags & CookieFlags::HttpOnly) != 0) { len += ";HttpOnly"_len; } if ((it.second.flags & CookieFlags::Secure) != 0) { len += ";Secure;"_len; } } } return len; } void OutputFilter::writeHeader(ap_filter_t* f, StringStream &output) const { output << _responseLine; if (_responseLine.back() != '\n') { output << '\n'; } for (auto &it : _headers) { output << it.key << ": " << it.val << "\r\n"; } auto &cookies = _request.getResponseCookies(); for (auto &it : cookies) { if ((_responseCode < 400 && (it.second.flags & CookieFlags::SetOnSuccess) != 0) || (_responseCode >= 400 && (it.second.flags & CookieFlags::SetOnError) != 0) ) { output << "Set-Cookie: " << it.first << "=" << it.second.data; if (it.second.data.empty() || it.second.maxAge) { output << ";Max-Age=" << it.second.maxAge.toSeconds(); } if ((it.second.flags & CookieFlags::HttpOnly) != 0) { output << ";HttpOnly"; } if ((it.second.flags & CookieFlags::Secure) != 0 && Connection(f->c).isSecureConnection()) { output << ";Secure"; } output << ";Path=/;Version=1\r\n"; } } output << "\r\n"; } apr_status_t OutputFilter::outputHeaders(ap_filter_t* f, apr_bucket *e, const char *data, size_t len) { conn_rec *c = f->c; apr_status_t rv = APR_SUCCESS; apr::ostringstream servVersion; servVersion << "Serenity/" << tools::getVersionString() << " (" << tools::getCompileUnixTime().toHttp() << ")"; _headers.emplace("Server", servVersion.str()); _buffer.clear(); if (_responseCode < 400) { _skipFilter = true; } else { output::writeData(_request, _buffer, [&] (const String &ct) { _headers.emplace("Content-Type", ct); }, resultForRequest(), true); _headers.emplace("Content-Length", apr_psprintf(c->pool, "%lu", _buffer.size())); // provide additional info for 416 if we can if (_responseCode == 416) { // we need to determine requested file size if (const char *filename = f->r->filename) { apr_finfo_t info; memset(&info, 0, sizeof(info)); if (apr_stat(&info, filename, APR_FINFO_SIZE, c->pool) == APR_SUCCESS) { _headers.emplace("X-Range", apr_psprintf(c->pool, "%ld", info.size)); } else { _headers.emplace("X-Range", "0"); } } else { _headers.emplace("X-Range", "0"); } } else if (_responseCode == 401) { if (_headers.at("WWW-Authenticate").empty()) { _headers.emplace("WWW-Authenticate", toString("Basic realm=\"", _request.getHostname(), "\"")); } } } // create ostream with preallocated storage auto bufLen = calcHeaderSize(); char dataBuf[bufLen+1]; apr::ostringstream output(dataBuf, bufLen); writeHeader(f, output); apr_bucket *b = apr_bucket_transient_create(output.data(), output.size(), _tmpBB->bucket_alloc); APR_BRIGADE_INSERT_TAIL(_tmpBB, b); if (!_buffer.empty()) { APR_BUCKET_REMOVE(e); APR_BRIGADE_INSERT_TAIL(_tmpBB, apr_bucket_transient_create( _buffer.data(), _buffer.size(), _tmpBB->bucket_alloc)); APR_BRIGADE_INSERT_TAIL(_tmpBB, apr_bucket_flush_create(_tmpBB->bucket_alloc)); APR_BRIGADE_INSERT_TAIL(_tmpBB, apr_bucket_eos_create( _tmpBB->bucket_alloc)); _seenEOS = true; rv = ap_pass_brigade(f->next, _tmpBB); apr_brigade_cleanup(_tmpBB); return rv; } else { rv = ap_pass_brigade(f->next, _tmpBB); apr_brigade_cleanup(_tmpBB); if (rv != APR_SUCCESS) return rv; } return rv; } bool OutputFilter::readRequestLine(Reader &r) { while (!r.empty()) { if (_isWhiteSpace) { auto tmp = r.readChars<Reader::CharGroup<CharGroupId::WhiteSpace>>(); _buffer << tmp; auto tmp2 = tmp.readUntil<Reader::Chars<'\n'>>(); if (tmp2.is('\n')) { return true; } if (r.empty()) { return false; } _isWhiteSpace = false; } if (_subState == State::Protocol) { _buffer << r.readUntil<Reader::CharGroup<CharGroupId::WhiteSpace>>(); if (r.is<CharGroupId::WhiteSpace>()) { _nameBuffer.clear(); _isWhiteSpace = true; _subState = State::Code; } } else if (_subState == State::Code) { auto b = r.readChars<Reader::Range<'0', '9'>>(); _nameBuffer << b; _buffer << b; if (r.is<CharGroupId::WhiteSpace>()) { _nameBuffer << '\0'; _responseCode = apr_strtoi64(_nameBuffer.data(), NULL, 0); _isWhiteSpace = true; _subState = State::Status; } } else if (_subState == State::Status) { auto statusText = r.readUntil<Reader::Chars<'\n'>>(); _statusText = statusText.str(); string::trim(_statusText); _buffer << statusText; } else { r.readUntil<Reader::Chars<'\n', '\r'>>(); } if (r.is('\n') || r.is('\r')) { ++ r; _buffer << r.readChars<Reader::Chars<'\n', '\r'>>(); _state = State::Headers; _subState = State::HeaderName; _isWhiteSpace = true; return true; } } return false; } bool OutputFilter::readHeaders(Reader &r) { while (!r.empty()) { if (_subState == State::HeaderName) { _nameBuffer << r.readUntil<Reader::Chars<':', '\n'>>(); if (r.is('\n')) { r ++; _state = State::Body; return true; } else if (r.is<':'>()) { r ++; _isWhiteSpace = true; _subState = State::HeaderValue; } } else if (_subState == State::HeaderValue) { _buffer << r.readUntil<Reader::Chars<'\n'>>(); if (r.is('\n')) { r ++; auto key = _nameBuffer.str(); string::trim(key); auto value = _buffer.str(); string::trim(value); _headers.emplace(std::move(key), std::move(value)); _buffer.clear(); _nameBuffer.clear(); _subState = State::HeaderName; _isWhiteSpace = true; } } } return false; } data::Value OutputFilter::resultForRequest() { data::Value ret; ret.setBool(false, "OK"); ret.setInteger(apr_time_now(), "date"); ret.setInteger(_responseCode, "status"); ret.setString(std::move(_statusText), "message"); #if DEBUG if (!_request.getDebugMessages().empty()) { ret.setArray(std::move(_request.getDebugMessages()), "debug"); } #endif if (!_request.getErrorMessages().empty()) { ret.setArray(std::move(_request.getErrorMessages()), "errors"); } return ret; } NS_SA_END
[ "sbkarr@stappler.org" ]
sbkarr@stappler.org
266ead328b4029dd4af6b281a87f6949eb52560f
8a36937a2098e3eaae402e3ea473824c91dfc077
/Libs/dtkCoreSupport/dtkPluginManager.cpp
93d8d13e511689e456e34ef30a5dc33ec3f59be9
[]
no_license
huangguojun/mydtk
27b35143043bce72b950d2f4d2d44251e87b219f
6b23ab2db87e4aaa4f87c0a872a644c6d646723c
refs/heads/master
2023-06-25T01:43:50.667281
2021-07-26T06:54:35
2021-07-26T06:54:35
224,398,233
2
0
null
null
null
null
UTF-8
C++
false
false
13,092
cpp
/* dtkPluginManager.cpp --- * * Author: Julien Wintz * Copyright (C) 2008 - Julien Wintz, Inria. * Created: Tue Aug 4 12:20:59 2009 (+0200) * Version: $Id: b3bc20cb17f746daf0068ab69d9642c37f8eb20a $ * Last-Updated: mer. avril 2 08:45:01 2014 (+0200) * By: Nicolas Niclausse * Update #: 321 */ /* Commentary: * */ /* Change log: * */ #include "dtkPluginManager.h" #include "dtkPlugin.h" #include <QtWidgets> #include <dtkLog> // ///////////////////////////////////////////////////////////////// // Helper functions // ///////////////////////////////////////////////////////////////// QStringList dtkPluginManagerPathSplitter(QString path) { QString paths = path; #ifdef Q_OS_WIN QStringList pathList; QRegExp pathFilterRx("(([a-zA-Z]:|)[^:]+)"); int pos = 0; while ((pos = pathFilterRx.indexIn(paths, pos)) != -1) { QString pathItem = pathFilterRx.cap(1); pathItem.replace("\\", "/"); if (!pathItem.isEmpty()) pathList << pathItem; pos += pathFilterRx.matchedLength(); } #else QStringList pathList = paths.split(":", QString::SkipEmptyParts); #endif return pathList; } // ///////////////////////////////////////////////////////////////// // dtkPluginManagerPrivate // ///////////////////////////////////////////////////////////////// class dtkPluginManagerPrivate { public: bool check(const QString &path); public: QHash<QString, QVariant> names; QHash<QString, QVariant> versions; QHash<QString, QVariantList> dependencies; public: QString path; QHash<QString, QPluginLoader *> loaders; bool verboseLoading; int argc; char *argv; }; #include "dtkAbstractData.h" // #include <dtkMath/dtkVector.h> // #include <dtkMath/dtkVector3D.h> // #include <dtkMath/dtkQuaternion.h> dtkPluginManager *dtkPluginManager::instance(void) { if (!s_instance) { s_instance = new dtkPluginManager; qRegisterMetaType<dtkAbstractObject>("dtkAbstractObject"); qRegisterMetaType<dtkAbstractObject *>("dtkAbstractObject*"); qRegisterMetaType<dtkAbstractData>("dtkAbstractData"); qRegisterMetaType<dtkAbstractData *>("dtkAbstractData*"); // qRegisterMetaType<dtkVectorReal>("dtkVectorReal"); // qRegisterMetaType<dtkVectorReal*>("dtkVectorReal*"); // qRegisterMetaType<dtkVector3DReal>("dtkVector3DReal"); // qRegisterMetaType<dtkVector3DReal*>("dtkVector3DReal*"); // qRegisterMetaType<dtkQuaternionReal>("dtkQuaternionReal"); // qRegisterMetaType<dtkQuaternionReal*>("dtkQuaternionReal*"); } return s_instance; } bool dtkPluginManagerPrivate::check(const QString &path) { bool status = true; foreach (QVariant item, this->dependencies.value(path)) { QVariantMap mitem = item.toMap(); QVariant na_mitem = mitem.value("name"); QVariant ve_mitem = mitem.value("version"); QString key = this->names.key(na_mitem); if (!this->names.values().contains(na_mitem)) { dtkWarn() << " Missing dependency:" << na_mitem.toString() << "for plugin" << path; status = false; continue; } if (this->versions.value(key) != ve_mitem) { dtkWarn() << " Version mismatch:" << na_mitem.toString() << "version" << this->versions.value(this->names.key(na_mitem)).toString() << "but" << ve_mitem.toString() << "required for plugin" << path; status = false; continue; } if (!check(key)) { dtkWarn() << "Corrupted dependency:" << na_mitem.toString() << "for plugin" << path; status = false; continue; } } return status; } // ///////////////////////////////////////////////////////////////// // dtkPluginManager // ///////////////////////////////////////////////////////////////// void dtkPluginManager::initializeApplication(void) { d->argc = 1; d->argv = new char[13]; d->argv = (char *)"dtk-embedded"; (void)new QApplication(d->argc, &(d->argv)); } void dtkPluginManager::initialize(void) { if (d->path.isNull()) this->readSettings(); QStringList pathList = dtkPluginManagerPathSplitter(d->path); const QString appDir = qApp->applicationDirPath(); foreach (QString path, pathList) { QDir dir(appDir); if (dir.cd(path)) { dir.setFilter(QDir::AllEntries | QDir::NoDotAndDotDot); foreach (QFileInfo entry, dir.entryInfoList()) scan(entry.absoluteFilePath()); foreach (QFileInfo entry, dir.entryInfoList()) loadPlugin(entry.absoluteFilePath()); } else { dtkWarn() << "Failed to load plugins from path " << path << ". Could not cd to directory."; } } } void dtkPluginManager::uninitialize(void) { this->writeSettings(); foreach (QString path, d->loaders.keys()) unloadPlugin(path); } void dtkPluginManager::uninitializeApplication(void) { delete qApp; } void dtkPluginManager::scan(const QString &path) { if (!QLibrary::isLibrary(path)) return; QPluginLoader *loader = new QPluginLoader(path); d->names.insert(path, loader->metaData().value("MetaData").toObject().value("name").toVariant()); d->versions.insert( path, loader->metaData().value("MetaData").toObject().value("version").toVariant()); d->dependencies.insert(path, loader->metaData() .value("MetaData") .toObject() .value("dependencies") .toArray() .toVariantList()); delete loader; } //! Load a specific plugin designated by its name. /*! The path is retrieved through the plugin manager settings. * * \param name The name of the plugin, without platform specific prefix (.e.g * lib) and suffix (e.g. .so or .dylib or .dll) */ void dtkPluginManager::load(const QString &name) { if (d->path.isNull()) this->readSettings(); QStringList pathList = dtkPluginManagerPathSplitter(d->path); const QString appDir = qApp->applicationDirPath(); foreach (QString path, pathList) { QDir dir(appDir); if (dir.cd(path)) { dir.setFilter(QDir::AllEntries | QDir::NoDotAndDotDot); foreach (QFileInfo entry, dir.entryInfoList()) if (entry.fileName().contains(name)) loadPlugin(entry.absoluteFilePath()); } else { dtkWarn() << "Failed to load plugins from path " << path << ". Could not cd to directory."; } } } //! Unload a specific plugin designated by its name. /*! The path is retrieved through the plugin manager settings. * * \param name The name of the plugin, without platform specific prefix (.e.g * lib) and suffix (e.g. .so or .dylib or .dll) */ void dtkPluginManager::unload(const QString &name) { if (d->path.isNull()) this->readSettings(); QStringList pathList = dtkPluginManagerPathSplitter(d->path); const QString appDir = qApp->applicationDirPath(); foreach (QString path, pathList) { QDir dir(appDir); if (dir.cd(path)) { dir.setFilter(QDir::AllEntries | QDir::NoDotAndDotDot); foreach (QFileInfo entry, dir.entryInfoList()) if (entry.fileName().contains(name)) if (this->plugin(name)) this->unloadPlugin(entry.absoluteFilePath()); } else { dtkWarn() << "Failed to load plugins from path " << path << ". Could not cd to directory."; } } } void dtkPluginManager::readSettings(void) { QSettings settings("inria", "dtk"); QString defaultPath; QDir plugins_dir; #ifdef Q_OS_MAC plugins_dir = qApp->applicationDirPath() + "/../PlugIns"; #else plugins_dir = qApp->applicationDirPath() + "/../plugins"; #endif defaultPath = plugins_dir.absolutePath(); settings.beginGroup("plugins"); if (!settings.contains("path")) { dtkDebug() << "Filling in empty path in settings with default path:" << defaultPath; settings.setValue("path", defaultPath); } d->path = settings.value("path", defaultPath).toString(); settings.endGroup(); if (d->path.isEmpty()) { dtkWarn() << "Your dtk config does not seem to be set correctly."; dtkWarn() << "Please set plugins.path."; } } void dtkPluginManager::writeSettings(void) { // QSettings settings("inria", "dtk"); // settings.beginGroup("plugins"); // settings.setValue("path", d->path); // settings.endGroup(); } void dtkPluginManager::printPlugins(void) { foreach (QString path, d->loaders.keys()) qDebug() << path; } void dtkPluginManager::setVerboseLoading(bool value) { d->verboseLoading = true; } bool dtkPluginManager::verboseLoading(void) const { return d->verboseLoading; } dtkPlugin *dtkPluginManager::plugin(const QString &name) { foreach (QPluginLoader *loader, d->loaders) { dtkPlugin *plugin = qobject_cast<dtkPlugin *>(loader->instance()); if (plugin->name() == name) return plugin; } return NULL; } QList<dtkPlugin *> dtkPluginManager::plugins(void) { QList<dtkPlugin *> list; foreach (QPluginLoader *loader, d->loaders) list << qobject_cast<dtkPlugin *>(loader->instance()); return list; } void dtkPluginManager::setPath(const QString &path) { d->path = path; } QString dtkPluginManager::path(void) const { return d->path; } dtkPluginManager::dtkPluginManager(void) : d(new dtkPluginManagerPrivate) { d->verboseLoading = false; d->argv = NULL; } dtkPluginManager::~dtkPluginManager(void) { if (d->argv) { delete d->argv; } delete d; d = NULL; } /*! \brief Loads the plugin from the given filename. Derived classes may override to prevent certain plugins being loaded, or provide additional functionality. In most cases they should still call the base implementation (this). \param path : Path to plugin file to be loaded. */ void dtkPluginManager::loadPlugin(const QString &path) { if (!d->check(path)) { QString error = "check failure for plugin file " + path; if (d->verboseLoading) { dtkWarn() << error; } return; } QPluginLoader *loader = new QPluginLoader(path); loader->setLoadHints(QLibrary::ExportExternalSymbolsHint); if (!loader->load()) { QString error = "Unable to load "; error += path; error += " - "; error += loader->errorString(); if (d->verboseLoading) { dtkWarn() << error; } emit loadError(error); delete loader; return; } dtkPlugin *plugin = qobject_cast<dtkPlugin *>(loader->instance()); if (!plugin) { QString error = "Unable to retrieve "; error += path; if (d->verboseLoading) { dtkWarn() << error; } emit loadError(error); return; } if (!plugin->initialize()) { QString error = "Unable to initialize "; error += plugin->name(); error += " plugin"; if (d->verboseLoading) { dtkWarn() << error; } emit loadError(error); return; } d->loaders.insert(path, loader); if (d->verboseLoading) { dtkTrace() << "Loaded plugin " << plugin->name() << " from " << path; } emit loaded(plugin->name()); } //! Unloads the plugin previously loaded from the given filename. /*! Derived classes may override to prevent certain plugins being * unloaded, or provide additional functionality. In most * cases they should still call the base implementation * (this). * * \param path Path to plugin file to be unloaded. */ void dtkPluginManager::unloadPlugin(const QString &path) { dtkPlugin *plugin = qobject_cast<dtkPlugin *>(d->loaders.value(path)->instance()); if (!plugin) { if (d->verboseLoading) { dtkDebug() << "dtkPluginManager - Unable to retrieve " << plugin->name() << " plugin"; } return; } if (!plugin->uninitialize()) { if (d->verboseLoading) { dtkTrace() << "Unable to uninitialize " << plugin->name() << " plugin"; } return; } QPluginLoader *loader = d->loaders.value(path); if (!loader->unload()) { if (d->verboseLoading) { dtkDebug() << "dtkPluginManager - Unable to unload plugin: " << loader->errorString(); } return; } delete loader; d->loaders.remove(path); // emit unloaded(plugin->name()); } dtkPluginManager *dtkPluginManager::s_instance = NULL;
[ "guojun.huang@qq.com" ]
guojun.huang@qq.com
2ceaa7546c0cc1aeb090345263b7da1be8717968
6b7cb5e1a66f4af9ea0a8b675a6abb8f6927b9fc
/src/19_RoboFightDesign/RoboFightWithFrontend/Robo.h
f84251062b8c1fb13adc3f0153ed11fc1ee650b9
[]
no_license
supercaracal/game-programmer-book-build
dc405763ed255e81ea8244d2c48dc24a8d98293e
c9e1f65cab3f59a4d552128d0ee22233d79b2773
refs/heads/master
2022-06-10T14:17:00.122380
2020-04-29T04:03:14
2020-04-29T04:03:14
259,812,505
1
0
null
2020-04-29T03:14:35
2020-04-29T03:14:34
null
SHIFT_JIS
C++
false
false
2,805
h
#ifndef INCLUDED_ROBO_H #define INCLUDED_ROBO_H #include "Library/Vector3.h" class Matrix34; class Matrix44; class GraphicsDatabase; class Model; class Bullet; class Robo{ public: Robo( int id ); //番号もらう。自分が何番か知りたいので。 ~Robo(); void draw( const Matrix44& perspectiveViewMatrix ) const; void update( Robo* robo ); void setPosition( const Vector3& ); void setAngleY( double ); const Vector3* position() const; void getViewMatrix( Matrix34* ) const; void setDamage( int damage ); int hitPoint() const; int energy() const; bool isLockOn() const; static const int mJumpUpTime; //上昇していく時間 static const int mJumpStayTime; //上昇後下降までの時間 static const int mJumpFallTime; //下降にかかる時間 static const int mMoveAccelEndCount; //歩き始めて加速が終了するまでの時間 static const double mMaxMoveSpeed; //最大移動速度 static const double mJumpHeight; //最大高度 static const int mCameraDelayCount; //ジャンプ開始後何フレームで敵の方を向くか static const double mCameraDistanceZ; //何メートル後ろから写す? static const double mCameraDistanceY; //見下ろし具合 static const double mCameraTargetDistanceZ; //注視点は何メートル先? static const double mTurnSpeed; //旋回速度 static const int mMaxHitPoint; //最大ヒットポイント static const int mMaxEnergy; //武器ポイント最大値 static const int mEnergyPerBullet; //一発あたりの消費エネルギー static const int mEnergyCharge; //毎フレーム溜まるエネルギー static const double mLockOnAngleIn; //ロックオンする角度 static const double mLockOnAngleOut; //ロックオンする角度 private: void move( bool left, bool right, bool up, bool down ); void turn( bool left, bool right ); //思考ルーチン。ボタン入力を返す。プレイヤー操作キャラならただ入力を取るだけ void think( bool* jump, bool* fire, bool* turn, bool* left, bool* right, bool* up, bool* down ) const; Vector3 mPosition; double mAngleY; int mId; GraphicsDatabase* mDatabase; Model* mModel; Bullet* mBullets; int mBulletNumber; int mCameraCount; int mCount; //移動開始後何フレーム経った? Vector3 mVelocity; //現在の平面速度 double mAngleVelocityY; //振り向き速度 enum Mode{ MODE_JUMP_UP, //ジャンプ上昇中 MODE_JUMP_STAY, //ジャンプ上空で停止中 MODE_JUMP_FALL, //ジャンプ降下中 MODE_ON_LAND, //着地してる }; Mode mMode; int mHitPoint; //体力 int mEnergy; //武器を撃つのに必要なエネルギー bool mLockOn; //ロックオンしてますか? }; #endif
[ "slash@watery.dip.jp" ]
slash@watery.dip.jp
80810640384abdf4166334be5f116b773f7463a2
6eaf9fd1d55e07addb1f5f53bfe919c02d0ef6ce
/loop_closure/main.cpp
8239adb2d142a5fe78ca56d258d21be24e11f3c0
[]
no_license
tys17/SLAM
50054596534134106c0e41f0d1aa057646de2f77
186f99d12c4ccb232934b0329b3baca08291b6a5
refs/heads/master
2021-05-06T13:33:49.280846
2017-12-05T05:11:49
2017-12-05T05:11:49
null
0
0
null
null
null
null
UTF-8
C++
false
false
9,484
cpp
#include <iostream> // opencv #include "opencv2/core.hpp" #include "opencv2/features2d.hpp" #include "opencv2/imgcodecs.hpp" #include "opencv2/highgui.hpp" #include "opencv2/calib3d.hpp" #include "opencv2/calib3d/calib3d_c.h" #include "opencv2/video/tracking.hpp" #include "opencv2/imgproc.hpp" #include "opencv2/videoio.hpp" // DBoW3 #include "DBoW3/DBoW3.h" //ceres-solver #include "ceres/ceres.h" #include "ceres/rotation.h" #include "fileIO.h" #include "Tracking.h" #include "Database.h" using namespace std; using namespace cv; #define PIX_THREH 2 vector<KeyPoint> convertToKeyPoints(vector<Point2f>& data){ vector<KeyPoint> res; for (size_t i = 0; i < data.size(); i++) { res.push_back(cv::KeyPoint(data[i], 1.f)); } return res; } int main() { double RansacThreshold = PIX_THREH; //DBoW3::Vocabulary voc("/home/jianwei/code/SLAM/loop_closure/orbvoc.dbow3"); //DBoW3::Vocabulary voc("/home/jianwei/code/SLAM/loop_closure/built_voc.yml.gz"); DBoW3::Vocabulary voc("/home/jianwei/code/SLAM/loop_closure/test.dbow3"); Database db(voc); int debug_LoopCount = 0; fileIO fIO; vector <string> files=fIO.loadImages("/home/jianwei/code/SLAM/data/rgb"); int interval = 1; int i = 0; vector<Mat> Orientations, poss, Rs; Mat BenchMarkFrame= imread(files[i]); //For Iphone Image //Rect Template(161, 0, 960, 720); //imshow("0", BenchMarkFrame); //CurFrame = CurFrame(Template); resize(BenchMarkFrame, BenchMarkFrame, Size(640, 480)); //Mat gray; //cvtColor(BenchMarkFrame, gray, COLOR_BGR2GRAY); //imshow("1", gray); //waitKey(0); Mat PreFrame, CurFrame; vector<Point2f> BenchMarkPoints; Tracking tracker; tracker.RansacThreshold = PIX_THREH; Mat CurDescriptors; tracker.ExtractORBFeature(BenchMarkFrame, BenchMarkPoints, CurDescriptors); vector<Point2f> CurPoints(BenchMarkPoints.size()), PrePoints; copy(BenchMarkPoints.begin(), BenchMarkPoints.end(), CurPoints.begin()); BenchMarkFrame.copyTo(CurFrame); Mat K = tracker.defineIntrinsic(); Mat Kt = K.t(); i += interval; double focal = 517; Mat CurOrientation(4, 1, CV_64FC1), PreOrientation(4, 1, CV_64FC1), Curpos(3, 1, CV_64FC1), Prepos(3, 1, CV_64FC1); Mat CurR(3, 3, CV_64FC1), PreR(3, 3, CV_64FC1), CurT(3, 1, CV_64FC1), PreT(3, 1, CV_64FC1); //Initialization For RGB Dataset CurOrientation.at<double>(0, 0) = 0.8596; CurOrientation.at<double>(1, 0) = -0.3534; CurOrientation.at<double>(2, 0) = 0.0838; CurOrientation.at<double>(3, 0) = -0.3594; Curpos.at<double>(0, 0) = 0.4388; Curpos.at<double>(1, 0) = -0.4332; Curpos.at<double>(2, 0) = 1.4779; //Initialization For Iphone /*CurOrientation.at<double>(0, 0) = 1; CurOrientation.at<double>(1, 0) = 0; CurOrientation.at<double>(2, 0) = 0; CurOrientation.at<double>(3, 0) = 0; Curpos.at<double>(0, 0) = 0; Curpos.at<double>(1, 0) = 0; Curpos.at<double>(2, 0) = 0;*/ CurR = tracker.QuaternionToMatrix(CurOrientation).t(); CurT = -1 * CurR*Curpos; Orientations.push_back(CurOrientation); //Rs.push_back(CurR); Mat tempt(1, 3, CV_64FC1); tempt = Curpos.clone(); poss.push_back(tempt); //poss.push_back(Curpos); //int q = 1; int BenchMarkFlag = 1; /*// convert point2f to keypoints vector<KeyPoint> CurKeyPoints = convertToKeyPoints(CurPoints); Mat CurDescriptors; Ptr<ORB> orb = ORB::create(1000, 2, 4, 5, 0, 2, ORB::HARRIS_SCORE, 5); orb->compute(CurFrame, CurKeyPoints, CurDescriptors);*/ // build a keyframe vector<int> feature_ids; int CurFrameID = 0; cv::Ptr<cv::Feature2D> fdetector; fdetector=cv::ORB::create(); Mat debug_CurDescriptors; vector<KeyPoint> debug_KeyPoints; fdetector->detectAndCompute(CurFrame, cv::Mat(), debug_KeyPoints, debug_CurDescriptors); //KeyFrame keyframe(feature_ids, CurDescriptors, CurFrameID, CurR, CurT); KeyFrame keyframe(feature_ids, debug_CurDescriptors, CurFrameID, CurR, CurT); CurFrameID++; // add a keyframe to database db.addKeyframe(keyframe); while (i < files.size()) { CurFrame.copyTo(PreFrame); CurFrame = imread(files[i]); resize(CurFrame, CurFrame, Size(640, 480)); PrePoints.clear(); PrePoints.resize(CurPoints.size()); copy(CurPoints.begin(), CurPoints.end(), PrePoints.begin()); //Check if CurPoints could have a size nonzero tracker.LKCorrespondence(PreFrame, CurFrame, PrePoints, CurPoints); if (BenchMarkFlag == 1) { BenchMarkPoints.clear(); BenchMarkPoints.resize(PrePoints.size()); copy(PrePoints.begin(), PrePoints.end(), BenchMarkPoints.begin()); BenchMarkFlag = 0; //cout << i << endl; } Mat fundamental_matrix = tracker.Triangulate(PrePoints, CurPoints); // Show the match between two adjacent frames //Show Epipolar Lines: if (1) { std::vector <cv::Vec3f> lines1; computeCorrespondEpilines(PrePoints, 1, fundamental_matrix, lines1); Mat Show; CurFrame.copyTo(Show); for (std::vector<cv::Vec3f>::const_iterator it = lines1.begin(); it != lines1.end(); ++it) { // Draw the line between first and last column cv::line(Show, cv::Point(0, -(*it)[2] / (*it)[1]), cv::Point(Show.cols, -((*it)[2] + (*it)[0] * Show.cols) / (*it)[1]), cv::Scalar(0, 255, 0)); } imwrite(to_string(i)+".jpg", Show);; } Mat E = Kt*fundamental_matrix*K; Mat TemptR, TemptT, Ori_, Pos_relative; Curpos.copyTo(Prepos); CurOrientation.copyTo(PreOrientation); CurR.copyTo(PreR); CurT.copyTo(PreT); Point2d tmp(K.at<double>(0, 2), K.at<double>(1, 2)); recoverPose(E, PrePoints, CurPoints, TemptR, TemptT, focal, tmp); //If the outputs are the orientation and the position. CurR = TemptR*PreR; CurOrientation = tracker.MatrixToQuaternion(CurR.t()); Curpos = -1 * tracker.QuaternionToMatrix(PreOrientation)*TemptR.inv()*TemptT + Prepos; CurT =-1* CurR*Curpos; double PointsRatio = double(CurPoints.size()) / double(BenchMarkPoints.size()); if (PointsRatio < 0.6|| CurPoints.size()<80) { //size changes BenchMarkPoints.clear(); CurFrame.copyTo(BenchMarkFrame); //Mat CurDescriptors; tracker.ExtractORBFeature(BenchMarkFrame, BenchMarkPoints, CurDescriptors); CurPoints.clear(); CurPoints.resize(BenchMarkPoints.size()); copy(BenchMarkPoints.begin(), BenchMarkPoints.end(), CurPoints.begin()); BenchMarkFlag = 1; } Orientations.push_back(CurOrientation); Mat tempt(1, 3, CV_64FC1); tempt=Curpos.clone(); poss.push_back(tempt); i += interval; /*// convert point2f to keypoints vector<KeyPoint> CurKeyPoints = convertToKeyPoints(CurPoints); Ptr<ORB> orb = ORB::create(1000, 2, 4, 5, 0, 2, ORB::HARRIS_SCORE, 5); orb->compute(CurFrame, CurKeyPoints, CurDescriptors);*/ // build a keyframe //feature_ids fdetector->detectAndCompute(CurFrame, cv::Mat(), debug_KeyPoints, debug_CurDescriptors); //KeyFrame keyframe(feature_ids, CurDescriptors, CurFrameID, CurR, CurT); KeyFrame keyframe(feature_ids, debug_CurDescriptors, CurFrameID, CurR, CurT); //KeyFrame keyframe(feature_ids, CurDescriptors, CurFrameID, CurR, CurT); CurFrameID++; // detect loop closure int startID = db.detectLoop(keyframe); if (startID != -1){ // loop detected cout << debug_LoopCount << ": " << startID << " and " << CurFrameID << endl; debug_LoopCount++; } // add a keyframe to database db.addKeyframe(keyframe); } ofstream location_out; string filename; filename = "Interval=" + to_string(interval) + "_Ransac=" + to_string(RansacThreshold) + ".txt"; location_out.open(filename, std::ios::out | std::ios::app); if (!location_out.is_open()) return 0; int num = Orientations.size(); location_out << num << endl; for (int j = 0; j < num; j++) { Mat Tempt = tracker.QuaternionToMatrix(Orientations[j]); location_out << K.at<double>(0, 0) << " " << K.at<double>(0, 1) << " " << K.at<double>(0, 2) << " " << K.at<double>(1, 0) << " " << K.at<double>(1, 1) << " " << K.at<double>(1, 2) << " " << K.at<double>(2, 0) << " " << K.at<double>(2, 1) << " " << K.at<double>(2, 2) << " "; location_out << Tempt.at<double>(0, 0) << " " << Tempt.at<double>(0, 1) << " " << Tempt.at<double>(0, 2) << " " << Tempt.at<double>(1, 0) << " " << Tempt.at<double>(1, 1) << " " << Tempt.at<double>(1, 2) << " " << Tempt.at<double>(2, 0) << " " << Tempt.at<double>(2, 1) << " " << Tempt.at<double>(2, 2) << " "; location_out << poss[j].at<double>(0, 0) << " " << poss[j].at<double>(1, 0) << " " << poss[j].at<double>(2, 0) << " "; location_out << 640 << " " << 480 << endl; } location_out.close(); return 0; }
[ "fjw_thu@163.com" ]
fjw_thu@163.com
9b84ab71d86264a7a36ef7da255499280d69c1d0
6fa38520d36225ea164da9f4466750faa98de7df
/clearBoard/clearBoard.ino
3f252d67b12ce1371895fe7b49f48986492a2fb4
[]
no_license
kailonfok/AER201
4a22a2fbb2553a5be6299d350a45c69e4d8e7a74
427947c42bdb2eda1ca5ebbe410a4582c4cc4ff0
refs/heads/master
2016-09-11T09:36:56.536805
2015-04-06T19:44:27
2015-04-06T19:44:27
29,438,272
0
0
null
null
null
null
UTF-8
C++
false
false
15,013
ino
#include <AFMotor.h> #include <Servo.h> //define objects for motors AF_DCMotor frontMotor(1); AF_DCMotor leftMotor(2); AF_DCMotor backMotor(3); AF_DCMotor rightMotor(4); // Define pins for wing pins const byte frontSwitchPin = 34; const byte leftSwitchPin = 33; const byte rightSwitchPin = 32; int leftSwitchVal, rightSwitchVal, frontSwitchVal; const byte echoPin[] = {46, 48, 50, 52}; const byte trigPin[] = {47, 49, 51, 53}; const float distanceConstant = 58.2; byte maxRange = 30; long duration, distance; byte dir = 2; byte sensorNum = 1; // Define servo objects Servo leftServo; Servo rightServo; Servo armServo; Servo frontServo; byte leftPos = 0; // Starting positions for servo claws byte rightPos = 180; byte armPos = 180; byte frontPos = 100; boolean onOff = 1; boolean start; boolean rotated = 0; boolean inPosition = 0; boolean enableState = 0; boolean prevEnableState = 0; byte switchKeepDriving = 1; char incomingByte = 0; int counter = 0; int xpos[2]; int tempValue = 0; int rotatingSpeed1 = 245; int rotatingSpeed2 = 235; int motorSpeeds[] = {100, 250, 255, 210}; int numBallsLeft[] = {6, 6, 7}; int index = 0; void setup() { Serial.begin(9600); pinMode(leftSwitchPin, INPUT); pinMode(rightSwitchPin, INPUT); pinMode(frontSwitchPin, INPUT); armServo.attach(42); leftServo.attach(41); rightServo.attach(40); frontServo.attach(39); frontServo.write(frontPos); for (int i = 0; i < 4; i++) { pinMode(echoPin[i], INPUT); pinMode(trigPin[i], OUTPUT); } frontMotor.run(RELEASE); leftMotor.run(RELEASE); backMotor.run(RELEASE); rightMotor.run(RELEASE); leftServo.write(leftPos); rightServo.write(rightPos); armServo.write(armPos); } void loop() { enableState = digitalRead(frontSwitchPin); delay(1); if (enableState != prevEnableState) // if button is pressed and released { if (enableState) // if switched to on { start = 1; } } if (numBallsLeft[2] == 0) { start = 0; } if (!start) { tempValue = 0; if (Serial.available() > 0) { while (true) { incomingByte = Serial.read(); if (incomingByte == '\n') break; tempValue *= 10; tempValue += (int) (incomingByte - '0'); } if(counter < 2) { xpos[counter] = tempValue; } else { motorSpeeds[counter-2] = tempValue; } counter++; } Serial.print("FMS: "); Serial.println(motorSpeeds[0]); } else { if (index != 2) { if (!rotated) { rightSwitchVal = digitalRead(rightSwitchPin); delay(1); if (numBallsLeft[0] == 6) // only for very initial retrieval { if (!rightSwitchVal) { leftMotor.setSpeed(245); rightMotor.setSpeed(245); rightMotor.run(BACKWARD); leftMotor.run(BACKWARD); } else { rotateIn(); } } else { leftSwitchVal = digitalRead(leftSwitchPin); delay(1); rightSwitchVal = digitalRead(rightSwitchPin); delay(1); if (!leftSwitchVal && !rightSwitchVal) // modify later for a state variable, to account for opposite hopper { //Every iteration, check distance to wall sensor(sensorNum); // function call to determine if at wall or not keepDriving(switchKeepDriving); Serial.println("I'm confused"); } else { rotateIn(); } } } else { if (dir == 2) // first retrieve the ball { dir = closeClaw(); // change direction to forward if (index == 0) rotateOutRight(); else rotateOutLeft(); liftFrontServo(-1); } else { if (!inPosition) { if(waitForBump()) { if (moveArm(-1)) { if (index == 0) { dir = 1; sensorNum = 1; } else { dir = 3; sensorNum = 3; } movement(dir); do { sensor(sensorNum); }while(distance >= 4); turnMotorsOff(); movement(2); delay(300); turnMotorsOff(); maxRange = 50; if (numBallsLeft[0] != 0) { sensorNum = 1; dir = 3; } else { sensorNum = 3; dir = 1; } movement(dir); do { sensor(sensorNum); } while (distance <= maxRange); turnMotorsOff(); maxRange = 5; inPosition = 1; } } } else { if(waitForBump()) { if (armPos == 0) { if (openClaw()) { moveArm(1); liftFrontServo(1); Serial.print("Direction: "); Serial.println(dir); Serial.print("Num balls left: "); Serial.println(numBallsLeft[index]); delay(2000); } } } } } } } else { if (xpos[0] == 1) { movement(1); do { sensor(1); } while (distance <= xpos[1]); dir = 3; sensorNum = 1; } else { movement(3); do { sensor(3); } while (distance <= xpos[1]); dir = 1; sensorNum = 3; } turnMotorsOff(); movement(2); do { rightSwitchVal = digitalRead(rightSwitchPin); leftSwitchVal = digitalRead(leftSwitchPin); } while (!rightSwitchVal && !leftSwitchVal); turnMotorsOff(); closeClaw(); liftFrontServo(-1); waitForBump(); if (moveArm(-1)) { movement(2); delay(300); turnMotorsOff(); maxRange = 55; movement(dir); do { sensor(sensorNum); } while (distance <= maxRange); turnMotorsOff(); waitForBump(); // delay(1000); if (armPos == 0) { if (openClaw()) { moveArm(1); liftFrontServo(1); } } } } } } // Function to turn off motors, before switching directions void turnMotorsOff() { // Write low to all enable pins on H-bridge (0 volts) frontMotor.run(RELEASE); leftMotor.run(RELEASE); backMotor.run(RELEASE); rightMotor.run(RELEASE); // Serial.println("Motors off?"); delay(1000); } boolean waitForBump() { int currentTime, prevTime; movement(0); while(true) { frontSwitchVal = digitalRead(frontSwitchPin); if(frontSwitchVal) { prevTime = millis(); do { Serial.println("Stuck"); currentTime = millis(); frontSwitchVal = digitalRead(frontSwitchPin); if(!frontSwitchVal) { return 0; } }while(frontSwitchVal && (currentTime - prevTime <= 2000)); turnMotorsOff(); return 1; } } } void keepDriving(byte lessGreater) { if (lessGreater == 1) { if (distance <= maxRange && distance != 0) { turnMotorsOff(); if (dir == 0) { if (index == 0) { dir = 3; sensorNum = 1; } else { dir = 1; sensorNum = 3; } maxRange = 55; switchKeepDriving = 0; } else if (dir == 1) { sensorNum = 0; dir = 2; } else if (dir == 3) { sensorNum = 0; dir = 2; } } else if (distance >= maxRange) { movement(dir); } } else { if (distance >= maxRange) { turnMotorsOff(); if (dir == 3) { dir = 1; inPosition = 1; maxRange = 5; } else if (dir == 1) { dir = 3; inPosition = 1; maxRange = 5; } } else if (distance <= maxRange) { movement(dir); } } } void movement(int motorDirection)//0 is forward, 1 is right, 2 is back, 3 is left, -1 is nothing { byte oneTwo = 0; // direct motors to turn in appropriate direction and speed if (motorDirection == 0) { oneTwo = 1; } else if (motorDirection == 1) { oneTwo = 2; } else if (motorDirection == 2) { oneTwo = 2; } else { oneTwo = 1; } if (motorDirection == 0 || motorDirection == 2) { byte speed1 = 250; byte speed2 = 210; if (index == 0) { leftMotor.setSpeed(motorSpeeds[1]); rightMotor.setSpeed(motorSpeeds[3]); } else if (index == 1) { leftMotor.setSpeed(motorSpeeds[3]); rightMotor.setSpeed(motorSpeeds[1]); } else { leftMotor.setSpeed(235); rightMotor.setSpeed(235); } leftMotor.run(oneTwo); rightMotor.run(oneTwo); } else if (motorDirection == 1 || motorDirection == 3) { frontMotor.setSpeed(motorSpeeds[0]); backMotor.setSpeed(motorSpeeds[2]); frontMotor.run(oneTwo); backMotor.run(oneTwo); } else { Serial.println("Don't need to move"); turnMotorsOff(); } } void rotateIn() { int speed1 = 240; int speed2 = 150; turnMotorsOff(); if (numBallsLeft[0] == 6 || index == 1) { rightSwitchVal = digitalRead(rightSwitchPin); rightMotor.setSpeed(speed1); frontMotor.setSpeed(speed2); rightMotor.run(BACKWARD); frontMotor.run(BACKWARD); do { Serial.println("rotating"); leftSwitchVal = digitalRead(leftSwitchPin); } while (!leftSwitchVal); turnMotorsOff(); leftMotor.setSpeed(speed1); frontMotor.setSpeed(speed2); leftMotor.run(BACKWARD); frontMotor.run(FORWARD); do { Serial.println("Aligning"); rightSwitchVal = digitalRead(rightSwitchPin); } while (!rightSwitchVal); } else { leftSwitchVal = digitalRead(leftSwitchPin); leftMotor.setSpeed(speed1); frontMotor.setSpeed(speed2); leftMotor.run(BACKWARD); frontMotor.run(FORWARD); do { Serial.println("rotating"); rightSwitchVal = digitalRead(rightSwitchPin); } while (!rightSwitchVal); turnMotorsOff(); rightMotor.setSpeed(speed1); frontMotor.setSpeed(speed2); rightMotor.run(BACKWARD); frontMotor.run(BACKWARD); do { Serial.println("Aligning"); leftSwitchVal = digitalRead(leftSwitchPin); } while (!leftSwitchVal); } turnMotorsOff(); movement(2); do { rightSwitchVal = digitalRead(rightSwitchPin); delay(1); leftSwitchVal = digitalRead(leftSwitchPin); delay(1); } while (!rightSwitchVal || !leftSwitchVal); turnMotorsOff(); rotated = 1; } void rotateOutRight() { int currentTime = millis(); int previousTime = currentTime; leftMotor.setSpeed(rotatingSpeed1); frontMotor.setSpeed(rotatingSpeed2); leftMotor.run(FORWARD); frontMotor.run(BACKWARD); do { Serial.println("rotating out"); currentTime = millis(); // sensor(1); } while (currentTime - previousTime <= 2000); // }while(distance <= 5); previousTime = currentTime; turnMotorsOff(); leftMotor.setSpeed(rotatingSpeed2); backMotor.setSpeed(rotatingSpeed1); leftMotor.run(BACKWARD); backMotor.run(BACKWARD); do { Serial.println("Back to wall"); currentTime = millis(); } while (currentTime - previousTime <= 2000); turnMotorsOff(); } void rotateOutLeft() { int currentTime = millis(); int previousTime = currentTime; rightMotor.setSpeed(rotatingSpeed1); frontMotor.setSpeed(rotatingSpeed2); rightMotor.run(FORWARD); frontMotor.run(FORWARD); do { Serial.println("rotating out"); currentTime = millis(); // sensor(3); } while (currentTime - previousTime <= 2000); // }while(distance <= 5); previousTime = currentTime; turnMotorsOff(); rightMotor.setSpeed(rotatingSpeed2); backMotor.setSpeed(rotatingSpeed1); rightMotor.run(BACKWARD); backMotor.run(FORWARD); do { Serial.println("Back to wall"); currentTime = millis(); } while (currentTime - previousTime <= 2000); turnMotorsOff(); } void sensor(int sensorNum) { digitalWrite(trigPin[sensorNum], LOW); delayMicroseconds(2); digitalWrite(trigPin[sensorNum], HIGH); delayMicroseconds(10); digitalWrite(trigPin[sensorNum], LOW); duration = pulseIn(echoPin[sensorNum], HIGH); //Calculate the distance (in cm) based on the speed of sound. distance = duration / distanceConstant; delay(50); } //Functions for depositing ball start here boolean moveArm(int upDown) // -1 for up, 1 for down { boolean value; boolean exit = 1; // loop until all the way up/down if (upDown == -1) { Serial.println("Raising arm"); } else if (upDown == 1) { Serial.println("Lowering arm"); } do { armServo.write(armPos); delay(15); armPos += upDown; Serial.println("Stuck??"); if (armPos == 0 || armPos == 180) exit = 0; } while (exit == 1); Serial.println("Reaching end of loop"); if (upDown == -1) { value = 1; } else if (upDown == 1) { value = 0; inPosition = 0; rotated = 0; numBallsLeft[index] -= 1; if (numBallsLeft[index] == 0) { index++; } if (index == 0) { dir = 1; sensorNum = 1; } else if (index == 1) { dir = 3; sensorNum = 3; } switchKeepDriving = 1; } return value; } boolean openClaw() { Serial.println("Opening claw"); do // loop to open the claws (left and right claws go 180 degrees) { leftServo.write(leftPos); rightServo.write(rightPos); delay(15); //increment/decrement the right and left claw positions each iteration rightPos++; leftPos--; } while (leftPos != 0 && rightPos != 180); return 1; } int closeClaw() { Serial.println("Closing claw"); do // loop to close the claws (left and right claws go 180 degrees) { leftServo.write(leftPos); delay(15); rightServo.write(rightPos); rightPos--; leftPos++; } while (leftPos != 90 && rightPos != 90); return 0; } void liftFrontServo(int upDown) { boolean exit = 1; do { frontServo.write(frontPos); delay(15); frontPos += upDown; if (frontPos == 5 || frontPos == 100) exit = 0; } while (exit == 1); }
[ "dknight_77@hotmail.com" ]
dknight_77@hotmail.com
b056f6ef6dce2a3234821e94b31fdb0636645ab8
dbf16f6522ae46d6cffd75577d76bffd1cbeaeb1
/Src/Modules/Infrastructure/RobotHealthProvider.cpp
9f5dd8263c7f6e76103ad0643c1ce434092f6972
[]
no_license
RomanMichna/diplomovka
df6e48f43f2b91407f63e7f100f7e10e16b5d52c
c3f090fe2662cc34f8ecc65ee14e1555695c0f54
refs/heads/master
2021-01-10T15:31:48.017316
2013-04-09T11:32:41
2013-04-09T11:32:41
8,552,952
3
0
null
null
null
null
UTF-8
C++
false
false
4,377
cpp
/** * @file Modules/Infrastructure/RobotHealthProvider.h * This file implements a module that provides information about the robot's health. * @author <a href="mailto:timlaue@informatik.uni-bremen.de">Tim Laue</a> */ #include "RobotHealthProvider.h" #include "Tools/Settings.h" #include "Tools/Debugging/ReleaseOptions.h" #include "Platform/SoundPlayer.h" #include "Tools/Streams/InStreams.h" RobotHealthProvider::RobotHealthProvider() : lastExecutionTime(0), lastRelaxtHealthComputation(0), startBatteryLow(0), lastBatteryLevel(1), batteryVoltageFalling(false), highTemperatureSince(0), lastBodyTemperatureReadTime(0), lastWlanCheckedTime(0) { p.batteryLow = 5; p.temperatureHigh = 79; InConfigFile stream("health.cfg"); if(stream.exists()) stream >> p; } void RobotHealthProvider::update(RobotHealth& robotHealth) { // count percepts if(theBallPercept.ballWasSeen) ++robotHealth.ballPercepts; robotHealth.linePercepts += theLinePercept.lines.size(); robotHealth.goalPercepts = theGoalPercept.goalPosts.size(); // Transfer information from other process: robotHealth = theMotionRobotHealth; // Compute frame rate of cognition process: unsigned now = SystemCall::getCurrentSystemTime(); if(lastExecutionTime != 0) timeBuffer.add(now - lastExecutionTime); robotHealth.cognitionFrameRate = timeBuffer.getSum() ? 1000.0f / (static_cast<float>(timeBuffer.getSum()) / timeBuffer.getNumberOfEntries()) : 0.0f; lastExecutionTime = now; // read cpu and mainboard temperature #ifdef TARGET_ROBOT if(theFrameInfo.getTimeSince(lastBodyTemperatureReadTime) > 10 * 1000) { lastBodyTemperatureReadTime = theFrameInfo.time; float cpuTemperature, mbTemperature; naoBody.getTemperature(cpuTemperature, mbTemperature); robotHealth.cpuTemperature = (unsigned char)cpuTemperature; robotHealth.boardTemperature = (unsigned char)mbTemperature; } if(theFrameInfo.getTimeSince(lastWlanCheckedTime) > 10 * 1000) { lastWlanCheckedTime = theFrameInfo.time; robotHealth.wlan = naoBody.getWlanStatus(); } #endif if(theFrameInfo.getTimeSince(lastRelaxtHealthComputation) > 5000) { lastRelaxtHealthComputation = theFrameInfo.time; // transfer temperature and batteryLevel data directly from SensorData: robotHealth.batteryLevel = (unsigned char)((theFilteredSensorData.data[SensorData::batteryLevel] == SensorData::off ? 1.f : theFilteredSensorData.data[SensorData::batteryLevel]) * 100.f); unsigned char maxTemperature(0); for(int i = 0; i < JointData::numOfJoints; ++i) if(theFilteredSensorData.temperatures[i] > maxTemperature) maxTemperature = theFilteredSensorData.temperatures[i]; robotHealth.maxJointTemperature = maxTemperature; // Add cpu load, memory load and robot name: float memoryUsage, load[3]; SystemCall::getLoad(memoryUsage, load); robotHealth.load[0] = (unsigned char)(load[0] * 10.f); robotHealth.load[1] = (unsigned char)(load[1] * 10.f); robotHealth.load[2] = (unsigned char)(load[2] * 10.f); robotHealth.memoryUsage = (unsigned char)(memoryUsage * 100.f); robotHealth.robotName = Global::getSettings().robot; std::string wavName = Global::getSettings().robot.c_str(); wavName.append(".wav"); //battery warning if(lastBatteryLevel < robotHealth.batteryLevel) batteryVoltageFalling = false; else if(lastBatteryLevel > robotHealth.batteryLevel) batteryVoltageFalling = true; if(robotHealth.batteryLevel < p.batteryLow) { if(batteryVoltageFalling && theFrameInfo.getTimeSince(startBatteryLow) > 1000) { SoundPlayer::play("lowbattery.wav"); //next warning in 90 seconds startBatteryLow = theFrameInfo.time + 30000; batteryVoltageFalling = false; } } else if(startBatteryLow < theFrameInfo.time) startBatteryLow = theFrameInfo.time; lastBatteryLevel = robotHealth.batteryLevel; //temperature warning if(maxTemperature > p.temperatureHigh) { if(theFrameInfo.getTimeSince(highTemperatureSince) > 1000) { SoundPlayer::play("heat.wav"); highTemperatureSince = theFrameInfo.time + 20000; } } else if(highTemperatureSince < theFrameInfo.time) highTemperatureSince = theFrameInfo.time; } } MAKE_MODULE(RobotHealthProvider, Infrastructure)
[ "roman.michna@student.tuke.sk" ]
roman.michna@student.tuke.sk
6e6fbbd130141fd5253c92b959783330e895fd11
31f09c1e92698617f547234ce4b75c7776c25e1b
/gameShao/Classes/GameFMS.hpp
80cde176a047384f1276a99e08a0b3c89f325ca0
[]
no_license
Midnightshao/Cocos2d-CocosCreator
20aa53c7389b99b40e336f0e3820399f195f8051
19edfeb7c98f3a99c261a22a6c1d3e2083452db6
refs/heads/master
2020-04-16T12:36:02.689116
2019-01-14T03:30:16
2019-01-14T03:30:16
165,587,103
1
0
null
null
null
null
UTF-8
C++
false
false
634
hpp
// // GameFMS.hpp // gameShao // // Created by shao on 2019/1/11. // #ifndef GameFMS_hpp #define GameFMS_hpp #include <iostream> #include "cocos2d.h" #include "ui/CocosGUI.h" #include "SceneManager.hpp" #include "reader/CreatorReader.h" #include "reader/Macros.h" USING_NS_CC; class GameFMS :public Layer{ public: bool init(); void setCamera(Camera *camera,Sprite *sprite); void Control(int a); void changeStop(); void changeLeft(); void changeRight(); void changeJump(); void changeJump1(); CREATE_FUNC(GameFMS); private: Sprite *player; Camera *camera; }; #endif /* GameFMS_hpp */
[ "748013352@qq.com" ]
748013352@qq.com
ac3f68d75db3503a424c4ca9b9e6e46410843a0b
9480e2e795e5e79b92e69270025351a3c517f901
/src/StateHandler/LobbyHandler/CharacterWearInfo.h
6e58636637316c95447b2301fdf073f848958704
[]
no_license
glandu2/rzgame
ed22db3bdd47cecdcd6f75a0a1c3dedc41040083
90116860a5ad95edef0a28bcea0db51bb3900aac
refs/heads/master
2021-07-06T07:22:06.558498
2020-08-11T21:46:23
2020-08-11T21:46:23
39,275,392
0
0
null
null
null
null
UTF-8
C++
false
false
478
h
#pragma once #include "Database/DbQueryJob.h" #include "GameTypes.h" namespace GameServer { class CharacterWearInfo { public: game_sid_t character_sid; int32_t wear_info; uint32_t code; uint32_t enhance; uint32_t level; uint8_t elemental_effect_type; uint32_t appearance_code; CharacterWearInfo() { wear_info = -1; } }; struct CharacterWearInfoBinding { struct Input { uint32_t account_id; }; typedef CharacterWearInfo Output; }; } // namespace GameServer
[ "glandu2epvp@gmail.com" ]
glandu2epvp@gmail.com
c0a0d26c5bcc6a0a7d9041412c338466c9583682
3f22fe0318a6a483bcbde81b5bdca012dcb278d0
/4_mainWindows/source/src/mydialog.cpp
fea5eccf2e8d2573563dc9ff5d02ffb07101cdbc
[]
no_license
yatt122496/QT
ad044e7cfa08b98ebe1eb13459934e7ba4746c59
e1ff5a04d11cd3212a4a9fd568949f65e32b70e8
refs/heads/master
2023-06-06T12:56:25.592198
2021-06-28T01:16:16
2021-06-28T01:16:16
373,773,890
0
0
null
null
null
null
UTF-8
C++
false
false
1,609
cpp
#include "source/inc/mydialog.h" #include <QtGui> #include <QLabel> #include <QLineEdit> #include <QGridLayout> #include <QPushButton> MyDialog::MyDialog(QWidget *parent) :QDialog(parent) { labelID = new QLabel("学号:"); lineEditID = new QLineEdit; labelName = new QLabel("姓名:"); lineEditName = new QLineEdit; labelAge = new QLabel("年龄:"); lineEditAge = new QLineEdit; QGridLayout *grid = new QGridLayout(); grid->addWidget(labelID,0,0,1,1); grid->addWidget(lineEditID,0,1,1,3); grid->addWidget(labelName,1,0,1,1); grid->addWidget(lineEditName,1,1,1,3); grid->addWidget(labelAge,2,0,1,1); grid->addWidget(lineEditAge,2,1,1,3); QPushButton *okButton = new QPushButton("确定"); QPushButton *resetButton = new QPushButton("重置"); QPushButton *cancelButton = new QPushButton("取消"); QHBoxLayout *btnLayout = new QHBoxLayout; btnLayout->addWidget(okButton); btnLayout->addWidget(resetButton); btnLayout->addWidget(cancelButton); QVBoxLayout *layout = new QVBoxLayout(this); layout->addLayout(grid); layout->addLayout(btnLayout); layout->setMargin(40); layout->setSpacing(20); connect(okButton,SIGNAL(clicked()),this,SLOT(slotEnsure)); connect(resetButton,SIGNAL(clicked()),this,SLOT(slotReset())); connect(cancelButton,SIGNAL(clicked()),this,SLOT(close())); labelID->setPixmap(QPixmap(":Resource/images/kie.jpeg")); } void MyDialog::slotReset() { lineEditID->clear(); lineEditName->clear(); lineEditAge->clear(); } void MyDialog::slotEnsure() { }
[ "1254452743@qq.com" ]
1254452743@qq.com
954837dae98cb4e8c30aab3728fd8f7756a2887f
c10650383e9bb52ef8b0c49e21c10d9867cb033c
/c++/Win32_1/First.cpp
8b6107909a395f03f1f6b7501c671013cc654919
[]
no_license
tangyiyong/Practise-project
f1ac50e8c7502a24f226257995e0457f43c45032
4a1d874d8e3cf572b68d56518a2496513ce5cb27
refs/heads/master
2020-08-11T16:28:11.670852
2016-03-05T04:24:41
2016-03-05T04:24:41
null
0
0
null
null
null
null
WINDOWS-1252
C++
false
false
3,667
cpp
#include <Windows.h> #include <stdio.h> #include <vector> using namespace std; HWND ChWndList; HWND PhWndList; HINSTANCE ghInstance; void CreateChilWin(); LRESULT CALLBACK WinProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { switch (uMsg) { case WM_SIZE: { RECT rt; ::GetClientRect(hWnd,&rt); int wx=rt.right-rt.left; int wy=rt.bottom-rt.top; ::SetWindowPos(ChWndList,NULL,0,0,wx,wy,SWP_SHOWWINDOW); } break; case WM_PAINT: { PAINTSTRUCT ps; int a=strcmp("b","°¡"); char sz[10]; sprintf(sz,"%d",a); HDC hdc=::BeginPaint(hWnd,&ps); ::TextOut(hdc,0,0,sz,strlen(sz)); ::EndPaint(hWnd,&ps); } break; case WM_CHAR: { HDC hdc=::GetDC(hWnd); char sz[10]; sprintf(sz,"%c",wParam); ::TextOut(hdc,0,0,sz,strlen(sz)); ::ReleaseDC(hWnd,hdc); } break; case WM_RBUTTONDOWN: CreateChilWin(); break; case WM_CLOSE: DestroyWindow(hWnd); break; case WM_DESTROY: ::PostQuitMessage(0); break; default: return ::DefWindowProc(hWnd, uMsg, wParam, lParam); } return 0; } LRESULT CALLBACK WinProcChild(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { switch (uMsg) { case WM_CREATE: ::SetTimer(hWnd,110,1000,NULL); break; case WM_TIMER: ::InvalidateRect(hWnd,NULL,TRUE); break; case WM_PAINT: { PAINTSTRUCT ps; char *str="²»"; int a=strcmp("°©","²»"); char sz[10]; sprintf(sz,"%d",a); HDC hdc=::BeginPaint(hWnd,&ps); ::TextOut(hdc,0,0,sz,strlen(sz)); ::EndPaint(hWnd,&ps); } break; case WM_KEYUP: { HDC hdc=::GetDC(hWnd); char sz[10]; sprintf(sz,"%c",wParam); ::TextOut(hdc,0,0,sz,strlen(sz)); ::ReleaseDC(hWnd,hdc); } break; case WM_RBUTTONDOWN: { HDC hdc=::GetDC(hWnd); char sz[20]; int x=LOWORD(lParam); int y=HIWORD(lParam); sprintf(sz,"%d,%d",x,y); ::TextOut(hdc,x,y,sz,strlen(sz)); ::ReleaseDC(hWnd,hdc); } break; case WM_CLOSE: ::KillTimer(hWnd,110); DestroyWindow(hWnd); ChWndList=NULL; break; default: return ::DefWindowProc(hWnd, uMsg, wParam, lParam); } return 0; } void CreateChilWin() { MSG msg = {0}; WNDCLASS wc; wc.cbClsExtra = 0; wc.cbWndExtra = 0; wc.hbrBackground = ::CreateSolidBrush(0xffffff); wc.hCursor = ::LoadCursor(NULL,IDC_ARROW); wc.hIcon = ::LoadIcon(NULL,IDI_INFORMATION); wc.hInstance = ghInstance; wc.lpfnWndProc = WinProcChild; wc.lpszClassName = "lawa2"; wc.lpszMenuName = NULL; wc.style = CS_DBLCLKS|CS_HREDRAW|CS_VREDRAW; ATOM aTom = ::RegisterClass(&wc); //if(!aTom) return NULL; HWND ChWnd=CreateWindow(wc.lpszClassName, NULL ,WS_CHILD, 0 , 0 , 150 , 150 , PhWndList , NULL , ghInstance , NULL); ChWndList=ChWnd; //if(!hWnd) return NULL; ::ShowWindow(ChWnd,SW_MAXIMIZE); ::UpdateWindow(ChWnd); } void CreateParenWin() { MSG msg = {0}; WNDCLASS wc; wc.cbClsExtra = 0; wc.cbWndExtra = 0; wc.hbrBackground =::CreateSolidBrush(0x0); wc.hCursor = ::LoadCursor(NULL,IDC_ARROW); wc.hIcon = ::LoadIcon(NULL,IDI_INFORMATION); wc.hInstance = ghInstance; wc.lpfnWndProc = WinProc; wc.lpszClassName = "lawa"; wc.lpszMenuName = "lawa"; wc.style = CS_DBLCLKS|CS_HREDRAW|CS_VREDRAW; ATOM aTom = ::RegisterClass(&wc); HWND ChWnd=CreateWindow(wc.lpszClassName, "lawa" ,WS_OVERLAPPEDWINDOW, 0 , 0 , 300 , 300 , NULL , NULL , ghInstance , NULL); PhWndList=ChWnd; ::ShowWindow(PhWndList,SW_SHOW); ::UpdateWindow(PhWndList); } int WINAPI WinMain( HINSTANCE hInstance,HINSTANCE hPrevInstance,LPSTR lpCmdLine,int nCmdShow ) { MSG msg = {0}; ghInstance=hInstance; CreateParenWin(); CreateChilWin(); while(::GetMessage(&msg,NULL,0,0)) { ::TranslateMessage(&msg); ::DispatchMessage(&msg); } return 0; }
[ "76275381@qq.com" ]
76275381@qq.com
ffa5bf2d4044fd476b7b70f8da60f49416c8b8e4
39b8e5e003e79fdde12d765a64e9e40f49c6b0b9
/第四周/A.cpp
257a38166f528d82e2bd8b4822d979505fcd7607
[]
no_license
Booooooooooo/wyb---ACM
2af10f93f323ad66e8dd467ee25605e0728c5fa4
dd17594d9c205ebae110022274022f2207878236
refs/heads/master
2021-09-21T02:04:37.847570
2018-08-19T07:37:46
2018-08-19T07:37:46
90,154,488
5
1
null
null
null
null
UTF-8
C++
false
false
725
cpp
#include<stdio.h> #include<iostream> #include<algorithm> using namespace std; int n; struct domin{ int up; int low; }a[105]; int main() { while(scanf("%d",&n)!=EOF) { int i,su=0,sl=0,cnt=0; for(i=0;i<n;i++) { scanf("%d%d",&a[i].up,&a[i].low); su+=a[i].up; sl+=a[i].low; } if(su%2==0&&sl%2==0) { printf("0\n"); continue; } if(su%2==0&&sl%2==1) { printf("-1\n"); continue; } if(sl%2==0&&su%2==1) { printf("-1\n"); continue; } for(i=0;i<n;i++) { if(a[i].up%2&&a[i].low%2==0) { cnt=1; break; } else if(a[i].up%2==0&&a[i].low%2) { cnt=1; break; } } if(i==n&&cnt==0) printf("-1\n"); else printf("%d\n",cnt); } return 0; }
[ "447539789@qq.com" ]
447539789@qq.com
74e5b3596ade28de1e199bacd3c29c105ac8417e
b88af1bf6ed92aababbc8423fe61607bffe9c9a6
/src/binary_search/278_remove_element.hh
1369fff521290cf580a05bc5cec4203a52ff8e4e
[]
no_license
long-gong/leetcode
0d84b5213e4437e8334ac3920ccf364ef31bacaa
afc756dd881dfd1447e410668b2359f646d17753
refs/heads/master
2020-03-25T19:51:01.822018
2018-10-09T05:33:29
2018-10-09T05:33:29
144,103,293
0
0
null
null
null
null
UTF-8
C++
false
false
771
hh
// // Created by saber on 8/18/18. // #ifndef LEETCODE_278_REMOVE_ELEMENT_HH #define LEETCODE_278_REMOVE_ELEMENT_HH /* * Given an array nums and a value val, remove all instances of that value in-place * and return the new length. * * Do not allocate extra space for another array, you must do this by modifying the * input array in-place with O(1) extra memory. * * The order of elements can be changed. It doesn't matter what you leave beyond the * new length. */ #include <leetcode.h> class RemoveElementBase { public: virtual int operator()(std::vector<int>&& nums, int val) = 0; }; class RemoveElement01 : public RemoveElementBase { public: int operator()(std::vector<int> &&nums, int val) override; }; #endif //LEETCODE_278_REMOVE_ELEMENT_HH
[ "saber@localhost.localdomain" ]
saber@localhost.localdomain
a6b3a7aacfd00455750a51666af48b84eb470854
d2d6aae454fd2042c39127e65fce4362aba67d97
/build/iOS/Preview1/include/Uno.Float2.h
b491d5ecfe9ce83d1e56a8c7dba20c4246ec0620
[]
no_license
Medbeji/Eventy
de88386ff9826b411b243d7719b22ff5493f18f5
521261bca5b00ba879e14a2992e6980b225c50d4
refs/heads/master
2021-01-23T00:34:16.273411
2017-09-24T21:16:34
2017-09-24T21:16:34
92,812,809
2
0
null
null
null
null
UTF-8
C++
false
false
3,291
h
// This file was generated based on '/Users/medbeji/Library/Application Support/Fusetools/Packages/UnoCore/1.0.11/source/uno/$.uno'. // WARNING: Changes might be lost if you edit this file directly. #pragma once #include <Uno.Object.h> namespace g{namespace Uno{struct Float2;}} namespace g{namespace Uno{struct Int2;}} namespace g{ namespace Uno{ // public intrinsic struct Float2 :2401 // { uStructType* Float2_typeof(); void Float2__ctor__fn(Float2* __this, float* xy); void Float2__ctor_1_fn(Float2* __this, float* x, float* y); void Float2__Equals_fn(Float2* __this, uType* __type, uObject* o, bool* __retval); void Float2__GetHashCode_fn(Float2* __this, uType* __type, int* __retval); void Float2__get_Item_fn(Float2* __this, int* index, float* __retval); void Float2__set_Item_fn(Float2* __this, int* index, float* value); void Float2__New1_fn(float* xy, Float2* __retval); void Float2__New2_fn(float* x, float* y, Float2* __retval); void Float2__op_Addition_fn(float* a, Float2* b, Float2* __retval); void Float2__op_Addition1_fn(Float2* a, float* b, Float2* __retval); void Float2__op_Addition2_fn(Float2* a, Float2* b, Float2* __retval); void Float2__op_Division1_fn(Float2* a, float* b, Float2* __retval); void Float2__op_Division2_fn(Float2* a, Float2* b, Float2* __retval); void Float2__op_Equality_fn(Float2* a, Float2* b, bool* __retval); void Float2__op_Implicit1_fn(::g::Uno::Int2* a, Float2* __retval); void Float2__op_Inequality_fn(Float2* a, Float2* b, bool* __retval); void Float2__op_Multiply_fn(float* a, Float2* b, Float2* __retval); void Float2__op_Multiply1_fn(Float2* a, float* b, Float2* __retval); void Float2__op_Multiply2_fn(Float2* a, Float2* b, Float2* __retval); void Float2__op_Subtraction1_fn(Float2* a, float* b, Float2* __retval); void Float2__op_Subtraction2_fn(Float2* a, Float2* b, Float2* __retval); void Float2__op_UnaryNegation_fn(Float2* a, Float2* __retval); void Float2__ToString_fn(Float2* __this, uType* __type, uString** __retval); struct Float2 { float X; float Y; void ctor_(float xy); void ctor_1(float x, float y); bool Equals(uType* __type, uObject* o) { bool __retval; return Float2__Equals_fn(this, __type, o, &__retval), __retval; } int GetHashCode(uType* __type) { int __retval; return Float2__GetHashCode_fn(this, __type, &__retval), __retval; } float Item(int index); void Item(int index, float value); uString* ToString(uType* __type) { uString* __retval; return Float2__ToString_fn(this, __type, &__retval), __retval; } }; Float2 Float2__New1(float xy); Float2 Float2__New2(float x, float y); Float2 Float2__op_Addition(float a, Float2 b); Float2 Float2__op_Addition1(Float2 a, float b); Float2 Float2__op_Addition2(Float2 a, Float2 b); Float2 Float2__op_Division1(Float2 a, float b); Float2 Float2__op_Division2(Float2 a, Float2 b); bool Float2__op_Equality(Float2 a, Float2 b); Float2 Float2__op_Implicit1(::g::Uno::Int2 a); bool Float2__op_Inequality(Float2 a, Float2 b); Float2 Float2__op_Multiply(float a, Float2 b); Float2 Float2__op_Multiply1(Float2 a, float b); Float2 Float2__op_Multiply2(Float2 a, Float2 b); Float2 Float2__op_Subtraction1(Float2 a, float b); Float2 Float2__op_Subtraction2(Float2 a, Float2 b); Float2 Float2__op_UnaryNegation(Float2 a); // } }} // ::g::Uno
[ "medbeji@MacBook-Pro-de-MedBeji.local" ]
medbeji@MacBook-Pro-de-MedBeji.local
101ba4ff30c6477e7d093e3d797f691a6d22cd75
23e393f8c385a4e0f8f3d4b9e2d80f98657f4e1f
/3rdparty/boost_1_60_0/boost/log/sinks/text_file_backend.hpp
6cc41742fb7304e8e54dd64d61e583b06099a9b2
[]
no_license
IgorYunusov/Mega-collection-cpp-1
c7c09e3c76395bcbf95a304db6462a315db921ba
42d07f16a379a8093b6ddc15675bf777eb10d480
refs/heads/master
2020-03-24T10:20:15.783034
2018-06-12T13:19:05
2018-06-12T13:19:05
142,653,486
3
1
null
2018-07-28T06:36:35
2018-07-28T06:36:35
null
UTF-8
C++
false
false
20,964
hpp
/* * Copyright Andrey Semashev 2007 - 2015. * Distributed under the Boost Software License, Version 1.0. * (See accompanying file LICENSE_1_0.txt or copy at * http://www.boost.org/LICENSE_1_0.txt) */ /*! * \file text_file_backend.hpp * \author Andrey Semashev * \date 09.06.2009 * * The header contains implementation of a text file sink backend. */ #ifndef BOOST_LOG_SINKS_TEXT_FILE_BACKEND_HPP_INCLUDED_ #define BOOST_LOG_SINKS_TEXT_FILE_BACKEND_HPP_INCLUDED_ #include <ios> #include <string> #include <ostream> #include <boost/limits.hpp> #include <boost/cstdint.hpp> #include <boost/smart_ptr/shared_ptr.hpp> #include <boost/date_time/date_defs.hpp> #include <boost/date_time/special_defs.hpp> #include <boost/date_time/gregorian/greg_day.hpp> #include <boost/date_time/posix_time/posix_time_types.hpp> #include <boost/filesystem/path.hpp> #include <boost/log/keywords/max_size.hpp> #include <boost/log/keywords/min_free_space.hpp> #include <boost/log/keywords/target.hpp> #include <boost/log/keywords/file_name.hpp> #include <boost/log/keywords/open_mode.hpp> #include <boost/log/keywords/auto_flush.hpp> #include <boost/log/keywords/rotation_size.hpp> #include <boost/log/keywords/time_based_rotation.hpp> #include <boost/log/detail/config.hpp> #include <boost/log/detail/light_function.hpp> #include <boost/log/detail/parameter_tools.hpp> #include <boost/log/sinks/basic_sink_backend.hpp> #include <boost/log/sinks/frontend_requirements.hpp> #include <boost/log/detail/header.hpp> #ifdef BOOST_HAS_PRAGMA_ONCE #pragma once #endif namespace boost { BOOST_LOG_OPEN_NAMESPACE namespace sinks { namespace file { //! The enumeration of the stored files scan methods enum scan_method { no_scan, //!< Don't scan for stored files scan_matching, //!< Scan for files with names matching the specified mask scan_all //!< Scan for all files in the directory }; /*! * \brief Base class for file collectors * * All file collectors, supported by file sink backends, should inherit this class. */ struct BOOST_LOG_NO_VTABLE collector { /*! * Default constructor */ BOOST_DEFAULTED_FUNCTION(collector(), {}) /*! * Virtual destructor */ virtual ~collector() {} /*! * The function stores the specified file in the storage. May lead to an older file * deletion and a long file moving. * * \param src_path The name of the file to be stored */ virtual void store_file(filesystem::path const& src_path) = 0; /*! * Scans the target directory for the files that have already been stored. The found * files are added to the collector in order to be tracked and erased, if needed. * * The function may scan the directory in two ways: it will either consider every * file in the directory a log file, or will only consider files with names that * match the specified pattern. The pattern may contain the following placeholders: * * \li %y, %Y, %m, %d - date components, in Boost.DateTime meaning. * \li %H, %M, %S, %f - time components, in Boost.DateTime meaning. * \li %N - numeric file counter. May also contain width specification * in printf-compatible form (e.g. %5N). The resulting number will always be zero-filled. * \li %% - a percent sign * * All other placeholders are not supported. * * \param method The method of scanning. If \c no_scan is specified, the call has no effect. * \param pattern The file name pattern if \a method is \c scan_matching. Otherwise the parameter * is not used. * \param counter If not \c NULL and \a method is \c scan_matching, the method suggests initial value * of a file counter that may be used in the file name pattern. The parameter * is not used otherwise. * \return The number of found files. * * \note In case if \a method is \c scan_matching the effect of this function is highly dependent * on the \a pattern definition. It is recommended to choose patterns with easily * distinguished placeholders (i.e. having delimiters between them). Otherwise * either some files can be mistakenly found or not found, which in turn may lead * to an incorrect file deletion. */ virtual uintmax_t scan_for_files( scan_method method, filesystem::path const& pattern = filesystem::path(), unsigned int* counter = 0) = 0; BOOST_DELETED_FUNCTION(collector(collector const&)) BOOST_DELETED_FUNCTION(collector& operator= (collector const&)) }; namespace aux { //! Creates and returns a file collector with the specified parameters BOOST_LOG_API shared_ptr< collector > make_collector( filesystem::path const& target_dir, uintmax_t max_size, uintmax_t min_free_space ); template< typename ArgsT > inline shared_ptr< collector > make_collector(ArgsT const& args) { return aux::make_collector( filesystem::path(args[keywords::target]), args[keywords::max_size | (std::numeric_limits< uintmax_t >::max)()], args[keywords::min_free_space | static_cast< uintmax_t >(0)]); } } // namespace aux #ifndef BOOST_LOG_DOXYGEN_PASS template< typename T1 > inline shared_ptr< collector > make_collector(T1 const& a1) { return aux::make_collector(a1); } template< typename T1, typename T2 > inline shared_ptr< collector > make_collector(T1 const& a1, T2 const& a2) { return aux::make_collector((a1, a2)); } template< typename T1, typename T2, typename T3 > inline shared_ptr< collector > make_collector(T1 const& a1, T2 const& a2, T3 const& a3) { return aux::make_collector((a1, a2, a3)); } #else /*! * The function creates a file collector for the specified target directory. * Each target directory is managed by a single file collector, so if * this function is called several times for the same directory, * it will return a reference to the same file collector. It is safe * to use the same collector in different sinks, even in a multithreaded * application. * * One can specify certain restrictions for the stored files, such as * maximum total size or minimum free space left in the target directory. * If any of the specified restrictions is not met, the oldest stored file * is deleted. If the same collector is requested more than once with * different restrictions, the collector will act according to the most strict * combination of all specified restrictions. * * The following named parameters are supported: * * \li \c target - Specifies the target directory for the files being stored in. This parameter * is mandatory. * \li \c max_size - Specifies the maximum total size, in bytes, of stored files that the collector * will try not to exceed. If the size exceeds this threshold the oldest file(s) is * deleted to free space. Note that the threshold may be exceeded if the size of * individual files exceed the \c max_size value. The threshold is not maintained, * if not specified. * \li \c min_free_space - Specifies the minimum free space, in bytes, in the target directory that * the collector tries to maintain. If the threshold is exceeded, the oldest * file(s) is deleted to free space. The threshold is not maintained, if not * specified. * * \return The file collector. */ template< typename... ArgsT > shared_ptr< collector > make_collector(ArgsT... const& args); #endif // BOOST_LOG_DOXYGEN_PASS /*! * The class represents the time point of log file rotation. One can specify one of three * types of time point based rotation: * * \li rotation takes place every day, at the specified time * \li rotation takes place on the specified day of every week, at the specified time * \li rotation takes place on the specified day of every month, at the specified time * * The time points are considered to be local time. */ class rotation_at_time_point { public: typedef bool result_type; private: enum day_kind { not_specified, weekday, monthday }; day_kind m_DayKind : 2; unsigned char m_Day : 6; unsigned char m_Hour, m_Minute, m_Second; mutable posix_time::ptime m_Previous; public: /*! * Creates a rotation time point of every day at the specified time * * \param hour The rotation hour, should be within 0 and 23 * \param minute The rotation minute, should be within 0 and 59 * \param second The rotation second, should be within 0 and 59 */ BOOST_LOG_API explicit rotation_at_time_point(unsigned char hour, unsigned char minute, unsigned char second); /*! * Creates a rotation time point of each specified weekday at the specified time * * \param wday The weekday of the rotation * \param hour The rotation hour, should be within 0 and 23 * \param minute The rotation minute, should be within 0 and 59 * \param second The rotation second, should be within 0 and 59 */ BOOST_LOG_API explicit rotation_at_time_point( date_time::weekdays wday, unsigned char hour = 0, unsigned char minute = 0, unsigned char second = 0); /*! * Creates a rotation time point of each specified day of month at the specified time * * \param mday The monthday of the rotation, should be within 1 and 31 * \param hour The rotation hour, should be within 0 and 23 * \param minute The rotation minute, should be within 0 and 59 * \param second The rotation second, should be within 0 and 59 */ BOOST_LOG_API explicit rotation_at_time_point( gregorian::greg_day mday, unsigned char hour = 0, unsigned char minute = 0, unsigned char second = 0); /*! * Checks if it's time to rotate the file */ BOOST_LOG_API bool operator() () const; }; /*! * The class represents the time interval of log file rotation. The log file will be rotated * after the specified time interval has passed. */ class rotation_at_time_interval { public: typedef bool result_type; private: posix_time::time_duration m_Interval; mutable posix_time::ptime m_Previous; public: /*! * Creates a rotation time interval of the specified duration * * \param interval The interval of the rotation, should be no less than 1 second */ explicit rotation_at_time_interval(posix_time::time_duration const& interval) : m_Interval(interval) { BOOST_ASSERT(!interval.is_special()); BOOST_ASSERT(interval.total_seconds() > 0); } /*! * Checks if it's time to rotate the file */ BOOST_LOG_API bool operator() () const; }; } // namespace file /*! * \brief An implementation of a text file logging sink backend * * The sink backend puts formatted log records to a text file. * The sink supports file rotation and advanced file control, such as * size and file count restriction. */ class text_file_backend : public basic_formatted_sink_backend< char, combine_requirements< synchronized_feeding, flushing >::type > { //! Base type typedef basic_formatted_sink_backend< char, combine_requirements< synchronized_feeding, flushing >::type > base_type; public: //! Character type typedef base_type::char_type char_type; //! String type to be used as a message text holder typedef base_type::string_type string_type; //! Stream type typedef std::basic_ostream< char_type > stream_type; //! File open handler typedef boost::log::aux::light_function< void (stream_type&) > open_handler_type; //! File close handler typedef boost::log::aux::light_function< void (stream_type&) > close_handler_type; //! Predicate that defines the time-based condition for file rotation typedef boost::log::aux::light_function< bool () > time_based_rotation_predicate; private: //! \cond struct implementation; implementation* m_pImpl; //! \endcond public: /*! * Default constructor. The constructed sink backend uses default values of all the parameters. */ BOOST_LOG_API text_file_backend(); /*! * Constructor. Creates a sink backend with the specified named parameters. * The following named parameters are supported: * * \li \c file_name - Specifies the file name pattern where logs are actually written to. The pattern may * contain directory and file name portions, but only the file name may contain * placeholders. The backend supports Boost.DateTime placeholders for injecting * current time and date into the file name. Also, an additional %N placeholder is * supported, it will be replaced with an integral increasing file counter. The placeholder * may also contain width specification in the printf-compatible form (e.g. %5N). The * printed file counter will always be zero-filled. If \c file_name is not specified, * pattern "%5N.log" will be used. * \li \c open_mode - File open mode. The mode should be presented in form of mask compatible to * <tt>std::ios_base::openmode</tt>. If not specified, <tt>trunc | out</tt> will be used. * \li \c rotation_size - Specifies the approximate size, in characters written, of the temporary file * upon which the file is passed to the file collector. Note the size does * not count any possible character conversions that may take place during * writing to the file. If not specified, the file won't be rotated upon reaching * any size. * \li \c time_based_rotation - Specifies the predicate for time-based file rotation. * No time-based file rotations will be performed, if not specified. * \li \c auto_flush - Specifies a flag, whether or not to automatically flush the file after each * written log record. By default, is \c false. * * \note Read the caution note regarding file name pattern in the <tt>sinks::file::collector::scan_for_files</tt> * documentation. */ #ifndef BOOST_LOG_DOXYGEN_PASS BOOST_LOG_PARAMETRIZED_CONSTRUCTORS_CALL(text_file_backend, construct) #else template< typename... ArgsT > explicit text_file_backend(ArgsT... const& args); #endif /*! * Destructor */ BOOST_LOG_API ~text_file_backend(); /*! * The method sets file name wildcard for the files being written. The wildcard supports * date and time injection into the file name. * * \param pattern The name pattern for the file being written. */ template< typename PathT > void set_file_name_pattern(PathT const& pattern) { set_file_name_pattern_internal(filesystem::path(pattern)); } /*! * The method sets the file open mode * * \param mode File open mode */ BOOST_LOG_API void set_open_mode(std::ios_base::openmode mode); /*! * The method sets the log file collector function. The function is called * on file rotation and is being passed the written file name. * * \param collector The file collector function object */ BOOST_LOG_API void set_file_collector(shared_ptr< file::collector > const& collector); /*! * The method sets file opening handler. The handler will be called every time * the backend opens a new temporary file. The handler may write a header to the * opened file in order to maintain file validity. * * \param handler The file open handler function object */ BOOST_LOG_API void set_open_handler(open_handler_type const& handler); /*! * The method sets file closing handler. The handler will be called every time * the backend closes a temporary file. The handler may write a footer to the * opened file in order to maintain file validity. * * \param handler The file close handler function object */ BOOST_LOG_API void set_close_handler(close_handler_type const& handler); /*! * The method sets maximum file size. When the size is reached, file rotation is performed. * * \note The size does not count any possible character translations that may happen in * the underlying API. This may result in greater actual sizes of the written files. * * \param size The maximum file size, in characters. */ BOOST_LOG_API void set_rotation_size(uintmax_t size); /*! * The method sets the predicate that defines the time-based condition for file rotation. * * \note The rotation always occurs on writing a log record, so the rotation is * not strictly bound to the specified condition. * * \param predicate The predicate that defines the time-based condition for file rotation. * If empty, no time-based rotation will take place. */ BOOST_LOG_API void set_time_based_rotation(time_based_rotation_predicate const& predicate); /*! * Sets the flag to automatically flush buffers of all attached streams after each log record */ BOOST_LOG_API void auto_flush(bool f = true); /*! * Performs scanning of the target directory for log files that may have been left from * previous runs of the application. The found files are considered by the file collector * as if they were rotated. * * The file scan can be performed in two ways: either all files in the target directory will * be considered as log files, or only those files that satisfy the file name pattern. * See documentation on <tt>sinks::file::collector::scan_for_files</tt> for more information. * * \pre File collector and the proper file name pattern have already been set. * * \param method File scanning method * \param update_counter If \c true and \a method is \c scan_matching, the method attempts * to update the internal file counter according to the found files. The counter * is unaffected otherwise. * \return The number of files found. * * \note The method essentially delegates to the same-named function of the file collector. */ BOOST_LOG_API uintmax_t scan_for_files( file::scan_method method = file::scan_matching, bool update_counter = true); /*! * The method writes the message to the sink */ BOOST_LOG_API void consume(record_view const& rec, string_type const& formatted_message); /*! * The method flushes the currently open log file */ BOOST_LOG_API void flush(); /*! * The method rotates the file */ BOOST_LOG_API void rotate_file(); private: #ifndef BOOST_LOG_DOXYGEN_PASS //! Constructor implementation template< typename ArgsT > void construct(ArgsT const& args) { construct( filesystem::path(args[keywords::file_name | filesystem::path()]), args[keywords::open_mode | (std::ios_base::trunc | std::ios_base::out)], args[keywords::rotation_size | (std::numeric_limits< uintmax_t >::max)()], args[keywords::time_based_rotation | time_based_rotation_predicate()], args[keywords::auto_flush | false]); } //! Constructor implementation BOOST_LOG_API void construct( filesystem::path const& pattern, std::ios_base::openmode mode, uintmax_t rotation_size, time_based_rotation_predicate const& time_based_rotation, bool auto_flush); //! The method sets file name mask BOOST_LOG_API void set_file_name_pattern_internal(filesystem::path const& pattern); //! Closes the currently open file void close_file(); #endif // BOOST_LOG_DOXYGEN_PASS }; } // namespace sinks BOOST_LOG_CLOSE_NAMESPACE // namespace log } // namespace boost #include <boost/log/detail/footer.hpp> #endif // BOOST_LOG_SINKS_TEXT_FILE_BACKEND_HPP_INCLUDED_
[ "wyrover@gmail.com" ]
wyrover@gmail.com
92ef838b5caed1ac48097322369e26a2c34241e1
630c2828e5caa69549eb5e9e135867b8b1003fc8
/P3_A3/berechnen2.cpp
3f9de83ae09bb287f6a53a2ff0862ac56569c237
[]
no_license
mabako/whz-computergrafik
7c6194a202333dad0741e27bd2d85f6bc46b9522
531efaef8629b28c450612d046a14fa048dbade2
refs/heads/master
2020-12-24T13:52:34.890384
2012-06-25T16:53:41
2012-06-25T16:53:41
null
0
0
null
null
null
null
UTF-8
C++
false
false
321
cpp
#include "berechnen2.h" minmax* berechnen2(int groesse, int* feld) { if(groesse == 0) return 0; minmax* m = new minmax(); m->max = feld[0]; m->min = feld[0]; for(int i = 1; i < groesse; ++ i) { int wert = feld[i]; if(wert > m->max) m->max = wert; if(wert < m->min) m->min = wert; } return m; }
[ "mabako@gmail.com" ]
mabako@gmail.com
fa918284dd0d6a34d98a575b6b6cd82c0a2c3e16
b4d3d5f66dc717753fd85639093a09599e0fc664
/curses/src/Gui.hh
b0b887fffd9163430ec6822e585e51f53acf5421
[ "MIT" ]
permissive
okeri/snm
eb4c5c810c4b940e32ea0c842cd5c7d1ca109ddd
7ea65600f9a7f18e029ddb3dd4498255acda2bf0
refs/heads/master
2022-08-25T05:35:48.834763
2022-07-20T14:24:58
2022-07-20T14:24:58
139,017,364
3
0
null
null
null
null
UTF-8
C++
false
false
1,030
hh
#pragma once #include <vector> #include <memory> #include <functional> #include <optional> #include <tuple> #include <string> #include <snm_types.hh> #include "Window.hh" class Gui { public: using PropGetter = std::function<snm::ConnectionProps(const std::string&)>; using Connector = std::function<void(const snm::ConnectionId &)>; enum class Display { Networks, Props, }; Gui(); ~Gui(); bool pressed(int ch); void setNetworkState(snm::ConnectionState &&state); void setNetworkStatus(snm::ConnectionStatus status); void setNetworkList(std::vector<snm::NetworkInfo> &&networks); void showProps(PropGetter getter); void showNetworks(); void connect(Connector connector); std::tuple<std::string, snm::ConnectionProps> getProps(); Display display() { return display_; } private: Display display_; std::vector<std::unique_ptr<Window>> windows_; unsigned cast(Display d) { return static_cast<unsigned>(d); } };
[ "ezhi99@gmail.com" ]
ezhi99@gmail.com
c6117b7e7ed39468f78c4021bad2640341430edc
7fab9494bd5ba64980d9bb86d8ba0735b538d2b5
/combination.cpp
f4e7f7ec91b778630bf4dc5295965f0e73092402
[]
no_license
IvanDonat/ssc19
38a2d8f56c22630c4fdfd5178d3d5859260cac74
0fd9edc776fdd47d985d012418c1c07ccc78b03c
refs/heads/master
2020-04-29T00:47:23.479490
2019-04-05T09:34:41
2019-04-05T09:34:41
175,707,875
0
0
null
null
null
null
UTF-8
C++
false
false
553
cpp
// Here it suffices to check all combinations of CW/ACW, as the input // is small enough. A bitmask is used to through iterate all possibilities. #include <iostream> using namespace std; int n, a[16]; int main() { cin >> n; for(int i = 0; i < n; i++) cin >> a[i]; for(int bits = 0; bits < (1<<(n-1)); bits++) { int sum = 0; for(int i = 0; i < n; i++) if(bits & (1<<i)) sum += a[i]; else sum -= a[i]; if(sum % 360 == 0) { cout << "YES" << endl; return 0; } } cout << "NO" << endl; return 0; }
[ "ivan.pupovac@student.manchester.ac.uk" ]
ivan.pupovac@student.manchester.ac.uk
4506525816361bee0406c75b23050ff43315e044
8e4b67f26bcb816bfaa9743341146f3abe25b130
/src/PRHS_Entity.cpp
fd61dfa59918bbc53512a3754e1bceb949a8730a
[]
no_license
PRHS-Programming-Club/PRHS-Game-Lib
0c3f3977b1f0bb031ebe37bdf561a6ee2a77dd42
e1494d80e3df91df741d4932d96de6cbc7f3b7d0
refs/heads/master
2020-04-17T10:22:37.677738
2019-09-05T21:34:50
2019-09-05T21:34:50
166,498,923
0
0
null
null
null
null
UTF-8
C++
false
false
2,444
cpp
/* Version 2.0.0 of the PRHS Game Library Last Modified on January 18, 2019 */ #include "PRHS_Entity.h" #include "PRHS_Window.h" namespace PRHS { TextureManager& Entity::textureManager = TextureManager::getInstance(); Entity::Entity() : skinId("NO SKIN"), position{ 0.0, 0.0, 0.0, 0.0, 0.0 }, skin() { } Entity::Entity(const std::string& textureManagerId, const FloatRect& newPosition) : skinId("NO SKIN"), skin(), position(newPosition) { setSkin(textureManagerId); //Set the entity's skin } void Entity::updatePosition(const FloatRect& adjustment, const EntityUpdateParam& updateParam) { switch (updateParam) { case UPDATE_ABSOLUTE: position = adjustment; break; case UPDATE_RELATIVE: position.x += adjustment.x; position.y += adjustment.y; position.w += adjustment.w; position.h += adjustment.h; position.r += adjustment.r; break; } } void Entity::setPosition(int newX, int newY, int newW, int newH, int newR) { if (newX != VOID) { position.x = newX; } if (newY != VOID) { position.y = newY; } if (newW != VOID) { position.w = newW; } if (newH != VOID) { position.h = newH; } if (newR != VOID) { position.r = newR; } } FloatRect Entity::getPosition() { return position; } bool Entity::checkCollision(const FloatRect& rect) { // TODO: Use floats, add rotation support SDL_Rect position1 = {position.x, position.y, position.w, position.h}; SDL_Rect position2 = {rect.x, rect.y, rect.w, rect.h}; return SDL_HasIntersection(&position1, &position2); } bool Entity::checkCollision(const Entity& entity) { return checkCollision(entity.position); } bool Entity::onScreen() { // TODO: Create more accurate bounding box from rotated position Window& window = Window::getInstance(); SDL_Rect screen = { 0, 0, window.getWidth(), window.getHeight()}; SDL_Rect position = { this->position.x, this->position.y, this->position.w, this->position.h }; return SDL_HasIntersection(&position, &screen); } void Entity::setSkin(const std::string& id) { if (textureManager.hasId(id)) { //Check if texture exists skinId = id; skin = textureManager.getTexture(skinId); } else { throw invalid_id("Texture with id \"" + id + "\" does not exist."); } } std::string Entity::getSkinId() { return skinId; } }
[ "sciencedude2003@gmail.com" ]
sciencedude2003@gmail.com
73c67956958e4987face605712635332d26d9a6c
d85a2cade5af30cea1f959a4ddd91db9bd857e60
/Core/Widgets/Tab/TabsSpaceSplitter.cpp
715b4774dc46aa863483caf953aa03107af4d4b8
[ "MIT" ]
permissive
hobbit19/SieloBrowser
d57dc8e6724cd6d8ac22e01569f2a0631704e378
6872caf3749eda3aa78d64ab5e3b926be2eb03ec
refs/heads/master
2020-04-08T20:29:53.909362
2018-11-19T22:12:04
2018-11-19T22:12:04
null
0
0
null
null
null
null
UTF-8
C++
false
false
13,892
cpp
/*********************************************************************************** ** MIT License ** ** ** ** Copyright (c) 2018 Victor DENIS (victordenis01@gmail.com) ** ** ** ** Permission is hereby granted, free of charge, to any person obtaining a copy ** ** of this software and associated documentation files (the "Software"), to deal ** ** in the Software without restriction, including without limitation the rights ** ** to use, copy, modify, merge, publish, distribute, sublicense, and/or sell ** ** copies of the Software, and to permit persons to whom the Software is ** ** furnished to do so, subject to the following conditions: ** ** ** ** The above copyright notice and this permission notice shall be included in all ** ** copies or substantial portions of the Software. ** ** ** ** THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR ** ** IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, ** ** FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE ** ** AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER ** ** LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, ** ** OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE ** ** SOFTWARE. ** ***********************************************************************************/ #include "TabsSpaceSplitter.hpp" #include "Utils/Settings.hpp" #include "Widgets/TitleBar.hpp" #include "Widgets/Tab/TabWidget.hpp" #include "Widgets/Tab/MainTabBar.hpp" #include "MaquetteGrid/MaquetteGridItem.hpp" #include "Application.hpp" #include "BrowserWindow.hpp" namespace Sn { TabsSpaceSplitter::SavedTabsSpace::SavedTabsSpace() { // Empty } TabsSpaceSplitter::SavedTabsSpace::SavedTabsSpace(TabsSpaceSplitter* splitter, TabWidget* tabWidget) { QWidget* columnWidget{nullptr}; TabsSpaceInfo info = splitter->tabsSpaceInfo(tabWidget); x = info.x; y = info.y; columnWidget = info.column; homeUrl = tabWidget->homeUrl().toString(); tabs.reserve(tabWidget->count()); for (int i{0}; i < tabWidget->count(); ++i) { WebTab* webTab{tabWidget->webTab(i)}; if (!webTab) continue; WebTab::SavedTab tab{webTab}; if (!tab.isValide()) continue; if (webTab->isCurrentTab()) currentTab = i; tabs.append(tab); } } bool TabsSpaceSplitter::SavedTabsSpace::isValid() const { for (const WebTab::SavedTab& tab : tabs) { if (!tab.isValide()) return false; } return currentTab > -1; } void TabsSpaceSplitter::SavedTabsSpace::clear() { x = 0; y = 0; currentTab = -1; tabs.clear(); } QDataStream &operator<<(QDataStream &stream, const TabsSpaceSplitter::SavedTabsSpace &tabsSpace) { stream << 1; stream << tabsSpace.x; stream << tabsSpace.y; stream << tabsSpace.homeUrl; stream << tabsSpace.tabs.count(); for (int i{0}; i < tabsSpace.tabs.count(); ++i) stream << tabsSpace.tabs[i]; stream << tabsSpace.currentTab; return stream; } QDataStream &operator>>(QDataStream &stream, TabsSpaceSplitter::SavedTabsSpace &tabsSpace) { int version{0}; stream >> version; if (version < 1) return stream; stream >> tabsSpace.x; stream >> tabsSpace.y; stream >> tabsSpace.homeUrl; int tabsCount{0}; stream >> tabsCount; for(int i{0}; i < tabsCount; ++i) { WebTab::SavedTab tab{}; stream >> tab; tabsSpace.tabs.append(tab); } stream >> tabsSpace.currentTab; return stream; } TabsSpaceSplitter::TabsSpaceSplitter(BrowserWindow* window) : QWidget(window), m_window(window) { m_horizontalSplitter = new QSplitter(this); m_horizontalSplitter->setContentsMargins(0, 0, 0, 0); m_layout = new QVBoxLayout(this); m_layout->setContentsMargins(0, 0, 0, 0); m_layout->setSpacing(0); m_layout->addWidget(m_horizontalSplitter); loadSettings(); } void TabsSpaceSplitter::loadSettings() { Settings settings{}; m_tabsSpacePadding = settings.value(QLatin1String("Settings/tabsSpacesPadding"), 7).toInt(); const bool showBookmarksToolBar{settings.value(QLatin1String("ShowBookmarksToolBar"), true).toBool()}; // We can apply a padding between tabs space, exactly like i3 gaps foreach(TabWidget* tabWidget, m_tabWidgets) { tabWidget->loadSettings(); tabWidget->updateShowBookmarksBarText(showBookmarksToolBar); if (tabWidget->parentWidget()) tabWidget->parentWidget()->setContentsMargins(m_tabsSpacePadding, m_tabsSpacePadding, m_tabsSpacePadding, m_tabsSpacePadding); } } bool TabsSpaceSplitter::restoreTabsSpace(const SavedTabsSpace& tabsSpace) { if (tabsSpace.tabs.isEmpty()) return false; TabWidget* tabWidget{new TabWidget(m_window)}; QVector<QPair<WebTab*, QVector<int>>> childTabs{}; for (int i{0}; i < tabsSpace.tabs.count(); ++i) { WebTab::SavedTab tab = tabsSpace.tabs[i]; WebTab *webTab = tabWidget->webTab(tabWidget->addView(QUrl(), Application::NTT_CleanSelectedTab, false, tab.isPinned)); webTab->restoreTab(tab); if (!tab.childTabs.isEmpty()) childTabs.append({webTab, tab.childTabs}); } for (const auto p : childTabs) { const auto indices = p.second; for (int index : indices) { WebTab *t = tabWidget->webTab(index); if (t) p.first->addChildTab(t); } } tabWidget->setCurrentIndex(tabsSpace.currentTab); tabWidget->setHomeUrl(tabsSpace.homeUrl); QTimer::singleShot(0, this, [tabWidget]() { tabWidget->tabBar()->ensureVisible(); }); tabWidget->webTab()->tabActivated(); insertTabsSpace(tabsSpace.x, tabsSpace.y, tabWidget); return true; } void TabsSpaceSplitter::createNewTabsSpace(int x, int y) { TabWidget* tabWidget = new TabWidget(m_window); insertTabsSpace(x, y, tabWidget); } void TabsSpaceSplitter::createNewTabsSpace(TabWidget* tabWidget) { Q_ASSERT(!m_tabWidgets.contains(tabWidget)); if (!tabWidget) tabWidget = new TabWidget(m_window); insertTabsSpace(m_horizontalSplitter->count(), 0, tabWidget); } void TabsSpaceSplitter::createNewTabsSpace(WebTab* startTab) { TabWidget* tabWidget{new TabWidget(m_window)}; tabWidget->addView(startTab, Application::NTT_SelectedTabAtEnd); insertTabsSpace(m_horizontalSplitter->count(), 0, tabWidget); } TabWidget* TabsSpaceSplitter::createNewTabsSpace(TabsSpacePosition position, TabWidget* from) { TabWidget* tabWidget = new TabWidget(m_window); insertTabsSpace(position, tabWidget, from); return tabWidget; } void TabsSpaceSplitter::insertTabsSpace(TabsSpacePosition position, TabWidget* tabWidget, TabWidget* from) { Q_ASSERT(m_tabWidgets.contains(from)); QWidget* container = tabWidgetContainer(tabWidget); TabsSpaceInfo info = tabsSpaceInfo(from); if (position == TabsSpacePosition::TSP_Left) { QSplitter* newColumn{createColumn()}; m_horizontalSplitter->insertWidget(info.x, newColumn->parentWidget()); newColumn->addWidget(container); } if (position == TabsSpacePosition::TSP_Right) { QSplitter* newColumn{createColumn()}; m_horizontalSplitter->insertWidget(info.x + 1, newColumn->parentWidget()); newColumn->addWidget(container); } if (position == TabsSpacePosition::TSP_Top) m_verticalSplitter[info.column]->insertWidget(info.y, container); if (position == TabsSpacePosition::TSP_Bottom) m_verticalSplitter[info.column]->insertWidget(info.y + 1, container); } void TabsSpaceSplitter::insertTabsSpace(int x, int y, TabWidget* tabWidget) { QWidget* container = tabWidgetContainer(tabWidget); int count = m_horizontalSplitter->count(); if (m_horizontalSplitter->count() <= x) { QSplitter* newColumn{createColumn()}; m_horizontalSplitter->addWidget(newColumn->parentWidget()); newColumn->addWidget(container); } else { m_verticalSplitter[m_horizontalSplitter->widget(x)]->insertWidget(y, container); connect(tabWidget, &TabWidget::focusIn, m_window, &BrowserWindow::tabWidgetIndexChanged); connect(m_window->titleBar(), &TitleBar::toggleBookmarksBar, tabWidget, &TabWidget::updateShowBookmarksBarText); } } void TabsSpaceSplitter::removeTabsSpace(TabWidget* tabWidget) { TabsSpaceInfo info = tabsSpaceInfo(tabWidget); QSplitter* column = m_verticalSplitter[info.column]; m_tabWidgets.removeOne(tabWidget); // We have to wait drag operation to be done on unix system #ifdef Q_OS_UNIX if (column->count() <= 1) { m_verticalSplitter.remove(info.column); QTimer::singleShot(200, info.column, &QWidget::deleteLater); } else { QTimer::singleShot(200, tabWidget->parentWidget(), &QWidget::deleteLater); } #else if (column->count() <= 1) { m_verticalSplitter.remove(info.column); info.column->deleteLater(); } else { tabWidget->parentWidget()->deleteLater(); } #endif } void TabsSpaceSplitter::autoResize() { QList<int> mainSizes; // Vertical splitter size QList<int> verticalSizes; // All sizes of all vertical splitter for (int i{0}; i < m_horizontalSplitter->count(); ++i) mainSizes.append(m_horizontalSplitter->width() / m_horizontalSplitter->count()); m_horizontalSplitter->setSizes(mainSizes); for (int i{0}; i < m_horizontalSplitter->count(); ++i) { verticalSizes.clear(); // We don't want to apply size of previous vertical splitter QSplitter* column = m_verticalSplitter[m_horizontalSplitter->widget(i)]; for (int j{0}; j < column->count(); ++j) verticalSizes.append(column->height() / column->count()); column->setSizes(verticalSizes); } } void TabsSpaceSplitter::tabsSpaceInFullView(TabWidget* tabWidget) { TabsSpaceInfo info = tabsSpaceInfo(tabWidget); QList<int> sizes{}; for (int i{0}; i < m_horizontalSplitter->count(); ++i) { QSplitter* column = m_verticalSplitter[m_horizontalSplitter->widget(i)]; QList<int> verticalSizes{}; if (info.x == i) { for (int j{0}; j < column->count(); ++j) { if (info.y == j) verticalSizes.append(height()); else verticalSizes.append(0); } column->setSizes(verticalSizes); sizes.append(width()); } else { sizes.append(0); } } m_horizontalSplitter->setSizes(sizes); } int TabsSpaceSplitter::count() const { return m_tabWidgets.count(); } int TabsSpaceSplitter::horizontalCount() const { return m_horizontalSplitter->count(); } void TabsSpaceSplitter::currentTabWidgetChanged(TabWidget* current) { m_currentTabWidget = current; } TabWidget* TabsSpaceSplitter::tabWidget(int index) const { return index >= 0 ? m_tabWidgets[index] : m_currentTabWidget; } TabWidget* TabsSpaceSplitter::tabWidget(QPoint position) const { // Check on wich tabs space the floating button is to call the right slots foreach(TabWidget* tabWidget, m_tabWidgets) { QRect tabWidgetRect = tabWidget->geometry(); if (tabWidgetRect.contains(tabWidget->mapFromGlobal(mapToGlobal(position)))) { return tabWidget; } } return m_currentTabWidget; } MaquetteGridItem* TabsSpaceSplitter::maquetteGridItem() const { MaquetteGridItem* item{new MaquetteGridItem(tr("Session"), true)}; item->clear(); // We don't want default maquetteGrid. // Loop throug each tabs space foreach(TabWidget* tabWidget, m_tabWidgets) { MaquetteGridItem::TabsSpace* tabsSpace{new MaquetteGridItem::TabsSpace()}; // Add all tabs of the tabs space foreach(WebTab* tab, tabWidget->allTabs()) { MaquetteGridItem::Tab* maquetteGridTab{new MaquetteGridItem::Tab()}; maquetteGridTab->icon = tab->icon(); maquetteGridTab->title = tab->title(); maquetteGridTab->url = tab->url(); maquetteGridTab->selected = tabWidget->webTab() == tab; maquetteGridTab->parent = tabsSpace; tabsSpace->tabs.append(maquetteGridTab); } TabsSpaceInfo info = tabsSpaceInfo(tabWidget); tabsSpace->verticalIndex = info.y; tabsSpace->parent = item; item->addTabsSpace(tabsSpace); } return item; } TabsSpaceSplitter::TabsSpaceInfo TabsSpaceSplitter::tabsSpaceInfo(TabWidget* from) const { bool found{false}; for (int i{0}; i < m_horizontalSplitter->count(); ++i) { QSplitter* column = m_verticalSplitter[m_horizontalSplitter->widget(i)]; for (int j{0}; j < column->count(); ++j) { if (column->widget(j) == from->parentWidget()) { TabsSpaceInfo info{}; info.column = m_horizontalSplitter->widget(i); info.x = i; info.y = j; return info; } } } return TabsSpaceInfo(); } bool TabsSpaceSplitter::valideCoordinates(int x, int y) const { if (x >= m_horizontalSplitter->count()) return false; if (y >= m_verticalSplitter.values(m_horizontalSplitter->widget(x)).count()) return false; return true; } QWidget* TabsSpaceSplitter::tabWidgetContainer(TabWidget* tabWidget) { Q_ASSERT(!m_tabWidgets.contains(tabWidget)); QWidget* widget{new QWidget(this)}; QVBoxLayout* layout{new QVBoxLayout(widget)}; widget->setContentsMargins(m_tabsSpacePadding, m_tabsSpacePadding, m_tabsSpacePadding, m_tabsSpacePadding); layout->setSpacing(0); layout->setContentsMargins(0, 0, 0, 0); m_tabWidgets.append(tabWidget); m_currentTabWidget = tabWidget; tabWidget->setParent(widget); tabWidget->tabBar()->show(); layout->addWidget(tabWidget->tabBar()); layout->addWidget(tabWidget); return widget; } QSplitter* TabsSpaceSplitter::createColumn() { QWidget *column{new QWidget(this)}; QSplitter* splitter{new QSplitter(Qt::Vertical, this)}; QVBoxLayout* layout{new QVBoxLayout(column)}; layout->setSpacing(0); layout->setContentsMargins(0, 0, 0, 0); layout->addWidget(splitter); m_verticalSplitter[column] = splitter; return splitter; } }
[ "admin@feldrise.com" ]
admin@feldrise.com
d111a3d5235b72cb012236ac2242ab355e66f39f
d77220ce79c81e5c7271ddee00e9e5bd9e0cce77
/exercise_2_1/convolution.h
804c45a4774259ebb48072939f4dc514c62c6697
[]
no_license
RoboJackets-Software-Training/week-2-programming-exercise-Khaidde
a0f332b3453673788f5068e712ac9fd7bdb92d7e
0c8a6957e2dbba3288a94a72512d3f2e83efb3cb
refs/heads/master
2022-12-22T07:21:07.467872
2020-10-01T20:53:33
2020-10-01T20:53:33
300,096,755
0
0
null
2020-10-01T00:26:21
2020-10-01T00:26:11
C++
UTF-8
C++
false
false
119
h
#pragma once std::vector<double> applyConvolution(std::vector<double> x, std::vector<double> w, bool pack_with_zeros);
[ "calthekhid@gmail.com" ]
calthekhid@gmail.com
e32365a25c023940314bfbb67b8b51cbb1463d40
1063f7e13f50fa0fee6723a77dc533d786e3082f
/trunk/src/main/manual/ManualResultDetailDlg.h
5bdeda109a273b1de147f9f0d522ce9a5631d2d5
[]
no_license
zjm1060/HandSet
9e9b8af71ee57a7b90a470473edb72ef7b03c336
59a896e38996fe9f9b549316974bf82ffa046e1e
refs/heads/master
2022-12-21T19:52:10.349284
2017-03-10T08:20:14
2017-03-10T08:20:14
112,681,985
0
0
null
2020-09-25T01:00:09
2017-12-01T01:50:46
C++
GB18030
C++
false
false
4,416
h
/// @file /// /// @brief /// 手动实验具体结果 头文件 /// /// Copyright (c) 2013 IUnknownBase Inc /// /// 作者: /// lqx 2013.7.18 /// /// 修改历史: /// #pragma once #include "src/main/resource.h" #include "src/main/dlg/basedlg.h" #include "src/service/datalayer/DsmDataLayer.h" enum eMRDShowReportType { MRDSmvReport = 0, MRDGooseReport , MRDDIActionReport, }; /// /// @brief /// 手动实验具体结果 对话框 /// class CManualResultDetailDlg : public CBaseDlg { DECLARE_DYNAMIC(CManualResultDetailDlg) public: CManualResultDetailDlg(CWnd* pParent = NULL); // 标准构造函数 virtual ~CManualResultDetailDlg(); // 对话框数据 enum { IDD = IDD_MANUAL_RESULT_DETAIL_DLG }; protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV 支持 DECLARE_MESSAGE_MAP() public: virtual BOOL OnInitDialog(); virtual BOOL PreTranslateMessage(MSG* pMsg); afx_msg void OnNaviMenuResultDetail(UINT nID); afx_msg void OnUpdateNaviMenuResultDetail(CCmdUI* pCmdUI); afx_msg void OnNaviMenuDetailCbSel( UINT nID ); public: /// /// @brief /// 保存页面 /// /// @return /// void /// void _SavePage(); protected: /// /// @brief /// 创建SMV设置报表 /// /// @return /// void /// void _createSmvReport(); /// /// @brief /// 显示Smv报表 /// /// @return /// void /// void _showSmvReport(); /// /// @brief /// 更新Smv报表 /// /// @return /// void /// void _updateSmvReport(); /// /// @brief /// 创建GOOSE设置报表 /// /// @return /// void /// void _createGooseReport(); /// /// @brief /// 显示goose报表 /// /// @return /// void /// void _showGooseReport(); /// /// @brief /// 更新Goose报表 /// /// @return /// void /// void _updateGooseReport(); /// /// @brief /// 高亮F2中选中的goose控制块 /// /// @return /// void /// void _highlightGooseF2( BOOL bHighLight = TRUE); /// /// @brief /// 创建DI改变报表 /// /// @return /// void /// void _createDIActionReport(); /// /// @brief /// 显示DIAction报表 /// /// @return /// void /// void _showDIActionReport(); /// /// @brief /// 更新DIAction报表 /// /// @return /// void /// void _updateDIActionReport(); /// /// @brief /// 重置菜单 /// /// @return /// void /// void _resetMenu(); /// /// @brief /// 重载加载菜单选项,使自动更新菜单 /// /// @return /// void /// void _loadNaviMenu(); /// /// @brief /// 设置tips, /// /// @param /// bAssign FALSE:默认获取焦点报表的焦点Item值, TRUE:显示指定的字符串 strTips /// /// @param /// strTips 指定的字符串 strTips /// /// @return /// void /// void _updateTips(BOOL bAssign = FALSE, CString strTips = _T("")); public: typedef std::map<UINT, CGooseCb*> CUINTGooseCbMap; CUINTGooseCbMap m_gooseCbMap; ///< cmdID对应的goose控制块映射表 eMRDShowReportType m_eShowReportType; ///< 显示的报表类型 CReportV m_ctlSmvReport; ///< smv报表 CReportV m_ctlGooseReport; ///< goose报表 CReportV m_ctlDIActionReport; ///< 设置报表 BOOL m_bShowAllData; ///< 标识是否过滤没有改变的数据通道 CGooseCb* m_pGooseCb; ///< 当前goose控制块 CStateTestResult* m_pStateTestResult; ///< 当前状态结果 CDsmDataLayer* m_pDataLayer; ///< 数据层指针 int m_nSmvGseFocusRowIndex; ///< 当前选中的行(用于显示提示) int m_nSmvGseFocusColIndex; ///< 当前选中的列(用于显示提示) };
[ "383789599@qq.com" ]
383789599@qq.com
935ace9a68d8405816dc4ce141e1a775e3233b3d
cfeeb8a7aea90d5acd4fc9ce1194ac4c426bea70
/IOCP_DummyClient/IOCP_DummyClient/CLFMemoryPool_TLS.h
62f5b3923b9cc44a2e855a5c27cb34fb174ef7c7
[ "MIT" ]
permissive
kbm0996/-Network-IOCP-EchoServerClient
17b1169514b882aaeeaa4bb2b9a4ffbd93032e3a
91f12607c522dd664d5997681abb5a503d9109bd
refs/heads/master
2020-08-15T16:31:36.913524
2019-12-15T21:22:40
2019-12-15T21:22:40
215,371,370
2
1
null
null
null
null
UHC
C++
false
false
6,068
h
/*--------------------------------------------------------------- MemoryPool TLS TLS(Thread Local Storage)를 활용해 하나의 메모리풀로부터 스레드별로 데이터 청크 할당 프로세스당 TLS 개수가 제한되어있으므로 이의 유의해야 함 - 클래스 * CLFMemoryPool_TLS: CDataChunk를 관리하는 메모리풀을 내장한 클래스 * CDataChunk : DATA Block 덩어리. 재활용X. - 사용법 CLFMemoryPool_TLS<DATA> MemPool(300, FALSE); DATA *pData = MemPool.Alloc(); ~ pData 사용 ~ MemPool.Free(pDATA); ----------------------------------------------------------------*/ #ifndef __MEMORY_POOL_TLS__ #define __MEMORY_POOL_TLS__ #include "CLFMemoryPool.h" #include "CSystemLog.h" #include "CrashDump.h" #define df_CHECK_CODE 0x12345ABCDE6789F0 namespace mylib { //#define DATA int template<class DATA> class CLFMemoryPool_TLS { private: class CChunk; struct st_CHUNK_NODE { CChunk* pChunk; UINT64 iCheck; DATA Data; }; public: ////////////////////////////////////////////////////////////////////////// // 생성자, 파괴자. // // Parameters: (int) 최대 블럭 개수. // (bool) 생성자 호출 여부. // Return: ////////////////////////////////////////////////////////////////////////// CLFMemoryPool_TLS(LONG lChunkSize = 3000); virtual ~CLFMemoryPool_TLS(); ////////////////////////////////////////////////////////////////////////// // CHUNK 할당, 해제 // // Parameters: 없음. // Return: (DATA *) 데이터 블럭 포인터. ////////////////////////////////////////////////////////////////////////// DATA* Alloc(); bool Free(DATA *pData); private: ////////////////////////////////////////////////////////////////////////// // CHUNK 할당 // // Parameters: 없음. // Return: (DATA *) 데이터 블럭 포인터. ////////////////////////////////////////////////////////////////////////// CChunk* ChunkAlloc(); public: ////////////////////////////////////////////////////////////////////////// // 사용 중인 블럭 개수 // // Parameters: 없음. // Return: (int) 메모리 풀 내부 전체 개수, ////////////////////////////////////////////////////////////////////////// int GetUseSize() { return _lUseCnt; } ////////////////////////////////////////////////////////////////////////// // 확보된 청크 개수 // // Parameters: 없음. // Return: (int) 메모리 풀 내부 전체 개수, ////////////////////////////////////////////////////////////////////////// int GetAllocSize() { return _pChunkPool->GetAllocSize(); } private: // TLS DWORD _dwTlsIndex; // CHUNK CLFMemoryPool<CChunk>* _pChunkPool; LONG _lChunkSize; // 청크 크기 // MONITOR LONG _lUseCnt; // 사용중인 블럭 수 private: class CChunk { public: ////////////////////////////////////////////////////////////////////////// // 생성자, 파괴자. // // Parameters: // Return: ////////////////////////////////////////////////////////////////////////// CChunk(); virtual ~CChunk() { delete[] _pDataNode; } void Init(CLFMemoryPool_TLS<DATA>* pMemoryPool, LONG lChunkSize); void Clear(LONG lChunkSize); DATA* Alloc(); bool Free(); private: friend class CLFMemoryPool_TLS<DATA>; CLFMemoryPool_TLS<DATA>* _pMemoryPoolTLS; // BLOCK st_CHUNK_NODE* _pDataNode; // 데이터 블럭 LONG _lChunkSize; // 청크 내 블럭 개수 (최대 블럭 개수) LONG _lAllocIndex; // 사용중인 블럭 개수 (인덱스) LONG _iFreeCount; // 0이 되면 Free }; }; template<class DATA> CLFMemoryPool_TLS<DATA>::CLFMemoryPool_TLS(LONG lChunkSize) { _dwTlsIndex = TlsAlloc(); if (_dwTlsIndex == TLS_OUT_OF_INDEXES) CRASH(); _pChunkPool = new CLFMemoryPool<CChunk>(); _lChunkSize = lChunkSize; _lUseCnt = 0; } template<class DATA> CLFMemoryPool_TLS<DATA>::~CLFMemoryPool_TLS() { TlsFree(_dwTlsIndex); delete[] _pChunkPool; } template<class DATA> DATA* CLFMemoryPool_TLS<DATA>::Alloc() { CChunk* pChunk = (CChunk*)TlsGetValue(_dwTlsIndex); if (pChunk == nullptr) pChunk = ChunkAlloc(); InterlockedIncrement(&_lUseCnt); return pChunk->Alloc(); } template<class DATA> bool CLFMemoryPool_TLS<DATA>::Free(DATA *pData) { st_CHUNK_NODE* pNode = (st_CHUNK_NODE*)((char*)pData - (sizeof(st_CHUNK_NODE::pChunk) + sizeof(st_CHUNK_NODE::iCheck))); if (pNode->iCheck != df_CHECK_CODE) CRASH(); InterlockedDecrement(&_lUseCnt); pNode->pChunk->Free(); return true; } template<class DATA> typename CLFMemoryPool_TLS<DATA>::CChunk * CLFMemoryPool_TLS<DATA>::ChunkAlloc() { CChunk* pChunk = _pChunkPool->Alloc(); if (pChunk->_pDataNode == nullptr) { pChunk->Init(this, _lChunkSize); } else { pChunk->Clear(_lChunkSize); } TlsSetValue(_dwTlsIndex, pChunk); return pChunk; } template<class DATA> CLFMemoryPool_TLS<DATA>::CChunk::CChunk() { _pMemoryPoolTLS = nullptr; _pDataNode = nullptr; _lChunkSize = 0; _lAllocIndex = 0; _iFreeCount = 0; } template<class DATA> void CLFMemoryPool_TLS<DATA>::CChunk::Init(CLFMemoryPool_TLS<DATA>* pMemoryPool, LONG lChunkSize) { _pMemoryPoolTLS = pMemoryPool; _lChunkSize = lChunkSize; _iFreeCount = lChunkSize; _pDataNode = new st_CHUNK_NODE[_lChunkSize]; for (int i = 0; i < lChunkSize; ++i) { _pDataNode[i].pChunk = this; _pDataNode[i].iCheck = df_CHECK_CODE; } } template<class DATA> void CLFMemoryPool_TLS<DATA>::CChunk::Clear(LONG lChunkSize) { _lAllocIndex = 0; _iFreeCount = lChunkSize; } template<class DATA> DATA* CLFMemoryPool_TLS<DATA>::CChunk::Alloc() { DATA* pData = &_pDataNode[_lAllocIndex].Data; if (_lChunkSize == InterlockedIncrement(&_lAllocIndex)) _pMemoryPoolTLS->ChunkAlloc(); return pData; } template<class DATA> bool CLFMemoryPool_TLS<DATA>::CChunk::Free() { if (0 == InterlockedDecrement(&_iFreeCount)) { _pMemoryPoolTLS->_pChunkPool->Free(_pDataNode->pChunk); return true; } return false; } } #endif
[ "kbm0996@naver.com" ]
kbm0996@naver.com
ce0f079f6a964417ed0b4d22c00e6638315110c9
9a2121d51f15d2fe4b242a01dd6463be44f2a251
/c++/BinarySearch1.h
f6b87381881cfb43b43a75fee7d688a5f8d87958
[]
no_license
marek5050/cs109
0f60a2162e8990caebe7797be302658fe79a2261
d03807b13092a977c4cc931594cd8394c8b8e870
refs/heads/master
2020-12-07T05:24:45.186061
2016-05-18T19:50:38
2016-05-18T19:50:38
35,233,438
0
0
null
2015-05-07T17:21:52
2015-05-07T17:21:50
C++
UTF-8
C++
false
false
1,244
h
// --------------- // BinarySearch1.h // --------------- #ifndef BinarySearch1_h #define BinarySearch1_h #include <cassert> // assert #include "LowerBound1.h" template <typename RI, typename T> bool binary_search_recursion_1 (RI b, RI e, const T& v) { if (b == e) return false; const RI p = b + ((e - b) / 2); assert((p >= b) && (p < e)); if (*p < v) return binary_search_recursion_1(p + 1, e, v); if (v < *p) return binary_search_recursion_1(b, p, v); return true;;} template <typename RI, typename T> bool binary_search_iteration_1 (RI b, RI e, const T& v) { while (b != e) { const RI p = b + ((e - b) / 2); assert((p >= b) && (p < e)); if (*p < v) b = p + 1; else if (v < *p) e = p; else return true;} return false;} template <typename RI, typename T> bool binary_search_recursion_2 (RI b, RI e, const T& v) { const RI p = lower_bound_recursion(b, e, v); return (p != e) && !(v < *p);} template <typename RI, typename T> bool binary_search_iteration_2 (RI b, RI e, const T& v) { const RI p = lower_bound_iteration(b, e, v); return (p != e) && !(v < *p);} #endif // BinarySearch1_h
[ "downing@cs.utexas.edu" ]
downing@cs.utexas.edu
1463c926bc2a34f4211f680bde99356dd5af49b8
8a7e5803bd6dfab67e43f338e382e9f20b07c8bd
/tools/RandomCubeToDoFormula.cpp
602301fd634056f26835d34857b2f7fa647f4b28
[]
no_license
xiaocjnu/cubesolve
0d78f31dbb11ec02798323c200b07aff6c275e7d
f32ad6187466f0c7a2c9766b9fa96ba8bf6a1e8c
refs/heads/master
2023-05-07T19:24:17.824302
2021-06-05T06:36:17
2021-06-05T06:36:17
374,013,715
0
0
null
null
null
null
UTF-8
C++
false
false
3,703
cpp
// 用来生成 CFOP 和 层先法公式练习所用的状态 #include "RandomCubeToDoFormula.h" #include <tuple> using namespace std; using namespace cs; AxisCubieCube randomCubeToDoFormulaF2L(int axis, int idx) { AxisCubieCube cc; if (idx < 0 || idx >= 41 || axis < 0 || axis >= 24) return cc; cc.cubie = CubieCube::randomCube(); cc = cc.rotateToAxis(axis); HumanSolverCFOP solver; vector<Move> moves = solver.solveF2L(cc); cc = cc.move(moves); cc = cc.rotateToAxis(axis); vector<Move> mvf = get<2>(HumanSolverCFOP::F2L_table[idx]); AxisCubieCube aa = cc.move(mvf); cc = cc.rotateToAxis(aa.axis); AxisCubieCube dd; dd = dd.move(mvf); cc = cc * dd.inv(); return cc; } AxisCubieCube randomCubeToDoFormulaF2L(int axis) { int idx = randInt(0, 40); return randomCubeToDoFormulaF2L(axis, idx); } static int _rand_axis_with_bottom(int bottom) { vector<int> axis; for (int i = 0; i < 24; ++i) { AxisCube ac = AxisCube::fromValidIdx(i); if (ac[3] == bottom) axis.push_back(i); } int j = randInt(0, axis.size() - 1); return axis[j]; } cs::AxisCubieCube randomCubeToDoFormulaF2L_v2(int bottom, int idx) { if (bottom < 0 || bottom >= 6) return cs::AxisCubieCube(); int axis = _rand_axis_with_bottom(bottom); AxisCubieCube cc = randomCubeToDoFormulaF2L(axis, idx); int n = randInt(0, 3); for (int i = 0; i < n; ++i) { cc = cc.move(Ux1); } return cc; } cs::AxisCubieCube randomCubeToDoFormulaF2L_v2(int bottom) { int idx = randInt(0, 40); return randomCubeToDoFormulaF2L_v2(bottom, idx); } cs::AxisCubieCube randomCubeToDoFormulaOLL(int axis, int idx) { AxisCubieCube cc; if (idx < 0 || idx >= 57 || axis < 0 || axis >= 24) return cc; cc.cubie = CubieCube::randomCube(); cc = cc.rotateToAxis(axis); HumanSolverCFOP solver; vector<Move> moves = solver.solveOLL(cc); cc = cc.move(moves); cc = cc.rotateToAxis(axis); vector<Move> mvf = get<2>(HumanSolverCFOP::OLL_table[idx]); AxisCubieCube aa = cc.move(mvf); cc = cc.rotateToAxis(aa.axis); AxisCubieCube dd; dd = dd.move(mvf); cc = cc * dd.inv(); return cc; } cs::AxisCubieCube randomCubeToDoFormulaOLL(int axis) { int idx = randInt(0, 56); return randomCubeToDoFormulaOLL(axis, idx); } cs::AxisCubieCube randomCubeToDoFormulaOLL_v2(int bottom, int idx) { if (bottom < 0 || bottom >= 6) return cs::AxisCubieCube(); int axis = _rand_axis_with_bottom(bottom); AxisCubieCube cc = randomCubeToDoFormulaOLL(axis, idx); int n = randInt(0, 3); for (int i = 0; i < n; ++i) { cc = cc.move(Ux1); } return cc; } cs::AxisCubieCube randomCubeToDoFormulaOLL_v2(int bottom) { int idx = randInt(0, 56); return randomCubeToDoFormulaOLL_v2(bottom, idx); } cs::AxisCubieCube randomCubeToDoFormulaPLL(int axis, int idx) { AxisCubieCube cc; if (idx < 0 || idx >= 21 || axis < 0 || axis >= 24) return cc; cc = cc.rotateToAxis(axis); vector<Move> mvf = get<2>(HumanSolverCFOP::PLL_table[idx]); AxisCubieCube aa = cc.move(mvf); cc = cc.rotateToAxis(aa.axis); AxisCubieCube dd; dd = dd.move(mvf); cc = cc * dd.inv(); return cc; } cs::AxisCubieCube randomCubeToDoFormulaPLL(int axis) { int idx = randInt(0, 20); return randomCubeToDoFormulaPLL(axis, idx); } cs::AxisCubieCube randomCubeToDoFormulaPLL_v2(int bottom, int idx) { if (bottom < 0 || bottom >= 6) return cs::AxisCubieCube(); int axis = _rand_axis_with_bottom(bottom); AxisCubieCube cc = randomCubeToDoFormulaPLL(axis, idx); int n = randInt(0, 3); for (int i = 0; i < n; ++i) { cc = cc.move(Ux1); } return cc; } cs::AxisCubieCube randomCubeToDoFormulaPLL_v2(int bottom) { int idx = randInt(0, 20); return randomCubeToDoFormulaPLL_v2(bottom, idx); }
[ "huxiaobin@gancube.com" ]
huxiaobin@gancube.com
4395f6f96672b2af9b5bdd692eb3782e908bdd95
33b567f6828bbb06c22a6fdf903448bbe3b78a4f
/opencascade/ShapeAnalysis_TransferParameters.hxx
477584834be5458121d079f71fd96e67dfc1d5e0
[ "Apache-2.0" ]
permissive
CadQuery/OCP
fbee9663df7ae2c948af66a650808079575112b5
b5cb181491c9900a40de86368006c73f169c0340
refs/heads/master
2023-07-10T18:35:44.225848
2023-06-12T18:09:07
2023-06-12T18:09:07
228,692,262
64
28
Apache-2.0
2023-09-11T12:40:09
2019-12-17T20:02:11
C++
UTF-8
C++
false
false
3,703
hxx
// Created on: 1999-06-21 // Created by: Galina KULIKOVA // Copyright (c) 1999 Matra Datavision // Copyright (c) 1999-2014 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _ShapeAnalysis_TransferParameters_HeaderFile #define _ShapeAnalysis_TransferParameters_HeaderFile #include <Standard.hxx> #include <Standard_Type.hxx> #include <TopoDS_Edge.hxx> #include <TopoDS_Face.hxx> #include <Standard_Transient.hxx> #include <TColStd_HSequenceOfReal.hxx> class ShapeAnalysis_TransferParameters; DEFINE_STANDARD_HANDLE(ShapeAnalysis_TransferParameters, Standard_Transient) //! This tool is used for transferring parameters //! from 3d curve of the edge to pcurve and vice versa. //! //! Default behaviour is to trsnafer parameters with help //! of linear transformation: //! //! T2d = myShift + myScale * T3d //! where //! myScale = ( Last2d - First2d ) / ( Last3d - First3d ) //! myShift = First2d - First3d * myScale //! [First3d, Last3d] and [First2d, Last2d] are ranges of //! edge on curve and pcurve //! //! This behaviour can be redefined in derived classes, for example, //! using projection. class ShapeAnalysis_TransferParameters : public Standard_Transient { public: //! Creates empty tool with myShift = 0 and myScale = 1 Standard_EXPORT ShapeAnalysis_TransferParameters(); //! Creates a tool and initializes it with edge and face Standard_EXPORT ShapeAnalysis_TransferParameters(const TopoDS_Edge& E, const TopoDS_Face& F); //! Initialize a tool with edge and face Standard_EXPORT virtual void Init (const TopoDS_Edge& E, const TopoDS_Face& F); //! Sets maximal tolerance to use linear recomputation of //! parameters. Standard_EXPORT void SetMaxTolerance (const Standard_Real maxtol); //! Transfers parameters given by sequence Params from 3d curve //! to pcurve (if To2d is True) or back (if To2d is False) Standard_EXPORT virtual Handle(TColStd_HSequenceOfReal) Perform (const Handle(TColStd_HSequenceOfReal)& Params, const Standard_Boolean To2d); //! Transfers parameter given by sequence Params from 3d curve //! to pcurve (if To2d is True) or back (if To2d is False) Standard_EXPORT virtual Standard_Real Perform (const Standard_Real Param, const Standard_Boolean To2d); //! Recomputes range of curves from NewEdge. //! If Is2d equals True parameters are recomputed by curve2d else by curve3d. Standard_EXPORT virtual void TransferRange (TopoDS_Edge& newEdge, const Standard_Real prevPar, const Standard_Real currPar, const Standard_Boolean To2d); //! Returns True if 3d curve of edge and pcurve are SameRange //! (in default implementation, if myScale == 1 and myShift == 0) Standard_EXPORT virtual Standard_Boolean IsSameRange() const; DEFINE_STANDARD_RTTIEXT(ShapeAnalysis_TransferParameters,Standard_Transient) protected: Standard_Real myFirst; Standard_Real myLast; TopoDS_Edge myEdge; Standard_Real myMaxTolerance; private: Standard_Real myShift; Standard_Real myScale; Standard_Real myFirst2d; Standard_Real myLast2d; TopoDS_Face myFace; }; #endif // _ShapeAnalysis_TransferParameters_HeaderFile
[ "adam.jan.urbanczyk@gmail.com" ]
adam.jan.urbanczyk@gmail.com
1905716e09d1afc0c1e0106acc214f013dc6de37
37d211eebb4bac08244a64bfe931f97420936682
/字符串通配符/字符串通配符/z.cpp
df2c012b06f806613b5e0bf5f966b28977eaa446
[]
no_license
girl-6/C-
203cf1fe09152098af9a346f144657352b5fc15f
05cc7c00398297def51e2211103e4fa8556f5701
refs/heads/master
2021-07-11T03:23:09.258195
2020-07-20T05:48:48
2020-07-20T05:48:48
179,990,456
2
0
null
null
null
null
UTF-8
C++
false
false
1,010
cpp
#include <iostream> #include <string> using namespace std; bool Compar(string &s1, string &s2) { if (s2.empty()) return false; for (int i = 0; i < s2.size(); i++) { if (s1[i] >= 'A'&&s1[i] <= 'Z') s1[i] += 32; if (s2[i] >= 'A'&&s2[i] <= 'Z') s2[i] += 32; if (s1[i] == s2[i] || s1[i] == '?') continue; else if (s1[i] == '*') { int j = i; while (j < s2.size()) { if (s2[j] == '.') break; else j++; } if (j == s2.size()) //return true; break; else { int k = i; while (k < s1.size()) { if (s1[k] == '.') break; else k++; } if (k == s1.size()) return false; else { s1 = s1.substr(k, s1.size() - k); s2 = s2.substr(j, s2.size() - j); Compar(s1, s2); } } } else return false; } return true; } int main() { string s3; string s4; while (cin>>s3>>s4) /*getline(cin, s3); getline(cin, s4);*/ cout << Compar(s3, s4) << endl; system("pause"); return 0; }
[ "1971561926@qq.com" ]
1971561926@qq.com
01bf7d4daccf0074c4565428deb8dc03e9fe37f1
33bd7c6d8df57039ec636cbf62f02265e7b861fb
/include/h3api/H3Assets/H3TextTable.cpp
06d07a07177bff750a19352ded0018608756d49f
[ "MIT" ]
permissive
RoseKavalier/H3API
26f5bd1e2d63d1a61f762bba16a009ba33bf021f
49c65f1e30fe82a2156918aa7e45349f91a8524d
refs/heads/master
2023-08-18T14:07:00.214661
2022-11-14T02:27:17
2022-11-14T02:27:17
367,050,838
21
8
MIT
2023-08-06T16:55:05
2021-05-13T13:04:01
C++
UTF-8
C++
false
false
2,364
cpp
////////////////////////////////////////////////////////////////////// // // // Created by RoseKavalier: // // rosekavalierhc@gmail.com // // Created or last updated on: 2021-02-03 // // ***You may use or distribute these files freely // // so long as this notice remains present.*** // // // ////////////////////////////////////////////////////////////////////// #include "h3api/H3Assets/H3TextTable.hpp" namespace h3 { _H3API_ H3Vector<H3Vector<LPCSTR>*>& H3TextTable::GetText() { return text; } _H3API_ UINT32 H3TextTable::CountRows() const { return text.Count(); } _H3API_ H3TextTable* H3TextTable::Load(LPCSTR name) { return THISCALL_1(H3TextTable*, 0x55C2B0, name); } _H3API_ VOID H3TextTable::UnLoad() { vTable->vEraseFromResourceManager(this); } _H3API_ H3Vector<LPCSTR>& H3TextTable::operator[](UINT row) { return *text[row]; } _H3API_ H3TextTable::iterator H3TextTable::begin() { return iterator(text.begin()); } _H3API_ H3TextTable::iterator H3TextTable::end() { return iterator(text.end()); } _H3API_ H3TextTable::iterator::iterator(H3Vector<LPCSTR>** vec) : data(vec) { } _H3API_ H3TextTable::iterator& H3TextTable::iterator::operator++() { ++data; return *this; } _H3API_ H3TextTable::iterator H3TextTable::iterator::operator++(int) { iterator it(data); ++data; return it; } _H3API_ H3Vector<LPCSTR>& H3TextTable::iterator::operator*() { return **data; } _H3API_ H3Vector<LPCSTR>* H3TextTable::iterator::operator->() { return *data; } _H3API_ LPCSTR H3TextTable::iterator::operator[](UINT column) { return (**data)[column]; } _H3API_ BOOL H3TextTable::iterator::operator==(const iterator& other) { return data == other.data; } _H3API_ BOOL H3TextTable::iterator::operator!=(const iterator& other) { return data != other.data; } } /* namespace h3 */
[ "rosekavalierhc@gmail.com" ]
rosekavalierhc@gmail.com
34e11e34dfd90da897cc6c2760d0fd33c92de0d1
4a13b76504c735d5a82a64ab2f6186a5d0df5f7b
/count-and-say.cpp
9d31b7b0b87344e2c6fd24904aaaca6828b69888
[]
no_license
lispc/leetcode
e586513217cc308418f15334d3fd42000aced3f9
e3cb380d364083a94fdf859aa38d5706206a9cb7
refs/heads/master
2020-06-05T05:16:58.867428
2014-07-14T13:30:39
2014-07-14T13:30:39
21,820,438
1
0
null
null
null
null
UTF-8
C++
false
false
640
cpp
class Solution { public: string it(string s) { stringstream ss; int l = s.size(); char prev=s[0]; int cnt=1; for(int i=1;i<l;i++) { if(s[i]!=prev) { ss<<cnt<<prev; cnt=1; prev=s[i]; } else { cnt++; } } ss<<cnt<<prev; return ss.str(); } string countAndSay(int n) { string seed="1"; while(--n) { seed=it(seed); } return seed; } };
[ "mycinbrin@gmail.com" ]
mycinbrin@gmail.com
51affbe6e0ae0c0f3817996c66b2c1bcd00b349b
8bfa3c91abe7f22bffc3115c1fa48ed1a4aabd82
/ABC/119/D/lazy_faith.cpp
5c231b3edee4bc6ae0e850eef2581dcb4d447e7b
[]
no_license
yugo1103/atcoder
96a0dcd41704fadc0a1ef3253cdffa4a961fdc0a
9b2d0b1a0f178cd442d51d2ad07added982d2a92
refs/heads/master
2020-07-26T04:04:41.019118
2020-03-30T10:42:39
2020-03-30T10:42:39
208,528,448
0
0
null
null
null
null
UTF-8
C++
false
false
2,601
cpp
#include<bits/stdc++.h> using namespace std; typedef long long ll; typedef long double ld; #define rep(i, n) for(int i = 0; i < n; i++) int main(void){ ll a, b, q; cin >> a >> b >> q; pair<ll, ll> sq[a + q], tq[b + q]; pair<ll, ll> x[q]; rep(i, a){ cin >> sq[i].first; sq[i].second = 0; } rep(i, b){ cin >> tq[i].first; tq[i].second = 1; } rep(i, q){ ll tmp; cin >> tmp; sq[a + i].first = tmp; sq[a + i].second = 2; tq[b + i].first = tmp; tq[b + i].second = 2; x[i].first = tmp; x[i].second = i; } sort(x, x + q); sort(sq, sq + a + q); sort(tq, tq + b + q); ll sr[q], sl[q], tr[q], tl[q]; ll count = 0; ll l = -100000000000; rep(i, a + q){ if(sq[i].second == 0){ l = sq[i].first; }else if(sq[i].second == 2){ sl[count] = l; count++; } } ll r = -100000000000; count = q - 1; rep(i, a + q){ if(sq[a + q - i - 1].second == 0){ r = sq[a + q - i - 1].first; }else if(sq[a + q - i - 1].second == 2){ sr[count] = r; count--; } } l = -100000000000; count = 0; rep(i, b + q){ if(tq[i].second == 1){ l = tq[i].first; }else if(tq[i].second == 2){ tl[count] = l; count++; } } r = -100000000000; count = q - 1; rep(i, b + q){ if(tq[b + q - i - 1].second == 1){ r = tq[b + q - i - 1].first; }else if(tq[b + q - i - 1].second == 2){ tr[count] = r; count--; } } pair<ll, ll> ans[q]; rep(i, q){ ans[i].second = 100000000000; if(sr[i] != -100000000000 && tl[i] != -100000000000){ ans[i].second = sr[i] - tl[i] + min(x[i].first - tl[i], sr[i] - x[i].first); } if(tr[i] != -100000000000 && sl[i] != -100000000000){ ans[i].second = min(ans[i].second, tr[i] - sl[i] + min(x[i].first - sl[i], tr[i] - x[i].first)); } if(tl[i] != -100000000000 && sl[i] != -100000000000){ ans[i].second = min(ans[i].second, max(x[i].first - tl[i], x[i].first - sl[i])); } if(tr[i] != -100000000000 && sr[i] != -100000000000){ ans[i].second = min(ans[i].second, max(tr[i] - x[i].first, sr[i] - x[i].first)); } ans[i].first = x[i].second; } sort(ans, ans + q); rep(i, q){ cout << ans[i].second << endl; } return 0; }
[ "y1103orz@akane.waseda.jp" ]
y1103orz@akane.waseda.jp
56eb36e35021c486973d300e36531bdf27fddefe
6090fd92273ffae6ac2fd1e6d63798267f2e797f
/LinkedStack/src/linked_stack.h
9e12959a598fc7d12964347586b4ec0b23f5dfc7
[]
no_license
vapstor/EstruturaDados
d62f0bc1708dc6932f6816e21b02b4a4f5942ea2
2475526bca22d9dfad495cddf869f1148b3c11d6
refs/heads/master
2021-07-12T08:21:42.475268
2017-10-17T05:02:10
2017-10-17T05:02:10
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,001
h
//! Copyright [2017] <Acauã Pitta> #ifndef STRUCTURES_LINKED_STACK_H #define STRUCTURES_LINKED_STACK_H #include "./linked_list.h" #include <cstdint> // std::size_t #include <stdexcept> // C++ Exceptions namespace structures { template<typename T> //! Class Pilha Encadeada class LinkedStack : LinkedList<T>{ public: LinkedStack() { // LinkedList<T>::LinkedList(); top_ = NULL; size_ = 0; } ~LinkedStack() { clear(); } //! limpa pilha void clear() { // LinkedList<T>::clear(); Node* anterior; Node* atual = top_; while (!empty()) { anterior = atual; atual = atual->next(); delete anterior; size_--; } top_ = NULL; } //! empilha void push(const T& data) { // LinkedList<T>::push_front(data); Node* novo = new Node(data, top_); if (novo == NULL) { throw std::out_of_range("Sem Memória Push!"); } top_ = novo; size_++; } //! desempilha T pop() { // return LinkedList<T>::pop(0); if (empty()) { throw std::out_of_range("Sem Memória Pop!"); } Node* deletar; T dadoVolta = top_->data(); deletar = top_; top_ = top_->next(); size_--; delete deletar; return dadoVolta; } //! dado no topo T& top() const { if (empty()) { throw std::out_of_range("Pilha Vazia Top()"); } return top_->data(); // return LinkedList<T>::at(0); } //! pilha vazia bool empty() const { return size_ == 0; // return LinkedList<T>::empty(); } //! tamanho da pilha std::size_t size() const { return size_; // return LinkedList<T>::size(); } private: //! Classe Elemento class Node { public: //! Construtor explicit Node(const T& data): data_{data} {} //! Construtor com next Node(const T& data, Node* next): data_{data}, next_{next} {} //! getter: info T& data() { return data_; } //! getter-constante: info const T& data() const { return data_; } //! getter: próximo Node* next() { return next_; } //! getter-constante: próximo const Node* next() const { return next_; } //! setter: próximo void next(Node* next) { next_ = next; } private: T data_; Node* next_; }; Node* top_; // nodo-topo std::size_t size_; // tamanho }; } //! namespace structures #endif
[ "acaua.pitta@hotmail.com" ]
acaua.pitta@hotmail.com
0558e5a3856ce56dbbd016feb794597b254d343c
36f94605da715fcf8820224cf4789c042f5dfbc4
/GramN2/GramN2_pssm/building_batchfile_pssm.cpp
8cdb2c522e22d8735ce17ee76e252da7b9ace12e
[]
no_license
swakkhar/ProteinLocalization
6f5334c2110c6b1d9b2a76d3f8e2371fc264fb5a
bd5c4b91d303a8ce8eb2c3601895b9ebdd197e4a
refs/heads/master
2016-09-12T12:38:45.084062
2016-04-27T13:43:45
2016-04-27T13:43:45
57,215,546
0
0
null
null
null
null
UTF-8
C++
false
false
1,254
cpp
#include <iostream> #include <fstream> #include <cctype> #include <ctype.h> #include <iomanip> #include <cstring> #include <string.h> #include <stdlib.h> using namespace std; int main() { long i,j; int m =10; char num_data[7]; char format[]=".txt"; char add_text[50]="dos2unix train"; ofstream out("e:\\pssm_convert.sh", ios::out); if(!out) { cout<<"shiiiiiiiiiiiiiiiit"; return 0; } //out<<"cd c:\\\\Program Files\\NCBI\\blast-2.2.25+\\bin"; //out<<endl; for(i=1;i<11212;i++) { j=i; itoa(j,num_data,10); strcat(add_text,num_data); strcat(add_text,format); //strcat(add_text," -db /export/home/s2784083/db/nr -out /export/home/s2784083/testT/outfile/out"); //strcat(add_text,num_data); //strcat(add_text,format); //strcat(add_text," -num_iterations 3 -out_ascii_pssm /export/home/s2784083/testT/pssmfile/pssm"); //strcat(add_text,num_data); //strcat(add_text,format); //strcat(add_text," -inclusion_ethresh 0.001"); out<<add_text; out<<'\n'; strcpy(add_text,"dos2unix train"); } out.close(); return 0; }
[ "sshatabda@gmail.com" ]
sshatabda@gmail.com
3d13d0a9c0c3f343f836570a50fe4834c809bc77
cd44c5b4e2687b38722b8ea74f0e9ca8930fb2c9
/abc067_a.cpp
5e8988f70debb8c44d74ba701df1091d84bee7b4
[]
no_license
sigu1011/atcoder
b1a3b54d9f1e8c178e5f58505cca69b5ace1b23f
8280c422a065b676eefeaf2374229635a92531bc
refs/heads/master
2020-06-11T17:44:17.073065
2020-01-26T14:50:48
2020-01-26T14:50:48
194,039,322
0
0
null
null
null
null
UTF-8
C++
false
false
231
cpp
#include <bits/stdc++.h> using namespace std; int main() { int A, B; scanf("%d%d", &A, &B); if (A % 3 == 0 || B % 3 == 0 || (A + B) % 3 == 0) { printf("Possible"); } else { printf("Impossible"); } return 0; }
[ "52273288+sigu1011@users.noreply.github.com" ]
52273288+sigu1011@users.noreply.github.com
454a9a3f8b70820cb9be7fef64bd34ea5f233148
8e0e9ecac8a3a79539d80cd41b1d66e476abd4a2
/src/app/MIA/src/tool_factory.h
1aa1760274a92c700080c23d84645673ca150348
[]
no_license
Tzishi/FlashPhoto
ddf28a4ece3bff2d79006061273af60e1b76739c
31cb94b9c2783c048402a29595a31ee12295183c
refs/heads/master
2020-04-08T18:43:36.078519
2018-11-29T07:02:15
2018-11-29T07:02:15
159,621,953
0
0
null
null
null
null
UTF-8
C++
false
false
1,938
h
/******************************************************************************* * Name : tool_factory.h * Project : image_tools * Module : Tool * Copyright : 2016 CSCI3081W TAs. All rights reserved. * Description : Header file for ToolFactory * Creation Data : 2/15/15 * Original Author : Seth Johnson * ******************************************************************************/ #ifndef PROJECT_ITERATION3_SRC_APP_MIA_SRC_TOOL_FACTORY_H_ #define PROJECT_ITERATION3_SRC_APP_MIA_SRC_TOOL_FACTORY_H_ /******************************************************************************* * Includes ******************************************************************************/ #include <vector> #include "lib/libimgtools/src/imgtools.h" /******************************************************************************* * Namespace Definitions ******************************************************************************/ namespace image_tools { /******************************************************************************* * Class Definitions ******************************************************************************/ /** * @brief Implementation of factory pattern to handle tool creation * This enables easy extension/addition of new tools. */ class ToolFactory { public: /** * @brief The list of tools that can be created by the factory and used by the * application */ enum TOOLS { TOOL_PEN = 0, TOOL_STAMP = 1, NUMTOOLS = 2 }; /** * @brief Return the total # of tools in the application */ static int num_tools(void) { return NUMTOOLS; } /** * @brief Create a tool from the list of defined tools * @return The initialized tool, or nullptr if an invalid index was passed */ static Tool* CreateTool(int tool_id); }; } /* namespace image_tools */ #endif /* PROJECT_ITERATION3_SRC_APP_MIA_SRC_TOOL_FACTORY_H_ */
[ "tengx096@umn.edu" ]
tengx096@umn.edu
d3f6c07cb9b967d09ce7b2b6def1123a2f4b2010
99cf7ed46654fabf55b4bd0a4e16eb512177e5c3
/Public_Library/Core/Matrices/SPARSE_MATRIX_THREADED_CONSTRUCTION.cpp
81ce174382453be7bfa387d3dfa1b339c2a004ec
[]
no_license
byrantwithyou/PhysBAM
095d0483673f8ca7cee04390e98b7f5fa8d230ca
31d8fdc35dbc5ed90d6bd4fd266eb76e7611c4a5
refs/heads/master
2022-03-29T06:20:32.128928
2020-01-21T15:15:26
2020-01-21T15:15:26
187,265,883
0
1
null
null
null
null
UTF-8
C++
false
false
2,562
cpp
//##################################################################### // Copyright 2017 Craig Schroeder // This file is part of PhysBAM whose distribution is governed by the license contained in the accompanying file PHYSBAM_COPYRIGHT.txt. //##################################################################### #include <Core/Matrices/SPARSE_MATRIX_FLAT_MXN.h> #include <Core/Matrices/SPARSE_MATRIX_THREADED_CONSTRUCTION.h> #ifdef USE_OPENMP #include <omp.h> #endif namespace PhysBAM{ //##################################################################### // Constructor //##################################################################### // User should fill in M.n; this class does not touch it. template<class T> SPARSE_MATRIX_THREADED_CONSTRUCTION<T>:: SPARSE_MATRIX_THREADED_CONSTRUCTION(SPARSE_MATRIX_FLAT_MXN<T>& M,ARRAY<int>& tmp0,ARRAY<int>& tmp1) :M(M),shared_num_rows(tmp0),shared_num_entries(tmp1),tid(0),threads(1) { #ifdef USE_OPENMP threads=omp_get_num_threads(); tid=omp_get_thread_num(); #endif #pragma omp single { shared_num_rows.Resize(threads+1); shared_num_entries.Resize(threads+1); } #pragma omp barrier } //##################################################################### // Function Start_Second_Pass //##################################################################### template<class T> void SPARSE_MATRIX_THREADED_CONSTRUCTION<T>:: Finish() { shared_num_rows(tid)=entries_per_row.m; shared_num_entries(tid)=entries_per_row.Sum(); #pragma omp barrier #pragma omp single { int last_row=0,last_entries=0; for(int i=0;i<threads;i++){ int s=shared_num_rows(i); shared_num_rows(i)=last_row; last_row+=s; int e=shared_num_entries(i); shared_num_entries(i)=last_entries; last_entries+=e;} shared_num_rows.Last()=last_row; shared_num_entries.Last()=last_entries; M.m=last_row; M.offsets.Resize(last_row+1,no_init); M.A.Resize(last_entries,no_init); } #pragma omp barrier int first_row=shared_num_rows(tid),last=shared_num_entries(tid); for(int i=0;i<A.m;i++) M.A(i+last)=A(i); for(int i=0;i<entries_per_row.m;i++){ M.offsets(i+first_row)=last; M.A.Array_View(last,entries_per_row(i)).Sort(); last+=entries_per_row(i);} if(tid==threads-1) M.offsets.Last()=last; #pragma omp barrier } template class SPARSE_MATRIX_THREADED_CONSTRUCTION<float>; template class SPARSE_MATRIX_THREADED_CONSTRUCTION<double>; }
[ "snubdodecahedron@gmail.com" ]
snubdodecahedron@gmail.com
ed270d0db79ed339ebe16a2b34db435d42b246f4
0026670c52b81d336d32f279624ccf51c7c75c23
/Bob/AIEngine/AIEnemyGMonsterFire.h
2f5bb96aa3a23e1c1f95dba81adf3ad49505d577
[ "MIT" ]
permissive
shoematt/BladeofBetrayal
c4863a220ad3e16d0610e1d4923756101a9cb9dd
8657c4bb41c8127e200fe529c526153ef5e1338f
refs/heads/master
2020-12-28T23:24:00.684411
2015-03-13T07:22:16
2015-03-13T07:22:16
null
0
0
null
null
null
null
UTF-8
C++
false
false
668
h
// EnemyGMonsterFire.h: interface for the EnemyGMonsterFire class. // ////////////////////////////////////////////////////////////////////// #if !defined(AFX_ENEMYGMONSTERFIRE_H__BFF05288_8859_4374_9A56_563294C71E28__INCLUDED_) #define AFX_ENEMYGMONSTERFIRE_H__BFF05288_8859_4374_9A56_563294C71E28__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 #include "BaseEnemy.h" class AIEnemyGMonsterFire : public BaseEnemy { public: float fire_time; float fire; void Wait(); void Attack(); AIEnemyGMonsterFire(); virtual ~AIEnemyGMonsterFire(); }; #endif // !defined(AFX_ENEMYGMONSTERFIRE_H__BFF05288_8859_4374_9A56_563294C71E28__INCLUDED_)
[ "duhone@conjuredrealms.com" ]
duhone@conjuredrealms.com
49270ce8376d340563d97e6e595166f66489b026
66fad47ebc33fb401e75948620004671643c26f3
/src/qt/rpcconsole.cpp
6302d1ad733524b8e3057ff4073779d307f3262a
[ "MIT" ]
permissive
TheQuantumCoin/QuantumCoin
903c4ef204ac61aad4cddbadf7ef4500d55c4f54
740a549bc0e9eee1d64ccde221af2d5250455986
refs/heads/master
2021-01-22T06:44:17.882676
2014-03-08T17:42:04
2014-03-08T17:42:04
17,347,677
0
1
null
null
null
null
UTF-8
C++
false
false
14,200
cpp
#include "rpcconsole.h" #include "ui_rpcconsole.h" #include "clientmodel.h" #include "bitcoinrpc.h" #include "guiutil.h" #include <QTime> #include <QThread> #include <QKeyEvent> #if QT_VERSION < 0x050000 #include <QUrl> #endif #include <QScrollBar> #include <openssl/crypto.h> // TODO: add a scrollback limit, as there is currently none // TODO: make it possible to filter out categories (esp debug messages when implemented) // TODO: receive errors and debug messages through ClientModel const int CONSOLE_HISTORY = 50; const QSize ICON_SIZE(24, 24); const struct { const char *url; const char *source; } ICON_MAPPING[] = { {"cmd-request", ":/icons/tx_input"}, {"cmd-reply", ":/icons/tx_output"}, {"cmd-error", ":/icons/tx_output"}, {"misc", ":/icons/tx_inout"}, {NULL, NULL} }; /* Object for executing console RPC commands in a separate thread. */ class RPCExecutor : public QObject { Q_OBJECT public slots: void request(const QString &command); signals: void reply(int category, const QString &command); }; #include "rpcconsole.moc" /** * Split shell command line into a list of arguments. Aims to emulate \c bash and friends. * * - Arguments are delimited with whitespace * - Extra whitespace at the beginning and end and between arguments will be ignored * - Text can be "double" or 'single' quoted * - The backslash \c \ is used as escape character * - Outside quotes, any character can be escaped * - Within double quotes, only escape \c " and backslashes before a \c " or another backslash * - Within single quotes, no escaping is possible and no special interpretation takes place * * @param[out] args Parsed arguments will be appended to this list * @param[in] strCommand Command line to split */ bool parseCommandLine(std::vector<std::string> &args, const std::string &strCommand) { enum CmdParseState { STATE_EATING_SPACES, STATE_ARGUMENT, STATE_SINGLEQUOTED, STATE_DOUBLEQUOTED, STATE_ESCAPE_OUTER, STATE_ESCAPE_DOUBLEQUOTED } state = STATE_EATING_SPACES; std::string curarg; foreach(char ch, strCommand) { switch(state) { case STATE_ARGUMENT: // In or after argument case STATE_EATING_SPACES: // Handle runs of whitespace switch(ch) { case '"': state = STATE_DOUBLEQUOTED; break; case '\'': state = STATE_SINGLEQUOTED; break; case '\\': state = STATE_ESCAPE_OUTER; break; case ' ': case '\n': case '\t': if(state == STATE_ARGUMENT) // Space ends argument { args.push_back(curarg); curarg.clear(); } state = STATE_EATING_SPACES; break; default: curarg += ch; state = STATE_ARGUMENT; } break; case STATE_SINGLEQUOTED: // Single-quoted string switch(ch) { case '\'': state = STATE_ARGUMENT; break; default: curarg += ch; } break; case STATE_DOUBLEQUOTED: // Double-quoted string switch(ch) { case '"': state = STATE_ARGUMENT; break; case '\\': state = STATE_ESCAPE_DOUBLEQUOTED; break; default: curarg += ch; } break; case STATE_ESCAPE_OUTER: // '\' outside quotes curarg += ch; state = STATE_ARGUMENT; break; case STATE_ESCAPE_DOUBLEQUOTED: // '\' in double-quoted text if(ch != '"' && ch != '\\') curarg += '\\'; // keep '\' for everything but the quote and '\' itself curarg += ch; state = STATE_DOUBLEQUOTED; break; } } switch(state) // final state { case STATE_EATING_SPACES: return true; case STATE_ARGUMENT: args.push_back(curarg); return true; default: // ERROR to end in one of the other states return false; } } void RPCExecutor::request(const QString &command) { std::vector<std::string> args; if(!parseCommandLine(args, command.toStdString())) { emit reply(RPCConsole::CMD_ERROR, QString("Parse error: unbalanced ' or \"")); return; } if(args.empty()) return; // Nothing to do try { std::string strPrint; // Convert argument list to JSON objects in method-dependent way, // and pass it along with the method name to the dispatcher. json_spirit::Value result = tableRPC.execute( args[0], RPCConvertValues(args[0], std::vector<std::string>(args.begin() + 1, args.end()))); // Format result reply if (result.type() == json_spirit::null_type) strPrint = ""; else if (result.type() == json_spirit::str_type) strPrint = result.get_str(); else strPrint = write_string(result, true); emit reply(RPCConsole::CMD_REPLY, QString::fromStdString(strPrint)); } catch (json_spirit::Object& objError) { try // Nice formatting for standard-format error { int code = find_value(objError, "code").get_int(); std::string message = find_value(objError, "message").get_str(); emit reply(RPCConsole::CMD_ERROR, QString::fromStdString(message) + " (code " + QString::number(code) + ")"); } catch(std::runtime_error &) // raised when converting to invalid type, i.e. missing code or message { // Show raw JSON object emit reply(RPCConsole::CMD_ERROR, QString::fromStdString(write_string(json_spirit::Value(objError), false))); } } catch (std::exception& e) { emit reply(RPCConsole::CMD_ERROR, QString("Error: ") + QString::fromStdString(e.what())); } } RPCConsole::RPCConsole(QWidget *parent) : QDialog(parent), ui(new Ui::RPCConsole), clientModel(0), historyPtr(0) { ui->setupUi(this); #ifndef Q_OS_MAC ui->openDebugLogfileButton->setIcon(QIcon(":/icons/export")); ui->showCLOptionsButton->setIcon(QIcon(":/icons/options")); #endif // Install event filter for up and down arrow ui->lineEdit->installEventFilter(this); ui->messagesWidget->installEventFilter(this); connect(ui->clearButton, SIGNAL(clicked()), this, SLOT(clear())); // set OpenSSL version label ui->openSSLVersion->setText(SSLeay_version(SSLEAY_VERSION)); startExecutor(); clear(); } RPCConsole::~RPCConsole() { emit stopExecutor(); delete ui; } bool RPCConsole::eventFilter(QObject* obj, QEvent *event) { if(event->type() == QEvent::KeyPress) // Special key handling { QKeyEvent *keyevt = static_cast<QKeyEvent*>(event); int key = keyevt->key(); Qt::KeyboardModifiers mod = keyevt->modifiers(); switch(key) { case Qt::Key_Up: if(obj == ui->lineEdit) { browseHistory(-1); return true; } break; case Qt::Key_Down: if(obj == ui->lineEdit) { browseHistory(1); return true; } break; case Qt::Key_PageUp: /* pass paging keys to messages widget */ case Qt::Key_PageDown: if(obj == ui->lineEdit) { QApplication::postEvent(ui->messagesWidget, new QKeyEvent(*keyevt)); return true; } break; default: // Typing in messages widget brings focus to line edit, and redirects key there // Exclude most combinations and keys that emit no text, except paste shortcuts if(obj == ui->messagesWidget && ( (!mod && !keyevt->text().isEmpty() && key != Qt::Key_Tab) || ((mod & Qt::ControlModifier) && key == Qt::Key_V) || ((mod & Qt::ShiftModifier) && key == Qt::Key_Insert))) { ui->lineEdit->setFocus(); QApplication::postEvent(ui->lineEdit, new QKeyEvent(*keyevt)); return true; } } } return QDialog::eventFilter(obj, event); } void RPCConsole::setClientModel(ClientModel *model) { this->clientModel = model; if(model) { // Subscribe to information, replies, messages, errors connect(model, SIGNAL(numConnectionsChanged(int)), this, SLOT(setNumConnections(int))); connect(model, SIGNAL(numBlocksChanged(int,int)), this, SLOT(setNumBlocks(int,int))); // Provide initial values ui->clientVersion->setText(model->formatFullVersion()); ui->clientName->setText(model->clientName()); ui->buildDate->setText(model->formatBuildDate()); ui->startupTime->setText(model->formatClientStartupTime()); setNumConnections(model->getNumConnections()); ui->isTestNet->setChecked(model->isTestNet()); } } static QString categoryClass(int category) { switch(category) { case RPCConsole::CMD_REQUEST: return "cmd-request"; break; case RPCConsole::CMD_REPLY: return "cmd-reply"; break; case RPCConsole::CMD_ERROR: return "cmd-error"; break; default: return "misc"; } } void RPCConsole::clear() { ui->messagesWidget->clear(); history.clear(); historyPtr = 0; ui->lineEdit->clear(); ui->lineEdit->setFocus(); // Add smoothly scaled icon images. // (when using width/height on an img, Qt uses nearest instead of linear interpolation) for(int i=0; ICON_MAPPING[i].url; ++i) { ui->messagesWidget->document()->addResource( QTextDocument::ImageResource, QUrl(ICON_MAPPING[i].url), QImage(ICON_MAPPING[i].source).scaled(ICON_SIZE, Qt::IgnoreAspectRatio, Qt::SmoothTransformation)); } // Set default style sheet ui->messagesWidget->document()->setDefaultStyleSheet( "table { }" "td.time { color: #808080; padding-top: 3px; } " "td.message { font-family: Monospace; font-size: 12px; } " "td.cmd-request { color: #006060; } " "td.cmd-error { color: red; } " "b { color: #006060; } " ); message(CMD_REPLY, (tr("Welcome to the Quantumcoin RPC console.") + "<br>" + tr("Use up and down arrows to navigate history, and <b>Ctrl-L</b> to clear screen.") + "<br>" + tr("Type <b>help</b> for an overview of available commands.")), true); } void RPCConsole::message(int category, const QString &message, bool html) { QTime time = QTime::currentTime(); QString timeString = time.toString(); QString out; out += "<table><tr><td class=\"time\" width=\"65\">" + timeString + "</td>"; out += "<td class=\"icon\" width=\"32\"><img src=\"" + categoryClass(category) + "\"></td>"; out += "<td class=\"message " + categoryClass(category) + "\" valign=\"middle\">"; if(html) out += message; else out += GUIUtil::HtmlEscape(message, true); out += "</td></tr></table>"; ui->messagesWidget->append(out); } void RPCConsole::setNumConnections(int count) { ui->numberOfConnections->setText(QString::number(count)); } void RPCConsole::setNumBlocks(int count, int countOfPeers) { ui->numberOfBlocks->setText(QString::number(count)); // If there is no current countOfPeers available display N/A instead of 0, which can't ever be true ui->totalBlocks->setText(countOfPeers == 0 ? tr("N/A") : QString::number(countOfPeers)); if(clientModel) ui->lastBlockTime->setText(clientModel->getLastBlockDate().toString()); } void RPCConsole::on_lineEdit_returnPressed() { QString cmd = ui->lineEdit->text(); ui->lineEdit->clear(); if(!cmd.isEmpty()) { message(CMD_REQUEST, cmd); emit cmdRequest(cmd); // Truncate history from current position history.erase(history.begin() + historyPtr, history.end()); // Append command to history history.append(cmd); // Enforce maximum history size while(history.size() > CONSOLE_HISTORY) history.removeFirst(); // Set pointer to end of history historyPtr = history.size(); // Scroll console view to end scrollToEnd(); } } void RPCConsole::browseHistory(int offset) { historyPtr += offset; if(historyPtr < 0) historyPtr = 0; if(historyPtr > history.size()) historyPtr = history.size(); QString cmd; if(historyPtr < history.size()) cmd = history.at(historyPtr); ui->lineEdit->setText(cmd); } void RPCConsole::startExecutor() { QThread *thread = new QThread; RPCExecutor *executor = new RPCExecutor(); executor->moveToThread(thread); // Replies from executor object must go to this object connect(executor, SIGNAL(reply(int,QString)), this, SLOT(message(int,QString))); // Requests from this object must go to executor connect(this, SIGNAL(cmdRequest(QString)), executor, SLOT(request(QString))); // On stopExecutor signal // - queue executor for deletion (in execution thread) // - quit the Qt event loop in the execution thread connect(this, SIGNAL(stopExecutor()), executor, SLOT(deleteLater())); connect(this, SIGNAL(stopExecutor()), thread, SLOT(quit())); // Queue the thread for deletion (in this thread) when it is finished connect(thread, SIGNAL(finished()), thread, SLOT(deleteLater())); // Default implementation of QThread::run() simply spins up an event loop in the thread, // which is what we want. thread->start(); } void RPCConsole::on_tabWidget_currentChanged(int index) { if(ui->tabWidget->widget(index) == ui->tab_console) { ui->lineEdit->setFocus(); } } void RPCConsole::on_openDebugLogfileButton_clicked() { GUIUtil::openDebugLogfile(); } void RPCConsole::scrollToEnd() { QScrollBar *scrollbar = ui->messagesWidget->verticalScrollBar(); scrollbar->setValue(scrollbar->maximum()); } void RPCConsole::on_showCLOptionsButton_clicked() { GUIUtil::HelpMessageBox help; help.exec(); }
[ "username@computername.(none)" ]
username@computername.(none)
192e5f93f512ee53385bdc0257df62c6150eb4bb
0ca50389f4b300fa318452128ab5437ecc97da65
/src/color/YPbPr/akin/YDbDr.hpp
23faa84d6adb1c695bd5ec23c31afaf732e22209
[ "Apache-2.0" ]
permissive
dmilos/color
5981a07d85632d5c959747dac646ac9976f1c238
84dc0512cb5fcf6536d79f0bee2530e678c01b03
refs/heads/master
2022-09-03T05:13:16.959970
2022-08-20T09:22:24
2022-08-22T06:03:32
47,105,546
160
25
Apache-2.0
2021-09-29T07:11:04
2015-11-30T08:37:43
C++
UTF-8
C++
false
false
1,748
hpp
#ifndef color_YPbPr_akin_YDbDr #define color_YPbPr_akin_YDbDr #include "../../generic/akin/YPbPr.hpp" #include "../category.hpp" #include "../../YDbDr/category.hpp" namespace color { namespace akin { template< ::color::constant::YPbPr::reference_enum reference_number >struct YPbPr< ::color::category::YDbDr_uint8 , reference_number >{ typedef ::color::category::YPbPr_uint8 <reference_number> akin_type; }; template< ::color::constant::YPbPr::reference_enum reference_number >struct YPbPr< ::color::category::YDbDr_uint16 , reference_number >{ typedef ::color::category::YPbPr_uint16 <reference_number> akin_type; }; template< ::color::constant::YPbPr::reference_enum reference_number >struct YPbPr< ::color::category::YDbDr_uint32 , reference_number >{ typedef ::color::category::YPbPr_uint32 <reference_number> akin_type; }; template< ::color::constant::YPbPr::reference_enum reference_number >struct YPbPr< ::color::category::YDbDr_uint64 , reference_number >{ typedef ::color::category::YPbPr_uint64 <reference_number> akin_type; }; template< ::color::constant::YPbPr::reference_enum reference_number >struct YPbPr< ::color::category::YDbDr_float , reference_number >{ typedef ::color::category::YPbPr_float <reference_number> akin_type; }; template< ::color::constant::YPbPr::reference_enum reference_number >struct YPbPr< ::color::category::YDbDr_double , reference_number >{ typedef ::color::category::YPbPr_double <reference_number> akin_type; }; template< ::color::constant::YPbPr::reference_enum reference_number >struct YPbPr< ::color::category::YDbDr_ldouble, reference_number >{ typedef ::color::category::YPbPr_ldouble<reference_number> akin_type; }; } } #endif
[ "dmilos@example.com" ]
dmilos@example.com
eb08f09fd281596fee24bb3a0d06dfc08ef56dfc
3d150aadc458dee33ebd532b33bc0e5e260d2ce5
/a4/q1printer.cc
9db9503cc1bf70449ea6c6311637799889c073be
[]
no_license
f2mahmud/concurrency-problems
5044169441287b98a8c7708aa0ad0e87d4512cf3
c54efdfca332cf82b437e3018be4b046b36c787c
refs/heads/master
2021-10-22T23:31:24.108762
2019-03-13T16:50:07
2019-03-13T16:50:07
168,610,012
0
0
null
null
null
null
UTF-8
C++
false
false
2,632
cc
#include <iostream> #include "q1printer.h" using namespace std; Printer::VoterState::VoterState(){} void Printer::VoterState::update( Voter::States s, unsigned int gv, unsigned int pv, unsigned int sv, unsigned int bc) { state = s; giftVote = gv; pictureVote = pv; statueVote = sv; blockCount =bc; dirty = true; } void Printer::VoterState::update( Voter::States s, TallyVotes::Tour t, unsigned int gv, unsigned int pv, unsigned int sv, unsigned int bc) { chosenTour = t; update(s,gv,pv,sv,bc); } Printer::Printer( unsigned int voters ) : voters(voters) { for (unsigned int i = 0; i < voters; i++) { // printing name of voters cout << "V" << i << (i != voters-1 ? '\t' : '\n'); } for (unsigned int i = 0; i < voters; i++) { //divider for each voter cout << "*******" << (i != voters-1 ? '\t' : '\n'); voterStates.push_back(new VoterState()); } resume(); // to main of coroutine } void Printer::flush() { // print moves for (unsigned int i = 0; i < voters; i+=1) { if (voterStates[i]->dirty) { cout << *voterStates[i]; voterStates[i]->dirty = false; } cout << '\t'; } cout << '\n'; } void Printer::main() { suspend(); //initial suspend for ( ;; ) { if (voterStates[voterId]->dirty) { flush(); } suspend(); } } //Used for S/b/C/X/T void Printer::print( unsigned int id, Voter::States state ) { voterId = id; if(voterStates[id]->dirty){ resume(); //head back to main } voterStates[id]->update(state, 0, 0, 0, 0); //update values } //Used for Ftg void Printer::print( unsigned int id, Voter::States state, TallyVotes::Tour tour ) { voterId = id; if(voterStates[id]->dirty){ resume(); //head back to main } voterStates[id]->update(state,tour, 0, 0, 0, 0); } //Used for Vpsg void Printer::print( unsigned int id, Voter::States state, TallyVotes::Ballot ballot ) { voterId = id; if(voterStates[id]->dirty){ resume(); //head back to main } voterStates[id]->update(state, ballot.picture, ballot.statue, ballot.giftshop, 0); //update } //Used for Un/Bn void Printer::print( unsigned int id, Voter::States state, unsigned int numBlocked ) { voterId = id; if(voterStates[id]->dirty){ resume(); //head back to main } voterStates[id]->update(state, 0, 0, 0, numBlocked); //update } Printer::~Printer() { flush(); //Printing final lines cout << "*****************" << endl; cout << "All tours started" << endl; for(unsigned int i = 0; i < voters; i+=1){ delete voterStates[i]; voterStates[0] = nullptr; } }
[ "f2mahmud@uwaterloo.ca" ]
f2mahmud@uwaterloo.ca
df33ed974fa7e7c7b0c1d779807edb29ce8533c0
76f9898ff7a555f4a729d725056a317af818375d
/tools/ZAPD/ZAPD/ZRoom/Commands/SetObjectList.cpp
f8d00a101e095a9b4bb1583412e535d922ca9f1b
[ "MIT" ]
permissive
z64proto/sw97
0b65837ab2f2a4073faca5670761d7fe0e74d29d
f571505ade2cefd4a5b5d19da06d33e7c6b02c60
refs/heads/master
2023-08-01T02:47:42.895871
2022-05-15T20:29:08
2022-05-15T20:29:08
430,216,978
208
29
null
2021-11-22T12:23:50
2021-11-20T21:52:59
C
UTF-8
C++
false
false
2,109
cpp
#include "SetObjectList.h" #include "../../BitConverter.h" #include "../../StringHelper.h" #include "../../ZFile.h" #include "../ObjectList.h" #include "../ZRoom.h" using namespace std; SetObjectList::SetObjectList(ZRoom* nZRoom, std::vector<uint8_t> rawData, int rawDataIndex) : ZRoomCommand(nZRoom, rawData, rawDataIndex) { objects = vector<uint16_t>(); uint8_t objectCnt = rawData[rawDataIndex + 1]; segmentOffset = GETSEGOFFSET(BitConverter::ToInt32BE(rawData, rawDataIndex + 4)); uint32_t currentPtr = segmentOffset; for (uint8_t i = 0; i < objectCnt; i++) { uint16_t objectIndex = BitConverter::ToInt16BE(rawData, currentPtr); objects.push_back(objectIndex); currentPtr += 2; } if (segmentOffset != 0) zRoom->parent->AddDeclarationPlaceholder(segmentOffset); } string SetObjectList::GenerateExterns() { return StringHelper::Sprintf("s16 %sObjectList0x%06X[];\n", zRoom->GetName().c_str(), segmentOffset); } string SetObjectList::GenerateSourceCodePass1(string roomName, int baseAddress) { string sourceOutput = ""; sourceOutput += StringHelper::Sprintf("%s 0x%02X, (u32)%sObjectList0x%06X", ZRoomCommand::GenerateSourceCodePass1(roomName, baseAddress).c_str(), objects.size(), zRoom->GetName().c_str(), segmentOffset); string declaration = ""; for (size_t i = 0; i < objects.size(); i++) { uint16_t objectIndex = objects[i]; declaration += StringHelper::Sprintf("\t%s,", ObjectList[objectIndex].c_str()); if (i < objects.size() - 1) declaration += "\n"; } zRoom->parent->AddDeclarationArray( segmentOffset, DeclarationAlignment::None, objects.size() * 2, "s16", StringHelper::Sprintf("%sObjectList0x%06X", zRoom->GetName().c_str(), segmentOffset), objects.size(), declaration); return sourceOutput; } int32_t SetObjectList::GetRawDataSize() { return ZRoomCommand::GetRawDataSize() + (objects.size() * 2); } string SetObjectList::GetCommandCName() { return "SCmdObjectList"; } RoomCommand SetObjectList::GetRoomCommand() { return RoomCommand::SetObjectList; }
[ "zelda@sw97" ]
zelda@sw97
2f31e19e9d1bc0ef2852ef09acf4cdbcea1b5ae7
8cd0711daac64d4396d6f231728283b5c2c50233
/code/project1.cpp
c7d3bad57a5c9e995c9a07bce4f3c52e709e74aa
[]
no_license
rcmccartney/comparing_optimal_sorts
af8ce6912ff7a051aa426903fd609b89eb89d5bb
63106a08ccc082224449f76628fe25305d12232d
refs/heads/master
2021-01-01T05:59:25.475211
2014-12-16T16:46:23
2014-12-16T16:46:23
null
0
0
null
null
null
null
UTF-8
C++
false
false
7,801
cpp
//============================================================================ // Name : project1.cpp // Author : rm7536 // Description : Uses sorting algorithms and generic templates to read in data // sort it and compare running times // Version : $Id$ // Revision : $Log$ //============================================================================ #include "mergesort.h" #include "quicksort.h" #include "heapsort.h" #include "my_choice_qsort.h" #include <iostream> #include <fstream> #include <stdlib.h> /* srand, rand */ #include <sstream> #include <math.h> /* log2 */ #include <time.h> /* clock_t, clock, CLOCKS_PER_SEC */ using namespace std; /* Name: printIt() * Description: Prints a generic array, 50 items per line. * Arguments: Filename of the file to be used * Modifies: None. * Returns: None. * Pre: None. * Post: None. * Exceptions: None. */ template<typename T> void printIt(T *array, long count) { for(int i = 0; i < count; i++) { cout << array[i]; if (i != count-1) { cout << ", "; } else { cout << "."; } } cout << endl; } /* Name: tokenizer() * Description: Fills the array passed to it by pointer. * Arguments: tokens - tokens: array of generic type. * filename: filename to tokenize. * count: - how many entries the array contains * Modifies: tokens array through pass by reference * Returns: None. * Pre: None. * Post: tokens is filled with entries from the file. * Exceptions: None. */ template<typename T> void tokenizer(T* tokens, char* filename, long &count) { ifstream file(filename); if ( file.is_open() ) { cout << "Reading in data file..." << endl; int i = 0; string line; while( i < count ) { getline( file, line ); stringstream ss(line); while(ss >> tokens[i]) { if (++i == count) { break; } } } if (i < count) { cout << "Warning: file contained less than " << count << " data items." << " Proceeding analysis on " << i << " data items." << endl; } else { cout << "File read in successfully" << endl; } file.close(); } else { cout << "Error: File not open to tokenize." << endl; exit(1); } } /* Name: makeCopy() * Description: Copies one array into another * Arguments: tokens - array: array from file * copy: array that gets the copy * count: - how many entries the array contains * Modifies: None. * Returns: None. * Pre: None. * Post: Copy contains the same contents as Array * Exceptions: None. */ template<typename T> void makeCopy(T* array, T* copy, long count) { for(int i =0; i < count; i++) { copy[i] = array[i]; } } /* Name: run10times() * Description: Runs each sorting array 10 times on input array & calculates the average time * Arguments: tokens - array: array from file * copy: array to sort, copied from array before each run * count: - how many entries the array contains * Modifies: sorts the copy array 10 times per algorithm * Returns: None. * Pre: None. * Post: Average running time calculated * Exceptions: None. */ template<typename T> void run10times(T* array, T* copy, long count, string distr, string type) { string file = "output_" + type + ".txt"; ofstream output(file.c_str(), ios::app); double total = 0; //format of each line in the dataset - only print this on first run if ( distr == "Ordered" && count == 1000) { output << "Dist, Size, MSTime, MSComp, HSTime, HSComp, QSTime, QSComp, QSRec, ISTime, ISComp, ISRec" << endl; } long *comparisons = new long; *comparisons = 0; for(int i = 0; i < 10; i++) { //read the integers into array, array modified through pass by pointer //Have to copy the array to be sorted so that you can run the algorithm //10 times on the original unsorted array. Otherwise it is sorted after the //first time. makeCopy(array, copy, count); clock_t start = clock(); //keep adding up the number of comparisons for all 10 times mergeSort(copy, count, comparisons); clock_t end = clock(); total += 1000.0 * (end-start) / CLOCKS_PER_SEC; } total = total / 10; (*comparisons) /= 10; output << distr << ", " << count << ", " << total << ", " << (*comparisons); //print the array if it is small enough, used for testing the sorts worked correctly if (count < 101) { printIt(copy, count); } total = 0; *comparisons = 0; for(int i = 0; i < 10; i++) { makeCopy(array, copy, count); clock_t start = clock(); heapSort(copy, count, comparisons); clock_t end = clock(); total += 1000.0 * (end-start) / CLOCKS_PER_SEC; } total /= 10; (*comparisons) /= 10; output << ", " << total << ", " << (*comparisons); if (count < 101) { printIt(copy, count); } total = 0; *comparisons = 0; long *partitionCount = new long; *partitionCount = 0; for(int i = 0; i < 10; i++) { makeCopy(array, copy, count); clock_t start = clock(); //partitionCount is added up 10 times in a row quickSort(copy, 0L, count-1, comparisons, partitionCount); clock_t end = clock(); total += 1000.0 * (end-start) / CLOCKS_PER_SEC; } total /= 10; (*comparisons) /= 10; (*partitionCount) /= 10; output << ", " << total << ", " << (*comparisons) << ", " << (*partitionCount); if (count < 101) { printIt(copy, count); } total = 0; *comparisons = 0; *partitionCount = 0; for(int i = 0; i < 10; i++) { makeCopy(array, copy, count); clock_t start = clock(); //use a depth limit of 2*log(n) for the recursion introSort(copy, 0L, count-1, 2*log2(count), comparisons, partitionCount ); clock_t end = clock(); total += 1000.0 * (end-start) / CLOCKS_PER_SEC; } total /= 10; (*comparisons) /= 10; (*partitionCount) /= 10; output << ", " << total << ", " << (*comparisons) << ", " << (*partitionCount) << endl; if (count < 101) { printIt(copy, count); } } /* Name: main() * Description: Reads a file and sorts it using each of the 4 sorting algorithms. File can contain INT, STRING, LONG, DOUBLE or CHAR. * Arguments: Filename of the file to be used. * Modifies: None. * Returns: None. * Pre: None. * Post: Prints time taken to sort the file and exits. If file is small enough it will print the sorted array * Exceptions: None. */ int main(int argc, char * argv[]) { if (argc < 5) { cout << "Error: Usage is 'project1 Filename Type Size Distribution'" << endl << "Filename = file that holds the generated data" << endl << "TYPE = ['int', 'long', or 'double']" << endl << "Size = the number of data elements in the file" << endl << "and Distribution is a string description" << endl << "Consult the README for more information." << endl; return 1; } try { string type(argv[2]); long count( atol(argv[3]) ); /* initialize random seed for quicksort rand() */ srand (time(NULL)); if (type == "int") { int* array = new int[count]; int* copy = new int[count]; //read the values into array, array modified through pass by pointer tokenizer(array, argv[1], count ); run10times(array, copy, count, argv[4], "int" ); } else if (type == "long") { long long* array = new long long[count]; long long* copy = new long long[count]; tokenizer(array, argv[1], count ); run10times(array, copy, count, argv[4], "long" ); } else if (type == "double") { double* array = new double[ count ]; double* copy = new double[ count ]; tokenizer(array, argv[1], count ); run10times(array, copy, count, argv[4], "double" ); } else { cout << "Error: TYPE must be ['int', 'long', or 'double'] and is case-sensitive." << endl; return 1; } } catch (exception& e) { cout << "Error: Arguments not formatted correctly. Consult README for correct usage." << endl; return 1; } }
[ "rm7536@rit.edu" ]
rm7536@rit.edu