blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
4
201
content_id
stringlengths
40
40
detected_licenses
listlengths
0
85
license_type
stringclasses
2 values
repo_name
stringlengths
7
100
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
260 values
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
11.4k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
17 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
80 values
src_encoding
stringclasses
28 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
8
9.86M
extension
stringclasses
52 values
content
stringlengths
8
9.86M
authors
listlengths
1
1
author
stringlengths
0
119
eb03174eb171262bd14b6eea7f7414c74a2f9923
99afd32a341fc466431a3710e3722f5632a749df
/MajorityElement2.cpp
ee2ee4f3031759e78626299dbc1d8ad138850b1b
[]
no_license
shuaijiang/LeetCode
0f537a14c5f185505ed3e75074b221fce54b93c4
ea614fa1eb6cad7bc23b4361f3f575129977cb62
refs/heads/master
2021-01-19T15:34:07.375565
2015-10-21T02:21:50
2015-10-21T02:21:50
32,854,479
1
1
null
null
null
null
UTF-8
C++
false
false
823
cpp
/* *Majority Element II *Author: shuaijiang *Email: zhaoshuaijiang8@gmail.com */ #include<iostream> #include<vector> #include<stdlib.h> using namespace std; class Solution { public: vector<int> majorityElement(vector<int>& nums) { int size = nums.size(); vector<int> result; if(size <= 1) return nums; if(size == 2){ if(nums[0] != nums[1]) return nums; else{ result.push_back(nums[0]); return result; } } sort(nums.begin(),nums.end()); int count = 1; for(int i=1;i<size;i++){ if(nums[i] == nums[i-1]){ count++; } else{ if(count>size/3) result.push_back(nums[i-1]); count = 1; } } if(count > size/3) result.push_back(nums[size-1]); return result; } };
[ "zhaoshuaijiang@sina.com" ]
zhaoshuaijiang@sina.com
68997c2a43de293859a76b6b386ada96f74ff5e7
a5b83e833a8bb998676b5053cbcdc59d39afb16b
/analyzer.cpp
58d3b15d642681b23c80328e3930aadb49b00075
[]
no_license
ArtKomarov/ExpressionAnalyzer
56e08bb85f8bfa1f90c2ba8e5e019b66f1b9c280
a4dc183a5ab2896dd4c235c78deab4ba05e1045b
refs/heads/master
2020-11-26T01:53:55.232024
2020-01-09T12:53:16
2020-01-09T12:53:16
null
0
0
null
null
null
null
UTF-8
C++
false
false
7,436
cpp
#include <iostream> #include <string> #include <string.h> #include <assert.h> #include <math.h> #include "analyzer.h" #include "analyzerconsts.h" //private /*Node* Analyzer::OpUnion(Node* nod1, Node* nod2, char op) { assert(nod1 != NULL); assert(nod2 != NULL); Node* total = new Node(OP, op, nod1, nod2); //total->Construct(OP, op, nod1, nod2); return total; }*/ /*Node* Analyzer::OpUnion(Node* nod1, char op) { assert(nod1 != NULL); Node* total = new Node(OP, op, nod1); //total->Construct(OP, op, nod1); return total; }*/ //void Analyzer::MyAssert(bool b) { // if(!b) // fprintf(stderr, "Ошибка, ожидалась скобка! (символ \"(\" или \")\", зависит от контекста)\n"); //} //public // Constructor Analyzer::Analyzer(char* s) { assert(s != NULL); this->s = strdup(s); this->slen = (int) strlen(s); this->tree = this->GetG(); // Analyze expression } // Destructor Analyzer::~Analyzer() { while(*s != '\0') s++; free(this->s - this->slen); this->s = NULL; delete this->tree; this->tree = NULL; } // Analyze expression, that must contain last symbol # Node* Analyzer::GetG() { Node *val = GetE(); //Get x+y or x-y if(val != NULL && *s != '#') fprintf(stderr, "Syntax error: expected last symbol \"#\"!\n"); return val; } // Analyze sub-expression, that contain constant value Node* Analyzer::GetN() { int val = 0; char *start = s; while(*s >= '0' && *s <= '9') { val = val * 10 + (*(s++) - '0'); } if(start == s) return NULL; Node* n = new Node(NUM, val); return n; } //Analyze sub-expression that contain addition or subtractin Node *Analyzer::GetE() { Node* val = GetT(); // Get x*y or x/y // May be NULL in case of '-' Node* total; while(*s == '+' || *s == '-') { char oper = *s; s++; Node* val2 = GetT(); // Get x*y or x/y if(val2 == NULL) { fprintf(stderr, "Syntax error: expected correct expression after /'%c/'!\n", oper); if(val != NULL) delete val; return NULL; } if(oper == '-' && val == NULL) total = new Node(OP, oper, val2); else if(val != NULL) total = new Node(OP, oper, val, val2); else { fprintf(stderr, "Syntax error: expected correct expression before /'+/'!\n"); if(val != NULL) delete val; return NULL; } val = total; } return val; } //Analyze sub-expression that contain multiplication or division Node *Analyzer::GetT() { Node* val = GetPow(); // Get x^y Node* total; while(*s == '*' || *s == '/') { if(val == NULL) { fprintf(stderr, "Syntax error: expected correct expression before /'%c/'!\n", *s); return NULL; } char oper = *s++; Node* val2 = GetPow(); //Get x^y if(val2 == NULL) { fprintf(stderr, "Syntax error: expected correct expression before /'%c/'!\n", *s); if(val != NULL) delete val; return NULL; } total = new Node(OP, oper, val, val2); val = total; } return val; } //Analyze sub-expression that contain braces (x) Node* Analyzer::GetP() { if(*s == '(') { s++; Node* val = GetE(); // Get x+y or x-y if(val == NULL) { //expresion fprintf(stderr, "Syntax error, expected expresion after /'(/'!\n"); return NULL; } if(*s++ != ')') fprintf(stderr, "Syntax error, expected /')/'!\n"); return val; } else return GetVN(); //Get sin/cos, var or const (or const * var) } //Analyze sub-expression that contain variable (var = x) Node* Analyzer::GetV() { char *start = s; if(this->varstr == "") { while((*s >= 'A' && *s <= 'Z') || (*s >= 'a' && *s <= 'z') || (*s == '_')) { this->varstr += *s++; //s++; } } else { int i = 0; while((*s >= 'A' && *s <= 'Z') || (*s >= 'a' && *s <= 'z') || (*s == '_')) { if(this->varstr[i] != *s) { fprintf(stderr, "Our analyzer works only with 1 variable!\n"); return NULL; } i++; s++; } } if(start == s) return NULL; else { Node* n = new Node(VAR); return n; } } //Analyze sub-expression that contain sin/cos, variable or constant (or const * var) Node* Analyzer::GetVN() { Node *val1 = NULL, *val2 = NULL; if((val1 = GetSC()) != NULL) // Get sin(x) or cos(x) return val1; if((val1 = GetL()) != NULL) // Get ln(x) return val1; if((val1 = GetN()) != NULL) { // Get const if((val2 = GetV()) != NULL) { // Get var Node* total; total = new Node(OP, '*', val1, val2); return total; } else { return val1; } } else return GetV(); //Get var } //Analyze sub-expression that contain sin() or cos() function Node* Analyzer::GetSC() { Node* val; char id; if(strncmp(s, "sin", 3) == 0) { s += 3; id = 's'; } else if(strncmp(s, "cos", 3) == 0) { s += 3; id = 'c'; } else return NULL; //MyAssert(*s == '('); //s++; if(*s++ != '(') { if(id == 's') fprintf(stderr, "Syntax error, expected /'(/' after sin!\n"); else fprintf(stderr, "Syntax error, expected /'(/' after cos!\n"); } val = GetE(); //Get x+y or x-y if(val == NULL) { if(id == 's') fprintf(stderr, "Syntax error, expected correct expression after \"sin(\"!\n"); else fprintf(stderr, "Syntax error, expected correct expression after \"cos(\"!\n"); } if(*s++ != ')') { if(id == 's') fprintf(stderr, "Syntax error, expected /')/' after sin!\n"); else fprintf(stderr, "Syntax error, expected /')/' after cos!\n"); } Node* val2 = new Node(OP, id, val); return val2; } //Analyze sub-expression that contain power Node *Analyzer::GetPow() { Node* val = GetP(); // Get (x) Node* total; while(*s == '^') { if(val == NULL) { fprintf(stderr, "Syntax error, expected correct expression before ^!\n"); return NULL; } s++; Node* val2 = GetP(); // Get (x) if(val2 == NULL) { fprintf(stderr, "Syntax error, expected correct expression after ^!\n"); delete val; val = NULL; return NULL; } total = new Node(OP, '^', val, val2); val = total; } return val; } Node *Analyzer::GetL() { Node* val; if(strncmp("ln", s, 2) == 0) { s += 2; } else return NULL; if(*s++ != '(') fprintf(stderr, "Syntax error, expected /'(/' after ln!\n"); val = GetE(); //Get x+y or x-y if(val == NULL) fprintf(stderr, "Syntax error, expected correct expression after \"ln(\"!\n"); if(*s++ != ')') fprintf(stderr, "Syntax error, expected /')/' after ln!\n"); Node* val2 = new Node(OP, 'l', val); return val2; }
[ "Komarov.A@phystech.edu" ]
Komarov.A@phystech.edu
ecd3dd429ca7061f2d2eb54728fb5db277ebf6e6
4a17ffbbad80656dd7303dbba247d85cd937964e
/662-MaxWidthOfBiTree/bfsOpt.cpp
37f747d1c68960d94d30640f9c3960ab0d1b49ad
[]
no_license
ZephyrLFY/Leetcode
0dbff7816076a8a40f52a1a22fe236d5b4fede19
2fa8b3e25d9895ab1ccd795568903fc48d352e33
refs/heads/master
2021-03-08T05:45:39.657804
2020-12-15T17:50:30
2020-12-15T17:50:30
246,322,611
0
0
null
null
null
null
UTF-8
C++
false
false
1,101
cpp
#include "../cppLib.h" #include <list> struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) {} }; class Solution { public: int widthOfBinaryTree(TreeNode* root) { if (!root) return 0; double res = 1; queue<TreeNode*> queue; queue.push(root); list<double> list; list.push_back(1); while (!queue.empty()) { int size = queue.size(); for (int i = 0; i < size; ++i) { TreeNode* cur = queue.front(); queue.pop(); double curDep = list.front(); list.pop_front(); if (cur->left) { queue.push(cur->left); list.push_back(2 * curDep); } if (cur->right) { queue.push(cur->right); list.push_back(2 * curDep + 1); } } if (list.size() > 1) res = max(res, list.back() - list.front() + 1); } return res; } };
[ "conpheedence@gmail.com" ]
conpheedence@gmail.com
f1f6bf48cf0a24a59aa3169510feba4efb20af97
a3d660495145e2dbeefabf1f76b5d2c690992c50
/Native/Live2DCubismFrameworkJNI/math/moe_leekcake_live2dforjvm_framework_jni_math_CubismMatrix44JNI.cpp
5136162b51392e5121e1a6bea220a47a16622d21
[ "MIT" ]
permissive
leekcake/Live2D-for-JVM
ea24010ccb37941b5a014cb9182189d72800dff5
686931131b43a1a1c0a6ca6cf01839b28876af2f
refs/heads/master
2021-05-11T17:28:38.707819
2019-01-15T11:39:54
2019-01-15T11:39:54
117,797,529
13
0
null
null
null
null
UTF-8
C++
false
false
7,073
cpp
#include <jni.h> #include <Math/CubismMatrix44.hpp> #include "moe_leekcake_live2dforjvm_framework_jni_math_CubismMatrix44JNI.h" using namespace Live2D::Cubism::Framework; /* * Class: moe_leekcake_live2dforjvm_framework_jni_math_CubismMatrix44JNI * Method: Construct * Signature: ()J */ JNIEXPORT jlong JNICALL Java_moe_leekcake_live2dforjvm_framework_jni_math_CubismMatrix44JNI_Construct (JNIEnv * env, jclass obj) { return (jlong) new CubismMatrix44(); } /* * Class: moe_leekcake_live2dforjvm_framework_jni_math_CubismMatrix44JNI * Method: Deconstruct * Signature: (J)V */ JNIEXPORT void JNICALL Java_moe_leekcake_live2dforjvm_framework_jni_math_CubismMatrix44JNI_Deconstruct (JNIEnv * env, jclass obj, jlong matrix) { delete (CubismMatrix44*)matrix; } /* * Class: moe_leekcake_live2dforjvm_framework_jni_math_CubismMatrix44JNI * Method: LoadIdentity * Signature: (J)V */ JNIEXPORT void JNICALL Java_moe_leekcake_live2dforjvm_framework_jni_math_CubismMatrix44JNI_LoadIdentity (JNIEnv * env, jclass obj, jlong matrix) { ((CubismMatrix44*)matrix)->LoadIdentity(); } /* * Class: moe_leekcake_live2dforjvm_framework_jni_math_CubismMatrix44JNI * Method: GetArray * Signature: (J)[F */ JNIEXPORT jfloatArray JNICALL Java_moe_leekcake_live2dforjvm_framework_jni_math_CubismMatrix44JNI_GetArray (JNIEnv * env, jclass obj, jlong matrix) { jfloatArray result = env->NewFloatArray(16); csmFloat32* arr = ((CubismMatrix44*)matrix)->GetArray(); env->SetFloatArrayRegion(result, 0, 16, arr); return result; } /* * Class: moe_leekcake_live2dforjvm_framework_jni_math_CubismMatrix44JNI * Method: SetMatrix * Signature: (J[F)V */ JNIEXPORT void JNICALL Java_moe_leekcake_live2dforjvm_framework_jni_math_CubismMatrix44JNI_SetMatrix (JNIEnv * env, jclass obj, jlong matrix, jfloatArray arr) { ((CubismMatrix44*)matrix)->SetMatrix(env->GetFloatArrayElements(arr, false)); } /* * Class: moe_leekcake_live2dforjvm_framework_jni_math_CubismMatrix44JNI * Method: GetScaleX * Signature: (J)F */ JNIEXPORT jfloat JNICALL Java_moe_leekcake_live2dforjvm_framework_jni_math_CubismMatrix44JNI_GetScaleX (JNIEnv * env, jclass obj, jlong matrix) { return ((CubismMatrix44*)matrix)->GetScaleX(); } /* * Class: moe_leekcake_live2dforjvm_framework_jni_math_CubismMatrix44JNI * Method: GetScaleY * Signature: (J)F */ JNIEXPORT jfloat JNICALL Java_moe_leekcake_live2dforjvm_framework_jni_math_CubismMatrix44JNI_GetScaleY (JNIEnv * env, jclass obj, jlong matrix) { return ((CubismMatrix44*)matrix)->GetScaleY(); } /* * Class: moe_leekcake_live2dforjvm_framework_jni_math_CubismMatrix44JNI * Method: GetTranslateX * Signature: (J)F */ JNIEXPORT jfloat JNICALL Java_moe_leekcake_live2dforjvm_framework_jni_math_CubismMatrix44JNI_GetTranslateX (JNIEnv * env, jclass obj, jlong matrix) { return ((CubismMatrix44*)matrix)->GetTranslateX(); } /* * Class: moe_leekcake_live2dforjvm_framework_jni_math_CubismMatrix44JNI * Method: GetTranslateY * Signature: (J)F */ JNIEXPORT jfloat JNICALL Java_moe_leekcake_live2dforjvm_framework_jni_math_CubismMatrix44JNI_GetTranslateY (JNIEnv * env, jclass obj, jlong matrix) { return ((CubismMatrix44*)matrix)->GetTranslateY(); } /* * Class: moe_leekcake_live2dforjvm_framework_jni_math_CubismMatrix44JNI * Method: TransformX * Signature: (JJ)V */ JNIEXPORT jfloat JNICALL Java_moe_leekcake_live2dforjvm_framework_jni_math_CubismMatrix44JNI_TransformX (JNIEnv * env, jclass obj, jlong matrix, jfloat x) { return ((CubismMatrix44*)matrix)->TransformX(x); } /* * Class: moe_leekcake_live2dforjvm_framework_jni_math_CubismMatrix44JNI * Method: TransformY * Signature: (JJ)V */ JNIEXPORT jfloat JNICALL Java_moe_leekcake_live2dforjvm_framework_jni_math_CubismMatrix44JNI_TransformY (JNIEnv * env, jclass obj, jlong matrix, jfloat y) { return ((CubismMatrix44*)matrix)->TransformY(y); } /* * Class: moe_leekcake_live2dforjvm_framework_jni_math_CubismMatrix44JNI * Method: InvertTransformX * Signature: (JJ)V */ JNIEXPORT jfloat JNICALL Java_moe_leekcake_live2dforjvm_framework_jni_math_CubismMatrix44JNI_InvertTransformX (JNIEnv * env, jclass obj, jlong matrix, jfloat x) { return ((CubismMatrix44*)matrix)->InvertTransformX(x); } /* * Class: moe_leekcake_live2dforjvm_framework_jni_math_CubismMatrix44JNI * Method: InvertTransformY * Signature: (JJ)V */ JNIEXPORT jfloat JNICALL Java_moe_leekcake_live2dforjvm_framework_jni_math_CubismMatrix44JNI_InvertTransformY (JNIEnv * env, jclass obj, jlong matrix, jfloat y) { return ((CubismMatrix44*)matrix)->InvertTransformY(y); } /* * Class: moe_leekcake_live2dforjvm_framework_jni_math_CubismMatrix44JNI * Method: TranslateRelative * Signature: (JFF)V */ JNIEXPORT void JNICALL Java_moe_leekcake_live2dforjvm_framework_jni_math_CubismMatrix44JNI_TranslateRelative (JNIEnv * env, jclass obj, jlong matrix, jfloat x, jfloat y) { ((CubismMatrix44*)matrix)->TranslateRelative(x, y); } /* * Class: moe_leekcake_live2dforjvm_framework_jni_math_CubismMatrix44JNI * Method: Translate * Signature: (JFF)V */ JNIEXPORT void JNICALL Java_moe_leekcake_live2dforjvm_framework_jni_math_CubismMatrix44JNI_Translate (JNIEnv * env, jclass obj, jlong matrix, jfloat x, jfloat y) { ((CubismMatrix44*)matrix)->Translate(x, y); } /* * Class: moe_leekcake_live2dforjvm_framework_jni_math_CubismMatrix44JNI * Method: TranslateX * Signature: (JF)V */ JNIEXPORT void JNICALL Java_moe_leekcake_live2dforjvm_framework_jni_math_CubismMatrix44JNI_TranslateX (JNIEnv * env, jclass obj, jlong matrix, jfloat x) { ((CubismMatrix44*)matrix)->TranslateX(x); } /* * Class: moe_leekcake_live2dforjvm_framework_jni_math_CubismMatrix44JNI * Method: TranslateY * Signature: (JF)V */ JNIEXPORT void JNICALL Java_moe_leekcake_live2dforjvm_framework_jni_math_CubismMatrix44JNI_TranslateY (JNIEnv * env, jclass obj, jlong matrix, jfloat y) { ((CubismMatrix44*)matrix)->TranslateY(y); } /* * Class: moe_leekcake_live2dforjvm_framework_jni_math_CubismMatrix44JNI * Method: ScaleRelative * Signature: (JFF)V */ JNIEXPORT void JNICALL Java_moe_leekcake_live2dforjvm_framework_jni_math_CubismMatrix44JNI_ScaleRelative (JNIEnv * env, jclass obj, jlong matrix, jfloat x, jfloat y) { ((CubismMatrix44*)matrix)->ScaleRelative(x, y); } /* * Class: moe_leekcake_live2dforjvm_framework_jni_math_CubismMatrix44JNI * Method: Scale * Signature: (JFF)V */ JNIEXPORT void JNICALL Java_moe_leekcake_live2dforjvm_framework_jni_math_CubismMatrix44JNI_Scale (JNIEnv * env, jclass obj, jlong matrix, jfloat x, jfloat y) { ((CubismMatrix44*)matrix)->Scale(x, y); } /* * Class: moe_leekcake_live2dforjvm_framework_jni_math_CubismMatrix44JNI * Method: MultiplyByMatrix * Signature: (JJ)V */ JNIEXPORT void JNICALL Java_moe_leekcake_live2dforjvm_framework_jni_math_CubismMatrix44JNI_MultiplyByMatrix (JNIEnv * env, jclass obj, jlong matrix, jlong anotherMatrix) { ((CubismMatrix44*)matrix)->MultiplyByMatrix(((CubismMatrix44*)anotherMatrix)); }
[ "fkdlxmslrx@gmail.com" ]
fkdlxmslrx@gmail.com
83dc107fb50323afd727d53223990d221a027e8f
6838efa75ba5de45b55fd45932750a054732f80d
/net/quic/crypto/crypto_handshake_test.cc
67d2caba4eb87b5a2e5f2208432e91ccb1b4ce0f
[ "BSD-3-Clause" ]
permissive
Sidney84/pa-chromium
3436ef9d5c786ce7f11456811143ee6db1f063f7
1816ff80336a6efd1616f9e936880af460b1e105
refs/heads/master
2021-01-15T20:48:51.636457
2013-07-11T17:09:48
2013-07-12T16:16:24
null
0
0
null
null
null
null
UTF-8
C++
false
false
10,791
cc
// Copyright (c) 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "net/quic/crypto/crypto_handshake.h" #include <stdarg.h> #include "base/stl_util.h" #include "net/quic/crypto/aes_128_gcm_12_encrypter.h" #include "net/quic/crypto/crypto_server_config.h" #include "net/quic/crypto/crypto_server_config_protobuf.h" #include "net/quic/crypto/quic_random.h" #include "net/quic/quic_time.h" #include "net/quic/test_tools/mock_clock.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" using base::StringPiece; using std::make_pair; using std::map; using std::pair; using std::string; using std::vector; namespace net { namespace test { class QuicCryptoServerConfigPeer { public: explicit QuicCryptoServerConfigPeer(QuicCryptoServerConfig* server_config) : server_config_(server_config) {} string NewSourceAddressToken(IPEndPoint ip, QuicRandom* rand, QuicWallTime now) { return server_config_->NewSourceAddressToken(ip, rand, now); } bool ValidateSourceAddressToken(StringPiece srct, IPEndPoint ip, QuicWallTime now) { return server_config_->ValidateSourceAddressToken(srct, ip, now); } // CheckConfigs compares the state of the Configs in |server_config_| to the // description given as arguments. The arguments are given as NULL-terminated // pairs. The first of each pair is the server config ID of a Config. The // second is a boolean describing whether the config is the primary. For // example: // CheckConfigs(NULL); // checks that no Configs are loaded. // // // Checks that exactly three Configs are loaded with the given IDs and // // status. // CheckConfigs( // "id1", false, // "id2", true, // "id3", false, // NULL); void CheckConfigs(const char* server_config_id1, ...) { va_list ap; va_start(ap, server_config_id1); vector<pair<ServerConfigID, bool> > expected; bool first = true; for (;;) { const char* server_config_id; if (first) { server_config_id = server_config_id1; first = false; } else { server_config_id = va_arg(ap, const char*); } if (!server_config_id) { break; } // varargs will promote the value to an int so we have to read that from // the stack and cast down. const bool is_primary = static_cast<bool>(va_arg(ap, int)); expected.push_back(make_pair(server_config_id, is_primary)); } va_end(ap); base::AutoLock locked(server_config_->configs_lock_); ASSERT_EQ(expected.size(), server_config_->configs_.size()) << ConfigsDebug(); for (QuicCryptoServerConfig::ConfigMap::const_iterator i = server_config_->configs_.begin(); i != server_config_->configs_.end(); ++i) { bool found = false; for (vector<pair<ServerConfigID, bool> >::iterator j = expected.begin(); j != expected.end(); ++j) { if (i->first == j->first && i->second->is_primary == j->second) { found = true; j->first.clear(); break; } } ASSERT_TRUE(found) << "Failed to find match for " << i->first << " in configs:\n" << ConfigsDebug(); } } // ConfigsDebug returns a string that contains debugging information about // the set of Configs loaded in |server_config_| and their status. // ConfigsDebug() should be called after acquiring // server_config_->configs_lock_. string ConfigsDebug() { if (server_config_->configs_.empty()) { return "No Configs in QuicCryptoServerConfig"; } string s; for (QuicCryptoServerConfig::ConfigMap::const_iterator i = server_config_->configs_.begin(); i != server_config_->configs_.end(); ++i) { const scoped_refptr<QuicCryptoServerConfig::Config> config = i->second; if (config->is_primary) { s += "(primary) "; } else { s += " "; } s += config->id; s += "\n"; } return s; } void SelectNewPrimaryConfig(int seconds) { base::AutoLock locked(server_config_->configs_lock_); server_config_->SelectNewPrimaryConfig( QuicWallTime::FromUNIXSeconds(seconds)); } private: const QuicCryptoServerConfig* server_config_; }; TEST(QuicCryptoServerConfigTest, ServerConfig) { QuicRandom* rand = QuicRandom::GetInstance(); QuicCryptoServerConfig server(QuicCryptoServerConfig::TESTING, rand); MockClock clock; scoped_ptr<CryptoHandshakeMessage>( server.AddDefaultConfig(rand, &clock, QuicCryptoServerConfig::ConfigOptions())); } TEST(QuicCryptoServerConfigTest, SourceAddressTokens) { if (!Aes128Gcm12Encrypter::IsSupported()) { LOG(INFO) << "AES GCM not supported. Test skipped."; return; } QuicRandom* rand = QuicRandom::GetInstance(); QuicCryptoServerConfig server(QuicCryptoServerConfig::TESTING, rand); IPAddressNumber ip; CHECK(ParseIPLiteralToNumber("192.0.2.33", &ip)); IPEndPoint ip4 = IPEndPoint(ip, 1); CHECK(ParseIPLiteralToNumber("2001:db8:0::42", &ip)); IPEndPoint ip6 = IPEndPoint(ip, 2); MockClock clock; clock.AdvanceTime(QuicTime::Delta::FromSeconds(1000000)); QuicCryptoServerConfigPeer peer(&server); QuicWallTime now = clock.WallNow(); const QuicWallTime original_time = now; const string token4 = peer.NewSourceAddressToken(ip4, rand, now); const string token6 = peer.NewSourceAddressToken(ip6, rand, now); EXPECT_TRUE(peer.ValidateSourceAddressToken(token4, ip4, now)); EXPECT_FALSE(peer.ValidateSourceAddressToken(token4, ip6, now)); EXPECT_TRUE(peer.ValidateSourceAddressToken(token6, ip6, now)); now = original_time.Add(QuicTime::Delta::FromSeconds(86400 * 7)); EXPECT_FALSE(peer.ValidateSourceAddressToken(token4, ip4, now)); now = original_time.Subtract(QuicTime::Delta::FromSeconds(3600 * 2)); EXPECT_FALSE(peer.ValidateSourceAddressToken(token4, ip4, now)); } class CryptoServerConfigsTest : public ::testing::Test { public: CryptoServerConfigsTest() : rand_(QuicRandom::GetInstance()), config_(QuicCryptoServerConfig::TESTING, rand_), test_peer_(&config_) {} virtual void SetUp() { clock_.AdvanceTime(QuicTime::Delta::FromSeconds(1000)); } // SetConfigs constructs suitable config protobufs and calls SetConfigs on // |config_|. The arguments are given as NULL-terminated pairs. The first of // each pair is the server config ID of a Config. The second is the // |primary_time| of that Config, given in epoch seconds. (Although note // that, in these tests, time is set to 1000 seconds since the epoch.) For // example: // SetConfigs(NULL); // calls |config_.SetConfigs| with no protobufs. // // // Calls |config_.SetConfigs| with two protobufs: one for a Config with // // a |primary_time| of 900, and another with a |primary_time| of 1000. // CheckConfigs( // "id1", 900, // "id2", 1000, // NULL); // // If the server config id starts with "INVALID" then the generated protobuf // will be invalid. void SetConfigs(const char* server_config_id1, ...) { va_list ap; va_start(ap, server_config_id1); bool has_invalid = false; vector<QuicServerConfigProtobuf*> protobufs; bool first = true; for (;;) { const char* server_config_id; if (first) { server_config_id = server_config_id1; first = false; } else { server_config_id = va_arg(ap, const char*); } if (!server_config_id) { break; } int primary_time = va_arg(ap, int); QuicCryptoServerConfig::ConfigOptions options; options.id = server_config_id; QuicServerConfigProtobuf* protobuf( QuicCryptoServerConfig::DefaultConfig(rand_, &clock_, options)); protobuf->set_primary_time(primary_time); if (string(server_config_id).find("INVALID") == 0) { protobuf->clear_key(); has_invalid = true; } protobufs.push_back(protobuf); } ASSERT_EQ(!has_invalid, config_.SetConfigs(protobufs, clock_.WallNow())); STLDeleteElements(&protobufs); } protected: QuicRandom* const rand_; MockClock clock_; QuicCryptoServerConfig config_; QuicCryptoServerConfigPeer test_peer_; }; TEST_F(CryptoServerConfigsTest, NoConfigs) { test_peer_.CheckConfigs(NULL); } TEST_F(CryptoServerConfigsTest, MakePrimaryFirst) { // Make sure that "b" is primary even though "a" comes first. SetConfigs("a", 1100, "b", 900, NULL); test_peer_.CheckConfigs( "a", false, "b", true, NULL); } TEST_F(CryptoServerConfigsTest, MakePrimarySecond) { // Make sure that a remains primary after b is added. SetConfigs("a", 900, "b", 1100, NULL); test_peer_.CheckConfigs( "a", true, "b", false, NULL); } TEST_F(CryptoServerConfigsTest, Delete) { // Ensure that configs get deleted when removed. SetConfigs("a", 800, "b", 900, "c", 1100, NULL); SetConfigs("b", 900, "c", 1100, NULL); test_peer_.CheckConfigs( "b", true, "c", false, NULL); } TEST_F(CryptoServerConfigsTest, DontDeletePrimary) { // Ensure that the primary config isn't deleted when removed. SetConfigs("a", 800, "b", 900, "c", 1100, NULL); SetConfigs("a", 800, "c", 1100, NULL); test_peer_.CheckConfigs( "a", false, "b", true, "c", false, NULL); } TEST_F(CryptoServerConfigsTest, AdvancePrimary) { // Check that a new primary config is enabled at the right time. SetConfigs("a", 900, "b", 1100, NULL); test_peer_.SelectNewPrimaryConfig(1000); test_peer_.CheckConfigs( "a", true, "b", false, NULL); test_peer_.SelectNewPrimaryConfig(1101); test_peer_.CheckConfigs( "a", false, "b", true, NULL); } TEST_F(CryptoServerConfigsTest, InvalidConfigs) { // Ensure that invalid configs don't change anything. SetConfigs("a", 800, "b", 900, "c", 1100, NULL); test_peer_.CheckConfigs( "a", false, "b", true, "c", false, NULL); SetConfigs("a", 800, "c", 1100, "INVALID1", 1000, NULL); test_peer_.CheckConfigs( "a", false, "b", true, "c", false, NULL); } } // namespace test } // namespace net
[ "rtenneti@chromium.org@0039d316-1c4b-4281-b951-d872f2087c98" ]
rtenneti@chromium.org@0039d316-1c4b-4281-b951-d872f2087c98
3f3f15ee353b9d4d12f83101b49088d8fab95fb0
6c77cf237697f252d48b287ae60ccf61b3220044
/aws-cpp-sdk-iot/source/model/DescribeStreamRequest.cpp
21c9b2c6e62e07050edccda404b411b96575ba59
[ "MIT", "Apache-2.0", "JSON" ]
permissive
Gohan/aws-sdk-cpp
9a9672de05a96b89d82180a217ccb280537b9e8e
51aa785289d9a76ac27f026d169ddf71ec2d0686
refs/heads/master
2020-03-26T18:48:43.043121
2018-11-09T08:44:41
2018-11-09T08:44:41
145,232,234
1
0
Apache-2.0
2018-08-30T13:42:27
2018-08-18T15:42:39
C++
UTF-8
C++
false
false
958
cpp
/* * Copyright 2010-2017 Amazon.com, Inc. or its affiliates. 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. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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 <aws/iot/model/DescribeStreamRequest.h> #include <aws/core/utils/json/JsonSerializer.h> #include <utility> using namespace Aws::IoT::Model; using namespace Aws::Utils::Json; using namespace Aws::Utils; DescribeStreamRequest::DescribeStreamRequest() : m_streamIdHasBeenSet(false) { } Aws::String DescribeStreamRequest::SerializePayload() const { return ""; }
[ "henso@amazon.com" ]
henso@amazon.com
7988330deb54296797d6327f6dd8011b98a11b1b
bb2381d2c243729a063dd137b38c13905427790f
/Source/NodeGraphLink.h
7672e6cab0f21b4d97e7e4a1c754534c141a1b62
[ "MIT" ]
permissive
JTippetts/U3DTerrainEditor
1840db2228d41f33ac2fbe8c7e6c1d6be0015ceb
90625d5ad9fb1720f10b8d054aa67d55465c7dff
refs/heads/master
2022-11-23T20:23:36.439180
2022-11-22T19:58:48
2022-11-22T19:58:48
29,431,415
120
41
null
2017-05-02T17:32:36
2015-01-18T16:03:52
HTML
UTF-8
C++
false
false
2,582
h
#ifndef GRAPH_NODE_LINK_H #define GRAPH_NODE_LINK_H #include <Urho3D/UI/BorderImage.h> #include <Urho3D/UI/Button.h> using namespace Urho3D; class NodeGraphLink; class NodeGraphLinkDest; class NodeGraphLinkSource : public Button { URHO3D_OBJECT(NodeGraphLinkSource, Button); public: static void RegisterObject(Context *context); NodeGraphLinkSource(Context *context); //NodeGraphLink *CreateLink(NodeGraphLinkDest *target); void AddLink(NodeGraphLink *link); void RemoveLink(NodeGraphLinkDest *target); void RemoveLink(NodeGraphLink *link); int GetNumLinks(); NodeGraphLink *GetLink(int which); NodeGraphLink *GetLink(NodeGraphLinkDest *target); void SetRoot(UIElement *root); void ClearRoot(); UIElement *GetRoot(); protected: ea::vector<SharedPtr<NodeGraphLink>> links_; UIElement *root_; }; class NodeGraphLinkDest : public Button { URHO3D_OBJECT(NodeGraphLinkDest, Button); public: static void RegisterObject(Context *context); NodeGraphLinkDest(Context *context); void SetLink(NodeGraphLink *link); void ClearLink(); NodeGraphLink *GetLink(); void SetRoot(UIElement *root); void ClearRoot(); UIElement *GetRoot(); protected: WeakPtr<NodeGraphLink> link_; UIElement *root_; }; class NodeGraphLink : public Object { URHO3D_OBJECT(NodeGraphLink, Object); public: static void RegisterObject(Context *context); NodeGraphLink(Context *context); void SetSource(NodeGraphLinkSource *src); void ClearSource(); void SetTarget(NodeGraphLinkDest *dest); void ClearTarget(); NodeGraphLinkSource *GetSource() { return source_; } NodeGraphLinkDest *GetTarget() { return target_; } //void GetBatches(ea::vector<UIBatch>& batches, ea::vector<float>& vertexData, const IntRect& currentScissor); void GetBatch(UIBatch &batch); void SetImageRect(const IntRect &rect); protected: NodeGraphLinkSource *source_; NodeGraphLinkDest *target_; IntRect imageRect_; }; class NodeGraphLinkPane : public BorderImage { URHO3D_OBJECT(NodeGraphLinkPane, BorderImage); public: static void RegisterObject(Context *context); NodeGraphLinkPane(Context *context); NodeGraphLink *CreateLink(NodeGraphLinkSource *source, NodeGraphLinkDest *target); void RemoveLink(NodeGraphLink *link); virtual void GetBatches(ea::vector<UIBatch>& batches, ea::vector<float>& vertexData, const IntRect& currentScissor) override; protected: ea::vector<SharedPtr<NodeGraphLink>> links_; }; #endif
[ "vertexnormal@gmail.com" ]
vertexnormal@gmail.com
9c6e470feb4ea218aff17ed1b5cc660a338b1471
a443c88fef23bbc5dab98e8b0461175f6a8536ea
/CoCaNgua/CoCaNgua/Graphic.cpp
183fe05cec26589b0599aa682906360440cda89a
[]
no_license
thuydx55/CoCaNgua
12be3db1e1664daa102e257e4236588f0c882fb8
81b61f796ffa18ed8573474fd573c3cf5edeb32c
refs/heads/master
2020-05-15T15:06:41.601986
2014-07-14T04:39:31
2014-07-14T04:39:31
8,817,293
1
2
null
null
null
null
UTF-8
C++
false
false
1,345
cpp
#include "Graphic.h" Graphic::Graphic(void) { mAppScene = APP_LOADING; near_height = 0.5; zNear = 1; zFar = 1000; } Graphic& Graphic::inst() { static Graphic Instance; return Instance; } void Graphic::drawString(const char *str, int x, int y, float color[4], void *font) { glPushAttrib(GL_LIGHTING_BIT | GL_CURRENT_BIT); // lighting and color mask glDisable(GL_LIGHTING); // need to disable lighting for proper text color glDisable(GL_TEXTURE_2D); glColor4fv(color); // set text color glRasterPos2i(x, y); // place text position // loop all characters in the string while(*str) { glutBitmapCharacter(font, *str); ++str; } glEnable(GL_TEXTURE_2D); glEnable(GL_LIGHTING); glPopAttrib(); } void Graphic::drawString3D(const char *str, float pos[3], float color[4], void *font) { glPushAttrib(GL_LIGHTING_BIT | GL_CURRENT_BIT); // lighting and color mask glDisable(GL_LIGHTING); // need to disable lighting for proper text color glDisable(GL_TEXTURE_2D); glColor4fv(color); // set text color glRasterPos3fv(pos); // place text position // loop all characters in the string while(*str) { glutBitmapCharacter(font, *str); ++str; } glEnable(GL_TEXTURE_2D); glEnable(GL_LIGHTING); glPopAttrib(); } Graphic::~Graphic(void) { }
[ "thuydx_55@vnu.edu.vn" ]
thuydx_55@vnu.edu.vn
a1ffd73ce7f374c5016f4ba6c8af24acba3a1420
8514a3f47a6edfdc129cb33b777b4c3ffbc592a9
/src/mypackage/src/go_straight.cpp
96a81c5bb4b144818254a1aadb0c7ae4c32b61a1
[]
no_license
coderofchina/catkin_ws
2486b0fcc412762069d4a64ebd309cccc0f8cdd4
dccd9d55bf34e6b1ccef208d803254a2c1a41721
refs/heads/master
2020-04-01T19:25:22.051977
2018-10-18T03:41:38
2018-10-18T03:41:38
153,552,863
0
0
null
null
null
null
UTF-8
C++
false
false
4,918
cpp
#include <ros/ros.h> #include <signal.h> #include <geometry_msgs/Twist.h> #include <tf/transform_listener.h> #include <nav_msgs/Odometry.h> #include <string.h> ros::Publisher cmdVelPub; void shutdown(int sig) { cmdVelPub.publish(geometry_msgs::Twist()); ROS_INFO("odom_out_and_back.cpp ended!"); ros::shutdown(); } int main(int argc, char** argv) { //How fast will we update the robot's movement? double rate = 20; int count = 0;//Loop through the two legs of the trip ros::init(argc, argv, "go_and_back"); std::string topic = "/cmd_vel"; ros::NodeHandle node; cmdVelPub = node.advertise<geometry_msgs::Twist>(topic, 1); //Set the equivalent ROS rate variable ros::Rate loopRate(rate); geometry_msgs::Twist speed; // 控制信号载体 Twist message signal(SIGINT, shutdown); ROS_INFO("odom_out_and_back.cpp start..."); //Set the forward linear speed to 0.2 meters per second 线速度 float linear_speed = 0.2; //Set the travel distance to 1.0 meters 移动距离 float goal_distance = 1.0; //Set the rotation speed to 0.5 radians per second 角速度 float angular_speed = 0.5; //Set the rotation angle to Pi radians (180 degrees) 角位移 double goal_angle = M_PI; //Set the angular tolerance in degrees converted to radians double angular_tolerance = 2.5*M_PI/180; //角度转换成弧度:deg*PI/180 tf::TransformListener listener; tf::StampedTransform transform; //Find out if the robot uses /base_link or /base_footprint std::string odom_frame = "/odom"; std::string base_frame; try { listener.waitForTransform(odom_frame, "/base_footprint", ros::Time(), ros::Duration(2.0) ); base_frame = "/base_footprint"; ROS_INFO("base_frame = /base_footprint"); } catch (tf::TransformException & ex) { try { listener.waitForTransform(odom_frame, "/base_link", ros::Time(), ros::Duration(2.0) ); base_frame = "/base_link"; ROS_INFO("base_frame = /base_link"); } catch (tf::TransformException ex) { ROS_INFO("Cannot find transform between /odom and /base_link or /base_footprint"); cmdVelPub.publish(geometry_msgs::Twist()); ros::shutdown(); } } //Loop once for each leg of the trip while(ros::ok()) { ROS_INFO("go straight...!"); speed.linear.x = linear_speed; // 设置线速度,正为前进,负为后退 //Get the starting position values listener.lookupTransform(odom_frame, base_frame, ros::Time(0), transform); float x_start = transform.getOrigin().x(); float y_start = transform.getOrigin().y(); // Keep track of the distance traveled float distance = 0; while( (distance < goal_distance) && (ros::ok()) ) { //Publish the Twist message and sleep 1 cycle cmdVelPub.publish(speed); loopRate.sleep(); listener.lookupTransform(odom_frame, base_frame, ros::Time(0), transform); //Get the current position float x = transform.getOrigin().x(); float y = transform.getOrigin().y(); //Compute the Euclidean distance from the start distance = sqrt(pow((x - x_start), 2) + pow((y - y_start), 2)); } //Stop the robot before the rotation cmdVelPub.publish(geometry_msgs::Twist()); ros::Duration(1).sleep(); // sleep for a second ROS_INFO("rotation...!"); //Now rotate left roughly 180 degrees speed.linear.x = 0; //Set the angular speed speed.angular.z = angular_speed; // 设置角速度,正为左转,负为右转 //yaw是围绕Y轴旋转,也叫偏航角 //Track the last angle measured double last_angle = fabs(tf::getYaw(transform.getRotation())); //Track how far we have turned double turn_angle = 0; while( (fabs(turn_angle + angular_tolerance) < M_PI) && (ros::ok()) ) { //Publish the Twist message and sleep 1 cycle cmdVelPub.publish(speed); loopRate.sleep(); // Get the current rotation listener.lookupTransform(odom_frame, base_frame, ros::Time(0), transform); //C++: abs()求得是正数的绝对值,fabs()求得是浮点数的绝对值;python:abs(x),参数可以是:负数、正数、浮点数或者长整形 double rotation = fabs(tf::getYaw(transform.getRotation())); //Compute the amount of rotation since the last loop double delta_angle = fabs(rotation - last_angle); //Add to the running total turn_angle += delta_angle; last_angle = rotation; } //Stop the robot before the rotation //Set the angular speed speed.angular.z = 0; cmdVelPub.publish(geometry_msgs::Twist()); ros::Duration(1).sleep(); // sleep for a second } cmdVelPub.publish(geometry_msgs::Twist()); ros::Duration(1).sleep(); // sleep for a second ROS_INFO("odom_out_and_back.cpp ended!"); ros::shutdown(); return 0; }
[ "1793426191@qq.com" ]
1793426191@qq.com
a74f061283b2c3b352fadba73377e49efd94c971
23c4109411bb6490d76430d485c19152c56e037a
/llvm-project/clang-tools-extra/clangd/ClangdLSPServer.cpp
99c2465a579c01ee5ec621b5ba7b9441fd41399b
[ "Apache-2.0", "LLVM-exception", "NCSA" ]
permissive
AlexErf/GPUProject
f9a060e63caec0c07584aa2a2826432dc6cfc0b5
c2740b6ca052436a73d05564187c473a37f362b9
refs/heads/main
2023-02-02T05:41:53.330592
2020-12-14T03:04:19
2020-12-14T03:04:19
310,434,160
2
0
null
null
null
null
UTF-8
C++
false
false
66,830
cpp
//===--- ClangdLSPServer.cpp - LSP server ------------------------*- C++-*-===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// #include "ClangdLSPServer.h" #include "ClangdServer.h" #include "CodeComplete.h" #include "Diagnostics.h" #include "DraftStore.h" #include "GlobalCompilationDatabase.h" #include "Protocol.h" #include "SemanticHighlighting.h" #include "SourceCode.h" #include "TUScheduler.h" #include "URI.h" #include "refactor/Tweak.h" #include "support/Context.h" #include "support/MemoryTree.h" #include "support/Trace.h" #include "clang/Basic/Version.h" #include "clang/Tooling/Core/Replacement.h" #include "llvm/ADT/ArrayRef.h" #include "llvm/ADT/Optional.h" #include "llvm/ADT/ScopeExit.h" #include "llvm/ADT/StringRef.h" #include "llvm/ADT/iterator_range.h" #include "llvm/Support/Allocator.h" #include "llvm/Support/Errc.h" #include "llvm/Support/Error.h" #include "llvm/Support/FormatVariadic.h" #include "llvm/Support/JSON.h" #include "llvm/Support/Path.h" #include "llvm/Support/SHA1.h" #include "llvm/Support/ScopedPrinter.h" #include "llvm/Support/raw_ostream.h" #include <chrono> #include <cstddef> #include <cstdint> #include <functional> #include <memory> #include <mutex> #include <string> #include <vector> namespace clang { namespace clangd { namespace { // Tracks end-to-end latency of high level lsp calls. Measurements are in // seconds. constexpr trace::Metric LSPLatency("lsp_latency", trace::Metric::Distribution, "method_name"); // LSP defines file versions as numbers that increase. // ClangdServer treats them as opaque and therefore uses strings instead. std::string encodeVersion(int64_t LSPVersion) { return llvm::to_string(LSPVersion); } llvm::Optional<int64_t> decodeVersion(llvm::StringRef Encoded) { int64_t Result; if (llvm::to_integer(Encoded, Result, 10)) return Result; if (!Encoded.empty()) // Empty can be e.g. diagnostics on close. elog("unexpected non-numeric version {0}", Encoded); return llvm::None; } /// Transforms a tweak into a code action that would apply it if executed. /// EXPECTS: T.prepare() was called and returned true. CodeAction toCodeAction(const ClangdServer::TweakRef &T, const URIForFile &File, Range Selection) { CodeAction CA; CA.title = T.Title; CA.kind = T.Kind.str(); // This tweak may have an expensive second stage, we only run it if the user // actually chooses it in the UI. We reply with a command that would run the // corresponding tweak. // FIXME: for some tweaks, computing the edits is cheap and we could send them // directly. CA.command.emplace(); CA.command->title = T.Title; CA.command->command = std::string(Command::CLANGD_APPLY_TWEAK); CA.command->tweakArgs.emplace(); CA.command->tweakArgs->file = File; CA.command->tweakArgs->tweakID = T.ID; CA.command->tweakArgs->selection = Selection; return CA; } void adjustSymbolKinds(llvm::MutableArrayRef<DocumentSymbol> Syms, SymbolKindBitset Kinds) { for (auto &S : Syms) { S.kind = adjustKindToCapability(S.kind, Kinds); adjustSymbolKinds(S.children, Kinds); } } SymbolKindBitset defaultSymbolKinds() { SymbolKindBitset Defaults; for (size_t I = SymbolKindMin; I <= static_cast<size_t>(SymbolKind::Array); ++I) Defaults.set(I); return Defaults; } CompletionItemKindBitset defaultCompletionItemKinds() { CompletionItemKindBitset Defaults; for (size_t I = CompletionItemKindMin; I <= static_cast<size_t>(CompletionItemKind::Reference); ++I) Defaults.set(I); return Defaults; } // Build a lookup table (HighlightingKind => {TextMate Scopes}), which is sent // to the LSP client. std::vector<std::vector<std::string>> buildHighlightScopeLookupTable() { std::vector<std::vector<std::string>> LookupTable; // HighlightingKind is using as the index. for (int KindValue = 0; KindValue <= (int)HighlightingKind::LastKind; ++KindValue) LookupTable.push_back( {std::string(toTextMateScope((HighlightingKind)(KindValue)))}); return LookupTable; } // Makes sure edits in \p FE are applicable to latest file contents reported by // editor. If not generates an error message containing information about files // that needs to be saved. llvm::Error validateEdits(const DraftStore &DraftMgr, const FileEdits &FE) { size_t InvalidFileCount = 0; llvm::StringRef LastInvalidFile; for (const auto &It : FE) { if (auto Draft = DraftMgr.getDraft(It.first())) { // If the file is open in user's editor, make sure the version we // saw and current version are compatible as this is the text that // will be replaced by editors. if (!It.second.canApplyTo(Draft->Contents)) { ++InvalidFileCount; LastInvalidFile = It.first(); } } } if (!InvalidFileCount) return llvm::Error::success(); if (InvalidFileCount == 1) return error("File must be saved first: {0}", LastInvalidFile); return error("Files must be saved first: {0} (and {1} others)", LastInvalidFile, InvalidFileCount - 1); } } // namespace // MessageHandler dispatches incoming LSP messages. // It handles cross-cutting concerns: // - serializes/deserializes protocol objects to JSON // - logging of inbound messages // - cancellation handling // - basic call tracing // MessageHandler ensures that initialize() is called before any other handler. class ClangdLSPServer::MessageHandler : public Transport::MessageHandler { public: MessageHandler(ClangdLSPServer &Server) : Server(Server) {} bool onNotify(llvm::StringRef Method, llvm::json::Value Params) override { WithContext HandlerContext(handlerContext()); log("<-- {0}", Method); if (Method == "exit") return false; if (!Server.Server) { elog("Notification {0} before initialization", Method); } else if (Method == "$/cancelRequest") { onCancel(std::move(Params)); } else if (auto Handler = Notifications.lookup(Method)) { Handler(std::move(Params)); Server.maybeExportMemoryProfile(); } else { log("unhandled notification {0}", Method); } return true; } bool onCall(llvm::StringRef Method, llvm::json::Value Params, llvm::json::Value ID) override { WithContext HandlerContext(handlerContext()); // Calls can be canceled by the client. Add cancellation context. WithContext WithCancel(cancelableRequestContext(ID)); trace::Span Tracer(Method, LSPLatency); SPAN_ATTACH(Tracer, "Params", Params); ReplyOnce Reply(ID, Method, &Server, Tracer.Args); log("<-- {0}({1})", Method, ID); if (!Server.Server && Method != "initialize") { elog("Call {0} before initialization.", Method); Reply(llvm::make_error<LSPError>("server not initialized", ErrorCode::ServerNotInitialized)); } else if (auto Handler = Calls.lookup(Method)) Handler(std::move(Params), std::move(Reply)); else Reply(llvm::make_error<LSPError>("method not found", ErrorCode::MethodNotFound)); return true; } bool onReply(llvm::json::Value ID, llvm::Expected<llvm::json::Value> Result) override { WithContext HandlerContext(handlerContext()); Callback<llvm::json::Value> ReplyHandler = nullptr; if (auto IntID = ID.getAsInteger()) { std::lock_guard<std::mutex> Mutex(CallMutex); // Find a corresponding callback for the request ID; for (size_t Index = 0; Index < ReplyCallbacks.size(); ++Index) { if (ReplyCallbacks[Index].first == *IntID) { ReplyHandler = std::move(ReplyCallbacks[Index].second); ReplyCallbacks.erase(ReplyCallbacks.begin() + Index); // remove the entry break; } } } if (!ReplyHandler) { // No callback being found, use a default log callback. ReplyHandler = [&ID](llvm::Expected<llvm::json::Value> Result) { elog("received a reply with ID {0}, but there was no such call", ID); if (!Result) llvm::consumeError(Result.takeError()); }; } // Log and run the reply handler. if (Result) { log("<-- reply({0})", ID); ReplyHandler(std::move(Result)); } else { auto Err = Result.takeError(); log("<-- reply({0}) error: {1}", ID, Err); ReplyHandler(std::move(Err)); } return true; } // Bind an LSP method name to a call. template <typename Param, typename Result> void bind(const char *Method, void (ClangdLSPServer::*Handler)(const Param &, Callback<Result>)) { Calls[Method] = [Method, Handler, this](llvm::json::Value RawParams, ReplyOnce Reply) { auto P = parse<Param>(RawParams, Method, "request"); if (!P) return Reply(P.takeError()); (Server.*Handler)(*P, std::move(Reply)); }; } // Bind a reply callback to a request. The callback will be invoked when // clangd receives the reply from the LSP client. // Return a call id of the request. llvm::json::Value bindReply(Callback<llvm::json::Value> Reply) { llvm::Optional<std::pair<int, Callback<llvm::json::Value>>> OldestCB; int ID; { std::lock_guard<std::mutex> Mutex(CallMutex); ID = NextCallID++; ReplyCallbacks.emplace_back(ID, std::move(Reply)); // If the queue overflows, we assume that the client didn't reply the // oldest request, and run the corresponding callback which replies an // error to the client. if (ReplyCallbacks.size() > MaxReplayCallbacks) { elog("more than {0} outstanding LSP calls, forgetting about {1}", MaxReplayCallbacks, ReplyCallbacks.front().first); OldestCB = std::move(ReplyCallbacks.front()); ReplyCallbacks.pop_front(); } } if (OldestCB) OldestCB->second( error("failed to receive a client reply for request ({0})", OldestCB->first)); return ID; } // Bind an LSP method name to a notification. template <typename Param> void bind(const char *Method, void (ClangdLSPServer::*Handler)(const Param &)) { Notifications[Method] = [Method, Handler, this](llvm::json::Value RawParams) { llvm::Expected<Param> P = parse<Param>(RawParams, Method, "request"); if (!P) return llvm::consumeError(P.takeError()); trace::Span Tracer(Method, LSPLatency); SPAN_ATTACH(Tracer, "Params", RawParams); (Server.*Handler)(*P); }; } private: // Function object to reply to an LSP call. // Each instance must be called exactly once, otherwise: // - the bug is logged, and (in debug mode) an assert will fire // - if there was no reply, an error reply is sent // - if there were multiple replies, only the first is sent class ReplyOnce { std::atomic<bool> Replied = {false}; std::chrono::steady_clock::time_point Start; llvm::json::Value ID; std::string Method; ClangdLSPServer *Server; // Null when moved-from. llvm::json::Object *TraceArgs; public: ReplyOnce(const llvm::json::Value &ID, llvm::StringRef Method, ClangdLSPServer *Server, llvm::json::Object *TraceArgs) : Start(std::chrono::steady_clock::now()), ID(ID), Method(Method), Server(Server), TraceArgs(TraceArgs) { assert(Server); } ReplyOnce(ReplyOnce &&Other) : Replied(Other.Replied.load()), Start(Other.Start), ID(std::move(Other.ID)), Method(std::move(Other.Method)), Server(Other.Server), TraceArgs(Other.TraceArgs) { Other.Server = nullptr; } ReplyOnce &operator=(ReplyOnce &&) = delete; ReplyOnce(const ReplyOnce &) = delete; ReplyOnce &operator=(const ReplyOnce &) = delete; ~ReplyOnce() { // There's one legitimate reason to never reply to a request: clangd's // request handler send a call to the client (e.g. applyEdit) and the // client never replied. In this case, the ReplyOnce is owned by // ClangdLSPServer's reply callback table and is destroyed along with the // server. We don't attempt to send a reply in this case, there's little // to be gained from doing so. if (Server && !Server->IsBeingDestroyed && !Replied) { elog("No reply to message {0}({1})", Method, ID); assert(false && "must reply to all calls!"); (*this)(llvm::make_error<LSPError>("server failed to reply", ErrorCode::InternalError)); } } void operator()(llvm::Expected<llvm::json::Value> Reply) { assert(Server && "moved-from!"); if (Replied.exchange(true)) { elog("Replied twice to message {0}({1})", Method, ID); assert(false && "must reply to each call only once!"); return; } auto Duration = std::chrono::steady_clock::now() - Start; if (Reply) { log("--> reply:{0}({1}) {2:ms}", Method, ID, Duration); if (TraceArgs) (*TraceArgs)["Reply"] = *Reply; std::lock_guard<std::mutex> Lock(Server->TranspWriter); Server->Transp.reply(std::move(ID), std::move(Reply)); } else { llvm::Error Err = Reply.takeError(); log("--> reply:{0}({1}) {2:ms}, error: {3}", Method, ID, Duration, Err); if (TraceArgs) (*TraceArgs)["Error"] = llvm::to_string(Err); std::lock_guard<std::mutex> Lock(Server->TranspWriter); Server->Transp.reply(std::move(ID), std::move(Err)); } } }; llvm::StringMap<std::function<void(llvm::json::Value)>> Notifications; llvm::StringMap<std::function<void(llvm::json::Value, ReplyOnce)>> Calls; // Method calls may be cancelled by ID, so keep track of their state. // This needs a mutex: handlers may finish on a different thread, and that's // when we clean up entries in the map. mutable std::mutex RequestCancelersMutex; llvm::StringMap<std::pair<Canceler, /*Cookie*/ unsigned>> RequestCancelers; unsigned NextRequestCookie = 0; // To disambiguate reused IDs, see below. void onCancel(const llvm::json::Value &Params) { const llvm::json::Value *ID = nullptr; if (auto *O = Params.getAsObject()) ID = O->get("id"); if (!ID) { elog("Bad cancellation request: {0}", Params); return; } auto StrID = llvm::to_string(*ID); std::lock_guard<std::mutex> Lock(RequestCancelersMutex); auto It = RequestCancelers.find(StrID); if (It != RequestCancelers.end()) It->second.first(); // Invoke the canceler. } Context handlerContext() const { return Context::current().derive( kCurrentOffsetEncoding, Server.Opts.Encoding.getValueOr(OffsetEncoding::UTF16)); } // We run cancelable requests in a context that does two things: // - allows cancellation using RequestCancelers[ID] // - cleans up the entry in RequestCancelers when it's no longer needed // If a client reuses an ID, the last wins and the first cannot be canceled. Context cancelableRequestContext(const llvm::json::Value &ID) { auto Task = cancelableTask( /*Reason=*/static_cast<int>(ErrorCode::RequestCancelled)); auto StrID = llvm::to_string(ID); // JSON-serialize ID for map key. auto Cookie = NextRequestCookie++; // No lock, only called on main thread. { std::lock_guard<std::mutex> Lock(RequestCancelersMutex); RequestCancelers[StrID] = {std::move(Task.second), Cookie}; } // When the request ends, we can clean up the entry we just added. // The cookie lets us check that it hasn't been overwritten due to ID // reuse. return Task.first.derive(llvm::make_scope_exit([this, StrID, Cookie] { std::lock_guard<std::mutex> Lock(RequestCancelersMutex); auto It = RequestCancelers.find(StrID); if (It != RequestCancelers.end() && It->second.second == Cookie) RequestCancelers.erase(It); })); } // The maximum number of callbacks held in clangd. // // We bound the maximum size to the pending map to prevent memory leakage // for cases where LSP clients don't reply for the request. // This has to go after RequestCancellers and RequestCancellersMutex since it // can contain a callback that has a cancelable context. static constexpr int MaxReplayCallbacks = 100; mutable std::mutex CallMutex; int NextCallID = 0; /* GUARDED_BY(CallMutex) */ std::deque<std::pair</*RequestID*/ int, /*ReplyHandler*/ Callback<llvm::json::Value>>> ReplyCallbacks; /* GUARDED_BY(CallMutex) */ ClangdLSPServer &Server; }; constexpr int ClangdLSPServer::MessageHandler::MaxReplayCallbacks; // call(), notify(), and reply() wrap the Transport, adding logging and locking. void ClangdLSPServer::callRaw(StringRef Method, llvm::json::Value Params, Callback<llvm::json::Value> CB) { auto ID = MsgHandler->bindReply(std::move(CB)); log("--> {0}({1})", Method, ID); std::lock_guard<std::mutex> Lock(TranspWriter); Transp.call(Method, std::move(Params), ID); } void ClangdLSPServer::notify(llvm::StringRef Method, llvm::json::Value Params) { log("--> {0}", Method); std::lock_guard<std::mutex> Lock(TranspWriter); Transp.notify(Method, std::move(Params)); } static std::vector<llvm::StringRef> semanticTokenTypes() { std::vector<llvm::StringRef> Types; for (unsigned I = 0; I <= static_cast<unsigned>(HighlightingKind::LastKind); ++I) Types.push_back(toSemanticTokenType(static_cast<HighlightingKind>(I))); return Types; } void ClangdLSPServer::onInitialize(const InitializeParams &Params, Callback<llvm::json::Value> Reply) { // Determine character encoding first as it affects constructed ClangdServer. if (Params.capabilities.offsetEncoding && !Opts.Encoding) { Opts.Encoding = OffsetEncoding::UTF16; // fallback for (OffsetEncoding Supported : *Params.capabilities.offsetEncoding) if (Supported != OffsetEncoding::UnsupportedEncoding) { Opts.Encoding = Supported; break; } } Opts.TheiaSemanticHighlighting = Params.capabilities.TheiaSemanticHighlighting; if (Params.capabilities.TheiaSemanticHighlighting && Params.capabilities.SemanticTokens) { log("Client supports legacy semanticHighlights notification and standard " "semanticTokens request, choosing the latter (no notifications)."); Opts.TheiaSemanticHighlighting = false; } if (Params.rootUri && *Params.rootUri) Opts.WorkspaceRoot = std::string(Params.rootUri->file()); else if (Params.rootPath && !Params.rootPath->empty()) Opts.WorkspaceRoot = *Params.rootPath; if (Server) return Reply(llvm::make_error<LSPError>("server already initialized", ErrorCode::InvalidRequest)); if (const auto &Dir = Params.initializationOptions.compilationDatabasePath) Opts.CompileCommandsDir = Dir; if (Opts.UseDirBasedCDB) { BaseCDB = std::make_unique<DirectoryBasedGlobalCompilationDatabase>( Opts.CompileCommandsDir); BaseCDB = getQueryDriverDatabase(llvm::makeArrayRef(Opts.QueryDriverGlobs), std::move(BaseCDB)); } auto Mangler = CommandMangler::detect(); if (Opts.ResourceDir) Mangler.ResourceDir = *Opts.ResourceDir; CDB.emplace(BaseCDB.get(), Params.initializationOptions.fallbackFlags, tooling::ArgumentsAdjuster(std::move(Mangler))); { // Switch caller's context with LSPServer's background context. Since we // rather want to propagate information from LSPServer's context into the // Server, CDB, etc. WithContext MainContext(BackgroundContext.clone()); llvm::Optional<WithContextValue> WithOffsetEncoding; if (Opts.Encoding) WithOffsetEncoding.emplace(kCurrentOffsetEncoding, *Opts.Encoding); Server.emplace(*CDB, TFS, Opts, static_cast<ClangdServer::Callbacks *>(this)); } applyConfiguration(Params.initializationOptions.ConfigSettings); Opts.CodeComplete.EnableSnippets = Params.capabilities.CompletionSnippets; Opts.CodeComplete.IncludeFixIts = Params.capabilities.CompletionFixes; if (!Opts.CodeComplete.BundleOverloads.hasValue()) Opts.CodeComplete.BundleOverloads = Params.capabilities.HasSignatureHelp; Opts.CodeComplete.DocumentationFormat = Params.capabilities.CompletionDocumentationFormat; DiagOpts.EmbedFixesInDiagnostics = Params.capabilities.DiagnosticFixes; DiagOpts.SendDiagnosticCategory = Params.capabilities.DiagnosticCategory; DiagOpts.EmitRelatedLocations = Params.capabilities.DiagnosticRelatedInformation; if (Params.capabilities.WorkspaceSymbolKinds) SupportedSymbolKinds |= *Params.capabilities.WorkspaceSymbolKinds; if (Params.capabilities.CompletionItemKinds) SupportedCompletionItemKinds |= *Params.capabilities.CompletionItemKinds; SupportsCodeAction = Params.capabilities.CodeActionStructure; SupportsHierarchicalDocumentSymbol = Params.capabilities.HierarchicalDocumentSymbol; SupportFileStatus = Params.initializationOptions.FileStatus; HoverContentFormat = Params.capabilities.HoverContentFormat; SupportsOffsetsInSignatureHelp = Params.capabilities.OffsetsInSignatureHelp; if (Params.capabilities.WorkDoneProgress) BackgroundIndexProgressState = BackgroundIndexProgress::Empty; BackgroundIndexSkipCreate = Params.capabilities.ImplicitProgressCreation; // Per LSP, renameProvider can be either boolean or RenameOptions. // RenameOptions will be specified if the client states it supports prepare. llvm::json::Value RenameProvider = llvm::json::Object{{"prepareProvider", true}}; if (!Params.capabilities.RenamePrepareSupport) // Only boolean allowed per LSP RenameProvider = true; // Per LSP, codeActionProvide can be either boolean or CodeActionOptions. // CodeActionOptions is only valid if the client supports action literal // via textDocument.codeAction.codeActionLiteralSupport. llvm::json::Value CodeActionProvider = true; if (Params.capabilities.CodeActionStructure) CodeActionProvider = llvm::json::Object{ {"codeActionKinds", {CodeAction::QUICKFIX_KIND, CodeAction::REFACTOR_KIND, CodeAction::INFO_KIND}}}; llvm::json::Object Result{ {{"serverInfo", llvm::json::Object{{"name", "clangd"}, {"version", getClangToolFullVersion("clangd")}}}, {"capabilities", llvm::json::Object{ {"textDocumentSync", llvm::json::Object{ {"openClose", true}, {"change", (int)TextDocumentSyncKind::Incremental}, {"save", true}, }}, {"documentFormattingProvider", true}, {"documentRangeFormattingProvider", true}, {"documentOnTypeFormattingProvider", llvm::json::Object{ {"firstTriggerCharacter", "\n"}, {"moreTriggerCharacter", {}}, }}, {"codeActionProvider", std::move(CodeActionProvider)}, {"completionProvider", llvm::json::Object{ {"allCommitCharacters", {" ", "\t", "(", ")", "[", "]", "{", "}", "<", ">", ":", ";", ",", "+", "-", "/", "*", "%", "^", "&", "#", "?", ".", "=", "\"", "'", "|"}}, {"resolveProvider", false}, // We do extra checks, e.g. that > is part of ->. {"triggerCharacters", {".", "<", ">", ":", "\"", "/"}}, }}, {"semanticTokensProvider", llvm::json::Object{ {"full", llvm::json::Object{{"delta", true}}}, {"range", false}, {"legend", llvm::json::Object{{"tokenTypes", semanticTokenTypes()}, {"tokenModifiers", llvm::json::Array()}}}, }}, {"signatureHelpProvider", llvm::json::Object{ {"triggerCharacters", {"(", ","}}, }}, {"declarationProvider", true}, {"definitionProvider", true}, {"documentHighlightProvider", true}, {"documentLinkProvider", llvm::json::Object{ {"resolveProvider", false}, }}, {"hoverProvider", true}, {"renameProvider", std::move(RenameProvider)}, {"selectionRangeProvider", true}, {"documentSymbolProvider", true}, {"workspaceSymbolProvider", true}, {"referencesProvider", true}, {"executeCommandProvider", llvm::json::Object{ {"commands", {ExecuteCommandParams::CLANGD_APPLY_FIX_COMMAND, ExecuteCommandParams::CLANGD_APPLY_TWEAK}}, }}, {"typeHierarchyProvider", true}, {"memoryUsageProvider", true}, // clangd extension. }}}}; if (Opts.Encoding) Result["offsetEncoding"] = *Opts.Encoding; if (Opts.TheiaSemanticHighlighting) Result.getObject("capabilities") ->insert( {"semanticHighlighting", llvm::json::Object{{"scopes", buildHighlightScopeLookupTable()}}}); if (Opts.FoldingRanges) Result.getObject("capabilities")->insert({"foldingRangeProvider", true}); Reply(std::move(Result)); } void ClangdLSPServer::onInitialized(const InitializedParams &Params) {} void ClangdLSPServer::onShutdown(const ShutdownParams &Params, Callback<std::nullptr_t> Reply) { // Do essentially nothing, just say we're ready to exit. ShutdownRequestReceived = true; Reply(nullptr); } // sync is a clangd extension: it blocks until all background work completes. // It blocks the calling thread, so no messages are processed until it returns! void ClangdLSPServer::onSync(const NoParams &Params, Callback<std::nullptr_t> Reply) { if (Server->blockUntilIdleForTest(/*TimeoutSeconds=*/60)) Reply(nullptr); else Reply(error("Not idle after a minute")); } void ClangdLSPServer::onDocumentDidOpen( const DidOpenTextDocumentParams &Params) { PathRef File = Params.textDocument.uri.file(); const std::string &Contents = Params.textDocument.text; auto Version = DraftMgr.addDraft(File, Params.textDocument.version, Contents); Server->addDocument(File, Contents, encodeVersion(Version), WantDiagnostics::Yes); } void ClangdLSPServer::onDocumentDidChange( const DidChangeTextDocumentParams &Params) { auto WantDiags = WantDiagnostics::Auto; if (Params.wantDiagnostics.hasValue()) WantDiags = Params.wantDiagnostics.getValue() ? WantDiagnostics::Yes : WantDiagnostics::No; PathRef File = Params.textDocument.uri.file(); llvm::Expected<DraftStore::Draft> Draft = DraftMgr.updateDraft( File, Params.textDocument.version, Params.contentChanges); if (!Draft) { // If this fails, we are most likely going to be not in sync anymore with // the client. It is better to remove the draft and let further operations // fail rather than giving wrong results. DraftMgr.removeDraft(File); Server->removeDocument(File); elog("Failed to update {0}: {1}", File, Draft.takeError()); return; } Server->addDocument(File, Draft->Contents, encodeVersion(Draft->Version), WantDiags, Params.forceRebuild); } void ClangdLSPServer::onDocumentDidSave( const DidSaveTextDocumentParams &Params) { reparseOpenFilesIfNeeded([](llvm::StringRef) { return true; }); } void ClangdLSPServer::onFileEvent(const DidChangeWatchedFilesParams &Params) { // We could also reparse all open files here. However: // - this could be frequent, and revalidating all the preambles isn't free // - this is useful e.g. when switching git branches, but we're likely to see // fresh headers but still have the old-branch main-file content Server->onFileEvent(Params); } void ClangdLSPServer::onCommand(const ExecuteCommandParams &Params, Callback<llvm::json::Value> Reply) { auto ApplyEdit = [this](WorkspaceEdit WE, std::string SuccessMessage, decltype(Reply) Reply) { ApplyWorkspaceEditParams Edit; Edit.edit = std::move(WE); call<ApplyWorkspaceEditResponse>( "workspace/applyEdit", std::move(Edit), [Reply = std::move(Reply), SuccessMessage = std::move(SuccessMessage)]( llvm::Expected<ApplyWorkspaceEditResponse> Response) mutable { if (!Response) return Reply(Response.takeError()); if (!Response->applied) { std::string Reason = Response->failureReason ? *Response->failureReason : "unknown reason"; return Reply(error("edits were not applied: {0}", Reason)); } return Reply(SuccessMessage); }); }; if (Params.command == ExecuteCommandParams::CLANGD_APPLY_FIX_COMMAND && Params.workspaceEdit) { // The flow for "apply-fix" : // 1. We publish a diagnostic, including fixits // 2. The user clicks on the diagnostic, the editor asks us for code actions // 3. We send code actions, with the fixit embedded as context // 4. The user selects the fixit, the editor asks us to apply it // 5. We unwrap the changes and send them back to the editor // 6. The editor applies the changes (applyEdit), and sends us a reply // 7. We unwrap the reply and send a reply to the editor. ApplyEdit(*Params.workspaceEdit, "Fix applied.", std::move(Reply)); } else if (Params.command == ExecuteCommandParams::CLANGD_APPLY_TWEAK && Params.tweakArgs) { auto Code = DraftMgr.getDraft(Params.tweakArgs->file.file()); if (!Code) return Reply(error("trying to apply a code action for a non-added file")); auto Action = [this, ApplyEdit, Reply = std::move(Reply), File = Params.tweakArgs->file, Code = std::move(*Code)]( llvm::Expected<Tweak::Effect> R) mutable { if (!R) return Reply(R.takeError()); assert(R->ShowMessage || (!R->ApplyEdits.empty() && "tweak has no effect")); if (R->ShowMessage) { ShowMessageParams Msg; Msg.message = *R->ShowMessage; Msg.type = MessageType::Info; notify("window/showMessage", Msg); } // When no edit is specified, make sure we Reply(). if (R->ApplyEdits.empty()) return Reply("Tweak applied."); if (auto Err = validateEdits(DraftMgr, R->ApplyEdits)) return Reply(std::move(Err)); WorkspaceEdit WE; WE.changes.emplace(); for (const auto &It : R->ApplyEdits) { (*WE.changes)[URI::createFile(It.first()).toString()] = It.second.asTextEdits(); } // ApplyEdit will take care of calling Reply(). return ApplyEdit(std::move(WE), "Tweak applied.", std::move(Reply)); }; Server->applyTweak(Params.tweakArgs->file.file(), Params.tweakArgs->selection, Params.tweakArgs->tweakID, std::move(Action)); } else { // We should not get here because ExecuteCommandParams would not have // parsed in the first place and this handler should not be called. But if // more commands are added, this will be here has a safe guard. Reply(llvm::make_error<LSPError>( llvm::formatv("Unsupported command \"{0}\".", Params.command).str(), ErrorCode::InvalidParams)); } } void ClangdLSPServer::onWorkspaceSymbol( const WorkspaceSymbolParams &Params, Callback<std::vector<SymbolInformation>> Reply) { Server->workspaceSymbols( Params.query, Opts.CodeComplete.Limit, [Reply = std::move(Reply), this](llvm::Expected<std::vector<SymbolInformation>> Items) mutable { if (!Items) return Reply(Items.takeError()); for (auto &Sym : *Items) Sym.kind = adjustKindToCapability(Sym.kind, SupportedSymbolKinds); Reply(std::move(*Items)); }); } void ClangdLSPServer::onPrepareRename(const TextDocumentPositionParams &Params, Callback<llvm::Optional<Range>> Reply) { Server->prepareRename( Params.textDocument.uri.file(), Params.position, /*NewName*/ llvm::None, Opts.Rename, [Reply = std::move(Reply)](llvm::Expected<RenameResult> Result) mutable { if (!Result) return Reply(Result.takeError()); return Reply(std::move(Result->Target)); }); } void ClangdLSPServer::onRename(const RenameParams &Params, Callback<WorkspaceEdit> Reply) { Path File = std::string(Params.textDocument.uri.file()); if (!DraftMgr.getDraft(File)) return Reply(llvm::make_error<LSPError>( "onRename called for non-added file", ErrorCode::InvalidParams)); Server->rename( File, Params.position, Params.newName, Opts.Rename, [File, Params, Reply = std::move(Reply), this](llvm::Expected<RenameResult> R) mutable { if (!R) return Reply(R.takeError()); if (auto Err = validateEdits(DraftMgr, R->GlobalChanges)) return Reply(std::move(Err)); WorkspaceEdit Result; Result.changes.emplace(); for (const auto &Rep : R->GlobalChanges) { (*Result.changes)[URI::createFile(Rep.first()).toString()] = Rep.second.asTextEdits(); } Reply(Result); }); } void ClangdLSPServer::onDocumentDidClose( const DidCloseTextDocumentParams &Params) { PathRef File = Params.textDocument.uri.file(); DraftMgr.removeDraft(File); Server->removeDocument(File); { std::lock_guard<std::mutex> Lock(FixItsMutex); FixItsMap.erase(File); } { std::lock_guard<std::mutex> HLock(HighlightingsMutex); FileToHighlightings.erase(File); } { std::lock_guard<std::mutex> HLock(SemanticTokensMutex); LastSemanticTokens.erase(File); } // clangd will not send updates for this file anymore, so we empty out the // list of diagnostics shown on the client (e.g. in the "Problems" pane of // VSCode). Note that this cannot race with actual diagnostics responses // because removeDocument() guarantees no diagnostic callbacks will be // executed after it returns. PublishDiagnosticsParams Notification; Notification.uri = URIForFile::canonicalize(File, /*TUPath=*/File); publishDiagnostics(Notification); } void ClangdLSPServer::onDocumentOnTypeFormatting( const DocumentOnTypeFormattingParams &Params, Callback<std::vector<TextEdit>> Reply) { auto File = Params.textDocument.uri.file(); auto Code = DraftMgr.getDraft(File); if (!Code) return Reply(llvm::make_error<LSPError>( "onDocumentOnTypeFormatting called for non-added file", ErrorCode::InvalidParams)); Server->formatOnType(File, Code->Contents, Params.position, Params.ch, std::move(Reply)); } void ClangdLSPServer::onDocumentRangeFormatting( const DocumentRangeFormattingParams &Params, Callback<std::vector<TextEdit>> Reply) { auto File = Params.textDocument.uri.file(); auto Code = DraftMgr.getDraft(File); if (!Code) return Reply(llvm::make_error<LSPError>( "onDocumentRangeFormatting called for non-added file", ErrorCode::InvalidParams)); Server->formatRange( File, Code->Contents, Params.range, [Code = Code->Contents, Reply = std::move(Reply)]( llvm::Expected<tooling::Replacements> Result) mutable { if (Result) Reply(replacementsToEdits(Code, Result.get())); else Reply(Result.takeError()); }); } void ClangdLSPServer::onDocumentFormatting( const DocumentFormattingParams &Params, Callback<std::vector<TextEdit>> Reply) { auto File = Params.textDocument.uri.file(); auto Code = DraftMgr.getDraft(File); if (!Code) return Reply(llvm::make_error<LSPError>( "onDocumentFormatting called for non-added file", ErrorCode::InvalidParams)); Server->formatFile(File, Code->Contents, [Code = Code->Contents, Reply = std::move(Reply)]( llvm::Expected<tooling::Replacements> Result) mutable { if (Result) Reply(replacementsToEdits(Code, Result.get())); else Reply(Result.takeError()); }); } /// The functions constructs a flattened view of the DocumentSymbol hierarchy. /// Used by the clients that do not support the hierarchical view. static std::vector<SymbolInformation> flattenSymbolHierarchy(llvm::ArrayRef<DocumentSymbol> Symbols, const URIForFile &FileURI) { std::vector<SymbolInformation> Results; std::function<void(const DocumentSymbol &, llvm::StringRef)> Process = [&](const DocumentSymbol &S, llvm::Optional<llvm::StringRef> ParentName) { SymbolInformation SI; SI.containerName = std::string(ParentName ? "" : *ParentName); SI.name = S.name; SI.kind = S.kind; SI.location.range = S.range; SI.location.uri = FileURI; Results.push_back(std::move(SI)); std::string FullName = !ParentName ? S.name : (ParentName->str() + "::" + S.name); for (auto &C : S.children) Process(C, /*ParentName=*/FullName); }; for (auto &S : Symbols) Process(S, /*ParentName=*/""); return Results; } void ClangdLSPServer::onDocumentSymbol(const DocumentSymbolParams &Params, Callback<llvm::json::Value> Reply) { URIForFile FileURI = Params.textDocument.uri; Server->documentSymbols( Params.textDocument.uri.file(), [this, FileURI, Reply = std::move(Reply)]( llvm::Expected<std::vector<DocumentSymbol>> Items) mutable { if (!Items) return Reply(Items.takeError()); adjustSymbolKinds(*Items, SupportedSymbolKinds); if (SupportsHierarchicalDocumentSymbol) return Reply(std::move(*Items)); else return Reply(flattenSymbolHierarchy(*Items, FileURI)); }); } void ClangdLSPServer::onFoldingRange( const FoldingRangeParams &Params, Callback<std::vector<FoldingRange>> Reply) { Server->foldingRanges(Params.textDocument.uri.file(), std::move(Reply)); } static llvm::Optional<Command> asCommand(const CodeAction &Action) { Command Cmd; if (Action.command && Action.edit) return None; // Not representable. (We never emit these anyway). if (Action.command) { Cmd = *Action.command; } else if (Action.edit) { Cmd.command = std::string(Command::CLANGD_APPLY_FIX_COMMAND); Cmd.workspaceEdit = *Action.edit; } else { return None; } Cmd.title = Action.title; if (Action.kind && *Action.kind == CodeAction::QUICKFIX_KIND) Cmd.title = "Apply fix: " + Cmd.title; return Cmd; } void ClangdLSPServer::onCodeAction(const CodeActionParams &Params, Callback<llvm::json::Value> Reply) { URIForFile File = Params.textDocument.uri; auto Code = DraftMgr.getDraft(File.file()); if (!Code) return Reply(llvm::make_error<LSPError>( "onCodeAction called for non-added file", ErrorCode::InvalidParams)); // We provide a code action for Fixes on the specified diagnostics. std::vector<CodeAction> FixIts; for (const Diagnostic &D : Params.context.diagnostics) { for (auto &F : getFixes(File.file(), D)) { FixIts.push_back(toCodeAction(F, Params.textDocument.uri)); FixIts.back().diagnostics = {D}; } } // Now enumerate the semantic code actions. auto ConsumeActions = [Reply = std::move(Reply), File, Code = std::move(*Code), Selection = Params.range, FixIts = std::move(FixIts), this]( llvm::Expected<std::vector<ClangdServer::TweakRef>> Tweaks) mutable { if (!Tweaks) return Reply(Tweaks.takeError()); std::vector<CodeAction> Actions = std::move(FixIts); Actions.reserve(Actions.size() + Tweaks->size()); for (const auto &T : *Tweaks) Actions.push_back(toCodeAction(T, File, Selection)); // If there's exactly one quick-fix, call it "preferred". // We never consider refactorings etc as preferred. CodeAction *OnlyFix = nullptr; for (auto &Action : Actions) { if (Action.kind && *Action.kind == CodeAction::QUICKFIX_KIND) { if (OnlyFix) { OnlyFix->isPreferred = false; break; } Action.isPreferred = true; OnlyFix = &Action; } } if (SupportsCodeAction) return Reply(llvm::json::Array(Actions)); std::vector<Command> Commands; for (const auto &Action : Actions) { if (auto Command = asCommand(Action)) Commands.push_back(std::move(*Command)); } return Reply(llvm::json::Array(Commands)); }; Server->enumerateTweaks( File.file(), Params.range, [&](const Tweak &T) { if (!Opts.TweakFilter(T)) return false; // FIXME: also consider CodeActionContext.only return true; }, std::move(ConsumeActions)); } void ClangdLSPServer::onCompletion(const CompletionParams &Params, Callback<CompletionList> Reply) { if (!shouldRunCompletion(Params)) { // Clients sometimes auto-trigger completions in undesired places (e.g. // 'a >^ '), we return empty results in those cases. vlog("ignored auto-triggered completion, preceding char did not match"); return Reply(CompletionList()); } Server->codeComplete( Params.textDocument.uri.file(), Params.position, Opts.CodeComplete, [Reply = std::move(Reply), this](llvm::Expected<CodeCompleteResult> List) mutable { if (!List) return Reply(List.takeError()); CompletionList LSPList; LSPList.isIncomplete = List->HasMore; for (const auto &R : List->Completions) { CompletionItem C = R.render(Opts.CodeComplete); C.kind = adjustKindToCapability(C.kind, SupportedCompletionItemKinds); LSPList.items.push_back(std::move(C)); } return Reply(std::move(LSPList)); }); } void ClangdLSPServer::onSignatureHelp(const TextDocumentPositionParams &Params, Callback<SignatureHelp> Reply) { Server->signatureHelp(Params.textDocument.uri.file(), Params.position, [Reply = std::move(Reply), this]( llvm::Expected<SignatureHelp> Signature) mutable { if (!Signature) return Reply(Signature.takeError()); if (SupportsOffsetsInSignatureHelp) return Reply(std::move(*Signature)); // Strip out the offsets from signature help for // clients that only support string labels. for (auto &SigInfo : Signature->signatures) { for (auto &Param : SigInfo.parameters) Param.labelOffsets.reset(); } return Reply(std::move(*Signature)); }); } // Go to definition has a toggle function: if def and decl are distinct, then // the first press gives you the def, the second gives you the matching def. // getToggle() returns the counterpart location that under the cursor. // // We return the toggled location alone (ignoring other symbols) to encourage // editors to "bounce" quickly between locations, without showing a menu. static Location *getToggle(const TextDocumentPositionParams &Point, LocatedSymbol &Sym) { // Toggle only makes sense with two distinct locations. if (!Sym.Definition || *Sym.Definition == Sym.PreferredDeclaration) return nullptr; if (Sym.Definition->uri.file() == Point.textDocument.uri.file() && Sym.Definition->range.contains(Point.position)) return &Sym.PreferredDeclaration; if (Sym.PreferredDeclaration.uri.file() == Point.textDocument.uri.file() && Sym.PreferredDeclaration.range.contains(Point.position)) return &*Sym.Definition; return nullptr; } void ClangdLSPServer::onGoToDefinition(const TextDocumentPositionParams &Params, Callback<std::vector<Location>> Reply) { Server->locateSymbolAt( Params.textDocument.uri.file(), Params.position, [Params, Reply = std::move(Reply)]( llvm::Expected<std::vector<LocatedSymbol>> Symbols) mutable { if (!Symbols) return Reply(Symbols.takeError()); std::vector<Location> Defs; for (auto &S : *Symbols) { if (Location *Toggle = getToggle(Params, S)) return Reply(std::vector<Location>{std::move(*Toggle)}); Defs.push_back(S.Definition.getValueOr(S.PreferredDeclaration)); } Reply(std::move(Defs)); }); } void ClangdLSPServer::onGoToDeclaration( const TextDocumentPositionParams &Params, Callback<std::vector<Location>> Reply) { Server->locateSymbolAt( Params.textDocument.uri.file(), Params.position, [Params, Reply = std::move(Reply)]( llvm::Expected<std::vector<LocatedSymbol>> Symbols) mutable { if (!Symbols) return Reply(Symbols.takeError()); std::vector<Location> Decls; for (auto &S : *Symbols) { if (Location *Toggle = getToggle(Params, S)) return Reply(std::vector<Location>{std::move(*Toggle)}); Decls.push_back(std::move(S.PreferredDeclaration)); } Reply(std::move(Decls)); }); } void ClangdLSPServer::onSwitchSourceHeader( const TextDocumentIdentifier &Params, Callback<llvm::Optional<URIForFile>> Reply) { Server->switchSourceHeader( Params.uri.file(), [Reply = std::move(Reply), Params](llvm::Expected<llvm::Optional<clangd::Path>> Path) mutable { if (!Path) return Reply(Path.takeError()); if (*Path) return Reply(URIForFile::canonicalize(**Path, Params.uri.file())); return Reply(llvm::None); }); } void ClangdLSPServer::onDocumentHighlight( const TextDocumentPositionParams &Params, Callback<std::vector<DocumentHighlight>> Reply) { Server->findDocumentHighlights(Params.textDocument.uri.file(), Params.position, std::move(Reply)); } void ClangdLSPServer::onHover(const TextDocumentPositionParams &Params, Callback<llvm::Optional<Hover>> Reply) { Server->findHover(Params.textDocument.uri.file(), Params.position, [Reply = std::move(Reply), this]( llvm::Expected<llvm::Optional<HoverInfo>> H) mutable { if (!H) return Reply(H.takeError()); if (!*H) return Reply(llvm::None); Hover R; R.contents.kind = HoverContentFormat; R.range = (*H)->SymRange; switch (HoverContentFormat) { case MarkupKind::PlainText: R.contents.value = (*H)->present().asPlainText(); return Reply(std::move(R)); case MarkupKind::Markdown: R.contents.value = (*H)->present().asMarkdown(); return Reply(std::move(R)); }; llvm_unreachable("unhandled MarkupKind"); }); } void ClangdLSPServer::onTypeHierarchy( const TypeHierarchyParams &Params, Callback<Optional<TypeHierarchyItem>> Reply) { Server->typeHierarchy(Params.textDocument.uri.file(), Params.position, Params.resolve, Params.direction, std::move(Reply)); } void ClangdLSPServer::onResolveTypeHierarchy( const ResolveTypeHierarchyItemParams &Params, Callback<Optional<TypeHierarchyItem>> Reply) { Server->resolveTypeHierarchy(Params.item, Params.resolve, Params.direction, std::move(Reply)); } void ClangdLSPServer::applyConfiguration( const ConfigurationSettings &Settings) { // Per-file update to the compilation database. llvm::StringSet<> ModifiedFiles; for (auto &Entry : Settings.compilationDatabaseChanges) { PathRef File = Entry.first; auto Old = CDB->getCompileCommand(File); auto New = tooling::CompileCommand(std::move(Entry.second.workingDirectory), File, std::move(Entry.second.compilationCommand), /*Output=*/""); if (Old != New) { CDB->setCompileCommand(File, std::move(New)); ModifiedFiles.insert(File); } } reparseOpenFilesIfNeeded( [&](llvm::StringRef File) { return ModifiedFiles.count(File) != 0; }); } void ClangdLSPServer::publishTheiaSemanticHighlighting( const TheiaSemanticHighlightingParams &Params) { notify("textDocument/semanticHighlighting", Params); } void ClangdLSPServer::publishDiagnostics( const PublishDiagnosticsParams &Params) { notify("textDocument/publishDiagnostics", Params); } void ClangdLSPServer::maybeExportMemoryProfile() { if (!trace::enabled()) return; // Profiling might be expensive, so we throttle it to happen once every 5 // minutes. static constexpr auto ProfileInterval = std::chrono::minutes(5); auto Now = std::chrono::steady_clock::now(); if (Now < NextProfileTime) return; static constexpr trace::Metric MemoryUsage( "memory_usage", trace::Metric::Value, "component_name"); trace::Span Tracer("ProfileBrief"); MemoryTree MT; profile(MT); record(MT, "clangd_lsp_server", MemoryUsage); NextProfileTime = Now + ProfileInterval; } // FIXME: This function needs to be properly tested. void ClangdLSPServer::onChangeConfiguration( const DidChangeConfigurationParams &Params) { applyConfiguration(Params.settings); } void ClangdLSPServer::onReference(const ReferenceParams &Params, Callback<std::vector<Location>> Reply) { Server->findReferences(Params.textDocument.uri.file(), Params.position, Opts.CodeComplete.Limit, [Reply = std::move(Reply)]( llvm::Expected<ReferencesResult> Refs) mutable { if (!Refs) return Reply(Refs.takeError()); return Reply(std::move(Refs->References)); }); } void ClangdLSPServer::onSymbolInfo(const TextDocumentPositionParams &Params, Callback<std::vector<SymbolDetails>> Reply) { Server->symbolInfo(Params.textDocument.uri.file(), Params.position, std::move(Reply)); } void ClangdLSPServer::onSelectionRange( const SelectionRangeParams &Params, Callback<std::vector<SelectionRange>> Reply) { Server->semanticRanges( Params.textDocument.uri.file(), Params.positions, [Reply = std::move(Reply)]( llvm::Expected<std::vector<SelectionRange>> Ranges) mutable { if (!Ranges) return Reply(Ranges.takeError()); return Reply(std::move(*Ranges)); }); } void ClangdLSPServer::onDocumentLink( const DocumentLinkParams &Params, Callback<std::vector<DocumentLink>> Reply) { // TODO(forster): This currently resolves all targets eagerly. This is slow, // because it blocks on the preamble/AST being built. We could respond to the // request faster by using string matching or the lexer to find the includes // and resolving the targets lazily. Server->documentLinks( Params.textDocument.uri.file(), [Reply = std::move(Reply)]( llvm::Expected<std::vector<DocumentLink>> Links) mutable { if (!Links) { return Reply(Links.takeError()); } return Reply(std::move(Links)); }); } // Increment a numeric string: "" -> 1 -> 2 -> ... -> 9 -> 10 -> 11 ... static void increment(std::string &S) { for (char &C : llvm::reverse(S)) { if (C != '9') { ++C; return; } C = '0'; } S.insert(S.begin(), '1'); } void ClangdLSPServer::onSemanticTokens(const SemanticTokensParams &Params, Callback<SemanticTokens> CB) { Server->semanticHighlights( Params.textDocument.uri.file(), [this, File(Params.textDocument.uri.file().str()), CB(std::move(CB))]( llvm::Expected<std::vector<HighlightingToken>> HT) mutable { if (!HT) return CB(HT.takeError()); SemanticTokens Result; Result.tokens = toSemanticTokens(*HT); { std::lock_guard<std::mutex> Lock(SemanticTokensMutex); auto &Last = LastSemanticTokens[File]; Last.tokens = Result.tokens; increment(Last.resultId); Result.resultId = Last.resultId; } CB(std::move(Result)); }); } void ClangdLSPServer::onSemanticTokensDelta( const SemanticTokensDeltaParams &Params, Callback<SemanticTokensOrDelta> CB) { Server->semanticHighlights( Params.textDocument.uri.file(), [this, PrevResultID(Params.previousResultId), File(Params.textDocument.uri.file().str()), CB(std::move(CB))]( llvm::Expected<std::vector<HighlightingToken>> HT) mutable { if (!HT) return CB(HT.takeError()); std::vector<SemanticToken> Toks = toSemanticTokens(*HT); SemanticTokensOrDelta Result; { std::lock_guard<std::mutex> Lock(SemanticTokensMutex); auto &Last = LastSemanticTokens[File]; if (PrevResultID == Last.resultId) { Result.edits = diffTokens(Last.tokens, Toks); } else { vlog("semanticTokens/full/delta: wanted edits vs {0} but last " "result had ID {1}. Returning full token list.", PrevResultID, Last.resultId); Result.tokens = Toks; } Last.tokens = std::move(Toks); increment(Last.resultId); Result.resultId = Last.resultId; } CB(std::move(Result)); }); } void ClangdLSPServer::onMemoryUsage(const NoParams &, Callback<MemoryTree> Reply) { llvm::BumpPtrAllocator DetailAlloc; MemoryTree MT(&DetailAlloc); profile(MT); Reply(std::move(MT)); } ClangdLSPServer::ClangdLSPServer(class Transport &Transp, const ThreadsafeFS &TFS, const ClangdLSPServer::Options &Opts) : BackgroundContext(Context::current().clone()), Transp(Transp), MsgHandler(new MessageHandler(*this)), TFS(TFS), SupportedSymbolKinds(defaultSymbolKinds()), SupportedCompletionItemKinds(defaultCompletionItemKinds()), Opts(Opts) { // clang-format off MsgHandler->bind("initialize", &ClangdLSPServer::onInitialize); MsgHandler->bind("initialized", &ClangdLSPServer::onInitialized); MsgHandler->bind("shutdown", &ClangdLSPServer::onShutdown); MsgHandler->bind("sync", &ClangdLSPServer::onSync); MsgHandler->bind("textDocument/rangeFormatting", &ClangdLSPServer::onDocumentRangeFormatting); MsgHandler->bind("textDocument/onTypeFormatting", &ClangdLSPServer::onDocumentOnTypeFormatting); MsgHandler->bind("textDocument/formatting", &ClangdLSPServer::onDocumentFormatting); MsgHandler->bind("textDocument/codeAction", &ClangdLSPServer::onCodeAction); MsgHandler->bind("textDocument/completion", &ClangdLSPServer::onCompletion); MsgHandler->bind("textDocument/signatureHelp", &ClangdLSPServer::onSignatureHelp); MsgHandler->bind("textDocument/definition", &ClangdLSPServer::onGoToDefinition); MsgHandler->bind("textDocument/declaration", &ClangdLSPServer::onGoToDeclaration); MsgHandler->bind("textDocument/references", &ClangdLSPServer::onReference); MsgHandler->bind("textDocument/switchSourceHeader", &ClangdLSPServer::onSwitchSourceHeader); MsgHandler->bind("textDocument/prepareRename", &ClangdLSPServer::onPrepareRename); MsgHandler->bind("textDocument/rename", &ClangdLSPServer::onRename); MsgHandler->bind("textDocument/hover", &ClangdLSPServer::onHover); MsgHandler->bind("textDocument/documentSymbol", &ClangdLSPServer::onDocumentSymbol); MsgHandler->bind("workspace/executeCommand", &ClangdLSPServer::onCommand); MsgHandler->bind("textDocument/documentHighlight", &ClangdLSPServer::onDocumentHighlight); MsgHandler->bind("workspace/symbol", &ClangdLSPServer::onWorkspaceSymbol); MsgHandler->bind("textDocument/didOpen", &ClangdLSPServer::onDocumentDidOpen); MsgHandler->bind("textDocument/didClose", &ClangdLSPServer::onDocumentDidClose); MsgHandler->bind("textDocument/didChange", &ClangdLSPServer::onDocumentDidChange); MsgHandler->bind("textDocument/didSave", &ClangdLSPServer::onDocumentDidSave); MsgHandler->bind("workspace/didChangeWatchedFiles", &ClangdLSPServer::onFileEvent); MsgHandler->bind("workspace/didChangeConfiguration", &ClangdLSPServer::onChangeConfiguration); MsgHandler->bind("textDocument/symbolInfo", &ClangdLSPServer::onSymbolInfo); MsgHandler->bind("textDocument/typeHierarchy", &ClangdLSPServer::onTypeHierarchy); MsgHandler->bind("typeHierarchy/resolve", &ClangdLSPServer::onResolveTypeHierarchy); MsgHandler->bind("textDocument/selectionRange", &ClangdLSPServer::onSelectionRange); MsgHandler->bind("textDocument/documentLink", &ClangdLSPServer::onDocumentLink); MsgHandler->bind("textDocument/semanticTokens/full", &ClangdLSPServer::onSemanticTokens); MsgHandler->bind("textDocument/semanticTokens/full/delta", &ClangdLSPServer::onSemanticTokensDelta); MsgHandler->bind("$/memoryUsage", &ClangdLSPServer::onMemoryUsage); if (Opts.FoldingRanges) MsgHandler->bind("textDocument/foldingRange", &ClangdLSPServer::onFoldingRange); // clang-format on // Delay first profile until we've finished warming up. NextProfileTime = std::chrono::steady_clock::now() + std::chrono::minutes(1); } ClangdLSPServer::~ClangdLSPServer() { IsBeingDestroyed = true; // Explicitly destroy ClangdServer first, blocking on threads it owns. // This ensures they don't access any other members. Server.reset(); } bool ClangdLSPServer::run() { // Run the Language Server loop. bool CleanExit = true; if (auto Err = Transp.loop(*MsgHandler)) { elog("Transport error: {0}", std::move(Err)); CleanExit = false; } return CleanExit && ShutdownRequestReceived; } void ClangdLSPServer::profile(MemoryTree &MT) const { if (Server) Server->profile(MT.child("clangd_server")); } std::vector<Fix> ClangdLSPServer::getFixes(llvm::StringRef File, const clangd::Diagnostic &D) { std::lock_guard<std::mutex> Lock(FixItsMutex); auto DiagToFixItsIter = FixItsMap.find(File); if (DiagToFixItsIter == FixItsMap.end()) return {}; const auto &DiagToFixItsMap = DiagToFixItsIter->second; auto FixItsIter = DiagToFixItsMap.find(D); if (FixItsIter == DiagToFixItsMap.end()) return {}; return FixItsIter->second; } // A completion request is sent when the user types '>' or ':', but we only // want to trigger on '->' and '::'. We check the preceeding text to make // sure it matches what we expected. // Running the lexer here would be more robust (e.g. we can detect comments // and avoid triggering completion there), but we choose to err on the side // of simplicity here. bool ClangdLSPServer::shouldRunCompletion( const CompletionParams &Params) const { if (Params.context.triggerKind != CompletionTriggerKind::TriggerCharacter) return true; auto Code = DraftMgr.getDraft(Params.textDocument.uri.file()); if (!Code) return true; // completion code will log the error for untracked doc. auto Offset = positionToOffset(Code->Contents, Params.position, /*AllowColumnsBeyondLineLength=*/false); if (!Offset) { vlog("could not convert position '{0}' to offset for file '{1}'", Params.position, Params.textDocument.uri.file()); return true; } return allowImplicitCompletion(Code->Contents, *Offset); } void ClangdLSPServer::onHighlightingsReady( PathRef File, llvm::StringRef Version, std::vector<HighlightingToken> Highlightings) { std::vector<HighlightingToken> Old; std::vector<HighlightingToken> HighlightingsCopy = Highlightings; { std::lock_guard<std::mutex> Lock(HighlightingsMutex); Old = std::move(FileToHighlightings[File]); FileToHighlightings[File] = std::move(HighlightingsCopy); } // LSP allows us to send incremental edits of highlightings. Also need to diff // to remove highlightings from tokens that should no longer have them. std::vector<LineHighlightings> Diffed = diffHighlightings(Highlightings, Old); TheiaSemanticHighlightingParams Notification; Notification.TextDocument.uri = URIForFile::canonicalize(File, /*TUPath=*/File); Notification.TextDocument.version = decodeVersion(Version); Notification.Lines = toTheiaSemanticHighlightingInformation(Diffed); publishTheiaSemanticHighlighting(Notification); } void ClangdLSPServer::onDiagnosticsReady(PathRef File, llvm::StringRef Version, std::vector<Diag> Diagnostics) { PublishDiagnosticsParams Notification; Notification.version = decodeVersion(Version); Notification.uri = URIForFile::canonicalize(File, /*TUPath=*/File); DiagnosticToReplacementMap LocalFixIts; // Temporary storage for (auto &Diag : Diagnostics) { toLSPDiags(Diag, Notification.uri, DiagOpts, [&](clangd::Diagnostic Diag, llvm::ArrayRef<Fix> Fixes) { auto &FixItsForDiagnostic = LocalFixIts[Diag]; llvm::copy(Fixes, std::back_inserter(FixItsForDiagnostic)); Notification.diagnostics.push_back(std::move(Diag)); }); } // Cache FixIts { std::lock_guard<std::mutex> Lock(FixItsMutex); FixItsMap[File] = LocalFixIts; } // Send a notification to the LSP client. publishDiagnostics(Notification); } void ClangdLSPServer::onBackgroundIndexProgress( const BackgroundQueue::Stats &Stats) { static const char ProgressToken[] = "backgroundIndexProgress"; std::lock_guard<std::mutex> Lock(BackgroundIndexProgressMutex); auto NotifyProgress = [this](const BackgroundQueue::Stats &Stats) { if (BackgroundIndexProgressState != BackgroundIndexProgress::Live) { WorkDoneProgressBegin Begin; Begin.percentage = true; Begin.title = "indexing"; progress(ProgressToken, std::move(Begin)); BackgroundIndexProgressState = BackgroundIndexProgress::Live; } if (Stats.Completed < Stats.Enqueued) { assert(Stats.Enqueued > Stats.LastIdle); WorkDoneProgressReport Report; Report.percentage = 100.0 * (Stats.Completed - Stats.LastIdle) / (Stats.Enqueued - Stats.LastIdle); Report.message = llvm::formatv("{0}/{1}", Stats.Completed - Stats.LastIdle, Stats.Enqueued - Stats.LastIdle); progress(ProgressToken, std::move(Report)); } else { assert(Stats.Completed == Stats.Enqueued); progress(ProgressToken, WorkDoneProgressEnd()); BackgroundIndexProgressState = BackgroundIndexProgress::Empty; } }; switch (BackgroundIndexProgressState) { case BackgroundIndexProgress::Unsupported: return; case BackgroundIndexProgress::Creating: // Cache this update for when the progress bar is available. PendingBackgroundIndexProgress = Stats; return; case BackgroundIndexProgress::Empty: { if (BackgroundIndexSkipCreate) { NotifyProgress(Stats); break; } // Cache this update for when the progress bar is available. PendingBackgroundIndexProgress = Stats; BackgroundIndexProgressState = BackgroundIndexProgress::Creating; WorkDoneProgressCreateParams CreateRequest; CreateRequest.token = ProgressToken; call<std::nullptr_t>( "window/workDoneProgress/create", CreateRequest, [this, NotifyProgress](llvm::Expected<std::nullptr_t> E) { std::lock_guard<std::mutex> Lock(BackgroundIndexProgressMutex); if (E) { NotifyProgress(this->PendingBackgroundIndexProgress); } else { elog("Failed to create background index progress bar: {0}", E.takeError()); // give up forever rather than thrashing about BackgroundIndexProgressState = BackgroundIndexProgress::Unsupported; } }); break; } case BackgroundIndexProgress::Live: NotifyProgress(Stats); break; } } void ClangdLSPServer::onFileUpdated(PathRef File, const TUStatus &Status) { if (!SupportFileStatus) return; // FIXME: we don't emit "BuildingFile" and `RunningAction`, as these // two statuses are running faster in practice, which leads the UI constantly // changing, and doesn't provide much value. We may want to emit status at a // reasonable time interval (e.g. 0.5s). if (Status.PreambleActivity == PreambleAction::Idle && (Status.ASTActivity.K == ASTAction::Building || Status.ASTActivity.K == ASTAction::RunningAction)) return; notify("textDocument/clangd.fileStatus", Status.render(File)); } void ClangdLSPServer::reparseOpenFilesIfNeeded( llvm::function_ref<bool(llvm::StringRef File)> Filter) { // Reparse only opened files that were modified. for (const Path &FilePath : DraftMgr.getActiveFiles()) if (Filter(FilePath)) if (auto Draft = DraftMgr.getDraft(FilePath)) // else disappeared in race? Server->addDocument(FilePath, std::move(Draft->Contents), encodeVersion(Draft->Version), WantDiagnostics::Auto); } } // namespace clangd } // namespace clang
[ "nlbrow@umich.edu" ]
nlbrow@umich.edu
3d20f0fc970afa37ac44c18f7d50c25b1acf4a8e
41cb99bb83887b2a2d9a6b4ba3570ccc27ac9152
/perception/src/PointMapCell.cpp
34e4fad9cd28cb0a198437eba39a304c4ba595f6
[ "BSD-2-Clause" ]
permissive
samigroup/DrivingAgent-2020-melodic
2d08ed7b008b559ffc85bc09d7c0ed0d801faf9e
b4ace8140313499702c4fd0f3270f2a82ebe0d1a
refs/heads/master
2023-02-01T15:42:29.029726
2020-12-21T23:13:36
2020-12-21T23:13:36
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,833
cpp
#include "PointMapCell.hpp" /*! Removes a set of points from the cell based on the update ID. @param id The ID of the update to be removed. */ void PointMapCell::RemoveUpdate(const int& id) { auto it = updates.begin(); while( it != updates.end() ) { if(it->id == id) { updates.erase(it); return; } } UpdateMetaData(); } void PointMapCell::UpdateMetaData() { bool first = true; meta_data.max_z = 0; meta_data.min_z = 0; //for every point in the updates. for( auto update : updates ) { if(first) { meta_data.max_z = update.data.max_z; meta_data.min_z = update.data.min_z; first = false; continue; } if(update.data.max_z > meta_data.max_z) meta_data.max_z = update.data.max_z; if(update.data.min_z < meta_data.min_z) meta_data.min_z = update.data.min_z; } } void PointMapCell::SetSize(const double& x, const double& y) { x_size = x; y_size = y; } void PointMapCell::AddUpdate(const int& update_id, const std::vector<Point>& points) { PointUpdate update; update.id = update_id; MetaData& update_meta_data = update.data; if(points.size() == 0) return; update_meta_data.occupied = true; //grab the first point in the cell and take it's z value as the minimum and maximum. update_meta_data.min_z = points[0].z; update_meta_data.max_z = points[0].z; //for every point in the updates. for( auto point : points) { if(point.z < update_meta_data.min_z) update_meta_data.min_z = point.z; if(point.z > update_meta_data.max_z) update_meta_data.max_z = point.z; } updates.push_back(update); UpdateMetaData(); }
[ "slabban2@gmail.com" ]
slabban2@gmail.com
ec16c84e0faba77bd6ec6a8005cd3466f0714404
d08784112bc3d868d0df650a61e91d5377cfa1e5
/SubMeter_Nano328p.ino
723fd65c22b116d0e2d8c57eacb75d013128fb14
[]
no_license
geraldcells18/Aquater-Hardware
1b8bbb520762ad1f47eab887bca2eb4ed99ada31
b626408f42476fca97c0490b46ee68aab1d1afe5
refs/heads/master
2020-04-29T12:01:09.925889
2019-03-17T15:56:22
2019-03-17T15:56:22
176,122,401
0
0
null
null
null
null
UTF-8
C++
false
false
2,961
ino
#include <SoftwareSerial.h> #define VALVE_PIN 4 SoftwareSerial wemos(5, 6); // Rx - Tx byte sensorInterrupt = 0; //Interrupt pin for the process of interrupt function. byte sensorPin = 2; //Water flow sensor pin for the water measuring. float calibrationFactor = 6.5; //This object used for water measuring (6.5 revolution per mL) volatile int pulseCount = 0; //This object used to get the water flow sensor pulse count. float flowRate = 0.0; //This object used for fetching the current flow of the water. long flowMilliLitres = 0; //This object used for storing the current flowed mL. long totalMilliLitres = -1; //This object used for storing the cumulative mL. unsigned long oldTime = 0; //This object used to hold the old millis. unsigned long liters = 0; //This object may vary and used for storing of cumulative total of liters. unsigned long old_liters = 0; //This object used to store the old Liters. float cm3 = 0.00; //This object may vary and used for storing the cumulative total of cubic meters. int LDR_READING = 0; String valve_status = "ON"; void getClarity() { LDR_READING = analogRead(A7); } void valveRoutine() { if (wemos.available()) { String valve_state = wemos.readStringUntil('\n'); valve_state.trim(); toggleValve(valve_state); } } void toggleValve(String state) { if (state == "ON" || state == "OFF") { if (state == "ON") { digitalWrite(VALVE_PIN, HIGH); digitalWrite(LED_BUILTIN, HIGH); valve_status = state; } else { digitalWrite(VALVE_PIN, LOW); digitalWrite(LED_BUILTIN, LOW); valve_status = state; } } } void setup() { Serial.begin(9600); wemos.begin(9600); wemos.setTimeout(300); delay(500); pinMode(VALVE_PIN, OUTPUT); digitalWrite(VALVE_PIN, HIGH); pinMode(LED_BUILTIN, OUTPUT); pinMode(sensorPin, INPUT); digitalWrite(sensorPin, HIGH); attachInterrupt(sensorInterrupt, pulseCounter, FALLING); delay(10000); while (totalMilliLitres == -1) { if (wemos.available()) { String data = wemos.readStringUntil('\n'); data.trim(); data.replace(" ", ""); if (data.toInt() >= 0) { wemos.println("r"); totalMilliLitres = data.toInt(); } } delay(500); } } //Pulse method void pulseCounter() { pulseCount++; } //Water flow process. void mainProc() { detachInterrupt(sensorInterrupt); flowRate = ((1000.0 / (millis() - oldTime)) * pulseCount) / calibrationFactor; oldTime = millis(); flowMilliLitres = (flowRate / 60) * 1000; totalMilliLitres += flowMilliLitres; liters = totalMilliLitres / 1000; cm3 = liters / 1000.0; pulseCount = 0; attachInterrupt(sensorInterrupt, pulseCounter, FALLING); } void sendData() { wemos.println(String(liters) + "," + String(cm3) + "," + String(LDR_READING) + ","); Serial.println(String(liters) + "," + String(cm3) + "," + String(LDR_READING) + "," + valve_status + ","); } void loop() { if (millis() - oldTime > 1000) { mainProc(); getClarity(); sendData(); } valveRoutine(); }
[ "diazgerald13@gmail.com" ]
diazgerald13@gmail.com
4890b17b9f511d69c6b4924780e0db2e7fce6c47
ae571e01b5fb10cd98dc6b79472170c0f567e6b9
/include/Map/Path.h
c72fd1e4d659ac4270afdf00434678eca30349d3
[]
no_license
Oscillation/oscMrk-II
9cda29f66db59148e0bfbb1ba640665ba423bda2
34833b85a42cf12514095d3a28ac3b3627fd712a
refs/heads/master
2021-01-23T04:09:27.631400
2014-03-03T06:34:41
2014-03-03T06:34:41
null
0
0
null
null
null
null
UTF-8
C++
false
false
123
h
#pragma once #include "Tile.h" class Path{ public: Path(); ~Path(); short x; short y; short width; short height; };
[ "trickepiclyawesome@gmail.com" ]
trickepiclyawesome@gmail.com
57cf2ed39e9ac32e9049c0adec57af8f7e23c0ba
ba8f56b4292be78b6df3cd423497f1962f855965
/Frameworks/JuceModules/juce_data_structures/values/juce_ValueTreeSynchroniser.h
30441adf444078622c251c2db918b7285b4b6c14
[ "MIT" ]
permissive
Sin-tel/protoplug
644355f4dbf072eea68ac1e548f9f164b1364cc4
236344b1c3b1cc64d7dc01ea0c0c2a656bdc4ba1
refs/heads/master
2023-09-01T00:45:02.745857
2023-08-15T22:54:52
2023-08-15T22:54:52
151,246,506
17
4
NOASSERTION
2018-10-02T11:54:37
2018-10-02T11:54:37
null
UTF-8
C++
false
false
3,848
h
/* ============================================================================== This file is part of the JUCE library. Copyright (c) 2017 - ROLI Ltd. JUCE is an open source library subject to commercial or open-source licensing. By using JUCE, you agree to the terms of both the JUCE 5 End-User License Agreement and JUCE 5 Privacy Policy (both updated and effective as of the 27th April 2017). End User License Agreement: www.juce.com/juce-5-licence Privacy Policy: www.juce.com/juce-5-privacy-policy Or: You may also use this code under the terms of the GPL v3 (see www.gnu.org/licenses). JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE DISCLAIMED. ============================================================================== */ namespace juce { //============================================================================== /** This class can be used to watch for all changes to the state of a ValueTree, and to convert them to a transmittable binary encoding. The purpose of this class is to allow two or more ValueTrees to be remotely synchronised by transmitting encoded changes over some kind of transport mechanism. To use it, you'll need to implement a subclass of ValueTreeSynchroniser and implement the stateChanged() method to transmit the encoded change (maybe via a network or other means) to a remote destination, where it can be applied to a target tree. @tags{DataStructures} */ class JUCE_API ValueTreeSynchroniser : private ValueTree::Listener { public: /** Creates a ValueTreeSynchroniser that watches the given tree. After creating an instance of this class and somehow attaching it to a target tree, you probably want to call sendFullSyncCallback() to get them into a common starting state. */ ValueTreeSynchroniser (const ValueTree& tree); /** Destructor. */ virtual ~ValueTreeSynchroniser(); /** This callback happens when the ValueTree changes and the given state-change message needs to be applied to any other trees that need to stay in sync with it. The data is an opaque blob of binary that you should transmit to wherever your target tree lives, and use applyChange() to apply this to the target tree. */ virtual void stateChanged (const void* encodedChange, size_t encodedChangeSize) = 0; /** Forces the sending of a full state message, which may be large, as it encodes the entire ValueTree. This will internally invoke stateChanged() with the encoded version of the state. */ void sendFullSyncCallback(); /** Applies an encoded change to the given destination tree. When you implement a receiver for changes that were sent by the stateChanged() message, this is the function that you'll need to call to apply them to the target tree that you want to be synced. */ static bool applyChange (ValueTree& target, const void* encodedChangeData, size_t encodedChangeDataSize, UndoManager* undoManager); /** Returns the root ValueTree that is being observed. */ const ValueTree& getRoot() noexcept { return valueTree; } private: ValueTree valueTree; void valueTreePropertyChanged (ValueTree&, const Identifier&) override; void valueTreeChildAdded (ValueTree&, ValueTree&) override; void valueTreeChildRemoved (ValueTree&, ValueTree&, int) override; void valueTreeChildOrderChanged (ValueTree&, int, int) override; void valueTreeParentChanged (ValueTree&) override; JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ValueTreeSynchroniser) }; } // namespace juce
[ "pierre@osar.fr" ]
pierre@osar.fr
ae61ac83644c30be455e71ff24b8cb463739fa04
c655f456c4892624f20652e540117dbbc26affd4
/BST.cpp
4cc261bb57ea33626c51b39c2b8646f341776d4a
[]
no_license
jrod0975/tree
7015d408a712781ac2a2301a85744a5ad08680b8
90d1a49fbcf0bc56fb7202d117d2943f85350071
refs/heads/main
2023-01-04T06:22:39.956261
2020-10-29T00:18:36
2020-10-29T00:18:36
308,173,150
0
0
null
null
null
null
UTF-8
C++
false
false
1,002
cpp
#include <iostream> #include <stdlib.h> #include "BST.h" using namespace std; BST* createNode(BST* root, int value) { BST* newNode = (BST*)malloc(sizeof(BST)); if (root == NULL) { newNode->value = value; newNode->left = NULL; newNode->right = NULL; return newNode; } else if (value <= root->value) { root->left = createNode(root->left, value); } else { root->right = createNode(root->right, value); } return root; } void printInOrder(BST* root) { BST* curr = root; if (curr == NULL) { return; } printInOrder(curr->left); cout << root->value << " "; printInOrder(curr->right); } void printPreOrder(BST* root) { BST* curr = root; if (curr == NULL) { return; } cout << root->value << " "; printInOrder(curr->left); printInOrder(curr->right); } void printPostOrder(BST* root) { BST* curr = root; if (curr == NULL) { return; } printInOrder(curr->left); printInOrder(curr->right); cout << root->value << " "; }
[ "noreply@github.com" ]
noreply@github.com
4281407258a5457e27bdaf4f1d877fe30f44cfbf
35f72ecafb4ad6b013eb629a965abd75ef0a082a
/日常/Math_1/J.cpp
554c7af0218c6e4bc799965ff971ce13bb2c0185
[]
no_license
cdegree/ACM
d8d478d789a4f57acd2f340e956d5b7a46f33f8f
42038ec0cbf99120e8416eed18b8a30dc6873947
refs/heads/master
2021-01-18T21:25:43.017457
2016-04-06T09:16:41
2016-04-06T09:16:41
29,577,653
0
0
null
null
null
null
UTF-8
C++
false
false
12,669
cpp
#include <cstdio> #include <cstdlib> #include <cstring> #include <cmath> #include <cctype> #include <vector> #include <stack> #include <queue> #include <map> #include <algorithm> #include <iostream> #include <string> #include <set> #define X first #define Y second #define sqr(x) (x)*(x) using namespace std; const double PI = acos(-1.0); map<int,int>::iterator it; typedef long long LL ; #pragma comment(linker,"/STACK:102400000,102400000") #define DIGIT 4 #define DEPTH 10000 #define MAX 50 typedef int bignum_t[MAX+1]; int read(bignum_t a,istream& is=cin){ char buf[MAX*DIGIT+1],ch; int i,j; memset((void*)a,0,sizeof(bignum_t)); if (!(is>>buf)) return 0; for (a[0]=strlen(buf),i=a[0]/2-1;i>=0;i--) ch=buf[i],buf[i]=buf[a[0]-1-i],buf[a[0]-1-i]=ch; for (a[0]=(a[0]+DIGIT-1)/DIGIT,j=strlen(buf);j<a[0]*DIGIT;buf[j++]='0'); for (i=1;i<=a[0];i++) for (a[i]=0,j=0;j<DIGIT;j++) a[i]=a[i]*10+buf[i*DIGIT-1-j]-'0'; for (;!a[a[0]]&&a[0]>1;a[0]--); return 1; } void write(const bignum_t a,ostream& os=cout){ int i,j; for (os<<a[i=a[0]],i--;i;i--) for (j=DEPTH/10;j;j/=10) os<<a[i]/j%10; } int comp(const bignum_t a,const bignum_t b){ int i; if (a[0]!=b[0]) return a[0]-b[0]; for (i=a[0];i;i--) if (a[i]!=b[i]) return a[i]-b[i]; return 0; } int comp(const bignum_t a,const int b){ int c[12]={1}; for (c[1]=b;c[c[0]]>=DEPTH;c[c[0]+1]=c[c[0]]/DEPTH,c[c[0]]%=DEPTH,c[0]++); return comp(a,c); } int comp(const bignum_t a,const int c,const int d,const bignum_t b){ int i,t=0,O=-DEPTH*2; if (b[0]-a[0]<d&&c) return 1; for (i=b[0];i>d;i--){ t=t*DEPTH+a[i-d]*c-b[i]; if (t>0) return 1; if (t<O) return 0; } for (i=d;i;i--){ t=t*DEPTH-b[i]; if (t>0) return 1; if (t<O) return 0; } return t>0; } void add(bignum_t a,const bignum_t b){ int i; for (i=1;i<=b[0];i++) if ((a[i]+=b[i])>=DEPTH) a[i]-=DEPTH,a[i+1]++; if (b[0]>=a[0]) a[0]=b[0]; else for (;a[i]>=DEPTH&&i<a[0];a[i]-=DEPTH,i++,a[i]++); a[0]+=(a[a[0]+1]>0); } void add(bignum_t a,const int b){ int i=1; for (a[1]+=b;a[i]>=DEPTH&&i<a[0];a[i+1]+=a[i]/DEPTH,a[i]%=DEPTH,i++); for (;a[a[0]]>=DEPTH;a[a[0]+1]=a[a[0]]/DEPTH,a[a[0]]%=DEPTH,a[0]++); } void sub(bignum_t a,const bignum_t b){ int i; for (i=1;i<=b[0];i++) if ((a[i]-=b[i])<0) a[i+1]--,a[i]+=DEPTH; for (;a[i]<0;a[i]+=DEPTH,i++,a[i]--); for (;!a[a[0]]&&a[0]>1;a[0]--); } void sub(bignum_t a,const int b){ int i=1; for (a[1]-=b;a[i]<0;a[i+1]+=(a[i]-DEPTH+1)/DEPTH,a[i]-=(a[i]-DEPTH+1)/DEPTH*DEPTH,i++); for (;!a[a[0]]&&a[0]>1;a[0]--); } void sub(bignum_t a,const bignum_t b,const int c,const int d){ int i,O=b[0]+d; for (i=1+d;i<=O;i++) if ((a[i]-=b[i-d]*c)<0) a[i+1]+=(a[i]-DEPTH+1)/DEPTH,a[i]-=(a[i]-DEPTH+1)/DEPTH*DEPTH; for (;a[i]<0;a[i+1]+=(a[i]-DEPTH+1)/DEPTH,a[i]-=(a[i]-DEPTH+1)/DEPTH*DEPTH,i++); for (;!a[a[0]]&&a[0]>1;a[0]--); } void mul(bignum_t c,const bignum_t a,const bignum_t b){ int i,j; memset((void*)c,0,sizeof(bignum_t)); for (c[0]=a[0]+b[0]-1,i=1;i<=a[0];i++) for (j=1;j<=b[0];j++) if ((c[i+j-1]+=a[i]*b[j])>=DEPTH) c[i+j]+=c[i+j-1]/DEPTH,c[i+j-1]%=DEPTH; for (c[0]+=(c[c[0]+1]>0);!c[c[0]]&&c[0]>1;c[0]--); } void mul(bignum_t a,const int b){ int i; for (a[1]*=b,i=2;i<=a[0];i++){ a[i]*=b; if (a[i-1]>=DEPTH) a[i]+=a[i-1]/DEPTH,a[i-1]%=DEPTH; } for (;a[a[0]]>=DEPTH;a[a[0]+1]=a[a[0]]/DEPTH,a[a[0]]%=DEPTH,a[0]++); for (;!a[a[0]]&&a[0]>1;a[0]--); } void mul(bignum_t b,const bignum_t a,const int c,const int d){ int i; memset((void*)b,0,sizeof(bignum_t)); for (b[0]=a[0]+d,i=d+1;i<=b[0];i++) if ((b[i]+=a[i-d]*c)>=DEPTH) b[i+1]+=b[i]/DEPTH,b[i]%=DEPTH; for (;b[b[0]+1];b[0]++,b[b[0]+1]=b[b[0]]/DEPTH,b[b[0]]%=DEPTH); for (;!b[b[0]]&&b[0]>1;b[0]--); } void div(bignum_t c,bignum_t a,const bignum_t b){ int h,l,m,i; memset((void*)c,0,sizeof(bignum_t)); c[0]=(b[0]<a[0]+1)?(a[0]-b[0]+2):1; for (i=c[0];i;sub(a,b,c[i]=m,i-1),i--) for (h=DEPTH-1,l=0,m=(h+l+1)>>1;h>l;m=(h+l+1)>>1) if (comp(b,m,i-1,a)) h=m-1; else l=m; for (;!c[c[0]]&&c[0]>1;c[0]--); c[0]=c[0]>1?c[0]:1; } void div(bignum_t a,const int b,int& c){ int i; for (c=0,i=a[0];i;c=c*DEPTH+a[i],a[i]=c/b,c%=b,i--); for (;!a[a[0]]&&a[0]>1;a[0]--); } void sqrt(bignum_t b,bignum_t a){ int h,l,m,i; memset((void*)b,0,sizeof(bignum_t)); for (i=b[0]=(a[0]+1)>>1;i;sub(a,b,m,i-1),b[i]+=m,i--) for (h=DEPTH-1,l=0,b[i]=m=(h+l+1)>>1;h>l;b[i]=m=(h+l+1)>>1) if (comp(b,m,i-1,a)) h=m-1; else l=m; for (;!b[b[0]]&&b[0]>1;b[0]--); for (i=1;i<=b[0];b[i++]>>=1); } int length(const bignum_t a){ int t,ret; for (ret=(a[0]-1)*DIGIT,t=a[a[0]];t;t/=10,ret++); return ret>0?ret:1; } int digit(const bignum_t a,const int b){ int i,ret; for (ret=a[(b-1)/DIGIT+1],i=(b-1)%DIGIT;i;ret/=10,i--); return ret%10; } int zeronum(const bignum_t a){ int ret,t; for (ret=0;!a[ret+1];ret++); for (t=a[ret+1],ret*=DIGIT;!(t%10);t/=10,ret++); return ret; } void comp(int* a,const int l,const int h,const int d){ int i,j,t; for (i=l;i<=h;i++) for (t=i,j=2;t>1;j++) while (!(t%j)) a[j]+=d,t/=j; } void convert(int* a,const int h,bignum_t b){ int i,j,t=1; memset(b,0,sizeof(bignum_t)); for (b[0]=b[1]=1,i=2;i<=h;i++) if (a[i]) for (j=a[i];j;t*=i,j--) if (t*i>DEPTH) mul(b,t),t=1; mul(b,t); } void combination(bignum_t a,int m,int n){ int* t=new int[m+1]; memset((void*)t,0,sizeof(int)*(m+1)); comp(t,n+1,m,1); comp(t,2,m-n,-1); convert(t,m,a); delete []t; } void permutation(bignum_t a,int m,int n){ int i,t=1; memset(a,0,sizeof(bignum_t)); a[0]=a[1]=1; for (i=m-n+1;i<=m;t*=i++) if (t*i>DEPTH) mul(a,t),t=1; mul(a,t); } #define SGN(x) ((x)>0?1:((x)<0?-1:0)) #define ABS(x) ((x)>0?(x):-(x)) int read(bignum_t a,int &sgn,istream& is=cin){ char str[MAX*DIGIT+2],ch,*buf; int i,j; memset((void*)a,0,sizeof(bignum_t)); if (!(is>>str)) return 0; buf=str,sgn=1; if (*buf=='-') sgn=-1,buf++; for (a[0]=strlen(buf),i=a[0]/2-1;i>=0;i--) ch=buf[i],buf[i]=buf[a[0]-1-i],buf[a[0]-1-i]=ch; for (a[0]=(a[0]+DIGIT-1)/DIGIT,j=strlen(buf);j<a[0]*DIGIT;buf[j++]='0'); for (i=1;i<=a[0];i++) for (a[i]=0,j=0;j<DIGIT;j++) a[i]=a[i]*10+buf[i*DIGIT-1-j]-'0'; for (;!a[a[0]]&&a[0]>1;a[0]--); if (a[0]==1&&!a[1]) sgn=0; return 1; } struct bignum{ bignum_t num; int sgn; public: inline bignum(){memset(num,0,sizeof(bignum_t));num[0]=1;sgn=0;} inline int operator!(){return num[0]==1&&!num[1];} inline bignum& operator=(const bignum& a){memcpy(num,a.num,sizeof(bignum_t));sgn=a.sgn;return *this;} inline bignum& operator=(const int a){memset(num,0,sizeof(bignum_t));num[0]=1;sgn=SGN(a);add(num,sgn*a);return *this;}; inline bignum& operator+=(const bignum& a){if(sgn==a.sgn)add(num,a.num);else if(sgn&&a.sgn){int ret=comp(num,a.num);if(ret>0)sub(num,a.num);else if(ret<0){bignum_t t; memcpy(t,num,sizeof(bignum_t));memcpy(num,a.num,sizeof(bignum_t));sub(num,t);sgn=a.sgn;}else memset(num,0,sizeof(bignum_t)),num[0]=1,sgn=0;}else if(!sgn)memcpy(num,a.num,sizeof(bignum_t)),sgn=a.sgn;return *this;} inline bignum& operator+=(const int a){if(sgn*a>0)add(num,ABS(a));else if(sgn&&a){int ret=comp(num,ABS(a));if(ret>0)sub(num,ABS(a));else if(ret<0){bignum_t t; memcpy(t,num,sizeof(bignum_t));memset(num,0,sizeof(bignum_t));num[0]=1;add(num,ABS(a));sgn=-sgn;sub(num,t);}else memset(num,0,sizeof(bignum_t)),num[0]=1,sgn=0;}else if(!sgn)sgn=SGN(a),add(num,ABS(a));return *this;} inline bignum operator+(const bignum& a){bignum ret;memcpy(ret.num,num,sizeof(bignum_t));ret.sgn=sgn;ret+=a;return ret;} inline bignum operator+(const int a){bignum ret;memcpy(ret.num,num,sizeof(bignum_t));ret.sgn=sgn;ret+=a;return ret;} inline bignum& operator-=(const bignum& a){if(sgn*a.sgn<0)add(num,a.num);else if(sgn&&a.sgn){int ret=comp(num,a.num);if(ret>0)sub(num,a.num);else if(ret<0){bignum_t t; memcpy(t,num,sizeof(bignum_t));memcpy(num,a.num,sizeof(bignum_t));sub(num,t);sgn=-sgn;}else memset(num,0,sizeof(bignum_t)),num[0]=1,sgn=0;}else if(!sgn)add(num,a.num),sgn=-a.sgn;return *this;} inline bignum& operator-=(const int a){if(sgn*a<0)add(num,ABS(a));else if(sgn&&a){int ret=comp(num,ABS(a));if(ret>0)sub(num,ABS(a));else if(ret<0){bignum_t t; memcpy(t,num,sizeof(bignum_t));memset(num,0,sizeof(bignum_t));num[0]=1;add(num,ABS(a));sub(num,t);sgn=-sgn;}else memset(num,0,sizeof(bignum_t)),num[0]=1,sgn=0;}else if(!sgn)sgn=-SGN(a),add(num,ABS(a));return *this;} inline bignum operator-(const bignum& a){bignum ret;memcpy(ret.num,num,sizeof(bignum_t));ret.sgn=sgn;ret-=a;return ret;} inline bignum operator-(const int a){bignum ret;memcpy(ret.num,num,sizeof(bignum_t));ret.sgn=sgn;ret-=a;return ret;} inline bignum& operator*=(const bignum& a){bignum_t t;mul(t,num,a.num);memcpy(num,t,sizeof(bignum_t));sgn*=a.sgn;return *this;} inline bignum& operator*=(const int a){mul(num,ABS(a));sgn*=SGN(a);return *this;} inline bignum operator*(const bignum& a){bignum ret;mul(ret.num,num,a.num);ret.sgn=sgn*a.sgn;return ret;} inline bignum operator*(const int a){bignum ret;memcpy(ret.num,num,sizeof(bignum_t));mul(ret.num,ABS(a));ret.sgn=sgn*SGN(a);return ret;} inline bignum& operator/=(const bignum& a){bignum_t t;div(t,num,a.num);memcpy(num,t,sizeof(bignum_t));sgn=(num[0]==1&&!num[1])?0:sgn*a.sgn;return *this;} inline bignum& operator/=(const int a){int t;div(num,ABS(a),t);sgn=(num[0]==1&&!num[1])?0:sgn*SGN(a);return *this;} inline bignum operator/(const bignum& a){bignum ret;bignum_t t;memcpy(t,num,sizeof(bignum_t));div(ret.num,t,a.num);ret.sgn=(ret.num[0]==1&&!ret.num[1])?0:sgn*a.sgn;return ret;} inline bignum operator/(const int a){bignum ret;int t;memcpy(ret.num,num,sizeof(bignum_t));div(ret.num,ABS(a),t);ret.sgn=(ret.num[0]==1&&!ret.num[1])?0:sgn*SGN(a);return ret;} inline bignum& operator%=(const bignum& a){bignum_t t;div(t,num,a.num);if (num[0]==1&&!num[1])sgn=0;return *this;} inline int operator%=(const int a){int t;div(num,ABS(a),t);memset(num,0,sizeof(bignum_t));num[0]=1;add(num,t);return t;} inline bignum operator%(const bignum& a){bignum ret;bignum_t t;memcpy(ret.num,num,sizeof(bignum_t));div(t,ret.num,a.num);ret.sgn=(ret.num[0]==1&&!ret.num[1])?0:sgn;return ret;} inline int operator%(const int a){bignum ret;int t;memcpy(ret.num,num,sizeof(bignum_t));div(ret.num,ABS(a),t);memset(ret.num,0,sizeof(bignum_t));ret.num[0]=1;add(ret.num,t);return t;} inline bignum& operator++(){*this+=1;return *this;} inline bignum& operator--(){*this-=1;return *this;}; inline int operator>(const bignum& a){return sgn>0?(a.sgn>0?comp(num,a.num)>0:1):(sgn<0?(a.sgn<0?comp(num,a.num)<0:0):a.sgn<0);} inline int operator>(const int a){return sgn>0?(a>0?comp(num,a)>0:1):(sgn<0?(a<0?comp(num,-a)<0:0):a<0);} inline int operator>=(const bignum& a){return sgn>0?(a.sgn>0?comp(num,a.num)>=0:1):(sgn<0?(a.sgn<0?comp(num,a.num)<=0:0):a.sgn<=0);} inline int operator>=(const int a){return sgn>0?(a>0?comp(num,a)>=0:1):(sgn<0?(a<0?comp(num,-a)<=0:0):a<=0);} inline int operator<(const bignum& a){return sgn<0?(a.sgn<0?comp(num,a.num)>0:1):(sgn>0?(a.sgn>0?comp(num,a.num)<0:0):a.sgn>0);} inline int operator<(const int a){return sgn<0?(a<0?comp(num,-a)>0:1):(sgn>0?(a>0?comp(num,a)<0:0):a>0);} inline int operator<=(const bignum& a){return sgn<0?(a.sgn<0?comp(num,a.num)>=0:1):(sgn>0?(a.sgn>0?comp(num,a.num)<=0:0):a.sgn>=0);} inline int operator<=(const int a){return sgn<0?(a<0?comp(num,-a)>=0:1):(sgn>0?(a>0?comp(num,a)<=0:0):a>=0);} inline int operator==(const bignum& a){return (sgn==a.sgn)?!comp(num,a.num):0;} inline int operator==(const int a){return (sgn*a>=0)?!comp(num,ABS(a)):0;} inline int operator!=(const bignum& a){return (sgn==a.sgn)?comp(num,a.num):1;} inline int operator!=(const int a){return (sgn*a>=0)?comp(num,ABS(a)):1;} inline int operator[](const int a){return digit(num,a);} friend inline istream& operator>>(istream& is,bignum& a){read(a.num,a.sgn,is);return is;} friend inline ostream& operator<<(ostream& os,const bignum& a){if(a.sgn<0)os<<'-';write(a.num,os);return os;} friend inline bignum sqrt(const bignum& a){bignum ret;bignum_t t;memcpy(t,a.num,sizeof(bignum_t));sqrt(ret.num,t);ret.sgn=ret.num[0]!=1||ret.num[1];return ret;} friend inline bignum sqrt(const bignum& a,bignum& b){bignum ret;memcpy(b.num,a.num,sizeof(bignum_t));sqrt(ret.num,b.num);ret.sgn=ret.num[0]!=1||ret.num[1];b.sgn=b.num[0]!=1||ret.num[1];return ret;} inline int length(){return ::length(num);} inline int zeronum(){return ::zeronum(num);} inline bignum C(const int m,const int n){combination(num,m,n);sgn=1;return *this;} inline bignum P(const int m,const int n){permutation(num,m,n);sgn=1;return *this;} }; int a[22][3]; bool vis[3003]; void dfs(int u,int cnt,) int main() { int n,k; while(cin>>n>>k) { for(int i=0;i<k;++i)for(int j=0;j<3;++j)scanf("%d",&a[i][j]); } return 0; }
[ "316403398@qq.com" ]
316403398@qq.com
6d974475b1d9549ffdc4dc0ac1989bfaba9add76
b7f1b4df5d350e0edf55521172091c81f02f639e
/storage/browser/blob/blob_registry_impl_unittest.cc
5d1b2793226c3fdf0f81c9e51354042d27fe21dd
[ "BSD-3-Clause" ]
permissive
blusno1/chromium-1
f13b84547474da4d2702341228167328d8cd3083
9dd22fe142b48f14765a36f69344ed4dbc289eb3
refs/heads/master
2023-05-17T23:50:16.605396
2018-01-12T19:39:49
2018-01-12T19:39:49
117,339,342
4
2
NOASSERTION
2020-07-17T07:35:37
2018-01-13T11:48:57
null
UTF-8
C++
false
false
36,421
cc
// Copyright 2017 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "storage/browser/blob/blob_registry_impl.h" #include <limits> #include "base/files/scoped_temp_dir.h" #include "base/rand_util.h" #include "base/run_loop.h" #include "base/task_scheduler/post_task.h" #include "base/test/scoped_task_environment.h" #include "base/threading/thread_restrictions.h" #include "mojo/edk/embedder/embedder.h" #include "mojo/public/cpp/bindings/strong_binding.h" #include "storage/browser/blob/blob_data_builder.h" #include "storage/browser/blob/blob_data_handle.h" #include "storage/browser/blob/blob_storage_context.h" #include "storage/browser/test/mock_blob_registry_delegate.h" #include "storage/browser/test/mock_bytes_provider.h" #include "storage/browser/test/mock_special_storage_policy.h" #include "testing/gtest/include/gtest/gtest.h" namespace storage { namespace { const size_t kTestBlobStorageIPCThresholdBytes = 5; const size_t kTestBlobStorageMaxSharedMemoryBytes = 20; const size_t kTestBlobStorageMaxBytesDataItemSize = 13; const size_t kTestBlobStorageMaxBlobMemorySize = 400; const uint64_t kTestBlobStorageMaxDiskSpace = 4000; const uint64_t kTestBlobStorageMinFileSizeBytes = 10; const uint64_t kTestBlobStorageMaxFileSizeBytes = 100; class MockBlob : public blink::mojom::Blob { public: explicit MockBlob(const std::string& uuid) : uuid_(uuid) {} void Clone(blink::mojom::BlobRequest request) override { mojo::MakeStrongBinding(base::MakeUnique<MockBlob>(uuid_), std::move(request)); } void ReadRange(uint64_t offset, uint64_t size, mojo::ScopedDataPipeProducerHandle, blink::mojom::BlobReaderClientPtr) override { NOTREACHED(); } void ReadAll(mojo::ScopedDataPipeProducerHandle, blink::mojom::BlobReaderClientPtr) override { NOTREACHED(); } void GetInternalUUID(GetInternalUUIDCallback callback) override { std::move(callback).Run(uuid_); } private: std::string uuid_; }; void BindBytesProvider(std::unique_ptr<MockBytesProvider> impl, blink::mojom::BytesProviderRequest request) { mojo::MakeStrongBinding(std::move(impl), std::move(request)); } } // namespace class BlobRegistryImplTest : public testing::Test { public: void SetUp() override { ASSERT_TRUE(data_dir_.CreateUniqueTempDir()); context_ = base::MakeUnique<BlobStorageContext>( data_dir_.GetPath(), base::CreateTaskRunnerWithTraits({base::MayBlock()})); auto storage_policy = base::MakeRefCounted<content::MockSpecialStoragePolicy>(); file_system_context_ = base::MakeRefCounted<storage::FileSystemContext>( base::ThreadTaskRunnerHandle::Get().get(), base::ThreadTaskRunnerHandle::Get().get(), nullptr /* external_mount_points */, storage_policy.get(), nullptr /* quota_manager_proxy */, std::vector<std::unique_ptr<FileSystemBackend>>(), std::vector<URLRequestAutoMountHandler>(), data_dir_.GetPath(), FileSystemOptions(FileSystemOptions::PROFILE_MODE_INCOGNITO, std::vector<std::string>(), nullptr)); registry_impl_ = base::MakeUnique<BlobRegistryImpl>(context_->AsWeakPtr(), file_system_context_); auto delegate = base::MakeUnique<MockBlobRegistryDelegate>(); delegate_ptr_ = delegate.get(); registry_impl_->Bind(MakeRequest(&registry_), std::move(delegate)); mojo::edk::SetDefaultProcessErrorCallback(base::Bind( &BlobRegistryImplTest::OnBadMessage, base::Unretained(this))); storage::BlobStorageLimits limits; limits.max_ipc_memory_size = kTestBlobStorageIPCThresholdBytes; limits.max_shared_memory_size = kTestBlobStorageMaxSharedMemoryBytes; limits.max_bytes_data_item_size = kTestBlobStorageMaxBytesDataItemSize; limits.max_blob_in_memory_space = kTestBlobStorageMaxBlobMemorySize; limits.desired_max_disk_space = kTestBlobStorageMaxDiskSpace; limits.effective_max_disk_space = kTestBlobStorageMaxDiskSpace; limits.min_page_file_size = kTestBlobStorageMinFileSizeBytes; limits.max_file_size = kTestBlobStorageMaxFileSizeBytes; context_->mutable_memory_controller()->set_limits_for_testing(limits); // Disallow IO on the main loop. base::ThreadRestrictions::SetIOAllowed(false); } void TearDown() override { base::ThreadRestrictions::SetIOAllowed(true); mojo::edk::SetDefaultProcessErrorCallback( mojo::edk::ProcessErrorCallback()); } std::unique_ptr<BlobDataHandle> CreateBlobFromString( const std::string& uuid, const std::string& contents) { BlobDataBuilder builder(uuid); builder.set_content_type("text/plain"); builder.AppendData(contents); return context_->AddFinishedBlob(builder); } std::string UUIDFromBlob(blink::mojom::Blob* blob) { base::RunLoop loop; std::string received_uuid; blob->GetInternalUUID(base::Bind( [](base::Closure quit_closure, std::string* uuid_out, const std::string& uuid) { *uuid_out = uuid; quit_closure.Run(); }, loop.QuitClosure(), &received_uuid)); loop.Run(); return received_uuid; } void OnBadMessage(const std::string& error) { bad_messages_.push_back(error); } void WaitForBlobCompletion(BlobDataHandle* blob_handle) { base::RunLoop loop; blob_handle->RunOnConstructionComplete(base::Bind( [](const base::Closure& closure, BlobStatus status) { closure.Run(); }, loop.QuitClosure())); loop.Run(); } blink::mojom::BytesProviderPtrInfo CreateBytesProvider( const std::string& bytes) { if (!bytes_provider_runner_) { bytes_provider_runner_ = base::CreateSequencedTaskRunnerWithTraits({base::MayBlock()}); } blink::mojom::BytesProviderPtrInfo result; auto provider = base::MakeUnique<MockBytesProvider>( std::vector<uint8_t>(bytes.begin(), bytes.end()), &reply_request_count_, &stream_request_count_, &file_request_count_); bytes_provider_runner_->PostTask( FROM_HERE, base::BindOnce(&BindBytesProvider, std::move(provider), MakeRequest(&result))); return result; } void CreateBytesProvider(const std::string& bytes, blink::mojom::BytesProviderRequest request) { if (!bytes_provider_runner_) { bytes_provider_runner_ = base::CreateSequencedTaskRunnerWithTraits({base::MayBlock()}); } auto provider = base::MakeUnique<MockBytesProvider>( std::vector<uint8_t>(bytes.begin(), bytes.end()), &reply_request_count_, &stream_request_count_, &file_request_count_); bytes_provider_runner_->PostTask( FROM_HERE, base::BindOnce(&BindBytesProvider, std::move(provider), std::move(request))); } size_t BlobsUnderConstruction() { return registry_impl_->BlobsUnderConstructionForTesting(); } protected: base::ScopedTempDir data_dir_; base::test::ScopedTaskEnvironment scoped_task_environment_; std::unique_ptr<BlobStorageContext> context_; scoped_refptr<storage::FileSystemContext> file_system_context_; std::unique_ptr<BlobRegistryImpl> registry_impl_; blink::mojom::BlobRegistryPtr registry_; MockBlobRegistryDelegate* delegate_ptr_; scoped_refptr<base::SequencedTaskRunner> bytes_provider_runner_; size_t reply_request_count_ = 0; size_t stream_request_count_ = 0; size_t file_request_count_ = 0; std::vector<std::string> bad_messages_; }; TEST_F(BlobRegistryImplTest, GetBlobFromUUID) { const std::string kId = "id"; std::unique_ptr<BlobDataHandle> handle = CreateBlobFromString(kId, "hello world"); { blink::mojom::BlobPtr blob; registry_->GetBlobFromUUID(MakeRequest(&blob), kId); EXPECT_EQ(kId, UUIDFromBlob(blob.get())); EXPECT_FALSE(blob.encountered_error()); } { blink::mojom::BlobPtr blob; registry_->GetBlobFromUUID(MakeRequest(&blob), "invalid id"); blob.FlushForTesting(); EXPECT_TRUE(blob.encountered_error()); } } TEST_F(BlobRegistryImplTest, GetBlobFromEmptyUUID) { blink::mojom::BlobPtr blob; registry_->GetBlobFromUUID(MakeRequest(&blob), ""); blob.FlushForTesting(); EXPECT_EQ(1u, bad_messages_.size()); EXPECT_TRUE(blob.encountered_error()); } TEST_F(BlobRegistryImplTest, Register_EmptyUUID) { blink::mojom::BlobPtr blob; EXPECT_FALSE( registry_->Register(MakeRequest(&blob), "", "", "", std::vector<blink::mojom::DataElementPtr>())); EXPECT_EQ(1u, bad_messages_.size()); registry_.FlushForTesting(); EXPECT_TRUE(registry_.encountered_error()); blob.FlushForTesting(); EXPECT_TRUE(blob.encountered_error()); EXPECT_EQ(0u, BlobsUnderConstruction()); } TEST_F(BlobRegistryImplTest, Register_ExistingUUID) { const std::string kId = "id"; std::unique_ptr<BlobDataHandle> handle = CreateBlobFromString(kId, "hello world"); blink::mojom::BlobPtr blob; EXPECT_FALSE( registry_->Register(MakeRequest(&blob), kId, "", "", std::vector<blink::mojom::DataElementPtr>())); EXPECT_EQ(1u, bad_messages_.size()); registry_.FlushForTesting(); EXPECT_TRUE(registry_.encountered_error()); blob.FlushForTesting(); EXPECT_TRUE(blob.encountered_error()); EXPECT_EQ(0u, BlobsUnderConstruction()); } TEST_F(BlobRegistryImplTest, Register_EmptyBlob) { const std::string kId = "id"; const std::string kContentType = "content/type"; const std::string kContentDisposition = "disposition"; blink::mojom::BlobPtr blob; EXPECT_TRUE(registry_->Register(MakeRequest(&blob), kId, kContentType, kContentDisposition, std::vector<blink::mojom::DataElementPtr>())); EXPECT_TRUE(bad_messages_.empty()); EXPECT_EQ(kId, UUIDFromBlob(blob.get())); EXPECT_TRUE(context_->registry().HasEntry(kId)); std::unique_ptr<BlobDataHandle> handle = context_->GetBlobDataFromUUID(kId); EXPECT_EQ(kContentType, handle->content_type()); EXPECT_EQ(kContentDisposition, handle->content_disposition()); EXPECT_EQ(0u, handle->size()); WaitForBlobCompletion(handle.get()); EXPECT_FALSE(handle->IsBroken()); EXPECT_EQ(BlobStatus::DONE, handle->GetBlobStatus()); EXPECT_EQ(0u, BlobsUnderConstruction()); } TEST_F(BlobRegistryImplTest, Register_ReferencedBlobClosedPipe) { const std::string kId = "id"; std::vector<blink::mojom::DataElementPtr> elements; blink::mojom::BlobPtrInfo referenced_blob_info; MakeRequest(&referenced_blob_info); elements.push_back( blink::mojom::DataElement::NewBlob(blink::mojom::DataElementBlob::New( std::move(referenced_blob_info), 0, 16))); blink::mojom::BlobPtr blob; EXPECT_TRUE(registry_->Register(MakeRequest(&blob), kId, "", "", std::move(elements))); EXPECT_TRUE(bad_messages_.empty()); std::unique_ptr<BlobDataHandle> handle = context_->GetBlobDataFromUUID(kId); WaitForBlobCompletion(handle.get()); EXPECT_TRUE(handle->IsBroken()); EXPECT_EQ(BlobStatus::ERR_REFERENCED_BLOB_BROKEN, handle->GetBlobStatus()); EXPECT_EQ(0u, BlobsUnderConstruction()); } TEST_F(BlobRegistryImplTest, Register_SelfReference) { const std::string kId = "id"; blink::mojom::BlobPtrInfo blob_info; blink::mojom::BlobRequest blob_request = MakeRequest(&blob_info); std::vector<blink::mojom::DataElementPtr> elements; elements.push_back(blink::mojom::DataElement::NewBlob( blink::mojom::DataElementBlob::New(std::move(blob_info), 0, 16))); EXPECT_TRUE(registry_->Register(std::move(blob_request), kId, "", "", std::move(elements))); EXPECT_TRUE(bad_messages_.empty()); std::unique_ptr<BlobDataHandle> handle = context_->GetBlobDataFromUUID(kId); WaitForBlobCompletion(handle.get()); EXPECT_TRUE(handle->IsBroken()); EXPECT_EQ(BlobStatus::ERR_INVALID_CONSTRUCTION_ARGUMENTS, handle->GetBlobStatus()); EXPECT_EQ(1u, bad_messages_.size()); registry_.FlushForTesting(); EXPECT_TRUE(registry_.encountered_error()); EXPECT_EQ(0u, BlobsUnderConstruction()); } TEST_F(BlobRegistryImplTest, Register_CircularReference) { const std::string kId1 = "id1"; const std::string kId2 = "id2"; const std::string kId3 = "id3"; blink::mojom::BlobPtrInfo blob1_info, blob2_info, blob3_info; blink::mojom::BlobRequest blob_request1 = MakeRequest(&blob1_info); blink::mojom::BlobRequest blob_request2 = MakeRequest(&blob2_info); blink::mojom::BlobRequest blob_request3 = MakeRequest(&blob3_info); std::vector<blink::mojom::DataElementPtr> elements1; elements1.push_back(blink::mojom::DataElement::NewBlob( blink::mojom::DataElementBlob::New(std::move(blob1_info), 0, 16))); std::vector<blink::mojom::DataElementPtr> elements2; elements2.push_back(blink::mojom::DataElement::NewBlob( blink::mojom::DataElementBlob::New(std::move(blob2_info), 0, 16))); std::vector<blink::mojom::DataElementPtr> elements3; elements3.push_back(blink::mojom::DataElement::NewBlob( blink::mojom::DataElementBlob::New(std::move(blob3_info), 0, 16))); EXPECT_TRUE(registry_->Register(std::move(blob_request1), kId1, "", "", std::move(elements2))); EXPECT_TRUE(registry_->Register(std::move(blob_request2), kId2, "", "", std::move(elements3))); EXPECT_TRUE(registry_->Register(std::move(blob_request3), kId3, "", "", std::move(elements1))); EXPECT_TRUE(bad_messages_.empty()); #if DCHECK_IS_ON() // Without DCHECKs on this will just hang forever. std::unique_ptr<BlobDataHandle> handle1 = context_->GetBlobDataFromUUID(kId1); std::unique_ptr<BlobDataHandle> handle2 = context_->GetBlobDataFromUUID(kId2); std::unique_ptr<BlobDataHandle> handle3 = context_->GetBlobDataFromUUID(kId3); WaitForBlobCompletion(handle1.get()); WaitForBlobCompletion(handle2.get()); WaitForBlobCompletion(handle3.get()); EXPECT_TRUE(handle1->IsBroken()); EXPECT_TRUE(handle2->IsBroken()); EXPECT_TRUE(handle3->IsBroken()); BlobStatus status1 = handle1->GetBlobStatus(); BlobStatus status2 = handle2->GetBlobStatus(); BlobStatus status3 = handle3->GetBlobStatus(); EXPECT_TRUE(status1 == BlobStatus::ERR_INVALID_CONSTRUCTION_ARGUMENTS || status1 == BlobStatus::ERR_REFERENCED_BLOB_BROKEN); EXPECT_TRUE(status2 == BlobStatus::ERR_INVALID_CONSTRUCTION_ARGUMENTS || status2 == BlobStatus::ERR_REFERENCED_BLOB_BROKEN); EXPECT_TRUE(status3 == BlobStatus::ERR_INVALID_CONSTRUCTION_ARGUMENTS || status3 == BlobStatus::ERR_REFERENCED_BLOB_BROKEN); EXPECT_EQ((status1 == BlobStatus::ERR_INVALID_CONSTRUCTION_ARGUMENTS) + (status2 == BlobStatus::ERR_INVALID_CONSTRUCTION_ARGUMENTS) + (status3 == BlobStatus::ERR_INVALID_CONSTRUCTION_ARGUMENTS), 1); EXPECT_EQ(1u, bad_messages_.size()); registry_.FlushForTesting(); EXPECT_TRUE(registry_.encountered_error()); EXPECT_EQ(0u, BlobsUnderConstruction()); #endif } TEST_F(BlobRegistryImplTest, Register_NonExistentBlob) { const std::string kId = "id"; std::vector<blink::mojom::DataElementPtr> elements; blink::mojom::BlobPtrInfo referenced_blob_info; mojo::MakeStrongBinding(base::MakeUnique<MockBlob>("mock blob"), MakeRequest(&referenced_blob_info)); elements.push_back( blink::mojom::DataElement::NewBlob(blink::mojom::DataElementBlob::New( std::move(referenced_blob_info), 0, 16))); blink::mojom::BlobPtr blob; EXPECT_TRUE(registry_->Register(MakeRequest(&blob), kId, "", "", std::move(elements))); EXPECT_TRUE(bad_messages_.empty()); std::unique_ptr<BlobDataHandle> handle = context_->GetBlobDataFromUUID(kId); WaitForBlobCompletion(handle.get()); EXPECT_TRUE(handle->IsBroken()); EXPECT_EQ(BlobStatus::ERR_INVALID_CONSTRUCTION_ARGUMENTS, handle->GetBlobStatus()); EXPECT_EQ(1u, bad_messages_.size()); registry_.FlushForTesting(); EXPECT_TRUE(registry_.encountered_error()); EXPECT_EQ(0u, BlobsUnderConstruction()); } TEST_F(BlobRegistryImplTest, Register_ValidBlobReferences) { const std::string kId1 = "id1"; std::unique_ptr<BlobDataHandle> handle = CreateBlobFromString(kId1, "hello world"); blink::mojom::BlobPtrInfo blob1_info; mojo::MakeStrongBinding(base::MakeUnique<MockBlob>(kId1), MakeRequest(&blob1_info)); const std::string kId2 = "id2"; blink::mojom::BlobPtrInfo blob2_info; blink::mojom::BlobRequest blob_request2 = MakeRequest(&blob2_info); std::vector<blink::mojom::DataElementPtr> elements1; elements1.push_back(blink::mojom::DataElement::NewBlob( blink::mojom::DataElementBlob::New(std::move(blob1_info), 0, 8))); std::vector<blink::mojom::DataElementPtr> elements2; elements2.push_back(blink::mojom::DataElement::NewBlob( blink::mojom::DataElementBlob::New(std::move(blob2_info), 0, 8))); blink::mojom::BlobPtr final_blob; const std::string kId3 = "id3"; EXPECT_TRUE(registry_->Register(MakeRequest(&final_blob), kId3, "", "", std::move(elements2))); EXPECT_TRUE(registry_->Register(std::move(blob_request2), kId2, "", "", std::move(elements1))); // kId3 references kId2, kId2 reference kId1, kId1 is a simple string. std::unique_ptr<BlobDataHandle> handle2 = context_->GetBlobDataFromUUID(kId2); std::unique_ptr<BlobDataHandle> handle3 = context_->GetBlobDataFromUUID(kId3); WaitForBlobCompletion(handle2.get()); WaitForBlobCompletion(handle3.get()); EXPECT_FALSE(handle2->IsBroken()); ASSERT_EQ(BlobStatus::DONE, handle2->GetBlobStatus()); EXPECT_FALSE(handle3->IsBroken()); ASSERT_EQ(BlobStatus::DONE, handle3->GetBlobStatus()); BlobDataBuilder expected_blob_data(kId2); expected_blob_data.AppendData("hello wo"); EXPECT_EQ(expected_blob_data, *handle2->CreateSnapshot()); EXPECT_EQ(expected_blob_data, *handle3->CreateSnapshot()); EXPECT_EQ(0u, BlobsUnderConstruction()); } TEST_F(BlobRegistryImplTest, Register_UnreadableFile) { delegate_ptr_->can_read_file_result = false; const std::string kId = "id"; std::vector<blink::mojom::DataElementPtr> elements; elements.push_back( blink::mojom::DataElement::NewFile(blink::mojom::DataElementFile::New( base::FilePath(FILE_PATH_LITERAL("foobar")), 0, 16, base::nullopt))); blink::mojom::BlobPtr blob; EXPECT_TRUE(registry_->Register(MakeRequest(&blob), kId, "", "", std::move(elements))); EXPECT_TRUE(bad_messages_.empty()); std::unique_ptr<BlobDataHandle> handle = context_->GetBlobDataFromUUID(kId); WaitForBlobCompletion(handle.get()); EXPECT_TRUE(handle->IsBroken()); EXPECT_EQ(BlobStatus::ERR_REFERENCED_FILE_UNAVAILABLE, handle->GetBlobStatus()); EXPECT_EQ(0u, BlobsUnderConstruction()); } TEST_F(BlobRegistryImplTest, Register_ValidFile) { delegate_ptr_->can_read_file_result = true; const std::string kId = "id"; const base::FilePath path(FILE_PATH_LITERAL("foobar")); std::vector<blink::mojom::DataElementPtr> elements; elements.push_back(blink::mojom::DataElement::NewFile( blink::mojom::DataElementFile::New(path, 0, 16, base::nullopt))); blink::mojom::BlobPtr blob; EXPECT_TRUE(registry_->Register(MakeRequest(&blob), kId, "", "", std::move(elements))); EXPECT_TRUE(bad_messages_.empty()); std::unique_ptr<BlobDataHandle> handle = context_->GetBlobDataFromUUID(kId); WaitForBlobCompletion(handle.get()); EXPECT_FALSE(handle->IsBroken()); ASSERT_EQ(BlobStatus::DONE, handle->GetBlobStatus()); BlobDataBuilder expected_blob_data(kId); expected_blob_data.AppendFile(path, 0, 16, base::Time()); EXPECT_EQ(expected_blob_data, *handle->CreateSnapshot()); EXPECT_EQ(0u, BlobsUnderConstruction()); } TEST_F(BlobRegistryImplTest, Register_FileSystemFile_InvalidScheme) { const std::string kId = "id"; std::vector<blink::mojom::DataElementPtr> elements; elements.push_back(blink::mojom::DataElement::NewFileFilesystem( blink::mojom::DataElementFilesystemURL::New(GURL("http://foobar.com/"), 0, 16, base::nullopt))); blink::mojom::BlobPtr blob; EXPECT_TRUE(registry_->Register(MakeRequest(&blob), kId, "", "", std::move(elements))); EXPECT_TRUE(bad_messages_.empty()); std::unique_ptr<BlobDataHandle> handle = context_->GetBlobDataFromUUID(kId); WaitForBlobCompletion(handle.get()); EXPECT_TRUE(handle->IsBroken()); EXPECT_EQ(BlobStatus::ERR_REFERENCED_FILE_UNAVAILABLE, handle->GetBlobStatus()); EXPECT_EQ(0u, BlobsUnderConstruction()); } TEST_F(BlobRegistryImplTest, Register_FileSystemFile_UnreadablFile) { delegate_ptr_->can_read_file_system_file_result = false; const std::string kId = "id"; const GURL url("filesystem:http://example.com/temporary/myfile.png"); std::vector<blink::mojom::DataElementPtr> elements; elements.push_back(blink::mojom::DataElement::NewFileFilesystem( blink::mojom::DataElementFilesystemURL::New(url, 0, 16, base::nullopt))); blink::mojom::BlobPtr blob; EXPECT_TRUE(registry_->Register(MakeRequest(&blob), kId, "", "", std::move(elements))); EXPECT_TRUE(bad_messages_.empty()); std::unique_ptr<BlobDataHandle> handle = context_->GetBlobDataFromUUID(kId); WaitForBlobCompletion(handle.get()); EXPECT_TRUE(handle->IsBroken()); EXPECT_EQ(BlobStatus::ERR_REFERENCED_FILE_UNAVAILABLE, handle->GetBlobStatus()); EXPECT_EQ(0u, BlobsUnderConstruction()); } TEST_F(BlobRegistryImplTest, Register_FileSystemFile_Valid) { delegate_ptr_->can_read_file_system_file_result = true; const std::string kId = "id"; const GURL url("filesystem:http://example.com/temporary/myfile.png"); std::vector<blink::mojom::DataElementPtr> elements; elements.push_back(blink::mojom::DataElement::NewFileFilesystem( blink::mojom::DataElementFilesystemURL::New(url, 0, 16, base::nullopt))); blink::mojom::BlobPtr blob; EXPECT_TRUE(registry_->Register(MakeRequest(&blob), kId, "", "", std::move(elements))); EXPECT_TRUE(bad_messages_.empty()); std::unique_ptr<BlobDataHandle> handle = context_->GetBlobDataFromUUID(kId); WaitForBlobCompletion(handle.get()); EXPECT_FALSE(handle->IsBroken()); ASSERT_EQ(BlobStatus::DONE, handle->GetBlobStatus()); BlobDataBuilder expected_blob_data(kId); expected_blob_data.AppendFileSystemFile(url, 0, 16, base::Time(), nullptr); EXPECT_EQ(expected_blob_data, *handle->CreateSnapshot()); EXPECT_EQ(0u, BlobsUnderConstruction()); } TEST_F(BlobRegistryImplTest, Register_BytesInvalidEmbeddedData) { const std::string kId = "id"; std::vector<blink::mojom::DataElementPtr> elements; elements.push_back( blink::mojom::DataElement::NewBytes(blink::mojom::DataElementBytes::New( 10, std::vector<uint8_t>(5), CreateBytesProvider("")))); blink::mojom::BlobPtr blob; EXPECT_FALSE(registry_->Register(MakeRequest(&blob), kId, "", "", std::move(elements))); EXPECT_EQ(1u, bad_messages_.size()); registry_.FlushForTesting(); EXPECT_TRUE(registry_.encountered_error()); std::unique_ptr<BlobDataHandle> handle = context_->GetBlobDataFromUUID(kId); WaitForBlobCompletion(handle.get()); EXPECT_TRUE(handle->IsBroken()); EXPECT_EQ(BlobStatus::ERR_INVALID_CONSTRUCTION_ARGUMENTS, handle->GetBlobStatus()); EXPECT_EQ(0u, reply_request_count_); EXPECT_EQ(0u, stream_request_count_); EXPECT_EQ(0u, file_request_count_); EXPECT_EQ(0u, BlobsUnderConstruction()); } TEST_F(BlobRegistryImplTest, Register_BytesInvalidDataSize) { const std::string kId = "id"; // Two elements that together are more than uint64_t::max bytes. std::vector<blink::mojom::DataElementPtr> elements; elements.push_back( blink::mojom::DataElement::NewBytes(blink::mojom::DataElementBytes::New( 8, base::nullopt, CreateBytesProvider("")))); elements.push_back( blink::mojom::DataElement::NewBytes(blink::mojom::DataElementBytes::New( std::numeric_limits<uint64_t>::max() - 4, base::nullopt, CreateBytesProvider("")))); blink::mojom::BlobPtr blob; EXPECT_FALSE(registry_->Register(MakeRequest(&blob), kId, "", "", std::move(elements))); EXPECT_EQ(1u, bad_messages_.size()); registry_.FlushForTesting(); EXPECT_TRUE(registry_.encountered_error()); std::unique_ptr<BlobDataHandle> handle = context_->GetBlobDataFromUUID(kId); WaitForBlobCompletion(handle.get()); EXPECT_TRUE(handle->IsBroken()); EXPECT_EQ(BlobStatus::ERR_INVALID_CONSTRUCTION_ARGUMENTS, handle->GetBlobStatus()); EXPECT_EQ(0u, reply_request_count_); EXPECT_EQ(0u, stream_request_count_); EXPECT_EQ(0u, file_request_count_); EXPECT_EQ(0u, BlobsUnderConstruction()); } TEST_F(BlobRegistryImplTest, Register_BytesOutOfMemory) { const std::string kId = "id"; // Two elements that together don't fit in the test quota. std::vector<blink::mojom::DataElementPtr> elements; elements.push_back( blink::mojom::DataElement::NewBytes(blink::mojom::DataElementBytes::New( kTestBlobStorageMaxDiskSpace, base::nullopt, CreateBytesProvider("")))); elements.push_back( blink::mojom::DataElement::NewBytes(blink::mojom::DataElementBytes::New( kTestBlobStorageMaxDiskSpace, base::nullopt, CreateBytesProvider("")))); blink::mojom::BlobPtr blob; EXPECT_TRUE(registry_->Register(MakeRequest(&blob), kId, "", "", std::move(elements))); std::unique_ptr<BlobDataHandle> handle = context_->GetBlobDataFromUUID(kId); WaitForBlobCompletion(handle.get()); EXPECT_TRUE(handle->IsBroken()); EXPECT_EQ(BlobStatus::ERR_OUT_OF_MEMORY, handle->GetBlobStatus()); EXPECT_EQ(0u, reply_request_count_); EXPECT_EQ(0u, stream_request_count_); EXPECT_EQ(0u, file_request_count_); EXPECT_EQ(0u, BlobsUnderConstruction()); } TEST_F(BlobRegistryImplTest, Register_ValidEmbeddedBytes) { const std::string kId = "id"; const std::string kData = "hello world"; std::vector<blink::mojom::DataElementPtr> elements; elements.push_back( blink::mojom::DataElement::NewBytes(blink::mojom::DataElementBytes::New( kData.size(), std::vector<uint8_t>(kData.begin(), kData.end()), CreateBytesProvider(kData)))); blink::mojom::BlobPtr blob; EXPECT_TRUE(registry_->Register(MakeRequest(&blob), kId, "", "", std::move(elements))); std::unique_ptr<BlobDataHandle> handle = context_->GetBlobDataFromUUID(kId); WaitForBlobCompletion(handle.get()); EXPECT_FALSE(handle->IsBroken()); ASSERT_EQ(BlobStatus::DONE, handle->GetBlobStatus()); BlobDataBuilder expected_blob_data(kId); expected_blob_data.AppendData(kData); EXPECT_EQ(expected_blob_data, *handle->CreateSnapshot()); EXPECT_EQ(0u, reply_request_count_); EXPECT_EQ(0u, stream_request_count_); EXPECT_EQ(0u, file_request_count_); EXPECT_EQ(0u, BlobsUnderConstruction()); } TEST_F(BlobRegistryImplTest, Register_ValidBytesAsReply) { const std::string kId = "id"; const std::string kData = "hello"; std::vector<blink::mojom::DataElementPtr> elements; elements.push_back( blink::mojom::DataElement::NewBytes(blink::mojom::DataElementBytes::New( kData.size(), base::nullopt, CreateBytesProvider(kData)))); blink::mojom::BlobPtr blob; EXPECT_TRUE(registry_->Register(MakeRequest(&blob), kId, "", "", std::move(elements))); std::unique_ptr<BlobDataHandle> handle = context_->GetBlobDataFromUUID(kId); WaitForBlobCompletion(handle.get()); EXPECT_FALSE(handle->IsBroken()); ASSERT_EQ(BlobStatus::DONE, handle->GetBlobStatus()); BlobDataBuilder expected_blob_data(kId); expected_blob_data.AppendData(kData); EXPECT_EQ(expected_blob_data, *handle->CreateSnapshot()); EXPECT_EQ(1u, reply_request_count_); EXPECT_EQ(0u, stream_request_count_); EXPECT_EQ(0u, file_request_count_); EXPECT_EQ(0u, BlobsUnderConstruction()); } TEST_F(BlobRegistryImplTest, Register_ValidBytesAsStream) { const std::string kId = "id"; const std::string kData = base::RandBytesAsString(kTestBlobStorageMaxSharedMemoryBytes * 3 + 13); std::vector<blink::mojom::DataElementPtr> elements; elements.push_back( blink::mojom::DataElement::NewBytes(blink::mojom::DataElementBytes::New( kData.size(), base::nullopt, CreateBytesProvider(kData)))); blink::mojom::BlobPtr blob; EXPECT_TRUE(registry_->Register(MakeRequest(&blob), kId, "", "", std::move(elements))); std::unique_ptr<BlobDataHandle> handle = context_->GetBlobDataFromUUID(kId); WaitForBlobCompletion(handle.get()); EXPECT_FALSE(handle->IsBroken()); ASSERT_EQ(BlobStatus::DONE, handle->GetBlobStatus()); size_t offset = 0; BlobDataBuilder expected_blob_data(kId); while (offset < kData.size()) { expected_blob_data.AppendData( kData.substr(offset, kTestBlobStorageMaxBytesDataItemSize)); offset += kTestBlobStorageMaxBytesDataItemSize; } EXPECT_EQ(expected_blob_data, *handle->CreateSnapshot()); EXPECT_EQ(0u, reply_request_count_); EXPECT_EQ(1u, stream_request_count_); EXPECT_EQ(0u, file_request_count_); EXPECT_EQ(0u, BlobsUnderConstruction()); } TEST_F(BlobRegistryImplTest, Register_ValidBytesAsFile) { const std::string kId = "id"; const std::string kData = base::RandBytesAsString(kTestBlobStorageMaxBlobMemorySize + 42); std::vector<blink::mojom::DataElementPtr> elements; elements.push_back( blink::mojom::DataElement::NewBytes(blink::mojom::DataElementBytes::New( kData.size(), base::nullopt, CreateBytesProvider(kData)))); blink::mojom::BlobPtr blob; EXPECT_TRUE(registry_->Register(MakeRequest(&blob), kId, "", "", std::move(elements))); std::unique_ptr<BlobDataHandle> handle = context_->GetBlobDataFromUUID(kId); WaitForBlobCompletion(handle.get()); EXPECT_FALSE(handle->IsBroken()); ASSERT_EQ(BlobStatus::DONE, handle->GetBlobStatus()); BlobDataBuilder expected_blob_data(kId); expected_blob_data.AppendData(kData); size_t expected_file_count = 1 + kData.size() / kTestBlobStorageMaxFileSizeBytes; EXPECT_EQ(0u, reply_request_count_); EXPECT_EQ(0u, stream_request_count_); EXPECT_EQ(expected_file_count, file_request_count_); auto snapshot = handle->CreateSnapshot(); EXPECT_EQ(expected_file_count, snapshot->items().size()); size_t remaining_size = kData.size(); for (const auto& item : snapshot->items()) { EXPECT_EQ(network::DataElement::TYPE_FILE, item->type()); EXPECT_EQ(0u, item->offset()); if (remaining_size > kTestBlobStorageMaxFileSizeBytes) EXPECT_EQ(kTestBlobStorageMaxFileSizeBytes, item->length()); else EXPECT_EQ(remaining_size, item->length()); remaining_size -= item->length(); } EXPECT_EQ(0u, remaining_size); EXPECT_EQ(0u, BlobsUnderConstruction()); } TEST_F(BlobRegistryImplTest, Register_BytesProviderClosedPipe) { const std::string kId = "id"; blink::mojom::BytesProviderPtrInfo bytes_provider_info; MakeRequest(&bytes_provider_info); std::vector<blink::mojom::DataElementPtr> elements; elements.push_back( blink::mojom::DataElement::NewBytes(blink::mojom::DataElementBytes::New( 32, base::nullopt, std::move(bytes_provider_info)))); blink::mojom::BlobPtr blob; EXPECT_TRUE(registry_->Register(MakeRequest(&blob), kId, "", "", std::move(elements))); EXPECT_TRUE(bad_messages_.empty()); std::unique_ptr<BlobDataHandle> handle = context_->GetBlobDataFromUUID(kId); WaitForBlobCompletion(handle.get()); EXPECT_TRUE(handle->IsBroken()); EXPECT_EQ(BlobStatus::ERR_SOURCE_DIED_IN_TRANSIT, handle->GetBlobStatus()); EXPECT_EQ(0u, BlobsUnderConstruction()); } TEST_F(BlobRegistryImplTest, Register_DefereferencedWhileBuildingBeforeBreaking) { const std::string kId = "id"; blink::mojom::BytesProviderPtrInfo bytes_provider_info; auto request = MakeRequest(&bytes_provider_info); std::vector<blink::mojom::DataElementPtr> elements; elements.push_back( blink::mojom::DataElement::NewBytes(blink::mojom::DataElementBytes::New( 32, base::nullopt, std::move(bytes_provider_info)))); blink::mojom::BlobPtr blob; EXPECT_TRUE(registry_->Register(MakeRequest(&blob), kId, "", "", std::move(elements))); EXPECT_TRUE(bad_messages_.empty()); EXPECT_TRUE(context_->registry().HasEntry(kId)); EXPECT_TRUE(context_->GetBlobDataFromUUID(kId)->IsBeingBuilt()); EXPECT_EQ(1u, BlobsUnderConstruction()); // Now drop all references to the blob. blob.reset(); base::RunLoop().RunUntilIdle(); EXPECT_FALSE(context_->registry().HasEntry(kId)); // Now cause construction to fail, if it would still be going on. request = nullptr; base::RunLoop().RunUntilIdle(); EXPECT_EQ(0u, BlobsUnderConstruction()); } TEST_F(BlobRegistryImplTest, Register_DefereferencedWhileBuildingBeforeResolvingDeps) { const std::string kId = "id"; const std::string kData = "hello world"; const std::string kDepId = "dep-id"; // Create future blob. auto blob_handle = context_->AddFutureBlob(kDepId, "", ""); blink::mojom::BlobPtrInfo referenced_blob_info; mojo::MakeStrongBinding(base::MakeUnique<MockBlob>(kDepId), MakeRequest(&referenced_blob_info)); // Create mojo blob depending on future blob. std::vector<blink::mojom::DataElementPtr> elements; elements.push_back( blink::mojom::DataElement::NewBlob(blink::mojom::DataElementBlob::New( std::move(referenced_blob_info), 0, kData.size()))); blink::mojom::BlobPtr blob; EXPECT_TRUE(registry_->Register(MakeRequest(&blob), kId, "", "", std::move(elements))); EXPECT_TRUE(bad_messages_.empty()); EXPECT_TRUE(context_->registry().HasEntry(kId)); EXPECT_TRUE(context_->GetBlobDataFromUUID(kId)->IsBeingBuilt()); EXPECT_EQ(1u, BlobsUnderConstruction()); // Now drop all references to the blob. blob.reset(); base::RunLoop().RunUntilIdle(); EXPECT_FALSE(context_->registry().HasEntry(kId)); // Now cause construction to complete, if it would still be going on. BlobDataBuilder builder(kDepId); builder.AppendData(kData); context_->BuildPreregisteredBlob( builder, BlobStorageContext::TransportAllowedCallback()); base::RunLoop().RunUntilIdle(); EXPECT_EQ(0u, BlobsUnderConstruction()); } TEST_F(BlobRegistryImplTest, Register_DefereferencedWhileBuildingBeforeTransporting) { const std::string kId = "id"; const std::string kData = "hello world"; blink::mojom::BytesProviderPtrInfo bytes_provider_info; auto request = MakeRequest(&bytes_provider_info); std::vector<blink::mojom::DataElementPtr> elements; elements.push_back( blink::mojom::DataElement::NewBytes(blink::mojom::DataElementBytes::New( kData.size(), base::nullopt, std::move(bytes_provider_info)))); blink::mojom::BlobPtr blob; EXPECT_TRUE(registry_->Register(MakeRequest(&blob), kId, "", "", std::move(elements))); EXPECT_TRUE(bad_messages_.empty()); EXPECT_TRUE(context_->registry().HasEntry(kId)); EXPECT_TRUE(context_->GetBlobDataFromUUID(kId)->IsBeingBuilt()); EXPECT_EQ(1u, BlobsUnderConstruction()); // Now drop all references to the blob. blob.reset(); base::RunLoop().RunUntilIdle(); EXPECT_FALSE(context_->registry().HasEntry(kId)); // Now cause construction to complete, if it would still be going on. CreateBytesProvider(kData, std::move(request)); scoped_task_environment_.RunUntilIdle(); base::RunLoop().RunUntilIdle(); EXPECT_EQ(0u, BlobsUnderConstruction()); } } // namespace storage
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
ab15758caed8952d2209cec466e701d34b854214
aeb853c66226f0ff06cb6ddfb3aed7d94a54a5d5
/TurboTowerTrouble/PlayerManual.cpp
9bd187d2e5793622592244b0d7c007abebdd42d4
[]
no_license
C00192781/TurboTowerTrouble-GroupProject
5c2ca13911290be1d4e8c412508327fd45150209
3ba66a07eeae5d356b584b701b1ae37ed52772ba
refs/heads/master
2020-09-09T09:12:58.238626
2020-07-20T17:07:10
2020-07-20T17:07:10
221,408,336
1
0
null
null
null
null
UTF-8
C++
false
false
530
cpp
//////////////////////////////////////////////////////////// // Name: Kevin Boylan // Student ID: C00192781 //////////////////////////////////////////////////////////// //#include "PlayerManual.h" //#include <iostream> // // // // //PlayerManual::PlayerManual() //{ // if (!playerTexture.loadFromFile("Sprites Folder/Tower Sprites/Dizzy.png")) // { // // error... // } // // circle.setPosition(100.0f, 100.0f); // //circle.setSize // // //if (sf::Joystick::isConnected()) //} // //void PlayerManual::PlayerMovement() //{ // //}
[ "idakev2396@gmail.com" ]
idakev2396@gmail.com
9506a2fd33239864f6e755f63d3b8d396e9b9c59
db23016a502292b8c1cd66498b9264a045ce7c89
/pipeline_kernel/hello.cpp
ed559c715f8bb684cfec931a0b396b47121856af
[]
no_license
xuhz/xrt_testsuite
7ce73b5adce17f4c0b91271a9d26663bbb73be65
05a816007f4d8109048eaf5aac62aef741ddf032
refs/heads/master
2023-04-20T21:18:49.411060
2021-05-07T00:13:48
2021-05-07T00:13:48
286,532,910
0
0
null
null
null
null
UTF-8
C++
false
false
4,121
cpp
/** * Copyright (C) 2016-2020 Xilinx, Inc * * Licensed under the Apache License, Version 2.0 (the "License"). You may * not use this file except in compliance with the License. A copy of the * License is located 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 <iostream> #include <stdexcept> #include <string> #include "experimental/xrt_device.h" #include "experimental/xrt_kernel.h" #include "experimental/xrt_bo.h" /** * Runs an OpenCL kernel which writes "Hello World\n" into the buffer passed */ #define ARRAY_SIZE 20 //////////////////////////////////////////////////////////////////////////////// #define LENGTH (20) //////////////////////////////////////////////////////////////////////////////// static const char gold[] = "Hello World\n"; static void usage() { std::cout << "usage: %s [options] -k <bitstream>\n\n"; std::cout << " -k <bitstream>\n"; std::cout << " -d <index>\n"; std::cout << " -v\n"; std::cout << " -h\n\n"; std::cout << "* Bitstream is required\n"; } static void run(const xrt::device& device, const xrt::uuid& uuid, bool verbose) { auto m2s = xrt::kernel(device, uuid.get(), "m2s:m2s_1"); auto s2m = xrt::kernel(device, uuid.get(), "s2m:s2m_1"); auto boin = xrt::bo(device, 1024, 0, m2s.group_id(0)); std::cout << "In bo created" << std::endl; auto bo_data_in = boin.map<char*>(); std::fill(bo_data_in, bo_data_in + 1024, 'a'); boin.sync(XCL_BO_SYNC_BO_TO_DEVICE, 1024,0); std::cout << "In bo synced" << std::endl; auto boout = xrt::bo(device, 1024, 0, s2m.group_id(1)); auto bo_data_out = boout.map<char*>(); std::cout << "Out bo created" << std::endl; auto runm2s = xrt::run(m2s); runm2s.set_arg(0,boin); runm2s.set_arg(2,1024/4); auto runs2m = xrt::run(s2m); runs2m.set_arg(1,boout); runs2m.set_arg(2,1024/4); std::cout << "Kernel m2s start command issued" << std::endl; runm2s.start(); std::cout << "Kernel s2m start command issued" << std::endl; runs2m.start(); std::cout << "Now wait until the m2s kernel finish" << std::endl; runm2s.wait(); std::cout << "Now wait until the s2m kernel finish" << std::endl; runs2m.wait(); //Get the output; std::cout << "Get the output data from the device" << std::endl; boout.sync(XCL_BO_SYNC_BO_FROM_DEVICE, 1024, 0); std::cout << "RESULT: " << std::endl; for (unsigned i = 0; i < 32; ++i) std::cout << bo_data_out[i]; std::cout << std::endl; } int run(int argc, char** argv) { if (argc < 3) { usage(); return 1; } std::string xclbin_fnm; bool verbose = false; unsigned int device_index = 0; std::vector<std::string> args(argv+1,argv+argc); std::string cur; for (auto& arg : args) { if (arg == "-h") { usage(); return 1; } else if (arg == "-v") { verbose = true; continue; } if (arg[0] == '-') { cur = arg; continue; } if (cur == "-k") xclbin_fnm = arg; else if (cur == "-d") device_index = std::stoi(arg); else throw std::runtime_error("Unknown option value " + cur + " " + arg); } if (xclbin_fnm.empty()) throw std::runtime_error("FAILED_TEST\nNo xclbin specified"); if (device_index >= xclProbe()) throw std::runtime_error("Cannot find device index (" + std::to_string(device_index) + ") specified"); auto device = xrt::device(device_index); auto uuid = device.load_xclbin(xclbin_fnm); run(device, uuid, verbose); return 0; } int main(int argc, char** argv) { try { auto ret = run(argc, argv); std::cout << "PASSED TEST\n"; return ret; } catch (std::exception const& e) { std::cout << "Exception: " << e.what() << "\n"; std::cout << "FAILED TEST\n"; return 1; } std::cout << "PASSED TEST\n"; return 0; }
[ "brianx@xilinx.com" ]
brianx@xilinx.com
5b940ecfa45783012a749b9615a12e18eb3ea440
800965a478f1c8d68c25d0837d1a3ffab75b50e9
/Week-02/day-2/Functions/11.cpp
eca06814595ce334c1bf699d6a4f27ec167ce8cd
[]
no_license
greenfox-zerda-sparta/Ak0s
8ed1eea5a63249cabb58f5de8620884aea7a8503
2f37db6512f6aa7057048ed189ed2259e3ee48ba
refs/heads/master
2021-01-12T18:15:08.523009
2017-02-13T18:06:12
2017-02-13T18:06:12
71,350,507
2
0
null
null
null
null
UTF-8
C++
false
false
513
cpp
//============================================================================ // Name : 11.cpp // Author : Ak0s //============================================================================ // write a function that gets a string as an input // and appends an 'a' character to its end #include <iostream> #include <string> using namespace std; void dog(string a) { a += "a"; cout << "The hungarian word for dog is " << a << "!"; } int main() { string k = "kuty"; dog(k); return 0; }
[ "modis1akos@msn.com" ]
modis1akos@msn.com
3a8ddf190113ccc2bd05bbbb0a0e1b7a8ff6227b
50eeb07fb93d89d981a7c95ed9141405b3105736
/move/inv_between_2opt.hpp
b9fd364ab7d83b0c5a309499c2358013eae892d8
[ "MIT" ]
permissive
zmdsn/MANSP
b143e47e2b7772b43e1132ff4c4a73586feac27a
180b985ed4abc255f5ccce5ee9e4da4e473433e2
refs/heads/main
2023-04-12T06:53:39.728665
2021-05-05T07:31:27
2021-05-05T07:31:27
360,737,970
0
0
null
null
null
null
UTF-8
C++
false
false
6,376
hpp
/************************************************************************* * Name : move.hpp * Author: zmdsn * Mail : zmdsn@126.com * Created Time: 2020年11月18日 星期三 13时47分27秒 * ************************************************************************/ #ifndef __INV_BETWEEN_2OPT__HPP__ #define __INV_BETWEEN_2OPT__HPP__ #include<iostream> #include "../move/move.hpp" using namespace std; class INV_BETWEEN_2OPT:public Move_base{ // (x,y) <==> (u,v) public: Move_base* m; vector<int> P1; vector<int> P2; vector<int> load1; vector<int> load2; inline bool prepare() { pre_val.resize(problem->task_number*2+1); back_val.resize(problem->task_number*2+1); get_val(R1); get_val_back(R1); if (R1!=R2) { get_val(R2); get_val_back(R2); } is_prepared = 1; return 1; } inline bool init_move() { is_legal= is_legal_move(); if (is_legal) { if (!is_prepared) prepare(); u = R1->route[position1]; v = R1->route[position1+1]; x = R2->route[position2]; y = R2->route[position2+1]; up = problem->get_invert(u); vp = problem->get_invert(v); xp = problem->get_invert(x); yp = problem->get_invert(y); R1->get_loads(); R2->get_loads(); get_load1(); get_load2(); loadi = load1[position1]; loadj = load2[position2]; } return 1; } void get_load1(){ loadi = 0; load1.resize(R1->route.size(),0); R1->get_loads(); for (int i=0; i<R1->route.size(); i++) { loadi += problem->get_demand(R1->route[i]); load1[i] = loadi; } } void get_load2(){ loadj = 0; load2.resize(R2->route.size(),0); R2->get_loads(); for (int i=0; i<R2->route.size(); i++) { loadj += problem->get_demand(R2->route[i]); load2[i] = loadj; } } DType get_over_load(){ // if(!is_legal) return 0; if (!is_legal) { over_load = old_over_load; return over_load; } over_load_changed = 0; over_load = 0; DType old_over_load = get_old_over_load(); DType total_over_load = R1->loads + R2->loads; DType temp_load; if (change_mode) { temp_load = loadi+loadj; over_load += problem->get_over_load(temp_load); temp_load = total_over_load-temp_load; over_load += problem->get_over_load(temp_load); } else { temp_load = loadi+R2->loads-loadj; over_load += problem->get_over_load(temp_load); temp_load = loadj+R1->loads-loadi; over_load += problem->get_over_load(temp_load); } over_load_changed = over_load-old_over_load; return over_load; } bool is_legal_move(){ is_legal = !(R1==R2)&&!(position1==0||position2==0); is_legal&=!(position1+1>=R1->route.size()|| position2+1>=R2->route.size()); return is_legal; } bool is_feasible(){ feasible = 1; if(!is_legal) return 0; if(get_over_load()>0) return 0; return 1; } VType merge_costs(int _change_mode) { VType cost=0; int a = _change_mode&1?problem->get_invert(u):u; int b = _change_mode&2?problem->get_invert(v):v; int c = _change_mode&4?problem->get_invert(x):x; int d = _change_mode&8?problem->get_invert(y):y; cost = (*problem)(a,d); cost += (*problem)(c,b); cost += pre_val[a]; cost += back_val[b]; cost += pre_val[c]; cost += back_val[d]; return cost; } VType reverse_costs(int _change_mode) { VType cost=0; int a = _change_mode&1?problem->get_invert(u):u; int b = _change_mode&2?v:problem->get_invert(v); int c = _change_mode&4?x:problem->get_invert(x); int d = _change_mode&8?problem->get_invert(y):y; cost = (*problem)(a,d); cost += (*problem)(c,b); cost += pre_val[a]; cost += back_val[b]; cost += pre_val[c]; cost += back_val[d]; cost -= R1->costs+R2->costs; return cost; } VType get_move_costs(){ // cout<<"between_2opt"<<endl; // 这里有值得商榷的地方 costs = 0; if(!is_legal) return 0; // init_move(); VType cost; // cost = merge_costs(); // change_mode = 0; // costs = cost; // cost = reverse_costs(); // if(cost<costs&&is_feasible()){ // costs = cost; // change_mode = 1; // } for (int i = 1; i <= 16; ++i) { cost = merge_costs(i); if(cost<costs) { costs = cost; costs -= R1->costs+R2->costs; change_mode = i; } } // cout<<costs<<endl; for (int i = 1; i <= 16; ++i) { cost = reverse_costs(i); if(cost<costs) { costs = cost; costs -= R1->costs+R2->costs; change_mode = i+32; } } return costs; } bool move(){ if(!is_legal) return 0; P1.clear(); P2.clear(); if(change_mode){ for (int i = 0; i <= position1; ++i) { P1.push_back(R1->route[i]); } for (int i = position2; i >=0; --i) { P1.push_back(problem->get_invert(R2->route[i])); } for (int i = R1->route.size()-1; i >=position1+1; --i) { P2.push_back(problem->get_invert(R1->route[i])); } for (int i = position2+1; i <R2->route.size(); ++i) { P2.push_back(R2->route[i]); } } else { for (int i = 0; i <= position1; ++i) { P1.push_back(R1->route[i]); } for (int i = position2+1; i <R2->route.size(); ++i) { P1.push_back(R2->route[i]); } for (int i = 0; i <= position2; ++i) { P2.push_back(R2->route[i]); } for (int i = position1+1; i <R1->route.size(); ++i) { P2.push_back(R1->route[i]); } } R1->set_route(P1); R2->set_route(P2); return 1; } INV_BETWEEN_2OPT(){} INV_BETWEEN_2OPT(CARP_INDIVIDUAL *_R1,CARP_INDIVIDUAL *_R2, int _position1, int _position2): Move_base(R1,R2,position1,position2){init_move();} INV_BETWEEN_2OPT(CARP_INDIVIDUAL *_R1,CARP_INDIVIDUAL *_R2): Move_base(_R1,_R2){} }; #endif
[ "zmdsn@126.com" ]
zmdsn@126.com
6681d21f5973d5bc3e348ec87a6de6aa12a24da0
eecf307b289299f444274c41152215f6ae5a9484
/Window.cpp
7b0bee7a1f260c7372429ec53df2b425837f470f
[]
no_license
Josue-Santos/shapes
c4f8d18c56fd633390382dfd4ea149b36f4fde9d
ebe940409cf57f1c5fb15bb5c947bb4b2a681dc4
refs/heads/main
2023-07-12T22:49:08.735898
2021-09-03T16:34:49
2021-09-03T16:34:49
402,820,775
0
0
null
null
null
null
UTF-8
C++
false
false
2,346
cpp
#include "Window.hpp" #include "Win32dow.hpp" #include <stdexcept> using namespace std; namespace easywin { void Window::requestRepaint() { InvalidateRect(hwnd, NULL, true); } void Window::addMenu(string name) { HMENU hmenu = GetMenu(hwnd); if (hmenu == 0) { hmenu = CreateMenu(); } HMENU hPopup = CreateMenu(); AppendMenu(hmenu, MF_POPUP, (UINT_PTR)hPopup, name.c_str()); if (SetMenu(hwnd, hmenu) == 0) { throw runtime_error("Cannot create menu"); } } void Window::addMenuItem(int menuPos, std::string item, int id) { HMENU hmenu = GetMenu(hwnd); if (hmenu == 0) { throw logic_error("Called addMenuItem with invalid menuPos"); } HMENU hPopup = GetSubMenu(hmenu, menuPos); if (hPopup == 0) { throw logic_error("Called addMenuItem with invalid menuPos"); } AppendMenu(hPopup, MF_STRING, (UINT_PTR)id, item.c_str()); } Window::Window(HINSTANCE hInstance, const char* className) { registerClass(hInstance, className); hwnd = CreateWindow( className, // window class name "Window", // window caption WS_OVERLAPPEDWINDOW, // window style CW_USEDEFAULT, // initial x position CW_USEDEFAULT, // initial y position CW_USEDEFAULT, // initial x size CW_USEDEFAULT, // initial y size NULL, // parent window handle NULL, // window menu handle hInstance, // program instance handle this ); } int Window::run() { ShowWindow(hwnd, SW_SHOWNORMAL); MSG msg; while (GetMessage(&msg, NULL, 0, 0)) { TranslateMessage(&msg); DispatchMessage(&msg); } return (int)msg.wParam; } string Window::getTitle() { char buffer[200]; GetWindowText(hwnd, buffer, 200); return buffer; } void Window::setTitle(const string& title) { SetWindowText(hwnd, title.c_str()); } void Window::paint(Canvas& canvas) { RECT client; GetClientRect(hwnd, &client); canvas.drawRectangle(0, 0, client.right, client.bottom, 0xffffff, 0xffffff); } void Window::mouseMove(int x, int y) { } void Window::mouseButtonDown(int x, int y) { } void Window::mouseButtonUp(int x, int y) { } void Window::mouseButtonDoubleClick(int x, int y) { } void Window::mouseWheel(int x, int y, bool up) { } void Window::menuSelect(int i) { } } // namespace easywin
[ "josuesantosfls@gmail.com" ]
josuesantosfls@gmail.com
0d1fb392d692ae51d30d35315116e81d7d2b60dd
f8517de40106c2fc190f0a8c46128e8b67f7c169
/AllJoyn/Samples/MyLivingRoom/Models/org.allseen.LSF/LampServiceProducer.h
639ef1b31f80c3f806658f98b8b44ed3d82b41ed
[ "MIT" ]
permissive
ferreiramarcelo/samples
eb77df10fe39567b7ebf72b75dc8800e2470108a
4691f529dae5c440a5df71deda40c57976ee4928
refs/heads/develop
2023-06-21T00:31:52.939554
2021-01-23T16:26:59
2021-01-23T16:26:59
66,746,116
0
0
MIT
2023-06-19T20:52:43
2016-08-28T02:48:20
C
UTF-8
C++
false
false
6,526
h
#pragma once namespace org { namespace allseen { namespace LSF { extern PCSTR c_LampServiceIntrospectionXml; ref class LampServiceProducer; public interface class ILampServiceProducer { event Windows::Foundation::TypedEventHandler<LampServiceProducer^, Windows::Devices::AllJoyn::AllJoynProducerStoppedEventArgs^>^ Stopped; event Windows::Foundation::TypedEventHandler<LampServiceProducer^, Windows::Devices::AllJoyn::AllJoynSessionLostEventArgs^>^ SessionLost; event Windows::Foundation::TypedEventHandler<LampServiceProducer^, Windows::Devices::AllJoyn::AllJoynSessionMemberAddedEventArgs^>^ SessionMemberAdded; event Windows::Foundation::TypedEventHandler<LampServiceProducer^, Windows::Devices::AllJoyn::AllJoynSessionMemberRemovedEventArgs^>^ SessionMemberRemoved; }; public ref class LampServiceProducer sealed : [Windows::Foundation::Metadata::Default] ILampServiceProducer { public: LampServiceProducer(Windows::Devices::AllJoyn::AllJoynBusAttachment^ busAttachment); virtual ~LampServiceProducer(); // The implementation of ILampServiceService that will handle method calls and property requests. property ILampServiceService^ Service { ILampServiceService^ get() { return m_serviceInterface; } void set(ILampServiceService^ value) { m_serviceInterface = value; } } // Used to send signals or register functions to handle received signals. property LampServiceSignals^ Signals { LampServiceSignals^ get() { return m_signals; } } // This event will fire whenever this producer is stopped. virtual event Windows::Foundation::TypedEventHandler<LampServiceProducer^, Windows::Devices::AllJoyn::AllJoynProducerStoppedEventArgs^>^ Stopped; // This event will fire whenever the producer loses the session that it created. virtual event Windows::Foundation::TypedEventHandler<LampServiceProducer^, Windows::Devices::AllJoyn::AllJoynSessionLostEventArgs^>^ SessionLost; // This event will fire whenever a member joins the session. virtual event Windows::Foundation::TypedEventHandler<LampServiceProducer^, Windows::Devices::AllJoyn::AllJoynSessionMemberAddedEventArgs^>^ SessionMemberAdded; // This event will fire whenever a member leaves the session. virtual event Windows::Foundation::TypedEventHandler<LampServiceProducer^, Windows::Devices::AllJoyn::AllJoynSessionMemberRemovedEventArgs^>^ SessionMemberRemoved; // Start advertising the service. void Start(); // Stop advertising the service. void Stop(); // Remove a member that has joined this session. int32 RemoveMemberFromSession(_In_ Platform::String^ uniqueName); internal: bool OnAcceptSessionJoiner(_In_ alljoyn_sessionport sessionPort, _In_ PCSTR joiner, _In_ const alljoyn_sessionopts opts); void OnSessionJoined(_In_ alljoyn_sessionport sessionPort, _In_ alljoyn_sessionid id, _In_ PCSTR joiner); QStatus OnPropertyGet(_In_ PCSTR interfaceName, _In_ PCSTR propertyName, _Inout_ alljoyn_msgarg val); QStatus OnPropertySet(_In_ PCSTR interfaceName, _In_ PCSTR propertyName, _In_ alljoyn_msgarg val); void OnSessionLost(_In_ alljoyn_sessionid sessionId, _In_ alljoyn_sessionlostreason reason); void OnSessionMemberAdded(_In_ alljoyn_sessionid sessionId, _In_ PCSTR uniqueName); void OnSessionMemberRemoved(_In_ alljoyn_sessionid sessionId, _In_ PCSTR uniqueName); property Platform::String^ ServiceObjectPath { Platform::String^ get() { return m_ServiceObjectPath; } void set(Platform::String^ value) { m_ServiceObjectPath = value; } } property alljoyn_busobject BusObject { alljoyn_busobject get() { return m_busObject; } void set(alljoyn_busobject value) { m_busObject = value; } } property alljoyn_sessionportlistener SessionPortListener { alljoyn_sessionportlistener get() { return m_sessionPortListener; } void set(alljoyn_sessionportlistener value) { m_sessionPortListener = value; } } property alljoyn_sessionlistener SessionListener { alljoyn_sessionlistener get() { return m_sessionListener; } void set(alljoyn_sessionlistener value) { m_sessionListener = value; } } property alljoyn_sessionport SessionPort { alljoyn_sessionport get() { return m_sessionPort; } internal: void set(alljoyn_sessionport value) { m_sessionPort = value; } } property alljoyn_sessionid SessionId { alljoyn_sessionid get() { return m_sessionId; } } // Stop advertising the service and pass status to anyone listening for the Stopped event. void StopInternal(int32 status); void BusAttachmentStateChanged(_In_ Windows::Devices::AllJoyn::AllJoynBusAttachment^ sender, _In_ Windows::Devices::AllJoyn::AllJoynBusAttachmentStateChangedEventArgs^ args); private: static void CallClearLampFaultHandler(_Inout_ alljoyn_busobject busObject, _In_ alljoyn_message message); // Register a callback function to handle methods. QStatus AddMethodHandler(_In_ alljoyn_interfacedescription interfaceDescription, _In_ PCSTR methodName, _In_ alljoyn_messagereceiver_methodhandler_ptr handler); // Register a callback function to handle incoming signals. QStatus AddSignalHandler(_In_ alljoyn_busattachment busAttachment, _In_ alljoyn_interfacedescription interfaceDescription, _In_ PCSTR methodName, _In_ alljoyn_messagereceiver_signalhandler_ptr handler); void UnregisterFromBus(); Windows::Devices::AllJoyn::AllJoynBusAttachment^ m_busAttachment; Windows::Foundation::EventRegistrationToken m_busAttachmentStateChangedToken; LampServiceSignals^ m_signals; ILampServiceService^ m_serviceInterface; Platform::String^ m_ServiceObjectPath; alljoyn_busobject m_busObject; alljoyn_sessionportlistener m_sessionPortListener; alljoyn_sessionlistener m_sessionListener; alljoyn_sessionport m_sessionPort; alljoyn_sessionid m_sessionId; // Used to pass a pointer to this class to callbacks Platform::WeakReference* m_weak; // These maps are required because we need a way to pass the producer to the method // and signal handlers, but the current AllJoyn C API does not allow passing a context to these // callbacks. static std::map<alljoyn_busobject, Platform::WeakReference*> SourceObjects; static std::map<alljoyn_interfacedescription, Platform::WeakReference*> SourceInterfaces; }; } } }
[ "artemz@microsoft.com" ]
artemz@microsoft.com
bf57b56627c2017670899fbcb38e16d6dc99ce61
928863f83611e4cd3256f58c0c0199b72baefabb
/3rd_party_libs/chai3d_a4/src/graphics/CDisplayList.h
7c77b392263fd705c7eb52c7c675fa660cb8c0d2
[ "BSD-3-Clause" ]
permissive
salisbury-robotics/jks-ros-pkg
b3c2f813885e48b1fcd732d1298027a4ee041a5c
367fc00f2a9699f33d05c7957d319a80337f1ed4
refs/heads/master
2020-03-31T01:20:29.860477
2015-09-03T22:13:17
2015-09-03T22:13:17
41,575,746
3
0
null
null
null
null
UTF-8
C++
false
false
4,459
h
//=========================================================================== /* Software License Agreement (BSD License) Copyright (c) 2003-2012, CHAI3D. (www.chai3d.org) 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 CHAI3D nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. \author <http://www.chai3d.org> \author Francois Conti \version $MAJOR.$MINOR.$RELEASE $Rev: 733 $ */ //=========================================================================== //--------------------------------------------------------------------------- #ifndef CDisplayListH #define CDisplayListH //--------------------------------------------------------------------------- #include "system/CGlobals.h" //--------------------------------------------------------------------------- //=========================================================================== /*! \file CDisplayList.h \brief <b> Graphics </b> \n OpenGL Display Lists. */ //=========================================================================== //=========================================================================== /*! \class cDisplayList \ingroup graphics \brief cDisplayList provides a simple structure to handle the creation of an OpenGL dislay list. */ //=========================================================================== class cDisplayList { //----------------------------------------------------------------------- // CONSTRUCTOR & DESTRUCTOR: //----------------------------------------------------------------------- public: //! Constructor of cDisplayList. cDisplayList(); //! Destructor of cDisplayList. ~cDisplayList(); //----------------------------------------------------------------------- // METHODS: //----------------------------------------------------------------------- public: //! Invalidate current display list. Request for update. void invalidate(); //! Render display list. bool render(const bool a_useDisplayList = true); //! Begin creating display list. bool begin(const bool a_useDisplayList = true); //! Finalize the creatio of display list. void end(const bool a_executeDisplayList = true); //! Get OpenGL display list number. unsigned int getDisplayListGL() { return (m_displayList); } //----------------------------------------------------------------------- // MEMBERS: //----------------------------------------------------------------------- private: //! OpenGL display list. unsigned int m_displayList; //! If \b true, then currently creating new display list. bool m_flagCreatingDisplayList; }; //--------------------------------------------------------------------------- #endif //---------------------------------------------------------------------------
[ "adamleeper@gmail.com" ]
adamleeper@gmail.com
2982e986cffd0a621797e82884d486b079a95917
2d7022c3705637183d67c7a43703360fe701ea37
/source/mileToKilometer.cpp
0318a0b04151f5c318209f21734315a539d10aae
[ "MIT" ]
permissive
guvo6384/programmiersprachen-blatt-1
9fec307c0fef479dd7c4424e4c93839b2e0c7cc2
6e44c524d64d508142f711d447644244fbbb9b8d
refs/heads/master
2016-09-13T19:06:52.978235
2016-04-25T13:58:58
2016-04-25T13:58:58
56,522,182
0
0
null
null
null
null
UTF-8
C++
false
false
413
cpp
#include <iostream> #include <string> double convert_to_kilometers(double miles); int main () { std :: cout << " Bitte geben Sie Meilen ein:" << std :: endl; double miles; std :: cin >> miles ; std :: cout << miles << " entspricht " << convert_to_kilometers(miles)<< std :: endl; } double convert_to_kilometers(double miles) { double kilometers; kilometers = 1.609 * miles; return kilometers; }
[ "jan-niklas.stumpe@uni-weimar.de" ]
jan-niklas.stumpe@uni-weimar.de
f169b5edc8a623decec28bc8277ef5859c8a87f1
57775c8be6575493be4968f939ecdb8a2fc42d85
/src/Texture.cpp
434f53e0bf720a0777968643939af764a6686da6
[]
no_license
nikunjarora12345/Opengl-Demo
f751e9e607fd9b8ac6684a30ad8141741b4bb999
df4ee62aff176781ddf17982f8c05471a6dd2128
refs/heads/master
2023-03-13T12:53:43.974177
2021-03-04T11:06:03
2021-03-04T11:06:03
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,415
cpp
#include "Texture.hpp" #include "stb_image.h" namespace Renderer { Texture::Texture(const std::string& path, bool freeMemory): m_RendererID(0), m_FilePath(path), m_LocalBuffer(nullptr), m_Width(0), m_Height(0), m_BitsPerPixel(0) { stbi_set_flip_vertically_on_load(1); m_LocalBuffer = stbi_load(m_FilePath.c_str(), &m_Width, &m_Height, &m_BitsPerPixel, 4); GLCall(glGenTextures(1, &m_RendererID)); GLCall(glBindTexture(GL_TEXTURE_2D, m_RendererID)); GLCall(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR)); GLCall(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR)); GLCall(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE)); GLCall(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE)); GLCall(glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, m_Width, m_Height, 0, GL_RGBA, GL_UNSIGNED_BYTE, m_LocalBuffer)); Unbind(); if (freeMemory && m_LocalBuffer) { stbi_image_free(m_LocalBuffer); m_LocalBuffer = nullptr; } } Texture::~Texture() { if (m_LocalBuffer) { stbi_image_free(m_LocalBuffer); m_LocalBuffer = nullptr; } GLCall(glDeleteTextures(1, &m_RendererID)); } void Texture::Bind(unsigned slot) const { GLCall(glActiveTexture(GL_TEXTURE0 + slot)); GLCall(glBindTexture(GL_TEXTURE_2D, m_RendererID)); } void Texture::Unbind() const { GLCall(glBindTexture(GL_TEXTURE_2D, 0)); } }
[ "nikunjarora12345@gmail.com" ]
nikunjarora12345@gmail.com
75e8983519352b521f4557a81ac6c89ab459ad31
8b2263d84d6888e62bff1773d7f737943efe78dd
/src/qt/optionsmodel.cpp
cb48a94fbdd31d98752e1ed505fd3630c45fc2e0
[ "MIT" ]
permissive
sigmabitorg/Sigmabitsha
c73d1bcb17bb0fb9aa0db821ef9ce0981b3b162f
7b06e46897ad0469210e01edaad3e5b0d9a533b4
refs/heads/master
2021-01-12T11:38:25.431054
2016-10-28T21:48:30
2016-10-28T21:48:30
72,244,305
0
0
null
null
null
null
UTF-8
C++
false
false
9,071
cpp
#include "optionsmodel.h" #include "bitcoinunits.h" #include "init.h" #include "walletdb.h" #include "guiutil.h" #include <QSettings> OptionsModel::OptionsModel(QObject *parent) : QAbstractListModel(parent) { Init(); } bool static ApplyProxySettings() { QSettings settings; CService addrProxy(settings.value("addrProxy", "127.0.0.1:9050").toString().toStdString()); int nSocksVersion(settings.value("nSocksVersion", 5).toInt()); if (!settings.value("fUseProxy", false).toBool()) { addrProxy = CService(); nSocksVersion = 0; return false; } if (nSocksVersion && !addrProxy.IsValid()) return false; if (!IsLimited(NET_IPV4)) SetProxy(NET_IPV4, addrProxy, nSocksVersion); if (nSocksVersion > 4) { #ifdef USE_IPV6 if (!IsLimited(NET_IPV6)) SetProxy(NET_IPV6, addrProxy, nSocksVersion); #endif SetNameProxy(addrProxy, nSocksVersion); } return true; } void OptionsModel::Init() { QSettings settings; // These are Qt-only settings: nDisplayUnit = settings.value("nDisplayUnit", BitcoinUnits::BTC).toInt(); bDisplayAddresses = settings.value("bDisplayAddresses", false).toBool(); fMinimizeToTray = settings.value("fMinimizeToTray", false).toBool(); fMinimizeOnClose = settings.value("fMinimizeOnClose", false).toBool(); nTransactionFee = settings.value("nTransactionFee").toLongLong(); language = settings.value("language", "").toString(); // These are shared with core Sigmabit; we want // command-line options to override the GUI settings: if (settings.contains("fUseUPnP")) SoftSetBoolArg("-upnp", settings.value("fUseUPnP").toBool()); if (settings.contains("addrProxy") && settings.value("fUseProxy").toBool()) SoftSetArg("-proxy", settings.value("addrProxy").toString().toStdString()); if (settings.contains("nSocksVersion") && settings.value("fUseProxy").toBool()) SoftSetArg("-socks", settings.value("nSocksVersion").toString().toStdString()); if (!language.isEmpty()) SoftSetArg("-lang", language.toStdString()); } void OptionsModel::Reset() { QSettings settings; // Remove all entries in this QSettings object settings.clear(); // default setting for OptionsModel::StartAtStartup - disabled if (GUIUtil::GetStartOnSystemStartup()) GUIUtil::SetStartOnSystemStartup(false); // Re-Init to get default values Init(); // Ensure Upgrade() is not running again by setting the bImportFinished flag settings.setValue("bImportFinished", true); } bool OptionsModel::Upgrade() { QSettings settings; if (settings.contains("bImportFinished")) return false; // Already upgraded settings.setValue("bImportFinished", true); // Move settings from old wallet.dat (if any): CWalletDB walletdb(strWalletFile); QList<QString> intOptions; intOptions << "nDisplayUnit" << "nTransactionFee"; foreach(QString key, intOptions) { int value = 0; if (walletdb.ReadSetting(key.toStdString(), value)) { settings.setValue(key, value); walletdb.EraseSetting(key.toStdString()); } } QList<QString> boolOptions; boolOptions << "bDisplayAddresses" << "fMinimizeToTray" << "fMinimizeOnClose" << "fUseProxy" << "fUseUPnP"; foreach(QString key, boolOptions) { bool value = false; if (walletdb.ReadSetting(key.toStdString(), value)) { settings.setValue(key, value); walletdb.EraseSetting(key.toStdString()); } } try { CAddress addrProxyAddress; if (walletdb.ReadSetting("addrProxy", addrProxyAddress)) { settings.setValue("addrProxy", addrProxyAddress.ToStringIPPort().c_str()); walletdb.EraseSetting("addrProxy"); } } catch (std::ios_base::failure &e) { // 0.6.0rc1 saved this as a CService, which causes failure when parsing as a CAddress CService addrProxy; if (walletdb.ReadSetting("addrProxy", addrProxy)) { settings.setValue("addrProxy", addrProxy.ToStringIPPort().c_str()); walletdb.EraseSetting("addrProxy"); } } ApplyProxySettings(); Init(); return true; } int OptionsModel::rowCount(const QModelIndex & parent) const { return OptionIDRowCount; } QVariant OptionsModel::data(const QModelIndex & index, int role) const { if(role == Qt::EditRole) { QSettings settings; switch(index.row()) { case StartAtStartup: return QVariant(GUIUtil::GetStartOnSystemStartup()); case MinimizeToTray: return QVariant(fMinimizeToTray); case MapPortUPnP: #ifdef USE_UPNP return settings.value("fUseUPnP", GetBoolArg("-upnp", true)); #else return QVariant(false); #endif case MinimizeOnClose: return QVariant(fMinimizeOnClose); case ProxyUse: { proxyType proxy; return QVariant(GetProxy(NET_IPV4, proxy)); } case ProxyIP: { proxyType proxy; if (GetProxy(NET_IPV4, proxy)) return QVariant(QString::fromStdString(proxy.first.ToStringIP())); else return QVariant(QString::fromStdString("127.0.0.1")); } case ProxyPort: { proxyType proxy; if (GetProxy(NET_IPV4, proxy)) return QVariant(proxy.first.GetPort()); else return QVariant(9050); } case ProxySocksVersion: { proxyType proxy; if (GetProxy(NET_IPV4, proxy)) return QVariant(proxy.second); else return QVariant(5); } case Fee: return QVariant(nTransactionFee); case DisplayUnit: return QVariant(nDisplayUnit); case DisplayAddresses: return QVariant(bDisplayAddresses); case Language: return settings.value("language", ""); default: return QVariant(); } } return QVariant(); } bool OptionsModel::setData(const QModelIndex & index, const QVariant & value, int role) { bool successful = true; /* set to false on parse error */ if(role == Qt::EditRole) { QSettings settings; switch(index.row()) { case StartAtStartup: successful = GUIUtil::SetStartOnSystemStartup(value.toBool()); break; case MinimizeToTray: fMinimizeToTray = value.toBool(); settings.setValue("fMinimizeToTray", fMinimizeToTray); break; case MapPortUPnP: settings.setValue("fUseUPnP", value.toBool()); MapPort(value.toBool()); break; case MinimizeOnClose: fMinimizeOnClose = value.toBool(); settings.setValue("fMinimizeOnClose", fMinimizeOnClose); break; case ProxyUse: settings.setValue("fUseProxy", value.toBool()); successful = ApplyProxySettings(); break; case ProxyIP: { proxyType proxy; proxy.first = CService("127.0.0.1", 9050); GetProxy(NET_IPV4, proxy); CNetAddr addr(value.toString().toStdString()); proxy.first.SetIP(addr); settings.setValue("addrProxy", proxy.first.ToStringIPPort().c_str()); successful = ApplyProxySettings(); } break; case ProxyPort: { proxyType proxy; proxy.first = CService("127.0.0.1", 9050); GetProxy(NET_IPV4, proxy); proxy.first.SetPort(value.toInt()); settings.setValue("addrProxy", proxy.first.ToStringIPPort().c_str()); successful = ApplyProxySettings(); } break; case ProxySocksVersion: { proxyType proxy; proxy.second = 5; GetProxy(NET_IPV4, proxy); proxy.second = value.toInt(); settings.setValue("nSocksVersion", proxy.second); successful = ApplyProxySettings(); } break; case Fee: nTransactionFee = value.toLongLong(); settings.setValue("nTransactionFee", nTransactionFee); break; case DisplayUnit: nDisplayUnit = value.toInt(); settings.setValue("nDisplayUnit", nDisplayUnit); emit displayUnitChanged(nDisplayUnit); break; case DisplayAddresses: bDisplayAddresses = value.toBool(); settings.setValue("bDisplayAddresses", bDisplayAddresses); break; case Language: settings.setValue("language", value); break; default: break; } } emit dataChanged(index, index); return successful; } qint64 OptionsModel::getTransactionFee() { return nTransactionFee; }
[ "admin@sigmabit.org" ]
admin@sigmabit.org
730e1b83c9ff942a1d219643a8d7139f8512147b
24b7fd2c31eae72646204ff94dfe13c1c05d1e00
/TDgame/CritterFactory.h
39c5763a9b9f676c314dad750b765eba5ba692e8
[]
no_license
patch100/comp345
e745019225c53ad7d4113ba66c08231b6d7dc9ba
e31bfe7b411ebc3096a2f534f5bd83cf13535c76
refs/heads/master
2021-01-17T12:19:11.646567
2014-10-04T15:39:45
2014-10-04T15:39:45
null
0
0
null
null
null
null
UTF-8
C++
false
false
248
h
#ifndef CRITTERFACTORY_H #define CRITTERFACTORY_H #include"Critter.h" class CritterFactory { public: int level; int critterNumber; CritterFactory(); ~CritterFactory(); void nextLevel(); bool canCreate(); Critter createCritter(); }; #endif
[ "haoran.sun.1993@gmail.com" ]
haoran.sun.1993@gmail.com
0a2d1e2f4fe9953a24dc451ecdd32afae65dbea6
e091e411012a603f14b58c3d05117b50312986c4
/GamePingPong_SweptAABB/Game/Game.cpp
1710c8f7a612de19b6295b9510b2421ec5adb607
[]
no_license
phamphuckhai/GameDirectX
071e477d4cae8ab60303ec989f7bfa1f20ad6a4b
f34a72b0bee71112f52a1b0aa22a3e8a025a3a9b
refs/heads/master
2020-06-24T03:56:28.697876
2019-07-25T14:01:36
2019-07-25T14:01:36
198,841,279
0
0
null
null
null
null
UTF-8
C++
false
false
10,632
cpp
#include<d3d9.h> #include<d3dx9.h> #include<time.h> #include<dinput.h> #include"game.h" #include"dxgraphics.h" #include"dxinput.h" #include<tchar.h> #include<sstream> #include<string> LPD3DXSPRITE sprite_handler; LPDIRECT3DSURFACE9 surface; SPRITE ball, paddle1, paddle2; LPDIRECT3DTEXTURE9 ball_image; LPDIRECT3DTEXTURE9 paddle1_image; LPDIRECT3DTEXTURE9 paddle2_image; LPDIRECT3DSURFACE9 back; ID3DXFont *font = NULL; ID3DXFont *fontS = NULL; RECT FRect, FRect2, SRect, SRect2; const char *text, *text2; int ballspeed = 20, paddlespeed = 20; int score1 = 0, score2 = 0; //Player Pl1(250, 350, 50, 70); //Player Pl2(250, 350, 730, 750); //Ball ball(290, 310, 390, 410); long start = GetTickCount(); int tmp; HRESULT result; int Game_Init(HWND hwnd) { srand((unsigned)time(NULL)); if (!Init_Mouse(hwnd)) { MessageBox(hwnd, L"Error initializing the mouse", L"Error", MB_OK); return 0; } if (!Init_Keyboard(hwnd)) { MessageBox(hwnd, L"Error initializing the keyboard", L"Error", MB_OK); return 0; } result = D3DXCreateSprite(d3ddev, &sprite_handler); if (result != D3D_OK) return 0; back = LoadSurface(L"background.jpg", NULL); if (back == NULL) return 0; paddle1_image = LoadTexture(L"paddle_1.png", D3DCOLOR_XRGB(255, 0, 255)); if (paddle1_image == NULL) return 0; paddle2_image = LoadTexture(L"paddle_2.png", D3DCOLOR_XRGB(255, 0, 255)); if (paddle2_image == NULL) return 0; ball_image = LoadTexture(L"ball.png", D3DCOLOR_XRGB(0, 0, 0)); if (ball_image == NULL) return 0; //ball ball.x = 400; ball.y = 200; ball.width = 32; ball.height = 32; /*ball.movex = ballspeed; ball.movey = -ballspeed;*/ ball.curframe = 1; ball.lastframe = 7; ball.animdelay = 3; ball.animcount = 0; ball.vx = ballspeed; ball.vy = -ballspeed; //paddle1 paddle1.x = 50; paddle1.y = 250; paddle1.width = 20; paddle1.height = 100; //paddle2 paddle2.x = 730; paddle2.y = 250; paddle2.width = 20; paddle2.height = 100; result = d3ddev->CreateOffscreenPlainSurface( 800, 600, D3DFMT_X8R8G8B8, D3DPOOL_DEFAULT, &surface, NULL); if (result != D3D_OK) return 1; result = D3DXCreateFontW(d3ddev, 40, 0, FW_NORMAL, 1, false, DEFAULT_CHARSET, OUT_DEFAULT_PRECIS, ANTIALIASED_QUALITY, DEFAULT_PITCH | FF_DONTCARE, L"Ariel", &font); if (result != D3D_OK) return 1; result = D3DXCreateFontW(d3ddev, 72, 0, FW_NORMAL, 1, false, DEFAULT_CHARSET, OUT_DEFAULT_PRECIS, ANTIALIASED_QUALITY, DEFAULT_PITCH | FF_DONTCARE, L"Ariel", &fontS); if (result != D3D_OK) return 1; SetRect(&FRect, 0, 0, 200, 200); SetRect(&FRect2, SCREEN_WIDTH - 155, 0, SCREEN_WIDTH, 200); SetRect(&SRect, 150, 100, 350, 300); SetRect(&SRect2, SCREEN_WIDTH - 200, 100, SCREEN_WIDTH - 50, 300); text = "PLAYER1"; text2 = "PLAYER2"; return 1; } int Collision(SPRITE sprite1, SPRITE sprite2) { RECT rect1; rect1.left = sprite1.x + 1; rect1.top = sprite1.y + 1; rect1.right = sprite1.x + sprite1.width - 1; rect1.bottom = sprite1.y + sprite1.height - 1; RECT rect2; rect2.left = sprite2.x + 1; rect2.top = sprite2.y + 1; rect2.right = sprite2.x + sprite2.width - 1; rect2.bottom = sprite2.y + sprite2.height - 1; RECT dest; return IntersectRect(&dest, &rect1, &rect2); } float SweptAABB(SPRITE b1, SPRITE b2, float& normalx, float &normaly) { float dxEntry, dyEntry; float dxExit, dyExit; float txEntry, tyEntry; float txExit, tyExit; if (b1.vx > 0.0f) { dxEntry = b2.x - (b1.x + b1.width); dxExit = (b2.x + b2.width) - b1.x; } else { dxEntry = (b2.x + b2.width) - b1.x; dxExit = b2.x - (b1.x + b1.width); } if (b1.vy > 0.0f) { dyEntry = b2.y - (b1.y + b1.height); dyExit = (b2.y + b2.height) - b1.y; } else { dyEntry = (b2.y + b2.height) - b1.y; dyExit = b2.y - (b1.y + b1.height); } if (b1.vx == 0.0f) { txEntry = -std::numeric_limits<float>::infinity(); txExit = std::numeric_limits<float>::infinity(); } else { txEntry = dxEntry / b1.vx; txExit = dxExit / b1.vx; } if (b1.vy == 0.0f) { tyEntry = -std::numeric_limits<float>::infinity(); tyExit = std::numeric_limits<float>::infinity(); } else { tyEntry = dyEntry / b1.vy; tyExit = dyExit / b1.vy; } float entryTime = max(txEntry, tyEntry); float exitTime = min(txExit, tyExit); if (entryTime > exitTime || (txEntry < 0.0f && tyEntry < 0.0f) || txEntry > 1.0f || tyEntry > 1.0f) { normalx = 0.0f; normaly = 0.0f; return 1.0f; } else { if (txEntry > tyEntry) { if (dxEntry < 0.0f) { normalx = 1.0f; normaly = 0.0f; } else { normalx = -1.0f; normaly = 0.0f; } } else { if (dyEntry < 0.0f) { normalx = 0.0f; normaly = 1.0f; } else { normalx = 0.0f; normaly = -1.0f; } } } return entryTime; } //Broad-Phasing SPRITE getSweptBroadphaseRect(const SPRITE& b) { SPRITE broadphasingbox; broadphasingbox.x = b.vx > 0 ? b.x : b.x + b.vx; broadphasingbox.y = b.vy > 0 ? b.y : b.y + b.vy; broadphasingbox.width = b.width + abs(b.vx); broadphasingbox.height = b.height + abs(b.vy); return broadphasingbox; } //Kiem tra va cham bool AABBCheck(SPRITE b1, SPRITE b2) { return !(b1.x + b1.width<b2.x || b1.x>b2.x + b2.width || b1.y + b1.height<b2.y || b1.y>b2.y + b2.height); } void Game_Run(HWND hwnd) { if (d3ddev == NULL) return; Poll_Mouse(); Poll_Keyboard(); SPRITE broadphasebox = getSweptBroadphaseRect(ball); //Va cham paddle 1 if (AABBCheck(broadphasebox, paddle1)) { float normalx, normaly; float collisiontime = SweptAABB(ball, paddle1, normalx, normaly); ball.x += ball.vx * collisiontime; ball.y += ball.vy * collisiontime; if (collisiontime < 1.0f) { if (abs(normalx) > 0.0001f) ball.vx = -ball.vx; if (abs(normaly) > 0.0001f) ball.vy = -ball.vy; } } //Va cham paddle 2 if (AABBCheck(broadphasebox, paddle2)) { float normalx, normaly; float collisiontime = SweptAABB(ball, paddle2, normalx, normaly); ball.x += ball.vx * collisiontime; ball.y += ball.vy * collisiontime; if (collisiontime < 1.0f) { if (abs(normalx) > 0.0001f) ball.vx = -ball.vx; if (abs(normaly) > 0.0001f) ball.vy = -ball.vy; } } if (GetTickCount() - start >= 30) { start = GetTickCount(); ball.x += ball.vx; ball.y += ball.vy; if (ball.x > SCREEN_WIDTH - ball.width) { /*ball.x -= ball.width; ball.movex *= -1;*/ score1++; ball.x = 400; ball.y = 200; ball.vx = ballspeed; ball.vy = -ballspeed; } else if (ball.x < 0) { /*ball.x += ball.width; ball.movex *= -1;*/ score2++; ball.x = 400; ball.y = 200; ball.vx = ballspeed; ball.vy = -ballspeed; } if (ball.y > SCREEN_HEIGHT - ball.height) { ball.y -= ball.height; ball.vy *= -1; } else if (ball.y < 0) { ball.y += ball.height; ball.vy *= -1; } paddle2.y += Mouse_Y(); /*if (Key_Down(DIK_W)) paddle2.y -= paddlespeed; if (Key_Down(DIK_S)) paddle2.y += paddlespeed;*/ if (Key_Down(DIK_UP)) paddle1.y -= paddlespeed; if (Key_Down(DIK_DOWN)) paddle1.y += paddlespeed; if (paddle1.y > SCREEN_HEIGHT - paddle1.height) paddle1.y = SCREEN_HEIGHT - paddle1.height; else if (paddle1.y < 0) paddle1.y = 0; if (paddle2.y > SCREEN_HEIGHT - paddle2.height) paddle2.y = SCREEN_HEIGHT - paddle2.height; else if (paddle2.y < 0) paddle2.y = 0; } /*a.left = ball.x; a.top = ball.y; a.right = ball.x + ball.width; a.bottom = ball.y + ball.height; b.left = paddle1.x; b.top = paddle1.y; b.right = paddle1.x + paddle1.width; b.bottom = paddle1.y + paddle1.height; c.left = paddle2.x; c.top = paddle2.y; c.right = paddle2.x + paddle2.width; c.bottom = paddle2.y + paddle2.height; rect.top = 0; rect.left = 0; rect.right = 100; rect.bottom = 100;*/ if (++ball.animcount > ball.animdelay) { ball.animcount = 0; if (++ball.curframe > ball.lastframe) ball.curframe = 0; } //Covert int to char* std::string s1 = std::to_string(score1); char const *pchar = s1.c_str(); std::string s2 = std::to_string(score2); char const *pchar2 = s2.c_str(); //Begin screen if (d3ddev->BeginScene()) { d3ddev->StretchRect(back, NULL, backbuffer, NULL, D3DTEXF_NONE); //Draw text font->DrawTextA(NULL, text, -1, &FRect, DT_LEFT, D3DCOLOR_XRGB(255, 0, 255)); font->DrawTextA(NULL, text2, -1, &FRect2, DT_LEFT, D3DCOLOR_XRGB(255, 0, 255)); fontS->DrawTextA(NULL, pchar, -1, &SRect, DT_LEFT, D3DCOLOR_XRGB(255, 255, 255)); fontS->DrawTextA(NULL, pchar2, -1, &SRect2, DT_LEFT, D3DCOLOR_XRGB(255, 255, 255)); sprite_handler->Begin(D3DXSPRITE_ALPHABLEND); //Ball D3DXVECTOR3 positionball((float)ball.x, (float)ball.y, 0); RECT bll; int columns = 2; bll.left = (ball.curframe % columns) * ball.width; bll.top = (ball.curframe / columns) * ball.height; bll.right = bll.left + ball.width; bll.bottom = bll.top + ball.height; // vẽ sprite sprite_handler->Draw( ball_image, &bll, NULL, &positionball, D3DCOLOR_XRGB(255, 255, 255)); //Vi tri paddle1 D3DXVECTOR3 positionPaddle1((float)paddle1.x, (float)paddle1.y, 0); //Ve paddle1 RECT player1; player1.left = paddle1.x; player1.top = paddle1.y; player1.right = paddle1.x + paddle1.width; player1.bottom = paddle1.y + paddle1.height; sprite_handler->Draw( paddle1_image, &player1, NULL, &positionPaddle1, D3DCOLOR_XRGB(255, 255, 255)); //Vi tri paddle2 D3DXVECTOR3 positionPaddle2((float)paddle2.x, (float)paddle2.y, 0); //Ve paddle2 RECT player2; player2.left = paddle2.x; player2.top = paddle2.y; player2.right = paddle2.x + paddle2.width; player2.bottom = paddle2.y + paddle2.height; sprite_handler->Draw( paddle2_image, &player2, NULL, &positionPaddle2, D3DCOLOR_XRGB(255, 255, 255)); sprite_handler->End(); /*d3ddev->StretchRect(surface, NULL, backbuffer, &a, D3DTEXF_NONE); d3ddev->StretchRect(surface, NULL, backbuffer, &b, D3DTEXF_NONE); d3ddev->StretchRect(surface, NULL, backbuffer, &c, D3DTEXF_NONE);*/ d3ddev->EndScene(); } //game Over //if (score1 == 10) { // MessageBox(hwnd, L"PLAYER1 WIN", L"CONGRATULATION", MB_OK); // PostMessage(hwnd, WM_DESTROY, 0, 0); //} //if (score2 == 10) { // MessageBox(hwnd, L"PLAYER2 WIN", L"CONGRATULATION", MB_OK); // PostMessage(hwnd, WM_DESTROY, 0, 0); //} d3ddev->Present(NULL, NULL, NULL, NULL); if (Mouse_Button(0)) PostMessage(hwnd, WM_DESTROY, 0, 0); if (Key_Down(DIK_ESCAPE)) PostMessage(hwnd, WM_DESTROY, 0, 0); } void Game_End(HWND hwnd) { if (surface != NULL) surface->Release(); if (d3ddev != NULL) d3ddev->Release(); if (d3d != NULL) d3d->Release(); if (back != NULL) back->Release(); if (font != NULL) font->Release(); }
[ "phamphuckhai@gmail.com" ]
phamphuckhai@gmail.com
d204f7c8a1eb9f9f48a621d11872701494669c61
dda6338397aa5d386ea1f49b6efcd1876a1d8aba
/src/draw/fonts.cpp
359f40e0fee28b4242f0a8dd46adf59aacbd63f6
[]
no_license
esimionato/lanarts
964fa3f3632ff7ac5e4c480078dc2289fb887153
a1301cd63f7d7b39963a1d661ddefeb34f071913
refs/heads/master
2020-03-16T17:49:29.940200
2018-03-30T22:30:19
2018-03-30T22:30:19
null
0
0
null
null
null
null
UTF-8
C++
false
false
306
cpp
/* * fonts.cpp: * Accessors for the fonts used by the game. */ #include "fonts.h" using namespace ldraw; static Font __primary, __menu; namespace res { Font& font_primary() { return __primary; } Font& font_menu() { return __menu; } void font_free() { __primary.clear(); __menu.clear(); } }
[ "domuradical@gmail.com" ]
domuradical@gmail.com
3d3b34be8c7f4eef2bddcb39e36ad1c7555a6fbc
6296408663242e9504c2305b521d9bfcf3630e52
/Week_06/1143-longest-common-subsequence.cpp
0c2655e2bce60af0121bb2d5f3eded5947fde5c3
[]
no_license
chenzj-czj/algorithm012
b0870cdf97ceaf02a6a8155cccc7f5da741b0747
763ca6f8a0777a41c699ef9f4163442b0e4872cc
refs/heads/master
2022-12-18T17:55:57.634808
2020-09-20T09:46:53
2020-09-20T09:46:53
277,009,126
0
0
null
2020-09-20T08:54:28
2020-07-04T00:17:11
C++
UTF-8
C++
false
false
710
cpp
class Solution { public: int longestCommonSubsequence(string text1, string text2) { int row = text1.length(); int col = text2.length(); int dp[row+1][col+1]; for (int i = 0; i <= row; i++) { dp[i][0] = 0; } for (int j = 0; j <= col; j++) { dp[0][j] = 0; } for (int i = 1; i <= row; i++) { for (int j = 1; j <= col; j++) { if (text1[i-1] == text2[j-1]) { dp[i][j] = dp[i - 1][j - 1] + 1; } else { dp[i][j] = max(dp[i-1][j], dp[i][j-1]); } } } return dp[row][col]; } };
[ "chenzhijie_dream@163.com" ]
chenzhijie_dream@163.com
8af7434967da2183ab93f518be8e118b15241cda
8465159705a71cede7f2e9970904aeba83e4fc6c
/src_change_the_layout/modules/IEC61131-3/Conversion/DINT/F_DINT_TO_STRING.h
01155adb36546aa57b6de097c0884ddb6216e14f
[]
no_license
TuojianLYU/forte_IO_OPCUA_Integration
051591b61f902258e3d0d6608bf68e2302f67ac1
4a3aed7b89f8a7d5f9554ac5937cf0a93607a4c6
refs/heads/main
2023-08-20T16:17:58.147635
2021-10-27T05:34:43
2021-10-27T05:34:43
419,704,624
1
0
null
null
null
null
UTF-8
C++
false
false
1,857
h
/******************************************************************************* * Copyright (c) 2012 ACIN * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0. * * SPDX-License-Identifier: EPL-2.0 * * Contributors: * Monika Wenger * - initial API and implementation and/or initial documentation *******************************************************************************/ #ifndef _F_DINT_TO_STRING_H_ #define _F_DINT_TO_STRING_H_ #include <funcbloc.h> class FORTE_F_DINT_TO_STRING: public CFunctionBlock{ DECLARE_FIRMWARE_FB(FORTE_F_DINT_TO_STRING) private: static const CStringDictionary::TStringId scm_anDataInputNames[]; static const CStringDictionary::TStringId scm_anDataInputTypeIds[]; CIEC_DINT &st_IN() { return *static_cast<CIEC_DINT*>(getDI(0)); }; static const CStringDictionary::TStringId scm_anDataOutputNames[]; static const CStringDictionary::TStringId scm_anDataOutputTypeIds[]; CIEC_STRING &st_OUT() { return *static_cast<CIEC_STRING*>(getDO(0)); }; static const TEventID scm_nEventREQID = 0; static const TForteInt16 scm_anEIWithIndexes[]; static const TDataIOID scm_anEIWith[]; static const CStringDictionary::TStringId scm_anEventInputNames[]; static const TEventID scm_nEventCNFID = 0; static const TForteInt16 scm_anEOWithIndexes[]; static const TDataIOID scm_anEOWith[]; static const CStringDictionary::TStringId scm_anEventOutputNames[]; static const SFBInterfaceSpec scm_stFBInterfaceSpec; FORTE_FB_DATA_ARRAY(1, 1, 1, 0); void executeEvent(int pa_nEIID); public: FUNCTION_BLOCK_CTOR(FORTE_F_DINT_TO_STRING){ }; virtual ~FORTE_F_DINT_TO_STRING(){}; }; #endif //close the ifdef sequence from the beginning of the file
[ "tuojianlyu@gmail.com" ]
tuojianlyu@gmail.com
078a63aaca6e145f2fddfa6cc4482deafbe9a83c
3bbad6f1f610ad8cc4edec00aae854f27e9abf73
/cpp/BFS/走迷宫/main.cpp
e0cfe59e10888acda15c910df773102d30a779e2
[]
no_license
torresng/Algorithms_practice
c765e6e60c4e2a84486a1a88fb6d42503629876a
dae0eaa1dd0663fb428a0002dc5fa8528ff4204f
refs/heads/master
2021-08-07T08:57:16.690536
2020-04-15T06:24:12
2020-04-15T06:24:12
152,349,445
0
0
null
null
null
null
UTF-8
C++
false
false
932
cpp
#include <cstring> #include <algorithm> #include <iostream> using namespace std; typedef pair<int, int> PII; int n, m; const int N = 110; int g[N][N]; int d[N][N]; PII q[N * N]; int bfs() { int hh = 0, tt = 0; q[0] = {0, 0}; memset(d, -1, sizeof d); d[0][0] = 0; int dx[4] = {-1, 0, 1, 0}, dy[4] = {0, 1, 0, -1}; while (hh <= tt) { auto t = q[hh++]; for (int i = 0; i < 4; i++) { int x = t.first + dx[i], y = t.second + dy[i]; if (x >= 0 && x < n && y >= 0 && y < m && g[x][y] == 0 && d[x][y] == -1) { d[x][y] = d[t.first][t.second] + 1; q[++tt] = {x, y}; } } } return d[n - 1][m - 1]; } int main() { cin >> n >> m; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { cin >> g[i][j]; } } cout << bfs() << endl; return 0; }
[ "torresng2684cte@gmail.com" ]
torresng2684cte@gmail.com
24a3f98c08a1a25e33bdee5538e64f7f3f851689
fe87d809058b57da26ffde0b494cc4e5aef85102
/qt5_study/hellostackview/currentform.cpp
7e71bc61bfe59174013e1134114c58b17460cc72
[ "MIT" ]
permissive
happyrabbit456/Qt5_dev
4f2c354d1cead315dc1b2c43fa6a4fceb1a09131
1812df2f04d4b6d24eaf0195ae25d4c67d4f3da2
refs/heads/master
2020-07-08T05:39:16.436243
2020-01-02T07:53:04
2020-01-02T07:53:04
203,581,423
0
0
null
null
null
null
UTF-8
C++
false
false
222
cpp
#include "currentform.h" #include "ui_currentform.h" CurrentForm::CurrentForm(QWidget *parent) : QWidget(parent), ui(new Ui::CurrentForm) { ui->setupUi(this); } CurrentForm::~CurrentForm() { delete ui; }
[ "530633668@qq.com" ]
530633668@qq.com
71a0e88b2ff4ebac8e9b640c4898db3d95b821c2
99f164e96e13db29deef720de9fa4ce0bd114c62
/mediatek/frameworks-ext/av/media/libstagefright/wifi-display-mediatek/uibc/UibcHandler.cpp
56b6b141224e559b4417b8fec2966e91d44756be
[]
no_license
GrapheneCt/android_kernel_zte_run4g_mod
75bb5092273ba4cd75d10f3fa09968853a822300
fbba1d6727878b70954cc4186a7b30504527cd20
refs/heads/master
2020-09-07T14:50:54.230550
2019-11-10T16:37:19
2019-11-10T16:37:19
220,814,914
0
0
null
2019-11-10T16:11:22
2019-11-10T16:11:22
null
UTF-8
C++
false
false
3,328
cpp
#define LOG_TAG "UibcHandler" #include "UibcHandler.h" #include <utils/Log.h> #include "UibcMessage.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #include <stdint.h> #include <fcntl.h> #include <sys/ioctl.h> #include <errno.h> #include <netinet/in.h> #include <unistd.h> #include <linux/fb.h> #include <sys/mman.h> namespace android { UibcHandler::UibcHandler() : m_wfdWidth(0), m_wfdHeight(0), m_localWidth(0), m_localHeight(0), m_wfdWidthScale(0.0), m_wfdHeightScale(0.0) { m_Capability = new UibcCapability(); } UibcHandler::~UibcHandler() { } status_t UibcHandler::init() { int version; UibcMessage::getScreenResolution(&m_localWidth, &m_localHeight); return OK; } status_t UibcHandler::destroy() { return OK; } void UibcHandler::setWFDResolution(int width, int heigh, int screenMode) { int temp; m_wfdWidth = width; m_wfdHeight = heigh; if ((screenMode == 1) && (m_localHeight > m_localWidth)) { // Landscape temp = m_localWidth; m_localWidth = m_localHeight; m_localHeight = temp; } else if ((screenMode == 0) && (m_wfdHeight < m_wfdWidth)) { // Protrait temp = m_wfdWidth; m_wfdWidth = m_wfdHeight; m_wfdHeight = temp; } m_wfdWidthScale = (double)m_localWidth / (double)m_wfdWidth; m_wfdHeightScale = (double)m_localHeight / (double)m_wfdHeight; ALOGD("setWFDResolution screenMode=%d", screenMode); ALOGD("setWFDResolution width=%d, heigh=%d", width, heigh); ALOGD("setWFDResolution m_wfdWidth=%d, m_wfdHeight=%d", m_wfdWidth, m_wfdHeight); ALOGD("setWFDResolution m_localWidth=%d, m_localHeight=%d", m_localWidth, m_localHeight); ALOGD("setWFDResolution m_wfdWidthScale=%f, m_wfdHeightScale=%f", m_wfdWidthScale, m_wfdHeightScale); } void UibcHandler::run_consol_cmd(char *command) { ALOGD("run_consol_cmd:\"%s\"", command); FILE *fpipe; char line[256]; if ( !(fpipe = (FILE*)popen(command, "r")) ) return; while ( fgets( line, sizeof line, fpipe)) { puts(line); } pclose(fpipe); } void UibcHandler::setUibcEnabled(bool enabled) { ALOGD("setUibcEnabled enabled=%d", enabled); mUibcEnabled = enabled; } bool UibcHandler::getUibcEnabled() { ALOGD("getUibcEnabled mUibcEnabled=%d", mUibcEnabled); return mUibcEnabled; } void UibcHandler::parseRemoteCapabilities(AString capStr) { ALOGD("parseRemoteCapabilities"); m_Capability->parseRemoteCapabilities(capStr); } const char* UibcHandler::getLocalCapabilities() { ALOGD("getLocalCapabilities"); return m_Capability->getLocalCapabilities(); } const char* UibcHandler::getSupportedCapabilities() { ALOGD("getSupportedCapabilities"); return m_Capability->getSupportedCapabilities(); } int UibcHandler::getPort() { ALOGD("getPort"); return m_Capability->getPort(); } bool UibcHandler::isUibcSupported() { ALOGD("isUibcSupported"); return m_Capability->isUibcSupported(); } bool UibcHandler::isGenericSupported(int devType) { ALOGD("isGenericSupported"); return m_Capability->isGenericSupported(devType); } bool UibcHandler::isHidcSupported(int devType, int path) { ALOGD("isHidcSupported"); return m_Capability->isHidcSupported(devType, path); } }
[ "danile71@gmail.com" ]
danile71@gmail.com
fa784f7557c8dfefdd7c0b0f969cc590c0f0dc06
4a233bdaf1ff70c579063cbf240928afa45a228c
/code/include/Ip_stream.h
f2b8b6fd0aac16a0596eb163fdfb579aeaac35ea
[]
no_license
ShasankaBorah/Ip.Analyzer
063ebaab0fbd667cfe85f2360d1c92114c35d010
fb1475bf9677265f5e8610994252d76eaddd7356
refs/heads/master
2021-04-27T17:19:02.675059
2018-08-08T20:16:52
2018-08-08T20:16:52
122,319,988
3
3
null
null
null
null
UTF-8
C++
false
false
1,533
h
#pragma once #include "Tcp_stream.h" #include <string> #include <iostream> #include <map> #include <vector> #include <algorithm> #include <fstream> #include <set> #include <boost/filesystem.hpp> #include <boost/property_tree/ptree.hpp> #include <boost/property_tree/json_parser.hpp> #include "boost/date_time/posix_time/posix_time.hpp" #include "json.hpp" using jsonnlohmann = nlohmann::json; class Ip_stream { private: std::string srcIP; std::string dstIP; boost::filesystem::path fl_fileName; boost::filesystem::path rl_fileName; std::vector<std::string> fl_files; std::vector<std::string> rl_files; std::map<std::string, Tcp_stream*> tcp_streams_map; uint64_t src_dst, dst_src; std::set<std::string> folders_FL; std::set<std::string> folders_RL; public: Ip_stream(); ~Ip_stream(); Ip_stream(std::string, std::string , std::string filename, bool is_fl); //overloaded contructor int ip_equals(const Ip_stream &that) const; std::string get_ip_srcIP(); std::string get_ip_dstIP(); std::string Ip_stream::get_fl_file(); std::string Ip_stream::get_rl_file(); boost::filesystem::path fl_files_return(); boost::filesystem::path rl_files_return(); std::pair<std::string , std::string> split_string(std::string str); // splits string and returns two values void is_fl_rl(std::string ip_src_dst, bool if_fl_rl, std::string file_name); // function to check if the file is fl or jsonnlohmann get_statistics(); void update(std::string port, uint64_t sequence, uint64_t acknowlegement); //void store_data(); };
[ "31131175+ShasankaBorah@users.noreply.github.com" ]
31131175+ShasankaBorah@users.noreply.github.com
8e10ce4a663bda0f0f34e37e89678e51da044a1e
4063bee0b810f5d308eab6b427108441c5033704
/Programming Languae/Syracuse C++/554Lec/2019_02_26_Lecture_Overload_sort_find_if.cpp
d2fafd9c93730c13fb0a7781abeaccbedbc6b340
[]
no_license
liulanz/Study-Personal-Lab
bece371164635131b3958efb72b88bf850557f94
895949bd87a06571daf80483e34b24c238c058b9
refs/heads/master
2022-12-04T10:50:25.004879
2020-07-31T07:55:16
2020-07-31T07:55:16
287,768,300
1
0
null
2020-08-15T15:00:35
2020-08-15T15:00:35
null
UTF-8
C++
false
false
969
cpp
#include <iostream> #include <list> #include <vector> #include <map> #include <string> #include <algorithm> //find_if using namespace std; bool comp1(int i) {return (i % 10 == 3); } bool comp2(int * p1, int * p2) { return *p1 < *p2; } int main() { vector<int> V1 = { 1,2,3,4,5 }; auto it1 = find(V1.begin(), V1.end(), 4); cout << *it1 << endl; auto it2 = find_if(V1.begin(), V1.end(), comp1);//find_if: find the first element that //satisties a condition cout << *it2 << endl; list<int *> L1 = { new int(30), new int(6), new int(11), new int(3) }; L1.sort(comp2); //sorting list of pointers to int. for (int *i : L1) { cout << *i << " "; } cout << endl; //list<vector<int *> *> L2 = {} How do we initialize L2? //L2.sort(f1000); ??? how should f1000 looks like? //Are these right topics for midterm exam? //auto it3 = find(L1.begin(), L1.end(), 6, f2000); //the above is not currently supported in C++ getchar(); getchar(); return 0; }
[ "junbinliang816@gmail.com" ]
junbinliang816@gmail.com
87d7c3530a5607e6a1c024e08994f7a4d6786790
14c685102101327da349f7da83099e90101c690c
/Service/jni/innoextract/src/util/fstream.hpp
1137ba758f0bbefbe0efcd79249702ebee522de2
[ "MIT", "Zlib", "Apache-2.0" ]
permissive
alanwoolley/innoextract-android
a59647cfe675ca404f4b041b7bd0acbef139deee
d0a72015a4a7898e0b5a24cae8642a4028c4d24b
refs/heads/master
2023-07-22T12:20:39.590781
2023-06-02T11:47:31
2023-06-02T11:47:31
14,408,419
23
11
null
null
null
null
UTF-8
C++
false
false
3,759
hpp
/* * Copyright (C) 2013-2014 Daniel Scharrer * * This software is provided 'as-is', without any express or implied * warranty. In no event will the author(s) be held liable for any damages * arising from the use of this software. * * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely, subject to the following restrictions: * * 1. The origin of this software must not be misrepresented; you must not * claim that you wrote the original software. If you use this software * in a product, an acknowledgment in the product documentation would be * appreciated but is not required. * 2. Altered source versions must be plainly marked as such, and must not be * misrepresented as being the original software. * 3. This notice may not be removed or altered from any source distribution. */ /*! * \file * * boost::filesystem::{i,o,}fstream doesn't support unicode names on windows * Implement our own wrapper using boost::iostreams. */ #ifndef INNOEXTRACT_UTIL_FSTREAM_HPP #define INNOEXTRACT_UTIL_FSTREAM_HPP #if !defined(_WIN32) #include <boost/filesystem/fstream.hpp> #ifdef __ANDROID__ #include "android_streams.hpp" #endif namespace util { typedef boost::filesystem::ifstream ifstream; #ifndef __ANDROID__ typedef boost::filesystem::ofstream ofstream; #else typedef android_ofstream ofstream; #endif typedef boost::filesystem::fstream fstream; } // namespace util #else // if defined(_WIN32) #include <boost/filesystem/path.hpp> #include <boost/iostreams/device/file_descriptor.hpp> #include <boost/iostreams/stream.hpp> namespace util { /*! * {i,o,}fstream implementation with support for Unicode filenames. * Create a subclass instead of a typedef to force boost::filesystem::path parameters. */ template <typename Device> class path_fstream : public boost::iostreams::stream<Device> { private: // disallow copying path_fstream(const path_fstream &); const path_fstream & operator=(const path_fstream &); typedef boost::filesystem::path path; typedef boost::iostreams::stream<Device> base; Device & device() { return **this; } void fix_open_mode(std::ios_base::openmode mode); public: path_fstream() : base(Device()) { } explicit path_fstream(const path & p) : base(p) { } path_fstream(const path & p, std::ios_base::openmode mode) : base(p, mode) { fix_open_mode(mode); } void open(const path & p) { base::close(); base::open(p); } void open(const path & p, std::ios_base::openmode mode) { base::close(); base::open(p, mode); fix_open_mode(mode); } bool is_open() { return device().is_open(); // return the real open state, not base::is_open() } virtual ~path_fstream() { } }; template <> inline void path_fstream<boost::iostreams::file_descriptor_source> ::fix_open_mode(std::ios_base::openmode mode) { if((mode & std::ios_base::ate) && is_open()) { seekg(0, std::ios_base::end); } } template <> inline void path_fstream<boost::iostreams::file_descriptor_sink> ::fix_open_mode(std::ios_base::openmode mode) { if((mode & std::ios_base::ate) && is_open()) { seekp(0, std::ios_base::end); } } template <> inline void path_fstream<boost::iostreams::file_descriptor> ::fix_open_mode(std::ios_base::openmode mode) { if((mode & std::ios_base::ate) && is_open()) { seekg(0, std::ios_base::end); seekp(0, std::ios_base::end); } } typedef path_fstream<boost::iostreams::file_descriptor_source> ifstream; typedef path_fstream<boost::iostreams::file_descriptor_sink> ofstream; typedef path_fstream<boost::iostreams::file_descriptor> fstream; } // namespace util #endif // defined(_WIN32) #endif // INNOEXTRACT_UTIL_FSTREAM_HPP
[ "alan@armedpineapple.co.uk" ]
alan@armedpineapple.co.uk
6f976dbba31ae12711647fc975b936fad547c364
2d926da3a7e99582bcc09e9a61e70a0d7175e8f8
/src/Magnum/Vk/Test/RenderPassVkTest.cpp
5c23db4fc37e65a370ad2a465ac2a0dc310d3ec3
[ "MIT" ]
permissive
black6816/magnum
5879fdf569b19bd835c1db87d3d5ce2f211e6c9f
a49602987499379e4a2d155472961d99ddfc75ba
refs/heads/master
2022-12-12T23:11:44.387207
2022-11-16T16:53:06
2022-11-19T14:26:39
155,795,059
0
0
null
2018-11-02T01:01:51
2018-11-02T01:01:51
null
UTF-8
C++
false
false
10,287
cpp
/* This file is part of Magnum. Copyright © 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020, 2021, 2022 Vladimír Vondruš <mosra@centrum.cz> 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 <sstream> #include <Corrade/Containers/Array.h> #include <Corrade/Utility/DebugStl.h> #include "Magnum/Math/Color.h" #include "Magnum/Math/Range.h" #include "Magnum/Vk/CommandBuffer.h" #include "Magnum/Vk/CommandPoolCreateInfo.h" #include "Magnum/Vk/DeviceProperties.h" #include "Magnum/Vk/Extensions.h" #include "Magnum/Vk/FramebufferCreateInfo.h" #include "Magnum/Vk/Handle.h" #include "Magnum/Vk/ImageCreateInfo.h" #include "Magnum/Vk/ImageViewCreateInfo.h" #include "Magnum/Vk/PixelFormat.h" #include "Magnum/Vk/RenderPassCreateInfo.h" #include "Magnum/Vk/Result.h" #include "Magnum/Vk/VulkanTester.h" namespace Magnum { namespace Vk { namespace Test { namespace { struct RenderPassVkTest: VulkanTester { explicit RenderPassVkTest(); void construct(); void constructNoSubpasses(); void constructSubpassNoAttachments(); void constructMove(); void wrap(); void cmdBeginEnd(); void cmdBeginEndDisallowedConversion(); }; RenderPassVkTest::RenderPassVkTest() { addTests({&RenderPassVkTest::construct, &RenderPassVkTest::constructNoSubpasses, &RenderPassVkTest::constructSubpassNoAttachments, &RenderPassVkTest::constructMove, &RenderPassVkTest::wrap, &RenderPassVkTest::cmdBeginEnd, &RenderPassVkTest::cmdBeginEndDisallowedConversion}); } void RenderPassVkTest::construct() { { RenderPass renderPass{device(), RenderPassCreateInfo{} .setAttachments({ AttachmentDescription{PixelFormat::RGBA8Unorm, AttachmentLoadOperation::Clear, AttachmentStoreOperation::Store, ImageLayout::Undefined, ImageLayout::General} }) .addSubpass(SubpassDescription{}.setColorAttachments({ AttachmentReference{0, ImageLayout::General} })) }; CORRADE_VERIFY(renderPass.handle()); CORRADE_COMPARE(renderPass.handleFlags(), HandleFlag::DestroyOnDestruction); } /* Shouldn't crash or anything */ CORRADE_VERIFY(true); } void RenderPassVkTest::constructNoSubpasses() { CORRADE_SKIP_IF_NO_ASSERT(); std::ostringstream out; Error redirectError{&out}; RenderPass{device(), RenderPassCreateInfo{}}; CORRADE_COMPARE(out.str(), "Vk::RenderPass: needs to be created with at least one subpass\n"); } void RenderPassVkTest::constructSubpassNoAttachments() { /* The spec requires at least one subpass, but it doesn't say anything about attachments, so this should work */ RenderPass renderPass{device(), RenderPassCreateInfo{} .addSubpass(SubpassDescription{}) }; CORRADE_VERIFY(renderPass.handle()); } void RenderPassVkTest::constructMove() { RenderPass a{device(), RenderPassCreateInfo{} .setAttachments({ AttachmentDescription{PixelFormat::RGBA8Unorm, AttachmentLoadOperation::Clear, AttachmentStoreOperation::Store, ImageLayout::Undefined, ImageLayout::ColorAttachment} }) .addSubpass(SubpassDescription{}.setColorAttachments({ AttachmentReference{0, ImageLayout::ColorAttachment} })) }; VkRenderPass handle = a.handle(); RenderPass b = std::move(a); CORRADE_VERIFY(!a.handle()); CORRADE_COMPARE(b.handle(), handle); CORRADE_COMPARE(b.handleFlags(), HandleFlag::DestroyOnDestruction); RenderPass c{NoCreate}; c = std::move(b); CORRADE_VERIFY(!b.handle()); CORRADE_COMPARE(b.handleFlags(), HandleFlags{}); CORRADE_COMPARE(c.handle(), handle); CORRADE_COMPARE(c.handleFlags(), HandleFlag::DestroyOnDestruction); CORRADE_VERIFY(std::is_nothrow_move_constructible<RenderPass>::value); CORRADE_VERIFY(std::is_nothrow_move_assignable<RenderPass>::value); } void RenderPassVkTest::wrap() { VkRenderPass renderPass{}; CORRADE_COMPARE(Result(device()->CreateRenderPass(device(), RenderPassCreateInfo{} .setAttachments({ AttachmentDescription{PixelFormat::RGBA8Unorm, AttachmentLoadOperation::Clear, AttachmentStoreOperation::Store, ImageLayout::Undefined, ImageLayout::ColorAttachment} }) .addSubpass(SubpassDescription{}.setColorAttachments({ AttachmentReference{0, ImageLayout::ColorAttachment} })) .vkRenderPassCreateInfo(), nullptr, &renderPass)), Result::Success); auto wrapped = RenderPass::wrap(device(), renderPass, HandleFlag::DestroyOnDestruction); CORRADE_COMPARE(wrapped.handle(), renderPass); /* Release the handle again, destroy by hand */ CORRADE_COMPARE(wrapped.release(), renderPass); CORRADE_VERIFY(!wrapped.handle()); device()->DestroyRenderPass(device(), renderPass, nullptr); } void RenderPassVkTest::cmdBeginEnd() { using namespace Math::Literals; CommandPool pool{device(), CommandPoolCreateInfo{ device().properties().pickQueueFamily(QueueFlag::Graphics)}}; CommandBuffer cmd = pool.allocate(); /* Using a depth attachment as well even though not strictly necessary to catch potential unexpected bugs */ Image color{device(), ImageCreateInfo2D{ImageUsage::ColorAttachment, PixelFormat::RGBA8Unorm, {256, 256}, 1}, MemoryFlag::DeviceLocal}; Image depth{device(), ImageCreateInfo2D{ImageUsage::DepthStencilAttachment, PixelFormat::Depth24UnormStencil8UI, {256, 256}, 1}, MemoryFlag::DeviceLocal}; ImageView colorView{device(), ImageViewCreateInfo2D{color}}; ImageView depthView{device(), ImageViewCreateInfo2D{depth}}; RenderPass renderPass{device(), RenderPassCreateInfo{} .setAttachments({ AttachmentDescription{color.format(), AttachmentLoadOperation::Clear, {}, ImageLayout::Undefined, ImageLayout::ColorAttachment}, AttachmentDescription{depth.format(), AttachmentLoadOperation::Clear, {}, ImageLayout::Undefined, ImageLayout::ColorAttachment}, }) .addSubpass(SubpassDescription{} .setColorAttachments({ AttachmentReference{0, ImageLayout::ColorAttachment} }) .setDepthStencilAttachment( AttachmentReference{1, ImageLayout::DepthStencilAttachment} ) ) /* Further subpasses with no attachments so we can test nextSubpass() but don't need to specify subpass dependencies (which I have no idea about yet) */ .addSubpass(SubpassDescription{}) .addSubpass(SubpassDescription{}) }; Framebuffer framebuffer{device(), FramebufferCreateInfo{renderPass, { colorView, depthView }, {256, 256}}}; cmd.begin() .beginRenderPass(RenderPassBeginInfo{renderPass, framebuffer} .clearColor(0, 0x1f1f1f_rgbf) .clearDepthStencil(1, 1.0f, 0)) .nextSubpass() /* The above overload goes through a different code path than this */ .nextSubpass(SubpassEndInfo{}) .endRenderPass() .end(); /* Err there's not really anything visible to verify */ CORRADE_VERIFY(cmd.handle()); } void RenderPassVkTest::cmdBeginEndDisallowedConversion() { CORRADE_SKIP_IF_NO_ASSERT(); if(device().isVersionSupported(Version::Vk12) ||device().isExtensionEnabled<Extensions::KHR::create_renderpass2>()) CORRADE_SKIP("KHR_create_renderpass2 enabled on the device, can't test"); CommandPool pool{device(), CommandPoolCreateInfo{ device().properties().pickQueueFamily(QueueFlag::Graphics)}}; CommandBuffer cmd = pool.allocate(); SubpassEndInfo endInfo; endInfo->pNext = &endInfo; SubpassBeginInfo beginInfo; beginInfo->pNext = &beginInfo; /* The commands shouldn't do anything, so it should be fine to just call them without any render pass set up */ std::ostringstream out; Error redirectError{&out}; cmd.beginRenderPass(RenderPassBeginInfo{NoInit}, beginInfo) .nextSubpass(beginInfo) .nextSubpass(endInfo) .endRenderPass(endInfo); CORRADE_COMPARE(out.str(), "Vk::CommandBuffer::beginRenderPass(): disallowing conversion of SubpassBeginInfo to VkSubpassContents with non-empty pNext to prevent information loss\n" "Vk::CommandBuffer::nextRenderPass(): disallowing conversion of SubpassBeginInfo to VkSubpassContents with non-empty pNext to prevent information loss\n" "Vk::CommandBuffer::nextRenderPass(): disallowing omission of SubpassEndInfo with non-empty pNext to prevent information loss\n" "Vk::CommandBuffer::endRenderPass(): disallowing omission of SubpassEndInfo with non-empty pNext to prevent information loss\n"); } }}}} CORRADE_TEST_MAIN(Magnum::Vk::Test::RenderPassVkTest)
[ "mosra@centrum.cz" ]
mosra@centrum.cz
3deafb5db885919fc5f195c72f7878a56b67a418
08b8cf38e1936e8cec27f84af0d3727321cec9c4
/data/crawl/git/new_hunk_2065.cpp
956860db5301c2dd1bf7ce60a5eee08d8019c148
[]
no_license
ccdxc/logSurvey
eaf28e9c2d6307140b17986d5c05106d1fd8e943
6b80226e1667c1e0760ab39160893ee19b0e9fb1
refs/heads/master
2022-01-07T21:31:55.446839
2018-04-21T14:12:43
2018-04-21T14:12:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
182
cpp
free(store.key); if ( ENOENT != errno ) { error_errno("opening %s", config_filename); ret = CONFIG_INVALID_FILE; /* same as "invalid config file" */ goto out_free; }
[ "993273596@qq.com" ]
993273596@qq.com
2c10518d4d8e9e913375461c60bbbbc592fcaa49
cd0ae1b0bec851eca3dabd27ccbfec5d5fbeea95
/src/BooleanOperation.cc
d4a5bd8a760cd81c64c3932925501e3ffbb559b7
[ "MIT" ]
permissive
liangcheng/node-occ
b64976746f80b19d1f62adcf0e62449b51acaea5
ea55726d6229f3cf754e8dce599748f6083af506
refs/heads/master
2020-07-10T09:57:50.850738
2015-07-09T08:14:55
2015-07-09T08:14:55
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,939
cc
#include "BooleanOperation.h" BooleanOperation::BooleanOperation() :m_bop(0) { } BooleanOperation::~BooleanOperation() { delete m_bop; } v8::Persistent<v8::FunctionTemplate> BooleanOperation::_template; v8::Handle<v8::Value> BooleanOperation::NewInstance(BOPAlgo_Operation op) { Local<Object> instance = NanNew<v8::FunctionTemplate>(_template)->GetFunction()->NewInstance(0,0); BooleanOperation* pThis = ObjectWrap::Unwrap<BooleanOperation>(instance); return instance; } BOPAlgo_Operation ReadOperationType(const Handle<Value>& arg) { if (arg->ToString()->Equals(NanNew("SECTION"))) return BOPAlgo_SECTION; if (arg->ToString()->Equals(NanNew("COMMON"))) return BOPAlgo_COMMON; if (arg->ToString()->Equals(NanNew("FUSE"))) return BOPAlgo_FUSE; if (arg->ToString()->Equals(NanNew("CUT"))) return BOPAlgo_CUT; if (arg->ToString()->Equals(NanNew("CUT21"))) return BOPAlgo_CUT21; return BOPAlgo_UNKNOWN; } NAN_METHOD(BooleanOperation::New) { NanScope(); BooleanOperation* pThis = new BooleanOperation(); pThis->Wrap(args.This()); BOPAlgo_Operation op = ReadOperationType(args[0]); if (op == BOPAlgo_UNKNOWN) { NanThrowError("bad operation type, must be SECTION COMMON FUSE CUT or CUT21"); ///NanThrowError("bad operation type, must be SECTION COMMON FUSE CUT or CUT21"); NanReturnUndefined(); } NanReturnValue(args.This()); } /* Handle<Value> BooleanOperation::getSameShape1(const v8::Arguments& args) { HandleScope scope; // can work with this Handle<Object> pJhis = args.This(); if ( pJhis.IsEmpty() || !constructor->HasInstance(pJhis)) { // create a new object ThrowException(Exception::Error(String::New("invalid object"))); } BooleanOperation* pThis = node::ObjectWrap::Unwrap<BooleanOperation>(pJhis); return scope.Close(arr); } Handle<Value> BooleanOperation_getSameShape2(const v8::Arguments& args) { } */ void BooleanOperation::Init(Handle<Object> target) { // Prepare constructor template v8::Local<v8::FunctionTemplate> tpl = NanNew<v8::FunctionTemplate>(BooleanOperation::New); tpl->SetClassName(NanNew("BooleanOperation")); // object has one internal filed ( the C++ object) tpl->InstanceTemplate()->SetInternalFieldCount(1); NanAssignPersistent<v8::FunctionTemplate>(_template, tpl); // constructor = Persistent<FunctionTemplate>::New(FunctionTemplate::New(BooleanOperation::New)); // Prototype //xx Local<ObjectTemplate> proto = constructor->PrototypeTemplate(); // xx Base::InitProto(proto); //xx EXPOSE_READ_ONLY_PROPERTY_INTEGER(Face,numWires); //xx EXPOSE_READ_ONLY_PROPERTY_DOUBLE(Face,area); //XX EXPOSE_METHOD(BooleanOperation,getSameShape1); //XX EXPOSE_METHOD(BooleanOperation,getSameShape2); //XX EXPOSE_READ_ONLY_PROPERTY(BooleanOperation,_shape1,shape1); //XX EXPOSE_READ_ONLY_PROPERTY(BooleanOperation,_shape2,shape2); target->Set(NanNew("BooleanOperation"), tpl->GetFunction()); }
[ "etienne.rossignon@gadz.org" ]
etienne.rossignon@gadz.org
dee5e3cec5bd26035f385982ff37e6c020ebe7b5
f52d7d227e774dcb2520ef649273f49403487951
/struct:file:class practice/Player.h
2531f3f654d48b54ceec96f6ea8877d7bc43d451
[]
no_license
zoeschmitt/common-algorithms
7ad345cc1fa01766095ad78273c9a3c1f191e4ee
d870f14bf2d99ae73db255d54e24212190716444
refs/heads/master
2022-04-29T14:28:11.605326
2019-03-07T17:19:11
2019-03-07T17:19:11
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,125
h
// File Name: Player.h // Holds the class for Player.cpp, // Which manages the songs on a music player device. #ifndef PLAYER_H #define PLAYER_H #include<iostream> using namespace std; #include "TimeStamp.h" const int SIZE = 1000; //Max size for amount of songs. class Player { private: struct Song { string band; //Band name. string title; //Song name. TimeStamp length; //Length of Song. float size; //Size of song in MB. }; int count; //counts the amount of songs in array. Song arr[SIZE]; //array of songs. string name1; //player name. float sizeMG; //max amount of mb. int searchInfo(string, string); void displaySongs(int); int totalSize(); public: Player(string name , float size); bool addSong(string , string , string , float ); bool removeSong(string band, string title); void displaySongInfo(string band, string title); void displaySongsByLength(); void deviceInfo(); }; #endif
[ "mica@Zoes-MacBook-Pro.local" ]
mica@Zoes-MacBook-Pro.local
73291d1d3b88049e0cf713752f9a0906d70dae0d
697f7f1964eadc95ccc6fa1eb871ae38e165b73c
/Day-27: Perfect Squares.cpp
0da4439b72ecb78fb8165b3db01d4ece257540d2
[]
no_license
amansharma07/June-Challenge-LeetCode
bc836af1d3e1751293b5878b69e40664dc343082
f4754e6ee0389daf411417c620240c88691df05b
refs/heads/master
2023-01-30T09:40:40.536949
2020-12-16T16:17:06
2020-12-16T16:17:06
268,540,990
1
0
null
2020-06-28T08:10:41
2020-06-01T14:12:08
C++
UTF-8
C++
false
false
498
cpp
class Solution { public: int numSquares(int n) { if(n<=3) return n; int dp[n+1]; dp[0] = 0; dp[1] = 1; dp[2] = 2; dp[3] = 3; for(int i=4; i<=n; i++) { dp[i] = i; for(int p=1; p<=ceil(sqrt(i)); p++) { int t = p*p; if(t>i) break; dp[i] = min(dp[i], 1+dp[i-t]); } } return dp[n]; } };
[ "noreply@github.com" ]
noreply@github.com
d341a57050edd787301deffdfa7763fd42cfa22c
4fb752a8b52ce3ebfa587fe7d08077486cf7e4a3
/tp5-bon/tp5-bon/ProduitAuxEncheres.cpp
90216cf4cb6de3e930fb7122e1a0f2cccd15e6e8
[]
no_license
YacerRazouani/INF1010
8a75d3d0cb97149dca250b190bd6ebe04e1ec78b
78be0c456ef2c77d45a4695c52321683167cb29e
refs/heads/master
2021-09-12T16:58:36.591142
2018-04-19T02:44:37
2018-04-19T02:44:37
118,972,459
0
0
null
null
null
null
UTF-8
C++
false
false
4,373
cpp
/******************************************** * Titre: Travail pratique #5 - ProduitAuxEncheres.cpp * Date: 6 avril 2018 * Modifier par: Amar Ghaly (1905322) & Yacer Razouani (1899606) *******************************************/ #include "ProduitAuxEncheres.h" /**************************************************************************** * Fonction: ProduitAuxEncheres::ProduitAuxEncheres() * Description: Constructeur par defaut * Parametres: (in) : double prix * Retour: Aucun ****************************************************************************/ ProduitAuxEncheres::ProduitAuxEncheres(double prix) : Produit(), prixInitial_(prix), encherisseur_(nullptr) { } /**************************************************************************** * Fonction: ProduitAuxEncheres::ProduitAuxEncheres() * Description: Constructeur par paramètre * Parametres: (in) : Fournisseur *fournisseur, const string &nom, * int reference, double prix * Retour: Aucun ****************************************************************************/ ProduitAuxEncheres::ProduitAuxEncheres(Fournisseur *fournisseur, const string &nom, int reference, double prix) : Produit(fournisseur, nom, reference, prix), prixInitial_(prix), encherisseur_(nullptr) { } /**************************************************************************** * Fonction: ProduitAuxEncheres::obtenirPrixInitial() * Description: Retourne la valeur de l'attribut prixInitial_ * Parametres: Aucun * Retour: (out) - double prixInitial_ ****************************************************************************/ double ProduitAuxEncheres::obtenirPrixInitial() const { return prixInitial_; } /**************************************************************************** * Fonction: ProduitAuxEncheres::obtenirEncherisseur() * Description: Retourne la valeur de l'attribut encherisseur_ * Parametres: Aucun * Retour: (out) - Client* encherisseur_ ****************************************************************************/ Client *ProduitAuxEncheres::obtenirEncherisseur() const { return encherisseur_; } /**************************************************************************** * Fonction: ProduitAuxEncheres::afficher() const * Description: Affiche les informations précises sur le produit aux encheres * Parametres: Aucun * Retour: Aucun ****************************************************************************/ void ProduitAuxEncheres::afficher() const { Produit::afficher(); cout << "\t\t\t\tprix initial:\t" << prixInitial_ << endl << "\t\t\t\tencherisseur:\t" << encherisseur_->obtenirNom() << endl; } /**************************************************************************** * Fonction: ProduitAuxEncheres::modifierPrixInitial() * Description: modifie la valeur de l'attribut prixInitial_ * Parametres: (in) : double prixInitial * Retour: Aucun ****************************************************************************/ void ProduitAuxEncheres::modifierPrixInitial(double prixInitial) { prixInitial_ = prixInitial; } /**************************************************************************** * Fonction: ProduitAuxEncheres::modifierEncherisseur() * Description: modifie la valeur de l'attribut enchirisseur_ * Parametres: (in) : Client *client * Retour: Aucun ****************************************************************************/ void ProduitAuxEncheres::modifierEncherisseur(Client *encherisseur) { encherisseur_ = encherisseur; } /**************************************************************************** * Fonction: ProduitAuxEncheres::mettreAJourEnchere() * Description: Met a jour les informations sur le produit aux enchere * Parametres: (in) : Client *encherisseur , double nouveauPrix * Retour: Aucun ****************************************************************************/ void ProduitAuxEncheres::mettreAJourEnchere(Client *encherisseur, double nouveauPrix) { if (encherisseur_ == encherisseur) return; prix_ = nouveauPrix; encherisseur->ajouterProduit(this); if (encherisseur_ != nullptr) encherisseur_->enleverProduit(this); encherisseur_ = encherisseur; }
[ "amar-gh@hotmail.com" ]
amar-gh@hotmail.com
cd17282f14cb468f16271b88e794c886fd0e42e4
dd80a584130ef1a0333429ba76c1cee0eb40df73
/external/chromium_org/chrome/common/extensions/manifest_handlers/nacl_modules_handler.h
9c7a4090ecb5ebcaa357356b7d158b03aeeee08b
[ "MIT", "BSD-3-Clause" ]
permissive
karunmatharu/Android-4.4-Pay-by-Data
466f4e169ede13c5835424c78e8c30ce58f885c1
fcb778e92d4aad525ef7a995660580f948d40bc9
refs/heads/master
2021-03-24T13:33:01.721868
2017-02-18T17:48:49
2017-02-18T17:48:49
81,847,777
0
2
MIT
2020-03-09T00:02:12
2017-02-13T16:47:00
null
UTF-8
C++
false
false
1,203
h
// Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CHROME_COMMON_EXTENSIONS_MANIFEST_HANDLERS_NACL_MODULES_HANDLER_H_ #define CHROME_COMMON_EXTENSIONS_MANIFEST_HANDLERS_NACL_MODULES_HANDLER_H_ #include <list> #include <string> #include "extensions/common/extension.h" #include "extensions/common/manifest_handler.h" namespace extensions { // An NaCl module included in the extension. struct NaClModuleInfo { typedef std::list<NaClModuleInfo> List; // Returns the NaCl modules for the extensions, or NULL if none exist. static const NaClModuleInfo::List* GetNaClModules( const Extension* extension); GURL url; std::string mime_type; }; // Parses the "nacl_modules" manifest key. class NaClModulesHandler : public ManifestHandler { public: NaClModulesHandler(); virtual ~NaClModulesHandler(); virtual bool Parse(Extension* extension, base::string16* error) OVERRIDE; private: virtual const std::vector<std::string> Keys() const OVERRIDE; }; } // namespace extensions #endif // CHROME_COMMON_EXTENSIONS_MANIFEST_HANDLERS_NACL_MODULES_HANDLER_H_
[ "karun.matharu@gmail.com" ]
karun.matharu@gmail.com
a55b3f98972787c8a5e23f6169588b3265423b91
04251e142abab46720229970dab4f7060456d361
/lib/rosetta/source/src/core/scoring/nmr/pre/PREData.cc
c29d756aaa9046540d08c572c181e3fc3f47826b
[]
no_license
sailfish009/binding_affinity_calculator
216257449a627d196709f9743ca58d8764043f12
7af9ce221519e373aa823dadc2005de7a377670d
refs/heads/master
2022-12-29T11:15:45.164881
2020-10-22T09:35:32
2020-10-22T09:35:32
null
0
0
null
null
null
null
UTF-8
C++
false
false
19,190
cc
// -*- mode:c++;tab-width:2;indent-tabs-mode:t;show-trailing-whitespace:t;rm-trailing-spaces:t -*- // vi: set ts=2 noet: // // (c) Copyright Rosetta Commons Member Institutions. // (c) This file is part of the Rosetta software suite and is made available under license. // (c) The Rosetta software is developed by the contributing members of the Rosetta Commons. // (c) For more information, see http://www.rosettacommons.org. Questions about this can be // (c) addressed to University of Washington UW TechTransfer, email: license@u.washington.edu. /// @file core/scoring/nmr/pre/PREData.cc /// @brief Implementation of class PREData /// @details last Modified: 10/12/16 /// @author Georg Kuenze (georg.kuenze@vanderbilt.edu) // Unit headers #include <core/scoring/nmr/pre/PREData.hh> // Package headers #include <core/scoring/nmr/pre/PREMultiSet.hh> #include <core/scoring/nmr/pre/PRESingleSet.hh> #include <core/scoring/nmr/pre/PRESingle.hh> #include <core/scoring/nmr/NMRDataFactory.hh> #include <core/scoring/nmr/NMRSpinlabel.hh> #include <core/scoring/nmr/NMRGridSearch.hh> #include <core/io/nmr/util.hh> #include <core/scoring/nmr/util.hh> // Project headers #include <core/types.hh> #include <core/pose/Pose.hh> #include <core/pose/PDBInfo.hh> #include <core/pose/util.hh> #include <core/id/AtomID.hh> #include <core/id/NamedAtomID.hh> #include <core/conformation/Residue.hh> // Basic headers #include <basic/Tracer.hh> #include <basic/datacache/CacheableData.hh> #include <basic/options/option.hh> #include <basic/options/keys/nmr.OptionKeys.gen.hh> // Utility headers #include <utility/exit.hh> #include <utility/vector1.hh> #include <utility/string_util.hh> #include <ObjexxFCL/string.functions.hh> // C++ headers #include <cmath> #include <string> #include <iostream> #include <sstream> #include <fstream> #include <utility> #include <algorithm> #include <numeric> namespace core { namespace scoring { namespace nmr { namespace pre { static basic::Tracer TR( "core.scoring.nmr.pre.PREData" ); /// @brief constructor with filename PREData::PREData( std::string const & filename, pose::Pose const & pose ) : basic::datacache::CacheableData(), number_spinlabel_sites_(0) { register_options(); init_pre_data_from_file(filename, pose); } /// @brief copy constructor PREData::PREData(PREData const & other) : basic::datacache::CacheableData(other), number_spinlabel_sites_(other.number_spinlabel_sites_) { // Make deep copy of PREMultiSet vector pre_multiset_vec_.clear(); pre_multiset_vec_.resize(other.pre_multiset_vec_.size()); for ( Size i = 1; i <= pre_multiset_vec_.size(); ++i ) { pre_multiset_vec_[i] = PREMultiSetOP( new PREMultiSet( *(other.pre_multiset_vec_[i]) ) ); } } /// @brief assignment operator PREData & PREData::operator=(PREData const & rhs) { if ( this != & rhs ) { basic::datacache::CacheableData::operator=(rhs); // Make deep copy of PREMultiSet vector pre_multiset_vec_.clear(); pre_multiset_vec_.resize(rhs.pre_multiset_vec_.size()); for ( Size i = 1; i <= pre_multiset_vec_.size(); ++i ) { pre_multiset_vec_[i] = PREMultiSetOP( new PREMultiSet( *(rhs.pre_multiset_vec_[i]) ) ); } number_spinlabel_sites_ = rhs.number_spinlabel_sites_; } return *this; } /// @brief destructor PREData::~PREData() {} basic::datacache::CacheableDataOP PREData::clone() const { return basic::datacache::CacheableDataOP( new PREData( *this )); } /// @brief compute the overall PRE score and individual scores for each spinlabel site Real PREData::compute_score_all_spinlabel( pose::Pose & pose, utility::vector1<Real> & individual_scores ) { using WeightCoordVector = PREMultiSet::WeightCoordVector; individual_scores.resize(number_spinlabel_sites_); // calculate total score and scores for each spinlabel site Real total_score(0); for ( Size i = 1; i <= number_spinlabel_sites_; ++i ) { WeightCoordVector para_ion_position; Real individual_score = pre_multiset_vec_[i]->find_para_ion_position_and_compute_pre_score(pose, para_ion_position); pre_multiset_vec_[i]->set_atom_derivatives(pose, para_ion_position); total_score += individual_score * pre_multiset_vec_[i]->get_weight(); individual_scores[i] = individual_score * pre_multiset_vec_[i]->get_weight(); } return total_score; } void PREData::show(std::ostream & tracer) const { auto sum_calc = [](Size const & a, PREMultiSetOP const & b) { return a + b->get_total_number_pre(); }; Size total_pre = std::accumulate(pre_multiset_vec_.begin(), pre_multiset_vec_.end(), 0, sum_calc); tracer << " * * * PREData Summary Report * * * " << std::endl; tracer << "No Spinlabel sites: " << number_spinlabel_sites_ << std::endl; tracer << "Total No PREs: " << total_pre << std::endl; for ( Size i = 1; i <= number_spinlabel_sites_; ++i ) { pre_multiset_vec_[i]->show(tracer); } } /// @brief register options void PREData::register_options() { using namespace basic::options; option.add_relevant(OptionKeys::nmr::pre::multiset_weights); } /// @brief utility function used during construction of PREData object void PREData::init_pre_data_from_file( std::string const & filename, pose::Pose const & pose ) { using namespace io::nmr; using id::AtomID; using id::NamedAtomID; using utility::to_string; using utility::string2Real; using ObjexxFCL::uppercased; std::ifstream infile; std::string line; utility::vector1< PRESingleSetOP > singleset_vec; utility::vector1< PREMultiSetOP > multiset_vec; std::map< std::string, std::string > multiset_params_map; pose::PDBInfoCOP pdbinfo = pose.pdb_info(); Size line_number(0); bool multisetblock(false); // initialize multiset weights from cml options utility::vector1<Real> multiset_weights; if ( basic::options::option[ basic::options::OptionKeys::nmr::pre::multiset_weights ].user() ) { multiset_weights = basic::options::option[ basic::options::OptionKeys::nmr::pre::multiset_weights ](); } TR.Info << "Opening file '" << utility::file_basename(filename) <<"' " << std::endl; infile.open(filename.c_str(), std::ios::in); if ( !infile.is_open() ) { utility_exit_with_message( "Unable to open PRE input file." ); } while ( std::getline(infile, line) ) { ++line_number; // Remove leading and trailing whitespace and skip comments and blank lines. utility::trim( line, " \t\n" ); if ( ( line.size() < 1 ) || ( line[ 0 ] == '#' ) ) { continue; } else if ( uppercased(line.substr(0,8)) == "MULTISET" ) { // Start of PREMultiSet group multisetblock = true; continue; } else if ( uppercased(line.substr(0,3)) == "END" ) { // End of PREMultiSet group // Create PREMultiSetOP and set members // Clear singleset vector and multiset_params map afterwards if ( !singleset_vec.empty() && !multiset_params_map.empty() ) { Size spinlabel_position; char chain_id; std::string ion_type; Real temperature; // Check that all parameter for the spinlabel and experimental conditions have been provided and convert them to the appropriate type // Mandatory are 'spinlabel_position', 'chain_id', 'spinlabel_type' or 'gridsearch', 'ion_type', 'temperature' and 'dataset', // and one of either option 'protein_mass' or 'taur'. Optional are 'tauc_min', 'tauc_max' and 'averaging'. if ( multiset_params_map.find("spinlabel_position") != multiset_params_map.end() ) { spinlabel_position = utility::string2Size(multiset_params_map["spinlabel_position"]); } else { utility_exit_with_message("ERROR in creating PREData. The spinlabel position for the PREMultiSet has not been provided."); } if ( multiset_params_map.find("chain_id") != multiset_params_map.end() ) { runtime_assert_msg(multiset_params_map["chain_id"].size() == 1, "ERROR in creating PREData. The spinlabel site chain ID for the PREMultiSet must be a single character."); chain_id = std::toupper(multiset_params_map["chain_id"].c_str()[0]); } else { utility_exit_with_message("ERROR in creating PREData. The spinlabel site chain ID for the PREMultiSet has not been provided."); } if ( multiset_params_map.find("ion_type") != multiset_params_map.end() ) { ion_type = multiset_params_map["ion_type"]; } else { utility_exit_with_message("ERROR in creating PREData. The spinlabel paramagnetic ion type for the PREMultiSet has not been provided."); } if ( multiset_params_map.find("temperature") != multiset_params_map.end() ) { temperature = string2Real(multiset_params_map["temperature"]); } else { utility_exit_with_message("ERROR in creating PREData. The temperature for the PREMultiSet has not been provided."); } // Try to convert tagging site number from pdb to pose numbering if ( pdbinfo ) { TR.Debug << "Converting PRE spinlabel site residue " + to_string(spinlabel_position) + " " + to_string(chain_id) + " in PRE input file from pdb to pose numbering." << std::endl; spinlabel_position = pdbinfo->pdb2pose(chain_id, spinlabel_position); if ( spinlabel_position == 0 ) { // Residue not found utility_exit_with_message( "ERROR: Cannot convert PRE spinlabel site residue residue " + to_string(spinlabel_position) + " " + to_string(chain_id) + " in PRE input file from pdb to pose numbering. Residue number was not found." ); } } else { // Assume pose numbering instead TR.Warning << "Cannot convert PRE spinlabel site residue in input file from pdb to pose numbering. No PDBInfo object. Using pose numbering instead." << std::endl; } // Finally create PREMultiSet with spinlabel or gridsearch PREMultiSetOP multiset_ptr; if ( multiset_params_map.find("spinlabel_type") != multiset_params_map.end() ) { if ( multiset_params_map.find("gridsearch") != multiset_params_map.end() ) { TR.Warning << "Gridsearch and spinlabel option have been both set in PREMultiSet, but only one method can be used for PRE calculation. "; TR.Warning << "Using spinlabel representation and skipping gridsearch." << std::endl; } std::string spinlabel_type = uppercased(multiset_params_map["spinlabel_type"]); NMRSpinlabelOP spinlabel_ptr( new NMRSpinlabel("fa_standard", spinlabel_type) ); if ( !spinlabel_ptr ) { utility_exit_with_message("ERROR in creating PREData. Could not create NMRSpinlabel object. Check if spinlabel ResidueType exists in Rosetta database."); } multiset_ptr = PREMultiSetOP( new PREMultiSet(singleset_vec, pose, spinlabel_position, ion_type, spinlabel_ptr) ); } else { if ( multiset_params_map.find("gridsearch") != multiset_params_map.end() ) { utility::vector1<std::string> gridsearch_params = read_gridsearch_values_from_string(multiset_params_map["gridsearch"]); std::string grid_atom1 = uppercased(gridsearch_params[1]); std::string grid_atom2 = uppercased(gridsearch_params[2]); Real distance_to_atom1 = string2Real(gridsearch_params[3]); Real grid_stepsize = string2Real(gridsearch_params[4]); Real grid_min_radius = string2Real(gridsearch_params[5]); Real grid_max_radius = string2Real(gridsearch_params[6]); AtomID atom1(named_atom_id_to_atom_id(NamedAtomID(grid_atom1, spinlabel_position), pose)); AtomID atom2(named_atom_id_to_atom_id(NamedAtomID(grid_atom2, spinlabel_position), pose)); NMRGridSearchOP gridsearch_ptr = NMRGridSearchOP( new NMRGridSearch(atom1, atom2, pose, distance_to_atom1, grid_stepsize, grid_min_radius, grid_max_radius) ); if ( !gridsearch_ptr ) { utility_exit_with_message("ERROR in creating PREData. Could not create NMRGridSearch object. Check gridsearch parameter."); } multiset_ptr = PREMultiSetOP( new PREMultiSet(singleset_vec, pose, spinlabel_position, ion_type, gridsearch_ptr) ); } else { utility_exit_with_message("ERROR in creating PREData. No gridsearch parameter or spinlabel type has been provided for the PREMultiSet."); } } multiset_ptr->set_temperature(temperature); if ( multiset_params_map.find("protein_mass") != multiset_params_map.end() ) { Real protein_mass = string2Real(multiset_params_map["protein_mass"]); multiset_ptr->set_protein_mass(protein_mass); } else if ( multiset_params_map.find("taur") != multiset_params_map.end() ) { Real taur = string2Real(multiset_params_map["taur"]); multiset_ptr->set_tau_r(taur); } else { utility_exit_with_message("ERROR in creating PREData. Neither the rotational correlation time nor the protein mass for the PREMultiSet have not been provided."); } if ( multiset_params_map.find("tauc_min") != multiset_params_map.end() && multiset_params_map.find("tauc_max") != multiset_params_map.end() ) { // correlation time is provided in nsec in input file Real tauc_min = string2Real(multiset_params_map["tauc_min"]) * 1.0e-9; Real tauc_max = string2Real(multiset_params_map["tauc_max"]) * 1.0e-9; if ( tauc_min > tauc_max ) { utility_exit_with_message("ERROR in creating PREData. Value of \"tauc_min\" is greater than \"tauc_max\"."); } multiset_ptr->set_tau_c_limits(tauc_min, tauc_max); } else { // Raise exit if only one of the two limits for tauc has been provided if ( multiset_params_map.find("tauc_min") != multiset_params_map.end() && multiset_params_map.find("tauc_max") == multiset_params_map.end() ) { utility_exit_with_message("ERROR in creating PREData. Value of \"tauc_min\" but not of \"tauc_max\" provided for PREMultiSet."); } else if ( multiset_params_map.find("tauc_min") == multiset_params_map.end() && multiset_params_map.find("tauc_max") != multiset_params_map.end() ) { utility_exit_with_message("ERROR in creating PREData. Value of \"tauc_max\" but not of \"tauc_min\" provided for PREMultiSet."); } } if ( multiset_params_map.find("averaging") != multiset_params_map.end() ) { std::string averaging_type = uppercased(multiset_params_map["averaging"]); runtime_assert( averaging_type == "SUM" || averaging_type == "MEAN" ); multiset_ptr->set_averaging_type(averaging_type); } multiset_vec.push_back(multiset_ptr); } else { TR.Warning << "Error in creating PREData. No PRE experiments or spinlabel parameter are available to create PREMultiSet at line " << line_number << " in PRE input file" << std::endl; TR.Warning << "Skip line " << line_number << std::endl; } multisetblock = false; singleset_vec.clear(); multiset_params_map.clear(); continue; } else if ( multisetblock ) { // Within the PREMultiSet block // Read spinlabel and experimental parameter as key-value pairs if ( line.find("spinlabel_position") != std::string::npos ) { read_key_value_pair_from_line(line, "spinlabel_position", multiset_params_map, line_number); } else if ( line.find("chain_id") != std::string::npos ) { read_key_value_pair_from_line(line, "chain_id", multiset_params_map, line_number); } else if ( line.find("gridsearch") != std::string::npos ) { read_key_value_pair_from_line(line, "gridsearch", multiset_params_map, line_number); } else if ( line.find("spinlabel_type") != std::string::npos ) { read_key_value_pair_from_line(line, "spinlabel_type", multiset_params_map, line_number); } else if ( line.find("ion_type") != std::string::npos ) { read_key_value_pair_from_line(line, "ion_type", multiset_params_map, line_number); } else if ( line.find("protein_mass") != std::string::npos ) { read_key_value_pair_from_line(line, "protein_mass", multiset_params_map, line_number); } else if ( line.find("taur") != std::string::npos ) { read_key_value_pair_from_line(line, "taur", multiset_params_map, line_number); } else if ( line.find("temperature") != std::string::npos ) { read_key_value_pair_from_line(line, "temperature", multiset_params_map, line_number); } else if ( line.find("tauc_min") != std::string::npos ) { read_key_value_pair_from_line(line, "tauc_min", multiset_params_map, line_number); } else if ( line.find("tauc_max") != std::string::npos ) { read_key_value_pair_from_line(line, "tauc_max", multiset_params_map, line_number); } else if ( line.find("averaging") != std::string::npos ) { read_key_value_pair_from_line(line, "averaging", multiset_params_map, line_number); } else if ( line.find("dataset") != std::string::npos ) { Size idx_key = line.find("dataset"); Size idx_equal_sign = line.find("=", idx_key + 7); if ( idx_equal_sign == std::string::npos ) { utility_exit_with_message("ERROR: No equal sign found after parameter \"dataset\" in NMR input file. Please provide input parameter \" key = value \"."); } else { utility::vector1<std::string> dataset_params = read_pre_dataset_params_list(utility::trim(line.substr(idx_equal_sign+1))); std::string pre_datafile = dataset_params[1]; Real weight = string2Real(dataset_params[2]); std::string weighting_scheme = uppercased(dataset_params[3]); std::string pre_rate_type = uppercased(dataset_params[4]); Real field_strength = string2Real(dataset_params[5]); // Check validity of input if ( weighting_scheme != "CONST" && weighting_scheme != "SIGMA" && weighting_scheme != "OBSIG" ) { utility_exit_with_message("ERROR in creating PREData. No valid single value weighting type in line " + to_string(line_number) + ". Possible weighting types are: \"CONST\", \"SIGMA\" and \"OBSIG\"."); } if ( pre_rate_type != "R1" && pre_rate_type != "R2" ) { utility_exit_with_message("ERROR in creating PREData. No valid PRE rate type in line " + to_string(line_number) + ". Possible weighting types are: \"R1\" and \"R2\"."); } PRESingleSetOP singleset_ptr( new PRESingleSet( pre_datafile, pose, weight, pre_rate_type, weighting_scheme) ); singleset_ptr->set_field_strength(field_strength); singleset_vec.push_back(singleset_ptr); } } } } if ( multiset_weights.size() != multiset_vec.size() ) { TR.Warning << "Number of PREMultiSet weights is inconsistent with the number of PREMultiSets in PRE input file. Set all weights to 1 instead." << std::endl; TR.Warning << "Make sure to provide weights on command line." << std::endl; for ( Size i = 1; i <= multiset_vec.size(); ++i ) { multiset_vec[i]->set_weight(1.0); } } else { for ( Size i = 1; i <= multiset_vec.size(); ++i ) { multiset_vec[i]->set_weight(multiset_weights[i]); } } infile.close(); // Finally, set the private data member of PREData pre_multiset_vec_ = multiset_vec; number_spinlabel_sites_ = multiset_vec.size(); TR.Info << "Finished reading PRE data for " << number_spinlabel_sites_ << " spinlabel site(s) from file " << utility::file_basename(filename) << std::endl; } Size PREData::get_total_number_pre() const { auto sum = [](Size const & a, PREMultiSetOP const & b) { return a + b->get_total_number_pre(); }; return std::accumulate(pre_multiset_vec_.begin(), pre_multiset_vec_.end(), 0, sum); } } // namespace pre } // namespace nmr } // namespace scoring } // namespace core
[ "lzhangbk@connect.ust.hk" ]
lzhangbk@connect.ust.hk
7cd5da523830e0d163c7f2945dc965a1ab06031d
1d6415afa337aae0e398b28bbf2e7d101f3de29a
/TestProject/data_structure/栈与队列/栈的链式结构/Stack.h
08b78be7af55951d28b4ef2d783fed7203c3778a
[]
no_license
WinstonLy/Job
131a0ecbb1b28eef1cd22fac4f196d46354093b0
b76d917c7f2cb2d6d4cb5613d447c43393448751
refs/heads/master
2022-12-04T01:23:01.072209
2020-08-30T08:56:09
2020-08-30T08:56:09
272,469,143
1
0
null
null
null
null
UTF-8
C++
false
false
277
h
/** * 定义栈的链式存储结构 */ #ifndef __LIST_H__ #define __LIST_H__ #include "Node.h" class Stack { public: Stack(); ~Stack(); void clearStack(); bool pushStack(Node* node); bool popStack(Node* node); int getTop(); private: int top; Node* head; }; #endif
[ "19961130g@gmail.com" ]
19961130g@gmail.com
256e41068a871428607a25d3e6acf4a3888219f9
00a2411cf452a3f1b69a9413432233deb594f914
/include/sqthird/poco/Foundation/StreamUtil.h
b9b3c427b3ec56ff7d44de571398a47a34f596e1
[]
no_license
willing827/lyCommon
a16aa60cd6d1c6ec84c109c17ce2b26197a57550
206651ca3022eda45c083bbf6e796d854ae808fc
refs/heads/master
2021-06-26T21:01:21.314451
2020-11-06T05:34:23
2020-11-06T05:34:23
156,497,356
4
0
null
null
null
null
UTF-8
C++
false
false
2,335
h
// // StreamUtil.h // // $Id: //poco/1.4/Foundation/include/Poco/StreamUtil.h#1 $ // // Library: Foundation // Package: Streams // Module: StreamUtil // // Stream implementation support. // // Copyright (c) 2005-2006, Applied Informatics Software Engineering GmbH. // and Contributors. // // SPDX-License-Identifier: BSL-1.0 // #ifndef Foundation_StreamUtil_INCLUDED #define Foundation_StreamUtil_INCLUDED #include "Poco/Foundation/Foundation.h" // poco_ios_init // // This is a workaround for a bug in the Dinkumware // implementation of iostreams. // // Calling basic_ios::init() multiple times for the // same basic_ios instance results in a memory leak // caused by the ios' locale being allocated more than // once, each time overwriting the old pointer. // This usually occurs in the following scenario: // // class MyStreamBuf: public std::streambuf // { // ... // }; // // class MyIOS: public virtual std::ios // { // public: // MyIOS() // { // init(&_buf); // } // protected: // MyStreamBuf _buf; // }; // // class MyIStream: public MyIOS, public std::istream // { // ... // }; // // In this scenario, std::ios::init() is called twice // (the first time by the MyIOS constructor, the second // time by the std::istream constructor), resulting in // two locale objects being allocated, the pointer second // one overwriting the pointer to the first one and thus // causing a memory leak. // // The workaround is to call init() only once for each // stream object - by the istream, ostream or iostream // constructor, and not calling init() in ios-derived // base classes. // // Some stream implementations, however, require that // init() is called in the MyIOS constructor. // Therefore we replace each call to init() with // the poco_ios_init macro defined below. #if !defined(POCO_IOS_INIT_HACK) // Microsoft Visual Studio with Dinkumware STL (but not STLport) # if defined(_MSC_VER) && (!defined(_STLP_MSVC) || defined(_STLP_NO_OWN_IOSTREAMS)) # define POCO_IOS_INIT_HACK 1 // QNX with Dinkumware but not GNU C++ Library # elif defined(__QNX__) && !defined(__GLIBCPP__) # define POCO_IOS_INIT_HACK 1 # endif #endif #if defined(POCO_IOS_INIT_HACK) # define poco_ios_init(buf) #else # define poco_ios_init(buf) init(buf) #endif #endif // Foundation_StreamUtil_INCLUDED
[ "willing827@163.com" ]
willing827@163.com
2bc2e4df6e4e0724945a9b86df8c517e6a985ab3
dc3be2481effa326f8556e8263e5502ef166f081
/firebase/firebase.h
1a0639e78cd412c934d31aa2fbdcef92a6b01549
[]
no_license
DrMoriarty/godot-firebase
e56199b0c0bd970d967a4020ccf7dbf370531b2a
d8b47af3961e2653433dabb8f3244019ade29e02
refs/heads/master
2020-04-13T15:11:22.643264
2019-10-11T10:01:02
2019-10-11T10:01:02
163,284,099
14
4
null
null
null
null
UTF-8
C++
false
false
715
h
#ifndef Firebase_h #define Firebase_h #include "core/reference.h" #include "firebase/app.h" #if defined(__ANDROID__) /// An Android Activity from Java. typedef jobject AppActivity; #elif defined(TARGET_OS_IPHONE) /// A pointer to an iOS UIView. typedef id AppActivity; #else /// A void pointer for stub classes. typedef void *AppActivity; #endif // __ANDROID__, TARGET_OS_IPHONE class Firebase : public Reference { GDCLASS(Firebase, Reference); protected: static firebase::App* app_ptr; static void _bind_methods(); static void createApplication(); public: Firebase(); static firebase::App* AppId(); static AppActivity GetAppActivity(); }; #endif // Firebase_h
[ "drmoriarty.0@gmail.com" ]
drmoriarty.0@gmail.com
3ce47de620bb0b974cfaa2a924b92e744f3310fd
684b85c6ca7d336ef1e778c1367d8d5e65e758d4
/linuxqq_client/moc_filerecieve.cpp
7a4860893631b840cc1bbb681486b7938d6c3b85
[]
no_license
jerrypy/linuxqq
a8bdaac689fff1d6a7474a15ac8502a303a112be
00e70a61750098546463b0c78285b7e4b41415fb
refs/heads/master
2021-01-01T05:47:01.363621
2014-12-16T10:03:54
2014-12-16T10:03:54
28,081,000
1
0
null
null
null
null
UTF-8
C++
false
false
2,365
cpp
/**************************************************************************** ** Meta object code from reading C++ file 'filerecieve.h' ** ** Created: Wed Mar 12 08:23:10 2014 ** by: The Qt Meta Object Compiler version 63 (Qt 4.8.3) ** ** WARNING! All changes made in this file will be lost! *****************************************************************************/ #include "filerecieve.h" #if !defined(Q_MOC_OUTPUT_REVISION) #error "The header file 'filerecieve.h' doesn't include <QObject>." #elif Q_MOC_OUTPUT_REVISION != 63 #error "This file was generated using the moc from 4.8.3. It" #error "cannot be used with the include files from this version of Qt." #error "(The moc has changed too much.)" #endif QT_BEGIN_MOC_NAMESPACE static const uint qt_meta_data_FileRecieve[] = { // content: 6, // revision 0, // classname 0, 0, // classinfo 0, 0, // methods 0, 0, // properties 0, 0, // enums/sets 0, 0, // constructors 0, // flags 0, // signalCount 0 // eod }; static const char qt_meta_stringdata_FileRecieve[] = { "FileRecieve\0" }; void FileRecieve::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) { Q_UNUSED(_o); Q_UNUSED(_id); Q_UNUSED(_c); Q_UNUSED(_a); } const QMetaObjectExtraData FileRecieve::staticMetaObjectExtraData = { 0, qt_static_metacall }; const QMetaObject FileRecieve::staticMetaObject = { { &QDialog::staticMetaObject, qt_meta_stringdata_FileRecieve, qt_meta_data_FileRecieve, &staticMetaObjectExtraData } }; #ifdef Q_NO_DATA_RELOCATION const QMetaObject &FileRecieve::getStaticMetaObject() { return staticMetaObject; } #endif //Q_NO_DATA_RELOCATION const QMetaObject *FileRecieve::metaObject() const { return QObject::d_ptr->metaObject ? QObject::d_ptr->metaObject : &staticMetaObject; } void *FileRecieve::qt_metacast(const char *_clname) { if (!_clname) return 0; if (!strcmp(_clname, qt_meta_stringdata_FileRecieve)) return static_cast<void*>(const_cast< FileRecieve*>(this)); return QDialog::qt_metacast(_clname); } int FileRecieve::qt_metacall(QMetaObject::Call _c, int _id, void **_a) { _id = QDialog::qt_metacall(_c, _id, _a); if (_id < 0) return _id; return _id; } QT_END_MOC_NAMESPACE
[ "jerrynwin@gmail.com" ]
jerrynwin@gmail.com
25ff27a2083f5fc3deff0275b45f86303a247404
fab5498a07621a3a1fe642aba754d3efeb582017
/src/osg/Viewer/View_wrap.cpp
6ba7f6dde79992c7428a8652b29d8be60ceb7964
[ "MIT" ]
permissive
vuvk/osg_vala_wrapper
e0beb1cdde040a1ac0917be40cbab7c333a63bc9
1d764277926a745844f8f7a9e5e1fe46f128bed1
refs/heads/master
2022-10-08T16:58:42.617097
2020-06-09T03:47:43
2020-06-09T03:47:43
268,712,396
2
0
null
null
null
null
UTF-8
C++
false
false
3,595
cpp
#include <osg/View> extern "C" { void* _view_new() { return new osg::View(); } void _view_dispose(void* view) { static_cast<osg::View*>(view)->unref(); } /** Take all the settings, Camera and Slaves from the passed in view, leaving it empty. */ void _view_take(void* view, void* rhs) { static_cast<osg::View*>(view)->take(*(static_cast<osg::View*>(rhs))); } /** Set the Stats object used to collect various frame related timing and scene graph stats.*/ void _view_set_stats(void* view, void* stats) { static_cast<osg::View*>(view)->setStats(static_cast<osg::Stats*>(stats)); } /** Get the Viewers Stats object.*/ void* _view_get_stats(void* view) { return static_cast<osg::View*>(view)->getStats(); } /** Set the global lighting to use for this view. * Defaults to headlight. */ void _view_set_lighting_mode(void* view, int lighting_mode) { static_cast<osg::View*>(view)->setLightingMode((osg::View::LightingMode)lighting_mode); } /** Get the global lighting used for this view.*/ int _view_get_lighting_mode(void* view) { return (int) static_cast<osg::View*>(view)->getLightingMode(); } /** Get the global light.*/ void _view_set_light(void* view, void* light) { static_cast<osg::View*>(view)->setLight(static_cast<osg::Light*>(light)); } /** Get the global lighting if assigned.*/ void* _view_get_light(void* view) { return static_cast<osg::View*>(view)->getLight(); } /** Set the master camera of the view. */ void _view_set_camera(void* view, void* camera) { static_cast<osg::View*>(view)->setCamera(static_cast<osg::Camera*>(camera)); } /** Get the master camera of the view. */ void* _view_get_camera(void* view) { return static_cast<osg::View*>(view)->getCamera(); } /** Set the frame stamp of the view. */ void _view_set_frame_stamp(void* view, void* fs) { static_cast<osg::View*>(view)->setFrameStamp(static_cast<osg::FrameStamp*>(fs)); } /** Get the frame stamp of the view. */ void* _view_get_frame_stamp(void* view) { return static_cast<osg::View*>(view)->getFrameStamp(); } bool _view_add_slave(void* view, void* camera, bool use_masters_sceneData/*=true*/) { return static_cast<osg::View*>(view)->addSlave(static_cast<osg::Camera*>(camera), use_masters_sceneData); } bool _view_add_slave_ext(void* view, void* camera, void* projection_offset, void* view_offset, bool use_masters_sceneData/*=true*/) { return static_cast<osg::View*>(view)->addSlave( static_cast<osg::Camera*>(camera), *static_cast<osg::Matrix*>(projection_offset), *static_cast<osg::Matrix*>(view_offset), use_masters_sceneData ); } bool _view_remove_slave(void* view, unsigned int pos) { return static_cast<osg::View*>(view)->removeSlave(pos); } unsigned int _view_get_num_slaves(void* view) { return static_cast<osg::View*>(view)->getNumSlaves(); } //Slave& _view_getSlave(void* view, unsigned int pos) { return _slaves[pos]; } unsigned int _view_find_slave_index_for_camera(void* view, void* camera) { return static_cast<osg::View*>(view)->findSlaveIndexForCamera(static_cast<osg::Camera*>(camera)); } //Slave * _view_findSlaveForCamera(void* view, osg::Camera* camera); void _view_update_slaves(void* view) { static_cast<osg::View*>(view)->updateSlaves(); } void _view_resize_gl_object_buffers(void* view, unsigned int max_size) { static_cast<osg::View*>(view)->resizeGLObjectBuffers(max_size); } void _view_release_gl_objects(void* view, void* state/* = 0*/) { static_cast<osg::View*>(view)->releaseGLObjects(static_cast<osg::State*>(state)); } }
[ "panknd@mail.ru" ]
panknd@mail.ru
27ff6961f599bbb52dc8d50fb4cd95c1dc53c540
ad361ddd3e64fdcd2ffda107c2ff121172b5e23d
/fieldsAtlantik/bateauVoyageur.h
1c768857b7d00679910d8f49a0a47a3d048e126d
[]
no_license
prostain/casAtlantik
622caf75fb12267f344908044bdb4b13eb521934
c6a53b90022886522abf00482de751b409de29ce
refs/heads/master
2020-03-11T18:18:33.900657
2018-04-19T07:14:25
2018-04-19T07:14:25
130,173,868
0
0
null
null
null
null
UTF-8
C++
false
false
532
h
#ifndef BATEAUVOYAGEUR_H #define BATEAUVOYAGEUR_H #include <iostream> #include <vector> #include "bateau.h" #include "colEquipement.h" #include <QString> using namespace std; class BateauVoyageur : public Bateau { private: int vitesseBatVoy; string imageBatVoy; ColEquipement lesEquipements; public: string versChaine(); BateauVoyageur(string idBateau,string nomBateau,int longueurBateau,int largeurBateau ,int vitesseBatVoyage ,string imageBatVoyage, ColEquipement lesEquipements); string getImageBatVoy(); }; #endif
[ "peterson.rostain@gmail.com" ]
peterson.rostain@gmail.com
c1befc0dbb1a5bb399f691db82d42a8125797c68
39cabd2d103523b8ee758009ecc4f0beaf768a1f
/reverseK.h
fbd05f12187a5172b4d293cfb558b1544be51fdb
[]
no_license
Yindong-Zhang/nowcoder
4de67b78b7ddb8cbae213f40cfc3dfa3d9ec05a0
28473f535d6ca564165bb8edad97f83e99202c42
refs/heads/master
2021-07-02T04:30:41.417765
2020-12-02T12:50:01
2020-12-02T12:50:01
202,059,878
0
1
null
null
null
null
UTF-8
C++
false
false
1,822
h
// // Created by so_go on 2020/4/23. // #ifndef UNTITLED_REVERSEK_H #define UNTITLED_REVERSEK_H # include <bits/stdc++.h> using namespace std; struct list_node{ int val; struct list_node * next; }; list_node * input_list() { int val, n; scanf("%d", &n); list_node * phead = new list_node(); list_node * cur_pnode = phead; for (int i = 1; i <= n; ++i) { scanf("%d", &val); if (i == 1) { cur_pnode->val = val; cur_pnode->next = NULL; } else { list_node * new_pnode = new list_node(); new_pnode->val = val; new_pnode->next = NULL; cur_pnode->next = new_pnode; cur_pnode = new_pnode; } } return phead; } list_node *recursive_reverse(list_node *head, int resCount, int K){ if(resCount < K){ return head; } list_node *curPtr = head->next, *lastPtr = head, *nextPtr; int count = 1; while(count < K){ nextPtr = curPtr->next; curPtr->next = lastPtr; lastPtr = curPtr; curPtr = nextPtr; count++; } head->next = recursive_reverse(nextPtr, resCount - K, K); return lastPtr; } list_node * reverse_knode(list_node * head1, int K) { //////在下面完成代码 int count = 0; list_node *ptr = head1; while(ptr != NULL){ count++; ptr = ptr->next; } return recursive_reverse(head1, count, K); } void print_list(list_node * head) { while (head != NULL) { printf("%d ", head->val); head = head->next; } puts(""); } int reverseK () { list_node * head = input_list(); int K; scanf("%d", &K); list_node * new_head = reverse_knode(head, K); print_list(new_head); return 0; } #endif //UNTITLED_REVERSEK_H
[ "so_go_flying@163.com" ]
so_go_flying@163.com
99fd4968da62970cb55ea1ddf36e97adadce5772
97e03fe85120edb2416a336d200fd2af471f17ca
/Personnal-projects-C++/2048/Sources/main.cpp
745459dd84851ab5dbb9afd49c62e9e4a7160cdf
[]
no_license
ericJz/Personnal-projects
06136ae4f34b99b3b60fbcb4eb4f0bcfaa913412
5d3dafd5bfe165480311176826219f1880e4af7b
refs/heads/master
2021-01-17T16:22:20.224633
2016-07-07T07:52:24
2016-07-07T07:52:24
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,521
cpp
#include <iostream> #include <conio.h> #include <ctime> #include "app.h" int main() { int order; int i = 0; // time_t start, end, period; int basechoix, dimension; std::cout << "you want to play with 2 or 3 as your base?" << std::endl; std::cin >> basechoix; while (basechoix != 2 && basechoix != 3){ std::cout << "you want to play with 2 or 3 as your base?" << std::endl; std::cin >> basechoix; } std::cout << "you want to play with which dimension? you can choose from 3 to 5" << std::endl; std::cin >> dimension; while (dimension != 3 && dimension != 4 && dimension != 5){ std::cout << "you want to play with which dimension? you can choose from 3 to 5" << std::endl; std::cin >> dimension; } app ex(basechoix, dimension); // 注意有构造函数时的声明方式!! ex.init(); while(1){ // start = clock(); ex.calculate(ex.direction); ex.newnum(i); // end = clock(); // period = end - start; system("cls"); ex.show(); std::cout << "you have moved " << ++i << " times" << std::endl; // std::cout << "this time takes " << period << " ms" << std::endl; if (ex.det() == 1){ break; } order = ex.getorder(); while (order != 1){ order = ex.getorder(); } } std::cout << "you failed!" << std::endl; std::cout << "press return to quit..." << std::endl; getch(); return 0; }
[ "zcy.scott@gmail.com" ]
zcy.scott@gmail.com
3caecf2ea3fbb64ead927ae690071d82c1ea9172
abc47d74bd60ee1655c0bae2af29391978674643
/yellow_belt/2_week/test_person.cpp
cf2383d309c8dbdd6b616091ec24ad0a3c02214c
[]
no_license
ivantishchenko/modern-cpp
1d021b9b7531449cfde056ea92e10458f0d9cc2c
695267d6e8d48c1b0bb276b497e362c0dd2c14b3
refs/heads/main
2023-07-15T18:37:55.854043
2021-08-25T20:09:26
2021-08-25T20:09:26
364,678,150
0
0
null
null
null
null
UTF-8
C++
false
false
5,092
cpp
#include <iostream> #include <map> #include <set> #include <sstream> #include <stdexcept> #include <string> #include <vector> using namespace std; template <class T> ostream& operator << (ostream& os, const vector<T>& s) { os << "{"; bool first = true; for (const auto& x : s) { if (!first) { os << ", "; } first = false; os << x; } return os << "}"; } template <class T> ostream& operator << (ostream& os, const set<T>& s) { os << "{"; bool first = true; for (const auto& x : s) { if (!first) { os << ", "; } first = false; os << x; } return os << "}"; } template <class K, class V> ostream& operator << (ostream& os, const map<K, V>& m) { os << "{"; bool first = true; for (const auto& kv : m) { if (!first) { os << ", "; } first = false; os << kv.first << ": " << kv.second; } return os << "}"; } template<class T, class U> void AssertEqual(const T& t, const U& u, const string& hint = {}) { if (t != u) { ostringstream os; os << "Assertion failed: " << t << " != " << u; if (!hint.empty()) { os << " hint: " << hint; } throw runtime_error(os.str()); } } void Assert(bool b, const string& hint) { AssertEqual(b, true, hint); } class TestRunner { public: template <class TestFunc> void RunTest(TestFunc func, const string& test_name) { try { func(); cerr << test_name << " OK" << endl; } catch (exception& e) { ++fail_count; cerr << test_name << " fail: " << e.what() << endl; } catch (...) { ++fail_count; cerr << "Unknown exception caught" << endl; } } ~TestRunner() { if (fail_count > 0) { cerr << fail_count << " unit tests failed. Terminate" << endl; exit(1); } } private: int fail_count = 0; }; //// если имя неизвестно, возвращает пустую строку //string FindNameByYear(const map<int, string>& names, int year) { // string name; // изначально имя неизвестно // // // перебираем всю историю по возрастанию ключа словаря, то есть в хронологическом порядке // for (const auto& item : names) { // // если очередной год не больше данного, обновляем имя // if (item.first <= year) { // name = item.second; // } else { // // иначе пора остановиться, так как эта запись и все последующие относятся к будущему // break; // } // } // // return name; //} // //class Person { //public: // void ChangeFirstName(int year, const string& first_name) { // first_names[year] = first_name; // } // void ChangeLastName(int year, const string& last_name) { // last_names[year] = last_name; // } // string GetFullName(int year) { // // получаем имя и фамилию по состоянию на год year // const string first_name = FindNameByYear(first_names, year); // const string last_name = FindNameByYear(last_names, year); // // // если и имя, и фамилия неизвестны // if (first_name.empty() && last_name.empty()) { // return "Incognito"; // // // если неизвестно только имя // } else if (first_name.empty()) { // return last_name + " with unknown first name"; // // // если неизвестна только фамилия // } else if (last_name.empty()) { // return first_name + " with unknown last name"; // // // если известны и имя, и фамилия // } else { // return first_name + " " + last_name; // } // } // //private: // map<int, string> first_names; // map<int, string> last_names; //}; void Test1() { Person person; person.ChangeFirstName(1965, "Polina"); person.ChangeLastName(1967, "Sergeeva"); Assert(person.GetFullName(1900) == "Incognito", "Incognito"); Assert(person.GetFullName(1965) == "Polina with unknown last name", "First name"); Assert(person.GetFullName(1990) == "Polina Sergeeva", "Full name"); person.ChangeFirstName(1970, "Appolinaria"); Assert(person.GetFullName(1969) == "Polina Sergeeva", "No change 1"); Assert(person.GetFullName(1970) == "Appolinaria Sergeeva", "Change 1"); person.ChangeLastName(1968, "Volkova"); Assert(person.GetFullName(1969) == "Polina Volkova", "No change 2"); Assert(person.GetFullName(1970) == "Appolinaria Volkova", "Change 2"); } void Test2() { Person person; person.ChangeLastName(1965, "Sergeeva"); person.ChangeFirstName(1967, "Polina"); AssertEqual(person.GetFullName(1964), "Incognito"); AssertEqual(person.GetFullName(1966), "Sergeeva with unknown first name"); AssertEqual(person.GetFullName(1968), "Polina Sergeeva"); } void Test3() { } int main() { TestRunner runner; runner.RunTest(Test1, "Block 1"); runner.RunTest(Test2, "Block 2"); // добавьте сюда свои тесты return 0; }
[ "johnny.tishchenko@gmail.com" ]
johnny.tishchenko@gmail.com
12613abfa9f0c9754b6284e227d43b0f3c006f19
0a4a0a089733395fc6207324ad8c9f1609e46c9f
/Maze C++/src/solve_line.cpp
fc94b39334c5acf575e3ff2e24b1f1a747688434
[]
no_license
suribe1010/University_Projects
2e913533337c3ee2e5c513aef29c5a664bdd66bc
fdda288cea4ce612d2e2ca21ba05f7c771858336
refs/heads/master
2021-01-04T20:17:07.572850
2020-02-15T16:35:19
2020-02-15T16:35:19
240,731,514
0
0
null
null
null
null
UTF-8
C++
false
false
3,783
cpp
#include <a_star.h> #include <maze.h> using namespace std; using namespace ecn; // a node is a x-y position, we move from 1 each time class Position : public Point { typedef std::unique_ptr<Position> PositionPtr; private: const int height=Position::maze.height(); const int width=Position::maze.width(); const int size = height*width; int w[2]; public: // constructor from coordinates Position(int _x, int _y) : Point(_x, _y) {} // constructor from base ecn::Point Position(ecn::Point p) : Point(p.x, p.y) {} // constructor for line-based motions Position(int _x, int _y, int _distance) : Point(_x, _y, _distance) {} static Point starting; static Point ending; int distToParent() //const Point &_child) { // in line-based motion, the distance is not 1 anymore return distance;//_child.distance; } //case in which we are in the ending or starting point bool terminalNodes (int x, int y) { if (x == ending.x && y == ending.y) return true; else { if (x == starting.x && y == starting.y) return true; else return false; } } //going through the corridor to childrens std::vector<PositionPtr> children() { // this method should return all positions reachable from this one std::vector<PositionPtr> generated; //Moving down if(Position::maze.isFree(x, y+1)){ int j=0; while(!Position::maze.isFree(x-1, y+1+j) && !Position::maze.isFree(x+1, y+1+j)&& Position::maze.isFree(x, y+2+j) && !terminalNodes(x, y)) j++; distance = j+1; generated.push_back(std::make_unique<Position>(x, y+1+j, distance)); } //Moving up if(Position::maze.isFree(x, y-1)){ int j=0; while( !Position::maze.isFree(x-1, y-1-j) && !Position::maze.isFree(x+1, y-1-j)&& Position::maze.isFree(x, y-2-j) && !terminalNodes(x, y)) j++; distance = j+1; generated.push_back(std::make_unique<Position>(x, y-1-j, distance)); } //Moving right if(Position::maze.isFree(x+1, y)){ int j=0; while( !Position::maze.isFree(x+1+j, y-1) && !Position::maze.isFree(x+1+j, y+1)&& Position::maze.isFree(x+2+j, y) && !terminalNodes(x, y)) j++; distance = j+1; generated.push_back(std::make_unique<Position>(x+1+j, y, distance)); } //Moving left if(Position::maze.isFree(x-1, y)){ int j=0; while( !Position::maze.isFree(x-1-j, y-1) && !Position::maze.isFree(x-1-j, y+1)&& Position::maze.isFree(x-2-j, y) && !terminalNodes(x, y)) j++; distance = j+1; generated.push_back(std::make_unique<Position>(x-1-j, y, distance)); } if(terminalNodes(x, y)) generated.push_back(std::make_unique<Position>(x, y, distance)); return generated; } }; Point Position::starting(0,0); Point Position::ending(0,0); int main( int argc, char **argv ) { // load file std::string filename = "maze.png"; if(argc == 2) filename = std::string(argv[1]); // let Point know about this maze Position::maze.load(filename); // initial and goal positions as Position's Position start = Position::maze.start(), goal = Position::maze.end(); Position::starting = start; Position::ending = goal; // call A* algorithm ecn::Astar(start, goal); // save final image Position::maze.saveSolution("cell"); cv::waitKey(0); }
[ "noreply@github.com" ]
noreply@github.com
f722f16ea42010ca8bb64e324afcb01fc875e98d
cbbcfcb52e48025cb6c83fbdbfa28119b90efbd2
/codechef/snackB/E.cpp
9ad8e01f252ae631a79a4abad824cb76c72fb6d4
[]
no_license
dmehrab06/Time_wasters
c1198b9f2f24e06bfb2199253c74a874696947a8
a158f87fb09d880dd19582dce55861512e951f8a
refs/heads/master
2022-04-02T10:57:05.105651
2019-12-05T20:33:25
2019-12-05T20:33:25
104,850,524
0
1
null
null
null
null
UTF-8
C++
false
false
3,774
cpp
/*-------property of the half blood prince-----*/ #include <bits/stdc++.h> #include <dirent.h> #include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/tree_policy.hpp> #include <ext/pb_ds/detail/standard_policies.hpp> #define MIN(X,Y) X<Y?X:Y #define MAX(X,Y) X>Y?X:Y #define ISNUM(a) ('0'<=(a) && (a)<='9') #define ISCAP(a) ('A'<=(a) && (a)<='Z') #define ISSML(a) ('a'<=(a) && (a)<='z') #define ISALP(a) (ISCAP(a) || ISSML(a)) #define MXX 10000000000 #define MNN -MXX #define ISVALID(X,Y,N,M) ((X)>=1 && (X)<=(N) && (Y)>=1 && (Y)<=(M)) #define LLI long long int #define VI vector<int> #define VLLI vector<long long int> #define MII map<int,int> #define SI set<int> #define PB push_back #define MSI map<string,int> #define PII pair<int,int> #define PLLI pair<LLI,LLI> #define FREP(i,I,N) for(int (i)=(int)(I);(i)<=(int)(N);(i)++) #define eps 0.0000000001 #define RFREP(i,N,I) for(int (i)=(int)(N);(i)>=(int)(I);(i)--) #define SORTV(VEC) sort(VEC.begin(),VEC.end()) #define SORTVCMP(VEC,cmp) sort(VEC.begin(),VEC.end(),cmp) #define REVV(VEC) reverse(VEC.begin(),VEC.end()) #define INRANGED(val,l,r) (((l)<(val) || fabs((val)-(l))<eps) && ((val)<(r) || fabs((val)-(r))<eps)) using namespace std; using namespace __gnu_pbds; //int dx[]={1,0,-1,0};int dy[]={0,1,0,-1}; //4 Direction //int dx[]={1,1,0,-1,-1,-1,0,1};int dy[]={0,1,1,1,0,-1,-1,-1};//8 direction //int dx[]={2,1,-1,-2,-2,-1,1,2};int dy[]={1,2,2,1,-1,-2,-2,-1};//Knight Direction //int dx[]={2,1,-1,-2,-1,1};int dy[]={0,1,1,0,-1,-1}; //Hexagonal Direction typedef tree < int, null_type, less<int>, rb_tree_tag, tree_order_statistics_node_update > ordered_set; vector< pair< PII, PII> > hsnk; vector< pair< PII, PII> > vsnk; void init(){ hsnk.clear(); vsnk.clear(); } void takeinp(int n){ FREP(i,1,n){ int x1,y1,x2,y2; scanf("%d %d %d %d",&x1,&y1,&x2,&y2); if(x1==x2){ vsnk.PB(make_pair(make_pair(x1,y1),make_pair(x2,y2))); } else{ hsnk.PB(make_pair(make_pair(x1,y1),make_pair(x2,y2))); } } } int manhattan(int x1, int y1, int x2, int y2){ return abs(x1-x2)+abs(y1-y2); } int getminmove(){ int ultimateminmove = 100000000; FREP(x,1,50){ FREP(y,1,50){ //x,y is cur intersection point int mxmove = 0; int hsz=hsnk.size(); FREP(i,0,(hsz-1)){ pair< PII,PII > cursnake=hsnk[i]; int yy = cursnake.first.second; int minx = min(cursnake.first.first,cursnake.second.first); int maxx = max(cursnake.first.first,cursnake.second.first); int minmove = 100000000; FREP(k,minx,maxx){ int travel = manhattan(k,yy,x,y); minmove = min(travel,minmove); } mxmove = max(mxmove,minmove); } int vsz=vsnk.size(); FREP(i,0,(vsz-1)){ pair< PII,PII > cursnake=vsnk[i]; int xx = cursnake.first.first; int miny = min(cursnake.first.second,cursnake.second.second); int maxy = max(cursnake.first.second,cursnake.second.second); int minmove = 100000000; FREP(k,miny,maxy){ int travel = manhattan(xx,k,x,y); minmove = min(travel,minmove); } mxmove = max(mxmove,minmove); } ultimateminmove = min(ultimateminmove,mxmove); } } return ultimateminmove; } int main(){ int t; scanf("%d",&t); while(t--){ init(); int n; scanf("%d",&n); takeinp(n); int ans = getminmove(); printf("%d\n",ans); } return 0; }
[ "1205112.zm@ugrad.cse.buet.ac.bd" ]
1205112.zm@ugrad.cse.buet.ac.bd
e0c723b9434967159f888ac5f2263d03cd11391e
1c4626a0898cf2f1fe40c9c573b986a8e3c1468c
/SpaceInvaders/Bullet.h
8d67c35d722d2bb0195351bc8ce85ec9c5184548
[]
no_license
Nerys-Thamm/SpaceInvaders-SFML
ae24a02d5fde5eb9d1d8af02982e24935bc3839d
14c58140f120e7de2063f94a57ed5cfbab0439e0
refs/heads/master
2022-12-20T19:01:07.324467
2020-10-03T02:14:30
2020-10-03T02:14:30
299,588,991
0
0
null
null
null
null
UTF-8
C++
false
false
2,662
h
//////////////////////////////////////////////////////////// //========================================================== // Bachelor of Software Engineering // Media Design School // Auckland // New Zealand //---------------------------------------------------------- // (c) 2020 Media Design School //========================================================== // File Name : Bullet.h //---------------------------------------------------------- // Description : Contains the definition and prototypes // for the CBullet class. // // //---------------------------------------------------------- // Author : Nerys Thamm BSE20021 //---------------------------------------------------------- // E-mail : NerysThamm@gmail.com //========================================================== //////////////////////////////////////////////////////////// #pragma once #include "Sprites.h" #include "EasySFML.h" // -------------------------------------------------------------------------------- /// <summary> /// Instances of CBullet are created by the player's weapon to destroy aliens /// </summary> // -------------------------------------------------------------------------------- class CBullet : private CGameObject { public: /// <summary>Hitbox of the bullet</summary> sf::RectangleShape bulletRect; /// <summary>Coordinates of the bullet</summary> float fX, fY; // ******************************************************************************** /// <summary> /// <para> /// Constructor with Parameters for Class: CBullet /// </para> /// </summary> /// <param name="_fX"><para> /// Type: float, X coord to spawn the bullet at /// </para></param> /// <returns></returns> // ******************************************************************************** CBullet(float _fx); // ******************************************************************************** /// <summary> /// <para> /// Function name: Update /// Function is part of Class: CBullet /// </para> /// </summary> /// <param name="_fDeltaTime"><para> /// Type: float, time since last frame /// </para></param> // ******************************************************************************** virtual void Update(float _fDeltaTime); };
[ "NerysThamm@gmail.com" ]
NerysThamm@gmail.com
764b0e69b28dc70485247698c4399d173208ccaf
7cb47a1edbc5a74a00af0e9e7b67cacf448994f0
/src/app/ext/media/gfx/gfx-scene.cpp
00bf0dfcb505bd0efe011135201b5bb54d07f272
[ "MIT" ]
permissive
indigoabstract/techno-globe
2c24819abe9774309fa7a9175c1c63676c31571a
1f01b231bece534282344fa660d5f9a8cc07262e
refs/heads/master
2021-04-06T10:25:27.866859
2018-04-11T12:18:42
2018-04-11T12:18:42
125,355,507
0
0
null
null
null
null
UTF-8
C++
false
false
6,791
cpp
#include "stdafx.h" #include "gfx-scene.hpp" #include "gfx-state.hpp" #include "gfx-camera.hpp" #include "gfx-vxo.hpp" #include "gfx.hpp" #include "gfx-tex.hpp" #include "gfx-util.hpp" #include "gfx-shader.hpp" #include "pfmgl.h" glm::vec3 gfx_transform::get_forward_dir() { return orientation() * glm::vec3(0, 0, -1.f); } glm::vec3 gfx_transform::get_up_dir() { return orientation() * glm::vec3(0, 1.f, 0); } glm::vec3 gfx_transform::get_right_dir() { return orientation() * glm::vec3(1.f, 0, 0); } void gfx_transform::look_at(glm::vec3 direction, glm::vec3 desiredUp) { orientation = gfx_util::look_at(direction, desiredUp); } void gfx_transform::look_at_pos(glm::vec3 iposition, glm::vec3 desiredUp) { glm::vec3 direction = iposition - position(); orientation = gfx_util::look_at(direction, desiredUp); } gfx_node::gfx_node(std::shared_ptr<gfx> i_gi) : gfx_obj(i_gi), name(this) { node_type = regular_node; visible = true; } gfx_obj::e_gfx_obj_type gfx_node::get_type()const { return e_gfx_node; } std::shared_ptr<gfx_node> gfx_node::get_shared_ptr() { return std::static_pointer_cast<gfx_node>(get_inst()); } std::shared_ptr<gfx_node> gfx_node::get_parent() { return parent.lock(); } std::shared_ptr<gfx_node> gfx_node::get_root() { return root.lock(); } std::shared_ptr<gfx_scene> gfx_node::get_scene() { return std::static_pointer_cast<gfx_scene>(root.lock()); } void gfx_node::add_to_draw_list(const std::string& icamera_id, std::vector<shared_ptr<gfx_vxo> >& idraw_list) { } void gfx_node::update() { std::vector<shared_ptr<gfx_node> >::iterator it = children.begin(); for (; it != children.end(); it++) { (*it)->update(); } } void gfx_node::attach(shared_ptr<gfx_node> inode) { if (inode->parent.lock()) { trx("this node is already part of a hierarchy"); } else { if (inode->node_type == camera_node) { shared_ptr<gfx_camera> icamera = static_pointer_cast<gfx_camera>(inode); root.lock()->add_camera_node(icamera); } children.push_back(inode); inode->parent = get_shared_ptr(); inode->root = root; } } void gfx_node::detach() { shared_ptr<gfx_node> parent_node = parent.lock(); if (parent_node) { if (node_type == camera_node) { shared_ptr<gfx_camera> icamera = static_pointer_cast<gfx_camera>(get_shared_ptr()); root.lock()->remove_camera_node(icamera); } parent_node->children.erase(std::find(parent_node->children.begin(), parent_node->children.end(), get_shared_ptr())); parent = shared_ptr<gfx_node>(); root = shared_ptr<gfx_scene>(); } else { trx("this node is not part of a hierarchy"); } } bool gfx_node::contains(const shared_ptr<gfx_node> inode) { if (inode == get_shared_ptr()) { return true; } std::vector<shared_ptr<gfx_node> >::iterator it = children.begin(); for (; it != children.end(); it++) { bool contains_node = (*it)->contains(inode); if (contains_node) { return true; } } return false; } shared_ptr<gfx_node> gfx_node::find_node_by_name(const std::string& iname) { if (iname == get_shared_ptr()->name()) { return get_shared_ptr(); } std::vector<shared_ptr<gfx_node> >::iterator it = children.begin(); for (; it != children.end(); it++) { shared_ptr<gfx_node> node = (*it)->find_node_by_name(iname); if (node) { return node; } } return shared_ptr<gfx_node>(); } gfx_scene::gfx_scene(std::shared_ptr<gfx> i_gi) : gfx_node(i_gi) { } void gfx_scene::init() { root = static_pointer_cast<gfx_scene>(get_shared_ptr()); } void gfx_scene::draw() { shared_ptr<gfx_state> gl_st = gfx::get_gfx_state(); struct pred { bool operator()(const shared_ptr<gfx_camera> a, const shared_ptr<gfx_camera> b) const { return a->rendering_priority < b->rendering_priority; } }; plist.clear(); plist.push_back({ gl::BLEND, gl::FALSE_GL }); plist.push_back({ gl::CULL_FACE, gl::FALSE_GL }); plist.push_back({ gl::DEPTH_TEST, gl::FALSE_GL }); plist.push_back({ gl::DEPTH_WRITEMASK, gl::TRUE_GL }); plist.push_back({ gl::DITHER, gl::TRUE_GL }); //plist.push_back({ gl::MULTISAMPLE, gl::TRUE_GL }); plist.push_back({ gl::POLYGON_OFFSET_FILL, gl::FALSE_GL }); plist.push_back({ gl::SCISSOR_TEST, gl::FALSE_GL }); plist.push_back({ gl::STENCIL_TEST, gl::FALSE_GL }); gl_st->set_state(&plist[0], plist.size()); std::sort(camera_list.begin(), camera_list.end(), pred()); std::vector<shared_ptr<gfx_camera> >::iterator it = camera_list.begin(); for (; it != camera_list.end(); it++) { shared_ptr<gfx_camera> cam = *it; if (!cam->enabled) { continue; } const std::string& camera_id = cam->camera_id; gfx_uint clear_mask = 0; plist.clear(); if (cam->clear_color) { glm::vec4 c = cam->clear_color_value.to_vec4(); plist.push_back({ gl::COLOR_CLEAR_VALUE, c.r, c.g, c.b, c.a }); clear_mask |= gl::COLOR_BUFFER_BIT_GL; } if (cam->clear_depth) { clear_mask |= gl::DEPTH_BUFFER_BIT_GL; } if (cam->clear_stencil) { clear_mask |= gl::STENCIL_BUFFER_BIT_GL; } if (clear_mask != 0) { plist.push_back({ gl::CLEAR_MASK, clear_mask }); } if (!plist.empty()) { gl_st->set_state(&plist[0], plist.size()); } cam->update_camera_state(); std::vector<shared_ptr<gfx_vxo> > draw_list; for (auto it = children.begin(); it != children.end(); it++) { (*it)->add_to_draw_list(camera_id, draw_list); } auto it3 = draw_list.begin(); for (; it3 != draw_list.end(); it3++) { shared_ptr<gfx_vxo> mesh = *it3; if (!mesh->visible) { continue; } gfx_material& mat = *mesh->get_material(); shared_ptr<gfx_shader> shader = mat.get_shader(); if (shader) { //mesh->push_material_params(); mesh->render_mesh(cam); } else { vprint("mesh object at [%p] has null shader\n", mesh.get()); } } } } void gfx_scene::update() { std::vector<shared_ptr<gfx_node> >::iterator it = children.begin(); for (; it != children.end(); it++) { (*it)->update(); } } void gfx_scene::add_camera_node(shared_ptr<gfx_camera> icamera) { camera_list.push_back(icamera); } void gfx_scene::remove_camera_node(shared_ptr<gfx_camera> icamera) { camera_list.erase(std::find(camera_list.begin(), camera_list.end(), icamera)); }
[ "indigoabstract@gmail.com" ]
indigoabstract@gmail.com
56557d70c471b3d5f0b9b34d7ae1b885f55aa803
c18fe82db18be9ac493d94362e5f08ae676a5b9a
/algorithms/dyanmic_programming/longestcommonsubs/main.cpp
47330d32d358de230fab90be41a5f04070a59c69
[]
no_license
charlesq/Euthenia
e05347d8dadd3249d06aece62d28bf3e10866339
5ca738a249215c439156e29dca495840a6488cbb
refs/heads/master
2021-01-15T19:40:13.679311
2019-01-21T04:05:11
2019-01-21T04:05:11
15,544,644
0
0
null
null
null
null
UTF-8
C++
false
false
1,308
cpp
#include <iostream> #include <utility> #include <ctime> #include <cstdlib> #include <climits> #include <forward_list> #include <stack> #include <queue> #include <string.h> #include <vector> using namespace std; string lcs(const string &a, const string & b) { unsigned int ai = 0, bi = 0; unsigned int l = 0; vector<vector<unsigned int>> v(a.length() + 1); for (vector<unsigned int > &aa: v) aa.resize(b.length() + 1, 0); for (int i = 0; i < a.length(); i++) { for ( int j = 0; j < b.length(); j ++) { if ( a[i] == b[j]) v[i + 1][j+1] = v[i][j] + 1; if (v[i +1] [j+1] > l) { ai = i ; bi = j ; l = v[i+1][j+1]; } } } cout << " len is " << l << endl; if (l == 0) return string(""); return a.substr(ai - l +1, l); } int main() { unsigned int k = 0; while(true) { string a, b; cout << "Input string a: "; cin >> a; cout << endl<<"Input string b: "; cin >> b; cout << endl; cout << lcs(a, b) << endl; char t; cout << "Halt(Y/N)?"; cin >> t; if ( t == 'y' || t == 'Y') break; } return 0; }
[ "Charles.Zxxx@gmail.com" ]
Charles.Zxxx@gmail.com
e1362858ae247a1454af14cc23bb595b02450087
02d1be45f769b40ccf1a28977019948443e49eab
/Regex_Example.cc
e208f6e94716bfe5a78a5744ba7394f4898bbe6b
[ "MIT" ]
permissive
ucarlos/Programming-Principles-Chapter23
79c20beae8758d1e93bb23a4ed18c7c75415c947
30234d31720e9194880cc84d04d3d6247ce1c1a0
refs/heads/master
2023-03-08T11:38:54.714376
2021-02-23T19:35:07
2021-02-23T19:35:07
327,123,124
0
0
null
null
null
null
UTF-8
C++
false
false
910
cc
/* * ----------------------------------------------------------------------------- * Created by Ulysses Carlos on 01/03/2021 at 06:10 PM * * Regex_Example.cc * * ----------------------------------------------------------------------------- */ #include <iostream> #include <string> #include <fstream> #include <regex> using namespace std; int main() { ifstream input {"Regex_File.txt"}; if (!input) { cerr << "Error: Cannot open file.\n"; exit(EXIT_FAILURE); } regex pattern {R"(\w{2}\s*\d{5}(-\d{4})?)"}; int line_num = 0; for (string line; getline(input, line); ) { line_num++; smatch matches; if (regex_search(line, matches, pattern)) { cout << line_num << ": " << matches[0] << "\n"; cout << "Also, for your convenience: \n"; for (int i = 1; i < matches.length(); i++) if (matches[i].matched) cout << "Match " << i << ": " << matches[i] << endl; } } }
[ "ulysses_carlos@protonmail.com" ]
ulysses_carlos@protonmail.com
0418101e870fedd4da20173e2c19448733d96765
7bc58e0e6a34f3d74c2da7b367ad348e1a8862d0
/tools/kactus2/kactus2-3.2.35/IPXACTmodels/kactusExtensions/Kactus2Value.h
9aae03d5ae84212df357e414fbd92b1f0c40b8bf
[]
no_license
ouabache/fossi
3069e7440597b283b657eaee11fbc203909d54aa
e780307bff0bb702e6da36df5d15305354c95f42
refs/heads/master
2020-07-02T08:58:41.834354
2017-04-06T15:59:09
2017-04-06T15:59:09
67,724,364
4
1
null
null
null
null
UTF-8
C++
false
false
2,423
h
//----------------------------------------------------------------------------- // File: Kactus2Value.h //----------------------------------------------------------------------------- // Project: Kactus 2 // Author: Esko Pekkarinen // Date: 20.5.2014 // // Description: // Kactus2 vendor extension for name-value pairs. //----------------------------------------------------------------------------- #ifndef KACTUS2VALUE_H #define KACTUS2VALUE_H #include <IPXACTmodels/ipxactmodels_global.h> #include <IPXACTmodels/common/VendorExtension.h> //----------------------------------------------------------------------------- // class Kactus2Value. //----------------------------------------------------------------------------- class IPXACTMODELS_EXPORT Kactus2Value : public VendorExtension { public: /*! * The constructor. * * @param [in] parent The parent object. */ Kactus2Value(QString name, QString value); /*! * The destructor. */ virtual ~Kactus2Value(); /*! * Clones the vendor extension. * * @return The clone copy of the vendor extension. */ virtual Kactus2Value* clone() const; /*! * Returns a type identifier for the vendor extension. * * @return A type identifier of the vendor extension. */ virtual QString type() const; /*! * Writes the vendor extension to XML. * * @param [in] writer The writer used for writing the XML. */ virtual void write(QXmlStreamWriter& writer) const; /*! * Gets the value of the vendor extension. * * @return The stored value. */ QString value() const; /*! * Sets the value of the vendor extension. * * @param [in] newValue The value to set. */ void setValue(QString const& newValue); private: //! Disable copying. Kactus2Value(Kactus2Value const& other); // Disable assignment. Kactus2Value& operator=(Kactus2Value const& rhs); //----------------------------------------------------------------------------- // Data. //----------------------------------------------------------------------------- //! The name identifier of the vendor extension. QString name_; //! The value of the vendor extension. QString value_; }; #endif // KACTUS2VALUE_H
[ "z3qmtr45@gmail.com" ]
z3qmtr45@gmail.com
0f92e3dfa43af89dbc4ab4a9bbbe397b242fa3d3
9f149db67482ca24c8abf8294a0b1e1d58b9a71f
/drake/examples/QPInverseDynamicsForHumanoids/humanoid_status.cc
a6498b3d59dcdf8dcf97e0e5fd3b97920f3d36fb
[ "BSD-3-Clause" ]
permissive
katanachan/drake
cbe57a07ab1042487b2703703dc3fff4e5894b05
07090bc103333304dfdbd78accfa64feb30ea197
refs/heads/master
2021-01-24T11:18:34.606922
2016-10-07T00:46:53
2016-10-07T00:46:53
70,239,226
1
0
null
2016-10-07T11:07:56
2016-10-07T11:07:56
null
UTF-8
C++
false
false
4,408
cc
#include "humanoid_status.h" #include <iostream> namespace drake { namespace example { namespace qp_inverse_dynamics { // TODO(siyuan.feng@tri.global): These are hard coded for Valkyrie, and they // should be included in the model file or loaded from a separate config file. const Eigen::Vector3d HumanoidStatus::kFootToSoleOffset = Eigen::Vector3d(0, 0, -0.09); const Eigen::Vector3d HumanoidStatus::kFootToSensorPositionOffset = Eigen::Vector3d(0.0215646, 0.0, -0.051054); const Eigen::Matrix3d HumanoidStatus::kFootToSensorRotationOffset = Eigen::Matrix3d(Eigen::AngleAxisd(-M_PI, Eigen::Vector3d::UnitX())); void HumanoidStatus::Update( double t, const Eigen::Ref<const Eigen::VectorXd>& q, const Eigen::Ref<const Eigen::VectorXd>& v, const Eigen::Ref<const Eigen::VectorXd>& joint_torque, const Eigen::Ref<const Eigen::Vector6d>& l_wrench, const Eigen::Ref<const Eigen::Vector6d>& r_wrench) { if (q.size() != position_.size() || v.size() != velocity_.size() || joint_torque.size() != joint_torque_.size()) { throw std::runtime_error("robot state update dimension mismatch."); } time_ = t; position_ = q; velocity_ = v; joint_torque_ = joint_torque; cache_.initialize(position_, velocity_); robot_.doKinematics(cache_, true); M_ = robot_.massMatrix(cache_); drake::eigen_aligned_std_unordered_map<RigidBody const*, drake::TwistVector<double>> f_ext; bias_term_ = robot_.dynamicsBiasTerm(cache_, f_ext); // com com_ = robot_.centerOfMass(cache_); J_com_ = robot_.centerOfMassJacobian(cache_); Jdot_times_v_com_ = robot_.centerOfMassJacobianDotTimesV(cache_); comd_ = J_com_ * velocity_; centroidal_momentum_matrix_ = robot_.centroidalMomentumMatrix(cache_); centroidal_momentum_matrix_dot_times_v_ = robot_.centroidalMomentumMatrixDotTimesV(cache_); centroidal_momentum_ = centroidal_momentum_matrix_ * velocity_; // body parts for (BodyOfInterest& body_of_interest : bodies_of_interest_) body_of_interest.Update(robot_, cache_); // ft sensor foot_wrench_raw_[Side::LEFT] = l_wrench; foot_wrench_raw_[Side::RIGHT] = r_wrench; for (int i = 0; i < 2; i++) { // Make H1 = H_sensor_to_sole. // Assuming the sole frame has the same orientation as the foot frame. Eigen::Isometry3d H1; H1.linear() = kFootToSensorRotationOffset.transpose(); H1.translation() = -kFootToSensorPositionOffset + kFootToSoleOffset; foot_wrench_in_sole_frame_[i] = transformSpatialForce(H1, foot_wrench_raw_[i]); // H2 = transformation from sensor frame to a frame that is aligned with the // world frame, and is located at the origin of the foot frame. Eigen::Isometry3d H2; H2.linear() = foot(i).pose().linear() * kFootToSensorRotationOffset.transpose(); H2.translation() = foot(i).pose().translation() - foot_sensor(i).pose().translation(); foot_wrench_in_world_frame_[i] = transformSpatialForce(H2, foot_wrench_raw_[i]); } // Compute center of pressure (CoP) Eigen::Vector2d cop_w[2]; double Fz[2] = {foot_wrench_in_world_frame_[Side::LEFT][5], foot_wrench_in_world_frame_[Side::RIGHT][5]}; for (int i = 0; i < 2; i++) { // Ignore CoP computation if normal force is small if (fabs(foot_wrench_raw_[i][5]) < 1) { cop_in_sole_frame_[i][0] = 0; cop_in_sole_frame_[i][1] = 0; cop_w[i][0] = foot(i).pose().translation()[0]; cop_w[i][1] = foot(i).pose().translation()[1]; } else { // CoP relative to the ft sensor cop_in_sole_frame_[i][0] = -foot_wrench_in_sole_frame_[i][1] / foot_wrench_in_sole_frame_[i][5]; cop_in_sole_frame_[i][1] = foot_wrench_in_sole_frame_[i][0] / foot_wrench_in_sole_frame_[i][5]; // CoP in the world frame cop_w[i][0] = -foot_wrench_in_world_frame_[i][1] / Fz[i] + foot(i).pose().translation()[0]; cop_w[i][1] = foot_wrench_in_world_frame_[i][0] / Fz[i] + foot(i).pose().translation()[1]; } } // This is assuming that both feet are on the same horizontal surface. cop_ = (cop_w[Side::LEFT] * Fz[Side::LEFT] + cop_w[Side::RIGHT] * Fz[Side::RIGHT]) / (Fz[Side::LEFT] + Fz[Side::RIGHT]); } } // end namespace qp_inverse_dynamics } // end namespace example } // end namespace drake
[ "siyuan.feng@tri.global" ]
siyuan.feng@tri.global
e24dff503d78b9ab57338b6469aa165d2870867a
44622e013415d2bcb82522b7bffdca652bd5d6e5
/stage_2/stage_2/StateShowProblem.h
4d753060f0b9a1c9696cd5e573be903765de98fa
[]
no_license
JeLLek1/pea-project
87d4a3a64d23e454e5fc9c2757a4bf170943490f
89214478fd253def7d6d072542f733c46dd90ea5
refs/heads/main
2023-02-28T06:14:42.650964
2021-01-25T20:21:28
2021-01-25T20:21:28
311,528,815
0
0
null
null
null
null
WINDOWS-1250
C++
false
false
273
h
#pragma once #include <string> #include "AState.h" class StateShowProblem : public AState { public: // przetwarzanie rządań i wyświetlanie informacji na ekranie virtual void process(); // przetwarzanie wciśniętych klawiszy virtual bool handleInput(char key); };
[ "jellek@wp.pl" ]
jellek@wp.pl
177fb037c5d544333b315adab0921caa628e8368
9923e30eb99716bfc179ba2bb789dcddc28f45e6
/openapi-generator/cpp-restsdk/model/InlineObject4.cpp
84fc2c921f171c9479f66d2a539f9e7a187d6b9d
[]
no_license
silverspace/samsara-sdks
cefcd61458ed3c3753ac5e6bf767229dd8df9485
c054b91e488ab4266f3b3874e9b8e1c9e2d4d5fa
refs/heads/master
2020-04-25T13:16:59.137551
2019-03-01T05:49:05
2019-03-01T05:49:05
172,804,041
2
0
null
null
null
null
UTF-8
C++
false
false
7,638
cpp
/** * Samsara API * # Introduction Samsara provides API endpoints for interacting with Samsara Cloud, so that you can build powerful applications and custom solutions with sensor data. Samsara has endpoints available to track and analyze sensors, vehicles, and entire fleets. The Samsara Cloud API is a [RESTful API](https://en.wikipedia.org/wiki/Representational_state_transfer) accessed by an [HTTP](https://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol) client such as wget or curl, or HTTP libraries of most modern programming languages including python, ruby, java. We use built-in HTTP features, like HTTP authentication and HTTP verbs, which are understood by off-the-shelf HTTP clients. We allow you to interact securely with our API from a client-side web application (though you should never expose your secret API key). [JSON](http://www.json.org/) is returned by all API responses, including errors. If you’re familiar with what you can build with a REST API, the following API reference guide will be your go-to resource. API access to the Samsara cloud is available to all Samsara administrators. To start developing with Samsara APIs you will need to [obtain your API keys](#section/Authentication) to authenticate your API requests. If you have any questions you can reach out to us on [support@samsara.com](mailto:support@samsara.com) # Endpoints All our APIs can be accessed through HTTP requests to URLs like: ```curl https://api.samsara.com/<version>/<endpoint> ``` All our APIs are [versioned](#section/Versioning). If we intend to make breaking changes to an API which either changes the response format or request parameter, we will increment the version. # Authentication To authenticate your API request you will need to include your secret token. You can manage your API tokens in the [Dashboard](https://cloud.samsara.com). They are visible under `Settings->Organization->API Tokens`. Your API tokens carry many privileges, so be sure to keep them secure. Do not share your secret API tokens in publicly accessible areas such as GitHub, client-side code, and so on. Authentication to the API is performed via [HTTP Basic Auth](https://en.wikipedia.org/wiki/Basic_access_authentication). Provide your API token as the basic access_token value in the URL. You do not need to provide a password. ```curl https://api.samsara.com/<version>/<endpoint>?access_token={access_token} ``` All API requests must be made over [HTTPS](https://en.wikipedia.org/wiki/HTTPS). Calls made over plain HTTP or without authentication will fail. # Request Methods Our API endpoints use [HTTP request methods](https://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol#Request_methods) to specify the desired operation to be performed. The documentation below specified request method supported by each endpoint and the resulting action. ## GET GET requests are typically used for fetching data (like data for a particular driver). ## POST POST requests are typically used for creating or updating a record (like adding new tags to the system). With that being said, a few of our POST requests can be used for fetching data (like current location data of your fleet). ## PUT PUT requests are typically used for updating an existing record (like updating all devices associated with a particular tag). ## PATCH PATCH requests are typically used for modifying an existing record (like modifying a few devices associated with a particular tag). ## DELETE DELETE requests are used for deleting a record (like deleting a tag from the system). # Response Codes All API requests will respond with appropriate [HTTP status code](https://en.wikipedia.org/wiki/List_of_HTTP_status_codes). Your API client should handle each response class differently. ## 2XX These are successful responses and indicate that the API request returned the expected response. ## 4XX These indicate that there was a problem with the request like a missing parameter or invalid values. Check the response for specific [error details](#section/Error-Responses). Requests that respond with a 4XX status code, should be modified before retrying. ## 5XX These indicate server errors when the server is unreachable or is misconfigured. In this case, you should retry the API request after some delay. # Error Responses In case of a 4XX status code, the body of the response will contain information to briefly explain the error reported. To help debugging the error, you can refer to the following table for understanding the error message. | Status Code | Message | Description | |-------------|----------------|-------------------------------------------------------------------| | 401 | Invalid token | The API token is invalid and could not be authenticated. Please refer to the [authentication section](#section/Authentication). | | 404 | Page not found | The API endpoint being accessed is invalid. | | 400 | Bad request | Default response for an invalid request. Please check the request to make sure it follows the format specified in the documentation. | # Versioning All our APIs are versioned. Our current API version is `v1` and we are continuously working on improving it further and provide additional endpoints. If we intend to make breaking changes to an API which either changes the response format or request parameter, we will increment the version. Thus, you can use our current API version worry free. # FAQs Check out our [responses to FAQs here](https://kb.samsara.com/hc/en-us/sections/360000538054-APIs). Don’t see an answer to your question? Reach out to us on [support@samsara.com](mailto:support@samsara.com). * * OpenAPI spec version: 1.0.0 * * NOTE: This class is auto generated by OpenAPI-Generator 4.0.0-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ #include "Inline_object_4.h" namespace org { namespace openapitools { namespace client { namespace model { Inline_object_4::Inline_object_4() { m_Reactivate = false; } Inline_object_4::~Inline_object_4() { } void Inline_object_4::validate() { // TODO: implement validation } web::json::value Inline_object_4::toJson() const { web::json::value val = web::json::value::object(); val[utility::conversions::to_string_t("reactivate")] = ModelBase::toJson(m_Reactivate); return val; } void Inline_object_4::fromJson(const web::json::value& val) { setReactivate(ModelBase::boolFromJson(val.at(utility::conversions::to_string_t("reactivate")))); } void Inline_object_4::toMultipart(std::shared_ptr<MultipartFormData> multipart, const utility::string_t& prefix) const { utility::string_t namePrefix = prefix; if(namePrefix.size() > 0 && namePrefix.substr(namePrefix.size() - 1) != utility::conversions::to_string_t(".")) { namePrefix += utility::conversions::to_string_t("."); } multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t("reactivate"), m_Reactivate)); } void Inline_object_4::fromMultiPart(std::shared_ptr<MultipartFormData> multipart, const utility::string_t& prefix) { utility::string_t namePrefix = prefix; if(namePrefix.size() > 0 && namePrefix.substr(namePrefix.size() - 1) != utility::conversions::to_string_t(".")) { namePrefix += utility::conversions::to_string_t("."); } setReactivate(ModelBase::boolFromHttpContent(multipart->getContent(utility::conversions::to_string_t("reactivate")))); } bool Inline_object_4::isReactivate() const { return m_Reactivate; } void Inline_object_4::setReactivate(bool value) { m_Reactivate = value; } } } } }
[ "greg@samsara.com" ]
greg@samsara.com
c62cf54977f7d7080016934d0a8eed1698101f81
ab9301143be53a6bd407f84c98356f5963c9f9be
/gr-demod_8/lib/qa_demod_8.h
a84e0b48a0b16ef9ee665bc9e7a63fcd6c79ceff
[]
no_license
Agrim9/FHSS_GNUradio
69511752207b28091c93c4d0750869b5aba8f0bf
b303a88cb62257c6167aa705e3f19d6eb60713c5
refs/heads/master
2021-01-11T08:00:11.419803
2016-12-31T12:24:37
2016-12-31T12:24:37
72,123,437
29
19
null
null
null
null
UTF-8
C++
false
false
1,163
h
/* -*- c++ -*- */ /* * Copyright 2012 Free Software Foundation, Inc. * * This file is part of GNU Radio * * GNU Radio 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 3, or (at your option) * any later version. * * GNU Radio 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 GNU Radio; see the file COPYING. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, * Boston, MA 02110-1301, USA. */ #ifndef _QA_DEMOD_8_H_ #define _QA_DEMOD_8_H_ #include <gnuradio/attributes.h> #include <cppunit/TestSuite.h> //! collect all the tests for the gr-filter directory class __GR_ATTR_EXPORT qa_demod_8 { public: //! return suite of tests for all of gr-filter directory static CppUnit::TestSuite *suite(); }; #endif /* _QA_DEMOD_8_H_ */
[ "agrim9gupta@gmail.com" ]
agrim9gupta@gmail.com
7b2ae738b1eb8fd925422f3ed00f256c57917871
8f63c9342469fc4055e76d85116a8188dd7e10b3
/CefSharp/JsTask.cpp
9c160b7887d8c93cdbefac904855cff473e00679
[ "BSD-3-Clause" ]
permissive
tenbits/CefSharp
f9391a584e1cedb0ee1b4ea12218493aaf0ce338
14e184d3f21e6a747c4bb7a016bfbe638d16e30c
refs/heads/master
2021-01-15T21:49:44.450599
2011-06-26T09:34:43
2011-06-26T09:34:43
2,000,629
1
0
null
null
null
null
UTF-8
C++
false
false
449
cpp
#include "stdafx.h" #include "JsTask.h" #include "Utils.h" namespace CefSharp { void JsTask::HandleSuccess(CefRefPtr<CefV8Value> result) { Object^ obj = convertFromCef(result); if(obj != nullptr) { _browser->SetJsResult(obj->ToString()); } else { _browser->SetJsResult(""); } } void JsTask::HandleError() { _browser->SetJsError(); } }
[ "tom.rathbone@gmail.com" ]
tom.rathbone@gmail.com
7edb301eb3b7779a15f3e4d5c5e8c863186371fc
e95bc36d974257613aca5c54ede8cae688071c62
/Anul 1/POO/QuizGame/QuizGame/QuestionCreationDialog.h
2c66825189597bf33aad288ed4d4e2e4e2baa377
[]
no_license
PredaMihaiDragos/Facultate
7891a5f07a372e0e06262b517956318a26fcdab4
f4080e537dee781200b129a4869151796f889ce1
refs/heads/master
2022-12-22T02:02:09.485931
2021-04-23T06:19:35
2021-04-23T06:19:35
249,676,290
0
0
null
null
null
null
UTF-8
C++
false
false
671
h
#pragma once #include <wx/wxprec.h> #ifndef WX_PRECOMP #include <wx/wx.h> #endif #include <wx/display.h> #include <wx/dialog.h> #include "Question.h" #include "style.h" class QuestionCreationDialog : public wxDialog { public: QuestionCreationDialog(wxWindow* parent); virtual ~QuestionCreationDialog() {}; protected: void SetSubmitPos(const wxPoint& pos) { submitQuestion->SetPosition(pos); } private: QuestionCreationDialog(const QuestionCreationDialog& oth) = delete; QuestionCreationDialog& operator=(const QuestionCreationDialog&) = delete; wxButton* submitQuestion; virtual void OnSubmitQuestion(wxCommandEvent& event) = 0; wxDECLARE_EVENT_TABLE(); };
[ "48451420+PredaMihaiDragos@users.noreply.github.com" ]
48451420+PredaMihaiDragos@users.noreply.github.com
a53578e227bd4bba0033bfea95a0a491f8382679
b401b6b804827c1cd017251130e506542d8eb554
/src/daemon/rpc_command_executor.cpp
c11dd7085b766083599b675f90481c92fe079281
[ "LicenseRef-scancode-unknown-license-reference", "BSD-3-Clause" ]
permissive
Drewsy0613/monerov
133faa7d6c66171d2b76ad9dc9823c07df1e80d0
2c78dc01aae6cbef447faa25a06371338b72aef8
refs/heads/master
2020-04-14T06:42:17.115523
2018-12-08T13:25:22
2018-12-08T13:25:22
null
0
0
null
null
null
null
UTF-8
C++
false
false
60,712
cpp
// Copyright (c) 2014-2018, The Monero 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. // // Parts of this file are originally copyright (c) 2012-2013 The Cryptonote developers #include "string_tools.h" #include "common/password.h" #include "common/scoped_message_writer.h" #include "daemon/rpc_command_executor.h" #include "rpc/core_rpc_server_commands_defs.h" #include "cryptonote_core/cryptonote_core.h" #include "cryptonote_basic/hardfork.h" #include <boost/format.hpp> #include <ctime> #include <string> #undef MONERO_DEFAULT_LOG_CATEGORY #define MONERO_DEFAULT_LOG_CATEGORY "daemon" namespace daemonize { namespace { void print_peer(std::string const & prefix, cryptonote::peer const & peer) { time_t now; time(&now); time_t last_seen = static_cast<time_t>(peer.last_seen); std::string id_str; std::string port_str; std::string elapsed = epee::misc_utils::get_time_interval_string(now - last_seen); std::string ip_str = epee::string_tools::get_ip_string_from_int32(peer.ip); std::stringstream peer_id_str; peer_id_str << std::hex << std::setw(16) << peer.id; peer_id_str >> id_str; epee::string_tools::xtype_to_string(peer.port, port_str); std::string addr_str = ip_str + ":" + port_str; tools::msg_writer() << boost::format("%-10s %-25s %-25s %s") % prefix % id_str % addr_str % elapsed; } void print_block_header(cryptonote::block_header_response const & header) { tools::success_msg_writer() << "timestamp: " << boost::lexical_cast<std::string>(header.timestamp) << std::endl << "previous hash: " << header.prev_hash << std::endl << "nonce: " << boost::lexical_cast<std::string>(header.nonce) << std::endl << "is orphan: " << header.orphan_status << std::endl << "height: " << boost::lexical_cast<std::string>(header.height) << std::endl << "depth: " << boost::lexical_cast<std::string>(header.depth) << std::endl << "hash: " << header.hash << std::endl << "difficulty: " << boost::lexical_cast<std::string>(header.difficulty) << std::endl << "reward: " << boost::lexical_cast<std::string>(header.reward); << "block size: " << header.block_size << std::endl << "num txes: " << header.num_txes << std::endl } std::string get_human_time_ago(time_t t, time_t now) { if (t == now) return "now"; time_t dt = t > now ? t - now : now - t; std::string s; if (dt < 90) s = boost::lexical_cast<std::string>(dt) + " seconds"; else if (dt < 90 * 60) s = boost::lexical_cast<std::string>(dt/60) + " minutes"; else if (dt < 36 * 3600) s = boost::lexical_cast<std::string>(dt/3600) + " hours"; else s = boost::lexical_cast<std::string>(dt/(3600*24)) + " days"; return s + " " + (t > now ? "in the future" : "ago"); } std::string get_time_hms(time_t t) { unsigned int hours, minutes, seconds; char buffer[24]; hours = t / 3600; t %= 3600; minutes = t / 60; t %= 60; seconds = t; snprintf(buffer, sizeof(buffer), "%02u:%02u:%02u", hours, minutes, seconds); return std::string(buffer); } std::string make_error(const std::string &base, const std::string &status) { if (status == CORE_RPC_STATUS_OK) return base; return base + " -- " + status; } } t_rpc_command_executor::t_rpc_command_executor( uint32_t ip , uint16_t port , const boost::optional<tools::login>& login , bool is_rpc , cryptonote::core_rpc_server* rpc_server ) : m_rpc_client(NULL), m_rpc_server(rpc_server) { if (is_rpc) { boost::optional<epee::net_utils::http::login> http_login{}; if (login) http_login.emplace(login->username, login->password.password()); m_rpc_client = new tools::t_rpc_client(ip, port, std::move(http_login)); } else { if (rpc_server == NULL) { throw std::runtime_error("If not calling commands via RPC, rpc_server pointer must be non-null"); } } m_is_rpc = is_rpc; } t_rpc_command_executor::~t_rpc_command_executor() { if (m_rpc_client != NULL) { delete m_rpc_client; } } bool t_rpc_command_executor::print_peer_list() { cryptonote::COMMAND_RPC_GET_PEER_LIST::request req; cryptonote::COMMAND_RPC_GET_PEER_LIST::response res; std::string failure_message = "Couldn't retrieve peer list"; if (m_is_rpc) { if (!m_rpc_client->rpc_request(req, res, "/get_peer_list", failure_message.c_str())) { return false; } } else { if (!m_rpc_server->on_get_peer_list(req, res) || res.status != CORE_RPC_STATUS_OK) { tools::fail_msg_writer() << failure_message; return false; } } for (auto & peer : res.white_list) { print_peer("white", peer); } for (auto & peer : res.gray_list) { print_peer("gray", peer); } return true; } bool t_rpc_command_executor::print_peer_list_stats() { cryptonote::COMMAND_RPC_GET_PEER_LIST::request req; cryptonote::COMMAND_RPC_GET_PEER_LIST::response res; std::string failure_message = "Couldn't retrieve peer list"; if (m_is_rpc) { if (!m_rpc_client->rpc_request(req, res, "/get_peer_list", failure_message.c_str())) { return false; } } else { if (!m_rpc_server->on_get_peer_list(req, res) || res.status != CORE_RPC_STATUS_OK) { tools::fail_msg_writer() << failure_message; return false; } } tools::msg_writer() << "White list size: " << res.white_list.size() << "/" << P2P_LOCAL_WHITE_PEERLIST_LIMIT << " (" << res.white_list.size() * 100.0 / P2P_LOCAL_WHITE_PEERLIST_LIMIT << "%)" << std::endl << "Gray list size: " << res.gray_list.size() << "/" << P2P_LOCAL_GRAY_PEERLIST_LIMIT << " (" << res.gray_list.size() * 100.0 / P2P_LOCAL_GRAY_PEERLIST_LIMIT << "%)"; return true; } bool t_rpc_command_executor::save_blockchain() { cryptonote::COMMAND_RPC_SAVE_BC::request req; cryptonote::COMMAND_RPC_SAVE_BC::response res; std::string fail_message = "Couldn't save blockchain"; if (m_is_rpc) { if (!m_rpc_client->rpc_request(req, res, "/save_bc", fail_message.c_str())) { return true; } } else { if (!m_rpc_server->on_save_bc(req, res) || res.status != CORE_RPC_STATUS_OK) { tools::fail_msg_writer() << make_error(fail_message, res.status); return true; } } tools::success_msg_writer() << "Blockchain saved"; return true; } bool t_rpc_command_executor::show_hash_rate() { cryptonote::COMMAND_RPC_SET_LOG_HASH_RATE::request req; cryptonote::COMMAND_RPC_SET_LOG_HASH_RATE::response res; req.visible = true; std::string fail_message = "Unsuccessful"; if (m_is_rpc) { if (!m_rpc_client->rpc_request(req, res, "/set_log_hash_rate", fail_message.c_str())) { return true; } } else { if (!m_rpc_server->on_set_log_hash_rate(req, res) || res.status != CORE_RPC_STATUS_OK) { tools::fail_msg_writer() << make_error(fail_message, res.status); } } tools::success_msg_writer() << "Hash rate logging is on"; return true; } bool t_rpc_command_executor::hide_hash_rate() { cryptonote::COMMAND_RPC_SET_LOG_HASH_RATE::request req; cryptonote::COMMAND_RPC_SET_LOG_HASH_RATE::response res; req.visible = false; std::string fail_message = "Unsuccessful"; if (m_is_rpc) { if (!m_rpc_client->rpc_request(req, res, "/set_log_hash_rate", fail_message.c_str())) { return true; } } else { if (!m_rpc_server->on_set_log_hash_rate(req, res) || res.status != CORE_RPC_STATUS_OK) { tools::fail_msg_writer() << make_error(fail_message, res.status); return true; } } tools::success_msg_writer() << "Hash rate logging is off"; return true; } bool t_rpc_command_executor::show_difficulty() { cryptonote::COMMAND_RPC_GET_INFO::request req; cryptonote::COMMAND_RPC_GET_INFO::response res; std::string fail_message = "Problem fetching info"; if (m_is_rpc) { if (!m_rpc_client->rpc_request(req, res, "/getinfo", fail_message.c_str())) { return true; } } else { if (!m_rpc_server->on_get_info(req, res) || res.status != CORE_RPC_STATUS_OK) { tools::fail_msg_writer() << make_error(fail_message.c_str(), res.status); return true; } } tools::success_msg_writer() << "BH: " << res.height << ", TH: " << res.top_block_hash << ", DIFF: " << res.difficulty << ", HR: " << res.difficulty / res.target << " H/s"; return true; } static std::string get_mining_speed(uint64_t hr) { if (hr>1e9) return (boost::format("%.2f GH/s") % (hr/1e9)).str(); if (hr>1e6) return (boost::format("%.2f MH/s") % (hr/1e6)).str(); if (hr>1e3) return (boost::format("%.2f kH/s") % (hr/1e3)).str(); return (boost::format("%.0f H/s") % hr).str(); } static std::string get_fork_extra_info(uint64_t t, uint64_t now, uint64_t block_time) { uint64_t blocks_per_day = 86400 / block_time; if (t == now) return " (forking now)"; if (t > now) { uint64_t dblocks = t - now; if (dblocks <= 30) return (boost::format(" (next fork in %u blocks)") % (unsigned)dblocks).str(); if (dblocks <= blocks_per_day / 2) return (boost::format(" (next fork in %.1f hours)") % (dblocks / (float)(blocks_per_day / 24))).str(); if (dblocks <= blocks_per_day * 30) return (boost::format(" (next fork in %.1f days)") % (dblocks / (float)blocks_per_day)).str(); return ""; } return ""; } static float get_sync_percentage(uint64_t height, uint64_t target_height) { target_height = target_height ? target_height < height ? height : target_height : height; float pc = 100.0f * height / target_height; if (height < target_height && pc > 99.9f) return 99.9f; // to avoid 100% when not fully synced return pc; } static float get_sync_percentage(const cryptonote::COMMAND_RPC_GET_INFO::response &ires) { return get_sync_percentage(ires.height, ires.target_height); } bool t_rpc_command_executor::show_status() { cryptonote::COMMAND_RPC_GET_INFO::request ireq; cryptonote::COMMAND_RPC_GET_INFO::response ires; cryptonote::COMMAND_RPC_HARD_FORK_INFO::request hfreq; cryptonote::COMMAND_RPC_HARD_FORK_INFO::response hfres; cryptonote::COMMAND_RPC_MINING_STATUS::request mreq; cryptonote::COMMAND_RPC_MINING_STATUS::response mres; epee::json_rpc::error error_resp; bool has_mining_info = true; std::string fail_message = "Problem fetching info"; hfreq.version = 0; bool mining_busy = false; if (m_is_rpc) { if (!m_rpc_client->rpc_request(ireq, ires, "/getinfo", fail_message.c_str())) { return true; } if (!m_rpc_client->json_rpc_request(hfreq, hfres, "hard_fork_info", fail_message.c_str())) { return true; } // mining info is only available non unrestricted RPC mode has_mining_info = m_rpc_client->rpc_request(mreq, mres, "/mining_status", fail_message.c_str()); } else { if (!m_rpc_server->on_get_info(ireq, ires) || ires.status != CORE_RPC_STATUS_OK) { tools::fail_msg_writer() << make_error(fail_message, ires.status); return true; } if (!m_rpc_server->on_hard_fork_info(hfreq, hfres, error_resp) || hfres.status != CORE_RPC_STATUS_OK) { tools::fail_msg_writer() << make_error(fail_message, hfres.status); return true; } if (!m_rpc_server->on_mining_status(mreq, mres)) { tools::fail_msg_writer() << fail_message.c_str(); return true; } if (mres.status == CORE_RPC_STATUS_BUSY) { mining_busy = true; } else if (mres.status != CORE_RPC_STATUS_OK) { tools::fail_msg_writer() << make_error(fail_message, mres.status); return true; } } std::time_t uptime = std::time(nullptr) - ires.start_time; uint64_t net_height = ires.target_height > ires.height ? ires.target_height : ires.height; std::string bootstrap_msg; if (ires.was_bootstrap_ever_used) { bootstrap_msg = ", bootstrapping from " + ires.bootstrap_daemon_address; if (ires.untrusted) { bootstrap_msg += (boost::format(", local height: %llu (%.1f%%)") % ires.height_without_bootstrap % get_sync_percentage(ires.height_without_bootstrap, net_height)).str(); } else { bootstrap_msg += " was used before"; } } tools::success_msg_writer() << boost::format("Height: %llu/%llu (%.1f%%) on %s%s, %s, net hash %s, v%u%s, %s, %u(out)+%u(in) connections, uptime %ud %uh %um %us") % (unsigned long long)ires.height % (unsigned long long)net_height % get_sync_percentage(ires) % (ires.testnet ? "testnet" : ires.stagenet ? "stagenet" : "mainnet") % bootstrap_msg % (!has_mining_info ? "mining info unavailable" : mining_busy ? "syncing" : mres.active ? ( ( mres.is_background_mining_enabled ? "smart " : "" ) + std::string("mining at ") + get_mining_speed(mres.speed) ) : "not mining") % get_mining_speed(ires.difficulty / ires.target) % (unsigned)hfres.version % get_fork_extra_info(hfres.earliest_height, net_height, ires.target) % (hfres.state == cryptonote::HardFork::Ready ? "up to date" : hfres.state == cryptonote::HardFork::UpdateNeeded ? "update needed" : "out of date, likely forked") % (unsigned)ires.outgoing_connections_count % (unsigned)ires.incoming_connections_count % (unsigned int)floor(uptime / 60.0 / 60.0 / 24.0) % (unsigned int)floor(fmod((uptime / 60.0 / 60.0), 24.0)) % (unsigned int)floor(fmod((uptime / 60.0), 60.0)) % (unsigned int)fmod(uptime, 60.0) ; return true; } bool t_rpc_command_executor::print_connections() { cryptonote::COMMAND_RPC_GET_CONNECTIONS::request req; cryptonote::COMMAND_RPC_GET_CONNECTIONS::response res; epee::json_rpc::error error_resp; std::string fail_message = "Unsuccessful"; if (m_is_rpc) { if (!m_rpc_client->json_rpc_request(req, res, "get_connections", fail_message.c_str())) { return true; } } else { if (!m_rpc_server->on_get_connections(req, res, error_resp) || res.status != CORE_RPC_STATUS_OK) { tools::fail_msg_writer() << make_error(fail_message, res.status); return true; } } tools::msg_writer() << std::setw(30) << std::left << "Remote Host" << std::setw(20) << "Peer id" << std::setw(20) << "Support Flags" << std::setw(30) << "Recv/Sent (inactive,sec)" << std::setw(25) << "State" << std::setw(20) << "Livetime(sec)" << std::setw(12) << "Down (kB/s)" << std::setw(14) << "Down(now)" << std::setw(10) << "Up (kB/s)" << std::setw(13) << "Up(now)" << std::endl; for (auto & info : res.connections) { std::string address = info.incoming ? "INC " : "OUT "; address += info.ip + ":" + info.port; //std::string in_out = info.incoming ? "INC " : "OUT "; tools::msg_writer() //<< std::setw(30) << std::left << in_out << std::setw(30) << std::left << address << std::setw(20) << epee::string_tools::pad_string(info.peer_id, 16, '0', true) << std::setw(20) << info.support_flags << std::setw(30) << std::to_string(info.recv_count) + "(" + std::to_string(info.recv_idle_time) + ")/" + std::to_string(info.send_count) + "(" + std::to_string(info.send_idle_time) + ")" << std::setw(25) << info.state << std::setw(20) << info.live_time << std::setw(12) << info.avg_download << std::setw(14) << info.current_download << std::setw(10) << info.avg_upload << std::setw(13) << info.current_upload << std::left << (info.localhost ? "[LOCALHOST]" : "") << std::left << (info.local_ip ? "[LAN]" : ""); //tools::msg_writer() << boost::format("%-25s peer_id: %-25s %s") % address % info.peer_id % in_out; } return true; } bool t_rpc_command_executor::print_blockchain_info(uint64_t start_block_index, uint64_t end_block_index) { cryptonote::COMMAND_RPC_GET_BLOCK_HEADERS_RANGE::request req; cryptonote::COMMAND_RPC_GET_BLOCK_HEADERS_RANGE::response res; epee::json_rpc::error error_resp; req.start_height = start_block_index; req.end_height = end_block_index; std::string fail_message = "Unsuccessful"; if (m_is_rpc) { if (!m_rpc_client->json_rpc_request(req, res, "getblockheadersrange", fail_message.c_str())) { return true; } } else { if (!m_rpc_server->on_get_block_headers_range(req, res, error_resp) || res.status != CORE_RPC_STATUS_OK) { tools::fail_msg_writer() << make_error(fail_message, res.status); return true; } } bool first = true; for (auto & header : res.headers) { if (!first) std::cout << std::endl; std::cout << "height: " << header.height << ", timestamp: " << header.timestamp << ", difficulty: " << header.difficulty << ", size: " << header.block_size << ", transactions: " << header.num_txes << std::endl << "major version: " << (unsigned)header.major_version << ", minor version: " << (unsigned)header.minor_version << std::endl << "block id: " << header.hash << ", previous block id: " << header.prev_hash << std::endl << "difficulty: " << header.difficulty << ", nonce " << header.nonce << ", reward " << cryptonote::print_money(header.reward) << std::endl; first = false; } return true; } bool t_rpc_command_executor::set_log_level(int8_t level) { cryptonote::COMMAND_RPC_SET_LOG_LEVEL::request req; cryptonote::COMMAND_RPC_SET_LOG_LEVEL::response res; req.level = level; std::string fail_message = "Unsuccessful"; if (m_is_rpc) { if (!m_rpc_client->rpc_request(req, res, "/set_log_level", fail_message.c_str())) { return true; } } else { if (!m_rpc_server->on_set_log_level(req, res) || res.status != CORE_RPC_STATUS_OK) { tools::fail_msg_writer() << make_error(fail_message, res.status); return true; } } tools::success_msg_writer() << "Log level is now " << std::to_string(level); return true; } bool t_rpc_command_executor::set_log_categories(const std::string &categories) { cryptonote::COMMAND_RPC_SET_LOG_CATEGORIES::request req; cryptonote::COMMAND_RPC_SET_LOG_CATEGORIES::response res; req.categories = categories; std::string fail_message = "Unsuccessful"; if (m_is_rpc) { if (!m_rpc_client->rpc_request(req, res, "/set_log_categories", fail_message.c_str())) { return true; } } else { if (!m_rpc_server->on_set_log_categories(req, res) || res.status != CORE_RPC_STATUS_OK) { tools::fail_msg_writer() << make_error(fail_message, res.status); return true; } } tools::success_msg_writer() << "Log categories are now " << res.categories; return true; } bool t_rpc_command_executor::print_height() { cryptonote::COMMAND_RPC_GET_HEIGHT::request req; cryptonote::COMMAND_RPC_GET_HEIGHT::response res; std::string fail_message = "Unsuccessful"; if (m_is_rpc) { if (!m_rpc_client->rpc_request(req, res, "/getheight", fail_message.c_str())) { return true; } } else { if (!m_rpc_server->on_get_height(req, res) || res.status != CORE_RPC_STATUS_OK) { tools::fail_msg_writer() << make_error(fail_message, res.status); return true; } } tools::success_msg_writer() << boost::lexical_cast<std::string>(res.height); return true; } bool t_rpc_command_executor::print_block_by_hash(crypto::hash block_hash) { cryptonote::COMMAND_RPC_GET_BLOCK::request req; cryptonote::COMMAND_RPC_GET_BLOCK::response res; epee::json_rpc::error error_resp; req.hash = epee::string_tools::pod_to_hex(block_hash); std::string fail_message = "Unsuccessful"; if (m_is_rpc) { if (!m_rpc_client->json_rpc_request(req, res, "getblock", fail_message.c_str())) { return true; } } else { if (!m_rpc_server->on_get_block(req, res, error_resp) || res.status != CORE_RPC_STATUS_OK) { tools::fail_msg_writer() << make_error(fail_message, res.status); return true; } } print_block_header(res.block_header); tools::success_msg_writer() << res.json << ENDL; return true; } bool t_rpc_command_executor::print_block_by_height(uint64_t height) { cryptonote::COMMAND_RPC_GET_BLOCK::request req; cryptonote::COMMAND_RPC_GET_BLOCK::response res; epee::json_rpc::error error_resp; req.height = height; std::string fail_message = "Unsuccessful"; if (m_is_rpc) { if (!m_rpc_client->json_rpc_request(req, res, "getblock", fail_message.c_str())) { return true; } } else { if (!m_rpc_server->on_get_block(req, res, error_resp) || res.status != CORE_RPC_STATUS_OK) { tools::fail_msg_writer() << make_error(fail_message, res.status); return true; } } print_block_header(res.block_header); tools::success_msg_writer() << res.json << ENDL; return true; } bool t_rpc_command_executor::print_transaction(crypto::hash transaction_hash, bool include_hex, bool include_json) { cryptonote::COMMAND_RPC_GET_TRANSACTIONS::request req; cryptonote::COMMAND_RPC_GET_TRANSACTIONS::response res; std::string fail_message = "Problem fetching transaction"; req.txs_hashes.push_back(epee::string_tools::pod_to_hex(transaction_hash)); req.decode_as_json = false; if (m_is_rpc) { if (!m_rpc_client->rpc_request(req, res, "/gettransactions", fail_message.c_str())) { return true; } } else { if (!m_rpc_server->on_get_transactions(req, res) || res.status != CORE_RPC_STATUS_OK) { tools::fail_msg_writer() << make_error(fail_message, res.status); return true; } } if (1 == res.txs.size() || 1 == res.txs_as_hex.size()) { if (1 == res.txs.size()) { // only available for new style answers if (res.txs.front().in_pool) tools::success_msg_writer() << "Found in pool"; else tools::success_msg_writer() << "Found in blockchain at height " << res.txs.front().block_height; } const std::string &as_hex = (1 == res.txs.size()) ? res.txs.front().as_hex : res.txs_as_hex.front(); // Print raw hex if requested if (include_hex) tools::success_msg_writer() << as_hex << std::endl; // Print json if requested if (include_json) { crypto::hash tx_hash, tx_prefix_hash; cryptonote::transaction tx; cryptonote::blobdata blob; if (!string_tools::parse_hexstr_to_binbuff(as_hex, blob)) { tools::fail_msg_writer() << "Failed to parse tx to get json format"; } else if (!cryptonote::parse_and_validate_tx_from_blob(blob, tx, tx_hash, tx_prefix_hash)) { tools::fail_msg_writer() << "Failed to parse tx blob to get json format"; } else { tools::success_msg_writer() << cryptonote::obj_to_json_str(tx) << std::endl; } } } else { tools::fail_msg_writer() << "Transaction wasn't found: " << transaction_hash << std::endl; } return true; } bool t_rpc_command_executor::is_key_image_spent(const crypto::key_image &ki) { cryptonote::COMMAND_RPC_IS_KEY_IMAGE_SPENT::request req; cryptonote::COMMAND_RPC_IS_KEY_IMAGE_SPENT::response res; std::string fail_message = "Problem checking key image"; req.key_images.push_back(epee::string_tools::pod_to_hex(ki)); if (m_is_rpc) { if (!m_rpc_client->rpc_request(req, res, "/is_key_image_spent", fail_message.c_str())) { return true; } } else { if (!m_rpc_server->on_is_key_image_spent(req, res) || res.status != CORE_RPC_STATUS_OK) { tools::fail_msg_writer() << make_error(fail_message, res.status); return true; } } if (1 == res.spent_status.size()) { // first as hex tools::success_msg_writer() << ki << ": " << (res.spent_status.front() ? "spent" : "unspent") << (res.spent_status.front() == cryptonote::COMMAND_RPC_IS_KEY_IMAGE_SPENT::SPENT_IN_POOL ? " (in pool)" : ""); } else { tools::fail_msg_writer() << "key image status could not be determined" << std::endl; } return true; } bool t_rpc_command_executor::print_transaction_pool_long() { cryptonote::COMMAND_RPC_GET_TRANSACTION_POOL::request req; cryptonote::COMMAND_RPC_GET_TRANSACTION_POOL::response res; std::string fail_message = "Problem fetching transaction pool"; if (m_is_rpc) { if (!m_rpc_client->rpc_request(req, res, "/get_transaction_pool", fail_message.c_str())) { return true; } } else { if (!m_rpc_server->on_get_transaction_pool(req, res, false) || res.status != CORE_RPC_STATUS_OK) { tools::fail_msg_writer() << make_error(fail_message, res.status); return true; } } if (res.transactions.empty() && res.spent_key_images.empty()) { tools::msg_writer() << "Pool is empty" << std::endl; } if (! res.transactions.empty()) { const time_t now = time(NULL); tools::msg_writer() << "Transactions: "; for (auto & tx_info : res.transactions) { tools::msg_writer() << "id: " << tx_info.id_hash << std::endl << tx_info.tx_json << std::endl << "blob_size: " << tx_info.blob_size << std::endl << "fee: " << cryptonote::print_money(tx_info.fee) << std::endl << "fee/byte: " << cryptonote::print_money(tx_info.fee / (double)tx_info.blob_size) << std::endl << "receive_time: " << tx_info.receive_time << " (" << get_human_time_ago(tx_info.receive_time, now) << ")" << std::endl << "relayed: " << [&](const cryptonote::tx_info &tx_info)->std::string { if (!tx_info.relayed) return "no"; return boost::lexical_cast<std::string>(tx_info.last_relayed_time) + " (" + get_human_time_ago(tx_info.last_relayed_time, now) + ")"; } (tx_info) << std::endl << "do_not_relay: " << (tx_info.do_not_relay ? 'T' : 'F') << std::endl << "kept_by_block: " << (tx_info.kept_by_block ? 'T' : 'F') << std::endl << "double_spend_seen: " << (tx_info.double_spend_seen ? 'T' : 'F') << std::endl << "max_used_block_height: " << tx_info.max_used_block_height << std::endl << "max_used_block_id: " << tx_info.max_used_block_id_hash << std::endl << "last_failed_height: " << tx_info.last_failed_height << std::endl << "last_failed_id: " << tx_info.last_failed_id_hash << std::endl; } if (res.spent_key_images.empty()) { tools::msg_writer() << "WARNING: Inconsistent pool state - no spent key images"; } } if (! res.spent_key_images.empty()) { tools::msg_writer() << ""; // one newline tools::msg_writer() << "Spent key images: "; for (const cryptonote::spent_key_image_info& kinfo : res.spent_key_images) { tools::msg_writer() << "key image: " << kinfo.id_hash; if (kinfo.txs_hashes.size() == 1) { tools::msg_writer() << " tx: " << kinfo.txs_hashes[0]; } else if (kinfo.txs_hashes.size() == 0) { tools::msg_writer() << " WARNING: spent key image has no txs associated"; } else { tools::msg_writer() << " NOTE: key image for multiple txs: " << kinfo.txs_hashes.size(); for (const std::string& tx_id : kinfo.txs_hashes) { tools::msg_writer() << " tx: " << tx_id; } } } if (res.transactions.empty()) { tools::msg_writer() << "WARNING: Inconsistent pool state - no transactions"; } } return true; } bool t_rpc_command_executor::print_transaction_pool_short() { cryptonote::COMMAND_RPC_GET_TRANSACTION_POOL::request req; cryptonote::COMMAND_RPC_GET_TRANSACTION_POOL::response res; std::string fail_message = "Problem fetching transaction pool"; if (m_is_rpc) { if (!m_rpc_client->rpc_request(req, res, "/get_transaction_pool", fail_message.c_str())) { return true; } } else { if (!m_rpc_server->on_get_transaction_pool(req, res, false) || res.status != CORE_RPC_STATUS_OK) { tools::fail_msg_writer() << make_error(fail_message, res.status); return true; } } if (res.transactions.empty()) { tools::msg_writer() << "Pool is empty" << std::endl; } else { const time_t now = time(NULL); for (auto & tx_info : res.transactions) { tools::msg_writer() << "id: " << tx_info.id_hash << std::endl << "blob_size: " << tx_info.blob_size << std::endl << "fee: " << cryptonote::print_money(tx_info.fee) << std::endl << "fee/byte: " << cryptonote::print_money(tx_info.fee / (double)tx_info.blob_size) << std::endl << "receive_time: " << tx_info.receive_time << " (" << get_human_time_ago(tx_info.receive_time, now) << ")" << std::endl << "relayed: " << [&](const cryptonote::tx_info &tx_info)->std::string { if (!tx_info.relayed) return "no"; return boost::lexical_cast<std::string>(tx_info.last_relayed_time) + " (" + get_human_time_ago(tx_info.last_relayed_time, now) + ")"; } (tx_info) << std::endl << "do_not_relay: " << (tx_info.do_not_relay ? 'T' : 'F') << std::endl << "kept_by_block: " << (tx_info.kept_by_block ? 'T' : 'F') << std::endl << "double_spend_seen: " << (tx_info.double_spend_seen ? 'T' : 'F') << std::endl << "max_used_block_height: " << tx_info.max_used_block_height << std::endl << "max_used_block_id: " << tx_info.max_used_block_id_hash << std::endl << "last_failed_height: " << tx_info.last_failed_height << std::endl << "last_failed_id: " << tx_info.last_failed_id_hash << std::endl; } } return true; } bool t_rpc_command_executor::print_transaction_pool_stats() { cryptonote::COMMAND_RPC_GET_TRANSACTION_POOL_STATS::request req; cryptonote::COMMAND_RPC_GET_TRANSACTION_POOL_STATS::response res; cryptonote::COMMAND_RPC_GET_INFO::request ireq; cryptonote::COMMAND_RPC_GET_INFO::response ires; std::string fail_message = "Problem fetching transaction pool stats"; if (m_is_rpc) { if (!m_rpc_client->rpc_request(req, res, "/get_transaction_pool_stats", fail_message.c_str())) { return true; } if (!m_rpc_client->rpc_request(ireq, ires, "/getinfo", fail_message.c_str())) { return true; } } else { memset(&res.pool_stats, 0, sizeof(res.pool_stats)); if (!m_rpc_server->on_get_transaction_pool_stats(req, res, false) || res.status != CORE_RPC_STATUS_OK) { tools::fail_msg_writer() << make_error(fail_message, res.status); return true; } if (!m_rpc_server->on_get_info(ireq, ires) || ires.status != CORE_RPC_STATUS_OK) { tools::fail_msg_writer() << make_error(fail_message, ires.status); return true; } } size_t n_transactions = res.pool_stats.txs_total; const uint64_t now = time(NULL); size_t avg_bytes = n_transactions ? res.pool_stats.bytes_total / n_transactions : 0; std::string backlog_message; const uint64_t full_reward_zone = ires.block_size_limit / 2; if (res.pool_stats.bytes_total <= full_reward_zone) { backlog_message = "no backlog"; } else { uint64_t backlog = (res.pool_stats.bytes_total + full_reward_zone - 1) / full_reward_zone; backlog_message = (boost::format("estimated %u block (%u minutes) backlog") % backlog % (backlog * DIFFICULTY_TARGET_V2 / 60)).str(); } tools::msg_writer() << n_transactions << " tx(es), " << res.pool_stats.bytes_total << " bytes total (min " << res.pool_stats.bytes_min << ", max " << res.pool_stats.bytes_max << ", avg " << avg_bytes << ", median " << res.pool_stats.bytes_med << ")" << std::endl << "fees " << cryptonote::print_money(res.pool_stats.fee_total) << " (avg " << cryptonote::print_money(n_transactions ? res.pool_stats.fee_total / n_transactions : 0) << " per tx" << ", " << cryptonote::print_money(res.pool_stats.bytes_total ? res.pool_stats.fee_total / res.pool_stats.bytes_total : 0) << " per byte)" << std::endl << res.pool_stats.num_double_spends << " double spends, " << res.pool_stats.num_not_relayed << " not relayed, " << res.pool_stats.num_failing << " failing, " << res.pool_stats.num_10m << " older than 10 minutes (oldest " << (res.pool_stats.oldest == 0 ? "-" : get_human_time_ago(res.pool_stats.oldest, now)) << "), " << backlog_message; if (n_transactions > 1 && res.pool_stats.histo.size()) { std::vector<uint64_t> times; uint64_t numer; size_t i, n = res.pool_stats.histo.size(), denom; times.resize(n); if (res.pool_stats.histo_98pc) { numer = res.pool_stats.histo_98pc; denom = n-1; for (i=0; i<denom; i++) times[i] = i * numer / denom; times[i] = now - res.pool_stats.oldest; } else { numer = now - res.pool_stats.oldest; denom = n; for (i=0; i<denom; i++) times[i] = i * numer / denom; } tools::msg_writer() << " Age Txes Bytes"; for (i=0; i<n; i++) { tools::msg_writer() << get_time_hms(times[i]) << std::setw(8) << res.pool_stats.histo[i].txs << std::setw(12) << res.pool_stats.histo[i].bytes; } } tools::msg_writer(); return true; } bool t_rpc_command_executor::start_mining(cryptonote::account_public_address address, uint64_t num_threads, cryptonote::network_type nettype, bool do_background_mining, bool ignore_battery) { cryptonote::COMMAND_RPC_START_MINING::request req; cryptonote::COMMAND_RPC_START_MINING::response res; req.miner_address = cryptonote::get_account_address_as_str(nettype, false, address); req.threads_count = num_threads; req.do_background_mining = do_background_mining; req.ignore_battery = ignore_battery; std::string fail_message = "Mining did not start"; if (m_is_rpc) { if (m_rpc_client->rpc_request(req, res, "/start_mining", fail_message.c_str())) { tools::success_msg_writer() << "Mining started"; } } else { if (!m_rpc_server->on_start_mining(req, res) || res.status != CORE_RPC_STATUS_OK) { tools::fail_msg_writer() << make_error(fail_message, res.status); return true; } } return true; } bool t_rpc_command_executor::stop_mining() { cryptonote::COMMAND_RPC_STOP_MINING::request req; cryptonote::COMMAND_RPC_STOP_MINING::response res; std::string fail_message = "Mining did not stop"; if (m_is_rpc) { if (!m_rpc_client->rpc_request(req, res, "/stop_mining", fail_message.c_str())) { return true; } } else { if (!m_rpc_server->on_stop_mining(req, res) || res.status != CORE_RPC_STATUS_OK) { tools::fail_msg_writer() << make_error(fail_message, res.status); return true; } } tools::success_msg_writer() << "Mining stopped"; return true; } bool t_rpc_command_executor::stop_daemon() { cryptonote::COMMAND_RPC_STOP_DAEMON::request req; cryptonote::COMMAND_RPC_STOP_DAEMON::response res; //# ifdef WIN32 // // Stop via service API // // TODO - this is only temporary! Get rid of hard-coded constants! // bool ok = windows::stop_service("BitMonero Daemon"); // ok = windows::uninstall_service("BitMonero Daemon"); // //bool ok = windows::stop_service(SERVICE_NAME); // //ok = windows::uninstall_service(SERVICE_NAME); // if (ok) // { // return true; // } //# endif // Stop via RPC std::string fail_message = "Daemon did not stop"; if (m_is_rpc) { if(!m_rpc_client->rpc_request(req, res, "/stop_daemon", fail_message.c_str())) { return true; } } else { if (!m_rpc_server->on_stop_daemon(req, res) || res.status != CORE_RPC_STATUS_OK) { tools::fail_msg_writer() << make_error(fail_message, res.status); return true; } } tools::success_msg_writer() << "Stop signal sent"; return true; } bool t_rpc_command_executor::print_status() { if (!m_is_rpc) { tools::success_msg_writer() << "print_status makes no sense in interactive mode"; return true; } bool daemon_is_alive = m_rpc_client->check_connection(); if(daemon_is_alive) { tools::success_msg_writer() << "monerovd is running"; } else { tools::fail_msg_writer() << "monerovd is NOT running"; } return true; } bool t_rpc_command_executor::get_limit() { cryptonote::COMMAND_RPC_GET_LIMIT::request req; cryptonote::COMMAND_RPC_GET_LIMIT::response res; std::string failure_message = "Couldn't get limit"; if (m_is_rpc) { if (!m_rpc_client->rpc_request(req, res, "/get_limit", failure_message.c_str())) { return true; } } else { if (!m_rpc_server->on_get_limit(req, res) || res.status != CORE_RPC_STATUS_OK) { tools::fail_msg_writer() << make_error(failure_message, res.status); return true; } } tools::msg_writer() << "limit-down is " << res.limit_down/1024 << " kB/s"; tools::msg_writer() << "limit-up is " << res.limit_up/1024 << " kB/s"; return true; } bool t_rpc_command_executor::set_limit(int64_t limit_down, int64_t limit_up) { cryptonote::COMMAND_RPC_SET_LIMIT::request req; cryptonote::COMMAND_RPC_SET_LIMIT::response res; req.limit_down = limit_down; req.limit_up = limit_up; std::string failure_message = "Couldn't set limit"; if (m_is_rpc) { if (!m_rpc_client->rpc_request(req, res, "/set_limit", failure_message.c_str())) { return true; } } else { if (!m_rpc_server->on_set_limit(req, res) || res.status != CORE_RPC_STATUS_OK) { tools::fail_msg_writer() << make_error(failure_message, res.status); return true; } } tools::msg_writer() << "Set limit-down to " << res.limit_down/1024 << " kB/s"; tools::msg_writer() << "Set limit-up to " << res.limit_up/1024 << " kB/s"; return true; } bool t_rpc_command_executor::get_limit_up() { cryptonote::COMMAND_RPC_GET_LIMIT::request req; cryptonote::COMMAND_RPC_GET_LIMIT::response res; std::string failure_message = "Couldn't get limit"; if (m_is_rpc) { if (!m_rpc_client->rpc_request(req, res, "/get_limit", failure_message.c_str())) { return true; } } else { if (!m_rpc_server->on_get_limit(req, res) || res.status != CORE_RPC_STATUS_OK) { tools::fail_msg_writer() << make_error(failure_message, res.status); return true; } } tools::msg_writer() << "limit-up is " << res.limit_up/1024 << " kB/s"; return true; } bool t_rpc_command_executor::get_limit_down() { cryptonote::COMMAND_RPC_GET_LIMIT::request req; cryptonote::COMMAND_RPC_GET_LIMIT::response res; std::string failure_message = "Couldn't get limit"; if (m_is_rpc) { if (!m_rpc_client->rpc_request(req, res, "/get_limit", failure_message.c_str())) { return true; } } else { if (!m_rpc_server->on_get_limit(req, res) || res.status != CORE_RPC_STATUS_OK) { tools::fail_msg_writer() << make_error(failure_message, res.status); return true; } } tools::msg_writer() << "limit-down is " << res.limit_down/1024 << " kB/s"; return true; } bool t_rpc_command_executor::out_peers(uint64_t limit) { cryptonote::COMMAND_RPC_OUT_PEERS::request req; cryptonote::COMMAND_RPC_OUT_PEERS::response res; epee::json_rpc::error error_resp; req.out_peers = limit; std::string fail_message = "Unsuccessful"; if (m_is_rpc) { if (!m_rpc_client->rpc_request(req, res, "/out_peers", fail_message.c_str())) { return true; } } else { if (!m_rpc_server->on_out_peers(req, res) || res.status != CORE_RPC_STATUS_OK) { tools::fail_msg_writer() << make_error(fail_message, res.status); return true; } } std::cout << "Max number of out peers set to " << limit << std::endl; return true; } bool t_rpc_command_executor::in_peers(uint64_t limit) { cryptonote::COMMAND_RPC_IN_PEERS::request req; cryptonote::COMMAND_RPC_IN_PEERS::response res; epee::json_rpc::error error_resp; req.in_peers = limit; std::string fail_message = "Unsuccessful"; if (m_is_rpc) { if (!m_rpc_client->rpc_request(req, res, "/in_peers", fail_message.c_str())) { return true; } } else { if (!m_rpc_server->on_in_peers(req, res) || res.status != CORE_RPC_STATUS_OK) { tools::fail_msg_writer() << make_error(fail_message, res.status); return true; } } std::cout << "Max number of in peers set to " << limit << std::endl; return true; } bool t_rpc_command_executor::start_save_graph() { cryptonote::COMMAND_RPC_START_SAVE_GRAPH::request req; cryptonote::COMMAND_RPC_START_SAVE_GRAPH::response res; std::string fail_message = "Unsuccessful"; if (m_is_rpc) { if (!m_rpc_client->rpc_request(req, res, "/start_save_graph", fail_message.c_str())) { return true; } } else { if (!m_rpc_server->on_start_save_graph(req, res) || res.status != CORE_RPC_STATUS_OK) { tools::fail_msg_writer() << make_error(fail_message, res.status); return true; } } tools::success_msg_writer() << "Saving graph is now on"; return true; } bool t_rpc_command_executor::stop_save_graph() { cryptonote::COMMAND_RPC_STOP_SAVE_GRAPH::request req; cryptonote::COMMAND_RPC_STOP_SAVE_GRAPH::response res; std::string fail_message = "Unsuccessful"; if (m_is_rpc) { if (!m_rpc_client->rpc_request(req, res, "/stop_save_graph", fail_message.c_str())) { return true; } } else { if (!m_rpc_server->on_stop_save_graph(req, res) || res.status != CORE_RPC_STATUS_OK) { tools::fail_msg_writer() << make_error(fail_message, res.status); return true; } } tools::success_msg_writer() << "Saving graph is now off"; return true; } bool t_rpc_command_executor::hard_fork_info(uint8_t version) { cryptonote::COMMAND_RPC_HARD_FORK_INFO::request req; cryptonote::COMMAND_RPC_HARD_FORK_INFO::response res; std::string fail_message = "Unsuccessful"; epee::json_rpc::error error_resp; req.version = version; if (m_is_rpc) { if (!m_rpc_client->json_rpc_request(req, res, "hard_fork_info", fail_message.c_str())) { return true; } } else { if (!m_rpc_server->on_hard_fork_info(req, res, error_resp) || res.status != CORE_RPC_STATUS_OK) { tools::fail_msg_writer() << make_error(fail_message, res.status); return true; } } version = version > 0 ? version : res.voting; tools::msg_writer() << "version " << (uint32_t)version << " " << (res.enabled ? "enabled" : "not enabled") << ", " << res.votes << "/" << res.window << " votes, threshold " << res.threshold; tools::msg_writer() << "current version " << (uint32_t)res.version << ", voting for version " << (uint32_t)res.voting; return true; } bool t_rpc_command_executor::print_bans() { cryptonote::COMMAND_RPC_GETBANS::request req; cryptonote::COMMAND_RPC_GETBANS::response res; std::string fail_message = "Unsuccessful"; epee::json_rpc::error error_resp; if (m_is_rpc) { if (!m_rpc_client->json_rpc_request(req, res, "get_bans", fail_message.c_str())) { return true; } } else { if (!m_rpc_server->on_get_bans(req, res, error_resp) || res.status != CORE_RPC_STATUS_OK) { tools::fail_msg_writer() << make_error(fail_message, res.status); return true; } } for (auto i = res.bans.begin(); i != res.bans.end(); ++i) { tools::msg_writer() << epee::string_tools::get_ip_string_from_int32(i->ip) << " banned for " << i->seconds << " seconds"; } return true; } bool t_rpc_command_executor::ban(const std::string &ip, time_t seconds) { cryptonote::COMMAND_RPC_SETBANS::request req; cryptonote::COMMAND_RPC_SETBANS::response res; std::string fail_message = "Unsuccessful"; epee::json_rpc::error error_resp; cryptonote::COMMAND_RPC_SETBANS::ban ban; if (!epee::string_tools::get_ip_int32_from_string(ban.ip, ip)) { tools::fail_msg_writer() << "Invalid IP"; return true; } ban.ban = true; ban.seconds = seconds; req.bans.push_back(ban); if (m_is_rpc) { if (!m_rpc_client->json_rpc_request(req, res, "set_bans", fail_message.c_str())) { return true; } } else { if (!m_rpc_server->on_set_bans(req, res, error_resp) || res.status != CORE_RPC_STATUS_OK) { tools::fail_msg_writer() << make_error(fail_message, res.status); return true; } } return true; } bool t_rpc_command_executor::unban(const std::string &ip) { cryptonote::COMMAND_RPC_SETBANS::request req; cryptonote::COMMAND_RPC_SETBANS::response res; std::string fail_message = "Unsuccessful"; epee::json_rpc::error error_resp; cryptonote::COMMAND_RPC_SETBANS::ban ban; if (!epee::string_tools::get_ip_int32_from_string(ban.ip, ip)) { tools::fail_msg_writer() << "Invalid IP"; return true; } ban.ban = false; ban.seconds = 0; req.bans.push_back(ban); if (m_is_rpc) { if (!m_rpc_client->json_rpc_request(req, res, "set_bans", fail_message.c_str())) { return true; } } else { if (!m_rpc_server->on_set_bans(req, res, error_resp) || res.status != CORE_RPC_STATUS_OK) { tools::fail_msg_writer() << make_error(fail_message, res.status); return true; } } return true; } bool t_rpc_command_executor::flush_txpool(const std::string &txid) { cryptonote::COMMAND_RPC_FLUSH_TRANSACTION_POOL::request req; cryptonote::COMMAND_RPC_FLUSH_TRANSACTION_POOL::response res; std::string fail_message = "Unsuccessful"; epee::json_rpc::error error_resp; if (!txid.empty()) req.txids.push_back(txid); if (m_is_rpc) { if (!m_rpc_client->json_rpc_request(req, res, "flush_txpool", fail_message.c_str())) { return true; } } else { if (!m_rpc_server->on_flush_txpool(req, res, error_resp) || res.status != CORE_RPC_STATUS_OK) { tools::fail_msg_writer() << make_error(fail_message, res.status); return true; } } tools::success_msg_writer() << "Pool successfully flushed"; return true; } bool t_rpc_command_executor::output_histogram(const std::vector<uint64_t> &amounts, uint64_t min_count, uint64_t max_count) { cryptonote::COMMAND_RPC_GET_OUTPUT_HISTOGRAM::request req; cryptonote::COMMAND_RPC_GET_OUTPUT_HISTOGRAM::response res; std::string fail_message = "Unsuccessful"; epee::json_rpc::error error_resp; req.amounts = amounts; req.min_count = min_count; req.max_count = max_count; req.unlocked = false; req.recent_cutoff = 0; if (m_is_rpc) { if (!m_rpc_client->json_rpc_request(req, res, "get_output_histogram", fail_message.c_str())) { return true; } } else { if (!m_rpc_server->on_get_output_histogram(req, res, error_resp) || res.status != CORE_RPC_STATUS_OK) { tools::fail_msg_writer() << make_error(fail_message, res.status); return true; } } std::sort(res.histogram.begin(), res.histogram.end(), [](const cryptonote::COMMAND_RPC_GET_OUTPUT_HISTOGRAM::entry &e1, const cryptonote::COMMAND_RPC_GET_OUTPUT_HISTOGRAM::entry &e2)->bool { return e1.total_instances < e2.total_instances; }); for (const auto &e: res.histogram) { tools::msg_writer() << e.total_instances << " " << cryptonote::print_money(e.amount); } return true; } bool t_rpc_command_executor::print_coinbase_tx_sum(uint64_t height, uint64_t count) { cryptonote::COMMAND_RPC_GET_COINBASE_TX_SUM::request req; cryptonote::COMMAND_RPC_GET_COINBASE_TX_SUM::response res; epee::json_rpc::error error_resp; req.height = height; req.count = count; std::string fail_message = "Unsuccessful"; if (m_is_rpc) { if (!m_rpc_client->json_rpc_request(req, res, "get_coinbase_tx_sum", fail_message.c_str())) { return true; } } else { if (!m_rpc_server->on_get_coinbase_tx_sum(req, res, error_resp) || res.status != CORE_RPC_STATUS_OK) { tools::fail_msg_writer() << make_error(fail_message, res.status); return true; } } tools::msg_writer() << "Sum of coinbase transactions between block heights [" << height << ", " << (height + count) << ") is " << cryptonote::print_money(res.emission_amount + res.fee_amount) << " " << "consisting of " << cryptonote::print_money(res.emission_amount) << " in emissions, and " << cryptonote::print_money(res.fee_amount) << " in fees"; return true; } bool t_rpc_command_executor::alt_chain_info() { cryptonote::COMMAND_RPC_GET_INFO::request ireq; cryptonote::COMMAND_RPC_GET_INFO::response ires; cryptonote::COMMAND_RPC_GET_ALTERNATE_CHAINS::request req; cryptonote::COMMAND_RPC_GET_ALTERNATE_CHAINS::response res; epee::json_rpc::error error_resp; std::string fail_message = "Unsuccessful"; if (m_is_rpc) { if (!m_rpc_client->rpc_request(ireq, ires, "/getinfo", fail_message.c_str())) { return true; } if (!m_rpc_client->json_rpc_request(req, res, "get_alternate_chains", fail_message.c_str())) { return true; } } else { if (!m_rpc_server->on_get_info(ireq, ires) || ires.status != CORE_RPC_STATUS_OK) { tools::fail_msg_writer() << make_error(fail_message, ires.status); return true; } if (!m_rpc_server->on_get_alternate_chains(req, res, error_resp)) { tools::fail_msg_writer() << make_error(fail_message, res.status); return true; } } tools::msg_writer() << boost::lexical_cast<std::string>(res.chains.size()) << " alternate chains found:"; for (const auto &chain: res.chains) { uint64_t start_height = (chain.height - chain.length + 1); tools::msg_writer() << chain.length << " blocks long, from height " << start_height << " (" << (ires.height - start_height - 1) << " deep), diff " << chain.difficulty << ": " << chain.block_hash; } return true; } bool t_rpc_command_executor::print_blockchain_dynamic_stats(uint64_t nblocks) { cryptonote::COMMAND_RPC_GET_INFO::request ireq; cryptonote::COMMAND_RPC_GET_INFO::response ires; cryptonote::COMMAND_RPC_GET_BLOCK_HEADERS_RANGE::request bhreq; cryptonote::COMMAND_RPC_GET_BLOCK_HEADERS_RANGE::response bhres; cryptonote::COMMAND_RPC_GET_PER_KB_FEE_ESTIMATE::request fereq; cryptonote::COMMAND_RPC_GET_PER_KB_FEE_ESTIMATE::response feres; epee::json_rpc::error error_resp; std::string fail_message = "Problem fetching info"; fereq.grace_blocks = 0; if (m_is_rpc) { if (!m_rpc_client->rpc_request(ireq, ires, "/getinfo", fail_message.c_str())) { return true; } if (!m_rpc_client->json_rpc_request(fereq, feres, "get_fee_estimate", fail_message.c_str())) { return true; } } else { if (!m_rpc_server->on_get_info(ireq, ires) || ires.status != CORE_RPC_STATUS_OK) { tools::fail_msg_writer() << make_error(fail_message, ires.status); return true; } if (!m_rpc_server->on_get_per_kb_fee_estimate(fereq, feres, error_resp) || feres.status != CORE_RPC_STATUS_OK) { tools::fail_msg_writer() << make_error(fail_message, feres.status); return true; } } tools::msg_writer() << "Height: " << ires.height << ", diff " << ires.difficulty << ", cum. diff " << ires.cumulative_difficulty << ", target " << ires.target << " sec" << ", dyn fee " << cryptonote::print_money(feres.fee) << "/kB"; if (nblocks > 0) { if (nblocks > ires.height) nblocks = ires.height; bhreq.start_height = ires.height - nblocks; bhreq.end_height = ires.height - 1; if (m_is_rpc) { if (!m_rpc_client->json_rpc_request(bhreq, bhres, "getblockheadersrange", fail_message.c_str())) { return true; } } else { if (!m_rpc_server->on_get_block_headers_range(bhreq, bhres, error_resp) || bhres.status != CORE_RPC_STATUS_OK) { tools::fail_msg_writer() << make_error(fail_message, bhres.status); return true; } } double avgdiff = 0; double avgnumtxes = 0; double avgreward = 0; std::vector<uint64_t> sizes; sizes.reserve(nblocks); uint64_t earliest = std::numeric_limits<uint64_t>::max(), latest = 0; std::vector<unsigned> major_versions(256, 0), minor_versions(256, 0); for (const auto &bhr: bhres.headers) { avgdiff += bhr.difficulty; avgnumtxes += bhr.num_txes; avgreward += bhr.reward; sizes.push_back(bhr.block_size); static_assert(sizeof(bhr.major_version) == 1, "major_version expected to be uint8_t"); static_assert(sizeof(bhr.minor_version) == 1, "major_version expected to be uint8_t"); major_versions[(unsigned)bhr.major_version]++; minor_versions[(unsigned)bhr.minor_version]++; earliest = std::min(earliest, bhr.timestamp); latest = std::max(latest, bhr.timestamp); } avgdiff /= nblocks; avgnumtxes /= nblocks; avgreward /= nblocks; uint64_t median_block_size = epee::misc_utils::median(sizes); tools::msg_writer() << "Last " << nblocks << ": avg. diff " << (uint64_t)avgdiff << ", " << (latest - earliest) / nblocks << " avg sec/block, avg num txes " << avgnumtxes << ", avg. reward " << cryptonote::print_money(avgreward) << ", median block size " << median_block_size; unsigned int max_major = 256, max_minor = 256; while (max_major > 0 && !major_versions[--max_major]); while (max_minor > 0 && !minor_versions[--max_minor]); std::string s = ""; for (unsigned n = 0; n <= max_major; ++n) if (major_versions[n]) s += (s.empty() ? "" : ", ") + boost::lexical_cast<std::string>(major_versions[n]) + std::string(" v") + boost::lexical_cast<std::string>(n); tools::msg_writer() << "Block versions: " << s; s = ""; for (unsigned n = 0; n <= max_minor; ++n) if (minor_versions[n]) s += (s.empty() ? "" : ", ") + boost::lexical_cast<std::string>(minor_versions[n]) + std::string(" v") + boost::lexical_cast<std::string>(n); tools::msg_writer() << "Voting for: " << s; } return true; } bool t_rpc_command_executor::update(const std::string &command) { cryptonote::COMMAND_RPC_UPDATE::request req; cryptonote::COMMAND_RPC_UPDATE::response res; epee::json_rpc::error error_resp; std::string fail_message = "Problem fetching info"; req.command = command; if (m_is_rpc) { if (!m_rpc_client->rpc_request(req, res, "/update", fail_message.c_str())) { return true; } } else { if (!m_rpc_server->on_update(req, res) || res.status != CORE_RPC_STATUS_OK) { tools::fail_msg_writer() << make_error(fail_message, res.status); return true; } } if (!res.update) { tools::msg_writer() << "No update available"; return true; } tools::msg_writer() << "Update available: v" << res.version << ": " << res.user_uri << ", hash " << res.hash; if (command == "check") return true; if (!res.path.empty()) tools::msg_writer() << "Update downloaded to: " << res.path; else tools::msg_writer() << "Update download failed: " << res.status; if (command == "download") return true; tools::msg_writer() << "'update' not implemented yet"; return true; } bool t_rpc_command_executor::relay_tx(const std::string &txid) { cryptonote::COMMAND_RPC_RELAY_TX::request req; cryptonote::COMMAND_RPC_RELAY_TX::response res; std::string fail_message = "Unsuccessful"; epee::json_rpc::error error_resp; req.txids.push_back(txid); if (m_is_rpc) { if (!m_rpc_client->json_rpc_request(req, res, "relay_tx", fail_message.c_str())) { return true; } } else { if (!m_rpc_server->on_relay_tx(req, res, error_resp) || res.status != CORE_RPC_STATUS_OK) { tools::fail_msg_writer() << make_error(fail_message, res.status); return true; } } tools::success_msg_writer() << "Transaction successfully relayed"; return true; } bool t_rpc_command_executor::sync_info() { cryptonote::COMMAND_RPC_SYNC_INFO::request req; cryptonote::COMMAND_RPC_SYNC_INFO::response res; std::string fail_message = "Unsuccessful"; epee::json_rpc::error error_resp; if (m_is_rpc) { if (!m_rpc_client->json_rpc_request(req, res, "sync_info", fail_message.c_str())) { return true; } } else { if (!m_rpc_server->on_sync_info(req, res, error_resp) || res.status != CORE_RPC_STATUS_OK) { tools::fail_msg_writer() << make_error(fail_message, res.status); return true; } } uint64_t target = res.target_height < res.height ? res.height : res.target_height; tools::success_msg_writer() << "Height: " << res.height << ", target: " << target << " (" << (100.0 * res.height / target) << "%)"; uint64_t current_download = 0; for (const auto &p: res.peers) current_download += p.info.current_download; tools::success_msg_writer() << "Downloading at " << current_download << " kB/s"; tools::success_msg_writer() << std::to_string(res.peers.size()) << " peers"; for (const auto &p: res.peers) { std::string address = epee::string_tools::pad_string(p.info.address, 24); uint64_t nblocks = 0, size = 0; for (const auto &s: res.spans) if (s.rate > 0.0f && s.connection_id == p.info.connection_id) nblocks += s.nblocks, size += s.size; tools::success_msg_writer() << address << " " << epee::string_tools::pad_string(p.info.peer_id, 16, '0', true) << " " << p.info.height << " " << p.info.current_download << " kB/s, " << nblocks << " blocks / " << size/1e6 << " MB queued"; } uint64_t total_size = 0; for (const auto &s: res.spans) total_size += s.size; tools::success_msg_writer() << std::to_string(res.spans.size()) << " spans, " << total_size/1e6 << " MB"; for (const auto &s: res.spans) { std::string address = epee::string_tools::pad_string(s.remote_address, 24); if (s.size == 0) { tools::success_msg_writer() << address << " " << s.nblocks << " (" << s.start_block_height << " - " << (s.start_block_height + s.nblocks - 1) << ") -"; } else { tools::success_msg_writer() << address << " " << s.nblocks << " (" << s.start_block_height << " - " << (s.start_block_height + s.nblocks - 1) << ", " << (uint64_t)(s.size/1e3) << " kB) " << (unsigned)(s.rate/1e3) << " kB/s (" << s.speed/100.0f << ")"; } } return true; } }// namespace daemonize
[ "miltonf@monerov.org" ]
miltonf@monerov.org
09d76eb450306d7231e54f448ef7f7a47d4b03b0
9de18ef120a8ae68483b866c1d4c7b9c2fbef46e
/src/Symbols/include/Symbols/MockSymbolCache.h
53314830326f0b5613f6455be70947377fae7a2c
[ "BSD-2-Clause", "LicenseRef-scancode-free-unknown" ]
permissive
google/orbit
02a5b4556cd2f979f377b87c24dd2b0a90dff1e2
68c4ae85a6fe7b91047d020259234f7e4961361c
refs/heads/main
2023-09-03T13:14:49.830576
2023-08-25T06:28:36
2023-08-25T06:28:36
104,358,587
2,680
325
BSD-2-Clause
2023-08-25T06:28:37
2017-09-21T14:28:35
C++
UTF-8
C++
false
false
600
h
// Copyright (c) 2022 The Orbit Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef SYMBOLS_MOCK_SYMBOL_CACHE_H_ #define SYMBOLS_MOCK_SYMBOL_CACHE_H_ #include <gmock/gmock.h> #include "Symbols/SymbolCacheInterface.h" namespace orbit_symbols { class MockSymbolCache : public SymbolCacheInterface { public: MOCK_METHOD(std::filesystem::path, GenerateCachedFilePath, (const std::filesystem::path&), (const, override)); }; } // namespace orbit_symbols #endif // SYMBOLS_MOCK_SYMBOL_CACHE_H_
[ "noreply@github.com" ]
noreply@github.com
ced9f45ce1946c1c3c187ced4a42124a3b9efb34
a17379e70b7b8bcd4b826475961666f25f4b7269
/image.hpp
74bdd02e4a404ea07e3d383646f9b6b436e8360e
[]
no_license
eightys3v3n/imageViewer
0e2aa7e4e92ed5255f866c5d40cc4178eed79019
e159fa36aa2a1d6d8ca2a1f64ef3447c697009f3
refs/heads/master
2020-05-25T22:42:11.588756
2017-01-16T03:00:19
2017-01-16T03:00:19
59,589,742
0
0
null
null
null
null
UTF-8
C++
false
false
337
hpp
#ifndef IMAGE_ #define IMAGE_ #include <string> #include <vector> #include <SFML/Graphics.hpp> #include <SFML/System.hpp> #include "filesystem.hpp" #include "sorting.hpp" typedef std::string string; bool loadImage(); void fitImage(); bool nextImage(); bool lastImage(); #endif // IMAGE_ // written by terrence plunkett (eightys3v3n)
[ "eightys3v3n+github@gmail.com" ]
eightys3v3n+github@gmail.com
5ffbecfe8c51d1aa578ba619d17b582bd9ce15ab
bc6baf9bce6867566c41e051bfa96da22ea36017
/OOP/test_file.cpp
8c6de4bc6dfc23536324cc26825ab61ce0a255c3
[]
no_license
hoangnamwar/c-
9ca1267e5ac9df9b39ae7c4c955eb624b301f3bd
d53b3cbc0015dca6d200afc31bcd51b763e3df79
refs/heads/master
2022-12-11T17:17:41.466844
2020-09-19T23:16:32
2020-09-19T23:16:32
297,013,998
0
0
null
null
null
null
UTF-8
C++
false
false
1,830
cpp
#include<iostream> #include<fstream> #include<string> using namespace std; #define MAX 200 string ten[MAX]; string sdt[MAX]; string email[MAX]; int main() { //----------Doc file-------------------------------- int N = 0; fstream fin("test_file.dat", ios::binary); fin >> N; char temp[100]; fin.getline(temp, 100); for(int i=0;i<N;i++) { getline(fin,ten[i]); getline(fin,sdt[i]); getline(fin,email[i]); } fin.close(); //----------Ket thuc doc file----------------------- for(int i=0;i<N;i++) { cout << ten[i] << endl; cout << sdt[i] << endl; cout << email[i] << endl; } //---------------- // cout<<"\t\tThem lien he\n"; // cout<<endl; // cout<<"Xim moi nhap ho va ten: "; // cin.ignore();//Doc va loai bo ky tu trong bo nho dem // getline(cin,ten[N]);//Nhan day ky tu nhap vao cho den khi ket thuc bang dau Enter // cout<<"Xin moi nhap so dien thoai: "; // getline(cin,sdt[N]);//Nhan day ky tu nhap vao cho den khi ket thuc bang dau Enter // cout<<"Xin moi nhap dia chi email: "; // getline(cin,email[N]);//Nhan day ky tu nhap vao cho den khi ket thuc bang dau Enter // N++;//Dem so danh ba //----------Tao file va ghi file-------------------- // ofstream fout("test_file.dat", ios::binary);//Tao file va luu thong tin toi file test_file.txt // fout << N << endl;//Ghi va dem so danh ba // for ( int i=0 ; i < N ; i++ ) // { // fout << ten[i] << endl // << sdt[i] << endl // << email[i] << endl; // //Ghi ten, sdt, mail vao file test_file.txt // } // fout.close(); //----------Ket thuc va luu file-------------------- }
[ "58459427+hoangnamwar@users.noreply.github.com" ]
58459427+hoangnamwar@users.noreply.github.com
9ed7588f9485b003f287e9cf364bdab614d3e39d
029c481b44b44c42605a8a828c358af39679300f
/basic/Calculator10869.cpp
150d9c143b7389956e78e20eca9c70d557f2e522
[]
no_license
cbajs12/BOJ
93f4406c8820b834a48166f18abf89b7481cab7e
1e6ac6c98fe1336dd48db146199f8ebe7c4e216f
refs/heads/master
2020-05-29T12:23:11.757012
2019-06-08T12:14:58
2019-06-08T12:14:58
68,577,265
0
0
null
null
null
null
UTF-8
C++
false
false
349
cpp
#include <iostream> using namespace std; int main(void){ int num1; int num2; cin>>num1>>num2; if(num1 < 1 || num1 > 10000) return 0; if(num2 < 1 || num2 > 10000) return 0; cout<<num1+num2<<endl; cout<<num1-num2<<endl; cout<<num1*num2<<endl; cout<<num1/num2<<endl; cout<<num1%num2<<endl; }
[ "cbajs20@gmail.com" ]
cbajs20@gmail.com
0ca0392e2f08b2e2aca0f90c333d8d4b71fe6f5d
d66e521445d85a1ff8a56140ffa9d09cb3b259cd
/exercicioPraticoMain.h
611c55e39b10aed38792fbb11dc090f3c191f0cc
[]
no_license
EdmilsonOSJr/exercicioPratico
783669b1137999dbf25da186a8a34f5c398ddf02
aa3e7d38b51fef91db5f28980110c3e5770396d2
refs/heads/main
2023-01-06T03:11:46.090269
2020-11-11T00:49:45
2020-11-11T00:49:45
311,811,761
0
0
null
null
null
null
UTF-8
C++
false
false
2,278
h
/*************************************************************** * Name: exercicioPraticoMain.h * Purpose: Defines Application Frame * Author: () * Created: 2020-11-10 * Copyright: () * License: **************************************************************/ #ifndef EXERCICIOPRATICOMAIN_H #define EXERCICIOPRATICOMAIN_H //(*Headers(exercicioPraticoFrame) #include <wx/button.h> #include <wx/frame.h> #include <wx/menu.h> #include <wx/panel.h> #include <wx/sizer.h> #include <wx/slider.h> #include <wx/statline.h> #include <wx/stattext.h> #include <wx/statusbr.h> //*) class exercicioPraticoFrame: public wxFrame { public: exercicioPraticoFrame(wxWindow* parent,wxWindowID id = -1); virtual ~exercicioPraticoFrame(); private: //(*Handlers(exercicioPraticoFrame) void OnQuit(wxCommandEvent& event); void OnAbout(wxCommandEvent& event); void OnescolheNotaSliderCmdScrollChanged(wxScrollEvent& event); void OncomparaNotaButtonClick(wxCommandEvent& event); //*) //(*Identifiers(exercicioPraticoFrame) static const long ID_SLIDER1; static const long ID_STATICTEXT1; static const long ID_BUTTON1; static const long ID_STATICTEXT2; static const long ID_STATICTEXT4; static const long ID_STATICLINE1; static const long ID_STATICTEXT5; static const long ID_STATICTEXT6; static const long ID_STATICTEXT7; static const long ID_STATICTEXT3; static const long ID_PANEL1; static const long idMenuQuit; static const long idMenuAbout; static const long ID_STATUSBAR1; //*) //(*Declarations(exercicioPraticoFrame) wxButton* comparaNotaButton; wxPanel* Panel1; wxSlider* escolheNotaSlider; wxStaticLine* StaticLine1; wxStaticText* StaticText1; wxStaticText* StaticText2; wxStaticText* notaDoTesteStaticTex; wxStaticText* notaEscolhidaStaticText; wxStaticText* precisoStaticText; wxStaticText* valorDoTesteStaticText; wxStaticText* valorExcolhidoStaticText; wxStatusBar* StatusBar1; //*) DECLARE_EVENT_TABLE() }; #endif // EXERCICIOPRATICOMAIN_H
[ "44274029+EdmilsonOSJr@users.noreply.github.com" ]
44274029+EdmilsonOSJr@users.noreply.github.com
fcb8e53eadf41f791b0a15206961a86de636f634
bcf138c82fcba9acc7d7ce4d3a92618b06ebe7c7
/rdr2/0x5EE6FCCC9C832CA2.cpp
958259ed15c82616a2eb969096be260b8d2c01c8
[]
no_license
DeepWolf413/additional-native-data
aded47e042f0feb30057e753910e0884c44121a0
e015b2500b52065252ffbe3c53865fe3cdd3e06c
refs/heads/main
2023-07-10T00:19:54.416083
2021-08-12T16:00:12
2021-08-12T16:00:12
395,340,507
1
0
null
null
null
null
UTF-8
C++
false
false
438
cpp
// annesburg.ysc @ L6193 void func_181(int iParam0, int iParam1) { if (iParam0 < 0 || iParam0 >= Global_40.f_9829) { return; } func_289(&(Global_40.f_9829[iParam0 /*4*/].f_2), iParam1); } Vector3 func_182(int iParam0) { if (!func_140(iParam0)) { return 0f, 0f, 0f; } if (!PERSCHAR::_0x800DF3FC913355F3(func_169(iParam0))) { return 0f, 0f, 0f; } return PERSCHAR::_0x5EE6FCCC9C832CA2(func_169(iParam0)); }
[ "jesper15fuji@live.dk" ]
jesper15fuji@live.dk
0a24cdde859c99e62a90a2508c4c41a79cbe2843
4c23be1a0ca76f68e7146f7d098e26c2bbfb2650
/ic8h18/0.0055/DC6H13
a409246699b37685f60ea72b72f5cfe6afe1430c
[]
no_license
labsandy/OpenFOAM_workspace
a74b473903ddbd34b31dc93917e3719bc051e379
6e0193ad9dabd613acf40d6b3ec4c0536c90aed4
refs/heads/master
2022-02-25T02:36:04.164324
2019-08-23T02:27:16
2019-08-23T02:27:16
null
0
0
null
null
null
null
UTF-8
C++
false
false
839
/*--------------------------------*- C++ -*----------------------------------*\ ========= | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox \\ / O peration | Website: https://openfoam.org \\ / A nd | Version: 6 \\/ M anipulation | \*---------------------------------------------------------------------------*/ FoamFile { version 2.0; format ascii; class volScalarField; location "0.0055"; object DC6H13; } // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // dimensions [0 0 0 0 0 0 0]; internalField uniform 5.01557e-19; boundaryField { boundary { type empty; } } // ************************************************************************* //
[ "jfeatherstone123@gmail.com" ]
jfeatherstone123@gmail.com
475557ea5dda2187be9ad27020cafc18bfa94cd5
80ce148b64401defbfdb2a9becdfbfcee25e4a01
/src/wallet/test/wallet_tests.cpp
7b33eb22fba564154bec7dd6936ede5944dd28a6
[ "MIT" ]
permissive
KhryptorGraphics/starshipscrypt
1015e19644aff5a79fe25e21a79492917c27f2f1
3a7e32fae33bc382fb31c4d588d2e9773ea490bc
refs/heads/master
2021-09-23T09:00:47.454818
2021-09-13T22:34:18
2021-09-13T22:34:18
138,207,950
1
0
null
null
null
null
UTF-8
C++
false
false
29,401
cpp
// Copyright (c) 2012-2016 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "wallet/wallet.h" #include <set> #include <stdint.h> #include <utility> #include <vector> #include "consensus/validation.h" #include "rpc/server.h" #include "test/test_bitcoin.h" #include "validation.h" #include "wallet/coincontrol.h" #include "wallet/test/wallet_test_fixture.h" #include <boost/test/unit_test.hpp> #include <univalue.h> extern CWallet* pwalletMain; extern UniValue importmulti(const JSONRPCRequest& request); extern UniValue dumpwallet(const JSONRPCRequest& request); extern UniValue importwallet(const JSONRPCRequest& request); // how many times to run all the tests to have a chance to catch errors that only show up with particular random shuffles #define RUN_TESTS 100 // some tests fail 1% of the time due to bad luck. // we repeat those tests this many times and only complain if all iterations of the test fail #define RANDOM_REPEATS 5 std::vector<std::unique_ptr<CWalletTx>> wtxn; typedef std::set<CInputCoin> CoinSet; BOOST_FIXTURE_TEST_SUITE(wallet_tests, WalletTestingSetup) static const CWallet testWallet; static std::vector<COutput> vCoins; static void add_coin(const CAmount& nValue, int nAge = 6*24, bool fIsFromMe = false, int nInput=0) { static int nextLockTime = 0; CMutableTransaction tx; tx.nLockTime = nextLockTime++; // so all transactions get different hashes tx.vout.resize(nInput+1); tx.vout[nInput].nValue = nValue; if (fIsFromMe) { // IsFromMe() returns (GetDebit() > 0), and GetDebit() is 0 if vin.empty(), // so stop vin being empty, and cache a non-zero Debit to fake out IsFromMe() tx.vin.resize(1); } std::unique_ptr<CWalletTx> wtx(new CWalletTx(&testWallet, MakeTransactionRef(std::move(tx)))); if (fIsFromMe) { wtx->fDebitCached = true; wtx->nDebitCached = 1; } COutput output(wtx.get(), nInput, nAge, true /* spendable */, true /* solvable */, true /* safe */); vCoins.push_back(output); wtxn.emplace_back(std::move(wtx)); } static void empty_wallet(void) { vCoins.clear(); wtxn.clear(); } static bool equal_sets(CoinSet a, CoinSet b) { std::pair<CoinSet::iterator, CoinSet::iterator> ret = mismatch(a.begin(), a.end(), b.begin()); return ret.first == a.end() && ret.second == b.end(); } BOOST_AUTO_TEST_CASE(coin_selection_tests) { CoinSet setCoinsRet, setCoinsRet2; CAmount nValueRet; LOCK(testWallet.cs_wallet); // test multiple times to allow for differences in the shuffle order for (int i = 0; i < RUN_TESTS; i++) { empty_wallet(); // with an empty wallet we can't even pay one cent BOOST_CHECK(!testWallet.SelectCoinsMinConf( 1 * CENT, 1, 6, 0, vCoins, setCoinsRet, nValueRet)); add_coin(1*CENT, 4); // add a new 1 cent coin // with a new 1 cent coin, we still can't find a mature 1 cent BOOST_CHECK(!testWallet.SelectCoinsMinConf( 1 * CENT, 1, 6, 0, vCoins, setCoinsRet, nValueRet)); // but we can find a new 1 cent BOOST_CHECK( testWallet.SelectCoinsMinConf( 1 * CENT, 1, 1, 0, vCoins, setCoinsRet, nValueRet)); BOOST_CHECK_EQUAL(nValueRet, 1 * CENT); add_coin(2*CENT); // add a mature 2 cent coin // we can't make 3 cents of mature coins BOOST_CHECK(!testWallet.SelectCoinsMinConf( 3 * CENT, 1, 6, 0, vCoins, setCoinsRet, nValueRet)); // we can make 3 cents of new coins BOOST_CHECK( testWallet.SelectCoinsMinConf( 3 * CENT, 1, 1, 0, vCoins, setCoinsRet, nValueRet)); BOOST_CHECK_EQUAL(nValueRet, 3 * CENT); add_coin(5*CENT); // add a mature 5 cent coin, add_coin(10*CENT, 3, true); // a new 10 cent coin sent from one of our own addresses add_coin(20*CENT); // and a mature 20 cent coin // now we have new: 1+10=11 (of which 10 was self-sent), and mature: 2+5+20=27. total = 38 // we can't make 38 cents only if we disallow new coins: BOOST_CHECK(!testWallet.SelectCoinsMinConf(38 * CENT, 1, 6, 0, vCoins, setCoinsRet, nValueRet)); // we can't even make 37 cents if we don't allow new coins even if they're from us BOOST_CHECK(!testWallet.SelectCoinsMinConf(38 * CENT, 6, 6, 0, vCoins, setCoinsRet, nValueRet)); // but we can make 37 cents if we accept new coins from ourself BOOST_CHECK( testWallet.SelectCoinsMinConf(37 * CENT, 1, 6, 0, vCoins, setCoinsRet, nValueRet)); BOOST_CHECK_EQUAL(nValueRet, 37 * CENT); // and we can make 38 cents if we accept all new coins BOOST_CHECK( testWallet.SelectCoinsMinConf(38 * CENT, 1, 1, 0, vCoins, setCoinsRet, nValueRet)); BOOST_CHECK_EQUAL(nValueRet, 38 * CENT); // try making 34 cents from 1,2,5,10,20 - we can't do it exactly BOOST_CHECK( testWallet.SelectCoinsMinConf(34 * CENT, 1, 1, 0, vCoins, setCoinsRet, nValueRet)); BOOST_CHECK_EQUAL(nValueRet, 35 * CENT); // but 35 cents is closest BOOST_CHECK_EQUAL(setCoinsRet.size(), 3U); // the best should be 20+10+5. it's incredibly unlikely the 1 or 2 got included (but possible) // when we try making 7 cents, the smaller coins (1,2,5) are enough. We should see just 2+5 BOOST_CHECK( testWallet.SelectCoinsMinConf( 7 * CENT, 1, 1, 0, vCoins, setCoinsRet, nValueRet)); BOOST_CHECK_EQUAL(nValueRet, 7 * CENT); BOOST_CHECK_EQUAL(setCoinsRet.size(), 2U); // when we try making 8 cents, the smaller coins (1,2,5) are exactly enough. BOOST_CHECK( testWallet.SelectCoinsMinConf( 8 * CENT, 1, 1, 0, vCoins, setCoinsRet, nValueRet)); BOOST_CHECK(nValueRet == 8 * CENT); BOOST_CHECK_EQUAL(setCoinsRet.size(), 3U); // when we try making 9 cents, no subset of smaller coins is enough, and we get the next bigger coin (10) BOOST_CHECK( testWallet.SelectCoinsMinConf( 9 * CENT, 1, 1, 0, vCoins, setCoinsRet, nValueRet)); BOOST_CHECK_EQUAL(nValueRet, 10 * CENT); BOOST_CHECK_EQUAL(setCoinsRet.size(), 1U); // now clear out the wallet and start again to test choosing between subsets of smaller coins and the next biggest coin empty_wallet(); add_coin( 6*CENT); add_coin( 7*CENT); add_coin( 8*CENT); add_coin(20*CENT); add_coin(30*CENT); // now we have 6+7+8+20+30 = 71 cents total // check that we have 71 and not 72 BOOST_CHECK( testWallet.SelectCoinsMinConf(71 * CENT, 1, 1, 0, vCoins, setCoinsRet, nValueRet)); BOOST_CHECK(!testWallet.SelectCoinsMinConf(72 * CENT, 1, 1, 0, vCoins, setCoinsRet, nValueRet)); // now try making 16 cents. the best smaller coins can do is 6+7+8 = 21; not as good at the next biggest coin, 20 BOOST_CHECK( testWallet.SelectCoinsMinConf(16 * CENT, 1, 1, 0, vCoins, setCoinsRet, nValueRet)); BOOST_CHECK_EQUAL(nValueRet, 20 * CENT); // we should get 20 in one coin BOOST_CHECK_EQUAL(setCoinsRet.size(), 1U); add_coin( 5*CENT); // now we have 5+6+7+8+20+30 = 75 cents total // now if we try making 16 cents again, the smaller coins can make 5+6+7 = 18 cents, better than the next biggest coin, 20 BOOST_CHECK( testWallet.SelectCoinsMinConf(16 * CENT, 1, 1, 0, vCoins, setCoinsRet, nValueRet)); BOOST_CHECK_EQUAL(nValueRet, 18 * CENT); // we should get 18 in 3 coins BOOST_CHECK_EQUAL(setCoinsRet.size(), 3U); add_coin( 18*CENT); // now we have 5+6+7+8+18+20+30 // and now if we try making 16 cents again, the smaller coins can make 5+6+7 = 18 cents, the same as the next biggest coin, 18 BOOST_CHECK( testWallet.SelectCoinsMinConf(16 * CENT, 1, 1, 0, vCoins, setCoinsRet, nValueRet)); BOOST_CHECK_EQUAL(nValueRet, 18 * CENT); // we should get 18 in 1 coin BOOST_CHECK_EQUAL(setCoinsRet.size(), 1U); // because in the event of a tie, the biggest coin wins // now try making 11 cents. we should get 5+6 BOOST_CHECK( testWallet.SelectCoinsMinConf(11 * CENT, 1, 1, 0, vCoins, setCoinsRet, nValueRet)); BOOST_CHECK_EQUAL(nValueRet, 11 * CENT); BOOST_CHECK_EQUAL(setCoinsRet.size(), 2U); // check that the smallest bigger coin is used add_coin( 1*COIN); add_coin( 2*COIN); add_coin( 3*COIN); add_coin( 4*COIN); // now we have 5+6+7+8+18+20+30+100+200+300+400 = 1094 cents BOOST_CHECK( testWallet.SelectCoinsMinConf(95 * CENT, 1, 1, 0, vCoins, setCoinsRet, nValueRet)); BOOST_CHECK_EQUAL(nValueRet, 1 * COIN); // we should get 1 BTC in 1 coin BOOST_CHECK_EQUAL(setCoinsRet.size(), 1U); BOOST_CHECK( testWallet.SelectCoinsMinConf(195 * CENT, 1, 1, 0, vCoins, setCoinsRet, nValueRet)); BOOST_CHECK_EQUAL(nValueRet, 2 * COIN); // we should get 2 BTC in 1 coin BOOST_CHECK_EQUAL(setCoinsRet.size(), 1U); // empty the wallet and start again, now with fractions of a cent, to test small change avoidance empty_wallet(); add_coin(MIN_CHANGE * 1 / 10); add_coin(MIN_CHANGE * 2 / 10); add_coin(MIN_CHANGE * 3 / 10); add_coin(MIN_CHANGE * 4 / 10); add_coin(MIN_CHANGE * 5 / 10); // try making 1 * MIN_CHANGE from the 1.5 * MIN_CHANGE // we'll get change smaller than MIN_CHANGE whatever happens, so can expect MIN_CHANGE exactly BOOST_CHECK( testWallet.SelectCoinsMinConf(MIN_CHANGE, 1, 1, 0, vCoins, setCoinsRet, nValueRet)); BOOST_CHECK_EQUAL(nValueRet, MIN_CHANGE); // but if we add a bigger coin, small change is avoided add_coin(1111*MIN_CHANGE); // try making 1 from 0.1 + 0.2 + 0.3 + 0.4 + 0.5 + 1111 = 1112.5 BOOST_CHECK( testWallet.SelectCoinsMinConf(1 * MIN_CHANGE, 1, 1, 0, vCoins, setCoinsRet, nValueRet)); BOOST_CHECK_EQUAL(nValueRet, 1 * MIN_CHANGE); // we should get the exact amount // if we add more small coins: add_coin(MIN_CHANGE * 6 / 10); add_coin(MIN_CHANGE * 7 / 10); // and try again to make 1.0 * MIN_CHANGE BOOST_CHECK( testWallet.SelectCoinsMinConf(1 * MIN_CHANGE, 1, 1, 0, vCoins, setCoinsRet, nValueRet)); BOOST_CHECK_EQUAL(nValueRet, 1 * MIN_CHANGE); // we should get the exact amount // run the 'mtgox' test (see http://blockexplorer.com/tx/29a3efd3ef04f9153d47a990bd7b048a4b2d213daaa5fb8ed670fb85f13bdbcf) // they tried to consolidate 10 50k coins into one 500k coin, and ended up with 50k in change empty_wallet(); for (int j = 0; j < 20; j++) add_coin(50000 * COIN); BOOST_CHECK( testWallet.SelectCoinsMinConf(500000 * COIN, 1, 1, 0, vCoins, setCoinsRet, nValueRet)); BOOST_CHECK_EQUAL(nValueRet, 500000 * COIN); // we should get the exact amount BOOST_CHECK_EQUAL(setCoinsRet.size(), 10U); // in ten coins // if there's not enough in the smaller coins to make at least 1 * MIN_CHANGE change (0.5+0.6+0.7 < 1.0+1.0), // we need to try finding an exact subset anyway // sometimes it will fail, and so we use the next biggest coin: empty_wallet(); add_coin(MIN_CHANGE * 5 / 10); add_coin(MIN_CHANGE * 6 / 10); add_coin(MIN_CHANGE * 7 / 10); add_coin(1111 * MIN_CHANGE); BOOST_CHECK( testWallet.SelectCoinsMinConf(1 * MIN_CHANGE, 1, 1, 0, vCoins, setCoinsRet, nValueRet)); BOOST_CHECK_EQUAL(nValueRet, 1111 * MIN_CHANGE); // we get the bigger coin BOOST_CHECK_EQUAL(setCoinsRet.size(), 1U); // but sometimes it's possible, and we use an exact subset (0.4 + 0.6 = 1.0) empty_wallet(); add_coin(MIN_CHANGE * 4 / 10); add_coin(MIN_CHANGE * 6 / 10); add_coin(MIN_CHANGE * 8 / 10); add_coin(1111 * MIN_CHANGE); BOOST_CHECK( testWallet.SelectCoinsMinConf(MIN_CHANGE, 1, 1, 0, vCoins, setCoinsRet, nValueRet)); BOOST_CHECK_EQUAL(nValueRet, MIN_CHANGE); // we should get the exact amount BOOST_CHECK_EQUAL(setCoinsRet.size(), 2U); // in two coins 0.4+0.6 // test avoiding small change empty_wallet(); add_coin(MIN_CHANGE * 5 / 100); add_coin(MIN_CHANGE * 1); add_coin(MIN_CHANGE * 100); // trying to make 100.01 from these three coins BOOST_CHECK(testWallet.SelectCoinsMinConf(MIN_CHANGE * 10001 / 100, 1, 1, 0, vCoins, setCoinsRet, nValueRet)); BOOST_CHECK_EQUAL(nValueRet, MIN_CHANGE * 10105 / 100); // we should get all coins BOOST_CHECK_EQUAL(setCoinsRet.size(), 3U); // but if we try to make 99.9, we should take the bigger of the two small coins to avoid small change BOOST_CHECK(testWallet.SelectCoinsMinConf(MIN_CHANGE * 9990 / 100, 1, 1, 0, vCoins, setCoinsRet, nValueRet)); BOOST_CHECK_EQUAL(nValueRet, 101 * MIN_CHANGE); BOOST_CHECK_EQUAL(setCoinsRet.size(), 2U); // test with many inputs for (CAmount amt=1500; amt < COIN; amt*=10) { empty_wallet(); // Create 676 inputs (= (old MAX_STANDARD_TX_SIZE == 100000) / 148 bytes per input) for (uint16_t j = 0; j < 676; j++) add_coin(amt); BOOST_CHECK(testWallet.SelectCoinsMinConf(2000, 1, 1, 0, vCoins, setCoinsRet, nValueRet)); if (amt - 2000 < MIN_CHANGE) { // needs more than one input: uint16_t returnSize = std::ceil((2000.0 + MIN_CHANGE)/amt); CAmount returnValue = amt * returnSize; BOOST_CHECK_EQUAL(nValueRet, returnValue); BOOST_CHECK_EQUAL(setCoinsRet.size(), returnSize); } else { // one input is sufficient: BOOST_CHECK_EQUAL(nValueRet, amt); BOOST_CHECK_EQUAL(setCoinsRet.size(), 1U); } } // test randomness { empty_wallet(); for (int i2 = 0; i2 < 100; i2++) add_coin(COIN); // picking 50 from 100 coins doesn't depend on the shuffle, // but does depend on randomness in the stochastic approximation code BOOST_CHECK(testWallet.SelectCoinsMinConf(50 * COIN, 1, 6, 0, vCoins, setCoinsRet , nValueRet)); BOOST_CHECK(testWallet.SelectCoinsMinConf(50 * COIN, 1, 6, 0, vCoins, setCoinsRet2, nValueRet)); BOOST_CHECK(!equal_sets(setCoinsRet, setCoinsRet2)); int fails = 0; for (int j = 0; j < RANDOM_REPEATS; j++) { // selecting 1 from 100 identical coins depends on the shuffle; this test will fail 1% of the time // run the test RANDOM_REPEATS times and only complain if all of them fail BOOST_CHECK(testWallet.SelectCoinsMinConf(COIN, 1, 6, 0, vCoins, setCoinsRet , nValueRet)); BOOST_CHECK(testWallet.SelectCoinsMinConf(COIN, 1, 6, 0, vCoins, setCoinsRet2, nValueRet)); if (equal_sets(setCoinsRet, setCoinsRet2)) fails++; } BOOST_CHECK_NE(fails, RANDOM_REPEATS); // add 75 cents in small change. not enough to make 90 cents, // then try making 90 cents. there are multiple competing "smallest bigger" coins, // one of which should be picked at random add_coin(5 * CENT); add_coin(10 * CENT); add_coin(15 * CENT); add_coin(20 * CENT); add_coin(25 * CENT); fails = 0; for (int j = 0; j < RANDOM_REPEATS; j++) { // selecting 1 from 100 identical coins depends on the shuffle; this test will fail 1% of the time // run the test RANDOM_REPEATS times and only complain if all of them fail BOOST_CHECK(testWallet.SelectCoinsMinConf(90*CENT, 1, 6, 0, vCoins, setCoinsRet , nValueRet)); BOOST_CHECK(testWallet.SelectCoinsMinConf(90*CENT, 1, 6, 0, vCoins, setCoinsRet2, nValueRet)); if (equal_sets(setCoinsRet, setCoinsRet2)) fails++; } BOOST_CHECK_NE(fails, RANDOM_REPEATS); } } empty_wallet(); } BOOST_AUTO_TEST_CASE(ApproximateBestSubset) { CoinSet setCoinsRet; CAmount nValueRet; LOCK(testWallet.cs_wallet); empty_wallet(); // Test vValue sort order for (int i = 0; i < 1000; i++) add_coin(1000 * COIN); add_coin(3 * COIN); BOOST_CHECK(testWallet.SelectCoinsMinConf(1003 * COIN, 1, 6, 0, vCoins, setCoinsRet, nValueRet)); BOOST_CHECK_EQUAL(nValueRet, 1003 * COIN); BOOST_CHECK_EQUAL(setCoinsRet.size(), 2U); empty_wallet(); } static void AddKey(CWallet& wallet, const CKey& key) { LOCK(wallet.cs_wallet); wallet.AddKeyPubKey(key, key.GetPubKey()); } BOOST_FIXTURE_TEST_CASE(rescan, TestChain100Setup) { LOCK(cs_main); // Cap last block file size, and mine new block in a new block file. CBlockIndex* const nullBlock = nullptr; CBlockIndex* oldTip = chainActive.Tip(); GetBlockFileInfo(oldTip->GetBlockPos().nFile)->nSize = MAX_BLOCKFILE_SIZE; CreateAndProcessBlock({}, GetScriptForRawPubKey(coinbaseKey.GetPubKey())); CBlockIndex* newTip = chainActive.Tip(); // Verify ScanForWalletTransactions picks up transactions in both the old // and new block files. { CWallet wallet; AddKey(wallet, coinbaseKey); BOOST_CHECK_EQUAL(nullBlock, wallet.ScanForWalletTransactions(oldTip)); BOOST_CHECK_EQUAL(wallet.GetImmatureBalance(), 100 * COIN); } // Prune the older block file. PruneOneBlockFile(oldTip->GetBlockPos().nFile); UnlinkPrunedFiles({oldTip->GetBlockPos().nFile}); // Verify ScanForWalletTransactions only picks transactions in the new block // file. { CWallet wallet; AddKey(wallet, coinbaseKey); BOOST_CHECK_EQUAL(oldTip, wallet.ScanForWalletTransactions(oldTip)); BOOST_CHECK_EQUAL(wallet.GetImmatureBalance(), 50 * COIN); } // Verify importmulti RPC returns failure for a key whose creation time is // before the missing block, and success for a key whose creation time is // after. { CWallet wallet; vpwallets.insert(vpwallets.begin(), &wallet); UniValue keys; keys.setArray(); UniValue key; key.setObject(); key.pushKV("scriptPubKey", HexStr(GetScriptForRawPubKey(coinbaseKey.GetPubKey()))); key.pushKV("timestamp", 0); key.pushKV("internal", UniValue(true)); keys.push_back(key); key.clear(); key.setObject(); CKey futureKey; futureKey.MakeNewKey(true); key.pushKV("scriptPubKey", HexStr(GetScriptForRawPubKey(futureKey.GetPubKey()))); key.pushKV("timestamp", newTip->GetBlockTimeMax() + TIMESTAMP_WINDOW + 1); key.pushKV("internal", UniValue(true)); keys.push_back(key); JSONRPCRequest request; request.params.setArray(); request.params.push_back(keys); UniValue response = importmulti(request); BOOST_CHECK_EQUAL(response.write(), strprintf("[{\"success\":false,\"error\":{\"code\":-1,\"message\":\"Rescan failed for key with creation " "timestamp %d. There was an error reading a block from time %d, which is after or within %d " "seconds of key creation, and could contain transactions pertaining to the key. As a result, " "transactions and coins using this key may not appear in the wallet. This error could be caused " "by pruning or data corruption (see starshipscryptd log for details) and could be dealt with by " "downloading and rescanning the relevant blocks (see -reindex and -rescan " "options).\"}},{\"success\":true}]", 0, oldTip->GetBlockTimeMax(), TIMESTAMP_WINDOW)); vpwallets.erase(vpwallets.begin()); } } // Verify importwallet RPC starts rescan at earliest block with timestamp // greater or equal than key birthday. Previously there was a bug where // importwallet RPC would start the scan at the latest block with timestamp less // than or equal to key birthday. BOOST_FIXTURE_TEST_CASE(importwallet_rescan, TestChain100Setup) { LOCK(cs_main); // Create two blocks with same timestamp to verify that importwallet rescan // will pick up both blocks, not just the first. const int64_t BLOCK_TIME = chainActive.Tip()->GetBlockTimeMax() + 5; SetMockTime(BLOCK_TIME); coinbaseTxns.emplace_back(*CreateAndProcessBlock({}, GetScriptForRawPubKey(coinbaseKey.GetPubKey())).vtx[0]); coinbaseTxns.emplace_back(*CreateAndProcessBlock({}, GetScriptForRawPubKey(coinbaseKey.GetPubKey())).vtx[0]); // Set key birthday to block time increased by the timestamp window, so // rescan will start at the block time. const int64_t KEY_TIME = BLOCK_TIME + TIMESTAMP_WINDOW; SetMockTime(KEY_TIME); coinbaseTxns.emplace_back(*CreateAndProcessBlock({}, GetScriptForRawPubKey(coinbaseKey.GetPubKey())).vtx[0]); // Import key into wallet and call dumpwallet to create backup file. { CWallet wallet; LOCK(wallet.cs_wallet); wallet.mapKeyMetadata[coinbaseKey.GetPubKey().GetID()].nCreateTime = KEY_TIME; wallet.AddKeyPubKey(coinbaseKey, coinbaseKey.GetPubKey()); JSONRPCRequest request; request.params.setArray(); request.params.push_back((pathTemp / "wallet.backup").string()); vpwallets.insert(vpwallets.begin(), &wallet); ::dumpwallet(request); } // Call importwallet RPC and verify all blocks with timestamps >= BLOCK_TIME // were scanned, and no prior blocks were scanned. { CWallet wallet; JSONRPCRequest request; request.params.setArray(); request.params.push_back((pathTemp / "wallet.backup").string()); vpwallets[0] = &wallet; ::importwallet(request); BOOST_CHECK_EQUAL(wallet.mapWallet.size(), 3); BOOST_CHECK_EQUAL(coinbaseTxns.size(), 103); for (size_t i = 0; i < coinbaseTxns.size(); ++i) { bool found = wallet.GetWalletTx(coinbaseTxns[i].GetHash()); bool expected = i >= 100; BOOST_CHECK_EQUAL(found, expected); } } SetMockTime(0); vpwallets.erase(vpwallets.begin()); } // Check that GetImmatureCredit() returns a newly calculated value instead of // the cached value after a MarkDirty() call. // // This is a regression test written to verify a bugfix for the immature credit // function. Similar tests probably should be written for the other credit and // debit functions. BOOST_FIXTURE_TEST_CASE(coin_mark_dirty_immature_credit, TestChain100Setup) { CWallet wallet; CWalletTx wtx(&wallet, MakeTransactionRef(coinbaseTxns.back())); LOCK2(cs_main, wallet.cs_wallet); wtx.hashBlock = chainActive.Tip()->GetBlockHash(); wtx.nIndex = 0; // Call GetImmatureCredit() once before adding the key to the wallet to // cache the current immature credit amount, which is 0. BOOST_CHECK_EQUAL(wtx.GetImmatureCredit(), 0); // Invalidate the cached value, add the key, and make sure a new immature // credit amount is calculated. wtx.MarkDirty(); wallet.AddKeyPubKey(coinbaseKey, coinbaseKey.GetPubKey()); BOOST_CHECK_EQUAL(wtx.GetImmatureCredit(), 50*COIN); } static int64_t AddTx(CWallet& wallet, uint32_t lockTime, int64_t mockTime, int64_t blockTime) { CMutableTransaction tx; tx.nLockTime = lockTime; SetMockTime(mockTime); CBlockIndex* block = nullptr; if (blockTime > 0) { auto inserted = mapBlockIndex.emplace(GetRandHash(), new CBlockIndex); assert(inserted.second); const uint256& hash = inserted.first->first; block = inserted.first->second; block->nTime = blockTime; block->phashBlock = &hash; } CWalletTx wtx(&wallet, MakeTransactionRef(tx)); if (block) { wtx.SetMerkleBranch(block, 0); } wallet.AddToWallet(wtx); return wallet.mapWallet.at(wtx.GetHash()).nTimeSmart; } // Simple test to verify assignment of CWalletTx::nSmartTime value. Could be // expanded to cover more corner cases of smart time logic. BOOST_AUTO_TEST_CASE(ComputeTimeSmart) { CWallet wallet; // New transaction should use clock time if lower than block time. BOOST_CHECK_EQUAL(AddTx(wallet, 1, 100, 120), 100); // Test that updating existing transaction does not change smart time. BOOST_CHECK_EQUAL(AddTx(wallet, 1, 200, 220), 100); // New transaction should use clock time if there's no block time. BOOST_CHECK_EQUAL(AddTx(wallet, 2, 300, 0), 300); // New transaction should use block time if lower than clock time. BOOST_CHECK_EQUAL(AddTx(wallet, 3, 420, 400), 400); // New transaction should use latest entry time if higher than // min(block time, clock time). BOOST_CHECK_EQUAL(AddTx(wallet, 4, 500, 390), 400); // If there are future entries, new transaction should use time of the // newest entry that is no more than 300 seconds ahead of the clock time. BOOST_CHECK_EQUAL(AddTx(wallet, 5, 50, 600), 300); // Reset mock time for other tests. SetMockTime(0); } BOOST_AUTO_TEST_CASE(LoadReceiveRequests) { CTxDestination dest = CKeyID(); pwalletMain->AddDestData(dest, "misc", "val_misc"); pwalletMain->AddDestData(dest, "rr0", "val_rr0"); pwalletMain->AddDestData(dest, "rr1", "val_rr1"); auto values = pwalletMain->GetDestValues("rr"); BOOST_CHECK_EQUAL(values.size(), 2); BOOST_CHECK_EQUAL(values[0], "val_rr0"); BOOST_CHECK_EQUAL(values[1], "val_rr1"); } class ListCoinsTestingSetup : public TestChain100Setup { public: ListCoinsTestingSetup() { CreateAndProcessBlock({}, GetScriptForRawPubKey(coinbaseKey.GetPubKey())); ::bitdb.MakeMock(); wallet.reset(new CWallet(std::unique_ptr<CWalletDBWrapper>(new CWalletDBWrapper(&bitdb, "wallet_test.dat")))); bool firstRun; wallet->LoadWallet(firstRun); AddKey(*wallet, coinbaseKey); wallet->ScanForWalletTransactions(chainActive.Genesis()); } ~ListCoinsTestingSetup() { wallet.reset(); ::bitdb.Flush(true); ::bitdb.Reset(); } CWalletTx& AddTx(CRecipient recipient) { CWalletTx wtx; CReserveKey reservekey(wallet.get()); CAmount fee; int changePos = -1; std::string error; CCoinControl dummy; BOOST_CHECK(wallet->CreateTransaction({recipient}, wtx, reservekey, fee, changePos, error, dummy)); CValidationState state; BOOST_CHECK(wallet->CommitTransaction(wtx, reservekey, nullptr, state)); auto it = wallet->mapWallet.find(wtx.GetHash()); BOOST_CHECK(it != wallet->mapWallet.end()); CreateAndProcessBlock({CMutableTransaction(*it->second.tx)}, GetScriptForRawPubKey(coinbaseKey.GetPubKey())); it->second.SetMerkleBranch(chainActive.Tip(), 1); return it->second; } std::unique_ptr<CWallet> wallet; }; BOOST_FIXTURE_TEST_CASE(ListCoins, ListCoinsTestingSetup) { std::string coinbaseAddress = coinbaseKey.GetPubKey().GetID().ToString(); LOCK2(cs_main, wallet->cs_wallet); // Confirm ListCoins initially returns 1 coin grouped under coinbaseKey // address. auto list = wallet->ListCoins(); BOOST_CHECK_EQUAL(list.size(), 1); BOOST_CHECK_EQUAL(boost::get<CKeyID>(list.begin()->first).ToString(), coinbaseAddress); BOOST_CHECK_EQUAL(list.begin()->second.size(), 1); // Check initial balance from one mature coinbase transaction. BOOST_CHECK_EQUAL(50 * COIN, wallet->GetAvailableBalance()); // Add a transaction creating a change address, and confirm ListCoins still // returns the coin associated with the change address underneath the // coinbaseKey pubkey, even though the change address has a different // pubkey. AddTx(CRecipient{GetScriptForRawPubKey({}), 1 * COIN, false /* subtract fee */}); list = wallet->ListCoins(); BOOST_CHECK_EQUAL(list.size(), 1); BOOST_CHECK_EQUAL(boost::get<CKeyID>(list.begin()->first).ToString(), coinbaseAddress); BOOST_CHECK_EQUAL(list.begin()->second.size(), 2); // Lock both coins. Confirm number of available coins drops to 0. std::vector<COutput> available; wallet->AvailableCoins(available); BOOST_CHECK_EQUAL(available.size(), 2); for (const auto& group : list) { for (const auto& coin : group.second) { wallet->LockCoin(COutPoint(coin.tx->GetHash(), coin.i)); } } wallet->AvailableCoins(available); BOOST_CHECK_EQUAL(available.size(), 0); // Confirm ListCoins still returns same result as before, despite coins // being locked. list = wallet->ListCoins(); BOOST_CHECK_EQUAL(list.size(), 1); BOOST_CHECK_EQUAL(boost::get<CKeyID>(list.begin()->first).ToString(), coinbaseAddress); BOOST_CHECK_EQUAL(list.begin()->second.size(), 2); } BOOST_AUTO_TEST_SUITE_END()
[ "khryptor@starshipcoin.com" ]
khryptor@starshipcoin.com
e58bc7187aeace46ade77bf0662b0b2af539723e
4623f7baa370845e384d2b613a4c1be4bfe53ab3
/planar_rgb_pose/planar_rgb_pose_estimator.h
9e29200828d498b542ea336ce2ffc8f0d0b3c840
[]
no_license
EricCousineau-TRI/tri_exp
97a9f65f4232cdca55de2606f17ec4fe5004de6c
6ca5b13451833907de9cce26bb869ff6ece471ac
refs/heads/master
2021-01-16T18:22:38.899595
2017-08-11T21:49:29
2017-08-11T21:49:29
100,066,964
0
0
null
null
null
null
UTF-8
C++
false
false
721
h
#include "planar_rgb_model.h" #include <memory> // This class loads a rgb template and a feature detector to do template matching. // KNN matching is used. Then a rigid transformation is estimated. // Todo (Jiaji): right now only takes orb feature. Use others later. // Provides interface to estimate pose given a query image. class PlanarRGBPoseEstimator{ public: PlanarRGBPoseEstimator(cv::Ptr<cv::cuda::DescriptorMatcher> matcher, double nn_match_ratio = 0.8); bool EstimatePlanarPose(const cv::Mat& image, cv::Ptr<cv::cuda::ORB> orb_detector, PlanarRGBModel& model_template, Eigen::Isometry2d* pose_est); private: double nn_match_ratio_; cv::Ptr<cv::cuda::DescriptorMatcher> matcher_; };
[ "robinzhou55@gmail.com" ]
robinzhou55@gmail.com
370ab3b36a1e8b979e906efe3b23b3a9688cfb20
43a54d76227b48d851a11cc30bbe4212f59e1154
/mps/src/v20190612/model/EditMediaTask.cpp
9fe7531fef679d8daad6f060c831ece2991943e0
[ "Apache-2.0" ]
permissive
make1122/tencentcloud-sdk-cpp
175ce4d143c90d7ea06f2034dabdb348697a6c1c
2af6954b2ee6c9c9f61489472b800c8ce00fb949
refs/heads/master
2023-06-04T03:18:47.169750
2021-06-18T03:00:01
2021-06-18T03:00:01
null
0
0
null
null
null
null
UTF-8
C++
false
false
7,113
cpp
/* * Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <tencentcloud/mps/v20190612/model/EditMediaTask.h> using TencentCloud::CoreInternalOutcome; using namespace TencentCloud::Mps::V20190612::Model; using namespace std; EditMediaTask::EditMediaTask() : m_taskIdHasBeenSet(false), m_statusHasBeenSet(false), m_errCodeHasBeenSet(false), m_messageHasBeenSet(false), m_inputHasBeenSet(false), m_outputHasBeenSet(false) { } CoreInternalOutcome EditMediaTask::Deserialize(const rapidjson::Value &value) { string requestId = ""; if (value.HasMember("TaskId") && !value["TaskId"].IsNull()) { if (!value["TaskId"].IsString()) { return CoreInternalOutcome(Error("response `EditMediaTask.TaskId` IsString=false incorrectly").SetRequestId(requestId)); } m_taskId = string(value["TaskId"].GetString()); m_taskIdHasBeenSet = true; } if (value.HasMember("Status") && !value["Status"].IsNull()) { if (!value["Status"].IsString()) { return CoreInternalOutcome(Error("response `EditMediaTask.Status` IsString=false incorrectly").SetRequestId(requestId)); } m_status = string(value["Status"].GetString()); m_statusHasBeenSet = true; } if (value.HasMember("ErrCode") && !value["ErrCode"].IsNull()) { if (!value["ErrCode"].IsInt64()) { return CoreInternalOutcome(Error("response `EditMediaTask.ErrCode` IsInt64=false incorrectly").SetRequestId(requestId)); } m_errCode = value["ErrCode"].GetInt64(); m_errCodeHasBeenSet = true; } if (value.HasMember("Message") && !value["Message"].IsNull()) { if (!value["Message"].IsString()) { return CoreInternalOutcome(Error("response `EditMediaTask.Message` IsString=false incorrectly").SetRequestId(requestId)); } m_message = string(value["Message"].GetString()); m_messageHasBeenSet = true; } if (value.HasMember("Input") && !value["Input"].IsNull()) { if (!value["Input"].IsObject()) { return CoreInternalOutcome(Error("response `EditMediaTask.Input` is not object type").SetRequestId(requestId)); } CoreInternalOutcome outcome = m_input.Deserialize(value["Input"]); if (!outcome.IsSuccess()) { outcome.GetError().SetRequestId(requestId); return outcome; } m_inputHasBeenSet = true; } if (value.HasMember("Output") && !value["Output"].IsNull()) { if (!value["Output"].IsObject()) { return CoreInternalOutcome(Error("response `EditMediaTask.Output` is not object type").SetRequestId(requestId)); } CoreInternalOutcome outcome = m_output.Deserialize(value["Output"]); if (!outcome.IsSuccess()) { outcome.GetError().SetRequestId(requestId); return outcome; } m_outputHasBeenSet = true; } return CoreInternalOutcome(true); } void EditMediaTask::ToJsonObject(rapidjson::Value &value, rapidjson::Document::AllocatorType& allocator) const { if (m_taskIdHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "TaskId"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_taskId.c_str(), allocator).Move(), allocator); } if (m_statusHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "Status"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_status.c_str(), allocator).Move(), allocator); } if (m_errCodeHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "ErrCode"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, m_errCode, allocator); } if (m_messageHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "Message"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_message.c_str(), allocator).Move(), allocator); } if (m_inputHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "Input"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(rapidjson::kObjectType).Move(), allocator); m_input.ToJsonObject(value[key.c_str()], allocator); } if (m_outputHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "Output"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(rapidjson::kObjectType).Move(), allocator); m_output.ToJsonObject(value[key.c_str()], allocator); } } string EditMediaTask::GetTaskId() const { return m_taskId; } void EditMediaTask::SetTaskId(const string& _taskId) { m_taskId = _taskId; m_taskIdHasBeenSet = true; } bool EditMediaTask::TaskIdHasBeenSet() const { return m_taskIdHasBeenSet; } string EditMediaTask::GetStatus() const { return m_status; } void EditMediaTask::SetStatus(const string& _status) { m_status = _status; m_statusHasBeenSet = true; } bool EditMediaTask::StatusHasBeenSet() const { return m_statusHasBeenSet; } int64_t EditMediaTask::GetErrCode() const { return m_errCode; } void EditMediaTask::SetErrCode(const int64_t& _errCode) { m_errCode = _errCode; m_errCodeHasBeenSet = true; } bool EditMediaTask::ErrCodeHasBeenSet() const { return m_errCodeHasBeenSet; } string EditMediaTask::GetMessage() const { return m_message; } void EditMediaTask::SetMessage(const string& _message) { m_message = _message; m_messageHasBeenSet = true; } bool EditMediaTask::MessageHasBeenSet() const { return m_messageHasBeenSet; } EditMediaTaskInput EditMediaTask::GetInput() const { return m_input; } void EditMediaTask::SetInput(const EditMediaTaskInput& _input) { m_input = _input; m_inputHasBeenSet = true; } bool EditMediaTask::InputHasBeenSet() const { return m_inputHasBeenSet; } EditMediaTaskOutput EditMediaTask::GetOutput() const { return m_output; } void EditMediaTask::SetOutput(const EditMediaTaskOutput& _output) { m_output = _output; m_outputHasBeenSet = true; } bool EditMediaTask::OutputHasBeenSet() const { return m_outputHasBeenSet; }
[ "tencentcloudapi@tenent.com" ]
tencentcloudapi@tenent.com
6ecd57bbd1268701c5b4e836c8f4603287d11fb4
c4d312876a4eeb2aea8cec7b971a802ab49640d8
/LearnOpenglGPGPU/HistogramEqualizationTask.h
e3cc2afa0f494786481d424df896feb66291332a
[]
no_license
cjj19970505/LearnOpenglGPGPU
510709a22cae43395a927d750f109ea94386cd28
3612734252ccee80675532a6c3c671d1fce20f41
refs/heads/master
2021-04-18T21:30:57.004604
2018-04-05T14:59:45
2018-04-05T14:59:45
126,440,948
0
0
null
null
null
null
GB18030
C++
false
false
3,306
h
#pragma once #include "ComputeTask.h" #include "ComputeShader.h" #include <glad\glad.h> #include "HistogramComputeTask.h" ///输入一副图像RGB,输出直方图均衡化的结果(只有灰度) class HistogramEqualizationTask : public ComputeTask { private: GLuint summedHistogramArrayId = 0; //GL_TEXTURE_2D, GL_RED, GL_R32F 灰度图!! GLuint sourceTextureId = 0; GLuint outputTextureId = 0; HistogramComputeTask *histogramComputeTask; //这货是用来将直方图做一个求和的 ComputeShader *histogramSummationComputeShader; ComputeShader *histogramEqualizationShader; int width = 0; int height = 0; public: HistogramEqualizationTask(); ~HistogramEqualizationTask(); bool isConfigCompleted() { if (glIsTexture(sourceTextureId) && glIsTexture(outputTextureId)) { return histogramComputeTask->isConfigCompleted(); } else { return false; } } void setTexture(GLuint textureId, int width, int height, bool deleteOutputTexture = true) { this->sourceTextureId = textureId; this->width = width; this->height = height; histogramComputeTask->setSourceTexture(textureId, width, height); if (deleteOutputTexture && glIsTexture(this->outputTextureId)) { glDeleteTextures(1, &outputTextureId); outputTextureId = 0; } GLuint outputImage; glGenTextures(1, &outputImage); glBindTexture(GL_TEXTURE_2D, outputImage); glTexStorage2D(GL_TEXTURE_2D, 1, GL_R32F, width, height); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glBindTexture(GL_TEXTURE_2D, 0); this->outputTextureId = outputImage; } GLuint getOuputTextureId() { return outputTextureId; } bool execute() { if (!isConfigCompleted()) { return false; } bool histogramSucceed = histogramComputeTask->execute(); if (!histogramSucceed) { return false; } histogramSummationComputeShader->use(); glBindImageTexture(0, histogramComputeTask->getHistogramArrayId(), 0, GL_FALSE, 0, GL_READ_ONLY, GL_R32UI); glBindImageTexture(1, summedHistogramArrayId, 0, GL_FALSE, 0, GL_READ_WRITE, GL_R32UI); glDispatchCompute(256, 1, 1); histogramEqualizationShader->use(); glBindImageTexture(0, summedHistogramArrayId, 0, GL_FALSE, 0, GL_READ_ONLY, GL_R32UI); glBindImageTexture(1, sourceTextureId, 0, GL_FALSE, 0, GL_READ_ONLY, GL_R32F); glBindImageTexture(2, outputTextureId, 0, GL_FALSE, 0, GL_READ_WRITE, GL_R32F); histogramEqualizationShader->setUvec2("app.imageSize", glm::uvec2(width, height)); glDispatchCompute(width/32+1, height/32+1, 1); return true; } }; HistogramEqualizationTask::HistogramEqualizationTask() { histogramComputeTask = new HistogramComputeTask(); histogramEqualizationShader = new ComputeShader("HistogramEqualizationComputeShader.glsl"); histogramSummationComputeShader = new ComputeShader("HistogramSummationComputeShader.glsl"); glGenTextures(1, &summedHistogramArrayId); glBindTexture(GL_TEXTURE_1D, summedHistogramArrayId); glTexStorage1D(GL_TEXTURE_1D, 1, GL_R32UI, 256); glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glBindTexture(GL_TEXTURE_1D, 0); } HistogramEqualizationTask::~HistogramEqualizationTask() { }
[ "cjj19970505@live.cn" ]
cjj19970505@live.cn
0a453a6e70d45e5e8e9e771b460e146ddd5594ea
ca71a8028ae57cac5e8f9b10fa0db3333efec086
/ACC sharedmemory exposer/SDK/ACC_SprintToEndurance_parameters.hpp
955d84336d72c66a02e1b6f6496c9ec0094ce8cb
[]
no_license
Sparten/ACC
42d08b17854329c245d9543e5184888d119251c1
3ee1e5c032dcd508e5913539feb575f42d74365e
refs/heads/master
2020-03-28T20:47:48.649504
2018-10-19T20:47:39
2018-10-19T20:47:39
149,102,523
0
0
null
null
null
null
UTF-8
C++
false
false
383
hpp
#pragma once // Assetto Corsa Competizione (0.1.0) SDK #ifdef _MSC_VER #pragma pack(push, 0x8) #endif #include "ACC_SprintToEndurance_classes.hpp" namespace SDK { //--------------------------------------------------------------------------- //Parameters //--------------------------------------------------------------------------- } #ifdef _MSC_VER #pragma pack(pop) #endif
[ "sportcorp@hotmail.com" ]
sportcorp@hotmail.com
a42d49c460226ee30735a2ba60eae47047ff2941
ab6feef7a398abf812bc23e19d71bdb3b6d27710
/c++/Others/Final Crisis.cpp
ff636442f588d17b8b4f4fbb2f7398a4bb2fb7f7
[]
no_license
VimForLaNie/C-Coding-Practice
90a6ad03008838b8d3da11a2c05f716f5425738d
42c6a7fa4a88352d8e3252cd717bf67d1a8fa42f
refs/heads/master
2023-03-24T09:38:45.464439
2021-03-07T12:24:40
2021-03-07T12:24:40
210,138,389
0
0
null
null
null
null
UTF-8
C++
false
false
925
cpp
#include <bits/stdc++.h> using namespace std; int n,m,q,a,b,c,d,k,i,j,i_b,i_h; vector <int> bio; vector <int> sum_bio; vector <int> his; vector <int> sum_his; int temp; int main(){ cin >> n >> m >> q; for(i = 0; i < n; i++){ cin >> temp; bio.push_back(temp); if(i > 1){ sum_bio.push_back(bio[i] + sum_bio[i-1]); }else{ sum_bio.push_back(temp); } cout << sum_bio[i] << " " << endl; } for(i = 0; i < m; i++){ cin >> temp; his.push_back(temp); if(i > 1){ sum_his.push_back(his[i] + sum_his[i-1]); }else{ sum_his.push_back(temp); } cout << sum_his[i] << " " << endl; } for(i = 0; i < q; i++){ cin >> a >> b >> c >> d >> k; i_b = a - 1; i_h = b - 1; for(j = 0; j < k; j++){ if(sum_bio[i_b] < sum_his[i_h]){ i_b++; } else{ i_h++; } } if(sum_bio[i_b] > sum_his[i_h]){ cout << sum_bio[i_b] << endl; } else{ cout << sum_his[i_h] << endl; } } }
[ "new.giant098@gmail.com" ]
new.giant098@gmail.com
7c6522f38cf902f9b0a4b71b137cbad463584fae
a8f4ba1a8144d461e4bfe7c41e674615de10ee34
/client/Classes/View/Layers/GameOverLayer/GameOverLayer.h
e267baaf3d2995799763d02e9f001f0c2caaaca8
[ "Apache-2.0" ]
permissive
gdtdftdqtd/BaseWar
0e8ff1e9a8809b32bfe11474da5aa94f8b556fe3
c1c98a9f431ebca7944a55495938da0334319afb
refs/heads/master
2023-03-08T13:00:20.847125
2023-02-12T15:05:40
2023-02-12T15:05:40
42,637,417
0
0
Apache-2.0
2023-02-12T15:05:41
2015-09-17T05:47:29
C++
UTF-8
C++
false
false
572
h
#ifndef __GAMEOVERLAYER_H__ #define __GAMEOVERLAYER_H__ #include "cocos2d.h" class GameOverLayer: public cocos2d::CCLayerColor { public: // Here's a difference. Method 'init' in cocos2d-x returns bool, instead of returning 'id' in cocos2d-iphone virtual bool init(); // a selector callback void leaveTouched(cocos2d::CCObject* pSender); virtual void ccTouchesBegan(cocos2d::CCSet * pTouches, cocos2d::CCEvent * pEvent); // implement the "static node()" method manually CREATE_FUNC (GameOverLayer); void setWon(bool won); }; #endif // __GAMEOVERLAYER_H__
[ "klaus.plankensteiner@gmx.at" ]
klaus.plankensteiner@gmx.at
b5168d6063ff06156d3130361484d59099a795a1
1ca4630d295872283280b5f953ffb4fc2b69d8b3
/PRIORITY_QUEUE-MIN_HEAP/priority_queue-min_heap.h
3f20217aa481426c80ea111c67482642a5a9e9b4
[]
no_license
Amit-Khobragade/Data-Structures-in-cpp
4759d3daca425bd0862a841b974673d978462344
a895d1cd0a6b0dbcd47f78eb80a0b94ec8ffa8fa
refs/heads/master
2022-11-28T04:16:27.288645
2020-07-17T12:25:24
2020-07-17T12:25:24
280,367,576
0
0
null
null
null
null
UTF-8
C++
false
false
4,592
h
#pragma once #include <iostream> #include <vector> //single queue element with priority and some overloaded //operator for cleaner code template<typename T> struct queue_element { T key; int priority; queue_element( T _key = 0, int _priority = 0 ) :key{ _key }, priority{ _priority } {} bool operator<( const queue_element& other ) { return (this->priority < other.priority); } bool operator>( const queue_element& other ) { return (this->priority > other.priority); } bool operator>=( const queue_element& other ) { return (this->priority >= other.priority); } bool operator<=( const queue_element& other ) { return (this->priority <= other.priority); } }; //priority queue defined as an //binary tree template<typename T> class Priority_Queue { public: //three constructors //default constructor Priority_Queue() = default; //custom constructor Priority_Queue( queue_element<T>& _first_elem ) { queue.push_back( _first_elem ); } //copy constructor Priority_Queue( const Priority_Queue<T>& other ) :queue{ other.queue } { for (int i = 0; i < other.queue.size(); ++i) queue.push_back( other.queue.at( i ) ); } int find( T key, int start_pt = 0 ) const { if (!(start_pt < size() && start_pt >= 0)) throw "out_of_range"; if (queue.at( start_pt ).key == key) return start_pt; int left{ left_child( start_pt ) }, right{ right_child( start_pt ) }; int result{ -1 }; if (left != -1) result = find( key, left ); if (right != -1 && result == -1) result = find( key, right ); return result; //recurring functions makes the code readable //but increases the load make sure you have a proper //data structure like binary tree which reduces resource //cost and time taken } bool change_priority( const T& key_to_change, const int& new_value ) { int i = find( key_to_change ); if (i == -1) return false; queue.at( i ).priority = new_value; while (i > 0 && queue.at( i ) <= queue.at( parent( i ) )) { std::swap( queue.at( i ), queue.at( parent( i ) ) ); i = parent( i ); } for (; i == -1 || i == -2; i = family_sort( i )); //sorting upwards and downwards after a sort } friend bool contains( const Priority_Queue<T>& _queue, T& to_find ) { try { _queue.find( to_find ); return true; } catch (std::string& ex) { return false; } } bool insert( queue_element<T>& to_insert ) { queue.push_back( to_insert ); int i{ size() - 1 }; while (i > 0 && queue.at( i ) <= queue.at( parent( i ) )) { std::swap( queue.at( i ), queue.at( parent( i ) ) ); i = parent( i ); } return true; //sorting on insertion and deletion makes the //queue maintainance easy and less heavy //on time and resources } inline queue_element<T> top() { if (size() == 0) throw "no elements"; return queue.at( 0 ); } void pop() { std::swap( queue.at( 0 ), queue.at( (size() - 1) ) ); queue.pop_back(); for (int j = 0; j != -1 && j != -2; j = family_sort( j )); //uses the family sort function(line 62) //for the easy arrangement } inline queue_element<T>& at( int i ) { return queue.at( i ); } inline void min_heapify() { sort_all( 0 ); } inline int size() const { return queue.size(); } private: std::vector<queue_element<T>> queue; inline void sort_all( int i = 0 ) { int left{ left_child( i ) }, right{ right_child( i ) }; int j = family_sort( i ); if (j == -2) return; if (left != -1) sort_all( left ); if (right != -1) sort_all( right ); } inline int family_sort( int _parent ) { if (!(_parent < size() && _parent >= 0)) return -1; int left{ left_child( _parent ) }; int right{ right_child( _parent ) }; int j{ -1 }; if (left != -1 && right != -1) j = ((queue.at( left ) < queue.at( right )) ? left : right); else if (left != -1) j = left; else return -2; if (j != -1 && (queue.at( _parent ) > queue.at( j ))) { std::swap( queue.at( _parent ), queue.at( j ) ); return j; } return -1; //if returned value is =-1 then nodes exists below the current parent //but the current family is sorted //if returned value is =-2 then the current node is the last parent //and has no child } inline int parent( int i ) const { int temp = ((i % 2 == 0) ? ((i - 2) / 2) : ((i - 1) / 2)); return ((temp < size() && temp >= 0) ? temp : (-1)); } inline int left_child( int i ) const { int temp = 2 * i + 1; return ((temp < size() && temp >= 0) ? temp : (-1)); } inline int right_child( int i ) const { int temp = 2 * i + 2; return ((temp < size() && temp >= 0) ? temp : (-1)); } };
[ "amitmusicstar@gmail.com" ]
amitmusicstar@gmail.com
be46bdcb3ff03c4d80cf2256940f7047e3a8c8fa
d68065af759b97bc2b078a893cd88a894e67a105
/src/binstats.hpp
37fdd7c05c20ae48a1ec97db0b27ec155ec99f12
[]
no_license
daniel-starke/binstats
3fa27a701ed3269356186dd4832c70f1240a56b4
5ead93b1dfdd0193ba74094d37276ef1b2235825
refs/heads/master
2023-05-04T19:55:39.257305
2023-04-22T08:25:39
2023-04-22T08:25:39
112,926,633
0
0
null
null
null
null
UTF-8
C++
false
false
247
hpp
/** * @file binstats.hpp * @author Daniel Starke * @copyright Copyright 2017-2023 Daniel Starke * @date 2017-12-01 * @version 2017-12-01 */ #ifndef __BINSTATS_HPP__ #define __BINSTATS_HPP__ #include <FL/Fl.H> #endif /* __BINSTATS_HPP__ */
[ "daniel-email@gmx.net" ]
daniel-email@gmx.net
281e5f0713a20d3e0f5abeea5703f68b6314a27f
43e8ddb15cbc59b871f10cc83395480a381c799b
/open_set.cpp
e9f0a3c08f7425ec35d5b75863cc676acff57638
[]
no_license
HarindiP/AdvancedRobotics
3d786a467ea0b99ffb98b0521055bacbe9b04c6b
a670bf011fd4694baeac8f4388cf49fa1db000ed
refs/heads/master
2020-07-14T11:51:14.711076
2019-09-11T11:36:36
2019-09-11T11:36:36
205,313,375
0
0
null
2019-11-27T06:34:46
2019-08-30T05:49:32
C++
UTF-8
C++
false
false
2,344
cpp
#include "astar_path_planner/open_set.h" #include <limits> #include <ros/ros.h> namespace astar_path_planner { void OpenSet::push(const Node& n) { nodes_.push_back(n); } Node OpenSet::pop(double heuristic_cost_weight) { int index = 0; //saves the id // double best_combined_cost = nodes_[0].cost + ( nodes_[0].heuristic_cost * heuristic_cost_weight ; //saves the cost double lowest_combined_cost = std::numeric_limits<double>::max(); int temp = 0; // Find the best node in "nodes_" // Save the index into "index" and it will be removed from "nodes_" and returned // You need to compare combined costs: the cost of the node + (heuristic cost * weight) // Use "heuristic_cost_weight" to calculate the combined cost so it can be modified later // YOUR CODE HERE // for loop that goes throght all values in the vector and try to get the node with the lowest heuristic cost for (int i = 0 ; i < ( sizeof(nodes_)) ; i++) { double combined = nodes_[i].cost + ( nodes_[i].heuristic_cost * heuristic_cost_weight); if ( combined < lowest_combined_cost ) { lowest_combined_cost = combined; index = i ; } } // YOU DON'T NEED TO MODIFY ANYTHING AFTER THIS LINE // Copy the node Node n = nodes_[index]; // Overwrite the node with the node at the end of the vector nodes_[index] = nodes_.back(); // Delete the node at the end of the vector nodes_.pop_back(); // Return the copy return n; } bool OpenSet::contains(int id) { // Returns true if the node is in nodes_ for (const auto& n : nodes_) { if (n.id == id) { return true; } } return false; } void OpenSet::update(const Node& n) { // Find node "n" in "nodes_" // If the cost of node "n" is less than the cost of the node already in the open set, replace it // YOUR CODE HERE for (auto& a : nodes_) { if ( a.id == n.id) { if (a.cost > n.cost) { //this line might be wrong a = n ; } } } } bool OpenSet::empty() { return nodes_.empty(); } const std::vector<Node>& OpenSet::getNodes() { return nodes_; } std::ostream& operator<<(std::ostream& os, const OpenSet& open_set) { os << "\n\nOpen set:" << std::endl; for (const auto& n : open_set.nodes_) { os << n; } return os; } } // namespace astar_path_planner
[ "noreply@github.com" ]
noreply@github.com
cf91ff6b2656656e64c75d5c3ce97e8376962be8
dbaa6e4666f52806c661379e4a67906bbf547b22
/test/exampleTest.cpp
fb9c25578d1220c61f48e81df8ff451230c1c89d
[ "BSD-2-Clause" ]
permissive
andy-c-jones/cpp-http-service
0aeec04fd90b7029569177c7884dbc8f3ab10a14
c81de2d4b5f4c031e4a16562882d570fa00239da
refs/heads/master
2021-05-06T19:42:14.106696
2017-11-29T16:29:36
2017-11-29T16:29:36
112,173,167
1
0
null
null
null
null
UTF-8
C++
false
false
365
cpp
#include <gmock/gmock.h> #include "../src/service/Example.h" using ::testing::_; class ExampleTest : public ::testing::Test { }; TEST(ExampleTest, test_something) { auto something = std::make_unique<Example>(); crow::json::wvalue actual; actual = something->doSomething(); EXPECT_EQ(crow::json::dump(actual), "{\"message\":\"Hello world\"}"); };
[ "acjones@protonmail.com" ]
acjones@protonmail.com
6096a7f4d082ad33f1250725be448b69988abd06
924c3b051dacc55d5d561572300368b1cc038bca
/cpp/testutils/src/core/OperationTestUtils.cpp
4732feb027ecedeaed543c7133fba9ae60e989e4
[ "MIT" ]
permissive
rohitphogat19/spectrum
ce803dcf5ed6ad28b4a680ac6653bbd4fa526758
71fa694d66de3513d57ba9b5afd620e8a0bdc571
refs/heads/master
2021-06-16T10:39:04.181349
2021-03-04T12:58:10
2021-03-04T12:58:10
172,004,814
0
0
MIT
2019-02-22T06:12:04
2019-02-22T06:12:01
null
UTF-8
C++
false
false
1,195
cpp
// Copyright (c) Facebook, Inc. and its affiliates. // // This source code is licensed under the MIT license found in the // LICENSE file in the root directory of this source tree. #include "OperationTestUtils.h" #include <spectrum/testutils/image/SpecificationTestUtils.h> namespace facebook { namespace spectrum { namespace core { namespace testutils { Operation::Parameters makeDummyOperationParameters( const image::Format& imageFormat) { return Operation::Parameters{ .inputImageSpecification = image::testutils::makeDummyImageSpecification(), .outputImageFormat = imageFormat, .transformations = {}, }; } Operation makeOperationFromIO(io::IImageSource& source, io::IImageSink& sink) { return Operation{ .io = { .source = source, .sink = sink, }, .codecs = {.decompressorProvider = {.format = image::formats::Bitmap}, .compressorProvider = {.format = image::formats::Bitmap}}, .parameters = makeDummyOperationParameters(), .configuration = Configuration(), }; } } // namespace testutils } // namespace core } // namespace spectrum } // namespace facebook
[ "facebook-github-bot@users.noreply.github.com" ]
facebook-github-bot@users.noreply.github.com
c2b3e29e8278468c39c89a0095917c736dca478a
0e56ee6fdfe0dd3dad736e608c2e823e8bbed521
/egen/TestHarness/Reference/inc/FlatTaxrateLoad.h
c134ea9b531109a0821b33fe063c2201ff9f77e7
[ "Artistic-1.0" ]
permissive
dotweiba/dbt5
d510ab80e979704db71b6d25a9cd7a1a754640b4
39e23b0a0bfd4dfcb80cb2231270324f6bbf4b42
refs/heads/master
2021-03-09T23:10:31.789560
2020-04-27T00:07:33
2020-04-27T00:38:06
246,391,034
0
0
NOASSERTION
2020-03-10T19:36:36
2020-03-10T19:36:36
null
UTF-8
C++
false
false
2,632
h
/* * Legal Notice * * This document and associated source code (the "Work") is a preliminary * version of a benchmark specification being developed by the TPC. The * Work is being made available to the public for review and comment only. * The TPC reserves all right, title, and interest to the Work as provided * under U.S. and international laws, including without limitation all patent * and trademark rights therein. * * No Warranty * * 1.1 TO THE MAXIMUM EXTENT PERMITTED BY APPLICABLE LAW, THE INFORMATION * CONTAINED HEREIN IS PROVIDED "AS IS" AND WITH ALL FAULTS, AND THE * AUTHORS AND DEVELOPERS OF THE WORK HEREBY DISCLAIM ALL OTHER * WARRANTIES AND CONDITIONS, EITHER EXPRESS, IMPLIED OR STATUTORY, * INCLUDING, BUT NOT LIMITED TO, ANY (IF ANY) IMPLIED WARRANTIES, * DUTIES OR CONDITIONS OF MERCHANTABILITY, OF FITNESS FOR A PARTICULAR * PURPOSE, OF ACCURACY OR COMPLETENESS OF RESPONSES, OF RESULTS, OF * WORKMANLIKE EFFORT, OF LACK OF VIRUSES, AND OF LACK OF NEGLIGENCE. * ALSO, THERE IS NO WARRANTY OR CONDITION OF TITLE, QUIET ENJOYMENT, * QUIET POSSESSION, CORRESPONDENCE TO DESCRIPTION OR NON-INFRINGEMENT * WITH REGARD TO THE WORK. * 1.2 IN NO EVENT WILL ANY AUTHOR OR DEVELOPER OF THE WORK BE LIABLE TO * ANY OTHER PARTY FOR ANY DAMAGES, INCLUDING BUT NOT LIMITED TO THE * COST OF PROCURING SUBSTITUTE GOODS OR SERVICES, LOST PROFITS, LOSS * OF USE, LOSS OF DATA, OR ANY INCIDENTAL, CONSEQUENTIAL, DIRECT, * INDIRECT, OR SPECIAL DAMAGES WHETHER UNDER CONTRACT, TORT, WARRANTY, * OR OTHERWISE, ARISING IN ANY WAY OUT OF THIS OR ANY OTHER AGREEMENT * RELATING TO THE WORK, WHETHER OR NOT SUCH AUTHOR OR DEVELOPER HAD * ADVANCE NOTICE OF THE POSSIBILITY OF SUCH DAMAGES. * * Contributors * - Doug Johnson */ /* * Flat file loader for TAXRATE. */ #ifndef FLAT_TAXRATE_LOAD_H #define FLAT_TAXRATE_LOAD_H namespace TPCE { class CFlatTaxrateLoad : public CFlatFileLoader <TAXRATE_ROW> { public: CFlatTaxrateLoad( char *szFileName, FlatFileOutputModes FlatFileOutputMode ) : CFlatFileLoader<TAXRATE_ROW>(szFileName, FlatFileOutputMode){}; /* * Writes a record to the file. */ void WriteNextRecord(PT next_record) { int rc = fprintf( hOutFile, TaxrateRowFmt, next_record->TX_ID, next_record->TX_NAME, next_record->TX_RATE ); if (rc < 0) { throw CSystemErr(CSystemErr::eWriteFile, "CFlatTaxrateLoad::WriteNextRecord"); } } }; } // namespace TPCE #endif //FLAT_TAXRATE_LOAD_H
[ "devnull@localhost" ]
devnull@localhost
d6b25dec8ab05395f94aa49872c55bcf2f12c8c7
5da79123d203da34fd45d1f5849f29d15a7ed211
/BST/search.cpp
93cf99bd9a686f0f03a5a8174c106b6d749a4195
[]
no_license
PrshntS/PREP
6d7c1f1ad3f1235e1f9c9b49b34e4b0a64c7a552
ca5a8c00006927a19a995e84253bfdd315e34bd4
refs/heads/master
2023-05-06T00:52:22.293090
2021-05-28T09:12:12
2021-05-28T09:12:12
305,622,125
1
0
null
null
null
null
UTF-8
C++
false
false
1,310
cpp
#include<bits/stdc++.h> using namespace std; #define ll long long #define endl "\n" #define mx INT_MAX #define mn INT_MIN #define pb push_back class node { public: int x; node* left; node* right; node(int d) { x = d; left = NULL; right = NULL; } }; node* insert(node* root, int key) { if (!root) { return new node(key); } if (key < root->x) { root->left = insert(root->left, key); } else { root->right = insert(root->right, key); } return root; } void inorder(node* root) { if (!root) { return; } inorder(root->left); cout << root->x << " "; inorder(root->right); } node* search(node* root, int key) { if (!root || root->x == key) { return root; } if (key < root->x) { return search(root->left, key); } else { return search(root->right, key); } } int main() { #ifndef ONLINE_JUDGE freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout); #endif ios_base::sync_with_stdio(false); cin.tie(NULL); node *root = insert(NULL, 50); root = insert(root, 30); root = insert(root, 20); root = insert(root, 40); root = insert(root, 70); root = insert(root, 60); root = insert(root, 80); inorder(root); cout << endl; node *b = search(root, 60); if (b) { cout << "KEY FOUND=" << b->x; } else { cout << "KEY NOT FOUND"; } return 0; }
[ "51121370+PrshntS@users.noreply.github.com" ]
51121370+PrshntS@users.noreply.github.com
3b4a45f965f6560e64dd4411b9df3886ddc9e50d
3b80b8cf0fdc3c3e7572df708b71fa0fee08f6ca
/Source/TgK/TrafficManager.h
9866620ecda213a4acf042743e5c48584909976c
[]
no_license
AaronReyes-ML/Game-Practice-1
6804b9a37437400cf63e39a7e7484c5b0f4021b1
ed47eb9459258c33ce2c606829a9fbaa77406ff7
refs/heads/master
2020-06-18T17:41:45.283904
2019-07-11T12:02:04
2019-07-11T12:02:04
196,385,939
1
0
null
null
null
null
UTF-8
C++
false
false
3,568
h
// Fill out your copyright notice in the Description page of Project Settings. #pragma once #include "CoreMinimal.h" #include "GameFramework/Actor.h" #include "Engine.h" #include "TrafficManager.generated.h" UCLASS() class TGK_API ATrafficManager : public AActor { GENERATED_BODY() public: // Sets default values for this actor's properties ATrafficManager(); UPROPERTY(EditAnywhere) int numberOfLanes = 2; UPROPERTY(EditAnywhere) int numberOfCarsActive = 0; //UPROPERTY(EditAnywhere) //TArray<class ATrafficLane*> trafficLanesArray; UPROPERTY(EditAnywhere) TArray<class USplineComponent*> trafficSplinesArray; UPROPERTY(EditAnywhere) TArray<int> numberOfCarsPerTrafficLane; int trafficLaneIndexToSpawn = 0; int trafficLaneIndexToDestroy = 0; UPROPERTY(EditAnywhere) int maxNumberOfCarsActive = 1; UPROPERTY(EditAnywhere) TArray<class ATrafficCarPawn*> activeCarsInTrafficLane0; UPROPERTY(EditAnywhere) TArray<class ATrafficCarPawn*> activeCarsInTrafficLane1; UPROPERTY(EditAnywhere) TArray<class ATrafficCarPawn*> activeCarsInTrafficLane2; UPROPERTY(EditAnywhere) TArray<class ATrafficCarPawn*> activeCars; bool canSpawnCars = false; //void SpawnCar(class ATrafficLane* trafficLaneToSpawnOn); //void SpawnCar(); //void DestroyCar(class ATrafficCarPawn* carToDestroy, class ATrafficLane* trafficLaneToDestroyFrom); //void DestroyCar(class ATrafficLane* trafficLaneToDestroyFrom); //class ATrafficLane* GetLeastPopulatedLane(); //class ATrafficLane* GetMostPopulatedLane(); bool isReadyToSpawn = true; float timeUntilNextCarSpawn = 300.f; float maxTimeUntilNextCarSpawn = 300.f; float baseOffset = 10000.f; float spacer = 1000.f; bool space = false; float allowedMaxDistanceBehind = 650.f; UPROPERTY(EditAnywhere) class APlayerCarPawn* playerCar; //float FindDistanceAlongSplineClosestToLocation(class ATrafficLane* trafficLaneToSpawnOn); //void AddTrafficCarPawnToArray(int index, class ATrafficCarPawn* carToAdd); //void RemoveTrafficCarPawnFromArray(int index, class ATrafficCarPawn* carToRemove); //void CheckIfExistingCarsAreBehindPlayer(); UBoxComponent* spawnCollisionVolume; bool SpawnDestinationCheckOverlap(); bool isReadyToDelete = false; float timeUntilCheckForDelete = 30.f; float maxTimeUntilCheckForDelete = 30.f; bool hasDoneInitialSpawn = false; //void SpawnCarInitial(); float initialCarSpawnDistance = 3000.f; float initialCarSpawnSameGroupDistance = 0.f; float initialCarSpawnSeperateGroupDistance = 0.f; UPROPERTY(EditAnywhere) float separateGroupDistanceMin = 4500.f; UPROPERTY(EditAnywhere) float separateGroupDistanceMax = 6500.f; int previousLane = -1; int groupSize = 0; int carsInThisGroup = 0; UPROPERTY(EditAnywhere) bool isTrafficActive = false; UPROPERTY(EditAnywhere) class AGameManager* gameManager; void CarHasBeenPassed(class ATrafficCarPawn* carPassed); void DoInitialCarSpawn(); void DoSingleCarSpawn(); void DoPairCarSpawn(); void DoCarDestroy(class ATrafficCarPawn* carToDestroy); float FindDistanceAlongSplineFromOffset(class USplineComponent* trafficLaneToSpawnOn); bool spawningAPair = false; UPROPERTY(EditAnywhere) float spawnOffsetDistance = 10000; UPROPERTY(EditAnywhere) class ATrack* track; protected: // Called when the game starts or when spawned virtual void BeginPlay() override; public: // Called every frame virtual void Tick(float DeltaTime) override; };
[ "52780561+AaronReyes-ML@users.noreply.github.com" ]
52780561+AaronReyes-ML@users.noreply.github.com
a35a453b9f14a9ff5523f6475707033c20ba3f70
c9a8813b53bc0ad229220f710c1f2b5a17b078b0
/example/Uniteller/InterchangeFormats/Kernel/System/t0262/references/kernel/message.h
f1abbc699fb8cb2924a37988cc5e581aa38ae0bb
[]
no_license
Adramalek/CppTestTask
b83c36aea9eca01491eb33af24fcfe7d3b10139a
6f3008dcbfa25d2cf6ced34e301bae03cb6934ba
refs/heads/master
2020-03-28T14:30:06.579277
2018-09-18T12:35:21
2018-09-18T12:35:21
147,964,408
0
0
null
null
null
null
WINDOWS-1251
C++
false
false
7,979
h
// Uniteller.Framework.Kernel // Version: 1.0.0 // Generation: 1 // Файл содержит реализацию сообщения, передаваемого по шине передачи сообщений #pragma once #include "imessage.h" // IMessage #include "variant.h" // Variant #include "smartpointer.h" // SmartPointer<T> #include <vector> // std::vector namespace Uniteller { namespace Framework { namespace Kernel { using std::vector; typedef SmartPointer<Variant> VariantPtr; /// <summary> /// Базовый класс для всех сообщений, передаваемых по шине передачи сообщений /// </summary> class Message : public Exportable<IMessage> { private: vector<IVariant *> m_Arguments; public: // Свойства // приоритет PROPERTY_IMPLEMENTATION(int, Priority); // идентификатор источника сообщения PROPERTY_IMPLEMENTATION_STRING(SourceId); // идентификатор приемника сообщения PROPERTY_IMPLEMENTATION_STRING(TargetId); // поколение READONLY_PROPERTY_IMPLEMENTATION(int, Generation); // тип сообщения READONLY_PROPERTY_IMPLEMENTATION(event_t, Kind); // Время отправки сообщения PROPERTY_IMPLEMENTATION(timestamp_t, SendTime); public: // Методы /// <summary> /// Инициализирует новый экземпляр сообщения <see cref="Message"/>. /// </summary> /// <param name="kind">Тип сообщения.</param> /// <param name="generation">Поколение.</param> Message(int kind, int generation) : m_Priority(0), m_Generation(generation), m_Kind(kind), m_SendTime(std::chrono::system_clock::now()) { } /// <summary> /// Инициализирует новый экземпляр сообщения <see cref="Message"/>. /// </summary> /// <param name="kind">Тип сообщения.</param> /// <param name="generation">Поколение.</param> /// <param name="priority">Приоритет.</param> Message(int kind, int generation, int priority, const char * szSource, const char * szTarget) : m_Priority(priority), m_SourceId(szSource), m_TargetId(szTarget), m_Generation(generation), m_Kind(kind), m_SendTime(std::chrono::system_clock::now()) { } /// <summary> /// Инициализирует новый экземпляр сообщения <see cref="Message"/> class. /// </summary> /// <param name="kind">Тип сообщения.</param> /// <param name="generation">Поколение.</param> /// <param name="argc">Число аргументов.</param> Message(int kind, int generation, int argc) : m_Arguments(argc), m_Priority(0), m_Generation(generation), m_Kind(kind), m_SendTime(std::chrono::system_clock::now()) { SetArgumentsCount(argc); } ~Message() { Clear(); } /// <summary> /// Позволяет очистить массив аргументов сообщения /// </summary> void Clear() { SetArgumentsCount(0); } /// <summary> /// Позволяет получить аргумент сообщения по индексу /// </summary> /// <param name="index">Индекс аргумента</param> /// <returns>Аргумент сообщения</returns> IVariant * GetArgument(size_t index) override { if (index<m_Arguments.size()) { IVariant * result = m_Arguments[index]; if (result) { result->AddRef(); return result; } return new Variant(); // Empty! } switch (index) { case (size_t)-2: return new Variant(m_SourceId); case (size_t)-3: return new Variant(m_TargetId); case (size_t)-4: return new Variant(m_Generation); case (size_t)-5: return new Variant(m_Kind); case (size_t)-6: return new Variant((int)m_Arguments.size()); case (size_t)-7: return new Variant(m_Priority); case (size_t)-8: return new Variant(m_SendTime); } return NULL; } /// <summary> /// Позволяет установить аргумент сообщения по индексу /// </summary> /// <param name="index">Индекс аргумента</param> /// <returns>Аргумент сообщения</returns> void SetArgument(size_t index, IVariant * value) { if (index < m_Arguments.size()) { IVariant * v = m_Arguments[index]; m_Arguments[index] = new Variant(value); if (v) { v->Release(); v = NULL; } } else throw OutOfRangeException("Индекс выходит за границы массива"); } PROPERTY(size_t, ArgumentsCount); void SetArgumentsCount(const size_t & value) { size_t current = m_Arguments.size(); if (current > value) Reduce(value, current); else if (current < value) m_Arguments.resize(value, NULL); //Expand(value, current); } /// <summary> /// Возвращает число аргументов в сообщении /// </summary> const size_t GetArgumentsCount() const { return m_Arguments.size(); } private: /// <summary> /// Уменьшает размер блока аргументов до значения, переданного в параметре size. /// </summary> /// <param name="size">Желаемый размер блока аргументов</param> /// <param name="current">Текущий размер блока аргументов</param> void Reduce(const size_t size, const size_t current) { for (size_t i = size; i<current; ++i) { IVariant * arg = m_Arguments[i]; if (arg) { m_Arguments[i] = NULL; arg->Release(); arg = NULL; } } m_Arguments.resize(size); } /// <summary> /// Позволяет установить аргумент сообщения по индексу /// </summary> /// <param name="index">Индекс аргумента</param> /// <returns>Аргумент сообщения</returns> void SetArgumentTo(size_t index, IVariant * value) { if (index < m_Arguments.size()) { IVariant * v = m_Arguments[index]; if (v) { v->Release(); v = NULL; } if (value) { m_Arguments[index] = value; value->AddRef(); } else m_Arguments[index] = new Variant(); } else throw OutOfRangeException("Индекс выходит за границы массива"); } }; } // пространство имен Kernel } // пространство имен Framework } // пространство имен Uniteller
[ "beherith10.02@gmail.com" ]
beherith10.02@gmail.com
e82ff26bb080a03047571c3dcb70c5af994b3c37
d09945668f19bb4bc17087c0cb8ccbab2b2dd688
/codeforce/241-260/cf252/b2.cpp
45648729db2d80792d5de6f872c69e34b9ec0125
[]
no_license
kmjp/procon
27270f605f3ae5d80fbdb28708318a6557273a57
8083028ece4be1460150aa3f0e69bdb57e510b53
refs/heads/master
2023-09-04T11:01:09.452170
2023-09-03T15:25:21
2023-09-03T15:25:21
30,825,508
23
2
null
2023-08-18T14:02:07
2015-02-15T11:25:23
C++
UTF-8
C++
false
false
1,184
cpp
#include <cstdlib> #include <cstring> #include <memory> #include <cstdio> #include <iostream> #include <cmath> #include <string> #include <stack> #include <queue> #include <vector> #include <set> #include <map> #include <algorithm> using namespace std; typedef signed long long ll; #undef _P #define _P(...) (void)printf(__VA_ARGS__) #define FOR(x,to) for(x=0;x<to;x++) #define ITR(x,c) for(__typeof(c.begin()) x=c.begin();x!=c.end();x++) #define ZERO(a) memset(a,0,sizeof(a)) void _fill_int(int* p,int val,int rep) {int i; FOR(i,rep) p[i]=val;} #define MINUS(a) _fill_int((int*)a,-1,sizeof(a)/4) //------------------------------------------------------- int N,V; int B[3002]; void solve() { int f,i,j,k,l,x,y; cin>>N>>V; FOR(i,N) { cin>>x>>y; B[x]+=y; } int ret=0; for(i=1;i<=3001;i++) { x=V; y=min(x,B[i-1]); ret+=y; x-=y; y=min(x,B[i]); ret+=y; B[i]-=y; } cout << ret << endl; } int main(int argc,char** argv){ string s; if(argc==1) ios::sync_with_stdio(false); for(int i=1;i<argc;i++) s+=argv[i],s+='\n'; for(int i=s.size()-1;i>=0;i--) ungetc(s[i],stdin); solve(); return 0; }
[ "kmjp" ]
kmjp
ea20d6760c096a59a6bdc325f2abc4df6d4e8a64
08b8cf38e1936e8cec27f84af0d3727321cec9c4
/data/crawl/squid/hunk_6533.cpp
bbd9f66ff6b248cb1800af21cdbc107a9a059aff
[]
no_license
ccdxc/logSurvey
eaf28e9c2d6307140b17986d5c05106d1fd8e943
6b80226e1667c1e0760ab39160893ee19b0e9fb1
refs/heads/master
2022-01-07T21:31:55.446839
2018-04-21T14:12:43
2018-04-21T14:12:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,283
cpp
storeAppendPrintf(sentry, "\tRequests given to unlinkd:\t%d\n", Counter.unlink.requests); + storeAppendPrintf(sentry, "Median Service Times (seconds) 5 min 60 min:\n"); + storeAppendPrintf(sentry, "\tHTTP Requests (All): %8.5f %8.5f\n", + statMedianSvc(5, MEDIAN_HTTP) / 1000.0, + statMedianSvc(60, MEDIAN_HTTP) / 1000.0); + storeAppendPrintf(sentry, "\tCache Misses: %8.5f %8.5f\n", + statMedianSvc(5, MEDIAN_MISS) / 1000.0, + statMedianSvc(60, MEDIAN_MISS) / 1000.0); + storeAppendPrintf(sentry, "\tCache Hits: %8.5f %8.5f\n", + statMedianSvc(5, MEDIAN_HIT) / 1000.0, + statMedianSvc(60, MEDIAN_HIT) / 1000.0); + storeAppendPrintf(sentry, "\tNot-Modified Replies: %8.5f %8.5f\n", + statMedianSvc(5, MEDIAN_NM) / 1000.0, + statMedianSvc(60, MEDIAN_NM) / 1000.0); + storeAppendPrintf(sentry, "\tDNS Lookups: %8.5f %8.5f\n", + statMedianSvc(5, MEDIAN_DNS) / 1000.0, + statMedianSvc(60, MEDIAN_DNS) / 1000.0); + storeAppendPrintf(sentry, "\tICP Queries: %8.5f %8.5f\n", + statMedianSvc(5, MEDIAN_ICP_QUERY) / 1000000.0, + statMedianSvc(60, MEDIAN_ICP_QUERY) / 1000000.0); + squid_getrusage(&rusage); cputime = rusage_cputime(&rusage); storeAppendPrintf(sentry, "Resource usage for %s:\n", appname);
[ "993273596@qq.com" ]
993273596@qq.com
24972c139f87b1e0038aeb647e38086ef6de5551
739732d3a6b548404f432ad8ff918841249a18ec
/src/TransController/TransSession.cc
7c52691faa56b3cc1416e722c33530ad67fcf171
[]
no_license
yiique/TranslationSystemSimple
9417e14c198c9622fbb9e1f046445ba1462b458f
62a9eea538bae1739b7a4e2bfa39fd0e27d8967d
refs/heads/master
2020-04-09T21:25:23.550131
2016-09-12T12:59:12
2016-09-12T12:59:12
68,007,511
0
0
null
2016-09-12T12:59:12
2016-09-12T12:37:25
C++
GB18030
C++
false
false
8,529
cc
#include "TransSession.h" #ifdef ENABLE_SOFT_PROTECT #include "SoftProtect/PermitKey.h" #endif TransSession::TransSession(const CallID & cid, const int sockfd, trans_task_share_ptr sp_task): CSession(cid, sockfd), m_sp_task(sp_task) { #ifdef OUTPUT_TRANS_TIME gettimeofday(&m_trans_beg_time,NULL); #endif } TransSession::~TransSession(void) { } bool TransSession::ParseRecvPacekt() { //获得报文数据 string content; if(!_recv_packet.GetBody(content)) { lerr << "ERROR: TransSession::ParseRecvPacekt() get packet's body failed." << endl; return false; } //lout << "Get trans result = [" <<content << "]" << endl; //解析XML TiXmlDocument xmldoc; xmldoc.Parse(content.c_str()); TiXmlHandle docHandle( &xmldoc ); /* <Msg> <TranslateResult rescode="0" > //用于验证 很可能此时服务器已经换为其他方向或领域 0为成功,1为拒绝 <Target>This is translate result . </Target> //其他翻译信息 <Assist1></Assist1> <Assist2></Assist2> </TranslateResult> </Msg> */ bool res = true; try { TiXmlElement* elem; //节点TranslateResult elem = docHandle.FirstChild("Msg").FirstChild("TranslateResult").ToElement(); if( !elem ) { //lerr << "ERROR: TransSession::ParseRecvPacekt() Parse xml failed: no this elem :TranslateResult. " << endl; throw -1; } //验证rescode const char * _tmp_rescode = elem->Attribute("rescode"); if(!_tmp_rescode) { //若不存在此属性,则认为服务器正常 m_ser_rescode = RES_CODE_SUC; }else { //存在此属性,则验证值 m_ser_rescode = _tmp_rescode; if(m_ser_rescode != RES_CODE_SUC) { lerr << "WARNING: TRANS SERVER DENIED. _rescode = " << m_ser_rescode << endl; throw -1; } } //节点Target elem = docHandle.FirstChild("Msg").FirstChild("TranslateResult").FirstChild("Target").ToElement(); if( !elem ) { //lerr << "ERROR: TransSession::ParseRecvPacekt() Parse xml failed: no this elem :Target. " << endl; throw -1; } const char * _tmp_target = elem->GetText(); if( !_tmp_target) { //ldbg2 << "WARNING: TransSession::ParseRecvPacekt() Parse xml failed: _tmp_target is null." << endl; _tmp_target = ""; } //设置trans_tgt m_sp_task->trans_tgt._decode_result = _tmp_target; m_sp_task->trans_tgt._tgt_str = _tmp_target; //去掉首位空格 del_head_tail_blank(m_sp_task->trans_tgt._tgt_str); //节点Assist1 elem = docHandle.FirstChild("Msg").FirstChild("TranslateResult").FirstChild("Assist1").ToElement(); if( elem ) { const char * _tmp_assist1 = elem->GetText(); if( !_tmp_assist1) { //ldbg2 << "WARNING: TransSession::ParseRecvPacekt() Parse xml failed: Assist1 is null." << endl; _tmp_assist1 = ""; } //设置Assist1 m_sp_task->trans_tgt._assist_str = _tmp_assist1; }else { m_sp_task->trans_tgt._assist_str = ""; } //节点Assist2 elem = docHandle.FirstChild("Msg").FirstChild("TranslateResult").FirstChild("Assist2").ToElement(); if( elem ) { const char * _tmp_assist2 = elem->GetText(); if( !_tmp_assist2) { //ldbg2 << "WARNING: TransSession::ParseRecvPacekt() Parse xml failed: Assist2 is null." << endl; _tmp_assist2 = ""; } //设置trans_tgt m_sp_task->trans_tgt._assist2_str = _tmp_assist2; }else { m_sp_task->trans_tgt._assist2_str = ""; } //节点oovwords elem = docHandle.FirstChild("Msg").FirstChild("TranslateResult").FirstChild("OOV").FirstChild("OOVWords").ToElement(); if( elem ) { const char * _tmp_oov_words = elem->GetText(); if( _tmp_oov_words) { split_string_by_tag(_tmp_oov_words, m_sp_task->trans_tgt._oov_vec, '\t'); } } //节点Alignment elem = docHandle.FirstChild("Msg").FirstChild("TranslateResult").FirstChild("Alignment").ToElement(); if( elem ) { const char * _tmp_align_src = elem->GetText(); if( _tmp_align_src) { //lout << "_tmp_align_src : " << _tmp_align_src << endl; BaseAlign::UnSerialize(_tmp_align_src, m_sp_task->trans_tgt._decode_align_vec); //lout << "Alignment vec size : " << m_sp_task->trans_tgt._decode_align_vec.size() << endl; }else { //ldbg2 << "WARNING: TransSession::ParseRecvPacekt() Parse xml failed: Alignment is null." << endl; } }else { //ldbg2 << "WARNING: TransSession::ParseRecvPacekt() Parse xml failed: no Alignment." << endl; } //节点OOVSent elem = docHandle.FirstChild("Msg").FirstChild("TranslateResult").FirstChild("OOV").FirstChild("OOVSent").ToElement(); if( elem ) { const char * _tmp_oov_sent = elem->GetText(); if( _tmp_oov_sent) { m_sp_task->trans_tgt._oov_sent = _tmp_oov_sent; } } }catch (...) { res = false; } //清理XML资源 xmldoc.Clear(); return res; } bool TransSession::BuildSendPacket() { //报文格式: /* <Msg> <Translate> <SerUUID>xxxx<SerUUID>//用于验证 <Domain>news</Domain> //用于验证 很可能此时服务器已经换为其他方向或领域 <Language src=“chinese” tgt=“english” /> //用于验证 <Source>这是 待 翻译 的 句子 。</Source> //词典和模板 <TemplateAndDict>xxxxx</TemplateAndDict> </Translate> </Msg> */ //XML生成 string xmldata; TiXmlDocument * xmlDocs = new TiXmlDocument(); try { //msg 节点 TiXmlElement * msgElem = new TiXmlElement("Msg"); xmlDocs->LinkEndChild(msgElem); //生成Translate TiXmlElement * transElem = new TiXmlElement("Translate"); msgElem->LinkEndChild(transElem); //生成SerUUID TiXmlElement * uuidElem = new TiXmlElement("SerUUID"); TiXmlText * uuidText = new TiXmlText(m_sp_task->sp_slave->GetInfo().slave_uuid); uuidElem->LinkEndChild(uuidText); transElem->LinkEndChild(uuidElem); //生成Domain TiXmlElement * domainElem = new TiXmlElement("Domain"); TiXmlText * domainText = new TiXmlText(m_sp_task->sp_slave->GetInfo().domain.first); domainElem->LinkEndChild(domainText); transElem->LinkEndChild(domainElem); //生成Language TiXmlElement * langElem = new TiXmlElement("Language"); transElem->LinkEndChild(langElem); langElem->SetAttribute("src", m_sp_task->sp_slave->GetInfo().domain.second.first); langElem->SetAttribute("tgt", m_sp_task->sp_slave->GetInfo().domain.second.second); //生成SubLanguage TiXmlElement * sublanguageElem = new TiXmlElement("SubLanguage"); TiXmlText * sublanguageText = new TiXmlText(num_2_str(m_sp_task->sub_src_language)); transElem->LinkEndChild(sublanguageElem); sublanguageElem->SetAttribute("src", num_2_str(m_sp_task->sub_src_language)); //生成Source TiXmlElement * sourceElem = new TiXmlElement("Source"); TiXmlText * sourceText = new TiXmlText(m_sp_task->trans_src._src_str); sourceElem->LinkEndChild(sourceText); transElem->LinkEndChild(sourceElem); //生成DictRule string dict_text; for(size_t i=0; i<m_sp_task->trans_src._dict_result_vec.size(); ++i) { dict_text += m_sp_task->trans_src._dict_result_vec[i] + "\n"; } TiXmlElement * dictElem = new TiXmlElement("DictRule"); TiXmlText * dictText = new TiXmlText(dict_text); dictElem->LinkEndChild(dictText); transElem->LinkEndChild(dictElem); #ifdef ENABLE_SOFT_PROTECT //PermitKey string src_key = m_sp_task->trans_src._src_str; string permit_key; PermitKey::Generate(filter_head_tail(src_key), permit_key); TiXmlElement * permitElem = new TiXmlElement("PermitKey"); TiXmlText * permitText = new TiXmlText(permit_key); permitElem->LinkEndChild(permitText); transElem->LinkEndChild(permitElem); #endif //输出到xmldata TiXmlPrinter print; xmlDocs->Accept(&print); xmldata = print.CStr(); } catch (...) { //删除xml解析器 delete xmlDocs; return false; } //删除xml解析器 delete xmlDocs; //其基类析构函数会保证中间节点被delete //加入到sendpacket this->_send_packet.Write(HEAD_REQUEST, MSG_TYPE_TRANSLATE, xmldata); //ldbg1 << "--> TransSession::BuildSendPacket() send packet get data = " << _send_packet.GetData() << endl; return true; }
[ "liushuman@liushumandeMBP.lan" ]
liushuman@liushumandeMBP.lan
dea59eb3395e43baa55ff9bb3a632126d3de0f0a
1d928c3f90d4a0a9a3919a804597aa0a4aab19a3
/c++/ClickHouse/2016/12/MergeList.cpp
0ed1d753a810f6f521c252b8d9f6da514ed45e23
[ "BSL-1.0" ]
permissive
rosoareslv/SED99
d8b2ff5811e7f0ffc59be066a5a0349a92cbb845
a062c118f12b93172e31e8ca115ce3f871b64461
refs/heads/main
2023-02-22T21:59:02.703005
2021-01-28T19:40:51
2021-01-28T19:40:51
306,497,459
1
1
null
2020-11-24T20:56:18
2020-10-23T01:18:07
null
UTF-8
C++
false
false
1,825
cpp
#include <DB/Storages/MergeTree/MergeList.h> #include <DB/Common/CurrentMetrics.h> #include <Poco/Ext/ThreadNumber.h> namespace CurrentMetrics { extern const Metric MemoryTrackingForMerges; } namespace DB { MergeListElement::MergeListElement(const std::string & database, const std::string & table, const std::string & result_part_name) : database{database}, table{table}, result_part_name{result_part_name}, thread_number{Poco::ThreadNumber::get()} { /// Each merge is executed into separate background processing pool thread background_pool_task_memory_tracker = current_memory_tracker; if (background_pool_task_memory_tracker) { background_pool_task_memory_tracker->setNext(&memory_tracker); memory_tracker.setMetric(CurrentMetrics::MemoryTrackingForMerges); } } MergeInfo MergeListElement::getInfo() const { MergeInfo res; res.database = database; res.table = table; res.result_part_name = result_part_name; res.elapsed = watch.elapsedSeconds(); res.progress = progress; res.num_parts = num_parts; res.total_size_bytes_compressed = total_size_bytes_compressed; res.total_size_marks = total_size_marks; res.bytes_read_uncompressed = bytes_read_uncompressed.load(std::memory_order_relaxed); res.bytes_written_uncompressed = bytes_written_uncompressed.load(std::memory_order_relaxed); res.rows_read = rows_read.load(std::memory_order_relaxed); res.rows_written = rows_written.load(std::memory_order_relaxed); res.columns_written = columns_written.load(std::memory_order_relaxed); res.memory_usage = memory_tracker.get(); res.thread_number = thread_number; return res; } MergeListElement::~MergeListElement() { /// Unplug memory_tracker from current background processing pool thread if (background_pool_task_memory_tracker) background_pool_task_memory_tracker->setNext(nullptr); } }
[ "rodrigosoaresilva@gmail.com" ]
rodrigosoaresilva@gmail.com
d1281cbdec66f42542d7bab4c481a44e246a2030
ced7da9b1460271e91f6f7516109cd7511dd9f44
/cppwamp/include/cppwamp/internal/conversion.ipp
58dc45efef410457dd4d426879884207ee9e695b
[ "BSL-1.0" ]
permissive
estan/cppwamp
850a586e6fb38aa98a07b276c84cfe6cb0e8fadb
f17db901b2ad444ab0191fade791845868c774e0
refs/heads/master
2021-01-15T11:24:21.259564
2015-10-26T20:52:39
2015-10-26T20:52:39
48,390,357
0
0
null
2015-12-21T19:36:15
2015-12-21T19:36:15
null
UTF-8
C++
false
false
6,771
ipp
/*------------------------------------------------------------------------------ Copyright Butterfly Energy Systems 2014-2015. Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) ------------------------------------------------------------------------------*/ #include <utility> #include "../error.hpp" #include "../variant.hpp" namespace wamp { //------------------------------------------------------------------------------ inline ToVariantConverter::ToVariantConverter(Variant& var) : var_(var) {} /** @details The array will `reserve` space for `n` elements. @post `this->variant().is<Array> == true` @post `this->variant().as<Array>.capacity() >= n` */ inline ToVariantConverter& ToVariantConverter::size(SizeType n) { Array array; array.reserve(n); var_ = std::move(array); return *this; } /** @details The given value is converted to a Variant via Variant::from before being assigned. */ template <typename T> ToVariantConverter& ToVariantConverter::operator()(T&& value) { var_ = Variant::from(std::forward<T>(value)); return *this; } /** @details If the destination Variant is not already an Array, it will be transformed into an array and all previously stored values will be cleared. @post `this->variant().is<Array> == true` */ template <typename T> ToVariantConverter& ToVariantConverter::operator[](T&& value) { if (!var_.is<Array>()) var_ = Array(); auto& array = var_.as<Array>(); array.emplace_back(Variant::from(std::forward<T>(value))); return *this; } /** @details If the destination Variant is not already an Object, it will be transformed into an object and all previously stored values will be cleared. @post `this->variant().is<Object> == true` */ template <typename T> ToVariantConverter& ToVariantConverter::operator()(String key, T&& value) { if (!var_.is<Object>()) var_ = Object(); auto& object = var_.as<Object>(); object.emplace( std::move(key), Variant::from(std::forward<T>(value)) ); return *this; } /** @details If the destination Variant is not already an Object, it will be transformed into an object and all previously stored values will be cleared. @post `this->variant().is<Object> == true` */ template <typename T, typename U> ToVariantConverter& ToVariantConverter::operator()(String key, T&& value, U&&) { return operator()(std::move(key), std::forward<T>(value)); } inline Variant& ToVariantConverter::variant() {return var_;} //------------------------------------------------------------------------------ inline FromVariantConverter::FromVariantConverter(const Variant& var) : var_(var) {} /** @details Returns this->variant()->size(). @see Variant::size */ inline FromVariantConverter::SizeType FromVariantConverter::size() const { return var_.size(); } /** @details Returns this->variant()->size(). @see Variant::size */ inline FromVariantConverter& FromVariantConverter::size(SizeType& n) { n = var_.size(); return *this; } /** @details The variant's value is converted to the destination type via Variant::to. @pre The variant is convertible to the destination type. @throws error::Conversion if the variant is not convertible to the destination type. */ template <typename T> FromVariantConverter& FromVariantConverter::operator()(T& value) { var_.to(value); return *this; } /** @details The element is converted to the destination type via Variant::to. @pre The variant is an array. @pre There are elements left in the variant array. @pre The element is convertible to the destination type. @throws error::Access if the variant is not an array. @throws std::out_of_range if there are no elements left in the variant array. @throws error::Conversion if the element is not convertible to the destination type. */ template <typename T> FromVariantConverter& FromVariantConverter::operator[](T& value) { var_.as<Array>().at(index_).to(value); ++index_; return *this; } /** @details The member is converted to the destination type via Variant::to. @pre The variant is an object. @pre There exists a member with the given key. @pre The member is convertible to the destination type. @throws error::Access if the variant is not an object. @throws std::out_of_range if there doesn't exist a member with the given key. @throws error::Conversion if the member is not convertible to the destination type. */ template <typename T> FromVariantConverter& FromVariantConverter::operator()(const String& key, T& value) { var_.as<Object>().at(key).to(value); return *this; } template <typename T, typename U> FromVariantConverter& FromVariantConverter::operator()(const String& key, T& value, U&& fallback) { auto& obj = var_.as<Object>(); auto kv = obj.find(key); if (kv != obj.end()) kv->second.to(value); else value = std::forward<U>(fallback); return *this; } inline const Variant& FromVariantConverter::variant() const {return var_;} //------------------------------------------------------------------------------ template <typename TConverter, typename TObject> void ConversionAccess::convert(TConverter& c, TObject& obj) { static_assert(has_member_convert<TObject>(), "The 'convert' function has not been specialized for this type. " "Either provide a 'convert' free function specialization, or " "a 'convert' member function."); obj.convert(c); } template <typename TObject> void ConversionAccess::convertFrom(FromVariantConverter& c, TObject& obj) { static_assert(has_member_convertFrom<TObject>(), "The 'convertFrom' member function has not provided " "for this type."); obj.convertFrom(c); } template <typename TObject> void ConversionAccess::convertTo(ToVariantConverter& c, const TObject& obj) { static_assert(has_member_convertTo<TObject>(), "The 'convertTo' member function has not provided " "for this type."); obj.convertTo(c); } //------------------------------------------------------------------------------ template <typename TConverter, typename TValue> void convert(TConverter& c, TValue& val) { // Fall back to intrusive conversion if 'convert' was not specialized // for the given type. ConversionAccess::convert(c, val); } } // namespace wamp
[ "ecorm@users.noreply.github.com" ]
ecorm@users.noreply.github.com
2f5847ee2ab1443a28661cfa6e0fd7f7c5ddb3c6
3a78fcd2c9a66789f995513d9beba219c8a45fe8
/Hardware/krnl_cornertracker.build/link/vivado/vpl/prj/prj.srcs/sources_1/bd/zcu104_base/ip/zcu104_base_auto_pc_0/sim/zcu104_base_auto_pc_0.h
15d8e713ab15613f707a69f123490000597f3620
[]
no_license
msimpsonbbx/test_fast
d25a36e3c067a75c1bae7163ece026879f1cb2aa
01b00070b2d4165c7796726f5a32be93bfee8482
refs/heads/main
2023-03-26T00:04:16.541544
2021-03-25T16:15:28
2021-03-25T16:15:28
351,492,336
0
0
null
null
null
null
UTF-8
C++
false
false
20,863
h
#ifndef IP_ZCU104_BASE_AUTO_PC_0_H_ #define IP_ZCU104_BASE_AUTO_PC_0_H_ // (c) Copyright 1995-2021 Xilinx, Inc. All rights reserved. // // This file contains confidential and proprietary information // of Xilinx, Inc. and is protected under U.S. and // international copyright and other intellectual property // laws. // // DISCLAIMER // This disclaimer is not a license and does not grant any // rights to the materials distributed herewith. Except as // otherwise provided in a valid license issued to you by // Xilinx, and to the maximum extent permitted by applicable // law: (1) THESE MATERIALS ARE MADE AVAILABLE "AS IS" AND // WITH ALL FAULTS, AND XILINX HEREBY DISCLAIMS ALL WARRANTIES // AND CONDITIONS, EXPRESS, IMPLIED, OR STATUTORY, INCLUDING // BUT NOT LIMITED TO WARRANTIES OF MERCHANTABILITY, NON- // INFRINGEMENT, OR FITNESS FOR ANY PARTICULAR PURPOSE; and // (2) Xilinx shall not be liable (whether in contract or tort, // including negligence, or under any other theory of // liability) for any loss or damage of any kind or nature // related to, arising under or in connection with these // materials, including for any direct, or any indirect, // special, incidental, or consequential loss or damage // (including loss of data, profits, goodwill, or any type of // loss or damage suffered as a result of any action brought // by a third party) even if such damage or loss was // reasonably foreseeable or Xilinx had been advised of the // possibility of the same. // // CRITICAL APPLICATIONS // Xilinx products are not designed or intended to be fail- // safe, or for use in any application requiring fail-safe // performance, such as life-support or safety devices or // systems, Class III medical devices, nuclear facilities, // applications related to the deployment of airbags, or any // other applications that could lead to death, personal // injury, or severe property or environmental damage // (individually and collectively, "Critical // Applications"). Customer assumes the sole risk and // liability of any use of Xilinx products in Critical // Applications, subject only to applicable laws and // regulations governing limitations on product liability. // // THIS COPYRIGHT NOTICE AND DISCLAIMER MUST BE RETAINED AS // PART OF THIS FILE AT ALL TIMES. // // DO NOT MODIFY THIS FILE. #ifndef XTLM #include "xtlm.h" #endif #ifndef SYSTEMC_INCLUDED #include <systemc> #endif #if defined(_MSC_VER) #define DllExport __declspec(dllexport) #elif defined(__GNUC__) #define DllExport __attribute__ ((visibility("default"))) #else #define DllExport #endif #include "zcu104_base_auto_pc_0_sc.h" #ifdef XILINX_SIMULATOR class DllExport zcu104_base_auto_pc_0 : public zcu104_base_auto_pc_0_sc { public: zcu104_base_auto_pc_0(const sc_core::sc_module_name& nm); virtual ~zcu104_base_auto_pc_0(); // module pin-to-pin RTL interface sc_core::sc_in< bool > aclk; sc_core::sc_in< bool > aresetn; sc_core::sc_in< sc_dt::sc_bv<16> > s_axi_awid; sc_core::sc_in< sc_dt::sc_bv<40> > s_axi_awaddr; sc_core::sc_in< sc_dt::sc_bv<8> > s_axi_awlen; sc_core::sc_in< sc_dt::sc_bv<3> > s_axi_awsize; sc_core::sc_in< sc_dt::sc_bv<2> > s_axi_awburst; sc_core::sc_in< sc_dt::sc_bv<1> > s_axi_awlock; sc_core::sc_in< sc_dt::sc_bv<4> > s_axi_awcache; sc_core::sc_in< sc_dt::sc_bv<3> > s_axi_awprot; sc_core::sc_in< sc_dt::sc_bv<4> > s_axi_awregion; sc_core::sc_in< sc_dt::sc_bv<4> > s_axi_awqos; sc_core::sc_in< bool > s_axi_awvalid; sc_core::sc_out< bool > s_axi_awready; sc_core::sc_in< sc_dt::sc_bv<32> > s_axi_wdata; sc_core::sc_in< sc_dt::sc_bv<4> > s_axi_wstrb; sc_core::sc_in< bool > s_axi_wlast; sc_core::sc_in< bool > s_axi_wvalid; sc_core::sc_out< bool > s_axi_wready; sc_core::sc_out< sc_dt::sc_bv<16> > s_axi_bid; sc_core::sc_out< sc_dt::sc_bv<2> > s_axi_bresp; sc_core::sc_out< bool > s_axi_bvalid; sc_core::sc_in< bool > s_axi_bready; sc_core::sc_in< sc_dt::sc_bv<16> > s_axi_arid; sc_core::sc_in< sc_dt::sc_bv<40> > s_axi_araddr; sc_core::sc_in< sc_dt::sc_bv<8> > s_axi_arlen; sc_core::sc_in< sc_dt::sc_bv<3> > s_axi_arsize; sc_core::sc_in< sc_dt::sc_bv<2> > s_axi_arburst; sc_core::sc_in< sc_dt::sc_bv<1> > s_axi_arlock; sc_core::sc_in< sc_dt::sc_bv<4> > s_axi_arcache; sc_core::sc_in< sc_dt::sc_bv<3> > s_axi_arprot; sc_core::sc_in< sc_dt::sc_bv<4> > s_axi_arregion; sc_core::sc_in< sc_dt::sc_bv<4> > s_axi_arqos; sc_core::sc_in< bool > s_axi_arvalid; sc_core::sc_out< bool > s_axi_arready; sc_core::sc_out< sc_dt::sc_bv<16> > s_axi_rid; sc_core::sc_out< sc_dt::sc_bv<32> > s_axi_rdata; sc_core::sc_out< sc_dt::sc_bv<2> > s_axi_rresp; sc_core::sc_out< bool > s_axi_rlast; sc_core::sc_out< bool > s_axi_rvalid; sc_core::sc_in< bool > s_axi_rready; sc_core::sc_out< sc_dt::sc_bv<40> > m_axi_awaddr; sc_core::sc_out< sc_dt::sc_bv<3> > m_axi_awprot; sc_core::sc_out< bool > m_axi_awvalid; sc_core::sc_in< bool > m_axi_awready; sc_core::sc_out< sc_dt::sc_bv<32> > m_axi_wdata; sc_core::sc_out< sc_dt::sc_bv<4> > m_axi_wstrb; sc_core::sc_out< bool > m_axi_wvalid; sc_core::sc_in< bool > m_axi_wready; sc_core::sc_in< sc_dt::sc_bv<2> > m_axi_bresp; sc_core::sc_in< bool > m_axi_bvalid; sc_core::sc_out< bool > m_axi_bready; sc_core::sc_out< sc_dt::sc_bv<40> > m_axi_araddr; sc_core::sc_out< sc_dt::sc_bv<3> > m_axi_arprot; sc_core::sc_out< bool > m_axi_arvalid; sc_core::sc_in< bool > m_axi_arready; sc_core::sc_in< sc_dt::sc_bv<32> > m_axi_rdata; sc_core::sc_in< sc_dt::sc_bv<2> > m_axi_rresp; sc_core::sc_in< bool > m_axi_rvalid; sc_core::sc_out< bool > m_axi_rready; protected: virtual void before_end_of_elaboration(); private: xtlm::xaximm_pin2xtlm_t<32,40,16,1,1,1,1,1>* mp_S_AXI_transactor; xsc::common::vectorN2scalar_converter<1>* mp_s_axi_awlock_converter; sc_signal< bool > m_s_axi_awlock_converter_signal; xsc::common::vectorN2scalar_converter<1>* mp_s_axi_arlock_converter; sc_signal< bool > m_s_axi_arlock_converter_signal; xtlm::xaximm_xtlm2pin_t<32,40,16,1,1,1,1,1>* mp_M_AXI_transactor; }; #endif // XILINX_SIMULATOR #ifdef XM_SYSTEMC class DllExport zcu104_base_auto_pc_0 : public zcu104_base_auto_pc_0_sc { public: zcu104_base_auto_pc_0(const sc_core::sc_module_name& nm); virtual ~zcu104_base_auto_pc_0(); // module pin-to-pin RTL interface sc_core::sc_in< bool > aclk; sc_core::sc_in< bool > aresetn; sc_core::sc_in< sc_dt::sc_bv<16> > s_axi_awid; sc_core::sc_in< sc_dt::sc_bv<40> > s_axi_awaddr; sc_core::sc_in< sc_dt::sc_bv<8> > s_axi_awlen; sc_core::sc_in< sc_dt::sc_bv<3> > s_axi_awsize; sc_core::sc_in< sc_dt::sc_bv<2> > s_axi_awburst; sc_core::sc_in< sc_dt::sc_bv<1> > s_axi_awlock; sc_core::sc_in< sc_dt::sc_bv<4> > s_axi_awcache; sc_core::sc_in< sc_dt::sc_bv<3> > s_axi_awprot; sc_core::sc_in< sc_dt::sc_bv<4> > s_axi_awregion; sc_core::sc_in< sc_dt::sc_bv<4> > s_axi_awqos; sc_core::sc_in< bool > s_axi_awvalid; sc_core::sc_out< bool > s_axi_awready; sc_core::sc_in< sc_dt::sc_bv<32> > s_axi_wdata; sc_core::sc_in< sc_dt::sc_bv<4> > s_axi_wstrb; sc_core::sc_in< bool > s_axi_wlast; sc_core::sc_in< bool > s_axi_wvalid; sc_core::sc_out< bool > s_axi_wready; sc_core::sc_out< sc_dt::sc_bv<16> > s_axi_bid; sc_core::sc_out< sc_dt::sc_bv<2> > s_axi_bresp; sc_core::sc_out< bool > s_axi_bvalid; sc_core::sc_in< bool > s_axi_bready; sc_core::sc_in< sc_dt::sc_bv<16> > s_axi_arid; sc_core::sc_in< sc_dt::sc_bv<40> > s_axi_araddr; sc_core::sc_in< sc_dt::sc_bv<8> > s_axi_arlen; sc_core::sc_in< sc_dt::sc_bv<3> > s_axi_arsize; sc_core::sc_in< sc_dt::sc_bv<2> > s_axi_arburst; sc_core::sc_in< sc_dt::sc_bv<1> > s_axi_arlock; sc_core::sc_in< sc_dt::sc_bv<4> > s_axi_arcache; sc_core::sc_in< sc_dt::sc_bv<3> > s_axi_arprot; sc_core::sc_in< sc_dt::sc_bv<4> > s_axi_arregion; sc_core::sc_in< sc_dt::sc_bv<4> > s_axi_arqos; sc_core::sc_in< bool > s_axi_arvalid; sc_core::sc_out< bool > s_axi_arready; sc_core::sc_out< sc_dt::sc_bv<16> > s_axi_rid; sc_core::sc_out< sc_dt::sc_bv<32> > s_axi_rdata; sc_core::sc_out< sc_dt::sc_bv<2> > s_axi_rresp; sc_core::sc_out< bool > s_axi_rlast; sc_core::sc_out< bool > s_axi_rvalid; sc_core::sc_in< bool > s_axi_rready; sc_core::sc_out< sc_dt::sc_bv<40> > m_axi_awaddr; sc_core::sc_out< sc_dt::sc_bv<3> > m_axi_awprot; sc_core::sc_out< bool > m_axi_awvalid; sc_core::sc_in< bool > m_axi_awready; sc_core::sc_out< sc_dt::sc_bv<32> > m_axi_wdata; sc_core::sc_out< sc_dt::sc_bv<4> > m_axi_wstrb; sc_core::sc_out< bool > m_axi_wvalid; sc_core::sc_in< bool > m_axi_wready; sc_core::sc_in< sc_dt::sc_bv<2> > m_axi_bresp; sc_core::sc_in< bool > m_axi_bvalid; sc_core::sc_out< bool > m_axi_bready; sc_core::sc_out< sc_dt::sc_bv<40> > m_axi_araddr; sc_core::sc_out< sc_dt::sc_bv<3> > m_axi_arprot; sc_core::sc_out< bool > m_axi_arvalid; sc_core::sc_in< bool > m_axi_arready; sc_core::sc_in< sc_dt::sc_bv<32> > m_axi_rdata; sc_core::sc_in< sc_dt::sc_bv<2> > m_axi_rresp; sc_core::sc_in< bool > m_axi_rvalid; sc_core::sc_out< bool > m_axi_rready; protected: virtual void before_end_of_elaboration(); private: xtlm::xaximm_pin2xtlm_t<32,40,16,1,1,1,1,1>* mp_S_AXI_transactor; xsc::common::vectorN2scalar_converter<1>* mp_s_axi_awlock_converter; sc_signal< bool > m_s_axi_awlock_converter_signal; xsc::common::vectorN2scalar_converter<1>* mp_s_axi_arlock_converter; sc_signal< bool > m_s_axi_arlock_converter_signal; xtlm::xaximm_xtlm2pin_t<32,40,16,1,1,1,1,1>* mp_M_AXI_transactor; }; #endif // XM_SYSTEMC #ifdef RIVIERA class DllExport zcu104_base_auto_pc_0 : public zcu104_base_auto_pc_0_sc { public: zcu104_base_auto_pc_0(const sc_core::sc_module_name& nm); virtual ~zcu104_base_auto_pc_0(); // module pin-to-pin RTL interface sc_core::sc_in< bool > aclk; sc_core::sc_in< bool > aresetn; sc_core::sc_in< sc_dt::sc_bv<16> > s_axi_awid; sc_core::sc_in< sc_dt::sc_bv<40> > s_axi_awaddr; sc_core::sc_in< sc_dt::sc_bv<8> > s_axi_awlen; sc_core::sc_in< sc_dt::sc_bv<3> > s_axi_awsize; sc_core::sc_in< sc_dt::sc_bv<2> > s_axi_awburst; sc_core::sc_in< sc_dt::sc_bv<1> > s_axi_awlock; sc_core::sc_in< sc_dt::sc_bv<4> > s_axi_awcache; sc_core::sc_in< sc_dt::sc_bv<3> > s_axi_awprot; sc_core::sc_in< sc_dt::sc_bv<4> > s_axi_awregion; sc_core::sc_in< sc_dt::sc_bv<4> > s_axi_awqos; sc_core::sc_in< bool > s_axi_awvalid; sc_core::sc_out< bool > s_axi_awready; sc_core::sc_in< sc_dt::sc_bv<32> > s_axi_wdata; sc_core::sc_in< sc_dt::sc_bv<4> > s_axi_wstrb; sc_core::sc_in< bool > s_axi_wlast; sc_core::sc_in< bool > s_axi_wvalid; sc_core::sc_out< bool > s_axi_wready; sc_core::sc_out< sc_dt::sc_bv<16> > s_axi_bid; sc_core::sc_out< sc_dt::sc_bv<2> > s_axi_bresp; sc_core::sc_out< bool > s_axi_bvalid; sc_core::sc_in< bool > s_axi_bready; sc_core::sc_in< sc_dt::sc_bv<16> > s_axi_arid; sc_core::sc_in< sc_dt::sc_bv<40> > s_axi_araddr; sc_core::sc_in< sc_dt::sc_bv<8> > s_axi_arlen; sc_core::sc_in< sc_dt::sc_bv<3> > s_axi_arsize; sc_core::sc_in< sc_dt::sc_bv<2> > s_axi_arburst; sc_core::sc_in< sc_dt::sc_bv<1> > s_axi_arlock; sc_core::sc_in< sc_dt::sc_bv<4> > s_axi_arcache; sc_core::sc_in< sc_dt::sc_bv<3> > s_axi_arprot; sc_core::sc_in< sc_dt::sc_bv<4> > s_axi_arregion; sc_core::sc_in< sc_dt::sc_bv<4> > s_axi_arqos; sc_core::sc_in< bool > s_axi_arvalid; sc_core::sc_out< bool > s_axi_arready; sc_core::sc_out< sc_dt::sc_bv<16> > s_axi_rid; sc_core::sc_out< sc_dt::sc_bv<32> > s_axi_rdata; sc_core::sc_out< sc_dt::sc_bv<2> > s_axi_rresp; sc_core::sc_out< bool > s_axi_rlast; sc_core::sc_out< bool > s_axi_rvalid; sc_core::sc_in< bool > s_axi_rready; sc_core::sc_out< sc_dt::sc_bv<40> > m_axi_awaddr; sc_core::sc_out< sc_dt::sc_bv<3> > m_axi_awprot; sc_core::sc_out< bool > m_axi_awvalid; sc_core::sc_in< bool > m_axi_awready; sc_core::sc_out< sc_dt::sc_bv<32> > m_axi_wdata; sc_core::sc_out< sc_dt::sc_bv<4> > m_axi_wstrb; sc_core::sc_out< bool > m_axi_wvalid; sc_core::sc_in< bool > m_axi_wready; sc_core::sc_in< sc_dt::sc_bv<2> > m_axi_bresp; sc_core::sc_in< bool > m_axi_bvalid; sc_core::sc_out< bool > m_axi_bready; sc_core::sc_out< sc_dt::sc_bv<40> > m_axi_araddr; sc_core::sc_out< sc_dt::sc_bv<3> > m_axi_arprot; sc_core::sc_out< bool > m_axi_arvalid; sc_core::sc_in< bool > m_axi_arready; sc_core::sc_in< sc_dt::sc_bv<32> > m_axi_rdata; sc_core::sc_in< sc_dt::sc_bv<2> > m_axi_rresp; sc_core::sc_in< bool > m_axi_rvalid; sc_core::sc_out< bool > m_axi_rready; protected: virtual void before_end_of_elaboration(); private: xtlm::xaximm_pin2xtlm_t<32,40,16,1,1,1,1,1>* mp_S_AXI_transactor; xsc::common::vectorN2scalar_converter<1>* mp_s_axi_awlock_converter; sc_signal< bool > m_s_axi_awlock_converter_signal; xsc::common::vectorN2scalar_converter<1>* mp_s_axi_arlock_converter; sc_signal< bool > m_s_axi_arlock_converter_signal; xtlm::xaximm_xtlm2pin_t<32,40,16,1,1,1,1,1>* mp_M_AXI_transactor; }; #endif // RIVIERA #ifdef VCSSYSTEMC #include "utils/xtlm_aximm_initiator_stub.h" #include "utils/xtlm_aximm_target_stub.h" class DllExport zcu104_base_auto_pc_0 : public zcu104_base_auto_pc_0_sc { public: zcu104_base_auto_pc_0(const sc_core::sc_module_name& nm); virtual ~zcu104_base_auto_pc_0(); // module pin-to-pin RTL interface sc_core::sc_in< bool > aclk; sc_core::sc_in< bool > aresetn; sc_core::sc_in< sc_dt::sc_bv<16> > s_axi_awid; sc_core::sc_in< sc_dt::sc_bv<40> > s_axi_awaddr; sc_core::sc_in< sc_dt::sc_bv<8> > s_axi_awlen; sc_core::sc_in< sc_dt::sc_bv<3> > s_axi_awsize; sc_core::sc_in< sc_dt::sc_bv<2> > s_axi_awburst; sc_core::sc_in< sc_dt::sc_bv<1> > s_axi_awlock; sc_core::sc_in< sc_dt::sc_bv<4> > s_axi_awcache; sc_core::sc_in< sc_dt::sc_bv<3> > s_axi_awprot; sc_core::sc_in< sc_dt::sc_bv<4> > s_axi_awregion; sc_core::sc_in< sc_dt::sc_bv<4> > s_axi_awqos; sc_core::sc_in< bool > s_axi_awvalid; sc_core::sc_out< bool > s_axi_awready; sc_core::sc_in< sc_dt::sc_bv<32> > s_axi_wdata; sc_core::sc_in< sc_dt::sc_bv<4> > s_axi_wstrb; sc_core::sc_in< bool > s_axi_wlast; sc_core::sc_in< bool > s_axi_wvalid; sc_core::sc_out< bool > s_axi_wready; sc_core::sc_out< sc_dt::sc_bv<16> > s_axi_bid; sc_core::sc_out< sc_dt::sc_bv<2> > s_axi_bresp; sc_core::sc_out< bool > s_axi_bvalid; sc_core::sc_in< bool > s_axi_bready; sc_core::sc_in< sc_dt::sc_bv<16> > s_axi_arid; sc_core::sc_in< sc_dt::sc_bv<40> > s_axi_araddr; sc_core::sc_in< sc_dt::sc_bv<8> > s_axi_arlen; sc_core::sc_in< sc_dt::sc_bv<3> > s_axi_arsize; sc_core::sc_in< sc_dt::sc_bv<2> > s_axi_arburst; sc_core::sc_in< sc_dt::sc_bv<1> > s_axi_arlock; sc_core::sc_in< sc_dt::sc_bv<4> > s_axi_arcache; sc_core::sc_in< sc_dt::sc_bv<3> > s_axi_arprot; sc_core::sc_in< sc_dt::sc_bv<4> > s_axi_arregion; sc_core::sc_in< sc_dt::sc_bv<4> > s_axi_arqos; sc_core::sc_in< bool > s_axi_arvalid; sc_core::sc_out< bool > s_axi_arready; sc_core::sc_out< sc_dt::sc_bv<16> > s_axi_rid; sc_core::sc_out< sc_dt::sc_bv<32> > s_axi_rdata; sc_core::sc_out< sc_dt::sc_bv<2> > s_axi_rresp; sc_core::sc_out< bool > s_axi_rlast; sc_core::sc_out< bool > s_axi_rvalid; sc_core::sc_in< bool > s_axi_rready; sc_core::sc_out< sc_dt::sc_bv<40> > m_axi_awaddr; sc_core::sc_out< sc_dt::sc_bv<3> > m_axi_awprot; sc_core::sc_out< bool > m_axi_awvalid; sc_core::sc_in< bool > m_axi_awready; sc_core::sc_out< sc_dt::sc_bv<32> > m_axi_wdata; sc_core::sc_out< sc_dt::sc_bv<4> > m_axi_wstrb; sc_core::sc_out< bool > m_axi_wvalid; sc_core::sc_in< bool > m_axi_wready; sc_core::sc_in< sc_dt::sc_bv<2> > m_axi_bresp; sc_core::sc_in< bool > m_axi_bvalid; sc_core::sc_out< bool > m_axi_bready; sc_core::sc_out< sc_dt::sc_bv<40> > m_axi_araddr; sc_core::sc_out< sc_dt::sc_bv<3> > m_axi_arprot; sc_core::sc_out< bool > m_axi_arvalid; sc_core::sc_in< bool > m_axi_arready; sc_core::sc_in< sc_dt::sc_bv<32> > m_axi_rdata; sc_core::sc_in< sc_dt::sc_bv<2> > m_axi_rresp; sc_core::sc_in< bool > m_axi_rvalid; sc_core::sc_out< bool > m_axi_rready; protected: virtual void before_end_of_elaboration(); private: xtlm::xaximm_pin2xtlm_t<32,40,16,1,1,1,1,1>* mp_S_AXI_transactor; xsc::common::vectorN2scalar_converter<1>* mp_s_axi_awlock_converter; sc_signal< bool > m_s_axi_awlock_converter_signal; xsc::common::vectorN2scalar_converter<1>* mp_s_axi_arlock_converter; sc_signal< bool > m_s_axi_arlock_converter_signal; xtlm::xaximm_xtlm2pin_t<32,40,16,1,1,1,1,1>* mp_M_AXI_transactor; // Transactor stubs xtlm::xtlm_aximm_initiator_stub * M_AXI_transactor_initiator_rd_socket_stub; xtlm::xtlm_aximm_initiator_stub * M_AXI_transactor_initiator_wr_socket_stub; xtlm::xtlm_aximm_target_stub * S_AXI_transactor_target_rd_socket_stub; xtlm::xtlm_aximm_target_stub * S_AXI_transactor_target_wr_socket_stub; // Socket stubs }; #endif // VCSSYSTEMC #ifdef MTI_SYSTEMC #include "utils/xtlm_aximm_initiator_stub.h" #include "utils/xtlm_aximm_target_stub.h" class DllExport zcu104_base_auto_pc_0 : public zcu104_base_auto_pc_0_sc { public: zcu104_base_auto_pc_0(const sc_core::sc_module_name& nm); virtual ~zcu104_base_auto_pc_0(); // module pin-to-pin RTL interface sc_core::sc_in< bool > aclk; sc_core::sc_in< bool > aresetn; sc_core::sc_in< sc_dt::sc_bv<16> > s_axi_awid; sc_core::sc_in< sc_dt::sc_bv<40> > s_axi_awaddr; sc_core::sc_in< sc_dt::sc_bv<8> > s_axi_awlen; sc_core::sc_in< sc_dt::sc_bv<3> > s_axi_awsize; sc_core::sc_in< sc_dt::sc_bv<2> > s_axi_awburst; sc_core::sc_in< sc_dt::sc_bv<1> > s_axi_awlock; sc_core::sc_in< sc_dt::sc_bv<4> > s_axi_awcache; sc_core::sc_in< sc_dt::sc_bv<3> > s_axi_awprot; sc_core::sc_in< sc_dt::sc_bv<4> > s_axi_awregion; sc_core::sc_in< sc_dt::sc_bv<4> > s_axi_awqos; sc_core::sc_in< bool > s_axi_awvalid; sc_core::sc_out< bool > s_axi_awready; sc_core::sc_in< sc_dt::sc_bv<32> > s_axi_wdata; sc_core::sc_in< sc_dt::sc_bv<4> > s_axi_wstrb; sc_core::sc_in< bool > s_axi_wlast; sc_core::sc_in< bool > s_axi_wvalid; sc_core::sc_out< bool > s_axi_wready; sc_core::sc_out< sc_dt::sc_bv<16> > s_axi_bid; sc_core::sc_out< sc_dt::sc_bv<2> > s_axi_bresp; sc_core::sc_out< bool > s_axi_bvalid; sc_core::sc_in< bool > s_axi_bready; sc_core::sc_in< sc_dt::sc_bv<16> > s_axi_arid; sc_core::sc_in< sc_dt::sc_bv<40> > s_axi_araddr; sc_core::sc_in< sc_dt::sc_bv<8> > s_axi_arlen; sc_core::sc_in< sc_dt::sc_bv<3> > s_axi_arsize; sc_core::sc_in< sc_dt::sc_bv<2> > s_axi_arburst; sc_core::sc_in< sc_dt::sc_bv<1> > s_axi_arlock; sc_core::sc_in< sc_dt::sc_bv<4> > s_axi_arcache; sc_core::sc_in< sc_dt::sc_bv<3> > s_axi_arprot; sc_core::sc_in< sc_dt::sc_bv<4> > s_axi_arregion; sc_core::sc_in< sc_dt::sc_bv<4> > s_axi_arqos; sc_core::sc_in< bool > s_axi_arvalid; sc_core::sc_out< bool > s_axi_arready; sc_core::sc_out< sc_dt::sc_bv<16> > s_axi_rid; sc_core::sc_out< sc_dt::sc_bv<32> > s_axi_rdata; sc_core::sc_out< sc_dt::sc_bv<2> > s_axi_rresp; sc_core::sc_out< bool > s_axi_rlast; sc_core::sc_out< bool > s_axi_rvalid; sc_core::sc_in< bool > s_axi_rready; sc_core::sc_out< sc_dt::sc_bv<40> > m_axi_awaddr; sc_core::sc_out< sc_dt::sc_bv<3> > m_axi_awprot; sc_core::sc_out< bool > m_axi_awvalid; sc_core::sc_in< bool > m_axi_awready; sc_core::sc_out< sc_dt::sc_bv<32> > m_axi_wdata; sc_core::sc_out< sc_dt::sc_bv<4> > m_axi_wstrb; sc_core::sc_out< bool > m_axi_wvalid; sc_core::sc_in< bool > m_axi_wready; sc_core::sc_in< sc_dt::sc_bv<2> > m_axi_bresp; sc_core::sc_in< bool > m_axi_bvalid; sc_core::sc_out< bool > m_axi_bready; sc_core::sc_out< sc_dt::sc_bv<40> > m_axi_araddr; sc_core::sc_out< sc_dt::sc_bv<3> > m_axi_arprot; sc_core::sc_out< bool > m_axi_arvalid; sc_core::sc_in< bool > m_axi_arready; sc_core::sc_in< sc_dt::sc_bv<32> > m_axi_rdata; sc_core::sc_in< sc_dt::sc_bv<2> > m_axi_rresp; sc_core::sc_in< bool > m_axi_rvalid; sc_core::sc_out< bool > m_axi_rready; protected: virtual void before_end_of_elaboration(); private: xtlm::xaximm_pin2xtlm_t<32,40,16,1,1,1,1,1>* mp_S_AXI_transactor; xsc::common::vectorN2scalar_converter<1>* mp_s_axi_awlock_converter; sc_signal< bool > m_s_axi_awlock_converter_signal; xsc::common::vectorN2scalar_converter<1>* mp_s_axi_arlock_converter; sc_signal< bool > m_s_axi_arlock_converter_signal; xtlm::xaximm_xtlm2pin_t<32,40,16,1,1,1,1,1>* mp_M_AXI_transactor; // Transactor stubs xtlm::xtlm_aximm_initiator_stub * M_AXI_transactor_initiator_rd_socket_stub; xtlm::xtlm_aximm_initiator_stub * M_AXI_transactor_initiator_wr_socket_stub; xtlm::xtlm_aximm_target_stub * S_AXI_transactor_target_rd_socket_stub; xtlm::xtlm_aximm_target_stub * S_AXI_transactor_target_wr_socket_stub; // Socket stubs }; #endif // MTI_SYSTEMC #endif // IP_ZCU104_BASE_AUTO_PC_0_H_
[ "m.simpson@beetlebox.org" ]
m.simpson@beetlebox.org
9cfc704a616e9a60ad599281f928cdea64791a2a
d31aed88f751ec8f9dd0a51ea215dba4577b5a9b
/framework/core/network_manager/sources/connection_manager/nm_connection_manager.hpp
4d3bd7a750a27b2596adea1761ed602f5715593d
[]
no_license
valeriyr/Hedgehog
56a4f186286608140f0e4ce5ef962e9a10b123a8
c045f262ca036570416c793f589ba1650223edd9
refs/heads/master
2016-09-05T20:00:51.747169
2015-09-04T05:21:38
2015-09-04T05:21:38
3,336,071
0
0
null
null
null
null
UTF-8
C++
false
false
1,911
hpp
#ifndef __NM_CONNECTION_MANAGER_HPP__ #define __NM_CONNECTION_MANAGER_HPP__ /*---------------------------------------------------------------------------*/ #include "network_manager/ih/nm_iconnection_manager.hpp" /*---------------------------------------------------------------------------*/ namespace Framework { namespace Core { namespace NetworkManager { /*---------------------------------------------------------------------------*/ class ConnectionManager : public Tools::Core::BaseWrapper< IConnectionManager > { /*---------------------------------------------------------------------------*/ public: /*---------------------------------------------------------------------------*/ ConnectionManager(); virtual ~ConnectionManager(); /*---------------------------------------------------------------------------*/ /*virtual*/ boost::intrusive_ptr< IUdpConnection > getUdpConnection( const ConnectionInfo& _connectionInfo, const quint32 _connectionTimeOut ); /*virtual*/ void closeUdpConnection( const ConnectionInfo& _connectionInfo ); /*---------------------------------------------------------------------------*/ private: /*---------------------------------------------------------------------------*/ typedef std::map< ConnectionInfo, boost::intrusive_ptr< IUdpConnection > > ConnectionsCollection; typedef ConnectionsCollection::iterator ConnectionsCollectionIterator; /*---------------------------------------------------------------------------*/ ConnectionsCollection m_connectionsCollection; /*---------------------------------------------------------------------------*/ }; /*---------------------------------------------------------------------------*/ } // namespace NetworkManager } // namespace Core } // namespace Framework /*---------------------------------------------------------------------------*/ #endif // __NM_CONNECTION_MANAGER_HPP__
[ "valeriy.reutov@gmail.com" ]
valeriy.reutov@gmail.com
70073af5b1f03721b19502d2a9cb85048ab9be66
5ac069e45cafd2ae9e0056bccf0537fa55f0f066
/UVA OJ - ALL/p671.cc
4e6968a521af57a63c3dcebab1f47acfd2d29414
[]
no_license
fernandesitalo-zz/Competitive-Progamming
ed9b4879f6d2b443a6d17a1426821d1674506eb8
a89f770b8616c00198f74c92a09b59d4a278711d
refs/heads/master
2022-02-12T17:44:19.641129
2019-07-30T12:26:02
2019-07-30T12:26:02
92,948,182
1
0
null
null
null
null
UTF-8
C++
false
false
1,434
cc
#include <bits/stdc++.h> using namespace std; //~ int pd[16][16]; //~ int ed(string str1,string str2, int n, int m){ //~ if(n == 0) return m; //~ if(m == 0) return n; //~ int &ref = pd[n][m]; //~ if(ref != -1) return ref; //~ if(str1[n-1] == str2[m-1]) return ref = ed(str1,str2,n-1,m-1); //~ return ref = 1 + min(ed(str1,str2,n-1,m),min(ed(str1,str2,n,m-1),ed(str1,str2,n-1,m-1))); //~ } bool f(string s1,string s2){ int n = s1.size(); int m = s2.size(); if(n == m){ int dif = 0; for(int i = 0 ; i < n && dif < 2; ++i) if(s1[i] != s2[i]) dif++; return (dif <= 1); } if(n == m+1){ int j = 0; int dif = 0; for(int i = 0 ; s1[i] && dif < 2 ; ++i){ if(s1[i] != s2[j]){ dif++; } else j++; } return (dif <= 1); } if(n == m-1){ int j = 0; int dif = 0; for(int i = 0 ; s2[i] && dif < 2 ; ++i){ if(s2[i] != s1[j]){ dif++; } else j++; } return (dif <= 1); } return false; } int main(){ //~ freopen("in","r",stdin); int t; string p; bool b = 0; for(cin>>t;t--;){ if(b) puts(""); b = 1; vector<string> v; set<string> s; while(cin>>p, p[0] != '#') v.push_back(p),s.insert(p); while(cin>>p,p[0] != '#'){ if(s.find(p) != s.end()) printf("%s is correct",p.data()); else{ printf("%s:",p.data()); for(auto it : v) { if(f(p,it)) printf(" %s",it.data()); } } puts(""); } } return 0; }
[ "italofernandes.fg@gmail.com" ]
italofernandes.fg@gmail.com