hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
109
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
48.5k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
9ba16e2b3b2e7967375bb965138ec895aebf545a
1,970
hpp
C++
include/core/Acceleration.hpp
BlauHimmel/Hikari
38746e5d03a8e106a346a6f792f3093034a576bb
[ "MIT" ]
11
2018-11-22T03:07:10.000Z
2022-03-31T15:51:29.000Z
include/core/Acceleration.hpp
BlauHimmel/Hikari
38746e5d03a8e106a346a6f792f3093034a576bb
[ "MIT" ]
2
2019-02-14T15:05:42.000Z
2019-07-26T06:07:13.000Z
include/core/Acceleration.hpp
BlauHimmel/Hikari
38746e5d03a8e106a346a6f792f3093034a576bb
[ "MIT" ]
4
2018-12-18T12:40:07.000Z
2022-03-31T15:51:31.000Z
#pragma once #include <core\Common.hpp> #include <core\Object.hpp> #include <core\Mesh.hpp> #include <core\MemoryArena.hpp> NAMESPACE_BEGIN /** * \brief Acceleration data structure for ray intersection queries * * The current implementation falls back to a brute force loop * through the geometry. */ class Acceleration : public Object { public: Acceleration(const PropertyList & PropList); /** * \brief Register a triangle mesh for inclusion in the acceleration * data structure * * This function can only be used before \ref Build() is called */ void AddMesh(Mesh * pMesh); /// Build the acceleration data structure (currently a no-op) virtual void Build(); /// Return an axis-aligned box that bounds the scene const BoundingBox3f & GetBoundingBox() const; /// Return the size used for store the Shape (eg. triangles of the mesh) size_t GetUsedMemoryForShape() const; /** * \brief Intersect a ray against all triangles stored in the scene and * return detailed intersection information * * \param Ray * A 3-dimensional ray data structure with minimum/maximum extent * information * * \param Isect * A detailed intersection record, which will be filled by the * intersection query * * \param bShadowRay * \c true if this is a shadow ray query, i.e. a query that only aims to * find out whether the ray is blocked or not without returning detailed * intersection information. * * \return \c true if an intersection was found */ virtual bool RayIntersect(const Ray3f & Ray, Intersection & Isect, bool bShadowRay) const; /** * \brief Return the type of object (i.e. Mesh/BSDF/etc.) * provided by this instance * */ virtual EClassType GetClassType() const override; /// Return a brief string summary of the instance (for debugging purposes) virtual std::string ToString() const override; protected: std::vector<Shape *> m_pShapes; BoundingBox3f m_BBox; MemoryArena m_MemoryArena; }; NAMESPACE_END
26.621622
91
0.732487
BlauHimmel
9bab83e12fb087a554f31d4e874efb503700a6c7
11,772
cpp
C++
wmis/lib/mis/ml/ml_features.cpp
josephholten/KaMIS-ml
9b17d8764a72b75b04519aaaa5858f69d2ae4c54
[ "MIT" ]
null
null
null
wmis/lib/mis/ml/ml_features.cpp
josephholten/KaMIS-ml
9b17d8764a72b75b04519aaaa5858f69d2ae4c54
[ "MIT" ]
null
null
null
wmis/lib/mis/ml/ml_features.cpp
josephholten/KaMIS-ml
9b17d8764a72b75b04519aaaa5858f69d2ae4c54
[ "MIT" ]
null
null
null
// // Created by joseph on 10/27/21. // #include "ml_features.h" #include <random> #include <unordered_set> #include "mis_config.h" #include "configuration_mis.h" #include "timer.h" #include "graph_io.h" #include "weighted_ls.h" #include "stat.h" // constructors // for training (many graphs with labels) ml_features::ml_features(const MISConfig& config) : has_labels {true} { configuration_mis cfg; cfg.standard(mis_config); mis_config.console_log = config.console_log; mis_config.ml_pruning = config.ml_pruning; mis_config.time_limit = config.ls_time; mis_config.ls_rounds = config.ls_rounds; } // for reducing (single graph without labels) ml_features::ml_features(const MISConfig& config, graph_access &G) : has_labels {false} { configuration_mis cfg; cfg.standard(mis_config); mis_config.console_log = config.console_log; mis_config.ls_updates = config.ls_updates; mis_config.ml_pruning = config.ml_pruning; mis_config.time_limit = config.ls_time; mis_config.ls_rounds = config.ls_rounds; reserveNodes(G.number_of_nodes()); fillGraph(G); } ml_features::~ml_features() { XGDMatrixFree(dmat); } void ml_features::fromPaths(const std::vector<std::string> &all_graph_paths, const std::vector<std::string>& all_label_paths) { assert((all_graph_paths.size() == all_label_paths.size()) && "Error: provide same number of graph and label paths\n"); std::vector<std::string> graph_paths; std::vector<std::string> label_paths; for (int i = 0; i < all_graph_paths.size(); ++i) { if (graph_io::readNumberOfNodes(all_graph_paths[i]) > 0) { graph_paths.push_back(all_graph_paths[i]); label_paths.push_back(all_label_paths[i]); } } std::cout << "LOG: ml-calcFeatures: " << graph_paths.size() << " of " << all_graph_paths.size() << " were non empty\n"; // calculate the node offsets of each graph // produces a mapping of index in the list of paths (provided by the user) and the start position in the feature_matrix and label_data std::vector<NodeID> offsets(graph_paths.size()+1,0); for (int i = 0; i < graph_paths.size(); i++) { offsets[i+1] = offsets[i] + graph_io::readNumberOfNodes(graph_paths[i]); } // last offset is total number of nodes reserveNodes(offsets[graph_paths.size()]); // #pragma omp parallel for default(none) shared(graph_paths, label_paths, offsets, std::cout) for (int i = 0; i < graph_paths.size(); ++i) { // std::cout << "Thread " << omp_get_thread_num() << std::endl; std::cout << "LOG: ml-calcFeatures: graph " << graph_paths[i] << " (" << (float) i / graph_paths.size() * 100 << "%)\n"; graph_access G; graph_io::readGraphWeighted(G, graph_paths[i]); std::vector<float> labels(G.number_of_nodes(), 0); graph_io::readVector<float>(labels.begin(), offsets[i+1]-offsets[i], label_paths[i]); fillGraph(G, labels, offsets[i]); } } // init void ml_features::reserveNodes(NodeID n) { feature_matrix.resize(feature_matrix.size() + n); label_data.resize(label_data.size() + n); } void ml_features::fillGraph(graph_access& G) { if (has_labels) { std::cerr << "Error: feature matrix was constructed for labels, so provide the labels for the graph.\n"; exit(1); } calcFeatures(G); } void ml_features::fillGraph(graph_access& G, std::vector<float>& labels, NodeID offset) { if (!has_labels) { std::cerr << "Error: feature matrix was constructed not for labels, so the labels will be discarded.\n"; } calcFeatures(G); std::copy(labels.begin(), labels.end(), label_data.begin() + offset); } template<ml_features::feature f> float& ml_features::getFeature(NodeID node) { return feature_matrix[node + current_size][f]; } void ml_features::calcFeatures(graph_access& G) { // timer t; NodeWeight total_weight = 0; forall_nodes(G, node) { total_weight += G.getNodeWeight(node); } endfor // greedy node coloring std::vector<int> node_coloring(G.number_of_nodes()); std::vector<bool> available(G.number_of_nodes(), true); forall_nodes(G, node) { std::fill(available.begin(), available.end(), true); forall_out_edges(G, edge, node) { available[node_coloring[G.getEdgeTarget(edge)]] = false; } endfor node_coloring[node] = (int) (std::find_if(available.begin(), available.end(), [](bool x){ return x; }) - available.begin()); } endfor int greedy_chromatic_number = *std::max_element(node_coloring.begin(), node_coloring.end()) + 1; std::vector<bool> used_colors(greedy_chromatic_number); // local search std::vector<int> ls_signal(G.number_of_nodes(), 0); std::random_device rd; for (int round = 0; round < mis_config.ls_rounds; ++round) { // TODO: only reduce the graph once, then perform the LS rounds with different seeds mis_config.seed = (int) rd(); std::cout << "ls_round " << round << std::endl; weighted_ls ls(mis_config, G); ls.run_ils(); forall_nodes(G, node) { ls_signal[node] += (int) G.getPartitionIndex(node); } endfor } if (mis_config.console_log) { int count = 0; double mean = 0; double std_dev = 0; for (const auto& val : ls_signal) { if (val != 0) { mean += val; ++count; } } mean /= count; for (const auto& val : ls_signal) { if (val != 0) { std_dev += (mean - val) * (mean - val); } } std_dev /= count; std::cout << "ls_std_dev " << std_dev << std::endl; } // loop variales EdgeID local_edges = 0; std::unordered_set<NodeID> neighbors {}; // don't know how to do faster? maybe using bitset from boost? neighbors.reserve(G.getMaxDegree()+1); float avg_lcc = 0; float avg_wdeg = 0; forall_nodes(G, node){ // num of nodes/ edges, deg getFeature<NODES>(node) = (float) G.number_of_nodes(); getFeature<EDGES>(node) = (float) G.number_of_edges(); getFeature<DEG>(node) = (float) G.getNodeDegree(node); // lcc neighbors.clear(); forall_out_edges(G, edge, node) { neighbors.insert(G.getEdgeTarget(edge)); } endfor for (auto& neighbor : neighbors) { forall_out_edges(G, neighbor_edge, neighbor) { if (neighbors.find(G.getEdgeTarget(neighbor_edge)) != neighbors.end()) ++local_edges; } endfor } if (G.getNodeDegree(node) > 1) // catch divide by zero getFeature<LCC>(node) = ((float) local_edges) / ((float) (G.getNodeDegree(node) * (G.getNodeDegree(node) - 1))); else getFeature<LCC>(node) = 0; avg_lcc += getFeature<LCC>(node); // local chromatic density forall_out_edges(G, edge, node) { used_colors[node_coloring[G.getEdgeTarget(edge)]] = true; } endfor getFeature<CHROMATIC>(node) = (float) std::accumulate(used_colors.begin(), used_colors.end(), 0) / (float) greedy_chromatic_number; // total weight getFeature<T_WEIGHT>(node) = (float) total_weight; // node weight getFeature<NODE_W>(node) = (float) G.getNodeWeight(node); // node weighted degree forall_out_edges(G, edge, node) { getFeature<W_DEG>(node) += (float) G.getNodeWeight(G.getEdgeTarget(edge)); } endfor avg_wdeg = getFeature<W_DEG>(node); // local search getFeature<LOCAL_SEARCH>(node) += (float) ls_signal[node] / mis_config.ls_rounds; } endfor avg_lcc /= (float) G.number_of_nodes(); avg_wdeg /= (float) G.number_of_nodes(); // statistical features float avg_deg = (2 * (float) G.number_of_edges()) / ((float) G.number_of_nodes()); forall_nodes(G,node) { getFeature<CHI2_DEG>(node) = (float) chi2(G.getNodeDegree(node), avg_deg); float avg_chi2_deg = 0; forall_out_edges(G, edge, node) { avg_chi2_deg += getFeature<AVG_CHI2_DEG>(node); } endfor if(G.getNodeDegree(node) > 0) // catch divide by zero getFeature<AVG_CHI2_DEG>(node) = avg_chi2_deg / (float) G.getNodeDegree(node); else getFeature<AVG_CHI2_DEG>(node) = 0; getFeature<CHI2_LCC>(node) = (float) chi2(getFeature<LCC>(node), avg_lcc); getFeature<CHI2_W_DEG>(node) = (float) chi2(getFeature<W_DEG>(node), avg_wdeg); } endfor current_size += G.number_of_nodes(); } void ml_features::initDMatrix() { if (feature_matrix.empty()) { std::cerr << "feature matrix empty, cannot create DMatrix from it!" << std::endl; return; } XGDMatrixCreateFromMat(c_arr(feature_matrix), getRows(), getCols(), 0, &dmat); XGDMatrixSetFloatInfo(dmat, "label", &label_data[0], label_data.size()); } DMatrixHandle ml_features::getDMatrix() { return dmat; } /* * For nodes from different graphs with equal features, average over the labels * to avoid conflicting information for the booster. */ void ml_features::regularize() { // iterators to rows std::vector<matrix::iterator> rows(getRows()); std::iota(rows.begin(), rows.end(), feature_matrix.begin()); // sort the rows by columns consecutively, // consecutive rows will then be approx equal std::sort(rows.begin(), rows.end(), [](auto row1, auto row2) { size_t col = 0; while (float_approx_eq((*row1)[col], (*row2)[col]) && col < FEATURE_NUM - 1) ++col; return row1[col] < row2[col]; }); // find all rows which are the same matrix regularized_feature_matrix; std::vector<float> regularized_label_data; { auto row = rows.begin(); float label_sum = label_data.front(); for (auto next = row + 1; next != rows.end(); next++) { size_t col = 0; while (float_approx_eq((**row)[col], (**next)[col]) && col < FEATURE_NUM) ++col; auto next_label = label_data[*next - feature_matrix.begin()]; // if row and equal are not equal until the last column (last feature) if (col < FEATURE_NUM) { // copy the row regularized_feature_matrix.push_back(**row); // copy averaged label regularized_label_data.push_back(label_sum / (float) (next-row)); // advance row to next row = next; // reset label_sum to only the label of the current row label_sum = next_label; } // if row and next are approx equal else { label_sum += next_label; } } } std::cout << "regularization: removed " << (float) (feature_matrix.size() - regularized_feature_matrix.size()) / feature_matrix.size() << "%" << std::endl; // update feature_matrix and label_data to the new regularized data feature_matrix = std::move(regularized_feature_matrix); current_size = feature_matrix.size(); label_data = std::move(regularized_label_data); } bool ml_features::float_approx_eq(float a, float b) { return std::abs(a-b) < eps; } float ml_features::scale_pos_weight_param() const { size_t number_of_positive = 0; size_t number_of_negative = 0; for (const auto label : label_data) { if (label == 0) ++number_of_negative; if (label == 1) ++number_of_positive; } return (float) number_of_negative / (float) number_of_positive; }
34.931751
159
0.619011
josephholten
9bab9f4bc1555af31e6a446e06bdb8c625ceec2b
1,027
cpp
C++
Main.cpp
EmuraDaisuke/Windows.HighPrecision-IntervalWait
0734c55383f193df7b6efb53a0459f69c01e75aa
[ "MIT" ]
1
2020-07-05T19:28:11.000Z
2020-07-05T19:28:11.000Z
Main.cpp
EmuraDaisuke/Windows.HighPrecision-IntervalWait
0734c55383f193df7b6efb53a0459f69c01e75aa
[ "MIT" ]
null
null
null
Main.cpp
EmuraDaisuke/Windows.HighPrecision-IntervalWait
0734c55383f193df7b6efb53a0459f69c01e75aa
[ "MIT" ]
null
null
null
#include <chrono> #include <iostream> #include <iomanip> #include <windows.h> #include <winuser.h> #include <conio.h> #include "./IntervalWait.h" #pragma comment(lib, "user32.lib") double Now() { using namespace std::chrono; return duration_cast<nanoseconds>(steady_clock::now().time_since_epoch()).count() / 1000000000.0; } int main(int argc, char* argv[]) { Mmcss m; // IntervalWait Interval(/*ms*/1 * /*us*/1000 * /*ns*/1000); // IntervalWait Interval(/*us*/1000 * /*ns*/1000); // IntervalWait Interval(3333333); IntervalWait Interval(1, IntervalWait::eLimiter::Minimum); double vOld = Now(); double vNow = Now(); double vSum = 0; int nSum = 0; while (!(GetAsyncKeyState(VK_ESCAPE) < 0)){ Interval.Wait(); vOld = vNow; vNow = Now(); vSum += vNow - vOld; ++nSum; std::cout << std::fixed << std::setprecision(9) << (vNow - vOld) << " " << (vSum / nSum) << std::endl; } return 0; }
19.377358
110
0.573515
EmuraDaisuke
9bb1da14b77ac8949214478663c1c4f92fa7c00f
425
cpp
C++
sources/Vertex.cpp
jbalestr42/GraphicsEngine
f317bddf750577602b231824c7f880142f5a8ce6
[ "WTFPL" ]
2
2017-05-26T14:37:23.000Z
2021-06-07T09:39:18.000Z
sources/Vertex.cpp
jbalestr42/GraphicsEngine
f317bddf750577602b231824c7f880142f5a8ce6
[ "WTFPL" ]
1
2016-11-26T15:18:26.000Z
2017-05-24T18:01:25.000Z
sources/Vertex.cpp
jbalestr42/GraphicsEngine
f317bddf750577602b231824c7f880142f5a8ce6
[ "WTFPL" ]
3
2017-06-07T16:41:58.000Z
2022-03-18T05:12:37.000Z
#include "Vertex.hpp" Vertex::Vertex(void) { } Vertex::Vertex(Vector3 const & pos, Vector2 const & u, Vector3 const & n, Color const & col) { position = pos; uv = u; normal = n; color = col; } Vertex::Vertex(Vertex const & vertex) { *this = vertex; } Vertex & Vertex::operator=(Vertex const & vertex) { position = vertex.position; uv = vertex.uv; normal = vertex.normal; color = vertex.color; return (*this); }
16.346154
92
0.656471
jbalestr42
9bb5e782a604379aea0b4df7a8df7d81af1c3062
4,003
cpp
C++
chapter24/ch24_drill.cpp
ClassAteam/stroustrup-ppp
ea9e85d4ea9890038eb5611c3bc82734c8706ce7
[ "MIT" ]
124
2018-06-23T10:16:56.000Z
2022-03-19T15:16:12.000Z
chapter24/ch24_drill.cpp
therootfolder/stroustrup-ppp
b1e936c9a67b9205fdc9712c42496b45200514e2
[ "MIT" ]
23
2018-02-08T20:57:46.000Z
2021-10-08T13:58:29.000Z
chapter24/ch24_drill.cpp
ClassAteam/stroustrup-ppp
ea9e85d4ea9890038eb5611c3bc82734c8706ce7
[ "MIT" ]
65
2019-05-27T03:05:56.000Z
2022-03-26T03:43:05.000Z
// // Stroustrup - Programming Principles & Practice // // Chapter 24 Drill // // Some fun and odd stuff here, including a sqrt exercise from chapter 5. // #include <iostream> #include <stdexcept> #include <iomanip> #include <complex> #include <numeric> #include "../text_lib/Matrix.h" #include "../text_lib/MatrixIO.h" using Numeric_lib::Matrix; void sqrt_out() // why is this a chapter 24 exercise..? { int val; std::cin >> val; if (val < 0) std::cout << "no square root\n"; else std::cout << sqrt(val) << '\n'; } int main() try { // 1. Print the size of a char, short, int, long, float, double, int* and // a double*; std::cout << "OBJECT SIZEOFs:\n" << "char: " << sizeof(char) << '\n' << "short: " << sizeof(short) << '\n' << "int: " << sizeof(int) << '\n' << "long: " << sizeof(long) << '\n' << "float: " << sizeof(float) << '\n' << "double: " << sizeof(double) << '\n' << "int*: " << sizeof(int*) << '\n' << "double*: " << sizeof(double*) << "\n\n"; // 2. Print out the sizes of different types of Matrixes Matrix<int> a(10); Matrix<int> b(100); Matrix<double> c(10); Matrix<int,2> d(10,10); Matrix<int,3> e(10,10,10); std::cout << "MATRIX SIZEOFs:\n" << "Matrix<int>(10): " << sizeof(a) << '\n' << "Matrix<int>(100): " << sizeof(b) << '\n' << "Matrix<double>(10): " << sizeof(c) << '\n' << "Matrix<int,2>(10,10): " << sizeof(d) << '\n' << "Matrix<int,3>(10,10,10): " << sizeof(e) << "\n\n"; // 3. Print out the number of elements in the different Matrixes std::cout << "MATRIX ELEMENTS:\n" << "Matrix<int>(10): " << a.size() << '\n' << "Matrix<int>(100): " << b.size() << '\n' << "Matrix<double>(10): " << c.size() << '\n' << "Matrix<int,2>(10,10): " << d.size() << '\n' << "Matrix<int,3>(10,10,10): " << e.size() << "\n\n"; // 4. Take ints from cin and output the sqrt of them. Check for bad input. std::cout << "Enter some ints for square-rooting:\n"; for (int i = 0; i < 5; ++i) sqrt_out(); // 5. Read 10 floating point values from input into a Matrix std::cout << "Enter 10 floats for entry into a Matrix:\n"; const int entries = 10; Matrix<double> md(entries); for (int i = 0; i < entries; ++i) std::cin >> md[i]; std::cout << md << '\n'; // 6. Compute a multiplication table and print it. std::cout << "Enter the dimensions for the table: "; int m, n; std::cin >> m >> n; std::cout << '\n'; Matrix<double,2> mult_table(m,n); for (int i = 0; i < m; ++i) for (int j = 0; j < n; ++j) mult_table(i,j) = i == 0 || j == 0 ? i + j : i * j; //std::cout << mult_table << '\n'; // ugly for (int i = 0; i < mult_table.dim1(); ++i) { for (int j = 0; j < mult_table.dim2(); ++j) std::cout << std::setw(5) << mult_table(i,j); std::cout << '\n'; } // 7. Read 10 complex<double>s in from cin. Output the sum. std::cout << "Enter 10 complex numbers:\n"; Matrix<std::complex<double>> mcd (10); for (int i = 0; i < mcd.size(); ++i) { std::cin >> mcd[i]; } std::cout << "Total: " << std::accumulate(mcd.data(), mcd.data() + mcd.size(), std::complex<double>{}) << '\n'; // 8. Read 6 ints into a Matrix<int,2> (2,3) and print them out std::cout << "Enter 6 ints for a 2x3 Matrix:\n"; Matrix<int,2> mm (2,3); for (int i = 0; i < mm.dim1(); ++i) for (int j = 0; j < mm.dim2(); ++j) std::cin >> mm[i][j]; std::cout << mm << '\n'; } catch(std::exception& e) { std::cerr << "Exception: " << e.what() << '\n'; return 1; } catch(...) { std::cerr << "Unknown exception\n"; return 2; }
30.792308
78
0.481139
ClassAteam
9bc32cff6bd178fb7f9757ed33635c622f424982
784
cpp
C++
Codeforces/1562A-the-miracle-and-the-sleeper.cpp
SusmoySenGupta/online-judge-solutions
8735a1bc71a05dc46255664c3ec6f47f042bfa6c
[ "MIT" ]
null
null
null
Codeforces/1562A-the-miracle-and-the-sleeper.cpp
SusmoySenGupta/online-judge-solutions
8735a1bc71a05dc46255664c3ec6f47f042bfa6c
[ "MIT" ]
null
null
null
Codeforces/1562A-the-miracle-and-the-sleeper.cpp
SusmoySenGupta/online-judge-solutions
8735a1bc71a05dc46255664c3ec6f47f042bfa6c
[ "MIT" ]
null
null
null
/* author: Susmoy Sen Gupta email: susmoy.cse@gmail.com github: github.com/SusmoySenGupta Judge: Codeforces problem no: 1562A problem name: The Miracle and the Sleeper problem link: https://codeforces.com/problemset/problem/1562/A Status: __Solved__ Solved at: Sep/03/2021 11:37 */ #include <iostream> #define INF (int)1e9 #define EPS 1e-9 #define MOD 1000000007ll #define PI 3.14159 #define MAX 1003 #define lli long long int #define rep(i, a, n) for (int i=a; i<n; i++) #define per(i, a, n) for (int i=n-1; i>=a; i--) using namespace std; void solve() { int l, r; scanf("%d%d", &l, &r); if(r < l*2) printf("%d\n", r-l); else printf("%d\n", (r-1) / 2); } int main() { int t; scanf("%d", &t); while(t--) solve(); return 0; }
15.68
63
0.618622
SusmoySenGupta
9bc8a62ca82accee9ad861984e54ccec21d7f854
1,835
cpp
C++
RedisPublishCommand.cpp
MutesK/Replication
8b77c7257e8265daebdc4b74a279e292906c6740
[ "MIT" ]
null
null
null
RedisPublishCommand.cpp
MutesK/Replication
8b77c7257e8265daebdc4b74a279e292906c6740
[ "MIT" ]
null
null
null
RedisPublishCommand.cpp
MutesK/Replication
8b77c7257e8265daebdc4b74a279e292906c6740
[ "MIT" ]
null
null
null
// // Created by JunMin Kim on 2020/11/01. // #include "RedisCommon.h" #include "RedisConnection.hpp" #include "RedisPublishCommand.hpp" #ifdef REPLICATION_REDIS namespace Replication { namespace Redis { RedisPublishCommand::RedisPublishCommand(const ConnectionPtr& Ptr) : Command(Ptr) { } bool RedisPublishCommand::Do(ErrorCode &Code) { auto Context = std::static_pointer_cast<RedisConnection>(_ConnectionPtr)->GetRedisContext(); std::for_each(_ParameterMap.begin(), _ParameterMap.end(), [&Context](const auto& Iter) { redisAppendCommand(Context, "PUBLISH %s %s", Iter.second.Channel.c_str(), Iter.second.Value.c_str()); }); std::for_each(_ParameterMap.begin(), _ParameterMap.end(), [&Context](const auto& Iter) { ScopedRedisReply Reply = nullptr; redisGetReply(Context, (void **)(&Reply)); // Debug if type reply_integer then print recvied client num. }); return true; } void RedisPublishCommand::PushParameter(const PublishParameters &Parameter) { _ParameterMap.insert({Parameter.Channel, Parameter}); } void RedisPublishCommand::EraseParameter(const std::string &ChannelName) { const auto& Iter = _ParameterMap.find(ChannelName); if(Iter == _ParameterMap.end()) { return; } _ParameterMap.erase(Iter); } void RedisPublishCommand::ResetParameter() { _ParameterMap.clear(); } std::size_t RedisPublishCommand::ParameterSize() const { return _ParameterMap.size(); } } } #endif
26.214286
117
0.575477
MutesK
9bc8c3fd80f849e76daae272e351538c8f0c4b2f
1,126
cpp
C++
engine/Fury/BufferManager.cpp
sindney/fury3d
a5880af615c3225e279eb63a9193c7ca8b5fcf49
[ "MIT" ]
95
2016-01-29T08:58:02.000Z
2022-02-07T02:42:20.000Z
engine/Fury/BufferManager.cpp
sindney/fury3d
a5880af615c3225e279eb63a9193c7ca8b5fcf49
[ "MIT" ]
3
2017-07-30T02:21:50.000Z
2018-10-12T13:55:32.000Z
engine/Fury/BufferManager.cpp
sindney/fury3d
a5880af615c3225e279eb63a9193c7ca8b5fcf49
[ "MIT" ]
30
2016-01-29T09:48:34.000Z
2021-11-09T13:15:36.000Z
#include "Fury/BufferManager.h" namespace fury { void BufferManager::Remove(size_t id) { auto it = m_Buffers.find(id); if (it != m_Buffers.end()) m_Buffers.erase(it); } void BufferManager::Release(size_t id) { auto it = m_Buffers.find(id); if (it != m_Buffers.end()) { if (!it->second.expired()) it->second.lock()->DeleteBuffer(); m_Buffers.erase(it); } } void BufferManager::RemoveAll() { m_Buffers.clear(); } void BufferManager::ReleaseAll() { for (auto pair : m_Buffers) { if (!pair.second.expired()) pair.second.lock()->DeleteBuffer(); } m_Buffers.clear(); } void BufferManager::IncreaseMemory(unsigned int byte, bool gpu) { if (gpu) m_GPUMemories += byte; else m_CPUMemories += byte; } void BufferManager::DecreaseMemory(unsigned int byte, bool gpu) { if (gpu) m_GPUMemories -= byte; else m_CPUMemories -= byte; } unsigned int BufferManager::GetMemoryInMegaByte(bool gpu) { if (gpu) return m_GPUMemories / 1000000; else return m_CPUMemories / 1000000; } }
17.59375
65
0.619005
sindney
9bcf042f20f6db6d3b65e55bf9555452197051ab
690
cpp
C++
sources/src/Sx/Signals/Observer.cpp
vsemyonoff/observer
e006286e102efc4d5c372bd742ff843579c1b5a7
[ "BSD-2-Clause" ]
1
2020-02-13T19:42:11.000Z
2020-02-13T19:42:11.000Z
sources/src/Sx/Signals/Observer.cpp
vsemyonoff/observer
e006286e102efc4d5c372bd742ff843579c1b5a7
[ "BSD-2-Clause" ]
null
null
null
sources/src/Sx/Signals/Observer.cpp
vsemyonoff/observer
e006286e102efc4d5c372bd742ff843579c1b5a7
[ "BSD-2-Clause" ]
null
null
null
#include <Sx/Signals/Connection.hpp> #include <Sx/Signals/Observer.hpp> using namespace Sx::Signals; Observer::~Observer() noexcept { for (const auto& c : connections) c->detached = true; connections.clear(); } Observer::Observer(const Observer&) noexcept {} Observer& Observer::operator=(const Observer&) noexcept { return *this; } // Static instance will hold static and free functions connections Observer* Observer::global() { static Observer d; return &d; } void Observer::attach(Connection* c) { connections.push_back(c); } void Observer::detach(Connection* c) { connections.remove_if([c](Connection* co) { return c == co; }); }
18.157895
66
0.678261
vsemyonoff
9bcfef469d052cec0fd780068f38ba19bea02d35
103
hpp
C++
code/include/common/graphics/drawables/menu/menu.hpp
StuntHacks/infinite-dungeons
b462dd27c4e0f7285940e45d086b5d022fea23df
[ "MIT" ]
null
null
null
code/include/common/graphics/drawables/menu/menu.hpp
StuntHacks/infinite-dungeons
b462dd27c4e0f7285940e45d086b5d022fea23df
[ "MIT" ]
null
null
null
code/include/common/graphics/drawables/menu/menu.hpp
StuntHacks/infinite-dungeons
b462dd27c4e0f7285940e45d086b5d022fea23df
[ "MIT" ]
null
null
null
#include "TextBox.hpp" #include "textboxes/textboxes.hpp" #include "circle_selects/circle_selects.hpp"
25.75
44
0.805825
StuntHacks
9bd80b08b5d3248db06b924845890cd9b9fa9d6f
7,249
hpp
C++
sdl/Hypergraph/OpenFstDraw.hpp
sdl-research/hyp
d39f388f9cd283bcfa2f035f399b466407c30173
[ "Apache-2.0" ]
29
2015-01-26T21:49:51.000Z
2021-06-18T18:09:42.000Z
sdl/Hypergraph/OpenFstDraw.hpp
hypergraphs/hyp
d39f388f9cd283bcfa2f035f399b466407c30173
[ "Apache-2.0" ]
1
2015-12-08T15:03:15.000Z
2016-01-26T14:31:06.000Z
sdl/Hypergraph/OpenFstDraw.hpp
hypergraphs/hyp
d39f388f9cd283bcfa2f035f399b466407c30173
[ "Apache-2.0" ]
4
2015-11-21T14:25:38.000Z
2017-10-30T22:22:00.000Z
// Copyright 2014-2015 SDL plc // 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. /** \file print openfst as graphviz/dot. */ #ifndef SDL_HYP__OPENFSTDRAW_LW201213_HPP #define SDL_HYP__OPENFSTDRAW_LW201213_HPP #pragma once #if HAVE_OPENFST #include <sdl/Hypergraph/ToOpenFst.hpp> #include <sdl/Hypergraph/ToReplaceFst.hpp> #include <sdl/Hypergraph/UseOpenFst.hpp> #include <fst/script/draw.h> #include <fst/script/print.h> #include <fst/script/prune.h> #endif #include <sdl/Hypergraph/HypergraphDrawer.hpp> #include <sdl/Hypergraph/WeightUtil.hpp> #include <sdl/Util/Constants.hpp> #include <graehl/shared/fileargs.hpp> #include <graehl/shared/is_null.hpp> namespace sdl { namespace Hypergraph { // TODO: for openfst, don't create axiom states except start. struct DrawOptions { static char const* caption() { return "Draw"; } // openfst options: std::string title; std::string dest; bool accep; float width; float height; bool portrait; bool vertical; float ranksep; float nodesep; int fontsize; int precision; bool show_weight_one; std::ostream* o; // our options: std::string terminator; bool replaceFst; graehl::ostream_arg openFstPrintFile; bool stateNames; double pruneBeam; #define FOR_DRAW_OPTIONS_INT(f) \ f(accep) f(width) f(height) f(portrait) f(vertical) f(ranksep) f(nodesep) f(fontsize) f(precision) \ f(show_weight_one) #define FOR_DRAW_OPTIONS(f) f(title) f(dest) FOR_DRAW_OPTIONS_INT(f) #define FOR_OUR_DRAW_OPTIONS(f) f(replaceFst) f(openFstPrintFile) f(terminator) f(stateNames) f(pruneBeam) DrawOptions() { replaceFst = false; terminator = "\n"; title = "Fsm"; dest = ""; // ?? // drawn FST destination name - presumably from final state? stateNames = true; #define FOR_DRAW_OPTIONS_SET_0(n) n = 0; FOR_DRAW_OPTIONS_INT(FOR_DRAW_OPTIONS_SET_0); // TODO: nonzero defaults accep = true; show_weight_one = false; width = 8.5; height = 11; portrait = true; fontsize = 10; precision = 3; pruneBeam = std::numeric_limits<double>::infinity(); o = 0; // don't draw, but maybe openFstPrintFile } graehl::ostream_arg oarg; template <class Config> void configure(Config& config) { #if HAVE_OPENFST config.is("OpenFst Draw/Print"); #define FOR_DRAW_OPTIONS_ADD_OPTION(n) config(#n, &n)("openfst draw " #n); FOR_DRAW_OPTIONS(FOR_DRAW_OPTIONS_ADD_OPTION); config("replaceFst", &replaceFst)("use ToReplaceFst for fsm"); config("openFstPrintFile", &openFstPrintFile)("also openfst print to this file (avoid drawing with -o=-0)"); config("terminator", &terminator)("this string after every transducer drawn or printed (newline default)"); config("stateNames", &stateNames)("name states for non-replaceFst openfst translation"); config("pruneBeam", &pruneBeam)("unless nan, openfst prune with this beam before print/draw"); // FOR_OUR_DRAW_OPTIONS(FOR_DRAW_OPTIONS_ADD_OPTION) ; #endif } void validate() { if (replaceFst) { SDL_WARN(Hypergraph.OpenFstDraw, "drawing a replaceFst will infinite-loop unless the Hg is finite (no cycles)"); } } template <class A> void drawHg(IHypergraph<A> const& h) const { if (o) drawHypergraph(*o, h); } #if HAVE_OPENFST fst::script::FstDrawerArgs drawArgs(std::ostream& o, fst::script::FstClass const& fstc, fst::SymbolTable const& isyms, fst::SymbolTable const& osyms, fst::SymbolTable const* pStateNames = 0) const { return fst::script::FstDrawerArgs(fstc, &isyms, &osyms, pStateNames, accep, title, width, height, portrait, vertical, ranksep, nodesep, fontsize, precision, show_weight_one, &o, dest); } fst::script::FstPrinterArgs printArgs(std::ostream& o, fst::script::FstClass const& fstc, fst::SymbolTable const& isyms, fst::SymbolTable const& osyms, fst::SymbolTable const* pStateNames = 0) const { return fst::script::FstPrinterArgs(fstc, &isyms, &osyms, pStateNames, accep, show_weight_one, &o, dest); } template <class FstArc> void print(std::ostream& o, fst::script::FstClass const& fstc, fst::SymbolTable const& isyms, fst::SymbolTable const& osyms, fst::SymbolTable const* pStateNames = 0) const { fst::script::FstPrinterArgs a = printArgs(o, fstc, isyms, osyms, pStateNames); fst::script::PrintFst<FstArc>(&a); } template <class FstArc> void drawClass(fst::script::FstClass const& fstc, fst::SymbolTable const& syms, fst::SymbolTable const* pStateNames = 0) const { if (o) { fst::script::FstDrawerArgs fa = drawArgs(*o, fstc, syms, syms, pStateNames); fst::script::DrawFst<FstArc>(&fa); *o << terminator; } if (openFstPrintFile) { std::ostream& of = openFstPrintFile.stream(); print<FstArc>(of, fstc, syms, syms, pStateNames); of << terminator; } } template <class FstArc> void drawClass(fst::script::FstClass const& fstc, fst::SymbolTable const* pStateNames = 0) const { drawClass<FstArc>(fstc, *fstc.InputSymbols(), pStateNames); } template <class FstArc> void drawFst(fst::Fst<FstArc>& fst, fst::SymbolTable const* pStateNames = 0) const { fst::script::FstClass fstc(&fst); drawClass<FstArc>(fstc, pStateNames); } template <class Arc> void drawReplaceFst(IHypergraph<Arc> const& h) const { // IVocabularySymbolTable syms(h.getVocabulary()); typedef typename Arc::Weight Weight; typedef fst::ArcTpl<Weight> FstArc; fst::SymbolTable fsyms("drawReplaceFst"); fst::ReplaceFst<FstArc>* r = toReplaceFst<FstArc>(h, &fsyms); drawFst(*r, &fsyms); delete r; } template <class A> void drawFsmOpenFst(IHypergraph<A> const& h) const { typedef typename A::Weight W; #if TO_OPENFST_GETVALUE typedef fst::StdArc FstArc; #else typedef fst::ArcTpl<W> FstArc; #endif typedef typename FstArc::Weight FW; typedef ToOpenFst<A, FstArc> T; T t(h, stateNames); if (pruneBeam != std::numeric_limits<double>::infinity()) { fst::Prune(&t.fst, FW(pruneBeam)); } drawFst<FstArc>(t.getFst(), t.stateNames()); } template <class A> void draw(IHypergraph<A> const& h) const { if (replaceFst) drawReplaceFst(h); // FIXME: may be able to handle some non-recursive CFG too else if (h.isFsm()) { drawFsmOpenFst(h); } else drawHg(h); } #else template <class A> void draw(IHypergraph<A> const& h) const { drawHg(h); } #endif }; }} #endif
33.873832
114
0.667816
sdl-research
9be1c4458b75455036fa5199e45d238c309b037f
4,567
hpp
C++
io/converter/math/string_to_value_converter.hpp
aconstlink/snakeoil
3c6e02655e1134f8422f01073090efdde80fc109
[ "MIT" ]
1
2017-08-11T19:12:24.000Z
2017-08-11T19:12:24.000Z
io/converter/math/string_to_value_converter.hpp
aconstlink/snakeoil
3c6e02655e1134f8422f01073090efdde80fc109
[ "MIT" ]
11
2018-07-07T20:09:44.000Z
2020-02-16T22:45:09.000Z
io/converter/math/string_to_value_converter.hpp
aconstlink/snakeoil
3c6e02655e1134f8422f01073090efdde80fc109
[ "MIT" ]
null
null
null
//------------------------------------------------------------ // snakeoil (c) Alexis Constantin Link // Distributed under the MIT license //------------------------------------------------------------ #ifndef _SNAKEOIL_IO_MATH_STRING_TO_VALUE_CONVERTER_H_ #define _SNAKEOIL_IO_MATH_STRING_TO_VALUE_CONVERTER_H_ #include "../../result.h" #include <snakeoil/math/vector/vector2.hpp> #include <snakeoil/math/vector/vector3.hpp> #include <snakeoil/math/vector/vector4.hpp> #include <snakeoil/std/string/split.hpp> namespace so_io { namespace io_math { #if 0 namespace so_internal { template< typename value_t > value_t convert_to_scalar( std::string const & s ) { return boost::lexical_cast< value_t, std::string >(s) ; } template< typename vec_t, size_t comp > so_io::result convert_to_vector( std::string const & s, std::string const & sep, vec_t & vec_out ) { typedef typename vec_t::type_t value_t ; typedef boost::tokenizer< boost::char_separator< char > > tokenizer_t ; tokenizer_t tokens( s, boost::char_separator<char>(sep.c_str()) ) ; size_t i = 0 ; std::for_each( tokens.begin(), tokens.end(), [&]( std::string const & s ) { if( i < comp ) vec_out[i] = convert_to_scalar<value_t>( s ) ; ++i ; }) ; return ( i != comp ) ? so_io::failed : so_io::ok ; } } template< typename value_t > so_io::result convert_to_value( std::string const & s, std::string const & sep, value_t & v_out ) { v_out = so_internal::convert_to_scalar<value_t>( s ) ; return so_io::ok ; } template<> so_io::result convert_to_value<so_math::vec2f_t>( std::string const & s, std::string const & sep, so_math::vec2f_t & v_out ) { typedef so_math::vec2f_t vec_t ; return so_internal::convert_to_vector<vec_t, 2>( s, sep, v_out ) ; } template<> so_io::result convert_to_value<so_math::vec3f_t>( std::string const & s, std::string const & sep, so_math::vec3f_t & v_out ) { typedef so_math::vec3f_t vec_t ; return so_internal::convert_to_vector<vec_t, 3>( s, sep, v_out ) ; } template<> so_io::result convert_to_value<so_math::vec4f_t>( std::string const & s, std::string const & sep, so_math::vec4f_t & v_out ) { typedef so_math::vec4f_t vec_t ; return so_internal::convert_to_vector<vec_t, 4>( s, sep, v_out ) ; } template<> so_io::result convert_to_value<so_math::vec2i_t>( std::string const & s, std::string const & sep, so_math::vec2i_t & v_out ) { typedef so_math::vec2i_t vec_t ; return so_internal::convert_to_vector<vec_t, 2>( s, sep, v_out ) ; } template<> so_io::result convert_to_value<so_math::vec3i_t>( std::string const & s, std::string const & sep, so_math::vec3i_t & v_out ) { typedef so_math::vec3i_t vec_t ; return so_internal::convert_to_vector<vec_t, 3>( s, sep, v_out ) ; } template<> so_io::result convert_to_value<so_math::vec4i_t>( std::string const & s, std::string const & sep, so_math::vec4i_t & v_out ) { typedef so_math::vec4i_t vec_t ; return so_internal::convert_to_vector<vec_t, 4>( s, sep, v_out ) ; } template<> so_io::result convert_to_value<so_math::vec2ui_t>( std::string const & s, std::string const & sep, so_math::vec2ui_t & v_out ) { typedef so_math::vec2ui_t vec_t ; return so_internal::convert_to_vector<vec_t, 2>( s, sep, v_out ) ; } template<> so_io::result convert_to_value<so_math::vec3ui_t>( std::string const & s, std::string const & sep, so_math::vec3ui_t & v_out ) { typedef so_math::vec3ui_t vec_t ; return so_internal::convert_to_vector<vec_t, 3>( s, sep, v_out ) ; } template<> so_io::result convert_to_value<so_math::vec4ui_t>( std::string const & s, std::string const & sep, so_math::vec4ui_t & v_out ) { typedef so_math::vec4ui_t vec_t ; return so_internal::convert_to_vector<vec_t, 4>( s, sep, v_out ) ; } #endif } } #endif
36.830645
134
0.563608
aconstlink
9be9bf0b529c7b7ad58fd54d05154becc1240e77
83
cpp
C++
Tests/TestsRosicAndRapt/Source/rosic_tests/PortedFromRSLib/RSLib/Core/Text/KeyValueStringPair.cpp
RobinSchmidt/RS-MET-Preliminary
6c01cbaad7cce3daa3293c444dd9e4b74e5ebfbe
[ "FTL" ]
34
2017-04-19T18:26:02.000Z
2022-02-15T17:47:26.000Z
Tests/TestsRosicAndRapt/Source/rosic_tests/PortedFromRSLib/RSLib/Core/Text/KeyValueStringPair.cpp
RobinSchmidt/RS-MET-Preliminary
6c01cbaad7cce3daa3293c444dd9e4b74e5ebfbe
[ "FTL" ]
307
2017-05-04T21:45:01.000Z
2022-02-03T00:59:01.000Z
Tests/TestsRosicAndRapt/Source/rosic_tests/PortedFromRSLib/RSLib/Core/Text/KeyValueStringPair.cpp
RobinSchmidt/RS-MET-Preliminary
6c01cbaad7cce3daa3293c444dd9e4b74e5ebfbe
[ "FTL" ]
4
2017-09-05T17:04:31.000Z
2021-12-15T21:24:28.000Z
using namespace RSLib; /* rsKeyValueStringPair::~rsKeyValueStringPair() { } */
9.222222
46
0.710843
RobinSchmidt
9bf69f554bcf843f358fa3a214d37b0a371f8ddf
962
cpp
C++
Programming-Contest/Strings/Automation.cpp
ar-pavel/Code-Library
2d1b952231c1059bbf98d85d2c23fd8fb21b455c
[ "MIT" ]
null
null
null
Programming-Contest/Strings/Automation.cpp
ar-pavel/Code-Library
2d1b952231c1059bbf98d85d2c23fd8fb21b455c
[ "MIT" ]
null
null
null
Programming-Contest/Strings/Automation.cpp
ar-pavel/Code-Library
2d1b952231c1059bbf98d85d2c23fd8fb21b455c
[ "MIT" ]
null
null
null
#define MAX_SIZE 1000010 int f[MAX_SIZE][26]; void Compute_Transition_Fnc(string P) { int m = P.size(); forab(q,0,m){ string Pq = P.substr(0,q); forab(c,'a','z'){ int K = min( m , q+1 ); string aux = Pq + c; while(1){ bool check = true; rep(i,K) if( aux [q-i] != P [K-1-i] ) check=false; if(check) break; K--; } f[ q ][ c - 'a' ] = K; } } } void Finite_Automata_Matcher(string T,int m){ int n = T.size() , q = 0 ; rep(i,n){ q = f[q][ T[i]-'a' ]; if(q == m ) cout<<"Pattern occurs with shift "<< i+1-m <<endl; } } int main(){ string P,T; cout<<"Text :"; cin >> T ; cout << endl; cout<<"Pattern : "; cin>>P ; cout << endl; Compute_Transition_Fnc(P); //assuming that the alphabet letters are lowercase Finite_Automata_Matcher(T,P.size()); }
24.666667
81
0.461538
ar-pavel
9bf946c493624f7160d5af830eb40502639eed13
6,208
cpp
C++
SATsolver.cpp
erikkvam/SATsolver
958bf94dd2748b8f6a16bac813b03bb409f097ad
[ "MIT" ]
null
null
null
SATsolver.cpp
erikkvam/SATsolver
958bf94dd2748b8f6a16bac813b03bb409f097ad
[ "MIT" ]
null
null
null
SATsolver.cpp
erikkvam/SATsolver
958bf94dd2748b8f6a16bac813b03bb409f097ad
[ "MIT" ]
null
null
null
#include <iostream> #include <stdlib.h> #include <algorithm> #include <vector> using namespace std; #define UNDEF -1 #define TRUE 1 #define FALSE 0 uint numVars; uint numClauses; vector<vector<int> > clauses; vector<int> model; vector<int> modelStack; uint indexOfNextLitToPropagate; uint decisionLevel; vector<vector <int> > clausesWithNegatedLiteral; void readClauses( ){ // Skip comments char c = cin.get(); while (c == 'c') { while (c != '\n') c = cin.get(); c = cin.get(); } // Read "cnf numVars numClauses" string aux; cin >> aux >> numVars >> numClauses; clauses.resize(numClauses); clausesWithNegatedLiteral.resize(numVars+1); // Read clauses for (uint i = 0; i < numClauses; ++i) { int lit; cout << "Reading clause " << i << ": "; while (cin >> lit and lit != 0){ cout << lit << ", "; clauses[i].push_back(lit); if (lit < 0) clausesWithNegatedLiteral[-lit].push_back(i); clausesWithNegatedLiteral[0].push_back(i); //totes les clausules estan a [0] per la primera iteracio } cout << "done." << endl; } } int currentValueInModel(int lit){ if (lit >= 0) return model[lit]; else { if (model[-lit] == UNDEF) return UNDEF; else return 1 - model[-lit]; } } void setLiteralToTrue(int lit){ modelStack.push_back(lit); if (lit > 0) model[lit] = TRUE; else model[-lit] = FALSE; } bool propagateGivesConflict (int decisionLit) { while ( indexOfNextLitToPropagate < modelStack.size() ) { ++indexOfNextLitToPropagate; cout << "There's " << clausesWithNegatedLiteral[decisionLit].size() << " clauses with " << decisionLit << " negated:" << endl; for (uint i = 0; i < clausesWithNegatedLiteral[decisionLit].size(); ++i) { cout << " Checking the clause in the " << i << " position, number " << clausesWithNegatedLiteral[decisionLit][i] << ": "<< endl; bool someLitTrue = false; int numUndefs = 0; int lastLitUndef = 0; for (uint k = 0; not someLitTrue and k < clauses[clausesWithNegatedLiteral[decisionLit][i]].size(); ++k){ int val = currentValueInModel(clauses[clausesWithNegatedLiteral[decisionLit][i]][k]); cout << " " << clauses[clausesWithNegatedLiteral[decisionLit][i]][k] << " is "; if (val == TRUE){ someLitTrue = true; cout << "TRUE, we are done here."; } else if (val == UNDEF){ ++numUndefs; lastLitUndef = clauses[clausesWithNegatedLiteral[decisionLit][i]][k]; cout << "UNDEF, we continue."; } else cout << "FALSE, we continue"; cout << endl; } if (not someLitTrue and numUndefs == 0) { cout << " CONFLICT! All lits false!" << endl; return true; // conflict! all lits false } else if (not someLitTrue and numUndefs == 1){ setLiteralToTrue(lastLitUndef); cout << " Only one UNDEF, " << lastLitUndef << ", which we set to true." << endl; } else cout << " No conflict" << endl; } } return false; } void backtrack(){ uint i = modelStack.size() -1; int lit = 0; while (modelStack[i] != 0){ // 0 is the DL mark lit = modelStack[i]; model[abs(lit)] = UNDEF; modelStack.pop_back(); --i; } // at this point, lit is the last decision modelStack.pop_back(); // remove the DL mark --decisionLevel; indexOfNextLitToPropagate = modelStack.size(); setLiteralToTrue(-lit); // reverse last decision } // Heuristic for finding the next decision literal: int getNextDecisionLiteral(){ for (uint i = 1; i <= numVars; ++i) // stupid heuristic: if (model[i] == UNDEF) return i; // returns first UNDEF var, positively return 0; // reurns 0 when all literals are defined } void checkmodel(){ for (int i = 0; i < numClauses; ++i){ bool someTrue = false; for (int j = 0; not someTrue and j < clauses[i].size(); ++j) someTrue = (currentValueInModel(clauses[i][j]) == TRUE); if (not someTrue) { cout << "Error in model, clause " << i << " is not satisfied:"; for (int j = 0; j < clauses[i].size(); ++j) cout << clauses[i][j] << " "; cout << endl; exit(1); } } } int main(){ readClauses(); // reads numVars, numClauses and clauses model.resize(numVars+1,UNDEF); indexOfNextLitToPropagate = 0; decisionLevel = 0; // Take care of initial unit clauses, if any for (uint i = 0; i < numClauses; ++i) if (clauses[i].size() == 1) { int lit = clauses[i][0]; int val = currentValueInModel(lit); if (val == FALSE) {cout << "UNSATISFIABLE" << endl; return 10;} else if (val == UNDEF) setLiteralToTrue(lit); } int decisionLit = 0; // DPLL algorithm while (true) { while ( propagateGivesConflict(decisionLit) ) { if ( decisionLevel == 0) { cout << "UNSATISFIABLE" << endl; return 10; } backtrack(); } decisionLit = getNextDecisionLiteral(); //for (int i = 0; i<decisionLevel; ++i) cout << " "; cout << "Propagating literal " << decisionLit << endl; if (decisionLit == 0) { for (int i = 1; i <= numVars; ++i) cout << "Value of " << i << " is " << currentValueInModel(i) << '.' << endl; checkmodel(); cout << "SATISFIABLE" << endl; return 20; } // start new decision level: modelStack.push_back(0); // push mark indicating new DL ++indexOfNextLitToPropagate; ++decisionLevel; setLiteralToTrue(decisionLit); // now push decisionLit on top of the mark } }
34.681564
143
0.536082
erikkvam
50000dfb3397b837cde449d5ec3cf38fcb308ea3
13,922
cpp
C++
mbed-client/source/m2mdiscover.cpp
marcuschangarm/mbed-cloud-client
d7edc529ed3722c811ff401440ef58ea980bf543
[ "Apache-2.0" ]
27
2018-04-04T12:06:23.000Z
2020-10-16T08:58:38.000Z
mbed-client/source/m2mdiscover.cpp
marcuschangarm/mbed-cloud-client
d7edc529ed3722c811ff401440ef58ea980bf543
[ "Apache-2.0" ]
41
2018-07-12T08:09:39.000Z
2020-11-06T13:47:43.000Z
mbed-client/source/m2mdiscover.cpp
marcuschangarm/mbed-cloud-client
d7edc529ed3722c811ff401440ef58ea980bf543
[ "Apache-2.0" ]
53
2018-04-16T08:36:25.000Z
2020-11-02T15:50:43.000Z
/* * Copyright (c) 2021 Pelion. All rights reserved. * SPDX-License-Identifier: Apache-2.0 * 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 "include/m2mdiscover.h" #include "include/m2mreporthandler.h" #include "mbed-trace/mbed_trace.h" #include <stdio.h> #include <string.h> #if defined (MBED_CONF_MBED_CLIENT_ENABLE_DISCOVERY) && (MBED_CONF_MBED_CLIENT_ENABLE_DISCOVERY == 1) #define TRACE_GROUP "mDisc" uint8_t *M2MDiscover::create_object_payload(const M2MObject *object, uint32_t &data_length) { // First we do a dryrun to calculate the needed space uint32_t len = 0; uint8_t *data = 0; create_object_payload(object, &data, len); // Then allocate memory and fill the data data = (uint8_t *)malloc(len + 1); len = 0; if (data) { // copy pointer as it's moved inside the function uint8_t *tmp_data = data; create_object_payload(object, &tmp_data, len); tr_debug("M2MDiscover::create_object_payload - len: %d, data:\n%.*s", len, len, (char *)data); data_length = len; } return data; } uint8_t *M2MDiscover::create_object_instance_payload(const M2MObjectInstance *obj_instance, uint32_t &data_length) { // First we do a dryrun to calculate the needed space uint32_t len = 0; uint8_t *data = 0; create_object_instance_payload(obj_instance, &data, len, true, true, true); // Then allocate memory and fill the data data = (uint8_t *)malloc(len + 1); len = 0; if (data) { // copy pointer as it's moved inside the function uint8_t *tmp_data = data; create_object_instance_payload(obj_instance, &tmp_data, len, true, true, true); tr_debug("M2MDiscover::create_object_instance_payload - len: %d, data:\n%.*s", len, len, (char *)data); data_length = len; } return data; } uint8_t *M2MDiscover::create_resource_payload(const M2MResource *res, uint32_t &data_length) { // First we do a dryrun to calculate the needed space uint32_t len = 0; uint8_t *data = 0; create_resource_payload(res, &data, len, true, true, true); // Then allocate memory and fill the data data = (uint8_t *)malloc(len + 1); len = 0; if (data) { // copy pointer as it's moved inside the function uint8_t *tmp_data = data; create_resource_payload(res, &tmp_data, len, true, true, true); tr_debug("M2MDiscover::create_resource_payload - len: %d, data:\n%.*s", len, len, (char *)data); data_length = len; } return data; } void M2MDiscover::create_object_payload(const M2MObject *object, uint8_t **data, uint32_t &data_length) { // when Discover is done to object level, only object level attributes are listed and then list of object instances and their resources // for example </3>;pmin=10,</3/0>,</3/0/1>,</3/0/2>,</3/0/3>,</3/0/4>,</3/0/6>,</3/0/7>,</3/0/8>,</3/0/11>,</3/0/16> // which means that the LwM2M Client supports the Device Info Object (Instance 0) Resources with IDs 1,2,3,4 // 6,7,8,11, and 16 among the Resources of Device Info Object, with an R-Attributes assigned to the Object level. const M2MObjectInstanceList &object_instance_list = object->instances(); // Add object path and it's Write-Attributes to payload set_path_and_attributes(object->report_handler(), object->uri_path(), data, data_length); // Add object instances paths and their resource paths to payload if (!object_instance_list.empty()) { // add comma between object and object instances set_comma(data, data_length); M2MObjectInstanceList::const_iterator it; it = object_instance_list.begin(); for (; it != object_instance_list.end();) { create_object_instance_payload((const M2MObjectInstance *)*it, data, data_length, false, false, false); it++; if (it != object_instance_list.end()) { // add comma between object instances set_comma(data, data_length); } } } } void M2MDiscover::create_object_instance_payload(const M2MObjectInstance *obj_instance, uint8_t **data, uint32_t &data_length, bool add_resource_dimension, bool add_resource_attribute, bool add_object_attribute) { // when Discover is done to object instance level, attributes for object instance must be listed, resources and their attibutes // For example </3/0>;pmax=60,</3/0/1>,<3/0/2>,</3/0/3>,</3/0/4>,</3/0/6>;dim=8,</3/0/7>;dim=8;gt=50;lt=42.2,</3/0/8>;dim=8,</3/0/11>,</3/0/16> // means that regarding the Device Info Object Instance, an R-Attribute has been assigned to this Instance level. And // the LwM2M Client supports the multiple Resources 6, 7, and 8 with a dimension of 8 and has 2 additional // Notification parameters assigned for Resource 7. const M2MResourceList &resource_list = obj_instance->resources(); // Add object instance path and it's Write-Attributes to payload if (add_object_attribute) { set_path_and_attributes(obj_instance->report_handler(), obj_instance->uri_path(), data, data_length); } else { set_path(obj_instance->uri_path(), data, data_length); } // Add resource paths to payload and possible Write-Attributes to payload if (!resource_list.empty()) { // add comma between object instance and resources set_comma(data, data_length); M2MResourceList::const_iterator it; it = resource_list.begin(); for (; it != resource_list.end();) { create_resource_payload((const M2MResource *)*it, data, data_length, add_resource_dimension, add_resource_attribute); it++; if (it != resource_list.end()) { // add comma between resources set_comma(data, data_length); } } } } void M2MDiscover::create_resource_payload(const M2MResource *res, uint8_t **data, uint32_t &data_length, bool add_resource_dimension, bool add_resource_attribute, bool add_inherited) { // when Discover is done to resource level, list resource and it's attributes, // including the assigned R-Attributes and the R-Attributes inherited from the Object and Object Instance // For example: if Object ID is 3, and Resource ID is 7, then // </3/0/7>;dim=8;pmin=10;pmax=60;gt=50;lt=42.2 // with pmin assigned at the Object level, and pmax assigned at the Object Instance level // Add resource path to payload set_path(res->uri_path(), data, data_length); // add dimension, e.g. how many resource instances does this resource have, if none, then nothing is added to payload if (add_resource_dimension && res->supports_multiple_instances()) { set_string_and_value(data, data_length, ";dim=", 0, res->resource_instance_count(), false); } #if defined (MBED_CONF_MBED_CLIENT_ENABLE_OBSERVATION_PARAMETERS) && (MBED_CONF_MBED_CLIENT_ENABLE_OBSERVATION_PARAMETERS == 1) // Add possible Write-Attributes to payload if (add_resource_attribute) { set_resource_attributes(*res, data, data_length, add_inherited); } #endif } void M2MDiscover::set_comma(uint8_t **data, uint32_t &data_length) { if (*data) { memcpy(*data, ",", 1); *data += 1; } data_length++; } void M2MDiscover::set_string_and_value(uint8_t **data, uint32_t &data_length, const char* str, float float_value, int32_t int_value, bool float_type) { int max_val_len = REGISTRY_FLOAT_STRING_MAX_LEN; if (*data == NULL) { max_val_len = 0; } uint32_t tmp_len = strlen(str); data_length += tmp_len; if (*data) { memcpy(*data, str, tmp_len); *data += tmp_len; } #if MBED_MINIMAL_PRINTF if (float_type) { tmp_len = snprintf((char *)*data, max_val_len, "%f", float_value); } else { tmp_len = snprintf((char *)*data, max_val_len, "%d", int_value); } #else tmp_len = snprintf((char *)*data, max_val_len, "%g", float_type ? float_value : int_value); #endif data_length += tmp_len; if (*data) { // move data pointer to point after the added data *data += tmp_len; } } #if defined (MBED_CONF_MBED_CLIENT_ENABLE_OBSERVATION_PARAMETERS) && (MBED_CONF_MBED_CLIENT_ENABLE_OBSERVATION_PARAMETERS == 1) void M2MDiscover::set_resource_attributes(const M2MResource &res, uint8_t **data, uint32_t &data_length, bool add_inherited) { float attribute_value_float; uint32_t attribute_value_int; bool set_attribute = false; bool float_val = true; M2MReportHandler *report_handler = res.report_handler(); for (int attribute = M2MReportHandler::Pmin; attribute <= M2MReportHandler::St; attribute *= 2) { if ((attribute == M2MReportHandler::Pmin) || (attribute == M2MReportHandler::Pmax)) { float_val = false; } else { float_val = true; } report_handler = res.report_handler(); set_attribute = false; if (report_handler && report_handler->attribute_flags() & attribute) { get_write_attributes(*report_handler, (M2MReportHandler::WriteAttribute)attribute, attribute_value_float, attribute_value_int, float_val); set_attribute = true; } else if (add_inherited) { // check if inherited from object or object instance M2MObjectInstance &obj_inst = res.get_parent_object_instance(); report_handler = obj_inst.report_handler(); if (report_handler && (report_handler->attribute_flags() & attribute)) { get_write_attributes(*report_handler, (M2MReportHandler::WriteAttribute)attribute, attribute_value_float, attribute_value_int, float_val); set_attribute = true; } else { M2MObject &obj = obj_inst.get_parent_object(); report_handler = obj.report_handler(); if (report_handler && (report_handler->attribute_flags() & attribute)) { get_write_attributes(*report_handler, (M2MReportHandler::WriteAttribute)attribute, attribute_value_float, attribute_value_int, float_val); set_attribute = true; } } } if (set_attribute) { set_string_and_value(data, data_length, get_attribute_string((M2MReportHandler::WriteAttribute)attribute), attribute_value_float, attribute_value_int, float_val); } } } void M2MDiscover::get_write_attributes(M2MReportHandler &report_handler, M2MReportHandler:: WriteAttribute attribute, float &attribute_value_float, uint32_t &attribute_value_int, bool float_val) { if (float_val) { attribute_value_float = report_handler.get_notification_attribute_float(attribute); } else { attribute_value_int = report_handler.get_notification_attribute_int(attribute); } } const char *M2MDiscover::get_attribute_string(M2MReportHandler::WriteAttribute attribute) { const char *tmp = 0; switch (attribute) { case M2MReportHandler::Pmin: tmp = ";pmin="; break; case M2MReportHandler::Pmax: tmp = ";pmax="; break; case M2MReportHandler::Lt: tmp = ";lt="; break; case M2MReportHandler::Gt: tmp = ";gt="; break; case M2MReportHandler::St: tmp = ";st="; break; case M2MReportHandler::Cancel: /* fall-thru */ default: // Can't actually come here as we start looping from pmin, but let's satisfy the compiler tr_error("Invalid attrubute type: %d", attribute); assert(true); break; } return tmp; } #endif void M2MDiscover::set_path_and_attributes(M2MReportHandler *report_handler, const char *path, uint8_t **data, uint32_t &data_length) { set_path(path, data, data_length); #if defined (MBED_CONF_MBED_CLIENT_ENABLE_OBSERVATION_PARAMETERS) && (MBED_CONF_MBED_CLIENT_ENABLE_OBSERVATION_PARAMETERS == 1) if (report_handler) { float attribute_value_float; uint32_t attribute_value_int; bool float_val = true; for (int i = M2MReportHandler::Pmin; i <= M2MReportHandler::St; i *= 2) { if (report_handler->attribute_flags() & i) { if ((i == M2MReportHandler::Pmin) || (i == M2MReportHandler::Pmax)) { float_val = false; } else { float_val = true; } get_write_attributes(*report_handler, (M2MReportHandler::WriteAttribute)i, attribute_value_float, attribute_value_int, float_val); set_string_and_value(data, data_length, get_attribute_string((M2MReportHandler::WriteAttribute)i), attribute_value_float, attribute_value_int, float_val); } } } #endif } void M2MDiscover::set_path(const char *path, uint8_t **data, uint32_t &data_length) { data_length += 3; // </ > data_length += strlen(path); // e.g. "3" or "3/0" or "3/0/7" if (*data) { memcpy(*data, "</", 2); *data += 2; memcpy(*data, path, strlen(path)); *data += strlen(path); memcpy(*data, ">", 1); *data += 1; } } #endif // defined (MBED_CONF_MBED_CLIENT_ENABLE_DISCOVERY) && (MBED_CONF_MBED_CLIENT_ENABLE_DISCOVERY == 1)
40.353623
194
0.661112
marcuschangarm
50055b78e2f5144dcbd0d4c4353d0018b8456238
1,680
hh
C++
LFSR/src/LFSR.hh
mvy/Cryptographic-C---Toolkit
74f46d4ccca4f8af3e1af9580d95be9d84ced152
[ "MIT" ]
null
null
null
LFSR/src/LFSR.hh
mvy/Cryptographic-C---Toolkit
74f46d4ccca4f8af3e1af9580d95be9d84ced152
[ "MIT" ]
null
null
null
LFSR/src/LFSR.hh
mvy/Cryptographic-C---Toolkit
74f46d4ccca4f8af3e1af9580d95be9d84ced152
[ "MIT" ]
1
2019-06-22T20:25:43.000Z
2019-06-22T20:25:43.000Z
/* * Cryptographic C++ Toolkit (CCTk) * Martial Lienert, Yves Stadler */ #ifndef __LFSR_HH__ #define __LFSR_HH__ #include "CCTkConfig.hh" #include<vector> /** * Linear Feedback Shift Register * * More information on : * http://en.wikipedia.org/wiki/Linear_feedback_shift_register */ /* Handling 32 bits / 64 bits formats */ #ifdef LFSR32BITS # include "maskntap32.hh" #else # ifdef LFSR64BITS # include "maskntap64.hh" # else # warning "You did not define any of LFSR32BITS and LFSR64BITS. The build will prooceed assuming LFSR32BITS" # include "maskntap32.hh" # endif #endif /* Forward declaration */ class LFSR; class LFSR { private: /* * The length of the register */ unsigned int length; /* * The value of the register * The capacity depends on the system implementation of int. */ unsigned int registerValue; /* Initial vector of the LFSR, must be set by constructor in the * same time registerValue is first set */ unsigned int initialVector; /* Mask, polynomial */ unsigned int mask; public: /* Get the value, do the shift */ bool getValue(); /* Convenient method */ unsigned char getChar(); unsigned short getShort(); unsigned int getInt(); unsigned long getLong(); /* Get position i */ bool getBitAt(int); /* Apply a shift operation based on the polynomial */ void shift(); /* * Reinitialisatio * */ void reinit(); LFSR(unsigned int length, unsigned int mask, unsigned int); LFSR(const LFSR&); virtual ~LFSR(); }; #endif
21
115
0.62381
mvy
500e80e7c5580d995ef762523f48b356735ccdb2
1,236
cpp
C++
src/memory/xstr.cpp
Colinwang531/av_converged_communication_system_architecture
d8d8a2ff72b5342fd0c3426978884c0e9c43dde8
[ "MIT" ]
2
2021-12-10T07:45:30.000Z
2021-12-17T01:42:36.000Z
src/memory/xstr.cpp
Colinwang531/av_converged_communication_system_architecture
d8d8a2ff72b5342fd0c3426978884c0e9c43dde8
[ "MIT" ]
null
null
null
src/memory/xstr.cpp
Colinwang531/av_converged_communication_system_architecture
d8d8a2ff72b5342fd0c3426978884c0e9c43dde8
[ "MIT" ]
null
null
null
#ifdef _WINDOWS #include <string.h> #else #include <cstring> #endif//WINDOWS #include <new> #include "error_code.h" #include "memory/xstr.h" using namespace framework::utils::memory; XStr::XStr() {} XStr::~XStr() {} int XStr::copy( const char* src/* = nullptr*/, const uint64_t src_bytes/* = 0*/, char* dest/* = nullptr*/, const uint64_t dest_bytes/* = 0*/) { int ret{src && 0 < src_bytes && dest && 0 < dest_bytes ? Error_Code_Success : Error_Code_Invalid_Param}; if(Error_Code_Success == ret) { const uint64_t bytes{src_bytes > dest_bytes ? dest_bytes : src_bytes}; #ifdef _WINDOWS strncpy_s(dest, bytes + 1, src, bytes); #else strncpy(dest, src, bytes); #endif//WINDOWS } return ret; } char* XStr::alloc( const char* src/* = nullptr*/, const uint64_t bytes/* = 0*/) { char* dest{nullptr}; if (src && 0 < bytes) { dest = new(std::nothrow) char[bytes]{0}; if (dest) { copy(src, bytes, dest, bytes); } } return dest; } const uint64_t XStr::len(const char* src/* = nullptr*/) { uint64_t bytes{0}; if (src) { bytes = strlen(src); } return bytes; }
17.913043
108
0.572816
Colinwang531
5019f50e041edd4dd3dd83e2568da473280fd281
11,926
cpp
C++
RelevanceAnnotator.cpp
briangreenery/useless-text-editor
3e0bf11a9f833b88a0a69f2e6f564743b2f9e5b3
[ "Unlicense" ]
4
2018-05-17T11:17:26.000Z
2021-12-01T00:48:43.000Z
RelevanceAnnotator.cpp
briangreenery/useless-text-editor
3e0bf11a9f833b88a0a69f2e6f564743b2f9e5b3
[ "Unlicense" ]
null
null
null
RelevanceAnnotator.cpp
briangreenery/useless-text-editor
3e0bf11a9f833b88a0a69f2e6f564743b2f9e5b3
[ "Unlicense" ]
1
2021-05-31T19:08:00.000Z
2021-05-31T19:08:00.000Z
// RelevanceAnnotator.cpp #include "RelevanceAnnotator.h" #include "TextStyleRegistry.h" #include "TextDocument.h" #include "TextDocumentReader.h" #include "TextRange.h" #include <algorithm> RelevanceAnnotator::RelevanceAnnotator( const TextDocument& doc, TextStyleRegistry& styleRegistry ) : m_doc( doc ) , m_styleRegistry( styleRegistry ) { m_default = styleRegistry.ClassID( "default" ); m_keyword = styleRegistry.ClassID( "keyword.operator.relevance" ); m_number = styleRegistry.ClassID( "constant.numeric.relevance" ); m_string = styleRegistry.ClassID( "string.quoted.double.relevance" ); } uint32_t RelevanceAnnotator::TokenStyle( size_t token ) const { switch ( m_tokens[token].token ) { case Relevance::t_concat: case Relevance::t_star: case Relevance::t_plus: case Relevance::t_comma: case Relevance::t_minus: case Relevance::t_slash: case Relevance::t_semi_colon: case Relevance::t_or: case Relevance::t_not: case Relevance::t_equal: case Relevance::t_not_equal: case Relevance::t_contained_by: case Relevance::t_less: case Relevance::t_less_or_equal: case Relevance::t_greater: case Relevance::t_greater_or_equal: case Relevance::t_not_greater: case Relevance::t_not_greater_or_equal: case Relevance::t_not_less: case Relevance::t_not_less_or_equal: case Relevance::t_not_contained_by: case Relevance::t_not_contains: case Relevance::t_not_ends_with: case Relevance::t_not_starts_with: case Relevance::t_ends_with: case Relevance::t_starts_with: case Relevance::t_exist: case Relevance::t_not_exist: case Relevance::t_contains: case Relevance::t_mod: case Relevance::t_whose: case Relevance::t_of: case Relevance::t_it: case Relevance::t_as: case Relevance::t_and: return m_keyword; case Relevance::t_comment: case Relevance::e_comment_not_terminated: return m_default; case Relevance::t_number: case Relevance::e_number_too_big: return m_number; case Relevance::t_string: case Relevance::e_string_too_long: case Relevance::e_string_not_terminated: return m_string; case Relevance::t_if: case Relevance::t_then: case Relevance::t_else: return ( std::find( m_matchingTokens.begin(), m_matchingTokens.end(), token ) != m_matchingTokens.end() ) ? m_default : m_keyword; } return m_default; } class LexerOutputReceiver : public Relevance::LexerOutput { public: LexerOutputReceiver( RelevanceTokenRuns& runs ) : m_runs( runs ) , m_lastEnd( 0 ) {} virtual void Token( Relevance::LexerToken token, uint32_t pos, uint32_t length ) { if ( token != Relevance::e_bad_percent_sequence ) AddToken( token, pos, length ); } virtual void Word( Relevance::TextRef, uint32_t pos, uint32_t length ) { AddToken( Relevance::t_word, pos, length ); } virtual void Number( uint64_t value, uint32_t pos, uint32_t length ) { AddToken( Relevance::t_number, pos, length ); } virtual void String( Relevance::TextRef value, uint32_t pos, uint32_t length ) { AddToken( Relevance::t_string, pos, length ); } private: void AddToken( Relevance::LexerToken token, uint32_t pos, uint32_t length ) { assert( pos >= m_lastEnd ); if ( pos > m_lastEnd ) m_runs.push_back( RelevanceTokenRun( Relevance::t_default, m_lastEnd, pos - m_lastEnd ) ); if ( token != Relevance::t_end_of_input ) m_runs.push_back( RelevanceTokenRun( token, pos, length ) ); m_lastEnd = pos + length; } size_t m_lastEnd; RelevanceTokenRuns& m_runs; }; void RelevanceAnnotator::TextChanged( TextChange change ) { m_tokens.clear(); m_matchingTokens.clear(); TextDocumentReader reader( m_doc ); LexerOutputReceiver receiver( m_tokens ); Relevance::Lexer lexer( receiver ); for ( size_t start = 0; start < m_doc.Length(); start += 512 ) { AsciiRef text = reader.AsciiRange( start, 512 ); lexer.Receive( text.begin(), text.size() ); } lexer.Finish(); } void RelevanceAnnotator::SelectionChanged( size_t start, size_t end ) { m_matchingTokens.clear(); if ( start != end || start == 0 ) return; size_t token = TokenAt( start - 1 ); switch ( m_tokens[token].token ) { case Relevance::t_open_paren: MatchOpenParen( token ); break; case Relevance::t_close_paren: MatchCloseParen( token ); break; case Relevance::t_if: MatchIf( token ); break; case Relevance::t_then: MatchThen( token ); break; case Relevance::t_else: MatchElse( token ); break; } } void RelevanceAnnotator::MatchOpenParen( size_t openParen ) { size_t nesting = 0; for ( size_t i = openParen + 1; i < m_tokens.size(); ++i ) { Relevance::LexerToken token = m_tokens[i].token; if ( token == Relevance::t_close_paren ) { if ( nesting == 0 ) { m_matchingTokens.push_back( openParen ); m_matchingTokens.push_back( i ); break; } nesting--; } else if ( token == Relevance::t_open_paren ) nesting++; } } void RelevanceAnnotator::MatchCloseParen( size_t closeParen ) { size_t nesting = 0; for ( size_t i = closeParen; i-- > 0; ) { Relevance::LexerToken token = m_tokens[i].token; if ( token == Relevance::t_open_paren ) { if ( nesting == 0 ) { m_matchingTokens.push_back( i ); m_matchingTokens.push_back( closeParen ); break; } nesting--; } else if ( token == Relevance::t_close_paren ) nesting++; } } void RelevanceAnnotator::MatchIf( size_t position ) { size_t nextThen = NextThen( position ); size_t nextElse = NextElse( nextThen ); if ( nextThen < m_tokens.size() || nextElse < m_tokens.size() ) m_matchingTokens.push_back( position ); if ( nextThen < m_tokens.size() ) m_matchingTokens.push_back( nextThen ); if ( nextElse < m_tokens.size() ) m_matchingTokens.push_back( nextElse ); } void RelevanceAnnotator::MatchThen( size_t position ) { size_t prevIf = PrevIf ( position ); size_t nextElse = NextElse( position ); if ( prevIf < m_tokens.size() || nextElse < m_tokens.size() ) m_matchingTokens.push_back( position ); if ( prevIf < m_tokens.size() ) m_matchingTokens.push_back( prevIf ); if ( nextElse < m_tokens.size() ) m_matchingTokens.push_back( nextElse ); } void RelevanceAnnotator::MatchElse( size_t position ) { size_t prevThen = PrevThen( position ); size_t prevIf = PrevIf ( prevThen ); if ( prevIf < m_tokens.size() || prevThen < m_tokens.size() ) m_matchingTokens.push_back( position ); if ( prevIf < m_tokens.size() ) m_matchingTokens.push_back( prevIf ); if ( prevThen < m_tokens.size() ) m_matchingTokens.push_back( prevThen ); } size_t RelevanceAnnotator::PrevIf( size_t position ) const { if ( position >= m_tokens.size() ) return position; size_t nesting = 0; for ( size_t i = position; i-- > 0; ) { Relevance::LexerToken token = m_tokens[i].token; if ( token == Relevance::t_if ) { if ( nesting == 0 ) return i; nesting--; } else if ( token == Relevance::t_else ) nesting++; } return m_tokens.size(); } size_t RelevanceAnnotator::PrevThen( size_t position ) const { if ( position >= m_tokens.size() ) return position; size_t nesting = 0; for ( size_t i = position; i-- > 0; ) { Relevance::LexerToken token = m_tokens[i].token; if ( token == Relevance::t_else ) { nesting++; } else if ( token == Relevance::t_then ) { if ( nesting == 0 ) return i; } else if ( token == Relevance::t_if ) { if ( nesting == 0 ) break; nesting--; } } return m_tokens.size(); } size_t RelevanceAnnotator::NextThen( size_t position ) const { size_t nesting = 0; for ( size_t i = position + 1; i < m_tokens.size(); ++i ) { Relevance::LexerToken token = m_tokens[i].token; if ( token == Relevance::t_if ) { nesting++; } else if ( token == Relevance::t_then ) { if ( nesting == 0 ) return i; } else if ( token == Relevance::t_else ) { if ( nesting == 0 ) break; nesting--; } } return m_tokens.size(); } size_t RelevanceAnnotator::NextElse( size_t position ) const { size_t nesting = 0; for ( size_t i = position + 1; i < m_tokens.size(); ++i ) { Relevance::LexerToken token = m_tokens[i].token; if ( token == Relevance::t_else ) { if ( nesting == 0 ) return i; nesting--; } else if ( token == Relevance::t_if ) nesting++; } return m_tokens.size(); } typedef std::pair<RelevanceTokenRuns::const_iterator, RelevanceTokenRuns::const_iterator> TokenRange; struct TokenRunCompare { bool operator()( const RelevanceTokenRun& a, const RelevanceTokenRun& b ) const { return a.start + a.count <= b.start; } bool operator()( const RelevanceTokenRun& a, const TextRange& b ) const { return a.start + a.count <= b.start; } bool operator()( const TextRange& a, const RelevanceTokenRun& b ) const { return a.start + a.count <= b.start; } }; size_t RelevanceAnnotator::TokenAt( size_t position ) const { TextRange textRange( position, 1 ); RelevanceTokenRuns::const_iterator it = std::lower_bound( m_tokens.begin(), m_tokens.end(), textRange, TokenRunCompare() ); assert( it != m_tokens.end() ); return it - m_tokens.begin(); } void RelevanceAnnotator::GetClasses( TextStyleRuns& classes, size_t start, size_t count ) { TextRange textRange( start, count ); TokenRange range = std::equal_range( m_tokens.begin(), m_tokens.end(), textRange, TokenRunCompare() ); for ( RelevanceTokenRuns::const_iterator it = range.first; it != range.second; ++it ) { size_t overlapStart = (std::max)( start, it->start ); size_t overlapEnd = (std::min)( start + count, it->start + it->count ); classes.push_back( TextStyleRun( TokenStyle( it - m_tokens.begin() ), overlapStart, overlapEnd - overlapStart ) ); } } void RelevanceAnnotator::GetSquiggles( TextRanges& squiggles, size_t start, size_t count ) { TextRange textRange( start, count ); TokenRange range = std::equal_range( m_tokens.begin(), m_tokens.end(), textRange, TokenRunCompare() ); for ( RelevanceTokenRuns::const_iterator it = range.first; it != range.second; ++it ) { size_t overlapStart = (std::max)( start, it->start ); size_t overlapEnd = (std::min)( start + count, it->start + it->count ); if ( it->token == Relevance::e_word_too_long || it->token == Relevance::e_number_too_big || it->token == Relevance::e_comment_not_terminated || it->token == Relevance::e_bad_percent_sequence || it->token == Relevance::e_string_not_terminated || it->token == Relevance::e_illegal_character ) { if ( !squiggles.empty() && squiggles.back().start + squiggles.back().count == overlapStart ) squiggles.back().count += overlapEnd - overlapStart; else squiggles.push_back( TextRange( overlapStart, overlapEnd - overlapStart ) ); } } } void RelevanceAnnotator::GetHighlights( TextRanges& highlights, size_t start, size_t count ) { TextRange textRange( start, count ); TokenRange range = std::equal_range( m_tokens.begin(), m_tokens.end(), textRange, TokenRunCompare() ); for ( RelevanceTokenRuns::const_iterator it = range.first; it != range.second; ++it ) { size_t overlapStart = (std::max)( start, it->start ); size_t overlapEnd = (std::min)( start + count, it->start + it->count ); if ( std::find( m_matchingTokens.begin(), m_matchingTokens.end(), it - m_tokens.begin() ) != m_matchingTokens.end() ) { if ( !highlights.empty() && highlights.back().start + highlights.back().count == overlapStart ) highlights.back().count += overlapEnd - overlapStart; else highlights.push_back( TextRange( overlapStart, overlapEnd - overlapStart ) ); } } }
27.353211
125
0.668372
briangreenery
501ac698ad9439e27bac3263edc9c84cd9d66f66
63,046
cxx
C++
Peridigm/Code/Anisotropic_Material/io/mesh_input/quick_grid/QuickGrid.cxx
oldninja/PeriDoX
f31bccc7b8ea60cd814d00732aebdbbe876a2ac7
[ "BSD-3-Clause" ]
null
null
null
Peridigm/Code/Anisotropic_Material/io/mesh_input/quick_grid/QuickGrid.cxx
oldninja/PeriDoX
f31bccc7b8ea60cd814d00732aebdbbe876a2ac7
[ "BSD-3-Clause" ]
null
null
null
Peridigm/Code/Anisotropic_Material/io/mesh_input/quick_grid/QuickGrid.cxx
oldninja/PeriDoX
f31bccc7b8ea60cd814d00732aebdbbe876a2ac7
[ "BSD-3-Clause" ]
null
null
null
/*! \file QuickGrid.cxx */ //@HEADER // ************************************************************************ // // Peridigm // Copyright (2011) Sandia Corporation // // Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation, // the U.S. Government retains certain rights in this software. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // 1. Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // 3. Neither the name of the Corporation nor the names of the // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY SANDIA CORPORATION "AS IS" AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL SANDIA CORPORATION OR THE // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Questions? // David J. Littlewood djlittl@sandia.gov // John A. Mitchell jamitch@sandia.gov // Michael L. Parks mlparks@sandia.gov // Stewart A. Silling sasilli@sandia.gov // // ************************************************************************ //@HEADER #include "QuickGrid.h" #include <Teuchos_ParameterList.hpp> #ifdef USE_YAML #include <Teuchos_YamlParameterListCoreHelpers.hpp> #endif #include "mpi.h" #include <vector> #include <cmath> #include <string> #include <iostream> #include <set> #include <map> #include <cstdlib> namespace QUICKGRID { using std::shared_ptr; using UTILITIES::Minus; using UTILITIES::Dot; shared_ptr<QuickGridMeshGenerationIterator> getMeshGenerator(size_t numProcs, const std::string& yaml_file_name) { Teuchos::ParameterList params; Teuchos::Ptr<Teuchos::ParameterList> params_ptr(&params); if (!file_exists(yaml_file_name)) { std::string msg = "\n**** Error, failed to open file " + yaml_file_name; msg += " (unit tests may need to be executed from within the directory where they reside)."; std::cout << "\n" << msg << std::endl;; throw std::runtime_error(msg); } #ifdef USE_YAML Teuchos::updateParametersFromYamlFile(yaml_file_name, params_ptr); #else std::string msg = "\n\n**** Error, getMeshGenerator() requires YAML."; std::cout << msg << std::endl; throw std::runtime_error(msg); #endif Teuchos::ParameterList disc_params = params.sublist("Discretization"); double horizon = disc_params.get<double>("Horizon"); std::string neighborhood_type = disc_params.get<std::string>("NeighborhoodType", "Not Supplied"); std::string type = disc_params.get<std::string>("Type"); shared_ptr<TensorProduct3DMeshGenerator> g; NormFunctionPointer norm = NoOpNormFunction; if(type == "QuickGrid.TensorProduct3DMeshGenerator"){ Teuchos::ParameterList mesh_params = params.sublist("QuickGrid").sublist("TensorProduct3DMeshGenerator"); double xStart = mesh_params.get<double>("X Origin"); double yStart = mesh_params.get<double>("Y Origin"); double zStart = mesh_params.get<double>("Z Origin"); double xLength = mesh_params.get<double>("X Length"); double yLength = mesh_params.get<double>("Y Length"); double zLength = mesh_params.get<double>("Z Length"); const int nx = mesh_params.get<int>("Number Points X"); const int ny = mesh_params.get<int>("Number Points Y"); const int nz = mesh_params.get<int>("Number Points Z"); const Spec1D xSpec(nx,xStart,xLength); const Spec1D ySpec(ny,yStart,yLength); const Spec1D zSpec(nz,zStart,zLength); // set neighborhood norm operator if("Spherical"==neighborhood_type) norm = SphericalNorm; // Create decomposition iterator g = shared_ptr<TensorProduct3DMeshGenerator>(new TensorProduct3DMeshGenerator(numProcs, horizon, xSpec, ySpec, zSpec, norm)); } else { std::string s; s = "Error-->QUICKGRID::getMeshGenerator()\n"; s += "\tOnly Reader for Discretization.Type==QuickGrid.TensorProduct3DMeshGenerator is implemented\n"; s += "\tCome back soon for the other type(s):)\n"; throw std::runtime_error(s); } return g; } void print_meta_data(const QuickGridData& gridData, const std::string& label) { std::stringstream s; s << label << "\n"; s << "QUICKGRID.print_meta_data(const QuickGridData& gridData)\n"; s << "\tdimension : " << gridData.dimension << "\n"; s << "\tglobalNumPoints : " << gridData.globalNumPoints << "\n"; s << "\tsizeNeighborhoodList : " << gridData.sizeNeighborhoodList << "\n"; s << "\tnumExport : " << gridData.numExport << "\n"; std::string unpack = gridData.unPack ? "true" : "false"; s << "\tunPack : " << unpack << "\n"; int *ptr = gridData.neighborhoodPtr.get(); int *neigh = gridData.neighborhood.get(); for(size_t n=0;n<gridData.numPoints;n++,ptr++){ int num_neigh = *neigh; neigh++; s << "\tNeighborhood : " << gridData.myGlobalIDs.get()[n] << "; neigh ptr : " << *ptr << "; num neigh : " << num_neigh << "\n\t"; for(int p=0;p<num_neigh;p++,neigh++){ if(0 == p%10 && 0 != p) s << "\n\t"; s << *neigh << ", "; } s << "\n"; } std::cout << s.str(); } bool SphericalNormFunction (const double* u, const double* v, double r) { double dx = v[0]-u[0]; double dy = v[1]-u[1]; double dz = v[2]-u[2]; return dx*dx+dy*dy+dz*dz - r*r < 0.0; } bool NoOpNormFunction (const double* u, const double* v, double r) { return true; } QuickGridData allocatePdGridData(size_t numCells, size_t dimension){ // coordinates Array<double> X(numCells*dimension); // angles Array<double> Angles(numCells*dimension); // volume Array<double> V(numCells); // Global ids for cells on this processor Array<int> globalIds(numCells); // array in indices that point to neighborhood for a given localId Array<int> neighborhoodPtr(numCells); // Flag for marking points that get exported during load balance Array<char> exportFlag(numCells); // Initialize all the above data to zero double *xPtr = X.get(); double *anglesPtr = Angles.get(); double *vPtr = V.get(); int *gIdsPtr = globalIds.get(); int *nPtr = neighborhoodPtr.get(); char *exportFlagPtr = exportFlag.get(); for(size_t p=0;p<numCells;p++){ for(size_t d=0;d<dimension;d++){ xPtr[p*dimension+d]=0; anglesPtr[p*dimension+d]=0;} vPtr[p]=0; gIdsPtr[p]=0; nPtr[p]=0; exportFlagPtr[p]=0; } /* * Neighborhood data is consistent but essentially empty. * Points, Ids, volume are allocated but need to be filled with * correct values */ QuickGridData gridData; /* * Initialize neighborhood list to a consistent state * 1) Set sizeNeighborhoodList=1 * 2) Create a new and empty neighborhood * 3) Set neighborhood pointer for each point to 0 */ int sizeNeighborhoodList=1; Array<int> neighborhoodList(sizeNeighborhoodList); int *neighborhood = neighborhoodList.get(); /* * number of neighbors for every point is zero */ *neighborhood = 0; gridData.dimension = dimension; gridData.globalNumPoints = 0; gridData.numPoints = numCells; gridData.sizeNeighborhoodList = sizeNeighborhoodList; gridData.numExport=0; gridData.myGlobalIDs = globalIds.get_shared_ptr(); gridData.myX = X.get_shared_ptr(); gridData.myAngle = Angles.get_shared_ptr(); gridData.cellVolume = V.get_shared_ptr(); gridData.neighborhood = neighborhoodList.get_shared_ptr(); gridData.neighborhoodPtr = neighborhoodPtr.get_shared_ptr(); gridData.exportFlag = exportFlag.get_shared_ptr(); gridData.unPack = true; return gridData; } Array<double> getDiscretization(const Spec1D& spec){ size_t numCells = spec.getNumCells(); Array<double> ptr(numCells); double x0=spec.getX0(); double cellSize=spec.getCellSize(); double p = x0+cellSize/2.0; double *x = ptr.get(); for(size_t i=0;i<numCells;p+=cellSize,i++) x[i]=p; return ptr; } Array<double> getDiscretization(const Spec1D& xSpec, const Spec1D& ySpec){ Array<double> xx = getDiscretization(xSpec); Array<double> yy = getDiscretization(ySpec); double*x=xx.get(); double*y=yy.get(); size_t nx = xSpec.getNumCells(); size_t ny = ySpec.getNumCells(); size_t numCells = nx*ny; Array<double> g(2*numCells); double* gPtr = g.get(); double *yPtr = y; for(size_t j=0;j<ny;j++,yPtr++){ double *xPtr = x; for(size_t i=0;i<nx;i++,xPtr++){ *gPtr=*xPtr; gPtr++; *gPtr=*yPtr; gPtr++; } } return g; } Array<double> getDiscretization(const Spec1D& xSpec, const Spec1D& ySpec, const Spec1D& zSpec){ // Set points and cells // note number of points is same as number of cells size_t nx = xSpec.getNumCells(); size_t ny = ySpec.getNumCells(); size_t nz = zSpec.getNumCells(); size_t numCells = nx*ny*nz; Array<double> xx = getDiscretization(xSpec); Array<double> yy = getDiscretization(ySpec); Array<double> zz = getDiscretization(zSpec); double*x=xx.get(); double*y=yy.get(); double*z=zz.get(); size_t dimension=3; Array<double> X(numCells*dimension); double *XPtr = X.get(); double point[3]={0.0,0.0,0.0}; for(size_t k=0;k<nz;k++){ point[2]=z[k]; for(size_t j=0;j<ny;j++){ point[1]=y[j]; for(size_t i=0;i<nx;i++){ point[0]=x[i]; for(size_t p=0;p<3;p++,XPtr++) *XPtr = point[p]; } } } return X; } Array<double> getDiscretization(const SpecRing2D& spec) { // Compute set of radii for each ring Spec1D rSpec(spec.getNumRings(), spec.getrI(), spec.getRingThickness()); Array<double> rPtr = getDiscretization(rSpec); Vector3D c = spec.getCenter(); size_t numRays = spec.getNumRays(); size_t numRings = spec.getNumRings(); double pi = PeridigmNS::value_of_pi(); Spec1D thetaSpec(numRays, 0.0, 2.0*pi); Array<double> thPtr = getDiscretization(thetaSpec); // Total number of cells size_t numCells = spec.getNumCells(); // At each point store (x,y,z=0) + (c[0]+c[1]+c[2]) Array<double> gPtr(3*numCells); double *g = gPtr.get(); // Outer loop on rays double *theta = thPtr.get(); for(size_t ny=0;ny<numRays;ny++,theta++){ // Loop over rings double *r = rPtr.get(); for(size_t nx=0;nx<numRings;nx++,r++){ *g = (*r)*cos(*theta) + c[0]; g++; *g = (*r)*sin(*theta) + c[1]; g++; *g = c[2]; g++; } } return gPtr; } Array<double> getDiscretization(const SpecRing2D& spec, const Spec1D& axisSpec){ Array<double> ptsPtr = getDiscretization(spec); Array<double> zPtr = getDiscretization(axisSpec); size_t nz = axisSpec.getNumCells(); size_t numCellsRing = spec.getNumCells(); size_t numCells = numCellsRing*nz; Array<double> gPtr(3*numCells); double *g = gPtr.get(); double *z = zPtr.get(); for(size_t n=0;n<nz;n++,z++){ double *pts = ptsPtr.get(); for(size_t i=0;i<numCellsRing;i++){ // this does x and y and z *g = *pts; g++, pts++; *g = *pts; g++, pts++; *g = *z; g++; pts++; } } return gPtr; } Horizon Spec1D::getCellHorizon(double h) const { int n = getCellNeighborhoodSize(h); return Horizon(n,this->numCells); } RingHorizon Spec1D::getRingCellHorizon(double h,double ringRadius) const { int n = getCellNeighborhoodSize(h,ringRadius); return RingHorizon(n,this->numCells); } /* * Input: double horizon * Output: integer horizon -- This is the one-sided size of the * neighborhood expressed in the number of cells which define * the discretization */ size_t Spec1D::getCellNeighborhoodSize(double horizon, double ringRadius) const { double dx = getCellSize()*ringRadius; double dCx = horizon/dx; size_t nCx = static_cast<size_t>(dCx); // std::cout << "PdQPointSet1d::getCellNeighborhoodSize" << std::endl; // std::cout << "\tincoming horizon = " << h << "; ratio dCx = h/dx = " << dCx << "; nCx = " << nCx << std::endl; if(std::abs(dCx - nCx) >= .5 ) nCx += 1; // std::cout << "Final nCx = " << nCx << std::endl; // this handles the pathology when the horizon > 1.5 * xLength if(nCx > numCells) nCx = numCells; return nCx; } SpecRing2D::SpecRing2D(Vector3D center, double innerRadius, double outerRadius, int numRings) : c(center), rI(innerRadius), r0(outerRadius), numRings(numRings), numRays(0), numCells(0) { // Compute set of radii for each ring double ringThickness = r0-rI; double dr=ringThickness/numRings; // Use an average radius double R = (rI+r0)/2; // Try to make cells with equal length sides -- compute angular increment double dTheta = dr/R; double pi = PeridigmNS::value_of_pi(); numRays = (size_t)(2 * pi / dTheta) + 1; numCells = numRays * this->numRings; } double SpecRing2D::getRingThickness() const { return std::abs(r0-rI); } QuickGridMeshGenerationIterator::QuickGridMeshGenerationIterator(size_t numProcs, NormFunctionPointer norm) : iteratorProc(0), numProcs(numProcs), neighborHoodNorm(norm) {} std::pair<Cell3D,QuickGridData> QuickGridMeshGenerationIterator::beginIterateProcs(QuickGridData& pdGridDataProc0) { iteratorProc = 0; Cell3D cellLocator(0,0,0); std::pair<Cell3D,QuickGridData> returnVal = computePdGridData(iteratorProc, cellLocator, pdGridDataProc0, neighborHoodNorm); iteratorProc++; return returnVal; } std::pair<Cell3D,QuickGridData> QuickGridMeshGenerationIterator::nextProc(Cell3D cellLocator, QuickGridData& pdGridDataProcN) { std::pair<Cell3D,QuickGridData> returnVal = computePdGridData(iteratorProc, cellLocator, pdGridDataProcN, neighborHoodNorm); iteratorProc++; return returnVal; } std::vector<size_t> QuickGridMeshGenerationIterator::getNumCellsPerProcessor(size_t globalNumCells, size_t numProcs) { // compute cellsPerProc std::vector<size_t> cellsPerProc; int numCellsPerProc = globalNumCells/numProcs; int numCellsLastProc = numCellsPerProc + globalNumCells % numProcs; cellsPerProc = std::vector<size_t>(numProcs,numCellsPerProc); cellsPerProc[numProcs-1] = numCellsLastProc; return cellsPerProc; } TensorProduct3DMeshGenerator::TensorProduct3DMeshGenerator ( size_t numProc, double radiusHorizon, const Spec1D& xSpec, const Spec1D& ySpec, const Spec1D& zSpec, NormFunctionPointer norm ) : QuickGridMeshGenerationIterator(numProc,norm), horizonRadius(radiusHorizon), globalNumberOfCells(0), specs(3,xSpec), H(3,xSpec.getCellHorizon(radiusHorizon)) { globalNumberOfCells = xSpec.getNumCells()*ySpec.getNumCells()*zSpec.getNumCells(); // Need to correct for the initial value set at default constructor of vector // specs[0] = xSpec; specs[1] = ySpec; H[1] = ySpec.getCellHorizon(radiusHorizon); specs[2] = zSpec; H[2] = zSpec.getCellHorizon(radiusHorizon); cellsPerProc = QuickGridMeshGenerationIterator::getNumCellsPerProcessor(globalNumberOfCells,numProc); // This is for computing the tensor product space xx = getDiscretization(xSpec); yy = getDiscretization(ySpec); zz = getDiscretization(zSpec); } QuickGridData TensorProduct3DMeshGenerator::allocatePdGridData() const { // Number of cells on this processor -- number of cells on last // processor is always <= numCellsPerProc size_t numCellsAllocate = cellsPerProc[getNumProcs()-1]; size_t dimension = 3; return QUICKGRID::allocatePdGridData(numCellsAllocate, dimension); } std::pair<Cell3D,QuickGridData> TensorProduct3DMeshGenerator::computePdGridData(size_t proc, Cell3D cellLocator, QuickGridData& pdGridData, NormFunctionPointer norm) const { // std::cout << "CellsPerProcessor3D::computePdGridData proc = " << proc << std::endl; Spec1D xSpec = specs[0]; Spec1D ySpec = specs[1]; Spec1D zSpec = specs[2]; size_t nx = xSpec.getNumCells(); size_t ny = ySpec.getNumCells(); size_t nz = zSpec.getNumCells(); // Each cell has the same volume double cellVolume = xSpec.getCellSize()*ySpec.getCellSize()*zSpec.getCellSize(); // Horizon in each of the coordinate directions Horizon hX = H[0]; Horizon hY = H[1]; Horizon hZ = H[2]; // Number of cells on this processor size_t myNumCells = cellsPerProc[proc]; // Coordinates used for tensor product space const double*x=xx.get(); const double*y=yy.get(); const double*z=zz.get(); // Discretization on this processor pdGridData.dimension = 3; pdGridData.globalNumPoints = nx*ny*nz; pdGridData.numPoints = myNumCells; int *gidsPtr = pdGridData.myGlobalIDs.get(); double *XPtr = pdGridData.myX.get(); double *volPtr = pdGridData.cellVolume.get(); // allocate neighborhood for incoming data since each one of these has a different length int sizeNeighborhoodList = getSizeNeighborList(proc, cellLocator); pdGridData.sizeNeighborhoodList = sizeNeighborhoodList; Array<int> neighborhoodList(sizeNeighborhoodList); pdGridData.neighborhood = neighborhoodList.get_shared_ptr(); int *neighborPtr = neighborhoodList.get(); int updateSizeNeighborhoodList = 0; // Compute discretization on processor size_t kStart = cellLocator.k; size_t jStart = cellLocator.j; size_t iStart = cellLocator.i; size_t cell = 0; double point[3]={0.0,0.0,0.0}; double pointNeighbor[3] = {0.0,0.0,0.0}; for(size_t k=kStart;k<nz && cell<myNumCells;k++){ // kStart = 0; this one doesn't matter cellLocator.k = k; point[2]=z[k]; size_t zStart = hZ.start(k); size_t nCz = hZ.numCells(k); for(size_t j=jStart;j<ny && cell<myNumCells;j++){ jStart=0; // begin at jStart only the first time cellLocator.j = j; point[1]=y[j]; size_t yStart = hY.start(j); size_t nCy = hY.numCells(j); for(size_t i=iStart;i<nx && cell<myNumCells;i++,cell++,cellLocator.i++){ iStart=0; // begin at iStart only the first time // global id *gidsPtr = i + j * nx + k * nx * ny; gidsPtr++; point[0]=x[i]; // copy point data for(size_t p=0;p<3;p++,XPtr++) *XPtr = point[p]; // copy cell volume *volPtr = cellVolume; volPtr++; size_t xStart = hX.start(i); size_t nCx = hX.numCells(i); // number of cells in this (i,j,k) neighborhood // *neighborPtr = computeNumNeighbors(i,j,k); neighborPtr++; // Compute neighborhood int *numNeigh = neighborPtr; neighborPtr++; int countNeighbors = 0; for(size_t kk=zStart;kk<nCz+zStart;kk++){ for(size_t jj=yStart;jj<nCy+yStart;jj++){ for(size_t ii=xStart;ii<nCx+xStart;ii++){ // skip this cell since its its own neighbor if(ii == i && jj == j && kk == k) continue; pointNeighbor[0] = x[ii]; pointNeighbor[1] = y[jj]; pointNeighbor[2] = z[kk]; if(norm(pointNeighbor,point,horizonRadius)){ int globalId = ii + jj * nx + kk * nx * ny; *neighborPtr = globalId; neighborPtr++; countNeighbors++; } } } } *numNeigh = countNeighbors; updateSizeNeighborhoodList += countNeighbors; } if(cellLocator.i == nx){ cellLocator.i = 0; if(cell==myNumCells){ // current j holds current last row which needs to be incremented cellLocator.j += 1; if(cellLocator.j == ny){ cellLocator.j = 0; // current k holds current last row which needs to be incremented cellLocator.k += 1; } } } } } // post process and compute neighborhoodPtr pdGridData.sizeNeighborhoodList = updateSizeNeighborhoodList+myNumCells; int *neighPtr = pdGridData.neighborhoodPtr.get(); int *neighborListPtr = neighborhoodList.get(); int sum=0; for(size_t n=0;n<myNumCells;n++){ neighPtr[n]=sum; int numCells = *neighborListPtr; neighborListPtr += (numCells+1); sum += (numCells+1); } return std::pair<Cell3D,QuickGridData>(cellLocator,pdGridData); } size_t TensorProduct3DMeshGenerator::getSizeNeighborList(size_t proc, Cell3D cellLocator) const { Spec1D xSpec = specs[0]; Spec1D ySpec = specs[1]; Spec1D zSpec = specs[2]; size_t nx = xSpec.getNumCells(); size_t ny = ySpec.getNumCells(); size_t nz = zSpec.getNumCells(); /* * Compacted list of neighbors * 1) for i = 0,..(numCells-1) * 2) numCellNeighborhood(i) * 3) neighorhood(i) -- does not include "i" */ // for each cell store numCells + neighborhood // int size = numCells + sum(numCells(i),i); size_t numCells = cellsPerProc[proc]; size_t size=numCells; // Perform sum over all neighborhoods size_t kStart = cellLocator.k; size_t jStart = cellLocator.j; size_t iStart = cellLocator.i; size_t cell = 0; for(size_t k=kStart;k<nz;k++){ // kStart = 0; this one doesn't matter for(size_t j=jStart;j<ny;j++){ jStart=0; // begin at jStart only the first time for(size_t i=iStart;i<nx && cell<numCells;i++,cell++){ // begin at iStart only the first time iStart = 0; size += computeNumNeighbors(i,j,k); } } } return size; } size_t TensorProduct3DMeshGenerator::computeNumNeighbors(size_t i, size_t j, size_t k) const { // Horizon in each of the coordinate directions Horizon hX = H[0]; Horizon hY = H[1]; Horizon hZ = H[2]; size_t nCx = hX.numCells(i); size_t nCy = hY.numCells(j); size_t nCz = hZ.numCells(k); /* * Number of cells in this (i,j,k) neighborhood * Note that '1' is subtracted to remove "this cell" */ return nCx * nCy * nCz - 1; } AxisSymmetric2DCylinderMeshGenerator::AxisSymmetric2DCylinderMeshGenerator ( size_t nProcs, double radiusHorizon, const SpecRing2D& rSpec, double cylinder_length, NormFunctionPointer norm ) : QuickGridMeshGenerationIterator(nProcs,norm), horizonRadius(radiusHorizon), global_num_cells(0), global_num_master_cells(0), global_num_slave_cells(0), ringSpec(rSpec), specs(3,rSpec.getRaySpec()), ringHorizon(0,0), H(3,Horizon(0,0)) { // Set up tensor product specs // radial direction Spec1D raySpec=ringSpec.getRaySpec(); specs[0] = raySpec; double dr=raySpec.getCellSize(); size_t nr=ringSpec.getNumRings(); H[0] = raySpec.getCellHorizon(radiusHorizon); // r // theta direction -- ultimately this will be a 'wedge' // number of slave cells on one side of master along theta dir size_t nt = (size_t)( 2.0 * horizonRadius * nr / ringSpec.getRingThickness() ); // Total number of cells along theta // master + 2 * nt // By construction, nt is 'odd' nt = 1 + 2 * nt; // uses average radius of ring for computing cell 'd_theta' double d_theta=2.0*ringSpec.getRingThickness() / nr / (ringSpec.getr0()+ringSpec.getrI()); // this is total wedge angle double wedge_theta=nt * d_theta; // mesh generator along theta begins at -wedge_theta/2 double theta_0=-wedge_theta/2.0; specs[1] = Spec1D(nt,theta_0,wedge_theta); // note that horizon of for theta direction is special because of the arc length // note the use of average radius // note that there is no 'H[1]' here; ringHorizon takes the place of 'H[1]' ringHorizon = specs[1].getRingCellHorizon(radiusHorizon,(rSpec.getrI()+rSpec.getr0())/2.0); // cylinder axis -- z direction // set number of cells along axis so that dz~dr double dz=dr; size_t nz= (size_t)( cylinder_length/dz ); if(0==nz) nz+=1; Vector3D center = rSpec.getCenter(); dz=cylinder_length/nz; double z0=center[2]-dz/2; Spec1D axisSpec(nz,z0,cylinder_length); specs[2] = axisSpec; H[2]=axisSpec.getCellHorizon(horizonRadius); // number of cells in master global_num_master_cells = nr * nz; // Number of cells in wedge global_num_cells = nr * nt * nz; // number of slave cells global_num_slave_cells=global_num_cells-global_num_master_cells; // compute cellsPerProc -- this is for the 2D r-z mesh cellsPerProc = QuickGridMeshGenerationIterator::getNumCellsPerProcessor(global_num_master_cells,nProcs); rPtr = getDiscretization(specs[0]); thetaPtr = getDiscretization(specs[1]); zPtr = getDiscretization(specs[2]); } QuickGridData AxisSymmetric2DCylinderMeshGenerator::sweep_to_wedge ( QuickGridData decomp ) const { Spec1D r_spec = specs[0]; Spec1D theta_spec = specs[1]; Spec1D z_spec = specs[2]; size_t nr = r_spec.getNumCells(); size_t nt = theta_spec.getNumCells(); size_t nz = z_spec.getNumCells(); size_t num_half_sweep = (nt-1)/2; size_t num_master=decomp.numPoints; size_t num_owned=num_master * nt; /* * Allocate a new wedge */ size_t dimension=3; QuickGridData wedge=QUICKGRID::allocatePdGridData(num_owned, dimension); Array<int> GIDs(wedge.numPoints,wedge.myGlobalIDs); shared_ptr<double> xOwned=wedge.myX; Array<double> cellVolume(wedge.numPoints*wedge.dimension,wedge.cellVolume); // cout << "QuickGridData AxisSymmetric2DCylinderMeshGenerator::sweep_to_wedge \n"; // cout << "\tnum cells along sweep = " << nt << "\n"; // cout << "\tnum cells half sweep = " << num_half_sweep << "\n"; /* * Put GIDs of master points at front of list */ { double *xMaster=decomp.myX.get(); double *xPtr=xOwned.get(); double *masterVolume=decomp.cellVolume.get(); for(int m=0,*gid=decomp.myGlobalIDs.get(), *end=decomp.myGlobalIDs.get()+num_master;gid!=end;m++,gid++){ size_t i=(*gid)%nr; size_t k=(*gid)/nr; // new master id size_t master_id= nt * nz * i + k * nt + num_half_sweep; /* * assign master id */ GIDs[m]=master_id; /* * copy master volumes over to slaves */ cellVolume[m]=masterVolume[m]; /* * copy coordinates */ xPtr[0]=xMaster[0]; xPtr[1]=xMaster[1]; xPtr[2]=xMaster[2]; xPtr+=3; xMaster+=3; } } /* * Now add owned slave nodes * Note shift of xPtr to beginning of slave points since we already set master points at start in above */ double *xMaster=decomp.myX.get(); double *xPtr=xOwned.get()+3*num_master; double *masterVolume=decomp.cellVolume.get(); double *slaveVolume=cellVolume.get()+num_master; size_t m = 0; for(int *gid=decomp.myGlobalIDs.get(),*GID=GIDs.get()+num_master;m<num_master;m++){ size_t i=(gid[m])%nr; size_t k=(gid[m])/nr; // new master id size_t master_id= nt * nz * i + k * nt + num_half_sweep; // coordinate of master point to be swept out below double r = *(xMaster+0); double z = *(xMaster+2); /* * move to next master point */ xMaster+=3; double masterCellVolume=masterVolume[m]; // sweep theta const double *theta=thetaPtr.get(); // sweep 1st half // create 1st half of slave ids for(size_t j=0;j<num_half_sweep;j++,GID++,theta++,xPtr+=3,slaveVolume++){ size_t slave_id=master_id - num_half_sweep + j; *GID=slave_id; xPtr[0] = r * cos(*theta); xPtr[1] = r * sin(*theta); xPtr[2] = z; *slaveVolume=masterCellVolume; } // skip master theta=0 theta++; // sweep 2nd half // create 2nd half of slave ids for(size_t j=num_half_sweep+1;j<2*num_half_sweep+1;j++,GID++,theta++,xPtr+=3,slaveVolume++){ size_t slave_id=master_id - num_half_sweep + j; *GID=slave_id; xPtr[0] = r * cos(*theta); xPtr[1] = r * sin(*theta); xPtr[2] = z; *slaveVolume=masterCellVolume; } } return wedge; } /* * This function re-arranges owned points into the following order * 1) master * 2) slaves with masters owned by this processor * 3) slaves with masters owned by another processor */ AxisSymmetricWedgeData AxisSymmetric2DCylinderMeshGenerator::create_wedge_data(QuickGridData& decomp) const { // Spec1D r_spec = specs[0]; Spec1D theta_spec = specs[1]; Spec1D z_spec = specs[2]; // size_t nr = r_spec.getNumCells(); size_t nt = theta_spec.getNumCells(); size_t nz = z_spec.getNumCells(); /* * note that nt = 2 num_half_sweep +1 */ size_t num_half_sweep = (nt-1)/2; /* * average radius of ring */ double R = (ringSpec.getrI()+ringSpec.getr0())/2.0; size_t num_owned=decomp.numPoints; Array<int> newGIDs(num_owned); Array<double> new_theta(num_owned); Array<double> newVolume(num_owned); Array<double> newX(num_owned*3); std::set<int> owned_masters; std::map<int,int> masters_localid_map; { /* * This loop collects all owned points in the master surface */ int *gids=decomp.myGlobalIDs.get(); double *volume=decomp.cellVolume.get(); double *X=decomp.myX.get(); double tolerance=1.0e-15; for(size_t p=0, num_master=0;p<num_owned;p++,gids++,X+=3){ /* * is gid a 'master' ?? * Every point in the master surface has y = 0.0 */ double y = *(X+1)/R; if(std::abs(y)<=tolerance){ /* * This is a master point; * Add to set; */ owned_masters.insert(*gids); masters_localid_map[*gids]=num_master; newGIDs[num_master]=*gids; /* * master points rotate into themselves: theta = 0.0 */ new_theta[num_master]=0.0; newVolume[num_master]=*volume; newX[3*num_master+0]=*(X+0); newX[3*num_master+1]=*(X+1); newX[3*num_master+2]=*(X+2); num_master+=1; } } } std::set<int>::iterator master_start = owned_masters.begin(); std::set<int>::const_iterator end=owned_masters.end(); size_t num_owned_slaves(0); size_t num_master = owned_masters.size(); { /* * This loop calculates the number of slave points whose master * is owned by this processor; * For these slave nodes, data is also moved to the * slave node */ int *gids=decomp.myGlobalIDs.get(); double *volume=decomp.cellVolume.get(); double *X=decomp.myX.get(); const double *theta=thetaPtr.get(); double tolerance=1.0e-15; for(size_t p=0;p<num_owned;p++,gids++,volume++,X+=3){ /* * gid an owned 'master' ?? */ double y = *(X+1)/R; if(std::abs(y)<=tolerance){ /* * this case was already handled above */ continue; } /* gid is a slave * Is master owned by ANOTHER processor * NOTE '!=' */ size_t j_theta = (*gids)%(nt*nz); size_t master_id = *gids + num_half_sweep - j_theta; if(end!=owned_masters.find(master_id)){ /* * we own this slave's master */ newGIDs[num_master+num_owned_slaves]=*gids; new_theta[num_master+num_owned_slaves]=theta[j_theta]; newVolume[num_master+num_owned_slaves]=*volume; newX[3*(num_master+num_owned_slaves)+0]=*(X+0); newX[3*(num_master+num_owned_slaves)+1]=*(X+1); newX[3*(num_master+num_owned_slaves)+2]=*(X+2); num_owned_slaves+=1; } } } size_t num_overlap_slaves(0); { /* * This loop calculates the number of slave points * whose master we DO NOT own */ int *gids=decomp.myGlobalIDs.get(); double *volume=decomp.cellVolume.get(); double *X=decomp.myX.get(); const double *theta=thetaPtr.get(); double tolerance=1.0e-15; for(size_t p=0;p<num_owned;p++,gids++,volume++,X+=3){ /* * gid an owned 'master' ?? */ double y = *(X+1)/R; if(std::abs(y)<=tolerance){ continue; } /* gid is a slave * Is master owned by ANOTHER processor * NOTE '==' */ size_t j_theta = (*gids)%(nt*nz); size_t master_id = *gids + num_half_sweep - j_theta; if(end==owned_masters.find(master_id)){ /* * we DO NOT own this slave's master; * Therefore we put their GIDs to the 'master' and act like * we don't own them -- use these to create 'overlap' map */ newGIDs[num_master+num_owned_slaves+num_overlap_slaves]=*gids; new_theta[num_master+num_owned_slaves+num_overlap_slaves]=theta[j_theta]; newVolume[num_master+num_owned_slaves+num_overlap_slaves]=*volume; newX[3*(num_master+num_owned_slaves+num_overlap_slaves)+0]=*(X+0); newX[3*(num_master+num_owned_slaves+num_overlap_slaves)+1]=*(X+1); newX[3*(num_master+num_owned_slaves+num_overlap_slaves)+2]=*(X+2); num_overlap_slaves+=1; } } } /* * Fill num_master+num_owned_slave with local_id of master */ Array<int> local_master_ids(num_master+num_owned_slaves); for(size_t m=0;m<num_master+num_owned_slaves;m++){ int gid=newGIDs[m]; int master_local_id=masters_localid_map[gid]; local_master_ids[m]=master_local_id; } size_t num_slave = num_owned_slaves+num_overlap_slaves; // std::stringstream m; // m << "num owned = " << num_owned << "\n"; // m << "num_master = " << num_master << "; num_owned_slaves = " << num_owned_slaves << "; num_overlap_slaves = " << num_overlap_slaves << "\n"; // std::cout << m.str(); if(num_owned!=num_slave+num_master){ std::stringstream s; s << "ERROR: AxisSymmetric2DCylinderMeshGenerator::re_order_data_and_create_wedge_operator\n"; s << "\tCalculation of num_owned and num_slave points inconsistent\n"; s << "\tCannot proceed\n"; throw std::runtime_error(s.str()); std::exit(0); } AxisSymmetricWedgeData wedge_data; wedge_data.numPoints=num_master+num_owned_slaves+num_overlap_slaves; wedge_data.num_master=num_master; wedge_data.num_slave_on_processor_masters=num_owned_slaves; wedge_data.num_slave_off_processor_masters=num_overlap_slaves; wedge_data.myGlobalIDs=newGIDs.get_shared_ptr(); wedge_data.local_master_ids=local_master_ids.get_shared_ptr(); wedge_data.theta=new_theta.get_shared_ptr(); wedge_data.cellVolume=newVolume.get_shared_ptr(); wedge_data.myX=newX.get_shared_ptr(); return wedge_data; } QuickGridData AxisSymmetric2DCylinderMeshGenerator::allocatePdGridData() const { // Number of cells on this processor -- number of cells on last // processor is always <= numCellsPerProc size_t numCellsAllocate = cellsPerProc[getNumProcs()-1]; size_t dimension = 3; return QUICKGRID::allocatePdGridData(numCellsAllocate, dimension); } /** * This function is distinct in that special care must be taken to * properly account for a cylinder */ size_t AxisSymmetric2DCylinderMeshGenerator::computeNumNeighbors(size_t i, size_t j, size_t k) const { // Horizon in each of the coordinate directions Horizon hX = H[0]; // Horizon hY = H[1]; // cylinder uses ringHorizon // RingHorizon::RingHorizonIterator hIter = ringHorizon.horizonIterator(j); // However, in this case, RingHorizon is not needed either because this is a 2D mesh generator Horizon hZ = H[2]; size_t nCx = hX.numCells(i); size_t nCy = 1; size_t nCz = hZ.numCells(k); /* * Number of cells in this (i,j,k) neighborhood * Note that '1' is subtracted to remove "this cell" */ return nCx * nCy * nCz - 1; } size_t AxisSymmetric2DCylinderMeshGenerator::getSizeNeighborList(size_t proc,Cell3D cellLocator) const { Spec1D xSpec = specs[0]; // r // Spec1D ySpec = specs[1]; // theta un-used here Spec1D zSpec = specs[2]; // z size_t nx = xSpec.getNumCells(); size_t ny = 1; size_t nz = zSpec.getNumCells(); /* * Compacted list of neighbors * 1) for i = 0,..(numCells-1) * 2) numCellNeighborhood(i) * 3) neighorhood(i) -- does not include "i" */ // for each cell store numCells + neighborhood // int size = numCells + sum(numCells(i),i); size_t numCells = cellsPerProc[proc]; size_t size=numCells; // Perform sum over all neighborhoods size_t kStart = cellLocator.k; size_t jStart = cellLocator.j; size_t iStart = cellLocator.i; size_t cell = 0; for(size_t k=kStart;k<nz;k++){ // kStart = 0; this one doesn't matter for(size_t j=jStart;j<ny;j++){ jStart=0; // begin at jStart only the first time for(size_t i=iStart;i<nx && cell<numCells;i++,cell++){ // begin at iStart only the first time iStart = 0; size += computeNumNeighbors(i,j,k); } } } return size; } std::pair<Cell3D,QuickGridData> AxisSymmetric2DCylinderMeshGenerator::computePdGridData(size_t proc, Cell3D cellLocator, QuickGridData& pdGridData, NormFunctionPointer norm) const { /** * This routine attempts to make as close of an analogy to CellsPerProcessor3D::computePdGridData(...) * as makes sense: * x <--> r * y <--> theta * z <--> z */ // std::cout << "CellsPerProcessorCylinder::computePdGridData proc = " << proc << std::endl; Spec1D xSpec = specs[0]; // r Spec1D ySpec = specs[1]; // theta Spec1D zSpec = specs[2]; // z size_t nx = xSpec.getNumCells(); size_t ny = 1; size_t nz = zSpec.getNumCells(); // Each cell has the same volume arc size in radians -- // Cells have different volumes bases upon "r" double dr = xSpec.getCellSize(); double dz = zSpec.getCellSize(); double cellRads = ySpec.getCellSize(); double cellVolume; // Horizon in each of the coordinate directions Horizon hX = H[0]; // Horizon hY = H[1]; // un-used here Horizon hZ = H[2]; // Number of cells on this processor size_t myNumCells = cellsPerProc[proc]; // Coordinates used for tensor product space const double*x=rPtr.get(); // const double*y=thetaPtr.get(); // un-used here because theta=0=fixed const double*z=zPtr.get(); // Discretization on this processor pdGridData.dimension = 3; // pdGridData.globalNumPoints = nx*nz; pdGridData.numPoints = myNumCells; int *gidsPtr = pdGridData.myGlobalIDs.get(); double *XPtr = pdGridData.myX.get(); double *volPtr = pdGridData.cellVolume.get(); // allocate neighborhood for incoming data since each one of these has a different length int sizeNeighborhoodList = getSizeNeighborList(proc, cellLocator); pdGridData.sizeNeighborhoodList = sizeNeighborhoodList; Array<int> neighborhoodList(sizeNeighborhoodList); pdGridData.neighborhood = neighborhoodList.get_shared_ptr(); int *neighborPtr = neighborhoodList.get(); int updateSizeNeighborhoodList = 0; // Compute discretization on processor int kStart = cellLocator.k; int jStart = cellLocator.j; int iStart = cellLocator.i; size_t cell = 0; double point[3]={0.0,0.0,0.0}; double pointNeighbor[3] = {0.0,0.0,0.0}; for(size_t k=kStart;k<nz && cell<myNumCells;k++){ // kStart = 0; this one doesn't matter cellLocator.k = k; point[2]=z[k]; size_t zStart = hZ.start(k); size_t nCz = hZ.numCells(k); for(size_t j=jStart;j<ny && cell<myNumCells;j++){ jStart=0; // begin at jStart only the first time cellLocator.j = j; for(size_t i=iStart;i<nx && cell<myNumCells;i++,cell++,cellLocator.i++){ iStart=0; // begin at iStart only the first time // global id *gidsPtr = i + j * nx + k * nx * ny; gidsPtr++; double r = x[i]; point[0] = r; point[1] = 0; // copy point data for(size_t p=0;p<3;p++,XPtr++) *XPtr = point[p]; // copy cell volume cellVolume = r*dr*cellRads*dz; *volPtr = cellVolume; volPtr++; size_t xStart = hX.start(i); size_t nCx = hX.numCells(i); // number of cells in this (i,j,k) neighborhood // Compute neighborhood int *numNeigh = neighborPtr; neighborPtr++; size_t countNeighbors = 0; for(size_t kk=zStart;kk<nCz+zStart;kk++){ for(size_t ii=xStart;ii<nCx+xStart;ii++){ // skip this cell since its its own neighbor if(ii == i && kk == k) continue; // Neighborhood norm calculation double r = x[ii]; pointNeighbor[0] = r; pointNeighbor[1] = 0; pointNeighbor[2] = z[kk]; if(norm(pointNeighbor,point,horizonRadius)){ int globalId = ii + kk * nx; *neighborPtr = globalId; neighborPtr++; countNeighbors++; } } } *numNeigh = countNeighbors; updateSizeNeighborhoodList += countNeighbors; } if(cellLocator.i == nx){ cellLocator.i = 0; if(cell==myNumCells){ // current j holds current last row which needs to be incremented cellLocator.j += 1; if(cellLocator.j == ny){ cellLocator.j = 0; // current k holds current last row which needs to be incremented cellLocator.k += 1; } } } } } // post process and compute neighborhoodPtr pdGridData.sizeNeighborhoodList = updateSizeNeighborhoodList+myNumCells; int *neighPtr = pdGridData.neighborhoodPtr.get(); int *neighborListPtr = neighborhoodList.get(); int sum=0; for(size_t n=0;n<myNumCells;n++){ neighPtr[n]=sum; int numCells = *neighborListPtr; neighborListPtr += (numCells+1); sum += (numCells+1); } return std::pair<Cell3D,QuickGridData>(cellLocator,pdGridData); } TensorProductCylinderMeshGenerator::TensorProductCylinderMeshGenerator ( size_t nProcs, double radiusHorizon, const SpecRing2D& rSpec, const Spec1D& axisSpec, NormFunctionPointer norm ) : QuickGridMeshGenerationIterator(nProcs,norm), horizonRadius(radiusHorizon), globalNumberOfCells(0), ringSpec(rSpec), specs(3,axisSpec), ringHorizon(0,0), H(3,axisSpec.getCellHorizon(radiusHorizon)) { // Number of cells in cylinder globalNumberOfCells = rSpec.getNumCells()*axisSpec.getNumCells(); // Set up tensor product specs // radial direction specs[0] = ringSpec.getRaySpec(); // theta direction specs[1] = ringSpec.getRingSpec(); // cylinder axis -- z direction // already set on initialization //specs[2] = axisSpec; // need to reset ringHorizon; /* * Uses average radius to compute cell size; * If careful attention is given to this everything will be fine. * But for special cases -- such as when size of elements along the * different axes are not approximately the same this may produce * unexpected results although they would be consistent. */ ringHorizon = specs[1].getRingCellHorizon(radiusHorizon,(rSpec.getrI()+rSpec.getr0())/2.0); // Now set up the horizon objects -- note that the ring horizon is special and needs special treatment H[0] = specs[0].getCellHorizon(radiusHorizon); // r H[1] = specs[1].getCellHorizon(radiusHorizon); // theta // H[2] = specs[2].getCellHorizon(radiusHorizon); // z -- this one is already set on initialization // compute cellsPerProc cellsPerProc = QuickGridMeshGenerationIterator::getNumCellsPerProcessor(globalNumberOfCells,nProcs); rPtr = getDiscretization(specs[0]); thetaPtr = getDiscretization(specs[1]); zPtr = getDiscretization(specs[2]); } std::pair<Cell3D,QuickGridData> TensorProductCylinderMeshGenerator::computePdGridData(size_t proc, Cell3D cellLocator, QuickGridData& pdGridData, NormFunctionPointer norm) const { /** * This routine attempts to make as close of an analogy to CellsPerProcessor3D::computePdGridData(...) * as makes sense: * x <--> r * y <--> theta * z <--> z */ // std::cout << "CellsPerProcessorCylinder::computePdGridData proc = " << proc << std::endl; Spec1D xSpec = specs[0]; // r Spec1D ySpec = specs[1]; // theta Spec1D zSpec = specs[2]; // z size_t nx = xSpec.getNumCells(); size_t ny = ySpec.getNumCells(); size_t nz = zSpec.getNumCells(); // Each cell has the same volume arc size in radians -- // Cells have different volumes bases upon "r" double dr = xSpec.getCellSize(); double dz = zSpec.getCellSize(); double cellRads = ySpec.getCellSize(); double cellVolume; // Horizon in each of the coordinate directions Horizon hX = H[0]; // Horizon hY = H[1]; Horizon hZ = H[2]; // Number of cells on this processor size_t myNumCells = cellsPerProc[proc]; // Coordinates used for tensor product space const double*x=rPtr.get(); const double*y=thetaPtr.get(); const double*z=zPtr.get(); // Discretization on this processor pdGridData.dimension = 3; pdGridData.globalNumPoints = nx*ny*nz; pdGridData.numPoints = myNumCells; int *gidsPtr = pdGridData.myGlobalIDs.get(); double *XPtr = pdGridData.myX.get(); double *volPtr = pdGridData.cellVolume.get(); // allocate neighborhood for incoming data since each one of these has a different length int sizeNeighborhoodList = getSizeNeighborList(proc, cellLocator); pdGridData.sizeNeighborhoodList = sizeNeighborhoodList; Array<int> neighborhoodList(sizeNeighborhoodList); pdGridData.neighborhood = neighborhoodList.get_shared_ptr(); int *neighborPtr = neighborhoodList.get(); int updateSizeNeighborhoodList = 0; // Compute discretization on processor size_t kStart = cellLocator.k; size_t jStart = cellLocator.j; size_t iStart = cellLocator.i; size_t cell = 0; double point[3]={0.0,0.0,0.0}; double pointNeighbor[3] = {0.0,0.0,0.0}; for(size_t k=kStart;k<nz && cell<myNumCells;k++){ // kStart = 0; this one doesn't matter cellLocator.k = k; point[2]=z[k]; size_t zStart = hZ.start(k); size_t nCz = hZ.numCells(k); for(size_t j=jStart;j<ny && cell<myNumCells;j++){ jStart=0; // begin at jStart only the first time cellLocator.j = j; double theta = y[j]; double c = cos(theta); double s = sin(theta); for(size_t i=iStart;i<nx && cell<myNumCells;i++,cell++,cellLocator.i++){ iStart=0; // begin at iStart only the first time // global id *gidsPtr = i + j * nx + k * nx * ny; gidsPtr++; double r = x[i]; point[0] = r * c; point[1] = r * s; // copy point data for(size_t p=0;p<3;p++,XPtr++) *XPtr = point[p]; // copy cell volume cellVolume = r*dr*cellRads*dz; *volPtr = cellVolume; volPtr++; size_t xStart = hX.start(i); size_t nCx = hX.numCells(i); // number of cells in this (i,j,k) neighborhood // *neighborPtr = computeNumNeighbors(i,j,k); neighborPtr++; // Compute neighborhood int *numNeigh = neighborPtr; neighborPtr++; size_t countNeighbors = 0; for(size_t kk=zStart;kk<nCz+zStart;kk++){ RingHorizon::RingHorizonIterator yHorizonIter = ringHorizon.horizonIterator(j); while(yHorizonIter.hasNextCell()){ size_t jj = yHorizonIter.nextCell(); for(size_t ii=xStart;ii<nCx+xStart;ii++){ // skip this cell since its its own neighbor if(ii == i && jj == j && kk == k) continue; // Neighborhood norm calculation double r = x[ii]; double theta = y[jj]; double c = cos(theta); double s = sin(theta); pointNeighbor[0] = r * c; pointNeighbor[1] = r * s; pointNeighbor[2] = z[kk]; if(norm(pointNeighbor,point,horizonRadius)){ int globalId = ii + jj * nx + kk * nx * ny; *neighborPtr = globalId; neighborPtr++; countNeighbors++; } } } } *numNeigh = countNeighbors; updateSizeNeighborhoodList += countNeighbors; } if(cellLocator.i == nx){ cellLocator.i = 0; if(cell==myNumCells){ // current j holds current last row which needs to be incremented cellLocator.j += 1; if(cellLocator.j == ny){ cellLocator.j = 0; // current k holds current last row which needs to be incremented cellLocator.k += 1; } } } } } // // post process and compute neighborhoodPtr pdGridData.sizeNeighborhoodList = updateSizeNeighborhoodList+myNumCells; int *neighPtr = pdGridData.neighborhoodPtr.get(); int *neighborListPtr = neighborhoodList.get(); int sum=0; for(size_t n=0;n<myNumCells;n++){ neighPtr[n]=sum; int numCells = *neighborListPtr; neighborListPtr += (numCells+1); sum += (numCells+1); } return std::pair<Cell3D,QuickGridData>(cellLocator,pdGridData); } /** * This function is distinct in that special care must be taken to * properly account for a cylinder */ size_t TensorProductCylinderMeshGenerator::computeNumNeighbors(size_t i, size_t j, size_t k) const { // Horizon in each of the coordinate directions Horizon hX = H[0]; // Horizon hY = H[1]; // cylinder uses ringHorizon RingHorizon::RingHorizonIterator hIter = ringHorizon.horizonIterator(j); Horizon hZ = H[2]; size_t nCx = hX.numCells(i); size_t nCy = hIter.numCells(); size_t nCz = hZ.numCells(k); /* * Number of cells in this (i,j,k) neighborhood * Note that '1' is subtracted to remove "this cell" */ return nCx * nCy * nCz - 1; } size_t TensorProductCylinderMeshGenerator::getSizeNeighborList(size_t proc, Cell3D cellLocator) const { Spec1D xSpec = specs[0]; Spec1D ySpec = specs[1]; Spec1D zSpec = specs[2]; size_t nx = xSpec.getNumCells(); size_t ny = ySpec.getNumCells(); size_t nz = zSpec.getNumCells(); /* * Compacted list of neighbors * 1) for i = 0,..(numCells-1) * 2) numCellNeighborhood(i) * 3) neighorhood(i) -- does not include "i" */ // for each cell store numCells + neighborhood // int size = numCells + sum(numCells(i),i); size_t numCells = cellsPerProc[proc]; size_t size=numCells; // Perform sum over all neighborhoods size_t kStart = cellLocator.k; size_t jStart = cellLocator.j; size_t iStart = cellLocator.i; size_t cell = 0; for(size_t k=kStart;k<nz;k++){ // kStart = 0; this one doesn't matter for(size_t j=jStart;j<ny;j++){ jStart=0; // begin at jStart only the first time for(size_t i=iStart;i<nx && cell<numCells;i++,cell++){ // begin at iStart only the first time iStart = 0; size += computeNumNeighbors(i,j,k); } } } return size; } QuickGridData TensorProductCylinderMeshGenerator::allocatePdGridData() const { // Number of cells on this processor -- number of cells on last // processor is always <= numCellsPerProc size_t numCellsAllocate = cellsPerProc[getNumProcs()-1]; size_t dimension = 3; return QUICKGRID::allocatePdGridData(numCellsAllocate, dimension); } TensorProductSolidCylinder::TensorProductSolidCylinder ( size_t nProcs, double radius, size_t numRings, double zStart, double cylinderLength ) : QuickGridMeshGenerationIterator(nProcs), coreRadius(0), outerRadius(radius), coreCellVolume(0), globalNumberOfCells(0), specs(3,Spec1D(1,0,1)) { /* * Compute inner radius of inner most ring */ double pi = PeridigmNS::value_of_pi(); double R = radius; size_t nR = numRings; double rI = R/nR/sqrt(pi); coreRadius = rI; /* * Create radial spec */ Spec1D raySpec(nR,rI,R-rI); /* * Compute dTheta -- ring secgment size -- attempts to create cells that have * approximately the same area */ double dTheta = 2.0 * sqrt(pi) / ( sqrt(pi) * nR + 1); /* * Create ring spec */ size_t numRays = (int)(2 * pi / dTheta) + 1; Spec1D ringSpec(numRays, 0.0, 2.0*pi); /* * Now get approximate cell size along length of cylinder */ double cellSize = (R-rI)/nR; /* * Now create discretization along axis of cylinder */ size_t numCellsAxis = (size_t)(cylinderLength/cellSize)+1; Spec1D axisSpec(numCellsAxis,zStart,cylinderLength); /* * Compute "coreCellVolume" */ coreCellVolume = pi * coreRadius * coreRadius * axisSpec.getCellSize(); /* * Add in 1 cell for the "core" */ globalNumberOfCells = (numRings * numRays + 1) * numCellsAxis; // cout << "TensorProductSolidCylinder; numRings, numRays, numCellsAxis, globalNumberOfCells = " // << numRings << ", " // << numRays << ", " // << numCellsAxis << ", " // << globalNumberOfCells // << endl; // compute cellsPerProc cellsPerProc = QuickGridMeshGenerationIterator::getNumCellsPerProcessor(globalNumberOfCells,nProcs); // cout << "cellsPerProc.size() = " << cellsPerProc.size() << endl; // for(std::size_t i=0;i<cellsPerProc.size();i++) // cout << "proc, cellsPerProc = " << i << ", " << cellsPerProc[i] << endl; /* * Save specs */ specs[0] = raySpec; specs[1] = ringSpec; specs[2] = axisSpec; rPtr = getDiscretization(specs[0]); thetaPtr = getDiscretization(specs[1]); zPtr = getDiscretization(specs[2]); } QuickGridData TensorProductSolidCylinder::allocatePdGridData() const { // Number of cells on this processor -- number of cells on last // processor is always <= numCellsPerProc size_t numCellsAllocate = cellsPerProc[getNumProcs()-1]; size_t dimension = 3; return QUICKGRID::allocatePdGridData(numCellsAllocate, dimension); } std::pair<Cell3D,QuickGridData> TensorProductSolidCylinder::computePdGridData(size_t proc, Cell3D cellLocator, QuickGridData& pdGridData, NormFunctionPointer norm) const { /** * This routine attempts to make as close of an analogy to CellsPerProcessor3D::computePdGridData(...) * as makes sense: * x <--> r * y <--> theta * z <--> z */ // std::cout << "CellsPerProcessorCylinder::computePdGridData proc = " << proc << std::endl; Spec1D xSpec = specs[0]; // r Spec1D ySpec = specs[1]; // theta Spec1D zSpec = specs[2]; // z size_t nx = xSpec.getNumCells(); size_t ny = ySpec.getNumCells(); size_t nz = zSpec.getNumCells(); // Each cell has the same volume arc size in radians -- // Cells have different volumes bases upon "r" double dr = xSpec.getCellSize(); double dz = zSpec.getCellSize(); double cellRads = ySpec.getCellSize(); double cellVolume; // Number of cells on this processor size_t myNumCells = cellsPerProc[proc]; // Coordinates used for tensor product space const double*x=rPtr.get(); const double*y=thetaPtr.get(); const double*z=zPtr.get(); // Discretization on this processor pdGridData.dimension = 3; size_t numRings = nx; size_t numRays = ny; /* * Note that the number of cells is the tensor product of nx, ny, and nz plus the number of core cells with is nz */ pdGridData.globalNumPoints = numRings*numRays*nz + nz; pdGridData.numPoints = myNumCells; int *gidsPtr = pdGridData.myGlobalIDs.get(); double *XPtr = pdGridData.myX.get(); double *volPtr = pdGridData.cellVolume.get(); // cout << "\tCellsPerProcessorCylinder::computePdGridData; proc, myNumCells = " << proc << ", " << myNumCells << endl; // cout << "CellsPerProcessorCylinder::computePdGridData globalNumPoints = " << pdGridData.globalNumPoints << endl; // Compute discretization on processor size_t kStart = cellLocator.k; size_t jStart = cellLocator.j; size_t iStart = cellLocator.i; size_t cell = 0; double point[3]={0.0,0.0,0.0}; for(size_t k=kStart;k<nz && cell<myNumCells;k++){ // kStart = 0; this one doesn't matter cellLocator.k = k; point[2]=z[k]; /* * We only add the core cell at the start of every x-y plane of points otherwise NOT */ if(0==jStart && 0==iStart){ /* * CORE CELL */ /* * Place core cell at start of cells in x-y disk * NOTE that number of cells in disk = nx * ny + 1 core cell */ *gidsPtr = k * ( nx * ny + 1); gidsPtr++; /* * increment cell counter */ cell++; *volPtr = coreCellVolume; volPtr++; point[0] = 0; point[1] = 0; // copy point data for(int p=0;p<3;p++,XPtr++) *XPtr = point[p]; // cout << "\tproc, core cell gid = " << proc << ", " << k * ( nx * ny + 1) << endl; } for(size_t j=jStart;j<ny && cell<myNumCells;j++){ jStart=0; // begin at jStart only the first time cellLocator.j = j; double theta = y[j]; double c = cos(theta); double s = sin(theta); for(size_t i=iStart;i<nx && cell<myNumCells;i++,cell++,cellLocator.i++){ iStart=0; // begin at iStart only the first time /* * global id: note that global ids start with on offset of "1" to include core cell at start */ *gidsPtr = 1 + i + j * nx + k * ( nx * ny + 1); gidsPtr++; // cout << "\tproc, cell gid = " << proc << ", " << (1 + i + j * nx + k * ( nx * ny + 1)) << endl; double r = x[i]; point[0] = r * c; point[1] = r * s; // copy point data for(int p=0;p<3;p++,XPtr++) *XPtr = point[p]; // copy cell volume cellVolume = r*dr*cellRads*dz; *volPtr = cellVolume; volPtr++; } if(cellLocator.i == nx){ cellLocator.i = 0; if(cell==myNumCells){ // current j holds current last row which needs to be incremented cellLocator.j += 1; if(cellLocator.j == ny){ cellLocator.j = 0; // current k holds current last row which needs to be incremented cellLocator.k += 1; } } } } } /* * Allocate 1 entry for number of neighbors -- note that neighborPtr points to 0 for every point (PdQuickGrid::allocatePdGridData) * and therefore the length of the neighborhood list for every point is zero */ pdGridData.sizeNeighborhoodList=1; Array<int> neighborhoodList(pdGridData.sizeNeighborhoodList); pdGridData.neighborhood = neighborhoodList.get_shared_ptr(); int *neighborhood = neighborhoodList.get(); /* * number of neighbors for every point is zero */ *neighborhood = 0; return std::pair<Cell3D,QuickGridData>(cellLocator,pdGridData); } /** * This function produces an unbalanced discretization although for some geometries it * may not be too bad */ QuickGridData getDiscretization(size_t rank, QuickGridMeshGenerationIterator &cellIter) { MPI_Status status; int ack = 0; int ackTag = 0; int numPointsTag=1; int idsTag = 2; int coordinatesTag = 3; int globalNumPointsTag=4; int sizeNeighborhoodListTag=5; int neighborhoodTag=6; int volumeTag=7; int neighborhoodPtrTag=8; QuickGridData gridData; int dimension = cellIter.getDimension(); if(0 == rank){ QuickGridData pdGridDataProc0 = cellIter.allocatePdGridData(); QuickGridData pdGridDataProcN = cellIter.allocatePdGridData(); std::pair<Cell3D,QuickGridData> p0Data = cellIter.beginIterateProcs(pdGridDataProc0); gridData = p0Data.second; Cell3D nextCellLocator = p0Data.first; while(cellIter.hasNextProc()){ int proc = cellIter.proc(); std::pair<Cell3D,QuickGridData> data = cellIter.nextProc(nextCellLocator,pdGridDataProcN); QuickGridData gridData = data.second; nextCellLocator = data.first; // Need to send this data to proc int globalNumPoints = gridData.globalNumPoints; int numPoints = gridData.numPoints; int sizeNeighborhoodList = gridData.sizeNeighborhoodList; shared_ptr<int> gIds = gridData.myGlobalIDs; shared_ptr<double> X = gridData.myX; shared_ptr<double> V = gridData.cellVolume; shared_ptr<int> neighborhood = gridData.neighborhood; shared_ptr<int> neighborhoodPtr = gridData.neighborhoodPtr; MPI_Send(&numPoints, 1, MPI_INT, proc, numPointsTag, MPI_COMM_WORLD); MPI_Recv(&ack, 1, MPI_INT, proc, ackTag, MPI_COMM_WORLD, &status); MPI_Send(&globalNumPoints, 1, MPI_INT, proc, globalNumPointsTag, MPI_COMM_WORLD); MPI_Send(&sizeNeighborhoodList, 1, MPI_INT, proc, sizeNeighborhoodListTag, MPI_COMM_WORLD); MPI_Send(gIds.get(), numPoints, MPI_INT, proc, idsTag, MPI_COMM_WORLD); MPI_Send(X.get(), dimension*numPoints, MPI_DOUBLE, proc, coordinatesTag, MPI_COMM_WORLD); MPI_Send(V.get(),numPoints, MPI_DOUBLE, proc, volumeTag, MPI_COMM_WORLD); MPI_Send(neighborhood.get(), sizeNeighborhoodList, MPI_INT, proc, neighborhoodTag, MPI_COMM_WORLD); MPI_Send(neighborhoodPtr.get(), numPoints, MPI_INT, proc, neighborhoodPtrTag, MPI_COMM_WORLD); } /* signal all procs it is OK to go on */ ack = 0; for(int proc=1;proc<cellIter.getNumProcs();proc++){ MPI_Send(&ack, 1, MPI_INT, proc, ackTag, MPI_COMM_WORLD); } } else { // Receive data from processor 0 // Create this procs 'GridData' int numPoints=0; int globalNumPoints = 0; int sizeNeighborhoodList = 0; MPI_Recv(&numPoints, 1, MPI_INT, 0, numPointsTag, MPI_COMM_WORLD, &status); ack = 0; if (numPoints > 0){ QuickGridData gData = QUICKGRID::allocatePdGridData(numPoints,dimension); std::shared_ptr<double> g=gData.myX; std::shared_ptr<double> cellVolume=gData.cellVolume; std::shared_ptr<int> gIds=gData.myGlobalIDs; std::shared_ptr<int> neighborhoodPtr=gData.neighborhoodPtr; MPI_Send(&ack, 1, MPI_INT, 0, ackTag, MPI_COMM_WORLD); MPI_Recv(&globalNumPoints, 1, MPI_INT, 0, globalNumPointsTag, MPI_COMM_WORLD, &status); MPI_Recv(&sizeNeighborhoodList, 1, MPI_INT, 0, sizeNeighborhoodListTag, MPI_COMM_WORLD, &status); Array<int> neighborhood(sizeNeighborhoodList); MPI_Recv(gIds.get(), numPoints, MPI_INT, 0, idsTag, MPI_COMM_WORLD, &status); MPI_Recv(g.get(), dimension*numPoints, MPI_DOUBLE, 0, coordinatesTag, MPI_COMM_WORLD, &status); MPI_Recv(cellVolume.get(), numPoints, MPI_DOUBLE, 0,volumeTag, MPI_COMM_WORLD, &status); MPI_Recv(neighborhood.get(), sizeNeighborhoodList, MPI_INT, 0, neighborhoodTag, MPI_COMM_WORLD, &status); MPI_Recv(neighborhoodPtr.get(), numPoints, MPI_INT, 0, neighborhoodPtrTag, MPI_COMM_WORLD, &status); gData.dimension = dimension; gData.globalNumPoints = globalNumPoints; gData.numPoints = numPoints; gData.sizeNeighborhoodList = sizeNeighborhoodList; gData.neighborhood=neighborhood.get_shared_ptr(); gridData = gData; } else if (numPoints == 0){ MPI_Send(&ack, 1, MPI_INT, 0, ackTag, MPI_COMM_WORLD); } else{ MPI_Finalize(); std::exit(1); } MPI_Recv(&ack, 1, MPI_INT, 0, 0, MPI_COMM_WORLD, &status); if (ack < 0){ MPI_Finalize(); std::exit(1); } } return gridData; } }
32.019299
181
0.657869
oldninja
501f5c8d526c8ad541d0e3388d5379bf84b0c33c
13,785
cpp
C++
Nacro/SDK/FN_Feedback_RateExperience_functions.cpp
Milxnor/Nacro
eebabf662bbce6d5af41820ea0342d3567a0aecc
[ "BSD-2-Clause" ]
11
2021-08-08T23:25:10.000Z
2022-02-19T23:07:22.000Z
Nacro/SDK/FN_Feedback_RateExperience_functions.cpp
Milxnor/Nacro
eebabf662bbce6d5af41820ea0342d3567a0aecc
[ "BSD-2-Clause" ]
1
2022-01-01T22:51:59.000Z
2022-01-08T16:14:15.000Z
Nacro/SDK/FN_Feedback_RateExperience_functions.cpp
Milxnor/Nacro
eebabf662bbce6d5af41820ea0342d3567a0aecc
[ "BSD-2-Clause" ]
8
2021-08-09T13:51:54.000Z
2022-01-26T20:33:37.000Z
// Fortnite (1.8) SDK #ifdef _MSC_VER #pragma pack(push, 0x8) #endif #include "../SDK.hpp" namespace SDK { //--------------------------------------------------------------------------- //Functions //--------------------------------------------------------------------------- // Function Feedback_RateExperience.Feedback_RateExperience_C.CreateToolTip // (Public, HasDefaults, BlueprintCallable, BlueprintEvent) // Parameters: // class UWidget* Star_Widget (Parm, ZeroConstructor, IsPlainOldData) // int WidgetIndex (Parm, ZeroConstructor, IsPlainOldData) void UFeedback_RateExperience_C::CreateToolTip(class UWidget* Star_Widget, int WidgetIndex) { static auto fn = UObject::FindObject<UFunction>("Function Feedback_RateExperience.Feedback_RateExperience_C.CreateToolTip"); UFeedback_RateExperience_C_CreateToolTip_Params params; params.Star_Widget = Star_Widget; params.WidgetIndex = WidgetIndex; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function Feedback_RateExperience.Feedback_RateExperience_C.CloseWidget // (Public, BlueprintCallable, BlueprintEvent) void UFeedback_RateExperience_C::CloseWidget() { static auto fn = UObject::FindObject<UFunction>("Function Feedback_RateExperience.Feedback_RateExperience_C.CloseWidget"); UFeedback_RateExperience_C_CloseWidget_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function Feedback_RateExperience.Feedback_RateExperience_C.SendAnalyticsEvent // (Public, HasDefaults, BlueprintCallable, BlueprintEvent) // Parameters: // struct FString FeedbackSentBy (Parm, ZeroConstructor) void UFeedback_RateExperience_C::SendAnalyticsEvent(const struct FString& FeedbackSentBy) { static auto fn = UObject::FindObject<UFunction>("Function Feedback_RateExperience.Feedback_RateExperience_C.SendAnalyticsEvent"); UFeedback_RateExperience_C_SendAnalyticsEvent_Params params; params.FeedbackSentBy = FeedbackSentBy; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function Feedback_RateExperience.Feedback_RateExperience_C.SetupStarButtons // (Public, BlueprintCallable, BlueprintEvent) void UFeedback_RateExperience_C::SetupStarButtons() { static auto fn = UObject::FindObject<UFunction>("Function Feedback_RateExperience.Feedback_RateExperience_C.SetupStarButtons"); UFeedback_RateExperience_C_SetupStarButtons_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function Feedback_RateExperience.Feedback_RateExperience_C.SetStarCount // (Public, BlueprintCallable, BlueprintEvent) // Parameters: // int Star_Count (Parm, ZeroConstructor, IsPlainOldData) void UFeedback_RateExperience_C::SetStarCount(int Star_Count) { static auto fn = UObject::FindObject<UFunction>("Function Feedback_RateExperience.Feedback_RateExperience_C.SetStarCount"); UFeedback_RateExperience_C_SetStarCount_Params params; params.Star_Count = Star_Count; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function Feedback_RateExperience.Feedback_RateExperience_C.Construct // (BlueprintCosmetic, Event, Public, BlueprintEvent) void UFeedback_RateExperience_C::Construct() { static auto fn = UObject::FindObject<UFunction>("Function Feedback_RateExperience.Feedback_RateExperience_C.Construct"); UFeedback_RateExperience_C_Construct_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function Feedback_RateExperience.Feedback_RateExperience_C.BndEvt__CancelButton_K2Node_ComponentBoundEvent_0_CommonButtonClicked__DelegateSignature // (BlueprintEvent) // Parameters: // class UCommonButton* Button (Parm, ZeroConstructor, IsPlainOldData) void UFeedback_RateExperience_C::BndEvt__CancelButton_K2Node_ComponentBoundEvent_0_CommonButtonClicked__DelegateSignature(class UCommonButton* Button) { static auto fn = UObject::FindObject<UFunction>("Function Feedback_RateExperience.Feedback_RateExperience_C.BndEvt__CancelButton_K2Node_ComponentBoundEvent_0_CommonButtonClicked__DelegateSignature"); UFeedback_RateExperience_C_BndEvt__CancelButton_K2Node_ComponentBoundEvent_0_CommonButtonClicked__DelegateSignature_Params params; params.Button = Button; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function Feedback_RateExperience.Feedback_RateExperience_C.BndEvt__SendButton_K2Node_ComponentBoundEvent_1_CommonButtonClicked__DelegateSignature // (BlueprintEvent) // Parameters: // class UCommonButton* Button (Parm, ZeroConstructor, IsPlainOldData) void UFeedback_RateExperience_C::BndEvt__SendButton_K2Node_ComponentBoundEvent_1_CommonButtonClicked__DelegateSignature(class UCommonButton* Button) { static auto fn = UObject::FindObject<UFunction>("Function Feedback_RateExperience.Feedback_RateExperience_C.BndEvt__SendButton_K2Node_ComponentBoundEvent_1_CommonButtonClicked__DelegateSignature"); UFeedback_RateExperience_C_BndEvt__SendButton_K2Node_ComponentBoundEvent_1_CommonButtonClicked__DelegateSignature_Params params; params.Button = Button; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function Feedback_RateExperience.Feedback_RateExperience_C.OnActivated // (Event, Protected, BlueprintEvent) void UFeedback_RateExperience_C::OnActivated() { static auto fn = UObject::FindObject<UFunction>("Function Feedback_RateExperience.Feedback_RateExperience_C.OnActivated"); UFeedback_RateExperience_C_OnActivated_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function Feedback_RateExperience.Feedback_RateExperience_C.BndEvt__5Star_K2Node_ComponentBoundEvent_868_On Mouse Hovered Changed__DelegateSignature // (BlueprintEvent) // Parameters: // bool Is_Hovered (Parm, ZeroConstructor, IsPlainOldData) void UFeedback_RateExperience_C::BndEvt__5Star_K2Node_ComponentBoundEvent_868_On_Mouse_Hovered_Changed__DelegateSignature(bool Is_Hovered) { static auto fn = UObject::FindObject<UFunction>("Function Feedback_RateExperience.Feedback_RateExperience_C.BndEvt__5Star_K2Node_ComponentBoundEvent_868_On Mouse Hovered Changed__DelegateSignature"); UFeedback_RateExperience_C_BndEvt__5Star_K2Node_ComponentBoundEvent_868_On_Mouse_Hovered_Changed__DelegateSignature_Params params; params.Is_Hovered = Is_Hovered; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function Feedback_RateExperience.Feedback_RateExperience_C.BndEvt__4Star_K2Node_ComponentBoundEvent_890_On Mouse Hovered Changed__DelegateSignature // (BlueprintEvent) // Parameters: // bool Is_Hovered (Parm, ZeroConstructor, IsPlainOldData) void UFeedback_RateExperience_C::BndEvt__4Star_K2Node_ComponentBoundEvent_890_On_Mouse_Hovered_Changed__DelegateSignature(bool Is_Hovered) { static auto fn = UObject::FindObject<UFunction>("Function Feedback_RateExperience.Feedback_RateExperience_C.BndEvt__4Star_K2Node_ComponentBoundEvent_890_On Mouse Hovered Changed__DelegateSignature"); UFeedback_RateExperience_C_BndEvt__4Star_K2Node_ComponentBoundEvent_890_On_Mouse_Hovered_Changed__DelegateSignature_Params params; params.Is_Hovered = Is_Hovered; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function Feedback_RateExperience.Feedback_RateExperience_C.BndEvt__3Star_K2Node_ComponentBoundEvent_907_On Mouse Hovered Changed__DelegateSignature // (BlueprintEvent) // Parameters: // bool Is_Hovered (Parm, ZeroConstructor, IsPlainOldData) void UFeedback_RateExperience_C::BndEvt__3Star_K2Node_ComponentBoundEvent_907_On_Mouse_Hovered_Changed__DelegateSignature(bool Is_Hovered) { static auto fn = UObject::FindObject<UFunction>("Function Feedback_RateExperience.Feedback_RateExperience_C.BndEvt__3Star_K2Node_ComponentBoundEvent_907_On Mouse Hovered Changed__DelegateSignature"); UFeedback_RateExperience_C_BndEvt__3Star_K2Node_ComponentBoundEvent_907_On_Mouse_Hovered_Changed__DelegateSignature_Params params; params.Is_Hovered = Is_Hovered; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function Feedback_RateExperience.Feedback_RateExperience_C.BndEvt__2Star_K2Node_ComponentBoundEvent_925_On Mouse Hovered Changed__DelegateSignature // (BlueprintEvent) // Parameters: // bool Is_Hovered (Parm, ZeroConstructor, IsPlainOldData) void UFeedback_RateExperience_C::BndEvt__2Star_K2Node_ComponentBoundEvent_925_On_Mouse_Hovered_Changed__DelegateSignature(bool Is_Hovered) { static auto fn = UObject::FindObject<UFunction>("Function Feedback_RateExperience.Feedback_RateExperience_C.BndEvt__2Star_K2Node_ComponentBoundEvent_925_On Mouse Hovered Changed__DelegateSignature"); UFeedback_RateExperience_C_BndEvt__2Star_K2Node_ComponentBoundEvent_925_On_Mouse_Hovered_Changed__DelegateSignature_Params params; params.Is_Hovered = Is_Hovered; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function Feedback_RateExperience.Feedback_RateExperience_C.BndEvt__1Star_K2Node_ComponentBoundEvent_944_On Mouse Hovered Changed__DelegateSignature // (BlueprintEvent) // Parameters: // bool Is_Hovered (Parm, ZeroConstructor, IsPlainOldData) void UFeedback_RateExperience_C::BndEvt__1Star_K2Node_ComponentBoundEvent_944_On_Mouse_Hovered_Changed__DelegateSignature(bool Is_Hovered) { static auto fn = UObject::FindObject<UFunction>("Function Feedback_RateExperience.Feedback_RateExperience_C.BndEvt__1Star_K2Node_ComponentBoundEvent_944_On Mouse Hovered Changed__DelegateSignature"); UFeedback_RateExperience_C_BndEvt__1Star_K2Node_ComponentBoundEvent_944_On_Mouse_Hovered_Changed__DelegateSignature_Params params; params.Is_Hovered = Is_Hovered; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function Feedback_RateExperience.Feedback_RateExperience_C.OnClientPartyStateChanged // (BlueprintCallable, BlueprintEvent) // Parameters: // EFortPartyState PartyState (Parm, ZeroConstructor, IsPlainOldData) void UFeedback_RateExperience_C::OnClientPartyStateChanged(EFortPartyState PartyState) { static auto fn = UObject::FindObject<UFunction>("Function Feedback_RateExperience.Feedback_RateExperience_C.OnClientPartyStateChanged"); UFeedback_RateExperience_C_OnClientPartyStateChanged_Params params; params.PartyState = PartyState; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function Feedback_RateExperience.Feedback_RateExperience_C.OnStarButtonClicked // (BlueprintCallable, BlueprintEvent) // Parameters: // class UFortBaseButton* Button_Clicked (Parm, ZeroConstructor, IsPlainOldData) void UFeedback_RateExperience_C::OnStarButtonClicked(class UFortBaseButton* Button_Clicked) { static auto fn = UObject::FindObject<UFunction>("Function Feedback_RateExperience.Feedback_RateExperience_C.OnStarButtonClicked"); UFeedback_RateExperience_C_OnStarButtonClicked_Params params; params.Button_Clicked = Button_Clicked; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function Feedback_RateExperience.Feedback_RateExperience_C.OnInputMethodChanged // (BlueprintCallable, BlueprintEvent) // Parameters: // bool bUsingGamepad (Parm, ZeroConstructor, IsPlainOldData) void UFeedback_RateExperience_C::OnInputMethodChanged(bool bUsingGamepad) { static auto fn = UObject::FindObject<UFunction>("Function Feedback_RateExperience.Feedback_RateExperience_C.OnInputMethodChanged"); UFeedback_RateExperience_C_OnInputMethodChanged_Params params; params.bUsingGamepad = bUsingGamepad; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function Feedback_RateExperience.Feedback_RateExperience_C.Destruct // (BlueprintCosmetic, Event, Public, BlueprintEvent) void UFeedback_RateExperience_C::Destruct() { static auto fn = UObject::FindObject<UFunction>("Function Feedback_RateExperience.Feedback_RateExperience_C.Destruct"); UFeedback_RateExperience_C_Destruct_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function Feedback_RateExperience.Feedback_RateExperience_C.ExecuteUbergraph_Feedback_RateExperience // () // Parameters: // int EntryPoint (Parm, ZeroConstructor, IsPlainOldData) void UFeedback_RateExperience_C::ExecuteUbergraph_Feedback_RateExperience(int EntryPoint) { static auto fn = UObject::FindObject<UFunction>("Function Feedback_RateExperience.Feedback_RateExperience_C.ExecuteUbergraph_Feedback_RateExperience"); UFeedback_RateExperience_C_ExecuteUbergraph_Feedback_RateExperience_Params params; params.EntryPoint = EntryPoint; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } } #ifdef _MSC_VER #pragma pack(pop) #endif
35.620155
200
0.796518
Milxnor
5023fef1b19ae04de7e5c6074238da5f964c3e25
3,589
cpp
C++
Graphs/bipartite_ques.cpp
hinduBale/30DayDSAlgoChallenge
86296763a6fbbff84de04e9da4128dae89466ce3
[ "MIT" ]
1
2021-04-04T13:22:37.000Z
2021-04-04T13:22:37.000Z
Graphs/bipartite_ques.cpp
hinduBale/30DayDSAlgoChallenge
86296763a6fbbff84de04e9da4128dae89466ce3
[ "MIT" ]
null
null
null
Graphs/bipartite_ques.cpp
hinduBale/30DayDSAlgoChallenge
86296763a6fbbff84de04e9da4128dae89466ce3
[ "MIT" ]
null
null
null
/* Link to question: https://www.spoj.com/problems/BUGLIFE/ Question: Professor Hopper is researching the sexual behavior of a rare species of bugs. He assumes that they feature two different genders and that they only interact with bugs of the opposite gender. In his experiment, individual bugs and their interactions were easy to identify, because numbers were printed on their backs. Given a list of bug interactions, decide whether the experiment supports his assumption of two genders with no homosexual bugs or if it contains some bug interactions that falsify it. Input The first line of the input contains the number of scenarios. Each scenario starts with one line giving the number of bugs (at least one, and up to 2000) and the number of interactions (up to 1000000) separated by a single space. In the following lines, each interaction is given in the form of two distinct bug numbers separated by a single space. Bugs are numbered consecutively starting from one. Output The output for every scenario is a line containing “Scenario #i:”, where i is the number of the scenario starting at 1, followed by one line saying either “No suspicious bugs found!” if the experiment is consistent with his assumption about the bugs’ sexual behavior, or “Suspicious bugs found!” if Professor Hopper’s assumption is definitely wrong. Sample Input: 2 3 3 1 2 2 3 1 3 4 2 1 2 3 4 Expected Output: Scenario #1: Suspicious bugs found! Scenario #2: No suspicious bugs found! Tip: Whereas it was important to check for bi-partite graph, don't forget the case of disconnected components. Bugs of a disconnected component may lead to suspicion. */ /*short and int: -32,767 to 32,767 **unsigned short int and unsigned int: 0 to 65,535 **long int: -2,147,483,647 to 2,147,483,647 **unsigned long int: 0 to 4,294,967,295 **long long int: -9,223,372,036,854,775,807 to 9,223,372,036,854,775,807 **unsigned long long int: 0 to 18,446,744,073,709,551,615.*/ #pragma optimize('O3') #include <bits/stdc++.h> #define lli long long int #define pii pair<int, int> #define pb push_back #define mp make_pair #define eb emplace_back #define pf push_front #define MOD 1000000007 #define F first #define S second #define inf INT_MAX #define gcd(x,y) __gcd(x,y) #define lcm(a,b) (a*(b/gcd(a,b))) #define i_am_iron_man ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL); using namespace std; vector<vector<lli>> graph; vector<bool> visited; vector<bool> bulb; void addEdge(lli u, lli v) { graph[u].pb(v); graph[v].pb(u); } void dfs(lli node) { visited[node] = true; cout << node << " "; for(lli i: graph[node]) if(!visited[i]) dfs(i); } bool bi_partite_dfs(lli node, bool light) { visited[node] = true; bulb[node] = light; for(lli i: graph[node]) { if(!visited[i]){ if(!bi_partite_dfs(i, !light)){ return false; } } else{ if(bulb[node] == bulb[i]){ return false; } } } return true; } int main() { i_am_iron_man lli test; cin >> test; for(lli t = 1; t <= test; t++) { lli n, e; cin >> n >> e; graph.assign(n, vector<lli>()); visited.assign(n, false); bulb.assign(n, false); while(e--) { lli u, v; cin >> u >> v; addEdge(--u, --v); } lli source = 1; --source; bulb[source] = true; bool res = bi_partite_dfs(source, bulb[source]); for(lli i = 1; i < n; i++){ if(!visited[i]){ res = res & bi_partite_dfs(i, true); } } cout << "Scenario #" << t << ":" << endl; if(res){ cout << "No suspicious bugs found!" << endl; } else { cout << "Suspicious bugs found!" << endl; } } return 0; }
26.984962
399
0.696573
hinduBale
502785fcbdf26c731c54ed2840555ef1d3910b87
1,225
hpp
C++
src/game/sys/sound/sound_comp.hpp
lowkey42/BanishedBlaze
71e66f444a84bea1eca3639de3f3ff1f79e385d1
[ "MIT" ]
null
null
null
src/game/sys/sound/sound_comp.hpp
lowkey42/BanishedBlaze
71e66f444a84bea1eca3639de3f3ff1f79e385d1
[ "MIT" ]
null
null
null
src/game/sys/sound/sound_comp.hpp
lowkey42/BanishedBlaze
71e66f444a84bea1eca3639de3f3ff1f79e385d1
[ "MIT" ]
null
null
null
/** Entities that can play sound effects ************************************* * * * Copyright (c) 2016 Florian Oetke * * This file is distributed under the MIT License * * See LICENSE file for details. * \*****************************************************************************/ #pragma once #include <core/audio/audio_ctx.hpp> #include <core/engine.hpp> #include <core/units.hpp> #include <core/ecs/component.hpp> namespace lux { namespace sys { namespace sound { class Sound_sys; class Sound_comp : public ecs::Component<Sound_comp> { public: static constexpr const char* name() {return "Sound";} Sound_comp(); Sound_comp(ecs::Entity_manager& manager, ecs::Entity_handle owner, audio::Audio_ctx* ctx=nullptr); Sound_comp(Sound_comp&&)noexcept; Sound_comp& operator=(Sound_comp&&)noexcept; ~Sound_comp(); private: friend class Sound_sys; static constexpr auto max_channels = 4; audio::Audio_ctx* _ctx; std::array<audio::Channel_id, max_channels> _channels; }; } } }
27.222222
79
0.528163
lowkey42
5029b126e8fa901b23dd5432a0392c4aecddda76
1,156
cpp
C++
src/Services/StringizeService/ConstStringHolderMemory.cpp
Terryhata6/Mengine
dfe36fdc84d7398fbbbd199feffc46c6f157f1d4
[ "MIT" ]
39
2016-04-21T03:25:26.000Z
2022-01-19T14:16:38.000Z
src/Services/StringizeService/ConstStringHolderMemory.cpp
Terryhata6/Mengine
dfe36fdc84d7398fbbbd199feffc46c6f157f1d4
[ "MIT" ]
23
2016-06-28T13:03:17.000Z
2022-02-02T10:11:54.000Z
src/Services/StringizeService/ConstStringHolderMemory.cpp
Terryhata6/Mengine
dfe36fdc84d7398fbbbd199feffc46c6f157f1d4
[ "MIT" ]
14
2016-06-22T20:45:37.000Z
2021-07-05T12:25:19.000Z
#include "ConstStringHolderMemory.h" #include "Kernel/MemoryAllocator.h" #include "stdex/memorycopy.h" namespace Mengine { ////////////////////////////////////////////////////////////////////////// ConstStringHolderMemory::ConstStringHolderMemory() { } ////////////////////////////////////////////////////////////////////////// ConstStringHolderMemory::~ConstStringHolderMemory() { const value_type * value = this->data(); Helper::deallocateMemory( const_cast<value_type *>(value), "const_string" ); } ////////////////////////////////////////////////////////////////////////// void ConstStringHolderMemory::setValue( const ConstStringHolder::value_type * _value, ConstStringHolder::size_type _size, hash_type _hash ) { ConstStringHolder::value_type * buff = Helper::allocateMemoryNT<ConstStringHolder::value_type>( _size + 1, "const_string" ); stdex::memorycopy( buff, 0, _value, _size ); buff[_size] = '\0'; this->setup( buff, _size, _hash ); } ////////////////////////////////////////////////////////////////////////// }
38.533333
144
0.482699
Terryhata6
df24b20b1e7b4e2edb6c344f2b05f59b5bcaccc6
5,505
cpp
C++
SDL_Guide XX Move A Box/main.cpp
xeek-pro/SDL_Guide
16c9fbff4dd246b73e984ab4149e94ef418e532a
[ "MIT" ]
3
2020-07-13T04:49:27.000Z
2020-07-24T21:27:43.000Z
SDL_Guide XX Move A Box/main.cpp
xeek-pro/sdl_guide
16c9fbff4dd246b73e984ab4149e94ef418e532a
[ "MIT" ]
null
null
null
SDL_Guide XX Move A Box/main.cpp
xeek-pro/sdl_guide
16c9fbff4dd246b73e984ab4149e94ef418e532a
[ "MIT" ]
1
2021-07-13T13:48:18.000Z
2021-07-13T13:48:18.000Z
#include <SDL.h> #include <iostream> #include <sstream> #include <string> #include <stdlib.h> #include <algorithm> #include "SDL_RectEx.h" int main(int argc, char* argv[]) { std::string app_title = "SDL Box Movement Example"; int screen_width = 1024, screen_height = 768; SDL_Window* main_window = NULL; SDL_Renderer* renderer = NULL; SDL_Event event = { 0 }; bool should_quit = false; SDL_RectF box_destination = { }; std::stringstream error; try { // INITIALIZATION: // ----------------------------------------------------------------------------------------------------------------- // Initialize SDL and create a window and renderer if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_EVENTS) < 0) { error << "Failed to initialize SDL: " << SDL_GetError(); throw(error.str()); } if ((main_window = SDL_CreateWindow( std::string(app_title + " - Use the arrow keys!").c_str(), SDL_WINDOWPOS_CENTERED, // Use Centered Top Coordinate SDL_WINDOWPOS_CENTERED, // Use Centered Left Coordinate screen_width, screen_height, // Width & Height 0 // Flags (Window is implicitly shown if SDL_WINDOW_HIDDEN is not set) )) == 0) { error << "Failed to create a window: " << SDL_GetError(); throw(error.str()); } if ((renderer = SDL_CreateRenderer(main_window, -1, 0)) == 0) { error << "Failed to create the renderer: " << SDL_GetError(); throw(error.str()); } // CONFIGURE THE BOX / PLAYER, IT'S INITIAL LOCATION AND SIZE: // ----------------------------------------------------------------------------------------------------------------- // We will primarily keep up with the box coordinates with box_x and box_y as doubles because when the frame-rate is // extremely high, we need the extra precision. box_destination.w = 100.0f; box_destination.h = 100.0f; box_destination.x = screen_width / 2.0f - box_destination.w / 2.0f; box_destination.y = screen_height / 2.0f - box_destination.h / 2.0f; // Setup the initial beforeTime before the game loop starts up... // SDL_GetPerformanceCounter is in a unit of measurement only meaningful to this computer // SDL_GetPerformanceFrequency is a value to divide by to convert the counter to seconds double beforeTime = (double)SDL_GetPerformanceCounter() / SDL_GetPerformanceFrequency(); float speed = 1.0f; /* pixel per millisecond of movement */ // PRIMARY & EVENT LOOP: while (!should_quit) { while (SDL_PollEvent(&event)) { switch (event.type) { case SDL_QUIT: should_quit = 1; break; case SDL_KEYDOWN: switch (event.key.keysym.sym) { case SDLK_ESCAPE: should_quit = 1; break; } break; } } // CALCULATE DELTA TIME: // ----------------------------------------------------------------------------------------------------------------- // Get the current time by querying the performance counter and using the performance frequency to give it meaning // (convert it to miliseconds) double currentTime = (double)SDL_GetPerformanceCounter() / SDL_GetPerformanceFrequency() /* currentTime is tick counter in Seconds */; float deltaTime = static_cast<float>(currentTime - beforeTime) * 1000.0f /* How long it's been since the last frame in Milliseconds */; beforeTime = currentTime; /* Prime beforeTime for the next frame */ // CHECK THE KEYBOARD STATE FOR MOVEMENT KEYS & MOVE THE BOX: // ----------------------------------------------------------------------------------------------------------------- // If you had used events for this instead (SDL_KEYDOWN/UP) you would have onlybeen able to act on one key press at // a time. This also uses min() and max() to keep the box on the screen. The box should not go beyond the boundaries // of the screen. const Uint8* state = SDL_GetKeyboardState(NULL); if (state[SDL_SCANCODE_LEFT]) { box_destination.x = std::max(box_destination.x - speed * deltaTime, 0.0f); } if (state[SDL_SCANCODE_RIGHT]) { box_destination.x = std::min(box_destination.x + speed * deltaTime, screen_width - box_destination.w); } if (state[SDL_SCANCODE_UP]) { box_destination.y = std::max(box_destination.y - speed * deltaTime, 0.0f); } if (state[SDL_SCANCODE_DOWN]) { box_destination.y = std::min(box_destination.y + speed * deltaTime, screen_height - box_destination.h); } // RENDERING: // ----------------------------------------------------------------------------------------------------------------- // Clear the background: SDL_SetRenderDrawColor(renderer, 0, 255, 115, 255); SDL_RenderClear(renderer); // Render the box: SDL_SetRenderDrawColor(renderer, 0, 0, 0, 255); SDL_RenderFillRect(renderer, &((SDL_Rect)box_destination)); // Show on screen: SDL_RenderPresent(renderer); } } catch (std::string error_str) { // This is a simple way to show a message box, if main_window failed to create this will still work // since main_window will be NULL (the message box will just not have a parent): SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, app_title.c_str(), error_str.c_str(), main_window); // Output the error to the console, if you have one std::cout << error_str << std::endl; } // CLEAN-UP & SHUTDOWN: // ----------------------------------------------------------------------------------------------------------------- if (renderer) SDL_DestroyRenderer(renderer); if (main_window) SDL_DestroyWindow(main_window); SDL_Quit(); return 0; }
40.182482
138
0.608174
xeek-pro
df2605f500607ef0a605342dc52c081358b2a97c
722
cpp
C++
jni/application/Item.cpp
clarkdonald/eecs494explore3d
fd4086d2c5482a289d51ef71c5f1ae20347db80a
[ "BSD-2-Clause" ]
null
null
null
jni/application/Item.cpp
clarkdonald/eecs494explore3d
fd4086d2c5482a289d51ef71c5f1ae20347db80a
[ "BSD-2-Clause" ]
null
null
null
jni/application/Item.cpp
clarkdonald/eecs494explore3d
fd4086d2c5482a289d51ef71c5f1ae20347db80a
[ "BSD-2-Clause" ]
null
null
null
// // Item.cpp // game // // Created by Donald Clark on 10/30/13. // // #include "Item.h" #include "Utility.h" using namespace Zeni; using namespace Zeni::Collision; Item::Item(const Point3f &corner_, const Vector3f &scale_, const Quaternion &rotation_) : Game_Object(corner_, scale_, rotation_) {} Item::~Item() {} bool Item::for_fire() const { return false; } bool Item::for_jumping() const { return false; } bool Item::for_lifting() const { return false; } bool Item::for_ghost() const { return false; } void Item::create_body() { body = Capsule(get_corner(), get_corner() + Vector3f(get_scale().x,get_scale().y,0.0f), get_scale().z * 2); }
16.409091
75
0.621884
clarkdonald
df263697f664190ec6cd11844239d5b2799142bb
1,201
hpp
C++
desktop_simple/ebuilds/v1.12.0-noetic/libqicore-1.12.0-noetic/libqicore/qicore/logmanager.hpp
Maelic/ros_overlay_on_gentoo_prefix_32b
a2c9b217d66f4d29b087741e7e7da22ce6f58492
[ "BSD-2-Clause" ]
null
null
null
desktop_simple/ebuilds/v1.12.0-noetic/libqicore-1.12.0-noetic/libqicore/qicore/logmanager.hpp
Maelic/ros_overlay_on_gentoo_prefix_32b
a2c9b217d66f4d29b087741e7e7da22ce6f58492
[ "BSD-2-Clause" ]
null
null
null
desktop_simple/ebuilds/v1.12.0-noetic/libqicore-1.12.0-noetic/libqicore/qicore/logmanager.hpp
Maelic/ros_overlay_on_gentoo_prefix_32b
a2c9b217d66f4d29b087741e7e7da22ce6f58492
[ "BSD-2-Clause" ]
null
null
null
/* ** Author(s): ** - Herve Cuche <hcuche@aldebaran-robotics.com> ** - Matthieu Nottale <mnottale@aldebaran-robotics.com> ** ** Copyright (C) 2013 Aldebaran Robotics */ #ifndef LOGMANAGER_HPP_ #define LOGMANAGER_HPP_ #include <qi/macro.hpp> #include <qicore/api.hpp> #include <qicore/logmessage.hpp> #include <qi/anyobject.hpp> namespace qi { class LogListener; using LogListenerPtr = qi::Object<LogListener>; class LogProvider; using LogProviderPtr = qi::Object<LogProvider>; class QICORE_API LogManager { protected: LogManager() = default; public: virtual ~LogManager() = default; virtual void log(const std::vector<LogMessage>& msgs) = 0; virtual LogListenerPtr createListener() = 0; /** * \deprecated since 2.3 use createListener() instead */ virtual QI_API_DEPRECATED_MSG(Use 'createListener' instead) LogListenerPtr getListener() = 0; virtual int addProvider(LogProviderPtr provider) = 0; virtual void removeProvider(int idProvider) = 0; }; using LogManagerPtr = qi::Object<LogManager>; } // !qi namespace qi { namespace detail { template <> struct QICORE_API ForceProxyInclusion<qi::LogManager> { bool dummyCall(); }; } } #endif // !LOGMANAGER_HPP_
20.706897
95
0.72856
Maelic
df49771f03ecc4b54003974a4397f9641afafb63
604
cpp
C++
tests/reconnect_on_signal.cpp
Yrds/observable
20182bcd721e51d056a7419f4e06f3d2502c68c4
[ "MIT" ]
45
2016-07-07T12:11:18.000Z
2022-02-11T08:24:22.000Z
tests/reconnect_on_signal.cpp
aseprite/observable
8e03c3cb060120b25517503e6c1d9072686d1cd3
[ "MIT" ]
1
2018-08-14T00:35:11.000Z
2018-08-14T23:13:27.000Z
tests/reconnect_on_signal.cpp
aseprite/observable
8e03c3cb060120b25517503e6c1d9072686d1cd3
[ "MIT" ]
13
2016-11-01T16:02:51.000Z
2021-07-14T22:48:57.000Z
// Observable Library // Copyright (c) 2016 David Capello // // This file is released under the terms of the MIT license. // Read LICENSE.txt for more information. #include "obs/signal.h" #include "test.h" obs::signal<void()> sig; obs::scoped_connection conn; void func() { conn = sig.connect(func); // This second connection produced an infinite loop in an old // implementation of iterators where we skipped removed nodes in the // same operator*(). So then the iterator::operator!=() was always // true. conn = sig.connect(func); } int main() { conn = sig.connect(func); sig(); }
22.37037
70
0.690397
Yrds
df51b92829664124a7ba513a939f4e7d6effebb6
295
cpp
C++
Codeforces/1~999/985/A.cpp
tiger0132/code-backup
9cb4ee5e99bf3c274e34f1e59d398ab52e51ecf7
[ "MIT" ]
6
2018-12-30T06:16:54.000Z
2022-03-23T08:03:33.000Z
Codeforces/1~999/985/A.cpp
tiger0132/code-backup
9cb4ee5e99bf3c274e34f1e59d398ab52e51ecf7
[ "MIT" ]
null
null
null
Codeforces/1~999/985/A.cpp
tiger0132/code-backup
9cb4ee5e99bf3c274e34f1e59d398ab52e51ecf7
[ "MIT" ]
null
null
null
#include <algorithm> #include <cstdio> int n, a[111], a1, a2; int main() { scanf("%d", &n), n /= 2; for (int i = 0; i < n; i++) scanf("%d", a + i); std::sort(a, a + n); for (int i = 0; i < n; i++) a1 += abs(2 * i + 1 - a[i]), a2 += abs(2 * i + 2 - a[i]); printf("%d", a1 < a2 ? a1 : a2); }
26.818182
86
0.447458
tiger0132
df552f60e2c9d8a8be9d1a0a9bb191c427ea5ab3
61
hpp
C++
src/boost_fusion_container_generation_make_vector.hpp
miathedev/BoostForArduino
919621dcd0c157094bed4df752b583ba6ea6409e
[ "BSL-1.0" ]
10
2018-03-17T00:58:42.000Z
2021-07-06T02:48:49.000Z
src/boost_fusion_container_generation_make_vector.hpp
miathedev/BoostForArduino
919621dcd0c157094bed4df752b583ba6ea6409e
[ "BSL-1.0" ]
2
2021-03-26T15:17:35.000Z
2021-05-20T23:55:08.000Z
src/boost_fusion_container_generation_make_vector.hpp
miathedev/BoostForArduino
919621dcd0c157094bed4df752b583ba6ea6409e
[ "BSL-1.0" ]
4
2019-05-28T21:06:37.000Z
2021-07-06T03:06:52.000Z
#include <boost/fusion/container/generation/make_vector.hpp>
30.5
60
0.836066
miathedev
df58d9e989d4c1ff39ff5ca925a18e3f7768a188
3,000
hpp
C++
include/arcade/types.hpp
MisterPeModder/Arcade-Interface
316e0ec874a98763cd1bad021814d476360d7ead
[ "MIT" ]
1
2022-03-11T16:04:30.000Z
2022-03-11T16:04:30.000Z
include/arcade/types.hpp
MisterPeModder/Arcade-Interface
316e0ec874a98763cd1bad021814d476360d7ead
[ "MIT" ]
3
2022-03-15T16:34:46.000Z
2022-03-31T19:41:18.000Z
include/arcade/types.hpp
MisterPeModder/Arcade-Interface
316e0ec874a98763cd1bad021814d476360d7ead
[ "MIT" ]
null
null
null
/* ** EPITECH PROJECT, 2022 ** Arcade: Interface ** File description: ** Misc types */ /// @file /// /// Misc types. #ifndef ARCADE_TYPES_HPP_ #define ARCADE_TYPES_HPP_ namespace arcade { /// A 2D vector. template <typename T> struct vec2 { /// x coordinate. T x; /// y coordinate. T y; /// Direct vector casting support. template <typename U> explicit constexpr operator vec2<U>() const { return vec2<U>{static_cast<U>(x), static_cast<U>(y)}; } constexpr vec2<T> operator+() const { return *this; } constexpr vec2<T> operator-() const { return vec2<T>{-x, -y}; } constexpr vec2<T> operator+(T const &v) const { return vec2<T>{x + v, y + v}; } constexpr vec2<T> operator+(vec2<T> const &v) const { return vec2<T>{x + v.x, y + v.y}; } constexpr vec2<T> operator-(T const &v) const { return vec2<T>{x - v, y - v}; } constexpr vec2<T> operator-(vec2<T> const &v) const { return vec2<T>{x - v.x, y - v.y}; } constexpr vec2<T> operator*(T const &v) const { return vec2<T>{x * v, y * v}; } /// Dot product. constexpr T operator*(vec2<T> const &v) const { return x * v.x + y * v.y; } constexpr vec2<T> operator/(T const &v) const { return vec2<T>{x / v, y / v}; } constexpr vec2<T> &operator+=(T const &v) { x += v; y += v; return *this; } constexpr vec2<T> &operator+=(vec2<T> const &v) { x += v.x; y += v.y; return *this; } constexpr vec2<T> &operator-=(T const &v) { x -= v; y -= v; return *this; } constexpr vec2<T> &operator-=(vec2<T> const &v) { x -= v.x; y -= v.y; return *this; } constexpr vec2<T> &operator*=(T const &v) { x *= v; y *= v; return *this; } constexpr vec2<T> &operator/=(T const &v) { x /= v; y /= v; return *this; } constexpr bool operator==(vec2<T> const &v) const { return x == v.x && y == v.y; } constexpr bool operator!=(vec2<T> const &v) const { return x != v.x || y != v.y; } }; /// A 2D vector of unsigned ints. using vec2u = vec2<unsigned int>; /// A 2D vector of ints. using vec2i = vec2<int>; /// A 2D vector of floats. using vec2f = vec2<float>; /// A 2D vector of doubles. using vec2d = vec2<double>; } // namespace arcade #endif // !defined(ARCADE_TYPES_HPP_)
20.979021
73
0.437667
MisterPeModder
df5d34c38359b1f660eb1efcce8a835d88584a70
5,889
cpp
C++
src/widget/menu.cpp
RyanDraves/CPPurses
19cbdae2d18e702144659187ec989c486c714a0f
[ "MIT" ]
null
null
null
src/widget/menu.cpp
RyanDraves/CPPurses
19cbdae2d18e702144659187ec989c486c714a0f
[ "MIT" ]
null
null
null
src/widget/menu.cpp
RyanDraves/CPPurses
19cbdae2d18e702144659187ec989c486c714a0f
[ "MIT" ]
null
null
null
#include <cppurses/widget/widgets/menu.hpp> #include <cstddef> #include <cstdint> #include <iterator> #include <string> #include <utility> #include <signals/signals.hpp> #include <cppurses/painter/attribute.hpp> #include <cppurses/painter/glyph_string.hpp> #include <cppurses/painter/painter.hpp> #include <cppurses/system/events/key.hpp> #include <cppurses/system/events/mouse.hpp> #include <cppurses/widget/focus_policy.hpp> #include <cppurses/widget/widget.hpp> #include <cppurses/widget/widgets/label.hpp> #include <cppurses/widget/widgets/push_button.hpp> namespace cppurses { Menu::Menu(Glyph_string title_text) : title{this->make_child<Label>(std::move(title_text))} { this->focus_policy = Focus_policy::Strong; title.set_alignment(Alignment::Center); title.brush.add_attributes(Attribute::Bold); line_break.wallpaper = L'─'; } sig::Signal<void()>& Menu::append_item(Glyph_string label) { return this->insert_item(std::move(label), this->size()); } sig::Signal<void()>& Menu::insert_item(Glyph_string label, std::size_t index) { auto button_ptr = std::make_unique<Push_button>(std::move(label)); Push_button& new_button = *button_ptr; this->children.insert(std::move(button_ptr), index + 2); items_.emplace(std::begin(items_) + index, new_button); new_button.install_event_filter(*this); new_button.height_policy.fixed(1); if (items_.size() == 1) { this->select_item(0); } new_button.clicked.connect([this, index] { this->select_item(index); this->send_selected_signal(); }); return items_[index].selected; } void Menu::remove_item(std::size_t index) { if (index >= items_.size()) { return; } items_[index].button.get().close(); items_.erase(std::begin(items_) + index); if (index == selected_index_) { this->select_item(0); } } void Menu::select_up(std::size_t n) { const auto new_index = selected_index_ > n ? selected_index_ - n : 0; this->select_item(new_index); } void Menu::select_down(std::size_t n) { this->select_item(selected_index_ + n); } void Menu::select_item(std::size_t index) { if (items_.empty()) { return; } auto& previous_btn = items_[selected_index_].button.get(); previous_btn.brush.remove_attributes(selected_attr_); previous_btn.update(); selected_index_ = index >= items_.size() ? items_.size() - 1 : index; auto& current_btn = items_[selected_index_].button.get(); current_btn.brush.add_attributes(selected_attr_); current_btn.update(); } void Menu::set_selected_attribute(const Attribute& attr) { auto& selected_btn = items_[selected_index_].button.get(); selected_btn.brush.remove_attributes(selected_attr_); selected_attr_ = attr; selected_btn.brush.add_attributes(selected_attr_); selected_btn.update(); } void Menu::hide_title() { title_enabled_ = false; this->enable(this->enabled()); } void Menu::show_title() { title_enabled_ = true; this->enable(this->enabled()); } void Menu::hide_line_break() { line_break_enabled_ = false; this->enable(this->enabled()); } void Menu::show_line_break() { line_break_enabled_ = true; this->enable(this->enabled()); } void Menu::enable(bool enable, bool post_child_polished_event) { this->enable_and_post_events(enable, post_child_polished_event); line_break.enable(line_break_enabled_ && enable, post_child_polished_event); title.enable(title_enabled_ && enable, post_child_polished_event); for (Menu_item& item : items_) { item.button.get().enable(enable, post_child_polished_event); } } bool Menu::key_press_event(const Key::State& keyboard) { if (keyboard.key == Key::Arrow_down || keyboard.key == Key::j) { this->select_down(); } else if (keyboard.key == Key::Arrow_up || keyboard.key == Key::k) { this->select_up(); } else if (keyboard.key == Key::Enter) { this->send_selected_signal(); } return true; } bool Menu::mouse_press_event(const Mouse::State& mouse) { if (mouse.button == Mouse::Button::ScrollUp) { this->select_up(); } else if (mouse.button == Mouse::Button::ScrollDown) { this->select_down(); } return layout::Vertical::mouse_press_event(mouse); } bool Menu::mouse_press_event_filter(Widget& /* receiver */, const Mouse::State& mouse) { if (mouse.button == Mouse::Button::ScrollUp) { this->select_up(); return true; } else if (mouse.button == Mouse::Button::ScrollDown) { this->select_down(); return true; } return false; } void Menu::send_selected_signal() { if (!items_.empty()) { items_[selected_index_].selected(); } } namespace slot { sig::Slot<void(std::size_t)> select_up(Menu& m) { sig::Slot<void(std::size_t)> slot{[&m](auto n) { m.select_up(n); }}; slot.track(m.destroyed); return slot; } sig::Slot<void()> select_up(Menu& m, std::size_t n) { sig::Slot<void()> slot{[&m, n] { m.select_up(n); }}; slot.track(m.destroyed); return slot; } sig::Slot<void(std::size_t)> select_down(Menu& m) { sig::Slot<void(std::size_t)> slot{[&m](auto n) { m.select_down(n); }}; slot.track(m.destroyed); return slot; } sig::Slot<void()> select_down(Menu& m, std::size_t n) { sig::Slot<void()> slot{[&m, n] { m.select_down(n); }}; slot.track(m.destroyed); return slot; } sig::Slot<void(std::size_t)> select_item(Menu& m) { sig::Slot<void(std::size_t)> slot{ [&m](auto index) { m.select_item(index); }}; slot.track(m.destroyed); return slot; } sig::Slot<void()> select_item(Menu& m, std::size_t index) { sig::Slot<void()> slot{[&m, index] { m.select_item(index); }}; slot.track(m.destroyed); return slot; } } // namespace slot } // namespace cppurses
29.009852
80
0.661572
RyanDraves
df5df3daab4989624d4b62d0c164d5c7b3c57da8
1,485
cpp
C++
gazebo_test_tools/src/spawn_cubes_unity.cpp
karthikm-0/gazebo-pkgs
14f5966cddac35b59501ff3ee378e0cba650d3fb
[ "BSD-3-Clause" ]
null
null
null
gazebo_test_tools/src/spawn_cubes_unity.cpp
karthikm-0/gazebo-pkgs
14f5966cddac35b59501ff3ee378e0cba650d3fb
[ "BSD-3-Clause" ]
null
null
null
gazebo_test_tools/src/spawn_cubes_unity.cpp
karthikm-0/gazebo-pkgs
14f5966cddac35b59501ff3ee378e0cba650d3fb
[ "BSD-3-Clause" ]
null
null
null
#include <gazebo_test_tools/gazebo_cube_spawner.h> #include <gazebo_test_tools/FakeObjectRecognizer.h> #include <gazebo_test_tools/SpawnCubesUnity.h> float dim = 0.05; float mass = 0.05; std::string frame_id = "world"; // Used to request cubes to be spawned through a cube_spawner service provided by Jennifer Buehler's repos bool spawn(gazebo_test_tools::SpawnCubesUnity::Request &req, gazebo_test_tools::SpawnCubesUnity::Response &res) { // Spawn the cube first ros::NodeHandle n; gazebo_test_tools::GazeboCubeSpawner spawner(n); spawner.spawnCube(req.name, "world", req.x, req.y, req.z, 0, 0, 0, 1, dim, dim, dim, mass); res.success = true; // Recognize the cube for MoveIt ros::ServiceClient client = n.serviceClient<gazebo_test_tools::RecognizeGazeboObject>("gazebo_test_tools/recognize_object"); gazebo_test_tools::RecognizeGazeboObject srv; srv.request.name = req.name; srv.request.republish = 1; if (client.call(srv)) { ROS_INFO("Result: "); std::cout<<srv.response<<std::endl; return true; } else { ROS_INFO("Failed to recognize object."); return false; } } int main(int argc, char **argv) { ros::init(argc, argv, "spawn_cubes_unity_server"); ros::NodeHandle n; // Advertise a service ros::ServiceServer service = n.advertiseService("spawn_cubes_unity_srv", spawn); ROS_INFO("Ready to spawn cubes"); ros::spin(); return 0; }
27.5
128
0.686869
karthikm-0
df608a16c05eec2080c7b18342b20acbaeeab262
849
cpp
C++
src/Exceptions.cpp
marcosivni/dicomlib
dd268d07368ff4f1ffd1f94cdaa1e2dbf30bc5c7
[ "BSD-3-Clause" ]
null
null
null
src/Exceptions.cpp
marcosivni/dicomlib
dd268d07368ff4f1ffd1f94cdaa1e2dbf30bc5c7
[ "BSD-3-Clause" ]
null
null
null
src/Exceptions.cpp
marcosivni/dicomlib
dd268d07368ff4f1ffd1f94cdaa1e2dbf30bc5c7
[ "BSD-3-Clause" ]
null
null
null
/************************************************************************ * DICOMLIB * Copyright 2003 Sunnybrook and Women's College Health Science Center * Implemented by Trevor Morgan (morgan@sten.sunnybrook.utoronto.ca) * * See LICENSE.txt for copyright and licensing info. *************************************************************************/ //Implementation of exception classes. #include "Exceptions.hpp" #include <sstream> #include <iostream> using namespace std; namespace dicom { exception::exception(std::string What) : What_(What) { } const char* exception::what() const throw() { return What_.c_str(); } /*! Simplified from http://www.cuj.com/documents/s=8250/cujcexp2106alexandr/alexandr.htm */ void Enforce(bool Condition,std::string Comment) { if(!Condition) throw dicom::exception(Comment); } }
22.342105
86
0.600707
marcosivni
df64eca128a21b76db80a47157a3c8144567bd50
971
hxx
C++
include/kinggame/Player.hxx
Zaechus/thekinggame
2a2dd1749f7c770a1c1c7f150fe6d8f1e69c6946
[ "MIT" ]
2
2018-04-15T23:13:18.000Z
2018-04-19T11:02:21.000Z
include/kinggame/Player.hxx
LuckyChucky/kinggame
6a5c89d70901645975af7f9fa5ee0c466a64b41b
[ "MIT" ]
null
null
null
include/kinggame/Player.hxx
LuckyChucky/kinggame
6a5c89d70901645975af7f9fa5ee0c466a64b41b
[ "MIT" ]
2
2018-04-23T00:05:28.000Z
2018-09-02T21:51:30.000Z
// include/kinggame/Player.hxx // // Maxwell Anderson 2018 #ifndef THEKINGGAME_INCLUDE_KINGGAME_PLAYER_HXX_ #define THEKINGGAME_INCLUDE_KINGGAME_PLAYER_HXX_ #include <map> #include <string> #include "Obj.hxx" #include "Room.hxx" #include "World.hxx" namespace kinggame { class World; class Player { public: Player(); explicit Player(std::string); void set_world(World *); inline int hp(); std::string name(); void set_name(std::string); void action(std::string); void action(std::string, std::string); void action(std::string, std::string, std::string, std::string); void look(); void print_inventory(); void move(std::string); void take(std::string); void drop(std::string); bool has_obj(std::string); private: World *world_; Room *curr_room_; std::string name_; int hp_; int gold_; std::map<std::string, std::unique_ptr<Obj>> inventory_; }; } // namespace kinggame #endif // THEKINGGAME_INCLUDE_KINGGAME_PLAYER_HXX_
19.039216
66
0.710608
Zaechus
df689544c12a535686b9c9f51cdc368e57d92253
1,298
hpp
C++
libraries/plugins/apis/block_api/include/morphene/plugins/block_api/block_api_objects.hpp
morphene/morphene
5620f9a8473690ff63e67b7b242a202d05f7ee86
[ "MIT" ]
4
2019-05-16T20:10:54.000Z
2019-05-27T22:41:14.000Z
libraries/plugins/apis/block_api/include/morphene/plugins/block_api/block_api_objects.hpp
morphene/morphene
5620f9a8473690ff63e67b7b242a202d05f7ee86
[ "MIT" ]
null
null
null
libraries/plugins/apis/block_api/include/morphene/plugins/block_api/block_api_objects.hpp
morphene/morphene
5620f9a8473690ff63e67b7b242a202d05f7ee86
[ "MIT" ]
null
null
null
#pragma once #include <morphene/chain/account_object.hpp> #include <morphene/chain/block_summary_object.hpp> #include <morphene/chain/global_property_object.hpp> #include <morphene/chain/history_object.hpp> #include <morphene/chain/morphene_objects.hpp> #include <morphene/chain/transaction_object.hpp> #include <morphene/chain/witness_objects.hpp> #include <morphene/chain/database.hpp> namespace morphene { namespace plugins { namespace block_api { using namespace morphene::chain; struct api_signed_block_object : public signed_block { api_signed_block_object( const signed_block& block ) : signed_block( block ) { block_id = id(); signing_key = signee(); transaction_ids.reserve( transactions.size() ); for( const signed_transaction& tx : transactions ) transaction_ids.push_back( tx.id() ); } api_signed_block_object() {} block_id_type block_id; public_key_type signing_key; vector< transaction_id_type > transaction_ids; }; } } } // morphene::plugins::database_api FC_REFLECT_DERIVED( morphene::plugins::block_api::api_signed_block_object, (morphene::protocol::signed_block), (block_id) (signing_key) (transaction_ids) )
33.282051
110
0.697227
morphene
df6c1484e866f38f78c718766f6ffc7938f05a1f
37
cpp
C++
Defines.cpp
dlsocool/dcx
3d209d27cbd719f1d6c6d125b6f935ecaa79094c
[ "BSD-3-Clause" ]
18
2015-02-21T05:41:19.000Z
2022-02-26T00:48:31.000Z
Defines.cpp
dlsocool/dcx
3d209d27cbd719f1d6c6d125b6f935ecaa79094c
[ "BSD-3-Clause" ]
68
2015-04-06T16:23:35.000Z
2022-03-09T17:33:50.000Z
Defines.cpp
dlsocool/dcx
3d209d27cbd719f1d6c6d125b6f935ecaa79094c
[ "BSD-3-Clause" ]
2
2018-04-01T09:39:33.000Z
2018-08-04T23:53:29.000Z
#include "defines.h" /* EOF */
7.4
21
0.486486
dlsocool
df71f82e1b480dbda71965ff96401214791386b2
14,850
cpp
C++
src/games/hexon/HexBlocks_Hexon_Utils.cpp
Press-Play-On-Tape/TheHex
ad2876e1de0d09dbe8123201ecc88bcd4a0d7c5c
[ "BSD-3-Clause" ]
1
2021-07-05T15:55:59.000Z
2021-07-05T15:55:59.000Z
src/games/hexon/HexBlocks_Hexon_Utils.cpp
Press-Play-On-Tape/TheHex
ad2876e1de0d09dbe8123201ecc88bcd4a0d7c5c
[ "BSD-3-Clause" ]
null
null
null
src/games/hexon/HexBlocks_Hexon_Utils.cpp
Press-Play-On-Tape/TheHex
ad2876e1de0d09dbe8123201ecc88bcd4a0d7c5c
[ "BSD-3-Clause" ]
null
null
null
#include "../../HexBlocks.h" using PC = Pokitto::Core; using PD = Pokitto::Display; #include "../../utils/Constants.h" #include "../../sounds/Sounds.h" bool Game::isValidMovement_Hexon(SelectedShape &selectedShape) { return isValidMovement_Hexon(selectedShape, this->gamePlayVariables.x, this->gamePlayVariables.y); } bool Game::isValidMovement_Hexon(SelectedShape &selectedShape, const int16_t xPlacement, const uint16_t yPlacement) { if (yPlacement + selectedShape.getHeight() > Constants::GridSize) return false; // Hanging over the left .. for (uint8_t y = 0; y < selectedShape.getHeight(); y++) { if (y == 0) { if (selectedShape.isUpperLeftCellBlank()) { if (xPlacement < Constants::Cell_Min_X[yPlacement + y] - 1) { return false; } } else { if (xPlacement < Constants::Cell_Min_X[yPlacement + y]) return false; } } else if (y == selectedShape.getHeight() - 1) { if (selectedShape.isLowerLeftCellBlank()) { if (xPlacement < Constants::Cell_Min_X[yPlacement + y] - 1) return false; } else { if (y % 2 == 0) { if (xPlacement <= Constants::Cell_Min_X[yPlacement + y] - 1) return false; } else { if (xPlacement < Constants::Cell_Min_X[yPlacement + y] + ((yPlacement+ y) % 2 == 0 ? -1 : 0)) return false; } } } } // Hanging over the right .. for (uint8_t y = 0; y < selectedShape.getHeight(); y++) { if (y == 0) { if (selectedShape.isUpperRightCellBlank()) { if (xPlacement + selectedShape.getWidth() - 2 > Constants::Cell_Max_X[yPlacement + y]) return false; } else { if (xPlacement + selectedShape.getWidth() - 1 > Constants::Cell_Max_X[yPlacement + y]) return false; } } else if (y == selectedShape.getHeight() - 1) { if (selectedShape.isLowerRightCellBlank()) { if (xPlacement + selectedShape.getWidth() - 2 > Constants::Cell_Max_X[yPlacement + y]) return false; } else { if (y % 2 == 0) { if (xPlacement + selectedShape.getWidth() - 1 > Constants::Cell_Max_X[yPlacement + y]) return false; } else { if (xPlacement + selectedShape.getWidth() - 1 > Constants::Cell_Max_X[yPlacement + y] + ((yPlacement+ y) % 2 == 0 ? -1 : 0)) return false; } } } } return true; } bool Game::isValidPlacement_Hexon(SelectedShape &selectedShape) { return this->isValidPlacement_Hexon(selectedShape, this->gamePlayVariables.x, this->gamePlayVariables.y); } bool Game::isValidPlacement_Hexon(SelectedShape &selectedShape, const uint8_t xPlacement, const uint8_t yPlacement) { for (int8_t y = 0; y < selectedShape.getHeight(); y++) { for (int8_t x = 0; x < selectedShape.getWidth(); x++) { int8_t xPos = xPlacement + x + (((yPlacement % 2 == 1) && ((yPlacement + y) % 2) == 0) ? 1 : 0); int8_t yPos = (yPlacement + y); if (selectedShape.getCell(x, y) != 0 && xPos < 0 || xPos > 8 || yPos < 0 || yPos > 8) { return false; } if (selectedShape.getCell(x, y) != 0 && this->gamePlayVariables.board[xPos][yPos] != 0) { return false; } } } return true; } void Game::placeShape_Hexon() { this->mode = Mode::ShapeSelection; this->shapes[this->selectedShape.getSelectedIndex()].setIndex(0); for (uint8_t y = 0; y < this->selectedShape.getHeight(); y++) { for (uint8_t x = 0; x < this->selectedShape.getWidth(); x++) { if (this->selectedShape.getCell(x, y) != 0) { uint8_t xPos = this->gamePlayVariables.x + x + ((this->gamePlayVariables.y % 2 == 1) && (y % 2 == 1) ? 1 : 0); this->gamePlayVariables.board[xPos][this->gamePlayVariables.y + y] = this->selectedShape.getCell(x, y); } } } // Shuffle shpaes up .. for (uint8_t i = 0; i < Constants::Hexon::noOfSideShapes - 1; i++) { if (this->shapes[i].getIndex() == 0) { for (uint8_t j = i; j < Constants::Hexon::noOfSideShapes - 1; j++) { this->shapes[j].setIndex(this->shapes[j + 1].getIndex()); this->shapes[j].setColor(this->shapes[j + 1].getColor()); this->shapes[j].setMinRange(this->shapes[j + 1].getMinRange()); this->shapes[j].setMaxRange(this->shapes[j + 1].getMaxRange()); } this->shapes[Constants::Hexon::noOfSideShapes - 1].setIndex(0); } } // Reset selected item index .. for (uint8_t i = 0; i < Constants::Hexon::noOfSideShapes; i++) { if (this->shapes[i].getIndex() != 0) { this->selectedShape.setSelectedIndex(i); this->selectedShape.setShape(this->shapes[i]); return; } } // No shapes left, get random items .. this->populateShapes_Hexon(); } void Game::populateShapes_Hexon() { uint8_t minColor = 0; uint8_t maxColor = 0; switch (this->gamePlayVariables.score) { case 0 ... 50: minColor = 3; maxColor = 7; break; case 51 ... 100: minColor = 2; maxColor = 7; break; case 101 ... 250: minColor = 1; maxColor = 7; break; default: minColor = 1; maxColor = 7; break; } for (uint8_t i = 0; i < Constants::Hexon::noOfSideShapes; i++) { uint8_t rndShape = random(1, Shapes::Count); uint8_t index = Shapes::ShapeIndexes[rndShape]; this->shapes[i].setIndex(index); this->shapes[i].setColor(random(minColor, maxColor)); this->shapes[i].setMinRange(Shapes::RotMin[index]); this->shapes[i].setMaxRange(Shapes::RotMax[index]); } this->selectedShape.setSelectedIndex(0); this->selectedShape.setShape(this->shapes[0]); } void Game::removeWinningLines_Hexon() { uint8_t winningLines = 0; // Horizontal lines .. for (uint8_t y = 0; y < Constants::GridSize; y++) { for (uint8_t l = 9; l >= 4; l--) { if (l > Constants::Cell_Count[y]) { continue; } else { int8_t color = 0; int8_t count = 0; for (uint8_t range = Constants::Cell_Min_X[y]; range < Constants::Cell_Max_X[y]; range++) { for (uint8_t startingPos = range; startingPos <= Constants::Cell_Max_X[y]; startingPos++) { if (startingPos == range) { color = abs(this->gamePlayVariables.board[startingPos][y]); if (color == 0) { break; } else { count = 1; } } else if (abs(this->gamePlayVariables.board[startingPos][y]) == color) { count++; if (count == l) { this->gamePlayVariables.scoreToAdd = this->gamePlayVariables.scoreToAdd + Constants::Hexon::Scores[l]; winningLines = winningLines + 1; for (uint8_t fill = range; fill < range + l; fill++) { this->gamePlayVariables.board[fill][y] = -abs(this->gamePlayVariables.board[fill][y]); } break; } } else { break; } } } } } } // Slash / for (uint8_t d = 0; d < Constants::GridSize; d++) { for (uint8_t l = Constants::GridSize; l >= 4; l--) { if (l > Constants::Cell_Count[d]) { continue; } else { int8_t color = 0; int8_t count = 0; for (uint8_t range = Constants::Cell_Min_X[d]; range < Constants::Cell_Max_X[d]; range++) { for (uint8_t startingPos = range; startingPos <= Constants::Cell_Max_X[d]; startingPos++) { if (startingPos == range) { color = abs(this->getCellSlash_Hexon(startingPos, d)); if (color == 0) { break; } else { count = 1; } } else if (abs(this->getCellSlash_Hexon(startingPos, d)) == color) { count++; if (count == l) { this->gamePlayVariables.scoreToAdd = this->gamePlayVariables.scoreToAdd + Constants::Hexon::Scores[l]; winningLines = winningLines + 1; for (uint8_t fill = range; fill < range + l; fill++) { this->setCellSlash_Hexon(fill, d, -abs(this->getCellSlash_Hexon(fill, d))); } break; } } else { break; } } } } } } // Backslash top left,bottom for (uint8_t d = 0; d < Constants::GridSize; d++) { for (uint8_t l = 9; l >= 4; l--) { if (l > Constants::Cell_Count[d]) { continue; } else { int8_t color = 0; int8_t count = 0; for (uint8_t range = Constants::Cell_Min_X[d]; range < Constants::Cell_Max_X[d]; range++) { for (uint8_t startingPos = range; startingPos <= Constants::Cell_Max_X[d]; startingPos++) { if (startingPos == range) { color = abs(this->getCellBackslash_Hexon(startingPos, d)); if (color == 0) { break; } else { count = 1; } } else if (abs(this->getCellBackslash_Hexon(startingPos, d)) == color) { count++; if (count == l) { this->gamePlayVariables.scoreToAdd = this->gamePlayVariables.scoreToAdd + Constants::Hexon::Scores[l]; winningLines = winningLines + 1; for (uint8_t fill = range; fill < range + l; fill++) { this->setCellBackslash_Hexon(fill, d, -abs(this->getCellBackslash_Hexon(fill, d))); } break; } } else { break; } } } } } } // launch particles .. for (uint8_t y = 0; y < Constants::GridSize; y++) { for (uint8_t x = 0; x < Constants::GridSize; x++) { for (uint8_t x = 0; x < Constants::GridSize; x++) { if (this->gamePlayVariables.board[x][y] < 0) { for (uint8_t i = 0; i < 15; i++) { uint8_t xCentre = 0; uint8_t yCentre = 0; this->getCentreOfTile_Common(x, y, xCentre, yCentre); this->launchParticles(xCentre, yCentre, ExplosionSize::Medium); this->gamePlayVariables.board[x][y] = 0; } } } } } // Play sounds .. switch (winningLines) { case 1: this->playSoundEffect(SoundTheme::Bubble1); break; case 2: this->playSoundEffect(SoundTheme::LevelUp1); break; case 3 ... 10: this->playSoundEffect(SoundTheme::LevelUp2); break; } } int8_t Game::getCellSlash_Hexon(const uint8_t x, const uint8_t d) { uint8_t xLoc = Constants::Hexon::slash_X[(d * 9) + x]; uint8_t yLoc = Constants::Hexon::slash_Y[(d * 9) + x]; return this->gamePlayVariables.board[xLoc][yLoc]; } void Game::setCellSlash_Hexon(const uint8_t x, const uint8_t d, const int8_t val) { uint8_t xLoc = Constants::Hexon::slash_X[(d * 9) + x]; uint8_t yLoc = Constants::Hexon::slash_Y[(d * 9) + x]; this->gamePlayVariables.board[xLoc][yLoc] = val; } int8_t Game::getCellBackslash_Hexon(const uint8_t x, const uint8_t d) { uint8_t xLoc = Constants::Hexon::backslash_X[(d * 9) + x]; uint8_t yLoc = Constants::Hexon::backslash_Y[(d * 9) + x]; return this->gamePlayVariables.board[xLoc][yLoc]; } void Game::setCellBackslash_Hexon(const uint8_t x, const uint8_t d, const int8_t val) { uint8_t xLoc = Constants::Hexon::backslash_X[(d * 9) + x]; uint8_t yLoc = Constants::Hexon::backslash_Y[(d * 9) + x]; this->gamePlayVariables.board[xLoc][yLoc] = val; } bool Game::isValidMoveAvailable_Hexon() { bool cont = false; for (uint8_t i = 0; i < Constants::Hexon::noOfSideShapes; i++) { if (this->shapes[i].getIndex() != 0) { SelectableShape shape = shapes[i]; shape.setIndex(shape.getMinRange()); for (uint8_t rot = shape.getMinRange(); rot <= shape.getMaxRange(); rot++) { SelectedShape selectedShape; selectedShape.setShape(shape); for (uint8_t y = 0; y <= 9; y++) { for (uint8_t x = 0; x <= 9; x++) { if (this->isValidPlacement_Hexon(selectedShape, x, y)) return true; } } shape.rotate(); } } } return false; }
24.50495
158
0.46303
Press-Play-On-Tape
df7e7b4824394733be5bed1bbf27832bb315434a
698
cpp
C++
example-midi.cpp
gsliepen/modsynth
38ef0cbdf7d5a61b682df8ce73ae5edb8adc40de
[ "MIT" ]
1
2021-01-11T02:02:19.000Z
2021-01-11T02:02:19.000Z
example-midi.cpp
gsliepen/modsynth
38ef0cbdf7d5a61b682df8ce73ae5edb8adc40de
[ "MIT" ]
null
null
null
example-midi.cpp
gsliepen/modsynth
38ef0cbdf7d5a61b682df8ce73ae5edb8adc40de
[ "MIT" ]
null
null
null
/* SPDX-License-Identifier: MIT */ #include <iostream> #include "modsynth.hpp" #include "midi.hpp" using namespace ModSynth; int main() { // Components MIDI midi; VCO vco; VCF vcf{0, 3}; VCA vca{2000}; Envelope envelope{0.1, 1, 0.1}; Speaker speaker; // Routing Wire wires[] { {midi.channels[0].gate, envelope.gate_in}, {midi.channels[0].frequency, vco.frequency}, {envelope.amplitude_out, vca.audio_in}, {vca.audio_out, vcf.cutoff}, {vco.sawtooth_out, vcf.audio_in}, {vcf.lowpass_out, speaker.left_in}, {vcf.lowpass_out, speaker.right_in}, }; start(); std::cout << "Press enter to exit...\n"; std::cin.get(); }
20.529412
49
0.620344
gsliepen
df7f817be3946af6097fbb92bcf18326b471680d
1,586
cpp
C++
test/core/testCoordinator.cpp
luyi0619/coco
486baa4341be58c26be8c964d0550ae84604cdac
[ "MIT" ]
2
2021-08-12T12:23:26.000Z
2021-09-12T04:12:41.000Z
test/core/testCoordinator.cpp
luyi0619/coco
486baa4341be58c26be8c964d0550ae84604cdac
[ "MIT" ]
null
null
null
test/core/testCoordinator.cpp
luyi0619/coco
486baa4341be58c26be8c964d0550ae84604cdac
[ "MIT" ]
null
null
null
// // Created by Yi Lu on 8/28/18. // #include "benchmark/tpcc/Database.h" #include "core/Coordinator.h" #include <gtest/gtest.h> DEFINE_int32(threads, 1, "the number of threads."); DEFINE_string(servers, "127.0.0.1:10010;127.0.0.1:10011;127.0.0.1:10012", "semicolon-separated list of servers"); TEST(TestCoordinator, TestTPCC) { using DatabaseType = coco::tpcc::Database; int n = FLAGS_threads; coco::tpcc::Context context; context.peers = {"127.0.0.1:10010"}; context.coordinator_num = 1; context.partition_num = n; context.worker_num = n; context.protocol = "Silo"; context.partitioner = "hash"; DatabaseType db; std::atomic<uint64_t> epoch; std::atomic<bool> stopFlag; coco::Coordinator c(0, db, context); EXPECT_EQ(true, true); } TEST(TestCoordinator, TestConnect) { using DatabaseType = coco::tpcc::Database; int n = FLAGS_threads; std::vector<std::string> peers; boost::algorithm::split(peers, FLAGS_servers, boost::is_any_of(";")); auto startCoordinator = [n, &peers](int id) { coco::tpcc::Context context; context.peers = peers; context.coordinator_num = 3; context.partition_num = n; context.worker_num = n; context.protocol = "Silo"; context.partitioner = "hash"; context.io_thread_num = 1; DatabaseType db; coco::Coordinator c(id, db, context); c.connectToPeers(); }; std::vector<std::thread> v; for (auto i = 0; i < 3; i++) { v.emplace_back(startCoordinator, i); } for (auto i = 0; i < 3; i++) { v[i].join(); } EXPECT_EQ(true, true); }
22.027778
73
0.653846
luyi0619
df7fe383943d3aef908aec409cab14e27574f932
1,287
cpp
C++
src/States/IntroState.cpp
ananace/LD43
5b52767d09b9fceb60200ef000e83e2a308adb81
[ "MIT" ]
null
null
null
src/States/IntroState.cpp
ananace/LD43
5b52767d09b9fceb60200ef000e83e2a308adb81
[ "MIT" ]
null
null
null
src/States/IntroState.cpp
ananace/LD43
5b52767d09b9fceb60200ef000e83e2a308adb81
[ "MIT" ]
null
null
null
#include "../Application.hpp" #include "IntroState.hpp" #include "MenuState.hpp" #include <SFML/Graphics/Sprite.hpp> #include <SFML/Window/Event.hpp> using States::IntroState; IntroState::IntroState() : m_introTimer(0) { } void IntroState::init() { auto& resman = getApp().getResourceManager(); // TODO: Probably should do resource registration some other place if (!resman.registered("sprite/intro")) resman.registerType<sf::Texture>("sprite/intro", "res/intro.png"); m_introTexture = resman.load<sf::Texture>("sprite/intro"); } void IntroState::event(const sf::Event& aEv) { if (aEv.type == aEv.KeyPressed && aEv.key.code == sf::Keyboard::Escape) m_introTimer = 9001; } void IntroState::update(float aDt) { m_introTimer += aDt; if (m_introTimer >= 10) getApp().setState(std::make_unique<MenuState>()); } void IntroState::draw(sf::RenderTarget& aRt, sf::RenderStates aStates) const { // Rotate and zoom out to the target view aStates.transform .rotate(10 - m_introTimer) .scale(0.5f, 0.5f); aRt.clear(sf::Color::White); sf::Sprite introImage; // TODO: Better fallback system? if (m_introTexture) introImage.setTexture(*m_introTexture); aRt.draw(introImage, aStates); }
24.75
76
0.671329
ananace
df8e2b842bd0864d39a8995a20cfeca468852bc6
460
cpp
C++
Intra NSU Programming Contest/Welcome to INPC/Welcome to INPC/main.cpp
anirudha-ani/Toph
e7781731e8b1d6a107df3eb88f3976b8f4b0f955
[ "Apache-2.0" ]
null
null
null
Intra NSU Programming Contest/Welcome to INPC/Welcome to INPC/main.cpp
anirudha-ani/Toph
e7781731e8b1d6a107df3eb88f3976b8f4b0f955
[ "Apache-2.0" ]
null
null
null
Intra NSU Programming Contest/Welcome to INPC/Welcome to INPC/main.cpp
anirudha-ani/Toph
e7781731e8b1d6a107df3eb88f3976b8f4b0f955
[ "Apache-2.0" ]
null
null
null
// // main.cpp // Welcome to INPC // // Created by Anirudha Paul on 2/16/16. // Copyright © 2016 Anirudha Paul. All rights reserved. // #include <iostream> using namespace std; int main(int argc, const char * argv[]) { int names; string input; cin >> names; for (int i = 0 ; i < names; i++) { cin >> input ; input[0] = input[0] - 'a' + 'A'; cout << "Welcome "<< input << endl; } return 0; }
16.428571
56
0.521739
anirudha-ani
df988e6431d9ac472e246f9dddb2bb6193bccdf1
9,099
cpp
C++
modules/actors/tests/test_actors.cpp
agruzdev/Yato
9b5a49f6ec4169b67b9e5ffd11fdae9c238b0a3d
[ "Apache-2.0" ]
9
2020-04-16T10:43:09.000Z
2022-03-07T04:31:52.000Z
modules/actors/tests/test_actors.cpp
agruzdev/Yato
9b5a49f6ec4169b67b9e5ffd11fdae9c238b0a3d
[ "Apache-2.0" ]
3
2020-04-16T10:51:31.000Z
2021-09-02T19:37:26.000Z
modules/actors/tests/test_actors.cpp
agruzdev/Yato
9b5a49f6ec4169b67b9e5ffd11fdae9c238b0a3d
[ "Apache-2.0" ]
null
null
null
/** * YATO library * * Apache License, Version 2.0 * Copyright (c) 2016-2020 Alexey Gruzdev */ #include "gtest/gtest.h" #include <thread> #include <yato/actors/actor_system.h> #include <yato/actors/logger.h> #include <yato/any_match.h> #include <yato/stl_utility.h> #include "test_actors_common.h" namespace { class EchoActor : public yato::actors::actor { void pre_start() override { log().info("pre_start() is called!"); } void receive(yato::any && message) override { yato::any_match( [this](const std::string & str) { log().info(str); }, [this](yato::match_default_t) { log().error("Unknown message!"); } )(message); sender().tell("Nobody will hear me"); } void post_stop() override { log().info("post_stop() is called!"); } }; } TEST(Yato_Actors, common) { const auto conf = actors_debug_config(); yato::actors::actor_system system("default", conf); auto actor = system.create_actor<EchoActor>("echo1"); actor.tell(std::string("Hello, Actor!")); system.shutdown(); } TEST(Yato_Actors, common_pinned) { const auto conf = actors_pinned_config(); yato::actors::actor_system system("default", conf); auto actor = system.create_actor<EchoActor>("echo1"); actor.tell(std::string("Hello, Actor!")); system.shutdown(); } namespace { const int PING_LIMIT = 100000; const int PING_TICK = PING_LIMIT / 10; class PingActor : public yato::actors::actor { void receive(yato::any && message) override { yato::any_match( [this](int count) { sender().tell(count + 1, self()); if(count >= PING_LIMIT) { self().stop(); } else { if (count % PING_TICK == 0) { log().info("Ping " + yato::stl::to_string(count)); } } } )(message); } }; class PongActor : public yato::actors::actor { void receive(yato::any && message) override { yato::any_match( [this](int count) { sender().tell(count + 1, self()); if (count >= PING_LIMIT) { self().stop(); } else { if (count % PING_TICK == 1) { log().info("Pong " + yato::stl::to_string(count)); } } } )(message); } }; } TEST(Yato_Actors, ping_pong) { const auto conf = actors_verbose_config(); yato::actors::actor_system system("default", conf); auto actor1 = system.create_actor<PongActor>("PongActor"); auto actor2 = system.create_actor<PingActor>("PingActor"); system.send_message(actor1, 1, actor2); } TEST(Yato_Actors, ping_pong_pinned) { const auto conf = actors_pinned_config("verbose"); yato::actors::actor_system system("default", conf); auto actor1 = system.create_actor<PongActor>("PongActor"); auto actor2 = system.create_actor<PingActor>("PingActor"); system.send_message(actor1, 1, actor2); } namespace { class actD : public yato::actors::actor { void pre_start() override { log().info("start %s", self().name().c_str()); if(self().name() == "D") { create_child<actD>("D0"); create_child<actD>("D1"); } } void receive(yato::any &&) override { } void post_stop() override { log().info("stop %s", self().name().c_str()); } }; class actB : public yato::actors::actor { void pre_start() override { log().info("start %s", self().name().c_str()); } void receive(yato::any &&) override { } void post_stop() override { log().info("stop %s", self().name().c_str()); } }; class actC : public yato::actors::actor { void pre_start() override { log().info("start %s", self().name().c_str()); create_child<actD>("D"); } void receive(yato::any &&) override { } void post_stop() override { log().info("stop %s", self().name().c_str()); } }; class actA : public yato::actors::actor { void pre_start() override { log().info("start %s", self().name().c_str()); create_child<actB>("B"); create_child<actC>("C"); } void receive(yato::any &&) override { } void post_stop() override { log().info("stop %s", self().name().c_str()); } }; } TEST(Yato_Actors, search) { const auto conf = actors_verbose_config(); yato::actors::actor_system system("default", conf); auto root = system.create_actor<actA>("A"); auto a = system.find(yato::actors::actor_path("yato://default/user/A"), std::chrono::seconds(5)).get(); EXPECT_FALSE(a.empty()); auto b = system.find(yato::actors::actor_path("yato://default/user/A/B"), std::chrono::seconds(5)).get(); EXPECT_FALSE(b.empty()); auto c = system.find(yato::actors::actor_path("yato://default/user/C"), std::chrono::seconds(5)).get(); EXPECT_TRUE(c.empty()); root.tell(yato::actors::poison_pill); } TEST(Yato_Actors, search_2) { const auto conf = actors_verbose_config(); yato::actors::actor_system system("default", conf); auto root = system.create_actor<actA>("A"); auto a = system.find("A", std::chrono::seconds(5)).get(); EXPECT_FALSE(a.empty()); auto b = system.find("A/B", std::chrono::seconds(5)).get(); EXPECT_FALSE(b.empty()); auto c = system.find("C", std::chrono::seconds(5)).get(); EXPECT_TRUE(c.empty()); root.tell(yato::actors::poison_pill); } namespace { class actF3 : public yato::actors::actor { void receive(yato::any && message) override { log().info("Got message from " + sender().name()); forward(std::move(message), sender()); } }; class actF2 : public yato::actors::actor { void receive(yato::any && message) override { log().info("Got message from " + sender().name()); const auto next_actor = system().find("F3", std::chrono::seconds(1)).get(); forward(std::move(message), next_actor); } }; class actF1 : public yato::actors::actor { void receive(yato::any && message) override { log().info("Got message from " + sender().name()); const auto next_actor = system().find("F2", std::chrono::seconds(1)).get(); forward(std::move(message), next_actor); } }; class actF0 : public yato::actors::actor { void pre_start() override { log().info("Send message"); system().find("F1", std::chrono::seconds(1)).get().tell("ping", self()); } void receive(yato::any &&) override { log().info("Got message from " + sender().name()); system().find("F1", std::chrono::seconds(1)).get().stop(); system().find("F2", std::chrono::seconds(1)).get().stop(); system().find("F3", std::chrono::seconds(1)).get().stop(); self().stop(); } }; } TEST(Yato_Actors, forward) { const auto conf = actors_debug_config(); yato::actors::actor_system system("default", conf); system.create_actor<actF3>("F3"); system.create_actor<actF2>("F2"); system.create_actor<actF1>("F1"); // wait until all actors are attached uint32_t attempts = 100; do { const auto ref = system.find("F1", std::chrono::seconds(1)).get(); if(ref) { break; } } while(--attempts); ASSERT_NE(0u, attempts); system.create_actor<actF0>("F0"); } TEST(Yato_Actors, executions) { const auto conf = actors_all_contexts_config(); yato::actors::actor_system system("default", conf); yato::actors::properties props_dyn; props_dyn.execution_name = "dynamic"; yato::actors::properties props_pin; props_pin.execution_name = "pinned"; system.create_actor<actF3>(props_pin, "F3"); system.create_actor<actF2>(props_dyn, "F2"); system.create_actor<actF1>(props_pin, "F1"); // wait until all actors are attached uint32_t attempts = 100; do { const auto ref = system.find("F1", std::chrono::seconds(1)).get(); if(ref) { break; } } while(--attempts); ASSERT_NE(0u, attempts); system.create_actor<actF0>(props_dyn, "F0"); }
24.658537
109
0.528849
agruzdev
dfa253a08b9190811a200df0db5021681ddfef32
371
cpp
C++
lib/src/dexode/eventbus/perk/TagPerk.cpp
nicolasnoble/EventBus
de1852c6394640c76ab58429245408dabcf6cc79
[ "Apache-2.0" ]
231
2017-08-17T16:08:44.000Z
2022-03-31T16:35:32.000Z
lib/src/dexode/eventbus/perk/TagPerk.cpp
qilinlee/EventBus
182fea93590524578fe90226e7e1b3eb42357e34
[ "Apache-2.0" ]
37
2018-07-31T08:00:01.000Z
2021-08-03T14:32:33.000Z
lib/src/dexode/eventbus/perk/TagPerk.cpp
qilinlee/EventBus
182fea93590524578fe90226e7e1b3eb42357e34
[ "Apache-2.0" ]
73
2017-07-25T14:45:14.000Z
2022-03-29T02:10:48.000Z
// // Created by gelldur on 24.12.2019. // #include "TagPerk.hpp" namespace dexode::eventbus::perk { Flag TagPerk::onPrePostponeEvent(PostponeHelper& postponeCall) { if(auto found = _eventsToWrap.find(postponeCall.eventID); found != _eventsToWrap.end()) { found->second(postponeCall.event); return Flag::postpone_cancel; } return Flag::postpone_continue; } }
17.666667
88
0.735849
nicolasnoble
dfac013e2cde596978dd01eea4a823cefd6bbb31
1,041
cpp
C++
STRINGS/Convert String to LowerCase .cpp
snanacha/Coding-questions
18c4b5a23fc3da5c419d2ec69fbf13b7b4ecee0d
[ "MIT" ]
null
null
null
STRINGS/Convert String to LowerCase .cpp
snanacha/Coding-questions
18c4b5a23fc3da5c419d2ec69fbf13b7b4ecee0d
[ "MIT" ]
1
2021-03-30T14:00:56.000Z
2021-03-30T14:00:56.000Z
STRINGS/Convert String to LowerCase .cpp
snanacha/Coding-questions
18c4b5a23fc3da5c419d2ec69fbf13b7b4ecee0d
[ "MIT" ]
null
null
null
Change the string /* Convert String to LowerCase School Accuracy: 80.57% Submissions: 4374 Points: 0 Given a string S. The task is to convert characters of string to lowercase. Example 1: Input: S = "ABCddE" Output: "abcdde" Explanation: A, B, C and E are converted to a, b, c and E thus all uppercase characters of the string converted to lowercase letter. Example 2: Input: S = "LMNOppQQ" Output: "lmnoppqq" Explanation: L, M, N, O, and Q are converted to l, m, n, o and q thus all uppercase characters of the string converted to lowercase letter. Your Task: You dont need to read input or print anything. Complete the function toLower() which takes S as input parameter and returns the converted string. Expected Time Complexity:O(n) Expected Auxiliary Space: O(1) Constraints: 1 <= |S| <= 1000 */ CODE ---- class Solution { public: string toLower(string S) { // code here transform(S.begin(),S.end(),S.begin(),::tolower); return S; } };
22.148936
146
0.666667
snanacha
dfbaabfaab63a43fbb34ed35306d1ce49f04d167
2,974
cpp
C++
src/core/parsers/message/token_scanner.cpp
tinganho/lya
d956220da76d5658e8e2c0654db2068427463c60
[ "Apache-2.0" ]
1
2020-06-04T06:57:31.000Z
2020-06-04T06:57:31.000Z
src/core/parsers/message/token_scanner.cpp
tinganho/lya
d956220da76d5658e8e2c0654db2068427463c60
[ "Apache-2.0" ]
6
2018-01-05T02:55:59.000Z
2018-01-09T03:29:55.000Z
src/core/parsers/message/token_scanner.cpp
tinganho/lya
d956220da76d5658e8e2c0654db2068427463c60
[ "Apache-2.0" ]
null
null
null
// // Created by Tingan Ho on 2017-11-06. // #include <glibmm/ustring.h> #include <memory> #include "token_scanner.h" #include "syntaxes.h" #include "diagnostics/diagnostics.h" using namespace Lya::core::diagnostics; using namespace Lya::lib::types; using namespace Lya::lib::utils; namespace Lya::core::parsers::message { TokenScanner::TokenScanner(const Glib::ustring& text): Scanner<MessageToken>(text, ldml_token_enum_to_string, reverse_map(ldml_token_enum_to_string)), in_formatted_text(false), unmatched_braces(0) { } MessageToken TokenScanner::next_token() { set_token_start_location(); while (position < size) { ch = current_char(); increment_position(); if (ch == Character::OpenBrace) { in_formatted_text = !in_formatted_text; unmatched_braces++; return MessageToken::OpenBrace; } if (!in_formatted_text) { // We don't skip close brace character when we scan text. if (ch == Character::CloseBrace) { in_formatted_text = !in_formatted_text; unmatched_braces--; return MessageToken::CloseBrace; } scan_text(); return MessageToken::Text; } switch (ch) { case Character::Space: case Character::CarriageReturn: case Character::LineFeed: set_token_start_location(); continue; case Character::_0: case Character::_1: case Character::_2: case Character::_3: case Character::_4: case Character::_5: case Character::_6: case Character::_7: case Character::_8: case Character::_9: scan_number(); return MessageToken::Number; case Character::Equal: return MessageToken::Equals; case Character::Comma: return MessageToken::Comma; case Character::CloseBrace: in_formatted_text = !in_formatted_text; unmatched_braces--; return MessageToken::CloseBrace; default: if (is_identifier_start(ch)) { while (position < size && is_identifier_part(current_char())) { increment_position(); } return get_identifier_token(get_token_value()); } } } return MessageToken::EndOfFile; } void TokenScanner::scan_text() { while (ch != Character::OpenBrace) { if (ch == Character::Backslash) { increment_position(); ch = current_char(); continue; } if (ch == Character::CloseBrace || ch == Character::OpenBrace || position == size) { break; } increment_position(); ch = current_char(); } } MessageToken TokenScanner::get_identifier_token(const Glib::ustring& value) { auto size = static_cast<unsigned int>(value.size()); // keywords are between 3 and 8 in size if (size >= 3 && size <= 8) { const char32_t ch = value.at(0); if (ch >= Character::a && ch <= Character::z) { auto it = string_to_token_enum.find(value); if (it != string_to_token_enum.end()) { return it->second; } } } return MessageToken::Identifier; } }
22.70229
97
0.654674
tinganho
dfbc2bbda90919250353bd56da1c6a15fd3f8b56
2,131
hpp
C++
src/backend/graph_compiler/core/src/compiler/config/context.hpp
wuxun-zhang/mkl-dnn
00a239ad2c932b967234ffb528069800ffcc0334
[ "Apache-2.0" ]
null
null
null
src/backend/graph_compiler/core/src/compiler/config/context.hpp
wuxun-zhang/mkl-dnn
00a239ad2c932b967234ffb528069800ffcc0334
[ "Apache-2.0" ]
null
null
null
src/backend/graph_compiler/core/src/compiler/config/context.hpp
wuxun-zhang/mkl-dnn
00a239ad2c932b967234ffb528069800ffcc0334
[ "Apache-2.0" ]
null
null
null
/******************************************************************************* * Copyright 2020-2022 Intel Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ #ifndef BACKEND_GRAPH_COMPILER_CORE_SRC_COMPILER_CONFIG_CONTEXT_HPP #define BACKEND_GRAPH_COMPILER_CORE_SRC_COMPILER_CONFIG_CONTEXT_HPP #include <memory> #include <string> #include "target_machine.hpp" namespace sc { namespace runtime { struct engine_t; } struct scflags_t { enum class brgemm_t : int { dnnl = 0, max_num }; jit_kind jit_kind_ = jit_kind::cfake; int backend_opt_level = 3; bool bf16_fast_trunc_ = false; bool boundary_check_ = false; bool trace_ = false; bool dead_write_elimination_ = true; int buffer_schedule_ = 3; // 0 off, 1 whole reuse, 2 size first, 3 hot first brgemm_t brgemm_backend_ = brgemm_t::dnnl; bool kernel_optim_ = true; bool index2var_ = true; bool print_ir_ = false; bool ssa_passes_ = false; bool brgemm_use_amx_ = false; std::string dump_graph_; std::string graph_dump_results_; bool value_check_ = false; }; struct context_t { sc::runtime::engine_t *engine_; scflags_t flags_; target_machine_t machine_; context_t(const scflags_t &flags, target_machine_t &&machine, runtime::engine_t *engine = nullptr); context_t(const context_t &) = default; uint32_t get_max_vector_lanes(sc_data_etype etype) const; }; using context_ptr = std::shared_ptr<context_t>; SC_API context_ptr get_default_context(); } // namespace sc #endif
33.825397
81
0.680432
wuxun-zhang
dfbeea734da4cfaf8372908ec4e6e8d614b2de90
6,978
hpp
C++
modules/haxm/src/common/interface/hax_types.hpp
dmiller423/virt86
f6cedb78dc55b8ea1b8ca4b53209a58a49b5bd60
[ "MIT" ]
148
2019-02-19T11:05:28.000Z
2022-02-26T11:57:05.000Z
modules/haxm/src/common/interface/hax_types.hpp
dmiller423/virt86
f6cedb78dc55b8ea1b8ca4b53209a58a49b5bd60
[ "MIT" ]
16
2019-02-19T02:51:48.000Z
2019-12-11T21:17:12.000Z
modules/haxm/src/common/interface/hax_types.hpp
dmiller423/virt86
f6cedb78dc55b8ea1b8ca4b53209a58a49b5bd60
[ "MIT" ]
17
2019-02-19T04:05:33.000Z
2021-05-02T12:14:13.000Z
/* * Copyright (c) 2011 Intel Corporation * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * 3. Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #ifndef HAX_TYPES_H_ #define HAX_TYPES_H_ /* Detect architecture */ // x86 (32-bit) #if defined(__i386__) || defined(_M_IX86) #define HAX_ARCH_X86_32 #define ASMCALL __cdecl // x86 (64-bit) #elif defined(__x86_64__) || defined(_M_X64) #define HAX_ARCH_X86_64 #define ASMCALL #else #error "Unsupported architecture" #endif /* Detect compiler */ // Clang #if defined(__clang__) #define HAX_COMPILER_CLANG #define PACKED __attribute__ ((packed)) #define ALIGNED(x) __attribute__ ((aligned(x))) // GCC #elif defined(__GNUC__) #define HAX_COMPILER_GCC #define PACKED __attribute__ ((packed)) #define ALIGNED(x) __attribute__ ((aligned(x))) #define __cdecl __attribute__ ((__cdecl__,regparm(0))) #define __stdcall __attribute__ ((__stdcall__)) // MSVC #elif defined(_MSC_VER) #define HAX_COMPILER_MSVC // FIXME: MSVC doesn't have a simple equivalent for PACKED. // Instead, The corresponding #pragma directives are added manually. #define PACKED #define ALIGNED(x) __declspec(align(x)) #else #error "Unsupported compiler" #endif /* Detect platform */ #ifndef HAX_TESTS // Prevent kernel-only exports from reaching userland code // MacOS #if defined(__MACH__) #define HAX_PLATFORM_DARWIN #include "darwin/hax_types_mac.hpp" // Linux #elif defined(__linux__) #define HAX_PLATFORM_LINUX #include "linux/hax_types_linux.hpp" // Windows #elif defined(_WIN32) #define HAX_PLATFORM_WINDOWS #include "windows/hax_types_windows.hpp" #else #error "Unsupported platform" #endif #else // !HAX_TESTS #include <stdint.h> #endif // HAX_TESTS #define HAX_PAGE_SIZE 4096 #define HAX_PAGE_SHIFT 12 #define HAX_PAGE_MASK 0xfff /* Common typedef for all platforms */ typedef uint64_t hax_pa_t; typedef uint64_t hax_pfn_t; typedef uint64_t hax_paddr_t; typedef uint64_t hax_vaddr_t; enum exit_status { HAX_EXIT_IO = 1, HAX_EXIT_MMIO, HAX_EXIT_REALMODE, HAX_EXIT_INTERRUPT, HAX_EXIT_UNKNOWN, HAX_EXIT_HLT, HAX_EXIT_STATECHANGE, HAX_EXIT_PAUSED, HAX_EXIT_FAST_MMIO, HAX_EXIT_PAGEFAULT, HAX_EXIT_DEBUG }; enum { VMX_EXIT_INT_EXCEPTION_NMI = 0, // An SW interrupt, exception or NMI has occurred VMX_EXIT_EXT_INTERRUPT = 1, // An external interrupt has occurred VMX_EXIT_TRIPLE_FAULT = 2, // Triple fault occurred VMX_EXIT_INIT_EVENT = 3, // INIT signal arrived VMX_EXIT_SIPI_EVENT = 4, // SIPI signal arrived VMX_EXIT_SMI_IO_EVENT = 5, VMX_EXIT_SMI_OTHER_EVENT = 6, VMX_EXIT_PENDING_INTERRUPT = 7, VMX_EXIT_PENDING_NMI = 8, VMX_EXIT_TASK_SWITCH = 9, // Guest attempted a task switch VMX_EXIT_CPUID = 10, // Guest executed CPUID instruction VMX_EXIT_GETSEC = 11, // Guest executed GETSEC instruction VMX_EXIT_HLT = 12, // Guest executed HLT instruction VMX_EXIT_INVD = 13, // Guest executed INVD instruction VMX_EXIT_INVLPG = 14, // Guest executed INVLPG instruction VMX_EXIT_RDPMC = 15, // Guest executed RDPMC instruction VMX_EXIT_RDTSC = 16, // Guest executed RDTSC instruction VMX_EXIT_RSM = 17, // Guest executed RSM instruction in SMM VMX_EXIT_VMCALL = 18, VMX_EXIT_VMCLEAR = 19, VMX_EXIT_VMLAUNCH = 20, VMX_EXIT_VMPTRLD = 21, VMX_EXIT_VMPTRST = 22, VMX_EXIT_VMREAD = 23, VMX_EXIT_VMRESUME = 24, VMX_EXIT_VMWRITE = 25, VMX_EXIT_VMXOFF = 26, VMX_EXIT_VMXON = 27, VMX_EXIT_CR_ACCESS = 28, // Guest accessed a control register VMX_EXIT_DR_ACCESS = 29, // Guest attempted access to debug register VMX_EXIT_IO = 30, // Guest attempted I/O VMX_EXIT_MSR_READ = 31, // Guest attempted to read an MSR VMX_EXIT_MSR_WRITE = 32, // Guest attempted to write an MSR VMX_EXIT_FAILED_VMENTER_GS = 33, // VMENTER failed due to guest state VMX_EXIT_FAILED_VMENTER_MSR = 34, // VMENTER failed due to MSR loading VMX_EXIT_MWAIT = 36, VMX_EXIT_MTF_EXIT = 37, VMX_EXIT_MONITOR = 39, VMX_EXIT_PAUSE = 40, VMX_EXIT_MACHINE_CHECK = 41, VMX_EXIT_TPR_BELOW_THRESHOLD = 43, VMX_EXIT_APIC_ACCESS = 44, VMX_EXIT_GDT_IDT_ACCESS = 46, VMX_EXIT_LDT_TR_ACCESS = 47, VMX_EXIT_EPT_VIOLATION = 48, VMX_EXIT_EPT_MISCONFIG = 49, VMX_EXIT_INVEPT = 50, VMX_EXIT_RDTSCP = 51, VMX_EXIT_VMX_TIMER_EXIT = 52, VMX_EXIT_INVVPID = 53, VMX_EXIT_WBINVD = 54, VMX_EXIT_XSETBV = 55, VMX_EXIT_APIC_WRITE = 56, VMX_EXIT_RDRAND = 57, VMX_EXIT_INVPCID = 58, VMX_EXIT_VMFUNC = 59, VMX_EXIT_ENCLS = 60, VMX_EXIT_RDSEED = 61, VMX_EXIT_XSAVES = 63, VMX_EXIT_XRSTORS = 64 }; #endif // HAX_TYPES_H_
38.766667
92
0.648037
dmiller423
dfc6192adf49382bc2eea0871d47c6adde41586e
1,272
hpp
C++
include/asmith/genetic-algorithm/optimisation_problem.hpp
asmith-git/genetic-algorithm
90f66b562233b5a4ff687ff905db46575a2456b5
[ "Apache-2.0" ]
null
null
null
include/asmith/genetic-algorithm/optimisation_problem.hpp
asmith-git/genetic-algorithm
90f66b562233b5a4ff687ff905db46575a2456b5
[ "Apache-2.0" ]
null
null
null
include/asmith/genetic-algorithm/optimisation_problem.hpp
asmith-git/genetic-algorithm
90f66b562233b5a4ff687ff905db46575a2456b5
[ "Apache-2.0" ]
null
null
null
// Copyright 2017 Adam Smith // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef ASMITH_GA_OPTIMISATION_PROBLEM_HPP #define ASMITH_GA_OPTIMISATION_PROBLEM_HPP #include <cstdint> #include "base_genetic_algorithm.hpp" namespace asmith { template<class T, class F> class optimisation_problem { public: typedef T input_t; typedef T output_t; virtual ~optimisation_problem() throw() {} virtual size_t get_dimensions() const throw() = 0; virtual base_genetic_algorithm::objective_mode get_objective_mode() const throw() = 0; virtual input_t get_minimum_bound(const size_t) const throw() = 0; virtual input_t get_maximum_bound(const size_t) const throw() = 0; virtual output_t operator()(const input_t* const) const throw() = 0; }; } #endif
35.333333
88
0.758648
asmith-git
dfcb68e61d0836ce410aba647e9b1ba55b96b1db
245
cpp
C++
gohbcalc/gohbcalc.cpp
skapix/ohbcalc
627ec6964268ce93d33032cff6f1813496881f78
[ "MIT" ]
1
2018-02-18T06:38:54.000Z
2018-02-18T06:38:54.000Z
gohbcalc/gohbcalc.cpp
skapix/ohbcalc
627ec6964268ce93d33032cff6f1813496881f78
[ "MIT" ]
null
null
null
gohbcalc/gohbcalc.cpp
skapix/ohbcalc
627ec6964268ce93d33032cff6f1813496881f78
[ "MIT" ]
null
null
null
#include "CalculatorWindow.h" #include <QApplication> #include <memory> using namespace std; int main(int argc, char *argv[]) { QApplication app(argc, argv); auto window = make_unique<CalculatorWindow>(); window->show(); app.exec(); }
17.5
48
0.702041
skapix
dfcc98e08f4028cbaf65113757a66dd8be982f1d
1,776
cpp
C++
atcoder/joi/JOI_012_yo/d.cpp
zaurus-yusya/atcoder
5fc345b3da50222fa1366d1ce52ae58799488cef
[ "MIT" ]
3
2020-05-27T16:27:12.000Z
2021-01-27T12:47:12.000Z
atcoder/joi/JOI_012_yo/d.cpp
zaurus-yusya/Competitive-Programming
c72e13a11f76f463510bd4a476b86631d9d1b13a
[ "MIT" ]
null
null
null
atcoder/joi/JOI_012_yo/d.cpp
zaurus-yusya/Competitive-Programming
c72e13a11f76f463510bd4a476b86631d9d1b13a
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> typedef long long ll; typedef long double ld; #define rep(i,n) for(ll i=0;i<(n);i++) #define repr(i,n) for(ll i=(n-1);i>=0;i--) #define all(x) x.begin(),x.end() #define br cout << "\n"; using namespace std; const long long INF = 1e10; const long long MOD = 1e9+7; using Graph = vector<vector<ll>>; using pll = pair<ll, ll>; template<class T> inline bool chmin(T &a, T b) { if(a > b){ a = b; return true;} return false;} template<class T> inline bool chmax(T &a, T b) { if(a < b){ a = b; return true;} return false;} // 0 false, 1 true // string to int : -48 // a to A : -32 // ceil(a) 1.2->2.0 // c++17 g++ -std=c++17 a.cpp int main() { std::cout << std::fixed << std::setprecision(15); ll d, n; cin >> d >> n; vector<long long> temperature(d); for(long long i = 0; i < d; i ++){ cin >> temperature[i]; } vector<ll> a(n); vector<ll> b(n); vector<ll> c(n); rep(i, n){ ll A, B, C; cin >> A >> B >> C; a[i] = A; b[i] = B; c[i] = C; } vector<vector<ll>> dp(d, vector<ll>(n, -1)); for(ll i = 0; i < d; i++){ if(i == 0){ for(ll j = 0; j < n; j++){ if(a[j] <= temperature[i] && temperature[i] <= b[j]){ dp[i][j] = 0; } } continue; } for(ll j = 0; j < n; j++){ if(a[j] <= temperature[i] && temperature[i] <= b[j]){ for(ll k = 0; k < n; k++){ if(dp[i-1][k] != -1){ dp[i][j] = max(dp[i][j], dp[i-1][k] + abs(c[j] - c[k])); } } } } } ll ans = 0; rep(i, n){ ans = max(ans, dp[d-1][i]); } cout << ans << endl; }
26.909091
95
0.433559
zaurus-yusya
2547fd128dec4c1801b6ef1a284b9824816804b7
6,450
hpp
C++
include/tagreader.hpp
dda119141/mp3tags
c75818e4fd6341f2c0c0b482f5c6eb1809b382aa
[ "MIT" ]
1
2020-08-01T21:51:05.000Z
2020-08-01T21:51:05.000Z
include/tagreader.hpp
dda119141/mp3tags
c75818e4fd6341f2c0c0b482f5c6eb1809b382aa
[ "MIT" ]
1
2020-05-01T11:52:59.000Z
2020-05-01T11:52:59.000Z
include/tagreader.hpp
dda119141/mp3tags
c75818e4fd6341f2c0c0b482f5c6eb1809b382aa
[ "MIT" ]
null
null
null
// Copyright(c) 2020-present, Moge & contributors. // Email: dda119141@gmail.com // Distributed under the MIT License (http://opensource.org/licenses/MIT) #ifndef _TAG_READER #define _TAG_READER #include <id3v2_common.hpp> #include <id3v2_v40.hpp> #include <id3v2_v30.hpp> #include <id3v2_v00.hpp> #include <id3v1.hpp> #include <ape.hpp> const std::string GetId3v2Tag( const std::string& fileName, const std::vector<std::pair<std::string, std::string_view>>& tags) { const auto ret = id3v2::GetTagHeader(fileName) | id3v2::checkForID3 | [](id3::buffer_t buffer) { return id3v2::GetID3Version(buffer); } | [&](const std::string& id3Version) { for (auto& tag : tags) { if (id3Version == tag.first) // tag.first is the id3 Version { const auto params = [&](){ if (id3Version == "0x0300") { const auto paramLoc = id3v2::basicParameters { fileName ,id3v2::v30() // Tag version ,tag.second // Frame ID }; return paramLoc; } else if (id3Version == "0x0400") { const auto paramLoc = id3v2::basicParameters{ fileName ,id3v2::v40() // Tag version ,tag.second // Frame ID }; return paramLoc; } else if (id3Version == "0x0000") { const auto paramLoc = id3v2::basicParameters{ fileName ,id3v2::v00() // Tag version ,tag.second // Frame ID }; return paramLoc; } else { const id3v2::basicParameters paramLoc { std::string("") } ; return paramLoc; } }; try { id3v2::TagReadWriter obj(params()); const auto found = obj.getFramePayload(); return id3::stripLeft(found); } catch (const std::runtime_error& e) { std::cout << e.what(); } catch (const id3::audio_tag_error & e) { std::cout << e.what(); } } } return std::string(""); }; return ret; } template <typename Function1, typename Function2> const std::string GetTag(const std::string& filename, const std::vector<std::pair<std::string, std::string_view>>& id3v2Tags, Function1 fuc1, Function2 fuc2) { const auto retApe = fuc1(filename); if (retApe.has_value()) { return retApe.value(); } const auto retId3v1 = fuc2(filename); if(retId3v1.has_value()){ return retId3v1.value(); } return GetId3v2Tag(filename, id3v2Tags); } const std::string GetAlbum(const std::string& filename) { const std::vector<std::pair<std::string, std::string_view>> id3v2Tags{ {"0x0400", "TALB"}, {"0x0300", "TALB"}, {"0x0000", "TAL"}, }; return GetTag(filename, id3v2Tags, ape::GetAlbum, id3v1::GetAlbum); } const std::string GetLeadArtist(const std::string& filename) { const std::vector<std::pair<std::string, std::string_view>> id3v2Tags{ {"0x0400", "TPE1"}, {"0x0300", "TPE1"}, {"0x0000", "TP1"}, }; return GetTag(filename, id3v2Tags, ape::GetLeadArtist, id3v1::GetLeadArtist); } const std::string GetComposer(const std::string& filename) { const std::vector<std::pair<std::string, std::string_view>> id3v2Tags{ {"0x0400", "TCOM"}, {"0x0300", "TCOM"}, {"0x0000", "TCM"}, }; return GetId3v2Tag(filename, id3v2Tags); } const std::string GetDate(const std::string& filename) { const std::vector<std::pair<std::string, std::string_view>> id3v2Tags{ {"0x0300", "TDAT"}, {"0x0400", "TDRC"}, {"0x0000", "TDA"}, }; return GetId3v2Tag(filename, id3v2Tags); } //Also known as Genre const std::string GetContentType(const std::string& filename) { const std::vector<std::pair<std::string, std::string_view>> id3v2Tags{ {"0x0400", "TCON"}, {"0x0300", "TCON"}, {"0x0000", "TCO"}, }; return GetTag(filename, id3v2Tags, ape::GetGenre, id3v1::GetGenre); } const std::string GetComment(const std::string& filename) { const std::vector<std::pair<std::string, std::string_view>> id3v2Tags{ {"0x0400", "COMM"}, {"0x0300", "COMM"}, {"0x0000", "COM"}, }; return GetTag(filename, id3v2Tags, ape::GetComment, id3v1::GetComment); } const std::string GetTextWriter(const std::string& filename) { const std::vector<std::pair<std::string, std::string_view>> id3v2Tags{ {"0x0400", "TEXT"}, {"0x0300", "TEXT"}, {"0x0000", "TXT"}, }; return GetId3v2Tag(filename, id3v2Tags); } const std::string GetYear(const std::string& filename) { const std::vector<std::pair<std::string, std::string_view>> id3v2Tags{ {"0x0400", "TDRC"}, {"0x0300", "TYER"}, {"0x0000", "TYE"}, }; return GetTag(filename, id3v2Tags, ape::GetYear, id3v1::GetYear); } const std::string GetFileType(const std::string& filename) { const std::vector<std::pair<std::string, std::string_view>> id3v2Tags{ {"0x0300", "TFLT"}, {"0x0000", "TFT"}, }; return GetId3v2Tag(filename, id3v2Tags); } const std::string GetTitle(const std::string& filename) { const std::vector<std::pair<std::string, std::string_view>> id3v2Tags{ {"0x0400", "TIT2"}, {"0x0300", "TIT2"}, {"0x0000", "TT2"}, }; return GetTag(filename, id3v2Tags, ape::GetTitle, id3v1::GetTitle); } const std::string GetContentGroupDescription(const std::string& filename) { const std::vector<std::pair<std::string, std::string_view>> id3v2Tags{ {"0x0400", "TIT1"}, {"0x0300", "TIT1"}, {"0x0000", "TT1"}, }; return GetId3v2Tag(filename, id3v2Tags); } const std::string GetTrackPosition(const std::string& filename) { const std::vector<std::pair<std::string, std::string_view>> id3v2Tags{ {"0x0400", "TRCK"}, {"0x0300", "TRCK"}, {"0x0000", "TRK"}, }; return GetId3v2Tag(filename, id3v2Tags); } const std::string GetBandOrchestra(const std::string& filename) { const std::vector<std::pair<std::string, std::string_view>> id3v2Tags{ {"0x0400", "TPE2"}, {"0x0300", "TPE2"}, {"0x0000", "TP2"}, }; return GetId3v2Tag(filename, id3v2Tags); } #endif //_TAG_READER
30.28169
91
0.58093
dda119141
2548f15afc9141f5d0376189a7ce5e0bbdbc0aa6
683
hpp
C++
tesla/base/Noncopyable.hpp
liuheng/tesla
da406aa9744618314a3dab99d8eb698b32234cbd
[ "MIT" ]
null
null
null
tesla/base/Noncopyable.hpp
liuheng/tesla
da406aa9744618314a3dab99d8eb698b32234cbd
[ "MIT" ]
null
null
null
tesla/base/Noncopyable.hpp
liuheng/tesla
da406aa9744618314a3dab99d8eb698b32234cbd
[ "MIT" ]
null
null
null
/* * * Author * Thomas Liu * Date * 4/17/2014 * Description * Noncopyable, copyed from boost::noncopyable.hpp * I don't want to include boost if <tr1> exists * * Licensed under the Apache License, Version 2.0 * */ #ifndef TESLA_BASE_NONCOPYABLE_HPP #define TESLA_BASE_NONCOPYABLE_HPP namespace tesla { namespace base { class Noncopyable { protected: Noncopyable() {} ~Noncopyable() {} private: // emphasize the following members are private Noncopyable( const Noncopyable& ); const Noncopyable& operator=( const Noncopyable& ); }; // class Noncopyable } // namespace base } // namespace tesla #endif // TESLA_BASE_NONCOPYABLE_HPP
17.512821
56
0.692533
liuheng
254b10bb9e8eb88df26dfc8ba4c94048b8fc8c27
8,307
cpp
C++
src/server/scripts/Kalimdor/LostCityOfTheTolvir/boss_high_prophet_barim.cpp
forgottenlands/ForgottenCore406
5dbbef6b3b0b17c277fde85e40ec9fdab0b51ad1
[ "OpenSSL" ]
null
null
null
src/server/scripts/Kalimdor/LostCityOfTheTolvir/boss_high_prophet_barim.cpp
forgottenlands/ForgottenCore406
5dbbef6b3b0b17c277fde85e40ec9fdab0b51ad1
[ "OpenSSL" ]
null
null
null
src/server/scripts/Kalimdor/LostCityOfTheTolvir/boss_high_prophet_barim.cpp
forgottenlands/ForgottenCore406
5dbbef6b3b0b17c277fde85e40ec9fdab0b51ad1
[ "OpenSSL" ]
null
null
null
/* * Copyright (C) 2010 - 2012 ProjectSkyfire <http://www.projectskyfire.org/> * * Copyright (C) 2011 - 2012 ArkCORE <http://www.arkania.net/> * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation; either version 2 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. */ #include"ScriptPCH.h" #include"WorldPacket.h" #include"lost_city_of_the_tolvir.h" enum Spells { SPELL_FIFTY_LASHING = 82506, SPELL_PLAGUE_OF_AGES = 82622, SPELL_REPENTANCE = 81947, SPELL_REPENTANCE_IMMUNE = 82320, SPELL_BLAZE_OF_HEAVENS = 95248, /* Blaze of Heavens ability */ SPELL_SOUL_SEVER = 82255, /* Harbinger of Darkness ability */ SPELL_HEAVENS_FURY = 81939, SPELL_HEAVENS_FURY_VISUAL = 81940, SPELL_HEAVENS_FURY_DMG = 81942, SPELL_HALLOWED_GROUND = 88814, }; enum Events { EVENT_FIFTY_LASHING = 0, EVENT_PLAGUE_OF_AGES, EVENT_REPENTANCE, EVENT_BLAZE_OF_HEAVENS, EVENT_SOUL_SEVER, EVENT_HEAVENS_FURY, EVENT_HALLOWED_GROUND, EVENT_PHASE_1, }; enum SummonIds { NPC_BLAZE_OF_HEAVENS = 48906, NPC_HARBINGER_OF_DARKNESS = 43927, }; const Position SummonLocations[2] = { {-11009.54f, -1294.94f, 10.88f, 0.05f}, // Blaze of Heavens {-11015.45f, -1288.05f, 10.88f, 4.82f}, // Harbinger of Darkness }; class boss_high_prophet_barim : public CreatureScript { public: boss_high_prophet_barim() : CreatureScript("boss_high_prophet_barim") { } CreatureAI* GetAI(Creature* creature) const { return new boss_high_prophet_barimAI (creature); } struct boss_high_prophet_barimAI : public BossAI { boss_high_prophet_barimAI(Creature* creature) : BossAI(creature, DATA_HIGH_PROPHET_BARIM_EVENT), summons(me) { pInstance = creature->GetInstanceScript(); } InstanceScript *pInstance; SummonList summons; EventMap events; void Reset() { events.Reset(); summons.DespawnAll(); if (pInstance) pInstance->SetData(DATA_HIGH_PROPHET_BARIM_EVENT, NOT_STARTED); } void JustDied(Unit* killer) { summons.DespawnAll(); if (pInstance) { pInstance->SetData(DATA_HIGH_PROPHET_BARIM_EVENT, DONE); if (pInstance->GetData(DATA_LOCKMAW) == DONE) { if (GameObject* platform = me->FindNearestGameObject(GO_SIAMAT_PLATFORM, 5000.0f)) platform->SetDestructibleState(GO_DESTRUCTIBLE_DESTROYED); } } } void EnterCombat(Unit* who) { DoZoneInCombat(); if (pInstance) pInstance->SetData(DATA_HIGH_PROPHET_BARIM_EVENT, IN_PROGRESS); events.ScheduleEvent(EVENT_FIFTY_LASHING, urand(10000, 15000)); events.ScheduleEvent(EVENT_PLAGUE_OF_AGES, urand(6000, 9000)); events.ScheduleEvent(EVENT_HEAVENS_FURY, urand(12000, 15000)); if (me->GetMap()->IsHeroic()) events.ScheduleEvent(EVENT_BLAZE_OF_HEAVENS, urand(3000, 8000)); } void EnterPhase2() { DoCast(me, SPELL_HALLOWED_GROUND); events.ScheduleEvent(EVENT_HALLOWED_GROUND, 4000); DoCast(me, SPELL_REPENTANCE_IMMUNE); Creature* Harbinger = me->SummonCreature(NPC_HARBINGER_OF_DARKNESS, SummonLocations[1], TEMPSUMMON_CORPSE_DESPAWN); Harbinger->AddThreat(me->getVictim(), 0.0f); DoZoneInCombat(Harbinger); } void UpdateAI(const uint32 diff) { if (!UpdateVictim()) return; if (me->HasUnitState(UNIT_STAT_CASTING)) return; events.Update(diff); while (uint32 eventId = events.ExecuteEvent()) { switch (eventId) { case EVENT_FIFTY_LASHING: DoCast(me, SPELL_FIFTY_LASHING); events.ScheduleEvent(EVENT_FIFTY_LASHING, urand(10000, 15000)); return; case EVENT_PLAGUE_OF_AGES: if (Unit* target = SelectUnit(SELECT_TARGET_RANDOM, 0)) me->AddAura(SPELL_PLAGUE_OF_AGES, target); events.ScheduleEvent(EVENT_PLAGUE_OF_AGES, urand(6000, 9000)); return; case EVENT_HEAVENS_FURY: if (Unit* target = SelectUnit(SELECT_TARGET_RANDOM, 0)) DoCast(target, SPELL_HEAVENS_FURY); events.ScheduleEvent(EVENT_HEAVENS_FURY, urand(12000, 15000)); break; case EVENT_BLAZE_OF_HEAVENS: if (Creature* BlazeOfHeavens = me->SummonCreature(NPC_BLAZE_OF_HEAVENS, SummonLocations[0], TEMPSUMMON_CORPSE_DESPAWN)) { BlazeOfHeavens->AddThreat(me->getVictim(), 0.0f); DoZoneInCombat(BlazeOfHeavens); } events.ScheduleEvent(EVENT_BLAZE_OF_HEAVENS, urand(20000, 30000)); break; default: break; } } DoMeleeAttackIfReady(); } void JustSummoned(Creature* summoned) { summons.Summon(summoned); switch (summoned->GetEntry()) { case 43801: summoned->AddAura(SPELL_HEAVENS_FURY_VISUAL, summoned); summoned->AddAura(SPELL_HEAVENS_FURY_DMG, summoned); break; case NPC_BLAZE_OF_HEAVENS: summoned->AddAura(SPELL_BLAZE_OF_HEAVENS, summoned); summoned->SetSpeed(MOVE_WALK, 0.5f, true); summoned->SetSpeed(MOVE_RUN, 0.5f, true); summoned->RemoveUnitMovementFlag(MOVEMENTFLAG_WALKING); break; } } }; }; class npc_harbinger_of_darkness: public CreatureScript { public: npc_harbinger_of_darkness() : CreatureScript("npc_harbinger_of_darkness") { } CreatureAI* GetAI(Creature* pCreature) const { return new npc_harbinger_of_darknessAI(pCreature); } struct npc_harbinger_of_darknessAI: public ScriptedAI { npc_harbinger_of_darknessAI(Creature* c) : ScriptedAI(c) { } EventMap events; void Reset() { events.Reset(); } void EnterCombat(Unit* /*who*/) { events.ScheduleEvent(EVENT_SOUL_SEVER, 1000); } void UpdateAI(const uint32 diff) { if (!UpdateVictim()) return; events.Update(diff); if (me->HasUnitState(UNIT_STAT_CASTING)) return; while (uint32 eventId = events.ExecuteEvent()) { switch (eventId) { case EVENT_SOUL_SEVER: DoCast(me->getVictim(), SPELL_SOUL_SEVER); events.RescheduleEvent(EVENT_SOUL_SEVER, 2000); return; } } DoMeleeAttackIfReady(); } }; }; void AddSC_boss_high_prophet_barim() { new boss_high_prophet_barim(); new npc_harbinger_of_darkness(); }
32.704724
143
0.559648
forgottenlands
255158e13e44296d47f07ca5721017a7c792fcb1
1,969
cpp
C++
sources/UseCases/JNI_Sampling/f2/function2.cpp
alrinach/ARISS
b84ace8412ebb037d7c1690ee488c111aef57b64
[ "CECILL-B", "MIT" ]
null
null
null
sources/UseCases/JNI_Sampling/f2/function2.cpp
alrinach/ARISS
b84ace8412ebb037d7c1690ee488c111aef57b64
[ "CECILL-B", "MIT" ]
null
null
null
sources/UseCases/JNI_Sampling/f2/function2.cpp
alrinach/ARISS
b84ace8412ebb037d7c1690ee488c111aef57b64
[ "CECILL-B", "MIT" ]
null
null
null
/* * Use case JNI_Template function2.cpp */ #include "CBasefunction.h" #include <iostream> int main(int argc, char *argv[]) { int redemarrage = atoi(argv[7]); int position = atoi(argv[6]); GUI_ARINC_partition("Partition2", position, redemarrage); int nbarg = argc; char **argument = new char*[argc]; int i = 0; for (i = 0; i <= nbarg; i++) { argument[i] = argv[i]; } COMMUNICATION_VECTOR myCvector; myCvector = init_communication(argument, NULL); Type_Message rMessage; int portID; int sock; vector_get(&(myCvector.vsamp_port), 0, &portID); std::cout << "SamplingPort : " << portID << std::endl; vector_get(&(myCvector.vsamp_socket), 0, &sock); std::cout << "Sampling socket : " << sock << std::endl; // CQueuing Qservice; int ifmessage = 0; int cptMessage = 0; for (ifmessage=0; ifmessage < 10 ; ifmessage++){ char sMessage[256]; std::cout << "Sending sampling message numero " << ifmessage << std::endl; sprintf(sMessage, "Message envoye depuis f2 numero %d", ifmessage); WRITE_SAMPLING_MESSAGE(argv[0], portID, sock, myCvector.emetteur, sMessage); } for (;;) { // std::cout << "debur boucle for, vqueuing_socket[0] : " << sock << std::endl; ifmessage = READ_SAMPLING_MESSAGE(sock, &rMessage); if (ifmessage > 0) { // Qservice.Display_Message(); std::cout << " " << std::endl; std::cout << "Display message : " << rMessage.m_message << std::endl; std::cout << "length " << rMessage.m_length << std::endl; std::cout << "total length " << sizeof (rMessage) << std::endl; std::cout << "receive :" << rMessage.m_message << std::endl; std::cout << " " << std::endl; }else{ std::cout << "No new sampling message" << std::endl; } sleep(1); } return 0; }
37.150943
88
0.562214
alrinach
255686deebe130e69adedc60fda42e28ac5ebd78
730
cpp
C++
lessons/week9/testy/test_guistyle.cpp
Wiladams/sr
4151ddc8303a78e44b0921d9dea0617dd412a7db
[ "MIT" ]
1
2020-03-25T22:02:46.000Z
2020-03-25T22:02:46.000Z
lessons/week9/testy/test_guistyle.cpp
Wiladams/sr
4151ddc8303a78e44b0921d9dea0617dd412a7db
[ "MIT" ]
null
null
null
lessons/week9/testy/test_guistyle.cpp
Wiladams/sr
4151ddc8303a78e44b0921d9dea0617dd412a7db
[ "MIT" ]
2
2020-02-06T01:59:27.000Z
2020-02-10T01:22:41.000Z
/* Test the guistyle object. The guistyle object draws the raised and sunken rectangles that are typical of UI elements such as buttons and sliders. */ #include "p5.hpp" #include "guistyle.hpp" GUIStyle gs; void draw() { background(colors.pink); gs.setBorderWidth(4); gs.drawSunkenRect(10, 10, 320, 40); gs.drawRaisedRect(10, 60, 320, 40); gs.setBorderWidth(6); gs.setBaseColor(colors.darkCyan); gs.drawSunkenRect(10, 120, 40, 320); gs.drawRaisedRect(60, 120, 40, 320); gs.setBorderWidth(2); gs.setBaseColor(colors.ltGray); gs.drawSunkenRect(320, 120, 40, 20); gs.drawRaisedRect(320, 160, 40, 20); noLoop(); } void setup() { createCanvas(640,480); }
19.72973
64
0.657534
Wiladams
2557a7ff3d8082672289297ac348180a32fb6168
10,474
cpp
C++
Connector/CmdMsg.cpp
openlastchaos/lastchaos-source-server
935b770fa857e67b705717d154b11b717741edeb
[ "Apache-2.0" ]
null
null
null
Connector/CmdMsg.cpp
openlastchaos/lastchaos-source-server
935b770fa857e67b705717d154b11b717741edeb
[ "Apache-2.0" ]
null
null
null
Connector/CmdMsg.cpp
openlastchaos/lastchaos-source-server
935b770fa857e67b705717d154b11b717741edeb
[ "Apache-2.0" ]
1
2022-01-17T09:34:39.000Z
2022-01-17T09:34:39.000Z
#include <boost/format.hpp> #include "stdhdrs.h" #include "Server.h" #include "../ShareLib/DBCmd.h" #include "CmdMsg.h" void LoginRepMsg(CNetMsg::SP& msg, MSG_CONN_ERRORCODE errcode, const char* id, CUser* user) { msg->Init(MSG_CONN_REP); RefMsg(msg) << (unsigned char)MSG_CONN_LOGIN_REP << id << (unsigned char)errcode; if (errcode != MSG_CONN_ERROR_SUCCESS) return ; RefMsg(msg) << user->m_index << (unsigned char)user->m_usertype << (unsigned char)user->m_paytype << (unsigned char)user->m_location << user->m_timeremain; RefMsg(msg) << user->m_userFlag;//0627 #ifdef CHARDEL_CHECKID #ifndef JUMIN_DB_CRYPT RefMsg(msg) << user->m_identification; #endif #endif RefMsg(msg) << user->m_proSite; } void ConnCashItemBalanceRep(CNetMsg::SP& msg, int userindex, MSG_EX_CASHITEM_ERROR_TYPE errorcode, int cashBalance) { msg->Init(MSG_CONN_REP); RefMsg(msg) << (unsigned char) MSG_CONN_CASHITEM_BALANCE_REP << userindex << (unsigned char) errorcode << cashBalance; } void ConnCashItemPurchaseRep(CNetMsg::SP& msg, int userindex, MSG_EX_CASHITEM_ERROR_TYPE errorCode, int cash) { msg->Init(MSG_CONN_REP); RefMsg(msg) << (unsigned char) MSG_CONN_CASHITEM_PURCHASE_REP << userindex << (unsigned char) errorCode << cash; } void ConnCashItemBringRep(CNetMsg::SP& msg, int charindex, MSG_EX_CASHITEM_ERROR_TYPE errorCode, bool bPresent, int count, int ctid[]) { msg->Init(MSG_CONN_REP); if( bPresent ) RefMsg(msg) << (unsigned char) MSG_CONN_CASHITEM_GIFT_RECV; else RefMsg(msg) << (unsigned char) MSG_CONN_CASHITEM_BRING_REP; RefMsg(msg) << charindex << (unsigned char) errorCode << count; for(int i = 0; i < count; i++) { RefMsg(msg) << ctid[i]; } } void ConnCashItemPurchaselistRep(CNetMsg::SP& msg, int charindex, MSG_EX_CASHITEM_ERROR_TYPE errorCode, int count, int idx[], int ctid[]) { msg->Init(MSG_CONN_REP); RefMsg(msg) << (unsigned char) MSG_CONN_CASHITEM_PURCHASELIST_REP << charindex << (unsigned char) errorCode << count; for(int i = 0; i < count; i++) { RefMsg(msg) << idx[i] << ctid[i]; } } void ConnCashItemPurchaseHistoryRep(CNetMsg::SP& msg, int userindex, int charindex, int y, int m, int d) { CLCString sql(4096); int ctid = -1, preCtid = -1, i; sql.Format("select * from t_purchase0%d where a_user_idx = %d and a_server = %d " "and year(a_pdate) = %d and month(a_pdate) = %d and dayofmonth(a_pdate) = %d order by a_ctid ", userindex % 10, userindex, gserver.m_serverno, y, m, d); CDBCmd cmd; cmd.Init(&gserver.m_dbuser); cmd.SetQuery(sql); msg->Init(MSG_CONN_REP); RefMsg(msg) << (unsigned char) MSG_CONN_CASHITEM_PURCHASEHISTORY_REP; i = 0; if( !cmd.Open() ) { RefMsg(msg) << charindex << (unsigned char) MSG_EX_CASHITEM_ERROR_CONN << i; return; } if( !cmd.MoveFirst() ) { RefMsg(msg) << charindex << (unsigned char) MSG_EX_CASHITEM_ERROR_SUCCESS << i; return; } CNetMsg ctmsg; ctmsg.Init(); int j = 1; do { cmd.GetRec("a_ctid", ctid); if( preCtid != -1 && preCtid != ctid ) { ctmsg << i << preCtid; i = 0; j++; } preCtid = ctid; i++; } while(cmd.MoveNext() ); ctmsg << i << ctid; RefMsg(msg) << charindex << (unsigned char) MSG_EX_CASHITEM_ERROR_SUCCESS << j << ctmsg; } void ConnCashItemPresentHistoryRep(CNetMsg::SP& msg, int userindex, int charindex, int y, int m, int d, bool bSend) { // 응답 : errorcode(uc) count(n) ctid(n) sendcharName(str) std::string sql = ""; sql.reserve(10240); std::string charName = ""; charName.reserve(MAX_CHAR_NAME_LENGTH + 1); if (bSend) { int i = 0; for (i = 0; i < 9; ++i) { sql += boost::str(boost::format( "SELECT a_ctid, a_recv_char_name AS a_charName FROM t_gift%02d WHERE" "a_send_user_idx = %d AND a_server = %d AND year(a_send_date) = %d AND month(a_send_date) = %d AND dayofmonth(a_send_date) = %d UNION ALL ") % i % userindex % gserver.m_serverno % y % m % d); } sql += boost::str(boost::format( "SELECT a_ctid, a_recv_char_name AS a_charName FROM t_gift%02d WHERE" "a_send_user_idx = %d AND a_server = %d AND year(a_send_date) = %d AND month(a_send_date) = %d AND dayofmonth(a_send_date) = %d") % i % userindex % gserver.m_serverno % y % m % d); } else { sql = boost::str(boost::format( "SELECT a_ctid, a_send_char_name AS a_charName from t_gift%02d WHERE a_recv_user_idx = %d and a_server = %d " "AND year(a_send_date) = %d AND month(a_send_date) = %d AND dayofmonth(a_send_date) = %d ORDER BY a_send_date ") % (userindex % 10) % userindex % gserver.m_serverno % y % m % d); } CDBCmd cmd; cmd.Init(&gserver.m_dbuser); msg->Init(MSG_CONN_REP); if( bSend ) RefMsg(msg) << (unsigned char) MSG_CONN_CASHITEM_GIFT_SENDHISTORY; else RefMsg(msg) << (unsigned char) MSG_CONN_CASHITEM_GIFT_RECVHISTORY; RefMsg(msg) << charindex; cmd.SetQuery(sql); if( cmd.Open() && cmd.MoveFirst() ) { RefMsg(msg) << (unsigned char) MSG_EX_CASHITEM_ERROR_SUCCESS; int count = cmd.m_nrecords; RefMsg(msg) << count; do { int ctid = -1; cmd.GetRec("a_ctid", ctid); cmd.GetRec("a_charName", charName); RefMsg(msg) << ctid << charName.c_str(); } while( cmd.MoveNext() ); } else { RefMsg(msg) << (unsigned char) MSG_EX_CASHITEM_ERROR_SUCCESS; RefMsg(msg) << (int) 0; } } void LimitCatalogMsg(CNetMsg::SP& msg, CLimitSell* limit) { msg->Init(MSG_CONN_REP); RefMsg(msg) << (unsigned char) MSG_CONN_LIMIT_CATALOG; if( !limit ) { int count = gserver.m_limitSell.size(); RefMsg(msg) << count; CServer::map_limitsell_t::iterator it = gserver.m_limitSell.begin(); CServer::map_limitsell_t::iterator endit = gserver.m_limitSell.end(); for(; it != endit; ++it) { CLimitSell* sellList = it->second; RefMsg(msg) << sellList->GetIndex() << sellList->GetSell(); } } else { RefMsg(msg) << 1 << limit->GetIndex() << limit->GetSell(); } } void PlayerRepMsg(CNetMsg::SP& msg) { msg->Init(MSG_CONN_REP); RefMsg(msg) << (unsigned char)MSG_CONN_PLAYER_REP << gserver.m_serverno << gserver.m_maxSubServer << gserver.m_hardcore_flag_in_connector; // zone 0번을 가지고 있는 넘을 찾는다 CDescriptor* d = gserver.m_desclist; CDescriptor** result = new CDescriptor*[gserver.m_maxSubServer]; memset(result, 0, sizeof(CDescriptor*) * gserver.m_maxSubServer); int i = 0; while (d) { if (d->m_bStartServer) { result[d->m_subno - 1] = d; } d = d->m_pNext; } for (i = 1; i <= gserver.m_maxSubServer; i++) { RefMsg(msg) << i; if (result[i - 1]) { RefMsg(msg) << gserver.m_user_list->getUserCountInChannel( result[i - 1]->m_subno ); #ifdef SETTING_IF_INNER_IP_NEW // 외부 아이피와 내부 아이피가 나뉘면 사용, 새로운 버젼 ...yhj CLCString ex_ip(100); ex_ip.Format("EX_IP_%d", i); if( strcmp(gserver.m_config.Find("GameServer", (const char*)ex_ip),"") != 0 ) { result[i - 1]->m_ipAddr.Format("%s", gserver.m_config.Find("GameServer", (const char*)ex_ip)); RefMsg(msg) << result[i - 1]->m_ipAddr; } else RefMsg(msg) << result[i - 1]->m_ipAddr; #else RefMsg(msg) << result[i - 1]->m_ipAddr; #endif // SETTING_IF_INNER_IP_NEW RefMsg(msg) << result[i - 1]->m_portNumber; } else { RefMsg(msg) << (int)-1 << "" << (int)0; } } delete [] result; } void RankerRepMsg(CNetMsg::SP& msg, int charindex) { msg->Init(MSG_CONN_REP); RefMsg(msg) << (unsigned char)MSG_CONN_RANKER_REP << charindex; } #ifdef EVENT_PACKAGE_ITEM void CouponConfirmMsg(CNetMsg::SP& msg, int charindex, MSG_EVENT_ERROR_TYPE subtype, int cIndex, int type) { msg->Init(MSG_CONN_REP); RefMsg(msg) << (unsigned char) MSG_CONN_COUPON_CONFIRM << charindex << (unsigned char) subtype << cIndex << type; } void CouponUseMsg(CNetMsg::SP& msg, int charindex, MSG_EVENT_ERROR_TYPE subtype, int type) { msg->Init(MSG_CONN_REP); RefMsg(msg) << (unsigned char) MSG_CONN_COUPON_USE << charindex << (unsigned char) subtype << type; } #endif // EVENT_PACKAGE_ITEM void MoveServerOKMsg(CNetMsg::SP& msg, int nUserIndex) { msg->Init(MSG_CONN_REP); RefMsg(msg) << (unsigned char)MSG_CONN_MOVESERVER_OK << nUserIndex; } void ConnEventGomdori2007StatusMsg(CNetMsg::SP& msg, int nCharIndex, int nCount, int* nStatus) { msg->Init(MSG_CONN_REP); RefMsg(msg) << (unsigned char)MSG_CONN_EVENT_GOMDORI_2007 << (unsigned char)MSG_CONN_EVENT_GOMDORI_2007_STATUS << nCharIndex << nCount; int i; for (i = 0; i < nCount; i++) RefMsg(msg) << nStatus[i]; } void ConnEventXmas2007Msg( CNetMsg::SP& msg, MSG_CONN_EVENT_XMAS_2007_TYPE subtype ) { msg->Init(MSG_CONN_REP); RefMsg(msg) << (unsigned char)MSG_CONN_EVENT_XMAS_2007 << (unsigned char)subtype; } #ifdef DEV_EVENT_PROMOTION2 void ConnPromotion2RepErrorMsg( CNetMsg::SP& msg, int charIndex, int errorType) { msg->Init( MSG_CONN_REP); RefMsg(msg) << (unsigned char) MSG_CONN_EVENT_PROMOTION2 << charIndex << (unsigned char) errorType; } #endif void ConnWishlistRep(CNetMsg::SP& msg, int count, int ctid[], int useridx, int charidx) { int i; msg->Init(MSG_CONN_REP); RefMsg(msg) << (unsigned char)MSG_CONN_WISHLIST << (unsigned char)MSG_WISHLIST_TYPE_LIST_REP << useridx << charidx << count; for(i = 0; i < count; i++) { RefMsg(msg) << ctid[i]; } } void ConnWishlistSaveRep(CNetMsg::SP& msg, int useridx, int charidx, int errorcode, int ctid) { msg->Init(MSG_CONN_REP); RefMsg(msg) << (unsigned char)MSG_CONN_WISHLIST << (unsigned char)MSG_WISHLIST_TYPE_SAVE_REP << useridx << charidx << (unsigned char)errorcode << ctid; } void ConnWishlistDelRep(CNetMsg::SP& msg, int useridx, int charidx, int errorcode, int ctid) { msg->Init(MSG_CONN_REP); RefMsg(msg) << (unsigned char)MSG_CONN_WISHLIST << (unsigned char)MSG_WISHLIST_TYPE_DEL_REP << useridx << charidx << (unsigned char)errorcode << ctid; } #ifdef EVENT_USER_COMEBACK void ConnEventUserComebackRepMsg( CNetMsg::SP& msg, char errortype, int userindex, int charindex) { msg->Init(MSG_CONN_REP); RefMsg(msg) << (unsigned char)MSG_CONN_EVENT_USER_COMEBACK << errortype << userindex << charindex; } #endif #ifdef EVENT_EUR2_PROMOTION void ConnEUR2PromotionRepMsg(CNetMsg::SP& msg, MSG_EVENT_EUR2_PROMOTION_ERROR_TYPE type, int charindex) { msg->Init(MSG_CONN_REP); RefMsg(msg) << (unsigned char)MSG_CONN_EVENT_EUR2_PROMOTION << type << charindex; } #endif //
24.761229
158
0.673477
openlastchaos
2557e99c2ce1a1d9e3e4ab2d113d67c7c1fe71b6
16,571
cpp
C++
pxr/imaging/plugin/hdOSPRay/basisCurves.cpp
ospray/hdOSPRay
b7b9dff23d3f2df71d4b5ca1028c970bfdc2669b
[ "Apache-2.0" ]
93
2019-02-27T17:25:12.000Z
2022-03-30T02:20:11.000Z
pxr/imaging/plugin/hdOSPRay/basisCurves.cpp
ospray/hdOSPRay
b7b9dff23d3f2df71d4b5ca1028c970bfdc2669b
[ "Apache-2.0" ]
14
2019-03-15T12:23:16.000Z
2021-11-15T23:32:00.000Z
pxr/imaging/plugin/hdOSPRay/basisCurves.cpp
ospray/hdOSPRay
b7b9dff23d3f2df71d4b5ca1028c970bfdc2669b
[ "Apache-2.0" ]
9
2019-03-11T14:47:49.000Z
2022-01-16T00:50:45.000Z
// // Copyright 2021 Intel // // Licensed under the Apache License, Version 2.0 (the "Apache License") // with the following modification; you may not use this file except in // compliance with the Apache License and the following modification to it: // Section 6. Trademarks. is deleted and replaced with: // // 6. Trademarks. This License does not grant permission to use the trade // names, trademarks, service marks, or product names of the Licensor // and its affiliates, except as required to comply with Section 4(c) of // the License and to reproduce the content of the NOTICE file. // // You may obtain a copy of the Apache License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the Apache License with the above modification is // distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the Apache License for the specific // language governing permissions and limitations under the Apache License. // #include "basisCurves.h" #include "config.h" #include "context.h" #include "instancer.h" #include "material.h" #include "renderParam.h" #include "renderPass.h" #include <pxr/base/gf/matrix4d.h> #include <pxr/base/gf/matrix4f.h> #include <pxr/base/gf/vec3f.h> #include <pxr/imaging/hd/meshUtil.h> #include <pxr/imaging/hd/smoothNormals.h> #include <pxr/imaging/pxOsd/tokens.h> #include <rkcommon/math/AffineSpace.h> using namespace rkcommon::math; PXR_NAMESPACE_OPEN_SCOPE // clang-format off TF_DEFINE_PRIVATE_TOKENS( HdOSPRayTokens, (st) ); // clang-format on HdOSPRayBasisCurves::HdOSPRayBasisCurves(SdfPath const& id, SdfPath const& instancerId) : HdBasisCurves(id, instancerId) { } HdDirtyBits HdOSPRayBasisCurves::GetInitialDirtyBitsMask() const { HdDirtyBits mask = HdChangeTracker::Clean | HdChangeTracker::InitRepr | HdChangeTracker::DirtyExtent | HdChangeTracker::DirtyNormals | HdChangeTracker::DirtyPoints | HdChangeTracker::DirtyPrimID | HdChangeTracker::DirtyPrimvar | HdChangeTracker::DirtyDisplayStyle | HdChangeTracker::DirtyRepr | HdChangeTracker::DirtyMaterialId | HdChangeTracker::DirtyTopology | HdChangeTracker::DirtyTransform | HdChangeTracker::DirtyVisibility | HdChangeTracker::DirtyWidths | HdChangeTracker::DirtyComputationPrimvarDesc; if (!GetInstancerId().IsEmpty()) { mask |= HdChangeTracker::DirtyInstancer; } return (HdDirtyBits)mask; } void HdOSPRayBasisCurves::_InitRepr(TfToken const& reprToken, HdDirtyBits* dirtyBits) { TF_UNUSED(reprToken); TF_UNUSED(dirtyBits); } HdDirtyBits HdOSPRayBasisCurves::_PropagateDirtyBits(HdDirtyBits bits) const { return bits; } void HdOSPRayBasisCurves::Sync(HdSceneDelegate* delegate, HdRenderParam* renderParam, HdDirtyBits* dirtyBits, TfToken const& reprToken) { // Pull top-level OSPRay state out of the render param. HdOSPRayRenderParam* ospRenderParam = static_cast<HdOSPRayRenderParam*>(renderParam); opp::Renderer renderer = ospRenderParam->GetOSPRayRenderer(); SdfPath const& id = GetId(); bool updateGeometry = false; bool isTransformDirty = false; if (*dirtyBits & HdChangeTracker::DirtyTopology) { _topology = delegate->GetBasisCurvesTopology(id); if (_topology.HasIndices()) { _indices = _topology.GetCurveIndices(); } updateGeometry = true; } if (*dirtyBits & HdChangeTracker::DirtyMaterialId) { } if (*dirtyBits & HdChangeTracker::DirtyPrimvar) { } if (*dirtyBits & HdChangeTracker::DirtyTransform) { _xfm = GfMatrix4f(delegate->GetTransform(id)); isTransformDirty = true; } if (*dirtyBits & HdChangeTracker::DirtyVisibility) { } if (HdChangeTracker::IsPrimvarDirty(*dirtyBits, id, HdTokens->normals) || HdChangeTracker::IsPrimvarDirty(*dirtyBits, id, HdTokens->widths) || HdChangeTracker::IsPrimvarDirty(*dirtyBits, id, HdTokens->points) || HdChangeTracker::IsPrimvarDirty(*dirtyBits, id, HdTokens->primvar) || HdChangeTracker::IsPrimvarDirty(*dirtyBits, id, HdTokens->displayColor) || HdChangeTracker::IsPrimvarDirty(*dirtyBits, id, HdTokens->displayOpacity) || HdChangeTracker::IsPrimvarDirty(*dirtyBits, id, HdOSPRayTokens->st)) { _UpdatePrimvarSources(delegate, *dirtyBits); updateGeometry = true; } if (updateGeometry) { _UpdateOSPRayRepr(delegate, reprToken, dirtyBits, ospRenderParam); } if ((HdChangeTracker::IsInstancerDirty(*dirtyBits, id) || isTransformDirty) && !_geometricModels.empty()) { _ospInstances.clear(); if (!GetInstancerId().IsEmpty()) { // Retrieve instance transforms from the instancer. HdRenderIndex& renderIndex = delegate->GetRenderIndex(); HdInstancer* instancer = renderIndex.GetInstancer(GetInstancerId()); VtMatrix4dArray transforms = static_cast<HdOSPRayInstancer*>(instancer) ->ComputeInstanceTransforms(GetId()); size_t newSize = transforms.size(); opp::Group group; group.setParam("geometry", opp::CopiedData(_geometricModels)); group.commit(); // TODO: CARSON: reform instancer for ospray2 _ospInstances.reserve(newSize); for (size_t i = 0; i < newSize; i++) { // Create the new instance. opp::Instance instance(group); // Combine the local transform and the instance transform. GfMatrix4f matf = _xfm * GfMatrix4f(transforms[i]); float* xfmf = matf.GetArray(); affine3f xfm(vec3f(xfmf[0], xfmf[1], xfmf[2]), vec3f(xfmf[4], xfmf[5], xfmf[6]), vec3f(xfmf[8], xfmf[9], xfmf[10]), vec3f(xfmf[12], xfmf[13], xfmf[14])); instance.setParam("xfm", xfm); instance.commit(); _ospInstances.push_back(instance); } } // Otherwise, create our single instance (if necessary) and update // the transform (if necessary). else { opp::Group group; group.setParam("geometry", opp::CopiedData(_geometricModels)); group.commit(); opp::Instance instance(group); // TODO: do we need to check for a local transform as well? GfMatrix4f matf = _xfm; float* xfmf = matf.GetArray(); affine3f xfm(vec3f(xfmf[0], xfmf[1], xfmf[2]), vec3f(xfmf[4], xfmf[5], xfmf[6]), vec3f(xfmf[8], xfmf[9], xfmf[10]), vec3f(xfmf[12], xfmf[13], xfmf[14])); instance.setParam("xfm", xfm); instance.commit(); _ospInstances.push_back(instance); } ospRenderParam->UpdateModelVersion(); } // Clean all dirty bits. *dirtyBits &= ~HdChangeTracker::AllSceneDirtyBits; } void HdOSPRayBasisCurves::_UpdatePrimvarSources(HdSceneDelegate* sceneDelegate, HdDirtyBits dirtyBits) { HD_TRACE_FUNCTION(); SdfPath const& id = GetId(); // Update _primvarSourceMap, our local cache of raw primvar data. // This function pulls data from the scene delegate, but defers processing. // // While iterating primvars, we skip "points" (vertex positions) because // the points primvar is processed by _PopulateMesh. We only call // GetPrimvar on primvars that have been marked dirty. // // Currently, hydra doesn't have a good way of communicating changes in // the set of primvars, so we only ever add and update to the primvar set. HdPrimvarDescriptorVector primvars; for (size_t i = 0; i < HdInterpolationCount; ++i) { HdInterpolation interp = static_cast<HdInterpolation>(i); primvars = GetPrimvarDescriptors(sceneDelegate, interp); for (HdPrimvarDescriptor const& pv : primvars) { const auto value = sceneDelegate->Get(id, pv.name); // Points are handled outside _UpdatePrimvarSources if (pv.name == HdTokens->points) { if ((dirtyBits & HdChangeTracker::DirtyPoints) && value.IsHolding<VtVec3fArray>()) { _points = value.Get<VtVec3fArray>(); } continue; } if (pv.name == HdTokens->normals) { if ((dirtyBits & HdChangeTracker::DirtyPoints) && value.IsHolding<VtVec3fArray>()) { _normals = value.Get<VtVec3fArray>(); } continue; } if (pv.name == "widths") { if (dirtyBits & HdChangeTracker::DirtyWidths) { // auto value = sceneDelegate->Get(id, HdTokens->widths); if (value.IsHolding<VtFloatArray>()) _widths = value.Get<VtFloatArray>(); } continue; } // TODO: need to find a better way to identify the primvar for // the texture coordinates // texcoords if ((pv.name == "Texture_uv" || pv.name == "st") && HdChangeTracker::IsPrimvarDirty(dirtyBits, id, HdOSPRayTokens->st)) { if (value.IsHolding<VtVec2fArray>()) { _texcoords = value.Get<VtVec2fArray>(); } continue; } if (pv.name == "displayColor" && HdChangeTracker::IsPrimvarDirty(dirtyBits, id, HdTokens->displayColor)) { // Create 4 component displayColor/opacity array for OSPRay // XXX OSPRay currently expects 4 component color array. // XXX Extend OSPRay to support separate RGB/Opacity arrays if (value.IsHolding<VtVec3fArray>()) { const VtVec3fArray& colors = value.Get<VtVec3fArray>(); _colors.resize(colors.size()); for (size_t i = 0; i < colors.size(); i++) { _colors[i] = { colors[i].data()[0], colors[i].data()[1], colors[i].data()[2], 1.f }; } if (!_colors.empty()) { if (_colors.size() > 1) { _singleColor = { 1.f, 1.f, 1.f, 1.f }; } else { _singleColor = { _colors[0][0], _colors[0][1], _colors[0][2], 1.f }; } } } continue; } if (pv.name == "displayOpacity" && HdChangeTracker::IsPrimvarDirty(dirtyBits, id, HdTokens->displayOpacity)) { std::cout << "hdospBC: has displayOpacity\n"; // XXX assuming displayOpacity can't exist without // displayColor and/or have a different size if (value.IsHolding<VtFloatArray>()) { const VtFloatArray& opacities = value.Get<VtFloatArray>(); if (_colors.size() < opacities.size()) _colors.resize(opacities.size()); for (size_t i = 0; i < opacities.size(); i++) _colors[i].data()[3] = opacities[i]; if (!_colors.empty()) _singleColor[3] = _colors[0][3]; } continue; } } } } void HdOSPRayBasisCurves::_UpdateOSPRayRepr(HdSceneDelegate* sceneDelegate, TfToken const& reprToken, HdDirtyBits* dirtyBitsState, HdOSPRayRenderParam* renderParam) { bool hasWidths = (_widths.size() == _points.size()); bool hasNormals = (_normals.size() == _points.size()); if (_points.empty()) { std::cout << "points empty\n"; TF_RUNTIME_ERROR("_UpdateOSPRayRepr: points empty"); return; } _ospCurves = opp::Geometry("curve"); _position_radii.clear(); for (size_t i = 0; i < _points.size(); i++) { const float width = hasWidths ? _widths[i] / 2.f : 1.0f; _position_radii.emplace_back( vec4f({ _points[i][0], _points[i][1], _points[i][2], width })); } opp::SharedData vertices = opp::SharedData( _position_radii.data(), OSP_VEC4F, _position_radii.size()); vertices.commit(); _ospCurves.setParam("vertex.position_radius", vertices); opp::SharedData normals; if (hasNormals) { normals = opp::SharedData(_normals.data(), OSP_VEC3F, _normals.size()); normals.commit(); _ospCurves.setParam("vertex.normal", normals); } auto type = _topology.GetCurveType(); if (type != HdTokens->cubic) // TODO: support hdTokens->linear TF_RUNTIME_ERROR("hdosp::basisCurves - Curve type not supported"); auto basis = _topology.GetCurveBasis(); const bool hasIndices = !_indices.empty(); auto vertexCounts = _topology.GetCurveVertexCounts(); size_t index = 0; for (auto vci : vertexCounts) { std::vector<unsigned int> indices; for (size_t i = 0; i < vci - size_t(3); i++) { if (hasIndices) indices.push_back(_indices[index]); else indices.push_back(index); index++; } index += 3; auto geometry = opp::Geometry("curve"); geometry.setParam("vertex.position_radius", vertices); if (_colors.size() > 1) { opp::SharedData colors = opp::SharedData(_colors.cdata(), OSP_VEC4F, _colors.size()); colors.commit(); geometry.setParam("vertex.color", colors); } if (_texcoords.size() > 1) { opp::SharedData texcoords = opp::SharedData( _texcoords.cdata(), OSP_VEC2F, _texcoords.size()); texcoords.commit(); geometry.setParam("vertex.texcoord", texcoords); } if (hasNormals) geometry.setParam("vertex.normal", normals); geometry.setParam("index", opp::CopiedData(indices)); geometry.setParam("type", OSP_ROUND); if (hasNormals) geometry.setParam("type", OSP_RIBBON); if (basis == HdTokens->bSpline) geometry.setParam("basis", OSP_BSPLINE); else if (basis == HdTokens->catmullRom) geometry.setParam("basis", OSP_CATMULL_ROM); else TF_RUNTIME_ERROR("hdospBS::sync: unsupported curve basis"); geometry.commit(); const HdRenderIndex& renderIndex = sceneDelegate->GetRenderIndex(); const HdOSPRayMaterial* material = static_cast<const HdOSPRayMaterial*>(renderIndex.GetSprim( HdPrimTypeTokens->material, GetMaterialId())); opp::Material ospMaterial; if (material && material->GetOSPRayMaterial()) { ospMaterial = material->GetOSPRayMaterial(); } else { // Create new ospMaterial ospMaterial = HdOSPRayMaterial::CreateDefaultMaterial(_singleColor); } // Create new OSP Mesh auto gm = opp::GeometricModel(geometry); gm.setParam("material", ospMaterial); gm.commit(); _geometricModels.push_back(gm); } renderParam->UpdateModelVersion(); if (!_populated) { renderParam->AddHdOSPRayBasisCurves(this); _populated = true; } } void HdOSPRayBasisCurves::AddOSPInstances( std::vector<opp::Instance>& instanceList) const { if (IsVisible()) { instanceList.insert(instanceList.end(), _ospInstances.begin(), _ospInstances.end()); } } PXR_NAMESPACE_CLOSE_SCOPE
38.899061
80
0.576791
ospray
25595e212acbae9095fa2df568ae2e27e042a1a2
1,981
cpp
C++
demo/vel_pkg/src/move_vel.cpp
KeKe0114/Team204
12a64614a6c8e477d2054bd1b44295ecc691894d
[ "MIT" ]
1
2020-05-16T10:30:43.000Z
2020-05-16T10:30:43.000Z
demo/vel_pkg/src/move_vel.cpp
dzh19990407/Team204
39d61db5a1d5abcff63f45d50a14c1d7c8277dd2
[ "MIT" ]
23
2020-03-08T05:22:09.000Z
2020-06-07T02:40:56.000Z
demo/vel_pkg/src/move_vel.cpp
dzh19990407/Team204
39d61db5a1d5abcff63f45d50a14c1d7c8277dd2
[ "MIT" ]
11
2020-03-08T02:51:59.000Z
2020-06-07T15:08:32.000Z
#include <ros/ros.h> #include <std_msgs/Float32MultiArray.h> #include <std_msgs/String.h> #include <std_msgs/Int32.h> #include <sensor_msgs/LaserScan.h> #include <geometry_msgs/Twist.h> static ros::Publisher vel_pub; static ros::Subscriber sub_sr; bool lock; geometry_msgs::Twist Move_and_turn(double x, double z) { geometry_msgs::Twist vel_cmd; vel_cmd.linear.x = x; vel_cmd.linear.y = 0; vel_cmd.linear.z = 0; vel_cmd.angular.x = 0; vel_cmd.angular.y = 0; vel_cmd.angular.z = z; return vel_cmd; } geometry_msgs::Twist Stop() { geometry_msgs::Twist vel_cmd; vel_cmd.linear.x = 0; vel_cmd.linear.y = 0; vel_cmd.linear.z = 0; vel_cmd.angular.x = 0; vel_cmd.angular.y = 0; vel_cmd.angular.z = 0; return vel_cmd; } void move_action(const std_msgs::Float32MultiArray::ConstPtr & msg) { float speed, turn; geometry_msgs::Twist vel_cmd; speed = msg->data.at(0); turn = msg->data.at(1); if (speed > 0.5) { speed = 0.5; ROS_INFO("linear speed warning"); } if (speed < -0.5) { speed = -0.5; ROS_INFO("linear speed warning"); } if (turn > 0.5) { turn = 0.5; ROS_INFO("angular speed warning"); } if (turn < -0.5) { turn = -0.5; ROS_INFO("angular speed warning"); } if(lock && speed > 0) { speed = 0; } vel_cmd = Move_and_turn(speed, turn*0.3); //printf("rec %f, %f\n", speed, turn); vel_pub.publish(vel_cmd); ros::spinOnce(); } void move_ctrl(const std_msgs::Int32::ConstPtr & msg) { if (msg -> data == 0) { lock = false; } else { lock = true; } } int main(int argc, char** argv) { bool lock = false; ROS_INFO("move_vel start\n"); ros::init(argc, argv, "move_vel"); ros::NodeHandle n; vel_pub = n.advertise<geometry_msgs::Twist>("/cmd_vel", 10); ros::Subscriber sub = n.subscribe("/move_lock", 10, move_ctrl); sub_sr = n.subscribe("/move_vel", 10, move_action); ros::Rate r(10); while(ros::ok()){ ros::spinOnce(); r.sleep(); } return 0; }
19.048077
67
0.636547
KeKe0114
255ca03db4054a6e9cca7a750c283cd666293209
18,762
cpp
C++
Sources/Plugins/Model_X/SDKMESHModelReader.cpp
jdelezenne/Sonata
fb1b1b64a78874a0ab2809995be4b6f14f9e4d56
[ "MIT" ]
null
null
null
Sources/Plugins/Model_X/SDKMESHModelReader.cpp
jdelezenne/Sonata
fb1b1b64a78874a0ab2809995be4b6f14f9e4d56
[ "MIT" ]
null
null
null
Sources/Plugins/Model_X/SDKMESHModelReader.cpp
jdelezenne/Sonata
fb1b1b64a78874a0ab2809995be4b6f14f9e4d56
[ "MIT" ]
null
null
null
/*============================================================================= SDKMESHModelReader.cpp Project: Sonata Engine Author: Julien Delezenne =============================================================================*/ #include "SDKMESHModelReader.h" namespace SE_X { #define SE_LOGNOTICE(message) Logger::Current()->Log(LogLevel::Notice, _T("SDKMESHModelReader"), ##message##); #define SE_LOGWARNING(message) Logger::Current()->Log(LogLevel::Warning, _T("SDKMESHModelReader"), ##message##); #define SE_LOGERROR(message) Logger::Current()->Log(LogLevel::Error, _T("SDKMESHModelReader"), ##message##); SDKMESHModelReader::SDKMESHModelReader() : ModelReader() { _sdkmesh.m_pStaticMeshData = NULL; _sdkmesh.m_pAnimationData = NULL; _sdkmesh.m_pMeshHeader = NULL; _sdkmesh.m_pVertexBufferArray = NULL; _sdkmesh.m_pIndexBufferArray = NULL; _sdkmesh.m_pMeshArray = NULL; _sdkmesh.m_pSubsetArray = NULL; _sdkmesh.m_pFrameArray = NULL; _sdkmesh.m_pMaterialArray = NULL; _sdkmesh.m_pAnimationHeader = NULL; _sdkmesh.m_pAnimationFrameData = NULL; } SDKMESHModelReader::~SDKMESHModelReader() { Destroy(); } void SDKMESHModelReader::D3DXMATRIXToTransform(D3DXMATRIX* d3dxmatrix, Vector3& position, Quaternion& orientation, Vector3& scale) { Matrix4 matrix = Matrix4::Transpose(Matrix4((real32*)d3dxmatrix->m)); position = Vector3(matrix.M03, matrix.M13, matrix.M23); //TODO: unscale the matrix Matrix3 rotationMatrix = Matrix3( matrix.M00, matrix.M01, matrix.M02, matrix.M10, matrix.M11, matrix.M12, matrix.M20, matrix.M21, matrix.M22); orientation = Quaternion::CreateFromRotationMatrix(rotationMatrix); scale = Vector3::One; } PrimitiveType SDKMESHModelReader::GetPrimitiveType(SDKMESH_PRIMITIVE_TYPE primType) { switch (primType) { case PT_TRIANGLE_LIST: return PrimitiveType_TriangleList; case PT_TRIANGLE_STRIP: return PrimitiveType_TriangleStrip; case PT_LINE_LIST: return PrimitiveType_LineList; case PT_LINE_STRIP: return PrimitiveType_LineStrip; case PT_POINT_LIST: return PrimitiveType_PointList; default: return PrimitiveType_TriangleList; }; } IndexBufferFormat SDKMESHModelReader::GetIBFormat(UINT indexType) { switch (indexType) { case IT_16BIT: return IndexBufferFormat_Int16; case IT_32BIT: return IndexBufferFormat_Int32; default: return IndexBufferFormat_Int16; }; } VertexFormat SDKMESHModelReader::GetVertexFormatType(D3DDECLTYPE value) { switch (value) { case D3DDECLTYPE_FLOAT1: return VertexFormat_Float1; case D3DDECLTYPE_FLOAT2: return VertexFormat_Float2; case D3DDECLTYPE_FLOAT3: return VertexFormat_Float3; case D3DDECLTYPE_FLOAT4: return VertexFormat_Float4; case D3DDECLTYPE_D3DCOLOR: return VertexFormat_Color; case D3DDECLTYPE_UBYTE4: return VertexFormat_UByte4; case D3DDECLTYPE_SHORT2: return VertexFormat_Short2; case D3DDECLTYPE_SHORT4: return VertexFormat_Short4; case D3DDECLTYPE_UBYTE4N: return VertexFormat_UByte4N; default: return VertexFormat_Float1; } } VertexSemantic SDKMESHModelReader::GetVertexSemantic(D3DDECLUSAGE value) { switch (value) { case D3DDECLUSAGE_POSITION: return VertexSemantic_Position; case D3DDECLUSAGE_BLENDWEIGHT: return VertexSemantic_BlendWeight; case D3DDECLUSAGE_BLENDINDICES: return VertexSemantic_BlendIndices; case D3DDECLUSAGE_NORMAL: return VertexSemantic_Normal; case D3DDECLUSAGE_PSIZE: return VertexSemantic_PSize; case D3DDECLUSAGE_TEXCOORD: return VertexSemantic_TextureCoordinate; case D3DDECLUSAGE_TANGENT: return VertexSemantic_Tangent; case D3DDECLUSAGE_BINORMAL: return VertexSemantic_Binormal; case D3DDECLUSAGE_TESSFACTOR: return VertexSemantic_TesselateFactor; case D3DDECLUSAGE_POSITIONT: return VertexSemantic_PositionTransformed; case D3DDECLUSAGE_COLOR: return VertexSemantic_Color; case D3DDECLUSAGE_FOG: return VertexSemantic_Fog; case D3DDECLUSAGE_DEPTH: return VertexSemantic_Depth; case D3DDECLUSAGE_SAMPLE: return VertexSemantic_Sample3; default: return VertexSemantic_Position; } } SDKMESH_FRAME* SDKMESHModelReader::FindFrame(const String& name) { for (UINT i = 0; i < _sdkmesh.m_pMeshHeader->NumFrames; i++) { if (String::Compare(_sdkmesh.m_pFrameArray[i].Name, name) == 0) { return &_sdkmesh.m_pFrameArray[i]; } } return NULL; } Model* SDKMESHModelReader::LoadModel(Stream& stream, ModelReaderOptions* options) { RenderSystem* renderer = RenderSystem::Current(); if (renderer == NULL) { SE_LOGERROR(_T("No active renderer.")); return NULL; } _fileName = ((FileStream*)&stream)->GetFileName(); _path = Path::GetDirectoryName(_fileName); _sdkmesh.m_pStaticMeshData = new BYTE[stream.GetLength()]; stream.Read(_sdkmesh.m_pStaticMeshData, stream.GetLength()); if (!ReadModel()) { return NULL; } if (!ReadAnimation()) { return NULL; } return CreateModel(); } bool SDKMESHModelReader::ReadModel() { // Pointer fixup _sdkmesh.m_pMeshHeader = (SDKMESH_HEADER*)_sdkmesh.m_pStaticMeshData; _sdkmesh.m_pVertexBufferArray = (SDKMESH_VERTEX_BUFFER_HEADER*)(_sdkmesh.m_pStaticMeshData + _sdkmesh.m_pMeshHeader->VertexStreamHeadersOffset); _sdkmesh.m_pIndexBufferArray = (SDKMESH_INDEX_BUFFER_HEADER*)(_sdkmesh.m_pStaticMeshData + _sdkmesh.m_pMeshHeader->IndexStreamHeadersOffset); _sdkmesh.m_pMeshArray = (SDKMESH_MESH*)(_sdkmesh.m_pStaticMeshData + _sdkmesh.m_pMeshHeader->MeshDataOffset); _sdkmesh.m_pSubsetArray = (SDKMESH_SUBSET*)(_sdkmesh.m_pStaticMeshData + _sdkmesh.m_pMeshHeader->SubsetDataOffset); _sdkmesh.m_pFrameArray = (SDKMESH_FRAME*)(_sdkmesh.m_pStaticMeshData + _sdkmesh.m_pMeshHeader->FrameDataOffset); _sdkmesh.m_pMaterialArray = (SDKMESH_MATERIAL*)(_sdkmesh.m_pStaticMeshData + _sdkmesh.m_pMeshHeader->MaterialDataOffset); // Setup subsets for (UINT i=0; i<_sdkmesh.m_pMeshHeader->NumMeshes; i++) { _sdkmesh.m_pMeshArray[i].pSubsets = (UINT*)(_sdkmesh.m_pStaticMeshData + _sdkmesh.m_pMeshArray[i].SubsetOffset); _sdkmesh.m_pMeshArray[i].pFrameInfluences = (UINT*)(_sdkmesh.m_pStaticMeshData + _sdkmesh.m_pMeshArray[i].FrameInfluenceOffset); } // error condition if (_sdkmesh.m_pMeshHeader->Version != SDKMESH_FILE_VERSION) { return false; } return true; } bool SDKMESHModelReader::ReadAnimation() { // Opens the animation file if one exists String animPath = String::Concat(_fileName, "_anim"); File animFile(animPath); if (!animFile.Exists()) { return true; } FileStreamPtr stream = animFile.Open(FileMode_Open, FileAccess_Read); if (stream == NULL) { return false; } SDKANIMATION_FILE_HEADER fileHeader; stream->Read((SEbyte*)&fileHeader, sizeof(SDKANIMATION_FILE_HEADER)); _sdkmesh.m_pAnimationData = new BYTE[(sizeof(SDKANIMATION_FILE_HEADER) + fileHeader.AnimationDataSize)]; stream->Seek(0, SeekOrigin_Begin); stream->Read(_sdkmesh.m_pAnimationData, sizeof(SDKANIMATION_FILE_HEADER) + fileHeader.AnimationDataSize); _sdkmesh.m_pAnimationHeader = (SDKANIMATION_FILE_HEADER*)_sdkmesh.m_pAnimationData; _sdkmesh.m_pAnimationFrameData = (SDKANIMATION_FRAME_DATA*)(_sdkmesh.m_pAnimationData + _sdkmesh.m_pAnimationHeader->AnimationDataOffset); for (UINT i = 0; i < _sdkmesh.m_pAnimationHeader->NumFrames; i++) { _sdkmesh.m_pAnimationFrameData[i].pAnimationData = (SDKANIMATION_DATA*)(_sdkmesh.m_pAnimationData + _sdkmesh.m_pAnimationFrameData[i].DataOffset + sizeof(SDKANIMATION_FILE_HEADER)); SDKMESH_FRAME* pFrame = FindFrame(_sdkmesh.m_pAnimationFrameData[i].FrameName); if (pFrame != NULL) { pFrame->AnimationDataIndex = i; } } return true; } void SDKMESHModelReader::Destroy() { SE_DELETE_ARRAY(_sdkmesh.m_pStaticMeshData); SE_DELETE_ARRAY(_sdkmesh.m_pAnimationData); _sdkmesh.m_pMeshHeader = NULL; _sdkmesh.m_pVertexBufferArray = NULL; _sdkmesh.m_pIndexBufferArray = NULL; _sdkmesh.m_pMeshArray = NULL; _sdkmesh.m_pSubsetArray = NULL; _sdkmesh.m_pFrameArray = NULL; _sdkmesh.m_pMaterialArray = NULL; _sdkmesh.m_pAnimationHeader = NULL; _sdkmesh.m_pAnimationFrameData = NULL; } Model* SDKMESHModelReader::CreateModel() { _model = new Model(); Skeleton* skeleton = new Skeleton(); _model->SetSkeleton(skeleton); CreateFrames(_sdkmesh.m_pFrameArray, _sdkmesh.m_pMeshHeader->NumFrames); // Setup buffer data pointer BYTE* pBufferData = _sdkmesh.m_pStaticMeshData + _sdkmesh.m_pMeshHeader->HeaderSize + _sdkmesh.m_pMeshHeader->NonBufferDataSize; // Get the start of the buffer data UINT64 BufferDataStart = _sdkmesh.m_pMeshHeader->HeaderSize + _sdkmesh.m_pMeshHeader->NonBufferDataSize; // Create VBs for (UINT i = 0; i < _sdkmesh.m_pMeshHeader->NumVertexBuffers; i++) { BYTE* pVertices = NULL; pVertices = (BYTE*)(pBufferData + (_sdkmesh.m_pVertexBufferArray[i].DataOffset - BufferDataStart)); CreateVertexBuffer(&_sdkmesh.m_pVertexBufferArray[i], pVertices); } // Create IBs for (UINT i = 0; i < _sdkmesh.m_pMeshHeader->NumIndexBuffers; i++) { BYTE* pIndices = NULL; pIndices = (BYTE*)(pBufferData + (_sdkmesh.m_pIndexBufferArray[i].DataOffset - BufferDataStart)); CreateIndexBuffer(&_sdkmesh.m_pIndexBufferArray[i], pIndices); } CreateMaterials(_sdkmesh.m_pMaterialArray, _sdkmesh.m_pMeshHeader->NumMaterials); CreateMeshes(_sdkmesh.m_pMeshArray, _sdkmesh.m_pMeshHeader->NumMeshes); CreateHierarchy(); for (int i = 0; i < skeleton->GetBoneCount(); i++) { Bone* bone = skeleton->GetBoneByIndex(i); bone->SetPoseTransform(bone->GetGlobalTransform()); } if (_sdkmesh.m_pAnimationData != NULL) { CreateAnimation(); } return _model; } void SDKMESHModelReader::CreateFrames(SDKMESH_FRAME* pFrames, UINT numFrames) { Skeleton* skeleton = _model->GetSkeleton(); // Create the bones for (UINT frame = 0; frame < numFrames; frame++) { SDKMESH_FRAME* pFrame = &pFrames[frame]; Bone* bone = skeleton->AddBone(); bone->SetName(pFrame->Name); Vector3 position; Quaternion orientation; Vector3 scale; D3DXMATRIXToTransform(&pFrame->Matrix, position, orientation, scale); bone->SetLocalPosition(position); bone->SetLocalOrientation(orientation); bone->SetLocalScale(scale); } } void SDKMESHModelReader::CreateVertexBuffer(SDKMESH_VERTEX_BUFFER_HEADER* pHeader, void* pVertices) { RenderSystem* renderSystem = RenderSystem::Current(); HardwareBuffer* vertexBuffer; if (!renderSystem->CreateVertexBuffer(pHeader->SizeBytes, HardwareBufferUsage_Static, &vertexBuffer)) { _vertexStreams.Add(SDKMESHVertexStream()); return; } void* lockedVertices; vertexBuffer->Map(HardwareBufferMode_Normal, &lockedVertices); Memory::Copy(lockedVertices, pVertices, pHeader->SizeBytes); vertexBuffer->Unmap(); SDKMESHVertexStream vertexStream; vertexStream._vertexBuffer = vertexBuffer; vertexStream._strideBytes = pHeader->StrideBytes; for (UINT vertexElement = 0; vertexElement < MAX_VERTEX_ELEMENTS; vertexElement++) { D3DVERTEXELEMENT9* pVertexElement = &pHeader->Decl[vertexElement]; if (pVertexElement->Stream == 0xff) break; vertexStream._vertexElements.Add(VertexElement(pVertexElement->Stream, pVertexElement->Offset, GetVertexFormatType((D3DDECLTYPE)pVertexElement->Type), GetVertexSemantic((D3DDECLUSAGE)pVertexElement->Usage), pVertexElement->UsageIndex)); } _vertexStreams.Add(vertexStream); } void SDKMESHModelReader::CreateIndexBuffer(SDKMESH_INDEX_BUFFER_HEADER* pHeader, void* pIndices) { RenderSystem* renderSystem = RenderSystem::Current(); HardwareBuffer* indexBuffer; IndexBufferFormat ibFormat = GetIBFormat(pHeader->IndexType); if (!renderSystem->CreateIndexBuffer(pHeader->SizeBytes, ibFormat, HardwareBufferUsage_Static, &indexBuffer)) { _indexBuffers.Add(NULL); return; } void* lockedIndices; indexBuffer->Map(HardwareBufferMode_Normal, &lockedIndices); Memory::Copy(lockedIndices, pIndices, pHeader->SizeBytes); indexBuffer->Unmap(); _indexBuffers.Add(indexBuffer); } void SDKMESHModelReader::CreateMaterials(SDKMESH_MATERIAL* pMaterials, UINT numMaterials) { for (UINT m = 0; m < numMaterials; m++) { SDKMESH_MATERIAL* pMaterial = &pMaterials[m]; DefaultMaterial* shader = new DefaultMaterial(); FFPPass* pass = (FFPPass*)shader->GetTechnique()->GetPassByIndex(0); pass->SetName(pMaterial->Name); pass->MaterialState.DiffuseColor = Color32(pMaterial->Diffuse.x, pMaterial->Diffuse.y, pMaterial->Diffuse.z, pMaterial->Diffuse.w); pass->MaterialState.SpecularColor = Color32(pMaterial->Specular.x, pMaterial->Specular.y, pMaterial->Specular.z); pass->MaterialState.EmissiveColor = Color32(pMaterial->Emissive.x, pMaterial->Emissive.y, pMaterial->Emissive.z); pass->MaterialState.Shininess = pMaterial->Power; pass->LightState.Lighting = true; if (pMaterial->Diffuse.w != 1.0f) { pass->AlphaState.BlendEnable[0] = true; pass->AlphaState.SourceBlend = BlendMode_SourceAlpha; pass->AlphaState.DestinationBlend = BlendMode_InvSourceAlpha; } String diffuseTexture = pMaterial->DiffuseTexture; if (!diffuseTexture.IsEmpty()) { String imagePath = Path::Combine(_path, diffuseTexture); Resource* resource = ResourceHelper::LoadFromFile( imagePath, SE_ID_DATA_IMAGE); if (resource != NULL) { Texture* texture; if (RenderSystem::Current()->CreateTexture(&texture) && texture->Create((Image*)resource->GetData(), TextureUsage_Static)) { SamplerState* samplerState = pass->GetSamplerStateByIndex(0); samplerState->SetTexture(texture); } } } _materials.Add(shader); } } void SDKMESHModelReader::CreateMeshes(SDKMESH_MESH* pMeshes, UINT numMeshes) { RenderSystem* renderSystem = RenderSystem::Current(); for (UINT m = 0; m < numMeshes; m++) { SDKMESH_MESH* pMesh = &pMeshes[m]; Mesh* mesh = new Mesh(); _model->AddMesh(mesh); mesh->SetName(pMesh->Name); Vector3 min, max; min.X = pMesh->BoundingBoxCenter.x - pMesh->BoundingBoxExtents.x; min.Y = pMesh->BoundingBoxCenter.y - pMesh->BoundingBoxExtents.y; min.Z = pMesh->BoundingBoxCenter.z - pMesh->BoundingBoxExtents.z; max.X = pMesh->BoundingBoxExtents.x - pMesh->BoundingBoxCenter.x; max.Y = pMesh->BoundingBoxExtents.y - pMesh->BoundingBoxCenter.y; max.Z = pMesh->BoundingBoxExtents.z - pMesh->BoundingBoxCenter.z; mesh->SetBoundingBox(BoundingBox(min, max)); if (pMesh->NumFrameInfluences > 0) { Skin* skin = new Skin(); mesh->SetSkin(skin); skin->SkinVertices.Resize(pMesh->NumFrameInfluences); for (UINT fi = 0; fi < pMesh->NumFrameInfluences; fi++) { skin->SkinVertices[fi].BoneIndex = pMesh->pFrameInfluences[fi]; } } for (UINT subset = 0; subset < pMesh->NumSubsets; subset++) { SDKMESH_SUBSET* pSubset = &_sdkmesh.m_pSubsetArray[pMesh->pSubsets[subset]]; MeshPart* meshPart = new MeshPart(); mesh->AddMeshPart(meshPart); VertexLayout* vertexLayout; if (!renderSystem->CreateVertexLayout(&vertexLayout)) { continue; } VertexData* vertexData = new VertexData(); for (UINT vertexBuffer = 0; vertexBuffer < pMesh->NumVertexBuffers; vertexBuffer++) { UINT vbIndex = pMesh->VertexBuffers[vertexBuffer]; vertexData->VertexStreams.Add(VertexStream(_vertexStreams[vbIndex]._vertexBuffer, _vertexStreams[vbIndex]._strideBytes)); vertexLayout->SetElements((const VertexElement*)&_vertexStreams[vbIndex]._vertexElements, _vertexStreams[vbIndex]._vertexElements.Count()); } vertexData->VertexLayout = vertexLayout; vertexData->VertexCount = pSubset->VertexCount; meshPart->SetVertexData(vertexData); #if 0 SDKMESH_PRIMITIVE_TYPE primType = (SDKMESH_PRIMITIVE_TYPE)pSubset->PrimitiveType; if (pSubset->IndexCount > 0) { IndexData* indexData = new IndexData(); indexData->IndexBuffer = _indexBuffers[pMesh->IndexBuffer]; indexData->IndexCount = pSubset->IndexCount; meshPart->SetIndexData(indexData); meshPart->SetStartIndex(pSubset->IndexStart); meshPart->SetIndexed(true); meshPart->SetPrimitiveTypeAndCount(GetPrimitiveType(primType), pSubset->IndexCount); } else { meshPart->SetPrimitiveTypeAndCount(GetPrimitiveType(primType), pSubset->VertexCount); } #else meshPart->SetPrimitiveTypeAndCount(PrimitiveType_PointList, pSubset->VertexCount); #endif ShaderMaterial* shader = _materials[pSubset->MaterialID]; meshPart->SetShader(shader); } } } void SDKMESHModelReader::CreateHierarchy() { Skeleton* skeleton = _model->GetSkeleton(); BaseArray<Bone*> rootBones; // Setup the hierarchy for (UINT frame = 0; frame < _sdkmesh.m_pMeshHeader->NumFrames; frame++) { SDKMESH_FRAME* pFrame = &_sdkmesh.m_pFrameArray[frame]; Bone* child = skeleton->GetBoneByIndex(frame); if (pFrame->Mesh != INVALID_MESH) { _model->GetMeshByIndex(pFrame->Mesh)->SetParentBone(child); } if (pFrame->ParentFrame == INVALID_FRAME) { rootBones.Add(child); } else { Bone* parent = skeleton->GetBoneByIndex(pFrame->ParentFrame); parent->AddChild(child); } } if (rootBones.Count() == 1) { skeleton->SetRootBone(rootBones[0]); } else { Bone* rootBone = skeleton->AddBone(); skeleton->SetRootBone(rootBone); for (int i = 0; i < rootBones.Count(); i++) { rootBone->AddChild(rootBones[i]); } } skeleton->GetRootBone()->Update(); } void SDKMESHModelReader::CreateAnimation() { Skeleton* skeleton = _model->GetSkeleton(); AnimationSet* animationSet = new AnimationSet(); AnimationSequence* sequence = new AnimationSequence(); TimeValue endTime; for (UINT frame = 0; frame < _sdkmesh.m_pMeshHeader->NumFrames; frame++) { SDKMESH_FRAME* pFrame = &_sdkmesh.m_pFrameArray[frame]; if (pFrame->AnimationDataIndex != INVALID_ANIMATION_DATA) { SDKANIMATION_FRAME_DATA* pFrameData = &_sdkmesh.m_pAnimationFrameData[pFrame->AnimationDataIndex]; BoneAnimationTrack* track = new BoneAnimationTrack(); track->SetBone(skeleton->GetBoneByIndex(frame)); TimeValue keyTime; Vector3 translation; Quaternion rotation; Vector3 scale; for (UINT animationKey = 0; animationKey < _sdkmesh.m_pAnimationHeader->NumAnimationKeys; animationKey++) { SDKANIMATION_DATA* pData = &pFrameData->pAnimationData[animationKey]; keyTime = TimeValue((real64)animationKey / (real64)_sdkmesh.m_pAnimationHeader->AnimationFPS); TransformKeyFrame* keyFrame = (TransformKeyFrame*)track->AddKeyFrame(keyTime); keyFrame->SetTransformType(TransformKeyFrameType_All); keyFrame->SetTranslation(Vector3((real32*)&pData->Translation)); keyFrame->SetRotation(Quaternion(pData->Orientation.x, pData->Orientation.y, pData->Orientation.z, pData->Orientation.w)); keyFrame->SetScale(Vector3((real32*)&pData->Scaling)); } track->SetEndTime(keyTime); sequence->AddAnimationTrack(track); if (keyTime > endTime) { endTime = keyTime; } } } sequence->SetEndTime(endTime); animationSet->AddAnimationSequence(sequence); skeleton->SetAnimationSet(animationSet); } }
31.21797
238
0.756316
jdelezenne
255e9d7110e1f6301c9e0cfd51e6090fab7f45ae
537
cpp
C++
src/engine/texture_manager.cpp
LorenzoDiStefano/CppEngine2D
1985b5ce92452aed73ed7b719cf555dabd9e9367
[ "MIT" ]
null
null
null
src/engine/texture_manager.cpp
LorenzoDiStefano/CppEngine2D
1985b5ce92452aed73ed7b719cf555dabd9e9367
[ "MIT" ]
null
null
null
src/engine/texture_manager.cpp
LorenzoDiStefano/CppEngine2D
1985b5ce92452aed73ed7b719cf555dabd9e9367
[ "MIT" ]
null
null
null
#include "texture_manager.hpp" namespace engine { texture_manager::texture_manager() : m_stored_texture{ 0 }, m_renderer{ NULL } { } void texture_manager::set_renderer(gfx::my_renderer* renderer) { this->m_renderer = renderer; } //return index of texture int texture_manager::load_texture(const std::string& path) { gfx::image_info* texture_inf = new gfx::image_info(); texture_inf->load_image(path); texture_inf->load_texture(m_renderer); textures[m_stored_texture] = *texture_inf; return m_stored_texture++; } }
24.409091
83
0.743017
LorenzoDiStefano
256425ecac572a9272b81f402129e0f16835e682
2,171
hpp
C++
include/codegen/include/UnityEngine/EventSystems/ExecuteEvents_--c.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
1
2021-11-12T09:29:31.000Z
2021-11-12T09:29:31.000Z
include/codegen/include/UnityEngine/EventSystems/ExecuteEvents_--c.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
null
null
null
include/codegen/include/UnityEngine/EventSystems/ExecuteEvents_--c.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
2
2021-10-03T02:14:20.000Z
2021-11-12T09:29:36.000Z
// Autogenerated from CppHeaderCreator on 7/27/2020 3:10:39 PM // Created by Sc2ad // ========================================================================= #pragma once #pragma pack(push, 8) // Begin includes #include "utils/typedefs.h" // Including type: System.Object #include "System/Object.hpp" // Including type: UnityEngine.EventSystems.ExecuteEvents #include "UnityEngine/EventSystems/ExecuteEvents.hpp" #include "utils/il2cpp-utils.hpp" // Completed includes // Begin forward declares // Forward declaring namespace: System::Collections::Generic namespace System::Collections::Generic { // Forward declaring type: List`1<T> template<typename T> class List_1; } // Forward declaring namespace: UnityEngine::EventSystems namespace UnityEngine::EventSystems { // Forward declaring type: IEventSystemHandler class IEventSystemHandler; } // Completed forward declares // Type namespace: UnityEngine.EventSystems namespace UnityEngine::EventSystems { // Autogenerated type: UnityEngine.EventSystems.ExecuteEvents/<>c class ExecuteEvents::$$c : public ::Il2CppObject { public: // Get static field: static public readonly UnityEngine.EventSystems.ExecuteEvents/<>c <>9 static UnityEngine::EventSystems::ExecuteEvents::$$c* _get_$$9(); // Set static field: static public readonly UnityEngine.EventSystems.ExecuteEvents/<>c <>9 static void _set_$$9(UnityEngine::EventSystems::ExecuteEvents::$$c* value); // static private System.Void .cctor() // Offset: 0xDE754C static void _cctor(); // System.Void <.cctor>b__79_0(System.Collections.Generic.List`1<UnityEngine.EventSystems.IEventSystemHandler> l) // Offset: 0xDE75BC void $_cctor$b__79_0(System::Collections::Generic::List_1<UnityEngine::EventSystems::IEventSystemHandler*>* l); // public System.Void .ctor() // Offset: 0xDE75B4 // Implemented from: System.Object // Base method: System.Void Object::.ctor() static ExecuteEvents::$$c* New_ctor(); }; // UnityEngine.EventSystems.ExecuteEvents/<>c } DEFINE_IL2CPP_ARG_TYPE(UnityEngine::EventSystems::ExecuteEvents::$$c*, "UnityEngine.EventSystems", "ExecuteEvents/<>c"); #pragma pack(pop)
42.568627
120
0.721787
Futuremappermydud
256b36811e459d3e3a7bbba144ffde399f61e83b
1,065
cc
C++
src/page_close_button.cc
jeff-cn/doogie
1b4ed74adecbae773b51e674d298e3d5b09e4244
[ "MIT" ]
291
2017-07-19T22:32:25.000Z
2022-02-16T03:03:21.000Z
charts/doogie-0.7.8/src/page_close_button.cc
hyq5436/playground
828b9d2266dbb7d0311e2e73b295fcafb101d94f
[ "MIT" ]
81
2017-09-06T15:46:27.000Z
2020-11-30T14:12:11.000Z
charts/doogie-0.7.8/src/page_close_button.cc
hyq5436/playground
828b9d2266dbb7d0311e2e73b295fcafb101d94f
[ "MIT" ]
29
2017-09-18T19:14:50.000Z
2022-01-24T06:03:17.000Z
#include "page_close_button.h" #include "util.h" namespace doogie { PageCloseButton::PageCloseButton(QTreeWidget* tree, QWidget* parent) : QToolButton(parent), tree_(tree) { setCheckable(true); setIcon(Util::CachedIcon(":/res/images/fontawesome/times.png")); setText("Close"); setAutoRaise(true); } void PageCloseButton::mouseMoveEvent(QMouseEvent*) { if (close_dragging_) { auto button = qobject_cast<PageCloseButton*>( tree_->childAt(tree_->mapFromGlobal(QCursor::pos()))); if (button && last_seen_ != button) { button->setChecked(!button->isChecked()); button->setDown(button->isChecked()); } last_seen_ = button; } } void PageCloseButton::mousePressEvent(QMouseEvent*) { close_dragging_ = true; last_seen_ = this; setChecked(true); setDown(true); setStyleSheet(":hover:!checked { background-color: transparent; }"); } void PageCloseButton::mouseReleaseEvent(QMouseEvent*) { close_dragging_ = false; last_seen_ = nullptr; setStyleSheet(""); emit Released(); } } // namespace doogie
24.767442
70
0.698592
jeff-cn
2570bf51db189f1c3ebcf4c384a4312d6478bcc3
1,412
cpp
C++
IonSymbolTable.cpp
wukakuki/ion-hash-cpp
94d35c6d44bb208e09b0eb5402d9c93af2b3337a
[ "Apache-2.0" ]
2
2021-08-09T05:57:50.000Z
2021-08-09T19:27:23.000Z
IonSymbolTable.cpp
wukakuki/ion-hash-cpp
94d35c6d44bb208e09b0eb5402d9c93af2b3337a
[ "Apache-2.0" ]
null
null
null
IonSymbolTable.cpp
wukakuki/ion-hash-cpp
94d35c6d44bb208e09b0eb5402d9c93af2b3337a
[ "Apache-2.0" ]
null
null
null
/* Copyright (C) Siqi.Wu - All Rights Reserved * Unauthorized copying of this file, via any medium is strictly prohibited * Written by Siqi.Wu <lion547016@gmail.com>, July 2021 */ #include "IonSymbolTable.h" #include "IonWriter.h" #include "ionc/ion.h" #include <cstdlib> #ifndef ION_OK #define ION_OK(x) if (x) { printf("In %s, line %d, %s Error: %s\n", __FUNCTION__, __LINE__, __func__, ion_error_to_str(x)); } #endif Ion::Symbol::Symbol() { type = Ion::Types::SYMBOL; } Ion::Symbol::~Symbol() = default; Ion::Symbol::Symbol(ION_SYMBOL &symbol) : symbol(symbol) { type = Ion::Types::SYMBOL; } Ion::Symbol::Symbol(Ion::Reader &reader) : Ion::ScalarValue(reader) { iERR err = ion_reader_read_ion_symbol(reader.reader, &symbol); ION_OK(err) type = Ion::Types::SYMBOL; } void Ion::Symbol::getBytes() { bytes.clear(); if (isNull) { this->bytes.push_back(type.binaryTypeId << 4 | 0x0f); } else { Ion::Writer writer(true); Ion::String str(symbol.value); writer.writeString(str); this->bytes = writer.getBytes(); } } Ion::SymbolTable::SymbolTable() { iERR err = ion_symbol_table_open(&symbol_table, nullptr); ION_OK(err) } Ion::SymbolTable::~SymbolTable() { iERR err = ion_symbol_table_close(symbol_table); ION_OK(err) } Ion::SymbolTable::SymbolTable(hSYMTAB symbol_table) : symbol_table(symbol_table) { }
22.774194
125
0.664306
wukakuki
257ba66d9da773ca868b7d1312cb3fec62143177
6,274
cc
C++
progprojet/trial/general/Vecteur3D.cc
YoussefSaied/MagneticFrustration
d3df5a70f4926540b97695170d85b15b8d895890
[ "MIT" ]
1
2020-12-18T15:39:49.000Z
2020-12-18T15:39:49.000Z
progprojet/trial/general/Vecteur3D.cc
YoussefSaied/MagneticFrustration
d3df5a70f4926540b97695170d85b15b8d895890
[ "MIT" ]
null
null
null
progprojet/trial/general/Vecteur3D.cc
YoussefSaied/MagneticFrustration
d3df5a70f4926540b97695170d85b15b8d895890
[ "MIT" ]
null
null
null
#include <iostream> #include "Vecteur3D.h" #include <cmath> #include "Aleatoire.h" using namespace std; // random utilisé dans la méthode random_vector() random_device generator; uniform_int_distribution<int> distribution(0, 10); // constructeurs Vecteur3D:: Vecteur3D(double x, double y, double z) : x(x), y(y), z(z){ } // manipulateurs void Vecteur3D :: set_coord(double newX, double newY, double newZ) { // x,y,z sont les coord du vecteur qui utilise la méthode x = newX; y = newY; z = newZ; } double Vecteur3D:: get_x() const { return x; } double Vecteur3D:: get_y() const { return y; } double Vecteur3D:: get_z() const { return z; } // methodes ostream&Vecteur3D:: affiche(ostream &sortie, bool withoutbrackets) const { if (withoutbrackets) { sortie << "(" << x << ", " << y << ", " << z << ") "; } else { sortie << x << " " << y << " " << z; } return sortie; } Vecteur3D Vecteur3D :: oppose() const { return Vecteur3D(x * -1, y * -1, z * -1); } double Vecteur3D :: norme2() const { return x * x + y * y + z * z; } double Vecteur3D :: norme() const { return sqrt(norme2()); } void Vecteur3D :: random_vector() // pour test { (*this).set_coord(distribution(generator), distribution(generator), distribution(generator)); cout << "Nouveau Vecteur3D aléatoire : "; cout << (*this) << endl; } Vecteur3D Vecteur3D :: GS1() const { if ( (*this).normalise() != Vecteur3D(1, 0, 0) ) { return Vecteur3D(1, 0, 0) - (Vecteur3D(1, 0, 0) * (*this)) * (*this) / norme2(); } else { return Vecteur3D(0, 1, 0); } } Vecteur3D Vecteur3D :: GS1(Vecteur3D excluded) const { if ( ((*this) ^ excluded) != 0) { return (*this) - (excluded * (*this)) * excluded / (norme2()); } else { return Vecteur3D(1, 10, 100) ^ excluded; } } Vecteur3D Vecteur3D :: normalise() const { if (norme() != 0) { return (*this) / ((*this).norme()); } return (*this); } double Vecteur3D :: distance(Vecteur3D const& v2) const { return ((*this) - v2).norme(); } Vecteur3D Vecteur3D :: rotate(double angle, Vecteur3D axe1) const { Vecteur3D axe = axe1.normalise(); double x1 = x * (cos(angle) + axe.x * axe.x * (1 - cos(angle))) + y * (axe.x * axe.y * (1 - cos(angle)) - axe.z * sin(angle)) + z * (axe.x * axe.z * (1 - cos(angle)) + axe.y * sin(angle)); double y1 = y * (cos(angle) + axe.y * axe.y * (1 - cos(angle))) + x * (axe.x * axe.y * (1 - cos(angle)) + axe.z * sin(angle)) + z * (axe.y * axe.z * (1 - cos(angle)) - axe.x * sin(angle)); double z1 = z * (cos(angle) + axe.z * axe.z * (1 - cos(angle))) + x * (axe.x * axe.z * (1 - cos(angle)) - axe.y * sin(angle)) + y * (axe.y * axe.z * (1 - cos(angle)) + axe.x * sin(angle)); return Vecteur3D(x1, y1, z1); } arma::Mat<double> Vecteur3D :: rotationMatrix(Vecteur3D finalVector) const { Vecteur3D initial = normalise(); Vecteur3D finalVectorN = finalVector.normalise(); arma::Mat<double> I(3, 3, arma::fill::eye); double C = initial * finalVectorN; Vecteur3D v = initial ^ finalVectorN; //double S = (v).norme(); arma::Mat<double> Skew(3, 3, arma::fill::zeros); Skew(0, 1) = -1 * v.z; Skew(1, 0) = +1 * v.z; Skew(0, 2) = v.y; Skew(2, 0) = -1 * v.y; Skew(1, 2) = -1 * v.x; Skew(2, 1) = +1 * v.x; return I + Skew + (1 / (1 + C)) * Skew*Skew; } // operateurs interne bool Vecteur3D:: operator == (Vecteur3D const& autre) const { return (autre.x == x && autre.y == y && autre.z == z); } bool Vecteur3D :: operator != (Vecteur3D const& autre) const { return !((*this) == autre); } bool Vecteur3D :: operator == (double c) const { return ((*this).norme() == c); } bool Vecteur3D :: operator != (double c) const { return !((*this) == c); } bool Vecteur3D :: operator < (double c) const { return ((*this).norme() < c); } bool Vecteur3D :: operator <= (double c) const { return ((*this) < c or (*this) == c); } bool Vecteur3D :: operator > (double c) const { return !((*this) < c); } bool Vecteur3D :: operator >= (double c) const { return ((*this) > c or (*this) == c); } Vecteur3D&Vecteur3D :: operator += (Vecteur3D const& autre) { x += autre.x; y += autre.y; z += autre.z; return (*this); } Vecteur3D&Vecteur3D :: operator -= (Vecteur3D const& autre) { x -= autre.x; y -= autre.y; z -= autre.z; return (*this); } Vecteur3D&Vecteur3D :: operator *= (double scalaire) { (*this).set_coord(x * scalaire, y * scalaire, z * scalaire); return (*this); } Vecteur3D&Vecteur3D :: operator += (double scalaire) { (*this).set_coord(x + scalaire, y + scalaire, z + scalaire); return (*this); } Vecteur3D&Vecteur3D :: operator = (double c) { set_coord(c, c, c); return (*this); } double Vecteur3D :: operator * (Vecteur3D const& vecteur) const // prod scalaire { return x * vecteur.x + y * vecteur.y + z * vecteur.z; } Vecteur3D Vecteur3D :: operator ^ (Vecteur3D const& vecteur) const // prod vectoriel { return Vecteur3D((y * vecteur.z - z * vecteur.y), (z * vecteur.x - x * vecteur.z), (x * vecteur.y - y * vecteur.x)); } // operateurs externe ostream&operator << (ostream &sortie, Vecteur3D const& vecteur) { vecteur.affiche(sortie); return sortie; } const Vecteur3D operator + (Vecteur3D vecteur, Vecteur3D const& autre) { return vecteur += autre; } const Vecteur3D operator * (double scalaire, Vecteur3D vecteur) { return vecteur *= scalaire; } const Vecteur3D operator * (Vecteur3D vecteur, double scalaire) { return vecteur *= scalaire; } const Vecteur3D operator / (Vecteur3D vecteur, double scalaire) { return vecteur *= (1 / scalaire); } const Vecteur3D operator - (Vecteur3D vecteur, Vecteur3D const& autre) { return vecteur -= autre; } const Vecteur3D operator * (arma::Mat<double> A, Vecteur3D vecteur) { double a1 = A(0, 0) * vecteur.x + A(0, 1) * vecteur.y + A(0, 2) * vecteur.z; double a2 = A(1, 0) * vecteur.x + A(1, 1) * vecteur.y + A(1, 2) * vecteur.z; double a3 = A(2, 0) * vecteur.x + A(2, 1) * vecteur.y + A(2, 2) * vecteur.z; return Vecteur3D(a1, a2, a3); }
22.89781
120
0.583201
YoussefSaied
257c2a8b0c80fb8b96fcf1f8d66bdc939336ad18
2,913
cpp
C++
solutions/integer-to-english-words/solution.cpp
locker/leetcode
bf34a697de47aaf32823224d054f9a45613ce180
[ "BSD-2-Clause-FreeBSD" ]
null
null
null
solutions/integer-to-english-words/solution.cpp
locker/leetcode
bf34a697de47aaf32823224d054f9a45613ce180
[ "BSD-2-Clause-FreeBSD" ]
null
null
null
solutions/integer-to-english-words/solution.cpp
locker/leetcode
bf34a697de47aaf32823224d054f9a45613ce180
[ "BSD-2-Clause-FreeBSD" ]
1
2019-08-30T06:53:23.000Z
2019-08-30T06:53:23.000Z
#include <cassert> #include <iostream> #include <string> #include <utility> using namespace std; class Solution { private: string numberLessThanTwentyToWord(int num) { assert(num >= 0); assert(num < 20); static const char *numToWord[] = { [0] = "Zero", [1] = "One", [2] = "Two", [3] = "Three", [4] = "Four", [5] = "Five", [6] = "Six", [7] = "Seven", [8] = "Eight", [9] = "Nine", [10] = "Ten", [11] = "Eleven", [12] = "Twelve", [13] = "Thirteen", [14] = "Fourteen", [15] = "Fifteen", [16] = "Sixteen", [17] = "Seventeen", [18] = "Eighteen", [19] = "Nineteen", }; return numToWord[num]; } string numberLessThanHundredToWords(int num) { assert(num >= 0); assert(num < 100); if (num < 20) return numberLessThanTwentyToWord(num); static const char *tensToWord[] = { [0] = nullptr, [1] = nullptr, [2] = "Twenty", [3] = "Thirty", [4] = "Forty", [5] = "Fifty", [6] = "Sixty", [7] = "Seventy", [8] = "Eighty", [9] = "Ninety", }; string result = tensToWord[num / 10]; num %= 10; if (num != 0) result += ' ' + numberLessThanTwentyToWord(num); return result; } string numberLessThanThousandToWords(int num) { assert(num >= 0); assert(num < 1000); if (num < 100) return numberLessThanHundredToWords(num); string result = numberLessThanTwentyToWord(num / 100) + " Hundred"; num %= 100; if (num != 0) result += ' ' + numberLessThanHundredToWords(num); return result; } public: string numberToWords(int num) { assert(num >= 0); string result; int milliards = num / 1000000000; if (milliards != 0) result += numberLessThanThousandToWords(milliards) + " Billion"; num %= 1000000000; int millions = num / 1000000; if (millions != 0) { if (!result.empty()) result += ' '; result += numberLessThanThousandToWords(millions) + " Million"; } num %= 1000000; int thousands = num / 1000; if (thousands != 0) { if (!result.empty()) result += ' '; result += numberLessThanThousandToWords(thousands) + " Thousand"; } num %= 1000; if (num != 0 || result.empty()) { if (!result.empty()) result += ' '; result += numberLessThanThousandToWords(num); } return result; } }; int main() { pair<int, string> test_data[] = { {0, "Zero"}, {1, "One"}, {2, "Two"}, {10, "Ten"}, {15, "Fifteen"}, {42, "Forty Two"}, {123, "One Hundred Twenty Three"}, {12345, "Twelve Thousand Three Hundred Forty Five"}, {1234567, "One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Seven"}, }; bool success = true; Solution solution; for (const auto& [num, expected] : test_data) { string result = solution.numberToWords(num); cout << num << " -> " << result << endl; if (result != expected) { cout << " ERROR: expected " << expected << endl; success = false; } } return success ? 0 : 1; }
22.937008
85
0.577755
locker
257e74fce27fd7bb75e222d8ca6989c8b88b5d53
11,541
cpp
C++
src/main/cpp/auton.cpp
RaidersRobotics5561/SwerveDrive2_2022
b21ecc272270b909ed58e65ce6e9241b99d85cc1
[ "BSD-3-Clause" ]
null
null
null
src/main/cpp/auton.cpp
RaidersRobotics5561/SwerveDrive2_2022
b21ecc272270b909ed58e65ce6e9241b99d85cc1
[ "BSD-3-Clause" ]
null
null
null
src/main/cpp/auton.cpp
RaidersRobotics5561/SwerveDrive2_2022
b21ecc272270b909ed58e65ce6e9241b99d85cc1
[ "BSD-3-Clause" ]
1
2022-02-02T01:45:57.000Z
2022-02-02T01:45:57.000Z
/* Auton.cpp Created on: Feb 28, 2021 Author: 5561 Changes: 2021-02-28 -> Beta */ #include <math.h> #include "control_pid.hpp" #include "Lookup.hpp" #include "Const.hpp" #include <frc/DriverStation.h> // #include "BallHandler.hpp" double distanceTarget; int theCoolerInteger; double V_autonTimer = 0; int V_autonState = 0; bool V_autonTargetCmd = false; bool V_autonTargetFin = false; /****************************************************************************** * Function: AutonMainController * * Description: Main calling function for the auton control. * ******************************************************************************/ void AutonDriveMain() { double timeleft = frc::DriverStation::GetInstance().GetMatchTime(); switch (theCoolerInteger){ case 1: if ((timeleft > 13) && (timeleft <= 15)){ //drive forward } else if ((timeleft > 9) && timeleft <= 13) { //auto pick up da balls function (+ some elevator) } else if ((timeleft > 7) && timeleft <= 9) { //rotate robot 180 degrees } else if ((timeleft > 5) && timeleft <= 7) { //auto align to shooter } else if ((timeleft > 0) && timeleft <= 5) { //shoot the balls (shooter + elevator) } } // switch (theCoolerInteger) // { // case 1: // if(timeleft > 8) // { // V_ShooterSpeedDesiredFinalUpper = -1400; // V_ShooterSpeedDesiredFinalLower = -1250; // // V_ShooterSpeedDesiredFinalUpper = DesiredUpperBeamSpeed(distanceTarget); // // V_ShooterSpeedDesiredFinalLower = DesiredLowerBeamSpeed(distanceTarget); // } // else // { // V_ShooterSpeedDesiredFinalUpper = 0; // V_ShooterSpeedDesiredFinalLower = 0; // } // V_ShooterSpeedDesired[E_rightShooter] = RampTo(V_ShooterSpeedDesiredFinalUpper, V_ShooterSpeedDesired[E_rightShooter], 50); // V_ShooterSpeedDesired[E_leftShooter] = RampTo(V_ShooterSpeedDesiredFinalLower, V_ShooterSpeedDesired[E_leftShooter], 50); // if(timeleft < 13 && timeleft > 8) // { // m_elevator.Set(ControlMode::PercentOutput, 0.420); // } // else // { // m_elevator.Set(ControlMode::PercentOutput, 0); // } // if(timeleft < 8 && timeleft > 4) // { // driveforward = (0.85); // } // break; // case 2: // if(timeleft > 10) // { // V_ShooterSpeedDesiredFinalUpper = DesiredUpperBeamSpeed(distanceTarget); // V_ShooterSpeedDesiredFinalLower = DesiredLowerBeamSpeed(distanceTarget); // } // else // { // V_ShooterSpeedDesiredFinalUpper = 0; // V_ShooterSpeedDesiredFinalLower = 0; // } // V_ShooterSpeedDesired[E_rightShooter] = RampTo(V_ShooterSpeedDesiredFinalUpper, V_ShooterSpeedDesired[E_rightShooter], 50); // V_ShooterSpeedDesired[E_leftShooter] = RampTo(V_ShooterSpeedDesiredFinalLower, V_ShooterSpeedDesired[E_leftShooter], 50); // if(timeleft < 14.5 && timeleft > 10) // { // m_elevator.Set(ControlMode::PercentOutput, 0.8); // } // else // { // m_elevator.Set(ControlMode::PercentOutput, 0); // } // if(timeleft < 15 && timeleft > 10) // { // driveforward = (0.420); // } // break; // case 3: // if(V_autonState == 0) // { // driveforward = (1); // V_autonTimer += C_ExeTime; // if (V_autonTimer >= 2){ // driveforward = (0); // V_autonState++; // V_autonTimer = 0; // } // } // else if(V_autonState == 1) // { // V_autonTargetCmd = true; // if (V_autonTargetFin == true){ // V_autonTargetCmd = false; // V_autonTargetFin = false; // V_autonState++; // } // } // else if(V_autonState == 2) // { // V_ShooterSpeedDesiredFinalUpper = DesiredUpperBeamSpeed(distanceTarget); // V_ShooterSpeedDesiredFinalLower = DesiredLowerBeamSpeed(distanceTarget); // V_ShooterSpeedDesired[E_rightShooter] = RampTo(V_ShooterSpeedDesiredFinalUpper, V_ShooterSpeedDesired[E_rightShooter], 50); // V_ShooterSpeedDesired[E_leftShooter] = RampTo(V_ShooterSpeedDesiredFinalLower, V_ShooterSpeedDesired[E_leftShooter], 50); // V_autonTimer += C_ExeTime; // if (V_autonTimer >= 1){ // V_autonState++; // V_autonTimer = 0; // } // } // else if (V_autonState == 3){ // V_elevatorValue = 0.8; // V_autonTimer += C_ExeTime; // if (V_autonTimer >= 1.5){ // V_elevatorValue = 0; // V_autonState++; // V_autonTimer = 0; // } // } // if(V_autonState == 4) // { // strafe = (-1.0); // V_ShooterSpeedDesiredFinalUpper = 0; // V_ShooterSpeedDesiredFinalLower = 0; // V_ShooterSpeedDesired[E_rightShooter] = RampTo(V_ShooterSpeedDesiredFinalUpper, V_ShooterSpeedDesired[E_rightShooter], 50); // V_ShooterSpeedDesired[E_leftShooter] = RampTo(V_ShooterSpeedDesiredFinalLower, V_ShooterSpeedDesired[E_leftShooter], 50); // V_autonTimer += C_ExeTime; // if (V_autonTimer >= 2){ // strafe = (0); // V_autonState++; // V_autonTimer = 0; // } // } // else if(V_autonState == 5) // { // V_autonTargetCmd = true; // if (V_autonTargetFin == true){ // V_autonTargetCmd = false; // V_autonTargetFin = false; // V_autonState++; // } // } // else if(V_autonState == 6) // { // V_ShooterSpeedDesiredFinalUpper = DesiredUpperBeamSpeed(distanceTarget); // V_ShooterSpeedDesiredFinalLower = DesiredLowerBeamSpeed(distanceTarget); // V_ShooterSpeedDesired[E_rightShooter] = RampTo(V_ShooterSpeedDesiredFinalUpper, V_ShooterSpeedDesired[E_rightShooter], 50); // V_ShooterSpeedDesired[E_leftShooter] = RampTo(V_ShooterSpeedDesiredFinalLower, V_ShooterSpeedDesired[E_leftShooter], 50); // V_autonTimer += C_ExeTime; // if (V_autonTimer >= 1){ // V_autonState++; // V_autonTimer = 0; // } // } // else if (V_autonState == 7){ // V_elevatorValue = 0.8; // V_autonTimer += C_ExeTime; // if (V_autonTimer >= 1.5){ // V_elevatorValue = 0; // V_autonState++; // V_autonTimer = 0; // } // } // if(V_autonState == 8) // { // V_ShooterSpeedDesiredFinalUpper = 0; // V_ShooterSpeedDesiredFinalLower = 0; // V_ShooterSpeedDesired[E_rightShooter] = RampTo(V_ShooterSpeedDesiredFinalUpper, V_ShooterSpeedDesired[E_rightShooter], 50); // V_ShooterSpeedDesired[E_leftShooter] = RampTo(V_ShooterSpeedDesiredFinalLower, V_ShooterSpeedDesired[E_leftShooter], 50); // strafe = (1.0); // V_autonTimer += C_ExeTime; // if (V_autonTimer >= 2){ // strafe = (0); // V_autonState++; // V_autonTimer = 0; // } // } // else if(V_autonState == 9) // { // V_autonTargetCmd = true; // if (V_autonTargetFin == true){ // V_autonTargetCmd = false; // V_autonTargetFin = false; // V_autonState++; // } // } // else if(V_autonState == 10) // { // V_ShooterSpeedDesiredFinalUpper = DesiredUpperBeamSpeed(distanceTarget); // V_ShooterSpeedDesiredFinalLower = DesiredLowerBeamSpeed(distanceTarget); // V_ShooterSpeedDesired[E_rightShooter] = RampTo(V_ShooterSpeedDesiredFinalUpper, V_ShooterSpeedDesired[E_rightShooter], 50); // V_ShooterSpeedDesired[E_leftShooter] = RampTo(V_ShooterSpeedDesiredFinalLower, V_ShooterSpeedDesired[E_leftShooter], 50); // V_autonTimer += C_ExeTime; // if (V_autonTimer >= 1){ // V_autonState++; // V_autonTimer = 0; // } // } // else if (V_autonState == 11){ // V_elevatorValue = 0.8; // V_autonTimer += C_ExeTime; // if (V_autonTimer >= 1.5){ // V_elevatorValue = 0; // V_autonState++; // V_autonTimer = 0; // } // } // else if(V_autonState == 12) // { // V_ShooterSpeedDesiredFinalUpper = 0; // V_ShooterSpeedDesiredFinalLower = 0; // V_ShooterSpeedDesired[E_rightShooter] = RampTo(V_ShooterSpeedDesiredFinalUpper, V_ShooterSpeedDesired[E_rightShooter], 50); // V_ShooterSpeedDesired[E_leftShooter] = RampTo(V_ShooterSpeedDesiredFinalLower, V_ShooterSpeedDesired[E_leftShooter], 50); // V_autonTimer += C_ExeTime; // if (V_autonTimer >= 1){ // V_autonState++; // V_autonTimer = 0; // } // } // else if(V_autonState == 13){ // speen = 1.0; // V_autonTimer += C_ExeTime; // if (V_autonTimer >= 3){ // speen = 0.0; // V_autonState++; // V_autonTimer = 0; // } // } // break; // case 4: // AutonDriveMain(&driveforward, // &strafe, // &speen, // V_M_RobotDisplacementY, // V_M_RobotDisplacementX, // V_GyroYawAngleDegrees, // 0); // // case 5 is expirimental, do not use for any real driving // // probably works // case 5 : // GyroZero(); // if(V_autonState == 0) // { // driveforward = (.7); // if (V_M_RobotDisplacementY <= -30.0){ // driveforward = (0.0); // V_autonState++; // } // } // else if(V_autonState == 1) // { // strafe = (.7); // if (V_M_RobotDisplacementX <= -30.0){ // strafe = (0.0); // V_autonState++; // } // } // else if(V_autonState == 2) // { // driveforward = (-.7); // if (V_M_RobotDisplacementY >= 0.0){ // driveforward = (0.0); // V_autonState++; // } // } // else if(V_autonState == 3) // { // strafe = (-.7); // if (V_M_RobotDisplacementX >= 0.0){ // strafe = (0.0); // } // } // break; // } }
34.044248
138
0.494585
RaidersRobotics5561
257f704e634247c7e4d0be070f88bb0dac9d8080
10,011
cpp
C++
FlexProxy/FlexServer/src/FlexServer/Forwarder.cpp
carlcc/FlexProxy
a9b6a11e44e75979409608317c19c3da7cc10def
[ "Apache-2.0" ]
null
null
null
FlexProxy/FlexServer/src/FlexServer/Forwarder.cpp
carlcc/FlexProxy
a9b6a11e44e75979409608317c19c3da7cc10def
[ "Apache-2.0" ]
null
null
null
FlexProxy/FlexServer/src/FlexServer/Forwarder.cpp
carlcc/FlexProxy
a9b6a11e44e75979409608317c19c3da7cc10def
[ "Apache-2.0" ]
null
null
null
#include "FlexServer/Forwarder.h" #include "FlexCommon/Log.h" #include "FlexCommon/MiscUtils.h" #include "FlexCommon/Time.h" #include <chrono> #define FORARDER_L_INFO(fmt, ...) L_INFO(fmt " ({})", ##__VA_ARGS__, id_) #define FORARDER_L_ERROR(fmt, ...) L_ERROR(fmt " ({})", ##__VA_ARGS__, id_) #define FORARDER_SCOPE_EXIT_INFO(fmt, ...) SCOPE_EXIT_INFO(fmt " ({})", ##__VA_ARGS__, id_) namespace FS { using namespace std::chrono_literals; static uint32_t gIdCounter = 0; Forwarder::Forwarder(asio::io_context& ioContext) : ioContext_ { ioContext } , udpSocket_ { ioContext } , tcpSocket_ { ioContext } , id_ { gIdCounter++ } { FORARDER_L_INFO("Construct forwarder"); } Forwarder::~Forwarder() { L_ASSERT(!isRunning_, "Bug!"); ikcp_release(kcpCb_); FORARDER_L_INFO("Destruct forwarder {}", (void*)this); } bool Forwarder::Start(const asio::ip::udp::endpoint& localUdpEndpoint, const asio::ip::udp::endpoint& remoteUdpEndpoint, const asio::ip::tcp::endpoint& remoteTcpEndpoint) { auto spThis = shared_from_this(); // Create udp socket boost::system::error_code ec; udpSocket_.open(localUdpEndpoint.protocol(), ec); if (ec.failed()) { FORARDER_L_ERROR("Failed to open udp address {}:{}: {}", localUdpEndpoint.address().to_string(), localUdpEndpoint.port(), ec.message()); return false; } udpSocket_.set_option(asio_udp::socket::reuse_address(true)); udpSocket_.bind(localUdpEndpoint, ec); if (ec.failed()) { FORARDER_L_ERROR("Failed to bind udp address {}:{}: {}", localUdpEndpoint.address().to_string(), localUdpEndpoint.port(), ec.message()); return false; } udpSocket_.connect(remoteUdpEndpoint, ec); if (ec.failed()) { FORARDER_L_ERROR("Failed to connect udp address {}:{}: {}", remoteUdpEndpoint.address().to_string(), remoteUdpEndpoint.port(), ec.message()); return false; } asio::spawn(ioContext_, [this, spThis, remoteTcpEndpoint](asio::yield_context yield) noexcept { FORARDER_SCOPE_EXIT_INFO("Forward start coroutine complete..."); // TODO: // Create tcp socket and connect boost::system::error_code ec; tcpSocket_.open(remoteTcpEndpoint.protocol(), ec); if (ec.failed()) { FORARDER_L_ERROR("Failed to open tcp socket: {}", ec.message()); return; } tcpSocket_.async_connect(remoteTcpEndpoint, yield[ec]); if (ec.failed()) { FORARDER_L_ERROR("Failed to connect to {}:{}: {}", remoteTcpEndpoint.address().to_string(), remoteTcpEndpoint.port(), ec.message()); return; } isRunning_ = true; asio::spawn(ioContext_, [this, spThis](asio::yield_context yield) noexcept { FORARDER_SCOPE_EXIT_INFO("tcp to kcp coroutine complete..."); // Receive from tcp, send to kcp boost::system::error_code ec; char receiveBufferMemory[4096]; auto receiveBuffer = asio::buffer(receiveBufferMemory, sizeof(receiveBufferMemory)); asio::steady_timer timer { ioContext_ }; while (isRunning_) { auto n = tcpSocket_.async_receive(receiveBuffer, yield[ec]); if (ec.failed()) { if (IsTryAgain(ec)) { continue; } FORARDER_L_ERROR("Failed to receive tcp: {}", ec.message()); Stop(); return; } ikcp_send(kcpCb_, receiveBufferMemory, (int)n); // 下面似乎会导致问题,git clone 拉代码时链接断开 // 1400 * (1024 * 10) = 14MB, the send buffer is about 14MB // wait data to be flushed, to avoid to many data in memory // while (ikcp_waitsnd(kcpCb_) > 1024 * 10) { // timer.expires_after(5ms); // timer.async_wait(yield[ec]); // if (ec.failed()) { // L_ASSERT(false, "Failed to async wait, should not happen!"); // abort(); // } // if (!isRunning_) { // return; // } // } } }); asio::spawn(ioContext_, [this, spThis](asio::yield_context yield) noexcept { FORARDER_SCOPE_EXIT_INFO("kcp to tcp coroutine complete..."); using namespace std::chrono; asio::steady_timer timer { ioContext_ }; boost::system::error_code ec; auto now = steady_clock::now(); char receiveBuffer[4 * 4096]; while (isRunning_) { ikcp_update(kcpCb_, (IUINT32)duration_cast<milliseconds>(now.time_since_epoch()).count()); do { // Try to read date from kcp, and forward to tcp auto n = ikcp_recv(kcpCb_, receiveBuffer, sizeof(receiveBuffer)); if (n <= 0) { break; } do { asio::async_write(tcpSocket_, asio::const_buffer(receiveBuffer, n), yield[ec]); if (ec.failed()) { if (IsTryAgain(ec)) { timer.expires_after(2ms); timer.async_wait(yield[ec]); continue; } FORARDER_L_INFO("Failed to write tcp: {}", ec.message()); Stop(); return; } break; } while (true); } while (true); timer.expires_at(now + 10ms); timer.async_wait(yield[ec]); if (ec.failed()) { L_ASSERT(false, "Unhandled error!"); return; } now = steady_clock::now(); } }); asio::spawn(ioContext_, [this, spThis](asio::yield_context yield) noexcept { FORARDER_SCOPE_EXIT_INFO("kcp feed coroutine complete..."); uint8_t receiveBufferMemory[4096]; auto receiveBuffer = asio::buffer(receiveBufferMemory, sizeof(receiveBufferMemory)); boost::system::error_code ec; while (isRunning_) { auto n = udpSocket_.async_receive(receiveBuffer, yield[ec]); if (ec.failed()) { if (IsTryAgain(ec)) { continue; } FORARDER_L_ERROR("Failed to receive udp: {}", ec.message()); Stop(); return; } isKcpAlive_ = true; #ifdef ENABLE_CHECK_SUM if (n > 1) { auto checkSum = MiscUtils::XorCheck((uint8_t*)receiveBufferMemory + 1, n - 1); if (checkSum == receiveBufferMemory[0]) { MiscUtils::Encrypt(receiveBufferMemory + 1, n - 1); ikcp_input(kcpCb_, (const char*)receiveBufferMemory + 1, (int)n - 1); } else { FORARDER_L_ERROR("Checksum error!"); } } else { FORARDER_L_ERROR("Invalid udp data!"); } #else MiscUtils::Encrypt(receiveBufferMemory , n); ikcp_input(kcpCb_, (const char*)receiveBufferMemory , (int)n); #endif } }); asio::spawn(ioContext_, [this, spThis](asio::yield_context yield) noexcept { FORARDER_SCOPE_EXIT_INFO("active timer coroutine complete..."); using namespace std::chrono; asio::steady_timer timer { ioContext_ }; boost::system::error_code ec; while (isRunning_) { timer.expires_after(5s); timer.async_wait(yield[ec]); L_ASSERT(!ec.failed(), "Bug unhandled error"); if (isKcpAlive_) { isKcpAlive_ = false; } else { FORARDER_L_INFO("The user is inactive for too long, close()"); Stop(); return; } } }); }); // create kcp callback kcpCb_ = ikcp_create(0x5a3331fd, this); kcpCb_->output = [](const char* buf, int len, ikcpcb* kcp, void* user) -> int { auto* self = reinterpret_cast<Forwarder*>(user); boost::system::error_code ec; MiscUtils::Encrypt((uint8_t*)buf, len); #ifdef ENABLE_CHECK_SUM auto checkSum = MiscUtils::XorCheck((const uint8_t*)buf, len); std::vector<asio::const_buffer> buffers { asio::const_buffer(&checkSum, 1), asio::const_buffer(buf, len), }; self->udpSocket_.send(buffers, 0, ec); #else self->udpSocket_.send(asio::const_buffer(buf, len), 0, ec); #endif return 0; }; ikcp_wndsize(kcpCb_, 1024, 1024); ikcp_nodelay(kcpCb_, 2, 10, 2, 1); return true; } void Forwarder::OnUdpData(const void* data, size_t len) { isKcpAlive_ = true; #ifdef ENABLE_CHECK_SUM if (len > 1) { auto* ptr = (uint8_t*)data; auto checkSum = MiscUtils::XorCheck(ptr + 1, len - 1); if (checkSum == ptr[0]) { MiscUtils::Encrypt(ptr + 1, len - 1); ikcp_input(kcpCb_, (const char*)ptr + 1, (int)len - 1); } else { FORARDER_L_ERROR("Checksum error!"); } // MiscUtils::Encrypt((uint8_t*)data, len); // ikcp_input(kcpCb_, (const char*)data, len); } #else MiscUtils::Encrypt((uint8_t*)data, len); ikcp_input(kcpCb_, (const char*)data, len); #endif } void Forwarder::Stop() { isRunning_ = false; boost::system::error_code ec; udpSocket_.close(ec); tcpSocket_.close(ec); } }
37.077778
149
0.528419
carlcc
257fb2ea69ae1ea1b16895697efcac76a15f6fb4
2,857
cpp
C++
thirdparty/ULib/examples/workflow/validation.cpp
liftchampion/nativejson-benchmark
6d575ffa4359a5c4230f74b07d994602a8016fb5
[ "MIT" ]
null
null
null
thirdparty/ULib/examples/workflow/validation.cpp
liftchampion/nativejson-benchmark
6d575ffa4359a5c4230f74b07d994602a8016fb5
[ "MIT" ]
null
null
null
thirdparty/ULib/examples/workflow/validation.cpp
liftchampion/nativejson-benchmark
6d575ffa4359a5c4230f74b07d994602a8016fb5
[ "MIT" ]
null
null
null
// validation.cpp #include <ulib/string.h> #undef PACKAGE #define PACKAGE "validation" #undef ARGS #define ARGS "" #define U_OPTIONS \ "purpose \"program for workflow validation...\"\n" \ "option c config 1 \"path of configuration file\" \"\"\n" #include "action.h" class Application : public Action { public: void run(int argc, char* argv[], char* env[]) { U_TRACE(5, "Application::run(%d,%p,%p)", argc, argv, env) Action::run(argc, argv, env); // read stdin and scanf Action::processInputData(2); // -------------------------------------------------------------------------------------------------------------- // configuration parameters // -------------------------------------------------------------------------------------------------------------- // SUBJECT_TEMPLATE scanf form to extract data from mail header Subject: // SEARCH_ENGINE_FOLDER_SEARCH_URL url to do query to search engine // -------------------------------------------------------------------------------------------------------------- UString subj_tmpl = cfg[U_STRING_FROM_CONSTANT("SUBJECT_TEMPLATE")], url = cfg[U_STRING_FROM_CONSTANT("SEARCH_ENGINE_FOLDER_SEARCH_URL")]; uint32_t subject = U_STRING_FIND(request, 0, "Subject: "); if (subject == U_NOT_FOUND) U_ERROR("cannot find mail header subject on input data"); // scanf mail header Subject: from request // ---------------------------------------------------------------------------------------------------------------------------- // "Subject: %*[^"]\"%[^"]\", %*[^"]\"%[^"]\", %*[^"]\"%[^"]\"" // ---------------------------------------------------------------------------------------------------------------------------- // Subject: Re: TUnwired processo di registrazione utente residenziale con CPE: // notifica produzione CPE cliente "workflow test", indirizzo installazione "Via Volturno, 12 50100 Firenze (FI)", // UID "37723e2d-d052-4c13-a1e9-134563eb9666" // ---------------------------------------------------------------------------------------------------------------------------- int n = U_SYSCALL(sscanf, "%S,%S,%p,%p,%p,%p", request.c_pointer(subject), subj_tmpl.data(), customer, installation, uid); if (n != 3) U_ERROR("scanf error on mail header subject"); U_INTERNAL_DUMP("sscanf() customer = %S installation = %S uid = %S", customer, installation, uid) // query to Search Engine UString body(10U + u__strlen(uid, __PRETTY_FUNCTION__)); body.snprintf(U_CONSTANT_TO_PARAM("query=%s"), uid); bool ok = Action::sendHttpPostRequest(url, body, "application/x-www-form-urlencoded", "1\n"); Action::writeToSTDOUT(ok, ok); } }; U_MAIN
40.239437
133
0.466923
liftchampion
257fc8096472fe90ab89ddd93e88157d474d9119
811
cpp
C++
leetcode/leetcode_0198_easy_house_robber/main.v01.cpp
friskit-china/leetcode-cn-repo
5f428e77f9d3f79da3e670a38b86d85bd58c81b2
[ "MIT" ]
null
null
null
leetcode/leetcode_0198_easy_house_robber/main.v01.cpp
friskit-china/leetcode-cn-repo
5f428e77f9d3f79da3e670a38b86d85bd58c81b2
[ "MIT" ]
null
null
null
leetcode/leetcode_0198_easy_house_robber/main.v01.cpp
friskit-china/leetcode-cn-repo
5f428e77f9d3f79da3e670a38b86d85bd58c81b2
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> using namespace std; class Solution { public: int rob(vector<int>& nums) { if (nums.size() == 0){ return 0; }else if (nums.size() == 1){ return nums[0]; }else if (nums.size() == 2){ return max(nums[0], nums[1]); } int result[nums.size() + 1]; result[0] = 0; result[1] = nums[0]; result[2] = max(nums[0], nums[1]); for (int i = 3; i < nums.size() + 1; ++i){ result[i] = max(result[i - 1], result[i - 2] + nums[i - 1]); } return result[nums.size()]; } }; int main(){ Solution sl; // vector<int> nums = {1, 2, 3, 1}; // 4 vector<int> nums = {2, 7, 9, 3, 1}; // 12 cout<<sl.rob(nums)<<endl; return 0; }
24.575758
72
0.454994
friskit-china
2580576a6f3cfa08a43f7f685f588146a186471e
1,666
cpp
C++
src/services/log.cpp
viniciusferrao/cloysterhpc
a7b51ce2e2110e21f2720a40d5b6a2c521158937
[ "Apache-2.0" ]
4
2021-10-10T22:38:54.000Z
2022-03-03T01:13:44.000Z
src/services/log.cpp
viniciusferrao/cloysterhpc
a7b51ce2e2110e21f2720a40d5b6a2c521158937
[ "Apache-2.0" ]
null
null
null
src/services/log.cpp
viniciusferrao/cloysterhpc
a7b51ce2e2110e21f2720a40d5b6a2c521158937
[ "Apache-2.0" ]
1
2021-10-30T20:29:27.000Z
2021-10-30T20:29:27.000Z
// // Created by Vinícius Ferrão on 23/11/21. // #include "log.h" #include <spdlog/sinks/stdout_color_sinks.h> #include <memory> void Log::init(Level level) { auto stderrSink = std::make_shared<spdlog::sinks::stderr_color_sink_mt>(); stderrSink->set_pattern("%^[%Y-%m-%d %H:%M:%S.%e] %v%$"); std::vector<spdlog::sink_ptr> sinks{stderrSink}; auto logger = std::make_shared<spdlog::logger>( productName, sinks.begin(), sinks.end()); switch (level) { case Log::Level::Trace: logger->set_level(spdlog::level::trace); logger->flush_on(spdlog::level::trace); break; case Log::Level::Debug: logger->set_level(spdlog::level::debug); logger->flush_on(spdlog::level::debug); break; case Log::Level::Info: logger->set_level(spdlog::level::info); logger->flush_on(spdlog::level::info); break; case Log::Level::Warn: logger->set_level(spdlog::level::warn); logger->flush_on(spdlog::level::warn); break; case Log::Level::Error: logger->set_level(spdlog::level::err); logger->flush_on(spdlog::level::err); break; case Log::Level::Critical: logger->set_level(spdlog::level::critical); logger->flush_on(spdlog::level::critical); break; case Log::Level::Off: logger->set_level(spdlog::level::off); logger->flush_on(spdlog::level::off); break; } spdlog::register_logger(logger); } void Log::shutdown() { spdlog::shutdown(); }
30.290909
78
0.567227
viniciusferrao
258671241fa45cb435baa3942436e876f0047ea6
1,683
hxx
C++
include/kry/Utility.hxx
rcgoodfellow/kry
29b0616d92c514b015eab4a93ad2c2c04d412190
[ "BSD-2-Clause" ]
null
null
null
include/kry/Utility.hxx
rcgoodfellow/kry
29b0616d92c514b015eab4a93ad2c2c04d412190
[ "BSD-2-Clause" ]
null
null
null
include/kry/Utility.hxx
rcgoodfellow/kry
29b0616d92c514b015eab4a93ad2c2c04d412190
[ "BSD-2-Clause" ]
null
null
null
/****************************************************************************** * libKrylov * ========= * Utility.hxx contians usefull stuff used throught libKrylov * * 19 August 2014 * ~ ry * ***************************************************************************/ #ifndef KRY_UTILITY_HXX #define KRY_UTILITY_HXX #include <string> #include <mm_malloc.h> #include <mutex> #include <condition_variable> #include <iostream> #define KRY_DEFAULT_ALIGN 64 #define CRIME_SCENE \ std::string(__FILE__) + std::string(":") + \ std::to_string(__LINE__) + \ std::string(":") + std::string(__func__) #define NON_CONFORMAL \ std::runtime_error("non-conformal operation:" + CRIME_SCENE); #define UNREAL \ std::runtime_error("unreal sparse matrix coordinates:" + CRIME_SCENE); #define OVERSTUFFED \ std::runtime_error("overstuffing sparse matrix row:" + CRIME_SCENE); #define BAD_COLRANGE \ std::runtime_error("bad column range:" + CRIME_SCENE); #define BAD_COLREF \ std::runtime_error("bad column reference:" + CRIME_SCENE); namespace kry { //Allocate a typed, aligned chunk of memory without havint to do the typecast //and sizeof math bit each time template<class T> T* alloc(size_t sz) { return (T*)_mm_malloc(sizeof(T)*sz, KRY_DEFAULT_ALIGN); } class CountdownLatch { public: CountdownLatch(int); void wait(); void set(int); void operator--(); void operator--(int); void operator++(); void operator++(int); int operator()() const; private: std::atomic<int> _cnt; std::shared_ptr<std::mutex> _mtx{new std::mutex}; std::shared_ptr<std::condition_variable> _cnd{new std::condition_variable}; }; } #endif
23.054795
79
0.63161
rcgoodfellow
25894e16fa3cb98e6c14015eae93fd0b1d2fbf80
727
hpp
C++
src/org/apache/poi/util/CloseIgnoringInputStream.hpp
pebble2015/cpoi
6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6
[ "Apache-2.0" ]
null
null
null
src/org/apache/poi/util/CloseIgnoringInputStream.hpp
pebble2015/cpoi
6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6
[ "Apache-2.0" ]
null
null
null
src/org/apache/poi/util/CloseIgnoringInputStream.hpp
pebble2015/cpoi
6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6
[ "Apache-2.0" ]
null
null
null
// Generated from /POI/java/org/apache/poi/util/CloseIgnoringInputStream.java #pragma once #include <java/io/fwd-POI.hpp> #include <org/apache/poi/util/fwd-POI.hpp> #include <java/io/FilterInputStream.hpp> struct default_init_tag; class poi::util::CloseIgnoringInputStream : public ::java::io::FilterInputStream { public: typedef ::java::io::FilterInputStream super; protected: void ctor(::java::io::InputStream* in); public: void close() override; // Generated CloseIgnoringInputStream(::java::io::InputStream* in); protected: CloseIgnoringInputStream(const ::default_init_tag&); public: static ::java::lang::Class *class_(); private: virtual ::java::lang::Class* getClass0(); };
20.771429
77
0.716644
pebble2015
259210636ee812b511e7b876d9b48592722bfc9b
644
cpp
C++
src/v8-extensions/array-buffer-allocator.cpp
localh0rzd/napajs
b3f5e67dd20caef5d96ea8c3e3d4c542fcb9a431
[ "MIT" ]
9,088
2017-08-08T22:28:16.000Z
2019-05-05T14:57:12.000Z
src/v8-extensions/array-buffer-allocator.cpp
localh0rzd/napajs
b3f5e67dd20caef5d96ea8c3e3d4c542fcb9a431
[ "MIT" ]
172
2017-08-09T21:32:15.000Z
2019-05-03T21:21:05.000Z
src/v8-extensions/array-buffer-allocator.cpp
localh0rzd/napajs
b3f5e67dd20caef5d96ea8c3e3d4c542fcb9a431
[ "MIT" ]
370
2017-08-09T04:58:14.000Z
2019-04-13T18:59:29.000Z
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. #include "v8-extensions-macros.h" #if !(V8_VERSION_CHECK_FOR_ARRAY_BUFFER_ALLOCATOR) #include "array-buffer-allocator.h" #include <cstring> #include <stdlib.h> #include <v8.h> using namespace napa::v8_extensions; void* ArrayBufferAllocator::Allocate(size_t length) { void* data = AllocateUninitialized(length); return std::memset(data, 0, length); } void* ArrayBufferAllocator::AllocateUninitialized(size_t length) { return malloc(length); } void ArrayBufferAllocator::Free(void* data, size_t length) { free(data); } #endif
22.206897
66
0.748447
localh0rzd
25936507865b3b7a0913e35ff5badc10e553c8b4
783
hpp
C++
FlicsFacts/Controller/shareresponsesformatter.hpp
pgulotta/FlicsFacts-2
a4c5cccd839793478d46e6eb32ef1233a9c723ae
[ "MIT" ]
null
null
null
FlicsFacts/Controller/shareresponsesformatter.hpp
pgulotta/FlicsFacts-2
a4c5cccd839793478d46e6eb32ef1233a9c723ae
[ "MIT" ]
null
null
null
FlicsFacts/Controller/shareresponsesformatter.hpp
pgulotta/FlicsFacts-2
a4c5cccd839793478d46e6eb32ef1233a9c723ae
[ "MIT" ]
null
null
null
#pragma once #include "../FlicsFacts/fam/qqmlobjectlistmodel.hpp" #include <../FlicsFacts/Model/movieresponse.hpp> #include <QObject> #include <vector> #include <iterator> #include <memory> class QString; class ShareResponsesFormatter final : public QObject { Q_OBJECT public slots: signals: public: explicit ShareResponsesFormatter( QObject* parent = nullptr ); explicit ShareResponsesFormatter( const ShareResponsesFormatter& rhs ) = delete; ShareResponsesFormatter& operator= ( const ShareResponsesFormatter& rhs ) = delete; QString formatAsText( QQmlObjectListModel<MovieResponse>::const_iterator begin, QQmlObjectListModel<MovieResponse>::const_iterator end ); private: QString mFormattedResponses; };
24.46875
86
0.733078
pgulotta
25968da7615c317e9215785ac7dc7cdd982ca6a2
6,041
cc
C++
src/monitor.cc
sails/saf
0af8ab73062e8c2adbb3412533cc64a0b291b7d6
[ "MIT" ]
8
2015-01-26T20:03:35.000Z
2022-03-22T14:32:48.000Z
src/monitor.cc
sails/saf
0af8ab73062e8c2adbb3412533cc64a0b291b7d6
[ "MIT" ]
null
null
null
src/monitor.cc
sails/saf
0af8ab73062e8c2adbb3412533cc64a0b291b7d6
[ "MIT" ]
9
2015-05-22T03:28:20.000Z
2022-03-23T08:59:57.000Z
// Copyright (C) 2014 sails Authors. // All rights reserved. // // Official git repository and contact information can be found at // https://github.com/sails/sails and http://www.sailsxu.com/. // // Filename: monitor.cc // // Author: sailsxu <sailsxu@gmail.com> // Created: 2014-10-20 17:14:50 #include "src/monitor.h" #include <string> #include <vector> #ifdef __linux__ #include "sails/system/cpu_usage.h" #endif #include "sails/system/mem_usage.h" #include "src/service_register.h" #include "cpptempl/src/cpptempl.h" namespace sails { void ServerStatProcessor::serverstat(sails::net::HttpRequest*, sails::net::HttpResponse* response) { cpptempl::auto_data dict; pid_t pid = getpid(); dict["PID"] = pid; dict["PORT"] = server->ListenPort(); // cpu info #ifdef __linux__ double cpu = 0; if (sails::system::GetProcessCpuUsage(pid, 100, &cpu)) { dict["CPU"] = cpu; } #endif // memory info uint64_t vm_size, mem_size; if (sails::system::GetMemoryUsedKiloBytes(pid, &vm_size, &mem_size)) { dict["VMSIZE"] = (int64_t)vm_size; dict["MEMSIZE"] = (int64_t)mem_size; } char run_mode[2]; snprintf(run_mode, sizeof(run_mode), "%d", server->RunMode()); dict["run_mode"] = run_mode; dict["recv_queue_size"] = (int64_t)server->GetRecvDataNum(); // 网络线程信息 dict["NetThreadNum"] = (int64_t)server->NetThreadNum(); for (size_t i = 0; i < server->NetThreadNum(); i++) { cpptempl::auto_data netthread_dict; net::NetThread<sails::ReqMessage>::NetThreadStatus netstatus = server->GetNetThreadStatus(i); netthread_dict["NetThread_NO"] = i; netthread_dict["NetThread_status"] = netstatus.status; netthread_dict["NetThread_connector_num"] = netstatus.connector_num; netthread_dict["NetThread_accept_times"] = (int64_t)netstatus.accept_times; netthread_dict["NetThread_reject_times"] = (int64_t)netstatus.reject_times; netthread_dict["NetThread_send_queue_capacity"] = (int64_t)netstatus.send_queue_capacity; netthread_dict["NetThread_send_queue_size"] = (int64_t)netstatus.send_queue_size; dict["net_threads"].push_back(netthread_dict); } // 处理线程信息 dict["HandleThreadNum"] = (int64_t)server->HandleThreadNum(); for (size_t i = 0; i < server->HandleThreadNum(); i++) { cpptempl::auto_data handlethread_dict; net::HandleThread<sails::ReqMessage>::HandleThreadStatus handlestatus = server->GetHandleThreadStatus(i); handlethread_dict["HandleThread_NO"] = i; handlethread_dict["HandleThread_status"] = handlestatus.status; handlethread_dict["HandleThread_handle_times"] = (int64_t)handlestatus.handle_times; if (server->RunMode() == 2) { handlethread_dict["HandleThread_handle_queue_capacity"] = (int64_t)handlestatus.handle_queue_capacity; handlethread_dict["HandleThread_handle_queue_size"] = (int64_t)handlestatus.handle_queue_size; } dict["handle_threads"].push_back(handlethread_dict); } // service std::vector<ServiceRegister::ServiceStat> services = ServiceRegister::instance()->GetAllServiceStat(); dict["serivcesNum"] = services.size(); for (size_t i = 0; i < services.size(); ++i) { cpptempl::auto_data service_dict; service_dict["serviceName"] = services[i].name; service_dict["callTimes"] = (int64_t)services[i].call_times; service_dict["failedTimes"] = (int64_t)services[i].failed_times; service_dict["successTimes"] = (int64_t)services[i].success_times; service_dict["io_in"] = (int64_t)services[i].io_in; service_dict["io_out"] = (int64_t)services[i].io_out; for (int index = 0; index < 11; index++) { char time_name[5] = {"\0"}; snprintf(time_name, sizeof(time_name), "L%d", index); service_dict[std::string(time_name)] = services[i].spendTime[index]; } dict["services"].push_back(service_dict); } FILE* file = fopen("../static/stat.html", "r"); if (file == NULL) { printf("can't open file\n"); } static std::string fileconent = ""; static time_t lastReloadTime = time(NULL); bool reloadFile = true; if (fileconent.length() > 0) { // 已经有内容了 time_t now = time(NULL); if (now - lastReloadTime < 60) { // 一分钟重新加载一次 reloadFile = false; } } if (reloadFile) { lastReloadTime = time(NULL); char buf[5000] = {'\0'}; int readNum = fread(buf, 1, 5000, file); fileconent = std::string(buf, readNum); } std::string body = cpptempl::parse(fileconent, dict); response->SetBody(body.c_str(), body.size()); } void ServerStatProcessor::index(sails::net::HttpRequest*, sails::net::HttpResponse* response) { response->SetBody("saf index"); } Monitor::Monitor(sails::Server* server, int port) { thread = NULL; status = Monitor::STOPING; isTerminate = false; this->server = server; this->port = port; } Monitor::~Monitor() { if (processor != NULL) { delete processor; processor = NULL; } if (thread != NULL) { Terminate(); Join(); } if (http_server != NULL) { delete http_server; http_server = NULL; } } void Monitor::Run() { isTerminate = false; thread = new std::thread(Start, this); status = Monitor::RUNING; } void Monitor::Terminate() { http_server->Stop(); isTerminate = true; } void Monitor::Join() { if (thread != NULL) { thread->join(); status = Monitor::STOPING; delete thread; thread = NULL; } } void Monitor::Start(Monitor* monitor) { monitor->http_server = new sails::net::HttpServer(); monitor->http_server->Init(monitor->port, 1, 10, 1); monitor->http_server->SetStaticResourcePath(std::string("../static/")); // 请求处理器与url映射 monitor->processor = new ServerStatProcessor(monitor->server); HTTPBIND(monitor->http_server, "/stat", monitor->processor, ServerStatProcessor::serverstat); HTTPBIND(monitor->http_server, "/", monitor->processor, ServerStatProcessor::index); while (!monitor->isTerminate) { sleep(1); } } } // namespace sails
29.183575
79
0.673398
sails
259824b9db342cd728f1885ec099400f396493b3
622
cpp
C++
AtCoder/ABC/ABC-134/SolveE.cpp
MonadicDavidHuang/CompetitiveProgramming
b5b6f39a1be05d257f8ea8e504dd910cc624b153
[ "MIT" ]
null
null
null
AtCoder/ABC/ABC-134/SolveE.cpp
MonadicDavidHuang/CompetitiveProgramming
b5b6f39a1be05d257f8ea8e504dd910cc624b153
[ "MIT" ]
null
null
null
AtCoder/ABC/ABC-134/SolveE.cpp
MonadicDavidHuang/CompetitiveProgramming
b5b6f39a1be05d257f8ea8e504dd910cc624b153
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; using ll = long long int; const int MAX = (int)(1e5 + 5); const ll INF = (ll)(1e10 + 5); const int MAX_N = (int)(1e5 + 5); int n; ll a[MAX_N]; multiset<ll> mst; int main(void) { // Here your code ! scanf("%d", &n); for (int i = 0; i < n; ++i) { scanf("%lld", &(a[i])); } for (int i = 0; i < n; ++i) { auto ptr = mst.upper_bound(a[i] - 1); if (mst.empty() || ptr == mst.begin()) { mst.insert(a[i]); continue; } auto prv = prev(ptr); mst.erase(prv); mst.insert(a[i]); } printf("%d\n", mst.size()); return 0; }
15.170732
44
0.506431
MonadicDavidHuang
259a5971339ae9b32e8c52e42993b4f7fd252dca
2,832
cpp
C++
chatroom/server.cpp
huangsunyang/shiyanlou
0b42f783d6aae639c1b0c2a33883a94e127038f7
[ "MIT" ]
30
2017-05-24T06:24:29.000Z
2020-12-18T11:09:53.000Z
chatroom/server.cpp
huangsunyang/shiyanlou
0b42f783d6aae639c1b0c2a33883a94e127038f7
[ "MIT" ]
null
null
null
chatroom/server.cpp
huangsunyang/shiyanlou
0b42f783d6aae639c1b0c2a33883a94e127038f7
[ "MIT" ]
15
2017-05-24T06:24:33.000Z
2020-04-21T11:32:36.000Z
#include "utility.h" int main() { struct sockaddr_in serverAddr; serverAddr.sin_family = PF_INET; serverAddr.sin_port = htons(SERVER_PORT); serverAddr.sin_addr.s_addr = inet_addr(SERVER_IP); int listener = socket(PF_INET, SOCK_STREAM, 0); if (listener < 0) { perror("Listener"); exit(-1); } std::cout << "Listen socket created" << std::endl; if (bind(listener, (struct sockaddr *)&serverAddr, sizeof(serverAddr)) < 0) { perror("bind error"); exit(-1); } int ret = listen(listener, 5); if (ret < 0) { perror("listen error"); exit(-1); } std::cout << "Start to listen" << std::endl; int epfd = epoll_create(EPOLL_SIZE); if (epfd < 0) { perror("epfd error"); exit(-1); } std::cout << "epoll created. epollfd = " << epfd; static struct epoll_event events[EPOLL_SIZE]; addfd(epfd, listener, true); while (true) { int epoll_events_count = epoll_wait(epfd, events, EPOLL_SIZE, -1); if (epoll_events_count < 0) { perror("epoll failure"); break; } std::cout <<"epoll_enents_count = " << epoll_events_count << std::endl; for (int i = 0; i < epoll_events_count; i++) { int sockfd = events[i].data.fd; if (sockfd == listener) { struct sockaddr_in client_address; socklen_t client_addrLength = sizeof(struct sockaddr_in); int clientfd = accept(listener, (struct sockaddr*) &client_address, &client_addrLength); std::cout << "client connection from" << inet_ntoa(client_address.sin_addr) << " :" << ntohs(client_address.sin_port) << "(IP:PORT), clientfd = " << clientfd << std::endl; addfd(epfd, clientfd, true); clients_list.push_back(clientfd); std::cout << "add new clientfd = " << clientfd << " to epoll" << std::endl; std::cout << "Now there are " << clients_list.size() << "clients in the chat room" << std::endl; std::cout << "weoclome message" << std::endl; char message[BUF_SIZE]; bzero(message, BUF_SIZE); sprintf(message, SERVER_WELCOME, clientfd); int ret = send(clientfd, message, BUF_SIZE, 0); if (ret < 0) { perror("send error"); exit (-1); } } else { int ret = sendBroadcastmessage(sockfd); if (ret < 0) { perror("send error"); exit (-1); } } } } close(listener); close(epfd); return 0; }
30.782609
112
0.509181
huangsunyang
259f1e13786bfbe41bb48dcc949b9c0d102b8fa2
538
cpp
C++
Acun3D/Spotlight.cpp
Catchouli-old/Acun3D
1a34791d30528a442d9734de31b0bcac86cb32d5
[ "MIT" ]
1
2018-11-15T18:53:44.000Z
2018-11-15T18:53:44.000Z
Acun3D/Spotlight.cpp
Catchouli-old/Acun3D
1a34791d30528a442d9734de31b0bcac86cb32d5
[ "MIT" ]
null
null
null
Acun3D/Spotlight.cpp
Catchouli-old/Acun3D
1a34791d30528a442d9734de31b0bcac86cb32d5
[ "MIT" ]
null
null
null
#include "Spotlight.h" namespace a3d { Spotlight::Spotlight(Vector position, Vector direction, Colour colour, float fov, float exponent) : Light(LightTypes::SPOT, colour), _position(position), _direction(direction), _fov(fov), _exponent(exponent) { } const Vector& Spotlight::getPosition() const { return _position; } const Vector& Spotlight::getDirection() const { return _direction; } float Spotlight::getFOV() const { return _fov; } float Spotlight::getExponent() const { return _exponent; } }
17.354839
98
0.702602
Catchouli-old
25a52f3c5a1d23b4e36fd418256f4e2482cf130a
1,709
hh
C++
aegir-brewd/src/GPIO.hh
gczuczy/aegir
1275ca41bfe4a56347eb2531211df4c70933fb96
[ "BSD-3-Clause" ]
null
null
null
aegir-brewd/src/GPIO.hh
gczuczy/aegir
1275ca41bfe4a56347eb2531211df4c70933fb96
[ "BSD-3-Clause" ]
11
2020-06-04T20:31:02.000Z
2022-02-26T01:39:26.000Z
aegir-brewd/src/GPIO.hh
gczuczy/aegir
1275ca41bfe4a56347eb2531211df4c70933fb96
[ "BSD-3-Clause" ]
1
2020-12-10T19:19:41.000Z
2020-12-10T19:19:41.000Z
/* Basic C++ wrapper for libgpio */ #ifndef GPIO_HH #define GPIO_HH #include <sys/types.h> #include <libgpio.h> #include <string> #include <map> #include <vector> #include "Exception.hh" namespace aegir { enum class PINState: uint8_t { Off=0, On=1, Pulsate=2, Unknown=255 }; class GPIO { GPIO() = delete; GPIO(GPIO &&) = delete; GPIO(const GPIO &) = delete; GPIO &operator=(GPIO &&) = delete; GPIO &operator=(const GPIO &) = delete; private: GPIO(int _unit); GPIO(const std::string _device); public: static GPIO *getInstance(); ~GPIO(); // PIN class for pin access class PIN { friend GPIO; PIN() = delete; protected: PIN(GPIO &_gpio, int _pin); private: GPIO &c_gpio; int c_pin; public: ~PIN(); PIN &input(); PIN &output(); PIN &high(); PIN &low(); PIN &toggle(); PIN &pullup(); PIN &pulldown(); PIN &opendrain(); PIN &tristate(); PINState get(); inline int getID() const { return c_pin; }; private: // In this app we don't need setname to be public, // because names are set up from Config PIN &setname(const std::string &); }; friend GPIO::PIN; // public functions PIN &operator[](const int _pin); PIN &operator[](const std::string &_name); std::vector<std::string> getPinNames() const; protected: gpio_handle_t c_handle; void setname(int _pin, const std::string &_name); private: static GPIO *c_instance; std::map<int, PIN> c_pins; std::map<std::string, int> c_names; void fetchpins(); void rewire(); }; } #endif
18.78022
56
0.574605
gczuczy
25a5464f1646714e89d1f2238694da8a8850d8d1
3,798
cpp
C++
Space Harrier Clone/GameScene.cpp
BrunoAOR/Space-Harrier-Clone
35465ad2d421f69a75a02855627c8ea726b248c6
[ "MIT" ]
12
2018-12-07T16:05:02.000Z
2021-09-06T01:46:50.000Z
Space Harrier Clone/GameScene.cpp
BrunoAOR/Space-Harrier-Clone
35465ad2d421f69a75a02855627c8ea726b248c6
[ "MIT" ]
null
null
null
Space Harrier Clone/GameScene.cpp
BrunoAOR/Space-Harrier-Clone
35465ad2d421f69a75a02855627c8ea726b248c6
[ "MIT" ]
1
2020-06-03T03:37:27.000Z
2020-06-03T03:37:27.000Z
#include "GameScene.h" #include "Engine/API.h" #include "Engine/GameObject.h" #include "Engine/Transform.h" #include "Engine/Behaviour.h" #include "Engine/Sprite.h" #include "Engine/Vector2.h" #include "gameData.h" #include "FloorManager.h" #include "DarkLineinfo.h" #include "FloorObjectsFactory.h" #include "BackgroundScroller.h" #include "PlayerPrefab.h" #include "Player.h" #include "EnemiesFactory.h" #include "EnemySpawnInfo.h" #include "MotionPattern.h" #include "ObstacleSpawnInfo.h" #include "UIManager.h" #include "Ranking.h" #include "SceneFader.h" #include "GameSceneMusicManager.h" bool GameScene::load() { Audio::setSFXVolume(0.25f); { auto go = Prefabs::instantiate(Prefabs::getPrefab(SCENE_FADER_PREFAB)); assert(go); auto sceneFader = go->getComponent<SceneFader>(); assert(sceneFader); sceneFader->init(0, SDL_Color{ 0, 0, 0, 255 }, 200, 100, 0, true); } auto worldGO = GameObject::createNew(); if (worldGO) { auto musicManager = worldGO->addComponent<GameSceneMusicManager>(); assert(musicManager); worldGO->transform->setWorldPosition(Vector2(SCREEN_WIDTH / 2.0f, 0)); auto floorManagerGo = GameObject::createNew(); if (floorManagerGo) { floorManagerGo->transform->setParent(worldGO->transform, false); auto floorManager = floorManagerGo->addComponent<FloorManager>(); if (floorManager) { floorManager->init(ASSET_IMG_FLOOR_GREEN); } auto playerGo = Prefabs::instantiate(Prefabs::getPrefab(PLAYER_PREFAB)); if (playerGo) { playerGo->transform->setParent(worldGO->transform, false); Reference<Player>& player = playerGo->getComponent<Player>(); if (player) { player->floorManager = floorManager; } auto enemiesFactoryGo = GameObject::createNew(); if (enemiesFactoryGo) { enemiesFactoryGo->transform->setParent(worldGO->transform, false); auto enemiesFactory = enemiesFactoryGo->addComponent<EnemiesFactory>(); if (enemiesFactory) { enemiesFactory->init(player->getCharacterTransform(), floorManager, getEnemiesSpawnInfo(), getMotionPatterns()); } } } auto objectsFactoryGo = GameObject::createNew(); if (objectsFactoryGo) { objectsFactoryGo->transform->setParent(worldGO->transform, false); auto floorObjectsFactory = objectsFactoryGo->addComponent<FloorObjectsFactory>(); if (floorObjectsFactory) { floorObjectsFactory->init(floorManager, getObstaclesSpawnInfo()); } } // True background auto backgroundScrollerGo = GameObject::createNew(); if (backgroundScrollerGo) { auto backgroundScroller = backgroundScrollerGo->addComponent<BackgroundScroller>(); if (backgroundScroller) { backgroundScroller->init(floorManager, ASSET_IMG_BACKGROUND, 0, -3); } } // Mountains auto backgroundScrollerGoMountains = GameObject::createNew(); if (backgroundScrollerGoMountains) { auto backgroundScroller = backgroundScrollerGoMountains->addComponent<BackgroundScroller>(); if (backgroundScroller) { backgroundScroller->init(floorManager, ASSET_IMG_BG_MOUNTAINS, 0.3f, -2); } } // Grass auto backgroundScrollerGoTrees = GameObject::createNew(); if (backgroundScrollerGoTrees) { auto backgroundScroller = backgroundScrollerGoTrees->addComponent<BackgroundScroller>(); if (backgroundScroller) { backgroundScroller->init(floorManager, ASSET_IMG_BG_TREES, 0.6f, -1); } } } auto uiGo = GameObject::createNew(); if (uiGo) { uiGo->transform->setWorldPosition(Vector2(0, 0)); auto uiManager = uiGo->addComponent<UIManager>(); auto ranking = uiGo->addComponent<Ranking>(); assert(uiManager && ranking); uiManager->init(ranking); } } return true; } void GameScene::unload() { }
26.193103
118
0.71169
BrunoAOR
25aa44984a1a5b6a8455e2cc7912cf0c0bf3cc3e
617
hpp
C++
Include/Injector/Graphics/Pipeline/DiffuseGpuPipeline.hpp
InjectorGames/Inject
09e74a83c287b81fd8272c10d6bae2b1aa785c0e
[ "BSD-3-Clause" ]
2
2019-12-10T16:26:58.000Z
2020-04-17T11:47:42.000Z
Include/Injector/Graphics/Pipeline/DiffuseGpuPipeline.hpp
InjectorGames/Inject
09e74a83c287b81fd8272c10d6bae2b1aa785c0e
[ "BSD-3-Clause" ]
28
2020-08-17T12:39:50.000Z
2020-11-16T20:42:50.000Z
Include/Injector/Graphics/Pipeline/DiffuseGpuPipeline.hpp
InjectorGames/InjectorEngine
09e74a83c287b81fd8272c10d6bae2b1aa785c0e
[ "BSD-3-Clause" ]
null
null
null
#pragma once #include "Injector/Mathematics/Vector4.hpp" namespace Injector { class DiffuseGpuPipeline { public: virtual const FloatVector4& getObjectColor() const = 0; virtual void setObjectColor(const FloatVector4& color) = 0; virtual const FloatVector4& getAmbientColor() const = 0; virtual void setAmbientColor(const FloatVector4& color) = 0; virtual const FloatVector4& getLightColor() const = 0; virtual void setLightColor(const FloatVector4& color) = 0; virtual const FloatVector3& getLightDirection() const = 0; virtual void setLightDirection(const FloatVector3& direction) = 0; }; }
28.045455
68
0.76175
InjectorGames
25ac395c76e5e39c1b36fe24d38740f89cb5553e
1,916
cpp
C++
runtime/thread/semaphore.cpp
braiam/ROCm-OpenCL-Runtime
a66edda66d98923e61fe97596c632eac743e63ed
[ "MIT" ]
1
2021-11-11T04:11:32.000Z
2021-11-11T04:11:32.000Z
runtime/thread/semaphore.cpp
braiam/ROCm-OpenCL-Runtime
a66edda66d98923e61fe97596c632eac743e63ed
[ "MIT" ]
null
null
null
runtime/thread/semaphore.cpp
braiam/ROCm-OpenCL-Runtime
a66edda66d98923e61fe97596c632eac743e63ed
[ "MIT" ]
1
2021-11-11T04:11:26.000Z
2021-11-11T04:11:26.000Z
// // Copyright (c) 2008,2010 Advanced Micro Devices, Inc. All rights reserved. // #include "thread/semaphore.hpp" #include "thread/thread.hpp" #if defined(_WIN32) || defined(__CYGWIN__) #include <windows.h> #else // !_WIN32 #include <semaphore.h> #include <errno.h> #endif // !_WIN32 namespace amd { Semaphore::Semaphore() : state_(0) { #ifdef _WIN32 handle_ = static_cast<void*>(CreateSemaphore(NULL, 0, LONG_MAX, NULL)); assert(handle_ != NULL && "CreateSemaphore failed"); #else // !_WIN32 if (sem_init(&sem_, 0, 0) != 0) { fatal("sem_init() failed"); } #endif // !_WIN32 } Semaphore::~Semaphore() { #ifdef _WIN32 if (!CloseHandle(static_cast<HANDLE>(handle_))) { fatal("CloseHandle() failed"); } #else // !_WIN32 if (sem_destroy(&sem_) != 0) { fatal("sem_destroy() failed"); } #endif // !WIN32 } void Semaphore::post() { int state = state_.load(std::memory_order_relaxed); for (;;) { if (state > 0) { int newstate = state_.load(std::memory_order_acquire); if (state == newstate) { return; } state = newstate; continue; } if (state_.compare_exchange_weak(state, state + 1, std::memory_order_acq_rel, std::memory_order_acquire)) { break; } } if (state < 0) { // We have threads waiting on this event. #ifdef _WIN32 ReleaseSemaphore(static_cast<HANDLE>(handle_), 1, NULL); #else // !_WIN32 if (0 != sem_post(&sem_)) { fatal("sem_post() failed"); } #endif // !_WIN32 } } void Semaphore::wait() { if (state_-- > 0) { return; } #ifdef _WIN32 if (WAIT_OBJECT_0 != WaitForSingleObject(static_cast<HANDLE>(handle_), INFINITE)) { fatal("WaitForSingleObject failed"); } #else // !_WIN32 while (0 != sem_wait(&sem_)) { if (EINTR != errno) { fatal("sem_wait() failed"); } } #endif // !_WIN32 } } // namespace amd
21.772727
85
0.608038
braiam
25ad3c8caffa3d545b376fdebb96c1aa69f8aee2
798
hpp
C++
src/ast/include/unary_operation_expr.hpp
bfeip/Lain
3df115167dbb0eb8147b225a24bb72b6c0920c64
[ "MIT" ]
5
2017-03-28T00:36:54.000Z
2019-08-06T00:05:44.000Z
src/ast/include/unary_operation_expr.hpp
bfeip/Lain
3df115167dbb0eb8147b225a24bb72b6c0920c64
[ "MIT" ]
4
2017-03-28T01:36:05.000Z
2017-04-17T20:34:46.000Z
src/ast/include/unary_operation_expr.hpp
bfeip/Lain
3df115167dbb0eb8147b225a24bb72b6c0920c64
[ "MIT" ]
null
null
null
#ifndef UNARY_OPERATION_EXPR_HPP #define UNARY_OPERATION_EXPR_HPP #include "ast_shared.hpp" #include "expr.hpp" #include "operation_type.hpp" class UnaryOperationExpr : virtual public Expr { private: std::unique_ptr<Expr> operand; OperationType op; public: UnaryOperationExpr() = delete; UnaryOperationExpr(ScopeCreator* owner, Expr* pe, std::unique_ptr<Expr>&& expr, OperationType ot) : Stmt(owner), Expr(owner, pe), operand(std::move(expr)), op(ot) {} virtual ~UnaryOperationExpr() = default; Expr* getOperand() { return operand.get(); } const Expr* getOperand() const { return operand.get(); } void setOperand(std::unique_ptr<Expr>&& expr) { operand = std::move(expr); } OperationType getOp() const { return op; } void setOp(OperationType ot) { op = ot; } }; #endif
29.555556
101
0.716792
bfeip
25ae0da3413de84735a70c76d68d862e6525e0ae
2,303
cpp
C++
products/gooeyfi_core/src/GooeyFiButton.cpp
cbtek/GooeyFi
f900d8465959f3ad73d2d4d528091afbe7570bb7
[ "MIT" ]
1
2018-01-23T14:59:28.000Z
2018-01-23T14:59:28.000Z
products/gooeyfi_core/src/GooeyFiButton.cpp
cbtek/GooeyFi
f900d8465959f3ad73d2d4d528091afbe7570bb7
[ "MIT" ]
null
null
null
products/gooeyfi_core/src/GooeyFiButton.cpp
cbtek/GooeyFi
f900d8465959f3ad73d2d4d528091afbe7570bb7
[ "MIT" ]
null
null
null
/* GooeyFiButton.cpp MIT License Copyright (c) 2016 cbtek Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ //---------------------------------------- //GooeyFiButton.cpp generated by CBTek Solutions on 02-17-2017 at 06:09:38 PM //---------------------------------------- #include "GooeyFiButton.h" namespace cbtek { namespace products { namespace gooeyfi { namespace core { inline static std::string getButtonTypeStr(GooeyFiButtonType type) { if (type == GooeyFiButtonType::Action) { return "ACTION"; } else if (type == GooeyFiButtonType::Checkbox) { return "CHECKBOX"; } else return "RADIO"; } GooeyFiButton::GooeyFiButton() { } GooeyFiButton::~GooeyFiButton() { } void GooeyFiButton::setType(const GooeyFiButtonType & value) { m_type=value; } const GooeyFiButtonType &GooeyFiButton::getType() const { return m_type; } void GooeyFiButton::write(common::utility::XMLStreamWriter &xml) { xml.writeAttribute("value",m_data); xml.writeAttribute("style",getButtonTypeStr(m_type)); } void GooeyFiButton::setData(const std::string &data) { m_data=data; } std::string GooeyFiButton::getData() const { return m_data; } GooeyFiWidgetType GooeyFiButton::getWidgetType() const { return GooeyFiWidgetType::Button; } }}}}//end namespace
23.742268
78
0.721233
cbtek
25bab4577369ee85445bb570dbd12573ef9a15c3
9,062
cpp
C++
src/TestTool/TestTeletext.cpp
qtlmovie/qtlmovie
082ad5ea6522a02d5ac0d86f23cdd6152edff613
[ "BSD-2-Clause" ]
8
2016-08-09T14:05:58.000Z
2020-09-05T14:43:36.000Z
src/TestTool/TestTeletext.cpp
qtlmovie/qtlmovie
082ad5ea6522a02d5ac0d86f23cdd6152edff613
[ "BSD-2-Clause" ]
15
2016-08-09T14:11:21.000Z
2022-01-15T23:39:07.000Z
src/TestTool/TestTeletext.cpp
qtlmovie/qtlmovie
082ad5ea6522a02d5ac0d86f23cdd6152edff613
[ "BSD-2-Clause" ]
1
2017-08-26T22:08:58.000Z
2017-08-26T22:08:58.000Z
//---------------------------------------------------------------------------- // // Copyright (c) 2013-2017, Thierry Lelegard // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // //---------------------------------------------------------------------------- // // Command line tool to test DVD. // //---------------------------------------------------------------------------- #include "TestToolCommand.h" #include "QtsSectionDemux.h" #include "QtsTeletextDemux.h" #include "QtsTeletextDescriptor.h" #include "QtsTeletextFrame.h" #include "QtsProgramAssociationTable.h" #include "QtsProgramMapTable.h" #include "QtsTsFile.h" #include "QtlSmartPointer.h" #include "QtlSubRipGenerator.h" typedef QtlSmartPointer<QtlSubRipGenerator,QtlNullMutexLocker> QtlSubRipGeneratorPtr; typedef QMap<int,QtlSubRipGeneratorPtr> SubRipMap; //---------------------------------------------------------------------------- // Test class. //---------------------------------------------------------------------------- class TestTeletext : public TestToolCommand, private QtsTeletextHandlerInterface, private QtsTableHandlerInterface { Q_OBJECT public: virtual int run(const QStringList& args) Q_DECL_OVERRIDE; TestTeletext() : TestToolCommand("teletext", "input-file [output-file-prefix]", "Read an MPEG2-TS file and locate all Teletext subtitles streams.\n" "If output-file-prefix is specified, extract each Teletext stream\n" "in a file named <prefix>_<pid>_<page>.srt"), _outputPrefix(), _teletextDemux(this), _input(), _outputs(), _frameCount(0) { } private: QString _outputPrefix; QtsTeletextDemux _teletextDemux; QtsTsFile _input; SubRipMap _outputs; int _frameCount; bool locateStreams(); bool extractStreams(); virtual void handleTable(QtsSectionDemux& demux, const QtsTable& table) Q_DECL_OVERRIDE; virtual void handleTeletextMessage(QtsTeletextDemux& demux, const QtsTeletextFrame& frame) Q_DECL_OVERRIDE; }; //---------------------------------------------------------------------------- // Locate all Teletext streams in the file. //---------------------------------------------------------------------------- bool TestTeletext::locateStreams() { if (!_input.isOpen() || !_input.seek(0)) { return false; } QtsSectionDemux sectionDemux(this); sectionDemux.addPid(QTS_PID_PAT); _teletextDemux.reset(); QtsTsPacket packet; while (sectionDemux.filteredPidCount() > 0 && _input.read(&packet) > 0) { sectionDemux.feedPacket(packet); } if (_teletextDemux.filteredPidCount() == 0) { err << "**** No Teletext stream found in " << _input.fileName() << endl; return false; } return true; } //---------------------------------------------------------------------------- // PSI Table Handler //---------------------------------------------------------------------------- void TestTeletext::handleTable(QtsSectionDemux& demux, const QtsTable& table) { switch (table.tableId()) { case QTS_TID_PAT: { demux.removePid(QTS_PID_PAT); const QtsProgramAssociationTable pat(table); if (pat.isValid()) { // Add a filter on the PMT PID of all services. foreach (const QtsProgramAssociationTable::ServiceEntry& service, pat.serviceList) { demux.addPid(service.pmtPid); } } break; } case QTS_TID_PMT: { demux.removePid(table.sourcePid()); const QtsProgramMapTable pmt(table); if (pmt.isValid()) { // Loop through all elementary streams in the service. foreach (const QtsProgramMapTable::StreamEntry& stream, pmt.streams) { // Loop through all teletext descriptors in the stream. for (int index = 0; (index = stream.descs.search(QTS_DID_TELETEXT, index)) < stream.descs.size(); ++index) { const QtsTeletextDescriptor td(*(stream.descs[index])); if (td.isValid()) { // Loop through all language entries. foreach (const QtsTeletextDescriptor::Entry& entry, td.entries) { if (entry.type == QTS_TELETEXT_SUBTITLES || entry.type == QTS_TELETEXT_SUBTITLES_HI) { _teletextDemux.addPid(stream.pid); err << "Found Teletext page " << entry.page << " in PID " << stream.pid << " for language " << entry.language << endl; } } } } } } break; } } } //---------------------------------------------------------------------------- // Extract all Teletext streams. //---------------------------------------------------------------------------- bool TestTeletext::extractStreams() { if (!_input.isOpen() || !_input.seek(0)) { return false; } _outputs.clear(); _frameCount = 0; QtsTsPacket packet; while (_input.read(&packet) > 0) { _teletextDemux.feedPacket(packet); } _teletextDemux.flushTeletext(); _outputs.clear(); if (_frameCount == 0) { err << "**** No Teletext frame found in " << _input.fileName() << endl; return false; } return true; } //---------------------------------------------------------------------------- // Teletext frame handler. //---------------------------------------------------------------------------- void TestTeletext::handleTeletextMessage(QtsTeletextDemux& demux, const QtsTeletextFrame& frame) { // Search an existing output file. // The index in the map is made of pid and page. const int index = (frame.pid() << 16) | (frame.page() & 0xFFFF); const SubRipMap::ConstIterator it = _outputs.find(index); QtlSubRipGeneratorPtr subrip; // Create a file if not found. if (it != _outputs.end()) { subrip = it.value(); } else { const QString fileName(QStringLiteral("%1_%2_%3.srt").arg(_outputPrefix).arg(frame.pid()).arg(frame.page())); subrip = new QtlSubRipGenerator(fileName); if (subrip->isOpen()) { out << "Created " << fileName << endl; _outputs.insert(index, subrip); } else { err << "*** Error creating " << fileName << endl; } } // Write SRT frame in output file. if (!subrip.isNull() && subrip->isOpen()) { subrip->addFrame(frame.showTimestamp(), frame.hideTimestamp(), frame.lines()); } _frameCount++; } //---------------------------------------------------------------------------- // Program entry point. //---------------------------------------------------------------------------- int TestTeletext::run(const QStringList& args) { if (args.size() < 1) { return syntaxError(); } const QString inputFile(args[0]); _input.setFileName(inputFile); if (!_input.open()) { err << "**** Error opening " << inputFile << endl; return EXIT_FAILURE; } if (args.size() >= 2) { _outputPrefix = args[1]; } if (_outputPrefix.isEmpty()) { _outputPrefix = QFileInfo(inputFile).completeBaseName(); } return locateStreams() && extractStreams() ? EXIT_SUCCESS : EXIT_FAILURE; } //---------------------------------------------------------------------------- #include "TestTeletext.moc" namespace {TestTeletext thisTest;}
35.537255
154
0.536526
qtlmovie
25bbfb56745fb8732ccd1877d0f1a6ce595a1b46
13,779
cc
C++
ja2/Build/Laptop/Insurance.cc
gtrafimenkov/ja2-vanilla-cp
961076add8175afa845cbd6c33dbf9cd78f61a0c
[ "BSD-Source-Code" ]
null
null
null
ja2/Build/Laptop/Insurance.cc
gtrafimenkov/ja2-vanilla-cp
961076add8175afa845cbd6c33dbf9cd78f61a0c
[ "BSD-Source-Code" ]
null
null
null
ja2/Build/Laptop/Insurance.cc
gtrafimenkov/ja2-vanilla-cp
961076add8175afa845cbd6c33dbf9cd78f61a0c
[ "BSD-Source-Code" ]
null
null
null
#include "Laptop/Insurance.h" #include "Directories.h" #include "Laptop/InsuranceContract.h" #include "Laptop/InsuranceText.h" #include "Laptop/Laptop.h" #include "Local.h" #include "SGP/ButtonSystem.h" #include "SGP/Font.h" #include "SGP/HImage.h" #include "SGP/Line.h" #include "SGP/VObject.h" #include "SGP/VSurface.h" #include "SGP/Video.h" #include "Utils/Cursors.h" #include "Utils/EncryptedFile.h" #include "Utils/FontControl.h" #include "Utils/MultiLanguageGraphicUtils.h" #include "Utils/Text.h" #include "Utils/WordWrap.h" #define INSURANCE_TEXT_SINGLE_FILE BINARYDATADIR "/insurancesingle.edt" #define INSURANCE_TEXT_MULTI_FILE BINARYDATADIR "/insurancemulti.edt" #define INSURANCE_BACKGROUND_WIDTH 125 #define INSURANCE_BACKGROUND_HEIGHT 100 #define INSURANCE_BIG_TITLE_X 95 + LAPTOP_SCREEN_UL_X #define INSURANCE_BIG_TITLE_Y 4 + LAPTOP_SCREEN_WEB_UL_Y #define INSURANCE_RED_BAR_X LAPTOP_SCREEN_UL_X #define INSURANCE_RED_BAR_Y LAPTOP_SCREEN_WEB_UL_Y #define INSURANCE_TOP_RED_BAR_X LAPTOP_SCREEN_UL_X + 66 #define INSURANCE_TOP_RED_BAR_Y 109 + LAPTOP_SCREEN_WEB_UL_Y #define INSURANCE_TOP_RED_BAR_Y1 31 + LAPTOP_SCREEN_WEB_UL_Y #define INSURANCE_BOTTOM_RED_BAR_Y 345 + LAPTOP_SCREEN_WEB_UL_Y #define INSURANCE_BOTTOM_LINK_RED_BAR_X 77 + LAPTOP_SCREEN_UL_X #define INSURANCE_BOTTOM_LINK_RED_BAR_Y 392 + LAPTOP_SCREEN_WEB_UL_Y #define INSURANCE_BOTTOM_LINK_RED_BAR_WIDTH 107 #define INSURANCE_BOTTOM_LINK_RED_BAR_OFFSET 148 #define INSURANCE_BOTTOM_LINK_RED_BAR_X_2 \ INSURANCE_BOTTOM_LINK_RED_BAR_X + INSURANCE_BOTTOM_LINK_RED_BAR_OFFSET #define INSURANCE_BOTTOM_LINK_RED_BAR_X_3 \ INSURANCE_BOTTOM_LINK_RED_BAR_X_2 + INSURANCE_BOTTOM_LINK_RED_BAR_OFFSET #define INSURANCE_LINK_TEXT_WIDTH INSURANCE_BOTTOM_LINK_RED_BAR_WIDTH #define INSURANCE_LINK_TEXT_1_X INSURANCE_BOTTOM_LINK_RED_BAR_X #define INSURANCE_LINK_TEXT_1_Y INSURANCE_BOTTOM_LINK_RED_BAR_Y - 36 #define INSURANCE_LINK_TEXT_2_X INSURANCE_LINK_TEXT_1_X + INSURANCE_BOTTOM_LINK_RED_BAR_OFFSET #define INSURANCE_LINK_TEXT_2_Y INSURANCE_LINK_TEXT_1_Y #define INSURANCE_LINK_TEXT_3_X INSURANCE_LINK_TEXT_2_X + INSURANCE_BOTTOM_LINK_RED_BAR_OFFSET #define INSURANCE_LINK_TEXT_3_Y INSURANCE_LINK_TEXT_1_Y #define INSURANCE_SUBTITLE_X INSURANCE_BOTTOM_LINK_RED_BAR_X + 15 #define INSURANCE_SUBTITLE_Y 150 + LAPTOP_SCREEN_WEB_UL_Y #define INSURANCE_BULLET_TEXT_1_Y 188 + LAPTOP_SCREEN_WEB_UL_Y #define INSURANCE_BULLET_TEXT_2_Y 215 + LAPTOP_SCREEN_WEB_UL_Y #define INSURANCE_BULLET_TEXT_3_Y 242 + LAPTOP_SCREEN_WEB_UL_Y #define INSURANCE_BOTTOM_SLOGAN_X INSURANCE_SUBTITLE_X #define INSURANCE_BOTTOM_SLOGAN_Y 285 + LAPTOP_SCREEN_WEB_UL_Y #define INSURANCE_BOTTOM_SLOGAN_WIDTH 370 #define INSURANCE_SMALL_TITLE_X 64 + LAPTOP_SCREEN_UL_X #define INSURANCE_SMALL_TITLE_Y 5 + LAPTOP_SCREEN_WEB_UL_Y #define INSURANCE_SMALL_TITLE_WIDTH 434 - 170 #define INSURANCE_SMALL_TITLE_HEIGHT 40 - 10 static SGPVObject *guiInsuranceBackGround; static SGPVObject *guiInsuranceTitleImage; static SGPVObject *guiInsuranceSmallTitleImage; static SGPVObject *guiInsuranceRedBarImage; static SGPVObject *guiInsuranceBigRedLineImage; static SGPVObject *guiInsuranceBulletImage; // link to the varios pages static MOUSE_REGION gSelectedInsuranceLinkRegion[3]; // link to the home page by clicking on the small title static MOUSE_REGION gSelectedInsuranceTitleLinkRegion; static void SelectInsuranceRegionCallBack(MOUSE_REGION *pRegion, INT32 iReason); void EnterInsurance() { UINT16 usPosX, i; SetBookMark(INSURANCE_BOOKMARK); InitInsuranceDefaults(); // load the Insurance title graphic and add it const char *const ImageFile = GetMLGFilename(MLG_INSURANCETITLE); guiInsuranceTitleImage = AddVideoObjectFromFile(ImageFile); // load the red bar on the side of the page and add it guiInsuranceBulletImage = AddVideoObjectFromFile(LAPTOPDIR "/bullet.sti"); usPosX = INSURANCE_BOTTOM_LINK_RED_BAR_X; for (i = 0; i < 3; i++) { MSYS_DefineRegion( &gSelectedInsuranceLinkRegion[i], usPosX, INSURANCE_BOTTOM_LINK_RED_BAR_Y - 37, (UINT16)(usPosX + INSURANCE_BOTTOM_LINK_RED_BAR_WIDTH), INSURANCE_BOTTOM_LINK_RED_BAR_Y + 2, MSYS_PRIORITY_HIGH, CURSOR_WWW, MSYS_NO_CALLBACK, SelectInsuranceRegionCallBack); MSYS_SetRegionUserData(&gSelectedInsuranceLinkRegion[i], 0, i); usPosX += INSURANCE_BOTTOM_LINK_RED_BAR_OFFSET; } RenderInsurance(); // reset the current merc index on the insurance contract page gsCurrentInsuranceMercIndex = 0; } void ExitInsurance() { RemoveInsuranceDefaults(); DeleteVideoObject(guiInsuranceTitleImage); DeleteVideoObject(guiInsuranceBulletImage); FOR_EACH(MOUSE_REGION, i, gSelectedInsuranceLinkRegion) MSYS_RemoveRegion(&*i); } void RenderInsurance() { wchar_t sText[800]; DisplayInsuranceDefaults(); SetFontShadow(INS_FONT_SHADOW); BltVideoObject(FRAME_BUFFER, guiInsuranceTitleImage, 0, INSURANCE_BIG_TITLE_X, INSURANCE_BIG_TITLE_Y); // Display the title slogan GetInsuranceText(INS_SNGL_WERE_LISTENING, sText); DrawTextToScreen(sText, LAPTOP_SCREEN_UL_X, INSURANCE_TOP_RED_BAR_Y - 35, LAPTOP_SCREEN_LR_X - LAPTOP_SCREEN_UL_X, INS_FONT_BIG, INS_FONT_COLOR, FONT_MCOLOR_BLACK, CENTER_JUSTIFIED); // Display the subtitle slogan GetInsuranceText(INS_SNGL_LIFE_INSURANCE_SPECIALISTS, sText); DrawTextToScreen(sText, INSURANCE_SUBTITLE_X, INSURANCE_SUBTITLE_Y, 0, INS_FONT_BIG, INS_FONT_COLOR, FONT_MCOLOR_BLACK, LEFT_JUSTIFIED); // Display the bulleted text 1 BltVideoObject(FRAME_BUFFER, guiInsuranceBulletImage, 0, INSURANCE_SUBTITLE_X, INSURANCE_BULLET_TEXT_1_Y); GetInsuranceText(INS_MLTI_EMPLOY_HIGH_RISK, sText); DrawTextToScreen(sText, INSURANCE_SUBTITLE_X + INSURANCE_BULLET_TEXT_OFFSET_X, INSURANCE_BULLET_TEXT_1_Y, 0, INS_FONT_MED, INS_FONT_COLOR, FONT_MCOLOR_BLACK, LEFT_JUSTIFIED); // Display the bulleted text 2 BltVideoObject(FRAME_BUFFER, guiInsuranceBulletImage, 0, INSURANCE_SUBTITLE_X, INSURANCE_BULLET_TEXT_2_Y); GetInsuranceText(INS_MLTI_HIGH_FATALITY_RATE, sText); DrawTextToScreen(sText, INSURANCE_SUBTITLE_X + INSURANCE_BULLET_TEXT_OFFSET_X, INSURANCE_BULLET_TEXT_2_Y, 0, INS_FONT_MED, INS_FONT_COLOR, FONT_MCOLOR_BLACK, LEFT_JUSTIFIED); // Display the bulleted text 3 BltVideoObject(FRAME_BUFFER, guiInsuranceBulletImage, 0, INSURANCE_SUBTITLE_X, INSURANCE_BULLET_TEXT_3_Y); GetInsuranceText(INS_MLTI_DRAIN_SALARY, sText); DrawTextToScreen(sText, INSURANCE_SUBTITLE_X + INSURANCE_BULLET_TEXT_OFFSET_X, INSURANCE_BULLET_TEXT_3_Y, 0, INS_FONT_MED, INS_FONT_COLOR, FONT_MCOLOR_BLACK, LEFT_JUSTIFIED); // Display the bottom slogan GetInsuranceText(INS_MLTI_IF_ANSWERED_YES, sText); DrawTextToScreen(sText, INSURANCE_BOTTOM_SLOGAN_X, INSURANCE_BOTTOM_SLOGAN_Y, INSURANCE_BOTTOM_SLOGAN_WIDTH, INS_FONT_MED, INS_FONT_COLOR, FONT_MCOLOR_BLACK, CENTER_JUSTIFIED); // Display the red bar under the link at the bottom. and the text DisplaySmallRedLineWithShadow( INSURANCE_BOTTOM_LINK_RED_BAR_X, INSURANCE_BOTTOM_LINK_RED_BAR_Y, INSURANCE_BOTTOM_LINK_RED_BAR_X + INSURANCE_BOTTOM_LINK_RED_BAR_WIDTH, INSURANCE_BOTTOM_LINK_RED_BAR_Y); GetInsuranceText(INS_SNGL_COMMENTSFROM_CLIENTS, sText); DisplayWrappedString(INSURANCE_LINK_TEXT_1_X, INSURANCE_LINK_TEXT_1_Y, INSURANCE_LINK_TEXT_WIDTH, 2, INS_FONT_MED, INS_FONT_COLOR, sText, FONT_MCOLOR_BLACK, CENTER_JUSTIFIED); // Display the red bar under the link at the bottom DisplaySmallRedLineWithShadow( INSURANCE_BOTTOM_LINK_RED_BAR_X_2, INSURANCE_BOTTOM_LINK_RED_BAR_Y, INSURANCE_BOTTOM_LINK_RED_BAR_X_2 + INSURANCE_BOTTOM_LINK_RED_BAR_WIDTH, INSURANCE_BOTTOM_LINK_RED_BAR_Y); GetInsuranceText(INS_SNGL_HOW_DOES_INS_WORK, sText); DisplayWrappedString(INSURANCE_LINK_TEXT_2_X, INSURANCE_LINK_TEXT_2_Y + 7, INSURANCE_LINK_TEXT_WIDTH, 2, INS_FONT_MED, INS_FONT_COLOR, sText, FONT_MCOLOR_BLACK, CENTER_JUSTIFIED); // Display the red bar under the link at the bottom DisplaySmallRedLineWithShadow( INSURANCE_BOTTOM_LINK_RED_BAR_X_3, INSURANCE_BOTTOM_LINK_RED_BAR_Y, INSURANCE_BOTTOM_LINK_RED_BAR_X_3 + INSURANCE_BOTTOM_LINK_RED_BAR_WIDTH, INSURANCE_BOTTOM_LINK_RED_BAR_Y); GetInsuranceText(INS_SNGL_TO_ENTER_REVIEW, sText); DisplayWrappedString(INSURANCE_LINK_TEXT_3_X, INSURANCE_LINK_TEXT_3_Y + 7, INSURANCE_LINK_TEXT_WIDTH, 2, INS_FONT_MED, INS_FONT_COLOR, sText, FONT_MCOLOR_BLACK, CENTER_JUSTIFIED); SetFontShadow(DEFAULT_SHADOW); MarkButtonsDirty(); RenderWWWProgramTitleBar(); InvalidateRegion(LAPTOP_SCREEN_UL_X, LAPTOP_SCREEN_WEB_UL_Y, LAPTOP_SCREEN_LR_X, LAPTOP_SCREEN_WEB_LR_Y); } static void SelectInsuranceTitleLinkRegionCallBack(MOUSE_REGION *pRegion, INT32 iReason); void InitInsuranceDefaults() { // load the Flower Account Box graphic and add it guiInsuranceBackGround = AddVideoObjectFromFile(LAPTOPDIR "/backgroundtile.sti"); // load the red bar on the side of the page and add it guiInsuranceRedBarImage = AddVideoObjectFromFile(LAPTOPDIR "/lefttile.sti"); // load the red bar on the side of the page and add it guiInsuranceBigRedLineImage = AddVideoObjectFromFile(LAPTOPDIR "/largebar.sti"); // if it is not the first page, display the small title if (guiCurrentLaptopMode != LAPTOP_MODE_INSURANCE) { // load the small title for the every page other then the first page const char *const ImageFile = GetMLGFilename(MLG_SMALLTITLE); guiInsuranceSmallTitleImage = AddVideoObjectFromFile(ImageFile); // create the link to the home page on the small titles MSYS_DefineRegion( &gSelectedInsuranceTitleLinkRegion, INSURANCE_SMALL_TITLE_X + 85, INSURANCE_SMALL_TITLE_Y, (UINT16)(INSURANCE_SMALL_TITLE_X + INSURANCE_SMALL_TITLE_WIDTH), (UINT16)(INSURANCE_SMALL_TITLE_Y + INSURANCE_SMALL_TITLE_HEIGHT), MSYS_PRIORITY_HIGH, CURSOR_WWW, MSYS_NO_CALLBACK, SelectInsuranceTitleLinkRegionCallBack); } } void DisplayInsuranceDefaults() { UINT8 i; UINT16 usPosY; WebPageTileBackground(4, 4, INSURANCE_BACKGROUND_WIDTH, INSURANCE_BACKGROUND_HEIGHT, guiInsuranceBackGround); usPosY = INSURANCE_RED_BAR_Y; for (i = 0; i < 4; i++) { BltVideoObject(FRAME_BUFFER, guiInsuranceRedBarImage, 0, INSURANCE_RED_BAR_X, usPosY); usPosY += INSURANCE_BACKGROUND_HEIGHT; } // display the top red bar switch (guiCurrentLaptopMode) { case LAPTOP_MODE_INSURANCE: usPosY = INSURANCE_TOP_RED_BAR_Y; BltVideoObject(FRAME_BUFFER, guiInsuranceBigRedLineImage, 0, INSURANCE_TOP_RED_BAR_X, usPosY); break; case LAPTOP_MODE_INSURANCE_INFO: case LAPTOP_MODE_INSURANCE_CONTRACT: usPosY = INSURANCE_TOP_RED_BAR_Y1; break; default: break; } BltVideoObject(FRAME_BUFFER, guiInsuranceBigRedLineImage, 0, INSURANCE_TOP_RED_BAR_X, INSURANCE_BOTTOM_RED_BAR_Y); // if it is not the first page, display the small title if (guiCurrentLaptopMode != LAPTOP_MODE_INSURANCE) { BltVideoObject(FRAME_BUFFER, guiInsuranceSmallTitleImage, 0, INSURANCE_SMALL_TITLE_X, INSURANCE_SMALL_TITLE_Y); } } void RemoveInsuranceDefaults() { DeleteVideoObject(guiInsuranceBackGround); DeleteVideoObject(guiInsuranceRedBarImage); DeleteVideoObject(guiInsuranceBigRedLineImage); // if it is not the first page, display the small title if (guiPreviousLaptopMode != LAPTOP_MODE_INSURANCE) { DeleteVideoObject(guiInsuranceSmallTitleImage); MSYS_RemoveRegion(&gSelectedInsuranceTitleLinkRegion); } } void DisplaySmallRedLineWithShadow(UINT16 usStartX, UINT16 usStartY, UINT16 EndX, UINT16 EndY) { SGPVSurface::Lock l(FRAME_BUFFER); SetClippingRegionAndImageWidth(l.Pitch(), 0, 0, SCREEN_WIDTH, SCREEN_HEIGHT); UINT16 *const pDestBuf = l.Buffer<UINT16>(); // draw the red line LineDraw(FALSE, usStartX, usStartY, EndX, EndY, Get16BPPColor(FROMRGB(255, 0, 0)), pDestBuf); // draw the black shadow line LineDraw(FALSE, usStartX + 1, usStartY + 1, EndX + 1, EndY + 1, Get16BPPColor(FROMRGB(0, 0, 0)), pDestBuf); } void GetInsuranceText(const UINT8 ubNumber, wchar_t *const pString) { UINT32 uiStartLoc = 0; if (ubNumber < INS_MULTI_LINE_BEGINS) { // Get and display the card saying uiStartLoc = INSURANCE_TEXT_SINGLE_LINE_SIZE * ubNumber; LoadEncryptedDataFromFile(INSURANCE_TEXT_SINGLE_FILE, pString, uiStartLoc, INSURANCE_TEXT_SINGLE_LINE_SIZE); } else { // Get and display the card saying uiStartLoc = INSURANCE_TEXT_MULTI_LINE_SIZE * (ubNumber - INS_MULTI_LINE_BEGINS - 1); LoadEncryptedDataFromFile(INSURANCE_TEXT_MULTI_FILE, pString, uiStartLoc, INSURANCE_TEXT_MULTI_LINE_SIZE); } } static void SelectInsuranceRegionCallBack(MOUSE_REGION *pRegion, INT32 iReason) { if (iReason & MSYS_CALLBACK_REASON_LBUTTON_UP) { UINT32 uiInsuranceLink = MSYS_GetRegionUserData(pRegion, 0); if (uiInsuranceLink == 0) guiCurrentLaptopMode = LAPTOP_MODE_INSURANCE_COMMENTS; else if (uiInsuranceLink == 1) guiCurrentLaptopMode = LAPTOP_MODE_INSURANCE_INFO; else if (uiInsuranceLink == 2) guiCurrentLaptopMode = LAPTOP_MODE_INSURANCE_CONTRACT; } } static void SelectInsuranceTitleLinkRegionCallBack(MOUSE_REGION *pRegion, INT32 iReason) { if (iReason & MSYS_CALLBACK_REASON_LBUTTON_UP) { guiCurrentLaptopMode = LAPTOP_MODE_INSURANCE; } }
39.25641
100
0.782713
gtrafimenkov
25c21ba065b3113f4bff89de7d8ee2c178457871
3,267
cpp
C++
test/utils/round_trip.cpp
mathisloge/mapnik-vector-tile
57d183482bf84e90072c2975829f3190bb62e19f
[ "BSD-3-Clause" ]
247
2015-01-06T07:05:59.000Z
2022-03-10T09:34:22.000Z
test/utils/round_trip.cpp
mathisloge/mapnik-vector-tile
57d183482bf84e90072c2975829f3190bb62e19f
[ "BSD-3-Clause" ]
210
2015-01-09T05:38:25.000Z
2021-04-27T10:43:24.000Z
test/utils/round_trip.cpp
mathisloge/mapnik-vector-tile
57d183482bf84e90072c2975829f3190bb62e19f
[ "BSD-3-Clause" ]
86
2015-01-06T01:04:35.000Z
2021-11-21T11:52:27.000Z
// test utils #include "round_trip.hpp" // mapnik-vector-tile #include "vector_tile_processor.hpp" #include "vector_tile_strategy.hpp" #include "vector_tile_geometry_decoder.hpp" // mapnik #include <mapnik/feature_factory.hpp> #include <mapnik/memory_datasource.hpp> // std #include <exception> // libprotobuf #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wunused-parameter" #pragma GCC diagnostic ignored "-Wsign-conversion" #include "vector_tile.pb.h" #pragma GCC diagnostic pop namespace test_utils { mapnik::geometry::geometry<double> round_trip(mapnik::geometry::geometry<double> const& geom, double simplify_distance, mapnik::vector_tile_impl::polygon_fill_type fill_type, bool mpu) { unsigned tile_size = 256 * 1000; // Create map note its not 3857 -- round trip as 4326 mapnik::Map map(tile_size,tile_size,"+init=epsg:4326"); // create layer mapnik::layer lyr("layer",map.srs()); // create feature with geometry mapnik::context_ptr ctx = std::make_shared<mapnik::context_type>(); mapnik::feature_ptr feature(mapnik::feature_factory::create(ctx,1)); mapnik::geometry::geometry<double> g(geom); feature->set_geometry(std::move(g)); mapnik::parameters params; params["type"] = "memory"; std::shared_ptr<mapnik::memory_datasource> ds = std::make_shared<mapnik::memory_datasource>(params); ds->push(feature); lyr.set_datasource(ds); map.add_layer(lyr); // Build request mapnik::box2d<double> bbox(-180,-90,180,90); // Build processor and create tile mapnik::vector_tile_impl::processor ren(map); ren.set_simplify_distance(simplify_distance); ren.set_fill_type(fill_type); ren.set_multi_polygon_union(mpu); mapnik::vector_tile_impl::tile out_tile = ren.create_tile(bbox, tile_size); if (out_tile.get_layers().size() != 1) { std::stringstream s; s << "expected 1 layer in `round_trip` found " << out_tile.get_layers().size(); throw std::runtime_error(s.str()); } protozero::pbf_reader layer_reader; out_tile.layer_reader(0, layer_reader); if (!layer_reader.next(mapnik::vector_tile_impl::Layer_Encoding::FEATURES)) { throw std::runtime_error("Expected at least one feature in layer"); } protozero::pbf_reader feature_reader = layer_reader.get_message(); int32_t geometry_type = mapnik::vector_tile_impl::Geometry_Type::UNKNOWN; mapnik::vector_tile_impl::GeometryPBF::pbf_itr geom_itr; while (feature_reader.next()) { if (feature_reader.tag() == mapnik::vector_tile_impl::Feature_Encoding::GEOMETRY) { geom_itr = feature_reader.get_packed_uint32(); } else if (feature_reader.tag() == mapnik::vector_tile_impl::Feature_Encoding::TYPE) { geometry_type = feature_reader.get_enum(); } else { feature_reader.skip(); } } mapnik::vector_tile_impl::GeometryPBF geoms(geom_itr); return mapnik::vector_tile_impl::decode_geometry<double>(geoms, geometry_type, 2, 0.0, 0.0, 1000.0, -1000.0); } } // end ns
34.755319
113
0.665136
mathisloge
25c6ead1068b0c55c14367d6a25390dece3f8fa8
2,035
cpp
C++
runtime/pass/EmitCodes.cpp
easywave/easy-just-in-time
6360bdcff1943b93fb92e71b8bbe5844f6c897ab
[ "BSD-3-Clause" ]
null
null
null
runtime/pass/EmitCodes.cpp
easywave/easy-just-in-time
6360bdcff1943b93fb92e71b8bbe5844f6c897ab
[ "BSD-3-Clause" ]
null
null
null
runtime/pass/EmitCodes.cpp
easywave/easy-just-in-time
6360bdcff1943b93fb92e71b8bbe5844f6c897ab
[ "BSD-3-Clause" ]
1
2021-11-29T01:10:25.000Z
2021-11-29T01:10:25.000Z
#include <easy/runtime/RuntimePasses.h> #include <easy/runtime/BitcodeTracker.h> #include <llvm/IR/Module.h> #include <llvm/IR/Function.h> #include <llvm/IR/Constant.h> #include <llvm/IR/Constants.h> #include <llvm/IR/InstIterator.h> #include <llvm/IR/IRBuilder.h> #include <llvm/Linker/Linker.h> #include <llvm/ADT/SmallVector.h> #include <llvm/Transforms/Utils/Cloning.h> #include <llvm/Support/raw_ostream.h> #include <numeric> #include <sstream> using namespace llvm; char easy::EmitCodes::ID = 0; llvm::Pass* easy::createEmitCodesPass(llvm::StringRef Name) { return new EmitCodes(Name); } static std::string BuildEmitString(const std::vector<uint8_t>& src) { if (src.empty()) return ""; std::ostringstream ss; for (auto i = 0; i < src.size(); i++) { ss << ".byte " << std::to_string(src[i]) << ";"; } return ss.str(); } bool easy::EmitCodes::runOnFunction(llvm::Function &F) { if(F.getName() != TargetName_) return false; easy::Context const &C = getAnalysis<ContextAnalysis>().getContext(); const auto &RawBytes = C.getRawBytes(); std::string s = BuildEmitString(RawBytes.bytes); bool changed = false; std::list<llvm::Instruction*> ToRemove; for(auto it = inst_begin(F); it != inst_end(F); ++it) { CallSite CS{&*it}; if(!CS) continue; Value* Called = CS.getCalledValue(); if (!isa<InlineAsm>(Called)) continue; //if (s.empty()) { // changed = true; // ToRemove.push_back(&*it); // continue; //} changed = true; const InlineAsm *IA = cast<InlineAsm>(Called); if (IA->getAsmString() != ".byte 0x90\n\t") continue; InlineAsm *newIA = InlineAsm::get( IA->getFunctionType(), s, IA->getConstraintString(), s.empty() ? false : IA->hasSideEffects(), IA->isAlignStack(), IA->getDialect()); CS.setCalledFunction(newIA); } //for (auto &&i : ToRemove) { // i->eraseFromParent(); //} return changed; } static RegisterPass<easy::EmitCodes> X("","",false, false);
25.123457
71
0.637838
easywave
5ad87d43cdc303e8bbd0461a3b02471c01a5ab44
289
cpp
C++
EntityComponentSystem/PbrRenderer/ModelResource.cpp
Spheya/Slamanander-Engine
d0708399eacab26b243045b33b51ff30d614b7bd
[ "MIT" ]
null
null
null
EntityComponentSystem/PbrRenderer/ModelResource.cpp
Spheya/Slamanander-Engine
d0708399eacab26b243045b33b51ff30d614b7bd
[ "MIT" ]
null
null
null
EntityComponentSystem/PbrRenderer/ModelResource.cpp
Spheya/Slamanander-Engine
d0708399eacab26b243045b33b51ff30d614b7bd
[ "MIT" ]
null
null
null
#include "ModelResource.hpp" void renderer::ModelResource::load() { _model = std::make_unique<Model>(getPath()); } renderer::Model* renderer::ModelResource::getModel() { return _model.get(); } const renderer::Model* renderer::ModelResource::getModel() const { return _model.get(); }
20.642857
66
0.719723
Spheya
5ad8ce0ad3510e13f3f813eda9426a37939b0232
580
cc
C++
ExampleWorkspace/ExampleLibC/src/class-c.cc
nidegen/Tart
030bae172e9c2bb59020a6ccc29dfa7b928ce3f7
[ "MIT" ]
null
null
null
ExampleWorkspace/ExampleLibC/src/class-c.cc
nidegen/Tart
030bae172e9c2bb59020a6ccc29dfa7b928ce3f7
[ "MIT" ]
null
null
null
ExampleWorkspace/ExampleLibC/src/class-c.cc
nidegen/Tart
030bae172e9c2bb59020a6ccc29dfa7b928ce3f7
[ "MIT" ]
null
null
null
#include "class-c.h" #include <iostream> #include <unordered_set> ClassC::ClassC() { is_true_ = true; std::cout << "Class C initialized, activation is: " << is_true_ << '\n'; std::cout << "ExampleLibC was copiled with C++ version " << __cplusplus << std::endl; std::cout << "ExampleLibC TART_TARGET_OS is: " << TART_TARGET_OS << std::endl; std::cout << "ExampleLibC TART_TARGET_ARCH is: " << TART_TARGET_ARCH << std::endl; } bool ClassC::isClassCActive() { std::cout << "Class C currently active? " << is_true_ << '\n'; is_true_ = !is_true_; return is_true_; }
30.526316
87
0.656897
nidegen
5ad8e5b1b7244e23e80cf401837e0f16fde8d22e
2,889
cpp
C++
Edu CF R25/B.cpp
parthlathiya/Codeforces_Submissions
6c8f40dbeea31a3c3c7d37b799b78f6af4bbcf68
[ "MIT" ]
null
null
null
Edu CF R25/B.cpp
parthlathiya/Codeforces_Submissions
6c8f40dbeea31a3c3c7d37b799b78f6af4bbcf68
[ "MIT" ]
null
null
null
Edu CF R25/B.cpp
parthlathiya/Codeforces_Submissions
6c8f40dbeea31a3c3c7d37b799b78f6af4bbcf68
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; #define rep(i,a,b) for(ll i=a;i<b;i++) #define re(i,b) for(ll i=0;i<b;i++) #define repr(i,n) for(ll i=n-1;i>=0;i--) #define ll long long #define ld long double #define llu long long unsigned #define pll std::pair<ll, ll> #define ppll std::pair<ll, pll> #define vll std::vector<ll> #define vpll std::vector<pll> #define vppll std::vector<ppll> #define mll std::map<ll, ll> #define mpll std::map<pll, ll> #define mppll std::map<ppll, ll> #define sll std::set<ll> #define ff first #define ss second #define msll std::multiset<ll> #define all(c) c.begin(), c.end() #define allr(c) c.rbegin(), c.rend() #define srt(x) sort(all(x)) #define rsrt(x) sort(allr(x)) #define mp make_pair #define mt make_tuple #define eb emplace_back #define pb push_back #define s(yy) ll yy;cin>>yy #define mod 1e9+7 #define maxlong 1e18+5 /* ###################################################### # # # @author # # Parth Lathiya # # https://www.cse.iitb.ac.in/~parthiitb/ # # # ###################################################### */ int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); #ifdef PARTH_LATHIYA_HOME freopen("B_in.txt","r",stdin); ll ttt,bkkk; cin>>ttt; bkkk=ttt; while(ttt--) { cout<<"Testcase - "<<bkkk-ttt<<"\n"; #endif //-------------------------------------------------------------------------------------- // std::vector<int> v[100]; // std::vector<int> temp(100,4); // rep(i,0,100) // v[i] = temp; string s[10]; re(i,10) cin>>s[i]; int x=0;int dot=0; re(i,10) { re(j,10) { //vert x=0;dot=0; rep(k,j,j+5) { if(i>=0 && i<10 && k>=0 && k<10) { if(s[i][k]=='X')x++; else if(s[i][k]=='.')dot++; } } if(x==4 && dot==1){ cout<<"YES"; return 0; } //hori x=0;dot=0; rep(k,i,i+5) { if(k>=0 && k<10 && j>=0 && j<10) { if(s[k][j]=='X')x++; else if(s[k][j]=='.')dot++; } } if(x==4 && dot==1){ cout<<"YES"; return 0; } //dia1 x=0;dot=0; rep(k,0,5) { if(i+k>=0 && i+k<10 && j+k>=0 && j+k<10) { if(s[i+k][j+k]=='X')x++; else if(s[i+k][j+k]=='.')dot++; } } if(x==4 && dot==1){ cout<<"YES"; return 0; } //dia2 x=0;dot=0; rep(k,0,5) { if(i+k>=0 && i+k<10 && j-k>=0 && j-k<10) { if(s[i+k][j-k]=='X')x++; else if(s[i+k][j-k]=='.')dot++; } } if(x==4 && dot==1){ cout<<"YES"; return 0; } } } cout<<"NO"; //-------------------------------------------------------------------------------------- #ifdef PARTH_LATHIYA_HOME cout<<"\n"; } #endif return 0; }
19.787671
88
0.421253
parthlathiya
5adafdca2d08620deb01d8b13702aca27d335996
761
cpp
C++
hackerrank/maxsubarray/solution.cpp
SamProkopchuk/coding-problems
fa0ca2c05ac90e41945de1a5751e5545a8459ac4
[ "MIT" ]
null
null
null
hackerrank/maxsubarray/solution.cpp
SamProkopchuk/coding-problems
fa0ca2c05ac90e41945de1a5751e5545a8459ac4
[ "MIT" ]
null
null
null
hackerrank/maxsubarray/solution.cpp
SamProkopchuk/coding-problems
fa0ca2c05ac90e41945de1a5751e5545a8459ac4
[ "MIT" ]
null
null
null
#include <algorithm> #include <climits> #include <iostream> #include <vector> typedef signed long long ll; #define FOR(x, to) for (x = 0; x < (to); ++x) #define FORR(x, arr) for (auto& x : arr) using namespace std; int main() { int t, n, i, x, cursum, maxsubarr, maxsubseq, largest; cin >> t; while (t--) { cin >> n; cursum = maxsubarr = maxsubseq = 0; largest = INT_MIN; FOR(i, n) { cin >> x; largest = max(largest, x); cursum += x; maxsubseq = max(maxsubseq, maxsubseq + x); maxsubarr = max(maxsubarr, cursum); cursum = max(cursum, 0); } if (largest < 0) maxsubseq = maxsubarr = largest; cout << maxsubarr << " " << maxsubseq << endl; } return 0; }
23.060606
57
0.549277
SamProkopchuk
5ae63bf0abeb5131d2947a797e28be60d7d0bb61
641
cpp
C++
YorozuyaGSLib/source/_attack_skill_result_zocl.cpp
lemkova/Yorozuya
f445d800078d9aba5de28f122cedfa03f26a38e4
[ "MIT" ]
29
2017-07-01T23:08:31.000Z
2022-02-19T10:22:45.000Z
YorozuyaGSLib/source/_attack_skill_result_zocl.cpp
kotopes/Yorozuya
605c97d3a627a8f6545cc09f2a1b0a8afdedd33a
[ "MIT" ]
90
2017-10-18T21:24:51.000Z
2019-06-06T02:30:33.000Z
YorozuyaGSLib/source/_attack_skill_result_zocl.cpp
kotopes/Yorozuya
605c97d3a627a8f6545cc09f2a1b0a8afdedd33a
[ "MIT" ]
44
2017-12-19T08:02:59.000Z
2022-02-24T23:15:01.000Z
#include <_attack_skill_result_zocl.hpp> START_ATF_NAMESPACE _attack_skill_result_zocl::_attack_skill_result_zocl() { using org_ptr = void (WINAPIV*)(struct _attack_skill_result_zocl*); (org_ptr(0x1400eed50L))(this); }; void _attack_skill_result_zocl::ctor__attack_skill_result_zocl() { using org_ptr = void (WINAPIV*)(struct _attack_skill_result_zocl*); (org_ptr(0x1400eed50L))(this); }; int _attack_skill_result_zocl::size() { using org_ptr = int (WINAPIV*)(struct _attack_skill_result_zocl*); return (org_ptr(0x1400eed70L))(this); }; END_ATF_NAMESPACE
30.52381
75
0.698908
lemkova
5ae831dfdb6a4baa77461d60a22d13714c3eae6d
692
cpp
C++
tests/std/utility.cpp
AlCash07/ACTL
15de4e2783d8e39dbd8e10cd635aaab328ca4f5b
[ "BSL-1.0" ]
17
2018-08-22T06:48:20.000Z
2022-02-22T21:20:09.000Z
tests/std/utility.cpp
AlCash07/ACTL
15de4e2783d8e39dbd8e10cd635aaab328ca4f5b
[ "BSL-1.0" ]
null
null
null
tests/std/utility.cpp
AlCash07/ACTL
15de4e2783d8e39dbd8e10cd635aaab328ca4f5b
[ "BSL-1.0" ]
null
null
null
// Copyright 2019 Oleksandr Bacherikov. // // Distributed under the Boost Software License, Version 1.0 // (see accompanying file LICENSE.txt or copy at // http://www.boost.org/LICENSE_1_0.txt). #include <actl/io/device/memory.hpp> #include <actl/std/utility.hpp> #include "test.hpp" using namespace ac::io; TEST_CASE("write pair") { char s[3]; CHECK(!write( memory<bin | io::out>{s}, std::pair{'a', 'c'}, std::pair{'b', 'c'})); CHECK_EQUAL("ac"sv, span{s, 2}); } TEST_CASE("read pair") { std::string s = "aba"; memory<bin | in> id{s}; std::pair<char, char> x; CHECK(read(id, x)); CHECK(std::pair{'a', 'b'} == x); CHECK_FALSE(read(id, x)); }
23.066667
77
0.611272
AlCash07
5ae9a899e453b0c591d3fa8f49e993d740cc8588
735
cpp
C++
tlx/timestamp.cpp
mullovc/tlx
e7c17b5981cbd7912b689fa0ad993e18424e26fe
[ "BSL-1.0" ]
284
2017-02-26T08:49:15.000Z
2022-03-30T21:55:37.000Z
tlx/timestamp.cpp
xiao2mo/tlx
b311126e670753897c1defceeaa75c83d2d9531a
[ "BSL-1.0" ]
24
2017-09-05T21:02:41.000Z
2022-03-07T10:09:59.000Z
tlx/timestamp.cpp
xiao2mo/tlx
b311126e670753897c1defceeaa75c83d2d9531a
[ "BSL-1.0" ]
62
2017-02-23T12:29:27.000Z
2022-03-31T07:45:59.000Z
/******************************************************************************* * tlx/timestamp.cpp * * Part of tlx - http://panthema.net/tlx * * Copyright (C) 2019 Timo Bingmann <tb@panthema.net> * * All rights reserved. Published under the Boost Software License, Version 1.0 ******************************************************************************/ #include <tlx/timestamp.hpp> #include <chrono> namespace tlx { double timestamp() { return static_cast<double>( std::chrono::duration_cast<std::chrono::microseconds>( std::chrono::steady_clock::now().time_since_epoch()).count()) / 1e6; } } // namespace tlx /******************************************************************************/
28.269231
80
0.451701
mullovc
5aea94dbf1a332c0bde67c48cfa530baca832597
271
cpp
C++
task5/MockConfiguration.cpp
hasherezade/mastercoder2014
cc9e201fa8e5c7b2b8b085a777b10b70e4827705
[ "BSD-3-Clause" ]
9
2015-09-27T10:35:02.000Z
2021-12-26T13:21:35.000Z
task5/MockConfiguration.cpp
hasherezade/mastercoder2014
cc9e201fa8e5c7b2b8b085a777b10b70e4827705
[ "BSD-3-Clause" ]
null
null
null
task5/MockConfiguration.cpp
hasherezade/mastercoder2014
cc9e201fa8e5c7b2b8b085a777b10b70e4827705
[ "BSD-3-Clause" ]
6
2016-03-25T07:02:36.000Z
2022-02-24T06:28:16.000Z
#include "MockConfiguration.h" DistanceType MockConfiguration::getDistnanceType() { return currentType; } void MockConfiguration::useJaroWinkler() { currentType = JARO_WINKLER; } void MockConfiguration::useLevenshtein() { currentType = LEVENSHTEIN; }
16.9375
51
0.745387
hasherezade
5aebd39ecd2063eadc43241eb6177b5810862f50
3,182
cpp
C++
dkk_lib/src/Communicator.cpp
mjf-89/DistributedKernelKmeans
ca6daa81cd51a0f2400a111c5d10a9ef144f1574
[ "MIT" ]
null
null
null
dkk_lib/src/Communicator.cpp
mjf-89/DistributedKernelKmeans
ca6daa81cd51a0f2400a111c5d10a9ef144f1574
[ "MIT" ]
null
null
null
dkk_lib/src/Communicator.cpp
mjf-89/DistributedKernelKmeans
ca6daa81cd51a0f2400a111c5d10a9ef144f1574
[ "MIT" ]
null
null
null
#include <stdlib.h> #include "Communicator.h" #include "DistributedArray2D.h" namespace DKK{ Communicator::Communicator(int *argc, char*** argv) { MPI_Init(argc, argv); MPI_Comm_rank(MPI_COMM_WORLD, &rank); MPI_Comm_size(MPI_COMM_WORLD, &size); dsps = (int*)malloc(sizeof(int)*size); cnts = (int*)malloc(sizeof(int)*size); } Communicator::~Communicator() { free(dsps); free(cnts); MPI_Finalize(); } void Communicator::bcast(DKK_TYPE_INT &val, int root) { MPI_Bcast(&val, 1, DKK_TYPE_MPI_INT, root, MPI_COMM_WORLD); } void Communicator::bcast(float &val, int root) { MPI_Bcast(&val, 1, MPI_FLOAT, root, MPI_COMM_WORLD); } void Communicator::bcast(double &val, int root) { MPI_Bcast(&val, 1, MPI_DOUBLE, root, MPI_COMM_WORLD); } void Communicator::allgather(DistributedArray2D<float> &src, Array2D<float> &dst) { for(int i=0; i<size; i++){ cnts[i] = (int)(src.grows()/size)+(i<src.grows()%size?1:0); cnts[i] *= src.cols(); dsps[i] = (i>0)?dsps[i-1]+cnts[i-1]:0; } MPI_Allgatherv(src.bff(0), src.length(), MPI_FLOAT, dst.bff(0), cnts, dsps, MPI_FLOAT, MPI_COMM_WORLD); } void Communicator::allgather(DistributedArray2D<double> &src, Array2D<double> &dst) { for(int i=0; i<size; i++){ cnts[i] = (int)(src.grows()/size)+(i<src.grows()%size?1:0); cnts[i] *= src.cols(); dsps[i] = (i>0)?dsps[i-1]+cnts[i-1]:0; } MPI_Allgatherv(src.bff(0), src.length(), MPI_DOUBLE, dst.bff(0), cnts, dsps, MPI_DOUBLE, MPI_COMM_WORLD); } void Communicator::allgather(DistributedArray2D<DKK_TYPE_INT> &src, Array2D<DKK_TYPE_INT> &dst) { for(int i=0; i<size; i++){ cnts[i] = (int)(src.grows()/size)+(i<src.grows()%size?1:0); cnts[i] *= src.cols(); dsps[i] = (i>0)?dsps[i-1]+cnts[i-1]:0; } MPI_Allgatherv(src.bff(0), src.length(), DKK_TYPE_MPI_INT, dst.bff(0), cnts, dsps, DKK_TYPE_MPI_INT, MPI_COMM_WORLD); } void Communicator::allreducemax(float &val) { MPI_Allreduce(MPI_IN_PLACE, &val, 1, MPI_FLOAT, MPI_MAX, MPI_COMM_WORLD); } void Communicator::allreducemax(double &val) { MPI_Allreduce(MPI_IN_PLACE, &val, 1, MPI_DOUBLE, MPI_MAX, MPI_COMM_WORLD); } void Communicator::allreducesum(float &val) { MPI_Allreduce(MPI_IN_PLACE, &val, 1, MPI_FLOAT, MPI_SUM, MPI_COMM_WORLD); } void Communicator::allreducesum(double &val) { MPI_Allreduce(MPI_IN_PLACE, &val, 1, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD); } void Communicator::allreducesum(Array2D<float> &arr) { MPI_Allreduce(MPI_IN_PLACE, arr.bff(0), arr.length(), MPI_FLOAT, MPI_SUM, MPI_COMM_WORLD); } void Communicator::allreducesum(Array2D<double> &arr) { MPI_Allreduce(MPI_IN_PLACE, arr.bff(0), arr.length(), MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD); } void Communicator::allreducesum(DKK_TYPE_INT &val) { MPI_Allreduce(MPI_IN_PLACE, &val, 1, DKK_TYPE_MPI_INT, MPI_SUM, MPI_COMM_WORLD); } void Communicator::allreducesum(Array2D<DKK_TYPE_INT> &arr) { MPI_Allreduce(MPI_IN_PLACE, arr.bff(0), arr.length(), DKK_TYPE_MPI_INT, MPI_SUM, MPI_COMM_WORLD); } void Communicator::allreduceminloc(Array2D<DKK_TYPE_REAL_INT> &arr) { MPI_Allreduce(MPI_IN_PLACE, arr.bff(0), arr.length(), DKK_TYPE_MPI_REAL_INT, MPI_MINLOC, MPI_COMM_WORLD); } double Communicator::wtime() { return MPI_Wtime(); } }
25.869919
118
0.714645
mjf-89
5af39e0a103be2f95f20ae701bb4c5c528617591
8,136
inl
C++
H3API/lib/h3api/H3Allocator/H3Allocator.inl
pawel54321/H3Plugins
737739beabb8c80f393ee480949c1e37b3c61507
[ "MIT" ]
45
2019-06-13T15:41:59.000Z
2022-03-20T06:04:42.000Z
H3API/lib/h3api/H3Allocator/H3Allocator.inl
pawel54321/H3Plugins
737739beabb8c80f393ee480949c1e37b3c61507
[ "MIT" ]
20
2020-04-06T14:09:42.000Z
2021-12-14T04:21:52.000Z
H3API/lib/h3api/H3Allocator/H3Allocator.inl
pawel54321/H3Plugins
737739beabb8c80f393ee480949c1e37b3c61507
[ "MIT" ]
9
2019-06-13T15:42:03.000Z
2021-02-10T12:03:30.000Z
////////////////////////////////////////////////////////////////////// // // // Created by RoseKavalier: // // rosekavalierhc@gmail.com // // Created: 2019-12-15 // // ***You may use or distribute these files freely // // so long as this notice remains present.*** // // // ////////////////////////////////////////////////////////////////////// #ifndef _H3ObjectAllocator_INL_ #define _H3ObjectAllocator_INL_ #include "H3Allocator.hpp" namespace h3 { template<typename T> inline H3ObjectAllocator<T>::H3ObjectAllocator() noexcept { } template<typename T> inline T * H3ObjectAllocator<T>::allocate(size_t number) const noexcept { return reinterpret_cast<T*>(F_malloc(number * sizeof(T))); } template<typename T> inline VOID H3ObjectAllocator<T>::deallocate(T * block) const noexcept { F_delete(reinterpret_cast<PVOID>(block)); } template<typename T> inline VOID H3ObjectAllocator<T>::deallocate(T* block, size_t number) const noexcept { F_delete(reinterpret_cast<PVOID>(block)); } template<typename T> inline VOID H3ObjectAllocator<T>::construct(T * block) const noexcept { new(reinterpret_cast<PVOID>(block)) T(); } template<typename T> inline VOID H3ObjectAllocator<T>::construct(T * block, const T & value) const noexcept { new(reinterpret_cast<PVOID>(block)) T(value); } template<typename T> template<typename U> inline VOID H3ObjectAllocator<T>::construct(T * block, const U & arg) const noexcept { new(reinterpret_cast<PVOID>(block)) T(arg); } template<typename T> inline VOID H3ObjectAllocator<T>::destroy(T * block) const noexcept { block->~T(); } #ifdef _H3API_CPLUSPLUS11_ template<typename T> template<typename ...Args> inline VOID H3ObjectAllocator<T>::construct(T * block, Args && ...args) { new(reinterpret_cast<PVOID>(block)) T(std::forward<Args>(args)...); } #endif template<typename T> inline size_t * H3ArrayAllocator<T>::getArrayBase(T * block) const noexcept { return reinterpret_cast<size_t*>(block) - 1; } template<typename T> inline size_t H3ArrayAllocator<T>::getArraySize(T * block) const noexcept { return *getArrayBase(block); } template<typename T> inline H3ArrayAllocator<T>::H3ArrayAllocator() noexcept { } template<typename T> inline T * H3ArrayAllocator<T>::allocate(size_t number) const noexcept { size_t* block = reinterpret_cast<size_t*>(F_malloc(number * sizeof(T) + sizeof(size_t))); *block = number; return reinterpret_cast<T*>(block + 1); } template<typename T> inline VOID H3ArrayAllocator<T>::deallocate(T * block) const noexcept { F_delete(reinterpret_cast<PVOID>(getArrayBase(block))); } template<typename T> inline VOID H3ArrayAllocator<T>::construct(T * block) const noexcept { size_t number = getArraySize(block); for (size_t i = 0; i < number; ++i) { new(reinterpret_cast<PVOID>(block)) T(); ++block; } } template<typename T> inline VOID H3ArrayAllocator<T>::construct(T * block, const T & value) const noexcept { size_t number = getArraySize(block); for (size_t i = 0; i < number; ++i) { new(reinterpret_cast<PVOID>(block)) T(value); ++block; } } template<typename T> template<typename U> inline VOID H3ArrayAllocator<T>::construct(T * block, const U & arg) const noexcept { size_t number = getArraySize(block); for (size_t i = 0; i < number; ++i) { new(reinterpret_cast<PVOID>(block)) T(arg); ++block; } } template<typename T> inline VOID H3ArrayAllocator<T>::destroy(T * block) const noexcept { size_t number = getArraySize(block); for (size_t i = 0; i < number; ++i) { block->~T(); ++block; } } template<typename T> template<typename U> inline H3ObjectAllocator<T>::H3ObjectAllocator(const H3ObjectAllocator<U>&) noexcept { } template<typename T> template<typename U> inline bool H3ObjectAllocator<T>::operator==(const H3ObjectAllocator<U>&) const noexcept { return TRUE; } template<typename T> template<typename U> inline bool H3ObjectAllocator<T>::operator!=(const H3ObjectAllocator<U>&) const noexcept { return FALSE; } template<typename T> template<typename U> inline H3ArrayAllocator<T>::H3ArrayAllocator(const H3ArrayAllocator<U>&) noexcept { } template<typename T> template<typename U> inline bool H3ArrayAllocator<T>::operator==(const H3ArrayAllocator<U>&) const noexcept { return true; } template<typename T> template<typename U> inline bool H3ArrayAllocator<T>::operator!=(const H3ArrayAllocator<U>&) const noexcept { return false; } #ifdef _H3API_CPLUSPLUS11_ template<typename T> template<typename ...Args> inline VOID H3ArrayAllocator<T>::construct(T * block, Args && ...args) { size_t number = getArraySize(block); for (size_t i = 0; i < number; ++i) { new(reinterpret_cast<PVOID>(block)) T(std::forward<Args>(args)...); ++block; } } #endif template<typename T, typename Allocator> inline void H3UniquePtr<T, Allocator>::destroy(T* replacement) { if (replacement && replacement == data) return; if (data) { Allocator().destroy(data); Allocator().deallocate(data); data = nullptr; } } template<typename T, typename Allocator> inline H3UniquePtr<T, Allocator>::H3UniquePtr() : data() { } template<typename T, typename Allocator> inline H3UniquePtr<T, Allocator>::H3UniquePtr(T* source) : data(source) { source = nullptr; } template<typename T, typename Allocator> inline H3UniquePtr<T, Allocator>::~H3UniquePtr() { destroy(); } template<typename T, typename Allocator> inline void H3UniquePtr<T, Allocator>::Set(T * source) { destroy(source); // check we aren't releasing ourselves data = source; } template<typename T, typename Allocator> inline T * H3UniquePtr<T, Allocator>::Get() { return data; } template<typename T, typename Allocator> inline T * H3UniquePtr<T, Allocator>::operator->() { return data; } template<typename T, typename Allocator> inline T * H3UniquePtr<T, Allocator>::Release() { T* r = data; data = nullptr; return r; } template<typename T, typename Allocator> inline void H3UniquePtr<T, Allocator>::Swap(H3UniquePtr<T>& other) { T* tmp = data; data = other.data; other.data = tmp; } template<typename T, typename Allocator> inline BOOL H3UniquePtr<T, Allocator>::operator!() const { return data == nullptr; } template<typename T, typename Allocator> inline H3UniquePtr<T, Allocator>::operator BOOL() const { return data != nullptr; } #ifdef _H3API_CPLUSPLUS11_ template<typename T, typename Allocator> inline H3UniquePtr<T, Allocator>::H3UniquePtr(H3UniquePtr<T, Allocator>&& other) : data(other.Release()) { } template<typename T, typename Allocator> inline H3UniquePtr<T, Allocator>& H3UniquePtr<T, Allocator>::operator=(H3UniquePtr<T, Allocator>&& other) { if (&other == this) return *this; destroy(); data = other.Release(); return *this; } #endif template<typename T> inline H3AutoPtr<T>::H3AutoPtr(T* _Ptr) : m_used(_Ptr != 0), m_data(_Ptr) { } template<typename T> inline H3AutoPtr<T>::~H3AutoPtr() { if (m_used) { delete m_data; m_used = FALSE; } } template<typename T> inline T* H3AutoPtr<T>::Get() { return m_data; } template<typename T> inline T* H3AutoPtr<T>::operator->() { return m_data; } template<typename T> inline T* H3AutoPtr<T>::Release() { T* ptr = m_data; m_used = FALSE; m_data = nullptr; return ptr; } template<typename T> inline BOOL8 H3AutoPtr<T>::Exists() const { return m_used; } template<typename T> inline H3AutoPtr<T>::operator BOOL() const { return m_used != FALSE; } template<typename T> inline BOOL H3AutoPtr<T>::operator!() const { return m_used == FALSE; } template<typename T> inline T& H3AutoPtr<T>::operator*() const { return *m_data; } } #endif /* #define _H3ObjectAllocator_INL_ */
24.286567
106
0.660767
pawel54321
5af6666e50842e290dae73c96e019c40f81b4ec2
54
hpp
C++
src/boost_flyweight_intermodule_holder_fwd.hpp
miathedev/BoostForArduino
919621dcd0c157094bed4df752b583ba6ea6409e
[ "BSL-1.0" ]
10
2018-03-17T00:58:42.000Z
2021-07-06T02:48:49.000Z
src/boost_flyweight_intermodule_holder_fwd.hpp
miathedev/BoostForArduino
919621dcd0c157094bed4df752b583ba6ea6409e
[ "BSL-1.0" ]
2
2021-03-26T15:17:35.000Z
2021-05-20T23:55:08.000Z
src/boost_flyweight_intermodule_holder_fwd.hpp
miathedev/BoostForArduino
919621dcd0c157094bed4df752b583ba6ea6409e
[ "BSL-1.0" ]
4
2019-05-28T21:06:37.000Z
2021-07-06T03:06:52.000Z
#include <boost/flyweight/intermodule_holder_fwd.hpp>
27
53
0.851852
miathedev