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
108
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
67k
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
a95162bd45b7b0ec0f5efe2a97c1b2974d3e52af
3,262
cpp
C++
training/HDU/5880.cpp
voleking/ICPC
fc2cf408fa2607ad29b01eb00a1a212e6d0860a5
[ "MIT" ]
68
2017-10-08T04:44:23.000Z
2019-08-06T20:15:02.000Z
training/HDU/5880.cpp
voleking/ICPC
fc2cf408fa2607ad29b01eb00a1a212e6d0860a5
[ "MIT" ]
null
null
null
training/HDU/5880.cpp
voleking/ICPC
fc2cf408fa2607ad29b01eb00a1a212e6d0860a5
[ "MIT" ]
18
2017-05-31T02:52:23.000Z
2019-07-05T09:18:34.000Z
#include <bits/stdc++.h> #define IOS std::ios::sync_with_stdio(false); std::cin.tie(nullptr); std::cout.tie(nullptr); // #define __DEBUG__ #ifdef __DEBUG__ #define DEBUG(...) printf(__VA_ARGS__) #else #define DEBUG(...) #endif #define filename "" #define setfile() freopen(filename".in", "r", stdin); freopen(filename".out", "w", stdout); using namespace std; typedef long long ll; typedef unsigned long long ull; typedef long double ld; typedef pair<int, int > Pii; const double pi = acos(-1.0); const int INF = INT_MAX; const int MAX_N = 1e6 + 10; template <typename T> inline T sqr(T a) { return a * a;}; int t, n, ans[MAX_N], d[MAX_N], len; char buf[MAX_N]; struct Trie { int nxt[MAX_N][26], fail[MAX_N], end[MAX_N]; int root, L; int newnode() { for(int i = 0; i < 26; i++) nxt[L][i] = -1; end[L++] = 0; return L-1; } void init() { L = 0; root = newnode(); } void insert(char buf[]) { int len = strlen(buf); int now = root; for(int i = 0; i < len; i++) { if(nxt[now][buf[i]-'a'] == -1) nxt[now][buf[i]-'a'] = newnode(); now = nxt[now][buf[i]-'a']; } end[now] = 1; d[now] = len; } void build() { queue<int> Q; fail[root] = root; for(int i = 0; i < 26; i++) if(nxt[root][i] == -1) nxt[root][i] = root; else { fail[nxt[root][i]] = root; Q.push(nxt[root][i]); } while( !Q.empty() ) { int now = Q.front(); Q.pop(); for(int i = 0; i < 26; i++) if(nxt[now][i] == -1) nxt[now][i] = nxt[fail[now]][i]; else { fail[nxt[now][i]] = nxt[fail[now]][i]; Q.push(nxt[now][i]); } } } void solve(char buf[]) { int cur = root; int len = strlen(buf); int index; for(int i = 0; i < len; ++i) { if(buf[i] >= 'A' && buf[i] <= 'Z') index = buf[i] - 'A'; else if(buf[i] >= 'a' && buf[i] <= 'z') index = buf[i] - 'a'; else continue; cur = nxt[cur][index]; int x = cur; while(x != root) { if(end[x]) { ans[i + 1] -= 1; ans[i - d[x] + 1] += 1; break; } x = fail[x]; } } } }; Trie ac; int main(void) { scanf("%d", &t); while (t--) { ac.init(); scanf("%d", &n); for (int i = 0; i < n; ++i) { scanf("%s", buf); ac.insert(buf); } getchar(); ac.build(); gets(buf); memset(ans, 0, sizeof ans); ac.solve(buf); ll res = 0; len = strlen(buf); for (int i = 0; i < len; ++i) { res += ans[i]; if (res <= 0) printf("%c", buf[i]); else printf("*"); } printf("\n"); for (int i = 0; i < len; ++i) cout << ans[i]; cout << endl; } return 0; }
25.092308
92
0.400061
voleking
a951c3ac39642012c75ac7abf687667c5fbdc250
2,475
cpp
C++
LibCarla/source/carla/geom/GeoLocation.cpp
simon0628/carla
b49664f94f87291be36805315593571678c8da28
[ "MIT" ]
null
null
null
LibCarla/source/carla/geom/GeoLocation.cpp
simon0628/carla
b49664f94f87291be36805315593571678c8da28
[ "MIT" ]
null
null
null
LibCarla/source/carla/geom/GeoLocation.cpp
simon0628/carla
b49664f94f87291be36805315593571678c8da28
[ "MIT" ]
1
2019-05-28T18:49:44.000Z
2019-05-28T18:49:44.000Z
// Copyright (c) 2017 Computer Vision Center (CVC) at the Universitat Autonoma // de Barcelona (UAB). // // This work is licensed under the terms of the MIT license. // For a copy, see <https://opensource.org/licenses/MIT>. #include "carla/geom/GeoLocation.h" #include "carla/geom/Location.h" #include "carla/geom/Math.h" #include <cmath> #if defined(_WIN32) && !defined(_USE_MATH_DEFINES) # define _USE_MATH_DEFINES # include <math.h> // cmath is not enough for MSVC #endif namespace carla { namespace geom { /// Earth radius at equator [m]. static constexpr double EARTH_RADIUS_EQUA = 6378137.0; /// Convert latitude to scale, which is needed by mercator /// transformations /// @param lat latitude in degrees (DEG) /// @return scale factor /// @note when converting from lat/lon -> mercator and back again, /// or vice versa, use the same scale in both transformations! static double LatToScale(double lat) { return std::cos(Math::to_radians(lat)); } /// Converts lat/lon/scale to mx/my (mx/my in meters if correct scale /// is given). template <class float_type> static void LatLonToMercator(double lat, double lon, double scale, float_type &mx, float_type &my) { mx = scale * Math::to_radians(lon) * EARTH_RADIUS_EQUA; my = scale * EARTH_RADIUS_EQUA * std::log(std::tan((90.0 + lat) * Math::pi() / 360.0)); } /// Converts mx/my/scale to lat/lon (mx/my in meters if correct scale /// is given). static void MercatorToLatLon(double mx, double my, double scale, double &lat, double &lon) { lon = mx * 180.0 / (Math::pi() * EARTH_RADIUS_EQUA * scale); lat = 360.0 * std::atan(std::exp(my / (EARTH_RADIUS_EQUA * scale))) / Math::pi() - 90.0; } /// Adds meters dx/dy to given lat/lon and returns new lat/lon. static void LatLonAddMeters( double lat_start, double lon_start, double dx, double dy, double &lat_end, double &lon_end) { double scale = LatToScale(lat_start); double mx, my; LatLonToMercator(lat_start, lon_start, scale, mx, my); mx += dx; my += dy; MercatorToLatLon(mx, my, scale, lat_end, lon_end); } GeoLocation GeoLocation::Transform(const Location &location) const { GeoLocation result{0.0, 0.0, altitude + location.z}; LatLonAddMeters( latitude, longitude, location.x, location.y, result.latitude, result.longitude); return result; } } // namespace geom } // namespace carla
32.142857
102
0.671111
simon0628
a951e001cfe5b4ebabed0c9303b5a0121317ef1a
427
cpp
C++
src/main.cpp
scotto3394/go-bot
b4f45fc796160c7f1e1c8bb593fc1a6c48bc9365
[ "MIT" ]
null
null
null
src/main.cpp
scotto3394/go-bot
b4f45fc796160c7f1e1c8bb593fc1a6c48bc9365
[ "MIT" ]
null
null
null
src/main.cpp
scotto3394/go-bot
b4f45fc796160c7f1e1c8bb593fc1a6c48bc9365
[ "MIT" ]
null
null
null
#include <iostream> #include "include/rules.hpp" #include "include/helper.hpp" int main(int argc, char **argv) { std::ios::sync_with_stdio(false); Game game(BoardSize::SMALL, atoi(argv[1])); while (true) { size_t c, r; game.render(); input_play(game, game.get_turn()); if (game.get_captured().first != 0) { break; } game.next_turn(); } }
20.333333
47
0.548009
scotto3394
a953393a7ad63fc028bfb973bbc6cb3acb0d13aa
6,051
hpp
C++
include/cxxdasp/filter/tsvf/tsvf.hpp
h6ah4i/cxxdasp
44bf437ad688760265ea10d2dc7cb3c57e0e7008
[ "Apache-2.0" ]
35
2015-01-28T07:49:02.000Z
2020-10-04T17:38:46.000Z
include/cxxdasp/filter/tsvf/tsvf.hpp
h6ah4i/cxxdasp
44bf437ad688760265ea10d2dc7cb3c57e0e7008
[ "Apache-2.0" ]
1
2018-02-16T10:45:19.000Z
2018-02-21T19:04:57.000Z
include/cxxdasp/filter/tsvf/tsvf.hpp
h6ah4i/cxxdasp
44bf437ad688760265ea10d2dc7cb3c57e0e7008
[ "Apache-2.0" ]
10
2015-01-28T07:49:02.000Z
2022-03-08T00:51:51.000Z
// // Copyright (C) 2014 Haruki Hasegawa // // 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 CXXDASP_FILTER_TSVF_TSVF_HPP_ #define CXXDASP_FILTER_TSVF_TSVF_HPP_ #include <cxxporthelper/compiler.hpp> #include <cxxdasp/filter/digital_filter.hpp> #include <cxxdasp/filter/tsvf/tsvf_coeffs.hpp> namespace cxxdasp { namespace filter { /** * Linear Trapezoidal Integrated State Variable Filter * * @tparam TFrame audio frame type * @tparam TTSVFCoreOperator core operator class * * @sa "Solving the continuous SVF equations using trapezoidal integration and equivalent currents" * by Andrew Simper <andy@cytomic.com> * http://www.cytomic.com/files/dsp/SvfLinearTrapOptimised2.pdf */ template <typename TFrame, class TTSVFCoreOperator> class trapezoidal_state_variable_filter { /// @cond INTERNAL_FIELD trapezoidal_state_variable_filter(const trapezoidal_state_variable_filter &) = delete; trapezoidal_state_variable_filter &operator=(const trapezoidal_state_variable_filter &) = delete; /// @endcond public: /** * Audio frame type. */ typedef TFrame frame_type; /** * Core operator class. */ typedef TTSVFCoreOperator core_operator_type; /** * Constructor. */ trapezoidal_state_variable_filter(); /** * Destructor. */ ~trapezoidal_state_variable_filter(); /** * Initialize. * @param params [in] general filter parameters * @returns Success or Failure */ bool init(const filter_params_t &params) CXXPH_NOEXCEPT; /** * Initialize. * @param coeffs [in] trapezoidal state variable filter coefficients * @returns Success or Failure */ bool init(const trapezoidal_state_variable_filter_coeffs &coeffs) CXXPH_NOEXCEPT; /** * Update filter parameters. * @param params [in] general filter parameters * @returns Success or Failure */ bool update(const filter_params_t &params) CXXPH_NOEXCEPT; /** * Update filter parameters. * @param coeffs [in] trapezoidal state variable filter coefficients * @returns Success or Failure */ bool update(const trapezoidal_state_variable_filter_coeffs &coeffs) CXXPH_NOEXCEPT; /** * Reset state. */ void reset() CXXPH_NOEXCEPT; /** * Perform filtering. * @param src_dest [in/out] data buffer (overwrite) * @param n [in] count of samples */ void perform(frame_type *src_dest, int n) CXXPH_NOEXCEPT; /** * Perform filtering. * @param src [in] source data buffer * @param dest [out] destination data buffer * @param n [in] count of samples */ void perform(const frame_type *CXXPH_RESTRICT src, frame_type *CXXPH_RESTRICT dest, int n) CXXPH_NOEXCEPT; private: /// @cond INTERNAL_FIELD core_operator_type core_operator_; /// @endcond }; template <typename TFrame, class TTSVFCoreOperator> inline trapezoidal_state_variable_filter<TFrame, TTSVFCoreOperator>::trapezoidal_state_variable_filter() : core_operator_() { } template <typename TFrame, class TTSVFCoreOperator> inline trapezoidal_state_variable_filter<TFrame, TTSVFCoreOperator>::~trapezoidal_state_variable_filter() { } template <typename TFrame, class TTSVFCoreOperator> inline bool trapezoidal_state_variable_filter<TFrame, TTSVFCoreOperator>::init(const filter_params_t &params) CXXPH_NOEXCEPT { trapezoidal_state_variable_filter_coeffs coeffs; if (!coeffs.make(params)) { return false; } return init(coeffs); } template <typename TFrame, class TTSVFCoreOperator> inline bool trapezoidal_state_variable_filter<TFrame, TTSVFCoreOperator>::init( const trapezoidal_state_variable_filter_coeffs &coeffs) CXXPH_NOEXCEPT { core_operator_.set_params(coeffs.a1, coeffs.a2, coeffs.a3, coeffs.m0, coeffs.m1, coeffs.m2); core_operator_.reset(); return true; } template <typename TFrame, class TTSVFCoreOperator> inline bool trapezoidal_state_variable_filter<TFrame, TTSVFCoreOperator>::update(const filter_params_t &params) CXXPH_NOEXCEPT { trapezoidal_state_variable_filter_coeffs coeffs; if (!coeffs.make(params)) { return false; } return update(coeffs); } template <typename TFrame, class TTSVFCoreOperator> inline bool trapezoidal_state_variable_filter<TFrame, TTSVFCoreOperator>::update( const trapezoidal_state_variable_filter_coeffs &coeffs) CXXPH_NOEXCEPT { core_operator_.set_params(coeffs.a1, coeffs.a2, coeffs.a3, coeffs.m0, coeffs.m1, coeffs.m2); return true; } template <typename TFrame, class TTSVFCoreOperator> inline void trapezoidal_state_variable_filter<TFrame, TTSVFCoreOperator>::reset() CXXPH_NOEXCEPT { core_operator_.reset(); } template <typename TFrame, class TTSVFCoreOperator> inline void trapezoidal_state_variable_filter<TFrame, TTSVFCoreOperator>::perform(frame_type *src_dest, int n) CXXPH_NOEXCEPT { core_operator_.perform(src_dest, n); } template <typename TFrame, class TTSVFCoreOperator> inline void trapezoidal_state_variable_filter<TFrame, TTSVFCoreOperator>::perform(const frame_type *CXXPH_RESTRICT src, frame_type *CXXPH_RESTRICT dest, int n) CXXPH_NOEXCEPT { core_operator_.perform(src, dest, n); } } // namespace filter } // namespace cxxdasp #endif // CXXDASP_FILTER_TSVF_TSVF_HPP_
29.955446
119
0.713932
h6ah4i
a95947b628f2cca2c3a5d4eae42bc87f15138940
723
cpp
C++
C++/21. MergeTwoSortedLists.cpp
nizD/LeetCode-Solutions
7f4ca37bab795e0d6f9bfd9148a8fe3b62aa5349
[ "MIT" ]
263
2020-10-05T18:47:29.000Z
2022-03-31T19:44:46.000Z
C++/21. MergeTwoSortedLists.cpp
nizD/LeetCode-Solutions
7f4ca37bab795e0d6f9bfd9148a8fe3b62aa5349
[ "MIT" ]
1,264
2020-10-05T18:13:05.000Z
2022-03-31T23:16:35.000Z
C++/21. MergeTwoSortedLists.cpp
nizD/LeetCode-Solutions
7f4ca37bab795e0d6f9bfd9148a8fe3b62aa5349
[ "MIT" ]
760
2020-10-05T18:22:51.000Z
2022-03-29T06:06:20.000Z
/* 21. Merge Two Sorted Lists https://leetcode.com/problems/merge-two-sorted-lists/ Merge two sorted linked lists and return it as a new sorted list. The new list should be made by splicing together the nodes of the first two lists. */ /* Solution: -> Simple and short recursive code that works by pointer manipulation. -> Uses O(1) space apart from stack usage of recursive function calls */ class Solution { public: ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) { if(l1 == NULL) return l2; if(l2 == NULL) return l1; if(l1 -> val < l2 -> val){ l1 -> next = mergeTwoLists(l1 -> next, l2); return l1; } else{ l2 -> next = mergeTwoLists(l1, l2 -> next); return l2; } } };
20.657143
148
0.662517
nizD
a95951225ff22873115c9c2b150972321e27f66a
2,711
hh
C++
src/project.hh
LeszekSwirski/ccls
a10d53071ce678a28d9444a6325605d6e22f589f
[ "Apache-2.0" ]
null
null
null
src/project.hh
LeszekSwirski/ccls
a10d53071ce678a28d9444a6325605d6e22f589f
[ "Apache-2.0" ]
null
null
null
src/project.hh
LeszekSwirski/ccls
a10d53071ce678a28d9444a6325605d6e22f589f
[ "Apache-2.0" ]
null
null
null
/* Copyright 2017-2018 ccls Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #pragma once #include "config.hh" #include "lsp.hh" #include <functional> #include <mutex> #include <string> #include <unordered_map> #include <vector> namespace ccls { struct WorkingFiles; std::pair<LanguageId, bool> lookupExtension(std::string_view filename); struct Project { struct Entry { std::string root; std::string directory; std::string filename; std::vector<const char *> args; // If true, this entry is inferred and was not read from disk. bool is_inferred = false; int id = -1; }; struct Folder { std::string name; // Include directories for <> headers std::vector<std::string> angle_search_list; // Include directories for "" headers std::vector<std::string> quote_search_list; std::vector<Entry> entries; std::unordered_map<std::string, int> path2entry_index; }; std::mutex mutex_; std::unordered_map<std::string, Folder> root2folder; // Loads a project for the given |directory|. // // If |config->compilationDatabaseDirectory| is not empty, look for .ccls or // compile_commands.json in it, otherwise they are retrieved in // |root_directory|. // For .ccls, recursive directory listing is used and files with known // suffixes are indexed. .ccls files can exist in subdirectories and they // will affect flags in their subtrees (relative paths are relative to the // project root, not subdirectories). For compile_commands.json, its entries // are indexed. void Load(const std::string &root_directory); // Lookup the CompilationEntry for |filename|. If no entry was found this // will infer one based on existing project structure. Entry FindEntry(const std::string &path, bool can_be_inferred); // If the client has overridden the flags, or specified them for a file // that is not in the compilation_database.json make sure those changes // are permanent. void SetArgsForFile(const std::vector<const char *> &args, const std::string &path); void Index(WorkingFiles *wfiles, RequestId id); }; } // namespace ccls
33.469136
80
0.704168
LeszekSwirski
a95c4a434df29fdba686b0aa8111a8bf6d41ee6c
338
hpp
C++
falcon/helper/use_difference_type.hpp
jonathanpoelen/falcon
5b60a39787eedf15b801d83384193a05efd41a89
[ "MIT" ]
2
2018-02-02T14:19:59.000Z
2018-05-13T02:48:24.000Z
falcon/helper/use_difference_type.hpp
jonathanpoelen/falcon
5b60a39787eedf15b801d83384193a05efd41a89
[ "MIT" ]
null
null
null
falcon/helper/use_difference_type.hpp
jonathanpoelen/falcon
5b60a39787eedf15b801d83384193a05efd41a89
[ "MIT" ]
null
null
null
#ifndef FALCON_HELPER_USE_DIFFERENCE_TYPE_HPP #define FALCON_HELPER_USE_DIFFERENCE_TYPE_HPP #include <falcon/type_traits/use_def.hpp> namespace falcon { namespace _aux { FALCON_USE_XXX_TRAIT_NAMED_DEF(difference_type, use_difference_type); } template <class T> struct use_difference_type : _aux::use_difference_type<T> {}; } #endif
16.9
69
0.828402
jonathanpoelen
a963135e2d002e028dbe1812a1c09a85853775ac
1,913
cc
C++
leetcode/16-3sum-closest.cc
Stone-Zeng/toys
ca040cb1b1546cdb422940f3785c6b1a5624bc89
[ "MIT" ]
6
2019-03-11T10:38:02.000Z
2022-01-07T08:55:58.000Z
leetcode/16-3sum-closest.cc
Stone-Zeng/toys
ca040cb1b1546cdb422940f3785c6b1a5624bc89
[ "MIT" ]
null
null
null
leetcode/16-3sum-closest.cc
Stone-Zeng/toys
ca040cb1b1546cdb422940f3785c6b1a5624bc89
[ "MIT" ]
1
2021-03-05T02:03:11.000Z
2021-03-05T02:03:11.000Z
// 16. 3Sum Closest // https://leetcode.com/problems/3sum-closest/ #include <algorithm> #include <climits> #include <iostream> #include <numeric> #include <vector> #include "leetcode_util.h" using namespace std; class Solution { public: int threeSumClosest(vector<int> & nums, int target) { if (nums.size() <= 3) return accumulate(nums.begin(), nums.end(), 0); sort(nums.begin(), nums.end()); int sum = 0, new_sum = 0, delta = INT_MAX, new_delta = INT_MAX; auto i = nums.begin(), j = i, k = i, nums_end = nums.end(); for (; i != nums_end; ++i) for (j = i + 1; j != nums_end; ++j) for (k = j + 1; k != nums_end; ++k) { if (delta == 0) return target; new_sum = *i + *j + *k; new_delta = abs(new_sum - target); if (new_delta < delta) { sum = new_sum; delta = new_delta; continue; } if (new_sum - target > 0) break; } return sum; } }; int main() { Solution sol; vector<pair<vector<int>, int>> data = { {{1,2,3},4}, {{1,2,5},4}, {{1,2,5,2},4}, {{0},1}, {{29,16,92,56,25,62,59,31,-52,-57,100,-68,-33,-93,-77,31,7,-44,-52,-30,-72,71,16,-68,-1,67,-58,21,-7,-90,-67,59,-38,-19,13,70,37,16,-86,25,-20,87,61,80,16,33,-50,48,-44,9}, 23}, {{0,7,-4,-7,0,14,-6,-4,-12,11,4,9,7,4,-10,8,10,5,4,14,6,0,-9,5,6,6,-11,1,-8,-1,2,-1,13,5,-1,-2,4,9,9,-1,-3,-1,-7,11,10,-2,-4,5,10,-15,-4,-6,-8,2,14,13,-7,11,-9,-8,-13,0,-1,-15,-10,13,-2,1,-1,-15,7,3,-9,7,-1,-14,-10,2,6,8,-6,-12,-13,1,-3,8,-9,-2,4,-2,-3,6,5,11,6,11,10,12,-11,-14}, 133}, }; for (auto i: data) { cout << leetcode::to_string(sol.threeSumClosest(i.first, i.second)) << endl; } }
36.788462
294
0.467329
Stone-Zeng
a968e015a319d86f23e6e06e970916c1b9c060a1
495
hpp
C++
src/code/Library/RandomSynthesizer.hpp
1iyiwei/texture
eaa78c00666060ca0a51c69920031b367c265e7d
[ "MIT" ]
33
2017-04-13T18:32:42.000Z
2021-12-21T07:53:59.000Z
src/code/Library/RandomSynthesizer.hpp
1iyiwei/texture
eaa78c00666060ca0a51c69920031b367c265e7d
[ "MIT" ]
1
2021-09-24T07:21:03.000Z
2021-09-29T23:39:41.000Z
src/code/Library/RandomSynthesizer.hpp
1iyiwei/texture
eaa78c00666060ca0a51c69920031b367c265e7d
[ "MIT" ]
5
2017-04-12T17:46:03.000Z
2021-03-31T00:50:12.000Z
/* RandomSynthesizer.hpp randomly copy from source to target; good for initialization Li-Yi Wei August 17, 2014 */ #ifndef _RANDOM_SYNTHESIZER_HPP #define _RANDOM_SYNTHESIZER_HPP #include "Synthesizer.hpp" class RandomSynthesizer : public Synthesizer { public: RandomSynthesizer(const Texture & source); virtual ~RandomSynthesizer(void); virtual string Synthesize(const Position & position, Texture & target) const; protected: const Texture & _source; }; #endif
17.068966
81
0.751515
1iyiwei
a96b79f4185018511ad52836bd23a6c7b577afcc
876
cpp
C++
src/frontends/tensorflow/src/op/slice.cpp
ryanloney/openvino-1
4e0a740eb3ee31062ba0df88fcf438564f67edb7
[ "Apache-2.0" ]
1,127
2018-10-15T14:36:58.000Z
2020-04-20T09:29:44.000Z
src/frontends/tensorflow/src/op/slice.cpp
ryanloney/openvino-1
4e0a740eb3ee31062ba0df88fcf438564f67edb7
[ "Apache-2.0" ]
439
2018-10-20T04:40:35.000Z
2020-04-19T05:56:25.000Z
src/frontends/tensorflow/src/op/slice.cpp
ryanloney/openvino-1
4e0a740eb3ee31062ba0df88fcf438564f67edb7
[ "Apache-2.0" ]
414
2018-10-17T05:53:46.000Z
2020-04-16T17:29:53.000Z
// Copyright (C) 2018-2022 Intel Corporation // SPDX-License-Identifier: Apache-2.0 // #include "op_table.hpp" #include "openvino/opsets/opset8.hpp" using namespace std; using namespace ov::opset8; namespace ov { namespace frontend { namespace tensorflow { namespace op { OutputVector translate_slice_op(const NodeContext& node) { auto input = node.get_input(0); auto start = node.get_input(1); auto size = node.get_input(2); auto stop = make_shared<Add>(start, size); auto one = make_shared<Constant>(element::i64, Shape{1}, 1); auto shape = make_shared<ShapeOf>(start); auto step = make_shared<Broadcast>(one, shape); auto res = make_shared<Slice>(input, start, stop, step); set_node_name(node.get_name(), res); return res->outputs(); } } // namespace op } // namespace tensorflow } // namespace frontend } // namespace ov
25.028571
64
0.697489
ryanloney
a96d3f67fa71635807792fd2038e9c3b8deb3d28
355
cc
C++
01_Basics/Variables3.cc
SEEM87/UdemyCpp
b1fe398c7134c74760341c9620eabca6c64043a9
[ "MIT" ]
14
2020-12-18T20:00:49.000Z
2022-02-23T12:44:26.000Z
01_Basics/Variables3.cc
SEEM87/UdemyCpp
b1fe398c7134c74760341c9620eabca6c64043a9
[ "MIT" ]
null
null
null
01_Basics/Variables3.cc
SEEM87/UdemyCpp
b1fe398c7134c74760341c9620eabca6c64043a9
[ "MIT" ]
56
2020-11-07T20:14:22.000Z
2022-03-31T12:36:09.000Z
#include <iostream> int main() { // 1 Byte = 8bit bool my_value0 = true; // false // 1 Byte = 8bit char my_value1 = 10; // 2 Byte = 16bit short my_value2 = 42; // 4 Byte = 32bit int my_value3 = 22; // 4 Byte = 32bit float my_value4 = 12.0f; // 8 Byte = 64bit double my_value5 = 13.0; return 0; }
14.2
35
0.535211
SEEM87
a96d9b4f9ac6218ac8509ce53b7741a842560504
899
cpp
C++
DSAA2/TestFastDisjSets.cpp
crosslife/DSAA
03472db6e61582187192073b6ea4649b6195222b
[ "MIT" ]
5
2017-03-30T23:23:08.000Z
2020-11-08T00:34:46.000Z
DSAA2/TestFastDisjSets.cpp
crosslife/DSAA
03472db6e61582187192073b6ea4649b6195222b
[ "MIT" ]
null
null
null
DSAA2/TestFastDisjSets.cpp
crosslife/DSAA
03472db6e61582187192073b6ea4649b6195222b
[ "MIT" ]
1
2019-04-12T13:17:31.000Z
2019-04-12T13:17:31.000Z
#include <iostream.h> #include "DisjSets.h" // Test main; all finds on same output line should be identical int main( ) { int numElements = 128; int numInSameSet = 16; DisjSets ds( numElements ); int set1, set2; for( int k = 1; k < numInSameSet; k *= 2 ) { for( int j = 0; j + k < numElements; j += 2 * k ) { set1 = ds.find( j ); set2 = ds.find( j + k ); ds.unionSets( set1, set2 ); } } for( int i = 0; i < numElements; i++ ) { cout << ds.find( i ) << "*"; if( i % numInSameSet == numInSameSet - 1 ) cout << endl; } cout << endl; return 0; }
27.242424
71
0.362625
crosslife
a96f83fa944ce9f5991efb911079510f47668262
6,810
cpp
C++
hamlet/utilities.cpp
delta4k/infinitelemurs
f0e09dcfdcf3b3e562775a7f6c8b979fed222038
[ "Apache-2.0" ]
null
null
null
hamlet/utilities.cpp
delta4k/infinitelemurs
f0e09dcfdcf3b3e562775a7f6c8b979fed222038
[ "Apache-2.0" ]
null
null
null
hamlet/utilities.cpp
delta4k/infinitelemurs
f0e09dcfdcf3b3e562775a7f6c8b979fed222038
[ "Apache-2.0" ]
null
null
null
/*****************************************************************************\ Copyright (c) 2011-2017 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 <cstdlib> #include <ctime> #include <cstdio> #include <conio.h> #include <cstdarg> #include <mutex> #include <set> #include "utilities.h" bool verboseOutput = true; // printf is only guaranteed to handle strings up to this length. // The Microsoft compiler handles much more than this, but // we want this to be as portable as reasonably possible. const int MAX_PRINTF_STRLEN = 4095; static char formatBuffer[MAX_PRINTF_STRLEN + 1]; static std::mutex formatMutex; #define FORMAT(fmt, buffer, bufflen) \ va_list argptr; \ va_start(argptr, fmt); \ int num_required = vsnprintf((buffer), (bufflen), (fmt), argptr); \ va_end(argptr); \ Assert(num_required < bufflen) /***********************************************\ Console output can slow a program down a lot. This is a printf-substitute that can be turned on or off. Use this only for stuff that you want to suppress when running flat-out for speed. Use plain-old printf for stuff that you want to always be printed. \***********************************************/ void prn(const char* fmt, ...) { if(!verboseOutput) return; std::lock_guard<std::mutex> lock{ formatMutex }; FORMAT(fmt, formatBuffer, MAX_PRINTF_STRLEN); printf("%s", formatBuffer); } /***********************************************\ Because printf-style formatting is just too nice to do without. \***********************************************/ std::string formatString(const char* fmt, ...) { std::lock_guard<std::mutex> lock{ formatMutex }; FORMAT(fmt, formatBuffer, MAX_PRINTF_STRLEN); std::string result(formatBuffer); return result; } /*****************************************************************************\ Return the size of the given file, or zero if the file can't be obtained \*****************************************************************************/ size_t getFileSize(const char* filename) { struct stat st; if (stat(filename, &st) != 0) { return 0; } return st.st_size; } /*****************************************************************************\ Load the given file into a single contiguous string. This function won't return if the load operation fails. It will fail for the usual reasons file operations fail, or if the file contains embedded zeros or characters that won't fit in a signed char. \*****************************************************************************/ std::string loadText(const char* fname) { std::string result; size_t size = getFileSize(fname); if(size > result.max_size()) { failf("File %s is too large for a single string", fname); } if(size == 0) { failf("Failure loading text file %s\n", fname); } // We use "rb" because we want an exact copy, with no // line ending translation. FILE* fp = fopen(fname, "rb"); if (!fp) { failf("Failure loading text file %s\n", fname); } result.reserve(size); char c = fgetc(fp); int charnum = 0; while(!feof(fp)) { if(c == 0) { failf("File contains embedded zero character in position %d\n", charnum); } if (c > 0x7E) { failf("Text contains non-printing character: (char)%d in character #%d\n", c, charnum); } result.push_back(c); c = fgetc(fp); charnum++; } return result; } /*****************************************************************************\ A simple, quick checksum, not intended for security or UUID purposes. \*****************************************************************************/ int checksum(const std::string& str) { int result = 0; for(auto c : str) { result += c; } return result; } /*****************************************************************************\ Fail sort of gracefully with an error message. \*****************************************************************************/ void failf(const char* fmt, ...) { // Something bad has happened, therefore we won't assume we can use // the shared format buffer. const int bufsize = 255; char failbuf[bufsize + 1]; FORMAT(fmt, failbuf, bufsize); printf("Failure: %s\n", failbuf); printf("Hit any key to exit..\n"); getch(); exit(-1); } /*****************************************************************************\ \*****************************************************************************/ Stopwatch::Stopwatch() { clock(); startTime = std::chrono::steady_clock::now(); } void Stopwatch::start() { startTime = std::chrono::steady_clock::now(); } double Stopwatch::elapsedSeconds() const { auto now = std::chrono::steady_clock::now(); std::chrono::duration<double> dt = now - startTime; double elapsed_seconds = dt.count(); return elapsed_seconds; } /*****************************************************************************\ Return the fractional difference between x and y: Abs(x-y) / Max(x,y) \*****************************************************************************/ double fractionalDifference(double x, double y) { double maxval = Max(Abs(x), Abs(y)); if (maxval == 0) return 0; double delta = Abs(x - y); // This is not intended as a general-purpose function that may // be called with pathological inputs, so we're going to be // pragmatic and not stress about things like overflows, except // for a basic sanity check. Assert(maxval > 1e-10); return delta / maxval; }
30
100
0.483847
delta4k
a972820ceae78b393e924d578b031d5218c3d373
19,771
cpp
C++
test/test_style.cpp
fargies/rapidyaml
6fd373c860b1eef3b190a521acabebc2fd2dcb04
[ "MIT" ]
null
null
null
test/test_style.cpp
fargies/rapidyaml
6fd373c860b1eef3b190a521acabebc2fd2dcb04
[ "MIT" ]
null
null
null
test/test_style.cpp
fargies/rapidyaml
6fd373c860b1eef3b190a521acabebc2fd2dcb04
[ "MIT" ]
null
null
null
#ifndef RYML_SINGLE_HEADER #include "c4/yml/std/std.hpp" #include "c4/yml/parse.hpp" #include "c4/yml/emit.hpp" #include <c4/format.hpp> #include <c4/yml/detail/checks.hpp> #include <c4/yml/detail/print.hpp> #endif #include "./test_case.hpp" #include <gtest/gtest.h> namespace c4 { namespace yml { std::string emit2str(Tree const& t) { return emitrs<std::string>(t); } TEST(style, flags) { Tree tree = parse_in_arena("foo: bar"); EXPECT_TRUE(tree.rootref().type().default_block()); EXPECT_FALSE(tree.rootref().type().marked_flow()); EXPECT_FALSE(tree.rootref().type().marked_flow_sl()); EXPECT_FALSE(tree.rootref().type().marked_flow_ml()); tree._add_flags(tree.root_id(), _WIP_STYLE_FLOW_SL); EXPECT_FALSE(tree.rootref().type().default_block()); EXPECT_TRUE(tree.rootref().type().marked_flow()); EXPECT_TRUE(tree.rootref().type().marked_flow_sl()); EXPECT_FALSE(tree.rootref().type().marked_flow_ml()); tree._rem_flags(tree.root_id(), _WIP_STYLE_FLOW_SL); tree._add_flags(tree.root_id(), _WIP_STYLE_FLOW_ML); EXPECT_FALSE(tree.rootref().type().default_block()); EXPECT_TRUE(tree.rootref().type().marked_flow()); EXPECT_FALSE(tree.rootref().type().marked_flow_sl()); EXPECT_TRUE(tree.rootref().type().marked_flow_ml()); } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- csubstr scalar_yaml = R"( this is the key: >- this is the multiline "val" with 'empty' lines )"; void check_same_emit(Tree const& expected) { #if 0 #define _showtrees(num) \ std::cout << "--------\nEMITTED" #num "\n--------\n"; \ std::cout << ws ## num; \ std::cout << "--------\nACTUAL" #num "\n--------\n"; \ print_tree(actual ## num); \ std::cout << "--------\nEXPECTED" #num "\n--------\n"; \ print_tree(expected) #else #define _showtrees(num) #endif std::string ws1, ws2, ws3, ws4; emitrs(expected, &ws1); { SCOPED_TRACE("actual1"); Tree actual1 = parse_in_arena(to_csubstr(ws1)); _showtrees(1); test_compare(actual1, expected); emitrs(actual1, &ws2); } { SCOPED_TRACE("actual2"); Tree actual2 = parse_in_arena(to_csubstr(ws2)); _showtrees(2); test_compare(actual2, expected); emitrs(actual2, &ws3); } { SCOPED_TRACE("actual3"); Tree actual3 = parse_in_arena(to_csubstr(ws3)); _showtrees(3); test_compare(actual3, expected); emitrs(actual3, &ws4); } { SCOPED_TRACE("actual4"); Tree actual4 = parse_in_arena(to_csubstr(ws4)); _showtrees(4); test_compare(actual4, expected); } } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- TEST(style, noflags) { Tree expected = parse_in_arena("{}"); NodeRef r = expected.rootref(); r["normal"] |= MAP; r["normal"]["singleline"] = "foo"; r["normal"]["multiline"] |= MAP; r["normal"]["multiline"]["____________"] = "foo"; r["normal"]["multiline"]["____mid_____"] = "foo\nbar"; r["normal"]["multiline"]["____mid_end1"] = "foo\nbar\n"; r["normal"]["multiline"]["____mid_end2"] = "foo\nbar\n\n"; r["normal"]["multiline"]["____mid_end3"] = "foo\nbar\n\n\n"; r["normal"]["multiline"]["____________"] = "foo"; r["normal"]["multiline"]["____________"] = "foo bar"; r["normal"]["multiline"]["________end1"] = "foo bar\n"; r["normal"]["multiline"]["________end2"] = "foo bar\n\n"; r["normal"]["multiline"]["________end3"] = "foo bar\n\n\n"; r["normal"]["multiline"]["beg_________"] = "\nfoo"; r["normal"]["multiline"]["beg_mid_____"] = "\nfoo\nbar"; r["normal"]["multiline"]["beg_mid_end1"] = "\nfoo\nbar\n"; r["normal"]["multiline"]["beg_mid_end2"] = "\nfoo\nbar\n\n"; r["normal"]["multiline"]["beg_mid_end3"] = "\nfoo\nbar\n\n\n"; r["leading_ws"] |= MAP; r["leading_ws"]["singleline"] |= MAP; r["leading_ws"]["singleline"]["space"] = " foo"; r["leading_ws"]["singleline"]["tab"] = "\tfoo"; r["leading_ws"]["singleline"]["space_and_tab0"] = " \tfoo"; r["leading_ws"]["singleline"]["space_and_tab1"] = "\t foo"; r["leading_ws"]["multiline"] |= MAP; r["leading_ws"]["multiline"]["beg_________"] = "\n \tfoo"; r["leading_ws"]["multiline"]["beg_mid_____"] = "\n \tfoo\nbar"; r["leading_ws"]["multiline"]["beg_mid_end1"] = "\n \tfoo\nbar\n"; r["leading_ws"]["multiline"]["beg_mid_end2"] = "\n \tfoo\nbar\n\n"; r["leading_ws"]["multiline"]["beg_mid_end3"] = "\n \tfoo\nbar\n\n\n"; check_same_emit(expected); } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- #ifdef WIP TEST(style, scalar_retains_style_after_parse) { { Tree t = parse_in_arena("foo"); EXPECT_TRUE(t.rootref().type().val_marked_plain()); EXPECT_FALSE(t.rootref().type().val_marked_squo()); EXPECT_FALSE(t.rootref().type().val_marked_dquo()); EXPECT_FALSE(t.rootref().type().val_marked_literal()); EXPECT_FALSE(t.rootref().type().val_marked_folded()); EXPECT_EQ(emitrs<std::string>(t), std::string("foo\n")); } { Tree t = parse_in_arena("'foo'"); EXPECT_FALSE(t.rootref().type().val_marked_plain()); EXPECT_TRUE(t.rootref().type().val_marked_squo()); EXPECT_FALSE(t.rootref().type().val_marked_dquo()); EXPECT_FALSE(t.rootref().type().val_marked_literal()); EXPECT_FALSE(t.rootref().type().val_marked_folded()); EXPECT_EQ(emitrs<std::string>(t), std::string("'foo'\n")); } { Tree t = parse_in_arena("'foo'"); EXPECT_FALSE(t.rootref().type().val_marked_plain()); EXPECT_FALSE(t.rootref().type().val_marked_squo()); EXPECT_TRUE(t.rootref().type().val_marked_dquo()); EXPECT_FALSE(t.rootref().type().val_marked_literal()); EXPECT_FALSE(t.rootref().type().val_marked_folded()); EXPECT_EQ(emitrs<std::string>(t), std::string("'foo'\n")); } { Tree t = parse_in_arena("[foo, 'baz', \"bat\"]"); EXPECT_TRUE(t.rootref().type().marked_flow()); EXPECT_TRUE(t[0].type().val_marked_plain()); EXPECT_FALSE(t[0].type().val_marked_squo()); EXPECT_FALSE(t[0].type().val_marked_dquo()); EXPECT_FALSE(t[0].type().val_marked_literal()); EXPECT_FALSE(t[0].type().val_marked_folded()); EXPECT_FALSE(t[1].type().val_marked_plain()); EXPECT_TRUE(t[1].type().val_marked_squo()); EXPECT_FALSE(t[1].type().val_marked_dquo()); EXPECT_FALSE(t[1].type().val_marked_literal()); EXPECT_FALSE(t[1].type().val_marked_folded()); EXPECT_FALSE(t[2].type().val_marked_plain()); EXPECT_FALSE(t[2].type().val_marked_squo()); EXPECT_TRUE(t[2].type().val_marked_dquo()); EXPECT_FALSE(t[2].type().val_marked_literal()); EXPECT_FALSE(t[2].type().val_marked_folded()); EXPECT_EQ(emitrs<std::string>(t), std::string("foo")); } } #endif //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- TEST(scalar, base) { Tree tree = parse_in_arena(scalar_yaml); EXPECT_EQ(tree[0].key(), csubstr("this is the key")); EXPECT_EQ(tree[0].val(), csubstr("this is the multiline \"val\" with\n'empty' lines")); EXPECT_EQ(emit2str(tree), R"(this is the key: |- this is the multiline "val" with 'empty' lines )"); check_same_emit(tree); } TEST(scalar, block_literal) { Tree tree = parse_in_arena(scalar_yaml); { SCOPED_TRACE("val only"); EXPECT_FALSE(tree[0].type().key_marked_literal()); EXPECT_FALSE(tree[0].type().val_marked_literal()); tree._add_flags(tree[0].id(), _WIP_VAL_LITERAL); EXPECT_FALSE(tree[0].type().key_marked_literal()); EXPECT_TRUE(tree[0].type().val_marked_literal()); EXPECT_EQ(emit2str(tree), R"(this is the key: |- this is the multiline "val" with 'empty' lines )"); check_same_emit(tree); } { SCOPED_TRACE("key+val"); tree._add_flags(tree[0].id(), _WIP_KEY_LITERAL); EXPECT_TRUE(tree[0].type().key_marked_literal()); EXPECT_TRUE(tree[0].type().val_marked_literal()); EXPECT_EQ(emit2str(tree), R"(? |- this is the key : |- this is the multiline "val" with 'empty' lines )"); check_same_emit(tree); } { SCOPED_TRACE("key only"); tree._rem_flags(tree[0].id(), _WIP_VAL_LITERAL); EXPECT_TRUE(tree[0].type().key_marked_literal()); EXPECT_FALSE(tree[0].type().val_marked_literal()); EXPECT_EQ(emit2str(tree), R"(? |- this is the key : |- this is the multiline "val" with 'empty' lines )"); check_same_emit(tree); } } TEST(scalar, block_folded) { Tree tree = parse_in_arena(scalar_yaml); { SCOPED_TRACE("val only"); EXPECT_FALSE(tree[0].type().key_marked_folded()); EXPECT_FALSE(tree[0].type().val_marked_folded()); tree._add_flags(tree[0].id(), _WIP_VAL_FOLDED); EXPECT_FALSE(tree[0].type().key_marked_folded()); EXPECT_TRUE(tree[0].type().val_marked_folded()); EXPECT_EQ(emit2str(tree), R"(this is the key: >- this is the multiline "val" with 'empty' lines )"); check_same_emit(tree); } { SCOPED_TRACE("key+val"); tree._add_flags(tree[0].id(), _WIP_KEY_FOLDED); EXPECT_TRUE(tree[0].type().key_marked_folded()); EXPECT_TRUE(tree[0].type().val_marked_folded()); EXPECT_EQ(emit2str(tree), R"(? >- this is the key : >- this is the multiline "val" with 'empty' lines )"); check_same_emit(tree); } { SCOPED_TRACE("val only"); tree._rem_flags(tree[0].id(), _WIP_VAL_FOLDED); EXPECT_TRUE(tree[0].type().key_marked_folded()); EXPECT_FALSE(tree[0].type().val_marked_folded()); EXPECT_EQ(emit2str(tree), R"(? >- this is the key : |- this is the multiline "val" with 'empty' lines )"); check_same_emit(tree); } } TEST(scalar, squot) { Tree tree = parse_in_arena(scalar_yaml); EXPECT_FALSE(tree[0].type().key_marked_squo()); EXPECT_FALSE(tree[0].type().val_marked_squo()); { SCOPED_TRACE("val only"); tree._add_flags(tree[0].id(), _WIP_VAL_SQUO); EXPECT_FALSE(tree[0].type().key_marked_squo()); EXPECT_TRUE(tree[0].type().val_marked_squo()); EXPECT_EQ(emit2str(tree), R"(this is the key: 'this is the multiline "val" with ''empty'' lines' )"); check_same_emit(tree); } { SCOPED_TRACE("key+val"); tree._add_flags(tree[0].id(), _WIP_KEY_SQUO); EXPECT_TRUE(tree[0].type().key_marked_squo()); EXPECT_TRUE(tree[0].type().val_marked_squo()); EXPECT_EQ(emit2str(tree), R"('this is the key': 'this is the multiline "val" with ''empty'' lines' )"); check_same_emit(tree); } { SCOPED_TRACE("key only"); tree._rem_flags(tree[0].id(), _WIP_VAL_SQUO); EXPECT_TRUE(tree[0].type().key_marked_squo()); EXPECT_FALSE(tree[0].type().val_marked_squo()); EXPECT_EQ(emit2str(tree), R"('this is the key': |- this is the multiline "val" with 'empty' lines )"); check_same_emit(tree); } } TEST(scalar, dquot) { Tree tree = parse_in_arena(scalar_yaml); EXPECT_FALSE(tree[0].type().key_marked_dquo()); EXPECT_FALSE(tree[0].type().val_marked_dquo()); { SCOPED_TRACE("val only"); tree._add_flags(tree[0].id(), _WIP_VAL_DQUO); EXPECT_FALSE(tree[0].type().key_marked_dquo()); EXPECT_TRUE(tree[0].type().val_marked_dquo()); // visual studio fails to compile this string when used inside // the EXPECT_EQ() macro below. So we declare it separately // instead: csubstr yaml = R"(this is the key: "this is the multiline \"val\" with 'empty' lines" )"; EXPECT_EQ(emit2str(tree), yaml); check_same_emit(tree); } { SCOPED_TRACE("key+val"); tree._add_flags(tree[0].id(), _WIP_KEY_DQUO); EXPECT_TRUE(tree[0].type().key_marked_dquo()); EXPECT_TRUE(tree[0].type().val_marked_dquo()); // visual studio fails to compile this string when used inside // the EXPECT_EQ() macro below. So we declare it separately // instead: csubstr yaml = R"("this is the key": "this is the multiline \"val\" with 'empty' lines" )"; EXPECT_EQ(emit2str(tree), yaml); check_same_emit(tree); } { SCOPED_TRACE("key only"); tree._rem_flags(tree[0].id(), _WIP_VAL_DQUO); EXPECT_TRUE(tree[0].type().key_marked_dquo()); EXPECT_FALSE(tree[0].type().val_marked_dquo()); EXPECT_EQ(emit2str(tree), R"("this is the key": |- this is the multiline "val" with 'empty' lines )"); check_same_emit(tree); } } TEST(scalar, plain) { Tree tree = parse_in_arena(scalar_yaml); EXPECT_FALSE(tree[0].type().key_marked_plain()); EXPECT_FALSE(tree[0].type().val_marked_plain()); { SCOPED_TRACE("val only"); tree._add_flags(tree[0].id(), _WIP_VAL_PLAIN); EXPECT_FALSE(tree[0].type().key_marked_plain()); EXPECT_TRUE(tree[0].type().val_marked_plain()); EXPECT_EQ(emit2str(tree), R"(this is the key: this is the multiline "val" with 'empty' lines )"); check_same_emit(tree); } { SCOPED_TRACE("key+val"); tree._add_flags(tree[0].id(), _WIP_KEY_PLAIN); EXPECT_TRUE(tree[0].type().key_marked_plain()); EXPECT_TRUE(tree[0].type().val_marked_plain()); EXPECT_EQ(emit2str(tree), R"(this is the key: this is the multiline "val" with 'empty' lines )"); check_same_emit(tree); } { SCOPED_TRACE("key only"); tree._rem_flags(tree[0].id(), _WIP_VAL_PLAIN); EXPECT_TRUE(tree[0].type().key_marked_plain()); EXPECT_FALSE(tree[0].type().val_marked_plain()); EXPECT_EQ(emit2str(tree), R"(this is the key: |- this is the multiline "val" with 'empty' lines )"); check_same_emit(tree); } } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- TEST(stream, block) { Tree tree = parse_in_arena(R"( --- scalar %YAML 1.2 --- foo --- bar )"); EXPECT_TRUE(tree.rootref().is_stream()); EXPECT_TRUE(tree.docref(0).is_doc()); EXPECT_TRUE(tree.docref(0).is_val()); EXPECT_EQ(emit2str(tree), "--- scalar %YAML 1.2\n--- foo\n--- bar\n"); tree._add_flags(tree.root_id(), _WIP_STYLE_FLOW_SL); EXPECT_EQ(emit2str(tree), "--- scalar %YAML 1.2\n--- foo\n--- bar\n"); } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- TEST(seq, block) { Tree tree = parse_in_arena("[1, 2, 3, 4, 5, 6]"); EXPECT_EQ(emit2str(tree), R"(- 1 - 2 - 3 - 4 - 5 - 6 )"); } TEST(seq, flow_sl) { Tree tree = parse_in_arena("[1, 2, 3, 4, 5, 6]"); tree._add_flags(tree.root_id(), _WIP_STYLE_FLOW_SL); EXPECT_EQ(emit2str(tree), R"([1,2,3,4,5,6])"); } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- TEST(keyseq, block) { Tree tree = parse_in_arena("{foo: [1, 2, 3, 4, 5, 6]}"); EXPECT_TRUE(tree.rootref().type().default_block()); EXPECT_EQ(emit2str(tree), R"(foo: - 1 - 2 - 3 - 4 - 5 - 6 )"); tree = parse_in_arena("{foo: [1, [2, 3], 4, [5, 6]]}"); EXPECT_EQ(emit2str(tree), R"(foo: - 1 - - 2 - 3 - 4 - - 5 - 6 )"); } TEST(keyseq, flow_sl) { Tree tree = parse_in_arena("{foo: [1, 2, 3, 4, 5, 6]}"); EXPECT_TRUE(tree.rootref().type().default_block()); tree._add_flags(tree.root_id(), _WIP_STYLE_FLOW_SL); EXPECT_FALSE(tree.rootref().type().default_block()); EXPECT_EQ(emit2str(tree), R"({foo: [1,2,3,4,5,6]})"); // tree = parse_in_arena("{foo: [1, [2, 3], 4, [5, 6]]}"); tree._add_flags(tree.root_id(), _WIP_STYLE_FLOW_SL); EXPECT_EQ(emit2str(tree), R"({foo: [1,[2,3],4,[5,6]]})"); // tree._rem_flags(tree.root_id(), _WIP_STYLE_FLOW_SL); tree._add_flags(tree["foo"][1].id(), _WIP_STYLE_FLOW_SL); tree._add_flags(tree["foo"][3].id(), _WIP_STYLE_FLOW_SL); EXPECT_EQ(emit2str(tree), R"(foo: - 1 - [2,3] - 4 - [5,6] )"); } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- TEST(map, block) { Tree tree = parse_in_arena("{1: 10, 2: 10, 3: 10, 4: 10, 5: 10, 6: 10}"); EXPECT_EQ(emit2str(tree), R"(1: 10 2: 10 3: 10 4: 10 5: 10 6: 10 )"); } TEST(map, flow_sl) { Tree tree = parse_in_arena("{1: 10, 2: 10, 3: 10, 4: 10, 5: 10, 6: 10}"); tree._add_flags(tree.root_id(), _WIP_STYLE_FLOW_SL); EXPECT_EQ(emit2str(tree), R"({1: 10,2: 10,3: 10,4: 10,5: 10,6: 10})"); } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- TEST(keymap, block) { Tree tree = parse_in_arena("{foo: {1: 10, 2: 10, 3: 10, 4: 10, 5: 10, 6: 10}}"); EXPECT_EQ(emit2str(tree), R"(foo: 1: 10 2: 10 3: 10 4: 10 5: 10 6: 10 )"); } TEST(keymap, flow_sl) { Tree tree = parse_in_arena("{foo: {1: 10, 2: 10, 3: 10, 4: 10, 5: 10, 6: 10}}"); tree._add_flags(tree.root_id(), _WIP_STYLE_FLOW_SL); EXPECT_EQ(emit2str(tree), R"({foo: {1: 10,2: 10,3: 10,4: 10,5: 10,6: 10}})"); // tree = parse_in_arena("{foo: {1: 10, 2: {2: 10, 3: 10}, 4: 10, 5: {5: 10, 6: 10}}}"); EXPECT_EQ(emit2str(tree), R"(foo: 1: 10 2: 2: 10 3: 10 4: 10 5: 5: 10 6: 10 )"); tree._add_flags(tree.root_id(), _WIP_STYLE_FLOW_SL); EXPECT_EQ(emit2str(tree), R"({foo: {1: 10,2: {2: 10,3: 10},4: 10,5: {5: 10,6: 10}}})"); tree._rem_flags(tree.root_id(), _WIP_STYLE_FLOW_SL); tree._add_flags(tree["foo"][1].id(), _WIP_STYLE_FLOW_SL); tree._add_flags(tree["foo"][3].id(), _WIP_STYLE_FLOW_SL); EXPECT_EQ(emit2str(tree), R"(foo: 1: 10 2: {2: 10,3: 10} 4: 10 5: {5: 10,6: 10} )"); } //------------------------------------------- // this is needed to use the test case library Case const* get_case(csubstr /*name*/) { return nullptr; } } // namespace yml } // namespace c4
32.04376
91
0.530019
fargies
a973eeb8b5a9e4755937fe237f6a9d598744d314
26,091
cc
C++
src/storage/fshost/block-watcher-test.cc
oshunter/fuchsia
2196fc8c176d01969466b97bba3f31ec55f7767b
[ "BSD-3-Clause" ]
2
2020-08-16T15:32:35.000Z
2021-11-07T20:09:46.000Z
src/storage/fshost/block-watcher-test.cc
oshunter/fuchsia
2196fc8c176d01969466b97bba3f31ec55f7767b
[ "BSD-3-Clause" ]
null
null
null
src/storage/fshost/block-watcher-test.cc
oshunter/fuchsia
2196fc8c176d01969466b97bba3f31ec55f7767b
[ "BSD-3-Clause" ]
null
null
null
// Copyright 2019 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <fuchsia/device/llcpp/fidl.h> #include <fuchsia/fshost/llcpp/fidl.h> #include <lib/devmgr-integration-test/fixture.h> #include <lib/driver-integration-test/fixture.h> #include <lib/fdio/cpp/caller.h> #include <lib/fdio/directory.h> #include <lib/fdio/watcher.h> #include <zircon/assert.h> #include <zircon/device/block.h> #include <zircon/hw/gpt.h> #include <ramdevice-client/ramdisk.h> #include <zxtest/zxtest.h> #include "block-device-interface.h" #include "block-watcher-test-data.h" #include "encrypted-volume-interface.h" namespace { using devmgr_integration_test::RecursiveWaitForFile; using driver_integration_test::IsolatedDevmgr; class MockBlockDevice : public devmgr::BlockDeviceInterface { public: disk_format_t GetFormat() override = 0; void SetFormat(disk_format_t format) override { ZX_PANIC("Test should not invoke function %s\n", __FUNCTION__); } bool Netbooting() override { return false; } zx_status_t GetInfo(fuchsia_hardware_block_BlockInfo* out_info) override { fuchsia_hardware_block_BlockInfo info = {}; info.flags = 0; info.block_size = 512; info.block_count = 1024; *out_info = info; return ZX_OK; } zx_status_t GetTypeGUID(fuchsia_hardware_block_partition_GUID* out_guid) override { ZX_PANIC("Test should not invoke function %s\n", __FUNCTION__); } zx_status_t AttachDriver(const std::string_view& driver) override { ZX_PANIC("Test should not invoke function %s\n", __FUNCTION__); } zx_status_t UnsealZxcrypt() override { ZX_PANIC("Test should not invoke function %s\n", __FUNCTION__); } zx_status_t IsTopologicalPathSuffix(const std::string_view& expected_path, bool* is_path) override { ZX_PANIC("Test should not invoke function %s\n", __FUNCTION__); } zx_status_t IsUnsealedZxcrypt(bool* is_unsealed_zxcrypt) override { ZX_PANIC("Test should not invoke function %s\n", __FUNCTION__); } zx_status_t FormatZxcrypt() override { ZX_PANIC("Test should not invoke function %s\n", __FUNCTION__); } bool ShouldCheckFilesystems() override { ZX_PANIC("Test should not invoke function %s\n", __FUNCTION__); } zx_status_t CheckFilesystem() override { ZX_PANIC("Test should not invoke function %s\n", __FUNCTION__); } zx_status_t FormatFilesystem() override { ZX_PANIC("Test should not invoke function %s\n", __FUNCTION__); } zx_status_t MountFilesystem() override { ZX_PANIC("Test should not invoke function %s\n", __FUNCTION__); } }; // Tests adding a device which has no GUID and an unknown format. TEST(AddDeviceTestCase, AddUnknownDevice) { class UnknownDevice : public MockBlockDevice { public: disk_format_t GetFormat() final { return DISK_FORMAT_UNKNOWN; } zx_status_t GetTypeGUID(fuchsia_hardware_block_partition_GUID* out_guid) final { return ZX_ERR_NOT_SUPPORTED; } }; UnknownDevice device; EXPECT_EQ(ZX_ERR_NOT_SUPPORTED, device.Add()); } // Tests adding a device with an unknown GUID and unknown format. TEST(AddDeviceTestCase, AddUnknownPartition) { class UnknownDevice : public MockBlockDevice { public: disk_format_t GetFormat() final { return DISK_FORMAT_UNKNOWN; } zx_status_t GetTypeGUID(fuchsia_hardware_block_partition_GUID* out_guid) final { const uint8_t expected[GPT_GUID_LEN] = GUID_EMPTY_VALUE; memcpy(out_guid->value, expected, sizeof(expected)); return ZX_OK; } }; UnknownDevice device; EXPECT_EQ(ZX_ERR_NOT_SUPPORTED, device.Add()); } // Tests adding a device which is smaller than the expected header size TEST(AddDeviceTestCase, AddSmallDevice) { class SmallDevice : public MockBlockDevice { public: disk_format_t GetFormat() final { return DISK_FORMAT_UNKNOWN; } zx_status_t GetTypeGUID(fuchsia_hardware_block_partition_GUID* out_guid) final { return ZX_ERR_NOT_SUPPORTED; } zx_status_t GetInfo(fuchsia_hardware_block_BlockInfo* out_info) override { fuchsia_hardware_block_BlockInfo info = {}; info.flags = 0; info.block_size = 512; info.block_count = 1; *out_info = info; return ZX_OK; } }; SmallDevice device; EXPECT_EQ(ZX_ERR_NOT_SUPPORTED, device.Add()); } // Tests adding a device with a GPT format. TEST(AddDeviceTestCase, AddGPTDevice) { class GptDevice : public MockBlockDevice { public: disk_format_t GetFormat() final { return DISK_FORMAT_GPT; } zx_status_t AttachDriver(const std::string_view& driver) final { EXPECT_STR_EQ(devmgr::kGPTDriverPath, driver.data()); attached = true; return ZX_OK; } bool attached = false; }; GptDevice device; EXPECT_OK(device.Add()); EXPECT_TRUE(device.attached); } // Tests adding a device with an FVM format. TEST(AddDeviceTestCase, AddFVMDevice) { class FvmDevice : public MockBlockDevice { public: disk_format_t GetFormat() final { return DISK_FORMAT_FVM; } zx_status_t AttachDriver(const std::string_view& driver) final { EXPECT_STR_EQ(devmgr::kFVMDriverPath, driver.data()); attached = true; return ZX_OK; } bool attached = false; }; FvmDevice device; EXPECT_OK(device.Add()); EXPECT_TRUE(device.attached); } // Tests adding a device with an MBR format. TEST(AddDeviceTestCase, AddMBRDevice) { class MbrDevice : public MockBlockDevice { public: disk_format_t GetFormat() final { return DISK_FORMAT_MBR; } zx_status_t AttachDriver(const std::string_view& driver) final { EXPECT_STR_EQ(devmgr::kMBRDriverPath, driver.data()); attached = true; return ZX_OK; } bool attached = false; }; MbrDevice device; EXPECT_OK(device.Add()); EXPECT_TRUE(device.attached); } // Tests adding a device with a factory GUID but an unknown disk format. TEST(AddDeviceTestCase, AddUnformattedBlockVerityDevice) { class BlockVerityDevice : public MockBlockDevice { public: // in FCT mode we need to be able to bind the block-verity driver to devices that don't yet // have detectable magic, so Add relies on the gpt guid. disk_format_t GetFormat() final { return DISK_FORMAT_UNKNOWN; } zx_status_t AttachDriver(const std::string_view& driver) final { EXPECT_STR_EQ(devmgr::kBlockVerityDriverPath, driver.data()); attached = true; return ZX_OK; } zx_status_t IsTopologicalPathSuffix(const std::string_view& expected_path, bool* is_path) final { EXPECT_STR_EQ("/mutable/block", expected_path.data()); *is_path = false; return ZX_OK; } zx_status_t GetTypeGUID(fuchsia_hardware_block_partition_GUID* out_guid) final { *out_guid = GPT_FACTORY_TYPE_GUID; return ZX_OK; } bool attached = false; }; BlockVerityDevice device; EXPECT_OK(device.Add()); EXPECT_TRUE(device.attached); } // Tests adding a device with a factory GUID but an unknown disk format with the topological path // suffix /mutable/block TEST(AddDeviceTestCase, AddUnformattedMutableBlockVerityDevice) { class BlockVerityDevice : public MockBlockDevice { public: disk_format_t GetFormat() final { return DISK_FORMAT_UNKNOWN; } zx_status_t AttachDriver(const std::string_view& driver) final { ADD_FATAL_FAILURE("Should not attach a driver"); return ZX_OK; } zx_status_t IsTopologicalPathSuffix(const std::string_view& expected_path, bool* is_path) final { EXPECT_STR_EQ("/mutable/block", expected_path.data()); *is_path = true; return ZX_OK; } zx_status_t GetTypeGUID(fuchsia_hardware_block_partition_GUID* out_guid) final { *out_guid = GPT_FACTORY_TYPE_GUID; return ZX_OK; } }; BlockVerityDevice device; EXPECT_OK(device.Add()); } // Tests adding a device with the block-verity disk format. TEST(AddDeviceTestCase, AddFormattedBlockVerityDevice) { class BlockVerityDevice : public MockBlockDevice { public: disk_format_t GetFormat() final { return DISK_FORMAT_BLOCK_VERITY; } zx_status_t AttachDriver(const std::string_view& driver) final { EXPECT_STR_EQ(devmgr::kBlockVerityDriverPath, driver.data()); attached = true; return ZX_OK; } bool attached = false; }; BlockVerityDevice device; EXPECT_OK(device.Add()); EXPECT_TRUE(device.attached); } // Tests adding blobfs which does not not have a valid type GUID. TEST(AddDeviceTestCase, AddNoGUIDBlobDevice) { class BlobDevice : public MockBlockDevice { public: disk_format_t GetFormat() final { return DISK_FORMAT_BLOBFS; } zx_status_t GetTypeGUID(fuchsia_hardware_block_partition_GUID* out_guid) final { *out_guid = GUID_TEST_VALUE; return ZX_OK; } zx_status_t CheckFilesystem() final { ADD_FATAL_FAILURE("Should not check filesystem"); return ZX_OK; } zx_status_t MountFilesystem() final { ADD_FATAL_FAILURE("Should not mount filesystem"); return ZX_OK; } }; BlobDevice device; EXPECT_EQ(ZX_ERR_INVALID_ARGS, device.Add()); } // Tests adding blobfs with a valid type GUID, but invalid metadata. TEST(AddDeviceTestCase, AddInvalidBlobDevice) { class BlobDevice : public MockBlockDevice { public: disk_format_t GetFormat() final { return DISK_FORMAT_BLOBFS; } zx_status_t GetTypeGUID(fuchsia_hardware_block_partition_GUID* out_guid) final { const uint8_t expected[GPT_GUID_LEN] = GUID_BLOB_VALUE; memcpy(out_guid->value, expected, sizeof(expected)); return ZX_OK; } zx_status_t CheckFilesystem() final { checked = true; return ZX_ERR_BAD_STATE; } zx_status_t FormatFilesystem() final { formatted = true; return ZX_OK; } zx_status_t MountFilesystem() final { mounted = true; return ZX_OK; } bool checked = false; bool formatted = false; bool mounted = false; }; BlobDevice device; EXPECT_EQ(ZX_ERR_BAD_STATE, device.Add()); EXPECT_TRUE(device.checked); EXPECT_FALSE(device.formatted); EXPECT_FALSE(device.mounted); } // Tests adding blobfs with a valid type GUID and valid metadata. TEST(AddDeviceTestCase, AddValidBlobDevice) { class BlobDevice : public MockBlockDevice { public: disk_format_t GetFormat() final { return DISK_FORMAT_BLOBFS; } zx_status_t GetTypeGUID(fuchsia_hardware_block_partition_GUID* out_guid) final { const uint8_t expected[GPT_GUID_LEN] = GUID_BLOB_VALUE; memcpy(out_guid->value, expected, sizeof(expected)); return ZX_OK; } zx_status_t CheckFilesystem() final { checked = true; return ZX_OK; } zx_status_t FormatFilesystem() final { formatted = true; return ZX_OK; } zx_status_t MountFilesystem() final { mounted = true; return ZX_OK; } bool checked = false; bool formatted = false; bool mounted = false; }; BlobDevice device; EXPECT_OK(device.Add()); EXPECT_TRUE(device.checked); EXPECT_FALSE(device.formatted); EXPECT_TRUE(device.mounted); } // Tests adding minfs which does not not have a valid type GUID. TEST(AddDeviceTestCase, AddNoGUIDMinfsDevice) { class MinfsDevice : public MockBlockDevice { public: disk_format_t GetFormat() final { return DISK_FORMAT_MINFS; } zx_status_t GetTypeGUID(fuchsia_hardware_block_partition_GUID* out_guid) final { *out_guid = GUID_TEST_VALUE; return ZX_OK; } zx_status_t CheckFilesystem() final { ADD_FATAL_FAILURE("Should not check filesystem"); return ZX_OK; } zx_status_t MountFilesystem() final { ADD_FATAL_FAILURE("Should not mount filesystem"); return ZX_OK; } }; MinfsDevice device; EXPECT_EQ(ZX_ERR_INVALID_ARGS, device.Add()); } // Tests adding minfs with a valid type GUID and invalid metadata. Observe that // the filesystem reformats itself. TEST(AddDeviceTestCase, AddInvalidMinfsDevice) { class MinfsDevice : public MockBlockDevice { public: disk_format_t GetFormat() final { return DISK_FORMAT_MINFS; } zx_status_t GetTypeGUID(fuchsia_hardware_block_partition_GUID* out_guid) final { const uint8_t expected[GPT_GUID_LEN] = GUID_DATA_VALUE; memcpy(out_guid->value, expected, sizeof(expected)); return ZX_OK; } zx_status_t CheckFilesystem() final { checked = true; return ZX_ERR_BAD_STATE; } zx_status_t FormatFilesystem() final { formatted = true; return ZX_OK; } zx_status_t MountFilesystem() final { mounted = true; return ZX_OK; } bool checked = false; bool formatted = false; bool mounted = false; }; MinfsDevice device; EXPECT_OK(device.Add()); EXPECT_TRUE(device.checked); EXPECT_TRUE(device.formatted); EXPECT_TRUE(device.mounted); } // Tests adding minfs with a valid type GUID and invalid format. Observe that // the filesystem reformats itself. TEST(AddDeviceTestCase, AddUnknownFormatMinfsDevice) { class MinfsDevice : public MockBlockDevice { public: disk_format_t GetFormat() final { return format; } zx_status_t GetTypeGUID(fuchsia_hardware_block_partition_GUID* out_guid) final { const uint8_t expected[GPT_GUID_LEN] = GUID_DATA_VALUE; memcpy(out_guid->value, expected, sizeof(expected)); return ZX_OK; } zx_status_t FormatFilesystem() final { formatted = true; return ZX_OK; } zx_status_t CheckFilesystem() final { return ZX_OK; } zx_status_t MountFilesystem() final { EXPECT_TRUE(formatted); mounted = true; return ZX_OK; } zx_status_t IsUnsealedZxcrypt(bool* is_unsealed_zxcrypt) final { *is_unsealed_zxcrypt = true; return ZX_OK; } void SetFormat(disk_format_t f) final { format = f; } disk_format_t format = DISK_FORMAT_UNKNOWN; bool formatted = false; bool mounted = false; }; MinfsDevice device; EXPECT_FALSE(device.formatted); EXPECT_FALSE(device.mounted); EXPECT_OK(device.Add()); EXPECT_TRUE(device.formatted); EXPECT_TRUE(device.mounted); } // Tests adding zxcrypt with a valid type GUID and invalid format. Observe that // the partition reformats itself. TEST(AddDeviceTestCase, AddUnknownFormatZxcryptDevice) { class ZxcryptDevice : public MockBlockDevice { public: disk_format_t GetFormat() final { return format; } zx_status_t GetTypeGUID(fuchsia_hardware_block_partition_GUID* out_guid) final { const uint8_t expected[GPT_GUID_LEN] = GUID_DATA_VALUE; memcpy(out_guid->value, expected, sizeof(expected)); return ZX_OK; } zx_status_t FormatZxcrypt() final { formatted_zxcrypt = true; return ZX_OK; } zx_status_t FormatFilesystem() final { formatted_filesystem = true; return ZX_OK; } zx_status_t CheckFilesystem() final { return ZX_OK; } zx_status_t UnsealZxcrypt() final { return ZX_OK; } zx_status_t IsUnsealedZxcrypt(bool* is_unsealed_zxcrypt) final { *is_unsealed_zxcrypt = false; return ZX_OK; } void SetFormat(disk_format_t f) final { format = f; } zx_status_t AttachDriver(const std::string_view& driver) final { EXPECT_STR_EQ(devmgr::kZxcryptDriverPath, driver.data()); return ZX_OK; } disk_format_t format = DISK_FORMAT_UNKNOWN; bool formatted_zxcrypt = false; bool formatted_filesystem = false; }; ZxcryptDevice device; EXPECT_OK(device.Add()); EXPECT_TRUE(device.formatted_zxcrypt); EXPECT_FALSE(device.formatted_filesystem); } // Tests adding a boot partition device with unknown format can be added with // the correct driver. TEST(AddDeviceTestCase, AddUnknownFormatBootPartitionDevice) { class BootPartDevice : public MockBlockDevice { public: disk_format_t GetFormat() final { return DISK_FORMAT_UNKNOWN; } zx_status_t GetInfo(fuchsia_hardware_block_BlockInfo* out_info) override { fuchsia_hardware_block_BlockInfo info = {}; info.flags = BLOCK_FLAG_BOOTPART; info.block_size = 512; info.block_count = 1024; *out_info = info; return ZX_OK; } zx_status_t AttachDriver(const std::string_view& driver) final { EXPECT_STR_EQ(devmgr::kBootpartDriverPath, driver.data()); return ZX_OK; } zx_status_t IsUnsealedZxcrypt(bool* is_unsealed_zxcrypt) final { *is_unsealed_zxcrypt = false; checked_unsealed_zxcrypt = true; return ZX_OK; } bool checked_unsealed_zxcrypt = false; }; BootPartDevice device; EXPECT_OK(device.Add()); EXPECT_FALSE(device.checked_unsealed_zxcrypt); } TEST(AddDeviceTestCase, AddPermanentlyMiskeyedZxcryptVolume) { class ZxcryptVolume : public devmgr::EncryptedVolumeInterface { public: zx_status_t Unseal() final { // Simulate a device where we've lost the key -- can't unlock until we // format the device with a new key, but can afterwards. if (formatted) { postformat_unseal_attempt_count++; return ZX_OK; } else { preformat_unseal_attempt_count++; return ZX_ERR_ACCESS_DENIED; } } zx_status_t Format() final { formatted = true; return ZX_OK; } int preformat_unseal_attempt_count = 0; int postformat_unseal_attempt_count = 0; bool formatted = false; }; ZxcryptVolume volume; EXPECT_OK(volume.EnsureUnsealedAndFormatIfNeeded()); EXPECT_TRUE(volume.preformat_unseal_attempt_count > 1); EXPECT_TRUE(volume.formatted); EXPECT_EQ(volume.postformat_unseal_attempt_count, 1); } TEST(AddDeviceTestCase, AddTransientlyMiskeyedZxcryptVolume) { class ZxcryptVolume : public devmgr::EncryptedVolumeInterface { public: zx_status_t Unseal() final { // Simulate a transient error -- fail the first time we try to unseal the // volume, but succeed on a retry or any subsequent attempt. unseal_attempt_count++; if (unseal_attempt_count > 1) { return ZX_OK; } else { return ZX_ERR_ACCESS_DENIED; } } zx_status_t Format() final { // We expect this to never be called. formatted = true; return ZX_OK; } int unseal_attempt_count = 0; bool formatted = false; }; ZxcryptVolume volume; EXPECT_OK(volume.EnsureUnsealedAndFormatIfNeeded()); EXPECT_FALSE(volume.formatted); EXPECT_EQ(volume.unseal_attempt_count, 2); } TEST(AddDeviceTestCase, AddFailingZxcryptVolumeShouldNotFormat) { class ZxcryptVolume : public devmgr::EncryptedVolumeInterface { public: zx_status_t Unseal() final { // Errors that are not ZX_ERR_ACCESS_DENIED should not trigger // formatting. return ZX_ERR_INTERNAL; } zx_status_t Format() final { // Expect this to not be called. formatted = true; return ZX_OK; } bool formatted = false; }; ZxcryptVolume volume; EXPECT_EQ(ZX_ERR_INTERNAL, volume.EnsureUnsealedAndFormatIfNeeded()); EXPECT_FALSE(volume.formatted); } class BlockWatcherTest : public zxtest::Test { protected: BlockWatcherTest() { // Launch the isolated devmgr. IsolatedDevmgr::Args args; args.driver_search_paths.push_back("/boot/driver"); args.path_prefix = "/pkg/"; args.disable_block_watcher = false; ASSERT_OK(IsolatedDevmgr::Create(&args, &devmgr_)); fbl::unique_fd fd; ASSERT_OK(RecursiveWaitForFile(devmgr_.devfs_root(), "misc/ramctl", &fd)); zx::channel remote; ASSERT_OK(zx::channel::create(0, &watcher_chan_, &remote)); ASSERT_OK(fdio_service_connect_at(devmgr_.fshost_outgoing_dir().get(), "/svc/fuchsia.fshost.BlockWatcher", remote.release())); } void CreateGptRamdisk(ramdisk_client** client) { zx::vmo ramdisk_vmo; ASSERT_OK(zx::vmo::create(kTestDiskSectors * kBlockSize, 0, &ramdisk_vmo)); // Write the GPT into the VMO. ASSERT_OK(ramdisk_vmo.write(kTestGptProtectiveMbr, 0, sizeof(kTestGptProtectiveMbr))); ASSERT_OK(ramdisk_vmo.write(kTestGptBlock1, kBlockSize, sizeof(kTestGptBlock1))); ASSERT_OK(ramdisk_vmo.write(kTestGptBlock2, 2 * kBlockSize, sizeof(kTestGptBlock2))); ASSERT_OK( ramdisk_create_at_from_vmo(devmgr_.devfs_root().get(), ramdisk_vmo.release(), client)); } void PauseWatcher() { auto result = llcpp::fuchsia::fshost::BlockWatcher::Call::Pause(watcher_chan_.borrow()); ASSERT_OK(result.status()); ASSERT_OK(result->status); } void ResumeWatcher() { auto result = llcpp::fuchsia::fshost::BlockWatcher::Call::Resume(watcher_chan_.borrow()); ASSERT_OK(result.status()); ASSERT_OK(result->status); } void WaitForBlockDevice(int number) { auto path = fbl::StringPrintf("class/block/%03d", number); fbl::unique_fd fd; ASSERT_NO_FATAL_FAILURES(RecursiveWaitForFile(devmgr_.devfs_root(), path.data(), &fd)); } // Check that the number of block devices bound by the block watcher // matches what we expect. Can only be called while the block watcher is running. // // This works by adding a new block device with a valid GPT. // We then wait for that block device to appear at class/block/|next_device_number|. // The block watcher should then bind the GPT driver to that block device, causing // another entry in class/block to appear representing the only partition on the GPT. // // We make sure that this entry's toplogical path corresponds to it being the first partition // of the block device we added. void CheckEventsDropped(int* next_device_number, ramdisk_client** client) { ASSERT_NO_FATAL_FAILURES(CreateGptRamdisk(client)); // Wait for the basic block driver to be bound auto path = fbl::StringPrintf("class/block/%03d", *next_device_number); *next_device_number += 1; fbl::unique_fd fd; ASSERT_OK(RecursiveWaitForFile(devmgr_.devfs_root(), path.data(), &fd)); // And now, wait for the GPT driver to be bound, and the first // partition to appear. path = fbl::StringPrintf("class/block/%03d", *next_device_number); *next_device_number += 1; ASSERT_OK(RecursiveWaitForFile(devmgr_.devfs_root(), path.data(), &fd)); // Figure out the expected topological path of the last block device. std::string expected_path(ramdisk_get_path(*client)); expected_path = "/dev/" + expected_path + "/part-000/block"; zx_handle_t handle; ASSERT_OK(fdio_get_service_handle(fd.release(), &handle)); zx::channel channel(handle); // Get the actual topological path of the block device. auto result = llcpp::fuchsia::device::Controller::Call::GetTopologicalPath(channel.borrow()); ASSERT_OK(result.status()); ASSERT_FALSE(result->result.is_err()); auto actual_path = std::string(result->result.response().path.begin(), result->result.response().path.size()); // Make sure expected path matches the actual path. ASSERT_EQ(expected_path, actual_path); } IsolatedDevmgr devmgr_; zx::channel watcher_chan_; }; TEST_F(BlockWatcherTest, TestBlockWatcherDisable) { ASSERT_NO_FATAL_FAILURES(PauseWatcher()); int next_device_number = 0; // Add a block device. ramdisk_client* client; ASSERT_NO_FATAL_FAILURES(CreateGptRamdisk(&client)); ASSERT_NO_FATAL_FAILURES(WaitForBlockDevice(next_device_number)); next_device_number++; ASSERT_NO_FATAL_FAILURES(ResumeWatcher()); ramdisk_client* client2; ASSERT_NO_FATAL_FAILURES(CheckEventsDropped(&next_device_number, &client2)); ASSERT_OK(ramdisk_destroy(client)); ASSERT_OK(ramdisk_destroy(client2)); } TEST_F(BlockWatcherTest, TestBlockWatcherAdd) { int next_device_number = 0; // Add a block device. ramdisk_client* client; ASSERT_NO_FATAL_FAILURES(CreateGptRamdisk(&client)); ASSERT_NO_FATAL_FAILURES(WaitForBlockDevice(next_device_number)); next_device_number++; ASSERT_NO_FATAL_FAILURES(PauseWatcher()); fbl::unique_fd fd; // Look for the first partition of the device we just added. ASSERT_OK(RecursiveWaitForFile(devmgr_.devfs_root(), "class/block/001", &fd)); ASSERT_NO_FATAL_FAILURES(ResumeWatcher()); ASSERT_OK(ramdisk_destroy(client)); } TEST_F(BlockWatcherTest, TestBlockWatcherUnmatchedResume) { auto result = llcpp::fuchsia::fshost::BlockWatcher::Call::Resume(watcher_chan_.borrow()); ASSERT_OK(result.status()); ASSERT_STATUS(result->status, ZX_ERR_BAD_STATE); } TEST_F(BlockWatcherTest, TestMultiplePause) { ASSERT_NO_FATAL_FAILURES(PauseWatcher()); ASSERT_NO_FATAL_FAILURES(PauseWatcher()); int next_device_number = 0; // Add a block device. ramdisk_client* client; ASSERT_NO_FATAL_FAILURES(CreateGptRamdisk(&client)); ASSERT_NO_FATAL_FAILURES(WaitForBlockDevice(next_device_number)); next_device_number++; // Resume once. ASSERT_NO_FATAL_FAILURES(ResumeWatcher()); ramdisk_client* client2; ASSERT_NO_FATAL_FAILURES(CreateGptRamdisk(&client2)); ASSERT_NO_FATAL_FAILURES(WaitForBlockDevice(next_device_number)); next_device_number++; fbl::unique_fd fd; RecursiveWaitForFile(devmgr_.devfs_root(), ramdisk_get_path(client2), &fd); // Resume again. The block watcher should be running again. ASSERT_NO_FATAL_FAILURES(ResumeWatcher()); // Make sure neither device was seen by the watcher. ramdisk_client* client3; ASSERT_NO_FATAL_FAILURES(CheckEventsDropped(&next_device_number, &client3)); // Pause again. ASSERT_NO_FATAL_FAILURES(PauseWatcher()); ramdisk_client* client4; ASSERT_NO_FATAL_FAILURES(CreateGptRamdisk(&client4)); ASSERT_NO_FATAL_FAILURES(WaitForBlockDevice(next_device_number)); next_device_number++; // Resume again. ASSERT_NO_FATAL_FAILURES(ResumeWatcher()); // Make sure the last device wasn't added. ramdisk_client* client5; ASSERT_NO_FATAL_FAILURES(CheckEventsDropped(&next_device_number, &client5)); ASSERT_OK(ramdisk_destroy(client)); ASSERT_OK(ramdisk_destroy(client2)); ASSERT_OK(ramdisk_destroy(client3)); ASSERT_OK(ramdisk_destroy(client4)); ASSERT_OK(ramdisk_destroy(client5)); } } // namespace
33.928479
99
0.722126
oshunter
a974357023fc1fe8281e98082fb732e715eb2cab
700
cpp
C++
source/flow/audio-source-impl.cpp
Breush/lava
1b1b1f0785300b93b4a9f35fca4490502fea6552
[ "MIT" ]
15
2018-02-26T08:20:03.000Z
2022-03-06T03:25:46.000Z
source/flow/audio-source-impl.cpp
Breush/lava
1b1b1f0785300b93b4a9f35fca4490502fea6552
[ "MIT" ]
32
2018-02-26T08:26:38.000Z
2020-09-12T17:09:38.000Z
source/flow/audio-source-impl.cpp
Breush/lava
1b1b1f0785300b93b4a9f35fca4490502fea6552
[ "MIT" ]
null
null
null
#include "./audio-source-impl.hpp" #include "./audio-engine-impl.hpp" using namespace lava::flow; AudioSource::Impl::Impl(AudioEngine::Impl& engine) : m_engine(engine) { } void AudioSource::Impl::playing(bool playing) { m_playing = playing; playing ? restart() : finish(); } void AudioSource::Impl::looping(bool looping) { m_looping = looping; } void AudioSource::Impl::removeOnFinish(bool removeOnFinish) { m_removeOnFinish = removeOnFinish; } // ----- Sub-class API void AudioSource::Impl::finish() { m_playing = false; if (m_removeOnFinish) { m_engine.remove(*this); } else if (m_looping) { m_playing = true; restart(); } }
16.666667
59
0.648571
Breush
a97465d5dcfdac6d6d37e719b5a6e78052a39cd4
1,095
cpp
C++
src/caps/cap_osc_selection.cpp
stonewell/wxglterm
27480ed01e2832e98785b517ac17037a71cefe7c
[ "MIT" ]
12
2017-11-23T16:02:41.000Z
2019-12-29T08:36:36.000Z
src/caps/cap_osc_selection.cpp
stonewell/wxglterm
27480ed01e2832e98785b517ac17037a71cefe7c
[ "MIT" ]
9
2017-12-04T15:55:51.000Z
2019-11-01T13:08:21.000Z
src/caps/cap_osc_selection.cpp
stonewell/wxglterm
27480ed01e2832e98785b517ac17037a71cefe7c
[ "MIT" ]
5
2018-09-02T07:35:13.000Z
2019-12-29T08:36:37.000Z
#include "term_buffer.h" #include "term_window.h" #include "term_network.h" #include "cap_manager.h" #include "term_cell.h" #include "string_utils.h" #include <string.h> #include <iostream> #include <sstream> #include <iterator> DEFINE_CAP(osc_selection_request); void osc_selection_request(term_data_context_s & term_context, const term_data_param_list & params){ if (params[0] == 52) { std::string buffer_index = "0"; std::string ss_data; std::string v = params[1].str_value; auto pos = v.find(";"); if (pos != std::string::npos) { buffer_index = v.substr(0, pos); ss_data = v.substr(pos + 1); } if (ss_data == "?") { std::string sel_data = term_context.term_window->GetSelectionData(); std::stringstream ss; ss << "\033]52;" << buffer_index << ";" << sel_data << "\007"; send(term_context, ss.str().c_str()); } else{ term_context.term_window->SetSelectionData(ss_data); } } }
24.886364
80
0.569863
stonewell
a9747aa1bf77b04a7d6c15d9fb3132517e1e0429
3,699
cpp
C++
trunk/knewcode/kc_web_plugins/kc_web_page_data_expr/expr_item_if.cpp
zogyzen/knewcode
bd414a52330cde040ceaf91d1b380c402b2814b4
[ "Apache-2.0" ]
null
null
null
trunk/knewcode/kc_web_plugins/kc_web_page_data_expr/expr_item_if.cpp
zogyzen/knewcode
bd414a52330cde040ceaf91d1b380c402b2814b4
[ "Apache-2.0" ]
null
null
null
trunk/knewcode/kc_web_plugins/kc_web_page_data_expr/expr_item_if.cpp
zogyzen/knewcode
bd414a52330cde040ceaf91d1b380c402b2814b4
[ "Apache-2.0" ]
null
null
null
#include "std.h" #include "expr_item_if.h" //////////////////////////////////////////////////////////////////////////////// // TOperandNode类 KC::TOperandNode::TOperandNode(IExprTreeWork& wk, IWebPageData& pd, const TKcSynBaseClass& syn) : m_work(wk), m_pd(pd), m_pBeginPtr(syn.GetBeginPtr()), m_pEndPtr(syn.GetEndPtr()), m_LineID(pd.GetLineID(syn)) { } // 得到行号 int KC::TOperandNode::GetLineID(void) const { return m_LineID; } //////////////////////////////////////////////////////////////////////////////// // TUnaryNode类 KC::TUnaryNode::TUnaryNode(IExprTreeWork& wk, IWebPageData& pd, const TKcSynBaseClass& syn) : TOperandNode(wk, pd, syn) { } // 获取值 boost::any KC::TUnaryNode::GetValue(IKCActionData& act) { // 操作数 IOperandNode *pOperand = dynamic_cast<IOperandNode*>(OperandPtr.get()); if (nullptr == pOperand) throw TExprTreeWorkSrvException(this->GetLineID(), __FUNCTION__, (boost::format(m_work.getHint("Not_set_operand")) % this->GetSymbol() % this->GetLineID()).str(), m_work); // 获取操作数的值 boost::any val = pOperand->GetValue(act); // 返回计算结果 return this->Calculate(val); } //////////////////////////////////////////////////////////////////////////////// // TBinaryNode类 KC::TBinaryNode::TBinaryNode(IExprTreeWork& wk, IWebPageData& pd, const TKcSynBaseClass& syn) : TOperandNode(wk, pd, syn) { } // 获取值 boost::any KC::TBinaryNode::GetValue(IKCActionData& act) { // 左操作数 IOperandNode *pOperandL = dynamic_cast<IOperandNode*>(OperandPtrL.get()); if (nullptr == pOperandL) throw TExprTreeWorkSrvException(this->GetLineID(), __FUNCTION__, (boost::format(m_work.getHint("Not_set_left_operand")) % this->GetSymbol() % this->GetLineID()).str(), m_work); boost::any valL = pOperandL->GetValue(act); // 右操作数 IOperandNode *pOperandR = dynamic_cast<IOperandNode*>(OperandPtrR.get()); if (nullptr == pOperandR) throw TExprTreeWorkSrvException(this->GetLineID(), __FUNCTION__, (boost::format(m_work.getHint("Not_set_right_operand")) % this->GetSymbol() % this->GetLineID()).str(), m_work); boost::any valR = pOperandR->GetValue(act); // 返回计算结果 return this->Calculate(valL, valR); } // 得到自适应类型的左值 boost::any KC::TBinaryNode::GetLValueNewType(boost::any& lv, boost::any& rv) { if (lv.empty()) { if (rv.empty()) return string(""); else if (rv.type() == typeid(int)) return (int)0; else if (rv.type() == typeid(double)) return (double)0; else if (rv.type() == typeid(bool)) return false; else return string(""); } else if (rv.empty() || lv.type() == rv.type()) return lv; else if (lv.type() == typeid(bool)) { if (rv.type() == typeid(int)) return boost::any_cast<bool>(lv) ? (int)1 : (int)0; if (rv.type() == typeid(double)) return boost::any_cast<bool>(lv) ? (double)1 : (double)0; else return boost::any_cast<bool>(lv) ? string("true") : string("false"); } else if (lv.type() == typeid(int)) { if (rv.type() == typeid(bool)) return lv; else if (rv.type() == typeid(double)) return (double)boost::any_cast<int>(lv); else return lexical_cast<string>(boost::any_cast<int>(lv)); } else if (lv.type() == typeid(double)) { if (rv.type() == typeid(bool) || rv.type() == typeid(int)) return lv; else return lexical_cast<string>(boost::any_cast<double>(lv)); } else if (lv.type() == typeid(TKcWebInfVal)) return boost::any_cast<TKcWebInfVal>(lv).str(); else return lv; }
34.570093
185
0.575561
zogyzen
a975fe3f4c047f3bb873ee5edd28042c6395a2e2
1,826
cpp
C++
libHCore/src/common/time.cpp
adeliktas/Hayha3
a505b6e79e6cabd8ef8d899eeb9f7e39251b58b5
[ "MIT" ]
15
2021-11-22T07:31:22.000Z
2022-02-22T22:53:51.000Z
libHCore/src/common/time.cpp
adeliktas/Hayha3
a505b6e79e6cabd8ef8d899eeb9f7e39251b58b5
[ "MIT" ]
1
2021-11-26T19:27:40.000Z
2021-11-26T19:27:40.000Z
libHCore/src/common/time.cpp
adeliktas/Hayha3
a505b6e79e6cabd8ef8d899eeb9f7e39251b58b5
[ "MIT" ]
5
2021-11-20T18:21:24.000Z
2021-12-26T12:32:47.000Z
#include "time.hpp" timeStamp programStart; timeStamp getCurrentTimeMicro(){ return time_point_cast<microseconds>(steady_clock::now()); } timeStamp getTimeInFuture(uint64_t usec){ return time_point_cast<microseconds>(steady_clock::now()) + std::chrono::microseconds(usec); } int64_t getTimeDifference(timeStamp t0, timeStamp t1){ return duration_cast<microseconds>(t0 - t1).count(); } int64_t timeSince(timeStamp t0){ return duration_cast<microseconds>(getCurrentTimeMicro() - t0).count(); } int64_t timeTo(timeStamp t0){ return duration_cast<microseconds>(t0-getCurrentTimeMicro()).count(); } int64_t timeSinceStart(timeStamp t0){ return duration_cast<microseconds>(t0 - programStart).count(); } int64_t unixTime(timeStamp t0){ return duration_cast<seconds>(t0.time_since_epoch()).count(); } /* #include "time.hpp" timeStamp programStart; nanoseconds timespecToDuration(timespec ts){ auto duration = seconds{ts.tv_sec} + nanoseconds{ts.tv_nsec}; return duration_cast<nanoseconds>(duration); } time_point<system_clock, nanoseconds>timespecToTimePoint(timespec ts){ return time_point<system_clock, nanoseconds>{duration_cast<system_clock::duration>(timespecToDuration(ts))}; } timeStamp getCurrentTimeMicro(){ timeStamp ts; timespec_get(&ts.time, TIME_UTC); return ts; } timeStamp getTimeInFuture(uint64_t usec){ timeStamp ts = getCurrentTimeMicro(); return ts + usec; } int64_t timeSince(timeStamp t0){ timeStamp ts = getCurrentTimeMicro() - t0; int64_t since = ts.time.tv_sec * 1000000 + ts.time.tv_nsec / 1000; return since; } int64_t timeTo(timeStamp t0){ return t0.micros(); } int64_t getTimeDifference(timeStamp t0, timeStamp t1){ } int64_t timeSinceStart(timeStamp t0){ } int64_t unixTime(timeStamp t0); */
22
112
0.740416
adeliktas
a978d36d9b5f5f5b2846857d1af8b34f96e080a2
17,693
cpp
C++
core/SensorBase.cpp
STMicroelectronics/st-mems-android-linux-sensors-hal
a12f3d9806b8851d17c331bc07acafae9dcb2d3b
[ "Apache-2.0" ]
7
2021-10-29T20:29:48.000Z
2022-03-03T01:38:45.000Z
core/SensorBase.cpp
STMicroelectronics/st-mems-android-linux-sensors-hal
a12f3d9806b8851d17c331bc07acafae9dcb2d3b
[ "Apache-2.0" ]
null
null
null
core/SensorBase.cpp
STMicroelectronics/st-mems-android-linux-sensors-hal
a12f3d9806b8851d17c331bc07acafae9dcb2d3b
[ "Apache-2.0" ]
null
null
null
/* * Copyright (C) 2018 The Android Open Source Project * Copyright (C) 2015-2020 STMicroelectronics * * 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 <stdint.h> #include <fcntl.h> #include <assert.h> #include <string.h> #include <signal.h> #include <unistd.h> #include "SensorBase.h" namespace stm { namespace core { static IConsole &console { IConsole::getInstance() }; SensorBase::SensorBase(const char *name, int handle, const STMSensorType &type, int module) : sensor_t_data(type), threadsRunning(true), sensorsCallback(nullptr), moduleId(module) { int i, err, pipe_fd[2]; if (strlen(name) + 1 > SENSOR_BASE_ANDROID_NAME_MAX) { memcpy(android_name, name, SENSOR_BASE_ANDROID_NAME_MAX - 1); android_name[SENSOR_BASE_ANDROID_NAME_MAX - 1] = '\0'; } else { memcpy(android_name, name, strlen(name) + 1); } valid_class = true; memset(&push_data, 0, sizeof(dependencies_t)); memset(&dependencies, 0, sizeof(push_data_t)); //memset(&sensor_t_data, 0, sizeof(struct sensor_t)); // memset(&sensor_event, 0, sizeof(sensors_event_t)); memset(sensors_pollrates, 0, ST_HAL_IIO_MAX_DEVICES * sizeof(int64_t)); for (i = 0; i < ST_HAL_IIO_MAX_DEVICES; i++) { sensors_timeout[i] = INT64_MAX; } sensor_event.version = sizeof(sensors_event_t); sensor_event.sensor = handle; if (!type.isInternal()) { sensor_event.type = static_cast<SensorType>(type); } sensor_t_data.name = android_name; sensor_t_data.handle = handle; //sensor_t_data.type = type; sensor_t_data.vendor = "STMicroelectronics"; last_data_timestamp = 0; enabled_sensors_mask = 0; current_real_pollrate = 0; sample_in_processing_timestamp = 0; current_min_pollrate = 0; current_min_timeout = INT64_MAX; sensor_global_enable = 0; sensor_global_disable = 1; sensor_my_enable = 0; sensor_my_disable = 1; decimator = 1; samples_counter = 0; injection_mode = SENSOR_INJECTION_NONE; write_pipe_fd = -EINVAL; read_pipe_fd = -EINVAL; pthread_mutex_init(&enable_mutex, NULL); pthread_mutex_init(&sample_in_processing_mutex, NULL); err = pipe(pipe_fd); if (err < 0) { console.error(GetName() + std::string(": Failed to create pipe file.")); goto invalid_the_class; } fcntl(pipe_fd[0], F_SETFL, O_NONBLOCK); write_pipe_fd = pipe_fd[1]; read_pipe_fd = pipe_fd[0]; return; invalid_the_class: InvalidThisClass(); } SensorBase::~SensorBase() { threadsRunning = false; close(write_pipe_fd); close(read_pipe_fd); if (dataThread && dataThread->joinable()) dataThread->join(); if (eventsThread && eventsThread->joinable()) eventsThread->join(); } DependencyID SensorBase::GetDependencyIDFromHandle(int handle) { return handle_remapping_ID[handle]; } void SensorBase::SetDependencyIDOfHandle(int handle, DependencyID id) { handle_remapping_ID[handle] = id; } void SensorBase::InvalidThisClass() { valid_class = false; } bool SensorBase::IsValidClass() { return valid_class; } int SensorBase::GetHandle() { return sensor_t_data.handle; } STMSensorType SensorBase::GetType() { return sensor_t_data.type; } int SensorBase::GetMaxFifoLenght() { return sensor_t_data.fifoMaxEventCount; } int SensorBase::GetFdPipeToRead() { return read_pipe_fd; } void SensorBase::SetBitEnableMask(int handle) { enabled_sensors_mask |= (1ULL << handle); } void SensorBase::ResetBitEnableMask(int handle) { enabled_sensors_mask &= ~(1ULL << handle); } int SensorBase::AddNewPollrate(int64_t timestamp, int64_t pollrate) { return odr_stack.writeElement(timestamp, pollrate); } int SensorBase::CheckLatestNewPollrate(int64_t *timestamp, int64_t *pollrate) { *timestamp = odr_stack.readLastElement(pollrate); if (*timestamp < 0) { return -EINVAL; } return 0; } void SensorBase::DeleteLatestNewPollrate() { odr_stack.removeLastElement(); } bool SensorBase::ValidDataToPush(int64_t timestamp) { if (sensor_my_enable > sensor_my_disable) { if (timestamp > sensor_my_enable) { return true; } } else { if ((timestamp > sensor_my_enable) && (timestamp < sensor_my_disable)) { return true; } } return false; } bool SensorBase::GetDependencyMaxRange(STMSensorType type, float *maxRange) { bool found; unsigned int i; float maxRange_priv = 0; if (sensor_t_data.type == type) { *maxRange = sensor_t_data.maxRange; return true; } for (i = 0; i < dependencies.num; i++) { found = dependencies.sb[i]->GetDependencyMaxRange(type, &maxRange_priv); if (found) { *maxRange = maxRange_priv; return true; } } return false; } char* SensorBase::GetName() { return (char *)sensor_t_data.name; } selftest_status SensorBase::ExecuteSelfTest() { return NOT_AVAILABLE; } int SensorBase::Enable(int handle, bool enable, bool lock_en_mutex) { int err = 0; unsigned int i = 0; if (lock_en_mutex) { pthread_mutex_lock(&enable_mutex); } if ((handle == sensor_t_data.handle) && (enable == GetStatusOfHandle(handle))) { goto enable_unlock_mutex; } if ((enable && !GetStatus(false)) || (!enable && !GetStatusExcludeHandle(handle))) { if (enable) { SetBitEnableMask(handle); flush_stack.resetBuffer(); lastDecimatedPollrate = 0; } else { err = SetDelay(handle, 0, INT64_MAX, false); if (err < 0) { goto enable_unlock_mutex; } ResetBitEnableMask(handle); } for (i = 0; i < dependencies.num; i++) { err = dependencies.sb[i]->Enable(sensor_t_data.handle, enable, true); if (err < 0) { goto restore_enable_dependencies; } } if (enable) { console.debug(GetName() + std::string(": power-on")); } else { console.debug(GetName() + std::string(": power-off")); } } else { if (enable) { SetBitEnableMask(handle); } else { err = SetDelay(handle, 0, INT64_MAX, false); if (err < 0) { goto enable_unlock_mutex; } ResetBitEnableMask(handle); } } if (lock_en_mutex) { pthread_mutex_unlock(&enable_mutex); } return 0; restore_enable_dependencies: while (i > 0) { i--; dependencies.sb[i]->Enable(sensor_t_data.handle, !enable, true); } if (enable) { ResetBitEnableMask(handle); } else { SetBitEnableMask(handle); } enable_unlock_mutex: if (lock_en_mutex) { pthread_mutex_unlock(&enable_mutex); } return err; } bool SensorBase::GetStatusExcludeHandle(int handle) { return (enabled_sensors_mask & ~(1ULL << handle)) > 0 ? true : false; } bool SensorBase::GetStatusOfHandle(int handle) { return (enabled_sensors_mask & (1ULL << handle)) > 0 ? true : false; } bool SensorBase::GetStatusOfHandle(int handle, bool lock_en_mutex) { bool status; if (lock_en_mutex) { pthread_mutex_lock(&enable_mutex); } status = (enabled_sensors_mask & (1ULL << handle)) > 0 ? true : false; if (lock_en_mutex) { pthread_mutex_unlock(&enable_mutex); } return status; } bool SensorBase::GetStatus(bool lock_en_mutex) { bool status; if (lock_en_mutex) { pthread_mutex_lock(&enable_mutex); } status = enabled_sensors_mask > 0 ? true : false; if (lock_en_mutex) { pthread_mutex_unlock(&enable_mutex); } return status; } int SensorBase::SetDelay(int handle, int64_t period_ns, int64_t timeout, bool lock_en_mutex) { int err, i; int64_t restore_min_timeout, restore_min_period_ms; if ((timeout > 0) && (timeout < INT64_MAX) && (sensor_t_data.fifoMaxEventCount == 0)) { return -EINVAL; } if (lock_en_mutex) { pthread_mutex_lock(&enable_mutex); } restore_min_timeout = sensors_timeout[handle]; restore_min_period_ms = sensors_pollrates[handle]; sensors_pollrates[handle] = period_ns; sensors_timeout[handle] = timeout; for (i = 0; i < (int)dependencies.num; i++) { err = dependencies.sb[i]->SetDelay(sensor_t_data.handle, GetMinPeriod(false), GetMinTimeout(false), true); if (err < 0) { goto restore_delay_dependencies; } } if (lock_en_mutex) { pthread_mutex_unlock(&enable_mutex); } return 0; restore_delay_dependencies: sensors_pollrates[handle] = restore_min_period_ms; sensors_timeout[handle] = restore_min_timeout; for (i--; i >= 0; i--) { dependencies.sb[i]->SetDelay(sensor_t_data.handle, GetMinPeriod(false), GetMinTimeout(false), true); } if (lock_en_mutex) { pthread_mutex_unlock(&enable_mutex); } return err; } const std::vector<STMSensorType>& SensorBase::GetDepenciesTypeList(void) const { return dependencies_type_list; } int SensorBase::AllocateBufferForDependencyData(DependencyID id, unsigned int max_fifo_len) { circular_buffer_data[id] = new CircularBuffer(max_fifo_len < 2 ? 10 : 10 * max_fifo_len); if (!circular_buffer_data[id]) { console.error(GetName() + std::string(": Failed to allocate circular buffer data.")); return -ENOMEM; } return 0; } void SensorBase::DeAllocateBufferForDependencyData(DependencyID id) { delete circular_buffer_data[id]; } int SensorBase::AddSensorToDataPush(SensorBase *t) { if (push_data.num >= SENSOR_DEPENDENCY_ID_MAX) { console.error(android_name + std::string(": Failed to add dependency data, too many sensors to push data.")); return -ENOMEM; } push_data.sb[push_data.num] = t; push_data.num++; return 0; } void SensorBase::RemoveSensorToDataPush(SensorBase *t) { unsigned int i; for (i = 0; i < push_data.num; i++) { if (t == push_data.sb[i]) { break; } } if (i == push_data.num) { return; } for (; i < push_data.num - 1; i++) { push_data.sb[i] = push_data.sb[i + 1]; } push_data.num--; } int SensorBase::AddSensorDependency(SensorBase *p) { int err; unsigned int dependency_id; if (dependencies.num >= SENSOR_DEPENDENCY_ID_MAX) { console.error(android_name + std::string(": Failed to add dependency, too many dependencies.")); return -ENOMEM; } dependency_id = dependencies.num; SetDependencyIDOfHandle(p->GetHandle(), (DependencyID)dependency_id); err = p->AddSensorToDataPush(this); if (err < 0) { return err; } struct sensor_t dependecy_data = p->GetSensor_tData(); sensor_t_data.power += dependecy_data.power; dependencies.sb[dependency_id] = p; dependencies.num++; return dependency_id; } void SensorBase::RemoveSensorDependency(SensorBase *p) { unsigned int i; for (i = 0; i < dependencies.num; i++) { if (p == dependencies.sb[i]) { break; } } if (i == dependencies.num) { return; } p->RemoveSensorToDataPush(this); for (; i < dependencies.num - 1; i++) { dependencies.sb[i] = dependencies.sb[i + 1]; } dependencies.num--; } int SensorBase::startThreads(void) { if (hasDataChannels()) { dataThread = std::make_unique<std::thread>(ThreadDataWork, this, std::ref(threadsRunning)); } if (hasEventChannels()) { eventsThread = std::make_unique<std::thread>(ThreadEventsWork, this, std::ref(threadsRunning)); } return 0; } void SensorBase::stopThreads(void) { } struct sensor_t SensorBase::GetSensor_tData(void) { struct sensor_t data(sensor_t_data); return data; } void SensorBase::WriteOdrChangeEventToPipe(int64_t timestamp, int64_t pollrate) { sensors_event_t odr_change_event_data; odr_change_event_data.sensor = sensor_t_data.handle; odr_change_event_data.timestamp = timestamp; odr_change_event_data.type = SensorType::ODR_SWITCH_INFO; odr_change_event_data.data.dataLen = 1; odr_change_event_data.data.data2[0] = pollrate; auto err = write(write_pipe_fd, &odr_change_event_data, sizeof(sensors_event_t)); if (err <= 0) { console.error(android_name + std::string(": Failed to write odr change event data to pipe.")); } } void SensorBase::WriteFlushEventToPipe() { int err; sensors_event_t flush_event_data; // memset(&flush_event_data, 0, sizeof(sensors_event_t)); flush_event_data.sensor = sensor_t_data.handle; flush_event_data.timestamp = 0; // flush_event_data.data_new[0] = // flush_event_data.meta_data.sensor = sensor_t_data.handle; //flush_event_data.meta_data.what = META_DATA_FLUSH_COMPLETE; flush_event_data.type = SensorType::META_DATA; //flush_event_data.version = META_DATA_VERSION; console.debug(GetName() + std::string(": write flush event to pipe")); err = write(write_pipe_fd, &flush_event_data, sizeof(sensors_event_t)); if (err <= 0) { console.error(android_name + std::string(": Failed to write flush event data to pipe.")); } } void SensorBase::WriteDataToPipe(int64_t __attribute__((unused))hw_pollrate) { int err; if (ValidDataToPush(sensor_event.timestamp)) { if (sensor_event.timestamp > last_data_timestamp) { err = write(write_pipe_fd, &sensor_event, sizeof(sensors_event_t)); if (err <= 0) { console.error(android_name + std::string(": Failed to write sensor data to pipe.")); return; } last_data_timestamp = sensor_event.timestamp; } } } void SensorBase::ProcessData(SensorBaseData *data) { unsigned int i; for (int i = 0; i < data->flushEventsNum; ++i) { if (data->flushEventHandles[i] == sensor_t_data.handle) { WriteFlushEventToPipe(); } } for (i = 0; i < push_data.num; i++) { push_data.sb[i]->ReceiveDataFromDependency(sensor_t_data.handle, data); } } void SensorBase::ReceiveDataFromDependency(int handle, SensorBaseData *data) { bool fill_buffer = false; if (sensor_global_enable > sensor_global_disable) { if (data->timestamp > sensor_global_enable) { fill_buffer = true; } } else { if ((data->timestamp > sensor_global_enable) && (data->timestamp < sensor_global_disable)) { fill_buffer = true; } } if (fill_buffer) { circular_buffer_data[GetDependencyIDFromHandle(handle)]->writeElement(data); } } int SensorBase::GetLatestValidDataFromDependency(int dependency_id, SensorBaseData *data, int64_t timesync) { return circular_buffer_data[dependency_id]->readSyncElement(data, timesync); } int64_t SensorBase::GetMinTimeout(bool lock_en_mutex) { int i; int64_t min = INT64_MAX; if (lock_en_mutex) { pthread_mutex_lock(&enable_mutex); } for (i = 0; i < ST_HAL_IIO_MAX_DEVICES; i++) { if ((sensors_timeout[i] < min) && (sensors_timeout[i] < INT64_MAX)) { min = sensors_timeout[i]; } } if (lock_en_mutex) { pthread_mutex_unlock(&enable_mutex); } return min; } int64_t SensorBase::GetMinPeriod(bool lock_en_mutex) { int i; int64_t min = INT64_MAX; if (lock_en_mutex) { pthread_mutex_lock(&enable_mutex); } for (i = 0; i < ST_HAL_IIO_MAX_DEVICES; i++) { if ((sensors_pollrates[i] < min) && (sensors_pollrates[i] > 0)) { min = sensors_pollrates[i]; } } if (lock_en_mutex) { pthread_mutex_unlock(&enable_mutex); } return min == INT64_MAX ? 0 : min; } void *SensorBase::ThreadDataWork(void *context, std::atomic<bool>& threadsRunning) { SensorBase *mypointer = (SensorBase *)context; mypointer->ThreadDataTask(threadsRunning); return mypointer; } void SensorBase::ThreadDataTask(std::atomic<bool>& threadsRunning) { (void)threadsRunning; } void *SensorBase::ThreadEventsWork(void *context, std::atomic<bool>& threadsRunning) { SensorBase *mypointer = (SensorBase *)context; mypointer->ThreadEventsTask(threadsRunning); return mypointer; } void SensorBase::ThreadEventsTask(std::atomic<bool>& threadsRunning) { (void)threadsRunning; } int SensorBase::InjectionMode(bool __attribute__((unused))enable) { return 0; } int SensorBase::InjectSensorData(const sensors_event_t __attribute__((unused))*data) { return -EINVAL; } bool SensorBase::hasEventChannels() { return false; } bool SensorBase::hasDataChannels() { return false; } void SensorBase::setCallbacks(const ISTMSensorsCallback &sensorsCallback) { this->sensorsCallback = (ISTMSensorsCallback *)&sensorsCallback; } int SensorBase::getHandleOfMyTrigger(void) const { return -1; } } // namespace core } // namespace stm
24.104905
117
0.653874
STMicroelectronics
a97a4df558a7983d46402fb822cb5faa478a7935
4,259
cc
C++
src/ui/gl/gl_implementation.cc
jxjnjjn/chromium
435c1d02fd1b99001dc9e1e831632c894523580d
[ "Apache-2.0" ]
9
2018-09-21T05:36:12.000Z
2021-11-15T15:14:36.000Z
ui/gl/gl_implementation.cc
devasia1000/chromium
919a8a666862fb866a6bb7aa7f3ae8c0442b4828
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
1
2015-07-21T08:02:01.000Z
2015-07-21T08:02:01.000Z
ui/gl/gl_implementation.cc
devasia1000/chromium
919a8a666862fb866a6bb7aa7f3ae8c0442b4828
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
6
2016-11-14T10:13:35.000Z
2021-01-23T15:29:53.000Z
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/gl/gl_implementation.h" #include <algorithm> #include <string> #include "base/at_exit.h" #include "base/command_line.h" #include "base/logging.h" #include "ui/gl/gl_bindings.h" namespace gfx { namespace { const struct { const char* name; GLImplementation implementation; } kGLImplementationNamePairs[] = { { kGLImplementationDesktopName, kGLImplementationDesktopGL }, { kGLImplementationOSMesaName, kGLImplementationOSMesaGL }, #if defined(OS_MACOSX) { kGLImplementationAppleName, kGLImplementationAppleGL }, #endif { kGLImplementationEGLName, kGLImplementationEGLGLES2 }, { kGLImplementationMockName, kGLImplementationMockGL } }; typedef std::vector<base::NativeLibrary> LibraryArray; GLImplementation g_gl_implementation = kGLImplementationNone; LibraryArray* g_libraries; GLGetProcAddressProc g_get_proc_address; void CleanupNativeLibraries(void* unused) { if (g_libraries) { for (LibraryArray::iterator it = g_libraries->begin(); it != g_libraries->end(); ++it) { base::UnloadNativeLibrary(*it); } delete g_libraries; g_libraries = NULL; } } bool ExportsCoreFunctionsFromGetProcAddress(GLImplementation implementation) { switch (GetGLImplementation()) { case kGLImplementationDesktopGL: case kGLImplementationOSMesaGL: case kGLImplementationAppleGL: case kGLImplementationMockGL: return true; case kGLImplementationEGLGLES2: return false; default: NOTREACHED(); return true; } } } GLApi* g_current_gl_context; OSMESAApi* g_current_osmesa_context; #if defined(OS_WIN) EGLApi* g_current_egl_context; WGLApi* g_current_wgl_context; #elif defined(USE_X11) EGLApi* g_current_egl_context; GLXApi* g_current_glx_context; #elif defined(OS_ANDROID) EGLApi* g_current_egl_context; #endif GLImplementation GetNamedGLImplementation(const std::string& name) { for (size_t i = 0; i < ARRAYSIZE_UNSAFE(kGLImplementationNamePairs); ++i) { if (name == kGLImplementationNamePairs[i].name) return kGLImplementationNamePairs[i].implementation; } return kGLImplementationNone; } const char* GetGLImplementationName(GLImplementation implementation) { for (size_t i = 0; i < ARRAYSIZE_UNSAFE(kGLImplementationNamePairs); ++i) { if (implementation == kGLImplementationNamePairs[i].implementation) return kGLImplementationNamePairs[i].name; } return "unknown"; } void SetGLImplementation(GLImplementation implementation) { g_gl_implementation = implementation; } GLImplementation GetGLImplementation() { return g_gl_implementation; } bool HasDesktopGLFeatures() { return kGLImplementationDesktopGL == g_gl_implementation || kGLImplementationOSMesaGL == g_gl_implementation || kGLImplementationAppleGL == g_gl_implementation; } void AddGLNativeLibrary(base::NativeLibrary library) { DCHECK(library); if (!g_libraries) { g_libraries = new LibraryArray; base::AtExitManager::RegisterCallback(CleanupNativeLibraries, NULL); } g_libraries->push_back(library); } void UnloadGLNativeLibraries() { CleanupNativeLibraries(NULL); } void SetGLGetProcAddressProc(GLGetProcAddressProc proc) { DCHECK(proc); g_get_proc_address = proc; } void* GetGLCoreProcAddress(const char* name) { DCHECK(g_gl_implementation != kGLImplementationNone); if (g_libraries) { for (size_t i = 0; i < g_libraries->size(); ++i) { void* proc = base::GetFunctionPointerFromNativeLibrary((*g_libraries)[i], name); if (proc) return proc; } } if (ExportsCoreFunctionsFromGetProcAddress(g_gl_implementation) && g_get_proc_address) { void* proc = g_get_proc_address(name); if (proc) return proc; } return NULL; } void* GetGLProcAddress(const char* name) { DCHECK(g_gl_implementation != kGLImplementationNone); void* proc = GetGLCoreProcAddress(name); if (!proc && g_get_proc_address) { proc = g_get_proc_address(name); if (proc) return proc; } return proc; } } // namespace gfx
24.761628
79
0.733506
jxjnjjn
a97e374f74ef7289099d71ff6aceb3ef4c82308f
17,048
cpp
C++
src/intel/compiler/test_fs_cmod_propagation.cpp
antmicro/kvm-aosp-external-mesa3d
9a3a0c1e30421cd1d66b138ef6a3269ceb6de39f
[ "MIT" ]
1
2022-03-26T08:39:34.000Z
2022-03-26T08:39:34.000Z
src/intel/compiler/test_fs_cmod_propagation.cpp
antmicro/kvm-aosp-external-mesa3d
9a3a0c1e30421cd1d66b138ef6a3269ceb6de39f
[ "MIT" ]
null
null
null
src/intel/compiler/test_fs_cmod_propagation.cpp
antmicro/kvm-aosp-external-mesa3d
9a3a0c1e30421cd1d66b138ef6a3269ceb6de39f
[ "MIT" ]
2
2018-09-19T09:53:12.000Z
2022-01-27T09:25:20.000Z
/* * Copyright © 2015 Intel Corporation * * 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 (including the next * paragraph) shall be included in all copies or substantial portions of the * Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS * IN THE SOFTWARE. */ #include <gtest/gtest.h> #include "brw_fs.h" #include "brw_cfg.h" #include "program/program.h" using namespace brw; class cmod_propagation_test : public ::testing::Test { virtual void SetUp(); public: struct brw_compiler *compiler; struct gen_device_info *devinfo; struct gl_context *ctx; struct brw_wm_prog_data *prog_data; struct gl_shader_program *shader_prog; fs_visitor *v; }; class cmod_propagation_fs_visitor : public fs_visitor { public: cmod_propagation_fs_visitor(struct brw_compiler *compiler, struct brw_wm_prog_data *prog_data, nir_shader *shader) : fs_visitor(compiler, NULL, NULL, NULL, &prog_data->base, (struct gl_program *) NULL, shader, 8, -1) {} }; void cmod_propagation_test::SetUp() { ctx = (struct gl_context *)calloc(1, sizeof(*ctx)); compiler = (struct brw_compiler *)calloc(1, sizeof(*compiler)); devinfo = (struct gen_device_info *)calloc(1, sizeof(*devinfo)); compiler->devinfo = devinfo; prog_data = ralloc(NULL, struct brw_wm_prog_data); nir_shader *shader = nir_shader_create(NULL, MESA_SHADER_FRAGMENT, NULL, NULL); v = new cmod_propagation_fs_visitor(compiler, prog_data, shader); devinfo->gen = 4; } static fs_inst * instruction(bblock_t *block, int num) { fs_inst *inst = (fs_inst *)block->start(); for (int i = 0; i < num; i++) { inst = (fs_inst *)inst->next; } return inst; } static bool cmod_propagation(fs_visitor *v) { const bool print = getenv("TEST_DEBUG"); if (print) { fprintf(stderr, "= Before =\n"); v->cfg->dump(v); } bool ret = v->opt_cmod_propagation(); if (print) { fprintf(stderr, "\n= After =\n"); v->cfg->dump(v); } return ret; } TEST_F(cmod_propagation_test, basic) { const fs_builder &bld = v->bld; fs_reg dest = v->vgrf(glsl_type::float_type); fs_reg src0 = v->vgrf(glsl_type::float_type); fs_reg src1 = v->vgrf(glsl_type::float_type); fs_reg zero(brw_imm_f(0.0f)); bld.ADD(dest, src0, src1); bld.CMP(bld.null_reg_f(), dest, zero, BRW_CONDITIONAL_GE); /* = Before = * * 0: add(8) dest src0 src1 * 1: cmp.ge.f0(8) null dest 0.0f * * = After = * 0: add.ge.f0(8) dest src0 src1 */ v->calculate_cfg(); bblock_t *block0 = v->cfg->blocks[0]; EXPECT_EQ(0, block0->start_ip); EXPECT_EQ(1, block0->end_ip); EXPECT_TRUE(cmod_propagation(v)); EXPECT_EQ(0, block0->start_ip); EXPECT_EQ(0, block0->end_ip); EXPECT_EQ(BRW_OPCODE_ADD, instruction(block0, 0)->opcode); EXPECT_EQ(BRW_CONDITIONAL_GE, instruction(block0, 0)->conditional_mod); } TEST_F(cmod_propagation_test, cmp_nonzero) { const fs_builder &bld = v->bld; fs_reg dest = v->vgrf(glsl_type::float_type); fs_reg src0 = v->vgrf(glsl_type::float_type); fs_reg src1 = v->vgrf(glsl_type::float_type); fs_reg nonzero(brw_imm_f(1.0f)); bld.ADD(dest, src0, src1); bld.CMP(bld.null_reg_f(), dest, nonzero, BRW_CONDITIONAL_GE); /* = Before = * * 0: add(8) dest src0 src1 * 1: cmp.ge.f0(8) null dest 1.0f * * = After = * (no changes) */ v->calculate_cfg(); bblock_t *block0 = v->cfg->blocks[0]; EXPECT_EQ(0, block0->start_ip); EXPECT_EQ(1, block0->end_ip); EXPECT_FALSE(cmod_propagation(v)); EXPECT_EQ(0, block0->start_ip); EXPECT_EQ(1, block0->end_ip); EXPECT_EQ(BRW_OPCODE_ADD, instruction(block0, 0)->opcode); EXPECT_EQ(BRW_OPCODE_CMP, instruction(block0, 1)->opcode); EXPECT_EQ(BRW_CONDITIONAL_GE, instruction(block0, 1)->conditional_mod); } TEST_F(cmod_propagation_test, non_cmod_instruction) { const fs_builder &bld = v->bld; fs_reg dest = v->vgrf(glsl_type::uint_type); fs_reg src0 = v->vgrf(glsl_type::uint_type); fs_reg zero(brw_imm_ud(0u)); bld.FBL(dest, src0); bld.CMP(bld.null_reg_ud(), dest, zero, BRW_CONDITIONAL_GE); /* = Before = * * 0: fbl(8) dest src0 * 1: cmp.ge.f0(8) null dest 0u * * = After = * (no changes) */ v->calculate_cfg(); bblock_t *block0 = v->cfg->blocks[0]; EXPECT_EQ(0, block0->start_ip); EXPECT_EQ(1, block0->end_ip); EXPECT_FALSE(cmod_propagation(v)); EXPECT_EQ(0, block0->start_ip); EXPECT_EQ(1, block0->end_ip); EXPECT_EQ(BRW_OPCODE_FBL, instruction(block0, 0)->opcode); EXPECT_EQ(BRW_OPCODE_CMP, instruction(block0, 1)->opcode); EXPECT_EQ(BRW_CONDITIONAL_GE, instruction(block0, 1)->conditional_mod); } TEST_F(cmod_propagation_test, intervening_flag_write) { const fs_builder &bld = v->bld; fs_reg dest = v->vgrf(glsl_type::float_type); fs_reg src0 = v->vgrf(glsl_type::float_type); fs_reg src1 = v->vgrf(glsl_type::float_type); fs_reg src2 = v->vgrf(glsl_type::float_type); fs_reg zero(brw_imm_f(0.0f)); bld.ADD(dest, src0, src1); bld.CMP(bld.null_reg_f(), src2, zero, BRW_CONDITIONAL_GE); bld.CMP(bld.null_reg_f(), dest, zero, BRW_CONDITIONAL_GE); /* = Before = * * 0: add(8) dest src0 src1 * 1: cmp.ge.f0(8) null src2 0.0f * 2: cmp.ge.f0(8) null dest 0.0f * * = After = * (no changes) */ v->calculate_cfg(); bblock_t *block0 = v->cfg->blocks[0]; EXPECT_EQ(0, block0->start_ip); EXPECT_EQ(2, block0->end_ip); EXPECT_FALSE(cmod_propagation(v)); EXPECT_EQ(0, block0->start_ip); EXPECT_EQ(2, block0->end_ip); EXPECT_EQ(BRW_OPCODE_ADD, instruction(block0, 0)->opcode); EXPECT_EQ(BRW_OPCODE_CMP, instruction(block0, 1)->opcode); EXPECT_EQ(BRW_CONDITIONAL_GE, instruction(block0, 1)->conditional_mod); EXPECT_EQ(BRW_OPCODE_CMP, instruction(block0, 2)->opcode); EXPECT_EQ(BRW_CONDITIONAL_GE, instruction(block0, 2)->conditional_mod); } TEST_F(cmod_propagation_test, intervening_flag_read) { const fs_builder &bld = v->bld; fs_reg dest0 = v->vgrf(glsl_type::float_type); fs_reg dest1 = v->vgrf(glsl_type::float_type); fs_reg src0 = v->vgrf(glsl_type::float_type); fs_reg src1 = v->vgrf(glsl_type::float_type); fs_reg src2 = v->vgrf(glsl_type::float_type); fs_reg zero(brw_imm_f(0.0f)); bld.ADD(dest0, src0, src1); set_predicate(BRW_PREDICATE_NORMAL, bld.SEL(dest1, src2, zero)); bld.CMP(bld.null_reg_f(), dest0, zero, BRW_CONDITIONAL_GE); /* = Before = * * 0: add(8) dest0 src0 src1 * 1: (+f0) sel(8) dest1 src2 0.0f * 2: cmp.ge.f0(8) null dest0 0.0f * * = After = * (no changes) */ v->calculate_cfg(); bblock_t *block0 = v->cfg->blocks[0]; EXPECT_EQ(0, block0->start_ip); EXPECT_EQ(2, block0->end_ip); EXPECT_FALSE(cmod_propagation(v)); EXPECT_EQ(0, block0->start_ip); EXPECT_EQ(2, block0->end_ip); EXPECT_EQ(BRW_OPCODE_ADD, instruction(block0, 0)->opcode); EXPECT_EQ(BRW_OPCODE_SEL, instruction(block0, 1)->opcode); EXPECT_EQ(BRW_PREDICATE_NORMAL, instruction(block0, 1)->predicate); EXPECT_EQ(BRW_OPCODE_CMP, instruction(block0, 2)->opcode); EXPECT_EQ(BRW_CONDITIONAL_GE, instruction(block0, 2)->conditional_mod); } TEST_F(cmod_propagation_test, intervening_dest_write) { const fs_builder &bld = v->bld; fs_reg dest = v->vgrf(glsl_type::vec4_type); fs_reg src0 = v->vgrf(glsl_type::float_type); fs_reg src1 = v->vgrf(glsl_type::float_type); fs_reg src2 = v->vgrf(glsl_type::vec2_type); fs_reg zero(brw_imm_f(0.0f)); bld.ADD(offset(dest, bld, 2), src0, src1); bld.emit(SHADER_OPCODE_TEX, dest, src2) ->size_written = 4 * REG_SIZE; bld.CMP(bld.null_reg_f(), offset(dest, bld, 2), zero, BRW_CONDITIONAL_GE); /* = Before = * * 0: add(8) dest+2 src0 src1 * 1: tex(8) rlen 4 dest+0 src2 * 2: cmp.ge.f0(8) null dest+2 0.0f * * = After = * (no changes) */ v->calculate_cfg(); bblock_t *block0 = v->cfg->blocks[0]; EXPECT_EQ(0, block0->start_ip); EXPECT_EQ(2, block0->end_ip); EXPECT_FALSE(cmod_propagation(v)); EXPECT_EQ(0, block0->start_ip); EXPECT_EQ(2, block0->end_ip); EXPECT_EQ(BRW_OPCODE_ADD, instruction(block0, 0)->opcode); EXPECT_EQ(BRW_CONDITIONAL_NONE, instruction(block0, 0)->conditional_mod); EXPECT_EQ(SHADER_OPCODE_TEX, instruction(block0, 1)->opcode); EXPECT_EQ(BRW_CONDITIONAL_NONE, instruction(block0, 0)->conditional_mod); EXPECT_EQ(BRW_OPCODE_CMP, instruction(block0, 2)->opcode); EXPECT_EQ(BRW_CONDITIONAL_GE, instruction(block0, 2)->conditional_mod); } TEST_F(cmod_propagation_test, intervening_flag_read_same_value) { const fs_builder &bld = v->bld; fs_reg dest0 = v->vgrf(glsl_type::float_type); fs_reg dest1 = v->vgrf(glsl_type::float_type); fs_reg src0 = v->vgrf(glsl_type::float_type); fs_reg src1 = v->vgrf(glsl_type::float_type); fs_reg src2 = v->vgrf(glsl_type::float_type); fs_reg zero(brw_imm_f(0.0f)); set_condmod(BRW_CONDITIONAL_GE, bld.ADD(dest0, src0, src1)); set_predicate(BRW_PREDICATE_NORMAL, bld.SEL(dest1, src2, zero)); bld.CMP(bld.null_reg_f(), dest0, zero, BRW_CONDITIONAL_GE); /* = Before = * * 0: add.ge.f0(8) dest0 src0 src1 * 1: (+f0) sel(8) dest1 src2 0.0f * 2: cmp.ge.f0(8) null dest0 0.0f * * = After = * 0: add.ge.f0(8) dest0 src0 src1 * 1: (+f0) sel(8) dest1 src2 0.0f */ v->calculate_cfg(); bblock_t *block0 = v->cfg->blocks[0]; EXPECT_EQ(0, block0->start_ip); EXPECT_EQ(2, block0->end_ip); EXPECT_TRUE(cmod_propagation(v)); EXPECT_EQ(0, block0->start_ip); EXPECT_EQ(1, block0->end_ip); EXPECT_EQ(BRW_OPCODE_ADD, instruction(block0, 0)->opcode); EXPECT_EQ(BRW_CONDITIONAL_GE, instruction(block0, 0)->conditional_mod); EXPECT_EQ(BRW_OPCODE_SEL, instruction(block0, 1)->opcode); EXPECT_EQ(BRW_PREDICATE_NORMAL, instruction(block0, 1)->predicate); } TEST_F(cmod_propagation_test, negate) { const fs_builder &bld = v->bld; fs_reg dest = v->vgrf(glsl_type::float_type); fs_reg src0 = v->vgrf(glsl_type::float_type); fs_reg src1 = v->vgrf(glsl_type::float_type); fs_reg zero(brw_imm_f(0.0f)); bld.ADD(dest, src0, src1); dest.negate = true; bld.CMP(bld.null_reg_f(), dest, zero, BRW_CONDITIONAL_GE); /* = Before = * * 0: add(8) dest src0 src1 * 1: cmp.ge.f0(8) null -dest 0.0f * * = After = * 0: add.le.f0(8) dest src0 src1 */ v->calculate_cfg(); bblock_t *block0 = v->cfg->blocks[0]; EXPECT_EQ(0, block0->start_ip); EXPECT_EQ(1, block0->end_ip); EXPECT_TRUE(cmod_propagation(v)); EXPECT_EQ(0, block0->start_ip); EXPECT_EQ(0, block0->end_ip); EXPECT_EQ(BRW_OPCODE_ADD, instruction(block0, 0)->opcode); EXPECT_EQ(BRW_CONDITIONAL_LE, instruction(block0, 0)->conditional_mod); } TEST_F(cmod_propagation_test, movnz) { const fs_builder &bld = v->bld; fs_reg dest = v->vgrf(glsl_type::float_type); fs_reg src0 = v->vgrf(glsl_type::float_type); fs_reg src1 = v->vgrf(glsl_type::float_type); bld.CMP(dest, src0, src1, BRW_CONDITIONAL_GE); set_condmod(BRW_CONDITIONAL_NZ, bld.MOV(bld.null_reg_f(), dest)); /* = Before = * * 0: cmp.ge.f0(8) dest src0 src1 * 1: mov.nz.f0(8) null dest * * = After = * 0: cmp.ge.f0(8) dest src0 src1 */ v->calculate_cfg(); bblock_t *block0 = v->cfg->blocks[0]; EXPECT_EQ(0, block0->start_ip); EXPECT_EQ(1, block0->end_ip); EXPECT_TRUE(cmod_propagation(v)); EXPECT_EQ(0, block0->start_ip); EXPECT_EQ(0, block0->end_ip); EXPECT_EQ(BRW_OPCODE_CMP, instruction(block0, 0)->opcode); EXPECT_EQ(BRW_CONDITIONAL_GE, instruction(block0, 0)->conditional_mod); } TEST_F(cmod_propagation_test, different_types_cmod_with_zero) { const fs_builder &bld = v->bld; fs_reg dest = v->vgrf(glsl_type::int_type); fs_reg src0 = v->vgrf(glsl_type::int_type); fs_reg src1 = v->vgrf(glsl_type::int_type); fs_reg zero(brw_imm_f(0.0f)); bld.ADD(dest, src0, src1); bld.CMP(bld.null_reg_f(), retype(dest, BRW_REGISTER_TYPE_F), zero, BRW_CONDITIONAL_GE); /* = Before = * * 0: add(8) dest:D src0:D src1:D * 1: cmp.ge.f0(8) null:F dest:F 0.0f * * = After = * (no changes) */ v->calculate_cfg(); bblock_t *block0 = v->cfg->blocks[0]; EXPECT_EQ(0, block0->start_ip); EXPECT_EQ(1, block0->end_ip); EXPECT_FALSE(cmod_propagation(v)); EXPECT_EQ(0, block0->start_ip); EXPECT_EQ(1, block0->end_ip); EXPECT_EQ(BRW_OPCODE_ADD, instruction(block0, 0)->opcode); EXPECT_EQ(BRW_OPCODE_CMP, instruction(block0, 1)->opcode); EXPECT_EQ(BRW_CONDITIONAL_GE, instruction(block0, 1)->conditional_mod); } TEST_F(cmod_propagation_test, andnz_one) { const fs_builder &bld = v->bld; fs_reg dest = v->vgrf(glsl_type::int_type); fs_reg src0 = v->vgrf(glsl_type::float_type); fs_reg zero(brw_imm_f(0.0f)); fs_reg one(brw_imm_d(1)); bld.CMP(retype(dest, BRW_REGISTER_TYPE_F), src0, zero, BRW_CONDITIONAL_L); set_condmod(BRW_CONDITIONAL_NZ, bld.AND(bld.null_reg_d(), dest, one)); /* = Before = * 0: cmp.l.f0(8) dest:F src0:F 0F * 1: and.nz.f0(8) null:D dest:D 1D * * = After = * 0: cmp.l.f0(8) dest:F src0:F 0F */ v->calculate_cfg(); bblock_t *block0 = v->cfg->blocks[0]; EXPECT_EQ(0, block0->start_ip); EXPECT_EQ(1, block0->end_ip); EXPECT_TRUE(cmod_propagation(v)); EXPECT_EQ(0, block0->start_ip); EXPECT_EQ(0, block0->end_ip); EXPECT_EQ(BRW_OPCODE_CMP, instruction(block0, 0)->opcode); EXPECT_EQ(BRW_CONDITIONAL_L, instruction(block0, 0)->conditional_mod); EXPECT_TRUE(retype(dest, BRW_REGISTER_TYPE_F) .equals(instruction(block0, 0)->dst)); } TEST_F(cmod_propagation_test, andnz_non_one) { const fs_builder &bld = v->bld; fs_reg dest = v->vgrf(glsl_type::int_type); fs_reg src0 = v->vgrf(glsl_type::float_type); fs_reg zero(brw_imm_f(0.0f)); fs_reg nonone(brw_imm_d(38)); bld.CMP(retype(dest, BRW_REGISTER_TYPE_F), src0, zero, BRW_CONDITIONAL_L); set_condmod(BRW_CONDITIONAL_NZ, bld.AND(bld.null_reg_d(), dest, nonone)); /* = Before = * 0: cmp.l.f0(8) dest:F src0:F 0F * 1: and.nz.f0(8) null:D dest:D 38D * * = After = * (no changes) */ v->calculate_cfg(); bblock_t *block0 = v->cfg->blocks[0]; EXPECT_EQ(0, block0->start_ip); EXPECT_EQ(1, block0->end_ip); EXPECT_FALSE(cmod_propagation(v)); EXPECT_EQ(0, block0->start_ip); EXPECT_EQ(1, block0->end_ip); EXPECT_EQ(BRW_OPCODE_CMP, instruction(block0, 0)->opcode); EXPECT_EQ(BRW_CONDITIONAL_L, instruction(block0, 0)->conditional_mod); EXPECT_EQ(BRW_OPCODE_AND, instruction(block0, 1)->opcode); EXPECT_EQ(BRW_CONDITIONAL_NZ, instruction(block0, 1)->conditional_mod); } TEST_F(cmod_propagation_test, andz_one) { const fs_builder &bld = v->bld; fs_reg dest = v->vgrf(glsl_type::int_type); fs_reg src0 = v->vgrf(glsl_type::float_type); fs_reg zero(brw_imm_f(0.0f)); fs_reg one(brw_imm_d(1)); bld.CMP(retype(dest, BRW_REGISTER_TYPE_F), src0, zero, BRW_CONDITIONAL_L); set_condmod(BRW_CONDITIONAL_Z, bld.AND(bld.null_reg_d(), dest, one)); /* = Before = * 0: cmp.l.f0(8) dest:F src0:F 0F * 1: and.z.f0(8) null:D dest:D 1D * * = After = * (no changes) */ v->calculate_cfg(); bblock_t *block0 = v->cfg->blocks[0]; EXPECT_EQ(0, block0->start_ip); EXPECT_EQ(1, block0->end_ip); EXPECT_FALSE(cmod_propagation(v)); EXPECT_EQ(0, block0->start_ip); EXPECT_EQ(1, block0->end_ip); EXPECT_EQ(BRW_OPCODE_CMP, instruction(block0, 0)->opcode); EXPECT_EQ(BRW_CONDITIONAL_L, instruction(block0, 0)->conditional_mod); EXPECT_EQ(BRW_OPCODE_AND, instruction(block0, 1)->opcode); EXPECT_EQ(BRW_CONDITIONAL_EQ, instruction(block0, 1)->conditional_mod); }
30.606822
79
0.664418
antmicro
a97e495e4da2e1d5c7884705e9d5bc03376111b1
2,444
cpp
C++
Source/Engine/Render/VertexArray.cpp
kukiric/SomeGame
8c058d82a93bc3f276bbb3ec57a3978ae57de82c
[ "MIT" ]
null
null
null
Source/Engine/Render/VertexArray.cpp
kukiric/SomeGame
8c058d82a93bc3f276bbb3ec57a3978ae57de82c
[ "MIT" ]
null
null
null
Source/Engine/Render/VertexArray.cpp
kukiric/SomeGame
8c058d82a93bc3f276bbb3ec57a3978ae57de82c
[ "MIT" ]
null
null
null
#include "VertexArray.h" #include <Engine/Render/API.h> using namespace Render; VertexArray::VertexArray() : indexArraySize(0) { glGenVertexArrays(1, &handle); glGenBuffers(1, &indexArrayID); } VertexArray::~VertexArray() { for(auto vbo : buffers) { deleteBuffer(vbo.id); } glDeleteBuffers(1, &indexArrayID); glDeleteVertexArrays(1, &handle); } int VertexArray::createBufferEx(void* data, size_t sizeElement, size_t numElements, GLenum usageHint) { // Create a new, null buffer buffers.push_back({0, 0}); // Get a reference to it auto& newVBO = buffers.back(); // Generate a buffer on its ID glGenBuffers(1, &newVBO.id); glBindBuffer(GL_ARRAY_BUFFER, newVBO.id); glBufferData(GL_ARRAY_BUFFER, sizeElement * numElements, data, usageHint); // Set the buffer size property newVBO.count = numElements; // And return the buffer's index in the array (last position) return buffers.size()-1; } int VertexArray::deleteBuffer(int vbo) { if(vbo >= 0 and vbo < (int)buffers.size()) { glDeleteBuffers(1, &buffers[vbo].id); buffers.erase(buffers.begin() + vbo); return vbo; } else { return -1; } } int VertexArray::getBufferCount() const { return (int)buffers.size(); } void VertexArray::setIndexArrayEx(void* data, size_t sizeElement, size_t numElements, GLenum usageHint) { if(data) { glBindVertexArray(handle); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indexArrayID); glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeElement * numElements, data, usageHint); indexArraySize = numElements; } else { indexArraySize = 0; } } void VertexArray::addAttrib(GLuint index, int vbo, GLuint size, GLenum type, GLvoid* offset, GLint stride) { glBindVertexArray(handle); glEnableVertexAttribArray(index); glBindBuffer(GL_ARRAY_BUFFER, buffers[vbo].id); glVertexAttribPointer(index, size, type, GL_FALSE, stride, offset); } void VertexArray::removeAttrib(GLuint index) { glBindVertexArray(handle); glDisableVertexAttribArray(index); } void VertexArray::drawElements(GLenum mode) { glBindVertexArray(handle); if(indexArraySize) { glDrawElements(mode, indexArraySize, GL_UNSIGNED_INT, NULL); } else { glDrawArrays(mode, 0, buffers[0].count); } }
27.772727
107
0.661211
kukiric
a97edea22c6dbbc4626abc58a3cc4a41ff792ad1
7,562
cpp
C++
Chapter_20/program.cpp
9ndres/Ray-Tracing-Gems-II
5fef3b49375c823431ef06f8c67d1b44b432304a
[ "MIT" ]
603
2021-08-04T11:46:33.000Z
2022-03-28T12:12:31.000Z
Chapter_20/program.cpp
9ndres/Ray-Tracing-Gems-II
5fef3b49375c823431ef06f8c67d1b44b432304a
[ "MIT" ]
null
null
null
Chapter_20/program.cpp
9ndres/Ray-Tracing-Gems-II
5fef3b49375c823431ef06f8c67d1b44b432304a
[ "MIT" ]
45
2021-08-04T18:57:37.000Z
2022-03-11T11:33:49.000Z
#include "program_defs.h" #define STB_IMAGE_WRITE_IMPLEMENTATION #include "stb_image_write.h" #include <stdint.h> #include <vector> #include <random> #ifdef WIN32 #define PCG_LITTLE_ENDIAN 1 #endif #include "pcg_random.hpp" // NOTE: Include order is a bit brittle due to some of these appearing exactly as they are int he RTG2 chapter. #include "functions.h" #include "balance_heuristic.h" // In article #include "sample_lights.h" // In article #include "sample_lights_pdf.h" // In article //#include "material_lambert.h" #include "material_rough.h" #include "direct_light.h" // In article #include "direct_cos.h" // In article #include "direct_mat.h" // In article #include "direct_mis.h" // In article #include "pathtrace_mis.h" // In article #include "pathtrace.h" #include "trace_wrappers.h" // Add camera-trace to functions so they can be used struct Random { pcg32 rng; std::uniform_real_distribution<float> uniform; Random() { pcg_extras::seed_seq_from<std::random_device> seed_source; rng.seed(seed_source); }; }; thread_local Random random; // NOTE: uniform is thread-safe since random generator is in a thread_local variable float uniform() { return random.uniform(random.rng); } // NOTE: This function only applies gamma. uint32_t convert_sRGB(vec3 color) { float r = color.x, g = color.y, b = color.z; r = min(max(r, 0.0), 1.0); g = min(max(g, 0.0), 1.0); b = min(max(b, 0.0), 1.0); // TODO: Is this correct? Validate r = powf(r, 1.0f/2.2f); g = powf(g, 1.0f/2.2f); b = powf(b, 1.0f/2.2f); uint8_t rb = floor(r * 255.0f); uint8_t gb = floor(g * 255.0f); uint8_t bb = floor(b * 255.0f); return 0xFF000000|(bb<<16)|(gb<<8)|rb; } inline vec3 camera_direction(float2 uv, int w, int h, float fov_horizontal_degrees) { float aspect = float(h) / float(w); float fov_factor = tanf(fov_horizontal_degrees * (float)(2.0 * PI / 360.0 * 0.5)); vec3 camera_forward = vec3(0.0f, 0.0f, 1.0f); vec3 camera_right = vec3(1.0f, 0.0f, 0.0f); vec3 camera_up = vec3(0.0f, 1.0f, 0.0f); return normalize(camera_forward + camera_right * ((uv.x * 2.0 - 1.0) * fov_factor) + camera_up * ((uv.y * 2.0 - 1.0) * fov_factor * aspect)); } typedef vec3(*renderFunction)(vec3 pos, vec3 normal); void render(const std::string &dir, const std::string &filename, const renderFunction per_pixel, int subpixels, int w = 800, int h = 600, const std::string &filename_variance = "") { printf("Rendering %s%s\n", dir.c_str(), filename.c_str()); int ws = subpixels, hs = subpixels; // Camera definition vec3 camera_pos = vec3(0.0f, 1.2f, -7.0f); std::vector<uint32_t> result(w*h); std::vector<uint32_t> result_variance; if (!filename_variance.empty()) { result_variance.resize(w * h); } #pragma omp parallel for // NOTE: Comment away this line to get single-threaded execution for (int y=0; y<h; y++) { for (int x=0; x<w; x++) { vec3 mean = vec3(0); vec3 M2 = vec3(0); int N = 0; for (int sy=0; sy<hs; sy++) { for (int sx=0; sx<ws; sx++) { float xc = (x + (sx + uniform()) / ws) * (1.0f / w); float yc = (y + (sy + uniform()) / hs) * (1.0f / h); yc = 1.0 - yc; // Turn y-coordinate upside down since image (0,0) is upper-left but we want (0,0) to be lower-left // NOTE: A "real" renderer would have some sort of tone mapper here and use some filter kernel. vec3 dir = camera_direction(float2(xc, yc), w, h, 70.0f); vec3 color = per_pixel(camera_pos, dir); // Welford's online algorithm so we get variance as well // https://en.wikipedia.org/wiki/Algorithms_for_calculating_variance N++; vec3 delta = color - mean; mean += delta/N; vec3 delta2 = color - mean; M2 += delta * delta2; } } vec3 variance = M2/(N-1)/N; // Sample variance from Welford's online algorithm result[y*w+x]= convert_sRGB(mean); if (!result_variance.empty()) { if (y<8) { // Fill top-most 8 lines with pink so we don't mix the images result_variance[y * w + x] = convert_sRGB(vec3(1.0, 0.0, 1.0)); } else { result_variance[y * w + x] = convert_sRGB(vec3(sqrtf(variance.x), sqrtf(variance.y), sqrtf(variance.z))); } } } } stbi_write_png((dir+filename).c_str(), w, h, 4, result.data(), w*4); if (!filename_variance.empty()) { stbi_write_png((dir + filename_variance).c_str(), w, h, 4, result_variance.data(), w * 4); } } void render_mis_weights(const std::string& dir, const std::string &filename, int subpixels, int w = 800, int h = 600, const char* const filename_variance = nullptr) { printf("Rendering %s%s\n", dir.c_str(), filename.c_str()); int ws = subpixels, hs = subpixels; // Camera definition vec3 camera_pos = vec3(0.0f, 1.2f, -7.0f); std::vector<uint32_t> result(w*h); #pragma omp parallel for // NOTE: Comment away this line to get single-threaded execution for (int y=0; y<h; y++) { for (int x=0; x<w; x++) { vec3 mean_light = vec3(0); vec3 mean_material = vec3(0); int N = 0; for (int sy=0; sy<hs; sy++) { for (int sx=0; sx<ws; sx++) { float xc = (x + (sx + uniform()) / ws) * (1.0f / w); float yc = (y + (sy + uniform()) / hs) * (1.0f / h); yc = 1.0 - yc; // Turn y-coordinate upside down since image (0,0) is upper-left but we want (0,0) to be lower-left // NOTE: A "real" renderer would have some sort of tone mapper here and use some filter kernel. vec3 dir = camera_direction(float2(xc, yc), w, h, 70.0f); vec3 color_light = trace_direct_mis_light(camera_pos, dir); vec3 color_material = trace_direct_mis_material(camera_pos, dir); mean_light += color_light / (ws*hs); mean_material += color_material / (ws*hs); } } vec3 mean_full = mean_light + mean_material; float a = dot(mean_light, mean_full); float b = dot(mean_material, mean_full); vec3 full = mean_light + mean_material; mean_light.x /= full.x; mean_light.y /= full.y; mean_light.z /= full.z; mean_material.x /= full.x; mean_material.y /= full.y; mean_material.z /= full.z; float l = a/(a+b); float m = b/(a+b); vec3 color = vec3(m,0,0) + vec3(0,l,0); result[y*w+x]= convert_sRGB(color); } } stbi_write_png((dir + filename).c_str(), w, h, 4, result.data(), w*4); } void rtg2_figures(const char * const dir) { // This is the code that was used to generate the images in the RTG2 chapter int w = 512, h = 300; // Direct light sampling int direct_N = 10; render(dir, "direct_light_sampling.png", { trace_direct_light_sampling}, direct_N, w, h); render(dir, "direct_material_sampling.png", {trace_direct_material_sampling }, direct_N, w, h); render(dir, "direct_cos_sampling.png", { trace_direct_cos_sampling }, direct_N, w, h); render(dir, "direct_mis.png", { trace_direct_mis }, direct_N, w, h); render(dir, "direct_mis_light.png", { trace_direct_mis_light<2> }, direct_N, w, h); render(dir, "direct_mis_material.png", { trace_direct_mis_material<2> }, direct_N, w, h); render(dir, "scene_description.png", { show_scene }, direct_N, w, h); // Path tracing int pathtrace_N = 15; render(dir, "pathtrace_mis.png", { pathtrace_mis_helper }, pathtrace_N, w, h); render(dir, "pathtrace_light_sampling.png", { pathtrace<direct_light> }, pathtrace_N, w, h); //render(dir, "pathtrace_material_sampling.png", { pathtrace<direct_mat> }, pathtrace_N, w, h); //render(dir, "pathtrace_hemisphere_sampling.png", { pathtrace<direct_hemi> }, pathtrace_N, w, h); // Weight image for direct MIS render_mis_weights(dir, "direct_mis_weights.png", 35, w, h); } int main(void) { rtg2_figures("../figures/"); }
35.336449
182
0.663052
9ndres
a97ef44ca5a2261976898d1483c693ac1c18ef43
7,893
cpp
C++
tests/unit/PayCrypter_test.cpp
clockzhong/sdk
46476bae44ba99afe7eecd0ee29232fd4df2ea2e
[ "BSD-2-Clause" ]
null
null
null
tests/unit/PayCrypter_test.cpp
clockzhong/sdk
46476bae44ba99afe7eecd0ee29232fd4df2ea2e
[ "BSD-2-Clause" ]
null
null
null
tests/unit/PayCrypter_test.cpp
clockzhong/sdk
46476bae44ba99afe7eecd0ee29232fd4df2ea2e
[ "BSD-2-Clause" ]
null
null
null
/** * @file tests/tests.cpp * @brief Mega SDK main test file * * (c) 2013 by Mega Limited, Wellsford, New Zealand * * This file is part of the MEGA SDK - Client Access Engine. * * Applications using the MEGA API must present a valid application key * and comply with the the rules set forth in the Terms of Service. * * The MEGA SDK 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. * * @copyright Simplified (2-clause) BSD License. * * You should have received a copy of the license along with this * program. */ #include "mega.h" #include "gtest/gtest.h" using namespace mega; TEST(PayCrypter, allFeatures) { char BASE64_IV[] = "7XS3jX8CrWh6gpZIavQamA"; char BASE64_ENCKEY[] = "IcfMNKnMLJNJAH-XPMDShw"; char BASE64_HMACKEY[] = "rChwtATCap-CXO-KGxbEKZLL88lVfdZPZfZcdnMtj8o"; char KEYS[] = "IcfMNKnMLJNJAH-XPMDSh6wocLQEwmqfglzvihsWxCmSy_PJVX3WT2X2XHZzLY_K"; char CONTENT[] = "{\"first_name\": \"First\", \"last_name\": \"Last\"," " \"card_number\": \"4532646653175959\"," " \"expiry_date_month\": \"10\", \"expiry_date_year\": \"2020\"," " \"cv2\": \"123\", \"address1\": \"120 Albert St\"," " \"address2\": \"Auckland Central\", \"city\": \"Auckland\"," " \"province\": \"Auckland\", \"postal_code\": \"1010\"," " \"country_code\": \"NZ\"}"; char CIPHER_BYTES[] = "Btu6B6YxQV1oeMRij4Fn0Que9FfIE1LJyYdacVbNBM1bS-GZAtwQh5" "ZTtsakK6v_mMZGiQ3egRFSTNHzQU0jVa0GYZJ087NhlKlGtVO6PvBKmTkxpcnZpy1im" "S6uzKLccQU-IxKm1XnBF7gB7McbXDxb-j_s3-sjMJo_npDBOR3hUePGSyN-jmed7mvO" "K_fNY8DHqodpdVk7vy2PL8_iAY2SefttWGCD8DwiyxXx42KAjUaRHiYJqgdkZheF_Rp" "9l-KxgW8krDdkHsQu-nqeciezk5iA5OlylUmCfc57AKztBElyd4KIfz4B7kprmTeiiH" "8lhTCq7xZ64GdABzwfQghkf-fM9NJUD9bHfbTYfnnDRSvDrdJtD1gRVrkxnHNNVKhd6" "rtKToreM2bFhfUpcw"; char HMAC[] = "C7WRAdge50wzsAMqdM2_BVhntsP_OUYxaDMkPtRvewg"; //The same as the Javascript example char SDK_PUBKEY[] = "CACmWnYy7M5dqH7shqrj4jERfhhCfzoU5uDycAof1o8JyHu_F47b0aAB9KhKsIVKv90" "nbuea7wGuWsc0pxlrR5kKOnqMEcIQrLysFupSleqwilIgp5MUBvkPTdsn22Qc9Qldwm" "p_cbBNVfTrUVFSifv0QjDnbl7t9sLF5GgFMfYhWqMxAr3D3072cQF9eTbDLCbPD7RrC" "vUiTdqI1bT79e_187YSzCdjeVq_tZb5YnhLPHlgNQffmFJj41itSwpqrEYN8e5kIvsE" "INpHiLtXIIBBnld6NZu55U37sHeYkn5PB6cMi3ZEm90uIB7MT5CyHYLaEbJ9RkzJNRc" "xJAC2w4CnABEBAAE"; //From the Javascript example, disabling random padding (padding with 0) char CRYPT_GORT_SAYS[] = "AQB4PLTVCTdrPFXPWWCWZA3LdkjsIQgr7Ug8WBqFQlGqDR0YX0heatGVudAEb3TBOwvuoYsbOwVLOya22pqDJP6E-RUYDxbYC0dA02K7TSs97A9ZqnxnL6jvjW95X3BuR8YjStQJyy-a3FyAhrjyT9TnLOfKuUwIMLHf1eZB8H4JlAJ8VEQq9-SlusubiQZGZpYMeu2SBFJN-HI-93PEw2U3k-K6h7YYdhM-kIJ4-d2LuPWfyvuyjhs5fncgDgqPGZhq_4XOmV5Xh76aoqx8SBrPsotFvxE_CxOydivXhBMRaN6b6iL7MhuQXXDbOjvVis9uV2HnWraCxHbFwmUxoD6K"; char CRYPT_KEYS_BYTES[] = "AQB1FZOZJiEviXTXeBEOjyM6F9odENY6q4wzt73X0vVCbGBZyubKzHrNzHLaNkwGubd1RQ6wTuH3ypbK5wdM3QsyTcLq6DMv7O3JsH2R3MynRLuPGzHiNmZq2VkAMvELOo-XBeUknxrAstHZhWNQJImH4DBtnY57Mid1o-BTz7xKvRIUQvsj217CqE4CnVV6lxaloq6jvlenWATzCdEa1Q6Y8XN7hftn4Hl5ZrnAltIblBI0_fq2bkhqzZolpURbhypAg0oTFpnmj82QEBy4vwwdCOaQ8_lQjqQhsd3ah4O9gSkpYa6YoAtV9eBu338skJbhjprUVq04qi62Er_iichx"; //Initialize values byte enckey[sizeof(BASE64_ENCKEY)]; Base64::atob(BASE64_ENCKEY, enckey, sizeof(enckey)); byte iv[sizeof(BASE64_IV)]; int ivLen = Base64::atob(BASE64_IV, iv, sizeof(iv)); byte hmacKey[sizeof(BASE64_HMACKEY)]; int hmacKeyLen = Base64::atob(BASE64_HMACKEY, hmacKey, sizeof(hmacKey)); char keys[sizeof(KEYS)]; int keysLen = Base64::atob(KEYS, (byte *)keys, sizeof(keys)); byte pubkdata[sizeof(SDK_PUBKEY)]; int pubkdatalen = Base64::atob(SDK_PUBKEY, (byte *)pubkdata, sizeof(pubkdata)); ////////////////////// //Test AES-CBC encryption string result; string input = CONTENT; SymmCipher sym(enckey); sym.cbc_encrypt_pkcs_padding(&input, iv, &result); //Check result char* base64Result = new char[result.size()*4/3+4]; Base64::btoa((const byte *)result.data(), result.size(), base64Result); ASSERT_STREQ(base64Result, CIPHER_BYTES); ////////////////////// //Test AES-CBC decryption string plain; sym.cbc_decrypt_pkcs_padding(&result, iv, &plain); //Check result ASSERT_STREQ(input.c_str(), plain.c_str()); ////////////////////// //Test HMAC-SHA256 string toAuth; toAuth.assign((char *)iv, ivLen); toAuth.append(result); string mac; mac.resize(32); HMACSHA256 hmacProcessor(hmacKey, hmacKeyLen); hmacProcessor.add((byte *)toAuth.data(), toAuth.size()); hmacProcessor.get((byte *)mac.data()); //Check result char* macResult = new char[mac.size()*4/3+4]; Base64::btoa((const byte *)mac.data(), mac.size(), macResult); ASSERT_STREQ(macResult, HMAC); ////////////////////// //Test PayCrypter:encryptPayload() PrnGen rng; string payCrypterResult; PayCrypter payCrypter(rng); payCrypter.setKeys(enckey, hmacKey, iv); ASSERT_TRUE(payCrypter.encryptPayload(&input, &payCrypterResult)); //Prepare the expected result string CRYPT_PAYLOAD = mac; CRYPT_PAYLOAD.append((char *)iv, ivLen); CRYPT_PAYLOAD.append(result); char* expectedPayload = new char[CRYPT_PAYLOAD.size()*4/3+4]; Base64::btoa((const byte *)CRYPT_PAYLOAD.data(), CRYPT_PAYLOAD.size(), expectedPayload); //Check result char* encryptPayloadResult = new char[payCrypterResult.size()*4/3+4]; Base64::btoa((const byte *)payCrypterResult.data(), payCrypterResult.size(), encryptPayloadResult); ASSERT_STREQ(expectedPayload, encryptPayloadResult); ////////////////////// //Test PayCrypter:rsaEncryptKeys(), disabling random padding to get known results string message = "Klaatu barada nikto."; string rsaRes; ASSERT_TRUE(payCrypter.rsaEncryptKeys(&message, pubkdata, pubkdatalen, &rsaRes, false)); //Check result char* rsaResult = new char[rsaRes.size()*4/3+4]; Base64::btoa((const byte *)rsaRes.data(), rsaRes.size(), rsaResult); ASSERT_STREQ(rsaResult, CRYPT_GORT_SAYS); ////////////////////// //Test PayCrypter:rsaEncryptKeys() with a binary input, disabling random padding to get known results string cryptKeysBytesBin; message.assign(keys, keysLen); ASSERT_TRUE(payCrypter.rsaEncryptKeys(&message, pubkdata, pubkdatalen, &cryptKeysBytesBin, false)); //Check result char* cryptKeysBytes = new char[cryptKeysBytesBin.size()*4/3+4]; Base64::btoa((const byte *)cryptKeysBytesBin.data(), cryptKeysBytesBin.size(), cryptKeysBytes); ASSERT_STREQ(cryptKeysBytes, CRYPT_KEYS_BYTES); ////////////////////// //Test PayCrypter:hybridEncrypt() string finalResult; string contentString = CONTENT; ASSERT_TRUE(payCrypter.hybridEncrypt(&contentString, pubkdata, pubkdatalen, &finalResult, false)); //Prepare the expected result string expectedResult = cryptKeysBytesBin; expectedResult.append(CRYPT_PAYLOAD); char* expectedBase64Result = new char[expectedResult.size()*4/3+4]; Base64::btoa((const byte *)expectedResult.data(), expectedResult.size(), expectedBase64Result); //Check result char* finalCheck = new char[finalResult.size()*4/3+4]; Base64::btoa((const byte *)finalResult.data(), finalResult.size(), finalCheck); ASSERT_STREQ(finalCheck, expectedBase64Result); ////////////////////// delete[] finalCheck; delete[] expectedBase64Result; delete[] cryptKeysBytes; delete[] rsaResult; delete[] base64Result; delete[] macResult; delete[] expectedPayload; delete[] encryptPayloadResult; }
40.476923
377
0.707842
clockzhong
a97f33d7b6158b151be24b213ddd9c1df1dde485
11,646
cpp
C++
examples/albumcalc/albumcalc.cpp
crf8472/libarcstk
b2c29006c7dda6476bf3e7098f51ee30675439fb
[ "MIT" ]
null
null
null
examples/albumcalc/albumcalc.cpp
crf8472/libarcstk
b2c29006c7dda6476bf3e7098f51ee30675439fb
[ "MIT" ]
null
null
null
examples/albumcalc/albumcalc.cpp
crf8472/libarcstk
b2c29006c7dda6476bf3e7098f51ee30675439fb
[ "MIT" ]
null
null
null
// // Example for calculating AccurateRip checksums from each track of an album, // represented by a CUESheet and a single losslessly encoded audio file. // #include <cstdint> // for uint32_t etc. #include <cstdio> // for fopen, fclose, FILE #include <iomanip> // for setw, setfill, hex #include <iostream> // for cerr, cout #include <stdexcept> // for runtime_error #include <string> // for string extern "C" { #include <libcue/libcue.h> // libcue for parsing the CUEsheet } #include <sndfile.hh> // libsndfile for reading the audio file #ifndef __LIBARCSTK_CALCULATE_HPP__ // libarcstk: calculate ARCSs #include <arcstk/calculate.hpp> #endif #ifndef __LIBARCSTK_SAMPLES_HPP__ // libarcstk: normalize input samples #include <arcstk/samples.hpp> #endif #ifndef __LIBARCSTK_LOGGING_HPP__ // libarcstk: log what you do #include <arcstk/logging.hpp> #endif // ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! // NOTE! THIS IS EXAMPLE CODE! IT IS INTENDED TO DEMONSTRATE HOW LIBARCSTK COULD // BE USED. IT IS NOT INTENDED TO BE USED IN REAL LIFE PRODUCTION. IT IS IN NO // WAY TESTED FOR PRODUCTION. TAKE THIS AS A STARTING POINT TO YOUR OWN // SOLUTION, NOT AS A TOOL. // ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! ! /** * \brief Parse a CUEsheet and return offsets and implicitly the track count. * * This method is implemented without any use of libarcstk. It just has to be * available for parsing the CUESheet. * * @param[in] cuefilename Name of the CUEsheet file to parse * * @return STL-like container with a size_type holding offsets */ auto parse_cuesheet(const std::string &cuefilename) { FILE* f = std::fopen(cuefilename.c_str(), "r"); if (!f) { std::cerr << "Failed to open CUEsheet: " << cuefilename << std::endl; throw std::runtime_error("Failed to open CUEsheet"); } ::Cd* cdinfo = ::cue_parse_file(f); if (std::fclose(f)) { std::cerr << "Failed to close CUEsheet: " << cuefilename << std::endl; } f = nullptr; if (!cdinfo) { std::cerr << "Failed to parse CUEsheet: " << cuefilename << std::endl; throw std::runtime_error("Failed to parse CUEsheet"); } const auto track_count = ::cd_get_ntrack(cdinfo); std::vector<int> offsets; offsets.reserve(static_cast<decltype(offsets)::size_type>(track_count)); ::Track* track = nullptr; for (auto i = int { 1 }; i <= track_count; ++i) { track = ::cd_get_track(cdinfo, i); if (!track) { offsets.emplace_back(0); continue; } offsets.emplace_back(::track_get_start(track)); } ::cd_delete(cdinfo); return offsets; } int main(int argc, char* argv[]) { if (argc != 3) { std::cout << "Usage: albumcalc <cuesheet> <audiofile>" << std::endl; return EXIT_SUCCESS; } // Of course you would validate your input parameters in production code. const auto cuefilename { std::string { argv[1] }}; const auto audiofilename { std::string { argv[2] }}; // If you like, you can activate the internal logging of libarcstk to // see what's going on behind the scenes. We provide an appender for stdout. arcstk::Logging::instance().add_appender( std::make_unique<arcstk::Appender>("stdout", stdout)); // 'INFO' means you should probably not see anything unless you give // libarcstk unexpected input. Try 'DEBUG' or 'DEBUG1' if you want to // see more about what libarcstk is doing with your input. arcstk::Logging::instance().set_level(arcstk::LOGLEVEL::INFO); // Define input block size in number of samples, where 'sample' means a // 32 bit unsigned integer holding a pair of PCM 16 bit stereo samples. const auto samples_per_block { 16777216 }; // == 64 MB block size // libsndfile API provides the file handle for the audio file SndfileHandle audiofile(audiofilename, SFM_READ); // Skip any sanity checks you would do in production code... // Calculation will have to distinguish the tracks in the audiofile. // To identify the track bounds, we need the TOC, precisely: // 1. the number of tracks // 2. the track offset for each track // 3. the leadout frame // We derive 1. total number of tracks and 2. actual track offsets from // parsing the CUEsheet. We skip the details here for libarcstk does not // provide this functionality and the author just did a quick hack with // libcue. (Just consult the implementation of function parse_cuesheet() // if you are interested in the details, but this is libcue, not libarcstk.) const auto offsets { parse_cuesheet(cuefilename) }; // Skip santiy checks and everything you could do with try/catch ... // Two completed, one to go. Since the CUEsheet usually does not know the // length of the last track, we have to derive the leadout frame from the // audio data. We could do this quite convenient by using libarcstk's // AudioReader::acquire_size() method. But thanks to libsndfile, this is // not even necessary: the information is conveniently provided by the // audiofile handle: auto total_samples { arcstk::AudioSize { audiofile.frames(), arcstk::AudioSize::UNIT::SAMPLES } }; // Remark: what libsndfile calls "frames" is what libarcstk calls // "PCM 32 bit samples" or just "samples". Our "sample" represents a pair of // 16 bit stereo samples as a single 32 bit unsigned int (left/right). // Libsndfile's frame encodes the same information as 2 signed 16 bit // integers, one per channel. // We now have derived all relevant metadata from our input files. // Let's print it one last time before starting with the real business: for (decltype(offsets)::size_type i = 1; i < offsets.size(); ++i) { std::cout << "Track " << std::setw(2) << std::setfill(' ') << i << " offset: " << std::setw(6) << std::setfill(' ') << offsets[i-1] << std::endl; } std::cout << "Track count: " << offsets.size() << std::endl; std::cout << "Leadout: " << total_samples.leadout_frame() << std::endl; // Step 1: Use libarcstk to construct the TOC. auto toc { std::unique_ptr<arcstk::TOC> { nullptr }}; try { // This validates the parsed toc data and will throw if the parsed data // is inconsistent. toc = arcstk::make_toc(offsets, total_samples.leadout_frame()); } catch (const std::exception &e) { std::cerr << e.what() << std::endl; return 1; } // Step 2: Create a context from the TOC and the name of the audiofile. // The context represents the configuration of the calculation process along // with the necessary metadata. auto context { arcstk::make_context(toc, audiofilename) }; // Step 3: Create a Calculation and provide it with the context. // We do not specify a checksum type, thus the Calculation will provide // ARCSv1 as well as ARCSv2 values as default result. auto calculation { arcstk::Calculation { std::move(context) }}; // Let's enumerate the blocks in the output. This is just to give some // informative logging. auto total_blocks { 1 + (total_samples.total_samples() - 1) / samples_per_block }; std::cout << "Expect " << total_blocks << " blocks" << std::endl; // Provide simple input buffer for libsndfile's genuine sample/frame format. // We decide to want 16 bit signed integers. const auto buffer_len { samples_per_block * 2 }; std::vector<int16_t> buffer(buffer_len); const auto samples_total { calculation.context().audio_size().total_samples() }; auto ints_in_block { int32_t { 0 }}; // Count ints read in single operation auto samples_read { int64_t { 0 }}; // Count total samples actually read // The input buffer 'buffer' holds each 16 bit sample in a single integer. // Since we have stereo audio, there are two channels, which makes one // 16 bit integer per sample for each channel in interleaved (== not planar) // order, where the 16 bit sample for the left channel makes the start. // Libarcstk is not interested in those details, so we provide the samples // via a SampleSequence that abstracts the concrete format away: arcstk::InterleavedSamples<int16_t> sequence; // NOTE: These prerequisites are just provided by libsndfile at this // site in the code. In production code, you would of course verify // things... If the channel order is switched, the sample format is // changed or the sequence is planar, the example code will screw up! // Main loop: let libsndfile read the sample in its own format, normalize it // and update the prepared Calculation with the samples read in the current // loop run. while ((ints_in_block = audiofile.read(&buffer[0], buffer_len))) { // Check whether we have read the expected amount of samples in this run if (buffer_len != ints_in_block) { // Ok, no! So, this must be the last block. Check! const auto samples_in_block { ints_in_block / arcstk::CDDA::NUMBER_OF_CHANNELS }; const auto samples_expected { samples_total - samples_read }; if (samples_in_block != samples_expected) { // Unexpected number of samples for the last block. // This is an unrecoverable error, act accordingly here. std::cerr << "Expected " << buffer_len << " integers but got " << ints_in_block << ". Bail out." << std::endl; return EXIT_FAILURE; } // Adjust buffer size of the read buffer buffer.resize( static_cast<decltype(buffer)::size_type>(ints_in_block)); } std::cout << "Read block " << (1 + samples_read / samples_per_block) << "/" << total_blocks << " (" << (buffer.size() / 2) << " samples)" << std::endl; // Wrap buffer in a reusable SampleSequence sequence.wrap_int_buffer(&buffer[0], buffer.size()); // Count PCM 32 bit stereo samples processed. samples_read += sequence.size(); // We could also compute the number of samples ourselves: // buffer.size() / static_cast<unsigned int>(CDDA::NUMBER_OF_CHANNELS) // Note: since libsndfile has told us the total sample count, we were // able to configure the context with the correct leadout. // Otherwise, we would not yet know the leadout frame number. If that // were the case we would have to provide our Calculation with this // information manually by doing: // // calculation.update_audiosize(samples_read); // // _before_ we send the last block of samples to it. This is absolutely // essential since otherwise the Calculation will not know when to stop // and eventually fail. It is sufficient to update the audio size // just before the last block of samples is passed to Calculation. Since // we can recognize the last block as demonstrated above, we can also // count the total number of samples read before the last update. // Update calculation with next portion of normalized samples. calculation.update(sequence.begin(), sequence.end()); } // Ok, no more samples. We demonstrate that the Calculation is complete: if (calculation.complete()) { std::cout << "Calculation complete" << std::endl; } else { std::cerr << "Error, calculation incomplete" << std::endl; } std::cout << "Read " << samples_read << " samples" << std::endl; // Let's finally get us the result! auto checksums { calculation.result() }; // And now, the time has come: print the actual checksums. std::cout << "Track ARCSv1 ARCSv2" << std::endl; auto trk_no { 1 }; for (const auto& track_values : checksums) { std::cout << std::dec << " " << std::setw(2) << std::setfill(' ') << trk_no << " " << std::hex << std::uppercase << std::setw(8) << std::setfill('0') << track_values.get(arcstk::checksum::type::ARCS1).value() << " " << std::setw(8) << std::setfill('0') << track_values.get(arcstk::checksum::type::ARCS2).value() << std::endl; ++trk_no; } }
37.446945
80
0.688477
crf8472
a97f7953fca960a16e8196db33b75180168d1990
853
cpp
C++
c++/nim_game.cpp
SongZhao/leetcode
4a2b4f554e91f6a2167b336f8a69b80fa9f3f920
[ "Apache-2.0" ]
null
null
null
c++/nim_game.cpp
SongZhao/leetcode
4a2b4f554e91f6a2167b336f8a69b80fa9f3f920
[ "Apache-2.0" ]
null
null
null
c++/nim_game.cpp
SongZhao/leetcode
4a2b4f554e91f6a2167b336f8a69b80fa9f3f920
[ "Apache-2.0" ]
null
null
null
/* You are playing the following Nim Game with your friend: There is a heap of stones on the table, each time one of you take turns to remove 1 to 3 stones. The one who removes the last stone will be the winner. You will take the first turn to remove the stones. Both of you are very clever and have optimal strategies for the game. Write a function to determine whether you can win the game given the number of stones in the heap. For example, if there are 4 stones in the heap, then you will never win the game: no matter 1, 2, or 3 stones you remove, the last stone will always be removed by your friend. */ /* * Win if n is not divisible by 4 */ #include "helper.h" class Solution { public: bool canWinNim(int n) { return n % 4 != 0; } }; int main() { Solution s; cout << s.canWinNim(4) << endl; return 0; }
25.848485
121
0.696366
SongZhao
a9848c97452e16123eb2c272fe3c0c09d409d170
1,522
hpp
C++
codegen.hpp
zsr2531/bfc
5f6917c1d8e084dd2ba4507c7bca8f73bbc4504e
[ "MIT" ]
5
2020-09-06T10:42:41.000Z
2021-12-22T09:37:44.000Z
codegen.hpp
zsr2531/bfc
5f6917c1d8e084dd2ba4507c7bca8f73bbc4504e
[ "MIT" ]
null
null
null
codegen.hpp
zsr2531/bfc
5f6917c1d8e084dd2ba4507c7bca8f73bbc4504e
[ "MIT" ]
1
2021-08-13T09:40:04.000Z
2021-08-13T09:40:04.000Z
#include <sstream> #include <unordered_map> #include "ast.hpp" class CodeGen : public Listener { public: explicit inline CodeGen() { builder = {}; indentLevel = 1; builder << "// Generated by bfc\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\nint main() {\n"; builder << " unsigned char* memory = (unsigned char*) malloc(80000);\n memset(memory, 0, 80000);\n long long current = 40000;\n"; } inline auto toString() -> std::string { indentation(); builder << "free(memory);\n}"; return builder.str(); } protected: auto visitPrintStatement(const PrintStatement& printStatement) -> void override; auto visitInputStatement(const InputStatement& inputStatement) -> void override; auto visitShiftLeftStatement(const ShiftLeftStatement& shiftLeftStatement) -> void override; auto visitShiftRightStatement(const ShiftRightStatement& shiftLeftStatement) -> void override; auto visitIncrementStatement(const IncrementStatement& incrementStatement) -> void override; auto visitDecrementStatement(const DecrementStatement& decrementStatement) -> void override; auto enterLoopStatement(const LoopStatement& loopStatement) -> void override; auto exitLoopStatement(const LoopStatement& loopStatement) -> void override; private: std::ostringstream builder; ulong indentLevel; inline auto indentation() -> void { for (auto i = 0; i < indentLevel; ++i) builder << " "; } };
40.052632
140
0.690539
zsr2531
a98bfbfbfd51a0805a97ea88749cfd7a97199d47
452
cpp
C++
book/cpp_templates/tmplbook/traits/hasmember.cpp
houruixiang/day_day_learning
208f70a4f0a85dd99191087835903d279452fd54
[ "MIT" ]
null
null
null
book/cpp_templates/tmplbook/traits/hasmember.cpp
houruixiang/day_day_learning
208f70a4f0a85dd99191087835903d279452fd54
[ "MIT" ]
null
null
null
book/cpp_templates/tmplbook/traits/hasmember.cpp
houruixiang/day_day_learning
208f70a4f0a85dd99191087835903d279452fd54
[ "MIT" ]
null
null
null
#include "hasmember.hpp" #include <iostream> #include <vector> #include <utility> DEFINE_HAS_MEMBER(size); DEFINE_HAS_MEMBER(first); int main() { std::cout << "int::size: " << HasMemberT_size<int>::value << '\n'; std::cout << "std::vector<int>::size: " << HasMemberT_size<std::vector<int>>::value << '\n'; std::cout << "std::pair<int,int>::first: " << HasMemberT_first<std::pair<int,int>>::value << '\n'; }
23.789474
67
0.586283
houruixiang
a98c9c9038aebe5a7eb8f50ccd34c321abdee0cd
5,650
cc
C++
src/base/file_reader.test.cc
dspeterson/dory
7261fb5481283fdd69b382c3cddbc9b9bd24366d
[ "Apache-2.0" ]
82
2016-06-11T23:12:40.000Z
2022-02-21T21:01:36.000Z
src/base/file_reader.test.cc
dspeterson/dory
7261fb5481283fdd69b382c3cddbc9b9bd24366d
[ "Apache-2.0" ]
18
2016-06-16T22:55:12.000Z
2020-07-02T10:32:53.000Z
src/base/file_reader.test.cc
dspeterson/dory
7261fb5481283fdd69b382c3cddbc9b9bd24366d
[ "Apache-2.0" ]
14
2016-06-15T18:34:08.000Z
2021-09-06T23:16:28.000Z
/* <base/file_reader.test.cc> ---------------------------------------------------------------------------- Copyright 2017 Dave Peterson <dave@dspeterson.com> 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. ---------------------------------------------------------------------------- Unit test for <base/file_reader.h>. */ #include <base/file_reader.h> #include <cstring> #include <fstream> #include <string> #include <base/error_util.h> #include <base/tmp_file.h> #include <gtest/gtest.h> using namespace Base; namespace { class TFileReaderSimpleTest : public ::testing::Test { protected: TFileReaderSimpleTest() { } virtual ~TFileReaderSimpleTest() { } virtual void SetUp() { } virtual void TearDown() { } }; // TFileReaderSimpleTest /* The fixture for testing class TFileReader. */ class TFileReaderTest : public ::testing::Test { protected: TFileReaderTest() : FileContents("a bunch of junk"), TmpFile("/tmp/file_reader_test.XXXXXX", true /* delete_on_destroy */), Reader(TmpFile.GetName().c_str()) { } virtual ~TFileReaderTest() { } virtual void SetUp() { std::ofstream f(TmpFile.GetName().c_str(), std::ios_base::out); f << FileContents; } virtual void TearDown() { } std::string FileContents; TTmpFile TmpFile; TFileReader Reader; }; // TFileReaderTest TEST_F(TFileReaderSimpleTest, TestNoSuchFile) { TFileReader reader("/blah/this_file_should_not_exist"); bool threw = false; try { reader.GetSize(); } catch (const std::ios_base::failure &x) { threw = true; } ASSERT_TRUE(threw); threw = false; char buf[16]; try { reader.ReadIntoBuf(buf, sizeof(buf)); } catch (const std::ios_base::failure &x) { threw = true; } ASSERT_TRUE(threw); threw = false; std::string s; try { reader.ReadIntoString(s); } catch (const std::ios_base::failure &x) { threw = true; } ASSERT_TRUE(threw); threw = false; try { reader.ReadIntoString(); } catch (const std::ios_base::failure &x) { threw = true; } ASSERT_TRUE(threw); threw = false; std::vector<char> v; try { reader.ReadIntoBuf(v); } catch (const std::ios_base::failure &x) { threw = true; } ASSERT_TRUE(threw); threw = false; try { reader.ReadIntoBuf<char>(); } catch (const std::ios_base::failure &x) { threw = true; } ASSERT_TRUE(threw); } TEST_F(TFileReaderTest, TestGetSize) { ASSERT_EQ(Reader.GetSize(), FileContents.size()); /* Make sure a second GetSize() operation with the same reader works. */ ASSERT_EQ(Reader.GetSize(), FileContents.size()); } TEST_F(TFileReaderTest, TestCallerSuppliedBuf) { char buf[2 * FileContents.size()]; std::fill(buf, buf + sizeof(buf), 'x'); size_t byte_count = Reader.ReadIntoBuf(buf, sizeof(buf)); ASSERT_EQ(byte_count, FileContents.size()); ASSERT_EQ(std::memcmp(buf, "a bunch of junkxxxxxxxxxxxxxxx", sizeof(buf)), 0); std::fill(buf, buf + sizeof(buf), 'x'); byte_count = Reader.ReadIntoBuf(buf, 7); ASSERT_EQ(byte_count, 7U); ASSERT_EQ(std::memcmp(buf, "a bunchxxxxxxxxxxxxxxxxxxxxxxx", sizeof(buf)), 0); } TEST_F(TFileReaderTest, TestCallerSuppliedBuf2) { char buf[2 * FileContents.size()]; std::fill(buf, buf + sizeof(buf), 'x'); size_t byte_count = ReadFileIntoBuf(TmpFile.GetName(), buf, sizeof(buf)); ASSERT_EQ(byte_count, FileContents.size()); ASSERT_EQ(std::memcmp(buf, "a bunch of junkxxxxxxxxxxxxxxx", sizeof(buf)), 0); std::fill(buf, buf + sizeof(buf), 'x'); byte_count = ReadFileIntoBuf(TmpFile.GetName(), buf, 7); ASSERT_EQ(byte_count, 7U); ASSERT_EQ(std::memcmp(buf, "a bunchxxxxxxxxxxxxxxxxxxxxxxx", sizeof(buf)), 0); } TEST_F(TFileReaderTest, TestReadIntoString) { std::string s; Reader.ReadIntoString(s); ASSERT_EQ(s, FileContents); ASSERT_EQ(Reader.ReadIntoString(), FileContents); } TEST_F(TFileReaderTest, TestReadIntoString2) { std::string s; ReadFileIntoString(TmpFile.GetName(), s); ASSERT_EQ(s, FileContents); ASSERT_EQ(ReadFileIntoString(TmpFile.GetName()), FileContents); } TEST_F(TFileReaderTest, TestReadIntoVector) { std::vector<char> v1; Reader.ReadIntoBuf(v1); ASSERT_EQ(v1.size(), FileContents.size()); ASSERT_EQ(std::memcmp(&v1[0], FileContents.data(), v1.size()), 0); std::vector<char> v2 = Reader.ReadIntoBuf<char>(); ASSERT_EQ(v2, v1); } TEST_F(TFileReaderTest, TestReadIntoVector2) { std::vector<char> v1; ReadFileIntoBuf(TmpFile.GetName(), v1); ASSERT_EQ(v1.size(), FileContents.size()); ASSERT_EQ(std::memcmp(&v1[0], FileContents.data(), v1.size()), 0); std::vector<char> v2 = ReadFileIntoBuf<char>(TmpFile.GetName()); ASSERT_EQ(v2, v1); } } // namespace int main(int argc, char **argv) { ::testing::InitGoogleTest(&argc, argv); DieOnTerminate(); return RUN_ALL_TESTS(); }
26.157407
79
0.629735
dspeterson
a98cd8343f943b0ee828d6eaae7e866c24bf41ce
6,583
cpp
C++
SpatialGDK/Source/SpatialGDKTests/SpatialGDKServices/LocalDeploymentManager/LocalDeploymentManagerTest.cpp
eddyrainy/UnrealGDK
eb86c58d23d55e74b584b91c2d35702ba08448be
[ "MIT" ]
null
null
null
SpatialGDK/Source/SpatialGDKTests/SpatialGDKServices/LocalDeploymentManager/LocalDeploymentManagerTest.cpp
eddyrainy/UnrealGDK
eb86c58d23d55e74b584b91c2d35702ba08448be
[ "MIT" ]
null
null
null
SpatialGDK/Source/SpatialGDKTests/SpatialGDKServices/LocalDeploymentManager/LocalDeploymentManagerTest.cpp
eddyrainy/UnrealGDK
eb86c58d23d55e74b584b91c2d35702ba08448be
[ "MIT" ]
null
null
null
// Copyright (c) Improbable Worlds Ltd, All Rights Reserved #include "TestDefinitions.h" #include "LocalDeploymentManager.h" #include "SpatialCommandUtils.h" #include "SpatialGDKDefaultLaunchConfigGenerator.h" #include "SpatialGDKDefaultWorkerJsonGenerator.h" #include "SpatialGDKEditorSettings.h" #include "CoreMinimal.h" #define LOCALDEPLOYMENT_TEST(TestName) \ GDK_TEST(Services, LocalDeployment, TestName) namespace { // TODO: UNR-1969 - Prepare LocalDeployment in CI pipeline const double MAX_WAIT_TIME_FOR_LOCAL_DEPLOYMENT_OPERATION = 20.0; // TODO: UNR-1964 - Move EDeploymentState enum to LocalDeploymentManager enum class EDeploymentState { IsRunning, IsNotRunning }; const FName AutomationWorkerType = TEXT("AutomationWorker"); const FString AutomationLaunchConfig = TEXT("Improbable/AutomationLaunchConfig.json"); FLocalDeploymentManager* GetLocalDeploymentManager() { FSpatialGDKServicesModule& GDKServices = FModuleManager::GetModuleChecked<FSpatialGDKServicesModule>("SpatialGDKServices"); FLocalDeploymentManager* LocalDeploymentManager = GDKServices.GetLocalDeploymentManager(); return LocalDeploymentManager; } bool GenerateWorkerAssemblies() { FString BuildConfigArgs = TEXT("worker build build-config"); FString WorkerBuildConfigResult; int32 ExitCode; SpatialCommandUtils::ExecuteSpatialCommandAndReadOutput(BuildConfigArgs, FSpatialGDKServicesModule::GetSpatialOSDirectory(), WorkerBuildConfigResult, ExitCode, false); const int32 ExitCodeSuccess = 0; return (ExitCode == ExitCodeSuccess); } bool GenerateWorkerJson() { const FString WorkerJsonDir = FSpatialGDKServicesModule::GetSpatialOSDirectory(TEXT("workers/unreal")); FString JsonPath = FPaths::Combine(WorkerJsonDir, TEXT("spatialos.UnrealAutomation.worker.json")); if (!FPaths::FileExists(JsonPath)) { bool bRedeployRequired = false; return GenerateDefaultWorkerJson(JsonPath, AutomationWorkerType.ToString(), bRedeployRequired); } return true; } } DEFINE_LATENT_AUTOMATION_COMMAND(FStartDeployment); bool FStartDeployment::Update() { if (const USpatialGDKEditorSettings* SpatialGDKSettings = GetDefault<USpatialGDKEditorSettings>()) { FLocalDeploymentManager* LocalDeploymentManager = GetLocalDeploymentManager(); const FString LaunchConfig = FPaths::Combine(FPaths::ConvertRelativePathToFull(FPaths::ProjectIntermediateDir()), AutomationLaunchConfig); const FString LaunchFlags = SpatialGDKSettings->GetSpatialOSCommandLineLaunchFlags(); const FString SnapshotName = SpatialGDKSettings->GetSpatialOSSnapshotToLoad(); AsyncTask(ENamedThreads::AnyBackgroundThreadNormalTask, [LocalDeploymentManager, LaunchConfig, LaunchFlags, SnapshotName] { if (!GenerateWorkerJson()) { return; } if (!GenerateWorkerAssemblies()) { return; } FSpatialLaunchConfigDescription LaunchConfigDescription(AutomationWorkerType); if (!GenerateDefaultLaunchConfig(LaunchConfig, &LaunchConfigDescription)) { return; } if (LocalDeploymentManager->IsLocalDeploymentRunning()) { return; } LocalDeploymentManager->TryStartLocalDeployment(LaunchConfig, LaunchFlags, SnapshotName, TEXT(""), FLocalDeploymentManager::LocalDeploymentCallback()); }); } return true; } DEFINE_LATENT_AUTOMATION_COMMAND(FStopDeployment); bool FStopDeployment::Update() { FLocalDeploymentManager* LocalDeploymentManager = GetLocalDeploymentManager(); if (!LocalDeploymentManager->IsLocalDeploymentRunning() && !LocalDeploymentManager->IsDeploymentStopping()) { return true; } if (!LocalDeploymentManager->IsDeploymentStopping()) { AsyncTask(ENamedThreads::AnyBackgroundThreadNormalTask, [LocalDeploymentManager] { LocalDeploymentManager->TryStopLocalDeployment(); }); } return true; } DEFINE_LATENT_AUTOMATION_COMMAND_TWO_PARAMETER(FWaitForDeployment, FAutomationTestBase*, Test, EDeploymentState, ExpectedDeploymentState); bool FWaitForDeployment::Update() { const double NewTime = FPlatformTime::Seconds(); if (NewTime - StartTime >= MAX_WAIT_TIME_FOR_LOCAL_DEPLOYMENT_OPERATION) { return true; } FLocalDeploymentManager* LocalDeploymentManager = GetLocalDeploymentManager(); if (LocalDeploymentManager->IsDeploymentStopping()) { return false; } else { return (ExpectedDeploymentState == EDeploymentState::IsRunning) ? LocalDeploymentManager->IsLocalDeploymentRunning() : !LocalDeploymentManager->IsLocalDeploymentRunning(); } } DEFINE_LATENT_AUTOMATION_COMMAND_TWO_PARAMETER(FCheckDeploymentState, FAutomationTestBase*, Test, EDeploymentState, ExpectedDeploymentState); bool FCheckDeploymentState::Update() { FLocalDeploymentManager* LocalDeploymentManager = GetLocalDeploymentManager(); if (ExpectedDeploymentState == EDeploymentState::IsRunning) { Test->TestTrue(TEXT("Deployment is running"), LocalDeploymentManager->IsLocalDeploymentRunning() && !LocalDeploymentManager->IsDeploymentStopping()); } else { Test->TestFalse(TEXT("Deployment is not running"), LocalDeploymentManager->IsLocalDeploymentRunning() || LocalDeploymentManager->IsDeploymentStopping()); } return true; } /* // UNR-1975 after fixing the flakiness of these tests, and investigating how they can be run in CI (UNR-1969), re-enable them LOCALDEPLOYMENT_TEST(GIVEN_no_deployment_running_WHEN_deployment_started_THEN_deployment_running) { // GIVEN ADD_LATENT_AUTOMATION_COMMAND(FStopDeployment()); ADD_LATENT_AUTOMATION_COMMAND(FWaitForDeployment(this, EDeploymentState::IsNotRunning)); // WHEN ADD_LATENT_AUTOMATION_COMMAND(FStartDeployment()); ADD_LATENT_AUTOMATION_COMMAND(FWaitForDeployment(this, EDeploymentState::IsRunning)); // THEN ADD_LATENT_AUTOMATION_COMMAND(FCheckDeploymentState(this, EDeploymentState::IsRunning)); // Cleanup ADD_LATENT_AUTOMATION_COMMAND(FStopDeployment()); ADD_LATENT_AUTOMATION_COMMAND(FWaitForDeployment(this, EDeploymentState::IsNotRunning)); return true; } LOCALDEPLOYMENT_TEST(GIVEN_deployment_running_WHEN_deployment_stopped_THEN_deployment_not_running) { // GIVEN ADD_LATENT_AUTOMATION_COMMAND(FStopDeployment()); ADD_LATENT_AUTOMATION_COMMAND(FWaitForDeployment(this, EDeploymentState::IsNotRunning)); ADD_LATENT_AUTOMATION_COMMAND(FStartDeployment()); ADD_LATENT_AUTOMATION_COMMAND(FWaitForDeployment(this, EDeploymentState::IsRunning)); // WHEN ADD_LATENT_AUTOMATION_COMMAND(FStopDeployment()); ADD_LATENT_AUTOMATION_COMMAND(FWaitForDeployment(this, EDeploymentState::IsNotRunning)); // THEN ADD_LATENT_AUTOMATION_COMMAND(FCheckDeploymentState(this, EDeploymentState::IsNotRunning)); return true; }*/
33.586735
173
0.809965
eddyrainy
a98cf28d3d49efba7b7a290d7fd9ff9ec3c64556
1,003
hpp
C++
buildSystemTests/multi_targets_project/code/StaticTarget3/public/StaticTarget3/StaticTarget3.hpp
iblis-ms/python_cmake_build_system
9f52f004241c6e8efc4a036d5c58f67a6d40e7ec
[ "MIT" ]
null
null
null
buildSystemTests/multi_targets_project/code/StaticTarget3/public/StaticTarget3/StaticTarget3.hpp
iblis-ms/python_cmake_build_system
9f52f004241c6e8efc4a036d5c58f67a6d40e7ec
[ "MIT" ]
6
2020-10-11T21:03:24.000Z
2020-10-12T20:32:13.000Z
buildSystemTests/multi_targets_project/code/StaticTarget3/public/StaticTarget3/StaticTarget3.hpp
iblis-ms/python_cmake_build_system
9f52f004241c6e8efc4a036d5c58f67a6d40e7ec
[ "MIT" ]
null
null
null
#ifndef STATIC_TARGET_3_HPP_ #define STATIC_TARGET_3_HPP_ #include <iostream> #include <InterfaceTarget3/InterfaceTarget3.hpp> #include <InterfaceTarget2/InterfaceTarget2.hpp> #include <InterfaceTarget4/InterfaceTarget4.hpp> #include <StaticTarget1/StaticTarget1.hpp> #include <StaticTarget2/StaticTarget2.hpp> /** * @brief Shared target 3 public class * */ struct CStaticTarget3 : IInterfaceTarget3, IInterfaceTarget4 { /** * @brief Function 3. * */ virtual void fun_interface3() override; /** * @brief Function 4. * */ virtual void fun_interface4() override; /** * @brief Get the Interface Target2 object * * @return IInterfaceTarget2& */ IInterfaceTarget2& getInterfaceTarget2(); /** * @brief Get the Static Target1 object * * @return CStaticTarget1& */ CStaticTarget1& getStaticTarget1(); /** * @brief Get the Static Target2 object * * @return CStaticTarget2& */ CStaticTarget2& getStaticTarget2(); }; #endif // STATIC_TARGET_3_HPP_
18.924528
60
0.716849
iblis-ms
a98d481499dd8267ddbe4ac416d3996e23c3e622
651
hpp
C++
homeworks/HW4Source/HW4/header/MountainCar.hpp
anshuman1811/cs687-reinforcementlearning
cf30cc0ab2b0e515cd4b643fc55c60cc5f38a481
[ "MIT" ]
null
null
null
homeworks/HW4Source/HW4/header/MountainCar.hpp
anshuman1811/cs687-reinforcementlearning
cf30cc0ab2b0e515cd4b643fc55c60cc5f38a481
[ "MIT" ]
null
null
null
homeworks/HW4Source/HW4/header/MountainCar.hpp
anshuman1811/cs687-reinforcementlearning
cf30cc0ab2b0e515cd4b643fc55c60cc5f38a481
[ "MIT" ]
null
null
null
#pragma once #include "stdafx.h" // MountainCar MDP - see Gridworld.hpp for comments regarding the general structure of these environment/MDP objects class MountainCar { public: MountainCar(); int getStateDim() const; int getNumActions() const; double update(const int & action, std::mt19937_64 & generator); std::vector<double> getState(std::mt19937_64 & generator); bool inTerminalState() const; void newEpisode(std::mt19937_64 & generator); private: const double minX = -1.2; const double maxX = 0.5; const double minXDot = -0.07; const double maxXDot = 0.07; std::vector<double> state; // [2] - x and xDot };
28.304348
117
0.703533
anshuman1811
a98f4ab7870560163705313937a8065595ba831f
2,320
cc
C++
RecoPixelVertexing/PixelLowPtUtilities/plugins/modules.cc
PKUfudawei/cmssw
8fbb5ce74398269c8a32956d7c7943766770c093
[ "Apache-2.0" ]
1
2021-11-30T16:24:46.000Z
2021-11-30T16:24:46.000Z
RecoPixelVertexing/PixelLowPtUtilities/plugins/modules.cc
PKUfudawei/cmssw
8fbb5ce74398269c8a32956d7c7943766770c093
[ "Apache-2.0" ]
4
2021-11-29T13:57:56.000Z
2022-03-29T06:28:36.000Z
RecoPixelVertexing/PixelLowPtUtilities/plugins/modules.cc
PKUfudawei/cmssw
8fbb5ce74398269c8a32956d7c7943766770c093
[ "Apache-2.0" ]
1
2022-02-27T06:12:26.000Z
2022-02-27T06:12:26.000Z
#include "FWCore/PluginManager/interface/ModuleDef.h" #include "FWCore/Framework/interface/MakerMacros.h" #include "FWCore/Framework/interface/ModuleFactory.h" #include "FWCore/Framework/interface/ESProducer.h" // Producers //#include "PixelTrackProducerWithZPos.h" //DEFINE_FWK_MODULE(PixelTrackProducerWithZPos); #include "PixelVertexProducerMedian.h" DEFINE_FWK_MODULE(PixelVertexProducerMedian); #include "PixelVertexProducerClusters.h" DEFINE_FWK_MODULE(PixelVertexProducerClusters); #include "TrackListCombiner.h" DEFINE_FWK_MODULE(TrackListCombiner); // Generator #include "RecoPixelVertexing/PixelTriplets/interface/HitTripletGeneratorFromPairAndLayers.h" #include "RecoPixelVertexing/PixelTriplets/interface/HitTripletGeneratorFromPairAndLayersFactory.h" #include "RecoPixelVertexing/PixelLowPtUtilities/interface/PixelTripletLowPtGenerator.h" DEFINE_EDM_PLUGIN(HitTripletGeneratorFromPairAndLayersFactory, PixelTripletLowPtGenerator, "PixelTripletLowPtGenerator"); // Seed //#include "RecoPixelVertexing/PixelLowPtUtilities/interface/SeedProducer.h" //DEFINE_FWK_MODULE(SeedProducer); // TrajectoryFilter #include "FWCore/Utilities/interface/typelookup.h" #include "FWCore/ParameterSet/interface/ValidatedPluginMacros.h" #include "TrackingTools/TrajectoryFiltering/interface/TrajectoryFilterFactory.h" #include "RecoPixelVertexing/PixelLowPtUtilities/interface/ClusterShapeTrajectoryFilter.h" DEFINE_EDM_VALIDATED_PLUGIN(TrajectoryFilterFactory, ClusterShapeTrajectoryFilter, "ClusterShapeTrajectoryFilter"); // the seed comparitor to remove seeds on incompatible angle/cluster compatibility #include "RecoPixelVertexing/PixelLowPtUtilities/interface/LowPtClusterShapeSeedComparitor.h" #include "RecoTracker/TkSeedingLayers/interface/SeedComparitorFactory.h" DEFINE_EDM_PLUGIN(SeedComparitorFactory, LowPtClusterShapeSeedComparitor, "LowPtClusterShapeSeedComparitor"); #include "RecoPixelVertexing/PixelLowPtUtilities/interface/StripSubClusterShapeTrajectoryFilter.h" DEFINE_EDM_VALIDATED_PLUGIN(TrajectoryFilterFactory, StripSubClusterShapeTrajectoryFilter, "StripSubClusterShapeTrajectoryFilter"); DEFINE_EDM_PLUGIN(SeedComparitorFactory, StripSubClusterShapeSeedFilter, "StripSubClusterShapeSeedFilter");
47.346939
115
0.840948
PKUfudawei
81799b89ff3310ff1fe99a362dcb69165582376f
4,571
cpp
C++
emulator/src/devices/machine/atapicdr.cpp
rjw57/tiw-computer
5ef1c79893165b8622d1114d81cd0cded58910f0
[ "MIT" ]
1
2022-01-15T21:38:38.000Z
2022-01-15T21:38:38.000Z
emulator/src/devices/machine/atapicdr.cpp
rjw57/tiw-computer
5ef1c79893165b8622d1114d81cd0cded58910f0
[ "MIT" ]
null
null
null
emulator/src/devices/machine/atapicdr.cpp
rjw57/tiw-computer
5ef1c79893165b8622d1114d81cd0cded58910f0
[ "MIT" ]
null
null
null
// license:BSD-3-Clause // copyright-holders:smf #include "emu.h" #include "atapicdr.h" #define SCSI_SENSE_ASC_MEDIUM_NOT_PRESENT 0x3a #define SCSI_SENSE_ASC_NOT_READY_TO_READY_TRANSITION 0x28 #define T10MMC_GET_EVENT_STATUS_NOTIFICATION 0x4a // device type definition DEFINE_DEVICE_TYPE(ATAPI_CDROM, atapi_cdrom_device, "cdrom", "ATAPI CD-ROM") DEFINE_DEVICE_TYPE(ATAPI_FIXED_CDROM, atapi_fixed_cdrom_device, "cdrom_fixed", "ATAPI fixed CD-ROM") atapi_cdrom_device::atapi_cdrom_device(const machine_config &mconfig, const char *tag, device_t *owner, uint32_t clock) : atapi_cdrom_device(mconfig, ATAPI_CDROM, tag, owner, clock) { } atapi_cdrom_device::atapi_cdrom_device(const machine_config &mconfig, device_type type, const char *tag, device_t *owner, uint32_t clock) : atapi_hle_device(mconfig, type, tag, owner, clock) { } atapi_fixed_cdrom_device::atapi_fixed_cdrom_device(const machine_config &mconfig, const char *tag, device_t *owner, uint32_t clock) : atapi_cdrom_device(mconfig, ATAPI_FIXED_CDROM, tag, owner, clock) { } //------------------------------------------------- // device_add_mconfig - add device configuration //------------------------------------------------- MACHINE_CONFIG_START(atapi_cdrom_device::device_add_mconfig) MCFG_CDROM_ADD("image") MCFG_CDROM_INTERFACE("cdrom") MCFG_SOUND_ADD("cdda", CDDA, 0) MACHINE_CONFIG_END void atapi_cdrom_device::device_start() { m_image = subdevice<cdrom_image_device>("image"); m_cdda = subdevice<cdda_device>("cdda"); memset(m_identify_buffer, 0, sizeof(m_identify_buffer)); m_identify_buffer[ 0 ] = 0x8500; // ATAPI device, cmd set 5 compliant, DRQ within 3 ms of PACKET command m_identify_buffer[ 23 ] = ('1' << 8) | '.'; m_identify_buffer[ 24 ] = ('0' << 8) | ' '; m_identify_buffer[ 25 ] = (' ' << 8) | ' '; m_identify_buffer[ 26 ] = (' ' << 8) | ' '; m_identify_buffer[ 27 ] = ('M' << 8) | 'A'; m_identify_buffer[ 28 ] = ('M' << 8) | 'E'; m_identify_buffer[ 29 ] = (' ' << 8) | ' '; m_identify_buffer[ 30 ] = (' ' << 8) | ' '; m_identify_buffer[ 31 ] = ('V' << 8) | 'i'; m_identify_buffer[ 32 ] = ('r' << 8) | 't'; m_identify_buffer[ 33 ] = ('u' << 8) | 'a'; m_identify_buffer[ 34 ] = ('l' << 8) | ' '; m_identify_buffer[ 35 ] = ('C' << 8) | 'D'; m_identify_buffer[ 36 ] = ('R' << 8) | 'O'; m_identify_buffer[ 37 ] = ('M' << 8) | ' '; m_identify_buffer[ 38 ] = (' ' << 8) | ' '; m_identify_buffer[ 39 ] = (' ' << 8) | ' '; m_identify_buffer[ 40 ] = (' ' << 8) | ' '; m_identify_buffer[ 41 ] = (' ' << 8) | ' '; m_identify_buffer[ 42 ] = (' ' << 8) | ' '; m_identify_buffer[ 43 ] = (' ' << 8) | ' '; m_identify_buffer[ 44 ] = (' ' << 8) | ' '; m_identify_buffer[ 45 ] = (' ' << 8) | ' '; m_identify_buffer[ 46 ] = (' ' << 8) | ' '; m_identify_buffer[ 49 ] = 0x0600; // Word 49=Capabilities, IORDY may be disabled (bit_10), LBA Supported mandatory (bit_9) atapi_hle_device::device_start(); } void atapi_cdrom_device::device_reset() { atapi_hle_device::device_reset(); m_media_change = true; } void atapi_fixed_cdrom_device::device_reset() { atapi_hle_device::device_reset(); m_cdrom = m_image->get_cdrom_file(); m_media_change = false; } void atapi_cdrom_device::process_buffer() { if(m_cdrom != m_image->get_cdrom_file()) { m_media_change = true; SetDevice(m_image->get_cdrom_file()); } atapi_hle_device::process_buffer(); } void atapi_cdrom_device::perform_diagnostic() { m_error = IDE_ERROR_DIAGNOSTIC_PASSED; } void atapi_cdrom_device::identify_packet_device() { } void atapi_cdrom_device::ExecCommand() { switch(command[0]) { case T10SBC_CMD_READ_CAPACITY: case T10SBC_CMD_READ_10: case T10MMC_CMD_READ_SUB_CHANNEL: case T10MMC_CMD_READ_TOC_PMA_ATIP: case T10MMC_CMD_PLAY_AUDIO_10: case T10MMC_CMD_PLAY_AUDIO_TRACK_INDEX: case T10MMC_CMD_PAUSE_RESUME: case T10MMC_CMD_PLAY_AUDIO_12: case T10SBC_CMD_READ_12: if(!m_cdrom) { m_phase = SCSI_PHASE_STATUS; m_sense_key = SCSI_SENSE_KEY_MEDIUM_ERROR; m_sense_asc = SCSI_SENSE_ASC_MEDIUM_NOT_PRESENT; m_status_code = SCSI_STATUS_CODE_CHECK_CONDITION; m_transfer_length = 0; return; } default: if(m_media_change) { m_phase = SCSI_PHASE_STATUS; m_sense_key = SCSI_SENSE_KEY_UNIT_ATTENTION; m_sense_asc = SCSI_SENSE_ASC_NOT_READY_TO_READY_TRANSITION; m_status_code = SCSI_STATUS_CODE_CHECK_CONDITION; m_transfer_length = 0; return; } break; case T10SPC_CMD_INQUIRY: break; case T10SPC_CMD_REQUEST_SENSE: m_media_change = false; break; } t10mmc::ExecCommand(); }
30.072368
139
0.684095
rjw57
817b9e2eb1041abb61704404c4ff63a8bd19e273
26,843
cpp
C++
src/gui/app/CompareFilesDialog.cpp
IncompleteWorlds/GMAT_2020
624de54d00f43831a4d46b46703e069d5c8c92ff
[ "Apache-2.0" ]
null
null
null
src/gui/app/CompareFilesDialog.cpp
IncompleteWorlds/GMAT_2020
624de54d00f43831a4d46b46703e069d5c8c92ff
[ "Apache-2.0" ]
null
null
null
src/gui/app/CompareFilesDialog.cpp
IncompleteWorlds/GMAT_2020
624de54d00f43831a4d46b46703e069d5c8c92ff
[ "Apache-2.0" ]
null
null
null
//$Id$ //------------------------------------------------------------------------------ // CompareFilesDialog //------------------------------------------------------------------------------ // GMAT: General Mission Analysis Tool // // Copyright (c) 2002 - 2020 United States Government as represented by the // Administrator of the National Aeronautics and Space Administration. // All Other Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // You may not use this file except in compliance with the License. // You may obtain a copy of the License at: // http://www.apache.org/licenses/LICENSE-2.0. // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either // express or implied. See the License for the specific language // governing permissions and limitations under the License. // // Author: Linda Jun // Created: 2005/12/22 // /** * Shows dialog where various run script folder option can be selected. */ //------------------------------------------------------------------------------ #include "CompareFilesDialog.hpp" #include "GmatStaticBoxSizer.hpp" #include "FileManager.hpp" #include "MessageInterface.hpp" #include <wx/dir.h> #include <wx/filename.h> //#define DEBUG_COMPARE_FILES_DIALOG 1 //------------------------------------------------------------------------------ // event tables and other macros for wxWindows //------------------------------------------------------------------------------ BEGIN_EVENT_TABLE(CompareFilesDialog, GmatDialog) EVT_BUTTON(ID_BUTTON_OK, GmatDialog::OnOK) EVT_BUTTON(ID_BUTTON_CANCEL, GmatDialog::OnCancel) EVT_BUTTON(ID_BUTTON, CompareFilesDialog::OnButtonClick) EVT_CHECKBOX(ID_CHECKBOX, CompareFilesDialog::OnCheckBoxChange) EVT_COMBOBOX(ID_COMBOBOX, CompareFilesDialog::OnComboBoxChange) EVT_TEXT_ENTER(ID_TEXTCTRL, CompareFilesDialog::OnTextEnterPress) EVT_RADIOBOX(ID_RADIOBOX, CompareFilesDialog::OnRadioButtonClick) END_EVENT_TABLE() //------------------------------------------------------------------------------ // CompareFilesDialog(wxWindow *parent) //------------------------------------------------------------------------------ CompareFilesDialog::CompareFilesDialog(wxWindow *parent) : GmatDialog(parent, -1, wxString(_T("CompareFilesDialog"))) { mCompareFiles = false; mSkipBlankLinesForTextCompare = false; mSaveCompareResults = false; mHasDir1 = false; mHasDir2 = false; mHasDir3 = false; mNumFilesToCompare = 0; mNumDirsToCompare = 1; mTolerance = 1.0e-6; mCompareOption = 1; mBaseDirectory = ""; mBaseString = ""; // we can have up to 3 directories to compare mCompareStrings.Add(""); mCompareStrings.Add(""); mCompareStrings.Add(""); mCompareDirs.Add(""); mCompareDirs.Add(""); mCompareDirs.Add(""); Create(); ShowData(); } //------------------------------------------------------------------------------ // ~CompareFilesDialog() //------------------------------------------------------------------------------ CompareFilesDialog::~CompareFilesDialog() { } //------------------------------------------------------------------------------ // virtual void Create() //------------------------------------------------------------------------------ void CompareFilesDialog::Create() { #if DEBUG_COMPARE_FILES_DIALOG MessageInterface::ShowMessage("CompareFilesDialog::Create() entered.\n"); #endif int bsize = 2; wxArrayString options; options.Add("Compare lines as text"); options.Add("Compare lines numerically (skips strings and blank lines)"); options.Add("Compare data columns numerically"); //------------------------------------------------------ // compare type //------------------------------------------------------ mCompareOptionRadioBox = new wxRadioBox(this, ID_RADIOBOX, wxT("Compare Option"), wxDefaultPosition, wxDefaultSize, options, 1, wxRA_SPECIFY_COLS); //------------------------------------------------------ // compare directory //------------------------------------------------------ mBaseDirTextCtrl = new wxTextCtrl(this, ID_TEXTCTRL, wxT(""), wxDefaultPosition, wxSize(400,-1), 0); mBaseDirButton = new wxButton(this, ID_BUTTON, wxT("Browse"), wxDefaultPosition, wxDefaultSize, 0); wxStaticText *baseStringLabel = new wxStaticText(this, ID_TEXT, wxT("Compare Files Contain:"), wxDefaultPosition, wxDefaultSize, 0); mBaseStrTextCtrl = new wxTextCtrl(this, ID_TEXTCTRL, mBaseString, wxDefaultPosition, wxDefaultSize, wxTE_PROCESS_ENTER); wxStaticText *numFilesBaseDirLabel = new wxStaticText(this, ID_TEXT, wxT("Number of Files:"), wxDefaultPosition, wxDefaultSize, 0); mNumFilesInBaseDirTextCtrl = new wxTextCtrl(this, ID_TEXTCTRL, wxT("0"), wxDefaultPosition, wxDefaultSize, 0); mBaseUpdateButton = new wxButton(this, ID_BUTTON, wxT("Update"), wxDefaultPosition, wxDefaultSize, 0); wxFlexGridSizer *baseDirGridSizer = new wxFlexGridSizer(2, 0, 0); baseDirGridSizer->Add(mBaseDirTextCtrl, 0, wxALIGN_RIGHT|wxALL|wxGROW, bsize); baseDirGridSizer->Add(mBaseDirButton, 0, wxALIGN_CENTER|wxALL, bsize); wxFlexGridSizer *baseFileGridSizer = new wxFlexGridSizer(3, 0, 0); baseFileGridSizer->Add(baseStringLabel, 0, wxALIGN_LEFT|wxALL, bsize); baseFileGridSizer->Add(mBaseStrTextCtrl, 0, wxALIGN_RIGHT|wxALL|wxGROW, bsize); baseFileGridSizer->Add(20, 20, 0, wxALIGN_RIGHT|wxALL|wxGROW, bsize); baseFileGridSizer->Add(numFilesBaseDirLabel, 0, wxALIGN_LEFT|wxALL, bsize); baseFileGridSizer->Add(mNumFilesInBaseDirTextCtrl, 0, wxALIGN_RIGHT|wxALL|wxGROW, bsize); baseFileGridSizer->Add(mBaseUpdateButton, 0, wxALIGN_LEFT|wxALL, bsize); GmatStaticBoxSizer *baseDirSizer = new GmatStaticBoxSizer(wxVERTICAL, this, "Base Directory"); baseDirSizer->Add(baseDirGridSizer, 0, wxALIGN_RIGHT|wxALL|wxGROW, bsize); baseDirSizer->Add(baseFileGridSizer, 0, wxALIGN_RIGHT|wxALL|wxGROW, bsize); //------------------------------------------------------ // compare file names //------------------------------------------------------ wxString dirArray[] = {"Directory1", "Directory2", "Directory3"}; mCompareDirsComboBox = new wxComboBox(this, ID_COMBOBOX, wxT("Compare Directories"), wxDefaultPosition, wxDefaultSize, 3, dirArray, wxCB_READONLY); mCompareDirTextCtrl = new wxTextCtrl(this, ID_TEXTCTRL, wxT(""), wxDefaultPosition, wxSize(400,-1), 0); mCompareDirButton = new wxButton(this, ID_BUTTON, wxT("Browse"), wxDefaultPosition, wxDefaultSize, 0); wxStaticText *compareStringLabel = new wxStaticText(this, ID_TEXT, wxT("Compare Files Contain:"), wxDefaultPosition, wxDefaultSize, 0); mCompareStrTextCtrl = new wxTextCtrl(this, ID_TEXTCTRL, mCompareStrings[0], wxDefaultPosition, wxDefaultSize, wxTE_PROCESS_ENTER); wxStaticText *numFilesInCompareDirLabel = new wxStaticText(this, ID_TEXT, wxT("Number of Files:"), wxDefaultPosition, wxDefaultSize, 0); mNumFilesInCompareDirTextCtrl = new wxTextCtrl(this, ID_TEXTCTRL, wxT("0"), wxDefaultPosition, wxDefaultSize, 0); mCompareUpdateButton = new wxButton(this, ID_BUTTON, wxT("Update"), wxDefaultPosition, wxDefaultSize, 0); //---------- sizer wxFlexGridSizer *compareDirGridSizer = new wxFlexGridSizer(2, 0, 0); compareDirGridSizer->Add(mCompareDirsComboBox, 0, wxALIGN_LEFT|wxALL, bsize); compareDirGridSizer->Add(20, 20, 0, wxALIGN_LEFT|wxALL, bsize); compareDirGridSizer->Add(mCompareDirTextCtrl, 0, wxALIGN_LEFT|wxALL, bsize); compareDirGridSizer->Add(mCompareDirButton, 0, wxALIGN_LEFT|wxALL, bsize); wxFlexGridSizer *compareFileGridSizer = new wxFlexGridSizer(3, 0, 0); compareFileGridSizer->Add(compareStringLabel, 0, wxALIGN_LEFT|wxALL, bsize); compareFileGridSizer->Add(mCompareStrTextCtrl, 0, wxALIGN_RIGHT|wxALL|wxGROW, bsize); compareFileGridSizer->Add(20, 20, 0, wxALIGN_RIGHT|wxALL|wxGROW, bsize); compareFileGridSizer->Add(numFilesInCompareDirLabel, 0, wxALIGN_RIGHT|wxALL|wxGROW, bsize); compareFileGridSizer->Add(mNumFilesInCompareDirTextCtrl, 0, wxALIGN_RIGHT|wxALL|wxGROW, bsize); compareFileGridSizer->Add(mCompareUpdateButton, 0, wxALIGN_LEFT|wxALL, bsize); GmatStaticBoxSizer *compareDirsSizer = new GmatStaticBoxSizer(wxVERTICAL, this, "Compare Directories"); compareDirsSizer->Add(compareDirGridSizer, 0, wxALIGN_LEFT|wxALL|wxGROW, bsize); compareDirsSizer->Add(compareFileGridSizer, 0, wxALIGN_LEFT|wxALL|wxGROW, bsize); //------------------------------------------------------ // compare results //------------------------------------------------------ wxStaticText *numDirsToCompareLabel = new wxStaticText(this, ID_TEXT, wxT("Number of Directories to Compare:"), wxDefaultPosition, wxDefaultSize, 0); mNumDirsToCompareTextCtrl = new wxTextCtrl(this, ID_TEXTCTRL, wxT("0"), wxDefaultPosition, wxDefaultSize, 0); wxStaticText *numFilesToCompareLabel = new wxStaticText(this, ID_TEXT, wxT("Number of Files to Compare:"), wxDefaultPosition, wxDefaultSize, 0); mNumFilesToCompareTextCtrl = new wxTextCtrl(this, ID_TEXTCTRL, wxT("0"), wxDefaultPosition, wxDefaultSize, 0); wxStaticText *toleranceLabel = new wxStaticText(this, ID_TEXT, wxT("Tolerance to be Used in Flagging:"), wxDefaultPosition, wxDefaultSize, 0); mToleranceTextCtrl = new wxTextCtrl(this, ID_TEXTCTRL, ToWxString(mTolerance), wxDefaultPosition, wxDefaultSize, 0); //---------- sizer wxFlexGridSizer *numFilesGridSizer = new wxFlexGridSizer(2, 0, 0); numFilesGridSizer->Add(numDirsToCompareLabel, 0, wxALIGN_LEFT|wxALL, bsize); numFilesGridSizer->Add(mNumDirsToCompareTextCtrl, 0, wxALIGN_RIGHT|wxALL|wxGROW, bsize); numFilesGridSizer->Add(numFilesToCompareLabel, 0, wxALIGN_LEFT|wxALL, bsize); numFilesGridSizer->Add(mNumFilesToCompareTextCtrl, 0, wxALIGN_RIGHT|wxALL|wxGROW, bsize); numFilesGridSizer->Add(toleranceLabel, 0, wxALIGN_LEFT|wxALL, bsize); numFilesGridSizer->Add(mToleranceTextCtrl, 0, wxALIGN_RIGHT|wxALL|wxGROW, bsize); // Inner parentheses were added below to turn off warnings // need to verify intent was not "if (!(mCompareOption == 1)" // the concern is that since mCompareOption isn't Bool the # of possible // options is unknown. As written, this is true only if mCompareOption is 0, // because if mCompareOption !=0 then !nCompareOption == 0. //if (!(mCompareOption) == 1) //warnings persisted even with parentheses around mCompareOption, so rewrote // using "!=" if (mCompareOption != 1) { numFilesGridSizer->Hide(toleranceLabel); numFilesGridSizer->Hide(mToleranceTextCtrl); } mSkipBlankLinesCheckBox = new wxCheckBox(this, ID_CHECKBOX, wxT("Skip Blank Lines for Text Compare"), wxDefaultPosition, wxDefaultSize, 0); mSaveResultCheckBox = new wxCheckBox(this, ID_CHECKBOX, wxT("Save Compare Results to File"), wxDefaultPosition, wxDefaultSize, 0); wxStaticText *saveFileLabel = new wxStaticText(this, ID_TEXT, wxT("File Name to Save:"), wxDefaultPosition, wxDefaultSize, 0); mSaveFileTextCtrl = new wxTextCtrl(this, ID_TEXTCTRL, wxT(""), wxDefaultPosition, wxSize(400,-1), 0); mSaveBrowseButton = new wxButton(this, ID_BUTTON, wxT("Browse"), wxDefaultPosition, wxDefaultSize, 0); //---------- sizer wxFlexGridSizer *saveGridSizer = new wxFlexGridSizer(2, 0, 0); saveGridSizer->Add(mSaveFileTextCtrl, 0, wxALIGN_LEFT|wxALL, bsize); saveGridSizer->Add(mSaveBrowseButton, 0, wxALIGN_CENTRE|wxALL, bsize); GmatStaticBoxSizer *compareSizer = new GmatStaticBoxSizer(wxVERTICAL, this, "Compare"); compareSizer->Add(numFilesGridSizer, 0, wxALIGN_LEFT|wxALL, bsize); compareSizer->Add(mSkipBlankLinesCheckBox, 0, wxALIGN_LEFT|wxALL, bsize); compareSizer->Add(mSaveResultCheckBox, 0, wxALIGN_LEFT|wxALL, bsize); compareSizer->Add(20, 5, 0, wxALIGN_LEFT|wxALL, bsize); compareSizer->Add(saveFileLabel, 0, wxALIGN_LEFT|wxALL, bsize); compareSizer->Add(saveGridSizer, 0, wxALIGN_LEFT|wxALL, bsize); //------------------------------------------------------ // add to page sizer //------------------------------------------------------ wxBoxSizer *pageBoxSizer = new wxBoxSizer(wxVERTICAL); pageBoxSizer->Add(mCompareOptionRadioBox, 0, wxALIGN_CENTRE|wxALL|wxGROW, bsize); pageBoxSizer->Add(baseDirSizer, 0, wxALIGN_CENTRE|wxALL|wxGROW, bsize); pageBoxSizer->Add(compareDirsSizer, 0, wxALIGN_CENTRE|wxALL|wxGROW, bsize); pageBoxSizer->Add(compareSizer, 0, wxALIGN_CENTRE|wxALL|wxGROW, bsize); theMiddleSizer->Add(pageBoxSizer, 0, wxALIGN_CENTRE|wxALL, bsize); } //------------------------------------------------------------------------------ // virtual void LoadData() //------------------------------------------------------------------------------ void CompareFilesDialog::LoadData() { #ifdef DEBUG_COMPARE_FILES_DIALOG MessageInterface::ShowMessage ("CompareFilesDialog::LoadData() entered, mNumFilesToCompare = %d\n", mNumFilesToCompare); #endif wxString str; str.Printf("%d", mNumFilesToCompare); mNumFilesToCompareTextCtrl->SetValue(str); str.Printf("%d", mNumDirsToCompare); mNumDirsToCompareTextCtrl->SetValue(str); str.Printf("%g", mTolerance); mToleranceTextCtrl->SetValue(str); FileManager *fm = FileManager::Instance(); mBaseDirectory = fm->GetFullPathname(FileManager::OUTPUT_PATH).c_str(); mCompareDirs[0] = fm->GetFullPathname(FileManager::OUTPUT_PATH).c_str(); mCompareDirs[1] = fm->GetFullPathname(FileManager::OUTPUT_PATH).c_str(); mCompareDirs[2] = fm->GetFullPathname(FileManager::OUTPUT_PATH).c_str(); mCompareDirsComboBox->SetSelection(0); mSaveFileName = mBaseDirectory + "CompareNumericResults.out"; mBaseDirTextCtrl->SetValue(mBaseDirectory); mCompareDirTextCtrl->SetValue(mCompareDirs[0]); mSaveFileTextCtrl->SetValue(mSaveFileName); // update file info in directory 1 and 2 UpdateFileInfo(0, true); UpdateFileInfo(1, false); mSaveResultCheckBox->Enable(); mSaveFileTextCtrl->Disable(); mSaveBrowseButton->Disable(); theOkButton->Enable(); #ifdef DEBUG_COMPARE_FILES_DIALOG MessageInterface::ShowMessage ("CompareFilesDialog::LoadData() leaving, mNumFilesToCompare = %d\n", mNumFilesToCompare); #endif } //------------------------------------------------------------------------------ // virtual void SaveData() //------------------------------------------------------------------------------ void CompareFilesDialog::SaveData() { long longNum; canClose = true; if (!mNumFilesToCompareTextCtrl->GetValue().ToLong(&longNum)) { wxMessageBox("Invalid number of scripts to run entered."); canClose = false; return; } mNumFilesToCompare = longNum; if (!mNumDirsToCompareTextCtrl->GetValue().ToLong(&longNum)) { wxMessageBox("Invalid number of scripts to run entered."); canClose = false; return; } mNumDirsToCompare = longNum; if (!mToleranceTextCtrl->GetValue().ToDouble(&mTolerance)) { wxMessageBox("Invalid tolerance entered."); canClose = false; return; } mSaveFileName = mSaveFileTextCtrl->GetValue(); mCompareFiles = true; if (mNumFilesToCompare <= 0) { wxMessageBox("There are no specific report files to compare.\n" "Please check file names to compare.", "GMAT Warning"); canClose = false; mCompareFiles = false; } mSkipBlankLinesForTextCompare = mSkipBlankLinesCheckBox->GetValue(); mSaveCompareResults = mSaveResultCheckBox->GetValue(); #if DEBUG_COMPARE_FILES_DIALOG MessageInterface::ShowMessage ("CompareFilesDialog::SaveData() mNumFilesToCompare=%d, " "mCompareFiles=%d, mTolerance=%e\n mBaseDirectory=%s, mCompareDirs[0]=%s, " "mBaseString=%s, mCompareStrings[0]=%s\n", mNumFilesToCompare, mCompareFiles, mTolerance, mBaseDirectory.WX_TO_C_STRING, mCompareDirs[0].WX_TO_C_STRING, mBaseString.WX_TO_C_STRING, mCompareStrings[0].WX_TO_C_STRING); #endif } //------------------------------------------------------------------------------ // virtual void ResetData() //------------------------------------------------------------------------------ void CompareFilesDialog::ResetData() { canClose = true; mCompareFiles = false; } //------------------------------------------------------------------------------ // void OnButtonClick(wxCommandEvent& event) //------------------------------------------------------------------------------ void CompareFilesDialog::OnButtonClick(wxCommandEvent& event) { if (event.GetEventObject() == mBaseDirButton) { wxDirDialog dialog(this, "Select a base directory", mBaseDirectory); if (dialog.ShowModal() == wxID_OK) { mBaseDirectory = dialog.GetPath(); mBaseDirTextCtrl->SetValue(mBaseDirectory); mSaveFileName = mBaseDirectory + "/CompareNumericResults.out"; mSaveFileTextCtrl->SetValue(mSaveFileName); //mSaveFileTextCtrl->SetValue(mBaseDirectory + "/CompareNumericResults.out"); UpdateFileInfo(0, true); #if DEBUG_COMPARE_FILES_DIALOG MessageInterface::ShowMessage ("CompareFilesDialog::OnButtonClick() mBaseDirectory=%s\n", mBaseDirectory.WX_TO_C_STRING); #endif } } else if (event.GetEventObject() == mCompareDirButton) { int dirIndex = mCompareDirsComboBox->GetSelection(); wxDirDialog dialog(this, "Select a compare dierctory", mCompareDirs[dirIndex]); if (dialog.ShowModal() == wxID_OK) { if (dirIndex == 0) mHasDir1 = true; else if (dirIndex == 1) mHasDir2 = true; else if (dirIndex == 2) mHasDir3 = true; mCompareDirs[dirIndex] = dialog.GetPath(); mCompareDirTextCtrl->SetValue(mCompareDirs[dirIndex]); UpdateFileInfo(dirIndex, false); // update number of directories to compare int numDirs = 0; if (mHasDir1) numDirs++; if (mHasDir2) numDirs++; if (mHasDir3) numDirs++; mNumDirsToCompare = numDirs; wxString str; str.Printf("%d", mNumDirsToCompare); mNumDirsToCompareTextCtrl->SetValue(str); #if DEBUG_COMPARE_FILES_DIALOG MessageInterface::ShowMessage ("CompareFilesDialog::OnButtonClick() mCompareDirs[%d]=%s\n", dirIndex, mCompareDirs[dirIndex].WX_TO_C_STRING); #endif } } else if (event.GetEventObject() == mBaseUpdateButton) { // update file info in base directory mBaseDirectory = mBaseDirTextCtrl->GetValue(); mBaseString = mBaseStrTextCtrl->GetValue(); mSaveFileName = mBaseDirectory + "/CompareNumericResults.out"; mSaveFileTextCtrl->SetValue(mSaveFileName); UpdateFileInfo(0, true); } else if (event.GetEventObject() == mCompareUpdateButton) { int dirIndex = mCompareDirsComboBox->GetSelection(); // update file info in compare directory mCompareDirs[dirIndex] = mCompareDirTextCtrl->GetValue(); mCompareStrings[dirIndex] = mCompareStrTextCtrl->GetValue(); UpdateFileInfo(dirIndex, false); } else if (event.GetEventObject() == mSaveBrowseButton) { wxString filename = wxFileSelector("Choose a file to save", mBaseDirectory, "", "txt", "Report files (*.report)|*.report|Text files (*.txt)|*.txt", wxFD_SAVE); //wxSAVE); if (!filename.empty()) { mSaveFileTextCtrl->SetValue(filename); #if DEBUG_COMPARE_FILES_DIALOG MessageInterface::ShowMessage ("CompareFilesDialog::OnButtonClick() savefile=%s\n", filename.WX_TO_C_STRING); #endif } } } //------------------------------------------------------------------------------ // void OnRadioButtonClick(wxCommandEvent& event) //------------------------------------------------------------------------------ void CompareFilesDialog::OnRadioButtonClick(wxCommandEvent& event) { mCompareOption = mCompareOptionRadioBox->GetSelection() + 1; } //------------------------------------------------------------------------------ // void OnCheckBoxChange(wxCommandEvent& event) //------------------------------------------------------------------------------ void CompareFilesDialog::OnCheckBoxChange(wxCommandEvent& event) { if (mSaveResultCheckBox->IsChecked()) { mSaveFileTextCtrl->Enable(); mSaveBrowseButton->Enable(); } else { mSaveFileTextCtrl->Disable(); mSaveBrowseButton->Disable(); } } // void OnComboBoxChange(wxCommandEvent& event) //------------------------------------------------------------------------------ void CompareFilesDialog::OnComboBoxChange(wxCommandEvent& event) { if (event.GetEventObject() == mCompareDirsComboBox) { int currDir = mCompareDirsComboBox->GetSelection(); mCompareDirTextCtrl->SetValue(mCompareDirs[currDir]); } } //------------------------------------------------------------------------------ // void OnTextEnterPress(wxCommandEvent& event) //------------------------------------------------------------------------------ void CompareFilesDialog::OnTextEnterPress(wxCommandEvent& event) { MessageInterface::ShowMessage("==> CompareFilesDialog::OnTextEnterPress() entered\n"); wxObject *eventObj = event.GetEventObject(); int dirIndex = mCompareDirsComboBox->GetSelection(); if (eventObj == mBaseDirTextCtrl) { mBaseDirectory = mBaseDirTextCtrl->GetValue(); mSaveFileName = mBaseDirectory + "/CompareNumericResults.out"; mSaveFileTextCtrl->SetValue(mSaveFileName); UpdateFileInfo(0, true); } else if (eventObj == mCompareDirTextCtrl) { mCompareDirs[dirIndex] = mCompareDirTextCtrl->GetValue(); UpdateFileInfo(0, false); } else if (eventObj == mBaseStrTextCtrl) { mBaseString = mBaseStrTextCtrl->GetValue(); UpdateFileInfo(0, true); } else if (eventObj == mCompareStrTextCtrl) { mCompareStrings[dirIndex] = mCompareStrTextCtrl->GetValue(); UpdateFileInfo(dirIndex, false); } } //------------------------------------------------------------------------------ // void UpdateFileInfo(Integer dir) //------------------------------------------------------------------------------ void CompareFilesDialog::UpdateFileInfo(Integer dir, bool isBaseDir) { #ifdef DEBUG_COMPARE_FILES_DIALOG MessageInterface::ShowMessage ("CompareFilesDialog::UpdateFileInfo() entered, dir = %d, isBaseDir = %d\n", dir, isBaseDir); #endif if (isBaseDir) { mFileNamesInBaseDir = GetFilenamesContain(mBaseDirectory, mBaseString); mNumFilesInBaseDir = mFileNamesInBaseDir.GetCount(); mNumFilesInBaseDirTextCtrl->SetValue(""); *mNumFilesInBaseDirTextCtrl << mNumFilesInBaseDir; } else { mFileNamesInCompareDir = GetFilenamesContain(mCompareDirs[dir], mCompareStrings[dir]); mNumFilesInCompareDir = mFileNamesInCompareDir.GetCount(); mNumFilesInCompareDirTextCtrl->SetValue(""); *mNumFilesInCompareDirTextCtrl << mNumFilesInCompareDir; } // number of files to compare mNumFilesToCompareTextCtrl->SetValue(""); if (mNumFilesInBaseDir == 0 || mNumFilesInCompareDir == 0) *mNumFilesToCompareTextCtrl << 0; else *mNumFilesToCompareTextCtrl << mNumFilesInBaseDir; mNumFilesToCompare = mNumFilesInBaseDir; #ifdef DEBUG_COMPARE_FILES_DIALOG MessageInterface::ShowMessage ("CompareFilesDialog::UpdateFileInfo() leaving, mNumFilesInBaseDir = %d, " "mNumFilesToCompare = %d\n", mNumFilesInBaseDir, mNumFilesToCompare); #endif } //------------------------------------------------------------------------------ // wxArrayString GetFilenamesContain(const wxString &dirname, // const wxString &str) //------------------------------------------------------------------------------ wxArrayString CompareFilesDialog::GetFilenamesContain(const wxString &dirname, const wxString &str) { #ifdef DEBUG_COMPARE_FILES_DIALOG MessageInterface::ShowMessage ("CompareFilesDialog::GetFilenamesContain() entered, dirname = '%s', str = '%s'\n", dirname.WX_TO_C_STRING, str.WX_TO_C_STRING); #endif wxDir dir(dirname); wxString filename; wxString filepath; wxArrayString fileNames; bool cont = dir.GetFirst(&filename); while (cont) { if (filename.Contains(".report") || filename.Contains(".txt") || filename.Contains(".data") || filename.Contains(".script") || filename.Contains(".eph") || filename.Contains(".oem") || filename.Contains(".e") || filename.Contains(".truth")) { // If not backup files // Add files ending 't' for report, txt, and script // 'a' for data, 'h' for eph and truth, 'm' for .oem, 'e' for .e if (filename.Last() == 't' || filename.Last() == 'a' || filename.Last() == 'h' || filename.Last() == 'm' || filename.Last() == 'e') { if (filename.Contains(str)) { filepath = dirname + "/" + filename; fileNames.Add(filepath); } } } cont = dir.GetNext(&filename); } #ifdef DEBUG_COMPARE_FILES_DIALOG MessageInterface::ShowMessage ("CompareFilesDialog::GetFilenamesContain() returning %d files\n", fileNames.size()); #endif return fileNames; }
37.700843
98
0.602578
IncompleteWorlds
817bbcf3063306c14fb815ca1cabf6526950eb8c
883
cpp
C++
lib/ReadWriteGraph/ReadWriteGraph.cpp
bloodycoder/dg
4d261fc688013bcc6d35284315b7d0e861f00b4b
[ "MIT" ]
null
null
null
lib/ReadWriteGraph/ReadWriteGraph.cpp
bloodycoder/dg
4d261fc688013bcc6d35284315b7d0e861f00b4b
[ "MIT" ]
null
null
null
lib/ReadWriteGraph/ReadWriteGraph.cpp
bloodycoder/dg
4d261fc688013bcc6d35284315b7d0e861f00b4b
[ "MIT" ]
null
null
null
#include <set> #include <vector> #include "dg/ReachingDefinitions/ReachingDefinitions.h" #include "dg/BBlocksBuilder.h" namespace dg { namespace dda { void ReadWriteGraph::buildBBlocks(bool dce) { assert(getRoot() && "No root node"); DBG(dda, "Building basic blocks"); BBlocksBuilder<RWBBlock> builder; _bblocks = std::move(builder.buildAndGetBlocks(getRoot())); assert(getRoot()->getBBlock() && "Root node has no BBlock"); // should we eliminate dead code? // The dead code are the nodes that have no basic block assigned // (follows from the DFS nature of the block builder algorithm) if (!dce) return; for (auto& nd : _nodes) { if (nd->getBBlock() == nullptr) { nd->isolate(); nd.reset(); } } } void ReadWriteGraph::removeUselessNodes() { } } // namespace dda } // namespace dg
22.641026
68
0.638732
bloodycoder
817da77491a5d3f35b804d3b71400ef3724f42a3
3,957
cpp
C++
src/core/features/flappybird.cpp
Metaphysical1/gamesneeze
59d31ee232bbcc80d29329e0f64ebdde599c37df
[ "MIT" ]
1,056
2020-11-17T11:49:12.000Z
2022-03-23T12:32:42.000Z
src/core/features/flappybird.cpp
dweee/gamesneeze
99f574db2617263470280125ec78afa813f27099
[ "MIT" ]
102
2021-01-15T12:05:18.000Z
2022-02-26T00:19:58.000Z
src/core/features/flappybird.cpp
dweee/gamesneeze
99f574db2617263470280125ec78afa813f27099
[ "MIT" ]
121
2020-11-18T12:08:21.000Z
2022-03-31T07:14:32.000Z
#include "features.hpp" #include <SDL2/SDL_scancode.h> #include <vector> int score; ImVec2 cursorPos; float deltaTime; bool alive = true; bool paused = false; float birdHeight; class Bird { public: void draw(ImDrawList* drawList) { drawList->AddRectFilled(ImVec2{cursorPos.x+60, cursorPos.y+(400-height)}, ImVec2{cursorPos.x+70, cursorPos.y+(400-height)+10}, ImColor(255, 255, 255, 255)); if (alive) { if (!paused) { height += velocity*deltaTime; // add velocity birdHeight = height; velocity -= 250.f*deltaTime; // gravity if (height < 50) { alive = false; } } } else { height = 300; score = 0; drawList->AddText(ImVec2{ImVec2{cursorPos.x+10, cursorPos.y+10}}, ImColor(255, 255, 255, 255), "You died, press up arrow to respawn"); } } void handleInput() { if (ImGui::IsKeyPressed(SDL_SCANCODE_UP, false) && !paused) { velocity = 140.f; alive = true; } else if (ImGui::IsKeyPressed(SDL_SCANCODE_DOWN, false) && alive) { paused = !paused; } } float velocity = 0; float height = 300; }; class Pipe { public: Pipe(float startX) { x = startX; xOriginal = startX; gapTop = (rand() % 200) + 130; gapBottom = gapTop - 65; } void draw(ImDrawList* drawList) { drawList->AddRectFilled(ImVec2{cursorPos.x+x, cursorPos.y}, ImVec2{cursorPos.x+x+40, cursorPos.y+(400-gapTop)}, ImColor(0, 65, 0, 255)); drawList->AddRectFilled(ImVec2{cursorPos.x+x, cursorPos.y+400}, ImVec2{cursorPos.x+x+40, cursorPos.y+(400-gapBottom)}, ImColor(0, 65, 0, 255)); if (alive) { if (!paused) { x -= 90.f * deltaTime; if (x < -200) { x = 400; gapTop = (rand() % 200) + 130; gapBottom = gapTop - 65; hasBirdPassed = false; } if ((x < 70) && (x > 20)) { if ((birdHeight > gapTop) || (birdHeight < gapBottom)) { alive = false; } if (!hasBirdPassed) { score++; hasBirdPassed = true; } } } } else { x = xOriginal; gapTop = (rand() % 200) + 130; gapBottom = gapTop - 65; hasBirdPassed = false; } } bool hasBirdPassed = false; float gapTop = 300, gapBottom = 235; float x; float xOriginal; }; void Features::FlappyBird::draw() { if (CONFIGBOOL("Misc>Misc>Misc>Flappy Birb")) { ImGui::Begin("Flappy Birb", nullptr, ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoCollapse | (Menu::open ? 0 : ImGuiWindowFlags_NoMouseInputs)); ImGui::Text("Flappy Birb (Score %i)", score); ImGui::Separator(); ImDrawList* drawList = ImGui::GetWindowDrawList(); deltaTime = ImGui::GetIO().DeltaTime; cursorPos = ImGui::GetCursorScreenPos(); drawList->AddRectFilled(ImVec2{cursorPos.x, cursorPos.y}, ImVec2{cursorPos.x+400, cursorPos.y+400}, ImColor(0, 0, 0, 255)); drawList->AddRectFilled(ImVec2{cursorPos.x, cursorPos.y+360}, ImVec2{cursorPos.x+400, cursorPos.y+400}, ImColor(0, 80, 0, 255)); static Bird bird; bird.handleInput(); bird.draw(drawList); static Pipe pipe(400); pipe.draw(drawList); static Pipe pipe2(550); pipe2.draw(drawList); static Pipe pipe3(700); pipe3.draw(drawList); if (paused) { drawList->AddText(ImVec2{ImVec2{cursorPos.x+10, cursorPos.y+10}}, ImColor(255, 255, 255, 255), "Paused"); } ImGui::End(); } }
31.91129
164
0.52464
Metaphysical1
817dabe08950620aba56e912f99b48bcb68eb706
4,729
cpp
C++
src/chip/16segchip.cpp
berezhko/Atanua
8c2cf22c8bc77934105c20a44a169bd024be58a9
[ "Zlib" ]
76
2015-01-04T05:35:22.000Z
2022-03-09T08:07:21.000Z
src/chip/16segchip.cpp
berezhko/Atanua
8c2cf22c8bc77934105c20a44a169bd024be58a9
[ "Zlib" ]
4
2015-03-04T14:16:23.000Z
2019-08-15T15:40:20.000Z
src/chip/16segchip.cpp
berezhko/Atanua
8c2cf22c8bc77934105c20a44a169bd024be58a9
[ "Zlib" ]
40
2015-01-09T14:21:33.000Z
2022-03-18T10:53:42.000Z
/* Atanua Real-Time Logic Simulator Copyright (c) 2008-2014 Jari Komppa This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. */ #include "atanua.h" #include "16segchip.h" #include "slidingaverage.h" SixteenSegChip::SixteenSegChip(int aColor, int aInverse) { mAvg = new SlidingAverage[17]; mInverse = aInverse; mColor = aColor & 0xffffff; set(0, 0, 3.5, 4, NULL); mPin.push_back(&mInputPin[0]); mPin.push_back(&mInputPin[1]); mPin.push_back(&mInputPin[2]); mPin.push_back(&mInputPin[3]); mPin.push_back(&mInputPin[4]); mPin.push_back(&mInputPin[5]); mPin.push_back(&mInputPin[6]); mPin.push_back(&mInputPin[7]); mPin.push_back(&mInputPin[8]); mPin.push_back(&mInputPin[9]); mPin.push_back(&mInputPin[10]); mPin.push_back(&mInputPin[11]); mPin.push_back(&mInputPin[12]); mPin.push_back(&mInputPin[13]); mPin.push_back(&mInputPin[14]); mPin.push_back(&mInputPin[15]); mPin.push_back(&mInputPin[16]); int i; for (i = 0; i < 17; i++) mInputPin[i].mReadOnly = 1; float ypos = 0.1; float step = 0.42; mInputPin[0].set(0.03,ypos,this,"Pin 1: A1"); ypos += step; mInputPin[1].set(0.03,ypos,this,"Pin 2: A2"); ypos += step; mInputPin[2].set(0.03,ypos,this,"Pin 3: J"); ypos += step; mInputPin[3].set(0.03,ypos,this,"Pin 4: H"); ypos += step; mInputPin[4].set(0.03,ypos,this,"Pin 5: F"); ypos += step; mInputPin[5].set(0.03,ypos,this,"Pin 6: E"); ypos += step; mInputPin[6].set(0.03,ypos,this,"Pin 7: N"); ypos += step; mInputPin[7].set(0.03,ypos,this,"Pin 8: D1"); ypos += step; mInputPin[8].set(0.03,ypos,this,"Pin 9: D2"); ypos += step; ypos -= step; ypos -= step; mInputPin[9].set(2.95,ypos,this,"Pin 11: K"); ypos -= step; mInputPin[10].set(2.95,ypos,this,"Pin 12: B"); ypos -= step; mInputPin[11].set(2.95,ypos,this,"Pin 13: G2"); ypos -= step; mInputPin[12].set(2.95,ypos,this,"Pin 14: G1"); ypos -= step; mInputPin[13].set(2.95,ypos,this,"Pin 15: C"); ypos -= step; mInputPin[14].set(2.95,ypos,this,"Pin 16: L"); ypos -= step; mInputPin[15].set(2.95,ypos,this,"Pin 17: M"); ypos -= step; mInputPin[16].set(2.95,ypos,this,"Pin 18: DP"); ypos -= step; mTexture[0] = load_texture("data/16seg_base.png"); mTexture[1] = load_texture("data/16seg_a1.png"); mTexture[2] = load_texture("data/16seg_a2.png"); mTexture[3] = load_texture("data/16seg_j.png"); mTexture[4] = load_texture("data/16seg_h.png"); mTexture[5] = load_texture("data/16seg_f.png"); mTexture[6] = load_texture("data/16seg_e.png"); mTexture[7] = load_texture("data/16seg_n.png"); mTexture[8] = load_texture("data/16seg_d1.png"); mTexture[9] = load_texture("data/16seg_d2.png"); mTexture[10] = load_texture("data/16seg_k.png"); mTexture[11] = load_texture("data/16seg_b.png"); mTexture[12] = load_texture("data/16seg_g1.png"); mTexture[13] = load_texture("data/16seg_g2.png"); mTexture[14] = load_texture("data/16seg_c.png"); mTexture[15] = load_texture("data/16seg_l.png"); mTexture[16] = load_texture("data/16seg_m.png"); mTexture[17] = load_texture("data/16seg_dp.png"); } SixteenSegChip::~SixteenSegChip() { delete[] mAvg; } void SixteenSegChip::render(int aChipId) { drawtexturedrect(mTexture[0], mX-0.25, mY, mW+0.5, mH, 0xffffffff); glBlendFunc(GL_ONE,GL_SRC_ALPHA); int i; for (i = 0; i < 17; i++) { float val = mAvg[i].getAverage(); if (val > 0) { if (val > 0.1) val = 1.0; else val *= 10; int col = ((int)(((mColor >> 0) & 0xff) * val) << 0) | ((int)(((mColor >> 8) & 0xff) * val) << 8) | ((int)(((mColor >> 16) & 0xff) * val) << 16); drawtexturedrect(mTexture[i+1], mX-0.25, mY, mW+0.5, mH, 0xff000000 | col); } } glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA); } void SixteenSegChip::update(float aTick) { int i; for (i = 0; i < 17; i++) { mAvg[i].setValue(mInputPin[i].mNet && ((mInputPin[i].mNet->mState == NETSTATE_HIGH) ^ (!!mInverse))); } mDirty = 1; }
34.518248
109
0.664411
berezhko
817dcad1853d2128a15890b29ec54d9067fdba99
2,392
cpp
C++
LinearList/LinkedList.cpp
FrostyBonny/DS
63f951a09a3e67ef89ffc2db4e4780decea2bcef
[ "MIT" ]
2
2019-07-16T08:23:47.000Z
2021-06-26T13:43:10.000Z
LinearList/LinkedList.cpp
FrostyBonny/DS
63f951a09a3e67ef89ffc2db4e4780decea2bcef
[ "MIT" ]
null
null
null
LinearList/LinkedList.cpp
FrostyBonny/DS
63f951a09a3e67ef89ffc2db4e4780decea2bcef
[ "MIT" ]
null
null
null
#include<iostream> #include<stdlib.h> using namespace std; // 单链表的操作 typedef struct LinkNode{ int data; struct LinkNode *next; }LinkNode; // headermake void creat(LinkNode *L){ LinkNode *node; for(int i = 0;i < 10;i++){ node = (LinkNode *)malloc(sizeof(LinkNode)); node->data = rand()%13; node->next = L->next; L->next = node; } // return L; } void PrintOut(LinkNode *L){ int time = 1; while(L->next != NULL){ if(time > 20) return; cout<<L->next->data<<" "; L = L->next; time ++; } cout<<endl; } //第一个为标准,前面比他小,后面比他大。practice 5 void sortA(LinkNode *L){ int time = 1; LinkNode *s = L->next; LinkNode *p = s->next; LinkNode *pre; cout<<s->data<<endl; s->next = NULL; LinkNode *qre = s; while(p != NULL){ if(time > 30) return; time++; if(p->data < s->data){ pre = p->next; p->next = L->next; L->next = p; p = pre; }else if(p->data > s->data){ pre = p->next; p->next = s->next; s->next = p; p = pre; } } } //practice 6 caculate the last site element int func_6(LinkNode *L,int k){ LinkNode *p,*q; p = L->next; q = L->next; while(k > 1&&q->next != NULL){ q = q->next; k--; } if(q->next == NULL){ cout<<0<<endl; return 0; } while(q->next != NULL){ q = q->next; p = p->next; } cout<<p->data<<endl; return 1; } // reversed way 1 void func_7(LinkNode *L){ LinkNode *p = L->next; LinkNode *q; L->next = NULL; while(p != NULL){ q = p->next; p->next = L->next; L->next = p; p = q; } } // reversede way 2 void func_8(LinkNode *L){ LinkNode *p,*q,*r; p = L->next; q = p->next; p->next = NULL; while(q->next != NULL){ r = q->next; q->next = p; p = q; q = r; } q->next = p; L->next = q; } int main(){ LinkNode *L; L = (LinkNode *)malloc(sizeof(LinkNode)); L->next = NULL; creat(L); PrintOut(L); //practice 5 //sortA(L); //PrintOut(L); //pracetice 6 //func_6(L,4); //reversed without other space //func_7(L); func_8(L); PrintOut(L); return 0; }
18.4
52
0.460284
FrostyBonny
8180eaa3530bf717aa9c2fc830ff699b322527d2
9,594
cpp
C++
Day23/main.cpp
baldwinmatt/AoC-2021
4a7f18f6364715f6e61127aba175db6fec6e6b13
[ "Apache-2.0" ]
4
2021-12-06T17:14:00.000Z
2021-12-10T06:29:35.000Z
Day23/main.cpp
baldwinmatt/AoC-2021
4a7f18f6364715f6e61127aba175db6fec6e6b13
[ "Apache-2.0" ]
null
null
null
Day23/main.cpp
baldwinmatt/AoC-2021
4a7f18f6364715f6e61127aba175db6fec6e6b13
[ "Apache-2.0" ]
null
null
null
#include "aoc21/helpers.h" #include <array> #include <algorithm> #include <list> #include <map> #include <set> #include <vector> namespace { constexpr int RoomCount = 4; constexpr int RoomDepth = 2; constexpr int HallwaySize = 4 + (RoomCount * 2) - 1; using Hallway = std::array<char, HallwaySize>; using Room = std::string; using Rooms = std::array<Room, RoomCount>; using CharIntMap = std::map<char, int>; CharIntMap EnergyCost = { {'A', 1 }, { 'B', 10 }, { 'C', 100 }, { 'D', 1000 } }; CharIntMap RoomAssignments = { { 'A', 0 }, { 'B', 1 }, { 'C', 2 }, { 'D', 3 } }; const auto IsFish = [](const char f) { return f >= 'A' && f <= 'D'; }; #if !defined (NDEBUG) const auto IsRoom = [](const int room) { return room >= 0 && room < RoomCount; }; #endif const auto TargetRoom = [](const char f) { assert(IsFish(f)); return f - 'A'; }; class MapState { public: int energy; int roomDepth; Hallway hallway; Rooms rooms; std::vector<int>doorways; MapState(int depth) : energy(0) , roomDepth(depth) { for (auto& c : hallway) { c = '.'; } } MapState() : MapState(RoomDepth) { } void insertFish(const std::vector<std::string> fish) { int i = 0; for (auto& r : rooms) { std::string new_r(&r[0], 1); new_r += fish[i++]; new_r += (r.substr(1)); r = new_r; } roomDepth = rooms[0].size(); } std::string hash() const { std::string s; for (const auto&c : hallway) { s.append(&c, 1); } for (const auto& r : rooms) { s.append(",", 1); s.append(r); } return s; } bool isDesiredRoom(char fish, int room) const { assert(IsFish(fish)); assert(IsRoom(room)); return RoomAssignments[fish] == room; } bool isRoomFinal(int room) const { assert(IsRoom(room)); if (rooms[room].size() < static_cast<size_t>(roomDepth)) { return false; } for (const auto& f : rooms[room]) { if (!isDesiredRoom(f, room)) { return false; } } return true; } bool final() const { for (int i = 0; i < RoomCount; i++) { if (!isRoomFinal(i)) { return false; } } return true; } bool isDoorway(const int p) const { return std::find(doorways.begin(), doorways.end(), p) != doorways.end(); } int getRoom(const int p) const { for (size_t i = 0; i < doorways.size(); i++) { if (doorways[i] == p) { return i; } } return -1; } MapState move(int from, int to) { MapState next(*this); auto fish = next.hallway[from]; int steps = 0; const int from_room = getRoom(from); const int to_room = getRoom(to); if (from_room != -1) { fish = next.rooms[from_room].front(); // remove the first element from the room next.rooms[from_room].erase(0, 1); // steps to get out of room steps += (next.roomDepth - next.rooms[from_room].size()); } else { next.hallway[from] = '.'; } // steps between spaces steps += ::abs(to - from); if (to_room != -1) { // steps to emplace in the room steps += (next.roomDepth - next.rooms[to_room].size()); next.rooms[to_room] = fish + next.rooms[to_room]; } else { next.hallway[to] = fish; } next.energy += steps * EnergyCost[fish]; return next; } bool isHallwayClear(const int from, const int to) const { assert(std::min(from, to) == from); assert(std::max(from, to) == to); for (int k = from; k < to; k++) { if (isDoorway(k)) { // nothing can be directly above a room continue; } // if a hallway spot is occupied, no bueno if (hallway[k] != '.') { return false; } } return true; } bool isTargetRoomClear(const int to) const { assert(IsRoom(to)); if (rooms[to].size() == static_cast<size_t>(roomDepth)) { // room is full return false; } for (const auto& c : rooms[to]) { // room has non-correct occupant if (!isDesiredRoom(c, to)) { return false; } } return true; } bool canMoveToHall(const int from, const int to) const { assert(IsRoom(from)); assert(to >= 0 && to < HallwaySize); const int door_from = doorways[from]; const int i = std::min(door_from, to); const int j = std::max(door_from, to); if (isDoorway(to)) { return false; } return isHallwayClear(i, j); } bool canMoveToRoom(const int from, const int to) const { assert(IsRoom(from)); assert(IsRoom(to)); const int door_from = doorways[from]; const int door_to = doorways[to]; const int i = std::min(door_from, door_to); const int j = std::max(door_from, door_to); return isTargetRoomClear(to) && isHallwayClear(i, j); } bool canMoveFromHall(const int from, const int to) const { assert(from >= 0 && from < HallwaySize); assert(IsRoom(to)); const int door_to = doorways[to]; const int i = std::min(from, door_to); const int j = std::max(from, door_to); return isTargetRoomClear(to) && isHallwayClear(i + 1, j); } bool valid() const { int fish = 0; for (const auto& r : rooms) { fish += r.size(); if (r.size() > static_cast<size_t>(roomDepth)) { return false; } } for (const auto& c : hallway) { fish += IsFish(c); } return fish == roomDepth * RoomCount; } friend std::ostream& operator<<(std::ostream& os, const MapState& m) { os << aoc::cls; os << "#"; for (size_t i = 0; i < m.hallway.size(); i++) { os << "#"; } os << "#"; os << std::endl; os << "#"; for (const auto& c : m.hallway) { os << c; } os << "#"; os << std::endl; os << "#"; for (size_t i = 0; i < m.hallway.size(); i++) { if (m.isDoorway(i)) { os << '.'; } else { os << "#"; } } os << "#"; return os; } }; struct HeapComparator { bool operator()(const MapState& lhs, const MapState& rhs) { return lhs.energy > rhs.energy; } }; using StateList = std::vector<MapState>; const auto HeapPop = [](auto& heap) { auto s = heap.front(); std::pop_heap(heap.begin(), heap.end(), HeapComparator()); heap.pop_back(); return s; }; const auto HeapPush = [](auto& heap, auto& s) { heap.emplace_back(s); std::push_heap(heap.begin(), heap.end(), HeapComparator()); }; int solve(MapState map) { aoc::AutoTimer __t; // Maintain a heap of states StateList sq; sq.push_back(map); std::make_heap(sq.begin(), sq.end(), HeapComparator()); // Maintain a list of visited states, so we can quickly eliminate them from our A* int result = INT_MAX; std::set<std::string> seen; while (result == INT_MAX && !sq.empty()) { auto s = HeapPop(sq); const auto r = seen.emplace(s.hash()); if (!r.second) { continue; } if (s.final()) { result = s.energy; break; } for (int i = 0; i < RoomCount; i++) { if (!s.isRoomFinal(i)) { const auto fish = s.rooms[i].front(); if (!IsFish(fish)) { continue; } const auto t = TargetRoom(fish); if (s.canMoveToRoom(i, t)) { const auto next = s.move(s.doorways[i], s.doorways[t]); assert(next.valid()); HeapPush(sq, next); } } for (int j = 0; j < HallwaySize; j++) { const auto fish = s.rooms[i].front(); if (!IsFish(fish)) { continue; } const auto tf = s.hallway[j]; if (IsFish(tf)) { continue; } if (s.canMoveToHall(i, j)) { const auto next = s.move(s.doorways[i], j); assert(next.valid()); HeapPush(sq, next); } } } for (int j = 0; j < HallwaySize; j++) { const char fish = s.hallway[j]; if (!IsFish(fish)) { continue; } const auto t = TargetRoom(fish); if (s.canMoveFromHall(j, t)) { const auto next = s.move(j, s.doorways[t]); assert(next.valid()); HeapPush(sq, next); } } } return result; } }; int main(int argc, char** argv) { aoc::AutoTimer t; auto f = aoc::open_argv_1(argc, argv); MapState map; std::string line; while (aoc::getline(f, line)) { constexpr int MinLineSize = 2 + (RoomCount * 2); constexpr int RoomOffset = 3; assert(line.size() > RoomOffset); const char c = line[RoomOffset]; assert(c == '#' || c == '.' || (c >= 'A' && c <= 'D')); if (c < 'A' || c > 'D') { continue; } assert(line.size() > MinLineSize); int room = 0; for (int i = RoomOffset; i < MinLineSize; i += 2) { map.rooms[room].push_back(line[i]); map.doorways.push_back(i - 1); room++; } } f.close(); const auto part1 = solve(map); aoc::print_result(1, part1); map.insertFish({ "DD", "CB", "BA", "AC" }); const auto part2 = solve(map); aoc::print_result(2, part2); return 0; }
23.747525
86
0.512508
baldwinmatt
81812d2db6128c0a250e57b5bbb7d8b3b2d7f689
7,181
cpp
C++
source/models/bundle.cpp
wilsonfonseca/iota.lib.cpp
c49791b8e4f1499dc652fb84dedb016e5f42cdf4
[ "MIT" ]
null
null
null
source/models/bundle.cpp
wilsonfonseca/iota.lib.cpp
c49791b8e4f1499dc652fb84dedb016e5f42cdf4
[ "MIT" ]
null
null
null
source/models/bundle.cpp
wilsonfonseca/iota.lib.cpp
c49791b8e4f1499dc652fb84dedb016e5f42cdf4
[ "MIT" ]
null
null
null
// // MIT License // // Copyright (c) 2017-2018 Thibault Martinez and Simon Ninon // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // // #include <algorithm> #include <iota/constants.hpp> #include <iota/crypto/kerl.hpp> #include <iota/models/bundle.hpp> #include <iota/types/trinary.hpp> #include <iota/types/utils.hpp> namespace IOTA { namespace Models { Bundle::Bundle(const std::vector<Models::Transaction>& transactions) : transactions_(transactions) { if (!empty()) { hash_ = transactions_[0].getBundle(); } } const std::vector<Models::Transaction>& Bundle::getTransactions() const { return transactions_; } std::vector<Models::Transaction>& Bundle::getTransactions() { return transactions_; } std::size_t Bundle::getLength() const { return transactions_.size(); } bool Bundle::empty() const { return getLength() == 0; } const Types::Trytes& Bundle::getHash() const { return hash_; } void Bundle::setHash(const Types::Trytes& hash) { hash_ = hash; } void Bundle::addTransaction(const Transaction& transaction, int32_t signatureMessageLength) { if (empty()) { hash_ = transaction.getBundle(); } transactions_.push_back(transaction); if (signatureMessageLength > 1) { Transaction signatureTransaction = { transaction.getAddress(), 0, transaction.getTag(), transaction.getTimestamp() }; for (int i = 1; i < signatureMessageLength; i++) { transactions_.push_back(signatureTransaction); } } } void Bundle::generateHash() { Crypto::Kerl k; for (std::size_t i = 0; i < transactions_.size(); i++) { auto& trx = transactions_[i]; trx.setCurrentIndex(i); trx.setLastIndex(transactions_.size() - 1); auto value = Types::tritsToTrytes(Types::intToTrits(trx.getValue(), SeedLength)); auto timestamp = Types::tritsToTrytes(Types::intToTrits(trx.getTimestamp(), TryteAlphabetLength)); auto currentIndex = Types::tritsToTrytes(Types::intToTrits(trx.getCurrentIndex(), TryteAlphabetLength)); auto lastIndex = Types::tritsToTrytes(Types::intToTrits(trx.getLastIndex(), TryteAlphabetLength)); auto bytes = Types::trytesToBytes(trx.getAddress().toTrytes() + value + trx.getObsoleteTag().toTrytesWithPadding() + timestamp + currentIndex + lastIndex); k.absorb(bytes); } std::vector<uint8_t> hash(ByteHashLength); k.finalSqueeze(hash); hash_ = Types::bytesToTrytes(hash); } void Bundle::finalize() { bool validBundle = false; while (!validBundle) { //! generate hash generateHash(); //! check that normalized hash does not contain "13" (otherwise, this may lead to security flaw) auto normalizedHash = normalizedBundle(hash_); if (!transactions_.empty() && std::find(std::begin(normalizedHash), std::end(normalizedHash), 13 /* = M */) != std::end(normalizedHash)) { // Insecure bundle. Increment Tag and recompute bundle hash. auto tagTrits = Types::trytesToTrits(transactions_[0].getObsoleteTag().toTrytesWithPadding()); Types::incrementTrits(tagTrits); transactions_[0].setObsoleteTag(Types::tritsToTrytes(tagTrits)); } else { validBundle = true; } } //! set bundle hash for each underlying transaction for (std::size_t i = 0; i < transactions_.size(); i++) { transactions_[i].setBundle(hash_); } } void Bundle::addTrytes(const std::vector<Types::Trytes>& signatureFragments) { Types::Trytes emptySignatureFragment = Types::Utils::rightPad("", 2187, '9'); for (unsigned int i = 0; i < transactions_.size(); i++) { auto& transaction = transactions_[i]; // Fill empty signatureMessageFragment transaction.setSignatureFragments( (signatureFragments.size() <= i || signatureFragments[i].empty()) ? emptySignatureFragment : signatureFragments[i]); // Fill empty trunkTransaction transaction.setTrunkTransaction(EmptyHash); // Fill empty branchTransaction transaction.setBranchTransaction(EmptyHash); // Fill empty nonce transaction.setNonce(EmptyNonce); } } std::vector<int8_t> Bundle::normalizedBundle(const Types::Trytes& bundleHash) { std::vector<int8_t> normalizedBundle(SeedLength, 0); for (int i = 0; i < 3; i++) { long sum = 0; for (unsigned int j = 0; j < TryteAlphabetLength; j++) { sum += (normalizedBundle[i * TryteAlphabetLength + j] = Types::tritsToInt<int32_t>( Types::trytesToTrits(Types::Trytes(1, bundleHash[i * TryteAlphabetLength + j])))); } if (sum >= 0) { while (sum-- > 0) { for (unsigned int j = 0; j < TryteAlphabetLength; j++) { if (normalizedBundle[i * TryteAlphabetLength + j] > -13) { normalizedBundle[i * TryteAlphabetLength + j]--; break; } } } } else { while (sum++ < 0) { for (unsigned int j = 0; j < TryteAlphabetLength; j++) { if (normalizedBundle[i * TryteAlphabetLength + j] < 13) { normalizedBundle[i * TryteAlphabetLength + j]++; break; } } } } } return normalizedBundle; } bool Bundle::operator<(const Bundle& rhs) const { int64_t lhsTS = empty() ? 0 : transactions_[0].getAttachmentTimestamp(); int64_t rhsTS = rhs.empty() ? 0 : rhs[0].getAttachmentTimestamp(); return lhsTS < rhsTS; } bool Bundle::operator>(const Bundle& rhs) const { int64_t lhsTS = empty() ? 0 : transactions_[0].getAttachmentTimestamp(); int64_t rhsTS = rhs.empty() ? 0 : rhs[0].getAttachmentTimestamp(); return lhsTS > rhsTS; } bool Bundle::operator==(const Bundle& rhs) const { return getHash() == rhs.getHash(); } bool Bundle::operator!=(const Bundle& rhs) const { return !operator==(rhs); } Transaction& Bundle::operator[](const int index) { return transactions_[index]; } const Transaction& Bundle::operator[](const int index) const { return transactions_[index]; } } // namespace Models } // namespace IOTA
29.430328
100
0.662164
wilsonfonseca
81833316b0516dda700810c584acdd92c655d8e3
1,180
cpp
C++
DeviceCode/Targets/Native/BF537/DeviceCode/various.cpp
valoni/STM32F103
75f0cb8be593ca287a08f5992d1f5d3c3bb12bfc
[ "Apache-2.0" ]
1
2020-06-09T02:16:43.000Z
2020-06-09T02:16:43.000Z
DeviceCode/Targets/Native/BF537/DeviceCode/various.cpp
valoni/STM32F103
75f0cb8be593ca287a08f5992d1f5d3c3bb12bfc
[ "Apache-2.0" ]
null
null
null
DeviceCode/Targets/Native/BF537/DeviceCode/various.cpp
valoni/STM32F103
75f0cb8be593ca287a08f5992d1f5d3c3bb12bfc
[ "Apache-2.0" ]
1
2015-02-08T20:51:53.000Z
2015-02-08T20:51:53.000Z
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) Microsoft Corporation. All rights reserved. ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////#include "tinyhal.h" #include "tinyhal.h" //////////////////////////////////////////////////////////////////////////////////////////////////// #if !defined(BUILD_RTM) void debug_printf(char const* format, ... ) { } void lcd_printf(char const * format,...) { } #endif const ConfigurationSector g_ConfigurationSector; int hal_strcpy_s( char* strDst, size_t sizeInBytes, const char* strSrc ) { strncpy(strDst, strSrc, sizeInBytes); } int hal_strncpy_s( char* strDst, size_t sizeInBytes, const char* strSrc, size_t count ) { strncpy(strDst, strSrc, __min(sizeInBytes, count)); } ///////////////////////////////////////////////////////////////////////////////////////////
36.875
221
0.339831
valoni
8183bdec4e950b8fd338c7b1916d50cd42e108c2
771
cpp
C++
JPZsumofdigits/JPZsumofdigits.cpp
jpaz26/intro-to-c-programming
2fbabfd4f2b53135eca67f781b4a925623dac330
[ "MIT" ]
null
null
null
JPZsumofdigits/JPZsumofdigits.cpp
jpaz26/intro-to-c-programming
2fbabfd4f2b53135eca67f781b4a925623dac330
[ "MIT" ]
null
null
null
JPZsumofdigits/JPZsumofdigits.cpp
jpaz26/intro-to-c-programming
2fbabfd4f2b53135eca67f781b4a925623dac330
[ "MIT" ]
null
null
null
// JPZsumofdigits.cpp : Defines the entry point for the console application. // Joshua Paz; a program that takes a whole integer and adds the digits for a sum #include "stdafx.h" #include <iostream> using namespace std; int main() { //variables int userint = 0; int intholder = 0; int sum = 0; //prompt for user to enter an integer cout << "Please enter an integer: "; cin >> userint; cout << endl; //storage for the integer intholder = userint; //create loop to run equation while (userint > 0) { intholder = userint % 10; cout << "Digit:" << intholder << endl; sum += intholder; userint /= 10; } cout << "" << endl; cout << "The sum of the digits is: " << sum << endl; // output the sum return 0; }
20.837838
82
0.618677
jpaz26
818414ca0e952068cb5348e6be69c2e002940000
10,727
cpp
C++
src/openms/source/ANALYSIS/ID/PrecursorPurity.cpp
andreott/OpenMS
718fa2e8a91280ff65e4cf834a3d825811dce1dc
[ "BSL-1.0", "Zlib", "Apache-2.0" ]
1
2021-07-06T09:15:10.000Z
2021-07-06T09:15:10.000Z
src/openms/source/ANALYSIS/ID/PrecursorPurity.cpp
andreott/OpenMS
718fa2e8a91280ff65e4cf834a3d825811dce1dc
[ "BSL-1.0", "Zlib", "Apache-2.0" ]
7
2018-06-19T14:51:57.000Z
2022-01-12T14:34:32.000Z
src/openms/source/ANALYSIS/ID/PrecursorPurity.cpp
andreott/OpenMS
718fa2e8a91280ff65e4cf834a3d825811dce1dc
[ "BSL-1.0", "Zlib", "Apache-2.0" ]
null
null
null
// -------------------------------------------------------------------------- // OpenMS -- Open-Source Mass Spectrometry // -------------------------------------------------------------------------- // Copyright The OpenMS Team -- Eberhard Karls University Tuebingen, // ETH Zurich, and Freie Universitaet Berlin 2002-2018. // // This software is released under a three-clause BSD license: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of any author or any participating institution // may be used to endorse or promote products derived from this software // without specific prior written permission. // For a full list of authors, refer to the file AUTHORS. // -------------------------------------------------------------------------- // 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 ANY OF THE AUTHORS OR THE CONTRIBUTING // INSTITUTIONS 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. // // -------------------------------------------------------------------------- // $Maintainer: Eugen Netz $ // $Authors: Eugen Netz $ // -------------------------------------------------------------------------- #include <OpenMS/ANALYSIS/ID/PrecursorPurity.h> #include <OpenMS/CONCEPT/Constants.h> #include <OpenMS/CONCEPT/LogStream.h> namespace OpenMS { PrecursorPurity::PurityScores PrecursorPurity::computePrecursorPurity(const PeakSpectrum& ms1, const Precursor& pre, const double precursor_mass_tolerance, const bool precursor_mass_tolerance_unit_ppm) { PrecursorPurity::PurityScores score; double target_mz = pre.getMZ(); double lower = target_mz - pre.getIsolationWindowLowerOffset(); double upper = target_mz + pre.getIsolationWindowUpperOffset(); int charge = pre.getCharge(); double precursor_tolerance_abs = precursor_mass_tolerance_unit_ppm ? (target_mz * precursor_mass_tolerance*2 * 1e-6) : precursor_mass_tolerance*2; auto lower_it = ms1.MZBegin(lower); auto upper_it = ms1.MZEnd(upper); // std::cout << "charge: " << charge << " | lower: " << lower << " | target: " << target_mz << " | upper: " << upper << std::endl; // std::cout << "lower offset: " << pre.getIsolationWindowLowerOffset() << " | upper offset: " << pre.getIsolationWindowUpperOffset() << std::endl; // std::cout << "lower peak: " << (*lower_it).getMZ() << " | upper peak: " << (*upper_it).getMZ() << std::endl; PeakSpectrum isolated_window; while (lower_it != upper_it) { isolated_window.push_back(*lower_it); lower_it++; } // std::cout << "Isolation window peaks: " << isolated_window.size(); // for (auto peak : isolated_window) // { // std::cout << " | " << peak.getMZ(); // } // std::cout << std::endl; // total intensity in isolation window double total_intensity(0); double target_intensity(0); Size target_peak_count(0); for (auto peak : isolated_window) { total_intensity += peak.getIntensity(); } // search for the target peak, return scores with 0-values if it is not found if (isolated_window.empty()) { return score; } // estimate a lower boundary for isotopic peaks int negative_isotopes((pre.getIsolationWindowLowerOffset() * charge)); double iso = -negative_isotopes; // depending on the isolation window, the first estimated peak might be outside the window if (target_mz + (iso * Constants::C13C12_MASSDIFF_U / charge) < lower) { iso++; } // std::cout << "target peaks: "; // deisotoping (try to find isotopic peaks of the precursor mass, even if the actual precursor peak is missing) while (true) // runs as long as the next mz is within the isolation window { double next_peak = target_mz + (iso * Constants::C13C12_MASSDIFF_U / charge); // std::cout << iso << " : iso | " << next_peak << " : next peak | "; // stop loop when new mz is outside the isolation window // changes through the isotope index iso if (next_peak > upper) { break; } int next_iso_index = isolated_window.findNearest(next_peak, precursor_tolerance_abs); if (next_iso_index != -1) { target_intensity += isolated_window[next_iso_index].getIntensity(); // std::cout << isolated_window[next_iso_index].getMZ() << " : matched | "; isolated_window.erase(isolated_window.begin()+next_iso_index); target_peak_count++; } // always increment iso to progress the loop iso++; } // std::cout << std::endl; // // std::cout << "noise peaks: "; // double noise_intensity(0); // for (auto peak : isolated_window) // { // noise_intensity += peak.getIntensity(); // // std::cout << peak.getMZ() << " | "; // } // // std::cout << std::endl; double rel_sig(0); if (target_intensity > 0.0) { rel_sig = target_intensity / total_intensity; } double noise_intensity = total_intensity - target_intensity; score.total_intensity = total_intensity; score.target_intensity = target_intensity; score.residual_intensity = noise_intensity; score.signal_proportion = rel_sig; score.target_peak_count = target_peak_count; score.residual_peak_count = isolated_window.size(); return score; } PrecursorPurity::PurityScores PrecursorPurity::combinePrecursorPurities(const PrecursorPurity::PurityScores& score1, const PrecursorPurity::PurityScores& score2) { PrecursorPurity::PurityScores score; score.total_intensity = score1.total_intensity + score2.total_intensity; score.target_intensity = score1.target_intensity + score2.target_intensity; score.residual_intensity = score1.residual_intensity + score2.residual_intensity; if (score.target_intensity > 0.0) // otherwise default value of 0 is used { score.signal_proportion = score.target_intensity / score.total_intensity; } score.target_peak_count = score1.target_peak_count + score2.target_peak_count; score.residual_peak_count = score1.residual_peak_count + score2.residual_peak_count; return score; } std::vector<PrecursorPurity::PurityScores> PrecursorPurity::computePrecursorPurities(const PeakMap& spectra, double precursor_mass_tolerance, bool precursor_mass_tolerance_unit_ppm) { std::vector<PrecursorPurity::PurityScores> purityscores; // TODO throw an exception or at least a warning? // if there is no MS1 before the first MS2, the spectra datastructure is not suitable for this function if (spectra[0].getMSLevel() == 2) { LOG_WARN << "Warning: Input data not suitable for Precursor Purity computation. Will be skipped!\n"; return purityscores; } // keep the index of the two MS1 spectra flanking the current group of MS2 spectra Size current_parent_index = 0; Size next_parent_index = 0; bool lastMS1(false); for (Size i = 0; i < spectra.size(); ++i) { // change current parent index if a new MS1 spectrum is reached if (spectra[i].getMSLevel() == 1) { current_parent_index = i; } else if (spectra[i].getMSLevel() == 2) { // update next MS1 index, if it is lower than the current MS2 index if (next_parent_index < i) { for (Size j = i+1; j < spectra.size(); ++j) { if (spectra[j].getMSLevel() == 1) { next_parent_index = j; break; } } // if the next MS1 index was not updated, // the end of the PeakMap was reached right after this current group of MS2 spectra if (next_parent_index < i) { lastMS1 = true; } } // std::cout << "MS1 Spectrum: " << spectra[current_parent_index].getNativeID() << " | MS2 : " << spectra[i].getNativeID() << std::endl; PrecursorPurity::PurityScores score1 = PrecursorPurity::computePrecursorPurity(spectra[current_parent_index], spectra[i].getPrecursors()[0], precursor_mass_tolerance, precursor_mass_tolerance_unit_ppm); // use default values of 0, if there is an MS2 spectrum without an MS1 after it (may happen for the last group of MS2 spectra) PrecursorPurity::PurityScores score2; if (!lastMS1) // there is an MS1 after this MS2 { score2 = PrecursorPurity::computePrecursorPurity(spectra[next_parent_index], spectra[i].getPrecursors()[0], precursor_mass_tolerance, precursor_mass_tolerance_unit_ppm); } PrecursorPurity::PurityScores score = PrecursorPurity::combinePrecursorPurities(score1, score2); purityscores.push_back(score); // std::cout << "Score1 | Spectrum: " << i << " | total intensity: " << score1.total_intensity << " | target intensity: " << score1.target_intensity << " | noise intensity: " << score1.residual_intensity << " | rel_sig: " << score1.signal_proportion << std::endl; // std::cout << "Score2 | Spectrum: " << i << " | total intensity: " << score2.total_intensity << " | target intensity: " << score2.target_intensity << " | noise intensity: " << score2.residual_intensity << " | rel_sig: " << score2.signal_proportion << std::endl; // std::cout << "Combin | Spectrum: " << i << " | total intensity: " << score.total_intensity << " | target intensity: " << score.target_intensity << " | noise intensity: " << score.residual_intensity << " | rel_sig: " << score.signal_proportion << std::endl; // std::cout << "#################################################################################################################" << std::endl; } // end of MS2 spectrum } // spectra loop return purityscores; } // end of function def }
46.038627
271
0.641932
andreott
818600efdd39bcacd111e4b0651f92f87aa52e56
6,211
hpp
C++
src/Environment.hpp
avilcheslopez/geopm
35ad0af3f17f42baa009c97ed45eca24333daf33
[ "MIT", "BSD-3-Clause" ]
null
null
null
src/Environment.hpp
avilcheslopez/geopm
35ad0af3f17f42baa009c97ed45eca24333daf33
[ "MIT", "BSD-3-Clause" ]
null
null
null
src/Environment.hpp
avilcheslopez/geopm
35ad0af3f17f42baa009c97ed45eca24333daf33
[ "MIT", "BSD-3-Clause" ]
null
null
null
/* * Copyright (c) 2015 - 2022, Intel Corporation * SPDX-License-Identifier: BSD-3-Clause */ #ifndef ENVIRONMENT_HPP_INCLUDE #define ENVIRONMENT_HPP_INCLUDE #include <string> #include <vector> #include <utility> #include <map> #include <set> #include <memory> namespace geopm { /// @brief Environment class encapsulates all functionality related to /// dealing with runtime environment variables. class Environment { public: /// @brief Enum for controller launch methods /// /// The return value from pmpi_ctl() is one of these. enum m_ctl_e { M_CTL_NONE, M_CTL_PROCESS, M_CTL_PTHREAD, }; Environment() = default; virtual ~Environment() = default; virtual std::string report(void) const = 0; virtual std::string comm(void) const = 0; virtual std::string policy(void) const = 0; virtual std::string endpoint(void) const = 0; virtual std::string shmkey(void) const = 0; virtual std::string trace(void) const = 0; virtual std::string trace_profile(void) const = 0; virtual std::string trace_endpoint_policy(void) const = 0; virtual std::string profile(void) const = 0; virtual std::string frequency_map(void) const = 0; virtual std::string agent(void) const = 0; virtual std::vector<std::pair<std::string, int> > trace_signals(void) const = 0; virtual std::vector<std::pair<std::string, int> > report_signals(void) const = 0; virtual int max_fan_out(void) const = 0; virtual int pmpi_ctl(void) const = 0; virtual bool do_policy(void) const = 0; virtual bool do_endpoint(void) const = 0; virtual bool do_trace(void) const = 0; virtual bool do_trace_profile(void) const = 0; virtual bool do_trace_endpoint_policy(void) const = 0; virtual bool do_profile(void) const = 0; virtual int timeout(void) const = 0; virtual bool do_ompt(void) const = 0; virtual std::string default_config_path(void) const = 0; virtual std::string override_config_path(void) const = 0; virtual std::string record_filter(void) const = 0; virtual bool do_record_filter(void) const = 0; virtual bool do_debug_attach_all(void) const = 0; virtual bool do_debug_attach_one(void) const = 0; virtual int debug_attach_process(void) const = 0; static std::map<std::string, std::string> parse_environment_file(const std::string &env_file_path); }; class PlatformIO; class EnvironmentImp : public Environment { public: EnvironmentImp(); EnvironmentImp(const std::string &default_settings_path, const std::string &override_settings_path, const PlatformIO *platform_io); virtual ~EnvironmentImp() = default; std::string report(void) const override; std::string comm(void) const override; std::string policy(void) const override; std::string endpoint(void) const override; std::string shmkey(void) const override; std::string trace(void) const override; std::string trace_profile(void) const override; std::string trace_endpoint_policy(void) const override; std::string profile(void) const override; std::string frequency_map(void) const override; std::string agent(void) const override; std::vector<std::pair<std::string, int> > trace_signals(void) const override; std::vector<std::pair<std::string, int> > report_signals(void) const override; std::vector<std::pair<std::string, int> > signal_parser(std::string environment_variable_contents) const; int max_fan_out(void) const override; int pmpi_ctl(void) const override; bool do_policy(void) const override; bool do_endpoint(void) const override; bool do_trace(void) const override; bool do_trace_profile(void) const override; bool do_trace_endpoint_policy(void) const override; bool do_profile() const override; int timeout(void) const override; static std::set<std::string> get_all_vars(void); bool do_ompt(void) const override; std::string default_config_path(void) const override; std::string override_config_path(void) const override; static void parse_environment_file(const std::string &settings_path, const std::set<std::string> &all_names, const std::set<std::string> &user_defined_names, std::map<std::string, std::string> &name_value_map); std::string record_filter(void) const override; bool do_record_filter(void) const override; bool do_debug_attach_all(void) const override; bool do_debug_attach_one(void) const override; int debug_attach_process(void) const override; protected: void parse_environment(void); bool is_set(const std::string &env_var) const; std::string lookup(const std::string &env_var) const; const std::set<std::string> m_all_names; const std::set<std::string> m_runtime_names; std::set<std::string> m_user_defined_names; std::map<std::string, std::string> m_name_value_map; const std::string m_default_config_path; const std::string m_override_config_path; // Pointer used here to avoid calling the singleton too // early as the Environment is used in the top of // geopm_pmpi_init(). Do *NOT* delete this pointer. mutable const PlatformIO *m_platform_io; }; const Environment &environment(void); } #endif
46.699248
117
0.608115
avilcheslopez
81873b4fff537b1b5e4b408d3766b4019bc9717f
1,290
hpp
C++
src/kernel_preprocessor.hpp
vbkaisetsu/CLBlast
441373c8fd1442cc4c024e59e7778b4811eb210c
[ "Apache-2.0" ]
null
null
null
src/kernel_preprocessor.hpp
vbkaisetsu/CLBlast
441373c8fd1442cc4c024e59e7778b4811eb210c
[ "Apache-2.0" ]
null
null
null
src/kernel_preprocessor.hpp
vbkaisetsu/CLBlast
441373c8fd1442cc4c024e59e7778b4811eb210c
[ "Apache-2.0" ]
1
2020-09-09T21:04:21.000Z
2020-09-09T21:04:21.000Z
// ================================================================================================= // This file is part of the CLBlast project. The project is licensed under Apache Version 2.0. This // project loosely follows the Google C++ styleguide and uses a tab-size of two spaces and a max- // width of 100 characters per line. // // Author(s): // Cedric Nugteren <www.cedricnugteren.nl> // // This file contains the a simple pre-processor for the OpenCL kernels. This pre-processor is used // in cases where the vendor's OpenCL compiler falls short in loop unrolling and array-to-register // promotion. This pre-processor is specific for the CLBlast code making many assumptions. // // ================================================================================================= #ifndef CLBLAST_KERNEL_PREPROCESSOR_H_ #define CLBLAST_KERNEL_PREPROCESSOR_H_ #include <string> #include "utilities/utilities.hpp" namespace clblast { // ================================================================================================= std::string PreprocessKernelSource(const std::string& kernel_source); // ================================================================================================= } // namespace clblast // CLBLAST_KERNEL_PREPROCESSOR_H_ #endif
39.090909
100
0.532558
vbkaisetsu
8187da5558734bf61db893fdf3be6507a32b506f
297
hh
C++
src/ChatCommands.hh
clint-david/newserv
40aa08bd4f391d8d3f6d41d3b539de5bc4c5c679
[ "MIT" ]
null
null
null
src/ChatCommands.hh
clint-david/newserv
40aa08bd4f391d8d3f6d41d3b539de5bc4c5c679
[ "MIT" ]
null
null
null
src/ChatCommands.hh
clint-david/newserv
40aa08bd4f391d8d3f6d41d3b539de5bc4c5c679
[ "MIT" ]
null
null
null
#pragma once #include <stdint.h> #include <memory> #include <string> #include "ServerState.hh" #include "Lobby.hh" #include "Client.hh" void process_chat_command(std::shared_ptr<ServerState> s, std::shared_ptr<Lobby> l, std::shared_ptr<Client> c, const std::u16string& text);
21.214286
84
0.700337
clint-david
8188d665c50246023d35ae91b9c7818a3e4a88af
29,325
cpp
C++
src/appleseed/renderer/kernel/rendering/progressive/progressiveframerenderer.cpp
Aakash1312/appleseed
0c81cacba6e513ca30a68a038afd67244f0c6b91
[ "MIT" ]
null
null
null
src/appleseed/renderer/kernel/rendering/progressive/progressiveframerenderer.cpp
Aakash1312/appleseed
0c81cacba6e513ca30a68a038afd67244f0c6b91
[ "MIT" ]
null
null
null
src/appleseed/renderer/kernel/rendering/progressive/progressiveframerenderer.cpp
Aakash1312/appleseed
0c81cacba6e513ca30a68a038afd67244f0c6b91
[ "MIT" ]
1
2020-10-01T14:42:39.000Z
2020-10-01T14:42:39.000Z
// // This source file is part of appleseed. // Visit http://appleseedhq.net/ for additional information and resources. // // This software is released under the MIT license. // // Copyright (c) 2010-2013 Francois Beaune, Jupiter Jazz Limited // Copyright (c) 2014-2017 Francois Beaune, The appleseedhq Organization // // 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. // // Interface header. #include "progressiveframerenderer.h" // appleseed.renderer headers. #include "renderer/global/globallogger.h" #include "renderer/kernel/rendering/iframerenderer.h" #include "renderer/kernel/rendering/isamplegenerator.h" #include "renderer/kernel/rendering/itilecallback.h" #include "renderer/kernel/rendering/progressive/samplecounter.h" #include "renderer/kernel/rendering/progressive/samplecounthistory.h" #include "renderer/kernel/rendering/progressive/samplegeneratorjob.h" #include "renderer/kernel/rendering/sampleaccumulationbuffer.h" #include "renderer/modeling/frame/frame.h" #include "renderer/modeling/project/project.h" #include "renderer/utility/settingsparsing.h" // appleseed.foundation headers. #include "foundation/core/concepts/noncopyable.h" #include "foundation/image/analysis.h" #include "foundation/image/canvasproperties.h" #include "foundation/image/genericimagefilereader.h" #include "foundation/image/image.h" #include "foundation/math/aabb.h" #include "foundation/math/scalar.h" #include "foundation/math/vector.h" #include "foundation/platform/defaulttimers.h" #include "foundation/platform/thread.h" #include "foundation/platform/timers.h" #include "foundation/platform/types.h" #include "foundation/utility/api/apistring.h" #include "foundation/utility/containers/dictionary.h" #include "foundation/utility/foreach.h" #include "foundation/utility/gnuplotfile.h" #include "foundation/utility/job.h" #include "foundation/utility/searchpaths.h" #include "foundation/utility/statistics.h" #include "foundation/utility/stopwatch.h" #include "foundation/utility/string.h" // Boost headers. #include "boost/filesystem.hpp" // Standard headers. #include <cassert> #include <cmath> #include <cstddef> #include <limits> #include <memory> #include <string> #include <vector> using namespace foundation; using namespace std; namespace bf = boost::filesystem; namespace renderer { namespace { // // Progressive frame renderer. // //#define PRINT_DISPLAY_THREAD_PERFS class ProgressiveFrameRenderer : public IFrameRenderer { public: ProgressiveFrameRenderer( const Project& project, ISampleGeneratorFactory* generator_factory, ITileCallbackFactory* callback_factory, const ParamArray& params) : m_project(project) , m_params(params) , m_sample_counter(m_params.m_max_sample_count) , m_ref_image_avg_lum(0.0) { // We must have a generator factory, but it's OK not to have a callback factory. assert(generator_factory); // Create an accumulation buffer. m_buffer.reset(generator_factory->create_sample_accumulation_buffer()); // Create and initialize the job manager. m_job_manager.reset( new JobManager( global_logger(), m_job_queue, m_params.m_thread_count, JobManager::KeepRunningOnEmptyQueue)); // Instantiate sample generators, one per rendering thread. m_sample_generators.reserve(m_params.m_thread_count); for (size_t i = 0; i < m_params.m_thread_count; ++i) { m_sample_generators.push_back( generator_factory->create(i, m_params.m_thread_count)); } // Create rendering jobs, one per rendering thread. m_sample_generator_jobs.reserve(m_params.m_thread_count); for (size_t i = 0; i < m_params.m_thread_count; ++i) { m_sample_generator_jobs.push_back( new SampleGeneratorJob( *m_buffer.get(), m_sample_generators[i], m_sample_counter, m_params.m_spectrum_mode, m_job_queue, i, // job index m_params.m_thread_count, // job count m_abort_switch)); } // Instantiate a single tile callback. if (callback_factory) m_tile_callback.reset(callback_factory->create()); // Load the reference image if one is specified. if (!m_params.m_ref_image_path.empty()) { const string ref_image_path = to_string(project.search_paths().qualify(m_params.m_ref_image_path)); RENDERER_LOG_DEBUG("loading reference image %s...", ref_image_path.c_str()); GenericImageFileReader reader; m_ref_image.reset(reader.read(ref_image_path.c_str())); if (are_images_compatible(m_project.get_frame()->image(), *m_ref_image)) { m_ref_image_avg_lum = compute_average_luminance(*m_ref_image.get()); RENDERER_LOG_DEBUG( "reference image average luminance is %s.", pretty_scalar(m_ref_image_avg_lum, 6).c_str()); } else { RENDERER_LOG_ERROR( "the reference image is not compatible with the output frame " "(different dimensions, tile size or number of channels)."); m_ref_image.reset(); } } RENDERER_LOG_INFO( "rendering settings:\n" " spectrum mode %s\n" " sampling mode %s\n" " threads %s", get_spectrum_mode_name(get_spectrum_mode(params)).c_str(), get_sampling_context_mode_name(get_sampling_context_mode(params)).c_str(), pretty_int(m_params.m_thread_count).c_str()); } ~ProgressiveFrameRenderer() override { // Stop the statistics thread. m_abort_switch.abort(); if (m_statistics_thread.get() && m_statistics_thread->joinable()) m_statistics_thread->join(); // Stop the display thread. m_display_thread_abort_switch.abort(); if (m_display_thread.get() && m_display_thread->joinable()) m_display_thread->join(); // Delete the tile callback. m_tile_callback.reset(); // Delete rendering jobs. for (const_each<SampleGeneratorJobVector> i = m_sample_generator_jobs; i; ++i) delete *i; // Delete sample generators. for (const_each<SampleGeneratorVector> i = m_sample_generators; i; ++i) (*i)->release(); } void release() override { delete this; } void render() override { start_rendering(); m_job_queue.wait_until_completion(); } bool is_rendering() const override { return m_job_queue.has_scheduled_or_running_jobs(); } void start_rendering() override { assert(!is_rendering()); assert(!m_job_queue.has_scheduled_or_running_jobs()); m_abort_switch.clear(); m_buffer->clear(); m_sample_counter.clear(); // Reset sample generators. for (size_t i = 0, e = m_sample_generators.size(); i < e; ++i) m_sample_generators[i]->reset(); // Schedule rendering jobs. for (size_t i = 0, e = m_sample_generator_jobs.size(); i < e; ++i) { m_job_queue.schedule( m_sample_generator_jobs[i], false); // don't transfer ownership of the job to the queue } // Start job execution. m_job_manager->start(); // Create and start the statistics thread. m_statistics_func.reset( new StatisticsFunc( m_project, *m_buffer.get(), m_params.m_perf_stats, m_params.m_luminance_stats, m_ref_image.get(), m_ref_image_avg_lum, m_abort_switch)); m_statistics_thread.reset( new boost::thread( ThreadFunctionWrapper<StatisticsFunc>(m_statistics_func.get()))); // Create and start the display thread. if (m_tile_callback.get() != nullptr && m_display_thread.get() == nullptr) { m_display_func.reset( new DisplayFunc( *m_project.get_frame(), *m_buffer.get(), m_tile_callback.get(), m_params.m_max_sample_count, m_params.m_max_fps, m_display_thread_abort_switch)); m_display_thread.reset( new boost::thread( ThreadFunctionWrapper<DisplayFunc>(m_display_func.get()))); } // Resume rendering if it was paused. resume_rendering(); } void stop_rendering() override { // First, delete scheduled jobs to prevent worker threads from picking them up. m_job_queue.clear_scheduled_jobs(); // Tell rendering jobs and the statistics thread to stop. m_abort_switch.abort(); // Wait until rendering jobs have effectively stopped. m_job_queue.wait_until_completion(); // Wait until the statistics thread has stopped. m_statistics_thread->join(); } void pause_rendering() override { m_job_manager->pause(); if (m_display_func.get()) m_display_func->pause(); m_statistics_func->pause(); } void resume_rendering() override { m_statistics_func->resume(); if (m_display_func.get()) m_display_func->resume(); m_job_manager->resume(); } void terminate_rendering() override { // Completely stop rendering. stop_rendering(); m_job_manager->stop(); // The statistics thread has already been joined in stop_rendering(). m_statistics_thread.reset(); m_statistics_func.reset(); // Join and delete the display thread. if (m_display_thread.get()) { m_display_thread_abort_switch.abort(); m_display_thread->join(); m_display_thread.reset(); } // Make sure the remaining calls of this method don't get interrupted. m_abort_switch.clear(); m_display_thread_abort_switch.clear(); if (m_display_func.get()) { // Merge the last samples and display the final frame. m_display_func->develop_and_display(); m_display_func.reset(); } else { // Just merge the last samples into the frame. m_buffer->develop_to_frame(*m_project.get_frame(), m_abort_switch); } // Merge and print sample generator statistics. print_sample_generators_stats(); } private: // // Progressive frame renderer parameters. // struct Parameters { const Spectrum::Mode m_spectrum_mode; const size_t m_thread_count; // number of rendering threads const uint64 m_max_sample_count; // maximum total number of samples to compute const double m_max_fps; // maximum display frequency in frames/second const bool m_perf_stats; // collect and print performance statistics? const bool m_luminance_stats; // collect and print luminance statistics? const string m_ref_image_path; // path to the reference image explicit Parameters(const ParamArray& params) : m_spectrum_mode(get_spectrum_mode(params)) , m_thread_count(get_rendering_thread_count(params)) , m_max_sample_count(params.get_optional<uint64>("max_samples", numeric_limits<uint64>::max())) , m_max_fps(params.get_optional<double>("max_fps", 30.0)) , m_perf_stats(params.get_optional<bool>("performance_statistics", false)) , m_luminance_stats(params.get_optional<bool>("luminance_statistics", false)) , m_ref_image_path(params.get_optional<string>("reference_image", "")) { } }; // // Frame display thread. // class DisplayFunc : public NonCopyable { public: DisplayFunc( Frame& frame, SampleAccumulationBuffer& buffer, ITileCallback* tile_callback, const uint64 max_sample_count, const double max_fps, IAbortSwitch& abort_switch) : m_frame(frame) , m_buffer(buffer) , m_tile_callback(tile_callback) , m_min_sample_count(min<uint64>(max_sample_count, 32 * 32 * 2)) , m_target_elapsed(1.0 / max_fps) , m_abort_switch(abort_switch) { } void pause() { m_pause_flag.set(); } void resume() { m_pause_flag.clear(); } void operator()() { set_current_thread_name("display"); DefaultWallclockTimer timer; const double rcp_timer_freq = 1.0 / timer.frequency(); uint64 last_time = timer.read(); #ifdef PRINT_DISPLAY_THREAD_PERFS m_stopwatch.start(); #endif while (!m_abort_switch.is_aborted()) { if (m_pause_flag.is_clear()) { // It's time to display but the sample accumulation buffer doesn't contain // enough samples yet. Giving up would lead to noticeable jerkiness, so we // wait until enough samples are available. while (!m_abort_switch.is_aborted() && m_buffer.get_sample_count() < m_min_sample_count) yield(); // Merge the samples and display the final frame. develop_and_display(); } // Compute time elapsed since last call to display(). const uint64 time = timer.read(); const double elapsed = (time - last_time) * rcp_timer_freq; last_time = time; // Limit display rate. if (elapsed < m_target_elapsed) { const double ms = ceil(1000.0 * (m_target_elapsed - elapsed)); sleep(truncate<uint32>(ms), m_abort_switch); } } } void develop_and_display() { #ifdef PRINT_DISPLAY_THREAD_PERFS m_stopwatch.measure(); const double t1 = m_stopwatch.get_seconds(); #endif // Develop the accumulation buffer to the frame. m_buffer.develop_to_frame(m_frame, m_abort_switch); #ifdef PRINT_DISPLAY_THREAD_PERFS m_stopwatch.measure(); const double t2 = m_stopwatch.get_seconds(); #endif // Make sure we don't present incomplete frames. if (m_abort_switch.is_aborted()) return; // Present the frame. m_tile_callback->on_progressive_frame_end(&m_frame); #ifdef PRINT_DISPLAY_THREAD_PERFS m_stopwatch.measure(); const double t3 = m_stopwatch.get_seconds(); RENDERER_LOG_DEBUG( "display thread:\n" " buffer to frame %s\n" " frame to widget %s\n" " total %s (%s fps)", pretty_time(t2 - t1).c_str(), pretty_time(t3 - t2).c_str(), pretty_time(t3 - t1).c_str(), pretty_ratio(1.0, t3 - t1).c_str()); #endif } private: Frame& m_frame; SampleAccumulationBuffer& m_buffer; ITileCallback* m_tile_callback; const uint64 m_min_sample_count; const double m_target_elapsed; IAbortSwitch& m_abort_switch; ThreadFlag m_pause_flag; Stopwatch<DefaultWallclockTimer> m_stopwatch; }; // // Statistics gathering and printing thread. // class StatisticsFunc : public NonCopyable { public: StatisticsFunc( const Project& project, SampleAccumulationBuffer& buffer, const bool perf_stats, const bool luminance_stats, const Image* ref_image, const double ref_image_avg_lum, IAbortSwitch& abort_switch) : m_project(project) , m_buffer(buffer) , m_perf_stats(perf_stats) , m_luminance_stats(luminance_stats) , m_ref_image(ref_image) , m_ref_image_avg_lum(ref_image_avg_lum) , m_abort_switch(abort_switch) , m_rcp_timer_frequency(1.0 / m_timer.frequency()) , m_timer_start_value(m_timer.read()) { const Vector2u crop_window_extent = m_project.get_frame()->get_crop_window().extent(); const size_t pixel_count = (crop_window_extent.x + 1) * (crop_window_extent.y + 1); m_rcp_pixel_count = 1.0 / pixel_count; } ~StatisticsFunc() { if (!m_sample_count_records.empty()) { const string filepath = (bf::path(m_project.search_paths().get_root_path().c_str()) / "sample_count.gnuplot").string(); RENDERER_LOG_DEBUG("writing %s...", filepath.c_str()); GnuplotFile plotfile; plotfile.set_xlabel("Time"); plotfile.set_ylabel("Samples"); plotfile .new_plot() .set_points(m_sample_count_records) .set_title("Total Sample Count Over Time"); plotfile.write(filepath); } if (!m_rmsd_records.empty()) { const string filepath = (bf::path(m_project.search_paths().get_root_path().c_str()) / "rms_deviation.gnuplot").string(); RENDERER_LOG_DEBUG("writing %s...", filepath.c_str()); GnuplotFile plotfile; plotfile.set_xlabel("Samples per Pixel"); plotfile.set_ylabel("RMS Deviation"); plotfile .new_plot() .set_points(m_rmsd_records) .set_title("RMS Deviation Over Time"); plotfile.write(filepath); } } void pause() { m_pause_flag.set(); } void resume() { m_pause_flag.clear(); } void operator()() { set_current_thread_name("statistics"); while (!m_abort_switch.is_aborted()) { if (m_pause_flag.is_clear()) { const double time = (m_timer.read() - m_timer_start_value) * m_rcp_timer_frequency; record_and_print_perf_stats(time); if (m_luminance_stats || m_ref_image) record_and_print_convergence_stats(); } sleep(1000, m_abort_switch); } } private: const Project& m_project; SampleAccumulationBuffer& m_buffer; const bool m_perf_stats; const bool m_luminance_stats; const Image* m_ref_image; const double m_ref_image_avg_lum; IAbortSwitch& m_abort_switch; ThreadFlag m_pause_flag; DefaultWallclockTimer m_timer; double m_rcp_timer_frequency; uint64 m_timer_start_value; double m_rcp_pixel_count; SampleCountHistory<128> m_sample_count_history; vector<Vector2d> m_sample_count_records; // total sample count over time vector<Vector2d> m_rmsd_records; // RMS deviation over time void record_and_print_perf_stats(const double time) { const uint64 samples = m_buffer.get_sample_count(); m_sample_count_history.insert(time, samples); const double samples_per_pixel = samples * m_rcp_pixel_count; const uint64 samples_per_second = truncate<uint64>(m_sample_count_history.get_samples_per_second()); RENDERER_LOG_INFO( "%s samples, %s samples/pixel, %s samples/second", pretty_uint(samples).c_str(), pretty_scalar(samples_per_pixel).c_str(), pretty_uint(samples_per_second).c_str()); if (m_perf_stats) m_sample_count_records.emplace_back(time, static_cast<double>(samples)); } void record_and_print_convergence_stats() { assert(m_luminance_stats || m_ref_image); string output; if (m_luminance_stats) { const double avg_lum = compute_average_luminance(m_project.get_frame()->image()); output += "average luminance " + pretty_scalar(avg_lum, 6); if (m_ref_image) { const double avg_lum_delta = abs(m_ref_image_avg_lum - avg_lum); output += " ("; output += pretty_percent(avg_lum_delta, m_ref_image_avg_lum, 3); output += " error)"; } } if (m_ref_image) { const double samples_per_pixel = m_buffer.get_sample_count() * m_rcp_pixel_count; const double rmsd = compute_rms_deviation(m_project.get_frame()->image(), *m_ref_image); m_rmsd_records.emplace_back(samples_per_pixel, rmsd); if (m_luminance_stats) output += ", "; output += "rms deviation " + pretty_scalar(rmsd, 6); } RENDERER_LOG_DEBUG("%s", output.c_str()); } }; // // Progressive frame renderer implementation details. // const Project& m_project; const Parameters m_params; SampleCounter m_sample_counter; unique_ptr<SampleAccumulationBuffer> m_buffer; JobQueue m_job_queue; unique_ptr<JobManager> m_job_manager; AbortSwitch m_abort_switch; typedef vector<ISampleGenerator*> SampleGeneratorVector; SampleGeneratorVector m_sample_generators; typedef vector<SampleGeneratorJob*> SampleGeneratorJobVector; SampleGeneratorJobVector m_sample_generator_jobs; auto_release_ptr<ITileCallback> m_tile_callback; unique_ptr<Image> m_ref_image; double m_ref_image_avg_lum; unique_ptr<DisplayFunc> m_display_func; unique_ptr<boost::thread> m_display_thread; AbortSwitch m_display_thread_abort_switch; unique_ptr<StatisticsFunc> m_statistics_func; unique_ptr<boost::thread> m_statistics_thread; void print_sample_generators_stats() const { assert(!m_sample_generators.empty()); StatisticsVector stats; for (size_t i = 0; i < m_sample_generators.size(); ++i) stats.merge(m_sample_generators[i]->get_statistics()); RENDERER_LOG_DEBUG("%s", stats.to_string().c_str()); } }; } // // ProgressiveFrameRendererFactory class implementation. // ProgressiveFrameRendererFactory::ProgressiveFrameRendererFactory( const Project& project, ISampleGeneratorFactory* generator_factory, ITileCallbackFactory* callback_factory, const ParamArray& params) : m_project(project) , m_generator_factory(generator_factory) , m_callback_factory(callback_factory) , m_params(params) { } void ProgressiveFrameRendererFactory::release() { delete this; } IFrameRenderer* ProgressiveFrameRendererFactory::create() { return new ProgressiveFrameRenderer( m_project, m_generator_factory, m_callback_factory, m_params); } IFrameRenderer* ProgressiveFrameRendererFactory::create( const Project& project, ISampleGeneratorFactory* generator_factory, ITileCallbackFactory* callback_factory, const ParamArray& params) { return new ProgressiveFrameRenderer( project, generator_factory, callback_factory, params); } Dictionary ProgressiveFrameRendererFactory::get_params_metadata() { Dictionary metadata; metadata.dictionaries().insert( "max_fps", Dictionary() .insert("type", "float") .insert("default", "30.0") .insert("label", "Max FPS") .insert("help", "Maximum progressive rendering update rate in frames per second")); metadata.dictionaries().insert( "max_samples", Dictionary() .insert("type", "int") .insert("label", "Max Samples") .insert("help", "Maximum number of samples per pixel")); return metadata; } } // namespace renderer
36.840452
120
0.541176
Aakash1312
8188e3941d6519d466adae0e0c84c853f659ccfa
2,591
cpp
C++
pwiz/analysis/eharmony/Matrix.cpp
edyp-lab/pwiz-mzdb
d13ce17f4061596c7e3daf9cf5671167b5996831
[ "Apache-2.0" ]
11
2015-01-08T08:33:44.000Z
2019-07-12T06:14:54.000Z
pwiz/analysis/eharmony/Matrix.cpp
shze/pwizard-deb
4822829196e915525029a808470f02d24b8b8043
[ "Apache-2.0" ]
61
2015-05-27T11:20:11.000Z
2019-12-20T15:06:21.000Z
pwiz/analysis/eharmony/Matrix.cpp
shze/pwizard-deb
4822829196e915525029a808470f02d24b8b8043
[ "Apache-2.0" ]
4
2016-02-03T09:41:16.000Z
2021-08-01T18:42:36.000Z
// // $Id: Matrix.cpp 1539 2009-11-19 20:12:28Z khoff $ // // // Original author: Kate Hoff <katherine.hoff@proteowizard.org> // // Copyright 2009 Center for Applied Molecular Medicine // University of Southern California, Los Angeles, CA // // 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. // /// /// Matrix.cpp /// #include "Matrix.hpp" #include <iostream> using namespace pwiz; using namespace eharmony; Matrix::Matrix(const int& r, const int& c) { _rows = vector<vector<double> >(r, vector<double>(c)); _columns = vector<vector<double> >(c, vector<double>(r)); for(int row_index = 0; row_index != r; ++row_index) { for(int column_index = 0; column_index != c; ++column_index) { _data.insert(make_pair(0,make_pair(row_index,column_index))); } } } void Matrix::insert(const double& value, const int& rowCoordinate, const int& columnCoordinate) { double oldValue = access(rowCoordinate, columnCoordinate); pair<multimap<double, pair<int,int> >::iterator, multimap<double, pair<int,int> >::iterator> candidates = _data.equal_range(oldValue); pair<int, int> coords = make_pair(rowCoordinate, columnCoordinate); multimap<double, pair<int,int> >::iterator it = candidates.first; for(; it != candidates.second; ++it ) if (it->second == coords) _data.erase(it); _rows.at(rowCoordinate).at(columnCoordinate) = value; _columns.at(columnCoordinate).at(rowCoordinate) = value; _data.insert(make_pair(value, make_pair(rowCoordinate, columnCoordinate))); } double Matrix::access(const int& rowCoordinate, const int& columnCoordinate) { return _rows.at(rowCoordinate).at(columnCoordinate); } ostream& Matrix::write(ostream& os) { vector<vector<double> >::const_iterator it = _rows.begin(); for( ; it != _rows.end(); ++it) { vector<double>::const_iterator jt = it->begin(); for( ; jt!= it->end(); ++jt) { os << *jt << " "; } os << endl; } return os; }
29.443182
138
0.655345
edyp-lab
818900af12ffe2d35a6f05743c05d9d999fc5da8
3,816
cc
C++
towr/src/base_motion_constraint.cc
eeoozz/towr
189fd39b156d1ed80894c3d9086da1b8f7426de3
[ "BSD-3-Clause" ]
592
2018-01-30T10:36:47.000Z
2022-03-28T16:40:16.000Z
towr/src/base_motion_constraint.cc
eeoozz/towr
189fd39b156d1ed80894c3d9086da1b8f7426de3
[ "BSD-3-Clause" ]
68
2018-02-08T06:00:16.000Z
2022-03-31T08:46:05.000Z
towr/src/base_motion_constraint.cc
eeoozz/towr
189fd39b156d1ed80894c3d9086da1b8f7426de3
[ "BSD-3-Clause" ]
185
2018-02-11T03:22:30.000Z
2022-03-28T12:56:21.000Z
/****************************************************************************** Copyright (c) 2018, Alexander W. Winkler. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of 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. ******************************************************************************/ #include <towr/constraints/base_motion_constraint.h> #include <towr/variables/variable_names.h> #include <towr/variables/cartesian_dimensions.h> #include <towr/variables/spline_holder.h> namespace towr { BaseMotionConstraint::BaseMotionConstraint (double T, double dt, const SplineHolder& spline_holder) :TimeDiscretizationConstraint(T, dt, "baseMotion") { base_linear_ = spline_holder.base_linear_; base_angular_ = spline_holder.base_angular_; double dev_rad = 0.05; node_bounds_.resize(k6D); node_bounds_.at(AX) = Bounds(-dev_rad, dev_rad); node_bounds_.at(AY) = Bounds(-dev_rad, dev_rad); node_bounds_.at(AZ) = ifopt::NoBound;//Bounds(-dev_rad, dev_rad); double z_init = base_linear_->GetPoint(0.0).p().z(); node_bounds_.at(LX) = ifopt::NoBound; node_bounds_.at(LY) = ifopt::NoBound;//Bounds(-0.05, 0.05); node_bounds_.at(LZ) = Bounds(z_init-0.02, z_init+0.1); // allow to move dev_z cm up and down int n_constraints_per_node = node_bounds_.size(); SetRows(GetNumberOfNodes()*n_constraints_per_node); } void BaseMotionConstraint::UpdateConstraintAtInstance (double t, int k, VectorXd& g) const { g.middleRows(GetRow(k, LX), k3D) = base_linear_->GetPoint(t).p(); g.middleRows(GetRow(k, AX), k3D) = base_angular_->GetPoint(t).p(); } void BaseMotionConstraint::UpdateBoundsAtInstance (double t, int k, VecBound& bounds) const { for (int dim=0; dim<node_bounds_.size(); ++dim) bounds.at(GetRow(k,dim)) = node_bounds_.at(dim); } void BaseMotionConstraint::UpdateJacobianAtInstance (double t, int k, std::string var_set, Jacobian& jac) const { if (var_set == id::base_ang_nodes) jac.middleRows(GetRow(k,AX), k3D) = base_angular_->GetJacobianWrtNodes(t, kPos); if (var_set == id::base_lin_nodes) jac.middleRows(GetRow(k,LX), k3D) = base_linear_->GetJacobianWrtNodes(t, kPos); } int BaseMotionConstraint::GetRow (int node, int dim) const { return node*node_bounds_.size() + dim; } } /* namespace towr */
40.595745
94
0.697065
eeoozz
818b46118366b6beea8b61c9c2605af1b5647166
402
cpp
C++
Menu Interno Console/Main.cpp
FuckLaw/Menu-Interno-Console
8fb2fcd63d280b7443a09daba1c9fbcae57b6a22
[ "MIT" ]
1
2020-04-09T22:11:47.000Z
2020-04-09T22:11:47.000Z
Menu Interno Console/Main.cpp
FuckLaw/Menu-Interno-Console
8fb2fcd63d280b7443a09daba1c9fbcae57b6a22
[ "MIT" ]
null
null
null
Menu Interno Console/Main.cpp
FuckLaw/Menu-Interno-Console
8fb2fcd63d280b7443a09daba1c9fbcae57b6a22
[ "MIT" ]
null
null
null
#include <Windows.h> #include "Includes.h" #include "Menu.h" #include "Keyboard.h" #include "Items.h" #include "Colors.h" #include "EnableDebug.h" #include "Hacks.h" #include "DrawMenu.h" BOOL APIENTRY DllMain(HMODULE hmodule, DWORD ui_reason_for_call, LPVOID lpReserved) { EnableDebugPrivilege(); if (ui_reason_for_call == DLL_PROCESS_ATTACH) { DrawMenu(); } return true; }
20.1
84
0.701493
FuckLaw
818d804c6d56ffcedf17622a5ecdfa9502bbdc8f
4,627
cpp
C++
Source/Compiler/SyntaxHandlers/AssignmentExpressionHandler.cpp
spencerparkin/Powder
2378c1d86c02ccd078e905b06c646777b074b9c0
[ "MIT" ]
1
2021-06-19T05:53:35.000Z
2021-06-19T05:53:35.000Z
Source/Compiler/SyntaxHandlers/AssignmentExpressionHandler.cpp
spencerparkin/Powder
2378c1d86c02ccd078e905b06c646777b074b9c0
[ "MIT" ]
6
2021-07-29T05:44:03.000Z
2021-07-29T05:56:58.000Z
Source/Compiler/SyntaxHandlers/AssignmentExpressionHandler.cpp
spencerparkin/Powder
2378c1d86c02ccd078e905b06c646777b074b9c0
[ "MIT" ]
null
null
null
#include "AssignmentExpressionHandler.h" #include "StoreInstruction.h" #include "MathInstruction.h" #include "PopInstruction.h" #include "Assembler.h" namespace Powder { AssignmentExpressionHandler::AssignmentExpressionHandler() { } /*virtual*/ AssignmentExpressionHandler::~AssignmentExpressionHandler() { } /*virtual*/ void AssignmentExpressionHandler::HandleSyntaxNode(const Parser::SyntaxNode* syntaxNode, LinkedList<Instruction*>& instructionList, InstructionGenerator* instructionGenerator) { if (syntaxNode->childList.GetCount() != 3) throw new CompileTimeException("Expected \"assignment-expression\" in AST to have exactly 3 children.", &syntaxNode->fileLocation); // We treat assignment to identifiers (or other things) different than a generic binary expression, because it is not // supported by the math instruction. Rather, it is supported by the store instruction. The math instruction only // operates on concrete values. Yes, we could introduce symbolic variable values as another type of value floating // around in the VM, and have the math instruction store variables when given an assignment operation to perform, or // load concrete values when it encounters a symbolic variable value, but I think that starts to violate a clear separation // of concerns, and furthermore, it makes one instruction (in this case, the math instruction), more complicated than it needs to be. const Parser::SyntaxNode* operationNode = syntaxNode->childList.GetHead()->GetNext()->value; if (*operationNode->name != "=") throw new CompileTimeException("Expected \"assignment-expression\" to have quality child node in AST.", &operationNode->fileLocation); const Parser::SyntaxNode* storeLocationNode = syntaxNode->childList.GetHead()->value; if (*storeLocationNode->name != "identifier" && *storeLocationNode->name != "container-field-expression") throw new CompileTimeException(FormatString("Expected left operand of \"assignment-expression\" in AST to be a storable location (not \"%s\".)", storeLocationNode->name->c_str()), &storeLocationNode->fileLocation); if (*storeLocationNode->name == "identifier") { const Parser::SyntaxNode* storeLocationNameNode = storeLocationNode->childList.GetHead()->value; // Lay down the instructions that will generate the value to be stored on top of the evaluation stack. instructionGenerator->GenerateInstructionListRecursively(instructionList, syntaxNode->childList.GetHead()->GetNext()->GetNext()->value); // Now issue a store instruction. Note that this also pops the value off the stack, which is // symmetrically consistent with its counter-part, the load instruction. StoreInstruction* storeInstruction = Instruction::CreateForAssembly<StoreInstruction>(syntaxNode->fileLocation); AssemblyData::Entry entry; entry.string = *storeLocationNameNode->name; storeInstruction->assemblyData->configMap.Insert("name", entry); instructionList.AddTail(storeInstruction); // TODO: For the case a = b = 1, look at our parent syntax nodes to see if we should issue // a load instruction here for the next store instruction. } else if (*storeLocationNode->name == "container-field-expression") { // First goes the container value. instructionGenerator->GenerateInstructionListRecursively(instructionList, storeLocationNode->childList.GetHead()->value); // Second goes the field value. (Not to be confused with the value that will be stored at the field value in the container value.) instructionGenerator->GenerateInstructionListRecursively(instructionList, storeLocationNode->childList.GetHead()->GetNext()->value); // Third goes the value to be store in the container value at the field value. instructionGenerator->GenerateInstructionListRecursively(instructionList, syntaxNode->childList.GetHead()->GetNext()->GetNext()->value); // Finally, issue a math instruction to insert a value into the container value at the field value. MathInstruction* mathInstruction = Instruction::CreateForAssembly<MathInstruction>(syntaxNode->fileLocation); AssemblyData::Entry entry; entry.code = MathInstruction::MathOp::SET_FIELD; mathInstruction->assemblyData->configMap.Insert("mathOp", entry); instructionList.AddTail(mathInstruction); // Lastly, check out context. If nothing wants the value we leave on the stack-stop, pop it. if (this->PopNeededForExpression(syntaxNode)) { PopInstruction* popInstruction = Instruction::CreateForAssembly<PopInstruction>(syntaxNode->fileLocation); instructionList.AddTail(popInstruction); } } } }
57.8375
217
0.768749
spencerparkin
818e8bc200fae67e4e4aa14fb7e82805adc23ebc
548
hpp
C++
src/reporter/resources/rp_different_type_report_resources.hpp
lpea/cppinclude
dc126c6057d2fe30569e6e86f66d2c8eebb50212
[ "MIT" ]
177
2020-08-24T19:20:35.000Z
2022-03-27T01:58:04.000Z
src/reporter/resources/rp_different_type_report_resources.hpp
lpea/cppinclude
dc126c6057d2fe30569e6e86f66d2c8eebb50212
[ "MIT" ]
15
2020-08-30T17:59:42.000Z
2022-01-12T11:14:10.000Z
src/reporter/resources/rp_different_type_report_resources.hpp
lpea/cppinclude
dc126c6057d2fe30569e6e86f66d2c8eebb50212
[ "MIT" ]
11
2020-09-17T23:31:10.000Z
2022-03-04T13:15:21.000Z
#pragma once //------------------------------------------------------------------------------ namespace reporter::resources::different_type_report { //------------------------------------------------------------------------------ extern const char * const Name; extern const char * const Header; extern const char * const UserIncludeLabel; extern const char * const SystemIncludeLabel; extern const char * const FileFmt; extern const char * const DetailFmt; //------------------------------------------------------------------------------ }
26.095238
80
0.432482
lpea
818f5d7c3c20565e970518af1ea7f57a32ec325a
947
hpp
C++
robot2019-ros/initial_pose/include/initialpose_node.hpp
junhuizhou/ROS_Learning
bb3a0c867ba2bd147bbd59176cf1224c09a63914
[ "MIT" ]
null
null
null
robot2019-ros/initial_pose/include/initialpose_node.hpp
junhuizhou/ROS_Learning
bb3a0c867ba2bd147bbd59176cf1224c09a63914
[ "MIT" ]
1
2021-05-07T07:30:11.000Z
2021-05-07T07:30:11.000Z
robot2019-ros/initial_pose/include/initialpose_node.hpp
junhuizhou/ROS_Learning
bb3a0c867ba2bd147bbd59176cf1224c09a63914
[ "MIT" ]
null
null
null
#ifndef INITIALPOSE_NODE_H #define INITIALPOSE_NODE_H #include <initialpose_include.hpp> #include <initialpose_config.hpp> #include <initialpose_estimation.hpp> class initialpose_node { public: initialpose_node(std::string node_name); bool setTransform(std::string laser_topic_name); bool GetStaticMap(); void LaserScanCallback(const sensor_msgs::LaserScanConstPtr msg); void GameStatusCallback(const roborts_msgs::GameStatusPtr msg); public: std::unique_ptr<initialpose_estimation> estimator_ptr_; bool CheckSide_WithLaser_Valid_ = false; double x_lb_; double y_lb_; double alpha_lb_; double cos_alpha_lb_; double sin_alpha_lb_; private: ros::NodeHandle n_; ros::Subscriber LaserScan_sub_; ros::Subscriber GameStatus_sub_; ros::ServiceClient static_map_srv_; std::unique_ptr<tf::TransformListener> tf_listener_ptr_; std::string base_frame_; ros::Publisher initialpose_pub_; bool is_status_valid_; }; #endif
21.522727
66
0.80359
junhuizhou
8190c3ae636d33baee970e4bb21ac030732c29e6
33
cpp
C++
MagneticPositioning_VC_Pro/MagneticPositioning_Matlab/openglhelper.cpp
Peefy/MagneticPositioningGUI
1adc91688ba14c0a361ce5a9d7fd939f7d088207
[ "MIT" ]
2
2018-04-21T04:54:28.000Z
2020-12-04T05:23:38.000Z
MagneticPositioning_VC_Pro/MagneticPositioning_Matlab/openglhelper.cpp
Peefy/MagneticPositioningGUI
1adc91688ba14c0a361ce5a9d7fd939f7d088207
[ "MIT" ]
null
null
null
MagneticPositioning_VC_Pro/MagneticPositioning_Matlab/openglhelper.cpp
Peefy/MagneticPositioningGUI
1adc91688ba14c0a361ce5a9d7fd939f7d088207
[ "MIT" ]
1
2020-10-28T07:43:17.000Z
2020-10-28T07:43:17.000Z
#include "util/openglhelper.h"
8.25
30
0.727273
Peefy
81919146816ee771de4ac0626d14b2315c490460
967
cpp
C++
Documentation/Examples/Matrices/DenseMatrix/DenseMatrixViewExample_wrap.cpp
grinisrit/tnl-dev
4403b2dca895e2c32636395d6f1c1210c7afcefd
[ "MIT" ]
null
null
null
Documentation/Examples/Matrices/DenseMatrix/DenseMatrixViewExample_wrap.cpp
grinisrit/tnl-dev
4403b2dca895e2c32636395d6f1c1210c7afcefd
[ "MIT" ]
null
null
null
Documentation/Examples/Matrices/DenseMatrix/DenseMatrixViewExample_wrap.cpp
grinisrit/tnl-dev
4403b2dca895e2c32636395d6f1c1210c7afcefd
[ "MIT" ]
null
null
null
#include <iostream> #include <TNL/Algorithms/ParallelFor.h> #include <TNL/Matrices/DenseMatrix.h> #include <TNL/Matrices/MatrixWrapping.h> #include <TNL/Devices/Host.h> #include <TNL/Devices/Cuda.h> template< typename Device > void wrapMatrixView() { const int rows( 3 ), columns( 4 ); TNL::Containers::Vector< double, Device > valuesVector { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 }; double* values = valuesVector.getData(); /*** * Wrap the array `values` to dense matrix view */ auto matrix = TNL::Matrices::wrapDenseMatrix< Device >( rows, columns, values ); std::cout << "Matrix reads as: " << std::endl << matrix << std::endl; } int main( int argc, char* argv[] ) { std::cout << "Wraping matrix view on host: " << std::endl; wrapMatrixView< TNL::Devices::Host >(); #ifdef HAVE_CUDA std::cout << "Wraping matrix view on CUDA device: " << std::endl; wrapMatrixView< TNL::Devices::Cuda >(); #endif }
27.628571
83
0.635988
grinisrit
8193ebd46c6978641d2dcd2c91896cdb838f4f33
46,314
cpp
C++
src/MapleFE/recdetect/rec_detect.cpp
venshine/OpenArkCompiler
264cd4463834356658154f0d254672ef559f245f
[ "MulanPSL-1.0" ]
2
2019-09-06T07:02:41.000Z
2019-09-09T12:24:46.000Z
src/MapleFE/recdetect/rec_detect.cpp
venshine/OpenArkCompiler
264cd4463834356658154f0d254672ef559f245f
[ "MulanPSL-1.0" ]
null
null
null
src/MapleFE/recdetect/rec_detect.cpp
venshine/OpenArkCompiler
264cd4463834356658154f0d254672ef559f245f
[ "MulanPSL-1.0" ]
null
null
null
/* * Copyright (C) [2020] Futurewei Technologies, Inc. All rights reverved. * * OpenArkFE is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR * FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #include "common_header_autogen.h" #include "ruletable_util.h" #include "rec_detect.h" #include "rule_summary.h" namespace maplefe { //////////////////////////////////////////////////////////////////////////////////// // The idea of Rursion Dectect is through a Depth First Traversal in the tree. // There are a few things we need make it clear. // 1) We are looking for back edge when traversing the tree. Those back edges form // the recursions. We differentiate a recursion using the first node, ie, the topmost // node in the tree in this recursion. // 2) Each node (ie rule table) could have multiple recursions. // 3) Recursions could include children recursions inside. // // [NOTE] The key point in recursion detector is to make sure for each loop, there // should be one and only one recursion counted, even if there are multiple // nodes in the loop. // To achieve this, we build the tree, and those back edges of recursion won't // be counted as tree edge. So in DFS traversal, children are done before parents. // If a child is involved in a loop, only the topmost ancestor will be the // leader of this loop. // // This DFS traversal also assures once a node is traversed, all the loops // containing it will be found at this single time. We don't need traverse // this node any more. -- This is the base of our algorithm. //////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////// // RecPath //////////////////////////////////////////////////////////////////////////////////// void RecPath::Dump() { for (unsigned i = 0; i < mPositions.GetNum(); i++) { std::cout << mPositions.ValueAtIndex(i) << ","; } std::cout << std::endl; } std::string RecPath::DumpToString() { std::string s; for (unsigned i = 0; i < mPositions.GetNum(); i++) { std::string num = std::to_string(mPositions.ValueAtIndex(i)); s += num; if (i < mPositions.GetNum() - 1) s += ","; } return s; } //////////////////////////////////////////////////////////////////////////////////// // Recursion //////////////////////////////////////////////////////////////////////////////////// void Recursion::AddRuleTable(RuleTable *rt) { if (!HaveRuleTable(rt)) mRuleTables.PushBack(rt); } void Recursion::Release() { for (unsigned i = 0; i < mPaths.GetNum(); i++) { RecPath *path = mPaths.ValueAtIndex(i); path->Release(); } mPaths.Release(); mRuleTables.Release(); } //////////////////////////////////////////////////////////////////////////////////// // Rule2Recursion //////////////////////////////////////////////////////////////////////////////////// // A rule table could have multiple instance in a recursion if the recursion has // multiple circle and the rule appears in multiple circles. void Rule2Recursion::AddRecursion(Recursion *rec) { for (unsigned i = 0; i < mRecursions.GetNum(); i++) { if (rec == mRecursions.ValueAtIndex(i)) return; } mRecursions.PushBack(rec); } //////////////////////////////////////////////////////////////////////////////////// // RecDetector //////////////////////////////////////////////////////////////////////////////////// void RecDetector::SetupTopTables() { for (unsigned i = 0; i < gTopRulesNum; i++) mToDo.PushBack(gTopRules[i]); } // A talbe is already been processed. bool RecDetector::IsInProcess(RuleTable *t) { for (unsigned i = 0; i < mInProcess.GetNum(); i++) { if (t == mInProcess.ValueAtIndex(i)) return true; } return false; } // A talbe is already done. bool RecDetector::IsDone(RuleTable *t) { for (unsigned i = 0; i < mDone.GetNum(); i++) { if (t == mDone.ValueAtIndex(i)) return true; } return false; } // A talbe is in ToDo bool RecDetector::IsToDo(RuleTable *t) { for (unsigned i = 0; i < mToDo.GetNum(); i++) { if (t == mToDo.ValueAtIndex(i)) return true; } return false; } // Add a rule to the ToDo list, if it's not in any of the following list, // mInProcess, mDone, mToDo. void RecDetector::AddToDo(RuleTable *rule) { if (!IsInProcess(rule) && !IsDone(rule) && !IsToDo(rule)) mToDo.PushBack(rule); } // Add all child rules into ToDo, starting from index 'start'. void RecDetector::AddToDo(RuleTable *rule_table, unsigned start) { for (unsigned i = start; i < rule_table->mNum; i++) { TableData *data = rule_table->mData + i; if (data->mType == DT_Subtable) { RuleTable *child = data->mData.mEntry; AddToDo(child); } } } bool RecDetector::IsMaybeZero(RuleTable *t) { for (unsigned i = 0; i < mMaybeZero.GetNum(); i++) { if (t == mMaybeZero.ValueAtIndex(i)) return true; } return false; } bool RecDetector::IsFail(RuleTable *t) { for (unsigned i = 0; i < mFail.GetNum(); i++) { if (t == mFail.ValueAtIndex(i)) return true; } return false; } Rule2Recursion* RecDetector::FindRule2Recursion(RuleTable *rule) { Rule2Recursion *map = NULL; for (unsigned i = 0; i < mRule2Recursions.GetNum(); i++) { Rule2Recursion *r2r = mRule2Recursions.ValueAtIndex(i); if (rule == r2r->mRule) { map = r2r; break; } } return map; } // Add 'rec' to the Rule2Recursion of 'rule' if not existing. void RecDetector::AddRule2Recursion(RuleTable *rule, Recursion *rec) { Rule2Recursion *map = FindRule2Recursion(rule); if (!map) { map = (Rule2Recursion*)gMemPool.Alloc(sizeof(Rule2Recursion)); new (map) Rule2Recursion(); map->mRule = rule; mRule2Recursions.PushBack(map); } // if the mapping already exists? bool found = false; for (unsigned i = 0; i < map->mRecursions.GetNum(); i++) { Recursion *r = map->mRecursions.ValueAtIndex(i); if (rec == r) { found = true; break; } } if (!found) { map->mRecursions.PushBack(rec); } } // There is a back edge from 'p' to the first appearance of 'rt'. Actually in our // traversal tree, in the current path (from 'p' upward to the root) there is one // and only node representing 'rt', which is the root. The successor of the back // edge is ignored. void RecDetector::AddRecursion(RuleTable *rt, ContTreeNode<RuleTable*> *p) { //std::cout << "Recursion in " << GetRuleTableName(rt) << std::endl; RecPath *path = (RecPath*)gMemPool.Alloc(sizeof(RecPath)); new (path) RecPath(); // Step 1. Traverse upwards to find the target tree node, and add the node // to the node_list. But the first to add is the back edge. ContTreeNode<RuleTable*> *target = NULL; ContTreeNode<RuleTable*> *node = p; SmallVector<RuleTable*> node_list; node_list.PushBack(rt); while (node) { if (node->GetData() == rt) { MASSERT(!target && "duplicated target node in a path."); target = node; break; } else { node_list.PushBack(node->GetData()); } node = node->GetParent(); } MASSERT(node_list.GetNum() > 0); MASSERT(target); MASSERT(target->GetData() == rt); // Step 2. Construct the path from target to 'p'. It's already in node_list, // and we simply read it in reverse order. Also find the index of // of each child rule in the parent rule. RuleTable *parent_rule = rt; for (int i = node_list.GetNum() - 1; i >= 0; i--) { RuleTable *child_rule = node_list.ValueAtIndex(i); unsigned index = 0; bool succ = RuleFindChildIndex(parent_rule, child_rule, index); MASSERT(succ && "Cannot find child rule in parent rule."); path->AddPos(index); parent_rule = child_rule; //std::cout << " child: " << GetRuleTableName(child_rule) << "@" << index << std::endl; } // Step 3. Get the right Recursion, Add the path to the Recursioin. Recursion *rec = FindOrCreateRecursion(rt); rec->AddPath(path); // Step 4. Add the Rule2Recursion mapping for (int i = node_list.GetNum() - 1; i >= 0; i--) { RuleTable *rule = node_list.ValueAtIndex(i); AddRule2Recursion(rule, rec); rec->AddRuleTable(rule); } } // Find the Recursion of 'rule'. // If Not found, create one. Recursion* RecDetector::FindOrCreateRecursion(RuleTable *rule) { for (unsigned i = 0; i < mRecursions.GetNum(); i++) { Recursion *rec = mRecursions.ValueAtIndex(i); if (rec->GetLead() == rule) return rec; } Recursion *rec = (Recursion*)gMemPool.Alloc(sizeof(Recursion)); new (rec) Recursion(); rec->SetLead(rule); mRecursions.PushBack(rec); return rec; } // 'done' is an IsDone node. // If 'p' can be reached from and to the recursion of 'done', add it to them. void RecDetector::HandleIsDoneRuleTable(RuleTable *done, ContTreeNode<RuleTable*> *p) { RuleTable *rule = p->GetData(); Rule2Recursion *map = FindRule2Recursion(done); if (map) { for (unsigned i = 0; i < map->mRecursions.GetNum(); i++) { Recursion *rec = map->mRecursions.ValueAtIndex(i); if (RuleReachable(rec->mLead, rule)) { AddRule2Recursion(rule, rec); rec->AddRuleTable(rule); } } } } TResult RecDetector::DetectRuleTable(RuleTable *rt, ContTreeNode<RuleTable*> *p) { // The children is done with traversal before. This means we need // stop here too, because all the further traversal from this point // have been done already. People may ask, what if I miss a recursion // from this rule table? The answer is you will never miss a single // one. Because any recursion including this rule will be found // the first time it's traversed. (We also addressed this at the // beginning of this file). // This guarantees there is one and only one recursion recorded for a loop // even if the loop has multiple nodes. // However, there is one complication scenario that we need take care. Please // see comments in BackPatch. if (IsDone(rt)) { return TRS_Done; } // If find a new Recursion, create the recursion. It is the successor of the // back edge. As mentioned in the comments in the beginning of this file, back // edge won't be furhter traversed as it is NOT part of the traversal tree. // // The key problem here is what value to return after AddRecursion(). The caller // does request a return value. We decided to return TRS_Fail because this is // the most possible value for a LeadNode of recursion. We actually don't expect // a lead node could be MaybeZero, which means it won't produce epsilon expression. if (IsInProcess(rt)) { AddRecursion(rt, p); return TRS_Fail; } else { mInProcess.PushBack(rt); } // Create new tree node. ContTreeNode<RuleTable*> *node = mTree.NewNode(rt, p); EntryType type = rt->mType; TResult res = TRS_MaybeZero; switch(type) { case ET_Oneof: res = DetectOneof(rt, node); break; case ET_Data: res = DetectData(rt, node); break; case ET_Zeroorone: case ET_Zeroormore: case ET_ASI: res = DetectZeroorXXX(rt, node); break; case ET_Concatenate: res = DetectConcatenate(rt, node); break; case ET_Null: default: MASSERT(0 && "Unexpected EntryType of rule."); break; } // Remove it from InProcess. MASSERT(IsInProcess(rt)); RuleTable *back = mInProcess.Back(); MASSERT(back == rt); mInProcess.PopBack(); // Add it to IsDone // It's clear that a node is push&pop in/off the stack just once, and then // it's set as IsDone. It's traversed only once. MASSERT(!IsDone(rt)); mDone.PushBack(rt); if (res == TRS_Fail) { MASSERT(!IsFail(rt)); mFail.PushBack(rt); } else if (res == TRS_MaybeZero) { MASSERT(!IsMaybeZero(rt)); mMaybeZero.PushBack(rt); } else { // It couldn't be TRS_Done or TRS_NA, since we already // handled TRS_Done in those DetectXXX(). MASSERT(0 && "Unexpected return result."); } return res; } // For Oneof rule, we try to detect for all its children if they are a rule table too. // 1. If there is one or more children are MaybeZero, the parent is MaybeZero // 2. Or the parent is Fail. // // No children will be put in ToDo, since all of them should be traversed. TResult RecDetector::DetectOneof(RuleTable *rule_table, ContTreeNode<RuleTable*> *p) { TResult result = TRS_NA; for (unsigned i = 0; i < rule_table->mNum; i++) { TableData *data = rule_table->mData + i; TResult temp_res = TRS_MaybeZero; RuleTable *child = NULL; if (data->mType == DT_Subtable) { child = data->mData.mEntry; temp_res = DetectRuleTable(child, p); } else { temp_res = TRS_Fail; } if (temp_res == TRS_MaybeZero) { result = TRS_MaybeZero; } else if (temp_res == TRS_Fail) { if (result != TRS_MaybeZero) result = TRS_Fail; } else if (temp_res == TRS_Done) { if (IsMaybeZero(child)) { result = TRS_MaybeZero; } else if (IsFail(child)) { if (result != TRS_MaybeZero) result = TRS_Fail; } else MASSERT(0 && "Unexpected result of done child."); } else MASSERT(0 && "Unexpected temp_res of child"); } return result; } // Zeroormore and Zeroorone and ASI has the same way to handle. TResult RecDetector::DetectZeroorXXX(RuleTable *rule_table, ContTreeNode<RuleTable*> *p) { TResult result = TRS_NA; MASSERT((rule_table->mNum == 1) && "zeroormore node has more than one elements?"); TableData *data = rule_table->mData; // For the non-table data, we just do nothing if (data->mType == DT_Subtable) { RuleTable *child = data->mData.mEntry; result = DetectRuleTable(child, p); } return TRS_MaybeZero; } TResult RecDetector::DetectData(RuleTable *rule_table, ContTreeNode<RuleTable*> *p) { TResult result = TRS_NA; RuleTable *child = NULL; MASSERT((rule_table->mNum == 1) && "Data node has more than one elements?"); TableData *data = rule_table->mData; if (data->mType == DT_Subtable) { child = data->mData.mEntry; result = DetectRuleTable(child, p); } else { result = TRS_Fail; } if (result == TRS_Done) { MASSERT(child); if (IsMaybeZero(child)) { MASSERT(!IsFail(child)); result = TRS_MaybeZero; } else if (IsFail(child)) { MASSERT(!IsMaybeZero(child)); result = TRS_Fail; } else { MASSERT(0 && "Child is not in any categories."); } } return result; } // The real challenge in left recursion detection is coming from Concatenate node. Before // we explain the details, we introduce three sets to keep rule table status. // ToDo : The main driver will walk on this list. Any rules which is encountered // in the traversal but we won't keep on traversing on it, will be put in // this todo list for later traversal. // InProcess: The rules are right now in the middle of traversal. This actually tells // the current working path of the DFS traversal. // Done : The rules that are finished. // The sum of the three sets is the total of rule tables. // And there is no overlapping among the three sets. // // We also elaborate a few rules which build the foundation of the algorithm. // // [Rule 1] // // E ---> '{' + E + '}', // |-> other rules // // It's obvious that E on RHS won't be considered as recursion child, and we can stop // at this point. The and parent rule will give up on it. // // [Rule 2] // // A ---> '{' + E + '}', // |-> other rules // // E on the RHS is not the first element. It won't be traversed at this DFS path. // The traversal stops at this point, and parent node will give up on this path. // But later we will work on it to see if there is recursion. So, E will be put into // ToDo list if it's not in Done or InProcess. // // Question is, what if the first element is not a token? // // [Rule 3] // // A ---> E + '}', // |-> other rules // // E is the first one. It always will go through the following traversal. // // [Rule 4] // // E ---> F + G, // |-> other rules // F ---> ZEROORMORE() // G ---> E + ... // // In this case F is an explicit ZeroorXXX() rule. E and G forms a left recursion. // Let's look at an even more complicated case. // // E ---> F + G, // |-> other rules // F ---> H // H ---> ZEROORMORE() // G ---> E + ... // // In this case F is an IMPLICIT ZeroorXXX() rule table. E and G form a left // recursion too. We cannot put G in ToDo list and give up the path. // Go further there are more complicated case like // // E ---> F + G, // |-> other rules // F ---> H // H ---> ZEROORMORE() + K // K ---> ZERORORMORE() // G ---> E + ... // // H is a ZeroorXXX() or not depends on all grand children's result. // // We introduce a set of TResult to indicate the result of a rule table. This is // corresponding to the three catagories of rule. // TRS_Fail: Definitely a fail for left recursion. Just stop here. // But the rest children could form some new recursions. // TRS_MaybeZero: The rule table could be empty. For a rule table, at the first // time it's traversed, we will save it to mMaybeZero if it's. // TRS_Done: This one is extra return result which doesn't have corresponding // rule catogeries of it. But the rule can be figured out by // checking IsFail() and IsMaybeZero(), because this // rule is done before. // Keep in mind, all TResult of leading elements are only used for determining // if the following element should be traversed, or just stop and put into ToDo list. // At any point when we want to return, we need take the remaining elements // to ToDo list, if they are not in any of InProcess, Done and ToDo. TResult RecDetector::DetectConcatenate(RuleTable *rule_table, ContTreeNode<RuleTable*> *p) { // We use 'res' to record the status of the leading children. TRS_MaybeZero is good // for the beginning as it means it's empty right now. TResult res = TRS_MaybeZero; TableData *data = rule_table->mData; RuleTable *child = NULL; // We accumulate and calculate the status from the beginning of the first child, and // make decision of the rest children accordingly. for (unsigned i = 0; i < rule_table->mNum; i++) { TableData *data = rule_table->mData + i; TResult temp_res = TRS_MaybeZero; child = NULL; if (data->mType == DT_Subtable) { child = data->mData.mEntry; temp_res = DetectRuleTable(child, p); } else { // Whenever we got a non-table child, eg. Token, the following children // won't be counted, and we return TRS_Fail at the end. temp_res = TRS_Fail; } MASSERT((res == TRS_MaybeZero)); if (temp_res == TRS_Fail) { // No matter how many leading children of MaybeZero, the first time // we get a Fail, the whole result is Fail. The rest children // cannot be traversed for these existing ancestors since they cannot // help form a LEFT recursion any more due to this Fail child. // However, we do need add them into ToDo list. res = TRS_Fail; AddToDo(rule_table, i+1); return res; } else if (temp_res == TRS_Done) { MASSERT(child); if (IsFail(child)) { res = TRS_Fail; AddToDo(rule_table, i+1); return res; } } } MASSERT(res == TRS_MaybeZero); return res; } // We start from the top tables. // Iterate until mToDo is empty. void RecDetector::Detect() { mDone.Clear(); SetupTopTables(); while(!mToDo.Empty()) { mInProcess.Clear(); mTree.Clear(); RuleTable *front = mToDo.Front(); mToDo.PopFront(); // It's possible that a rule is put in ToDo multiple times. So it's possible // the first instance IsDone while the second is still in ToDo. So is InProcess. if (!IsDone(front) && !IsInProcess(front)) DetectRuleTable(front, NULL); } // Back Patch // During TraverseRuleTable(), once we see a child IsDone(), we simply return. // This brings an issue that we may miss the opportunity to identify the parent // node as a Recursion Node. // Below is an example. // rule UnannClassType: ONEOF(Identifier + ZEROORONE(TypeArguments), // UnannClassOrInterfaceType + '.' + ...) // rule UnannClassOrInterfaceType: ONEOF(UnannClassType, UnannInterfaceType) // rule UnannInterfaceType : UnannClassType // // These rules form a recursion where there are 2 paths. During recdetect traversal // UnannClassOrInterfaceType is the first to hit and becomes the LeadNode. // The problem is when handling the edge UnannClassOrInterfaceType --> UnannClassType, // we find the first path, and UnannClassType becomes IsDone. Now, we need deal // with UnannClassOrInterfaceType --> UnannInterfaceType, but UnannClassType which // is the child of UnannInterfaceType is IsDone. // Why we do it after DetectRuleTable is completely done? We need the complete // information of IsDone, MaybeZero, Fail, which can be available only after all // DetectRuleTable is done. mChanged = true; while(mChanged) { mChanged = false; mDone.Clear(); mToDo.Clear(); SetupTopTables(); while(!mToDo.Empty()) { RuleTable *front = mToDo.Front(); mToDo.PopFront(); if (!IsDone(front)) { BackPatch(front); mDone.PushBack(front); } } } } // The algorithm is simple, we only check the direct children to see if they are // in some recursion which 'parent' is not in or not in the same group. void RecDetector::BackPatch(RuleTable *parent) { Rule2Recursion *parent_r2r = FindRule2Recursion(parent); Rule2Recursion *child_r2r = NULL; for (unsigned i = 0; i < parent->mNum; i++) { TableData *data = parent->mData + i; if (data->mType == DT_Subtable) { RuleTable *child = data->mData.mEntry; // add child to ToDo list if (!IsDone(child)) mToDo.PushBack(child); child_r2r = FindRule2Recursion(child); if (!child_r2r) continue; // If parent and child share some recursion, we skip bool found = false; for (unsigned j = 0; parent_r2r && (j < parent_r2r->mRecursions.GetNum()); j++) { Recursion *pr = parent_r2r->mRecursions.ValueAtIndex(j); for (unsigned k = 0; k < child_r2r->mRecursions.GetNum(); k++) { Recursion *cr = child_r2r->mRecursions.ValueAtIndex(k); if (cr == pr) { found = true; break; } } if (found) break; } if (found) continue; // Now they are sharing any common recursion, and child has its // exclusive recursions. bool lr_reachable = false; for (unsigned k = 0; k < child_r2r->mRecursions.GetNum(); k++) { Recursion *rec = child_r2r->mRecursions.ValueAtIndex(k); RuleTable *lead = rec->GetLead(); lr_reachable = LRReachable(lead, parent) && LRReachable(parent, child); // Adding parent to one of recursion is good enough. Don't need add // to all appropriate recursions since they will be grouped together // later and parsing is on group unit. if (lr_reachable) { AddRule2Recursion(parent, rec); rec->AddRuleTable(parent); mChanged = true; } } } } } // If there is a path from 'from' to 'to', and it's LeftRecursive reachable which // means 'from' to 'to' could be a left recursion valid path. // // Left Recursive Reachable is the fundamental idea of building recursion group. // We look for recursion group and parse on the groups like waves moving forward. // A non-left-recursive reachable group breaks this moving since it goes the different // tokens. bool RecDetector::LRReachable(RuleTable *from, RuleTable *to) { bool found = false; SmallList<RuleTable*> working_list; SmallVector<RuleTable*> done_list; working_list.PushBack(from); while (!working_list.Empty()) { RuleTable *rt = working_list.Front(); working_list.PopFront(); if (rt == to) { found = true; break; } bool is_done = false; for (unsigned i = 0; i < done_list.GetNum(); i++) { if (rt == done_list.ValueAtIndex(i)) { is_done = true; break; } } if (is_done) continue; EntryType type = rt->mType; switch(type) { case ET_Oneof: { // Add all table children to working list. for (unsigned i = 0; i < rt->mNum; i++) { TableData *data = rt->mData + i; if (data->mType == DT_Subtable) { RuleTable *child = data->mData.mEntry; working_list.PushBack(child); } } break; } case ET_Zeroorone: case ET_Zeroormore: case ET_ASI: case ET_Data: { MASSERT(rt->mNum == 1); TableData *data = rt->mData; if (data->mType == DT_Subtable) { RuleTable *child = data->mData.mEntry; working_list.PushBack(child); } break; } case ET_Concatenate: { for (unsigned i = 0; i < rt->mNum; i++) { TableData *data = rt->mData + i; // If the child is not a rule table, all the rest children // including this one are not left recursive legitimate. if (data->mType != DT_Subtable) break; RuleTable *child = data->mData.mEntry; working_list.PushBack(child); // If 'child' is not MaybeZero, the rest children are // not left recursive legitimate. if (!IsMaybeZero(child)) break; } break; } case ET_Null: default: MASSERT(0 && "Unexpected EntryType of rule."); break; } done_list.PushBack(rt); } return found; } // Return the RecursionGroup if there is one containing 'rec'. RecursionGroup* RecDetector::FindRecursionGroup(Recursion *rec) { RecursionGroup *group = NULL; for (unsigned i = 0; i < mRecursionGroups.GetNum(); i++) { RecursionGroup *rg = mRecursionGroups.ValueAtIndex(i); for (unsigned j = 0; j < rg->mRecursions.GetNum(); j++) { Recursion *r = rg->mRecursions.ValueAtIndex(j); if (rec == r) { group = rg; break; } } if (group) break; } return group; } // We are iterate the recursions in order. It has two level of iterations. // In this algorithm, // 1. The recursion which doesn't belong to any existing group is always // the one to create its group. // 2. All recursions of a group can be identified in just one single // inner iteration. void RecDetector::DetectGroups() { for (unsigned i = 0; i < mRecursions.GetNum(); i++) { Recursion *rec_i = mRecursions.ValueAtIndex(i); RecursionGroup *group_i = FindRecursionGroup(rec_i); // It's already done. if (group_i) continue; group_i = new RecursionGroup(); group_i->AddRecursion(rec_i); mRecursionGroups.PushBack(group_i); for (unsigned j = i + 1; j < mRecursions.GetNum(); j++) { Recursion *rec_j = mRecursions.ValueAtIndex(j); if (LRReachable(rec_i->GetLead(), rec_j->GetLead()) && LRReachable(rec_j->GetLead(), rec_i->GetLead())) { RecursionGroup *group_j = FindRecursionGroup(rec_j); MASSERT(!group_j); group_i->AddRecursion(rec_j); } } } // Build the rule2group for (unsigned i = 0; i < mRecursionGroups.GetNum(); i++) { RecursionGroup *group = mRecursionGroups.ValueAtIndex(i); for (unsigned j = 0; j < group->mRecursions.GetNum(); j++) { Recursion *rec = group->mRecursions.ValueAtIndex(j); for (unsigned k = 0; k < rec->mRuleTables.GetNum(); k++) { RuleTable *rt = rec->mRuleTables.ValueAtIndex(k); // Duplication is checked in AddRule2Group(). AddRule2Group(rt, group); } } } } void RecDetector::AddRule2Group(RuleTable *rt, RecursionGroup *group) { bool found = false; for (unsigned i = 0; i < mRule2Group.GetNum(); i++) { Rule2Group r2g = mRule2Group.ValueAtIndex(i); if ((r2g.mRuleTable == rt) && (r2g.mGroup == group)) { found = true; break; } } if (found) return; Rule2Group r2g = {rt, group}; mRule2Group.PushBack(r2g); } // The reason I have a Release() is to make sure the destructors of Recursion and Paths // are invoked ahead of destructor of gMemPool. void RecDetector::Release() { for (unsigned i = 0; i < mRecursions.GetNum(); i++) { Recursion *rec = mRecursions.ValueAtIndex(i); rec->Release(); } for (unsigned i = 0; i < mRule2Recursions.GetNum(); i++) { Rule2Recursion *map = mRule2Recursions.ValueAtIndex(i); map->Release(); } for (unsigned i = 0; i < mRecursionGroups.GetNum(); i++) { RecursionGroup *rg = mRecursionGroups.ValueAtIndex(i); rg->Release(); } mRule2Recursions.Release(); mRecursions.Release(); mRecursionGroups.Release(); mToDo.Release(); mInProcess.Release(); mDone.Release(); mMaybeZero.Release(); mFail.Release(); mTree.Release(); } // The header file would be java/include/gen_recursion.h. void RecDetector::WriteHeaderFile() { mHeaderFile->WriteOneLine("#ifndef __GEN_RECUR_H__", 23); mHeaderFile->WriteOneLine("#define __GEN_RECUR_H__", 23); mHeaderFile->WriteOneLine("#include \"recursion.h\"", 22); mHeaderFile->WriteOneLine("#endif", 6); } void RecDetector::WriteCppFile() { mCppFile->WriteOneLine("#include \"gen_recursion.h\"", 26); mCppFile->WriteOneLine("#include \"common_header_autogen.h\"", 34); mCppFile->WriteOneLine("namespace maplefe {", 19); //Step 1. Dump paths of a rule table's recursions. // unsigned tablename_path_1[N]={1, 2, ...}; // unsigned tablename_path_2[M]={1, 2, ...}; // unsigned *tablename_path_list[2] = {tablename_path_1, tablename_path_2}; // LeftRecursion tablename_rec = {&Tbltablename, 2, tablename_path_list}; for (unsigned i = 0; i < mRecursions.GetNum(); i++) { Recursion *rec = mRecursions.ValueAtIndex(i); const char *tablename = GetRuleTableName(rec->GetLead()); // dump comment of tablename std::string comment("// "); comment += tablename; mCppFile->WriteOneLine(comment.c_str(), comment.size()); // dump : unsigned tablename_path_1[N]={1, 2, ...}; for (unsigned j = 0; j < rec->PathsNum(); j++) { RecPath *path = rec->GetPath(j); std::string path_str = "unsigned "; path_str += tablename; path_str += "_path_"; std::string index_str = std::to_string(j); path_str += index_str; path_str += "["; // As mentioned in recursion.h, we put the #elem in the first element // tell the users of the array length. std::string num_str = std::to_string(path->PositionsNum()+1); path_str += num_str; path_str += "]= {"; num_str = std::to_string(path->PositionsNum()); path_str += num_str; path_str += ","; std::string path_dump = path->DumpToString(); path_str += path_dump; path_str += "};"; mCppFile->WriteOneLine(path_str.c_str(), path_str.size()); } // to dump // unsigned *tablename_path_list[2] = {tablename_path_1, tablename_path_2}; std::string path_list = "unsigned *"; path_list += tablename; path_list += "_path_list["; std::string num_str = std::to_string(rec->PathsNum()); path_list += num_str; path_list += "]={"; for (unsigned j = 0; j < rec->PathsNum(); j++) { std::string path_str; path_str += tablename; path_str += "_path_"; std::string index_str = std::to_string(j); path_str += index_str; if (j < rec->PathsNum() - 1) path_str += ","; path_list += path_str; } path_list += "};"; mCppFile->WriteOneLine(path_list.c_str(), path_list.size()); // dump // LeftRecursion tablename_rec = {&Tbltablename, 2, tablename_path_list}; std::string rec_str = "LeftRecursion "; rec_str += tablename; rec_str += "_rec = {&"; rec_str += tablename; rec_str += ", "; rec_str += num_str, rec_str += ", "; rec_str += tablename; rec_str += "_path_list};"; mCppFile->WriteOneLine(rec_str.c_str(), rec_str.size()); } // Step 2. Dump num of Recursions mCppFile->WriteOneLine("// Total recursions", 19); std::string s = "unsigned gLeftRecursionsNum="; std::string num = std::to_string(mRecursions.GetNum()); s += num; s += ';'; mCppFile->WriteOneLine(s.c_str(), s.size()); // Step 3. dump all the recursions array, as below // Recusion* TotalRecursions[N] = {&tablename_rec, &tablename_rec, ...}; // Recursion **gLeftRecursions = TotalRecursions; std::string total_str = "LeftRecursion* TotalRecursions["; std::string num_rec = std::to_string(mRecursions.GetNum()); total_str += num_rec; total_str += "] = {"; for (unsigned i = 0; i < mRecursions.GetNum(); i++) { Recursion *rec = mRecursions.ValueAtIndex(i); const char *tablename = GetRuleTableName(rec->GetLead()); total_str += "&"; total_str += tablename; total_str += "_rec"; if (i < mRecursions.GetNum() - 1) total_str += ", "; } total_str += "};"; mCppFile->WriteOneLine(total_str.c_str(), total_str.size()); std::string last_str = "LeftRecursion **gLeftRecursions = TotalRecursions;"; mCppFile->WriteOneLine(last_str.c_str(), last_str.size()); // Step 4. Write RecursionGroups last_str = "///////////////////////////////////////////////////////////////"; mCppFile->WriteOneLine(last_str.c_str(), last_str.size()); last_str = "// RecursionGroup //"; mCppFile->WriteOneLine(last_str.c_str(), last_str.size()); last_str = "///////////////////////////////////////////////////////////////"; mCppFile->WriteOneLine(last_str.c_str(), last_str.size()); WriteRecursionGroups(); // step 5. Write Rule2Recursion mapping. last_str = "///////////////////////////////////////////////////////////////"; mCppFile->WriteOneLine(last_str.c_str(), last_str.size()); last_str = "// Ruel2Recursion //"; mCppFile->WriteOneLine(last_str.c_str(), last_str.size()); last_str = "///////////////////////////////////////////////////////////////"; mCppFile->WriteOneLine(last_str.c_str(), last_str.size()); WriteRule2Recursion(); // step 6. Write Rule2Group mapping. last_str = "///////////////////////////////////////////////////////////////"; mCppFile->WriteOneLine(last_str.c_str(), last_str.size()); last_str = "// Ruel2Group //"; mCppFile->WriteOneLine(last_str.c_str(), last_str.size()); last_str = "///////////////////////////////////////////////////////////////"; mCppFile->WriteOneLine(last_str.c_str(), last_str.size()); WriteRule2Group(); // step 7. Write Group2Rule mapping. last_str = "///////////////////////////////////////////////////////////////"; mCppFile->WriteOneLine(last_str.c_str(), last_str.size()); last_str = "// Group2Rule //"; mCppFile->WriteOneLine(last_str.c_str(), last_str.size()); last_str = "///////////////////////////////////////////////////////////////"; mCppFile->WriteOneLine(last_str.c_str(), last_str.size()); WriteGroup2Rule(); mCppFile->WriteOneLine("}", 1); } // unsigned gRecursionGroupsNum = N; // unsigned group_sizes[N] = {1,2,...}; // unsigned *gRecursionGroupSizes = group_sizes; // LeftRecursion *RecursionGroup_1[1] = {&TblPrimary_rec, ...}; // LeftRecursion *RecursionGroup_2[1] = {&TblPrimary_rec, ...}; // LeftRecursion **recursion_groups[N] = {RecursionGroup_1, RecursionGroup_2...}; // LeftRecursion ***gRecursionGroups = recursion_groups; void RecDetector::WriteRecursionGroups() { // groups num std::string groups_num = "unsigned gRecursionGroupsNum = "; std::string num_str = std::to_string(mRecursionGroups.GetNum()); groups_num += num_str; groups_num += ";"; mCppFile->WriteOneLine(groups_num.c_str(), groups_num.size()); // group sizes std::string group_sizes = "unsigned group_sizes["; group_sizes += num_str; group_sizes += "] = {"; for (unsigned i = 0; i < mRecursionGroups.GetNum(); i++) { RecursionGroup *rg = mRecursionGroups.ValueAtIndex(i); unsigned size = rg->mRecursions.GetNum(); std::string size_str = std::to_string(size); group_sizes += size_str; if (i != (mRecursionGroups.GetNum() - 1)) group_sizes += ","; } group_sizes += "};"; mCppFile->WriteOneLine(group_sizes.c_str(), group_sizes.size()); group_sizes = "unsigned *gRecursionGroupSizes = group_sizes;"; mCppFile->WriteOneLine(group_sizes.c_str(), group_sizes.size()); // LeftRecursion *RecursionGroup_1[1] = {&TblPrimary_rec, ...}; // LeftRecursion *RecursionGroup_2[1] = {&TblPrimary_rec, ...}; for (unsigned i = 0; i < mRecursionGroups.GetNum(); i++) { std::string group = "LeftRecursion *RecursionGroup_"; std::string i_str = std::to_string(i); group += i_str; group += "["; RecursionGroup *rg = mRecursionGroups.ValueAtIndex(i); unsigned size = rg->mRecursions.GetNum(); i_str = std::to_string(size); group += i_str; group += "] = {"; for (unsigned j = 0; j < rg->mRecursions.GetNum(); j++) { Recursion *rec = rg->mRecursions.ValueAtIndex(j); RuleTable *rule_table = rec->GetLead(); const char *name = GetRuleTableName(rule_table); group += "&"; group += name; group += "_rec"; if (j < (rg->mRecursions.GetNum() - 1)) group += ","; } group += "};"; mCppFile->WriteOneLine(group.c_str(), group.size()); } // LeftRecursion **recursion_groups[N] = {RecursionGroup_1, RecursionGroup_2...}; // LeftRecursion ***gRecursionGroups = recursion_groups; std::string final_groups = "LeftRecursion **recursion_groups["; final_groups += num_str; final_groups += "] = {"; for (unsigned i = 0; i < mRecursionGroups.GetNum(); i++) { final_groups += "RecursionGroup_"; std::string i_str = std::to_string(i); final_groups += i_str; if (i < (mRecursionGroups.GetNum() - 1)) final_groups += ","; } final_groups += "};"; mCppFile->WriteOneLine(final_groups.c_str(), final_groups.size()); final_groups = "LeftRecursion ***gRecursionGroups = recursion_groups;"; mCppFile->WriteOneLine(final_groups.c_str(), final_groups.size()); } // We want to dump like below. // unsigned gRule2GroupNum = X; // void RecDetector::WriteRule2Group() { std::string comment = "// Rule2Group mapping"; mCppFile->WriteOneLine(comment.c_str(), comment.size()); std::string groups_num = "unsigned gRule2GroupNum = "; std::string num_str = std::to_string(mRule2Group.GetNum()); groups_num += num_str; groups_num += ";"; mCppFile->WriteOneLine(groups_num.c_str(), groups_num.size()); std::string groups = "int rule2group["; groups += std::to_string(RuleTableNum); groups += "] = {"; for (unsigned rt_idx = 0; rt_idx < RuleTableNum; rt_idx++) { const RuleTable *rt_target = gRuleTableSummarys[rt_idx].mAddr; bool found = false; RecursionGroup *group = NULL; for (unsigned i = 0; i < mRule2Group.GetNum(); i++) { Rule2Group r2g = mRule2Group.ValueAtIndex(i); RuleTable *rt = r2g.mRuleTable; if (rt == rt_target) { found = true; group = r2g.mGroup; break; } } if (found) { // find the index of group. int index = -1; for (unsigned j = 0; j < mRecursionGroups.GetNum(); j++) { if (group == mRecursionGroups.ValueAtIndex(j)) { index = j; break; } } MASSERT(index >= 0); std::string id_str = std::to_string(index); groups += id_str; } else { groups += "-1"; } if (rt_idx < RuleTableNum - 1) groups += ", "; } // The ending groups += "};"; mCppFile->WriteOneLine(groups.c_str(), groups.size()); groups = "int *gRule2Group = rule2group;"; mCppFile->WriteOneLine(groups.c_str(), groups.size()); } // Dump group to rule mapping. // RuleTable* RuleTableArray_1[] = {&TblStatement,...} // RuleTable* RuleTableArray_2[] = {&TblStatement,...} // ... // Group2Rule gGroup2Rule[num of groups] = { // {1, RuleTableArray_1}, // {1, RuleTableArray_2}, // }; void RecDetector::WriteGroup2Rule() { SmallVector<unsigned> group2rule_num; for (unsigned i = 0; i < mRecursionGroups.GetNum(); i++) { std::string array = "RuleTable* RuleTableArray_"; std::string i_str = std::to_string(i); array += i_str; array += "[] = {"; RecursionGroup *target_group = mRecursionGroups.ValueAtIndex(i); unsigned num = 0; for (unsigned r2g_idx = 0; r2g_idx < mRule2Group.GetNum(); r2g_idx++) { Rule2Group r2g = mRule2Group.ValueAtIndex(r2g_idx); RuleTable *rule = r2g.mRuleTable; RecursionGroup *group = r2g.mGroup; if (group == target_group) { num++; const char *tablename = GetRuleTableName(rule); array += "&"; array += tablename; array += ", "; } } MASSERT(num > 0); group2rule_num.PushBack(num); array += "};"; mCppFile->WriteOneLine(array.c_str(), array.size()); } // Group2Rule gGroup2Rule[num of groups] = { std::string group2rule = "Group2Rule ggroup2rule["; std::string g_num_str = std::to_string(mRecursionGroups.GetNum()); group2rule += g_num_str; group2rule += "] = {"; mCppFile->WriteOneLine(group2rule.c_str(), group2rule.size()); for (unsigned i = 0; i < mRecursionGroups.GetNum(); i++) { group2rule = "{"; std::string i_str = std::to_string(i); std::string num_str = std::to_string(group2rule_num.ValueAtIndex(i)); group2rule += num_str; group2rule += ", RuleTableArray_"; group2rule += i_str; group2rule += "},"; mCppFile->WriteOneLine(group2rule.c_str(), group2rule.size()); } group2rule = "};"; mCppFile->WriteOneLine(group2rule.c_str(), group2rule.size()); group2rule = "Group2Rule *gGroup2Rule = ggroup2rule;"; mCppFile->WriteOneLine(group2rule.c_str(), group2rule.size()); } // Dump rule2recursion mapping, as below // LeftRecursion *TblPrimary_r2r_data[2] = {&TblPrimary_rec, &TblBinary_rec}; // Rule2Recursion TblPrimary_r2r = {&TblPrimary, 2, TblPrimary_r2r_data}; // .... // Rule2Recursion *arrayRule2Recursion[yyy] = {&TblPrimary_r2r, &TblTypeOrPackNam_r2r,...} // gRule2RecursionNum = xxx; // Rule2Recursion **gRule2Recursion = arrayRule2Recursion; void RecDetector::WriteRule2Recursion() { std::string comment = "// Rule2Recursion mapping"; mCppFile->WriteOneLine(comment.c_str(), comment.size()); // Step 1. Write each r2r data. for (unsigned i = 0; i < mRule2Recursions.GetNum(); i++) { // Dump: // LeftRecursion *TblPrimary_r2r_data[2] = {&TblPrimary_rec, &TblBinary_rec}; Rule2Recursion *r2r = mRule2Recursions.ValueAtIndex(i); const char *tablename = GetRuleTableName(r2r->mRule); std::string dump = "LeftRecursion *"; dump += tablename; dump += "_r2r_data["; std::string num = std::to_string(r2r->mRecursions.GetNum()); dump += num; dump += "] = {"; // get the list of recursions. std::string lr_str; for (unsigned j = 0; j < r2r->mRecursions.GetNum(); j++) { Recursion *lr = r2r->mRecursions.ValueAtIndex(j); lr_str += "&"; const char *n = GetRuleTableName(lr->GetLead()); lr_str += n; lr_str += "_rec"; if (j < (r2r->mRecursions.GetNum() - 1)) lr_str += ","; } dump += lr_str; dump += "};"; mCppFile->WriteOneLine(dump.c_str(), dump.size()); // Dump: // Rule2Recursion TblPrimary_r2r = {&TblPrimary, 2, TblPrimary_r2r_data}; dump = "Rule2Recursion "; dump += tablename; dump += "_r2r = {&"; dump += tablename; dump += ", "; dump += num; dump += ", "; dump += tablename; dump += "_r2r_data};"; mCppFile->WriteOneLine(dump.c_str(), dump.size()); } // Step 2. Write arryRule2Recursion as below // Rule2Recursion *arrayRule2Recursion[yyy] = {&TblPrimary_r2r, &TblTypeOrPackNam_r2r,...} std::string dump = "Rule2Recursion *arrayRule2Recursion["; std::string num = std::to_string(mRule2Recursions.GetNum()); dump += num; dump += "] = {"; std::string r2r_list; for (unsigned i = 0; i < mRule2Recursions.GetNum(); i++) { // &TblPrimary_rec, &TblBinary_rec, .. Rule2Recursion *r2r = mRule2Recursions.ValueAtIndex(i); const char *tablename = GetRuleTableName(r2r->mRule); r2r_list += "&"; r2r_list += tablename; r2r_list += "_r2r"; if (i < (mRule2Recursions.GetNum() - 1)) r2r_list += ", "; } dump += r2r_list; dump += "};"; mCppFile->WriteOneLine(dump.c_str(), dump.size()); // Step 3. Write gRule2RecursionNum and gRule2Recursion // gRule2RecursionNum = xxx; // Rule2Recursion **gRule2Recursion = arrayRule2Recursion; dump = "unsigned gRule2RecursionNum = "; dump += num; dump += ";"; mCppFile->WriteOneLine(dump.c_str(), dump.size()); dump = "Rule2Recursion **gRule2Recursion = arrayRule2Recursion;"; mCppFile->WriteOneLine(dump.c_str(), dump.size()); } // Write the recursion to java/gen_recursion.h and java/gen_recursion.cpp void RecDetector::Write() { std::string lang_path("../gen/"); std::string file_name = lang_path + "genmore_recursion.cpp"; mCppFile = new Write2File(file_name); file_name = lang_path + "gen_recursion.h"; mHeaderFile = new Write2File(file_name); WriteHeaderFile(); WriteCppFile(); delete mCppFile; delete mHeaderFile; } } int main(int argc, char *argv[]) { maplefe::gMemPool.SetBlockSize(4096); maplefe::RecDetector dtc; dtc.Detect(); dtc.DetectGroups(); dtc.Write(); dtc.Release(); return 0; }
33.415584
94
0.621324
venshine
819474638dc5b1cca9837569cd09459ab6c47db7
2,199
cpp
C++
src/cpp/wkbreader.cpp
sanak/node-geos-c
7cd965a72627e6a9034c3e2bdb9f9acc5057f868
[ "MIT" ]
19
2015-01-25T16:50:48.000Z
2021-08-17T11:34:34.000Z
src/cpp/wkbreader.cpp
sanak/node-geos-c
7cd965a72627e6a9034c3e2bdb9f9acc5057f868
[ "MIT" ]
8
2016-03-23T18:29:47.000Z
2022-01-04T07:18:26.000Z
src/cpp/wkbreader.cpp
sanak/node-geos
7cd965a72627e6a9034c3e2bdb9f9acc5057f868
[ "MIT" ]
9
2015-02-04T03:52:40.000Z
2020-10-11T07:11:02.000Z
#include "wkbreader.hpp" #include <sstream> WKBReader::WKBReader() { _reader = new geos::io::WKBReader(); } WKBReader::WKBReader(const geos::geom::GeometryFactory *gf) { _reader = new geos::io::WKBReader(*gf); } WKBReader::~WKBReader() {} Persistent<Function> WKBReader::constructor; void WKBReader::Initialize(Handle<Object> target) { Isolate* isolate = Isolate::GetCurrent(); HandleScope scope(isolate); Local<FunctionTemplate> tpl = FunctionTemplate::New(isolate, WKBReader::New); tpl->InstanceTemplate()->SetInternalFieldCount(1); tpl->SetClassName(String::NewFromUtf8(isolate, "WKBReader")); NODE_SET_PROTOTYPE_METHOD(tpl, "readHEX", WKBReader::ReadHEX); constructor.Reset(isolate, tpl->GetFunction()); target->Set(String::NewFromUtf8(isolate, "WKBReader"), tpl->GetFunction()); } void WKBReader::New(const FunctionCallbackInfo<Value>& args) { Isolate* isolate = Isolate::GetCurrent(); HandleScope scope(isolate); WKBReader *wkbReader; if(args.Length() == 1) { GeometryFactory *factory = ObjectWrap::Unwrap<GeometryFactory>(args[0]->ToObject()); wkbReader = new WKBReader(factory->_factory); } else { wkbReader = new WKBReader(); } wkbReader->Wrap(args.This()); args.GetReturnValue().Set(args.This()); } void WKBReader::ReadHEX(const FunctionCallbackInfo<Value>& args) { Isolate* isolate = Isolate::GetCurrent(); HandleScope scope(isolate); WKBReader* reader = ObjectWrap::Unwrap<WKBReader>(args.This()); String::Utf8Value hex(args[0]->ToString()); std::string str = std::string(*hex); std::istringstream is( str ); try { geos::geom::Geometry* geom = reader->_reader->readHEX(is); args.GetReturnValue().Set(Geometry::New(geom)); } catch (geos::io::ParseException e) { isolate->ThrowException(Exception::Error(String::NewFromUtf8(isolate, e.what()))); } catch (geos::util::GEOSException e) { isolate->ThrowException(Exception::Error(String::NewFromUtf8(isolate, e.what()))); } catch (...) { isolate->ThrowException(Exception::Error(String::NewFromUtf8(isolate, "Exception while reading WKB."))); } }
31.414286
112
0.678035
sanak
819573b70a5710b3ef86fc2f10db4ffbecb23301
1,148
cpp
C++
Engine/Plugins/Runtime/SoundUtilities/Source/SoundUtilitiesEditor/Private/SoundUtilitiesEditorModule.cpp
windystrife/UnrealEngine_NVIDIAGameWork
b50e6338a7c5b26374d66306ebc7807541ff815e
[ "MIT" ]
1
2022-01-29T18:36:12.000Z
2022-01-29T18:36:12.000Z
Engine/Plugins/Runtime/SoundUtilities/Source/SoundUtilitiesEditor/Private/SoundUtilitiesEditorModule.cpp
windystrife/UnrealEngine_NVIDIAGameWork
b50e6338a7c5b26374d66306ebc7807541ff815e
[ "MIT" ]
null
null
null
Engine/Plugins/Runtime/SoundUtilities/Source/SoundUtilitiesEditor/Private/SoundUtilitiesEditorModule.cpp
windystrife/UnrealEngine_NVIDIAGameWork
b50e6338a7c5b26374d66306ebc7807541ff815e
[ "MIT" ]
null
null
null
// Copyright 1998-2017 Epic Games, Inc. All Rights Reserved. #include "SoundUtilitiesEditorModule.h" #include "CoreMinimal.h" #include "Stats/Stats.h" #include "Modules/ModuleInterface.h" #include "Modules/ModuleManager.h" #include "AssetToolsModule.h" #include "AssetTypeActions_SoundSimple.h" #include "AssetTypeActions_Base.h" #include "AudioEditorModule.h" IMPLEMENT_MODULE(FSoundUtilitiesEditorModule, FSynthesisEditor) void FSoundUtilitiesEditorModule::StartupModule() { SoundWaveAssetActionExtender = TSharedPtr<ISoundWaveAssetActionExtensions>(new FSoundWaveAssetActionExtender()); IAssetTools& AssetTools = FModuleManager::LoadModuleChecked<FAssetToolsModule>("AssetTools").Get(); // Now that we've loaded this module, we need to register our effect preset actions IAudioEditorModule* AudioEditorModule = &FModuleManager::LoadModuleChecked<IAudioEditorModule>("AudioEditor"); AudioEditorModule->AddSoundWaveActionExtender(SoundWaveAssetActionExtender); // Register asset actions AssetTools.RegisterAssetTypeActions(MakeShareable(new FAssetTypeActions_SoundSimple)); } void FSoundUtilitiesEditorModule::ShutdownModule() { }
33.764706
113
0.827526
windystrife
819684a2218044976d61e1c21b2892b23c0875a5
2,848
cpp
C++
algorithms/0100_same_tree/solution.cpp
GambuzX/LeetCode
8cd60debb906579ccb6936a69aaa3cc13d2dce8d
[ "MIT" ]
null
null
null
algorithms/0100_same_tree/solution.cpp
GambuzX/LeetCode
8cd60debb906579ccb6936a69aaa3cc13d2dce8d
[ "MIT" ]
null
null
null
algorithms/0100_same_tree/solution.cpp
GambuzX/LeetCode
8cd60debb906579ccb6936a69aaa3cc13d2dce8d
[ "MIT" ]
null
null
null
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: bool isSameTree(TreeNode* p, TreeNode* q) { stack<TreeNode*> s1; stack<TreeNode*> s2; if (p != NULL) s1.push(p); if (q != NULL) s2.push(q); while(!s1.empty() && !s2.empty()) { TreeNode* t1 = s1.top(); TreeNode* t2 = s2.top(); s1.pop(); s2.pop(); if (t1 == NULL && t2 == NULL) continue; if (t1 == NULL || t2 == NULL) return false; if (t1->val != t2->val) return false; s1.push(t1->right); s1.push(t1->left); s2.push(t2->right); s2.push(t2->left); } return s1.empty() && s2.empty(); } }; void trimLeftTrailingSpaces(string &input) { input.erase(input.begin(), find_if(input.begin(), input.end(), [](int ch) { return !isspace(ch); })); } void trimRightTrailingSpaces(string &input) { input.erase(find_if(input.rbegin(), input.rend(), [](int ch) { return !isspace(ch); }).base(), input.end()); } TreeNode* stringToTreeNode(string input) { trimLeftTrailingSpaces(input); trimRightTrailingSpaces(input); input = input.substr(1, input.length() - 2); if (!input.size()) { return nullptr; } string item; stringstream ss; ss.str(input); getline(ss, item, ','); TreeNode* root = new TreeNode(stoi(item)); queue<TreeNode*> nodeQueue; nodeQueue.push(root); while (true) { TreeNode* node = nodeQueue.front(); nodeQueue.pop(); if (!getline(ss, item, ',')) { break; } trimLeftTrailingSpaces(item); if (item != "null") { int leftNumber = stoi(item); node->left = new TreeNode(leftNumber); nodeQueue.push(node->left); } if (!getline(ss, item, ',')) { break; } trimLeftTrailingSpaces(item); if (item != "null") { int rightNumber = stoi(item); node->right = new TreeNode(rightNumber); nodeQueue.push(node->right); } } return root; } string boolToString(bool input) { return input ? "True" : "False"; } int main() { string line; while (getline(cin, line)) { TreeNode* p = stringToTreeNode(line); getline(cin, line); TreeNode* q = stringToTreeNode(line); bool ret = Solution().isSameTree(p, q); string out = boolToString(ret); cout << out << endl; } return 0; }
24.135593
79
0.499298
GambuzX
8196c292c22d7abf127a7afbe219296c7696d64f
18,247
cpp
C++
SpatialGDK/Source/SpatialGDK/Private/Utils/SpatialDebugger.cpp
Bowbee/GDKPrebuilt
420b3fa19fdc36755a43e655c057b5624264407a
[ "MIT" ]
363
2018-07-30T12:57:42.000Z
2022-03-25T14:30:28.000Z
SpatialGDK/Source/SpatialGDK/Private/Utils/SpatialDebugger.cpp
Bowbee/GDKPrebuilt
420b3fa19fdc36755a43e655c057b5624264407a
[ "MIT" ]
1,634
2018-07-30T14:30:25.000Z
2022-03-03T01:55:15.000Z
SpatialGDK/Source/SpatialGDK/Private/Utils/SpatialDebugger.cpp
Bowbee/GDKPrebuilt
420b3fa19fdc36755a43e655c057b5624264407a
[ "MIT" ]
153
2018-07-31T13:45:02.000Z
2022-03-03T05:20:24.000Z
// Copyright (c) Improbable Worlds Ltd, All Rights Reserved #include "Utils/SpatialDebugger.h" #include "EngineClasses/SpatialNetDriver.h" #include "Interop/SpatialReceiver.h" #include "Interop/SpatialSender.h" #include "Interop/SpatialStaticComponentView.h" #include "LoadBalancing/GridBasedLBStrategy.h" #include "LoadBalancing/LayeredLBStrategy.h" #include "LoadBalancing/WorkerRegion.h" #include "Schema/AuthorityIntent.h" #include "Schema/SpatialDebugging.h" #include "SpatialCommonTypes.h" #include "Utils/InspectionColors.h" #include "Debug/DebugDrawService.h" #include "Engine/Engine.h" #include "GameFramework/Pawn.h" #include "GameFramework/PlayerController.h" #include "GameFramework/PlayerState.h" #include "GenericPlatform/GenericPlatformMath.h" #include "Kismet/GameplayStatics.h" #include "Net/UnrealNetwork.h" using namespace SpatialGDK; DEFINE_LOG_CATEGORY(LogSpatialDebugger); namespace { const FString DEFAULT_WORKER_REGION_MATERIAL = TEXT("/SpatialGDK/SpatialDebugger/Materials/TranslucentWorkerRegion.TranslucentWorkerRegion"); } ASpatialDebugger::ASpatialDebugger(const FObjectInitializer& ObjectInitializer) : Super(ObjectInitializer) { PrimaryActorTick.bCanEverTick = true; PrimaryActorTick.bStartWithTickEnabled = true; PrimaryActorTick.TickInterval = 1.f; bAlwaysRelevant = true; bNetLoadOnClient = false; bReplicates = true; NetUpdateFrequency = 1.f; NetDriver = Cast<USpatialNetDriver>(GetNetDriver()); // For GDK design reasons, this is the approach chosen to get a pointer // on the net driver to the client ASpatialDebugger. Various alternatives // were considered and this is the best of a bad bunch. if (NetDriver != nullptr && GetNetMode() == NM_Client) { NetDriver->SetSpatialDebugger(this); } } void ASpatialDebugger::GetLifetimeReplicatedProps(TArray<FLifetimeProperty>& OutLifetimeProps) const { Super::GetLifetimeReplicatedProps(OutLifetimeProps); DOREPLIFETIME_CONDITION(ASpatialDebugger, WorkerRegions, COND_SimulatedOnly); } void ASpatialDebugger::Tick(float DeltaSeconds) { Super::Tick(DeltaSeconds); check(NetDriver != nullptr); if (!NetDriver->IsServer()) { for (TMap<Worker_EntityId_Key, TWeakObjectPtr<AActor>>::TIterator It = EntityActorMapping.CreateIterator(); It; ++It) { if (!It->Value.IsValid()) { It.RemoveCurrent(); } } // Since we have no guarantee on the order we'll receive the PC/Pawn/PlayerState // over the wire, we check here once per tick (currently 1 Hz tick rate) to setup our local pointers. // Note that we can capture the PC in OnEntityAdded() since we know we will only receive one of those. if (LocalPawn.IsValid() == false && LocalPlayerController.IsValid()) { LocalPawn = LocalPlayerController->GetPawn(); } if (LocalPlayerState.IsValid() == false && LocalPawn.IsValid()) { LocalPlayerState = LocalPawn->GetPlayerState(); } if (LocalPawn.IsValid()) { SCOPE_CYCLE_COUNTER(STAT_SortingActors); const FVector& PlayerLocation = LocalPawn->GetActorLocation(); EntityActorMapping.ValueSort([PlayerLocation](const TWeakObjectPtr<AActor>& A, const TWeakObjectPtr<AActor>& B) { return FVector::Dist(PlayerLocation, A->GetActorLocation()) > FVector::Dist(PlayerLocation, B->GetActorLocation()); }); } } } void ASpatialDebugger::BeginPlay() { Super::BeginPlay(); check(NetDriver != nullptr); if (!NetDriver->IsServer()) { EntityActorMapping.Reserve(ENTITY_ACTOR_MAP_RESERVATION_COUNT); LoadIcons(); TArray<Worker_EntityId_Key> EntityIds; NetDriver->StaticComponentView->GetEntityIds(EntityIds); // Capture any entities that are already present on this client (ie they came over the wire before the SpatialDebugger did). for (const Worker_EntityId_Key EntityId : EntityIds) { OnEntityAdded(EntityId); } // Register callbacks to get notified of all future entity arrivals / deletes. OnEntityAddedHandle = NetDriver->Receiver->OnEntityAddedDelegate.AddUObject(this, &ASpatialDebugger::OnEntityAdded); OnEntityRemovedHandle = NetDriver->Receiver->OnEntityRemovedDelegate.AddUObject(this, &ASpatialDebugger::OnEntityRemoved); FontRenderInfo.bClipText = true; FontRenderInfo.bEnableShadow = true; RenderFont = GEngine->GetSmallFont(); if (bAutoStart) { SpatialToggleDebugger(); } } } void ASpatialDebugger::OnAuthorityGained() { if (NetDriver->LoadBalanceStrategy) { const ULayeredLBStrategy* LayeredLBStrategy = Cast<ULayeredLBStrategy>(NetDriver->LoadBalanceStrategy); if (LayeredLBStrategy == nullptr) { UE_LOG(LogSpatialDebugger, Warning, TEXT("SpatialDebugger enabled but unable to get LayeredLBStrategy.")); return; } if (const UGridBasedLBStrategy* GridBasedLBStrategy = Cast<UGridBasedLBStrategy>(LayeredLBStrategy->GetLBStrategyForVisualRendering())) { const UGridBasedLBStrategy::LBStrategyRegions LBStrategyRegions = GridBasedLBStrategy->GetLBStrategyRegions(); WorkerRegions.SetNum(LBStrategyRegions.Num()); for (int i = 0; i < LBStrategyRegions.Num(); i++) { const TPair<VirtualWorkerId, FBox2D>& LBStrategyRegion = LBStrategyRegions[i]; const PhysicalWorkerName* WorkerName = NetDriver->VirtualWorkerTranslator->GetPhysicalWorkerForVirtualWorker(LBStrategyRegion.Key); FWorkerRegionInfo WorkerRegionInfo; WorkerRegionInfo.Color = (WorkerName == nullptr) ? InvalidServerTintColor : SpatialGDK::GetColorForWorkerName(*WorkerName); WorkerRegionInfo.Extents = LBStrategyRegion.Value; WorkerRegions[i] = WorkerRegionInfo; } } } } void ASpatialDebugger::CreateWorkerRegions() { UMaterial* WorkerRegionMaterial = LoadObject<UMaterial>(nullptr, *DEFAULT_WORKER_REGION_MATERIAL); if (WorkerRegionMaterial == nullptr) { UE_LOG(LogSpatialDebugger, Error, TEXT("Worker regions were not rendered. Could not find default material: %s"), *DEFAULT_WORKER_REGION_MATERIAL); return; } // Create new actors for all new worker regions FActorSpawnParameters SpawnParams; SpawnParams.bNoFail = true; SpawnParams.SpawnCollisionHandlingOverride = ESpawnActorCollisionHandlingMethod::AlwaysSpawn; for (const FWorkerRegionInfo& WorkerRegionData : WorkerRegions) { AWorkerRegion* WorkerRegion = GetWorld()->SpawnActor<AWorkerRegion>(SpawnParams); WorkerRegion->Init(WorkerRegionMaterial, WorkerRegionData.Color, WorkerRegionData.Extents, WorkerRegionVerticalScale); WorkerRegion->SetActorEnableCollision(false); } } void ASpatialDebugger::DestroyWorkerRegions() { TArray<AActor*> WorkerRegionsToRemove; UGameplayStatics::GetAllActorsOfClass(this, AWorkerRegion::StaticClass(), WorkerRegionsToRemove); for (AActor* WorkerRegion : WorkerRegionsToRemove) { WorkerRegion->Destroy(); } } void ASpatialDebugger::OnRep_SetWorkerRegions() { if (NetDriver != nullptr && !NetDriver->IsServer() && DrawDebugDelegateHandle.IsValid() && bShowWorkerRegions) { DestroyWorkerRegions(); CreateWorkerRegions(); } } void ASpatialDebugger::Destroyed() { if (NetDriver != nullptr && NetDriver->Receiver != nullptr) { if (OnEntityAddedHandle.IsValid()) { NetDriver->Receiver->OnEntityAddedDelegate.Remove(OnEntityAddedHandle); } if (OnEntityRemovedHandle.IsValid()) { NetDriver->Receiver->OnEntityRemovedDelegate.Remove(OnEntityRemovedHandle); } } if (DrawDebugDelegateHandle.IsValid()) { UDebugDrawService::Unregister(DrawDebugDelegateHandle); DestroyWorkerRegions(); } Super::Destroyed(); } void ASpatialDebugger::LoadIcons() { check(NetDriver != nullptr && !NetDriver->IsServer()); UTexture2D* DefaultTexture = LoadObject<UTexture2D>(nullptr, TEXT("/Engine/EngineResources/DefaultTexture.DefaultTexture")); const float IconWidth = 16.0f; const float IconHeight = 16.0f; Icons[ICON_AUTH] = UCanvas::MakeIcon(AuthTexture != nullptr ? AuthTexture : DefaultTexture, 0.0f, 0.0f, IconWidth, IconHeight); Icons[ICON_AUTH_INTENT] = UCanvas::MakeIcon(AuthIntentTexture != nullptr ? AuthIntentTexture : DefaultTexture, 0.0f, 0.0f, IconWidth, IconHeight); Icons[ICON_UNLOCKED] = UCanvas::MakeIcon(UnlockedTexture != nullptr ? UnlockedTexture : DefaultTexture, 0.0f, 0.0f, IconWidth, IconHeight); Icons[ICON_LOCKED] = UCanvas::MakeIcon(LockedTexture != nullptr ? LockedTexture : DefaultTexture, 0.0f, 0.0f, IconWidth, IconHeight); Icons[ICON_BOX] = UCanvas::MakeIcon(BoxTexture != nullptr ? BoxTexture : DefaultTexture, 0.0f, 0.0f, IconWidth, IconHeight); } void ASpatialDebugger::OnEntityAdded(const Worker_EntityId EntityId) { check(NetDriver != nullptr && !NetDriver->IsServer()); TWeakObjectPtr<AActor>* ExistingActor = EntityActorMapping.Find(EntityId); if (ExistingActor != nullptr) { return; } if (AActor* Actor = Cast<AActor>(NetDriver->PackageMap->GetObjectFromEntityId(EntityId).Get())) { EntityActorMapping.Add(EntityId, Actor); // Each client will only receive a PlayerController once. if (Actor->IsA<APlayerController>()) { LocalPlayerController = Cast<APlayerController>(Actor); } } } void ASpatialDebugger::OnEntityRemoved(const Worker_EntityId EntityId) { check(NetDriver != nullptr && !NetDriver->IsServer()); EntityActorMapping.Remove(EntityId); } void ASpatialDebugger::ActorAuthorityChanged(const Worker_AuthorityChangeOp& AuthOp) const { check(AuthOp.authority == WORKER_AUTHORITY_AUTHORITATIVE && AuthOp.component_id == SpatialConstants::AUTHORITY_INTENT_COMPONENT_ID); if (NetDriver->VirtualWorkerTranslator == nullptr) { // Currently, there's nothing to display in the debugger other than load balancing information. return; } VirtualWorkerId LocalVirtualWorkerId = NetDriver->VirtualWorkerTranslator->GetLocalVirtualWorkerId(); FColor LocalVirtualWorkerColor = SpatialGDK::GetColorForWorkerName(NetDriver->VirtualWorkerTranslator->GetLocalPhysicalWorkerName()); SpatialDebugging* DebuggingInfo = NetDriver->StaticComponentView->GetComponentData<SpatialDebugging>(AuthOp.entity_id); if (DebuggingInfo == nullptr) { // Some entities won't have debug info, so create it now. SpatialDebugging NewDebuggingInfo(LocalVirtualWorkerId, LocalVirtualWorkerColor, SpatialConstants::INVALID_VIRTUAL_WORKER_ID, InvalidServerTintColor, false); NetDriver->Sender->SendAddComponents(AuthOp.entity_id, { NewDebuggingInfo.CreateSpatialDebuggingData() }); return; } DebuggingInfo->AuthoritativeVirtualWorkerId = LocalVirtualWorkerId; DebuggingInfo->AuthoritativeColor = LocalVirtualWorkerColor; FWorkerComponentUpdate DebuggingUpdate = DebuggingInfo->CreateSpatialDebuggingUpdate(); NetDriver->Connection->SendComponentUpdate(AuthOp.entity_id, &DebuggingUpdate); } void ASpatialDebugger::ActorAuthorityIntentChanged(Worker_EntityId EntityId, VirtualWorkerId NewIntentVirtualWorkerId) const { SpatialDebugging* DebuggingInfo = NetDriver->StaticComponentView->GetComponentData<SpatialDebugging>(EntityId); check(DebuggingInfo != nullptr); DebuggingInfo->IntentVirtualWorkerId = NewIntentVirtualWorkerId; const PhysicalWorkerName* NewAuthoritativePhysicalWorkerName = NetDriver->VirtualWorkerTranslator->GetPhysicalWorkerForVirtualWorker(NewIntentVirtualWorkerId); check(NewAuthoritativePhysicalWorkerName != nullptr); DebuggingInfo->IntentColor = SpatialGDK::GetColorForWorkerName(*NewAuthoritativePhysicalWorkerName); FWorkerComponentUpdate DebuggingUpdate = DebuggingInfo->CreateSpatialDebuggingUpdate(); NetDriver->Connection->SendComponentUpdate(EntityId, &DebuggingUpdate); } void ASpatialDebugger::DrawTag(UCanvas* Canvas, const FVector2D& ScreenLocation, const Worker_EntityId EntityId, const FString& ActorName) { SCOPE_CYCLE_COUNTER(STAT_DrawTag); // TODO: Smarter positioning of elements so they're centered no matter how many are enabled https://improbableio.atlassian.net/browse/UNR-2360. int32 HorizontalOffset = -32.0f; check(NetDriver != nullptr && !NetDriver->IsServer()); if (!NetDriver->StaticComponentView->HasComponent(EntityId, SpatialConstants::SPATIAL_DEBUGGING_COMPONENT_ID)) { return; } const SpatialDebugging* DebuggingInfo = NetDriver->StaticComponentView->GetComponentData<SpatialDebugging>(EntityId); static const float BaseHorizontalOffset(16.0f); if (!FApp::CanEverRender()) // DrawIcon can attempt to use the underlying texture resource even when using nullrhi { return; } if (bShowLock) { SCOPE_CYCLE_COUNTER(STAT_DrawIcons); const bool bIsLocked = DebuggingInfo->IsLocked; const EIcon LockIcon = bIsLocked ? ICON_LOCKED : ICON_UNLOCKED; Canvas->SetDrawColor(FColor::White); Canvas->DrawIcon(Icons[LockIcon], ScreenLocation.X + HorizontalOffset, ScreenLocation.Y, 1.0f); HorizontalOffset += BaseHorizontalOffset; } if (bShowAuth) { SCOPE_CYCLE_COUNTER(STAT_DrawIcons); const FColor& ServerWorkerColor = DebuggingInfo->AuthoritativeColor; Canvas->SetDrawColor(FColor::White); Canvas->DrawIcon(Icons[ICON_AUTH], ScreenLocation.X + HorizontalOffset, ScreenLocation.Y, 1.0f); HorizontalOffset += BaseHorizontalOffset; Canvas->SetDrawColor(ServerWorkerColor); const float BoxScaleBasedOnNumberSize = 0.75f * GetNumberOfDigitsIn(DebuggingInfo->AuthoritativeVirtualWorkerId); Canvas->DrawScaledIcon(Icons[ICON_BOX], ScreenLocation.X + HorizontalOffset, ScreenLocation.Y, FVector(BoxScaleBasedOnNumberSize, 1.f, 1.f)); Canvas->SetDrawColor(GetTextColorForBackgroundColor(ServerWorkerColor)); Canvas->DrawText(RenderFont, FString::FromInt(DebuggingInfo->AuthoritativeVirtualWorkerId), ScreenLocation.X + HorizontalOffset + 1, ScreenLocation.Y, 1.1f, 1.1f, FontRenderInfo); HorizontalOffset += (BaseHorizontalOffset * BoxScaleBasedOnNumberSize); } if (bShowAuthIntent) { SCOPE_CYCLE_COUNTER(STAT_DrawIcons); const FColor& VirtualWorkerColor = DebuggingInfo->IntentColor; Canvas->SetDrawColor(FColor::White); Canvas->DrawIcon(Icons[ICON_AUTH_INTENT], ScreenLocation.X + HorizontalOffset, ScreenLocation.Y, 1.0f); HorizontalOffset += 16.0f; Canvas->SetDrawColor(VirtualWorkerColor); const float BoxScaleBasedOnNumberSize = 0.75f * GetNumberOfDigitsIn(DebuggingInfo->IntentVirtualWorkerId); Canvas->DrawScaledIcon(Icons[ICON_BOX], ScreenLocation.X + HorizontalOffset, ScreenLocation.Y, FVector(BoxScaleBasedOnNumberSize, 1.f, 1.f)); Canvas->SetDrawColor(GetTextColorForBackgroundColor(VirtualWorkerColor)); Canvas->DrawText(RenderFont, FString::FromInt(DebuggingInfo->IntentVirtualWorkerId), ScreenLocation.X + HorizontalOffset + 1, ScreenLocation.Y, 1.1f, 1.1f, FontRenderInfo); HorizontalOffset += (BaseHorizontalOffset * BoxScaleBasedOnNumberSize); } FString Label; if (bShowEntityId) { SCOPE_CYCLE_COUNTER(STAT_BuildText); Label += FString::Printf(TEXT("%lld "), EntityId); } if (bShowActorName) { SCOPE_CYCLE_COUNTER(STAT_BuildText); Label += FString::Printf(TEXT("(%s)"), *ActorName); } if (bShowEntityId || bShowActorName) { SCOPE_CYCLE_COUNTER(STAT_DrawText); Canvas->SetDrawColor(FColor::Green); Canvas->DrawText(RenderFont, Label, ScreenLocation.X + HorizontalOffset, ScreenLocation.Y, 1.0f, 1.0f, FontRenderInfo); } } FColor ASpatialDebugger::GetTextColorForBackgroundColor(const FColor& BackgroundColor) const { return BackgroundColor.ReinterpretAsLinear().ComputeLuminance() > 0.5 ? FColor::Black : FColor::White; } // This will break once we have more than 10,000 workers, happily kicking that can down the road. int32 ASpatialDebugger::GetNumberOfDigitsIn(int32 SomeNumber) const { SomeNumber = FMath::Abs(SomeNumber); return (SomeNumber < 10 ? 1 : (SomeNumber < 100 ? 2 : (SomeNumber < 1000 ? 3 : 4))); } void ASpatialDebugger::DrawDebug(UCanvas* Canvas, APlayerController* /* Controller */) // Controller is invalid. { SCOPE_CYCLE_COUNTER(STAT_DrawDebug); check(NetDriver != nullptr && !NetDriver->IsServer()); #if WITH_EDITOR // Prevent one client's data rendering in another client's view in PIE when using UDebugDrawService. Lifted from EQSRenderingComponent. if (Canvas && Canvas->SceneView && Canvas->SceneView->Family && Canvas->SceneView->Family->Scene && Canvas->SceneView->Family->Scene->GetWorld() != GetWorld()) { return; } #endif DrawDebugLocalPlayer(Canvas); FVector PlayerLocation = FVector::ZeroVector; if (LocalPawn.IsValid()) { PlayerLocation = LocalPawn->GetActorLocation(); } for (TPair<Worker_EntityId_Key, TWeakObjectPtr<AActor>>& EntityActorPair : EntityActorMapping) { const TWeakObjectPtr<AActor> Actor = EntityActorPair.Value; const Worker_EntityId EntityId = EntityActorPair.Key; if (Actor != nullptr) { FVector ActorLocation = Actor->GetActorLocation(); if (ActorLocation.IsZero()) { continue; } if (FVector::Dist(PlayerLocation, ActorLocation) > MaxRange) { continue; } FVector2D ScreenLocation = FVector2D::ZeroVector; if (LocalPlayerController.IsValid()) { SCOPE_CYCLE_COUNTER(STAT_Projection); UGameplayStatics::ProjectWorldToScreen(LocalPlayerController.Get(), ActorLocation + WorldSpaceActorTagOffset, ScreenLocation, false); } if (ScreenLocation.IsZero()) { continue; } DrawTag(Canvas, ScreenLocation, EntityId, Actor->GetName()); } } } void ASpatialDebugger::DrawDebugLocalPlayer(UCanvas* Canvas) { if (LocalPawn == nullptr || LocalPlayerController == nullptr || LocalPlayerState == nullptr) { return; } const TArray<TWeakObjectPtr<AActor>> LocalPlayerActors = { LocalPawn, LocalPlayerController, LocalPlayerState }; FVector2D ScreenLocation(PlayerPanelStartX, PlayerPanelStartY); for (int32 i = 0; i < LocalPlayerActors.Num(); ++i) { if (LocalPlayerActors[i].IsValid()) { const Worker_EntityId EntityId = NetDriver->PackageMap->GetEntityIdFromObject(LocalPlayerActors[i].Get()); DrawTag(Canvas, ScreenLocation, EntityId, LocalPlayerActors[i]->GetName()); ScreenLocation.Y -= PLAYER_TAG_VERTICAL_OFFSET; } } } void ASpatialDebugger::SpatialToggleDebugger() { check(NetDriver != nullptr && !NetDriver->IsServer()); if (DrawDebugDelegateHandle.IsValid()) { UDebugDrawService::Unregister(DrawDebugDelegateHandle); DrawDebugDelegateHandle.Reset(); DestroyWorkerRegions(); } else { DrawDebugDelegateHandle = UDebugDrawService::Register(TEXT("Game"), FDebugDrawDelegate::CreateUObject(this, &ASpatialDebugger::DrawDebug)); if (bShowWorkerRegions) { CreateWorkerRegions(); } } }
34.690114
181
0.775744
Bowbee
8198abf50adc2d6525c9e1e7d0e6dc61507d28e8
1,490
cc
C++
examples/UniformObjectPoolExample/main.cc
PerttuP/PPUtils
97971d6e2b662bab9a4966b4c39ac59509c01359
[ "MIT" ]
null
null
null
examples/UniformObjectPoolExample/main.cc
PerttuP/PPUtils
97971d6e2b662bab9a4966b4c39ac59509c01359
[ "MIT" ]
null
null
null
examples/UniformObjectPoolExample/main.cc
PerttuP/PPUtils
97971d6e2b662bab9a4966b4c39ac59509c01359
[ "MIT" ]
null
null
null
/* * This is a simple example program to demonstrate the usage of the * PPUtils::UniformObjectPool class template. * * Author: Perttu Paarlahti perttu.paarlahti@gmail.com * Created: 29-June-2015 */ #include <iostream> #include <functional> #include "../../source/PPUtils/uniformobjectpool.hh" class VeryComplexClass { static int n; public: VeryComplexClass() { // Very expensive construction std::cout << "Constructing a massively complex object" << std::endl; ++n; } void foo() { std::cout << "Expensive constructor was called " << n << " times\n"; } }; int VeryComplexClass::n = 0; int main() { // Create the object pool PPUtils::UniformObjectPool<VeryComplexClass> pool; std::cout << "Pool contains: " << pool.size() << " objects" << std::endl; std::unique_ptr<VeryComplexClass> obj = pool.reserve(); std::cout << "Pool contains: " << pool.size() << " objects" << std::endl; pool.release( std::move(obj) ); std::cout << "Pool contains: " << pool.size() << " objects" << std::endl; obj = pool.reserve(); std::cout << "Pool contains: " << pool.size() << " objects" << std::endl; obj->foo(); return 0; } /* * Expected output: * * Pool contains 0 objects * Constructing a massively complex object * Pool contains 0 objects * Pool contains 1 objects * Pool contains 0 objects * Expensive constructor was called 1 times * */
22.575758
77
0.610738
PerttuP
819d2321ac2018d65bf373e8e9e768e8b162ca37
530
cxx
C++
rutil/ParseException.cxx
dulton/reSipServer
ac4241df81c1e3eef2e678271ffef4dda1fc6747
[ "Apache-2.0" ]
1
2019-04-15T14:10:58.000Z
2019-04-15T14:10:58.000Z
rutil/ParseException.cxx
dulton/reSipServer
ac4241df81c1e3eef2e678271ffef4dda1fc6747
[ "Apache-2.0" ]
null
null
null
rutil/ParseException.cxx
dulton/reSipServer
ac4241df81c1e3eef2e678271ffef4dda1fc6747
[ "Apache-2.0" ]
2
2019-10-31T09:11:09.000Z
2021-09-17T01:00:49.000Z
#include "rutil/ParseException.hxx" namespace resip { ParseException::ParseException(const Data& msg, const Data& context, const Data& file, const int line) : resip::BaseException(msg, file, line), mContext(context) {} ParseException::~ParseException() throw() {} const char* ParseException::name() const { return "ParseException"; } const Data& ParseException::getContext() const { return mContext; } }
17.666667
54
0.575472
dulton
819e1cbc99fc76163756220c8033c8e8415940c7
2,183
hpp
C++
miopengemm/include/miopengemm/tinytwo.hpp
pruthvistony/MIOpenGEMM
8f844e134d54244a6138504a4190486d8702e8fd
[ "MIT" ]
52
2017-06-30T06:45:19.000Z
2021-11-04T01:53:48.000Z
miopengemm/include/miopengemm/tinytwo.hpp
pruthvistony/MIOpenGEMM
8f844e134d54244a6138504a4190486d8702e8fd
[ "MIT" ]
31
2017-08-01T03:17:25.000Z
2022-03-22T18:19:41.000Z
miopengemm/include/miopengemm/tinytwo.hpp
pruthvistony/MIOpenGEMM
8f844e134d54244a6138504a4190486d8702e8fd
[ "MIT" ]
23
2017-07-17T02:09:17.000Z
2021-11-10T00:38:19.000Z
/******************************************************************************* * Copyright (C) 2017 Advanced Micro Devices, Inc. All rights reserved. *******************************************************************************/ #ifndef GUARD_MIOPENGEMM_DEGEMMAPIQQ_HPP #define GUARD_MIOPENGEMM_DEGEMMAPIQQ_HPP #include <memory> #include <stdlib.h> #include <string> #include <vector> #include <miopengemm/geometry.hpp> #include <miopengemm/oclutil.hpp> #include <miopengemm/solution.hpp> #include <miopengemm/tinyone.hpp> namespace MIOpenGEMM { namespace dev { class TinyTwo { private: std::unique_ptr<TinyOne<double>> d_moa{nullptr}; std::unique_ptr<TinyOne<float>> f_moa{nullptr}; char active_type{'?'}; template <typename TFloat> std::unique_ptr<TinyOne<TFloat>>& get_up_moa() { throw miog_error("unrecognised template parameter TFloat in TinyTwo get_up_moa"); } template <typename TFloat> void set_active_type() { throw miog_error("unrecognised template parameter TFloat in TinyTwo set_active_type"); } public: template <typename TFloat> TinyTwo(Geometry gg_, Offsets toff_, const TFloat* a_, const TFloat* b_, const TFloat* c_, owrite::Writer& mowri_, const CLHint& xhint) { get_up_moa<TFloat>().reset(new TinyOne<TFloat>(gg_, toff_, a_, b_, c_, mowri_, xhint)); set_active_type<TFloat>(); } TinyTwo(Geometry gg_, Offsets toff_, owrite::Writer& mowri_, const CLHint& xhint); std::vector<std::vector<double>> benchgemm(const std::vector<HyPas>& hps, const Halt& hl); Solution find2(const FindParams& find_params, const Constraints& constraints); // template <typename TFloat> // void accuracy_test(const HyPas& hp) //{ // get_up_moa<TFloat>()->accuracy_test(hp); //} void accuracy_test(const HyPas& hp); }; template <> std::unique_ptr<TinyOne<float>>& TinyTwo::get_up_moa<float>(); template <> std::unique_ptr<TinyOne<double>>& TinyTwo::get_up_moa<double>(); template <> void TinyTwo::set_active_type<float>(); template <> void TinyTwo::set_active_type<double>(); } } #endif
25.682353
92
0.637655
pruthvistony
819ec17303f0d6f29fec611f81d2e4c369592e9f
1,664
cpp
C++
Userland/Libraries/LibGUI/DisplayLink.cpp
AristodamusAdairs/SegueBaseOS
36e8546009cfea6acd25f111b1cd0ce766271a77
[ "BSD-2-Clause", "MIT" ]
1
2021-07-05T13:51:23.000Z
2021-07-05T13:51:23.000Z
Userland/Libraries/LibGUI/DisplayLink.cpp
AristodamusAdairs/SegueBaseOS
36e8546009cfea6acd25f111b1cd0ce766271a77
[ "BSD-2-Clause", "MIT" ]
1
2021-08-02T21:33:29.000Z
2021-08-06T21:22:19.000Z
Userland/Libraries/LibGUI/DisplayLink.cpp
AristodamusAdairs/SegueBaseOS
36e8546009cfea6acd25f111b1cd0ce766271a77
[ "BSD-2-Clause", "MIT" ]
null
null
null
/* * Copyright (c) 2020, Andreas Kling <kling@seguebaseos.org> * * SPDX-License-Identifier: BSD-2-Clause */ #include <AK/Badge.h> #include <AK/Function.h> #include <AK/HashMap.h> #include <LibGUI/DisplayLink.h> #include <LibGUI/WindowServerConnection.h> namespace GUI { class DisplayLinkCallback : public RefCounted<DisplayLinkCallback> { public: DisplayLinkCallback(i32 link_id, Function<void(i32)> callback) : m_link_id(link_id) , m_callback(move(callback)) { } void invoke() { m_callback(m_link_id); } private: i32 m_link_id { 0 }; Function<void(i32)> m_callback; }; static HashMap<i32, RefPtr<DisplayLinkCallback>>& callbacks() { static HashMap<i32, RefPtr<DisplayLinkCallback>>* map; if (!map) map = new HashMap<i32, RefPtr<DisplayLinkCallback>>; return *map; } static i32 s_next_callback_id = 1; i32 DisplayLink::register_callback(Function<void(i32)> callback) { if (callbacks().is_empty()) WindowServerConnection::the().async_enable_display_link(); i32 callback_id = s_next_callback_id++; callbacks().set(callback_id, adopt_ref(*new DisplayLinkCallback(callback_id, move(callback)))); return callback_id; } bool DisplayLink::unregister_callback(i32 callback_id) { VERIFY(callbacks().contains(callback_id)); callbacks().remove(callback_id); if (callbacks().is_empty()) WindowServerConnection::the().async_disable_display_link(); return true; } void DisplayLink::notify(Badge<WindowServerConnection>) { auto copy_of_callbacks = callbacks(); for (auto& it : copy_of_callbacks) it.value->invoke(); } }
22.794521
99
0.696514
AristodamusAdairs
819f8ddb9ade96e04c8ed3540d7fc38ed513bdea
220
cxx
C++
Utilities/planio/realloc.cxx
NIRALUser/AtlasWerks
a074ca208ab41a6ed89c1f0b70004998f7397681
[ "BSD-3-Clause" ]
3
2016-04-26T05:06:06.000Z
2020-08-01T09:46:54.000Z
Utilities/planio/realloc.cxx
scalphunters/AtlasWerks
9d224bf8db628805368fcb7973ac578937b6b595
[ "BSD-3-Clause" ]
1
2018-11-27T21:53:48.000Z
2019-05-13T15:21:31.000Z
Utilities/planio/realloc.cxx
scalphunters/AtlasWerks
9d224bf8db628805368fcb7973ac578937b6b595
[ "BSD-3-Clause" ]
2
2019-01-24T02:07:17.000Z
2019-12-11T17:27:42.000Z
#include <stdio.h> #include <stdlib.h> void * Realloc(void *ptr, int size) { if (size == 0) size = sizeof(int); if (ptr == NULL) ptr = calloc(size,1); else ptr = realloc(ptr, size); return(ptr); }
12.222222
42
0.568182
NIRALUser
81a0a0d1f022e000527c7301b1d4c1c2d42b9bd9
6,346
cpp
C++
src/Programs/Terminal/Terminal.cpp
Kaj9296/Electric_OS
31e1d9318943e50e2bc095dc2ba32d4ce26e7e8b
[ "MIT" ]
7
2022-02-20T16:34:48.000Z
2022-02-26T06:14:51.000Z
src/Programs/Terminal/Terminal.cpp
Kaj9296/Electric_OS
31e1d9318943e50e2bc095dc2ba32d4ce26e7e8b
[ "MIT" ]
null
null
null
src/Programs/Terminal/Terminal.cpp
Kaj9296/Electric_OS
31e1d9318943e50e2bc095dc2ba32d4ce26e7e8b
[ "MIT" ]
4
2022-02-20T16:25:44.000Z
2022-03-20T07:49:25.000Z
#include "Terminal.h" #include "STL/Graphics/Framebuffer.h" #include "STL/String/String.h" #include "STL/String/cstr.h" #include "STL/System/System.h" #include "Version.h" #define NEWLINE_OFFSET RAISED_WIDTH * 3 namespace Terminal { uint64_t PrevTick = 0; char Command[64]; STL::String Text; STL::Point CursorPos = STL::Point(0, 0); bool RedrawText = false; bool DrawUnderline = false; bool ClearCommand = false; void Write(const char* cstr) { Text += cstr; } STL::PROR Procedure(STL::PROM Message, STL::PROI Input) { switch(Message) { case STL::PROM::INIT: { STL::PINFO* Info = (STL::PINFO*)Input; Info->Type = STL::PROT::WINDOWED; Info->Depth = 1; Info->Left = 360; Info->Top = 200; Info->Width = 1000 + NEWLINE_OFFSET * 2; Info->Height = 650; Info->Title = "Terminal"; Text = ""; Command[0] = 0; CursorPos = STL::Point(0, 0); Write("\n\r"); Write("Welcome to the Terminal of "); Write(OS_VERSION); Write("!\n\r"); Write("Type \"help\" for a list of all available commands.\n\n\r"); Write(STL::System("sysfetch")); Write("\n\r"); Write("> "); RedrawText = true; } break; case STL::PROM::TICK: { uint64_t CurrentTick = *(uint64_t*)Input; if (PrevTick + 50 < CurrentTick) { DrawUnderline = !DrawUnderline; PrevTick = CurrentTick; return STL::PROR::DRAW; } } break; case STL::PROM::DRAW: { STL::Framebuffer* Buffer = (STL::Framebuffer*)Input; //Clear command for (uint32_t i = 0; i < STL::Length(Command) + 2; i++) { Buffer->PutChar(' ', STL::Point(CursorPos.X + 8 * i, CursorPos.Y), 1, STL::ARGB(255), STL::ARGB(0)); } //Scroll up if (CursorPos.Y + STL::LineAmount(Text.cstr()) * 16 + NEWLINE_OFFSET * 2 > Buffer->Height) { uint64_t Amount = (CursorPos.Y + STL::LineAmount(Text.cstr()) * 16 + NEWLINE_OFFSET * 2) - Buffer->Height; for (uint32_t y = NEWLINE_OFFSET; y < Buffer->Height - NEWLINE_OFFSET - Amount; y++) { for (uint32_t x = NEWLINE_OFFSET; x < Buffer->Width - NEWLINE_OFFSET; x++) { *(STL::ARGB*)((uint64_t)Buffer->Base + x * 4 + y * Buffer->PixelsPerScanline * 4) = *(STL::ARGB*)((uint64_t)Buffer->Base + x * 4 + (y + Amount) * Buffer->PixelsPerScanline * 4); } } for (uint32_t y = Buffer->Height - NEWLINE_OFFSET - Amount; y < Buffer->Height; y++) { for (uint32_t x = NEWLINE_OFFSET; x < Buffer->Width - NEWLINE_OFFSET; x++) { *(STL::ARGB*)((uint64_t)Buffer->Base + x * 4 + y * Buffer->PixelsPerScanline * 4) = STL::ARGB(0); } } CursorPos.Y -= Amount; if (CursorPos.Y < 0) { CursorPos.Y = 0; } } if (RedrawText) { //Print text Buffer->Print(Text.cstr(), CursorPos, 1, STL::ARGB(255), STL::ARGB(0), NEWLINE_OFFSET); Text = ""; Command[0] = 0; RedrawText = false; //Draw Edge Buffer->DrawRect(STL::Point(0, 0), STL::Point(Buffer->Width, RAISED_WIDTH * 2), STL::ARGB(200)); Buffer->DrawRect(STL::Point(0, 0), STL::Point(RAISED_WIDTH * 2, Buffer->Height), STL::ARGB(200)); Buffer->DrawRect(STL::Point(Buffer->Width - RAISED_WIDTH * 2, 0), STL::Point(Buffer->Width, Buffer->Height), STL::ARGB(200)); Buffer->DrawRect(STL::Point(0, Buffer->Height - RAISED_WIDTH * 2), STL::Point(Buffer->Width, Buffer->Height), STL::ARGB(200)); Buffer->DrawSunkenRectEdge(STL::Point(RAISED_WIDTH * 2, RAISED_WIDTH * 2), STL::Point(Buffer->Width - RAISED_WIDTH * 2, Buffer->Height - RAISED_WIDTH * 2)); } //Print command STL::Point Temp = CursorPos; Buffer->Print(Command, Temp, 1, STL::ARGB(255), STL::ARGB(0), NEWLINE_OFFSET); //Print underline if (DrawUnderline) { Buffer->PutChar('_', Temp, 1, STL::ARGB(255), STL::ARGB(0)); } else { Buffer->PutChar(' ', Temp, 1, STL::ARGB(255), STL::ARGB(0)); } } break; case STL::PROM::KEYPRESS: { uint8_t Key = *(uint8_t*)Input; if (Key == ENTER) { Text += Command; Text += "\n\r"; Text += STL::System(Command); Text += "\n\r> "; RedrawText = true; } else if (Key == BACKSPACE) { uint64_t CommandLength = STL::Length(Command); if (CommandLength != 0) { Command[CommandLength - 1] = 0; Command[CommandLength] = 0; } } else { uint64_t CommandLength = STL::Length(Command); if (CommandLength < 63) { Command[CommandLength] = Key; Command[CommandLength + 1] = 0; } } return STL::PROR::DRAW; } break; case STL::PROM::CLEAR: { Text = ""; Command[0] = 0; CursorPos = STL::Point(0, 0); } break; case STL::PROM::KILL: { Text = ""; Command[0] = 0; } break; default: { } break; } return STL::PROR::SUCCESS; } }
31.73
173
0.443744
Kaj9296
81a158690d1e2643f6cc70d65bfeeea9bd7f520c
2,223
hpp
C++
src/3rd party/components/ElPack/Code/Source/ElTreeDTPickEdit.hpp
OLR-xray/OLR-3.0
b6a9bb2a0c1fb849b8c6cea2e831e1ceea5cc611
[ "Apache-2.0" ]
8
2016-01-25T20:18:51.000Z
2019-03-06T07:00:04.000Z
src/3rd party/components/ElPack/Code/Source/ElTreeDTPickEdit.hpp
OLR-xray/OLR-3.0
b6a9bb2a0c1fb849b8c6cea2e831e1ceea5cc611
[ "Apache-2.0" ]
null
null
null
src/3rd party/components/ElPack/Code/Source/ElTreeDTPickEdit.hpp
OLR-xray/OLR-3.0
b6a9bb2a0c1fb849b8c6cea2e831e1ceea5cc611
[ "Apache-2.0" ]
3
2016-02-14T01:20:43.000Z
2021-02-03T11:19:11.000Z
// Borland C++ Builder // Copyright (c) 1995, 2002 by Borland Software Corporation // All rights reserved // (DO NOT EDIT: machine generated header) 'ElTreeDTPickEdit.pas' rev: 6.00 #ifndef ElTreeDTPickEditHPP #define ElTreeDTPickEditHPP #pragma delphiheader begin #pragma option push -w- #pragma option push -Vx #include <ElDTPick.hpp> // Pascal unit #include <ElHeader.hpp> // Pascal unit #include <ElTree.hpp> // Pascal unit #include <Types.hpp> // Pascal unit #include <Classes.hpp> // Pascal unit #include <SysUtils.hpp> // Pascal unit #include <Forms.hpp> // Pascal unit #include <Controls.hpp> // Pascal unit #include <Messages.hpp> // Pascal unit #include <Windows.hpp> // Pascal unit #include <SysInit.hpp> // Pascal unit #include <System.hpp> // Pascal unit //-- user supplied ----------------------------------------------------------- namespace Eltreedtpickedit { //-- type declarations ------------------------------------------------------- class DELPHICLASS TElTreeInplaceDateTimePicker; class PASCALIMPLEMENTATION TElTreeInplaceDateTimePicker : public Eltree::TElTreeInplaceEditor { typedef Eltree::TElTreeInplaceEditor inherited; private: Classes::TWndMethod SaveWndProc; void __fastcall EditorWndProc(Messages::TMessage &Message); protected: Eldtpick::TElDateTimePicker* FEditor; virtual void __fastcall DoStartOperation(void); virtual void __fastcall DoStopOperation(bool Accepted); virtual bool __fastcall GetVisible(void); virtual void __fastcall TriggerAfterOperation(bool &Accepted, bool &DefaultConversion); virtual void __fastcall TriggerBeforeOperation(bool &DefaultConversion); virtual void __fastcall SetEditorParent(void); public: __fastcall virtual TElTreeInplaceDateTimePicker(Classes::TComponent* AOwner); __fastcall virtual ~TElTreeInplaceDateTimePicker(void); __property Eldtpick::TElDateTimePicker* Editor = {read=FEditor}; }; //-- var, const, procedure --------------------------------------------------- } /* namespace Eltreedtpickedit */ using namespace Eltreedtpickedit; #pragma option pop // -w- #pragma option pop // -Vx #pragma delphiheader end. //-- end unit ---------------------------------------------------------------- #endif // ElTreeDTPickEdit
33.681818
94
0.695906
OLR-xray
81a3842fb532d19187fa8cdb45c554b79470b22d
8,541
hpp
C++
master/core/third/boost/geometry/algorithms/disjoint.hpp
importlib/klib
a59837857689d0e60d3df6d2ebd12c3160efa794
[ "MIT" ]
198
2015-01-13T05:47:18.000Z
2022-03-09T04:46:46.000Z
master/core/third/boost/geometry/algorithms/disjoint.hpp
isuhao/klib
a59837857689d0e60d3df6d2ebd12c3160efa794
[ "MIT" ]
197
2017-07-06T16:53:59.000Z
2019-05-31T17:57:51.000Z
master/core/third/boost/geometry/algorithms/disjoint.hpp
isuhao/klib
a59837857689d0e60d3df6d2ebd12c3160efa794
[ "MIT" ]
139
2015-01-15T20:09:31.000Z
2022-01-31T15:21:16.000Z
// Boost.Geometry (aka GGL, Generic Geometry Library) // Copyright (c) 2007-2012 Barend Gehrels, Amsterdam, the Netherlands. // Copyright (c) 2008-2012 Bruno Lalande, Paris, France. // Copyright (c) 2009-2012 Mateusz Loskot, London, UK. // Parts of Boost.Geometry are redesigned from Geodan's Geographic Library // (geolib/GGL), copyright (c) 1995-2010 Geodan, Amsterdam, the Netherlands. // Use, modification and distribution is subject to the Boost Software License, // Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #ifndef BOOST_GEOMETRY_ALGORITHMS_DISJOINT_HPP #define BOOST_GEOMETRY_ALGORITHMS_DISJOINT_HPP #include <cstddef> #include <deque> #include <boost/mpl/if.hpp> #include <boost/range.hpp> #include <boost/static_assert.hpp> #include <boost/geometry/core/access.hpp> #include <boost/geometry/core/coordinate_dimension.hpp> #include <boost/geometry/core/reverse_dispatch.hpp> #include <boost/geometry/algorithms/detail/disjoint.hpp> #include <boost/geometry/algorithms/detail/for_each_range.hpp> #include <boost/geometry/algorithms/detail/point_on_border.hpp> #include <boost/geometry/algorithms/detail/overlay/get_turns.hpp> #include <boost/geometry/algorithms/within.hpp> #include <boost/geometry/geometries/concepts/check.hpp> #include <boost/geometry/util/math.hpp> namespace boost { namespace geometry { #ifndef DOXYGEN_NO_DETAIL namespace detail { namespace disjoint { template<typename Geometry> struct check_each_ring_for_within { bool has_within; Geometry const& m_geometry; inline check_each_ring_for_within(Geometry const& g) : has_within(false) , m_geometry(g) {} template <typename Range> inline void apply(Range const& range) { typename geometry::point_type<Range>::type p; geometry::point_on_border(p, range); if (geometry::within(p, m_geometry)) { has_within = true; } } }; template <typename FirstGeometry, typename SecondGeometry> inline bool rings_containing(FirstGeometry const& geometry1, SecondGeometry const& geometry2) { check_each_ring_for_within<FirstGeometry> checker(geometry1); geometry::detail::for_each_range(geometry2, checker); return checker.has_within; } struct assign_disjoint_policy { // We want to include all points: static bool const include_no_turn = true; static bool const include_degenerate = true; static bool const include_opposite = true; // We don't assign extra info: template < typename Info, typename Point1, typename Point2, typename IntersectionInfo, typename DirInfo > static inline void apply(Info& , Point1 const& , Point2 const&, IntersectionInfo const&, DirInfo const&) {} }; template <typename Geometry1, typename Geometry2> struct disjoint_linear { static inline bool apply(Geometry1 const& geometry1, Geometry2 const& geometry2) { typedef typename geometry::point_type<Geometry1>::type point_type; typedef overlay::turn_info<point_type> turn_info; std::deque<turn_info> turns; // Specify two policies: // 1) Stop at any intersection // 2) In assignment, include also degenerate points (which are normally skipped) disjoint_interrupt_policy policy; geometry::get_turns < false, false, assign_disjoint_policy >(geometry1, geometry2, turns, policy); if (policy.has_intersections) { return false; } return true; } }; template <typename Segment1, typename Segment2> struct disjoint_segment { static inline bool apply(Segment1 const& segment1, Segment2 const& segment2) { typedef typename point_type<Segment1>::type point_type; segment_intersection_points<point_type> is = strategy::intersection::relate_cartesian_segments < policies::relate::segments_intersection_points < Segment1, Segment2, segment_intersection_points<point_type> > >::apply(segment1, segment2); return is.count == 0; } }; template <typename Geometry1, typename Geometry2> struct general_areal { static inline bool apply(Geometry1 const& geometry1, Geometry2 const& geometry2) { if (! disjoint_linear<Geometry1, Geometry2>::apply(geometry1, geometry2)) { return false; } // If there is no intersection of segments, they might located // inside each other if (rings_containing(geometry1, geometry2) || rings_containing(geometry2, geometry1)) { return false; } return true; } }; }} // namespace detail::disjoint #endif // DOXYGEN_NO_DETAIL #ifndef DOXYGEN_NO_DISPATCH namespace dispatch { template < typename GeometryTag1, typename GeometryTag2, typename Geometry1, typename Geometry2, std::size_t DimensionCount > struct disjoint : detail::disjoint::general_areal<Geometry1, Geometry2> {}; template <typename Point1, typename Point2, std::size_t DimensionCount> struct disjoint<point_tag, point_tag, Point1, Point2, DimensionCount> : detail::disjoint::point_point<Point1, Point2, 0, DimensionCount> {}; template <typename Box1, typename Box2, std::size_t DimensionCount> struct disjoint<box_tag, box_tag, Box1, Box2, DimensionCount> : detail::disjoint::box_box<Box1, Box2, 0, DimensionCount> {}; template <typename Point, typename Box, std::size_t DimensionCount> struct disjoint<point_tag, box_tag, Point, Box, DimensionCount> : detail::disjoint::point_box<Point, Box, 0, DimensionCount> {}; template <typename Linestring1, typename Linestring2> struct disjoint<linestring_tag, linestring_tag, Linestring1, Linestring2, 2> : detail::disjoint::disjoint_linear<Linestring1, Linestring2> {}; template <typename Linestring1, typename Linestring2> struct disjoint<segment_tag, segment_tag, Linestring1, Linestring2, 2> : detail::disjoint::disjoint_segment<Linestring1, Linestring2> {}; template <typename Linestring, typename Segment> struct disjoint<linestring_tag, segment_tag, Linestring, Segment, 2> : detail::disjoint::disjoint_linear<Linestring, Segment> {}; template < typename GeometryTag1, typename GeometryTag2, typename Geometry1, typename Geometry2, std::size_t DimensionCount > struct disjoint_reversed { static inline bool apply(Geometry1 const& g1, Geometry2 const& g2) { return disjoint < GeometryTag2, GeometryTag1, Geometry2, Geometry1, DimensionCount >::apply(g2, g1); } }; } // namespace dispatch #endif // DOXYGEN_NO_DISPATCH /*! \brief \brief_check2{are disjoint} \ingroup disjoint \tparam Geometry1 \tparam_geometry \tparam Geometry2 \tparam_geometry \param geometry1 \param_geometry \param geometry2 \param_geometry \return \return_check2{are disjoint} \qbk{[include reference/algorithms/disjoint.qbk]} */ template <typename Geometry1, typename Geometry2> inline bool disjoint(Geometry1 const& geometry1, Geometry2 const& geometry2) { concept::check_concepts_and_equal_dimensions < Geometry1 const, Geometry2 const >(); return boost::mpl::if_c < reverse_dispatch<Geometry1, Geometry2>::type::value, dispatch::disjoint_reversed < typename tag<Geometry1>::type, typename tag<Geometry2>::type, Geometry1, Geometry2, dimension<Geometry1>::type::value >, dispatch::disjoint < typename tag<Geometry1>::type, typename tag<Geometry2>::type, Geometry1, Geometry2, dimension<Geometry1>::type::value > >::type::apply(geometry1, geometry2); } }} // namespace boost::geometry #endif // BOOST_GEOMETRY_ALGORITHMS_DISJOINT_HPP
28.281457
89
0.65449
importlib
81a46bb917d47aca2ad6d58fe1943d5095915be2
12,782
cpp
C++
src/test/simple_kv/checker.cpp
imzhenyu/rDSN.dist.service
741cdfcaabd7312e64d10f3f194de7790b578d01
[ "MIT" ]
2
2016-12-08T05:56:22.000Z
2021-12-08T18:41:47.000Z
src/test/simple_kv/checker.cpp
imzhenyu/rDSN.dist.service
741cdfcaabd7312e64d10f3f194de7790b578d01
[ "MIT" ]
15
2016-08-09T23:37:11.000Z
2018-09-21T09:45:28.000Z
src/test/simple_kv/checker.cpp
imzhenyu/rDSN.dist.service
741cdfcaabd7312e64d10f3f194de7790b578d01
[ "MIT" ]
4
2016-11-18T08:25:33.000Z
2021-12-08T18:41:49.000Z
/* * The MIT License (MIT) * * Copyright (c) 2015 Microsoft Corporation * * -=- Robust Distributed System Nucleus (rDSN) -=- * * 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. */ /* * Description: * Replication testing framework. * * Revision history: * Nov., 2015, @qinzuoyan (Zuoyan Qin), first version * xxxx-xx-xx, author, fix bug about xxx */ # include "checker.h" # include "case.h" # include "dsn/utility/factory_store.h" # include "../../replica_server/replication_lib/replica.h" # include "../../replica_server/replication_lib/replica_stub.h" # include "../../replica_server/replication_lib/mutation_log.h" # include "../../meta_server/meta_server_lib/meta_service.h" # include "../../meta_server/meta_server_lib/meta_server_failure_detector.h" # include "../../meta_server/meta_server_lib/server_state.h" # include "../../meta_server/meta_server_lib/server_load_balancer.h" # include "../../common/replication_ds.h" # include <sstream> # include <boost/lexical_cast.hpp> # include <dsn/tool_api.h> # ifdef __TITLE__ # undef __TITLE__ # endif # define __TITLE__ "simple_kv.checker" namespace dsn { namespace replication { namespace test { class checker_load_balancer: public simple_load_balancer { public: static bool s_disable_balancer; public: checker_load_balancer(meta_service* svc): simple_load_balancer(svc) {} pc_status cure(const meta_view &view, const dsn::gpid& gpid, configuration_proposal_action &action) override { const partition_configuration& pc = *get_config(*view.apps, gpid); action.type = config_type::CT_INVALID; if (s_disable_balancer) return pc_status::healthy; pc_status result; if (pc.primary.is_invalid()) { if (pc.secondaries.size() > 0) { action.node = pc.secondaries[0]; for (unsigned int i=1; i<pc.secondaries.size(); ++i) if (pc.secondaries[i] < action.node) action.node = pc.secondaries[i]; action.type = config_type::CT_UPGRADE_TO_PRIMARY; result = pc_status::ill; } else if (pc.last_drops.size() == 0) { std::vector<rpc_address> sort_result; sort_alive_nodes(*view.nodes, primary_comparator(*view.nodes), sort_result); action.node = sort_result[0]; action.type = config_type::CT_ASSIGN_PRIMARY; result = pc_status::ill; } // DDD else { action.node = *pc.last_drops.rbegin(); action.type = config_type::CT_ASSIGN_PRIMARY; derror("%d.%d enters DDD state, we are waiting for its last primary node %s to come back ...", pc.pid.get_app_id(), pc.pid.get_partition_index(), action.node.to_string() ); result = pc_status::dead; } action.target = action.node; } else if (static_cast<int>(pc.secondaries.size()) + 1 < pc.max_replica_count) { std::vector<rpc_address> sort_result; sort_alive_nodes(*view.nodes, partition_comparator(*view.nodes), sort_result); for (auto& node: sort_result) { if (!is_member(pc, node)) { action.node = node; break; } } action.target = pc.primary; action.type = config_type::CT_ADD_SECONDARY; result = pc_status::ill; } else { result = pc_status::healthy; } return result; } }; bool test_checker::s_inited = false; bool checker_load_balancer::s_disable_balancer = false; test_checker::test_checker() { } void test_checker::control_balancer(bool disable_it) { checker_load_balancer::s_disable_balancer = disable_it; if (disable_it && meta_leader()) { server_state* ss = meta_leader()->_service->_state.get(); for (auto& kv: ss->_exist_apps) { std::shared_ptr<app_state>& app = kv.second; app->helpers->clear_proposals(); } } } bool test_checker::init(const char* name, dsn_app_info* info, int count) { if (s_inited) return false; _apps.resize(count); for (int i = 0; i < count; i++) { _apps[i] = info[i]; } utils::factory_store<replication::server_load_balancer>::register_factory( "checker_load_balancer", replication::server_load_balancer::create<checker_load_balancer>, PROVIDER_TYPE_MAIN); for (auto& app : _apps) { if (0 == strcmp(app.type, "meta")) { meta_service_app* meta_app = (meta_service_app*)app.app.app_context_ptr; meta_app->_service->_state->set_config_change_subscriber_for_test( std::bind(&test_checker::on_config_change, this, std::placeholders::_1)); meta_app->_service->_meta_opts.server_load_balancer_type = "checker_load_balancer"; _meta_servers.push_back(meta_app); } else if (0 == strcmp(app.type, "replica")) { replication_service_app* replica_app = (replication_service_app*)app.app.app_context_ptr; replica_app->_stub->set_replica_state_subscriber_for_test( std::bind(&test_checker::on_replica_state_change, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3), false); _replica_servers.push_back(replica_app); } } for (int i = 0; i < count; i++) { auto& node = _apps[i]; int id = node.app_id; std::string name = node.name; rpc_address paddr(node.primary_address); int port = paddr.port(); _node_to_address[name] = paddr; ddebug("=== node_to_address[%s]=%s", name.c_str(), paddr.to_string()); _address_to_node[port] = name; ddebug("=== address_to_node[%u]=%s", port, name.c_str()); if (id != port) { _address_to_node[id] = name; ddebug("=== address_to_node[%u]=%s", id, name.c_str()); } } s_inited = true; if (!test_case::instance().init(g_case_input)) { std::cerr << "init test_case failed" << std::endl; s_inited = false; return false; } return true; } void test_checker::exit() { if (!s_inited) return; for (meta_service_app* app : _meta_servers) { app->_service->_started = false; } if (test_case::s_close_replica_stub_on_exit) { dsn::tools::tool_app* app = dsn::tools::get_current_tool(); app->stop_all_apps(true); } } void test_checker::check() { test_case::instance().on_check(); if (g_done) return; // 'config_change' and 'replica_state_change' are detected in two ways: // - each time this check() is called, checking will be applied // - register subscribers on meta_server and replica_server to be notified parti_config cur_config; if (get_current_config(cur_config) && cur_config != _last_config) { test_case::instance().on_config_change(_last_config, cur_config); _last_config = cur_config; } state_snapshot cur_states; get_current_states(cur_states); if (cur_states != _last_states) { test_case::instance().on_state_change(_last_states, cur_states); _last_states = cur_states; } } void test_checker::on_replica_state_change(::dsn::rpc_address from, const replica_configuration& new_config, bool is_closing) { state_snapshot cur_states; get_current_states(cur_states); if (cur_states != _last_states) { test_case::instance().on_state_change(_last_states, cur_states); _last_states = cur_states; } } void test_checker::on_config_change(const app_mapper& new_config) { const partition_configuration* pc = get_config(new_config, g_default_gpid); dassert(pc != nullptr, "drop table is not allowed in test"); parti_config cur_config; cur_config.convert_from(*pc); if (cur_config != _last_config) { test_case::instance().on_config_change(_last_config, cur_config); _last_config = cur_config; } } void test_checker::get_current_states(state_snapshot& states) { states.state_map.clear(); for (auto& app : _replica_servers) { if (!app->is_started()) continue; for (auto& kv : app->_stub->_replicas) { replica_ptr r = kv.second; dassert(kv.first == r->get_gpid(), ""); replica_id id(r->get_gpid(), app->name()); replica_state& rs = states.state_map[id]; rs.id = id; rs.status = r->status(); rs.ballot = r->get_ballot(); rs.last_committed_decree = r->last_committed_decree(); rs.last_durable_decree = r->last_durable_decree(); } } } bool test_checker::get_current_config(parti_config& config) { meta_service_app* meta = meta_leader(); if (meta == nullptr) return false; partition_configuration c; //we should never try to acquire lock when we are in checker. Because we are the only //thread that is running. //The app and emulator have lots in common with the OS's userspace and kernel space. //In normal case, "apps" runs in "userspace". You can "trap into kernel(i.e. the emulator)" by the rDSN's //"enqueue,dequeue and lock..." //meta->_service->_state->query_configuration_by_gpid(g_default_gpid, c); const meta_view view = meta->_service->_state->get_meta_view(); const partition_configuration* pc = get_config(*(view.apps), g_default_gpid); c = *pc; config.convert_from(c); return true; } meta_service_app* test_checker::meta_leader() { for (auto& meta : _meta_servers) { if (!meta->is_started()) return nullptr; if (meta->_service->_failure_detector->is_primary()) return meta; } return nullptr; } bool test_checker::is_server_normal() { auto meta = meta_leader(); if (!meta) return false; return check_replica_state(1, 2, 0); } bool test_checker::check_replica_state(int primary_count, int secondary_count, int inactive_count) { int p = 0; int s = 0; int i = 0; for (auto& rs : _replica_servers) { if (!rs->is_started()) return false; for (auto& replica : rs->_stub->_replicas) { auto status = replica.second->status(); if (status == partition_status::PS_PRIMARY) p++; else if (status == partition_status::PS_SECONDARY) s++; else if (status == partition_status::PS_INACTIVE) i++; } } return p == primary_count && s == secondary_count && i == inactive_count; } std::string test_checker::address_to_node_name(rpc_address addr) { auto find = _address_to_node.find(addr.port()); if (find != _address_to_node.end()) return find->second; return "node@" + boost::lexical_cast<std::string>(addr.port()); } rpc_address test_checker::node_name_to_address(const std::string& name) { auto find = _node_to_address.find(name); if (find != _node_to_address.end()) return find->second; return rpc_address(); } void install_checkers() { dsn_register_app_checker( "simple_kv.checker", ::dsn::tools::checker::create<wrap_checker>, ::dsn::tools::checker::apply ); } }}}
31.955
125
0.622751
imzhenyu
81a5206236d59672af33811fd865ded83964a51e
925
cpp
C++
Codeforces/B_394.cpp
ahakouz17/Competitive-Programming-Practice
5f4daaf491ab03bb86387e491ecc5634b7f99433
[ "MIT" ]
null
null
null
Codeforces/B_394.cpp
ahakouz17/Competitive-Programming-Practice
5f4daaf491ab03bb86387e491ecc5634b7f99433
[ "MIT" ]
null
null
null
Codeforces/B_394.cpp
ahakouz17/Competitive-Programming-Practice
5f4daaf491ab03bb86387e491ecc5634b7f99433
[ "MIT" ]
null
null
null
// solved: 2014-03-06 21:38:08 // https://codeforces.com/contest/394/problem/B #include <bits/stdc++.h> using namespace std; int main() { int p, x, n = 0, rem = 0, last; vector<int> num; cin >> p >> x; for (int i = 1; i <= 9; i++) { n = 1; last = i; rem = 0; num.push_back(i); if (p + x == 2) { cout << 1; return 0; } while (n < p) { int L = last; last = (L * x + rem) % 10; rem = ((L * x + rem) - (L * x + rem) % 10) / 10; num.push_back(last); n = num.size(); if ((last * x + rem) == i && num.size() == p && last != 0) { for (int i = p - 1; i >= 0; i--) cout << num[i]; return 0; } } num.clear(); } cout << "Impossible"; return 0; }
23.717949
70
0.353514
ahakouz17
81a552e0cc23619db8c57f0642d0156b11290d26
12,750
cpp
C++
src/modules/filesystem/file_stream.cpp
badlee/TideSDK
fe6f6c93c6cab3395121696f48d3b55d43e1eddd
[ "Apache-2.0" ]
1
2021-09-18T10:10:39.000Z
2021-09-18T10:10:39.000Z
src/modules/filesystem/file_stream.cpp
hexmode/TideSDK
2c0276de08d7b760b53416bbd8038d79b8474fc5
[ "Apache-2.0" ]
1
2022-02-08T08:45:29.000Z
2022-02-08T08:45:29.000Z
src/modules/filesystem/file_stream.cpp
hexmode/TideSDK
2c0276de08d7b760b53416bbd8038d79b8474fc5
[ "Apache-2.0" ]
null
null
null
/** * Copyright (c) 2012 - 2014 TideSDK contributors * http://www.tidesdk.org * Includes modified sources under the Apache 2 License * Copyright (c) 2008 - 2012 Appcelerator Inc * Refer to LICENSE for details of distribution and use. **/ #include "file_stream.h" #include <cstring> #include <sstream> #include <sys/stat.h> #include <Poco/LineEndingConverter.h> namespace ti { FileStream::FileStream(std::string filename) : Stream("Filesystem.FileStream"), istream(0), ostream(0), stream(0) { #ifdef OS_OSX // in OSX, we need to expand ~ in paths to their absolute path value // we do that with a nifty helper method in NSString this->filename = [[[NSString stringWithUTF8String:filename.c_str()] stringByExpandingTildeInPath] fileSystemRepresentation]; #else this->filename = filename; #endif this->SetMethod("open", &FileStream::_Open); this->SetMethod("isOpen", &FileStream::_IsOpen); this->SetMethod("close", &FileStream::_Close); this->SetMethod("seek", &FileStream::_Seek); this->SetMethod("tell", &FileStream::_Tell); this->SetMethod("write", &FileStream::_Write); this->SetMethod("read", &FileStream::_Read); this->SetMethod("readLine", &FileStream::_ReadLine); this->SetMethod("writeLine", &FileStream::_WriteLine); this->SetMethod("ready", &FileStream::_Ready); // These should be depricated and no longer used. // All constants should be kept on Ti.Filesystem object. this->Set("MODE_READ", Value::NewInt(MODE_READ)); this->Set("MODE_APPEND", Value::NewInt(MODE_APPEND)); this->Set("MODE_WRITE", Value::NewInt(MODE_WRITE)); } FileStream::~FileStream() { this->Close(); } bool FileStream::Open(FileStreamMode mode, bool binary, bool append) { // close the prev stream if needed this->Close(); try { std::ios::openmode flags = (std::ios::openmode) 0; bool output = false; if (binary) { flags|=std::ios::binary; } if (mode == MODE_APPEND) { flags|=std::ios::out|std::ios::app; output = true; } else if (mode == MODE_WRITE) { flags |= std::ios::out|std::ios::trunc; output = true; } else if (mode == MODE_READ) { flags |= std::ios::in; } if (output) { this->ostream = new Poco::FileOutputStream(this->filename,flags); this->stream = this->ostream; #ifndef OS_WIN32 chmod(this->filename.c_str(),S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH); #endif } else { this->istream = new Poco::FileInputStream(this->filename,flags); this->stream = this->istream; } return true; } catch (Poco::Exception& exc) { Logger* logger = Logger::Get("Filesystem.FileStream"); logger->Error("Error in open. Exception: %s",exc.displayText().c_str()); throw ValueException::FromString(exc.displayText()); } } bool FileStream::IsOpen() const { return this->stream != NULL; } void FileStream::Close() { try { if (this->stream) { if (this->ostream) { this->ostream->flush(); } this->stream->close(); delete this->stream; this->stream = NULL; this->istream = NULL; this->ostream = NULL; } } catch (Poco::Exception& exc) { Logger* logger = Logger::Get("Filesystem.FileStream"); logger->Error("Error in close. Exception: %s",exc.displayText().c_str()); throw ValueException::FromString(exc.displayText()); } } void FileStream::Seek(int offset, int direction) { if (this->istream) this->istream->seekg(offset, (std::ios::seekdir)direction); else if (this->ostream) this->ostream->seekp(offset, (std::ios::seekdir)direction); else throw ValueException::FromString("FileStream must be opened before seeking"); } int FileStream::Tell() { if (this->istream) return this->istream->tellg(); else if (this->ostream) return this->ostream->tellp(); throw ValueException::FromString("FileStream must be opend before using tell"); } void FileStream::Write(const char* buffer, size_t size) { if(!this->ostream) throw ValueException::FromString("FileStream must be opened for writing before calling write"); try { this->ostream->write(buffer, size); } catch (Poco::Exception& ex) { Logger* logger = Logger::Get("Filesystem.FileStream"); logger->Error("Error in write. Exception: %s",ex.displayText().c_str()); throw ValueException::FromString(ex.displayText()); } } bool FileStream::IsWritable() const { return this->ostream != NULL; } size_t FileStream::Read(const char* buffer, size_t size) { if(!this->istream) throw ValueException::FromString("FileStream must be opened for writing before calling write"); try { this->istream->read((char*)buffer, size); return this->istream->gcount(); } catch (Poco::Exception& ex) { Logger* logger = Logger::Get("Filesystem.FileStream"); logger->Error("Error in read. Exception: %s",ex.displayText().c_str()); throw ValueException::FromString(ex.displayText()); } } bool FileStream::IsReadable() const { return this->istream != NULL; } void FileStream::_Open(const ValueList& args, ValueRef result) { args.VerifyException("open", "?ibb"); FileStreamMode mode = (FileStreamMode) args.GetInt(0, MODE_READ); bool binary = args.GetBool(1, false); bool append = args.GetBool(2, false); bool opened = this->Open(mode, binary, append); result->SetBool(opened); } void FileStream::_IsOpen(const ValueList& args, ValueRef result) { result->SetBool(this->IsOpen()); } void FileStream::_Close(const ValueList& args, ValueRef result) { this->Close(); } void FileStream::_Seek(const ValueList& args, ValueRef result) { args.VerifyException("seek", "i?i"); int offset = args.GetInt(0); int direction = args.GetInt(1, std::ios::beg); this->Seek(offset, direction); } void FileStream::_Tell(const ValueList& args, ValueRef result) { result->SetInt(this->Tell()); } void FileStream::_Write(const ValueList& args, ValueRef result) { args.VerifyException("write", "s|o|n"); char *text = NULL; int size = 0; if (args.at(0)->IsObject()) { TiObjectRef b = args.at(0)->ToObject(); AutoPtr<Bytes> bytes = b.cast<Bytes>(); if (!bytes.isNull()) { text = (char*)bytes->Pointer(); size = (int)bytes->Length(); } } else if (args.at(0)->IsString()) { text = (char*)args.at(0)->ToString(); } else if (args.at(0)->IsInt()) { std::stringstream ostr; ostr << args.at(0)->ToInt(); text = (char*)ostr.str().c_str(); size = ostr.str().length(); } else if (args.at(0)->IsDouble()) { std::stringstream ostr; ostr << args.at(0)->ToDouble(); text = (char*)ostr.str().c_str(); size = ostr.str().length(); } else { throw ValueException::FromString("Could not write with type passed"); } if (size==0) { size = strlen(text); } if (text == NULL || size <= 0) { result->SetBool(false); return; } Write(text,size); result->SetBool(true); } void FileStream::_Read(const ValueList& args, ValueRef result) { args.VerifyException("read", "?i"); try { if (args.size() >= 1) { int size = args.GetInt(0); if (size <= 0) throw ValueException::FromString("File.read() size must be greater than zero"); BytesRef buffer = new Bytes(size + 1); int readCount = this->Read(buffer->Pointer(), size); if (readCount > 0) { buffer->Write("\0", 1, readCount); result->SetObject(buffer); } else { // No data read, must be at EOF result->SetNull(); } } else { // If no read size is provided, read the entire file. // TODO: this is not a very efficent method and should be deprecated // and replaced by buffered stream transports std::vector<char> buffer; char data[4096]; while (!this->istream->eof()) { this->istream->read((char*)&data, 4095); int length = this->istream->gcount(); if (length > 0) { buffer.insert(buffer.end(), data, data+length); } else break; } result->SetObject(new Bytes(&(buffer[0]), buffer.size())); } } catch (Poco::Exception& exc) { Logger* logger = Logger::Get("Filesystem.FileStream"); logger->Error("Error in read. Exception: %s",exc.displayText().c_str()); throw ValueException::FromString(exc.displayText()); } } void FileStream::_ReadLine(const ValueList& args, ValueRef result) { try { if (!this->istream) { Logger* logger = Logger::Get("Filesystem.FileStream"); logger->Error("Error in readLine. FileInputStream is null"); throw ValueException::FromString("FileStream must be opened for reading before calling readLine"); } if (this->istream->eof()) { // close the file result->SetNull(); } else { std::string line; std::getline(*this->istream, line); #ifdef OS_WIN32 // In some cases std::getline leaves a CR on the end of the line in win32 -- why God, why? if (!line.empty()) { char lastChar = line.at(line.size()-1); if (lastChar == '\r') { line = line.substr(0, line.size()-1); } } #endif if (line.empty() || line.size()==0) { if (this->istream->eof()) { // if this is EOF, return null result->SetNull(); } else { // this is an empty line, just empty Bytes object. result->SetObject(new Bytes()); } } else { result->SetObject(new Bytes(line)); } } } catch (Poco::Exception& exc) { Logger* logger = Logger::Get("Filesystem.FileStream"); logger->Error("Error in readLine. Exception: %s",exc.displayText().c_str()); throw ValueException::FromString(exc.displayText()); } } void FileStream::_WriteLine(const ValueList& args, ValueRef result) { args.VerifyException("writeLine", "s|o|n"); if(! this->stream) { throw ValueException::FromString("FileStream must be opened before calling readLine"); } char *text = NULL; int size = 0; if (args.at(0)->IsObject()) { TiObjectRef b = args.at(0)->ToObject(); AutoPtr<Bytes> bytes = b.cast<Bytes>(); if (!bytes.isNull()) { text = (char*)bytes->Pointer(); size = (int)bytes->Length(); } } else if (args.at(0)->IsString()) { text = (char*)args.at(0)->ToString(); } else if (args.at(0)->IsInt()) { std::stringstream ostr; ostr << args.at(0)->ToInt(); text = (char*)ostr.str().c_str(); size = ostr.str().length(); } else if (args.at(0)->IsDouble()) { std::stringstream ostr; ostr << args.at(0)->ToDouble(); text = (char*)ostr.str().c_str(); size = ostr.str().length(); } else { throw ValueException::FromString("Could not write with type passed"); } if (size==0) { size = strlen(text); } if (text == NULL || size <= 0) { result->SetBool(false); return; } std::string astr = text; #ifdef OS_WIN32 astr += "\r\n"; #else astr += "\n"; #endif Write((char*)astr.c_str(),astr.length()); result->SetBool(true); } void FileStream::_Ready(const ValueList& args, ValueRef result) { if(!this->stream) { result->SetBool(false); } else { result->SetBool(this->stream->eof()==false); } } }
26.452282
110
0.552627
badlee
81a57fbb39618fb478255792c263a7155cfa18ea
2,439
cpp
C++
modules/bindings/src/loggerdevice.cpp
OpenMA/openma
6f3b55292fd0a862b3444f11d71d0562cfe81ac1
[ "Unlicense" ]
41
2016-06-28T13:51:39.000Z
2022-01-20T16:33:00.000Z
modules/bindings/src/loggerdevice.cpp
bmswgnp/openma
6f3b55292fd0a862b3444f11d71d0562cfe81ac1
[ "Unlicense" ]
82
2016-04-09T15:19:31.000Z
2018-11-15T18:56:12.000Z
modules/bindings/src/loggerdevice.cpp
bmswgnp/openma
6f3b55292fd0a862b3444f11d71d0562cfe81ac1
[ "Unlicense" ]
9
2016-03-29T14:28:31.000Z
2020-07-29T07:39:19.000Z
/* * Open Source Movement Analysis Library * Copyright (C) 2016, Moveck Solution Inc., all rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above * copyright notice, this list of conditions and the following * disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials * provided with the distribution. * * Neither the name(s) of the copyright holders nor the names * of its contributors may be used to endorse or promote products * derived from this software without specific prior written * permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include "openma/bindings/loggerdevice.h" namespace ma { namespace bindings { LoggerDevice::LoggerDevice() : m_ErrorFlag(false), m_ErrorMessage() {}; void LoggerDevice::clearError() { this->m_ErrorFlag = false; this->m_ErrorMessage.clear(); }; bool LoggerDevice::errorFlag() const _OPENMA_NOEXCEPT { return this->m_ErrorFlag; }; const std::string& LoggerDevice::errorMessage() const _OPENMA_NOEXCEPT { return this->m_ErrorMessage; }; void LoggerDevice::write(ma::Message category, const char* msg) _OPENMA_NOEXCEPT { if (category == ma::Message::Error) { this->m_ErrorFlag = true; this->m_ErrorMessage.append("\n"); this->m_ErrorMessage.append(msg); } }; }; };
34.352113
82
0.715457
OpenMA
81a5df87357c8f940e4c2aacfc8b016b64853a6a
5,921
cc
C++
third_party/blink/renderer/platform/graphics/filters/fe_lighting.cc
Ron423c/chromium
2edf7b980065b648f8b2a6e52193d83832fe36b7
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
575
2015-06-18T23:58:20.000Z
2022-03-23T09:32:39.000Z
third_party/blink/renderer/platform/graphics/filters/fe_lighting.cc
Ron423c/chromium
2edf7b980065b648f8b2a6e52193d83832fe36b7
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
113
2015-05-04T09:58:14.000Z
2022-01-31T19:35:03.000Z
third_party/blink/renderer/platform/graphics/filters/fe_lighting.cc
iridium-browser/iridium-browser
907e31cf5ce5ad14d832796e3a7c11e496828959
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
52
2015-07-14T10:40:50.000Z
2022-03-15T01:11:49.000Z
/* * Copyright (C) 2010 University of Szeged * Copyright (C) 2010 Zoltan Herczeg * Copyright (C) 2013 Google Inc. 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 UNIVERSITY OF SZEGED ``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 UNIVERSITY OF SZEGED 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. */ #include "third_party/blink/renderer/platform/graphics/filters/fe_lighting.h" #include "third_party/blink/renderer/platform/graphics/filters/distant_light_source.h" #include "third_party/blink/renderer/platform/graphics/filters/paint_filter_builder.h" #include "third_party/blink/renderer/platform/graphics/filters/point_light_source.h" #include "third_party/blink/renderer/platform/graphics/filters/spot_light_source.h" #include "third_party/skia/include/core/SkPoint3.h" namespace blink { FELighting::FELighting(Filter* filter, LightingType lighting_type, const Color& lighting_color, float surface_scale, float diffuse_constant, float specular_constant, float specular_exponent, scoped_refptr<LightSource> light_source) : FilterEffect(filter), lighting_type_(lighting_type), light_source_(std::move(light_source)), lighting_color_(lighting_color), surface_scale_(surface_scale), diffuse_constant_(std::max(diffuse_constant, 0.0f)), specular_constant_(std::max(specular_constant, 0.0f)), specular_exponent_(clampTo(specular_exponent, 1.0f, 128.0f)) {} sk_sp<PaintFilter> FELighting::CreateImageFilter() { if (!light_source_) return CreateTransparentBlack(); base::Optional<PaintFilter::CropRect> crop_rect = GetCropRect(); const PaintFilter::CropRect* rect = base::OptionalOrNullptr(crop_rect); Color light_color = AdaptColorToOperatingInterpolationSpace(lighting_color_); sk_sp<PaintFilter> input(paint_filter_builder::Build( InputEffect(0), OperatingInterpolationSpace())); switch (light_source_->GetType()) { case LS_DISTANT: { DistantLightSource* distant_light_source = static_cast<DistantLightSource*>(light_source_.get()); float azimuth_rad = deg2rad(distant_light_source->Azimuth()); float elevation_rad = deg2rad(distant_light_source->Elevation()); const SkPoint3 direction = SkPoint3::Make( cosf(azimuth_rad) * cosf(elevation_rad), sinf(azimuth_rad) * cosf(elevation_rad), sinf(elevation_rad)); return sk_make_sp<LightingDistantPaintFilter>( GetLightingType(), direction, light_color.Rgb(), surface_scale_, GetFilterConstant(), specular_exponent_, std::move(input), rect); } case LS_POINT: { PointLightSource* point_light_source = static_cast<PointLightSource*>(light_source_.get()); const FloatPoint3D position = point_light_source->GetPosition(); const SkPoint3 sk_position = SkPoint3::Make(position.X(), position.Y(), position.Z()); return sk_make_sp<LightingPointPaintFilter>( GetLightingType(), sk_position, light_color.Rgb(), surface_scale_, GetFilterConstant(), specular_exponent_, std::move(input), rect); } case LS_SPOT: { SpotLightSource* spot_light_source = static_cast<SpotLightSource*>(light_source_.get()); const SkPoint3 location = SkPoint3::Make(spot_light_source->GetPosition().X(), spot_light_source->GetPosition().Y(), spot_light_source->GetPosition().Z()); const SkPoint3 target = SkPoint3::Make(spot_light_source->Direction().X(), spot_light_source->Direction().Y(), spot_light_source->Direction().Z()); float specular_exponent = spot_light_source->SpecularExponent(); float limiting_cone_angle = spot_light_source->LimitingConeAngle(); if (!limiting_cone_angle || limiting_cone_angle > 90 || limiting_cone_angle < -90) limiting_cone_angle = 90; return sk_make_sp<LightingSpotPaintFilter>( GetLightingType(), location, target, specular_exponent, limiting_cone_angle, light_color.Rgb(), surface_scale_, GetFilterConstant(), specular_exponent_, std::move(input), rect); } default: NOTREACHED(); return nullptr; } } PaintFilter::LightingType FELighting::GetLightingType() { return specular_constant_ > 0 ? PaintFilter::LightingType::kSpecular : PaintFilter::LightingType::kDiffuse; } float FELighting::GetFilterConstant() { return GetLightingType() == PaintFilter::LightingType::kSpecular ? specular_constant_ : diffuse_constant_; } } // namespace blink
47.368
86
0.703597
Ron423c
81a88c5d877373caa948e8f5d4af79e8f1f8b328
12,808
cpp
C++
media/libeffects/lvm/lib/SpectrumAnalyzer/src/LVPSA_Process.cpp
Dreadwyrm/lhos_frameworks_av
62c63ccfdf5c79a3ad9be4836f473da9398c671b
[ "Apache-2.0" ]
null
null
null
media/libeffects/lvm/lib/SpectrumAnalyzer/src/LVPSA_Process.cpp
Dreadwyrm/lhos_frameworks_av
62c63ccfdf5c79a3ad9be4836f473da9398c671b
[ "Apache-2.0" ]
null
null
null
media/libeffects/lvm/lib/SpectrumAnalyzer/src/LVPSA_Process.cpp
Dreadwyrm/lhos_frameworks_av
62c63ccfdf5c79a3ad9be4836f473da9398c671b
[ "Apache-2.0" ]
2
2021-07-08T07:42:11.000Z
2021-07-09T21:56:10.000Z
/* * Copyright (C) 2004-2010 NXP Software * Copyright (C) 2010 The Android Open Source Project * * 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 "LVPSA.h" #include "LVPSA_Private.h" #include "LVM_Macros.h" #include "VectorArithmetic.h" #define LVM_MININT_32 0x80000000 static LVM_INT32 mult32x32in32_shiftr(LVM_INT32 a, LVM_INT32 b, LVM_INT32 c) { LVM_INT64 result = ((LVM_INT64)a * b) >> c; if (result >= INT32_MAX) { return INT32_MAX; } else if (result <= INT32_MIN) { return INT32_MIN; } else { return (LVM_INT32)result; } } /************************************************************************************/ /* */ /* FUNCTION: LVPSA_Process */ /* */ /* DESCRIPTION: */ /* The process applies band pass filters to the signal. Each output */ /* feeds a quasi peak filter for level detection. */ /* */ /* PARAMETERS: */ /* hInstance Pointer to the instance */ /* pLVPSA_InputSamples Pointer to the input samples buffer */ /* InputBlockSize Number of mono samples to process */ /* AudioTime Playback time of the input samples */ /* */ /* */ /* RETURNS: */ /* LVPSA_OK Succeeds */ /* otherwise Error due to bad parameters */ /* */ /************************************************************************************/ LVPSA_RETURN LVPSA_Process ( pLVPSA_Handle_t hInstance, LVM_FLOAT *pLVPSA_InputSamples, LVM_UINT16 InputBlockSize, LVPSA_Time AudioTime ) { LVPSA_InstancePr_t *pLVPSA_Inst = (LVPSA_InstancePr_t*)hInstance; LVM_FLOAT *pScratch; LVM_INT16 ii; LVM_INT32 AudioTimeInc; extern LVM_UINT32 LVPSA_SampleRateInvTab[]; LVM_UINT8 *pWrite_Save; /* Position of the write pointer at the beginning of the process */ /****************************************************************************** CHECK PARAMETERS *******************************************************************************/ if(hInstance == LVM_NULL || pLVPSA_InputSamples == LVM_NULL) { return(LVPSA_ERROR_NULLADDRESS); } if(InputBlockSize == 0 || InputBlockSize > pLVPSA_Inst->MaxInputBlockSize) { return(LVPSA_ERROR_INVALIDPARAM); } pScratch = (LVM_FLOAT*)pLVPSA_Inst->MemoryTable.Region[LVPSA_MEMREGION_SCRATCH].pBaseAddress; pWrite_Save = pLVPSA_Inst->pSpectralDataBufferWritePointer; /****************************************************************************** APPLY NEW SETTINGS IF NEEDED *******************************************************************************/ if (pLVPSA_Inst->bControlPending == LVM_TRUE) { pLVPSA_Inst->bControlPending = 0; LVPSA_ApplyNewSettings( pLVPSA_Inst); } /****************************************************************************** PROCESS SAMPLES *******************************************************************************/ /* Put samples in range [-0.5;0.5[ for BP filters (see Biquads documentation) */ Copy_Float(pLVPSA_InputSamples, pScratch, (LVM_INT16)InputBlockSize); Shift_Sat_Float(-1, pScratch, pScratch, (LVM_INT16)InputBlockSize); for (ii = 0; ii < pLVPSA_Inst->nRelevantFilters; ii++) { switch(pLVPSA_Inst->pBPFiltersPrecision[ii]) { case LVPSA_SimplePrecisionFilter: BP_1I_D16F16C14_TRC_WRA_01 ( &pLVPSA_Inst->pBP_Instances[ii], pScratch, pScratch + InputBlockSize, (LVM_INT16)InputBlockSize); break; case LVPSA_DoublePrecisionFilter: BP_1I_D16F32C30_TRC_WRA_01 ( &pLVPSA_Inst->pBP_Instances[ii], pScratch, pScratch + InputBlockSize, (LVM_INT16)InputBlockSize); break; default: break; } LVPSA_QPD_Process_Float ( pLVPSA_Inst, pScratch + InputBlockSize, (LVM_INT16)InputBlockSize, ii); } /****************************************************************************** UPDATE SpectralDataBufferAudioTime *******************************************************************************/ if(pLVPSA_Inst->pSpectralDataBufferWritePointer != pWrite_Save) { AudioTimeInc = mult32x32in32_shiftr( (AudioTime + ((LVM_INT32)pLVPSA_Inst->LocalSamplesCount * 1000)), (LVM_INT32)LVPSA_SampleRateInvTab[pLVPSA_Inst->CurrentParams.Fs], LVPSA_FsInvertShift); pLVPSA_Inst->SpectralDataBufferAudioTime = AudioTime + AudioTimeInc; } return(LVPSA_OK); } /************************************************************************************/ /* */ /* FUNCTION: LVPSA_GetSpectrum */ /* */ /* DESCRIPTION: */ /* Gets the levels values at a certain point in time */ /* */ /* */ /* PARAMETERS: */ /* hInstance Pointer to the instance */ /* GetSpectrumAudioTime Retrieve the values at this time */ /* pCurrentValues Pointer to a buffer that will contain levels' values */ /* pMaxValues Pointer to a buffer that will contain max levels' values */ /* */ /* */ /* RETURNS: */ /* LVPSA_OK Succeeds */ /* otherwise Error due to bad parameters */ /* */ /************************************************************************************/ LVPSA_RETURN LVPSA_GetSpectrum ( pLVPSA_Handle_t hInstance, LVPSA_Time GetSpectrumAudioTime, LVM_UINT8 *pCurrentValues, LVM_UINT8 *pPeakValues ) { LVPSA_InstancePr_t *pLVPSA_Inst = (LVPSA_InstancePr_t*)hInstance; LVM_INT32 StatusDelta, ii; LVM_UINT8 *pRead; if(hInstance == LVM_NULL || pCurrentValues == LVM_NULL || pPeakValues == LVM_NULL) { return(LVPSA_ERROR_NULLADDRESS); } /* First find the place where to look in the status buffer */ if(GetSpectrumAudioTime <= pLVPSA_Inst->SpectralDataBufferAudioTime) { MUL32x32INTO32((pLVPSA_Inst->SpectralDataBufferAudioTime - GetSpectrumAudioTime),LVPSA_InternalRefreshTimeInv,StatusDelta,LVPSA_InternalRefreshTimeShift); if((StatusDelta * LVPSA_InternalRefreshTime) != (pLVPSA_Inst->SpectralDataBufferAudioTime - GetSpectrumAudioTime)) { StatusDelta += 1; } } else { /* This part handles the wrap around */ MUL32x32INTO32(((pLVPSA_Inst->SpectralDataBufferAudioTime - (LVM_INT32)LVM_MININT_32) + ((LVM_INT32)LVM_MAXINT_32 - GetSpectrumAudioTime)),LVPSA_InternalRefreshTimeInv,StatusDelta,LVPSA_InternalRefreshTimeShift) if(((LVM_INT32)(StatusDelta * LVPSA_InternalRefreshTime)) != ((LVM_INT32)((pLVPSA_Inst->SpectralDataBufferAudioTime - (LVM_INT32)LVM_MININT_32) + ((LVM_INT32)LVM_MAXINT_32 - GetSpectrumAudioTime)))) { StatusDelta += 1; } } /* Check whether the desired level is not too "old" (see 2.10 in LVPSA_DesignNotes.doc)*/ if( ((GetSpectrumAudioTime < pLVPSA_Inst->SpectralDataBufferAudioTime)&& ((GetSpectrumAudioTime<0)&&(pLVPSA_Inst->SpectralDataBufferAudioTime>0))&& (((LVM_INT32)(-GetSpectrumAudioTime + pLVPSA_Inst->SpectralDataBufferAudioTime))>LVM_MAXINT_32))|| ((GetSpectrumAudioTime > pLVPSA_Inst->SpectralDataBufferAudioTime)&& (((GetSpectrumAudioTime>=0)&&(pLVPSA_Inst->SpectralDataBufferAudioTime>=0))|| ((GetSpectrumAudioTime<=0)&&(pLVPSA_Inst->SpectralDataBufferAudioTime<=0))|| (((GetSpectrumAudioTime>=0)&&(pLVPSA_Inst->SpectralDataBufferAudioTime<=0))&& (((LVM_INT32)(GetSpectrumAudioTime - pLVPSA_Inst->SpectralDataBufferAudioTime))<LVM_MAXINT_32))))|| (StatusDelta > (LVM_INT32)pLVPSA_Inst->SpectralDataBufferLength) || (!StatusDelta)) { for(ii = 0; ii < pLVPSA_Inst->nBands; ii++) { pCurrentValues[ii] = 0; pPeakValues[ii] = 0; } return(LVPSA_OK); } /* Set the reading pointer */ if((LVM_INT32)(StatusDelta * pLVPSA_Inst->nBands) > (pLVPSA_Inst->pSpectralDataBufferWritePointer - pLVPSA_Inst->pSpectralDataBufferStart)) { pRead = pLVPSA_Inst->pSpectralDataBufferWritePointer + (pLVPSA_Inst->SpectralDataBufferLength - (LVM_UINT32)StatusDelta) * pLVPSA_Inst->nBands; } else { pRead = pLVPSA_Inst->pSpectralDataBufferWritePointer - StatusDelta * pLVPSA_Inst->nBands; } /* Read the status buffer and fill the output buffers */ for(ii = 0; ii < pLVPSA_Inst->nBands; ii++) { pCurrentValues[ii] = pRead[ii]; if(pLVPSA_Inst->pPreviousPeaks[ii] <= pRead[ii]) { pLVPSA_Inst->pPreviousPeaks[ii] = pRead[ii]; } else if(pLVPSA_Inst->pPreviousPeaks[ii] != 0) { LVM_INT32 temp; /*Re-compute max values for decay */ temp = (LVM_INT32)(LVPSA_MAXUNSIGNEDCHAR - pLVPSA_Inst->pPreviousPeaks[ii]); temp = ((temp * LVPSA_MAXLEVELDECAYFACTOR)>>LVPSA_MAXLEVELDECAYSHIFT); /* If the gain has no effect, "help" the value to increase */ if(temp == (LVPSA_MAXUNSIGNEDCHAR - pLVPSA_Inst->pPreviousPeaks[ii])) { temp += 1; } /* Saturate */ temp = (temp > LVPSA_MAXUNSIGNEDCHAR) ? LVPSA_MAXUNSIGNEDCHAR : temp; /* Store new max level */ pLVPSA_Inst->pPreviousPeaks[ii] = (LVM_UINT8)(LVPSA_MAXUNSIGNEDCHAR - temp); } pPeakValues[ii] = pLVPSA_Inst->pPreviousPeaks[ii]; } return(LVPSA_OK); }
49.072797
219
0.462523
Dreadwyrm
81a957f1b1737e8ad6faa7205757a2dab551470d
2,109
cpp
C++
test/src/fetch_request_test.cpp
perchits/libkafka-asio
cbdced006d49a4498955a222915c6514b4ac57a7
[ "MIT" ]
77
2015-04-07T08:14:14.000Z
2022-02-14T01:07:05.000Z
test/src/fetch_request_test.cpp
perchits/libkafka-asio
cbdced006d49a4498955a222915c6514b4ac57a7
[ "MIT" ]
28
2015-04-07T08:57:41.000Z
2020-04-19T21:25:22.000Z
test/src/fetch_request_test.cpp
perchits/libkafka-asio
cbdced006d49a4498955a222915c6514b4ac57a7
[ "MIT" ]
48
2015-04-15T05:34:51.000Z
2022-03-17T11:50:20.000Z
// // fetch_request_test.cpp // ---------------------- // // Copyright (c) 2015 Daniel Joos // // Distributed under MIT license. (See file LICENSE) // #include <gtest/gtest.h> #include <libkafka_asio/libkafka_asio.h> class FetchRequestTest : public ::testing::Test { protected: virtual void SetUp() { ASSERT_EQ(0, request.topics().size()); } libkafka_asio::FetchRequest request; }; TEST_F(FetchRequestTest, FetchTopic_New) { request.FetchTopic("mytopic", 1, 2); ASSERT_EQ(1, request.topics().size()); ASSERT_EQ(1, request.topics()[0].partitions.size()); ASSERT_STREQ("mytopic", request.topics()[0].topic_name.c_str()); ASSERT_EQ(1, request.topics()[0].partitions[0].partition); ASSERT_EQ(2, request.topics()[0].partitions[0].fetch_offset); ASSERT_EQ(libkafka_asio::constants::kDefaultFetchMaxBytes, request.topics()[0].partitions[0].max_bytes); } TEST_F(FetchRequestTest, FetchTopic_Override) { request.FetchTopic("mytopic", 1, 2); ASSERT_EQ(1, request.topics().size()); ASSERT_EQ(1, request.topics()[0].partitions.size()); ASSERT_EQ(2, request.topics()[0].partitions[0].fetch_offset); request.FetchTopic("mytopic", 1, 4); ASSERT_EQ(1, request.topics().size()); ASSERT_EQ(1, request.topics()[0].partitions.size()); ASSERT_EQ(4, request.topics()[0].partitions[0].fetch_offset); } TEST_F(FetchRequestTest, FetchTopic_MultiplePartitions) { request.FetchTopic("mytopic", 0, 2); request.FetchTopic("mytopic", 1, 4); ASSERT_EQ(1, request.topics().size()); ASSERT_EQ(2, request.topics()[0].partitions.size()); ASSERT_EQ(2, request.topics()[0].partitions[0].fetch_offset); ASSERT_EQ(4, request.topics()[0].partitions[1].fetch_offset); } TEST_F(FetchRequestTest, FetchTopic_MultipleTopics) { request.FetchTopic("foo", 0, 2); request.FetchTopic("bar", 1, 4); ASSERT_EQ(2, request.topics().size()); ASSERT_EQ(1, request.topics()[0].partitions.size()); ASSERT_EQ(1, request.topics()[1].partitions.size()); ASSERT_EQ(2, request.topics()[0].partitions[0].fetch_offset); ASSERT_EQ(4, request.topics()[1].partitions[0].fetch_offset); }
30.565217
66
0.700806
perchits
81a99ce7a41dc4391f2f712f9b64fb747b4e3d52
18,533
cc
C++
third_party/blink/renderer/core/editing/commands/apply_block_element_command.cc
sarang-apps/darshan_browser
173649bb8a7c656dc60784d19e7bb73e07c20daa
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
third_party/blink/renderer/core/editing/commands/apply_block_element_command.cc
sarang-apps/darshan_browser
173649bb8a7c656dc60784d19e7bb73e07c20daa
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
third_party/blink/renderer/core/editing/commands/apply_block_element_command.cc
sarang-apps/darshan_browser
173649bb8a7c656dc60784d19e7bb73e07c20daa
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
2
2021-01-05T23:43:46.000Z
2021-01-07T23:36:34.000Z
/* * Copyright (C) 2006, 2008 Apple Inc. All rights reserved. * Copyright (C) 2010 Google Inc. 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. */ #include "third_party/blink/renderer/core/editing/commands/apply_block_element_command.h" #include "third_party/blink/renderer/core/dom/node_computed_style.h" #include "third_party/blink/renderer/core/dom/text.h" #include "third_party/blink/renderer/core/editing/commands/editing_commands_utilities.h" #include "third_party/blink/renderer/core/editing/editing_utilities.h" #include "third_party/blink/renderer/core/editing/selection_template.h" #include "third_party/blink/renderer/core/editing/visible_position.h" #include "third_party/blink/renderer/core/editing/visible_selection.h" #include "third_party/blink/renderer/core/editing/visible_units.h" #include "third_party/blink/renderer/core/html/html_br_element.h" #include "third_party/blink/renderer/core/html/html_element.h" #include "third_party/blink/renderer/core/html_names.h" #include "third_party/blink/renderer/core/style/computed_style.h" #include "third_party/blink/renderer/platform/bindings/exception_state.h" #include "third_party/blink/renderer/platform/heap/heap.h" namespace blink { ApplyBlockElementCommand::ApplyBlockElementCommand( Document& document, const QualifiedName& tag_name, const AtomicString& inline_style) : CompositeEditCommand(document), tag_name_(tag_name), inline_style_(inline_style) {} ApplyBlockElementCommand::ApplyBlockElementCommand( Document& document, const QualifiedName& tag_name) : CompositeEditCommand(document), tag_name_(tag_name) {} void ApplyBlockElementCommand::DoApply(EditingState* editing_state) { // ApplyBlockElementCommands are only created directly by editor commands' // execution, which updates layout before entering doApply(). DCHECK(!GetDocument().NeedsLayoutTreeUpdate()); if (!RootEditableElementOf(EndingSelection().Base())) return; VisiblePosition visible_end = EndingVisibleSelection().VisibleEnd(); VisiblePosition visible_start = EndingVisibleSelection().VisibleStart(); if (visible_start.IsNull() || visible_start.IsOrphan() || visible_end.IsNull() || visible_end.IsOrphan()) return; // When a selection ends at the start of a paragraph, we rarely paint // the selection gap before that paragraph, because there often is no gap. // In a case like this, it's not obvious to the user that the selection // ends "inside" that paragraph, so it would be confusing if Indent/Outdent // operated on that paragraph. // FIXME: We paint the gap before some paragraphs that are indented with left // margin/padding, but not others. We should make the gap painting more // consistent and then use a left margin/padding rule here. if (visible_end.DeepEquivalent() != visible_start.DeepEquivalent() && IsStartOfParagraph(visible_end)) { const Position& new_end = PreviousPositionOf(visible_end, kCannotCrossEditingBoundary) .DeepEquivalent(); SelectionInDOMTree::Builder builder; builder.Collapse(visible_start.ToPositionWithAffinity()); if (new_end.IsNotNull()) builder.Extend(new_end); SetEndingSelection(SelectionForUndoStep::From(builder.Build())); ABORT_EDITING_COMMAND_IF(EndingVisibleSelection().VisibleStart().IsNull()); ABORT_EDITING_COMMAND_IF(EndingVisibleSelection().VisibleEnd().IsNull()); } VisibleSelection selection = SelectionForParagraphIteration(EndingVisibleSelection()); VisiblePosition start_of_selection = selection.VisibleStart(); ABORT_EDITING_COMMAND_IF(start_of_selection.IsNull()); VisiblePosition end_of_selection = selection.VisibleEnd(); ABORT_EDITING_COMMAND_IF(end_of_selection.IsNull()); ContainerNode* start_scope = nullptr; int start_index = IndexForVisiblePosition(start_of_selection, start_scope); ContainerNode* end_scope = nullptr; int end_index = IndexForVisiblePosition(end_of_selection, end_scope); FormatSelection(start_of_selection, end_of_selection, editing_state); if (editing_state->IsAborted()) return; GetDocument().UpdateStyleAndLayout(DocumentUpdateReason::kEditing); DCHECK_EQ(start_scope, end_scope); DCHECK_GE(start_index, 0); DCHECK_LE(start_index, end_index); if (start_scope == end_scope && start_index >= 0 && start_index <= end_index) { VisiblePosition start(VisiblePositionForIndex(start_index, start_scope)); VisiblePosition end(VisiblePositionForIndex(end_index, end_scope)); if (start.IsNotNull() && end.IsNotNull()) { SetEndingSelection(SelectionForUndoStep::From( SelectionInDOMTree::Builder() .Collapse(start.ToPositionWithAffinity()) .Extend(end.DeepEquivalent()) .Build())); } } } static bool IsAtUnsplittableElement(const Position& pos) { Node* node = pos.AnchorNode(); return node == RootEditableElementOf(pos) || node == EnclosingNodeOfType(pos, &IsTableCell); } void ApplyBlockElementCommand::FormatSelection( const VisiblePosition& start_of_selection, const VisiblePosition& end_of_selection, EditingState* editing_state) { // Special case empty unsplittable elements because there's nothing to split // and there's nothing to move. const Position& caret_position = MostForwardCaretPosition(start_of_selection.DeepEquivalent()); if (IsAtUnsplittableElement(caret_position)) { HTMLElement* blockquote = CreateBlockElement(); InsertNodeAt(blockquote, caret_position, editing_state); if (editing_state->IsAborted()) return; auto* placeholder = MakeGarbageCollected<HTMLBRElement>(GetDocument()); AppendNode(placeholder, blockquote, editing_state); if (editing_state->IsAborted()) return; SetEndingSelection(SelectionForUndoStep::From( SelectionInDOMTree::Builder() .Collapse(Position::BeforeNode(*placeholder)) .Build())); return; } HTMLElement* blockquote_for_next_indent = nullptr; VisiblePosition end_of_current_paragraph = EndOfParagraph(start_of_selection); const VisiblePosition& visible_end_of_last_paragraph = EndOfParagraph(end_of_selection); const Position& end_of_next_last_paragraph = EndOfParagraph(NextPositionOf(visible_end_of_last_paragraph)) .DeepEquivalent(); Position end_of_last_paragraph = visible_end_of_last_paragraph.DeepEquivalent(); bool at_end = false; while (end_of_current_paragraph.DeepEquivalent() != end_of_next_last_paragraph && !at_end) { if (end_of_current_paragraph.DeepEquivalent() == end_of_last_paragraph) at_end = true; Position start, end; RangeForParagraphSplittingTextNodesIfNeeded( end_of_current_paragraph, end_of_last_paragraph, start, end); end_of_current_paragraph = CreateVisiblePosition(end); Node* enclosing_cell = EnclosingNodeOfType(start, &IsTableCell); PositionWithAffinity end_of_next_paragraph = EndOfNextParagrahSplittingTextNodesIfNeeded( end_of_current_paragraph, end_of_last_paragraph, start, end) .ToPositionWithAffinity(); FormatRange(start, end, end_of_last_paragraph, blockquote_for_next_indent, editing_state); if (editing_state->IsAborted()) return; // Don't put the next paragraph in the blockquote we just created for this // paragraph unless the next paragraph is in the same cell. if (enclosing_cell && enclosing_cell != EnclosingNodeOfType(end_of_next_paragraph.GetPosition(), &IsTableCell)) blockquote_for_next_indent = nullptr; // indentIntoBlockquote could move more than one paragraph if the paragraph // is in a list item or a table. As a result, // |endOfNextLastParagraph| could refer to a position no longer in the // document. if (end_of_next_last_paragraph.IsNotNull() && !end_of_next_last_paragraph.IsConnected()) break; // Sanity check: Make sure our moveParagraph calls didn't remove // endOfNextParagraph.anchorNode() If somehow, e.g. mutation // event handler, we did, return to prevent crashes. if (end_of_next_paragraph.IsNotNull() && !end_of_next_paragraph.IsConnected()) return; GetDocument().UpdateStyleAndLayout(DocumentUpdateReason::kEditing); end_of_current_paragraph = CreateVisiblePosition(end_of_next_paragraph); } } static bool IsNewLineAtPosition(const Position& position) { auto* text_node = DynamicTo<Text>(position.ComputeContainerNode()); int offset = position.OffsetInContainerNode(); if (!text_node || offset < 0 || offset >= static_cast<int>(text_node->length())) return false; DummyExceptionStateForTesting exception_state; String text_at_position = text_node->substringData(offset, 1, exception_state); if (exception_state.HadException()) return false; return text_at_position[0] == '\n'; } static const ComputedStyle* ComputedStyleOfEnclosingTextNode( const Position& position) { if (!position.IsOffsetInAnchor() || !position.ComputeContainerNode() || !position.ComputeContainerNode()->IsTextNode()) return nullptr; return position.ComputeContainerNode()->GetComputedStyle(); } void ApplyBlockElementCommand::RangeForParagraphSplittingTextNodesIfNeeded( const VisiblePosition& end_of_current_paragraph, Position& end_of_last_paragraph, Position& start, Position& end) { start = StartOfParagraph(end_of_current_paragraph).DeepEquivalent(); end = end_of_current_paragraph.DeepEquivalent(); bool is_start_and_end_on_same_node = false; if (const ComputedStyle* start_style = ComputedStyleOfEnclosingTextNode(start)) { is_start_and_end_on_same_node = ComputedStyleOfEnclosingTextNode(end) && start.ComputeContainerNode() == end.ComputeContainerNode(); bool is_start_and_end_of_last_paragraph_on_same_node = ComputedStyleOfEnclosingTextNode(end_of_last_paragraph) && start.ComputeContainerNode() == end_of_last_paragraph.ComputeContainerNode(); // Avoid obtanining the start of next paragraph for start // TODO(yosin) We should use |PositionMoveType::CodePoint| for // |previousPositionOf()|. if (start_style->PreserveNewline() && IsNewLineAtPosition(start) && !IsNewLineAtPosition( PreviousPositionOf(start, PositionMoveType::kCodeUnit)) && start.OffsetInContainerNode() > 0) start = StartOfParagraph(CreateVisiblePosition(PreviousPositionOf( end, PositionMoveType::kCodeUnit))) .DeepEquivalent(); // If start is in the middle of a text node, split. if (!start_style->CollapseWhiteSpace() && start.OffsetInContainerNode() > 0) { int start_offset = start.OffsetInContainerNode(); auto* start_text = To<Text>(start.ComputeContainerNode()); SplitTextNode(start_text, start_offset); GetDocument().UpdateStyleAndLayoutTree(); start = Position::FirstPositionInNode(*start_text); if (is_start_and_end_on_same_node) { DCHECK_GE(end.OffsetInContainerNode(), start_offset); end = Position(start_text, end.OffsetInContainerNode() - start_offset); } if (is_start_and_end_of_last_paragraph_on_same_node) { DCHECK_GE(end_of_last_paragraph.OffsetInContainerNode(), start_offset); end_of_last_paragraph = Position(start_text, end_of_last_paragraph.OffsetInContainerNode() - start_offset); } } } if (const ComputedStyle* end_style = ComputedStyleOfEnclosingTextNode(end)) { bool is_end_and_end_of_last_paragraph_on_same_node = ComputedStyleOfEnclosingTextNode(end_of_last_paragraph) && end.AnchorNode() == end_of_last_paragraph.AnchorNode(); // Include \n at the end of line if we're at an empty paragraph if (end_style->PreserveNewline() && start == end && end.OffsetInContainerNode() < static_cast<int>(To<Text>(end.ComputeContainerNode())->length())) { int end_offset = end.OffsetInContainerNode(); // TODO(yosin) We should use |PositionMoveType::CodePoint| for // |previousPositionOf()|. if (!IsNewLineAtPosition( PreviousPositionOf(end, PositionMoveType::kCodeUnit)) && IsNewLineAtPosition(end)) end = Position(end.ComputeContainerNode(), end_offset + 1); if (is_end_and_end_of_last_paragraph_on_same_node && end.OffsetInContainerNode() >= end_of_last_paragraph.OffsetInContainerNode()) end_of_last_paragraph = end; } // If end is in the middle of a text node, split. if (end_style->UserModify() != EUserModify::kReadOnly && !end_style->CollapseWhiteSpace() && end.OffsetInContainerNode() && end.OffsetInContainerNode() < static_cast<int>(To<Text>(end.ComputeContainerNode())->length())) { auto* end_container = To<Text>(end.ComputeContainerNode()); SplitTextNode(end_container, end.OffsetInContainerNode()); GetDocument().UpdateStyleAndLayoutTree(); const Node* const previous_sibling_of_end = end_container->previousSibling(); DCHECK(previous_sibling_of_end); if (is_start_and_end_on_same_node) { start = FirstPositionInOrBeforeNode(*previous_sibling_of_end); } if (is_end_and_end_of_last_paragraph_on_same_node) { if (end_of_last_paragraph.OffsetInContainerNode() == end.OffsetInContainerNode()) { end_of_last_paragraph = LastPositionInOrAfterNode(*previous_sibling_of_end); } else { end_of_last_paragraph = Position( end_container, end_of_last_paragraph.OffsetInContainerNode() - end.OffsetInContainerNode()); } } end = Position::LastPositionInNode(*previous_sibling_of_end); } } } VisiblePosition ApplyBlockElementCommand::EndOfNextParagrahSplittingTextNodesIfNeeded( VisiblePosition& end_of_current_paragraph, Position& end_of_last_paragraph, Position& start, Position& end) { const VisiblePosition& end_of_next_paragraph = EndOfParagraph(NextPositionOf(end_of_current_paragraph)); const Position& end_of_next_paragraph_position = end_of_next_paragraph.DeepEquivalent(); const ComputedStyle* style = ComputedStyleOfEnclosingTextNode(end_of_next_paragraph_position); if (!style) return end_of_next_paragraph; auto* const end_of_next_paragraph_text = To<Text>(end_of_next_paragraph_position.ComputeContainerNode()); if (!style->PreserveNewline() || !end_of_next_paragraph_position.OffsetInContainerNode() || !IsNewLineAtPosition( Position::FirstPositionInNode(*end_of_next_paragraph_text))) return end_of_next_paragraph; // \n at the beginning of the text node immediately following the current // paragraph is trimmed by moveParagraphWithClones. If endOfNextParagraph was // pointing at this same text node, endOfNextParagraph will be shifted by one // paragraph. Avoid this by splitting "\n" SplitTextNode(end_of_next_paragraph_text, 1); GetDocument().UpdateStyleAndLayout(DocumentUpdateReason::kEditing); Text* const previous_text = DynamicTo<Text>(end_of_next_paragraph_text->previousSibling()); if (end_of_next_paragraph_text == start.ComputeContainerNode() && previous_text) { DCHECK_LT(start.OffsetInContainerNode(), end_of_next_paragraph_position.OffsetInContainerNode()); start = Position(previous_text, start.OffsetInContainerNode()); } if (end_of_next_paragraph_text == end.ComputeContainerNode() && previous_text) { DCHECK_LT(end.OffsetInContainerNode(), end_of_next_paragraph_position.OffsetInContainerNode()); end = Position(previous_text, end.OffsetInContainerNode()); } if (end_of_next_paragraph_text == end_of_last_paragraph.ComputeContainerNode()) { if (end_of_last_paragraph.OffsetInContainerNode() < end_of_next_paragraph_position.OffsetInContainerNode()) { // We can only fix endOfLastParagraph if the previous node was still text // and hasn't been modified by script. if (previous_text && static_cast<unsigned>( end_of_last_paragraph.OffsetInContainerNode()) <= previous_text->length()) { end_of_last_paragraph = Position( previous_text, end_of_last_paragraph.OffsetInContainerNode()); } } else { end_of_last_paragraph = Position(end_of_next_paragraph_text, end_of_last_paragraph.OffsetInContainerNode() - 1); } } return CreateVisiblePosition( Position(end_of_next_paragraph_text, end_of_next_paragraph_position.OffsetInContainerNode() - 1)); } HTMLElement* ApplyBlockElementCommand::CreateBlockElement() const { HTMLElement* element = CreateHTMLElement(GetDocument(), tag_name_); if (inline_style_.length()) element->setAttribute(html_names::kStyleAttr, inline_style_); return element; } } // namespace blink
43.917062
89
0.732261
sarang-apps
81ac79b2f71f976e02888fc20fceb936a204eb47
6,368
cpp
C++
src/graphics/Color.cpp
bigplayszn/nCine
43f5fe8e82e9daa21e4d1feea9ca41ed4cce7454
[ "MIT" ]
675
2019-05-28T19:00:55.000Z
2022-03-31T16:44:28.000Z
src/graphics/Color.cpp
bigplayszn/nCine
43f5fe8e82e9daa21e4d1feea9ca41ed4cce7454
[ "MIT" ]
13
2020-03-29T06:46:32.000Z
2022-01-29T03:19:30.000Z
src/graphics/Color.cpp
bigplayszn/nCine
43f5fe8e82e9daa21e4d1feea9ca41ed4cce7454
[ "MIT" ]
53
2019-06-02T03:04:10.000Z
2022-03-11T06:17:50.000Z
#include "Color.h" #include "Colorf.h" #include <nctl/algorithms.h> namespace ncine { /////////////////////////////////////////////////////////// // STATIC DEFINITIONS /////////////////////////////////////////////////////////// const Color Color::Black(0, 0, 0, 255); const Color Color::White(255, 255, 255, 255); const Color Color::Red(255, 0, 0, 255); const Color Color::Green(0, 255, 0, 255); const Color Color::Blue(0, 0, 255, 255); const Color Color::Yellow(255, 255, 0, 255); const Color Color::Magenta(255, 0, 255, 255); const Color Color::Cyan(0, 255, 255, 255); /////////////////////////////////////////////////////////// // CONSTRUCTORS and DESTRUCTOR /////////////////////////////////////////////////////////// Color::Color() : Color(255, 255, 255, 255) { } Color::Color(unsigned int red, unsigned int green, unsigned int blue) : Color(red, green, blue, 255) { } Color::Color(unsigned int red, unsigned int green, unsigned int blue, unsigned int alpha) : channels_(nctl::StaticArrayMode::EXTEND_SIZE) { set(red, green, blue, alpha); } Color::Color(unsigned int hex) : channels_(nctl::StaticArrayMode::EXTEND_SIZE) { setAlpha(255); // The following method might set the alpha channel set(hex); } Color::Color(const unsigned int channels[NumChannels]) : channels_(nctl::StaticArrayMode::EXTEND_SIZE) { setVec(channels); } Color::Color(const Colorf &color) : channels_(nctl::StaticArrayMode::EXTEND_SIZE) { channels_[0] = static_cast<unsigned char>(color.r() * 255); channels_[1] = static_cast<unsigned char>(color.g() * 255); channels_[2] = static_cast<unsigned char>(color.b() * 255); channels_[3] = static_cast<unsigned char>(color.a() * 255); } /////////////////////////////////////////////////////////// // PUBLIC FUNCTIONS /////////////////////////////////////////////////////////// unsigned int Color::rgba() const { return (channels_[0] << 24) + (channels_[1] << 16) + (channels_[2] << 8) + channels_[3]; } unsigned int Color::argb() const { return (channels_[3] << 24) + (channels_[0] << 16) + (channels_[1] << 8) + channels_[2]; } unsigned int Color::abgr() const { return (channels_[3] << 24) + (channels_[2] << 16) + (channels_[1] << 8) + channels_[0]; } unsigned int Color::bgra() const { return (channels_[2] << 24) + (channels_[1] << 16) + (channels_[0] << 8) + channels_[3]; } void Color::set(unsigned int red, unsigned int green, unsigned int blue, unsigned int alpha) { channels_[0] = static_cast<unsigned char>(red); channels_[1] = static_cast<unsigned char>(green); channels_[2] = static_cast<unsigned char>(blue); channels_[3] = static_cast<unsigned char>(alpha); } void Color::set(unsigned int red, unsigned int green, unsigned int blue) { channels_[0] = static_cast<unsigned char>(red); channels_[1] = static_cast<unsigned char>(green); channels_[2] = static_cast<unsigned char>(blue); } void Color::set(unsigned int hex) { channels_[0] = static_cast<unsigned char>((hex & 0xFF0000) >> 16); channels_[1] = static_cast<unsigned char>((hex & 0xFF00) >> 8); channels_[2] = static_cast<unsigned char>(hex & 0xFF); if (hex > 0xFFFFFF) channels_[3] = static_cast<unsigned char>((hex & 0xFF000000) >> 24); } void Color::setVec(const unsigned int channels[NumChannels]) { set(channels[0], channels[1], channels[2], channels[3]); } void Color::setAlpha(unsigned int alpha) { channels_[3] = static_cast<unsigned char>(alpha); } Color &Color::operator=(const Colorf &color) { channels_[0] = static_cast<unsigned char>(color.r() * 255.0f); channels_[1] = static_cast<unsigned char>(color.g() * 255.0f); channels_[2] = static_cast<unsigned char>(color.b() * 255.0f); channels_[3] = static_cast<unsigned char>(color.a() * 255.0f); return *this; } bool Color::operator==(const Color &color) const { return (r() == color.r() && g() == color.g() && b() == color.b() && a() == color.a()); } Color &Color::operator+=(const Color &color) { for (unsigned int i = 0; i < NumChannels; i++) { unsigned int channelValue = channels_[i] + color.channels_[i]; channelValue = nctl::clamp(channelValue, 0U, 255U); channels_[i] = static_cast<unsigned char>(channelValue); } return *this; } Color &Color::operator-=(const Color &color) { for (unsigned int i = 0; i < NumChannels; i++) { unsigned int channelValue = channels_[i] - color.channels_[i]; channelValue = nctl::clamp(channelValue, 0U, 255U); channels_[i] = static_cast<unsigned char>(channelValue); } return *this; } Color &Color::operator*=(const Color &color) { for (unsigned int i = 0; i < NumChannels; i++) { float channelValue = channels_[i] * (color.channels_[i] / 255.0f); channelValue = nctl::clamp(channelValue, 0.0f, 255.0f); channels_[i] = static_cast<unsigned char>(channelValue); } return *this; } Color &Color::operator*=(float scalar) { for (unsigned int i = 0; i < NumChannels; i++) { float channelValue = channels_[i] * scalar; channelValue = nctl::clamp(channelValue, 0.0f, 255.0f); channels_[i] = static_cast<unsigned char>(channelValue); } return *this; } Color Color::operator+(const Color &color) const { Color result; for (unsigned int i = 0; i < NumChannels; i++) { unsigned int channelValue = channels_[i] + color.channels_[i]; channelValue = nctl::clamp(channelValue, 0U, 255U); result.channels_[i] = static_cast<unsigned char>(channelValue); } return result; } Color Color::operator-(const Color &color) const { Color result; for (unsigned int i = 0; i < NumChannels; i++) { unsigned int channelValue = channels_[i] - color.channels_[i]; channelValue = nctl::clamp(channelValue, 0U, 255U); result.channels_[i] = static_cast<unsigned char>(channelValue); } return result; } Color Color::operator*(const Color &color) const { Color result; for (unsigned int i = 0; i < NumChannels; i++) { float channelValue = channels_[i] * (color.channels_[i] / 255.0f); channelValue = nctl::clamp(channelValue, 0.0f, 255.0f); result.channels_[i] = static_cast<unsigned char>(channelValue); } return result; } Color Color::operator*(float scalar) const { Color result; for (unsigned int i = 0; i < NumChannels; i++) { float channelValue = channels_[i] * scalar; channelValue = nctl::clamp(channelValue, 0.0f, 255.0f); result.channels_[i] = static_cast<unsigned char>(channelValue); } return result; } }
26.205761
92
0.642588
bigplayszn
81b344fc301f62971a7fa3913a9e10952f711638
33
cpp
C++
Alerter/Alerter.cpp
gr82morozr/iot-common
3de2e0a9ff4d6cdf71d7f47a7709574e4777d831
[ "MIT" ]
1
2022-01-22T23:56:51.000Z
2022-01-22T23:56:51.000Z
Alerter/Alerter.cpp
gr82morozr/iot-common
3de2e0a9ff4d6cdf71d7f47a7709574e4777d831
[ "MIT" ]
null
null
null
Alerter/Alerter.cpp
gr82morozr/iot-common
3de2e0a9ff4d6cdf71d7f47a7709574e4777d831
[ "MIT" ]
null
null
null
#include <Alerter/Alerter.h>
5.5
28
0.666667
gr82morozr
81b61523d4ac1c0b5ede6db155a0c87b938828be
1,315
cpp
C++
leetcode/cpp/qt_palindrome_permutation.cpp
qiaotian/CodeInterview
294c1ba86d8ace41a121c5ada4ba4c3765ccc17d
[ "WTFPL" ]
5
2016-10-29T09:28:11.000Z
2019-10-19T23:02:48.000Z
leetcode/cpp/qt_palindrome_permutation.cpp
qiaotian/CodeInterview
294c1ba86d8ace41a121c5ada4ba4c3765ccc17d
[ "WTFPL" ]
null
null
null
leetcode/cpp/qt_palindrome_permutation.cpp
qiaotian/CodeInterview
294c1ba86d8ace41a121c5ada4ba4c3765ccc17d
[ "WTFPL" ]
null
null
null
/** * @Author: Tian Qiao <qiaotian> * @Date: 2016-07-03T11:17:52+08:00 * @Email: qiaotian@me.com * @Last modified by: qiaotian * @Last modified time: 2016-07-03T11:19:50+08:00 * @License: Free License * @Inc: Google, Uber * @Easy */ Given a string, determine if a permutation of the string could form a palindrome. For example, "code" -> False, "aab" -> True, "carerac" -> True. Hint: 1. Consider the palindromes of odd vs even length. What difference do you notice? 2. Count the frequency of each character. 3. If each character occurs even number of times, then it must be a palindrome. How about character which occurs odd number of times? ________________________________________________________________________________ class Solution { public: /* bool canPermutePalindrome(string s) { int xnor = 0; for(auto i:s) { xnor^=i; } if(xnor==0) return true; int count = 0; // the times s occurs for(auto i:s) count+=(i==xnor); return count!=0; } */ bool canPermutePalindrome(string s) { vector<int> dict(256, 0); for(auto i:s) dict[i]++; int odd = 0; // the count of odd letter for(auto i:dict) { if(i%2) odd++; } return odd<=1; // 出现奇数次的字符不存在或者仅有一个 } };
27.395833
133
0.626616
qiaotian
81b6588b2b602e7ee29cd4b5ae59e945f4cf7586
9,991
cc
C++
chrome/browser/sync/test/integration/passwords_helper.cc
metux/chromium-deb
3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
chrome/browser/sync/test/integration/passwords_helper.cc
metux/chromium-deb
3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
chrome/browser/sync/test/integration/passwords_helper.cc
metux/chromium-deb
3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/sync/test/integration/passwords_helper.h" #include <sstream> #include <utility> #include "base/compiler_specific.h" #include "base/macros.h" #include "base/message_loop/message_loop.h" #include "base/strings/stringprintf.h" #include "base/strings/utf_string_conversions.h" #include "base/synchronization/waitable_event.h" #include "base/time/time.h" #include "chrome/browser/password_manager/password_store_factory.h" #include "chrome/browser/sync/profile_sync_service_factory.h" #include "chrome/browser/sync/test/integration/profile_sync_service_harness.h" #include "chrome/browser/sync/test/integration/sync_datatype_helper.h" #include "components/password_manager/core/browser/password_manager_test_utils.h" #include "components/password_manager/core/browser/password_store.h" #include "components/password_manager/core/browser/password_store_consumer.h" #include "content/public/test/test_utils.h" using autofill::PasswordForm; using password_manager::PasswordStore; using sync_datatype_helper::test; namespace { const char kFakeSignonRealm[] = "http://fake-signon-realm.google.com/"; const char kIndexedFakeOrigin[] = "http://fake-signon-realm.google.com/%d"; // We use a WaitableEvent to wait when logins are added, removed, or updated // instead of running the UI message loop because of a restriction that // prevents a DB thread from initiating a quit of the UI message loop. void PasswordStoreCallback(base::WaitableEvent* wait_event) { // Wake up passwords_helper::AddLogin. wait_event->Signal(); } class PasswordStoreConsumerHelper : public password_manager::PasswordStoreConsumer { public: PasswordStoreConsumerHelper() {} void OnGetPasswordStoreResults( std::vector<std::unique_ptr<PasswordForm>> results) override { result_.swap(results); // Quit the message loop to wake up passwords_helper::GetLogins. base::MessageLoopForUI::current()->QuitWhenIdle(); } std::vector<std::unique_ptr<PasswordForm>> result() { return std::move(result_); } private: std::vector<std::unique_ptr<PasswordForm>> result_; DISALLOW_COPY_AND_ASSIGN(PasswordStoreConsumerHelper); }; // PasswordForm::date_synced is a local field. Therefore it may be different // across clients. void ClearSyncDateField(std::vector<std::unique_ptr<PasswordForm>>* forms) { for (auto& form : *forms) { form->date_synced = base::Time(); } } } // namespace namespace passwords_helper { void AddLogin(PasswordStore* store, const PasswordForm& form) { ASSERT_TRUE(store); base::WaitableEvent wait_event( base::WaitableEvent::ResetPolicy::MANUAL, base::WaitableEvent::InitialState::NOT_SIGNALED); store->AddLogin(form); store->ScheduleTask(base::Bind(&PasswordStoreCallback, &wait_event)); wait_event.Wait(); } void UpdateLogin(PasswordStore* store, const PasswordForm& form) { ASSERT_TRUE(store); base::WaitableEvent wait_event( base::WaitableEvent::ResetPolicy::MANUAL, base::WaitableEvent::InitialState::NOT_SIGNALED); store->UpdateLogin(form); store->ScheduleTask(base::Bind(&PasswordStoreCallback, &wait_event)); wait_event.Wait(); } std::vector<std::unique_ptr<PasswordForm>> GetLogins(PasswordStore* store) { EXPECT_TRUE(store); password_manager::PasswordStore::FormDigest matcher_form = { PasswordForm::SCHEME_HTML, kFakeSignonRealm, GURL()}; PasswordStoreConsumerHelper consumer; store->GetLogins(matcher_form, &consumer); content::RunMessageLoop(); return consumer.result(); } void RemoveLogin(PasswordStore* store, const PasswordForm& form) { ASSERT_TRUE(store); base::WaitableEvent wait_event( base::WaitableEvent::ResetPolicy::MANUAL, base::WaitableEvent::InitialState::NOT_SIGNALED); store->RemoveLogin(form); store->ScheduleTask(base::Bind(&PasswordStoreCallback, &wait_event)); wait_event.Wait(); } void RemoveLogins(PasswordStore* store) { std::vector<std::unique_ptr<PasswordForm>> forms = GetLogins(store); for (const auto& form : forms) { RemoveLogin(store, *form); } } PasswordStore* GetPasswordStore(int index) { return PasswordStoreFactory::GetForProfile(test()->GetProfile(index), ServiceAccessType::IMPLICIT_ACCESS) .get(); } PasswordStore* GetVerifierPasswordStore() { return PasswordStoreFactory::GetForProfile( test()->verifier(), ServiceAccessType::IMPLICIT_ACCESS).get(); } bool ProfileContainsSamePasswordFormsAsVerifier(int index) { std::vector<std::unique_ptr<PasswordForm>> verifier_forms = GetLogins(GetVerifierPasswordStore()); std::vector<std::unique_ptr<PasswordForm>> forms = GetLogins(GetPasswordStore(index)); ClearSyncDateField(&forms); std::ostringstream mismatch_details_stream; bool is_matching = password_manager::ContainsEqualPasswordFormsUnordered( verifier_forms, forms, &mismatch_details_stream); if (!is_matching) { VLOG(1) << "Profile " << index << " does not contain the same Password forms as Verifier Profile."; VLOG(1) << mismatch_details_stream.str(); } return is_matching; } bool ProfilesContainSamePasswordForms(int index_a, int index_b) { std::vector<std::unique_ptr<PasswordForm>> forms_a = GetLogins(GetPasswordStore(index_a)); std::vector<std::unique_ptr<PasswordForm>> forms_b = GetLogins(GetPasswordStore(index_b)); ClearSyncDateField(&forms_a); ClearSyncDateField(&forms_b); std::ostringstream mismatch_details_stream; bool is_matching = password_manager::ContainsEqualPasswordFormsUnordered( forms_a, forms_b, &mismatch_details_stream); if (!is_matching) { VLOG(1) << "Password forms in Profile " << index_a << " (listed as 'expected forms' below)" << " do not match those in Profile " << index_b << " (listed as 'actual forms' below)"; VLOG(1) << mismatch_details_stream.str(); } return is_matching; } bool AllProfilesContainSamePasswordFormsAsVerifier() { for (int i = 0; i < test()->num_clients(); ++i) { if (!ProfileContainsSamePasswordFormsAsVerifier(i)) { DVLOG(1) << "Profile " << i << " does not contain the same password" " forms as the verifier."; return false; } } return true; } bool AllProfilesContainSamePasswordForms() { for (int i = 1; i < test()->num_clients(); ++i) { if (!ProfilesContainSamePasswordForms(0, i)) { DVLOG(1) << "Profile " << i << " does not contain the same password" " forms as Profile 0."; return false; } } return true; } int GetPasswordCount(int index) { return GetLogins(GetPasswordStore(index)).size(); } int GetVerifierPasswordCount() { return GetLogins(GetVerifierPasswordStore()).size(); } PasswordForm CreateTestPasswordForm(int index) { PasswordForm form; form.signon_realm = kFakeSignonRealm; form.origin = GURL(base::StringPrintf(kIndexedFakeOrigin, index)); form.username_value = base::ASCIIToUTF16(base::StringPrintf("username%d", index)); form.password_value = base::ASCIIToUTF16(base::StringPrintf("password%d", index)); form.date_created = base::Time::Now(); return form; } } // namespace passwords_helper SamePasswordFormsChecker::SamePasswordFormsChecker() : MultiClientStatusChangeChecker( sync_datatype_helper::test()->GetSyncServices()), in_progress_(false), needs_recheck_(false) {} // This method needs protection against re-entrancy. // // This function indirectly calls GetLogins(), which starts a RunLoop on the UI // thread. This can be a problem, since the next task to execute could very // well contain a ProfileSyncService::OnStateChanged() event, which would // trigger another call to this here function, and start another layer of // nested RunLoops. That makes the StatusChangeChecker's Quit() method // ineffective. // // The work-around is to not allow re-entrancy. But we can't just drop // IsExitConditionSatisifed() calls if one is already in progress. Instead, we // set a flag to ask the current execution of IsExitConditionSatisfied() to be // re-run. This ensures that the return value is always based on the most // up-to-date state. bool SamePasswordFormsChecker::IsExitConditionSatisfied() { if (in_progress_) { LOG(WARNING) << "Setting flag and returning early to prevent nesting."; needs_recheck_ = true; return false; } // Keep retrying until we get a good reading. bool result = false; in_progress_ = true; do { needs_recheck_ = false; result = passwords_helper::AllProfilesContainSamePasswordForms(); } while (needs_recheck_); in_progress_ = false; return result; } std::string SamePasswordFormsChecker::GetDebugMessage() const { return "Waiting for matching passwords"; } SamePasswordFormsAsVerifierChecker::SamePasswordFormsAsVerifierChecker(int i) : SingleClientStatusChangeChecker( sync_datatype_helper::test()->GetSyncService(i)), index_(i), in_progress_(false), needs_recheck_(false) { } // This method uses the same re-entrancy prevention trick as // the SamePasswordFormsChecker. bool SamePasswordFormsAsVerifierChecker::IsExitConditionSatisfied() { if (in_progress_) { LOG(WARNING) << "Setting flag and returning early to prevent nesting."; needs_recheck_ = true; return false; } // Keep retrying until we get a good reading. bool result = false; in_progress_ = true; do { needs_recheck_ = false; result = passwords_helper::ProfileContainsSamePasswordFormsAsVerifier(index_); } while (needs_recheck_); in_progress_ = false; return result; } std::string SamePasswordFormsAsVerifierChecker::GetDebugMessage() const { return "Waiting for passwords to match verifier"; }
34.215753
81
0.730157
metux
81ba9781070eba3e35c32695ddcc6d305e99e3a4
2,402
hpp
C++
include/UnityEngine/Animations/AnimationHumanStream.hpp
RedBrumbler/virtuoso-codegen
e83f6f0f9b47bec4b6dd976b21edc1d46bf3cfe3
[ "Unlicense" ]
null
null
null
include/UnityEngine/Animations/AnimationHumanStream.hpp
RedBrumbler/virtuoso-codegen
e83f6f0f9b47bec4b6dd976b21edc1d46bf3cfe3
[ "Unlicense" ]
null
null
null
include/UnityEngine/Animations/AnimationHumanStream.hpp
RedBrumbler/virtuoso-codegen
e83f6f0f9b47bec4b6dd976b21edc1d46bf3cfe3
[ "Unlicense" ]
null
null
null
// Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once // Begin includes #include "beatsaber-hook/shared/utils/byref.hpp" // Including type: System.ValueType #include "System/ValueType.hpp" // Including type: System.IntPtr #include "System/IntPtr.hpp" // Completed includes // Type namespace: UnityEngine.Animations namespace UnityEngine::Animations { // Forward declaring type: AnimationHumanStream struct AnimationHumanStream; } #include "beatsaber-hook/shared/utils/il2cpp-type-check.hpp" DEFINE_IL2CPP_ARG_TYPE(::UnityEngine::Animations::AnimationHumanStream, "UnityEngine.Animations", "AnimationHumanStream"); // Type namespace: UnityEngine.Animations namespace UnityEngine::Animations { // Size: 0x8 #pragma pack(push, 1) // WARNING Layout: Sequential may not be correctly taken into account! // Autogenerated type: UnityEngine.Animations.AnimationHumanStream // [TokenAttribute] Offset: FFFFFFFF // [MovedFromAttribute] Offset: 5A6440 // [NativeHeaderAttribute] Offset: 5A6440 // [NativeHeaderAttribute] Offset: 5A6440 // [RequiredByNativeCodeAttribute] Offset: 5A6440 struct AnimationHumanStream/*, public ::System::ValueType*/ { public: public: // private System.IntPtr stream // Size: 0x8 // Offset: 0x0 ::System::IntPtr stream; // Field size check static_assert(sizeof(::System::IntPtr) == 0x8); public: // Creating value type constructor for type: AnimationHumanStream constexpr AnimationHumanStream(::System::IntPtr stream_ = {}) noexcept : stream{stream_} {} // Creating interface conversion operator: operator ::System::ValueType operator ::System::ValueType() noexcept { return *reinterpret_cast<::System::ValueType*>(this); } // Creating conversion operator: operator ::System::IntPtr constexpr operator ::System::IntPtr() const noexcept { return stream; } // Get instance field reference: private System.IntPtr stream ::System::IntPtr& dyn_stream(); }; // UnityEngine.Animations.AnimationHumanStream #pragma pack(pop) static check_size<sizeof(AnimationHumanStream), 0 + sizeof(::System::IntPtr)> __UnityEngine_Animations_AnimationHumanStreamSizeCheck; static_assert(sizeof(AnimationHumanStream) == 0x8); } #include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
41.413793
135
0.722315
RedBrumbler
81bad7f3ace1ba946ccf02caa28e9a3f7265a159
4,709
cpp
C++
inference_backend/image_inference/async_with_va_api/va_api_wrapper/vaapi_context.cpp
MisterArslan/dlstreamer_gst
ff6d0bc138f372bb988baf368af4a3693b808e16
[ "MIT" ]
125
2020-09-18T10:50:27.000Z
2022-02-10T06:20:59.000Z
inference_backend/image_inference/async_with_va_api/va_api_wrapper/vaapi_context.cpp
MisterArslan/dlstreamer_gst
ff6d0bc138f372bb988baf368af4a3693b808e16
[ "MIT" ]
155
2020-09-10T23:32:29.000Z
2022-02-05T07:10:26.000Z
inference_backend/image_inference/async_with_va_api/va_api_wrapper/vaapi_context.cpp
MisterArslan/dlstreamer_gst
ff6d0bc138f372bb988baf368af4a3693b808e16
[ "MIT" ]
41
2020-09-15T08:49:17.000Z
2022-01-24T10:39:36.000Z
/******************************************************************************* * Copyright (C) 2019-2021 Intel Corporation * * SPDX-License-Identifier: MIT ******************************************************************************/ #include "vaapi_context.h" #include "inference_backend/logger.h" #include "utils.h" #include <cassert> #include <vector> #include <fcntl.h> #include <unistd.h> using namespace InferenceBackend; VaApiContext::VaApiContext(VADisplay va_display) : _display(va_display) { create_config_and_contexts(); create_supported_pixel_formats(); assert(_va_config_id != VA_INVALID_ID && "Failed to initalize VaApiContext. Expected valid VAConfigID."); assert(_va_context_id != VA_INVALID_ID && "Failed to initalize VaApiContext. Expected valid VAContextID."); } VaApiContext::VaApiContext(VaApiDisplayPtr va_display_ptr) : _display_storage(va_display_ptr), _display(va_display_ptr.get()) { create_config_and_contexts(); create_supported_pixel_formats(); assert(_va_config_id != VA_INVALID_ID && "Failed to initalize VaApiContext. Expected valid VAConfigID."); assert(_va_context_id != VA_INVALID_ID && "Failed to initalize VaApiContext. Expected valid VAContextID."); } VaApiContext::VaApiContext(const std::string &device) { _display_storage = vaApiCreateVaDisplay(Utils::getRelativeGpuDeviceIndex(device)); _display = VaDpyWrapper::fromHandle(_display_storage.get()); create_config_and_contexts(); create_supported_pixel_formats(); assert(_va_config_id != VA_INVALID_ID && "Failed to initalize VaApiContext. Expected valid VAConfigID."); assert(_va_context_id != VA_INVALID_ID && "Failed to initalize VaApiContext. Expected valid VAContextID."); } VaApiContext::~VaApiContext() { auto vtable = _display.drvVtable(); auto ctx = _display.drvCtx(); if (_va_context_id != VA_INVALID_ID) { vtable.vaDestroyContext(ctx, _va_context_id); } if (_va_config_id != VA_INVALID_ID) { vtable.vaDestroyConfig(ctx, _va_config_id); } } VAContextID VaApiContext::Id() const { return _va_context_id; } VaDpyWrapper VaApiContext::Display() const { return _display; } VADisplay VaApiContext::DisplayRaw() const { return _display.raw(); } int VaApiContext::RTFormat() const { return _rt_format; } bool VaApiContext::IsPixelFormatSupported(int format) const { return _supported_pixel_formats.count(format); } /** * Creates config, va context, and sets the driver context using the internal VADisplay. * Setting the VADriverContextP, VAConfigID, and VAContextID to the corresponding variables. * * @pre _display must be set and initialized. * @post _va_config_id is set. * @post _va_context_id is set. * * @throw std::invalid_argument if the VaDpyWrapper is not created, runtime format not supported, unable to get config * attributes, unable to create config, or unable to create context. */ void VaApiContext::create_config_and_contexts() { assert(_display); auto ctx = _display.drvCtx(); auto vtable = _display.drvVtable(); VAConfigAttrib format_attrib; format_attrib.type = VAConfigAttribRTFormat; VA_CALL(vtable.vaGetConfigAttributes(ctx, VAProfileNone, VAEntrypointVideoProc, &format_attrib, 1)); if (not(format_attrib.value & _rt_format)) throw std::invalid_argument("Could not create context. Runtime format is not supported."); VAConfigAttrib attrib; attrib.type = VAConfigAttribRTFormat; attrib.value = _rt_format; VA_CALL(vtable.vaCreateConfig(ctx, VAProfileNone, VAEntrypointVideoProc, &attrib, 1, &_va_config_id)); if (_va_config_id == 0) { throw std::invalid_argument("Could not create VA config. Cannot initialize VaApiContext without VA config."); } VA_CALL(vtable.vaCreateContext(ctx, _va_config_id, 0, 0, VA_PROGRESSIVE, nullptr, 0, &_va_context_id)); if (_va_context_id == 0) { throw std::invalid_argument("Could not create VA context. Cannot initialize VaApiContext without VA context."); } } /** * Creates a set of formats supported by image. * * @pre _display must be set and initialized. * @post _supported_pixel_formats is set. * * @throw std::runtime_error if vaQueryImageFormats return non success code */ void VaApiContext::create_supported_pixel_formats() { assert(_display); auto ctx = _display.drvCtx(); auto vtable = _display.drvVtable(); std::vector<VAImageFormat> image_formats(ctx->max_image_formats); int size = 0; VA_CALL(vtable.vaQueryImageFormats(ctx, image_formats.data(), &size)); for (int i = 0; i < size; i++) _supported_pixel_formats.insert(image_formats[i].fourcc); }
33.635714
119
0.712678
MisterArslan
81baf3ae028b0ebf7d0bc882ffb7ba903141ed6e
2,594
cpp
C++
src/lib/tide/api/environment_binding.cpp
dubcanada/TideSDKLite
f2f3959e8d464c1096bd5e0963149a3589d54a25
[ "Apache-2.0" ]
2
2015-11-05T01:53:44.000Z
2015-12-17T06:52:12.000Z
src/lib/tide/api/environment_binding.cpp
aykutb/TideSDK
267e1cb86dc2dc7bef136a78a6f2177233bad233
[ "Apache-2.0" ]
null
null
null
src/lib/tide/api/environment_binding.cpp
aykutb/TideSDK
267e1cb86dc2dc7bef136a78a6f2177233bad233
[ "Apache-2.0" ]
1
2015-07-12T19:35:36.000Z
2015-07-12T19:35:36.000Z
/** * This file has been modified from its orginal sources. * * Copyright (c) 2012 Software in the Public Interest Inc (SPI) * Copyright (c) 2012 David Pratt * * 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. * *** * Copyright (c) 2008-2012 Appcelerator Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. **/ #include "environment_binding.h" #include <tideutils/environment_utils.h> namespace tide { ValueRef EnvironmentBinding::Get(const char *name) { return Value::NewString(EnvironmentUtils::Get(name)); } SharedStringList EnvironmentBinding::GetPropertyNames() { std::map<std::string, std::string> env = EnvironmentUtils::GetEnvironment(); SharedStringList keys = new StringList(); std::map<std::string, std::string>::iterator iter = env.begin(); for (; iter != env.end(); iter++) { keys->push_back(new std::string(iter->first)); } return keys; } void EnvironmentBinding::Set(const char *name, ValueRef value) { if (value->IsString()) { EnvironmentUtils::Set(name, value->ToString()); } } SharedString EnvironmentBinding::DisplayString(int levels) { std::map<std::string, std::string> env = EnvironmentUtils::GetEnvironment(); std::map<std::string, std::string>::iterator iter = env.begin(); SharedString str = new std::string(); for (; iter != env.end(); iter++) { (*str) += iter->first + "=" + iter->second + ","; } return str; } }
32.835443
84
0.660756
dubcanada
81bb477134247026f24cc1f3ab678d0eeb1151f4
3,508
cpp
C++
o3d/collada_edge/cross/collada_edge.cpp
rwatson/chromium-capsicum
b03da8e897f897c6ad2cda03ceda217b760fd528
[ "BSD-3-Clause" ]
11
2015-03-20T04:08:08.000Z
2021-11-15T15:51:36.000Z
o3d/collada_edge/cross/collada_edge.cpp
rwatson/chromium-capsicum
b03da8e897f897c6ad2cda03ceda217b760fd528
[ "BSD-3-Clause" ]
null
null
null
o3d/collada_edge/cross/collada_edge.cpp
rwatson/chromium-capsicum
b03da8e897f897c6ad2cda03ceda217b760fd528
[ "BSD-3-Clause" ]
null
null
null
/* * Copyright 2009, Google Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ // collada_edge.cpp : Defines the entry point for the console application. #include "precompile.h" #include "conditioner.h" #include <cstdio> static const char *usage = "\nUsage: ColladaEdgeConditioner <infile.dae> <outifle.dae> [ options ]\n\n\ Options:\n\ -sharpEdgeThreshold t : sharp edge threshold defined by dihedral \n\ angle. Edges with a angle smaller than t\n\ will be defined as a sharp edge.\n\ -sharpEdgeColor r,g,b : color of addtional edges.\n\ default value is 1,0,0 .(no space)\n\n\ ColladaEdgeConditioner checks all polygon edges in <infile.dae> and add\n\ addtional edges to the model if normal angle of certain edge is larger\n\ than the pre-defined threshold.\n"; int wmain(int argc, wchar_t **argv) { wchar_t* input_file = NULL; wchar_t* output_file = NULL; Options options; if (argc < 3) { printf("%s", usage); return -1; } int file_count = 0; for (int i = 1; i < argc; i++) { if (wcscmp(argv[i], L"-sharpEdgeThreshold") == 0) { if (++i < argc) { options.enable_soften_edge = true; options.soften_edge_threshold = static_cast<float>(_wtof(argv[i])); } } else if (wcscmp(argv[i], L"-sharpEdgeColor") == 0) { if (++i < argc) { int r, g, b; if (swscanf_s(argv[i], L"%d,%d,%d", &r, &g, &b) != 3) { printf("Invalid -sharpEdgeColor. Should be -sharpEdgeColor=x,y,z\n"); return -1; } options.sharp_edge_color = Vector3(static_cast<float>(r), static_cast<float>(g), static_cast<float>(b)); } } else if (file_count < 2) { ++file_count; if (file_count == 1) input_file = argv[i]; else output_file = argv[i]; } } bool result = Condition(input_file, output_file, options); return 0; }
39.863636
79
0.65992
rwatson
81bc6385d9522fc960507eb8b4db75542d010bfd
3,361
cpp
C++
build/linux-build/Sources/src/kha/kore/graphics4/ConstantLocation.cpp
5Mixer/GGJ20
a12a14d596ab150e8d96dda5a21defcd176f251f
[ "MIT" ]
null
null
null
build/linux-build/Sources/src/kha/kore/graphics4/ConstantLocation.cpp
5Mixer/GGJ20
a12a14d596ab150e8d96dda5a21defcd176f251f
[ "MIT" ]
null
null
null
build/linux-build/Sources/src/kha/kore/graphics4/ConstantLocation.cpp
5Mixer/GGJ20
a12a14d596ab150e8d96dda5a21defcd176f251f
[ "MIT" ]
null
null
null
// Generated by Haxe 4.0.5 #include <hxcpp.h> #ifndef INCLUDED_kha_graphics4_ConstantLocation #include <hxinc/kha/graphics4/ConstantLocation.h> #endif #ifndef INCLUDED_kha_kore_graphics4_ConstantLocation #include <hxinc/kha/kore/graphics4/ConstantLocation.h> #endif HX_DEFINE_STACK_FRAME(_hx_pos_8a98049bf91d5975_10_new,"kha.kore.graphics4.ConstantLocation","new",0x99ddedbd,"kha.kore.graphics4.ConstantLocation.new","kha/kore/graphics4/ConstantLocation.hx",10,0x6d842492) namespace kha{ namespace kore{ namespace graphics4{ void ConstantLocation_obj::__construct(){ HX_STACKFRAME(&_hx_pos_8a98049bf91d5975_10_new) } Dynamic ConstantLocation_obj::__CreateEmpty() { return new ConstantLocation_obj; } void *ConstantLocation_obj::_hx_vtable = 0; Dynamic ConstantLocation_obj::__Create(hx::DynamicArray inArgs) { hx::ObjectPtr< ConstantLocation_obj > _hx_result = new ConstantLocation_obj(); _hx_result->__construct(); return _hx_result; } bool ConstantLocation_obj::_hx_isInstanceOf(int inClassId) { return inClassId==(int)0x00000001 || inClassId==(int)0x3f26b36b; } static ::kha::graphics4::ConstantLocation_obj _hx_kha_kore_graphics4_ConstantLocation__hx_kha_graphics4_ConstantLocation= { }; void *ConstantLocation_obj::_hx_getInterface(int inHash) { switch(inHash) { case (int)0x9aec187e: return &_hx_kha_kore_graphics4_ConstantLocation__hx_kha_graphics4_ConstantLocation; } #ifdef HXCPP_SCRIPTABLE return super::_hx_getInterface(inHash); #else return 0; #endif } hx::ObjectPtr< ConstantLocation_obj > ConstantLocation_obj::__new() { hx::ObjectPtr< ConstantLocation_obj > __this = new ConstantLocation_obj(); __this->__construct(); return __this; } hx::ObjectPtr< ConstantLocation_obj > ConstantLocation_obj::__alloc(hx::Ctx *_hx_ctx) { ConstantLocation_obj *__this = (ConstantLocation_obj*)(hx::Ctx::alloc(_hx_ctx, sizeof(ConstantLocation_obj), false, "kha.kore.graphics4.ConstantLocation")); *(void **)__this = ConstantLocation_obj::_hx_vtable; __this->__construct(); return __this; } ConstantLocation_obj::ConstantLocation_obj() { } #ifdef HXCPP_SCRIPTABLE static hx::StorageInfo *ConstantLocation_obj_sMemberStorageInfo = 0; static hx::StaticInfo *ConstantLocation_obj_sStaticStorageInfo = 0; #endif hx::Class ConstantLocation_obj::__mClass; void ConstantLocation_obj::__register() { ConstantLocation_obj _hx_dummy; ConstantLocation_obj::_hx_vtable = *(void **)&_hx_dummy; hx::Static(__mClass) = new hx::Class_obj(); __mClass->mName = HX_("kha.kore.graphics4.ConstantLocation",4b,4b,13,b9); __mClass->mSuper = &super::__SGetClass(); __mClass->mConstructEmpty = &__CreateEmpty; __mClass->mConstructArgs = &__Create; __mClass->mGetStaticField = &hx::Class_obj::GetNoStaticField; __mClass->mSetStaticField = &hx::Class_obj::SetNoStaticField; __mClass->mStatics = hx::Class_obj::dupFunctions(0 /* sStaticFields */); __mClass->mMembers = hx::Class_obj::dupFunctions(0 /* sMemberFields */); __mClass->mCanCast = hx::TCanCast< ConstantLocation_obj >; #ifdef HXCPP_SCRIPTABLE __mClass->mMemberStorageInfo = ConstantLocation_obj_sMemberStorageInfo; #endif #ifdef HXCPP_SCRIPTABLE __mClass->mStaticStorageInfo = ConstantLocation_obj_sStaticStorageInfo; #endif hx::_hx_RegisterClass(__mClass->mName, __mClass); } } // end namespace kha } // end namespace kore } // end namespace graphics4
33.61
206
0.793216
5Mixer
81bcd962a09c7acfef22ec2f48bc02b249a56c44
7,086
cpp
C++
Tools/WebKitTestRunner/InjectedBundle/gtk/ActivateFontsGtk.cpp
jacadcaps/webkitty
9aebd2081349f9a7b5d168673c6f676a1450a66d
[ "BSD-2-Clause" ]
6
2021-07-05T16:09:39.000Z
2022-03-06T22:44:42.000Z
Tools/WebKitTestRunner/InjectedBundle/gtk/ActivateFontsGtk.cpp
jacadcaps/webkitty
9aebd2081349f9a7b5d168673c6f676a1450a66d
[ "BSD-2-Clause" ]
7
2022-03-15T13:25:39.000Z
2022-03-15T13:25:44.000Z
Tools/WebKitTestRunner/InjectedBundle/gtk/ActivateFontsGtk.cpp
jacadcaps/webkitty
9aebd2081349f9a7b5d168673c6f676a1450a66d
[ "BSD-2-Clause" ]
null
null
null
/* * Copyright (C) 2005, 2006 Apple Inc. All rights reserved. * Copyright (C) 2008 Nokia Corporation and/or its subsidiary(-ies) * Copyright (C) 2010 Igalia S.L. * * 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 Apple Inc. ("Apple") 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 APPLE AND ITS 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 APPLE OR ITS 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. */ #include "config.h" #include "ActivateFonts.h" #include "InjectedBundleUtilities.h" #include <fontconfig/fontconfig.h> #include <gtk/gtk.h> #include <wtf/glib/GLibUtilities.h> #include <wtf/glib/GUniquePtr.h> namespace WTR { void initializeGtkSettings() { GtkSettings* settings = gtk_settings_get_default(); if (!settings) return; g_object_set(settings, "gtk-xft-dpi", 98304, "gtk-xft-antialias", 1, "gtk-xft-hinting", 0, "gtk-font-name", "Liberation Sans 12", "gtk-xft-rgba", "none", nullptr); } CString getOutputDir() { const char* webkitOutputDir = g_getenv("WEBKIT_OUTPUTDIR"); if (webkitOutputDir) return webkitOutputDir; CString topLevelPath = WTR::topLevelPath(); GUniquePtr<char> outputDir(g_build_filename(topLevelPath.data(), "WebKitBuild", nullptr)); return outputDir.get(); } static CString getFontsPath() { // Try flatpak sandbox path. GUniquePtr<char>fontsPath(g_build_filename("/usr", "share", "webkitgtk-test-fonts", NULL)); if (g_file_test(fontsPath.get(), static_cast<GFileTest>(G_FILE_TEST_EXISTS | G_FILE_TEST_IS_DIR))) return fontsPath.get(); CString webkitOutputDir = getOutputDir(); fontsPath.reset(g_build_filename(webkitOutputDir.data(), "DependenciesGTK", "Root", "webkitgtk-test-fonts", nullptr)); if (g_file_test(fontsPath.get(), static_cast<GFileTest>(G_FILE_TEST_EXISTS | G_FILE_TEST_IS_DIR))) return fontsPath.get(); // Try alternative fonts path. fontsPath.reset(g_build_filename(webkitOutputDir.data(), "webkitgtk-test-fonts", NULL)); if (g_file_test(fontsPath.get(), static_cast<GFileTest>(G_FILE_TEST_EXISTS | G_FILE_TEST_IS_DIR))) return fontsPath.get(); return CString(); } void initializeFontConfigSetting() { if (g_getenv("WEBKIT_SKIP_WEBKITTESTRUNNER_FONTCONFIG_INITIALIZATION")) return; FcInit(); // If a test resulted a font being added or removed via the @font-face rule, then // we want to reset the FontConfig configuration to prevent it from affecting other tests. static int numFonts = 0; FcFontSet* appFontSet = FcConfigGetFonts(0, FcSetApplication); if (appFontSet && numFonts && appFontSet->nfont == numFonts) return; // Load our configuration file, which sets up proper aliases for family // names like sans, serif and monospace. FcConfig* config = FcConfigCreate(); GUniquePtr<gchar> fontConfigFilename(g_build_filename(FONTS_CONF_DIR, "fonts.conf", nullptr)); if (!g_file_test(fontConfigFilename.get(), G_FILE_TEST_IS_REGULAR)) g_error("Cannot find fonts.conf at %s\n", fontConfigFilename.get()); if (!FcConfigParseAndLoad(config, reinterpret_cast<FcChar8*>(fontConfigFilename.get()), true)) g_error("Couldn't load font configuration file from: %s", fontConfigFilename.get()); CString fontsPath = getFontsPath(); if (fontsPath.isNull()) g_error("Could not locate test fonts at %s. Is WEBKIT_TOP_LEVEL set?", fontsPath.data()); GUniquePtr<GDir> fontsDirectory(g_dir_open(fontsPath.data(), 0, nullptr)); while (const char* directoryEntry = g_dir_read_name(fontsDirectory.get())) { if (!g_str_has_suffix(directoryEntry, ".ttf") && !g_str_has_suffix(directoryEntry, ".otf")) continue; GUniquePtr<gchar> fontPath(g_build_filename(fontsPath.data(), directoryEntry, nullptr)); if (!FcConfigAppFontAddFile(config, reinterpret_cast<const FcChar8*>(fontPath.get()))) g_error("Could not load font at %s!", fontPath.get()); } // Ahem is used by many layout tests. GUniquePtr<gchar> ahemFontFilename(g_build_filename(FONTS_CONF_DIR, "AHEM____.TTF", nullptr)); if (!FcConfigAppFontAddFile(config, reinterpret_cast<FcChar8*>(ahemFontFilename.get()))) g_error("Could not load font at %s!", ahemFontFilename.get()); static const char* fontFilenames[] = { "WebKitWeightWatcher100.ttf", "WebKitWeightWatcher200.ttf", "WebKitWeightWatcher300.ttf", "WebKitWeightWatcher400.ttf", "WebKitWeightWatcher500.ttf", "WebKitWeightWatcher600.ttf", "WebKitWeightWatcher700.ttf", "WebKitWeightWatcher800.ttf", "WebKitWeightWatcher900.ttf", 0 }; for (size_t i = 0; fontFilenames[i]; ++i) { GUniquePtr<gchar> fontFilename(g_build_filename(FONTS_CONF_DIR, "..", "..", "fonts", fontFilenames[i], nullptr)); if (!FcConfigAppFontAddFile(config, reinterpret_cast<FcChar8*>(fontFilename.get()))) g_error("Could not load font at %s!", fontFilename.get()); } // A font with no valid Fontconfig encoding to test https://bugs.webkit.org/show_bug.cgi?id=47452 GUniquePtr<gchar> fontWithNoValidEncodingFilename(g_build_filename(FONTS_CONF_DIR, "FontWithNoValidEncoding.fon", nullptr)); if (!FcConfigAppFontAddFile(config, reinterpret_cast<FcChar8*>(fontWithNoValidEncodingFilename.get()))) g_error("Could not load font at %s!", fontWithNoValidEncodingFilename.get()); if (!FcConfigSetCurrent(config)) g_error("Could not set the current font configuration!"); numFonts = FcConfigGetFonts(config, FcSetApplication)->nfont; } void activateFonts() { initializeGtkSettings(); initializeFontConfigSetting(); } void installFakeHelvetica(WKStringRef) { } void uninstallFakeHelvetica() { } }
41.197674
128
0.715213
jacadcaps
81bff200be727f64fe62189180933f80e4d7d903
369
cpp
C++
Codeforces/Solutions/1333A.cpp
Mohammed-Shoaib/HackerRank-Problems
ccfb9fc2f0d8dff454439d75ce519cf83bad7c3b
[ "MIT" ]
54
2019-05-13T12:13:09.000Z
2022-02-27T02:59:00.000Z
Codeforces/Solutions/1333A.cpp
Mohammed-Shoaib/HackerRank-Problems
ccfb9fc2f0d8dff454439d75ce519cf83bad7c3b
[ "MIT" ]
2
2020-10-02T07:16:43.000Z
2020-10-19T04:36:19.000Z
Codeforces/Solutions/1333A.cpp
Mohammed-Shoaib/HackerRank-Problems
ccfb9fc2f0d8dff454439d75ce519cf83bad7c3b
[ "MIT" ]
20
2020-05-26T09:48:13.000Z
2022-03-18T15:18:27.000Z
// Problem Code: 1333A #include <iostream> #include <string> #include <vector> using namespace std; void little_artem(int n, int m) { vector<string> grid(n, string(m, 'B')); grid[0][0] = 'W'; for (int i = 0; i < n; i++) cout << grid[i] << endl; } int main() { int t; cin >> t; while (t--) { int n, m; cin >> n >> m; little_artem(n, m); } return 0; }
14.76
40
0.558266
Mohammed-Shoaib
81c094b450ad01b902cec3b24adeddf2af841f88
6,046
cpp
C++
VC2012Samples/Windows 8 samples/C++/Windows 8 app samples/Hilo C++ sample (Windows 8)/C++/Hilo/ThumbnailGenerator.cpp
alonmm/VCSamples
6aff0b4902f5027164d593540fcaa6601a0407c3
[ "MIT" ]
300
2019-05-09T05:32:33.000Z
2022-03-31T20:23:24.000Z
VC2012Samples/Windows 8 samples/C++/Windows 8 app samples/Hilo C++ sample (Windows 8)/C++/Hilo/ThumbnailGenerator.cpp
JaydenChou/VCSamples
9e1d4475555b76a17a3568369867f1d7b6cc6126
[ "MIT" ]
9
2016-09-19T18:44:26.000Z
2018-10-26T10:20:05.000Z
VC2012Samples/Windows 8 samples/C++/Windows 8 app samples/Hilo C++ sample (Windows 8)/C++/Hilo/ThumbnailGenerator.cpp
JaydenChou/VCSamples
9e1d4475555b76a17a3568369867f1d7b6cc6126
[ "MIT" ]
633
2019-05-08T07:34:12.000Z
2022-03-30T04:38:28.000Z
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF // ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A // PARTICULAR PURPOSE. // // Copyright (c) Microsoft Corporation. All rights reserved #include "pch.h" #include "ThumbnailGenerator.h" #include "ExceptionPolicy.h" using namespace concurrency; using namespace std; using namespace Platform; using namespace Platform::Collections; using namespace Windows::Foundation::Collections; using namespace Windows::Graphics::Imaging; using namespace Windows::Storage; using namespace Windows::Storage::Streams; using namespace Windows::Storage::FileProperties; using namespace Hilo; // See http://go.microsoft.com/fwlink/?LinkId=267275 for info about Hilo's implementation of tiles. const unsigned int ThumbnailSize = 270; const wstring ThumbnailImagePrefix = L"thumbImage_"; ThumbnailGenerator::ThumbnailGenerator(std::shared_ptr<ExceptionPolicy> policy) : m_exceptionPolicy(policy) { } task<Vector<StorageFile^>^> ThumbnailGenerator::Generate( IVector<StorageFile^>^ files, StorageFolder^ thumbnailsFolder) { vector<task<StorageFile^>> thumbnailTasks; unsigned int imageCounter = 0; for (auto imageFile : files) { wstringstream localFileName; localFileName << ThumbnailImagePrefix << imageCounter++ << ".jpg"; thumbnailTasks.push_back( CreateLocalThumbnailAsync( thumbnailsFolder, imageFile, ref new String(localFileName.str().c_str()), ThumbnailSize, m_exceptionPolicy)); } return when_all(begin(thumbnailTasks), end(thumbnailTasks)).then( [](vector<StorageFile^> files) { auto result = ref new Vector<StorageFile^>(); for (auto file : files) { if (file != nullptr) { result->Append(file); } } return result; }); } task<StorageFile^> ThumbnailGenerator::CreateLocalThumbnailAsync( StorageFolder^ folder, StorageFile^ imageFile, String^ localFileName, unsigned int thumbSize, std::shared_ptr<ExceptionPolicy> exceptionPolicy) { auto createThumbnail = create_task( CreateThumbnailFromPictureFileAsync(imageFile, thumbSize)); return createThumbnail.then([exceptionPolicy, folder, localFileName]( task<InMemoryRandomAccessStream^> createdThumbnailTask) { InMemoryRandomAccessStream^ createdThumbnail; try { createdThumbnail = createdThumbnailTask.get(); } catch(Exception^ ex) { exceptionPolicy->HandleException(ex); // If we have any exceptions we won't return the results // of this task, but instead nullptr. Downstream // tasks will need to account for this. return create_task_from_result<StorageFile^>(nullptr); } return InternalSaveToFile(folder, createdThumbnail, localFileName); }); } task<StorageFile^> ThumbnailGenerator::InternalSaveToFile( StorageFolder^ thumbnailsFolder, InMemoryRandomAccessStream^ stream, Platform::String^ filename) { auto imageFile = make_shared<StorageFile^>(nullptr); auto streamReader = ref new DataReader(stream); auto loadStreamTask = create_task( streamReader->LoadAsync(static_cast<unsigned int>(stream->Size))); return loadStreamTask.then( [thumbnailsFolder, filename](unsigned int loadedBytes) { (void)loadedBytes; // Unused parameter return thumbnailsFolder->CreateFileAsync( filename, CreationCollisionOption::ReplaceExisting); }).then([streamReader, imageFile](StorageFile^ thumbnailDestinationFile) { (*imageFile) = thumbnailDestinationFile; auto buffer = streamReader->ReadBuffer( streamReader->UnconsumedBufferLength); return FileIO::WriteBufferAsync(thumbnailDestinationFile, buffer); }).then([imageFile]() { return (*imageFile); }); } task<InMemoryRandomAccessStream^> ThumbnailGenerator::CreateThumbnailFromPictureFileAsync( StorageFile^ sourceFile, unsigned int thumbSize) { (void)thumbSize; // Unused parameter auto decoder = make_shared<BitmapDecoder^>(nullptr); auto pixelProvider = make_shared<PixelDataProvider^>(nullptr); auto resizedImageStream = ref new InMemoryRandomAccessStream(); auto createThumbnail = create_task( sourceFile->GetThumbnailAsync( ThumbnailMode::PicturesView, ThumbnailSize)); return createThumbnail.then([](StorageItemThumbnail^ thumbnail) { IRandomAccessStream^ imageFileStream = static_cast<IRandomAccessStream^>(thumbnail); return BitmapDecoder::CreateAsync(imageFileStream); }).then([decoder](BitmapDecoder^ createdDecoder) { (*decoder) = createdDecoder; return createdDecoder->GetPixelDataAsync( BitmapPixelFormat::Rgba8, BitmapAlphaMode::Straight, ref new BitmapTransform(), ExifOrientationMode::IgnoreExifOrientation, ColorManagementMode::ColorManageToSRgb); }).then([pixelProvider, resizedImageStream](PixelDataProvider^ provider) { (*pixelProvider) = provider; return BitmapEncoder::CreateAsync( BitmapEncoder::JpegEncoderId, resizedImageStream); }).then([pixelProvider, decoder](BitmapEncoder^ createdEncoder) { createdEncoder->SetPixelData(BitmapPixelFormat::Rgba8, BitmapAlphaMode::Straight, (*decoder)->PixelWidth, (*decoder)->PixelHeight, (*decoder)->DpiX, (*decoder)->DpiY, (*pixelProvider)->DetachPixelData()); return createdEncoder->FlushAsync(); }).then([resizedImageStream] { resizedImageStream->Seek(0); return resizedImageStream; }); }
32.331551
107
0.676811
alonmm
81c1c41f2a88147dab9a2a82d236621e7cddeb25
817
cpp
C++
src/Stopwatch.cpp
matheuscscp/metallicar
6508735a7f3ce526637622834fdb95f6d6297687
[ "MIT" ]
null
null
null
src/Stopwatch.cpp
matheuscscp/metallicar
6508735a7f3ce526637622834fdb95f6d6297687
[ "MIT" ]
null
null
null
src/Stopwatch.cpp
matheuscscp/metallicar
6508735a7f3ce526637622834fdb95f6d6297687
[ "MIT" ]
null
null
null
/* * Stopwatch.cpp * * Created on: Jul 14, 2014 * Author: Pimenta */ // this #include "metallicar_time.hpp" namespace metallicar { Stopwatch::Stopwatch() : started(false), paused(false), initialTime(0), pauseTime(0) { } void Stopwatch::start() { started = true; paused = false; initialTime = Time::get(); } void Stopwatch::pause() { if (!paused) { paused = true; pauseTime = Time::get(); } } void Stopwatch::resume() { if (paused) { paused = false; initialTime += Time::get() - pauseTime; } } void Stopwatch::reset() { started = false; } uint32_t Stopwatch::time() { if (!started) return 0; if (paused) return pauseTime - initialTime; return Time::get() - initialTime; } } // namespace metallicar
15.711538
60
0.578947
matheuscscp
81c2485a415b77dc4cc7cbaf97f96adba66a3f36
330
cpp
C++
src/ResourceFormatter/ResourceFormatterText.cpp
farlepet/coapserver
5709add6cc4c1d61db1b719196d6941bdde96878
[ "MIT" ]
1
2021-07-04T21:52:23.000Z
2021-07-04T21:52:23.000Z
src/ResourceFormatter/ResourceFormatterText.cpp
farlepet/coapserver
5709add6cc4c1d61db1b719196d6941bdde96878
[ "MIT" ]
12
2022-02-26T16:27:58.000Z
2022-03-26T17:32:22.000Z
src/ResourceFormatter/ResourceFormatterText.cpp
farlepet/coapserver
5709add6cc4c1d61db1b719196d6941bdde96878
[ "MIT" ]
null
null
null
#include <stdio.h> #include "ResourceFormatter/ResourceFormatterText.hpp" ResourceFormatterText::ResourceFormatterText() { } int ResourceFormatterText::decode(const std::vector<uint8_t> &data, std::ostream &out) { for(size_t i = 0; i < data.size(); i++) { out << static_cast<char>(data[i]); } return 0; }
20.625
88
0.672727
farlepet
81c5225c29991d1c912b627488024fe772733b79
145,529
cpp
C++
src/crypto/digest.cpp
nextcashtech/nextcash
f16e9938d55dd42ce9a6d6fcfbf948d0ee6165e7
[ "MIT" ]
1
2017-11-23T03:00:39.000Z
2017-11-23T03:00:39.000Z
src/crypto/digest.cpp
arcmist/arcmist
f16e9938d55dd42ce9a6d6fcfbf948d0ee6165e7
[ "MIT" ]
null
null
null
src/crypto/digest.cpp
arcmist/arcmist
f16e9938d55dd42ce9a6d6fcfbf948d0ee6165e7
[ "MIT" ]
null
null
null
/************************************************************************** * Copyright 2017-2018 NextCash, LLC * * Contributors : * * Curtis Ellis <curtis@nextcash.tech> * * Distributed under the MIT software license, see the accompanying * * file license.txt or http://www.opensource.org/licenses/mit-license.php * **************************************************************************/ #include "digest.hpp" #include "endian.hpp" #include "math.hpp" #include "log.hpp" #include "stream.hpp" #include "buffer.hpp" #include <cstdint> #include <cstring> #include <vector> #define NEXTCASH_DIGEST_LOG_NAME "Digest" namespace NextCash { namespace CRC32 { static const uint32_t table[256] = { 0x00000000, 0x77073096, 0xee0e612c, 0x990951ba, 0x076dc419, 0x706af48f, 0xe963a535, 0x9e6495a3, 0x0edb8832, 0x79dcb8a4, 0xe0d5e91e, 0x97d2d988, 0x09b64c2b, 0x7eb17cbd, 0xe7b82d07, 0x90bf1d91, 0x1db71064, 0x6ab020f2, 0xf3b97148, 0x84be41de, 0x1adad47d, 0x6ddde4eb, 0xf4d4b551, 0x83d385c7, 0x136c9856, 0x646ba8c0, 0xfd62f97a, 0x8a65c9ec, 0x14015c4f, 0x63066cd9, 0xfa0f3d63, 0x8d080df5, 0x3b6e20c8, 0x4c69105e, 0xd56041e4, 0xa2677172, 0x3c03e4d1, 0x4b04d447, 0xd20d85fd, 0xa50ab56b, 0x35b5a8fa, 0x42b2986c, 0xdbbbc9d6, 0xacbcf940, 0x32d86ce3, 0x45df5c75, 0xdcd60dcf, 0xabd13d59, 0x26d930ac, 0x51de003a, 0xc8d75180, 0xbfd06116, 0x21b4f4b5, 0x56b3c423, 0xcfba9599, 0xb8bda50f, 0x2802b89e, 0x5f058808, 0xc60cd9b2, 0xb10be924, 0x2f6f7c87, 0x58684c11, 0xc1611dab, 0xb6662d3d, 0x76dc4190, 0x01db7106, 0x98d220bc, 0xefd5102a, 0x71b18589, 0x06b6b51f, 0x9fbfe4a5, 0xe8b8d433, 0x7807c9a2, 0x0f00f934, 0x9609a88e, 0xe10e9818, 0x7f6a0dbb, 0x086d3d2d, 0x91646c97, 0xe6635c01, 0x6b6b51f4, 0x1c6c6162, 0x856530d8, 0xf262004e, 0x6c0695ed, 0x1b01a57b, 0x8208f4c1, 0xf50fc457, 0x65b0d9c6, 0x12b7e950, 0x8bbeb8ea, 0xfcb9887c, 0x62dd1ddf, 0x15da2d49, 0x8cd37cf3, 0xfbd44c65, 0x4db26158, 0x3ab551ce, 0xa3bc0074, 0xd4bb30e2, 0x4adfa541, 0x3dd895d7, 0xa4d1c46d, 0xd3d6f4fb, 0x4369e96a, 0x346ed9fc, 0xad678846, 0xda60b8d0, 0x44042d73, 0x33031de5, 0xaa0a4c5f, 0xdd0d7cc9, 0x5005713c, 0x270241aa, 0xbe0b1010, 0xc90c2086, 0x5768b525, 0x206f85b3, 0xb966d409, 0xce61e49f, 0x5edef90e, 0x29d9c998, 0xb0d09822, 0xc7d7a8b4, 0x59b33d17, 0x2eb40d81, 0xb7bd5c3b, 0xc0ba6cad, 0xedb88320, 0x9abfb3b6, 0x03b6e20c, 0x74b1d29a, 0xead54739, 0x9dd277af, 0x04db2615, 0x73dc1683, 0xe3630b12, 0x94643b84, 0x0d6d6a3e, 0x7a6a5aa8, 0xe40ecf0b, 0x9309ff9d, 0x0a00ae27, 0x7d079eb1, 0xf00f9344, 0x8708a3d2, 0x1e01f268, 0x6906c2fe, 0xf762575d, 0x806567cb, 0x196c3671, 0x6e6b06e7, 0xfed41b76, 0x89d32be0, 0x10da7a5a, 0x67dd4acc, 0xf9b9df6f, 0x8ebeeff9, 0x17b7be43, 0x60b08ed5, 0xd6d6a3e8, 0xa1d1937e, 0x38d8c2c4, 0x4fdff252, 0xd1bb67f1, 0xa6bc5767, 0x3fb506dd, 0x48b2364b, 0xd80d2bda, 0xaf0a1b4c, 0x36034af6, 0x41047a60, 0xdf60efc3, 0xa867df55, 0x316e8eef, 0x4669be79, 0xcb61b38c, 0xbc66831a, 0x256fd2a0, 0x5268e236, 0xcc0c7795, 0xbb0b4703, 0x220216b9, 0x5505262f, 0xc5ba3bbe, 0xb2bd0b28, 0x2bb45a92, 0x5cb36a04, 0xc2d7ffa7, 0xb5d0cf31, 0x2cd99e8b, 0x5bdeae1d, 0x9b64c2b0, 0xec63f226, 0x756aa39c, 0x026d930a, 0x9c0906a9, 0xeb0e363f, 0x72076785, 0x05005713, 0x95bf4a82, 0xe2b87a14, 0x7bb12bae, 0x0cb61b38, 0x92d28e9b, 0xe5d5be0d, 0x7cdcefb7, 0x0bdbdf21, 0x86d3d2d4, 0xf1d4e242, 0x68ddb3f8, 0x1fda836e, 0x81be16cd, 0xf6b9265b, 0x6fb077e1, 0x18b74777, 0x88085ae6, 0xff0f6a70, 0x66063bca, 0x11010b5c, 0x8f659eff, 0xf862ae69, 0x616bffd3, 0x166ccf45, 0xa00ae278, 0xd70dd2ee, 0x4e048354, 0x3903b3c2, 0xa7672661, 0xd06016f7, 0x4969474d, 0x3e6e77db, 0xaed16a4a, 0xd9d65adc, 0x40df0b66, 0x37d83bf0, 0xa9bcae53, 0xdebb9ec5, 0x47b2cf7f, 0x30b5ffe9, 0xbdbdf21c, 0xcabac28a, 0x53b39330, 0x24b4a3a6, 0xbad03605, 0xcdd70693, 0x54de5729, 0x23d967bf, 0xb3667a2e, 0xc4614ab8, 0x5d681b02, 0x2a6f2b94, 0xb40bbe37, 0xc30c8ea1, 0x5a05df1b, 0x2d02ef8d }; } void Digest::crc32(InputStream *pInput, stream_size pInputLength, OutputStream *pOutput) { uint32_t result = 0xffffffff; stream_size remaining = pInputLength; while(remaining--) result = (result >> 8) ^ CRC32::table[(result & 0xFF) ^ pInput->readByte()]; result ^= 0xffffffff; pOutput->writeUnsignedInt(Endian::convert(result, Endian::BIG)); } uint32_t Digest::crc32(const char *pText) { uint32_t result = 0xffffffff; unsigned int offset = 0; while(pText[offset]) result = (result >> 8) ^ CRC32::table[(result & 0xFF) ^ pText[offset++]]; return result ^ 0xffffffff; } uint32_t Digest::crc32(const uint8_t *pData, stream_size pSize) { uint32_t result = 0xffffffff; stream_size offset = 0; while(offset < pSize) result = (result >> 8) ^ CRC32::table[(result & 0xFF) ^ pData[offset++]]; return result ^ 0xffffffff; } namespace MD5 { inline int f(int pX, int pY, int pZ) { // XY v not(X) Z return (pX & pY) | (~pX & pZ); } inline int g(int pX, int pY, int pZ) { // XZ v Y not(Z) return (pX & pZ) |(pY & ~pZ); } inline int h(int pX, int pY, int pZ) { // X xor Y xor Z return (pX ^ pY) ^ pZ; } inline int i(int pX, int pY, int pZ) { // Y xor(X v not(Z)) return pY ^ (pX | ~pZ); } inline void round1(int &pA, int pB, int pC, int pD, int pXK, int pS, int pTI) { int step1 = (pA + f(pB, pC, pD) + pXK + pTI); pA = pB + Math::rotateLeft(step1, pS); } inline void round2(int &pA, int pB, int pC, int pD, int pXK, int pS, int pTI) { int step1 = (pA + g(pB, pC, pD) + pXK + pTI); pA = pB + Math::rotateLeft(step1, pS); } inline void round3(int &pA, int pB, int pC, int pD, int pXK, int pS, int pTI) { int step1 = (pA + h(pB, pC, pD) + pXK + pTI); pA = pB + Math::rotateLeft(step1, pS); } inline void round4(int &pA, int pB, int pC, int pD, int pXK, int pS, int pTI) { int step1 = (pA + i(pB, pC, pD) + pXK + pTI); pA = pB + Math::rotateLeft(step1, pS); } // Encodes raw bytes into the 16 integer block inline void encode(uint8_t *pData, int *pBlock) { int i, j; for(i=0,j=0;j<64;i++,j+=4) pBlock[i] = ((int)pData[j]) | (((int)pData[j+1]) << 8) | (((int)pData[j+2]) << 16) | (((int)pData[j+3]) << 24); } // Decodes 16 integer block into raw bytes inline void decode(int *pBlock, uint8_t *pData) { int i, j; for(i=0,j=0;j<64;i++,j+=4) { pData[j] = (uint8_t)(pBlock[i] & 0xff); pData[j+1] = (uint8_t)((pBlock[i] >> 8) & 0xff); pData[j+2] = (uint8_t)((pBlock[i] >> 16) & 0xff); pData[j+3] = (uint8_t)((pBlock[i] >> 24) & 0xff); } } } void Digest::md5(InputStream *pInput, stream_size pInputLength, OutputStream *pOutput) // 128 bit(16 byte) result { uint8_t *data; stream_size dataSize = pInputLength + 9; // Make the data size is congruent to 448, modulo 512 bits(56, 64 modulo bytes) dataSize += (64 - (dataSize % 64)); data = new uint8_t[dataSize]; stream_size offset = pInputLength; pInput->read(data, pInputLength); data[offset++] = 128; // 10000000 - append a one bit and the rest zero bits // Append the rest zero bits if(offset <(dataSize - 1)) std::memset(data + offset, 0, dataSize - offset); // Append the data length as a 64 bit number low order word first int bitLength = pInputLength * 8; data[dataSize - 8] = (uint8_t)(bitLength & 0xff); data[dataSize - 7] = (uint8_t)((bitLength >> 8) & 0xff); data[dataSize - 6] = (uint8_t)((bitLength >> 16) & 0xff); data[dataSize - 5] = (uint8_t)((bitLength >> 24) & 0xff); std::memset((data + dataSize) - 4, 0, 4); // Setup buffers int state[4], a, b, c, d; state[0] = 0x67452301; // A state[1] = 0xEFCDAB89; // B state[2] = 0x98BADCFE; // C state[3] = 0x10325476; // D // Process 16 word(64 byte) blocks of data int blockIndex, blockCount = dataSize / 64; int blockX[16]; for(blockIndex=0;blockIndex<blockCount;blockIndex++) { // Copy current block into blockX MD5::encode(data + (blockIndex * 64), blockX); a = state[0]; b = state[1]; c = state[2]; d = state[3]; // Round 1 - a = b +((a + F(b,c,d) + X[k] + T[i]) <<< s) MD5::round1(a, b, c, d, blockX[ 0], 7, 0xD76AA478); MD5::round1(d, a, b, c, blockX[ 1], 12, 0xE8C7B756); MD5::round1(c, d, a, b, blockX[ 2], 17, 0x242070DB); MD5::round1(b, c, d, a, blockX[ 3], 22, 0xC1BDCEEE); MD5::round1(a, b, c, d, blockX[ 4], 7, 0xF57C0FAF); MD5::round1(d, a, b, c, blockX[ 5], 12, 0x4787C62A); MD5::round1(c, d, a, b, blockX[ 6], 17, 0xA8304613); MD5::round1(b, c, d, a, blockX[ 7], 22, 0xFD469501); MD5::round1(a, b, c, d, blockX[ 8], 7, 0x698098D8); MD5::round1(d, a, b, c, blockX[ 9], 12, 0x8B44F7AF); MD5::round1(c, d, a, b, blockX[10], 17, 0xFFFF5BB1); MD5::round1(b, c, d, a, blockX[11], 22, 0x895CD7BE); MD5::round1(a, b, c, d, blockX[12], 7, 0x6B901122); MD5::round1(d, a, b, c, blockX[13], 12, 0xFD987193); MD5::round1(c, d, a, b, blockX[14], 17, 0xA679438E); MD5::round1(b, c, d, a, blockX[15], 22, 0x49B40821); // Round 2 - a = b +((a + G(b,,d) + X[k] + T[i]) <<< s) MD5::round2(a, b, c, d, blockX[ 1], 5, 0xF61E2562); MD5::round2(d, a, b, c, blockX[ 6], 9, 0xC040B340); MD5::round2(c, d, a, b, blockX[11], 14, 0x265E5A51); MD5::round2(b, c, d, a, blockX[ 0], 20, 0xE9B6C7AA); MD5::round2(a, b, c, d, blockX[ 5], 5, 0xD62F105D); MD5::round2(d, a, b, c, blockX[10], 9, 0x02441453); MD5::round2(c, d, a, b, blockX[15], 14, 0xD8A1E681); MD5::round2(b, c, d, a, blockX[ 4], 20, 0xE7D3FBC8); MD5::round2(a, b, c, d, blockX[ 9], 5, 0x21E1CDE6); MD5::round2(d, a, b, c, blockX[14], 9, 0xC33707D6); MD5::round2(c, d, a, b, blockX[ 3], 14, 0xF4D50D87); MD5::round2(b, c, d, a, blockX[ 8], 20, 0x455A14ED); MD5::round2(a, b, c, d, blockX[13], 5, 0xA9E3E905); MD5::round2(d, a, b, c, blockX[ 2], 9, 0xFCEFA3F8); MD5::round2(c, d, a, b, blockX[ 7], 14, 0x676F02D9); MD5::round2(b, c, d, a, blockX[12], 20, 0x8D2A4C8A); // Round 3 - a = b +((a + H(b,,d) + X[k] + T[i]) <<< s) MD5::round3(a, b, c, d, blockX[ 5], 4, 0xFFFA3942); MD5::round3(d, a, b, c, blockX[ 8], 11, 0x8771F681); MD5::round3(c, d, a, b, blockX[11], 16, 0x6D9D6122); MD5::round3(b, c, d, a, blockX[14], 23, 0xFDE5380C); MD5::round3(a, b, c, d, blockX[ 1], 4, 0xA4BEEA44); MD5::round3(d, a, b, c, blockX[ 4], 11, 0x4BDECFA9); MD5::round3(c, d, a, b, blockX[ 7], 16, 0xF6BB4B60); MD5::round3(b, c, d, a, blockX[10], 23, 0xBEBFBC70); MD5::round3(a, b, c, d, blockX[13], 4, 0x289B7EC6); MD5::round3(d, a, b, c, blockX[ 0], 11, 0xEAA127FA); MD5::round3(c, d, a, b, blockX[ 3], 16, 0xD4EF3085); MD5::round3(b, c, d, a, blockX[ 6], 23, 0x04881D05); MD5::round3(a, b, c, d, blockX[ 9], 4, 0xD9D4D039); MD5::round3(d, a, b, c, blockX[12], 11, 0xE6DB99E5); MD5::round3(c, d, a, b, blockX[15], 16, 0x1FA27CF8); MD5::round3(b, c, d, a, blockX[ 2], 23, 0xC4AC5665); // Round 4 - a = b +((a + I(b,,d) + X[k] + T[i]) <<< s) MD5::round4(a, b, c, d, blockX[ 0], 6, 0xF4292244); MD5::round4(d, a, b, c, blockX[ 7], 10, 0x432AFF97); MD5::round4(c, d, a, b, blockX[14], 15, 0xAB9423A7); MD5::round4(b, c, d, a, blockX[ 5], 21, 0xFC93A039); MD5::round4(a, b, c, d, blockX[12], 6, 0x655B59C3); MD5::round4(d, a, b, c, blockX[ 3], 10, 0x8F0CCC92); MD5::round4(c, d, a, b, blockX[10], 15, 0xFFEFF47D); MD5::round4(b, c, d, a, blockX[ 1], 21, 0x85845DD1); MD5::round4(a, b, c, d, blockX[ 8], 6, 0x6FA87E4F); MD5::round4(d, a, b, c, blockX[15], 10, 0xFE2CE6E0); MD5::round4(c, d, a, b, blockX[ 6], 15, 0xA3014314); MD5::round4(b, c, d, a, blockX[13], 21, 0x4E0811A1); MD5::round4(a, b, c, d, blockX[ 4], 6, 0xF7537E82); MD5::round4(d, a, b, c, blockX[11], 10, 0xBD3AF235); MD5::round4(c, d, a, b, blockX[ 2], 15, 0x2AD7D2BB); MD5::round4(b, c, d, a, blockX[ 9], 21, 0xEB86D391); // Increment each state by it's previous value state[0] += a; state[1] += b; state[2] += c; state[3] += d; } pOutput->write((const uint8_t *)state, 16); // Zeroize sensitive information std::memset(blockX, 0, sizeof(blockX)); std::memset(data, 0, dataSize); delete[] data; } namespace SHA1 { void initialize(uint32_t *pResult) { pResult[0] = 0x67452301; pResult[1] = 0xEFCDAB89; pResult[2] = 0x98BADCFE; pResult[3] = 0x10325476; pResult[4] = 0xC3D2E1F0; } void process(uint32_t *pResult, uint32_t *pBlock) { unsigned int i; uint32_t a, b, c, d, e, f, k, step; uint32_t extendedBlock[80]; std::memcpy(extendedBlock, pBlock, 64); // Adjust for big endian if(Endian::sSystemType != Endian::BIG) for(i=0;i<16;i++) extendedBlock[i] = Endian::convert(extendedBlock[i], Endian::BIG); // Extend the sixteen 32-bit words into eighty 32-bit words: for(i=16;i<80;i++) extendedBlock[i] = Math::rotateLeft(extendedBlock[i-3] ^ extendedBlock[i-8] ^ extendedBlock[i-14] ^ extendedBlock[i-16], 1); // Initialize hash value for this chunk: a = pResult[0]; b = pResult[1]; c = pResult[2]; d = pResult[3]; e = pResult[4]; // Main loop: for(i=0;i<80;i++) { if(i < 20) { f = (b & c) |((~b) & d); k = 0x5A827999; } else if(i < 40) { f = b ^ c ^ d; k = 0x6ED9EBA1; } else if(i < 60) { f = (b & c) |(b & d) |(c & d); k = 0x8F1BBCDC; } else // if(i < 80) { f = b ^ c ^ d; k = 0xCA62C1D6; } step = Math::rotateLeft(a, 5) + f + e + k + extendedBlock[i]; e = d; d = c; c = Math::rotateLeft(b, 30); b = a; a = step; } // Add this chunk's hash to result so far: pResult[0] += a; pResult[1] += b; pResult[2] += c; pResult[3] += d; pResult[4] += e; } void finish(uint32_t *pResult, uint32_t *pBlock, unsigned int pBlockLength, uint64_t pTotalLength) { // Zeroize the end of the block std::memset(((uint8_t *)pBlock) + pBlockLength, 0, 64 - pBlockLength); // Add 0x80 byte (basically a 1 bit at the end of the data) ((uint8_t *)pBlock)[pBlockLength] = 0x80; // Check if there is enough room for the total length in this block if(pBlockLength > 55) // 55 because of the 0x80 byte already added { process(pResult, pBlock); // Process this block std::memset(pBlock, 0, 64); // Clear the block } // Put bit length in last 8 bytes of block (Big Endian) pTotalLength *= 8; uint32_t lower = pTotalLength & 0xffffffff; pBlock[15] = Endian::convert(lower, Endian::BIG); uint32_t upper = (pTotalLength >> 32) & 0xffffffff; pBlock[14] = Endian::convert(upper, Endian::BIG); // Process last block process(pResult, pBlock); // Adjust for big endian if(Endian::sSystemType != Endian::BIG) for(unsigned int i=0;i<5;i++) pResult[i] = Endian::convert(pResult[i], Endian::BIG); } } void Digest::sha1(InputStream *pInput, stream_size pInputLength, OutputStream *pOutput) // 160 bit(20 byte) result { // Note 1: All variables are unsigned 32 bits and wrap modulo 232 when calculating // Note 2: All constants in this pseudo code are in big endian. // Within each word, the most significant bit is stored in the leftmost bit position stream_size dataSize = pInputLength + (64 - (pInputLength % 64)); uint64_t bitLength = (uint64_t)pInputLength * 8; Buffer message; message.setEndian(Endian::BIG); message.writeStream(pInput, pInputLength); // Pre-processing: // append the bit '1' to the message message.writeByte(0x80); // append k bits '0', where k is the minimum number ? 0 such that the resulting message // length(in bits) is congruent to 448(mod 512) // Append the rest zero bits while(message.length() < dataSize - 8) message.writeByte(0); // append length of message(before pre-processing), in bits, as 64-bit big-endian integer // Append the data length as a 64 bit number low order word first message.writeUnsignedLong(bitLength); uint32_t state[5] = { 0x67452301, 0xEFCDAB89, 0x98BADCFE, 0x10325476, 0xC3D2E1F0 }; uint32_t a, b, c, d, e; // Process the message in successive 512-bit chunks: // break message into 512-bit chunks // for each chunk unsigned int i, blockIndex, blockCount = dataSize / 64; uint32_t extended[80]; uint32_t f, k, step; for(blockIndex=0;blockIndex<blockCount;blockIndex++) { // break chunk into sixteen 32-bit big-endian words w[i], 0 ? i ? 15 for(i=0;i<16;i++) extended[i] = message.readUnsignedInt(); // Extend the sixteen 32-bit words into eighty 32-bit words: for(i=16;i<80;i++) extended[i] = Math::rotateLeft(extended[i-3] ^ extended[i-8] ^ extended[i-14] ^ extended[i-16], 1); // Initialize hash value for this chunk: a = state[0]; b = state[1]; c = state[2]; d = state[3]; e = state[4]; // Main loop: for(i=0;i<80;i++) { if(i < 20) { f = (b & c) |((~b) & d); k = 0x5A827999; } else if(i < 40) { f = b ^ c ^ d; k = 0x6ED9EBA1; } else if(i < 60) { f = (b & c) |(b & d) |(c & d); k = 0x8F1BBCDC; } else // if(i < 80) { f = b ^ c ^ d; k = 0xCA62C1D6; } step = Math::rotateLeft(a, 5) + f + e + k + extended[i]; e = d; d = c; c = Math::rotateLeft(b, 30); b = a; a = step; } // Add this chunk's hash to result so far: state[0] += a; state[1] += b; state[2] += c; state[3] += d; state[4] += e; } for(unsigned int i=0;i<5;i++) pOutput->writeUnsignedInt(Endian::convert(state[i], Endian::BIG)); // Zeroize possible sensitive data message.zeroize(); std::memset(extended, 0, sizeof(int) * 80); std::memset(state, 0, sizeof(int) * 5); } namespace RIPEMD160 { inline uint32_t f(uint32_t pX, uint32_t pY, uint32_t pZ) { return pX ^ pY ^ pZ; } inline uint32_t g(uint32_t pX, uint32_t pY, uint32_t pZ) { return (pX & pY) | (~pX & pZ); } inline uint32_t h(uint32_t pX, uint32_t pY, uint32_t pZ) { return (pX | ~pY) ^ pZ; } inline uint32_t i(uint32_t pX, uint32_t pY, uint32_t pZ) { return (pX & pZ) | (pY & ~pZ); } inline uint32_t j(uint32_t pX, uint32_t pY, uint32_t pZ) { return pX ^ (pY | ~pZ); } inline void ff(uint32_t &pA, uint32_t &pB, uint32_t &pC, uint32_t &pD, uint32_t &pE, uint32_t &pX, uint32_t pS) { pA += f(pB, pC, pD) + pX; pA = Math::rotateLeft(pA, pS) + pE; pC = Math::rotateLeft(pC, 10); } inline void gg(uint32_t &pA, uint32_t &pB, uint32_t &pC, uint32_t &pD, uint32_t &pE, uint32_t &pX, uint32_t pS) { pA += g(pB, pC, pD) + pX + 0x5a827999; pA = Math::rotateLeft(pA, pS) + pE; pC = Math::rotateLeft(pC, 10); } inline void hh(uint32_t &pA, uint32_t &pB, uint32_t &pC, uint32_t &pD, uint32_t &pE, uint32_t &pX, uint32_t pS) { pA += h(pB, pC, pD) + pX + 0x6ed9eba1; pA = Math::rotateLeft(pA, pS) + pE; pC = Math::rotateLeft(pC, 10); } inline void ii(uint32_t &pA, uint32_t &pB, uint32_t &pC, uint32_t &pD, uint32_t &pE, uint32_t &pX, uint32_t pS) { pA += i(pB, pC, pD) + pX + 0x8f1bbcdc; pA = Math::rotateLeft(pA, pS) + pE; pC = Math::rotateLeft(pC, 10); } inline void jj(uint32_t &pA, uint32_t &pB, uint32_t &pC, uint32_t &pD, uint32_t &pE, uint32_t &pX, uint32_t pS) { pA += j(pB, pC, pD) + pX + 0xa953fd4e; pA = Math::rotateLeft(pA, pS) + pE; pC = Math::rotateLeft(pC, 10); } inline void fff(uint32_t &pA, uint32_t &pB, uint32_t &pC, uint32_t &pD, uint32_t &pE, uint32_t &pX, uint32_t pS) { pA += f(pB, pC, pD) + pX; pA = Math::rotateLeft(pA, pS) + pE; pC = Math::rotateLeft(pC, 10); } inline void ggg(uint32_t &pA, uint32_t &pB, uint32_t &pC, uint32_t &pD, uint32_t &pE, uint32_t &pX, uint32_t pS) { pA += g(pB, pC, pD) + pX + 0x7a6d76e9; pA = Math::rotateLeft(pA, pS) + pE; pC = Math::rotateLeft(pC, 10); } inline void hhh(uint32_t &pA, uint32_t &pB, uint32_t &pC, uint32_t &pD, uint32_t &pE, uint32_t &pX, uint32_t pS) { pA += h(pB, pC, pD) + pX + 0x6d703ef3; pA = Math::rotateLeft(pA, pS) + pE; pC = Math::rotateLeft(pC, 10); } inline void iii(uint32_t &pA, uint32_t &pB, uint32_t &pC, uint32_t &pD, uint32_t &pE, uint32_t &pX, uint32_t pS) { pA += i(pB, pC, pD) + pX + 0x5c4dd124; pA = Math::rotateLeft(pA, pS) + pE; pC = Math::rotateLeft(pC, 10); } inline void jjj(uint32_t &pA, uint32_t &pB, uint32_t &pC, uint32_t &pD, uint32_t &pE, uint32_t &pX, uint32_t pS) { pA += j(pB, pC, pD) + pX + 0x50a28be6; pA = Math::rotateLeft(pA, pS) + pE; pC = Math::rotateLeft(pC, 10); } void initialize(uint32_t *pResult) { pResult[0] = 0x67452301; pResult[1] = 0xefcdab89; pResult[2] = 0x98badcfe; pResult[3] = 0x10325476; pResult[4] = 0xc3d2e1f0; } void process(uint32_t *pResult, uint32_t *pBlock) { uint32_t aa = pResult[0], bb = pResult[1], cc = pResult[2], dd = pResult[3], ee = pResult[4]; uint32_t aaa = pResult[0], bbb = pResult[1], ccc = pResult[2], ddd = pResult[3], eee = pResult[4]; // Round 1 ff(aa, bb, cc, dd, ee, pBlock[ 0], 11); ff(ee, aa, bb, cc, dd, pBlock[ 1], 14); ff(dd, ee, aa, bb, cc, pBlock[ 2], 15); ff(cc, dd, ee, aa, bb, pBlock[ 3], 12); ff(bb, cc, dd, ee, aa, pBlock[ 4], 5); ff(aa, bb, cc, dd, ee, pBlock[ 5], 8); ff(ee, aa, bb, cc, dd, pBlock[ 6], 7); ff(dd, ee, aa, bb, cc, pBlock[ 7], 9); ff(cc, dd, ee, aa, bb, pBlock[ 8], 11); ff(bb, cc, dd, ee, aa, pBlock[ 9], 13); ff(aa, bb, cc, dd, ee, pBlock[10], 14); ff(ee, aa, bb, cc, dd, pBlock[11], 15); ff(dd, ee, aa, bb, cc, pBlock[12], 6); ff(cc, dd, ee, aa, bb, pBlock[13], 7); ff(bb, cc, dd, ee, aa, pBlock[14], 9); ff(aa, bb, cc, dd, ee, pBlock[15], 8); // Round 2 gg(ee, aa, bb, cc, dd, pBlock[ 7], 7); gg(dd, ee, aa, bb, cc, pBlock[ 4], 6); gg(cc, dd, ee, aa, bb, pBlock[13], 8); gg(bb, cc, dd, ee, aa, pBlock[ 1], 13); gg(aa, bb, cc, dd, ee, pBlock[10], 11); gg(ee, aa, bb, cc, dd, pBlock[ 6], 9); gg(dd, ee, aa, bb, cc, pBlock[15], 7); gg(cc, dd, ee, aa, bb, pBlock[ 3], 15); gg(bb, cc, dd, ee, aa, pBlock[12], 7); gg(aa, bb, cc, dd, ee, pBlock[ 0], 12); gg(ee, aa, bb, cc, dd, pBlock[ 9], 15); gg(dd, ee, aa, bb, cc, pBlock[ 5], 9); gg(cc, dd, ee, aa, bb, pBlock[ 2], 11); gg(bb, cc, dd, ee, aa, pBlock[14], 7); gg(aa, bb, cc, dd, ee, pBlock[11], 13); gg(ee, aa, bb, cc, dd, pBlock[ 8], 12); // Round 3 hh(dd, ee, aa, bb, cc, pBlock[ 3], 11); hh(cc, dd, ee, aa, bb, pBlock[10], 13); hh(bb, cc, dd, ee, aa, pBlock[14], 6); hh(aa, bb, cc, dd, ee, pBlock[ 4], 7); hh(ee, aa, bb, cc, dd, pBlock[ 9], 14); hh(dd, ee, aa, bb, cc, pBlock[15], 9); hh(cc, dd, ee, aa, bb, pBlock[ 8], 13); hh(bb, cc, dd, ee, aa, pBlock[ 1], 15); hh(aa, bb, cc, dd, ee, pBlock[ 2], 14); hh(ee, aa, bb, cc, dd, pBlock[ 7], 8); hh(dd, ee, aa, bb, cc, pBlock[ 0], 13); hh(cc, dd, ee, aa, bb, pBlock[ 6], 6); hh(bb, cc, dd, ee, aa, pBlock[13], 5); hh(aa, bb, cc, dd, ee, pBlock[11], 12); hh(ee, aa, bb, cc, dd, pBlock[ 5], 7); hh(dd, ee, aa, bb, cc, pBlock[12], 5); // Round 4 ii(cc, dd, ee, aa, bb, pBlock[ 1], 11); ii(bb, cc, dd, ee, aa, pBlock[ 9], 12); ii(aa, bb, cc, dd, ee, pBlock[11], 14); ii(ee, aa, bb, cc, dd, pBlock[10], 15); ii(dd, ee, aa, bb, cc, pBlock[ 0], 14); ii(cc, dd, ee, aa, bb, pBlock[ 8], 15); ii(bb, cc, dd, ee, aa, pBlock[12], 9); ii(aa, bb, cc, dd, ee, pBlock[ 4], 8); ii(ee, aa, bb, cc, dd, pBlock[13], 9); ii(dd, ee, aa, bb, cc, pBlock[ 3], 14); ii(cc, dd, ee, aa, bb, pBlock[ 7], 5); ii(bb, cc, dd, ee, aa, pBlock[15], 6); ii(aa, bb, cc, dd, ee, pBlock[14], 8); ii(ee, aa, bb, cc, dd, pBlock[ 5], 6); ii(dd, ee, aa, bb, cc, pBlock[ 6], 5); ii(cc, dd, ee, aa, bb, pBlock[ 2], 12); // Round 5 jj(bb, cc, dd, ee, aa, pBlock[ 4], 9); jj(aa, bb, cc, dd, ee, pBlock[ 0], 15); jj(ee, aa, bb, cc, dd, pBlock[ 5], 5); jj(dd, ee, aa, bb, cc, pBlock[ 9], 11); jj(cc, dd, ee, aa, bb, pBlock[ 7], 6); jj(bb, cc, dd, ee, aa, pBlock[12], 8); jj(aa, bb, cc, dd, ee, pBlock[ 2], 13); jj(ee, aa, bb, cc, dd, pBlock[10], 12); jj(dd, ee, aa, bb, cc, pBlock[14], 5); jj(cc, dd, ee, aa, bb, pBlock[ 1], 12); jj(bb, cc, dd, ee, aa, pBlock[ 3], 13); jj(aa, bb, cc, dd, ee, pBlock[ 8], 14); jj(ee, aa, bb, cc, dd, pBlock[11], 11); jj(dd, ee, aa, bb, cc, pBlock[ 6], 8); jj(cc, dd, ee, aa, bb, pBlock[15], 5); jj(bb, cc, dd, ee, aa, pBlock[13], 6); // Parallel round 1 jjj(aaa, bbb, ccc, ddd, eee, pBlock[ 5], 8); jjj(eee, aaa, bbb, ccc, ddd, pBlock[14], 9); jjj(ddd, eee, aaa, bbb, ccc, pBlock[ 7], 9); jjj(ccc, ddd, eee, aaa, bbb, pBlock[ 0], 11); jjj(bbb, ccc, ddd, eee, aaa, pBlock[ 9], 13); jjj(aaa, bbb, ccc, ddd, eee, pBlock[ 2], 15); jjj(eee, aaa, bbb, ccc, ddd, pBlock[11], 15); jjj(ddd, eee, aaa, bbb, ccc, pBlock[ 4], 5); jjj(ccc, ddd, eee, aaa, bbb, pBlock[13], 7); jjj(bbb, ccc, ddd, eee, aaa, pBlock[ 6], 7); jjj(aaa, bbb, ccc, ddd, eee, pBlock[15], 8); jjj(eee, aaa, bbb, ccc, ddd, pBlock[ 8], 11); jjj(ddd, eee, aaa, bbb, ccc, pBlock[ 1], 14); jjj(ccc, ddd, eee, aaa, bbb, pBlock[10], 14); jjj(bbb, ccc, ddd, eee, aaa, pBlock[ 3], 12); jjj(aaa, bbb, ccc, ddd, eee, pBlock[12], 6); // Parallel round 2 iii(eee, aaa, bbb, ccc, ddd, pBlock[ 6], 9); iii(ddd, eee, aaa, bbb, ccc, pBlock[11], 13); iii(ccc, ddd, eee, aaa, bbb, pBlock[ 3], 15); iii(bbb, ccc, ddd, eee, aaa, pBlock[ 7], 7); iii(aaa, bbb, ccc, ddd, eee, pBlock[ 0], 12); iii(eee, aaa, bbb, ccc, ddd, pBlock[13], 8); iii(ddd, eee, aaa, bbb, ccc, pBlock[ 5], 9); iii(ccc, ddd, eee, aaa, bbb, pBlock[10], 11); iii(bbb, ccc, ddd, eee, aaa, pBlock[14], 7); iii(aaa, bbb, ccc, ddd, eee, pBlock[15], 7); iii(eee, aaa, bbb, ccc, ddd, pBlock[ 8], 12); iii(ddd, eee, aaa, bbb, ccc, pBlock[12], 7); iii(ccc, ddd, eee, aaa, bbb, pBlock[ 4], 6); iii(bbb, ccc, ddd, eee, aaa, pBlock[ 9], 15); iii(aaa, bbb, ccc, ddd, eee, pBlock[ 1], 13); iii(eee, aaa, bbb, ccc, ddd, pBlock[ 2], 11); // Parallel round 3 hhh(ddd, eee, aaa, bbb, ccc, pBlock[15], 9); hhh(ccc, ddd, eee, aaa, bbb, pBlock[ 5], 7); hhh(bbb, ccc, ddd, eee, aaa, pBlock[ 1], 15); hhh(aaa, bbb, ccc, ddd, eee, pBlock[ 3], 11); hhh(eee, aaa, bbb, ccc, ddd, pBlock[ 7], 8); hhh(ddd, eee, aaa, bbb, ccc, pBlock[14], 6); hhh(ccc, ddd, eee, aaa, bbb, pBlock[ 6], 6); hhh(bbb, ccc, ddd, eee, aaa, pBlock[ 9], 14); hhh(aaa, bbb, ccc, ddd, eee, pBlock[11], 12); hhh(eee, aaa, bbb, ccc, ddd, pBlock[ 8], 13); hhh(ddd, eee, aaa, bbb, ccc, pBlock[12], 5); hhh(ccc, ddd, eee, aaa, bbb, pBlock[ 2], 14); hhh(bbb, ccc, ddd, eee, aaa, pBlock[10], 13); hhh(aaa, bbb, ccc, ddd, eee, pBlock[ 0], 13); hhh(eee, aaa, bbb, ccc, ddd, pBlock[ 4], 7); hhh(ddd, eee, aaa, bbb, ccc, pBlock[13], 5); // Parallel round 4 ggg(ccc, ddd, eee, aaa, bbb, pBlock[ 8], 15); ggg(bbb, ccc, ddd, eee, aaa, pBlock[ 6], 5); ggg(aaa, bbb, ccc, ddd, eee, pBlock[ 4], 8); ggg(eee, aaa, bbb, ccc, ddd, pBlock[ 1], 11); ggg(ddd, eee, aaa, bbb, ccc, pBlock[ 3], 14); ggg(ccc, ddd, eee, aaa, bbb, pBlock[11], 14); ggg(bbb, ccc, ddd, eee, aaa, pBlock[15], 6); ggg(aaa, bbb, ccc, ddd, eee, pBlock[ 0], 14); ggg(eee, aaa, bbb, ccc, ddd, pBlock[ 5], 6); ggg(ddd, eee, aaa, bbb, ccc, pBlock[12], 9); ggg(ccc, ddd, eee, aaa, bbb, pBlock[ 2], 12); ggg(bbb, ccc, ddd, eee, aaa, pBlock[13], 9); ggg(aaa, bbb, ccc, ddd, eee, pBlock[ 9], 12); ggg(eee, aaa, bbb, ccc, ddd, pBlock[ 7], 5); ggg(ddd, eee, aaa, bbb, ccc, pBlock[10], 15); ggg(ccc, ddd, eee, aaa, bbb, pBlock[14], 8); // Parallel round 5 fff(bbb, ccc, ddd, eee, aaa, pBlock[12] , 8); fff(aaa, bbb, ccc, ddd, eee, pBlock[15] , 5); fff(eee, aaa, bbb, ccc, ddd, pBlock[10] , 12); fff(ddd, eee, aaa, bbb, ccc, pBlock[ 4] , 9); fff(ccc, ddd, eee, aaa, bbb, pBlock[ 1] , 12); fff(bbb, ccc, ddd, eee, aaa, pBlock[ 5] , 5); fff(aaa, bbb, ccc, ddd, eee, pBlock[ 8] , 14); fff(eee, aaa, bbb, ccc, ddd, pBlock[ 7] , 6); fff(ddd, eee, aaa, bbb, ccc, pBlock[ 6] , 8); fff(ccc, ddd, eee, aaa, bbb, pBlock[ 2] , 13); fff(bbb, ccc, ddd, eee, aaa, pBlock[13] , 6); fff(aaa, bbb, ccc, ddd, eee, pBlock[14] , 5); fff(eee, aaa, bbb, ccc, ddd, pBlock[ 0] , 15); fff(ddd, eee, aaa, bbb, ccc, pBlock[ 3] , 13); fff(ccc, ddd, eee, aaa, bbb, pBlock[ 9] , 11); fff(bbb, ccc, ddd, eee, aaa, pBlock[11] , 11); // Combine results ddd += cc + pResult[1]; pResult[1] = pResult[2] + dd + eee; pResult[2] = pResult[3] + ee + aaa; pResult[3] = pResult[4] + aa + bbb; pResult[4] = pResult[0] + bb + ccc; pResult[0] = ddd; } // BlockLength must be less than 64 void finish(uint32_t *pResult, uint32_t *pBlock, unsigned int pBlockLength, uint64_t pTotalLength) { // Zeroize the end of the block std::memset(((uint8_t *)pBlock) + pBlockLength, 0, 64 - pBlockLength); // Add 0x80 byte (basically a 1 bit at the end of the data) ((uint8_t *)pBlock)[pBlockLength] = 0x80; // Check if there is enough room for the total length in this block if(pBlockLength > 55) // 55 because of the 0x80 byte { process(pResult, pBlock); // Process this block std::memset(pBlock, 0, 64); // Clear the block } // Put bit length in last 8 bytes of block pTotalLength *= 8; ((uint64_t *)pBlock)[7] = Endian::convert(pTotalLength, Endian::LITTLE); // Process last block process(pResult, pBlock); } } void Digest::ripEMD160(InputStream *pInput, stream_size pInputLength, OutputStream *pOutput) { uint32_t result[5]; uint32_t block[16]; stream_size remaining = pInputLength; RIPEMD160::initialize(result); // Process all full (64 byte) blocks while(remaining >= 64) { pInput->read(block, 64); remaining -= 64; RIPEMD160::process(result, block); } // Get last partial block (must be less than 64 bytes) pInput->read(block, remaining); // Process last block RIPEMD160::finish(result, block, remaining, pInputLength); // Write output pOutput->write(result, 20); } namespace SHA256 { static const uint32_t table[64] = { 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2 }; void initialize(uint32_t *pResult) { pResult[0] = 0x6a09e667; pResult[1] = 0xbb67ae85; pResult[2] = 0x3c6ef372; pResult[3] = 0xa54ff53a; pResult[4] = 0x510e527f; pResult[5] = 0x9b05688c; pResult[6] = 0x1f83d9ab; pResult[7] = 0x5be0cd19; } void process(uint32_t *pResult, uint32_t *pBlock) { unsigned int i; uint32_t s0, s1, t1, t2; uint32_t extendedBlock[64]; std::memcpy(extendedBlock, pBlock, 64); // Adjust for big endian if(Endian::sSystemType != Endian::BIG) for(i=0;i<16;i++) extendedBlock[i] = Endian::convert(extendedBlock[i], Endian::BIG); // Extend the block to 64 32-bit words: for(i=16;i<64;i++) { s0 = extendedBlock[i-15]; s0 = Math::rotateRight(s0, 7) ^ Math::rotateRight(s0, 18) ^ (s0 >> 3); s1 = extendedBlock[i-2]; s1 = Math::rotateRight(s1, 17) ^ Math::rotateRight(s1, 19) ^ (s1 >> 10); extendedBlock[i] = extendedBlock[i-16] + extendedBlock[i-7] + s0 + s1; } uint32_t state[8]; std::memcpy(state, pResult, 32); for(i=0;i<64;i++) { s0 = Math::rotateRight(state[0], 2) ^ Math::rotateRight(state[0], 13) ^ Math::rotateRight(state[0], 22); t2 = s0 +((state[0] & state[1]) ^(state [0] & state[2]) ^(state[1] & state[2])); s1 = Math::rotateRight(state[4], 6) ^ Math::rotateRight(state[4], 11) ^ Math::rotateRight(state[4], 25); t1 = state[7] + s1 +((state[4] & state[5]) ^(~state[4] & state[6])) + table[i] + extendedBlock[i]; state[7] = state[6]; state[6] = state[5]; state[5] = state[4]; state[4] = state[3] + t1; state[3] = state[2]; state[2] = state[1]; state[1] = state[0]; state[0] = t1 + t2; } for(i=0;i<8;i++) pResult[i] += state[i]; } void finish(uint32_t *pResult, uint32_t *pBlock, unsigned int pBlockLength, uint64_t pTotalLength) { // Zeroize the end of the block std::memset(((uint8_t *)pBlock) + pBlockLength, 0, 64 - pBlockLength); // Add 0x80 byte (basically a 1 bit at the end of the data) ((uint8_t *)pBlock)[pBlockLength] = 0x80; // Check if there is enough room for the total length in this block if(pBlockLength > 55) // 56 - 1 because of the 0x80 byte already added { process(pResult, pBlock); // Process this block std::memset(pBlock, 0, 64); // Clear the block } // Put bit length in last 8 bytes of block (Big Endian) pTotalLength *= 8; ((uint64_t *)pBlock)[7] = Endian::convert(pTotalLength, Endian::BIG); // Process last block process(pResult, pBlock); // Adjust for big endian if(Endian::sSystemType != Endian::BIG) for(unsigned int i=0;i<8;i++) pResult[i] = Endian::convert(pResult[i], Endian::BIG); } } void Digest::sha256(InputStream *pInput, stream_size pInputLength, OutputStream *pOutput) // 256 bit(32 byte) result { stream_size remaining = pInputLength; uint32_t result[8]; uint32_t block[16]; SHA256::initialize(result); while(remaining >= 64) { pInput->read(block, 64); remaining -= 64; SHA256::process(result, block); } pInput->read(block, remaining); SHA256::finish(result, block, remaining, pInputLength); pOutput->write(result, 32); return; } namespace SHA512 { static const uint64_t table[80] = { 0x428a2f98d728ae22, 0x7137449123ef65cd, 0xb5c0fbcfec4d3b2f, 0xe9b5dba58189dbbc, 0x3956c25bf348b538, 0x59f111f1b605d019, 0x923f82a4af194f9b, 0xab1c5ed5da6d8118, 0xd807aa98a3030242, 0x12835b0145706fbe, 0x243185be4ee4b28c, 0x550c7dc3d5ffb4e2, 0x72be5d74f27b896f, 0x80deb1fe3b1696b1, 0x9bdc06a725c71235, 0xc19bf174cf692694, 0xe49b69c19ef14ad2, 0xefbe4786384f25e3, 0x0fc19dc68b8cd5b5, 0x240ca1cc77ac9c65, 0x2de92c6f592b0275, 0x4a7484aa6ea6e483, 0x5cb0a9dcbd41fbd4, 0x76f988da831153b5, 0x983e5152ee66dfab, 0xa831c66d2db43210, 0xb00327c898fb213f, 0xbf597fc7beef0ee4, 0xc6e00bf33da88fc2, 0xd5a79147930aa725, 0x06ca6351e003826f, 0x142929670a0e6e70, 0x27b70a8546d22ffc, 0x2e1b21385c26c926, 0x4d2c6dfc5ac42aed, 0x53380d139d95b3df, 0x650a73548baf63de, 0x766a0abb3c77b2a8, 0x81c2c92e47edaee6, 0x92722c851482353b, 0xa2bfe8a14cf10364, 0xa81a664bbc423001, 0xc24b8b70d0f89791, 0xc76c51a30654be30, 0xd192e819d6ef5218, 0xd69906245565a910, 0xf40e35855771202a, 0x106aa07032bbd1b8, 0x19a4c116b8d2d0c8, 0x1e376c085141ab53, 0x2748774cdf8eeb99, 0x34b0bcb5e19b48a8, 0x391c0cb3c5c95a63, 0x4ed8aa4ae3418acb, 0x5b9cca4f7763e373, 0x682e6ff3d6b2b8a3, 0x748f82ee5defb2fc, 0x78a5636f43172f60, 0x84c87814a1f0ab72, 0x8cc702081a6439ec, 0x90befffa23631e28, 0xa4506cebde82bde9, 0xbef9a3f7b2c67915, 0xc67178f2e372532b, 0xca273eceea26619c, 0xd186b8c721c0c207, 0xeada7dd6cde0eb1e, 0xf57d4f7fee6ed178, 0x06f067aa72176fba, 0x0a637dc5a2c898a6, 0x113f9804bef90dae, 0x1b710b35131c471b, 0x28db77f523047d84, 0x32caab7b40c72493, 0x3c9ebe0a15c9bebc, 0x431d67c49c100d4c, 0x4cc5d4becb3e42b6, 0x597f299cfc657e2a, 0x5fcb6fab3ad6faec, 0x6c44198c4a475817 }; void initialize(uint32_t *pResult) { ((uint64_t *)pResult)[0] = 0x6a09e667f3bcc908; ((uint64_t *)pResult)[1] = 0xbb67ae8584caa73b; ((uint64_t *)pResult)[2] = 0x3c6ef372fe94f82b; ((uint64_t *)pResult)[3] = 0xa54ff53a5f1d36f1; ((uint64_t *)pResult)[4] = 0x510e527fade682d1; ((uint64_t *)pResult)[5] = 0x9b05688c2b3e6c1f; ((uint64_t *)pResult)[6] = 0x1f83d9abfb41bd6b; ((uint64_t *)pResult)[7] = 0x5be0cd19137e2179; } void process(uint32_t *pResult, uint32_t *pBlock) { unsigned int i; uint64_t s0, s1, t1, t2; uint64_t extendedBlock[80]; std::memcpy(extendedBlock, pBlock, 128); // Adjust for big endian if(Endian::sSystemType != Endian::BIG) for(i=0;i<16;++i) extendedBlock[i] = Endian::convert(extendedBlock[i], Endian::BIG); // Extend the block to 80 64-bit words: for(i=16;i<80;++i) { s0 = extendedBlock[i-15]; s0 = Math::rotateRight64(s0, 1) ^ Math::rotateRight64(s0, 8) ^ (s0 >> 7); s1 = extendedBlock[i-2]; s1 = Math::rotateRight64(s1, 19) ^ Math::rotateRight64(s1, 61) ^ (s1 >> 6); extendedBlock[i] = extendedBlock[i-16] + extendedBlock[i-7] + s0 + s1; } uint64_t state[8]; std::memcpy(state, pResult, 64); for(i=0;i<80;++i) { s0 = Math::rotateRight64(state[0], 28) ^ Math::rotateRight64(state[0], 34) ^ Math::rotateRight64(state[0], 39); t2 = s0 +((state[0] & state[1]) ^ (state [0] & state[2]) ^ (state[1] & state[2])); s1 = Math::rotateRight64(state[4], 14) ^ Math::rotateRight64(state[4], 18) ^ Math::rotateRight64(state[4], 41); t1 = state[7] + s1 + ((state[4] & state[5]) ^ (~state[4] & state[6])) + table[i] + extendedBlock[i]; state[7] = state[6]; state[6] = state[5]; state[5] = state[4]; state[4] = state[3] + t1; state[3] = state[2]; state[2] = state[1]; state[1] = state[0]; state[0] = t1 + t2; } for(i=0;i<8;++i) ((uint64_t *)pResult)[i] += state[i]; } void finish(uint32_t *pResult, uint32_t *pBlock, unsigned int pBlockLength, uint64_t pTotalLength) { // Zeroize the end of the block if(pBlockLength < 128) std::memset(((uint8_t *)pBlock) + pBlockLength, 0, 128 - pBlockLength); // Add 0x80 byte (basically a 1 bit at the end of the data) ((uint8_t *)pBlock)[pBlockLength] = 0x80; // Check if there is enough room for the total length in this block if(pBlockLength > 111) // 112 - 1 because of the 0x80 byte already added { process(pResult, pBlock); // Process this block std::memset(pBlock, 0, 128); // Clear the block } // Put bit length in last 16 bytes of block (Big Endian) pTotalLength *= 8; ((uint64_t *)pBlock)[15] = Endian::convert(pTotalLength, Endian::BIG); // Process last block process(pResult, pBlock); // Adjust for big endian if(Endian::sSystemType != Endian::BIG) for(unsigned int i=0;i<8;++i) ((uint64_t *)pResult)[i] = Endian::convert(((uint64_t *)pResult)[i], Endian::BIG); } } void Digest::sha512(InputStream *pInput, stream_size pInputLength, OutputStream *pOutput) // 512 bit(64 byte) result { stream_size remaining = pInputLength; uint32_t result[16]; uint32_t block[32]; SHA512::initialize(result); while(remaining >= 128) { pInput->read(block, 128); remaining -= 128; SHA512::process(result, block); } pInput->read(block, remaining); SHA512::finish(result, block, remaining, pInputLength); pOutput->write(result, 64); return; } namespace SipHash24 { void round(uint64_t *pResult, unsigned int pRounds) { for(unsigned i=0;i<pRounds;i++) { pResult[0] += pResult[1]; pResult[1] = Math::rotateLeft64(pResult[1], 13); pResult[1] ^= pResult[0]; pResult[0] = Math::rotateLeft64(pResult[0], 32); pResult[2] += pResult[3]; pResult[3] = Math::rotateLeft64(pResult[3], 16); pResult[3] ^= pResult[2]; pResult[0] += pResult[3]; pResult[3] = Math::rotateLeft64(pResult[3], 21); pResult[3] ^= pResult[0]; pResult[2] += pResult[1]; pResult[1] = Math::rotateLeft64(pResult[1], 17); pResult[1] ^= pResult[2]; pResult[2] = Math::rotateLeft64(pResult[2], 32); } } void initialize(uint64_t *pResult, uint64_t pKey0, uint64_t pKey1) { pResult[0] = 0x736f6d6570736575 ^ pKey0; pResult[1] = 0x646f72616e646f6d ^ pKey1; pResult[2] = 0x6c7967656e657261 ^ pKey0; pResult[3] = 0x7465646279746573 ^ pKey1; } // Process 8 bytes void process(uint64_t *pResult, const uint8_t *pBlock) { // Grab 8 bytes from pBlock and convert to uint64_t uint64_t block = 0; const uint8_t *byte = pBlock; for(unsigned int i=0;i<8;++i) block |= (uint64_t)*byte++ << (i * 8); pResult[3] ^= block; round(pResult, 2); // The 2 from SipHash-2-4 pResult[0] ^= block; } // Process less than 8 bytes and length uint64_t finish(uint64_t *pResult, const uint8_t *pBlock, unsigned int pBlockLength, uint64_t pTotalLength) { // Create last block uint8_t lastBlock[8]; std::memset(lastBlock, 0, 8); // Copy partial block into last block std::memcpy(lastBlock, pBlock, pBlockLength); // Put least significant byte of total length into most significant byte of // last "block" lastBlock[7] = pTotalLength & 0xff; // Process last block process(pResult, lastBlock); pResult[2] ^= 0xff; round(pResult, 4); // The 4 from SipHash-2-4 return pResult[0] ^ pResult[1] ^ pResult[2] ^ pResult[3]; } } uint64_t Digest::sipHash24(const uint8_t *pData, stream_size pLength, uint64_t pKey0, uint64_t pKey1) { uint64_t result[4]; SipHash24::initialize(result, pKey0, pKey1); stream_size offset = 0; while(pLength - offset >= 8) { SipHash24::process(result, pData); pData += 8; offset += 8; } return SipHash24::finish(result, pData, pLength - offset, pLength); } namespace MURMUR3 { // Only 32 bit implemented void initialize(uint32_t &pResult, uint32_t pSeed) { pResult = pSeed; } // Process 4 bytes void process(uint32_t &pResult, uint32_t pBlock) { uint32_t block = pBlock; block *= 0xcc9e2d51; block = (block << 15) | (block >> 17); block *= 0x1b873593; pResult ^= block; pResult = (pResult << 13) | (pResult >> 19); pResult = (pResult * 5) + 0xe6546b64; } // Process less than 4 bytes and length void finish(uint32_t &pResult, const uint8_t *pBlockData, unsigned int pBlockLength, uint64_t pTotalLength) { if(pBlockLength > 0) { uint32_t block = 0; const uint8_t *byte = pBlockData; for(unsigned int i=0;i<pBlockLength;++i) block |= (uint32_t)*byte++ << (i * 8); block *= 0xcc9e2d51; block = (block << 15) | (block >> 17); block *= 0x1b873593; pResult ^= block; } pResult ^= pTotalLength; pResult ^= pResult >> 16; pResult *= 0x85ebca6b; pResult ^= pResult >> 13; pResult *= 0xc2b2ae35; pResult ^= pResult >> 16; } } uint32_t Digest::murMur3(const uint8_t *pData, stream_size pLength, uint32_t pSeed) { uint32_t result; MURMUR3::initialize(result, pSeed); stream_size offset = 0; while(pLength - offset >= 4) { MURMUR3::process(result, Endian::convert(*(uint32_t *)pData, Endian::LITTLE)); pData += 4; offset += 4; } MURMUR3::finish(result, pData, pLength - offset, pLength); return result; } Digest::Digest(Type pType) { mType = pType; mByteCount = 0; setOutputEndian(Endian::BIG); switch(mType) { case CRC32: mBlockSize = 1; mResultData = new uint32_t[1]; mBlockData = NULL; break; //case MD5: // mBlockSize = 64; // break; case SHA1: case RIPEMD160: mBlockSize = 64; mResultData = new uint32_t[5]; mBlockData = new uint32_t[mBlockSize / 4]; break; case SHA256: case SHA256_SHA256: case SHA256_RIPEMD160: mBlockSize = 64; mResultData = new uint32_t[8]; mBlockData = new uint32_t[mBlockSize / 4]; break; case MURMUR3: mBlockSize = 4; mResultData = new uint32_t[1]; mBlockData = new uint32_t[mBlockSize / 4]; break; case SHA512: mBlockSize = 128; mResultData = new uint32_t[16]; mBlockData = new uint32_t[mBlockSize / 4]; break; default: mBlockSize = 0; mResultData = NULL; mBlockData = NULL; break; } initialize(); } Digest::~Digest() { if(mBlockData != NULL) delete[] mBlockData; if(mResultData != NULL) delete[] mResultData; } HMACDigest::HMACDigest(Type pType, InputStream *pKey) : Digest(pType) { initialize(pKey); } void HMACDigest::initialize(InputStream *pKey) { Digest::initialize(); Buffer key; key.writeStream(pKey, pKey->remaining()); if(key.length() > mBlockSize) { // Hash key writeStream(&key, key.length()); key.clear(); // Clear key data Digest::getResult(&key); // Read key hash into key Digest::initialize(); // Reinitialize digest } // Pad key to block size while(key.length() < mBlockSize) key.writeByte(0); // Create outer padded key key.setReadOffset(0); mOuterPaddedKey.setWriteOffset(0); while(key.remaining()) mOuterPaddedKey.writeByte(0x5c ^ key.readByte()); // Create inner padded key Buffer innerPaddedKey; key.setReadOffset(0); while(key.remaining()) innerPaddedKey.writeByte(0x36 ^ key.readByte()); // Write inner padded key into digest innerPaddedKey.setReadOffset(0); writeStream(&innerPaddedKey, innerPaddedKey.length()); } void HMACDigest::getResult(RawOutputStream *pOutput) { // Get digest result Buffer firstResult; Digest::getResult(&firstResult); // Reinitialize digest Digest::initialize(); // Write outer padded key into digest mOuterPaddedKey.setReadOffset(0); writeStream(&mOuterPaddedKey, mOuterPaddedKey.length()); // Write previous digest result into digest writeStream(&firstResult, firstResult.length()); // Get the final result Digest::getResult(pOutput); } void Digest::write(const void *pInput, stream_size pSize) { mInput.write(pInput, pSize); mByteCount += pSize; process(); } void Digest::initialize(uint32_t pSeed) { mByteCount = 0; mInput.clear(); switch(mType) { case CRC32: mResultData[0] = 0xffffffff; break; //case MD5: // break; case SHA1: SHA1::initialize(mResultData); break; case RIPEMD160: RIPEMD160::initialize(mResultData); break; case SHA256: case SHA256_SHA256: case SHA256_RIPEMD160: SHA256::initialize(mResultData); break; case MURMUR3: MURMUR3::initialize(*mResultData, pSeed); break; case SHA512: SHA512::initialize(mResultData); break; } } void Digest::process() { switch(mType) { case CRC32: while(mInput.remaining() >= mBlockSize) *mResultData = (*mResultData >> 8) ^ CRC32::table[(*mResultData & 0xFF) ^ mInput.readByte()]; break; //case MD5: // break; case SHA1: while(mInput.remaining() >= mBlockSize) { mInput.read(mBlockData, mBlockSize); SHA1::process(mResultData, mBlockData); } break; case RIPEMD160: while(mInput.remaining() >= mBlockSize) { mInput.read(mBlockData, mBlockSize); RIPEMD160::process(mResultData, mBlockData); } break; case SHA256: case SHA256_SHA256: case SHA256_RIPEMD160: while(mInput.remaining() >= mBlockSize) { mInput.read(mBlockData, mBlockSize); SHA256::process(mResultData, mBlockData); } break; case MURMUR3: while(mInput.remaining() >= mBlockSize) { mInput.read(mBlockData, mBlockSize); MURMUR3::process(*mResultData, *mBlockData); } break; case SHA512: while(mInput.remaining() >= mBlockSize) { mInput.read(mBlockData, mBlockSize); SHA512::process(mResultData, mBlockData); } break; } mInput.flush(); } unsigned int Digest::getResult() { switch(mType) { case CRC32: // Finalize result *mResultData ^= 0xffffffff; *mResultData = Endian::convert(*mResultData, Endian::BIG); return *mResultData; case MURMUR3: { // Get last partial block (must be less than 4 bytes) unsigned int lastBlockSize = mInput.remaining(); mInput.read(mBlockData, lastBlockSize); MURMUR3::finish(*mResultData, (uint8_t *)mBlockData, lastBlockSize, mByteCount); return *mResultData; } default: return 0; } } void Digest::getResult(RawOutputStream *pOutput) { switch(mType) { case CRC32: // Finalize result *mResultData ^= 0xffffffff; *mResultData = Endian::convert(*mResultData, Endian::BIG); // Output result pOutput->write(mResultData, 4); // Zeroize *mResultData = 0; break; //case MD5: // break; case SHA1: { // Get last partial block (must be less than 64 bytes) unsigned int lastBlockSize = mInput.remaining(); mInput.read(mBlockData, lastBlockSize); SHA1::finish(mResultData, mBlockData, lastBlockSize, mByteCount); // Output result pOutput->write(mResultData, 20); // Zeroize std::memset(mResultData, 0, 20); std::memset(mBlockData, 0, mBlockSize); break; } case RIPEMD160: { // Get last partial block (must be less than 64 bytes) unsigned int lastBlockSize = mInput.remaining(); mInput.read(mBlockData, lastBlockSize); RIPEMD160::finish(mResultData, mBlockData, lastBlockSize, mByteCount); // Output result pOutput->write(mResultData, 20); // Zeroize std::memset(mResultData, 0, 20); std::memset(mBlockData, 0, mBlockSize); break; } case SHA256: { // Get last partial block (must be less than 64 bytes) unsigned int lastBlockSize = mInput.remaining(); mInput.read(mBlockData, lastBlockSize); SHA256::finish(mResultData, mBlockData, lastBlockSize, mByteCount); // Output result pOutput->write(mResultData, 32); // Zeroize std::memset(mResultData, 0, 32); std::memset(mBlockData, 0, mBlockSize); break; } case SHA256_SHA256: { // Get last partial block (must be less than 64 bytes) unsigned int lastBlockSize = mInput.remaining(); mInput.read(mBlockData, lastBlockSize); SHA256::finish(mResultData, mBlockData, lastBlockSize, mByteCount); // Compute SHA256 of result Digest secondSHA256(SHA256); secondSHA256.write(mResultData, 32); Buffer secondSHA256Data(32); secondSHA256.getResult(&secondSHA256Data); // Output result pOutput->writeStream(&secondSHA256Data, 32); // Zeroize std::memset(mResultData, 0, 32); std::memset(mBlockData, 0, mBlockSize); break; } case SHA256_RIPEMD160: { // Get last partial block (must be less than 64 bytes) unsigned int lastBlockSize = mInput.remaining(); mInput.read(mBlockData, lastBlockSize); SHA256::finish(mResultData, mBlockData, lastBlockSize, mByteCount); // Compute SHA256 of result Digest ripEMD160(RIPEMD160); ripEMD160.write(mResultData, 32); Buffer ripEMD160Data(20); ripEMD160.getResult(&ripEMD160Data); // Output result pOutput->writeStream(&ripEMD160Data, 20); // Zeroize std::memset(mResultData, 0, 20); std::memset(mBlockData, 0, mBlockSize); break; } case MURMUR3: { // Get last partial block (must be less than 4 bytes) unsigned int lastBlockSize = mInput.remaining(); mInput.read(mBlockData, lastBlockSize); MURMUR3::finish(*mResultData, (uint8_t *)mBlockData, lastBlockSize, mByteCount); // Output result pOutput->write(mResultData, 4); // Zeroize std::memset(mResultData, 0, 4); std::memset(mBlockData, 0, mBlockSize); break; } case SHA512: { // Get last partial block (must be less than 64 bytes) unsigned int lastBlockSize = mInput.remaining(); mInput.read(mBlockData, lastBlockSize); SHA512::finish(mResultData, mBlockData, lastBlockSize, mByteCount); // Output result pOutput->write(mResultData, 64); // Zeroize std::memset(mResultData, 0, 64); std::memset(mBlockData, 0, mBlockSize); break; } } } bool buffersMatch(Buffer &pLeft, Buffer &pRight) { if(pLeft.length() != pRight.length()) return false; while(pLeft.remaining()) if(pLeft.readByte() != pRight.readByte()) return false; return true; } void logResults(const char *pDescription, Buffer &pBuffer) { Buffer hex; pBuffer.setReadOffset(0); hex.writeAsHex(&pBuffer, pBuffer.length(), true); char *hexText = new char[hex.length()]; hex.read((uint8_t *)hexText, hex.length()); Log::addFormatted(Log::VERBOSE, NEXTCASH_DIGEST_LOG_NAME, "%s : %s", pDescription, hexText); delete[] hexText; } bool Digest::test() { Log::add(NextCash::Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "------------- Starting Digest Tests -------------"); bool result = true; Buffer input, correctDigest, resultDigest, hmacKey; /****************************************************************************************** * Test empty (All confirmed from outside sources) ******************************************************************************************/ input.clear(); /***************************************************************************************** * CRC32 empty *****************************************************************************************/ input.setReadOffset(0); crc32(&input, input.length(), &resultDigest); correctDigest.writeHex("00000000"); if(buffersMatch(correctDigest, resultDigest)) Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed CRC32 empty"); else { Log::add(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed CRC32 empty"); logResults("Correct Digest", correctDigest); logResults("Result Digest ", resultDigest); result = false; } correctDigest.clear(); resultDigest.clear(); /***************************************************************************************** * MD5 empty *****************************************************************************************/ input.setReadOffset(0); md5(&input, input.length(), &resultDigest); correctDigest.writeHex("d41d8cd98f00b204e9800998ecf8427e"); if(buffersMatch(correctDigest, resultDigest)) Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed MD5 empty"); else { Log::add(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed MD5 empty"); logResults("Correct Digest", correctDigest); logResults("Result Digest ", resultDigest); result = false; } correctDigest.clear(); resultDigest.clear(); /***************************************************************************************** * SHA1 empty *****************************************************************************************/ input.setReadOffset(0); sha1(&input, input.length(), &resultDigest); correctDigest.writeHex("da39a3ee5e6b4b0d3255bfef95601890afd80709"); if(buffersMatch(correctDigest, resultDigest)) Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed SHA1 empty"); else { Log::add(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed SHA1 empty"); logResults("Correct Digest", correctDigest); logResults("Result Digest ", resultDigest); result = false; } correctDigest.clear(); resultDigest.clear(); /***************************************************************************************** * SHA1 digest empty *****************************************************************************************/ input.setReadOffset(0); Digest sha1EmptyDigest(SHA1); sha1EmptyDigest.writeStream(&input, input.length()); sha1EmptyDigest.getResult(&resultDigest); correctDigest.writeHex("da39a3ee5e6b4b0d3255bfef95601890afd80709"); if(buffersMatch(correctDigest, resultDigest)) Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed SHA1 digest empty"); else { Log::add(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed SHA1 digest empty"); logResults("Correct Digest", correctDigest); logResults("Result Digest ", resultDigest); result = false; } correctDigest.clear(); resultDigest.clear(); /***************************************************************************************** * RIPEMD160 empty *****************************************************************************************/ input.setReadOffset(0); ripEMD160(&input, input.length(), &resultDigest); correctDigest.writeHex("9c1185a5c5e9fc54612808977ee8f548b2258d31"); if(buffersMatch(correctDigest, resultDigest)) Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed RIPEMD160 empty"); else { Log::add(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed RIPEMD160 empty"); logResults("Correct Digest", correctDigest); logResults("Result Digest ", resultDigest); result = false; } correctDigest.clear(); resultDigest.clear(); /***************************************************************************************** * RIPEMD160 digest empty *****************************************************************************************/ input.setReadOffset(0); Digest ripemd160EmptyDigest(RIPEMD160); ripemd160EmptyDigest.writeStream(&input, input.length()); ripemd160EmptyDigest.getResult(&resultDigest); correctDigest.writeHex("9c1185a5c5e9fc54612808977ee8f548b2258d31"); if(buffersMatch(correctDigest, resultDigest)) Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed RIPEMD160 digest empty"); else { Log::add(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed RIPEMD160 digest empty"); logResults("Correct Digest", correctDigest); logResults("Result Digest ", resultDigest); result = false; } correctDigest.clear(); resultDigest.clear(); /***************************************************************************************** * SHA256 empty *****************************************************************************************/ input.setReadOffset(0); sha256(&input, input.length(), &resultDigest); correctDigest.writeHex("e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"); if(buffersMatch(correctDigest, resultDigest)) Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed SHA256 empty"); else { Log::add(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed SHA256 empty"); logResults("Correct Digest", correctDigest); logResults("Result Digest ", resultDigest); result = false; } correctDigest.clear(); resultDigest.clear(); /***************************************************************************************** * SHA256 digest empty *****************************************************************************************/ input.setReadOffset(0); Digest sha256EmptyDigest(SHA256); sha256EmptyDigest.writeStream(&input, input.length()); sha256EmptyDigest.getResult(&resultDigest); correctDigest.writeHex("e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"); if(buffersMatch(correctDigest, resultDigest)) Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed SHA256 digest empty"); else { Log::add(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed SHA256 digest empty"); logResults("Correct Digest", correctDigest); logResults("Result Digest ", resultDigest); result = false; } correctDigest.clear(); resultDigest.clear(); /***************************************************************************************** * SHA512 empty *****************************************************************************************/ input.setReadOffset(0); sha512(&input, input.length(), &resultDigest); correctDigest.writeHex("cf83e1357eefb8bdf1542850d66d8007d620e4050b5715dc83f4a921d36ce9ce47d0d13c5d85f2b0ff8318d2877eec2f63b931bd47417a81a538327af927da3e"); if(buffersMatch(correctDigest, resultDigest)) Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed SHA512 empty"); else { Log::add(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed SHA512 empty"); logResults("Correct Digest", correctDigest); logResults("Result Digest ", resultDigest); result = false; } correctDigest.clear(); resultDigest.clear(); /***************************************************************************************** * HMAC SHA256 digest empty *****************************************************************************************/ input.setReadOffset(0); HMACDigest hmacSHA256EmptyDigest(SHA256, &hmacKey); hmacSHA256EmptyDigest.writeStream(&input, input.length()); hmacSHA256EmptyDigest.getResult(&resultDigest); correctDigest.writeHex("b613679a0814d9ec772f95d778c35fc5ff1697c493715653c6c712144292c5ad"); if(buffersMatch(correctDigest, resultDigest)) Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed HMAC SHA256 digest empty"); else { Log::add(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed HMAC SHA256 digest empty"); logResults("Correct Digest", correctDigest); logResults("Result Digest ", resultDigest); result = false; } correctDigest.clear(); resultDigest.clear(); /***************************************************************************************** * SHA512 digest empty *****************************************************************************************/ input.setReadOffset(0); Digest sha512EmptyDigest(SHA512); sha512EmptyDigest.writeStream(&input, input.length()); sha512EmptyDigest.getResult(&resultDigest); correctDigest.writeHex("cf83e1357eefb8bdf1542850d66d8007d620e4050b5715dc83f4a921d36ce9ce47d0d13c5d85f2b0ff8318d2877eec2f63b931bd47417a81a538327af927da3e"); if(buffersMatch(correctDigest, resultDigest)) Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed SHA512 digest empty"); else { Log::add(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed SHA512 digest empty"); logResults("Correct Digest", correctDigest); logResults("Result Digest ", resultDigest); result = false; } correctDigest.clear(); resultDigest.clear(); /***************************************************************************************** * HMAC SHA512 digest empty *****************************************************************************************/ input.setReadOffset(0); HMACDigest hmacSHA512EmptyDigest(SHA512, &hmacKey); hmacSHA512EmptyDigest.writeStream(&input, input.length()); hmacSHA512EmptyDigest.getResult(&resultDigest); correctDigest.writeHex("b936cee86c9f87aa5d3c6f2e84cb5a4239a5fe50480a6ec66b70ab5b1f4ac6730c6c515421b327ec1d69402e53dfb49ad7381eb067b338fd7b0cb22247225d47"); if(buffersMatch(correctDigest, resultDigest)) Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed HMAC SHA512 digest empty"); else { Log::add(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed HMAC SHA512 digest empty"); logResults("Correct Digest", correctDigest); logResults("Result Digest ", resultDigest); result = false; } correctDigest.clear(); resultDigest.clear(); /****************************************************************************************** * Test febooti.com (All confirmed from outside sources) ******************************************************************************************/ input.clear(); input.writeString("Test vector from febooti.com"); /***************************************************************************************** * CRC32 febooti.com *****************************************************************************************/ input.setReadOffset(0); crc32(&input, input.length(), &resultDigest); correctDigest.writeHex("0c877f61"); if(buffersMatch(correctDigest, resultDigest)) Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed CRC32 febooti.com"); else { Log::add(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed CRC32 febooti.com"); logResults("Correct Digest", correctDigest); logResults("Result Digest ", resultDigest); result = false; } correctDigest.clear(); resultDigest.clear(); /***************************************************************************************** * CRC32 text febooti.com *****************************************************************************************/ unsigned int crc32Text = crc32("Test vector from febooti.com"); unsigned int crc32Result = Endian::convert(0x0c877f61, Endian::BIG); if(crc32Text != crc32Result) Log::addFormatted(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed CRC32 text febooti.com"); else { Log::addFormatted(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed CRC32 text febooti.com : 0x0c877f61 != 0x%08x", crc32Text); result = false; } /***************************************************************************************** * CRC32 binary febooti.com *****************************************************************************************/ unsigned int crc32Binary = crc32((uint8_t *)"Test vector from febooti.com", 28); if(crc32Binary != crc32Result) Log::addFormatted(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed CRC32 binary febooti.com"); else { Log::addFormatted(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed CRC32 binary febooti.com : 0x0c877f61 != 0x%08x", crc32Binary); result = false; } /***************************************************************************************** * MD5 febooti.com *****************************************************************************************/ input.setReadOffset(0); md5(&input, input.length(), &resultDigest); correctDigest.writeHex("500ab6613c6db7fbd30c62f5ff573d0f"); if(buffersMatch(correctDigest, resultDigest)) Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed MD5 febooti.com"); else { Log::add(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed MD5 febooti.com"); logResults("Correct Digest", correctDigest); logResults("Result Digest ", resultDigest); result = false; } correctDigest.clear(); resultDigest.clear(); /***************************************************************************************** * SHA1 febooti.com *****************************************************************************************/ input.setReadOffset(0); sha1(&input, input.length(), &resultDigest); correctDigest.writeHex("a7631795f6d59cd6d14ebd0058a6394a4b93d868"); if(buffersMatch(correctDigest, resultDigest)) Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed SHA1 febooti.com"); else { Log::add(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed SHA1 febooti.com"); logResults("Correct Digest", correctDigest); logResults("Result Digest ", resultDigest); result = false; } correctDigest.clear(); resultDigest.clear(); /***************************************************************************************** * RIPEMD160 febooti.com *****************************************************************************************/ input.setReadOffset(0); ripEMD160(&input, input.length(), &resultDigest); correctDigest.writeHex("4e1ff644ca9f6e86167ccb30ff27e0d84ceb2a61"); if(buffersMatch(correctDigest, resultDigest)) Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed RIPEMD160 febooti.com"); else { Log::add(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed RIPEMD160 febooti.com"); logResults("Correct Digest", correctDigest); logResults("Result Digest ", resultDigest); result = false; } correctDigest.clear(); resultDigest.clear(); /***************************************************************************************** * SHA256 febooti.com *****************************************************************************************/ input.setReadOffset(0); sha256(&input, input.length(), &resultDigest); correctDigest.writeHex("077b18fe29036ada4890bdec192186e10678597a67880290521df70df4bac9ab"); if(buffersMatch(correctDigest, resultDigest)) Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed SHA256 febooti.com"); else { Log::add(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed SHA256 febooti.com"); logResults("Correct Digest", correctDigest); logResults("Result Digest ", resultDigest); result = false; } correctDigest.clear(); resultDigest.clear(); /***************************************************************************************** * SHA512 febooti.com *****************************************************************************************/ input.setReadOffset(0); sha512(&input, input.length(), &resultDigest); correctDigest.writeHex("09fb898bc97319a243a63f6971747f8e102481fb8d5346c55cb44855adc2e0e98f304e552b0db1d4eeba8a5c8779f6a3010f0e1a2beb5b9547a13b6edca11e8a"); if(buffersMatch(correctDigest, resultDigest)) Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed SHA512 febooti.com"); else { Log::add(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed SHA512 febooti.com"); logResults("Correct Digest", correctDigest); logResults("Result Digest ", resultDigest); result = false; } correctDigest.clear(); resultDigest.clear(); /***************************************************************************************** * SHA512 digest febooti.com *****************************************************************************************/ input.setReadOffset(0); Digest sha512febootiDigest(SHA512); sha512febootiDigest.writeStream(&input, input.length()); sha512febootiDigest.getResult(&resultDigest); correctDigest.writeHex("09fb898bc97319a243a63f6971747f8e102481fb8d5346c55cb44855adc2e0e98f304e552b0db1d4eeba8a5c8779f6a3010f0e1a2beb5b9547a13b6edca11e8a"); if(buffersMatch(correctDigest, resultDigest)) Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed SHA512 digest febooti.com"); else { Log::add(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed SHA512 digest febooti.com"); logResults("Correct Digest", correctDigest); logResults("Result Digest ", resultDigest); result = false; } correctDigest.clear(); resultDigest.clear(); /****************************************************************************************** * Test quick brown fox (All confirmed from outside sources) ******************************************************************************************/ input.clear(); input.writeString("The quick brown fox jumps over the lazy dog"); /***************************************************************************************** * CRC32 quick brown fox *****************************************************************************************/ input.setReadOffset(0); crc32(&input, input.length(), &resultDigest); correctDigest.writeHex("414FA339"); if(buffersMatch(correctDigest, resultDigest)) Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed CRC32 quick brown fox"); else { Log::add(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed CRC32 quick brown fox"); logResults("Correct Digest", correctDigest); logResults("Result Digest ", resultDigest); result = false; } correctDigest.clear(); resultDigest.clear(); /***************************************************************************************** * MD5 quick brown fox *****************************************************************************************/ input.setReadOffset(0); md5(&input, input.length(), &resultDigest); correctDigest.writeHex("9e107d9d372bb6826bd81d3542a419d6"); if(buffersMatch(correctDigest, resultDigest)) Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed MD5 quick brown fox"); else { Log::add(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed MD5 quick brown fox"); logResults("Correct Digest", correctDigest); logResults("Result Digest ", resultDigest); result = false; } correctDigest.clear(); resultDigest.clear(); /***************************************************************************************** * SHA1 quick brown fox *****************************************************************************************/ input.setReadOffset(0); sha1(&input, input.length(), &resultDigest); correctDigest.writeHex("2fd4e1c67a2d28fced849ee1bb76e7391b93eb12"); if(buffersMatch(correctDigest, resultDigest)) Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed SHA1 quick brown fox"); else { Log::add(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed SHA1 quick brown fox"); logResults("Correct Digest", correctDigest); logResults("Result Digest ", resultDigest); result = false; } correctDigest.clear(); resultDigest.clear(); /***************************************************************************************** * RIPEMD160 quick brown fox *****************************************************************************************/ input.setReadOffset(0); ripEMD160(&input, input.length(), &resultDigest); correctDigest.writeHex("37f332f68db77bd9d7edd4969571ad671cf9dd3b"); if(buffersMatch(correctDigest, resultDigest)) Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed RIPEMD160 quick brown fox"); else { Log::add(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed RIPEMD160 quick brown fox"); logResults("Correct Digest", correctDigest); logResults("Result Digest ", resultDigest); result = false; } correctDigest.clear(); resultDigest.clear(); /***************************************************************************************** * SHA256 quick brown fox *****************************************************************************************/ input.setReadOffset(0); sha256(&input, input.length(), &resultDigest); correctDigest.writeHex("d7a8fbb307d7809469ca9abcb0082e4f8d5651e46d3cdb762d02d0bf37c9e592"); if(buffersMatch(correctDigest, resultDigest)) Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed SHA256 quick brown fox"); else { Log::add(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed SHA256 quick brown fox"); logResults("Correct Digest", correctDigest); logResults("Result Digest ", resultDigest); result = false; } correctDigest.clear(); resultDigest.clear(); /***************************************************************************************** * HMAC SHA256 digest quick brown fox *****************************************************************************************/ input.setReadOffset(0); hmacKey.clear(); hmacKey.writeString("key"); HMACDigest hmacSHA256QBFDigest(SHA256, &hmacKey); hmacSHA256QBFDigest.writeStream(&input, input.length()); hmacSHA256QBFDigest.getResult(&resultDigest); correctDigest.writeHex("f7bc83f430538424b13298e6aa6fb143ef4d59a14946175997479dbc2d1a3cd8"); if(buffersMatch(correctDigest, resultDigest)) Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed HMAC SHA256 digest quick brown fox"); else { Log::add(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed HMAC SHA256 digest quick brown fox"); logResults("Correct Digest", correctDigest); logResults("Result Digest ", resultDigest); result = false; } correctDigest.clear(); resultDigest.clear(); /***************************************************************************************** * SHA512 quick brown fox *****************************************************************************************/ input.setReadOffset(0); sha512(&input, input.length(), &resultDigest); correctDigest.writeHex("07e547d9586f6a73f73fbac0435ed76951218fb7d0c8d788a309d785436bbb642e93a252a954f23912547d1e8a3b5ed6e1bfd7097821233fa0538f3db854fee6"); if(buffersMatch(correctDigest, resultDigest)) Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed SHA512 quick brown fox"); else { Log::add(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed SHA512 quick brown fox"); logResults("Correct Digest", correctDigest); logResults("Result Digest ", resultDigest); result = false; } correctDigest.clear(); resultDigest.clear(); /***************************************************************************************** * HMAC SHA512 digest quick brown fox *****************************************************************************************/ input.setReadOffset(0); hmacKey.clear(); hmacKey.writeString("key"); HMACDigest hmacSHA512QBFDigest(SHA512, &hmacKey); hmacSHA512QBFDigest.writeStream(&input, input.length()); hmacSHA512QBFDigest.getResult(&resultDigest); correctDigest.writeHex("b42af09057bac1e2d41708e48a902e09b5ff7f12ab428a4fe86653c73dd248fb82f948a549f7b791a5b41915ee4d1ec3935357e4e2317250d0372afa2ebeeb3a"); if(buffersMatch(correctDigest, resultDigest)) Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed HMAC SHA512 digest quick brown fox"); else { Log::add(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed HMAC SHA512 digest quick brown fox"); logResults("Correct Digest", correctDigest); logResults("Result Digest ", resultDigest); result = false; } correctDigest.clear(); resultDigest.clear(); /****************************************************************************************** * Test random data 1024 (All confirmed from outside sources) ******************************************************************************************/ input.clear(); input.writeHex("9cd248ed860b10bbc7cd5f0ef18f81291a90307c91296dc67d3a1759f02e2a34db020eb9c1f401c1"); input.writeHex("1820349dc9401246bab85810989136420a49830fb96a28e22247ec1073536862e6c2ce82adb93b1d"); input.writeHex("b3193a938dfefe8db8aef7eefb784e6af35191b7bf79dd96da777d7b2423fd49c255839232934344"); input.writeHex("41c94a6e2aa84e926a40ff9e640e224d0241a89565feb539791b2dcb31185b3ce463d638c99db0ed"); input.writeHex("e615dded590af0c89e093d0db3637aac61cd052c776409d992ddfc0249221121909bea8085871db2"); input.writeHex("a00011dc46d159b5ce630efff43117e379d7bb105142f4ef6e3af41ff0284624d16987b7ee6187e7"); input.writeHex("3df4761d2710414f216310b8193c530568ce423b76cc0342ad0ed86a3e7c15530c54ab4022ebaeed"); input.writeHex("df4e7996fec005e2d62b3ec1097af9b29443d45531399490cd763a78d58682fcf3bb483aa7448a44"); input.writeHex("9ac089cf695a9285954751f4c139904d10512c3e1adb00de962f4912f5fd160ade61c7e8ba45c5b9"); input.writeHex("4a763c943bf30249026f1c9eaf9be10f3f47ac2f001f633f5df3774bbcbc6cb85738a0d74778a07e"); input.writeHex("736adfd769c99509d2aad922d49b6b1c67fe886578e95988961e20c64ed6b7e4e080bbda3ce24ce6"); input.writeHex("741c51cacf401cc8b373ed6170d7b70a033f553eaef18d94065f06699d6bcd0bf5d845e09fd364e3"); input.writeHex("98e96d3ed54f78dc5d6200560001a3c0f721ccba58eaf9fde2760e937b820e0c41c161530d1f6b25"); input.writeHex("6b30463fd1dfe3e9d293afd5f278bf21e2b8bfc8860f7c86f4575cd7a922e4d9dbb8857815ede9a7"); input.writeHex("628af97c7ecadf59d385de8f2a3b3d114344fd9429f15a4aabe42c3934347bc039121dd666c6cef7"); input.writeHex("a81822889f394b82458f4016ed947fb86d8ef15b40d2a36b751f983339eeb7d4880554c5feebf6a6"); input.writeHex("59467f9716afc92ad05b41aab06e958f5874d431c836419ed2c595282c6804c600e97ce3929380d9"); input.writeHex("7f2687cc210890f95b3cf428ed66cb4e853505ba380bad5bda6c89b835c711a980ea946279051ea8"); input.writeHex("d12d002a52e40b0b162e7ff1464a9474450980ff3354a04522dc869905573ee0418adbe5938e87f2"); input.writeHex("0c3761960bf64c21de39ff305420a2127de03afdc5d117489271671219ccd538c0944ecd9ea869dc"); input.writeHex("135246b03b5ac5474b8d7c1741f68bbe616048c53ebc49814c757435a0f82c48bee85c339bbfb134"); input.writeHex("d4b64f561ca82ca1413eef619966d1e34bffb2771d069f795682e9559991d6239713fca03975d8fd"); input.writeHex("e0c2fd4cfe37daf274a3298fdfb9637191524505aa608573b819b0271b97a76328130c0ad8b60d3d"); input.writeHex("e53272e3e3b49760bfd3d20e5fc57bc5baa4b070c91f4eedd5e398405ac47a4bfa307747449ce0ad"); input.writeHex("7b9e9e6e1cc3b4bdef0be7b773af02b590626c92e3a85e97e0726ac1f7061e149c550a8d1b17360d"); input.writeHex("b22d56251b4fb0a6bb40595d1001d87d799d8544fdc54dfc"); /***************************************************************************************** * CRC32 random data 1024 *****************************************************************************************/ input.setReadOffset(0); crc32(&input, input.length(), &resultDigest); correctDigest.writeHex("1f483b3f"); if(buffersMatch(correctDigest, resultDigest)) Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed CRC32 random data 1024"); else { Log::add(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed CRC32 random data 1024"); logResults("Correct Digest", correctDigest); logResults("Result Digest ", resultDigest); result = false; } correctDigest.clear(); resultDigest.clear(); /***************************************************************************************** * CRC32 digest random data 1024 *****************************************************************************************/ input.setReadOffset(0); Digest crc32Digest(CRC32); crc32Digest.writeStream(&input, input.length()); crc32Digest.getResult(&resultDigest); correctDigest.writeHex("1f483b3f"); if(buffersMatch(correctDigest, resultDigest)) Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed CRC32 digest random data 1024"); else { Log::add(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed CRC32 digest random data 1024"); logResults("Correct Digest", correctDigest); logResults("Result Digest ", resultDigest); result = false; } correctDigest.clear(); resultDigest.clear(); /***************************************************************************************** * MD5 random data 1024 *****************************************************************************************/ input.setReadOffset(0); md5(&input, input.length(), &resultDigest); correctDigest.writeHex("6950a08814ee1e774314c28bce8707b0"); if(buffersMatch(correctDigest, resultDigest)) Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed MD5 random data 1024"); else { Log::add(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed MD5 random data 1024"); logResults("Correct Digest", correctDigest); logResults("Result Digest ", resultDigest); result = false; } correctDigest.clear(); resultDigest.clear(); /***************************************************************************************** * SHA1 random data 1024 *****************************************************************************************/ input.setReadOffset(0); sha1(&input, input.length(), &resultDigest); correctDigest.writeHex("2F7A0D349F1B6ABD7354965E94800BDC3D6463AC"); if(buffersMatch(correctDigest, resultDigest)) Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed SHA1 random data 1024"); else { Log::add(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed SHA1 random data 1024"); logResults("Correct Digest", correctDigest); logResults("Result Digest ", resultDigest); result = false; } correctDigest.clear(); resultDigest.clear(); /***************************************************************************************** * SHA1 digest random data 1024 *****************************************************************************************/ input.setReadOffset(0); Digest sha1RandomDigest(SHA1); sha1RandomDigest.writeStream(&input, input.length()); sha1RandomDigest.getResult(&resultDigest); correctDigest.writeHex("2F7A0D349F1B6ABD7354965E94800BDC3D6463AC"); if(buffersMatch(correctDigest, resultDigest)) Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed SHA1 digest random data 1024"); else { Log::add(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed SHA1 digest random data 1024"); logResults("Correct Digest", correctDigest); logResults("Result Digest ", resultDigest); result = false; } correctDigest.clear(); resultDigest.clear(); /***************************************************************************************** * RIPEMD160 random data 1024 *****************************************************************************************/ input.setReadOffset(0); ripEMD160(&input, input.length(), &resultDigest); correctDigest.writeHex("0dae1c4a362242d2ffa49c26204ed5ac2f88c454"); if(buffersMatch(correctDigest, resultDigest)) Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed RIPEMD160 random data 1024"); else { Log::add(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed RIPEMD160 random data 1024"); logResults("Correct Digest", correctDigest); logResults("Result Digest ", resultDigest); result = false; } correctDigest.clear(); resultDigest.clear(); /***************************************************************************************** * RIPEMD160 digest random data 1024 *****************************************************************************************/ input.setReadOffset(0); Digest ripemd160Digest(RIPEMD160); ripemd160Digest.writeStream(&input, input.length()); ripemd160Digest.getResult(&resultDigest); correctDigest.writeHex("0dae1c4a362242d2ffa49c26204ed5ac2f88c454"); if(buffersMatch(correctDigest, resultDigest)) Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed RIPEMD160 digest random data 1024"); else { Log::add(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed RIPEMD160 digest random data 1024"); logResults("Correct Digest", correctDigest); logResults("Result Digest ", resultDigest); result = false; } correctDigest.clear(); resultDigest.clear(); /***************************************************************************************** * SHA256 random data 1024 *****************************************************************************************/ input.setReadOffset(0); sha256(&input, input.length(), &resultDigest); correctDigest.writeHex("2baef0b3638abc90b17f2895e3cb24b6bbe7ff6ba7c291345102ea4eec785730"); if(buffersMatch(correctDigest, resultDigest)) Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed SHA256 random data 1024"); else { Log::add(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed SHA256 random data 1024"); logResults("Correct Digest", correctDigest); logResults("Result Digest ", resultDigest); result = false; } correctDigest.clear(); resultDigest.clear(); /***************************************************************************************** * SHA256 digest random data 1024 *****************************************************************************************/ input.setReadOffset(0); Digest sha256Digest(SHA256); sha256Digest.writeStream(&input, input.length()); sha256Digest.getResult(&resultDigest); correctDigest.writeHex("2baef0b3638abc90b17f2895e3cb24b6bbe7ff6ba7c291345102ea4eec785730"); if(buffersMatch(correctDigest, resultDigest)) Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed SHA256 digest random data 1024"); else { Log::add(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed SHA256 digest random data 1024"); logResults("Correct Digest", correctDigest); logResults("Result Digest ", resultDigest); result = false; } correctDigest.clear(); resultDigest.clear(); /***************************************************************************************** * SHA512 random data 1024 *****************************************************************************************/ input.setReadOffset(0); sha512(&input, input.length(), &resultDigest); correctDigest.writeHex("8c63c499586f24f3209acad229b043f02eddfc19ec04d41c2f0aeee60b3a95e87297b2de4cfaaaca9a6691bbc5f63a0453fa98b02742da313fa9075ef633a94c"); if(buffersMatch(correctDigest, resultDigest)) Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed SHA512 random data 1024"); else { Log::add(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed SHA512 random data 1024"); logResults("Correct Digest", correctDigest); logResults("Result Digest ", resultDigest); result = false; } correctDigest.clear(); resultDigest.clear(); /***************************************************************************************** * HMAC SHA512 RFC4231 Text Case 4 *****************************************************************************************/ input.clear(); input.writeHex("cdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcdcd"); hmacKey.clear(); hmacKey.writeHex("0102030405060708090a0b0c0d0e0f10111213141516171819"); HMACDigest hmacSHA512RFC4231Test4Digest(SHA512); hmacSHA512RFC4231Test4Digest.initialize(&hmacKey); hmacSHA512RFC4231Test4Digest.writeStream(&input, input.length()); hmacSHA512RFC4231Test4Digest.getResult(&resultDigest); correctDigest.writeHex("b0ba465637458c6990e5a8c5f61d4af7e576d97ff94b872de76f8050361ee3dba91ca5c11aa25eb4d679275cc5788063a5f19741120c4f2de2adebeb10a298dd"); if(buffersMatch(correctDigest, resultDigest)) Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed HMAC SHA512 RFC4231 Test Case 4"); else { Log::add(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed HMAC SHA512 RFC4231 Test Case 4"); logResults("Correct Digest", correctDigest); logResults("Result Digest ", resultDigest); result = false; } correctDigest.clear(); resultDigest.clear(); /***************************************************************************************** * HMAC SHA512 RFC4231 Text Case 7 *****************************************************************************************/ input.clear(); input.writeHex("5468697320697320612074657374207573696e672061206c6172676572207468616e20626c6f636b2d73697a65206b657920616e642061206c6172676572207468616e20626c6f636b2d73697a6520646174612e20546865206b6579206e6565647320746f20626520686173686564206265666f7265206265696e6720757365642062792074686520484d414320616c676f726974686d2e"); hmacKey.clear(); hmacKey.writeHex("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"); HMACDigest hmacSHA512RFC4231Test7Digest(SHA512); hmacSHA512RFC4231Test7Digest.initialize(&hmacKey); hmacSHA512RFC4231Test7Digest.writeStream(&input, input.length()); hmacSHA512RFC4231Test7Digest.getResult(&resultDigest); correctDigest.writeHex("e37b6a775dc87dbaa4dfa9f96e5e3ffddebd71f8867289865df5a32d20cdc944b6022cac3c4982b10d5eeb55c3e4de15134676fb6de0446065c97440fa8c6a58"); if(buffersMatch(correctDigest, resultDigest)) Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed HMAC SHA512 RFC4231 Test Case 7"); else { Log::add(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed HMAC SHA512 RFC4231 Test Case 7"); logResults("Correct Digest", correctDigest); logResults("Result Digest ", resultDigest); result = false; } correctDigest.clear(); resultDigest.clear(); /****************************************************************************************** * Test 56 letters (All confirmed from outside sources) ******************************************************************************************/ input.clear(); input.writeString("abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq"); /***************************************************************************************** * RIPEMD160 56 letters *****************************************************************************************/ input.setReadOffset(0); ripEMD160(&input, input.length(), &resultDigest); correctDigest.writeHex("12a053384a9c0c88e405a06c27dcf49ada62eb2b"); if(buffersMatch(correctDigest, resultDigest)) Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed RIPEMD160 56 letters"); else { Log::add(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed RIPEMD160 56 letters"); logResults("Correct Digest", correctDigest); logResults("Result Digest ", resultDigest); result = false; } correctDigest.clear(); resultDigest.clear(); /****************************************************************************************** * Test 8 times "1234567890" (All confirmed from outside sources) ******************************************************************************************/ input.clear(); input.writeString("12345678901234567890123456789012345678901234567890123456789012345678901234567890"); /***************************************************************************************** * RIPEMD160 8 times "1234567890" *****************************************************************************************/ input.setReadOffset(0); ripEMD160(&input, input.length(), &resultDigest); correctDigest.writeHex("9b752e45573d4b39f4dbd3323cab82bf63326bfb"); if(buffersMatch(correctDigest, resultDigest)) Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed RIPEMD160 8 times \"1234567890\""); else { Log::add(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed RIPEMD160 8 times \"1234567890\""); logResults("Correct Digest", correctDigest); logResults("Result Digest ", resultDigest); result = false; } correctDigest.clear(); resultDigest.clear(); /****************************************************************************************** * Test million a (All confirmed from outside sources) ******************************************************************************************/ input.clear(); for(unsigned int i=0;i<1000000;i++) input.writeByte('a'); /***************************************************************************************** * RIPEMD160 million a *****************************************************************************************/ input.setReadOffset(0); ripEMD160(&input, input.length(), &resultDigest); correctDigest.writeHex("52783243c1697bdbe16d37f97f68f08325dc1528"); if(buffersMatch(correctDigest, resultDigest)) Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed RIPEMD160 million a"); else { Log::add(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed RIPEMD160 million a"); logResults("Correct Digest", correctDigest); logResults("Result Digest ", resultDigest); result = false; } correctDigest.clear(); resultDigest.clear(); /****************************************************************************************** * Test random data 150 (All confirmed from outside sources) ******************************************************************************************/ input.clear(); input.writeHex("182d86ed47df1c1673558e3d1ed08dcc7de3a906615589084f6316e71cabd18e7c37451d514d9ede653b03d047345a522ef1c55f27ac8bff3564635116855d862bac06d21f8abb3026746b5c74dd46e9679bd30137bf6b143b67249931ff3f0a3f50426a4479871d15603aa4151ef4b9321762553df9946f5bc194ac4a44e94205d8b0854f1722ea6915770f03bc598c306cabf23878"); /***************************************************************************************** * RIPEMD160 random data 150 *****************************************************************************************/ input.setReadOffset(0); ripEMD160(&input, input.length(), &resultDigest); correctDigest.writeHex("de4c02fe629897e3a2658c042f260a96ccfccac9"); if(buffersMatch(correctDigest, resultDigest)) Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed RIPEMD160 random data 150"); else { Log::add(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed RIPEMD160 random data 150"); logResults("Correct Digest", correctDigest); logResults("Result Digest ", resultDigest); result = false; } correctDigest.clear(); resultDigest.clear(); /****************************************************************************************** * Test hello ******************************************************************************************/ input.clear(); input.writeString("hello"); /***************************************************************************************** * SHA256_SHA256 hello *****************************************************************************************/ input.setReadOffset(0); Digest doubleSHA256(SHA256_SHA256); doubleSHA256.writeStream(&input, input.length()); doubleSHA256.getResult(&resultDigest); correctDigest.writeHex("9595c9df90075148eb06860365df33584b75bff782a510c6cd4883a419833d50"); if(buffersMatch(correctDigest, resultDigest)) Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed SHA256_SHA256 hello"); else { Log::add(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed SHA256_SHA256 hello"); logResults("Correct Digest", correctDigest); logResults("Result Digest ", resultDigest); result = false; } correctDigest.clear(); resultDigest.clear(); /***************************************************************************************** * SHA256_RIPEMD160 hello *****************************************************************************************/ input.setReadOffset(0); Digest sha256RIPEMD160(SHA256_RIPEMD160); sha256RIPEMD160.writeStream(&input, input.length()); sha256RIPEMD160.getResult(&resultDigest); correctDigest.writeHex("b6a9c8c230722b7c748331a8b450f05566dc7d0f"); if(buffersMatch(correctDigest, resultDigest)) Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed SHA256_RIPEMD160 hello"); else { Log::add(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed SHA256_RIPEMD160 hello"); logResults("Correct Digest", correctDigest); logResults("Result Digest ", resultDigest); result = false; } correctDigest.clear(); resultDigest.clear(); /***************************************************************************************** * SipHash24 *****************************************************************************************/ uint8_t sipHash24Vectors[64][8] = { { 0x31, 0x0e, 0x0e, 0xdd, 0x47, 0xdb, 0x6f, 0x72, }, { 0xfd, 0x67, 0xdc, 0x93, 0xc5, 0x39, 0xf8, 0x74, }, { 0x5a, 0x4f, 0xa9, 0xd9, 0x09, 0x80, 0x6c, 0x0d, }, { 0x2d, 0x7e, 0xfb, 0xd7, 0x96, 0x66, 0x67, 0x85, }, { 0xb7, 0x87, 0x71, 0x27, 0xe0, 0x94, 0x27, 0xcf, }, { 0x8d, 0xa6, 0x99, 0xcd, 0x64, 0x55, 0x76, 0x18, }, { 0xce, 0xe3, 0xfe, 0x58, 0x6e, 0x46, 0xc9, 0xcb, }, { 0x37, 0xd1, 0x01, 0x8b, 0xf5, 0x00, 0x02, 0xab, }, { 0x62, 0x24, 0x93, 0x9a, 0x79, 0xf5, 0xf5, 0x93, }, { 0xb0, 0xe4, 0xa9, 0x0b, 0xdf, 0x82, 0x00, 0x9e, }, { 0xf3, 0xb9, 0xdd, 0x94, 0xc5, 0xbb, 0x5d, 0x7a, }, { 0xa7, 0xad, 0x6b, 0x22, 0x46, 0x2f, 0xb3, 0xf4, }, { 0xfb, 0xe5, 0x0e, 0x86, 0xbc, 0x8f, 0x1e, 0x75, }, { 0x90, 0x3d, 0x84, 0xc0, 0x27, 0x56, 0xea, 0x14, }, { 0xee, 0xf2, 0x7a, 0x8e, 0x90, 0xca, 0x23, 0xf7, }, { 0xe5, 0x45, 0xbe, 0x49, 0x61, 0xca, 0x29, 0xa1, }, { 0xdb, 0x9b, 0xc2, 0x57, 0x7f, 0xcc, 0x2a, 0x3f, }, { 0x94, 0x47, 0xbe, 0x2c, 0xf5, 0xe9, 0x9a, 0x69, }, { 0x9c, 0xd3, 0x8d, 0x96, 0xf0, 0xb3, 0xc1, 0x4b, }, { 0xbd, 0x61, 0x79, 0xa7, 0x1d, 0xc9, 0x6d, 0xbb, }, { 0x98, 0xee, 0xa2, 0x1a, 0xf2, 0x5c, 0xd6, 0xbe, }, { 0xc7, 0x67, 0x3b, 0x2e, 0xb0, 0xcb, 0xf2, 0xd0, }, { 0x88, 0x3e, 0xa3, 0xe3, 0x95, 0x67, 0x53, 0x93, }, { 0xc8, 0xce, 0x5c, 0xcd, 0x8c, 0x03, 0x0c, 0xa8, }, { 0x94, 0xaf, 0x49, 0xf6, 0xc6, 0x50, 0xad, 0xb8, }, { 0xea, 0xb8, 0x85, 0x8a, 0xde, 0x92, 0xe1, 0xbc, }, { 0xf3, 0x15, 0xbb, 0x5b, 0xb8, 0x35, 0xd8, 0x17, }, { 0xad, 0xcf, 0x6b, 0x07, 0x63, 0x61, 0x2e, 0x2f, }, { 0xa5, 0xc9, 0x1d, 0xa7, 0xac, 0xaa, 0x4d, 0xde, }, { 0x71, 0x65, 0x95, 0x87, 0x66, 0x50, 0xa2, 0xa6, }, { 0x28, 0xef, 0x49, 0x5c, 0x53, 0xa3, 0x87, 0xad, }, { 0x42, 0xc3, 0x41, 0xd8, 0xfa, 0x92, 0xd8, 0x32, }, { 0xce, 0x7c, 0xf2, 0x72, 0x2f, 0x51, 0x27, 0x71, }, { 0xe3, 0x78, 0x59, 0xf9, 0x46, 0x23, 0xf3, 0xa7, }, { 0x38, 0x12, 0x05, 0xbb, 0x1a, 0xb0, 0xe0, 0x12, }, { 0xae, 0x97, 0xa1, 0x0f, 0xd4, 0x34, 0xe0, 0x15, }, { 0xb4, 0xa3, 0x15, 0x08, 0xbe, 0xff, 0x4d, 0x31, }, { 0x81, 0x39, 0x62, 0x29, 0xf0, 0x90, 0x79, 0x02, }, { 0x4d, 0x0c, 0xf4, 0x9e, 0xe5, 0xd4, 0xdc, 0xca, }, { 0x5c, 0x73, 0x33, 0x6a, 0x76, 0xd8, 0xbf, 0x9a, }, { 0xd0, 0xa7, 0x04, 0x53, 0x6b, 0xa9, 0x3e, 0x0e, }, { 0x92, 0x59, 0x58, 0xfc, 0xd6, 0x42, 0x0c, 0xad, }, { 0xa9, 0x15, 0xc2, 0x9b, 0xc8, 0x06, 0x73, 0x18, }, { 0x95, 0x2b, 0x79, 0xf3, 0xbc, 0x0a, 0xa6, 0xd4, }, { 0xf2, 0x1d, 0xf2, 0xe4, 0x1d, 0x45, 0x35, 0xf9, }, { 0x87, 0x57, 0x75, 0x19, 0x04, 0x8f, 0x53, 0xa9, }, { 0x10, 0xa5, 0x6c, 0xf5, 0xdf, 0xcd, 0x9a, 0xdb, }, { 0xeb, 0x75, 0x09, 0x5c, 0xcd, 0x98, 0x6c, 0xd0, }, { 0x51, 0xa9, 0xcb, 0x9e, 0xcb, 0xa3, 0x12, 0xe6, }, { 0x96, 0xaf, 0xad, 0xfc, 0x2c, 0xe6, 0x66, 0xc7, }, { 0x72, 0xfe, 0x52, 0x97, 0x5a, 0x43, 0x64, 0xee, }, { 0x5a, 0x16, 0x45, 0xb2, 0x76, 0xd5, 0x92, 0xa1, }, { 0xb2, 0x74, 0xcb, 0x8e, 0xbf, 0x87, 0x87, 0x0a, }, { 0x6f, 0x9b, 0xb4, 0x20, 0x3d, 0xe7, 0xb3, 0x81, }, { 0xea, 0xec, 0xb2, 0xa3, 0x0b, 0x22, 0xa8, 0x7f, }, { 0x99, 0x24, 0xa4, 0x3c, 0xc1, 0x31, 0x57, 0x24, }, { 0xbd, 0x83, 0x8d, 0x3a, 0xaf, 0xbf, 0x8d, 0xb7, }, { 0x0b, 0x1a, 0x2a, 0x32, 0x65, 0xd5, 0x1a, 0xea, }, { 0x13, 0x50, 0x79, 0xa3, 0x23, 0x1c, 0xe6, 0x60, }, { 0x93, 0x2b, 0x28, 0x46, 0xe4, 0xd7, 0x06, 0x66, }, { 0xe1, 0x91, 0x5f, 0x5c, 0xb1, 0xec, 0xa4, 0x6c, }, { 0xf3, 0x25, 0x96, 0x5c, 0xa1, 0x6d, 0x62, 0x9f, }, { 0x57, 0x5f, 0xf2, 0x8e, 0x60, 0x38, 0x1b, 0xe5, }, { 0x72, 0x45, 0x06, 0xeb, 0x4c, 0x32, 0x8a, 0x95, } }; uint64_t key0 = 0x0706050403020100; uint64_t key1 = 0x0f0e0d0c0b0a0908; //Log::addFormatted(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "SipHash-2-4 : Key0 0x%08x%08x, Key1 0x%08x%08x", // key0 >> 32, key0 & 0xffffffff, key1 >> 32, key1 & 0xffffffff); uint64_t sipResult; uint64_t check; uint8_t *byte; uint8_t sipHash24Data[64]; bool sipSuccess = true; for(unsigned int i=0;i<64;++i) { sipHash24Data[i] = i; sipResult = sipHash24(sipHash24Data, i, key0, key1); check = 0; byte = sipHash24Vectors[i]; for(unsigned int j=0;j<8;++j) check |= (uint64_t)*byte++ << (j * 8); if(sipResult != check) { Log::addFormatted(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed SipHash24 %d 0x%08x%08x == 0x%08x%08x", i, sipResult >> 32, sipResult & 0xffffffff, check >> 32, check & 0xffffffff); result = false; sipSuccess = false; } } if(sipSuccess) Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed SipHash24 test set"); /***************************************************************************************** * MurMur3 empty 0 *****************************************************************************************/ input.clear(); Digest murmur3Digest(MURMUR3); murmur3Digest.initialize(0); murmur3Digest.writeStream(&input, input.length()); murmur3Digest.getResult(&resultDigest); correctDigest.writeUnsignedInt(0x00000000); if(buffersMatch(correctDigest, resultDigest)) Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed MURMUR3 empty 0"); else { Log::add(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed MURMUR3 empty 0"); logResults("Correct Digest", correctDigest); logResults("Result Digest ", resultDigest); result = false; } correctDigest.clear(); resultDigest.clear(); /***************************************************************************************** * MurMur3 empty 1 *****************************************************************************************/ input.clear(); murmur3Digest.initialize(1); murmur3Digest.writeStream(&input, input.length()); murmur3Digest.getResult(&resultDigest); correctDigest.writeUnsignedInt(0x514E28B7); if(buffersMatch(correctDigest, resultDigest)) Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed MURMUR3 empty 1"); else { Log::add(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed MURMUR3 empty 1"); logResults("Correct Digest", correctDigest); logResults("Result Digest ", resultDigest); result = false; } correctDigest.clear(); resultDigest.clear(); /***************************************************************************************** * MurMur3 empty ffffffff *****************************************************************************************/ input.clear(); murmur3Digest.initialize(0xffffffff); murmur3Digest.writeStream(&input, input.length()); murmur3Digest.getResult(&resultDigest); correctDigest.writeUnsignedInt(0x81F16F39); if(buffersMatch(correctDigest, resultDigest)) Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed MURMUR3 empty ffffffff"); else { Log::add(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed MURMUR3 empty ffffffff"); logResults("Correct Digest", correctDigest); logResults("Result Digest ", resultDigest); result = false; } correctDigest.clear(); resultDigest.clear(); /***************************************************************************************** * MurMur3 ffffffff 0 *****************************************************************************************/ input.clear(); input.writeUnsignedInt(0xffffffff); murmur3Digest.initialize(0); murmur3Digest.writeStream(&input, input.length()); murmur3Digest.getResult(&resultDigest); correctDigest.writeUnsignedInt(0x76293B50); if(buffersMatch(correctDigest, resultDigest)) Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed MURMUR3 ffffffff 0"); else { Log::add(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed MURMUR3 ffffffff 0"); logResults("Correct Digest", correctDigest); logResults("Result Digest ", resultDigest); result = false; } correctDigest.clear(); resultDigest.clear(); /***************************************************************************************** * MurMur3 87654321 0 *****************************************************************************************/ input.clear(); input.writeUnsignedInt(0x87654321); murmur3Digest.initialize(0); murmur3Digest.writeStream(&input, input.length()); murmur3Digest.getResult(&resultDigest); correctDigest.writeUnsignedInt(0xF55B516B); if(buffersMatch(correctDigest, resultDigest)) Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed MURMUR3 87654321 0"); else { Log::add(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed MURMUR3 87654321 0"); logResults("Correct Digest", correctDigest); logResults("Result Digest ", resultDigest); result = false; } correctDigest.clear(); resultDigest.clear(); /***************************************************************************************** * MurMur3 87654321 5082EDEE *****************************************************************************************/ input.clear(); input.writeUnsignedInt(0x87654321); murmur3Digest.initialize(0x5082EDEE); murmur3Digest.writeStream(&input, input.length()); murmur3Digest.getResult(&resultDigest); correctDigest.writeUnsignedInt(0x2362F9DE); if(buffersMatch(correctDigest, resultDigest)) Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed MURMUR3 87654321 5082EDEE"); else { Log::add(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed MURMUR3 87654321 5082EDEE"); logResults("Correct Digest", correctDigest); logResults("Result Digest ", resultDigest); result = false; } correctDigest.clear(); resultDigest.clear(); /***************************************************************************************** * MurMur3 214365 0 *****************************************************************************************/ input.clear(); input.writeHex("214365"); murmur3Digest.initialize(0); murmur3Digest.writeStream(&input, input.length()); murmur3Digest.getResult(&resultDigest); correctDigest.writeUnsignedInt(0x7E4A8634); if(buffersMatch(correctDigest, resultDigest)) Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed MURMUR3 214365 0"); else { Log::add(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed MURMUR3 214365 0"); logResults("Correct Digest", correctDigest); logResults("Result Digest ", resultDigest); result = false; } correctDigest.clear(); resultDigest.clear(); /***************************************************************************************** * MurMur3 2143 0 *****************************************************************************************/ input.clear(); input.writeHex("2143"); murmur3Digest.initialize(0); murmur3Digest.writeStream(&input, input.length()); murmur3Digest.getResult(&resultDigest); correctDigest.writeUnsignedInt(0xA0F7B07A); if(buffersMatch(correctDigest, resultDigest)) Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed MURMUR3 2143 0"); else { Log::add(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed MURMUR3 2143 0"); logResults("Correct Digest", correctDigest); logResults("Result Digest ", resultDigest); result = false; } correctDigest.clear(); resultDigest.clear(); /***************************************************************************************** * MurMur3 21 0 *****************************************************************************************/ input.clear(); input.writeHex("21"); murmur3Digest.initialize(0); murmur3Digest.writeStream(&input, input.length()); murmur3Digest.getResult(&resultDigest); correctDigest.writeUnsignedInt(0x72661CF4); if(buffersMatch(correctDigest, resultDigest)) Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed MURMUR3 21 0"); else { Log::add(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed MURMUR3 21 0"); logResults("Correct Digest", correctDigest); logResults("Result Digest ", resultDigest); result = false; } correctDigest.clear(); resultDigest.clear(); /***************************************************************************************** * MurMur3 00000000 0 *****************************************************************************************/ input.clear(); input.writeHex("00000000"); murmur3Digest.initialize(0); murmur3Digest.writeStream(&input, input.length()); murmur3Digest.getResult(&resultDigest); correctDigest.writeUnsignedInt(0x2362F9DE); if(buffersMatch(correctDigest, resultDigest)) Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed MURMUR3 00000000 0"); else { Log::add(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed MURMUR3 00000000 0"); logResults("Correct Digest", correctDigest); logResults("Result Digest ", resultDigest); result = false; } correctDigest.clear(); resultDigest.clear(); /***************************************************************************************** * MurMur3 000000 0 *****************************************************************************************/ input.clear(); input.writeHex("000000"); murmur3Digest.initialize(0); murmur3Digest.writeStream(&input, input.length()); murmur3Digest.getResult(&resultDigest); correctDigest.writeUnsignedInt(0x85F0B427); if(buffersMatch(correctDigest, resultDigest)) Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed MURMUR3 000000 0"); else { Log::add(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed MURMUR3 000000 0"); logResults("Correct Digest", correctDigest); logResults("Result Digest ", resultDigest); result = false; } correctDigest.clear(); resultDigest.clear(); /***************************************************************************************** * MurMur3 0000 0 *****************************************************************************************/ input.clear(); input.writeHex("0000"); murmur3Digest.initialize(0); murmur3Digest.writeStream(&input, input.length()); murmur3Digest.getResult(&resultDigest); correctDigest.writeUnsignedInt(0x30F4C306); if(buffersMatch(correctDigest, resultDigest)) Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed MURMUR3 0000 0"); else { Log::add(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed MURMUR3 0000 0"); logResults("Correct Digest", correctDigest); logResults("Result Digest ", resultDigest); result = false; } correctDigest.clear(); resultDigest.clear(); /***************************************************************************************** * MurMur3 00 0 *****************************************************************************************/ input.clear(); input.writeHex("00"); murmur3Digest.initialize(0); murmur3Digest.writeStream(&input, input.length()); murmur3Digest.getResult(&resultDigest); correctDigest.writeUnsignedInt(0x514E28B7); if(buffersMatch(correctDigest, resultDigest)) Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed MURMUR3 00 0"); else { Log::add(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed MURMUR3 00 0"); logResults("Correct Digest", correctDigest); logResults("Result Digest ", resultDigest); result = false; } correctDigest.clear(); resultDigest.clear(); /***************************************************************************************** * MurMur3 empty 0 direct *****************************************************************************************/ input.clear(); uint32_t murMur3Result = murMur3(input.begin(), input.length(), 0); uint32_t murMur3Correct = 0x00000000; if(murMur3Correct == murMur3Result) Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed MURMUR3 direct empty 0"); else { Log::add(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed MURMUR3 direct empty 0"); Log::addFormatted(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Correct : 0x%08x", murMur3Correct); Log::addFormatted(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Result : 0x%08x", murMur3Result); result = false; } correctDigest.clear(); resultDigest.clear(); /***************************************************************************************** * MurMur3 empty 1 direct *****************************************************************************************/ input.clear(); murMur3Result = murMur3(input.begin(), input.length(), 1); murMur3Correct = 0x514E28B7; if(murMur3Correct == murMur3Result) Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed MURMUR3 direct empty 1"); else { Log::add(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed MURMUR3 direct empty 1"); Log::addFormatted(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Correct : 0x%08x", murMur3Correct); Log::addFormatted(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Result : 0x%08x", murMur3Result); result = false; } correctDigest.clear(); resultDigest.clear(); /***************************************************************************************** * MurMur3 empty ffffffff direct *****************************************************************************************/ input.clear(); murMur3Result = murMur3(input.begin(), input.length(), 0xffffffff); murMur3Correct = 0x81F16F39; if(murMur3Correct == murMur3Result) Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed MURMUR3 direct empty ffffffff"); else { Log::add(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed MURMUR3 direct empty ffffffff"); Log::addFormatted(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Correct : 0x%08x", murMur3Correct); Log::addFormatted(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Result : 0x%08x", murMur3Result); result = false; } correctDigest.clear(); resultDigest.clear(); /***************************************************************************************** * MurMur3 ffffffff 0 direct *****************************************************************************************/ input.clear(); input.writeUnsignedInt(0xffffffff); murMur3Result = murMur3(input.begin(), input.length(), 0); murMur3Correct = 0x76293B50; if(murMur3Correct == murMur3Result) Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed MURMUR3 direct ffffffff 0"); else { Log::add(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed MURMUR3 direct ffffffff 0"); Log::addFormatted(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Correct : 0x%08x", murMur3Correct); Log::addFormatted(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Result : 0x%08x", murMur3Result); result = false; } correctDigest.clear(); resultDigest.clear(); /***************************************************************************************** * MurMur3 87654321 0 direct *****************************************************************************************/ input.clear(); input.writeUnsignedInt(0x87654321); murMur3Result = murMur3(input.begin(), input.length(), 0); murMur3Correct = 0xF55B516B; if(murMur3Correct == murMur3Result) Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed MURMUR3 direct 87654321 0"); else { Log::add(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed MURMUR3 direct 87654321 0"); Log::addFormatted(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Correct : 0x%08x", murMur3Correct); Log::addFormatted(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Result : 0x%08x", murMur3Result); result = false; } correctDigest.clear(); resultDigest.clear(); /***************************************************************************************** * MurMur3 87654321 5082EDEE direct *****************************************************************************************/ input.clear(); input.writeUnsignedInt(0x87654321); murMur3Result = murMur3(input.begin(), input.length(), 0x5082EDEE); murMur3Correct = 0x2362F9DE; if(murMur3Correct == murMur3Result) Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed MURMUR3 direct 87654321 5082EDEE"); else { Log::add(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed MURMUR3 direct 87654321 5082EDEE"); Log::addFormatted(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Correct : 0x%08x", murMur3Correct); Log::addFormatted(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Result : 0x%08x", murMur3Result); result = false; } correctDigest.clear(); resultDigest.clear(); /***************************************************************************************** * MurMur3 214365 0 direct *****************************************************************************************/ input.clear(); input.writeHex("214365"); murMur3Result = murMur3(input.begin(), input.length(), 0); murMur3Correct = 0x7E4A8634; if(murMur3Correct == murMur3Result) Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed MURMUR3 direct 214365 0"); else { Log::add(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed MURMUR3 direct 214365 0"); Log::addFormatted(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Correct : 0x%08x", murMur3Correct); Log::addFormatted(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Result : 0x%08x", murMur3Result); result = false; } correctDigest.clear(); resultDigest.clear(); /***************************************************************************************** * MurMur3 2143 0 direct *****************************************************************************************/ input.clear(); input.writeHex("2143"); murMur3Result = murMur3(input.begin(), input.length(), 0); murMur3Correct = 0xA0F7B07A; if(murMur3Correct == murMur3Result) Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed MURMUR3 direct 2143 0"); else { Log::add(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed MURMUR3 direct 2143 0"); Log::addFormatted(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Correct : 0x%08x", murMur3Correct); Log::addFormatted(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Result : 0x%08x", murMur3Result); result = false; } correctDigest.clear(); resultDigest.clear(); /***************************************************************************************** * MurMur3 21 0 direct *****************************************************************************************/ input.clear(); input.writeHex("21"); murMur3Result = murMur3(input.begin(), input.length(), 0); murMur3Correct = 0x72661CF4; if(murMur3Correct == murMur3Result) Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed MURMUR3 direct 21 0"); else { Log::add(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed MURMUR3 direct 21 0"); Log::addFormatted(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Correct : 0x%08x", murMur3Correct); Log::addFormatted(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Result : 0x%08x", murMur3Result); result = false; } correctDigest.clear(); resultDigest.clear(); /***************************************************************************************** * MurMur3 00000000 0 direct *****************************************************************************************/ input.clear(); input.writeHex("00000000"); murMur3Result = murMur3(input.begin(), input.length(), 0); murMur3Correct = 0x2362F9DE; if(murMur3Correct == murMur3Result) Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed MURMUR3 direct 00000000 0"); else { Log::add(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed MURMUR3 direct 00000000 0"); Log::addFormatted(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Correct : 0x%08x", murMur3Correct); Log::addFormatted(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Result : 0x%08x", murMur3Result); result = false; } correctDigest.clear(); resultDigest.clear(); /***************************************************************************************** * MurMur3 000000 0 direct *****************************************************************************************/ input.clear(); input.writeHex("000000"); murMur3Result = murMur3(input.begin(), input.length(), 0); murMur3Correct = 0x85F0B427; if(murMur3Correct == murMur3Result) Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed MURMUR3 direct 000000 0"); else { Log::add(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed MURMUR3 direct 000000 0"); Log::addFormatted(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Correct : 0x%08x", murMur3Correct); Log::addFormatted(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Result : 0x%08x", murMur3Result); result = false; } correctDigest.clear(); resultDigest.clear(); /***************************************************************************************** * MurMur3 0000 0 direct *****************************************************************************************/ input.clear(); input.writeHex("0000"); murMur3Result = murMur3(input.begin(), input.length(), 0); murMur3Correct = 0x30F4C306; if(murMur3Correct == murMur3Result) Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed MURMUR3 direct 0000 0"); else { Log::add(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed MURMUR3 direct 0000 0"); Log::addFormatted(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Correct : 0x%08x", murMur3Correct); Log::addFormatted(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Result : 0x%08x", murMur3Result); result = false; } correctDigest.clear(); resultDigest.clear(); /***************************************************************************************** * MurMur3 00 0 direct *****************************************************************************************/ input.clear(); input.writeHex("00"); murMur3Result = murMur3(input.begin(), input.length(), 0); murMur3Correct = 0x514E28B7; if(murMur3Correct == murMur3Result) Log::add(Log::INFO, NEXTCASH_DIGEST_LOG_NAME, "Passed MURMUR3 direct 00 0"); else { Log::add(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Failed MURMUR3 direct 00 0"); Log::addFormatted(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Correct : 0x%08x", murMur3Correct); Log::addFormatted(Log::ERROR, NEXTCASH_DIGEST_LOG_NAME, "Result : 0x%08x", murMur3Result); result = false; } correctDigest.clear(); resultDigest.clear(); return result; } }
42.182319
331
0.508833
nextcashtech
81c682b89e3d55da90e268bdaa9d5249951adc4b
814
cpp
C++
Source/DummyTransformationSceneNode.cpp
slater1/Irrlicht.NetCore
5f1584f9a0b8590eefbfcf361d62ff544fdeba57
[ "Zlib" ]
2
2020-05-19T04:49:01.000Z
2020-08-03T08:43:46.000Z
Source/DummyTransformationSceneNode.cpp
slater1/Irrlicht.Net
42fb8260871b24d30dbc2c968d13e78753b25aca
[ "Zlib" ]
null
null
null
Source/DummyTransformationSceneNode.cpp
slater1/Irrlicht.Net
42fb8260871b24d30dbc2c968d13e78753b25aca
[ "Zlib" ]
null
null
null
#include "stdafx.h" #include "DummyTransformationSceneNode.h" #include "SceneNode.h" using namespace irr; using namespace System; namespace Irrlicht { namespace Scene { DummyTransformationSceneNode^ DummyTransformationSceneNode::Wrap(scene::IDummyTransformationSceneNode* ref) { if (ref == nullptr) return nullptr; return gcnew DummyTransformationSceneNode(ref); } DummyTransformationSceneNode::DummyTransformationSceneNode(scene::IDummyTransformationSceneNode* ref) : SceneNode(ref) { LIME_ASSERT(ref != nullptr); m_DummyTransformationSceneNode = ref; } Matrix^ DummyTransformationSceneNode::RelativeTransformationMatrix::get() { return gcnew Matrix(&m_DummyTransformationSceneNode->getRelativeTransformationMatrix()); } } // end namespace Scene } // end namespace Irrlicht
24.666667
107
0.783784
slater1
81c7cc88b0df00e63c1372c1bc59fece5427dd12
6,285
cpp
C++
wpilibc/src/main/native/cpp/Watchdog.cpp
bvisness/allwpilib
549af990072a1ed0c1649c34dc6e1a5cc5f01bd1
[ "BSD-3-Clause" ]
null
null
null
wpilibc/src/main/native/cpp/Watchdog.cpp
bvisness/allwpilib
549af990072a1ed0c1649c34dc6e1a5cc5f01bd1
[ "BSD-3-Clause" ]
null
null
null
wpilibc/src/main/native/cpp/Watchdog.cpp
bvisness/allwpilib
549af990072a1ed0c1649c34dc6e1a5cc5f01bd1
[ "BSD-3-Clause" ]
null
null
null
/*----------------------------------------------------------------------------*/ /* Copyright (c) 2018-2020 FIRST. All Rights Reserved. */ /* Open Source Software - may be modified and shared by FRC teams. The code */ /* must be accompanied by the FIRST BSD license file in the root directory of */ /* the project. */ /*----------------------------------------------------------------------------*/ #include "frc/Watchdog.h" #include <atomic> #include <hal/Notifier.h> #include <wpi/Format.h> #include <wpi/SmallString.h> #include <wpi/priority_queue.h> #include <wpi/raw_ostream.h> #include "frc/DriverStation.h" #include "frc2/Timer.h" using namespace frc; class Watchdog::Impl { public: Impl(); ~Impl(); template <typename T> struct DerefGreater { constexpr bool operator()(const T& lhs, const T& rhs) const { return *lhs > *rhs; } }; wpi::mutex m_mutex; std::atomic<HAL_NotifierHandle> m_notifier; wpi::priority_queue<Watchdog*, std::vector<Watchdog*>, DerefGreater<Watchdog*>> m_watchdogs; void UpdateAlarm(); private: void Main(); std::thread m_thread; }; Watchdog::Impl::Impl() { int32_t status = 0; m_notifier = HAL_InitializeNotifier(&status); wpi_setGlobalHALError(status); HAL_SetNotifierName(m_notifier, "Watchdog", &status); m_thread = std::thread([=] { Main(); }); } Watchdog::Impl::~Impl() { int32_t status = 0; // atomically set handle to 0, then clean HAL_NotifierHandle handle = m_notifier.exchange(0); HAL_StopNotifier(handle, &status); wpi_setGlobalHALError(status); // Join the thread to ensure the handler has exited. if (m_thread.joinable()) m_thread.join(); HAL_CleanNotifier(handle, &status); } void Watchdog::Impl::UpdateAlarm() { int32_t status = 0; // Return if we are being destructed, or were not created successfully auto notifier = m_notifier.load(); if (notifier == 0) return; if (m_watchdogs.empty()) HAL_CancelNotifierAlarm(notifier, &status); else HAL_UpdateNotifierAlarm( notifier, static_cast<uint64_t>(m_watchdogs.top()->m_expirationTime.to<double>() * 1e6), &status); wpi_setGlobalHALError(status); } void Watchdog::Impl::Main() { for (;;) { int32_t status = 0; HAL_NotifierHandle notifier = m_notifier.load(); if (notifier == 0) break; uint64_t curTime = HAL_WaitForNotifierAlarm(notifier, &status); if (curTime == 0 || status != 0) break; std::unique_lock lock(m_mutex); if (m_watchdogs.empty()) continue; // If the condition variable timed out, that means a Watchdog timeout // has occurred, so call its timeout function. auto watchdog = m_watchdogs.pop(); units::second_t now{curTime * 1e-6}; if (now - watchdog->m_lastTimeoutPrintTime > kMinPrintPeriod) { watchdog->m_lastTimeoutPrintTime = now; if (!watchdog->m_suppressTimeoutMessage) { wpi::SmallString<128> buf; wpi::raw_svector_ostream err(buf); err << "Watchdog not fed within " << wpi::format("%.6f", watchdog->m_timeout.to<double>()) << "s\n"; frc::DriverStation::ReportWarning(err.str()); } } // Set expiration flag before calling the callback so any manipulation // of the flag in the callback (e.g., calling Disable()) isn't // clobbered. watchdog->m_isExpired = true; lock.unlock(); watchdog->m_callback(); lock.lock(); UpdateAlarm(); } } Watchdog::Watchdog(double timeout, std::function<void()> callback) : Watchdog(units::second_t{timeout}, callback) {} Watchdog::Watchdog(units::second_t timeout, std::function<void()> callback) : m_timeout(timeout), m_callback(callback), m_impl(GetImpl()) {} Watchdog::~Watchdog() { Disable(); } Watchdog::Watchdog(Watchdog&& rhs) { *this = std::move(rhs); } Watchdog& Watchdog::operator=(Watchdog&& rhs) { m_impl = rhs.m_impl; std::scoped_lock lock(m_impl->m_mutex); m_startTime = rhs.m_startTime; m_timeout = rhs.m_timeout; m_expirationTime = rhs.m_expirationTime; m_callback = std::move(rhs.m_callback); m_lastTimeoutPrintTime = rhs.m_lastTimeoutPrintTime; m_suppressTimeoutMessage = rhs.m_suppressTimeoutMessage; m_tracer = std::move(rhs.m_tracer); m_isExpired = rhs.m_isExpired; if (m_expirationTime != 0_s) { m_impl->m_watchdogs.remove(&rhs); m_impl->m_watchdogs.emplace(this); } return *this; } double Watchdog::GetTime() const { return (frc2::Timer::GetFPGATimestamp() - m_startTime).to<double>(); } void Watchdog::SetTimeout(double timeout) { SetTimeout(units::second_t{timeout}); } void Watchdog::SetTimeout(units::second_t timeout) { m_startTime = frc2::Timer::GetFPGATimestamp(); m_tracer.ClearEpochs(); std::scoped_lock lock(m_impl->m_mutex); m_timeout = timeout; m_isExpired = false; m_impl->m_watchdogs.remove(this); m_expirationTime = m_startTime + m_timeout; m_impl->m_watchdogs.emplace(this); m_impl->UpdateAlarm(); } double Watchdog::GetTimeout() const { std::scoped_lock lock(m_impl->m_mutex); return m_timeout.to<double>(); } bool Watchdog::IsExpired() const { std::scoped_lock lock(m_impl->m_mutex); return m_isExpired; } void Watchdog::AddEpoch(wpi::StringRef epochName) { m_tracer.AddEpoch(epochName); } void Watchdog::PrintEpochs() { m_tracer.PrintEpochs(); } void Watchdog::Reset() { Enable(); } void Watchdog::Enable() { m_startTime = frc2::Timer::GetFPGATimestamp(); m_tracer.ClearEpochs(); std::scoped_lock lock(m_impl->m_mutex); m_isExpired = false; m_impl->m_watchdogs.remove(this); m_expirationTime = m_startTime + m_timeout; m_impl->m_watchdogs.emplace(this); m_impl->UpdateAlarm(); } void Watchdog::Disable() { std::scoped_lock lock(m_impl->m_mutex); if (m_expirationTime != 0_s) { m_impl->m_watchdogs.remove(this); m_expirationTime = 0_s; m_impl->UpdateAlarm(); } } void Watchdog::SuppressTimeoutMessage(bool suppress) { m_suppressTimeoutMessage = suppress; } bool Watchdog::operator>(const Watchdog& rhs) const { return m_expirationTime > rhs.m_expirationTime; } Watchdog::Impl* Watchdog::GetImpl() { static Impl inst; return &inst; }
27.207792
80
0.660621
bvisness
81c81d437ad7da06a3aa7bd15d319b9d8f9ebdde
1,356
cc
C++
tests/models/pmx/lstm_test.cc
kuroro-tian/ppl.nn
7b33cd1fd0660540aec483f299b20094425e7138
[ "Apache-2.0" ]
1
2022-03-27T07:55:37.000Z
2022-03-27T07:55:37.000Z
tests/models/pmx/lstm_test.cc
kuroro-tian/ppl.nn
7b33cd1fd0660540aec483f299b20094425e7138
[ "Apache-2.0" ]
null
null
null
tests/models/pmx/lstm_test.cc
kuroro-tian/ppl.nn
7b33cd1fd0660540aec483f299b20094425e7138
[ "Apache-2.0" ]
null
null
null
#include "pmx_utils.h" #include "ppl/nn/models/pmx/oputils/onnx/lstm.h" using namespace std; using namespace ppl::nn::onnx; using namespace ppl::nn::pmx::onnx; TEST_F(PmxTest, test_lstm) { DEFINE_ARG(LSTMParam, lstm); lstm_param1.activation_alpha = {0.23f}; lstm_param1.activation_beta = {0.33f}; lstm_param1.activations = {ppl::nn::onnx::LSTMParam::ACT_ELU}; lstm_param1.clip = 0.34; lstm_param1.direction = ppl::nn::onnx::LSTMParam::DIR_REVERSE; lstm_param1.hidden_size = 44; lstm_param1.input_forget = 23; MAKE_BUFFER(LSTMParam, lstm); std::vector<float> activation_alpha = lstm_param3.activation_alpha; std::vector<float> activation_beta = lstm_param3.activation_beta; std::vector<ppl::nn::onnx::LSTMParam::activation_t> activations = lstm_param3.activations; float clip = lstm_param3.clip; ppl::nn::onnx::LSTMParam::direction_t direction = lstm_param3.direction; int32_t hidden_size = lstm_param3.hidden_size; int32_t input_forget = lstm_param3.input_forget; EXPECT_FLOAT_EQ(0.23, activation_alpha[0]); EXPECT_FLOAT_EQ(0.33, activation_beta[0]); EXPECT_EQ(ppl::nn::onnx::LSTMParam::ACT_ELU, activations[0]); EXPECT_FLOAT_EQ(0.34, clip); EXPECT_EQ(ppl::nn::onnx::LSTMParam::DIR_REVERSE, direction); EXPECT_EQ(44, hidden_size); EXPECT_EQ(23, input_forget); }
41.090909
94
0.730088
kuroro-tian
81c9f2f62d91c68a68be1d27924c90c02f4b8021
442
hpp
C++
src/gdx-cpp/graphics/g3d/loaders/ModelLoader.hpp
aevum/libgdx-cpp
88603a59af4d915259a841e13ce88f65c359f0df
[ "Apache-2.0" ]
77
2015-01-28T17:21:49.000Z
2022-02-17T17:59:21.000Z
src/gdx-cpp/graphics/g3d/loaders/ModelLoader.hpp
aevum/libgdx-cpp
88603a59af4d915259a841e13ce88f65c359f0df
[ "Apache-2.0" ]
5
2015-03-22T23:14:54.000Z
2020-09-18T13:26:03.000Z
src/gdx-cpp/graphics/g3d/loaders/ModelLoader.hpp
aevum/libgdx-cpp
88603a59af4d915259a841e13ce88f65c359f0df
[ "Apache-2.0" ]
24
2015-02-12T04:34:37.000Z
2021-06-19T17:05:23.000Z
/* * ModelLoader.h * * Created on: Jan 23, 2013 * Author: anton */ #ifndef MODELLOADER_H_ #define MODELLOADER_H_ #include "gdx-cpp/graphics/g3d/ModelLoaderHints.hpp" #include "gdx-cpp/graphics/g3d/model/Model.hpp" #include "gdx-cpp/files/FileHandle.hpp" namespace gdx { class ModelLoader { public: virtual Model* load(const FileHandle& file, ModelLoaderHints hints) = 0; }; } /* namespace gdx */ #endif /* MODELLOADER_H_ */
17
73
0.710407
aevum
81d13142e82759355bf8bbc6ab9f051c50417089
5,100
cc
C++
gazebo/gui/plot/VariablePill_TEST.cc
traversaro/gazebo
6fd426b3949c4ca73fa126cde68f5cc4a59522eb
[ "ECL-2.0", "Apache-2.0" ]
887
2020-04-18T08:43:06.000Z
2022-03-31T11:58:50.000Z
gazebo/gui/plot/VariablePill_TEST.cc
traversaro/gazebo
6fd426b3949c4ca73fa126cde68f5cc4a59522eb
[ "ECL-2.0", "Apache-2.0" ]
462
2020-04-21T21:59:19.000Z
2022-03-31T23:23:21.000Z
gazebo/gui/plot/VariablePill_TEST.cc
traversaro/gazebo
6fd426b3949c4ca73fa126cde68f5cc4a59522eb
[ "ECL-2.0", "Apache-2.0" ]
421
2020-04-21T09:13:03.000Z
2022-03-30T02:22:01.000Z
/* * Copyright (C) 2016 Open Source Robotics Foundation * * 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 "gazebo/gui/plot/VariablePill.hh" #include "gazebo/gui/plot/VariablePill_TEST.hh" ///////////////////////////////////////////////// void VariablePill_TEST::Variable() { this->resMaxPercentChange = 5.0; this->shareMaxPercentChange = 2.0; this->Load("worlds/empty.world"); // test various variable pill set/get functions gazebo::gui::VariablePill *var01 = new gazebo::gui::VariablePill(nullptr); QVERIFY(var01 != nullptr); // name std::string varName = "var01name"; var01->SetName(varName); QCOMPARE(var01->Name(), varName); // text std::string varText = "var01"; var01->SetText(varText); QCOMPARE(var01->Text(), varText); // selected state QCOMPARE(var01->IsSelected(), false); var01->SetSelected(true); QCOMPARE(var01->IsSelected(), true); var01->SetSelected(false); QCOMPARE(var01->IsSelected(), false); // parent QVERIFY(var01->Parent() == nullptr); gazebo::gui::VariablePill *var02 = new gazebo::gui::VariablePill(nullptr); QVERIFY(var02 != nullptr); var01->SetParent(var02); QCOMPARE(var01->Parent(), var02); delete var01; delete var02; } ///////////////////////////////////////////////// void VariablePill_TEST::VariableId() { this->resMaxPercentChange = 5.0; this->shareMaxPercentChange = 2.0; this->Load("worlds/empty.world"); // a set of unique variable ids std::set<unsigned int> ids; // Create new variable pills and verify they all have unique ids gazebo::gui::VariablePill *var01 = new gazebo::gui::VariablePill(nullptr); QVERIFY(var01 != nullptr); unsigned int id = var01->Id(); QVERIFY(id != gazebo::gui::VariablePill::EmptyVariable); QVERIFY(ids.count(id) == 0u); ids.insert(id); gazebo::gui::VariablePill *var02 = new gazebo::gui::VariablePill(nullptr); QVERIFY(var02 != nullptr); id = var02->Id(); QVERIFY(id != gazebo::gui::VariablePill::EmptyVariable); QVERIFY(ids.count(id) == 0u); ids.insert(id); gazebo::gui::VariablePill *var03 = new gazebo::gui::VariablePill(nullptr); QVERIFY(var03 != nullptr); id = var03->Id(); QVERIFY(id != gazebo::gui::VariablePill::EmptyVariable); QVERIFY(ids.count(id) == 0u); ids.insert(id); delete var01; delete var02; delete var03; } ///////////////////////////////////////////////// void VariablePill_TEST::MultiVariable() { // create 4 variable pills gazebo::gui::VariablePill *var01 = new gazebo::gui::VariablePill(nullptr); QVERIFY(var01 != nullptr); QCOMPARE(var01->VariablePillCount(), 0u); gazebo::gui::VariablePill *var02 = new gazebo::gui::VariablePill(nullptr); QVERIFY(var02 != nullptr); QCOMPARE(var02->VariablePillCount(), 0u); gazebo::gui::VariablePill *var03 = new gazebo::gui::VariablePill(nullptr); QVERIFY(var03 != nullptr); QCOMPARE(var03->VariablePillCount(), 0u); gazebo::gui::VariablePill *var04 = new gazebo::gui::VariablePill(nullptr); QVERIFY(var04 != nullptr); QCOMPARE(var04->VariablePillCount(), 0u); // add var02 to var01 - var01 becomes a multi-variable pill var01->AddVariablePill(var02); QCOMPARE(var01->VariablePillCount(), 1u); QVERIFY(var02->Parent() == var01); // verify we cannot add var03 to var02 because var02 already has a parent // this will implicitly add var03 to var02's parent var02->AddVariablePill(var03); QCOMPARE(var01->VariablePillCount(), 2u); QCOMPARE(var02->VariablePillCount(), 0u); QVERIFY(var02->Parent() == var01); QVERIFY(var03->Parent() == var01); // verify we can add var03 to var01 again // their the parent-child relationship should not change var01->AddVariablePill(var03); QCOMPARE(var01->VariablePillCount(), 2u); QVERIFY(var03->Parent() == var01); // move var03 from var01 to var04 var04->AddVariablePill(var03); QCOMPARE(var01->VariablePillCount(), 1u); QCOMPARE(var04->VariablePillCount(), 1u); QVERIFY(var03->Parent() == var04); // remove var02 from var01 var01->RemoveVariablePill(var02); QCOMPARE(var01->VariablePillCount(), 0u); QVERIFY(var02->Parent() == nullptr); // try remove var02 again - it should not do anything var01->RemoveVariablePill(var02); QCOMPARE(var01->VariablePillCount(), 0u); QVERIFY(var02->Parent() == nullptr); // remove var03 from var04 var04->RemoveVariablePill(var03); QCOMPARE(var04->VariablePillCount(), 0u); QVERIFY(var03->Parent() == nullptr); delete var01; delete var02; delete var03; delete var04; } // Generate a main function for the test QTEST_MAIN(VariablePill_TEST)
29.651163
76
0.684902
traversaro
81d59017badc7a971abc038128261e7291e7ae71
1,234
cpp
C++
src/testing/experiment/test_loop_functions.cpp
freedomcondor/argos3-harry
10cc040af3d5339538cfd801f0317fa8269429a5
[ "MIT" ]
1
2021-01-15T21:58:34.000Z
2021-01-15T21:58:34.000Z
src/testing/experiment/test_loop_functions.cpp
freedomcondor/argos3-harry
10cc040af3d5339538cfd801f0317fa8269429a5
[ "MIT" ]
1
2021-02-28T23:45:32.000Z
2021-02-28T23:45:32.000Z
src/testing/experiment/test_loop_functions.cpp
freedomcondor/argos3-harry
10cc040af3d5339538cfd801f0317fa8269429a5
[ "MIT" ]
7
2021-02-26T16:41:06.000Z
2022-01-19T21:36:31.000Z
/** * @file <argos3/testing/experiment/test_loop_functions.cpp> * * @author Carlo Pinciroli <ilpincy@gmail.com> */ #include "test_loop_functions.h" #include <argos3/plugins/robots/foot-bot/simulator/footbot_entity.h> #include <argos3/plugins/simulator/entities/led_entity.h> /****************************************/ /****************************************/ void CTestLoopFunctions::Init(TConfigurationNode& t_tree) { LOG << "CTestLoopFunctions init running!\n"; CFootBotEntity& fb = dynamic_cast<CFootBotEntity&>(GetSpace().GetEntity("fb")); CLEDEntity& cLedA = fb.GetComponent<CLEDEntity>("leds.led[led_2]"); CLEDEntity& cLedB = fb.GetComponent<CLEDEntity>("leds.led[led_3]"); CLEDEntity& cLedC = fb.GetComponent<CLEDEntity>("leds.led[led_4]"); cLedA.SetColor(CColor::GREEN); cLedB.SetColor(CColor::BLUE); cLedC.SetColor(CColor::YELLOW); } CColor CTestLoopFunctions::GetFloorColor(const CVector2& c_pos_on_floor) { if(Sign(c_pos_on_floor.GetX()) == Sign(c_pos_on_floor.GetY())) return CColor::GRAY30; else return CColor::GRAY70; } /****************************************/ /****************************************/ REGISTER_LOOP_FUNCTIONS(CTestLoopFunctions, "test_lf");
33.351351
82
0.634522
freedomcondor
81d5db984932e341f16deda1effa122be9e22a15
2,381
hpp
C++
src/lib/rendering/synchronization/Fence.hpp
Lut99/Rasterizer
453864506db749a93fb82fb17cc5ee88cc4ada01
[ "MIT" ]
1
2021-08-15T19:20:14.000Z
2021-08-15T19:20:14.000Z
src/lib/rendering/synchronization/Fence.hpp
Lut99/Rasterizer
453864506db749a93fb82fb17cc5ee88cc4ada01
[ "MIT" ]
17
2021-06-05T12:37:04.000Z
2021-10-01T10:20:09.000Z
src/lib/rendering/synchronization/Fence.hpp
Lut99/Rasterizer
453864506db749a93fb82fb17cc5ee88cc4ada01
[ "MIT" ]
null
null
null
/* FENCE.hpp * by Lut99 * * Created: * 28/06/2021, 16:57:12 * Last edited: * 28/06/2021, 16:57:12 * Auto updated? * Yes * * Description: * Contains a class that wraps a VkFence object. **/ #ifndef RENDERING_FENCE_HPP #define RENDERING_FENCE_HPP #include <vulkan/vulkan.h> #include "../gpu/GPU.hpp" namespace Makma3D::Rendering { /* The Fence class, which wraps a VkFence object and manages its memory. */ class Fence { public: /* Channel name for the Fence class. */ static constexpr const char* channel = "Fence"; /* The GPU where the semaphore lives. */ const Rendering::GPU& gpu; private: /* The VkFence object we wrap. */ VkFence vk_fence; /* The flags used to create the fence. */ VkFenceCreateFlags vk_create_flags; public: /* Constructor for the Fence class, which takes completely nothing! (except for the GPU where it lives, obviously, and optionally some flags) */ Fence(const Rendering::GPU& gpu, VkFenceCreateFlags create_flags = 0); /* Copy constructor for the Fence class. */ Fence(const Fence& other); /* Move constructor for the Fence class. */ Fence(Fence&& other); /* Destructor for the Fence class. */ ~Fence(); /* Blocks the CPU until the Fence is signalled. */ inline void wait() const { vkWaitForFences(this->gpu, 1, &this->vk_fence, true, UINT64_MAX); } /* Resets the Fence once signalled. */ inline void reset() const { vkResetFences(this->gpu, 1, &this->vk_fence); } /* Expliticly returns the internal VkFence object. */ inline const VkFence& fence() const { return this->vk_fence; } /* Implicitly returns the internal VkFence object. */ inline operator VkFence() const { return this->vk_fence; } /* Copy assignment operator for the Fence class. */ inline Fence& operator=(const Fence& other) { return *this = Fence(other); } /* Move assignment operator for the Fence class. */ inline Fence& operator=(Fence&& other) { if (this != &other) { swap(*this, other); } return *this; } /* Swap operator for the Fence class. */ friend void swap(Fence& s1, Fence& s2); }; /* Swap operator for the Fence class. */ void swap(Fence& f1, Fence& f2); } #endif
33.069444
152
0.622848
Lut99