hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
109
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
48.5k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
122ae8a4dbb851bd8b0686cc72850a236e1f754e
8,475
cpp
C++
common/events/src/events/zsysd.cpp
naazgull/zapata
e5734ff88a17b261a2f4547fa47f01dbb1a69d84
[ "Unlicense" ]
9
2016-08-10T16:51:23.000Z
2020-04-08T22:07:47.000Z
common/events/src/events/zsysd.cpp
naazgull/zapata
e5734ff88a17b261a2f4547fa47f01dbb1a69d84
[ "Unlicense" ]
78
2015-02-25T15:16:02.000Z
2021-10-31T15:58:15.000Z
common/events/src/events/zsysd.cpp
naazgull/zapata
e5734ff88a17b261a2f4547fa47f01dbb1a69d84
[ "Unlicense" ]
7
2015-01-13T14:39:21.000Z
2018-11-24T06:48:09.000Z
/* This is free and unencumbered software released into the public domain. Anyone is free to copy, modify, publish, use, compile, sell, or distribute this software, either in source code form or as a compiled binary, for any purpose, commercial or non-commercial, and by any means. In jurisdictions that recognize copyright laws, the author or authors of this software dedicate any and all copyright interest in the software to the public domain. We make this dedication for the benefit of the public at large and to the detriment of our heirs and successors. We intend this dedication to be an overt act of relinquishment in perpetuity of all present and future rights to this software under copyright law. 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 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 <fstream> #include <iostream> #include <signal.h> #include <string> #include <unistd.h> #include <semaphore.h> #include <zapata/base.h> #include <zapata/events.h> #include <zapata/json.h> auto generate(zpt::json _to_add, zpt::json _global_conf) -> void { std::ifstream _ifs; _ifs.open( (std::string("/etc/zapata/backend-available/") + std::string(_to_add) + std::string(".conf")) .data()); if (_ifs.is_open()) { zpt::json _conf; _ifs >> _conf; _ifs.close(); _conf = _global_conf + _conf; zpt::conf::setup(_conf); _conf << "!warning" << "AUTOMATIC GENERATED FILE, do NOT edit by hand"; _conf << "$source" << _to_add; if (!_conf["boot"][0]["name"]->is_string()) { std::cout << "no bootable configuration found in /etc/zapata/backend-available/" << std::string(_to_add) << ".conf" << std::endl << std::flush; exit(-1); } std::ofstream _ofs; _ofs.open((std::string("/etc/zapata/backend-enabled/") + std::string(_conf["boot"][0]["name"]) + std::string(".conf")) .data(), std::ios::out | std::ios::trunc); _ofs << zpt::json::pretty(_conf) << std::flush; _ofs.close(); std::cout << "> wrote /etc/zapata/backend-enabled/" << std::string(_conf["boot"][0]["name"]) << ".conf" << std::endl << std::flush; std::string _sysd("[Unit]\n" "Description=${name}\n" "${dependencies}\n" "${requirements}\n" "\n" "[Service]\n" "LimitNOFILE=${fd_max}\n" "Type=notify\n" "TimeoutStartSec=0\n" "TimeoutStopSec=2\n" "Restart=${restart}\n" "RemainAfterExit=no\n" "WatchdogSec=${keep_alive}\n" "\n" "ExecStart=/usr/bin/zpt -c /etc/zapata/backend-enabled/${name}.conf\n" "\n" "[Install]\n" "WantedBy=multi-user.target\n"); std::string _after; std::string _requires; if (_conf["boot"][0]["depends"]->is_array()) { for (auto [_idx, _key, _dep] : _conf["boot"][0]["depends"]) { _after += std::string("After=") + std::string(_dep) + std::string(".service\n"); _requires += std::string("Requires=") + std::string(_dep) + std::string(".service\n"); } } zpt::replace(_sysd, "${dependencies}", _after); zpt::replace(_sysd, "${requirements}", _requires); zpt::replace(_sysd, "${name}", std::string(_conf["boot"][0]["name"])); if (_conf["boot"][0]["keep_alive"]->ok()) { zpt::replace(_sysd, "${keep_alive}", std::string(_conf["boot"][0]["keep_alive"])); } else { zpt::replace(_sysd, "${keep_alive}", "0"); } if (_conf["boot"][0]["fd_max"]->ok()) { zpt::replace(_sysd, "${fd_max}", std::string(_conf["boot"][0]["fd_max"])); } else { zpt::replace(_sysd, "${fd_max}", "0"); } if (_conf["boot"][0]["restart_policy"]->ok()) { zpt::replace(_sysd, "${restart}", std::string(_conf["boot"][0]["restart_policy"])); } else { zpt::replace(_sysd, "${restart}", "no"); } std::ofstream _sfs; _sfs.open((std::string("/lib/systemd/system/") + std::string(_conf["boot"][0]["name"]) + std::string(".service")) .data()); if (_sfs.is_open()) { _sfs << _sysd << std::endl << std::flush; _sfs.close(); std::cout << "> wrote /lib/systemd/system/" << std::string(_conf["boot"][0]["name"]) << ".service" << std::endl << std::flush; } else { std::cout << "couldn't write to /lib/systemd/system/" << std::string(_conf["boot"][0]["name"]) << ".service" << std::endl << std::flush; exit(-1); } } else { std::cout << "no such file named /etc/zapata/backend-available/" << std::string(_to_add) << ".conf" << std::endl << std::flush; exit(-1); } } int main(int argc, char* argv[]) { zpt::json _args = zpt::conf::getopt(argc, argv); if (_args["add"]) { zpt::json _global_conf; std::ifstream _zfs; _zfs.open((std::string("/etc/zapata/zapata.conf")).data()); if (_zfs.is_open()) { zpt::json _conf; _zfs >> _conf; _zfs.close(); } for (auto _to_add : _args["add"]->array()) { generate(_to_add, _global_conf); } } else if (_args["reconfigure"]) { zpt::json _global_conf; std::ifstream _zfs; _zfs.open((std::string("/etc/zapata/zapata.conf")).data()); if (_zfs.is_open()) { zpt::json _conf; _zfs >> _conf; _zfs.close(); } std::vector<std::string> _files; zpt::glob("/etc/zapata/backend-enabled/", _files, "(.*)\\.conf"); for (auto _file : _files) { std::ifstream _ifs; _ifs.open(_file.data()); if (_ifs.is_open()) { zpt::json _conf; _ifs >> _conf; _ifs.close(); generate(_conf["$source"], _global_conf); } else { std::cout << "no such file named " << _file << std::endl << std::flush; exit(-1); } } } else if (_args["remove"]) { for (auto _to_remove : _args["remove"]->array()) { std::ifstream _ifs; _ifs.open((std::string("/etc/zapata/backend-available/") + std::string(_to_remove) + std::string(".conf")) .data()); if (_ifs.is_open()) { zpt::json _conf; _ifs >> _conf; _ifs.close(); if (system((std::string("rm -rf /etc/zapata/backend-enabled/") + std::string(_conf["boot"][0]["name"]) + std::string(".conf")) .data())) {} std::cout << "> removing /etc/zapata/backend-enabled/" << std::string(_conf["boot"][0]["name"]) << ".conf" << std::endl << std::flush; if (system((std::string("rm -rf /lib/systemd/system/") + std::string(_conf["boot"][0]["name"]) + std::string(".service")) .data())) {} std::cout << "> removing /lib/systemd/system/" << std::string(_conf["boot"][0]["name"]) << ".service" << std::endl << std::flush; } } } return 0; }
38.004484
100
0.487198
naazgull
122b1f5dd7e100112c1df1920bb2392b584c44bc
8,793
cpp
C++
parameter_generator.cpp
alexrow/LEDAtools
f847707833650706519cc57f5956b8e1a17a157c
[ "Unlicense" ]
null
null
null
parameter_generator.cpp
alexrow/LEDAtools
f847707833650706519cc57f5956b8e1a17a157c
[ "Unlicense" ]
null
null
null
parameter_generator.cpp
alexrow/LEDAtools
f847707833650706519cc57f5956b8e1a17a157c
[ "Unlicense" ]
1
2021-03-12T09:12:30.000Z
2021-03-12T09:12:30.000Z
#include <NTL/ZZ.h> #include <cstdint> #include <cmath> #define NUM_BITS_REAL_MANTISSA 128 #define IGNORE_DECODING_COST 0 #define SKIP_BJMM 0 #define LOG_COST_CRITERION 1 #include "proper_primes.hpp" #include "binomials.hpp" #include "bit_error_probabilities.hpp" #include "partitions_permanents.hpp" #include "isd_cost_estimate.hpp" #include <cmath> uint32_t estimate_t_val(const uint32_t c_sec_level, const uint32_t q_sec_level, const uint32_t n_0, const uint32_t p){ double achieved_c_sec_level = c_sec_level; double achieved_q_sec_level = q_sec_level; uint32_t lo = 1, t, t_prec; uint32_t hi; hi = p < 4*c_sec_level ? p : 4*c_sec_level; t = lo; t_prec = lo; while (hi - lo > 1){ t_prec = t; t = (lo + hi)/2; std::cerr << "testing t " << t << std::endl; achieved_c_sec_level = c_isd_log_cost(n_0*p,((n_0-1)*p),t,p,0); achieved_q_sec_level = q_isd_log_cost(n_0*p,((n_0-1)*p),t,p,0); if ( (achieved_c_sec_level >= c_sec_level) && (achieved_q_sec_level >= q_sec_level) ){ hi = t; } else { lo = t; } } if( (achieved_c_sec_level >= c_sec_level) && (achieved_q_sec_level >= q_sec_level) ){ return t; } return t_prec; } int ComputeDvMPartition(const uint64_t d_v_prime, const uint64_t n_0, uint64_t mpartition[], uint64_t &d_v){ d_v = floor(sqrt(d_v_prime)); d_v = (d_v & 0x01) ? d_v : d_v + 1; uint64_t m = ceil( (double) d_v_prime / (double) d_v ); int partition_ok; partition_ok = FindmPartition(m,mpartition,n_0); while(!partition_ok && (d_v_prime/d_v) >= n_0){ d_v += 2; m = ceil( (double) d_v_prime / (double) d_v ); partition_ok = FindmPartition(m,mpartition,n_0); } return partition_ok; } uint64_t estimate_dv (const uint32_t c_sec_level, // expressed as const uint32_t q_sec_level, const uint32_t n_0, const uint32_t p, uint64_t mpartition[]){ double achieved_c_sec_level = 0.0; double achieved_q_sec_level = 0.0; double achieved_c_enum_sec_level = 0.0; double achieved_q_enum_sec_level = 0.0; NTL::ZZ keyspace; uint32_t lo = 1, d_v_prime, hi; uint64_t d_v,d_v_prec =0; int found_dv_mpartition = 0; // recalling that the weight of the sought codeword in a KRA is // d_c_prime = n_0 * d_v_prime, d_c_prime < p // d_v_prime should not be greater than p/n_0 hi = (p/n_0) < 4*c_sec_level ? (p/n_0) : 4*c_sec_level; d_v_prime = lo; d_v = (int) sqrt(lo); while (hi - lo > 1){ d_v_prec = d_v; d_v_prime = (lo + hi)/2; found_dv_mpartition = ComputeDvMPartition(d_v_prime,n_0,mpartition,d_v); if(found_dv_mpartition) { keyspace = 1; for(int i =0; i < (int)n_0; i++){ keyspace *= binomial_wrapper(p,mpartition[i]); } keyspace = NTL::power(keyspace,n_0); keyspace += NTL::power(binomial_wrapper(p,d_v),n_0); achieved_c_enum_sec_level = NTL::conv<double>(log2_RR(NTL::to_RR(keyspace))); achieved_q_enum_sec_level = achieved_c_enum_sec_level/2; if ((achieved_q_enum_sec_level >= q_sec_level) && (achieved_c_enum_sec_level >= c_sec_level) ){ /* last parameter indicates a KRA, reduce margin by p due to quasi cyclicity */ achieved_c_sec_level = c_isd_log_cost(n_0*p,p,n_0*d_v_prime,p,1); achieved_q_sec_level = q_isd_log_cost(n_0*p,p,n_0*d_v_prime,p,1); } } if ( (found_dv_mpartition) && (achieved_q_enum_sec_level >= q_sec_level) && (achieved_c_enum_sec_level >= c_sec_level) && (achieved_c_sec_level >= c_sec_level) && (achieved_q_sec_level >= q_sec_level) ){ hi = d_v_prime; } else { lo = d_v_prime; } } if ( (found_dv_mpartition) && (achieved_q_enum_sec_level >= q_sec_level) && (achieved_c_enum_sec_level >= c_sec_level) && (achieved_c_sec_level >= c_sec_level) && (achieved_q_sec_level >= q_sec_level) ){ return d_v; } return d_v_prec; } int main(int argc, char* argv[]){ if(argc != 6){ std::cout << "Code Parameter Computer for LEDA[kem|pkc]" << std::endl << " Usage " << argv[0] << " security_level_classic security_level_pq n_0 epsilon starting_prime_lb" << std::endl; return -1; } uint32_t c_sec_level = atoi(argv[1]); uint32_t q_sec_level = atoi(argv[2]); uint32_t n_0 = atoi(argv[3]); float epsilon = atof(argv[4]); uint32_t starting_prime_lower_bound = atoi(argv[5]); std::cerr << "Computing the parameter set for security level classic:2^" << c_sec_level << " post-q:2^" << q_sec_level << " n_0 " << n_0 << " epsilon " << epsilon << std::endl; uint64_t p, p_th, t, d_v_prime, d_v; uint64_t mpartition[n_0] = {0}; int current_prime_pos = 0; while (proper_primes[current_prime_pos] < starting_prime_lower_bound){ current_prime_pos++; } p_th = proper_primes[current_prime_pos]; InitBinomials(); NTL::RR::SetPrecision(NUM_BITS_REAL_MANTISSA); pi = NTL::ComputePi_RR(); /* since some values of p may yield no acceptable partitions for m, binary * search on p is not feasible. Fall back to fast increase of the value of * p exploiting the value of the p expected to be correcting the required t * errors */ std::cout << "finding parameters" << std::endl; do { /* estimate the current prime as the closest * to the previous p_th * (1+epsilon) */ uint32_t next_prime = ceil(p_th * (1.0+epsilon)); current_prime_pos = 0; while (proper_primes[current_prime_pos] < next_prime){ current_prime_pos++; } p = proper_primes[current_prime_pos]; std::cout << " -- testing p: " << p << std::endl; // Estimate number of errors to ward off ISD decoding t = estimate_t_val(c_sec_level,q_sec_level,n_0,p); std::cout << " -- found t: " << t << std::endl; /* Estimate H*Q density to avoid key recovery via ISD and enumeration * of H and Q */ d_v = estimate_dv(c_sec_level,q_sec_level,n_0,p,mpartition); std::cout << " -- found d_v: " << d_v << std::endl; // Estimate the bit flipping thresholds and correction capability d_v_prime=0; for(int i=0;i< (int)n_0;i++){ d_v_prime += mpartition[i]; } d_v_prime = d_v * d_v_prime; p_th=Findpth(n_0, d_v_prime, t); std::cout << " -- p should be at least " << (1.0+epsilon)* p_th << "to correct the errors" << std::endl; } while ((p <= (1.0+epsilon)* p_th) && (current_prime_pos < PRIMES_NO) ); std::cout << "refining parameters" << std::endl; uint64_t p_ok, t_ok, d_v_ok, mpartition_ok[n_0] = {0}; /* refinement step taking into account possible invalid m partitions */ do { p = proper_primes[current_prime_pos]; std::cout << " -- testing p: " << p << std::endl; // Estimate number of errors to ward off ISD decoding t = estimate_t_val(c_sec_level,q_sec_level,n_0,p); std::cout << " -- found t: " << t << std::endl; /* Estimate H*Q density to avoid key recovery via ISD and enumeration * of H and Q */ d_v = estimate_dv(c_sec_level,q_sec_level,n_0,p,mpartition); std::cout << " -- found d_v: " << d_v << std::endl; // Estimate the bit flipping thresholds and correction capability d_v_prime=0; for(int i=0;i< (int)n_0;i++){ d_v_prime += mpartition[i]; } d_v_prime = d_v * d_v_prime; p_th=Findpth(n_0, d_v_prime, t); std::cout << " -- the threshold value for p to be correcting errors is " << p_th << std::endl; if(p > (1.0+epsilon)* p_th ) { //store last valid parameter set std::cout << " -- p is at least " << (1.0+epsilon)*p_th << "; it corrects the errors" << std::endl; p_ok = p; t_ok = t; d_v_ok = d_v; for(unsigned i = 0; i < n_0 ; i++){ mpartition_ok[i] = mpartition[i]; } } current_prime_pos--; } while ((p > (1.0+epsilon)* p_th ) && (current_prime_pos > 0)); std::cout << "parameter set found: p:" << p_ok << " t: " << t_ok; std::cout << " d_v : " << d_v_ok << " mpartition: [ "; for (unsigned i = 0; i < n_0 ; i++ ){ std::cout << mpartition_ok[i] << " "; } std::cout << " ]" << std::endl; return 0; }
35.455645
116
0.589446
alexrow
122e5086319ce6bf859f46f5a1bc19bb9cdc8c8a
923
cpp
C++
src/terminal/render/Translate.cpp
KeinR/Etermal
9bf66f6be6ae8585b763dd902701e72013a5abcc
[ "MIT" ]
null
null
null
src/terminal/render/Translate.cpp
KeinR/Etermal
9bf66f6be6ae8585b763dd902701e72013a5abcc
[ "MIT" ]
null
null
null
src/terminal/render/Translate.cpp
KeinR/Etermal
9bf66f6be6ae8585b763dd902701e72013a5abcc
[ "MIT" ]
null
null
null
#include "Translate.h" #include <glm/gtx/rotate_vector.hpp> #include "../Resources.h" #include "Model.h" #include "RModel.h" glm::mat4 etm::tsl::model(Resources *res, Model &m) { glm::mat4 model(1.0f); // Translate so that the x/y coords are in the middle // of the object, then convert to quads (OpenGL style). const float xPos = (m.x + m.width / 2) / res->getViewportWidth() * 2 - 1; const float yPos = ((m.y + m.height / 2) / res->getViewportHeight() * 2 - 1) * -1; model = glm::translate(model, glm::vec3(xPos, yPos, 0.0f)); // Convert width and height to OpenGL-readable clamped floats, 0-1 model = glm::scale(model, glm::vec3(m.width / res->getViewportWidth(), m.height / res->getViewportHeight(), 0.0f)); return model; } glm::mat4 etm::tsl::rModel(Resources *res, RModel &m) { return glm::rotate(model(res, m), glm::radians(m.rotation), glm::vec3(0.0f, 0.0f, 1.0f)); }
34.185185
119
0.641387
KeinR
122ed0e34c0bb22804e4541fc998efbf1fd47cd7
112
cpp
C++
language.cpp
MasterQ32/CodersNotepad
8248ce25bda3b9fb82d84ec682bc9c82ac4e868a
[ "MIT" ]
null
null
null
language.cpp
MasterQ32/CodersNotepad
8248ce25bda3b9fb82d84ec682bc9c82ac4e868a
[ "MIT" ]
null
null
null
language.cpp
MasterQ32/CodersNotepad
8248ce25bda3b9fb82d84ec682bc9c82ac4e868a
[ "MIT" ]
null
null
null
#include "language.h" Language::Language(QString id, QObject *parent) : QObject(parent), mId(id) { }
11.2
49
0.642857
MasterQ32
12321dfd81c2143f28ab45a2e45581e2ee362dd0
9,804
cpp
C++
unittest/benchmark/benchmark_knowhere_binary.cpp
ChunelFeng/knowhere
4c6ff55b5a23a9a38b12db40cbb5cd847cae1408
[ "Apache-2.0" ]
null
null
null
unittest/benchmark/benchmark_knowhere_binary.cpp
ChunelFeng/knowhere
4c6ff55b5a23a9a38b12db40cbb5cd847cae1408
[ "Apache-2.0" ]
null
null
null
unittest/benchmark/benchmark_knowhere_binary.cpp
ChunelFeng/knowhere
4c6ff55b5a23a9a38b12db40cbb5cd847cae1408
[ "Apache-2.0" ]
null
null
null
// Copyright (C) 2019-2020 Zilliz. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software distributed under the License // is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express // or implied. See the License for the specific language governing permissions and limitations under the License. #include <gtest/gtest.h> #include <vector> #include "knowhere/index/IndexType.h" #include "knowhere/index/VecIndexFactory.h" #include "knowhere/index/vector_index/adapter/VectorAdapter.h" #include "unittest/benchmark/benchmark_sift.h" #include "unittest/utils.h" #define CALC_TIME_SPAN(X) \ double t_start = elapsed(); \ X; \ double t_diff = elapsed() - t_start; class Benchmark_knowhere_binary : public Benchmark_sift { public: void write_index(const std::string& filename, const knowhere::Config& conf) { binary_set_.clear(); FileIOWriter writer(filename); binary_set_ = index_->Serialize(conf); const auto& m = binary_set_.binary_map_; for (auto it = m.begin(); it != m.end(); ++it) { const std::string& name = it->first; size_t name_size = name.length(); const knowhere::BinaryPtr data = it->second; size_t data_size = data->size; writer(&name_size, sizeof(size_t)); writer(&data->size, sizeof(data->size)); writer((void*)name.c_str(), name_size); writer(data->data.get(), data->size); } } void read_index(const std::string& filename) { binary_set_.clear(); FileIOReader reader(filename); int64_t file_size = reader.size(); if (file_size < 0) { throw knowhere::KnowhereException(filename + " not exist"); } int64_t offset = 0; while (offset < file_size) { size_t name_size, data_size; reader(&name_size, sizeof(size_t)); offset += sizeof(size_t); reader(&data_size, sizeof(size_t)); offset += sizeof(size_t); std::string name; name.resize(name_size); reader(name.data(), name_size); offset += name_size; auto data = new uint8_t[data_size]; reader(data, data_size); offset += data_size; std::shared_ptr<uint8_t[]> data_ptr(data); binary_set_.Append(name, data_ptr, data_size); } } std::string get_index_name(const std::vector<int32_t>& params) { std::string params_str = ""; for (size_t i = 0; i < params.size(); i++) { params_str += "_" + std::to_string(params[i]); } return ann_test_name_ + "_" + std::string(index_type_) + params_str + ".index"; } void create_cpu_index(const std::string& index_file_name, const knowhere::Config& conf) { printf("[%.3f s] Creating CPU index \"%s\"\n", get_time_diff(), std::string(index_type_).c_str()); auto& factory = knowhere::VecIndexFactory::GetInstance(); index_ = factory.CreateVecIndex(index_type_); try { printf("[%.3f s] Reading index file: %s\n", get_time_diff(), index_file_name.c_str()); read_index(index_file_name); } catch (...) { printf("[%.3f s] Building all on %d vectors\n", get_time_diff(), nb_); knowhere::DatasetPtr ds_ptr = knowhere::GenDataset(nb_, dim_, xb_); index_->BuildAll(ds_ptr, conf); printf("[%.3f s] Writing index file: %s\n", get_time_diff(), index_file_name.c_str()); write_index(index_file_name, conf); } } void test_binary_idmap(const knowhere::Config& cfg) { auto conf = cfg; printf("\n[%0.3f s] %s | %s \n", get_time_diff(), ann_test_name_.c_str(), std::string(index_type_).c_str()); printf("================================================================================\n"); for (auto nq : NQs_) { knowhere::DatasetPtr ds_ptr = knowhere::GenDataset(nq, dim_, xq_); for (auto k : TOPKs_) { knowhere::SetMetaTopk(conf, k); CALC_TIME_SPAN(auto result = index_->Query(ds_ptr, conf, nullptr)); auto ids = knowhere::GetDatasetIDs(result); float recall = CalcRecall(ids, nq, k); printf(" nq = %4d, k = %4d, elapse = %.4fs, R@ = %.4f\n", nq, k, t_diff, recall); } } printf("================================================================================\n"); printf("[%.3f s] Test '%s/%s' done\n\n", get_time_diff(), ann_test_name_.c_str(), std::string(index_type_).c_str()); } void test_binary_ivf(const knowhere::Config& cfg) { auto conf = cfg; auto nlist = knowhere::GetIndexParamNlist(conf); printf("\n[%0.3f s] %s | %s | nlist=%ld\n", get_time_diff(), ann_test_name_.c_str(), std::string(index_type_).c_str(), nlist); printf("================================================================================\n"); for (auto nprobe : NPROBEs_) { knowhere::SetIndexParamNprobe(conf, nprobe); for (auto nq : NQs_) { knowhere::DatasetPtr ds_ptr = knowhere::GenDataset(nq, dim_, xq_); for (auto k : TOPKs_) { knowhere::SetMetaTopk(conf, k); CALC_TIME_SPAN(auto result = index_->Query(ds_ptr, conf, nullptr)); auto ids = knowhere::GetDatasetIDs(result); float recall = CalcRecall(ids, nq, k); printf(" nprobe = %4d, nq = %4d, k = %4d, elapse = %.4fs, R@ = %.4f\n", nprobe, nq, k, t_diff, recall); } } } printf("================================================================================\n"); printf("[%.3f s] Test '%s/%s' done\n\n", get_time_diff(), ann_test_name_.c_str(), std::string(index_type_).c_str()); } protected: void SetUp() override { T0_ = elapsed(); // set_ann_test_name("sift-128-euclidean"); set_ann_test_name("sift-4096-hamming"); parse_ann_test_name(); load_hdf5_data<true>(); assert(metric_str_ == METRIC_HAM_STR || metric_str_ == METRIC_JAC_STR || metric_str_ == METRIC_TAN_STR); metric_type_ = (metric_str_ == METRIC_HAM_STR) ? knowhere::metric::HAMMING : (metric_str_ == METRIC_JAC_STR) ? knowhere::metric::JACCARD : knowhere::metric::TANIMOTO; knowhere::SetMetaMetricType(cfg_, metric_type_); knowhere::KnowhereConfig::SetSimdType(knowhere::KnowhereConfig::SimdType::AUTO); } void TearDown() override { free_all(); } protected: knowhere::MetricType metric_type_; knowhere::BinarySet binary_set_; knowhere::IndexType index_type_; knowhere::VecIndexPtr index_ = nullptr; knowhere::Config cfg_; const std::vector<int32_t> NQs_ = {10000}; const std::vector<int32_t> TOPKs_ = {10}; // IVF index params const std::vector<int32_t> NLISTs_ = {1024}; const std::vector<int32_t> NPROBEs_ = {1, 2, 4, 8, 16, 32, 64, 128, 256}; }; // This testcase can be used to generate binary sift1m HDF5 file // Following these steps: // 1. set_ann_test_name("sift-128-euclidean") // 2. use load_hdf5_data<false>(); // 3. change metric type to expected value (hamming/jaccard/tanimoto) manually // 4. specify the hdf5 file name to generate // 5. run this testcase #if 0 TEST_F(Benchmark_knowhere_binary, TEST_CREATE_BINARY_HDF5) { index_type_ = knowhere::IndexEnum::INDEX_FAISS_BIN_IDMAP; knowhere::Config conf = cfg_; std::string index_file_name = get_index_name({}); // use sift1m data as binary data dim_ *= 32; metric_type_ = knowhere::metric::HAMMING; knowhere::SetMetaMetricType(conf, metric_type_); create_cpu_index(index_file_name, conf); index_->Load(binary_set_); knowhere::DatasetPtr ds_ptr = knowhere::GenDataset(nq_, dim_, xq_); knowhere::SetMetaTopk(conf, gt_k_); auto result = index_->Query(ds_ptr, conf, nullptr); auto gt_ids = knowhere::GetDatasetIDs(result); auto gt_dist = knowhere::GetDatasetDistance(result); auto gt_ids_int = new int32_t[gt_k_ * nq_]; for (int32_t i = 0; i < gt_k_ * nq_; i++) { gt_ids_int[i] = gt_ids[i]; } assert(dim_ == 4096); assert(nq_ == 10000); assert(gt_k_ == 100); hdf5_write<true>("sift-4096-hamming.hdf5", dim_/32, gt_k_, xb_, nb_, xq_, nq_, gt_ids_int, gt_dist); delete[] gt_ids_int; } #endif TEST_F(Benchmark_knowhere_binary, TEST_BINARY_IDMAP) { index_type_ = knowhere::IndexEnum::INDEX_FAISS_BIN_IDMAP; knowhere::Config conf = cfg_; std::string index_file_name = get_index_name({}); create_cpu_index(index_file_name, conf); index_->Load(binary_set_); test_binary_idmap(conf); } TEST_F(Benchmark_knowhere_binary, TEST_BINARY_IVFFLAT) { index_type_ = knowhere::IndexEnum::INDEX_FAISS_BIN_IVFFLAT; knowhere::Config conf = cfg_; for (auto nlist : NLISTs_) { std::string index_file_name = get_index_name({nlist}); knowhere::SetIndexParamNlist(conf, nlist); create_cpu_index(index_file_name, conf); index_->Load(binary_set_); test_binary_ivf(conf); } }
37.853282
116
0.586597
ChunelFeng
123358de8146823dfc763ad8df7083420de0c640
8,638
hpp
C++
OBJ_IO.hpp
James-Wickenden/computer-graphics
03a2661e4c9368773b21ea9e7b459f0bde7a649c
[ "MIT" ]
1
2020-07-15T13:14:57.000Z
2020-07-15T13:14:57.000Z
OBJ_IO.hpp
James-Wickenden/computer-graphics
03a2661e4c9368773b21ea9e7b459f0bde7a649c
[ "MIT" ]
null
null
null
OBJ_IO.hpp
James-Wickenden/computer-graphics
03a2661e4c9368773b21ea9e7b459f0bde7a649c
[ "MIT" ]
null
null
null
#include <string> #include <fstream> #include <sstream> #include <vector> #include <unordered_map> #include <algorithm> #include <cmath> #include <tuple> #include <optional> #include "OBJ_Structure.hpp" #include "Texture.hpp" using namespace std; using namespace glm; class OBJ_IO { public: OBJ_IO () {} // For clarity: each ModelTriangle (a triangle in 3D space) may get their // "filling" from a TextureTriangle (a triangle in 2D space). tuple<vector<GObject>, optional<Texture>> loadOBJ(string filename) { optional<Texture> maybeTexture; OBJ_Structure structure = loadOBJpass1(filename); if (structure.textureFilename.empty()) maybeTexture = nullopt; else maybeTexture.emplace(Texture(structure.textureFilename)); //cout << structure << endl; return make_tuple(structure.toGObjects(), maybeTexture); } std::vector<GObject> scale_additive(std::vector<GObject> gobjects) { float currentMinComponent = std::numeric_limits<float>::infinity(); for (uint j=0; j<gobjects.size(); j++) { for (uint i=0; i<gobjects.at(j).faces.size(); i++) { for (int k=0; k<3; k++) { float smallest = minComponent(gobjects.at(j).faces.at(i).vertices[k]); if (smallest < currentMinComponent) currentMinComponent = smallest; } } } float addFactor = currentMinComponent < 0.0f ? abs(currentMinComponent) : 0.0f; for (uint j=0; j<gobjects.size(); j++) { //std::cout << "gobject " << gobjects.at(j).name << '\n'; for (uint i=0; i<gobjects.at(j).faces.size(); i++) { for (int k=0; k<3; k++) { glm::vec3 v = gobjects.at(j).faces.at(i).vertices[k]; v[0] += addFactor; v[1] += addFactor; v[2] += addFactor; gobjects.at(j).faces.at(i).vertices[k] = v; // std::cout << "NEW VERTEX: (" << v.x << ", " << v.y << ", " << v.z << ")\n"; } } } return gobjects; } std::vector<GObject> scale_multiplicative(int width, std::vector<GObject> gobjects) { float currentMaxComponent = -std::numeric_limits<float>::infinity(); for (uint j=0; j<gobjects.size(); j++) { for (uint i=0; i<gobjects.at(j).faces.size(); i++) { for (int k=0; k<3; k++) { float greatest = maxComponent(gobjects.at(j).faces.at(i).vertices[k]); if (greatest > currentMaxComponent) currentMaxComponent = greatest; } } } float multFactor = width / (currentMaxComponent); //std::cout << "MULTIPLICATIVE SCALE FACTOR: " << multFactor << '\n'; //std::cout << "ADDITIVE SCALE FACTOR: " << addFactor << '\n'; for (uint j=0; j<gobjects.size(); j++) { //std::cout << "gobject " << gobjects.at(j).name << '\n'; for (uint i=0; i<gobjects.at(j).faces.size(); i++) { for (int k=0; k<3; k++) { glm::vec3 v = gobjects.at(j).faces.at(i).vertices[k]; v[0] *= multFactor; v[1] *= multFactor; v[2] *= multFactor; gobjects.at(j).faces.at(i).vertices[k] = v; //std::cout << "NEW VERTEX: (" << v.x << ", " << v.y << ", " << v.z << ")\n"; } } } //std::cout << "finished scaling" << '\n'; return gobjects; } private: void skipToNextLine(ifstream& inFile) { inFile.ignore(numeric_limits<int>::max(), '\n'); } bool emptyOrCommentLine(string lineString) { return (lineString.empty() || lineString.front() == '#'); } faceData processFaceLine(istringstream& lineStream, OBJ_Structure structure) { string faceTerm; vec3_int vindices; vec3_int tindices; // vec3_int nindices; bool vts = true; faceData face; int i = 0; // Repeatedly get "v1/vt1/vn1" or similar, then parse /-delimited ints. // Ignore vector normals for now. while (lineStream >> faceTerm) { sscanf(faceTerm.c_str(), "%d/%d", &vindices[i], &tindices[i]); // nindices[i] if (structure.textureFilename.empty()) vts = false; i += 1; } // Don't forget to subtract one from all the indices, since OBJ files use // 1-based indices for (int i=0; i<(int)vindices.size(); i++) vindices[i] -= 1; if (vts) { for (int i=0; i<(int)tindices.size(); i++) tindices[i] -= 1; face = make_tuple(vindices, tindices, nullopt); } else { face = make_tuple(vindices, nullopt, nullopt); } return face; } // Don't bother having an MTL_Structure class, just use a tuple tuple<materialDict, string> loadMTL(string filename) { // Return values materialDict mtlDict; string textureFilename; // Temp vars string mtlName; float r, g, b; Colour colour; ifstream inFile; inFile.open(filename); if (inFile.fail()) { cout << "File not found." << endl; exit(1); } string lineString, linePrefix; while (getline(inFile, lineString)) { if (emptyOrCommentLine(lineString)) continue; istringstream lineStream(lineString); lineStream >> linePrefix; // use this as the conditional in an if stmt to detect failure if needed if (linePrefix == "map_Kd") { lineStream >> textureFilename; } else if (linePrefix == "newmtl") { lineStream >> mtlName; } // Assumes a "newmtl" line has come before, initialising mtlName else if (linePrefix == "Kd") { lineStream >> r >> g >> b; mtlDict.insert({mtlName, Colour(mtlName, round(255*r), round(255*g), round(255*b))}); } } inFile.close(); return make_tuple(mtlDict, textureFilename); } OBJ_Structure loadOBJpass1(string filename) { // Store all intermediate stuff in here. Use it to build a vector of // gobjects. OBJ_Structure structure; // Temp vars float a, b, c; vec3 vertex; vec2 textureVertex; faceData face; string currentObjName = "loose"; string currentObjMtlName; ifstream inFile; inFile.open(filename); if (inFile.fail()) { cout << "File not found." << endl; exit(1); } string lineString, linePrefix; while (getline(inFile, lineString)) { if (emptyOrCommentLine(lineString)) continue; istringstream lineStream(lineString); lineStream >> linePrefix; //cout << "linePrefix '" << linePrefix << "'" << endl; if (linePrefix == "mtllib") { // cout << "This should only appear once" << endl; lineStream >> structure.mtlLibFileName; // TODO: check which of these is empty, if any, and do sth appropriate tie(structure.mtlDict, structure.textureFilename) = loadMTL(structure.mtlLibFileName); } else if (linePrefix == "v") { lineStream >> a >> b >> c; vertex[0] = a; vertex[1] = b; vertex[2] = c; structure.allVertices.push_back(vertex); } else if (linePrefix == "vt") { lineStream >> a >> b; textureVertex[0] = a; textureVertex[1] = b; // Normalise texture vertices in case of erroneous .objs if (a > 1 || a < 0) { textureVertex[0] = abs(a); if (textureVertex[0] > 1) textureVertex[0] = 1 / textureVertex[0]; } if (b > 1 || b < 0) { textureVertex[1] = abs(b); if (textureVertex[1] > 1) textureVertex[1] = 1 / textureVertex[1]; } structure.allTextureVertices.push_back(textureVertex); } else if (linePrefix == "f") { face = processFaceLine(lineStream, structure); structure.faceDict.insert({currentObjName, face}); } else if (linePrefix == "o") { lineStream >> currentObjName; } // Assumes an "o" line has come before it, initialising currentObjName else if (linePrefix == "usemtl") { lineStream >> currentObjMtlName; structure.objMatNameDict.insert({currentObjName, currentObjMtlName}); } } inFile.close(); return structure; } float maxComponent(glm::vec3 v) { float greatest = std::max(std::max(v[0], v[1]), v[2]); return greatest; } // potentially most negative float minComponent(glm::vec3 v) { float smallest = std::min(std::min(v[0], v[1]), v[2]); return smallest; } };
33.48062
106
0.56263
James-Wickenden
72ef6173b28a1535cc00fc18f6393683ab11f2f5
10,181
cpp
C++
Components/Components/Logic/KalmanFilter6DOF.cpp
muellerlab/agri-fly
6851f2f207e73300b4ed9be7ec1c72c2f23eeef5
[ "BSD-2-Clause" ]
1
2022-03-09T21:31:49.000Z
2022-03-09T21:31:49.000Z
Components/Components/Logic/KalmanFilter6DOF.cpp
muellerlab/agri-fly
6851f2f207e73300b4ed9be7ec1c72c2f23eeef5
[ "BSD-2-Clause" ]
4
2022-02-11T18:24:49.000Z
2022-03-28T01:16:51.000Z
Components/Components/Logic/KalmanFilter6DOF.cpp
muellerlab/agri-fly
6851f2f207e73300b4ed9be7ec1c72c2f23eeef5
[ "BSD-2-Clause" ]
null
null
null
#include "KalmanFilter6DOF.hpp" #include <cerrno> using namespace Onboard; float const TIME_CONST_ATT_CORR = 4.0f; //[s] KalmanFilter6DOF::KalmanFilter6DOF(BaseTimer* const masterTimer) : _estimateTimer(masterTimer), _timerLastGoodMeasUpdate(masterTimer), _IMUInitialized(false), _UWBInitialized(false) { //TODO: Sensible numbers here! _initStdDevPos = 3.0f; //[m] _initStdDevVel = 3.0f; //[m/s] _initStdDevAtt_perpToGravity = 10.0f * float(M_PI) / 180.0f; //[rad] _initStdDevAtt_aboutGravity = 30.0f * float(M_PI) / 180.0f; //[rad] _measNoiseStdDevAccelerometer = 5; //[m/s**2] _measNoiseStdDevRateGyro = 0.1f; //[rad/s] _measNoiseStdDevRangeMeasurements = 0.14f; //[m] _outlierDetectionStatisticalDist = 3.0f; _numMeasRejected = 0; _numMeasRejectedSequentially = 0; _maxNumMeasRejectedSequentially = 5; // TODO: add a set function for this _numResets = 0; _lastCheckNumResets = 0; } void KalmanFilter6DOF::Reset() { _numResets++; _IMUInitialized = _UWBInitialized = false; _pos = Vec3f(0, 0, 0); _vel = Vec3f(0, 0, 0); _att = Rotationf::Identity(); _angVel = Vec3f(0, 0, 0); //Default initial covariance, should make a paramter (or something!) for (int i = 0; i < NUM_STATES; i++) { for (int j = 0; j < NUM_STATES; j++) { _cov(i, j) = 0; } } for (int i = 0; i < 3; i++) { _cov(I_POS + i, I_POS + i) = _initStdDevPos * _initStdDevPos; _cov(I_VEL + i, I_VEL + i) = _initStdDevVel * _initStdDevVel; } //TODO FIXME. This is a hack. We want to encode that we're less certain of orientation // about gravity than other two directions. Below is OK, because _att is identity, but // this isn't future-proof. Nicer would be a geometric construction, using current estimate // of gravity. _cov(I_ATT + 0, I_ATT + 0) = _initStdDevAtt_perpToGravity * _initStdDevAtt_perpToGravity; _cov(I_ATT + 1, I_ATT + 1) = _initStdDevAtt_perpToGravity * _initStdDevAtt_perpToGravity; _cov(I_ATT + 2, I_ATT + 2) = _initStdDevAtt_aboutGravity * _initStdDevAtt_aboutGravity; //estimate is valid *now*: _estimateTimer.Reset(); _timerLastGoodMeasUpdate.Reset(); _lastMeasUpdateAttCorrection = Vec3f(0, 0, 0); } void KalmanFilter6DOF::Predict(Vec3f const measGyro, Vec3f const measAcc) { if (!_IMUInitialized) { Reset(); _IMUInitialized = true; _estimateTimer.Reset(); /*Assume we're measuring gravity; construct a consistent initial attitude: * * TODO: note, this does not correctly initialise the attitude covariance * necessarily: we want large uncertainty about gravity */ errno = 0; Vec3f const expAccelerometer = _att.Inverse() * Vec3f(0, 0, 1); Vec3f const accUnitVec = measAcc.GetUnitVector(); float const cosAngleError = expAccelerometer.Dot(accUnitVec); Vec3f rotAx = (accUnitVec.Cross(expAccelerometer)); if (rotAx.GetNorm2() > 1e-6f) { rotAx = rotAx / rotAx.GetNorm2(); } else { rotAx = Vec3f(1, 0, 0); //somewhat arbitrary } float angle = acosf(cosAngleError); if (errno) { //acos failed: if (cosAngleError < 0) { angle = float(M_PI); } else { angle = 0; } } _att = _att * Rotationf::FromAxisAngle(rotAx, angle); return; } //time since last run: float const dt = _estimateTimer.GetSeconds<float>(); _estimateTimer.Reset(); if (!_UWBInitialized) { _angVel = measGyro; //do a low-pass ("complementary") estimate of attitude, using gyro & accelerometer Rotationf newAtt = _att * Rotationf::FromRotationVector(measGyro * dt); _att = newAtt; Vec3f const expAccelerometer = _att.Inverse() * Vec3f(0, 0, 1); Vec3f const accUnitVec = measAcc.GetUnitVector(); Vec3f rotAx = (accUnitVec.Cross(expAccelerometer)); if (rotAx.GetNorm2() > 1e-6f) { rotAx = rotAx / rotAx.GetNorm2(); } else { rotAx = Vec3f(1, 0, 0); //somewhat arbitrary } float const cosAngleError = expAccelerometer.Dot(accUnitVec); errno = 0; float angle = acosf(cosAngleError); if (errno) { //acos failed, or sqrtf: if (cosAngleError < 0) { angle = float(M_PI); } else { angle = 0; } } float const corrAngle = (dt / TIME_CONST_ATT_CORR) * angle; _att = _att * Rotationf::FromAxisAngle(rotAx, corrAngle); return; } //mean prediction: //we're assuming that dt**2 ~= 0 Vec3f const pos(_pos); Vec3f const vel(_vel); Rotationf const att(_att); // Vec3f const angVel(_angVel); Vec3f const acc = _att * measAcc + Vec3f(0, 0, -9.81f); _pos = pos + vel * dt; _vel = vel + acc * dt; _att = att * Rotationf::FromRotationVector(measGyro * dt); //NOTE: we're using the rate gyro to integrate, not old estimate _angVel = measGyro; float rotMat[9]; att.GetRotationMatrix(rotMat); SquareMatrix<float, NUM_STATES> f = ZeroMatrix<float, NUM_STATES, NUM_STATES>(); //del(d(pos))/del(pos) = I f(I_POS + 0, I_POS + 0) = 1; f(I_POS + 1, I_POS + 1) = 1; f(I_POS + 2, I_POS + 2) = 1; //del(d(pos))/del(vel) = I*dt f(I_POS + 0, I_VEL + 0) = dt; f(I_POS + 1, I_VEL + 1) = dt; f(I_POS + 2, I_VEL + 2) = dt; //del(d(vel))/del(vel) = I f(I_VEL + 0, I_VEL + 0) = 1; f(I_VEL + 1, I_VEL + 1) = 1; f(I_VEL + 2, I_VEL + 2) = 1; //del(d(vel))/del(att) //dt*(accMeas(1)*Rref(0, 2) - accMeas(2)*Rref(0, 1)) //dt*(accMeas(1)*Rref(1, 2) - accMeas(2)*Rref(1, 1)) //dt*(accMeas(1)*Rref(2, 2) - accMeas(2)*Rref(2, 1)) f(I_VEL + 0, I_ATT + 0) = dt * (+measAcc.y * rotMat[3 * 0 + 2] - measAcc.z * rotMat[3 * 0 + 1]); f(I_VEL + 1, I_ATT + 0) = dt * (+measAcc.y * rotMat[3 * 1 + 2] - measAcc.z * rotMat[3 * 1 + 1]); f(I_VEL + 2, I_ATT + 0) = dt * (+measAcc.y * rotMat[3 * 2 + 2] - measAcc.z * rotMat[3 * 2 + 1]); //dt*(-accMeas(0)*Rref(0, 2) + accMeas(2)*Rref(0, 0)) //dt*(-accMeas(0)*Rref(1, 2) + accMeas(2)*Rref(1, 0)) //dt*(-accMeas(0)*Rref(2, 2) + accMeas(2)*Rref(2, 0)) f(I_VEL + 0, I_ATT + 1) = dt * (-measAcc.x * rotMat[3 * 0 + 2] + measAcc.z * rotMat[3 * 0 + 0]); f(I_VEL + 1, I_ATT + 1) = dt * (-measAcc.x * rotMat[3 * 1 + 2] + measAcc.z * rotMat[3 * 1 + 0]); f(I_VEL + 2, I_ATT + 1) = dt * (-measAcc.x * rotMat[3 * 2 + 2] + measAcc.z * rotMat[3 * 2 + 0]); //dt*(accMeas(0)*Rref(0, 1) - accMeas(1)*Rref(0, 0)), //dt*(accMeas(0)*Rref(1, 1) - accMeas(1)*Rref(1, 0)), //dt*(accMeas(0)*Rref(2, 1) - accMeas(1)*Rref(2, 0)), f(I_VEL + 0, I_ATT + 2) = dt * (+measAcc.x * rotMat[3 * 0 + 1] - measAcc.y * rotMat[3 * 0 + 0]); f(I_VEL + 1, I_ATT + 2) = dt * (+measAcc.x * rotMat[3 * 1 + 1] - measAcc.y * rotMat[3 * 1 + 0]); f(I_VEL + 2, I_ATT + 2) = dt * (+measAcc.x * rotMat[3 * 2 + 1] - measAcc.y * rotMat[3 * 2 + 0]); //del(d(att))/del(att) f(I_ATT + 0, I_ATT + 0) = 1; f(I_ATT + 1, I_ATT + 0) = -(dt * measGyro.z + _lastMeasUpdateAttCorrection.z / 2.0f); f(I_ATT + 2, I_ATT + 0) = +(dt * measGyro.y + _lastMeasUpdateAttCorrection.y / 2.0f); f(I_ATT + 0, I_ATT + 1) = +(dt * measGyro.z + _lastMeasUpdateAttCorrection.z / 2.0f); f(I_ATT + 1, I_ATT + 1) = 1; f(I_ATT + 2, I_ATT + 1) = -(dt * measGyro.x + _lastMeasUpdateAttCorrection.x / 2.0f); f(I_ATT + 0, I_ATT + 2) = -(dt * measGyro.y + _lastMeasUpdateAttCorrection.y / 2.0f); f(I_ATT + 1, I_ATT + 2) = +(dt * measGyro.x + _lastMeasUpdateAttCorrection.x / 2.0f); f(I_ATT + 2, I_ATT + 2) = 1; _lastMeasUpdateAttCorrection = Vec3f(0, 0, 0); //Covariance prediction: _cov = f * _cov * f.transpose(); //add process noise: for (int i = 0; i < 3; i++) { _cov(I_VEL + i, I_VEL + i) += _measNoiseStdDevAccelerometer * _measNoiseStdDevAccelerometer * dt * dt; _cov(I_ATT + i, I_ATT + i) += _measNoiseStdDevRateGyro * _measNoiseStdDevRateGyro * dt * dt; } } void KalmanFilter6DOF::UpdateWithRangeMeasurement(Vec3f const targetPosition, float const range) { if (!_IMUInitialized) { return; } //Test for NaN in range: if (not (range == range)) { return; } _UWBInitialized = true; float const expectedRange = (_pos - targetPosition).GetNorm2(); Vec3f const targetDirection = (_pos - targetPosition) / expectedRange; //Measurement matrix: Matrix<float, 1, NUM_STATES> H; for (int i = 0; i < 3; i++) { H(0, I_POS + i) = targetDirection[i]; H(0, I_VEL + i) = 0; H(0, I_ATT + i) = 0; } //filter gain: float const innovationCov = (H * (_cov * H.transpose()))(0, 0) + _measNoiseStdDevRangeMeasurements * _measNoiseStdDevRangeMeasurements; //scalar measurement, so easy Matrix<float, NUM_STATES, 1> L = _cov * H.transpose() * (1 / innovationCov); //can now do a Mahalanobis outlier detection: float const measDistSqr = (range - expectedRange) * (range - expectedRange) / innovationCov; //scalar is easy if (measDistSqr > _outlierDetectionStatisticalDist * _outlierDetectionStatisticalDist) { //Reject this as an outlier _numMeasRejected++; _numMeasRejectedSequentially++; if (_numMeasRejectedSequentially >= _maxNumMeasRejectedSequentially) { //TODO: Is this the right action? Alternative is to force-accept the measurment. -- blame Saman. Reset(); } return; } _numMeasRejectedSequentially = 0; //state update: Matrix<float, NUM_STATES, 1> dx = L * (range - expectedRange); _pos = _pos + Vec3f(dx(I_POS + 0, 0), dx(I_POS + 1, 0), dx(I_POS + 2, 0)); _vel = _vel + Vec3f(dx(I_VEL + 0, 0), dx(I_VEL + 1, 0), dx(I_VEL + 2, 0)); _lastMeasUpdateAttCorrection = Vec3f(dx(I_ATT + 0, 0), dx(I_ATT + 1, 0), dx(I_ATT + 2, 0)); _att = _att * Rotationf::FromRotationVector(_lastMeasUpdateAttCorrection); //covariance update: _cov = (IdentityMatrix<float, NUM_STATES>() - L * H) * _cov; MakeCovarianceSymmetric(); _timerLastGoodMeasUpdate.Reset(); } void KalmanFilter6DOF::MakeCovarianceSymmetric() { for (int i = 0; i < NUM_STATES; i++) { for (int j = i + 1; j < NUM_STATES; j++) { _cov(i, j) = _cov(j, i); } } }
32.841935
126
0.615264
muellerlab
72f505ad7263cbbb422071cf83d1160c3602ebe7
5,074
cpp
C++
Game/keyconfiglabel.cpp
sethballantyne/Plexis
49b98918d9184321ba0dd449aded46b68eedb752
[ "MIT" ]
1
2021-04-14T15:06:55.000Z
2021-04-14T15:06:55.000Z
Game/keyconfiglabel.cpp
sethballantyne/Plexis
49b98918d9184321ba0dd449aded46b68eedb752
[ "MIT" ]
7
2020-05-14T02:14:26.000Z
2020-05-22T04:57:47.000Z
Game/keyconfiglabel.cpp
sethballantyne/Plexis
49b98918d9184321ba0dd449aded46b68eedb752
[ "MIT" ]
null
null
null
// Copyright(c) 2018 Seth Ballantyne <[email protected]> // // 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 "keyconfiglabel.h" #include "gameoptions.h" void KeyConfigLabel::HandleKey(unsigned char key) { if(!KeyInUse(key)) { UpdateConfig(key); changingKey = false; } else { // attempted to assign a key that's already in bound // to another option. Play a prompt indicating the error. ResourceManager::GetSoundBuffer("error3")->Play(); } } bool KeyConfigLabel::KeyInUse(unsigned char key) { array<SelectableControl ^, 1> ^controls = ParentContainer->GetControls(); for(int i = 0; i < controls->Length; i++) { if(controls[i]->GetType() == KeyConfigLabel::typeid && !ReferenceEquals(this, controls[i])) { KeyConfigLabel ^keyConfigLabel = dynamic_cast<KeyConfigLabel ^>(controls[i]); String ^keyText = Input::GetDIKAsString(key); // is the key in use? if(nullptr == keyText || keyConfigLabel->label->Text == keyText) { // if keyText evaluates to nullptr, the user has pressed a key that's not in the // lookup table used by GetDIKAsString() to retrieve the string representation of the key. // If it's not in the table, it's an invalid key for our purposes, so pretend // it's already in use; this'll force them to bind another key and play the error // sound effect. return true; } } } return false; } KeyConfigLabel::KeyConfigLabel(int x, int y, String ^font, int selectedIndex, String ^optionsKey, MenuItemContainer ^parentContainer) : ContainerControl(x, y, selectedIndex, parentContainer) { if(nullptr == optionsKey) { throw gcnew ArgumentNullException("optionsKey"); } else if(nullptr == font) { throw gcnew ArgumentNullException("font"); } else if(nullptr == parentContainer) { throw gcnew ArgumentNullException("parentContainer"); } if(String::Empty == optionsKey) { throw gcnew ArgumentException("optionsKey evaluates to String::Empty."); } else if(String::Empty == font) { throw gcnew ArgumentException("font evaluates to String::Empty."); } this->optionsKey = optionsKey; try { label = gcnew Label(x, y, font, nullptr); } catch(...) { throw; } } void KeyConfigLabel::ReceiveSceneArgs(array<Object ^, 1> ^sceneArgs) { if(firstRun) { firstRun = false; int keyValue = GameOptions::GetValue(optionsKey, -1); String ^caption = Input::GetDIKAsString(keyValue); if(nullptr == caption) { caption = "UNDEFINED"; LogManager::WriteLine(LogType::Debug, "Key assigned to {0} is an illegal value.", optionsKey); } label->Text = caption; } } void KeyConfigLabel::Update(Keys ^keyboardState, Mouse ^mouseState) { if(nullptr == keyboardState) { throw gcnew ArgumentNullException("keyboardState"); } else if(nullptr == mouseState) { throw gcnew ArgumentNullException("keyboardState"); } if(changingKey != true) { if(keyboardState->KeyPressed(DIK_RETURN)) { changingKey = true; label->Text = "PRESS A KEY"; } else if(keyboardState->KeyPressed(DIK_UP)) { ParentContainer->SelectPreviousControl(); } else if(keyboardState->KeyPressed(DIK_DOWN)) { ParentContainer->SelectNextControl(); } } else { if(mouseState->ButtonDown(0)) { HandleKey(0); } else if(mouseState->ButtonDown(1)) { HandleKey(1); } else { int pressedKey = keyboardState->PressedKey; // in the off chance that the user presses keys and mouse buttons(s) at the same time, // the keyboard takes precendence. if(pressedKey != -1) // -1 means a key hasn't been pressed. { HandleKey(pressedKey); } } } }
30.566265
133
0.645644
sethballantyne
72f5f37c1905bf7f237fd45aa63ef18e7bc77b41
11,687
cpp
C++
src/services/events/system.cpp
patrick-lafferty/saturn
6dc36adb42ad9b647704dd19247423a522eeb551
[ "BSD-3-Clause" ]
26
2018-03-19T15:59:46.000Z
2021-08-06T16:13:16.000Z
src/services/events/system.cpp
patrick-lafferty/saturn
6dc36adb42ad9b647704dd19247423a522eeb551
[ "BSD-3-Clause" ]
34
2018-01-21T17:43:29.000Z
2020-06-27T02:00:53.000Z
src/services/events/system.cpp
patrick-lafferty/saturn
6dc36adb42ad9b647704dd19247423a522eeb551
[ "BSD-3-Clause" ]
3
2019-12-08T22:26:35.000Z
2021-06-25T17:05:57.000Z
/* Copyright (c) 2017, Patrick Lafferty 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 "system.h" #include "ipc.h" #include <services.h> #include <system_calls.h> #include <saturn/wait.h> #include <saturn/parsing.h> using namespace VirtualFileSystem; namespace Event { void Log::addEntry(std::string_view entry) { entries.push_back(std::string{entry}); } int EventSystem::getFunction(std::string_view name) { if (name.compare("subscribe") == 0) { return static_cast<int>(FunctionId::Subscribe); } return -1; } void EventSystem::readFunction(uint32_t requesterTaskId, uint32_t requestId, uint32_t functionId) { describeFunction(requesterTaskId, requestId, functionId); } void EventSystem::writeFunction(uint32_t requesterTaskId, uint32_t requestId, uint32_t functionId, Vostok::ArgBuffer& args) { auto type = args.readType(); if (type != Vostok::ArgTypes::Function) { Vostok::replyWriteSucceeded(requesterTaskId, requestId, false); return; } switch(functionId) { case static_cast<uint32_t>(FunctionId::Subscribe): { auto subscriberTaskId = args.read<uint32_t>(Vostok::ArgTypes::Uint32); if (!args.hasErrors()) { subscribe(requesterTaskId, requestId, subscriberTaskId); } else { Vostok::replyWriteSucceeded(requesterTaskId, requestId, false); } break; } default: { Vostok::replyWriteSucceeded(requesterTaskId, requestId, false); } } } void EventSystem::describeFunction(uint32_t requesterTaskId, uint32_t requestId, uint32_t functionId) { ReadResult result {}; result.requestId = requestId; result.success = true; Vostok::ArgBuffer args{result.buffer, sizeof(result.buffer)}; args.writeType(Vostok::ArgTypes::Function); switch(functionId) { case static_cast<uint32_t>(FunctionId::Subscribe): { args.writeType(Vostok::ArgTypes::Uint32); args.writeType(Vostok::ArgTypes::EndArg); break; } default: { result.success = false; } } result.recipientId = requesterTaskId; send(IPC::RecipientType::TaskId, &result); } void EventSystem::subscribe(uint32_t requesterTaskId, uint32_t requestId, uint32_t subscriberTaskId) { char path[256]; memset(path, '\0', 256); sprintf(path, "/applications/%d/receive", subscriberTaskId); auto result = openSynchronous(path); if (result.success) { subscribers.push_back(result.fileDescriptor); if (!receiveSignature) { auto readResult = readSynchronous(result.fileDescriptor, 0); receiveSignature = ReceiveSignature {{}, {nullptr, 0}}; auto& sig = receiveSignature.value(); sig.result = readResult; sig.args = Vostok::ArgBuffer{&sig.result.buffer[0], 256}; } } Vostok::replyWriteSucceeded(requesterTaskId, requestId, result.success); } void EventSystem::handleOpenRequest(OpenRequest& request) { OpenResult result; result.requestId = request.requestId; result.serviceType = Kernel::ServiceType::VFS; auto words = split({request.path, strlen(request.path)}, '/'); if (words.size() == 1) { if (words[0].compare("subscribe") == 0) { Vostok::FileDescriptor descriptor; descriptor.instance = this; descriptor.functionId = 0; descriptor.type = Vostok::DescriptorType::Function; auto id = nextDescriptorId++; openDescriptors.push_back(FileDescriptor{id, descriptor}); result.fileDescriptor = id; result.success = true; } else { auto it = std::find_if(begin(logs), end(logs), [&](const auto& log) { return words[0].compare(log->name) == 0; }); if (it != end(logs)) { FileDescriptor descriptor {nextDescriptorId++, it->get()}; openDescriptors.push_back(descriptor); result.fileDescriptor = descriptor.id; result.success = true; } } } send(IPC::RecipientType::ServiceName, &result); } void EventSystem::handleCreateRequest(CreateRequest& request) { auto words = split({request.path, strlen(request.path)}, '/'); CreateResult result; result.requestId = request.requestId; result.serviceType = Kernel::ServiceType::VFS; if (words.size() == 1) { auto it = std::find_if(begin(logs), end(logs), [&](const auto& log) { return words[0].compare(log->name) == 0; }); if (it == end(logs)) { logs.push_back(std::make_unique<Log>(words[0])); result.success = true; } } send(IPC::RecipientType::ServiceName, &result); } void EventSystem::handleReadRequest(ReadRequest& request) { auto it = std::find_if(begin(openDescriptors), end(openDescriptors), [&](const auto& descriptor) { return descriptor.id == request.fileDescriptor; }); if (it != end(openDescriptors)) { if (std::holds_alternative<Vostok::FileDescriptor>(it->object)) { auto& desc = std::get<Vostok::FileDescriptor>(it->object); desc.read(request.senderTaskId, request.requestId); } } } void EventSystem::handleWriteRequest(WriteRequest& request) { WriteResult result; result.requestId = request.requestId; result.serviceType = Kernel::ServiceType::VFS; result.recipientId = request.senderTaskId; auto it = std::find_if(begin(openDescriptors), end(openDescriptors), [&](auto& d) { return d.id == request.fileDescriptor; }); if (it != end(openDescriptors)) { result.success = true; if (std::holds_alternative<Log*>(it->object)) { auto log = std::get<Log*>(it->object); std::string_view view {reinterpret_cast<char*>(&request.buffer[0]), request.writeLength}; log->addEntry(view); if (!subscribers.empty()) { broadcastEvent(view); } forwardToSerialPort(request); } else if (std::holds_alternative<Vostok::FileDescriptor>(it->object)) { auto descriptor = std::get<Vostok::FileDescriptor>(it->object); Vostok::ArgBuffer args{request.buffer, sizeof(request.buffer)}; descriptor.write(request.senderTaskId, request.requestId, args); return; } } send(IPC::RecipientType::TaskId, &result); } void EventSystem::broadcastEvent(std::string_view event) { auto signature = receiveSignature.value(); signature.args.typedBuffer = signature.result.buffer; signature.args.readType(); signature.args.write(event.data(), Vostok::ArgTypes::Cstring); for (auto subscriber : subscribers) { write(subscriber, signature.result.buffer, sizeof(signature.result.buffer)); } } void EventSystem::forwardToSerialPort(WriteRequest& request) { request.fileDescriptor = serialFileDescriptor; request.serviceType = Kernel::ServiceType::VFS; send(IPC::RecipientType::ServiceName, &request); } void EventSystem::messageLoop() { auto openResult = openSynchronous("/serial/output"); serialFileDescriptor = openResult.fileDescriptor; while (true) { IPC::MaximumMessageBuffer buffer; receive(&buffer); switch (buffer.messageNamespace) { case IPC::MessageNamespace::VFS: { switch (static_cast<MessageId>(buffer.messageId)) { case MessageId::OpenRequest: { auto request = IPC::extractMessage<OpenRequest>(buffer); handleOpenRequest(request); break; } case MessageId::CreateRequest: { auto request = IPC::extractMessage<CreateRequest>(buffer); handleCreateRequest(request); break; } case MessageId::ReadRequest: { auto request = IPC::extractMessage<ReadRequest>(buffer); handleReadRequest(request); break; } case MessageId::WriteRequest: { auto request = IPC::extractMessage<WriteRequest>(buffer); handleWriteRequest(request); break; } case MessageId::WriteResult: { break; } default: break; } break; } default: break; } } } void service() { waitForServiceRegistered(Kernel::ServiceType::VFS); Saturn::Event::waitForMount("/serial"); MountRequest request; const char* path = "/events"; memcpy(request.path, path, strlen(path) + 1); request.serviceType = Kernel::ServiceType::VFS; request.cacheable = false; send(IPC::RecipientType::ServiceName, &request); auto system = new EventSystem(); system->messageLoop(); } }
36.867508
129
0.57534
patrick-lafferty
72fabfadf143f37ccb37fb1957981107315c2112
3,480
cpp
C++
src/plugins/azoth/plugins/vader/vader.cpp
Maledictus/leechcraft
79ec64824de11780b8e8bdfd5d8a2f3514158b12
[ "BSL-1.0" ]
120
2015-01-22T14:10:39.000Z
2021-11-25T12:57:16.000Z
src/plugins/azoth/plugins/vader/vader.cpp
Maledictus/leechcraft
79ec64824de11780b8e8bdfd5d8a2f3514158b12
[ "BSL-1.0" ]
8
2015-02-07T19:38:19.000Z
2017-11-30T20:18:28.000Z
src/plugins/azoth/plugins/vader/vader.cpp
Maledictus/leechcraft
79ec64824de11780b8e8bdfd5d8a2f3514158b12
[ "BSL-1.0" ]
33
2015-02-07T16:59:55.000Z
2021-10-12T00:36:40.000Z
/********************************************************************** * LeechCraft - modular cross-platform feature rich internet client. * Copyright (C) 2006-2014 Georg Rudoy * * Distributed under the Boost Software License, Version 1.0. * (See accompanying file LICENSE or copy at https://www.boost.org/LICENSE_1_0.txt) **********************************************************************/ #include "vader.h" #include <QIcon> #include <QAction> #include <QUrl> #include <util/util.h> #include <util/xpc/util.h> #include <xmlsettingsdialog/xmlsettingsdialog.h> #include <interfaces/core/ientitymanager.h> #include <interfaces/azoth/iproxyobject.h> #include "mrimprotocol.h" #include "mrimbuddy.h" #include "vaderutil.h" #include "xmlsettingsmanager.h" namespace LC { namespace Azoth { namespace Vader { void Plugin::Init (ICoreProxy_ptr proxy) { Util::InstallTranslator ("azoth_vader"); XSD_ = std::make_shared<Util::XmlSettingsDialog> (); XSD_->RegisterObject (&XmlSettingsManager::Instance (), "azothvadersettings.xml"); CoreProxy_ = proxy; } void Plugin::SecondInit () { Proto_ = std::make_shared<MRIMProtocol> (AzothProxy_, CoreProxy_); emit gotNewProtocols ({ Proto_.get () }); } void Plugin::Release () { Proto_.reset (); } QByteArray Plugin::GetUniqueID () const { return "org.LeechCraft.Azoth.Vader"; } QString Plugin::GetName () const { return "Azoth Vader"; } QString Plugin::GetInfo () const { return tr ("Support for the Mail.ru Agent protocol."); } QIcon Plugin::GetIcon () const { static QIcon icon ("lcicons:/plugins/azoth/plugins/vader/resources/images/vader.svg"); return icon; } Util::XmlSettingsDialog_ptr Plugin::GetSettingsDialog () const { return XSD_; } QSet<QByteArray> Plugin::GetPluginClasses () const { QSet<QByteArray> classes; classes << "org.LeechCraft.Plugins.Azoth.Plugins.IProtocolPlugin"; return classes; } QObject* Plugin::GetQObject () { return this; } QList<QObject*> Plugin::GetProtocols () const { if (Proto_) return { Proto_.get () }; else return {}; } void Plugin::initPlugin (QObject *proxy) { AzothProxy_ = qobject_cast<IProxyObject*> (proxy); } void Plugin::hookEntryActionAreasRequested (LC::IHookProxy_ptr, QObject*, QObject*) { } void Plugin::hookEntryActionsRequested (LC::IHookProxy_ptr proxy, QObject *entry) { if (!qobject_cast<MRIMBuddy*> (entry)) return; if (!EntryServices_.contains (entry)) { auto list = VaderUtil::GetBuddyServices (this, SLOT (entryServiceRequested ())); for (const auto act : list) act->setProperty ("Azoth/Vader/Entry", QVariant::fromValue<QObject*> (entry)); EntryServices_ [entry] = list; } auto list = proxy->GetReturnValue ().toList (); for (const auto act : EntryServices_ [entry]) list += QVariant::fromValue<QObject*> (act); proxy->SetReturnValue (list); } void Plugin::entryServiceRequested () { const auto& url = sender ()->property ("URL").toString (); const auto buddyObj = sender ()->property ("Azoth/Vader/Entry").value<QObject*> (); const auto buddy = qobject_cast<MRIMBuddy*> (buddyObj); const auto& subst = VaderUtil::SubstituteNameDomain (url, buddy->GetHumanReadableID ()); const auto& e = Util::MakeEntity (QUrl (subst), {}, OnlyHandle | FromUserInitiated); CoreProxy_->GetEntityManager ()->HandleEntity (e); } } } } LC_EXPORT_PLUGIN (leechcraft_azoth_vader, LC::Azoth::Vader::Plugin);
24
88
0.670977
Maledictus
72fd44ad283abd8d85d93a4d070f7e9932fdb001
922
hpp
C++
Libraries/Libui/LayoutParams.hpp
Plunkerusr/podsOS
b68e2ebdaa4eb99366dea6cc5509ba0c92c3601a
[ "MIT" ]
21
2021-08-22T19:06:54.000Z
2022-03-31T12:44:30.000Z
Libraries/Libui/LayoutParams.hpp
Plunkerusr/podsOS
b68e2ebdaa4eb99366dea6cc5509ba0c92c3601a
[ "MIT" ]
1
2021-09-01T22:55:59.000Z
2021-09-08T20:52:09.000Z
Libraries/Libui/LayoutParams.hpp
Plunkerusr/podsOS
b68e2ebdaa4eb99366dea6cc5509ba0c92c3601a
[ "MIT" ]
null
null
null
#pragma once namespace UI { enum class LayoutParamsType { Default, MarginLayoutParams, LinearLayoutParams, }; struct LayoutParams { LayoutParams() = default; LayoutParams(LayoutParamsType type) : type(type) { } enum Size { WRAP_CONTENT = -2, MATCH_PARENT = -1, }; int width {}; int height {}; LayoutParamsType type {}; }; struct MarginLayoutParams : public LayoutParams { using LayoutParams::LayoutParams; MarginLayoutParams() : LayoutParams(LayoutParamsType::MarginLayoutParams) { } int left_margin {}; int top_margin {}; int right_margin {}; int bottom_margin {}; }; struct LinearLayoutParams : public MarginLayoutParams { using MarginLayoutParams::MarginLayoutParams; LinearLayoutParams() : MarginLayoutParams(LayoutParamsType::LinearLayoutParams) { } int weight {}; }; }
18.816327
66
0.64859
Plunkerusr
72fe365c0ac25e513416ba572994d39c7a0c54bf
545
cpp
C++
ICPC/Repechaje2021/base.cpp
CaDe27/Co-digos
9eea1dbf6ed06fd115391328c0a2481029c83fc0
[ "MIT" ]
null
null
null
ICPC/Repechaje2021/base.cpp
CaDe27/Co-digos
9eea1dbf6ed06fd115391328c0a2481029c83fc0
[ "MIT" ]
null
null
null
ICPC/Repechaje2021/base.cpp
CaDe27/Co-digos
9eea1dbf6ed06fd115391328c0a2481029c83fc0
[ "MIT" ]
null
null
null
#include <iostream> #include <algorithm> #include <stdio.h> #include <string> #include <vector> #include <map> #include <math.h> #include <numeric> #include <queue> #include <stack> #include <utility> #include <queue> #include <set> #include <iomanip> using namespace std; typedef int64_t ll; typedef pair<int,int> pii; #define loop(i,a,b) for(int i = a; i < b; ++i) const int maxN = 200005; int n; int main(){ ios_base::sync_with_stdio(0); cin.tie(0); //if(fopen("case.txt", "r")) freopen("case.txt", "r", stdin); return 0; }
17.580645
65
0.658716
CaDe27
72fe5603bd613549421b714a7f45b5f916b921bd
132
cpp
C++
Numbers/Fibonacci_Recursive.cpp
PhilRybka/Algorithms
86a11777aa7fc19abee845f0c18893afbd491130
[ "MIT" ]
null
null
null
Numbers/Fibonacci_Recursive.cpp
PhilRybka/Algorithms
86a11777aa7fc19abee845f0c18893afbd491130
[ "MIT" ]
null
null
null
Numbers/Fibonacci_Recursive.cpp
PhilRybka/Algorithms
86a11777aa7fc19abee845f0c18893afbd491130
[ "MIT" ]
null
null
null
//Returns the n-th element of the Fibonacci sequence int fib(int n){ if(n==1||n==2) return 1; return fib(n-2)+fib(n-1); }
16.5
52
0.613636
PhilRybka
72ffb2d48de7d5b06f9e60c525b2c3c216c1aabf
3,828
cpp
C++
aligndiff/algorithms/lcslength_ondgreedy.cpp
mogemimi/daily-snippets
d9da3db8c62538e4a37f0f6b69c5d46d55c4225f
[ "MIT" ]
14
2017-06-16T22:52:38.000Z
2022-02-14T04:11:06.000Z
aligndiff/algorithms/lcslength_ondgreedy.cpp
mogemimi/daily-snippets
d9da3db8c62538e4a37f0f6b69c5d46d55c4225f
[ "MIT" ]
2
2016-03-13T14:50:04.000Z
2019-04-01T09:53:17.000Z
aligndiff/algorithms/lcslength_ondgreedy.cpp
mogemimi/daily-snippets
d9da3db8c62538e4a37f0f6b69c5d46d55c4225f
[ "MIT" ]
2
2016-03-13T14:05:17.000Z
2018-09-18T01:28:42.000Z
// Copyright (c) 2017 mogemimi. Distributed under the MIT license. #include "aligndiff.h" #include <cassert> #include <cstdlib> namespace aligndiff { int computeLCSLength_ONDGreedyAlgorithm( const std::string& text1, const std::string& text2) { // NOTE: // This algorithm is based on Myers's An O((M+N)D) Greedy Algorithm in // "An O(ND)Difference Algorithm and Its Variations", // Algorithmica (1986), pages 251-266. if (text1.empty() || text2.empty()) { return 0; } const auto M = static_cast<int>(text1.size()); const auto N = static_cast<int>(text2.size()); const auto maxD = M + N; const auto offset = N; std::vector<int> vertices(M + N + 1); #if !defined(NDEBUG) // NOTE: // There is no need to initialize with the zero value for array elements, // but you have to assign the zero value to `vertices[1 + offset]`. std::fill(std::begin(vertices), std::end(vertices), -1); #endif vertices[1 + offset] = 0; std::vector<int> lcsLengths(M + N + 1); lcsLengths[1 + offset] = 0; for (int d = 0; d <= maxD; ++d) { const int startK = -std::min(d, (N * 2) - d); const int endK = std::min(d, (M * 2) - d); assert((-N <= startK) && (endK <= M)); assert(std::abs(startK % 2) == (d % 2)); assert(std::abs(endK % 2) == (d % 2)); assert((d > N) ? (startK == -(N * 2 - d)) : (startK == -d)); assert((d > M) ? (endK == (M * 2 - d)) : (endK == d)); for (int k = startK; k <= endK; k += 2) { assert((-N <= k) && (k <= M)); assert(std::abs(k % 2) == (d % 2)); const auto kOffset = k + offset; int x = 0; int lcsLength = 0; if (k == startK) { // NOTE: Move directly from vertex(x, y - 1) to vertex(x, y) x = vertices[kOffset + 1]; lcsLength = lcsLengths[kOffset + 1]; } else if (k == endK) { // NOTE: Move directly from vertex(x - 1, y) to vertex(x, y) x = vertices[kOffset - 1] + 1; lcsLength = lcsLengths[kOffset - 1]; } else if (vertices[kOffset - 1] < vertices[kOffset + 1]) { // NOTE: Move from vertex(k + 1) to vertex(k) // vertex(k + 1) is ahead of vertex(k - 1). assert(-N < k && k < M); assert((k != -d) && (k != -N)); assert((k != d) && (k != M)); x = vertices[kOffset + 1]; lcsLength = lcsLengths[kOffset + 1]; } else { // NOTE: Move from vertex(k - 1) to vertex(k) // vertex(k - 1) is ahead of vertex(k + 1). assert(-N < k && k < M); assert((k != -d) && (k != -N)); assert((k != d) && (k != M)); assert(vertices[kOffset - 1] >= vertices[kOffset + 1]); x = vertices[kOffset - 1] + 1; lcsLength = lcsLengths[kOffset - 1]; } // NOTE: `k` is defined from `x - y = k`. int y = x - k; assert(x >= 0 && y >= 0); #if !defined(NDEBUG) if (d == 0) { assert((x == 0) && (y == 0) && (k == 0)); } #endif while (x < M && y < N && text1[x] == text2[y]) { // NOTE: This loop finds a possibly empty sequence // of diagonal edges called a 'snake'. x += 1; y += 1; lcsLength += 1; } if (x >= M && y >= N) { return lcsLength; } vertices[kOffset] = x; lcsLengths[kOffset] = lcsLength; } } return 0; } } // namespace aligndiff
32.440678
77
0.449582
mogemimi
f4031124c33c5e509c18ccefb7d3aadddd44d520
237
hpp
C++
learnBoost/learnBoost/c++/bootregister.hpp
zhenyiyi/LearnDiary
7e88ced2c4294b5cfb7dd60c046fbc9510aab489
[ "MIT" ]
1
2019-03-18T06:58:36.000Z
2019-03-18T06:58:36.000Z
learnBoost/learnBoost/c++/bootregister.hpp
zhenyiyi/LearnDiary
7e88ced2c4294b5cfb7dd60c046fbc9510aab489
[ "MIT" ]
null
null
null
learnBoost/learnBoost/c++/bootregister.hpp
zhenyiyi/LearnDiary
7e88ced2c4294b5cfb7dd60c046fbc9510aab489
[ "MIT" ]
null
null
null
// // bootregister.hpp // learnBoost // // Created by fenglin on 2017/11/20. // Copyright © 2017年 fenglin. All rights reserved. // #ifndef bootregister_hpp #define bootregister_hpp #include <stdio.h> #endif /* bootregister_hpp */
15.8
51
0.704641
zhenyiyi
f40ad5b256b350cf7df9faaf45d8e5a0b7b3d58f
2,953
cpp
C++
src/sound/snth5.cpp
DavidLudwig/executor
eddb527850af639b3ffe314e05d92a083ba47af6
[ "MIT" ]
null
null
null
src/sound/snth5.cpp
DavidLudwig/executor
eddb527850af639b3ffe314e05d92a083ba47af6
[ "MIT" ]
null
null
null
src/sound/snth5.cpp
DavidLudwig/executor
eddb527850af639b3ffe314e05d92a083ba47af6
[ "MIT" ]
null
null
null
/* Copyright 1992 by Abacus Research and * Development, Inc. All rights reserved. */ #include <base/common.h> #include <SoundMgr.h> #include <sound/soundopts.h> using namespace Executor; /* * It's not really clear how an actual synthesizer is expected to work * with the Sound Manager's queues. In this implementation we start * the relavent command playing and see that the ROMLIB_soundcomplete() * function is called when we're done. */ BOOLEAN Executor::C_snth5(SndChannelPtr chanp, SndCommand *cmdp, ModifierStubPtr mp) { #if defined(MACOSX_) soundbuffer_t *bufp; BOOLEAN done; static BOOLEAN beenhere = 0; if(!beenhere) { /* ROMlib_soundreserve(); */ beenhere = 1; } done = true; switch(cmdp->cmd) { case initCmd: LM(SoundActive) = soundactive5; /* TODO */ break; case freeCmd: LM(SoundActive) = 0; done = false; /* TODO */ break; case quietCmd: /* TODO */ break; case flushCmd: /* TODO */ break; case waitCmd: /* TODO */ break; case pauseCmd: /* TODO */ break; case resumeCmd: /* TODO */ break; case callBackCmd: #if 0 printf("CB"); fflush(stdout); #endif chanp->callBack(chanp, cmdp); break; case syncCmd: /* TODO */ break; case availableCmd: done = false; /* TODO */ break; case bufferCmd: bufp = (soundbuffer_t *)cmdp->param2; #if 0 printf("offset = %d, nsamples = %d, rate = 0x%x\n", bufp->offset, bufp->nsamples, bufp->rate); printf("BU"); fflush(stdout); #endif ROMlib_outbuffer((char *)bufp->buf, bufp->nsamples, bufp->rate, chanp); done = false; break; case requestNextCmd: /* not needed */ case tickleCmd: /* not implemented */ case howOftenCmd: /* not implemented */ case wakeUpCmd: /* not implemented */ case noteCmd: /* not implemented */ case restCmd: /* not implemented */ case freqCmd: /* not implemented */ case ampCmd: /* not implemented */ case timbreCmd: /* not implemented */ case waveTableCmd: /* not implemented */ case phaseCmd: /* not implemented */ case soundCmd: /* not implemented */ case rateCmd: /* not implemented */ case emptyCmd: /* does nothing */ case nullCmd: /* does nothing */ case midiDataCmd: /* not implemented */ default: #if 1 printf("unexpected sound command %d\n", (LONGINT)cmdp->cmd); #endif break; } if(done) ROMlib_callcompletion(chanp); #endif return false; }
26.603604
75
0.532001
DavidLudwig
f411a425aa78cc87e1a5004a9440c1c257518beb
267
cpp
C++
Tools/CRCompilerAudio/SoundsHandler.cpp
duhone/HeadstoneHarry
961a314a0e69d67275253da802e41429cff80097
[ "MIT" ]
1
2020-02-06T16:11:02.000Z
2020-02-06T16:11:02.000Z
Tools/CRCompilerAudio/SoundsHandler.cpp
duhone/HeadstoneHarry
961a314a0e69d67275253da802e41429cff80097
[ "MIT" ]
null
null
null
Tools/CRCompilerAudio/SoundsHandler.cpp
duhone/HeadstoneHarry
961a314a0e69d67275253da802e41429cff80097
[ "MIT" ]
null
null
null
#include "StdAfx.h" #include "SoundsHandler.h" #include "SoundsCompiler.h" using namespace CR::Compiler; SoundsHandler::SoundsHandler(void) { } SoundsHandler::~SoundsHandler(void) { } INodeCompiler* SoundsHandler::StartElement() { return new SoundsCompiler(); }
14.052632
44
0.756554
duhone
f4121a8096dd1546344ae9e51201b37b92148ef1
5,841
cxx
C++
nn.cxx
pgomoluch/simple-nn
8075338939f1293824de67ce2c6a21b295d65e7e
[ "MIT" ]
null
null
null
nn.cxx
pgomoluch/simple-nn
8075338939f1293824de67ce2c6a21b295d65e7e
[ "MIT" ]
null
null
null
nn.cxx
pgomoluch/simple-nn
8075338939f1293824de67ce2c6a21b295d65e7e
[ "MIT" ]
null
null
null
#include "config.h" #include "network.h" #include "utils.h" #include <chrono> #include <cmath> #include <cstdlib> #include <fstream> #include <iostream> using namespace std; using namespace std::chrono; const char *learning_log_file = "learning_log.txt"; const char *features_train_file = "features_train.txt"; const char *features_test_file = "features_test.txt"; const char *labels_train_file = "labels_train.txt"; const char *labels_test_file = "labels_test.txt"; void test1(); void test5_learn_split(); void test6_learn_all(); void learn(const vector<vector<double> > &features, const vector<double> &labels, const Config &config); int main(int argc, const char *argv[]) { srand(time(NULL)); if (argc == 1) { test6_learn_all(); //test5_learn_split(); } else if (argc == 2) { Config config; config.load(argv[1]); vector<vector<double> > features; vector<double> labels; read_data(config.features_train.c_str(), config.labels_train.c_str(), features, labels); learn(features, labels, config); } else if (argc >= 5) // old command line interface, deprecated, use a configuration file instead { // nn <features file> <labels file> <iterations> [<first hidden layer size> [<second ...> ...]] const char *features_path = argv[1]; const char *labels_path = argv[2]; unsigned iters = atoi(argv[3]); vector<unsigned> architecture; for (int i = 4; i < argc; ++i) architecture.push_back(atoi(argv[i])); vector<vector<double> > features; vector<double> labels; read_data(features_path, labels_path, features, labels); Config config; config.iterations = iters; config.hidden_layers = architecture; config.learning_rate = 0.0000000001; learn(features, labels, config); } else { cout << "Usage: nn <configuration file>" << endl; } return 0; } void learn(const vector<vector<double> > &features, const vector<double> &labels, const Config &config) { vector<unsigned> architecture = config.hidden_layers; architecture.insert(architecture.begin(), features[0].size()); Network network(architecture); ofstream learning_log(learning_log_file); double initial_mae = network.mae(features, labels); double initial_mse = network.mse(features, labels); learning_log << 0 << " " << initial_mae << " " << initial_mse << endl; cout << "Initial MAE: " << initial_mae << endl; steady_clock::time_point t1 = steady_clock::now(); for (unsigned i = 0; i < config.iterations; ++i) { //network.train(features, labels, 100000, 0.0000000001); network.train(features, labels, 100000, config.learning_rate); double _mae = network.mae(features, labels); double _mse = network.mse(features, labels); cout << "Ep: " << i << " MAE: " << _mae << " MSE: " << _mse << endl; learning_log << i+1 << " " << _mae << " " << _mse << endl; if(i && (i % 10000 == 0)) { char filename[100]; sprintf(filename, "%s-b%d", config.network_file.c_str(), i); network.save(filename); } } steady_clock::time_point t2 = steady_clock::now(); auto duration = duration_cast<seconds>(t2 - t1).count(); cout << "Total training time: " << duration << "s." << endl; learning_log.close(); network.save(config.network_file.c_str()); Network network2(config.network_file.c_str()); double mse_result; high_resolution_clock::time_point et1 = high_resolution_clock::now(); mse_result = network2.mse(features, labels); high_resolution_clock::time_point et2 = high_resolution_clock::now(); duration = (duration_cast<milliseconds>(et2 - et1)).count(); cout << "MSE on loaded network: " << mse_result << ". Computed in " << duration << " ms." << endl; cout << "MAE on loaded network: " << network2.mae(features, labels) << endl; cout << "Total samples: " << labels.size() << endl; } void test1() { vector<vector<double> > features = {{0.0, 0.0}, {0.0, 1.0}, {1.0, 0.0}, {1.0, 1.0}}; vector<double> labels = {0.3, 0.5, 0.2, 0.4}; Network network({2, 4}); cout << "Initial MAE:" << network.mae(features, labels) << endl; for (int j=0; j < 10; j++) { network.train(features, labels, 1000, 0.001); cout << "MAE: " << network.mae(features, labels) << " MSE: " << network.mse(features, labels) << endl; } } void test5_learn_split() { vector<vector<double> > features_train, features_test; vector<double> labels_train, labels_test; read_data(features_train_file, labels_train_file, features_train, labels_train); read_data(features_test_file, labels_test_file, features_test, labels_test); Config config; config.iterations = 100; config.hidden_layers = vector<unsigned>({5,3}); config.learning_rate = 0.00000001; learn(features_train, labels_train, config); Network network3(config.network_file.c_str()); cout << "MSE (test set): " << network3.mse(features_test, labels_test) << ".\n"; cout << "MAE (test set): " << network3.mae(features_test, labels_test) << ".\n"; } void test6_learn_all() { vector<vector<double> > features; vector<double> labels; // merge train and test read_data(features_train_file, labels_train_file, features, labels); read_data(features_test_file, labels_test_file, features, labels); Config config; config.iterations = 10000; config.hidden_layers = vector<unsigned>({7,3}); config.learning_rate = 0.00000001; learn(features, labels, config); }
33.1875
104
0.624551
pgomoluch
f41386ed732c16e12d9272c3610a72b476cb478e
1,584
cpp
C++
Source/Life/Systems/Persistent/AiSystem.cpp
PsichiX/Unreal-Systems-Architecture
fb2ccb243c8e79b0890736d611db7ba536937a93
[ "Apache-2.0" ]
5
2022-02-09T21:19:03.000Z
2022-03-03T01:53:03.000Z
Source/Life/Systems/Persistent/AiSystem.cpp
PsichiX/Unreal-Systems-Architecture
fb2ccb243c8e79b0890736d611db7ba536937a93
[ "Apache-2.0" ]
null
null
null
Source/Life/Systems/Persistent/AiSystem.cpp
PsichiX/Unreal-Systems-Architecture
fb2ccb243c8e79b0890736d611db7ba536937a93
[ "Apache-2.0" ]
null
null
null
#include "Life/Systems/Persistent/AiSystem.h" #include "Systems/Public/SystemsWorld.h" #include "Life/AI/Reasoner/UtilityAiReasoner.h" #include "Life/Components/AiComponent.h" #include "Life/Components/CameraRelationComponent.h" #include "Life/Components/GodComponent.h" #include "Life/Resources/LifeSettings.h" struct Meta { float Difference = 0; float DecideDelay = 0; }; void AiSystem(USystemsWorld& Systems) { const auto* Settings = Systems.Resource<ULifeSettings>(); if (IsValid(Settings) == false) { return; } const auto& LOD = Settings->AiLOD; const auto DeltaTime = Systems.GetWorld()->GetDeltaSeconds(); const auto TimePassed = Settings->TimeScale * DeltaTime; Systems.Query<UAiComponent, UCameraRelationComponent>().ForEach( [&](auto& QueryItem) { const auto* Actor = QueryItem.Get<0>(); auto* Ai = QueryItem.Get<1>(); if (IsValid(Ai->Reasoner) == false) { return; } const auto* CameraRelation = QueryItem.Get<2>(); const auto Found = IterStdConst(LOD) .Map<Meta>( [&](const auto& Info) { const auto Difference = FMath::Abs(Info.Distance - CameraRelation->Distance); return CameraRelation->bIsVisible ? Meta{Difference, Info.DecideDelay} : Meta{Difference, Info.DecideOffscreenDelay}; }) .ComparedBy([](const auto& A, const auto& B) { return A.Difference < B.Difference; }); if (Found.IsSet()) { Ai->TryDecide(Systems, Found.GetValue().DecideDelay, TimePassed); } }); }
25.967213
69
0.649621
PsichiX
f41663583ff9e6b610256f6729cc0c92d8be0f41
92
cpp
C++
node_modules/lzz-gyp/lzz-source/smtc_Access.cpp
SuperDizor/dizornator
9f57dbb3f6af80283b4d977612c95190a3d47900
[ "ISC" ]
3
2019-09-18T16:44:33.000Z
2021-03-29T13:45:27.000Z
node_modules/lzz-gyp/lzz-source/smtc_Access.cpp
SuperDizor/dizornator
9f57dbb3f6af80283b4d977612c95190a3d47900
[ "ISC" ]
null
null
null
node_modules/lzz-gyp/lzz-source/smtc_Access.cpp
SuperDizor/dizornator
9f57dbb3f6af80283b4d977612c95190a3d47900
[ "ISC" ]
2
2019-03-29T01:06:38.000Z
2019-09-18T16:44:34.000Z
// smtc_Access.cpp // #include "smtc_Access.h" #define LZZ_INLINE inline #undef LZZ_INLINE
13.142857
25
0.76087
SuperDizor
f41d35b2f4ee2ad35d042e78b16825068ac41d7e
2,046
cpp
C++
Ch 15/15.34_35_36_37_38/main.cpp
Felon03/CppPrimer
7dc2daf59f0ae7ec5670def15cb5fab174fe9780
[ "Apache-2.0" ]
null
null
null
Ch 15/15.34_35_36_37_38/main.cpp
Felon03/CppPrimer
7dc2daf59f0ae7ec5670def15cb5fab174fe9780
[ "Apache-2.0" ]
null
null
null
Ch 15/15.34_35_36_37_38/main.cpp
Felon03/CppPrimer
7dc2daf59f0ae7ec5670def15cb5fab174fe9780
[ "Apache-2.0" ]
null
null
null
// 15.34 针对图15.3(pp565)构建的表达式: // (a) 列举出在处理表达式的过程中执行的所有构造函数 // Query q = Query("fiery") & Query("bird") | Query("wind"); // 1: Query::Query(const std::string &s) where s = "fiery", "bird" and "wind" // 2: WordQuery::WordQuery(const std::string &s) where s = "fiery", "bird" and "wind" // 3: AndQuery::AndQuery(const Query &left, const Query &right) // 4: BinaryQuery::BinayQuery(const Query &l, const Query &r, std::string s) where s = "&" // 5: Query::Query(std::shared_ptr<Query_base> query) 2 times // 6: OrQuery::OrQuery(const Query &left, const Query &right) // 7: BinaryQuery::BinaryQuery(const Query &l, const Query &r, std::string s) where s = "|" // 8: Quer::Query(std::shared_ptr<Query_base> query) 2 times // // (b) 列举出cout<<q所调用的rep // // Query::rep() // BinaryQuery::rep() // Query::rep() // WordQuery::rep() // Query::rep() // BinaryQuery::rep() // Query::rep() // WordQuery::rep() // Query::rep() // WordQuery::rep() // ((fiery & bird) | wind) // // (c) 列举出q.eval()所调用的eval // // 15.35 实现Query类和Query_base类,其中需要定义rep无需定义eval // // 15.36 在构造函数和rep成员中添加打印语句,运行代码以检验(a)(b)的回答是否正确 // 需要定义eval /* (a) WordQuery::WordQuery(wind) Query::Query(const std::sting &s) where s= wind WordQuery::WordQuery(bird) Query::Query(const std::sting &s) where s= bird WordQuery::WordQuery(fiery) Query::Query(const std::sting &s) where s= fiery BinayQuery::BinaryQuery() where s=& AndQuery::AndQuery() BinayQuery::BinaryQuery() where s=| OrQuery::OrQuery() (b) Query::rep() BinaryQuery::rep() Query::rep() WordQuery::rep() Query::rep() BinaryQuery::rep() Query::rep() WordQuery::rep() Query::rep() WordQuery::rep() ((fiery & bird) | wind) */ #include <iostream> #include <string> #include <vector> #include <memory> #include <fstream> #include "queryresult.h" #include "textquery.h" #include "query_base.h" #include "query.h" #include "andquery.h" #include "orquery.h" int main() { std::ifstream file("data/story.txt"); TextQuery tQuery(file); Query q = Query("fiery") & Query("bird") | Query("wind"); std::cout << q << std::endl; return 0; }
25.575
91
0.668133
Felon03
f41d5caa99623ed28364db2edb2e52236fad31b4
6,498
cxx
C++
tomviz/Module.cxx
yijiang1/tomviz
93bf1b0f3ebc1d55db706184339a94660fb08d91
[ "BSD-3-Clause" ]
null
null
null
tomviz/Module.cxx
yijiang1/tomviz
93bf1b0f3ebc1d55db706184339a94660fb08d91
[ "BSD-3-Clause" ]
null
null
null
tomviz/Module.cxx
yijiang1/tomviz
93bf1b0f3ebc1d55db706184339a94660fb08d91
[ "BSD-3-Clause" ]
1
2021-01-14T02:25:32.000Z
2021-01-14T02:25:32.000Z
/****************************************************************************** This source file is part of the tomviz project. Copyright Kitware, Inc. This source code is released under the New BSD License, (the "License"). 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 "Module.h" #include "ActiveObjects.h" #include "DataSource.h" #include "pqProxiesWidget.h" #include "pqView.h" #include "Utilities.h" #include "vtkNew.h" #include "vtkSmartPointer.h" #include "vtkSMPropertyHelper.h" #include "vtkSMSessionProxyManager.h" #include "vtkSMSourceProxy.h" #include "vtkSMTransferFunctionManager.h" #include "vtkSMViewProxy.h" namespace tomviz { class Module::MInternals { vtkSmartPointer<vtkSMProxy> DetachedColorMap; vtkSmartPointer<vtkSMProxy> DetachedOpacityMap; public: vtkWeakPointer<vtkSMProxy> ColorMap; vtkWeakPointer<vtkSMProxy> OpacityMap; vtkSMProxy* detachedColorMap() { if (!this->DetachedColorMap) { static unsigned int colorMapCounter=0; colorMapCounter++; vtkSMSessionProxyManager* pxm = ActiveObjects::instance().proxyManager(); vtkNew<vtkSMTransferFunctionManager> tfmgr; this->DetachedColorMap = tfmgr->GetColorTransferFunction(QString("ModuleColorMap%1") .arg(colorMapCounter).toLatin1().data(), pxm); this->DetachedOpacityMap = vtkSMPropertyHelper(this->DetachedColorMap, "ScalarOpacityFunction").GetAsProxy(); } return this->DetachedColorMap; } vtkSMProxy* detachedOpacityMap() { this->detachedColorMap(); return this->DetachedOpacityMap; } }; //----------------------------------------------------------------------------- Module::Module(QObject* parentObject) : Superclass(parentObject), UseDetachedColorMap(false), Internals(new Module::MInternals()) { } //----------------------------------------------------------------------------- Module::~Module() { } //----------------------------------------------------------------------------- bool Module::initialize(DataSource* dataSource, vtkSMViewProxy* view) { this->View = view; this->ADataSource = dataSource; if (this->View && this->ADataSource) { // FIXME: we're connecting this too many times. Fix it. tomviz::convert<pqView*>(view)->connect( this->ADataSource, SIGNAL(dataChanged()), SLOT(render())); } return (this->View && this->ADataSource); } //----------------------------------------------------------------------------- vtkSMViewProxy* Module::view() const { return this->View; } //----------------------------------------------------------------------------- DataSource* Module::dataSource() const { return this->ADataSource; } //----------------------------------------------------------------------------- void Module::addToPanel(pqProxiesWidget* panel) { if (this->UseDetachedColorMap) { // add color map to the panel, since it's detached from the dataSource. vtkSMProxy* lut = this->colorMap(); QStringList list; list << "Mapping Data" << "EnableOpacityMapping" << "RGBPoints" << "ScalarOpacityFunction" << "UseLogScale"; panel->addProxy(lut, "Module Color Map", list, true); } } //----------------------------------------------------------------------------- void Module::setUseDetachedColorMap(bool val) { this->UseDetachedColorMap = val; if (this->isColorMapNeeded() == false) { return; } if (this->UseDetachedColorMap) { this->Internals->ColorMap = this->Internals->detachedColorMap(); this->Internals->OpacityMap = this->Internals->detachedOpacityMap(); tomviz::rescaleColorMap(this->Internals->ColorMap, this->dataSource()); } else { this->Internals->ColorMap = NULL; this->Internals->OpacityMap = NULL; } this->updateColorMap(); } //----------------------------------------------------------------------------- vtkSMProxy* Module::colorMap() const { return this->useDetachedColorMap()? this->Internals->ColorMap.GetPointer(): this->dataSource()->colorMap(); } //----------------------------------------------------------------------------- vtkSMProxy* Module::opacityMap() const { Q_ASSERT(this->Internals->ColorMap || !this->UseDetachedColorMap); return this->useDetachedColorMap()? this->Internals->OpacityMap.GetPointer(): this->dataSource()->opacityMap(); } //----------------------------------------------------------------------------- bool Module::serialize(pugi::xml_node& ns) const { if (this->isColorMapNeeded()) { ns.append_attribute("use_detached_colormap").set_value(this->UseDetachedColorMap? 1 : 0); if (this->UseDetachedColorMap) { pugi::xml_node nodeL = ns.append_child("ColorMap"); pugi::xml_node nodeS = ns.append_child("OpacityMap"); // using detached color map, so we need to save the local color map. if (tomviz::serialize(this->colorMap(), nodeL) == false || tomviz::serialize(this->opacityMap(), nodeS) == false) { return false; } } } return true; } //----------------------------------------------------------------------------- bool Module::deserialize(const pugi::xml_node& ns) { if (this->isColorMapNeeded()) { bool dcm = ns.attribute("use_detached_colormap").as_int(0) == 1; if (dcm && ns.child("ColorMap")) { if (!tomviz::deserialize(this->Internals->detachedColorMap(), ns.child("ColorMap"))) { qCritical("Failed to deserialze ColorMap"); return false; } } if (dcm && ns.child("OpacityMap")) { if (!tomviz::deserialize(this->Internals->detachedOpacityMap(), ns.child("OpacityMap"))) { qCritical("Failed to deserialze OpacityMap"); return false; } } this->setUseDetachedColorMap(dcm); } return true; } //----------------------------------------------------------------------------- } // end of namespace tomviz
30.223256
103
0.544629
yijiang1
f420330cd14e6e035795bb4f65932d3ceb96aeb6
14,297
cpp
C++
nntrainer/src/databuffer.cpp
dongju-chae/nntrainer
9742569355e1d787ccb4818b7c827bc95662cbe9
[ "Apache-2.0" ]
1
2022-03-27T18:56:11.000Z
2022-03-27T18:56:11.000Z
nntrainer/src/databuffer.cpp
dongju-chae/nntrainer
9742569355e1d787ccb4818b7c827bc95662cbe9
[ "Apache-2.0" ]
2
2021-04-19T11:42:07.000Z
2021-04-21T10:26:04.000Z
nntrainer/src/databuffer.cpp
dongju-chae/nntrainer
9742569355e1d787ccb4818b7c827bc95662cbe9
[ "Apache-2.0" ]
null
null
null
/** * Copyright (C) 2019 Samsung Electronics Co., Ltd. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * * @file databuffer.cpp * @date 04 December 2019 * @brief This is buffer object to handle big data * @see https://github.com/nnstreamer/nntrainer * @author Jijoong Moon <[email protected]> * @bug No known bugs except for NYI items * */ #include <cassert> #include <climits> #include <condition_variable> #include <cstring> #include <databuffer.h> #include <databuffer_util.h> #include <functional> #include <iomanip> #include <mutex> #include <nntrainer_error.h> #include <nntrainer_log.h> #include <parse_util.h> #include <sstream> #include <stdexcept> #include <stdio.h> #include <stdlib.h> #include <thread> #include <util_func.h> std::exception_ptr globalExceptionPtr = nullptr; namespace nntrainer { constexpr char USER_DATA[] = "user_data"; std::mutex data_lock; std::mutex readyTrainData; std::mutex readyValData; std::mutex readyTestData; std::condition_variable cv_train; std::condition_variable cv_val; std::condition_variable cv_test; DataBuffer::DataBuffer(DataBufferType type) : train_running(), val_running(), test_running(), train_thread(), val_thread(), test_thread(), data_buffer_type(type), user_data(nullptr) { SET_VALIDATION(false); class_num = 0; cur_train_bufsize = 0; cur_val_bufsize = 0; cur_test_bufsize = 0; train_bufsize = 0; val_bufsize = 0; test_bufsize = 0; max_train = 0; max_val = 0; max_test = 0; rest_train = 0; rest_val = 0; rest_test = 0; batch_size = 0; train_running = false; val_running = false; test_running = false; trainReadyFlag = DATA_NOT_READY; valReadyFlag = DATA_NOT_READY; testReadyFlag = DATA_NOT_READY; rng.seed(getSeed()); }; int DataBuffer::rangeRandom(int min, int max) { std::uniform_int_distribution<int> dist(min, max); return dist(rng); } int DataBuffer::run(BufferType type) { int status = ML_ERROR_NONE; switch (type) { case BufferType::BUF_TRAIN: if (trainReadyFlag == DATA_ERROR) return ML_ERROR_INVALID_PARAMETER; if (validation[DATA_TRAIN]) { this->train_running = true; this->train_thread = std::thread(&DataBuffer::updateData, this, type); if (globalExceptionPtr) { try { std::rethrow_exception(globalExceptionPtr); } catch (const std::exception &ex) { std::cout << ex.what() << "\n"; return ML_ERROR_INVALID_PARAMETER; } } } else { ml_loge("Error: Training Data Set is not valid"); return ML_ERROR_INVALID_PARAMETER; } break; case BufferType::BUF_VAL: if (valReadyFlag == DATA_ERROR) return ML_ERROR_INVALID_PARAMETER; if (validation[DATA_VAL]) { this->val_running = true; this->val_thread = std::thread(&DataBuffer::updateData, this, type); if (globalExceptionPtr) { try { std::rethrow_exception(globalExceptionPtr); } catch (const std::exception &ex) { std::cout << ex.what() << "\n"; return ML_ERROR_INVALID_PARAMETER; } } } else { ml_loge("Error: Validation Data Set is not valid"); return ML_ERROR_INVALID_PARAMETER; } break; case BufferType::BUF_TEST: if (testReadyFlag == DATA_ERROR) return ML_ERROR_INVALID_PARAMETER; if (validation[DATA_TEST]) { this->test_running = true; this->test_thread = std::thread(&DataBuffer::updateData, this, type); if (globalExceptionPtr) { try { std::rethrow_exception(globalExceptionPtr); } catch (const std::exception &ex) { std::cout << ex.what() << "\n"; return ML_ERROR_INVALID_PARAMETER; } } } else { ml_loge("Error: Test Data Set is not valid"); return ML_ERROR_INVALID_PARAMETER; } break; default: ml_loge("Error: Not Supported Data Type"); status = ML_ERROR_INVALID_PARAMETER; break; } return status; } int DataBuffer::clear(BufferType type) { int status = ML_ERROR_NONE; NN_EXCEPTION_NOTI(DATA_NOT_READY); switch (type) { case BufferType::BUF_TRAIN: { train_running = false; if (validation[DATA_TRAIN] && true == train_thread.joinable()) train_thread.join(); this->train_data.clear(); this->train_data_label.clear(); this->cur_train_bufsize = 0; this->rest_train = max_train; } break; case BufferType::BUF_VAL: { val_running = false; if (validation[DATA_VAL] && true == val_thread.joinable()) val_thread.join(); this->val_data.clear(); this->val_data_label.clear(); this->cur_val_bufsize = 0; this->rest_val = max_val; } break; case BufferType::BUF_TEST: { test_running = false; if (validation[DATA_TEST] && true == test_thread.joinable()) test_thread.join(); this->test_data.clear(); this->test_data_label.clear(); this->cur_test_bufsize = 0; this->rest_test = max_test; } break; default: ml_loge("Error: Not Supported Data Type"); status = ML_ERROR_INVALID_PARAMETER; break; } return status; } int DataBuffer::clear() { unsigned int i; int status = ML_ERROR_NONE; for (i = (int)BufferType::BUF_TRAIN; i <= (int)BufferType::BUF_TEST; ++i) { BufferType type = static_cast<BufferType>(i); status = this->clear(type); if (status != ML_ERROR_NONE) { ml_loge("Error: error occurred during clearing"); return status; } } return status; } bool DataBuffer::getDataFromBuffer(BufferType type, float *out, float *label) { using QueueType = std::vector<std::vector<float>>; auto wait_for_data_fill = [](std::mutex &ready_mutex, std::condition_variable &cv, DataStatus &flag, const unsigned int batch_size, QueueType &queue) { while (true) { std::unique_lock<std::mutex> ul(ready_mutex); cv.wait(ul, [&]() -> bool { return flag; }); if (flag == DATA_ERROR || flag == DATA_END) return queue.size() < batch_size ? false : true; if (flag == DATA_READY && queue.size() >= batch_size) return true; } throw std::logic_error("[getDataFromBuffer] control should not reach here"); }; auto fill_bundled_data_from_queue = [](std::mutex &q_lock, QueueType &q, const unsigned int batch_size, const unsigned int feature_size, float *buf) { for (unsigned int b = 0; b < batch_size; ++b) std::copy(q[b].begin(), q[b].begin() + feature_size, buf + b * feature_size); q_lock.lock(); q.erase(q.begin(), q.begin() + batch_size); q_lock.unlock(); }; /// facade that wait for the databuffer to be filled and pass it to outparam /// note that batch_size is passed as an argument because it can vary by /// BufferType::BUF_TYPE later... auto fill_out_params = [&](std::mutex &ready_mutex, std::condition_variable &cv, DataStatus &flag, QueueType &data_q, QueueType &label_q, const unsigned int batch_size, unsigned int &cur_bufsize) { if (!wait_for_data_fill(ready_mutex, cv, flag, batch_size, data_q)) { return false; } fill_bundled_data_from_queue(data_lock, data_q, batch_size, this->input_dim.getFeatureLen(), out); fill_bundled_data_from_queue(data_lock, label_q, batch_size, this->class_num, label); cur_bufsize -= batch_size; return true; }; switch (type) { case BufferType::BUF_TRAIN: if (!fill_out_params(readyTrainData, cv_train, trainReadyFlag, train_data, train_data_label, batch_size, cur_train_bufsize)) return false; break; case BufferType::BUF_VAL: if (!fill_out_params(readyValData, cv_val, valReadyFlag, val_data, val_data_label, batch_size, cur_val_bufsize)) return false; break; case BufferType::BUF_TEST: if (!fill_out_params(readyTestData, cv_test, testReadyFlag, test_data, test_data_label, batch_size, cur_test_bufsize)) return false; break; default: ml_loge("Error: Not Supported Data Type"); return false; break; } return true; } int DataBuffer::setClassNum(unsigned int num) { int status = ML_ERROR_NONE; if (num <= 0) { ml_loge("Error: number of class should be bigger than 0"); SET_VALIDATION(false); return ML_ERROR_INVALID_PARAMETER; } if (class_num != 0 && class_num != num) { ml_loge("Error: number of class should be same with number of label label"); SET_VALIDATION(false); return ML_ERROR_INVALID_PARAMETER; } class_num = num; return status; } int DataBuffer::setBufSize(unsigned int size) { int status = ML_ERROR_NONE; train_bufsize = size; val_bufsize = size; test_bufsize = size; return status; } int DataBuffer::setBatchSize(unsigned int size) { int status = ML_ERROR_NONE; if (size == 0) { ml_loge("Error: batch size must be greater than 0"); SET_VALIDATION(false); return ML_ERROR_INVALID_PARAMETER; } batch_size = size; return status; } int DataBuffer::init() { if (batch_size == 0) { ml_loge("Error: batch size must be greater than 0"); SET_VALIDATION(false); return ML_ERROR_INVALID_PARAMETER; } /** for now, train_bufsize, val_bufsize and test_bufsize are same value */ if (train_bufsize < batch_size) { if (train_bufsize > 1) { ml_logw("Dataset buffer size reset to be at least batch size"); } train_bufsize = batch_size; val_bufsize = batch_size; test_bufsize = batch_size; } if (!class_num) { ml_loge("Error: number of class must be set"); SET_VALIDATION(false); return ML_ERROR_INVALID_PARAMETER; } if (!this->input_dim.getFeatureLen()) { ml_loge("Error: feature size must be set"); SET_VALIDATION(false); return ML_ERROR_INVALID_PARAMETER; } this->cur_train_bufsize = 0; this->cur_val_bufsize = 0; this->cur_test_bufsize = 0; readyTrainData.lock(); trainReadyFlag = DATA_NOT_READY; readyTrainData.unlock(); readyValData.lock(); valReadyFlag = DATA_NOT_READY; readyValData.unlock(); readyTestData.lock(); testReadyFlag = DATA_NOT_READY; readyTestData.unlock(); return ML_ERROR_NONE; } int DataBuffer::setFeatureSize(TensorDim indim) { int status = ML_ERROR_NONE; input_dim = indim; return status; } void DataBuffer::displayProgress(const int count, BufferType type, float loss) { int barWidth = 20; float max_size = max_train; switch (type) { case BufferType::BUF_TRAIN: max_size = max_train; break; case BufferType::BUF_VAL: max_size = max_val; break; case BufferType::BUF_TEST: max_size = max_test; break; default: ml_loge("Error: Not Supported Data Type"); break; } std::stringstream ssInt; ssInt << count * batch_size; std::string str = ssInt.str(); int len = str.length(); if (max_size == 0) { int pad_left = (barWidth - len) / 2; int pad_right = barWidth - pad_left - len; std::string out_str = std::string(pad_left, ' ') + str + std::string(pad_right, ' '); std::cout << " [ "; std::cout << out_str; std::cout << " ] " << " ( Training Loss: " << loss << " )\r"; } else { float progress; if (batch_size > max_size) progress = 1.0; else progress = (((float)(count * batch_size)) / max_size); int pos = barWidth * progress; std::cout << " [ "; for (int l = 0; l < barWidth; ++l) { if (l <= pos) std::cout << "="; else std::cout << " "; } std::cout << " ] " << int(progress * 100.0) << "% ( Training Loss: " << loss << " )\r"; } std::cout.flush(); } int DataBuffer::setProperty(std::vector<void *> values) { int status = ML_ERROR_NONE; std::vector<std::string> properties; for (unsigned int i = 0; i < values.size(); ++i) { char *key_ptr = (char *)values[i]; std::string key = key_ptr; std::string value; /** Handle the user_data as a special case */ if (key == USER_DATA) { /** This ensures that a valid user_data element is passed by the user */ if (i + 1 >= values.size()) return ML_ERROR_INVALID_PARAMETER; this->user_data = values[i + 1]; /** As values of i+1 is consumed, increase i by 1 */ i++; } else { properties.push_back(key); continue; } } status = setProperty(properties); return status; } int DataBuffer::setProperty(std::vector<std::string> values) { int status = ML_ERROR_NONE; for (unsigned int i = 0; i < values.size(); ++i) { std::string key; std::string value; status = getKeyValue(values[i], key, value); NN_RETURN_STATUS(); unsigned int type = parseDataProperty(key); if (value.empty()) return ML_ERROR_INVALID_PARAMETER; status = setProperty(static_cast<PropertyType>(type), value); NN_RETURN_STATUS(); } return status; } int DataBuffer::setProperty(const PropertyType type, std::string &value) { int status = ML_ERROR_NONE; unsigned int size = 0; switch (type) { case PropertyType::buffer_size: status = setUint(size, value); NN_RETURN_STATUS(); status = this->setBufSize(size); NN_RETURN_STATUS(); break; default: ml_loge("Error: Unknown Data Buffer Property Key"); status = ML_ERROR_INVALID_PARAMETER; break; } return status; } int DataBuffer::setGeneratorFunc(BufferType type, datagen_cb func) { return ML_ERROR_NOT_SUPPORTED; } int DataBuffer::setDataFile(DataType type, std::string path) { return ML_ERROR_NOT_SUPPORTED; } } /* namespace nntrainer */
27.441459
80
0.650206
dongju-chae
f421a9c67194078f59b1357e593efd2c97a4777d
5,110
cpp
C++
src/ClientLib/VisualEntity.cpp
ImperatorS79/BurgWar
5d8282513945e8f25e30d8491639eb297bfc0317
[ "MIT" ]
null
null
null
src/ClientLib/VisualEntity.cpp
ImperatorS79/BurgWar
5d8282513945e8f25e30d8491639eb297bfc0317
[ "MIT" ]
null
null
null
src/ClientLib/VisualEntity.cpp
ImperatorS79/BurgWar
5d8282513945e8f25e30d8491639eb297bfc0317
[ "MIT" ]
null
null
null
// Copyright (C) 2020 Jérôme Leclercq // This file is part of the "Burgwar" project // For conditions of distribution and use, see copyright notice in LICENSE #include <ClientLib/VisualEntity.hpp> #include <ClientLib/LocalLayerEntity.hpp> #include <NDK/Components/GraphicsComponent.hpp> #include <NDK/Components/NodeComponent.hpp> #include <NDK/World.hpp> namespace bw { VisualEntity::VisualEntity(Ndk::World& renderWorld, LocalLayerEntityHandle layerEntityHandle, int baseRenderOrder) : m_entity(renderWorld.CreateEntity()), m_layerEntity(std::move(layerEntityHandle)), m_baseRenderOrder(baseRenderOrder) { m_entity->AddComponent<Ndk::NodeComponent>(); m_entity->AddComponent<Ndk::GraphicsComponent>(); m_layerEntity->RegisterVisualEntity(this); } VisualEntity::VisualEntity(Ndk::World& renderWorld, LocalLayerEntityHandle layerEntityHandle, const Nz::Node& parentNode, int baseRenderOrder) : VisualEntity(renderWorld, std::move(layerEntityHandle), baseRenderOrder) { m_entity->GetComponent<Ndk::NodeComponent>().SetParent(parentNode); } VisualEntity::VisualEntity(VisualEntity&& entity) noexcept : m_hoveringRenderables(std::move(entity.m_hoveringRenderables)), m_entity(std::move(entity.m_entity)), m_layerEntity(std::move(entity.m_layerEntity)), m_baseRenderOrder(entity.m_baseRenderOrder) { m_layerEntity->NotifyVisualEntityMoved(&entity, this); } VisualEntity::~VisualEntity() { if (m_layerEntity) m_layerEntity->UnregisterVisualEntity(this); } void VisualEntity::Update(const Nz::Vector2f& position, const Nz::Quaternionf& rotation, const Nz::Vector2f& scale) { auto& visualNode = m_entity->GetComponent<Ndk::NodeComponent>(); visualNode.SetPosition(position); visualNode.SetRotation(rotation); visualNode.SetScale(scale); Nz::Vector2f absolutePosition = Nz::Vector2f(visualNode.GetPosition(Nz::CoordSys_Global)); absolutePosition.x = std::floor(absolutePosition.x); absolutePosition.y = std::floor(absolutePosition.y); visualNode.SetPosition(absolutePosition, Nz::CoordSys_Global); if (!m_hoveringRenderables.empty()) { auto& visualGfx = m_entity->GetComponent<Ndk::GraphicsComponent>(); Nz::Vector3f absoluteScale = visualNode.GetScale(Nz::CoordSys_Global); Nz::Vector2f positiveScale(std::abs(absoluteScale.x), std::abs(absoluteScale.y)); const Nz::Boxf& aabb = visualGfx.GetAABB(); float halfHeight = aabb.height / 2.f; Nz::Vector3f center = aabb.GetCenter(); for (auto& hoveringRenderable : m_hoveringRenderables) { auto& node = hoveringRenderable.entity->GetComponent<Ndk::NodeComponent>(); node.SetPosition(center.x, center.y - (halfHeight + hoveringRenderable.offset) * absoluteScale.y); node.SetScale(positiveScale); } } } void VisualEntity::AttachHoveringRenderables(std::initializer_list<Nz::InstancedRenderableRef> renderables, std::initializer_list<Nz::Matrix4f> offsetMatrices, float hoverOffset, std::initializer_list<int> renderOrders) { std::size_t renderableCount = renderables.size(); assert(renderableCount == offsetMatrices.size()); assert(renderableCount == renderOrders.size()); assert(renderables.size() > 0); auto& hoveringRenderable = m_hoveringRenderables.emplace_back(); hoveringRenderable.entity = m_entity->GetWorld()->CreateEntity(); hoveringRenderable.entity->AddComponent<Ndk::NodeComponent>(); hoveringRenderable.offset = hoverOffset; auto& gfxComponent = hoveringRenderable.entity->AddComponent<Ndk::GraphicsComponent>(); auto renderableIt = renderables.begin(); auto renderOrderIt = renderOrders.begin(); auto matrixIt = offsetMatrices.begin(); for (std::size_t i = 0; i < renderableCount; ++i) gfxComponent.Attach(*renderableIt++, *matrixIt++, m_baseRenderOrder + *renderOrderIt++); } void VisualEntity::AttachRenderable(Nz::InstancedRenderableRef renderable, const Nz::Matrix4f& offsetMatrix, int renderOrder) { m_entity->GetComponent<Ndk::GraphicsComponent>().Attach(std::move(renderable), offsetMatrix, m_baseRenderOrder + renderOrder); } void VisualEntity::DetachRenderable(const Nz::InstancedRenderableRef& renderable) { m_entity->GetComponent<Ndk::GraphicsComponent>().Detach(renderable); } void VisualEntity::UpdateRenderableMatrix(const Nz::InstancedRenderableRef& renderable, const Nz::Matrix4f& offsetMatrix) { m_entity->GetComponent<Ndk::GraphicsComponent>().UpdateLocalMatrix(renderable, offsetMatrix); } void VisualEntity::UpdateRenderableRenderOrder(const Nz::InstancedRenderableRef& renderable, int renderOrder) { m_entity->GetComponent<Ndk::GraphicsComponent>().UpdateRenderOrder(renderable, m_baseRenderOrder + renderOrder); } void VisualEntity::DetachHoveringRenderables(std::initializer_list<Nz::InstancedRenderableRef> renderables) { for (auto it = m_hoveringRenderables.begin(); it != m_hoveringRenderables.end(); ++it) { auto& hoveringRenderable = *it; if (std::equal(hoveringRenderable.renderables.begin(), hoveringRenderable.renderables.end(), renderables.begin(), renderables.end())) { m_hoveringRenderables.erase(it); break; } } } }
38.421053
220
0.76908
ImperatorS79
f4258645452b668d1edcc886ed26b657edee8127
8,535
cpp
C++
NYUCodebase/hw05/Entity.cpp
MarcNYU/Game-Files
43781cae89ea02d18930b1b2ead04db400c7f1dd
[ "Artistic-2.0" ]
null
null
null
NYUCodebase/hw05/Entity.cpp
MarcNYU/Game-Files
43781cae89ea02d18930b1b2ead04db400c7f1dd
[ "Artistic-2.0" ]
null
null
null
NYUCodebase/hw05/Entity.cpp
MarcNYU/Game-Files
43781cae89ea02d18930b1b2ead04db400c7f1dd
[ "Artistic-2.0" ]
null
null
null
// // Entity.cpp // NYUCodebase // // Created by Marcus Williams on 2/20/15. // Copyright (c) 2015 Ivan Safrin. All rights reserved. // #include <SDL.h> #include <SDL_opengl.h> #include <SDL_image.h> #include <vector> #include "Entity.h" // 60 FPS (1.0f/60.0f) #define FIXED_TIMESTEP 0.0166666f #define MAX_TIMESTEPS 6 float timeLeftOver = 0.0f; void Entity::Render(float elapsed) { // sprite.u = 0.1;//increment .1 // sprite.v = 0.0;//0 // sprite.v = 0.23;//1 // sprite.v = 0.45;//2 // sprite.v = 0.7;//3 if (name == "player") { sprite.width = 0.104; sprite.height = 0.22; sprite.Draw(scale); std::vector<float> idel_r_s = {0.0, 0.1}; std::vector<float> idel_r = {0.1, 0.1, 0.1, 0.1, 0.3}; std::vector<float> run_r_s = {0.1, 0.2, 0.1, 0.0}; std::vector<float> run_r = {0.1, 0.2, 0.1, 0.0}; std::vector<float> jump_r_s = {0.3, 0.4}; std::vector<float> jump_r = {0.3, 0.4}; std::vector<float> idel_l_s = {0.9, 0.8}; std::vector<float> idel_l = {0.8, 0.8, 0.8, 0.8, 0.6}; std::vector<float> run_l_s = {0.8, 0.7, 0.8, 0.9}; std::vector<float> run_l = {0.8, 0.7, 0.8, 0.9}; std::vector<float> jump_l_s = {0.6, 0.5}; std::vector<float> jump_l = {0.6, 0.5}; animationElapsed += elapsed; if(animationElapsed > 1.0/framesPerSecond) { currentIndex++; animationElapsed = 0.0; } const Uint8 *keys = SDL_GetKeyboardState(NULL); if (keys[SDL_SCANCODE_SPACE]) { if(keys[SDL_SCANCODE_RIGHT]) { if (collidedBottom) { //Rigth Running Animation sprite.v = 0.45; for (currentIndex; currentIndex < run_r_s.size(); currentIndex++) { sprite.u = run_r_s[currentIndex]; } if(currentIndex > run_r_s.size()) { currentIndex = 0; } } } else if(keys[SDL_SCANCODE_LEFT]) { if (collidedBottom) { //Left Running Animation sprite.v = 0.45; for (currentIndex; currentIndex < run_l_s.size(); currentIndex++) { sprite.u = run_l_s[currentIndex]; } } } else if(keys[SDL_SCANCODE_UP]) { if (direction_x < 0.0) { //Left Jump sprite.v = 0.45; for (currentIndex; currentIndex < jump_l_s.size(); currentIndex++) { sprite.u = jump_l_s[currentIndex]; } } else //Right Jump sprite.v = 0.45; for (currentIndex; currentIndex < jump_r_s.size(); currentIndex++) { sprite.u = jump_r_s[currentIndex]; } } else { if (collidedBottom) { if (direction_x < 0.0) { //Left Idel sprite.v = 0.0; for (currentIndex; currentIndex < idel_l_s.size(); currentIndex++) { sprite.u = idel_l_s[currentIndex]; } } else //Right Idel sprite.v = 0.0; for (currentIndex; currentIndex < idel_r_s.size(); currentIndex++) { sprite.u = idel_r_s[currentIndex]; } } else { if (direction_x < 0.0) { //Left Fall sprite.v = 0.0; sprite.u = 0.7; } else //Right Fall sprite.v = 0.0; sprite.u = 0.2; } } if (!collidedBottom) { if (direction_x < 0.0) { //Left Fall sprite.v = 0.0; sprite.u = 0.7; } else //Right Fall sprite.v = 0.0; sprite.u = 0.2; } } else { if(keys[SDL_SCANCODE_RIGHT]) { if (collidedBottom) { //Rigth Running Animation sprite.v = 0.45; for (currentIndex; currentIndex < run_r.size(); currentIndex++) { sprite.u = run_r[currentIndex]; } } } else if(keys[SDL_SCANCODE_LEFT]) { if (collidedBottom) { //Left Running Animation sprite.v = 0.45; for (currentIndex; currentIndex < run_l.size(); currentIndex++) { sprite.u = run_l[currentIndex]; } } } else if(keys[SDL_SCANCODE_UP]) { if (direction_x < 0.0) { //Left Jump sprite.v = 0.45; for (currentIndex; currentIndex < jump_l.size(); currentIndex++) { sprite.u = jump_l[currentIndex]; } } else //Right Jump sprite.v = 0.45; for (currentIndex; currentIndex < jump_r.size(); currentIndex++) { sprite.u = jump_r[currentIndex]; } } else { if (collidedBottom) { if (direction_x < 0.0) { //Left Idel sprite.v = 0.0; for (currentIndex; currentIndex < idel_l.size(); currentIndex++) { sprite.u = idel_l[currentIndex]; } } else //Right Idel sprite.v = 0.0; for (currentIndex; currentIndex < idel_r.size(); currentIndex++) { sprite.u = idel_r[currentIndex]; } } else { if (direction_x < 0.0) { //Left Fall sprite.v = 0.0; sprite.u = 0.7; } else //Right Fall sprite.v = 0.0; sprite.u = 0.2; } } if (!collidedBottom) { if (direction_x < 0.0) { //Left Fall sprite.v = 0.0; sprite.u = 0.7; } else //Right Fall sprite.v = 0.0; sprite.u = 0.2; } } } else if (name == "robot") { } } void Entity::Update(float elapsed) { float fixedElapsed = elapsed + timeLeftOver; if(fixedElapsed > FIXED_TIMESTEP * MAX_TIMESTEPS) { fixedElapsed = FIXED_TIMESTEP * MAX_TIMESTEPS; } while (fixedElapsed >= FIXED_TIMESTEP ) { fixedElapsed -= FIXED_TIMESTEP; FixedUpdate(); } timeLeftOver = fixedElapsed; if (direction_x > 0.0) { acceleration_x = 1.0; } else if (direction_x < 0.0) { acceleration_x = -1.0; } } float lerp(float v0, float v1, float t) { return (1.0-t)*v0 + t*v1; } void Entity::FixedUpdate() { velocity_x = lerp(velocity_x, 0.0f, FIXED_TIMESTEP * friction_x); velocity_y = lerp(velocity_y, 0.0f, FIXED_TIMESTEP * friction_y); velocity_x += acceleration_x * FIXED_TIMESTEP; velocity_y += acceleration_y * FIXED_TIMESTEP; x += velocity_x * FIXED_TIMESTEP; y += velocity_y * FIXED_TIMESTEP; } bool Entity::collidesWith(Entity *entity) { //Bottom Collison if (y-height/2 < entity->height) { collidedBottom = true; return true; } //Right Collison if (x+width/2 > entity->width) { collidedRight = true; return true; } //Left Collison if (x-width/2 < entity->width) { collidedLeft = true; return true; } //Top Collison if (y+height/2 > entity->height) { collidedTop = true; return true; } return false; } void Bullet::Update(float elapsed) { x += elapsed; } void animatePlayer (SheetSprite sprite) { }
33.869048
92
0.433626
MarcNYU
f427425e383e6661138ff8864f512a371d0122a7
4,454
cpp
C++
Kawakawa/KawaiiGraphic/RHI/DX12Viewport.cpp
JiaqiJin/KawaiiDesune
e5c3031898f96f1ec5370b41371b2c1cf22c3586
[ "MIT" ]
null
null
null
Kawakawa/KawaiiGraphic/RHI/DX12Viewport.cpp
JiaqiJin/KawaiiDesune
e5c3031898f96f1ec5370b41371b2c1cf22c3586
[ "MIT" ]
null
null
null
Kawakawa/KawaiiGraphic/RHI/DX12Viewport.cpp
JiaqiJin/KawaiiDesune
e5c3031898f96f1ec5370b41371b2c1cf22c3586
[ "MIT" ]
null
null
null
#include "pch.h" #include "DX12Viewport.h" #include "DX12GraphicRHI.h" #include "DX12Device.h" #include "Texture/TextureInfo.h" namespace RHI { DX12Viewport::DX12Viewport(DX12GraphicRHI* DX12RHI, const DX12ViewportInfo& Info, int Width, int Height) : m_DX12RHI(DX12RHI), m_ViewportInfo(Info), m_ViewportWidth(Width), m_ViewportHeight(Height) { CreateSwapChain(); } DX12Viewport::~DX12Viewport() { } void DX12Viewport::OnResize(int NewWidth, int NewHeight) { m_ViewportWidth = NewWidth; m_ViewportHeight = NewHeight; // Flush before changing any resources. m_DX12RHI->GetDevice()->GetCommandContext()->FlushCommandQueue(); m_DX12RHI->GetDevice()->GetCommandContext()->ResetCommandList(); // Release the previous resources for (UINT i = 0; i < m_SwapChainBufferCount; i++) { m_RenderTargetTextures[i].reset(); } m_DepthStencilTexture.reset(); // Resize the swap chain. ThrowIfFailed(m_SwapChain->ResizeBuffers(m_SwapChainBufferCount, m_ViewportWidth, m_ViewportHeight, m_ViewportInfo.BackBufferFormat, DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH)); m_CurrBackBuffer = 0; // Create RenderTargetTextures for (UINT i = 0; i < m_SwapChainBufferCount; i++) { Microsoft::WRL::ComPtr<ID3D12Resource> SwapChainBuffer = nullptr; ThrowIfFailed(m_SwapChain->GetBuffer(i, IID_PPV_ARGS(&SwapChainBuffer))); D3D12_RESOURCE_DESC BackBufferDesc = SwapChainBuffer->GetDesc(); TextureInfo textureInfo; textureInfo.RTVFormat = BackBufferDesc.Format; textureInfo.InitState = D3D12_RESOURCE_STATE_PRESENT; m_RenderTargetTextures[i] = m_DX12RHI->CreateTexture(SwapChainBuffer, textureInfo, TexCreate_RTV); } // Create DepthStencilTexture TextureInfo textureInfo; textureInfo.Type = ETextureType::TEXTURE_2D; textureInfo.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; textureInfo.Width = m_ViewportWidth; textureInfo.Height = m_ViewportHeight; textureInfo.Depth = 1; textureInfo.MipCount = 1; textureInfo.ArraySize = 1; textureInfo.InitState = D3D12_RESOURCE_STATE_DEPTH_WRITE; textureInfo.Format = DXGI_FORMAT_R24G8_TYPELESS; // Create with a typeless format, support DSV and SRV(for SSAO) textureInfo.DSVFormat = DXGI_FORMAT_D24_UNORM_S8_UINT; textureInfo.SRVFormat = DXGI_FORMAT_R24_UNORM_X8_TYPELESS; m_DepthStencilTexture = m_DX12RHI->CreateTexture(textureInfo, TexCreate_DSV | TexCreate_SRV); // Execute the resize commands. m_DX12RHI->GetDevice()->GetCommandContext()->ExecuteCommandLists(); // Wait until resize is complete. m_DX12RHI->GetDevice()->GetCommandContext()->FlushCommandQueue(); } void DX12Viewport::Present() { // swap the back and front buffers ThrowIfFailed(m_SwapChain->Present(0, 0)); m_CurrBackBuffer = (m_CurrBackBuffer + 1) % m_SwapChainBufferCount; } void DX12Viewport::CreateSwapChain() { // Release the previous swapchain we will be recreating. m_SwapChain.Reset(); DXGI_SWAP_CHAIN_DESC Desc; Desc.BufferDesc.Width = m_ViewportWidth; Desc.BufferDesc.Height = m_ViewportHeight; Desc.BufferDesc.RefreshRate.Numerator = 60; Desc.BufferDesc.RefreshRate.Denominator = 1; Desc.BufferDesc.Format = m_ViewportInfo.BackBufferFormat; Desc.BufferDesc.ScanlineOrdering = DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED; Desc.BufferDesc.Scaling = DXGI_MODE_SCALING_UNSPECIFIED; Desc.SampleDesc.Count = m_ViewportInfo.bEnable4xMsaa ? 4 : 1; Desc.SampleDesc.Quality = m_ViewportInfo.bEnable4xMsaa ? (m_ViewportInfo.QualityOf4xMsaa - 1) : 0; Desc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; Desc.BufferCount = m_SwapChainBufferCount; Desc.OutputWindow = m_ViewportInfo.WindowHandle; Desc.Windowed = true; Desc.SwapEffect = DXGI_SWAP_EFFECT_FLIP_DISCARD; Desc.Flags = DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH; // Note: Swap chain uses queue to perform flush. Microsoft::WRL::ComPtr<ID3D12CommandQueue> CommandQueue = m_DX12RHI->GetDevice()->GetCommandQueue(); ThrowIfFailed(m_DX12RHI->GetDxgiFactory()->CreateSwapChain(CommandQueue.Get(), &Desc, m_SwapChain.GetAddressOf())); } void DX12Viewport::GetD3DViewport(D3D12_VIEWPORT& OutD3DViewPort, D3D12_RECT& OutD3DRect) { OutD3DViewPort.TopLeftX = 0; OutD3DViewPort.TopLeftY = 0; OutD3DViewPort.Width = static_cast<float>(m_ViewportWidth); OutD3DViewPort.Height = static_cast<float>(m_ViewportHeight); OutD3DViewPort.MinDepth = 0.0f; OutD3DViewPort.MaxDepth = 1.0f; OutD3DRect = { 0, 0, m_ViewportWidth, m_ViewportHeight }; } }
35.632
117
0.776605
JiaqiJin
f4278b973fda15c5eba16fd9839c1cf2851857e4
324
hpp
C++
include/bisera/mainwindow.hpp
DanielAckerson/bisera
f574c257a4a20d663eae6c52d50444280bbfe67d
[ "MIT" ]
null
null
null
include/bisera/mainwindow.hpp
DanielAckerson/bisera
f574c257a4a20d663eae6c52d50444280bbfe67d
[ "MIT" ]
null
null
null
include/bisera/mainwindow.hpp
DanielAckerson/bisera
f574c257a4a20d663eae6c52d50444280bbfe67d
[ "MIT" ]
null
null
null
#ifndef MAINWINDOW_HPP #define MAINWINDOW_HPP #include <glad/glad.h> #include <GLFW/glfw3.h> class MainWindow { GLFWwindow *window; GLFWmonitor *monitor; GLuint width, height; public: MainWindow(); ~MainWindow(); public: inline GLFWwindow *context() { return window; } }; #endif//MAINWINDOW_HPP
15.428571
51
0.694444
DanielAckerson
f42f71b0782e115902afe80664e901a9130de4e1
4,088
cpp
C++
src/dbus/dbus_watch.cpp
tpruzina/dvc-toggler-linux
ccd70fedfdc47172e876c04357b863bb758bd304
[ "BSD-3-Clause" ]
null
null
null
src/dbus/dbus_watch.cpp
tpruzina/dvc-toggler-linux
ccd70fedfdc47172e876c04357b863bb758bd304
[ "BSD-3-Clause" ]
1
2019-05-20T16:47:28.000Z
2019-05-20T16:47:28.000Z
src/dbus/dbus_watch.cpp
tpruzina/dvc-toggler-linux
ccd70fedfdc47172e876c04357b863bb758bd304
[ "BSD-3-Clause" ]
null
null
null
#include "dbus_watch.hpp" #include <cstdlib> #include <cstring> #include <dbus/dbus.h> #include <iostream> #include <unistd.h> auto DBusInterface::sendSignal(char *message) noexcept -> void { auto args = DBusMessageIter{}; dbus_uint32_t serial = 0; auto conn = dbus_bus_get(DBUS_BUS_STARTER, nullptr); if (!conn) return; dbus_bus_request_name( conn, DBUS_CLIENT_NAME, DBUS_NAME_FLAG_REPLACE_EXISTING, nullptr); auto msg = dbus_message_new_signal( DBUS_SIGNAL_OBJECT, // object name of the signal DBUS_IF_NAME, // interface name of the signal DBUS_SIGNAL_SHOW // name of the signal ); dbus_message_iter_init_append(msg, &args); dbus_message_iter_append_basic(&args, DBUS_TYPE_STRING, &message); // send the message and flush the connection dbus_connection_send(conn, msg, &serial); dbus_connection_flush(conn); dbus_message_unref(msg); dbus_bus_release_name(conn, DBUS_CLIENT_NAME, nullptr); dbus_connection_unref(conn); return; } auto DBusInterface::spawnListener(void (*cb)(void*), void* object) noexcept -> void { this->callback_fn = cb; this->callback_object = object; listener = std::thread(&DBusInterface::receive, this); return; } auto DBusInterface::receive() noexcept -> void { if (!callback_fn) return; auto conn = dbus_bus_get(DBUS_BUS_STARTER, nullptr); if (!conn) return; dbus_bus_request_name( conn, DBUS_HOST_SERVER, DBUS_NAME_FLAG_REPLACE_EXISTING, NULL ); dbus_bus_add_match( conn, "type='signal',interface='" DBUS_IF_NAME "'", nullptr); dbus_connection_flush(conn); // loop listening for signals being emmitted while (true) { if(shutdown) break; // non blocking read of the next available message dbus_connection_read_write(conn, 0); auto msg = dbus_connection_pop_message(conn); // loop again if we haven't read a message if (!msg) { std::this_thread::sleep_for( std::chrono::milliseconds(sleep_ms)); continue; } // check if the message is a signal from the correct interface and with the correct name if (dbus_message_is_signal( msg, DBUS_IF_NAME, DBUS_SIGNAL_SHOW)) { auto args = DBusMessageIter{}; // read the parameters dbus_message_iter_init(msg, &args); if (DBUS_TYPE_STRING == dbus_message_iter_get_arg_type(&args)) { auto sigvalue = (char const *)(nullptr); dbus_message_iter_get_basic(&args, &sigvalue); // display mainWindow if (!strcmp(sigvalue, "show()")) callback_fn(callback_object); } } // free the message dbus_message_unref(msg); } // close the connection dbus_bus_remove_match( conn, "type='signal',interface='" DBUS_IF_NAME "'", nullptr); dbus_bus_release_name(conn, DBUS_HOST_SERVER, nullptr); dbus_connection_unref(conn); return; }
32.967742
104
0.489237
tpruzina
f42f8917e49952f4de8da45c32f5120c71609fa3
1,095
hpp
C++
test/ClientTester.hpp
AlexSL92/udp-packet-replicator
90a3feb138e7ad2ae7e4b87f97305f658b7f6eeb
[ "MIT" ]
2
2020-06-18T09:06:45.000Z
2021-03-27T14:16:54.000Z
test/ClientTester.hpp
AlexSL92/udp-packet-replicator
90a3feb138e7ad2ae7e4b87f97305f658b7f6eeb
[ "MIT" ]
null
null
null
test/ClientTester.hpp
AlexSL92/udp-packet-replicator
90a3feb138e7ad2ae7e4b87f97305f658b7f6eeb
[ "MIT" ]
1
2020-06-18T06:29:17.000Z
2020-06-18T06:29:17.000Z
#pragma once #include <asio.hpp> #include <array> #include <cstdint> #include <vector> /** * @brief Tester of client sockets */ class ClientTester { public: /** * @brief Construct a new Client Tester object * * @param port Port where listen for packets */ ClientTester(uint16_t port) : io_context_{}, socket_{ io_context_, asio::ip::udp::endpoint(asio::ip::udp::v4(), port) } {} /** * @brief Destroy the Client Tester object * */ ~ClientTester() {} /** * @brief Read data from socket * * @return std::vector<uint8_t> Data received on the socket */ std::vector<uint8_t> ReceiveData() { std::array<uint8_t, 8192> recv_buf{}; asio::ip::udp::endpoint remote_endpoint{}; auto recv{ socket_.receive_from(asio::buffer(recv_buf), remote_endpoint) }; return std::vector<uint8_t>{ recv_buf.begin(), recv_buf.begin() + recv }; } private: asio::io_context io_context_; //!< Asio context object asio::ip::udp::socket socket_; //!< Asio socket };
21.9
85
0.601826
AlexSL92
f4378ba73efb592ab9fc2e6d69fecf7c201c49b5
2,449
cpp
C++
leetcode/problems/easy/26-remove-duplicates-from-sorted-array.cpp
wingkwong/competitive-programming
e8bf7aa32e87b3a020b63acac20e740728764649
[ "MIT" ]
18
2020-08-27T05:27:50.000Z
2022-03-08T02:56:48.000Z
leetcode/problems/easy/26-remove-duplicates-from-sorted-array.cpp
wingkwong/competitive-programming
e8bf7aa32e87b3a020b63acac20e740728764649
[ "MIT" ]
null
null
null
leetcode/problems/easy/26-remove-duplicates-from-sorted-array.cpp
wingkwong/competitive-programming
e8bf7aa32e87b3a020b63acac20e740728764649
[ "MIT" ]
1
2020-10-13T05:23:58.000Z
2020-10-13T05:23:58.000Z
/* Remove Duplicates from Sorted Array Given a sorted array nums, remove the duplicates in-place such that each element appear only once and return the new length. Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory. Example 1: Given nums = [1,1,2], Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively. It doesn't matter what you leave beyond the returned length. Example 2: Given nums = [0,0,1,1,1,2,2,3,3,4], Your function should return length = 5, with the first five elements of nums being modified to 0, 1, 2, 3, and 4 respectively. It doesn't matter what values are set beyond the returned length. Clarification: Confused why the returned value is an integer but your answer is an array? Note that the input array is passed in by reference, which means modification to the input array will be known to the caller as well. Internally you can think of this: // nums is passed in by reference. (i.e., without making a copy) int len = removeDuplicates(nums); // any modification to nums in your function would be known by the caller. // using the length returned by your function, it prints the first len elements. for (int i = 0; i < len; i++) { print(nums[i]); } */ class Solution { public: int removeDuplicates(vector<int>& nums) { int i = !nums.empty(); for (int n : nums) if (n > nums[i - 1]) nums[i++] = n; return i; } }; class Solution { public: int removeDuplicates(vector<int>& nums) { int sz=nums.size(); if(!sz) return 0; int i=0; for(int j=1;j<nums.size();j++){ if(nums[j]!=nums[i]){ // We need to modify the array in-place and the size of the final array would potentially be smaller than the size of the input array. // So, we ought to use a two-pointer approach here. // One, that would keep track of the current element in the original array and another one for just the unique elements. i++; nums[i]=nums[j]; } // Essentially, once an element is encountered, you simply need to bypass its duplicates and move on to the next unique element. } return i+1; } }; static const auto io_sync_off = []() {std::ios::sync_with_stdio(false);cin.tie(nullptr);cout.tie(nullptr);return 0;}();
34.985714
151
0.665986
wingkwong
f438c6540d1b2df16928dedfb42152e7866f5de5
1,724
hpp
C++
babyrobot/src/object-assembly-agent-master/object_assembly_ros/include/object_assembly_ros/assembly_task_guess_mode.hpp
babyrobot-eu/core-modules
7e8c006c40153fb649208c9a78fc71aa70243f69
[ "MIT" ]
1
2019-02-07T15:32:06.000Z
2019-02-07T15:32:06.000Z
babyrobot/src/object-assembly-agent-master/object_assembly_ros/include/object_assembly_ros/assembly_task_guess_mode.hpp
babyrobot-eu/core-modules
7e8c006c40153fb649208c9a78fc71aa70243f69
[ "MIT" ]
9
2020-01-28T22:09:41.000Z
2022-03-11T23:39:17.000Z
babyrobot/src/object-assembly-agent-master/object_assembly_ros/include/object_assembly_ros/assembly_task_guess_mode.hpp
babyrobot-eu/core-modules
7e8c006c40153fb649208c9a78fc71aa70243f69
[ "MIT" ]
null
null
null
#include <assembly_subtask.hpp> #include <cstdlib> class AssemblyTask { public: AssemblyTask( int id, int num_parts, std::vector<std::vector<int>> connnection_pairs, int num_connections, std::vector<AssemblySubtask> subtasks, int max_particles, int all_particles, int connection_list_offset, std::string connection_vector_topic); //returns current subtask double evaluate_task(std::vector<tf::Transform> current_object_poses, std::vector<object_assembly_msgs::ConnectionInfo> &connection_list); void set_connections(std::vector<object_assembly_msgs::ConnectionInfo> &connection_list); tf::Quaternion calculate_prerotation(); void publish_connection_vector(); int num_connections_; //struct AssemblySubgraph //{ // std::vector<tf::Quaternion> rotations; // std::vector<int> nodes; //}; private: ros::NodeHandle node_handle_; ros::Publisher connection_vector_publisher_; //int current_subtask_ = 0; const int task_id_; const int num_parts_; const int connection_list_offset_; int subgraph_max_index_ = -1; std::vector<AssemblySubtask> subtasks_; int max_particles_; int all_particles_; std::vector<std::vector<int>> connection_pairs_; std::vector<bool> connection_status_vector_; //std::vector<AssemblySubgraph> subgraph_list_; std::vector<int> part_subgraph_index_; //which subgraph each part belongs to (-1 means none) std::vector<double> scores_; std::list<int> zero_score_queue_; std::vector<int> zero_score_spotlight_times_; std::vector<tf::Quaternion> rotations_; //std::vector<int> rotation_index; };
28.733333
142
0.703596
babyrobot-eu
f443843d4f7f7e67650e9d5c9413d5fec5e2ad56
11,726
cc
C++
src/scheduler.cc
sunnyxhuang/2D-Placement
53310fa7336430a1b82b3ed3fa98409ab5d4b7d5
[ "Apache-2.0" ]
4
2017-09-01T14:43:01.000Z
2017-09-02T04:58:55.000Z
src/scheduler.cc
little-by/2D-Placement
53310fa7336430a1b82b3ed3fa98409ab5d4b7d5
[ "Apache-2.0" ]
null
null
null
src/scheduler.cc
little-by/2D-Placement
53310fa7336430a1b82b3ed3fa98409ab5d4b7d5
[ "Apache-2.0" ]
3
2017-09-21T08:24:51.000Z
2018-10-30T04:46:15.000Z
#include <algorithm> #include <iomanip> #include <cfloat> #include <sys/time.h> #include <string.h> #include "coflow.h" #include "events.h" #include "global.h" #include "scheduler.h" #include "util.h" #define MWM_RANGE 100000000 //2147483647 = 2,147,483,647 using namespace std; /////////////////////////////////////////////////////// ////////////// Code for base class Scheduler /////////////////////////////////////////////////////// Scheduler::Scheduler() { m_simPtr = NULL; m_currentTime = 0; m_myTimeLine = new SchedulerTimeLine(); m_coflowPtrVector = vector<Coflow *>(); m_nextElecRate = map<int, long>(); m_nextOptcRate = map<int, long>(); } Scheduler::~Scheduler() { delete m_myTimeLine; } void Scheduler::UpdateAlarm() { // update alarm for scheduler on simulator if (!m_myTimeLine->isEmpty()) { Event *nextEvent = m_myTimeLine->PeekNext(); double nextTime = nextEvent->GetEventTime(); Event *schedulerAlarm = new Event(ALARM_SCHEDULER, nextTime); m_simPtr->UpdateSchedulerAlarm(schedulerAlarm); } } void Scheduler::NotifySimEnd() { return; cout << "[Scheduler::NotifySimEnd()] is called." << endl; for (vector<Coflow *>::iterator cfIt = m_coflowPtrVector.begin(); cfIt != m_coflowPtrVector.end(); cfIt++) { vector<Flow *> *flowVecPtr = (*cfIt)->GetFlows(); for (vector<Flow *>::iterator fpIt = flowVecPtr->begin(); fpIt != flowVecPtr->end(); fpIt++) { if ((*fpIt)->GetBitsLeft() <= 0) { // such flow has finished continue; } cout << "[Scheduler::NotifySimEnd()] flow [" << (*fpIt)->GetFlowId() << "] " << "(" << (*fpIt)->GetSrc() << "=>" << (*fpIt)->GetDest() << ") " << (*fpIt)->GetSizeInBit() << " bytes " << (*fpIt)->GetBitsLeft() << " bytes left " << (*fpIt)->GetElecRate() << " bps" << endl; } } } bool Scheduler::Transmit(double startTime, double endTime, bool basic, bool local, bool salvage) { CircuitAuditIfNeeded(startTime, endTime); bool hasCoflowFinish = false; bool hasFlowFinish = false; bool hasCoflowTmpFinish = false; vector<Coflow *> finished_coflows; vector<Flow *> finished_flows; m_validate_last_tx_src_bits.clear(); m_validate_last_tx_dst_bits.clear(); for (vector<Coflow *>::iterator cfIt = m_coflowPtrVector.begin(); cfIt != m_coflowPtrVector.end();) { if ((*cfIt)->IsFlowsAddedComplete()) { // coflow not completed yet // but the flows added so far have finished cfIt++; continue; } vector<Flow *> *flowVecPtr = (*cfIt)->GetFlows(); for (vector<Flow *>::iterator fpIt = flowVecPtr->begin(); fpIt != flowVecPtr->end(); fpIt++) { if ((*fpIt)->GetBitsLeft() <= 0) { // such flow has finished continue; } // tx rate verification debug long validate_tx_this_flow_bits = (*fpIt)->GetBitsLeft(); // ********* begin tx **************** if (basic) { (*fpIt)->Transmit(startTime, endTime); } if (local) { (*fpIt)->TxLocal(); } if (salvage) { (*fpIt)->TxSalvage(); } // ********* end tx ******************** // tx rate verification debug validate_tx_this_flow_bits -= (*fpIt)->GetBitsLeft(); MapWithInc(m_validate_last_tx_src_bits, (*fpIt)->GetSrc(), validate_tx_this_flow_bits); MapWithInc(m_validate_last_tx_dst_bits, (*fpIt)->GetDest(), validate_tx_this_flow_bits); if ((*fpIt)->GetBitsLeft() == 0) { hasFlowFinish = true; (*cfIt)->NumFlowFinishInc(); (*fpIt)->SetEndTime(endTime); finished_flows.push_back(*fpIt); } // update coflow account on bytes sent. (*cfIt)->AddTxBit(validate_tx_this_flow_bits); } // debug for coflow progress if (DEBUG_LEVEL >= 3 && hasFlowFinish) { cout << fixed << setw(FLOAT_TIME_WIDTH) << endTime << "s "; cout << (*cfIt)->toString() << endl; } if ((*cfIt)->IsComplete()) { //cout << string(FLOAT_TIME_WIDTH+2, ' ') cout << fixed << setw(FLOAT_TIME_WIDTH) << endTime << "s " << "[Scheduler::Transmit] coflow finish! # " << (*cfIt)->GetJobId() << endl; Coflow * finished_coflow = *cfIt; finished_coflows.push_back(finished_coflow); finished_coflow->SetEndTime(endTime); hasCoflowFinish = true; // advance coflow iterator. cfIt = m_coflowPtrVector.erase(cfIt); } else { if ((*cfIt)->IsFlowsAddedComplete()) { hasCoflowTmpFinish = true; } // jump to next coflow cfIt++; } } ScheduleToNotifyTrafficFinish(endTime, finished_coflows, finished_flows); if (hasCoflowFinish || hasCoflowTmpFinish) { CoflowFinishCallBack(endTime); } else if (hasFlowFinish) { FlowFinishCallBack(endTime); } if (hasCoflowFinish || hasCoflowTmpFinish || hasFlowFinish) { Scheduler::UpdateFlowFinishEvent(endTime); } if (hasCoflowFinish || hasCoflowTmpFinish || hasFlowFinish) { return true; } return false; } void Scheduler::ScheduleToNotifyTrafficFinish(double end_time, vector<Coflow *> &coflows_done, vector<Flow *> &flows_done) { if (coflows_done.empty() && flows_done.empty()) { return; } //notify traffic generator of coflow / flow finish vector<Coflow *> *finishedCf = new vector<Coflow *>(coflows_done); vector<Flow *> *finishedF = new vector<Flow *>(flows_done); MsgEventTrafficFinish *msgEventPtr = new MsgEventTrafficFinish(end_time, finishedCf, finishedF); m_simPtr->AddEvent(msgEventPtr); if (!coflows_done.empty()) { WriteCircuitAuditIfNeeded(end_time, coflows_done); } } //returns negative if all flows has finished //return DBL_MAX if all flows are waiting indefinitely double Scheduler::CalcTime2FirstFlowEnd() { double time2FirstFinish = DBL_MAX; bool hasUnfinishedFlow = false; bool finishTimeValid = false; for (vector<Coflow *>::iterator cfIt = m_coflowPtrVector.begin(); cfIt != m_coflowPtrVector.end(); cfIt++) { if ((*cfIt)->IsFlowsAddedComplete()) { //flows added in such coflow have all completed continue; } vector<Flow *> *flowVecPtr = (*cfIt)->GetFlows(); for (vector<Flow *>::iterator fpIt = flowVecPtr->begin(); fpIt != flowVecPtr->end(); fpIt++) { if ((*fpIt)->GetBitsLeft() <= 0) { //such flow has completed continue; } hasUnfinishedFlow = true; // calc the min finishing time double flowCompleteTime = DBL_MAX; if ((*fpIt)->isThruOptic() && (*fpIt)->GetOptcRate() > 0) { flowCompleteTime = SecureFinishTime((*fpIt)->GetBitsLeft(), (*fpIt)->GetOptcRate()); } else if (!(*fpIt)->isThruOptic() && (*fpIt)->GetElecRate() > 0) { flowCompleteTime = SecureFinishTime((*fpIt)->GetBitsLeft(), (*fpIt)->GetElecRate()); } if (time2FirstFinish > flowCompleteTime) { finishTimeValid = true; time2FirstFinish = flowCompleteTime; } } } if (hasUnfinishedFlow) { if (finishTimeValid) { return time2FirstFinish; } else { //all flows are waiting indefinitely return DBL_MAX; } } else { // all flows are finished return -DBL_MAX; } } void Scheduler::UpdateFlowFinishEvent(double baseTime) { double time2FirstFinish = CalcTime2FirstFlowEnd(); if (time2FirstFinish == DBL_MAX) { // all flows are waiting indefinitely m_myTimeLine->RemoveSingularEvent(FLOW_FINISH); } else if (time2FirstFinish == -DBL_MAX) { // all flows are done } else { // valid finishing time m_myTimeLine->RemoveSingularEvent(FLOW_FINISH); double firstFinishTime = baseTime + time2FirstFinish; Event *flowFinishEventPtr = new Event(FLOW_FINISH, firstFinishTime); m_myTimeLine->AddEvent(flowFinishEventPtr); } } void Scheduler::UpdateRescheduleEvent(double reScheduleTime) { m_myTimeLine->RemoveSingularEvent(RESCHEDULE); Event *rescheduleEventPtr = new Event(RESCHEDULE, reScheduleTime); m_myTimeLine->AddEvent(rescheduleEventPtr); } void Scheduler::NotifyAddFlows(double alarmTime) { //FlowArrive(alarmTime); EventFlowArrive *msgEp = new EventFlowArrive(alarmTime); m_myTimeLine->AddEvent(msgEp); UpdateAlarm(); } void Scheduler::NotifyAddCoflows(double alarmTime, vector<Coflow *> *cfVecPtr) { //CoflowArrive(alarmTime,cfVecPtr); EventCoflowArrive *msgEp = new EventCoflowArrive(alarmTime, cfVecPtr); m_myTimeLine->AddEvent(msgEp); UpdateAlarm(); } double Scheduler::SecureFinishTime(long bits, long rate) { if (rate == 0) { return DBL_MAX; } double timeLen = (double) bits / (double) rate; // more complicated impl below ********* long bitsleft = 1; int delta = 0; while (bitsleft > 0) { timeLen = (double) (delta + bits) / (double) rate; bitsleft = bits - rate * timeLen; delta++; } // more complicated impl above ***** //if (timeLen < 0.0000000001) return 0.0000000001; return timeLen; } void Scheduler::Print(void) { return; for (vector<Coflow *>::iterator cfIt = m_coflowPtrVector.begin(); cfIt != m_coflowPtrVector.end(); cfIt++) { if (cfIt == m_coflowPtrVector.begin()) { cout << fixed << setw(FLOAT_TIME_WIDTH) << m_currentTime << "s "; } else { cout << string(FLOAT_TIME_WIDTH + 2, ' '); } cout << "[Scheduler::Print] " << "Coflow ID " << (*cfIt)->GetCoflowId() << endl; (*cfIt)->Print(); } } // copy flow rate from m_nextElecRate & m_nextOptcRate // and reflect the rate on flow record. void Scheduler::SetFlowRate() { for (vector<Coflow *>::iterator cfIt = m_coflowPtrVector.begin(); cfIt != m_coflowPtrVector.end(); cfIt++) { vector<Flow *> *flowVecPtr = (*cfIt)->GetFlows(); for (vector<Flow *>::iterator fpIt = flowVecPtr->begin(); fpIt != flowVecPtr->end(); fpIt++) { //set flow rate int flowId = (*fpIt)->GetFlowId(); long elecBps = MapWithDef(m_nextElecRate, flowId, (long) 0); long optcBps = MapWithDef(m_nextOptcRate, flowId, (long) 0); (*fpIt)->SetRate(elecBps, optcBps); } } } void Scheduler::CalAlphaAndSortCoflowsInPlace(vector<Coflow *> &coflows) { for (vector<Coflow *>::iterator it = coflows.begin(); it != coflows.end(); it++) { (*it)->CalcAlpha(); } std::stable_sort(coflows.begin(), coflows.end(), coflowCompAlpha); } bool Scheduler::ValidateLastTxMeetConstraints(long port_bound_bits) { for (map<int, long>::const_iterator src_kv_pair = m_validate_last_tx_src_bits.begin(); src_kv_pair != m_validate_last_tx_src_bits.end(); src_kv_pair++) { if (src_kv_pair->second > port_bound_bits) { cout << "Error in validating TX constraints!!! " << endl << " src " << src_kv_pair->first << " flows over bound " << port_bound_bits << endl; return false; } } for (map<int, long>::const_iterator dst_kv_pair = m_validate_last_tx_dst_bits.begin(); dst_kv_pair != m_validate_last_tx_dst_bits.end(); dst_kv_pair++) { if (dst_kv_pair->second > port_bound_bits) { cout << "Error in validating TX constraints!!! " << endl << " dst " << dst_kv_pair->first << " flows over bound " << port_bound_bits << endl; return false; } } // cout << "TX budget is valid." << endl; return true; }
28.953086
76
0.609074
sunnyxhuang
f444a252e66e85d298218ff08191db87f3891e87
238
hpp
C++
include/RavEngine/AnimatorSystem.hpp
Ravbug/RavEngine
73249827cb2cd3c938bb59447e9edbf7b6f0defc
[ "Apache-2.0" ]
48
2020-11-18T23:14:25.000Z
2022-03-11T09:13:42.000Z
include/RavEngine/AnimatorSystem.hpp
Ravbug/RavEngine
73249827cb2cd3c938bb59447e9edbf7b6f0defc
[ "Apache-2.0" ]
1
2020-11-17T20:53:10.000Z
2020-12-01T20:27:36.000Z
include/RavEngine/AnimatorSystem.hpp
Ravbug/RavEngine
73249827cb2cd3c938bb59447e9edbf7b6f0defc
[ "Apache-2.0" ]
3
2020-12-22T02:40:39.000Z
2021-10-08T02:54:22.000Z
#pragma once #include "System.hpp" #include "AnimatorComponent.hpp" namespace RavEngine{ class AnimatorSystem : public AutoCTTI{ public: inline void Tick(float fpsScale, Ref<AnimatorComponent> c) const { c->Tick(fpsScale); } }; }
18.307692
70
0.739496
Ravbug
f446e49c22efe8b62648400235466cd0079e1715
353
cpp
C++
Practice/2019.2.9/CF15E.cpp
SYCstudio/OI
6e9bfc17dbd4b43467af9b19aa2aed41e28972fa
[ "MIT" ]
4
2017-10-31T14:25:18.000Z
2018-06-10T16:10:17.000Z
Practice/2019.2.9/CF15E.cpp
SYCstudio/OI
6e9bfc17dbd4b43467af9b19aa2aed41e28972fa
[ "MIT" ]
null
null
null
Practice/2019.2.9/CF15E.cpp
SYCstudio/OI
6e9bfc17dbd4b43467af9b19aa2aed41e28972fa
[ "MIT" ]
null
null
null
#include<cstdio> #include<cstdlib> #include<cstring> #include<algorithm> using namespace std; const int Mod=1000000009; int main() { int n; scanf("%d",&n); int sum=0,mul=4,pw=2; while (n>2) { n-=2; pw=2ll*pw%Mod; mul=1ll*mul*(pw-3+Mod)%Mod; sum=(sum+mul)%Mod; } sum=(2ll*sum*sum%Mod+8ll*sum%Mod+10)%Mod; printf("%d\n",sum); return 0; }
15.347826
42
0.631728
SYCstudio
f44776b3a2b74cf641e9ff802c03579e5fd140aa
12,871
hpp
C++
src/mge/core/exception.hpp
mge-engine/mge
e7a6253f99dd640a655d9a80b94118d35c7d8139
[ "MIT" ]
null
null
null
src/mge/core/exception.hpp
mge-engine/mge
e7a6253f99dd640a655d9a80b94118d35c7d8139
[ "MIT" ]
91
2019-03-09T11:31:29.000Z
2022-02-27T13:06:06.000Z
src/mge/core/exception.hpp
mge-engine/mge
e7a6253f99dd640a655d9a80b94118d35c7d8139
[ "MIT" ]
null
null
null
// mge - Modern Game Engine // Copyright (c) 2021 by Alexander Schroeder // All rights reserved. #pragma once #include "mge/config.hpp" #include "mge/core/dllexport.hpp" #include "mge/core/stacktrace.hpp" #include "mge/core/type_name.hpp" #include <any> #include <exception> #include <optional> #include <sstream> #include <string_view> #include <type_traits> #include <typeindex> #include <typeinfo> namespace mge { /** * @brief An exception. */ class MGECORE_EXPORT exception : virtual public std::exception { public: /** * Helper class for detailed exception information. */ struct exception_details { public: exception_details(const mge::exception* ex) noexcept : m_ex(ex) {} inline const mge::exception* ex() const noexcept { return m_ex; } private: const mge::exception* m_ex; }; private: struct tag_base {}; public: /** * @brief Exception value tag type. * * @tparam Tag type used to access the value * @tparam Value stored value type * * The tag type is used to attach values to the * exception. * * To use it, create a type that will hold the information as a * member @c value, and derive that type from the tag type as follows. * @code * // A 'foo' value will hold a string attached to an exception. * struct foo : public tag<foo, std::string> * { * std::string value; * }; * @endcode */ template <typename Tag, typename Value> struct tag : public tag_base { using tag_type = Tag; //!< Tag type. using value_type = Value; //!< Value type of value stored under tag. }; /** * @brief Source file name attached to exception. */ struct source_file : public tag<source_file, std::string_view> { /** * @brief Capture source file name. * @param value_ source file name */ source_file(const std::string_view& value_) noexcept : m_value(value_) {} std::string_view value() const noexcept { return m_value; } std::string_view m_value; }; /** * @brief Function name attached to exception. */ struct function : public tag<function, std::string_view> { /** * @brief Capture current function name. * @param value_ current function name */ function(const std::string_view& value_) noexcept : m_value(value_) {} std::string_view value() const noexcept { return m_value; } std::string_view m_value; }; /** * @brief Source file line number attached to exception. */ struct source_line : public tag<source_line, uint32_t> { /** * @brief Capture source line number. * @param value_ source line number */ source_line(uint32_t value_) noexcept : m_value(value_) {} uint32_t value() const noexcept { return m_value; } uint32_t m_value; }; /** * @brief Stack backtrace attached to exception. */ struct stack : public tag<stack, mge::stacktrace> { /** * @brief Capture stack backtrace. * * @param s stack backtrace */ stack(mge::stacktrace&& s) : m_value(std::move(s)) {} const mge::stacktrace& value() const noexcept { return m_value; } mge::stacktrace m_value; }; /** * @brief Message attached to exception. */ struct message : public tag<message, std::string> { message() {} std::string_view value() const noexcept { return m_value; } std::string m_value; }; /** * @brief Exception type name. */ struct type_name : public tag<type_name, std::string> { /** * @brief Capture exception type name (subclass of mge::exception). * * @param name type name */ type_name(std::string_view name) : m_value(name) {} const std::string& value() const noexcept { return m_value; } std::string m_value; }; /** * @brief Function in which exception is thrown. */ struct called_function : public tag<called_function, std::string_view> { /** * @brief Capture called function that raised the error. * * @param name called function */ called_function(const std::string_view& name) : m_value(name) {} std::string_view value() const noexcept { return m_value; } std::string_view m_value; }; struct cause; /** * @brief Construct empty exception. */ exception(); /** * @brief Copy constructor. * @param ex copied exception */ exception(const exception& ex); /** * @brief Move constructor. * @param ex moved exception */ exception(exception&& ex); /** * Destructor. */ virtual ~exception(); /** * Assignment. * @return @c *this */ exception& operator=(const exception&); /** * Move assignment. * @param e moved exception * @return @c *this */ exception& operator=(exception&& e); /** * Overrides @c std::exception @c what function. * @return exception message */ const char* what() const override; /** * Get current exception of this thread. * @return pointer to current exception or @c nullptr if there is none */ static mge::exception* current_exception(); /** * @brief Set information associated with tag type. * * @tparam Info info tag type * @param info information stored under the tag * @return @c *this */ template <typename Info> inline exception& set_info(const Info& info) { m_infos[std::type_index(typeid(typename Info::tag_type))] = info.value(); return *this; } /** * @brief Set information associated with exception message. * * @tparam exception::message * @param info info object containing message * @return @c *this */ template <> exception& set_info<exception::message>(const exception::message& info) { m_raw_message = info.value(); return *this; } /** * @brief Retrieve information stored under a tag type. * * @tparam Info tag type * @return the stored value */ template <typename Info> inline auto get() const { auto it = m_infos.find(std::type_index(typeid(typename Info::tag_type))); std::optional<Info::value_type> result; if (it != m_infos.end()) { result = std::any_cast<Info::value_type>(it->second); } return result; } /** * @brief Get an exception details instance referring to this * exception. * * @return exception details for this exception */ exception_details details() const noexcept { return exception_details(this); } /** * @brief Set exception information. * This is same as calling @c set_info. * * @tparam T type of appended value, is a @c tag type * @param value value to set * @return @c *this */ template <class T> typename std::enable_if<std::is_base_of<tag_base, T>::value, exception&>::type operator<<(const T& value) { set_info(value); return *this; } /** * @brief Append value to message. * * @tparam T type of appended value * @param value value to append * @return @c *this */ template <class T> typename std::enable_if<!std::is_base_of<tag_base, T>::value, exception&>::type operator<<(const T& value) { if (!m_raw_message_stream) { m_raw_message_stream = std::make_unique<std::stringstream>(); if (!m_raw_message.empty()) { (*m_raw_message_stream) << m_raw_message; m_raw_message.clear(); } } (*m_raw_message_stream) << value; return *this; } private: using exception_info_map = std::map<std::type_index, std::any>; exception_info_map m_infos; private: void copy_message_or_materialize(const exception& e); void materialize_message() const; mutable std::unique_ptr<std::stringstream> m_raw_message_stream; mutable std::string m_raw_message; }; /** * @brief Exception cause. */ struct exception::cause : public tag<cause, mge::exception> { /** * @brief Capture causing exception. * * @param ex causing exception */ cause(const mge::exception& ex) : m_value(ex) {} /** * @brief Capture causing exception. * * @param ex causing exception */ cause(mge::exception&& ex) : m_value(std::move(ex)) {} const mge::exception& value() const noexcept { return m_value; } mge::exception m_value; }; /** * Throw exception instance. * @param ex exception type */ #define MGE_THROW(ex) \ throw(ex().set_info(mge::exception::source_file(__FILE__)) \ .set_info(mge::exception::source_line(__LINE__)) \ .set_info(mge::exception::function(MGE_FUNCTION_SIGNATURE)) \ .set_info(mge::exception::stack(mge::stacktrace())) \ .set_info(mge::exception::type_name(mge::type_name<ex>()))) /** * Throw exception and adds a cause. * @param ex exception type * @param causing_exception exception causing this exception */ #define MGE_THROW_WITH_CAUSE(ex, causing_exception) \ throw ex() \ .set_info(mge::exception::source_file(__FILE__)) \ .set_info(mge::exception::source_line(__LINE__)) \ .set_info(mge::exception::function(MGE_FUNCTION_SIGNATURE)) \ .set_info(mge::exception::stack(mge::stacktrace())) \ .set_info(mge::exception::type_name(mge::type_name<ex>())) \ .set_info(mge::exception::cause(causing_exception)) /** * @def MGE_CALLED_FUNCTION * @brief Helper to add called function to exception information. * @param X name of called function * This helper is usually used to attach additional information * to the exception, e.g. in case of system or foreign API errors. * @code * MGE_THROW(mge::exception) << MGE_CALLED_FUNCTION(fopen); * @endcode */ #define MGE_CALLED_FUNCTION(X) ::mge::exception::called_function(#X) /** * @brief Print exception message. * * @param os output stream * @param ex exception * @return @c os */ MGECORE_EXPORT std::ostream& operator<<(std::ostream& os, const exception& ex); /** * @brief Print exception details. * * @param os output stream * @param details wrapped exception * @return @c os */ MGECORE_EXPORT std::ostream& operator<<(std::ostream& os, const exception::exception_details& details); /** * @brief Re-throws the current exception. * * This function does not return. */ [[noreturn]] inline void rethrow() { throw; } } // namespace mge
29.054176
80
0.515345
mge-engine
f449581900d35f80d252e4c6b7048e79b825a99b
13,114
cpp
C++
samples/basic.cpp
fabriquer/lug
884a58531c359882585084e48625aa688208a7f6
[ "MIT" ]
53
2017-07-20T10:01:44.000Z
2022-02-13T04:57:22.000Z
samples/basic.cpp
fabriquer/lug
884a58531c359882585084e48625aa688208a7f6
[ "MIT" ]
4
2018-08-31T14:06:50.000Z
2020-06-17T17:34:20.000Z
samples/basic.cpp
fabriquer/lug
884a58531c359882585084e48625aa688208a7f6
[ "MIT" ]
6
2017-07-16T22:54:51.000Z
2019-12-04T13:15:12.000Z
// lug - Embedded DSL for PE grammar parser combinators in C++ // Copyright (c) 2017 Jesse W. Towner // See LICENSE.md file for license details // Derived from BASIC, Dartmouth College Computation Center, October 1st 1964 // http://www.bitsavers.org/pdf/dartmouth/BASIC_Oct64.pdf #include <lug/lug.hpp> #include <cmath> #include <cstdlib> #include <cstring> #include <deque> #include <fstream> #include <iomanip> #include <map> #ifdef _MSC_VER #include <io.h> #define fileno _fileno #define isatty _isatty #define strcasecmp _stricmp #define strncasecmp _strnicmp #else #include <unistd.h> #endif class basic_interpreter { public: basic_interpreter() { using namespace lug::language; rule Expr; implicit_space_rule SP = *"[ \t]"_rx; rule NL = lexeme["\n"_sx | "\r\n" | "\r"]; rule Func = lexeme[capture(id_)["[A-Za-z]"_rx > *"[0-9A-Za-z]"_rx]] <[this]{ return lug::utf8::toupper(*id_); }; rule LineNo = lexeme[capture(sv_)[+"[0-9]"_rx]] <[this]{ return std::stoi(std::string{*sv_}); }; rule Real = lexeme[capture(sv_)[+"[0-9]"_rx > ~("."_sx > +"[0-9]"_rx) > ~("[Ee]"_rx > ~"[+-]"_rx > +"[0-9]"_rx)]] <[this]{ return std::stod(std::string{*sv_}); }; rule String = lexeme["\"" > capture(sv_)[*"[^\"]"_rx] > "\""] <[this]{ return *sv_; }; rule Var = lexeme[capture(id_)["[A-Za-z]"_rx > ~"[0-9]"_rx]] <[this]{ return lug::utf8::toupper(*id_); }; rule RelOp = "=" <[]() -> RelOpFn { return [](double x, double y) { return x == y; }; } | ">=" <[]() -> RelOpFn { return std::isgreaterequal; } | ">" <[]() -> RelOpFn { return std::isgreater; } | "<=" <[]() -> RelOpFn { return std::islessequal; } | "<>" <[]() -> RelOpFn { return [](double x, double y) { return x != y; }; } | "<" <[]() -> RelOpFn { return std::isless; }; rule Ref = id_%Var > "(" > r1_%Expr > "," > r2_%Expr > ")" <[this]{ return &at(tables_[*id_], *r1_, *r2_); } | id_%Var > "(" > r1_%Expr > ")" <[this]{ return &at(lists_[*id_], *r1_); } | id_%Var <[this]{ return &vars_[*id_]; }; rule Value = !("[A-Z][A-Z][A-Z]"_irx > "(") > ( ref_%Ref <[this]{ return **ref_; } | Real | "(" > Expr > ")" ) | "SIN"_isx > "(" > r1_%Expr > ")" <[this]{ return std::sin(*r1_); } | "COS"_isx > "(" > r1_%Expr > ")" <[this]{ return std::cos(*r1_); } | "TAN"_isx > "(" > r1_%Expr > ")" <[this]{ return std::tan(*r1_); } | "ATN"_isx > "(" > r1_%Expr > ")" <[this]{ return std::atan(*r1_); } | "EXP"_isx > "(" > r1_%Expr > ")" <[this]{ return std::exp(*r1_); } | "ABS"_isx > "(" > r1_%Expr > ")" <[this]{ return std::abs(*r1_); } | "LOG"_isx > "(" > r1_%Expr > ")" <[this]{ return std::log(*r1_); } | "SQR"_isx > "(" > r1_%Expr > ")" <[this]{ return std::sqrt(*r1_); } | "INT"_isx > "(" > r1_%Expr > ")" <[this]{ return std::trunc(*r1_); } | "RND"_isx > "(" > r1_%Expr > ")" <[this]{ return std::rand() / static_cast<double>(RAND_MAX); }; rule Factor = r1_%Value > ~(u8"[↑^]"_rx > r2_%Value <[this]{ *r1_ = std::pow(*r1_, *r2_); } ) <[this]{ return *r1_; }; rule Term = r1_%Factor > *( "*"_sx > r2_%Factor <[this]{ *r1_ *= *r2_; } | "/"_sx > r2_%Factor <[this]{ *r1_ /= *r2_; } ) <[this]{ return *r1_; }; Expr = ( ~ "+"_sx > r1_%Term | "-"_sx > r1_%Term <[this]{ *r1_ = -*r1_; } ) > *( "+"_sx > r2_%Term <[this]{ *r1_ += *r2_; } | "-"_sx > r2_%Term <[this]{ *r1_ -= *r2_; } ) <[this]{ return *r1_; }; rule DimEl = id_%Var > "(" > r1_%Expr > "," > r2_%Expr > ")" <[this]{ dimension(tables_[*id_], *r1_, *r2_); } | id_%Var > "(" > r1_%Expr > ")" <[this]{ dimension(lists_[*id_], *r1_); }; rule ReadEl = ref_%Ref <[this]{ read(*ref_); }; rule DataEl = r1_%Real <[this]{ data_.push_back(*r1_); }; rule InptEl = ref_%Ref <[this]{ std::cin >> **ref_; }; rule PrntEl = sv_%String <[this]{ std::cout << *sv_; } | r1_%Expr <[this]{ std::cout << *r1_; }; rule Stmnt = "IF"_isx > r1_%Expr > rop_%RelOp > r2_%Expr <[this]{ if (!(*rop_)(*r1_, *r2_)) { environment_.escape(); } } > "THEN"_isx > Stmnt | "FOR"_isx > id_%Var > "=" > r1_%Expr > "TO"_isx > r2_%Expr > ( "STEP"_isx > r3_%Expr | eps < [this]{ *r3_ = 1.0; } ) <[this]{ for_to_step(*id_, *r1_, *r2_, *r3_); } | "NEXT"_isx > id_%Var <[this]{ next(*id_); } | "GOTO"_isx > no_%LineNo <[this]{ goto_line(*no_); } | "LET"_isx > ref_%Ref > "=" > r1_%Expr <[this]{ **ref_ = *r1_; } | "DIM"_isx > DimEl > *("," > DimEl) | "RESTORE"_isx <[this]{ read_itr_ = data_.cbegin(); } | "READ"_isx > ReadEl > *("," > ReadEl) | "INPUT"_isx > InptEl > *("," > InptEl) | "PRINT"_isx > ~PrntEl > *("," > PrntEl) <[this]{ std::cout << std::endl; } | "GOSUB"_isx > no_%LineNo <[this]{ gosub(*no_); } | "RETURN"_isx <[this]{ retsub(); } | "STOP"_isx <[this]{ haltline_ = line_; line_ = lines_.end(); } | "END"_isx <[this]{ if (line_ == lines_.end()) std::exit(EXIT_SUCCESS); line_ = lines_.end(); } | ("EXIT"_isx | "QUIT"_isx) <[this]{ std::exit(EXIT_SUCCESS); } | "REM"_isx > *(!NL > any); rule Cmnd = "CLEAR"_isx <[this]{ lines_.clear(); } | "CONT"_isx <[this]{ cont(); } | "LIST"_isx <[this]{ list(std::cout); } | "LOAD"_isx > sv_%String <[this]{ load(*sv_); } | "RUN"_isx <[this]{ line_ = lines_.begin(); read_itr_ = data_.cbegin(); } | "SAVE"_isx > sv_%String <[this]{ save(*sv_); }; rule Line = Stmnt > NL | Cmnd > NL | no_%LineNo > capture(sv_)[*(!NL > any) > NL] <[this]{ update_line(*no_, *sv_); } | NL | (*(!NL > any) > NL) <[this]{ print_error("ILLEGAL FORMULA"); } | !any <[this]{ std::exit(EXIT_SUCCESS); }; grammar_ = start(Line); } void repl() { lug::parser parser{grammar_, environment_}; parser.push_source([this](std::string& out) { if (line_ != lines_.end()) { lastline_ = line_++; out = lastline_->second; } else { if (stdin_tty_) std::cout << "> " << std::flush; if (!std::getline(std::cin, out)) return false; out.push_back('\n'); } return true; }); while (parser.parse()) ; } void load(std::string_view name) { std::ifstream file{filename_with_ext(name), std::ifstream::in}; if (file) { while (!file.bad() && !file.eof()) { int lineno; std::string line; if (file >> lineno && std::getline(file >> std::ws, line)) { update_line(lineno, line + "\n"); } else { file.clear(); file.ignore(std::numeric_limits<std::streamsize>::max(), file.widen('\n')); } } } else { print_error("FILE DOES NOT EXIST"); } } private: struct List { std::vector<double> values = std::vector<double>(11, 0.0); }; struct Table { std::vector<double> values = std::vector<double>(121, 0.0); std::size_t width = 11, height = 11; }; using RelOpFn = bool(*)(double, double); std::string filename_with_ext(std::string_view name) { std::string filename{name}; if (filename.size() < 4 || strncasecmp(filename.data() + filename.size() - 4, ".BAS", 4) != 0) filename.append(".BAS"); return filename; } void print_error(char const* message) { std::cerr << message << "\n"; if (lastline_ != lines_.end()) std::cerr << "LINE " << lastline_->first << ": " << lastline_->second << std::flush; line_ = lastline_ = lines_.end(); stack_.clear(), for_stack_.clear(); } void cont() { line_ = haltline_; haltline_ = lines_.end(); if (line_ == haltline_) print_error("CAN'T CONTINUE"); } void list(std::ostream& out) { for (auto const& [n, l] : lines_) out << n << "\t" << l; out << std::flush; } void save(std::string_view name) { std::ofstream file{filename_with_ext(name), std::ofstream::out}; if (file) list(file); else print_error("UNABLE TO SAVE TO FILE"); } void update_line(int n, std::string_view s) { haltline_ = lines_.end(); if (s.empty() || s.front() < ' ') lines_.erase(n); else lines_[n] = s; } bool goto_line(int n) { if (lastline_ = line_, line_ = lines_.find(n); line_ == lines_.end()) { print_error("ILLEGAL LINE NUMBER"); return false; } return true; } void gosub(int n) { lastline_ = line_; if (goto_line(n)) stack_.push_back(lastline_); } void retsub() { if (!stack_.empty()) line_ = stack_.back(), stack_.pop_back(); else print_error("ILLEGAL RETURN"); } void for_to_step(std::string const& id, double from, double to, double step) { if (lastline_ != lines_.end()) { double& v = vars_[id]; v += step; if (for_stack_.empty() || id != for_stack_.back().first) { for_stack_.emplace_back(id, lastline_); v = from; } if ((step >= 0 && v <= to) || (step < 0 && v >= to)) return; for_stack_.pop_back(); for (auto k = id.size(); line_ != lines_.end(); ++line_) { auto& t = line_->second; if (auto n = t.size(); n > 4 && !strncasecmp(t.data(), "NEXT", 4)) { if (auto i = t.find_first_not_of(" \t", 4); i != std::string::npos && i + k <= n && !strncasecmp(t.data() + i, id.data(), k)) { lastline_ = line_++; return; } } } } print_error("FOR WITHOUT NEXT"); } void next(std::string const& id) { if (lastline_ != lines_.end() && !for_stack_.empty() && for_stack_.back().first == id) { lastline_ = line_; line_ = for_stack_.back().second; } else { print_error("NOT MATCH WITH FOR"); } } void read(double* ref) { if (read_itr_ != data_.cend()) *ref = *(read_itr_++); else print_error("NO DATA"); } double& at(List& lst, double i) { auto const index = static_cast<std::size_t>(i); if (index < lst.values.size()) return lst.values[index]; print_error("ARRAY INDEX OUT OF RANGE"); return (invalid_value_ = std::numeric_limits<double>::quiet_NaN()); } double& at(Table& tab, double i, double j) { auto const row = static_cast<std::size_t>(i), col = static_cast<std::size_t>(j); if (row < tab.height || col < tab.width) return tab.values[tab.width * row + col]; print_error("ARRAY INDEX OUT OF RANGE"); return (invalid_value_ = std::numeric_limits<double>::quiet_NaN()); } void dimension(List& lst, double n) { if (n < 0.0) print_error("ARRAY SIZE OUT OF RANGE"); else lst.values = std::vector<double>(static_cast<std::size_t>(n) + 1, 0.0); } void dimension(Table& tab, double m, double n) { if (m < 0.0 || n < 0.0) { print_error("ARRAY SIZE OUT OF RANGE"); } else { tab.width = static_cast<std::size_t>(m) + 1; tab.height = static_cast<std::size_t>(n) + 1; tab.values = std::vector<double>(tab.width * tab.height, 0.0); } } lug::grammar grammar_; lug::environment environment_; lug::variable<std::string> id_{environment_}; lug::variable<std::string_view> sv_{environment_}; lug::variable<double> r1_{environment_}, r2_{environment_}, r3_{environment_}; lug::variable<int> no_{environment_}; lug::variable<double*> ref_{environment_}; lug::variable<RelOpFn> rop_{environment_}; std::deque<double> data_; std::deque<double>::const_iterator read_itr_; std::unordered_map<std::string, double> vars_; std::unordered_map<std::string, List> lists_; std::unordered_map<std::string, Table> tables_; std::map<int, std::string> lines_; std::map<int, std::string>::iterator line_{lines_.end()}, lastline_{lines_.end()}, haltline_{lines_.end()}; std::vector<std::map<int, std::string>::iterator> stack_; std::vector<std::pair<std::string, std::map<int, std::string>::iterator>> for_stack_; double invalid_value_{std::numeric_limits<double>::quiet_NaN()}; bool const stdin_tty_{isatty(fileno(stdin)) != 0}; }; int main(int argc, char** argv) { try { basic_interpreter interpreter; while (--argc > 1) interpreter.load(*++argv); interpreter.repl(); } catch (std::exception& e) { std::cerr << "ERROR: " << e.what() << std::endl; return -1; } return 0; }
35.928767
133
0.516852
fabriquer
f44ab1aea43bc79fc0c47f9c39d8ad1bb618c21d
619
cpp
C++
examples/CBuilder/Compound/ModelEvolution/Common/dSystemTypeInfo.cpp
LenakeTech/BoldForDelphi
3ef25517d5c92ebccc097c6bc2f2af62fc506c71
[ "MIT" ]
121
2020-09-22T10:46:20.000Z
2021-11-17T12:33:35.000Z
examples/CBuilder/Compound/ModelEvolution/Common/dSystemTypeInfo.cpp
LenakeTech/BoldForDelphi
3ef25517d5c92ebccc097c6bc2f2af62fc506c71
[ "MIT" ]
8
2020-09-23T12:32:23.000Z
2021-07-28T07:01:26.000Z
examples/CBuilder/Compound/ModelEvolution/Common/dSystemTypeInfo.cpp
LenakeTech/BoldForDelphi
3ef25517d5c92ebccc097c6bc2f2af62fc506c71
[ "MIT" ]
42
2020-09-22T14:37:20.000Z
2021-10-04T10:24:12.000Z
//--------------------------------------------------------------------------- #include <vcl.h> #pragma hdrstop #include "dSystemTypeInfo.h" //--------------------------------------------------------------------------- #pragma package(smart_init) #pragma link "BoldHandles" #pragma link "BoldSubscription" #pragma resource "*.dfm" TdmSystemTypeInfo *dmSystemTypeInfo; //--------------------------------------------------------------------------- __fastcall TdmSystemTypeInfo::TdmSystemTypeInfo(TComponent* Owner) : TDataModule(Owner) { } //---------------------------------------------------------------------------
32.578947
77
0.390953
LenakeTech
f44ad3e847afa0014af02a60083c04175689a6e2
1,783
cpp
C++
src/pipeline/profile.cpp
seagull1993/librealsense
18cf36775c16efd1f727b656c7e88a928a53a427
[ "Apache-2.0" ]
6,457
2016-01-21T03:56:07.000Z
2022-03-31T11:57:15.000Z
src/pipeline/profile.cpp
seagull1993/librealsense
18cf36775c16efd1f727b656c7e88a928a53a427
[ "Apache-2.0" ]
8,393
2016-01-21T09:47:28.000Z
2022-03-31T22:21:42.000Z
src/pipeline/profile.cpp
seagull1993/librealsense
18cf36775c16efd1f727b656c7e88a928a53a427
[ "Apache-2.0" ]
4,874
2016-01-21T09:20:08.000Z
2022-03-31T15:18:00.000Z
// License: Apache 2.0. See LICENSE file in root directory. // Copyright(c) 2015 Intel Corporation. All Rights Reserved. #include "profile.h" #include "media/record/record_device.h" #include "media/ros/ros_writer.h" namespace librealsense { namespace pipeline { profile::profile(std::shared_ptr<device_interface> dev, util::config config, const std::string& to_file) : _dev(dev), _to_file(to_file) { if (!to_file.empty()) { if (!dev) throw librealsense::invalid_value_exception("Failed to create a profile, device is null"); _dev = std::make_shared<record_device>(dev, std::make_shared<ros_writer>(to_file, dev->compress_while_record())); } _multistream = config.resolve(_dev.get()); } std::shared_ptr<device_interface> profile::get_device() { //profile can be retrieved from a pipeline_config and pipeline::start() //either way, it is created by the pipeline //TODO: handle case where device has disconnected and reconnected //TODO: remember to recreate the device as record device in case of to_file.empty() == false if (!_dev) { throw std::runtime_error("Device is unavailable"); } return _dev; } stream_profiles profile::get_active_streams() const { auto profiles_per_sensor = _multistream.get_profiles_per_sensor(); stream_profiles profiles; for (auto&& kvp : profiles_per_sensor) for (auto&& p : kvp.second) profiles.push_back(p); return profiles; } } }
33.641509
129
0.583847
seagull1993
f45212aa6b029307dd24242672315effb4ceb9cc
2,917
cc
C++
ortools/math_opt/samples/integer_programming.cc
bollhals/or-tools
87cc5a1cb12d901089de0aab55f7ec50bce2cdfd
[ "Apache-2.0" ]
null
null
null
ortools/math_opt/samples/integer_programming.cc
bollhals/or-tools
87cc5a1cb12d901089de0aab55f7ec50bce2cdfd
[ "Apache-2.0" ]
null
null
null
ortools/math_opt/samples/integer_programming.cc
bollhals/or-tools
87cc5a1cb12d901089de0aab55f7ec50bce2cdfd
[ "Apache-2.0" ]
null
null
null
// Copyright 2010-2021 Google LLC // 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. // Simple integer programming example #include <iostream> #include <limits> #include "absl/flags/parse.h" #include "absl/flags/usage.h" #include "absl/status/statusor.h" #include "absl/time/time.h" #include "ortools/base/logging.h" #include "ortools/math_opt/cpp/math_opt.h" namespace { using ::operations_research::math_opt::Model; using ::operations_research::math_opt::SolveResult; using ::operations_research::math_opt::SolverType; using ::operations_research::math_opt::TerminationReason; using ::operations_research::math_opt::Variable; using ::operations_research::math_opt::VariableMap; constexpr double kInf = std::numeric_limits<double>::infinity(); // Model and solve the problem: // max x + 10 * y // s.t. x + 7 * y <= 17.5 // x <= 3.5 // x in {0.0, 1.0, 2.0, ..., // y in {0.0, 1.0, 2.0, ..., // void SolveSimpleMIP() { Model model("Integer programming example"); // Variables const Variable x = model.AddIntegerVariable(0.0, kInf, "x"); const Variable y = model.AddIntegerVariable(0.0, kInf, "y"); // Constraints model.AddLinearConstraint(x + 7 * y <= 17.5, "c1"); model.AddLinearConstraint(x <= 3.5, "c2"); // Objective model.Maximize(x + 10 * y); std::cout << "Num variables: " << model.num_variables() << std::endl; std::cout << "Num constraints: " << model.num_linear_constraints() << std::endl; const SolveResult result = Solve(model, SolverType::kGscip).value(); // Check for warnings. for (const auto& warning : result.warnings) { LOG(ERROR) << "Solver warning: " << warning << std::endl; } // Check that the problem has an optimal solution. QCHECK_EQ(result.termination.reason, TerminationReason::kOptimal) << "Failed to find an optimal solution: " << result.termination; std::cout << "Problem solved in " << result.solve_time() << std::endl; std::cout << "Objective value: " << result.objective_value() << std::endl; const double x_val = result.variable_values().at(x); const double y_val = result.variable_values().at(y); std::cout << "Variable values: [x=" << x_val << ", y=" << y_val << "]" << std::endl; } } // namespace int main(int argc, char** argv) { google::InitGoogleLogging(argv[0]); absl::ParseCommandLine(argc, argv); SolveSimpleMIP(); return 0; }
33.147727
76
0.675694
bollhals
f45239977eb81a0662fa9614d652ad55f0557382
5,504
cpp
C++
dali-toolkit/internal/image-loader/atlas-packer.cpp
pwisbey/dali-toolkit
aeb2a95e6cb48788c99d0338dd9788c402ebde07
[ "Apache-2.0" ]
null
null
null
dali-toolkit/internal/image-loader/atlas-packer.cpp
pwisbey/dali-toolkit
aeb2a95e6cb48788c99d0338dd9788c402ebde07
[ "Apache-2.0" ]
null
null
null
dali-toolkit/internal/image-loader/atlas-packer.cpp
pwisbey/dali-toolkit
aeb2a95e6cb48788c99d0338dd9788c402ebde07
[ "Apache-2.0" ]
null
null
null
/* * Copyright (c) 2015 Samsung Electronics Co., Ltd. * * 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. * */ // CLASS HEADER #include "atlas-packer.h" // EXTERNAL HEADER #include <stdlib.h> // For abs() namespace Dali { namespace Toolkit { namespace Internal { namespace { bool ApproximatelyEqual( uint32_t a, uint32_t b ) { return abs( a-b ) <= 1; } } AtlasPacker::Node::Node( Node* parent, SizeType x, SizeType y, SizeType width, SizeType height ) : rectArea( x, y, width, height ), parent(parent), occupied( false ) { child[0] = NULL; child[1] = NULL; } AtlasPacker:: AtlasPacker( SizeType atlasWidth, SizeType atlasHeight ) : mAvailableArea( atlasWidth * atlasHeight ) { mRoot = new Node( NULL, 0u, 0u, atlasWidth, atlasHeight ); } AtlasPacker::~AtlasPacker() { DeleteNode( mRoot ); } bool AtlasPacker::Pack( SizeType blockWidth, SizeType blockHeight, SizeType& packPositionX, SizeType& packPositionY) { Node* firstFit = InsertNode( mRoot, blockWidth, blockHeight ); if( firstFit != NULL ) { firstFit->occupied = true; packPositionX = firstFit->rectArea.x; packPositionY = firstFit->rectArea.y; mAvailableArea -= blockWidth*blockHeight; return true; } return false; } void AtlasPacker::DeleteBlock( SizeType packPositionX, SizeType packPositionY, SizeType blockWidth, SizeType blockHeight ) { Node* node = SearchNode( mRoot, packPositionX, packPositionY, blockWidth, blockHeight ); if( node != NULL ) { mAvailableArea += blockWidth*blockHeight; MergeToNonOccupied( node ); } } unsigned int AtlasPacker::GetAvailableArea() const { return mAvailableArea; } AtlasPacker::Node* AtlasPacker::InsertNode( Node* root, SizeType blockWidth, SizeType blockHeight ) { if( root == NULL ) { return NULL; } if( root->occupied ) { // if not the leaf, then try insert into the first child. Node* newNode = InsertNode(root->child[0], blockWidth, blockHeight); if( newNode == NULL )// no room, try insert into the second child. { newNode = InsertNode(root->child[1], blockWidth, blockHeight); } return newNode; } // too small, return if( root->rectArea.width < blockWidth || root->rectArea.height < blockHeight ) { return NULL; } // right size, accept if( root->rectArea.width == blockWidth && root->rectArea.height == blockHeight ) { return root; } //too much room, need to split SplitNode( root, blockWidth, blockHeight ); // insert into the first child created. return InsertNode( root->child[0], blockWidth, blockHeight); } void AtlasPacker::SplitNode( Node* node, SizeType blockWidth, SizeType blockHeight ) { node->occupied = true; // decide which way to split SizeType remainingWidth = node->rectArea.width - blockWidth; SizeType remainingHeight = node->rectArea.height - blockHeight; if( remainingWidth > remainingHeight ) // split vertically { node->child[0] = new Node( node, node->rectArea.x, node->rectArea.y, blockWidth, node->rectArea.height ); node->child[1] = new Node( node, node->rectArea.x+blockWidth, node->rectArea.y, node->rectArea.width-blockWidth, node->rectArea.height ); } else // split horizontally { node->child[0] = new Node( node, node->rectArea.x, node->rectArea.y, node->rectArea.width, blockHeight ); node->child[1] = new Node( node, node->rectArea.x, node->rectArea.y+blockHeight, node->rectArea.width, node->rectArea.height-blockHeight ); } } AtlasPacker::Node* AtlasPacker::SearchNode( Node* node, SizeType packPositionX, SizeType packPositionY, SizeType blockWidth, SizeType blockHeight ) { if( node != NULL ) { if( node->child[0] != NULL) //not a leaf { Node* newNode = SearchNode(node->child[0], packPositionX, packPositionY, blockWidth, blockHeight); if( newNode == NULL )// try search from the second child. { newNode = SearchNode(node->child[1], packPositionX, packPositionY, blockWidth, blockHeight); } return newNode; } else if( ApproximatelyEqual(node->rectArea.x, packPositionX) && ApproximatelyEqual(node->rectArea.y, packPositionY ) && ApproximatelyEqual(node->rectArea.width, blockWidth) && ApproximatelyEqual( node->rectArea.height, blockHeight) ) { return node; } } return NULL; } void AtlasPacker::MergeToNonOccupied( Node* node ) { node->occupied = false; Node* parent = node->parent; // both child are not occupied, merge the space to parent if( parent != NULL && parent->child[0]->occupied == false && parent->child[1]->occupied == false) { delete parent->child[0]; parent->child[0] = NULL; delete parent->child[1]; parent->child[1] = NULL; MergeToNonOccupied( parent ); } } void AtlasPacker::DeleteNode( Node *node ) { if( node != NULL ) { DeleteNode( node->child[0] ); DeleteNode( node->child[1] ); delete node; } } } // namespace Internal } // namespace Toolkit } // namespace Dali
27.1133
148
0.683866
pwisbey
f45448509a0b8e87a7012398a743007c74b9413d
9,952
cpp
C++
src/main.cpp
yafeiwang89/liver2gui
77c8b0e54a106682fe392e64108402e886440206
[ "BSD-3-Clause" ]
null
null
null
src/main.cpp
yafeiwang89/liver2gui
77c8b0e54a106682fe392e64108402e886440206
[ "BSD-3-Clause" ]
null
null
null
src/main.cpp
yafeiwang89/liver2gui
77c8b0e54a106682fe392e64108402e886440206
[ "BSD-3-Clause" ]
1
2020-06-09T20:16:58.000Z
2020-06-09T20:16:58.000Z
/* ############################################################################# # If you use PhysiCell in your project, please cite PhysiCell and the ver- # # sion number, such as below: # # # # We implemented and solved the model using PhysiCell (Version 1.2.0) [1]. # # # # [1] A Ghaffarizadeh, SH Friedman, SM Mumenthaler, and P Macklin, # # PhysiCell: an Open Source Physics-Based Cell Simulator for # # Multicellular Systems, PLoS Comput. Biol. 2017 (in revision). # # preprint DOI: 10.1101/088773 # # # # Because PhysiCell extensively uses BioFVM, we suggest you also cite # # BioFVM as below: # # # # We implemented and solved the model using PhysiCell (Version 1.2.0) [1], # # with BioFVM [2] to solve the transport equations. # # # # [1] A Ghaffarizadeh, SH Friedman, SM Mumenthaler, and P Macklin, # # PhysiCell: an Open Source Physics-Based Cell Simulator for # # Multicellular Systems, PLoS Comput. Biol. 2017 (in revision). # # preprint DOI: 10.1101/088773 # # # # [2] A Ghaffarizadeh, SH Friedman, and P Macklin, BioFVM: an efficient # # parallelized diffusive transport solver for 3-D biological simulations,# # Bioinformatics 32(8): 1256-8, 2016. DOI: 10.1093/bioinformatics/btv730 # # # ############################################################################# # # # BSD 3-Clause License (see https://opensource.org/licenses/BSD-3-Clause) # # # # Copyright (c) 2015-2017, Paul Macklin and the PhysiCell Project # # 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. # # # # 3. Neither the name of the copyright holder nor the names of its # # contributors may be used to endorse or promote products derived from this # # software without specific prior written permission. # # # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED # # TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A # # PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER # # OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, # # EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, # # PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR # # PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF # # LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING # # NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # # # ############################################################################# */ #include <cstdio> #include <cstdlib> #include <iostream> #include <ctime> #include <cmath> #include <omp.h> #include <fstream> #include "./core/PhysiCell.h" #include "./modules/PhysiCell_standard_modules.h" // put custom code modules here! #include "./custom_modules/liver.h" using namespace BioFVM; using namespace PhysiCell; int main( int argc, char* argv[] ) { // load and parse settings file(s) bool XML_status = false; if( argc > 1 ) { XML_status = load_PhysiCell_config_file( argv[1] ); } else { XML_status = load_PhysiCell_config_file( "./config/PhysiCell_settings.xml" ); } if( !XML_status ) { exit(-1); } // OpenMP setup omp_set_num_threads(PhysiCell_settings.omp_num_threads); // PNRG setup SeedRandom(); // time setup std::string time_units = "min"; setup_liver(); // some more setup Cell* pC = create_cell( HCT116 ); pC->assign_position( 0,0,0 ); /* Users typically stop modifying here. END USERMODS */ // set MultiCellDS save options set_save_biofvm_mesh_as_matlab( true ); set_save_biofvm_data_as_matlab( true ); set_save_biofvm_cell_data( true ); set_save_biofvm_cell_data_as_custom_matlab( true ); // save a simulation snapshot char filename[1024]; sprintf( filename , "%s/initial" , PhysiCell_settings.folder.c_str() ); save_PhysiCell_to_MultiCellDS_xml_pugi( filename , microenvironment , PhysiCell_globals.current_time ); // save a quick SVG cross section through z = 0, after setting its // length bar to 200 microns PhysiCell_SVG_options.length_bar = 1000; // for simplicity, set a pathology coloring function std::vector<std::string> (*cell_coloring_function)(Cell*) = liver_strain_coloring_function; // false_cell_coloring_Ki67; sprintf( filename , "%s/initial.svg" , PhysiCell_settings.folder.c_str() ); SVG_plot( filename , microenvironment, 0.0 , PhysiCell_globals.current_time, cell_coloring_function ); // set the performance timers BioFVM::RUNTIME_TIC(); BioFVM::TIC(); std::ofstream report_file; if( PhysiCell_settings.enable_legacy_saves == true ) { sprintf( filename , "%s/simulation_report.txt" , PhysiCell_settings.folder.c_str() ); report_file.open(filename); // create the data log file report_file<<"simulated time\tnum cells\tnum division\tnum death\twall time"<<std::endl; } // main loop try { while( PhysiCell_globals.current_time < PhysiCell_settings.max_time + 0.1*diffusion_dt ) { // save data if it's time. if( fabs( PhysiCell_globals.current_time - PhysiCell_globals.next_full_save_time ) < 0.01 * diffusion_dt ) { display_simulation_status( std::cout ); if( PhysiCell_settings.enable_legacy_saves == true ) { log_output( PhysiCell_globals.current_time , PhysiCell_globals.full_output_index, microenvironment, report_file); } if( PhysiCell_settings.enable_full_saves == true ) { sprintf( filename , "%s/output%08u" , PhysiCell_settings.folder.c_str(), PhysiCell_globals.full_output_index ); save_PhysiCell_to_MultiCellDS_xml_pugi( filename , microenvironment , PhysiCell_globals.current_time ); } PhysiCell_globals.full_output_index++; PhysiCell_globals.next_full_save_time += PhysiCell_settings.full_save_interval; } // save SVG plot if it's time if( fabs( PhysiCell_globals.current_time - PhysiCell_globals.next_SVG_save_time ) < 0.01 * diffusion_dt ) { if( PhysiCell_settings.enable_SVG_saves == true ) { sprintf( filename , "%s/snapshot%08u.svg" , PhysiCell_settings.folder.c_str() , PhysiCell_globals.SVG_output_index ); SVG_plot( filename , microenvironment, 0.0 , PhysiCell_globals.current_time, cell_coloring_function ); PhysiCell_globals.SVG_output_index++; PhysiCell_globals.next_SVG_save_time += PhysiCell_settings.SVG_save_interval; } } // run the liver model advance_liver_model( diffusion_dt ); // update the microenvironment microenvironment.simulate_diffusion_decay( diffusion_dt ); // run PhysiCell ((Cell_Container *)microenvironment.agent_container)->update_all_cells( PhysiCell_globals.current_time ); PhysiCell_globals.current_time += diffusion_dt; } if( PhysiCell_settings.enable_legacy_saves == true ) { log_output(PhysiCell_globals.current_time, PhysiCell_globals.full_output_index, microenvironment, report_file); report_file.close(); } } catch( const std::exception& e ) { // reference to the base of a polymorphic object std::cout << e.what(); // information from length_error printed } // save a final simulation snapshot sprintf( filename , "%s/final" , PhysiCell_settings.folder.c_str() ); save_PhysiCell_to_MultiCellDS_xml_pugi( filename , microenvironment , PhysiCell_globals.current_time ); sprintf( filename , "%s/final.svg" , PhysiCell_settings.folder.c_str() ); SVG_plot( filename , microenvironment, 0.0 , PhysiCell_globals.current_time, cell_coloring_function ); // timer std::cout << std::endl << "Total simulation runtime: " << std::endl; BioFVM::display_stopwatch_value( std::cout , BioFVM::runtime_stopwatch_value() ); return 0; }
43.649123
123
0.58963
yafeiwang89
f45a441e40b04c7a67ee2f8beec28f9650f6f103
1,936
cpp
C++
inference-engine/src/vpu/common/src/ngraph/transformations/dynamic_to_static_shape_transpose.cpp
asenina/openvino
3790b3506091d132e2bbe491755001b0decc84db
[ "Apache-2.0" ]
null
null
null
inference-engine/src/vpu/common/src/ngraph/transformations/dynamic_to_static_shape_transpose.cpp
asenina/openvino
3790b3506091d132e2bbe491755001b0decc84db
[ "Apache-2.0" ]
null
null
null
inference-engine/src/vpu/common/src/ngraph/transformations/dynamic_to_static_shape_transpose.cpp
asenina/openvino
3790b3506091d132e2bbe491755001b0decc84db
[ "Apache-2.0" ]
null
null
null
// Copyright (C) 2020 Intel Corporation // SPDX-License-Identifier: Apache-2.0 // #include "vpu/ngraph/transformations/dynamic_to_static_shape_transpose.hpp" #include "vpu/ngraph/operations/dynamic_shape_resolver.hpp" #include <vpu/utils/error.hpp> #include "ngraph/graph_util.hpp" #include "ngraph/opsets/opset3.hpp" #include <memory> namespace vpu { void dynamicToStaticShapeTranspose(std::shared_ptr<ngraph::Node> target) { const auto dsr = target->get_argument(0); VPU_THROW_UNLESS(ngraph::as_type_ptr<ngraph::vpu::op::DynamicShapeResolver>(dsr), "DynamicToStaticShape transformation for {} of type {} expects {} as input with index {}", target->get_friendly_name(), target->get_type_info(), ngraph::vpu::op::DynamicShapeResolver::type_info, 0); const auto transposition = target->get_argument(1); VPU_THROW_UNLESS(ngraph::as_type_ptr<ngraph::opset3::Constant>(transposition), "DynamicToStaticShape transformation for {] of type {} expects {} as input with index {}", target->get_friendly_name(), target->get_type_info(), ngraph::opset3::Constant::type_info, 1); const auto transpose = std::dynamic_pointer_cast<ngraph::opset3::Transpose>(target); const auto copied = transpose->copy_with_new_args(target->get_arguments()); const auto shape = dsr->input(1).get_source_output(); const auto axis = std::make_shared<ngraph::opset3::Constant>( ngraph::element::i64, ngraph::Shape{std::initializer_list<std::size_t>{1}}, std::vector<std::int64_t>{0}); const auto scatterElementsUpdate = std::make_shared<ngraph::opset3::ScatterElementsUpdate>(shape, transposition, shape, axis); auto outDSR = std::make_shared<ngraph::vpu::op::DynamicShapeResolver>(copied, scatterElementsUpdate); outDSR->set_friendly_name(transpose->get_friendly_name()); ngraph::replace_node(std::move(target), std::move(outDSR)); } } // namespace vpu
44
130
0.731405
asenina
f4629c897f06bdee647dec24d30f7218ba4b14fe
1,219
hpp
C++
valiant/sprite_renderer.hpp
claby2/valiant
d932574fe1f424c444a09ac99ae53fa2c7c4a9ac
[ "MIT" ]
null
null
null
valiant/sprite_renderer.hpp
claby2/valiant
d932574fe1f424c444a09ac99ae53fa2c7c4a9ac
[ "MIT" ]
null
null
null
valiant/sprite_renderer.hpp
claby2/valiant
d932574fe1f424c444a09ac99ae53fa2c7c4a9ac
[ "MIT" ]
null
null
null
#ifndef VALIANT_SPRITE_RENDERER_HPP #define VALIANT_SPRITE_RENDERER_HPP #define SDL_MAIN_HANDLED #include <SDL2/SDL.h> #include <SDL2/SDL_image.h> #include <string> #include "error.hpp" namespace valiant { struct Sprite { std::string path; int width{0}; int height{0}; SDL_Surface* surface; SDL_Texture* texture; Sprite() : path(""), surface(nullptr), texture(nullptr) {} Sprite& operator=(const std::string& new_path) { path = new_path; surface = IMG_Load(path.c_str()); if (!surface) { // Error encountered when loading image throw ValiantError(IMG_GetError()); } width = surface->w; height = surface->h; // Reset texture texture = nullptr; return *this; } void create_texture(SDL_Renderer* renderer) { texture = SDL_CreateTextureFromSurface(renderer, surface); SDL_FreeSurface(surface); } }; struct SpriteRendererComponent { Sprite sprite; bool flip_x{false}; bool flip_y{false}; SpriteRendererComponent() : sprite() {} }; class SpriteRenderer { public: SpriteRendererComponent sprite_renderer; }; }; // namespace valiant #endif
21.385965
66
0.64397
claby2
f463b59d45aba293705ee4538fa9c5333e4d5d16
836
hpp
C++
include/customizer/serialization.hpp
neilbu/osrm-backend
2a8e1f77459fef33ca34c9fe01ec62e88e255452
[ "BSD-2-Clause" ]
null
null
null
include/customizer/serialization.hpp
neilbu/osrm-backend
2a8e1f77459fef33ca34c9fe01ec62e88e255452
[ "BSD-2-Clause" ]
null
null
null
include/customizer/serialization.hpp
neilbu/osrm-backend
2a8e1f77459fef33ca34c9fe01ec62e88e255452
[ "BSD-2-Clause" ]
1
2021-11-24T14:24:44.000Z
2021-11-24T14:24:44.000Z
#ifndef OSRM_CUSTOMIZER_SERIALIZATION_HPP #define OSRM_CUSTOMIZER_SERIALIZATION_HPP #include "partition/cell_storage.hpp" #include "storage/io.hpp" #include "storage/serialization.hpp" #include "storage/shared_memory_ownership.hpp" namespace osrm { namespace customizer { namespace serialization { template <storage::Ownership Ownership> inline void read(storage::io::FileReader &reader, detail::CellMetricImpl<Ownership> &metric) { storage::serialization::read(reader, metric.weights); storage::serialization::read(reader, metric.durations); } template <storage::Ownership Ownership> inline void write(storage::io::FileWriter &writer, const detail::CellMetricImpl<Ownership> &metric) { storage::serialization::write(writer, metric.weights); storage::serialization::write(writer, metric.durations); } } } } #endif
23.885714
99
0.783493
neilbu
f4658709122414d4df7b5c21c1560364298d8a57
2,654
cpp
C++
11-stream_file/14-regex.cpp
stevenokm/cpp_tutorial
0cbc0917bcee8c503a3b9318e945a6ec662ac402
[ "MIT" ]
1
2021-09-23T00:35:43.000Z
2021-09-23T00:35:43.000Z
11-stream_file/14-regex.cpp
stevenokm/cpp_tutorial
0cbc0917bcee8c503a3b9318e945a6ec662ac402
[ "MIT" ]
null
null
null
11-stream_file/14-regex.cpp
stevenokm/cpp_tutorial
0cbc0917bcee8c503a3b9318e945a6ec662ac402
[ "MIT" ]
2
2021-08-30T05:34:42.000Z
2021-09-21T14:11:22.000Z
#include <iostream> #include <sstream> #include <string> #include <regex> int main() { std::string log = R"( [2021-10-13T14:47:22.050Z] info code-server 3.11.1 acb5de66b71a3f8f1cc065df4633ecd3f9788d46 [2021-10-13T14:47:22.051Z] info Using user-data-dir ~/.local/share/code-server [2021-10-13T14:47:22.059Z] info Using config file ~/.config/code-server/config.yaml [2021-10-13T14:47:22.059Z] info HTTP server listening on http://0.0.0.0:8080 [2021-10-13T14:47:22.059Z] info - Authentication is enabled [2021-10-13T14:47:22.059Z] info - Using password from ~/.config/code-server/config.yaml [2021-10-13T14:47:22.059Z] info - Not serving HTTPS [2021-10-13T14:47:22.185Z] error vscode is not running Error: vscode is not running at VscodeProvider.send (/usr/lib/code-server/out/node/vscode.js:121:19) at VscodeProvider.sendWebsocket (/usr/lib/code-server/out/node/vscode.js:117:14) at async /usr/lib/code-server/out/node/routes/vscode.js:205:5 [2021-10-13T14:47:22.435Z] error vscode is not running Error: vscode is not running at VscodeProvider.send (/usr/lib/code-server/out/node/vscode.js:121:19) at VscodeProvider.sendWebsocket (/usr/lib/code-server/out/node/vscode.js:117:14) at async /usr/lib/code-server/out/node/routes/vscode.js:205:5 INFO Detected extension installed from another source ms-python.python INFO Detected extension installed from another source ms-toolsai.jupyter [IPC Library: Pty Host] INFO Persistent process "1": Replaying 30070 chars and 1 size events [node.js fs] readdir with filetypes failed with error: [Error: ENOENT: no such file or directory, scandir '/home/coder/project/upload/210051214'] { errno: -2, code: 'ENOENT', syscall: 'scandir', path: '/home/coder/project/upload/210051214' } [node.js fs] readdir with filetypes failed with error: [Error: ENOENT: no such file or directory, scandir '/home/coder/project/upload/210051214'] { errno: -2, code: 'ENOENT', syscall: 'scandir', path: '/home/coder/project/upload/210051214' } )"; std::stringstream ss; ss << log; std::string prefix = R"(^\[\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z\])"; std::string level = R"((info|error))"; std::string pattern = prefix + R"(\s+)" + level; std::regex r(pattern, std::regex_constants::ECMAScript); std::smatch sm; while(!ss.eof()) { std::string line; std::getline(ss, line); if(std::regex_search(line, sm, r)) { std::string msg = sm.suffix(); //std::string keyword; //std::regex r_key(pattern); std::cout << msg << '\n'; } } return 0; }
40.830769
148
0.677845
stevenokm
f4692cadb178355504574ca04a011f5e9b145776
12,365
cpp
C++
Sources/Internal/UI/UISpinner.cpp
BlitzModder/dava.engine
0c7a16e627fc0d12309250d6e5e207333b35361e
[ "BSD-3-Clause" ]
4
2019-11-15T11:30:00.000Z
2021-12-27T21:16:31.000Z
Sources/Internal/UI/UISpinner.cpp
TTopox/dava.engine
0c7a16e627fc0d12309250d6e5e207333b35361e
[ "BSD-3-Clause" ]
null
null
null
Sources/Internal/UI/UISpinner.cpp
TTopox/dava.engine
0c7a16e627fc0d12309250d6e5e207333b35361e
[ "BSD-3-Clause" ]
4
2017-04-07T04:32:41.000Z
2021-12-27T21:55:49.000Z
#include "UISpinner.h" #include "UI/UIEvent.h" #include "Animation/Animation.h" #include "Reflection/ReflectionRegistrator.h" #include "UI/Update/UIUpdateComponent.h" #include "UI/Render/UIClipContentComponent.h" namespace DAVA { //use these names for children buttons to define UISpinner in .yaml static const FastName UISPINNER_BUTTON_NEXT_NAME("buttonNext"); static const FastName UISPINNER_BUTTON_PREVIOUS_NAME("buttonPrevious"); static const FastName UISPINNER_CONTENT_NAME("content"); static const float32 UISPINNER_ANIRMATION_TIME = 0.1f; static const int32 UISPINNER_MOVE_ANIMATION_TRACK = 10; static const float32 UISPINNER_X_UNDEFINED = 10000; static const float32 UISPINNER_SLIDE_GESTURE_SPEED = 20.f; static const float32 UISPINNER_SLIDE_GESTURE_TIME = 0.1f; DAVA_VIRTUAL_REFLECTION_IMPL(UISpinner) { ReflectionRegistrator<UISpinner>::Begin() .ConstructorByPointer() .DestructorByPointer([](UISpinner* o) { o->Release(); }) .End(); } void SpinnerAdapter::AddObserver(SelectionObserver* anObserver) { observers.insert(anObserver); } void SpinnerAdapter::RemoveObserver(SelectionObserver* anObserver) { observers.erase(anObserver); } void SpinnerAdapter::NotifyObservers(bool isSelectedFirst, bool isSelectedLast, bool isSelectedChanged) { Set<SelectionObserver*>::const_iterator end = observers.end(); for (Set<SelectionObserver*>::iterator it = observers.begin(); it != end; ++it) { (*it)->OnSelectedChanged(isSelectedFirst, isSelectedLast, isSelectedChanged); } } bool SpinnerAdapter::Next() { bool completedOk = SelectNext(); if (completedOk) NotifyObservers(false /*as we selected next it can't be first*/, IsSelectedLast(), true); return completedOk; } bool SpinnerAdapter::Previous() { bool completedOk = SelectPrevious(); if (completedOk) NotifyObservers(IsSelectedFirst(), false /*as we selected previous it can't be last*/, true); return completedOk; } void SpinnerAdapter::DisplaySelectedData(UISpinner* spinner) { FillScrollableContent(spinner->GetContent(), EIO_CURRENT); } UISpinner::UISpinner(const Rect& rect) : UIControl(rect) , adapter(nullptr) , buttonNext(new UIControl()) , buttonPrevious(new UIControl()) , content(new UIControl()) , nextContent(new UIControl()) , contentViewport(new UIControl()) , dragAnchorX(UISPINNER_X_UNDEFINED) , previousTouchX(UISPINNER_X_UNDEFINED) , currentTouchX(UISPINNER_X_UNDEFINED) , totalGestureTime(0) , totalGestureDx(0) { buttonNext->SetName(UISPINNER_BUTTON_NEXT_NAME); buttonPrevious->SetName(UISPINNER_BUTTON_PREVIOUS_NAME); content->SetName(UISPINNER_CONTENT_NAME); AddControl(buttonNext.Get()); AddControl(buttonPrevious.Get()); AddControl(content.Get()); contentViewport->AddControl(nextContent.Get()); contentViewport->SetInputEnabled(false); contentViewport->GetOrCreateComponent<UIClipContentComponent>(); GetOrCreateComponent<UIUpdateComponent>(); } UISpinner::~UISpinner() { SetAdapter(nullptr); } void UISpinner::Update(DAVA::float32 timeElapsed) { if (currentTouchX < UISPINNER_X_UNDEFINED) { Move move; move.dx = currentTouchX - previousTouchX; move.time = timeElapsed; moves.push_back(move); totalGestureDx += move.dx; totalGestureTime += move.time; if (totalGestureTime > UISPINNER_SLIDE_GESTURE_TIME) { List<Move>::iterator it = moves.begin(); totalGestureTime -= it->time; totalGestureDx -= it->dx; moves.erase(it); } previousTouchX = currentTouchX; } } void UISpinner::Input(UIEvent* currentInput) { if (NULL == adapter) { return; } if (content->IsAnimating(UISPINNER_MOVE_ANIMATION_TRACK)) { return; } Vector2 touchPos = currentInput->point; if (currentInput->phase == UIEvent::Phase::BEGAN) { if (content->IsPointInside(touchPos)) { content->relativePosition = Vector2(); content->SetPivot(Vector2()); contentViewport->AddControl(content.Get()); AddControl(contentViewport.Get()); dragAnchorX = touchPos.x - content->relativePosition.x; currentTouchX = touchPos.x; previousTouchX = currentTouchX; } else { dragAnchorX = UISPINNER_X_UNDEFINED; } } else if (currentInput->phase == UIEvent::Phase::DRAG) { if (dragAnchorX < UISPINNER_X_UNDEFINED) { currentTouchX = touchPos.x; float32 contentNewX = touchPos.x - dragAnchorX; float32 contentNewLeftEdge = contentNewX - content->GetPivotPoint().x; if (!(contentNewLeftEdge < 0 && adapter->IsSelectedLast()) && !(contentNewLeftEdge > 0 && adapter->IsSelectedFirst())) { if (contentNewX != 0) { if (content->relativePosition.x * contentNewX <= 0) //next content just appears or visible side changes { //adjust nextContent->pivotPoint to make more convenient setting of nextContent->relativePosition below Vector2 newPivotPoint = nextContent->GetPivotPoint(); newPivotPoint.x = contentNewX > 0 ? content->size.dx : -content->size.dx; nextContent->SetPivotPoint(newPivotPoint); adapter->FillScrollableContent(nextContent.Get(), contentNewX > 0 ? SpinnerAdapter::EIO_PREVIOUS : SpinnerAdapter::EIO_NEXT); } } content->relativePosition.x = contentNewX; nextContent->relativePosition.x = contentNewX; //for this to work we adjust pivotPoint above if (Abs(content->relativePosition.x) > content->size.dx / 2) { OnSelectWithSlide(content->relativePosition.x > 0); dragAnchorX = touchPos.x - content->relativePosition.x; } } } } else if (currentInput->phase == UIEvent::Phase::ENDED || currentInput->phase == UIEvent::Phase::CANCELLED) { if (dragAnchorX < UISPINNER_X_UNDEFINED) { if (totalGestureTime > 0) { float32 averageSpeed = totalGestureDx / totalGestureTime; bool selectPrevious = averageSpeed > 0; if (selectPrevious == content->relativePosition.x > 0) //switch only if selected item is already shifted in slide direction { bool isSelectedLast = selectPrevious ? adapter->IsSelectedFirst() : adapter->IsSelectedLast(); if (Abs(averageSpeed) > UISPINNER_SLIDE_GESTURE_SPEED && !isSelectedLast) { OnSelectWithSlide(selectPrevious); } } } Animation* animation = content->PositionAnimation(Vector2(0, content->relativePosition.y), UISPINNER_ANIRMATION_TIME, Interpolation::EASY_IN, UISPINNER_MOVE_ANIMATION_TRACK); animation->AddEvent(Animation::EVENT_ANIMATION_END, Message(this, &UISpinner::OnScrollAnimationEnd)); nextContent->PositionAnimation(Vector2(0, content->relativePosition.y), UISPINNER_ANIRMATION_TIME, Interpolation::EASY_IN, UISPINNER_MOVE_ANIMATION_TRACK); currentTouchX = UISPINNER_X_UNDEFINED; previousTouchX = UISPINNER_X_UNDEFINED; dragAnchorX = UISPINNER_X_UNDEFINED; moves.clear(); totalGestureTime = 0; totalGestureDx = 0; } } currentInput->SetInputHandledType(UIEvent::INPUT_HANDLED_HARD); // Drag is handled - see please DF-2508. } void UISpinner::OnSelectWithSlide(bool isPrevious) { RefPtr<UIControl> temp = content; content = nextContent; nextContent = temp; //save display position but change pivot points Vector2 newPivotPoint = nextContent->GetPivotPoint(); newPivotPoint.x -= content->GetPivotPoint().x; nextContent->SetPivotPoint(newPivotPoint); nextContent->relativePosition.x -= content->GetPivotPoint().x; content->relativePosition.x -= content->GetPivotPoint().x; newPivotPoint = content->GetPivotPoint(); newPivotPoint.x = 0; content->SetPivotPoint(newPivotPoint); if (isPrevious) adapter->Previous(); else adapter->Next(); } void UISpinner::OnScrollAnimationEnd(BaseObject* caller, void* param, void* callerData) { DVASSERT(NULL != contentViewport->GetParent()); content->SetPivotPoint(contentViewport->GetPivotPoint()); content->relativePosition = contentViewport->relativePosition; RemoveControl(contentViewport.Get()); AddControl(content.Get()); } void UISpinner::CopyDataFrom(UIControl* srcControl) { UIControl::CopyDataFrom(srcControl); SetupInternalControls(); UISpinner* src = DynamicTypeCheck<UISpinner*>(srcControl); SetAdapter(src->GetAdater()); } UISpinner* UISpinner::Clone() { UISpinner* control = new UISpinner(GetRect()); control->CopyDataFrom(this); return control; } void UISpinner::AddControl(UIControl* control) { UIControl::AddControl(control); if (control->GetName() == UISPINNER_BUTTON_NEXT_NAME && control != buttonNext.Get()) { buttonNext = control; } else if (control->GetName() == UISPINNER_BUTTON_PREVIOUS_NAME && control != buttonPrevious.Get()) { buttonPrevious = control; } } void UISpinner::RemoveControl(UIControl* control) { if (control == buttonNext.Get()) { buttonNext = nullptr; } else if (control == buttonPrevious.Get()) { buttonPrevious = nullptr; } UIControl::RemoveControl(control); } void UISpinner::LoadFromYamlNodeCompleted() { SetupInternalControls(); SetAdapter(nullptr); } void UISpinner::SetAdapter(SpinnerAdapter* anAdapter) { buttonNext->RemoveEvent(UIControl::EVENT_TOUCH_UP_INSIDE, Message(this, &UISpinner::OnNextPressed)); buttonPrevious->RemoveEvent(UIControl::EVENT_TOUCH_UP_INSIDE, Message(this, &UISpinner::OnPreviousPressed)); if (adapter) { adapter->RemoveObserver(this); SafeRelease(adapter); } adapter = SafeRetain(anAdapter); if (adapter) { adapter->DisplaySelectedData(this); adapter->AddObserver(this); buttonNext->AddEvent(UIControl::EVENT_TOUCH_UP_INSIDE, Message(this, &UISpinner::OnNextPressed)); buttonPrevious->AddEvent(UIControl::EVENT_TOUCH_UP_INSIDE, Message(this, &UISpinner::OnPreviousPressed)); } buttonNext->SetDisabled(!adapter || adapter->IsSelectedLast()); buttonPrevious->SetDisabled(!adapter || adapter->IsSelectedFirst()); } void UISpinner::OnNextPressed(DAVA::BaseObject* caller, void* param, void* callerData) { if (content->IsAnimating(UISPINNER_MOVE_ANIMATION_TRACK)) { return; } //buttonNext is disabled if we have no adapter or selected adapter element is last, so we don't need checks here adapter->Next(); } void UISpinner::OnPreviousPressed(DAVA::BaseObject* caller, void* param, void* callerData) { if (content->IsAnimating(UISPINNER_MOVE_ANIMATION_TRACK)) { return; } //buttonPrevious is disabled if we have no adapter or selected adapter element is first, so we don't need checks here adapter->Previous(); } void UISpinner::OnSelectedChanged(bool isSelectedFirst, bool isSelectedLast, bool isSelectedChanged) { buttonNext->SetDisabled(isSelectedLast); buttonPrevious->SetDisabled(isSelectedFirst); if (isSelectedChanged) { adapter->DisplaySelectedData(this); PerformEvent(UIControl::EVENT_VALUE_CHANGED, nullptr); } } void UISpinner::SetupInternalControls() { content = FindByName(UISPINNER_CONTENT_NAME, false); content->SetInputEnabled(false); contentViewport->SetRect(content->GetRect()); contentViewport->SetPivotPoint(content->GetPivotPoint()); nextContent->CopyDataFrom(content.Get()); nextContent->relativePosition = Vector2(); Vector2 newPivotPoint = nextContent->GetPivotPoint(); newPivotPoint.x = content->size.dx; nextContent->SetPivotPoint(newPivotPoint); } }
33.328841
186
0.671573
BlitzModder
f469355b193e56c177df94300d0ce34221270fb3
607
hpp
C++
cpmf/parallel/switch.hpp
xxthermidorxx/cpmf
134283d66665a4b5cf2452ded4614ca8b219cfd7
[ "MIT" ]
2
2015-01-21T01:23:36.000Z
2016-07-26T16:22:09.000Z
cpmf/parallel/switch.hpp
xxthermidorxx/cpmf
134283d66665a4b5cf2452ded4614ca8b219cfd7
[ "MIT" ]
2
2018-11-21T02:46:49.000Z
2018-12-02T10:53:32.000Z
cpmf/parallel/switch.hpp
xxthermidorxx/cpmf
134283d66665a4b5cf2452ded4614ca8b219cfd7
[ "MIT" ]
1
2016-12-11T12:57:49.000Z
2016-12-11T12:57:49.000Z
#ifndef CPMF_PARALLEL_SWITCH_HPP_ #define CPMF_PARALLEL_SWITCH_HPP_ #include "../common/common.hpp" #include "../utils/utils.hpp" #if defined TP_BASED #include "tp_based/tp_based.hpp" using namespace cpmf::parallel::tp_based; #elif defined FPSGD #include "fpsgd/fpsgd.hpp" using namespace cpmf::parallel::fpsgd; #endif namespace cpmf { namespace parallel { void train(const std::shared_ptr<cpmf::common::Matrix> R, std::shared_ptr<cpmf::common::Model> model, const cpmf::BaseParams &base_params); } // namespace parallel } // namespace cpmf #endif // CPMF_PARALLEL_SWITCH_HPP_
21.678571
57
0.741351
xxthermidorxx
f46ae5658725a597b2bfbe8eecf8d64038a7d3fc
7,942
cpp
C++
src/bindings/Scriptdev2/scripts/kalimdor/caverns_of_time/culling_of_stratholme/boss_salramm.cpp
mfooo/wow
3e5fad4cfdf0fd1c0a2fd7c9844e6f140a1bb32d
[ "OpenSSL" ]
1
2017-11-16T19:04:07.000Z
2017-11-16T19:04:07.000Z
src/bindings/Scriptdev2/scripts/kalimdor/caverns_of_time/culling_of_stratholme/boss_salramm.cpp
mfooo/wow
3e5fad4cfdf0fd1c0a2fd7c9844e6f140a1bb32d
[ "OpenSSL" ]
null
null
null
src/bindings/Scriptdev2/scripts/kalimdor/caverns_of_time/culling_of_stratholme/boss_salramm.cpp
mfooo/wow
3e5fad4cfdf0fd1c0a2fd7c9844e6f140a1bb32d
[ "OpenSSL" ]
null
null
null
/* Copyright (C) 2006 - 2010 ScriptDev2 <https://scriptdev2.svn.sourceforge.net/> * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ /* ScriptData SDName: instance_culling_of_stratholme SD%Complete: ?% SDComment: by MaxXx2021 SDCategory: Culling of Stratholme EndScriptData */ #include "precompiled.h" #include "def_culling_of_stratholme.h" enum { SAY_SALRAMM_AGGRO = -1594130, SAY_SALRAMM_DEATH = -1594131, SAY_SALRAMM_SLAY01 = -1594132, SAY_SALRAMM_SLAY02 = -1594133, SAY_SALRAMM_SLAY03 = -1594134, SAY_SALRAMM_STEAL01 = -1594135, SAY_SALRAMM_STEAL02 = -1594136, SAY_SALRAMM_STEAL03 = -1594137, SAY_SUMMON01 = -1594138, SAY_SUMMON02 = -1594139, SAY_BOOM01 = -1594140, SAY_BOOM02 = -1594141, SPELL_SB_N = 57725, SPELL_SB_H = 58827, SPELL_FLESH = 58845, SPELL_STEAL = 52708, SPELL_GNOUL_BLOW = 58825, SPELL_SUMMON_GNOUL = 52451, NPC_GNOUL = 27733 }; struct MANGOS_DLL_DECL boss_salrammAI : public ScriptedAI { boss_salrammAI(Creature *pCreature) : ScriptedAI(pCreature) { m_pInstance = (ScriptedInstance*)pCreature->GetInstanceData(); m_bIsHeroic = pCreature->GetMap()->IsRaidOrHeroicDungeon(); m_creature->SetActiveObjectState(true); Reset(); } ScriptedInstance* m_pInstance; bool m_bIsHeroic; uint32 ShadowBoltTimer; uint32 FleshTimer; uint32 StealTimer; uint32 SummonTimer; void Reset() { ShadowBoltTimer = 5000; FleshTimer = (urand(7000, 9000)); StealTimer = (urand(9000, 17000)); SummonTimer = (urand(12000, 17000)); if(m_pInstance) m_pInstance->SetData64(NPC_SALRAMM, m_creature->GetGUID()); } void Aggro(Unit* who) { DoScriptText(SAY_SALRAMM_AGGRO, m_creature); } void JustDied(Unit *killer) { DoScriptText(SAY_SALRAMM_DEATH, m_creature); if(m_pInstance) m_pInstance->SetData(TYPE_ENCOUNTER, DONE); } void KilledUnit(Unit* pVictim) { switch(rand()%3) { case 0: DoScriptText(SAY_SALRAMM_SLAY01, m_creature); break; case 1: DoScriptText(SAY_SALRAMM_SLAY02, m_creature); break; case 2: DoScriptText(SAY_SALRAMM_SLAY03, m_creature); break; } } void SpellHitTarget(Unit *target, const SpellEntry *spell) { if(spell->Id == SPELL_GNOUL_BLOW) if(target->GetTypeId() != TYPEID_PLAYER && target->GetEntry() == NPC_GNOUL) target->SetDisplayId(11686); } void UpdateAI(const uint32 diff) { if (!m_creature->SelectHostileTarget() || !m_creature->getVictim()) return; if (ShadowBoltTimer < diff) { DoCast(m_creature->getVictim(), m_bIsHeroic ? SPELL_SB_H : SPELL_SB_N); ShadowBoltTimer = (urand(5000, 6000)); }else ShadowBoltTimer -= diff; if (FleshTimer < diff) { if (Unit* target = m_creature->SelectAttackingTarget(ATTACKING_TARGET_RANDOM,0)) DoCast(target,SPELL_FLESH); FleshTimer = 7300; }else FleshTimer -= diff; if (StealTimer < diff) { if (Unit* target = m_creature->SelectAttackingTarget(ATTACKING_TARGET_RANDOM,0)) DoCast(target,SPELL_STEAL); switch(rand()%3) { case 0: DoScriptText(SAY_SALRAMM_STEAL01, m_creature); break; case 1: DoScriptText(SAY_SALRAMM_STEAL02, m_creature); break; case 2: DoScriptText(SAY_SALRAMM_STEAL03, m_creature); break; } StealTimer = (urand(8000, 11000)); }else StealTimer -= diff; if (SummonTimer < diff) { switch(rand()%2) { case 0: DoScriptText(SAY_SUMMON01, m_creature); break; case 1: DoScriptText(SAY_SUMMON02, m_creature); break; } m_creature->InterruptNonMeleeSpells(false); DoCast(m_creature,SPELL_SUMMON_GNOUL); SummonTimer = (urand(12000, 17000)); }else SummonTimer -= diff; DoMeleeAttackIfReady(); } }; /*### ## npc_salramm_gnoul ###*/ struct MANGOS_DLL_DECL npc_salramm_gnoulAI : public ScriptedAI { npc_salramm_gnoulAI(Creature *pCreature) : ScriptedAI(pCreature) { m_pInstance = (ScriptedInstance*)pCreature->GetInstanceData(); m_bIsHeroic = pCreature->GetMap()->IsRaidOrHeroicDungeon(); m_creature->SetActiveObjectState(true); Reset(); } ScriptedInstance* m_pInstance; bool m_bIsHeroic; uint32 m_uiBlowTimer; void Reset() { m_uiBlowTimer = (urand(3000, 15000)); } void MoveInLineOfSight(Unit* pWho) { if (!pWho) return; if (!m_creature->hasUnitState(UNIT_STAT_STUNNED) && pWho->isTargetableForAttack() && m_creature->IsHostileTo(pWho) && pWho->isInAccessablePlaceFor(m_creature)) { if (!m_creature->CanFly() && m_creature->GetDistanceZ(pWho) > CREATURE_Z_ATTACK_RANGE) return; float attackRadius = m_creature->GetAttackDistance(pWho); if (m_creature->IsWithinDistInMap(pWho, attackRadius) && m_creature->IsWithinLOSInMap(pWho)) { if (!m_creature->getVictim()) { AttackStart(pWho); pWho->RemoveSpellsCausingAura(SPELL_AURA_MOD_STEALTH); } else if (m_creature->GetMap()->IsDungeon()) { pWho->SetInCombatWith(m_creature); m_creature->AddThreat(pWho, 0.0f); } } } } void UpdateAI(const uint32 uiDiff) { if (!m_creature->SelectHostileTarget() || !m_creature->getVictim()) return; if(m_uiBlowTimer < uiDiff) { if(Creature* pSalramm = m_pInstance->instance->GetCreature(m_pInstance->GetData64(NPC_SALRAMM))) { if(pSalramm->isDead()) return; switch(rand()%2) { case 0: DoScriptText(SAY_BOOM01, pSalramm); break; case 1: DoScriptText(SAY_BOOM02, pSalramm); break; } pSalramm->InterruptNonMeleeSpells(false); pSalramm->CastSpell(m_creature, SPELL_GNOUL_BLOW, false); } } else m_uiBlowTimer -= uiDiff; DoMeleeAttackIfReady(); return; } }; CreatureAI* GetAI_boss_salramm(Creature* pCreature) { return new boss_salrammAI(pCreature); } CreatureAI* GetAI_npc_salramm_gnoul(Creature* pCreature) { return new npc_salramm_gnoulAI(pCreature); } void AddSC_boss_salramm() { Script *newscript; newscript = new Script; newscript->Name = "boss_salramm"; newscript->GetAI = &GetAI_boss_salramm; newscript->RegisterSelf(); newscript = new Script; newscript->Name = "npc_salramm_gnoul"; newscript->GetAI = &GetAI_npc_salramm_gnoul; newscript->RegisterSelf(); }
29.634328
108
0.607152
mfooo
c2e1bcc8922079f4325d6d89070c07ce37a42390
9,750
cpp
C++
vendor/github.com/apple/foundationdb/fdbserver/DatabaseConfiguration.cpp
jukylin/meq
5a90566b820adc42ef1e390c3f3942eccd77d84a
[ "Apache-2.0" ]
1
2019-10-16T04:00:57.000Z
2019-10-16T04:00:57.000Z
vendor/github.com/apple/foundationdb/fdbserver/DatabaseConfiguration.cpp
jukylin/meq
5a90566b820adc42ef1e390c3f3942eccd77d84a
[ "Apache-2.0" ]
null
null
null
vendor/github.com/apple/foundationdb/fdbserver/DatabaseConfiguration.cpp
jukylin/meq
5a90566b820adc42ef1e390c3f3942eccd77d84a
[ "Apache-2.0" ]
null
null
null
/* * DatabaseConfiguration.cpp * * This source file is part of the FoundationDB open source project * * Copyright 2013-2018 Apple Inc. and the FoundationDB project 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. */ #include "DatabaseConfiguration.h" #include "fdbclient/SystemData.h" DatabaseConfiguration::DatabaseConfiguration() { resetInternal(); } void DatabaseConfiguration::resetInternal() { // does NOT reset rawConfiguration initialized = false; masterProxyCount = resolverCount = desiredTLogCount = tLogWriteAntiQuorum = tLogReplicationFactor = durableStorageQuorum = storageTeamSize = -1; tLogDataStoreType = storageServerStoreType = KeyValueStoreType::END; autoMasterProxyCount = CLIENT_KNOBS->DEFAULT_AUTO_PROXIES; autoResolverCount = CLIENT_KNOBS->DEFAULT_AUTO_RESOLVERS; autoDesiredTLogCount = CLIENT_KNOBS->DEFAULT_AUTO_LOGS; storagePolicy = IRepPolicyRef(); tLogPolicy = IRepPolicyRef(); } void parse( int* i, ValueRef const& v ) { // FIXME: Sanity checking *i = atoi(v.toString().c_str()); } void parseReplicationPolicy(IRepPolicyRef* policy, ValueRef const& v) { BinaryReader reader(v, IncludeVersion()); serializeReplicationPolicy(reader, *policy); } void DatabaseConfiguration::setDefaultReplicationPolicy() { storagePolicy = IRepPolicyRef(new PolicyAcross(storageTeamSize, "zoneid", IRepPolicyRef(new PolicyOne()))); tLogPolicy = IRepPolicyRef(new PolicyAcross(tLogReplicationFactor, "zoneid", IRepPolicyRef(new PolicyOne()))); } bool DatabaseConfiguration::isValid() const { return initialized && tLogWriteAntiQuorum >= 0 && tLogReplicationFactor >= 1 && durableStorageQuorum >= 1 && storageTeamSize >= 1 && getDesiredProxies() >= 1 && getDesiredLogs() >= 1 && getDesiredResolvers() >= 1 && durableStorageQuorum <= storageTeamSize && tLogDataStoreType != KeyValueStoreType::END && storageServerStoreType != KeyValueStoreType::END && autoMasterProxyCount >= 1 && autoResolverCount >= 1 && autoDesiredTLogCount >= 1 && storagePolicy && tLogPolicy ; } std::map<std::string, std::string> DatabaseConfiguration::toMap() const { std::map<std::string, std::string> result; if( initialized ) { std::string tlogInfo = tLogPolicy->info(); std::string storageInfo = storagePolicy->info(); if( durableStorageQuorum == storageTeamSize && tLogWriteAntiQuorum == 0 ) { if( tLogReplicationFactor == 1 && durableStorageQuorum == 1 ) result["redundancy_mode"] = "single"; else if( tLogReplicationFactor == 2 && durableStorageQuorum == 2 ) result["redundancy_mode"] = "double"; else if( tLogReplicationFactor == 4 && durableStorageQuorum == 6 && tlogInfo == "dcid^2 x zoneid^2 x 1" && storageInfo == "dcid^3 x zoneid^2 x 1" ) result["redundancy_mode"] = "three_datacenter"; else if( tLogReplicationFactor == 3 && durableStorageQuorum == 3 ) result["redundancy_mode"] = "triple"; else if( tLogReplicationFactor == 4 && durableStorageQuorum == 3 && tlogInfo == "data_hall^2 x zoneid^2 x 1" && storageInfo == "data_hall^3 x 1" ) result["redundancy_mode"] = "three_data_hall"; else result["redundancy_mode"] = "custom"; } else result["redundancy_mode"] = "custom"; if( tLogDataStoreType == KeyValueStoreType::SSD_BTREE_V1 && storageServerStoreType == KeyValueStoreType::SSD_BTREE_V1) result["storage_engine"] = "ssd-1"; else if (tLogDataStoreType == KeyValueStoreType::SSD_BTREE_V2 && storageServerStoreType == KeyValueStoreType::SSD_BTREE_V2) result["storage_engine"] = "ssd-2"; else if( tLogDataStoreType == KeyValueStoreType::MEMORY && storageServerStoreType == KeyValueStoreType::MEMORY ) result["storage_engine"] = "memory"; else result["storage_engine"] = "custom"; if( desiredTLogCount != -1 ) result["logs"] = format("%d", desiredTLogCount); if( masterProxyCount != -1 ) result["proxies"] = format("%d", masterProxyCount); if( resolverCount != -1 ) result["resolvers"] = format("%d", resolverCount); } return result; } std::string DatabaseConfiguration::toString() const { std::string result; std::map<std::string, std::string> config = toMap(); for(auto itr : config) { result += itr.first + "=" + itr.second; result += ";"; } return result.substr(0, result.length()-1); } bool DatabaseConfiguration::setInternal(KeyRef key, ValueRef value) { KeyRef ck = key.removePrefix( configKeysPrefix ); int type; if (ck == LiteralStringRef("initialized")) initialized = true; else if (ck == LiteralStringRef("proxies")) parse(&masterProxyCount, value); else if (ck == LiteralStringRef("resolvers")) parse(&resolverCount, value); else if (ck == LiteralStringRef("logs")) parse(&desiredTLogCount, value); else if (ck == LiteralStringRef("log_replicas")) parse(&tLogReplicationFactor, value); else if (ck == LiteralStringRef("log_anti_quorum")) parse(&tLogWriteAntiQuorum, value); else if (ck == LiteralStringRef("storage_quorum")) parse(&durableStorageQuorum, value); else if (ck == LiteralStringRef("storage_replicas")) parse(&storageTeamSize, value); else if (ck == LiteralStringRef("log_engine")) { parse((&type), value); tLogDataStoreType = (KeyValueStoreType::StoreType)type; } else if (ck == LiteralStringRef("storage_engine")) { parse((&type), value); storageServerStoreType = (KeyValueStoreType::StoreType)type; } else if (ck == LiteralStringRef("auto_proxies")) parse(&autoMasterProxyCount, value); else if (ck == LiteralStringRef("auto_resolvers")) parse(&autoResolverCount, value); else if (ck == LiteralStringRef("auto_logs")) parse(&autoDesiredTLogCount, value); else if (ck == LiteralStringRef("storage_replication_policy")) parseReplicationPolicy(&storagePolicy, value); else if (ck == LiteralStringRef("log_replication_policy")) parseReplicationPolicy(&tLogPolicy, value); else return false; return true; // All of the above options currently require recovery to take effect } inline static KeyValueRef * lower_bound( VectorRef<KeyValueRef> & config, KeyRef const& key ) { return std::lower_bound( config.begin(), config.end(), KeyValueRef(key, ValueRef()), KeyValueRef::OrderByKey() ); } inline static KeyValueRef const* lower_bound( VectorRef<KeyValueRef> const& config, KeyRef const& key ) { return lower_bound( const_cast<VectorRef<KeyValueRef> &>(config), key ); } void DatabaseConfiguration::applyMutation( MutationRef m ) { if( m.type == MutationRef::SetValue && m.param1.startsWith(configKeysPrefix) ) { set(m.param1, m.param2); } else if( m.type == MutationRef::ClearRange ) { KeyRangeRef range(m.param1, m.param2); if( range.intersects( configKeys ) ) { clear(range & configKeys); } } } bool DatabaseConfiguration::set(KeyRef key, ValueRef value) { makeConfigurationMutable(); mutableConfiguration.get()[ key.toString() ] = value.toString(); return setInternal(key,value); } bool DatabaseConfiguration::clear( KeyRangeRef keys ) { makeConfigurationMutable(); auto& mc = mutableConfiguration.get(); mc.erase( mc.lower_bound( keys.begin.toString() ), mc.lower_bound( keys.end.toString() ) ); // FIXME: More efficient bool wasValid = isValid(); resetInternal(); for(auto c = mc.begin(); c != mc.end(); ++c) setInternal(c->first, c->second); return wasValid && !isValid(); } Optional<ValueRef> DatabaseConfiguration::get( KeyRef key ) const { if (mutableConfiguration.present()) { auto i = mutableConfiguration.get().find(key.toString()); if (i == mutableConfiguration.get().end()) return Optional<ValueRef>(); return ValueRef(i->second); } else { auto i = lower_bound(rawConfiguration, key); if (i == rawConfiguration.end() || i->key != key) return Optional<ValueRef>(); return i->value; } } bool DatabaseConfiguration::isExcludedServer( NetworkAddress a ) const { return get( encodeExcludedServersKey( AddressExclusion(a.ip, a.port) ) ).present() || get( encodeExcludedServersKey( AddressExclusion(a.ip) ) ).present(); } std::set<AddressExclusion> DatabaseConfiguration::getExcludedServers() const { const_cast<DatabaseConfiguration*>(this)->makeConfigurationImmutable(); std::set<AddressExclusion> addrs; for( auto i = lower_bound(rawConfiguration, excludedServersKeys.begin); i != rawConfiguration.end() && i->key < excludedServersKeys.end; ++i ) { AddressExclusion a = decodeExcludedServersKey( i->key ); if (a.isValid()) addrs.insert(a); } return addrs; } void DatabaseConfiguration::makeConfigurationMutable() { if (mutableConfiguration.present()) return; mutableConfiguration = std::map<std::string,std::string>(); auto& mc = mutableConfiguration.get(); for(auto r = rawConfiguration.begin(); r != rawConfiguration.end(); ++r) mc[ r->key.toString() ] = r->value.toString(); rawConfiguration = Standalone<VectorRef<KeyValueRef>>(); } void DatabaseConfiguration::makeConfigurationImmutable() { if (!mutableConfiguration.present()) return; auto & mc = mutableConfiguration.get(); rawConfiguration = Standalone<VectorRef<KeyValueRef>>(); rawConfiguration.resize( rawConfiguration.arena(), mc.size() ); int i = 0; for(auto r = mc.begin(); r != mc.end(); ++r) rawConfiguration[i++] = KeyValueRef( rawConfiguration.arena(), KeyValueRef( r->first, r->second ) ); mutableConfiguration = Optional<std::map<std::string,std::string>>(); }
40.966387
150
0.728
jukylin
c2e241bbc6ad3e6f568c14b33203990cb52cec8b
2,711
hpp
C++
include/qcpc/input/input_utils.hpp
QuarticCat/qc-parser-comb
fd7bbd09233c3f42b23236b242f344ea4d26080e
[ "MIT" ]
1
2021-07-26T03:16:02.000Z
2021-07-26T03:16:02.000Z
include/qcpc/input/input_utils.hpp
QuarticCat/qc-parser-comb
fd7bbd09233c3f42b23236b242f344ea4d26080e
[ "MIT" ]
null
null
null
include/qcpc/input/input_utils.hpp
QuarticCat/qc-parser-comb
fd7bbd09233c3f42b23236b242f344ea4d26080e
[ "MIT" ]
null
null
null
#pragma once #include <concepts> #include <cstddef> namespace qcpc { struct InputPos { const char* current; size_t line; size_t column; }; // TODO: refactor this CRTP template<class Derived> struct InputCRTP { InputCRTP(const char* begin, const char* end) noexcept: _begin(begin), _end(end) {} InputCRTP(const InputCRTP&) = delete; InputCRTP(InputCRTP&&) = delete; InputCRTP& operator=(const InputCRTP&) = delete; InputCRTP& operator=(InputCRTP&&) = delete; Derived& operator++() noexcept { this->_next(); return *static_cast<Derived*>(this); } [[nodiscard]] const char& operator*() const noexcept { return *this->_current; } [[nodiscard]] char operator[](size_t n) const noexcept { return this->_current[n]; } [[nodiscard]] bool is_boi() const noexcept { return this->_current == this->_begin; } [[nodiscard]] bool is_eoi() const noexcept { return this->_current == this->_end; } [[nodiscard]] const char* begin() const noexcept { return this->_begin; } [[nodiscard]] const char* end() const noexcept { return this->_end; } /// Return number of remaining characters. [[nodiscard]] size_t size() const noexcept { return this->_end - this->_current; } /// Return current pointer. [[nodiscard]] const char* current() const noexcept { return this->_current; } /// Return current position. [[nodiscard]] InputPos pos() const noexcept { return {this->_current, this->_line, this->_column}; } /// Return current line. [[nodiscard]] size_t line() const noexcept { return this->_line; } /// Return current column. [[nodiscard]] size_t column() const noexcept { return this->_column; } /// Jump to given position. Caller should ensure the correctness of the argument. void jump(InputPos pos) noexcept { this->_current = pos.current; this->_line = pos.line; this->_column = pos.column; } /// Execute self-increment `n` times. void advance(size_t n) noexcept { for (size_t i = 0; i < n; ++i) this->_next(); } protected: const char* _begin = nullptr; const char* _end = nullptr; const char* _current = _begin; size_t _line = 1; size_t _column = 0; InputCRTP() = default; void _next() noexcept { if (*this->_current++ == '\n') { this->_line += 1; this->_column = 0; } else { this->_column += 1; } } }; template<class T> concept InputType = std::derived_from<T, InputCRTP<T>>; } // namespace qcpc
23.780702
87
0.593508
QuarticCat
c2e62c0276e99b1e6c74d32c45db6ada7e288c98
7,191
cpp
C++
Dark Basic Public Shared/Dark Basic Pro SDK/Shared/Objects/GameFXCalls.cpp
domydev/Dark-Basic-Pro
237fd8d859782cb27b9d5994f3c34bc5372b6c04
[ "MIT" ]
231
2018-01-28T00:06:56.000Z
2022-03-31T21:39:56.000Z
Dark Basic Public Shared/Dark Basic Pro SDK/Shared/Objects/GameFXCalls.cpp
domydev/Dark-Basic-Pro
237fd8d859782cb27b9d5994f3c34bc5372b6c04
[ "MIT" ]
9
2016-02-10T10:46:16.000Z
2017-12-06T17:27:51.000Z
Dark Basic Public Shared/Dark Basic Pro SDK/Shared/Objects/GameFXCalls.cpp
domydev/Dark-Basic-Pro
237fd8d859782cb27b9d5994f3c34bc5372b6c04
[ "MIT" ]
66
2018-01-28T21:54:52.000Z
2022-02-16T22:50:57.000Z
// // GameFX Functions called into Basic3D-Integrated-Functions // // Includes #include "CommonC.h" #include "CObjectsNewC.h" // Static DARKSDK void GFCreateNodeTree ( float fX, float fY, float fZ ) { CreateNodeTree ( fX, fY, fZ ); } DARKSDK void GFAddNodeTreeObject ( int iID, int iType, int iArbitaryValue, int iCastShadow, int iPortalBlocker ) { AddNodeTreeObject ( iID, iType, iArbitaryValue, iCastShadow, iPortalBlocker ); } DARKSDK void GFAddNodeTreeLimb ( int iID, int iLimb, int iType, int iArbitaryValue, int iCastShadow, int iPortalBlocker ) { AddNodeTreeLimb ( iID, iLimb, iType, iArbitaryValue, iCastShadow, iPortalBlocker ); } DARKSDK void GFRemoveNodeTreeObject ( int iID ) { RemoveNodeTreeObject ( iID ); } DARKSDK void GFDeleteNodeTree ( void ) { DeleteNodeTree(); } DARKSDK void GFSetNodeTreeWireframeOn ( void ) { SetNodeTreeWireframeOn(); } DARKSDK void GFSetNodeTreeWireframeOff ( void ) { SetNodeTreeWireframeOff(); } DARKSDK void GFMakeNodeTreeCollisionBox ( float fX1, float fY1, float fZ1, float fX2, float fY2, float fZ2 ) { MakeNodeTreeCollisionBox ( fX1, fY1, fZ1, fX2, fY2, fZ2 ); } DARKSDK void GFSetNodeTreeTextureMode ( int iMode ) { SetNodeTreeTextureMode ( iMode ); } DARKSDK void GFDisableNodeTreeOcclusion ( void ) { DisableNodeTreeOcclusion(); } DARKSDK void GFEnableNodeTreeOcclusion ( void ) { EnableNodeTreeOcclusion(); } DARKSDK void GFSaveNodeTreeObjects ( LPSTR pFilename ) { SaveNodeTreeObjects ( (DWORD)pFilename ); } DARKSDK void GFSetNodeTreeEffectTechnique ( LPSTR pFilename ) { SetNodeTreeEffectTechnique ( (DWORD)pFilename ); } DARKSDK void GFLoadNodeTreeObjects ( LPSTR pFilename, int iDivideTextureSize ) { LoadNodeTreeObjects ( (DWORD)pFilename, iDivideTextureSize ); } DARKSDK void GFAttachObjectToNodeTree ( int iID ) { AttachObjectToNodeTree ( iID ); } DARKSDK void GFDetachObjectFromNodeTree ( int iID ) { DetachObjectFromNodeTree ( iID ); } DARKSDK void GFSetNodeTreePortalsOn ( void ) { SetNodeTreePortalsOn(); } DARKSDK void GFSetNodeTreeCulling ( int iFlag ) { SetNodeTreeCulling(iFlag); } DARKSDK void GFSetNodeTreePortalsOff ( void ) { SetNodeTreePortalsOff(); } DARKSDK void GFBuildNodeTreePortals ( void ) { BuildNodeTreePortals(); } DARKSDK void GFSetNodeTreeScorchTexture ( int iImageID, int iWidth, int iHeight ) { SetNodeTreeScorchTexture ( iImageID, iWidth, iHeight ); } DARKSDK void GFAddNodeTreeScorch ( float fSize, int iType ) { AddNodeTreeScorch ( fSize, iType ); } DARKSDK void GFAddNodeTreeLight ( int iLightIndex, float fX, float fY, float fZ, float fRange ) { AddNodeTreeLight ( iLightIndex, fX, fY, fZ, fRange ); } // Static Expressions DARKSDK int GFGetStaticHit ( float fOldX1, float fOldY1, float fOldZ1, float fOldX2, float fOldY2, float fOldZ2, float fNX1, float fNY1, float fNZ1, float fNX2, float fNY2, float fNZ2 ) { return GetStaticHit ( fOldX1, fOldY1, fOldZ1, fOldX2, fOldY2, fOldZ2, fNX1, fNY1, fNZ1, fNX2, fNY2, fNZ2 ); } DARKSDK int GFGetStaticLineOfSight ( float fSx, float fSy, float fSz, float fDx, float fDy, float fDz, float fWidth, float fAccuracy ) { return GetStaticLineOfSight ( fSx, fSy, fSz, fDx, fDy, fDz, fWidth, fAccuracy ); } DARKSDK int GFGetStaticRayCast ( float fSx, float fSy, float fSz, float fDx, float fDy, float fDz ) { return GetStaticRayCast ( fSx, fSy, fSz, fDx, fDy, fDz ); } DARKSDK int GFGetStaticVolumeCast ( float fX, float fY, float fZ, float fNewX, float fNewY, float fNewZ, float fSize ) { return GetStaticVolumeCast ( fX, fY, fZ, fNewX, fNewY, fNewZ, fSize ); } DARKSDK DWORD GFGetStaticX ( void ) { return GetStaticX ( ); } DARKSDK DWORD GFGetStaticY ( void ) { return GetStaticY ( ); } DARKSDK DWORD GFGetStaticZ ( void ) { return GetStaticZ ( ); } DARKSDK int GFGetStaticFloor ( void ) { return GetStaticFloor ( ); } DARKSDK int GFGetStaticColCount ( void ) { return GetStaticColCount ( ); } DARKSDK int GFGetStaticColValue ( void ) { return GetStaticColValue ( ); } DARKSDK DWORD GFGetStaticLineOfSightX ( void ) { return GetStaticLineOfSightX ( ); } DARKSDK DWORD GFGetStaticLineOfSightY ( void ) { return GetStaticLineOfSightY ( ); } DARKSDK DWORD GFGetStaticLineOfSightZ ( void ) { return GetStaticLineOfSightZ ( ); } // CSG Commands (CSG) DARKSDK void GFPeformCSGUnion ( int iObjectA, int iObjectB ) { PeformCSGUnion ( iObjectA, iObjectB ); } DARKSDK void GFPeformCSGDifference ( int iObjectA, int iObjectB ) { PeformCSGDifference ( iObjectA, iObjectB ); } DARKSDK void GFPeformCSGIntersection ( int iObjectA, int iObjectB ) { PeformCSGIntersection ( iObjectA, iObjectB ); } DARKSDK void GFPeformCSGClip ( int iObjectA, int iObjectB ) { PeformCSGClip ( iObjectA, iObjectB ); } DARKSDK void GFPeformCSGUnionOnVertexData ( int iBrushMeshID ) { PeformCSGUnionOnVertexData ( iBrushMeshID ); } DARKSDK void GFPeformCSGDifferenceOnVertexData ( int iBrushMeshID ) { PeformCSGDifferenceOnVertexData ( iBrushMeshID ); } DARKSDK void GFPeformCSGIntersectionOnVertexData ( int iBrushMeshID ) { PeformCSGIntersectionOnVertexData ( iBrushMeshID ); } DARKSDK int GFObjectBlocking ( int iID, float X1, float Y1, float Z1, float X2, float Y2, float Z2 ) { return ObjectBlocking ( iID, X1, Y1, Z1, X2, Y2, Z2 ); } DARKSDK void GFReduceMesh ( int iMeshID, int iBlockMode, int iNearMode, int iGX, int iGY, int iGZ ) { ReduceMesh ( iMeshID, iBlockMode, iNearMode, iGX, iGY, iGZ ); } DARKSDK void GFMakeLODFromMesh ( int iMeshID, int iVertNum, int iNewMeshID ) { MakeLODFromMesh ( iMeshID, iVertNum, iNewMeshID ); } // Light Maps DARKSDK void GFAddObjectToLightMapPool ( int iID ) { AddObjectToLightMapPool ( iID ); } DARKSDK void GFAddLimbToLightMapPool ( int iID, int iLimb ) { AddLimbToLightMapPool ( iID, iLimb ); } DARKSDK void GFAddStaticObjectsToLightMapPool ( void ) { AddStaticObjectsToLightMapPool(); } DARKSDK void GFAddLightMapLight ( float fX, float fY, float fZ, float fRadius, float fRed, float fGreen, float fBlue, float fBrightness, int bCastShadow ) { AddLightMapLight ( fX, fY, fZ, fRadius, fRed, fGreen, fBlue, fBrightness, bCastShadow ); } DARKSDK void GFFlushLightMapLights ( void ) { FlushLightMapLights(); } DARKSDK void GFCreateLightMaps ( int iLMSize, int iLMQuality, LPSTR dwPathForLightMaps ) { CreateLightMaps ( iLMSize, iLMQuality, (DWORD)dwPathForLightMaps ); } // Shadows DARKSDK void GFSetGlobalShadowsOn ( void ) { SetGlobalShadowsOn(); } DARKSDK void GFSetGlobalShadowsOff ( void ) { SetGlobalShadowsOff(); } DARKSDK void GFSetShadowPosition ( int iMode, float fX, float fY, float fZ ) { SetShadowPosition ( iMode, fX, fY, fZ ); } DARKSDK void GFSetShadowColor ( int iRed, int iGreen, int iBlue, int iAlphaLevel ) { SetShadowColor ( iRed, iGreen, iBlue, iAlphaLevel ); } DARKSDK void GFSetShadowShades ( int iShades ) { SetShadowShades ( iShades ); } // Others DARKSDK void GFAddLODToObject ( int iCurrentID, int iLODModelID, int iLODLevel, float fDistanceOfLOD ) { AddLODToObject ( iCurrentID, iLODModelID, iLODLevel, fDistanceOfLOD ); }
23.347403
197
0.732026
domydev
c2e8503fb5d9eeb82f0269fff33c4c4f6958c0a2
1,666
cpp
C++
src/frontend/A64/translate/impl/data_processing_conditional_select.cpp
Esigodini/dynarmic
664de9eaaf10bee0fdd5e88f4f125cb9c3df5c54
[ "0BSD" ]
11
2020-05-23T22:12:33.000Z
2021-06-23T08:11:45.000Z
src/frontend/A64/translate/impl/data_processing_conditional_select.cpp
Esigodini/dynarmic
664de9eaaf10bee0fdd5e88f4f125cb9c3df5c54
[ "0BSD" ]
1
2020-05-30T05:01:27.000Z
2020-05-31T04:46:38.000Z
src/frontend/A64/translate/impl/data_processing_conditional_select.cpp
Esigodini/dynarmic
664de9eaaf10bee0fdd5e88f4f125cb9c3df5c54
[ "0BSD" ]
5
2020-05-23T04:10:48.000Z
2022-03-23T14:58:28.000Z
/* This file is part of the dynarmic project. * Copyright (c) 2018 MerryMage * SPDX-License-Identifier: 0BSD */ #include "frontend/A64/translate/impl/impl.h" namespace Dynarmic::A64 { bool TranslatorVisitor::CSEL(bool sf, Reg Rm, Cond cond, Reg Rn, Reg Rd) { const size_t datasize = sf ? 64 : 32; const IR::U32U64 operand1 = X(datasize, Rn); const IR::U32U64 operand2 = X(datasize, Rm); const IR::U32U64 result = ir.ConditionalSelect(cond, operand1, operand2); X(datasize, Rd, result); return true; } bool TranslatorVisitor::CSINC(bool sf, Reg Rm, Cond cond, Reg Rn, Reg Rd) { const size_t datasize = sf ? 64 : 32; const IR::U32U64 operand1 = X(datasize, Rn); const IR::U32U64 operand2 = X(datasize, Rm); const IR::U32U64 result = ir.ConditionalSelect(cond, operand1, ir.Add(operand2, I(datasize, 1))); X(datasize, Rd, result); return true; } bool TranslatorVisitor::CSINV(bool sf, Reg Rm, Cond cond, Reg Rn, Reg Rd) { const size_t datasize = sf ? 64 : 32; const IR::U32U64 operand1 = X(datasize, Rn); const IR::U32U64 operand2 = X(datasize, Rm); const IR::U32U64 result = ir.ConditionalSelect(cond, operand1, ir.Not(operand2)); X(datasize, Rd, result); return true; } bool TranslatorVisitor::CSNEG(bool sf, Reg Rm, Cond cond, Reg Rn, Reg Rd) { const size_t datasize = sf ? 64 : 32; const IR::U32U64 operand1 = X(datasize, Rn); const IR::U32U64 operand2 = X(datasize, Rm); const IR::U32U64 result = ir.ConditionalSelect(cond, operand1, ir.Add(ir.Not(operand2), I(datasize, 1))); X(datasize, Rd, result); return true; } } // namespace Dynarmic::A64
28.237288
109
0.668067
Esigodini
c2ec5ef92d269d50cebf881ca7db67a24b57e642
4,389
cpp
C++
zybo/ROOT_FS/lib/zynqpl/src/pcam/pcam.cpp
meiseihyu/ad-refkit
69ef3a636326102591294eaabd765b55cab28944
[ "MIT" ]
8
2020-07-11T08:22:19.000Z
2022-03-04T09:38:56.000Z
zybo/ROOT_FS/lib/zynqpl/src/pcam/pcam.cpp
meiseihyu/ad-refkit
69ef3a636326102591294eaabd765b55cab28944
[ "MIT" ]
3
2020-04-20T14:21:38.000Z
2020-08-07T03:34:23.000Z
zybo/ROOT_FS/lib/zynqpl/src/pcam/pcam.cpp
meiseihyu/ad-refkit
69ef3a636326102591294eaabd765b55cab28944
[ "MIT" ]
7
2020-04-20T07:54:09.000Z
2021-12-07T11:49:53.000Z
/** * Pcam: Pcamの初期化・Pcamからの画像取得を行うクラス * * Copyright (C) 2019 Yuya Kudo. * * Authors: * Yuya Kudo <[email protected]> */ #include <pcam/pcam.h> namespace zynqpl { Pcam::Pcam(const std::string& video_devname, const std::string& iic_devname, OV5640_cfg::mode_t mode, OV5640_cfg::awb_t awb, uint32_t pixelformat) : width_(OV5640_cfg::resolutions[mode].width), height_(OV5640_cfg::resolutions[mode].height) { psgpio_ = std::make_unique<PSGPIO>(); psiic_ = std::make_unique<PSIIC>(iic_devname, OV5640_cfg::OV5640_SLAVE_ADDR); reset(); init(); applyMode(mode); applyAwb(awb); video_ = std::make_unique<VideoController>(video_devname, OV5640_cfg::resolutions[mode].width, OV5640_cfg::resolutions[mode].height, pixelformat); } Pcam::~Pcam() { shutdown(); } void Pcam::fetchFrame(uint8_t* frame) const { auto v4l2_buf = video_->grub(); memcpy(frame, v4l2_buf, video_->buf_size); video_->release(); } uint32_t Pcam::getImageWidth() const { return width_; } uint32_t Pcam::getImageHeight() const { return height_; } void Pcam::init() const { uint8_t id_h, id_l; readReg(OV5640_cfg::REG_ID_H, id_h); readReg(OV5640_cfg::REG_ID_H, id_h); readReg(OV5640_cfg::REG_ID_L, id_l); if (id_h != OV5640_cfg::DEV_ID_H_ || id_l != OV5640_cfg::DEV_ID_L_) { char msg[100]; snprintf(msg, sizeof(msg), "Got %02x %02x. Expected %02x %02x\r\n", id_h, id_l, OV5640_cfg::DEV_ID_H_, OV5640_cfg::DEV_ID_L_); throw std::runtime_error(std::string(msg)); } writeReg(0x3103, 0x11); writeReg(0x3008, 0x82); usleep(10000); for(size_t i = 0; i < sizeof(OV5640_cfg::cfg_init_) / sizeof(OV5640_cfg::cfg_init_[0]); ++i) { writeReg(OV5640_cfg::cfg_init_[i].addr, OV5640_cfg::cfg_init_[i].data); } } void Pcam::shutdown() const { psgpio_->turnOffPowerToCam(); usleep(10000); } void Pcam::reset() const { psgpio_->turnOffPowerToCam(); usleep(10000); psgpio_->turnOnPowerToCam(); usleep(10000); } void Pcam::applyMode(OV5640_cfg::mode_t mode) const { if(mode >= OV5640_cfg::mode_t::MODE_END) { throw std::runtime_error("OV5640 MODE setting is invalid"); } writeReg(0x3008, 0x42); const auto cfg_mode = &OV5640_cfg::modes[mode]; writeConfig(cfg_mode->cfg, cfg_mode->cfg_size); writeReg(0x3008, 0x02); } void Pcam::applyAwb(OV5640_cfg::awb_t awb) const { if(awb >= OV5640_cfg::awb_t::AWB_END) { throw std::runtime_error("OV5640 AWB setting is invalid"); } writeReg(0x3008, 0x42); auto cfg_mode = &OV5640_cfg::awbs[awb]; writeConfig(cfg_mode->cfg, cfg_mode->cfg_size); writeReg(0x3008, 0x02); } void Pcam::readReg(uint16_t reg_addr, uint8_t& buf) const { buf = psiic_->iicRead(reg_addr); usleep(10000); } void Pcam::writeReg(uint16_t reg_addr, uint8_t const reg_data) const { auto cnt = 10; while(true) { psiic_->iicWrite(reg_addr, reg_data); usleep(10000); if(reg_addr == 0x3008) break; uint8_t buf; readReg(reg_addr, buf); if(buf == reg_data) { std::cout << "[PCam init : Status OK] "; } else { std::cout << "[PCam init : Status NG] "; } printf("addr : 0x%04X, write : 0x%02X, read : 0x%02X\n", reg_addr, (int)reg_data, (int)buf); if(buf == reg_data) break; cnt--; if(cnt == 0) { throw std::runtime_error("process that write to reg by using iic is failure"); } } } void Pcam::writeConfig(OV5640_cfg::config_word_t const* cfg, size_t cfg_size) const { for(size_t i = 0; i < cfg_size; ++i) { writeReg(cfg[i].addr, cfg[i].data); } } }
30.268966
104
0.543176
meiseihyu
c2ed785f55a7573d277412689f1486f0a280f697
2,810
cpp
C++
CPPWorkspace/absolutecpp/main.cpp
troyAmlee/udemycpp
42e1bdb4c29132ec8cac36f3f33d4f6283c5fb32
[ "MIT" ]
null
null
null
CPPWorkspace/absolutecpp/main.cpp
troyAmlee/udemycpp
42e1bdb4c29132ec8cac36f3f33d4f6283c5fb32
[ "MIT" ]
null
null
null
CPPWorkspace/absolutecpp/main.cpp
troyAmlee/udemycpp
42e1bdb4c29132ec8cac36f3f33d4f6283c5fb32
[ "MIT" ]
null
null
null
#include <stdio.h> #include <iostream> #include <string> using namespace std; int jogger(); double box(); double money(); double feetConversion(); double liquid(); double average(); int main(int argc, char **argv) { jogger(); box(); money(); feetConversion(); liquid(); average(); return 0; } int jogger(){ int miles; cout << "Enter number of miles to jog: "; cin >> miles; int totalLaps = miles*14; cout << "You need to jog " << totalLaps << " laps." << endl; return 0; } double box(){ cout << "Welcome to the box calculator" << endl; cout << "Please enter the dimensions of your box in inches: "; int length; int width; int height; cin >> length >> width >> height; double boxArea = 2*(length*width+length*height+width*height); double boxVolume = length*width*height; cout << "Box surface area = " << boxArea << " square inches" << endl; cout << "Box volume = " << boxVolume << " cubic inches" << endl; return 0; } double money(){ cout << "How much change do you have?" << endl; int quarters; int dimes; int nickels; int pennies; double totalQuarters; double totalDimes; double totalNickels; double totalPennies; cout << "Enter number of quarters: "; cin >> quarters; cout << "Enter number of dimes: "; cin >> dimes; cout << "Enter number of nickels: "; cin >> nickels; cout << "Enter number of pennies: "; cin >> pennies; totalQuarters = quarters*.25; totalDimes = dimes*.10; totalNickels = nickels*.05; totalPennies = pennies*.01; cout.setf(ios::fixed); cout.setf(ios::showpoint); cout.precision(2); double total = totalQuarters+totalDimes+totalNickels+totalPennies; cout << quarters << " quarters, " << dimes << " dimes, " << nickels << " nickels, and " << pennies << " pennies = $" << total << endl; return 0; } double feetConversion(){ int feet; double yards; double inches; double centimeters; double meters; cout << "Please input number of feet to be converted: "; cin >> feet; yards = (feet*12)/36; inches = feet*12; centimeters = (feet*12)*2.54; meters = (feet*12)*(2.54)/(100); cout << "= " << yards << " yards" << endl << "= " << inches << " inches" << endl << "= " << centimeters << " centimeters" << endl << "= " << meters << " meters" << endl; return 0; } double liquid(){ int ounces; int leftoverOz; int maxQuarts; cout << "Please enter number of ounces: "; cin >> ounces; leftoverOz = ounces%32; maxQuarts = ounces/32; cout << ounces << " oz. = " << maxQuarts << " qt. " << leftoverOz << " oz." << endl; return 0; } double average(){ cout << "Enter the price (x y z): " << endl; double x; double y; double z; cin >> x >> y >> z; double sum; sum = x + y + z; double average_; average_ = sum/3.0; cout << "The average variable = " << average_ << endl; }
20.814815
70
0.619217
troyAmlee
c2f2b011439c92f9dbbea516f41ed755987f2a79
6,081
cpp
C++
util/Utilities.cpp
traviscross/libzina
6583baa68549a7d90bf6f9af5836361e41b3cef5
[ "Apache-2.0" ]
21
2016-04-03T00:05:34.000Z
2020-05-19T23:08:37.000Z
util/Utilities.cpp
traviscross/libzina
6583baa68549a7d90bf6f9af5836361e41b3cef5
[ "Apache-2.0" ]
null
null
null
util/Utilities.cpp
traviscross/libzina
6583baa68549a7d90bf6f9af5836361e41b3cef5
[ "Apache-2.0" ]
4
2018-01-15T07:17:27.000Z
2021-01-10T02:01:37.000Z
/* Copyright 2016 Silent Circle, LLC 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. */ // // Created by werner on 07.06.16. // #include <sys/time.h> #include <string.h> #include <time.h> #include "Utilities.h" using namespace std; using namespace zina; bool Utilities::hasJsonKey(const cJSON* const root, const char* const key) { if (root == nullptr) return false; cJSON* jsonItem = cJSON_GetObjectItem(const_cast<cJSON*>(root), key); return jsonItem != nullptr; } int32_t Utilities::getJsonInt(const cJSON* const root, const char* const name, int32_t error) { if (root == nullptr) return error; cJSON* jsonItem = cJSON_GetObjectItem(const_cast<cJSON*>(root), name); if (jsonItem == nullptr) return error; return jsonItem->valueint; } uint32_t Utilities::getJsonUInt(const cJSON* const root, const char* const name, uint32_t error) { if (root == nullptr) return error; cJSON* jsonItem = cJSON_GetObjectItem(const_cast<cJSON*>(root), name); if (jsonItem == nullptr) return error; if (jsonItem->valuedouble > 0xffffffff) return 0xffffffff; if (jsonItem->valuedouble < 0) return 0; return (uint32_t)jsonItem->valuedouble; } double Utilities::getJsonDouble(const cJSON* const root, const char* const name, double error) { if (root == nullptr) return error; cJSON* jsonItem = cJSON_GetObjectItem(const_cast<cJSON*>(root), name); if (jsonItem == nullptr) return error; return jsonItem->valuedouble; } const char *const Utilities::getJsonString(const cJSON* const root, const char* const name, const char *error) { if (root == nullptr) return error; cJSON* jsonItem = cJSON_GetObjectItem(const_cast<cJSON*>(root), name); if (jsonItem == nullptr) return error; return jsonItem->valuestring; } void Utilities::setJsonString(cJSON* const root, const char* const name, const char *value, const char *def) { if (root == nullptr || name == nullptr) return; cJSON_AddStringToObject(root, name, value == nullptr ? def : value); return; } bool Utilities::getJsonBool(const cJSON *const root, const char *const name, bool error) { if (root == nullptr) return error; cJSON* jsonItem = cJSON_GetObjectItem(const_cast<cJSON*>(root), name); if (jsonItem == nullptr) return error; if (jsonItem->type == cJSON_True || jsonItem->type == cJSON_False) return jsonItem->type == cJSON_True; return error; } shared_ptr<vector<string> > Utilities::splitString(const string& data, const string delimiter) { shared_ptr<vector<string> > result = make_shared<vector<string> >(); if (data.empty() || (delimiter.empty() || delimiter.size() > 1)) { return result; } string copy(data); size_t pos = 0; while ((pos = copy.find(delimiter)) != string::npos) { string token = copy.substr(0, pos); copy.erase(0, pos + 1); result->push_back(token); } if (!copy.empty()) { result->push_back(copy); } size_t idx = result->empty() ? 0: result->size() - 1; while (idx != 0) { if (result->at(idx).empty()) { result->pop_back(); idx--; } else break; } return result; } string Utilities::currentTimeMsISO8601() { char buffer[80]; char outbuf[80]; struct timeval tv; struct tm timeinfo; gettimeofday(&tv, NULL); time_t currentTime = tv.tv_sec; const char* format = "%FT%T"; strftime(buffer, 80, format ,gmtime_r(&currentTime, &timeinfo)); snprintf(outbuf, 80, "%s.%03dZ\n", buffer, static_cast<int>(tv.tv_usec / 1000)); return string(outbuf); } string Utilities::currentTimeISO8601() { char outbuf[80]; struct tm timeinfo; time_t currentTime = time(NULL); const char* format = "%FT%TZ"; strftime(outbuf, 80, format, gmtime_r(&currentTime, &timeinfo)); return string(outbuf); } uint64_t Utilities::currentTimeMillis() { struct timeval tv; gettimeofday(&tv, 0); uint64_t timeStamp = static_cast<uint64_t>(tv.tv_usec / 1000); timeStamp += ((uint64_t) tv.tv_sec) * 1000; return timeStamp; } void Utilities::wipeString(string &toWipe) { // This append is necessary: the GCC C++ string implementation uses shared strings, reference counted. Thus // if we set the data buffer to 0 then all other references are also cleared. Appending a blank forces the string // implementation to really copy the string and we can set the contents to 0. string.clear() does not clear the // contents, just sets the length to 0 which is not good enough. toWipe.append(" "); wipeMemory((void*)toWipe.data(), toWipe.size()); toWipe.clear(); } static const char decimal2hex[] = "0123456789ABCDEF"; string Utilities::urlEncode(string s) { const char *str = s.c_str(); vector<char> v(s.size()); v.clear(); for (size_t i = 0, l = s.size(); i < l; i++) { char c = str[i]; if ((c >= '0' && c <= '9') || (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '-' || c == '_' || c == '.' || c == '!' || c == '~' || c == '*' || c == '\'' || c == '(' || c == ')') { v.push_back(c); } else { v.push_back('%'); char d1 = decimal2hex[c >> 4]; char d2 = decimal2hex[c & 0x0F]; v.push_back(d1); v.push_back(d2); } } return string(v.cbegin(), v.cend()); }
28.549296
117
0.622102
traviscross
c2f39a09453322cc3ba48b9a2125b9c5fb169a50
2,672
ipp
C++
Siv3D/include/Siv3D/detail/MemoryViewReader.ipp
tas9n/OpenSiv3D
c561cba1d88eb9cd9606ba983fcc1120192d5615
[ "MIT" ]
2
2021-11-22T00:52:48.000Z
2021-12-24T09:33:55.000Z
Siv3D/include/Siv3D/detail/MemoryViewReader.ipp
tas9n/OpenSiv3D
c561cba1d88eb9cd9606ba983fcc1120192d5615
[ "MIT" ]
32
2021-10-09T10:04:11.000Z
2022-02-25T06:10:13.000Z
Siv3D/include/Siv3D/detail/MemoryViewReader.ipp
tas9n/OpenSiv3D
c561cba1d88eb9cd9606ba983fcc1120192d5615
[ "MIT" ]
1
2021-12-31T05:08:00.000Z
2021-12-31T05:08:00.000Z
//----------------------------------------------- // // This file is part of the Siv3D Engine. // // Copyright (c) 2008-2022 Ryo Suzuki // Copyright (c) 2016-2022 OpenSiv3D Project // // Licensed under the MIT License. // //----------------------------------------------- # pragma once namespace s3d { inline constexpr MemoryViewReader::MemoryViewReader(const void* data, const size_t size_bytes) noexcept : m_size{ static_cast<int64>(size_bytes) } , m_ptr{ static_cast<const Byte*>(data) } {} inline bool MemoryViewReader::supportsLookahead() const noexcept { return true; } inline bool MemoryViewReader::isOpen() const noexcept { return (m_ptr != nullptr); } inline int64 MemoryViewReader::size() const { return m_size; } inline int64 MemoryViewReader::getPos() const { return m_pos; } inline bool MemoryViewReader::setPos(const int64 pos) { if (not InRange<int64>(pos, 0, m_size)) { return false; } m_pos = pos; return true; } inline int64 MemoryViewReader::skip(const int64 offset) { m_pos = Clamp<int64>((m_pos + offset), 0, m_size); return m_pos; } inline int64 MemoryViewReader::read(void* dst, const int64 size) { if (not dst) { return 0; } const int64 readSize = Clamp<int64>(size, 0, m_size - m_pos); std::memcpy(dst, (m_ptr + m_pos), static_cast<size_t>(readSize)); m_pos += readSize; return readSize; } inline int64 MemoryViewReader::read(void* dst, const int64 pos, const int64 size) { if (not dst) { return 0; } const int64 readSize = Clamp<int64>(size, 0, m_size - pos); std::memcpy(dst, (m_ptr + pos), static_cast<size_t>(readSize)); m_pos = pos + readSize; return readSize; } SIV3D_CONCEPT_TRIVIALLY_COPYABLE_ inline bool MemoryViewReader::read(TriviallyCopyable& dst) { return read(std::addressof(dst), sizeof(TriviallyCopyable)) == sizeof(TriviallyCopyable); } inline int64 MemoryViewReader::lookahead(void* dst, const int64 size) const { if (not dst) { return 0; } const int64 readSize = Clamp<int64>(size, 0, m_size - m_pos); std::memcpy(dst, (m_ptr + m_pos), static_cast<size_t>(readSize)); return readSize; } inline int64 MemoryViewReader::lookahead(void* dst, const int64 pos, const int64 size) const { if (not dst) { return 0; } const int64 readSize = Clamp<int64>(size, 0, m_size - pos); std::memcpy(dst, (m_ptr + m_pos), static_cast<size_t>(readSize)); return readSize; } SIV3D_CONCEPT_TRIVIALLY_COPYABLE_ inline bool MemoryViewReader::lookahead(TriviallyCopyable& dst) const { return lookahead(std::addressof(dst), sizeof(TriviallyCopyable)) == sizeof(TriviallyCopyable); } }
20.396947
104
0.668787
tas9n
6c013b547378eafcac88200b21484c344818b634
4,406
hh
C++
include/formrow.hh
conclusiveeng/devclient
98e3ab39acaab156ab52705be8b4d9213efe9633
[ "BSD-2-Clause" ]
null
null
null
include/formrow.hh
conclusiveeng/devclient
98e3ab39acaab156ab52705be8b4d9213efe9633
[ "BSD-2-Clause" ]
null
null
null
include/formrow.hh
conclusiveeng/devclient
98e3ab39acaab156ab52705be8b4d9213efe9633
[ "BSD-2-Clause" ]
1
2020-11-25T11:24:42.000Z
2020-11-25T11:24:42.000Z
/*- * SPDX-License-Identifier: BSD-2-Clause-FreeBSD * * Copyright (c) 2019 Conclusive Engineering * * 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 AUTHOR 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 AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * */ #ifndef DEVCLIENT_FORMROW_HH #define DEVCLIENT_FORMROW_HH #include <gtkmm.h> template <class T> class FormRow: public Gtk::Box { public: explicit FormRow(const Glib::ustring &label): Gtk::Box(Gtk::Orientation::ORIENTATION_HORIZONTAL, 10), m_label(label) { m_label.set_justify(Gtk::Justification::JUSTIFY_LEFT); m_label.set_size_request(250, -1); pack_start(m_label, false, true); pack_start(m_widget, true, true); show_all_children(); } T &get_widget() { return (m_widget); } protected: T m_widget; Gtk::Label m_label; }; class FormRowGpio: public Gtk::Box { public: explicit FormRowGpio(const Glib::ustring &label): Gtk::Box(Gtk::Orientation::ORIENTATION_HORIZONTAL, 10), m_toggle("off"), m_image("gtk-no", Gtk::ICON_SIZE_BUTTON), m_label(label) { m_label.set_justify(Gtk::Justification::JUSTIFY_LEFT); m_label.set_size_request(250, -1); pack_start(m_label, false, true); m_radio_in.set_label("input"); m_radio_out.set_label("output"); m_radio_out.join_group(m_radio_in); m_toggle.set_sensitive(false); m_image.set_sensitive(false); pack_start(m_radio_in, true, true); pack_start(m_radio_out, true, true); pack_start(m_toggle, true, true); pack_start(m_image, false, false); m_toggle.signal_toggled().connect(sigc::mem_fun(*this, &FormRowGpio::toggled)); m_radio_in.signal_toggled().connect(sigc::mem_fun(*this, &FormRowGpio::in_toggled)); m_radio_out.signal_toggled().connect(sigc::mem_fun(*this, &FormRowGpio::out_toggled)); show_all_children(); } void toggled() { bool active = m_toggle.get_active(); if (active) { m_state_changed.emit(true); m_toggle.set_label("on"); m_image.set_from_icon_name("gtk-yes", Gtk::ICON_SIZE_BUTTON); } else { m_state_changed.emit(false); m_toggle.set_label("off"); m_image.set_from_icon_name("gtk-no", Gtk::ICON_SIZE_BUTTON); } } void in_toggled() { m_toggle.set_sensitive(false); m_image.set_sensitive(false); m_direction_changed.emit(false); } void out_toggled() { m_toggle.set_sensitive(true); m_image.set_sensitive(true); m_direction_changed.emit(true); } bool get_direction() { return (m_radio_out.get_active()); } void set_direction(bool output) { m_radio_in.set_active(!output); m_radio_out.set_active(output); m_direction_changed.emit(output); } bool get_state() { return (m_toggle.get_active()); } void set_state(bool state) { m_toggle.set_active(state); m_state_changed.emit(state); } void set_gpio_name(const std::string &name) { m_label.set_label(name); } sigc::signal<void(bool)> direction_changed() { return m_direction_changed; } sigc::signal<void(bool)> state_changed() { return m_state_changed; } protected: Gtk::ToggleButton m_toggle; Gtk::RadioButton m_radio_in; Gtk::RadioButton m_radio_out; Gtk::Image m_image; Gtk::Label m_label; sigc::signal<void(bool)> m_direction_changed; sigc::signal<void(bool)> m_state_changed; }; #endif //DEVCLIENT_FORMROW_HH
26.22619
88
0.73695
conclusiveeng
6c0361b1e8fbff232a724a27fda06a3c6e7cf9b9
1,282
cpp
C++
src/lib/src/cli/commands/load-tag-database-cli-command.cpp
Penguin-Guru/imgbrd-grabber
69bdd5566dc2b2cb3a67456bf1a159d544699bc9
[ "Apache-2.0" ]
1,449
2015-03-16T02:21:41.000Z
2022-03-31T22:49:10.000Z
src/lib/src/cli/commands/load-tag-database-cli-command.cpp
sisco0/imgbrd-grabber
89bf97ccab3df62286784baac242f00bf006d562
[ "Apache-2.0" ]
2,325
2015-03-16T02:23:30.000Z
2022-03-31T21:38:26.000Z
src/lib/src/cli/commands/load-tag-database-cli-command.cpp
evanjs/imgbrd-grabber
491f8f3c05be3fc02bc10007735c5afa19d47449
[ "Apache-2.0" ]
242
2015-03-22T11:00:54.000Z
2022-03-31T12:37:15.000Z
#include "load-tag-database-cli-command.h" #include <QList> #include "cli-command.h" #include "logger.h" #include "models/site.h" #include "tools/tag-list-loader.h" LoadTagDatabaseCliCommand::LoadTagDatabaseCliCommand(Profile *profile, const QList<Site*> &sites, int minTagCount, QObject *parent) : CliCommand(parent), m_profile(profile), m_sites(sites), m_minTagCount(minTagCount) {} bool LoadTagDatabaseCliCommand::validate() { if (m_sites.isEmpty()) { log("You must provide at least one source to load the tag database of", Logger::Error); return false; } if (m_minTagCount < 100) { log("Loading a tag database with a tag count under 100 can take a long time and generate lots of requests", Logger::Warning); } return true; } void LoadTagDatabaseCliCommand::run() { loadNext(); } void LoadTagDatabaseCliCommand::loadNext() { Site *site = m_sites.takeFirst(); auto *loader = new TagListLoader(m_profile, site, m_minTagCount, this); connect(loader, &TagListLoader::finished, this, &LoadTagDatabaseCliCommand::finishedLoading); connect(loader, &TagListLoader::finished, loader, &TagListLoader::deleteLater); loader->start(); } void LoadTagDatabaseCliCommand::finishedLoading() { if (!m_sites.isEmpty()) { loadNext(); return; } emit finished(0); }
25.137255
131
0.74181
Penguin-Guru
6c07d27b25624931e756a63be014f42c7441e35d
4,640
cpp
C++
modules/3d/src/rgbd/volume.cpp
HattrickGenerator/opencv
7554b53adfff8996e576691af4242f6f4acdc8f3
[ "Apache-2.0" ]
null
null
null
modules/3d/src/rgbd/volume.cpp
HattrickGenerator/opencv
7554b53adfff8996e576691af4242f6f4acdc8f3
[ "Apache-2.0" ]
null
null
null
modules/3d/src/rgbd/volume.cpp
HattrickGenerator/opencv
7554b53adfff8996e576691af4242f6f4acdc8f3
[ "Apache-2.0" ]
1
2021-04-30T18:00:41.000Z
2021-04-30T18:00:41.000Z
// This file is part of OpenCV project. // It is subject to the license terms in the LICENSE file found in the top-level directory // of this distribution and at http://opencv.org/license.html #include "../precomp.hpp" #include "tsdf.hpp" #include "hash_tsdf.hpp" #include "colored_tsdf.hpp" namespace cv { Ptr<VolumeParams> VolumeParams::defaultParams(int _volumeKind) { VolumeParams params; params.kind = _volumeKind; params.maxWeight = 64; params.raycastStepFactor = 0.25f; params.unitResolution = 0; // unitResolution not used for TSDF float volumeSize = 3.0f; Matx44f pose = Affine3f().translate(Vec3f(-volumeSize / 2.f, -volumeSize / 2.f, 0.5f)).matrix; params.pose = Mat(pose); if(params.kind == VolumeKind::TSDF) { params.resolutionX = 512; params.resolutionY = 512; params.resolutionZ = 512; params.voxelSize = volumeSize / 512.f; params.depthTruncThreshold = 0.f; // depthTruncThreshold not required for TSDF params.tsdfTruncDist = 7 * params.voxelSize; //! About 0.04f in meters return makePtr<VolumeParams>(params); } else if(params.kind == VolumeKind::HASHTSDF) { params.unitResolution = 16; params.voxelSize = volumeSize / 512.f; params.depthTruncThreshold = 4.f; params.tsdfTruncDist = 7 * params.voxelSize; //! About 0.04f in meters return makePtr<VolumeParams>(params); } else if (params.kind == VolumeKind::COLOREDTSDF) { params.resolutionX = 512; params.resolutionY = 512; params.resolutionZ = 512; params.voxelSize = volumeSize / 512.f; params.depthTruncThreshold = 0.f; // depthTruncThreshold not required for TSDF params.tsdfTruncDist = 7 * params.voxelSize; //! About 0.04f in meters return makePtr<VolumeParams>(params); } CV_Error(Error::StsBadArg, "Invalid VolumeType does not have parameters"); } Ptr<VolumeParams> VolumeParams::coarseParams(int _volumeKind) { Ptr<VolumeParams> params = defaultParams(_volumeKind); params->raycastStepFactor = 0.75f; float volumeSize = 3.0f; if(params->kind == VolumeKind::TSDF) { params->resolutionX = 128; params->resolutionY = 128; params->resolutionZ = 128; params->voxelSize = volumeSize / 128.f; params->tsdfTruncDist = 2 * params->voxelSize; //! About 0.04f in meters return params; } else if(params->kind == VolumeKind::HASHTSDF) { params->voxelSize = volumeSize / 128.f; params->tsdfTruncDist = 2 * params->voxelSize; //! About 0.04f in meters return params; } else if (params->kind == VolumeKind::COLOREDTSDF) { params->resolutionX = 128; params->resolutionY = 128; params->resolutionZ = 128; params->voxelSize = volumeSize / 128.f; params->tsdfTruncDist = 2 * params->voxelSize; //! About 0.04f in meters return params; } CV_Error(Error::StsBadArg, "Invalid VolumeType does not have parameters"); } Ptr<Volume> makeVolume(const Ptr<VolumeParams>& _volumeParams) { int kind = _volumeParams->kind; if(kind == VolumeParams::VolumeKind::TSDF) return makeTSDFVolume(*_volumeParams); else if(kind == VolumeParams::VolumeKind::HASHTSDF) return makeHashTSDFVolume(*_volumeParams); else if(kind == VolumeParams::VolumeKind::COLOREDTSDF) return makeColoredTSDFVolume(*_volumeParams); CV_Error(Error::StsBadArg, "Invalid VolumeType does not have parameters"); } Ptr<Volume> makeVolume(int _volumeKind, float _voxelSize, Matx44f _pose, float _raycastStepFactor, float _truncDist, int _maxWeight, float _truncateThreshold, int _resolutionX, int _resolutionY, int _resolutionZ) { Point3i _presolution(_resolutionX, _resolutionY, _resolutionZ); if (_volumeKind == VolumeParams::VolumeKind::TSDF) { return makeTSDFVolume(_voxelSize, _pose, _raycastStepFactor, _truncDist, _maxWeight, _presolution); } else if (_volumeKind == VolumeParams::VolumeKind::HASHTSDF) { return makeHashTSDFVolume(_voxelSize, _pose, _raycastStepFactor, _truncDist, _maxWeight, _truncateThreshold); } else if (_volumeKind == VolumeParams::VolumeKind::COLOREDTSDF) { return makeColoredTSDFVolume(_voxelSize, _pose, _raycastStepFactor, _truncDist, _maxWeight, _presolution); } CV_Error(Error::StsBadArg, "Invalid VolumeType does not have parameters"); } } // namespace cv
38.347107
117
0.663793
HattrickGenerator
6c0e3472cd0f8f02f5e64cfbc93ef1174ed4003b
3,025
cpp
C++
src/cascadia/TerminalSettingsEditor/PaddingConverter.cpp
hessedoneen/terminal
aa54de1d648f45920996aeba1edecc67237c6642
[ "MIT" ]
4
2021-05-11T06:11:52.000Z
2021-07-31T22:32:57.000Z
src/cascadia/TerminalSettingsEditor/PaddingConverter.cpp
Apasys/terminal
c1f844307ca5d5d8d5a457faa616f5fa089aa771
[ "MIT" ]
2
2021-10-30T02:38:17.000Z
2021-10-30T02:45:05.000Z
src/cascadia/TerminalSettingsEditor/PaddingConverter.cpp
Apasys/terminal
c1f844307ca5d5d8d5a457faa616f5fa089aa771
[ "MIT" ]
2
2021-02-02T22:12:35.000Z
2021-05-04T23:24:57.000Z
// Copyright (c) Microsoft Corporation. // Licensed under the MIT license. #include "pch.h" #include "PaddingConverter.h" #include "PaddingConverter.g.cpp" using namespace winrt::Windows; using namespace winrt::Windows::UI::Xaml; using namespace winrt::Windows::UI::Text; namespace winrt::Microsoft::Terminal::Settings::Editor::implementation { Foundation::IInspectable PaddingConverter::Convert(Foundation::IInspectable const& value, Windows::UI::Xaml::Interop::TypeName const& /* targetType */, Foundation::IInspectable const& /* parameter */, hstring const& /* language */) { const auto& padding = winrt::unbox_value<hstring>(value); const wchar_t singleCharDelim = L','; std::wstringstream tokenStream(padding.c_str()); std::wstring token; double maxVal = 0; size_t* idx = nullptr; // Get padding values till we run out of delimiter separated values in the stream // Non-numeral values detected will default to 0 // std::getline will not throw exception unless flags are set on the wstringstream // std::stod will throw invalid_argument exception if the input is an invalid double value // std::stod will throw out_of_range exception if the input value is more than DBL_MAX try { while (std::getline(tokenStream, token, singleCharDelim)) { // std::stod internally calls wcstod which handles whitespace prefix (which is ignored) // & stops the scan when first char outside the range of radix is encountered // We'll be permissive till the extent that stod function allows us to be by default // Ex. a value like 100.3#535w2 will be read as 100.3, but ;df25 will fail const auto curVal = std::stod(token, idx); if (curVal > maxVal) { maxVal = curVal; } } } catch (...) { // If something goes wrong, even if due to a single bad padding value, we'll return default 0 padding maxVal = 0; LOG_CAUGHT_EXCEPTION(); } return winrt::box_value<double>(maxVal); } Foundation::IInspectable PaddingConverter::ConvertBack(Foundation::IInspectable const& value, Windows::UI::Xaml::Interop::TypeName const& /* targetType */, Foundation::IInspectable const& /*parameter*/, hstring const& /* language */) { const auto padding{ winrt::unbox_value<double>(value) }; return winrt::box_value(winrt::to_hstring(padding)); } }
45.833333
121
0.551736
hessedoneen
6c1137755d76ede42e7f26a3229ad4714f37eb02
4,633
hpp
C++
sprout/iterator/distance.hpp
osyo-manga/Sprout
8885b115f739ef255530f772067475d3bc0dcef7
[ "BSL-1.0" ]
1
2020-02-04T05:16:01.000Z
2020-02-04T05:16:01.000Z
sprout/iterator/distance.hpp
osyo-manga/Sprout
8885b115f739ef255530f772067475d3bc0dcef7
[ "BSL-1.0" ]
null
null
null
sprout/iterator/distance.hpp
osyo-manga/Sprout
8885b115f739ef255530f772067475d3bc0dcef7
[ "BSL-1.0" ]
null
null
null
#ifndef SPROUT_ITERATOR_DISTANCE_HPP #define SPROUT_ITERATOR_DISTANCE_HPP #include <iterator> #include <type_traits> #include <sprout/config.hpp> #include <sprout/iterator/next.hpp> #include <sprout/iterator/type_traits/category.hpp> #include <sprout/utility/pair/pair.hpp> #include <sprout/adl/not_found.hpp> namespace sprout_adl { sprout::not_found_via_adl iterator_distance(...); } // namespace sprout_adl namespace sprout { namespace iterator_detail { template<typename RandomAccessIterator> inline SPROUT_CONSTEXPR typename std::enable_if< sprout::is_constant_distance_iterator<RandomAccessIterator>::value, typename std::iterator_traits<RandomAccessIterator>::difference_type >::type iterator_distance(RandomAccessIterator first, RandomAccessIterator last, std::random_access_iterator_tag*) { return last - first; } template<typename InputIterator> inline SPROUT_CONSTEXPR sprout::pair<InputIterator, typename std::iterator_traits<InputIterator>::difference_type> iterator_distance_impl_1( sprout::pair<InputIterator, typename std::iterator_traits<InputIterator>::difference_type> const& current, InputIterator last, typename std::iterator_traits<InputIterator>::difference_type n ) { typedef sprout::pair<InputIterator, typename std::iterator_traits<InputIterator>::difference_type> type; return current.first == last ? current : n == 1 ? type(sprout::next(current.first), current.second + 1) : sprout::iterator_detail::iterator_distance_impl_1( sprout::iterator_detail::iterator_distance_impl_1( current, last, n / 2 ), last, n - n / 2 ) ; } template<typename InputIterator> inline SPROUT_CONSTEXPR sprout::pair<InputIterator, typename std::iterator_traits<InputIterator>::difference_type> iterator_distance_impl( sprout::pair<InputIterator, typename std::iterator_traits<InputIterator>::difference_type> const& current, InputIterator last, typename std::iterator_traits<InputIterator>::difference_type n ) { return current.first == last ? current : sprout::iterator_detail::iterator_distance_impl( sprout::iterator_detail::iterator_distance_impl_1( current, last, n ), last, n * 2 ) ; } template<typename InputIterator> inline SPROUT_CONSTEXPR typename std::iterator_traits<InputIterator>::difference_type iterator_distance(InputIterator first, InputIterator last, std::input_iterator_tag*) { typedef sprout::pair<InputIterator, typename std::iterator_traits<InputIterator>::difference_type> type; return sprout::iterator_detail::iterator_distance_impl(type(first, 0), last, 1).second; } template<typename InputIterator> inline SPROUT_CONSTEXPR typename std::enable_if< std::is_literal_type<InputIterator>::value, typename std::iterator_traits<InputIterator>::difference_type >::type iterator_distance(InputIterator first, InputIterator last) { typedef typename std::iterator_traits<InputIterator>::iterator_category* category; return sprout::iterator_detail::iterator_distance(first, last, category()); } template<typename InputIterator> inline SPROUT_CONSTEXPR typename std::enable_if< !std::is_literal_type<InputIterator>::value, typename std::iterator_traits<InputIterator>::difference_type >::type iterator_distance(InputIterator first, InputIterator last) { return std::distance(first, last); } } // namespace iterator_detail } // namespace sprout namespace sprout_iterator_detail { template<typename InputIterator> inline SPROUT_CONSTEXPR typename std::iterator_traits<InputIterator>::difference_type distance(InputIterator first, InputIterator last) { using sprout::iterator_detail::iterator_distance; using sprout_adl::iterator_distance; return iterator_distance(first, last); } } // namespace sprout_iterator_detail namespace sprout { // // distance // // effect: // ADL callable iterator_distance(first, last) -> iterator_distance(first, last) // otherwise, [first, last) is not LiteralType -> std::distance(first, last) // otherwise, [first, last) is RandomAccessIterator && not Pointer -> last - first // otherwise -> linearly count: first to last // template<typename InputIterator> inline SPROUT_CONSTEXPR typename std::iterator_traits<InputIterator>::difference_type distance(InputIterator first, InputIterator last) { return sprout_iterator_detail::distance(first, last); } } // namespace sprout #endif // #ifndef SPROUT_ITERATOR_DISTANCE_HPP
39.262712
117
0.751133
osyo-manga
6c120ec4711794fadcb50fe0695f0623c8ac08f0
1,639
cpp
C++
igl/edge_flaps.cpp
aviadtzemah/animation2
9a3f980fbe27672fe71f8f61f73b5713f2af5089
[ "Apache-2.0" ]
2,392
2016-12-17T14:14:12.000Z
2022-03-30T19:40:40.000Z
igl/edge_flaps.cpp
aviadtzemah/animation2
9a3f980fbe27672fe71f8f61f73b5713f2af5089
[ "Apache-2.0" ]
106
2018-04-19T17:47:31.000Z
2022-03-01T19:44:11.000Z
igl/edge_flaps.cpp
aviadtzemah/animation2
9a3f980fbe27672fe71f8f61f73b5713f2af5089
[ "Apache-2.0" ]
184
2017-11-15T09:55:37.000Z
2022-02-21T16:30:46.000Z
// This file is part of libigl, a simple c++ geometry processing library. // // Copyright (C) 2015 Alec Jacobson <[email protected]> // // This Source Code Form is subject to the terms of the Mozilla Public License // v. 2.0. If a copy of the MPL was not distributed with this file, You can // obtain one at http://mozilla.org/MPL/2.0/. #include "edge_flaps.h" #include "unique_edge_map.h" #include <vector> #include <cassert> IGL_INLINE void igl::edge_flaps( const Eigen::MatrixXi & F, const Eigen::MatrixXi & uE, const Eigen::VectorXi & EMAP, Eigen::MatrixXi & EF, Eigen::MatrixXi & EI) { // Initialize to boundary value EF.setConstant(uE.rows(),2,-1); EI.setConstant(uE.rows(),2,-1); // loop over all faces for(int f = 0;f<F.rows();f++) { // loop over edges across from corners for(int v = 0;v<3;v++) { // get edge id const int e = EMAP(v*F.rows()+f); // See if this is left or right flap w.r.t. edge orientation if( F(f,(v+1)%3) == uE(e,0) && F(f,(v+2)%3) == uE(e,1)) { EF(e,0) = f; EI(e,0) = v; }else { assert(F(f,(v+1)%3) == uE(e,1) && F(f,(v+2)%3) == uE(e,0)); EF(e,1) = f; EI(e,1) = v; } } } } IGL_INLINE void igl::edge_flaps( const Eigen::MatrixXi & F, Eigen::MatrixXi & uE, Eigen::VectorXi & EMAP, Eigen::MatrixXi & EF, Eigen::MatrixXi & EI) { Eigen::MatrixXi allE; std::vector<std::vector<int> > uE2E; igl::unique_edge_map(F,allE,uE,EMAP,uE2E); // Const-ify to call overload const auto & cuE = uE; const auto & cEMAP = EMAP; return edge_flaps(F,cuE,cEMAP,EF,EI); }
26.868852
79
0.596705
aviadtzemah
6c13f776d29e995deef1cf9b390891a093a070d2
165
cpp
C++
chapter-9/9.30.cpp
zero4drift/Cpp-Primer-5th-Exercises
d3d0f0d228e8c2c5a3b3fe1fd03ce34e0894e93f
[ "MIT" ]
null
null
null
chapter-9/9.30.cpp
zero4drift/Cpp-Primer-5th-Exercises
d3d0f0d228e8c2c5a3b3fe1fd03ce34e0894e93f
[ "MIT" ]
null
null
null
chapter-9/9.30.cpp
zero4drift/Cpp-Primer-5th-Exercises
d3d0f0d228e8c2c5a3b3fe1fd03ce34e0894e93f
[ "MIT" ]
null
null
null
// The one parameter version of resize requires that the element type must support value initialization, or it must has a default constructor if it is a class type.
82.5
164
0.8
zero4drift
6c218dfacf9f30759eeee36d48f91b71a81f22b1
1,549
cpp
C++
src/Robots/Skyline.cpp
Overture-7421/OvertureRobotCode_2020
be9b69ea5f852b1077d1531b4f34921964544c86
[ "BSD-3-Clause" ]
1
2020-03-17T04:15:33.000Z
2020-03-17T04:15:33.000Z
src/Robots/Skyline.cpp
Overture-7421/Overture-FRC
be9b69ea5f852b1077d1531b4f34921964544c86
[ "BSD-3-Clause" ]
null
null
null
src/Robots/Skyline.cpp
Overture-7421/Overture-FRC
be9b69ea5f852b1077d1531b4f34921964544c86
[ "BSD-3-Clause" ]
null
null
null
#include "Skyline.h" #include "frc2/command/CommandScheduler.h" #include <frc/smartdashboard/SmartDashboard.h> Skyline::Skyline() : TimedRobot() {} void Skyline::RobotInit() { frc::SmartDashboard::PutNumber("Setpoint Pos", 0); frc::SmartDashboard::PutBoolean("Setpoint Piston", false); } /** * This function is called every robot packet, no matter the mode. Use * this for items like diagnostics that you want to run during disabled, * autonomous, teleoperated and test. * * <p> This runs after the mode specific periodic functions, but before * LiveWindow and SmartDashboard integrated updating. */ void Skyline::RobotPeriodic() { testMotor.set(frc::SmartDashboard::GetNumber("Setpoint Pos", 0)); frc::SmartDashboard::PutNumber("Pos", testMotor.getPosition()); testPiston.setState(frc::SmartDashboard::GetBoolean("Setpoint Piston", false)); } /** * This function is called once each time the robot enters Disabled mode. You * can use it to reset any subsystem information you want to clear when the * robot is disabled. */ void Skyline::DisabledInit() {} void Skyline::DisabledPeriodic() {} /** * This autonomous runs the autonomous command selected by your {@link * RobotContainer} class. */ void Skyline::AutonomousInit() {} void Skyline::AutonomousPeriodic() {} void Skyline::TeleopInit() {} /** * This function is called periodically during operator control. */ void Skyline::TeleopPeriodic() {} /** * This function is called periodically during test mode. */ void Skyline::TestPeriodic() {}
28.163636
83
0.726921
Overture-7421
6c2962777801cc4f90a55341e8dc85b7d16b4e25
15,223
cpp
C++
remodet_repository_wdh_part/src/caffe/remo/visualizer.cpp
UrwLee/Remo_experience
a59d5b9d6d009524672e415c77d056bc9dd88c72
[ "MIT" ]
null
null
null
remodet_repository_wdh_part/src/caffe/remo/visualizer.cpp
UrwLee/Remo_experience
a59d5b9d6d009524672e415c77d056bc9dd88c72
[ "MIT" ]
null
null
null
remodet_repository_wdh_part/src/caffe/remo/visualizer.cpp
UrwLee/Remo_experience
a59d5b9d6d009524672e415c77d056bc9dd88c72
[ "MIT" ]
null
null
null
#include "caffe/remo/visualizer.hpp" namespace caffe { static bool DRAW_HANDS = false; template <typename Dtype> Visualizer<Dtype>::Visualizer(cv::Mat& image, int max_display_size) { const int width = image.cols; const int height = image.rows; const int maxsize = (width > height) ? width : height; const Dtype ratio = (Dtype)max_display_size / maxsize; const int display_width = static_cast<int>(width * ratio); const int display_height = static_cast<int>(height * ratio); cv::resize(image, image_, cv::Size(display_width,display_height), cv::INTER_LINEAR); } template <typename Dtype> void Visualizer<Dtype>::draw_bbox(const BoundingBox<Dtype>& bbox, const int id) { draw_bbox(0,255,0,bbox,id); } template <typename Dtype> void Visualizer<Dtype>::draw_bbox(int r, int g, int b, const BoundingBox<Dtype>& bbox, const int id) { cv::Point top_left_pt(static_cast<int>(bbox.x1_ * image_.cols), static_cast<int>(bbox.y1_ * image_.rows)); cv::Point bottom_right_pt(static_cast<int>(bbox.x2_ * image_.cols), static_cast<int>(bbox.y2_ * image_.rows)); cv::rectangle(image_, top_left_pt, bottom_right_pt, cv::Scalar(b,g,r), 3); // draw person id if (id >= 1) { cv::Point bottom_left_pt1(static_cast<int>(bbox.x1_ * image_.cols + 5), static_cast<int>(bbox.y2_ * image_.rows - 5)); cv::Point bottom_left_pt2(static_cast<int>(bbox.x1_ * image_.cols + 3), static_cast<int>(bbox.y2_ * image_.rows - 3)); char buffer[50]; snprintf(buffer, sizeof(buffer), "%d", id); cv::putText(image_, buffer, bottom_left_pt1, cv::FONT_HERSHEY_SIMPLEX, 0.75, cv::Scalar(0,0,0), 2); cv::putText(image_, buffer, bottom_left_pt2, cv::FONT_HERSHEY_SIMPLEX, 0.75, cv::Scalar(150,150,255), 2); } } template <typename Dtype> void Visualizer<Dtype>::draw_bbox(const BoundingBox<Dtype>& bbox, const int id, cv::Mat* out_image) { draw_bbox(0,255,0,bbox,id,out_image); } template <typename Dtype> void Visualizer<Dtype>::draw_bbox(int r, int g, int b, const BoundingBox<Dtype>& bbox, const int id, cv::Mat* out_image) { cv::Mat image; image_.copyTo(image); cv::Point top_left_pt(static_cast<int>(bbox.x1_ * image.cols), static_cast<int>(bbox.y1_ * image.rows)); cv::Point bottom_right_pt(static_cast<int>(bbox.x2_ * image.cols), static_cast<int>(bbox.y2_ * image.rows)); cv::rectangle(image, top_left_pt, bottom_right_pt, cv::Scalar(b,g,r), 3); // draw person id if (id >= 1) { cv::Point bottom_left_pt1(static_cast<int>(bbox.x1_ * image.cols + 5), static_cast<int>(bbox.y2_ * image.rows - 5)); cv::Point bottom_left_pt2(static_cast<int>(bbox.x1_ * image.cols + 3), static_cast<int>(bbox.y2_ * image.rows - 3)); char buffer[50]; snprintf(buffer, sizeof(buffer), "%d", id); cv::putText(image, buffer, bottom_left_pt1, cv::FONT_HERSHEY_SIMPLEX, 0.75, cv::Scalar(0,0,0), 2); cv::putText(image, buffer, bottom_left_pt2, cv::FONT_HERSHEY_SIMPLEX, 0.75, cv::Scalar(150,150,255), 2); } // output *out_image = image; } template <typename Dtype> void Visualizer<Dtype>::draw_hand(const PMeta<Dtype>& meta, cv::Mat* image) { int re = 3, rw = 4; // int le = 6, lw = 7; Dtype scale_hand = 1; // RIGHT if (meta.kps[re].v > 0.05 && meta.kps[rw].v > 0.05) { // draw right hand // four corners float xe = meta.kps[re].x; float ye = meta.kps[re].y; float xw = meta.kps[rw].x; float yw = meta.kps[rw].y; float dx = xw - xe; float dy = yw - ye; float norm = sqrt(dx*dx+dy*dy); dx /= norm; dy /= norm; cv::Point2f p1,p2,p3,p4; p1.x = xw + norm*scale_hand*dy*0.5*9/16; p1.y = yw - norm*scale_hand*dx*0.5*9/16; p2.x = xw - norm*scale_hand*dy*0.5*9/16; p2.y = yw + norm*scale_hand*dx*0.5*9/16; p3.x = p1.x + norm*scale_hand*dx; p3.y = p1.y + norm*scale_hand*dy; p4.x = p2.x + norm*scale_hand*dx; p4.y = p2.y + norm*scale_hand*dy; // get bbox float xmin,ymin,xmax,ymax; xmin = std::min(std::min(std::min(p1.x,p2.x),p3.x),p4.x); xmin = std::min(std::max(xmin,float(0.)),float(1.)); ymin = std::min(std::min(std::min(p1.y,p2.y),p3.y),p4.y); ymin = std::min(std::max(ymin,float(0.)),float(1.)); xmax = std::max(std::max(std::max(p1.x,p2.x),p3.x),p4.x); xmax = std::min(std::max(xmax,float(0.)),float(1.)); ymax = std::max(std::max(std::max(p1.y,p2.y),p3.y),p4.y); ymax = std::min(std::max(ymax,float(0.)),float(1.)); // get min square box include <...> float cx = (xmin+xmax)/2; float cy = (ymin+ymax)/2; float wh = std::max(xmax-xmin,(ymax-ymin)*9/16); xmin = cx - wh/2; xmax = cx + wh/2; ymin = cy - wh*16/9/2; ymax = cy + wh*16/9/2; xmin = std::min(std::max(xmin,float(0.)),float(1.)); ymin = std::min(std::max(ymin,float(0.)),float(1.)); xmax = std::min(std::max(xmax,float(0.)),float(1.)); ymax = std::min(std::max(ymax,float(0.)),float(1.)); cv::Point top_left_pt(xmin*image->cols,ymin*image->rows); cv::Point bottom_right_pt(xmax*image->cols,ymax*image->rows); cv::rectangle(*image, top_left_pt, bottom_right_pt, cv::Scalar(0,0,255), 3); } // LEFT // if (meta.kps[le].v > 0.05 && meta.kps[lw].v > 0.05) { // // draw left hand // float xe = meta.kps[le].x; // float ye = meta.kps[le].y; // float xw = meta.kps[lw].x; // float yw = meta.kps[lw].y; // float dx = xw - xe; // float dy = yw - ye; // float norm = sqrt(dx*dx+dy*dy); // dx /= norm; // dy /= norm; // cv::Point2f p1,p2,p3,p4; // p1.x = xw + norm*scale_hand*dy*0.5*9/16; // p1.y = yw - norm*scale_hand*dx*0.5*9/16; // p2.x = xw - norm*scale_hand*dy*0.5*9/16; // p2.y = yw + norm*scale_hand*dx*0.5*9/16; // p3.x = p1.x + norm*scale_hand*dx; // p3.y = p1.y + norm*scale_hand*dy; // p4.x = p2.x + norm*scale_hand*dx; // p4.y = p2.y + norm*scale_hand*dy; // // get bbox // float xmin,ymin,xmax,ymax; // xmin = std::min(std::min(std::min(p1.x,p2.x),p3.x),p4.x); // xmin = std::min(std::max(xmin,float(0.)),float(1.)); // ymin = std::min(std::min(std::min(p1.y,p2.y),p3.y),p4.y); // ymin = std::min(std::max(ymin,float(0.)),float(1.)); // xmax = std::max(std::max(std::max(p1.x,p2.x),p3.x),p4.x); // xmax = std::min(std::max(xmax,float(0.)),float(1.)); // ymax = std::max(std::max(std::max(p1.y,p2.y),p3.y),p4.y); // ymax = std::min(std::max(ymax,float(0.)),float(1.)); // // get min square box include <...> // float cx = (xmin+xmax)/2; // float cy = (ymin+ymax)/2; // float wh = std::max(xmax-xmin,(ymax-ymin)*9/16); // xmin = cx - wh/2; // xmax = cx + wh/2; // ymin = cy - wh*16/9/2; // ymax = cy + wh*16/9/2; // xmin = std::min(std::max(xmin,float(0.)),float(1.)); // ymin = std::min(std::max(ymin,float(0.)),float(1.)); // xmax = std::min(std::max(xmax,float(0.)),float(1.)); // ymax = std::min(std::max(ymax,float(0.)),float(1.)); // cv::Point top_left_pt(xmin*image->cols,ymin*image->rows); // cv::Point bottom_right_pt(xmax*image->cols,ymax*image->rows); // cv::rectangle(*image, top_left_pt, bottom_right_pt, cv::Scalar(0,0,255), 3); // } } template <typename Dtype> void Visualizer<Dtype>::draw_bbox(const vector<PMeta<Dtype> >& meta) { draw_bbox(0,255,0,DRAW_HANDS,meta); } template <typename Dtype> void Visualizer<Dtype>::draw_bbox(int r, int g, int b, bool draw_hands, const vector<PMeta<Dtype> >& meta) { if (meta.size() == 0) return; for (int i = 0; i < meta.size(); ++i) { const BoundingBox<Dtype>& bbox = meta[i].bbox; const int id = meta[i].id; const Dtype similarity = meta[i].similarity; const Dtype max_back_similarity = meta[i].max_back_similarity; int xmin = (int)(bbox.x1_*image_.cols); int xmax = (int)(bbox.x2_*image_.cols); int ymin = (int)(bbox.y1_*image_.rows); int ymax = (int)(bbox.y2_*image_.rows); xmin = std::max(std::min(xmin,image_.cols-1),0); xmax = std::max(std::min(xmax,image_.cols-1),0); ymin = std::max(std::min(ymin,image_.rows-1),0); ymax = std::max(std::min(ymax,image_.rows-1),0); cv::Point top_left_pt(xmin,ymin); cv::Point bottom_right_pt(xmax,ymax); cv::rectangle(image_, top_left_pt, bottom_right_pt, cv::Scalar(b,g,r), 3); //-------------------------------------------------------------------------- if (draw_hands) { draw_hand(meta[i],&image_); } //-------------------------------------------------------------------------- if (id >= 1) { // id cv::Point bottom_left_pt1(xmin+5,ymax-5); cv::Point bottom_left_pt2(xmin+3,ymax-3); char buffer[50]; snprintf(buffer, sizeof(buffer), "%d", id); cv::putText(image_, buffer, bottom_left_pt1, cv::FONT_HERSHEY_SIMPLEX, 0.75, cv::Scalar(0,0,0), 2); cv::putText(image_, buffer, bottom_left_pt2, cv::FONT_HERSHEY_SIMPLEX, 0.75, cv::Scalar(150,150,255), 2); // similarity cv::Point bottom_right_pt1(xmax-150,ymax-5); cv::Point bottom_right_pt2(xmax-148,ymax-3); char sm_buffer[50]; snprintf(sm_buffer, sizeof(sm_buffer), "%.2f/%.2f", (float)similarity, (float)max_back_similarity); cv::putText(image_, sm_buffer, bottom_right_pt1, cv::FONT_HERSHEY_SIMPLEX, 0.75, cv::Scalar(0,0,0), 2); cv::putText(image_, sm_buffer, bottom_right_pt1, cv::FONT_HERSHEY_SIMPLEX, 0.75, cv::Scalar(150,150,255), 2); } } } template <typename Dtype> void Visualizer<Dtype>::draw_bbox(const vector<PMeta<Dtype> >& meta, cv::Mat* out_image) { draw_bbox(0,255,0,DRAW_HANDS,meta,out_image); } template <typename Dtype> void Visualizer<Dtype>::draw_bbox(int r, int g, int b, bool draw_hands, const vector<PMeta<Dtype> >& meta, cv::Mat* out_image) { cv::Mat image; image_.copyTo(image); if (meta.size() > 0) { for (int i = 0; i < meta.size(); ++i) { const BoundingBox<Dtype>& bbox = meta[i].bbox; const int id = meta[i].id; const Dtype similarity = meta[i].similarity; const Dtype max_back_similarity = meta[i].max_back_similarity; int xmin = (int)(bbox.x1_*image.cols); int xmax = (int)(bbox.x2_*image.cols); int ymin = (int)(bbox.y1_*image.rows); int ymax = (int)(bbox.y2_*image.rows); xmin = std::max(std::min(xmin,image.cols-1),0); xmax = std::max(std::min(xmax,image.cols-1),0); ymin = std::max(std::min(ymin,image.rows-1),0); ymax = std::max(std::min(ymax,image.rows-1),0); cv::Point top_left_pt(xmin,ymin); cv::Point bottom_right_pt(xmax,ymax); cv::rectangle(image, top_left_pt, bottom_right_pt, cv::Scalar(b,g,r), 3); //------------------------------------------------------------------------ // draw hands if (draw_hands) { draw_hand(meta[i],&image); } //------------------------------------------------------------------------ if (id >= 1) { cv::Point bottom_left_pt1(xmin+5,ymax-5); cv::Point bottom_left_pt2(xmin+3,ymax-3); char buffer[50]; snprintf(buffer, sizeof(buffer), "%d", id); cv::putText(image, buffer, bottom_left_pt1, cv::FONT_HERSHEY_SIMPLEX, 0.75, cv::Scalar(0,0,0), 2); cv::putText(image, buffer, bottom_left_pt2, cv::FONT_HERSHEY_SIMPLEX, 0.75, cv::Scalar(150,150,255), 2); // similarity cv::Point bottom_right_pt1(xmax-150,ymax-5); cv::Point bottom_right_pt2(xmax-148,ymax-3); char sm_buffer[50]; snprintf(sm_buffer, sizeof(sm_buffer), "%.2f/%.2f", (float)similarity, (float)max_back_similarity); cv::putText(image, sm_buffer, bottom_right_pt1, cv::FONT_HERSHEY_SIMPLEX, 0.75, cv::Scalar(0,0,0), 2); cv::putText(image, sm_buffer, bottom_right_pt1, cv::FONT_HERSHEY_SIMPLEX, 0.75, cv::Scalar(150,150,255), 2); } } *out_image = image; } else { *out_image = image; } } template <typename Dtype> void Visualizer<Dtype>::draw_bbox(const vector<PMeta<Dtype> >& meta, const cv::Mat& src_image, cv::Mat* out_image) { draw_bbox(0,255,0,DRAW_HANDS,meta,src_image,out_image); } template <typename Dtype> void Visualizer<Dtype>::draw_bbox(int r, int g, int b, bool draw_hands, const vector<PMeta<Dtype> >& meta, const cv::Mat& src_image, cv::Mat* out_image) { cv::Mat image; src_image.copyTo(image); if (meta.size() > 0) { for (int i = 0; i < meta.size(); ++i) { const BoundingBox<Dtype>& bbox = meta[i].bbox; const int id = meta[i].id; const Dtype similarity = meta[i].similarity; const Dtype max_back_similarity = meta[i].max_back_similarity; int xmin = (int)(bbox.x1_*image.cols); int xmax = (int)(bbox.x2_*image.cols); int ymin = (int)(bbox.y1_*image.rows); int ymax = (int)(bbox.y2_*image.rows); xmin = std::max(std::min(xmin,image.cols-1),0); xmax = std::max(std::min(xmax,image.cols-1),0); ymin = std::max(std::min(ymin,image.rows-1),0); ymax = std::max(std::min(ymax,image.rows-1),0); cv::Point top_left_pt(xmin,ymin); cv::Point bottom_right_pt(xmax,ymax); cv::rectangle(image, top_left_pt, bottom_right_pt, cv::Scalar(b,g,r), 3); // ----------------------------------------------------------------------- // draw hands if (draw_hands) { draw_hand(meta[i],&image); } // ----------------------------------------------------------------------- if (id >= 1) { cv::Point bottom_left_pt1(xmin+5,ymax-5); cv::Point bottom_left_pt2(xmin+3,ymax-3); char buffer[50]; snprintf(buffer, sizeof(buffer), "%d", id); cv::putText(image, buffer, bottom_left_pt1, cv::FONT_HERSHEY_SIMPLEX, 0.75, cv::Scalar(0,0,0), 2); cv::putText(image, buffer, bottom_left_pt2, cv::FONT_HERSHEY_SIMPLEX, 0.75, cv::Scalar(150,150,255), 2); // similarity cv::Point bottom_right_pt1(xmax-150,ymax-5); cv::Point bottom_right_pt2(xmax-148,ymax-3); char sm_buffer[50]; snprintf(sm_buffer, sizeof(sm_buffer), "%.2f/%.2f", (float)similarity, (float)max_back_similarity); cv::putText(image, sm_buffer, bottom_right_pt1, cv::FONT_HERSHEY_SIMPLEX, 0.75, cv::Scalar(0,0,0), 2); cv::putText(image, sm_buffer, bottom_right_pt1, cv::FONT_HERSHEY_SIMPLEX, 0.75, cv::Scalar(150,150,255), 2); } } *out_image = image; } else { *out_image = image; } } template <typename Dtype> void Visualizer<Dtype>::save(const cv::Mat& image, const std::string& save_dir, const int image_id) { char imagename [256]; sprintf(imagename, "%s/%10d.jpg", save_dir.c_str(), image_id); cv::imwrite(imagename, image); } template <typename Dtype> void Visualizer<Dtype>::save(const std::string& save_dir, const int image_id) { char imagename [256]; sprintf(imagename, "%s/%10d.jpg", save_dir.c_str(), image_id); cv::imwrite(imagename, image_); } INSTANTIATE_CLASS(Visualizer); }
43.247159
116
0.591605
UrwLee
6c2a6a022e735a4a6e358275906b4d5a5dbecc8d
956
hpp
C++
include/h3api/H3AdventureMap/H3MapOceanBottle.hpp
Patrulek/H3API
91f10de37c6b86f3160706c1fdf4792f927e9952
[ "MIT" ]
14
2020-09-07T21:49:26.000Z
2021-11-29T18:09:41.000Z
include/h3api/H3AdventureMap/H3MapOceanBottle.hpp
Day-of-Reckoning/H3API
a82d3069ec7d5127b13528608d5350d2b80d57be
[ "MIT" ]
2
2021-02-12T15:52:31.000Z
2021-02-12T16:21:24.000Z
include/h3api/H3AdventureMap/H3MapOceanBottle.hpp
Day-of-Reckoning/H3API
a82d3069ec7d5127b13528608d5350d2b80d57be
[ "MIT" ]
8
2021-02-12T15:52:41.000Z
2022-01-31T15:28:10.000Z
////////////////////////////////////////////////////////////////////// // // // Created by RoseKavalier: // // [email protected] // // Created or last updated on: 2021-02-02 // // ***You may use or distribute these files freely // // so long as this notice remains present.*** // // // ////////////////////////////////////////////////////////////////////// #pragma once #include "h3api/H3Base.hpp" #include "h3api/H3AdventureMap/H3MapSign.hpp" namespace h3 { _H3API_DECLARE_(MapitemOceanBottle); #pragma pack(push, 4) struct H3OceanBottle : H3Signpost { }; struct H3MapitemOceanBottle : H3MapitemSign { }; #pragma pack(pop) /* align-4 */ } /* namespace h3 */
28.969697
70
0.384937
Patrulek
6c2d2289ef49a99011d46242b204db085668532a
1,655
hpp
C++
include/UnityEngine/ProBuilder/IHasDefault.hpp
RedBrumbler/BeatSaber-Quest-Codegen
73dda50b5a3e51f10d86b766dcaa24b0c6226e25
[ "Unlicense" ]
null
null
null
include/UnityEngine/ProBuilder/IHasDefault.hpp
RedBrumbler/BeatSaber-Quest-Codegen
73dda50b5a3e51f10d86b766dcaa24b0c6226e25
[ "Unlicense" ]
null
null
null
include/UnityEngine/ProBuilder/IHasDefault.hpp
RedBrumbler/BeatSaber-Quest-Codegen
73dda50b5a3e51f10d86b766dcaa24b0c6226e25
[ "Unlicense" ]
null
null
null
// Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once // Begin includes #include "beatsaber-hook/shared/utils/byref.hpp" // Completed includes // Type namespace: UnityEngine.ProBuilder namespace UnityEngine::ProBuilder { // Forward declaring type: IHasDefault class IHasDefault; } #include "beatsaber-hook/shared/utils/il2cpp-type-check.hpp" NEED_NO_BOX(::UnityEngine::ProBuilder::IHasDefault); DEFINE_IL2CPP_ARG_TYPE(::UnityEngine::ProBuilder::IHasDefault*, "UnityEngine.ProBuilder", "IHasDefault"); // Type namespace: UnityEngine.ProBuilder namespace UnityEngine::ProBuilder { // Size: 0x10 #pragma pack(push, 1) // Autogenerated type: UnityEngine.ProBuilder.IHasDefault // [TokenAttribute] Offset: FFFFFFFF class IHasDefault { public: // public System.Void SetDefaultValues() // Offset: 0xFFFFFFFFFFFFFFFF void SetDefaultValues(); }; // UnityEngine.ProBuilder.IHasDefault #pragma pack(pop) } #include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" // Writing MetadataGetter for method: UnityEngine::ProBuilder::IHasDefault::SetDefaultValues // Il2CppName: SetDefaultValues template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (UnityEngine::ProBuilder::IHasDefault::*)()>(&UnityEngine::ProBuilder::IHasDefault::SetDefaultValues)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(UnityEngine::ProBuilder::IHasDefault*), "SetDefaultValues", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } };
42.435897
179
0.713595
RedBrumbler
6c30ab0fe4f19b91cafd968cff6bae99acb31d67
3,722
hpp
C++
include/knapsack/branch_and_bound.hpp
fhamonic/knapsack
c5105720b3770fc76d54f14d5001fcc7ac3ec69a
[ "BSL-1.0" ]
1
2021-09-23T09:49:15.000Z
2021-09-23T09:49:15.000Z
include/knapsack/branch_and_bound.hpp
fhamonic/knapsack
c5105720b3770fc76d54f14d5001fcc7ac3ec69a
[ "BSL-1.0" ]
null
null
null
include/knapsack/branch_and_bound.hpp
fhamonic/knapsack
c5105720b3770fc76d54f14d5001fcc7ac3ec69a
[ "BSL-1.0" ]
null
null
null
#ifndef FHAMONIC_KNAPSACK_BRANCH_AND_BOUND_HPP #define FHAMONIC_KNAPSACK_BRANCH_AND_BOUND_HPP #include <numeric> #include <stack> #include <vector> #include <range/v3/algorithm/remove_if.hpp> #include <range/v3/algorithm/sort.hpp> #include <range/v3/view/zip.hpp> #include "knapsack/instance.hpp" #include "knapsack/solution.hpp" namespace fhamonic { namespace knapsack { template <typename Value, typename Cost> class BranchAndBound { public: using TInstance = Instance<Value, Cost>; using TItem = typename TInstance::Item; using TSolution = Solution<Value, Cost>; private: double computeUpperBound(const std::vector<TItem> & sorted_items, std::size_t depth, Value bound_value, Cost bound_budget_left) { for(; depth < sorted_items.size(); ++depth) { const TItem & item = sorted_items[depth]; if(bound_budget_left <= item.cost) return bound_value + bound_budget_left * item.getRatio(); bound_budget_left -= item.cost; bound_value += item.value; } return bound_value; } std::stack<std::size_t> iterative_bnb( const std::vector<TItem> & sorted_items, Cost budget_left) { const std::size_t nb_items = sorted_items.size(); std::size_t depth = 0; Value value = 0; Value best_value = 0; std::stack<std::size_t> stack; std::stack<std::size_t> best_stack; goto begin; backtrack: while(!stack.empty()) { depth = stack.top(); stack.pop(); value -= sorted_items[depth].value; budget_left += sorted_items[depth].cost; for(++depth; depth < nb_items; ++depth) { if(budget_left < sorted_items[depth].cost) continue; if(computeUpperBound(sorted_items, depth, value, budget_left) <= best_value) goto backtrack; begin: value += sorted_items[depth].value; budget_left -= sorted_items[depth].cost; stack.push(depth); } if(value <= best_value) continue; best_value = value; best_stack = stack; } return best_stack; } public: BranchAndBound() {} TSolution solve(const TInstance & instance) { TSolution solution(instance); if(instance.itemCount() > 0) { std::vector<TItem> sorted_items = instance.getItems(); std::vector<int> permuted_id(instance.itemCount()); std::iota(permuted_id.begin(), permuted_id.end(), 0); auto zip_view = ranges::view::zip(sorted_items, permuted_id); auto end = ranges::remove_if(zip_view, [&](const auto & r) { return r.first.cost > instance.getBudget(); }); const ptrdiff_t new_size = std::distance(zip_view.begin(), end); sorted_items.erase(sorted_items.begin() + new_size, sorted_items.end()); permuted_id.erase(permuted_id.begin() + new_size, permuted_id.end()); ranges::sort(zip_view, [](auto p1, auto p2) { return p1.first < p2.first; }); std::stack<std::size_t> best_stack = iterative_bnb(sorted_items, instance.getBudget()); while(!best_stack.empty()) { solution.add(permuted_id[best_stack.top()]); best_stack.pop(); } } return solution; } }; } // namespace knapsack } // namespace fhamonic #endif // FHAMONIC_KNAPSACK_BRANCH_AND_BOUND_HPP
34.785047
80
0.577646
fhamonic
6c396882b41745ec719bb3277321f334a8d14ff9
558
cpp
C++
test/20171018/source/std/test20171018/source/sxy/sequence/rand.cpp
DesZou/Eros
f49c9ce1dfe193de8199163286afc28ff8c52eef
[ "MIT" ]
1
2017-10-12T13:49:10.000Z
2017-10-12T13:49:10.000Z
test/20171018/source/std/test20171018/source/sxy/sequence/rand.cpp
DesZou/Eros
f49c9ce1dfe193de8199163286afc28ff8c52eef
[ "MIT" ]
null
null
null
test/20171018/source/std/test20171018/source/sxy/sequence/rand.cpp
DesZou/Eros
f49c9ce1dfe193de8199163286afc28ff8c52eef
[ "MIT" ]
1
2017-10-12T13:49:38.000Z
2017-10-12T13:49:38.000Z
//Serene #include<algorithm> #include<iostream> #include<cstring> #include<cstdlib> #include<cstdio> #include<cmath> #include<ctime> using namespace std; const int n=200000,f=100,q=200000; int m,k; int main() { freopen("sequence.in","w",stdout); srand((unsigned)time(NULL)); m=rand()%f+1;k=rand()%(n/4)+1; cout<<n<<" "<<m<<" "<<k<<"\n"; int x,y; for(int i=1;i<=n;++i) { x=rand()%f+1; cout<<x<<" "; } cout<<"\n"<<q<<"\n"; for(int i=1;i<=q;++i) { x=rand()%n+1; if(x!=n) y=rand()%(n-x+1); else y=0; cout<<x<<" "<<x+y<<"\n"; } return 0; }
17.4375
38
0.557348
DesZou
6c3d3e4d198a428c654c1703399d7755f6c7c411
6,836
cpp
C++
examples/EchoClientServer.cpp
whamon35/NetTcp
db49b774abadde40132058040fdf92b60ae178c2
[ "MIT" ]
3
2020-05-16T14:00:40.000Z
2022-03-16T10:09:37.000Z
examples/EchoClientServer.cpp
whamon35/NetTcp
db49b774abadde40132058040fdf92b60ae178c2
[ "MIT" ]
null
null
null
examples/EchoClientServer.cpp
whamon35/NetTcp
db49b774abadde40132058040fdf92b60ae178c2
[ "MIT" ]
1
2022-02-25T10:49:12.000Z
2022-02-25T10:49:12.000Z
 // ───────────────────────────────────────────────────────────── // INCLUDE // ───────────────────────────────────────────────────────────── #include <MyServer.hpp> #include <MySocket.hpp> // Dependencies #include <Net/Tcp/NetTcp.hpp> #include <spdlog/sinks/stdout_color_sinks.h> #ifdef _MSC_VER # include <spdlog/sinks/msvc_sink.h> #endif // Qt #include <QCommandLineParser> #include <QCoreApplication> #include <QTimer> // ───────────────────────────────────────────────────────────── // DECLARATION // ───────────────────────────────────────────────────────────── std::shared_ptr<spdlog::logger> appLog = std::make_shared<spdlog::logger>("app"); std::shared_ptr<spdlog::logger> serverLog = std::make_shared<spdlog::logger>("server"); std::shared_ptr<spdlog::logger> clientLog = std::make_shared<spdlog::logger>("client"); class App { public: int counter = 0; uint16_t port = 9999; QString ip = QStringLiteral("127.0.0.1"); MyServer server; MySocket client; bool multiThreaded = false; QTimer timer; public: void start() { appLog->info("Init application"); server.multiThreaded = multiThreaded; // Send Echo counter every seconds QObject::connect(&timer, &QTimer::timeout, [this]() { if(client.isConnected()) { Q_EMIT client.sendString("Echo " + QString::number(counter++)); } }); // Print the message that echoed from server socket QObject::connect(&client, &MySocket::stringReceived, [this](const QString value) { clientLog->info("Rx \"{}\" from server {}:{}", qPrintable(value), qPrintable(client.peerAddress()), signed(client.peerPort())); }); // Print the message that received from client socket QObject::connect(&server, &MyServer::stringReceived, [](const QString value, const QString address, const quint16 port) { serverLog->info("Rx \"{}\" from server {}:{}", qPrintable(value), qPrintable(address), port); }); QObject::connect( &server, &net::tcp::Server::isRunningChanged, [](bool value) { serverLog->info("isRunning : {}", value); }); QObject::connect(&server, &net::tcp::Server::isListeningChanged, [](bool value) { serverLog->info("isBounded : {}", value); }); QObject::connect( &client, &net::tcp::Socket::isRunningChanged, [](bool value) { clientLog->info("isRunning : {}", value); }); QObject::connect(&client, &net::tcp::Socket::isConnectedChanged, [this](bool value) { clientLog->info("isConnected : {}", value); // Reset counter at connection/disconnection counter = 0; }); QObject::connect(&server, &net::tcp::Server::acceptError, [](int value, const QString& error) { serverLog->error("accept error : {}", error.toStdString()); }); QObject::connect(&client, &net::tcp::Socket::socketError, [](int value, const QString& error) { clientLog->error("socket error : {}", error.toStdString()); }); QObject::connect(&server, &net::tcp::Server::newClient, [](const QString& address, const quint16 port) { serverLog->info("New Client {}:{}", qPrintable(address), signed(port)); }); QObject::connect(&server, &net::tcp::Server::clientLost, [](const QString& address, const quint16 port) { serverLog->info("Client Disconnected {}:{}", qPrintable(address), signed(port)); }); QObject::connect(&client, &net::tcp::Socket::txBytesTotalChanged, [](quint64 total) { clientLog->info("Sent bytes : {}", total); }); serverLog->info("Start server on address {}:{}", qPrintable(ip), signed(port)); // server.start(port) can be called to listen from every interfaces server.start(ip, port); client.setUseWorkerThread(multiThreaded); clientLog->info("Start client to connect to address {}, on port {}", qPrintable(ip), signed(port)); client.start(ip, port); appLog->info("Start application"); timer.start(1); } }; static void installLoggers() { #ifdef _MSC_VER const auto msvcSink = std::make_shared<spdlog::sinks::msvc_sink_mt>(); msvcSink->set_level(spdlog::level::debug); net::tcp::Logger::registerSink(msvcSink); appLog->sinks().emplace_back(msvcSink); clientLog->sinks().emplace_back(msvcSink); serverLog->sinks().emplace_back(msvcSink); #endif const auto stdoutSink = std::make_shared<spdlog::sinks::stdout_color_sink_mt>(); stdoutSink->set_level(spdlog::level::debug); net::tcp::Logger::registerSink(stdoutSink); appLog->sinks().emplace_back(stdoutSink); clientLog->sinks().emplace_back(stdoutSink); serverLog->sinks().emplace_back(stdoutSink); } int main(int argc, char* argv[]) { installLoggers(); QCoreApplication app(argc, argv); // ────────── COMMAND PARSER ────────────────────────────────────── QCommandLineParser parser; parser.setApplicationDescription("Echo Client Server"); parser.addHelpOption(); QCommandLineOption multiThreadOption(QStringList() << "t", QCoreApplication::translate("main", "Make the worker live in a different thread. Default false")); parser.addOption(multiThreadOption); QCommandLineOption portOption(QStringList() << "s" << "src", QCoreApplication::translate("main", "Port for rx packet. Default \"9999\"."), QCoreApplication::translate("main", "port")); portOption.setDefaultValue("9999"); parser.addOption(portOption); QCommandLineOption ipOption(QStringList() << "i" << "ip", QCoreApplication::translate("main", "Ip address of multicast group. Default \"127.0.0.1\""), QCoreApplication::translate("main", "ip")); ipOption.setDefaultValue(QStringLiteral("127.0.0.1")); parser.addOption(ipOption); // Process the actual command line arguments given by the user parser.process(app); // ────────── APPLICATION ────────────────────────────────────── // Register types for to use SharedDatagram in signals net::tcp::registerQmlTypes(); // Create the app and start it App echo; bool ok; const auto port = parser.value(portOption).toInt(&ok); if(ok) echo.port = port; const auto ip = parser.value(ipOption); if(!ip.isEmpty()) echo.ip = ip; echo.multiThreaded = parser.isSet(multiThreadOption); echo.start(); // Start event loop return QCoreApplication::exec(); }
36.951351
120
0.581773
whamon35
6c3f945302ef140ba265e55112522a7cb3521338
1,131
cpp
C++
pulse_integration_quality_analysis/one_value_per_cycle/pulse_integration_quality_analysis_test_bench.cpp
knodel/hzdr-mu2e-daq-algo-cores
ae646f66e3b71ef7b06013b4d835cc61d1221ffc
[ "BSD-3-Clause" ]
1
2020-11-17T15:21:04.000Z
2020-11-17T15:21:04.000Z
pulse_integration_quality_analysis/one_value_per_cycle/pulse_integration_quality_analysis_test_bench.cpp
knodel/hzdr-mu2e-daq-algo-cores
ae646f66e3b71ef7b06013b4d835cc61d1221ffc
[ "BSD-3-Clause" ]
null
null
null
pulse_integration_quality_analysis/one_value_per_cycle/pulse_integration_quality_analysis_test_bench.cpp
knodel/hzdr-mu2e-daq-algo-cores
ae646f66e3b71ef7b06013b4d835cc61d1221ffc
[ "BSD-3-Clause" ]
null
null
null
#include "pulse_integration_quality_analysis_core.h" #include "stdio.h" int main(int argc, char* argv[]){ in_stream_t in; out_stream_t out; report result; double value = 0; FILE* file = NULL; if(argc >= 2) file = fopen(argv[1], "r"); else file = fopen("", "r"); if(file == NULL){ perror("\n\nUnable to open input file!"); return 1; } printf("file opened\n"); //read file for(int i=0; i<data_len; i++){ if(fscanf(file, "%lf", &value) != 1) printf("file too short\n"); in << value; } fclose(file); file = NULL; printf("data read\n"); //execute core analysis_core(in, out, trigger_delay_); printf("core executed\n"); //print results if(argc == 3){ file = fopen(argv[2], "w"); if(!file) perror("output file not opened!"); } printf("results:\n"); while(!out.empty()){ out >> result; //printf(" energy: %f, time: %d, quality: %d\n", result.pulse_energy, result.pulse_time, result.quality); printf("%f\t%d\t%d\n", result.pulse_energy, result.pulse_time, result.quality); if(file) fprintf(file, "%d\t%f\t%d\n", result.pulse_time, result.pulse_energy, result.quality); } return 0; }
22.62
109
0.639257
knodel
6c43ab09963e0439d1d595c18b4f3e760296a1dc
528
cpp
C++
bin-int/Debug-windows-x86_64/NextEngine/unity_ZQ3LOIMG5RJ3ZMYP.cpp
CompilerLuke/NextEngine
aa1a8e9d9370bce004dba00854701597cab74989
[ "MIT" ]
1
2021-09-10T18:19:16.000Z
2021-09-10T18:19:16.000Z
bin-int/Debug-windows-x86_64/NextEngine/unity_ZQ3LOIMG5RJ3ZMYP.cpp
CompilerLuke/NextEngine
aa1a8e9d9370bce004dba00854701597cab74989
[ "MIT" ]
null
null
null
bin-int/Debug-windows-x86_64/NextEngine/unity_ZQ3LOIMG5RJ3ZMYP.cpp
CompilerLuke/NextEngine
aa1a8e9d9370bce004dba00854701597cab74989
[ "MIT" ]
2
2020-04-02T06:46:56.000Z
2021-06-17T16:47:57.000Z
#include "stdafx.h" #include "C:\Users\User\source\repos\NextEngine\NextEngine\src\graphics\assets\VULKAN\vk_model.cpp" #include "C:\Users\User\source\repos\NextEngine\NextEngine\src\graphics\assets\VULKAN\vk_shader.cpp" #include "C:\Users\User\source\repos\NextEngine\NextEngine\src\graphics\assets\VULKAN\vk_texture.cpp" #include "C:\Users\User\source\repos\NextEngine\NextEngine\src\graphics\assets\assets.cpp" #include "C:\Users\User\source\repos\NextEngine\NextEngine\src\graphics\assets\assimp_model_loader.cpp"
31.058824
103
0.80303
CompilerLuke
6c47855ad32ae38d7865f06e98fb58dbea3ea85e
3,960
cpp
C++
libro/SpinPQ.cpp
transpixel/tpqz
2d8400b1be03292d0c5ab74710b87e798ae6c52c
[ "MIT" ]
1
2017-06-01T00:21:16.000Z
2017-06-01T00:21:16.000Z
libro/SpinPQ.cpp
transpixel/tpqz
2d8400b1be03292d0c5ab74710b87e798ae6c52c
[ "MIT" ]
3
2017-06-01T00:26:16.000Z
2020-05-09T21:06:27.000Z
libro/SpinPQ.cpp
transpixel/tpqz
2d8400b1be03292d0c5ab74710b87e798ae6c52c
[ "MIT" ]
null
null
null
// // // MIT License // // Copyright (c) 2017 Stellacore 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 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. // // /*! \file \brief Definitions for ro::SpinPQ */ #include "libro/SpinPQ.h" #include "libga/spin.h" #include "libro/PairRel.h" #include "libro/ro.h" #include <array> #include <string> #include <sstream> namespace ro { // static std::pair<ga::Spinor, ga::Spinor> SpinPQ :: pairPQ ( ga::BiVector const & phi , ga::BiVector const & theta , ga::BiVector const & basePlane ) { std::pair<ga::Spinor, ga::Spinor> spinPair; ga::Spinor const ephP{ ga::exp( .5 * phi) }; ga::Spinor const enhP{ ephP.reverse() }; ga::Spinor const ephT{ ga::exp( .5 * theta) }; ga::Spinor const enhT{ ephT.reverse() }; ga::Spinor const P0{ -ephT * basePlane * enhP }; ga::Spinor const Q0{ ephP * enhT }; spinPair = { P0, Q0 }; return spinPair; } // static SpinPQ SpinPQ :: from ( ga::BiVector const & phi , ga::BiVector const & theta , ga::BiVector const & basePlane ) { return SpinPQ(pairPQ(phi, theta, basePlane)); } // static SpinPQ SpinPQ :: from ( std::pair<ga::Rigid, ga::Rigid> const & oriPair ) { ro::PairRel const roRel(oriPair.first, oriPair.second); ga::BiVector const basePrime{ ga::E123 * roRel.baseVector2w1() }; return from(roRel.angle1w0(), roRel.angle2w0(), basePrime); } // explicit SpinPQ :: SpinPQ ( std::pair<ga::Spinor, ga::Spinor> const & pairPQ ) : thePQ{ pairPQ } { } // explicit SpinPQ :: SpinPQ ( ro::Pair const & anyRO ) : thePQ{ from(anyRO.pair()).thePQ } { } double SpinPQ :: tripleProductGap ( std::pair<ga::Vector, ga::Vector> const & uvPair ) const { ga::Spinor const & PP = thePQ.first; ga::Spinor const & QQ = thePQ.second; ga::Vector const & uu = uvPair.first; ga::Vector const & vv = uvPair.second; ga::Spinor const triPro{ PP * uu * QQ * vv }; return triPro.theS.theValue; } bool SpinPQ :: isValid () const { return ( thePQ.first.isValid() && thePQ.second.isValid() ); } OriPair SpinPQ :: pair () const { // shortand names for current values ga::Spinor const & PP = thePQ.first; ga::Spinor const & QQ = thePQ.second; // dependent RO recovery static ga::BiVector const depPhi{ ga::bZero }; ga::BiVector const depTheta{ (-2.*ga::logG2(QQ)).theB }; ga::BiVector const basePlane{ -(QQ * PP).theB }; ga::Vector const baseVec{ -ga::E123 * basePlane }; // gather into orientation pair static ga::Rigid const ori1w0{ ga::Rigid::identity() }; ga::Rigid const ori2w0(baseVec, ga::Pose(depTheta)); // and return as RO object return { ori1w0, ori2w0 }; } std::string SpinPQ :: infoString ( std::string const & title , std::string const & fmt ) const { std::ostringstream oss; if (! title.empty()) { oss << title << std::endl; } if (isValid()) { oss << thePQ.first.infoStringFmt("P", fmt) << " " << thePQ.second.infoStringFmt("Q", fmt) ; } else { oss << " <null>"; } return oss.str(); } } // ro
22.122905
72
0.674495
transpixel
6c482133827736d165d01d873f1aef248b736198
4,860
hpp
C++
src/OpenSimBindings/UndoableUiModel.hpp
ComputationalBiomechanicsLab/opensim-creator
e5c4b24f5ef3bffe10c84899d0a0c79037020b6d
[ "Apache-2.0" ]
5
2021-07-13T12:03:29.000Z
2021-12-22T20:21:58.000Z
src/OpenSimBindings/UndoableUiModel.hpp
ComputationalBiomechanicsLab/opensim-creator
e5c4b24f5ef3bffe10c84899d0a0c79037020b6d
[ "Apache-2.0" ]
180
2022-01-27T15:25:15.000Z
2022-03-30T13:41:12.000Z
src/OpenSimBindings/UndoableUiModel.hpp
ComputationalBiomechanicsLab/opensim-creator
e5c4b24f5ef3bffe10c84899d0a0c79037020b6d
[ "Apache-2.0" ]
null
null
null
#pragma once #include "src/OpenSimBindings/UiModel.hpp" #include "src/Utils/CircularBuffer.hpp" #include <memory> #include <optional> namespace OpenSim { class Model; class Component; } namespace SimTK { class State; } namespace osc { // a "UI-ready" OpenSim::Model with undo/redo and rollback support // // this is what the top-level editor screens are managing. As the user makes // edits to the model, the current/undo/redo states are being updated. This // class also has light support for handling "rollbacks", which is where the // implementation detects that the user modified the model into an invalid state // and the implementation tried to fix the problem by rolling back to an earlier // (hopefully, valid) undo state struct UndoableUiModel final { UiModel current; CircularBuffer<UiModel, 32> undo; CircularBuffer<UiModel, 32> redo; // holding space for a "damaged" model // // this is set whenever the implementation detects that the current // model was damaged by a modification (i.e. the model does not survive a // call to .initSystem with its modified properties). // // The implementation will try to recover from the damage by popping models // from the undo buffer and making them `current`. It will then store the // damaged model here for later cleanup (by the user of this class, which // should `std::move` out the damaged instance) // // the damaged model is kept "alive" so that any pointers into the model are // still valid. The reason this is important is because the damage may have // been done midway through a larger process (e.g. rendering) and there may // be local (stack-allocated) pointers into the damaged model's components. // In that case, it is *probably* safer to let that process finish with a // damaged model than potentially segfault. std::optional<UiModel> damaged; // make a new undoable UI model UndoableUiModel(); explicit UndoableUiModel(std::unique_ptr<OpenSim::Model> model); [[nodiscard]] constexpr bool canUndo() const noexcept { return !undo.empty(); } void doUndo(); [[nodiscard]] constexpr bool canRedo() const noexcept { return !redo.empty(); } void doRedo(); [[nodiscard]] OpenSim::Model& model() const noexcept { return *current.model; } void setModel(std::unique_ptr<OpenSim::Model>); // this should be called before any modification is made to the current model // // it gives the implementation a chance to save a known-to-be-undamaged // version of `current` before any potential damage happens void beforeModifyingModel(); // this should be called after any modification is made to the current model // // it "commits" the modification by calling `on_model_modified` on the model // in a way that will "rollback" if comitting the change throws an exception void afterModifyingModel(); // tries to rollback the model to an earlier state, throwing an exception if // that isn't possible (e.g. because there are no earlier states) void forciblyRollbackToEarlierState(); [[nodiscard]] OpenSim::Component* getSelection() noexcept { return current.selected; } void setSelection(OpenSim::Component* c) { current.selected = c; } [[nodiscard]] OpenSim::Component* getHover() noexcept { return current.hovered; } void setHover(OpenSim::Component* c) { current.hovered = c; } [[nodiscard]] OpenSim::Component* getIsolated() noexcept { return current.isolated; } void setIsolated(OpenSim::Component* c) { current.isolated = c; } [[nodiscard]] SimTK::State& state() noexcept { return *current.state; } void clearAnyDamagedModels(); // declare the death of a component pointer // // this happens when we know that OpenSim has destructed a component in // the model indirectly (e.g. it was destructed by an OpenSim container) // and that we want to ensure the pointer isn't still held by this state void declareDeathOf(OpenSim::Component const* c) noexcept { if (current.selected == c) { current.selected = nullptr; } if (current.hovered == c) { current.hovered = nullptr; } if (current.isolated == c) { current.isolated = nullptr; } } }; }
34.714286
85
0.620165
ComputationalBiomechanicsLab
6c49251988a31d236810dd74ca1c8e9a4e4237ce
15,696
cpp
C++
src/Tools/TriangulatePolygon/TriangulatePolygon.cpp
Terryhata6/Mengine
dfe36fdc84d7398fbbbd199feffc46c6f157f1d4
[ "MIT" ]
null
null
null
src/Tools/TriangulatePolygon/TriangulatePolygon.cpp
Terryhata6/Mengine
dfe36fdc84d7398fbbbd199feffc46c6f157f1d4
[ "MIT" ]
null
null
null
src/Tools/TriangulatePolygon/TriangulatePolygon.cpp
Terryhata6/Mengine
dfe36fdc84d7398fbbbd199feffc46c6f157f1d4
[ "MIT" ]
null
null
null
#include <Windows.h> #include <shellapi.h> #include <stdio.h> #include <string> #include <vector> #include <sstream> #include "ToolUtils/ToolUtils.h" #define BOOST_NO_IOSTREAM #pragma warning(push, 0) #pragma warning(disable:4800) #include "boost/geometry/geometry.hpp" #include "boost/geometry/core/tag.hpp" #include "boost/geometry/geometries/polygon.hpp" #include "boost/geometry/geometries/box.hpp" #include "boost/geometry/geometries/point_xy.hpp" #include "boost/geometry/geometries/segment.hpp" #include "boost/geometry/strategies/agnostic/point_in_poly_winding.hpp" #pragma warning(pop) #include "poly2tri/poly2tri.h" struct vec2f { vec2f() { }; vec2f( const vec2f & _v ) : x( _v.x ) , y( _v.y ) { }; const vec2f & operator = ( const vec2f & _v ) { x = _v.x; y = _v.y; return *this; } vec2f( double _x, double _y ) : x( _x ) , y( _y ) { }; double operator [] ( size_t i ) const { return (&x)[i]; } double & operator [] ( size_t i ) { return (&x)[i]; } template <int K> double get() const { return this->operator [] ( K ); } template <int K> void set( double _value ) { this->operator [] ( K ) = _value; } double x; double y; }; namespace boost { namespace geometry { namespace traits { template <> struct tag<vec2f> { typedef boost::geometry::point_tag type; }; template<> struct coordinate_type<vec2f> { typedef double type; }; template<> struct coordinate_system<vec2f> { typedef boost::geometry::cs::cartesian type; }; template<> struct dimension<vec2f> : boost::mpl::int_<2> { }; template<size_t Dimension> struct access<vec2f, Dimension > { static inline double get( vec2f const & p ) { return p.template get<Dimension>(); } static inline void set( vec2f & p, double const & value ) { p.template set<Dimension>( value ); } }; } // namespace traits } } typedef boost::geometry::model::polygon<vec2f, true, true> BoostPolygon; typedef std::vector<BoostPolygon> TVectorPolygon; typedef std::vector<vec2f> TVectorPoints; typedef std::vector<uint32_t> TVectorIndices; ////////////////////////////////////////////////////////////////////////// static void parse_arg( const std::wstring & _str, TVectorPoints & _value ) { std::vector<std::wstring> tokens; std::wstringstream wss( _str ); std::wstring buf; while( wss >> buf ) { tokens.push_back( buf ); } std::vector<std::wstring>::size_type count = tokens.size(); if( count % 2 != 0 ) { return; } for( uint32_t i = 0; i != count; i += 2 ) { const wchar_t * tocken_0 = tokens[i + 0].c_str(); const wchar_t * tocken_1 = tokens[i + 1].c_str(); double value_x; swscanf( tocken_0, L"%lf", &value_x ); double value_y; swscanf( tocken_1, L"%lf", &value_y ); vec2f v( (float)value_x, (float)value_y ); _value.push_back( v ); } } ////////////////////////////////////////////////////////////////////////// struct Mesh { uint16_t vertexCount; uint16_t indexCount; std::vector<vec2f> pos; std::vector<vec2f> uv; std::vector<uint16_t> indices; }; ////////////////////////////////////////////////////////////////////////// static bool polygonize( const vec2f & image_base_size, const vec2f & image_trim_size, const vec2f & image_trim_offset, bool image_bb, bool image_subtract, const TVectorPoints & points, Mesh & mesh ) { (void)image_base_size; size_t points_count = points.size(); BoostPolygon polygon_input; for( size_t points_index = 0; points_index != points_count; ++points_index ) { const vec2f & v = points[points_index]; boost::geometry::append( polygon_input, v ); } boost::geometry::correct( polygon_input ); TVectorPolygon output; if( image_bb == true ) { vec2f v0( image_trim_offset.x, image_trim_offset.y ); vec2f v1( image_trim_offset.x + image_trim_size.x, image_trim_offset.y ); vec2f v2( image_trim_offset.x + image_trim_size.x, image_trim_offset.y + image_trim_size.y ); vec2f v3( image_trim_offset.x, image_trim_offset.y + image_trim_size.y ); BoostPolygon imagePolygon; boost::geometry::append( imagePolygon, v0 ); boost::geometry::append( imagePolygon, v1 ); boost::geometry::append( imagePolygon, v2 ); boost::geometry::append( imagePolygon, v3 ); boost::geometry::correct( imagePolygon ); if( image_subtract == false ) { std::deque<BoostPolygon> result; try { boost::geometry::intersection( polygon_input, imagePolygon, result ); } catch( const std::exception & ) { return false; } for( std::deque<BoostPolygon>::const_iterator it = result.begin(), it_end = result.end(); it != it_end; ++it ) { const BoostPolygon & polygon = *it; output.push_back( polygon ); } } else { std::deque<BoostPolygon> result; try { boost::geometry::difference( imagePolygon, polygon_input, result ); } catch( const std::exception & ) { return false; } for( std::deque<BoostPolygon>::const_iterator it = result.begin(), it_end = result.end(); it != it_end; ++it ) { const BoostPolygon & polygon = *it; output.push_back( polygon ); } } } else { output.push_back( polygon_input ); } std::vector<p2t::Point> p2t_points; std::vector<p2t::Point *> p2t_polygon_trinagles; size_t max_points = 0; for( TVectorPolygon::const_iterator it = output.begin(), it_end = output.end(); it != it_end; ++it ) { const BoostPolygon & shape_vertex = *it; const BoostPolygon::ring_type & shape_vertex_ring = shape_vertex.outer(); size_t outer_count = shape_vertex_ring.size(); max_points += outer_count - 1; const BoostPolygon::inner_container_type & shape_vertex_inners = shape_vertex.inners(); size_t inners_count = shape_vertex_inners.size(); for( size_t index = 0; index != inners_count; ++index ) { const BoostPolygon::ring_type & shape_vertex_inners_ring = shape_vertex_inners[index]; size_t inner_count = shape_vertex_inners_ring.size(); max_points += inner_count - 1; } } p2t_points.reserve( max_points ); TVectorIndices shape_indices; for( TVectorPolygon::const_iterator it = output.begin(), it_end = output.end(); it != it_end; ++it ) { const BoostPolygon & shape_vertex = *it; std::vector<p2t::Point *> p2t_polygon; const BoostPolygon::ring_type & shape_vertex_ring = shape_vertex.outer(); size_t outer_count = shape_vertex_ring.size(); for( size_t index = 0; index != outer_count - 1; ++index ) { const vec2f & v = shape_vertex_ring[index]; p2t_points.push_back( p2t::Point( v.x, v.y ) ); p2t::Point * p = &p2t_points.back(); p2t_polygon.push_back( p ); } p2t::CDT cdt( p2t_polygon ); const BoostPolygon::inner_container_type & shape_vertex_inners = shape_vertex.inners(); size_t inners_count = shape_vertex_inners.size(); for( size_t index_inners = 0; index_inners != inners_count; ++index_inners ) { std::vector<p2t::Point *> p2t_hole; const BoostPolygon::ring_type & shape_vertex_inners_ring = shape_vertex_inners[index_inners]; size_t inner_count = shape_vertex_inners_ring.size(); for( size_t index_inner = 0; index_inner != inner_count - 1; ++index_inner ) { const vec2f & v = shape_vertex_inners_ring[index_inner]; p2t_points.push_back( p2t::Point( v.x, v.y ) ); p2t::Point * p = &p2t_points.back(); p2t_hole.push_back( p ); } cdt.AddHole( p2t_hole ); } cdt.Triangulate(); std::vector<p2t::Triangle *> triangles = cdt.GetTriangles(); for( std::vector<p2t::Triangle *>::iterator it_triangle = triangles.begin(), it_triangle_end = triangles.end(); it_triangle != it_triangle_end; ++it_triangle ) { p2t::Triangle * tr = *it_triangle; p2t::Point * p0 = tr->GetPoint( 0 ); p2t::Point * p1 = tr->GetPoint( 1 ); p2t::Point * p2 = tr->GetPoint( 2 ); if( std::find( p2t_polygon_trinagles.begin(), p2t_polygon_trinagles.end(), p0 ) == p2t_polygon_trinagles.end() ) { p2t_polygon_trinagles.push_back( p0 ); } if( std::find( p2t_polygon_trinagles.begin(), p2t_polygon_trinagles.end(), p1 ) == p2t_polygon_trinagles.end() ) { p2t_polygon_trinagles.push_back( p1 ); } if( std::find( p2t_polygon_trinagles.begin(), p2t_polygon_trinagles.end(), p2 ) == p2t_polygon_trinagles.end() ) { p2t_polygon_trinagles.push_back( p2 ); } } for( std::vector<p2t::Triangle *>::iterator it_triangle = triangles.begin(), it_triangle_end = triangles.end(); it_triangle != it_triangle_end; ++it_triangle ) { p2t::Triangle * tr = *it_triangle; p2t::Point * p0 = tr->GetPoint( 0 ); p2t::Point * p1 = tr->GetPoint( 1 ); p2t::Point * p2 = tr->GetPoint( 2 ); uint32_t i0 = (uint32_t)std::distance( p2t_polygon_trinagles.begin(), std::find( p2t_polygon_trinagles.begin(), p2t_polygon_trinagles.end(), p0 ) ); uint32_t i1 = (uint32_t)std::distance( p2t_polygon_trinagles.begin(), std::find( p2t_polygon_trinagles.begin(), p2t_polygon_trinagles.end(), p1 ) ); uint32_t i2 = (uint32_t)std::distance( p2t_polygon_trinagles.begin(), std::find( p2t_polygon_trinagles.begin(), p2t_polygon_trinagles.end(), p2 ) ); shape_indices.push_back( i0 ); shape_indices.push_back( i1 ); shape_indices.push_back( i2 ); } } if( output.empty() == true ) { mesh.vertexCount = 0U; mesh.indexCount = 0U; } else { size_t shapeVertexCount = p2t_polygon_trinagles.size(); size_t shapeIndicesCount = shape_indices.size(); mesh.vertexCount = (uint16_t)shapeVertexCount; mesh.indexCount = (uint16_t)shapeIndicesCount; mesh.pos.resize( shapeVertexCount ); mesh.uv.resize( shapeVertexCount ); mesh.indices.resize( shapeIndicesCount ); for( size_t i = 0; i != shapeVertexCount; ++i ) { const p2t::Point * shape_pos = p2t_polygon_trinagles[i]; mesh.pos[i].x = (float)shape_pos->x; mesh.pos[i].y = (float)shape_pos->y; mesh.uv[i].x = ((float)shape_pos->x - image_trim_offset.x) / image_trim_size.x; mesh.uv[i].y = ((float)shape_pos->y - image_trim_offset.y) / image_trim_size.y; } for( size_t i = 0; i != shapeIndicesCount; ++i ) { mesh.indices[i] = (uint16_t)shape_indices[i]; } } return true; } ////////////////////////////////////////////////////////////////////////// int APIENTRY wWinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, PWSTR lpCmdLine, int nShowCmd ) { (void)hInstance; (void)hPrevInstance; (void)nShowCmd; std::wstring arg_image_bb; std::wstring arg_image_base_size; std::wstring arg_image_trim_size; std::wstring arg_image_trim_offset; std::wstring arg_polygon_input; bool image_bb = parse_kwds( lpCmdLine, L"--bb", false ); float base_width = parse_kwds( lpCmdLine, L"--base_width", 0.f ); float base_height = parse_kwds( lpCmdLine, L"--base_height", 0.f ); float trim_width = parse_kwds( lpCmdLine, L"--trim_width", 0.f ); float trim_height = parse_kwds( lpCmdLine, L"--trim_height", 0.f ); float trim_offset_x = parse_kwds( lpCmdLine, L"--trim_offset_x", 0.f ); float trim_offset_y = parse_kwds( lpCmdLine, L"--trim_offset_y", 0.f ); bool image_subtract = parse_kwds( lpCmdLine, L"--subtract", false ); TVectorPoints points = parse_kwds( lpCmdLine, L"--points", TVectorPoints() ); std::wstring result_path = parse_kwds( lpCmdLine, L"--result_path", std::wstring() ); vec2f image_base_size( base_width, base_height ); vec2f image_trim_size( trim_width, trim_height ); vec2f image_trim_offset( trim_offset_x, trim_offset_y ); Mesh mesh; bool successful = polygonize( image_base_size, image_trim_size, image_trim_offset, image_bb, image_subtract, points, mesh ); WCHAR infoCanonicalizeQuote[MAX_PATH]; ForcePathQuoteSpaces( infoCanonicalizeQuote, result_path.c_str() ); PathUnquoteSpaces( infoCanonicalizeQuote ); FILE * f_result; errno_t err = _wfopen_s( &f_result, infoCanonicalizeQuote, L"wt" ); if( err != 0 ) { message_error( "invalid _wfopen %ls err %d\n" , infoCanonicalizeQuote , err ); return 0; } if( successful == false ) { fprintf_s( f_result, "# invalid polygonize\n" ); } else { fprintf_s( f_result, "%u\n", mesh.vertexCount ); fprintf_s( f_result, "%u\n", mesh.indexCount ); fprintf_s( f_result, "" ); for( uint16_t i = 0; i != mesh.vertexCount; ++i ) { if( i != 0 ) { fprintf_s( f_result, "," ); } const vec2f & pos = mesh.pos[i]; fprintf_s( f_result, " %12f, %12f" , pos.x , pos.y ); } fprintf_s( f_result, "\n" ); fprintf_s( f_result, "" ); for( uint16_t i = 0; i != mesh.vertexCount; ++i ) { if( i != 0 ) { fprintf_s( f_result, "," ); } const vec2f & uv = mesh.uv[i]; fprintf_s( f_result, " %12f, %12f" , uv.x , uv.y ); } fprintf_s( f_result, "\n" ); fprintf_s( f_result, "" ); for( uint16_t i = 0; i != mesh.indexCount; ++i ) { if( i != 0 ) { fprintf_s( f_result, "," ); } uint16_t index = mesh.indices[i]; fprintf_s( f_result, " %u" , index ); } fprintf_s( f_result, "\n" ); } fclose( f_result ); return 0; }
27.731449
198
0.544151
Terryhata6
6c54d6f2a98c3073bbe807c2ecf0950ab6be0785
3,298
cpp
C++
2048.cpp
eric0410771/Game_Theory_CPP
d739035ef64b4831491ca47126baf6f2216ad498
[ "MIT" ]
null
null
null
2048.cpp
eric0410771/Game_Theory_CPP
d739035ef64b4831491ca47126baf6f2216ad498
[ "MIT" ]
null
null
null
2048.cpp
eric0410771/Game_Theory_CPP
d739035ef64b4831491ca47126baf6f2216ad498
[ "MIT" ]
null
null
null
/** * Basic Environment for Game 2048 * use 'g++ -std=c++11 -O3 -g -o 2048 2048.cpp' to compile the source * * Computer Games and Intelligence (CGI) Lab, NCTU, Taiwan * http://www.aigames.nctu.edu.tw */ #include <iostream> #include <fstream> #include <iterator> #include <string> #include "board.h" #include "action.h" #include "agent.h" #include "episode.h" #include "statistic.h" #include <stdio.h> #include<vector> int main(int argc, const char* argv[]) { std::cout << "Thress-Demo: "; std::copy(argv, argv + argc, std::ostream_iterator<const char*>(std::cout, " ")); std::cout << std::endl << std::endl; size_t total = 5000, block = 0, limit = 0; std::string play_args, evil_args; std::string load, save; bool summary = false; for (int i = 1; i < argc; i++) { std::string para(argv[i]); if (para.find("--total=") == 0) { total = std::stoull(para.substr(para.find("=") + 1)); } else if (para.find("--block=") == 0) { block = std::stoull(para.substr(para.find("=") + 1)); } else if (para.find("--limit=") == 0) { limit = std::stoull(para.substr(para.find("=") + 1)); } else if (para.find("--play=") == 0) { play_args = para.substr(para.find("=") + 1); } else if (para.find("--evil=") == 0) { evil_args = para.substr(para.find("=") + 1); } else if (para.find("--load=") == 0) { load = para.substr(para.find("=") + 1); } else if (para.find("--save=") == 0) { save = para.substr(para.find("=") + 1); } else if (para.find("--summary") == 0) { summary = true; } } statistic stat(total, block, limit); if (load.size()) { std::ifstream in(load, std::ios::in); in >> stat; in.close(); summary |= stat.is_finished(); } weight_agent play(play_args); rndenv evil(evil_args); action move; int last_slide; action_op player_move; action_reward action_result; while (!stat.is_finished()) { play.open_episode("~:" + evil.name()); evil.open_episode(play.name() + ":~"); std::vector<std::vector<int>> state_index; std::vector<std::vector<int>> after_state_index; std::vector<int> rewards; stat.open_episode(play.name() + ":" + evil.name()); episode& game = stat.back(); last_slide = -1; std::vector<int> state; while (true) { agent& who = game.take_turns(play, evil); if(who.role().compare("player") == 0){ player_move = who.take_action2(game.state()); last_slide = player_move.op; move = player_move.s; } else{ move = who.take_action(game.state(),last_slide); } action_result = game.apply_action(move); if (who.role().compare("player") == 0){ if(state.size() == 0){ state = game.state().features(); }else{ state_index.push_back(state); after_state_index.push_back(game.state().features()); rewards.push_back(action_result.reward); state = game.state().features(); } } if (not action_result.legal_action or who.check_for_win(game.state())) break; } agent& win = game.last_turns(play, evil); stat.close_episode(win.name()); play.update_weights(state_index, rewards, after_state_index); play.close_episode(win.name()); evil.close_episode(win.name()); } if (summary) { stat.summary(); } if (save.size()) { std::ofstream out(save, std::ios::out | std::ios::trunc); out << stat; out.close(); } return 0; }
27.949153
82
0.620376
eric0410771
6c598852f77a18abe809573eecdd8da4ae6f3507
310
cpp
C++
libs/test/doc/src/examples/example26.cpp
zyiacas/boost-doc-zh
689e5a3a0a4dbead1a960f7b039e3decda54aa2c
[ "BSL-1.0" ]
198
2015-01-13T05:47:18.000Z
2022-03-09T04:46:46.000Z
libs/test/doc/src/examples/example26.cpp
sdfict/boost-doc-zh
689e5a3a0a4dbead1a960f7b039e3decda54aa2c
[ "BSL-1.0" ]
9
2015-01-28T16:33:19.000Z
2020-04-12T23:03:28.000Z
libs/test/doc/src/examples/example26.cpp
sdfict/boost-doc-zh
689e5a3a0a4dbead1a960f7b039e3decda54aa2c
[ "BSL-1.0" ]
139
2015-01-15T20:09:31.000Z
2022-01-31T15:21:16.000Z
#include <boost/test/prg_exec_monitor.hpp> // this header is optional //____________________________________________________________________________// int cpp_main( int, char* [] ) // note the name { return 5; } //____________________________________________________________________________//
28.181818
81
0.783871
zyiacas
6c5c7e3ee59db26f09b2a1e518ce451f09854e1b
23,913
cpp
C++
directfire_github/trunk/gameui/battle.net/headsettingdialog.cpp
zhwsh00/DirectFire-android
10c757e1be0b25dee951f9ba3a0e1f6d5c04a938
[ "MIT" ]
1
2015-08-12T04:05:33.000Z
2015-08-12T04:05:33.000Z
directfire_github/trunk/gameui/battle.net/headsettingdialog.cpp
zhwsh00/DirectFire-android
10c757e1be0b25dee951f9ba3a0e1f6d5c04a938
[ "MIT" ]
null
null
null
directfire_github/trunk/gameui/battle.net/headsettingdialog.cpp
zhwsh00/DirectFire-android
10c757e1be0b25dee951f9ba3a0e1f6d5c04a938
[ "MIT" ]
null
null
null
#include "headsettingdialog.h" #include "gamecore/resource/resourcemgr.h" #include "gamecore/sounds/soundmgr.h" #include "utils/sysutils.h" #include "utils/fileutils.h" #include "ccimagecliper.h" HeadSettingDialog::HeadSettingDialog(CCNode *parent,const ccColor4B &color) : BasShowDialog(parent,color) { m_serverInf = ServerInterface::getInstance(); m_accountInf = m_serverInf->getLoginAccountInfo(); m_headSprite = CCSprite::create(); m_headPortrait = "portraitdefault"; m_resetImg = "buttonbg"; m_resetButton = 0; m_loadingDialog = 0; m_submitPortraitListener = 0; m_submitPortraitFunc = 0; PhotoHelper::getInstance()->registerListener(this); m_serverInf->setHeadSettingCB(this,callfuncND_selector(HeadSettingDialog::onSubmitSuc),callfuncND_selector(HeadSettingDialog::onSubmitFailed)); m_editAble = false; } HeadSettingDialog::~HeadSettingDialog() { PhotoHelper::getInstance()->unRegisterListener(this); } void HeadSettingDialog::takePhotoFinished(const char* imageData, int len, const char* imageDataHq, int lenHq) { m_headPortrait.assign(imageDataHq, lenHq); portraitUpdated(m_headPortrait); if(m_submitPortraitListener && m_submitPortraitFunc) { (m_submitPortraitListener->*m_submitPortraitFunc)(this,&m_headPortrait); } } void HeadSettingDialog::takePhotoFinished(const char* imageFile) { if(imageFile == 0) return; CCNode *root = this->getParent(); while(root->getParent()) root = root->getParent(); CCImageCliper *cliper = new CCImageCliper(imageFile,this,root,ccc4(0,0,0,128)); cliper->setTouchPriority(this->touchPriority() - uilib::SafePriorityGap); cliper->exec(); } void HeadSettingDialog::takePhotoFailed() { } void HeadSettingDialog::takePhotoCanceled() { } void HeadSettingDialog::setHeadSprite(CCSprite *headSprite) { m_headSprite->initWithTexture(headSprite->getTexture()); } void HeadSettingDialog::setEditAble(bool editAble) { m_editAble = editAble; } void HeadSettingDialog::setSubmitPortraitCB(CCNode *listener,SEL_CallFuncND func) { m_submitPortraitListener = listener; m_submitPortraitFunc = func; } void HeadSettingDialog::portraitUpdated(const std::string& imgData) { float width = 220; float height = 220; CCImage *img = new CCImage; img->initWithImageData((void*)imgData.data(),imgData.size(), CCImage::kFmtUnKnown); CCTexture2D *texture = new CCTexture2D; texture->initWithImage(img); m_headSprite->initWithTexture(texture); CCSize csize = m_headSprite->getContentSize(); m_headSprite->setScaleX(width / csize.width); m_headSprite->setScaleY(height / csize.height); delete img; CCFadeIn *fade = CCFadeIn::create(0.5); m_headSprite->runAction(fade); } void HeadSettingDialog::exec() { finish(); BasShowDialog::exec(); } void HeadSettingDialog::finish() { // dialog CCSize size = CCDirector::sharedDirector()->getWinSize(); setHeight(size.height * 0.9); LangDef *lang = ResourceMgr::getInstance()->getLangDef(); // base area m_baseArea = new BasWidget; this->addChild(m_baseArea); m_baseArea->setFill("parent"); BasWidget *portraitArea = new BasWidget; m_baseArea->addChild(portraitArea); portraitArea->setHeight(getHeight() / 4.0); portraitArea->setWidth(getWidth() - (m_edgeSize * 2)); BasWidget *accountArea = new BasWidget; m_baseArea->addChild(accountArea); accountArea->setHeight(getHeight() / 2.0); accountArea->setWidth(getWidth() - (m_edgeSize * 2)); BasWidget *accountAreaLeft = new BasWidget; BasWidget *accountAreaRight = new BasWidget; accountAreaLeft->setTop("parent", uilib::Top); accountAreaLeft->setBottom("parent", uilib::Bottom); accountAreaLeft->setLeft("parent", uilib::Left); accountAreaLeft->setMaxWidthRefSize("parent", 0.3); accountAreaLeft->setMinWidthRefSize("parent", 0.3); accountAreaRight->setTop("parent", uilib::Top); accountAreaRight->setBottom("parent", uilib::Bottom); accountAreaRight->setLeft(accountAreaLeft->getName(), uilib::Right); accountAreaRight->setLeftMargin(m_edgeSize); accountAreaRight->setRight("parent", uilib::Right); accountAreaRight->setRightMargin(m_edgeSize * 2); accountArea->addChild(accountAreaLeft); accountArea->addChild(accountAreaRight); BasWidget *bottomArea = new BasWidget; m_baseArea->addChild(bottomArea); bottomArea->setHeight(getHeight() / 6.0); bottomArea->setWidth(getWidth() - (m_edgeSize * 2)); // portrait area portraitArea->setTop("parent",uilib::Top); portraitArea->setTopMargin(m_edgeSize * 10.0); portraitArea->setHorizontal("parent",0.5); BasWidget *portraitLeftArea = new BasWidget; BasWidget *portraitRightArea = new BasWidget; portraitLeftArea->setLeft("parent", uilib::Left); portraitLeftArea->setTop("parent", uilib::Top); portraitLeftArea->setBottom("parent", uilib::Bottom); portraitLeftArea->setMaxWidthRefSize("parent", 0.6); portraitLeftArea->setMinWidthRefSize("parent", 0.6); portraitRightArea->setLeft(portraitLeftArea->getName(), uilib::Right); portraitRightArea->setLeftMargin(m_edgeSize); portraitRightArea->setTop("parent", uilib::Top); portraitRightArea->setBottom("parent", uilib::Bottom); portraitRightArea->setRight("parent", uilib::Right); portraitArea->addChild(portraitLeftArea); portraitArea->addChild(portraitRightArea); // portrait sub area m_headDelegate = new BasNodeDelegateWidget(m_headSprite); portraitLeftArea->addChild(m_headDelegate); m_headDelegate->setVertical("parent",0.5); m_headDelegate->setHorizontal("parent",0.5); // upload button layout BasButton* uploadButton = new BasButton; uploadButton->setWidth(150.0f); // logout button layout BasButton* logoutButton = new BasButton; logoutButton->setWidth(150.0f); //exit button BasButton *exitButton = new BasButton; exitButton->setWidth(150.0f); VerticalLayout *vlayPortrait = new VerticalLayout; vlayPortrait->addWidget(exitButton); vlayPortrait->addWidget(logoutButton); vlayPortrait->addWidget(uploadButton); vlayPortrait->setAveraged(true); vlayPortrait->setChildAlign(0,uilib::Left); vlayPortrait->setChildAlign(1,uilib::Left); vlayPortrait->setChildAlign(2,uilib::Left); portraitRightArea->setLayout(vlayPortrait); // portrait UiThemeDef *uiDef = UiThemeMgrProxy::getInstance()->getThemeByName(m_theme); if(!m_headSprite->getTexture()) { std::string headimg; uiDef->getNormalData()->getImg(m_headPortrait,headimg); m_headSprite->initWithSpriteFrameName(headimg.data()); } // upload button uploadButton->setButtonInfo(lang->getStringById(StringEnum::Upload),m_theme,m_resetImg,CCSizeMake(0,0),m_resetPressedImg,getSystemFont(),24,ccWHITE); uploadButton->setClickCB(this,callfuncND_selector(HeadSettingDialog::onUploadClicked)); // logout button logoutButton->setButtonInfo(lang->getStringById(StringEnum::Logout),m_theme,m_resetImg,CCSizeMake(0,0),m_resetPressedImg,getSystemFont(),24,ccWHITE); logoutButton->setClickCB(this,callfuncND_selector(HeadSettingDialog::onLogOutClicked)); //exit button exitButton->setButtonInfo(lang->getStringById(StringEnum::QuitGame),m_theme,m_resetImg,CCSizeMake(0,0),m_resetPressedImg,getSystemFont(),24,ccWHITE); exitButton->setClickCB(this,callfuncND_selector(HeadSettingDialog::onExitGameClicked)); // account info area accountArea->setBottom(bottomArea->getName(),uilib::Top); accountArea->setBottomMargin(m_edgeSize * 2.0); accountArea->setHorizontal("parent",0.5); // id BasLabel *idLbl = new BasLabel; idLbl->setLabelInfo(lang->getStringById(StringEnum::ID),"","",CCSizeMake(0,0),getSystemFont(),24); BasLabel *idLbl2 = new BasLabel; idLbl2->setLabelInfo(m_accountInf->m_id,"","",CCSizeMake(0,0),getSystemFont(),24); // account BasLabel *accountLbl = new BasLabel; accountLbl->setLabelInfo(lang->getStringById(StringEnum::Mail),"","",CCSizeMake(0,0),getSystemFont(),24); m_accountInput = new InputBox; m_accountInput->setMaxLength(24); m_accountInput->setTheme("default","inputbg"); m_accountInput->setText(m_accountInf->m_mail); m_accountInput->setHeight(60); // password BasLabel *pwdLbl = new BasLabel; pwdLbl->setLabelInfo(lang->getStringById(StringEnum::Password),"","",CCSizeMake(0,0),getSystemFont(),24); m_pwdInput = new InputBox; m_pwdInput->setMaxLength(24); m_pwdInput->setTheme("default","inputbg"); m_pwdInput->setText(m_accountInf->m_password); m_pwdInput->setInputFlag(kEditBoxInputFlagPassword); m_pwdInput->setHeight(60); // password confirm BasLabel *pwdConfirmLbl = new BasLabel; pwdConfirmLbl->setLabelInfo(lang->getStringById(StringEnum::PasswordConfirm),"","",CCSizeMake(0,0),getSystemFont(),24); m_pwdConfirmInput = new InputBox; m_pwdConfirmInput->setMaxLength(24); m_pwdConfirmInput->setTheme("default","inputbg"); m_pwdConfirmInput->setText(m_accountInf->m_password); m_pwdConfirmInput->setInputFlag(kEditBoxInputFlagPassword); m_pwdConfirmInput->setHeight(60); // nick name BasLabel *nickNameLbl = new BasLabel; nickNameLbl->setLabelInfo(lang->getStringById(StringEnum::NickName),"","",CCSizeMake(0,0),getSystemFont(),24); m_nickNameInput = new InputBox; m_nickNameInput->setMaxLength(14); m_nickNameInput->setTheme("default","inputbg"); m_nickNameInput->setText(m_accountInf->m_name); m_nickNameInput->setHeight(60); if(m_accountInf->m_name.empty()){ //show the nick name no exist warnning BasLabel *nickNameSet = new BasLabel; nickNameSet->setLabelInfo(lang->getStringById(StringEnum::SetYourNickName),"","",CCSizeMake(0,0),getSystemFont(),24,ccWHITE); this->addChild(nickNameSet); nickNameSet->setHorizontal("parent",0.5); nickNameSet->setTop("parent",uilib::Top); nickNameSet->setTopMargin(10); } // sex BasLabel *sexLbl = new BasLabel; sexLbl->setLabelInfo(lang->getStringById(StringEnum::Sex),"","",CCSizeMake(0,0),getSystemFont(),24); BasWidget *sexRadioArea = new BasWidget; sexRadioArea->setWidth(accountAreaRight->getWidth()); // female radio button m_femaleButton = new CheckBox; m_maleButton = new CheckBox; sexRadioArea->addChild(m_maleButton); sexRadioArea->addChild(m_femaleButton); m_maleButton->setTop("parent", uilib::Top); m_maleButton->setBottom("parent", uilib::Bottom); m_maleButton->setLeft("parent", uilib::Left); m_maleButton->setMaxWidthRefSize("parent", 0.5); m_maleButton->setMinWidthRefSize("parent", 0.5); m_maleButton->setClickCB(this,callfuncND_selector(HeadSettingDialog::onMaleClicked)); m_maleButton->setCheckInfo(lang->getStringById(StringEnum::Male).data(),"fonts/uifont24.fnt","default","",CCSizeMake(60,60)); m_femaleButton->setTop("parent", uilib::Top); m_femaleButton->setBottom("parent", uilib::Bottom); m_femaleButton->setLeft(m_maleButton->getName(), uilib::Right); m_femaleButton->setLeftMargin(m_edgeSize); m_femaleButton->setRight("parent", uilib::Right); m_femaleButton->setRightMargin(m_edgeSize * 2); m_femaleButton->setClickCB(this,callfuncND_selector(HeadSettingDialog::onFemaleClicked)); m_femaleButton->setCheckInfo(lang->getStringById(StringEnum::Female).data(),"fonts/uifont24.fnt","default","",CCSizeMake(60,60)); if (m_accountInf->m_sex == 0) { m_femaleButton->setCheck(true); m_maleButton->setCheck(false); } else { m_femaleButton->setCheck(false); m_maleButton->setCheck(true); } // account area layout VerticalLayout *vlayAccountLeft = new VerticalLayout; vlayAccountLeft->addWidget(idLbl); vlayAccountLeft->addWidget(accountLbl); vlayAccountLeft->addWidget(pwdLbl); vlayAccountLeft->addWidget(pwdConfirmLbl); vlayAccountLeft->addWidget(nickNameLbl); vlayAccountLeft->addWidget(sexLbl); vlayAccountLeft->setAveraged(true); vlayAccountLeft->setChildAlign(0,uilib::Left); vlayAccountLeft->setChildAlign(1,uilib::Left); vlayAccountLeft->setChildAlign(2,uilib::Left); vlayAccountLeft->setChildAlign(3,uilib::Left); vlayAccountLeft->setChildAlign(4,uilib::Left); vlayAccountLeft->setChildAlign(5,uilib::Left); vlayAccountLeft->setLeftMargin(40); accountAreaLeft->setLayout(vlayAccountLeft); VerticalLayout *vlayAccountRight = new VerticalLayout; vlayAccountRight->addWidget(idLbl2); vlayAccountRight->addWidget(m_accountInput); vlayAccountRight->addWidget(m_pwdInput); vlayAccountRight->addWidget(m_pwdConfirmInput); vlayAccountRight->addWidget(m_nickNameInput); vlayAccountRight->addWidget(sexRadioArea); vlayAccountRight->setAveraged(true); vlayAccountRight->setChildAlign(0,uilib::Left); vlayAccountRight->setChildAlign(1,uilib::Left); vlayAccountRight->setChildAlign(2,uilib::Left); vlayAccountRight->setChildAlign(3,uilib::Left); vlayAccountRight->setChildAlign(4,uilib::Left); vlayAccountRight->setChildAlign(5,uilib::Left); vlayAccountRight->setChildAlign(1,uilib::Right); vlayAccountRight->setChildAlign(2,uilib::Right); vlayAccountRight->setChildAlign(3,uilib::Right); vlayAccountRight->setChildAlign(4,uilib::Right); vlayAccountRight->setChildAlign(5,uilib::Right); accountAreaRight->setLayout(vlayAccountRight); // button area bottomArea->setBottom("parent",uilib::Bottom); bottomArea->setBottomMargin(m_edgeSize * 2.0); bottomArea->setHorizontal("parent",0.5); // reset button m_resetButton = new BasButton; m_resetButton->setButtonInfo(lang->getStringById(StringEnum::Reset),m_theme,m_resetImg,CCSizeMake(0,0),m_resetPressedImg,getSystemFont(),24,ccWHITE); bottomArea->addChild(m_resetButton); m_resetButton->setVertical("parent",0.5); m_resetButton->setHorizontal("parent",0.5); m_resetButton->setClickCB(this,callfuncND_selector(HeadSettingDialog::onResetClicked)); // submit button m_submitButton = new BasButton; m_submitButton->setButtonInfo(lang->getStringById(StringEnum::Submit),m_theme,m_resetImg,CCSizeMake(0,0),m_resetPressedImg,getSystemFont(),24,ccWHITE); bottomArea->addChild(m_submitButton); m_submitButton->setVertical("parent",0.5); m_submitButton->setHorizontal("parent",0.5); m_submitButton->setClickCB(this,callfuncND_selector(HeadSettingDialog::onSubmitClicked)); editEnabled(m_editAble); } void HeadSettingDialog::setResetImg(const std::string &normal,const std::string &pressed) { m_resetImg = normal; m_resetPressedImg = pressed; } void HeadSettingDialog::onUploadClicked(CCNode *sender,void *data) { SoundMgr::getInstance()->playEffect(SoundEnum::BTN_EFFECT_NORMAL); if (CC_TARGET_PLATFORM == CC_PLATFORM_BLACKBERRY){ std::string text; text.append("Upload portrait no supported in bb10 now!"); new SplashMessageWidget(this,text); return; }else if(CC_TARGET_PLATFORM == CC_PLATFORM_LINUX){ takePhotoFinished("/home/water/work/cocos2d-2.1beta3-x-2.1.0/directfire/trunk/Resources/ss0.jpg"); return; } LangDef *lang = ResourceMgr::getInstance()->getLangDef(); PhotoHelper::getInstance()->setLangCancel(lang->getStringById(StringEnum::Cancel)); PhotoHelper::getInstance()->setLangChooseImage(lang->getStringById(StringEnum::ChooseImage)); PhotoHelper::getInstance()->setLangTakePhoto(lang->getStringById(StringEnum::TakePhoto)); PhotoHelper::getInstance()->takePhoto(); } void HeadSettingDialog::onLogOutClicked(CCNode *sender,void *data) { SoundMgr::getInstance()->playEffect(SoundEnum::BTN_EFFECT_NORMAL); m_serverInf->disconnectGameServer(); } void HeadSettingDialog::onExitGameClicked(CCNode *sender,void *data) { SoundMgr::getInstance()->playEffect(SoundEnum::BTN_EFFECT_NORMAL); m_serverInf->disconnectGameServer(); ResourceMgr::getInstance()->getUserDataMgr()->getInstance()->flush(); CCDirector::sharedDirector()->end(); #if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS) exit(0); #endif } void HeadSettingDialog::onResetClicked(CCNode *sender,void *data) { SoundMgr::getInstance()->playEffect(SoundEnum::BTN_EFFECT_NORMAL); editEnabled(true); } void HeadSettingDialog::editEnabled(bool enable) { if (enable) { m_resetButton->setVisible(false); m_submitButton->setVisible(true); showEditAbleInputBox(); m_femaleButton->setEnabled(true); m_maleButton->setEnabled(true); } else { m_resetButton->setVisible(true); m_submitButton->setVisible(false); showDisableInputBox(); m_femaleButton->setEnabled(false); m_maleButton->setEnabled(false); } } void HeadSettingDialog::onSubmitClicked(CCNode *sender,void *data) { SoundMgr::getInstance()->playEffect(SoundEnum::BTN_EFFECT_NORMAL); if(!sendFormData()) return; } bool HeadSettingDialog::sendFormData() { m_resetButton->setVisible(true); m_submitButton->setVisible(false); // hidden the inputbox prevent on top of loading dialog hiddenInputBox(); m_femaleButton->setEnabled(false); m_maleButton->setEnabled(false); LangDef *lang = ResourceMgr::getInstance()->getLangDef(); string mail = m_accountInput->getText(); string password = m_pwdInput->getText(); string passwordConfirm = m_pwdConfirmInput->getText(); string nickName = m_nickNameInput->getText(); short sex = 0; if(m_femaleButton->isCheck()) sex = 0; else sex = 1; // nothing changed if ((mail.compare(m_accountInf->m_mail) == 0 && !mail.empty()) && (password.compare(m_accountInf->m_password) == 0 && !password.empty()) && (passwordConfirm.compare(m_accountInf->m_password) == 0 && !passwordConfirm.empty()) && (nickName.compare(m_accountInf->m_name) == 0 && !nickName.empty()) && (sex == m_accountInf->m_sex)) { showDisableInputBox(); return true; } // verify account if (mail.empty()) { SplashMessageWidget *splash = new SplashMessageWidget(this,lang->getStringById(StringEnum::AccountEmptyError)); splash->setFinishedCB(this,callfuncN_selector(HeadSettingDialog::onFailedSplashFinished)); return false; } if (!isMailAddress(mail)) { SplashMessageWidget *splash = new SplashMessageWidget(this,lang->getStringById(StringEnum::AccountNotMailError)); splash->setFinishedCB(this,callfuncN_selector(HeadSettingDialog::onFailedSplashFinished)); return false; } // verify password if (password.empty() || passwordConfirm.empty()) { SplashMessageWidget *splash = new SplashMessageWidget(this,lang->getStringById(StringEnum::PasswordEmptyError)); splash->setFinishedCB(this,callfuncN_selector(HeadSettingDialog::onFailedSplashFinished)); return false; } if (password.size() < 4) { SplashMessageWidget *splash = new SplashMessageWidget(this,lang->getStringById(StringEnum::PasswordLenError)); splash->setFinishedCB(this,callfuncN_selector(HeadSettingDialog::onFailedSplashFinished)); return false; } if (password.compare(passwordConfirm) != 0) { SplashMessageWidget *splash = new SplashMessageWidget(this,lang->getStringById(StringEnum::PasswordConfirmError)); splash->setFinishedCB(this,callfuncN_selector(HeadSettingDialog::onFailedSplashFinished)); return false; } if (nickName.empty()) { SplashMessageWidget *splash = new SplashMessageWidget(this,lang->getStringById(StringEnum::NickNameEmptyError)); splash->setFinishedCB(this,callfuncN_selector(HeadSettingDialog::onFailedSplashFinished)); return false; } if (hasSpecialChar(mail) || hasSpecialChar(password) || hasSpecialChar(nickName)) { SplashMessageWidget *splash = new SplashMessageWidget(this,lang->getStringById(StringEnum::SpecialCharactersError)); splash->setFinishedCB(this,callfuncN_selector(HeadSettingDialog::onFailedSplashFinished)); return false; } if(m_loadingDialog == 0){ m_loadingDialog = new BusyDialog(); m_loadingDialog->setTouchPriority(this->touchPriority() - uilib::SafePriorityGap); CCNode *root = this->getParent(); while (root->getParent()) { root = root->getParent(); } root->addChild(m_loadingDialog, 11000); m_loadingDialog->setBusyText(lang->getStringById(StringEnum::Loading)); m_loadingDialog->setAnimationName("uiloadinga"); } m_loadingDialog->setLoadFinishedCB(this,callfuncN_selector(HeadSettingDialog::onSubmitStart)); m_loadingDialog->exec(); return true; } void HeadSettingDialog::onSubmitStart() { string mail = m_accountInput->getText(); string password = m_pwdInput->getText(); string passwordConfirm = m_pwdConfirmInput->getText(); string nickName = m_nickNameInput->getText(); short sex = 0; if(m_femaleButton->isCheck()) sex = 0; else sex = 1; // send change m_serverInf->resetUserInfo(mail, password, nickName, sex); } void HeadSettingDialog::onSubmitSuc(CCNode *sender,void *data) { if(m_loadingDialog != 0){ m_loadingDialog->destory(); m_loadingDialog = 0; } showDisableInputBox(); } void HeadSettingDialog::onSubmitFailed(CCNode *sender,void *data) { int no = *(int*)data; if(m_loadingDialog != 0){ m_loadingDialog->destory(); m_loadingDialog = 0; } LangDef *lang = ResourceMgr::getInstance()->getNetLangDef(); SplashMessageWidget *splash = new SplashMessageWidget(this,lang->getStringById(no)); splash->setFinishedCB(this,callfuncN_selector(HeadSettingDialog::onFailedSplashFinished)); } void HeadSettingDialog::onFailedSplashFinished(CCNode *sender) { m_resetButton->setVisible(false); m_submitButton->setVisible(true); showEditAbleInputBox(); m_femaleButton->setEnabled((true)); m_maleButton->setEnabled((true)); } void HeadSettingDialog::onFemaleClicked(CCNode *sender,void *data) { if(!m_femaleButton->isEnabled()) return; SoundMgr::getInstance()->playEffect(SoundEnum::BTN_EFFECT_NORMAL); m_femaleButton->setCheck(true); m_maleButton->setCheck(false); } void HeadSettingDialog::onMaleClicked(CCNode *sender,void *data) { if(!m_maleButton->isEnabled()) return; SoundMgr::getInstance()->playEffect(SoundEnum::BTN_EFFECT_NORMAL); m_femaleButton->setCheck(false); m_maleButton->setCheck(true); } void HeadSettingDialog::hiddenInputBox() { m_accountInput->setVisible(false); m_pwdInput->setVisible(false); m_pwdConfirmInput->setVisible(false); m_nickNameInput->setVisible(false); } void HeadSettingDialog::showEditAbleInputBox() { // show inputbox and enable edit m_accountInput->setVisible(true); m_pwdInput->setVisible(true); m_pwdConfirmInput->setVisible(true); m_nickNameInput->setVisible(true); if (m_accountInf->m_mail.empty()) { m_accountInput->setEnabled(true); } else { m_accountInput->setEnabled(false); } m_pwdInput->setEnabled(true); m_pwdConfirmInput->setEnabled(true); m_nickNameInput->setEnabled(true); } void HeadSettingDialog::showDisableInputBox() { // show inputbox and disable edit m_accountInput->setVisible(true); m_pwdInput->setVisible(true); m_pwdConfirmInput->setVisible(true); m_nickNameInput->setVisible(true); m_accountInput->setEnabled(false); m_pwdInput->setEnabled(false); m_pwdConfirmInput->setEnabled(false); m_nickNameInput->setEnabled(false); }
41.371972
155
0.720027
zhwsh00
6c6209dc6c677a30dee8c46d4f40c671423853df
7,573
cpp
C++
out/src/tink/core/_Callback/CallbackList_Impl_.cpp
sonygod/pb
a1bdc04c74bd91c71e96feb9f673075e780cbc81
[ "MIT" ]
null
null
null
out/src/tink/core/_Callback/CallbackList_Impl_.cpp
sonygod/pb
a1bdc04c74bd91c71e96feb9f673075e780cbc81
[ "MIT" ]
1
2020-05-17T04:37:32.000Z
2020-05-17T04:37:32.000Z
out/src/tink/core/_Callback/CallbackList_Impl_.cpp
sonygod/pb
a1bdc04c74bd91c71e96feb9f673075e780cbc81
[ "MIT" ]
null
null
null
// Generated by Haxe 4.1.0-rc.1+0545ce110 #include <hxcpp.h> #ifndef INCLUDED_tink_core_LinkObject #include <tink/core/LinkObject.h> #endif #ifndef INCLUDED_tink_core__Callback_CallbackList_Impl_ #include <tink/core/_Callback/CallbackList_Impl_.h> #endif #ifndef INCLUDED_tink_core__Callback_Callback_Impl_ #include <tink/core/_Callback/Callback_Impl_.h> #endif #ifndef INCLUDED_tink_core__Callback_ListCell #include <tink/core/_Callback/ListCell.h> #endif HX_LOCAL_STACK_FRAME(_hx_pos_fd28a8b3e9ec0864_153__new,"tink.core._Callback.CallbackList_Impl_","_new",0x5530bdef,"tink.core._Callback.CallbackList_Impl_._new","tink/core/Callback.hx",153,0x0104eb06) HX_LOCAL_STACK_FRAME(_hx_pos_fd28a8b3e9ec0864_157_get_length,"tink.core._Callback.CallbackList_Impl_","get_length",0x2f368bbd,"tink.core._Callback.CallbackList_Impl_.get_length","tink/core/Callback.hx",157,0x0104eb06) HX_LOCAL_STACK_FRAME(_hx_pos_fd28a8b3e9ec0864_159_add,"tink.core._Callback.CallbackList_Impl_","add",0x29b71553,"tink.core._Callback.CallbackList_Impl_.add","tink/core/Callback.hx",159,0x0104eb06) HX_LOCAL_STACK_FRAME(_hx_pos_fd28a8b3e9ec0864_166_invoke,"tink.core._Callback.CallbackList_Impl_","invoke",0x9c17df86,"tink.core._Callback.CallbackList_Impl_.invoke","tink/core/Callback.hx",166,0x0104eb06) HX_LOCAL_STACK_FRAME(_hx_pos_fd28a8b3e9ec0864_170_clear,"tink.core._Callback.CallbackList_Impl_","clear",0x81bd453f,"tink.core._Callback.CallbackList_Impl_.clear","tink/core/Callback.hx",170,0x0104eb06) HX_LOCAL_STACK_FRAME(_hx_pos_fd28a8b3e9ec0864_174_invokeAndClear,"tink.core._Callback.CallbackList_Impl_","invokeAndClear",0xfb2cccdc,"tink.core._Callback.CallbackList_Impl_.invokeAndClear","tink/core/Callback.hx",174,0x0104eb06) namespace tink{ namespace core{ namespace _Callback{ void CallbackList_Impl__obj::__construct() { } Dynamic CallbackList_Impl__obj::__CreateEmpty() { return new CallbackList_Impl__obj; } void *CallbackList_Impl__obj::_hx_vtable = 0; Dynamic CallbackList_Impl__obj::__Create(hx::DynamicArray inArgs) { hx::ObjectPtr< CallbackList_Impl__obj > _hx_result = new CallbackList_Impl__obj(); _hx_result->__construct(); return _hx_result; } bool CallbackList_Impl__obj::_hx_isInstanceOf(int inClassId) { return inClassId==(int)0x00000001 || inClassId==(int)0x17f0bab2; } ::Array< ::Dynamic> CallbackList_Impl__obj::_new(){ HX_STACKFRAME(&_hx_pos_fd28a8b3e9ec0864_153__new) HXDLIN( 153) ::Array< ::Dynamic> this1 = ::Array_obj< ::Dynamic>::__new(0); HXDLIN( 153) return this1; } STATIC_HX_DEFINE_DYNAMIC_FUNC0(CallbackList_Impl__obj,_new,return ) int CallbackList_Impl__obj::get_length(::Array< ::Dynamic> this1){ HX_STACKFRAME(&_hx_pos_fd28a8b3e9ec0864_157_get_length) HXDLIN( 157) return this1->length; } STATIC_HX_DEFINE_DYNAMIC_FUNC1(CallbackList_Impl__obj,get_length,return ) ::Dynamic CallbackList_Impl__obj::add(::Array< ::Dynamic> this1, ::Dynamic cb){ HX_GC_STACKFRAME(&_hx_pos_fd28a8b3e9ec0864_159_add) HXLINE( 160) ::tink::core::_Callback::ListCell node = ::tink::core::_Callback::ListCell_obj::__alloc( HX_CTX ,cb,this1); HXLINE( 161) this1->push(node); HXLINE( 162) return node; } STATIC_HX_DEFINE_DYNAMIC_FUNC2(CallbackList_Impl__obj,add,return ) void CallbackList_Impl__obj::invoke(::Array< ::Dynamic> this1, ::Dynamic data){ HX_STACKFRAME(&_hx_pos_fd28a8b3e9ec0864_166_invoke) HXDLIN( 166) int _g = 0; HXDLIN( 166) ::Array< ::Dynamic> _g1 = this1->copy(); HXDLIN( 166) while((_g < _g1->length)){ HXDLIN( 166) ::tink::core::_Callback::ListCell cell = _g1->__get(_g).StaticCast< ::tink::core::_Callback::ListCell >(); HXDLIN( 166) _g = (_g + 1); HXLINE( 167) if (hx::IsNotNull( cell->cb )) { HXLINE( 167) ::tink::core::_Callback::Callback_Impl__obj::invoke(cell->cb,data); } } } STATIC_HX_DEFINE_DYNAMIC_FUNC2(CallbackList_Impl__obj,invoke,(void)) void CallbackList_Impl__obj::clear(::Array< ::Dynamic> this1){ HX_STACKFRAME(&_hx_pos_fd28a8b3e9ec0864_170_clear) HXDLIN( 170) int _g = 0; HXDLIN( 170) ::Array< ::Dynamic> _g1 = this1->splice(0,this1->length); HXDLIN( 170) while((_g < _g1->length)){ HXDLIN( 170) ::tink::core::_Callback::ListCell cell = _g1->__get(_g).StaticCast< ::tink::core::_Callback::ListCell >(); HXDLIN( 170) _g = (_g + 1); HXLINE( 171) cell->clear(); } } STATIC_HX_DEFINE_DYNAMIC_FUNC1(CallbackList_Impl__obj,clear,(void)) void CallbackList_Impl__obj::invokeAndClear(::Array< ::Dynamic> this1, ::Dynamic data){ HX_STACKFRAME(&_hx_pos_fd28a8b3e9ec0864_174_invokeAndClear) HXDLIN( 174) int _g = 0; HXDLIN( 174) ::Array< ::Dynamic> _g1 = this1->splice(0,this1->length); HXDLIN( 174) while((_g < _g1->length)){ HXDLIN( 174) ::tink::core::_Callback::ListCell cell = _g1->__get(_g).StaticCast< ::tink::core::_Callback::ListCell >(); HXDLIN( 174) _g = (_g + 1); HXLINE( 175) if (hx::IsNotNull( cell->cb )) { HXLINE( 175) ::tink::core::_Callback::Callback_Impl__obj::invoke(cell->cb,data); } } } STATIC_HX_DEFINE_DYNAMIC_FUNC2(CallbackList_Impl__obj,invokeAndClear,(void)) CallbackList_Impl__obj::CallbackList_Impl__obj() { } bool CallbackList_Impl__obj::__GetStatic(const ::String &inName, Dynamic &outValue, hx::PropertyAccess inCallProp) { switch(inName.length) { case 3: if (HX_FIELD_EQ(inName,"add") ) { outValue = add_dyn(); return true; } break; case 4: if (HX_FIELD_EQ(inName,"_new") ) { outValue = _new_dyn(); return true; } break; case 5: if (HX_FIELD_EQ(inName,"clear") ) { outValue = clear_dyn(); return true; } break; case 6: if (HX_FIELD_EQ(inName,"invoke") ) { outValue = invoke_dyn(); return true; } break; case 10: if (HX_FIELD_EQ(inName,"get_length") ) { outValue = get_length_dyn(); return true; } break; case 14: if (HX_FIELD_EQ(inName,"invokeAndClear") ) { outValue = invokeAndClear_dyn(); return true; } } return false; } #ifdef HXCPP_SCRIPTABLE static hx::StorageInfo *CallbackList_Impl__obj_sMemberStorageInfo = 0; static hx::StaticInfo *CallbackList_Impl__obj_sStaticStorageInfo = 0; #endif hx::Class CallbackList_Impl__obj::__mClass; static ::String CallbackList_Impl__obj_sStaticFields[] = { HX_("_new",61,15,1f,3f), HX_("get_length",af,04,8f,8f), HX_("add",21,f2,49,00), HX_("invoke",78,77,e0,9f), HX_("clear",8d,71,5b,48), HX_("invokeAndClear",ce,a6,19,d4), ::String(null()) }; void CallbackList_Impl__obj::__register() { CallbackList_Impl__obj _hx_dummy; CallbackList_Impl__obj::_hx_vtable = *(void **)&_hx_dummy; hx::Static(__mClass) = new hx::Class_obj(); __mClass->mName = HX_("tink.core._Callback.CallbackList_Impl_",a0,82,ff,67); __mClass->mSuper = &super::__SGetClass(); __mClass->mConstructEmpty = &__CreateEmpty; __mClass->mConstructArgs = &__Create; __mClass->mGetStaticField = &CallbackList_Impl__obj::__GetStatic; __mClass->mSetStaticField = &hx::Class_obj::SetNoStaticField; __mClass->mStatics = hx::Class_obj::dupFunctions(CallbackList_Impl__obj_sStaticFields); __mClass->mMembers = hx::Class_obj::dupFunctions(0 /* sMemberFields */); __mClass->mCanCast = hx::TCanCast< CallbackList_Impl__obj >; #ifdef HXCPP_SCRIPTABLE __mClass->mMemberStorageInfo = CallbackList_Impl__obj_sMemberStorageInfo; #endif #ifdef HXCPP_SCRIPTABLE __mClass->mStaticStorageInfo = CallbackList_Impl__obj_sStaticStorageInfo; #endif hx::_hx_RegisterClass(__mClass->mName, __mClass); } } // end namespace tink } // end namespace core } // end namespace _Callback
40.068783
229
0.74594
sonygod
48417b49da918eff1b1f74ab854371df97d8386b
12,316
cpp
C++
VS/Graphics/VS_TextureInternal.cpp
vectorstorm/vectorstorm
7306214108b23fa97d4a1a598197bbaa52c17d3a
[ "Zlib" ]
19
2017-04-03T09:06:21.000Z
2022-03-05T19:06:07.000Z
VS/Graphics/VS_TextureInternal.cpp
vectorstorm/vectorstorm
7306214108b23fa97d4a1a598197bbaa52c17d3a
[ "Zlib" ]
2
2019-05-24T14:40:07.000Z
2020-04-15T01:10:23.000Z
VS/Graphics/VS_TextureInternal.cpp
vectorstorm/vectorstorm
7306214108b23fa97d4a1a598197bbaa52c17d3a
[ "Zlib" ]
2
2020-03-08T07:14:49.000Z
2020-03-09T10:39:52.000Z
/* * VS_TextureInternal.cpp * VectorStorm * * Created by Trevor Powell on 3/08/08. * Copyright 2009 Trevor Powell. All rights reserved. * */ #include "VS_TextureInternal.h" #include "VS_Color.h" #include "VS_FloatImage.h" #include "VS_Image.h" #include "VS_HalfIntImage.h" #include "VS_HalfFloatImage.h" #include "VS_RenderTarget.h" #include "VS_RenderBuffer.h" #include "VS/Files/VS_File.h" #include "VS/Memory/VS_Store.h" #include "VS_OpenGL.h" #if TARGET_OS_IPHONE #include "VS_TextureInternalIPhone.h" vsTextureInternal::vsTextureInternal( const vsString &filename_in ): vsResource(filename_in), m_texture(0), m_premultipliedAlpha(true), m_tbo(NULL), m_renderTarget(NULL), m_surfaceBuffer(0) { vsString filename = vsFile::GetFullFilename(filename_in); m_texture = ::loadTexture( filename.c_str() ); m_nearestSampling = false; } vsTextureInternal::vsTextureInternal( const vsString &name, vsImage *maker ): vsResource(name), m_texture(0), m_premultipliedAlpha(true), m_tbo(NULL), m_renderTarget(NULL), m_surfaceBuffer(0) { m_nearestSampling = false; } vsTextureInternal::vsTextureInternal( const vsString &name, vsFloatImage *image ): vsResource(name), m_texture(0), m_premultipliedAlpha(true), m_tbo(NULL), m_renderTarget(NULL), m_surfaceBuffer(0) { m_nearestSampling = false; } vsTextureInternal::vsTextureInternal( const vsString &name, vsHalfFloatImage *image ): vsResource(name), m_texture(0), m_premultipliedAlpha(true), m_tbo(NULL), m_renderTarget(NULL), m_surfaceBuffer(0) { m_nearestSampling = false; } vsTextureInternal::vsTextureInternal( const vsString &name, vsSurface *surface, bool depth ): vsResource(name), m_texture(0), m_premultipliedAlpha(true), m_tbo(NULL), m_renderTarget(NULL), m_surfaceBuffer(0) { if ( surface ) m_texture = (depth) ? surface->m_depth : surface->m_texture; m_nearestSampling = false; } vsTextureInternal::vsTextureInternal( const vsString &name, vsRenderBuffer *buffer ): vsResource(name), m_texture(0), m_premultipliedAlpha(false), m_tbo(buffer), m_renderTarget(NULL), m_surfaceBuffer(0) { GLuint t; glGenTextures(1, &t); m_texture = t; m_nearestSampling = false; } vsTextureInternal::~vsTextureInternal() { GLuint t = m_texture; glDeleteTextures(1, &t); m_texture = 0; vsDelete( m_tbo ); m_renderTarget = NULL; } #else // TARGET_OS_IPHONE void vsTextureInternal::PrepareToBind() { if ( m_renderTarget ) { if ( IsDepth() ) m_renderTarget->ResolveDepth(); else m_renderTarget->Resolve(m_surfaceBuffer); } } /* Quick utility function for texture creation */ void vsTextureInternal::SetRenderTarget( vsRenderTarget* renderTarget, int surfaceBuffer, bool depth ) { // to be used for deferred texture creation (We went through the vsSurface // constructor with a NULL argument; now we're providing the surface) m_renderTarget = renderTarget; m_surfaceBuffer = surfaceBuffer; vsSurface *surface = renderTarget->GetTextureSurface(); if ( surface ) { m_texture = (depth) ? surface->m_depth : surface->m_texture[surfaceBuffer]; m_glTextureWidth = surface->m_width; m_glTextureHeight = surface->m_height; m_width = surface->m_width; m_height = surface->m_height; if ( m_nearestSampling ) SetNearestSampling(); } } vsTextureInternal::vsTextureInternal( const vsString &filename_in ): vsResource(filename_in), m_texture(0), m_depth(false), m_premultipliedAlpha(false), m_tbo(NULL), m_renderTarget(NULL), m_surfaceBuffer(0) { vsImage image(filename_in); if ( image.IsOK() ) { int w = image.GetWidth(); int h = image.GetHeight(); m_width = w; m_height = w; GLuint t; glGenTextures(1, &t); m_texture = t; glBindTexture(GL_TEXTURE_2D, m_texture); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, w, h, 0, GL_RGBA, GL_UNSIGNED_INT_8_8_8_8_REV, image.RawData()); glGenerateMipmap(GL_TEXTURE_2D); m_nearestSampling = false; } } vsTextureInternal::vsTextureInternal( const vsString&name, const vsArray<vsString> &mipmaps ): vsResource(name), m_texture(0), m_depth(false), m_premultipliedAlpha(false), m_tbo(NULL), m_renderTarget(NULL), m_surfaceBuffer(0) { GLuint t; glGenTextures(1, &t); m_texture = t; glBindTexture(GL_TEXTURE_2D, m_texture); for ( int i = 0; i < mipmaps.ItemCount(); i++ ) { vsImage image(mipmaps[i]); int w = image.GetWidth(); int h = image.GetHeight(); m_width = w; m_height = w; glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); glTexImage2D(GL_TEXTURE_2D, i, GL_RGBA, w, h, 0, GL_RGBA, GL_UNSIGNED_INT_8_8_8_8_REV, image.RawData()); } glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); // Anisotropic filtering didn't become part of OpenGL core contextx until // OpenGL 4.6 (!!), so.. we sort of still have to explicitly check for // support. Blah!! if ( GL_EXT_texture_filter_anisotropic ) { float aniso = 0.0f; glGetFloatv(GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT, &aniso); aniso = vsMin(aniso,9); glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, aniso); } } vsTextureInternal::vsTextureInternal( const vsString &name, vsImage *image ): vsResource(name), m_texture(0), m_depth(false), m_premultipliedAlpha(false), m_tbo(NULL), m_renderTarget(NULL), m_surfaceBuffer(0) { int w = image->GetWidth(); int h = image->GetHeight(); m_width = w; m_height = w; GLuint t; glGenTextures(1, &t); m_texture = t; glBindTexture(GL_TEXTURE_2D, m_texture); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, w, h, 0, GL_RGBA, GL_UNSIGNED_INT_8_8_8_8_REV, image->RawData()); glGenerateMipmap(GL_TEXTURE_2D); m_nearestSampling = false; } vsTextureInternal::vsTextureInternal( const vsString &name, vsFloatImage *image ): vsResource(name), m_texture(0), m_depth(false), m_premultipliedAlpha(false), m_tbo(NULL), m_renderTarget(NULL), m_surfaceBuffer(0) { int w = image->GetWidth(); int h = image->GetHeight(); m_width = w; m_height = w; GLuint t; glGenTextures(1, &t); m_texture = t; glBindTexture(GL_TEXTURE_2D, m_texture); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA32F, w, h, 0, GL_RGBA, GL_FLOAT, image->RawData()); glGenerateMipmap(GL_TEXTURE_2D); m_nearestSampling = false; } vsTextureInternal::vsTextureInternal( const vsString &name, vsHalfIntImage *image ): vsResource(name), m_texture(0), m_depth(false), m_premultipliedAlpha(false), m_tbo(NULL), m_renderTarget(NULL), m_surfaceBuffer(0) { int w = image->GetWidth(); int h = image->GetHeight(); m_width = w; m_height = w; GLuint t; glGenTextures(1, &t); m_texture = t; glBindTexture(GL_TEXTURE_2D, m_texture); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, 0); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA16UI, w, h, 0, GL_RGBA_INTEGER, GL_UNSIGNED_SHORT, image->RawData()); m_nearestSampling = false; } vsTextureInternal::vsTextureInternal( const vsString &name, vsHalfFloatImage *image ): vsResource(name), m_texture(0), m_depth(false), m_premultipliedAlpha(false), m_tbo(NULL), m_renderTarget(NULL), m_surfaceBuffer(0) { int w = image->GetWidth(); int h = image->GetHeight(); m_width = w; m_height = w; GLuint t; glGenTextures(1, &t); m_texture = t; glBindTexture(GL_TEXTURE_2D, m_texture); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, 0); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA16F, w, h, 0, GL_RGBA, GL_HALF_FLOAT, image->RawData()); m_nearestSampling = false; } vsTextureInternal::vsTextureInternal( const vsString &name, vsRenderBuffer *buffer ): vsResource(name), m_texture(0), m_premultipliedAlpha(false), m_tbo(buffer), m_renderTarget(NULL), m_surfaceBuffer(0) { GLuint t; glGenTextures(1, &t); m_texture = t; m_nearestSampling = false; } vsTextureInternal::vsTextureInternal( const vsString &name, uint32_t glTextureId ): vsResource(name), m_texture(glTextureId), m_premultipliedAlpha(false), m_tbo(NULL), m_renderTarget(NULL), m_surfaceBuffer(0) { m_nearestSampling = false; } void vsTextureInternal::Blit( vsImage *image, const vsVector2D &where) { glBindTexture(GL_TEXTURE_2D, m_texture); glTexSubImage2D(GL_TEXTURE_2D, 0, (int)where.x, (int)where.y, image->GetWidth(), image->GetHeight(), GL_RGBA, GL_UNSIGNED_INT_8_8_8_8_REV, image->RawData()); glGenerateMipmap(GL_TEXTURE_2D); } void vsTextureInternal::Blit( vsFloatImage *image, const vsVector2D &where) { glBindTexture(GL_TEXTURE_2D, m_texture); glTexSubImage2D(GL_TEXTURE_2D, 0, (int)where.x, (int)where.y, image->GetWidth(), image->GetHeight(), GL_RGBA, GL_FLOAT, image->RawData()); glGenerateMipmap(GL_TEXTURE_2D); } vsTextureInternal::vsTextureInternal( const vsString &name, vsRenderTarget *renderTarget, int surfaceBuffer, bool depth ): vsResource(name), m_texture(0), m_glTextureWidth(0), m_glTextureHeight(0), m_width(0), m_height(0), m_depth(depth), m_premultipliedAlpha(true), m_tbo(NULL), m_renderTarget(NULL), m_surfaceBuffer(0) { if ( renderTarget && renderTarget->GetTextureSurface() ) { SetRenderTarget(renderTarget, surfaceBuffer, depth); } m_nearestSampling = false; } vsTextureInternal::~vsTextureInternal() { GLuint t = m_texture; glDeleteTextures(1, &t); m_texture = 0; vsDelete( m_tbo ); m_renderTarget = NULL; // this doesn't belong to us; don't destroy it! } void vsTextureInternal::SetNearestSampling() { glBindTexture(GL_TEXTURE_2D, m_texture); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); m_nearestSampling = true; } void vsTextureInternal::SetLinearSampling(bool linearMipmaps) { glBindTexture(GL_TEXTURE_2D, m_texture); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); if ( linearMipmaps ) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); else glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); m_nearestSampling = false; } #endif // TARGET_OS_IPHONE uint32_t vsTextureInternal::ScaleColour(uint32_t ini, float amt) { char r = (ini & 0x000000FF); char g = (ini & 0x0000FF00) >> 8; char b = (ini & 0x00FF0000) >> 16; char a = (ini & 0xFF000000) >> 24; r = (char)(r * amt); g = (char)(g * amt); b = (char)(b * amt); a = (char)(a * amt); uint32_t result = (r & 0x000000FF) | ((g << 8) & 0x0000FF00) | ((b << 16) & 0x00FF0000) | ((a << 24) & 0xFF000000); return result; } uint32_t vsTextureInternal::SafeAddColour(uint32_t acolour, uint32_t bcolour) { int ra = (acolour & 0x000000FF); int ga = (acolour & 0x0000FF00) >> 8; int ba = (acolour & 0x00FF0000) >> 16; int aa = (acolour & 0xFF000000) >> 24; int rb = (bcolour & 0x000000FF); int gb = (bcolour & 0x0000FF00) >> 8; int bb = (bcolour & 0x00FF0000) >> 16; int ab = (bcolour & 0xFF000000) >> 24; int r = vsMin( ra + rb, 0xFF ); int g = vsMin( ga + gb, 0xFF ); int b = vsMin( ba + bb, 0xFF ); int a = vsMin( aa + ab, 0xFF ); uint32_t result = (r & 0x000000FF) | ((g << 8) & 0x0000FF00) | ((b << 16) & 0x00FF0000) | ((a << 24) & 0xFF000000); return result; } void vsTextureInternal::ClampUV( bool u, bool v ) { glBindTexture(GL_TEXTURE_2D, m_texture); glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, u ? GL_CLAMP_TO_EDGE : GL_REPEAT ); glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, v ? GL_CLAMP_TO_EDGE : GL_REPEAT ); }
22.723247
122
0.732543
vectorstorm
48448f9efd2e96c394fd1a77cd8ecdc53972eebb
319
hpp
C++
examples/publisher_transformer_subscriber/string_publisher.hpp
ManuelMeraz/flow
e9cf18dfc633bd9670e012a48595a1f931fcac79
[ "BSD-3-Clause" ]
3
2021-01-05T16:12:08.000Z
2021-01-12T21:44:10.000Z
examples/publisher_transformer_subscriber/string_publisher.hpp
RoboSDK/Flow
e9cf18dfc633bd9670e012a48595a1f931fcac79
[ "BSD-3-Clause" ]
9
2020-10-06T23:53:39.000Z
2021-01-23T00:41:39.000Z
examples/publisher_transformer_subscriber/string_publisher.hpp
RoboSDK/Flow
e9cf18dfc633bd9670e012a48595a1f931fcac79
[ "BSD-3-Clause" ]
null
null
null
#pragma once #include <flow/publisher.hpp> #include <spdlog/spdlog.h> namespace example { class string_publisher { public: std::string operator()() { spdlog::info("Producing Hello World string!"); return "Hello World!"; } std::string publish_to() { return "hello_world"; }; }; }// namespace example
16.789474
53
0.677116
ManuelMeraz
484dde96e9de72bdd23d2f17e6eb641ee184be83
1,223
hpp
C++
include/Keybinding.hpp
DangerInteractive/ArcticWolf
74999f00cb4ef44f358bea1df266967cd1e7ed6c
[ "MIT" ]
null
null
null
include/Keybinding.hpp
DangerInteractive/ArcticWolf
74999f00cb4ef44f358bea1df266967cd1e7ed6c
[ "MIT" ]
null
null
null
include/Keybinding.hpp
DangerInteractive/ArcticWolf
74999f00cb4ef44f358bea1df266967cd1e7ed6c
[ "MIT" ]
null
null
null
#ifndef H_AW_KEYBINDING #define H_AW_KEYBINDING #include <vector> #include <functional> #include <SFML/Window.hpp> namespace aw { class Keybinding { public: typedef std::function <void()> KeybindingCallback; Keybinding (const KeybindingCallback&, bool, sf::Keyboard::Key, bool, bool, bool); ~Keybinding () = default; Keybinding (Keybinding&&) = default; Keybinding& operator = (Keybinding&&) = default; Keybinding (const Keybinding&) = default; Keybinding& operator = (const Keybinding&) = default; bool check (bool, sf::Keyboard::Key, bool, bool, bool) const; void process (bool, sf::Keyboard::Key, bool, bool, bool); const KeybindingCallback& getCallback () const; bool getAction () const; sf::Keyboard::Key getKey () const; bool getAlt () const; bool getControl () const; bool getShift () const; void setCallback (const KeybindingCallback&); void setAction (bool); void setKey (sf::Keyboard::Key); void setAlt (bool); void setControl (bool); void setShift (bool); private: KeybindingCallback m_callback; bool m_action; sf::Keyboard::Key m_key; bool m_alt; bool m_control; bool m_shift; }; } #endif
22.648148
86
0.6713
DangerInteractive
48520d2a6ff5106755db288823bef13e0dec8ccf
2,236
cpp
C++
Editor/Code/EntityManager.cpp
Negawisp/GameEnginePractice-2021
367768cdf43e15df194fa6691acba3fac6ef12ad
[ "MIT" ]
null
null
null
Editor/Code/EntityManager.cpp
Negawisp/GameEnginePractice-2021
367768cdf43e15df194fa6691acba3fac6ef12ad
[ "MIT" ]
null
null
null
Editor/Code/EntityManager.cpp
Negawisp/GameEnginePractice-2021
367768cdf43e15df194fa6691acba3fac6ef12ad
[ "MIT" ]
null
null
null
#include "EntityManager.h" EntityManager::EntityManager(RenderEngine* pRenderEngine, EditorSystem* pEditorSystem, ScriptSystem* pScriptSystem, flecs::world* ecs) : m_pRenderEngine(pRenderEngine), m_pEditorSystem(pEditorSystem), m_pEcs(ecs), m_pScriptSystem(pScriptSystem) { } EntityManager::~EntityManager() { m_entityQueue.clear(); } void EntityManager::CreateEntity(std::string strScriptName) { flecs::entity newEntity = m_pEcs->entity(); uint32_t nIndex = GetNewIndex(); ScriptNode* pScriptNode = m_pScriptSystem->CreateScriptNode(strScriptName, newEntity); Ogre::String strMeshName = pScriptNode->GetMeshName(); RenderNode* pRenderNode = new RenderNode(nIndex, strMeshName); newEntity.set(EntityIndex{ nIndex }) .set(RenderNodeComponent{ pRenderNode }) .set(ScriptNodeComponent{ pScriptNode }); m_pRenderEngine->GetRT()->RC_CreateSceneNode(pRenderNode); Entity entity; entity.pRenderNode = pRenderNode; entity.pScriptNode = pScriptNode; entity.idx = nIndex; m_entityQueue[nIndex] = entity; } void EntityManager::CreateEntity(const EntityInfo &fromSave) { flecs::entity newEntity = m_pEcs->entity(); uint32_t nIndex = GetNewIndex(); EditorNode* pEditorNode = m_pEditorSystem->CreateNode(fromSave, nIndex, newEntity); ScriptNode* pScriptNode = m_pScriptSystem->CreateScriptNode(fromSave.scriptName, newEntity); pScriptNode->SetPosition(fromSave.position); pScriptNode->SetOrientation(fromSave.rotation); Ogre::String strEnityName = fromSave.entityName; Ogre::String strMeshName = fromSave.meshName; RenderNode* pRenderNode = new RenderNode(nIndex, strMeshName); newEntity.set(EntityIndex{ nIndex }) .set(RenderNodeComponent{ pRenderNode }) .set(EditorNodeComponent{ pEditorNode }) .set(ScriptNodeComponent{ pScriptNode }); m_pRenderEngine->GetRT()->RC_CreateSceneNode(pRenderNode); Entity entity; entity.idx = nIndex; entity.entityName = strEnityName; entity.pEditorNode = pEditorNode; entity.pRenderNode = pRenderNode; entity.pScriptNode = pScriptNode; m_entityQueue[nIndex] = entity; } uint32_t EntityManager::GetNewIndex() const { return m_entityQueue.size(); } std::unordered_map<uint32_t, Entity> EntityManager::GetEntityQueue() const { return m_entityQueue; }
27.268293
136
0.780859
Negawisp
48552f2a2ff3689b70b88b5ae5b11add416e6fd5
1,288
cpp
C++
src/threadinterrupt.cpp
yinchengtsinghua/BitCoinCppChinese
76f64ad8cee5b6c5671b3629f39e7ae4ef84be0a
[ "MIT" ]
13
2019-01-23T04:36:05.000Z
2022-02-21T11:20:25.000Z
src/threadinterrupt.cpp
yinchengtsinghua/BitCoinCppChinese
76f64ad8cee5b6c5671b3629f39e7ae4ef84be0a
[ "MIT" ]
null
null
null
src/threadinterrupt.cpp
yinchengtsinghua/BitCoinCppChinese
76f64ad8cee5b6c5671b3629f39e7ae4ef84be0a
[ "MIT" ]
3
2019-01-24T07:48:15.000Z
2021-06-11T13:34:44.000Z
//此源码被清华学神尹成大魔王专业翻译分析并修改 //尹成QQ77025077 //尹成微信18510341407 //尹成所在QQ群721929980 //尹成邮箱 [email protected] //尹成毕业于清华大学,微软区块链领域全球最有价值专家 //https://mvp.microsoft.com/zh-cn/PublicProfile/4033620 //版权所有(c)2009-2010 Satoshi Nakamoto //版权所有(c)2009-2018比特币核心开发者 //根据MIT软件许可证分发,请参见随附的 //文件复制或http://www.opensource.org/licenses/mit-license.php。 #include <threadinterrupt.h> #include <sync.h> CThreadInterrupt::CThreadInterrupt() : flag(false) {} CThreadInterrupt::operator bool() const { return flag.load(std::memory_order_acquire); } void CThreadInterrupt::reset() { flag.store(false, std::memory_order_release); } void CThreadInterrupt::operator()() { { LOCK(mut); flag.store(true, std::memory_order_release); } cond.notify_all(); } bool CThreadInterrupt::sleep_for(std::chrono::milliseconds rel_time) { WAIT_LOCK(mut, lock); return !cond.wait_for(lock, rel_time, [this]() { return flag.load(std::memory_order_acquire); }); } bool CThreadInterrupt::sleep_for(std::chrono::seconds rel_time) { return sleep_for(std::chrono::duration_cast<std::chrono::milliseconds>(rel_time)); } bool CThreadInterrupt::sleep_for(std::chrono::minutes rel_time) { return sleep_for(std::chrono::duration_cast<std::chrono::milliseconds>(rel_time)); }
23.851852
101
0.737578
yinchengtsinghua
4858df62263f0cb9b3b2f3e516f30fc13f39ab3d
9,595
cpp
C++
src/landing-aruco.cpp
alanprodam/Filters-VO
ecb177d7b7cb3149b831d3b62545ec54e3e53f16
[ "MIT" ]
null
null
null
src/landing-aruco.cpp
alanprodam/Filters-VO
ecb177d7b7cb3149b831d3b62545ec54e3e53f16
[ "MIT" ]
null
null
null
src/landing-aruco.cpp
alanprodam/Filters-VO
ecb177d7b7cb3149b831d3b62545ec54e3e53f16
[ "MIT" ]
null
null
null
#include "opencv2/core.hpp" #include "opencv2/imgcodecs.hpp" #include "opencv2/imgproc/imgproc.hpp" #include "opencv2/highgui/highgui.hpp" #include "opencv2/aruco.hpp" #include "opencv2/aruco/dictionary.hpp" #include "opencv2/calib3d/calib3d.hpp" #include "opencv2/video/tracking.hpp" #include "opencv2/features2d/features2d.hpp" #include <vector> #include <sstream> #include <iostream> #include <fstream> #include <ctype.h> #include <algorithm> #include <iterator> #include <ctime> #include <string> #include <stdio.h> using namespace std; using namespace cv; // 2.6 cm - 26 mm - 0.026 m const float calibrationSquareDimension = 0.026f; //meters // 13.2 cm - 132 mm - 0.132 m // 33.9 cm - 339 mm - 0.339 m const float arucoSquareDimensionMaior = 0.339f; //meters // 7.9 cm - 79 mm - 0.079 m const float arucoSquareDimensionMenor = 0.079f; //meters // dimension of cheesboard const Size chessboardDimensions = Size(6,9); //default capture width and height const int FRAME_WIDTH = 640; const int FRAME_HEIGHT = 480; //initial min and max THRESHOLD filter values //our sensitivity value to be used in the threshold() function //these will be changed using trackbars int THRESHOLD_MIN = 220; int THRESHOLD_MAX = 256; int BLUR_SIZE = 5; int DILATATION = 2; int ERODE = 2; //diameter of circle is 54 cm const float DIAMETER = 54; // focal distance const float FOCO = 675; void on_trackbar(int, void *) { //This function gets called whenever a // trackbar position is changed } //int to string helper function string intToString(int number) { //this function has a number input and string output std::stringstream ss; ss << number; return ss.str(); } //float to string helper function string floatToString(float number) { //this function has a number input and string output std::stringstream ss; ss << number; return ss.str(); } string doubleToString(double number) { //this function has a number input and string output std::stringstream ss; ss << number; return ss.str(); } float distanceLandmarck(int &radius) { // f = foco(taxa de transformação); x = diâmetro(pixels); // Z = distáncia entre câmera(altura) = landmark(centimetros); X = diâmetro do landmark(centimetros) // Z = (X * f) / x; // diâmetro circulo em pixels float pixelDiametro = radius * 2; // f(24) = 672 f(20) = 680 f(54) = 675 float altura = (DIAMETER * FOCO) / pixelDiametro; return altura; } // calcular distancias(x,y) do mundo real entre landmark e o frame do drone float *positionCenter(float &xLandmark, float &yLandmark, float &altura) { float px = xLandmark - FRAME_WIDTH / 2; float py = yLandmark - FRAME_HEIGHT / 2; float *out = (float *)calloc(2, sizeof(float)); // contastane k que relaciona diametro com a quantidade de pixels Z/f ou X/x float k = altura / FOCO; out[0] = px * k; out[1] = py * k; return out; } void searchForCircule(Mat &thresholdImage, Mat &cameraFeed) { vector<Vec3f> circles; HoughCircles(thresholdImage, circles, HOUGH_GRADIENT, 1.4, thresholdImage.rows / 2, // change this value to detect circles with different distances to each other 100, 100, 0, 0 // change the last two parameters // (min_radius & max_radius) to detect larger circles ); //cout << "size circulo " << circles.size() << endl; if (circles.size() == 1) { for (size_t i = 0; i < circles.size(); i++) { Point center(cvRound(circles[i][0]), cvRound(circles[i][1])); int radius = cvRound(circles[i][2]); float Xc = cvRound(circles[i][0]); float Yc = cvRound(circles[i][1]); float Altura = distanceLandmarck(radius); // converction cm to mm Altura = Altura * 10; float *direction = positionCenter(Xc, Yc, Altura); // converction to meters Altura = Altura / 1000; // circle center circle(cameraFeed, center, 3, Scalar(0, 255, 0), -1, 8, 0); // circle outline circle(cameraFeed, center, radius, Scalar(0, 0, 255), 3, 8, 0); putText(cameraFeed, "Tracking first aim at (" + intToString(cvRound(circles[i][0])) + "pixel , " + intToString(cvRound(circles[i][1])) + "pixel )", Point(10, 20), 1.2, 1.2, Scalar(255, 0, 0), 2); putText(cameraFeed, "Altitude: " + doubleToString(Altura) + " m", Point(10, 50), 1.2, 1.2, Scalar(0, 0, 255), 2); putText(cameraFeed, "Correction coordinates (" + floatToString(cvRound(direction[0])) + "mm , " + floatToString(cvRound(direction[1])) + "mm )", Point(10, 80), 1.2, 1.2, Scalar(0, 255, 0), 2); putText(cameraFeed, "X", Point(FRAME_WIDTH / 2, FRAME_HEIGHT / 2), 1.2, 1.2, Scalar(0, 0, 255), 2); // Vec3i c = circles[i]; // circle(cameraFeed, Point(c[0], c[1]), c[2], Scalar(0, 0, 255), 3, LINE_AA); // circle(cameraFeed, Point(c[0], c[1]), 2, Scalar(0, 255, 0), 3, LINE_AA); } // realizar o processo para identificar sempre o maior circulo para calculo da altura // associar os circulos (diametro pixels) com suas respectivas distancias // altura próxima de 1 m baixar o threshold // achar triangulo para encontrar orientação (por angulos em relação ao quadrado) } } bool loadCameraCalibration(Mat& cameraMatrix, Mat& distanceCoefficients) { ifstream myfile; myfile.open("calibrationFile(smartphone).txt"); if (myfile.is_open()) { uint16_t rows; uint16_t columns; myfile >> rows; myfile >> columns; cameraMatrix = Mat(Size(columns, rows), CV_64F); for (int r = 0; r < rows; r++) { for (int c = 0; c < columns; c++) { double read = 0.0f; myfile >> read; cameraMatrix.at<double>(r, c) = read; //cout << cameraMatrix.at<double>(r, c) << endl; } } //Distance Coefficients myfile >> rows; myfile >> columns; distanceCoefficients = Mat(Size(columns, rows), CV_64F); for (int r = 0; r < rows; r++) { for (int c = 0; c < columns; c++) { double read = 0.0f; myfile >> read; distanceCoefficients.at<double>(r, c) = read; //cout << distanceCoefficients.at<double>(r, c) << endl; } } myfile.close(); return true; } return false; } int startWebcamMonitoring(Mat& cameraMatrix, Mat& distanceCoefficients, float arucoSquareDimension) { Mat frame, frameCopy; vector<int> markerIds; vector<vector<Point2f > > markerCorners, rejectedCandidates; aruco::DetectorParameters parameters; Ptr<aruco::Dictionary> markerDictionary = aruco::getPredefinedDictionary(aruco::DICT_4X4_1000); VideoCapture video(1); vector<Vec3d> rotationVectors, translationVectors; // visualizar parametros intrinsecos da camera for (int r = 0; r < cameraMatrix.rows; r++) { for (int c = 0; c < cameraMatrix.cols; c++) { cout << cameraMatrix.at<double>(r, c) << endl; } } // visualizar distorções da camera for (int r = 0; r < distanceCoefficients.rows; r++) { for (int c = 0; c < distanceCoefficients.cols; c++) { cout << distanceCoefficients.at<double>(r, c) << endl; } } namedWindow("WebCam Aruco", CV_WINDOW_NORMAL); while (1) { video.open("/home/alantavares/Datasets/indoor_HD_1920.mp4"); if (!video.isOpened()) { cout << "ERROR ACQUIRING VIDEO FEED" << endl; getchar(); return -1; } else{ cout << "CORRECT ACQUIRING VIDEO FEED" << endl; } //check if the video has reach its last frame. //we add '-1' because we are reading two frames from the video at a time. //if this is not included, we get a memory error! while (video.get(CV_CAP_PROP_POS_FRAMES) < video.get(CV_CAP_PROP_FRAME_COUNT) - 1) { //read first frame video.read(frame); frame.copyTo(frameCopy); aruco::detectMarkers(frame, markerDictionary, markerCorners, markerIds); aruco::estimatePoseSingleMarkers(markerCorners, arucoSquareDimension, cameraMatrix, distanceCoefficients, rotationVectors, translationVectors); //cout << "markerIds: " << markerIds.size() << endl; for (int i = 0; i < markerIds.size(); i++) { //cout << "markerCorners: " << markerCorners.at<Point2f> << endl; aruco::drawDetectedMarkers(frame, markerCorners, markerIds); aruco::drawAxis(frame, cameraMatrix, distanceCoefficients, rotationVectors[i], translationVectors[i], 0.1f); } //***************************************************************** // //thresholded difference image (for use in findContours() function) // Mat thresholdImage, grayImage; // //convert frame1 to gray scale for frame differencing // cvtColor(frameCopy, grayImage, COLOR_BGR2GRAY); // //threshold intensity image at a given sensitivity value // threshold(grayImage, thresholdImage, THRESHOLD_MIN, THRESHOLD_MAX, THRESH_BINARY); // //use blur() to smooth the image, remove possible noise and // blur(thresholdImage, thresholdImage, Size(BLUR_SIZE, BLUR_SIZE)); // searchForCircule(thresholdImage,frame); imshow("WebCam Aruco", frame); if (waitKey(1) >= 0) { break; } } return 1; } } int main(int argc, char const *argv[]) { Mat cameraMatrix = Mat::eye(3, 3, CV_64F); Mat distanceCoefficients; loadCameraCalibration(cameraMatrix, distanceCoefficients); startWebcamMonitoring(cameraMatrix, distanceCoefficients, arucoSquareDimensionMaior); return 0; }
28.47181
153
0.642001
alanprodam
485a83cf0a500058b73ecf8893830d9c71894a58
417
cpp
C++
modules/image/vendor/stb.cpp
lenamueller/glpp
f7d29e5924537fd405a5bb409d67e65efdde8d9e
[ "MIT" ]
16
2019-12-10T19:44:17.000Z
2022-01-04T03:16:19.000Z
modules/image/vendor/stb.cpp
lenamueller/glpp
f7d29e5924537fd405a5bb409d67e65efdde8d9e
[ "MIT" ]
null
null
null
modules/image/vendor/stb.cpp
lenamueller/glpp
f7d29e5924537fd405a5bb409d67e65efdde8d9e
[ "MIT" ]
3
2021-06-04T21:56:55.000Z
2022-03-03T06:47:56.000Z
#pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wsign-compare" #pragma GCC diagnostic ignored "-Wunused-but-set-variable" #pragma GCC diagnostic ignored "-Wmissing-field-initializers" #define STB_IMAGE_IMPLEMENTATION #include "stb_image.h" #undef STB_IMAGE_IMPLEMENTATION #define STB_IMAGE_WRITE_IMPLEMENTATION #include "stb_image_write.h" #undef STB_IMAGE_WRITE_IMPLEMENTATION #pragma GCC diagnostic pop
37.909091
61
0.841727
lenamueller
485c58814be7293221cd4d7d77617cd22764ae9a
707
cpp
C++
linked_list/leetcode_linked_list/160_intersection_of_two_linked_lists.cpp
Hadleyhzy/data_structure_and_algorithm
0e610ba78dcb216323d9434a0f182756780ce5c0
[ "MIT" ]
1
2020-10-12T19:18:19.000Z
2020-10-12T19:18:19.000Z
linked_list/leetcode_linked_list/160_intersection_of_two_linked_lists.cpp
Hadleyhzy/data_structure_and_algorithm
0e610ba78dcb216323d9434a0f182756780ce5c0
[ "MIT" ]
null
null
null
linked_list/leetcode_linked_list/160_intersection_of_two_linked_lists.cpp
Hadleyhzy/data_structure_and_algorithm
0e610ba78dcb216323d9434a0f182756780ce5c0
[ "MIT" ]
1
2020-10-12T19:18:04.000Z
2020-10-12T19:18:04.000Z
// // 160_intersection_of_two_linked_lists.cpp // leetcode_linked_list // // Created by Hadley on 25.09.20. // Copyright © 2020 Hadley. All rights reserved. // #include <stdio.h> #include <vector> #include <unordered_set> #include <unordered_map> #include "83_Remove_duplicats_from_sorted_list.cpp" using namespace std; class Solution { public: ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) { unordered_map<ListNode*,int>map; while(headA){ map[headA]++; headA=headA->next; } while(headB){ map[headB]++; if(map[headB]==2)break; headB=headB->next; } return headB; } };
22.09375
69
0.618105
Hadleyhzy
485e7897324f471024044742b871a41222a2b572
4,234
cpp
C++
src/engine/gen/FlowField.cpp
Eothaun/Eyos
adc63fa9051aa5c2e61250307c0cdcefbc9b6c06
[ "MIT" ]
8
2019-12-08T23:37:13.000Z
2021-10-04T06:14:00.000Z
src/engine/gen/FlowField.cpp
Eothaun/Eyos
adc63fa9051aa5c2e61250307c0cdcefbc9b6c06
[ "MIT" ]
null
null
null
src/engine/gen/FlowField.cpp
Eothaun/Eyos
adc63fa9051aa5c2e61250307c0cdcefbc9b6c06
[ "MIT" ]
1
2019-12-31T02:44:01.000Z
2019-12-31T02:44:01.000Z
#include "engine/gen/FlowField.h" FlowField::FlowField() { dijkstraGrid = std::vector<std::vector<node>>(gridWidth); } FlowField::~FlowField() { } void FlowField::GenerateFlowField() { GenerateDijkstraGrid(std::vector<glm::vec2>{ {2, 4}, { 5,6 }}); int x, y; std::vector<std::vector<glm::vec2>> flowField(gridWidth); for (x = 0; x < gridWidth; x++) { std::vector<glm::vec2> arr(gridHeight); for (y = 0; y < gridHeight; y++) { arr[y] = glm::vec2(0,0); } flowField[x] = arr; } for (x = 0; x < gridWidth; x++) { for (y = 0; y < gridHeight; y++) { if (dijkstraGrid[x][y].weight == INT_MAX) { continue; } std::vector neighbours = AllNeighboursOf(dijkstraGrid[x][y]); node min = node(); float minDist = 0; for (int i = 0; i < neighbours.size(); i++) { node n = neighbours[i]; float dist = dijkstraGrid[n.pos.x][n.pos.y].weight - dijkstraGrid[x][y].weight; //if (i == 0) minDist = dist; //if (dist < minDist) // minDist = dist; if (dist < minDist) { n.distance = dist; min = n; minDist = dist; } } //if valid neightbour point in its direction if (min.distance != 0) { flowField[x][y] = glm::normalize(min.pos - dijkstraGrid[x][y].pos); } } } } void FlowField::GenerateDijkstraGrid(std::vector<glm::vec2> obstacles) { int gridWidth = 10; int gridHeight = 10; for (int x = 0; x < gridWidth; x++) { std::vector<node> arr(gridHeight); for (int y = 0; y < gridHeight; y++) { arr[y].weight = 0; arr[y].pos = glm::vec2(x, y); arr[y].distance = 0; } dijkstraGrid[x] = arr; } //set all places with obstacles with weight of MAXINT for (int i = 0; i<obstacles.size(); i++) { glm::vec2 t = obstacles[i]; dijkstraGrid[t.x][t.y].weight = INT_MAX; } node pathEnd; pathEnd.distance = 0; pathEnd.pos = { 2,4 }; pathEnd.weight = 0; dijkstraGrid[pathEnd.pos.x][pathEnd.pos.y].weight = 0; std::vector<node> toVisit{ pathEnd }; for (int i = 0; i < toVisit.size(); i++) { std::vector<node> neighbours = NeighboursOf(toVisit[i]); //for each neighbour of this node (only straight line neighbours) for (int j = 0; j < neighbours.size(); j++) { node n = neighbours[j]; if (dijkstraGrid[n.pos.x][n.pos.y].weight == 0) { n.distance = toVisit[i].distance + 1; dijkstraGrid[n.pos.x][n.pos.y].weight = n.distance; toVisit.push_back(n); } } } } //no diagonal neighbours std::vector<node> FlowField::NeighboursOf(node& neighbour) { std::vector<node> neighbours; if (neighbour.pos.x != gridWidth-1) neighbours.push_back(dijkstraGrid[(int)neighbour.pos.x + 1][neighbour.pos.y]); if (neighbour.pos.x != 0) neighbours.push_back(dijkstraGrid[(int)neighbour.pos.x - 1][neighbour.pos.y]); if (neighbour.pos.y != gridHeight-1) neighbours.push_back(dijkstraGrid[neighbour.pos.x][(int)neighbour.pos.y + 1]); if (neighbour.pos.y != 0)neighbours.push_back(dijkstraGrid[neighbour.pos.x][(int)neighbour.pos.y - 1]); return neighbours; } //all neighbours including diagonal std::vector<node> FlowField::AllNeighboursOf(node& neighbour) { std::vector<node> neighbours; if (neighbour.pos.x != gridWidth -1) neighbours.push_back(dijkstraGrid[(int)neighbour.pos.x + 1][neighbour.pos.y]); if(neighbour.pos.x != 0) neighbours.push_back(dijkstraGrid[(int)neighbour.pos.x - 1][neighbour.pos.y]); if (neighbour.pos.y != gridHeight -1) neighbours.push_back(dijkstraGrid[neighbour.pos.x][(int)neighbour.pos.y + 1]); if(neighbour.pos.y != 0 )neighbours.push_back(dijkstraGrid[neighbour.pos.x][(int)neighbour.pos.y - 1]); if (neighbour.pos.x != gridWidth - 1 && neighbour.pos.y != gridHeight -1) neighbours.push_back(dijkstraGrid[(int)neighbour.pos.x + 1][(int)neighbour.pos.y + 1]); if (neighbour.pos.x != 0 && neighbour.pos.y != 0) neighbours.push_back(dijkstraGrid[(int)neighbour.pos.x - 1][(int)neighbour.pos.y - 1]); if (neighbour.pos.y != gridHeight - 1 && neighbour.pos.x != 0) neighbours.push_back(dijkstraGrid[(int)neighbour.pos.x - 1][(int)neighbour.pos.y + 1]); if (neighbour.pos.y != 0 && neighbour.pos.x != gridWidth - 1)neighbours.push_back(dijkstraGrid[(int)neighbour.pos.x + 1][(int)neighbour.pos.y - 1]); return neighbours; }
27.493506
162
0.645253
Eothaun
4861bc5e8598ec7ae2279bff66213b13e006ec1b
836
cpp
C++
codeforces/1485A.cpp
sgrade/cpptest
84ade6ec03ea394d4a4489c7559d12b4799c0b62
[ "MIT" ]
null
null
null
codeforces/1485A.cpp
sgrade/cpptest
84ade6ec03ea394d4a4489c7559d12b4799c0b62
[ "MIT" ]
null
null
null
codeforces/1485A.cpp
sgrade/cpptest
84ade6ec03ea394d4a4489c7559d12b4799c0b62
[ "MIT" ]
null
null
null
// A. Add and Divide #include <iostream> #include <limits> using namespace std; int main() { int t; cin >> t; while(t--) { int a, b; cin >> a >> b; int ans = numeric_limits<int>::max(); bool b_is_one = false; if (b == 1) { b += 1; b_is_one = true; } // Explanation - https://www.youtube.com/watch?v=BzIc0ZwLvps int tmp, current_ans; for (int i = 0; i < 31; ++i) { tmp = a; current_ans = 0; if (b_is_one) { ++current_ans; } while (tmp != 0) { tmp /= (b + i); ++current_ans; } ans = min(ans, current_ans + i); } cout << ans << endl; } return 0; }
16.72
68
0.389952
sgrade
486768fc3c4659bb98f60b08d39a319baece52b2
8,095
cpp
C++
SMHasher/SpeedTest.cpp
Bulat-Ziganshin/FARSH
d74ef3a21cd4cde0a97639ec400f42c6169cca93
[ "MIT" ]
44
2015-05-29T14:37:31.000Z
2021-11-17T11:22:04.000Z
SMHasher/SpeedTest.cpp
Bulat-Ziganshin/FARSH
d74ef3a21cd4cde0a97639ec400f42c6169cca93
[ "MIT" ]
4
2016-06-28T12:34:31.000Z
2019-12-03T10:54:10.000Z
SMHasher/SpeedTest.cpp
Bulat-Ziganshin/FARSH
d74ef3a21cd4cde0a97639ec400f42c6169cca93
[ "MIT" ]
4
2016-08-09T08:51:46.000Z
2018-01-13T15:36:36.000Z
#include "SpeedTest.h" #include "Random.h" #include <stdio.h> // for printf #include <memory.h> // for memset #include <math.h> // for sqrt #include <algorithm> // for sort //----------------------------------------------------------------------------- // We view our timing values as a series of random variables V that has been // contaminated with occasional outliers due to cache misses, thread // preemption, etcetera. To filter out the outliers, we search for the largest // subset of V such that all its values are within three standard deviations // of the mean. double CalcMean ( std::vector<double> & v ) { double mean = 0; for(int i = 0; i < (int)v.size(); i++) { mean += v[i]; } mean /= double(v.size()); return mean; } double CalcMean ( std::vector<double> & v, int a, int b ) { double mean = 0; for(int i = a; i <= b; i++) { mean += v[i]; } mean /= (b-a+1); return mean; } double CalcStdv ( std::vector<double> & v, int a, int b ) { double mean = CalcMean(v,a,b); double stdv = 0; for(int i = a; i <= b; i++) { double x = v[i] - mean; stdv += x*x; } stdv = sqrt(stdv / (b-a+1)); return stdv; } // Return true if the largest value in v[0,len) is more than three // standard deviations from the mean bool ContainsOutlier ( std::vector<double> & v, size_t len ) { double mean = 0; for(size_t i = 0; i < len; i++) { mean += v[i]; } mean /= double(len); double stdv = 0; for(size_t i = 0; i < len; i++) { double x = v[i] - mean; stdv += x*x; } stdv = sqrt(stdv / double(len)); double cutoff = mean + stdv*3; return v[len-1] > cutoff; } // Do a binary search to find the largest subset of v that does not contain // outliers. void FilterOutliers ( std::vector<double> & v ) { std::sort(v.begin(),v.end()); size_t len = 0; for(size_t x = 0x40000000; x; x = x >> 1 ) { if((len | x) >= v.size()) continue; if(!ContainsOutlier(v,len | x)) { len |= x; } } v.resize(len); } // Iteratively tighten the set to find a subset that does not contain // outliers. I'm not positive this works correctly in all cases. void FilterOutliers2 ( std::vector<double> & v ) { std::sort(v.begin(),v.end()); int a = 0; int b = (int)(v.size() - 1); for(int i = 0; i < 10; i++) { //printf("%d %d\n",a,b); double mean = CalcMean(v,a,b); double stdv = CalcStdv(v,a,b); double cutA = mean - stdv*3; double cutB = mean + stdv*3; while((a < b) && (v[a] < cutA)) a++; while((b > a) && (v[b] > cutB)) b--; } std::vector<double> v2; v2.insert(v2.begin(),v.begin()+a,v.begin()+b+1); v.swap(v2); } //----------------------------------------------------------------------------- // We really want the rdtsc() calls to bracket the function call as tightly // as possible, but that's hard to do portably. We'll try and get as close as // possible by marking the function as NEVER_INLINE (to keep the optimizer from // moving it) and marking the timing variables as "volatile register". NEVER_INLINE int64_t timehash ( pfHash hash, int hashsize, const void * key, int len, int seed, const int repeats, bool measure_throughput ) { volatile register int64_t begin,end; uint32_t temp[16]; begin = rdtsc(); if (measure_throughput) { for(int i = 0; i < repeats; i++) { hash(key,len,seed,temp); } } else { // measure back-to-back latency switch (hashsize) { case 32: for(int i = 0; i < repeats; i++) { hash(key,len,seed,temp); seed = temp[0]; // ensure that new seed depends on ALL bits of hash result } break; case 64: for(int i = 0; i < repeats; i++) { hash(key,len,seed,temp); seed = (sizeof(size_t) == 4? temp[0] + temp[1] : (*(uint64_t*)temp >> 1)); } break; case 128: for(int i = 0; i < repeats; i++) { hash(key,len,seed,temp); seed = temp[0] + temp[1] + temp[2] + temp[3]; } break; case 256: for(int i = 0; i < repeats; i++) { hash(key,len,seed,temp); seed = temp[0]; for (int j=1; j < 256/32; j++) seed += temp[j]; } break; case 512: for(int i = 0; i < repeats; i++) { hash(key,len,seed,temp); seed = temp[0]; for (int j=1; j < 512/32; j++) seed += temp[j]; } break; } } end = rdtsc(); return end-begin; } //----------------------------------------------------------------------------- double SpeedTest ( pfHash hash, int hashsize, uint32_t seed, const int trials, const int repeats, const int blocksize, const int align, bool measure_throughput ) { Rand r(seed); uint8_t * buf = new uint8_t[blocksize + 512]; uint64_t t1 = reinterpret_cast<uint64_t>(buf); t1 = (t1 + 255) & BIG_CONSTANT(0xFFFFFFFFFFFFFF00); t1 += align; uint8_t * block = reinterpret_cast<uint8_t*>(t1); r.rand_p(block,blocksize); //---------- std::vector<double> times; times.reserve(trials); for(int itrial = 0; itrial < trials; itrial++) { r.rand_p(block,blocksize); double t = (double)timehash(hash,hashsize,block,blocksize,itrial,repeats,measure_throughput); if(t > 0) times.push_back(t); } //---------- std::sort(times.begin(),times.end()); FilterOutliers(times); delete [] buf; return CalcMean(times)/repeats; } //----------------------------------------------------------------------------- // 256k blocks seem to give the best results. void BulkSpeedTest ( pfHash hash, int hashsize, uint32_t seed ) { const int trials = 2999; const int repeats = 1; const int blocksize = 256 * 1024; const bool measure_throughput = true; printf("Bulk speed test - %d-byte keys\n",blocksize); for(int align = 0; align < 8; align++) { double cycles = SpeedTest(hash,hashsize,seed,trials,repeats,blocksize,align,measure_throughput); double bestbpc = double(blocksize)/cycles; double bestbps = (bestbpc * 3000000000.0 / 1048576.0); printf("Alignment %2d - %6.3f bytes/cycle - %7.2f MiB/sec @ 3 ghz\n",align,bestbpc,bestbps); } } //----------------------------------------------------------------------------- void TinySpeedTest ( pfHash hash, int hashsize, int max_keysize, uint32_t seed, bool verbose ) { const int trials = 1000; const int repeats = 1000; std::vector<double> cycles_latency(max_keysize+1); std::vector<double> cycles_throughput(max_keysize+1); printf("Small key speed test"); for (int i=0; i<10; i++) { if(verbose) printf("."); for(int keysize = 0; keysize <= max_keysize; keysize++) { double cycles; cycles = SpeedTest(hash,hashsize,seed,trials,repeats,keysize,0,false); if (i==0 || cycles < cycles_latency[keysize]) cycles_latency[keysize] = cycles; cycles = SpeedTest(hash,hashsize,seed,trials,repeats,keysize,0,true); if (i==0 || cycles < cycles_throughput[keysize]) cycles_throughput[keysize] = cycles; } } printf("\n"); for(int keysize = 0; keysize <= max_keysize; keysize++) { printf("%4d-byte keys - latency %8.2f cycles/hash, throughput %8.2f cycles/hash\n", keysize, cycles_latency[keysize], cycles_throughput[keysize]); } } //-----------------------------------------------------------------------------
25.455975
162
0.512786
Bulat-Ziganshin
48695be33dc62aab206b61ad431856e152a0fb5c
634
cpp
C++
codes/HDU/hdu2352.cpp
JeraKrs/ACM
edcd61ec6764b8cd804bf1538dfde53d0ff572b5
[ "Apache-2.0" ]
null
null
null
codes/HDU/hdu2352.cpp
JeraKrs/ACM
edcd61ec6764b8cd804bf1538dfde53d0ff572b5
[ "Apache-2.0" ]
null
null
null
codes/HDU/hdu2352.cpp
JeraKrs/ACM
edcd61ec6764b8cd804bf1538dfde53d0ff572b5
[ "Apache-2.0" ]
null
null
null
#include <cstdio> #include <cstring> #include <algorithm> using namespace std; const int maxn = 1005; char s[maxn]; inline int idx(char c) { if (c == 'I') return 1; else if (c == 'V') return 5; else if (c == 'X') return 10; else if (c == 'L') return 50; else if (c == 'C') return 100; else if (c == 'D') return 500; else if (c == 'M') return 1000; return 0; } int main () { int cas; scanf("%d", &cas); while (cas--) { scanf("%s", s); int ans = 0, len = strlen(s); for (int i = 0; i < len; i++) { int k = (idx(s[i]) >= idx(s[i+1]) ? 1 : -1); ans += k * idx(s[i]); } printf("%d\n", ans); } return 0; }
18.114286
47
0.520505
JeraKrs
486e3ce93dbdc4edc36fc00bb0f7316686a0cca3
558
hpp
C++
src/RuleBoost.hpp
d3wy/pool-controller
182d8c67638abf56d8e5126103b5995006c06b42
[ "MIT" ]
12
2020-03-04T18:43:43.000Z
2022-01-30T22:59:27.000Z
src/RuleBoost.hpp
d3wy/pool-controller
182d8c67638abf56d8e5126103b5995006c06b42
[ "MIT" ]
17
2019-05-20T20:22:09.000Z
2022-01-11T16:55:26.000Z
src/RuleBoost.hpp
d3wy/pool-controller
182d8c67638abf56d8e5126103b5995006c06b42
[ "MIT" ]
6
2020-06-05T18:17:13.000Z
2022-03-19T20:13:58.000Z
#pragma once #include "Rule.hpp" #include "RelayModuleNode.hpp" class RuleBoost : public Rule { public: RuleBoost(RelayModuleNode* solarRelay, RelayModuleNode* poolRelay); const char* getMode() { return "boost"; }; void setSolarRelayNode(RelayModuleNode* relay) { _solarRelay = relay; }; void setPoolRelayNode(RelayModuleNode* relay) { _poolRelay = relay; }; virtual void loop(); protected: RelayModuleNode* _solarRelay; RelayModuleNode* _poolRelay; private: const char* cCaption = "• RuleBoost:"; const char* cIndent = " ◦ "; };
21.461538
74
0.716846
d3wy
4872cb9656f275d58c9a8bf2c3a83edd2382339f
4,646
cpp
C++
src/qhebot/lib/qheduino_CAR.cpp
zzboss/qhebot-openblock-extension
2fdadc1303046e231cef4df29594a11893b31e7c
[ "MIT" ]
null
null
null
src/qhebot/lib/qheduino_CAR.cpp
zzboss/qhebot-openblock-extension
2fdadc1303046e231cef4df29594a11893b31e7c
[ "MIT" ]
null
null
null
src/qhebot/lib/qheduino_CAR.cpp
zzboss/qhebot-openblock-extension
2fdadc1303046e231cef4df29594a11893b31e7c
[ "MIT" ]
null
null
null
#include "qheduino_CAR.h" //输入参数为TB6612六个引脚对应的Arduino管脚 CAR::CAR(int left_go, int left_back, int left_pwm, int right_go, int right_back, int right_pwm ) { Left_motor_go = left_go; //左电机前进 AIN1 Left_motor_back = left_back; //左电机后退 AIN2 Right_motor_go = right_go; //右电机前进 BIN1 Right_motor_back = right_back; //右电机后退 BIN2 Left_motor_pwm = left_pwm; //左电机控速 PWMA Right_motor_pwm = right_pwm; //右电机控速 PWMB //初始化电机驱动IO口为输出方式 pinMode(Left_motor_go, OUTPUT); pinMode(Left_motor_back, OUTPUT); pinMode(Right_motor_go, OUTPUT); pinMode(Right_motor_back, OUTPUT); } //dir ----- 0:刹车 1:前进 2:后退 3:左转 4:右转 5:原地左转 6:原地右转 //speed 0~255 void CAR::direction_speed_ctrl(int dir, int speed){ speed = (int)( ((float)speed)*2.55 ); speed = speed>255?255:speed; speed = speed<0?0:speed; switch(dir){ case 1: run( speed ); break; case 2: back( speed ); break; case 3: left( speed ); break; case 4: right( speed ); break; case 5: spin_left( speed ); break; case 6: spin_right( speed ); break; case 0: brake(); break; default: brake(); break; } } /** * Function run * @author George * @brief 小车前进 * @param[in] time * @param[out] void * @retval void * @par History 无 */ void CAR::run(int speed) { //左电机前进 digitalWrite(Left_motor_go, HIGH); //左电机前进使能 digitalWrite(Left_motor_back, LOW); //左电机后退禁止 analogWrite(Left_motor_pwm, speed); //PWM比例0-255调速,左右轮差异略增减 //右电机前进 digitalWrite(Right_motor_go, HIGH); //右电机前进使能 digitalWrite(Right_motor_back, LOW); //右电机后退禁止 analogWrite(Right_motor_pwm, speed); //PWM比例0-255调速,左右轮差异略增减 } /** * Function back * @author George * @brief 小车后退 * @param[in] time * @param[out] void * @retval void * @par History 无 */ void CAR::back(int speed) { //左电机后退 digitalWrite(Left_motor_go, LOW); //左电机前进禁止 digitalWrite(Left_motor_back, HIGH); //左电机后退使能 analogWrite(Left_motor_pwm, speed); //右电机后退 digitalWrite(Right_motor_go, LOW); //右电机前进禁止 digitalWrite(Right_motor_back, HIGH); //右电机后退使能 analogWrite(Right_motor_pwm, speed); } /** * Function brake * @author George * @brief 小车刹车 * @param[in] time * @param[out] void * @retval void * @par History 无 */ void CAR::brake() { digitalWrite(Left_motor_go, LOW); digitalWrite(Left_motor_back, LOW); digitalWrite(Right_motor_go, LOW); digitalWrite(Right_motor_back, LOW); } /** * Function left * @author George * @brief 小车左转 左转(左轮不动,右轮前进) * @param[in] time * @param[out] void * @retval void * @par History 无 */ void CAR::left(int speed) { //左电机停止 digitalWrite(Left_motor_go, LOW); //左电机前进禁止 digitalWrite(Left_motor_back, LOW); //左电机后退禁止 analogWrite(Left_motor_pwm, 0); //左边电机速度设为0(0-255) //右电机前进 digitalWrite(Right_motor_go, HIGH); //右电机前进使能 digitalWrite(Right_motor_back, LOW); //右电机后退禁止 analogWrite(Right_motor_pwm, speed); //右边电机速度设200(0-255) } /** * Function right * @author George * @brief 小车右转 右转(左轮前进,右轮不动) * @param[in] time * @param[out] void * @retval void * @par History 无 */ void CAR::right(int speed) { //左电机前进 digitalWrite(Left_motor_go, HIGH); //左电机前进使能 digitalWrite(Left_motor_back, LOW); //左电机后退禁止 analogWrite(Left_motor_pwm, speed); //左边电机速度设200(0-255) //右电机停止 digitalWrite(Right_motor_go, LOW); //右电机前进禁止 digitalWrite(Right_motor_back, LOW); //右电机后退禁止 analogWrite(Right_motor_pwm, 0); //右边电机速度设0(0-255) } /** * Function spin_left * @author George * @brief 小车原地左转 原地左转(左轮后退,右轮前进) * @param[in] time * @param[out] void * @retval void * @par History 无 */ void CAR::spin_left(int speed) { //左电机后退 digitalWrite(Left_motor_go, LOW); //左电机前进禁止 digitalWrite(Left_motor_back, HIGH); //左电机后退使能 analogWrite(Left_motor_pwm, speed); //右电机前进 digitalWrite(Right_motor_go, HIGH); //右电机前进使能 digitalWrite(Right_motor_back, LOW); //右电机后退禁止 analogWrite(Right_motor_pwm, speed); } /** * Function spin_right * @author George * @brief 小车原地右转 原地右转(右轮后退,左轮前进) * @param[in] time * @param[out] void * @retval void * @par History 无 */ void CAR::spin_right(int speed) { //左电机前进 digitalWrite(Left_motor_go, HIGH); //左电机前进使能 digitalWrite(Left_motor_back, LOW); //左电机后退禁止 analogWrite(Left_motor_pwm, speed); //右电机后退 digitalWrite(Right_motor_go, LOW); //右电机前进禁止 digitalWrite(Right_motor_back, HIGH); //右电机后退使能 analogWrite(Right_motor_pwm, speed); }
23.114428
98
0.64378
zzboss
4873d633f2dfe552a6768aa2782d82ae5d9b5008
4,633
cxx
C++
graphics/nxwm/src/cfullscreenwindow.cxx
DS-LK/incubator-nuttx-apps
5719753399c41529478ced0a3af9a8fae93a50a9
[ "Apache-2.0" ]
1
2022-01-04T04:04:58.000Z
2022-01-04T04:04:58.000Z
graphics/nxwm/src/cfullscreenwindow.cxx
VanFeo/incubator-nuttx-apps
009e66874538658c10a26bc076d27e9de48fabc6
[ "Apache-2.0" ]
null
null
null
graphics/nxwm/src/cfullscreenwindow.cxx
VanFeo/incubator-nuttx-apps
009e66874538658c10a26bc076d27e9de48fabc6
[ "Apache-2.0" ]
null
null
null
/******************************************************************************************** * apps/graphics/nxwm/src/cfullscreenwindow.cxx * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. The * ASF licenses this file to you 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. * ********************************************************************************************/ /******************************************************************************************** * Included Files ********************************************************************************************/ #include <nuttx/config.h> #include <nuttx/nx/nxglib.h> #include "graphics/nxwidgets/nxconfig.hxx" #include "graphics/nxwidgets/cwidgetcontrol.hxx" #include "graphics/nxwidgets/cgraphicsport.hxx" #include "graphics/nxwm/nxwmconfig.hxx" #include "graphics/nxglyphs.hxx" #include "graphics/nxwm/cfullscreenwindow.hxx" /******************************************************************************************** * Pre-Processor Definitions ********************************************************************************************/ /******************************************************************************************** * CFullScreenWindow Method Implementations ********************************************************************************************/ using namespace NxWM; /** * CFullScreenWindow Constructor * * @param window. The raw window to be used by this application. */ CFullScreenWindow::CFullScreenWindow(NXWidgets::CNxWindow *window) { // Save the window for later use m_window = window; } /** * CFullScreenWindow Destructor */ CFullScreenWindow::~CFullScreenWindow(void) { // We didn't create the window. That was done by the task bar, // But we will handle destruction of with window as a courtesy. if (m_window) { delete m_window; } } /** * Initialize window. Window initialization is separate from * object instantiation so that failures can be reported. * * @return True if the window was successfully initialized. */ bool CFullScreenWindow::open(void) { return true; } /** * Re-draw the application window */ void CFullScreenWindow::redraw(void) { } /** * The application window is hidden (either it is minimized or it is * maximized, but not at the top of the hierarchy) */ void CFullScreenWindow::hide(void) { } /** * Recover the contained raw window instance * * @return. The window used by this application */ NXWidgets::INxWindow *CFullScreenWindow::getWindow(void) const { return static_cast<NXWidgets::INxWindow*>(m_window); } /** * Recover the contained widget control * * @return. The widget control used by this application */ NXWidgets::CWidgetControl *CFullScreenWindow::getWidgetControl(void) const { return m_window->getWidgetControl(); } /** * Block further activity on this window in preparation for window * shutdown. * * @param app. The application to be blocked */ void CFullScreenWindow::block(IApplication *app) { // Get the widget control from the NXWidgets::CNxWindow instance NXWidgets::CWidgetControl *control = m_window->getWidgetControl(); // And then block further reporting activity on the underlying // NX raw window nx_block(control->getWindowHandle(), (FAR void *)app); } /** * Set the window label * * @param appname. The name of the application to place on the window */ void CFullScreenWindow::setWindowLabel(NXWidgets::CNxString &appname) { } /** * Report of this is a "normal" window or a full screen window. The * primary purpose of this method is so that window manager will know * whether or not it show draw the task bar. * * @return True if this is a full screen window. */ bool CFullScreenWindow::isFullScreen(void) const { return true; } /** * Register to receive callbacks when toolbar icons are selected */ void CFullScreenWindow::registerCallbacks(IApplicationCallback *callback) { }
26.474286
94
0.616879
DS-LK
4876effedc7f70ccacd951b3eadcfce9fc0e8480
11,299
cpp
C++
aladdin/core/Scene.cpp
Khuongnb1997/game-aladdin
74b13ffcd623de0d6f799b0669c7e8917eef3b14
[ "MIT" ]
2
2017-11-08T16:27:25.000Z
2018-08-10T09:08:35.000Z
aladdin/core/Scene.cpp
Khuongnb1997/game-aladdin
74b13ffcd623de0d6f799b0669c7e8917eef3b14
[ "MIT" ]
null
null
null
aladdin/core/Scene.cpp
Khuongnb1997/game-aladdin
74b13ffcd623de0d6f799b0669c7e8917eef3b14
[ "MIT" ]
4
2017-11-08T16:25:30.000Z
2021-05-23T06:14:59.000Z
/* * Created by phuctm97 on Sep 30th 2017 */ #include "Scene.h" #include "StdHelper.h" #include "GameResource.h" #include "GameManager.h" #include "../2d/2dMacros.h" #include "../2d/Camera.h" NAMESPACE_ALA { ALA_CLASS_SOURCE_2(ala::Scene, ala::Initializable, ala::Releasable) // ================================================ // Basic // ================================================ Scene::Scene(): _toReleaseInNextFrame( false ), _gameObjectInLock( false ), _quadTree( NULL ), _camera( NULL ), _cameraTransform( NULL ), _visibleWidth( 0 ), _visibleHeight( 0 ), _halfVisibleWidth( 0 ), _halfVisibleHeight( 0 ), _physicsEnabled( false ), _gravityAcceleration( 0, -100.0f ) { // check initial state ALA_ASSERT((!isInitialized()) && (!isInitializing()) && (!isReleased()) && (!isReleasing())); TOTAL_SCENES_CREATED++; } Scene::~Scene() { if ( isInitialized() ) { // make sure object released after destruction // ALA_ASSERT(isReleased()); } TOTAL_SCENES_DELETED++; } // ================================================= // Events // ================================================= void Scene::initialize() { // make sure scene is not initialized; ALA_ASSERT((!isInitializing()) && (!isInitialized())); // required framework objects const auto gameManager = GameManager::get(); _camera = gameManager->getPrefab( ALA_MAIN_CAMERA )->instantiate( ALA_MAIN_CAMERA ); _cameraTransform = _camera->getTransform(); _visibleWidth = gameManager->getVisibleWidth(); _visibleHeight = gameManager->getVisibleHeight(); _halfVisibleWidth = _visibleWidth / 2; _halfVisibleHeight = _visibleHeight / 2; onPreInitialize(); setToInitializing(); // TODO: lock mutual exclusive when run in multithreading mode // load resources scope with this for ( auto resource : GameManager::get()->getResourcesWith( this ) ) { if ( !resource->isLoaded() ) { resource->load(); } } // init game objects for ( const auto it : _gameObjects ) { auto object = it.second; if ( !object->isInitialized() ) { object->initialize(); } } setToInitialized(); onPostInitialize(); } void Scene::onPreInitialize() { } void Scene::onPostInitialize() {} void Scene::updatePhysics( const float delta ) { if ( isReleasing() || isReleased() || !isInitialized() || !isPhysicsEnabled() ) return; lockGameObjects(); onPrePhysicsUpdate( delta ); // update game objects if ( !isQuadTreeEnabled() ) { for ( const auto it : _gameObjects ) { auto object = it.second; object->updatePhysics( delta ); } } else { for ( const auto visibleNode : _quadTree->getVisibleNodes() ) { for ( const auto object : visibleNode->getGameObjects() ) { object->updatePhysics( delta ); } } for ( const auto it : _dynamicGameObjects ) { auto object = it.second; object->updatePhysics( delta ); } } onPostPhysicsUpdate( delta ); unlockGameObjects(); } void Scene::onPrePhysicsUpdate( const float delta ) {} void Scene::onPostPhysicsUpdate( const float delta ) {} void Scene::update( const float delta ) { if ( isReleasing() || isReleased() || !isInitialized() ) return; lockGameObjects(); onPreUpdate( delta ); // update game objects if ( !isQuadTreeEnabled() ) { for ( const auto it : _gameObjects ) { auto object = it.second; object->update( delta ); } } else { for ( const auto visibleNode : _quadTree->getVisibleNodes() ) { for ( const auto object : visibleNode->getGameObjects() ) { object->update( delta ); } } for ( const auto it : _dynamicGameObjects ) { auto object = it.second; object->update( delta ); } } onPostUpdate( delta ); unlockGameObjects(); } void Scene::onPreUpdate( const float delta ) {} void Scene::onPostUpdate( const float delta ) {} void Scene::render() { // make sure scene is initialized and not being released if ( (!isInitialized()) || isReleasing() || isReleased() ) return; lockGameObjects(); onPreRender(); // render game objects if ( !isQuadTreeEnabled() ) { for ( const auto it : _gameObjects ) { auto object = it.second; object->render(); } } else { for ( const auto visibleNode : _quadTree->getVisibleNodes() ) { for ( const auto object : visibleNode->getGameObjects() ) { object->render(); } } for ( const auto it : _dynamicGameObjects ) { auto object = it.second; object->render(); } } onPostRender(); unlockGameObjects(); } void Scene::onPreRender() {} void Scene::onPostRender() {} void Scene::release() { // check lock if ( _gameObjectInLock ) { releaseInNextFrame(); return; } // make sure scene is initialized and not released // ALA_ASSERT(isInitialized() && (!isReleasing()) && (!isReleased())); onPreRelease(); setToReleasing(); // release quad tree if ( _quadTree != NULL ) delete _quadTree; // release game objects std::vector<GameObject*> gameObjectsToRelease; for ( const auto it : _gameObjects ) { auto object = it.second; object->release(); } // release resources scope with this for ( auto resouce : GameManager::get()->getResourcesWith( this ) ) { resouce->release(); } setToReleased(); onPostRelease(); // destroy delete this; } void Scene::releaseInNextFrame() { // make sure scene is initialized and not released // ALA_ASSERT(isInitialized() && (!isReleasing()) && (!isReleased())); _toReleaseInNextFrame = true; } void Scene::onPreRelease() {} void Scene::onPostRelease() {} void Scene::resolveLockedTasks() { if ( isReleasing() || isReleased() ) return; // lazy initialization if ( !isInitialized() ) { initialize(); } // update to release in next frame if ( _toReleaseInNextFrame ) { release(); _toReleaseInNextFrame = false; return; } // update locked actions updateAddAndRemoveGameObjects(); // update quad tree if ( isQuadTreeEnabled() ) { updateQuadTreeVisibility(); } // client onResolveLockedTasks(); // update game object locked tasks lockGameObjects(); if ( !isQuadTreeEnabled() ) { for ( const auto it : _gameObjects ) { auto object = it.second; object->resolveLockedTasks(); } } else { for ( const auto visibleNode : _quadTree->getVisibleNodes() ) { for ( const auto object : visibleNode->getGameObjects() ) { object->resolveLockedTasks(); } } for ( const auto it : _dynamicGameObjects ) { auto object = it.second; object->resolveLockedTasks(); } } unlockGameObjects(); } void Scene::onResolveLockedTasks() { } // ================================================== // Objects Management // ================================================== GameObject* Scene::getGameObject( const long id ) const { const auto it = _gameObjects.find( id ); if ( it == _gameObjects.end() ) return NULL; return it->second; } GameObject* Scene::getMainCamera() const { return _camera; } bool Scene::isInLock() const { return _gameObjectInLock; } void Scene::addGameObject( GameObject* gameObject, const std::string& quadIndex ) { // check lock if ( _gameObjectInLock ) { addGameObjectInNextFrame( gameObject ); return; } if ( isReleasing() || isReleased() ) return; if ( gameObject == NULL ) return; doAddGameObject( gameObject, quadIndex ); } void Scene::addGameObjectInNextFrame( GameObject* gameObject, const std::string& quadIndex ) { if ( isReleasing() || isReleased() ) return; if ( gameObject == NULL ) return; _gameObjectsToAddInNextFrame.push_back( std::make_pair( gameObject, quadIndex ) ); } void Scene::removeGameObject( GameObject* gameObject ) { // check lock if ( _gameObjectInLock ) { removeGameObjectInNextFrame( gameObject ); return; } if ( isReleasing() || isReleased() ) return; if ( gameObject == NULL ) return; doRemoveGameObject( gameObject->getId() ); } void Scene::removeGameObjectInNextFrame( GameObject* gameObject ) { if ( isReleasing() || isReleased() ) return; if ( gameObject == NULL ) return; _gameObjectsToRemoveInNextFrame.push_back( gameObject->getId() ); } QuadTree* Scene::getQuadTree() const { return _quadTree; } void Scene::enableQuadTree( const float spaceMinX, const float spaceMinY, const float spaceWidth, const float spaceHeight, const int level ) { _quadTree = new QuadTree( spaceMinX, spaceMinY, spaceWidth, spaceHeight, level ); } bool Scene::isQuadTreeEnabled() const { return _quadTree != NULL; } void Scene::updateQuadTreeVisibility() const { const auto cameraPosition = _cameraTransform->getPosition(); // TODO: calculate with camera scale const auto cameraMinX = cameraPosition.getX() - _halfVisibleWidth; const auto cameraMinY = cameraPosition.getY() - _halfVisibleHeight; const auto cameraMaxX = cameraPosition.getX() + _halfVisibleWidth; const auto cameraMaxY = cameraPosition.getY() + _halfVisibleHeight; _quadTree->updateVisibility( cameraMinX, cameraMinY, cameraMaxX, cameraMaxY ); } void Scene::lockGameObjects() { _gameObjectInLock = true; } void Scene::unlockGameObjects() { _gameObjectInLock = false; } void Scene::updateAddAndRemoveGameObjects() { for ( const auto it : _gameObjectsToAddInNextFrame ) { doAddGameObject( it.first, it.second ); } _gameObjectsToAddInNextFrame.clear(); for ( auto objectId : _gameObjectsToRemoveInNextFrame ) { doRemoveGameObject( objectId ); } _gameObjectsToRemoveInNextFrame.clear(); } void Scene::doAddGameObject( GameObject* gameObject, const std::string& quadIndex ) { _gameObjects.emplace( gameObject->getId(), gameObject ); if ( !isQuadTreeEnabled() || quadIndex.empty() ) { _dynamicGameObjects.emplace( gameObject->getId(), gameObject ); } else { _quadTree->getNode( quadIndex )->addGameObject( gameObject ); _gameObjectToQuadNode.emplace( gameObject->getId(), quadIndex ); } } void Scene::doRemoveGameObject( const long id ) { const auto gameObjectIt = _gameObjects.find( id ); if ( gameObjectIt == _gameObjects.cend() ) return; if ( isQuadTreeEnabled() ) { const auto gameObjectToQuadNodeIt = _gameObjectToQuadNode.find( id ); if ( gameObjectToQuadNodeIt != _gameObjectToQuadNode.cend() ) { _quadTree->getNode( gameObjectToQuadNodeIt->second )->removeGameObject( gameObjectIt->second ); _gameObjectToQuadNode.erase( gameObjectToQuadNodeIt ); } } _gameObjects.erase( id ); _dynamicGameObjects.erase( id ); } const Vec2& Scene::getGravityAcceleration() const { return _gravityAcceleration; } void Scene::enablePhysics( const Vec2& gravity ) { _physicsEnabled = true; _gravityAcceleration = gravity; } bool Scene::isPhysicsEnabled() const { return _physicsEnabled; } // ============================================= // Debug memory allocation // ============================================= long Scene::TOTAL_SCENES_CREATED( 0 ); long Scene::TOTAL_SCENES_DELETED( 0 ); }
24.887665
101
0.638995
Khuongnb1997
487aa1d1c63091c25dde2241d1062b1d7dd5af96
1,195
cpp
C++
higan/ms/psg/io.cpp
13824125580/higan
fbdd3f980b65412c362096579869ae76730e4118
[ "Intel", "ISC" ]
38
2018-04-05T05:00:05.000Z
2022-02-06T00:02:02.000Z
higan/ms/psg/io.cpp
13824125580/higan
fbdd3f980b65412c362096579869ae76730e4118
[ "Intel", "ISC" ]
1
2018-04-29T19:45:14.000Z
2018-04-29T19:45:14.000Z
higan/ms/psg/io.cpp
13824125580/higan
fbdd3f980b65412c362096579869ae76730e4118
[ "Intel", "ISC" ]
8
2018-04-16T22:37:46.000Z
2021-02-10T07:37:03.000Z
auto PSG::write(uint8 data) -> void { bool l = data.bit(7); if(l) select = data.bits(4,6); switch(select) { case 0: { if(l) tone0.pitch.bits(0,3) = data.bits(0,3); else tone0.pitch.bits(4,9) = data.bits(0,5); break; } case 1: { tone0.volume = data.bits(0,3); break; } case 2: { if(l) tone1.pitch.bits(0,3) = data.bits(0,3); else tone1.pitch.bits(4,9) = data.bits(0,5); break; } case 3: { tone1.volume = data.bits(0,3); break; } case 4: { if(l) tone2.pitch.bits(0,3) = data.bits(0,3); else tone2.pitch.bits(4,9) = data.bits(0,5); noise.pitch = tone2.pitch; break; } case 5: { tone2.volume = data.bits(0,3); break; } case 6: { noise.rate = data.bits(0,1); noise.enable = data.bit(2); noise.lfsr = 0x8000; break; } case 7: { noise.volume = data.bits(0,3); break; } } } //Game Gear only auto PSG::balance(uint8 data) -> void { tone0.right = data.bit(0); tone1.right = data.bit(1); tone2.right = data.bit(2); noise.right = data.bit(3); tone0.left = data.bit(4); tone1.left = data.bit(5); tone2.left = data.bit(6); noise.left = data.bit(7); }
17.835821
49
0.553975
13824125580
487aefa8e6a9b2449309a561ee11d697dc3562ec
1,403
cpp
C++
test/constant/scalar/sqrt_2o_3.cpp
TobiasLudwig/boost.simd
c04d0cc56747188ddb9a128ccb5715dd3608dbc1
[ "BSL-1.0" ]
6
2018-02-25T22:23:33.000Z
2021-01-15T15:13:12.000Z
test/constant/scalar/sqrt_2o_3.cpp
remymuller/boost.simd
3caefb7ee707e5f68dae94f8f31f72f34b7bb5de
[ "BSL-1.0" ]
null
null
null
test/constant/scalar/sqrt_2o_3.cpp
remymuller/boost.simd
3caefb7ee707e5f68dae94f8f31f72f34b7bb5de
[ "BSL-1.0" ]
7
2017-12-12T12:36:31.000Z
2020-02-10T14:27:07.000Z
//================================================================================================== /*! Copyright 2016 NumScale SAS Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt) */ //================================================================================================== #include <boost/simd/constant/sqrt_2o_3.hpp> #include <boost/simd/constant/ratio.hpp> #include <boost/simd/as.hpp> #include <scalar_test.hpp> STF_CASE_TPL( "Check sqrt_2o_3 behavior for integral types" , (std::uint8_t)(std::uint16_t)(std::uint32_t)(std::uint64_t) (std::int8_t)(std::int16_t)(std::int32_t)(std::int64_t) ) { using boost::simd::as; using boost::simd::detail::sqrt_2o_3; using boost::simd::Sqrt_2o_3; STF_TYPE_IS(decltype(Sqrt_2o_3<T>()), T); STF_EQUAL(Sqrt_2o_3<T>(), T(0)); STF_EQUAL(sqrt_2o_3( as(T{}) ),T(0)); } STF_CASE_TPL( "Check sqrt_2o_3 behavior for floating types" , (double)(float) ) { using boost::simd::as; using boost::simd::detail::sqrt_2o_3; using boost::simd::Sqrt_2o_3; using boost::simd::Ratio; STF_TYPE_IS(decltype(Sqrt_2o_3<T>()), T); auto z1 = Sqrt_2o_3<T>(); STF_ULP_EQUAL(z1*z1, (Ratio<T,2,3>()), 0.5); auto z2 = sqrt_2o_3( as(T{}) ); STF_ULP_EQUAL(z2*z2, (Ratio<T,2,3>()), 0.5); }
29.851064
100
0.558803
TobiasLudwig
488178167970c29b3461a8ddb955a4034ebb91bf
8,974
cpp
C++
src/main.cpp
jk-jeon/dtoa-benchmark
7bf593b5bfdbc7cfb0c0c583b8f509807e0b1fee
[ "MIT" ]
1
2020-11-05T06:51:16.000Z
2020-11-05T06:51:16.000Z
src/main.cpp
jk-jeon/dtoa-benchmark
7bf593b5bfdbc7cfb0c0c583b8f509807e0b1fee
[ "MIT" ]
null
null
null
src/main.cpp
jk-jeon/dtoa-benchmark
7bf593b5bfdbc7cfb0c0c583b8f509807e0b1fee
[ "MIT" ]
4
2019-06-06T11:35:42.000Z
2021-11-20T02:40:15.000Z
#include <algorithm> #include <cassert> #include <cstdio> #include <cstring> #include <exception> #include <limits> #if _MSC_VER #include "msinttypes/stdint.h" #else #include <stdint.h> #endif #include <cstdlib> #include <math.h> #include <random> #include "resultfilename.h" #include "timer.h" #include "test.h" #include "double-conversion/double-conversion.h" const unsigned kIterationForRandom = 100; const unsigned kIterationPerDigit = 10; const unsigned kTrial = 10; class RandomData { public: static double* GetData() { static RandomData singleton; return singleton.mData; } static const size_t kCount = 100000; private: RandomData() : mData(new double[kCount]) { std::mt19937 rg{ std::random_device{}() }; union { double d; uint64_t u; }u; for (size_t i = 0; i < kCount; i++) { do { // Need to call r() in two statements for cross-platform coherent sequence. u.u = uint64_t(rg()) << 32; u.u |= uint64_t(rg()); } while (isnan(u.d) || isinf(u.d)); mData[i] = u.d; } } ~RandomData() { delete[] mData; } double* mData; }; static size_t VerifyValue(double value, void(*f)(double, char*), const char* expect = 0) { char buffer[1024]; f(value, buffer); //printf("%.17g -> %s\n", value, buffer); if (expect && strcmp(buffer, expect) != 0) { printf("Error: expect %s but actual %s\n", expect, buffer); //throw std::exception(); } #if 0 char* end; double roundtrip = strtod(buffer, &end); int processed = int(end - buffer); #else // double-conversion returns correct result. using namespace double_conversion; StringToDoubleConverter converter(StringToDoubleConverter::ALLOW_TRAILING_JUNK, 0.0, 0.0, NULL, NULL); int processed = 0; double roundtrip = converter.StringToDouble(buffer, 1024, &processed); #endif size_t len = strlen(buffer); if (len != (size_t)processed) { printf("Error: some extra character %g -> '%s'\n", value, buffer); throw std::exception(); } if (value != roundtrip) { printf("Error: roundtrip fail %.17g -> '%s' -> %.17g\n", value, buffer, roundtrip); //throw std::exception(); } return len; } static void Verify(void(*f)(double, char*), const char* fname) { printf("Verifying %-20s ... ", fname); // Boundary and simple cases VerifyValue(0, f); /*VerifyValue(0.1, f, "0.1"); VerifyValue(0.12, f, "0.12"); VerifyValue(0.123, f, "0.123"); VerifyValue(0.1234, f, "0.1234"); VerifyValue(1.2345, f, "1.2345");*/ ////////////////////// VerifyValue(0.1, f); VerifyValue(0.12, f); VerifyValue(0.123, f); VerifyValue(0.1234, f); VerifyValue(1.2345, f); ////////////////////// VerifyValue(1.0 / 3.0, f); VerifyValue(2.0 / 3.0, f); VerifyValue(10.0 / 3.0, f); VerifyValue(20.0 / 3.0, f); VerifyValue(std::numeric_limits<double>::min(), f); VerifyValue(std::numeric_limits<double>::max(), f); VerifyValue(std::numeric_limits<double>::denorm_min(), f); char buffer[256]; double* data = RandomData::GetData(); size_t n = RandomData::kCount; uint64_t lenSum = 0; size_t lenMax = 0; for (unsigned i = 0; i < n; i++) { size_t len = VerifyValue(data[i], f); lenSum += len; lenMax = std::max(lenMax, len); } double lenAvg = double(lenSum) / n; printf("OK. Length Avg = %2.3f, Max = %d\n", lenAvg, (int)lenMax); } void VerifyAll() { const TestList& tests = TestManager::Instance().GetTests(); for (TestList::const_iterator itr = tests.begin(); itr != tests.end(); ++itr) { if (strcmp((*itr)->fname, "null") != 0) { // skip null try { Verify((*itr)->dtoa, (*itr)->fname); } catch (...) { } } } } void BenchSequential(void(*f)(double, char*), const char* fname, FILE* fp) { printf("Benchmarking sequential %-20s ... ", fname); char buffer[256] = { '\0' }; double minDuration = std::numeric_limits<double>::max(); double maxDuration = 0.0; int64_t start = 1; for (int digit = 1; digit <= 17; digit++) { int64_t end = start * 10; double duration = std::numeric_limits<double>::max(); for (unsigned trial = 0; trial < kTrial; trial++) { int64_t v = start; std::mt19937 rg{ std::random_device{}() }; v += ((int64_t(rg()) << 32) | int64_t(rg())) % start; double sign = 1; Timer timer; timer.Start(); for (unsigned iteration = 0; iteration < kIterationPerDigit; iteration++) { double d = v * sign; f(d, buffer); //printf("%.17g -> %s\n", d, buffer); sign = -sign; v += 1; if (v >= end) v = start; } timer.Stop(); duration = std::min(duration, timer.GetElapsedMilliseconds()); } duration *= 1e6 / kIterationPerDigit; // convert to nano second per operation minDuration = std::min(minDuration, duration); maxDuration = std::max(maxDuration, duration); fprintf(fp, "%s_sequential,%d,%f\n", fname, digit, duration); start = end; } printf("[%8.3fns, %8.3fns]\n", minDuration, maxDuration); } void BenchRandom(void(*f)(double, char*), const char* fname, FILE* fp) { printf("Benchmarking random %-20s ... ", fname); char buffer[256]; double* data = RandomData::GetData(); size_t n = RandomData::kCount; double duration = std::numeric_limits<double>::max(); for (unsigned trial = 0; trial < kTrial; trial++) { Timer timer; timer.Start(); for (unsigned iteration = 0; iteration < kIterationForRandom; iteration++) for (size_t i = 0; i < n; i++) f(data[i], buffer); timer.Stop(); duration = std::min(duration, timer.GetElapsedMilliseconds()); } duration *= 1e6 / (kIterationForRandom * n); // convert to nano second per operation fprintf(fp, "random,%s,0,%f\n", fname, duration); printf("%8.3fns\n", duration); } class RandomDigitData { public: static double* GetData(int digit) { assert(digit >= 1 && digit <= 17); static RandomDigitData singleton; return singleton.mData + (digit - 1) * kCount; } static const int kMaxDigit = 17; static const size_t kCount = 10000; private: RandomDigitData() : mData(new double[kMaxDigit * kCount]) { std::mt19937 rg{ std::random_device{}() }; union { double d; uint64_t u; }u; double* p = mData; for (int digit = 1; digit <= kMaxDigit; digit++) { for (size_t i = 0; i < kCount; i++) { do { // Need to call r() in two statements for cross-platform coherent sequence. u.u = uint64_t(rg()) << 32; u.u |= uint64_t(rg()); } while (isnan(u.d) || isinf(u.d)); // Convert to string with limited digits, and convert it back. char buffer[256]; sprintf(buffer, "%.*g", digit, u.d); using namespace double_conversion; StringToDoubleConverter converter(StringToDoubleConverter::ALLOW_TRAILING_JUNK, 0.0, 0.0, NULL, NULL); int processed = 0; double roundtrip = converter.StringToDouble(buffer, 256, &processed); *p++ = roundtrip; } } } ~RandomDigitData() { delete[] mData; } double* mData; }; void BenchRandomDigit(void(*f)(double, char*), const char* fname, FILE* fp) { printf("Benchmarking randomdigit %-20s ... ", fname); char buffer[256]; double minDuration = std::numeric_limits<double>::max(); double maxDuration = 0.0; for (int digit = 1; digit <= RandomDigitData::kMaxDigit; digit++) { double* data = RandomDigitData::GetData(digit); size_t n = RandomDigitData::kCount; double duration = std::numeric_limits<double>::max(); for (unsigned trial = 0; trial < kTrial; trial++) { Timer timer; timer.Start(); for (unsigned iteration = 0; iteration < kIterationPerDigit; iteration++) { for (size_t i = 0; i < n; i++) { f(data[i], buffer); //if (trial == 0 && iteration == 0 && i == 0) // printf("%.17g -> %s\n", data[i], buffer); } } timer.Stop(); duration = std::min(duration, timer.GetElapsedMilliseconds()); } duration *= 1e6 / (kIterationPerDigit * n); // convert to nano second per operation minDuration = std::min(minDuration, duration); maxDuration = std::max(maxDuration, duration); fprintf(fp, "randomdigit,%s,%d,%f\n", fname, digit, duration); } printf("[%8.3fns, %8.3fns]\n", minDuration, maxDuration); } void Bench(void(*f)(double, char*), const char* fname, FILE* fp) { //BenchSequential(f, fname, fp); //BenchRandom(f, fname, fp); BenchRandomDigit(f, fname, fp); } void BenchAll() { // doublery to write to /result path, where template.php exists FILE *fp; if ((fp = fopen("../../result/template.php", "r")) != NULL) { fclose(fp); fp = fopen("../../result/" RESULT_FILENAME, "w"); } else if ((fp = fopen("../result/template.php", "r")) != NULL) { fclose(fp); fp = fopen("../result/" RESULT_FILENAME, "w"); } else fp = fopen(RESULT_FILENAME, "w"); fprintf(fp, "Type,Function,Digit,Time(ns)\n"); const TestList& tests = TestManager::Instance().GetTests(); for (TestList::const_iterator itr = tests.begin(); itr != tests.end(); ++itr) Bench((*itr)->dtoa, (*itr)->fname, fp); fclose(fp); } int main() { // sort tests TestList& tests = TestManager::Instance().GetTests(); std::sort(tests.begin(), tests.end()); VerifyAll(); BenchAll(); }
26.087209
106
0.634723
jk-jeon
4882d3004fbce99beccaf4a94e9ac7b8b46da600
1,596
cpp
C++
snippets/cpp/VS_Snippets_CLR_System/system.Decimal.Ctor.Ints/CPP/ctorui.cpp
BohdanMosiyuk/samples
59d435ba9e61e0fc19f5176c96b1cdbd53596142
[ "CC-BY-4.0", "MIT" ]
2
2020-02-22T09:30:21.000Z
2021-08-02T23:44:31.000Z
snippets/cpp/VS_Snippets_CLR_System/system.Decimal.Ctor.Ints/CPP/ctorui.cpp
BohdanMosiyuk/samples
59d435ba9e61e0fc19f5176c96b1cdbd53596142
[ "CC-BY-4.0", "MIT" ]
555
2019-09-23T22:22:58.000Z
2021-07-15T18:51:12.000Z
snippets/cpp/VS_Snippets_CLR_System/system.Decimal.Ctor.Ints/CPP/ctorui.cpp
BohdanMosiyuk/samples
59d435ba9e61e0fc19f5176c96b1cdbd53596142
[ "CC-BY-4.0", "MIT" ]
3
2020-01-29T16:31:15.000Z
2021-08-24T07:00:15.000Z
//<Snippet2> // Example of the Decimal( unsigned int ) constructor. using namespace System; // Create a Decimal object and display its value. void CreateDecimal( unsigned int value, String^ valToStr ) { Decimal decimalNum = Decimal(value); // Format the constructor for display. String^ ctor = String::Format( "Decimal( {0} )", valToStr ); // Display the constructor and its value. Console::WriteLine( "{0,-30}{1,16}", ctor, decimalNum ); } int main() { Console::WriteLine( "This example of the Decimal( unsigned " "int ) constructor \ngenerates the following output.\n" ); Console::WriteLine( "{0,-30}{1,16}", "Constructor", "Value" ); Console::WriteLine( "{0,-30}{1,16}", "-----------", "-----" ); // Construct Decimal objects from unsigned int values. CreateDecimal( UInt32::MinValue, "UInt32::MinValue" ); CreateDecimal( UInt32::MaxValue, "UInt32::MaxValue" ); CreateDecimal( Int32::MaxValue, "Int32::MaxValue" ); CreateDecimal( 999999999, "999999999" ); CreateDecimal( 0x40000000, "0x40000000" ); CreateDecimal( 0xC0000000, "0xC0000000" ); } /* This example of the Decimal( unsigned int ) constructor generates the following output. Constructor Value ----------- ----- Decimal( UInt32::MinValue ) 0 Decimal( UInt32::MaxValue ) 4294967295 Decimal( Int32::MaxValue ) 2147483647 Decimal( 999999999 ) 999999999 Decimal( 0x40000000 ) 1073741824 Decimal( 0xC0000000 ) 3221225472 */ //</Snippet2>
33.25
65
0.62406
BohdanMosiyuk
4886e4e3705016ccad778d9ed1e290088926b00e
9,867
cpp
C++
Atum/SceneObjects/Other/Demo/SimpleCharacter2D.cpp
ENgineE777/Atum
3e9417e2a7deda83bf937612fd070566eb932484
[ "Zlib" ]
23
2017-11-01T14:47:26.000Z
2021-12-30T08:04:31.000Z
Atum/SceneObjects/Other/Demo/SimpleCharacter2D.cpp
ENgineE777/Atum
3e9417e2a7deda83bf937612fd070566eb932484
[ "Zlib" ]
1
2018-12-06T14:19:55.000Z
2018-12-07T04:06:35.000Z
Atum/SceneObjects/Other/Demo/SimpleCharacter2D.cpp
ENgineE777/Atum
3e9417e2a7deda83bf937612fd070566eb932484
[ "Zlib" ]
4
2017-11-30T10:25:58.000Z
2019-04-21T14:11:40.000Z
#include "SimpleCharacter2D.h" #include "Services/Render/Render.h" #include "SceneObjects/2D/SpriteAsset.h" CLASSREG(SceneObject, SimpleCharacter2D, "SimpleCharacter2D") META_DATA_DESC(SimpleCharacter2D) BASE_SCENE_OBJ_PROP(SimpleCharacter2D) FLOAT_PROP(SimpleCharacter2D, trans.pos.x, 100.0f, "Geometry", "x", "X coordinate of position of a character") FLOAT_PROP(SimpleCharacter2D, trans.pos.y, 100.0f, "Geometry", "y", "X coordinate of position of a character") SCENEOBJECT_PROP(SimpleCharacter2D, vjoy_ref, "Prop", "VJoy") STRING_PROP(SimpleCharacter2D, asset_name, "", "Prop", "Asset") FLOAT_PROP(SimpleCharacter2D, speed, 120.0f, "Prop", "Speed", "Speed of a charater") BOOL_PROP(SimpleCharacter2D, is_enemy, true, "Prop", "IsEnemy", "Definig if charcter is a enemy") INT_PROP(SimpleCharacter2D, max_hp, 100, "Prop", "HP", "Max Health of a character") FLOAT_PROP(SimpleCharacter2D, floor_width, 500.0f, "Prop", "FloorWidth", "Width of a level floor") FLOAT_PROP(SimpleCharacter2D, floor_height, 200.0f, "Prop", "FloorHeight", "Higth of a level floor") META_DATA_DESC_END() void SimpleCharacter2D::BindClassToScript() { BIND_TYPE_TO_SCRIPT(SimpleCharacter2D, "SimpleCharacter2D") core.scripts.RegisterObjectProperty(script_class_name, "int cur_hp", memberOFFSET(SimpleCharacter2D, cur_hp), "Health of acharacter"); core.scripts.RegisterObjectMethod(script_class_name, "void Reset()", WRAP_MFN(SimpleCharacter2D, Reset), "Setting postion to initial position on start scene"); core.scripts.RegisterObjectMethod(script_class_name, "void SetAnimGraph(string&in)", WRAP_MFN(SimpleCharacter2D, SetAnimGraph), "Setting anim graph asset by name"); } void SimpleCharacter2D::Init() { trans.offset.y = 1.0f; Tasks(false)->AddTask(10, this, (Object::Delegate)&SimpleCharacter2D::Update); RenderTasks(false)->AddTask(ExecuteLevels::Sprites, this, (Object::Delegate)&SimpleCharacter2D::Draw); GetScene()->AddToGroup(this, "SimpleCharacter2D"); } void SimpleCharacter2D::ApplyProperties() { SetAnimGraph(asset_name); vjoy = (VirtualJoystick*)vjoy_ref.object; } void SimpleCharacter2D::Update(float dt) { if (state != Active) { return; } if (!asset || !graph_instance.cur_node) { return; } if (GetScene()->Playing()) { if (arraive > 0.0f) { arraive -= dt; if (arraive < 0.0f) { arraive = -1.0f; graph_instance.ActivateLink("Idle"); } else { return; } } if (!target) { target = FindTarget(); } if (!is_enemy) { ControlPlayer(dt); } else { ControlEnemy(dt); } if (cur_time_to_kick > 0.0f) { cur_time_to_kick -= dt; if (cur_time_to_kick < 0.0f) { cur_time_to_kick = -1.0f; Vector2 kick_pos = trans.pos; kick_pos.x += flipped ? -120.0f : 120.0f; MakeHit(kick_pos, 25); if (target && target->cur_hp == 0) { target = nullptr; } } } if (target && allow_move) { flipped = trans.pos.x > target->trans.pos.x; } if (dir_horz == 0 && dir_vert == 0) { if (allow_move) { graph_instance.ActivateLink("Idle"); allow_move = false; } } else { trans.pos.x += dt * speed * dir_horz; trans.pos.x = fmax(-floor_width, trans.pos.x); trans.pos.x = fmin( floor_width, trans.pos.x); trans.pos.y += dt * speed * 0.75f * dir_vert; trans.pos.y = fmax(floor_margin.x, trans.pos.y); trans.pos.y = fmin(floor_margin.y, trans.pos.y); } if (resp_time > 0.0f) { resp_time -= dt; if (resp_time < 0.0f) { resp_time = -1.0f; Respawn(); } } if (vanish_time > 0.0f) { vanish_time -= dt; if (vanish_time < 0.0f) { vanish_time = -1.0f; resp_time = 3.0f; } } if (death_fly > 0.0f) { death_fly -= dt; trans.pos.x += dt * (flipped ? 380.0f : -380.0f); if (death_fly < 0.0f) { death_fly = -1.0f; vanish_time = 2.0f; } } } } void SimpleCharacter2D::Draw(float dt) { if (GetState() == Invisible) { return; } if (!asset || !graph_instance.cur_node) { return; } if (resp_time > 0.0f || (vanish_time > 0.0f && ((int)(vanish_time / 0.1f) % 2 == 0))) { return; } trans.size = graph_instance.cur_node->asset->trans.size; trans.depth = 0.74f - ((trans.pos.y - floor_margin.x) / floor_height) * 0.5f; graph_instance.state.horz_flipped = flipped; trans.BuildMatrices(); if (arraive > 0.0f) { trans.mat_global.Pos().y -= 1024.0f * arraive; } if (GetState() == Active) { graph_instance.Update(GetName(), 0, Script(), nullptr, dt); } Sprite::Draw(&trans, COLOR_WHITE, &graph_instance.cur_node->asset->sprite, &graph_instance.state, true, false); } SimpleCharacter2D* SimpleCharacter2D::FindTarget() { vector<Scene::Group*> out_group; GetScene()->GetGroup(out_group, "SimpleCharacter2D"); for (auto group : out_group) { for (auto& object : group->objects) { SimpleCharacter2D* chraracter = (SimpleCharacter2D*)object; if (chraracter->cur_hp <= 0) { continue; } if (chraracter->is_enemy == !is_enemy) { return chraracter; } } } return nullptr; } void SimpleCharacter2D::ControlPlayer(float dt) { dir_horz = 0; if (core.controls.DebugKeyPressed("KEY_A", Controls::Active) || (vjoy && vjoy->stick_delta.x < 0.0f)) { if (!allow_move) { allow_move = graph_instance.ActivateLink(target ? "WalkBack" : "Walk"); } if (allow_move) { if (!target) { flipped = true; } dir_horz = -1; } } else if (core.controls.DebugKeyPressed("KEY_D", Controls::Active) || (vjoy && vjoy->stick_delta.x > 0.0f)) { if (!allow_move) { allow_move = graph_instance.ActivateLink("Walk"); } if (allow_move) { if (!target) { flipped = false; } dir_horz = 1; } } dir_vert = 0; if (core.controls.DebugKeyPressed("KEY_W", Controls::Active) || (vjoy && vjoy->stick_delta.y < 0.0f)) { if (!allow_move) { allow_move = graph_instance.ActivateLink("WalkBack"); } if (allow_move) { dir_vert = -1; } } else if (core.controls.DebugKeyPressed("KEY_S", Controls::Active) || (vjoy && vjoy->stick_delta.y > 0.0f)) { if (!allow_move) { allow_move = graph_instance.ActivateLink("Walk"); } if (allow_move) { dir_vert = 1; } } if (core.controls.DebugKeyPressed("KEY_E") || (vjoy && vjoy->button_a_pressed == 2)) { if (graph_instance.ActivateLink("LegKick1")) { cur_time_to_kick = 0.45f; allow_move = false; } } if (core.controls.DebugKeyPressed("KEY_R") || (vjoy && vjoy->button_b_pressed == 2)) { if (graph_instance.ActivateLink("LegKick2")) { cur_time_to_kick = 0.55f; allow_move = false; } } } void SimpleCharacter2D::ControlEnemy(float dt) { if (target) { //if (next_kick == -1) { //next_kick } if (fabs(trans.pos.x - target->trans.pos.x) > 200.0f) { if (!allow_move) { allow_move = graph_instance.ActivateLink("Walk"); } if (allow_move) { dir_horz = (trans.pos.x - target->trans.pos.x) > 0.0f ? -1 : 1; } } else { dir_horz = 0; } if (fabs(trans.pos.x - target->trans.pos.x) < 500.0f && fabs(trans.pos.y - target->trans.pos.y) > 5.0f) { if (!allow_move) { allow_move = graph_instance.ActivateLink("Walk"); } if (allow_move) { dir_vert = (trans.pos.y - target->trans.pos.y) > 0.0f ? -1 : 1; } } else { dir_vert = 0; } if (fabs(trans.pos.x - target->trans.pos.x) < 200.0f && fabs(trans.pos.y - target->trans.pos.y) < 5.0f) { cur_time_2_kuck += dt; if (cur_time_2_kuck > time_2_kick) { cur_time_2_kuck = 0.0f; bool sec_kick = Math::Rand() > 0.5; if (graph_instance.ActivateLink(sec_kick ? "LegKick1" : "LegKick2")) { cur_time_to_kick = sec_kick ? 0.55f : 0.85f; flipped = trans.pos.x > target->trans.pos.x; allow_move = false; } } } else { cur_time_2_kuck = 0.0f; } } } void SimpleCharacter2D::MakeHit(Vector2 pos, int damage) { vector<Scene::Group*> out_group; GetScene()->GetGroup(out_group, "SimpleCharacter2D"); for (auto group : out_group) { for (auto& object : group->objects) { SimpleCharacter2D* chraracter = (SimpleCharacter2D*)object; if (chraracter->is_enemy == !is_enemy && chraracter->cur_hp > 0) { if ((chraracter->trans.pos.x - 85.0f) < pos.x && pos.x < (chraracter->trans.pos.x + 85.0f) && fabs(chraracter->trans.pos.y - pos.y) < 15.0f) { if (chraracter->graph_instance.ActivateLink("Hit")) { chraracter->cur_hp -= damage; chraracter->cur_time_to_kick = -1.0f; chraracter->allow_move = false; if (chraracter->cur_hp <= 0) { chraracter->cur_hp = 0; chraracter->target = nullptr; chraracter->graph_instance.GotoNode("Death"); chraracter->death_fly = 0.75f; } } } } } } } void SimpleCharacter2D::Respawn() { cur_hp = max_hp; arraive = 1.0f; graph_instance.GotoNode("Resp"); } void SimpleCharacter2D::Reset() { trans.pos = init_pos; cur_hp = max_hp; allow_move = false; flipped = false; dir_horz = 0; dir_vert = 0; time_2_kick = 0.5f; cur_time_2_kuck = 0; cur_time_to_kick = -1.0f; death_fly = -1.0f; vanish_time = -1.0f; arraive = -1.0f; resp_time = -1.0f; next_kick = -1; graph_instance.Reset(); if (is_enemy) { Respawn(); } } void SimpleCharacter2D::SetAnimGraph(string& graph) { asset = (SpriteGraphAsset*)GetScene()->FindInGroup("SpriteGraphAsset", graph.c_str()); if (asset) { asset->PrepareInstance(&graph_instance); if (graph_instance.cur_node) { floor_margin.y = 1024.0f; floor_margin.x = floor_margin.y - floor_height; } } } bool SimpleCharacter2D::Play() { init_pos = trans.pos; Reset(); return true; } #ifdef EDITOR void SimpleCharacter2D::SetEditMode(bool ed) { SceneObject::SetEditMode(ed); Gizmo::inst->SetTrans2D(Gizmo::Transform2D(trans), Gizmo::trans_2d_move); } #endif
20.095723
165
0.643458
ENgineE777