blob_id
stringlengths
40
40
language
stringclasses
1 value
repo_name
stringlengths
5
117
path
stringlengths
3
268
src_encoding
stringclasses
34 values
length_bytes
int64
6
4.23M
score
float64
2.52
5.19
int_score
int64
3
5
detected_licenses
listlengths
0
85
license_type
stringclasses
2 values
text
stringlengths
13
4.23M
download_success
bool
1 class
d5fa9024a0b422033f62882afde8b2a212a399d9
C++
huangxueqin/algorithm_exercise
/leetcode/96.cc
UTF-8
1,104
3.046875
3
[]
no_license
#include "leetc.h" using namespace std; class Solution { public: int numTrees(int n) { vector<vector<int>> dp = init_dp_table(n); return compute_num_trees(0, n-1, dp); } private: int compute_num_trees(int i, int j, vector<vector<int>> &dp) { if(i > j) return 1; if(dp[i][j] == -1) { int result = 0; for(int k = i; k <= j; k++) { result += compute_num_trees(i, k-1, dp) * compute_num_trees(k+1, j, dp); } dp[i][j] = result; } return dp[i][j]; } vector<vector<int>> init_dp_table(int n) { vector<vector<int>> dp; for(int i = 0; i < n; i++) { dp.push_back(vector<int>(n, -1)); } return dp; } }; Solution sol; int main(int argc, char *argv[]) { if(argc < 2) { printf("more param"); return 0; } int n = std::atoi(argv[1]); printf("%d\n",sol.numTrees(n)); return 0; }
true
de5c13eb7efdc61803451c21de98dd34b8e6c685
C++
brock7/TianLong
/Common/Packets/GCAddLockObj.h
GB18030
1,577
2.84375
3
[]
no_license
// GCAddLockObj.h // // Ʒ // ////////////////////////////////////////////////////// #ifndef __GCADDLOCKOBJ_H__ #define __GCADDLOCKOBJ_H__ #include "Type.h" #include "Packet.h" #include "PacketFactory.h" #include "DB_Struct.h" namespace Packets { class GCAddLockObj : public Packet { public: enum { LOCK_ITEM =0, LOCK_PET, }; enum { RESULT_LOCK_OK =0, RESULT_LOCK_FALSE, RESULT_UNLOCK_OK, RESULT_UNLOCK_FALSE, RESULT_NO_JINGLI, }; GCAddLockObj() { } virtual ~GCAddLockObj(){} //ü̳нӿ virtual BOOL Read( SocketInputStream& iStream ) ; virtual BOOL Write( SocketOutputStream& oStream )const ; virtual UINT Execute( Player* pPlayer ) ; virtual PacketID_t GetPacketID()const { return PACKET_GC_ADDLOCKOBJ ; } virtual UINT GetPacketSize()const { return sizeof(BYTE)*2; } public: //ʹݽӿ BYTE GetLockObj(){return m_bLockObj;} VOID SetLockObj(BYTE bLockObj) {m_bLockObj=bLockObj;} BYTE GetResult(){return m_bResult;} VOID SetResult(BYTE bResult) {m_bResult=bResult;} private: // BYTE m_bLockObj; // ʲô͵Ķ BYTE m_bResult; // }; class GCAddLockObjFactory : public PacketFactory { public: Packet* CreatePacket() { return new GCAddLockObj() ; } PacketID_t GetPacketID()const { return PACKET_GC_ADDLOCKOBJ; } UINT GetPacketMaxSize()const { return sizeof(BYTE)*2; } }; class GCAddLockObjHandler { public: static UINT Execute( GCAddLockObj* pPacket, Player* pPlayer ) ; }; } using namespace Packets; #endif
true
f437b3257e582295441a5b6c5deb6652dabec7e6
C++
firewood/topcoder
/atcoder/abc_266/f.cpp
UTF-8
2,464
2.625
3
[]
no_license
#include <algorithm> #include <cctype> #include <cmath> #include <cstring> #include <iostream> #include <sstream> #include <numeric> #include <map> #include <set> #include <queue> #include <vector> using namespace std; struct Tree { int64_t size; vector<vector<pair<int, int>>> edges; vector<int> vis; vector<int> node_history; vector<int> edge_history; vector<int> dis; Tree(int64_t size_) : size(size_), edges(size), vis(size) { } void build_bidirectional_edges(std::vector<int>& from, std::vector<int>& to) { for (size_t i = 0; i < from.size(); ++i) { edges[from[i]].emplace_back(make_pair(int(to[i]), int(i))); edges[to[i]].emplace_back(make_pair(int(from[i]), int(i))); } dis.resize(from.size()); } void dfs(int n, int from, int from_ei) { node_history.emplace_back(from); edge_history.emplace_back(from_ei); if (!vis[n]) { vis[n] = 1; for (auto kv : edges[n]) { int to = kv.first, ei = kv.second; if (to != from && vis[to] != 2) { dfs(to, n, ei); } } } else { for (int i = int(edge_history.size()) - 1; i >= 0; --i) { dis[edge_history[i]] = 1; if (node_history[i] == n) break; } } node_history.pop_back(); edge_history.pop_back(); vis[n] = 2; } }; struct UnionFind { std::vector<int> _parent; std::vector<int> _size; UnionFind(int size) : _parent(size, -1), _size(size, 1) { } void unite(int a, int b) { int ra = root(a), rb = root(b); if (ra == rb) { return; } if (_size[ra] < _size[rb]) swap(ra, rb); _parent[rb] = ra, _size[ra] += _size[rb]; } int root(int a) { int p = _parent[a]; if (p < 0) { return a; } while (_parent[p] >= 0) { p = _parent[p]; } return _parent[a] = p; } int size(int a) { return _size[root(a)]; } }; void solve(int N, std::vector<int> u, std::vector<int> v, int Q, std::vector<int> x, std::vector<int> y) { Tree tree(N); tree.build_bidirectional_edges(u, v); tree.dfs(0, -1, -1); UnionFind uf(N); for (int i = 0; i < N; ++i) { if (!tree.dis[i]) { uf.unite(u[i], v[i]); } } for (int i = 0; i < Q; ++i) { bool ans = uf.root(x[i]) == uf.root(y[i]); cout << (ans ? "Yes" : "No") << endl; } } int main() { int N, Q; std::cin >> N; std::vector<int> u(N), v(N); for (int i = 0; i < N; i++) { std::cin >> u[i] >> v[i]; --u[i], --v[i]; } std::cin >> Q; std::vector<int> x(Q), y(Q); for (int i = 0; i < Q; i++) { std::cin >> x[i] >> y[i]; --x[i], --y[i]; } solve(N, u, v, Q, x, y); return 0; }
true
4ab5467866cfc2fbac4e187b6cfa892469a5ca67
C++
CSEKU160212/C_Programming_And_Data_Structure
/C Programming (Home Practice)/programming/programming/string/1 -1 0.cpp
UTF-8
638
3.28125
3
[]
no_license
#include<stdio.h> int string_compare(char a[50], char b[50]) { int i, j; for(i = 0; a[i] != '\0' && b[i] != '\0'; i++) { if(a[i] < b[i]) { return -1; } if(a[i] > b[i]) { return 1; } } int main() { int string_compare; char a[500],b[500]; if(string_compare(a) == string_compare(b)) { return 0; } if(string_compare(a) < string_compare(b)) { return -1; } if(string_compare(a) > string_compare(b)) { return 1; } } }
true
4bbf01fea0409521a4c20e5c3342332aab1dd732
C++
cmiyachi/CygWinAlgorithms
/DailyCodingProblem/productsNotSelf.cpp
UTF-8
1,239
3.625
4
[]
no_license
#include <bits/stdc++.h> using namespace std; class Solution { public: vector<int> productExceptSelf(vector<int>& nums) { int length = nums.size(); vector<int> answer(length); answer[0] = 1; for (int i = 1; i < length; i++) { // answer[i - 1] already contains the product of elements to the left of 'i - 1' // Simply multiplying it with nums[i - 1] would give the product of all // elements to the left of index 'i' answer[i] = nums[i - 1] * answer[i - 1]; } // R contains the product of all the elements to the right // Note: for the element at index 'length - 1', there are no elements to the right, // so the R would be 1 int R = 1; for (int i = length - 1; i >= 0; i--) { // For the index 'i', R would contain the // product of all elements to the right. We update R accordingly answer[i] = answer[i] * R; R *= nums[i]; } return answer; } }; int main(void) { vector<int> num1{1,2,3,4,5}; Solution sol; vector<int> result = sol.productExceptSelf(num1); for (auto& it :result) cout << it << " "; cout << endl; return 0; }
true
05ba8b7399d0c4ec315b7b586d7adfb1fe81d90e
C++
monsoon235/USTC-Parallel-Computing-Course
/src/lab4/lab4.cpp
UTF-8
5,109
2.625
3
[]
no_license
#include <iostream> #include <iomanip> #include <algorithm> #include <string> #include <random> #include <mpi.h> // 归并 void multi_merge(int arr[], int arr_len, int offsets[], int size, int output[]) { int *starts[size]; int *ends[size]; for (int i = 0; i < size; ++i) { starts[i] = arr + offsets[i]; } ends[size - 1] = arr + arr_len; for (int i = 0; i < size - 1; ++i) { ends[i] = starts[i + 1]; } for (int i = 0; i < arr_len; ++i) { int min = 0; while (starts[min] >= ends[min]) { min++; } for (int j = min + 1; j < size; ++j) { if (starts[j] < ends[j] && *starts[j] < *starts[min]) { min = j; } } output[i] = *starts[min]; starts[min]++; } } double PSRS(int arr[], int arr_len) { double start_time = MPI_Wtime(); int rank, size; MPI_Comm_rank(MPI_COMM_WORLD, &rank); MPI_Comm_size(MPI_COMM_WORLD, &size); // 数据分段 int offsets[size]; int lengths[size]; for (int i = 0; i < size; ++i) { offsets[i] = i * arr_len / size; lengths[i] = (i + 1) * arr_len / size - offsets[i]; } // 给每个线程分配数据 auto local = new int[lengths[rank]]; auto local_len = lengths[rank]; MPI_Scatterv(arr, lengths, offsets, MPI_INT, local, local_len, MPI_INT, 0, MPI_COMM_WORLD); // 区域排序 std::sort(local, local + local_len); // 采样 int sample[size]; std::sample(local, local + local_len, sample, size, std::mt19937{std::random_device{}()}); // 选取划分元素 int sample_all[size * size]; int fake_pivot[size + 1];// 添加哨兵方便进行划分 int *pivot = fake_pivot + 1; MPI_Gather(sample, size, MPI_INT, sample_all, size, MPI_INT, 0, MPI_COMM_WORLD); if (rank == 0) { std::sort(sample_all, sample_all + size * size); // 此处需要均匀划分 for (int i = 0; i < size - 1; ++i) { pivot[i] = sample_all[(i + 1) * size]; } } MPI_Bcast(pivot, size - 1, MPI_INT, 0, MPI_COMM_WORLD); // 按 pivot 对局部进行划分 pivot[-1] = local[0]; pivot[size - 1] = local[local_len - 1] + 1; int part_offset[size]; // 每一部分的开始位置 int part_len[size]; // 每一部分的长度 part_offset[0] = 0; int now_index = 0; for (int i = 0; i < size; ++i) { while (now_index < local_len && pivot[i - 1] <= local[now_index] && local[now_index] < pivot[i]) { now_index++; } part_len[i] = now_index - part_offset[i]; if (i + 1 < size) { part_offset[i + 1] = now_index; } } // 发送每个划分长度 for (int i = 0; i < size; ++i) { MPI_Gather(&part_len[i], 1, MPI_INT, lengths, 1, MPI_INT, i, MPI_COMM_WORLD); } offsets[0] = 0; for (int i = 1; i < size; ++i) { offsets[i] = offsets[i - 1] + lengths[i - 1]; } local_len = std::accumulate(lengths, lengths + size, 0); auto local_new = new int[local_len]; // 把每个线程的第 i 个划分发送到第 i 个线程 for (int i = 0; i < size; ++i) { MPI_Gatherv(local + part_offset[i], part_len[i], MPI_INT, local_new, lengths, offsets, MPI_INT, i, MPI_COMM_WORLD); } // 每个线程重新排序,可以用归并的方法 delete[] local; local = new int[local_len]; multi_merge(local_new, local_len, offsets, size, local); delete[] local_new; // 所有长度数据汇总到 root MPI_Gather(&local_len, 1, MPI_INT, lengths, 1, MPI_INT, 0, MPI_COMM_WORLD); if (rank == 0) { offsets[0] = 0; for (int i = 1; i < size; ++i) { offsets[i] = offsets[i - 1] + lengths[i - 1]; } } // 所有数据汇总到 root MPI_Gatherv(local, local_len, MPI_INT, arr, lengths, offsets, MPI_INT, 0, MPI_COMM_WORLD); delete[] local; double end_time = MPI_Wtime(); return end_time - start_time; } int main(int argc, char *argv[]) { auto arr_len = std::stoi(argv[1]); MPI_Init(&argc, &argv); int rank, size; MPI_Comm_rank(MPI_COMM_WORLD, &rank); MPI_Comm_size(MPI_COMM_WORLD, &size); int *arr = nullptr; if (rank == 0) { arr = new int[arr_len]; // 初始化 std::generate_n(arr, arr_len, []() { static int i = 0; return i++; }); // 打乱 std::shuffle(arr, arr + arr_len, std::mt19937(std::random_device()())); } if (rank == 0) { std::cout << std::setiosflags(std::ios::fixed); std::cout << "PSRS 排序\n"; std::cout << "线程数\t数组长度\t用时(ms)\t结果检查\n"; } auto time = PSRS(arr, arr_len); if (rank == 0) { std::cout << size << '\t' << arr_len << '\t' << std::setprecision(4) << time * 1e3 << '\t' << (std::is_sorted(arr, arr + arr_len) ? "正确" : "错误") << std::endl; } MPI_Finalize(); return 0; }
true
0ee180a8202dd09d9fbb8f45958ae94ff1fc0474
C++
pankajdevrath96/Cpp
/STL/dequeue.cpp
UTF-8
449
2.75
3
[]
no_license
#include "iostream" #include "deque" using namespace std; int main() { deque<int> q1; int i,x,n,l1=0,sl=0; cin>>n; for(i=0;i<n;i++) { cin>>x; q1.push_back(x); } for(i=0;i<n;i++) { x=q1.front(); q1.pop_front(); if(x>l1) { sl=l1; l1=x; } else if(x>sl) sl=x; } cout<<sl; }
true
021ced2c87d7ab77188136ac43461861c48078b8
C++
DevJhin/Weekly_Algorithm_Quiz
/2018_11/Week_5/11050_Binomial_Coefficient_1/main.cpp
UTF-8
437
3.546875
4
[]
no_license
#include <iostream> int Factorial(int val); int BinomialCoefficient(int N, int K); int main() { int N, K; scanf("%d %d", &N, &K); printf("%d", BinomialCoefficient(N, K)); } int Factorial(int val) { int rlt = 1; for (int i = 1; i <= val; i++) { rlt *= i; } return rlt; } //Calculate Binomial Coeffiecient => N!/((K!)(N-K)!) int BinomialCoefficient(int N, int K) { return Factorial(N) / (Factorial(K)*Factorial(N - K)); }
true
df7d4b34af65aadee433b63ea78cb7184b6ef38f
C++
oides/AutonomousRaspRobot
/Raspberry/RaspOpenCV/moviment.cpp
UTF-8
1,139
2.703125
3
[]
no_license
#include "moviment.h" void Moviment::startMoviment(bool &walk) { walk = true; while(1) { if(walk) executeFrente(walk); sleep(SLEEP_MOVIMENT); } } void Moviment::executeFrente(bool &walk) { printf("executeFrente\n"); walk = true; strncpy(client_message, FRENTE, MQ_MESSAGE_LENGTH); printf("executeFrente3\n"); messageQueue.sendMessage(client_message); printf("executeFrente4\n"); sleep(2); } void Moviment::executeDireita(bool &walk) { printf("executeDireita\n"); walk = true; strncpy(client_message, DIREITA, MQ_MESSAGE_LENGTH); messageQueue.sendMessage(client_message); } void Moviment::interromperExecucao(bool &walk) { printf("interromperExecucao\n"); walk = false; } void Moviment::executeRe(bool &walk) { printf("executeRe\n"); walk = false; strncpy(client_message, RE, MQ_MESSAGE_LENGTH); messageQueue.sendMessage(client_message); } void Moviment::executeEsquerda(bool &walk) { printf("executeEsquerda\n"); walk = true; strncpy(client_message, ESQUERDA, MQ_MESSAGE_LENGTH); messageQueue.sendMessage(client_message); }
true
4cc5c75ea574f48cefbb25f9567c7bcdeabf0236
C++
dpicken/utils
/src/network/SocketAddress.h
UTF-8
773
2.59375
3
[ "MIT" ]
permissive
#ifndef network_SocketAddress_h #define network_SocketAddress_h #include "IpAddress.h" #include <netinet/in.h> #include <cstddef> #include <cstdint> #include <iosfwd> namespace network { class SocketAddress { public: SocketAddress(const sockaddr_in6& m_address); static SocketAddress ip(const IpAddress& ipAddress, uint16_t port = 0); const sockaddr* addr() const; std::size_t addrSize() const; std::string str() const; private: const sockaddr_in6 m_address; }; std::ostream& operator<<(std::ostream& os, const SocketAddress& address); bool operator==(const SocketAddress& lhs, const SocketAddress& address); bool operator!=(const SocketAddress& lhs, const SocketAddress& address); } // namespace network #endif // ifndef network_SocketAddress_h
true
66164a635fd041303659e3fdba4cc70d3cacf774
C++
Kose-i/training_algorithm
/problem/CodeIq/book2/prob41.cpp
UTF-8
2,136
3.28125
3
[]
no_license
#include <iostream> #include <utility> #include <vector> #include <map> #include <algorithm> struct Box{ int x; int y; }; namespace prob41{ unsigned long long search(std::vector<int>& tile_column, std::map<std::vector<int>, unsigned long long>& memo, const std::vector<Box>& box_type, const int& column_size, const int& row_size) { if (memo.find(tile_column) != memo.end()) return memo[tile_column]; auto min_elem_it = std::min_element(tile_column.begin(), tile_column.end()); if (*min_elem_it == row_size) return 1; auto min_index_pos = std::distance(tile_column.begin(), min_elem_it); unsigned long long cnt {}; unsigned box_type_size = box_type.size(); for (auto i = 0;i < box_type_size;++i) { bool check = true; for (auto x = 0;x < box_type[i].x;++x) { if ( (min_index_pos+x >= column_size) || (tile_column[min_index_pos + x] + box_type[i].y > row_size) ) { check = false; break; } else if (tile_column[min_index_pos + x] != tile_column[min_index_pos]) { check = false; break; } } if (!check) break; for (auto x = 0;x < box_type[i].x;++x) { tile_column[min_index_pos + x] += box_type[i].y; } cnt += search(tile_column, memo, box_type, column_size, row_size); for (auto x = 0;x < box_type[i].x;++x) { tile_column[min_index_pos + x] -= box_type[i].y; } } memo.insert(std::make_pair(tile_column, cnt)); return cnt; } unsigned long long answer(const int& column_size, const int& row_size) { std::vector<Box> box_type(4); box_type[0].x = 1; box_type[0].y = 1; box_type[1].x = 2; box_type[1].y = 2; box_type[2].x = 4; box_type[2].y = 2; box_type[3].x = 4; box_type[3].y = 4; std::vector<int> tile_column(column_size, 0); std::map<std::vector<int>, unsigned long long> memo; return search(tile_column, memo, box_type, column_size, row_size); } } int main(int argc, char** argv) { const int column_size {10}; const int row_size {10}; std::cout << prob41::answer(column_size, row_size) << '\n'; }
true
58f94bf9b37b5830bac0c9a89bce017146ef469a
C++
panda3d/panda3d
/panda/src/bullet/bulletTriangleMesh.cxx
UTF-8
15,817
2.5625
3
[ "BSD-3-Clause", "BSD-2-Clause" ]
permissive
/** * PANDA 3D SOFTWARE * Copyright (c) Carnegie Mellon University. All rights reserved. * * All use of this software is subject to the terms of the revised BSD * license. You should have received a copy of this license along * with this source code in a file named "LICENSE." * * @file bulletTriangleMesh.cxx * @author enn0x * @date 2010-02-09 */ #include "bulletTriangleMesh.h" #include "bulletWorld.h" #include "pvector.h" #include "geomTriangles.h" #include "geomVertexData.h" #include "geomVertexReader.h" using std::endl; TypeHandle BulletTriangleMesh::_type_handle; /** * */ BulletTriangleMesh:: BulletTriangleMesh() : _welding_distance(0) { btIndexedMesh mesh; mesh.m_numTriangles = 0; mesh.m_numVertices = 0; mesh.m_indexType = PHY_INTEGER; mesh.m_triangleIndexBase = nullptr; mesh.m_triangleIndexStride = 3 * sizeof(int); mesh.m_vertexBase = nullptr; mesh.m_vertexStride = sizeof(btVector3); _mesh.addIndexedMesh(mesh); } /** * Returns the number of vertices in this triangle mesh. */ size_t BulletTriangleMesh:: get_num_vertices() const { LightMutexHolder holder(BulletWorld::get_global_lock()); return _vertices.size(); } /** * Returns the vertex at the given vertex index. */ LPoint3 BulletTriangleMesh:: get_vertex(size_t index) const { LightMutexHolder holder(BulletWorld::get_global_lock()); nassertr(index < (size_t)_vertices.size(), LPoint3::zero()); const btVector3 &vertex = _vertices[index]; return LPoint3(vertex[0], vertex[1], vertex[2]); } /** * Returns the vertex indices making up the given triangle index. */ LVecBase3i BulletTriangleMesh:: get_triangle(size_t index) const { LightMutexHolder holder(BulletWorld::get_global_lock()); index *= 3; nassertr(index + 2 < (size_t)_indices.size(), LVecBase3i::zero()); return LVecBase3i(_indices[index], _indices[index + 1], _indices[index + 2]); } /** * Returns the number of triangles in this triangle mesh. * Assumes the lock(bullet global lock) is held by the caller */ size_t BulletTriangleMesh:: do_get_num_triangles() const { return _indices.size() / 3; } /** * Returns the number of triangles in this triangle mesh. */ size_t BulletTriangleMesh:: get_num_triangles() const { LightMutexHolder holder(BulletWorld::get_global_lock()); return do_get_num_triangles(); } /** * Used to reserve memory in anticipation of the given amount of vertices and * indices being added to the triangle mesh. This is useful if you are about * to call add_triangle() many times, to prevent unnecessary reallocations. */ void BulletTriangleMesh:: preallocate(int num_verts, int num_indices) { LightMutexHolder holder(BulletWorld::get_global_lock()); _vertices.reserve(num_verts); _indices.reserve(num_indices); btIndexedMesh &mesh = _mesh.getIndexedMeshArray()[0]; mesh.m_vertexBase = (unsigned char*)&_vertices[0]; mesh.m_triangleIndexBase = (unsigned char *)&_indices[0]; } /** * Adds a triangle with the indicated coordinates. * * If remove_duplicate_vertices is true, it will make sure that it does not * add duplicate vertices if they already exist in the triangle mesh, within * the tolerance specified by set_welding_distance(). This comes at a * significant performance cost, especially for large meshes. * Assumes the lock(bullet global lock) is held by the caller */ void BulletTriangleMesh:: do_add_triangle(const LPoint3 &p0, const LPoint3 &p1, const LPoint3 &p2, bool remove_duplicate_vertices) { nassertv(!p0.is_nan()); nassertv(!p1.is_nan()); nassertv(!p2.is_nan()); btIndexedMesh &mesh = _mesh.getIndexedMeshArray()[0]; mesh.m_numTriangles++; if (!remove_duplicate_vertices) { unsigned int index = _vertices.size(); _indices.push_back(index++); _indices.push_back(index++); _indices.push_back(index++); _vertices.push_back(LVecBase3_to_btVector3(p0)); _vertices.push_back(LVecBase3_to_btVector3(p1)); _vertices.push_back(LVecBase3_to_btVector3(p2)); mesh.m_numVertices += 3; mesh.m_vertexBase = (unsigned char*)&_vertices[0]; } else { _indices.push_back(find_or_add_vertex(p0)); _indices.push_back(find_or_add_vertex(p1)); _indices.push_back(find_or_add_vertex(p2)); } mesh.m_triangleIndexBase = (unsigned char *)&_indices[0]; } /** * Adds a triangle with the indicated coordinates. * * If remove_duplicate_vertices is true, it will make sure that it does not * add duplicate vertices if they already exist in the triangle mesh, within * the tolerance specified by set_welding_distance(). This comes at a * significant performance cost, especially for large meshes. */ void BulletTriangleMesh:: add_triangle(const LPoint3 &p0, const LPoint3 &p1, const LPoint3 &p2, bool remove_duplicate_vertices) { LightMutexHolder holder(BulletWorld::get_global_lock()); do_add_triangle(p0, p1, p2, remove_duplicate_vertices); } /** * Sets the square of the distance at which vertices will be merged * together when adding geometry with remove_duplicate_vertices set to true. * * The default is 0, meaning vertices will only be merged if they have the * exact same position. */ void BulletTriangleMesh:: set_welding_distance(PN_stdfloat distance) { LightMutexHolder holder(BulletWorld::get_global_lock()); _welding_distance = distance; } /** * Returns the value previously set with set_welding_distance(), or the * value of 0 if none was set. */ PN_stdfloat BulletTriangleMesh:: get_welding_distance() const { LightMutexHolder holder(BulletWorld::get_global_lock()); return _welding_distance; } /** * Adds the geometry from the indicated Geom from the triangle mesh. This is * a one-time copy operation, and future updates to the Geom will not be * reflected. * * If remove_duplicate_vertices is true, it will make sure that it does not * add duplicate vertices if they already exist in the triangle mesh, within * the tolerance specified by set_welding_distance(). This comes at a * significant performance cost, especially for large meshes. */ void BulletTriangleMesh:: add_geom(const Geom *geom, bool remove_duplicate_vertices, const TransformState *ts) { LightMutexHolder holder(BulletWorld::get_global_lock()); nassertv(geom); nassertv(ts); CPT(GeomVertexData) vdata = geom->get_vertex_data(); size_t num_vertices = vdata->get_num_rows(); GeomVertexReader reader = GeomVertexReader(vdata, InternalName::get_vertex()); btIndexedMesh &mesh = _mesh.getIndexedMeshArray()[0]; if (!remove_duplicate_vertices) { // Fast path: directly copy the vertices and indices. mesh.m_numVertices += num_vertices; unsigned int index_offset = _vertices.size(); _vertices.reserve(_vertices.size() + num_vertices); if (ts->is_identity()) { while (!reader.is_at_end()) { _vertices.push_back(LVecBase3_to_btVector3(reader.get_data3())); } } else { LMatrix4 m = ts->get_mat(); while (!reader.is_at_end()) { _vertices.push_back(LVecBase3_to_btVector3(m.xform_point(reader.get_data3()))); } } for (size_t k = 0; k < geom->get_num_primitives(); ++k) { CPT(GeomPrimitive) prim = geom->get_primitive(k); prim = prim->decompose(); if (prim->is_of_type(GeomTriangles::get_class_type())) { int num_vertices = prim->get_num_vertices(); _indices.reserve(_indices.size() + num_vertices); mesh.m_numTriangles += num_vertices / 3; CPT(GeomVertexArrayData) vertices = prim->get_vertices(); if (vertices != nullptr) { GeomVertexReader index(std::move(vertices), 0); while (!index.is_at_end()) { _indices.push_back(index_offset + index.get_data1i()); } } else { int index = index_offset + prim->get_first_vertex(); int end_index = index + num_vertices; while (index < end_index) { _indices.push_back(index++); } } } } nassertv(mesh.m_numTriangles * 3 == _indices.size()); } else { // Collect points pvector<LPoint3> points; points.reserve(_vertices.size() + num_vertices); if (ts->is_identity()) { while (!reader.is_at_end()) { points.push_back(reader.get_data3()); } } else { LMatrix4 m = ts->get_mat(); while (!reader.is_at_end()) { points.push_back(m.xform_point(reader.get_data3())); } } // Add triangles for (size_t k = 0; k < geom->get_num_primitives(); ++k) { CPT(GeomPrimitive) prim = geom->get_primitive(k); prim = prim->decompose(); if (prim->is_of_type(GeomTriangles::get_class_type())) { int num_vertices = prim->get_num_vertices(); _indices.reserve(_indices.size() + num_vertices); mesh.m_numTriangles += num_vertices / 3; CPT(GeomVertexArrayData) vertices = prim->get_vertices(); if (vertices != nullptr) { GeomVertexReader index(std::move(vertices), 0); while (!index.is_at_end()) { _indices.push_back(find_or_add_vertex(points[index.get_data1i()])); } } else { int index = prim->get_first_vertex(); int end_index = index + num_vertices; while (index < end_index) { _indices.push_back(find_or_add_vertex(points[index])); } } } } nassertv(mesh.m_numTriangles * 3 == _indices.size()); } // Reset the pointers, since the vectors may have been reallocated. mesh.m_vertexBase = (unsigned char*)&_vertices[0]; mesh.m_triangleIndexBase = (unsigned char *)&_indices[0]; } /** * Adds triangle information from an array of points and indices referring to * these points. This is more efficient than adding triangles one at a time. * * If remove_duplicate_vertices is true, it will make sure that it does not * add duplicate vertices if they already exist in the triangle mesh, within * the tolerance specified by set_welding_distance(). This comes at a * significant performance cost, especially for large meshes. */ void BulletTriangleMesh:: add_array(const PTA_LVecBase3 &points, const PTA_int &indices, bool remove_duplicate_vertices) { LightMutexHolder holder(BulletWorld::get_global_lock()); btIndexedMesh &mesh = _mesh.getIndexedMeshArray()[0]; _indices.reserve(_indices.size() + indices.size()); if (!remove_duplicate_vertices) { unsigned int index_offset = _vertices.size(); for (size_t i = 0; i < indices.size(); ++i) { _indices.push_back(index_offset + indices[i]); } _vertices.reserve(_vertices.size() + points.size()); for (size_t i = 0; i < points.size(); ++i) { _vertices.push_back(LVecBase3_to_btVector3(points[i])); } mesh.m_numVertices += points.size(); } else { // Add the points one by one. _indices.reserve(_indices.size() + indices.size()); for (size_t i = 0; i < indices.size(); ++i) { LVecBase3 p = points[indices[i]]; _indices.push_back(find_or_add_vertex(p)); } } mesh.m_numTriangles += indices.size() / 3; // Reset the pointers, since the vectors may have been reallocated. mesh.m_vertexBase = (unsigned char*)&_vertices[0]; mesh.m_triangleIndexBase = (unsigned char *)&_indices[0]; } /** * */ void BulletTriangleMesh:: output(std::ostream &out) const { LightMutexHolder holder(BulletWorld::get_global_lock()); out << get_type() << ", " << _indices.size() / 3 << " triangles"; } /** * */ void BulletTriangleMesh:: write(std::ostream &out, int indent_level) const { indent(out, indent_level) << get_type() << ":" << endl; const IndexedMeshArray &array = _mesh.getIndexedMeshArray(); for (int i = 0; i < array.size(); ++i) { indent(out, indent_level + 2) << "IndexedMesh " << i << ":" << endl; const btIndexedMesh &mesh = array[0]; indent(out, indent_level + 4) << "num triangles:" << mesh.m_numTriangles << endl; indent(out, indent_level + 4) << "num vertices:" << mesh.m_numVertices << endl; } } /** * Finds the indicated vertex and returns its index. If it was not found, * adds it as a new vertex and returns its index. */ unsigned int BulletTriangleMesh:: find_or_add_vertex(const LVecBase3 &p) { btVector3 vertex = LVecBase3_to_btVector3(p); for (int i = 0; i < _vertices.size(); ++i) { if ((_vertices[i] - vertex).length2() <= _welding_distance) { return i; } } _vertices.push_back(vertex); btIndexedMesh &mesh = _mesh.getIndexedMeshArray()[0]; mesh.m_numVertices++; mesh.m_vertexBase = (unsigned char*)&_vertices[0]; return _vertices.size() - 1; } /** * Tells the BamReader how to create objects of type BulletTriangleMesh. */ void BulletTriangleMesh:: register_with_read_factory() { BamReader::get_factory()->register_factory(get_class_type(), make_from_bam); } /** * Writes the contents of this object to the datagram for shipping out to a * Bam file. */ void BulletTriangleMesh:: write_datagram(BamWriter *manager, Datagram &dg) { dg.add_stdfloat(get_welding_distance()); // In case we ever want to represent more than 1 indexed mesh. dg.add_int32(1); btIndexedMesh &mesh = _mesh.getIndexedMeshArray()[0]; dg.add_int32(mesh.m_numVertices); dg.add_int32(mesh.m_numTriangles); // In case we want to use this to distinguish 16-bit vs 32-bit indices. dg.add_bool(true); // Add the vertices. const unsigned char *vptr = mesh.m_vertexBase; nassertv(vptr != nullptr || mesh.m_numVertices == 0); for (int i = 0; i < mesh.m_numVertices; ++i) { const btVector3 &vertex = *((btVector3 *)vptr); dg.add_stdfloat(vertex.getX()); dg.add_stdfloat(vertex.getY()); dg.add_stdfloat(vertex.getZ()); vptr += mesh.m_vertexStride; } // Now add the triangle indices. const unsigned char *iptr = mesh.m_triangleIndexBase; nassertv(iptr != nullptr || mesh.m_numTriangles == 0); for (int i = 0; i < mesh.m_numTriangles; ++i) { int *triangle = (int *)iptr; dg.add_int32(triangle[0]); dg.add_int32(triangle[1]); dg.add_int32(triangle[2]); iptr += mesh.m_triangleIndexStride; } } /** * This function is called by the BamReader's factory when a new object of * type BulletShape is encountered in the Bam file. It should create the * BulletShape and extract its information from the file. */ TypedWritable *BulletTriangleMesh:: make_from_bam(const FactoryParams &params) { BulletTriangleMesh *param = new BulletTriangleMesh; DatagramIterator scan; BamReader *manager; parse_params(params, scan, manager); param->fillin(scan, manager); return param; } /** * This internal function is called by make_from_bam to read in all of the * relevant data from the BamFile for the new BulletTriangleMesh. */ void BulletTriangleMesh:: fillin(DatagramIterator &scan, BamReader *manager) { set_welding_distance(scan.get_stdfloat()); nassertv(scan.get_int32() == 1); int num_vertices = scan.get_int32(); int num_triangles = scan.get_int32(); nassertv(scan.get_bool() == true); btIndexedMesh &mesh = _mesh.getIndexedMeshArray()[0]; mesh.m_numVertices = num_vertices; mesh.m_numTriangles = num_triangles; // Read and add the vertices. _vertices.clear(); _vertices.reserve(num_vertices); for (int i = 0; i < num_vertices; ++i) { PN_stdfloat x = scan.get_stdfloat(); PN_stdfloat y = scan.get_stdfloat(); PN_stdfloat z = scan.get_stdfloat(); _vertices.push_back(btVector3(x, y, z)); } // Now read and add the indices. size_t num_indices = (size_t)num_triangles * 3; _indices.resize(num_indices); scan.extract_bytes((unsigned char *)&_indices[0], num_indices * sizeof(int)); // Reset the pointers, since the vectors may have been reallocated. mesh.m_vertexBase = (unsigned char*)&_vertices[0]; mesh.m_triangleIndexBase = (unsigned char *)&_indices[0]; }
true
129d59537ecb63db86520e091e211675923cf9a8
C++
zhangxu128/Cplusplus
/进制转换/进制转换/进制转换.cpp
GB18030
679
3.390625
3
[]
no_license
#include <string> #include <iostream> using namespace std; //Ŀ //һʮMԼҪתĽNʮMתΪN // : //ΪһУM(32λ)N(2 N 16)Կո // : //ΪÿʵתÿռһСN9 //Ӧֹο16ƣ磬10Aʾȵȣ int main() { string s = "", table = "0123456789ABCDEF"; int m, n; cin >> m >> n; while (m) { if (m < 0) { m = -m; cout << "-"; } s = table[m%n] + s; m /= n; } cout << s << endl; system("pause"); return 0; }
true
7e3a62add265f38daa333833bce45cf1ff7303d8
C++
benitogr-code/cs101
/src/lib/BigInt.h
UTF-8
1,393
3.171875
3
[]
no_license
#pragma once #include <string> #include <vector> /** Big Int Implements storage for big integers and some common math operations */ class CBigInt { private: enum { eBase = 1000000000 }; typedef std::vector<int> Storage; public: CBigInt(); CBigInt(long long value); CBigInt(const CBigInt& value); void operator=(long long value); void operator=(const CBigInt& value); bool operator==(const CBigInt& rhs) const; bool operator!=(const CBigInt& rhs) const; bool operator<(const CBigInt& rhs) const; bool operator<=(const CBigInt& rhs) const; bool operator>(const CBigInt& rhs) const; bool operator>=(const CBigInt& rhs) const; CBigInt operator-() const; CBigInt operator+(long long value) const; CBigInt operator+(const CBigInt& value) const; CBigInt& operator+=(long long value); CBigInt& operator+=(const CBigInt& value); CBigInt operator-(long long value) const; CBigInt operator-(const CBigInt& value) const; CBigInt& operator-=(long long value); CBigInt& operator-=(const CBigInt& value); CBigInt operator*(long long value) const; CBigInt operator*(const CBigInt& value) const; CBigInt& operator*=(long long value); CBigInt& operator*=(const CBigInt& value); std::string ToString() const; private: void Trim(); static CBigInt Sum(const CBigInt& a, const CBigInt& b, size_t shift = 0); private: Storage m_data; bool m_bPositive; };
true
7f01d0801f4d0774da33576163e2070b2713e90d
C++
rmagalhaess/Calendario
/atual/U_Projeto_Arquivo.cpp
UTF-8
3,151
2.765625
3
[]
no_license
#ifndef U_Projeto_Arquivo_H #define U_Projeto_Arquivo_H #include <U_Projeto_Arquivo.h> #endif #ifndef U_Projeto_H #define U_Projeto_H #include <U_Projeto.h> #endif /* struct struct_Projeto { String Nome; String Data_Entrega; String Data_Alteracao; int Tamanho; }; */ int Salvar_Arquivo_Projeto( TPanel *p_Painel, Tp_Projeto *p_Lst_Projeto ) { FILE *arquivo = NULL; char nome[256], data[16]; int quant=p_Painel->Tag, cont=0, tam=0; arquivo = fopen( "projeto.txt", "w" ); if( arquivo != NULL ) { while (cont<quant) { tam += fprintf(arquivo, "%s %s %s\n\0", p_Lst_Projeto[cont].Nome, p_Lst_Projeto[cont].Data_Entrega, p_Lst_Projeto[cont].Data_Alteracao); cont++; } } fclose (arquivo); return tam; } int Abrir_Arquivo_Projeto( TPanel *p_Painel, Tp_Projeto *p_Lst_Projeto ) { FILE *arquivo = NULL; char nome[256], data_entrega[16], data_alteracao[16]; int tam=0, cont=0; arquivo = fopen( "projeto.txt", "r" ); if( arquivo != NULL ) { while ( fscanf(arquivo, "%s %s %s", nome, data_entrega, data_alteracao) > 0) //!feof(arquivo)) { //tam += fscanf(arquivo, "%s %s", nome, data); p_Lst_Projeto[cont].Nome = nome; p_Lst_Projeto[cont].Data_Entrega = data_entrega; p_Lst_Projeto[cont].Data_Alteracao = data_alteracao; cont++; } p_Painel->Tag = cont; } fclose (arquivo); return tam; } /* int Tamanho_Arquivo( char p_Arquivo[256] ) { FILE * pFile; long size; pFile = fopen (p_Arquivo,"rb"); if (pFile!=NULL) { fseek(pFile, 0, SEEK_END); size=ftell(pFile); } fclose (pFile); return size; } int Tamanho_SubDiretorio( char p_Dir[256] ) { DIR *dpdf, *aux; struct dirent *epdf; int tamanho=0; dpdf = opendir(p_Dir); if (dpdf != NULL) { while (epdf = readdir(dpdf)) { if ((strcmp(epdf->d_name, ".")!=0) && (strcmp(epdf->d_name, "..")!=0)) { aux = opendir(epdf->d_name); if (aux != NULL) { tamanho += Tamanho_SubDiretorio( epdf->d_name ); } else { tamanho += Tamanho_Arquivo( epdf->d_name ); } aux = NULL; } } } return tamanho; } int Tamanho_Diretorio() { DIR *dpdf, *aux; struct dirent *epdf; int tamanho=0; dpdf = opendir("./"); if (dpdf != NULL) { while (epdf = readdir(dpdf)) { if ((strcmp(epdf->d_name, ".")!=0) && (strcmp(epdf->d_name, "..")!=0)) { aux = opendir(epdf->d_name); if (aux != NULL) { tamanho += Tamanho_SubDiretorio( epdf->d_name ); } else { tamanho += Tamanho_Arquivo( epdf->d_name ); } aux = NULL; } } } return tamanho; } */
true
4731c0f45f659800a1f383099ff80fb8f27f441e
C++
TheIslland/learning-in-collegelife
/5.数据结构学习/重建二叉树.cpp
UTF-8
2,005
3.234375
3
[]
no_license
/************************************************************************* > File Name: 重建二叉树.cpp > Author:TheIslland > Mail: 861436930@qq.com > Created Time: 2019年03月26日 星期二 18时58分03秒 ************************************************************************/ /** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ /*关于重建二叉树,我们使用前序遍历与中序遍历建树时,根据前序遍历根左右的输出顺序,与中序遍历左根右的输出顺序 得知,前序遍历的首位置为根节点,后接左子树与右子树,但区间不明确,故我们需要划分区间,中序遍历的根节点左部分为左子树, 根节点右部分右子树,所以当我们在中序遍历中获取到根节点位置即可划分左右子树 故我们在前序遍历中获取根节点后在中序遍历中寻找其位置的过程中同步划分前序遍历的左子树与中序遍历左子树, 根节点位置找到后我们就得知了前序遍历左子树与右子树区间,与中序遍历的左子树与右子树, 我们将前序遍历的左子树与中序遍历的左子树递归重复此过程,右子树同理,故重建二叉树 */ class Solution { public: TreeNode *build(vector<int> &pre, vector<int> &vin, int i, int j, int k, int l) { if(j < i) return nullptr; TreeNode *root = new TreeNode(pre[i]); int di = i + 1, dj = i + 1, dk = k, dl = k;; while(vin[dl] != pre[i]) dl += 1, dj += 1; dl -= 1, dj -= 1; root->left = build(pre, vin, di, dj, dk, dl); di = dj + 1; dj = j; dk = dl + 2; dl = l; root->right = build(pre, vin, di, dj, dk, dl); return root; } TreeNode* reConstructBinaryTree(vector<int> pre,vector<int> vin) { return build(pre, vin, 0, pre.size() - 1, 0, vin.size() - 1); } };
true
253fce9585fc9ca41ba4e30870f5ec42f8d8ac83
C++
weichaoage789/CCOV-CSB
/CcovRsov/Utilities/NetWork/Ping.cpp
UTF-8
6,509
2.625
3
[]
no_license
#include "Ping.h" namespace NetWork { Ping::Ping() { _MaxCnt = 4; _DataLen = 56; _SendCnt = 0; _RecvCnt = 0; _ICMP_SEQ = 0; } unsigned short Ping::getChksum(unsigned short *addr, int len) { int nleft = len; int sum = 0; unsigned short *w = addr; unsigned short answer = 0; /*把ICMP报头二进制数据以2字节为单位累加起来*/ while (nleft > 1) { sum += *w++; nleft -= 2; } /*若ICMP报头为奇数个字节,会剩下最后一字节。把最后一个字节视为一个2字节数据的高字节,这个2字节数据的低字节为0,继续累加*/ if (nleft == 1) { *(unsigned char *)(&answer) = *(unsigned char *)w; sum += answer; } sum = (sum >> 16) + (sum & 0xffff); sum += (sum >> 16); answer = ~sum; return answer; } int Ping::packIcmp(int pack_no, struct icmp* icmp) { int packsize; struct icmp *picmp; struct timeval *tval; picmp = icmp; picmp->icmp_type = ICMP_ECHO; picmp->icmp_code = 0; picmp->icmp_cksum = 0; picmp->icmp_seq = pack_no; picmp->icmp_id = _Pid; packsize = 8 + _DataLen; tval = (struct timeval *)icmp->icmp_data; /** @记录发送时间 */ gettimeofday(tval, NULL); /** @校验算法 */ picmp->icmp_cksum = getChksum((unsigned short *)icmp, packsize); return packsize; } bool Ping::unpackIcmp(char *buf, int len, struct IcmpEchoReply *icmpEchoReply) { int i, iphdrlen; struct ip *ip; struct icmp *icmp; struct timeval *tvsend, tvrecv, tvresult; double rtt; ip = (struct ip *)buf; iphdrlen = ip->ip_hl << 2; /*求ip报头长度,即ip报头的长度标志乘4*/ icmp = (struct icmp *)(buf + iphdrlen); /*越过ip报头,指向ICMP报头*/ len -= iphdrlen; /*ICMP报头及ICMP数据报的总长度*/ if (len < 8) /*小于ICMP报头长度则不合理*/ { printf("ICMP packets\'s length is less than 8\n"); return false; } /*确保所接收的是我所发的的ICMP的回应*/ if ((icmp->icmp_type == ICMP_ECHOREPLY) && (icmp->icmp_id == _Pid)) { tvsend = (struct timeval *)icmp->icmp_data; gettimeofday(&tvrecv, NULL); /*记录接收时间*/ tvresult = tvSub(tvrecv, *tvsend); /*接收和发送的时间差*/ rtt = tvresult.tv_sec * 1000 + tvresult.tv_usec / 1000; /*以毫秒为单位计算rtt*/ icmpEchoReply->rtt = rtt; icmpEchoReply->icmpSeq = icmp->icmp_seq; icmpEchoReply->ipTtl = ip->ip_ttl; icmpEchoReply->icmpLen = len; return true; } return false; } struct timeval Ping::tvSub(struct timeval timeval1, struct timeval timeval2) { struct timeval result; result = timeval1; if (result.tv_usec < timeval2.tv_usec < 0) { --result.tv_sec; result.tv_usec += 1000000; } result.tv_sec -= timeval2.tv_sec; return result; } bool Ping::sendPacket() { size_t packetsize; while (_SendCnt < _MaxCnt) { _SendCnt++; _ICMP_SEQ++; /*设置ICMP报头*/ packetsize = packIcmp(_ICMP_SEQ, (struct icmp*)_SendBuf); if (sendto(_SocketFd, _SendBuf, packetsize, 0, (struct sockaddr *) &_DestAddr, sizeof(_DestAddr)) < 0) { continue; } } return true; } bool Ping::recvPacket(PingResult &pingResult) { int len; struct IcmpEchoReply icmpEchoReply; int maxfds = _SocketFd + 1; int nfd = 0; fd_set rset; FD_ZERO(&rset); socklen_t fromlen = sizeof(_HostAddr); struct timeval timeout; timeout.tv_sec = 4; timeout.tv_usec = 0; for (int recvCount = 0; recvCount < _MaxCnt; recvCount++) { FD_SET(_SocketFd, &rset); if ((nfd = select(maxfds, &rset, NULL, NULL, &timeout)) == -1) { perror("select error"); continue; } if (nfd == 0) { icmpEchoReply.isReply = false; pingResult.icmpEchoReplys.push_back(icmpEchoReply); continue; } if (FD_ISSET(_SocketFd, &rset)) { if ((len = recvfrom(_SocketFd, _RecvBuf, sizeof(_RecvBuf), 0, (struct sockaddr *)&_HostAddr, &fromlen)) < 0) { if (errno == EINTR) continue; perror("receive from error"); continue; } icmpEchoReply.fromAddr = inet_ntoa(_HostAddr.sin_addr); if (icmpEchoReply.fromAddr != pingResult.ip) { recvCount--; continue; } } if (unpackIcmp(_RecvBuf, len, &icmpEchoReply) == -1) { recvCount--; continue; } icmpEchoReply.isReply = true; pingResult.icmpEchoReplys.push_back(icmpEchoReply); _RecvCnt++; } return true; } bool Ping::getsockaddr(const char * hostOrIp, struct sockaddr_in* sockaddr) { struct hostent *host; struct sockaddr_in dest_addr; unsigned long inaddr = 0l; bzero(&dest_addr, sizeof(dest_addr)); dest_addr.sin_family = AF_INET; /*判断是主机名还是ip地址*/ if (inaddr = inet_addr(hostOrIp) == INADDR_NONE) { if ((host = gethostbyname(hostOrIp)) == NULL) { /*是主机名*/ return false; } memcpy((char *)&dest_addr.sin_addr, host->h_addr, host->h_length); } else if (!inet_aton(hostOrIp, &dest_addr.sin_addr)) { /*是ip地址*/ return false; } *sockaddr = dest_addr; return true; } bool Ping::ping(std::string host, PingResult& pingResult) { return ping(host, 1, pingResult); } bool Ping::ping(std::string host, int count, PingResult& pingResult) { struct protoent *protocol; int size = 50 * 1024; IcmpEchoReply icmpEchoReply; bool ret; _SendCnt = 0; _RecvCnt = 0; pingResult.icmpEchoReplys.clear(); _MaxCnt = count; _Pid = getpid(); pingResult.dataLen = _DataLen; if ((protocol = getprotobyname("icmp")) == NULL) { perror("getprotobyname"); return false; } /*生成使用ICMP的原始套接字,这种套接字只有root才能生成*/ if ((_SocketFd = socket(AF_INET, SOCK_RAW, protocol->p_proto)) < 0) { //extern int errno; //pingResult.error = strerror(errno); return false; } /*扩大套接字接收缓冲区到50K这样做主要为了减小接收缓冲区溢出的 的可能性,若无意中ping一个广播地址或多播地址,将会引来大量应答*/ setsockopt(_SocketFd, SOL_SOCKET, SO_RCVBUF, &size, sizeof(size)); /*获取main的进程id,用于设置ICMP的标志符*/ if (!getsockaddr(host.c_str(), &_DestAddr)) { pingResult.error = "unknow host " + host; return false; } pingResult.ip = inet_ntoa(_DestAddr.sin_addr); sendPacket(); /*发送所有ICMP报文*/ recvPacket(pingResult); /*接收所有ICMP报文*/ pingResult.nsend = _SendCnt; pingResult.nreceived = _RecvCnt; close(_SocketFd); return true; } }
true
9983d632fb7a4d31f4db84b23c370d843f74cc8c
C++
MTBorg/Ambii
/Arduino/interpolated.ino
UTF-8
3,141
2.953125
3
[]
no_license
#include "FastLED.h" #define BAUD_RATE 57600 #define PIN_OUTPUT 13 #define PIXEL_AMOUNT 30 //Interpolation settings #define INTERPOL_TICKS 20 //Keep this as low as possible, color differences lower than this will not be interpolated (diff/ticks < 1 will be rounded to 0). #define INTERPOL_WAITTIME 1 //This is recommended to be about zero for everything but debugging purposes. CRGB outputBuffer[PIXEL_AMOUNT]; CRGB newBuffer[PIXEL_AMOUNT]; //Function prototypes void setup(); void loop(); /* * Interpolates the output value linearly. */ void interpolLin(){ CRGB diffs[PIXEL_AMOUNT]; for(unsigned int i = 0; i < PIXEL_AMOUNT; i++){ diffs[i].b = (newBuffer[i].b - outputBuffer[i].b) / INTERPOL_TICKS; diffs[i].g = (newBuffer[i].g - outputBuffer[i].g) / INTERPOL_TICKS; diffs[i].r = (newBuffer[i].r - outputBuffer[i].r) / INTERPOL_TICKS; } for(unsigned int tick = 0; tick < INTERPOL_TICKS; tick++){ for(unsigned int pixel = 0; pixel < PIXEL_AMOUNT; pixel++){ outputBuffer[pixel].r += diffs[pixel].r; outputBuffer[pixel].g += diffs[pixel].g; outputBuffer[pixel].b += diffs[pixel].b; } FastLED.show(); delay(INTERPOL_WAITTIME); } } void readBuffer(){ for(unsigned int i = 0;i < PIXEL_AMOUNT; i++){ //DEBUG, should be PIXEL_AMOUNT instead of 1 while(Serial.available() < 4); //Wait for the entire pixel to be read //Read the data newBuffer[i].b = Serial.read(); newBuffer[i].g = Serial.read(); newBuffer[i].r = Serial.read(); Serial.read(); //Throw away the fourth (reserved) byte //DEBUG /*Serial.print("I received: "); Serial.print(newBuffer[i].r, DEC); Serial.print(","); Serial.print(newBuffer[i].g), DEC; Serial.print(","); Serial.println(newBuffer[i].b, DEC);*/ } } void readBufferInt(){ for(unsigned int i = 0;i < 1; i++){ //DEBUG, should be PIXEL_AMOUNT instead of 1 while(Serial.available() < 10); //Wait for the entire pixel to be read //Read the data newBuffer[i].r = (Serial.read() - 48) * 100; newBuffer[i].r += (Serial.read() - 48) * 10; newBuffer[i].r += Serial.read() - 48; newBuffer[i].g = (Serial.read() - 48) * 100; newBuffer[i].g += (Serial.read() - 48) * 10; newBuffer[i].g += Serial.read() - 48; newBuffer[i].b = (Serial.read() - 48) * 100; newBuffer[i].b += (Serial.read() - 48) * 10; newBuffer[i].b += Serial.read() - 48; Serial.read(); //Throw away the fourth (reserved) byte //DEBUG /*Serial.print("I received: "); Serial.print(newBuffer[i].r, DEC); Serial.print(","); Serial.print(newBuffer[i].g), DEC; Serial.print(","); Serial.println(newBuffer[i].b, DEC);*/ } } void loop() { // put your main code here, to run repeatedly: readBuffer(); //readBufferInt(); interpolLin(); FastLED.show(); } void setup() { // put your setup code here, to run once: Serial.begin(BAUD_RATE); for(unsigned int i = 0; i < PIXEL_AMOUNT; i++){ outputBuffer[i].r = outputBuffer[i].g = outputBuffer[i].b = 0; } FastLED.addLeds<NEOPIXEL, PIN_OUTPUT>(outputBuffer, PIXEL_AMOUNT); }
true
78f47f349a69d3836a8bb379e06e03523aa2731f
C++
BragCat/USACO
/Section3.4/fence9.cpp
UTF-8
742
2.90625
3
[]
no_license
/* ID: bragcat1 LANG: C++11 TASK: fence9 */ #include <fstream> using namespace std; int n, m, p; int main() { ifstream fin("fence9.in"); fin >> n >> m >> p; fin.close(); int count = 0; for (int i = 1; i <= n; ++i) { count += i * m / n + ((i * m % n == 0) ? -1 : 0); } if (p > n) { n = p - n; for (int i = 1; i < n; ++i) { count += i * m / n + ((i * m % n == 0) ? -1 : 0); } } else if (n == p) { count -= m - 1; } else { n = n - p; for (int i = 1; i <= n; ++i) { count -= i * m / n; } ++count; } ofstream fout("fence9.out"); fout << count << endl; fout.close(); return 0; }
true
563b5ef9b8ee92d379c8ea68ee147fc712beffec
C++
limjaein/java-algorithm
/C++/색종이만들기.cpp
UTF-8
1,324
3.390625
3
[]
no_license
#include <iostream> #include <string.h> using namespace std; namespace { enum { BLUE = 0, WHITE = 1 }; } const int maxSize = 129; int N; int paper[maxSize][maxSize]; typedef struct Pos { int x, y; }Pos; class Cnt { private: int b, w; public: Cnt() { b = w = 0; } Cnt(int bCnt, int wCnt) { b = bCnt; w = wCnt; } int getBlueCnt() { return b; } int getWhiteCnt() { return w; } void addCnt(Cnt cnt) { b += cnt.b; w += cnt.w; } }; bool isAll1Color(int size, Pos p, bool color) { for (int i = 0; i < size; i++) { for (int j = 0; j < size; j++) { if (paper[p.y + i][p.x + j] != color) return false; } } return true; } Cnt countPaper(int size, Pos p) { Cnt cnt; int half; if (isAll1Color(size, p, 1)) return { 1, 0 }; else if (isAll1Color(size, p, 0)) return { 0, 1 }; half = size / 2; cnt.addCnt(countPaper(half, p)); cnt.addCnt(countPaper(half, {p.x + half, p.y})); cnt.addCnt(countPaper(half, {p.x, p.y + half})); cnt.addCnt(countPaper(half, { p.x + half,p.y + half })); return cnt; } int main() { Cnt result; cin >> N; memset(paper, 0, sizeof(paper)); for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) cin >> paper[i][j]; } result = countPaper(N, { 0, 0 }); cout << result.getWhiteCnt() << endl; cout << result.getBlueCnt() << endl; }
true
5735c874141439927b230fa90ffeb6956609f6d9
C++
valerik87/PathFinding
/PathFinding/PathFinding/Button.cpp
UTF-8
1,035
2.890625
3
[]
no_license
#include "Button.h" Button::Button(Vector2f size): RectangleShape(size) {} void Button::Draw(sf::RenderWindow& i_oWindow) { i_oWindow.draw(*this); i_oWindow.draw(m_oText); } void Button::SetPosition(Vector2f pos) { setPosition(pos); m_oText.setPosition(pos); } void Button::SetFillColor(Color color) { setFillColor(color); } void Button::SetSize(Vector2f size) { setSize(size); } void Button::SetText(const char* i_cText) { bool b = m_oFont.loadFromFile("Font\\arial.ttf"); m_oText.setFont(m_oFont); m_oText.setString(i_cText); m_oText.setCharacterSize(30); m_oText.setFillColor(sf::Color::Red); m_oText.setOutlineColor(sf::Color::Red); m_oText.setStyle(sf::Text::Bold); } bool Button::IsMouseClickOn(Vector2i i_iMousePosition) const { Vector2f m_oOriginPos = RectangleShape::getPosition(); Vector2f m_oSize = m_oOriginPos+RectangleShape::getSize(); return i_iMousePosition.x >= m_oOriginPos.x && i_iMousePosition.x <= m_oSize.x && i_iMousePosition.y >= m_oOriginPos.y && i_iMousePosition.y <= m_oSize.y; }
true
bf475092045ae74a313e109ef31d7521ed40eea1
C++
nalidzhik/object-oriented-programming
/dates/main.cpp
UTF-8
697
3.25
3
[]
no_license
/** * Solution to homework assignment 1 * Object Oriented Programming Course * Faculty of Mathematics and Informatics of Sofia University * Summer semester 2020/2021 * * @author Nazife Alidzhik * @idnumber 62598 * @task 1 * @compiler VC */ #include <iostream> #include "Dates.hpp" using namespace std; int main() { Date d1; d1.print(); cout << endl; Date d2 = Date(31, 3, 2014); d2.print(); Date d3 = Date(31, 8, 2019); cout << endl; cout << "result" << " " << d3.isLeapYear(); cout << endl; cout << d3.daysToXmas() << endl; cout << d2.isLaterThen(d3) << endl; cout << d2.daysToHoliday(d3) << endl; d2.addDays(1); d2.print(); cout << endl; d3.removeDays(45); d3.print(); return 0; }
true
2732a0636e39b58d53e87731132532593212fb41
C++
dumitrubogdanmihai/ObjectTracking
/ObjectTracking/ObjectTracking/ObjectFinder.cpp
UTF-8
4,904
2.609375
3
[]
no_license
#include "ObjectFinder.h" #include "Helper.h" using std::cout; ObjectFinder::ObjectFinder(int minHessian) { detector = SurfFeatureDetector(minHessian); } ObjectFinder::~ObjectFinder() { cout << "ObjectFinder class destructor was called!" << std::endl; } void ObjectFinder::find(Object const &obj, Mat &scene, vector<Point> &contourRez) { contourRez.clear(); if (!obj.cap.data || !scene.data) { std::cout << " --(!) Error reading images " << std::endl; } //-- Step 1: Detect the keypoints using SURF Detector vector<KeyPoint> keypoints_scene = detectKeypoints(scene); //-- Step 2: Calculate descriptors (feature vectors) Mat descriptors_scene = calculateDescriptors(keypoints_scene, scene); extractor.compute(scene, keypoints_scene, descriptors_scene); //-- Step 3: Matching descriptor vectors using FLANN matcher std::vector< DMatch > matches; matcher.match(obj.descriptors, descriptors_scene, matches); double max_dist = 0; double min_dist = 100; //-- Quick calculation of max and min distances between keypoints double dist; for (int i = 0; i < obj.descriptors.rows; i++) { dist = matches[i].distance; dist < min_dist ? min_dist = dist : 0; dist > max_dist ? max_dist = dist : 0; } //printf("-- Max dist : %f \n", max_dist); //printf("-- Min dist : %f \n\n", min_dist); //-- Draw only "good" matches (i.e. whose distance is less than 3*min_dist ) std::vector< DMatch > good_matches; //void filterMatches(vector< DMatch > &good_matches, vector< DMatch > matches); for (int i = 0; i < obj.descriptors.rows; i++) { if (matches[i].distance < 3 * min_dist) { good_matches.push_back(matches[i]); } } /*drawMatches(img_object, keypoints_object, img_scene, keypoints_scene, good_matches, img_matches, Scalar::all(-1), Scalar::all(-1), vector<char>(), DrawMatchesFlags::NOT_DRAW_SINGLE_POINTS); */ //-- Localize the object std::vector<Point2f> objV; std::vector<Point2f> sceneV; for (unsigned int i = 0; i < good_matches.size(); i++) { //-- Get the keypoints from the good matches objV.push_back(obj.keypoints[good_matches[i].queryIdx].pt); sceneV.push_back(keypoints_scene[good_matches[i].trainIdx].pt); } if (good_matches.size() < 5) { cout << "Good_matches vector size : " << good_matches.size() << endl << endl; return; } Mat H = findHomography(objV, sceneV, CV_RANSAC); //-- Get the corners from the image_1 ( the object to be "detected" ) std::vector<Point2f> obj_corners(4); obj_corners[0] = cvPoint(0, 0); obj_corners[1] = cvPoint(obj.cap.cols, 0); obj_corners[2] = cvPoint(obj.cap.cols, obj.cap.rows); obj_corners[3] = cvPoint(0, obj.cap.rows); std::vector<Point2f> scene_corners(4); //for (int j = 0; j < scene_corners.size(); j++) //{ // scene_corners[j] = Point2f(0, 0); //} perspectiveTransform(obj_corners, scene_corners, H); //cout << "scene_corners " << endl << scene_corners << endl << " size:" << obj_corners.size() << endl << endl; contourRez.push_back(Point(scene_corners[0].x, scene_corners[0].y)); contourRez.push_back(Point(scene_corners[1].x, scene_corners[1].y)); contourRez.push_back(Point(scene_corners[2].x, scene_corners[2].y)); contourRez.push_back(Point(scene_corners[3].x, scene_corners[3].y)); return; } bool ObjectFinder::objectFinded(vector<Point> const &contour, Mat const &frame, Point const &decal) { if (contour.size() < 4) { return false; } if (contourArea(contour) < 15) { cout << "Contour area < 15" << endl << endl; return false; } if (intersection(contour[0], contour[1], contour[2], contour[3])) { cout << "Diagonals are intersecting" << endl << endl; //cout << contour << endl; return false; } for (int j = 0; j < 4; j++) { if (contour[j].x + decal.x < 0) { cout << "Object unfinded! " << endl; cout << " Contour out of limits : "; // cout << " x= " << contour[j].x + decal.x << endl << endl; return false; } else if (contour[j].x + decal.x > frame.cols) { cout << "Object unfinded! " << endl; cout << " Contour out of limits : "; // cout << " x= " << contour[j].x + decal.x << endl << endl; return false; } else if (contour[j].y + decal.y < 0) { cout << "Object unfinded! " << endl; cout << " Contour out of limits : "; // cout << " y= " << contour[j].y + decal.y << endl << endl; return false; } else if (contour[j].y + decal.y > frame.rows) { cout << "Object unfinded! " << endl; cout << " Contour out of limits : "; // cout << " y= " << contour[j].y + decal.y << endl << endl; return false; } } cout << "Object finded! " << endl; return true; } vector<KeyPoint> ObjectFinder::detectKeypoints(Mat &m) { vector<KeyPoint> keyp; detector.detect(m, keyp); return keyp; } Mat ObjectFinder::calculateDescriptors(vector<KeyPoint> &keypoints, Mat &m) { Mat descriptors; extractor.compute(m, keypoints, descriptors); return descriptors; }
true
75d6f3a69d71b44056c03bce3c09b0408ce31a62
C++
agspathis/task-space-projection
/task_space/tests/TestUtil.h
UTF-8
3,712
3.359375
3
[]
no_license
#ifndef TEST_UTIL_H #define TEST_UTIL_H /** * \file This file contains some test utilities. * * @author Dimitar Stanev <jimstanev@gmail.com> * * @see <a href="https://simtk.org/projects/task-space">[SimTK Project]</a>, <a * href="http://ieeexplore.ieee.org/document/8074739/">[Publication]</a> */ #include <iostream> /** * Test whether the supplied statement throws an std::exception of some kind, * and show what message got thrown. * * @param statement the statement to be executed. */ #define MUST_THROW(statement) \ do { \ int threw = 0; \ try { \ statement; \ } \ catch(const std::exception& e) { \ threw = 1; \ std::cout << "(OK) Threw: " << e.what() << std::endl; \ } \ catch(...) { \ threw=2; \ } \ if (threw == 0) { \ printf("The statement %s was expected to throw an exception but it did not.", #statement); \ throw std::exception(); \ } \ if (threw == 2) { \ printf("The statement %s was expected to throw an std::exception but it threw something else.", #statement); \ throw std::exception(); \ } \ }while(false) /** * Test that the supplied statement throws a particular exception. * * @param statement the statement to be executed. * * @param exc the exeption tha must be thrown */ #define MUST_THROW_EXCEPTION(statement, exc) \ do { \ int threw = 0; \ try { \ statement; \ } \ catch(const exc& e) { \ threw = 1; \ std::cout << "(OK) Threw: " << e.what() << std::endl; \ } \ catch(...) { \ threw=2; \ } \ if (threw == 0) { \ printf("The statement %s was expected to throw an exception but it did not.", #statement); \ throw std::exception(); \ } \ if (threw == 2) { \ printf("The statement %s was expected to throw an %s exception but it threw something else.", #statement, #exc); \ throw std::exception(); \ } \ }while(false) #endif
true
8ba1b767fdbb9230e022043636eefc60e2b55723
C++
flynn2016/5850_FinalProject
/src/Key.cpp
UTF-8
837
2.859375
3
[]
no_license
#include "Key.h" Key::Key() { mKey = new Texture("Key.png", 0, 0, Key_WIDTH, Key_HEIGHT); mKey->Pos(Vector2(50, 50)); mKey->Scale(Vector2(0.3f, 0.3f)); mWin = new Texture("You Passed!", "alpha_echo.ttf", 36*2 , {255, 249, 196}); mWin->Pos(Vector2(640, 500)); mLose = new Texture("You Lost!", "alpha_echo.ttf", 36*2 , {255, 249, 196}); mLose->Pos(Vector2(640, 500)); } Key::~Key() { delete mKey; mKey = nullptr; } void Key::Update(float delta) { if (!finished) { x += (640 - 50) / 200; y += (360 - 50) / 300; scale += 0.004; mKey->Pos(Vector2(x, y)); mKey->Scale(Vector2(scale, scale)); } if (x > 640) finished = true; if (finished) { mKey->Rotate(20 * delta); } } void Key::Render(float delta) { mKey->Render(); mWin->Render(); } void Key::RenderLost(){ mLose->Render(); }
true
927a193ee60fe709423a3f061edb9caa9b657af7
C++
Nuos/shadow
/src/engine/mobs/Mob.cc
UTF-8
490
2.984375
3
[]
no_license
/* * File: Mob.cc * Author: jts * * Created on 8 July 2014, 11:59 AM */ #include "Mob.h" #include <list> #include <iostream> void Mob::tick(Vector<int> target) { std::list<Vector<int>> path = this->map->pathfinder.Dijkstra(this->pos, target); path.pop_front(); Vector<int> move = path.front().sub(this->pos).toDouble().normalise().scale(MAP_SCALE).toInt(); this->move(move); std::cout << "Mob moved by (" << move.x << "," << move.y << ")" << std::endl; }
true
2cc5411e1aa598bd4cb3a69823411a7b2a62e519
C++
PeiJunLiu/Breakout
/post_processor.h
GB18030
1,330
2.703125
3
[]
no_license
#ifndef POST_PROCESSOR_H #define POST_PROCESSOR_H #include <GL/glew.h> #include <glm/glm.hpp> #include "texture.h" #include "sprite_renderer.h" #include "Shader.h" //PostProcessorΪBreakout GameṩкڴЧ //ıȾϷȻͨConfuseChaosShakeֵضЧ //ڳϷЧ֮ǰҪBeginRenderȻȾϷ֮EndRender class PostProcessor { public: // ״̬ Shader PostProcessingShader; Texture2D Texture; GLuint Width, Height; // ЧЧѡת磬 GLboolean Confuse, Chaos, Shake; // 캯 PostProcessor(Shader shader, GLuint width, GLuint height); // ȾϷ֮ǰ׼֡ void BeginRender(); // ӦȾϷãȾݴ洢 void EndRender(); // Renders the PostProcessor texture quad (as a screen-encompassing large sprite) void Render(GLfloat time); private: // Ⱦ״̬ GLuint MSFBO, FBO; // MSFBO =زFBO FBOdzģڽMSɫֵ GLuint RBO; // RBOڶزɫ GLuint VAO; // ʼıȾ void initRenderData(); }; #endif
true
bc8d0c90a3d4ab46e0a7b9e18adf39f596dc6eac
C++
Algocourse/autumn2016-contests
/strings/D.cpp
UTF-8
901
3.125
3
[]
no_license
#include <algorithm> #include <chrono> #include <iostream> #include <vector> using namespace std; using namespace std::chrono; void do_shift(string& s, int l, int r, int k) { k %= (r - l + 1); string buf = ""; for (int i = r - k + 1; i <= r; ++i) buf += s[i]; for (int i = l; i < r - k + 1; ++i) buf += s[i]; for (int i = 0; i < r - l + 1; ++i) s[l + i] = buf[i]; } int main() { auto start = high_resolution_clock::now(); ios_base::sync_with_stdio(false); cin.tie(nullptr); string s; int m; cin >> s >> m; for (int i = 0; i < m; ++i) { int l, r, k; cin >> l >> r >> k; --l; --r; do_shift(s, l, r, k); } cout << s << endl; cerr << "Total execution time : " << duration_cast<milliseconds>(high_resolution_clock::now() - start).count() << " ms" << endl; return 0; }
true
772979b843d71ff98e07228ef2c012062ad94920
C++
Afinogen/calc
/tokens.h
WINDOWS-1251
917
2.65625
3
[]
no_license
//--------------------------------------------------------------------------- #ifndef tokensH #define tokensH #include <vector> #include "token.h" //#include "convert.h" using namespace std; /* */ class Tokens//: public Convert { public: Tokens(); // ~Tokens(); // bool addToken(const Operator, double num=0); // bool deleteToken(const unsigned int id); // int getSize() const; // Token *getToken(const int id) const; // private: vector<Token*> __vTokens; // }; //--------------------------------------------------------------------------- #endif
true
7a60fcf6edb8f984d3be98945caadd4c19a87b12
C++
efdazedo/asgard
/src/pde/pde_fokkerplanck2_complete.hpp
UTF-8
17,850
2.546875
3
[ "MIT" ]
permissive
#pragma once #include <algorithm> #include <cassert> #include <cmath> #include <functional> #include <iostream> #include <map> #include <math.h> #include <memory> #include <string> #include <typeinfo> #include <vector> #include "../tensors.hpp" #include "pde_base.hpp" // --------------------------------------------------------------------------- // Full PDE from the 2D runaway electron paper // // d/dt f(p,z) == -div(flux_C + flux_E + flux_R) // // where // // flux_C is flux due to electron-ion collisions // flux_E is the flux due to E accleration // flux_R is the flux due to radiation damping // // -div(flux_C) == termC1 + termC2 + termC3 // // termC1 == 1/p^2*d/dp*p^2*Ca*df/dp // termC2 == 1/p^2*d/dp*p^2*Cf*f // termC3 == termC3 == Cb(p)/p^4 * d/dz( (1-z^2) * df/dz ) // // -div(flux_E) == termE1 + termE2 // // termE1 == -E*z*f(z) * 1/p^2 (d/dp p^2 f(p)) // termE2 == -E*p*f(p) * d/dz (1-z^2) f(z) // // -div(flux_R) == termR1 + termR2 // // termR1 == 1/p^2 d/dp p^2 gamma(p) p / tau f(p) * (1-z^2) * f(z) // termR2 == -1/(tau*gam(p)) f(p) * d/dz z(1-z^2) f(z) // --------------------------------------------------------------------------- template<typename P> class PDE_fokkerplanck_2d_complete : public PDE<P> { public: PDE_fokkerplanck_2d_complete(int const num_levels = -1, int const degree = -1) : PDE<P>(num_levels, degree, num_dims_, num_sources_, num_terms_, dimensions_, terms_, sources_, exact_vector_funcs_, exact_scalar_func_, get_dt_, do_poisson_solve_, has_analytic_soln_) {} private: // these fields will be checked against provided functions to make sure // everything is specified correctly static int constexpr num_dims_ = 2; static int constexpr num_sources_ = 0; static int constexpr num_terms_ = 7; static bool constexpr do_poisson_solve_ = false; static bool constexpr has_analytic_soln_ = false; // ------------------------------------------------ // // define constants / data / functions for this PDE // // ------------------------------------------------ static auto constexpr phi = [](P x) { return std::erf(x); }; static auto constexpr psi = [](P x) { auto dphi_dx = 2.0 / std::sqrt(M_PI) * std::exp(-std::pow(x, 2)); auto ret = 1.0 / (2 * std::pow(x, 2)) * (phi(x) - x * dphi_dx); if (x < 1e-5) ret = 0; return ret; }; static P constexpr nuEE = 1; static P constexpr vT = 1; static P constexpr delta = 0.042; static P constexpr Z = 1; static P constexpr E = 0.0025; static P constexpr tau = 1e5; static auto constexpr gamma = [](P p) { return std::sqrt(1 + std::pow(delta * p, 2)); }; static auto constexpr vx = [](P p) { return 1.0 / vT * (p / gamma(p)); }; static auto constexpr Ca = [](P p) { return nuEE * std::pow(vT, 2) * (psi(vx(p)) / vx(p)); }; static auto constexpr Cb = [](P p) { return 1.0 / 2.0 * nuEE * std::pow(vT, 2) * 1.0 / vx(p) * (Z + phi(vx(p)) - psi(vx(p)) + std::pow(delta, 4) * std::pow(vx(p), 2) / 2.0); }; static auto constexpr Cf = [](P p) { return 2.0 * nuEE * vT * psi(vx(p)); }; // ----------------- // // define dimensions // // ----------------- // specify initial conditions for each dim // p dimension // initial condition in p static fk::vector<P> initial_condition_p(fk::vector<P> const x, P const t = 0) { ignore(t); fk::vector<P> ret(x.size()); std::transform(x.begin(), x.end(), ret.begin(), [](auto const elem) { P const a = 2; return 2.0 / (std::sqrt(M_PI) * std::pow(a, 3)) * std::exp(-std::pow(elem, 2) / std::pow(a, 2)); }); return ret; } // initial conditionn in z static fk::vector<P> initial_condition_z(fk::vector<P> const x, P const t = 0) { ignore(t); fk::vector<P> ret(x.size()); std::fill(ret.begin(), ret.end(), 1.0); return ret; } // p dimension inline static dimension<P> const dim_p = dimension<P>(0.0, // domain min 10.0, // domain max 2, // levels 2, // degree initial_condition_p, // initial condition "p"); // name // z dimension inline static dimension<P> const dim_z = dimension<P>(-1.0, // domain min +1.0, // domain max 2, // levels 2, // degree initial_condition_z, // initial condition "z"); // name // assemble dimensions inline static std::vector<dimension<P>> const dimensions_ = {dim_p, dim_z}; // ---------------------------------------- // // Setup the terms of the PDE // // -div(flux_C) == termC1 + termC2 + termC3 // // ---------------------------------------- // create a default mass matrix static P gI(P const x, P const time = 0) { ignore(x); ignore(time); return 1.0; } inline static partial_term<P> const pterm_I = partial_term<P>(coefficient_type::mass, gI); inline static term<P> const I_ = term<P>(false, // time-dependent fk::vector<P>(), // additional data vector "massY", // name dim_p, // owning dim {pterm_I}); // termC1 == 1/p^2*d/dp*p^2*Ca*df/dp // // // becomes // // termC1 == g1(p) q(p) [mass, g1(p) = 1/p^2, BC N/A] // q(p) == d/dp g2(p) r(p) [grad, g2(p) = p^2*Ca, BCL=D,BCR=N] // r(p) == d/dp g3(p) f(p) [grad, g3(p) = 1, BCL=N,BCR=D] static P c1_g1(P const x, P const time = 0) { ignore(time); return 1.0 / std::pow(x, 2); } static P c1_g2(P const x, P const time = 0) { ignore(time); return std::pow(x, 2) * Ca(x); } static P c1_g3(P const x, P const time = 0) { ignore(x); ignore(time); return 1.0; } // 1. create partial_terms inline static partial_term<P> const c1_pterm1 = partial_term<P>(coefficient_type::mass, c1_g1); inline static partial_term<P> const c1_pterm2 = partial_term<P>( coefficient_type::grad, c1_g2, flux_type::upwind, boundary_condition::dirichlet, boundary_condition::neumann); inline static partial_term<P> const c1_pterm3 = partial_term<P>( coefficient_type::grad, c1_g3, flux_type::downwind, boundary_condition::neumann, boundary_condition::dirichlet); // 2. combine partial terms into single dimension term inline static term<P> const c1_term_p = term<P>(false, // time-dependent fk::vector<P>(), // additional data vector "C1_p", // name dim_p, // owning dim {c1_pterm1, c1_pterm2, c1_pterm3}); // 3. combine single dimension terms into multi dimension term inline static std::vector<term<P>> const termC1 = {c1_term_p, I_}; // termC2 == 1/p^2*d/dp*p^2*Cf*f // // becomes // // termC2 == g1(p) q(p) [mass, g1(p)=1/p^2, BC N/A] // q(p) == d/dp g2(p) f(p) [grad, g2(p)=p^2*Cf, BCL=N,BCR=D] static P c2_g1(P const x, P const time = 0) { ignore(time); return 1.0 / std::pow(x, 2); } static P c2_g2(P const x, P const time = 0) { ignore(time); return std::pow(x, 2) * Cf(x); } // 1. create partial_terms inline static partial_term<P> const c2_pterm1 = partial_term<P>(coefficient_type::mass, c2_g1); inline static partial_term<P> const c2_pterm2 = partial_term<P>( coefficient_type::grad, c2_g2, flux_type::upwind, boundary_condition::neumann, boundary_condition::dirichlet); // 2. combine partial terms into single dimension term inline static term<P> const c2_term_p = term<P>(false, // time-dependent fk::vector<P>(), // additional data vector "C2_p", // name dim_p, // owning dim {c2_pterm1, c2_pterm2}); // 3. combine single dimension terms into multi dimension term inline static std::vector<term<P>> const termC2 = {c2_term_p, I_}; // termC3 == Cb(p)/p^4 * d/dz( (1-z^2) * df/dz ) // // becomes // // termC3 == q(p) r(z) // q(p) == g1(p) [mass, g1(p) = Cb(p)/p^4, BC N/A] // r(z) == d/dz g2(z) s(z) [grad, g2(z) = 1-z^2, BCL=D,BCR=D] // s(z) == d/dz g3(z) f(z) [grad, g3(z) = 1, BCL=N,BCR=N] static P c3_g1(P const x, P const time = 0) { ignore(time); return Cb(x) / std::pow(x, 4); } static P c3_g2(P const x, P const time = 0) { ignore(time); return 1.0 - std::pow(x, 2); } static P c3_g3(P const x, P const time = 0) { ignore(x); ignore(time); return 1.0; } // 1. create partial_terms inline static partial_term<P> const c3_pterm1 = partial_term<P>(coefficient_type::mass, c3_g1); inline static partial_term<P> const c3_pterm2 = partial_term<P>( coefficient_type::grad, c3_g2, flux_type::upwind, boundary_condition::dirichlet, boundary_condition::dirichlet); inline static partial_term<P> const c3_pterm3 = partial_term<P>(coefficient_type::grad, c3_g3, flux_type::downwind, boundary_condition::neumann, boundary_condition::neumann); // 2. combine partial terms into single dimension term inline static term<P> const c3_term_p = term<P>(false, // time-dependent fk::vector<P>(), // additional data vector "C3_p", // name dim_p, // owning dim {c3_pterm1}); inline static term<P> const c3_term_z = term<P>(false, // time-dependent fk::vector<P>(), // additional data vector "C3_z", // name dim_p, // owning dim {c3_pterm2, c3_pterm3}); // 3. combine single dimension terms into multi dimension term inline static std::vector<term<P>> const termC3 = {c3_term_p, c3_term_z}; // -div(flux_E) == termE1 + termE2 // termE1 == -E*z*f(z) * 1/p^2 (d/dp p^2 f(p)) // == r(z) * q(p) // r(z) == g1(z) f(z) [mass, g1(z) = -E*z, BC N/A] // q(p) == g2(p) u(p) [mass, g2(p) = 1/p^2, BC N/A] // u(p) == d/dp g3(p) f(p) [grad, g3(p) = p^2, BCL=N,BCR=D] static P e1_g1(P const x, P const time = 0) { ignore(time); return -E * x; } static P e1_g2(P const x, P const time = 0) { ignore(time); assert(x > 0); return 1.0 / std::pow(x, 2); } static P e1_g3(P const x, P const time = 0) { ignore(time); return std::pow(x, 2); } // 1. create partial_terms inline static partial_term<P> const e1_pterm1 = partial_term<P>(coefficient_type::mass, e1_g1); inline static partial_term<P> const e1_pterm2 = partial_term<P>(coefficient_type::mass, e1_g2); inline static partial_term<P> const e1_pterm3 = partial_term<P>( coefficient_type::grad, e1_g3, flux_type::upwind, boundary_condition::neumann, boundary_condition::dirichlet); // 2. combine partial terms into single dimension term inline static term<P> const e1_term_p = term<P>(false, // time-dependent fk::vector<P>(), // additional data vector "E1_p", // name dim_p, // owning dim {e1_pterm2, e1_pterm3}); inline static term<P> const e1_term_z = term<P>(false, // time-dependent fk::vector<P>(), // additional data vector "E1_z", // name dim_p, // owning dim {e1_pterm1}); // 3. combine single dimension terms into multi dimension term inline static std::vector<term<P>> const termE1 = {e1_term_p, e1_term_z}; // termE2 == -E*p*f(p) * d/dz (1-z^2) f(z) // == q(p) * r(z) // q(p) == g1(p) f(p) [mass, g1(p) = -E*p, BC N/A] // r(z) == d/dz g2(z) f(z) [grad, g2(z) = 1-z^2, BCL=N,BCR=N] static P e2_g1(P const x, P const time = 0) { ignore(time); return -E * x; } static P e2_g2(P const x, P const time = 0) { ignore(time); return 1.0 - std::pow(x, 2); } // 1. create partial_terms inline static partial_term<P> const e2_pterm1 = partial_term<P>(coefficient_type::mass, e2_g1); inline static partial_term<P> const e2_pterm2 = partial_term<P>(coefficient_type::grad, e2_g2, flux_type::central, boundary_condition::neumann, boundary_condition::neumann); // 2. combine partial terms into single dimension term inline static term<P> const e2_term_p = term<P>(false, // time-dependent fk::vector<P>(), // additional data vector "E2_p", // name dim_p, // owning dim {e2_pterm1}); inline static term<P> const e2_term_z = term<P>(false, // time-dependent fk::vector<P>(), // additional data vector "E2_z", // name dim_p, // owning dim {e2_pterm2}); // 3. combine single dimension terms into multi dimension term inline static std::vector<term<P>> const termE2 = {e2_term_p, e2_term_z}; // -div(flux_R) == termR1 + termR2 // clang-format off // // termR1 == 1/p^2 d/dp p^2 gamma(p) p / tau f(p) * (1-z^2) * f(z) // == q(p) * r(z) // q(p) == g1(p) u(p) [mass, g1(p) = 1/p^2, BC N/A] // u(p) == d/dp g2(p) f(p) [grad, g2(p) = p^3 * gamma(p) / tau, BCL=N,BCR=D] // r(z) == g3(z) f(z) [mass, g3(z) = 1-z^2, BC N/A] // // clang-format on static P r1_g1(P const x, P const time = 0) { ignore(time); return 1.0 / std::pow(x, 2); } static P r1_g2(P const x, P const time = 0) { ignore(time); return std::pow(x, 3) * gamma(x) / tau; } static P r1_g3(P const x, P const time = 0) { ignore(time); return 1.0 - std::pow(x, 2); } // 1. create partial_terms inline static partial_term<P> const r1_pterm1 = partial_term<P>(coefficient_type::mass, r1_g1); inline static partial_term<P> const r1_pterm2 = partial_term<P>( coefficient_type::grad, r1_g2, flux_type::upwind, boundary_condition::neumann, boundary_condition::dirichlet); inline static partial_term<P> const r1_pterm3 = partial_term<P>(coefficient_type::mass, r1_g3); // 2. combine partial terms into single dimension term inline static term<P> const r1_term_p = term<P>(false, // time-dependent fk::vector<P>(), // additional data vector "R1_p", // name dim_p, // owning dim {r1_pterm1, r1_pterm2}); inline static term<P> const r1_term_z = term<P>(false, // time-dependent fk::vector<P>(), // additional data vector "R1_z", // name dim_p, // owning dim {r1_pterm3}); // 3. combine single dimension terms into multi dimension term inline static std::vector<term<P>> const termR1 = {r1_term_p, r1_term_z}; // clang-format off // // termR2 == -1/(tau*gam(p)) f(p) * d/dz z(1-z^2) f(z) // == q(p) * r(z) // q(p) == g1(p) f(p) [mass, g1(p) = -1/(tau*gamma(p)), BC N/A] // r(z) == d/dz g2(z) f(z) [grad, g2(z) = z(1-z^2), BCL=N,BCR=N] // // clang-format on static P r2_g1(P const x, P const time = 0) { ignore(time); return -1.0 / (tau * gamma(x)); } static P r2_g2(P const x, P const time = 0) { ignore(time); return x * (1.0 - std::pow(x, 2)); } // 1. create partial_terms inline static partial_term<P> const r2_pterm1 = partial_term<P>(coefficient_type::mass, r2_g1); inline static partial_term<P> const r2_pterm2 = partial_term<P>(coefficient_type::grad, r2_g2, flux_type::central, boundary_condition::neumann, boundary_condition::neumann); // 2. combine partial terms into single dimension term inline static term<P> const r2_term_p = term<P>(false, // time-dependent fk::vector<P>(), // additional data vector "R2_p", // name dim_p, // owning dim {r2_pterm1}); inline static term<P> const r2_term_z = term<P>(false, // time-dependent fk::vector<P>(), // additional data vector "R2_z", // name dim_p, // owning dim {r2_pterm2}); // 3. combine single dimension terms into multi dimension term inline static std::vector<term<P>> const termR2 = {r2_term_p, r2_term_z}; // collect all the terms inline static term_set<P> const terms_ = {termC1, termC2, termC3, termE1, termE2, termR1, termR2}; // -------------- // // define sources // // -------------- inline static std::vector<source<P>> const sources_ = {}; // ------------------ // // get time step (dt) // // ------------------ static P get_dt_(dimension<P> const &dim) { P const x_range = dim.domain_max - dim.domain_min; P const dx = x_range / std::pow(2, dim.get_level()); P const dt = dx; // this will be scaled by CFL from command line return dt; } // ------------------------------------------------- // // define exact soln functions (unused for this PDE) // // ------------------------------------------------- inline static std::vector<vector_func<P>> const exact_vector_funcs_ = {}; inline static scalar_func<P> const exact_scalar_func_ = {}; };
true
851840f81d1761a3bea66f25b82b953b0064d797
C++
namlunthkl/team4-trynity
/Aeona Sprint 2/Aeona Project/source/Light System/LightEngine.h
UTF-8
9,122
2.828125
3
[]
no_license
#ifndef LIGHTENGINE_H_ #define LIGHTENGINE_H_ class LightEngine { private: // CURRENT CYCLE enum CYCLE{ MORNING = 1, AFTERNOON, DAY, EVENING, DUSK, NIGHT, DAWN }; // SOUND int m_nDay_AirBed; int m_nNight_AirBed; int m_sCurrentCycle; float m_fCurrentLTime; float m_fTimeToWait; // AMBIENT LIGHT float m_fAmbientAlpha; float m_fAmbientRed; float m_fAmbientGeen; float m_fAmbientBlue; // PLAYER POINT LIGHT bool m_bPlayerPointLight; float m_fPlayerPointAlpha; float m_fPlayerPointRed; float m_fPlayerPointGeen; float m_fPlayerPointBlue; float m_fPlayerPointPosX; float m_fPlayerPointPosY; // ITEM 1 POINT LIGHT bool m_bItem1PointLight; float m_fItem1PointAlpha; float m_fItem1PointRed; float m_fItem1PointGeen; float m_fItem1PointBlue; float m_fItem1PointPosX; float m_fItem1PointPosY; // ITEM 2 POINT LIGHT bool m_bItem2PointLight; float m_fItem2PointAlpha; float m_fItem2PointRed; float m_fItem2PointGeen; float m_fItem2PointBlue; float m_fItem2PointPosX; float m_fItem2PointPosY; // ITEM 3 POINT LIGHT bool m_bItem3PointLight; float m_fItem3PointAlpha; float m_fItem3PointRed; float m_fItem3PointGeen; float m_fItem3PointBlue; float m_fItem3PointPosX; float m_fItem3PointPosY; // ITEM 4 POINT LIGHT bool m_bItem4PointLight; float m_fItem4PointAlpha; float m_fItem4PointRed; float m_fItem4PointGeen; float m_fItem4PointBlue; float m_fItem4PointPosX; float m_fItem4PointPosY; // PLAYER POINT LIGHT float m_fPlayerPointRadius; // ITEMS POINT LIGHT float m_fItemPointRadius; LightEngine(void); LightEngine(const LightEngine&){} LightEngine& operator=(const LightEngine&){} ~LightEngine(void); public: static LightEngine* GetInstance(void); // CYCLE void SetCurrentCycle( int cycle ) { m_sCurrentCycle = cycle; } int GetCurrentCycle(void) { return m_sCurrentCycle; } void SetCurrentLTime( float fTime ) { m_fCurrentLTime = fTime; } float GetCurrentLTime(void) { return m_fCurrentLTime; } void SetTimeToWait( float fTimeToWait ) { m_fTimeToWait = fTimeToWait; } float GetTimeToWait(void) { return m_fTimeToWait; } //AMBIENT LIGHT void SetAmbientAlpha( float fAmbientAlpha ) { m_fAmbientAlpha = fAmbientAlpha; } void SetAmbientRed( float fAmbientRed ) { m_fAmbientRed = fAmbientRed; } void SetAmbientGreen( float fAmbientGreen ) { m_fAmbientGeen = fAmbientGreen; } void SetAmbientBlue(float fAmbientBlue ) { m_fAmbientBlue = fAmbientBlue; } float GetAmbientAlpha(void) { return m_fAmbientAlpha; } float GetAmbientRed(void) { return m_fAmbientRed; } float GetAmbientGreen(void) { return m_fAmbientGeen; } float GetAmbientBlue(void) { return m_fAmbientBlue; } //PLAYER POINT LIGHT void SetPlayerPointLight( bool bPlayerPoint) { m_bPlayerPointLight = bPlayerPoint; } void SetPlayerPointAlpha( float fPointAlpha ) { m_fPlayerPointAlpha = fPointAlpha; } void SetPlayerPointRed( float fPointRed ) { m_fPlayerPointRed = fPointRed; } void SetPlayerPointGreen( float fPointGreen ) { m_fPlayerPointGeen = fPointGreen; } void SetPlayerPointBlue( float fPointBlue ) { m_fPlayerPointBlue = fPointBlue; } void SetPlayerPointPosX( float fPlayerPosX ) { m_fPlayerPointPosX = fPlayerPosX; } void SetPlayerPointPosY( float fPlayerPosY ) { m_fPlayerPointPosY = fPlayerPosY; } bool GetPlayerPointLight(void) { return m_bPlayerPointLight; } float GetPlayerPointAlpha(void) { return m_fPlayerPointAlpha; } float GetPlayerPointRed(void) { return m_fPlayerPointRed; } float GetPlayerPointGreen(void) { return m_fPlayerPointGeen; } float GetPlayerPointBlue(void) { return m_fPlayerPointBlue; } float GetPlayerPointPosX(void) { return m_fPlayerPointPosX; } float GetPlayerPointPosY(void) { return m_fPlayerPointPosY; } //ITEM1 POINT LIGHT void SetItem1PointLight( bool bItem1Point) { m_bItem1PointLight = bItem1Point; } void SetItem1PointAlpha( float fPointAlpha ) { m_fItem1PointAlpha = fPointAlpha; } void SetItem1PointRed( float fPointRed ) { m_fItem1PointRed = fPointRed; } void SetItem1PointGreen( float fPointGreen ) { m_fItem1PointGeen = fPointGreen; } void SetItem1PointBlue( float fPointBlue ) { m_fItem1PointBlue = fPointBlue; } void SetItem1PointPosX( float fItem1PosX ) { m_fItem1PointPosX = fItem1PosX; } void SetItem1PointPosY( float fItem1PosY ) { m_fItem1PointPosY = fItem1PosY; } bool GetItem1PointLight(void) { return m_bItem1PointLight; } float GetItem1PointAlpha(void) { return m_fItem1PointAlpha; } float GetItem1PointRed(void) { return m_fItem1PointRed; } float GetItem1PointGreen(void) { return m_fItem1PointGeen; } float GetItem1PointBlue(void) { return m_fItem1PointBlue; } float GetItem1PointPosX(void) { return m_fItem1PointPosX; } float GetItem1PointPosY(void) { return m_fItem1PointPosY; } //ITEM2 POINT LIGHT void SetItem2PointLight( bool bItem2Point) { m_bItem2PointLight = bItem2Point; } void SetItem2PointAlpha( float fPointAlpha ) { m_fItem2PointAlpha = fPointAlpha; } void SetItem2PointRed( float fPointRed ) { m_fItem2PointRed = fPointRed; } void SetItem2PointGreen( float fPointGreen ) { m_fItem2PointGeen = fPointGreen; } void SetItem2PointBlue( float fPointBlue ) { m_fItem2PointBlue = fPointBlue; } void SetItem2PointPosX( float fItem2PosX ) { m_fItem2PointPosX = fItem2PosX; } void SetItem2PointPosY( float fItem2PosY ) { m_fItem2PointPosY = fItem2PosY; } bool GetItem2PointLight(void) { return m_bItem2PointLight; } float GetItem2PointAlpha(void) { return m_fItem2PointAlpha; } float GetItem2PointRed(void) { return m_fItem2PointRed; } float GetItem2PointGreen(void) { return m_fItem2PointGeen; } float GetItem2PointBlue(void) { return m_fItem2PointBlue; } float GetItem2PointPosX(void) { return m_fItem2PointPosX; } float GetItem2PointPosY(void) { return m_fItem2PointPosY; } //ITEM3 POINT LIGHT void SetItem3PointLight( bool bItem3Point) { m_bItem3PointLight = bItem3Point; } void SetItem3PointAlpha( float fPointAlpha ) { m_fItem3PointAlpha = fPointAlpha; } void SetItem3PointRed( float fPointRed ) { m_fItem3PointRed = fPointRed; } void SetItem3PointGreen( float fPointGreen ) { m_fItem3PointGeen = fPointGreen; } void SetItem3PointBlue( float fPointBlue ) { m_fItem3PointBlue = fPointBlue; } void SetItem3PointPosX( float fItem3PosX ) { m_fItem3PointPosX = fItem3PosX; } void SetItem3PointPosY( float fItem3PosY ) { m_fItem3PointPosY = fItem3PosY; } bool GetItem3PointLight(void) { return m_bItem3PointLight; } float GetItem3PointAlpha(void) { return m_fItem3PointAlpha; } float GetItem3PointRed(void) { return m_fItem3PointRed; } float GetItem3PointGreen(void) { return m_fItem3PointGeen; } float GetItem3PointBlue(void) { return m_fItem3PointBlue; } float GetItem3PointPosX(void) { return m_fItem3PointPosX; } float GetItem3PointPosY(void) { return m_fItem3PointPosY; } //ITEM4 POINT LIGHT void SetItem4PointLight( bool bItem4Point) { m_bItem4PointLight = bItem4Point; } void SetItem4PointAlpha( float fPointAlpha ) { m_fItem4PointAlpha = fPointAlpha; } void SetItem4PointRed( float fPointRed ) { m_fItem4PointRed = fPointRed; } void SetItem4PointGreen( float fPointGreen ) { m_fItem4PointGeen = fPointGreen; } void SetItem4PointBlue( float fPointBlue ) { m_fItem4PointBlue = fPointBlue; } void SetItem4PointPosX( float fItem4PosX ) { m_fItem4PointPosX = fItem4PosX; } void SetItem4PointPosY( float fItem4PosY ) { m_fItem4PointPosY = fItem4PosY; } bool GetItem4PointLight(void) { return m_bItem4PointLight; } float GetItem4PointAlpha(void) { return m_fItem4PointAlpha; } float GetItem4PointRed(void) { return m_fItem4PointRed; } float GetItem4PointGreen(void) { return m_fItem4PointGeen; } float GetItem4PointBlue(void) { return m_fItem4PointBlue; } float GetItem4PointPosX(void) { return m_fItem4PointPosX; } float GetItem4PointPosY(void) { return m_fItem4PointPosY; } // PLAYER POINT LIGHT void SetPointRadius( float bPointRadius) { m_fPlayerPointRadius = bPointRadius; } float GetPointRadius(void) { return m_fPlayerPointRadius; } // ITEMS POINT LIGHT void SetItemRadius( float bItemRadius) { m_fItemPointRadius = bItemRadius; } float GetItemRadius(void) { return m_fItemPointRadius; } void Initialize( void ); void Update( float fElapsedTime ); void Input( void ); void ShutDown( void ); void SetPlayerPointPos( float fPosX, float fPosY ); void SetItem1PointPos( float fPosX, float fPosY ); void SetItem2PointPos( float fPosX, float fPosY ); void SetItem3PointPos( float fPosX, float fPosY ); void SetItem4PointPos( float fPosX, float fPosY ); void Flicker(void); void Morning( void ); void Afternoon( void ); void Day( void ); void Evening( void ); void Dusk( void ); void Night( void ); void Dawn( void ); void DayNightCycle( void ); }; #endif
true
3267146bfaffa44f490d6c851f51ab9fe40d53d4
C++
Toxe/test-cpp
/src/chrono_time_point.cpp
UTF-8
2,603
3.734375
4
[ "MIT" ]
permissive
#include <chrono> #include <ctime> #include <iomanip> #include <iostream> using namespace std::literals::chrono_literals; void output_tp_seconds(const std::chrono::time_point<std::chrono::system_clock, std::chrono::seconds> tp) { const std::time_t tc = std::chrono::system_clock::to_time_t(tp); std::cout << tp.time_since_epoch().count() << "s = " << std::put_time(std::localtime(&tc), "%F %T") << '\n'; } void output_tp_hours(const std::chrono::time_point<std::chrono::system_clock, std::chrono::hours> tp) { const std::time_t tc = std::chrono::system_clock::to_time_t(tp); std::cout << tp.time_since_epoch().count() << "h = " << std::put_time(std::localtime(&tc), "%F %T") << '\n'; } void output_hours(const std::chrono::hours dur) { std::cout << dur << '\n'; } void conversion() { const std::chrono::time_point<std::chrono::system_clock, std::chrono::seconds> tp_seconds1{5000s}; // seconds const std::chrono::time_point<std::chrono::system_clock, std::chrono::seconds> tp_seconds2{5000h}; // hours to seconds output_tp_seconds(tp_seconds1); // 5000s = 1970-01-01 02:23:20 output_tp_seconds(tp_seconds2); // 18000000s = 1970-07-28 10:00:00 const std::chrono::time_point<std::chrono::system_clock, std::chrono::hours> tp_hours1{5000h}; // hours output_tp_seconds(tp_hours1); // 18000000s = 1970-07-28 10:00:00 output_tp_hours(tp_hours1); // 5000h = 1970-07-28 10:00:00 const std::chrono::time_point<std::chrono::system_clock, std::chrono::hours> tp_hours2{}; output_tp_hours(tp_hours2); // 0h = 1970-01-01 01:00:00 // const std::chrono::time_point<std::chrono::system_clock, std::chrono::hours> tp_hours2{3600s}; // error: no loss-less conversion possible } void arithmetic() { const std::chrono::time_point<std::chrono::system_clock, std::chrono::hours> tp1{5000h}; const std::chrono::time_point<std::chrono::system_clock, std::chrono::hours> tp2{6000h}; // subtraction: time_point - time_point --> duration (std::chrono::hours) output_hours(tp2 - tp1); // 1000h // addition/subtraction: time_point +/- duration --> time_point output_tp_hours(tp1 + 24h); // 1970-07-29 10:00:00 output_tp_hours(tp1 - 24h); // 1970-07-27 10:00:00 // auto foo = tp1 + tp2; // error, addition of time_points is not allowed } void to_duration() { const std::chrono::time_point<std::chrono::system_clock, std::chrono::hours> tp{10h}; const std::chrono::hours dur = tp.time_since_epoch(); output_hours(dur); // 10h } int main() { conversion(); arithmetic(); to_duration(); }
true
695351cd3191dc1ef47044e6fa0a9aa990d89c0b
C++
mxm001/UNLaM
/Programacion Basica I/clase 7/clase7-1.cpp
UTF-8
922
3.53125
4
[]
no_license
#include<stdio.h> #include<conio.h> /* ct= Contador total, El bucle va 10 veces xq el interior va 5 (5*10) Siempre al final resetea suma5. suma5=Guarda el resultado de las sumas de los 5 numeros del for interno. Al salir de ese bucle se vuelve a igualar a 0. num=Guarda el numero ingresado. Suma=La suma de todos los numeros. cn= Contador parcial, regula el bucle interno para que solo corra 5 veces, antes de salir para resetearse 'suma5'. */ main() { int cn=1,ct=1,num=0,suma5=0,suma=0; for(ct=1;ct<=10;ct++) { for(cn=1;cn<=5;cn++) { printf("\nIngrese un numero: "); scanf("%d",&num); suma5=suma5+num; } printf("\n--------------------"); printf("\nLa suma de los 5 numeros anteriores es %d.",suma5); printf("\n--------------------"); suma=suma+suma5; suma5=0; } printf("\nLa suma de todos los numeros es de %d.",suma); printf("\n--------------------"); getch(); return(1); }
true
e740f8074610179fe1cc0029e60a04ef74e27186
C++
yashparmar15/Cpp-Codes
/3Sum.cpp
UTF-8
1,513
3.03125
3
[]
no_license
// Given an array nums of n integers, are there elements a, b, c in nums such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero. // Note: // The solution set must not contain duplicate triplets. // Example: // Given array nums = [-1, 0, 1, 2, -1, -4], // A solution set is: // [ // [-1, 0, 1], // [-1, -1, 2] // ] class Solution { public: vector<vector<int>> threeSum(vector<int>& v) { vector<vector<int>> ans; map<vector<int>,int> M; int N = v.size(); sort(v.begin(),v.end()); for(int i = 0 ; i < N - 2 ; i++){ if(i == 0 or v[i] != v[i-1]){ int left = i + 1; int right = N - 1; while(left < right){ int Sum = v[i] + v[right] + v[left]; if(Sum == 0){ vector<int> a; a.push_back(v[i]); a.push_back(v[left]); a.push_back(v[right]); if(M.count(a) == 0){ ans.push_back(a); M[a] = 1; } } if(Sum > 0){ right --; } else{ left ++; } } } } return ans; } };
true
d299f76c99b0246308881d8fa8b501469b469b81
C++
StanfordAHA/Halide-to-Hardware
/test/correctness/debug_to_file_multiple_outputs.cpp
UTF-8
3,508
2.59375
3
[ "MIT" ]
permissive
#include "Halide.h" #include <stdio.h> #include "test/common/halide_test_dirs.h" using namespace Halide; int main(int argc, char **argv) { const int size_x = 766; const int size_y = 311; std::string f_tmp = Internal::get_test_tmp_dir() + "f3.tmp"; std::string g_tmp = Internal::get_test_tmp_dir() + "g3.tmp"; std::string h_tmp = Internal::get_test_tmp_dir() + "h3.tmp"; Internal::ensure_no_file_exists(f_tmp); Internal::ensure_no_file_exists(g_tmp); Internal::ensure_no_file_exists(h_tmp); { Func f, g, h, j; Var x, y; f(x, y) = x + y; g(x, y) = cast<float>(f(x, y) + f(x + 1, y)); h(x, y) = f(x, y) + g(x, y); f.compute_root().debug_to_file(f_tmp); g.compute_root().debug_to_file(g_tmp); h.compute_root().debug_to_file(h_tmp); Pipeline p({f, g, h}); Buffer<int> f_im(size_x + 1, size_y); Buffer<float> g_im(size_x, size_y), h_im(size_x, size_y); Realization r(f_im, g_im, h_im); p.realize(r); } Internal::assert_file_exists(f_tmp); Internal::assert_file_exists(g_tmp); Internal::assert_file_exists(h_tmp); FILE *f = fopen(f_tmp.c_str(), "rb"); FILE *g = fopen(g_tmp.c_str(), "rb"); FILE *h = fopen(h_tmp.c_str(), "rb"); assert(f && g && h); int header[5]; assert(fread((void *)(&header[0]), 4, 5, f) == 5); assert(header[0] == size_x+1); assert(header[1] == size_y); assert(header[2] == 1); assert(header[3] == 1); assert(header[4] == 7); std::vector<int32_t> f_data((size_x + 1)*size_y); assert(fread((void *)(&f_data[0]), 4, (size_x+1)*size_y, f) == (size_x+1)*size_y); for (int y = 0; y < size_y; y++) { for (int x = 0; x < size_x+1; x++) { int32_t val = f_data[y*(size_x+1)+x]; if (val != x+y) { printf("f_data[%d, %d] = %d instead of %d\n", x, y, val, x+y); return -1; } } } fclose(f); assert(fread((void *)(&header[0]), 4, 5, g) == 5); assert(header[0] == size_x); assert(header[1] == size_y); assert(header[2] == 1); assert(header[3] == 1); assert(header[4] == 0); std::vector<float> g_data(size_x*size_y); assert(fread((void *)(&g_data[0]), 4, size_x*size_y, g) == size_x*size_y); for (int y = 0; y < size_y; y++) { for (int x = 0; x < size_x; x++) { float val = g_data[y*size_x+x]; float correct = (float)(f_data[y*(size_x+1)+x] + f_data[y*(size_x+1)+x+1]); if (val != correct) { printf("g_data[%d, %d] = %f instead of %f\n", x, y, val, correct); return -1; } } } fclose(g); assert(fread((void *)(&header[0]), 4, 5, h) == 5); assert(header[0] == size_x); assert(header[1] == size_y); assert(header[2] == 1); assert(header[3] == 1); assert(header[4] == 0); std::vector<float> h_data(size_x*size_y); assert(fread((void *)(&h_data[0]), 4, size_x*size_y, h) == size_x*size_y); for (int y = 0; y < size_y; y++) { for (int x = 0; x < size_x; x++) { float val = h_data[y*size_x+x]; float correct = f_data[y*(size_x+1)+x] + g_data[y*size_x+x]; if (val != correct) { printf("h_data[%d, %d] = %f instead of %f\n", x, y, val, correct); return -1; } } } fclose(h); printf("Success!\n"); return 0; }
true
0c7d82dfc8e60d3cfa61a56f9ae5bacad75633c5
C++
ShadiHelf950/OpenGL3D
/OpenGL3D/Light.h
UTF-8
1,036
2.921875
3
[]
no_license
#pragma once #include<iostream> #include<fstream> #include<string> #include<glew.h> #include<glfw3.h> #include<glm.hpp> #include<vec2.hpp> #include<vec3.hpp> #include<vec4.hpp> #include<mat4x4.hpp> #include<gtc\type_ptr.hpp> class Light { public: Light(std::string t, glm::vec3 pos, glm::vec3 a, glm::vec3 d, glm::vec3 s) { type = t; // parallel or point light position = pos; ambient = a; diffuse = d; specular = s; transformations = glm::mat4(1.0f); } void SetTransformations(glm::mat4& T) { transformations = T; } const glm::vec3 GetAmbient() const { return ambient; } const glm::vec3 GetDiffuse() const { return diffuse; } const glm::vec3 GetSpecular() const { return specular; } const glm::vec3 GetPosition() const { return position; } const glm::mat4 GetTransformations() const { return transformations; } std::string GetType() const { return type; } private: std::string type; glm::mat4 transformations; glm::vec3 position; glm::vec3 ambient; glm::vec3 diffuse; glm::vec3 specular; };
true
7a8a1b6bbd48c1f57f025c55073f4c0e6bb0bd56
C++
orangeate/webserver
/threadpool/thread_pool.h
UTF-8
3,154
3.359375
3
[]
no_license
#ifndef THREAD_POOL_H #define THREAD_POOL_H #include <list> #include <cstdio> #include <exception> #include <pthread.h> #include <vector> #include "../lock/lock.h" template <typename T> class ThreadPool { public: ThreadPool(int thread_number = 8, int max_request = 10000); ~ThreadPool(); bool append(T *request, int state); private: /* 工作线程运行的函数 */ static void *worker(void *arg); void run(); private: pthread_t *p_threads_; //描述线程池的数组 int thread_number_; //线程池中的线程数 std::list<T *> request_queue_; //请求队列 int max_request_; //请求队列中允许的最大请求数 Mutex mutex_; //保护请求队列的互斥锁 Semaphore sem_; //是否有任务需要处理 bool stop_; //是否结束线程 }; /* 线程池大小 创建线程池 请求队列大小 */ template <typename T> ThreadPool<T>::ThreadPool(int thread_number, int max_requests): thread_number_(thread_number), max_request_(max_requests) { stop_ = false; p_threads_ = nullptr; if (thread_number_ <= 0 || max_request_ <= 0) throw std::exception(); p_threads_ = new pthread_t[thread_number_]; if (!p_threads_) throw std::exception(); // 创建 thread_number 个线程 for (int i = 0; i < thread_number; ++i) { // 创建线程 if (pthread_create(p_threads_ + i, NULL, worker, this) != 0) { delete[] p_threads_; throw std::exception(); } // 分离线程 if (pthread_detach(p_threads_[i])) { delete[] p_threads_; throw std::exception(); } } } template <typename T> ThreadPool<T>::~ThreadPool() { // 销毁线程池 delete[] p_threads_; stop_ = true; } template <typename T> void *ThreadPool<T>::worker(void *arg) { // 执行任务 ThreadPool *pool = (ThreadPool *)arg; pool->run(); return pool; } template <typename T> void ThreadPool<T>::run() { while (!stop_) { sem_.wait(); mutex_.lock(); if (request_queue_.empty()) { mutex_.unlock(); continue; } T *request = request_queue_.front(); request_queue_.pop_front(); mutex_.unlock(); if (!request) continue; // 处理读 if (request->state_ == 0) { request->process_read(); } // 处理写 else if(request->state_ == 1) { request->process_write(); } else { continue; } } } template <typename T> bool ThreadPool<T>::append(T *request, int state) { mutex_.lock(); // 请求队列满 if (request_queue_.size() > max_request_) { mutex_.unlock(); return false; } request->state_ = state; request_queue_.push_back(request); mutex_.unlock(); sem_.post(); return true; } #endif //THREAD_POOL_H
true
23163c2f027a44c8ac6f8d50ebbf3dbed9d327f0
C++
incoder1/IO
/include/charsets.hpp
UTF-8
4,761
2.671875
3
[ "BSL-1.0" ]
permissive
/* * * Copyright (c) 2016-2019 * Viktor Gubin * * Use, modification and distribution are subject to the * Boost Software License, Version 1.0. (See accompanying file * LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) * */ #ifndef __CHARSETS_HPP_INCLUDED__ #define __CHARSETS_HPP_INCLUDED__ #include "config.hpp" #ifdef HAS_PRAGMA_ONCE #pragma once #endif // HAS_PRAGMA_ONCE namespace io { /// \brief A named mapping for the character set code page class IO_PUBLIC_SYMBOL charset { public: charset(const charset& rhs) = default; charset& operator=(const charset& rhs) = default; charset(charset&& rhs) noexcept = default; charset& operator=(charset&& rhs) noexcept = default; explicit constexpr charset(uint16_t code, const char* name, uint8_t char_max, bool unicode) noexcept: name_(name), code_(code), char_max_(char_max), unicode_(unicode) {} constexpr charset() noexcept: charset(0,nullptr,0,false) {} /// Checks this charset points to a known code page explicit operator bool() const noexcept { return char_max_ != 0 && code_ != 0; } /// Returns integer identifier of this character set, number is equal to Win32 id-s /// \return charset integer identifier constexpr inline uint32_t code() const { return code_; } /// Returns string identifier of this character set, names are the same as used by /// POSIX iconv /// \return string identifier of this character set constexpr inline const char* name() const { return name_; } /// Returns maximal width of a single character in bytes /// \return maximal width of a single character constexpr inline uint8_t char_max_size() const { return char_max_; } /// Returns whether this character set is point on an UNICODE representation code page /// \return whether this character set is UNICODE representation constexpr inline bool unicode() const { return unicode_; } /// Checks character set equality bool operator==(const charset& rhs) const noexcept { return code_ == rhs.code_; } /// Checks character set equality bool operator!=(const charset& rhs) const noexcept { return code_ != rhs.code_; } private: inline void swap(charset& with) noexcept { std::swap(unicode_, with.unicode_); std::swap(char_max_, with.char_max_); std::swap(code_, with.code_); std::swap(name_, with.name_); } private: const char* name_; uint16_t code_; uint8_t char_max_; bool unicode_; }; #define DECLARE_CHARSET(ID) static const charset ID; /// Enumeration of supported character sets constants class IO_PUBLIC_SYMBOL code_pages { code_pages(const code_pages&) = delete; code_pages& operator=(code_pages&) = delete; // to avoid externs, enums etc public: /** UNICODE representations **/ DECLARE_CHARSET(UTF_8) DECLARE_CHARSET(UTF_16LE) DECLARE_CHARSET(UTF_16BE) DECLARE_CHARSET(UTF_32BE) DECLARE_CHARSET(UTF_32LE) DECLARE_CHARSET(UTF_7) /** one byte code pages **/ DECLARE_CHARSET(ASCII) // ISO standards ASCII comp DECLARE_CHARSET(ISO_8859_1) DECLARE_CHARSET(ISO_8859_2) DECLARE_CHARSET(ISO_8859_3) DECLARE_CHARSET(ISO_8859_4) DECLARE_CHARSET(ISO_8859_5) DECLARE_CHARSET(ISO_8859_6) DECLARE_CHARSET(ISO_8859_7) DECLARE_CHARSET(ISO_8859_8) DECLARE_CHARSET(ISO_8859_9) DECLARE_CHARSET(ISO_8859_10) DECLARE_CHARSET(ISO_8859_11) DECLARE_CHARSET(ISO_8859_12) DECLARE_CHARSET(ISO_8859_13) DECLARE_CHARSET(ISO_8859_14) DECLARE_CHARSET(ISO_8859_15) DECLARE_CHARSET(ISO_8859_16) // Cyrillic Unix DECLARE_CHARSET(KOI8_R) // Unix Kyrylic single byte for Belarusian DECLARE_CHARSET(KOI8_U) // Unix Kyrylic soveit DOS single byte for Ukrainian DECLARE_CHARSET(KOI8_RU) // Unix Kyrylic soveit DOS single byte for Russian // Windows national code pages for the an alphabet based languages DECLARE_CHARSET(CP_1250) // latin 1 DECLARE_CHARSET(CP_1251) // latin1 extended DECLARE_CHARSET(CP_1252) // Kyrylic (Belarusian,Bulgarian,Russian,Serbian,Ukrainian etc.) DECLARE_CHARSET(CP_1253) // Greek DECLARE_CHARSET(CP_1254) DECLARE_CHARSET(CP_1255) DECLARE_CHARSET(CP_1256) DECLARE_CHARSET(CP_1257) DECLARE_CHARSET(CP_1258) /// Returns a character set for a iconv name static std::pair<bool, charset> for_name(const char* name) noexcept; /// Returns character set which is default for current operating system API /// I.e. UTF-16LE for Winfows or UTF-8 for Linux /// \return operating system API default character set static const charset& platform_default() noexcept; /// Returns character set assigned for this process/application, /// i.e. current locale character set /// \return current locale charter set static const charset& platform_current() noexcept; private: constexpr code_pages() noexcept {} }; #undef DECLARE_CHARSET } // namespace io #endif // __CHARSETS_HPP_INCLUDED__
true
1479733d0b542c14de4c98249d13a86255299184
C++
lianaivanova/social-media
/QuickSortImpl.h
UTF-8
816
3.1875
3
[]
no_license
#ifndef SOCIALMEDIA_QUICKSORTIMPL_H #define SOCIALMEDIA_QUICKSORTIMPL_H #include <vector> template<typename T> void swap(T *a, T *b) { T t = *a; *a = *b; *b = t; } template<typename T> int partition(vector<T> &elements, int low, int high) { T pivot = elements[high]; int i = (low - 1); for (int j = low; j <= high - 1; j++) { if (elements[j] < pivot) { i++; swap(&elements[i], &elements[j]); } } swap(&elements[i + 1], &elements[high]); return (i + 1); } template<typename T> void quickSort(vector<T> &elements, int low, int high) { if (low < high) { int pi = partition(elements, low, high); quickSort(elements, low, pi - 1); quickSort(elements, pi + 1, high); } } #endif //SOCIALMEDIA_QUICKSORTIMPL_H
true
26858585992d28c800401a6ce3cc5d89c814e6d4
C++
TeoPaius/Projects
/c++/Diverse problems and algorithms/Ore particular/extra/26.11/26.11/euler2.cpp
UTF-8
1,998
2.5625
3
[]
no_license
// ok infoarena #include <fstream> #include <iostream> #include <vector> #include <bitset> #include <string.h> #include <algorithm> #include <string> #include <queue> #include <stack> using namespace std; const char infile[] = "ciclueuler.in"; const char outfile[] = "ciclueuler.out"; ifstream fin(infile); ofstream fout(outfile); const int MAXN = 100005; const int oo = 0x3f3f3f3f; typedef vector<int> Graph[MAXN]; typedef vector<int> :: iterator It; const int lim = (1 << 20); char buff[lim]; int pos; inline void get(int &x) { while(!('0' <= buff[pos] && buff[pos] <= '9')) if(++ pos == lim) { pos = 0; fread(buff, 1, lim, stdin); } x = 0; while('0' <= buff[pos] && buff[pos] <= '9') { x = x * 10 + buff[pos] - '0'; if(++ pos == lim) { pos = 0; fread(buff, 1, lim, stdin); } } } Graph G; int N, M; stack <int> st; inline void Euler(int x) { st.push(x); vector <int> Ans; while(!st.empty()) { int Node = st.top(); if(G[Node].size()) { int newNode = G[Node].back(); G[Node].pop_back(); G[newNode].erase(find(G[newNode].begin(), G[newNode].end(), Node)); st.push(newNode); } else { st.pop(); if(!st.empty()) Ans.push_back(Node); } } for(It it = Ans.begin(), fin = Ans.end(); it != fin ; ++ it) fout << *it << ' '; fout << '\n'; } inline bool checkEulerProperty(void) { for(int i = 1 ; i <= N ; ++ i) if(!G[i].size() || G[i].size() & 1) return false; return true; } int main() { freopen(infile, "r", stdin); get(N); get(M); int x, y; for(int i = 1 ; i <= M ; ++ i) { get(x); get(y); G[x].push_back(y); G[y].push_back(x); } if(!checkEulerProperty()) fout << "-1\n"; else Euler(1); fin.close(); fout.close(); return 0; }
true
5edffc91883376c1c26c5caa5b629ca916cbeb4d
C++
RapidWorkers/ProblemSolving
/BOJ/소수 판정/5615.cpp
UTF-8
1,095
3.203125
3
[]
no_license
#include <iostream> #include <array> #include <vector> using namespace std; //fast modulo-power algorithm unsigned long long pow_mod(unsigned long long a, unsigned long long b, unsigned long long mod) { long long r = 1; a = a % mod; while (b) { if (b & 1) r = ((r % mod) * (a % mod)) % mod; b = b >> 1; a = (a * a) % mod; } return r; } //miller-rabin test bool isP(unsigned long long n) { vector<int> testArr = { 2, 3, 5, 7, 11};//from wikipedia bool prime = false; for (int a : testArr) { unsigned long long k = n - 1; if (a >= n) break; while (true) { unsigned long long tmp = pow_mod(a, k, n); if (tmp == n - 1) { prime = true; break; } if (k % 2) { if (tmp == 1) prime = true; else return false; break; } k = k >> 1; } } //cout << n << ' ' << prime << endl; return prime; } int main() { ios::sync_with_stdio(false); cin.tie(NULL); int N; cin >> N; int cnt = 0; for (int i = 0; i < N; i++) { unsigned long long area; cin >> area; if (isP(area+area+1)) cnt++; } cout << cnt; return 0; }
true
d54c0737ac231e4a91e3cbc38408ab2e1dcb7962
C++
cxjwin/algorithms
/LeetCode-CPP/offer.58/solution.cpp
UTF-8
1,764
3.296875
3
[]
no_license
#include <string> #include <vector> using namespace std; class Solution { public: string reverseWords(string s) { vector<int> pos; pos.push_back(-1); for (int i = 0; i < s.length(); ++i) { if (s[i] == ' ') { pos.push_back(i); } } pos.push_back(s.length()); vector<string> res; for (int i = 0; i < pos.size() - 1; ++i) { int next = pos[i + 1]; int start = pos[i] + 1; int end = next - 1; if (start <= end && s[end] != ' ') { int len = end - start + 1; res.push_back(s.substr(start, len)); } } if (res.size() == 0) { return ""; } string ret = res[res.size() - 1]; for (int i = res.size() - 2; i >= 0; --i) { ret += " "; ret += res[i]; } return ret; } }; class Solution2 { public: string reverseWords(string s) { int n = s.length(); if (n == 0) { return ""; } string res; int r = n - 1; while (r >= 0) { while (r >= 0 && s[r] == ' ') { --r; } if (r < 0) { break; } int l = r; while (l >= 0 && s[l] != ' ') { --l; } auto sub = s.substr(l + 1, r - l); if (res.length() == 0) { res = sub; } else { res = res + " " + sub; } r = l; } return res; } }; class SolutionII { public: string reverseLeftWords(string s, int n) { string res(s.size(), ' '); int j = 0; for (int i = n; i < s.size(); ++i) { res[j++] = s[i]; } for (int i = 0; i < n; ++i) { res[j++] = s[i]; } return res; } };
true
b5dfa5e1b96ee618d89790a05b873520632ad4f6
C++
busradogru/Robot-Proje
/MyAlgo/MyAlgo/MyAlgo.cpp
UTF-8
1,953
2.609375
3
[]
no_license
#include "MyAlgo.h" #include <stdio.h> #include <stdlib.h> bool __stdcall Algo1(int S, int L, int R, int Init, float& VL, float& VR) { float Output = PIDKontrolSistemi(); if (Output <= -1) { VR = 1100 + Output * 10; VL = 1100 - Output * 10; } else if (Output >= 1) { VR = 1100 + Output * 10; VL = 1100 - Output * 10; } else { VR = 1100 + Output * 10; VL = 1100 - Output * 10; } if (VR > 127) { VR = 60; } else if (VR < 127) VR = 5; if (VL > 127) VL = 60; else if (VL < 127) VL = 5; return true; } bool __stdcall Algo2(int S, int L, int R, int Init, int& VL, int& VR) { VL = 120; VR = 120; return true; } bool __stdcall Algo3(int S, int L, int R, int Init, int& VL, int& VR) { VL = 120; VR = 120; return true; } bool __stdcall Algo4(int S, int L, int R, int Init, int& VL, int& VR) { VL = 120; VR = 120; return true; } bool __stdcall Algo5(int S, int L, int R, int Init, int& VL, int& VR) { VL = 120; VR = 120; return true; } bool __stdcall Algo6(int S, int L, int R, int Init, int& VL, int& VR) { VL = 120; VR = 120; return true; } bool __stdcall Algo7(int S, int L, int R, int Init, int& VL, int& VR) { VL = 120; VR = 120; return true; } float PIDKontrolSistemi() { return 0.0; } unsigned long millis() { return 0; } unsigned long lastTime; double Input, Setpoint; double errSum, lastErr; double kp, ki, kd; unsigned long now = millis(); void Compute() { Input = 922; /*How long since we last calculated*/ double timeChange = (double)(now - lastTime); /*Compute all the working error variables*/ double error = Setpoint - Input; errSum += (error * timeChange); double dErr = (error - lastErr) / timeChange; /*Compute PID Output*/ static double Output; Output = kp * error + ki * errSum + kd * dErr; /*Remember some variables for next time*/ lastErr = error; lastTime = now; } void SetTunings(double Kp, double Ki, double Kd) { kp = Kp; ki = Ki; kd = Kd; }
true
7a0e377cb45dde703c89373a0b4b41045783f8cc
C++
mostafa-saad/ArabicCompetitiveProgramming
/18-Programming-4kids/08_homework_09_answer.cpp
UTF-8
407
3.28125
3
[]
no_license
#include<iostream> using namespace std; int main() { int N; cin >> N; int pos = 0; while (pos < N) { string str; cin>>str; // there are 8 different ways to make 2 letters no in lower/upper cases if (str == "no" || str == "No" || str == "nO" || str == "NO" || str == "on" || str == "oN" || str == "On" || str == "ON") cout<<str<<" "; pos++; } return 0; }
true
2b673f54aea9225f9e698fefbefeaf299afdd50f
C++
culturedsys/foc
/linearlists/linked/stack.hpp
UTF-8
504
3.109375
3
[]
no_license
#ifndef LINKED_STACK_HPP #define LINKED_STACK_HPP #include "../allocator.hpp" #include "node.hpp" namespace linked { class stack { node* top; node_allocator<node> allocator; public: // Create a stack with the specified maximum size stack(int); // Add the specified value to the stop of the stack void push(int); // Remove the value at the top of the stack and return it int pop(); }; } #endif
true
60e19d3995680f530adca3a64efad750c5cafa19
C++
barani008/C-programs
/DP/String Interleeving.cpp
UTF-8
1,237
3.578125
4
[]
no_license
/* Given s1, s2, s3, find whether s3 is formed by the interleaving of s1 and s2. For example, Given: s1 = "aabcc", s2 = "dbbca", When s3 = "aadbbcbcac", return true. When s3 = "aadbbbaccc", return false. */ class Solution { public: bool isInterleave(string s1, string s2, string s3) { if(s1.size() + s2.size() != s3.size()) return false; bool mat[s1.size()+1][s2.size()+1]; mat[0][0] = true; for(int i=1;i<=s1.size();i++){ if(s3[i-1]==s1[i-1] && mat[i-1][0]) mat[i][0] = true; else mat[i][0] = false; } for(int i=1;i<=s2.size();i++){ if(s3[i-1]==s2[i-1] && mat[0][i-1]) mat[0][i] = true; else mat[0][i] = false; } for(int i=1;i<=s1.size();i++){ for(int j=1;j<=s2.size();j++){ if(s1[i-1] == s3[i+j-1] && mat[i-1][j]){ mat[i][j] = true; }else if(s2[j-1] == s3[i+j-1] && mat[i][j-1]){ mat[i][j] = true; }else{ mat[i][j] = false; } } } return mat[s1.size()][s2.size()]; } };
true
7e68221fdecc0665f733097d0549c4857f6d42d7
C++
zhangjin19880118/Qt_Code
/IdeFile/mainwindow.cpp
UTF-8
6,594
2.90625
3
[]
no_license
#include "mainwindow.h" #include "ui_mainwindow.h" #include <QtDebug> #include <QFileDialog> #define cout qDebug() enum mycode { utf_8,gbk }; enum mycode flag; QString path; MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); flag=utf_8; path=""; } MainWindow::~MainWindow() { delete ui; } //选择utf-8编码显示 void MainWindow::on_actionUtf_8_triggered() { cout << "utf-8"; ui->label->setText("当前以utf-8编码显示"); flag=utf_8; readFile(); } //选择gbk编码显示 void MainWindow::on_actionGbk_triggered() { cout << "gbk"; ui->label->setText("当前以gbk编码显示"); flag=gbk; readFile(); } void MainWindow::on_actionOpen_triggered() { //1、选择打开文件的路径,Qt,返回文件的路径QString path = QFileDialog::getOpenFileName(); //需要头文件#include <QFileDialog> readFile(); } void MainWindow::readFile() { //判断打开路径是否为空 //if( path.isEmpty() == true) if( path == "") { cout << "文件路径为NULL"; return; } cout << "path = " << path.toStdString().data(); //将QString -> char * //2、QString -> char * //从Qt得到的字符串都是utf-8编码,如果是在windows,需要gbk,会打开失败 //const char *file = path.toStdString().data(); //toLocal8Bit(), 转换为本地字符集,如果windows则为gbk编码,如果linux则为utf-8编码 char *file = path.toLocal8Bit().data(); //3、打开文件, fopen //ANSI C(标准C)使用中文字符串和系统有关,如果是在windows,需要gbk // 如果是liunx,需要utf-8 FILE *fp = NULL; fp = fopen(file, "rb"); if(fp == NULL) { cout << "fopen err"; return; } cout << "文件打开成功"; //4、读取文件内容,fread(), char buf[4*1024] char buf[4*1024] = {0}; int ret; QString str; while(1) { memset(buf, 0, sizeof(buf)); //很重要 //从文件读取内容,放在buf中 ret = fread(buf, 1, sizeof(buf), fp); //cout << "ret = " << ret; if(ret == 0) //文件没有内容 { break; //跳出循环 } //如果读取内容为utf-8 if(utf_8 == flag) { str += buf; //str = str + buf; //char * ---> QString } //如果读取内容为gbk, 把gbk -----> utf-8 // //fromLocal8Bit(), 本地字符集转换为utf-8 //QString tmp = QString::fromLocal8Bit( (const char *)buf); else { str += QString::fromLocal8Bit( (const char *)buf); } } //5、buf内容显示到编辑区, 设置内容,需要参数类型QString //Qt控件显示中文,必须是utf-8编码 ui->textEdit->setText(str); //6、关闭文件 fclose() fclose(fp); } void MainWindow::on_actionSaveas_triggered() { //1、选择保存的路径, Qt, 路径是QString, utf-8 path = QFileDialog::getSaveFileName(); writeFile(); } void MainWindow::writeFile() { if( path.isEmpty() ) { cout << "文件路径为空"; return; } cout << "path = " << path.toStdString().data(); //2、utf-8 转换为本地编码, QString --> char * //从Qt得到的字符串都是utf-8编码,如果是在windows,需要gbk,会打开失败 //const char *file = path.toStdString().data(); //toLocal8Bit(), 转换为本地字符集,如果windows则为gbk编码,如果linux则为utf-8编码 char *file = path.toLocal8Bit().data(); //3、fopen("wb") FILE *fp = NULL; fp = fopen(file, "wb"); if(fp == NULL) { cout << "fopen err"; return; } //4、读取编辑区内容QString,写入文件char * // QString ---> char * QString str; str = ui->textEdit->toPlainText(); const char *buf = str.toStdString().data(); //QString ---> char * size_t size = str.toStdString().size(); //获取字符串的大小 fwrite(buf, 1, size, fp); //5、关闭文件 fclose(fp); fp = NULL; } void MainWindow::on_actionUndo_triggered() { ui->textEdit->undo(); } void MainWindow::on_actionCopy_triggered() { ui->textEdit->copy(); } void MainWindow::on_actionPaste_triggered() { ui->textEdit->paste(); } void MainWindow::on_actionCut_triggered() { ui->textEdit->cut(); } void MainWindow::on_actionCompile_triggered() { /* //编译 int flag = system("gcc C:\\Users\\MikeJiang\\Desktop\\mike.c -o C:\\Users\\MikeJiang\\Desktop\\mike"); cout << "flag = " << flag; if(flag != 0) //代码有问题 { system("cmd /k gcc C:\\Users\\MikeJiang\\Desktop\\mike.c -o C:\\Users\\MikeJiang\\Desktop\\mike"); return; } //运行 system("cmd /k C:\\Users\\MikeJiang\\Desktop\\mike"); */ if(path == "") { cout << "路径为空"; return; } //可执行程序的名字 QString target = path; cout << "target1 = " << target; target.replace(".c", ""); //把.c替换我空字符 cout << "target2 = " << target; //gcc xxx.c -o xxx QString cmd; //cmd = QString("gcc %1 -o %2").arg(path).arg(target); cmd = "gcc " + path + " -o " + target; cout << "cmd = " << cmd; int flag; //cmd为QString类型 //转换为本地编码,QString --> char * flag = system( cmd.toLocal8Bit().data() ); if(flag != 0) { cout << "编译的代码有错误"; cmd = "cmd /k " + cmd; cout << cmd; system( cmd.toLocal8Bit().data() ); return; } //运行代码 cmd = "cmd /k " + target; cout << cmd; system( cmd.toLocal8Bit().data() ); } void MainWindow::on_actionExit_triggered() { exit(1); } void MainWindow::on_actionSave_triggered() { if(path.isEmpty()) //if(path="") { path = QFileDialog::getSaveFileName(); writeFile(); return; } writeFile(); } void MainWindow::on_actionNew_triggered() { // ui->textEdit->setText(""); ui->textEdit->clear(); }
true
eb9562f137dbe73b6897dac4d9941e507cf3d63c
C++
hienlth/AP
/codes/Source_FILE_PTB2.cpp
UTF-8
1,494
2.984375
3
[]
no_license
#include <iostream> #include <stdio.h> #include <stdlib.h> #define MAX 100 #define VOSONGHIEM -1 #define VONGHIEM 0 #define CO1NGHIEM 1 #define CO2NGHIEM 2 struct PTB2{ double A, B, C; //hệ số PTB2 int sn; //số nghiệm: -1 (vô số nghiệm); 0 (vô nghiệm); 1 (có 1 nghiệm), 2 (có 2 nghiệm) double X1, X2; //giá trị nghiệm }; struct DSPTB2{ PTB2 a[MAX]; int n; }; void DocTaptin(char* fname, DSPTB2& ds); void GhiTaptin(char* fname, DSPTB2 ds); void GiaiPTB2(PTB2& pt); void main() { DSPTB2 ds; DocTaptin("PTB2.txt",ds); for(int i=0; i<ds.n; i++) GiaiPTB2(ds.a[i]); GhiTaptin("GiaiPTB2.txt",ds); } void DocTaptin(char* fname, DSPTB2& ds) { FILE* fp; fopen_s(&fp,fname,"rt"); //fp = fopen(fname,"rt"); //đọc dữ liệu PTB2 từ tập tin fscanf_s(fp,"%d",&ds.n); for(int i=0; i<ds.n; i++) { fscanf_s(fp,"%lf%lf%lf",&ds.a[i].A,&ds.a[i].B,&ds.a[i].C); } fclose(fp); } void GhiTaptin(char* fname, DSPTB2 ds) { FILE* fp; fopen_s(&fp,fname,"wt"); //fp = fopen(fname,"rt"); //ghi dữ liệu PTB2 ra tập tin for(int i=0; i<ds.n; i++) { switch(ds.a[i].sn) { case VOSONGHIEM: fprintf(fp,"VO SO NGHIEM\n"); break; case VONGHIEM: fprintf(fp,"VO NGHIEM\n"); break; case CO1NGHIEM: fprintf(fp,"X = %.2lf\n",ds.a[i].X1); break; case CO2NGHIEM: fprintf(fp,"X1 = %.2lf X2 = %.2lf\n",ds.a[i].X1,ds.a[i].X2); break; } } fclose(fp); }
true
f6404113f1c2fcdf9ef606124ad52a6593973e81
C++
leojavier/CPP_matrix_implementation
/matrix.h
UTF-8
696
2.96875
3
[]
no_license
#ifndef MATRIX_H #define MATRIX_H #include <iostream> #include <vector> #include <stdexcept> class Matrix { private: std::vector< std::vector<float> > grid; std::vector<int>::size_type rows; std::vector<int>::size_type columns; public: //Constructor function Matrix(); Matrix(std::vector< std::vector<float> >); //Setters void setGrid(std::vector< std::vector<float> >); //Getters std::vector< std::vector<float> > getGrid(); std::vector<int>::size_type getRows(); std::vector<int>::size_type getColumns(); //Methods Matrix matrix_transpose(); Matrix matrix_addition(Matrix); void matrix_print(); }; #endif /* MATRIX_H */
true
02a2d1e69b38b318fb638b545bfc08126c6b3646
C++
kmmao/REDM
/DmMain/inc/Common/Template/DMAllocT.h
GB18030
8,025
2.96875
3
[ "MIT" ]
permissive
//------------------------------------------------------- // Copyright (c) DuiMagic // All rights reserved. // // File Name: DMAllocT.h // File Des: // File Summary: // Cur Version: 1.0 // Author: // Create Data: // History: // <Author> <Time> <Version> <Des> // guoyou 2015-01-13 1.0 //------------------------------------------------------- #pragma once #include <new> namespace DM { /// <summary> /// ָתָ /// </summary> template <class Dst> Dst DMCastT(const void* ptr) { union { const void* src; Dst dst; } data; data.src = ptr; return data.dst; } // -----------------------------------------------------ΪDMLazyT-------------------------------------------------------------------- /// <summary> /// Ϊһʱ棬ʵȿջϷڴ棬ջϿռ䲻ʱʹӶз /// </summary> /// <remarks> /// atlapp.CTempBuffer,η,ȸһε /// </remarks> template<class T, int t_nFixedBytes = 128> class DMBufT { public: DMBufT() : m_p(NULL) { } DMBufT(size_t nElements) : m_p(NULL) { Allocate(nElements); } ~DMBufT() { Free(); } operator T*() const { return m_p; } T* operator ->() const { DMASSERT(NULL != m_p); return m_p; } T * get(void) const {return m_p;} /// ------------------------------------------------- /// @brief ͷڴ void Free() { if (m_p&&m_p != DMCastT<T*>(m_abFixedBuffer)) { free(m_p); } } /// ------------------------------------------------- /// @brief ڴ棨 T* Allocate(size_t nElements) { DMASSERT(nElements <= (SIZE_MAX / sizeof(T))); return AllocateBytes(nElements * sizeof(T)); } /// ------------------------------------------------- /// @brief ڴ棨ֽ T* AllocateBytes(size_t nBytes) { Free(); //DMASSERT(m_p == NULL); if (nBytes > t_nFixedBytes) { m_p = reinterpret_cast<T*>(malloc(nBytes));/// ʹstatic_cast,static_castʽתпܲתreinterpret_castǵͲ } else { m_p = DMCastT<T*>(m_abFixedBuffer); } // Ϊ0 memset(m_p, 0, (nBytes>t_nFixedBytes)?nBytes:t_nFixedBytes); return m_p; } private: T* m_p; BYTE m_abFixedBuffer[t_nFixedBytes]; }; // -----------------------------------------------------ΪDMLazyT-------------------------------------------------------------------- /// <summary> /// Ĭ /// </summary> template <class T> struct DMDefLazyTraits { static T* New(void* Storage) { /// ע⣬ʹnewStorageΪʼַ return new (DMCastT<T*>(Storage)) T; } static T* NewWithCopy(void* Storage, T* src) { return new (DMCastT<T*>(Storage)) (*src); } static void Delete(T* Storage) { Storage->~T(); } }; /// <summary> /// עDeleteĴ /// </summary> template <typename T> struct DMLeakLazyTraits { static T* New(void* Storage) { return new (DMCastT<T*>(Storage)) T; } static T* NewWithCopy(void* Storage, T* src) { return new (DMCastT<T*>(Storage)) (*src); } static void Delete(T* Storage) { // nothing } }; template <typename T, bool bAutoInit,typename LazyTraits, int STORAGESIZE> class DMLazyBaseT; /// <summary> /// LayzTĴSkTLazy.h+SkTypes.h,лzcԭʼ /// </summary> /// <remarks> /// ӳٳʼǽijʼӳٵһʹøöʱӶ߳Чʣʹռøٵڴ /// </remarks> template<typename T, bool bAutoInit=true, typename LazyTraits = DMDefLazyTraits<T> > class DMLazyT : public DMLazyBaseT<T, bAutoInit,LazyTraits, sizeof(T)> { typedef DMLazyBaseT<T, bAutoInit,LazyTraits, sizeof(T)> __baseClass; typedef T* TPtr; public: DMLazyT():__baseClass() { } explicit DMLazyT(const TPtr src):__baseClass() { this->InitWithCopy(src); } DMLazyT(const DMLazyT<T>& src): __baseClass() { if (src.IsValid()) { this->InitWithCopy(src.Get()); } } public: /// ------------------------------------------------- /// @brief ʼ /// @return ԭʼѴ,ԭʼģٴµ TPtr InitWithNew() { this->destroy(); return this->Init(); } /// ------------------------------------------------- /// @brief /// @return һԴָ룬Ḳԭʼģԭѳʼ TPtr Set(const T& src) { if (!IsValid()) { return __baseClass::InitWithCopy(&src); } *Get() = src; return Get(); } }; /// <summary> /// DMLazyTĻ,Ԥȷڴ沢ʱ /// </summary> template <typename T, bool bAutoInit=true, typename LazyTraits = DMDefLazyTraits<T>, int STORAGESIZE = sizeof(T)> class DMLazyBaseT { public: typedef T TClass; typedef T* TPtr; typedef T& TRef; public: DMLazyBaseT():m_ptr(NULL) {} ~DMLazyBaseT() { if (this->IsValid()) { // LeakyDMLazyTraits LazyTraits::Delete(m_ptr); } } public: /// ------------------------------------------------- /// @brief ʼ /// @return 򷵻ѴڵĶ. TPtr Init() { if (NULL == m_ptr) { m_ptr = LazyTraits::New(m_storage); } return m_ptr; } /// ------------------------------------------------- /// @brief 󲢸ƣѴڵĶ /// @return شڵĶ. template<size_t N> TPtr InitWithCopy(TPtr src) { DMASSERT_MSG(src, "DMLazyBaseT::InitWithCopy"); if (NULL == m_ptr) { m_ptr = LazyTraits::NewWithCopy(m_storage, src); } return m_ptr; } /// ------------------------------------------------- /// @brief DMLazy. /// @return DMLazy. void destroy() { if (this->IsValid()) { LazyTraits::Delete(m_ptr); } m_ptr = NULL; } /// ------------------------------------------------- /// @brief ǷЧ /// @return true:Ч,false:Ч bool IsValid() const { return NULL != m_ptr; } /// ------------------------------------------------- /// @brief ȡ /// @return 󣬿ΪNULL TPtr Get() { if (!m_ptr) { if (bAutoInit) { Init(); } } DMASSERT_MSG(this->IsValid(), "DMLazyBaseT::Get"); return m_ptr; } /// ------------------------------------------------- /// @brief /// @return -> const TPtr operator->() const { if (!m_ptr) { if (bAutoInit) { Init(); } } DMASSERT_MSG(m_ptr, "const DMLazyBaseT::->"); return m_ptr; } /// ------------------------------------------------- /// @brief /// @return -> TPtr operator->() { if (!m_ptr) { if (bAutoInit) { Init(); } } DMASSERT_MSG(m_ptr, "DMLazyBaseT::->"); return m_ptr; } /// ------------------------------------------------- /// @brief unspecified_bool_type /// @remark http://hgy413.com/1958.html /// @return boolֵж typedef TPtr DMLazyBaseT::*unspecified_bool_type; operator unspecified_bool_type() const { return m_ptr ? &DMLazyBaseT::m_ptr : NULL; } protected: /// ------------------------------------------------- /// @brief شгʼ. /// @return void* InitWithStorage() { if (NULL == m_ptr) { m_ptr = reinterpret_cast<T*>(this->m_storage); } return m_ptr; } protected: TPtr m_ptr; ///<ҪôΪNULLҪôָm_storageλ char m_storage[STORAGESIZE]; ///<СĬʹջ洢 }; }//namespace DM
true
b9c3e4d3e36c625a4e5bd91947e8a28d6017136e
C++
danyveve/UBB-PDP
/PPD-Lab7.2/Lab7.2/Lab7.2/Lab7.2.cpp
UTF-8
1,112
3.109375
3
[]
no_license
#include "pch.h" #include <iostream> #include "ParallelSumHhelper.h" #include <queue> #include "Lab7.2.h" #include <future> int main() { std::vector<std::vector<int>> numbers = readNumbersFromFile("numbers.txt"); //transform numbers into queues of digits std::vector<std::queue<int>> numbersQueues; for (std::vector<int> number : numbers) { std::reverse(number.begin(), number.end()); std::queue<int, std::deque<int>> qNr(std::deque<int>(number.begin(), number.end())); numbersQueues.push_back(qNr); } //start sequential version first ParallelSumHelper::startSequential(numbersQueues); //create threads and arrange in binaryTree ParallelSumHelper::createThreadsAndStart(numbersQueues); } std::vector<std::vector<int>> readNumbersFromFile(std::string fileName) { std::vector<std::vector<int>> numbers; std::ifstream file(fileName); std::string line; while (std::getline(file, line)) { std::vector<int> number; std::istringstream numberStream(line); int digit; while (numberStream >> digit) { number.push_back(digit); } numbers.push_back(number); } return numbers; }
true
4da139a5a75f9447ad57a12887106b7675dd2e4a
C++
lincomatic/WeatherCube
/software/zonda/zonda/rtc.ino
UTF-8
1,890
2.515625
3
[]
no_license
void rtc_write_date(int sec, int mint, int hr24, int dotw, int dy, int mon, int yr) { Wire.beginTransmission(RTC_ADDR); Wire.write((uint8_t)TIME_REG); Wire.write(dec2bcd(sec) | B10000000); //stops the oscillator (Bit 7, ST == 0) Wire.write(dec2bcd(mint)); Wire.write(dec2bcd(hr24)); //hr Wire.write(dec2bcd(dotw) | B00001000); //dotw Wire.write(dec2bcd(dy)); //date Wire.write(dec2bcd(mon)); //month Wire.write(dec2bcd(yr)); //year Wire.write((byte) 0); //Wire.write((uint8_t)0x00); /* Wire.write(dec2bcd(05)); Wire.write(dec2bcd(04)); //sets 24 hour format (Bit 6 == 0) Wire.endTransmission(); Wire.beginTransmission(RTC_ADDR); Wire.write((uint8_t)TIME_REG); Wire.write(dec2bcd(30) | _BV(ST)); //set the seconds and start the oscillator (Bit 7, ST == 1) */ Wire.endTransmission(); } void rtc_read_timestamp(int mode) { byte rtc_out[RTC_TS_BITS]; //int integer_time[RTC_TS_BITS]; Wire.beginTransmission(RTC_ADDR); Wire.write((byte)0x00); if (Wire.endTransmission() != 0) { Serial.println(F("no luck")); //return false; } else { //request 7 bytes (secs, min, hr, dow, date, mth, yr) Wire.requestFrom(RTC_ADDR, RTC_TS_BITS); // cycle through bytes and remove non-time data (eg, 12 hour or 24 hour bit) for (int i = 0; i < RTC_TS_BITS; i++) { rtc_out[i] = Wire.read(); //if (mode == 0) printBits(rtc_out[i]); //else //{ //byte b = rtc_out[i]; if (i == 0) rtc_out[i] &= B01111111; else if (i == 3) rtc_out[i] &= B00000111; else if (i == 5) rtc_out[i] &= B00011111; //int j = bcd2dec(b); //Serial.print(j); //if(i < how_many - 1) Serial.print(","); //} } } for (int i = 0; i < RTC_TS_BITS ; i++) { int ii = rtc_out[i]; integer_time[i] = bcd2dec(ii); } }
true
d9eb4731f8a5235ea117b95adc1d18b420c25693
C++
abdullah13314/Book-Store
/code/InventoryTransaction.cpp
UTF-8
668
2.671875
3
[]
no_license
#include "stdafx.h" #include "InventoryTransaction.h" InventoryTransaction::InventoryTransaction() { pAudioBooksInventoryTree = NULL; pOtherBooksInventoryTree = NULL; } InventoryTransaction::InventoryTransaction(BST * pAudioBooksInventoryT, BST * pOtherBooksInventoryT) { pAudioBooksInventoryTree = pAudioBooksInventoryT; pOtherBooksInventoryTree = pOtherBooksInventoryT; } InventoryTransaction::~InventoryTransaction() { } void InventoryTransaction::ExecuteTransection() { cout << "Audio Books: " << endl; cout << (*pAudioBooksInventoryTree) << endl; cout << "Standard Books and Graphic Novels: " << endl; cout << (*pOtherBooksInventoryTree) << endl; }
true
fe6e03d319020e0e978668f53829fda48bd36fb2
C++
Ujwalgulhane/Data-Structure-Algorithm
/Algorithms/DynamicProgramming/mincostMatrixTraversal.cpp
UTF-8
680
2.859375
3
[]
no_license
#include<climits> #include<iostream> #include<vector> using namespace std; int cost(vector<vector<int>>arr,int n,int m){ vector<vector<int>>dp(n,vector<int>(m)); dp[n-1][m-1]=arr[n-1][m-1]; for(int i=arr.size()-1;i>=0;i--){ for(int j=arr[0].size()-1;j>=0;j--){ if(i==n-1 && j==m-1) dp[i][j]=arr[i][j]; else if(i==n-1){ dp[i][j]=dp[i][j+1]+arr[i][j]; }else if(j==m-1){ dp[i][j]=dp[i+1][j]+arr[i][j]; }else{ dp[i][j]=arr[i][j]+min(dp[i+1][j],dp[i][j+1]); } } } return dp[0][0]; } int main(){ int n,m; cin>>n>>m; vector<vector<int>>arr(n,vector<int>(m)); for(int i=0;i<n;i++) for(int j=0;j<m;j++) cin>>arr[i][j]; cout<<cost(arr,n,m)<<endl; }
true
ef88b4728b274247ef1652a87c6582f3a43595b9
C++
SamChien/Competitive-Programming
/uva_online_judge/10050-Hartals.cpp
UTF-8
626
2.578125
3
[]
no_license
#include <cstdio> int main() { int caseNum; scanf("%d", &caseNum); while (caseNum--) { int n, p, loseDays; scanf("%d%d", &n, &p); bool table[n]; for (int i=0; i<n; i++) table[i] = false; for (int i=0; i<p; i++) { int hartal; scanf("%d", &hartal); for (int j=hartal-1; j<n; j+=hartal) { if (j % 7 != 5 && j % 7 != 6) table[j] = true; } } loseDays = 0; for (int i=0; i<n; i++) { if (table[i]) loseDays++; } printf("%d\n", loseDays); } return 0; }
true
c55a436d08eb2a6dcf04e088a2e28ce87e1840f7
C++
shaniherskowitz/othello
/src/client/Menu.h
UTF-8
828
2.625
3
[]
no_license
#ifndef OTHELLO_MENU_H #define OTHELLO_MENU_H #include "GameUI.h" #include "Game.h" #include "HumanPlayer.h" #include "AIPlayer.h" #include "RemotePlayer.h" #include "Client.h" #include <fstream> #include <sstream> #define DEF_SIZE 8 /** * Defining a Menu class. */ class Menu { public: /** * The Menu's default constructor. */ Menu(); /** * The Menu's destructor. */ ~Menu(); /** * The method starts a game according to the user's choice. */ void showMenu(); /** * * @param to print to user what to do * @return game with remote players based on if the client connected first. */ Game *getServerGame(GameUI *print); /** * * @param print to user his options * @return the game the user selected */ int getUserInput(GameUI *print); }; #endif //OTHELLO_MENU_H
true
c9acc920e2a4e28e8b33190a3acd6b7bdf1b62b7
C++
jqhong/klee-native
/remill/tools/klee/runtime/Native/OS/Linux/Intercepts.cpp
UTF-8
12,365
2.578125
3
[ "Apache-2.0", "NCSA" ]
permissive
/* * Copyright (c) 2019 Trail of Bits, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "runtime/Native/Intrinsics.h" namespace { extern "C" { long strtol_intercept(addr_t nptr, addr_t endptr, int base, Memory *memory); addr_t malloc_intercept( Memory *memory, uint64_t size); bool free_intercept( Memory *memory, addr_t ptr); addr_t calloc_intercept( Memory *memory, uint64_t size); addr_t realloc_intercept( Memory *memory, addr_t ptr, uint64_t size); size_t malloc_size( Memory *memory, addr_t ptr); addr_t memset_intercept(Memory * memory, addr_t s, int c, size_t n); addr_t memcpy_intercept(Memory * memory, addr_t dest, addr_t src, size_t n); addr_t memmove_intercept(Memory * memory, addr_t dest, addr_t src, size_t n); addr_t strcpy_intercept(Memory *memory, addr_t dest, addr_t src); addr_t strncpy_intercept(Memory *memory, addr_t dest, addr_t src, size_t n); size_t strlen_intercept(Memory *memory, addr_t s); size_t strnlen_intercept(Memory *memory, addr_t s, size_t n); } // extern C template <typename ABI> static Memory *Intercept_strtol(Memory *memory, State *state, const ABI &intercept) { addr_t nptr = 0; addr_t endptr = 0; int base = 0; if (!intercept.TryGetArgs(memory, state, &nptr, &endptr, &base)) { STRACE_ERROR(libc_strtol, "Couldn't get args"); exit(1); } long number = strtol_intercept(nptr, endptr, base, memory); exit(0); } static constexpr addr_t kBadAddr = ~0ULL; static constexpr addr_t kReallocInternalPtr = ~0ULL - 1ULL; static constexpr addr_t kReallocTooBig = ~0ULL - 2ULL; static constexpr addr_t kReallocInvalidPtr = ~0ULL - 3ULL; static constexpr addr_t kReallocFreedPtr = ~0ULL - 4ULL; static constexpr addr_t kMallocTooBig = ~0ULL - 1ULL; template <typename ABI> static Memory *Intercept_malloc(Memory *memory, State *state, const ABI &intercept) { addr_t alloc_size = 0; if (!intercept.TryGetArgs(memory, state, &alloc_size)) { STRACE_ERROR(malloc, "Couldn't get args"); return intercept.SetReturn(memory, state, 0); } if (!alloc_size) { STRACE_SUCCESS(libc_malloc, "size=0, ptr=0"); return intercept.SetReturn(memory, state, 0); } const auto ptr = malloc_intercept(memory, alloc_size); if (ptr == kBadAddr) { STRACE_ERROR(libc_malloc, "Falling back to real malloc for size=%" PRIxADDR, alloc_size); return memory; } else if (ptr == kMallocTooBig) { STRACE_ERROR(libc_malloc, "Malloc for size=%" PRIxADDR " too big", alloc_size); return memory; } else { STRACE_SUCCESS(libc_malloc, "size=%" PRIdADDR ", ptr=%" PRIxADDR, alloc_size, ptr); return intercept.SetReturn(memory, state, ptr); } } template <typename ABI> static Memory *Intercept_free(Memory *memory, State *state, const ABI &intercept) { addr_t address = 0; if (!intercept.TryGetArgs(memory, state, &address)) { STRACE_ERROR(libc_free, "Couldn't get args"); return intercept.SetReturn(memory, state, 0); } if (!address) { STRACE_SUCCESS(libc_free, "ptr=%" PRIxADDR, address); return intercept.SetReturn(memory, state, 0); } if (!free_intercept(memory, address)) { STRACE_ERROR(libc_free, "Falling back to real free for ptr=%" PRIxADDR, address); return memory; } STRACE_SUCCESS(libc_free, "ptr=%" PRIxADDR, address); return intercept.SetReturn(memory, state, 0); } template <typename ABI> static Memory *Intercept_calloc(Memory *memory, State *state, const ABI &intercept) { addr_t num = 0; addr_t size = 0; if (!intercept.TryGetArgs(memory, state, &num, &size)) { STRACE_ERROR(libc_calloc, "Couldn't get args"); return intercept.SetReturn(memory, state, 0); } addr_t alloc_size = num * size; if (!alloc_size) { STRACE_SUCCESS(libc_calloc, "num=%" PRIxADDR ", size=%" PRIxADDR ", ptr=0", num, size); return intercept.SetReturn(memory, state, 0); } const auto ptr = calloc_intercept(memory, alloc_size); if (ptr == kBadAddr) { STRACE_ERROR(libc_calloc, "Falling back to real calloc for num=%" PRIxADDR ", size=%" PRIxADDR, num, size); return memory; } else if (ptr == kMallocTooBig) { STRACE_ERROR(libc_calloc, "Calloc for size=%" PRIxADDR " too big", alloc_size); return memory; } else { STRACE_SUCCESS(libc_calloc, "num=%" PRIdADDR ", size=%" PRIdADDR ", ptr=%" PRIxADDR, num, size, ptr); return intercept.SetReturn(memory, state, ptr); } } template <typename ABI> static Memory *Intercept_realloc(Memory *memory, State *state, const ABI &intercept) { addr_t ptr; size_t alloc_size; if (!intercept.TryGetArgs(memory, state, &ptr, &alloc_size)) { STRACE_ERROR(libc_realloc, "Couldn't get args"); return intercept.SetReturn(memory, state, 0); } if (!alloc_size) { if (ptr && !free_intercept(memory, ptr)) { STRACE_ERROR(libc_realloc, "Error freeing old_ptr=%" PRIxADDR, ptr); } STRACE_SUCCESS(libc_realloc, "old_ptr=%" PRIxADDR ", new_size=%" PRIdADDR ", new_ptr=%" PRIxADDR, ptr, alloc_size, 0); return intercept.SetReturn(memory, state, 0); } addr_t new_ptr = realloc_intercept(memory, ptr, alloc_size); if (new_ptr == kBadAddr) { STRACE_ERROR(libc_realloc, "Falling back to real realloc for ptr=%" PRIxADDR ", size=%" PRIxADDR, ptr, alloc_size); return memory; } else if (kReallocInternalPtr == new_ptr) { STRACE_ERROR(libc_realloc, "Can't realloc displaced malloc addr=%" PRIxADDR, ptr); klee_abort(); } else if (kReallocTooBig == new_ptr) { STRACE_ERROR(libc_realloc, "Realloc size=%" PRIxADDR " too big", alloc_size); klee_abort(); } else if (kReallocInvalidPtr == new_ptr) { STRACE_ERROR(libc_realloc, "Realloc on untracked addr=%" PRIxADDR, ptr); klee_abort(); } else if (kReallocFreedPtr == new_ptr) { STRACE_ERROR(libc_realloc, "Realloc on freed addr=%" PRIxADDR, ptr); klee_abort(); } else { STRACE_SUCCESS(libc_realloc, "old_ptr=%" PRIxADDR ", new_size=%" PRIdADDR ", new_ptr=%" PRIxADDR, ptr, alloc_size, new_ptr); return intercept.SetReturn(memory, state, new_ptr); } } template <typename ABI> static Memory *Intercept_memalign(Memory *memory, State *state, const ABI &intercept) { size_t alignment; size_t size; if (!intercept.TryGetArgs(memory, state, &alignment, &size)) { STRACE_ERROR(libc_memalign, "Couldn't get args"); return intercept.SetReturn(0, state, 0); } const auto ptr = malloc_intercept(memory, size); if (ptr == kBadAddr) { STRACE_ERROR(libc_memalign, "Falling back to real memalign for align=%" PRIxADDR ", size=%" PRIxADDR, alignment, size); return memory; } return intercept.SetReturn(memory, state, ptr); } template <typename ABI> static Memory *Intercept_malloc_usable_size(Memory *memory, State *state, const ABI &intercept) { addr_t ptr; if (!intercept.TryGetArgs(memory, state, &ptr)) { STRACE_ERROR(read, "Couldn't get args"); return intercept.SetReturn(memory, state, 0); } const auto size = malloc_size(memory, ptr); if (!size) { STRACE_ERROR( libc_malloc_usable_size, "Falling back to real malloc_usable_size for ptr=%" PRIxADDR, ptr); return memory; } return intercept.SetReturn(memory, state, size); } template <typename ABI> static Memory *Intercept_memset(Memory *memory, State *state, const ABI &intercept) { addr_t s; int c; size_t n; if (!intercept.TryGetArgs(memory, state, &s, &c, &n)) { STRACE_ERROR(libc_memset, "Couldn't get args"); return intercept.SetReturn(memory, state, 0); } addr_t ptr = memset_intercept(memory, s, (char) c, n); STRACE_SUCCESS(libc_memset, "dest=%" PRIxADDR ", val=%x, len=%" PRIdADDR ", ret=%" PRIxADDR, ptr, (int)(char)c, n, ptr); return intercept.SetReturn(memory, state, ptr); } template <typename ABI> static Memory *Intercept_memcpy(Memory *memory, State *state, const ABI &intercept) { addr_t dest; addr_t src; size_t n; if (!intercept.TryGetArgs(memory, state, &dest, &src, &n)) { STRACE_ERROR(libc_memcpy, "Couldn't get args"); return intercept.SetReturn(memory, state, 0); } addr_t ptr = memcpy_intercept(memory, dest, src, n); STRACE_SUCCESS(libc_memcpy, "dest=%" PRIxADDR ", src=%" PRIxADDR ", len=%" PRIdADDR ", ret=%" PRIxADDR, dest, src, n, ptr); return intercept.SetReturn(memory, state, ptr); } template <typename ABI> static Memory *Intercept_memmove(Memory *memory, State *state, const ABI &intercept) { addr_t dest; addr_t src; size_t n; if (!intercept.TryGetArgs(memory, state, &dest, &src, &n)) { STRACE_ERROR(libc_memmove, "Couldn't get args"); return intercept.SetReturn(memory, state, 0); } addr_t ptr = memmove_intercept(memory, dest, src, n); STRACE_SUCCESS(libc_memmove, "dest=%" PRIxADDR ", src=%" PRIxADDR ", len=%" PRIdADDR ", ret=%" PRIxADDR, dest, src, n, ptr); return intercept.SetReturn(memory, state, ptr); } template <typename ABI> static Memory *Intercept_strcpy(Memory *memory, State *state, const ABI &intercept) { addr_t dest; addr_t src; if (!intercept.TryGetArgs(memory, state, &dest, &src)) { STRACE_ERROR(libc_strcpy, "Couldn't get args"); return intercept.SetReturn(memory, state, 0); } addr_t ptr = strcpy_intercept(memory, dest, src); STRACE_SUCCESS(libc_strcpy, "dest=%" PRIxADDR ", src=%" PRIxADDR ", ret=%" PRIxADDR, dest, src, ptr); return intercept.SetReturn(memory, state, ptr); } template <typename ABI> static Memory *Intercept_strncpy(Memory *memory, State *state, const ABI &intercept) { addr_t dest; addr_t src; size_t n; if (!intercept.TryGetArgs(memory, state, &dest, &src, &n)) { STRACE_ERROR(libc_strncpy, "Couldn't get args"); return intercept.SetReturn(memory, state, 0); } addr_t ptr = strncpy_intercept(memory, dest, src, n); STRACE_SUCCESS(libc_strncpy, "dest=%" PRIxADDR ", src=%" PRIxADDR ", len=%" PRIdADDR ", ret=%" PRIxADDR, dest, src, n, ptr); return intercept.SetReturn(memory, state, ptr); } template <typename ABI> static Memory *Intercept_strlen(Memory *memory, State *state, const ABI &intercept) { addr_t s; if (!intercept.TryGetArgs(memory, state,&s)) { STRACE_ERROR(libc_strlen, "Couldn't get args"); return intercept.SetReturn(memory, state, 0); } size_t size = strlen_intercept(memory, s); STRACE_SUCCESS(libc_strlen, "ptr=%" PRIxADDR ", len=%" PRIdADDR, s, size); return intercept.SetReturn(memory, state, size); } template <typename ABI> static Memory *Intercept_strnlen(Memory *memory, State *state, const ABI &intercept) { addr_t s; size_t n; if (!intercept.TryGetArgs(memory, state, &s, &n)) { STRACE_ERROR(libc_strnlen, "Couldn't get args"); return intercept.SetReturn(memory, state, 0); } size_t size = strnlen_intercept(memory, s, n); STRACE_SUCCESS(libc_strnlen, "ptr=%" PRIxADDR ", max_len=%" PRIdADDR ", len=%" PRIdADDR, s, n, size); return intercept.SetReturn(memory, state, size); } template <typename ABI> static Memory *Intercept_strncmp(Memory *memory, State *state, const ABI &intercept) { return memory; } template <typename ABI> static Memory *Intercept_strcmp(Memory *memory, State *state, const ABI &intercept) { return memory; } } // namespace
true
30e9e3542e3b52937944f63a3a239af15228b25e
C++
anoopskapoor95148/leetcode
/easy/Symmetric-Tree-101.cpp
UTF-8
817
3.296875
3
[]
no_license
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: bool isSameTree(struct TreeNode* p, struct TreeNode* q, bool *flag) { if (*flag == true) return false; if (!p && !q) return true; if (!p || !q) { *flag = true; return false; } if (p->val != q->val) { *flag = true; return false; } return (isSameTree (p->left, q->right, flag) && isSameTree (p->right, q->left, flag)); } bool isSymmetric(struct TreeNode* root) { if (!root) return true; bool flag = false; return isSameTree (root->left, root->right, &flag); } };
true
6fa793fa62fdc74bb1992ab79bad3d3df92098d3
C++
kk4728/CppPrimer5th
/ch12_mem-sp/exer.12.1.2.cpp
UTF-8
644
3.140625
3
[]
no_license
#include <iostream> #include <memory> #include <vector> using namespace std; shared_ptr<vector<int>> revec2() { return make_shared<vector<int>>(); } std::vector<int>* revec() { vector<int> *pvi = new vector<int>(); return pvi; } void f126(vector<int>* p) { int i; while(cin>>i) { p->push_back(i); } } void print(const vector<int> & vi) { cout << "======================" << endl; for(auto & n : vi) cout << n << endl; } int main() { // std::vector<int> * p = revec(); // shared_ptr<vector<int>> p = revec2(); shared_ptr<vector<int>> p = make_shared<vector<int>>(); f126(p.get()); print(*p); // delete p; return 0; }
true
bebc8e57430b22f5ad4236719eafa71662aa4318
C++
nahratzah/ilias_os
/proper/abi/include/stdimpl/functional_comparators.h
UTF-8
2,784
2.6875
3
[]
no_license
#ifndef _STDIMPL_FUNCTIONAL_COMPARATORS_H_ #define _STDIMPL_FUNCTIONAL_COMPARATORS_H_ #include <cdecl.h> _namespace_begin(std) template<typename T = void> struct equal_to { constexpr bool operator()(const T& x, const T& y) const { return x == y; } using first_argument_type = T; using second_argument_type = T; using result_type = bool; }; template<typename T = void> struct not_equal_to { constexpr bool operator()(const T& x, const T& y) const { return x != y; } using first_argument_type = T; using second_argument_type = T; using result_type = bool; }; template<typename T = void> struct greater { constexpr bool operator()(const T& x, const T& y) const { return x > y; } using first_argument_type = T; using second_argument_type = T; using result_type = bool; }; template<typename T = void> struct less { constexpr bool operator()(const T& x, const T& y) const { return x < y; } using first_argument_type = T; using second_argument_type = T; using result_type = bool; }; template<typename T = void> struct greater_equal { constexpr bool operator()(const T& x, const T& y) const { return x >= y; } using first_argument_type = T; using second_argument_type = T; using result_type = bool; }; template<typename T = void> struct less_equal { constexpr bool operator()(const T& x, const T& y) const { return x <= y; } using first_argument_type = T; using second_argument_type = T; using result_type = bool; }; template<> struct equal_to<void> { template<typename T, typename U> auto operator()(T&& x, U&& y) const -> decltype(forward<T>(x) == forward<U>(y)); using is_transparent = true_type; }; template<> struct not_equal_to<void> { template<typename T, typename U> auto operator()(T&& x, U&& y) const -> decltype(forward<T>(x) != forward<U>(y)); using is_transparent = true_type; }; template<> struct greater<void> { template<typename T, typename U> auto operator()(T&& x, U&& y) const -> decltype(forward<T>(x) > forward<U>(y)); using is_transparent = true_type; }; template<> struct less<void> { template<typename T, typename U> auto operator()(T&& x, U&& y) const -> decltype(forward<T>(x) < forward<U>(y)); using is_transparent = true_type; }; template<> struct greater_equal<void> { template<typename T, typename U> auto operator()(T&& x, U&& y) const -> decltype(forward<T>(x) >= forward<U>(y)); using is_transparent = true_type; }; template<> struct less_equal<void> { template<typename T, typename U> auto operator()(T&& x, U&& y) const -> decltype(forward<T>(x) <= forward<U>(y)); using is_transparent = true_type; }; _namespace_end(std) #include <stdimpl/functional_comparators-inl.h> #endif /* _STDIMPL_FUNCTIONAL_COMPARATORS_H_ */
true
117e9249076e2fe212e599ccabba85490c65eadb
C++
vreverdy/bit-algorithms
/include/copy_backward.hpp
UTF-8
1,258
2.515625
3
[ "BSD-3-Clause" ]
permissive
// ============================= COPY BACKWARD ============================= // // Project: The Experimental Bit Algorithms Library // Name: copy_backward.hpp // Description: bit_iterator overloads for std::copy_backward // Creator: Vincent Reverdy // Contributor(s): // License: BSD 3-Clause License // ========================================================================== // #ifndef _COPY_BACKWARD_HPP_INCLUDED #define _COPY_BACKWARD_HPP_INCLUDED // ========================================================================== // // ============================== PREAMBLE ================================== // // C++ standard library // Project sources // Third-party libraries // Miscellaneous namespace bit { // ========================================================================== // // Status: to do template <class BidirIt1, class BidirIt2> constexpr bit_iterator<BidirIt2> copy_backward(bit_iterator<BidirIt1> first, bit_iterator<BidirIt1> last, bit_iterator<BidirIt2> d_last) { (first, last); return d_last; } // ========================================================================== // } // namespace bit #endif // _COPY_BACKWARD_HPP_INCLUDED // ========================================================================== //
true
6f3461a74f27710fefed148d6921734f803cfe67
C++
adi618/Data-Structures
/Data Structures/Data Structures/Queue.cpp
UTF-8
2,214
4.1875
4
[]
no_license
#include <iostream> namespace { struct Node { int value; Node* next; Node(int value) :value(value), next(nullptr) {} }; } class Queue { private: Node* first; Node* last; int totalNodes; public: Queue() : first(nullptr), last(nullptr), totalNodes(0) {} int getTotalNodes() { return totalNodes; } void enqueue(int value) { Node* newNode = new Node(value); totalNodes++; if (first == nullptr) { first = newNode; last = newNode; return; } last->next = newNode; last = newNode; } int dequeue() { if (first == nullptr) return 0; if (first == last) last = nullptr; first = first->next; totalNodes--; } int peek() { if (first == nullptr) return 0; return first->value; } bool isEmpty() { return totalNodes == 0; } void printQueue() { if (totalNodes == 0) { std::cout << " [empty]"; } else { Node* temp = first; std::cout << temp->value; temp = temp->next; while (temp != nullptr) { std::cout << " <- " << temp->value; temp = temp->next; } } } ~Queue() { Node* toDelete = first; while (first != nullptr) { first = first->next; delete toDelete; toDelete = first; } } }; void queue() { int option; int value; Queue myQueue; while (true) { system("cls"); std::cout << "\n\n\tQueue: "; myQueue.printQueue(); std::cout << "\n\n\tChoose an option:" << "\n\t\t1 - .dequeue()" << "\n\t\t2 - .enqueue()" << "\n\t\t3 - .top()" << "\n\t\t10 - Exit"; std::cout << "\n\n\t\tOption: "; std::cin >> option; if (option == 1) { std::cout << "\n\t\tEnter the number: "; std::cin >> value; myQueue.enqueue(value); } else if (option == 2) { if (myQueue.isEmpty()) { std::cout << "\n\t\tQueue is empty!"; std::cout << "\n\n\t\t"; system("pause"); } myQueue.dequeue(); } else if (option == 3) { if (myQueue.isEmpty()) std::cout << "\n\t\tQueue is empty!"; else std::cout << "\n\t\tFirst in queue: " << myQueue.peek(); std::cout << "\n\n\t\t"; system("pause"); } else if (option == 10) return; else { std::cout << "\n\t\tInvalid option!\n\n"; system("pause"); } } }
true
19ee76f3909ad0d209a2beecb661eda45ee9b51c
C++
progcomposantsEJP/dev2
/developpement2/Composant2/Composant2.cpp
UTF-8
3,851
2.75
3
[]
no_license
// Composant2.cpp : Defines the exported functions for the DLL application. // /* // This is an example of an exported variable COMPOSANT2_API int nComposant2=0; // This is an example of an exported function. COMPOSANT2_API int fnComposant2(void) { return 42; } // This is the constructor of a class that has been exported. // see Composant2.h for the class definition CComposant2::CComposant2() { return; } */ // Composant2.cpp : Defines the exported functions for the DLL application. // //#include "stdafx.h" #include "Composant2.h" #include "Composant6.h" #include "Composant7.h" //#include "Composant2Version.h" using namespace std; const double SPOT = 100; Composant2::Composant2(){ }; double Composant2::doMonteCarlo(string typePayOff, double maturity, double strike, int nbIterations){ string s1= "NEGATIVE VALUE"; string s2= "MISSED DATA"; if (typePayOff.empty() || maturity == NULL || strike == NULL || nbIterations == NULL) throw s2; else if (maturity < 0 || strike < 0 || nbIterations < 0) throw s1; vector<double> vecteurPayOff(nbIterations); double sumPayOff = 0; //double* vectorFromC6_tmp; vector<double> vectorFromC6_tmp(maturity); double payOff_tmp; double esperancePayOff; //Recuperation des n PayOff; soit n le nbIterations. for (int i = 0; i < nbIterations; i++){ vectorFromC6_tmp = getPath(maturity, SPOT);//Recuperation des 504 VA payOff_tmp = getPricePath(typePayOff, vectorFromC6_tmp, strike, maturity);//Alimentation du C7 par le tableau des 504 VA, puis recuperation du payOff associe en fonction du type d option traite (asiat, euro ect.) vecteurPayOff.push_back(payOff_tmp);//Ajout du payOff dans le vecteur de PayOffs } //Calcul de la somme des PayOff for (vector<double>::iterator j = vecteurPayOff.begin(); j != vecteurPayOff.end(); ++j){ sumPayOff = sumPayOff + *j; } esperancePayOff = sumPayOff / nbIterations; //EXCEPTION si l esperance du payoff est manquante ou negative if (esperancePayOff == NULL )// || typePayOff.empty() || maturity == NULL || strike == NULL || nbIterations == NULL) throw s2; else if (esperancePayOff < 0 )//|| maturity < 0 || strike < 0 || nbIterations < 0) throw s1; //Calcul de l'esperance : Somme PayOff / Nb PayOff return esperancePayOff; }; //double* Composant2::getPath(){ vector<double> Composant2::getPath(double maturity, double spot){ //Recupere un vector depuis Composant6::getChemin(int jours, double spot) string s1 = "MISSED DATA", s2 = "NEGATIVE VALUE"; vector<double> path(maturity); path = getChemin(maturity, spot); if(path.size()<maturity) throw s1; // EXCEPTION si une des valeur du tableau est manquante ou negative. for (int z(0); z<path.size(); z++) { if (path[z] < 0) throw s2; } return path; }; double Composant2::getPricePath(string typePayOff, vector<double> vecteur, double strike, double maturity){ //Recupere un double depuis Composant7::pricePath(String typePayOff, double path[], double strike, double maturity) double priceOfPath = 0; //Conversion du vector en double* double* path = &vecteur[0]; string error1="MISSED DATA", error2 = "NEGATIVE VALUE", error3 = "VALUE GREATER THAN 1000000"; //priceOfPath = Composant7::pricePath(typePayOff, path, strike, maturity); - TODO priceOfPath = pricePath(typePayOff, path, strike, maturity); //EXCEPTION si la valeur retourne par C7 est manquante, negative ou > 1000000 if (priceOfPath == NULL || strike == NULL || maturity == NULL) throw error1; else if (priceOfPath < 0 || strike < 0 || maturity < 0) throw error2; else if (priceOfPath > 1000000)// || strike > 1000000 || maturity < 1000000) throw error3; return priceOfPath; }; /* char * Composant2::getComposant2Version() { return "Composant 2 version " COMPOSANT_VERSION_STR; }; */
true
648fa3d8b11f43644793ab81baa91c71ed12cf4b
C++
DoctorLai/ACM
/leetcode/949. Largest Time for Given Digits/949.cpp
UTF-8
819
3.484375
3
[]
no_license
// https://helloacm.com/algorithms-to-compute-the-largest-time-for-given-digits/ // https://leetcode.com/problems/largest-time-for-given-digits/ // EASY, PERMUTATION class Solution { public: string largestTimeFromDigits(vector<int>& A) { sort(begin(A), end(A)); string ans = getTime(A); while (next_permutation(begin(A), end(A))) { auto time = getTime(A); ans = max(ans, time); } return ans; } private: string getTime(vector<int>& A) { int hour = A[0] * 10 + A[1]; int minute = A[2] * 10 + A[3]; if ((hour > 23) || (minute >= 60)) return ""; return std::to_string(A[0]) + std::to_string(A[1]) + ":" + std::to_string(A[2]) + std::to_string(A[3]); } };
true
3aa0eb7480723d6c117269e814721b1ae3d429cb
C++
CallyyllaC/LeapMotion-Telemanipulation
/vm_leap/src/vmleap.cpp
UTF-8
1,888
2.734375
3
[]
no_license
// // Depricated, no longer required due to using ros network to connect multiple PC's for dual leaps // #include "ros/ros.h" #include "leap_motion/Human.h" #include "leap_motion/Hand.h" #include "geometry_msgs/Point.h" #include "leap_motion/Gesture.h" #include "vm_leap/Modified_leap.h" class VMLeap { private: ros::NodeHandle node; ros::Publisher publisher; ros::Subscriber subscriber; void Leap_filteredCallback(const leap_motion::Human::ConstPtr& msg) { leap_motion::Hand handLeft = msg->left_hand; leap_motion::Hand handRight = msg->right_hand; //create output message vm_leap::Modified_leap output; //get the palm point objects geometry_msgs::Point leftPalm = handLeft.palm_center; geometry_msgs::Point rightPalm = handRight.palm_center; //Get center of mass of both hands output.left_location = {leftPalm.x, leftPalm.y, leftPalm.z}; output.right_location = {rightPalm.x, rightPalm.y, rightPalm.z}; //Get the roll, pitch and yaw of both hands in radians output.left_orientation = {handLeft.roll, handLeft.pitch, handLeft.yaw}; output.right_orientation = {handRight.roll, handRight.pitch, handRight.yaw}; output.grab = handLeft.grab_strength; output.pinch = handRight.pinch_strength; publisher.publish(output); } public: VMLeap() { //Topic you want to publish publisher = node.advertise<vm_leap::Modified_leap>("vm_leap", 1); //Topic you want to subscribe subscriber = node.subscribe("/leap2/leap_motion/leap_filtered", 1, &VMLeap::Leap_filteredCallback, this); } };//End of class VMLeap int main(int argc, char **argv) { //Initiate ROS ros::init(argc, argv, "vmleap"); //Create an object of class VMLeap that will take care of everything VMLeap VMLeapObj; ros::spin(); return 0; }
true
0efe3e6b31ee672f6b599edbc8d1980be3a4c617
C++
dingge/LightTheMaze
/Classes/Game/Mechanism/MechanismCollisionNode/PotalMechainismCell.h
GB18030
1,397
2.53125
3
[]
no_license
/******************************************************************** date : 2016/01/30 15:30 author: TLeaves e-mail: 664570530@qq.com github: https://github.com/TLeaves *********************************************************************/ #ifndef POTALMECHAINISMCELL_H_ #define POTALMECHAINISMCELL_H_ #include "Game/Mechanism/MechanismCollisionNode/MechanismCollisionNode.h" class LightSpriteNode; /*ײ룬⾫鲻ײӦ*/ #define POTAL_COLLISION_BITMASK 0x00000000 /** * صԪ * һӣ * ⾫ĽӴⲢӦź */ class PotalMechainismCell : public MechanismCollisionNode { public: static PotalMechainismCell* create(const std::string& fileName); virtual void processCollision(LightSpriteNode* node, const ContactInfo& info)override; virtual void update(float delta)override; //һελΪǰλ void resetPosition(); protected: PotalMechainismCell() : m_isTrigger(false), m_particle(nullptr), m_isLeaved(false) {} virtual ~PotalMechainismCell() {} bool init(const std::string& fileName); private: cocos2d::Vec2 m_prePos; public: bool m_isTrigger; //־ǷѽӴ bool m_isLeaved; //־Ƿ뿪󣬱νӴ cocos2d::ParticleSystemQuad* m_particle; }; #endif // POTALMECHAINISMCELL_H_
true
f81b62ddfacd11d8fb74428bc38e094b8c16dd9f
C++
jejewu/nphard_2020_fall
/hw4/socks_server.cpp
UTF-8
11,703
2.625
3
[]
no_license
#include "socks_server.h" class SocksConnect : public enable_shared_from_this<SocksConnect>{ private: shared_ptr<boost::asio::ip::tcp::socket> cli_socket; boost::asio::ip::tcp::socket ser_socket; SocksReq req; array<char, MAXLEN> bytes; public: SocksConnect(boost::asio::ip::tcp::socket socket, SocksReq request): cli_socket(make_shared<boost::asio::ip::tcp::socket>(move(socket))), ser_socket(ioservice), req(request){} void start(int op){ bytes.fill('\0'); if(op == 1) //Connect do_connect(); else if(op == 2) //Bind do_accept(); else SocksReply(req, false); } private: void SocksReply(SocksReq req, bool granted){ auto self(shared_from_this()); string msg; msg += '\0'; msg += (granted ? 0x5A : 0x5B); for(int i=0; i<2; i++){ msg += req.DSTPORT[i]; } for(int i=0; i<4; i++){ msg += req.DSTIP[i]; } cli_socket->async_send(boost::asio::buffer(msg), [this, self, msg](boost::system::error_code ec, size_t){}); } void SocksRedirect(bool enableser_socket, bool enablecli_socket){ auto self(shared_from_this()); if(enableser_socket){ ser_socket.async_read_some(boost::asio::buffer(bytes, bytes.size()), [this, self](boost::system::error_code ec, size_t length){ if(!ec){ cli_socket->async_send(boost::asio::buffer(bytes, length), [this, self](boost::system::error_code ec, size_t){}); bytes.fill('\0'); SocksRedirect(1, 0); } if(ec == boost::asio::error::eof){ cli_socket->close(); } }); } if(enablecli_socket){ cli_socket->async_read_some(boost::asio::buffer(bytes, bytes.size()), [this, self](boost::system::error_code ec, size_t length) { if(!ec){ ser_socket.async_send(boost::asio::buffer(bytes, length), [this, self](boost::system::error_code ec, size_t){}); bytes.fill('\0'); SocksRedirect(0, 1); } }); } } void do_connect(){ auto self(shared_from_this()); boost::asio::ip::tcp::endpoint ep(boost::asio::ip::address::from_string(req.D_IP), req.D_PORT); ser_socket.async_connect(ep, [this, self](const boost::system::error_code &ec){ if(!ec){ cout << "connection build to " << req.D_IP << ":" << req.D_PORT << endl; SocksReply(req, true); SocksRedirect(1, 1); } else cout << "connect failed" << endl; }); } void do_accept(){ boost::asio::ip::tcp::acceptor tcp_acceptor(ioservice, boost::asio::ip::tcp::endpoint(boost::asio::ip::tcp::v4(), 0)); tcp_acceptor.listen(); int b_port = tcp_acceptor.local_endpoint().port(); req.D_PORT = b_port; req.DSTPORT[0] = b_port/256; req.DSTPORT[1] = b_port%256; for(int i=0; i<4; i++) req.DSTIP[i] = 0; SocksReply(req, true); try{ tcp_acceptor.accept(ser_socket); SocksReply(req, true); SocksRedirect(1, 1); } catch (boost::system::error_code ec){ cout << "failed: " << ec << endl; } } }; class SocksSession : public enable_shared_from_this<SocksSession>{ private: boost::asio::ip::tcp::socket tcp_socket; boost::asio::ip::tcp::socket rsock; array<char, MAXLEN> bytes; public: SocksSession(boost::asio::ip::tcp::socket socket) : tcp_socket(move(socket)), rsock(ioservice) {} void start() { do_read(); } private: bool CheckFW(SocksReq req){ char D_Mode = req.CD == 1 ? 'c' : 'b'; ifstream infile("socks.conf"); string line; while(getline(infile, line)){ string str, mode, ip; stringstream ss(line); vector<string> sub_ip; ss >> str; ss >> mode; ss >> ip; if(str == "permit"){ if(mode[0] == D_Mode){ stringstream ssip(ip); string s; while(getline(ssip, s, '.')) sub_ip.push_back(s); for(int i=0; i<4; i++){ s = to_string(Ch2Int(req.DSTIP, i, 1)); if(sub_ip[i] != s && sub_ip[i] != "*") break; if(i == 3) return 1; } } } } return 0; } int Ch2Int(string data, int begin, int bytes_num){ int power = 1, ans = 0; for(int i=begin+bytes_num-1; i>=begin; i--){ char ch = data[i]; for(int j=0; j<8; j++){ ans += ((ch & (1 << j))? power : 0); power *= 2; } } return ans; } void printinfo(SocksReq req){ cout << "<S_IP>: " << req.S_IP << endl; cout << "<S_PORT>: " << req.S_PORT << endl; cout << "<D_IP>: " << req.D_IP << endl; cout << "<D_PORT>: " << req.D_PORT << endl; cout << "<Command>: "; if(req.CD == 1) cout << "CONNECT" << endl; else if(req.CD == 2) cout << "BIND" << endl; } void do_read(){ auto self(shared_from_this()); tcp_socket.async_read_some(boost::asio::buffer(bytes), [this, self](boost::system::error_code ec, size_t length) { if (!ec){ string data(length, '\0'); for(int i=0; i<length; i++) data[i] = bytes[i]; bytes.fill('\0'); //parsing SocksReq new_req; new_req.VN = data[0]; new_req.CD = data[1]; new_req.D_PORT = Ch2Int(data, 2, 2); for(int i=0; i<2; i++){ new_req.DSTPORT[i] = data[i+2]; } new_req.D_IP = ""; for(int i=0; i<4; i++){ new_req.D_IP += to_string(Ch2Int(data, i+4, 1)); new_req.D_IP += (i == 3 ? "" : "."); new_req.DSTIP[i] = data[i+4]; } bool is_socks4a = 1; for(int i=0; i<4; i++){ if(i != 3){ if(new_req.DSTIP[i] != 0){ is_socks4a = 0; break; } } else{ if(new_req.DSTIP[i] == 0){ is_socks4a = 0; break; } } } new_req.DOMAIN_NAME = ""; if(is_socks4a){ int pos = 8; while(data[pos++] != 0); while(pos != length-1) new_req.DOMAIN_NAME += data[pos++]; cout << new_req.DOMAIN_NAME << endl; boost::asio::ip::tcp::resolver resolv{ioservice}; auto results = resolv.resolve(new_req.DOMAIN_NAME, to_string(new_req.D_PORT)); for(auto entry : results) { if(entry.endpoint().address().is_v4()) { new_req.D_IP = entry.endpoint().address().to_string(); stringstream ss(new_req.D_IP); string s; for(int i=0; i<4; i++){ getline(ss, s, '.'); new_req.DSTIP[i] = Ch2Int(s, 0, s.length()); } break; } } } boost::asio::ip::tcp::endpoint remote_ep = tcp_socket.remote_endpoint(); boost::asio::ip::address remote_ad = remote_ep.address(); new_req.S_IP = remote_ad.to_string(); new_req.S_PORT = (int)remote_ep.port(); printinfo(new_req); if(new_req.CD == 1){ //socks connect if(CheckFW(new_req)){ cout << "<Reply> Accept" << endl << endl; make_shared<SocksConnect>(move(tcp_socket), new_req)->start(1); } else{ cout << "<Reply> Reject" << endl << endl; make_shared<SocksConnect>(move(tcp_socket), new_req)->start(0); } } else if(new_req.CD == 2){ //socks bind if(CheckFW(new_req)){ cout << "<Reply> Accept" << endl << endl; make_shared<SocksConnect>(move(tcp_socket), new_req)->start(2); } else{ cout << "<Reply> Reject" << endl << endl; make_shared<SocksConnect>(move(tcp_socket), new_req)->start(0); } } do_read(); } }); } }; class SocksServer { private: boost::asio::ip::tcp::acceptor tcp_acceptor; boost::asio::ip::tcp::socket tcp_socket; public: SocksServer(short port) : tcp_acceptor(ioservice, boost::asio::ip::tcp::endpoint(boost::asio::ip::tcp::v4(), port)), tcp_socket(ioservice) { do_accept(); } private: void do_accept(){ boost::asio::socket_base::reuse_address option(true); tcp_acceptor.set_option(option); tcp_acceptor.async_accept(tcp_socket, [this](boost::system::error_code ec) { if (!ec) { ioservice.notify_fork(boost::asio::io_service::fork_prepare); if(fork() == 0){ ioservice.notify_fork(boost::asio::io_service::fork_child); make_shared<SocksSession>(move(tcp_socket))->start(); } else{ ioservice.notify_fork(boost::asio::io_service::fork_parent); tcp_socket.close(); do_accept(); } } do_accept(); }); } }; int main(int argc, char* argv[]) { if (argc != 2) { cerr << "./http_server [port]" << endl; return 69; } unsigned short port = atoi(argv[1]); signal(SIGCHLD, SIG_IGN); SocksServer server(port); ioservice.run(); }
true
903932875ee6760fc18d85b1e205c6e1e31ea2b4
C++
QuantumBob/BlankGL
/src/cWindow.cpp
UTF-8
5,169
2.515625
3
[]
no_license
#include "cWindow.h" #include "cApp.h" //#include <gl/gl.h> //#include "gl/glext.h" //#include "gl/wglext.h" extern LRESULT ImGui_ImplWin32_WndProcHandler(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam); /////////////////////////////////////////////////////////// cWindow::cWindow() : m_RC(0), m_hwnd(0), m_DC(0), m_window_class(nullptr) { config.width = 720; config.height = 720; config.posX = CW_USEDEFAULT; config.posY = 0; config.windowed = true; style = CS_OWNDC | WS_CAPTION | WS_SYSMENU | WS_CLIPSIBLINGS | WS_CLIPCHILDREN | WS_MAXIMIZEBOX | WS_MINIMIZEBOX | WS_SIZEBOX; } /////////////////////////////////////////////////////////// cWindow::~cWindow() { } /////////////////////////////////////////////////////////// HWND cWindow::CreateFake(HINSTANCE hInstance) { m_window_class = MAKEINTATOM(RegisterWindowClass(hInstance)); if (m_window_class == 0) { cApp::App()->ShowMessage("RegisterClassEx() failed.", " in cWindow::CreateFake()"); return NULL; } // create temporary window HWND fakeWND = CreateWindow(m_window_class, // class is set above "Fake Window", // title of fake window style, // set in constructor 0, 0, // position x, y 1, 1, // width, height NULL, NULL, // parent window, menu hInstance, NULL); // instance, param return fakeWND; } /////////////////////////////////////////////////////////// HWND cWindow::Create(HINSTANCE hInstance, int nCmdShow) { if (m_window_class == 0) { m_window_class = MAKEINTATOM(RegisterWindowClass(hInstance)); } if (m_window_class == 0) { cApp::App()->ShowMessage("RegisterClassEx() failed.", " in cWindow::Create()"); return NULL; } if (config.windowed == true) { AdjustSize(); Center(); } // create a new window and context m_hwnd = CreateWindow( m_window_class, "OpenGL Window", // class name, window name style, // styles config.posX, config.posY, // posx, posy. If x is set to CW_USEDEFAULT y is ignored config.width, config.height, // width, height NULL, NULL, // parent window, menu hInstance, this); // instance, param if (m_hwnd == NULL) { return NULL; } return m_hwnd; } /////////////////////////////////////////////////////////// void cWindow::Show() { ShowWindow(m_hwnd, SW_SHOWDEFAULT); // WM_SIZE called here } /////////////////////////////////////////////////////////// ATOM cWindow::RegisterWindowClass(HINSTANCE hInstance) { WNDCLASSEX wcex; ZeroMemory(&wcex, sizeof(wcex)); wcex.cbSize = sizeof(wcex); wcex.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC; wcex.lpfnWndProc = s_WindowProcedure; wcex.hInstance = hInstance; wcex.hCursor = LoadCursor(NULL, IDC_ARROW); wcex.lpszClassName = "Core"; return RegisterClassEx(&wcex); } /////////////////////////////////////////////////////////// HDC cWindow::GetWindowDC() { return m_DC; } /////////////////////////////////////////////////////////// // Adjust window's size for non-client area elements like border and title bar void cWindow::AdjustSize() { RECT rect = { 0, 0, config.width, config.height }; AdjustWindowRect(&rect, style, false); config.width = rect.right - rect.left; config.height = rect.bottom - rect.top; } /////////////////////////////////////////////////////////// void cWindow::Center() { RECT primaryDisplaySize; SystemParametersInfo(SPI_GETWORKAREA, 0, &primaryDisplaySize, 0); // system taskbar and application desktop toolbars not included config.posX = (primaryDisplaySize.right - config.width) / 2; config.posY = (primaryDisplaySize.bottom - config.height) / 2; } /////////////////////////////////////////////////////////// void cWindow::Destroy() { wglMakeCurrent(NULL, NULL); if (m_RC) { wglDeleteContext(m_RC); } if (m_DC) { ReleaseDC(m_hwnd, m_DC); } if (m_hwnd) { DestroyWindow(m_hwnd); } } /////////////////////////////////////////////////////////// LRESULT cWindow::s_WindowProcedure(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { cWindow* p_this; if (message == WM_NCCREATE) { LPCREATESTRUCT lpcs = reinterpret_cast<LPCREATESTRUCT>(lParam); p_this = static_cast<cWindow*>(lpcs->lpCreateParams); // Put the value in a safe place for future use SetWindowLongPtr(hWnd, GWLP_USERDATA, reinterpret_cast<LONG_PTR>(p_this)); } else { p_this = reinterpret_cast<cWindow*>(GetWindowLongPtr(hWnd, GWLP_USERDATA)); } if (p_this) { return p_this->WindowProcedure(hWnd, message, wParam, lParam); } return DefWindowProc(hWnd, message, wParam, lParam); } /////////////////////////////////////////////////////////// LRESULT CALLBACK cWindow::WindowProcedure(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { // use win32 to process controls using handler below if (ImGui_ImplWin32_WndProcHandler(hWnd, message, wParam, lParam)) return true; switch (message) { case WM_KEYDOWN: if (wParam == VK_ESCAPE) { PostQuitMessage(0); } break; case WM_CLOSE: PostQuitMessage(0); break; case WM_SIZE: if (wParam != SIZE_MINIMIZED) { config.width = LOWORD(lParam); config.height = HIWORD(lParam); } break; default: return DefWindowProc(hWnd, message, wParam, lParam); } return 0; // message handled }
true
8b863a74d7faf1185b226bba4af6b41385b563bb
C++
tumtumtum/blaster
/src/Blaster/Url.cpp
UTF-8
3,083
2.796875
3
[]
no_license
// // Author: Thong Nguyen // Copyright (c) 2015 tum@kingstreetapps.com // #include "Url.h" #include <string.h> #include "http_parser.h" namespace Blaster { Url::Url() : hashValue(0) { } Url::Url(const string& url) : Url(url.c_str(), url.length()) { } Url::Url(const char* url) : Url(url, strlen(url)) { } Url::Url(const char* url, size_t len) : hashValue(0) { http_parser_url result; memset(&result, 0, sizeof(result)); http_parser_parse_url(url, strlen(url), 0, &result); if (result.field_set & (1 << UF_SCHEMA)) { scheme = string(url + result.field_data[UF_SCHEMA].off, result.field_data[UF_SCHEMA].len); } if (result.field_set & (1 << UF_HOST)) { host = string(url + result.field_data[UF_HOST].off, result.field_data[UF_HOST].len); } if (result.field_set & (1 << UF_PATH)) { path = string(url + result.field_data[UF_PATH].off, result.field_data[UF_PATH].len); } if (result.field_set & (1 << UF_QUERY)) { query = string(url + result.field_data[UF_QUERY].off, result.field_data[UF_QUERY].len); } if (result.field_set & (1 << UF_FRAGMENT)) { fragment = string(url + result.field_data[UF_FRAGMENT].off, result.field_data[UF_FRAGMENT].len); } if (result.field_set & (1 << UF_USERINFO)) { userinfo = string(url + result.field_data[UF_USERINFO].off, result.field_data[UF_USERINFO].len); } if (scheme == "http") { port = result.port == 0 ? 80 : result.port; } else if (scheme == "https") { port = result.port == 0 ? 443 : result.port; } else if (scheme == "ftp") { port = result.port == 0 ? 21 : result.port; } this->s = scheme + "://" + userinfo + host + (result.port == 0 ? "" : ":" + to_string(result.port)) + path + (query.length() > 0 ? "?" + query : "") + fragment; hashValue = std::hash<string>()(s); pathHashValue = std::hash<string>()(this->getPath()); } Url::~Url() { } const string& Url::getScheme() const { return this->scheme; } int Url::getPort() const { return this->port; } const string& Url::getHost() const { return this->host; } const string& Url::getPath() const { return this->path; } const string& Url::getQuery() const { return this->query; } const string& Url::getFragment() const { return this->fragment; } const string& Url::getUserInfo() const { return this->userinfo; } bool Url::operator==(const Url& url) const { if (this->hashValue != url.hashValue) { return false; } return this->s == url.s; } bool Url::operator!=(const Url& url) const { if (this->hashValue != url.hashValue) { return true; } return this->s != url.s; } bool Url::operator<(const Url& other) const { return this->s < other.s; } bool Url::operator>(const Url& other) const { return this->s > other.s; } Url::operator const string&() const { return s; } Url::operator string() const { return s; } const string& Url::toString() const { return s; } size_t Url::getHash() const { return hashValue; } size_t Url::getPathHash() const { return pathHashValue; } }
true
87f049d9ce8999455adb28a0d22a105ab7306809
C++
Loks-/competitions
/common/graph/tree/lca/tarjan_offline.h
UTF-8
1,187
2.640625
3
[ "MIT" ]
permissive
#pragma once #include "common/data_structures/disjoint_set.h" #include "common/graph/tree.h" #include <functional> #include <utility> #include <vector> namespace graph { namespace lca { // Tarjan algorithm for offline LCA // Time: O(g.Size() + q.Size()) template <class TGraph> inline std::vector<unsigned> TarjanOffline( const Tree<TGraph>& g, const std::vector<std::pair<unsigned, unsigned>>& q) { unsigned n = g.Size(); std::vector<unsigned> output(q.size()); std::vector<std::vector<std::pair<unsigned, unsigned>>> q2(n); for (unsigned i = 0; i < q.size(); ++i) { q2[q[i].first].push_back({q[i].second, i}); q2[q[i].second].push_back({q[i].first, i}); } std::vector<unsigned> va(n, CNone); ds::DisjointSet djs(n); std::function<void(unsigned)> dfs = [&](unsigned u) -> void { va[u] = u; for (auto v : g.Edges(u)) { if (va[v] == CNone) { dfs(v); djs.Union(v, u); va[djs.Find(u)] = u; } } for (auto p : q2[u]) { if (va[p.first] != CNone) { output[p.second] = va[djs.Find(p.first)]; } } }; dfs(g.GetRoot()); return output; } } // namespace lca } // namespace graph
true
54043dc52eab28fb501334d2dff1525bc506754b
C++
AlexLeoTW/Linux_C_Socket_Example
/client/client.cpp
UTF-8
1,432
3.046875
3
[ "MIT" ]
permissive
#include <stdio.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <unistd.h> #include <string.h> class myTCP { struct sockaddr_in server; int socketDescriptor = 0; public: myTCP(const char* address, int port) { server.sin_family = PF_INET; server.sin_addr.s_addr = inet_addr(address); /* Comvert to Binary */ server.sin_port = htons(port); /* Comvert to Binary */ socketDescriptor = socket(PF_INET, SOCK_STREAM, 0); /* IPV4, TCP, No Flag */ } bool connectServer() { return (connect(socketDescriptor, (struct sockaddr*)&server, sizeof(server))) == 0 ; } int sendMessages(char* buffer, int size) { return send(socketDescriptor, buffer, size, 0); } int readMessage(char* buffer, int size) { return read(socketDescriptor, buffer, size); } ~myTCP() { printf("closse connection" ); close(socketDescriptor); } }; int main() { char buffer[256] = {}; char flag = 'y'; myTCP tcp("127.0.0.1", 3500); tcp.connectServer(); printf("Please input needed messages: \n"); scanf ("%[^\n]%*c", buffer); printf("sending [%s] ...\n", buffer); tcp.sendMessages(buffer, sizeof(buffer)); memset(buffer, 0, sizeof(buffer)); tcp.readMessage(buffer, sizeof(buffer)); printf("Server Reply = [%s]\n", buffer); return 0; }
true
bdb79d51618b90fbe47b063f8f827a58d7621295
C++
HideakiImamura/MyCompetitiveProgramming
/ARC089/d.cpp
UTF-8
1,822
2.859375
3
[]
no_license
// // Created by 今村秀明 on 2018/02/21. // #include <stdio.h> #include <algorithm> const int max_n = 1e5; const int max_k = 1000; int a[3 * max_k][3 * max_k]; int s[2][max_k][max_k]; void print(int n, int m) { for (int i = 0; i < n; ++i) { for (int j = 0; j < m; ++j) { printf("%d ", a[i][j]); } printf("\n"); } printf("--------------------\n"); } int main() { int N, K; scanf("%d %d", &N, &K); for (int i = 0; i < 3 * K; i++) { for (int j = 0; j < 3 * K; j++) { a[i][j] = 0; } } for (int i = 0; i < K; ++i) { for (int j = 0; j < K; ++j) { s[0][i][j] = 0; s[1][i][j] = 0; } } for (int i = 0; i < N; ++i) { int x, y; char c; scanf("%d %d %c", &x, &y, &c); if (c == 'W') { y += K; } x %= 2 * K; y %= 2 * K; a[x][y] += 1; a[x + K][y + K] += 1; a[x + K][y] -= 1; a[x][y + K] -= 1; } //print(3 * K, 3 * K); for (int i = 0; i < 3 * K; ++i) { for (int j = 1; j < 3 * K; ++j) { a[i][j] += a[i][j - 1]; } } //print(3 * K, 3 * K); for (int i = 1; i < 3 * K; ++i) { for (int j = 0; j < 3 * K; ++j) { a[i][j] += a[i - 1][j]; } } //print(3 * K, 3 * K); for(int i = 0; i < 3 * K; ++i) { for(int j = 0; j < 3 * K; ++j) { int p = (i / K + j / K) % 2; s[p][i % K][j % K] += a[i][j]; } } int ans = 0; for(int p = 0; p < 2; ++p) { for (int i = 0; i < 2 * K; ++i) { for (int j = 0; j < 2 * K; ++j) { ans = std::max(ans, s[p][i][j]); } } } printf("%d\n", ans); return 0; }
true
cde3265f8bd147faf543ef5c911596af0e6df52d
C++
ABasitIrfan/Intensive-Programming-Cpp-Basics
/Factorial17.cpp
UTF-8
211
2.859375
3
[]
no_license
#include<stdio.h> #include<conio.h> main() { int a,b,num,count=1; printf("Enter Number: "); scanf("%d",&num); for(a=num;a>=1;a--) { count=count*a; } printf("Factorial Of %d Is %d",num,count); }
true
29f4abc20e31baf75eaf9b1429a5e6b24c24f443
C++
JoshBramlett/RDGE
/tests/physics/gjk_test.cpp
UTF-8
1,004
2.59375
3
[]
no_license
#include <gtest/gtest.h> #include <rdge/physics/collision.hpp> #include <rdge/math/vec2.hpp> #include <rdge/math/intrinsics.hpp> #include <rdge/physics/shapes/circle.hpp> #include <rdge/physics/shapes/polygon.hpp> #include <exception> namespace { using namespace rdge; using namespace rdge::math; using namespace rdge::physics; TEST(GJKTest, VerifyIntersection) { // TODO Add more tests polygon::PolygonData data1; data1[0] = { 4.f, 11.f }; data1[1] = { 9.f, 9.f }; data1[2] = { 4.f, 5.f }; polygon::PolygonData data2; data2[0] = { 5.f, 7.f }; data2[1] = { 12.f, 7.f }; data2[2] = { 7.f, 3.f }; data2[3] = { 10.f, 2.f }; polygon p1(data1, 3); polygon p2(data2, 4); gjk test1(&p1, &p2); EXPECT_TRUE(test1.intersects()); circle c1({ 4.f, 8.f }, 1.1f); circle c2({ 4.f, 8.f }, 1.5f); gjk test2(&p2, &c1); gjk test3(&p2, &c2); EXPECT_FALSE(test2.intersects()); EXPECT_TRUE(test3.intersects()); } } // namespace rdge
true
b6b99b3e04e98cf456ec9b20a722b902a9c95f5c
C++
alvls/mp1-2021-1
/Krainev_AA/task4/Source.cpp
UTF-8
23,469
2.859375
3
[]
no_license
#include <iostream> #include <string> #include <vector> #include <iostream> #include <clocale> #include <windows.h> #include <fstream> #include <sstream> #include <cctype> #include <cstring> #include <locale> using namespace std; void printMenu(); void welcomeMessege(); struct Date { unsigned short int day; unsigned short int month; unsigned short int year; Date& operator=(const Date& date); friend ostream& operator<<(ostream& out, const Date& date) { out << date.day << ' ' << date.month << ' ' << date.year; return out; } Date(int otherDay = 0, int otherMonth = 0, int otherYear = 0) : year(otherYear), month(otherMonth), day(otherDay){ }; }; Date& Date::operator=(const Date& date) { if (this != &date) { day = date.day; month = date.month; year = date.year; } return *this; } struct Weight { Date dateInWeight; double weightMember; Weight(Date otherDate, double otherWeight) :dateInWeight(otherDate), weightMember(otherWeight) {}; Weight& operator=(const Weight& weight); friend ostream& operator<<(ostream& out, Weight& weight) { out << weight.dateInWeight.day << ' ' << weight.dateInWeight.month << ' ' << weight.dateInWeight.year << ' ' << weight.weightMember; return out; } }; Weight& Weight::operator=(const Weight& weight) { if (this != &weight) { dateInWeight = weight.dateInWeight; weightMember = weight.weightMember; } return *this; } Date startDateOfObservations; struct memberOfFamily { string name; vector <Weight> informationAboutWeightDate; memberOfFamily(string nameMember) { name = nameMember; }; memberOfFamily& operator=(const memberOfFamily& member); friend ostream& operator<<(ostream& out, memberOfFamily& member) { out << member.name << endl; for (unsigned int i = 0; i < member.informationAboutWeightDate.size(); i++) { out << member.informationAboutWeightDate[i] << endl; } return out; } void Observation(unsigned short int otherDay, unsigned short int otherMonth, unsigned short int otherYear, double otherWeight); int searchMember(unsigned short int otherDay, unsigned short int otherMonth, unsigned short int otherYear); }; memberOfFamily& memberOfFamily::operator=(const memberOfFamily& member) { if (this != &member) { informationAboutWeightDate = member.informationAboutWeightDate; name = member.name; } return *this; } int memberOfFamily::searchMember(unsigned short int otherDay, unsigned short int otherMonth, unsigned short int otherYear) { for (unsigned int j = 0; j < informationAboutWeightDate.size(); j++) { if (informationAboutWeightDate[j].dateInWeight.day == otherDay && informationAboutWeightDate[j].dateInWeight.month == otherMonth && informationAboutWeightDate[j].dateInWeight.year == otherYear) { return j; } } return false; } void memberOfFamily::Observation(unsigned short int otherDay, unsigned short int otherMonth, unsigned short int otherYear, double otherWeight) { unsigned int checkSearchMember = searchMember(otherDay, otherMonth, otherYear); if (checkSearchMember == false) { Date date(otherDay, otherMonth, otherYear); Weight weight(date, otherWeight); informationAboutWeightDate.push_back(weight); //пуляем в конец вектора } else { informationAboutWeightDate[checkSearchMember].weightMember = otherWeight; } } class floorScales { //класс напольные весы private: vector <memberOfFamily> Scale; public: floorScales() {}; floorScales(vector <memberOfFamily> other) { Scale = other; } floorScales(string filename); void setNameMember(string nameMember); void setTheStartDateOfObservations(unsigned short int day, unsigned short int month, unsigned short int year); Date getTheStartDateOfObservations(); void setObservation(unsigned short int day, unsigned short int month, unsigned short int year, double weight, string name); double getObservation(unsigned short int day, unsigned short int month, unsigned short int year, string nameMember); double getAverageWeightOfFamilyMember(string NameMember); double getAverageWeightOfFamilyMember(string otherNameMember, unsigned short int otherMonth, unsigned short int otherYear); double getMinimumWeightOfFamilyMember(string nameMember); double getMinimumWeightOfFamilyMember(string otherNameMember, unsigned short int otherMonth, unsigned short int otherYear); double getMaximumWeightOfFamilyMember(string nameMember); double getMaximumWeightOfFamilyMember(string otherNameMember, unsigned short int otherMonth, unsigned short int otherYear); void printDateOfMinimumWeightOfFamilyMember(string nameMember); void printDateOfMinimumWeightOfFamilyMember(string otherNameMember, unsigned short int otherMonth, unsigned short int otherYear); void printDateOfMaximumWeightOfFamilyMember(string nameMember); void printDateOfMaximumWeightOfFamilyMember(string otherNameMember, unsigned short int otherMonth, unsigned short int otherYear); void saveFile(); }; void floorScales::setNameMember(string nameMember) { memberOfFamily newMember(nameMember); //помещаем в конец вектора структуру с новым именем Scale.push_back(newMember); } void floorScales::setTheStartDateOfObservations(unsigned short int day, unsigned short int month, unsigned short int year) { if (startDateOfObservations.day == 0 && startDateOfObservations.month == 0 && startDateOfObservations.year == 0) { //cout << "Начальная дата измерения не была задана" << endl; startDateOfObservations.day = day; startDateOfObservations.month = month; startDateOfObservations.year = year; } else { cout << "Начальная дата измерений уже задана. Если вы хотите ее изменить, придется удалить файл. Данные будут потеряны! (Для этого выберите соотвествующий пункт меню)" << endl; } } int main() { setlocale(LC_ALL, "rus"); welcomeMessege(); int choice; string nameMember; string str = "Scales.txt"; floorScales Scale(str); while (1) { printMenu(); cin >> choice; switch (choice) { case 1: { cout << "Введите имя нового пользователя" << endl; cin >> nameMember; cout << nameMember << endl; Scale.setNameMember(nameMember); break; } case 2: { cout << "Установить начальную дату наблюдений" << endl; unsigned short int day, month, year; cout << "Введите день: " << endl; cin >> day; cout << "Введите месяц: " << endl; cin >> month; cout << "Введите год: " << endl; cin >> year; Scale.setTheStartDateOfObservations(day, month, year); break; } case 3: { cout << "Начальная дата наблюдений: " << endl; cout << Scale.getTheStartDateOfObservations() << endl; break; } case 4: { unsigned short int day, month, year; if (((startDateOfObservations.day == 0 && startDateOfObservations.month == 0) && startDateOfObservations.year == 0)) { cout << "Задайте сначала начальную дату наблюдений." << endl; } else { cout << "Сейчас вы сможете ввести новые измерения для пользователя " << endl; cout << "Введите имя: "; cin >> nameMember; cout << "Введите день : "; cin >> day; cout << "Введите месяц: "; cin >> month; cout << "Введите год: "; cin >> year; if ((year < startDateOfObservations.year) || (year == startDateOfObservations.year) && (month < startDateOfObservations.month) || (year == startDateOfObservations.year) && (month == startDateOfObservations.month) && (day < startDateOfObservations.day)) { cout << "Введенная дата раньше начала наблюдений." << endl; } else { cout << "Введите вес: "; double weight; cin >> weight; Scale.setObservation(day, month, year, weight, nameMember); } } break; } case 5: { unsigned short int day, month, year; cout << "А сейчас узнаем вес у пользователя в выбранную дату" << endl; cout << "Имя: "; cin >> nameMember; cout << "День: "; cin >> day; cout << "Месяц: "; cin >> month; cout << "год: "; cin >> year; cout << "Вес в выбранную дату: " << Scale.getObservation(day, month, year, nameMember) << " кг." << endl; break; } case 6: { unsigned short int day, month, year; cout << "Найдем средний вес члена семьи в выбранном месяце или за всю историю наблюдений" << endl; cout << "Введите имя: " << endl; cin >> nameMember; cout << "Выберите промежуток времени " << endl; cout << "1. За все время" << endl; cout << "2. В выбранном месяце" << endl; cin >> choice; switch (choice) { case 1: { cout << "Средний вес за все время наблюдений: " << Scale.getAverageWeightOfFamilyMember(nameMember) << endl; break; } case 2: { cout << "Введите месяц: "; cin >> month; cout << "Введите год: "; cin >> year; cout << "Средний вес в выбранное время: " << Scale.getAverageWeightOfFamilyMember(nameMember, month, year) << endl; break; } } break; } case 7: { unsigned short int day, month, year; cout << "Введите имя: " << endl; cin >> nameMember; cout << "1. За все время" << endl; cout << "2. В выбранном месяце" << endl; cin >> choice; switch (choice) { case 1: { cout << "Минимальный вес за все время наблюдений: " << Scale.getMinimumWeightOfFamilyMember(nameMember) << endl; Scale.printDateOfMinimumWeightOfFamilyMember(nameMember); break; } case 2: { cout << "Введите месяц: "; cin >> month; cout << "Введите год: "; cin >> year; cout << "Минимальный вес в выбраное время: " << Scale.getMinimumWeightOfFamilyMember(nameMember, month, year) << endl; Scale.printDateOfMinimumWeightOfFamilyMember(nameMember, month, year); break; } } break; } case 8: { unsigned short int day, month, year; //найти максимальный вес члена семьи в выбранном месяце или за всю историю наблюдений и дату, когда он наблюдался, cout << "Введите имя: " << endl; cin >> nameMember; cout << "1. За все время" << endl; cout << "2. В выбранном месяце" << endl; cin >> choice; switch (choice) { case 1: { cout << "Максимальный вес за все время наблюдений: " << Scale.getMaximumWeightOfFamilyMember(nameMember) << endl; Scale.printDateOfMaximumWeightOfFamilyMember(nameMember); break; } case 2: { cout << "Введите месяц: "; cin >> month; cout << "Введите год: "; cin >> year; cout << "Максимальный вес в выбранное время: " << Scale.getMaximumWeightOfFamilyMember(nameMember, month, year) << endl; Scale.printDateOfMaximumWeightOfFamilyMember(nameMember, month, year); break; } } break; } case 9: { Scale.saveFile(); break; } case 10: {//очищение файлика те его удаление if (remove("Scales.txt") != 0) { cout << "Ошибка удаления файла."; } else cout << "Файл очищен, перезапустите программу!" << endl; break; } case 11: { cout << "До встречи!" << endl; return 0; } } } } floorScales::floorScales(string filename) { ifstream in(filename); unsigned short int startDay = 0; unsigned short int startMonth = 0; unsigned short int startYear = 0; unsigned short int day; unsigned short int month; unsigned short int year; double weight; string name; string line; string str1, str2, str3, str4; int countString = 0; startDateOfObservations.day = 0; startDateOfObservations.month = 0; startDateOfObservations.year = 0; while (getline(in, line)) { istringstream ist(line); if (countString == 0) { if (((startDateOfObservations.day == 0 && startDateOfObservations.month == 0) && startDateOfObservations.year == 0)) { ist >> str1; ist >> str2; ist >> str3; ist >> str4; ist >> startDay; ist >> startMonth; ist >> startYear; startDateOfObservations.day = startDay; startDateOfObservations.month = startMonth; startDateOfObservations.year = startYear; } } if (countString > 0) { ist >> name; ist >> day; ist >> month; ist >> year; ist >> weight; memberOfFamily newMember(name); //помещаем в конец вектора структуру с новым именем Scale.push_back(newMember); for (int i = 0; i < Scale.size(); i++) { if (Scale[i].name == name) { Scale[i].Observation(day, month, year, weight); } } } countString++; } in.close(); } Date floorScales::getTheStartDateOfObservations() { return startDateOfObservations; } void floorScales::setObservation(unsigned short int day, unsigned short int month, unsigned short int year, double weight, string otherNameMember) { for (unsigned int i = 0; i < Scale.size(); i++) { if (Scale[i].name == otherNameMember) { Scale[i].Observation(day, month, year, weight); } } } double floorScales::getObservation(unsigned short int day, unsigned short int month, unsigned short int year, string nameMember) { if (Scale.size() > 0) { // чтобы хоть что-то было for (unsigned int i = 0; i < Scale.size(); i++) { if (Scale[i].name == nameMember) { //cout << "Число взвешиваний у члена семьи: " << Scale[i].informationAboutWeightDate.size() << endl; //для отладки for (int j = 0; j < Scale[i].informationAboutWeightDate.size(); j++) if (((Scale[i].informationAboutWeightDate[j].dateInWeight.month == month) && (Scale[i].informationAboutWeightDate[j].dateInWeight.year == year) && (Scale[i].informationAboutWeightDate[j].dateInWeight.day == day))) { return Scale[i].informationAboutWeightDate[j].weightMember; } } } } else { return 0; } } double floorScales::getAverageWeightOfFamilyMember(string nameMember) { double averageMeasurement = 0; int countingMeasurement = 0; for (unsigned int i = 0; i < Scale.size(); i++) { if (Scale[i].name == nameMember) { for (unsigned int j = 0; j < Scale[i].informationAboutWeightDate.size(); j++) { averageMeasurement += Scale[i].informationAboutWeightDate[j].weightMember; countingMeasurement++; } } } if (countingMeasurement == 0) { return 0; } //чтобы на нолик не поделить else { return averageMeasurement / countingMeasurement; } } double floorScales::getAverageWeightOfFamilyMember(string otherNameMember, unsigned short int otherMonth, unsigned short int otherYear) { double averageMeasurement = 0; int countingMeasurement = 0; for (unsigned int i = 0; i < Scale.size(); i++) { if (Scale[i].name == otherNameMember) { for (unsigned int j = 0; j < Scale[i].informationAboutWeightDate.size(); j++) { if ((Scale[i].informationAboutWeightDate[j].dateInWeight.month == otherMonth) && (Scale[i].informationAboutWeightDate[j].dateInWeight.year == otherYear)) { averageMeasurement += Scale[i].informationAboutWeightDate[j].weightMember; countingMeasurement++; } } } } if (countingMeasurement == 0) { return 0; } else { return averageMeasurement / countingMeasurement; } } double floorScales::getMinimumWeightOfFamilyMember(string nameMember) { double min = 200;// пусть весы будут до 200 кг for (unsigned int i = 0; i < Scale.size(); i++) { if (Scale[i].name == nameMember) { for (unsigned int j = 0; j < Scale[i].informationAboutWeightDate.size(); j++) { if (Scale[i].informationAboutWeightDate[j].weightMember < min) { min = Scale[i].informationAboutWeightDate[j].weightMember; return min; } } } } return min; } double floorScales::getMinimumWeightOfFamilyMember(string otherNameMember, unsigned short int otherMonth, unsigned short int otherYear) { double min = 1000; for (unsigned int i = 0; i < Scale.size(); i++) { if (Scale[i].name == otherNameMember) { for (unsigned int j = 0; j < Scale[i].informationAboutWeightDate.size(); j++) { if ((Scale[i].informationAboutWeightDate[j].dateInWeight.month == otherMonth) && (Scale[i].informationAboutWeightDate[j].dateInWeight.year == otherYear)) { if (Scale[i].informationAboutWeightDate[j].weightMember < min) { min = Scale[i].informationAboutWeightDate[j].weightMember; } } } } } return min; } double floorScales::getMaximumWeightOfFamilyMember(string nameMember) { double max = 0; // ну и соотвественно с 0 for (unsigned int i = 0; i < Scale.size(); i++) { if (Scale[i].name == nameMember) { for (unsigned int j = 0; j < Scale[i].informationAboutWeightDate.size(); j++) { if (Scale[i].informationAboutWeightDate[j].weightMember > max) { max = Scale[i].informationAboutWeightDate[j].weightMember; } } } } return max; } double floorScales::getMaximumWeightOfFamilyMember(string otherNameMember, unsigned short int otherMonth, unsigned short int otherYear) { double max = 0; for (unsigned int i = 0; i < Scale.size(); i++) { if (Scale[i].name == otherNameMember) { for (unsigned int j = 0; j < Scale[i].informationAboutWeightDate.size(); j++) { if ((Scale[i].informationAboutWeightDate[j].dateInWeight.month == otherMonth) && (Scale[i].informationAboutWeightDate[j].dateInWeight.year == otherYear)) { if (Scale[i].informationAboutWeightDate[j].weightMember > max) { max = Scale[i].informationAboutWeightDate[j].weightMember; } } } } } return max; } void floorScales::printDateOfMinimumWeightOfFamilyMember(string nameMember) { double min = 200;// пусть весы будут до 200 кг int x = -1, y = -1; for (unsigned int i = 0; i < Scale.size(); i++) { if (Scale[i].name == nameMember) { for (unsigned int j = 0; j < Scale[i].informationAboutWeightDate.size(); j++) { if (Scale[i].informationAboutWeightDate[j].weightMember < min) { min = Scale[i].informationAboutWeightDate[j].weightMember; x = i; y = j; } } } } cout << "Дата этого наблюдения: " << Scale[x].informationAboutWeightDate[y].dateInWeight << endl; } void floorScales::printDateOfMinimumWeightOfFamilyMember(string otherNameMember, unsigned short int otherMonth, unsigned short int otherYear) { double min = 1000; int x = -1; int y = -1; for (unsigned int i = 0; i < Scale.size(); i++) { if (Scale[i].name == otherNameMember) { for (unsigned int j = 0; j < Scale[i].informationAboutWeightDate.size(); j++) { if ((Scale[i].informationAboutWeightDate[j].dateInWeight.month == otherMonth) && (Scale[i].informationAboutWeightDate[j].dateInWeight.year == otherYear)) { if (Scale[i].informationAboutWeightDate[j].weightMember < min) { min = Scale[i].informationAboutWeightDate[j].weightMember; x = i; y = j; } } } } } cout << "Дата этого наблюдения: " << Scale[x].informationAboutWeightDate[y].dateInWeight << endl; } void floorScales::printDateOfMaximumWeightOfFamilyMember(string nameMember) { double max = 0; // ну и соотвественно с 0 int x = -1; int y = -1; for (unsigned int i = 0; i < Scale.size(); i++) { if (Scale[i].name == nameMember) { for (unsigned int j = 0; j < Scale[i].informationAboutWeightDate.size(); j++) { if (Scale[i].informationAboutWeightDate[j].weightMember > max) { max = Scale[i].informationAboutWeightDate[j].weightMember; x = i; y = j; } } } } cout << "Дата этого наблюдения: " << Scale[x].informationAboutWeightDate[y].dateInWeight << endl; } void floorScales::printDateOfMaximumWeightOfFamilyMember(string otherNameMember, unsigned short int otherMonth, unsigned short int otherYear) { double max = 0; int x = -1; int y = -1; for (unsigned int i = 0; i < Scale.size(); i++) { if (Scale[i].name == otherNameMember) { for (unsigned int j = 0; j < Scale[i].informationAboutWeightDate.size(); j++) { if ((Scale[i].informationAboutWeightDate[j].dateInWeight.month == otherMonth) && (Scale[i].informationAboutWeightDate[j].dateInWeight.year == otherYear)) { if (Scale[i].informationAboutWeightDate[j].weightMember > max) { max = Scale[i].informationAboutWeightDate[j].weightMember; x = i; y = j; } } } } } cout << "Дата этого наблюдения: " << Scale[x].informationAboutWeightDate[y].dateInWeight << endl; } void floorScales::saveFile() { //удаляю весь файл, Зачем? навсякий случай! remove("Scales.txt"); //if (remove("Scales.txt") != 0) { cout << "Ошибка удаления файла."; } //else { cout << "Файл успешно удалён" << endl; } ofstream file; file.open("Scales.txt"); if (!file.is_open()) { std::cout << "File not open!" << std::endl; } file << "Задана начальная дата наблюдений: " << " " << startDateOfObservations << endl; for (unsigned int i = 0; i < Scale.size(); i++) { for (unsigned int j = 0; j < Scale[i].informationAboutWeightDate.size(); j++) { file << Scale[i].name << " " << Scale[i].informationAboutWeightDate[j] << endl; } } file.close(); } void printMenu() { cout << " Меню:" << endl; cout << "1. Добавить нового пользователя" << endl; cout << "2. Установить начальную дату измерений" << endl; cout << "3. Посмотреть начальную дату измерений" << endl; cout << "4. Записать новое измерение" << endl; cout << "5. Узнать вес в выбранном измерении по дате и имени" << endl; cout << "6. Найти средний вес члена семьи в выбранном месяце или за всю историю наблюдений" << endl; cout << "7. Найти минимальный вес члена семьи в выбранном месяце или за всю историю наблюдений" << endl; cout << "8. Найти максимальный вес члена семьи в выбранном месяце или за всю историю наблюдений" << endl; cout << "9. Сохранить историю наблюдений в файл" << endl; cout << "10. Удалить файл и всю историю наблюдений!" << endl; cout << "11. Выход" << endl; } void welcomeMessege() { cout << "Добро пожаловать в программу <Весы напольные>." << endl; cout << "Считывание из файла происходит при запуске программы, не забудьте сохранить данные в файл по окончании работы." << endl; }
true
069931a537fd0fca35ffcee13afcb73d5098d83b
C++
yevhenii-sir/C_Cpp
/Study/C/6_Function/Zavdannna_1_1.cpp
UTF-8
1,849
3.359375
3
[]
no_license
#include <stdio.h> #include <conio.h> #include <math.h> int NSD (int a, int b) { while (a != b) if (a > b) a -= b; else b -= a; return a; } int fmax(int a, int b) { return (a > b) ? a:b; } float fser(int a, int b) { return (a + b) / 2.0; } void parn(int a) { if (a % 2 == 0) printf("\nЧисло %d - парне\n", a); else printf("\nЧисло %d - непране\n", a); } float chaska(int a, int b) { return ((b != 0) ? (a / (float)b) : 0); //if ((b != 0)) return (a / (float)b); else return 0; } int main() { int x1, x2, nsd, oz; float chast; printf("\nВведи два числа: "); scanf("%d%d", &x1, &x2); do { printf("Create by Yevhenii Sirenko\n"); printf("\nОберіть правильне: \n1 - НСД\n2 - Максимум\n3 - Серед. арефм.\n4 - Частка чисел\n5 - Парність числа(x1)\n6 - Вихід\n"); printf("Введіть номер пункту: "); scanf("%d", &oz); switch (oz) { case 1: nsd = NSD(x1, x2); printf("\nНСД чисел - %d i %d = %d\n", x1, x2, nsd); break; case 2: printf("Максимальне число з %d i %d = %d\n", x1, x2, fmax(x1, x2)); break; case 3: printf("\n Середнє арефметичне - %d i %d = %.2f\n", x1, x2, fser(x1, x2)); break; case 4: chast = chaska(x1, x2); if (chast != 0) printf("\nЧастка чисел %d i %d = %.2f\n", x1, x2, chast); else printf("На нуль ділити не можна!!!\n"); break; case 5: parn(x1); break; case 6: exit(0); default: printf("\n Не правильна операція!"); } } while (1); }
true
752b210509c192943e5b4aa077c4c22b36c6a100
C++
chess1424/Programming_contests
/Code_chef/ WDTBAM.cpp
UTF-8
607
2.75
3
[]
no_license
#include <iostream> #include <stdio.h> #include <string> using namespace std; int main(int argc, char const *argv[]) { int t,n; cin>>t; while(t--) { cin>>n; int correct = 0; string str,str2; cin>>str; cin>>str2; for(int i = 0; i < str.size(); i++) { char c = str[i]; char c2 = str2[i]; if(c == c2) ++correct; } long long out = 0, money; for(int i = 0; i <= n; i++) { cin>>money; if(i <= correct) out = max(money,out); } if(correct == n) cout<<money<<'\n'; else cout<<out<<'\n'; } return 0; }
true
9ca7b35741c800b3edfa292ad0c39dc3bec49eb7
C++
adikrasimirowa/FMI-SDP-2021
/seminar3/main.cpp
UTF-8
497
2.640625
3
[]
no_license
#include <iostream> #include "DArray.h" int main() { ///така не се конструира обект , заделя се само памет / размер в байтове DArray<int>* array= (DArray<int>*)(operator new(sizeof(DArray<int>))); new(array) DArray<int>(); /// създаваме обекта в/у дадената памет DArray<int>* arrPointer = static_cast<DArray<int>*>(array); arrPointer->pushBack(1); arrPointer->print(); return 0; }
true
1a85a841ccaf6a42cd32d875a4eb9dee258f75cb
C++
emarmol/comp11
/lab10/vector1.h
UTF-8
1,038
3.40625
3
[]
no_license
// A dynamic array with fixed size #ifndef VECTOR_H #define VECTOR_H class Vector { public: Vector(int capacity); // Constructor // args: capacity of the Vector ~Vector(); // Destructor int getSize(); // Returns size of the Vector object int get(int index); // Returns element at the given index bool add(int element); // Adds given element to end of array bool add(int element, int index); // Places the given element at // given index. Index must be less // than current size of the // Vector object private: int capacity; // Current capacity of the Vector int n_elements; // Number of elements stored in the Vector object int *data; //Actual data stored in the Vector }; #endif
true
9e4eaf6e4d475a56b292b51905af1009f5f68ae2
C++
German-Rotili/tpGrupal
/common_src/Snapshot.h
UTF-8
658
2.59375
3
[]
no_license
#ifndef __SNAPSHOT__ #define __SNAPSHOT__ #include <vector> #include "Serializer.h" #include "Action.h" class World; struct player_t; struct intention_t; struct object_t; class Snapshot{ private: std::vector<player_t> players; std::vector<object_t> objects; std::vector <Action> actions; public: Snapshot(); ~Snapshot(); player_t get_player(int & id); object_t get_object(int & id); Action get_action(int & id); void add_player(player_t player); void add_object(object_t object); void add_action(Action action); void print(); friend class Serializer; friend class World; friend class Enemy; }; #endif
true
aacc897385c9143a9cad8a0ea0624325cb07efaa
C++
Willson1989/WillsonGO
/LearningCpp/LearningCpp/OOP/Student.cpp
UTF-8
582
2.796875
3
[]
no_license
// // Student.cpp // StudyCpp // // Created by fn-273 on 2020/10/9. // Copyright © 2020 ZhengYi. All rights reserved. // #include "Student.hpp" #include <sstream> void Student::set_score(int s) { score = s; } int Student::get_score() { return score; } void Student::set_address(string addr) { address = addr; } string Student::stu_desc() { stringstream s(""); s << "student name : " << name; s << ", age : " << age; s << ", class : " << class_num << " - " << grade_num; s << ", address : " << address; s << endl; return s.str(); }
true
0df113a4df527f907cd39319cc59e4b171dd7e38
C++
HRex39/SensorCalibration
/imu-lidar/include/sensor_calibration/ErrorTerm.h
UTF-8
1,305
2.625
3
[]
no_license
#ifndef _ERROR_TERM_H_ #define _ERROR_TERM_H #include <pcl/point_types.h> #include <ceres/ceres.h> #include <ceres/rotation.h> namespace SensorCalibration { class ErrorTerm { public: ErrorTerm(const pcl::PointXYZI &pt1, const pcl::PointXYZI &pt2) :mPoint1(pt1.x, pt1.y, pt1.z), mPoint2(pt2.x, pt2.y, pt2.z) {} template<typename T> bool operator()(const T* const rotation1, const T* const translation1, const T* const rotation2, const T* const translation2, T* residuals) const { T point1[3]; T point2[3]; for(int i=0; i<3; i++) { point1[i] = T(mPoint1[i]); point2[i] = T(mPoint2[i]); } T transformedPoint1[3]; T transformedPoint2[3]; ceres::QuaternionRotatePoint(rotation1, point1, transformedPoint1); ceres::QuaternionRotatePoint(rotation2, point2, transformedPoint2); for(int i=0; i<3; i++) { transformedPoint1[i] = transformedPoint1[i] + translation1[i]; transformedPoint2[i] = transformedPoint2[i] + translation2[i]; residuals[i] = transformedPoint1[i] - transformedPoint2[i]; } return true; } private: Eigen::Vector3d mPoint1; Eigen::Vector3d mPoint2; }; } #endif
true
900bf146bebf938843435e972c080a666da1e58e
C++
SayaUrobuchi/uvachan
/USACO/詳解/cpp/camelot.cpp
UTF-8
3,424
2.609375
3
[]
no_license
/* ID: dd.ener1 PROG: camelot LANG: C++ */ #include <cstdio> #include <cstring> using namespace std; const long maxP=26*40+20; const long maxR=26,maxC=40; long R,C;//R<=40, C<=26 long kingx,kingy; long knightx[maxP]; long knighty[maxP]; long k_num; unsigned long g[maxR][maxC][maxR][maxC]; bool inque[maxR][maxC]; long best; void input(){ freopen("camelot.in","r",stdin); scanf("%d %d\n",&R,&C); scanf("%c %d\n",&kingx,&kingy); kingx-='A'; kingy-=1; char c; long l; for(;;){ for(;;){ c=getchar(); if(c!=' '&&c!='\n')break; } if(feof(stdin))return; scanf("%d",&l); knightx[k_num]=c-'A'; knighty[k_num]=l-1; ++k_num; } } template<class T> class queue{ private: long N; T* s; long beg,end; public: inline void init(){ beg=end=0; } queue(long size):N(size),s(new T[size]){ init(); } inline void push(const T& item){ s[end]=item; ++end; if(end==N)end=0; } inline T pop(){ T res=s[beg]; ++beg; if(beg==N)beg=0; return res; } inline bool empty(){ return beg==end; } }; struct item{ item(){} item(long _x,long _y,long _dis):x(_x),y(_y),dis(_dis){} long x,y; long dis; }; void DFS(long x,long y){ static const long deltax[8]={1,1,-1,-1,2,2,-2,-2}; static const long deltay[8]={2,-2,2,-2,1,-1,1,-1}; static queue<item> que(R*C+1); que.init(); memset(inque,0,sizeof(inque)); for(long i=0;i<C;++i) for(long j=0;j<R;++j) g[x][y][i][j]=10000; g[x][y][x][y]=0; inque[x][y]=true; que.push(item(x,y,0)); do{ item now=que.pop(); g[x][y][now.x][now.y]=now.dis; for(long k=0;k<8;++k){ long newx=now.x+deltax[k]; if(newx<0||newx>=C)continue; long newy=now.y+deltay[k]; if(newy<0||newy>=R)continue; if(inque[newx][newy])continue; que.push(item(newx,newy,now.dis+1)); inque[newx][newy]=true; } }while(!que.empty()); } void DFS(){ for(long i=0;i<C;++i) for(long j=0;j<R;++j) DFS(i,j); } struct point{ point(){} point(long _x,long _y):x(_x),y(_y){} long x,y; }; long abs(long x){ return x<0?-x:x; } long dis(point carry){ long x=abs(carry.x-kingx); long y=abs(carry.y-kingy); return x>y?x:y; } void update(long& x,const long y){ if(x>y)x=y; } long solve(const point &gather,const point &carry,long k){ long res=0; res-=g[gather.x][gather.y][knightx[k]][knighty[k]]; res+=dis(carry); res+=g[gather.x][gather.y][carry.x][carry.y]; res+=g[carry.x][carry.y][knightx[k]][knighty[k]]; return res; } void solve(const point &gather){ long res=0; for(long k=0;k<k_num;++k) res+=g[knightx[k]][knighty[k]][gather.x][gather.y]; if(res>best)return; point carry; long bestdelta=100000000; for(carry.x=0;carry.x<C;++carry.x) for(carry.y=0;carry.y<R;++carry.y){ if(dis(carry)>bestdelta)continue; for(long k=0;k<k_num;++k) update(bestdelta,solve(gather,carry,k)); } update(best,res+=bestdelta); } point midknight(){ long sumx=0,sumy=0; for(long k=0;k<k_num;++k){ sumx+=knightx[k]; sumy+=knightx[k]; } return point(sumx/k_num,sumy/k_num); } void presolve(){ point pre=midknight(); solve(pre); pre.x=kingx; pre.y=kingy; solve(pre); } void solve(){ if(k_num==0){ best=0; return; } best=1000000000; presolve(); point gather; for(gather.x=0;gather.x<C;++gather.x) for(gather.y=0;gather.y<R;++gather.y) solve(gather); } void output(){ freopen("camelot.out","w",stdout); printf("%d\n",best); } int main(){ input(); DFS(); solve(); output(); return 0; }
true
7fa3eae4529b7c136c4d7de83542149a4dafefb8
C++
macnaer/OOP-CPP
/13. Functor/13. Functor/Source.cpp
UTF-8
353
3.40625
3
[]
no_license
#include <iostream> #include <string> using namespace std; class Functor { public: int operator()(int a, int b) { return a + b; } int operator= (int a) { return a; } }; int main() { int a = 5, b = 10; Functor foo; int result = foo(a, b); foo = (5); cout << a << " + " << b << " = " << result << endl; system("pause"); return 0; }
true
c2d775537db3dd2ea88a78b1258ed0b11b853a8c
C++
MichalSara99/differential_equation_solvers
/differential_equation_solvers/euler_method_t.h
UTF-8
16,305
3.34375
3
[]
no_license
#pragma once #if !defined(_EULER_METHOD_T_H_) #define _EULER_METHOD_T_H_ #include<iostream> #include"euler_method.h" using namespace euler_method; void simple_ode_first_order() { std::cout << "Euler Method: \n"; // numerical solution of // first-order differential equation // // x'(t) = 2.0*x(t)*(1.0 - x(t)), t\in <10,12> // x(10) = 0.2 // // The exact solution is: // // x(t) = 1.0/(1.0 + 4.0*exp(2.0*(10.0 - t))) double x0{ 0.2 }; double h{ 0.2 }; Range<> range{ 10.0,12.0 }; // Exact solution: auto x_exact = [](double t){ return (1.0 / (1.0 + 4.0*std::exp(2.0*(10.0 - t)))); }; // This is the actual x'(t): auto derivative = [](double t,double x) { return (2.0*x*(1.0 - x)); }; IDerivatives<decltype(derivative)> holder = std::make_tuple(derivative); EulerMethod<1> em{ holder,range,x0,h }; std::cout << "Order of ODE: " << em.equationOrder() << "\n"; std::cout << "Time resolution:\n"; auto t_points = em.resolution(); for (auto const &t : t_points) { std::cout << t << ", "; } std::cout << "\nNumerical solution: \n"; try { auto curve = em.solutionCurve(); for (auto const &v : curve) { std::cout << v << ", "; } } catch (std::exception &e) { std::cerr << e.what() << "\n"; } std::cout << "\nExact solution:\n"; for (auto const &t : t_points) { std::cout << x_exact(t) << ", "; } std::cout << "\n"; std::cout << "solution at x(11.0): " << em.solutionAt(11.0) << "\n"; } void simple_ode_first_order2() { // numerical solution of // first-order differential equation // // x'(t) = 1.0 + t - x(t) , t\in <0.0,2.0> // x(0.0) = 0.0 // // The exact solution is: // // x(t) = t double x0{ 0.0 }; double h{ 0.01 }; Range<> range{ 0.0,2.0 }; // Exact solution: auto x_exact = [](double t) { return t; }; // This is the actual x'(t): auto derivative = [](double t, double x) { return (1.0 + t - x); }; IDerivatives<decltype(derivative)> holder = std::make_tuple(derivative); EulerMethod<1> em{ holder,range,x0,h }; std::cout << "Order of ODE: " << em.equationOrder() << "\n"; std::cout << "Numerical solution: \n"; try { auto curve = em.solutionCurve(); for (auto const &v : curve) { std::cout << v << ", "; } } catch (std::exception &e) { std::cerr << e.what() << "\n"; } // get independent variable resolution: auto t_points = em.resolution(); std::cout << "\nExact solution:\n"; for (auto const &t : t_points) { std::cout << x_exact(t) << ", "; } std::cout << "\n"; std::cout << "solution at x(0.5): " << em.solutionAt(0.5) << "\n"; } void simple_ode_second_order() { // numerical solution of // second-order differential equation // // x''(t) + x(t) = t, t\in <0,2> // x'(0) = 2, x(0) = 1 // // Setting u = x and v = x' we have // v' = u'' = x'' = t - u and // u' = v. Therefore this gives // // u'(t) = v(t), // v'(t) = t - u(t), // u(0) = 1, v(0) = 2 // // Notice that the solution to the original // problem is found by extracting the solution curve // from u(t), since we put u(t) = x(t) in the previous // transformation // // The exact solution is: // // x(t) = sin(t) + cos(t) + t // double t{ 0.0 }; double u{ 1.0 }; double v{ 2.0 }; double h{ 0.1 }; Range<> range{ 0.0,2.0 }; // Exact solution: auto x_exact = [](double t) { return (std::sin(t) + std::cos(t) + t); }; // Construct the slopes on the right-hand side: auto u_prime = [](double t, double u, double v) {return v; }; auto v_prime = [](double t, double u, double v) {return t - u; }; // Wrap it up into IDerivatives: auto odeSystem = std::make_tuple(u_prime, v_prime); // Create instance of EulerMethod<2> EulerMethod<2> em{ odeSystem,range,std::make_pair(u,v),h }; std::cout << "Order of ODE: " << em.equationOrder() << "\n"; std::cout << "Time resolution:\n"; auto t_points = em.resolution(); for (auto const &t : t_points) { std::cout << t << ", "; } std::cout << "\nNumerical solution: \n"; try { auto curves = em.solutionCurve(); for (auto const &v : curves[0]) { std::cout << v << ", "; } } catch (std::exception &e) { std::cerr << e.what() << "\n"; } std::cout << "\nExact solution:\n"; for (auto const &t : t_points) { std::cout << x_exact(t) << ", "; } std::cout << "\n\nNumerical solution at x(0.1) = " << em.solutionAt<0>(0.1) << "\n"; std::cout << "Numerical solution at x(0.6) = " << em.solutionAt<0>(0.6) << "\n"; std::cout << "Numerical solution at x(0.8) = " << em.solutionAt<0>(0.8) << "\n"; std::cout << "Numerical solution at x(1.5) = " << em.solutionAt<0>(1.5) << "\n"; std::cout << "Numerical solution at x(1.7) = " << em.solutionAt<0>(1.7) << "\n"; } void another_ode_second_order() { std::cout << "\n\nEuler Method: \n"; // numerical solution of // second-order differential equation // // x''(t) + x(t) = 0, t\in <0,2> // x(0) = pi/10, x'(0) = 0 // // Setting u = x and v = x' we have // v' = u'' = x'' = t - u and // u' = v. Therefore this gives // // u'(t) = v(t), // v'(t) = u(t), // u(0) = pi/10, v(0) = 0 // // Notice that the solution to the original // problem is found by extracting the solution curve // from u(t), since we put u(t) = x(t) in the previous // transformation // // The exact solution is: // // x(t) = (pi/10)*cos(t) // double t{ 0.0 }; double u{ PI / 10.0 }; double v{ 0.0 }; double h{ 0.1 }; Range<> range{ 0.0,2.0 }; // Exact solution: auto x_exact = [](double t) { return ((PI / 10.0)* std::cos(t)); }; // Construct the slopes on the right-hand side: auto u_prime = [](double t, double u, double v) {return v; }; auto v_prime = [](double t, double u, double v) {return (-1.0*u); }; // Wrap it up into IDerivatives: auto odeSystem = std::make_tuple(u_prime, v_prime); // Create instance of EulerMethod<2> EulerMethod<2> em{ odeSystem,range,std::make_pair(u,v),h }; std::cout << "Order of ODE: " << em.equationOrder() << "\n"; std::cout << "Time resolution:\n"; auto t_points = em.resolution(); for (auto const &t : t_points) { std::cout << t << ", "; } std::cout << "\nNumerical solution: \n"; try { auto curves = em.solutionCurve(); for (auto const &v : curves[0]) { std::cout << v << ", "; } } catch (std::exception &e) { std::cerr << e.what() << "\n"; } std::cout << "\nExact solution:\n"; for (auto const &t : t_points) { std::cout << x_exact(t) << ", "; } std::cout << "\n\nNumerical solution at x(0.2) = " << em.solutionAt<0>(0.2) << "\n"; } void second_order_ode() { // numerical solution of // second-order differential equation // // x''(t) + x(t) * x'(t) + 4.0 * x(t)= t*t, t\in <0,2> // x'(0) = 1, x(0) = 0 // // Setting u = x and v = x' we have // v' = u'' = x'' = t - u and // u' = v. Therefore this gives // // u'(t) = v(t), // v'(t) = t * t - 4.0 * u(t)- u(t) * v(t), // u(0) = 0, v(0) = 1 // // Notice that the solution to the original // problem is found by extracting the solution curve // from u(t), since we put u(t) = x(t) in the previous // transformation // // The exact solution is: // unknown as far as i know // double t{ 0.0 }; double u{ 0.0 }; double v{ 1.0 }; double h{ 0.1 }; Range<> range{ 0.0,2.0 }; // Construct the slopes on the right-hand side: auto u_prime = [](double t, double u, double v) {return v; }; auto v_prime = [](double t, double u, double v) {return (t * t - 4.0 * u - u * v); }; // Wrap it up into IDerivatives: auto odeSystem = std::make_tuple(u_prime, v_prime); // Create instance of EulerMethod<2> EulerMethod<2> em{ odeSystem,range,std::make_pair(u,v),h }; std::cout << "Order of ODE: " << em.equationOrder() << "\n"; std::cout << "Time resolution:\n"; auto t_points = em.resolution(); for (auto const &t : t_points) { std::cout << t << ", "; } std::cout << "\nNumerical solution: \n"; try { auto curves = em.solutionCurve(); auto curve1 = curves[0]; auto curve2 = curves[1]; for (std::size_t t = 0; t < curve1.size();++t) { std::cout << "(" << curve1[t] << "," << curve2[t] << "), "; } } catch (std::exception &e) { std::cerr << e.what() << "\n"; } std::cout << "\n\nNumerical solution at x(0.2) = " << "(" << em.solutionAt(0.2).first << ", " << em.solutionAt(0.2).second << ")\n"; } void second_order_ode1() { // numerical solution of // second-order differential equation // // x''(t) + 3.0 * x'(t) * 2.0 * x(t) = t*t, t\in <0,2> // x'(0) = 1, x(0) = 0 // // Setting u = x and v = x' we have // v' = u'' = x'' = t - u and // u' = v. Therefore this gives // // u'(t) = v(t), // v'(t) = t * t - 2.0 * u(t) - 3.0 * v(t), // u(0) = 1, v(0) = 0 // // Notice that the solution to the original // problem is found by extracting the solution curve // from u(t), since we put u(t) = x(t) in the previous // transformation // // The exact solution is: // x(t) = (3.0/4.0) * exp(-2.0*t) - (3.0/2.0) * exp(-1.0*t) + (1.0/2.0) * t*t - (3.0/2.0)*t + (7.0/4.0) // double u{ 1.0 }; double v{ 0.0 }; double h{ 0.1 }; Range<> range{ 0.0,1.0 }; // Exact solution: auto x_exact = [](double t) { return ((3.0 / 4.0) * std::exp(-2.0*t) - (3.0 / 2.0) * std::exp(-1.0*t) + (1.0 / 2.0) * t*t - (3.0 / 2.0)*t + (7.0 / 4.0)); }; // Construct the slopes on the right-hand side: auto u_prime = [](double t, double u, double v) {return v; }; auto v_prime = [](double t, double u, double v) {return (t * t - 2.0 * u - 3.0 * v); }; // Wrap it up into IDerivatives: auto odeSystem = std::make_tuple(u_prime, v_prime); // Create instance of EulerMethod<2> EulerMethod<2> em{ odeSystem,range,std::make_pair(u,v),h }; std::cout << "Order of ODE: " << em.equationOrder() << "\n"; std::cout << "Time resolution:\n"; auto t_points = em.resolution(); for (auto const &t : t_points) { std::cout << t << ", "; } std::cout << "\nNumerical solution: \n"; try { auto curves = em.solutionCurve(); for (auto const &v: curves[0]) { std::cout << v << ", "; } } catch (std::exception &e) { std::cerr << e.what() << "\n"; } std::cout << "\nExact solution:\n"; for (auto const &t : t_points) { std::cout << x_exact(t) << ", "; } std::cout << "\n\nNumerical solution at x(0.2) = " <<em.solutionAt<0>(0.2)<<"\n"; } void system_odes1() { // numerical solution of // system // // u'(t) = -2.0 * u(t) + 1.0 * v(t), // v'(t) = t * t - v(t), // u(0) = 1, v(0) = 0 // // // The exact solution is: // x(t) = (3.0/4.0) * exp(-2.0*t) - (3.0/2.0) * exp(-1.0*t) + (1.0/2.0) * t*t - (3.0/2.0)*t + (7.0/4.0) // double u{ 1.0 }; double v{ 0.0 }; double h{ 0.1 }; Range<> range{ 0.0,1.0 }; // Exact solution: auto x_exact = [](double t) { return ((3.0 / 4.0) * std::exp(-2.0*t) - (3.0 / 2.0) * std::exp(-1.0*t) + (1.0 / 2.0) * t*t - (3.0 / 2.0)*t + (7.0 / 4.0)); }; // Construct the slopes on the right-hand side: auto u_prime = [](double t, double u, double v) {return (-2.0 * u + 1.0 * v); }; auto v_prime = [](double t, double u, double v) {return (t * t - v); }; // Wrap it up into IDerivatives: auto odeSystem = std::make_tuple(u_prime, v_prime); // Create instance of EulerMethod<2> EulerMethod<2> em{ odeSystem,range,std::make_pair(u,v),h }; std::cout << "Order of ODE: " << em.equationOrder() << "\n"; std::cout << "Time resolution:\n"; auto t_points = em.resolution(); for (auto const &t : t_points) { std::cout << t << ", "; } std::cout << "\nNumerical solution: \n"; try { auto curves = em.solutionCurve(); for (auto const &v : curves[0]) { std::cout << v << ", "; } } catch (std::exception &e) { std::cerr << e.what() << "\n"; } std::cout << "\nExact solution:\n"; for (auto const &t : t_points) { std::cout << x_exact(t) << ", "; } std::cout << "\n\nNumerical solution at x(0.2) = " << em.solutionAt<0>(0.2) << "\n"; } void simple_system_odes() { // numerical solution of system of // first-order odes // // u'(t) = -2.0 * u(t) + v(t), t\in <0,2> // v'(t) = -u(t) - 2.0 * v(t), // u(0) = 1, v(0) = 0 // // // The exact solution is: // // u(t) = exp(-2.0*t) * cos(t) // v(t) = -1.0*exp(-2.0*t) * sin(t) // double t{ 0.0 }; double u{ 1.0 }; double v{ 0.0 }; double h{ 0.1 }; Range<> range{ 0.0,2.0 }; // Exact solution: auto x_exact = [](double t) { return std::make_pair(std::exp(-2.0*t)*std::cos(t), -1.0 * std::exp(-2.0*t)*std::sin(t)); }; // Construct the slopes on the right-hand side: auto u_prime = [](double t, double u, double v) {return (-2.0*u + 1.0*v); }; auto v_prime = [](double t, double u, double v) {return (-1.0*u - 2.0*v); }; // Wrap it up into IDerivatives: auto odeSystem = std::make_tuple(u_prime, v_prime); // Create instance of EulerMethod<2> EulerMethod<2> em{ odeSystem,range,std::make_pair(u,v),h }; std::cout << "Order of ODE: " << em.equationOrder() << "\n"; std::cout << "Time resolution:\n"; auto t_points = em.resolution(); for (auto const &t : t_points) { std::cout << t << ", "; } std::cout << "\nNumerical solution: \n"; try { auto curves = em.solutionCurve(); auto first = curves[0]; auto second = curves[1]; for (std::size_t t = 0; t < first.size();++t) { std::cout << "(" << first[t] << "," << second[t] << "), "; } } catch (std::exception &e) { std::cerr << e.what() << "\n"; } std::cout << "\nExact solution:\n"; for (auto const &t : t_points) { auto[f, s] = x_exact(t); std::cout << "(" << f << "," << s << "), "; } std::cout << "\n\nNumerical solution at x(0.2) = (" << em.solutionAt(0.2).first << "," << em.solutionAt(0.2).second << ")\n"; } void simple_ode_first_order1() { // numerical solution of // first-order differential equation // // x'(t) = -10.0*x(t), t\in <0,1> // x(0.0) = 1.0 // // The exact solution is: // // x(t) = e(-10.0*t) double x0{ 1.0 }; double h{ 1.0/100.0 }; Range<> range{ 0.0,1.0 }; // Exact solution: auto x_exact = [](double t) { return (std::exp(-10.0*t)); }; // This is the actual x'(t): auto derivative = [](double t, double x) { return (-10.0*x); }; IDerivatives<decltype(derivative)> holder = std::make_tuple(derivative); EulerMethod<1> em{ holder,range,x0,h }; std::cout << "Order of ODE: " << em.equationOrder() << "\n"; std::cout << "Numerical solution: \n"; try { auto curve = em.solutionCurve(); for (auto const &v : curve) { std::cout << v << ", "; } } catch (std::exception &e) { std::cerr << e.what() << "\n"; } // get independent variable resolution: auto t_points = em.resolution(); std::cout << "\nt points:\n"; for (auto const &t : t_points) { std::cout << t << ", "; } std::cout << "\nExact solution:\n"; for (auto const &t : t_points) { std::cout << x_exact(t) << ", "; } std::cout << "\n"; //std::cout << "solution at x(1/6): " << em.solutionAt(1.0/6.0) << "\n"; } void nonlinear_ode_first_order() { // numerical solution of // first-order differential equation // // x'(t) = t*t - x(t)*x(t), t\in <0,1> // x(0.0) = 1.0 // // The exact solution is not known, although // we can obtain approximate solution via series: // // x(t) = 1 - t + t*t - (2/3)*t*t*t + (5/6)*t*t*t*t + O(t^5) // // But this converges only for |t| < 1 therefore for range with right end-point // greater or equal to 1.0 this series won't work double x0{ 1.0 }; double h{ 0.1 }; Range<> range{ 0.0,0.9 }; // Exact solution: auto x_exact_series = [](double t) { return (1.0 - t + t * t - (2.0 / 3.0)*t*t*t + (5.0 / 6.0)*t*t*t*t); }; // This is the actual x'(t): auto derivative = [](double t, double x) { return (t*t - x * x); }; IDerivatives<decltype(derivative)> holder = std::make_tuple(derivative); EulerMethod<1> em{ holder,range,x0,h }; std::cout << "Order of ODE: " << em.equationOrder() << "\n"; std::cout << "Numerical solution: \n"; try { auto curve = em.solutionCurve(); for (auto const &v : curve) { std::cout << v << ", "; } } catch (std::exception &e) { std::cerr << e.what() << "\n"; } // get independent variable resolution: auto t_points = em.resolution(); std::cout << "\nExact solution:\n"; for (auto const &t : t_points) { std::cout << x_exact_series(t) << ", "; } std::cout << "\n"; std::cout << "Solution at x(0.4): " << em.solutionAt(0.4) << "\n"; std::cout << "Solution at x(0.9): " << em.solutionAt(0.9) << "\n"; } #endif ///_EULER_METHOD_T_H_
true
cc35124356431131e7f96a21ba46960d14c170d7
C++
DeepLearnPhysics/larcv2
/larcv/app/ImageMod/arxiv/ImageFromPixel2DCluster.h
UTF-8
1,731
2.71875
3
[ "MIT" ]
permissive
/** * \file ImageFromPixel2DCluster.h * * \ingroup Package_Name * * \brief Class def header for a class ImageFromPixel2DCluster * * @author kazuhiro */ /** \addtogroup Package_Name @{*/ #ifndef __IMAGEFROMPIXEL2D_H__ #define __IMAGEFROMPIXEL2D_H__ #include "Processor/ProcessBase.h" #include "Processor/ProcessFactory.h" namespace larcv { /** \class ProcessBase User defined class ImageFromPixel2DCluster ... these comments are used to generate doxygen documentation! */ class ImageFromPixel2DCluster : public ProcessBase { public: /// Default constructor ImageFromPixel2DCluster(const std::string name="ImageFromPixel2DCluster"); /// Default destructor ~ImageFromPixel2DCluster(){} void configure(const PSet&); void initialize(); bool process(IOManager& mgr); void finalize(); private: enum class PIType_t { kPITypeFixedPI, kPITypeInputImage, kPITypeClusterIndex }; float _fixed_pi; PIType_t _type_pi; std::string _pixel_producer; std::string _image_producer; std::string _output_producer; }; /** \class larcv::ImageFromPixel2DClusterFactory \brief A concrete factory class for larcv::ImageFromPixel2DCluster */ class ImageFromPixel2DClusterProcessFactory : public ProcessFactoryBase { public: /// ctor ImageFromPixel2DClusterProcessFactory() { ProcessFactory::get().add_factory("ImageFromPixel2DCluster",this); } /// dtor ~ImageFromPixel2DClusterProcessFactory() {} /// creation method ProcessBase* create(const std::string instance_name) { return new ImageFromPixel2DCluster(instance_name); } }; } #endif /** @} */ // end of doxygen group
true
9a9c542780efbbb5e096f2cdb22192b0b2253d3a
C++
hMarcorivas/MARCO-RIVAS-PARALELA
/laboratorio9/factorial1/src/factorial1.cpp
UTF-8
503
2.703125
3
[]
no_license
#include <stdio.h> #include<pthread.h> #include <stdlib.h> //using namespace std; int num; void* factorial() { int fac=1; for(int a=1;a<=num;a++) { fac=fac*a; //cout<<"Factorial of Given Number is ="<<fac; printf("Hello from thread is %d\n", fac); } } int main(){ pthread_t* t; printf("El factorial del numero: "); //cin>>num; scanf("%d", &num); pthread_create(&t,NULL,factorial,(void*)&num); /*pthread_create(&thread_handles[thread], NULL, Pth_mat_vect, (void*) thread);*/ return 0; }
true
98f85cdfb3f6b4afe5659c1727a06c1752c4b461
C++
GustavoSilveira/arduino-projects
/pwm-interrupts/pwm-interrupts.ino
UTF-8
3,440
2.78125
3
[]
no_license
// Exercício: Prova de Suficiência 2020/2 // Aluno: Gustavo de Souza Silveira - 23/10/2020 // Prof. Sergio Moribe - UTFPR-CT #include <LiquidCrystal.h> //Define os pinos do Display LCD no Arduino const int rs = 8, en = 9, d4 = 10, d5 = 11, d6 = 12, d7 = 13; //Instancia objeto lcd LiquidCrystal lcd(rs, en, d4, d5, d6, d7); //lcd em 4 bits // quantidade de linhas e colunas do LCD const int linhasLCD = 2, colunasLCD = 16; // texto inicial do editor de texto const String textoInicial = "Proj. PWM"; // linha vazia para limpar o LCD const String linhaVazia = " "; // Configuração das interrupções #define pinIniciar 2 #define pinParar 3 // Declaração da função de estado void estadoCircuito(); void botaoLigar(); void botaoDesligar(); // Estado do PWM bool estado = false; // Saidas PWM #define pinLed1 5 #define pinLed2 6 // millis unsigned long time = 0; unsigned long timeAnterior= 0; void setup() { // Configurações do PWM que aciona os LEDs pinMode(pinLed1, OUTPUT); //Onde vai sair o sinal PWM 1 pinMode(pinLed2, OUTPUT); //Onde vai sair o sinal PWM 2 // Pinos de interrupção pinMode(pinIniciar, INPUT_PULLUP); pinMode(pinParar, INPUT_PULLUP); // Configuração do LCD lcd.begin(colunasLCD, linhasLCD); lcd.setCursor(0,0); //Posiciona cursor na 1a linha lcd.print(textoInicial); lcd.setCursor(0,1); //Posiciona cursor na 2a linha lcd.noBlink(); //Pisca o cursor // Modo padrão: Desligado estadoCircuito(); // Instancia das interrupções attachInterrupt(digitalPinToInterrupt(pinIniciar), botaoLigar, FALLING); attachInterrupt(digitalPinToInterrupt(pinParar), botaoDesligar, FALLING); } void loop() { char LCD[16]; int canal01 = 0; int canal02 = 0; time = millis(); // tempo atual if (estado) { // Lendo valores analogicos canal01 = analogRead(A0); canal02 = analogRead(A1); // percentual de cada canal int percentualCanal01 = map(canal01 , 0, 1023, 0, 100); int percentualCanal02 = map(canal02 , 0, 1023, 0, 100); percentualCanal01 = percentualCanal01 > 0 ? percentualCanal01 : 0; percentualCanal02 = percentualCanal02 > 0 ? percentualCanal02 : 0; if ( (time - timeAnterior) > 100 ) { // Canal 01 dtostrf(percentualCanal01,3,0,LCD); lcd.setCursor(0,1); //Posiciona cursor na 2a linha lcd.print(linhaVazia); lcd.setCursor(2,1); //Posiciona cursor na 2a linha lcd.print(" "); lcd.setCursor(2,1); //Posiciona cursor na 2a linha lcd.print(LCD); lcd.print("%"); // Canal 02 dtostrf(percentualCanal02,3,0,LCD); lcd.setCursor(8,1); //Posiciona cursor na 2a linha lcd.print(" "); lcd.setCursor(8,1); //Posiciona cursor na 2a linha lcd.print(LCD); lcd.print("%"); timeAnterior = time; } } // Atualizando LEDs analogWrite(pinLed1, canal01 / 4); analogWrite(pinLed2, canal02 / 4); } void estadoCircuito() { lcd.setCursor(0,1); //Posiciona cursor na 2a linha lcd.print(linhaVazia); lcd.setCursor(0,1); if (estado) { lcd.print("Ligado... "); delay(5000); } else { lcd.print("Desligado... "); } } void botaoLigar() { estado = true; estadoCircuito(); } void botaoDesligar() { estado = false; estadoCircuito(); }
true
d8e7880307c5fb4ab6d88a57956df5ac184fe5cc
C++
veldrinlab/veldrinlabProjects
/SakuraEngine/SakuraEngine/Game/Game.hpp
WINDOWS-1250
710
3.046875
3
[]
no_license
/** * File contains declaration of main game class - Game. * @file Game.hpp * @author Szymon "Veldrin" Jaboski & Adam Sznajder * @date 2010-11-09 * @version 1.0 */ #ifndef GAME_HPP #define GAME_HPP #include "../Engine/Engine.hpp" #include "../Engine/Configuration.hpp" #include "GameState.hpp" namespace Game { /** * Game main class. * @remarks */ class Game { private: Engine::Engine* gameEngine; GameState* actualState; bool gameDone; public: Game(); ~Game(); virtual void performAction(); Engine::Engine* getGameEngine() const; GameState* getActualState() const; bool isGameDone() const; void setGameDone(const bool done); void setGameState(GameState* gameState); }; } #endif
true
2ec3aafb8b27ee5e6e5bb354deb53503c8740b6a
C++
asntr/DAS
/CPP/12-spin-lock/spin_lock.h
UTF-8
323
3.28125
3
[]
no_license
#pragma once #include <atomic> #include <thread> class SpinLock { public: void lock() { while (lock_.test_and_set(std::memory_order_acquire)) std::this_thread::yield(); } void unlock() { lock_.clear(std::memory_order_release); } private: std::atomic_flag lock_ = ATOMIC_FLAG_INIT; };
true
14d3b8e3e7a60fe9a84cc42de8e85d6909ab785e
C++
12Dong/acm
/hdu/1181.cpp
UTF-8
703
2.671875
3
[]
no_license
#include<iostream> #include<string> #include<cstring> using namespace std; int map[26][26]; int vis[26]; int flag; void dfs(int x,int y) { if(vis[x]) return ; vis[x]=1; if(x==y) { flag=1; return ; } for(int i=0;i<26;i++) { if(map[x][i]==1) { dfs(i,y); } } } int main() { string str; flag=0; memset(vis,0,sizeof(vis)); memset(map,0,sizeof(map)); while(cin >>str) { flag=0; map[str[0]-'a'][str[str.size()-1]-'a']=1; while(cin >> str && str[0]!='0') { map[str[0]-'a'][str[str.size()-1]-'a']=1; } dfs('b'-'a','m'-'a'); if(flag==1) cout <<"Yes."<<endl; else cout <<"No."<<endl; memset(vis,0,sizeof(vis)); memset(map,0,sizeof(map)); } }
true
c1d0fef8582cdd9b6a0b14aa1891d1b6a21cf445
C++
sameerad2001/myGeekForGeeksPracticeQuestions
/Tree/Easy/Level of a Node in Binary Tree/main.cpp
UTF-8
636
3.40625
3
[]
no_license
#include <iostream> using namespace std; struct Node { int data; struct Node *left; struct Node *right; }; void get_level_utl(Node *node, int target, int &target_level, int curr_level) { if (node == NULL) return; if (node->data == target) { target_level = curr_level; return; } get_level_utl(node->left, target, target_level, curr_level + 1); get_level_utl(node->right, target, target_level, curr_level + 1); } int getLevel(Node *node, int target) { int target_level = 0; get_level_utl(node, target, target_level, 1); return target_level; } int main() { }
true
8c2833977e7c8e85ea18665f8766b71dea8782f5
C++
geoo993/LearningCpp
/BeginnersTutorials/workspace/Classes/src/Countries.h
UTF-8
898
2.75
3
[]
no_license
/* * Countries.h * * Created on: Sep 6, 2016 * Author: GeorgeQuentin */ #ifndef COUNTRIES_H_ #define COUNTRIES_H_ #include <string> class Country { private: std::string countryName; std::string capital; long int population; std::string nationalLanguage; std::string currency; public: Country(); Country(std::string countryName, std::string capital, long int population, std::string nationalLanguage, std::string currency); void setCountry(std::string countryName, std::string capital, long int population, std::string nationalLanguage, std::string currency); int stringToInt(std::string str); void countryInfo(std::string name); std::string getCountryName(); std::string getCapital(); long int getPopulation(); std::string getNationalLanguage(); std::string getCurrency(); void print(); // }; #endif /* COUNTRIES_H_ */
true
40873a730c6693958bd7cb1bce7e17e7a978eea9
C++
falgon/mikoCppLibraries
/miko/casting.hpp
UTF-8
1,393
2.609375
3
[]
no_license
namespace miko{ template<class from> class Static_Cast{ from var; public: Static_Cast(from f):var(f){} template<class T> operator T()const { return static_cast<T>(var); } }; template<class from> Static_Cast<from> st_cast(from v) { return Static_Cast<from>(v); } template<class from> class Dynamic_Cast{ from var; public: Dynamic_Cast(from f):var(f){} template<class T> operator T()const { return dynamic_cast<T>(var); } }; template<class from> Dynamic_Cast<from> dy_cast(from v) { return Dynamic_Cast<from>(v); } template<class from> class Const_Cast{ from var; public: Const_Cast(from f):var(f){} template<class T> operator T()const { return const_cast<T>(var); } }; template<class from> Const_Cast<from> co_cast(from v) { return Const_Cast<from>(v); } template<class from> class Reinterpret_Cast{ from var; public: Reinterpret_Cast(from f):var(f){} template<class T> operator T()const { return reinterpret_cast<T>(var); } }; template<class from> Reinterpret_Cast<from> re_cast(from v) { return Reinterpret_Cast<from>(v); } #include<sstream> template<class from> class Lexical_Cast{ from var; public: Lexical_Cast(from f):var(f){} template<class T> operator T()const { T result; std::stringstream ss; ss<<var; ss>>result; return result; } }; template<class from> Lexical_Cast<from> le_cast(from v) { return Lexical_Cast<from>(v); } }
true
7b4360c0f2fcda5a2ca15a3205e5d6b490eda85d
C++
YoshiroAraya/Yoshidagakuen_ArayaYoshiro
/吉田学園情報ビジネス専門学校 荒谷由朗/04_OverKillSoulHell/00_制作環境/bullet.cpp
SHIFT_JIS
13,872
2.625
3
[]
no_license
//============================================================================= // // obg [bullet.cpp] // Author : rJ RN // //============================================================================= #include "bullet.h" #include "input.h" #include "manager.h" #include "scene2D.h" #include "renderer.h" #include "explosion.h" #include "player.h" #include "enemy.h" #include "score.h" #include "effect.h" //============================================================================= // ÓIoϐ //============================================================================= LPDIRECT3DTEXTURE9 CBullet::m_pTexture[MAX_BULLETTEXTURE] = {}; //============================================================================= //@RXgN^ //============================================================================= CBullet::CBullet():CScene2D(2) { m_fWidth = NULL; m_fHeight = NULL; m_fAngle = NULL; } //============================================================================= //@fXgN^ //============================================================================= CBullet::~CBullet() { } //============================================================================= //@ //============================================================================= CBullet *CBullet::Create(D3DXVECTOR3 pos, float width, float height, BULLETTYPE Bullettype) { CBullet *pBullet = NULL; pBullet = new CBullet; pBullet->Init(pos, width, height, Bullettype); pBullet->m_BulletType = Bullettype; switch (Bullettype) { case BULLETTYPE_SLASH: pBullet->BindTexture(m_pTexture[0]); break; case BULLETTYPE_POISON: pBullet->BindTexture(m_pTexture[1]); break; case BULLETTYPE_FLAME: pBullet->BindTexture(m_pTexture[2]); break; case BULLETTYPE_WIND: pBullet->BindTexture(m_pTexture[3]); break; case BULLETTYPE_ENEMY: pBullet->BindTexture(m_pTexture[4]); break; case BULLETTYPE_MP_HOMING: pBullet->BindTexture(m_pTexture[5]); break; case BULLETTYPE_MP_PAIR: pBullet->BindTexture(m_pTexture[2]); break; } return pBullet; } //============================================================================= //@[h //============================================================================= HRESULT CBullet::Load(void) { // foCX̎擾 CRenderer *pRenderer = CManager::GetRenderer(); LPDIRECT3DDEVICE9 pDevice = pRenderer->GetDevice(); // eNX`̓ǂݍ D3DXCreateTextureFromFile(pDevice, BULLET_TEXTURENAME00, &m_pTexture[0]); D3DXCreateTextureFromFile(pDevice, BULLET_TEXTURENAME01, &m_pTexture[1]); D3DXCreateTextureFromFile(pDevice, BULLET_TEXTURENAME02, &m_pTexture[2]); D3DXCreateTextureFromFile(pDevice, BULLET_TEXTURENAME03, &m_pTexture[3]); D3DXCreateTextureFromFile(pDevice, BULLET_TEXTURENAME04, &m_pTexture[4]); D3DXCreateTextureFromFile(pDevice, BULLET_TEXTURENAME05, &m_pTexture[5]); return S_OK; } //============================================================================= //@A[h //============================================================================= void CBullet::Unload(void) { // eNX`̔j for (int nCntBullet = 0;nCntBullet < MAX_BULLETTEXTURE;nCntBullet++) { if (m_pTexture[nCntBullet] != NULL) { m_pTexture[nCntBullet]->Release(); m_pTexture[nCntBullet] = NULL; } } } //============================================================================= // //============================================================================= HRESULT CBullet::Init(D3DXVECTOR3 pos, float width, float height, BULLETTYPE Bullettype) { m_fWidth = width; m_fHeight = height; m_nCounterAnim = 0; CScene2D::Init(); SetObjType(CScene::OBJTYPE_BULLET); // IuWFNg̎ނݒ CScene2D::SetPosition(pos, m_fWidth, m_fHeight); switch (Bullettype) { case BULLETTYPE_SLASH: CScene2D::SetTexture(m_nPatternAnim, 4, 1); break; case BULLETTYPE_POISON: CScene2D::SetTexture(m_nPatternAnim, 5, 2); break; case BULLETTYPE_FLAME: CScene2D::SetTexture(m_nPatternAnim, 5, 1); break; case BULLETTYPE_WIND: CScene2D::SetTexture(m_nPatternAnim, 8, 2); break; case BULLETTYPE_ENEMY: CScene2D::SetTexture(m_nPatternAnim, 1, 1); break; case BULLETTYPE_MP_HOMING: CScene2D::SetTexture(m_nPatternAnim, 1, 1); break; case BULLETTYPE_MP_PAIR: CScene2D::SetTexture(m_nPatternAnim, 5, 1); break; } return S_OK; } //============================================================================= // I //============================================================================= void CBullet::Uninit(void) { CScene2D::Uninit(); } //============================================================================= // XV //============================================================================= void CBullet::Update(void) { float fWidth, fHeight; D3DXVECTOR3 pos = CScene2D::GetPosition(); // W̎擾 BULLETTYPE BulletType = GetBulletType(); // e^Cv̎擾 CPlayer *pPlayer = CManager::GetPlayer(); // vC[̎擾 if (pPlayer != NULL) { m_PlayerPos = pPlayer->GetPosition(); } m_nCounterAnim++; if ((m_nCounterAnim % 2) == 0) // Aj[V̑ς { m_nPatternAnim = (m_nPatternAnim + 1); switch (BulletType) { case BULLETTYPE_SLASH: if (m_nPatternAnim >= 3) { m_nPatternAnim = 3; } break; case BULLETTYPE_POISON: if (m_nPatternAnim > 9) { m_nPatternAnim = 9; } break; case BULLETTYPE_FLAME: if (m_nPatternAnim > 4) { m_nPatternAnim = 4; } break; case BULLETTYPE_WIND: break; case BULLETTYPE_ENEMY: if (m_nPatternAnim > 0) { m_nPatternAnim = 0; } break; case BULLETTYPE_MP_HOMING: if (m_nPatternAnim > 0) { m_nPatternAnim = 0; } break; case BULLETTYPE_MP_PAIR: if (m_nPatternAnim > 4) { m_nPatternAnim = 4; } break; } switch (BulletType) { case BULLETTYPE_SLASH: CScene2D::SetTexture(m_nPatternAnim, 4, 1); break; case BULLETTYPE_POISON: CScene2D::SetTexture(m_nPatternAnim, 5, 2); break; case BULLETTYPE_FLAME: CScene2D::SetTexture(m_nPatternAnim, 5, 1); break; case BULLETTYPE_WIND: CScene2D::SetTexture(m_nPatternAnim, 8, 2); break; case BULLETTYPE_ENEMY: CScene2D::SetTexture(m_nPatternAnim, 1, 1); break; case BULLETTYPE_MP_HOMING: CScene2D::SetTexture(m_nPatternAnim, 1, 1); break; case BULLETTYPE_MP_PAIR: CScene2D::SetTexture(m_nPatternAnim, 5, 1); break; } } if (pos.x < SCREEN_WIDTH && pos.x > 0) { if (BulletType == BULLETTYPE_ENEMY) { if (m_nCounterAnim < 25) { m_fAngle = atan2f(m_PlayerPos.x - pos.x, m_PlayerPos.y - pos.y); } m_move.x += sinf(m_fAngle) * ENEMY_SPEED; m_move.y += cosf(m_fAngle) * ENEMY_SPEED; // ʒuXV pos.x += m_move.x; pos.y += m_move.y; CScene2D::SetPosition(pos, m_fWidth, m_fHeight); CScene2D::SetRot(m_fAngle, m_fWidth, m_fHeight); } else if (BulletType == BULLETTYPE_MP_HOMING) { m_mode = CManager::GetMode(); switch (m_mode) { case CManager::MODE_TUTORIAL: m_fAngle = atan2f((pos.x + 10.0f) - pos.x, pos.y - pos.y); m_move.x += sinf(m_fAngle) * 0.25f; m_move.y += cosf(m_fAngle) * 0.25f; // ʒuXV pos.x += m_move.x; pos.y += m_move.y; CScene2D::SetPosition (pos, m_fWidth, m_fHeight); CScene2D::SetRot (m_fAngle, m_fWidth, m_fHeight); break; case CManager::MODE_GAME: for (int nCntPri = 0; nCntPri < NUM_PRIORITY; nCntPri++) { for (int nCntScene = 0; nCntScene < MAX_SCENE; nCntScene++) { CScene *pScene; pScene = CScene::GetScene(nCntPri, nCntScene); if (pScene != NULL) { // IuWFNg̎ނ擾 CScene::OBJTYPE objtype; objtype = pScene->GetObjType(); if (objtype == OBJTYPE_ENEMY) {// G̓蔻 // Gl~[̍W擾 CScene2D *pScene2D = ((CScene2D*)pScene); D3DXVECTOR3 posEnemy = pScene2D->GetPosition(); if (pScene2D != NULL && m_nCounterAnim < 25) { m_fAngle = atan2f(posEnemy.x - pos.x, posEnemy.y - pos.y); } } } } } m_move.x += sinf(m_fAngle) * 0.25f; m_move.y += cosf(m_fAngle) * 0.25f; // ʒuXV pos.x += m_move.x; pos.y += m_move.y; CScene2D::SetPosition (pos, m_fWidth, m_fHeight); CScene2D::SetRot (m_fAngle, m_fWidth, m_fHeight); break; } } else if (BulletType == BULLETTYPE_MP_PAIR) { for (int nCntPri = 0; nCntPri < NUM_PRIORITY; nCntPri++) { for (int nCntScene = 0; nCntScene < MAX_SCENE; nCntScene++) { CScene *pScene; pScene = CScene::GetScene(nCntPri, nCntScene); if (pScene != NULL) { // IuWFNg̎ނ擾 CScene::OBJTYPE objtype; objtype = pScene->GetObjType(); if (objtype == OBJTYPE_ENEMY) {// G̓蔻 // Gl~[̍W擾 CScene2D *pScene2D = ((CScene2D*)pScene); D3DXVECTOR3 posEnemy = pScene2D->GetPosition(); if (pScene2D != NULL && m_nCounterAnim < 42) { m_fAngle = atan2f(posEnemy.x - pos.x, posEnemy.y - pos.y); } } } } } if (m_nCounterAnim < 10) { if (m_PlayerPos.y <= SCREEN_HEIGHT / 2) {// ɂƂ m_move.x += 0.5f; m_move.y += 0.5f; // m_move.x += (0.0f - m_move.x) * PAIR_SPEED; m_move.y += (0.0f - m_move.y) * PAIR_SPEED; } else if (m_PlayerPos.y > SCREEN_HEIGHT / 2) {// ɂƂ m_move.x += 0.5f; m_move.y -= 0.5f; // m_move.x += (0.0f - m_move.x) * PAIR_SPEED; m_move.y += (0.0f - m_move.y) * PAIR_SPEED; } } else if (m_nCounterAnim < 42) { m_move.x += sinf(m_fAngle) * PAIR_SPEED; m_move.y += cosf(m_fAngle) * PAIR_SPEED; } // ʒuXV pos.x += m_move.x; pos.y += m_move.y; CScene2D::SetPosition (pos, m_fWidth, m_fHeight); CScene2D::SetRot (m_fAngle, m_fWidth, m_fHeight); } else { switch (BulletType) { case BULLETTYPE_SLASH: m_move.x += SLASH_SPEED; break; case BULLETTYPE_POISON: m_move.x += POISON_SPEED; break; case BULLETTYPE_FLAME: m_move.x += FLAME_SPEED; break; case BULLETTYPE_WIND: m_move.x += WIND_SPEED; break; } // m_move.x += (0.0f - m_move.x) * 0.25f; m_move.y += (0.0f - m_move.y) * 0.25f; // ʒuXV pos.x += m_move.x; pos.y += m_move.y; CScene2D::SetPosition(pos, m_fWidth, m_fHeight); } for (int nCntPri = 0; nCntPri < NUM_PRIORITY; nCntPri++) {// 蔻 for (int nCntScene = 0; nCntScene < MAX_SCENE; nCntScene++) { CScene *pScene; pScene = CScene::GetScene(nCntPri, nCntScene); if (pScene != NULL) { // IuWFNg̎ނ擾 CScene::OBJTYPE objtype; objtype = pScene->GetObjType(); if (objtype == OBJTYPE_ENEMY && BulletType != BULLETTYPE_ENEMY) {// G̓蔻 // Gl~[̍W擾 CScene2D *pScene2D = ((CScene2D*)pScene); D3DXVECTOR3 posEnemy = pScene2D->GetPosition(); fWidth = pScene2D->GetWidth(); fHeight = pScene2D->GetHeight(); if (pScene2D != NULL) { if (posEnemy.x + fWidth > pos.x && pos.x > posEnemy.x - fWidth && posEnemy.y + fHeight > pos.y && pos.y > posEnemy.y - fHeight) { //蔻 CEnemy *pEnemy = ((CEnemy*)pScene); switch (BulletType) { case BULLETTYPE_SLASH: pEnemy->HitEnemy(SLASH_POWER, BulletType); break; case BULLETTYPE_POISON: pEnemy->HitEnemy(POISON_POWER, BulletType); break; case BULLETTYPE_FLAME: pEnemy->HitEnemy(FLAME_POWER, BulletType); break; case BULLETTYPE_WIND: pEnemy->HitEnemy(WIND_POWER, BulletType); break; case BULLETTYPE_MP_HOMING: pEnemy->HitEnemy(HOMING_POWER, BulletType); break; case BULLETTYPE_MP_PAIR: pEnemy->HitEnemy(PAIR_POWER, BulletType); break; } Uninit(); break; } } } else if (objtype == OBJTYPE_PLAYER && BulletType == BULLETTYPE_ENEMY) { CScene2D *pScene2D = ((CScene2D*)pScene); D3DXVECTOR3 posPlayer = pScene2D->GetPosition(); fWidth = pScene2D->GetWidth(); fHeight = pScene2D->GetHeight(); if (pScene2D != NULL) { if (posPlayer.x + fWidth > pos.x && pos.x > posPlayer.x - fWidth && posPlayer.y + fHeight > pos.y && pos.y > posPlayer.y - fHeight) { //蔻 CPlayer *pPlayer = ((CPlayer*)pScene); pPlayer->HitPlayer(1); if (pPlayer != NULL) { Uninit(); } break; } } } } } } } else { Uninit(); } } //============================================================================= // `揈 //============================================================================= void CBullet::Draw(void) { CScene2D::Draw(); } //============================================================================= // ^Cv̐ݒ //============================================================================= void CBullet::SetBulletType(BULLETTYPE bullettype) { m_BulletType = bullettype; } //============================================================================= // ^Cv̎擾 //============================================================================= CBullet::BULLETTYPE CBullet::GetBulletType(void) { return m_BulletType; }
true
d82d026e1d8db10b42b1f3a6a922577c99530942
C++
imanoid/drobot
/new/src/drobot/util/exception.h
UTF-8
1,013
3.234375
3
[]
no_license
#ifndef DROBOT_UTIL_EXCEPTION_H #define DROBOT_UTIL_EXCEPTION_H #include <string> #include <sstream> namespace drobot { namespace util { /** * @brief The Exception class is the base class for all exceptions. */ class Exception { private: std::string _message; public: Exception(std::string message); Exception(); std::string getMessage(); /** * @brief operator << is used to append a string to the message * @param message * @return reference to the exception */ Exception& operator<<(std::string message); /** * @brief operator << is used to append a int to the message * @param message * @return reference to the exception */ Exception& operator<<(int message); /** * @brief operator << is used to append a double to the message * @param message * @return reference to the exception */ Exception& operator<<(double message); }; } // namespace util } // namespace drobot #endif // DROBOT_UTIL_EXCEPTION_H
true
f74b1fe7b029203b09cadac3e171f0196a456c2f
C++
vuongjn/PE4
/TicTacToe.cpp
UTF-8
1,314
3.84375
4
[]
no_license
#include <iostream> #include <string> class TicTacToe { private: int turnCount_ = 0; std::string board_[3][3]; public: void CreateBoard(){ for(int i = 0; i < 3; i++){ for(int j = 0; j < 3; j++){ board_[i][j] = "_"; } } } void DisplayBoard(){ for(int i = 0; i < 3; i++){ for(int j = 0; j < 3; j++){ std::cout << board_[i][j] << " "; } std::cout<<std::endl; } } void PlaceMarker(int input[]){ int row = input[0]; int col = input[1]; if(turnCount_ % 2 == 0){ board_[row][col] = "X"; } else{ board_[row][col] ="O"; } turnCount_++; } int* GetPlayerChoice(){ int row; int col; std::cout<< "What x move do you want to make?" << std::endl; std::cin >> row; std::cout<< "What y move do you want to make?" << std::endl; std::cin >> col; int* input = new int[2]; input[0] = row; input[1] = col; return input; } }; int main() { TicTacToe *game = new TicTacToe(); game->CreateBoard(); game->DisplayBoard(); for (int i = 0; i < 9; i++) { int* arr = game->GetPlayerChoice(); game->PlaceMarker(arr); game->DisplayBoard(); } }
true
97a7ea2bd5a775649f35ef8ab2f6ffd6e31fa3bd
C++
hapo31/My-MikanOS
/kernel/font.cpp
UTF-8
1,283
2.765625
3
[ "Apache-2.0" ]
permissive
#include "font.hpp" extern const uint8_t _binary_hankaku_bin_start; extern const uint8_t _binary_hankaku_bin_end; extern const uint8_t _binary_hankaku_bin_size; void WriteAscii(PixelWriter &writer, int x, int y, const PixelColor &color, char c) { const uint8_t *font = GetFont(c); if (font == nullptr) { return; } for (int dy = 0; dy < 16; ++dy) { for (int dx = 0; dx < 8; ++dx) { if (font[dy] << dx & 0x80u) { writer.Write(color, dx + x, dy + y); } } } } void WriteAscii(PixelWriter &writer, Vector2D<int> pos, const PixelColor &color, char c) { WriteAscii(writer, pos.x, pos.y, color, c); } void WriteString(PixelWriter &writer, int x, int y, const PixelColor &color, const char *str) { for (int i = 0; str[i] != '\0'; ++i) { WriteAscii(writer, x + i * 8, y, color, str[i]); } } void WriteString(PixelWriter &writer, Vector2D<int> pos, const PixelColor &color, const char *c) { WriteString(writer, pos.x, pos.y, color, c); } const uint8_t *GetFont(char c) { auto index = 16 * static_cast<unsigned int>(c); if (index >= reinterpret_cast<uintptr_t>(&_binary_hankaku_bin_size)) { return nullptr; } return &_binary_hankaku_bin_start + index; }
true
8be4e6ed2a25110371e92097199b51738e4c1a69
C++
RecetteLemon/SymphonyOfNight
/woojin/Hynjun(DataBase+CharaScene) - 복사본/player.h
UHC
2,871
2.625
3
[]
no_license
#pragma once #include "gameNode.h" #include "pixelCollision.h" #include "familiarManager.h" #define MOVESPEED 3.0f #define JUMPFORCE 6.0f #define GRAVITYPOWER 0.5f enum KEYINPUT { INPUT_LEFT, INPUT_LEFT_DOWN, INPUT_DOWN, INPUT_RIGHT_DOWN, INPUT_RIGHT, INPUT_LEFT_UP, INPUT_UP, INPUT_RIGHT_UP, INPUT_Z, INPUT_X, INPUT_S, INPUT_D, INPUT_NOT }; // ÷̾ ൿ enum PLAYERDIRECTION { DIR_RIGHT_STOP, // DIR_LEFT_STOP, DIR_RIGHT_MOVE, // ϶ DIR_LEFT_MOVE, DIR_RIGHT_SIT, // DIR_LEFT_SIT, DIR_RIGHT_BACKDASH, // 뽬 Ҷ DIR_LEFT_BACKDASH, DIR_RIGHT_JUMP, // Ҷ DIR_LEFT_JUMP, DIR_RIGHT_MOVE_JUMP, // ̸鼭 Ҷ DIR_LEFT_MOVE_JUMP, DIR_RIGHT_SUPER_JUMP, // Ҷ DIR_LEFT_SUPER_JUMP, DIR_RIGHT_FALL, // DIR_LEFT_FALL, DIR_RIGHT_ATK, // Ϲ Ҷ DIR_LEFT_ATK, DIR_RIGHT_AIR_ATK, // ߿ Ҷ DIR_LEFT_AIR_ATK, DIR_RIGHT_HIT, // ¾ DIR_LEFT_HIT, DIR_RIGHT_SKILL, // ų DIR_LEFT_SKILL }; class player : public gameNode { private: bool _isOp; PLAYERDIRECTION _playerDir; // ÷̾ ൿ image* _image[2]; float _x, _y, _gravity, _jumpForce; bool isDjump; RECT _rc_Hit; // ǰ RECT _rc_Atk; // animation* _playerMotion; // pixelCollision _collision; // ȼ 浹 // Ŀǵ vector<KEYINPUT> _vCommand; vector<KEYINPUT>::iterator _viCommand; KEYINPUT _currentInput; KEYINPUT _prevInput; float keyTimer; // ۹и familiarManager* _fm; float _fX, _fY; image* _imageName; public: HRESULT init(float x, float y, image* img, bool isOp = false); void release(); void update(); void render(HDC hdc); void playerDirection(); void opening(); // Ŀǵ void keyInput(); void showInput(); void checkCommand(); // ̱ static void rightMoving(void* obj); static void leftMoving(void* obj); // static void rightStopping(void* obj); static void leftStopping(void* obj); // ɾ static void rightSitting(void* obj); static void leftSitting(void * obj); // static void rightFalling(void* obj); static void leftFalling(void* obj); // getter setter inline float getPlayerPosX() { return _x; } inline float getPlayerPosY() { return _y; } void setPlayerPosX(float x) { _x = x; } void setPlayerPosY(float y) { _y = y; } //inline const char* getImageName() { return _imageName; } PLAYERDIRECTION getPlayerDir() { return _playerDir; } void setPlayerDir(PLAYERDIRECTION dir) { _playerDir = dir; } animation* getPlayerMotion() { return _playerMotion; } void setPlayerMotion(animation* ani) { _playerMotion = ani; } void setFamiliarDirection(void); player(); ~player(); };
true
3202969307817243cc950a60913abc841524bc41
C++
creator83/stm8s003
/cpp/prj/use_gpio.cpp
UTF-8
676
2.625
3
[]
no_license
#include "stm8s.h" #include "pin.h" #include "delay.h" Pin triac1 (Gpio::A, 3, Gpio::lowSpeed); Pin triac2 (Gpio::D, 3, Gpio::lowSpeed); Pin triac3 (Gpio::D, 4, Gpio::lowSpeed); Pin triac4 (Gpio::D, 5, Gpio::lowSpeed); Pin triac5 (Gpio::D, 6, Gpio::lowSpeed); union rgb24 { uint32_t color; struct colors { uint8_t red; uint8_t green; uint8_t blue; }; }; Pin * triacs [5] = {&triac1, &triac2, &triac3, &triac4, &triac5}; int main() { CLK->CKDIVR = 0; while (1) { for (uint8_t i=0;i<5;++i) triacs [i]->set (); delay_ms (1000); for (uint8_t i=0;i<5;++i) triacs [i]->clear (); delay_ms (1000); } }
true