blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
3
264
content_id
stringlengths
40
40
detected_licenses
listlengths
0
85
license_type
stringclasses
2 values
repo_name
stringlengths
5
140
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
905 values
visit_date
timestamp[us]date
2015-08-09 11:21:18
2023-09-06 10:45:07
revision_date
timestamp[us]date
1997-09-14 05:04:47
2023-09-17 19:19:19
committer_date
timestamp[us]date
1997-09-14 05:04:47
2023-09-06 06:22:19
github_id
int64
3.89k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
22 values
gha_event_created_at
timestamp[us]date
2012-06-07 00:51:45
2023-09-14 21:58:39
gha_created_at
timestamp[us]date
2008-03-27 23:40:48
2023-08-21 23:17:38
gha_language
stringclasses
141 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
3
10.4M
extension
stringclasses
115 values
content
stringlengths
3
10.4M
authors
listlengths
1
1
author_id
stringlengths
0
158
1dc3e031a9fca378926f6ae62debbd7c1a7e26f6
385021ee821bedfe372f7d93b880e2a8f0821f53
/Recursion/substr.cpp
fe60b63f7e9688606a76e077cf1daabdc5cab431
[]
no_license
indranil2507/cpp
ee0fbb9bf0d00358c356367f9b63e0f11c1b8f50
af4221a55ba760d57b22411365377ac34e1c4938
refs/heads/master
2023-06-13T01:32:47.420511
2021-07-08T15:12:29
2021-07-08T15:12:29
327,627,448
0
0
null
null
null
null
UTF-8
C++
false
false
318
cpp
#include <iostream> using namespace std; void subseq(string s, string ans) { if (s.length() == 0) { cout << ans << endl; return; } char ch = s[0]; string ros = s.substr(1); subseq(ros, ans); subseq(ros, ans + ch); } int main() { subseq("ABC", ""); cout << endl; }
[ "iindranilsaha1@gmail.com" ]
iindranilsaha1@gmail.com
789cfa67373b5be22a2ee26d4ba6ebf4b3c1d709
37e2b11c0d749e1e34d7be81ef304679c03af701
/src/cppverify.h
70c955444d44efd27aa624797aab8deee221bdb3
[]
no_license
phaero/cppverify
8f7257d857ab6036873ed2b2a2ee8e299e8bf52c
f8da32d8fbba65ec9a6634b0baf9092fda72b560
refs/heads/master
2021-01-15T23:45:18.424978
2010-07-07T22:29:35
2010-07-07T22:29:35
null
0
0
null
null
null
null
UTF-8
C++
false
false
430
h
#ifndef __CCPPVERIFY_H_INCL__ #define __CCPPVERIFY_H_INCL__ /** * Main class of the cppverify project. * This class instantiates the main classes. * * NOTES: * * Start out todo's: * Add file loader * Add recursive directory scanner * Add main hash table. * Figure out how to fill the hash tables, arrays? */ class CCppVerify { public: CCppVerify(); virtual ~CCppVerify(); }; #endif // __CCPPVERIFY_H_INCL__
[ "christer.soderlund@gmail.com" ]
christer.soderlund@gmail.com
dd65d20999cea67e6741cef4b153aff2c9fe203c
a4a072ec59436e148121e87889714a68859da9da
/Src/Engine/3_Modules/File/Serialize/JSON/JsonSerializer_Morph.h
d97dc5b793332dea3cf5a827af87347b9cb81735
[]
no_license
morcosan/CYRED
3615441445bcfdfada3cd55533b3af4c1d14fac6
a65c7645148c522b2f14a5e447e1fe01ed3455bc
refs/heads/master
2021-03-23T07:25:30.131090
2016-05-10T20:49:47
2016-05-10T20:49:47
247,435,142
0
0
null
null
null
null
UTF-8
C++
false
false
571
h
// Copyright (c) 2015 Morco (www.morco.ro) // MIT License #pragma once #include "../../../../1_Required/Required.h" #include "JsonSerializer.h" namespace CYRED { class DLL JsonSerializer_Morph : public JsonSerializer { const Char* const UNIQUE_ID = "uid"; const Char* const FILE_PATHS = "file_paths"; public: JsonSerializer_Morph() {} virtual ~JsonSerializer_Morph() {}; public: rapidjson::Value ToJson ( void* object ) override; void FromJson( rapidjson::Value& json, OUT void* object, DeserFlag flag ) override; }; }
[ "morco.mail@gmail.com" ]
morco.mail@gmail.com
35da6007bb1a6b66c17556cb7bda365734b37a26
32b582d8ada9f3a77527aacfefe6c6bd7fe9458e
/part2_starter/server/server.cpp
aae7db10967ceb259d0b8aa87474439204cef705
[]
no_license
revanthavs/cmput275-Revanth-
d690915f5074ac38aeccae698e82dacf17b20279
2046e533e238120f9cad0e114627909c3089b0fa
refs/heads/master
2023-05-21T20:49:46.970809
2021-06-12T16:23:30
2021-06-12T16:23:30
328,596,132
0
2
null
null
null
null
UTF-8
C++
false
false
10,894
cpp
#include <iostream> #include <cassert> #include <fstream> #include <sstream> #include <string> #include <string.h> #include <list> #include <unistd.h> #include <sys/socket.h> #include <stdlib.h> #include <arpa/inet.h> #include "wdigraph.h" #include "dijkstra.h" struct Point { long long lat, lon; }; // returns the manhattan distance between two points long long manhattan(const Point& pt1, const Point& pt2) { long long dLat = pt1.lat - pt2.lat, dLon = pt1.lon - pt2.lon; return abs(dLat) + abs(dLon); } // finds the point that is closest to a given point, pt int findClosest(const Point& pt, const unordered_map<int, Point>& points) { std::cout << "In findClosest 28\n"; // pair<int, Point> best = *points.begin(); // for (const auto& check : points) { // if (manhattan(pt, check.second) < manhattan(pt, best.second)) { // best = check; // } // } // std::cout << "Returning form findClosest 35\n"; // return best.first; int startVertex = 0; int distance = 2147483647; for (auto it: points){ //computing the vertex nearest to start vertex long long temp = manhattan(it.second, pt); if (temp <= distance){ distance = temp; startVertex = it.first; } } return startVertex; } // reads graph description from the input file and builts a graph instance void readGraph(const string& filename, WDigraph& g, unordered_map<int, Point>& points) { ifstream fin(filename); string line; while (getline(fin, line)) { // split the string around the commas, there will be 4 substrings either way string p[4]; int at = 0; for (auto c : line) { if (c == ',') { // starting a new string ++at; } else { // appending a character to the string we are building p[at] += c; } } if (at != 3) { // empty line break; } if (p[0] == "V") { // adding a new vertex int id = stoi(p[1]); assert(id == stoll(p[1])); // sanity check: asserts if some id is not 32-bit points[id].lat = static_cast<long long>(stod(p[2])*100000); points[id].lon = static_cast<long long>(stod(p[3])*100000); g.addVertex(id); } else { // adding a new directed edge int u = stoi(p[1]), v = stoi(p[2]); g.addEdge(u, v, manhattan(points[u], points[v])); } } } // Keep in mind that in Part I, your program must handle 1 request // but in Part 2 you must serve the next request as soon as you are // done handling the previous one // int main(int argc, char* argv[]) { // WDigraph graph; // unordered_map<int, Point> points; // // build the graph // readGraph("edmonton-roads-2.0.1.txt", graph, points); // // In Part 2, client and server communicate using a pair of sockets // // modify the part below so that the route request is read from a socket // // (instead of stdin) and the route information is written to a socket // // read a request // char c; // Point sPoint, ePoint; // cin >> c >> sPoint.lat >> sPoint.lon >> ePoint.lat >> ePoint.lon; // // c is guaranteed to be 'R' in part 1, no need to error check until part 2 // // get the points closest to the two points we read // int start = findClosest(sPoint, points), end = findClosest(ePoint, points); // // run dijkstra's, this is the unoptimized version that does not stop // // when the end is reached but it is still fast enough // unordered_map<int, PIL> tree; // dijkstra(graph, start, tree); // // no path // if (tree.find(end) == tree.end()) { // cout << "N 0" << endl; // } // else { // // read off the path by stepping back through the search tree // list<int> path; // while (end != start) { // path.push_front(end); // end = tree[end].first; // } // path.push_front(start); // // output the path // cout << "N " << path.size() << endl; // for (int v : path) { // cout << "W " << points[v].lat << ' ' << points[v].lon << endl; // } // cout << "E" << endl; // } // return 0; // } // Keep in mind that in Part I, your program must handle 1 request // but in Part 2 you must serve the next request as soon as you are // done handling the previous one int main(int argc, char* argv[]) { // need to make it unsign int PORT = 50000, LISTEN_BACKLOG = 50, BUFFER_SIZE = 1024; WDigraph graph; unordered_map<int, Point> points; Point sPoint, ePoint; unordered_map<int, PIL> tree; int start, end; // build the graph readGraph("edmonton-roads-2.0.1.txt", graph, points); // In Part 2, client and server communicate using a pair of sockets // modify the part below so that the route request is read from a socket // (instead of stdin) and the route information is written to a socket if (argc == 2){ PORT = atoi(argv[1]); } else{ std::cout << "Enter port number: \n"; } struct sockaddr_in my_addr, peer_addr; memset(&my_addr, '\0', sizeof my_addr); int lstn_socket_desc, conn_socket_desc; char buffer[BUFFER_SIZE] = {}; lstn_socket_desc = socket(AF_INET, SOCK_STREAM, 0); if (lstn_socket_desc == -1){ std::cerr << "Listening socket creation failed!\n"; return 1; } my_addr.sin_family = AF_INET; my_addr.sin_port = htons(PORT); my_addr.sin_addr.s_addr = htonl(INADDR_ANY); if (bind(lstn_socket_desc, (struct sockaddr *) &my_addr, sizeof my_addr) == -1){ std::cerr << "Binding failed!\n"; close(lstn_socket_desc); return 1; } std::cout<< "Binding was successful\n"; if(listen(lstn_socket_desc, LISTEN_BACKLOG) == -1){ std::cerr << "Cannot listen to the specified socket!\n"; close(lstn_socket_desc); return 1; } socklen_t peer_addr_size = sizeof my_addr; conn_socket_desc = accept(lstn_socket_desc, (struct sockaddr *) &peer_addr, &peer_addr_size); if (conn_socket_desc == -1){ std::cerr << "Connection socket creation failed!\n"; // Need to check weather to continue // Need to check if we need to close the socket descriptor return 1; } std::cout << "Connection request accepted from " << inet_ntoa(peer_addr.sin_addr); std::cout << ":" << ntohs(peer_addr.sin_port) << "\n"; // struct timeval timer = {.tv_sec = 1, .tv_usec = 10000}; struct timeval timer = {.tv_sec = 1}; if (setsockopt(conn_socket_desc, SOL_SOCKET, SO_RCVTIMEO, (void *) &timer, sizeof(timer)) == -1) { std::cerr << "Cannot set socket options!\n"; close(lstn_socket_desc); return 1; } while(true) { std::cout << "Inside while loop\n"; int rec_size = recv(conn_socket_desc, buffer, BUFFER_SIZE, 0); if (rec_size == -1){ std::cout << "Timeout occurred.. still waiting!\n"; continue; } std::cout << "Message received\n"; // Point sPoint, ePoint; // unordered_map<int, PIL> tree; // int start, end; // sPoint.lat = 0; sPoint.lon = 0; ePoint.lat = 0; ePoint.lat = 0; if (strcmp("Q", buffer) == 0) { std::cout << "Connection will be closed\n"; // Need to check since we need to close connection // I am thinking to closing the file destrctor would make more sense // and then returning from the program break; } char R = 'R'; std::cout << "Checkpotin1\n"; if (buffer[0] == R){ // Need to check this way // char *p[5]; // std::cout << "Checkpoint1\n"; string point[5]; int at = 0; for (auto c : buffer) { if (c == ' ') { // starting a new string ++at; } else { // appending a character to the string we are building point[at] += c; } } char point1[point[1].length()]; for (int i = 0; i < point[1].length(); i++){ point1[i] = point[1][i]; } char point2[point[2].length()]; for (int i = 0; i < point[2].length(); i++){ point2[i] = point[2][i]; } char point3[point[3].length()]; for (int i = 0; i < point[3].length(); i++){ point3[i] = point[3][i]; } char point4[point[4].length()]; for (int i = 0; i < point[4].length(); i++){ point4[i] = point[4][i]; } sPoint.lat = atol(point1); sPoint.lon = atol(point2); ePoint.lat = atol(point3); ePoint.lon = atol(point4); // sPoint.lat = atoi(p[1]);sPoint.lon = atoi(p[2]); // ePoint.lat = atoi(p[3]);ePoint.lon = atoi(p[4]); start = findClosest(sPoint, points); end = findClosest(ePoint, points); std::cout << "Checkpoint1 279\n"; std::cout << "Calling dijkstra\n"; dijkstra(graph, start, tree); std::cout << "After dijkstra\n"; if (tree.find(end) == tree.end()) { std::string str = "N 0"; send(conn_socket_desc, str.c_str(), str.length() + 1, 0); std::cout << "No path\n"; continue; } else { // read off the path by stepping back through the search tree list<int> path; while (end != start) { path.push_front(end); end = tree[end].first; } path.push_front(start); // output the path // cout << "N " << path.size() << endl; std::string str = "N "; str += std::to_string(path.size()); send(conn_socket_desc, str.c_str(), str.length() + 1, 0); rec_size = recv(conn_socket_desc, buffer, BUFFER_SIZE, 0); if (rec_size == -1){ std::cout << "Timeout occurred.. still waiting!\n"; continue; } char A = 'A'; if (buffer[0] != A){ std::cout << "Received unexpected message!\n"; continue; } for (int v : path) { std::string Way_point = "W "; str += std::to_string(points[v].lat); str += " "; str += std::to_string(points[v].lon); // str += "\n"; need to check if I need to send newline character send(conn_socket_desc, Way_point.c_str(), Way_point.length() + 1, 0); rec_size = recv(conn_socket_desc, buffer, BUFFER_SIZE, 0); // if (rec_size == -1) {} if (rec_size == -1) { std::cout << "Timeout occurred.. still waiting!\n"; // Need to find a way to get to ther outer loop continue; } else{ if (buffer[0] != A){ std::cout << "Received unexpected message!\n"; // Need to find a way to get to the outer loop continue; } } } str = "E"; send(conn_socket_desc, str.c_str(), str.length() + 1, 0); continue; // Need to conform } } else{ std::cout << "Received unexpected message!\n"; continue; } } return 0; }
[ "atmakurirevanth@gamil.com" ]
atmakurirevanth@gamil.com
ddb7ba7577bd9bb8e5d49ffd531a27cf74e7e65e
77222419f857e8a79ee142f9b388a917b28a6b51
/Dragon/src/operators/utils/compare_op.cc
07077d97553616de66e761268cf2c3d7fad57e2d
[ "BSD-2-Clause" ]
permissive
zhangkaij/Dragon
f7032dd32179918e9c38314c4414a4c6c75cbf7d
31e02b2b20f382ac558094d1a57fa91328a8b3ad
refs/heads/master
2021-01-02T22:52:32.986372
2017-08-02T10:33:41
2017-08-02T10:33:41
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,080
cc
#include "operators/utils/compare_op.h" #include "utils/op_kernel.h" namespace dragon { template <class Context> template <typename T> void CompareOp<Context>::EqualRunWithType() { auto* X1data = input(0).template data<T, Context>(); auto* X2data = input(1).template data<T, Context>(); auto* Ydata = output(0)->template mutable_data<T, Context>(); kernel::Equal<T, Context>(output(0)->count(), X1data, X2data, Ydata); } template <class Context> void CompareOp<Context>::RunOnDevice(){ CHECK_EQ(input(0).count(), input(1).count()) << "both conditioned tensor must have same elements."; output(0)->ReshapeLike(input(0)); if (operation == "EQUAL") { if (input(0).template IsType<float>()) EqualRunWithType<float>(); else LOG(FATAL) << "unsupported input types."; } else { LOG(FATAL) << "unsupport operation: [" << operation << "]."; } } DEPLOY_CPU(Compare); #ifdef WITH_CUDA DEPLOY_CUDA(Compare); #endif OPERATOR_SCHEMA(Compare).NumInputs(2).NumOutputs(1); NO_GRADIENT(Compare); } // namespace dragon
[ "ting.pan@seetatech.com" ]
ting.pan@seetatech.com
02e2cf933d1a13ae9e0c9eb37bd587dc63ba9345
4c984f6363ebb33d4cea7412c0292c85a500abed
/src/tile_map.hpp
5a18bcfa060f51a598cb92590d8efd5b431309e5
[]
no_license
ibawt/evpp
feb94efc807f34f82fb6d2b033328d6e4e3618ff
1e0d4f53cf8a9083caadfc9d3857160ae518264c
refs/heads/master
2020-03-28T19:48:24.435441
2018-09-16T15:58:16
2018-09-16T15:58:16
149,011,409
0
0
null
null
null
null
UTF-8
C++
false
false
1,177
hpp
#pragma once #include "sprite_batch.hpp" namespace ev { enum TileType { OUTER_UPPER_LEFT = 0x0, OUTER_TOP = 0x1, OUTER_UPPER_RIGHT = 0x2, MIDDLE_SMALL = 0x3, TOP_T = 0x4, EMPTY_0 = 0x5, OUTER_LEFT = 0x6, MIDDLE_LARGE = 0x7, EMPTY_1 = 0x8, LEFT_T = 0x9, CROSS_T = 10, RIGHT_T = 11, OUTER_BOTTOM_LEFT = 12, EMPTY_2 = 13, OUTER_BOTTOM_RIGHT = 14, EMPTY_3 = 15, BOTTOM_T = 16, EMPTY_4 = 17 }; struct Tile { int tile_set = 0; TileType type = TileType::OUTER_LEFT; }; class TileMap { public: TileMap(int rows, int cols, int tile_size, std::shared_ptr<Texture> tex); virtual ~TileMap(); void set_viewport(const Rectangle&); Rectangle get_viewport() const; int get_rows() const { return rows; } int get_cols() const { return columns; } int get_tile_size() const { return tile_size; } void render(const glm::mat4&); private: int fill(BatchVertex *bv, const Tile&, const vec2&); Rectangle view_port; int rows = 0; int columns = 0; int tile_size = 0; Size texture_size; std::vector<Tile> tiles; SpriteBatch batch; }; }
[ "ian.quick@gmail.com" ]
ian.quick@gmail.com
ea1b6c72dd33c7d3d9fb71f46e5c2acd51296b4b
4c3bb93a8975083665456c3ce89a37b318d12c2d
/src/util.h
d3528e9117d93f9acfd7e0012d1c245099ffcf8b
[ "MIT" ]
permissive
HexxDev/Hexx
0b8fc063103b4f794903ee8e1b822be6875b5b6c
6a955ae132e0227bf40f5cb9532d8aa7e21b4676
refs/heads/master
2020-05-01T05:03:29.199732
2015-06-24T20:24:57
2015-06-24T20:24:57
37,999,283
0
0
null
null
null
null
UTF-8
C++
false
false
17,549
h
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2012 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef BITCOIN_UTIL_H #define BITCOIN_UTIL_H #ifndef WIN32 #include <sys/types.h> #include <sys/time.h> #include <sys/resource.h> #endif #include "serialize.h" #include "tinyformat.h" #include <map> #include <list> #include <utility> #include <vector> #include <string> #include <boost/thread.hpp> #include <boost/filesystem.hpp> #include <boost/filesystem/path.hpp> #include <boost/date_time/gregorian/gregorian_types.hpp> #include <boost/date_time/posix_time/posix_time_types.hpp> #include <openssl/bio.h> #include <openssl/evp.h> #include <openssl/buffer.h> #include <openssl/crypto.h> // for OPENSSL_cleanse() #include <openssl/rand.h> #include <openssl/bn.h> #include <stdint.h> class uint256; static const int64_t COIN = 100000000; static const int64_t CENT = 1000000; typedef int64_t CAmount; #define BEGIN(a) ((char*)&(a)) #define END(a) ((char*)&((&(a))[1])) #define UBEGIN(a) ((unsigned char*)&(a)) #define UEND(a) ((unsigned char*)&((&(a))[1])) #define ARRAYLEN(array) (sizeof(array)/sizeof((array)[0])) #define UVOIDBEGIN(a) ((void*)&(a)) #define CVOIDBEGIN(a) ((const void*)&(a)) #define UINTBEGIN(a) ((uint32_t*)&(a)) #define CUINTBEGIN(a) ((const uint32_t*)&(a)) /* Format characters for (s)size_t and ptrdiff_t */ #if defined(_MSC_VER) || defined(__MSVCRT__) /* (s)size_t and ptrdiff_t have the same size specifier in MSVC: http://msdn.microsoft.com/en-us/library/tcxf1dw6%28v=vs.100%29.aspx */ #define PRIszx "Ix" #define PRIszu "Iu" #define PRIszd "Id" #define PRIpdx "Ix" #define PRIpdu "Iu" #define PRIpdd "Id" #else /* C99 standard */ #define PRIszx "zx" #define PRIszu "zu" #define PRIszd "zd" #define PRIpdx "tx" #define PRIpdu "tu" #define PRIpdd "td" #endif // This is needed because the foreach macro can't get over the comma in pair<t1, t2> #define PAIRTYPE(t1, t2) std::pair<t1, t2> // Align by increasing pointer, must have extra space at end of buffer template <size_t nBytes, typename T> T* alignup(T* p) { union { T* ptr; size_t n; } u; u.ptr = p; u.n = (u.n + (nBytes-1)) & ~(nBytes-1); return u.ptr; } boost::filesystem::path GetMasternodeConfigFile(); #ifdef WIN32 #define MSG_NOSIGNAL 0 #define MSG_DONTWAIT 0 #ifndef S_IRUSR #define S_IRUSR 0400 #define S_IWUSR 0200 #endif #else #define MAX_PATH 1024 #endif inline void MilliSleep(int64_t n) { #if BOOST_VERSION >= 105000 boost::this_thread::sleep_for(boost::chrono::milliseconds(n)); #else boost::this_thread::sleep(boost::posix_time::milliseconds(n)); #endif } //Dark features extern bool fMasterNode; extern bool fLiteMode; extern int nInstantXDepth; extern int nDarksendRounds; extern int nAnonymizeHXXAmount; extern int nLiquidityProvider; extern bool fEnableDarksend; extern int64_t enforceMasternodePaymentsTime; extern std::string strMasterNodeAddr; extern int keysLoaded; extern bool fSucessfullyLoaded; extern std::vector<int64_t> darkSendDenominations; extern std::map<std::string, std::string> mapArgs; extern std::map<std::string, std::vector<std::string> > mapMultiArgs; extern bool fDebug; extern bool fPrintToConsole; extern bool fPrintToDebugLog; extern bool fDaemon; extern bool fServer; extern bool fCommandLine; extern std::string strMiscWarning; extern bool fNoListen; extern bool fLogTimestamps; extern volatile bool fReopenDebugLog; void RandAddSeed(); void RandAddSeedPerfmon(); /* Return true if log accepts specified category */ bool LogAcceptCategory(const char* category); /* Send a string to the log output */ int LogPrintStr(const std::string &str); #define LogPrintf(...) LogPrint(NULL, __VA_ARGS__) /* When we switch to C++11, this can be switched to variadic templates instead * of this macro-based construction (see tinyformat.h). */ #define MAKE_ERROR_AND_LOG_FUNC(n) \ /* Print to debug.log if -debug=category switch is given OR category is NULL. */ \ template<TINYFORMAT_ARGTYPES(n)> \ static inline int LogPrint(const char* category, const char* format, TINYFORMAT_VARARGS(n)) \ { \ if(!LogAcceptCategory(category)) return 0; \ return LogPrintStr(tfm::format(format, TINYFORMAT_PASSARGS(n))); \ } \ /* Log error and return false */ \ template<TINYFORMAT_ARGTYPES(n)> \ static inline bool error(const char* format, TINYFORMAT_VARARGS(n)) \ { \ LogPrintStr("ERROR: " + tfm::format(format, TINYFORMAT_PASSARGS(n)) + "\n"); \ return false; \ } TINYFORMAT_FOREACH_ARGNUM(MAKE_ERROR_AND_LOG_FUNC) /* Zero-arg versions of logging and error, these are not covered by * TINYFORMAT_FOREACH_ARGNUM */ static inline int LogPrint(const char* category, const char* format) { if(!LogAcceptCategory(category)) return 0; return LogPrintStr(format); } static inline bool error(const char* format) { LogPrintStr(std::string("ERROR: ") + format + "\n"); return false; } void PrintException(std::exception* pex, const char* pszThread); void PrintExceptionContinue(std::exception* pex, const char* pszThread); void ParseString(const std::string& str, char c, std::vector<std::string>& v); std::string FormatMoney(int64_t n, bool fPlus=false); bool ParseMoney(const std::string& str, int64_t& nRet); bool ParseMoney(const char* pszIn, int64_t& nRet); std::string SanitizeString(const std::string& str); std::vector<unsigned char> ParseHex(const char* psz); std::vector<unsigned char> ParseHex(const std::string& str); bool IsHex(const std::string& str); std::vector<unsigned char> DecodeBase64(const char* p, bool* pfInvalid = NULL); std::string DecodeBase64(const std::string& str); std::string EncodeBase64(const unsigned char* pch, size_t len); std::string EncodeBase64(const std::string& str); SecureString DecodeBase64Secure(const SecureString& input); SecureString EncodeBase64Secure(const SecureString& input); std::vector<unsigned char> DecodeBase32(const char* p, bool* pfInvalid = NULL); std::string DecodeBase32(const std::string& str); std::string EncodeBase32(const unsigned char* pch, size_t len); std::string EncodeBase32(const std::string& str); void ParseParameters(int argc, const char*const argv[]); bool WildcardMatch(const char* psz, const char* mask); bool WildcardMatch(const std::string& str, const std::string& mask); void FileCommit(FILE *fileout); bool RenameOver(boost::filesystem::path src, boost::filesystem::path dest); boost::filesystem::path GetDefaultDataDir(); const boost::filesystem::path &GetDataDir(bool fNetSpecific = true); boost::filesystem::path GetConfigFile(); boost::filesystem::path GetPidFile(); #ifndef WIN32 void CreatePidFile(const boost::filesystem::path &path, pid_t pid); #endif void ReadConfigFile(std::map<std::string, std::string>& mapSettingsRet, std::map<std::string, std::vector<std::string> >& mapMultiSettingsRet); #ifdef WIN32 boost::filesystem::path GetSpecialFolderPath(int nFolder, bool fCreate = true); #endif void ShrinkDebugFile(); void GetRandBytes(unsigned char* buf, int num); int GetRandInt(int nMax); uint64_t GetRand(uint64_t nMax); uint256 GetRandHash(); int64_t GetTime(); void SetMockTime(int64_t nMockTimeIn); std::string FormatFullVersion(); std::string FormatSubVersion(const std::string& name, int nClientVersion, const std::vector<std::string>& comments); void runCommand(std::string strCommand); /** * Convert string to signed 32-bit integer with strict parse error feedback. * @returns true if the entire string could be parsed as valid integer, * false if not the entire string could be parsed or when overflow or underflow occurred. */ bool ParseInt32(const std::string& str, int32_t *out); /** * Format a paragraph of text to a fixed width, adding spaces for * indentation to any added line. */ std::string FormatParagraph(const std::string in, size_t width=79, size_t indent=0); inline std::string i64tostr(int64_t n) { return strprintf("%d", n); } inline std::string itostr(int n) { return strprintf("%d", n); } inline int64_t atoi64(const char* psz) { #ifdef _MSC_VER return _atoi64(psz); #else return strtoll(psz, NULL, 10); #endif } inline int64_t atoi64(const std::string& str) { #ifdef _MSC_VER return _atoi64(str.c_str()); #else return strtoll(str.c_str(), NULL, 10); #endif } inline int atoi(const std::string& str) { return atoi(str.c_str()); } inline int roundint(double d) { return (int)(d > 0 ? d + 0.5 : d - 0.5); } inline int64_t roundint64(double d) { return (int64_t)(d > 0 ? d + 0.5 : d - 0.5); } inline int64_t abs64(int64_t n) { return (n >= 0 ? n : -n); } inline std::string leftTrim(std::string src, char chr) { std::string::size_type pos = src.find_first_not_of(chr, 0); if(pos > 0) src.erase(0, pos); return src; } template<typename T> std::string HexStr(const T itbegin, const T itend, bool fSpaces=false) { std::string rv; static const char hexmap[16] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' }; rv.reserve((itend-itbegin)*3); for(T it = itbegin; it < itend; ++it) { unsigned char val = (unsigned char)(*it); if(fSpaces && it != itbegin) rv.push_back(' '); rv.push_back(hexmap[val>>4]); rv.push_back(hexmap[val&15]); } return rv; } template<typename T> inline std::string HexStr(const T& vch, bool fSpaces=false) { return HexStr(vch.begin(), vch.end(), fSpaces); } inline int64_t GetPerformanceCounter() { int64_t nCounter = 0; #ifdef WIN32 QueryPerformanceCounter((LARGE_INTEGER*)&nCounter); #else timeval t; gettimeofday(&t, NULL); nCounter = (int64_t) t.tv_sec * 1000000 + t.tv_usec; #endif return nCounter; } inline int64_t GetTimeMillis() { return (boost::posix_time::ptime(boost::posix_time::microsec_clock::universal_time()) - boost::posix_time::ptime(boost::gregorian::date(1970,1,1))).total_milliseconds(); } inline int64_t GetTimeMicros() { return (boost::posix_time::ptime(boost::posix_time::microsec_clock::universal_time()) - boost::posix_time::ptime(boost::gregorian::date(1970,1,1))).total_microseconds(); } std::string DateTimeStrFormat(const char* pszFormat, int64_t nTime); static const std::string strTimestampFormat = "%Y-%m-%d %H:%M:%S UTC"; inline std::string DateTimeStrFormat(int64_t nTime) { return DateTimeStrFormat(strTimestampFormat.c_str(), nTime); } template<typename T> void skipspaces(T& it) { while (isspace(*it)) ++it; } inline bool IsSwitchChar(char c) { #ifdef WIN32 return c == '-' || c == '/'; #else return c == '-'; #endif } /** * Return string argument or default value * * @param strArg Argument to get (e.g. "-foo") * @param default (e.g. "1") * @return command-line argument or default value */ std::string GetArg(const std::string& strArg, const std::string& strDefault); /** * Return integer argument or default value * * @param strArg Argument to get (e.g. "-foo") * @param default (e.g. 1) * @return command-line argument (0 if invalid number) or default value */ int64_t GetArg(const std::string& strArg, int64_t nDefault); /** * Return boolean argument or default value * * @param strArg Argument to get (e.g. "-foo") * @param default (true or false) * @return command-line argument or default value */ bool GetBoolArg(const std::string& strArg, bool fDefault); /** * Set an argument if it doesn't already have a value * * @param strArg Argument to set (e.g. "-foo") * @param strValue Value (e.g. "1") * @return true if argument gets set, false if it already had a value */ bool SoftSetArg(const std::string& strArg, const std::string& strValue); /** * Set a boolean argument if it doesn't already have a value * * @param strArg Argument to set (e.g. "-foo") * @param fValue Value (e.g. false) * @return true if argument gets set, false if it already had a value */ bool SoftSetBoolArg(const std::string& strArg, bool fValue); /** * MWC RNG of George Marsaglia * This is intended to be fast. It has a period of 2^59.3, though the * least significant 16 bits only have a period of about 2^30.1. * * @return random value */ extern uint32_t insecure_rand_Rz; extern uint32_t insecure_rand_Rw; static inline uint32_t insecure_rand(void) { insecure_rand_Rz=36969*(insecure_rand_Rz&65535)+(insecure_rand_Rz>>16); insecure_rand_Rw=18000*(insecure_rand_Rw&65535)+(insecure_rand_Rw>>16); return (insecure_rand_Rw<<16)+insecure_rand_Rz; } /** * Seed insecure_rand using the random pool. * @param Deterministic Use a determinstic seed */ void seed_insecure_rand(bool fDeterministic=false); /** * Timing-attack-resistant comparison. * Takes time proportional to length * of first argument. */ template <typename T> bool TimingResistantEqual(const T& a, const T& b) { if (b.size() == 0) return a.size() == 0; size_t accumulator = a.size() ^ b.size(); for (size_t i = 0; i < a.size(); i++) accumulator |= a[i] ^ b[i%b.size()]; return accumulator == 0; } /** Median filter over a stream of values. * Returns the median of the last N numbers */ template <typename T> class CMedianFilter { private: std::vector<T> vValues; std::vector<T> vSorted; unsigned int nSize; public: CMedianFilter(unsigned int size, T initial_value): nSize(size) { vValues.reserve(size); vValues.push_back(initial_value); vSorted = vValues; } void input(T value) { if(vValues.size() == nSize) { vValues.erase(vValues.begin()); } vValues.push_back(value); vSorted.resize(vValues.size()); std::copy(vValues.begin(), vValues.end(), vSorted.begin()); std::sort(vSorted.begin(), vSorted.end()); } T median() const { int size = vSorted.size(); assert(size>0); if(size & 1) // Odd number of elements { return vSorted[size/2]; } else // Even number of elements { return (vSorted[size/2-1] + vSorted[size/2]) / 2; } } int size() const { return vValues.size(); } std::vector<T> sorted () const { return vSorted; } }; #ifdef WIN32 inline void SetThreadPriority(int nPriority) { SetThreadPriority(GetCurrentThread(), nPriority); } #else #define THREAD_PRIORITY_LOWEST PRIO_MAX #define THREAD_PRIORITY_BELOW_NORMAL 2 #define THREAD_PRIORITY_NORMAL 0 #define THREAD_PRIORITY_ABOVE_NORMAL 0 inline void SetThreadPriority(int nPriority) { // It's unclear if it's even possible to change thread priorities on Linux, // but we really and truly need it for the generation threads. #ifdef PRIO_THREAD setpriority(PRIO_THREAD, 0, nPriority); #else setpriority(PRIO_PROCESS, 0, nPriority); #endif } #endif void RenameThread(const char* name); inline uint32_t ByteReverse(uint32_t value) { value = ((value & 0xFF00FF00) >> 8) | ((value & 0x00FF00FF) << 8); return (value<<16) | (value>>16); } // Standard wrapper for do-something-forever thread functions. // "Forever" really means until the thread is interrupted. // Use it like: // new boost::thread(boost::bind(&LoopForever<void (*)()>, "dumpaddr", &DumpAddresses, 900000)); // or maybe: // boost::function<void()> f = boost::bind(&FunctionWithArg, argument); // threadGroup.create_thread(boost::bind(&LoopForever<boost::function<void()> >, "nothing", f, milliseconds)); template <typename Callable> void LoopForever(const char* name, Callable func, int64_t msecs) { std::string s = strprintf("hexxcoin-%s", name); RenameThread(s.c_str()); LogPrintf("%s thread start\n", name); try { while (1) { MilliSleep(msecs); func(); } } catch (boost::thread_interrupted) { LogPrintf("%s thread stop\n", name); throw; } catch (std::exception& e) { PrintException(&e, name); } catch (...) { PrintException(NULL, name); } } // .. and a wrapper that just calls func once template <typename Callable> void TraceThread(const char* name, Callable func) { std::string s = strprintf("hexxcoin-%s", name); RenameThread(s.c_str()); try { LogPrintf("%s thread start\n", name); func(); LogPrintf("%s thread exit\n", name); } catch (boost::thread_interrupted) { LogPrintf("%s thread interrupt\n", name); throw; } catch (std::exception& e) { PrintException(&e, name); } catch (...) { PrintException(NULL, name); } } #endif
[ "I@know.you" ]
I@know.you
713fd8f7cb37769cc2263919b4a3d74e60a8ea7d
b9b6a727aff37f61f2e9b0003fc385168fc8af7c
/Arduino/prueba_Control/prueba_Control.ino
ef37a674dcd3dd419abb5c3736c55caa245c6fd8
[]
no_license
larivera-UVG/AmboVent-UVG
791ba3256058b755f99df89801dd4905b81d0b5b
eda7adcba78ae75743da0e1050a52ea05096525c
refs/heads/master
2021-05-22T23:05:41.786087
2020-08-04T22:11:07
2020-08-04T22:11:07
253,135,081
0
0
null
null
null
null
UTF-8
C++
false
false
7,528
ino
/* AmboVent-UVG prueba_Control.ino Para verificar la función calculate_wanted_pos_vel() Based on the original code for the AmboVent (April 12, 2020) */ #define DEBUG 1 // 1 para que forzar a |error| < ERROR_DEBUG #define ERROR_DEBUG 25 #define cycleTime 10 // milisec #define FF 0.6 // motion control feed forward. 0.6, 4.5 #define KP 0.2 // motion control propportional gain 0.2, 1.2 #define KI 2 // motion control integral gain 2, 7 #define integral_limit 5 // limits the integral of error #define f_reduction_up_val 0.85 // reduce feedforward by this factor when moving up #define motion_control_allowed_error 30 // % of range #define profile_length 250 // motion control profile length #define PWM_mid 93 // mid value for PWM 0 motion - higher pushes up #define PWM_max 85 #define PWM_min (-PWM_max) #define DELTA_TELE_MONITOR 23 // Para que no se despliegue tantas veces, y no siempre // se desplieguen los mismos índices. #define pin_POT A0 // analog pin of motion feedback potentiometer #define invert_mot 0 const PROGMEM byte pos[profile_length] = { 0, 0, 1, 2, 4, 6, 8, 10, 13, 15, 18, 21, 25, 28, 31, 35, 38, 42, 46, 50, 54, 57, 61, 66, 70, 74, 78, 82, 86, 91, 95, 99,104,108,112,117,121,125,130,134, 138,143,147,151,156,160,164,169,173,177,181,185,189,194,198,201,205,209,213,217, 220,224,227,230,234,237,240,242,245,247,249,251,253,254,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,254,253,252,250,248,246,244,241,238,235,232,229,225, 222,218,214,210,206,202,198,193,189,184,180,175,171,166,162,157,152,148,143,138, 134,129,124,120,115,111,106,102, 97, 93, 89, 84, 80, 76, 72, 68, 64, 61, 57, 54, 50, 47, 44, 41, 38, 36, 33, 31, 29, 27, 25, 23, 22, 20, 19, 17, 16, 15, 13, 12, 11, 10, 9, 8, 7, 6, 6, 5, 4, 3, 3, 2, 2, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0}; const PROGMEM byte vel[profile_length] = {129,132,134,136,137,139,140,141,142,143,143,144,144,145,146,146,146,147,147,147, 148,148,148,148,149,149,149,149,149,149,150,150,150,150,150,150,150,150,150,150, 150,150,150,150,150,149,149,149,149,149,149,148,148,148,148,147,147,147,146,146, 146,145,144,144,143,143,142,141,140,139,137,136,134,132,129,128,128,128,128,128, 128,128,128,128,128,128,128,128,128,128,128,128,128,128,128,128,128,128,128,128, 128,128,128,128,128,128,128,128,128,128,128,128,128,128,128,128,128,128,128,128, 128,128,128,128,128,127,125,123,121,120,119,117,116,115,114,113,112,111,111,110, 109,109,108,108,107,107,106,106,106,106,105,105,105,105,105,105,105,105,105,105, 105,105,105,105,105,105,106,106,106,107,107,107,108,108,109,109,110,110,111,111, 112,113,113,114,115,116,117,118,118,119,119,120,120,120,121,121,121,122,122,122, 123,123,123,124,124,124,124,125,125,125,125,125,126,126,126,126,126,127,127,127, 127,127,127,127,128,128,128,128,128,128,128,128,128,128,128,128,129,129,129,129, 129,129,129,129,129,128,128,128,128,128}; // --------- PARÁMETROS PARA PROBAR ------------------------------------------- // 0 <= min_arm_pos < max_arm_pos <= 1023 unsigned int min_arm_pos = 8, max_arm_pos = 1023; float range_factor = 1.0; // entre 0.0 y 1.0 byte wanted_cycle_time = 10; // entre 10 y 20 // ---------------------------------------------------------------------------- byte motion_failure = 0; float wanted_pos, wanted_vel_PWM, range, profile_planned_vel, planned_vel, integral, error, prev_error, f_reduction_up; int index = 0, A_pot, motorPWM; unsigned long lastTele = 0, lastIndex = 0; void setup() { Serial.begin(115200); #if DEBUG == 1 randomSeed(analogRead(0)); #endif } void loop() { A_pot = analogRead(pin_POT); if(millis() - lastIndex >= wanted_cycle_time) // wait for the cycle time { lastIndex = millis(); // last start of cycle time calculate_wanted_pos_vel(); if(100*abs(error)/(max_arm_pos - min_arm_pos) > motion_control_allowed_error) motion_failure = 1; else motion_failure = 0; if(millis() - lastTele >= DELTA_TELE_MONITOR) // esperar para mostrar telemetry { lastTele = millis(); // last time telemetry was displayed print_tele(); } index = (index + 1)%profile_length; } set_motor_PWM(wanted_vel_PWM); } void calculate_wanted_pos_vel() { byte pos_from_profile, vel_from_profile; pos_from_profile = pgm_read_byte_near(pos + index); vel_from_profile = pgm_read_byte_near(vel + index + 1); range = range_factor*(max_arm_pos - min_arm_pos); // range of movement in pot' readings wanted_pos = float(pos_from_profile)*range/255 + min_arm_pos; // wanted pos in pot clicks profile_planned_vel = (float(vel_from_profile) - 128.01)*range/255; // in clicks per 0.2 second planned_vel = profile_planned_vel; /* if(hold_breath == 1 && safety_pressure_detected == 0) { if(wanted_pos <= float(A_pot) || index == 0) hold_breath = 0; planned_vel = 0; integral = 0; wanted_pos = float(A_pot); // hold current position } if(safety_pressure_detected) // to do the revese in case high pressure detected planned_vel = -speed_multiplier_reverse*planned_vel; */ prev_error = error; error = wanted_pos - float(A_pot); #if DEBUG == 1 error = -ERROR_DEBUG + random(2*ERROR_DEBUG); #endif integral += error*float(wanted_cycle_time)/1000; if(integral > integral_limit) integral = integral_limit; if(integral < -integral_limit) integral = -integral_limit; if(index < 2 || prev_error*error < 0) integral = 0; // zero the integral accumulator at the beginning of cycle and movement up if(planned_vel < 0) f_reduction_up = f_reduction_up_val; else f_reduction_up = 1; // reduce f for the movement up // PID correction wanted_vel_PWM = FF*planned_vel*f_reduction_up + KP*error + KI*integral; // reduce speed for longer cycles wanted_vel_PWM = wanted_vel_PWM*float(cycleTime)/float(wanted_cycle_time); } void set_motor_PWM(float wanted_vel_PWM) { // Se quitaron muchas cosas de la función en AmboVent-UVG if(invert_mot) wanted_vel_PWM = -wanted_vel_PWM; if(wanted_vel_PWM > 0) wanted_vel_PWM += 3; // undo controller dead band if(wanted_vel_PWM < 0) wanted_vel_PWM -= 3; // undo controller dead band if(wanted_vel_PWM > PWM_max) wanted_vel_PWM = PWM_max; // limit PWM if(wanted_vel_PWM < PWM_min) wanted_vel_PWM = PWM_min; // limit PWM motorPWM = (int)(wanted_vel_PWM*255.0/PWM_max); // set between 0 and 255 } void print_tele() { Serial.print("Index: "); Serial.print(index); Serial.print(", Feedback: "); Serial.print(A_pot); Serial.print(", wanted_pos: "); Serial.print(wanted_pos); Serial.print(", error: "); Serial.print(error); Serial.print(", integral: "); Serial.println(integral); Serial.print("planned_vel: "); Serial.print(planned_vel); Serial.print(", wanted_vel_PWM: "); Serial.print(wanted_vel_PWM); Serial.print(", motorPWM: "); Serial.print(motorPWM); Serial.print(", motion_failure: "); Serial.println(motion_failure); Serial.println(""); }
[ "60155635+larivera-UVG@users.noreply.github.com" ]
60155635+larivera-UVG@users.noreply.github.com
4501819b6ffe3e6a241cc0d3ac53f49d2ee9ad1a
b2439de602f728583084ff65e726cb8eb427f6fc
/ipc/ipc_systemv_mq_send.cpp
59270ae6f7e808c096fdc464a11812317cbf5b87
[ "Apache-2.0" ]
permissive
opensource000/cnblogs
2ba43784167872edccb55cad3bc43827429f4a57
31eaee01e150072f26ac50d43a740143016588ea
refs/heads/master
2021-01-19T04:18:50.799106
2016-07-17T14:42:17
2016-07-17T14:42:17
44,439,330
3
1
null
null
null
null
UTF-8
C++
false
false
1,486
cpp
#include <unistd.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #include <errno.h> #include <sys/types.h> #include <sys/ipc.h> #include <sys/msg.h> #define BUFF_SIZE 1024 struct mq_msg_st { long msg_type; char text[BUFF_SIZE]; }; int main(int argc, char** argv) { int msgid = -1; struct mq_msg_st data; long msgtype = 0; int iret = 0; char buffer[BUFF_SIZE]; //建立消息队列 msgid = msgget((key_t)1234, 0666); if(msgid == -1) { printf("msgget failed with error: %s\n", strerror(errno)); return -1; } printf("msgget succ, msgid = %d\n", msgid); // 获取消息队列状态 struct msqid_ds ds; iret = msgctl(msgid, IPC_STAT, (struct msqid_ds *)&ds); if(iret == -1) { printf("msgctl IPC_STAT failed\n"); return -2; } while(1) { //输入数据 printf("Enter some text: "); fgets(buffer, BUFF_SIZE, stdin); data.msg_type = 1; strcpy(data.text, buffer); //向队列发送数据 iret = msgsnd(msgid, (void*)&data, strlen(data.text)+1, IPC_NOWAIT); if(iret == -1) { if (errno == EAGAIN) { continue; } else { printf("msgsnd failed, error = %s\n", strerror(errno)); return -1; } } //输入end结束输入 if(strncmp(buffer, "end", 3) == 0) { break; } } return 0; }
[ "kfzhang82@gmail.com" ]
kfzhang82@gmail.com
29b38532a3a1827f20a92349d5c7cd5fb0b824ce
c3ffa07567d3d29a7439e33a6885a5544e896644
/codechef/JAN15/Sereja and LCM.cpp
3cc7ba86f8047784c1bfbffe20551fbd1173fa5d
[]
no_license
a00012025/Online_Judge_Code
398c90c046f402218bd14867a06ae301c0c67687
7084865a7050fc09ffb0e734f77996172a93d3ce
refs/heads/master
2018-01-08T11:33:26.352408
2015-10-10T23:20:35
2015-10-10T23:20:35
44,031,127
0
0
null
null
null
null
UTF-8
C++
false
false
1,935
cpp
#include<bits/stdc++.h> #define LL long long #define MOD 1000000007 using namespace std; int pcnt=0,prime[2000] ; bool vis[2000] ; void make_prime() { for(int i=2;i*i<2000;i++) if(!vis[i]) for(int j=i*i;j<2000;j+=i) vis[j]=1 ; for(int i=2;i<2000;i++) if(!vis[i]) prime[++pcnt]=i ; } LL get_pow(LL x,int n) { if(n==0) return 1LL ; if(n==1) return x ; LL y=get_pow(x,n/2) ; if(n%2) return (((y*y)%MOD)*x)%MOD ; else return ((y*y)%MOD) ; } int n,m ; LL power[2000] ; void pre_cal() { power[0]=0 ; for(int i=1;i<=m;i++) power[i]=get_pow((LL)i,n) ; } int event[200],num[50] ; int Union(int S) { int ret=0 ; for(int S0=S;S0;S0=((S0-1)&S)) { int cnt=0 ; for(int j=0;(1<<j)<=S0;j++) if(S0&(1<<j)) cnt++ ; if(cnt%2) ret+=event[S0] ; else ret-=event[S0] ; } return ret ; } LL cal(int d) { int cnt=0 ; for(int i=1;i<=pcnt && d!=1;i++) if(d%prime[i]==0) { num[cnt]=1 ; while(d%prime[i]==0) d/=prime[i] , num[cnt]*=prime[i] ; cnt++ ; } memset(event,0,sizeof(event)) ; for(int i=1;i<=m;i++) for(int j=1;j<(1<<cnt);j++) { bool ok=1 ; for(int k=0;k<cnt;k++) if((j&(1<<k)) && (i%num[k])) {ok=0 ; break ;} if(ok) event[j]++ ; } LL ret=power[m] ; for(int i=1;i<(1<<cnt);i++) { int cnt2=0 ; for(int j=0;j<cnt;j++) if(i&(1<<j)) cnt2++ ; if(cnt2%2) ret-=power[m-Union(i)] ; else ret+=power[m-Union(i)] ; ret%=MOD ; if(ret<0) ret+=MOD ; } return ret ; } main() { make_prime() ; int T ; scanf("%d",&T) ; while(T--) { int L,R ; scanf("%d%d%d%d",&n,&m,&L,&R) ; pre_cal() ; LL ans=0LL ; for(int i=L;i<=R;i++) ans=(ans+cal(i))%MOD ; printf("%lld\n",ans) ; } }
[ "a00012025@gmail.com" ]
a00012025@gmail.com
54cd4436644af7ef50d1e320fe5b8227ff8e26ad
5f45d136b340c467cdf74d45494ff25fb271a7cd
/equipment.cpp
e7bc700d1ac736eb97a7596596e2efb656e80dca
[]
no_license
notsodistantworlds/spaceblitz
db72afe30167bb48770a139fc788704d09a42463
0921613229cad69d3625f5e92666550decfe2122
refs/heads/master
2021-10-19T00:20:48.104707
2019-02-15T21:12:45
2019-02-15T21:12:45
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,087
cpp
#include <gameconsole.h> #include <projectiles.h> #include <vehicles.h> #include <debuglogger.h> #include <equipment.h> #include <artassetmanager.h> #include <gameassetmanager.h> #include <math.h> #include <stdio.h> //class Vehicle; Gun* EquipmentSpawner::spawnBasicGun(){ Gun* g = new Gun(500, 1.5, 20,0, 1); GunRenderer* grend = new GunRenderer(g, 50, 50); GameObject* gun = g; gun -> assignComponents(0, grend); return g; } Gun* EquipmentSpawner::spawnBasicEnemyGun(){ Gun* g = new Gun(500, -1.2, 10, 0, -2); GunRenderer* grend = new GunRenderer(g, 50, 50); GameObject* gun = g; gun -> assignComponents(0, grend); return g; } Equipment* EquipmentSpawner::spawnEquipment(GameAsset* asset){ std::string t = asset->getData(0); switch(t[0]){ case 'g':{ int art = std::stoi(asset->getData(1)); int col = std::stoi(asset->getData(2)); float speed = std::stof(asset->getData(3)); int reload = std::stoi(asset->getData(4)); int spawnX = std::stoi(asset->getData(5)); int spawnY = std::stoi(asset->getData(6)); int proj = std::stoi(asset->getData(7)); Gun* g = new Gun(proj, speed, reload, spawnX, spawnY); GunRenderer* grend = new GunRenderer(g, art, col); GameObject* gun = g; gun -> assignComponents(0, grend); return g; //gun } default: DebugLogger::outputLine("Unknown type"); return 0; } } Equipment::Equipment(){ } void Equipment::updatePos(){ int hx=0; int hy=0; GameObject* att = attachedTo.getPointer(); if(att!=0) att->getGridPos(hx, hy); this->setPosition(xoff + hx, yoff+hy); } void Equipment::tick(){ } void Equipment::fire(){ } void Equipment::attachEq(int x, int y, Vehicle* h){ this -> attachedTo = h->createPointer(); this -> xoff = x; this -> yoff = y; } Gun::Gun(int projAsset, float speed, int reloadTime, int spawnOffsetX, int spawnOffsetY){ this -> projAsset = projAsset; this -> speed = speed; this -> reloadTime = reloadTime; this -> spawnOffsetX = spawnOffsetX; this -> spawnOffsetY = spawnOffsetY; } void Gun::tick(){ if(attachedTo.getPointer()==0&&toBeDestroyed==-1) toBeDestroyed = 5; reload++; } void Gun::fire(){ if(reload<reloadTime)return; reload = 0; int xp = 0; int yp = 0; this -> getGridPos(xp, yp); xp += spawnOffsetX; yp += spawnOffsetY; float vx = 0; float vy = 0; GameObject* att = attachedTo.getPointer(); if(att!=0) att -> getRigidBody() -> getVelocity(vx, vy); GameObject * fired = GameAssetManager::spawn(projAsset); if(fired!=0){ fired->setPosition(xp, yp); fired->setLayer(1); if(fired->getRigidBody()!=0){ fired->getRigidBody()->setVelocity(vx, vy+speed); } } } GunRenderer::GunRenderer(Gun* gun, int art, int col){ this -> g = gun->createPointer(); this -> art = art; this -> col = col; } void GunRenderer::draw(){ int xpos = 0;//(*vehicle).getGridPos()[0]; int ypos = 0;//(*vehicle).getGridPos()[1]; Gun* gun = dynamic_cast<Gun*>(g.getPointer()); if(gun!=0){ gun->getGridPos(xpos, ypos); }else return; ArtAssetManager::draw(art, col, xpos, ypos, 1); } GunRenderer::~GunRenderer(){ }
[ "strutinsky5386@gmail.com" ]
strutinsky5386@gmail.com
4cf97e13d206f1e7d27f3b4c176eb5934d8f8438
290af6001c0133c9f36fb46e6948de72cd642037
/Project Solutions/Program3_Solution/BaseballPlayer.cpp
b2eaa54cfccf2dc41fd8df8238b56bf2d53716c8
[]
no_license
nam0011/DataStructuresProjects
e11dfb3f5d6c04bab9c88d1e4cabb1f79b6a4330
f779aec5dba1a3d3cf3a2df7665ef41084934957
refs/heads/main
2023-08-15T02:19:39.957794
2021-09-19T17:12:36
2021-09-19T17:12:36
408,192,446
0
0
null
null
null
null
UTF-8
C++
false
false
7,177
cpp
/* File: BaseballPlayer.cpp Program 3: Beth Allen Implementation of the class BaseballPlayer - VERSION 2. See the .h file for more descriptions of the member attributes and functions. All of the methods are contained in this file. Program 3: Added compareByName to return an ordering (-1, 0, 1) of two players based on their names */ #include "BaseballPlayer.h" #include <string.h> //-----------------------------------------------------------------------------------------------// // Default Constructor // Sets numberic values to zeros, and other values to either empty strings or default values //-----------------------------------------------------------------------------------------------// BaseballPlayer::BaseballPlayer() { mFirstName = "unknown"; mLastName = "unknown"; for (int i = 0; i <= APPEARANCES; i++) mHitting[i] = 0; } //-----------------------------------------------------------------------------------------------// // read(input) // VERSION 2: reads in plate apperances before the hits data, and the walks and HBP // // This method reads the baseball player's data from a single line on an input stream. // Some special restrictions - the player's first name and last name can each only consist of // a single word (no embedded spaces), other wise the input will be read in incorrectly. // There must also be all 5 statistics data values on the line. // The order of input is firstname lastname appearances atbats singles doubles triples homeruns walks hbp // // Parameters: // input : a variable representing the input stream to read data from //-----------------------------------------------------------------------------------------------// void BaseballPlayer::read(istream &input) { input >> mFirstName >> mLastName; input >> mHitting[APPEARANCES]; // i am storing the first value at the end of my data array for (int i = ATBATS; i <= HBP; i++) input >> mHitting[i]; // read in each stat from input stream } //-----------------------------------------------------------------------------------------------// // computeStats // This function currently computes the player's batting average based on the hitting data. // Later revisions will compute additional player statistics. //-----------------------------------------------------------------------------------------------// void BaseballPlayer::computeStats() { mBattingAverage = 0.0; mSluggingPercentage = 0.0; for (int i = SINGLES; i <= HOMERS; i++) {// step through the hitting values and sum them mBattingAverage = mBattingAverage + mHitting[i]; mSluggingPercentage = mSluggingPercentage + (i * mHitting[i]); } if (mHitting[ATBATS] > 0) { mBattingAverage = mBattingAverage / mHitting[ATBATS]; mSluggingPercentage = mSluggingPercentage / mHitting[ATBATS]; } else { mBattingAverage = 0.0; // if there was a 0 in the at bats, we can't divide by it mSluggingPercentage = 0.0; } // compute on base percentage too mOnBasePercentage = 0.0; for (int i = SINGLES; i <= HBP; i++) { mOnBasePercentage = mOnBasePercentage + mHitting[i]; } if (mHitting[APPEARANCES] > 0) mOnBasePercentage = mOnBasePercentage / mHitting[APPEARANCES]; else mOnBasePercentage = 0.0; mOPS = mOnBasePercentage + mSluggingPercentage; } //-----------------------------------------------------------------------------------------------// // getFullName() // This get method is used to get the player's full name built as a single string from the // names stored in the class. //-----------------------------------------------------------------------------------------------// string BaseballPlayer::getFullName() { return mFirstName + " " + mLastName; } //-----------------------------------------------------------------------------------------------// // getFirstName() // This get method is used to get the player's first name //-----------------------------------------------------------------------------------------------// string BaseballPlayer::getFirstName() { return mFirstName; } //-----------------------------------------------------------------------------------------------// // getLastName() // This get method is used to get the player's last name //-----------------------------------------------------------------------------------------------// string BaseballPlayer::getLastName() { return mLastName; } //-----------------------------------------------------------------------------------------------// // getBattingAverage() // Used to retrieve the batting average for this player after it has been computed. //-----------------------------------------------------------------------------------------------// double BaseballPlayer::getBattingAverage() { return mBattingAverage; } //-----------------------------------------------------------------------------------------------// // getSluggingPercentage() // Used to retrieve the slugging average for this player after it has been computed. //-----------------------------------------------------------------------------------------------// double BaseballPlayer::getSluggingPercentage() { return mSluggingPercentage; } //-----------------------------------------------------------------------------------------------// // getOnBasePercentage() // Used to retrieve the on base average for this player after it has been computed. //-----------------------------------------------------------------------------------------------// double BaseballPlayer::getOnBasePercentage() { return mOnBasePercentage; } //-----------------------------------------------------------------------------------------------// // getOPS() // Used to retrieve the OPS for this player after it has been computed. //-----------------------------------------------------------------------------------------------// double BaseballPlayer::getOPS() { return mOPS; } //-----------------------------------------------------------------------------------------------// // compareByName // uses the full name to do a comparison for sort order // returns -1 0 1 to reflect < = > //-----------------------------------------------------------------------------------------------// /*int BaseballPlayer::compareByName(BaseballPlayer& otherPlayer) { // _stricmp is a utility to do string comparisons, case insensitive // .c_str() is a utility to pull out the character array of a string variable to use with // the _stricmp utility int compareStatus = stricmp(mLastName.c_str(), otherPlayer.mLastName.c_str()); // compare last names if (compareStatus == 0) // the last names are the same so do a comparison on the first names to update compareStatus = stricmp(mFirstName.c_str(), otherPlayer.mFirstName.c_str()); // so compare the first names return compareStatus; } */ //-----------------------------------------------------------------------------------------------// // setName // sets the full name (first and last) for a player object //-----------------------------------------------------------------------------------------------// void BaseballPlayer::setName(string firstName, string lastName) { mFirstName = firstName; mLastName = lastName; }
[ "65084807+nam0011@users.noreply.github.com" ]
65084807+nam0011@users.noreply.github.com
1ac6a0f9b16faa87d7b43f4e28c15e57169dade0
3c5c1e3836edf3e9627a64600785503d1814df51
/build/Android/Debug/app/src/main/include/Fuse.Android.StatusBarConfig.h
58f5a7167e33db7ebe53638019cd3383e18b085f
[]
no_license
fypwyt/wytcarpool
70a0c9ca12d0f2981187f2ea21a8a02ee4cbcbd4
4fbdeedf261ee8ecd563260816991741ec701432
refs/heads/master
2021-09-08T10:32:17.612628
2018-03-09T05:24:54
2018-03-09T05:24:54
124,490,692
0
0
null
null
null
null
UTF-8
C++
false
false
1,171
h
// This file was generated based on C:/Users/Brian/AppData/Local/Fusetools/Packages/Fuse.Android/1.6.0/StatusBarConfig.uno. // WARNING: Changes might be lost if you edit this file directly. #pragma once #include <Fuse.Behavior.h> #include <Fuse.Binding.h> #include <Fuse.INotifyUnrooted.h> #include <Fuse.IProperties.h> #include <Fuse.Scripting.IScriptObject.h> #include <Uno.Collections.ICollection-1.h> #include <Uno.Collections.IEnumerable-1.h> #include <Uno.Collections.IList-1.h> namespace g{namespace Fuse{namespace Android{struct StatusBarConfig;}}} namespace g{namespace Uno{struct Float4;}} namespace g{ namespace Fuse{ namespace Android{ // public sealed class StatusBarConfig :82 // { ::g::Fuse::Node_type* StatusBarConfig_typeof(); void StatusBarConfig__SetStatusBarColor_fn(::g::Uno::Float4* color, bool* __retval); void StatusBarConfig__UpdateStatusBar_fn(); struct StatusBarConfig : ::g::Fuse::Behavior { static bool _isVisible_; static bool& _isVisible() { return StatusBarConfig_typeof()->Init(), _isVisible_; } static bool SetStatusBarColor(::g::Uno::Float4 color); static void UpdateStatusBar(); }; // } }}} // ::g::Fuse::Android
[ "s1141120@studentdmn.ouhk.edu.hk" ]
s1141120@studentdmn.ouhk.edu.hk
5c76e17e8cc93fd87766163c2dfe806d001161b0
4a3e5419e89dfbd9788a4539740b8ea7321ee7ef
/algo/dijkstra.cpp
92c55da595477c4f6a97c82665ebc00b6bf9236b
[]
no_license
tars0x9752/atcoder
d3cbfefeb5164edab72d87f8feb16e1160c231a2
0e54c9a34055e47ae6bb19d4493306e974a50eee
refs/heads/master
2022-11-19T15:36:17.711849
2020-07-19T12:56:31
2020-07-19T12:56:31
182,626,178
0
0
null
null
null
null
UTF-8
C++
false
false
1,526
cpp
#include <bits/stdc++.h> using namespace std; typedef long long ll; typedef pair<int, int> P; // fisrtは最短距離、 secondは頂点の番号 constexpr int INF = 1001001001; struct Edge { int to, cost; }; int V, E; constexpr int MAX_V = 100000; vector<Edge> G[MAX_V]; // G[i] = 頂点iに隣接するEdgeのvectorからなる隣接リスト // G[i][j].to でi から to への辺、 G[i][j].cost でその辺のコスト int d[MAX_V]; void dijkstra(int s) { priority_queue<P, vector<P>, greater<P>> que; fill(d, d + V, INF); // 距離を全部 INF で初期化 d[s] = 0; que.push(P(0, s)); // 始点への最短距離0, 始点の番号 while (!que.empty()) { P p = que.top(); que.pop(); int v = p.second; // 頂点の番号 // 頂点vの最短距離よりqueから取り出したものの最短距離のほうがでかかったらスキップ if (d[v] < p.first) continue; for (int i = 0; i < G[v].size(); i++) { Edge e = G[v][i]; if (d[e.to] > d[v] + e.cost) { d[e.to] = d[v] + e.cost; que.push(P(d[e.to], e.to)); } } } } int main() { cin.tie(nullptr); ios::sync_with_stdio(false); cin >> V >> E; int r; //始点 cin >> r; for (int i = 0; i < E; i++) { int s, t, cost; cin >> s >> t >> cost; Edge e = {t, cost}; G[s].push_back(e); } dijkstra(r); for (int i = 0; i < V; i++) { if (d[i] == INF) { cout << "INF" << endl; } else { cout << d[i] << endl; } } return 0; }
[ "46079709+huffhuffman@users.noreply.github.com" ]
46079709+huffhuffman@users.noreply.github.com
9e92e59345bc31f817fb2de4949b5074c2a385c6
56eac16758991b564e6c0261ff61f0201488c665
/Algorithm/Example_1197.cpp
03d46941260128beb07844755f73de97ae7acd2a
[]
no_license
jihyun-s/Algorithm
5f1587660d0fa6641101f23777332d1ff1675a25
f7e98adef7e0e30bc4e008f8b7847061c614ad70
refs/heads/master
2021-01-21T14:27:54.446649
2017-08-09T02:07:38
2017-08-09T02:07:38
95,281,689
0
0
null
null
null
null
UHC
C++
false
false
1,999
cpp
/* [작성일] 2017.01.28 [문제] 최소 스패닝 트리 https://www.acmicpc.net/problem/1197 그래프가 주어졌을 때, 그 그래프의 최소 스패닝 트리를 구하는 프로그램을 작성하시오. 최소 스패닝 트리는, 주어진 그래프의 모든 정점들을 연결하는 부분 그래프 중에서 그 가중치의 합이 최소인 트리를 말한다. [입력] 첫째 줄에 정점의 개수 V(1≤V≤10,000)와 간선의 개수 E(1≤E≤100,000)가 주어진다. 다음 E개의 줄에는 각 간선에 대한 정보를 나타내는 세 정수 A, B, C가 주어진다. 이는 A번 정점과 B번 정점이 가중치 C인 간선으로 연결되어 있다는 의미이다. C는 음수일 수도 있으며, 절대값이 1,000,000을 넘지 않는다. [출력] 첫째 줄에 최소 스패닝 트리의 가중치를 출력한다. */ //#define PROBLEM_1197 #ifdef PROBLEM_1197 #include<iostream> #include<queue> #include<vector> #include<cstring> using namespace std; priority_queue<pair<int, pair<int, int>>> q; int nSum = 0; int parent[10001]; void unionVertex(int a, int b) { if (a == b) return; parent[a] = b; } int find(int a) { if (parent[a] == -1) return a; return parent[a] = find(parent[a]); } void kruskal(int nEdgeMaxCount) { int nDistance; int nCount = 0; memset(parent, -1, sizeof(parent)); pair<int, pair<int, int>> tmp; // 간선 갯수가 정점-1이 될 때까지 while (nCount < nEdgeMaxCount) { tmp = q.top(); q.pop(); nDistance = -tmp.first; int v1 = find(tmp.second.first); int v2 = find(tmp.second.second); if (v1 != v2) { unionVertex(v1, v2); nSum += nDistance; nCount++; } } } int main() { int nVertex, nEdge; scanf("%d", &nVertex); scanf("%d", &nEdge); int nTotalCount = nVertex - 1; int v1, v2, d; while (nEdge-- > 0) { scanf("%d", &v1); scanf("%d", &v2); scanf("%d", &d); q.push(make_pair(-d, make_pair(v1, v2))); } kruskal(nTotalCount); printf("%d", nSum); return 0; } #endif
[ "sjh8911@naver.com" ]
sjh8911@naver.com
a944797296adaac7c46dc63278807075c72e9c53
2d361696ad060b82065ee116685aa4bb93d0b701
/src/util/util_misc.cpp
87d0d51ebaf267e70c3f0a144ac877e3b811be07
[ "LicenseRef-scancode-public-domain" ]
permissive
AaronNGray/GenomeWorkbench
5151714257ce73bdfb57aec47ea3c02f941602e0
7156b83ec589e0de8f7b0a85699d2a657f3e1c47
refs/heads/master
2022-11-16T12:45:40.377330
2020-07-10T00:54:19
2020-07-10T00:54:19
278,501,064
1
1
null
null
null
null
UTF-8
C++
false
false
6,505
cpp
/* $Id: util_misc.cpp 530021 2017-03-09 19:06:46Z ucko $ * =========================================================================== * * PUBLIC DOMAIN NOTICE * National Center for Biotechnology Information * * This software/database is a "United States Government Work" under the * terms of the United States Copyright Act. It was written as part of * the author's official duties as a United States Government employee and * thus cannot be copyrighted. This software/database is freely available * to the public for use. The National Library of Medicine and the U.S. * Government have not placed any restriction on its use or reproduction. * * Although all reasonable efforts have been taken to ensure the accuracy * and reliability of the software and data, the NLM and the U.S. * Government do not and cannot warrant the performance or results that * may be obtained by using this software or data. The NLM and the U.S. * Government disclaim all warranties, express or implied, including * warranties of performance, merchantability or fitness for any particular * purpose. * * Please cite the author in any work or product based on this material. * * =========================================================================== * * Author: Sergey Satskiy, * Anton Lavrentiev (providing line by line advices of how it must be * implemented) * */ #include <ncbi_pch.hpp> #include <util/util_misc.hpp> #include <corelib/ncbi_param.hpp> #include <corelib/ncbifile.hpp> #if defined(NCBI_OS_UNIX) # include <unistd.h> #if defined(HAVE_READPASSPHRASE) # include <readpassphrase.h> #endif #elif defined(NCBI_OS_MSWIN) # include <conio.h> #else # error "Unsuported platform" #endif BEGIN_NCBI_SCOPE const char* CGetPasswordFromConsoleException::GetErrCodeString(void) const { switch (GetErrCode()) { case eGetPassError: return "eGetPassError"; case eKeyboardInterrupt: return "eKeyboardInterrupt"; default: return CException::GetErrCodeString(); } } string g_GetPasswordFromConsole(const string& prompt) { string password; CMutex lock; CMutexGuard guard(lock); #if defined(NCBI_OS_UNIX) // UNIX implementation #if defined(HAVE_READPASSPHRASE) char password_buffer[1024]; char* raw_password = readpassphrase(prompt.c_str(), password_buffer, sizeof(password_buffer), RPP_ECHO_OFF | RPP_REQUIRE_TTY); #elif defined(HAVE_GETPASSPHRASE) char* raw_password = getpassphrase(prompt.c_str()); #elif defined(HAVE_GETPASS) char* raw_password = getpass(prompt.c_str()); #else # error "Unsupported Unix platform; the getpass, getpassphrase, and readpassphrase functions are all absent" #endif if (!raw_password) NCBI_THROW (CGetPasswordFromConsoleException, eGetPassError, "g_GetPasswordFromConsole(): error getting password"); password = string(raw_password); #elif defined(NCBI_OS_MSWIN) // Windows implementation for (size_t index = 0; index < prompt.size(); ++index) { _putch(prompt[index]); } for (;;) { char ch; ch = _getch(); if (ch == '\r' || ch == '\n') break; if (ch == '\003') NCBI_THROW(CGetPasswordFromConsoleException, eKeyboardInterrupt, "g_GetPasswordFromConsole(): keyboard interrupt"); if (ch == '\b') { if ( !password.empty() ) { password.resize(password.size() - 1); } } else password.append(1, ch); } _putch('\r'); _putch('\n'); #endif return password; } NCBI_PARAM_DECL (string, NCBI, DataPath); NCBI_PARAM_DEF_EX(string, NCBI, DataPath, "", 0, NCBI_DATA_PATH); typedef NCBI_PARAM_TYPE(NCBI, DataPath) TNCBIDataPath; NCBI_PARAM_DECL(string, NCBI, Data); NCBI_PARAM_DEF (string, NCBI, Data, ""); typedef NCBI_PARAM_TYPE(NCBI, Data) TNCBIDataDir; typedef vector<string> TIgnoreDataFiles; static CSafeStatic<TIgnoreDataFiles> s_IgnoredDataFiles; string g_FindDataFile(const CTempString& name, CDirEntry::EType type) { #ifdef NCBI_OS_MSWIN static const char* kDelim = ";"; #else static const char* kDelim = ":"; #endif if ( !s_IgnoredDataFiles->empty() && CDirEntry::MatchesMask(name, *s_IgnoredDataFiles) ) { return kEmptyStr; } list<string> dirs; if (CDirEntry::IsAbsolutePath(name)) { dirs.push_back(kEmptyStr); } else { TNCBIDataPath path; TNCBIDataDir dir; if ( !path.Get().empty() ) { NStr::Split(path.Get(), kDelim, dirs, NStr::fSplit_MergeDelimiters | NStr::fSplit_Truncate); } if ( !dir.Get().empty() ) { dirs.push_back(dir.Get()); } } CDirEntry candidate; EFollowLinks fl = (type == CDirEntry::eLink) ? eIgnoreLinks : eFollowLinks; ITERATE (list<string>, dir, dirs) { candidate.Reset(CDirEntry::MakePath(*dir, name)); if (candidate.Exists() && candidate.GetType(fl) == type) { return candidate.GetPath(); } } return kEmptyStr; // not found } void g_IgnoreDataFile(const string& pattern, bool do_ignore) { vector<string>& idf = *s_IgnoredDataFiles; if (do_ignore) { idf.push_back(pattern); } else { idf.erase(remove(idf.begin(), idf.end(), pattern), idf.end()); } } bool g_IsDataFileOld(const CTempString& path, const CTempString& id_line) { // $Id: FILENAME REVISION DATE TIME ... SIZE_TYPE pos = id_line.find("$Id: "); if (pos == NPOS) { return false; } pos = id_line.find(' ', pos + 5); // skip filename if (pos == NPOS) { return false; } pos = id_line.find(' ', pos + 1); // skip revision if (pos == NPOS) { return false; } SIZE_TYPE end = id_line.find(' ', ++pos); if (end == NPOS) { return false; } end = id_line.find(' ', end + 1); // got date, now want time too if (end == NPOS) { return false; } CTempString builtin_timestamp_str = id_line.substr(pos, end - pos); CTime builtin_timestamp(builtin_timestamp_str, "Y-M-D h:m:sZ"); CTime file_timestamp; CFile(path).GetTime(&file_timestamp); return file_timestamp < builtin_timestamp; } END_NCBI_SCOPE
[ "aaronngray@gmail.com" ]
aaronngray@gmail.com
f6c560a466af2330cd45a12df4864eef71059b80
04b1803adb6653ecb7cb827c4f4aa616afacf629
/third_party/blink/renderer/bindings/core/v8/rejected_promises.cc
cb6ba97fcb12e8b0c05a26c3724e808d84b523d9
[ "LGPL-2.0-or-later", "LicenseRef-scancode-warranty-disclaimer", "LGPL-2.1-only", "GPL-1.0-or-later", "GPL-2.0-only", "LGPL-2.0-only", "BSD-2-Clause", "LicenseRef-scancode-other-copyleft", "MIT", "Apache-2.0", "BSD-3-Clause" ]
permissive
Samsung/Castanets
240d9338e097b75b3f669604315b06f7cf129d64
4896f732fc747dfdcfcbac3d442f2d2d42df264a
refs/heads/castanets_76_dev
2023-08-31T09:01:04.744346
2021-07-30T04:56:25
2021-08-11T05:45:21
125,484,161
58
49
BSD-3-Clause
2022-10-16T19:31:26
2018-03-16T08:07:37
null
UTF-8
C++
false
false
10,027
cc
// Copyright 2015 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 "third_party/blink/renderer/bindings/core/v8/rejected_promises.h" #include <memory> #include "base/memory/ptr_util.h" #include "third_party/blink/public/platform/platform.h" #include "third_party/blink/renderer/bindings/core/v8/script_value.h" #include "third_party/blink/renderer/bindings/core/v8/v8_binding_for_core.h" #include "third_party/blink/renderer/core/dom/events/event_target.h" #include "third_party/blink/renderer/core/events/promise_rejection_event.h" #include "third_party/blink/renderer/core/execution_context/execution_context.h" #include "third_party/blink/renderer/core/inspector/thread_debugger.h" #include "third_party/blink/renderer/platform/bindings/scoped_persistent.h" #include "third_party/blink/renderer/platform/bindings/script_state.h" #include "third_party/blink/renderer/platform/bindings/v8_per_isolate_data.h" #include "third_party/blink/renderer/platform/scheduler/public/thread.h" #include "third_party/blink/renderer/platform/scheduler/public/thread_scheduler.h" #include "third_party/blink/renderer/platform/wtf/functional.h" #include "third_party/blink/renderer/platform/wtf/hash_map.h" namespace blink { static const unsigned kMaxReportedHandlersPendingResolution = 1000; class RejectedPromises::Message final { public: Message(ScriptState* script_state, v8::Local<v8::Promise> promise, v8::Local<v8::Value> exception, const String& error_message, std::unique_ptr<SourceLocation> location, SanitizeScriptErrors sanitize_script_errors) : script_state_(script_state), promise_(script_state->GetIsolate(), promise), exception_(script_state->GetIsolate(), exception), error_message_(error_message), location_(std::move(location)), promise_rejection_id_(0), collected_(false), should_log_to_console_(true), sanitize_script_errors_(sanitize_script_errors) {} bool IsCollected() { return collected_ || !script_state_->ContextIsValid(); } bool HasPromise(v8::Local<v8::Value> promise) { ScriptState::Scope scope(script_state_); return promise == promise_.NewLocal(script_state_->GetIsolate()); } void Report() { if (!script_state_->ContextIsValid()) return; // If execution termination has been triggered, quietly bail out. if (script_state_->GetIsolate()->IsExecutionTerminating()) return; ExecutionContext* execution_context = ExecutionContext::From(script_state_); if (!execution_context) return; ScriptState::Scope scope(script_state_); v8::Local<v8::Value> value = promise_.NewLocal(script_state_->GetIsolate()); v8::Local<v8::Value> reason = exception_.NewLocal(script_state_->GetIsolate()); // Either collected or https://crbug.com/450330 if (value.IsEmpty() || !value->IsPromise()) return; DCHECK(!HasHandler()); EventTarget* target = execution_context->ErrorEventTarget(); if (target && sanitize_script_errors_ == SanitizeScriptErrors::kDoNotSanitize) { PromiseRejectionEventInit* init = PromiseRejectionEventInit::Create(); init->setPromise(ScriptPromise(script_state_, value)); init->setReason(ScriptValue(script_state_, reason)); init->setCancelable(true); PromiseRejectionEvent* event = PromiseRejectionEvent::Create( script_state_, event_type_names::kUnhandledrejection, init); // Log to console if event was not canceled. should_log_to_console_ = target->DispatchEvent(*event) == DispatchEventResult::kNotCanceled; } if (should_log_to_console_) { ThreadDebugger* debugger = ThreadDebugger::From(script_state_->GetIsolate()); if (debugger) { promise_rejection_id_ = debugger->PromiseRejected( script_state_->GetContext(), error_message_, reason, std::move(location_)); } } location_.reset(); } void Revoke() { ExecutionContext* execution_context = ExecutionContext::From(script_state_); if (!execution_context) return; ScriptState::Scope scope(script_state_); v8::Local<v8::Value> value = promise_.NewLocal(script_state_->GetIsolate()); v8::Local<v8::Value> reason = exception_.NewLocal(script_state_->GetIsolate()); // Either collected or https://crbug.com/450330 if (value.IsEmpty() || !value->IsPromise()) return; EventTarget* target = execution_context->ErrorEventTarget(); if (target && sanitize_script_errors_ == SanitizeScriptErrors::kDoNotSanitize) { PromiseRejectionEventInit* init = PromiseRejectionEventInit::Create(); init->setPromise(ScriptPromise(script_state_, value)); init->setReason(ScriptValue(script_state_, reason)); PromiseRejectionEvent* event = PromiseRejectionEvent::Create( script_state_, event_type_names::kRejectionhandled, init); target->DispatchEvent(*event); } if (should_log_to_console_ && promise_rejection_id_) { ThreadDebugger* debugger = ThreadDebugger::From(script_state_->GetIsolate()); if (debugger) { debugger->PromiseRejectionRevoked(script_state_->GetContext(), promise_rejection_id_); } } } void MakePromiseWeak() { DCHECK(!promise_.IsEmpty()); DCHECK(!promise_.IsWeak()); promise_.SetWeak(this, &Message::DidCollectPromise); exception_.SetWeak(this, &Message::DidCollectException); } void MakePromiseStrong() { DCHECK(!promise_.IsEmpty()); DCHECK(promise_.IsWeak()); promise_.ClearWeak(); exception_.ClearWeak(); } bool HasHandler() { DCHECK(!IsCollected()); ScriptState::Scope scope(script_state_); v8::Local<v8::Value> value = promise_.NewLocal(script_state_->GetIsolate()); return v8::Local<v8::Promise>::Cast(value)->HasHandler(); } ExecutionContext* GetContext() { return ExecutionContext::From(script_state_); } private: static void DidCollectPromise(const v8::WeakCallbackInfo<Message>& data) { data.GetParameter()->collected_ = true; data.GetParameter()->promise_.Clear(); } static void DidCollectException(const v8::WeakCallbackInfo<Message>& data) { data.GetParameter()->exception_.Clear(); } Persistent<ScriptState> script_state_; ScopedPersistent<v8::Promise> promise_; ScopedPersistent<v8::Value> exception_; String error_message_; std::unique_ptr<SourceLocation> location_; unsigned promise_rejection_id_; bool collected_; bool should_log_to_console_; SanitizeScriptErrors sanitize_script_errors_; }; RejectedPromises::RejectedPromises() = default; RejectedPromises::~RejectedPromises() = default; void RejectedPromises::RejectedWithNoHandler( ScriptState* script_state, v8::PromiseRejectMessage data, const String& error_message, std::unique_ptr<SourceLocation> location, SanitizeScriptErrors sanitize_script_errors) { queue_.push_back(std::make_unique<Message>( script_state, data.GetPromise(), data.GetValue(), error_message, std::move(location), sanitize_script_errors)); } void RejectedPromises::HandlerAdded(v8::PromiseRejectMessage data) { // First look it up in the pending messages and fast return, it'll be covered // by processQueue(). for (auto* it = queue_.begin(); it != queue_.end(); ++it) { if (!(*it)->IsCollected() && (*it)->HasPromise(data.GetPromise())) { queue_.erase(it); return; } } // Then look it up in the reported errors. for (wtf_size_t i = 0; i < reported_as_errors_.size(); ++i) { std::unique_ptr<Message>& message = reported_as_errors_.at(i); if (!message->IsCollected() && message->HasPromise(data.GetPromise())) { message->MakePromiseStrong(); message->GetContext() ->GetTaskRunner(TaskType::kDOMManipulation) ->PostTask(FROM_HERE, WTF::Bind(&RejectedPromises::RevokeNow, scoped_refptr<RejectedPromises>(this), WTF::Passed(std::move(message)))); reported_as_errors_.EraseAt(i); return; } } } void RejectedPromises::Dispose() { if (queue_.IsEmpty()) return; ProcessQueueNow(std::move(queue_)); queue_.clear(); } void RejectedPromises::ProcessQueue() { if (queue_.IsEmpty()) return; HeapHashMap<Member<ExecutionContext>, MessageQueue> queues; for (auto& message : queue_) { auto result = queues.insert(message->GetContext(), MessageQueue()); result.stored_value->value.push_back(std::move(message)); } queue_.clear(); for (auto& kv : queues) { kv.key->GetTaskRunner(blink::TaskType::kDOMManipulation) ->PostTask(FROM_HERE, WTF::Bind(&RejectedPromises::ProcessQueueNow, scoped_refptr<RejectedPromises>(this), WTF::Passed(std::move(kv.value)))); } } void RejectedPromises::ProcessQueueNow(MessageQueue queue) { // Remove collected handlers. auto* new_end = std::remove_if( reported_as_errors_.begin(), reported_as_errors_.end(), [](const auto& message) { return message->IsCollected(); }); reported_as_errors_.Shrink( static_cast<wtf_size_t>(new_end - reported_as_errors_.begin())); for (auto& message : queue) { if (message->IsCollected()) continue; if (!message->HasHandler()) { message->Report(); message->MakePromiseWeak(); reported_as_errors_.push_back(std::move(message)); if (reported_as_errors_.size() > kMaxReportedHandlersPendingResolution) { reported_as_errors_.EraseAt(0, kMaxReportedHandlersPendingResolution / 10); } } } } void RejectedPromises::RevokeNow(std::unique_ptr<Message> message) { message->Revoke(); } } // namespace blink
[ "sunny.nam@samsung.com" ]
sunny.nam@samsung.com
ed2ea4f8f7af5581389ed2620bc34cd8cfbbe47f
3af68b32aaa9b7522a1718b0fc50ef0cf4a704a9
/cpp/A/D/E/B/B/AADEBB.cpp
ba89274a225f6559d9f755bb396ee8a33830a6cc
[]
no_license
devsisters/2021-NDC-ICECREAM
7cd09fa2794cbab1ab4702362a37f6ab62638d9b
ac6548f443a75b86d9e9151ff9c1b17c792b2afd
refs/heads/master
2023-03-19T06:29:03.216461
2021-03-10T02:53:14
2021-03-10T02:53:14
341,872,233
0
0
null
null
null
null
UTF-8
C++
false
false
108
cpp
#include "AADEBB.h" namespace AADEBB { std::string run() { std::string out("AADEBB"); return out; } }
[ "nakhyun@devsisters.com" ]
nakhyun@devsisters.com
315dafa0db41ef3ff0aaa4398de5899f48488ccb
78fb0f50a8aff82c5a3e4d2475baf9723923a2e1
/problem-00142/solution.cpp
efe261058fb5bb0bf3f27d484d017f84c19ab235
[]
no_license
RathiRohit/daily-coding-problem
300619b472fd3ee5e019f1b626861a1cbaf1a9ad
06b43fce175eaa5cc50d93b1f47d70a11844eecf
refs/heads/master
2021-08-10T18:14:15.043597
2021-07-21T14:23:03
2021-07-21T14:23:03
244,369,454
3
0
null
null
null
null
UTF-8
C++
false
false
519
cpp
#include <iostream> #include <vector> #include <queue> #define ll long long #define ull unsigned long long using namespace std; int main() { int n, k, tmp; cin>>n>>k; vector<int> window; for (int k_i=0; k_i<=k && k_i<n; k_i++) { cin>>tmp; window.push_back(tmp); } priority_queue<int, vector<int>, greater<int>> pq(window.begin(), window.end()); for (int n_i=0; n_i<n; n_i++) { cout<<pq.top()<<" "; pq.pop(); if (n_i < (n - k - 1)) { cin>>tmp; pq.push(tmp); } } cout<<endl; return 0; }
[ "rathirohitg1997@gmail.com" ]
rathirohitg1997@gmail.com
3c1277de0a8bd1e23f55fff2947aaa8b6e17f7ab
2a642208008c1ce2000431bea29f087d81d62abf
/Code_Analysis/argument_selection_inspection.cpp
165dc4150065c2b60461b0d5bd2fdec49cf8d1ed
[ "Apache-2.0" ]
permissive
anastasiak2512/basicDemo
563308f7a012623f832caa9cfad59854e68164b5
d43b16f79d5212eb60f1be8f7c16a86471d0da2f
refs/heads/main
2023-08-07T17:38:28.408710
2023-07-28T07:14:09
2023-07-28T07:14:09
72,375,534
10
16
NOASSERTION
2023-07-28T07:14:10
2016-10-30T21:06:28
C++
UTF-8
C++
false
false
773
cpp
#include <cstdint> #include <string> int Square(int width, int height) { return width * height; } class Rectangle { int width; int height; public: Rectangle(int w, int h) : width(w), height(h) {} int getWidth() const { return width; } int getHeight() const { return height; } }; int CalculateSquareOutsideTheClass(const Rectangle& rect){ return Square(rect.getHeight(), rect.getWidth()); } struct User { int64_t user_id; int64_t company_id; std::string user_name; }; const User* get_User(int64_t company_id, int64_t user_id) { return new User{company_id, user_id, "foo"}; } void call_User(int64_t company_id, int64_t user_id) { const User* user = get_User(user_id, company_id); //... }
[ "anastasia.kazakova@jetbrains.com" ]
anastasia.kazakova@jetbrains.com
ce5afa59b54e18130c988c6bd1ff65e98cc1137f
5df074aba01b6ab6a27ce2e14a923f39aecf2244
/src/clbind/class_registry.h
c73a2fe38c46ea8c13c946b16f89945ec9c23e68
[]
no_license
erm410/clasp
668e9e0c8c10baceec4de74a35d540b691b93912
1f60c8b60dffac1b9e346022fd7b017670e72098
refs/heads/master
2021-01-21T15:26:53.204310
2014-10-08T12:04:36
2014-10-08T12:04:36
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,097
h
/* File: class_registry.h */ /* Copyright (c) 2014, Christian E. Schafmeister CLASP is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. See directory 'clasp/licenses' for full details. 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. */ /* -^- */ // Copyright (c) 2003 Daniel Wallin and Arvid Norberg // 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. #ifndef CLBIND_CLASS_REGISTRY_HPP_INCLUDED #define CLBIND_CLASS_REGISTRY_HPP_INCLUDED #include <map> #include <clbind/config.h> #include <clbind/clbindPackage.h> #include <clbind/open.h> #include <clbind/typeid.h> namespace clbind { FORWARD(ClassRep); FORWARD(ClassRegistry); class ClassRegistry_O : public core::T_O { LISP_BASE1(core::T_O); LISP_CLASS(clbind,ClbindPkg,ClassRegistry_O,"ClassRegistry"); void initialize(); public: ClassRegistry_O() {}; virtual ~ClassRegistry_O() {}; public: static ClassRegistry_sp get_registry(); #if 0 int cpp_instance() const { return m_instance_metatable; } int cpp_class() const { return m_cpp_class_metatable; } int cl_instance() const { return m_instance_metatable; } int cl_class() const { return m_cl_class_metatable; } int cl_function() const { return m_cl_function_metatable; } #endif void add_class(type_id const& info, ClassRep_sp crep); ClassRep_sp find_class(type_id const& info) const; private: /*! Index on the type_id.id converted to a core::Pointer and use EQL equality */ core::HashTableEql_sp m_classes; // std::map<type_id, ClassRep_sp> m_classes; #if 0 // this is a cl reference that points to the cl table // that is to be used as meta table for all C++ class // instances. It is a kind of v-table. int m_instance_metatable; // this is a cl reference to the metatable to be used // for all classes defined in C++. int m_cpp_class_metatable; // this is a cl reference to the metatable to be used // for all classes defined in cl int m_cl_class_metatable; // this metatable only contains a destructor // for clbind::Detail::free_functions::function_rep int m_cl_function_metatable; #endif }; } #endif // CLBIND_CLASS_REGISTRY_HPP_INCLUDED
[ "chris.schaf@verizon.net" ]
chris.schaf@verizon.net
30569c5da8dbe8764881120b318853d61e02af9f
db9d6b3794941bc151a3557c258a5328d426fcdd
/computerS.cpp
54cfa8a8da8cddc83d3d9400e8dd07409c7d2539
[]
no_license
haopengsong/Scrabble-Game
1f34c9278e9664c65c34b5dcad3de258b98e80bd
27979824d1e0f4e28642c0df386f8228f745ac96
refs/heads/master
2021-06-25T08:03:34.052493
2020-09-22T10:19:11
2020-09-22T10:19:11
100,786,371
0
0
null
null
null
null
UTF-8
C++
false
false
31,110
cpp
#include "computerS.h" using namespace std; computerS::computerS() { } computerS::computerS(string n) { name = n; } computerS::~computerS() { } string computerS::getName() { return name; } //look up if there is square on the way before place tiles bool computerS::check7letter_(int s_x, int s_y, const Board & board, string verhor) { //col row if(verhor == "-") { //horizontally for(int i=1; i<=7; i++) { if(s_x+i<15 && board.getSquare(s_x+i,s_y)->isOccupied()) { //within 7 square, if the square is occupied return false; } } } else if (verhor == "|") { //downward upward for(int i=1; i<=7; i++) { if(s_y+i<15 && board.getSquare(s_x,s_y+i)->isOccupied()) { //within 7 square, if the square is occupied return false; } if(s_y-i>=0 && board.getSquare(s_x,s_y-i)->isOccupied()) { //within 7 square, if the square is occupied return false; } } } return true; } //find max score Move computerS::maxScoreMove(const Player & player) { //start find the maximum score Move m; int max=0; int count = 0; //iterator map<int, Move*>::iterator itmap; map<int, Move*>::iterator maxit; //for cpus if(checkForAI(player.getName()) == "CPUS") { //FIND THE MAX SCORE for(itmap=map_.begin(); itmap!=map_.end(); ++itmap) { count++; //cout <<"score: "<< itmap->first << endl; if(itmap->first > max) { max = itmap->first; maxit = itmap; } } if(map_.size() == 0) { //no move for this turn //should pass // cout << "pass move" << endl; Move* m_pass = new Move("PASS",player); return *m_pass; } else { m = *maxit->second; // cout <<"best move row ,col :" << m.y() << " " << m.x() << endl; // cout << "max " << maxit->first<< " counter "<< count << endl; } } //to check for CPUL else if (checkForAI(player.getName()) == "CPUL") { //reset counter count=0; //FIND THE LONGEST WORD FORMED BY CURRENT TILES for(itmap=letterLength_map_.begin(); itmap!=letterLength_map_.end(); ++itmap) { count++; //cout <<"length: "<< itmap->first << endl; if(itmap->first > max) { max = itmap->first; maxit = itmap; } } //cout <<"map size: " << map_.size() << endl; if(map_.size() == 0) { //cout << "pass move" << endl; //no move for this turn //should pass Move* m_pass = new Move("PASS",player); return *m_pass; } else { m = *maxit->second; //tile of the move vector<Tile*> vT = m.tileVector(); // for(unsigned int i=0; i<vT.size(); i++) // { // cout << vT[i]->getLetter() << endl; // } // cout <<"longest move row ,col :" << m.y() << " " << m.x() << endl; // cout << "number letters: " << maxit->first<< "counter "<< count << endl; } } return m; } bool computerS::checkLegal(vector<string> vv) { vector<string>::iterator vecit1; for(vecit1=vv.begin(); vecit1!=vv.end(); ++vecit1) { if(!dicT->isLegalWord(*vecit1)) return false; } return true; } //this function figure out all possible move and its score, store in a map(for word) void computerS::helper_Findstartlocation_word(const Board & board, int row,int col,string startWord, const Player & player) { //incrememnt row, col index ++row; ++col; string s1 = "PLACE"; string s2 = "-"; string s_col,s_row; string s3; set<string>::iterator it1; for(it1=v.begin(); it1!=v.end(); ++it1) { //words to be checked string word = *it1; s3 = word.substr(startWord.length()); // cout << "word :" << word << endl; // cout << "word mod: "<<s3 << endl; //check boundary before place //row stays the same, col increment if(col+word.length()<15) { //place word Move * temp_move = new Move(col+startWord.length(),row,true,s3,player); //cout << s1+" "+s2+" "<<row<<" "<<col+startWord.length()<<" "+s3 << endl; vector<string> v_board = board.getWords(*temp_move,score); int word_length = s3.length(); //check if there is a legal move before insert to map if(checkLegal(v_board)) { //FOR CPUS //store move into map along with its score map_.insert(std::make_pair(score,temp_move)); //for CPUL letterLength_map_.insert(std::make_pair(word_length,temp_move)); } } } } void computerS::helper_Findstartlocation_word_vertical(const Board & board, int row,int col,string startWord, const Player & player) { //incrememnt row, col index ++row; ++col; string s1 = "PLACE"; string s2 = "|"; string s_col,s_row; string s3; set<string>::iterator it1; for(it1=v.begin(); it1!=v.end(); ++it1) { //words to be checked string word = *it1; s3 = word.substr(startWord.length()); //cout << "word :" << word << endl; //cout << "word mod: "<<s3 << endl; //check boundary before place //row stays the same, col increment if(row+word.length()<15) { //place word Move * temp_move = new Move(col,row+startWord.length(),false,s3,player); //cout << s1+" "+s2+" "<<row+startWord.length()<<" "<<col<<" "+s3 << endl; vector<string> v_board = board.getWords(*temp_move,score); int word_length = s3.length(); //check if there is a legal move before insert to map if(checkLegal(v_board)) { //FOR CPUS //store move into map along with its score map_.insert(std::make_pair(score,temp_move)); //for CPUL letterLength_map_.insert(std::make_pair(word_length,temp_move)); } } } } //this function figure out all possible move and its score, store in a map(for single letter) void computerS::helper_Findstartlocation_letter_vertical(const Board & board, int row,int col,string startLetter, const Player & player,string tiles) { // ++i_y; // row // ++j_x; // col string s1 = "PLACE"; string s2 = "|"; string s3; //go over the set set<string>::iterator it1; for(it1=v.begin(); it1!=v.end(); ++it1) { //words to be checked string word = *it1; //make sure that AI won't place itself if(word != startLetter) { //locate the letter std::size_t found = word.find(startLetter); if (found!=std::string::npos) { s3 = word.substr(0,found)+word.substr(found+1); } // cout << "word :" << word << endl; // cout << "word mod: "<<s3 << endl; // cout << "found :" << found << endl; //if the letter is the start letter if(found == 0 && row + s3.length() <15) { //col row if(col+1<=15 && col+1 >= 1 && row+1<=15 && row+1>=1) { Move * temp_move; int temp; //make sure there is a blank tiles in player's tiles if(checkForBlank(tiles,temp)) { string mod_tiles_blank = checkBlankLetter(tiles,word); temp_move = new Move(col+1,row+1+1,false,mod_tiles_blank,player); } else { temp_move = new Move(col+1,row+1+1,false,s3,player); } //row col //cout << board.getDisplay(); // cout << s1+" "+s2+" "<<row+1+1<<" "<<col+1<<" "+s3 << endl; vector<string> v_board = board.getWords(*temp_move,score); //check if there is a legal move before insert to map int word_length = s3.length(); //check if there is a legal move before insert to map if(checkLegal(v_board)) { //FOR CPUS //store move into map along with its score map_.insert(std::make_pair(score,temp_move)); //for CPUL letterLength_map_.insert(std::make_pair(word_length,temp_move)); } } } else if(found !=0 && row + s3.length() <15) { //construct a move //cout << "if found is not 0" << endl; if(col+1<=15 && col+1 >= 1 && row+1-found<=15 && row+1-found >=1) { Move * temp_move; int temp; //make sure there is a blank tiles in player's tiles if(checkForBlank(tiles,temp)) { string mod_tiles_blank = checkBlankLetter(tiles,word); temp_move = new Move(col+1,1+row-found,false,mod_tiles_blank,player); } else { temp_move = new Move(col+1,1+row-found,false,s3,player); } //cout << board.getDisplay(); //cout << s1+" "+s2+" "<<row-found+1<<" "<<col+1<<" "+s3 << endl; vector<string> v_board = board.getWords(*temp_move,score); //vector<string>::iterator vecit2; // for(vecit2=v_board.begin(); vecit2!=v_board.end(); ++vecit2) // { // cout << *vecit2<<endl; // } int word_length = s3.length(); //check if there is a legal move before insert to map if(checkLegal(v_board)) { //FOR CPUS //store move into map along with its score map_.insert(std::make_pair(score,temp_move)); //for CPUL letterLength_map_.insert(std::make_pair(word_length,temp_move)); } } } } } } //check for position of blank tiles with word formed and add ? before it string computerS::checkBlankLetter(string tiles, string word) { string temp = word; string retval; for(unsigned int i=0;i<word.size();i++) { std::size_t found = tiles.find(word[i]); if(found!=std::string::npos) { //cout << found << endl; //if tiles has the letter //erase tiles.erase(tiles.begin()+found); } else { temp.insert(i,"?"); } } retval = temp; return retval; } //create all the move with a single letter void computerS::helper_Findstartlocation_letter(const Board & board, int i_y,int j_x,string startLetter, const Player & player, string tiles) { //incrememnt row, col index ++i_y; ++j_x; string s1 = "PLACE"; string s2 = "-"; string col,row; string s3; //if there are letters //go over the set set<string>::iterator it1; for(it1=v.begin(); it1!=v.end(); ++it1) { //words to be checked string word = *it1; //make sure that AI won't place itself if(word != startLetter) { //locate the letter std::size_t found = word.find(startLetter); if (found!=std::string::npos) { s3 = word.substr(0,found)+word.substr(found+1); } // cout << "word :" << word << endl; // cout << "word mod: "<<s3 << endl; // cout << "found :" << found << endl; //if the letter is the start letter if(found == 0 && i_y+1 + s3.length() <15) { //col row //making sure the starting location is valid if(!board.getSquare(i_y,j_x-1)->isOccupied()) { Move * temp_move; int temp; //make sure there is a blank tiles in player's tiles if(checkForBlank(tiles,temp)) { string mod_tiles_blank = checkBlankLetter(tiles,word); temp_move = new Move(i_y+1,j_x,true,mod_tiles_blank,player); } else { temp_move = new Move(i_y+1,j_x,true,s3,player); } //row col // cout << s1+" "+s2+" "<<j_x<<" "<<i_y+1<<" "+s3 << endl; // cout << board.getDisplay(); vector<string> v_board = board.getWords(*temp_move,score); //check the length of the main word int word_length = s3.length(); //check if there is a legal move before insert to map if(checkLegal(v_board)) { //FOR CPUS //store move into map along with its score map_.insert(std::make_pair(score,temp_move)); //for CPUL letterLength_map_.insert(std::make_pair(word_length,temp_move)); } } } else if(found !=0 && i_y-found + s3.length() <15) { //construct a move // cout << "if found is not 0" << endl; if(!board.getSquare(i_y-found-1,j_x-1)->isOccupied()) { Move * temp_move; //cout << i_y-found-1 << " " <<j_x-1 << endl; int temp; //make sure there is a blank tiles in player's tiles if(checkForBlank(tiles,temp)) { string mod_tiles_blank = checkBlankLetter(tiles,word); temp_move = new Move(i_y-found,j_x,true,mod_tiles_blank,player); } else { temp_move = new Move(i_y-found,j_x,true,s3,player); } // cout << s1+" "+s2+" "<<j_x<<" "<<i_y-found<<" "+s3 << endl; //cout << board.getDisplay(); vector<string> v_board = board.getWords(*temp_move,score); int word_length = s3.length(); //vector<string>::iterator vecit2; // for(vecit2=v_board.begin(); vecit2!=v_board.end(); ++vecit2) // { // //cout << *vecit2<<endl; // } if(checkLegal(v_board)) { //store move into map along with its score //CPUS map_.insert(std::make_pair(score,temp_move)); //for CPUL letterLength_map_.insert(std::make_pair(word_length,temp_move)); } } } } } } //this function returns true if there is a blank tiles in player's hand bool computerS::checkForBlank(string s,int & blank_pos) { std::size_t found = s.find("?"); blank_pos = found; if (found!=std::string::npos) { return true; } return false; } void computerS::blankTileOnFire(int blank_pos, string s1,string letter) { string allletter = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; for(unsigned int i=0; i<allletter.length(); i++) { //delete blank tile string s2 = s1.substr(0,blank_pos) + s1.substr(blank_pos+1); //add one option s2=s2+allletter[i]; //run findword string sofar=""; FindWord_letter(sofar,s2,*dicT,letter); } } Move computerS::getMove (const Board & board, const Player & player, std::map<char, int> initialTileCount) { //get AI's tiles set<Tile*> AI_tile = player.getHandTiles(); //for a string of tile only with letters string s_AI_tile; set<Tile*>::iterator it; for(it=AI_tile.begin(); it!=AI_tile.end(); ++it) { char letter = (*it)->getLetter(); string s_letter; stringstream ss; ss<<letter; ss>>s_letter; s_AI_tile+=s_letter; } //cout <<"ai tiles :" <<s_AI_tile << endl; //string to select horizontal or vertical string hor = "-"; string ver = "|"; //get cols and rows int col = board.getColumns(); int row = board.getRows(); //exhaustive search every square //if there are tiles on board if(!checkBoard(board)) { for(int j=0; j<row; j++) { for(int i=0; i<col; i++) { Square * sq = board.getSquare(i,j); //if there is a letter on the square if(sq->isOccupied()) { // cout<< "col " << i << endl; // cout << "row " << j << endl; //check bourdary //check if it is a single letter //horizontal if(i+1<col && !board.getSquare(i+1,j)->isOccupied() && i-1>=0 && !board.getSquare(i-1,j)->isOccupied()) { //this is a single letter //and there is no letter present is in 7 squares if(check7letter_(i,j,board,hor)) { //cast letter to string char letter = sq->getLetter(); string s_letter; stringstream ss; ss<<letter; ss>>s_letter; //cout <<" letter :"<< s_letter << endl; //for each subset of tiles, combine with the letter //lookup all possible combination string rest = s_AI_tile+s_letter; //add one letter to ai tiles and produce all possible words string sofar_find=""; int blank_position; if(checkForBlank(s_AI_tile,blank_position)) { blankTileOnFire(blank_position,s_AI_tile,s_letter); } else { string possible_word = FindWord_letter(sofar_find,rest,*dicT,s_letter); } //cout << "size :" << v.size()<< endl; helper_Findstartlocation_letter(board,i,j,s_letter,player,s_AI_tile); v.clear(); } } //if it is not a single letter, then there must be a whole word onboard else if(i+1<col && board.getSquare(i+1,j)->isOccupied() && i-1>=0 && !board.getSquare(i-1,j)->isOccupied()) { //first try grab the whole word into a string string theword; //start counting int count=0; while(board.getSquare(i+count,j)->isOccupied()) { char makeword = board.getSquare(i+count,j)->getLetter(); stringstream ss; ss<<makeword; string s_makeword; ss>>s_makeword; theword+=s_makeword; count++; } // cout << "theword " << theword << endl; if(dicT->isLegalWord(theword)) { //RUN findword on the whole word string sofar_find=""; string possible_word = FindWord_word(sofar_find,s_AI_tile,*dicT,theword); // cout << "size :" << v.size()<< endl; helper_Findstartlocation_word(board,j,i,theword, player); v.clear(); } } //vertical //for vertical placement, //need a function to check //check boundary //if the square has no up and down neighbor in 7 square if(j+1<15 && j-1>=0 && check7letter_(i,j,board,ver)) { // cout << "v1" << endl; char letter = sq->getLetter(); string s_letter; stringstream ss; ss<<letter; ss>>s_letter; // cout <<" letter :"<< s_letter << endl; //for each subset of tiles, combine with the letter //lookup all possible combination string rest = s_AI_tile+s_letter; //add one letter to ai tiles and produce all possible words string sofar_find=""; int blank_position; if(checkForBlank(s_AI_tile,blank_position)) { blankTileOnFire(blank_position,s_AI_tile,s_letter); } else { string possible_word = FindWord_letter(sofar_find,rest,*dicT,s_letter); } helper_Findstartlocation_letter_vertical( board,j,i,s_letter, player,s_AI_tile);//j is row, i is col v.clear(); } else if(j+1<15 && !board.getSquare(i,j-1)->isOccupied() && j-1>=0 && board.getSquare(i,j+1)->isOccupied()) { //cout << "v2" << endl; //first try grab the whole word into a string string theword; //start counting int count=0; // cout << "row col :" << j+count << " " << i << endl; while(j+count < 15 && board.getSquare(i,j+count)->isOccupied() == 1) { // cout << board.getSquare(i,j+count)->isOccupied() << endl; // cout << board.getSquare(i,j+count)->getLetter()<< endl; char makeword = board.getSquare(i,j+count)->getLetter(); stringstream ss; ss<<makeword; string s_makeword; ss>>s_makeword; theword+=s_makeword; count++; if(j+count+1 == 15) break; } if(dicT->isLegalWord(theword)) { // cout << "theword " << theword << endl; string sofar_find=""; string possible_word = FindWord_word(sofar_find,s_AI_tile,*dicT,theword); //cout << "size :" << v.size()<< endl; helper_Findstartlocation_word_vertical(board,j,i,theword, player); v.clear(); } } } } } Move m = maxScoreMove(player); map_.clear(); letterLength_map_.clear(); return m; } else { //nothing on board string empty_square = ""; string rest = s_AI_tile+empty_square; //add one letter to ai tiles and produce all possible words string sofar_find=""; string possible_word = FindWord_letter(sofar_find,rest,*dicT,empty_square); //helper_Findstartlocation_letter(board,7,7,s_letter,player); helper_start(board,player); v.clear(); Move m_start = maxScoreMove(player); map_.clear(); letterLength_map_.clear(); return m_start; } } void computerS::helper_start(const Board & board, const Player & player) { set<string>::iterator it1; for(it1=v.begin(); it1!=v.end(); ++it1) { //words to be checked string word = *it1; Move * temp_move = new Move(8,8,true,word,player); vector<string> v_board = board.getWords(*temp_move,score); //check the length of the main word int word_length = word.length(); //check if there is a legal move before insert to map if(checkLegal(v_board)) { //FOR CPUS //store move into map along with its score map_.insert(std::make_pair(score,temp_move)); //for CPUL letterLength_map_.insert(std::make_pair(word_length,temp_move)); } } } void computerS::initialize(Dictionary* d) { //STORE ALL PREFIXS prefix_set = allPrefix(d->allWords()); dicT = d; } set<string> computerS::allPrefix(set<string> allwords) { set<string> prefix; set<string>::iterator it; //to split every words to prefixs for(it=allwords.begin(); it!=allwords.end(); ++it) { string word = *it; for(unsigned int i=0; i<word.length()+1; i++) { //insert prefix to set prefix.insert(word.substr(0,i)); } } return prefix; } //findword for whole word on board string computerS::FindWord_word(string soFar, string rest, Dictionary d, string word_onboard) { if (rest.empty()) { if (d.isLegalWord(soFar)) { return "finished!"; } else return ""; } else { for (unsigned int i = 0; i < rest.length(); i++) { string remain = rest.substr(0, i) + rest.substr(i+1); string found; //cout << "pre check : " <<word_onboard + soFar+rest[i] << endl; if(prefix_set.find(word_onboard + soFar+rest[i])!=prefix_set.end() || prefix_set.find(soFar+rest[i] + word_onboard)!=prefix_set.end()) { if(d.isLegalWord(word_onboard + soFar+rest[i])) { //store all possible words to a vector // cout << "words on the road : " <<word_onboard + soFar+rest[i] << endl; v.insert(word_onboard + soFar+rest[i]); } if(d.isLegalWord(soFar+rest[i] + word_onboard)) { // cout << "words on the road : " << soFar+rest[i] + word_onboard<< endl; } //recursive found = FindWord_word(soFar + rest[i], remain, d,word_onboard); if (!found.empty()) return found; } else { continue; } } } return ""; } //findword for single letter on board string computerS::FindWord_letter(string soFar, string rest, Dictionary d,string mustHold) { if (rest.empty()) { if (d.isLegalWord(soFar)) { return "finished!"; } else return ""; } else { for (unsigned int i = 0; i < rest.length(); i++) { string remain = rest.substr(0, i) + rest.substr(i+1); string found; if(prefix_set.find(soFar+rest[i])!=prefix_set.end()) { if(mustHold != "") { //if the start square is occupied if(d.isLegalWord(soFar+rest[i]) && CheckContent(soFar+rest[i],mustHold) && v.find(soFar+rest[i])==v.end()) { //store all possible words to a vector // cout << soFar+rest[i] << endl; v.insert(soFar+rest[i]); } } else if(mustHold == "") { //if the start square is not occupied if(d.isLegalWord(soFar+rest[i]) && v.find(soFar+rest[i])==v.end()) { v.insert(soFar+rest[i]); } } //recursive found = FindWord_letter(soFar + rest[i], remain, d,mustHold); if (!found.empty()) return found; } else { continue; } } } return ""; } //check that the word must contain s inside bool computerS::CheckContent(string ss,string mustHave) { int count = 0; for(unsigned int i=0; i<ss.length(); i++) { stringstream sss; sss<<ss[i]; string tocheck; sss>>tocheck; if(tocheck == mustHave) { count++; } } if(count == 0) { return false; } return true; } string computerS::checkForAI(string s) { string cpus = "CPUS"; string cpul = "CPUL"; string notAI = "NOTAI"; //grab the first 4 letters string tocheck = refineupper(s); //check length if(s.length() >= 4) { string first_four=""; for(int i=0; i<4; i++) { char toadd = tocheck[i]; first_four+=toadd; } if(first_four == "CPUS") { return cpus; } else if (first_four == "CPUL") { return cpul; } } return notAI; } string computerS::refineupper (string torefine) { string input; char in; for(unsigned int i=0; i<torefine.length(); i++) { in = (char)toupper(torefine[i]); input = input + in; } return input; } //return true if nothing on the board(need to place start square) bool computerS::checkBoard(const Board & board) { int col = board.getColumns(); int row = board.getRows(); for(int j=0; j<row; j++) { for(int i=0; i<col; i++) { if(board.getSquare(j,i)->isOccupied()) { return false; } } } return true; }
[ "haopengs@usc.edu" ]
haopengs@usc.edu
46f964da963ee5d8f62b4c8a8ccf038c9f91bd8e
0e8a1c2ec92accda91ac251e36a202890404c45a
/src/main.h
20f31fe17ad0d32218420d1408408367c957ed4e
[ "MIT" ]
permissive
tnmchain/tnmblockchain
f176ceaf15f9bd4ea3726b49dfc6d264eb012d4a
e41de60273e0f091cce84a9f95e3c0a1e5d575bf
refs/heads/master
2022-11-30T02:13:38.651541
2020-08-11T14:54:43
2020-08-11T14:54:43
286,573,716
0
0
null
null
null
null
UTF-8
C++
false
false
72,423
h
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2014 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef BITCOIN_MAIN_H #define BITCOIN_MAIN_H #include "bignum.h" #include "sync.h" #include "net.h" #include "script.h" #include "scrypt.h" #include <list> class CWallet; class CBlock; class CBlockIndex; class CKeyItem; class CReserveKey; class CAddress; class CInv; class CNode; struct CBlockIndexWorkComparator; /** The maximum allowed size for a serialized block, in bytes (network rule) */ static const unsigned int MAX_BLOCK_SIZE = 1000000; // 1000KB block hard limit /** Obsolete: maximum size for mined blocks */ static const unsigned int MAX_BLOCK_SIZE_GEN = MAX_BLOCK_SIZE/4; // 250KB block soft limit /** Default for -blockmaxsize, maximum size for mined blocks **/ static const unsigned int DEFAULT_BLOCK_MAX_SIZE = 250000; /** Default for -blockprioritysize, maximum space for zero/low-fee transactions **/ static const unsigned int DEFAULT_BLOCK_PRIORITY_SIZE = 17000; /** The maximum size for transactions we're willing to relay/mine */ static const unsigned int MAX_STANDARD_TX_SIZE = 100000; /** The maximum allowed number of signature check operations in a block (network rule) */ static const unsigned int MAX_BLOCK_SIGOPS = MAX_BLOCK_SIZE/50; /** Default for -maxorphantx, maximum number of orphan transactions kept in memory */ static const unsigned int DEFAULT_MAX_ORPHAN_TRANSACTIONS = 25; /** The maximum size of a blk?????.dat file (since 0.8) */ static const unsigned int MAX_BLOCKFILE_SIZE = 0x8000000; // 128 MiB /** The pre-allocation chunk size for blk?????.dat files (since 0.8) */ static const unsigned int BLOCKFILE_CHUNK_SIZE = 0x1000000; // 16 MiB /** The pre-allocation chunk size for rev?????.dat files (since 0.8) */ static const unsigned int UNDOFILE_CHUNK_SIZE = 0x100000; // 1 MiB /** Fake height value used in CCoins to signify they are only in the memory pool (since 0.8) */ static const unsigned int MEMPOOL_HEIGHT = 0x7FFFFFFF; /** Dust Soft Limit, allowed with additional fee per output */ static const int64 DUST_SOFT_LIMIT = 100000; // 0.001 TNM /** Dust Hard Limit, ignored as wallet inputs (mininput default) */ static const int64 DUST_HARD_LIMIT = 1000; // 0.00001 TNM mininput /** No amount larger than this (in satoshi) is valid */ static const int64 MAX_MONEY = 100000000 * COIN; inline bool MoneyRange(int64 nValue) { return (nValue >= 0 && nValue <= MAX_MONEY); } /** Coinbase transaction outputs can only be spent after this number of new blocks (network rule) */ static const int COINBASE_MATURITY = 120; /** Threshold for nLockTime: below this value it is interpreted as block number, otherwise as UNIX timestamp. */ static const unsigned int LOCKTIME_THRESHOLD = 500000000; // Tue Nov 5 00:53:20 1985 UTC /** Maximum number of script-checking threads allowed */ static const int MAX_SCRIPTCHECK_THREADS = 16; #ifdef USE_UPNP static const int fHaveUPnP = true; #else static const int fHaveUPnP = false; #endif extern CScript COINBASE_FLAGS; extern CCriticalSection cs_main; extern std::map<uint256, CBlockIndex*> mapBlockIndex; extern std::set<CBlockIndex*, CBlockIndexWorkComparator> setBlockIndexValid; extern uint256 hashGenesisBlock; extern CBlockIndex* pindexGenesisBlock; extern int nBestHeight; extern uint256 nBestChainWork; extern uint256 nBestInvalidWork; extern uint256 hashBestChain; extern CBlockIndex* pindexBest; extern unsigned int nTransactionsUpdated; extern uint64 nLastBlockTx; extern uint64 nLastBlockSize; extern const std::string strMessageMagic; extern double dHashesPerSec; extern int64 nHPSTimerStart; extern int64 nTimeBestReceived; extern CCriticalSection cs_setpwalletRegistered; extern std::set<CWallet*> setpwalletRegistered; extern unsigned char pchMessageStart[4]; extern bool fImporting; extern bool fReindex; extern bool fBenchmark; extern int nScriptCheckThreads; extern bool fTxIndex; extern unsigned int nCoinCacheSize; // Settings extern int64 nTransactionFee; extern int64 nMinimumInputValue; // Minimum disk space required - used in CheckDiskSpace() static const uint64 nMinDiskSpace = 52428800; class CReserveKey; class CCoinsDB; class CBlockTreeDB; struct CDiskBlockPos; class CCoins; class CTxUndo; class CCoinsView; class CCoinsViewCache; class CScriptCheck; class CValidationState; struct CBlockTemplate; /** Register a wallet to receive updates from core */ void RegisterWallet(CWallet* pwalletIn); /** Unregister a wallet from core */ void UnregisterWallet(CWallet* pwalletIn); /** Push an updated transaction to all registered wallets */ void SyncWithWallets(const uint256 &hash, const CTransaction& tx, const CBlock* pblock = NULL, bool fUpdate = false); /** Process an incoming block */ bool ProcessBlock(CValidationState &state, CNode* pfrom, CBlock* pblock, CDiskBlockPos *dbp = NULL); /** Check whether enough disk space is available for an incoming block */ bool CheckDiskSpace(uint64 nAdditionalBytes = 0); /** Open a block file (blk?????.dat) */ FILE* OpenBlockFile(const CDiskBlockPos &pos, bool fReadOnly = false); /** Open an undo file (rev?????.dat) */ FILE* OpenUndoFile(const CDiskBlockPos &pos, bool fReadOnly = false); /** Import blocks from an external file */ bool LoadExternalBlockFile(FILE* fileIn, CDiskBlockPos *dbp = NULL); /** Initialize a new block tree database + block data on disk */ bool InitBlockIndex(); /** Load the block tree and coins database from disk */ bool LoadBlockIndex(); /** Unload database information */ void UnloadBlockIndex(); /** Verify consistency of the block and coin databases */ bool VerifyDB(int nCheckLevel, int nCheckDepth); /** Print the loaded block tree */ void PrintBlockTree(); /** Find a block by height in the currently-connected chain */ CBlockIndex* FindBlockByHeight(int nHeight); /** Process protocol messages received from a given node */ bool ProcessMessages(CNode* pfrom); /** Send queued protocol messages to be sent to a give node */ bool SendMessages(CNode* pto, bool fSendTrickle); /** Run an instance of the script checking thread */ void ThreadScriptCheck(); /** Run the miner threads */ void GenerateBitcoins(bool fGenerate, CWallet* pwallet); /** Generate a new block, without valid proof-of-work */ CBlockTemplate* CreateNewBlock(const CScript& scriptPubKeyIn); CBlockTemplate* CreateNewBlockWithKey(CReserveKey& reservekey); /** Modify the extranonce in a block */ void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce); /** Do mining precalculation */ void FormatHashBuffers(CBlock* pblock, char* pmidstate, char* pdata, char* phash1); /** Check mined block */ bool CheckWork(CBlock* pblock, CWallet& wallet, CReserveKey& reservekey); /** Check whether a block hash satisfies the proof-of-work requirement specified by nBits */ bool CheckProofOfWork(uint256 hash, unsigned int nBits); /** Calculate the minimum amount of work a received block needs, without knowing its direct parent */ unsigned int ComputeMinWork(unsigned int nBase, int64 nTime); /** Get the number of active peers */ int GetNumBlocksOfPeers(); /** Check whether we are doing an initial block download (synchronizing from disk or network) */ bool IsInitialBlockDownload(); /** Format a string that describes several potential problems detected by the core */ std::string GetWarnings(std::string strFor); /** Retrieve a transaction (from memory pool, or from disk, if possible) */ bool GetTransaction(const uint256 &hash, CTransaction &tx, uint256 &hashBlock, bool fAllowSlow = false); /** Connect/disconnect blocks until pindexNew is the new tip of the active block chain */ bool SetBestChain(CValidationState &state, CBlockIndex* pindexNew); /** Find the best known block, and make it the tip of the block chain */ bool ConnectBestBlock(CValidationState &state); /** Create a new block index entry for a given block hash */ CBlockIndex * InsertBlockIndex(uint256 hash); /** Verify a signature */ bool VerifySignature(const CCoins& txFrom, const CTransaction& txTo, unsigned int nIn, unsigned int flags, int nHashType); /** Abort with a message */ bool AbortNode(const std::string &msg); bool GetWalletFile(CWallet* pwallet, std::string &strWalletFileOut); struct CDiskBlockPos { int nFile; unsigned int nPos; IMPLEMENT_SERIALIZE( READWRITE(VARINT(nFile)); READWRITE(VARINT(nPos)); ) CDiskBlockPos() { SetNull(); } CDiskBlockPos(int nFileIn, unsigned int nPosIn) { nFile = nFileIn; nPos = nPosIn; } friend bool operator==(const CDiskBlockPos &a, const CDiskBlockPos &b) { return (a.nFile == b.nFile && a.nPos == b.nPos); } friend bool operator!=(const CDiskBlockPos &a, const CDiskBlockPos &b) { return !(a == b); } void SetNull() { nFile = -1; nPos = 0; } bool IsNull() const { return (nFile == -1); } }; struct CDiskTxPos : public CDiskBlockPos { unsigned int nTxOffset; // after header IMPLEMENT_SERIALIZE( READWRITE(*(CDiskBlockPos*)this); READWRITE(VARINT(nTxOffset)); ) CDiskTxPos(const CDiskBlockPos &blockIn, unsigned int nTxOffsetIn) : CDiskBlockPos(blockIn.nFile, blockIn.nPos), nTxOffset(nTxOffsetIn) { } CDiskTxPos() { SetNull(); } void SetNull() { CDiskBlockPos::SetNull(); nTxOffset = 0; } }; /** An inpoint - a combination of a transaction and an index n into its vin */ class CInPoint { public: CTransaction* ptx; unsigned int n; CInPoint() { SetNull(); } CInPoint(CTransaction* ptxIn, unsigned int nIn) { ptx = ptxIn; n = nIn; } void SetNull() { ptx = NULL; n = (unsigned int) -1; } bool IsNull() const { return (ptx == NULL && n == (unsigned int) -1); } }; /** An outpoint - a combination of a transaction hash and an index n into its vout */ class COutPoint { public: uint256 hash; unsigned int n; COutPoint() { SetNull(); } COutPoint(uint256 hashIn, unsigned int nIn) { hash = hashIn; n = nIn; } IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); ) void SetNull() { hash = 0; n = (unsigned int) -1; } bool IsNull() const { return (hash == 0 && n == (unsigned int) -1); } friend bool operator<(const COutPoint& a, const COutPoint& b) { return (a.hash < b.hash || (a.hash == b.hash && a.n < b.n)); } friend bool operator==(const COutPoint& a, const COutPoint& b) { return (a.hash == b.hash && a.n == b.n); } friend bool operator!=(const COutPoint& a, const COutPoint& b) { return !(a == b); } std::string ToString() const { return strprintf("COutPoint(%s, %u)", hash.ToString().c_str(), n); } void print() const { printf("%s\n", ToString().c_str()); } }; /** An input of a transaction. It contains the location of the previous * transaction's output that it claims and a signature that matches the * output's public key. */ class CTxIn { public: COutPoint prevout; CScript scriptSig; unsigned int nSequence; CTxIn() { nSequence = std::numeric_limits<unsigned int>::max(); } explicit CTxIn(COutPoint prevoutIn, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=std::numeric_limits<unsigned int>::max()) { prevout = prevoutIn; scriptSig = scriptSigIn; nSequence = nSequenceIn; } CTxIn(uint256 hashPrevTx, unsigned int nOut, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=std::numeric_limits<unsigned int>::max()) { prevout = COutPoint(hashPrevTx, nOut); scriptSig = scriptSigIn; nSequence = nSequenceIn; } IMPLEMENT_SERIALIZE ( READWRITE(prevout); READWRITE(scriptSig); READWRITE(nSequence); ) bool IsFinal() const { return (nSequence == std::numeric_limits<unsigned int>::max()); } friend bool operator==(const CTxIn& a, const CTxIn& b) { return (a.prevout == b.prevout && a.scriptSig == b.scriptSig && a.nSequence == b.nSequence); } friend bool operator!=(const CTxIn& a, const CTxIn& b) { return !(a == b); } std::string ToString() const { std::string str; str += "CTxIn("; str += prevout.ToString(); if (prevout.IsNull()) str += strprintf(", coinbase %s", HexStr(scriptSig).c_str()); else str += strprintf(", scriptSig=%s", scriptSig.ToString().substr(0,24).c_str()); if (nSequence != std::numeric_limits<unsigned int>::max()) str += strprintf(", nSequence=%u", nSequence); str += ")"; return str; } void print() const { printf("%s\n", ToString().c_str()); } }; /** An output of a transaction. It contains the public key that the next input * must be able to sign with to claim it. */ class CTxOut { public: int64 nValue; CScript scriptPubKey; CTxOut() { SetNull(); } CTxOut(int64 nValueIn, CScript scriptPubKeyIn) { nValue = nValueIn; scriptPubKey = scriptPubKeyIn; } IMPLEMENT_SERIALIZE ( READWRITE(nValue); READWRITE(scriptPubKey); ) void SetNull() { nValue = -1; scriptPubKey.clear(); } bool IsNull() const { return (nValue == -1); } uint256 GetHash() const { return SerializeHash(*this); } friend bool operator==(const CTxOut& a, const CTxOut& b) { return (a.nValue == b.nValue && a.scriptPubKey == b.scriptPubKey); } friend bool operator!=(const CTxOut& a, const CTxOut& b) { return !(a == b); } bool IsDust() const; std::string ToString() const { return strprintf("CTxOut(nValue=%"PRI64d".%08"PRI64d", scriptPubKey=%s)", nValue / COIN, nValue % COIN, scriptPubKey.ToString().substr(0,30).c_str()); } void print() const { printf("%s\n", ToString().c_str()); } }; enum GetMinFee_mode { GMF_BLOCK, GMF_RELAY, GMF_SEND, }; /** The basic transaction that is broadcasted on the network and contained in * blocks. A transaction can contain multiple inputs and outputs. */ class CTransaction { public: static int64 nMinTxFee; static int64 nMinRelayTxFee; static const int CURRENT_VERSION=1; int nVersion; std::vector<CTxIn> vin; std::vector<CTxOut> vout; unsigned int nLockTime; CTransaction() { SetNull(); } IMPLEMENT_SERIALIZE ( READWRITE(this->nVersion); nVersion = this->nVersion; READWRITE(vin); READWRITE(vout); READWRITE(nLockTime); ) void SetNull() { nVersion = CTransaction::CURRENT_VERSION; vin.clear(); vout.clear(); nLockTime = 0; } bool IsNull() const { return (vin.empty() && vout.empty()); } uint256 GetHash() const { return SerializeHash(*this); } uint256 GetNormalizedHash() const { return SignatureHash(CScript(), *this, 0, SIGHASH_ALL); } bool IsFinal(int nBlockHeight=0, int64 nBlockTime=0) const { // Time based nLockTime implemented in 0.1.6 if (nLockTime == 0) return true; if (nBlockHeight == 0) nBlockHeight = nBestHeight; if (nBlockTime == 0) nBlockTime = GetAdjustedTime(); if ((int64)nLockTime < ((int64)nLockTime < LOCKTIME_THRESHOLD ? (int64)nBlockHeight : nBlockTime)) return true; BOOST_FOREACH(const CTxIn& txin, vin) if (!txin.IsFinal()) return false; return true; } bool IsNewerThan(const CTransaction& old) const { if (vin.size() != old.vin.size()) return false; for (unsigned int i = 0; i < vin.size(); i++) if (vin[i].prevout != old.vin[i].prevout) return false; bool fNewer = false; unsigned int nLowest = std::numeric_limits<unsigned int>::max(); for (unsigned int i = 0; i < vin.size(); i++) { if (vin[i].nSequence != old.vin[i].nSequence) { if (vin[i].nSequence <= nLowest) { fNewer = false; nLowest = vin[i].nSequence; } if (old.vin[i].nSequence < nLowest) { fNewer = true; nLowest = old.vin[i].nSequence; } } } return fNewer; } bool IsCoinBase() const { return (vin.size() == 1 && vin[0].prevout.IsNull()); } /** Check for standard transaction types @return True if all outputs (scriptPubKeys) use only standard transaction forms */ bool IsStandard(std::string& strReason) const; bool IsStandard() const { std::string strReason; return IsStandard(strReason); } /** Check for standard transaction types @param[in] mapInputs Map of previous transactions that have outputs we're spending @return True if all inputs (scriptSigs) use only standard transaction forms */ bool AreInputsStandard(CCoinsViewCache& mapInputs) const; /** Count ECDSA signature operations the old-fashioned (pre-0.6) way @return number of sigops this transaction's outputs will produce when spent */ unsigned int GetLegacySigOpCount() const; /** Count ECDSA signature operations in pay-to-script-hash inputs. @param[in] mapInputs Map of previous transactions that have outputs we're spending @return maximum number of sigops required to validate this transaction's inputs */ unsigned int GetP2SHSigOpCount(CCoinsViewCache& mapInputs) const; /** Amount of bitcoins spent by this transaction. @return sum of all outputs (note: does not include fees) */ int64 GetValueOut() const { int64 nValueOut = 0; BOOST_FOREACH(const CTxOut& txout, vout) { nValueOut += txout.nValue; if (!MoneyRange(txout.nValue) || !MoneyRange(nValueOut)) throw std::runtime_error("CTransaction::GetValueOut() : value out of range"); } return nValueOut; } /** Amount of bitcoins coming in to this transaction Note that lightweight clients may not know anything besides the hash of previous transactions, so may not be able to calculate this. @param[in] mapInputs Map of previous transactions that have outputs we're spending @return Sum of value of all inputs (scriptSigs) */ int64 GetValueIn(CCoinsViewCache& mapInputs) const; static bool AllowFree(double dPriority) { // Large (in bytes) low-priority (new, small-coin) transactions // need a fee. return dPriority > COIN * 1160 / 250; } // Apply the effects of this transaction on the UTXO set represented by view void UpdateCoins(const CTransaction& tx, CValidationState &state, CCoinsViewCache &inputs, CTxUndo &txundo, int nHeight, const uint256 &txhash); int64 GetMinFee(unsigned int nBlockSize=1, bool fAllowFree=true, enum GetMinFee_mode mode=GMF_BLOCK) const; friend bool operator==(const CTransaction& a, const CTransaction& b) { return (a.nVersion == b.nVersion && a.vin == b.vin && a.vout == b.vout && a.nLockTime == b.nLockTime); } friend bool operator!=(const CTransaction& a, const CTransaction& b) { return !(a == b); } std::string ToString() const { std::string str; str += strprintf("CTransaction(hash=%s, ver=%d, vin.size=%"PRIszu", vout.size=%"PRIszu", nLockTime=%u)\n", GetHash().ToString().c_str(), nVersion, vin.size(), vout.size(), nLockTime); for (unsigned int i = 0; i < vin.size(); i++) str += " " + vin[i].ToString() + "\n"; for (unsigned int i = 0; i < vout.size(); i++) str += " " + vout[i].ToString() + "\n"; return str; } void print() const { printf("%s", ToString().c_str()); } // Check whether all prevouts of this transaction are present in the UTXO set represented by view bool HaveInputs(CCoinsViewCache &view) const; // Check whether all inputs of this transaction are valid (no double spends, scripts & sigs, amounts) // This does not modify the UTXO set. If pvChecks is not NULL, script checks are pushed onto it // instead of being performed inline. bool CheckInputs(CValidationState &state, CCoinsViewCache &view, bool fScriptChecks = true, unsigned int flags = SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_STRICTENC, std::vector<CScriptCheck> *pvChecks = NULL) const; // Apply the effects of this transaction on the UTXO set represented by view void UpdateCoins(CValidationState &state, CCoinsViewCache &view, CTxUndo &txundo, int nHeight, const uint256 &txhash) const; // Context-independent validity checks bool CheckTransaction(CValidationState &state) const; // Try to accept this transaction into the memory pool bool AcceptToMemoryPool(CValidationState &state, bool fCheckInputs=true, bool fLimitFree = true, bool* pfMissingInputs=NULL, bool fRejectInsaneFee = false); protected: static const CTxOut &GetOutputFor(const CTxIn& input, CCoinsViewCache& mapInputs); }; /** wrapper for CTxOut that provides a more compact serialization */ class CTxOutCompressor { private: CTxOut &txout; public: static uint64 CompressAmount(uint64 nAmount); static uint64 DecompressAmount(uint64 nAmount); CTxOutCompressor(CTxOut &txoutIn) : txout(txoutIn) { } IMPLEMENT_SERIALIZE(({ if (!fRead) { uint64 nVal = CompressAmount(txout.nValue); READWRITE(VARINT(nVal)); } else { uint64 nVal = 0; READWRITE(VARINT(nVal)); txout.nValue = DecompressAmount(nVal); } CScriptCompressor cscript(REF(txout.scriptPubKey)); READWRITE(cscript); });) }; /** Undo information for a CTxIn * * Contains the prevout's CTxOut being spent, and if this was the * last output of the affected transaction, its metadata as well * (coinbase or not, height, transaction version) */ class CTxInUndo { public: CTxOut txout; // the txout data before being spent bool fCoinBase; // if the outpoint was the last unspent: whether it belonged to a coinbase unsigned int nHeight; // if the outpoint was the last unspent: its height int nVersion; // if the outpoint was the last unspent: its version CTxInUndo() : txout(), fCoinBase(false), nHeight(0), nVersion(0) {} CTxInUndo(const CTxOut &txoutIn, bool fCoinBaseIn = false, unsigned int nHeightIn = 0, int nVersionIn = 0) : txout(txoutIn), fCoinBase(fCoinBaseIn), nHeight(nHeightIn), nVersion(nVersionIn) { } unsigned int GetSerializeSize(int nType, int nVersion) const { return ::GetSerializeSize(VARINT(nHeight*2+(fCoinBase ? 1 : 0)), nType, nVersion) + (nHeight > 0 ? ::GetSerializeSize(VARINT(this->nVersion), nType, nVersion) : 0) + ::GetSerializeSize(CTxOutCompressor(REF(txout)), nType, nVersion); } template<typename Stream> void Serialize(Stream &s, int nType, int nVersion) const { ::Serialize(s, VARINT(nHeight*2+(fCoinBase ? 1 : 0)), nType, nVersion); if (nHeight > 0) ::Serialize(s, VARINT(this->nVersion), nType, nVersion); ::Serialize(s, CTxOutCompressor(REF(txout)), nType, nVersion); } template<typename Stream> void Unserialize(Stream &s, int nType, int nVersion) { unsigned int nCode = 0; ::Unserialize(s, VARINT(nCode), nType, nVersion); nHeight = nCode / 2; fCoinBase = nCode & 1; if (nHeight > 0) ::Unserialize(s, VARINT(this->nVersion), nType, nVersion); ::Unserialize(s, REF(CTxOutCompressor(REF(txout))), nType, nVersion); } }; /** Undo information for a CTransaction */ class CTxUndo { public: // undo information for all txins std::vector<CTxInUndo> vprevout; IMPLEMENT_SERIALIZE( READWRITE(vprevout); ) }; /** Undo information for a CBlock */ class CBlockUndo { public: std::vector<CTxUndo> vtxundo; // for all but the coinbase IMPLEMENT_SERIALIZE( READWRITE(vtxundo); ) bool WriteToDisk(CDiskBlockPos &pos, const uint256 &hashBlock) { // Open history file to append CAutoFile fileout = CAutoFile(OpenUndoFile(pos), SER_DISK, CLIENT_VERSION); if (!fileout) return error("CBlockUndo::WriteToDisk() : OpenUndoFile failed"); // Write index header unsigned int nSize = fileout.GetSerializeSize(*this); fileout << FLATDATA(pchMessageStart) << nSize; // Write undo data long fileOutPos = ftell(fileout); if (fileOutPos < 0) return error("CBlockUndo::WriteToDisk() : ftell failed"); pos.nPos = (unsigned int)fileOutPos; fileout << *this; // calculate & write checksum CHashWriter hasher(SER_GETHASH, PROTOCOL_VERSION); hasher << hashBlock; hasher << *this; fileout << hasher.GetHash(); // Flush stdio buffers and commit to disk before returning fflush(fileout); if (!IsInitialBlockDownload()) FileCommit(fileout); return true; } bool ReadFromDisk(const CDiskBlockPos &pos, const uint256 &hashBlock) { // Open history file to read CAutoFile filein = CAutoFile(OpenUndoFile(pos, true), SER_DISK, CLIENT_VERSION); if (!filein) return error("CBlockUndo::ReadFromDisk() : OpenBlockFile failed"); // Read block uint256 hashChecksum; try { filein >> *this; filein >> hashChecksum; } catch (std::exception &e) { return error("%s() : deserialize or I/O error", __PRETTY_FUNCTION__); } // Verify checksum CHashWriter hasher(SER_GETHASH, PROTOCOL_VERSION); hasher << hashBlock; hasher << *this; if (hashChecksum != hasher.GetHash()) return error("CBlockUndo::ReadFromDisk() : checksum mismatch"); return true; } }; /** pruned version of CTransaction: only retains metadata and unspent transaction outputs * * Serialized format: * - VARINT(nVersion) * - VARINT(nCode) * - unspentness bitvector, for vout[2] and further; least significant byte first * - the non-spent CTxOuts (via CTxOutCompressor) * - VARINT(nHeight) * * The nCode value consists of: * - bit 1: IsCoinBase() * - bit 2: vout[0] is not spent * - bit 4: vout[1] is not spent * - The higher bits encode N, the number of non-zero bytes in the following bitvector. * - In case both bit 2 and bit 4 are unset, they encode N-1, as there must be at * least one non-spent output). * * Example: 0104835800816115944e077fe7c803cfa57f29b36bf87c1d358bb85e * <><><--------------------------------------------><----> * | \ | / * version code vout[1] height * * - version = 1 * - code = 4 (vout[1] is not spent, and 0 non-zero bytes of bitvector follow) * - unspentness bitvector: as 0 non-zero bytes follow, it has length 0 * - vout[1]: 835800816115944e077fe7c803cfa57f29b36bf87c1d35 * * 8358: compact amount representation for 60000000000 (600 BTC) * * 00: special txout type pay-to-pubkey-hash * * 816115944e077fe7c803cfa57f29b36bf87c1d35: address uint160 * - height = 203998 * * * Example: 0109044086ef97d5790061b01caab50f1b8e9c50a5057eb43c2d9563a4eebbd123008c988f1a4a4de2161e0f50aac7f17e7f9555caa486af3b * <><><--><--------------------------------------------------><----------------------------------------------><----> * / \ \ | | / * version code unspentness vout[4] vout[16] height * * - version = 1 * - code = 9 (coinbase, neither vout[0] or vout[1] are unspent, * 2 (1, +1 because both bit 2 and bit 4 are unset) non-zero bitvector bytes follow) * - unspentness bitvector: bits 2 (0x04) and 14 (0x4000) are set, so vout[2+2] and vout[14+2] are unspent * - vout[4]: 86ef97d5790061b01caab50f1b8e9c50a5057eb43c2d9563a4ee * * 86ef97d579: compact amount representation for 234925952 (2.35 BTC) * * 00: special txout type pay-to-pubkey-hash * * 61b01caab50f1b8e9c50a5057eb43c2d9563a4ee: address uint160 * - vout[16]: bbd123008c988f1a4a4de2161e0f50aac7f17e7f9555caa4 * * bbd123: compact amount representation for 110397 (0.001 BTC) * * 00: special txout type pay-to-pubkey-hash * * 8c988f1a4a4de2161e0f50aac7f17e7f9555caa4: address uint160 * - height = 120891 */ class CCoins { public: // whether transaction is a coinbase bool fCoinBase; // unspent transaction outputs; spent outputs are .IsNull(); spent outputs at the end of the array are dropped std::vector<CTxOut> vout; // at which height this transaction was included in the active block chain int nHeight; // version of the CTransaction; accesses to this value should probably check for nHeight as well, // as new tx version will probably only be introduced at certain heights int nVersion; // construct a CCoins from a CTransaction, at a given height CCoins(const CTransaction &tx, int nHeightIn) : fCoinBase(tx.IsCoinBase()), vout(tx.vout), nHeight(nHeightIn), nVersion(tx.nVersion) { } // empty constructor CCoins() : fCoinBase(false), vout(0), nHeight(0), nVersion(0) { } // remove spent outputs at the end of vout void Cleanup() { while (vout.size() > 0 && vout.back().IsNull()) vout.pop_back(); if (vout.empty()) std::vector<CTxOut>().swap(vout); } void swap(CCoins &to) { std::swap(to.fCoinBase, fCoinBase); to.vout.swap(vout); std::swap(to.nHeight, nHeight); std::swap(to.nVersion, nVersion); } // equality test friend bool operator==(const CCoins &a, const CCoins &b) { return a.fCoinBase == b.fCoinBase && a.nHeight == b.nHeight && a.nVersion == b.nVersion && a.vout == b.vout; } friend bool operator!=(const CCoins &a, const CCoins &b) { return !(a == b); } // calculate number of bytes for the bitmask, and its number of non-zero bytes // each bit in the bitmask represents the availability of one output, but the // availabilities of the first two outputs are encoded separately void CalcMaskSize(unsigned int &nBytes, unsigned int &nNonzeroBytes) const { unsigned int nLastUsedByte = 0; for (unsigned int b = 0; 2+b*8 < vout.size(); b++) { bool fZero = true; for (unsigned int i = 0; i < 8 && 2+b*8+i < vout.size(); i++) { if (!vout[2+b*8+i].IsNull()) { fZero = false; continue; } } if (!fZero) { nLastUsedByte = b + 1; nNonzeroBytes++; } } nBytes += nLastUsedByte; } bool IsCoinBase() const { return fCoinBase; } unsigned int GetSerializeSize(int nType, int nVersion) const { unsigned int nSize = 0; unsigned int nMaskSize = 0, nMaskCode = 0; CalcMaskSize(nMaskSize, nMaskCode); bool fFirst = vout.size() > 0 && !vout[0].IsNull(); bool fSecond = vout.size() > 1 && !vout[1].IsNull(); assert(fFirst || fSecond || nMaskCode); unsigned int nCode = 8*(nMaskCode - (fFirst || fSecond ? 0 : 1)) + (fCoinBase ? 1 : 0) + (fFirst ? 2 : 0) + (fSecond ? 4 : 0); // version nSize += ::GetSerializeSize(VARINT(this->nVersion), nType, nVersion); // size of header code nSize += ::GetSerializeSize(VARINT(nCode), nType, nVersion); // spentness bitmask nSize += nMaskSize; // txouts themself for (unsigned int i = 0; i < vout.size(); i++) if (!vout[i].IsNull()) nSize += ::GetSerializeSize(CTxOutCompressor(REF(vout[i])), nType, nVersion); // height nSize += ::GetSerializeSize(VARINT(nHeight), nType, nVersion); return nSize; } template<typename Stream> void Serialize(Stream &s, int nType, int nVersion) const { unsigned int nMaskSize = 0, nMaskCode = 0; CalcMaskSize(nMaskSize, nMaskCode); bool fFirst = vout.size() > 0 && !vout[0].IsNull(); bool fSecond = vout.size() > 1 && !vout[1].IsNull(); assert(fFirst || fSecond || nMaskCode); unsigned int nCode = 8*(nMaskCode - (fFirst || fSecond ? 0 : 1)) + (fCoinBase ? 1 : 0) + (fFirst ? 2 : 0) + (fSecond ? 4 : 0); // version ::Serialize(s, VARINT(this->nVersion), nType, nVersion); // header code ::Serialize(s, VARINT(nCode), nType, nVersion); // spentness bitmask for (unsigned int b = 0; b<nMaskSize; b++) { unsigned char chAvail = 0; for (unsigned int i = 0; i < 8 && 2+b*8+i < vout.size(); i++) if (!vout[2+b*8+i].IsNull()) chAvail |= (1 << i); ::Serialize(s, chAvail, nType, nVersion); } // txouts themself for (unsigned int i = 0; i < vout.size(); i++) { if (!vout[i].IsNull()) ::Serialize(s, CTxOutCompressor(REF(vout[i])), nType, nVersion); } // coinbase height ::Serialize(s, VARINT(nHeight), nType, nVersion); } template<typename Stream> void Unserialize(Stream &s, int nType, int nVersion) { unsigned int nCode = 0; // version ::Unserialize(s, VARINT(this->nVersion), nType, nVersion); // header code ::Unserialize(s, VARINT(nCode), nType, nVersion); fCoinBase = nCode & 1; std::vector<bool> vAvail(2, false); vAvail[0] = nCode & 2; vAvail[1] = nCode & 4; unsigned int nMaskCode = (nCode / 8) + ((nCode & 6) != 0 ? 0 : 1); // spentness bitmask while (nMaskCode > 0) { unsigned char chAvail = 0; ::Unserialize(s, chAvail, nType, nVersion); for (unsigned int p = 0; p < 8; p++) { bool f = (chAvail & (1 << p)) != 0; vAvail.push_back(f); } if (chAvail != 0) nMaskCode--; } // txouts themself vout.assign(vAvail.size(), CTxOut()); for (unsigned int i = 0; i < vAvail.size(); i++) { if (vAvail[i]) ::Unserialize(s, REF(CTxOutCompressor(vout[i])), nType, nVersion); } // coinbase height ::Unserialize(s, VARINT(nHeight), nType, nVersion); Cleanup(); } // mark an outpoint spent, and construct undo information bool Spend(const COutPoint &out, CTxInUndo &undo) { if (out.n >= vout.size()) return false; if (vout[out.n].IsNull()) return false; undo = CTxInUndo(vout[out.n]); vout[out.n].SetNull(); Cleanup(); if (vout.size() == 0) { undo.nHeight = nHeight; undo.fCoinBase = fCoinBase; undo.nVersion = this->nVersion; } return true; } // mark a vout spent bool Spend(int nPos) { CTxInUndo undo; COutPoint out(0, nPos); return Spend(out, undo); } // check whether a particular output is still available bool IsAvailable(unsigned int nPos) const { return (nPos < vout.size() && !vout[nPos].IsNull()); } // check whether the entire CCoins is spent // note that only !IsPruned() CCoins can be serialized bool IsPruned() const { BOOST_FOREACH(const CTxOut &out, vout) if (!out.IsNull()) return false; return true; } }; /** Closure representing one script verification * Note that this stores references to the spending transaction */ class CScriptCheck { private: CScript scriptPubKey; const CTransaction *ptxTo; unsigned int nIn; unsigned int nFlags; int nHashType; public: CScriptCheck() {} CScriptCheck(const CCoins& txFromIn, const CTransaction& txToIn, unsigned int nInIn, unsigned int nFlagsIn, int nHashTypeIn) : scriptPubKey(txFromIn.vout[txToIn.vin[nInIn].prevout.n].scriptPubKey), ptxTo(&txToIn), nIn(nInIn), nFlags(nFlagsIn), nHashType(nHashTypeIn) { } bool operator()() const; void swap(CScriptCheck &check) { scriptPubKey.swap(check.scriptPubKey); std::swap(ptxTo, check.ptxTo); std::swap(nIn, check.nIn); std::swap(nFlags, check.nFlags); std::swap(nHashType, check.nHashType); } }; /** A transaction with a merkle branch linking it to the block chain. */ class CMerkleTx : public CTransaction { private: int GetDepthInMainChainINTERNAL(CBlockIndex* &pindexRet) const; public: uint256 hashBlock; std::vector<uint256> vMerkleBranch; int nIndex; // memory only mutable bool fMerkleVerified; CMerkleTx() { Init(); } CMerkleTx(const CTransaction& txIn) : CTransaction(txIn) { Init(); } void Init() { hashBlock = 0; nIndex = -1; fMerkleVerified = false; } IMPLEMENT_SERIALIZE ( nSerSize += SerReadWrite(s, *(CTransaction*)this, nType, nVersion, ser_action); nVersion = this->nVersion; READWRITE(hashBlock); READWRITE(vMerkleBranch); READWRITE(nIndex); ) int SetMerkleBranch(const CBlock* pblock=NULL); // Return depth of transaction in blockchain: // -1 : not in blockchain, and not in memory pool (conflicted transaction) // 0 : in memory pool, waiting to be included in a block // >=1 : this many blocks deep in the main chain int GetDepthInMainChain(CBlockIndex* &pindexRet) const; int GetDepthInMainChain() const { CBlockIndex *pindexRet; return GetDepthInMainChain(pindexRet); } bool IsInMainChain() const { CBlockIndex *pindexRet; return GetDepthInMainChainINTERNAL(pindexRet) > 0; } int GetBlocksToMaturity() const; bool AcceptToMemoryPool(bool fCheckInputs=true, bool fLimitFree=true); }; /** Data structure that represents a partial merkle tree. * * It respresents a subset of the txid's of a known block, in a way that * allows recovery of the list of txid's and the merkle root, in an * authenticated way. * * The encoding works as follows: we traverse the tree in depth-first order, * storing a bit for each traversed node, signifying whether the node is the * parent of at least one matched leaf txid (or a matched txid itself). In * case we are at the leaf level, or this bit is 0, its merkle node hash is * stored, and its children are not explorer further. Otherwise, no hash is * stored, but we recurse into both (or the only) child branch. During * decoding, the same depth-first traversal is performed, consuming bits and * hashes as they written during encoding. * * The serialization is fixed and provides a hard guarantee about the * encoded size: * * SIZE <= 10 + ceil(32.25*N) * * Where N represents the number of leaf nodes of the partial tree. N itself * is bounded by: * * N <= total_transactions * N <= 1 + matched_transactions*tree_height * * The serialization format: * - uint32 total_transactions (4 bytes) * - varint number of hashes (1-3 bytes) * - uint256[] hashes in depth-first order (<= 32*N bytes) * - varint number of bytes of flag bits (1-3 bytes) * - byte[] flag bits, packed per 8 in a byte, least significant bit first (<= 2*N-1 bits) * The size constraints follow from this. */ class CPartialMerkleTree { protected: // the total number of transactions in the block unsigned int nTransactions; // node-is-parent-of-matched-txid bits std::vector<bool> vBits; // txids and internal hashes std::vector<uint256> vHash; // flag set when encountering invalid data bool fBad; // helper function to efficiently calculate the number of nodes at given height in the merkle tree unsigned int CalcTreeWidth(int height) { return (nTransactions+(1 << height)-1) >> height; } // calculate the hash of a node in the merkle tree (at leaf level: the txid's themself) uint256 CalcHash(int height, unsigned int pos, const std::vector<uint256> &vTxid); // recursive function that traverses tree nodes, storing the data as bits and hashes void TraverseAndBuild(int height, unsigned int pos, const std::vector<uint256> &vTxid, const std::vector<bool> &vMatch); // recursive function that traverses tree nodes, consuming the bits and hashes produced by TraverseAndBuild. // it returns the hash of the respective node. uint256 TraverseAndExtract(int height, unsigned int pos, unsigned int &nBitsUsed, unsigned int &nHashUsed, std::vector<uint256> &vMatch); public: // serialization implementation IMPLEMENT_SERIALIZE( READWRITE(nTransactions); READWRITE(vHash); std::vector<unsigned char> vBytes; if (fRead) { READWRITE(vBytes); CPartialMerkleTree &us = *(const_cast<CPartialMerkleTree*>(this)); us.vBits.resize(vBytes.size() * 8); for (unsigned int p = 0; p < us.vBits.size(); p++) us.vBits[p] = (vBytes[p / 8] & (1 << (p % 8))) != 0; us.fBad = false; } else { vBytes.resize((vBits.size()+7)/8); for (unsigned int p = 0; p < vBits.size(); p++) vBytes[p / 8] |= vBits[p] << (p % 8); READWRITE(vBytes); } ) // Construct a partial merkle tree from a list of transaction id's, and a mask that selects a subset of them CPartialMerkleTree(const std::vector<uint256> &vTxid, const std::vector<bool> &vMatch); CPartialMerkleTree(); // extract the matching txid's represented by this partial merkle tree. // returns the merkle root, or 0 in case of failure uint256 ExtractMatches(std::vector<uint256> &vMatch); }; /** Nodes collect new transactions into a block, hash them into a hash tree, * and scan through nonce values to make the block's hash satisfy proof-of-work * requirements. When they solve the proof-of-work, they broadcast the block * to everyone and the block is added to the block chain. The first transaction * in the block is a special one that creates a new coin owned by the creator * of the block. */ class CBlockHeader { public: // header static const int CURRENT_VERSION=2; int nVersion; uint256 hashPrevBlock; uint256 hashMerkleRoot; unsigned int nTime; unsigned int nBits; unsigned int nNonce; CBlockHeader() { SetNull(); } IMPLEMENT_SERIALIZE ( READWRITE(this->nVersion); nVersion = this->nVersion; READWRITE(hashPrevBlock); READWRITE(hashMerkleRoot); READWRITE(nTime); READWRITE(nBits); READWRITE(nNonce); ) void SetNull() { nVersion = CBlockHeader::CURRENT_VERSION; hashPrevBlock = 0; hashMerkleRoot = 0; nTime = 0; nBits = 0; nNonce = 0; } bool IsNull() const { return (nBits == 0); } uint256 GetHash() const { return Hash(BEGIN(nVersion), END(nNonce)); } int64 GetBlockTime() const { return (int64)nTime; } void UpdateTime(const CBlockIndex* pindexPrev); }; class CBlock : public CBlockHeader { public: // network and disk std::vector<CTransaction> vtx; // memory only mutable std::vector<uint256> vMerkleTree; CBlock() { SetNull(); } CBlock(const CBlockHeader &header) { SetNull(); *((CBlockHeader*)this) = header; } IMPLEMENT_SERIALIZE ( READWRITE(*(CBlockHeader*)this); READWRITE(vtx); ) void SetNull() { CBlockHeader::SetNull(); vtx.clear(); vMerkleTree.clear(); } uint256 GetPoWHash() const { uint256 thash; scrypt_1024_1_1_256(BEGIN(nVersion), BEGIN(thash)); return thash; } CBlockHeader GetBlockHeader() const { CBlockHeader block; block.nVersion = nVersion; block.hashPrevBlock = hashPrevBlock; block.hashMerkleRoot = hashMerkleRoot; block.nTime = nTime; block.nBits = nBits; block.nNonce = nNonce; return block; } uint256 BuildMerkleTree() const { vMerkleTree.clear(); BOOST_FOREACH(const CTransaction& tx, vtx) vMerkleTree.push_back(tx.GetHash()); int j = 0; for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2) { for (int i = 0; i < nSize; i += 2) { int i2 = std::min(i+1, nSize-1); vMerkleTree.push_back(Hash(BEGIN(vMerkleTree[j+i]), END(vMerkleTree[j+i]), BEGIN(vMerkleTree[j+i2]), END(vMerkleTree[j+i2]))); } j += nSize; } return (vMerkleTree.empty() ? 0 : vMerkleTree.back()); } const uint256 &GetTxHash(unsigned int nIndex) const { assert(vMerkleTree.size() > 0); // BuildMerkleTree must have been called first assert(nIndex < vtx.size()); return vMerkleTree[nIndex]; } std::vector<uint256> GetMerkleBranch(int nIndex) const { if (vMerkleTree.empty()) BuildMerkleTree(); std::vector<uint256> vMerkleBranch; int j = 0; for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2) { int i = std::min(nIndex^1, nSize-1); vMerkleBranch.push_back(vMerkleTree[j+i]); nIndex >>= 1; j += nSize; } return vMerkleBranch; } static uint256 CheckMerkleBranch(uint256 hash, const std::vector<uint256>& vMerkleBranch, int nIndex) { if (nIndex == -1) return 0; BOOST_FOREACH(const uint256& otherside, vMerkleBranch) { if (nIndex & 1) hash = Hash(BEGIN(otherside), END(otherside), BEGIN(hash), END(hash)); else hash = Hash(BEGIN(hash), END(hash), BEGIN(otherside), END(otherside)); nIndex >>= 1; } return hash; } bool WriteToDisk(CDiskBlockPos &pos) { // Open history file to append CAutoFile fileout = CAutoFile(OpenBlockFile(pos), SER_DISK, CLIENT_VERSION); if (!fileout) return error("CBlock::WriteToDisk() : OpenBlockFile failed"); // Write index header unsigned int nSize = fileout.GetSerializeSize(*this); fileout << FLATDATA(pchMessageStart) << nSize; // Write block long fileOutPos = ftell(fileout); if (fileOutPos < 0) return error("CBlock::WriteToDisk() : ftell failed"); pos.nPos = (unsigned int)fileOutPos; fileout << *this; // Flush stdio buffers and commit to disk before returning fflush(fileout); if (!IsInitialBlockDownload()) FileCommit(fileout); return true; } bool ReadFromDisk(const CDiskBlockPos &pos) { SetNull(); // Open history file to read CAutoFile filein = CAutoFile(OpenBlockFile(pos, true), SER_DISK, CLIENT_VERSION); if (!filein) return error("CBlock::ReadFromDisk() : OpenBlockFile failed"); // Read block try { filein >> *this; } catch (std::exception &e) { return error("%s() : deserialize or I/O error", __PRETTY_FUNCTION__); } // Check the header if (!CheckProofOfWork(GetPoWHash(), nBits)) return error("CBlock::ReadFromDisk() : errors in block header"); return true; } void print() const { printf("CBlock(hash=%s, input=%s, PoW=%s, ver=%d, hashPrevBlock=%s, hashMerkleRoot=%s, nTime=%u, nBits=%08x, nNonce=%u, vtx=%"PRIszu")\n", GetHash().ToString().c_str(), HexStr(BEGIN(nVersion),BEGIN(nVersion)+80,false).c_str(), GetPoWHash().ToString().c_str(), nVersion, hashPrevBlock.ToString().c_str(), hashMerkleRoot.ToString().c_str(), nTime, nBits, nNonce, vtx.size()); for (unsigned int i = 0; i < vtx.size(); i++) { printf(" "); vtx[i].print(); } printf(" vMerkleTree: "); for (unsigned int i = 0; i < vMerkleTree.size(); i++) printf("%s ", vMerkleTree[i].ToString().c_str()); printf("\n"); } /** Undo the effects of this block (with given index) on the UTXO set represented by coins. * In case pfClean is provided, operation will try to be tolerant about errors, and *pfClean * will be true if no problems were found. Otherwise, the return value will be false in case * of problems. Note that in any case, coins may be modified. */ bool DisconnectBlock(CValidationState &state, CBlockIndex *pindex, CCoinsViewCache &coins, bool *pfClean = NULL); // Apply the effects of this block (with given index) on the UTXO set represented by coins bool ConnectBlock(CValidationState &state, CBlockIndex *pindex, CCoinsViewCache &coins, bool fJustCheck=false); // Read a block from disk bool ReadFromDisk(const CBlockIndex* pindex); // Add this block to the block index, and if necessary, switch the active block chain to this bool AddToBlockIndex(CValidationState &state, const CDiskBlockPos &pos); // Context-independent validity checks bool CheckBlock(CValidationState &state, bool fCheckPOW=true, bool fCheckMerkleRoot=true) const; // Store block on disk // if dbp is provided, the file is known to already reside on disk bool AcceptBlock(CValidationState &state, CDiskBlockPos *dbp = NULL); }; class CBlockFileInfo { public: unsigned int nBlocks; // number of blocks stored in file unsigned int nSize; // number of used bytes of block file unsigned int nUndoSize; // number of used bytes in the undo file unsigned int nHeightFirst; // lowest height of block in file unsigned int nHeightLast; // highest height of block in file uint64 nTimeFirst; // earliest time of block in file uint64 nTimeLast; // latest time of block in file IMPLEMENT_SERIALIZE( READWRITE(VARINT(nBlocks)); READWRITE(VARINT(nSize)); READWRITE(VARINT(nUndoSize)); READWRITE(VARINT(nHeightFirst)); READWRITE(VARINT(nHeightLast)); READWRITE(VARINT(nTimeFirst)); READWRITE(VARINT(nTimeLast)); ) void SetNull() { nBlocks = 0; nSize = 0; nUndoSize = 0; nHeightFirst = 0; nHeightLast = 0; nTimeFirst = 0; nTimeLast = 0; } CBlockFileInfo() { SetNull(); } std::string ToString() const { return strprintf("CBlockFileInfo(blocks=%u, size=%u, heights=%u...%u, time=%s...%s)", nBlocks, nSize, nHeightFirst, nHeightLast, DateTimeStrFormat("%Y-%m-%d", nTimeFirst).c_str(), DateTimeStrFormat("%Y-%m-%d", nTimeLast).c_str()); } // update statistics (does not update nSize) void AddBlock(unsigned int nHeightIn, uint64 nTimeIn) { if (nBlocks==0 || nHeightFirst > nHeightIn) nHeightFirst = nHeightIn; if (nBlocks==0 || nTimeFirst > nTimeIn) nTimeFirst = nTimeIn; nBlocks++; if (nHeightIn > nHeightFirst) nHeightLast = nHeightIn; if (nTimeIn > nTimeLast) nTimeLast = nTimeIn; } }; extern CCriticalSection cs_LastBlockFile; extern CBlockFileInfo infoLastBlockFile; extern int nLastBlockFile; enum BlockStatus { BLOCK_VALID_UNKNOWN = 0, BLOCK_VALID_HEADER = 1, // parsed, version ok, hash satisfies claimed PoW, 1 <= vtx count <= max, timestamp not in future BLOCK_VALID_TREE = 2, // parent found, difficulty matches, timestamp >= median previous, checkpoint BLOCK_VALID_TRANSACTIONS = 3, // only first tx is coinbase, 2 <= coinbase input script length <= 100, transactions valid, no duplicate txids, sigops, size, merkle root BLOCK_VALID_CHAIN = 4, // outputs do not overspend inputs, no double spends, coinbase output ok, immature coinbase spends, BIP30 BLOCK_VALID_SCRIPTS = 5, // scripts/signatures ok BLOCK_VALID_MASK = 7, BLOCK_HAVE_DATA = 8, // full block available in blk*.dat BLOCK_HAVE_UNDO = 16, // undo data available in rev*.dat BLOCK_HAVE_MASK = 24, BLOCK_FAILED_VALID = 32, // stage after last reached validness failed BLOCK_FAILED_CHILD = 64, // descends from failed block BLOCK_FAILED_MASK = 96 }; /** The block chain is a tree shaped structure starting with the * genesis block at the root, with each block potentially having multiple * candidates to be the next block. pprev and pnext link a path through the * main/longest chain. A blockindex may have multiple pprev pointing back * to it, but pnext will only point forward to the longest branch, or will * be null if the block is not part of the longest chain. */ class CBlockIndex { public: // pointer to the hash of the block, if any. memory is owned by this CBlockIndex const uint256* phashBlock; // pointer to the index of the predecessor of this block CBlockIndex* pprev; // (memory only) pointer to the index of the *active* successor of this block CBlockIndex* pnext; // height of the entry in the chain. The genesis block has height 0 int nHeight; // Which # file this block is stored in (blk?????.dat) int nFile; // Byte offset within blk?????.dat where this block's data is stored unsigned int nDataPos; // Byte offset within rev?????.dat where this block's undo data is stored unsigned int nUndoPos; // (memory only) Total amount of work (expected number of hashes) in the chain up to and including this block uint256 nChainWork; // Number of transactions in this block. // Note: in a potential headers-first mode, this number cannot be relied upon unsigned int nTx; // (memory only) Number of transactions in the chain up to and including this block unsigned int nChainTx; // change to 64-bit type when necessary; won't happen before 2030 // Verification status of this block. See enum BlockStatus unsigned int nStatus; // block header int nVersion; uint256 hashMerkleRoot; unsigned int nTime; unsigned int nBits; unsigned int nNonce; CBlockIndex() { phashBlock = NULL; pprev = NULL; pnext = NULL; nHeight = 0; nFile = 0; nDataPos = 0; nUndoPos = 0; nChainWork = 0; nTx = 0; nChainTx = 0; nStatus = 0; nVersion = 0; hashMerkleRoot = 0; nTime = 0; nBits = 0; nNonce = 0; } CBlockIndex(CBlockHeader& block) { phashBlock = NULL; pprev = NULL; pnext = NULL; nHeight = 0; nFile = 0; nDataPos = 0; nUndoPos = 0; nChainWork = 0; nTx = 0; nChainTx = 0; nStatus = 0; nVersion = block.nVersion; hashMerkleRoot = block.hashMerkleRoot; nTime = block.nTime; nBits = block.nBits; nNonce = block.nNonce; } CDiskBlockPos GetBlockPos() const { CDiskBlockPos ret; if (nStatus & BLOCK_HAVE_DATA) { ret.nFile = nFile; ret.nPos = nDataPos; } return ret; } CDiskBlockPos GetUndoPos() const { CDiskBlockPos ret; if (nStatus & BLOCK_HAVE_UNDO) { ret.nFile = nFile; ret.nPos = nUndoPos; } return ret; } CBlockHeader GetBlockHeader() const { CBlockHeader block; block.nVersion = nVersion; if (pprev) block.hashPrevBlock = pprev->GetBlockHash(); block.hashMerkleRoot = hashMerkleRoot; block.nTime = nTime; block.nBits = nBits; block.nNonce = nNonce; return block; } uint256 GetBlockHash() const { return *phashBlock; } int64 GetBlockTime() const { return (int64)nTime; } CBigNum GetBlockWork() const { CBigNum bnTarget; bnTarget.SetCompact(nBits); if (bnTarget <= 0) return 0; return (CBigNum(1)<<256) / (bnTarget+1); } bool IsInMainChain() const { return (pnext || this == pindexBest); } bool CheckIndex() const { /** Scrypt is used for block proof-of-work, but for purposes of performance the index internally uses sha256. * This check was considered unneccessary given the other safeguards like the genesis and checkpoints. */ return true; // return CheckProofOfWork(GetBlockHash(), nBits); } enum { nMedianTimeSpan=11 }; int64 GetMedianTimePast() const { int64 pmedian[nMedianTimeSpan]; int64* pbegin = &pmedian[nMedianTimeSpan]; int64* pend = &pmedian[nMedianTimeSpan]; const CBlockIndex* pindex = this; for (int i = 0; i < nMedianTimeSpan && pindex; i++, pindex = pindex->pprev) *(--pbegin) = pindex->GetBlockTime(); std::sort(pbegin, pend); return pbegin[(pend - pbegin)/2]; } int64 GetMedianTime() const { const CBlockIndex* pindex = this; for (int i = 0; i < nMedianTimeSpan/2; i++) { if (!pindex->pnext) return GetBlockTime(); pindex = pindex->pnext; } return pindex->GetMedianTimePast(); } /** * Returns true if there are nRequired or more blocks of minVersion or above * in the last nToCheck blocks, starting at pstart and going backwards. */ static bool IsSuperMajority(int minVersion, const CBlockIndex* pstart, unsigned int nRequired, unsigned int nToCheck); std::string ToString() const { return strprintf("CBlockIndex(pprev=%p, pnext=%p, nHeight=%d, merkle=%s, hashBlock=%s)", pprev, pnext, nHeight, hashMerkleRoot.ToString().c_str(), GetBlockHash().ToString().c_str()); } void print() const { printf("%s\n", ToString().c_str()); } }; struct CBlockIndexWorkComparator { bool operator()(CBlockIndex *pa, CBlockIndex *pb) { if (pa->nChainWork > pb->nChainWork) return false; if (pa->nChainWork < pb->nChainWork) return true; if (pa->GetBlockHash() < pb->GetBlockHash()) return false; if (pa->GetBlockHash() > pb->GetBlockHash()) return true; return false; // identical blocks } }; /** Used to marshal pointers into hashes for db storage. */ class CDiskBlockIndex : public CBlockIndex { public: uint256 hashPrev; CDiskBlockIndex() { hashPrev = 0; } explicit CDiskBlockIndex(CBlockIndex* pindex) : CBlockIndex(*pindex) { hashPrev = (pprev ? pprev->GetBlockHash() : 0); } IMPLEMENT_SERIALIZE ( if (!(nType & SER_GETHASH)) READWRITE(VARINT(nVersion)); READWRITE(VARINT(nHeight)); READWRITE(VARINT(nStatus)); READWRITE(VARINT(nTx)); if (nStatus & (BLOCK_HAVE_DATA | BLOCK_HAVE_UNDO)) READWRITE(VARINT(nFile)); if (nStatus & BLOCK_HAVE_DATA) READWRITE(VARINT(nDataPos)); if (nStatus & BLOCK_HAVE_UNDO) READWRITE(VARINT(nUndoPos)); // block header READWRITE(this->nVersion); READWRITE(hashPrev); READWRITE(hashMerkleRoot); READWRITE(nTime); READWRITE(nBits); READWRITE(nNonce); ) uint256 GetBlockHash() const { CBlockHeader block; block.nVersion = nVersion; block.hashPrevBlock = hashPrev; block.hashMerkleRoot = hashMerkleRoot; block.nTime = nTime; block.nBits = nBits; block.nNonce = nNonce; return block.GetHash(); } std::string ToString() const { std::string str = "CDiskBlockIndex("; str += CBlockIndex::ToString(); str += strprintf("\n hashBlock=%s, hashPrev=%s)", GetBlockHash().ToString().c_str(), hashPrev.ToString().c_str()); return str; } void print() const { printf("%s\n", ToString().c_str()); } }; /** Capture information about block/transaction validation */ class CValidationState { private: enum mode_state { MODE_VALID, // everything ok MODE_INVALID, // network rule violation (DoS value may be set) MODE_ERROR, // run-time error } mode; int nDoS; bool corruptionPossible; public: CValidationState() : mode(MODE_VALID), nDoS(0), corruptionPossible(false) {} bool DoS(int level, bool ret = false, bool corruptionIn = false) { if (mode == MODE_ERROR) return ret; nDoS += level; mode = MODE_INVALID; corruptionPossible = corruptionIn; return ret; } bool Invalid(bool ret = false) { return DoS(0, ret); } bool Error() { mode = MODE_ERROR; return false; } bool Abort(const std::string &msg) { AbortNode(msg); return Error(); } bool IsValid() { return mode == MODE_VALID; } bool IsInvalid() { return mode == MODE_INVALID; } bool IsError() { return mode == MODE_ERROR; } bool IsInvalid(int &nDoSOut) { if (IsInvalid()) { nDoSOut = nDoS; return true; } return false; } bool CorruptionPossible() { return corruptionPossible; } }; /** Describes a place in the block chain to another node such that if the * other node doesn't have the same branch, it can find a recent common trunk. * The further back it is, the further before the fork it may be. */ class CBlockLocator { protected: std::vector<uint256> vHave; public: CBlockLocator() { } explicit CBlockLocator(const CBlockIndex* pindex) { Set(pindex); } explicit CBlockLocator(uint256 hashBlock) { std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock); if (mi != mapBlockIndex.end()) Set((*mi).second); } CBlockLocator(const std::vector<uint256>& vHaveIn) { vHave = vHaveIn; } IMPLEMENT_SERIALIZE ( if (!(nType & SER_GETHASH)) READWRITE(nVersion); READWRITE(vHave); ) void SetNull() { vHave.clear(); } bool IsNull() { return vHave.empty(); } void Set(const CBlockIndex* pindex) { vHave.clear(); int nStep = 1; while (pindex) { vHave.push_back(pindex->GetBlockHash()); // Exponentially larger steps back for (int i = 0; pindex && i < nStep; i++) pindex = pindex->pprev; if (vHave.size() > 10) nStep *= 2; } vHave.push_back(hashGenesisBlock); } int GetDistanceBack() { // Retrace how far back it was in the sender's branch int nDistance = 0; int nStep = 1; BOOST_FOREACH(const uint256& hash, vHave) { std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash); if (mi != mapBlockIndex.end()) { CBlockIndex* pindex = (*mi).second; if (pindex->IsInMainChain()) return nDistance; } nDistance += nStep; if (nDistance > 10) nStep *= 2; } return nDistance; } CBlockIndex* GetBlockIndex() { // Find the first block the caller has in the main chain BOOST_FOREACH(const uint256& hash, vHave) { std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash); if (mi != mapBlockIndex.end()) { CBlockIndex* pindex = (*mi).second; if (pindex->IsInMainChain()) return pindex; } } return pindexGenesisBlock; } uint256 GetBlockHash() { // Find the first block the caller has in the main chain BOOST_FOREACH(const uint256& hash, vHave) { std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash); if (mi != mapBlockIndex.end()) { CBlockIndex* pindex = (*mi).second; if (pindex->IsInMainChain()) return hash; } } return hashGenesisBlock; } int GetHeight() { CBlockIndex* pindex = GetBlockIndex(); if (!pindex) return 0; return pindex->nHeight; } }; class CTxMemPool { public: mutable CCriticalSection cs; std::map<uint256, CTransaction> mapTx; std::map<COutPoint, CInPoint> mapNextTx; bool accept(CValidationState &state, CTransaction &tx, bool fCheckInputs, bool fLimitFree, bool* pfMissingInputs, bool fRejectInsaneFee = false); bool addUnchecked(const uint256& hash, const CTransaction &tx); bool remove(const CTransaction &tx, bool fRecursive = false); bool removeConflicts(const CTransaction &tx); void clear(); void queryHashes(std::vector<uint256>& vtxid); void pruneSpent(const uint256& hash, CCoins &coins); unsigned long size() { LOCK(cs); return mapTx.size(); } bool exists(uint256 hash) { return (mapTx.count(hash) != 0); } CTransaction& lookup(uint256 hash) { return mapTx[hash]; } }; extern CTxMemPool mempool; struct CCoinsStats { int nHeight; uint256 hashBlock; uint64 nTransactions; uint64 nTransactionOutputs; uint64 nSerializedSize; uint256 hashSerialized; int64 nTotalAmount; CCoinsStats() : nHeight(0), hashBlock(0), nTransactions(0), nTransactionOutputs(0), nSerializedSize(0), hashSerialized(0), nTotalAmount(0) {} }; /** Abstract view on the open txout dataset. */ class CCoinsView { public: // Retrieve the CCoins (unspent transaction outputs) for a given txid virtual bool GetCoins(const uint256 &txid, CCoins &coins); // Modify the CCoins for a given txid virtual bool SetCoins(const uint256 &txid, const CCoins &coins); // Just check whether we have data for a given txid. // This may (but cannot always) return true for fully spent transactions virtual bool HaveCoins(const uint256 &txid); // Retrieve the block index whose state this CCoinsView currently represents virtual CBlockIndex *GetBestBlock(); // Modify the currently active block index virtual bool SetBestBlock(CBlockIndex *pindex); // Do a bulk modification (multiple SetCoins + one SetBestBlock) virtual bool BatchWrite(const std::map<uint256, CCoins> &mapCoins, CBlockIndex *pindex); // Calculate statistics about the unspent transaction output set virtual bool GetStats(CCoinsStats &stats); // As we use CCoinsViews polymorphically, have a virtual destructor virtual ~CCoinsView() {} }; /** CCoinsView backed by another CCoinsView */ class CCoinsViewBacked : public CCoinsView { protected: CCoinsView *base; public: CCoinsViewBacked(CCoinsView &viewIn); bool GetCoins(const uint256 &txid, CCoins &coins); bool SetCoins(const uint256 &txid, const CCoins &coins); bool HaveCoins(const uint256 &txid); CBlockIndex *GetBestBlock(); bool SetBestBlock(CBlockIndex *pindex); void SetBackend(CCoinsView &viewIn); bool BatchWrite(const std::map<uint256, CCoins> &mapCoins, CBlockIndex *pindex); bool GetStats(CCoinsStats &stats); }; /** CCoinsView that adds a memory cache for transactions to another CCoinsView */ class CCoinsViewCache : public CCoinsViewBacked { protected: CBlockIndex *pindexTip; std::map<uint256,CCoins> cacheCoins; public: CCoinsViewCache(CCoinsView &baseIn, bool fDummy = false); // Standard CCoinsView methods bool GetCoins(const uint256 &txid, CCoins &coins); bool SetCoins(const uint256 &txid, const CCoins &coins); bool HaveCoins(const uint256 &txid); CBlockIndex *GetBestBlock(); bool SetBestBlock(CBlockIndex *pindex); bool BatchWrite(const std::map<uint256, CCoins> &mapCoins, CBlockIndex *pindex); // Return a modifiable reference to a CCoins. Check HaveCoins first. // Many methods explicitly require a CCoinsViewCache because of this method, to reduce // copying. CCoins &GetCoins(const uint256 &txid); // Push the modifications applied to this cache to its base. // Failure to call this method before destruction will cause the changes to be forgotten. bool Flush(); // Calculate the size of the cache (in number of transactions) unsigned int GetCacheSize(); private: std::map<uint256,CCoins>::iterator FetchCoins(const uint256 &txid); }; /** CCoinsView that brings transactions from a memorypool into view. It does not check for spendings by memory pool transactions. */ class CCoinsViewMemPool : public CCoinsViewBacked { protected: CTxMemPool &mempool; public: CCoinsViewMemPool(CCoinsView &baseIn, CTxMemPool &mempoolIn); bool GetCoins(const uint256 &txid, CCoins &coins); bool HaveCoins(const uint256 &txid); }; /** Global variable that points to the active CCoinsView (protected by cs_main) */ extern CCoinsViewCache *pcoinsTip; /** Global variable that points to the active block tree (protected by cs_main) */ extern CBlockTreeDB *pblocktree; struct CBlockTemplate { CBlock block; std::vector<int64_t> vTxFees; std::vector<int64_t> vTxSigOps; }; #if defined(_M_IX86) || defined(__i386__) || defined(__i386) || defined(_M_X64) || defined(__x86_64__) || defined(_M_AMD64) extern unsigned int cpuid_edx; #endif /** Used to relay blocks as header + vector<merkle branch> * to filtered nodes. */ class CMerkleBlock { public: // Public only for unit testing CBlockHeader header; CPartialMerkleTree txn; public: // Public only for unit testing and relay testing // (not relayed) std::vector<std::pair<unsigned int, uint256> > vMatchedTxn; // Create from a CBlock, filtering transactions according to filter // Note that this will call IsRelevantAndUpdate on the filter for each transaction, // thus the filter will likely be modified. CMerkleBlock(const CBlock& block, CBloomFilter& filter); IMPLEMENT_SERIALIZE ( READWRITE(header); READWRITE(txn); ) }; #endif
[ "cryptotnm@outlook.com" ]
cryptotnm@outlook.com
00f9b45fc92ef036565877ab13a9a618ebeec0fa
575513a397d4c8b1a69d3a545791d35928e72d48
/lab9-part3.cpp
f1748760059ffd2a276163daf8bd228b7039f2b0
[]
no_license
HyunlangBan/git_cpp
4a8a46c162ab93b93bdbfa5f0cf0904533cfff18
88026941ef95acaa2d0e675008812b8c828e92d9
refs/heads/master
2020-04-09T03:53:29.860123
2019-01-06T21:01:07
2019-01-06T21:01:07
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,522
cpp
//============================================================================== // Filename : lab9-part3.cpp // Author : Hyunlang Ban // Date : 06-December-2018 // Description : Implement a partially working Todo List application in Curses. // Collaborators: Samuel Page //============================================================================== #include <iostream> #include <cstdlib> using namespace std; // Different platforms need different header files. Here's how, using // most C++ compilers, you can include different libraries for different // operating systems. #ifdef _WIN32 #include <curses.h> #elif __APPLE__ #include <ncurses.h> #elif __linux #include <ncurses.h> #endif struct Border { int maxWidth, maxHeight; char borderChar; }; struct ToDoList { string todo; bool done; }; const static char BORDER_CHAR = char(219); const int MAX_INPUT_SIZE = 100; const int MAX_TODOS = 500; void drawBorder(Border &border); void initializeBoard(Border &border); void clearWindow(); void drawMenu(Border &border, ToDoList &todoItems, int &size); void drawToDoList(ToDoList &todoItems, int &size); int charArrayToInt(char numAsString[]); /** * Displays a prompt for the user to enter their initials. * * @return The exit status. */ int main() { int size = 0; Border border; ToDoList todoItems[MAX_TODOS]; border.borderChar = BORDER_CHAR; initializeBoard(border); drawMenu(border, todoItems[size], size); return 0; } /** * Initialize board. * * @param border A Border instance. */ void initializeBoard(Border &border) { // initscr() is a function defined by ncurses/pdcurses. It initializes // the screen. initscr(); // Says to not wait for the user to enter a key when getch is called -- just // start processing. nodelay(stdscr, true); // Allows the user to touch all keys, including F1-12, up, down, etc. keypad(stdscr, true); // If user presses a key, it won't be written to the screen. noecho(); // Removes the cursor. curs_set(0); // Get the max width and height. getmaxyx(stdscr, border.maxHeight, border.maxWidth); // Draws the border. drawBorder(border); } /** * Draw a border. * * @param border A Border instance. */ void drawBorder(Border &border) { // Draw the the top border. for (int i = 0; i < border.maxWidth; i++) { move(0, i); addch(border.borderChar); } // Draw the bottom border. for (int i = 0; i < border.maxWidth; i++) { move(border.maxHeight - 2, i); addch(border.borderChar); } } /** * remove all characters from the screen. * */ void clearWindow() { clear(); } /** * Draw a menu. * * @param border A Border instance. * @param todoItems A ToDoList instance. * @param size the size in main memory */ void drawMenu(Border &border, ToDoList &todoItems, int &size) { // This is a character array -- it's like a string. It only holds 3 // characters, plus a '\0' -- the end of string character. char userInput[MAX_INPUT_SIZE + 1]; do { clear(); drawBorder(border); // Initialize ncurse stuff. initscr(); nodelay(stdscr, false); // Wait for user input. keypad(stdscr, true); // Interpret all keyboard keys. curs_set(1); // Display the cursor. echo(); // Makes user inputs display on the screen. // Prompt the user. mvprintw(border.maxHeight - 3, 10, "Menu -- [a]dd todo; [m]ark item as done; [q]uit: "); // Read in only three characters. getnstr(userInput, 1); //if user enter a(add): if (userInput[0] == 'a') { //clear(); move(border.maxHeight - 4, 10); clrtoeol(); //print "you selected to add a todo" mvprintw(border.maxHeight - 4, 10, "Enter todo item: "); getnstr(userInput, MAX_INPUT_SIZE); todoItems.todo = string(userInput); move(border.maxHeight - 4, 10); clrtoeol(); mvprintw(border.maxHeight - 4, 10, "You added: %s", todoItems.todo.c_str()); drawToDoList(todoItems, size); //mark as undone todoItems.done = false; //drawtodolist size++; //else if user enter m(mark as done) } else if (userInput[0] == 'm') { move(border.maxHeight - 4, 10); clrtoeol(); mvprintw(border.maxHeight - 4, 10, "Please enter the index of the item to mark done: "); getnstr(userInput, MAX_INPUT_SIZE); todoItems.done = true; move(border.maxHeight - 4, 10); clrtoeol(); mvprintw(border.maxHeight - 4, 10, "%s is marked as done", todoItems.todo.c_str()); //else if user enter q(quit) } else if (userInput[0] == 'q') { //print "your selected to quit" mvprintw(border.maxHeight - 4, 10, "You selected to quit."); //else: } else { // print "invalid option" mvprintw(7, 10, "invalid option"); } getch(); // wait for user's input } while (userInput[0] != 'q'); // Don't exit until the user presses another key. endwin(); } void drawToDoList(ToDoList &todoItems, int &size) { } int charArrayToInt(char numAsString[]) { return 0; }
[ "gusfkd2827@gmail.com" ]
gusfkd2827@gmail.com
cf9f17b5f979ef67d97aafacad6c468ee4897c14
060d69c63f19b4ffb1ee5d758352f69e00edaa2c
/app/src/main/cpp/PacketQueue.cpp
2793f7e564b7b9f18f41c2bdfaadf332d656a02a
[]
no_license
linhaosheng/VideoPlayProject
8f4716ff90d5e3db94f6cef557758693d5a2ee1d
377d72c365052e8522eaf8c2854b1c85145e7fd4
refs/heads/master
2020-04-01T01:07:02.191810
2018-10-22T05:58:01
2018-10-22T05:58:01
152,726,741
1
0
null
null
null
null
UTF-8
C++
false
false
3,396
cpp
// // Created by Administrator on 2018/10/16. // #include "local/PacketQueue.h" #include "local/androidLog.h" //初始化队列 void packet_queue_init(PacketQueue *packetQueue) { memset(packetQueue, 0, sizeof(PacketQueue)); pthread_mutex_init(&packetQueue->mutex, NULL); pthread_cond_init(&packetQueue->cond, NULL); } //清除队列 void packet_queue_clear(PacketQueue *packetQueue) { pthread_mutex_lock(&packetQueue->mutex); AVPacketList *tmp = NULL; tmp = packetQueue->first_pkt; while (packetQueue->size > 0 && tmp != NULL) { packetQueue->first_pkt = tmp->next; if (tmp->pkt.data) { av_free(&tmp->pkt); tmp->pkt.data = NULL; } av_free(tmp); tmp = packetQueue->first_pkt; packetQueue->nb_packets--; } packetQueue->nb_packets = 0; packetQueue->first_pkt = NULL; packetQueue->last_pkt = NULL; packetQueue->size = 0; pthread_mutex_unlock(&packetQueue->mutex); } //销毁队列 void packet_queue_destory(PacketQueue *packetQueue) { pthread_mutex_lock(&packetQueue->mutex); AVPacketList *temp = NULL; temp = packetQueue->first_pkt; while (packetQueue->nb_packets > 0 && temp != NULL) { packetQueue->first_pkt = temp->next; av_free(temp); temp = packetQueue->first_pkt; packetQueue->nb_packets--; } packetQueue->first_pkt = NULL; packetQueue->last_pkt = NULL; packetQueue->nb_packets = 0; packetQueue->size = 0; if (&packetQueue->mutex) { pthread_mutex_destroy(&packetQueue->mutex); } if (&packetQueue->cond) { pthread_cond_destroy(&packetQueue->cond); } pthread_mutex_unlock(&packetQueue->mutex); } //数据进队列 int packet_queue_put(PacketQueue *packetQueue, AVPacket *pkt) { AVPacketList *packetList; if (av_dup_packet(pkt) < 0) { return -1; } packetList = (AVPacketList *) av_malloc(sizeof(AVPacketList)); if (packetList == NULL) { return -1; } packetList->pkt = *pkt; packetList->next = NULL; pthread_mutex_lock(&packetQueue->mutex); if (packetQueue->last_pkt == NULL) { packetQueue->first_pkt = packetList; } else { packetQueue->last_pkt->next = packetList; } packetQueue->last_pkt = packetList; packetQueue->nb_packets++; packetQueue->size += packetList->pkt.size; pthread_cond_signal(&packetQueue->cond); pthread_mutex_unlock(&packetQueue->mutex); return 0; } //数据出队列 int packet_queue_get(PacketQueue *packetQueue, AVPacket *pkt, int block) { AVPacketList *packetList; int ret; pthread_mutex_lock(&packetQueue->mutex); for (;;) { packetList = packetQueue->first_pkt; if (packetList != NULL) { packetQueue->first_pkt = packetList->next; if (!packetQueue->first_pkt){ packetQueue->last_pkt = NULL; } packetQueue->nb_packets--; packetQueue->size -= packetList->pkt.size; *pkt = packetList->pkt; free(packetList); ret = 1; break; } else{ ret = 0; break; } } pthread_mutex_unlock(&packetQueue->mutex); return ret; }
[ "lin1282634597@163.com" ]
lin1282634597@163.com
9fbb7b48df97b6af826111685f6daeba5893e2c5
bbcda48854d6890ad029d5973e011d4784d248d2
/trunk/win/Source/Includes/QtIncludes/src/3rdparty/clucene/src/CLucene/util/VoidList.h
a40a5e3c1d588b1cd540d803593e6a9ae04677f6
[ "LGPL-2.1-only", "Apache-2.0", "GPL-1.0-or-later", "LGPL-2.0-or-later", "LGPL-2.1-or-later", "LicenseRef-scancode-unknown-license-reference", "MIT", "curl", "BSD-3-Clause", "BSL-1.0", "LicenseRef-scancode-public-domain", "Zlib", "LicenseRef-scancode-unknown", "MS-LPL" ]
permissive
dyzmapl/BumpTop
9c396f876e6a9ace1099b3b32e45612a388943ff
1329ea41411c7368516b942d19add694af3d602f
refs/heads/master
2020-12-20T22:42:55.100473
2020-01-25T21:00:08
2020-01-25T21:00:08
236,229,087
0
0
Apache-2.0
2020-01-25T20:58:59
2020-01-25T20:58:58
null
UTF-8
C++
false
false
4,617
h
/*------------------------------------------------------------------------------ * Copyright (C) 2003-2006 Ben van Klinken and the CLucene Team * * Distributable under the terms of either the Apache License (Version 2.0) or * the GNU Lesser General Public License, as specified in the COPYING file. ------------------------------------------------------------------------------*/ #ifndef _lucene_util_VoidList_ #define _lucene_util_VoidList_ #if defined(_LUCENE_PRAGMA_ONCE) # pragma once #endif #include "Equators.h" CL_NS_DEF(util) /** * A template to encapsulate various list type classes * @internal */ template<typename _kt,typename _base,typename _valueDeletor> class __CLList:public _base,LUCENE_BASE { private: bool dv; typedef _base base; public: DEFINE_MUTEX(THIS_LOCK) typedef typename _base::const_iterator const_iterator; typedef typename _base::iterator iterator; virtual ~__CLList(){ clear(); } __CLList ( const bool deleteValue ): dv(deleteValue) { } void setDoDelete(bool val){ dv=val; } //sets array to the contents of this array. //array must be size+1, otherwise memory may be overwritten void toArray(_kt* into) const{ int i=0; for ( const_iterator itr=base::begin();itr!=base::end();itr++ ){ into[i] = *itr; i++; } into[i] = NULL; } void set(int32_t i, _kt val) { if ( dv ) _valueDeletor::doDelete((*this)[i]); (*this)[i] = val; } //todo: check this void delete_back(){ if ( base::size() > 0 ){ iterator itr = base::end(); if ( itr != base::begin()) itr --; _kt key = *itr; base::erase(itr); if ( dv ) _valueDeletor::doDelete(key); } } void delete_front(){ if ( base::size() > 0 ){ iterator itr = base::begin(); _kt key = *itr; base::erase(itr); if ( dv ) _valueDeletor::doDelete(key); } } void clear(){ if ( dv ){ iterator itr = base::begin(); while ( itr != base::end() ){ _valueDeletor::doDelete(*itr); ++itr; } } base::clear(); } void remove(int32_t i, bool dontDelete=false){ iterator itr=base::begin(); itr+=i; _kt key = *itr; base::erase( itr ); if ( dv && !dontDelete ) _valueDeletor::doDelete(key); } void remove(iterator itr, bool dontDelete=false){ _kt key = *itr; base::erase( itr ); if ( dv && !dontDelete ) _valueDeletor::doDelete(key); } }; //growable arrays of Objects (like a collection or list) //a list, so can contain duplicates //it grows in chunks... todo: check jlucene for initial size of array, and growfactors template<typename _kt, typename _valueDeletor=CL_NS(util)::Deletor::Dummy> class CLVector:public __CLList<_kt, CL_NS_STD(vector)<_kt> , _valueDeletor> { public: CLVector ( const bool deleteValue=true ): __CLList<_kt, CL_NS_STD(vector)<_kt> , _valueDeletor>(deleteValue) { } }; //An array-backed implementation of the List interface //a list, so can contain duplicates //*** a very simple list - use <valarray> //(This class is roughly equivalent to Vector, except that it is unsynchronized.) #define CLArrayList CLVector #define CLHashSet CLHashList //implementation of the List interface, provides access to the first and last list elements in O(1) //no comparator is required... and so can contain duplicates //a simple list with no comparator //*** a very simple list - use <list> #ifdef LUCENE_DISABLE_HASHING #define CLHashList CLSetList #else template<typename _kt, typename _Comparator=CL_NS(util)::Compare::TChar, typename _valueDeletor=CL_NS(util)::Deletor::Dummy> class CLHashList:public __CLList<_kt, CL_NS_HASHING(hash_set)<_kt,_Comparator> , _valueDeletor> { public: CLHashList ( const bool deleteValue=true ): __CLList<_kt, CL_NS_HASHING(hash_set)<_kt,_Comparator> , _valueDeletor>(deleteValue) { } }; #endif template<typename _kt, typename _valueDeletor=CL_NS(util)::Deletor::Dummy> class CLLinkedList:public __CLList<_kt, CL_NS_STD(list)<_kt> , _valueDeletor> { public: CLLinkedList ( const bool deleteValue=true ): __CLList<_kt, CL_NS_STD(list)<_kt> , _valueDeletor>(deleteValue) { } }; template<typename _kt, typename _Comparator=CL_NS(util)::Compare::TChar, typename _valueDeletor=CL_NS(util)::Deletor::Dummy> class CLSetList:public __CLList<_kt, CL_NS_STD(set)<_kt,_Comparator> , _valueDeletor> { public: CLSetList ( const bool deleteValue=true ): __CLList<_kt, CL_NS_STD(set)<_kt,_Comparator> , _valueDeletor>(deleteValue) { } }; CL_NS_END #endif
[ "anandx@google.com" ]
anandx@google.com
030e5e9c8fae8b4d5acb3d3bbee77aceb4db95b8
5456502f97627278cbd6e16d002d50f1de3da7bb
/net/dns/mojo_host_resolver_impl_unittest.cc
d2fa1155ed61337baaae591dc0e8adbc1e1b4cee
[ "BSD-3-Clause" ]
permissive
TrellixVulnTeam/Chromium_7C66
72d108a413909eb3bd36c73a6c2f98de1573b6e5
c8649ab2a0f5a747369ed50351209a42f59672ee
refs/heads/master
2023-03-16T12:51:40.231959
2017-12-20T10:38:26
2017-12-20T10:38:26
null
0
0
null
null
null
null
UTF-8
C++
false
false
9,382
cc
// Copyright 2015 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/dns/mojo_host_resolver_impl.h" #include <memory> #include <string> #include <utility> #include "base/run_loop.h" #include "base/time/time.h" #include "mojo/public/cpp/bindings/binding.h" #include "mojo/public/cpp/bindings/interface_request.h" #include "net/base/address_list.h" #include "net/base/net_errors.h" #include "net/dns/mock_host_resolver.h" #include "net/test/gtest_util.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" using net::test::IsError; using net::test::IsOk; namespace net { namespace { class TestRequestClient : public interfaces::HostResolverRequestClient { public: explicit TestRequestClient( mojo::InterfaceRequest<interfaces::HostResolverRequestClient> req) : done_(false), binding_(this, std::move(req)) { binding_.set_connection_error_handler(base::Bind( &TestRequestClient::OnConnectionError, base::Unretained(this))); } void WaitForResult(); void WaitForConnectionError(); int32_t error_; AddressList results_; private: // Overridden from interfaces::HostResolverRequestClient. void ReportResult(int32_t error, const AddressList& results) override; // Mojo error handler. void OnConnectionError(); bool done_; base::Closure run_loop_quit_closure_; base::Closure connection_error_quit_closure_; mojo::Binding<interfaces::HostResolverRequestClient> binding_; }; void TestRequestClient::WaitForResult() { if (done_) return; base::RunLoop run_loop; run_loop_quit_closure_ = run_loop.QuitClosure(); run_loop.Run(); ASSERT_TRUE(done_); } void TestRequestClient::WaitForConnectionError() { base::RunLoop run_loop; connection_error_quit_closure_ = run_loop.QuitClosure(); run_loop.Run(); } void TestRequestClient::ReportResult(int32_t error, const AddressList& results) { if (!run_loop_quit_closure_.is_null()) { run_loop_quit_closure_.Run(); } ASSERT_FALSE(done_); error_ = error; results_ = results; done_ = true; } void TestRequestClient::OnConnectionError() { if (!connection_error_quit_closure_.is_null()) connection_error_quit_closure_.Run(); } class CallbackMockHostResolver : public MockHostResolver { public: CallbackMockHostResolver() {} ~CallbackMockHostResolver() override {} // Set a callback to run whenever Resolve is called. Callback is cleared after // every run. void SetResolveCallback(base::Closure callback) { resolve_callback_ = callback; } // Overridden from MockHostResolver. int Resolve(const RequestInfo& info, RequestPriority priority, AddressList* addresses, const CompletionCallback& callback, std::unique_ptr<Request>* request, const NetLogWithSource& net_log) override; private: base::Closure resolve_callback_; }; int CallbackMockHostResolver::Resolve(const RequestInfo& info, RequestPriority priority, AddressList* addresses, const CompletionCallback& callback, std::unique_ptr<Request>* request, const NetLogWithSource& net_log) { int result = MockHostResolver::Resolve(info, priority, addresses, callback, request, net_log); if (!resolve_callback_.is_null()) { resolve_callback_.Run(); resolve_callback_.Reset(); } return result; } } // namespace class MojoHostResolverImplTest : public testing::Test { protected: void SetUp() override { mock_host_resolver_.rules()->AddRule("example.com", "1.2.3.4"); mock_host_resolver_.rules()->AddRule("chromium.org", "8.8.8.8"); mock_host_resolver_.rules()->AddSimulatedFailure("failure.fail"); resolver_service_.reset( new MojoHostResolverImpl(&mock_host_resolver_, NetLogWithSource())); } std::unique_ptr<HostResolver::RequestInfo> CreateRequest(const std::string& host, uint16_t port, bool is_my_ip_address) { std::unique_ptr<HostResolver::RequestInfo> request = base::MakeUnique<HostResolver::RequestInfo>(HostPortPair(host, port)); request->set_is_my_ip_address(is_my_ip_address); request->set_address_family(ADDRESS_FAMILY_IPV4); return request; } // Wait until the mock resolver has received |num| resolve requests. void WaitForRequests(size_t num) { while (mock_host_resolver_.num_resolve() < num) { base::RunLoop run_loop; mock_host_resolver_.SetResolveCallback(run_loop.QuitClosure()); run_loop.Run(); } } CallbackMockHostResolver mock_host_resolver_; std::unique_ptr<MojoHostResolverImpl> resolver_service_; }; TEST_F(MojoHostResolverImplTest, Resolve) { interfaces::HostResolverRequestClientPtr client_ptr; TestRequestClient client(mojo::GetProxy(&client_ptr)); resolver_service_->Resolve(CreateRequest("example.com", 80, false), std::move(client_ptr)); client.WaitForResult(); EXPECT_THAT(client.error_, IsOk()); AddressList& address_list = client.results_; EXPECT_EQ(1U, address_list.size()); EXPECT_EQ("1.2.3.4:80", address_list[0].ToString()); } TEST_F(MojoHostResolverImplTest, ResolveSynchronous) { interfaces::HostResolverRequestClientPtr client_ptr; TestRequestClient client(mojo::GetProxy(&client_ptr)); mock_host_resolver_.set_synchronous_mode(true); resolver_service_->Resolve(CreateRequest("example.com", 80, false), std::move(client_ptr)); client.WaitForResult(); EXPECT_THAT(client.error_, IsOk()); AddressList& address_list = client.results_; EXPECT_EQ(1U, address_list.size()); EXPECT_EQ("1.2.3.4:80", address_list[0].ToString()); } TEST_F(MojoHostResolverImplTest, ResolveMultiple) { interfaces::HostResolverRequestClientPtr client1_ptr; TestRequestClient client1(mojo::GetProxy(&client1_ptr)); interfaces::HostResolverRequestClientPtr client2_ptr; TestRequestClient client2(mojo::GetProxy(&client2_ptr)); mock_host_resolver_.set_ondemand_mode(true); resolver_service_->Resolve(CreateRequest("example.com", 80, false), std::move(client1_ptr)); resolver_service_->Resolve(CreateRequest("chromium.org", 80, false), std::move(client2_ptr)); WaitForRequests(2); mock_host_resolver_.ResolveAllPending(); client1.WaitForResult(); client2.WaitForResult(); EXPECT_THAT(client1.error_, IsOk()); AddressList& address_list1 = client1.results_; EXPECT_EQ(1U, address_list1.size()); EXPECT_EQ("1.2.3.4:80", address_list1[0].ToString()); EXPECT_THAT(client2.error_, IsOk()); AddressList& address_list2 = client2.results_; EXPECT_EQ(1U, address_list2.size()); EXPECT_EQ("8.8.8.8:80", address_list2[0].ToString()); } TEST_F(MojoHostResolverImplTest, ResolveDuplicate) { interfaces::HostResolverRequestClientPtr client1_ptr; TestRequestClient client1(mojo::GetProxy(&client1_ptr)); interfaces::HostResolverRequestClientPtr client2_ptr; TestRequestClient client2(mojo::GetProxy(&client2_ptr)); mock_host_resolver_.set_ondemand_mode(true); resolver_service_->Resolve(CreateRequest("example.com", 80, false), std::move(client1_ptr)); resolver_service_->Resolve(CreateRequest("example.com", 80, false), std::move(client2_ptr)); WaitForRequests(2); mock_host_resolver_.ResolveAllPending(); client1.WaitForResult(); client2.WaitForResult(); EXPECT_THAT(client1.error_, IsOk()); AddressList& address_list1 = client1.results_; EXPECT_EQ(1U, address_list1.size()); EXPECT_EQ("1.2.3.4:80", address_list1[0].ToString()); EXPECT_THAT(client2.error_, IsOk()); AddressList& address_list2 = client2.results_; EXPECT_EQ(1U, address_list2.size()); EXPECT_EQ("1.2.3.4:80", address_list2[0].ToString()); } TEST_F(MojoHostResolverImplTest, ResolveFailure) { interfaces::HostResolverRequestClientPtr client_ptr; TestRequestClient client(mojo::GetProxy(&client_ptr)); resolver_service_->Resolve(CreateRequest("failure.fail", 80, false), std::move(client_ptr)); client.WaitForResult(); EXPECT_THAT(client.error_, IsError(net::ERR_NAME_NOT_RESOLVED)); EXPECT_TRUE(client.results_.empty()); } TEST_F(MojoHostResolverImplTest, DestroyClient) { interfaces::HostResolverRequestClientPtr client_ptr; std::unique_ptr<TestRequestClient> client( new TestRequestClient(mojo::GetProxy(&client_ptr))); mock_host_resolver_.set_ondemand_mode(true); resolver_service_->Resolve(CreateRequest("example.com", 80, false), std::move(client_ptr)); WaitForRequests(1); client.reset(); base::RunLoop().RunUntilIdle(); mock_host_resolver_.ResolveAllPending(); base::RunLoop().RunUntilIdle(); } } // namespace net
[ "lixiaodonglove7@aliyun.com" ]
lixiaodonglove7@aliyun.com
2a46941097398f3987d63117553ace98d2cebba3
6f27c01df5b7c248293213c326df18e3c1593753
/Tercer Parcial/Proyectos/Lopez Zambrano/SFML_visual/ejercicios/244/Matriz.cpp
025fb52ef5925fa63e43294f334a09bda5ee6630
[]
no_license
rengarcia/Data-Structure
ded6d6c4759cd01dc30fb61e1b25aa47a13b0708
d9cc01d028a083f7cf2130952c1180b045c46476
refs/heads/master
2023-06-18T04:52:39.250613
2021-07-20T12:35:24
2021-07-20T12:35:24
220,644,703
1
0
null
null
null
null
UTF-8
C++
false
false
908
cpp
#include <iostream> #include "Matriz.h" using namespace std; void Matriz::imprime(int** matriz, int dim) { cout << endl; for (int i = 0; i < dim; i++) { for (int j = 0; j < dim; j++) { cout << *(*(matriz + i) + j) << " "; } cout << endl; } } void Matriz::ingreso(int** matriz, int dim) { int numero; for (int i = 0; i < dim; i++) { for (int j = 0; j < dim; j++) { cout << endl; cout << "Ingrese el dato para la posicion " << "(" << i + 1 << "," << j + 1 << ") : "; cin >> numero; *(*(matriz + i) + j) = numero; } } } int** Matriz::generar(int dim) { int** matriz; matriz = (int**)malloc(dim * sizeof(int*)); for (int j = 0; j < dim; j++) { *(matriz + j) = (int*)malloc(dim * sizeof(int)); } return matriz; } void Matriz::encerar(int** matriz, int dim) { int i, j; for (i = 0; i < dim; i++) for (j = 0; j < dim; j++) * (*(matriz + i) + j) = 0; return; }
[ "waza1995@gmail" ]
waza1995@gmail
d034df5ef32a142b10c51569fbd5ffaff8ddc2a1
39853ff7bd630de7e3af2b16f7e044d2c691ab2c
/Src/prov/DatasrcExImpl.h
00bf00774e425f63b006fd7370f008b74c50195c
[]
no_license
holem2k/MySqlOleDbProvider
8b1ff312d416c70feac9995f6c7ff595efb81acb
9f60823d20f61d9c4e51c7540210c4a2cdc271d1
refs/heads/master
2022-11-19T07:45:25.308026
2020-07-17T20:36:43
2020-07-17T20:36:43
280,519,430
2
1
null
null
null
null
UTF-8
C++
false
false
9,927
h
#include "stdafx.h" const LPOLESTR szKeywords[] = { OLESTR("AGGREGATE"), OLESTR("AFTER"), OLESTR("AVG_ROW_LENGTH"), OLESTR("AUTO_INCREMENT"), OLESTR("BIGINT"), OLESTR("BINARY"), OLESTR("BLOB"), OLESTR("BOOL"), OLESTR("CHANGE"), OLESTR("CHECKSUM"), OLESTR("COLUMNS"), OLESTR("COMMENT"), OLESTR("DATA"), OLESTR("DATABASE"), OLESTR("DATABASES"), OLESTR("DATETIME"), OLESTR("DAY_HOUR"), OLESTR("DAY_MINUTE"), OLESTR("DAY_SECOND"), OLESTR("DAYOFMONTH"), OLESTR("DAYOFWEEK"), OLESTR("DAYOFYEAR"), OLESTR("DELAYED"), OLESTR("DELAY_KEY_WRITE"), OLESTR("ESCAPED"), OLESTR("ENCLOSED"), OLESTR("ENUM"), OLESTR("EXPLAIN"), OLESTR("FIELDS"), OLESTR("FILE"), OLESTR("FLOAT4"), OLESTR("FLOAT8"), OLESTR("FLUSH"), OLESTR("FUNCTION"), OLESTR("GRANTS"), OLESTR("HEAP"), OLESTR("HIGH_PRIORITY"), OLESTR("HOUR_MINUTE"), OLESTR("HOUR_SECOND"), OLESTR("HOSTS"), OLESTR("IDENTIFIED"), OLESTR("IGNORE"), OLESTR("INDEX"), OLESTR("INFILE"), OLESTR("INSERT_ID"), OLESTR("INT1"), OLESTR("INT2"), OLESTR("INT3"), OLESTR("INT4"), OLESTR("INT8"), OLESTR("IF"), OLESTR("ISAM"), OLESTR("KEYS"), OLESTR("KILL"), OLESTR("LAST_INSERT_ID"), OLESTR("LENGTH"), OLESTR("LINES"), OLESTR("LIMIT"), OLESTR("LOAD"), OLESTR("LOCK"), OLESTR("LOGS"), OLESTR("LONG"), OLESTR("LONGBLOB"), OLESTR("LONGTEXT"), OLESTR("LOW_PRIORITY"), OLESTR("MAX_ROWS"), OLESTR("MEDIUMBLOB"), OLESTR("MEDIUMTEXT"), OLESTR("MEDIUMINT"), OLESTR("MIDDLEINT"), OLESTR("MIN_ROWS"), OLESTR("MINUTE_SECOND"), OLESTR("MODIFY"), OLESTR("MONTHNAME"), OLESTR("MYISAM"), OLESTR("OPTIMIZE"), OLESTR("OPTIONALLY"), OLESTR("OUTFILE"), OLESTR("PACK_KEYS"), OLESTR("PASSWORD"), OLESTR("PROCESS"), OLESTR("PROCESSLIST"), OLESTR("RELOAD"), OLESTR("REGEXP"), OLESTR("RENAME"), OLESTR("REPLACE"), OLESTR("RETURNS"), OLESTR("RLIKE"), OLESTR("ROW"), OLESTR("SHOW"), OLESTR("SHUTDOWN"), OLESTR("SONAME"), OLESTR("SQL_BIG_TABLES"), OLESTR("SQL_BIG_SELECTS"), OLESTR("SQL_LOW_PRIORITY_UPDATES"), OLESTR("SQL_LOG_OFF"), OLESTR("SQL_LOG_UPDATE"), OLESTR("SQL_SELECT_LIMIT"), OLESTR("SQL_SMALL_RESULT"), OLESTR("SQL_BIG_RESULT"), OLESTR("SQL_WARNINGS"), OLESTR("STRAIGHT_JOIN"), OLESTR("STARTING"), OLESTR("STATUS"), OLESTR("STRING"), OLESTR("TABLES"), OLESTR("TERMINATED"), OLESTR("TEXT"), OLESTR("TINYBLOB"), OLESTR("TINYTEXT"), OLESTR("TINYINT"), OLESTR("TYPE"), OLESTR("USE"), OLESTR("UNLOCK"), OLESTR("UNSIGNED"), OLESTR("VARIABLES"), OLESTR("VARBINARY"), OLESTR("YEAR_MONTH"), OLESTR("ZEROFILL") }; const DBLITERALINFO rgLiteralInfo[] = { {NULL, OLESTR("!\"%&'()*_+,-./:;<=>?@[\\]^{|}~"), OLESTR("0123456789!\"%&'()*_+,-./:;<=>?@[\\]^{|}~"), DBLITERAL_CATALOG_NAME, TRUE, 64}, {NULL, OLESTR("!\"%&'()*_+,-./:;<=>?@[\\]^{|}~"), OLESTR("0123456789!\"%&'()*_+,-./:;<=>?@[\\]^{|}~"), DBLITERAL_VIEW_NAME, TRUE, 64}, {NULL, OLESTR("!\"%&'()*_+,-./:;<=>?@[\\]^{|}~"), OLESTR("0123456789!\"%&'()*_+,-./:;<=>?@[\\]^{|}~"), DBLITERAL_TABLE_NAME, TRUE, 64}, {NULL, OLESTR("!\"%&'()*_+,-./:;<=>?@[\\]^{|}~"), OLESTR("0123456789!\"%&'()*_+,-./:;<=>?@[\\]^{|}~"), DBLITERAL_CORRELATION_NAME, TRUE, 64}, {NULL, OLESTR("!\"%&'()*_+,-./:;<=>?@[\\]^{|}~"), OLESTR("0123456789!\"%&'()*_+,-./:;<=>?@[\\]^{|}~"), DBLITERAL_COLUMN_NAME, TRUE, 64}, {NULL, OLESTR("!\"%&'()*_+,-./:;<=>?@[\\]^{|}~"), OLESTR("0123456789!\"%&'()*_+,-./:;<=>?@[\\]^{|}~"), DBLITERAL_COLUMN_ALIAS, TRUE, 64}, {NULL, OLESTR("!\"%&'()*_+,-./:;<=>?@[\\]^{|}~"), OLESTR("0123456789!\"%&'()*_+,-./:;<=>?@[\\]^{|}~"), DBLITERAL_INDEX_NAME, TRUE, 64}, {NULL, NULL, NULL, DBLITERAL_TEXT_COMMAND, TRUE, 8192}, {NULL, NULL, NULL, DBLITERAL_USER_NAME, TRUE, 16}, {OLESTR("."), NULL, NULL, DBLITERAL_CATALOG_SEPARATOR, TRUE, 1}, {OLESTR("%"), NULL, NULL, DBLITERAL_LIKE_PERCENT, TRUE, 1}, {OLESTR("_"), NULL, NULL, DBLITERAL_LIKE_UNDERSCORE, TRUE, 1}, {OLESTR("\\")/*\*/, NULL, NULL, DBLITERAL_ESCAPE_PERCENT_PREFIX, TRUE, 1}, {OLESTR("\\")/*\*/, NULL, NULL, DBLITERAL_ESCAPE_UNDERSCORE_PREFIX, TRUE, 1}, //{OLESTR("'"), NULL, NULL, DBLITERAL_QUOTE_PREFIX, TRUE, 1}, //{OLESTR("'"), NULL, NULL, DBLITERAL_QUOTE_SUFFIX, TRUE, 1}, //{OLESTR("{}"), NULL, NULL, DBLITERAL_QUOTE, TRUE, 2} }; ///////////////////////////////////////////////////////////////////////// // IDBInfoImpl template <class T> class IDBInfoImpl : public IDBInfo { STDMETHOD(GetKeywords)( LPOLESTR *ppwszKeywords) { ATLTRACE2(atlTraceDBProvider, 0, "IDBInfoImpl::GetKeywords\n"); T *pT = (T *)this; if (!(pT->m_dwStatus & DSF_INITIALIZED)) return E_UNEXPECTED; if (!ppwszKeywords) return E_INVALIDARG; UINT cKeywords = sizeof(szKeywords)/sizeof(szKeywords[0]); UINT cbKeywords = 0; for (UINT i = 0; i < cKeywords; i++) cbKeywords += lstrlenW(szKeywords[i]) + 1; cbKeywords = ++cbKeywords*sizeof(OLECHAR); HRESULT hr; LPOLESTR szKeywordsBuf = (LPOLESTR)CoTaskMemAlloc(cbKeywords); if (szKeywords) { UINT cbOffset = 0; for (UINT i = 0; i < cKeywords; i++) { lstrcpyW(szKeywordsBuf + cbOffset, szKeywords[i]); cbOffset += lstrlenW(szKeywords[i]); *(szKeywordsBuf + cbOffset++) = OLESTR(','); } *(szKeywordsBuf + cbOffset - 1) = OLESTR('\0'); *ppwszKeywords = szKeywordsBuf; hr = S_OK; } else { *ppwszKeywords = NULL; hr = E_OUTOFMEMORY; } return hr; } STDMETHOD(GetLiteralInfo)( ULONG cLiterals, const DBLITERAL rgLiterals[], ULONG *pcLiteralInfo, DBLITERALINFO **prgLiteralInfo, OLECHAR **ppCharBuffer) { ATLTRACE2(atlTraceDBProvider, 0, "IDBInfoImpl::GetLiteralInfo\n"); T *pT = (T *)this; if (!(pT->m_dwStatus & DSF_INITIALIZED)) return E_UNEXPECTED; if (cLiterals > 0 && rgLiterals == NULL) return E_INVALIDARG; if (prgLiteralInfo == NULL || ppCharBuffer == NULL || pcLiteralInfo == NULL) return E_INVALIDARG; // assume error *pcLiteralInfo = 0; *prgLiteralInfo = NULL; *ppCharBuffer = NULL; ULONG cRealLiterals = sizeof(rgLiteralInfo)/sizeof(rgLiteralInfo[0]); HRESULT hr; if (cLiterals == 0) { ULONG cbCharBuffer = 0; for (UINT i = 0; i < cRealLiterals; i++) cbCharBuffer += LiteralInfoStringsLength(rgLiteralInfo + i); DBLITERALINFO *rgInfo = (DBLITERALINFO *)CoTaskMemAlloc(cRealLiterals * sizeof(DBLITERALINFO)); OLECHAR *pCharBuffer = (OLECHAR *)CoTaskMemAlloc(cbCharBuffer); if (rgInfo && pCharBuffer) { ULONG nOffset = 0; for (UINT i = 0; i < cRealLiterals; i++) CopyLiteralInfo(rgInfo + i, rgLiteralInfo + i, pCharBuffer, nOffset); *pcLiteralInfo = cRealLiterals; *prgLiteralInfo = rgInfo; *ppCharBuffer = pCharBuffer; hr = S_OK; } else { CoTaskMemFree(rgInfo); CoTaskMemFree(pCharBuffer); hr = E_OUTOFMEMORY; } } else { INT *pIndex; ATLTRY(pIndex = new INT[cLiterals]); if (pIndex == NULL) return E_OUTOFMEMORY; ULONG cErrors = 0; ULONG cbCharBuffer = 0; for (ULONG i = 0; i < cLiterals; i++) { pIndex[i] = -1; for (ULONG j = 0; j < cRealLiterals; j++) { if (rgLiteralInfo[j].lt == rgLiterals[i]) { pIndex[i] = j; cbCharBuffer += LiteralInfoStringsLength(rgLiteralInfo + j); break; } } if (pIndex[i] == -1) cErrors++; } DBLITERALINFO *rgInfo = (DBLITERALINFO *)CoTaskMemAlloc(cLiterals * sizeof(DBLITERALINFO)); OLECHAR *pCharBuffer = (OLECHAR *)CoTaskMemAlloc(cbCharBuffer); if (rgInfo && pCharBuffer) { ULONG cbOffset = 0; for (UINT i = 0; i < cLiterals; i++) { if (pIndex[i] != -1) CopyLiteralInfo(rgInfo + i, rgLiteralInfo + pIndex[i], pCharBuffer, cbOffset); else CopyUnsupportedLiteralInfo(rgInfo + i, rgLiterals[i]); } *pcLiteralInfo = cLiterals; *prgLiteralInfo = rgInfo; *ppCharBuffer = pCharBuffer; if (cErrors == cLiterals) hr = DB_E_ERRORSOCCURRED; else if (cErrors > 0) hr = DB_S_ERRORSOCCURRED; else hr = S_OK; } else { CoTaskMemFree(rgInfo); CoTaskMemFree(pCharBuffer); hr = E_OUTOFMEMORY; } delete [] pIndex; } return hr; } protected: void CopyLiteralInfo(DBLITERALINFO *pDestInfo, const DBLITERALINFO *pSrcInfo, OLECHAR *pBuffer, ULONG &nOffset) { pDestInfo->lt = pSrcInfo->lt; ATLASSERT(pSrcInfo->fSupported); pDestInfo->fSupported = pSrcInfo->fSupported; pDestInfo->cchMaxLen = pSrcInfo->cchMaxLen; if (pSrcInfo->pwszLiteralValue) { pDestInfo->pwszLiteralValue = pBuffer + nOffset; lstrcpyW(pDestInfo->pwszLiteralValue, pSrcInfo->pwszLiteralValue); nOffset += lstrlenW(pDestInfo->pwszLiteralValue) + 1; } else pDestInfo->pwszLiteralValue = NULL; if (pSrcInfo->pwszInvalidStartingChars) { pDestInfo->pwszInvalidStartingChars = pBuffer + nOffset; lstrcpyW(pDestInfo->pwszInvalidStartingChars, pSrcInfo->pwszInvalidStartingChars); nOffset += lstrlenW(pDestInfo->pwszInvalidStartingChars) + 1; } else pDestInfo->pwszInvalidStartingChars = NULL; if (pSrcInfo->pwszInvalidChars) { pDestInfo->pwszInvalidChars = pBuffer + nOffset; lstrcpyW(pDestInfo->pwszInvalidChars, pSrcInfo->pwszInvalidChars); nOffset += lstrlenW(pDestInfo->pwszInvalidChars) + 1; } else pDestInfo->pwszInvalidChars = NULL; } void CopyUnsupportedLiteralInfo(DBLITERALINFO *pDestInfo, const DBLITERAL lt) { pDestInfo->pwszLiteralValue = NULL; pDestInfo->pwszInvalidStartingChars = NULL; pDestInfo->pwszInvalidChars = NULL; pDestInfo->lt = lt; pDestInfo->fSupported = FALSE; pDestInfo->cchMaxLen = ~0; } ULONG LiteralInfoStringsLength(const DBLITERALINFO *pInfo) { UINT cLen = 0; if (pInfo->pwszLiteralValue) cLen += lstrlenW(pInfo->pwszLiteralValue) + 1; if (pInfo->pwszInvalidStartingChars) cLen += lstrlenW(pInfo->pwszInvalidStartingChars) + 1; if (pInfo->pwszInvalidChars) cLen += lstrlenW(pInfo->pwszInvalidChars) + 1; return cLen*2; } };
[ "holem2k@hotmail.com" ]
holem2k@hotmail.com
82dd9110eabe910e6be68c90374016588a23ef09
349fe789ab1e4e46aae6812cf60ada9423c0b632
/Forms/HLP_SprNaborInfBlock/UHLP_FormaElementaSprNaborInfBlockImpl.h
2d629d13987fc523c7fbdfb49f47573c8c6da042
[]
no_license
presscad/ERP
a6acdaeb97b3a53f776677c3a585ca860d4de980
18ecc6c8664ed7fc3f01397d587cce91fc3ac78b
refs/heads/master
2020-08-22T05:24:15.449666
2019-07-12T12:59:13
2019-07-12T12:59:13
216,326,440
1
0
null
2019-10-20T07:52:26
2019-10-20T07:52:26
null
UTF-8
C++
false
false
1,907
h
#ifndef UHLP_FormaElementaSprNaborInfBlockImplH #define UHLP_FormaElementaSprNaborInfBlockImplH #include "IHLP_FormaElementaSprNaborInfBlock.h" #include "UHLP_FormaElementaSprNaborInfBlock.h" #include "UGlobalConstant.h" //--------------------------------------------------------------- class __declspec(uuid(Global_CLSID_THLP_FormaElementaSprNaborInfBlockImpl)) THLP_FormaElementaSprNaborInfBlockImpl : public IHLP_FormaElementaSprNaborInfBlock, IkanCallBack { public: THLP_FormaElementaSprNaborInfBlockImpl(); ~THLP_FormaElementaSprNaborInfBlockImpl(); THLP_FormaElementaSprNaborInfBlock * Object; int NumRefs; bool flDeleteObject; void DeleteImpl(void); //IUnknown virtual int kanQueryInterface(REFIID id_interface,void ** ppv); virtual int kanAddRef(void); virtual int kanRelease(void); //IMainInterface virtual int get_CodeError(void); virtual void set_CodeError(int CodeError); virtual UnicodeString get_TextError(void); virtual void set_TextError(UnicodeString TextError); virtual int Init(IkanUnknown * i_main_object, IkanUnknown * i_owner_object); virtual int Done(void); //IkanCallBack virtual int kanExternalEvent(IkanUnknown * pUnk, REFIID id_object,int type_event, int number_procedure_end); //IHLP_FormaElementaSprNaborInfBlock virtual bool get_Prosmotr(void); virtual void set_Prosmotr(bool Prosmotr); virtual bool get_Vibor(void); virtual void set_Vibor(bool Vibor); virtual int get_NumberProcVibor(void); virtual void set_NumberProcVibor(int NumberProcVibor); virtual IHLP_DMSprNaborInfBlock * get_DM(void); virtual void set_DM(IHLP_DMSprNaborInfBlock * DM); virtual bool get_SaveElement(void); virtual void set_SaveElement(bool SaveElement); virtual void UpdateForm(void); }; #define CLSID_THLP_FormaElementaSprNaborInfBlockImpl __uuidof(THLP_FormaElementaSprNaborInfBlockImpl) #endif
[ "sasha@kaserv.ru" ]
sasha@kaserv.ru
8a5dfd92732b385559659623d84ce6655da9c092
eac0a13fea8acd3ee5d8c6bd72b97f39102c6337
/ObjectOrientedProgramming/OOP_indie_studio_2019/src/IrrGui.cpp
5fc7d5c775270fcf1c0fcda84df3f1aff2144d2f
[]
no_license
Jean-MichelGRONDIN/EPITECH_Tek2_Projects
ddb022cc6dafd9c3d8d1e8b17bad8de108a0cd2c
eb4621bb747b1f2cca3edfe993fefef4b564835f
refs/heads/master
2023-01-04T13:12:21.670186
2020-10-23T06:16:50
2020-10-23T06:16:50
null
0
0
null
null
null
null
UTF-8
C++
false
false
938
cpp
/* ** EPITECH PROJECT, 2020 ** cross_platform ** File description: ** IrrGui */ #include "IrrGui.hpp" IrrGui::IrrGui(irr::IrrlichtDevice *device) { _guiEnv = device->getGUIEnvironment(); irr::gui::IGUISkin* skin = _guiEnv->getSkin(); irr::gui::IGUIFont* font = _guiEnv->getFont("../assets/NineteenNinetySeven-11XB.png"); skin->setFont(font); skin->setFont(_guiEnv->getBuiltInFont(), irr::gui::EGDF_TOOLTIP); } IrrGui::~IrrGui() { } irr::u32 IrrGui::getNewId() { return (_guiEvent.size() + 1); } irr::gui::IGUIEnvironment *IrrGui::getGuiEnv() { return (_guiEnv); } bool IrrGui::manageEvent(const irr::SEvent& event) { irr::s32 id = event.GUIEvent.Caller->getID(); if (_guiEvent[id]) return (_guiEvent[id]->onEvent(event)); return (false); } void IrrGui::addItem(irr::u32 id, IEventHandeler *event) { _guiEvent.insert({id, event}); }
[ "jean-michel@pop-os.localdomain" ]
jean-michel@pop-os.localdomain
870efbf741c2cdb17500da6c5de45dd3331972b8
055f6dc4f9479b3c04f0278376f684c656f00308
/main.cpp
4ee15e9f12f78a91ef44e5f3657eb42dc056e50e
[]
no_license
nguyentrungduc08/testMemory_QT
4cc62ee372ecd9af43a101788fce58091786aff4
32b290af6886eb43c38e63301160c9cc1423a7b8
refs/heads/master
2020-03-13T19:43:35.630555
2018-05-02T12:20:47
2018-05-02T12:20:47
131,259,499
0
0
null
null
null
null
UTF-8
C++
false
false
3,772
cpp
#include <QGuiApplication> #include <QQmlApplicationEngine> #include <QList> #include <QVector> #include <QObject> #include <iostream> #include <unistd.h> #include <QDebug> #include <iostream> #include <vector> #define rep(i,n) for(int i = 0; i < n ; ++i) class objectTest{ private: QString _proString; int _proInt; public: objectTest(QString proString, int proInt) : _proString(proString), _proInt(proInt){ std::cout << "created object" << std::endl; }; ~objectTest(){ std::cout << "released object " << _proInt << std::endl; }; }; class uQList { private: QList<objectTest> _list; public: uQList(){ std::cout << "created object uQList" << std::endl; }; ~uQList(){ std::cout << "released object uQList" << std::endl; }; void setData(){ for (int i = 0; i < 500000; ++i) { objectTest test("asdfnnmgkdfawngdfnkdlngansdfknalkklfashdglajbdglkjasdbflkasdjfklahgakdfehinlfjnalkjdghkadjshfadshgdgjaksldlkasjdhfkajbdgldlkfjbaldkfghasdf",i); this->_list.append(test); } }; void clearData(){ this->_list.clear(); } QList<objectTest> getlist() { QList<objectTest> _listTest; for (int i = 0; i < 500000; ++i) { objectTest test("asdfnnmgkdfawngdfnkdlngansdfknalkklfashdglajbdglkjasdbflkasdjfklahgakdfehinlfjnalkjdghkadjshfadshgdgjaksldlkasjdhfkajbdgldlkfjbaldkfghasdf",i); _listTest.append(test); } std::cout <<" begin count to show " << std::endl; sleep(5); std::cout <<" begin return data " << std::endl; return _listTest; } void testDataUsing(){ std::cout << "begin test getlist" << std::endl; this->_list = getlist(); std::cout << "close test getlist" << std::endl; } }; class uQVector { private: QVector<objectTest> _vector; public: uQVector(){ } }; class UIchecker: public QObject { Q_OBJECT }; struct entity { int x,y,z; entity(int x, int y, int z) : x(x), y(y), z(z) { std::cout << "constructor!!!!" << x << std::endl; } entity(const entity& e) : x(e.x) , y(e.y) , z(e.z) { std::cout << "copied constructor!!!!" << e.x << std::endl; } }; class obj { private: int _x,_y,_z; public: obj(int x, int y, int z): _x(x), _y(y), _z(z){ std::cout << "constructor " << this->_x << " - address: " << this << std::endl; }; obj(const obj& o): _x(o._x), _y(o._y), _z(o._z){ std::cout << "copied constructor " << this->_x << " - address: " << this << std::endl; } ~obj(){ std::cout << "destroy " << this->_x << " - address: " << this << std::endl; }; }; std::vector<obj> myVector; std::vector<obj> createData(){ std::vector<obj> tem; std::cout << " Create data " << std::endl; rep(i,10){ std::cout << "_____________________________________________begin" << std::endl; obj o(i,i,i); tem.emplace_back(o); std::cout << "_____________________________________________end" << std::endl; } return tem; } void testFunc(){ myVector = createData(); std::cout << "datasize: " << myVector.size() << std::endl; return; } int main(int argc, char *argv[]) { // QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling); // QGuiApplication app(argc, argv); // QQmlApplicationEngine engine; // engine.load(QUrl(QStringLiteral("qrc:/main.qml"))); // if (engine.rootObjects().isEmpty()) // return -1; testFunc(); std::cout << "finished test" << std::endl; //std::cin.get(); // return app.exec(); return 0; }
[ "nguyentrungduc08@gmail.com" ]
nguyentrungduc08@gmail.com
cc889fcd44410b4c0e044bb0ebeecd0f948ef39b
4eebe8f5542f060b8fdb831f05d1960e51193b3e
/isolation/inputs.cpp
59cd06506cc5dca1906e846047205c93c9a508ac
[]
no_license
harish1996/graph_assignment
189eb11a2be4054cccd0c8862a30f871f360df75
11aa4b062bf6e67308807617e28b0ec0bd67c434
refs/heads/master
2020-05-09T09:48:07.503403
2019-06-26T22:36:35
2019-06-26T22:36:35
181,016,974
0
0
null
null
null
null
UTF-8
C++
false
false
308
cpp
#include <iostream> #include <string> #include <string.h> using namespace std; char *readlines( int lines ) { string full; string line; for( int i=0; i<lines; i++ ){ getline(line); full += line; } return strdup( full.c_str() ); } int main() { int n; cin>>n; char *s; cout<<readlines(n); }
[ "harishganesan96@gmail.com" ]
harishganesan96@gmail.com
fe27239caeea5ea3c1677dedd5f3364b5884b01b
5d83739af703fb400857cecc69aadaf02e07f8d1
/Archive2/3b/e5877aa14466da/main.cpp
202da028e0b5d111ed139c580ea3c1624daef699
[]
no_license
WhiZTiM/coliru
3a6c4c0bdac566d1aa1c21818118ba70479b0f40
2c72c048846c082f943e6c7f9fa8d94aee76979f
refs/heads/master
2021-01-01T05:10:33.812560
2015-08-24T19:09:22
2015-08-24T19:09:22
56,789,706
3
0
null
null
null
null
UTF-8
C++
false
false
121
cpp
#include <cstdlib> struct big{ int array [42]; }; big* foo() { return new big{ { std::rand() } } ; }
[ "francis.rammeloo@36614edc-3e3a-acb8-9062-c8ae0e4185df" ]
francis.rammeloo@36614edc-3e3a-acb8-9062-c8ae0e4185df
e8502a30807e2fbd687e7f02db6377f4d2008074
24f26275ffcd9324998d7570ea9fda82578eeb9e
/ui/ozone/platform/scenic/sysmem_buffer_collection.cc
1a26bd171f9b8206ce3a6b3dc797fbd52ae5dc20
[ "BSD-3-Clause" ]
permissive
Vizionnation/chromenohistory
70a51193c8538d7b995000a1b2a654e70603040f
146feeb85985a6835f4b8826ad67be9195455402
refs/heads/master
2022-12-15T07:02:54.461083
2019-10-25T15:07:06
2019-10-25T15:07:06
217,557,501
2
1
BSD-3-Clause
2022-11-19T06:53:07
2019-10-25T14:58:54
null
UTF-8
C++
false
false
16,612
cc
// Copyright 2019 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/ozone/platform/scenic/sysmem_buffer_collection.h" #include "base/bits.h" #include "base/fuchsia/fuchsia_logging.h" #include "gpu/vulkan/vulkan_device_queue.h" #include "gpu/vulkan/vulkan_function_pointers.h" #include "ui/gfx/buffer_format_util.h" #include "ui/gfx/native_pixmap.h" namespace ui { namespace { class SysmemNativePixmap : public gfx::NativePixmap { public: SysmemNativePixmap(scoped_refptr<SysmemBufferCollection> collection, gfx::NativePixmapHandle handle) : collection_(collection), handle_(std::move(handle)) {} bool AreDmaBufFdsValid() const override { return false; } int GetDmaBufFd(size_t plane) const override { NOTREACHED(); return -1; } uint32_t GetDmaBufPitch(size_t plane) const override { NOTREACHED(); return 0u; } size_t GetDmaBufOffset(size_t plane) const override { NOTREACHED(); return 0u; } size_t GetDmaBufPlaneSize(size_t plane) const override { NOTREACHED(); return 0; } size_t GetNumberOfPlanes() const override { NOTREACHED(); return 0; } uint64_t GetBufferFormatModifier() const override { NOTREACHED(); return 0; } gfx::BufferFormat GetBufferFormat() const override { return collection_->format(); } gfx::Size GetBufferSize() const override { return collection_->size(); } uint32_t GetUniqueId() const override { return 0; } bool ScheduleOverlayPlane(gfx::AcceleratedWidget widget, int plane_z_order, gfx::OverlayTransform plane_transform, const gfx::Rect& display_bounds, const gfx::RectF& crop_rect, bool enable_blend, std::unique_ptr<gfx::GpuFence> gpu_fence) override { NOTIMPLEMENTED(); return false; } gfx::NativePixmapHandle ExportHandle() override { return gfx::CloneHandleForIPC(handle_); } private: ~SysmemNativePixmap() override = default; // Keep reference to the collection to make sure it outlives the pixmap. scoped_refptr<SysmemBufferCollection> collection_; gfx::NativePixmapHandle handle_; DISALLOW_COPY_AND_ASSIGN(SysmemNativePixmap); }; size_t RoundUp(size_t value, size_t alignment) { return ((value + alignment - 1) / alignment) * alignment; } VkFormat VkFormatForBufferFormat(gfx::BufferFormat buffer_format) { switch (buffer_format) { case gfx::BufferFormat::YVU_420: return VK_FORMAT_G8_B8_R8_3PLANE_420_UNORM; case gfx::BufferFormat::YUV_420_BIPLANAR: return VK_FORMAT_G8_B8R8_2PLANE_420_UNORM; case gfx::BufferFormat::BGRA_8888: case gfx::BufferFormat::BGRX_8888: return VK_FORMAT_B8G8R8A8_UNORM; case gfx::BufferFormat::RGBA_8888: case gfx::BufferFormat::RGBX_8888: return VK_FORMAT_R8G8B8A8_UNORM; default: NOTREACHED(); return VK_FORMAT_UNDEFINED; } } } // namespace // static bool SysmemBufferCollection::IsNativePixmapConfigSupported( gfx::BufferFormat format, gfx::BufferUsage usage) { bool format_supported = format == gfx::BufferFormat::YUV_420_BIPLANAR || format == gfx::BufferFormat::RGBA_8888 || format == gfx::BufferFormat::RGBX_8888 || format == gfx::BufferFormat::BGRA_8888 || format == gfx::BufferFormat::BGRX_8888; bool usage_supported = usage == gfx::BufferUsage::SCANOUT || usage == gfx::BufferUsage::SCANOUT_CPU_READ_WRITE || usage == gfx::BufferUsage::GPU_READ_CPU_READ_WRITE; return format_supported && usage_supported; } SysmemBufferCollection::SysmemBufferCollection() : SysmemBufferCollection(gfx::SysmemBufferCollectionId::Create()) {} SysmemBufferCollection::SysmemBufferCollection(gfx::SysmemBufferCollectionId id) : id_(id) {} bool SysmemBufferCollection::Initialize( fuchsia::sysmem::Allocator_Sync* allocator, gfx::Size size, gfx::BufferFormat format, gfx::BufferUsage usage, VkDevice vk_device, size_t num_buffers) { DCHECK(IsNativePixmapConfigSupported(format, usage)); DCHECK(!collection_); DCHECK(!vk_buffer_collection_); // Currently all supported |usage| values require GPU access, which requires // a valid VkDevice. if (vk_device == VK_NULL_HANDLE) return false; size_ = size; format_ = format; usage_ = usage; vk_device_ = vk_device; fuchsia::sysmem::BufferCollectionTokenSyncPtr collection_token; zx_status_t status = allocator->AllocateSharedCollection(collection_token.NewRequest()); if (status != ZX_OK) { ZX_DLOG(ERROR, status) << "fuchsia.sysmem.Allocator.AllocateSharedCollection()"; return false; } return InitializeInternal(allocator, std::move(collection_token), num_buffers); } bool SysmemBufferCollection::Initialize( fuchsia::sysmem::Allocator_Sync* allocator, VkDevice vk_device, zx::channel token_handle) { DCHECK(!collection_); DCHECK(!vk_buffer_collection_); usage_ = gfx::BufferUsage::GPU_READ; vk_device_ = vk_device; // Assume that all imported collections are in NV12 format. format_ = gfx::BufferFormat::YUV_420_BIPLANAR; fuchsia::sysmem::BufferCollectionTokenSyncPtr token; token.Bind(std::move(token_handle)); return InitializeInternal(allocator, std::move(token), /*buffers_for_camping=*/0); } scoped_refptr<gfx::NativePixmap> SysmemBufferCollection::CreateNativePixmap( size_t buffer_index) { CHECK_LT(buffer_index, num_buffers()); gfx::NativePixmapHandle handle; handle.buffer_collection_id = id(); handle.buffer_index = buffer_index; handle.ram_coherency = buffers_info_.settings.buffer_settings.coherency_domain == fuchsia::sysmem::CoherencyDomain::RAM; zx::vmo main_plane_vmo; if (is_mappable()) { DCHECK(buffers_info_.buffers[buffer_index].vmo.is_valid()); zx_status_t status = buffers_info_.buffers[buffer_index].vmo.duplicate( ZX_RIGHT_SAME_RIGHTS, &main_plane_vmo); if (status != ZX_OK) { ZX_DLOG(ERROR, status) << "zx_handle_duplicate"; return nullptr; } } const fuchsia::sysmem::ImageFormatConstraints& format = buffers_info_.settings.image_format_constraints; // The logic should match LogicalBufferCollection::Allocate(). size_t width = RoundUp(std::max(format.min_coded_width, format.required_max_coded_width), format.coded_width_divisor); size_t stride = RoundUp(std::max(static_cast<size_t>(format.min_bytes_per_row), gfx::RowSizeForBufferFormat(width, format_, 0)), format.bytes_per_row_divisor); size_t height = RoundUp( std::max(format.min_coded_height, format.required_max_coded_height), format.coded_height_divisor); size_t plane_offset = buffers_info_.buffers[buffer_index].vmo_usable_start; size_t plane_size = stride * height; handle.planes.emplace_back(stride, plane_offset, plane_size, std::move(main_plane_vmo)); // For YUV images add a second plane. if (format_ == gfx::BufferFormat::YUV_420_BIPLANAR) { size_t uv_plane_offset = plane_offset + plane_size; size_t uv_plane_size = plane_size / 2; handle.planes.emplace_back(stride, uv_plane_offset, uv_plane_size, zx::vmo()); DCHECK_LE(uv_plane_offset + uv_plane_size, buffer_size_); } return new SysmemNativePixmap(this, std::move(handle)); } bool SysmemBufferCollection::CreateVkImage( size_t buffer_index, VkDevice vk_device, gfx::Size size, VkImage* vk_image, VkImageCreateInfo* vk_image_info, VkDeviceMemory* vk_device_memory, VkDeviceSize* mem_allocation_size, base::Optional<gpu::VulkanYCbCrInfo>* ycbcr_info) { DCHECK_CALLED_ON_VALID_THREAD(vulkan_thread_checker_); if (vk_device_ != vk_device) { DLOG(FATAL) << "Tried to import NativePixmap that was created for a " "different VkDevice."; return false; } VkBufferCollectionPropertiesFUCHSIA properties = { VK_STRUCTURE_TYPE_BUFFER_COLLECTION_PROPERTIES_FUCHSIA}; if (vkGetBufferCollectionPropertiesFUCHSIA(vk_device_, vk_buffer_collection_, &properties) != VK_SUCCESS) { DLOG(ERROR) << "vkGetBufferCollectionPropertiesFUCHSIA failed"; return false; } InitializeImageCreateInfo(vk_image_info, size); VkBufferCollectionImageCreateInfoFUCHSIA image_format_fuchsia = { VK_STRUCTURE_TYPE_BUFFER_COLLECTION_IMAGE_CREATE_INFO_FUCHSIA, }; image_format_fuchsia.collection = vk_buffer_collection_; image_format_fuchsia.index = buffer_index; vk_image_info->pNext = &image_format_fuchsia; if (vkCreateImage(vk_device_, vk_image_info, nullptr, vk_image) != VK_SUCCESS) { DLOG(ERROR) << "Failed to create VkImage."; return false; } vk_image_info->pNext = nullptr; VkMemoryRequirements requirements; vkGetImageMemoryRequirements(vk_device, *vk_image, &requirements); uint32_t viable_memory_types = properties.memoryTypeBits & requirements.memoryTypeBits; uint32_t memory_type = base::bits::CountTrailingZeroBits(viable_memory_types); VkImportMemoryBufferCollectionFUCHSIA buffer_collection_info = { VK_STRUCTURE_TYPE_IMPORT_MEMORY_BUFFER_COLLECTION_FUCHSIA}; buffer_collection_info.collection = vk_buffer_collection_; buffer_collection_info.index = buffer_index; VkMemoryAllocateInfo alloc_info = {VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO, &buffer_collection_info}; alloc_info.allocationSize = requirements.size; alloc_info.memoryTypeIndex = memory_type; if (vkAllocateMemory(vk_device_, &alloc_info, nullptr, vk_device_memory) != VK_SUCCESS) { DLOG(ERROR) << "Failed to create VkMemory from sysmem buffer."; vkDestroyImage(vk_device_, *vk_image, nullptr); *vk_image = VK_NULL_HANDLE; return false; } if (vkBindImageMemory(vk_device_, *vk_image, *vk_device_memory, 0u) != VK_SUCCESS) { DLOG(ERROR) << "Failed to bind sysmem buffer to a VkImage."; vkDestroyImage(vk_device_, *vk_image, nullptr); *vk_image = VK_NULL_HANDLE; vkFreeMemory(vk_device_, *vk_device_memory, nullptr); *vk_device_memory = VK_NULL_HANDLE; return false; } *mem_allocation_size = requirements.size; auto color_space = buffers_info_.settings.image_format_constraints.color_space[0].type; switch (color_space) { case fuchsia::sysmem::ColorSpaceType::SRGB: *ycbcr_info = base::nullopt; break; case fuchsia::sysmem::ColorSpaceType::REC709: { // Currently sysmem doesn't specify location of chroma samples relative to // luma (see fxb/13677). Assume they are cosited with luma. YCbCr info // here must match the values passed for the same buffer in // FuchsiaVideoDecoder. |format_features| are resolved later in the GPU // process before the ycbcr info is passed to Skia. *ycbcr_info = gpu::VulkanYCbCrInfo( vk_image_info->format, /*external_format=*/0, VK_SAMPLER_YCBCR_MODEL_CONVERSION_YCBCR_709, VK_SAMPLER_YCBCR_RANGE_ITU_NARROW, VK_CHROMA_LOCATION_COSITED_EVEN, VK_CHROMA_LOCATION_COSITED_EVEN, /*format_features=*/0); break; } default: DLOG(ERROR) << "Sysmem allocated buffer with unsupported color space: " << static_cast<int>(color_space); return false; } return true; } void SysmemBufferCollection::SetOnDeletedCallback( base::OnceClosure on_deleted) { DCHECK(!on_deleted_); on_deleted_ = std::move(on_deleted); } SysmemBufferCollection::~SysmemBufferCollection() { if (vk_buffer_collection_ != VK_NULL_HANDLE) { vkDestroyBufferCollectionFUCHSIA(vk_device_, vk_buffer_collection_, nullptr); } if (collection_) collection_->Close(); if (on_deleted_) std::move(on_deleted_).Run(); } bool SysmemBufferCollection::InitializeInternal( fuchsia::sysmem::Allocator_Sync* allocator, fuchsia::sysmem::BufferCollectionTokenSyncPtr collection_token, size_t buffers_for_camping) { fidl::InterfaceHandle<fuchsia::sysmem::BufferCollectionToken> collection_token_for_vulkan; collection_token->Duplicate(ZX_RIGHT_SAME_RIGHTS, collection_token_for_vulkan.NewRequest()); zx_status_t status = collection_token->Sync(); if (status != ZX_OK) { ZX_DLOG(ERROR, status) << "fuchsia.sysmem.BufferCollectionToken.Sync()"; return false; } status = allocator->BindSharedCollection(std::move(collection_token), collection_.NewRequest()); if (status != ZX_OK) { ZX_DLOG(ERROR, status) << "fuchsia.sysmem.Allocator.BindSharedCollection()"; return false; } fuchsia::sysmem::BufferCollectionConstraints constraints; if (is_mappable()) { constraints.usage.cpu = fuchsia::sysmem::cpuUsageRead | fuchsia::sysmem::cpuUsageWrite; constraints.has_buffer_memory_constraints = true; constraints.buffer_memory_constraints.ram_domain_supported = true; constraints.buffer_memory_constraints.cpu_domain_supported = true; } else { constraints.usage.none = fuchsia::sysmem::noneUsage; } constraints.min_buffer_count_for_camping = buffers_for_camping; constraints.image_format_constraints_count = 0; status = collection_->SetConstraints(/*has_constraints=*/true, std::move(constraints)); if (status != ZX_OK) { ZX_DLOG(ERROR, status) << "fuchsia.sysmem.BufferCollection.SetConstraints()"; return false; } zx::channel token_channel = collection_token_for_vulkan.TakeChannel(); VkBufferCollectionCreateInfoFUCHSIA buffer_collection_create_info = { VK_STRUCTURE_TYPE_BUFFER_COLLECTION_CREATE_INFO_FUCHSIA}; buffer_collection_create_info.collectionToken = token_channel.get(); if (vkCreateBufferCollectionFUCHSIA(vk_device_, &buffer_collection_create_info, nullptr, &vk_buffer_collection_) != VK_SUCCESS) { vk_buffer_collection_ = VK_NULL_HANDLE; DLOG(ERROR) << "vkCreateBufferCollectionFUCHSIA() failed"; return false; } // vkCreateBufferCollectionFUCHSIA() takes ownership of the token on success. ignore_result(token_channel.release()); VkImageCreateInfo image_create_info; InitializeImageCreateInfo(&image_create_info, size_); if (vkSetBufferCollectionConstraintsFUCHSIA(vk_device_, vk_buffer_collection_, &image_create_info) != VK_SUCCESS) { DLOG(ERROR) << "vkSetBufferCollectionConstraintsFUCHSIA() failed"; return false; } zx_status_t wait_status; status = collection_->WaitForBuffersAllocated(&wait_status, &buffers_info_); if (status != ZX_OK) { ZX_DLOG(ERROR, status) << "fuchsia.sysmem.BufferCollection failed"; return false; } if (wait_status != ZX_OK) { ZX_DLOG(ERROR, status) << "fuchsia.sysmem.BufferCollection::" "WaitForBuffersAllocated() failed."; return false; } DCHECK_GE(buffers_info_.buffer_count, buffers_for_camping); DCHECK(buffers_info_.settings.has_image_format_constraints); buffer_size_ = buffers_info_.settings.buffer_settings.size_bytes; // CreateVkImage() should always be called on the same thread, but it may be // different from the thread that called Initialize(). DETACH_FROM_THREAD(vulkan_thread_checker_); return true; } void SysmemBufferCollection::InitializeImageCreateInfo( VkImageCreateInfo* vk_image_info, gfx::Size size) { *vk_image_info = {VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO}; vk_image_info->imageType = VK_IMAGE_TYPE_2D; vk_image_info->format = VkFormatForBufferFormat(format_); vk_image_info->extent = VkExtent3D{size.width(), size.height(), 1}; vk_image_info->mipLevels = 1; vk_image_info->arrayLayers = 1; vk_image_info->samples = VK_SAMPLE_COUNT_1_BIT; vk_image_info->tiling = is_mappable() ? VK_IMAGE_TILING_LINEAR : VK_IMAGE_TILING_OPTIMAL; vk_image_info->usage = VK_IMAGE_USAGE_SAMPLED_BIT; vk_image_info->sharingMode = VK_SHARING_MODE_EXCLUSIVE; vk_image_info->initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; } } // namespace ui
[ "rjkroege@chromium.org" ]
rjkroege@chromium.org
dca9ae44f39aa59c452f37a33601843db3423003
46d4712c82816290417d611a75b604d51b046ecc
/Samples/Win7Samples/winui/speech/reco/reco.h
f4a2ad5b52a0ca75240f0d6dc9caf6e377ee7859
[ "MIT" ]
permissive
ennoherr/Windows-classic-samples
00edd65e4808c21ca73def0a9bb2af9fa78b4f77
a26f029a1385c7bea1c500b7f182d41fb6bcf571
refs/heads/master
2022-12-09T20:11:56.456977
2022-12-04T16:46:55
2022-12-04T16:46:55
156,835,248
1
0
NOASSERTION
2022-12-04T16:46:55
2018-11-09T08:50:41
null
WINDOWS-1252
C++
false
false
8,015
h
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF // ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A // PARTICULAR PURPOSE. // // Copyright © Microsoft Corporation. All rights reserved /**************************************************************************** * Reco.H * *--------* * Description: * Header file for Reco tool. This file declares the various dialog classes. * ****************************************************************************/ #if !defined(AFX_RECO_H__BD16E9D0_597E_11D2_960E_00C04F8EE628__INCLUDED_) #define AFX_RECO_H__BD16E9D0_597E_11D2_960E_00C04F8EE628__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 // // Defines // #define MYGRAMMARID 101 #define ITNGRAMMARID 102 #define WM_RECOEVENT WM_APP // Window message used for recognition events #define MAX_LOADSTRING 250 // // Constant strings // const WCHAR g_szDynRuleName[] = L"DynRule"; // // Forward class declarations // class CRecoDlgListItem; class CRecoDlgClass; class CDynGrammarDlgClass; // // Helper class for CSpBasicQueue // class CDynItem { public: CDynItem(LPCWSTR psz) : m_dstr(psz) {} ; public: CSpDynamicString m_dstr; CDynItem * m_pNext; }; /**************************************************************************** * CRecoDlgListItem * *------------------* * * This class stores the recognition result as well as a text string associated * with the recognition. Note that the string will sometimes be <noise> and * the pResult will be NULL. In other cases the string will be <Unrecognized> * and pResult will be valid. * ****************************************************************************/ class CRecoDlgListItem { public: CRecoDlgListItem(ISpRecoResult * pResult, const WCHAR * pwsz, BOOL fHypothesis) : m_cpRecoResult(pResult), m_dstr(pwsz), m_fHypothesis(fHypothesis) {} ISpRecoResult * GetRecoResult() const { return m_cpRecoResult; } int GetTextLength() const { return m_dstr.Length(); } const WCHAR * GetText() const { return m_dstr; } BOOL IsHypothesis() const { return m_fHypothesis; } private: CComPtr<ISpRecoResult> m_cpRecoResult; CSpDynamicString m_dstr; BOOL m_fHypothesis; }; /**************************************************************************** * CRecoDlgClass * *---------------* * * This class manages the main application dialog. * ****************************************************************************/ class CRecoDlgClass { friend CDynGrammarDlgClass; // // Public methods // public: CRecoDlgClass(HINSTANCE hInstance) : m_hInstance(hInstance), m_bInSound(FALSE), m_bGotReco(FALSE), m_hfont(NULL) { m_szGrammarFile[0] = 0; } static LRESULT CALLBACK DlgProc(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam); // // Private methods // private: HRESULT Create(BOOL bCreateChecked); BOOL InitDialog(HWND hDlg); HRESULT CreateRecoCtxt(LRESULT ItemData); HRESULT UpdateRecoCtxtState(); void Cleanup(); void Reset(); void RecoEvent(); void SpecifyCAndCGrammar(); void SetWordSequenceData(); void EmulateRecognition(__in WCHAR *pszText); void UpdateGrammarStatusWindow(); HRESULT ConstructRuleDisplay(const SPPHRASERULE *pRule, CSpDynamicString & dstr, ULONG ulLevel); HRESULT ConstructPropertyDisplay(const SPPHRASEELEMENT *pElem, const SPPHRASEPROPERTY *pProp, CSpDynamicString & dstr, ULONG ulLevel); BOOL UpdatePropWindow(const CRecoDlgListItem * pli); HRESULT UpdateGrammarState(WORD wIdOfChangedControl); HRESULT GetTextFile(__deref_out_ecount_opt(*pcch) WCHAR ** ppwszCoMem, __out ULONG * pcch); HRESULT FeedDocumentFromFile(); HRESULT FeedDocumentFromClipboard(); HRESULT FeedDocument(const WCHAR * pwszCoMem, SIZE_T cch); HRESULT TrainFromFile(); int MessageBoxFromResource( UINT uiResource ); // // Member data // private: const HINSTANCE m_hInstance; // Instance handle of process HWND m_hDlg; // Window handle of dialog CComPtr<ISpRecoGrammar> m_cpCFGGrammar; // Loaded CFG grammar CComPtr<ISpVoice> m_cpCFGVoice; CComPtr<ISpRecoGrammar> m_cpITNGrammar; // Loaded ITN cfg grammar CComPtr<ISpRecoGrammar> m_cpDictationGrammar; // Loaded dictation grammar CComPtr<ISpRecoGrammar> m_cpSpellingGrammar; // Loaded spelling grammar CComPtr<ISpRecoContext> m_cpRecoCtxt; // Recognition context CComPtr<ISpRecognizer> m_cpRecognizer; // Recognition instance CComPtr<ISpPhoneConverter> m_cpPhoneConv; // Phone converter BOOL m_bInSound; BOOL m_bGotReco; TCHAR m_szGrammarFile[MAX_PATH]; // Fully qualified file path TCHAR m_szGrammarFileTitle[MAX_PATH]; // Name of the file (no path) LANGID m_langid; HFONT m_hfont; CSpBasicQueue<CDynItem> m_ItemList; }; /**************************************************************************** * CDynGrammarDlgClass * *---------------------* * * This class manages the dynamic rule dialog. * ****************************************************************************/ class CDynGrammarDlgClass { // // Public methods // public: CDynGrammarDlgClass(CRecoDlgClass * pParent, CSpBasicQueue<CDynItem> *pItemList) : m_pParent(pParent) { m_hinstRichEdit = LoadLibrary(_T("riched20.dll")); m_hDynRule = NULL; m_pItemList = pItemList; } ~CDynGrammarDlgClass() { FreeLibrary(m_hinstRichEdit); } static LRESULT CALLBACK DlgProc(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam); // // Private methods // private: BOOL InitDialog(HWND hDlg, CSpBasicQueue<CDynItem> *pItemList); void AddItem(); void Cleanup(); void ClearAll(); // // Member data // private: const CRecoDlgClass * m_pParent; HWND m_hDlg; SPSTATEHANDLE m_hDynRule; HINSTANCE m_hinstRichEdit; CSpBasicQueue<CDynItem> * m_pItemList; }; //=== This is for the alternates pop window /**************************************************************************** * CAlternatesDlgClass * *---------------------* * ****************************************************************************/ #define NUM_ALTS 5 class CAlternatesDlgClass { public: CAlternatesDlgClass() { m_ulNumAltsReturned = 0; memset( m_Alts, 0, NUM_ALTS * sizeof(ISpPhraseAlt*) ); } ~CAlternatesDlgClass() { for( ULONG i = 0; i < m_ulNumAltsReturned; ++i ) { m_Alts[i]->Release(); } } static LRESULT CALLBACK AlternatesDlgProc(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam); //--- Member data ISpRecoResult* m_pResult; ISpPhraseAlt* m_Alts[NUM_ALTS]; ULONG m_ulNumAltsReturned; }; // // Dialog function // LRESULT CALLBACK BetaHelpDlgProc(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam); // // Helper function // inline WCHAR ConfidenceGroupChar(char Confidence) { switch (Confidence) { case SP_LOW_CONFIDENCE: return L'-'; case SP_NORMAL_CONFIDENCE: return L' '; case SP_HIGH_CONFIDENCE: return L'+'; default: _ASSERTE(false); return L'?'; } } #endif // !defined(AFX_RECO_H__BD16E9D0_597E_11D2_960E_00C04F8EE628__INCLUDED_)
[ "chrisg@microsoft.com" ]
chrisg@microsoft.com
7fba9a73b444e7deee6d1c914f4f41d1c7c6aaca
7ffe39937a0ba217632284d7cab2520809a5e0f7
/src/s_core/commands.h
2d012c31950863dd5d6e1abf50f6767b90d9bf69
[]
no_license
Smitt64/Depot
1124b4ba660ddc553dd8f4e7c316e090f67c923e
e72acbfd13b8897ab2698a3fd1f2c7b4dcdf7d39
refs/heads/master
2016-08-04T21:11:37.151525
2011-10-31T18:32:52
2011-10-31T18:32:52
2,018,456
0
0
null
null
null
null
UTF-8
C++
false
false
1,095
h
#ifndef COMMAND_H #define COMMAND_H #include "s_core_global.h" #include <QUndoCommand> #include <QStringList> class S_CORESHARED_EXPORT addThemeCommand : public QUndoCommand { public: addThemeCommand(const QString &title, QUndoCommand *parent = 0); void undo(); void redo(); private: QString theme_title, theme_alias; int row; }; class S_CORESHARED_EXPORT removeThemeCommand : public QUndoCommand { public: removeThemeCommand(const QString &alias, QUndoCommand *parent = 0); void undo(); void redo(); private: QString theme_title, theme_alias; int row; }; class S_CORESHARED_EXPORT addQuestionCommand : public QUndoCommand { public: addQuestionCommand(const QString &type, const QString &alias, const QByteArray &settings, const QString &label, const QStringList &toThemes, QUndoCommand *parent = 0); void undo(); void redo(); private: QString quest_type, quest_alias, quest_label; QStringList qthemes; QByteArray quest_settings; }; #endif // COMMAND_H
[ "smitt64@yandex.ru" ]
smitt64@yandex.ru
ca957c52d3ea5ba275923fde1d560baa7353951e
d50485b09ab650de355e82594f956e45b7d87983
/Seaurchin/ScenePlayer.cpp
dfe6299a21f68c14b03e84202af012dc7a207fc9
[ "Zlib", "BSD-3-Clause", "MIT", "BSL-1.0", "FTL" ]
permissive
nazawa/Seaurchin
6f0b06b37662780656c4c1366555ab5264197d9f
fffa13602ce6ee4413cd34c845293dd7ecd0a375
refs/heads/develop
2021-05-07T15:08:10.823628
2017-11-07T11:57:13
2017-11-07T11:57:13
109,979,714
42
17
null
2017-11-08T13:31:19
2017-11-08T13:31:19
null
SHIFT_JIS
C++
false
false
16,208
cpp
#include "ScenePlayer.h" #include "ScriptSprite.h" #include "ExecutionManager.h" #include "Setting.h" #include "Misc.h" using namespace std; void RegisterPlayerScene(ExecutionManager * manager) { auto engine = manager->GetScriptInterfaceUnsafe()->GetEngine(); engine->RegisterObjectType(SU_IF_PLAY_STATUS, sizeof(PlayStatus), asOBJ_VALUE | asOBJ_POD); engine->RegisterObjectProperty(SU_IF_PLAY_STATUS, "uint32 JusticeCritical", asOFFSET(PlayStatus, JusticeCritical)); engine->RegisterObjectProperty(SU_IF_PLAY_STATUS, "uint32 Justice", asOFFSET(PlayStatus, Justice)); engine->RegisterObjectProperty(SU_IF_PLAY_STATUS, "uint32 Attack", asOFFSET(PlayStatus, Attack)); engine->RegisterObjectProperty(SU_IF_PLAY_STATUS, "uint32 Miss", asOFFSET(PlayStatus, Miss)); engine->RegisterObjectProperty(SU_IF_PLAY_STATUS, "uint32 AllNotes", asOFFSET(PlayStatus, AllNotes)); engine->RegisterObjectProperty(SU_IF_PLAY_STATUS, "uint32 Combo", asOFFSET(PlayStatus, Combo)); engine->RegisterObjectProperty(SU_IF_PLAY_STATUS, "double CurrentGauge", asOFFSET(PlayStatus, CurrentGauge)); engine->RegisterObjectProperty(SU_IF_PLAY_STATUS, "double GaugeDefaultMax", asOFFSET(PlayStatus, GaugeDefaultMax)); engine->RegisterObjectMethod(SU_IF_PLAY_STATUS, "void GetGaugeValue(int &out, double &out)", asMETHOD(PlayStatus, GetGaugeValue), asCALL_THISCALL); engine->RegisterObjectMethod(SU_IF_PLAY_STATUS, "uint32 GetScore()", asMETHOD(PlayStatus, GetScore), asCALL_THISCALL); engine->RegisterObjectType(SU_IF_SCENE_PLAYER, 0, asOBJ_REF); engine->RegisterObjectBehaviour(SU_IF_SCENE_PLAYER, asBEHAVE_ADDREF, "void f()", asMETHOD(ScenePlayer, AddRef), asCALL_THISCALL); engine->RegisterObjectBehaviour(SU_IF_SCENE_PLAYER, asBEHAVE_RELEASE, "void f()", asMETHOD(ScenePlayer, Release), asCALL_THISCALL); engine->RegisterObjectProperty(SU_IF_SCENE_PLAYER, "int Z", asOFFSET(ScenePlayer, ZIndex)); engine->RegisterObjectMethod(SU_IF_SPRITE, SU_IF_SCENE_PLAYER "@ opCast()", asFUNCTION((CastReferenceType<SSprite, ScenePlayer>)), asCALL_CDECL_OBJLAST); engine->RegisterObjectMethod(SU_IF_SCENE_PLAYER, SU_IF_SPRITE "@ opImplCast()", asFUNCTION((CastReferenceType<ScenePlayer, SSprite>)), asCALL_CDECL_OBJLAST); engine->RegisterObjectMethod(SU_IF_SCENE_PLAYER, "void Initialize()", asMETHOD(ScenePlayer, Initialize), asCALL_THISCALL); engine->RegisterObjectMethod(SU_IF_SCENE_PLAYER, "void AdjustCamera(double, double, double)", asMETHOD(ScenePlayer, AdjustCamera), asCALL_THISCALL); engine->RegisterObjectMethod(SU_IF_SCENE_PLAYER, "void SetResource(const string &in, " SU_IF_IMAGE "@)", asMETHOD(ScenePlayer, SetPlayerResource), asCALL_THISCALL); engine->RegisterObjectMethod(SU_IF_SCENE_PLAYER, "void SetResource(const string &in, " SU_IF_FONT "@)", asMETHOD(ScenePlayer, SetPlayerResource), asCALL_THISCALL); engine->RegisterObjectMethod(SU_IF_SCENE_PLAYER, "void SetResource(const string &in, " SU_IF_SOUND "@)", asMETHOD(ScenePlayer, SetPlayerResource), asCALL_THISCALL); engine->RegisterObjectMethod(SU_IF_SCENE_PLAYER, "void SetResource(const string &in, " SU_IF_ANIMEIMAGE "@)", asMETHOD(ScenePlayer, SetPlayerResource), asCALL_THISCALL); engine->RegisterObjectMethod(SU_IF_SCENE_PLAYER, "void Load()", asMETHOD(ScenePlayer, Load), asCALL_THISCALL); engine->RegisterObjectMethod(SU_IF_SCENE_PLAYER, "bool IsLoadCompleted()", asMETHOD(ScenePlayer, IsLoadCompleted), asCALL_THISCALL); engine->RegisterObjectMethod(SU_IF_SCENE_PLAYER, "void Play()", asMETHOD(ScenePlayer, Play), asCALL_THISCALL); engine->RegisterObjectMethod(SU_IF_SCENE_PLAYER, "double GetCurrentTime()", asMETHOD(ScenePlayer, GetPlayingTime), asCALL_THISCALL); engine->RegisterObjectMethod(SU_IF_SCENE_PLAYER, "void GetPlayStatus(" SU_IF_PLAY_STATUS " &out)", asMETHOD(ScenePlayer, GetPlayStatus), asCALL_THISCALL); engine->RegisterObjectMethod(SU_IF_SCENE_PLAYER, "void MovePositionBySecond(double)", asMETHOD(ScenePlayer, MovePositionBySecond), asCALL_THISCALL); engine->RegisterObjectMethod(SU_IF_SCENE_PLAYER, "void MovePositionByMeasure(int)", asMETHOD(ScenePlayer, MovePositionByMeasure), asCALL_THISCALL); } ScenePlayer::ScenePlayer(ExecutionManager *exm) : manager(exm) { soundManager = manager->GetSoundManagerUnsafe(); } ScenePlayer::~ScenePlayer() { Finalize(); } void ScenePlayer::Initialize() { analyzer = make_unique<SusAnalyzer>(192); isLoadCompleted = false; if (manager->ExistsData("AutoPlay") ? manager->GetData<int>("AutoPlay") : 1) { processor = new AutoPlayerProcessor(this); } else { processor = new PlayableProcessor(this); } auto setting = manager->GetSettingInstanceSafe(); HispeedMultiplier = setting->ReadValue<double>("Play", "Hispeed", 6); SoundBufferingLatency = setting->ReadValue<double>("Sound", "BufferLatency", 0.03); LoadResources(); } void ScenePlayer::Finalize() { soundManager->StopGlobal(soundHoldLoop->GetSample()); soundManager->StopGlobal(soundSlideLoop->GetSample()); for (auto& res : resources) res.second->Release(); soundManager->StopGlobal(bgmStream); delete processor; delete bgmStream; fontCombo->Release(); DeleteGraph(hGroundBuffer); DeleteGraph(hBlank); } void ScenePlayer::LoadWorker() { auto mm = manager->GetMusicsManager(); auto scorefile = mm->GetSelectedScorePath(); analyzer->LoadFromFile(scorefile.wstring()); analyzer->RenderScoreData(data); for (auto &note : data) { if (note->Type.test((size_t)SusNoteType::Slide) || note->Type.test((size_t)SusNoteType::AirAction)) CalculateCurves(note); } processor->Reset(); State = PlayingState::BgmNotLoaded; auto file = boost::filesystem::path(scorefile).parent_path() / ConvertUTF8ToUnicode(analyzer->SharedMetaData.UWaveFileName); bgmStream = SoundStream::CreateFromFile(file.wstring().c_str()); State = PlayingState::ReadyToStart; // 前カウントの計算 // WaveOffsetが1小節分より長いとめんどくさそうなので差し引いてく BackingTime = -60.0 / analyzer->GetBpmAt(0, 0) * analyzer->GetBeatsAt(0); NextMetronomeTime = BackingTime; while (BackingTime > analyzer->SharedMetaData.WaveOffset) BackingTime -= 60.0 / analyzer->GetBpmAt(0, 0) * analyzer->GetBeatsAt(0); CurrentTime = BackingTime; { lock_guard<mutex> lock(asyncMutex); isLoadCompleted = true; } } void ScenePlayer::CalculateCurves(std::shared_ptr<SusDrawableNoteData> note) { auto lastStep = note; double segmentsPerSecond = 20; // Buffer上での最小の長さ vector<tuple<double, double>> controlPoints; // lastStepからの時間, X中央位置(0~1) vector<tuple<double, double>> bezierBuffer; controlPoints.push_back(make_tuple(0, (lastStep->StartLane + lastStep->Length / 2.0) / 16.0)); for (auto &slideElement : note->ExtraData) { if (slideElement->Type.test((size_t)SusNoteType::Injection)) continue; if (slideElement->Type.test((size_t)SusNoteType::Control)) { auto cpi = make_tuple(slideElement->StartTime - lastStep->StartTime, (slideElement->StartLane + slideElement->Length / 2.0) / 16.0); controlPoints.push_back(cpi); continue; } // EndかStep controlPoints.push_back(make_tuple(slideElement->StartTime - lastStep->StartTime, (slideElement->StartLane + slideElement->Length / 2.0) / 16.0)); int segmentPoints = segmentsPerSecond * (slideElement->StartTime - lastStep->StartTime) + 2; vector<tuple<double, double>> segmentPositions; for (int j = 0; j < segmentPoints; j++) { double relativeTimeInBlock = j / (double)(segmentPoints - 1); bezierBuffer.clear(); copy(controlPoints.begin(), controlPoints.end(), back_inserter(bezierBuffer)); for (int k = controlPoints.size() - 1; k >= 0; k--) { for (int l = 0; l < k; l++) { auto derivedTime = lerp(relativeTimeInBlock, get<0>(bezierBuffer[l]), get<0>(bezierBuffer[l + 1])); auto derivedPosition = lerp(relativeTimeInBlock, get<1>(bezierBuffer[l]), get<1>(bezierBuffer[l + 1])); bezierBuffer[l] = make_tuple(derivedTime, derivedPosition); } } segmentPositions.push_back(bezierBuffer[0]); } curveData[slideElement] = segmentPositions; lastStep = slideElement; controlPoints.clear(); controlPoints.push_back(make_tuple(0, (slideElement->StartLane + slideElement->Length / 2.0) / 16.0)); } } void ScenePlayer::CalculateNotes(double time, double duration, double preced) { judgeData.clear(); copy_if(data.begin(), data.end(), back_inserter(judgeData), [&](shared_ptr<SusDrawableNoteData> n) { double ptime = time - preced; if (n->Type.to_ulong() & SU_NOTE_LONG_MASK) { // ロング return (ptime <= n->StartTime && n->StartTime <= time + preced) || (ptime <= n->StartTime + n->Duration && n->StartTime + n->Duration <= time + preced) || (n->StartTime <= ptime && time + preced <= n->StartTime + n->Duration); } else { // ショート return (ptime <= n->StartTime && n->StartTime <= time + preced); } }); seenData.clear(); copy_if(data.begin(), data.end(), back_inserter(seenData), [&](shared_ptr<SusDrawableNoteData> n) { double ptime = time - preced; if (n->Type.to_ulong() & SU_NOTE_LONG_MASK) { // ロング if (time > n->StartTime + n->Duration) return false; auto st = n->GetStateAt(time); // 先頭が見えてるならもちろん見える if (n->ModifiedPosition >= -preced && n->ModifiedPosition <= duration) return get<0>(st); // 先頭含めて全部-precedより手前なら見えない if (all_of(n->ExtraData.begin(), n->ExtraData.end(), [preced, duration](shared_ptr<SusDrawableNoteData> en) { if (isnan(en->ModifiedPosition)) return true; if (en->ModifiedPosition < -preced) return true; return false; }) && n->ModifiedPosition < -preced) return false; //先頭含めて全部durationより後なら見えない if (all_of(n->ExtraData.begin(), n->ExtraData.end(), [preced, duration](shared_ptr<SusDrawableNoteData> en) { if (isnan(en->ModifiedPosition)) return true; if (en->ModifiedPosition > duration) return true; return false; }) && n->ModifiedPosition > duration) return false; return true; } else { // ショート if (time > n->StartTime) return false; auto st = n->GetStateAt(time); if (n->ModifiedPosition < -preced || n->ModifiedPosition > duration) return false; return get<0>(st); } }); } void ScenePlayer::Tick(double delta) { textCombo->Tick(delta); for (auto& sprite : spritesPending) sprites.emplace(sprite); spritesPending.clear(); auto i = sprites.begin(); while (i != sprites.end()) { (*i)->Tick(delta); if ((*i)->IsDead) { (*i)->Release(); i = sprites.erase(i); } else { i++; } } if (State >= PlayingState::ReadyCounting) CurrentTime += delta; CurrentSoundTime = CurrentTime + SoundBufferingLatency; if (State >= PlayingState::ReadyCounting) { // ---------------------- // (HSx1000)px / 4beats double referenceBpm = 120.0; // ---------------------- double cbpm = get<1>(analyzer->SharedBpmChanges[0]); for (const auto &bc : analyzer->SharedBpmChanges) { if (get<0>(bc) < CurrentTime) break; cbpm = get<1>(bc); } double bpmMultiplier = (cbpm / analyzer->SharedMetaData.BaseBpm); double sizeFor4Beats = bpmMultiplier * HispeedMultiplier * 1000.0; double seenRatio = (SU_LANE_Z_MAX - SU_LANE_Z_MIN) / sizeFor4Beats; SeenDuration = 60.0 * 4.0 * seenRatio / referenceBpm; CalculateNotes(CurrentTime, SeenDuration, PreloadingTime); } int pCombo = Status.Combo; processor->Update(judgeData); Status = *processor->GetPlayStatus(); if (Status.Combo > pCombo) { textCombo->AbortMove(true); textCombo->Apply("scaleY:8.4, scaleX:8.4"); textCombo->AddMove("scale_to(x:8, y:8, time:0.2, ease:out_quad)"); } UpdateSlideEffect(); } void ScenePlayer::ProcessSound() { double ActualOffset = analyzer->SharedMetaData.WaveOffset - SoundBufferingLatency; if (State < PlayingState::ReadyCounting) return; switch (State) { case PlayingState::ReadyCounting: if (ActualOffset < 0 && CurrentTime >= ActualOffset) { soundManager->PlayGlobal(bgmStream); State = PlayingState::BgmPreceding; } else if (CurrentTime >= 0) { State = PlayingState::OnlyScoreOngoing; } else if (NextMetronomeTime < 0 && CurrentTime >= NextMetronomeTime) { //TODO: NextMetronomeにもLatency適用? soundManager->PlayGlobal(soundTap->GetSample()); NextMetronomeTime += 60 / analyzer->GetBpmAt(0, 0); } break; case PlayingState::BgmPreceding: if (CurrentTime >= 0) State = PlayingState::BothOngoing; break; case PlayingState::OnlyScoreOngoing: if (CurrentTime >= ActualOffset) { soundManager->PlayGlobal(bgmStream); State = PlayingState::BothOngoing; } break; case PlayingState::BothOngoing: // BgmLastingは実質なさそうですね… //TODO: 曲の再生に応じてScoreLastingへ移行 break; } } // スクリプト側から呼べるやつら void ScenePlayer::Load() { thread loadThread([&] { LoadWorker(); }); loadThread.detach(); //LoadWorker(); } bool ScenePlayer::IsLoadCompleted() { lock_guard<mutex> lock(asyncMutex); return isLoadCompleted; } void ScenePlayer::SetPlayerResource(const string & name, SResource * resource) { if (resources.find(name) != resources.end()) resources[name]->Release(); resources[name] = resource; } void ScenePlayer::Play() { if (State < PlayingState::ReadyToStart) return; State = PlayingState::ReadyCounting; } double ScenePlayer::GetPlayingTime() { return CurrentTime; } void ScenePlayer::GetPlayStatus(PlayStatus *status) { *status = Status; } void ScenePlayer::MovePositionBySecond(double sec) { //実際に動いた時間で計算せよ if (State < PlayingState::BothOngoing) return; double gap = analyzer->SharedMetaData.WaveOffset - SoundBufferingLatency; double oldBgmPos = bgmStream->GetPlayingPosition(); double oldTime = CurrentTime; int oldMeas = get<0>(analyzer->GetRelativeTime(CurrentTime)); double newTime = oldTime + sec; double newBgmPos = oldBgmPos + (newTime - oldTime); newBgmPos = max(0.0, newBgmPos); bgmStream->SetPlayingPosition(newBgmPos); CurrentTime = newBgmPos + gap; processor->MovePosition(CurrentTime - oldTime); } void ScenePlayer::MovePositionByMeasure(int meas) { if (State < PlayingState::BothOngoing) return; double gap = analyzer->SharedMetaData.WaveOffset - SoundBufferingLatency; double oldBgmPos = bgmStream->GetPlayingPosition(); double oldTime = CurrentTime; int oldMeas = get<0>(analyzer->GetRelativeTime(CurrentTime)); double newTime = analyzer->GetAbsoluteTime(max(0, oldMeas + meas), 0); double newBgmPos = oldBgmPos + (newTime - oldTime); newBgmPos = max(0.0, newBgmPos); bgmStream->SetPlayingPosition(newBgmPos); CurrentTime = newBgmPos + gap; processor->MovePosition(CurrentTime - oldTime); } void ScenePlayer::AdjustCamera(double cy, double cz, double ctz) { cameraY += cy; cameraZ += cz; cameraTargetZ += ctz; }
[ "kb10uy@live.jp" ]
kb10uy@live.jp
b2169820e962f3aec98f0113a65ba004890dd585
b999e8c802019a6eaa1ce4bb8d054349a37eee25
/third_party/externals/angle2/src/libANGLE/validationES2.h
92da7cca94485f64d12378cf27c9153744d35972
[ "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference" ]
permissive
kniefliu/skia
a647dd2011660f72c946362aad24f8d44836f928
f7d3ea6d9ec7a3d8ef17456cc23da7291737c680
refs/heads/master
2021-06-09T02:42:35.989816
2020-03-22T09:28:02
2020-03-22T09:28:02
150,810,052
4
4
null
null
null
null
UTF-8
C++
false
false
36,331
h
// // Copyright (c) 2013 The ANGLE Project Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // // validationES2.h: Validation functions for OpenGL ES 2.0 entry point parameters #ifndef LIBANGLE_VALIDATION_ES2_H_ #define LIBANGLE_VALIDATION_ES2_H_ #include <GLES2/gl2.h> #include <GLES2/gl2ext.h> namespace gl { class Context; class ValidationContext; bool ValidateES2TexStorageParameters(Context *context, GLenum target, GLsizei levels, GLenum internalformat, GLsizei width, GLsizei height); bool ValidateDiscardFramebufferEXT(Context *context, GLenum target, GLsizei numAttachments, const GLenum *attachments); bool ValidateDrawBuffersEXT(ValidationContext *context, GLsizei n, const GLenum *bufs); bool ValidateBindVertexArrayOES(Context *context, GLuint array); bool ValidateDeleteVertexArraysOES(Context *context, GLsizei n); bool ValidateGenVertexArraysOES(Context *context, GLsizei n); bool ValidateIsVertexArrayOES(Context *context); bool ValidateProgramBinaryOES(Context *context, GLuint program, GLenum binaryFormat, const void *binary, GLint length); bool ValidateGetProgramBinaryOES(Context *context, GLuint program, GLsizei bufSize, GLsizei *length, GLenum *binaryFormat, void *binary); // GL_KHR_debug bool ValidateDebugMessageControlKHR(Context *context, GLenum source, GLenum type, GLenum severity, GLsizei count, const GLuint *ids, GLboolean enabled); bool ValidateDebugMessageInsertKHR(Context *context, GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const GLchar *buf); bool ValidateDebugMessageCallbackKHR(Context *context, GLDEBUGPROCKHR callback, const void *userParam); bool ValidateGetDebugMessageLogKHR(Context *context, GLuint count, GLsizei bufSize, GLenum *sources, GLenum *types, GLuint *ids, GLenum *severities, GLsizei *lengths, GLchar *messageLog); bool ValidatePushDebugGroupKHR(Context *context, GLenum source, GLuint id, GLsizei length, const GLchar *message); bool ValidatePopDebugGroupKHR(Context *context); bool ValidateObjectLabelKHR(Context *context, GLenum identifier, GLuint name, GLsizei length, const GLchar *label); bool ValidateGetObjectLabelKHR(Context *context, GLenum identifier, GLuint name, GLsizei bufSize, GLsizei *length, GLchar *label); bool ValidateObjectPtrLabelKHR(Context *context, const void *ptr, GLsizei length, const GLchar *label); bool ValidateGetObjectPtrLabelKHR(Context *context, const void *ptr, GLsizei bufSize, GLsizei *length, GLchar *label); bool ValidateGetPointervKHR(Context *context, GLenum pname, void **params); bool ValidateBlitFramebufferANGLE(Context *context, GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1, GLint dstX0, GLint dstY0, GLint dstX1, GLint dstY1, GLbitfield mask, GLenum filter); bool ValidateClear(ValidationContext *context, GLbitfield mask); bool ValidateTexImage2D(Context *context, GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, const void *pixels); bool ValidateTexImage2DRobust(Context *context, GLenum target, GLint level, GLint internalformat, GLsizei width, GLsizei height, GLint border, GLenum format, GLenum type, GLsizei bufSize, const void *pixels); bool ValidateTexSubImage2D(Context *context, GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLenum type, const void *pixels); bool ValidateTexSubImage2DRobustANGLE(Context *context, GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLenum type, GLsizei bufSize, const void *pixels); bool ValidateCompressedTexImage2D(Context *context, GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, GLsizei imageSize, const void *data); bool ValidateCompressedTexSubImage2D(Context *context, GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLsizei imageSize, const void *data); bool ValidateCompressedTexImage2DRobustANGLE(Context *context, GLenum target, GLint level, GLenum internalformat, GLsizei width, GLsizei height, GLint border, GLsizei imageSize, GLsizei dataSize, const void *data); bool ValidateCompressedTexSubImage2DRobustANGLE(Context *context, GLenum target, GLint level, GLint xoffset, GLint yoffset, GLsizei width, GLsizei height, GLenum format, GLsizei imageSize, GLsizei dataSize, const void *data); bool ValidateBindTexture(Context *context, GLenum target, GLuint texture); bool ValidateGetBufferPointervOES(Context *context, GLenum target, GLenum pname, void **params); bool ValidateMapBufferOES(Context *context, GLenum target, GLenum access); bool ValidateUnmapBufferOES(Context *context, GLenum target); bool ValidateMapBufferRangeEXT(Context *context, GLenum target, GLintptr offset, GLsizeiptr length, GLbitfield access); bool ValidateMapBufferBase(Context *context, GLenum target); bool ValidateFlushMappedBufferRangeEXT(Context *context, GLenum target, GLintptr offset, GLsizeiptr length); bool ValidateBindUniformLocationCHROMIUM(Context *context, GLuint program, GLint location, const GLchar *name); bool ValidateCoverageModulationCHROMIUM(Context *context, GLenum components); // CHROMIUM_path_rendering bool ValidateMatrix(Context *context, GLenum matrixMode, const GLfloat *matrix); bool ValidateMatrixMode(Context *context, GLenum matrixMode); bool ValidateGenPaths(Context *context, GLsizei range); bool ValidateDeletePaths(Context *context, GLuint first, GLsizei range); bool ValidatePathCommands(Context *context, GLuint path, GLsizei numCommands, const GLubyte *commands, GLsizei numCoords, GLenum coordType, const void *coords); bool ValidateSetPathParameter(Context *context, GLuint path, GLenum pname, GLfloat value); bool ValidateGetPathParameter(Context *context, GLuint path, GLenum pname, GLfloat *value); bool ValidatePathStencilFunc(Context *context, GLenum func, GLint ref, GLuint mask); bool ValidateStencilFillPath(Context *context, GLuint path, GLenum fillMode, GLuint mask); bool ValidateStencilStrokePath(Context *context, GLuint path, GLint reference, GLuint mask); bool ValidateCoverPath(Context *context, GLuint path, GLenum coverMode); bool ValidateStencilThenCoverFillPath(Context *context, GLuint path, GLenum fillMode, GLuint mask, GLenum coverMode); bool ValidateStencilThenCoverStrokePath(Context *context, GLuint path, GLint reference, GLuint mask, GLenum coverMode); bool ValidateIsPath(Context *context); bool ValidateCoverFillPathInstanced(Context *context, GLsizei numPaths, GLenum pathNameType, const void *paths, GLuint pathBase, GLenum coverMode, GLenum transformType, const GLfloat *transformValues); bool ValidateCoverStrokePathInstanced(Context *context, GLsizei numPaths, GLenum pathNameType, const void *paths, GLuint pathBase, GLenum coverMode, GLenum transformType, const GLfloat *transformValues); bool ValidateStencilFillPathInstanced(Context *context, GLsizei numPaths, GLenum pathNameType, const void *paths, GLuint pathBAse, GLenum fillMode, GLuint mask, GLenum transformType, const GLfloat *transformValues); bool ValidateStencilStrokePathInstanced(Context *context, GLsizei numPaths, GLenum pathNameType, const void *paths, GLuint pathBase, GLint reference, GLuint mask, GLenum transformType, const GLfloat *transformValues); bool ValidateStencilThenCoverFillPathInstanced(Context *context, GLsizei numPaths, GLenum pathNameType, const void *paths, GLuint pathBase, GLenum fillMode, GLuint mask, GLenum coverMode, GLenum transformType, const GLfloat *transformValues); bool ValidateStencilThenCoverStrokePathInstanced(Context *context, GLsizei numPaths, GLenum pathNameType, const void *paths, GLuint pathBase, GLint reference, GLuint mask, GLenum coverMode, GLenum transformType, const GLfloat *transformValues); bool ValidateBindFragmentInputLocation(Context *context, GLuint program, GLint location, const GLchar *name); bool ValidateProgramPathFragmentInputGen(Context *context, GLuint program, GLint location, GLenum genMode, GLint components, const GLfloat *coeffs); bool ValidateCopyTextureCHROMIUM(Context *context, GLuint sourceId, GLint sourceLevel, GLenum destTarget, GLuint destId, GLint destLevel, GLint internalFormat, GLenum destType, GLboolean unpackFlipY, GLboolean unpackPremultiplyAlpha, GLboolean unpackUnmultiplyAlpha); bool ValidateCopySubTextureCHROMIUM(Context *context, GLuint sourceId, GLint sourceLevel, GLenum destTarget, GLuint destId, GLint destLevel, GLint xoffset, GLint yoffset, GLint x, GLint y, GLsizei width, GLsizei height, GLboolean unpackFlipY, GLboolean unpackPremultiplyAlpha, GLboolean unpackUnmultiplyAlpha); bool ValidateCompressedCopyTextureCHROMIUM(Context *context, GLuint sourceId, GLuint destId); bool ValidateCreateShader(Context *context, GLenum type); bool ValidateBufferData(ValidationContext *context, GLenum target, GLsizeiptr size, const void *data, GLenum usage); bool ValidateBufferSubData(ValidationContext *context, GLenum target, GLintptr offset, GLsizeiptr size, const void *data); bool ValidateRequestExtensionANGLE(ValidationContext *context, const GLchar *name); bool ValidateActiveTexture(ValidationContext *context, GLenum texture); bool ValidateAttachShader(ValidationContext *context, GLuint program, GLuint shader); bool ValidateBindAttribLocation(ValidationContext *context, GLuint program, GLuint index, const GLchar *name); bool ValidateBindBuffer(ValidationContext *context, GLenum target, GLuint buffer); bool ValidateBindFramebuffer(ValidationContext *context, GLenum target, GLuint framebuffer); bool ValidateBindRenderbuffer(ValidationContext *context, GLenum target, GLuint renderbuffer); bool ValidateBlendColor(ValidationContext *context, GLclampf red, GLclampf green, GLclampf blue, GLclampf alpha); bool ValidateBlendEquation(ValidationContext *context, GLenum mode); bool ValidateBlendEquationSeparate(ValidationContext *context, GLenum modeRGB, GLenum modeAlpha); bool ValidateBlendFunc(ValidationContext *context, GLenum sfactor, GLenum dfactor); bool ValidateBlendFuncSeparate(ValidationContext *context, GLenum srcRGB, GLenum dstRGB, GLenum srcAlpha, GLenum dstAlpha); bool ValidateGetString(Context *context, GLenum name); bool ValidateLineWidth(ValidationContext *context, GLfloat width); bool ValidateVertexAttribPointer(ValidationContext *context, GLuint index, GLint size, GLenum type, GLboolean normalized, GLsizei stride, const void *ptr); bool ValidateDepthRangef(ValidationContext *context, GLclampf zNear, GLclampf zFar); bool ValidateRenderbufferStorage(ValidationContext *context, GLenum target, GLenum internalformat, GLsizei width, GLsizei height); bool ValidateRenderbufferStorageMultisampleANGLE(ValidationContext *context, GLenum target, GLsizei samples, GLenum internalformat, GLsizei width, GLsizei height); bool ValidateCheckFramebufferStatus(ValidationContext *context, GLenum target); bool ValidateClearColor(ValidationContext *context, GLclampf red, GLclampf green, GLclampf blue, GLclampf alpha); bool ValidateClearDepthf(ValidationContext *context, GLclampf depth); bool ValidateClearStencil(ValidationContext *context, GLint s); bool ValidateColorMask(ValidationContext *context, GLboolean red, GLboolean green, GLboolean blue, GLboolean alpha); bool ValidateCompileShader(ValidationContext *context, GLuint shader); bool ValidateCreateProgram(ValidationContext *context); bool ValidateCullFace(ValidationContext *context, GLenum mode); bool ValidateDeleteProgram(ValidationContext *context, GLuint program); bool ValidateDeleteShader(ValidationContext *context, GLuint shader); bool ValidateDepthFunc(ValidationContext *context, GLenum func); bool ValidateDepthMask(ValidationContext *context, GLboolean flag); bool ValidateDetachShader(ValidationContext *context, GLuint program, GLuint shader); bool ValidateDisableVertexAttribArray(ValidationContext *context, GLuint index); bool ValidateEnableVertexAttribArray(ValidationContext *context, GLuint index); bool ValidateFinish(ValidationContext *context); bool ValidateFlush(ValidationContext *context); bool ValidateFrontFace(ValidationContext *context, GLenum mode); bool ValidateGetActiveAttrib(ValidationContext *context, GLuint program, GLuint index, GLsizei bufsize, GLsizei *length, GLint *size, GLenum *type, GLchar *name); bool ValidateGetActiveUniform(ValidationContext *context, GLuint program, GLuint index, GLsizei bufsize, GLsizei *length, GLint *size, GLenum *type, GLchar *name); bool ValidateGetAttachedShaders(ValidationContext *context, GLuint program, GLsizei maxcount, GLsizei *count, GLuint *shaders); bool ValidateGetAttribLocation(ValidationContext *context, GLuint program, const GLchar *name); bool ValidateGetBooleanv(ValidationContext *context, GLenum pname, GLboolean *params); bool ValidateGetError(ValidationContext *context); bool ValidateGetFloatv(ValidationContext *context, GLenum pname, GLfloat *params); bool ValidateGetIntegerv(ValidationContext *context, GLenum pname, GLint *params); bool ValidateGetProgramInfoLog(ValidationContext *context, GLuint program, GLsizei bufsize, GLsizei *length, GLchar *infolog); bool ValidateGetShaderInfoLog(ValidationContext *context, GLuint shader, GLsizei bufsize, GLsizei *length, GLchar *infolog); bool ValidateGetShaderPrecisionFormat(ValidationContext *context, GLenum shadertype, GLenum precisiontype, GLint *range, GLint *precision); bool ValidateGetShaderSource(ValidationContext *context, GLuint shader, GLsizei bufsize, GLsizei *length, GLchar *source); bool ValidateGetUniformLocation(ValidationContext *context, GLuint program, const GLchar *name); bool ValidateHint(ValidationContext *context, GLenum target, GLenum mode); bool ValidateIsBuffer(ValidationContext *context, GLuint buffer); bool ValidateIsFramebuffer(ValidationContext *context, GLuint framebuffer); bool ValidateIsProgram(ValidationContext *context, GLuint program); bool ValidateIsRenderbuffer(ValidationContext *context, GLuint renderbuffer); bool ValidateIsShader(ValidationContext *context, GLuint shader); bool ValidateIsTexture(ValidationContext *context, GLuint texture); bool ValidatePixelStorei(ValidationContext *context, GLenum pname, GLint param); bool ValidatePolygonOffset(ValidationContext *context, GLfloat factor, GLfloat units); bool ValidateReleaseShaderCompiler(ValidationContext *context); bool ValidateSampleCoverage(ValidationContext *context, GLclampf value, GLboolean invert); bool ValidateScissor(ValidationContext *context, GLint x, GLint y, GLsizei width, GLsizei height); bool ValidateShaderBinary(ValidationContext *context, GLsizei n, const GLuint *shaders, GLenum binaryformat, const void *binary, GLsizei length); bool ValidateShaderSource(ValidationContext *context, GLuint shader, GLsizei count, const GLchar *const *string, const GLint *length); bool ValidateStencilFunc(ValidationContext *context, GLenum func, GLint ref, GLuint mask); bool ValidateStencilFuncSeparate(ValidationContext *context, GLenum face, GLenum func, GLint ref, GLuint mask); bool ValidateStencilMask(ValidationContext *context, GLuint mask); bool ValidateStencilMaskSeparate(ValidationContext *context, GLenum face, GLuint mask); bool ValidateStencilOp(ValidationContext *context, GLenum fail, GLenum zfail, GLenum zpass); bool ValidateStencilOpSeparate(ValidationContext *context, GLenum face, GLenum fail, GLenum zfail, GLenum zpass); bool ValidateUniform1f(ValidationContext *context, GLint location, GLfloat x); bool ValidateUniform1fv(ValidationContext *context, GLint location, GLsizei count, const GLfloat *v); bool ValidateUniform1i(ValidationContext *context, GLint location, GLint x); bool ValidateUniform2f(ValidationContext *context, GLint location, GLfloat x, GLfloat y); bool ValidateUniform2fv(ValidationContext *context, GLint location, GLsizei count, const GLfloat *v); bool ValidateUniform2i(ValidationContext *context, GLint location, GLint x, GLint y); bool ValidateUniform2iv(ValidationContext *context, GLint location, GLsizei count, const GLint *v); bool ValidateUniform3f(ValidationContext *context, GLint location, GLfloat x, GLfloat y, GLfloat z); bool ValidateUniform3fv(ValidationContext *context, GLint location, GLsizei count, const GLfloat *v); bool ValidateUniform3i(ValidationContext *context, GLint location, GLint x, GLint y, GLint z); bool ValidateUniform3iv(ValidationContext *context, GLint location, GLsizei count, const GLint *v); bool ValidateUniform4f(ValidationContext *context, GLint location, GLfloat x, GLfloat y, GLfloat z, GLfloat w); bool ValidateUniform4fv(ValidationContext *context, GLint location, GLsizei count, const GLfloat *v); bool ValidateUniform4i(ValidationContext *context, GLint location, GLint x, GLint y, GLint z, GLint w); bool ValidateUniform4iv(ValidationContext *context, GLint location, GLsizei count, const GLint *v); bool ValidateUniformMatrix2fv(ValidationContext *context, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); bool ValidateUniformMatrix3fv(ValidationContext *context, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); bool ValidateUniformMatrix4fv(ValidationContext *context, GLint location, GLsizei count, GLboolean transpose, const GLfloat *value); bool ValidateValidateProgram(ValidationContext *context, GLuint program); bool ValidateVertexAttrib1f(ValidationContext *context, GLuint index, GLfloat x); bool ValidateVertexAttrib1fv(ValidationContext *context, GLuint index, const GLfloat *values); bool ValidateVertexAttrib2f(ValidationContext *context, GLuint index, GLfloat x, GLfloat y); bool ValidateVertexAttrib2fv(ValidationContext *context, GLuint index, const GLfloat *values); bool ValidateVertexAttrib3f(ValidationContext *context, GLuint index, GLfloat x, GLfloat y, GLfloat z); bool ValidateVertexAttrib3fv(ValidationContext *context, GLuint index, const GLfloat *values); bool ValidateVertexAttrib4f(ValidationContext *context, GLuint index, GLfloat x, GLfloat y, GLfloat z, GLfloat w); bool ValidateVertexAttrib4fv(ValidationContext *context, GLuint index, const GLfloat *values); bool ValidateViewport(ValidationContext *context, GLint x, GLint y, GLsizei width, GLsizei height); bool ValidateDrawElements(ValidationContext *context, GLenum mode, GLsizei count, GLenum type, const void *indices); bool ValidateDrawArrays(ValidationContext *context, GLenum mode, GLint first, GLsizei count); bool ValidateGetFramebufferAttachmentParameteriv(ValidationContext *context, GLenum target, GLenum attachment, GLenum pname, GLint *params); bool ValidateGetProgramiv(ValidationContext *context, GLuint program, GLenum pname, GLint *params); bool ValidateCopyTexImage2D(ValidationContext *context, GLenum target, GLint level, GLenum internalformat, GLint x, GLint y, GLsizei width, GLsizei height, GLint border); bool ValidateCopyTexSubImage2D(Context *context, GLenum target, GLint level, GLint xoffset, GLint yoffset, GLint x, GLint y, GLsizei width, GLsizei height); bool ValidateDeleteBuffers(Context *context, GLint n, const GLuint *buffers); bool ValidateDeleteFramebuffers(Context *context, GLint n, const GLuint *framebuffers); bool ValidateDeleteRenderbuffers(Context *context, GLint n, const GLuint *renderbuffers); bool ValidateDeleteTextures(Context *context, GLint n, const GLuint *textures); bool ValidateDisable(Context *context, GLenum cap); bool ValidateEnable(Context *context, GLenum cap); bool ValidateFramebufferRenderbuffer(Context *context, GLenum target, GLenum attachment, GLenum renderbuffertarget, GLuint renderbuffer); bool ValidateFramebufferTexture2D(Context *context, GLenum target, GLenum attachment, GLenum textarget, GLuint texture, GLint level); bool ValidateGenBuffers(Context *context, GLint n, GLuint *buffers); bool ValidateGenerateMipmap(Context *context, GLenum target); bool ValidateGenFramebuffers(Context *context, GLint n, GLuint *framebuffers); bool ValidateGenRenderbuffers(Context *context, GLint n, GLuint *renderbuffers); bool ValidateGenTextures(Context *context, GLint n, GLuint *textures); bool ValidateGetBufferParameteriv(ValidationContext *context, GLenum target, GLenum pname, GLint *params); bool ValidateGetRenderbufferParameteriv(Context *context, GLenum target, GLenum pname, GLint *params); bool ValidateGetShaderiv(Context *context, GLuint shader, GLenum pname, GLint *params); bool ValidateGetTexParameterfv(Context *context, GLenum target, GLenum pname, GLfloat *params); bool ValidateGetTexParameteriv(Context *context, GLenum target, GLenum pname, GLint *params); bool ValidateGetUniformfv(Context *context, GLuint program, GLint location, GLfloat *params); bool ValidateGetUniformiv(Context *context, GLuint program, GLint location, GLint *params); bool ValidateGetVertexAttribfv(Context *context, GLuint index, GLenum pname, GLfloat *params); bool ValidateGetVertexAttribiv(Context *context, GLuint index, GLenum pname, GLint *params); bool ValidateGetVertexAttribPointerv(Context *context, GLuint index, GLenum pname, void **pointer); bool ValidateIsEnabled(Context *context, GLenum cap); bool ValidateLinkProgram(Context *context, GLuint program); bool ValidateReadPixels(Context *context, GLint x, GLint y, GLsizei width, GLsizei height, GLenum format, GLenum type, void *pixels); bool ValidateTexParameterf(Context *context, GLenum target, GLenum pname, GLfloat param); bool ValidateTexParameterfv(Context *context, GLenum target, GLenum pname, const GLfloat *params); bool ValidateTexParameteri(Context *context, GLenum target, GLenum pname, GLint param); bool ValidateTexParameteriv(Context *context, GLenum target, GLenum pname, const GLint *params); bool ValidateUniform1iv(ValidationContext *context, GLint location, GLsizei count, const GLint *value); bool ValidateUseProgram(Context *context, GLuint program); } // namespace gl #endif // LIBANGLE_VALIDATION_ES2_H_
[ "liuxiufeng@qiyi.com" ]
liuxiufeng@qiyi.com
d1a1b9df1b7e43919c07251f2859940698fac8b9
e2ae2ef89d635272ca45d3ed80518b4ab0d21647
/cub/string/Scanner.cc
653423257e145b2172b990d445071fc6e5ed1c8b
[ "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
XJTUeducation/cub
02a2ece287b3354a9198d1f9c232cfa0e6a4bf1e
869b52073c0d4463e063a64c2ab3b4fb0fb1106d
refs/heads/master
2020-04-10T10:10:27.661335
2018-09-26T02:31:16
2018-09-26T02:31:16
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,535
cc
#include "cub/string/Scanner.h" CUB_NS_BEGIN Scanner::Scanner(StringView source) : cur(source) { restartCapture(); } Scanner& Scanner::one(CharSpec spec) { if (cur.empty() || !spec(cur[0])) { return onError(); } cur.removePrefix(1); return *this; } Scanner& Scanner::optional(StringView s) { cur.consumePrefix(s); return *this; } Scanner& Scanner::literal(StringView s) { return cur.consumePrefix(s) ? *this : onError(); } Scanner& Scanner::any(CharSpec spec) { while (!cur.empty() && spec(cur[0])) { cur.removePrefix(1); } return *this; } Scanner& Scanner::many(CharSpec spec) { return one(spec).any(spec); } Scanner& Scanner::until(CharSpec spec) { any(is_not(spec)); return cur.empty() ? onError() : *this; } Scanner& Scanner::restartCapture() { start = cur.data(); end = nullptr; return *this; } Scanner& Scanner::stopCapture() { end = cur.data(); return *this; } Scanner& Scanner::eos() { if (!cur.empty()) error = true; return *this; } Scanner& Scanner::onError() { error = true; return *this; } char Scanner::peek(char defaultValue) const { return cur.empty() ? defaultValue : cur[0]; } int Scanner::empty() const { return cur.empty(); } bool Scanner::result(StringView* remain, StringView* capture) { if (error) { return false; } if (remain != nullptr) { *remain = cur; } if (capture != nullptr) { auto last = (end == nullptr ? cur.data() : end); *capture = StringView(start, last - start); } return true; } CUB_NS_END
[ "horance@aliyun.com" ]
horance@aliyun.com
8f613aefdbb7343820c1d0b88d8cdca68563b4b1
c7237c17023b0970b56f1b91a97d72a3f0f0f206
/Source/PluginEditor.cpp
d96956a08fe457b1af719f9eb51a630331081ee8
[]
no_license
KMACDO202/AmbiEncoder
fb812f576c8284e9f43b27f72c474dd3d9c7c54b
3b5bd1033c3ee24602aa53eb08ea155f0bf40e01
refs/heads/master
2021-01-22T10:57:19.673885
2017-02-15T13:49:47
2017-02-15T13:49:47
82,058,141
0
0
null
null
null
null
UTF-8
C++
false
false
4,668
cpp
/* ============================================================================== This is an automatically generated GUI class created by the Projucer! Be careful when adding custom code to these files, as only the code within the "//[xyz]" and "//[/xyz]" sections will be retained when the file is loaded and re-saved. Created with Projucer version: 4.3.0 ------------------------------------------------------------------------------ The Projucer is part of the JUCE library - "Jules' Utility Class Extensions" Copyright (c) 2015 - ROLI Ltd. ============================================================================== */ //[Headers] You can add your own extra header files here... //[/Headers] #include "PluginEditor.h" //[MiscUserDefs] You can add your own user definitions and misc code here... //[/MiscUserDefs] //============================================================================== AmbiEncoderAudioProcessorEditor::AmbiEncoderAudioProcessorEditor (AmbiEncoderAudioProcessor& p) : AudioProcessorEditor(p), processor(p) { //[Constructor_pre] You can add your own custom stuff here.. //[/Constructor_pre] addAndMakeVisible (sliderPanPosition = new Slider ("new slider")); sliderPanPosition->setRange (0, 360, 0); sliderPanPosition->setSliderStyle (Slider::LinearHorizontal); sliderPanPosition->setTextBoxStyle (Slider::TextBoxLeft, false, 80, 20); sliderPanPosition->addListener (this); //[UserPreSize] //[/UserPreSize] setSize (600, 400); //[Constructor] You can add your own custom stuff here.. startTimer(200);//starts timer with interval of 200mS //[/Constructor] } AmbiEncoderAudioProcessorEditor::~AmbiEncoderAudioProcessorEditor() { //[Destructor_pre]. You can add your own custom destruction code here.. //[/Destructor_pre] sliderPanPosition = nullptr; //[Destructor]. You can add your own custom destruction code here.. //[/Destructor] } //============================================================================== void AmbiEncoderAudioProcessorEditor::paint (Graphics& g) { //[UserPrePaint] Add your own custom painting code here.. //[/UserPrePaint] g.fillAll (Colours::white); //[UserPaint] Add your own custom painting code here.. //[/UserPaint] } void AmbiEncoderAudioProcessorEditor::resized() { //[UserPreResize] Add your own custom resize code here.. //[/UserPreResize] sliderPanPosition->setBounds (64, 64, 240, 32); //[UserResized] Add your own custom resize handling here.. //[/UserResized] } void AmbiEncoderAudioProcessorEditor::sliderValueChanged (Slider* sliderThatWasMoved) { //[UsersliderValueChanged_Pre] //[/UsersliderValueChanged_Pre] if (sliderThatWasMoved == sliderPanPosition) { //[UserSliderCode_sliderPanPosition] -- add your slider handling code here.. //[/UserSliderCode_sliderPanPosition] } //[UsersliderValueChanged_Post] //[/UsersliderValueChanged_Post] } //[MiscUserCode] You can add your own definitions of your custom methods or any other code here... void AmbiEncoderAudioProcessorEditor::timerCallback() { //exchange any data you want between UI elements and the Plugin "ourProcessor" } //[/MiscUserCode] //============================================================================== #if 0 /* -- Projucer information section -- This is where the Projucer stores the metadata that describe this GUI layout, so make changes in here at your peril! BEGIN_JUCER_METADATA <JUCER_COMPONENT documentType="Component" className="AmbiEncoderAudioProcessorEditor" componentName="" parentClasses="public AudioProcessorEditor, public Timer" constructorParams="StereoPannerAudioProcessor&amp; p" variableInitialisers="AudioProcessorEditor(p), processor(p)" snapPixels="8" snapActive="1" snapShown="1" overlayOpacity="0.330" fixedSize="0" initialWidth="600" initialHeight="400"> <BACKGROUND backgroundColour="ffffffff"/> <SLIDER name="new slider" id="62fc45f6b7b51c4" memberName="sliderPanPosition" virtualName="" explicitFocusOrder="0" pos="64 64 240 32" min="0" max="360" int="0" style="LinearHorizontal" textBoxPos="TextBoxLeft" textBoxEditable="1" textBoxWidth="80" textBoxHeight="20" skewFactor="1" needsCallback="1"/> </JUCER_COMPONENT> END_JUCER_METADATA */ #endif //[EndFile] You can add extra defines here... //[/EndFile]
[ "kmacdo202@lab-m329-mac-11.enterprise.gcal.ac.uk" ]
kmacdo202@lab-m329-mac-11.enterprise.gcal.ac.uk
bf84913a76c0ba2b7e423f61c4ffbe1ec3960b6a
b7536dc2604a7fe8b4ac430f753d17b4506f2c3b
/include/FlatNVG/graphics-pathiterator.h
1104f62e98f6aed2199d88dda6d3cf23fdc9e42c
[]
no_license
VB6Hobbyst7/wasm-gdiplus
dc5ddf10d7f58978da4b788facf2dc728eea4417
b6af72bbee832e2afb40b6ff6812f55c3997f484
refs/heads/master
2023-03-16T07:49:30.761335
2021-01-07T14:43:14
2021-01-07T14:43:14
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,838
h
/* * 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. * * Authors: * Duncan Mak (duncan@ximian.com) * Ravindra (rkumar@novell.com) * Sebastien Pouliot <sebastien@ximian.com> * * Copyright (C) 2003, 2006-2007 Novell, Inc (http://www.novell.com) */ #ifndef __GRAPHICS_PATHITERATOR_H__ #define __GRAPHICS_PATHITERATOR_H__ #include "GdiPlusFlatImpl.h" namespace DLLExports { GpStatus WINGDIPAPI GdipCreatePathIter(GpPathIterator** iterator, GpPath* path); GpStatus WINGDIPAPI GdipDeletePathIter(GpPathIterator* iterator); GpStatus WINGDIPAPI GdipPathIterGetCount(GpPathIterator* iterator, INT* count); GpStatus WINGDIPAPI GdipPathIterGetSubpathCount(GpPathIterator* iterator, INT* count); GpStatus WINGDIPAPI GdipPathIterCopyData(GpPathIterator* iterator, INT* resultCount, GpPointF* points, BYTE* types, INT startIndex, INT endIndex); GpStatus WINGDIPAPI GdipPathIterHasCurve(GpPathIterator* iterator, BOOL* hasCurve); GpStatus WINGDIPAPI GdipPathIterNextMarkerPath(GpPathIterator* iterator, INT* resultCount, GpPath* path); GpStatus WINGDIPAPI GdipPathIterNextMarker(GpPathIterator* iterator, INT* resultCount, INT* startIndex, INT* endIndex); GpStatus WINGDIPAPI GdipPathIterNextPathType(GpPathIterator* iterator, INT* resultCount, BYTE* pathType, INT* startIndex, INT* endIndex); GpStatus WINGDIPAPI GdipPathIterNextSubpathPath(GpPathIterator* iterator, INT* resultCount, GpPath* path, BOOL* isClosed); GpStatus WINGDIPAPI GdipPathIterNextSubpath(GpPathIterator* iterator, INT* resultCount, INT* startIndex, INT* endIndex, BOOL* isClosed); GpStatus WINGDIPAPI GdipPathIterEnumerate(GpPathIterator* iterator, INT* resultCount, GpPointF* points, BYTE* types, INT count); GpStatus WINGDIPAPI GdipPathIterRewind(GpPathIterator* iterator); /* missing API GdipPathIterIsValid */ } #endif
[ "64893442+asobo-solroo@users.noreply.github.com" ]
64893442+asobo-solroo@users.noreply.github.com
2c4c80514f9e85464526151654c3ab213b31bf0e
014070ac64dfc699b5c5c1e06cffc817e178f13e
/assignments/assignment04/Question.h
f2837a40d9dac6acbd0548de8ef987e48034775e
[ "BSD-3-Clause" ]
permissive
jay3ss/co-sci-140
c146969cf04624d0c32e28724ef579ff1e38f55e
2751bd12bcd8a24bf15fba656e086f1b0615b4a9
refs/heads/master
2020-04-22T07:09:39.367244
2019-06-01T21:30:36
2019-06-01T21:30:36
170,211,780
0
0
null
null
null
null
UTF-8
C++
false
false
1,183
h
// Class for a quiz question. Holds #ifndef QUESTION_H #define QUESTION_H #include <string> using namespace std; class Question { public: Question(int na = 4); ~Question(); bool checkAnswer(int ans) const { return ans == correctAnswer; } // Accessors string getQuestionText() { return questionText; } string *getPossibleAnswers() { return possibleAnswers; } int getCorrectAnswerNum() const { return correctAnswer; } int getNumAnswers() const { return numAnswers; } string getCorrectAnswerText() { return possibleAnswers[correctAnswer - 1]; } // Mutators void setQuestionText(string qt) { questionText = qt; } void setPossibleAnswer(string pAns, int idx) { possibleAnswers[idx] = pAns; } void setPossibleAnswers(string pa[]); void setCorrectAnswer(int ca) { correctAnswer = ca; } private: int numAnswers; // Number of answers (default=4) string questionText; // The question text string* possibleAnswers; // Possible answers to question int correctAnswer; // Correct answer (1, 2, 3, or 4 for default) }; #endif // QUESTION_H
[ "mentoce@gmail.com" ]
mentoce@gmail.com
e88009c2d6b0246fa85001280775fd1f0090ced9
19907e496cfaf4d59030ff06a90dc7b14db939fc
/POC/oracle_dapp/node_modules/wrtc/third_party/webrtc/include/chromium/src/chrome/browser/ui/views/validation_message_bubble_view.h
3d2f3a05fdbcc8372dcbf86df43fb0e98ea381b5
[ "BSD-2-Clause", "BSD-3-Clause" ]
permissive
ATMatrix/demo
c10734441f21e24b89054842871a31fec19158e4
e71a3421c75ccdeac14eafba38f31cf92d0b2354
refs/heads/master
2020-12-02T20:53:29.214857
2017-08-28T05:49:35
2017-08-28T05:49:35
96,223,899
8
4
null
2017-08-28T05:49:36
2017-07-04T13:59:26
JavaScript
UTF-8
C++
false
false
1,449
h
// Copyright 2015 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_BROWSER_UI_VIEWS_VALIDATION_MESSAGE_BUBBLE_VIEW_H_ #define CHROME_BROWSER_UI_VIEWS_VALIDATION_MESSAGE_BUBBLE_VIEW_H_ #include "base/macros.h" #include "chrome/browser/ui/validation_message_bubble.h" #include "chrome/browser/ui/views/validation_message_bubble_delegate.h" namespace content { class WebContents; } // A ValidationMessageBubble implementation for Views. class ValidationMessageBubbleView : public ValidationMessageBubble, public ValidationMessageBubbleDelegate::Observer { public: ValidationMessageBubbleView(content::WebContents* web_contents, const gfx::Rect& anchor_in_root_view, const base::string16& main_text, const base::string16& sub_text); ~ValidationMessageBubbleView() override; // ValidationMessageBubble overrides: void SetPositionRelativeToAnchor( content::RenderWidgetHost* widget_host, const gfx::Rect& anchor_in_root_view) override; // ValidationMessageBubbleDelegate::Observer overrides: void WindowClosing() override; private: ValidationMessageBubbleDelegate* delegate_; DISALLOW_COPY_AND_ASSIGN(ValidationMessageBubbleView); }; #endif // CHROME_BROWSER_UI_VIEWS_VALIDATION_MESSAGE_BUBBLE_VIEW_H_
[ "steven.jun.liu@qq.com" ]
steven.jun.liu@qq.com
84a44167217f8cc195478f36aa5b71a9b1640d92
60fdc45761aac91af97028e2861e709d9dbbe2cd
/kscope-binary-only-works-on-lucid/include/ktoolbarbutton.h
7526f025453402482b00b3654af8b2e3e0acf533
[]
no_license
fredollinger/kscope
f3636cd4809f6be8e22cb8b20fc68d14740d9292
8bd0f6d1f5ec49e130ee86292b1e6b6cfe3b0f4d
refs/heads/master
2021-01-01T19:56:55.106226
2010-09-29T20:17:22
2010-09-29T20:17:22
948,786
3
0
null
null
null
null
UTF-8
C++
false
false
9,555
h
/* This file is part of the KDE libraries Copyright (C) 1997, 1998 Stephan Kulow (coolo@kde.org) (C) 1997, 1998 Sven Radej (radej@kde.org) (C) 1997, 1998 Mark Donohoe (donohoe@kde.org) (C) 1997, 1998 Matthias Ettrich (ettrich@kde.org) (C) 2000 Kurt Granroth (granroth@kde.org) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License version 2 as published by the Free Software Foundation. This library 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 Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef _KTOOLBARBUTTON_H #define _KTOOLBARBUTTON_H #include <qpixmap.h> #include <qtoolbutton.h> #include <qintdict.h> #include <qstring.h> #include <kglobal.h> class KToolBar; class KToolBarButtonPrivate; class KInstance; class QEvent; class QPopupMenu; class QPainter; /** * A toolbar button. This is used internally by KToolBar, use the * KToolBar methods instead. * @internal */ class KDEUI_EXPORT KToolBarButton : public QToolButton { Q_OBJECT public: /** * Construct a button with an icon loaded by the button itself. * This will trust the button to load the correct icon with the * correct size. * * @param icon Name of icon to load (may be absolute or relative) * @param id Id of this button * @param parent This button's parent * @param name This button's internal name * @param txt This button's text (in a tooltip or otherwise) * @param _instance the instance to use for this button */ KToolBarButton(const QString& icon, int id, QWidget *parent, const char *name=0L, const QString &txt=QString::null, KInstance *_instance = KGlobal::instance()); /** * Construct a button with an existing pixmap. It is not * recommended that you use this as the internal icon loading code * will almost always get it "right". * * @param pixmap Name of icon to load (may be absolute or relative) * @param id Id of this button * @param parent This button's parent * @param name This button's internal name * @param txt This button's text (in a tooltip or otherwise) */ KToolBarButton(const QPixmap& pixmap, int id, QWidget *parent, const char *name=0L, const QString &txt=QString::null); /** * Construct a separator button * * @param parent This button's parent * @param name This button's internal name */ KToolBarButton(QWidget *parent=0L, const char *name=0L); /** * Standard destructor */ ~KToolBarButton(); #ifndef KDE_NO_COMPAT /** * @deprecated * Set the pixmap directly for this button. This pixmap should be * the active one... the dimmed and disabled pixmaps are constructed * based on this one. However, don't use this function unless you * are positive that you don't want to use setIcon. * * @param pixmap The active pixmap */ // this one is from QButton, so #ifdef-ing it out doesn't break BC virtual void setPixmap(const QPixmap &pixmap) KDE_DEPRECATED; /** * @deprecated * Force the button to use this pixmap as the default one rather * then generating it using effects. * * @param pixmap The pixmap to use as the default (normal) one */ void setDefaultPixmap(const QPixmap& pixmap) KDE_DEPRECATED; /** * @deprecated * Force the button to use this pixmap when disabled one rather then * generating it using effects. * * @param pixmap The pixmap to use when disabled */ void setDisabledPixmap(const QPixmap& pixmap) KDE_DEPRECATED; #endif /** * Set the text for this button. The text will be either used as a * tooltip (IconOnly) or will be along side the icon * * @param text The button (or tooltip) text */ virtual void setText(const QString &text); /** * Set the icon for this button. The icon will be loaded internally * with the correct size. This function is preferred over setIconSet * * @param icon The name of the icon */ virtual void setIcon(const QString &icon); /// @since 3.1 virtual void setIcon( const QPixmap &pixmap ) { QToolButton::setIcon( pixmap ); } /** * Set the pixmaps for this toolbar button from a QIconSet. * If you call this you don't need to call any of the other methods * that set icons or pixmaps. * @param iconset The iconset to use */ virtual void setIconSet( const QIconSet &iconset ); #ifndef KDE_NO_COMPAT /** * @deprecated * Set the active icon for this button. The pixmap itself is loaded * internally based on the icon size... .. the disabled and default * pixmaps, however will only be constructed if generate is * true. This function is preferred over setPixmap * * @param icon The name of the active icon * @param generate If true, then the other icons are automagically * generated from this one */ KDE_DEPRECATED void setIcon(const QString &icon, bool generate ) { Q_UNUSED(generate); setIcon( icon ); } /** * @deprecated * Force the button to use this icon as the default one rather * then generating it using effects. * * @param icon The icon to use as the default (normal) one */ void setDefaultIcon(const QString& icon) KDE_DEPRECATED; /** * @deprecated * Force the button to use this icon when disabled one rather then * generating it using effects. * * @param icon The icon to use when disabled */ void setDisabledIcon(const QString& icon) KDE_DEPRECATED; #endif /** * Turn this button on or off * * @param flag true or false */ void on(bool flag = true); /** * Toggle this button */ void toggle(); /** * Turn this button into a toggle button or disable the toggle * aspects of it. This does not toggle the button itself. * Use toggle() for that. * * @param toggle true or false */ void setToggle(bool toggle = true); /** * Return a pointer to this button's popup menu (if it exists) */ QPopupMenu *popup(); /** * Returns the button's id. * @since 3.2 */ int id() const; /** * Give this button a popup menu. There will not be a delay when * you press the button. Use setDelayedPopup if you want that * behavior. * * @param p The new popup menu * @param unused Has no effect - ignore it. */ void setPopup (QPopupMenu *p, bool unused = false); /** * Gives this button a delayed popup menu. * * This function allows you to add a delayed popup menu to the button. * The popup menu is then only displayed when the button is pressed and * held down for about half a second. * * @param p the new popup menu * @param unused Has no effect - ignore it. */ void setDelayedPopup(QPopupMenu *p, bool unused = false); /** * Turn this button into a radio button * * @param f true or false */ void setRadio(bool f = true); /** * Toolbar buttons naturally will assume the global styles * concerning icons, icons sizes, etc. You can use this function to * explicitly turn this off, if you like. * * @param no_style Will disable styles if true */ void setNoStyle(bool no_style = true); signals: /** * Emitted when the toolbar button is clicked (with LMB or MMB) */ void clicked(int); /** * Emitted when the toolbar button is clicked (with any mouse button) * @param state makes it possible to find out which button was pressed, * and whether any keyboard modifiers were held. * @since 3.4 */ void buttonClicked(int, Qt::ButtonState state); void doubleClicked(int); void pressed(int); void released(int); void toggled(int); void highlighted(int, bool); public slots: /** * This slot should be called whenever the toolbar mode has * potentially changed. This includes such events as text changing, * orientation changing, etc. */ void modeChange(); virtual void setTextLabel(const QString&, bool tipToo); protected: bool event(QEvent *e); void paletteChange(const QPalette &); void leaveEvent(QEvent *e); void enterEvent(QEvent *e); void drawButton(QPainter *p); bool eventFilter (QObject *o, QEvent *e); /// @since 3.4 void mousePressEvent( QMouseEvent * ); /// @since 3.4 void mouseReleaseEvent( QMouseEvent * ); void showMenu(); QSize sizeHint() const; QSize minimumSizeHint() const; QSize minimumSize() const; /// @since 3.1 bool isRaised() const; /// @since 3.1 bool isActive() const; /// @since 3.1 int iconTextMode() const; protected slots: void slotClicked(); void slotPressed(); void slotReleased(); void slotToggled(); void slotDelayTimeout(); protected: virtual void virtual_hook( int id, void* data ); private: KToolBarButtonPrivate *d; }; /** * List of KToolBarButton objects. * @internal * @version $Id: ktoolbarbutton.h 465272 2005-09-29 09:47:40Z mueller $ */ class KDEUI_EXPORT KToolBarButtonList : public QIntDict<KToolBarButton> { public: KToolBarButtonList(); ~KToolBarButtonList() {} }; #endif
[ "follinge@gmail.com" ]
follinge@gmail.com
e4f37ac0fe8b8c1e1d18ffcd2a59a4b4cd3c02a5
7eb9b7f2fb4bfa54773c1e77b9c86fe8ab6a928e
/P3/June/10_June/recursion/11.cpp
0fa249641fe53d0487ff1d9084d63c29428d58b7
[]
no_license
Aloknegi19april/Programs
f7bdd87110864f7c0de005963a6dd91eb84ec775
b2e2ccd1ed671fa51ff31322ea70c17cc384ac1e
refs/heads/master
2020-06-08T14:42:18.354534
2019-07-05T00:00:18
2019-07-05T00:00:18
193,245,750
0
0
null
null
null
null
UTF-8
C++
false
false
410
cpp
#include<bits/stdc++.h> using namespace std; int maxofArray(int *Ar, int last) { if(last == 0) return Ar[0]; if(Ar[last]>maxofArray(Ar,last-1)) return Ar[last]; else return maxofArray(Ar,last-1); } int main() { int n; cin >> n; int Ar[n]; for(int i = 0; i < n; i++) { cin >> Ar[i]; } int last = n-1; cout << maxofArray(Ar,last); }
[ "30485749+Aloknegi19april@users.noreply.github.com" ]
30485749+Aloknegi19april@users.noreply.github.com
b27bb9ab205b1a9580ba97e342f0beceb214a8ec
5470aaa73c0e30bb6a17f2f3b4650d30a7c9e273
/Code/CharacterControl/Tank/ServerTank.h
4d32703dccac2444554f4e4e2e35d3103e34a7f3
[]
no_license
Hengxiac/RTS-pathfinding-game-demo
6e593ebb03ae0e304299f1a65fc127365a9af2be
af2fad48df6c97f0067998c7ed5692610628327d
refs/heads/master
2021-01-20T18:06:52.152527
2017-05-10T20:22:40
2017-05-10T20:22:40
90,905,626
1
0
null
null
null
null
UTF-8
C++
false
false
1,766
h
#ifndef S_TANK_H_ #define S_TANK_H_ #include "PrimeEngine/Events/Component.h" #include "PrimeEngine/Math/Matrix4x4.h" namespace PE { namespace Events{ //struct EventQueueManager; } } namespace CharacterControl { namespace Components { struct ServerTank : public PE::Components::Component, public PE::Networkable { enum BitNum { TOPPOSITION = 3, POSITION = 2, HITPOINT = 0, SHELLLEFT = 1 }; // component API PE_DECLARE_CLASS(ServerTank); PE_DECLARE_NETWORKABLE_CLASS ServerTank(PE::GameContext &context, PE::MemoryArena arena, PE::Handle myHandle, float speed, Matrix4x4 &spawnPos, float networkPingInterval, int hitPoint, int shellVolume); // constructor virtual void addDefaultComponents(); // adds default children and event handlers PE_DECLARE_IMPLEMENT_EVENT_HANDLER_WRAPPER(do_UPDATE); virtual void do_UPDATE(PE::Events::Event *pEvt); PE_DECLARE_IMPLEMENT_EVENT_HANDLER_WRAPPER(do_Update_Ghost); virtual void do_Update_Ghost(PE::Events::Event *pEvt); PE_DECLARE_IMPLEMENT_EVENT_HANDLER_WRAPPER(do_Restart_Game); virtual void do_Restart_Game(PE::Events::Event *pEvt); virtual int packStateData(char *pDataStream); //virtual int constructFromStream(char *pDataStream); void overrideTransform(Matrix4x4 &t); float m_timeSpeed; float m_time; float m_networkPingTimer; float m_networkPingInterval; Vector2 m_center; Matrix4x4 m_spawnPos; Matrix4x4 m_topTransform; PrimitiveTypes::UInt32 m_counter; int m_hitPoint; int m_HPMax; int m_shellMax; int m_shellLeft; int m_clientProcessing; }; }; // namespace Components }; // namespace CharacterControl #endif
[ "achiga2020@gmail.com" ]
achiga2020@gmail.com
022ed7f492fb91f12dce03d34c19604672b0d85f
2a290e9f6a6796a70db287e99becaa06a593e482
/Win32Project_20150120/Win32Project_20150120.cpp
598c4a0a94dca41cf2a955ef1bb72f3fa929a2cb
[]
no_license
iamsulphur/Win32Project
af60bbb7d3dee16d7760c062028f82ab613e69cb
1d7d2683ed4846e473ebfe14f7dffbb54cf2c491
refs/heads/master
2016-09-01T22:51:37.739549
2015-02-11T14:04:45
2015-02-11T14:04:45
29,679,577
0
0
null
null
null
null
GB18030
C++
false
false
5,763
cpp
// WIN32PROJECT_20150120.cpp : 定义应用程序的入口点。 // #include "stdafx.h" #include "WIN32PROJECT_20150120.h" #define MAX_LOADSTRING 100 // 全局变量: HINSTANCE hInst; // 当前实例 TCHAR szTitle[MAX_LOADSTRING]; // 标题栏文本 TCHAR szWindowClass[MAX_LOADSTRING]; // 主窗口类名 // 此代码模块中包含的函数的前向声明: ATOM MyRegisterClass(HINSTANCE hInstance); BOOL InitInstance(HINSTANCE, int); LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM); INT_PTR CALLBACK About(HWND, UINT, WPARAM, LPARAM); int APIENTRY _tWinMain(_In_ HINSTANCE hInstance, _In_opt_ HINSTANCE hPrevInstance, _In_ LPTSTR lpCmdLine, _In_ int nCmdShow) { UNREFERENCED_PARAMETER(hPrevInstance); UNREFERENCED_PARAMETER(lpCmdLine); // TODO: 在此放置代码。 MSG msg; HACCEL hAccelTable; // 初始化全局字符串 LoadString(hInstance, IDS_APP_TITLE, szTitle, MAX_LOADSTRING); LoadString(hInstance, IDC_WIN32PROJECT_20150120, szWindowClass, MAX_LOADSTRING); MyRegisterClass(hInstance); // 执行应用程序初始化: if (!InitInstance(hInstance, nCmdShow)) { return FALSE; } hAccelTable = LoadAccelerators(hInstance, MAKEINTRESOURCE(IDC_WIN32PROJECT_20150120)); // 主消息循环: while (GetMessage(&msg, NULL, 0, 0)) { if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg)) { TranslateMessage(&msg); DispatchMessage(&msg); } } return (int)msg.wParam; } // // 函数: MyRegisterClass() // // 目的: 注册窗口类。 // ATOM MyRegisterClass(HINSTANCE hInstance) { WNDCLASSEX wcex; wcex.cbSize = sizeof(WNDCLASSEX); wcex.style = CS_HREDRAW | CS_VREDRAW; wcex.lpfnWndProc = WndProc; wcex.cbClsExtra = 0; wcex.cbWndExtra = 0; wcex.hInstance = hInstance; wcex.hIcon = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_WIN32PROJECT_20150120)); wcex.hCursor = LoadCursor(NULL, IDC_ARROW); wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW + 1); wcex.lpszMenuName = MAKEINTRESOURCE(IDC_WIN32PROJECT_20150120); wcex.lpszClassName = szWindowClass; wcex.hIconSm = LoadIcon(wcex.hInstance, MAKEINTRESOURCE(IDI_SMALL)); return RegisterClassEx(&wcex); } // // 函数: InitInstance(HINSTANCE, int) // // 目的: 保存实例句柄并创建主窗口 // // 注释: // // 在此函数中,我们在全局变量中保存实例句柄并 // 创建和显示主程序窗口。 // BOOL InitInstance(HINSTANCE hInstance, int nCmdShow) { HWND hWnd; hInst = hInstance; // 将实例句柄存储在全局变量中 hWnd = CreateWindow(szWindowClass, szTitle, WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, 0, 816, 859, NULL, NULL, hInstance, NULL); //窗口大小默认为816*859,这样子可以是客户区大小为800*800。窗口包括标题栏、工具栏、边框的距离。 if (!hWnd) { return FALSE; } ShowWindow(hWnd, nCmdShow); UpdateWindow(hWnd); return TRUE; } // // 函数: WndProc(HWND, UINT, WPARAM, LPARAM) // // 目的: 处理主窗口的消息。 // // WM_COMMAND - 处理应用程序菜单 // WM_PAINT - 绘制主窗口 // WM_DESTROY - 发送退出消息并返回 // // LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { int wmId, wmEvent; int number = 0; //测试循环的次数 static int times = 0; //paint的测试。 PAINTSTRUCT ps; HDC hdc; HFONT hFont; //字体句柄 int cxClient = 0; int cyClient = 0; switch (message) { case WM_COMMAND: wmId = LOWORD(wParam); wmEvent = HIWORD(wParam); // 分析菜单选择: switch (wmId) { case IDM_ABOUT: DialogBox(hInst, MAKEINTRESOURCE(IDD_ABOUTBOX), hWnd, About); break; case IDM_EXIT: DestroyWindow(hWnd); break; default: return DefWindowProc(hWnd, message, wParam, lParam); } break; case WM_CREATE: cxClient = LOWORD(lParam); cyClient = HIWORD(lParam); break; case WM_SIZE: cxClient = LOWORD(lParam); cyClient = HIWORD(lParam); break; case WM_PAINT: times++; //处理WM_PAINT消息的次数。 InvalidateRect(hWnd, NULL, TRUE); //让整个窗口变成无效区域,第三个参数,标注BeginPaint时是否需要刷新背景 hdc = BeginPaint(hWnd, &ps); number = rand() % 10000 + 50000; for (int i = 0; i < number; i++) { int x = rand() % 800; int y = rand() % 800; SetPixel(hdc, x, y, RGB(0, 0, 255)); } //while (true) //{ // int x = rand() % 800; // int y = rand() % 800; // SetPixel(hdc, x, y, RGB(0, 0, 255)); //} hFont = CreateFont( 40, 0, //高度40, 宽取0表示由系统选择最佳值 0, 0, //文本倾斜,与字体倾斜都为0 FW_NORMAL, 0, 1, 0, //斜体,下划线,无中划线 GB2312_CHARSET, //字符集 OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS, DEFAULT_QUALITY, //一系列的默认值 DEFAULT_PITCH | FF_DONTCARE, TEXT("微软雅黑") //字体名称 ); SelectObject(hdc, hFont); SetTextAlign(hdc, TA_RIGHT | TA_BOTTOM); TCHAR szTotal[10]; //默认宽度是10,当然不严谨 TextOut(hdc, 800, 800, szTotal, wsprintf(szTotal, TEXT("%d:%d"), times, number)); EndPaint(hWnd, &ps); DeleteObject(hFont); break; case WM_DESTROY: PostQuitMessage(0); break; default: return DefWindowProc(hWnd, message, wParam, lParam); } return 0; } // “关于”框的消息处理程序。 INT_PTR CALLBACK About(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam) { UNREFERENCED_PARAMETER(lParam); switch (message) { case WM_INITDIALOG: return (INT_PTR)TRUE; case WM_COMMAND: if (LOWORD(wParam) == IDOK || LOWORD(wParam) == IDCANCEL) { EndDialog(hDlg, LOWORD(wParam)); return (INT_PTR)TRUE; } break; } return (INT_PTR)FALSE; }
[ "mirrorbyice@163.com" ]
mirrorbyice@163.com
a0eb21ad7e51432acc3599b09afcdbf73975fdda
4f516e38ecc967e6d0585343d5e4d24e5743190c
/src/common/game2d/world/Uniform2dParticleGenerator.h
2bb77d0ab6936c7f294dd7690b35adf12e46a15a
[ "Apache-2.0" ]
permissive
johan1/rocket
6e0ba1f854f5fe191301ce1086daf29bc6b24b1d
b614f317ca380c82f84149a56ea163e7bc88cd8d
refs/heads/master
2021-01-12T13:43:00.361359
2016-10-26T08:44:19
2016-10-26T08:44:19
16,081,320
0
0
null
null
null
null
UTF-8
C++
false
false
966
h
#ifndef _ROCKET_UNIFORM_2D_PARTICLE_GENERATOR_H_ #define _ROCKET_UNIFORM_2D_PARTICLE_GENERATOR_H_ #include "ParticleGenerator.h" #include <random> #include <ctime> namespace rocket { namespace game2d { class Uniform2dParticleGenerator : public ParticleGenerator { public: Uniform2dParticleGenerator(float a1, float a2, float r, float d1, float d2, float s1, float s2, glutils::RGBAColor c1, glutils::RGBAColor c2) : random_engine(static_cast<std::size_t>(std::time(nullptr))), angleDist(a1,a2), radiusDist(0.0f, r), durationDist(d1, d2), s1(s1), s2(s2), c1(c1), c2(c2) {} private: std::default_random_engine random_engine; std::uniform_real_distribution<float> angleDist; std::uniform_real_distribution<float> radiusDist; std::uniform_real_distribution<float> durationDist; float s1; float s2; glutils::RGBAColor c1; glutils::RGBAColor c2; virtual Particle generateImpl(); }; } using namespace game2d; // Collapse } #endif
[ "johan.viktorsson.dev@gmail.com" ]
johan.viktorsson.dev@gmail.com
89db904289f9b8f5a87911d04d3fd7ebf3a0b9bf
eb50a330cb3d2402d17bee9a5f91f2b372c1e1c1
/Codeforces/arpa_theater.cpp
88b0a4a81c4caa15c64a90c269507dcef3e26682
[]
no_license
MaxSally/Competitive_Programming
2190552a8c8a97d13f33d5fdbeb94c5d92fa9038
8c57924224ec0d1bbc5f17078505ef8864f4caa3
refs/heads/master
2023-04-27T22:28:19.276998
2023-04-12T22:47:10
2023-04-12T22:47:10
270,885,835
0
0
null
null
null
null
UTF-8
C++
false
false
2,554
cpp
//http://codeforces.com/contest/742/problem/D #include <vector> #include <iostream> #include <stdio.h> #include <algorithm> #include <cmath> #include <stack> using namespace std; int const lim=1005; int n,m,w; bool visi[lim]; vector <int> weight, beauty; vector < vector<int> > graph, group; vector<int> groupW, groupB; int dp[lim][lim]; int prepare(){ for(int i = 0; i <= n; i++){ for(int j = 0; j <= w; j++){ dp[i][j] = 0; } } } void dfs(){ stack<int> s; for(int i = 1; i <= n; i++){ vector<int> temp; if(!visi[i]){ int n1 = group.size(); visi[i]=1; s.push(i); while(!s.empty()){ int a = s.top(); s.pop(); temp.push_back(a); groupB[n1] += beauty[a]; groupW[n1] += weight[a]; for(int j = 0; j < graph[a].size(); j++){ int b = graph[a][j]; if(!visi[b]){ visi[b]=1; s.push(b); } } } } group.push_back(temp); } } void print(){ for(int i=0;i<group.size();i++){ for(int j=0;j<=w;j++){ cout << dp[i][j] << " "; } cout << endl; } cout << endl; } int knapsack(){ for(int i = 1; i <= group.size(); i++){ for(int j = 0; j <= w; j++){ dp[i][j] = dp[i-1][j]; if(groupW[i-1] <= j){ dp[i][j] = max(dp[i][j], dp[i-1][j-groupW[i-1]] + groupB[i-1]); } //print(); for(int k = 0; k < group[i-1].size(); k++){ int a = group[i-1][k]; if(weight[a] <= j){ dp[i][j] = max(dp[i][j], dp[i-1][j-weight[a]] + beauty[a]); } //print(); } } } return dp[group.size()][w]; } int main(){ freopen("input.txt","r",stdin); cin >> n >> m >> w; //cout << n << m << w; weight.resize(n+1); beauty.resize(n+1); graph.resize(n+1); groupB.resize(n+1,0); groupW.resize(n+1,0); for(int i = 1; i <= n; i++){ visi[i]=0; cin >> weight[i]; } for(int i = 1; i <= n; i++){ cin >> beauty[i]; } for(int i = 0; i < m; i++){ int a,b; cin >> a >> b; graph[a].push_back(b); graph[b].push_back(a); } //cout <<"YES"; prepare(); dfs(); cout << knapsack(); return 0; }
[ "qnguyen16@huskers.unl.edu" ]
qnguyen16@huskers.unl.edu
9edffa4275ef4620af230e2948571c26ece03b76
d6f0bfe60b10c08bea59935fcf4e7be13d861141
/chapter9/9_14.cpp
ac709b84de1181734ecca4461734ad8c0aeb1ca7
[]
no_license
ttylinux/cppPrimer
74176ba90faf586dbbe1db66d60f32ae695fe841
4bc5de3ded83f819d07ad066ccd3093dac2ddf81
refs/heads/master
2020-05-17T14:44:41.263249
2017-12-04T08:22:31
2017-12-04T08:22:31
27,017,864
0
0
null
null
null
null
UTF-8
C++
false
false
279
cpp
#include <iostream> #include <string> #include <vector> #include <list> int main() { std::list<const char*> l{ "Mooophy", "pezy", "Queeuqueg" }; std::vector<std::string> v; v.assign(l.cbegin(), l.cend()); for (const auto& ch : v) std::cout << ch << std::endl; return 0; }
[ "albertxiaoyu@163.com" ]
albertxiaoyu@163.com
cdf1d4d8267182f5e8efe2aa461264fa715a76dd
402947226e4306f3ff29fde51baab964d83e2247
/Test/StackTest.cpp
4fc832067b19d37f70d3031da527490ecf67efde
[]
no_license
PeterGH/Test
1add271f16fdf861ece35a042949450463336e46
4f9a32d42f70ebd1b7137cc796d06b0eb40472e7
refs/heads/master
2021-01-01T17:32:26.701687
2015-06-23T03:55:14
2015-06-23T03:55:14
13,944,833
0
0
null
null
null
null
UTF-8
C++
false
false
1,190
cpp
#include "StackTest.h" void StackTest::Init(void) { Add("Stack", [&](){ Test::Stack<int> s1; stack<int> s2; ASSERTERROR(s1.Top(), runtime_error); ASSERTERROR(s1.Pop(), runtime_error); ASSERT1(s1.Empty() == true); ASSERT1(s2.empty() == true); ASSERT1(s1.Size() == s2.size()); for (int i = 0; i < 100; i++) { s1.Push(i); s2.push(i); ASSERT1(s1.Top() == i); ASSERT1(s2.top() == i); ASSERT1(s1.Empty() == false); ASSERT1(s2.empty() == false); ASSERT1(s1.Size() == s2.size()); } int v1, v2; for (int i = 0; i < 99; i++) { v1 = s1.Top(); s1.Pop(); v2 = s2.top(); s2.pop(); ASSERT1(v1 == 99 - i); ASSERT1(v2 == 99 - i); ASSERT1(s1.Top() == 99 - i - 1); ASSERT1(s2.top() == 99 - i - 1); ASSERT1(s1.Empty() == false); ASSERT1(s2.empty() == false); ASSERT1(s1.Size() == s2.size()); } v1 = s1.Top(); s1.Pop(); v2 = s2.top(); s2.pop(); ASSERT1(v1 == 0); ASSERT1(v2 == 0); ASSERTERROR(s1.Top(), runtime_error); ASSERTERROR(s1.Pop(), runtime_error); ASSERT1(s1.Empty() == true); ASSERT1(s2.empty() == true); ASSERT1(s1.Size() == s2.size()); }); }
[ "peteryzufl@gmail.com" ]
peteryzufl@gmail.com
b47e97b58d7637262639f4250ba95f99d6b961f1
046d3a51ac31fb85fa54958c5bd2f824b85c99cd
/OmaPuoli/drooni.hh
76e78950a5a38e1d9879a7d650dbf4a9511f92e3
[]
no_license
poytiis/QTpeli_Cplusplus
554b07384def908f25a0ac10a2a95d318afc4f2b
5fef531eaba17137ca7e68d01009c559114e3649
refs/heads/master
2021-09-26T06:35:56.961181
2018-10-27T14:13:54
2018-10-27T14:13:54
null
0
0
null
null
null
null
UTF-8
C++
false
false
7,071
hh
// Pelissä käytettävän droonin esittely #ifndef DROONI_H #define DROONI_H #include "toimijarp.hh" #include "sijainti.hh" #include "rynnakkokivaari.hh" #include <QGraphicsObject> #include <QImage> #include <QPointF> #include <QTimer> /** * @file * @brief Drooni luokka toteuttaa pelissä käytettävän droonin. Periytetty * QGraphicsObject ja ToimijaRP luokista. */ class Drooni : public QGraphicsObject, public Rajapinta::ToimijaRP { Q_OBJECT public: /** * @brief Droonin rakentaja, luo uuden drooni olion. * @param parent droonin vanhempi, mahdollista jättää määrittelemättä. * @pre - * @post Drooni on luotu ja valmis käytettäväksi. Poikkeustakuu: ?? */ Drooni(QGraphicsItem* parent = NULL); /** * @brief ~Drooni tuhoaa droonin. * @post drooni on tuhottu. */ virtual ~Drooni(); /** * @brief keyPressEvent vastaanottaa olion saaman näppäimistösyötteen. * Muuntaa nuolinäppäimet ja välilyönnin droonin liikkeiksi. Ei yleensä tarvitse * kutsua itse. * @param event QKeyEvent* tyyppinen tapahtuma. * @pre - * @post Drooni on reagoinnut painikkeeseen halutulla tavalla. Poikkeustakuu: ?? */ void keyPressEvent(QKeyEvent* event); /** * @brief keyReleaseEvent ks. keyPressEvent. * @param event ks. keyPressEvent. */ void keyReleaseEvent(QKeyEvent* event); /** * @brief ammuksiaJaljella Kertoo paljonko kysytyssä aseessa on ammuksia jäljellä * @param ase Aseen, jonka ammustiedot halutaan, numero. 1 = RK, 2 = Maamiina, 3 = Laser * @return Jäljellä olevien ammusten lukumäärä * @pre ase on välillä [0,2] * @post Poikkeustakuu: vahva * @exception PeliVirhe mikäli aseen tietoja ei löydy */ short int ammuksiaJaljella(int ase) const; // ToimijaRP:n toteutus - MUISTA TEHDÄ!!! virtual Rajapinta::Sijainti annaSijainti() const; virtual void liiku(Rajapinta::Sijainti sij); virtual bool onkoTuhottu() const; virtual void tuhoa(); /** * @brief liikuSulavasti Laittaa droonin liikkumaan sulavasti kohti annettua sijaintia. * @param sij Määränpää sijainti * @pre - * @post Drooni liikkuu kohti määränpäätä. Poikkeustakuu: perus */ void liikuSulavasti(Rajapinta::Sijainti sij); // Droonin sulavan liikkumisen mahdollistamiseen käytetty ajastin // ja boolean arvot QTimer* animaatioajastin; bool liikkuuEteen; bool liikkuuTaakse; bool kaantyyVasemmalle; bool kaantyyOikealle; protected: // QGraphicsObjectin vaatimien metodien toteutus void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget); virtual QRectF boundingRect() const; // Toteutettu droonin pitämiseksi pelialueella. Kutsutaan aina kun droonin sijainti // muuttuu. virtual QVariant itemChange(GraphicsItemChange change, const QVariant &value); public slots: /** * @brief alaLiikkuaEteen Laittaa droonin liikkumaan eteenpäin kunnes liike lopetetaan. * @pre - * @post liikkuuEteen = true */ void alaLiikkuaEteen(); /** * @brief alaLiikkuaTaakse Laittaa droonin liikkumaan taaksepäin kunnes liike lopetetaan. * @pre - * @post liikkuuTaakse = true */ void alaLiikkuaTaakse(); /** * @brief alaKaantyaMyota Laittaa droonin kääntymään myötäpäivään kunnes kääntyminen lopetetaan. * @pre - * @post kaantyyOikealle = true */ void alaKaantyaMyota(); /** * @brief alaKaantyaVasta Laittaa droonin kääntymään vastapäivään kunnes kääntyminen lopetetaan. * @pre - * @post kaantyyVasemmalle = true; */ void alaKaantyaVasta(); /** * @brief lopetaEteenLiikkuminen Lopettaa droonin eteenpäin liikkumisen. * @pre - * @post liikkuuEteen = false */ void lopetaEteenLiikkuminen(); /** * @brief lopetaTaakseLiikkuminen Lopettaa droonin taaksepäin liikkumisen. * @pre - * @post liikkuuTaakse = false */ void lopetaTaakseLiikkuminen(); /** * @brief lopetaKaannosMyota Lopettaa droonin kääntymisen myötäpäivään. * @pre - * @post kaantyyOikealle = false */ void lopetaKaannosMyota(); /** * @brief lopetaKaannosVasta Lopettaa droonin kääntymisen vastapäivään. * @pre - * @post kaantyyVasemmalle = false */ void lopetaKaannosVasta(); /** * @brief ammu luo uuden valitun aseen ammuksen ja lisää sen samaan QGraphicsScenee droonin * kanssa. * @pre Drooni kuuluu QGraphicsSceneen ja ase on valituna. * @post Uusi ammus on luotu ja lisätty QGraphicsSceneen. Poikkeustakuu: vahva */ void ammu(); /** * @brief valitseRynkky valitsee rynnäkkökiväärin aktiiviseksi aseeksi. * @pre - * @post Rynnäkkökivääri on valittuna. Poikkeustakuu: vahva */ void valitseRynkky(); /** * @brief valitseMiina valitsee maamiinan aktiiviseksi aseeksi. * @pre - * @post Maamiina on valittuna. Poikkeustakuu: vahva */ void valitseMiina(); /** * @brief valitseLaser valitsee laserin aktiiviseksi aseeksi. * @pre - * @post Laser on valittuna. Poikkeustakuu: vahva */ void valitseLaser(); signals: /** * @brief drooniLiikkunut signaali lähetetään aina kun drooni on liikkunut. * @param ottaa droonin parametrinansa. */ void drooniLiikkunut(QGraphicsItem* drooni); /** * @brief drooniAmpunut signaali lähetetään aina kun drooni on ampunut. * @param ase Ampumiseen käytetty ase. * @param ammuksia_jaljella Aseen jäljellä oleva ammusmäärä. */ void drooniAmpunut(short int ase, short int ammuksia_jaljella); /** * @brief ammuksetLopussa signaali lähetetään kun droonin ammukset ovat lopussa. */ void ammuksetLopussa(); private: // Droonin liikuttamiseen "konepellin alla" käytetyt funktiot. void liikuYlos(); void liikuAlas(); void liikuVasen(); void liikuOikea(); void tarkistaSulavaLiike(); QPointF sulava_kohde_{QPointF(0,0)}; bool kaantyySulavasti_{false}; bool liikkuuSulavasti_{false}; // Palauttaa droonin keulan edessä 1 etäisyydellä olevan pisteen QPointF suuntaPiste() const; // Droonin kuva QImage alus_; // Keulan suunta asteina //qreal suunta; // Droonin huippunopeus, tämänhetkinen nopeus ja kiihtyvyys short int nopeus_{4}; qreal hetkellinen_nopeus_{0}; qreal kiihtyvyys_{0.1}; qreal pakitus_nopeus_{(double)nopeus_/2}; qreal hetkellinen_pakitus_nopeus_{0}; short int kaantymis_nopeus_{4}; short int puolikas_{20}; // Aseen valinta short int valittu_ase_{0}; // Droonin ammukset. Julkisia, koska esim. kauppa voi lisätä ammuksia suoraan. short int rk_ammuksia{20}; short int mm_ammuksia{10}; short int laser_ammuksia{3}; bool tuhottu_{false}; }; #endif // DROONI_H
[ "teemu.poytaniemi@student.tut.fi" ]
teemu.poytaniemi@student.tut.fi
404d4b90b0ab619ae9fe12801591d8c380353f30
11ae3c532ad1097335a6f1d289cde03d269bdf05
/sem1/hw4/p4-3/stackChar.cpp
9ac9ecfe886d280f794526ee395e8e5e6690d8e0
[]
no_license
yurii9999/hw
8e151d25e81d958c6acb3a954bd3b5096ad7a228
b2a4f8ff07cf15694e1e54a23338589526f5343d
refs/heads/master
2021-06-06T07:48:32.072539
2019-11-05T10:11:30
2019-11-05T10:11:30
109,320,792
0
0
null
null
null
null
UTF-8
C++
false
false
821
cpp
#include <iostream> #include "stackChar.h" #include "listChar.h" struct Stack { List *list; }; Stack *createStack() { Stack *stack = new Stack; stack->list = createList(); return stack; } void deleteStack(Stack *stack) { deleteList(stack->list); delete stack; } int sizeStack(Stack *stack) { return sizeList(stack->list); } void push(Stack *stack, char value) { addElementTo(stack->list, value, 0); } char peek(Stack *stack) { if (isEmpty(stack)) return -1; return peekListElement(stack->list, 0); } char pop(Stack *stack) { char result = peekListElement(stack->list, 0); deleteElementFrom(stack->list, 0); return result; } void printStack(Stack *stack) { printList(stack->list); } bool isEmpty(Stack *stack) { return(sizeStack(stack) == 0); }
[ "yurii9kuzmin@gmail.com" ]
yurii9kuzmin@gmail.com
ec1b3e392f29a95c02dccd9cbb9c79c7d2eb9fa9
d7085a2924fb839285146f88518c69c567e77968
/KS/SRC/script_lib_scene_anim.cpp
b1364c60212b7d524891a7ad44b075ff2fd9fa8f
[]
no_license
historicalsource/kelly-slaters-pro-surfer
540f8f39c07e881e9ecebc764954c3579903ad85
7c3ade041cc03409a3114ce3ba4a70053c6e4e3b
refs/heads/main
2023-07-04T09:34:09.267099
2021-07-29T19:35:13
2021-07-29T19:35:13
390,831,183
40
2
null
null
null
null
UTF-8
C++
false
false
3,473
cpp
// script_lib_scene_anim.cpp // // This file contains application-specific code and data that makes use of the // Script Runtime Core to define script library classes and functions that // provide the interface between the script language and the application. #include "global.h" #include "script_lib_scene_anim.h" #include "vm_stack.h" #include "vm_thread.h" #include "wds.h" /////////////////////////////////////////////////////////////////////////////// // script library class: scene_anim /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// // scene_anim script library class member functions /////////////////////////////////////////////////////////////////////////////// // script library function: scene_anim::kill_anim(); class slf_scene_anim_kill_anim_t : public script_library_class::function { public: // constructor required slf_scene_anim_kill_anim_t( script_library_class* slc, const char* n ) : script_library_class::function( slc, n ) { } // library function parameters struct parms_t { // parameters vm_scene_anim_t me; }; // library function execution virtual bool operator()( vm_stack& stack, entry_t entry ) { SLF_PARMS; g_world_ptr->kill_scene_anim( parms->me ); SLF_DONE; } }; //slf_scene_anim_kill_anim_t slf_scene_anim_kill_anim(slc_scene_anim,"kill_anim()"); /////////////////////////////////////////////////////////////////////////////// // Global script functions supporting scene_anim class /////////////////////////////////////////////////////////////////////////////// // script library function: load_scene_anim( str name ) class slf_load_scene_anim_t : public script_library_class::function { public: // constructor required slf_load_scene_anim_t(const char* n) : script_library_class::function(n) {} // library function parameters struct parms_t { // parameters vm_str_t name; }; // library function execution virtual bool operator()( vm_stack& stack,entry_t entry ) { SLF_PARMS; g_world_ptr->load_scene_anim( *parms->name ); SLF_DONE; } }; //slf_load_scene_anim_t slf_load_scene_anim("load_scene_anim(str)"); // script library function: scene_anim play_scene_anim( str name ) class slf_play_scene_anim_t : public script_library_class::function { public: // constructor required slf_play_scene_anim_t(const char* n) : script_library_class::function(n) {} // library function parameters struct parms_t { // parameters vm_str_t name; }; // library function execution virtual bool operator()( vm_stack& stack,entry_t entry ) { SLF_PARMS; vm_scene_anim_t result = g_world_ptr->play_scene_anim( *parms->name ); SLF_RETURN; SLF_DONE; } }; //slf_play_scene_anim_t slf_play_scene_anim("play_scene_anim(str)"); void register_scene_anim_lib() { // pointer to single instance of library class slc_scene_anim_t* slc_scene_anim = NEW slc_scene_anim_t("scene_anim",4); NEW slf_scene_anim_kill_anim_t(slc_scene_anim,"kill_anim()"); NEW slf_load_scene_anim_t("load_scene_anim(str)"); NEW slf_play_scene_anim_t("play_scene_anim(str)"); }
[ "root@teamarchive2.fnf.archive.org" ]
root@teamarchive2.fnf.archive.org
add43762133cda296e673406482258a953657ac2
0495506c783c8f25694e13da1856d4a52102650a
/DSA learning series/Week 2/STFOOD.CPP
f1472b0adbdc5f7f2fb55f46a2eb76e00dce860a
[]
no_license
divyanshrastogi51/Data-Structures-and-algorithms
88e8746dec1044f912c4aa1c87cacf6023584246
294b5d5cef2944c01f15924e730f211b90531070
refs/heads/master
2023-02-07T13:08:51.283076
2020-12-28T10:13:05
2020-12-28T10:13:05
264,381,634
0
0
null
null
null
null
UTF-8
C++
false
false
485
cpp
#include <bits/stdc++.h> using namespace std; #define ll long long int int main() { ios::sync_with_stdio(0);cin.tie(0);cout.tie(0); ll t; cin>>t; while(t--) { ll n,ans=0; cin>>n; ll s[n],p[n],v[n]; for(ll i=0;i<n;i++) { cin>>s[i]>>p[i]>>v[i]; s[i]++; } for(ll i=0;i<n;i++) { ans=max(ans,(p[i]/s[i])*v[i]); } cout<<ans<<endl; } return 0; }
[ "54467001+divyanshrastogi51@users.noreply.github.com" ]
54467001+divyanshrastogi51@users.noreply.github.com
a57314feadea426a038ea478bd51bd962dfef143
d833434eb168ce1892366be0e0e92ad67efbe618
/Sequence/Button_sequence/Pushbutton.h
64440546037ab7e551b8d8f45fbf5bc55928e27c
[ "MIT" ]
permissive
jonra1993/Arduino_Examples
fa7041e99cf2f6ae1b78b60a76366dac1e9a43d8
3989c1afedf89f68beaf99388cf4ff50d006d057
refs/heads/master
2022-12-25T18:44:06.956580
2020-09-29T18:48:28
2020-09-29T18:48:28
174,265,960
0
0
MIT
2022-12-09T20:02:11
2019-03-07T03:37:57
C++
UTF-8
C++
false
false
6,068
h
// Copyright Pololu Corporation. For more information, see http://www.pololu.com/ /*! \file Pushbutton.h * * This is the main header file for the %Pushbutton library. * * For an overview of the library's features, see * https://github.com/pololu/pushbutton-arduino. That is the main repository * for the library, though copies of the library may exist in other * repositories. */ #pragma once #include <Arduino.h> /*! Indicates the that pull-up resistor should be disabled. */ #define PULL_UP_DISABLED 0 /*! Indicates the that pull-up resistor should be enabled. */ #define PULL_UP_ENABLED 1 /*! Indicates that the default (released) state of the button is when the * I/O line reads low. */ #define DEFAULT_STATE_LOW 0 /*! Indicates that the default (released) state of the button is when the * I/O line reads high. */ #define DEFAULT_STATE_HIGH 1 /*! The pin used for the button on the * [Zumo Shield for Arduino](http://www.pololu.com/product/2508). * * This does not really belong here in this general pushbutton library and will * probably be removed in the future. */ #define ZUMO_BUTTON 12 // \cond /** \brief A state machine that detects when a boolean value changes from false * to true, with debouncing. * * This should be considered a private implementation detail of the library. */ class PushbuttonStateMachine { public: PushbuttonStateMachine(); /** This should be called repeatedly in a loop. It will return true once after * each time it detects the given value changing from false to true. */ bool getSingleDebouncedRisingEdge(bool value); private: uint8_t state; uint16_t prevTimeMillis; }; // \endcond /*! \brief General pushbutton class that handles debouncing. * * This is an abstract class used for interfacing with pushbuttons. It knows * about debouncing, but it knows nothing about how to read the current state of * the button. The functions in this class get the current state of the button * by calling isPressed(), a virtual function which must be implemented in a * subclass of PushbuttonBase, such as Pushbutton. * * Most users of this library do not need to directly use PushbuttonBase or even * know that it exists. They can use Pushbutton instead.*/ class PushbuttonBase { public: /*! \brief Waits until the button is pressed and takes care of debouncing. * * This function waits until the button is in the pressed state and then * returns. Note that if the button is already pressed when you call this * function, it will return quickly (in 10 ms). */ void waitForPress(); /*! \brief Waits until the button is released and takes care of debouncing. * * This function waits until the button is in the released state and then * returns. Note that if the button is already released when you call this * function, it will return quickly (in 10 ms). */ void waitForRelease(); /*! \brief Waits until the button is pressed and then waits until the button * is released, taking care of debouncing. * * This is equivalent to calling waitForPress() and then waitForRelease(). */ void waitForButton(); /*! \brief Uses a state machine to return true once after each time it detects * the button moving from the released state to the pressed state. * * This is a non-blocking function that is meant to be called repeatedly in a * loop. Each time it is called, it updates a state machine that monitors the * state of the button. When it detects the button changing from the released * state to the pressed state, with debouncing, it returns true. */ bool getSingleDebouncedPress(); /*! \brief Uses a state machine to return true once after each time it detects the button moving from the pressed state to the released state. * * This is just like getSingleDebouncedPress() except it has a separate state * machine and it watches for when the button goes from the pressed state to * the released state. * * There is no strict guarantee that every debounced button press event * returned by getSingleDebouncedPress() will have a corresponding * button release event returned by getSingleDebouncedRelease(); the two * functions use independent state machines and sample the button at different * times. */ bool getSingleDebouncedRelease(); /*! \brief indicates whether button is currently pressed without any debouncing. * * @return 1 if the button is pressed right now, 0 if it is not. * * This function must be implemented in a subclass of PushbuttonBase, such as * Pushbutton. */ virtual bool isPressed() = 0; private: PushbuttonStateMachine pressState; PushbuttonStateMachine releaseState; }; /** \brief Main class for interfacing with pushbuttons. * * This class can interface with any pushbutton whose state can be read with * the `digitalRead` function, which is part of the Arduino core. * * See https://github.com/pololu/pushbutton-arduino for an overview * of the different ways to use this class. */ class Pushbutton : public PushbuttonBase { public: /** Constructs a new instance of Pushbutton. * * @param pin The pin number of the pin. This is used as an argument to * `pinMode` and `digitalRead`. * * @param pullUp Specifies whether the pin's internal pull-up resistor should * be enabled. This should be either #PULL_UP_ENABLED (which is the default if * the argument is omitted) or #PULL_UP_DISABLED. * * @param defaultState Specifies the voltage level that corresponds to the * button's default (released) state. This should be either * #DEFAULT_STATE_HIGH (which is the default if this argument is omitted) or * #DEFAULT_STATE_LOW. */ Pushbutton(uint8_t pin, uint8_t pullUp = PULL_UP_ENABLED, uint8_t defaultState = DEFAULT_STATE_HIGH); virtual bool isPressed(); private: void init() { if (!initialized) { initialized = true; init2(); } } void init2(); bool initialized; uint8_t _pin; bool _pullUp; bool _defaultState; };
[ "jon_ra@hotmail.es" ]
jon_ra@hotmail.es
f48d5ba75c28d29f23aaf09d1fb18a3df7256272
3ac127279d44ab691be1eab1720f6e06eb56872f
/main.cpp
1d0e434b01863f032ebad0ae86e23ceed03860b5
[]
no_license
neucoder/OPOnCpp
77261a841c767114f715e55b6e411118c358b3b6
9991df9aa71ce03d0173b3a60254264161464401
refs/heads/master
2020-05-23T15:45:39.445607
2019-07-22T11:48:25
2019-07-22T11:48:25
186,833,433
0
0
null
null
null
null
UTF-8
C++
false
false
310
cpp
#include <iostream> #include "cpp/GraphTheoryAndAlgorithm/MST.hxx" #include "cpp/Algorithm/beibao.hxx" #include "cpp/Algorithm/GA.hxx" #include "cpp/math/mathProblem.hxx" #include <vector> using namespace std; int main() { // test string str = "abc"; powerSet("abc"); getchar(); return 0; }
[ "neucoder@163.com" ]
neucoder@163.com
b2f793128e5b1761b5d14f39ca2a5959497744f3
c95f7f3695aa278563a04a5867950786a21b754a
/src/httprpc.h
de4d66cc01005b2b76e81c1dfa8cf4c2e2cb5fbd
[ "MIT" ]
permissive
bitcoinexodus/bitcoinexodus-source
e2a809ce6e07bcc5ea8c4c6c9eb260c4a486a8d0
742661b3dc9abce61c05fa1561b7fd9496629866
refs/heads/master
2022-11-20T08:34:01.892341
2020-07-23T15:45:08
2020-07-23T15:45:08
281,992,806
0
0
null
null
null
null
UTF-8
C++
false
false
830
h
// Copyright (c) 2015-2018 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef BITCOINEXODUS_HTTPRPC_H #define BITCOINEXODUS_HTTPRPC_H #include <string> #include <map> /** Start HTTP RPC subsystem. * Precondition; HTTP and RPC has been started. */ bool StartHTTPRPC(); /** Interrupt HTTP RPC subsystem. */ void InterruptHTTPRPC(); /** Stop HTTP RPC subsystem. * Precondition; HTTP and RPC has been stopped. */ void StopHTTPRPC(); /** Start HTTP REST subsystem. * Precondition; HTTP and RPC has been started. */ bool StartREST(); /** Interrupt RPC REST subsystem. */ void InterruptREST(); /** Stop HTTP REST subsystem. * Precondition; HTTP and RPC has been stopped. */ void StopREST(); #endif
[ "67246077+bitcoinexodus@users.noreply.github.com" ]
67246077+bitcoinexodus@users.noreply.github.com
d8bdf7d66f642552db31227e1ffb4306d4e0d3a7
a0b0eb383ecfeaeed3d2b0271657a0c32472bf8e
/leetcode/2001-3000/2140-solving-questions-with-brainpower.cpp
fc529889032e1e99432446605b65dfe2a90ece93
[ "Apache-2.0" ]
permissive
tangjz/acm-icpc
45764d717611d545976309f10bebf79c81182b57
f1f3f15f7ed12c0ece39ad0dd044bfe35df9136d
refs/heads/master
2023-04-07T10:23:07.075717
2022-12-24T15:30:19
2022-12-26T06:22:53
13,367,317
53
20
Apache-2.0
2022-12-26T06:22:54
2013-10-06T18:57:09
C++
UTF-8
C++
false
false
393
cpp
class Solution { public: long long mostPoints(vector<vector<int>>& seq) { typedef long long LL; int n = seq.size(); vector<LL> dp(n + 1); for(int i = 0; i < n; ++i) { dp[i + 1] = max(dp[i + 1], dp[i]); int j = min(i + seq[i][1] + 1, n); dp[j] = max(dp[j], dp[i] + seq[i][0]); } return dp.back(); } };
[ "t251346744@gmail.com" ]
t251346744@gmail.com
eaf6c4429e579d478b3299d4732eaf627ce9e97c
caae5375bfa3a6144e6921e7a00d1a927de8063e
/source/tests/structures/set/MySet_UnitTest.cpp
2753add0a878e4f9dadaac06a4d8cd78ed427d9e
[]
no_license
fcomuniz/my-lib
599a70131f69a45b9289e4761a49fb2c1e4e1f62
a0df4ce25096c96100224899c00a2aee0c988206
refs/heads/master
2020-03-06T18:03:02.988987
2018-03-27T23:49:22
2018-03-27T23:49:22
126,999,295
0
0
null
null
null
null
UTF-8
C++
false
false
896
cpp
#include "structures/set/MySet.h" #include <gtest/gtest.h> #include <fstream> #include <string> using namespace std; using my_lib::MySet; TEST(MySet, addingAndRemovingElements){ MySet<int,1000> mySet; mySet.insert(1); ASSERT_TRUE(mySet.hasValue(1)); ASSERT_FALSE(mySet.hasValue(2)); mySet.insert(2); ASSERT_TRUE(mySet.hasValue(2)); mySet.remove(2); ASSERT_FALSE(mySet.hasValue(2)); ASSERT_TRUE(mySet.hasValue(1)); } TEST(MySet, addingAndRemovingElementsDouble){ MySet<double,1000> mySet; mySet.insert(1); ASSERT_TRUE(mySet.hasValue(1)); ASSERT_FALSE(mySet.hasValue(2)); mySet.insert(2); ASSERT_TRUE(mySet.hasValue(2)); mySet.remove(2); ASSERT_FALSE(mySet.hasValue(2)); ASSERT_TRUE(mySet.hasValue(1)); } TEST(MySet, addingManyElements){ ifstream f("MySetTest.txt") ; MySet<int,100> mySet; std::string line; while(getline(f,line)){ mySet.insert(stoi(line)); } }
[ "munizfco@gmail.com" ]
munizfco@gmail.com
7fe9f7da55a166f92ec1362fba3f4269e7ed000f
b4ce2e4c28cceec2a46c62bb779bd85992f407a0
/software/sjSkeletonizer/source/core/sjPlugin.cpp
49f5314bbd2f807a3dbf89110de7fe037dfb9c3d
[]
no_license
hksonngan/jeronimo
b4b148d0d7fb3514357eb1d001601492bbc6ab59
9b803e1194be0fa6f3d5a8895e32fb84a028b0b5
refs/heads/master
2021-01-10T10:04:50.282419
2015-04-12T00:45:09
2015-04-12T00:45:09
47,669,420
1
0
null
null
null
null
UTF-8
C++
false
false
579
cpp
#include "sjPlugin.h" using namespace sj; sjPlugin::sjPlugin() :m_pfnRegisterPlugin(0){ } sjPlugin::sjPlugin(const sjPlugin &Other) :m_pfnRegisterPlugin(Other.m_pfnRegisterPlugin), name(Other.name){ } sjPlugin::~sjPlugin(){ } std::string sjPlugin::getName(){ return name; } std::string sjPlugin::getNameType(){ return name_type; } std::string sjPlugin::getPluginName(){ return name_type + "->" + name; } void sjPlugin::registerPlugin(sjKernelPlugin & K) { if(m_pfnRegisterPlugin == NULL)return; m_pfnRegisterPlugin(K, name); }
[ "apinzonf@78a4e28a-90cd-11de-9d83-e924b18393b8" ]
apinzonf@78a4e28a-90cd-11de-9d83-e924b18393b8
52eed4fa2c18429dae26b06079f0c438f1aa2f5a
2ba94892764a44d9c07f0f549f79f9f9dc272151
/Engine/Source/Runtime/Renderer/Private/PostProcess/PostProcessVisualizeBuffer.h
523944a9da5b80df7e5670fd2565b1ce774a0012
[ "BSD-2-Clause", "LicenseRef-scancode-proprietary-license" ]
permissive
PopCap/GameIdea
934769eeb91f9637f5bf205d88b13ff1fc9ae8fd
201e1df50b2bc99afc079ce326aa0a44b178a391
refs/heads/master
2021-01-25T00:11:38.709772
2018-09-11T03:38:56
2018-09-11T03:38:56
37,818,708
0
0
BSD-2-Clause
2018-09-11T03:39:05
2015-06-21T17:36:44
null
UTF-8
C++
false
false
1,374
h
// Copyright 1998-2015 Epic Games, Inc. All Rights Reserved. /*============================================================================= PostProcessVisualizeBuffer.h: Post processing buffer visualization =============================================================================*/ #pragma once #include "RenderingCompositionGraph.h" // derives from TRenderingCompositePassBase<InputCount, OutputCount> // ePId_Input0: SceneColor // ePId_Input1: SeparateTranslucency class FRCPassPostProcessVisualizeBuffer : public TRenderingCompositePassBase<2, 1> { public: /** Data for a single buffer overview tile **/ struct TileData { FRenderingCompositeOutputRef Source; FString Name; TileData(FRenderingCompositeOutputRef InSource, const FString& InName) : Source (InSource) , Name (InName) { } }; // constructor void AddVisualizationBuffer(FRenderingCompositeOutputRef InSource, const FString& InName); // interface FRenderingCompositePass --------- virtual void Process(FRenderingCompositePassContext& Context) override; virtual void Release() override { delete this; } virtual FPooledRenderTargetDesc ComputeOutputDesc(EPassOutputId InPassOutputId) const override; private: // @return VertexShader template <bool bDrawTileTemplate> FShader* SetShaderTempl(const FRenderingCompositePassContext& Context); TArray<TileData> Tiles; };
[ "dkroell@acm.org" ]
dkroell@acm.org
9c9c674c7159faccb6d7c0c24db474569e1ebd37
add70b6fd60742e5cb7bfda75ed6f00df542921d
/Eternity Engine (Outerspace)/Code/code/ETY-Engine/Dev-Libs/boost_old/mpl/aux_/config/forwarding.hpp
babecd1c935d457c418a22fe821772b02ab6b12d
[]
no_license
jsaevecke/Harbinger-of-Eternity-2D-Space-Game
0e6f3484c91154978eb374c8936dc1d3c0f94570
17185227648972c7ae206bbb8498cccff83b232e
refs/heads/master
2021-09-29T08:18:35.420165
2018-02-26T16:34:22
2018-02-26T16:34:22
null
0
0
null
null
null
null
UTF-8
C++
false
false
820
hpp
#ifndef BOOST_MPL_AUX_CONFIG_FORWARDING_HPP_INCLUDED #define BOOST_MPL_AUX_CONFIG_FORWARDING_HPP_INCLUDED // Copyright Aleksey Gurtovoy 2004 // // 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) // // See http://www.boost.org/libs/mpl for documentation. // $Id: forwarding.hpp 3 2013-07-17 10:04:05Z Trout-31 $ // $Date: 2013-07-17 12:04:05 +0200 (Mi, 17 Jul 2013) $ // $Revision: 3 $ #include <boost/mpl/aux_/config/workaround.hpp> #if !defined(BOOST_MPL_CFG_NO_NESTED_FORWARDING) \ && !defined(BOOST_MPL_PREPROCESSING_MODE) \ && BOOST_WORKAROUND(__BORLANDC__, BOOST_TESTED_AT(0x610)) # define BOOST_MPL_CFG_NO_NESTED_FORWARDING #endif #endif // BOOST_MPL_AUX_CONFIG_FORWARDING_HPP_INCLUDED
[ "Julien.Saevecke@udo.edu" ]
Julien.Saevecke@udo.edu
744cc32186bcc60ae6cd5714f03c5fe453cd9bbd
fc6bb5893ea122a848e5138dee1a1b2a740c0432
/myEmailTools/main.cpp
5441f61002c89c706699e20e07e3063d7587208c
[]
no_license
QtWorks/QtDemos
f5046335503762b78466130c0974c641d77466ba
2473fa5dbf718b4e5e4238696051c110d1d4b146
refs/heads/master
2020-04-27T19:20:02.103689
2019-03-07T06:44:23
2019-03-07T06:44:23
null
0
0
null
null
null
null
UTF-8
C++
false
false
774
cpp
#include "frmmain.h" #include <QApplication> #include <QTextCodec> #include <QDesktopWidget> int main(int argc, char *argv[]) { QApplication a(argc, argv); //设置UTF-8编码 QTextCodec *codec=QTextCodec::codecForName("UTF-8"); QTextCodec::setCodecForLocale(codec); // QTextCodec::setCodecForCStrings(codec); // QTextCodec::setCodecForTr(codec); //设置全局样式 // qApp->setStyle("Plastique"); frmMain w; //设置窗体居中 int deskWidth=qApp->desktop()->availableGeometry().width(); int deskHeigth=qApp->desktop()->availableGeometry().height(); int frmX=w.width(); int frmY=w.height(); QPoint movePoint(deskWidth/2-frmX/2,deskHeigth/2-frmY/2); w.move(movePoint); w.show(); return a.exec(); }
[ "anyetiangong@qq.com" ]
anyetiangong@qq.com
83211a543883ae3530343ca29cbbe7d1036190ed
c0fc2cb70c91aa958f880e4a37e764f761e19c98
/c++/include/leet-code/data-structures/list-node.h
21879bc855bdf2047bd1c651380a9a230f3a1632
[]
no_license
EFanZh/LeetCode
6ec36b117c5f16f2a1ca6d5aac932ff67b461800
591004c0b28242260352c0e43c9a83d2e4a22e39
refs/heads/master
2023-08-18T15:36:00.314222
2023-08-07T15:30:00
2023-08-07T15:30:00
151,554,211
223
17
null
2020-12-13T15:09:46
2018-10-04T10:24:22
Rust
UTF-8
C++
false
false
356
h
#ifndef LEET_CODE_DATA_STRUCTURES_LIST_NODE_H #define LEET_CODE_DATA_STRUCTURES_LIST_NODE_H namespace leet_code::data_structures::list_node { struct ListNode { int val; ListNode *next = nullptr; explicit ListNode(int x) : val{x} { } }; } // namespace leet_code::data_structures::list_node #endif // LEET_CODE_DATA_STRUCTURES_LIST_NODE_H
[ "efanzh@gmail.com" ]
efanzh@gmail.com
f12b2f0d1568b313e22bf14caf51e554854dc39e
b77349e25b6154dae08820d92ac01601d4e761ee
/Apps/Burning/CDBurn/ImageHeader/StudyProtocol.h
4b96c8e7efb9927e22bd248c89b54c2dab791a6a
[]
no_license
ShiverZm/MFC
e084c3460fe78f820ff1fec46fe1fc575c3e3538
3d05380d2e02b67269d2f0eb136a3ac3de0dbbab
refs/heads/master
2023-02-21T08:57:39.316634
2021-01-26T10:18:38
2021-01-26T10:18:38
332,725,087
0
0
null
2021-01-25T11:35:20
2021-01-25T11:29:59
null
UTF-8
C++
false
false
4,240
h
/******************************************************************** File Name: StudyProtocol.h Written by: Yang Guang Copyright(C) XinaoMDT, 2001 - Purpose: This file defines following classes: History: 2002/3/28 Created. *********************************************************************/ #if !defined(AFX_STUDYPROTOCOL_H__AF2BC97A_CFBC_4CF9_91F0_811CA37AA9D3__INCLUDED_) #define AFX_STUDYPROTOCOL_H__AF2BC97A_CFBC_4CF9_91F0_811CA37AA9D3__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 #pragma warning (disable:4786) #include <vector> #include "BI_Constants.h" #include "../BIGlobals/BI_ImageHeader.h" #include "Study.h" #include "../BIGlobals/inifile.h" class CSeriesProtocol; typedef std::vector<CSeriesProtocol*> CSeriesProtocolContainer; typedef CSeriesProtocolContainer::iterator CSeriesProtocolIter; typedef CSeriesProtocolContainer::const_iterator CSeriesProtocolConstIter; #ifdef IMAGEHEADER_IMP #define CLASS_DECL_IMAGEHEADER __declspec(dllexport) #else #define CLASS_DECL_IMAGEHEADER __declspec(dllimport) #endif struct CStudyProtocolField { char m_achTag[4]; //!< "BIP\0" //! Version of the field format: (major_version << 16) + lower_version. unsigned int m_uFormatVersion; unsigned int m_uSize; //!< Size of this field. unsigned char m_ucNumSeries; //!< Number of series. char m_achDesc[128]; //!< Description of protocol unsigned short m_usProtocolVersion; //!< Version of protocol used. BIDateTime m_timeCreated; //!< Date/time of creation. char m_achCreator[16]; //!< ID of the protocol creator. EBodyPosition m_BodyPosition; //!< Position of the patient. EBodyEntry m_BodyEntry; //!< Entry of the patient. EBodyPart m_PatBodyPart; //!< Part of body examined. ELandmarkPosition m_LandmarkPos; //!< Scan landmark position reference. char m_achGradientId[32]; //!< ID of Gradient coil. }; //! This class is used to store a study protocol. /*! A study protocol is simply a template for generating study */ class CLASS_DECL_IMAGEHEADER CStudyProtocol { public: enum EProtocolType { ptUnknown, ptSystem, ptUser, ptUnsorted, }; //! Container used to hold series protocols. CSeriesProtocolContainer m_SeriesProtocols; public: //! \name Constructors and destructor //@{ //! Constructor. CStudyProtocol(); explicit CStudyProtocol(const CStudy& study, std::string strName = ""); //! Destructor. virtual ~CStudyProtocol(); //@} const CStudyProtocol& operator= (const CStudy& study); //! Returns pointer to the series protocol container. CSeriesProtocolContainer& GetSeriesProtocols() { return m_SeriesProtocols; } //! Returns pointer to the series protocol container. const CSeriesProtocolContainer& GetSeriesProtocols() const { return m_SeriesProtocols; } //! Save the protocol to file. bool Save(EProtocolType type); //! Load the protocol from file. bool Load(EProtocolType type, std::string strName = "", unsigned short usVersion = 256 /* version 1.0 */); //begin dolphin bool Save(CIniFile& inifile,EProtocolType type); bool Load(CIniFile& inifile,EProtocolType type, std::string strName = "", unsigned short usVersion = 256 /* version 1.0 */); //end CStudyProtocolField& Params() { return m_Parameters; } const CStudyProtocolField& Params() const { return m_Parameters; } std::string& GetName() { return m_strName; } const std::string& GetName() const { return m_strName; } void SetName(const std::string& strName) { m_strName = strName; } //! Create a new study based on this protocol. CStudy* CreateStudy() const; protected: CStudyProtocolField m_Parameters; std::string GetProtocolSubDirectory(EProtocolType type); static bool SetRootDirectory(const std::string& strRoot); EProtocolType m_Type; std::string m_strName; static std::string s_strRoot; }; #endif // !defined(AFX_STUDYPROTOCOL_H__AF2BC97A_CFBC_4CF9_91F0_811CA37AA9D3__INCLUDED_)
[ "w.z.y2006@163.com" ]
w.z.y2006@163.com
94b493ffbf321ea9abe1a04777939ddb93304007
f81124e4a52878ceeb3e4b85afca44431ce68af2
/re20_2/processor24/40/phi
0e35e998272fb40b9c9260222569056c6a2886cc
[]
no_license
chaseguy15/coe-of2
7f47a72987638e60fd7491ee1310ee6a153a5c10
dc09e8d5f172489eaa32610e08e1ee7fc665068c
refs/heads/master
2023-03-29T16:59:14.421456
2021-04-06T23:26:52
2021-04-06T23:26:52
355,040,336
0
1
null
null
null
null
UTF-8
C++
false
false
12,620
/*--------------------------------*- C++ -*----------------------------------*\ ========= | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox \\ / O peration | Website: https://openfoam.org \\ / A nd | Version: 7 \\/ M anipulation | \*---------------------------------------------------------------------------*/ FoamFile { version 2.0; format ascii; class surfaceScalarField; location "40"; object phi; } // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // dimensions [0 3 -1 0 0 0 0]; internalField nonuniform List<scalar> 637 ( -6.67441e-05 6.99471e-06 -3.628e-13 -7.37592e-05 7.01506e-06 -2.29742e-13 -8.07376e-05 6.97841e-06 -5.34698e-14 -8.76354e-05 6.8978e-06 1.71011e-13 6.7911e-06 4.46128e-13 -6.51461e-05 1.37307e-05 -7.1867e-05 1.3736e-05 -7.85121e-05 1.36235e-05 -8.50333e-05 1.34189e-05 1.31581e-05 -6.1962e-05 1.99513e-05 -6.80969e-05 1.98709e-05 -7.40776e-05 1.96042e-05 -7.98479e-05 1.91893e-05 -8.53693e-05 1.86795e-05 1.81443e-05 -5.72153e-05 2.54033e-05 -6.24763e-05 2.51319e-05 -6.74662e-05 2.45941e-05 -7.21165e-05 2.38396e-05 -7.6376e-05 2.2939e-05 2.19855e-05 -5.09401e-05 2.98392e-05 -5.50455e-05 2.92373e-05 -5.8725e-05 2.82735e-05 -6.18933e-05 2.70079e-05 -6.44824e-05 2.55281e-05 2.39513e-05 -4.31791e-05 -4.58554e-05 3.19136e-05 -4.79136e-05 3.03317e-05 -4.92477e-05 2.83421e-05 -4.9768e-05 2.60484e-05 2.35927e-05 -3.49654e-05 3.28968e-05 -3.51024e-05 3.04687e-05 -3.42617e-05 2.75014e-05 -3.2327e-05 2.41137e-05 2.04729e-05 -2.24411e-05 3.19343e-05 -2.03696e-05 2.83972e-05 -1.70275e-05 2.41593e-05 -1.2266e-05 1.93522e-05 1.41686e-05 -8.35119e-06 -3.79861e-06 2.38446e-05 2.35514e-06 1.80055e-05 1.02969e-05 1.14105e-05 2.01892e-05 4.27626e-06 -3.09763e-06 1.45264e-05 1.65543e-05 2.37832e-05 8.74871e-06 3.52376e-05 -4.38464e-08 4.90984e-05 -9.58456e-06 -1.95292e-05 3.45247e-05 6.28652e-06 4.71556e-05 -3.88218e-06 6.24314e-05 -1.53196e-05 8.06156e-05 -2.77688e-05 -4.08399e-05 5.61235e-05 7.23779e-05 -2.01366e-05 9.17578e-05 -3.46996e-05 0.000114591 -5.06016e-05 0.00014116 -6.74096e-05 -8.45077e-05 9.93682e-05 -4.02417e-05 0.000123107 -5.84383e-05 0.00015088 -7.83744e-05 0.00018305 -9.95803e-05 -0.000121346 0.000128063 0.000156386 -8.67609e-05 0.000189352 -0.000111341 0.000227421 -0.00013765 -0.000164886 0.000191527 -0.000119864 0.0002299 -0.000149714 0.000274115 -0.000181865 0.000324669 -0.00021544 -0.000248964 0.000228495 0.000272446 -0.000193665 0.000322995 -0.000232414 0.0003808 -0.000273245 -0.000314469 0.000316961 -0.000243327 0.000373964 -0.000289418 0.000439167 -0.000338447 0.000513256 -0.000388559 -0.000435807 0.000363478 0.000426997 -0.000352937 0.000499638 -0.000411088 0.000582429 -0.00047135 -0.000529133 0.000482173 0.000562187 -0.000491102 0.000653628 -0.000562791 -0.000632981 0.000626972 0.00072681 -0.000662629 -0.000747335 0.000841163 0.00080224 -0.00077042 -0.000871851 0.000926756 0.000880714 -0.0010061 0.00101496 0.00110808 0.0010061 0.00110808 0.000880714 0.00077042 0.000871851 0.00101496 0.000694449 0.000578352 0.00080224 0.000662629 0.000747335 0.000926756 0.000626972 0.000491102 0.00072681 0.000562791 0.000632981 0.000841163 0.000482173 0.000352937 0.000562187 0.000411088 0.000653628 0.00047135 0.000529133 0.000363478 0.000243327 0.000426997 0.000289418 0.000499638 0.000338447 0.000582429 0.000388559 0.000435807 0.000316961 0.000193665 0.000373964 0.000232414 0.000439167 0.000273245 0.000513256 0.000314469 0.000228495 0.000119864 0.000272446 0.000149714 0.000322995 0.000181865 0.0003808 0.00021544 0.000248964 0.000191527 8.67609e-05 0.0002299 0.000111341 0.000274115 0.00013765 0.000324669 0.000164886 0.000128063 4.02417e-05 0.000156386 5.84383e-05 0.000189352 7.83744e-05 0.000227421 9.95803e-05 0.000121346 9.93682e-05 2.01366e-05 0.000123107 3.46996e-05 0.00015088 5.06016e-05 0.00018305 6.74096e-05 8.45077e-05 5.61235e-05 -6.28653e-06 7.23779e-05 3.88218e-06 9.17578e-05 1.53196e-05 0.000114591 2.77688e-05 0.00014116 4.08399e-05 3.45247e-05 -1.65543e-05 4.71556e-05 -8.74871e-06 6.24314e-05 4.38437e-08 8.06156e-05 9.58455e-06 1.95292e-05 7.2361e-06 -2.87857e-05 1.45264e-05 -2.38447e-05 2.37832e-05 -1.80055e-05 3.52376e-05 -1.14105e-05 4.90984e-05 -4.27627e-06 3.09763e-06 -8.35119e-06 -3.19343e-05 -3.79861e-06 -2.83972e-05 2.35514e-06 -2.41593e-05 1.02969e-05 -1.93522e-05 2.01892e-05 -1.41686e-05 -2.24411e-05 -3.28968e-05 -2.03696e-05 -3.04687e-05 -1.70275e-05 -2.75014e-05 -1.2266e-05 -2.41137e-05 -2.04729e-05 -3.49654e-05 -3.19136e-05 -3.51024e-05 -3.03317e-05 -3.42617e-05 -2.83421e-05 -3.2327e-05 -2.60484e-05 -2.35927e-05 -4.31791e-05 -2.98392e-05 -4.58554e-05 -2.92373e-05 -4.79136e-05 -2.82735e-05 -4.92477e-05 -2.70079e-05 -4.9768e-05 -2.55281e-05 -2.39513e-05 -5.09401e-05 -2.54033e-05 -5.50455e-05 -2.51319e-05 -5.8725e-05 -2.45941e-05 -6.18933e-05 -2.38396e-05 -6.44824e-05 -2.2939e-05 -2.19855e-05 -5.72153e-05 -1.99513e-05 -6.24763e-05 -1.98709e-05 -6.74662e-05 -1.96042e-05 -7.21165e-05 -1.91893e-05 -7.6376e-05 -1.86795e-05 -1.81443e-05 -6.1962e-05 -1.37307e-05 -6.80969e-05 -1.3736e-05 -7.40776e-05 -1.36235e-05 -7.98479e-05 -1.34189e-05 -8.53693e-05 -1.31581e-05 -6.51461e-05 -6.99471e-06 -7.1867e-05 -7.01506e-06 -7.85121e-05 -6.97841e-06 -8.50333e-05 -6.8978e-06 -6.7911e-06 -6.67441e-05 -7.37592e-05 -8.07376e-05 -8.76354e-05 -0.000113594 -0.000139178 -0.000167272 0.00113748 -0.000196666 -0.000284771 0.00123918 -0.000227001 -0.000295394 0.00555772 -0.000121622 -0.000210578 0.00673707 2.63687e-06 -8.16743e-05 0.00774468 0.000139194 5.56584e-05 0.00858957 0.000276794 0.000190739 0.00926903 0.000405722 0.000315626 0.00978953 0.0005176 0.000424405 0.0101657 0.000607389 0.000513258 0.0104185 0.000673477 0.000580818 0.010572 0.000716991 0.000627871 0.0106497 0.000740807 0.000656687 0.0106728 0.000748588 0.0006703 0.0106588 0.000744048 0.000671898 0.0106209 0.000730503 0.000664416 0.0105688 0.00071066 0.000650334 0.0105093 0.000686592 0.000631608 0.0104467 0.000659807 0.000609711 0.0103838 0.000631361 0.000585709 0.0103222 0.000601974 0.000560354 0.0102628 0.000572127 0.00053417 0.0102062 0.000542137 0.000507514 0.0101526 0.000512211 0.000480632 0.010102 0.000482483 0.000453693 0.0100546 0.000453039 0.000426813 0.0100103 0.000423929 0.000400069 0.00996905 0.000395183 0.000373512 0.00993073 0.000366814 0.000347177 0.00989529 0.000338822 0.00032108 0.00986268 0.000311199 0.000295231 0.00983282 0.00028393 0.000269629 0.00980565 0.000256996 0.000244268 0.00978113 0.000230375 0.000219136 0.00975919 0.00020404 0.000194218 0.00973979 0.000177962 0.000169495 0.0097229 0.000152112 0.000144947 0.00970848 0.000126457 0.00012055 0.0096965 0.000100963 9.62781e-05 0.00968696 7.5596e-05 7.21075e-05 0.00967985 5.03273e-05 4.80155e-05 0.00967515 2.51317e-05 2.39845e-05 0.00967284 -0.000121622 0.00555772 0.000227001 2.63689e-06 0.00673707 0.000139194 0.00774468 0.000276794 0.00858957 0.000405722 0.00926903 0.0005176 0.00978953 0.000607389 0.0101657 0.000673477 0.0104185 0.000716991 0.010572 0.000740807 0.0106497 0.000748588 0.0106728 0.000744048 0.0106588 0.000730503 0.0106209 0.00071066 0.0105688 0.000686592 0.0105093 0.000659807 0.0104467 0.000631361 0.0103838 0.000601974 0.0103222 0.000572127 0.0102628 0.000542137 0.0102062 0.000512211 0.0101526 0.000482483 0.010102 0.000453039 0.0100546 0.000423929 0.0100103 0.000395183 0.00996905 0.000366814 0.00993073 0.000338822 0.00989529 0.000311199 0.00986268 0.00028393 0.00983282 0.000256996 0.00980565 0.000230375 0.00978113 0.00020404 0.00975919 0.000177962 0.00973979 0.000152112 0.0097229 0.000126457 0.00970848 0.000100963 0.0096965 7.5596e-05 0.00968696 5.03273e-05 0.00967985 2.51317e-05 0.00967515 0.00967284 -0.000210578 0.000295394 -8.16742e-05 5.56585e-05 0.000190739 0.000315626 0.000424406 0.000513258 0.000580818 0.000627871 0.000656687 0.0006703 0.000671898 0.000664416 0.000650334 0.000631608 0.000609711 0.000585709 0.000560354 0.00053417 0.000507514 0.000480632 0.000453693 0.000426813 0.000400069 0.000373513 0.000347177 0.00032108 0.000295231 0.000269629 0.000244268 0.000219136 0.000194218 0.000169495 0.000144947 0.00012055 9.62781e-05 7.21074e-05 4.80155e-05 2.39845e-05 0.00123918 0.000196666 0.000284771 0.00113748 0.000167272 0.000139177 0.000113594 ) ; boundaryField { inlet { type calculated; value nonuniform 0(); } outlet { type calculated; value nonuniform 0(); } cylinder { type calculated; value nonuniform 0(); } top { type symmetryPlane; value uniform 0; } bottom { type symmetryPlane; value uniform 0; } defaultFaces { type empty; value nonuniform 0(); } procBoundary24to23 { type processor; value nonuniform List<scalar> 148 ( 5.97494e-05 5.84101e-05 5.57414e-05 5.17633e-05 4.65042e-05 3.99998e-05 3.30185e-05 3.39822e-05 2.34037e-05 1.14997e-05 2.87857e-05 -7.2361e-06 -2.42569e-05 -4.26558e-05 -7.18112e-06 -7.9263e-05 -0.000103901 -6.44036e-05 -0.000158424 -0.000190441 -0.000157918 -0.000267299 -0.000307995 -0.000298811 -0.000412115 -0.000422994 -0.000539722 -0.000578352 -0.000694449 -0.000765474 -0.00088566 -0.000964445 -0.00114973 -0.00120885 -0.00114973 -0.00120885 -0.000964445 -0.00088566 -0.000765474 -0.000672738 -0.000600063 -0.000539722 -0.000422994 -0.000412115 -0.000298811 -0.000307995 -0.000267299 -0.000157918 -0.000190441 -0.000158424 -6.44036e-05 -0.000103901 -7.9263e-05 -7.18112e-06 -4.26558e-05 -2.42569e-05 2.32245e-05 -1.67486e-06 1.14997e-05 2.34037e-05 3.39822e-05 3.30185e-05 3.99998e-05 4.65042e-05 5.17633e-05 5.57414e-05 5.84101e-05 5.97494e-05 -0.0056631 -0.00686133 -0.00788124 -0.00872717 -0.00939795 -0.00990141 -0.0102555 -0.0104846 -0.0106155 -0.0106735 -0.0106806 -0.0106542 -0.0106073 -0.010549 -0.0104852 -0.0104199 -0.0103553 -0.0102928 -0.0102329 -0.0101762 -0.0101226 -0.0100723 -0.0100252 -0.00998123 -0.0099403 -0.00990236 -0.0098673 -0.00983505 -0.00980555 -0.00977872 -0.00975451 -0.00973285 -0.00971371 -0.00969705 -0.00968282 -0.00967101 -0.0096616 -0.00965458 -0.00964995 -0.00964771 -0.0056631 -0.00686133 -0.00788124 -0.00872717 -0.00939795 -0.00990141 -0.0102555 -0.0104846 -0.0106155 -0.0106735 -0.0106806 -0.0106542 -0.0106073 -0.010549 -0.0104852 -0.0104199 -0.0103553 -0.0102928 -0.0102329 -0.0101762 -0.0101226 -0.0100723 -0.0100252 -0.00998123 -0.0099403 -0.00990236 -0.0098673 -0.00983505 -0.00980555 -0.00977872 -0.00975451 -0.00973285 -0.00971371 -0.00969705 -0.00968282 -0.00967101 -0.0096616 -0.00965458 -0.00964995 -0.00964771 ) ; } procBoundary24to25 { type processor; value nonuniform List<scalar> 142 ( -9.44265e-05 -9.14002e-05 -1.28871e-05 -9.06265e-05 -8.02172e-05 -6.64482e-05 -4.94094e-05 -2.92072e-05 -5.96166e-06 -8.86539e-06 3.21522e-05 6.55299e-05 0.000101926 5.40068e-05 0.000171661 0.000219889 0.000270961 0.000191798 0.000381835 0.000446305 0.000352788 0.000596274 0.000675756 0.000757477 0.000757477 0.000675756 0.000352788 0.000596274 0.000446305 0.000381835 0.000191798 0.000270961 0.000219889 0.000171661 5.40067e-05 0.000101926 6.55299e-05 3.21522e-05 -8.8654e-06 -5.96167e-06 -2.92072e-05 -4.94094e-05 -6.64482e-05 -8.02172e-05 -9.06265e-05 -1.28871e-05 -9.14002e-05 -9.44265e-05 9.091e-05 0.000863847 0.00095234 0.00104305 0.00026596 0.00115629 0.0012498 0.00547291 0.00660817 0.00760735 0.00845449 0.00914414 0.00968075 0.0100768 0.010351 0.0105249 0.0106209 0.0106592 0.0106572 0.0106283 0.0105829 0.010528 0.0104686 0.0104078 0.0103475 0.010289 0.0102328 0.0101794 0.010129 0.0100815 0.0100371 0.00999561 0.00995706 0.00992139 0.00988853 0.00985842 0.00983101 0.00980626 0.00978411 0.00976451 0.00974745 0.00973287 0.00972077 0.00971113 0.00970394 0.00969918 0.00969682 0.00547291 0.00660817 0.00760735 0.00845449 0.00914414 0.00968075 0.0100768 0.010351 0.0105249 0.0106209 0.0106592 0.0106572 0.0106283 0.0105829 0.010528 0.0104686 0.0104078 0.0103475 0.010289 0.0102328 0.0101794 0.010129 0.0100815 0.0100371 0.00999561 0.00995706 0.00992139 0.00988853 0.00985842 0.00983102 0.00980626 0.00978411 0.00976451 0.00974745 0.00973287 0.00972077 0.00971113 0.00970394 0.00969918 0.00969682 0.0012498 0.00115629 0.00026596 0.00104305 0.00095234 0.000863847 9.091e-05 ) ; } } // ************************************************************************* //
[ "chaseh13@login4.stampede2.tacc.utexas.edu" ]
chaseh13@login4.stampede2.tacc.utexas.edu
f5a9d863f0ac75407f9690a274970b6621cf7dfc
cae2280fb8310888c003cf936e7643a29599dd6d
/tools/vio2sf/src/foobar8/foobar2000/helpers/dropdown_helper.cpp
ec00a27ee54cfca7ff8a1abc079ba584874b0a2e
[]
no_license
icedream/desmume
7f674f450c06eaf372dc4b5ad7df39e22311aa32
a5e7d85acf928493650f80b69dbf96ec5555a2c4
refs/heads/master
2021-01-20T21:48:47.655011
2015-01-23T13:19:17
2015-01-23T13:23:20
22,377,003
5
1
null
null
null
null
UTF-8
C++
false
false
1,659
cpp
#include "stdafx.h" #include "dropdown_helper.h" void cfg_dropdown_history::build_list(ptr_list_simple<char> & out) { const char * src = data; while(*src) { int ptr = 0; while(src[ptr] && src[ptr]!=separator) ptr++; if (ptr>0) { out.add_item(strdup_n(src,ptr)); src += ptr; } while(*src==separator) src++; } } void cfg_dropdown_history::parse_list(const ptr_list_simple<char> & src) { unsigned n; string8 temp; temp.set_mem_logic(mem_block::ALLOC_FAST); for(n=0;n<src.get_count();n++) { temp.add_string(src[n]); temp.add_char(separator); } data = temp; } void cfg_dropdown_history::setup_dropdown(HWND wnd) { ptr_list_simple<char> list; build_list(list); unsigned n; for(n=0;n<list.get_count();n++) { uSendMessageText(wnd,CB_ADDSTRING,0,list[n]); } list.free_all(); } void cfg_dropdown_history::add_item(const char * item) { if (!item || !*item) return; string8 meh; if (strchr(item,separator)) { uReplaceChar(meh,item,-1,separator,'|',false); item = meh; } ptr_list_simple<char> list; build_list(list); unsigned n; bool found = false; for(n=0;n<list.get_count();n++) { if (!strcmp(list[n],item)) { char* temp = list.remove_by_idx(n); list.insert_item(temp,0); found = true; } } if (!found) { while(list.get_count() > max) list.delete_by_idx(list.get_count()-1); list.insert_item(strdup(item),0); } parse_list(list); list.free_all(); } bool cfg_dropdown_history::is_empty() { const char * src = data; while(*src) { if (*src!=separator) return false; src++; } return true; }
[ "kode54@5577840e-afb3-4e59-9ef3-2b7f898b1952" ]
kode54@5577840e-afb3-4e59-9ef3-2b7f898b1952
431f8af02602a11e631f7097b571cd2cccaf5423
349fe789ab1e4e46aae6812cf60ada9423c0b632
/FIB_DataModule/REM_DocRemontKKT/UREM_DMDocRemontKKT.h
92e6e751c8b9d1c11679da08188a7ec447f59261
[]
no_license
presscad/ERP
a6acdaeb97b3a53f776677c3a585ca860d4de980
18ecc6c8664ed7fc3f01397d587cce91fc3ac78b
refs/heads/master
2020-08-22T05:24:15.449666
2019-07-12T12:59:13
2019-07-12T12:59:13
216,326,440
1
0
null
2019-10-20T07:52:26
2019-10-20T07:52:26
null
WINDOWS-1251
C++
false
false
5,367
h
//--------------------------------------------------------------------------- #ifndef UREM_DMDocRemontKKTH #define UREM_DMDocRemontKKTH //--------------------------------------------------------------------------- #include "IDMFibConnection.h" //--------------------------------------------------------------------------- #include <Classes.hpp> #include <Controls.hpp> #include <StdCtrls.hpp> #include <Forms.hpp> #include <DB.hpp> #include <IBCustomDataSet.hpp> #include <IBDatabase.hpp> #include <IBQuery.hpp> #include "FIBDatabase.hpp" #include "FIBDataSet.hpp" #include "pFIBDatabase.hpp" #include "pFIBDataSet.hpp" #include "FIBQuery.hpp" #include "pFIBQuery.hpp" //--------------------------------------------------------------------------- class TREM_DMDocRemontKKT : public TDataModule { __published: // IDE-managed Components TDataSource *DataSourceDoc; TDataSource *DataSourceDocT; TDataSource *DataSourceDocAll; TpFIBDataSet *DocAll; TpFIBDataSet *Doc; TpFIBDataSet *DocT; TpFIBTransaction *IBTr; TpFIBTransaction *IBTrUpdate; TpFIBTransaction *IBTrDvReg; TpFIBDataSet *NumDoc; TpFIBQuery *pFIBQ; TpFIBQuery *QueryCancelDvReg; TpFIBQuery *QueryDvReg; TFIBIntegerField *NumDocMAXNUMBER; TIntegerField *DocTRECNO; TFIBBCDField *DocTKOL_REM_DREMONTKKTT; TFIBBCDField *DocTKF_REM_DREMONTKKTT; TFIBBCDField *DocTPRICE_REM_DREMONTKKTT; TFIBBCDField *DocTSUM_REM_DREMONTKKTT; TFIBBCDField *DocTPRICEMEX_REM_DREMONTKKTT; TFIBBCDField *DocTSUMMEX_REM_DREMONTKKTT; TFIBLargeIntField *DocAllID_REM_GALLDOC; TFIBLargeIntField *DocAllIDBASE_REM_GALLDOC; TFIBLargeIntField *DocAllIDFIRM_REM_GALLDOC; TFIBLargeIntField *DocAllIDSKLAD_REM_GALLDOC; TFIBLargeIntField *DocAllIDKLIENT_REM_GALLDOC; TFIBLargeIntField *DocAllIDUSER_REM_GALLDOC; TFIBDateTimeField *DocAllPOS_REM_GALLDOC; TFIBIntegerField *DocAllNUM_REM_GALLDOC; TFIBSmallIntField *DocAllPR_REM_GALLDOC; TFIBWideStringField *DocAllTDOC_REM_GALLDOC; TFIBLargeIntField *DocAllIDDOCOSN_REM_GALLDOC; TFIBIntegerField *DocAllTYPEEXTDOC_REM_GALLDOC; TFIBLargeIntField *DocAllIDEXTDOC_REM_GALLDOC; TFIBBCDField *DocAllSUM_REM_GALLDOC; TFIBWideStringField *DocAllFNAME_USER; TFIBWideStringField *DocAllNAME_SINFBASE_OBMEN; TFIBWideStringField *DocAllNAMEFIRM; TFIBWideStringField *DocAllNAMESKLAD; TFIBWideStringField *DocAllNAMEKLIENT; TFIBLargeIntField *DocID_REM_DREMONTKKT; TFIBLargeIntField *DocIDBASE_REM_DREMONTKKT; TFIBLargeIntField *DocIDDOC_REM_DREMONTKKT; TFIBLargeIntField *DocIDKKT_REM_DREMONTKKT; TFIBLargeIntField *DocIDTPRICE_REM_DREMONTKKT; TFIBWideStringField *DocPRIM_REM_DREMONTKKT; TFIBWideStringField *DocNAME_REM_SKKT; TFIBLargeIntField *DocTID_REM_DREMONTKKTT; TFIBLargeIntField *DocTIDBASE_REM_DREMONTKKTT; TFIBLargeIntField *DocTIDDOC_REM_DREMONTKKTT; TFIBLargeIntField *DocTIDNOM_REM_DREMONTKKTT; TFIBLargeIntField *DocTIDED_REM_DREMONTKKTT; TFIBWideStringField *DocTNAMENOM; TFIBWideStringField *DocTNAMEED; TFIBLargeIntField *DocAllIDPROJECT_REM_GALLDOC; TFIBLargeIntField *DocAllIDBUSINOP_REM_GALLDOC; TFIBWideStringField *DocAllPREFIKS_NUM_REM_GALLDOC; TFIBWideStringField *DocAllNAME_SPROJECT; TFIBWideStringField *DocAllNAME_SBUSINESS_OPER; void __fastcall DataModuleDestroy(TObject *Sender); void __fastcall DocTNewRecord(TDataSet *DataSet); void __fastcall DocTCalcFields(TDataSet *DataSet); void __fastcall DocNewRecord(TDataSet *DataSet); void __fastcall DocTAfterDelete(TDataSet *DataSet); void __fastcall DocTBeforeDelete(TDataSet *DataSet); void __fastcall DocAllPOS_REM_GALLDOCChange(TField *Sender); void __fastcall DocAllIDBASE_REM_GALLDOCChange(TField *Sender); void __fastcall DocTKOL_REM_DREMONTKKTTChange(TField *Sender); void __fastcall DocTPRICE_REM_DREMONTKKTTChange(TField *Sender); private: // User declarations bool ExecPriv, InsertPriv, EditPriv, DeletePriv; double OldSummaStr; double NewSummaStr; double OldSummaMexStr; double NewSummaMexStr; public: // User declarations __fastcall TREM_DMDocRemontKKT(TComponent* Owner); typedef void (__closure * TFunctionDeleteImplType)(void); TFunctionDeleteImplType FunctionDeleteImpl; //функция удаления реализации интерфейса bool flDeleteImpl; //надо ли удалять реализацию при удалении текущего модуля IDMFibConnection * DM_Connection; IkanCom *InterfaceGlobalCom; IkanUnknown * InterfaceMainObject; IkanUnknown * InterfaceOwnerObject; IkanUnknown * InterfaceImpl; //интерфейс класса реализации GUID ClsIdImpl; //GUID класса реализации //IMainInterface int CodeError; UnicodeString TextError; bool Init(void); int Done(void); //Текущий интерфейс __int64 IdDoc; //идентификатор текущей записи bool Prosmotr; //только просмотр bool NewDoc(void); bool OpenDoc(__int64 id); bool SaveDoc(void); bool DeleteDoc(__int64 id); bool DvRegDoc(void); bool CancelDvRegDoc(void); void TableAppend(void); void TableDelete(void); }; //--------------------------------------------------------------------------- extern PACKAGE TREM_DMDocRemontKKT *REM_DMDocRemontKKT; //--------------------------------------------------------------------------- #endif
[ "sasha@kaserv.ru" ]
sasha@kaserv.ru
da5a40506608df0375396bea66083a21150d72ff
8a9f0a0924706ded24ab4214aa42ab07f201e38b
/GeeksforGeeks/Algorithms/Sorting/sorting.cpp
2d6eaa10e3be7270f34a42581e7cded018f8a6e1
[]
no_license
gitzx/Data-Structure-Algorithm
687162565729b12551cb660aa55a94f1d382014c
d6af7dfdc4d3d139fd939687a45dd36e327c914c
refs/heads/master
2021-06-03T21:27:17.750464
2019-06-27T10:50:48
2019-06-27T10:50:48
14,443,488
0
0
null
null
null
null
UTF-8
C++
false
false
1,254
cpp
#include<stdio.h> void swap(int *xp, int *yp){ int tmp = *xp; *xp = *yp; *yp = tmp; } void bubbleSort(int a[], int n){ for(int i=0; i<n; i++){ bool isswap = false; for(int j=i; j<n; j++){ if(a[j]>a[j+1]){ swap(&a[j], &a[j+1]); isswap = true; } } if(isswap == false){ break; } } } void selectionSort(int a[], int n){ int min_idx; for(int i=0; i<n-1; i++){ min_idx=i; for(int j=i+1; j<n; j++){ if(a[j]<a[min_idx]){ min_idx = j; } } swap(&a[i]), &a[min_idx]; } } void insertionSort(int a[], int n){ int key; for(int i=1; i<n; i++){ key=a[i]; for(int j=i-1; j>=0&&a[j]>key; j--){ a[j+1] = a[j]; } a[j+1] = key; } } void shellSort(int a[], int n){ int key; for(int gap=n/2; gap>0; gap/=2){ for(int i=gap; i<n; i++){ key=a[i]; for(int j=i; j>=0&&a[j-gap]>key; j-=gap){ a[j]=a[j-gap]; } a[j]=key; } } } int partition(int a[], int low, int high){ int key=a[high]; int i=low-1; for(int j=low-1; j<high; j++){ if(a[j]<=key){ i++; swap(&a[i], &a[j]); } } swap(&a[i+1], &a[high]); return i+1; } void quickSort(int a[], int low, int high){ if(low<high){ int p = partition(a, low, high); quickSort(a, low, p-1); quickSort(a, p+1, high); } }
[ "gzzhangxiang@GIH-D-3964.game.ntes" ]
gzzhangxiang@GIH-D-3964.game.ntes
9d5ca6c81ac6db46551b90743d71f32ada3a4ef3
9fb27ac416a720df790542bccd163f1689498259
/src/UniTest/test_Node.cpp
a19863f2a2fe601c746e3114ce28de5d053a91a1
[ "BSD-2-Clause" ]
permissive
LANLhakel/FESTR
be24d02ca35ae82ba53bbdc43b241c8d26fb7d4c
38ef3e7aa6d01ad2f60691cdc8df7fabe5c67cdb
refs/heads/master
2023-08-31T22:09:43.746484
2023-08-20T18:53:09
2023-08-20T18:53:09
37,750,290
2
0
null
null
null
null
UTF-8
C++
false
false
4,940
cpp
/*============================================================================= test_Node.cpp Definitions for unit, integration, and regression tests for class Node. Peter Hakel Los Alamos National Laboratory XCP-5 group Created on 19 November 2014 Last modified on 2 October 2020 Copyright (c) 2015, Triad National Security, LLC. All rights reserved. Use of this source code is governed by the BSD 3-Clause License. See top-level license.txt file for full license text. CODE NAME: FESTR, Version 0.9 (C15068) Classification Review Number: LA-CC-15-045 Export Control Classification Number (ECCN): EAR99 B&R Code: DP1516090 =============================================================================*/ // Note: only use trimmed strings for names #include <test_Node.h> #include <Test.h> void test_Node(int &failed_test_count, int &disabled_test_count) { const std::string GROUP = "Node"; const double EQT = 1.0e-15; //----------------------------------------------------------------------------- { Test t(GROUP, "set_get_i", "fast"); t.check_to_disable_test(disabled_test_count); if (t.is_enabled()) { Node n; size_t expected = 7; n.seti(expected); size_t actual = n.geti(); failed_test_count += t.check_equal(expected, actual); } } //----------------------------------------------------------------------------- { Test t(GROUP, "set_get_r", "fast"); t.check_to_disable_test(disabled_test_count); if (t.is_enabled()) { Node n; Vector3d expected(1.0, -1.0, 0.0); n.setr(expected); Vector3d actual = n.getr(); failed_test_count += t.check_equal_real_obj(expected, actual, EQT); } } //----------------------------------------------------------------------------- { Test t(GROUP, "set_get_v", "fast"); t.check_to_disable_test(disabled_test_count); if (t.is_enabled()) { Node n; Vector3d expected(-1.0, 0.0, 1.0); n.setv(expected); Vector3d actual = n.getv(); failed_test_count += t.check_equal_real_obj(expected, actual, EQT); } } //----------------------------------------------------------------------------- { Test t(GROUP, "abs_diff", "fast"); t.check_to_disable_test(disabled_test_count); if (t.is_enabled()) { Vector3d r(12.0, 4.0, -3.0); Vector3d v(-4.0, 3.0, 12.0); Node x(1, r, v); Node y; double expected = 27.0; double actual = x.abs_diff(y); failed_test_count += t.check_equal_real_num(expected, actual, EQT); } } //----------------------------------------------------------------------------- { Test t(GROUP, "to_string", "fast"); t.check_to_disable_test(disabled_test_count); if (t.is_enabled()) { Vector3d v(7.0e-11, 0.0, -500.0); Node n(1, v, v); std::string expected = " 7.000000e-11 0.000000e+00 -5.000000e+02"; expected+= " 7.000000e-11 0.000000e+00 -5.000000e+02"; std::string actual = n.to_string(); failed_test_count += t.check_equal(expected, actual); } } //----------------------------------------------------------------------------- { Test t(GROUP, "ctor_i0_r0_v0", "fast"); t.check_to_disable_test(disabled_test_count); if (t.is_enabled()) { Vector3d zero; Node expected(0, zero, zero); Node actual; failed_test_count += t.check_equal_real_obj(expected, actual, EQT); } } //----------------------------------------------------------------------------- { Test t(GROUP, "ctor_v0", "fast"); t.check_to_disable_test(disabled_test_count); if (t.is_enabled()) { Vector3d r(12.0, 4.0, -3.0); Vector3d zero; Node expected(0, r, zero); Node actual(0, r); failed_test_count += t.check_equal_real_obj(expected, actual, EQT); } } //----------------------------------------------------------------------------- { Test t(GROUP, "copy_ctor", "fast"); t.check_to_disable_test(disabled_test_count); if (t.is_enabled()) { Vector3d r(12.0, 4.0, -3.0); Vector3d v(-4.0, 3.0, 12.0); Node n(0, r, v); Node expected(0, r, v); Node actual(n); failed_test_count += t.check_equal_real_obj(expected, actual, EQT); } } //----------------------------------------------------------------------------- { Test t(GROUP, "assignment", "fast"); t.check_to_disable_test(disabled_test_count); if (t.is_enabled()) { Vector3d r(12.0, 4.0, -3.0); Vector3d v(-4.0, 3.0, 12.0); Node n(0, r, v); Node expected(0, r, v); Node actual = n; failed_test_count += t.check_equal_real_obj(expected, actual, EQT); } } //----------------------------------------------------------------------------- } // end test_Node.cpp
[ "hakel@lanl.gov" ]
hakel@lanl.gov
ba321656f2f92f6ef03dc78d77aeabee451f35e5
cd34f29cf3106d4869bb819e57fcb3b0b56eb869
/src/netbase.cpp
9038f0da4d7e4d075b1da032cb2395b468bdcc20
[ "MIT" ]
permissive
BitcoinBridgeOffical/Bitcoin-Bridge
026618c6024e3ee3f853d13efdbad4d0a2cd6cea
d800625c9b4b6fe1ddc0f0615a854e43463b82ad
refs/heads/master
2021-05-12T16:21:43.281020
2018-01-10T21:35:40
2018-01-10T21:35:40
117,009,438
1
0
null
null
null
null
UTF-8
C++
false
false
25,472
cpp
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-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. #ifdef HAVE_CONFIG_H #include "config/bitcoinbridge-config.h" #endif #include "netbase.h" #include "hash.h" #include "random.h" #include "sync.h" #include "uint256.h" #include "util.h" #include "utilstrencodings.h" #include <atomic> #ifndef WIN32 #include <fcntl.h> #endif #include <boost/algorithm/string/case_conv.hpp> // for to_lower() #include <boost/algorithm/string/predicate.hpp> // for startswith() and endswith() #if !defined(HAVE_MSG_NOSIGNAL) #define MSG_NOSIGNAL 0 #endif // Settings static proxyType proxyInfo[NET_MAX]; static proxyType nameProxy; static CCriticalSection cs_proxyInfos; int nConnectTimeout = DEFAULT_CONNECT_TIMEOUT; bool fNameLookup = DEFAULT_NAME_LOOKUP; // Need ample time for negotiation for very slow proxies such as Tor (milliseconds) static const int SOCKS5_RECV_TIMEOUT = 20 * 1000; static std::atomic<bool> interruptSocks5Recv(false); enum Network ParseNetwork(std::string net) { boost::to_lower(net); if (net == "ipv4") return NET_IPV4; if (net == "ipv6") return NET_IPV6; if (net == "tor" || net == "onion") return NET_TOR; return NET_UNROUTABLE; } std::string GetNetworkName(enum Network net) { switch (net) { case NET_IPV4: return "ipv4"; case NET_IPV6: return "ipv6"; case NET_TOR: return "onion"; default: return ""; } } bool static LookupIntern(const char* pszName, std::vector<CNetAddr>& vIP, unsigned int nMaxSolutions, bool fAllowLookup) { vIP.clear(); { CNetAddr addr; if (addr.SetSpecial(std::string(pszName))) { vIP.push_back(addr); return true; } } struct addrinfo aiHint; memset(&aiHint, 0, sizeof(struct addrinfo)); aiHint.ai_socktype = SOCK_STREAM; aiHint.ai_protocol = IPPROTO_TCP; aiHint.ai_family = AF_UNSPEC; #ifdef WIN32 aiHint.ai_flags = fAllowLookup ? 0 : AI_NUMERICHOST; #else aiHint.ai_flags = fAllowLookup ? AI_ADDRCONFIG : AI_NUMERICHOST; #endif struct addrinfo* aiRes = nullptr; int nErr = getaddrinfo(pszName, nullptr, &aiHint, &aiRes); if (nErr) return false; struct addrinfo* aiTrav = aiRes; while (aiTrav != nullptr && (nMaxSolutions == 0 || vIP.size() < nMaxSolutions)) { CNetAddr resolved; if (aiTrav->ai_family == AF_INET) { assert(aiTrav->ai_addrlen >= sizeof(sockaddr_in)); resolved = CNetAddr(((struct sockaddr_in*)(aiTrav->ai_addr))->sin_addr); } if (aiTrav->ai_family == AF_INET6) { assert(aiTrav->ai_addrlen >= sizeof(sockaddr_in6)); struct sockaddr_in6* s6 = (struct sockaddr_in6*)aiTrav->ai_addr; resolved = CNetAddr(s6->sin6_addr, s6->sin6_scope_id); } /* Never allow resolving to an internal address. Consider any such result invalid */ if (!resolved.IsInternal()) { vIP.push_back(resolved); } aiTrav = aiTrav->ai_next; } freeaddrinfo(aiRes); return (vIP.size() > 0); } bool LookupHost(const char* pszName, std::vector<CNetAddr>& vIP, unsigned int nMaxSolutions, bool fAllowLookup) { std::string strHost(pszName); if (strHost.empty()) return false; if (boost::algorithm::starts_with(strHost, "[") && boost::algorithm::ends_with(strHost, "]")) { strHost = strHost.substr(1, strHost.size() - 2); } return LookupIntern(strHost.c_str(), vIP, nMaxSolutions, fAllowLookup); } bool LookupHost(const char* pszName, CNetAddr& addr, bool fAllowLookup) { std::vector<CNetAddr> vIP; LookupHost(pszName, vIP, 1, fAllowLookup); if (vIP.empty()) return false; addr = vIP.front(); return true; } bool Lookup(const char* pszName, std::vector<CService>& vAddr, int portDefault, bool fAllowLookup, unsigned int nMaxSolutions) { if (pszName[0] == 0) return false; int port = portDefault; std::string hostname = ""; SplitHostPort(std::string(pszName), port, hostname); std::vector<CNetAddr> vIP; bool fRet = LookupIntern(hostname.c_str(), vIP, nMaxSolutions, fAllowLookup); if (!fRet) return false; vAddr.resize(vIP.size()); for (unsigned int i = 0; i < vIP.size(); i++) vAddr[i] = CService(vIP[i], port); return true; } bool Lookup(const char* pszName, CService& addr, int portDefault, bool fAllowLookup) { std::vector<CService> vService; bool fRet = Lookup(pszName, vService, portDefault, fAllowLookup, 1); if (!fRet) return false; addr = vService[0]; return true; } CService LookupNumeric(const char* pszName, int portDefault) { CService addr; // "1.2:345" will fail to resolve the ip, but will still set the port. // If the ip fails to resolve, re-init the result. if (!Lookup(pszName, addr, portDefault, false)) addr = CService(); return addr; } struct timeval MillisToTimeval(int64_t nTimeout) { struct timeval timeout; timeout.tv_sec = nTimeout / 1000; timeout.tv_usec = (nTimeout % 1000) * 1000; return timeout; } /** SOCKS version */ enum SOCKSVersion : uint8_t { SOCKS4 = 0x04, SOCKS5 = 0x05 }; /** Values defined for METHOD in RFC1928 */ enum SOCKS5Method : uint8_t { NOAUTH = 0x00, //! No authentication required GSSAPI = 0x01, //! GSSAPI USER_PASS = 0x02, //! Username/password NO_ACCEPTABLE = 0xff, //! No acceptable methods }; /** Values defined for CMD in RFC1928 */ enum SOCKS5Command : uint8_t { CONNECT = 0x01, BIND = 0x02, UDP_ASSOCIATE = 0x03 }; /** Values defined for REP in RFC1928 */ enum SOCKS5Reply : uint8_t { SUCCEEDED = 0x00, //! Succeeded GENFAILURE = 0x01, //! General failure NOTALLOWED = 0x02, //! Connection not allowed by ruleset NETUNREACHABLE = 0x03, //! Network unreachable HOSTUNREACHABLE = 0x04, //! Network unreachable CONNREFUSED = 0x05, //! Connection refused TTLEXPIRED = 0x06, //! TTL expired CMDUNSUPPORTED = 0x07, //! Command not supported ATYPEUNSUPPORTED = 0x08, //! Address type not supported }; /** Values defined for ATYPE in RFC1928 */ enum SOCKS5Atyp : uint8_t { IPV4 = 0x01, DOMAINNAME = 0x03, IPV6 = 0x04, }; /** Status codes that can be returned by InterruptibleRecv */ enum class IntrRecvError { OK, Timeout, Disconnected, NetworkError, Interrupted }; /** * Read bytes from socket. This will either read the full number of bytes requested * or return False on error or timeout. * This function can be interrupted by calling InterruptSocks5() * * @param data Buffer to receive into * @param len Length of data to receive * @param timeout Timeout in milliseconds for receive operation * * @note This function requires that hSocket is in non-blocking mode. */ static IntrRecvError InterruptibleRecv(uint8_t* data, size_t len, int timeout, const SOCKET& hSocket) { int64_t curTime = GetTimeMillis(); int64_t endTime = curTime + timeout; // Maximum time to wait in one select call. It will take up until this time (in millis) // to break off in case of an interruption. const int64_t maxWait = 1000; while (len > 0 && curTime < endTime) { ssize_t ret = recv(hSocket, (char*)data, len, 0); // Optimistically try the recv first if (ret > 0) { len -= ret; data += ret; } else if (ret == 0) { // Unexpected disconnection return IntrRecvError::Disconnected; } else { // Other error or blocking int nErr = WSAGetLastError(); if (nErr == WSAEINPROGRESS || nErr == WSAEWOULDBLOCK || nErr == WSAEINVAL) { if (!IsSelectableSocket(hSocket)) { return IntrRecvError::NetworkError; } struct timeval tval = MillisToTimeval(std::min(endTime - curTime, maxWait)); fd_set fdset; FD_ZERO(&fdset); FD_SET(hSocket, &fdset); int nRet = select(hSocket + 1, &fdset, nullptr, nullptr, &tval); if (nRet == SOCKET_ERROR) { return IntrRecvError::NetworkError; } } else { return IntrRecvError::NetworkError; } } if (interruptSocks5Recv) return IntrRecvError::Interrupted; curTime = GetTimeMillis(); } return len == 0 ? IntrRecvError::OK : IntrRecvError::Timeout; } /** Credentials for proxy authentication */ struct ProxyCredentials { std::string username; std::string password; }; /** Convert SOCKS5 reply to a an error message */ std::string Socks5ErrorString(uint8_t err) { switch (err) { case SOCKS5Reply::GENFAILURE: return "general failure"; case SOCKS5Reply::NOTALLOWED: return "connection not allowed"; case SOCKS5Reply::NETUNREACHABLE: return "network unreachable"; case SOCKS5Reply::HOSTUNREACHABLE: return "host unreachable"; case SOCKS5Reply::CONNREFUSED: return "connection refused"; case SOCKS5Reply::TTLEXPIRED: return "TTL expired"; case SOCKS5Reply::CMDUNSUPPORTED: return "protocol error"; case SOCKS5Reply::ATYPEUNSUPPORTED: return "address type not supported"; default: return "unknown"; } } /** Connect using SOCKS5 (as described in RFC1928) */ static bool Socks5(const std::string& strDest, int port, const ProxyCredentials* auth, SOCKET& hSocket) { IntrRecvError recvr; LogPrint(BCLog::NET, "SOCKS5 connecting %s\n", strDest); if (strDest.size() > 255) { CloseSocket(hSocket); return error("Hostname too long"); } // Accepted authentication methods std::vector<uint8_t> vSocks5Init; vSocks5Init.push_back(SOCKSVersion::SOCKS5); if (auth) { vSocks5Init.push_back(0x02); // Number of methods vSocks5Init.push_back(SOCKS5Method::NOAUTH); vSocks5Init.push_back(SOCKS5Method::USER_PASS); } else { vSocks5Init.push_back(0x01); // Number of methods vSocks5Init.push_back(SOCKS5Method::NOAUTH); } ssize_t ret = send(hSocket, (const char*)vSocks5Init.data(), vSocks5Init.size(), MSG_NOSIGNAL); if (ret != (ssize_t)vSocks5Init.size()) { CloseSocket(hSocket); return error("Error sending to proxy"); } uint8_t pchRet1[2]; if ((recvr = InterruptibleRecv(pchRet1, 2, SOCKS5_RECV_TIMEOUT, hSocket)) != IntrRecvError::OK) { CloseSocket(hSocket); LogPrintf("Socks5() connect to %s:%d failed: InterruptibleRecv() timeout or other failure\n", strDest, port); return false; } if (pchRet1[0] != SOCKSVersion::SOCKS5) { CloseSocket(hSocket); return error("Proxy failed to initialize"); } if (pchRet1[1] == SOCKS5Method::USER_PASS && auth) { // Perform username/password authentication (as described in RFC1929) std::vector<uint8_t> vAuth; vAuth.push_back(0x01); // Current (and only) version of user/pass subnegotiation if (auth->username.size() > 255 || auth->password.size() > 255) return error("Proxy username or password too long"); vAuth.push_back(auth->username.size()); vAuth.insert(vAuth.end(), auth->username.begin(), auth->username.end()); vAuth.push_back(auth->password.size()); vAuth.insert(vAuth.end(), auth->password.begin(), auth->password.end()); ret = send(hSocket, (const char*)vAuth.data(), vAuth.size(), MSG_NOSIGNAL); if (ret != (ssize_t)vAuth.size()) { CloseSocket(hSocket); return error("Error sending authentication to proxy"); } LogPrint(BCLog::PROXY, "SOCKS5 sending proxy authentication %s:%s\n", auth->username, auth->password); uint8_t pchRetA[2]; if ((recvr = InterruptibleRecv(pchRetA, 2, SOCKS5_RECV_TIMEOUT, hSocket)) != IntrRecvError::OK) { CloseSocket(hSocket); return error("Error reading proxy authentication response"); } if (pchRetA[0] != 0x01 || pchRetA[1] != 0x00) { CloseSocket(hSocket); return error("Proxy authentication unsuccessful"); } } else if (pchRet1[1] == SOCKS5Method::NOAUTH) { // Perform no authentication } else { CloseSocket(hSocket); return error("Proxy requested wrong authentication method %02x", pchRet1[1]); } std::vector<uint8_t> vSocks5; vSocks5.push_back(SOCKSVersion::SOCKS5); // VER protocol version vSocks5.push_back(SOCKS5Command::CONNECT); // CMD CONNECT vSocks5.push_back(0x00); // RSV Reserved must be 0 vSocks5.push_back(SOCKS5Atyp::DOMAINNAME); // ATYP DOMAINNAME vSocks5.push_back(strDest.size()); // Length<=255 is checked at beginning of function vSocks5.insert(vSocks5.end(), strDest.begin(), strDest.end()); vSocks5.push_back((port >> 8) & 0xFF); vSocks5.push_back((port >> 0) & 0xFF); ret = send(hSocket, (const char*)vSocks5.data(), vSocks5.size(), MSG_NOSIGNAL); if (ret != (ssize_t)vSocks5.size()) { CloseSocket(hSocket); return error("Error sending to proxy"); } uint8_t pchRet2[4]; if ((recvr = InterruptibleRecv(pchRet2, 4, SOCKS5_RECV_TIMEOUT, hSocket)) != IntrRecvError::OK) { CloseSocket(hSocket); if (recvr == IntrRecvError::Timeout) { /* If a timeout happens here, this effectively means we timed out while connecting * to the remote node. This is very common for Tor, so do not print an * error message. */ return false; } else { return error("Error while reading proxy response"); } } if (pchRet2[0] != SOCKSVersion::SOCKS5) { CloseSocket(hSocket); return error("Proxy failed to accept request"); } if (pchRet2[1] != SOCKS5Reply::SUCCEEDED) { // Failures to connect to a peer that are not proxy errors CloseSocket(hSocket); LogPrintf("Socks5() connect to %s:%d failed: %s\n", strDest, port, Socks5ErrorString(pchRet2[1])); return false; } if (pchRet2[2] != 0x00) { // Reserved field must be 0 CloseSocket(hSocket); return error("Error: malformed proxy response"); } uint8_t pchRet3[256]; switch (pchRet2[3]) { case SOCKS5Atyp::IPV4: recvr = InterruptibleRecv(pchRet3, 4, SOCKS5_RECV_TIMEOUT, hSocket); break; case SOCKS5Atyp::IPV6: recvr = InterruptibleRecv(pchRet3, 16, SOCKS5_RECV_TIMEOUT, hSocket); break; case SOCKS5Atyp::DOMAINNAME: { recvr = InterruptibleRecv(pchRet3, 1, SOCKS5_RECV_TIMEOUT, hSocket); if (recvr != IntrRecvError::OK) { CloseSocket(hSocket); return error("Error reading from proxy"); } int nRecv = pchRet3[0]; recvr = InterruptibleRecv(pchRet3, nRecv, SOCKS5_RECV_TIMEOUT, hSocket); break; } default: CloseSocket(hSocket); return error("Error: malformed proxy response"); } if (recvr != IntrRecvError::OK) { CloseSocket(hSocket); return error("Error reading from proxy"); } if ((recvr = InterruptibleRecv(pchRet3, 2, SOCKS5_RECV_TIMEOUT, hSocket)) != IntrRecvError::OK) { CloseSocket(hSocket); return error("Error reading from proxy"); } LogPrint(BCLog::NET, "SOCKS5 connected %s\n", strDest); return true; } bool static ConnectSocketDirectly(const CService& addrConnect, SOCKET& hSocketRet, int nTimeout) { hSocketRet = INVALID_SOCKET; struct sockaddr_storage sockaddr; socklen_t len = sizeof(sockaddr); if (!addrConnect.GetSockAddr((struct sockaddr*)&sockaddr, &len)) { LogPrintf("Cannot connect to %s: unsupported network\n", addrConnect.ToString()); return false; } SOCKET hSocket = socket(((struct sockaddr*)&sockaddr)->sa_family, SOCK_STREAM, IPPROTO_TCP); if (hSocket == INVALID_SOCKET) return false; #ifdef SO_NOSIGPIPE int set = 1; // Different way of disabling SIGPIPE on BSD setsockopt(hSocket, SOL_SOCKET, SO_NOSIGPIPE, (void*)&set, sizeof(int)); #endif //Disable Nagle's algorithm SetSocketNoDelay(hSocket); // Set to non-blocking if (!SetSocketNonBlocking(hSocket, true)) { CloseSocket(hSocket); return error("ConnectSocketDirectly: Setting socket to non-blocking failed, error %s\n", NetworkErrorString(WSAGetLastError())); } if (connect(hSocket, (struct sockaddr*)&sockaddr, len) == SOCKET_ERROR) { int nErr = WSAGetLastError(); // WSAEINVAL is here because some legacy version of winsock uses it if (nErr == WSAEINPROGRESS || nErr == WSAEWOULDBLOCK || nErr == WSAEINVAL) { struct timeval timeout = MillisToTimeval(nTimeout); fd_set fdset; FD_ZERO(&fdset); FD_SET(hSocket, &fdset); int nRet = select(hSocket + 1, nullptr, &fdset, nullptr, &timeout); if (nRet == 0) { LogPrint(BCLog::NET, "connection to %s timeout\n", addrConnect.ToString()); CloseSocket(hSocket); return false; } if (nRet == SOCKET_ERROR) { LogPrintf("select() for %s failed: %s\n", addrConnect.ToString(), NetworkErrorString(WSAGetLastError())); CloseSocket(hSocket); return false; } socklen_t nRetSize = sizeof(nRet); #ifdef WIN32 if (getsockopt(hSocket, SOL_SOCKET, SO_ERROR, (char*)(&nRet), &nRetSize) == SOCKET_ERROR) #else if (getsockopt(hSocket, SOL_SOCKET, SO_ERROR, &nRet, &nRetSize) == SOCKET_ERROR) #endif { LogPrintf("getsockopt() for %s failed: %s\n", addrConnect.ToString(), NetworkErrorString(WSAGetLastError())); CloseSocket(hSocket); return false; } if (nRet != 0) { LogPrintf("connect() to %s failed after select(): %s\n", addrConnect.ToString(), NetworkErrorString(nRet)); CloseSocket(hSocket); return false; } } #ifdef WIN32 else if (WSAGetLastError() != WSAEISCONN) #else else #endif { LogPrintf("connect() to %s failed: %s\n", addrConnect.ToString(), NetworkErrorString(WSAGetLastError())); CloseSocket(hSocket); return false; } } hSocketRet = hSocket; return true; } bool SetProxy(enum Network net, const proxyType& addrProxy) { assert(net >= 0 && net < NET_MAX); if (!addrProxy.IsValid()) return false; LOCK(cs_proxyInfos); proxyInfo[net] = addrProxy; return true; } bool GetProxy(enum Network net, proxyType& proxyInfoOut) { assert(net >= 0 && net < NET_MAX); LOCK(cs_proxyInfos); if (!proxyInfo[net].IsValid()) return false; proxyInfoOut = proxyInfo[net]; return true; } bool SetNameProxy(const proxyType& addrProxy) { if (!addrProxy.IsValid()) return false; LOCK(cs_proxyInfos); nameProxy = addrProxy; return true; } bool GetNameProxy(proxyType& nameProxyOut) { LOCK(cs_proxyInfos); if (!nameProxy.IsValid()) return false; nameProxyOut = nameProxy; return true; } bool HaveNameProxy() { LOCK(cs_proxyInfos); return nameProxy.IsValid(); } bool IsProxy(const CNetAddr& addr) { LOCK(cs_proxyInfos); for (int i = 0; i < NET_MAX; i++) { if (addr == (CNetAddr)proxyInfo[i].proxy) return true; } return false; } static bool ConnectThroughProxy(const proxyType& proxy, const std::string& strDest, int port, SOCKET& hSocketRet, int nTimeout, bool* outProxyConnectionFailed) { SOCKET hSocket = INVALID_SOCKET; // first connect to proxy server if (!ConnectSocketDirectly(proxy.proxy, hSocket, nTimeout)) { if (outProxyConnectionFailed) *outProxyConnectionFailed = true; return false; } // do socks negotiation if (proxy.randomize_credentials) { ProxyCredentials random_auth; static std::atomic_int counter(0); random_auth.username = random_auth.password = strprintf("%i", counter++); if (!Socks5(strDest, (unsigned short)port, &random_auth, hSocket)) return false; } else { if (!Socks5(strDest, (unsigned short)port, 0, hSocket)) return false; } hSocketRet = hSocket; return true; } bool ConnectSocket(const CService& addrDest, SOCKET& hSocketRet, int nTimeout, bool* outProxyConnectionFailed) { proxyType proxy; if (outProxyConnectionFailed) *outProxyConnectionFailed = false; if (GetProxy(addrDest.GetNetwork(), proxy)) return ConnectThroughProxy(proxy, addrDest.ToStringIP(), addrDest.GetPort(), hSocketRet, nTimeout, outProxyConnectionFailed); else // no proxy needed (none set for target network) return ConnectSocketDirectly(addrDest, hSocketRet, nTimeout); } bool ConnectSocketByName(CService& addr, SOCKET& hSocketRet, const char* pszDest, int portDefault, int nTimeout, bool* outProxyConnectionFailed) { std::string strDest; int port = portDefault; if (outProxyConnectionFailed) *outProxyConnectionFailed = false; SplitHostPort(std::string(pszDest), port, strDest); proxyType proxy; GetNameProxy(proxy); std::vector<CService> addrResolved; if (Lookup(strDest.c_str(), addrResolved, port, fNameLookup && !HaveNameProxy(), 256)) { if (addrResolved.size() > 0) { addr = addrResolved[GetRand(addrResolved.size())]; return ConnectSocket(addr, hSocketRet, nTimeout); } } addr = CService(); if (!HaveNameProxy()) return false; return ConnectThroughProxy(proxy, strDest, port, hSocketRet, nTimeout, outProxyConnectionFailed); } bool LookupSubNet(const char* pszName, CSubNet& ret) { std::string strSubnet(pszName); size_t slash = strSubnet.find_last_of('/'); std::vector<CNetAddr> vIP; std::string strAddress = strSubnet.substr(0, slash); if (LookupHost(strAddress.c_str(), vIP, 1, false)) { CNetAddr network = vIP[0]; if (slash != strSubnet.npos) { std::string strNetmask = strSubnet.substr(slash + 1); int32_t n; // IPv4 addresses start at offset 12, and first 12 bytes must match, so just offset n if (ParseInt32(strNetmask, &n)) { // If valid number, assume /24 syntax ret = CSubNet(network, n); return ret.IsValid(); } else // If not a valid number, try full netmask syntax { // Never allow lookup for netmask if (LookupHost(strNetmask.c_str(), vIP, 1, false)) { ret = CSubNet(network, vIP[0]); return ret.IsValid(); } } } else { ret = CSubNet(network); return ret.IsValid(); } } return false; } #ifdef WIN32 std::string NetworkErrorString(int err) { char buf[256]; buf[0] = 0; if (FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_MAX_WIDTH_MASK, nullptr, err, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), buf, sizeof(buf), nullptr)) { return strprintf("%s (%d)", buf, err); } else { return strprintf("Unknown error (%d)", err); } } #else std::string NetworkErrorString(int err) { char buf[256]; buf[0] = 0; /* Too bad there are two incompatible implementations of the * thread-safe strerror. */ const char* s; #ifdef STRERROR_R_CHAR_P /* GNU variant can return a pointer outside the passed buffer */ s = strerror_r(err, buf, sizeof(buf)); #else /* POSIX variant always returns message in buffer */ s = buf; if (strerror_r(err, buf, sizeof(buf))) buf[0] = 0; #endif return strprintf("%s (%d)", s, err); } #endif bool CloseSocket(SOCKET& hSocket) { if (hSocket == INVALID_SOCKET) return false; #ifdef WIN32 int ret = closesocket(hSocket); #else int ret = close(hSocket); #endif hSocket = INVALID_SOCKET; return ret != SOCKET_ERROR; } bool SetSocketNonBlocking(const SOCKET& hSocket, bool fNonBlocking) { if (fNonBlocking) { #ifdef WIN32 u_long nOne = 1; if (ioctlsocket(hSocket, FIONBIO, &nOne) == SOCKET_ERROR) { #else int fFlags = fcntl(hSocket, F_GETFL, 0); if (fcntl(hSocket, F_SETFL, fFlags | O_NONBLOCK) == SOCKET_ERROR) { #endif return false; } } else { #ifdef WIN32 u_long nZero = 0; if (ioctlsocket(hSocket, FIONBIO, &nZero) == SOCKET_ERROR) { #else int fFlags = fcntl(hSocket, F_GETFL, 0); if (fcntl(hSocket, F_SETFL, fFlags & ~O_NONBLOCK) == SOCKET_ERROR) { #endif return false; } } return true; } bool SetSocketNoDelay(const SOCKET& hSocket) { int set = 1; int rc = setsockopt(hSocket, IPPROTO_TCP, TCP_NODELAY, (const char*)&set, sizeof(int)); return rc == 0; } void InterruptSocks5(bool interrupt) { interruptSocks5Recv = interrupt; }
[ "info@thebitcoinbridge.com" ]
info@thebitcoinbridge.com
55f050b6d0d8e587e9cd9bb559c257fd6821c807
6b8f6c1fd28f90c67588d203de9a27fe5962068b
/RobotProgram/MoveLoop.h
f9398e7148e6fd37c511e19ff43555168bfe9742
[]
no_license
Gouki-0209/EMTRobotProgram
ee4e853934b94a186f7e7adb53307ec6f1ec0574
57e12b1fceca67c3efb85f2dbcd294f2a91c549d
refs/heads/master
2023-02-17T23:33:24.476224
2021-01-12T07:13:05
2021-01-12T07:13:05
284,885,579
0
0
null
null
null
null
UTF-8
C++
false
false
532
h
#ifndef __MOVELOOP__ #define __MOVELOOP__ #include "ShareParts.h" typedef struct { int theta; int radius; } IRInfo_t; int EEPROM_load(); template <class T>void background(T SerialPrintValue); void SerialBTPrint(int value); void SerialBTPrint(byte value); //int MotorSpeedSet(); //void LineThresholdSet(); void LineSerialReceive(byte *LineData); bool IRSerialReceive(IRInfo_t *rslt); void MotorSerialWrite(int GyroAngle, int IRAngle, int IRDistance, byte LineByte, int Speed); int MoveLoop(int Angle, int Distance); #endif
[ "55020456+Gouki-0209@users.noreply.github.com" ]
55020456+Gouki-0209@users.noreply.github.com
f8d555fb515ed646203af0cc13c0091547dad8d4
20dd9e7448370249a0e9a3e91886432b9ff96d76
/src/TGigOscillator.h
847605fc700e41e32f07f8b645b9468bcc9e98d7
[ "MIT" ]
permissive
JonasNorling/jacksynth
cedcf8f8a1c13fc27b2fd7332c79c981789c3dec
527f58067bf7a660506c5a9ebf11770b148224b4
refs/heads/master
2021-01-01T06:05:06.972887
2019-08-03T11:15:25
2019-08-03T11:15:25
15,508,874
10
0
null
null
null
null
UTF-8
C++
false
false
733
h
/* -*- mode: c++ -*- */ #pragma once #include <memory> #include "TBaseOscillator.h" #include "TGigInstrument.h" class TGigOscillator: public TBaseOscillator { UNCOPYABLE(TGigOscillator) ; public: TGigOscillator(const TNoteData& noteData) : TBaseOscillator(noteData), Instrument(NULL), Region(NULL), Sample(NULL), UnityHz(0), StreamId(-1), Stream(NULL) { } ~TGigOscillator(); void SetInstrument(TGigInstrument& instrument); void Process(TSampleBuffer& in, TSampleBuffer& out, TSampleBuffer& syncin, TSampleBuffer& syncout); private: TGigInstrument* Instrument; gig::Region* Region; gig::Sample* Sample; float UnityHz; int StreamId; TGigStream* Stream; };
[ "jonas.norling@gmail.com" ]
jonas.norling@gmail.com
61de1aca43537bd82503ffb272449b6eecb7af21
8f13b9b6c002773cb3d1a770b6cc28c01321c4b3
/src/chatbot.h
d3d892fe7da8201f0d37b792e96dbb3e3f1fb3b8
[]
no_license
thewickk/udacity-cpp-memory-management-chatbot
b01dab741e236fe7d5878d663f1046ec813b0101
e42e750b95644f10a79829b30f29fa872d28a862
refs/heads/master
2020-12-08T22:10:51.416442
2020-01-10T18:43:43
2020-01-10T18:43:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,499
h
#ifndef CHATBOT_H_ #define CHATBOT_H_ #include <wx/bitmap.h> #include <string> class GraphNode; // forward declaration class ChatLogic; // forward declaration class ChatBot { private: // data handles (owned) wxBitmap *_image; // avatar image // data handles (not owned) GraphNode *_currentNode; GraphNode *_rootNode; ChatLogic *_chatLogic; // proprietary functions int ComputeLevenshteinDistance(std::string s1, std::string s2); public: // constructors / destructors ChatBot(); // constructor WITHOUT memory allocation ChatBot(std::string filename); // constructor WITH memory allocation // Rule of Five #1 - Destructor: ~ChatBot(); //// STUDENT CODE //// // Rule of Five #2 - Copy Constructor: ChatBot(const ChatBot &source); // Rule of Five #3 - Copy Assignment Operator: ChatBot &operator=(const ChatBot &source); // Rule of Five #4 - Move Constructor: ChatBot(ChatBot &&source); // Rule of Five #5 - Move Assignment Operator: ChatBot &operator=(ChatBot &&source); //// //// EOF STUDENT CODE // getters / setters void SetCurrentNode(GraphNode *node); void SetRootNode(GraphNode *rootNode) { _rootNode = rootNode; } void SetChatLogicHandle(ChatLogic *chatLogic) { _chatLogic = chatLogic; } wxBitmap *GetImageHandle() { return _image; } // communication void ReceiveMessageFromUser(std::string message); }; #endif /* CHATBOT_H_ */
[ "chadlewis53@gmail.com" ]
chadlewis53@gmail.com
1f6379b89ac905abc2b3b5909dd8e89a4dee4fd8
4ca019d30f376af9cb4e97c4f80792c18772db1e
/PSME/agent-intel/compute/src/command/intel/set_component_attributes.cpp
9f798f698c9d1c0ee68f3b0f918c5b6fda1f8d32
[ "BSD-3-Clause", "MIT", "LicenseRef-scancode-other-permissive", "Apache-2.0", "LicenseRef-scancode-public-domain" ]
permissive
shingchuang/intelRSD
0f56a6bff3b71ba1ec2edbddb781b9eaaac8d1d7
a2939201dd4487acec88ca47657702378577c5cf
refs/heads/master
2021-01-23T01:50:55.150654
2017-03-23T10:35:15
2017-03-23T10:35:15
85,937,247
0
0
null
2017-03-23T10:31:41
2017-03-23T10:31:41
null
UTF-8
C++
false
false
14,292
cpp
/*! * @copyright * Copyright (c) 2015-2016 Intel Corporation * * @copyright * 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 * * @copyright * http://www.apache.org/licenses/LICENSE-2.0 * * @copyright * 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. * * @brief Set Component Attributes JSONRPC command implementation. * */ #include "agent-framework/command/compute/set_component_attributes.hpp" #include "agent-framework/module-ref/utils/utils.hpp" #include "agent-framework/module-ref/constants/compute.hpp" #include "agent-framework/module-ref/constants/common.hpp" #include "agent-framework/module-ref/compute_manager.hpp" #include "ipmi/manager/ipmitool/management_controller.hpp" #include "ipmi/command/generic/chassis_control_command.hpp" #include "ipmi/command/generic/force_pxe_boot_once.hpp" #include "ipmi/command/generic/force_pxe_boot_continuous.hpp" #include "ipmi/command/generic/force_hdd_boot_once.hpp" #include "ipmi/command/generic/force_hdd_boot_continuous.hpp" using namespace agent_framework::command; using namespace agent_framework::model; using namespace ipmi::manager::ipmitool; using namespace ipmi::command::generic; namespace agent { /*! SetComponentAttributes implementation */ class SetComponentAttributes : public compute::SetComponentAttributes { public: SetComponentAttributes() {} using ComputeComponents = agent_framework::module::ComputeManager; using compute::SetComponentAttributes::execute; void execute(const Request& request, Response&) { log_debug(GET_LOGGER("agent"), "Executing SetComponentAttributes."); const auto& system_uuid = request.get_component(); get_command_attributes(request); set_boot_options(system_uuid, m_boot_override, m_boot_target); set_power_state(system_uuid, m_power_state); } ~SetComponentAttributes(); private: using SystemReference = agent_framework::generic::ObjReference <System, std::recursive_mutex>; enums::BootOverride m_boot_override = enums::BootOverride::Once; enums::BootOverrideTarget m_boot_target = enums::BootOverrideTarget::None; enums::ResetType m_power_state = enums::ResetType::None; void get_command_attributes(const Request& request) { const auto& attributes = request.get_attributes(); const auto& attributes_names = attributes.get_names(); for (const auto& attribute_name : attributes_names) { const auto& value = attributes.get_value(attribute_name).asString(); log_debug(GET_LOGGER("agent"), "Attribute name:" << attribute_name); log_debug(GET_LOGGER("agent"), "Attribute value:" << value); if (literals::System::BOOT_OVERRIDE == attribute_name) { m_boot_override = enums::BootOverride::from_string(value); } else if (literals::System::BOOT_OVERRIDE_TARGET == attribute_name) { m_boot_target = enums::BootOverrideTarget::from_string(value); } else if (literals::System::POWER_STATE == attribute_name) { m_power_state = enums::ResetType::from_string(value); } else if (literals::System::OEM == attribute_name) { log_warning(GET_LOGGER("rpc"), "Unsupported attribute: oem."); } else { log_error(GET_LOGGER("rpc"), "Unrecognized attribute: " << attribute_name); } } } void set_boot_options(const string& system_uuid, enums::BootOverride boot_override, enums::BootOverrideTarget boot_target) { log_debug(GET_LOGGER("agent"), "Set Boot Options for System: " << system_uuid); log_debug(GET_LOGGER("agent"), "BootOverride: " << boot_override); log_debug(GET_LOGGER("agent"), "BootOverrideTarget: " << boot_target); ManagementController mc{}; set_connection_data(mc, system_uuid); if (enums::BootOverrideTarget::Pxe == boot_target) { if (enums::BootOverride::Once == boot_override) { log_debug(GET_LOGGER("agent"), "Sending IPMI Force Pxe Once Boot."); send_force_pxe_boot_once(mc); } else if (enums::BootOverride::Continuous == boot_override) { log_debug(GET_LOGGER("agent"), "Sending IPMI Force Pxe Continous Boot."); send_force_pxe_boot_continous(mc); } } else if (enums::BootOverrideTarget::Hdd == boot_target) { if (enums::BootOverride::Once == boot_override) { log_debug(GET_LOGGER("agent"), "Sending IPMI Force Hdd Once Boot."); send_force_hdd_boot_once(mc); } else if (enums::BootOverride::Continuous == boot_override) { log_debug(GET_LOGGER("agent"), "Sending IPMI Force Hdd Continous Boot."); send_force_hdd_boot_continous(mc); } } else if (enums::BootOverrideTarget::None == boot_target) { log_debug(GET_LOGGER("agent"), "Sending IPMI Boot None."); // TODO: implement setting None for boot options via IPMI. } else { log_error(GET_LOGGER("agent"), "Not supported option: " << boot_target.to_string()); } auto system = get_system_reference(system_uuid); system->set_boot_override(boot_override); system->set_boot_override_target(boot_target); } void set_connection_data(ManagementController& mc, const string& system_uuid) { auto manager = find_parent_manager(system_uuid); auto connection_data = manager.get_connection_data(); mc.set_ip(connection_data.get_ip_address()); mc.set_port(connection_data.get_port()); mc.set_username(connection_data.get_username()); mc.set_password(connection_data.get_password()); } Manager find_parent_manager(const string& system_uuid) { auto& sm = ComputeComponents::get_instance()->get_system_manager(); auto system = sm.get_entry(system_uuid); auto& mm = ComputeComponents::get_instance()->get_module_manager(); auto managers = mm.get_keys("", [&system](const Manager& manager) { return manager.get_uuid() == system.get_parent_uuid(); }); if (managers.empty()) { log_error(GET_LOGGER("agent"), "Manger for System: " << system_uuid << " not found!"); throw runtime_error("System without manager!"); } return mm.get_entry(managers.front()); } void send_force_pxe_boot_once(ManagementController& mc) { request::ForcePxeBootOnce request{}; response::ForcePxeBootOnce response{}; mc.send(request, response); if (response.get_completion_code()) { log_error(GET_LOGGER("agent"), "Error Sending Force Pxe Once Boot CC:" << to_string(unsigned(response.get_completion_code()))); } } void send_force_pxe_boot_continous(ManagementController& mc) { request::ForcePxeBootContinuous request{}; response::ForcePxeBootContinuous response{}; mc.send(request, response); if (response.get_completion_code()) { log_error(GET_LOGGER("agent"), "Error Sending Force Pxe Continous Boot CC:" << to_string(unsigned(response.get_completion_code()))); } } void send_force_hdd_boot_once(ManagementController& mc) { request::ForceHddBootOnce request{}; response::ForceHddBootOnce response{}; mc.send(request, response); if (response.get_completion_code()) { log_error(GET_LOGGER("agent"), "Error Sending Force Hdd Once Boot CC:" << to_string(unsigned(response.get_completion_code()))); } } void send_force_hdd_boot_continous(ManagementController& mc) { request::ForceHddBootContinuous request{}; response::ForceHddBootContinuous response{}; mc.send(request, response); if (response.get_completion_code()) { log_error(GET_LOGGER("agent"), "Error Sending Force Hdd Continous Boot CC:" << to_string(unsigned(response.get_completion_code()))); } } SystemReference get_system_reference(const string& system_uuid) { auto& sm = ComputeComponents::get_instance()->get_system_manager(); return sm.get_entry_reference(system_uuid); } void set_power_state(const string& system_uuid, enums::ResetType power_state) { auto system = get_system(system_uuid); ManagementController mc{}; set_connection_data(mc, system_uuid); switch (power_state) { case enums::ResetType::On: log_debug(GET_LOGGER("agent"), "Sending Power State On."); send_power_on(mc); system.set_power_state(enums::PowerState::On); break; case enums::ResetType::ForceOff: log_debug(GET_LOGGER("agent"), "Sending Power State Off."); send_power_off(mc); system.set_power_state(enums::PowerState::Off); break; case enums::ResetType::GracefulRestart: log_debug(GET_LOGGER("agent"), "Sending GracefulRestart."); send_reset(mc); break; case enums::ResetType::ForceRestart: log_debug(GET_LOGGER("agent"), "Sending ForceRestart."); send_power_cycle(mc); break; case enums::ResetType::Nmi: log_debug(GET_LOGGER("agent"), "Nmi not supported."); break; case enums::ResetType::ForceOn: log_debug(GET_LOGGER("agent"), "ForceOn not supported."); break; case enums::ResetType::PushPowerButton: log_debug(GET_LOGGER("agent"), "PushPowerButton not supported."); break; case enums::ResetType::GracefulShutdown: log_debug(GET_LOGGER("agent"), "Sending SoftShutdown."); send_soft_power_off(mc); system.set_power_state(enums::PowerState::Off); break; case enums::ResetType::None: log_debug(GET_LOGGER("agent"), "Sending Power State None."); break; default: // do nothing; log_error(GET_LOGGER("agent"), "Unknow Reset Type."); break; } } System get_system(const string& system_uuid) { auto& sm = ComputeComponents::get_instance()->get_system_manager(); return sm.get_entry(system_uuid); } void send_power_on(ManagementController& mc) { request::ChassisControlCommand request{}; response::ChassisControlCommand response{}; request.set_power_state(request::ChassisControlCommand:: PowerState::POWER_UP); mc.send(request, response); if (response.get_completion_code()) { log_error(GET_LOGGER("agent"), "Error Sending Power On CC:" << to_string(unsigned(response.get_completion_code()))); } } void send_power_off(ManagementController& mc) { request::ChassisControlCommand request{}; response::ChassisControlCommand response{}; request.set_power_state(request::ChassisControlCommand:: PowerState::POWER_DOWN); mc.send(request, response); if (response.get_completion_code()) { log_error(GET_LOGGER("agent"), "Error Sending Power Off CC:" << to_string(unsigned(response.get_completion_code()))); } } void send_soft_power_off(ManagementController& mc) { request::ChassisControlCommand request{}; response::ChassisControlCommand response{}; request.set_power_state(request::ChassisControlCommand:: PowerState::ACPI_SOFT_SHUTDOWN); mc.send(request, response); if (response.get_completion_code()) { log_error(GET_LOGGER("agent"), "Error Sending Soft Power Off CC:" << to_string(unsigned(response.get_completion_code()))); } } void send_power_cycle(ManagementController& mc) { request::ChassisControlCommand request{}; response::ChassisControlCommand response{}; request.set_power_state(request::ChassisControlCommand:: PowerState::POWER_CYCLE); mc.send(request, response); if (response.get_completion_code()) { log_error(GET_LOGGER("agent"), "Error Sending Power Cycle CC:" << to_string(unsigned(response.get_completion_code()))); } } void send_reset(ManagementController& mc) { request::ChassisControlCommand request{}; response::ChassisControlCommand response{}; request.set_power_state(request::ChassisControlCommand:: PowerState::HARD_RESET); mc.send(request, response); if (response.get_completion_code()) { log_error(GET_LOGGER("agent"), "Error Sending Power Cycle CC:" << to_string(unsigned(response.get_completion_code()))); } } }; SetComponentAttributes::~SetComponentAttributes() {} } static Command::Register<agent::SetComponentAttributes> g("Intel");
[ "maciej.a.romanowski@intel.com" ]
maciej.a.romanowski@intel.com
98a7fd643bae3d6bf56a137ede56d21a80d59b64
8e5ae87af13e723705d41e2ad686ca80ee2ce3d6
/application/main.cxx
5bc9f98dd3c6112f350ffcf8b44eebfe8424df2a
[ "MIT" ]
permissive
xTachyon/PluginSystem
1d970963e6239e1e0d010e0a135a3e64ed4c9f82
6c3a83743f706eedf1cfcad92eb756289d8f79e1
refs/heads/master
2020-12-31T06:55:12.369309
2017-07-05T08:32:37
2017-07-05T08:32:37
86,615,708
2
1
null
null
null
null
UTF-8
C++
false
false
155
cxx
#include "server.hpp" int main() { Server s; s.loadPlugin("/home/andrei/redi/PluginSystem/cmake-build-debug/myplugin/myplugin.so"); return 0; }
[ "andreidaamian@gmail.com" ]
andreidaamian@gmail.com
deda48296624e371bfaca0bfa56bbb13fcdd413f
2fbeb09a417bd678963ee8417766dade77dcd4c1
/game_framework/components/physics_definition_component.h
c908841b8d5ae3cb8f06fbeb6cd310a32df1ff6e
[]
no_license
Kartezjan/Augmentations
5ebdb5b770e99a3c8e6ee79ec7db3a9b76c3e3a7
d8397cf0951bdbb66d8be14173f36ccbe733586e
refs/heads/master
2021-04-15T06:52:56.278827
2016-02-29T22:34:34
2016-02-29T22:34:34
52,829,837
0
0
null
2016-02-29T22:32:41
2016-02-29T22:32:41
null
UTF-8
C++
false
false
546
h
#pragma once #include "../shared/physics_setup_helpers.h" namespace components { struct physics_definition { bool dont_create_fixtures_and_body = false; bool preserve_definition_for_cloning = true; body_definition body; std::vector<fixture_definition> fixtures; augs::entity_id attach_fixtures_to_entity; fixture_definition& new_fixture(augs::entity_id attached_to_entity = augs::entity_id()) { attach_fixtures_to_entity = attached_to_entity; fixtures.push_back(fixture_definition()); return *fixtures.rbegin(); } }; }
[ "unknown.unreleased@gmail.com" ]
unknown.unreleased@gmail.com
6d83c1cd2456e1b14990be4a6e38a78a8b88d78a
abea3523cd2cc1f582a6fa37e8ade1d54e7e18e2
/EPI/HashTables_Ch12/smallesSubArrayInSequence.cpp
ed068da86c1c28edd13b2f6ee4424f9ba7feddcb
[]
no_license
aravind254/CodingExperiments
a78c17d9f4d8e227a07e1073daf5cc3c5183583f
0b37ec7380bf82b5f0b92d0b1c15cd4e734dfbc7
refs/heads/master
2022-12-26T02:36:23.305592
2018-05-26T05:06:01
2018-05-26T05:06:01
80,171,962
2
0
null
2022-12-16T20:59:00
2017-01-27T01:20:15
C++
UTF-8
C++
false
false
2,131
cpp
#include<iostream> #include<unordered_map> #include<vector> #include<list> #include<string> using namespace std; struct subArray { int start; int end; }; // Assuming input size is n, searchSet size is k // TimeComplexity : O(n+k) // SpaceComplexity : O(k) subArray findSmallestSubarrayInSequence(const vector<string> &input, const vector<string> &searchSet) { unordered_map<string,int> sMap; subArray result = {-1,-1}; int minDistance = std::numeric_limits<int>::max(); int searchSetSize = searchSet.size(); vector<int> latestOccurence(searchSetSize,-1); // Tracks the latest index of the searchSet vector<int> subArrayLength(searchSetSize,std::numeric_limits<int>::max());// Tracks the distance of the sub array int curIndex = 0; // index that tracks the sequence of strings in the searchSet // Map the search set to the index for(int i = 0;i<searchSet.size();i++) { sMap[searchSet[i]] = i; } for(int i = 0;i<input.size();i++) { if(sMap.count(input[i])) // Is the input string present in the search set { int curIndex = sMap[input[i]]; if(curIndex == 0) // This is start of the search set sequence { subArrayLength[0] = 1; } else if(subArrayLength[curIndex-1] != std::numeric_limits<int>::max()) { subArrayLength[curIndex] = subArrayLength[curIndex-1] + (i - latestOccurence[curIndex-1]); } latestOccurence[curIndex] = i; // Is this the last word in the searchSet if(curIndex == searchSetSize-1) { if(subArrayLength[curIndex] < minDistance) { minDistance = subArrayLength[curIndex]; result.start = latestOccurence[0]; result.end = latestOccurence[curIndex]; } } } } cout << "minDistance," << minDistance << endl; return result; } int main() { vector<string> input = {"apple","banana","apple","apple","dog","cat","apple","dog","banana","dog","cat","apple"}; vector<string> searchSet = {"banana","cat","dog"}; subArray result = findSmallestSubarrayInSequence(input,searchSet); cout << "start,"<< result.start << ",end,"<< result.end << endl; }
[ "aravind@Aravinds-MacBook-Pro.local" ]
aravind@Aravinds-MacBook-Pro.local
007da88fc03d38bd1786e5d791d263a6de024ee1
8d3f02ad6e8a22d844b402c64e3ab2f42e2cf8e8
/rtmaps4wifibot_sdk/src/wifibot.u/src/maps_keyboard_4_wifibot.cpp
e86f3cb445c4cbd9e91ffc1a9e02f0064d06f8e9
[]
no_license
Wexiwa/utc-sy27-line-following-wifibot
64b42d46261b31f6946e90f60de602ed626050ea
b67c972b236f32080a9c03d157014f0aed63709d
refs/heads/master
2016-09-05T15:08:09.143167
2013-01-14T04:19:29
2013-01-14T04:19:29
32,279,516
0
0
null
null
null
null
UTF-8
C++
false
false
6,512
cpp
//////////////////////////////// // RTMaps SDK Component //////////////////////////////// //////////////////////////////// // Purpose of this module : //////////////////////////////// #include "maps_keyboard_4_wifibot.h" // Includes the header of this component // Use the macros to declare the inputs MAPS_BEGIN_INPUTS_DEFINITION(MAPSkeyboard_4_wifibot) MAPS_INPUT("input_code",MAPS::FilterInteger,MAPS::FifoReader) MAPS_END_INPUTS_DEFINITION // Use the macros to declare the outputs MAPS_BEGIN_OUTPUTS_DEFINITION(MAPSkeyboard_4_wifibot) MAPS_OUTPUT("left_and_right_motor_speeds",MAPS::Integer,NULL,NULL,2) MAPS_OUTPUT("left_motor_speed",MAPS::Integer,NULL,NULL,1) MAPS_OUTPUT("right_motor_speed",MAPS::Integer,NULL,NULL,1) MAPS_END_OUTPUTS_DEFINITION // Use the macros to declare the properties MAPS_BEGIN_PROPERTIES_DEFINITION(MAPSkeyboard_4_wifibot) MAPS_PROPERTY_ENUM("output_mode","Vectorized|Separated left/right speeds",0,false,false) MAPS_PROPERTY("input_code_1",200,false,false) MAPS_PROPERTY("input_code_1_left_speed",40,false,false) MAPS_PROPERTY("input_code_1_right_speed",40,false,false) MAPS_PROPERTY("input_code_2",208,false,false) MAPS_PROPERTY("input_code_2_left_speed",-40,false,false) MAPS_PROPERTY("input_code_2_right_speed",-40,false,false) MAPS_PROPERTY("input_code_3",203,false,false) MAPS_PROPERTY("input_code_3_left_speed",-30,false,false) MAPS_PROPERTY("input_code_3_right_speed",30,false,false) MAPS_PROPERTY("input_code_4",205,false,false) MAPS_PROPERTY("input_code_4_left_speed",30,false,false) MAPS_PROPERTY("input_code_4_right_speed",-30,false,false) MAPS_PROPERTY("input_code_5",32,false,false) MAPS_PROPERTY("input_code_5_left_speed",0,false,false) MAPS_PROPERTY("input_code_5_right_speed",0,false,false) MAPS_PROPERTY_ENUM("any_other_code","Ignore|Stop the robot",0,false,false) MAPS_PROPERTY("nb_additional_configs",0,false,false) MAPS_END_PROPERTIES_DEFINITION #define FIRST_DYN_PROP 18 // Use the macros to declare the actions MAPS_BEGIN_ACTIONS_DEFINITION(MAPSkeyboard_4_wifibot) //MAPS_ACTION("aName",MAPSkeyboard_4_wifibot::ActionName) MAPS_END_ACTIONS_DEFINITION // Use the macros to declare this component (keyboard_4_wifibot) behaviour MAPS_COMPONENT_DEFINITION(MAPSkeyboard_4_wifibot,"keyboard_4_wifibot","1.0",128, MAPS::Threaded,MAPS::Threaded, 1, // Nb of inputs 0, // Nb of outputs FIRST_DYN_PROP, // Nb of properties 0) // Nb of actions void MAPSkeyboard_4_wifibot::Dynamic() { _output_mode = (int)GetIntegerProperty("output_mode"); _nb_confs = (int)GetIntegerProperty("nb_additional_configs"); switch(_output_mode) { case 0: NewOutput(0); break; case 1: NewOutput(1); NewOutput(2); break; } for (int i=0; i<_nb_confs; i++) { MAPSStreamedString name1("input_code_"); name1 << 6+i; MAPSStreamedString name2("input_code_"); name2 << 6+i << "_left_speed"; MAPSStreamedString name3("input_code_"); name3 << 6+i << "_right_speed"; NewProperty("input_code_1",name1); NewProperty("input_code_1_left_speed",name2); NewProperty("input_code_1_right_speed",name3); } } void MAPSkeyboard_4_wifibot::Birth() { _default_action = (int)GetIntegerProperty("any_other_code"); _config1.code = (int)GetIntegerProperty("input_code_1"); _config1.left = (int)GetIntegerProperty("input_code_1_left_speed"); _config1.right = (int)GetIntegerProperty("input_code_1_right_speed"); _config2.code = (int)GetIntegerProperty("input_code_2"); _config2.left = (int)GetIntegerProperty("input_code_2_left_speed"); _config2.right = (int)GetIntegerProperty("input_code_2_right_speed"); _config3.code = (int)GetIntegerProperty("input_code_3"); _config3.left = (int)GetIntegerProperty("input_code_3_left_speed"); _config3.right = (int)GetIntegerProperty("input_code_3_right_speed"); _config4.code = (int)GetIntegerProperty("input_code_4"); _config4.left = (int)GetIntegerProperty("input_code_4_left_speed"); _config4.right = (int)GetIntegerProperty("input_code_4_right_speed"); _config5.code = (int)GetIntegerProperty("input_code_5"); _config5.left = (int)GetIntegerProperty("input_code_5_left_speed"); _config5.right = (int)GetIntegerProperty("input_code_5_right_speed"); _additional_configs = NULL; if (_nb_confs > 0) { _additional_configs = new CodeConfig[_nb_confs]; for (int i=0; i<_nb_confs; i++) { _additional_configs[i].code = (int)GetIntegerProperty(FIRST_DYN_PROP + 3*i); _additional_configs[i].left = (int)GetIntegerProperty(FIRST_DYN_PROP + 3*i + 1); _additional_configs[i].right = (int)GetIntegerProperty(FIRST_DYN_PROP + 3*i + 2); } } } void MAPSkeyboard_4_wifibot::Core() { MAPSIOElt* ioeltin = StartReading(Input(0)); if (ioeltin == NULL) return; int code = ioeltin->Integer(); int left = 0; int right = 0; bool discard = false; if (code == _config1.code) { left = _config1.left; right = _config1.right; } else if (code == _config2.code) { left = _config2.left; right = _config2.right; } else if (code == _config3.code) { left = _config3.left; right = _config3.right; } else if (code == _config4.code) { left = _config4.left; right = _config4.right; } else if (code == _config5.code) { left = _config5.left; right = _config5.right; } else { bool found = false; for (int i=0; i< _nb_confs; i++) { if (code == _additional_configs[i].code) { found = true; left = _additional_configs[i].left; right = _additional_configs[i].right; break; } } if (false == found) { if (_default_action == 0) { //ignore discard = true; } } } if (false == discard) { if (_output_mode == 0) { //vectorized MAPSIOElt* ioeltout = StartWriting(Output(0)); ioeltout->Integer() = left; ioeltout->Integer(1) = right; ioeltout->Timestamp() = ioeltin->Timestamp(); StopWriting(ioeltout); } else { //splitted outputs MAPSIOElt* ioeltout = StartWriting(Output(0)); MAPSIOElt* ioeltout2 = StartWriting(Output(1)); ioeltout->Integer() = left; ioeltout2->Integer() = right; ioeltout->Timestamp() = ioeltin->Timestamp(); ioeltout2->Timestamp() = ioeltin->Timestamp(); StopWriting(ioeltout2); StopWriting(ioeltout); } } } void MAPSkeyboard_4_wifibot::Death() { if (_additional_configs) { delete [] _additional_configs; _additional_configs = NULL; } }
[ "maxime.vinci@c3762529-cd7b-1f0b-eac3-90952162ebf1" ]
maxime.vinci@c3762529-cd7b-1f0b-eac3-90952162ebf1
5318cd3787fd29bb0c743a985e0a389063243fa9
03136041822d3f4336897539ba28cba7019de650
/ShittyUxTheme.cpp
e3081a0d5113aca14060299410ec1c1a34d40f57
[ "MIT" ]
permissive
namazso/ShittyUxTheme
2fd1acf2db6011ae543b16682ebbd68b5660b3e3
19d6cfb25f3775cbd3753013d2e2ef8908124a1a
refs/heads/master
2023-07-09T18:05:55.642170
2021-08-13T00:48:16
2021-08-13T00:48:16
395,409,927
8
2
null
null
null
null
UTF-8
C++
false
false
6,153
cpp
#define _NO_CVCONST_H #include <Windows.h> #include <DbgHelp.h> #include <cstdio> #include <unordered_set> #include <xutility> #include <vector> #include <string> #include <fstream> #include <cstdint> BOOL TakeOwnership(LPTSTR lpszOwnFile); std::vector<uint8_t> read_all(const wchar_t* path) { std::ifstream is(path, std::ios::binary); if (!is.good() || !is.is_open()) return {}; is.seekg(0, std::ifstream::end); std::vector<uint8_t> data; data.resize((size_t)is.tellg()); is.seekg(0, std::ifstream::beg); is.read(reinterpret_cast<char*>(data.data()), (std::streamsize)data.size()); return data; } bool write_all(const wchar_t* path, const void* data, size_t size) { std::ofstream os(path, std::ios::binary); if (!os.is_open() || !os.good()) return false; os.write((const char*)data, size); return os.good(); } uint32_t rva2fo(const uint8_t* image, uint32_t rva) { const auto idh = (PIMAGE_DOS_HEADER)image; if (idh->e_magic != IMAGE_DOS_SIGNATURE) return 0; const auto inh = (PIMAGE_NT_HEADERS)(image + idh->e_lfanew); if (inh->Signature != IMAGE_NT_SIGNATURE) return 0; const auto sections = IMAGE_FIRST_SECTION(inh); const auto sections_count = inh->FileHeader.NumberOfSections; for (size_t i = 0; i < sections_count; ++i) { const auto& sec = sections[i]; if (sec.PointerToRawData && sec.VirtualAddress <= rva && sec.VirtualAddress + sec.SizeOfRawData > rva) return rva - sec.VirtualAddress + sec.PointerToRawData; } return 0; } static int do_the_patch(const wchar_t* image) { wprintf(L"Trying image %s\n", image); const auto lib = LoadLibraryExW(image, nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32); if (!lib) { wprintf(L"LoadLibraryExW failed: %lu\n", GetLastError()); return 0; // whatever } wchar_t path[MAX_PATH + 1]; if (!GetModuleFileNameW(lib, path, (DWORD)std::size(path))) { wprintf(L"GetModuleFileNameW failed: %lu\n", GetLastError()); return 0; } const auto load_base = SymLoadModuleExW( GetCurrentProcess(), nullptr, path, nullptr, (DWORD64)lib, 0, nullptr, 0 ); if (load_base == 0) { wprintf(L"SymLoadModuleExW failed: %lu\n", GetLastError()); return 0; } std::unordered_set<uint32_t> patch_rvas; auto success = SymEnumSymbolsExW( GetCurrentProcess(), (DWORD64)lib, nullptr, []( _In_ PSYMBOL_INFOW sym_info, _In_ ULONG /*SymbolSize*/, _In_opt_ PVOID ctx )->BOOL { if (0 == wcscmp(sym_info->Name, L"CThemeSignature::Verify")) { const auto rva = (uint32_t)(sym_info->Address - sym_info->ModBase); ((std::unordered_set<uint32_t>*)ctx)->insert(rva); } return TRUE; }, &patch_rvas, SYMENUM_OPTIONS_DEFAULT ); if (patch_rvas.empty()) return 0; auto file = read_all(path); if(file.empty()) { wprintf(L"can't read file\n"); return 0; } constexpr static uint8_t patch[] = { #if defined(_M_IX86) 0x31, 0xC0, // xor eax, eax 0xC2, 0x08, 0x00 // ret 8 #elif defined(_M_AMD64) 0x31, 0xC0, // xor eax, eax 0xC3 // ret #elif defined(_M_ARM64) 0x00, 0x00, 0x80, 0x52, // mov w0, #0 0xC0, 0x03, 0x5F, 0xD6, // ret #endif }; unsigned patched = 0; for (auto rva : patch_rvas) { const auto fo = rva2fo(file.data(), rva); wprintf(L"found at rva %08X file offset %08X\n", rva, fo); if (fo == 0) continue; if (0 != memcmp(file.data() + fo, patch, sizeof patch)) { memcpy(file.data() + fo, patch, sizeof patch); patched++; } } if (patched == 0) { wprintf(L"file already patched!\n"); return (int)patch_rvas.size(); } const auto patched_path = std::wstring(path) + L".patched"; const auto backup_path = std::wstring(path) + L".bak" + std::to_wstring(_time64(nullptr)); if(!write_all(patched_path.c_str(), file.data(), file.size())) { fwprintf(stderr, L"write_all failed\n"); return 0; } if(!TakeOwnership(path)) { fwprintf(stderr, L"TakeOwnership failed: %lu\n", GetLastError()); return 0; } if(!MoveFileW(path, backup_path.c_str())) { fwprintf(stderr, L"MoveFileW %s -> %s failed: %lu\n", path, backup_path.c_str(), GetLastError()); return 0; } if (!MoveFileW(patched_path.c_str(), path)) { fwprintf(stderr, L"MoveFileW %s -> %s failed: %lu\n", patched_path.c_str(), path, GetLastError()); if (!MoveFileW(backup_path.c_str(), path)) fwprintf(stderr, L"MoveFileW %s -> %s failed: %lu. This is pretty bad!\n", backup_path.c_str(), path, GetLastError()); return 0; } return (int)patch_rvas.size(); } constexpr static const wchar_t* s_images[] = { L"themeui", L"themeservice", L"uxinit", L"uxtheme", }; enum return_code { error_success, error_no_symsrv, error_sym_set_options, error_get_temp_path, error_sym_initialize, error_none_patched }; int main() { if(nullptr == LoadLibraryW(L"symsrv.dll")) { fwprintf(stderr, L"Can't load symsrv: %lu\n", GetLastError()); return error_no_symsrv; } if (!SymSetOptions(SYMOPT_UNDNAME | SYMOPT_EXACT_SYMBOLS | SYMOPT_FAIL_CRITICAL_ERRORS)) { fwprintf(stderr, L"SymSetOptions failed: %lu\n", GetLastError()); return error_sym_set_options; } wchar_t temp_path[MAX_PATH + 1]; if(0 == GetTempPathW((DWORD)std::size(temp_path), temp_path)) { fwprintf(stderr, L"GetTempPathW failed: %lu\n", GetLastError()); return error_get_temp_path; } wchar_t search_path[MAX_PATH + 100]; swprintf_s(search_path, L"srv*%sSymbols*https://msdl.microsoft.com/download/symbols", temp_path); if (!SymInitializeW(GetCurrentProcess(), search_path, false)) { fwprintf(stderr, L"SymInitializeW failed: %lu\n", GetLastError()); return error_sym_initialize; } auto patched = 0; for (auto image : s_images) { const auto result = do_the_patch(image); patched += result; } if (patched == 0) { fwprintf(stderr, L"patching failed: none patched\n"); return error_none_patched; } wprintf(L"patched %d\n", patched); return 0; }
[ "admin@namazso.eu" ]
admin@namazso.eu
3cd6e70b6cdaf75b2dff6c43183a9ed8097ebd2d
3f4e4d2927d44c4f30d5a3b23c99934e643eb9b4
/SyncopationXY/src/ofApp.cpp
6831225faffaf85f2d0e7e68de84713220c31f72
[]
no_license
tado/SyncopationStudy
96abcf8eb4485b06fade0ecb4a52a60f9b0d544d
e4e44aedfb5e8debb0cd4dda346e88d5b0e5dba3
refs/heads/master
2021-01-20T08:13:50.991148
2017-07-12T17:08:59
2017-07-12T17:08:59
90,114,909
1
0
null
null
null
null
UTF-8
C++
false
false
3,610
cpp
#include "ofApp.h" //-------------------------------------------------------------- void ofApp::setup(){ ofBackground(0); ofSetFrameRate(30); gui = new GUI(); showGui = false; parseSyncoKTH = new ParseSyncopation("KTH.json"); parseSyncoLHL = new ParseSyncopation("LHL.json"); parseSyncoPRS = new ParseSyncopation("PRS.json"); parseSyncoSG = new ParseSyncopation("SG.json"); parseSyncoTMC = new ParseSyncopation("TMC.json"); parseSyncoTOB = new ParseSyncopation("TOB.json"); parseSyncoWNBD = new ParseSyncopation("WNBD.json"); recorder = new Recorder(); rhythmPicker = new RhythmPicker(); rhythmPlayer = new RhythmPlayer(); rhythmPlayer->bpm = 120; //rhythmPlayer->start(); } //-------------------------------------------------------------- void ofApp::update(){ switch (gui->syncoMode) { case 0: parseSynco = parseSyncoKTH; break; case 1: parseSynco = parseSyncoLHL; break; case 2: parseSynco = parseSyncoPRS; break; case 3: parseSynco = parseSyncoSG; break; case 4: parseSynco = parseSyncoTMC; break; case 5: parseSynco = parseSyncoTOB; break; case 6: parseSynco = parseSyncoWNBD; break; default: break; } rhythmPicker->update(); gui->update(); recorder->update(); } //-------------------------------------------------------------- void ofApp::draw(){ if (gui->drawSynco) { parseSynco->draw(); rhythmPlayer->draw(); } rhythmPicker->draw(); recorder->draw(); if (showGui) { gui->draw(); } } void ofApp::exit(){ rhythmPlayer->stop(); } //-------------------------------------------------------------- void ofApp::keyPressed(int key){ if (key == 'g') { if (showGui) { showGui = false; } else { showGui = true; } } if (key == ' ') { if (recorder->started == false) { recorder->start(); rhythmPlayer->start(); } else { recorder->stop(); rhythmPlayer->stop(); } } } //-------------------------------------------------------------- void ofApp::keyReleased(int key){ } //-------------------------------------------------------------- void ofApp::mouseMoved(int x, int y ){ rhythmPicker->mouseMoved(x, y); } //-------------------------------------------------------------- void ofApp::mouseDragged(int x, int y, int button){ //rhythmPicker->mouseDragged(x, y, button); } //-------------------------------------------------------------- void ofApp::mousePressed(int x, int y, int button){ //rhythmPicker->mousePressed(x, y, button); } //-------------------------------------------------------------- void ofApp::mouseReleased(int x, int y, int button){ //rhythmPicker->mouseReleased(x, y, button); } //-------------------------------------------------------------- void ofApp::mouseEntered(int x, int y){ } //-------------------------------------------------------------- void ofApp::mouseExited(int x, int y){ } //-------------------------------------------------------------- void ofApp::windowResized(int w, int h){ } //-------------------------------------------------------------- void ofApp::gotMessage(ofMessage msg){ } //-------------------------------------------------------------- void ofApp::dragEvent(ofDragInfo dragInfo){ }
[ "tadokoro@gmail.com" ]
tadokoro@gmail.com
225ddcee7056519717cf45b2a5d92adc723efd74
2238d9c2818ea708aea0d12e7345705245b2a628
/application/source/Warpzone.h
693ef72f5421cf7d83c26216d601174076bc20a0
[]
no_license
PowerKiKi/polukili
1e1cb69bce1c92982807b0a033735ec235f44b64
6c9b84d817dc2c6cdfac09a74030cf7ecc6417a9
refs/heads/master
2020-05-19T23:29:30.853455
2011-02-14T08:09:04
2011-02-14T08:09:04
173,132
2
0
null
null
null
null
UTF-8
C++
false
false
310
h
#ifndef Polukili_Warpzone_h #define Polukili_Warpzone_h #include <Actor.h> namespace Polukili { /** * Represent a warpzone object which will allow the player to enter other levels. (eg: fridge, bed, etc.) */ class Warpzone : public Actor { //end of class Warpzone }; } #endif
[ "adrien.crivelli@gmail.com" ]
adrien.crivelli@gmail.com
5e2c1f6cd70a7c626f78969b936444191fe93399
b6de03d101fcfdb83f6b16f1783385e48bfdb584
/thirdparty/gRPC/third_party/protobuf/src/google/protobuf/compiler/javanano/javanano_enum_field.h
1a8e912cbff5c6e2207b16b7b72c463b43d5e0a8
[ "LicenseRef-scancode-protobuf", "Apache-2.0" ]
permissive
Romantic-LiXuefeng/StudyProgram
b173308171895e118ae27bab96566a9d6b38f1e5
03a36009c8917cdc9f6dde39bc681d263bc1b3cc
refs/heads/master
2021-12-23T06:02:12.776062
2017-11-05T08:56:52
2017-11-05T08:56:52
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,075
h
// Protocol Buffers - Google's data interchange format // Copyright 2008 Google Inc. All rights reserved. // http://code.google.com/p/protobuf/ // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // Author: kenton@google.com (Kenton Varda) // Based on original Protocol Buffers design by // Sanjay Ghemawat, Jeff Dean, and others. #ifndef GOOGLE_PROTOBUF_COMPILER_JAVANANO_ENUM_FIELD_H__ #define GOOGLE_PROTOBUF_COMPILER_JAVANANO_ENUM_FIELD_H__ #include <map> #include <string> #include <vector> #include <google/protobuf/compiler/javanano/javanano_field.h> namespace google { namespace protobuf { namespace compiler { namespace javanano { class EnumFieldGenerator : public FieldGenerator { public: explicit EnumFieldGenerator( const FieldDescriptor* descriptor, const Params& params); ~EnumFieldGenerator(); // implements FieldGenerator --------------------------------------- void GenerateMembers(io::Printer* printer, bool lazy_init) const; void GenerateClearCode(io::Printer* printer) const; void GenerateMergingCode(io::Printer* printer) const; void GenerateSerializationCode(io::Printer* printer) const; void GenerateSerializedSizeCode(io::Printer* printer) const; void GenerateEqualsCode(io::Printer* printer) const; void GenerateHashCodeCode(io::Printer* printer) const; private: const FieldDescriptor* descriptor_; map<string, string> variables_; vector<string> canonical_values_; GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(EnumFieldGenerator); }; class AccessorEnumFieldGenerator : public FieldGenerator { public: explicit AccessorEnumFieldGenerator(const FieldDescriptor* descriptor, const Params& params, int has_bit_index); ~AccessorEnumFieldGenerator(); // implements FieldGenerator --------------------------------------- void GenerateMembers(io::Printer* printer, bool lazy_init) const; void GenerateClearCode(io::Printer* printer) const; void GenerateMergingCode(io::Printer* printer) const; void GenerateSerializationCode(io::Printer* printer) const; void GenerateSerializedSizeCode(io::Printer* printer) const; void GenerateEqualsCode(io::Printer* printer) const; void GenerateHashCodeCode(io::Printer* printer) const; private: const FieldDescriptor* descriptor_; map<string, string> variables_; vector<string> canonical_values_; GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(AccessorEnumFieldGenerator); }; class RepeatedEnumFieldGenerator : public FieldGenerator { public: explicit RepeatedEnumFieldGenerator( const FieldDescriptor* descriptor, const Params& params); ~RepeatedEnumFieldGenerator(); // implements FieldGenerator --------------------------------------- void GenerateMembers(io::Printer* printer, bool lazy_init) const; void GenerateClearCode(io::Printer* printer) const; void GenerateMergingCode(io::Printer* printer) const; void GenerateMergingCodeFromPacked(io::Printer* printer) const; void GenerateSerializationCode(io::Printer* printer) const; void GenerateSerializedSizeCode(io::Printer* printer) const; void GenerateEqualsCode(io::Printer* printer) const; void GenerateHashCodeCode(io::Printer* printer) const; void GenerateFixClonedCode(io::Printer* printer) const; private: void GenerateRepeatedDataSizeCode(io::Printer* printer) const; const FieldDescriptor* descriptor_; map<string, string> variables_; vector<string> canonical_values_; GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(RepeatedEnumFieldGenerator); }; } // namespace javanano } // namespace compiler } // namespace protobuf } // namespace google #endif // GOOGLE_PROTOBUF_COMPILER_JAVANANO_ENUM_FIELD_H__
[ "529647632@qq.com" ]
529647632@qq.com
3b4673db8de2b9225ecafea4e2804e32cf07ac25
4b9418e3f535ccd551b02e86c5b699127d77233f
/packages/driver/Driver.hh
3b872c9014ef41c763de5e470e360d8c954ac16b
[]
no_license
brbass/yak
2e4352218a48fb2c77998026e5f9f6748d109da9
ef3654139ca6590278917951ebc8418545a9addf
refs/heads/master
2022-12-22T13:59:58.710252
2022-12-14T19:29:32
2022-12-14T19:29:32
56,200,793
1
0
null
null
null
null
UTF-8
C++
false
false
593
hh
#ifndef Driver_hh #define Driver_hh #include <string> #include "pugixml.hh" using std::string; /* Create and run transport problem from XML file */ class Driver { public: // Constructor Driver(string filename); void output(pugi::xml_node &output_node) const; private: // Run transport problem void run_problem(); double total_time_; double discretization_parser_time_; double data_parser_time_; double solver_parser_time_; double transport_parser_time_; double solution_time_; string xml_in_; string xml_out_; }; #endif
[ "brbass@umich.edu" ]
brbass@umich.edu
f70b17f589e02f63f1e2a396bd06f90542444fdf
7ef31498eff2724173ec13d44333820b0731301b
/read_memory_with_template.cpp
fee991b59aa9243ecc2c3c1f4c0eeb9fdaac85d4
[]
no_license
AliMeheik/ReadingProcessMemory
cafe18c70742f136a8759bfcaf10cb0cc786ed45
3ff04212efdb13b5f6386ad88291cbb0faf203dd
refs/heads/master
2022-11-07T05:16:59.943675
2020-06-15T10:49:45
2020-06-15T10:49:45
272,387,035
0
0
null
null
null
null
UTF-8
C++
false
false
2,198
cpp
#include <string> #include <iostream> #include <windows.h> #include <TlHelp32.h> #include <optional> using std::cin; using std::cout; using std::endl; using std::hex; using std::wstring; using std::optional; DWORD GetProcessID_byName( const std::wstring* process_name ) { PROCESSENTRY32 process_buffer; DWORD processId = 0; HANDLE process_snapshot = CreateToolhelp32Snapshot( TH32CS_SNAPPROCESS, NULL ); if( process_snapshot != INVALID_HANDLE_VALUE ) { process_buffer.dwSize = sizeof( PROCESSENTRY32 ); if( Process32First( process_snapshot, &process_buffer ) ) { do { if( !_wcsicmp( process_name->c_str(), process_buffer.szExeFile ) ) { processId = process_buffer.th32ProcessID; break; } } while( Process32Next( process_snapshot, &process_buffer ) ); } CloseHandle( process_snapshot ); } return processId; } template<typename Read_type> const optional<Read_type> ReadMemoryValue( const uintptr_t& address, const HANDLE *process_handle ) { Read_type read_value; if( !ReadProcessMemory( *process_handle, (LPCVOID)address, &read_value, sizeof( Read_type ), nullptr ) ) { return std::nullopt; } return read_value; } int main() { do { cout << "Enter process name: "; std::wstring process_name; getline( std::wcin, process_name ); DWORD process_id = GetProcessID_byName( &process_name ); if( !process_id ) { cout << "Failed to get process id" << endl; break; } HANDLE process_handle = OpenProcess( PROCESS_ALL_ACCESS, false, process_id ); if( !process_handle ) { cout << "Failed to open process" << endl; break; } uintptr_t address; cout << "Enter variable address: "; cin >> hex >> address; optional<int> value = ReadMemoryValue<int>( address, &process_handle ); if( !value ) { cout << "Read failed" << endl; break; } cout << "Read value: " << *value << endl; } while( 0 ); system( "pause" ); return 0; }
[ "ali.meheik@gmail.com" ]
ali.meheik@gmail.com
b49c5fe8e8f5354bbcdec6412e32dcb602fd2a9e
2564189bae21f3c175d7b8e2d2635484600d59da
/Zadaće/Z5/Z1/main.cpp
ff2e58da19824a86646e382c6c5a825f57b49976
[]
no_license
almulalic/Tehnike-Programiranja-2020
f7ceffba624af05fe72783eaaebf4523bbc2e1de
bda207c1b750aade2a99dd179df45186c04527fc
refs/heads/main
2023-02-21T11:20:04.998310
2021-01-19T00:52:48
2021-01-19T00:52:48
330,823,228
1
1
null
null
null
null
UTF-8
C++
false
false
8,820
cpp
//TP 2018/2019: Zadaća 5, Zadatak 1 #include <iostream> #include <initializer_list> #include <iomanip> #include <vector> template <class T> class SimetricnaMatrica { std::vector<std::vector<T>> elementi; public: SimetricnaMatrica(SimetricnaMatrica& sm); SimetricnaMatrica(SimetricnaMatrica&& sm); SimetricnaMatrica(std::vector<std::vector<T>> vv); SimetricnaMatrica(std::initializer_list<std::initializer_list<T>> vv); explicit SimetricnaMatrica(int n=0); int DajDimenziju() const { return elementi.size(); } bool operator!(); template <typename Tp1,typename Tp2> friend auto operator+(const SimetricnaMatrica<Tp1>& a, const SimetricnaMatrica<Tp2>& b) -> decltype(auto c = a.elementi.at(0) + b.elementi.at(0)); template <typename Tp1,typename Tp2> friend auto operator-(const SimetricnaMatrica<Tp1>& a, const SimetricnaMatrica<Tp2>& b); template <typename Tp1,typename Tp2> friend auto operator*(const SimetricnaMatrica<Tp1>& a, const SimetricnaMatrica<Tp2>& b); template <typename Tp> friend bool operator==(const SimetricnaMatrica<Tp>&a,const SimetricnaMatrica<Tp>&b); template <typename Tp> friend bool operator!=(const SimetricnaMatrica<Tp>&a,const SimetricnaMatrica<Tp>&b); template <typename Tp> friend std::ostream& operator<<(std::ostream& izlaz, const SimetricnaMatrica<Tp>& sm); template <typename Tp> friend std::istream& operator>>(std::istream& ulaz,SimetricnaMatrica<Tp>& sm); }; template <class T> SimetricnaMatrica<T>::SimetricnaMatrica(SimetricnaMatrica<T>& sm) { int count(1); for(int i=0;i<sm.elementi.size();++i) { if(sm.elementi.at(i).size() != count) throw std::logic_error("Nekorektna forma simetricne matrice"); else count++; } elementi.clear(); std::vector<T> tempRed; for(int i=0;i<sm.elementi.size();++i) { for(int j=0;j<sm.elementi.at(i).size();++j) { tempRed.push_back(sm.elementi.at(i).at(j)); } elementi.push_back(tempRed); tempRed.clear(); } } template <class T> SimetricnaMatrica<T>::SimetricnaMatrica(SimetricnaMatrica<T>&& sm) { int count(1); for(int i=0;i<sm.elementi.size();++i) { if(sm.elementi.at(i).size() != count) throw std::logic_error("Nekorektna forma simetricne matrice"); else count++; } elementi.clear(); std::vector<T> tempRed; for(int i=0;i<sm.elementi.size();++i) { for(int j=0;j<sm.elementi.at(i).size();++j) { tempRed.push_back(sm.elementi.at(i).at(j)); } elementi.push_back(tempRed); tempRed.clear(); } } template <class T> SimetricnaMatrica<T>::SimetricnaMatrica(std::vector<std::vector<T>> vv){ int count(1); for(auto red:vv) { if(red.size() != count) throw std::logic_error("Nekorektna forma simetricne matrice"); else count++; } } template <class T> SimetricnaMatrica<T>::SimetricnaMatrica(std::initializer_list<std::initializer_list<T>> vv) { int count(1); for(auto red:vv) { if(red.size() != count) throw std::logic_error("Nekorektna forma simetricne matrice"); else count++; } std::vector<T> tempRed; for(auto red:vv) { for(auto broj:red) { tempRed.push_back(broj); } elementi.push_back(tempRed); tempRed.clear(); } } template <class T> SimetricnaMatrica<T>::SimetricnaMatrica(int n) { if(n < 0) throw std::domain_error("Neispravna dimenzija"); int limit(1); std::vector<T> tempRed; for(int i=0;i<n;++i) { for(int j=0;j<limit;++j) { tempRed.push_back(0); } elementi.push_back(tempRed); limit++; } } template <class T> bool SimetricnaMatrica<T>::operator!() { for(auto red:elementi) { for(auto broj:elementi) { if(broj != 0) return false; } } return true; } template <class Tp1, class Tp2> auto operator+(const SimetricnaMatrica<Tp1>& a, const SimetricnaMatrica<Tp2>& b) -> decltype(a.at(0).at(0) + b.at(0).at(0)) { if(a.elementi.size() != b.elementi.size()) throw std::domain_error("Matrice nisu saglasne za trazenu operaciju"); SimetricnaMatrica<Tr> c(a.elementi.size()); for(int i=0;i<a.elementi.size();++i) { for(int j=0;j<a.elementi.at(i).size();++j) { c.elementi.at(i).at(j) = a.elementi.at(i).at(j) + b.elementi.at(i).at(j); } } return c; } template <class Tp1, class Tp2> auto operator-(const SimetricnaMatrica<Tp1>& a, const SimetricnaMatrica<Tp2>& b) -> decltype(a.at(0).at(0) + b.at(0).at(0)) { if(a.elementi.size() != b.elementi.size()) throw std::domain_error("Matrice nisu saglasne za trazenu operaciju"); SimetricnaMatrica<Tr> c(a.elementi.size()); for(int i=0;i<a.elementi.size();++i) { for(int j=0;j<a.elementi.at(i).size();++j) { c.elementi.at(i).at(j) = a.elementi.at(i).at(j) - b.elementi.at(i).at(j); } } return c; } template <class Tr, class Tp1, class Tp2> auto operator*(const SimetricnaMatrica<Tp1>& a, const SimetricnaMatrica<Tp2>& b) -> decltype(a.at(0).at(0) + b.at(0).at(0)) { if(a.elementi.size() != b.elementi.size( )) throw std::domain_error("Matrice nisu saglasne za trazenu operaciju"); SimetricnaMatrica<Tr> c(a.elementi.size()); int clan; for(int i=0;i<a.elementi.size();++i) { for(int j=0;j<a.elementi.at(i).size();++j) { for(int k=0;k<a.elementi.at(i).size();++k) { clan += (a.elementi.at(i).at(k) * b.elementi.at(k).at(j)); } c.elementi.at(i).at(j) = clan; clan=0; } } return c; } template <class T> bool operator==(const SimetricnaMatrica<T>&a,const SimetricnaMatrica<T>&b) { if(a.elementi.size() != b.elementi.size()) return false; for(int i=0;i<a.elementi.size();i++) { for(int j=0;j<a.elementi.at(i).size();j++) { if(a.elementi.at(i).at(j) != b.elementi.at(i).at(j)) return false; } } return true; } template <class T> bool operator!=(const SimetricnaMatrica<T>&a,const SimetricnaMatrica<T>&b) { return !(a==b); } template <class T> std::ostream& operator<<(std::ostream& izlaz, const SimetricnaMatrica<T>& sm) { int inputWidth = izlaz.width(); for(int i=0;i<sm.elementi.size();++i) { for(int j=0;j<sm.elementi.size();++j) { if(j < sm.elementi.at(i).size()) izlaz << std::setw(inputWidth) << sm.elementi.at(i).at(j); else izlaz << std::setw(inputWidth) << sm.elementi.at(j).at(i); } izlaz << std::endl; } return izlaz; } template <class T> std::istream& operator>>(std::istream& ulaz,SimetricnaMatrica<T>& sm) { int limit(1); for(int i=0;i<sm.elementi.size();++i) { for(int j=0;j<limit;++j) { ulaz >> sm.elementi.at(i).at(j); } limit++; } return ulaz; } int main () { {//op+ i op-, trivijalan SimetricnaMatrica<int> m1 ({{1}, {3, 4}}); SimetricnaMatrica<int> m2 ({{8}, {6, 5}}); std::cout << std::setw(3) << m1 + m2; std::cout << std::setw(3) << m1 - m2; } // SimetricnaMatrica<int> sm({{1},{1,2},{1,2,3}}); // SimetricnaMatrica<int> sm2({{20},{20,30},{30,40,50}}); // SimetricnaMatrica<int> zbir(3); // zbir = sm + sm2; // std::cout << std::setw(5) << zbir; // SimetricnaMatrica<int> razlika(3); // razlika = sm - sm2; // std::cout << std::setw(5) << razlika; // SimetricnaMatrica<int> razlike = sm - sm2; // std::cout << std::setw(15) << sm + sm2; // std::initializer_list<std::initializer_list<int>> l = {{1}, {0, 7}, {0, 0, -1}, {0, 0, 0, 17}}; // std::vector<std::vector<int>> v = {{17}, {0, -3}, {0, 0, -7}, {0, 0, 0, 12}}; // SimetricnaMatrica<int> A {l}; // SimetricnaMatrica<int> B (v); // auto AB = A * B, BA = B * A; // std::cout << "AB:" << std::endl << std::setw(10) << AB << std::endl // << std::endl << "BA:" << std::endl << std::left << std::setw (12) << BA; return 0; }
[ "almir.mulalic.am@gmail.com" ]
almir.mulalic.am@gmail.com
0426fbabea136cb728ce8efd2dd68111832669b1
cde72953df2205c2322aac3debf058bb31d4f5b9
/win10.19042/SysWOW64/vm3dum_loader.dll.cpp
5374b819a822a871a3dcd5573ee25026be1bf4b1
[]
no_license
v4nyl/dll-exports
928355082725fbb6fcff47cd3ad83b7390c60c5a
4ec04e0c8f713f6e9a61059d5d87abc5c7db16cf
refs/heads/main
2023-03-30T13:49:47.617341
2021-04-10T20:01:34
2021-04-10T20:01:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
282
cpp
#print comment(linker, "/export:OpenAdapter=\"C:\\Windows\\SysWOW64\\vm3dum_loader.dll\"") #print comment(linker, "/export:OpenAdapter10=\"C:\\Windows\\SysWOW64\\vm3dum_loader.dll\"") #print comment(linker, "/export:OpenAdapter10_2=\"C:\\Windows\\SysWOW64\\vm3dum_loader.dll\"")
[ "magnus@stubman.eu" ]
magnus@stubman.eu
3184d796196ccd02e53064090a3ce05a101866a0
fab3558facbc6d6f5f9ffba1d99d33963914027f
/include/fcppt/math/math.hpp
20dde03dd3f7b957764eacd4b623077a152d0796
[]
no_license
pmiddend/sgedoxy
315aa941979a26c6f840c6ce6b3765c78613593b
00b8a4aaf97c2c927a008929fb4892a1729853d7
refs/heads/master
2021-01-20T04:32:43.027585
2011-10-28T17:30:23
2011-10-28T17:30:23
2,666,694
0
0
null
null
null
null
UTF-8
C++
false
false
1,777
hpp
// Copyright Carl Philipp Reh 2009 - 2011. // 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) #ifndef FCPPT_MATH_MATH_HPP_INCLUDED #define FCPPT_MATH_MATH_HPP_INCLUDED #include <fcppt/math/almost_zero.hpp> #include <fcppt/math/ceil_div.hpp> #include <fcppt/math/clamp.hpp> #include <fcppt/math/compare.hpp> #include <fcppt/math/deg_to_rad.hpp> #include <fcppt/math/diff.hpp> #include <fcppt/math/difference_type.hpp> #include <fcppt/math/exception.hpp> #include <fcppt/math/generate_binary_vectors.hpp> #include <fcppt/math/instantiate_arithmetic.hpp> #include <fcppt/math/inverse.hpp> #include <fcppt/math/is_dynamic_size.hpp> #include <fcppt/math/is_negative.hpp> #include <fcppt/math/is_power_of_2.hpp> #include <fcppt/math/is_rational.hpp> #include <fcppt/math/is_static_size.hpp> #include <fcppt/math/log.hpp> #include <fcppt/math/machine_epsilon.hpp> #include <fcppt/math/mod.hpp> #include <fcppt/math/mod_assign.hpp> #include <fcppt/math/nearly_equals.hpp> #include <fcppt/math/next_pow_2.hpp> #include <fcppt/math/null.hpp> #include <fcppt/math/pi.hpp> #include <fcppt/math/point_rotate.hpp> #include <fcppt/math/quad.hpp> #include <fcppt/math/rad_to_deg.hpp> #include <fcppt/math/range_compare.hpp> #include <fcppt/math/round_div_int.hpp> #include <fcppt/math/signum.hpp> #include <fcppt/math/size_type.hpp> #include <fcppt/math/twopi.hpp> #include <fcppt/math/box/box.hpp> #include <fcppt/math/dim/dim.hpp> #include <fcppt/math/interpolation/interpolation.hpp> #include <fcppt/math/matrix/matrix.hpp> #include <fcppt/math/quaternion/quaternion.hpp> #include <fcppt/math/sphere/sphere.hpp> #include <fcppt/math/vector/vector.hpp> #endif
[ "pmidden@gmx.net" ]
pmidden@gmx.net
d1bab2365eb0f49b47b8bea367c7d6842c71e1bd
8061b2e9327cd3e2b8e2d5e643889a62336228ef
/src/main/cpp/Modules/Robot/SwerveRobot/SimulatedOdometry.cpp
617e4794e0fcec6f731e514752ba81b916ededb4
[]
no_license
JamesTerm/Swerve2021
f6990a1cdcf9454c7ef74fef1af56e35435bc741
b189eacf77d6579cfe8756d2e15869f06bea7a5b
refs/heads/main
2023-03-11T12:21:31.599781
2021-03-03T03:51:46
2021-03-03T03:51:46
329,052,148
0
0
null
null
null
null
UTF-8
C++
false
false
83,050
cpp
#pragma region _includes_ //The usual include stuff #include "stdafx.h" #include <future> #include <chrono> #include <iostream> #include <math.h> #include <assert.h> #include <algorithm> #include "../../../Base/Base_Includes.h" #include "../../../Base/Vec2d.h" #include "../../../Base/Misc.h" #include "../../../Base/PIDController.h" #include "../DriveKinematics/Vehicle_Drive.h" #include "../../../Properties/RegistryV1.h" #include "SimulatedOdometry.h" #include "RotaryProperties_Legacy.h" //Note __UseBypass__ is replaced by a properties driven asset //TODO //Get simulator 3 working //Tweak properties for ideal ride in the example script //Ensure pot simulator is unlimited //Keep around if the new simulation has issues //#define __UseLegacySimulation__ #pragma endregion namespace Module { namespace Robot { #pragma region _Legacy CalibrationTesting_ //I do not want to use any legacy code for the new simulation //TODO put macro back once everything is working properly #ifdef __UseLegacySimulation__ namespace Legacy { //Note: This section really belongs with the simulated odometry; however, given the legacy dependency on ship 1D and properties //it is cleaner to keep the code intact in the order of dependencies, and rewrite a better updated simulation there #pragma region _CT constants_ const double c_OptimalAngleUp_r = DEG_2_RAD(70.0); const double c_OptimalAngleDn_r = DEG_2_RAD(50.0); const double c_ArmToGearRatio = 72.0 / 28.0; const double c_GearToArmRatio = 1.0 / c_ArmToGearRatio; //const double c_PotentiometerToGearRatio=60.0/32.0; //const double c_PotentiometerToArmRatio=c_PotentiometerToGearRatio * c_GearToArmRatio; const double c_PotentiometerToArmRatio = 36.0 / 54.0; const double c_PotentiometerToGearRatio = c_PotentiometerToArmRatio * c_ArmToGearRatio; const double c_ArmToPotentiometerRatio = 1.0 / c_PotentiometerToArmRatio; const double c_GearToPotentiometer = 1.0 / c_PotentiometerToGearRatio; //const double c_TestRate=3.0; //const double c_TestRate=6.0; //const double c_Potentiometer_TestRate=18.0; const double c_Potentiometer_TestRate = 24.0; //const double c_Potentiometer_TestRate=48.0; const double Polynomial[5] = { 0.0,1.0 ,0.0 ,0.0 ,0.0 //0.0,2.4878,-2.2091,0.7134,0.0 }; const double c_DeadZone = 0.085; const double c_MidRangeZone = .150; const double c_MidDistance = c_MidRangeZone - c_DeadZone; const double c_rMidDistance = 1.0 / c_MidDistance; const double c_EndDistance = 1.0 - c_MidRangeZone; const double c_rEndDistance = 1.0 / c_EndDistance; #define ENCODER_TEST_RATE 1 #if ENCODER_TEST_RATE==0 const double c_Encoder_TestRate = 16.0; const double c_Encoder_MaxAccel = 120.0; #endif #if ENCODER_TEST_RATE==1 const double c_Encoder_TestRate = 2.916; const double c_Encoder_MaxAccel = 60.0; #endif #if ENCODER_TEST_RATE==2 const double c_Encoder_TestRate = 2.4; const double c_Encoder_MaxAccel = 4.0; #endif #if ENCODER_TEST_RATE==3 const double c_Encoder_TestRate = 1.1; const double c_Encoder_MaxAccel = 2.0; #endif const double c_OunceInchToNewton = 0.00706155183333; const double c_CIM_Amp_To_Torque_oz = (1.0 / (133.0 - 2.7)) * 343.3; const double c_CIM_Amp_To_Torque_nm = c_CIM_Amp_To_Torque_oz * c_OunceInchToNewton; const double c_CIM_Vel_To_Torque_oz = (1.0 / (5310 / 60.0)) * 343.4; const double c_CIM_Vel_To_Torque_nm = c_CIM_Vel_To_Torque_oz * c_OunceInchToNewton; const double c_CIM_Torque_to_Vel_nm = 1.0 / c_CIM_Vel_To_Torque_nm; #define __USE_PAYLOAD_MASS__ #pragma endregion #pragma region _helper functions_ double GetTweakedVoltage(double Voltage) { double VoltMag = fabs(Voltage); double sign = Voltage / VoltMag; //simulate stresses on the robot if (VoltMag > 0.0) { if (VoltMag < c_DeadZone) { //DebugOutput("Buzz %f\n", Voltage); //simulate no movement but hearing the motor VoltMag = 0.0; } else if (VoltMag < c_MidRangeZone) VoltMag = (VoltMag - c_DeadZone) * c_rMidDistance * 0.5; else VoltMag = ((VoltMag - c_MidRangeZone) * c_rEndDistance * 0.5) + 0.5; Voltage = VoltMag * sign; } return Voltage; } //Not used #if 0 static double AngleToHeight_m(double Angle_r) { //TODO fix const double c_ArmToGearRatio = 72.0 / 28.0; const double c_GearToArmRatio = 1.0 / c_ArmToGearRatio; const double c_ArmLength_m = 1.8288; //6 feet const double c_GearHeightOffset = 1.397; //55 inches return (sin(Angle_r * c_GearToArmRatio) * c_ArmLength_m) + c_GearHeightOffset; } #endif #pragma endregion class COMMON_API Potentiometer_Tester : public Ship_1D { private: double m_Time_s=0.0; Ship_1D_Properties m_PotentiometerProps; //GG_Framework::Base::EventMap m_DummyMap; bool m_Bypass; //used for stress test public: Potentiometer_Tester() : m_PotentiometerProps( "Potentiometer", 2.0, //Mass 0.0, //Dimension (this really does not matter for this, there is currently no functionality for this property, although it could impact limits) c_Potentiometer_TestRate, //Max Speed 1.0, 1.0, //ACCEL, BRAKE (These can be ignored) c_Potentiometer_TestRate, c_Potentiometer_TestRate, //Ship_1D_Props::eRobotArm, true, //Using the range DEG_2_RAD(-135.0), DEG_2_RAD(135.0) ), Ship_1D("Potentiometer") { m_Bypass = false; Initialize(&m_PotentiometerProps); } void UpdatePotentiometerVoltage(double Voltage) { Voltage = GetTweakedVoltage(Voltage); if (!m_Bypass) SetRequestedVelocity(Voltage * c_GearToPotentiometer * m_PotentiometerProps.GetMaxSpeed()); else SetRequestedVelocity(0.0); } virtual double GetPotentiometerCurrentPosition() { //Note this is in native potentiometer ratios double Pos_m = GetPos_m(); //double height = AngleToHeight_m(Pos_m); //not used... for reference //DOUT5("Pot=%f Angle=%f %fft %fin",m_Physics.GetVelocity(),RAD_2_DEG(Pos_m*c_GearToArmRatio),height*3.2808399,height*39.3700787); return Pos_m; } //This is broken up so that the real interface does not have to pass time void SetTimeDelta(double dTime_s) {m_Time_s=dTime_s;} void TimeChange() { Ship_1D::TimeChange(m_Time_s); } void SetBypass(bool bypass) {m_Bypass=bypass;} }; class COMMON_API Potentiometer_Tester2 : public Ship_1D { private: void SimulateOpposingForce(double Voltage) { const double OuterDistance = 3.8; const double CoreDistance = 4.0; const double Pos = GetPos_m(); const double Velocity = m_Physics.GetVelocity(); double ForceScaler = 0.0; if ((Pos > OuterDistance) && (Velocity >= 0.0)) { //determine how much force is being applied const double Force = m_Physics.GetForceFromVelocity(Velocity + Velocity, m_Time_s); if (Pos < CoreDistance) { //dampen force depending on the current distance const double scale = 1.0 / (CoreDistance - OuterDistance); ForceScaler = (Pos - OuterDistance) * scale; } else ForceScaler = 1.0; m_Physics.ApplyFractionalForce(-Force * ForceScaler, m_Time_s); } SetRequestedVelocity(Voltage * (1.0 - ForceScaler) * m_PotentiometerProps.GetMaxSpeed()); } double m_Time_s=0.0; Ship_1D_Properties m_PotentiometerProps; //GG_Framework::Base::EventMap m_DummyMap; bool m_SimulateOpposingForce; //used for stress test public: Potentiometer_Tester2() : m_PotentiometerProps( "Potentiometer2", 2.0, //Mass 0.0, //Dimension (this really does not matter for this, there is currently no functionality for this property, although it could impact limits) 10.0, //Max Speed 1.0, 1.0, //ACCEL, BRAKE (These can be ignored) 10.0, 10.0, //Ship_1D_Props::eSwivel, true, //Using the range DEG_2_RAD(-180.0), DEG_2_RAD(180.0) ), Ship_1D("Potentiometer2") { m_SimulateOpposingForce = false; } virtual void Init_Ship_1D(const Ship_1D_Properties* props = NULL) { if (props) m_PotentiometerProps = *props; Ship_1D::Initialize(&m_PotentiometerProps); } virtual void Initialize(size_t index, const Framework::Base::asset_manager* props = NULL) { #pragma region _setup get vars_ double ftest = 0.0; //use to test if an asset exists #define GET_NUMBER(x,y) \ constructed_name = prefix, constructed_name += csz_##x; \ y = props->get_number(constructed_name.c_str(), y); #define GET_BOOL(x,y) \ constructed_name = prefix, constructed_name += csz_##x; \ y = props->get_bool(constructed_name.c_str(), y); using namespace properties::registry_v1; std::string constructed_name; const char * const prefix = csz_CommonSwivel_; #pragma endregion //just pull the ship props from the asset manager Ship_1D_Properties props_to_send; #pragma region _Entity1D_ //entity 1D Entity1D_Props& e1d = props_to_send.AsEntityProps(); //constructed_name = prefix, constructed_name += csz_Entity1D_StartingPosition; //e1d.m_StartingPosition = asset_properties->get_number(constructed_name.c_str(), e1d.m_StartingPosition); GET_NUMBER(Entity1D_StartingPosition, e1d.m_StartingPosition); GET_NUMBER(Entity1D_Mass, e1d.m_Mass); GET_NUMBER(Entity1D_Dimension, e1d.m_Dimension); GET_BOOL(Entity1D_IsAngular,e1d.m_IsAngular); #pragma endregion #pragma region _Ship1D_ Ship_1D_Props& _Ship_1D = props_to_send.GetShip_1D_Props_rw(); GET_NUMBER(Ship_1D_MAX_SPEED, _Ship_1D.MAX_SPEED); //IF we have this asset assign it to forward and reverse if (props->get_number_native(constructed_name.c_str(), ftest)) { _Ship_1D.MaxSpeed_Forward = _Ship_1D.MAX_SPEED; _Ship_1D.MaxSpeed_Reverse = -_Ship_1D.MAX_SPEED; } GET_NUMBER(Ship_1D_MaxSpeed_Forward, _Ship_1D.MaxSpeed_Forward); GET_NUMBER(Ship_1D_MaxSpeed_Reverse, _Ship_1D.MaxSpeed_Reverse); GET_NUMBER(Ship_1D_ACCEL, _Ship_1D.ACCEL); GET_NUMBER(Ship_1D_BRAKE, _Ship_1D.BRAKE); //I don't do this often but there may be an easier way to handle this, try the simulation one first //if none then use MaxAccelForward constructed_name = prefix, constructed_name += csz_Ship_1D_MaxAccel_simulation; std::string name2 = prefix; name2 += csz_Ship_1D_MaxAccelForward; _Ship_1D.MaxAccelForward = props->get_number(constructed_name.c_str(), props->get_number(name2.c_str(), _Ship_1D.MaxAccelForward)); //if I don't have reverse use forward here for default //GET_NUMBER(Ship_1D_MaxAccelReverse, _Ship_1D.MaxAccelForward); constructed_name = prefix, constructed_name += csz_Ship_1D_MaxAccelReverse; _Ship_1D.MaxAccelReverse = props->get_number(constructed_name.c_str(), _Ship_1D.MaxAccelForward); GET_NUMBER(Ship_1D_MinRange, _Ship_1D.MinRange); GET_NUMBER(Ship_1D_MaxRange, _Ship_1D.MaxRange); GET_NUMBER(Ship_1D_DistanceDegradeScaler, _Ship_1D.DistanceDegradeScaler); GET_BOOL(Ship_1D_UsingRange, _Ship_1D.UsingRange) //bool #pragma endregion //finished with macros #undef GET_NUMBER #undef GET_BOOL //send these props Init_Ship_1D(&props_to_send); } void UpdatePotentiometerVoltage(double Voltage) { //Voltage=GetTweakedVoltage(Voltage); if (!m_SimulateOpposingForce) SetRequestedVelocity(Voltage * m_PotentiometerProps.GetMaxSpeed()); else SimulateOpposingForce(Voltage); } virtual double GetPotentiometerCurrentPosition() { //Note this is in native potentiometer ratios double Pos_m = GetPos_m(); return Pos_m; } //This is broken up so that the real interface does not have to pass time void SetTimeDelta(double dTime_s) {m_Time_s=dTime_s;} void TimeChange() { Ship_1D::TimeChange(m_Time_s); } void SetSimulateOpposingForce(bool Simulate) {m_SimulateOpposingForce=Simulate;} }; class COMMON_API Encoder_Simulator : public Ship_1D { private: double m_Time_s; Ship_1D_Properties m_EncoderProps; //GG_Framework::Base::EventMap m_DummyMap; Framework::Base::LatencyFilter m_Latency; double m_EncoderScaler; //used to implement reverse bool m_GetEncoderFirstCall; //allows GetEncoderVelocity to know when a new set of calls occur within a time slice public: Encoder_Simulator(const char *EntityName="EncSimulator") : m_Time_s(0.0), m_EncoderProps( EntityName, 68.0, //Mass 0.0, //Dimension (this really does not matter for this, there is currently no functionality for this property, although it could impact limits) c_Encoder_TestRate, //Max Speed 1.0, 1.0, //ACCEL, BRAKE (These can be ignored) c_Encoder_MaxAccel, c_Encoder_MaxAccel, //Ship_1D_Props::eRobotArm, false //Not using the range ), Ship_1D(EntityName), m_Latency(0.300), m_EncoderScaler(1.0), m_GetEncoderFirstCall(false) { } virtual void Initialize(const Ship_1D_Properties* props = NULL) { if (props) m_EncoderProps = *props; Ship_1D::Initialize(&m_EncoderProps); } void UpdateEncoderVoltage(double Voltage) { //Here is some stress to emulate a bad curved victor #if 0 //This is how it would be if the motor was set to non-coast double VoltageMag = pow(fabs(Voltage), 0.5); Voltage = (Voltage > 0.0) ? VoltageMag : -VoltageMag; #endif SetRequestedVelocity(Voltage * m_EncoderProps.GetMaxSpeed()); #if 0 //For coast it is more like applying force double Velocity = m_Physics.GetVelocity(); double MaxSpeed = m_EncoderProps.GetMaxSpeed(); double Accel = Voltage * 5000.0 * MaxSpeed * m_Time_s; //determine current acceleration by applying the ratio with a scaler double filter = 1.0 - (fabs(Velocity) / MaxSpeed); //as there is more speed there is less torque //double friction=((Velocity>0.04)?-0.025 : (Velocity<-0.04)?+0.025 : 0.0 )* rTime ; //There is a constant amount of friction opposite to current velocity double friction = ((Velocity > 0.04) ? -250 : (Velocity < -0.04) ? +250 : 0.0) * m_Time_s; //There is a constant amount of friction opposite to current velocity SetCurrentLinearAcceleration((Accel * filter * filter) + friction); //square the filter (matches read out better) #endif } virtual double GetEncoderVelocity() { #if 0 return m_Physics.GetVelocity() * m_EncoderScaler; #else //if (!m_GetEncoderFirstCall) return m_Latency(); double Voltage = m_Physics.GetVelocity() / m_EncoderProps.GetMaxSpeed(); double Direction = Voltage < 0 ? -1.0 : 1.0; Voltage = fabs(Voltage); //make positive //Apply the victor curve //Apply the polynomial equation to the voltage to linearize the curve { const double* c = Polynomial; double x2 = Voltage * Voltage; double x3 = Voltage * x2; double x4 = x2 * x2; Voltage = (c[4] * x4) + (c[3] * x3) + (c[2] * x2) + (c[1] * Voltage) + c[0]; Voltage *= Direction; } double ret = Voltage * m_EncoderProps.GetMaxSpeed() * m_EncoderScaler; //ret=m_Latency(ret,m_Time_s); m_GetEncoderFirstCall = false; //weed out the repeat calls return ret; #endif } //This is broken up so that the real interface does not have to pass time void SetTimeDelta(double dTime_s) {m_Time_s=dTime_s;} void TimeChange() { m_GetEncoderFirstCall = true; Ship_1D::TimeChange(m_Time_s); } void SetReverseDirection(bool reverseDirection) { //emulates functionality of the encoder (needed because kids put them in differently) m_EncoderScaler = reverseDirection ? -1.0 : 1.0; } void SetEncoderScaler(double value) {m_EncoderScaler=value;} //This helps to simulate differences between sides void SetFriction(double StaticFriction,double KineticFriction) {} }; //TorqueAccelerationDampener - formerly known as ForceAppliedOnWheelRadius has become the solution to account for empirical testing of torque acceleration //measured in the motor, unfortunately I haven't yet found a way to compute for this, but this is quite effective as its factoring happens in the best //place (same place as it was before) struct EncoderSimulation_Props { double Wheel_Mass; //This is a total mass of all the wheels and gears for one side double COF_Efficiency; double GearReduction; //In reciprocal form of spread sheet driving gear / driven gear double TorqueAccelerationDampener; //ratio 1.0 no change double DriveWheelRadius; //in meters double NoMotors; //Used to get total torque double PayloadMass; //The robot weight in kg double SpeedLossConstant; double DriveTrainEfficiency; struct Motor_Specs { double FreeSpeed_RPM; double Stall_Torque_NM; double Stall_Current_Amp; double Free_Current_Amp; } motor; }; //This is used in calibration testing to simulate encoder readings class COMMON_API EncoderSimulation_Properties { public: EncoderSimulation_Properties() { EncoderSimulation_Props props; memset(&props, 0, sizeof(EncoderSimulation_Props)); props.Wheel_Mass = 1.5; props.COF_Efficiency = 1.0; props.GearReduction = 12.4158; props.TorqueAccelerationDampener = 0.0508; props.DriveWheelRadius = 0.0762; props.NoMotors = 1.0; props.PayloadMass = 200.0 * 0.453592; //in kilograms props.SpeedLossConstant = 0.81; props.DriveTrainEfficiency = 0.9; props.motor.FreeSpeed_RPM = 5310; props.motor.Stall_Torque_NM = 343.4 * c_OunceInchToNewton; props.motor.Stall_Current_Amp = 133.0; props.motor.Free_Current_Amp = 2.7; m_EncoderSimulation_Props = props; } //virtual void LoadFromScript(GG_Framework::Logic::Scripting::Script& script); const EncoderSimulation_Props &GetEncoderSimulationProps() const {return m_EncoderSimulation_Props;} //Get and Set the properties EncoderSimulation_Props &EncoderSimulationProps() {return m_EncoderSimulation_Props;} protected: EncoderSimulation_Props m_EncoderSimulation_Props; }; class COMMON_API Drive_Train_Characteristics { public: Drive_Train_Characteristics() { EncoderSimulation_Properties default_props; m_Props = default_props.GetEncoderSimulationProps(); } void UpdateProps(const EncoderSimulation_Props &props) {m_Props=props;} void UpdateProps(const Framework::Base::asset_manager* props = NULL) { if (!props) return; using namespace ::properties::registry_v1; #define GET_NUMBER(x,y) \ y = props->get_number(csz_##x, y); GET_NUMBER(EncoderSimulation_Wheel_Mass,m_Props.Wheel_Mass); GET_NUMBER(EncoderSimulation_COF_Efficiency, m_Props.COF_Efficiency); GET_NUMBER(EncoderSimulation_GearReduction, m_Props.GearReduction); GET_NUMBER(EncoderSimulation_TorqueAccelerationDampener, m_Props.TorqueAccelerationDampener); GET_NUMBER(EncoderSimulation_DriveWheelRadius, m_Props.DriveWheelRadius); GET_NUMBER(EncoderSimulation_NoMotors, m_Props.NoMotors); GET_NUMBER(EncoderSimulation_PayloadMass, m_Props.PayloadMass); GET_NUMBER(EncoderSimulation_SpeedLossConstant, m_Props.SpeedLossConstant); GET_NUMBER(EncoderSimulation_DriveTrainEfficiency, m_Props.DriveTrainEfficiency); // struct Motor_Specs EncoderSimulation_Props::Motor_Specs& motor = m_Props.motor; GET_NUMBER(EncoderSimulation_FreeSpeed_RPM, motor.FreeSpeed_RPM); GET_NUMBER(EncoderSimulation_Stall_Torque_NM, motor.Stall_Torque_NM); GET_NUMBER(EncoderSimulation_Stall_Current_Amp, motor.Stall_Current_Amp); GET_NUMBER(EncoderSimulation_Free_Current_Amp, motor.Free_Current_Amp); #undef GET_NUMBER } __inline double GetAmp_To_Torque_nm(double Amps) const { const EncoderSimulation_Props::Motor_Specs& _ = m_Props.motor; const double c_Amp_To_Torque_nm = (1.0 / (_.Stall_Current_Amp - _.Free_Current_Amp)) * _.Stall_Torque_NM; return std::max((Amps - _.Free_Current_Amp) * c_Amp_To_Torque_nm, 0.0); } __inline double INV_GetVel_To_Torque_nm(double Vel_rps) const { //depreciated const EncoderSimulation_Props::Motor_Specs& _ = m_Props.motor; const double c_Vel_To_Torque_nm = (1.0 / (_.FreeSpeed_RPM / 60.0)) * _.Stall_Torque_NM; return (Vel_rps * c_Vel_To_Torque_nm); } __inline double GetVel_To_Torque_nm(double motor_Vel_rps) const { const EncoderSimulation_Props::Motor_Specs& _ = m_Props.motor; const double FreeSpeed_RPS = (_.FreeSpeed_RPM / 60.0); //ensure we don't exceed the max velocity const double x = std::min(fabs(motor_Vel_rps) / FreeSpeed_RPS, 1.0); //working with normalized positive number for inversion const double Torque_nm((1.0 - x) * _.Stall_Torque_NM); return (motor_Vel_rps >= 0) ? Torque_nm : -Torque_nm; } __inline double GetTorque_To_Vel_nm_V1(double motor_Vel_rps) const { //depreciated return 0.0; } __inline double GetWheelTorque(double Torque) const { return Torque / m_Props.GearReduction * m_Props.DriveTrainEfficiency; } __inline double INV_GetWheelTorque(double Torque) const { //depreciated return Torque * m_Props.GearReduction * m_Props.COF_Efficiency; } __inline double GetWheelStallTorque() const { return m_Props.motor.Stall_Torque_NM / m_Props.GearReduction * m_Props.DriveTrainEfficiency; } __inline double GetTorqueAtWheel(double Torque) const { return (GetWheelTorque(Torque) / m_Props.DriveWheelRadius); } __inline double GetWheelRPS(double LinearVelocity) const { return LinearVelocity / (M_PI * 2.0 * m_Props.DriveWheelRadius); } __inline double GetLinearVelocity(double wheel_RPS) const { return wheel_RPS * (M_PI * 2.0 * m_Props.DriveWheelRadius); } __inline double GetLinearVelocity_WheelAngular(double wheel_AngularVelocity) const { return wheel_AngularVelocity * m_Props.DriveWheelRadius; } __inline double GetMotorRPS(double LinearVelocity) const { return GetWheelRPS(LinearVelocity) / m_Props.GearReduction; } __inline double GetWheelRPS_Angular(double wheel_AngularVelocity) const { return wheel_AngularVelocity / (M_PI * 2.0); } __inline double GetWheelAngular_RPS(double wheel_RPS) const { return wheel_RPS * (M_PI * 2.0); } __inline double GetWheelAngular_LinearVelocity(double LinearVelocity) const { //accurate as long as there is no skid return LinearVelocity / m_Props.DriveWheelRadius; } __inline double GetMotorRPS_Angular(double wheel_AngularVelocity) const { return GetWheelRPS_Angular(wheel_AngularVelocity) / m_Props.GearReduction; } __inline double INV_GetMotorRPS_Angular(double wheel_AngularVelocity) const { //depreciated return GetWheelRPS_Angular(wheel_AngularVelocity) * m_Props.GearReduction; } __inline double GetTorqueFromLinearVelocity(double LinearVelocity) const { const double MotorTorque = GetVel_To_Torque_nm(GetMotorRPS(LinearVelocity)); return GetTorqueAtWheel(MotorTorque); } __inline double GetWheelTorqueFromVoltage(double Voltage) const { const EncoderSimulation_Props::Motor_Specs& motor = m_Props.motor; const double Amps = fabs(Voltage * motor.Stall_Current_Amp); const double MotorTorque = GetAmp_To_Torque_nm(Amps); const double WheelTorque = GetTorqueAtWheel(MotorTorque * 2.0); return (Voltage > 0) ? WheelTorque : -WheelTorque; //restore sign } __inline double GetTorqueFromVoltage_V1(double Voltage) const { //depreciated const EncoderSimulation_Props::Motor_Specs& motor = m_Props.motor; const double Amps = fabs(Voltage * motor.Stall_Current_Amp); const double MotorTorque = GetAmp_To_Torque_nm(Amps); const double WheelTorque = INV_GetWheelTorque(MotorTorque * m_Props.NoMotors); return (Voltage > 0) ? WheelTorque : -WheelTorque; //restore sign } __inline double GetTorqueFromVoltage(double Voltage) const { const EncoderSimulation_Props::Motor_Specs& motor = m_Props.motor; const double Amps = fabs(Voltage * motor.Stall_Current_Amp); const double MotorTorque = GetAmp_To_Torque_nm(Amps); const double WheelTorque = GetWheelTorque(MotorTorque * m_Props.NoMotors); return (Voltage > 0) ? WheelTorque : -WheelTorque; //restore sign } __inline double INV_GetTorqueFromVelocity(double wheel_AngularVelocity) const { //depreciated const double MotorTorque_nm = INV_GetVel_To_Torque_nm(INV_GetMotorRPS_Angular(wheel_AngularVelocity)); return INV_GetWheelTorque(MotorTorque_nm * m_Props.NoMotors); } __inline double GetTorqueFromVelocity(double wheel_AngularVelocity) const { const double MotorTorque_nm = GetVel_To_Torque_nm(GetMotorRPS_Angular(wheel_AngularVelocity)); return GetWheelTorque(MotorTorque_nm * m_Props.NoMotors); } __inline double GetMaxTraction() const {return m_Props.PayloadMass*m_Props.COF_Efficiency;} __inline double GetMaxDriveForce() const {return GetWheelStallTorque()/m_Props.DriveWheelRadius*2.0;} __inline double GetCurrentDriveForce(double WheelTorque) const {return WheelTorque/m_Props.DriveWheelRadius*2.0;} __inline double GetMaxPushingForce() const { return std::min(GetMaxTraction()*9.80665,GetMaxDriveForce());} const EncoderSimulation_Props &GetDriveTrainProps() const {return m_Props;} void SetGearReduction(double NewGearing) {m_Props.GearReduction=NewGearing;} private: EncoderSimulation_Props m_Props; }; class COMMON_API Encoder_Simulator2 { protected: //The wheel physics records the velocity of the wheel in radians Framework::Base::PhysicsEntity_1D m_Physics; Drive_Train_Characteristics m_DriveTrain; double m_Time_s; double m_Position; //also keep track of position to simulate distance use case (i.e. used as a potentiometer) double m_EncoderScaler; //used for position updates double m_ReverseMultiply; //used to implement set reverse direction public: Encoder_Simulator2(const char* EntityName = "EncSimulator") : m_Time_s(0.0), m_EncoderScaler(1.0), m_ReverseMultiply(1.0), m_Position(0.0) { } virtual void Initialize(const Framework::Base::asset_manager *props = NULL) { //const Rotary_Properties* rotary_props = dynamic_cast<const Rotary_Properties*>(props); //if (rotary_props) //{ //m_DriveTrain.UpdateProps(rotary_props->GetEncoderSimulationProps()); // m_EncoderScaler = rotary_props->GetRotaryProps().EncoderToRS_Ratio; //} m_DriveTrain.UpdateProps(props); if (props) m_EncoderScaler = props->get_number(properties::registry_v1::csz_EncoderSimulation_EncoderScaler, 1.0); #if 0 //m_Physics.SetMass(68); //(about 150 pounds) m_Physics.SetMass(50); //adjust this to match latency we observe m_Physics.SetFriction(0.8, 0.08); #else m_Physics.SetMass(m_DriveTrain.GetDriveTrainProps().Wheel_Mass); m_Physics.SetFriction(0.8, 0.2); m_Physics.SetRadiusOfConcentratedMass(m_DriveTrain.GetDriveTrainProps().DriveWheelRadius); #endif } virtual void UpdateEncoderVoltage(double Voltage) { double Direction=Voltage<0 ? -1.0 : 1.0; Voltage=fabs(Voltage); //make positive //Apply the polynomial equation to the voltage to linearize the curve { const double *c=Polynomial; double x2=Voltage*Voltage; double x3=Voltage*x2; double x4=x2*x2; Voltage = (c[4]*x4) + (c[3]*x3) + (c[2]*x2) + (c[1]*Voltage) + c[0]; Voltage *= Direction; } //From this point it is a percentage (hopefully linear distribution after applying the curve) of the max force to apply... This can be //computed from stall torque ratings of motor with various gear reductions and so forth //on JVN's spread sheet torque at wheel is (WST / DWR) * 2 (for nm) (Wheel stall torque / Drive Wheel Radius * 2 sides) //where stall torque is ST / GearReduction * DriveTrain efficiency //This is all computed in the drive train #if 0 double ForceToApply=m_DriveTrain.GetWheelTorqueFromVoltage(Voltage); const double ForceAbsorbed=m_DriveTrain.GetWheelTorqueFromVelocity(m_Physics.GetVelocity()); ForceToApply-=ForceAbsorbed; m_Physics.ApplyFractionalForce(ForceToApply,m_Time_s); #else double TorqueToApply=m_DriveTrain.GetTorqueFromVoltage_V1(Voltage); const double TorqueAbsorbed=m_DriveTrain.INV_GetTorqueFromVelocity(m_Physics.GetVelocity()); TorqueToApply-=TorqueAbsorbed; m_Physics.ApplyFractionalTorque_depreciated(TorqueToApply,m_Time_s,m_DriveTrain.GetDriveTrainProps().TorqueAccelerationDampener); #endif } virtual double GetEncoderVelocity() const { #if 0 static size_t i = 0; double Velocity = m_Physics.GetVelocity(); if (((i++ % 50) == 0) && (Velocity != 0.0)) printf("Velocty=%f\n", Velocity * m_DriveTrain.GetDriveTrainProps().DriveWheelRadius); return 0.0; #else //return m_Physics.GetVelocity(); return m_Physics.GetVelocity() * m_DriveTrain.GetDriveTrainProps().DriveWheelRadius * m_ReverseMultiply; #endif } double GetDistance() const { return m_Position; } //This is broken up so that the real interface does not have to pass time void SetTimeDelta(double dTime_s) {m_Time_s=dTime_s;} virtual void TimeChange() { //m_GetEncoderFirstCall=true; const double Ground = 0.0; //ground in radians double FrictionForce = m_Physics.GetFrictionalForce(m_Time_s, Ground); m_Physics.ApplyFractionalForce(FrictionForce, m_Time_s); //apply the friction double PositionDisplacement; m_Physics.TimeChangeUpdate(m_Time_s, PositionDisplacement); m_Position += PositionDisplacement * m_EncoderScaler * m_ReverseMultiply; } void SetReverseDirection(bool reverseDirection) { //emulates functionality of the encoder (needed because kids put them in differently) m_ReverseMultiply = reverseDirection ? -1.0 : 1.0; } void SetEncoderScaler(double value) {m_EncoderScaler=value;} //This helps to simulate differences between sides void SetFriction(double StaticFriction,double KineticFriction) {m_Physics.SetFriction(StaticFriction,KineticFriction);} virtual void ResetPos() { m_Physics.ResetVectors(); m_Position = 0; } void SetGearReduction(double NewGearing) {m_DriveTrain.SetGearReduction(NewGearing);} }; class COMMON_API Encoder_Simulator3 : public Encoder_Simulator2 { private: static void TimeChange_UpdatePhysics(double Voltage, Drive_Train_Characteristics dtc,Framework::Base::PhysicsEntity_1D &PayloadPhysics, Framework::Base::PhysicsEntity_1D &WheelPhysics,double Time_s,bool UpdatePayload) { //local function to avoid redundant code const double PayloadVelocity=PayloadPhysics.GetVelocity(); const double WheelVelocity=WheelPhysics.GetVelocity(); double PositionDisplacement; //TODO add speed loss force if (UpdatePayload) { //apply a constant speed loss using new velocity - old velocity if (Voltage==0.0) { const double MaxStop=fabs(PayloadVelocity/Time_s); const double SpeedLoss=std::min(5.0,MaxStop); const double acceleration=PayloadVelocity>0.0?-SpeedLoss:SpeedLoss; //now to factor in the mass const double SpeedLossForce = PayloadPhysics.GetMass() * acceleration; PayloadPhysics.ApplyFractionalTorque(SpeedLossForce,Time_s); } PayloadPhysics.TimeChangeUpdate(Time_s,PositionDisplacement); } #ifdef __USE_PAYLOAD_MASS__ //Now to add force normal against the wheel this is the difference between the payload and the wheel velocity //When the mass is lagging behind it add adverse force against the motor... and if the mass is ahead it will //relieve the motor and make it coast in the same direction //const double acceleration = dtc.GetWheelAngular_RPS(dtc.GetWheelRPS(PayloadVelocity))-WheelVelocity; const double acceleration = dtc.GetWheelAngular_LinearVelocity(PayloadVelocity)-WheelVelocity; if (PayloadVelocity!=0.0) { #if 0 if (UpdatePayload) SmartDashboard::PutNumber("Test",dtc.GetWheelAngular_LinearVelocity(PayloadVelocity)); if (fabs(acceleration)>50) int x=8; #endif //make sure wheel and payload are going in the same direction... if (PayloadVelocity*WheelVelocity >= 0.0) { //now to factor in the mass const double PayloadForce = WheelPhysics.GetMomentofInertia()*(1.0/dtc.GetDriveTrainProps().TorqueAccelerationDampener)* acceleration; WheelPhysics.ApplyFractionalTorque(PayloadForce,Time_s); } //else // printf("skid %.2f\n",acceleration); //if not... we have skidding (unless its some error of applying the force normal) for now let it continue its discourse by simply not applying the payload force //this will make it easy to observe cases when skids can happen, but eventually we should compute the kinetic friction to apply } else WheelPhysics.SetVelocity(0.0); #endif } protected: double m_Voltage; //cache voltage for speed loss assistance //We are pulling a heavy mass this will present more load on the wheel, we can simulate a bench test vs. an actual run by factoring this in static Framework::Base::PhysicsEntity_1D s_PayloadPhysics_Left; static Framework::Base::PhysicsEntity_1D s_PayloadPhysics_Right; //Cache last state to determine if we are accelerating or decelerating static double s_PreviousPayloadVelocity_Left; static double s_PreviousPayloadVelocity_Right; double m_PreviousWheelVelocity; size_t m_EncoderKind; public: //The payload mass is shared among multiple instances per motor, so each instance will need to identify the kind it is //multiple instance can read, but only one write per side. Use ignore and the payload computations will be bypassed enum EncoderKind { eIgnorePayload, //an easy way to make it on the bench eReadOnlyLeft, eReadOnlyRight, eRW_Left, eRW_Right }; Encoder_Simulator3(const char *EntityName="EncSimulator") : Encoder_Simulator2(EntityName), m_EncoderKind(eIgnorePayload), m_PreviousWheelVelocity(0.0) { } //has to be late binding for arrays void SetEncoderKind(EncoderKind kind) { //Comment this out to do bench testing m_EncoderKind = kind; } virtual void Initialize(const Framework::Base::asset_manager *props = NULL) { const double Pounds2Kilograms = 0.453592; const double wheel_mass = 1.5; const double cof_efficiency = 0.9; const double gear_reduction = 1.0; const double torque_on_wheel_radius = Inches2Meters(1.8); const double drive_wheel_radius = Inches2Meters(4.0); const double number_of_motors = 1; const double payload_mass = 200 * Pounds2Kilograms; const double speed_loss_constant = 0.81; const double drive_train_effciency = 0.9; const double free_speed_rpm = 263.88; const double stall_torque = 34; const double stall_current_amp = 84; const double free_current_amp = 0.4; EncoderSimulation_Props defaults_for_sim3 = { wheel_mass, //This is a total mass of all the wheels and gears for one side cof_efficiency, //double COF_Efficiency; gear_reduction, //In reciprocal form of spread sheet driving gear / driven gear torque_on_wheel_radius, //double TorqueAccelerationDampener; //ratio.. where 1.0 is no change drive_wheel_radius, //double DriveWheelRadius; //in meters number_of_motors, //double NoMotors; //Used to get total torque payload_mass, //double PayloadMass; //The robot weight in kg speed_loss_constant, //double SpeedLossConstant; drive_train_effciency, //double DriveTrainEfficiency; //struct Motor_Specs { free_speed_rpm, //double FreeSpeed_RPM; stall_torque, //double Stall_Torque_NM; stall_current_amp, //double Stall_Current_Amp; free_current_amp //double Free_Current_Amp; } }; m_DriveTrain.UpdateProps(defaults_for_sim3); Encoder_Simulator2::Initialize(props); m_Physics.SetAngularInertiaCoefficient(0.5); //Going for solid cylinder //now to setup the payload physics Note: each side pulls half the weight if (m_EncoderKind == eRW_Left) s_PayloadPhysics_Left.SetMass(m_DriveTrain.GetDriveTrainProps().PayloadMass / 2.0); else if (m_EncoderKind == eRW_Right) s_PayloadPhysics_Right.SetMass(m_DriveTrain.GetDriveTrainProps().PayloadMass / 2.0); //TODO see if this is needed //m_PayloadPhysics.SetFriction(0.8,0.2); } virtual void UpdateEncoderVoltage(double Voltage) { m_Voltage = Voltage; //depreciated #if 0 const double Direction = Voltage < 0 ? -1.0 : 1.0; Voltage = fabs(Voltage); //make positive //Apply the victor curve //Apply the polynomial equation to the voltage to linearize the curve { const double* c = Polynomial; double x2 = Voltage * Voltage; double x3 = Voltage * x2; double x4 = x2 * x2; Voltage = (c[4] * x4) + (c[3] * x3) + (c[2] * x2) + (c[1] * Voltage) + c[0]; Voltage *= Direction; } #endif //This is line is somewhat subtle... basically if the voltage is in the same direction as the velocity we use the linear distribution of the curve, when they are in //opposite directions zero gives the stall torque where we need max current to switch directions (same amount as if there is no motion) const double VelocityToUse = m_Physics.GetVelocity() * Voltage > 0 ? m_Physics.GetVelocity() : 0.0; double TorqueToApply = m_DriveTrain.GetTorqueFromVelocity(VelocityToUse); //Avoid ridiculous division and zero it out... besides a motor can't really turn the wheel in the dead zone range, but I'm not going to factor that in yet if ((TorqueToApply != 0.0) && (fabs(TorqueToApply) < m_Physics.GetMass() * 2)) TorqueToApply = 0.0; //Note: Even though TorqueToApply has direction, if it gets saturated to 0 it loses it... ultimately the voltage parameter is sacred to the correct direction //in all cases so we'll convert TorqueToApply to magnitude m_Physics.ApplyFractionalTorque_depreciated(fabs(TorqueToApply) * Voltage, m_Time_s, m_DriveTrain.GetDriveTrainProps().TorqueAccelerationDampener); //Apply the appropriate change in linear velocity to the payload. Note: This is not necessarily torque because of the TorqueAccelerationDampener... the torque //acts as voltage acts to a circuit... it gives the potential but the current doesn't reflect this right away... its the current, or in our case the velocity //change of he wheel itself that determines how much force to apply. const double Wheel_Acceleration = (m_Physics.GetVelocity() - m_PreviousWheelVelocity) / m_Time_s; //Now to reconstruct the torque Ia, where I = cm R^2 /torquedampner const double Wheel_Torque = Wheel_Acceleration * m_Physics.GetMomentofInertia()*(1.0/m_DriveTrain.GetDriveTrainProps().TorqueAccelerationDampener); //Grrr I have to blend this... mostly because of the feedback from the payload... I'll see if there is some way to avoid needing to do this const double smoothing_value = 0.75; const double BlendTorqueToApply = (Wheel_Torque * smoothing_value) + (TorqueToApply * (1.0 - smoothing_value)); //TODO check for case when current drive force is greater than the traction //Compute the pushing force of the mass and apply it just the same if (m_EncoderKind == eRW_Left) { //Testing #if 0 SmartDashboard::PutNumber("Wheel_Torque_Left", Wheel_Torque); SmartDashboard::PutNumber("Motor_Torque_Left", TorqueToApply); #endif s_PayloadPhysics_Left.ApplyFractionalForce(fabs(m_DriveTrain.GetCurrentDriveForce(BlendTorqueToApply)) * Voltage, m_Time_s); } else if (m_EncoderKind == eRW_Right) s_PayloadPhysics_Right.ApplyFractionalForce(fabs(m_DriveTrain.GetCurrentDriveForce(BlendTorqueToApply)) * Voltage, m_Time_s); } virtual double GetEncoderVelocity() const { //we return linear velocity (which is native to the ship) return m_DriveTrain.GetLinearVelocity(m_DriveTrain.GetWheelRPS_Angular(m_Physics.GetVelocity())) * m_ReverseMultiply; } virtual void TimeChange() { //For best results if we locked to the payload we needn't apply a speed loss constant here #ifndef __USE_PAYLOAD_MASS__ //first apply a constant speed loss using new velocity - old velocity //if (fabs(m_Voltage)<0.65) { if ((fabs(m_Physics.GetVelocity()) > 0.01)) { const double acceleration = m_DriveTrain.GetDriveTrainProps().SpeedLossConstant * m_Physics.GetVelocity() - m_Physics.GetVelocity(); //now to factor in the mass const double SpeedLossForce = m_Physics.GetMass() * acceleration; const double VoltageMagnitue = fabs(m_Voltage); m_Physics.ApplyFractionalTorque(SpeedLossForce, m_Time_s, VoltageMagnitue > 0.5 ? (1.0 - VoltageMagnitue) * 0.5 : 0.25); } else m_Physics.SetVelocity(0.0); } #endif double PositionDisplacement; m_Physics.TimeChangeUpdate(m_Time_s, PositionDisplacement); m_Position += PositionDisplacement * m_EncoderScaler * m_ReverseMultiply; //cache velocities m_PreviousWheelVelocity = m_Physics.GetVelocity(); if ((m_EncoderKind == eRW_Left) || (m_EncoderKind == eReadOnlyLeft)) { TimeChange_UpdatePhysics(m_Voltage, m_DriveTrain, s_PayloadPhysics_Left, m_Physics, m_Time_s, m_EncoderKind == eRW_Left); if (m_EncoderKind == eRW_Left) { s_PreviousPayloadVelocity_Left = s_PayloadPhysics_Left.GetVelocity(); //SmartDashboard::PutNumber("PayloadLeft", Meters2Feet(s_PreviousPayloadVelocity_Left)); //SmartDashboard::PutNumber("WheelLeft", Meters2Feet(GetEncoderVelocity())); } } else if ((m_EncoderKind == eRW_Right) || (m_EncoderKind == eReadOnlyRight)) { TimeChange_UpdatePhysics(m_Voltage, m_DriveTrain, s_PayloadPhysics_Right, m_Physics, m_Time_s, m_EncoderKind == eRW_Right); if (m_EncoderKind == eReadOnlyRight) { s_PreviousPayloadVelocity_Right = s_PayloadPhysics_Right.GetVelocity(); //SmartDashboard::PutNumber("PayloadRight", Meters2Feet(s_PreviousPayloadVelocity_Right)); //SmartDashboard::PutNumber("WheelRight", Meters2Feet(GetEncoderVelocity())); } } } virtual void ResetPos() { Encoder_Simulator2::ResetPos(); if (m_EncoderKind == eRW_Left) s_PayloadPhysics_Left.ResetVectors(); if (m_EncoderKind == eRW_Right) s_PayloadPhysics_Right.ResetVectors(); } }; #pragma region _Encoder simulator 3 global variables_ Framework::Base::PhysicsEntity_1D Encoder_Simulator3::s_PayloadPhysics_Left; Framework::Base::PhysicsEntity_1D Encoder_Simulator3::s_PayloadPhysics_Right; double Encoder_Simulator3::s_PreviousPayloadVelocity_Left = 0.0; double Encoder_Simulator3::s_PreviousPayloadVelocity_Right = 0.0; #pragma endregion class COMMON_API Potentiometer_Tester3 : public Encoder_Simulator2 { private: std::queue<double> m_Slack; //when going down this will grow to x frames, and going up with shrink... when not moving it will shrink to nothing double m_SlackedValue=0.0; // ensure the pop of the slack only happens in the time change protected: double m_InvEncoderToRS_Ratio; public: Potentiometer_Tester3(const char* EntityName = "PotSimulator3") : Encoder_Simulator2(EntityName), m_InvEncoderToRS_Ratio(1.0) { } virtual void Initialize(const Framework::Base::asset_manager* props = NULL) { Encoder_Simulator2::Initialize(props); //const Rotary_Properties* rotary = dynamic_cast<const Rotary_Properties*>(props); //if (rotary) // m_InvEncoderToRS_Ratio = 1.0 / rotary->GetRotaryProps().EncoderToRS_Ratio; m_SlackedValue = GetDistance(); } void UpdatePotentiometerVoltage(double Voltage) { double Direction = Voltage < 0 ? -1.0 : 1.0; Voltage = fabs(Voltage); //make positive //Apply the victor curve //Apply the polynomial equation to the voltage to linearize the curve { const double* c = Polynomial; double x2 = Voltage * Voltage; double x3 = Voltage * x2; double x4 = x2 * x2; Voltage = (c[4] * x4) + (c[3] * x3) + (c[2] * x2) + (c[1] * Voltage) + c[0]; Voltage *= Direction; } //From this point it is a percentage (hopefully linear distribution after applying the curve) of the max force to apply... This can be //computed from stall torque ratings of motor with various gear reductions and so forth //on JVN's spread sheet torque at wheel is (WST / DWR) * 2 (for nm) (Wheel stall torque / Drive Wheel Radius * 2 sides) //where stall torque is ST / GearReduction * DriveTrain efficiency //This is all computed in the drive train double TorqueToApply = m_DriveTrain.GetTorqueFromVoltage(Voltage); const double TorqueAbsorbed = m_DriveTrain.INV_GetTorqueFromVelocity(m_Physics.GetVelocity()); TorqueToApply -= TorqueAbsorbed; m_Physics.ApplyFractionalTorque_depreciated(TorqueToApply, m_Time_s, m_DriveTrain.GetDriveTrainProps().TorqueAccelerationDampener); //If we have enough voltage and enough velocity the locking pin is not engaged... gravity can apply extra torque //if ((fabs(Voltage)>0.04)&&(fabs(m_Physics.GetVelocity())>0.05)) if (fabs(Voltage) > 0.04) { // t=Ia //I=sum(m*r^2) or sum(AngularCoef*m*r^2) const double Pounds2Kilograms = 0.453592; const double mass = 16.27 * Pounds2Kilograms; const double r2 = 1.82 * 1.82; //point mass at radius is 1.0 const double I = mass * r2; double Torque = I * 9.80665 * -0.55; //the last scaler gets the direction correct with negative... and tones it down from surgical tubing double TorqueWithAngle = cos(GetDistance() * m_InvEncoderToRS_Ratio) * Torque * m_Time_s; //gravity has most effect when the angle is zero //add surgical tubing simulation... this works in both directions //1.6 seemed closest but on weaker battery, and can't hit 9 feet well TorqueWithAngle += sin(GetDistance() * m_InvEncoderToRS_Ratio) * -1.5; //The pin can protect it against going the wrong direction... if they are opposite... saturate the max opposing direction if (((Torque * TorqueToApply) < 0.0) && (fabs(TorqueWithAngle) > fabs(TorqueToApply))) TorqueWithAngle = -TorqueToApply; m_Physics.ApplyFractionalTorque_depreciated(TorqueWithAngle, m_Time_s, m_DriveTrain.GetDriveTrainProps().TorqueAccelerationDampener); } } virtual double GetPotentiometerCurrentPosition() { #if 1 return m_SlackedValue; #else return GetDistance(); #endif } virtual void TimeChange() { Encoder_Simulator2::TimeChange(); double CurrentVelociy = m_Physics.GetVelocity(); m_Slack.push(GetDistance()); const size_t MaxLatencyCount = 40; if (CurrentVelociy >= 0.0) //going up or still shrink { if (m_Slack.size() > (MaxLatencyCount >> 1)) m_Slack.pop(); if (!m_Slack.empty()) { m_SlackedValue = m_Slack.front(); m_Slack.pop(); } else m_SlackedValue = GetDistance(); } else //going down expand { if (m_Slack.size() >= MaxLatencyCount) m_Slack.pop(); m_SlackedValue = m_Slack.front(); } //SmartDashboard::PutNumber("TestSlack",(double)m_Slack.size()); } virtual void ResetPos() { Encoder_Simulator2::ResetPos(); while (!m_Slack.empty()) m_Slack.pop(); m_SlackedValue = GetDistance(); } }; class COMMON_API Encoder_Tester { private: #if 0 //This is still good for a lesser stress (keeping the latency disabled) Encoder_Simulator m_LeftEncoder; Encoder_Simulator m_RightEncoder; #else Encoder_Simulator2 m_LeftEncoder; Encoder_Simulator2 m_RightEncoder; #endif public: Encoder_Tester() : m_LeftEncoder("LeftEncoder"), m_RightEncoder("RightEncoder") { m_LeftEncoder.Initialize(NULL); m_RightEncoder.Initialize(NULL); } virtual void Initialize(const Framework::Base::asset_manager* props = NULL) { m_LeftEncoder.Initialize(props); m_RightEncoder.Initialize(props); //Cool way to add friction uneven to simulate //m_RightEncoder.SetFriction(0.8,0.12); } virtual void GetLeftRightVelocity(double& LeftVelocity, double& RightVelocity) { LeftVelocity = m_LeftEncoder.GetEncoderVelocity(); RightVelocity = m_RightEncoder.GetEncoderVelocity(); } virtual void UpdateLeftRightVoltage(double LeftVoltage, double RightVoltage) { //LeftVoltage=GetTweakedVoltage(LeftVoltage); //RightVoltage=GetTweakedVoltage(RightVoltage); m_LeftEncoder.UpdateEncoderVoltage(LeftVoltage); m_RightEncoder.UpdateEncoderVoltage(RightVoltage); } void SetTimeDelta(double dTime_s) { m_LeftEncoder.SetTimeDelta(dTime_s); m_RightEncoder.SetTimeDelta(dTime_s); } void TimeChange() { m_LeftEncoder.TimeChange(); m_RightEncoder.TimeChange(); } void SetLeftRightReverseDirectionEncoder(bool Left_reverseDirection,bool Right_reverseDirection) { m_LeftEncoder.SetReverseDirection(Left_reverseDirection),m_RightEncoder.SetReverseDirection(Right_reverseDirection); } void SetLeftRightScaler(double LeftScaler,double RightScaler) { m_LeftEncoder.SetEncoderScaler(LeftScaler),m_RightEncoder.SetEncoderScaler(RightScaler); } }; } #else #pragma endregion #pragma region _Simulation_ class Potentiometer_Tester4 { #pragma region _Description_ //This is specialized for motor simulation turning a loaded mass //This version is much simpler than the others in that it works with the motor curves to determine //This will model a solid sphere for the moment of inertia #pragma endregion private: #pragma region _members_ Framework::Base::PhysicsEntity_1D m_motor_wheel_model; double m_free_speed_rad = 18730 * (1.0 / 60.0) * Pi2; //radians per second of motor double m_stall_torque = 0.71; //Nm double m_gear_reduction = (1.0 / 81.0) * (3.0 / 7.0); //This will account for the friction, and the load torque lever arm double m_gear_box_effeciency = 0.65; double m_mass = Pounds2Kilograms(1.0); //just motor double m_RadiusOfConcentratedMass = Inches2Meters(1.12); //just the motor's diameter double m_AngularInertiaCoefficient = 0.5; //solid cylinder //The dead zone defines the opposing force to be added to the mass we'll clip it down to match the velocity double m_dead_zone = 0.10; //this is the amount of voltage to get motion can be tested double m_anti_backlash_scaler = 0.85; //Any momentum beyond the steady state will be consumed 1.0 max is full consumption double m_Time_s = 0.010; double m_Heading = 0.0; size_t m_InstanceIndex = 0; //for ease of debugging #pragma endregion public: void Initialize(size_t index, const Framework::Base::asset_manager* props = NULL, const char* prefix = properties::registry_v1::csz_CommonSwivel_) { if (props) { using namespace ::properties::registry_v1; std::string constructed_name; #define GET_NUMBER(x,y) \ constructed_name = prefix, constructed_name += csz_##x; \ y = props->get_number(constructed_name.c_str(), y); GET_NUMBER(Pot4_free_speed_rad, m_free_speed_rad); GET_NUMBER(Pot4_stall_torque_NM, m_stall_torque); GET_NUMBER(Pot4_motor_gear_reduction, m_gear_reduction); GET_NUMBER(Pot4_gear_box_effeciency, m_gear_box_effeciency); GET_NUMBER(Pot4_mass, m_mass); GET_NUMBER(Pot4_RadiusOfConcentratedMass, m_RadiusOfConcentratedMass); GET_NUMBER(Pot4_AngularInertiaCoefficient, m_AngularInertiaCoefficient); GET_NUMBER(Pot4_dead_zone, m_dead_zone); GET_NUMBER(Pot4_anti_backlash_scaler, m_anti_backlash_scaler); //GET_NUMBER(); #undef GET_NUMBER } m_motor_wheel_model.SetMass(m_mass); m_motor_wheel_model.SetAngularInertiaCoefficient(m_AngularInertiaCoefficient); m_motor_wheel_model.SetRadiusOfConcentratedMass(m_RadiusOfConcentratedMass); m_InstanceIndex = index; } double GetTorqueFromVoltage(double Voltage) { //Compute the torque to apply from the speed of a scaled voltage curve of a scaled max torque; //Note: the motor curve max torque is scaled //Important: The only one voltage factor here will establish the direction of torque const double max_torque = m_stall_torque * Voltage; //The speed ratio is a ratio of speed to "max speed" of a voltage scaled motor curve and must only be magnitude const double speed_ratio = fabs(Voltage) > 0.0 ? std::max(1.0 - (fabs(m_motor_wheel_model.GetVelocity()) / (m_free_speed_rad * fabs(Voltage))), 0.0) : 0.0; const double torque = max_torque * speed_ratio; return torque; } double GetMechanicalRestaintTorque(double Voltage, double next_current_velocity) { double adverse_torque = 0.0; const double max_torque = m_stall_torque; //Compute adverse torque as the equilibrium sets in to no motion, note the current velocity is motor velocity (no reduction) //as this will be easier to read if (next_current_velocity != 0) { //Don't have this mess with small increments, friction will take the final bite here if (fabs(next_current_velocity) < 0.01) { m_motor_wheel_model.ResetVectors(); } else if (m_Time_s > 0.0) // no division by zero { //May want to provide properties to control how much dead-zone torque to blend //Found a straight constant gives correct result, but have to adjust mass to get correct latency #if 0 const double dead_zone_torque = m_dead_zone * max_torque; adverse_torque = (1.0 - fabs(0.6*Voltage)) * dead_zone_torque + (0.4*Voltage)* dead_zone_torque; //this is the minimum start #else adverse_torque = (m_dead_zone * max_torque); //this is the minimum start #endif //Evaluate anti backlash, on deceleration the momentum of the payload that exceeds the current steady state //will be consumed by the gearing, we apply a scaler to module the strength of this //Note: this could work without reduction if next_current_velocity didn't have it as well, but it is easier to read with it in const double steady_state_velocity = Voltage * m_free_speed_rad; //for now not factoring in efficiency //both the voltage and velocity must be in the same direction... then see if we have deceleration if ((steady_state_velocity * next_current_velocity > 0.0) && (fabs(next_current_velocity) > fabs(steady_state_velocity))) { //factor all in to evaluate note we restore direction at the end const double anti_backlash_accel = (fabs(next_current_velocity) - fabs(steady_state_velocity)) / m_Time_s; const double anti_backlash_torque = m_motor_wheel_model.GetMomentofInertia() * anti_backlash_accel; //Backlash only kicks in when the excess momentum exceed the dead zone threshold adverse_torque += anti_backlash_torque * m_anti_backlash_scaler; } //just compute in magnitude, then restore the opposite direction of the velocity const double adverse_accel_limit = fabs(next_current_velocity) / m_Time_s; //acceleration in radians enough to stop motion //Now to convert into torque still in magnitude const double adverse_torque_limit = m_motor_wheel_model.GetMomentofInertia() * adverse_accel_limit; //clip adverse torque as-needed and restore the opposite sign (this makes it easier to add in the next step adverse_torque = std::min(adverse_torque_limit, adverse_torque) * ((next_current_velocity > 0) ? -1.0 : 1.0); } } return adverse_torque; } void UpdatePotentiometerVoltage(double Voltage) { //Note: these are broken up for SwerveEncoders_Simulator4 to obtain both torques before applying them const double voltage_torque = GetTorqueFromVoltage(Voltage); m_motor_wheel_model.ApplyFractionalTorque(voltage_torque, m_Time_s); const double adverse_torque = GetMechanicalRestaintTorque(Voltage, m_motor_wheel_model.GetVelocity()); m_motor_wheel_model.ApplyFractionalTorque(adverse_torque, m_Time_s); } double GetPotentiometerCurrentPosition() const { return m_Heading; } void TimeChange() { double PositionDisplacement; m_motor_wheel_model.TimeChangeUpdate(m_Time_s, PositionDisplacement); //No normalizing here, we represent the actual position! m_Heading += PositionDisplacement * m_gear_reduction; //velocity is motor, so convert to output rate with the gear reduction } //This is broken up so that the real interface does not have to pass time void SetTimeDelta(double dTime_s) { m_Time_s = dTime_s; } void ResetPos() { m_motor_wheel_model.ResetVectors(); } Framework::Base::PhysicsEntity_1D& GetWheelModel_rw() { return m_motor_wheel_model; } double GetMaxSpeed(bool with_reduction = false) const { return m_free_speed_rad * (with_reduction ? m_gear_reduction : 1.0); } double GetGearReduction() const { return m_gear_reduction; } double GetGearBoxEffeciency() const { return m_gear_box_effeciency; } }; class SwerveEncoders_Simulator4 { #pragma region _Description_ //This works on the same motor concepts as Potentiometer_Tester4 to compute the torque out, but there is an additional load working //against the motor, to work out what this is the interface mechanism will be cleaner to write by providing all at the same time //Ultimately we can make use of Torque = F X R equation and apply this to the mass where R is the wheel radius. To properly simulate //We need to move a 2D mass (using 2D physics) and then break down the vectors that are n line with the wheel, and apply. This can go //in either direction. In the case of opposing torques the magnitude of the forces (before they cancel each other) must be less than //weight * static CoF. The force is torque / wheel radius and the acceleration is known from the torque applied if this is greater //clamp down torque to max and put in kinetic friction mode while the forces are clamped. When it kinetic mode the torque is detached //somewhat where the limit is lower (that goes for how much torque can be transferred to mass as well. Once the forces subside to the //lower limit (weight * kinetic CoF) this can flip it back to static CoF mode. #pragma endregion private: #pragma region _member variables_ Potentiometer_Tester4 m_Encoders[4]; Framework::Base::PhysicsEntity_2D m_Payload; Framework::Base::PhysicsEntity_1D m_Friction; //apply friction to skid std::function< SwerveVelocities&()> m_CurrentVelocities_callback; std::function<SwerveVelocities()> m_VoltageCallback; Inv_Swerve_Drive m_Input; double m_KineticFriction = 0.50; //this looks about right, but we can try to fix class SwerveDrive_Plus : public Swerve_Drive { private: SwerveVelocities m_FromExistingOutput; public: const SwerveVelocities &UpdateFromExisting(double FWD, double STR, double RCW,const SwerveVelocities &CurrentVelocities) { using namespace Framework::Base; //Essentially there is a common vector that has to work with the wheel angles from current velocities. Because the wheel //angles can be reversed we have to approach this per each wheel angle. The result is that the magnitude that occupies the //same direction will be preserved, and the rest will be discarded to friction. We'll also have to be mindful the direction //may be opposite in which case we reverse the sign to keep the same direction. //First we let the kinematics we inherit from work like before, and then work from those quad vectors Swerve_Drive::UpdateVelocities(FWD, STR, RCW); //If the wheel angles are not know, then grab then grab them from existing if (IsZero(fabs(FWD) + fabs(STR) + fabs(RCW))) { for (size_t i = 0; i < 4; i++) SetVelocitiesFromIndex(i + 4, CurrentVelocities.Velocity.AsArray[i + 4]); } for (size_t i = 0; i < 4; i++) { //This next part is tricky... we take our projected vector and rotate it to a global view using the direction of our actual //wheel angle. Everything that exists in the Y component will be what we consume... X will be discarded const Vec2D projected_vector_local(0,GetIntendedVelocitiesFromIndex(i)); //local magnitude pointing up const double projected_vector_heading = GetSwerveVelocitiesFromIndex(i); //point it in it's current direction const Vec2D projected_vector_global = LocalToGlobal(projected_vector_heading,projected_vector_local); //Point it back locally to the direction of our actual wheel angle const double actual_vector_heading = CurrentVelocities.Velocity.AsArray[i + 4]; const Vec2D actual_vector_local = GlobalToLocal(actual_vector_heading, projected_vector_global); //TODO see if there is ever a need to reverse the direction, there is a case where 2 wheels on one side are //opposite causing the velocity to go half speed (not sure if that is here though) const double IsReversed = 1.0; //We have our velocity in the Y component, now to evaluate if it needs to be reversed //const double IsReversed = fabs(projected_vector_heading) - fabs(actual_vector_heading) > Pi / 2 ? -1.0 : 1.0; //Now to populate our result m_FromExistingOutput.Velocity.AsArray[i] = actual_vector_local.y() * IsReversed; m_FromExistingOutput.Velocity.AsArray[i + 4] = CurrentVelocities.Velocity.AsArray[i + 4]; //pedantic } return m_FromExistingOutput; } }; SwerveDrive_Plus m_Output; Swerve_Drive m_TestForce; //used to measure acceleration double m_WheelDiameter_In=4.0; bool m_IsSkidding=false; //cache last state to determine or force normal #pragma endregion public: virtual void Initialize(const Framework::Base::asset_manager* props = NULL) { //TODO get properties for our local members m_Input.Init(props); m_TestForce.Init(props); m_Output.Init(props); Framework::Base::asset_manager DefaultMotorProps; using namespace properties::registry_v1; if (props) { m_WheelDiameter_In = props->get_number(csz_Drive_WheelDiameter_in,m_WheelDiameter_In); //This loads up the defaults first and then any scripted override for (size_t i = 0; i < 4; i++) { m_Encoders[i].Initialize(i, &DefaultMotorProps, csz_CommonDrive_); m_Encoders[i].Initialize(i, props, csz_CommonDrive_); } } else { //We only have defaults for (size_t i = 0; i < 4; i++) m_Encoders[i].Initialize(i, &DefaultMotorProps, csz_CommonDrive_); } //TODO: We may want to add property to the mass m_Payload.SetMass(Pounds2Kilograms(148)); m_Friction.SetMass(Pounds2Kilograms(148)); //May want friction coefficients as well m_Friction.SetStaticFriction(1.0); //rated from wheels m_Friction.SetKineticFriction(m_KineticFriction); //not so easy to measure } void SetVoltageCallback(std::function<SwerveVelocities()> callback) { m_VoltageCallback = callback; } void TimeChange(double dTime_s) { using namespace Framework::Base; //Make sure the potentiometer angles are set in current velocities before calling in here SwerveVelocities InitialVelocitiesForPayload = m_CurrentVelocities_callback(); for (size_t i = 0; i < 4; i++) { const double Voltage = m_VoltageCallback().Velocity.AsArray[i]; Potentiometer_Tester4& encoder = m_Encoders[i]; encoder.UpdatePotentiometerVoltage(Voltage); //This is our initial velocity to submit to payload const double LinearVelocity = encoder.GetWheelModel_rw().GetVelocity() * encoder.GetGearReduction() * Inches2Meters(m_WheelDiameter_In * 0.5); #if 0 m_CurrentVelocities_callback().Velocity.AsArray[i] = LinearVelocity; return; #else InitialVelocitiesForPayload.Velocity.AsArray[i] = LinearVelocity; #endif } //Now we can interpolate the velocity vectors with the same kinematics of the drive m_Input.InterpolateVelocities(InitialVelocitiesForPayload); //printf("force=%.2f\n",ForcesForPayload.Velocity.AsArray[0]); //Before we apply the forces grab the current velocities to compute the new forces const Vec2D last_payload_velocity = m_Payload.GetLinearVelocity(); const double last_payload_angular_velocity = m_Payload.GetAngularVelocity(); const double drive_train_efficiency = m_Encoders[0].GetGearBoxEffeciency(); //Now to convert the inputs velocities into force, which is the velocity change (per second) and divide out the time //to get our acceleration impulse, finally multiple by mass for the total. //Note: I may need to consider conservation of momentum here, but for now scaling down using drive train efficiency does add the latency Vec2D InputAsForce = (Vec2D(m_Input.GetLocalVelocityX(), m_Input.GetLocalVelocityY()) - last_payload_velocity) / dTime_s * m_Payload.GetMass() * drive_train_efficiency; double InputAsTorque = (m_Input.GetAngularVelocity() - last_payload_angular_velocity) / dTime_s * m_Payload.GetMomentofInertia() * drive_train_efficiency; double summed_y_force = 0.0; //see if we are decelerating const Vec2D current_local_velocity(m_Input.GetLocalVelocityX(), m_Input.GetLocalVelocityY()); const double current_local_speed = current_local_velocity.length(); //aka magnitude const double last_payload_speed = last_payload_velocity.length(); bool IsDecelerating = current_local_speed < last_payload_speed; if (IsDecelerating) { //Make sure the rotation isn't overpowering this indication if (fabs(m_Input.GetAngularVelocity()) > fabs(last_payload_angular_velocity)) { //compare apples to apples const double angular_velocity_asLinear = m_Input.GetAngularVelocity() * Pi * m_Input.GetDriveProperties().GetTurningDiameter(); if (fabs(angular_velocity_asLinear) > current_local_speed) IsDecelerating = false; } } if ((!IsDecelerating) && (fabs(m_Input.GetAngularVelocity()) < fabs(last_payload_angular_velocity))) { IsDecelerating = true; //kind of redundant but makes the logic a mirror reflection of above if (current_local_speed > last_payload_speed) { //compare oranges to oranges const double angular_velocity_asLinear = m_Input.GetAngularVelocity() * Pi * m_Input.GetDriveProperties().GetTurningDiameter(); if (current_local_speed > fabs(angular_velocity_asLinear)) IsDecelerating = false; } } if (!IsDecelerating) { //Testing the total force start by adding up the total velocity delta m_TestForce.UpdateVelocities(m_Input.GetLocalVelocityY() - last_payload_velocity.y(), m_Input.GetLocalVelocityX() - last_payload_velocity.x(), m_Input.GetAngularVelocity() - last_payload_angular_velocity); double max_wheel_velocity=0.0; for (size_t i = 0; i < 4; i++) if (m_TestForce.GetIntendedVelocitiesFromIndex(i) > max_wheel_velocity) max_wheel_velocity = m_TestForce.GetIntendedVelocitiesFromIndex(i); //sum all 4 wheels... if one of them exceeds force they all do summed_y_force = max_wheel_velocity / dTime_s * m_Payload.GetMass() * drive_train_efficiency; //printf("|sum=%.2f,y=%.2f|",summed_y_force,InputAsForce.y()); } //Now we can easily evaluate the y-component of force to see if we have a skid, for now we only care about linear motion //as rotation with motion only impacts the x-component of the wheels and is addressed below //The spin in place may be added here later, but leaving out for now as this is not a typical stress that needs to be simulated const bool IsSkidding = fabs(summed_y_force) > m_Friction.GetForceNormal(g,m_IsSkidding?1:0); const int FrictionMode = IsSkidding ? 1 : 0; //Scale down even further if we are skidding if (IsSkidding) { #if 0 static int counter = 0; printf("[%d]skid [%.2f>%.2f]\n",counter++,InputAsForce.y(),m_Friction.GetForceNormal(g, m_IsSkidding ? 1 : 0)); #endif //the scaled amount is fudged to what looks about right since the summed forces is not quite accurate const double scale = m_Friction.GetForceNormal(g, m_IsSkidding ? 1 : 0) / std::max(fabs(summed_y_force)*2.0,m_KineticFriction); //This may be a bit more scale than in reality but should be effective InputAsForce *= scale; InputAsTorque *= scale; } m_IsSkidding = IsSkidding; //stays skid until we slow down enough below the kinetic friction //Apply our torque forces now, before working with friction forces //Note: each vector was averaged (and the multiply by 0.25 was the last operation) m_Payload.ApplyFractionalForce(InputAsForce, dTime_s); m_Payload.ApplyFractionalTorque(InputAsTorque, dTime_s); //printf("|pay_t=%.2f|", m_Input.GetAngularVelocity()); //Check direction, while the controls may not take centripetal forces into consideration, or if in open loop and no feedback //It is possible to skid, where the intended direction of travel doesn't match the existing, to simulate, we localize the //the existing velocity to the new intended direction of travel, and then apply friction force to the x component which is force normal //by the kinetic friction coefficient. This has to clip as the x components velocity reaches zero { const Vec2D IntendedVelocities = Vec2D(m_Input.GetLocalVelocityX(),m_Input.GetLocalVelocityY()); Vec2D IntendedVelocities_normalized(m_Input.GetLocalVelocityX(), m_Input.GetLocalVelocityY()); double magnitude = IntendedVelocities_normalized.normalize(); //Use this heading to rotate our velocity to global const double IntendedDirection=atan2(IntendedVelocities_normalized[0], IntendedVelocities_normalized[1]); const Vec2D local_payload_velocity = m_Payload.GetLinearVelocity(); //Note: aligned_to_Intended this is the current velocity rotated to align with the intended velocity, when the current velocity direction //is mostly the same as the intended, the Y component will consume it. const Vec2D aligned_to_Intended_velocity = GlobalToLocal(IntendedDirection, local_payload_velocity); const Vec2D IntendedVelocity_fromWheelAngle = GlobalToLocal(IntendedDirection, IntendedVelocities); const double Skid_Velocity = aligned_to_Intended_velocity.x(); //velocity to apply friction force to can be in either direction m_Friction.SetVelocity(Skid_Velocity); const double friction_x = m_Friction.GetFrictionalForce(dTime_s, FrictionMode); //printf("|fnx=%.2f|",friction_x); double friction_y = 0.0; //Test for friction Y (only when controls for Y are idle) if (IsZero(IntendedVelocity_fromWheelAngle.y(),0.01)) { double combined_velocity_magnitude=0.0; for (size_t i = 0; i < 4; i++) combined_velocity_magnitude += m_CurrentVelocities_callback().Velocity.AsArray[i]; //while we are here... if we are stopped then we need to do the same for the y Component if (IsZero(combined_velocity_magnitude,0.01)) { m_Friction.SetVelocity(aligned_to_Intended_velocity.y()); friction_y = m_Friction.GetFrictionalForce(dTime_s, FrictionMode); } } //now to get friction force to be applied to x component const Vec2D global_friction_force(friction_x, friction_y); const Vec2D local_friction_force = LocalToGlobal(IntendedDirection, global_friction_force); //We can now consume these forces into the payload m_Payload.ApplyFractionalForce(local_friction_force, dTime_s); //Same goes for the angular velocity as this should not be sliding around if (IsZero(m_Input.GetAngularVelocity(), 0.01)&&(m_Payload.GetAngularVelocity()!=0.00)) { const double AngularVelocity = m_Payload.GetAngularVelocity(); //Avoid small fractions by putting a bite in the threshold if (fabs(AngularVelocity) < 0.0001) { m_Payload.SetAngularVelocity(0.0); } else { //The way to think of this is that in space something could spin forever and it is friction that would stop it //lack of friction (like a top or something on bearings demonstrates this as well) once the robot spins it is //the friction of the wheels that stops the spin. To be compatible to our units of force (which work with KMS i.e. meters) //we convert our angular velocity into linear compute this force and scale back down //force = mass * acceleration, acceleration = vel_a-vel_b, vel = distance / time //proof... using 1 for time distance a is 3 and distance b is 2. 3-2 (meters) a =1 meters per second square //for radians, for now let's assume Pi * D= 2. 1/D(3-2)= 1/D so we can scale this back down to radians, where D is the turning diameter const double turning_diameter = m_Input.GetDriveProperties().GetTurningDiameter(); const double to_linear = Pi * turning_diameter; const double rot_linear = AngularVelocity * to_linear; assert(turning_diameter != 0.0); //sanity check m_Friction.SetVelocity(rot_linear); const double friction_rot = m_Friction.GetFrictionalForce(dTime_s, FrictionMode) / to_linear; //as radians m_Payload.ApplyFractionalTorque(friction_rot, dTime_s); } } } // we could m_Payload.TimeChangeUpdate() at some point const Vec2D current_payload_velocity = m_Payload.GetLinearVelocity(); //printf("--%.2f,", current_payload_velocity.y()); const double current_payload_angular_velocity = m_Payload.GetAngularVelocity(); const SwerveVelocities &AdjustedToExisting=m_Output.UpdateFromExisting(current_payload_velocity.y(), current_payload_velocity.x(), current_payload_angular_velocity, InitialVelocitiesForPayload); //Now we can apply the torque to the wheel for (size_t i = 0; i < 4; i++) { Potentiometer_Tester4& encoder = m_Encoders[i]; Framework::Base::PhysicsEntity_1D& wheel_model = encoder.GetWheelModel_rw(); //const double Force = m_Output.GetIntendedVelocitiesFromIndex(i); //const double Torque = Force * Inches2Meters(m_WheelDiameter_In * 0.5); const double WheelVelocity_fromPayload = AdjustedToExisting.Velocity.AsArray[i] / Inches2Meters(m_WheelDiameter_In * 0.5); #if 0 //To set the velocity directly it works with motor velocity so we'll need to apply the inverse gear ratio wheel_model.SetVelocity(WheelVelocity_fromPayload * (1.0/encoder.GetGearReduction())); #else //Instead of setting the velocity directly, we can apply as a torque, this way if we skid we can apply less force for adjustments //Note: In simulation we work with motor velocity, and do not care about where the physical encoder is, because the actual encoder //output is linear velocity. Outside the simulation using a real encoder will need to use the encoder's reduction to have the //same output of linear velocity const double motor_velocity = WheelVelocity_fromPayload * (1.0 / encoder.GetGearReduction()); double torque_load = (motor_velocity - wheel_model.GetVelocity()) / dTime_s * wheel_model.GetMomentofInertia(); //separating this out for easy of debugging: if (IsSkidding) torque_load = 0.0; //This is not correct, but will help us visualize the skid this is some impact on the velocity though wheel_model.ApplyFractionalTorque(torque_load, dTime_s); #endif //Now that the velocity has taken effect we can add in the adverse torque const double WheelVelocity= wheel_model.GetVelocity() * encoder.GetGearReduction(); const double LinearVelocity = WheelVelocity * Inches2Meters(m_WheelDiameter_In * 0.5); //finally update our odometry, note we work in linear velocity so we multiply by the wheel radius m_CurrentVelocities_callback().Velocity.AsArray[i] = LinearVelocity; } } void SetCurrentVelocities_Callback(std::function<SwerveVelocities&()> callback) { m_CurrentVelocities_callback=callback; } void ResetPos() { for (size_t i = 0; i < 4; i++) m_Encoders[i].ResetPos(); m_Payload.ResetVectors(); } const Framework::Base::PhysicsEntity_2D& GetPayload() const { //read access for advanced sensors to use return m_Payload; } }; #endif //If __UseLegacySimulation__ #pragma endregion #pragma region _Simulated Odometry Internal_ class SimulatedOdometry_Internal { private: static inline double NormalizeRotation2(double Rotation) { const double Pi2 = M_PI * 2.0; //Normalize the rotation if (Rotation > M_PI) Rotation -= Pi2; else if (Rotation < -M_PI) Rotation += Pi2; return Rotation; } #pragma region _member vars_ SwerveVelocities m_CurrentVelocities; std::function<SwerveVelocities()> m_VoltageCallback; double m_maxspeed = Feet2Meters(12.0); //max velocity forward in meters per second double m_current_position[4] = {}; //keep track of the pot's position of each angle //const Framework::Base::asset_manager *m_properties=nullptr; <----reserved struct properties { double swivel_max_speed[4]; } m_bypass_properties; #ifdef __UseLegacySimulation__ Legacy::Potentiometer_Tester2 m_Potentiometers[4]; //simulate a real potentiometer for calibration testing std::shared_ptr<Legacy::Encoder_Simulator2> m_Encoders[4]; #else Potentiometer_Tester4 m_Potentiometers[4]; SwerveEncoders_Simulator4 m_EncoderSim4; class AdvancedSensors { private: SimulatedOdometry_Internal* m_pParent; Vec2D m_current_position; double m_current_heading = 0.0; public: AdvancedSensors(SimulatedOdometry_Internal* parent) : m_pParent(parent) { } void TimeSlice(double d_time_s) { using namespace Framework::Base; //grab our velocities const Framework::Base::PhysicsEntity_2D& payload = m_pParent->m_EncoderSim4.GetPayload(); const double AngularVelocity = payload.GetAngularVelocity(); //update our heading m_current_heading += AngularVelocity * d_time_s; m_current_heading=NormalizeRotation2(m_current_heading); //With latest heading we can adjust our position delta to proper heading const Vec2D local_velocity = payload.GetLinearVelocity(); const Vec2D global_velocity = LocalToGlobal(m_current_heading, local_velocity); //Now we can advance with the global m_current_position += global_velocity * d_time_s; } void Reset() { m_current_position = Vec2D(0.0, 0.0); m_current_heading = 0.0; } Vec2D Vision_GetCurrentPosition() const { return m_current_position; } double GyroMag_GetCurrentHeading() const { return m_current_heading; } } m_AdvancedSensors=this; #endif bool m_UseBypass = true; #pragma endregion void SetHooks(bool enabled) { #ifndef __UseLegacySimulation__ if (enabled) { m_EncoderSim4.SetCurrentVelocities_Callback( [&]() -> SwerveVelocities & { return m_CurrentVelocities; } ); } else m_EncoderSim4.SetCurrentVelocities_Callback(nullptr); #endif } public: void Init(const Framework::Base::asset_manager *props) { using namespace ::properties::registry_v1; //m_properties = props; <---- reserved... most likely should restrict properties here m_UseBypass = props ? props->get_bool(csz_Build_bypass_simulation, m_UseBypass) : true; //Since we define these props as we need them the client code will not need default ones m_bypass_properties.swivel_max_speed[0] = m_bypass_properties.swivel_max_speed[1] = m_bypass_properties.swivel_max_speed[2] = m_bypass_properties.swivel_max_speed[3] = 8.0; //If we are using bypass, we are finished if (m_UseBypass) return; #ifdef __UseLegacySimulation__ for (size_t i = 0; i < 4; i++) { //TODO hook up to properties... the defaults do not work with sim 3, as they were made for sim 2 //I may want to make the defaults for 3 override as well const bool Simulator3 = props ? !props->get_bool(csz_EncoderSimulation_UseEncoder2,true) : false; if (Simulator3) { using Encoder_Simulator3 = Legacy::Encoder_Simulator3; m_Encoders[i] = std::make_shared<Encoder_Simulator3>(); Encoder_Simulator3* ptr = dynamic_cast<Encoder_Simulator3 *>(m_Encoders[i].get()); switch (i) { case 0: ptr->SetEncoderKind(Encoder_Simulator3::eRW_Left); break; case 1: ptr->SetEncoderKind(Encoder_Simulator3::eRW_Right); break; case 2: ptr->SetEncoderKind(Encoder_Simulator3::eReadOnlyLeft); break; case 3: ptr->SetEncoderKind(Encoder_Simulator3::eReadOnlyRight); break; } } else m_Encoders[i] = std::make_shared<Legacy::Encoder_Simulator2>(); m_Encoders[i]->Initialize(props); } #else m_EncoderSim4.Initialize(props); #endif for (size_t i = 0; i < 4; i++) m_Potentiometers[i].Initialize(i, props); ResetPos(); } void ResetPos() { if (m_UseBypass) { m_current_position[0]= m_current_position[1] = m_current_position[2] = m_current_position[3] = 0.0; } else { #ifdef __UseLegacySimulation__ for (size_t i = 0; i < 4; i++) { m_Encoders[i]->ResetPos(); m_Potentiometers[i].ResetPos(); } #else for (size_t i = 0; i < 4; i++) m_Potentiometers[i].ResetPos(); m_EncoderSim4.ResetPos(); m_AdvancedSensors.Reset(); #endif } } void ShutDown() { SetHooks(false); } SimulatedOdometry_Internal() { SetHooks(true); } ~SimulatedOdometry_Internal() { ShutDown(); } void SetVoltageCallback(std::function<SwerveVelocities()> callback) { //Input get it from client m_VoltageCallback = callback; #ifndef __UseLegacySimulation__ m_EncoderSim4.SetVoltageCallback(callback); #endif } //Run the simulation time-slice void TimeSlice(double d_time_s) { if (m_UseBypass) { //If only life were this simple, but alas robots are not god-ships m_CurrentVelocities = m_VoltageCallback(); //convert voltages back to velocities //for drive this is easy for (size_t i = 0; i < 4; i++) { m_CurrentVelocities.Velocity.AsArray[i] *= m_maxspeed; } //for position we have to track this ourselves for (size_t i = 0; i < 4; i++) { //go ahead and apply the voltage to the position... this is over-simplified but effective for a bypass //from the voltage determine the velocity delta const double velocity_delta = m_CurrentVelocities.Velocity.AsArray[i + 4] * m_bypass_properties.swivel_max_speed[i]; m_current_position[i] = NormalizeRotation2(m_current_position[i] + velocity_delta * d_time_s); m_CurrentVelocities.Velocity.AsArray[i + 4] = m_current_position[i]; } } else { SwerveVelocities CurrentVoltage; CurrentVoltage = m_VoltageCallback(); for (size_t i = 0; i < 4; i++) { //We'll put the pot update first in case the simulation factors in the direction (probably shouldn't matter though) m_Potentiometers[i].SetTimeDelta(d_time_s); m_Potentiometers[i].UpdatePotentiometerVoltage(CurrentVoltage.Velocity.AsArray[i + 4]); m_Potentiometers[i].TimeChange(); //cannot normalize here //m_current_position[i] = NormalizeRotation2(m_Potentiometers[i].GetPotentiometerCurrentPosition()); m_current_position[i] = m_Potentiometers[i].GetPotentiometerCurrentPosition(); m_CurrentVelocities.Velocity.AsArray[i + 4] = m_current_position[i]; } #ifdef __UseLegacySimulation__ for (size_t i = 0; i < 4; i++) { m_Encoders[i]->SetTimeDelta(d_time_s); m_Encoders[i]->UpdateEncoderVoltage(CurrentVoltage.Velocity.AsArray[i]); m_Encoders[i]->TimeChange(); m_CurrentVelocities.Velocity.AsArray[i] = m_Encoders[i]->GetEncoderVelocity(); } #else //Ensure potentiometers are updated before calling sim4 m_EncoderSim4.TimeChange(d_time_s); m_AdvancedSensors.TimeSlice(d_time_s); #endif } } const SwerveVelocities &GetCurrentVelocities() const { //Output: contains the current speeds and positions of any given moment of time return m_CurrentVelocities; } #pragma region _advanced_sensor_methods_ bool Sim_SupportVision() const { #ifdef __UseLegacySimulation__ return false; #else return true; #endif } Vec2D Vision_GetCurrentPosition() const { #ifdef __UseLegacySimulation__ return Vec2D(0, 0); #else return m_AdvancedSensors.Vision_GetCurrentPosition(); #endif } bool Sim_SupportHeading() const { #ifdef __UseLegacySimulation__ return false; #else return true; #endif } double GyroMag_GetCurrentHeading() const { #ifdef __UseLegacySimulation__ return 0.0; #else return m_AdvancedSensors.GyroMag_GetCurrentHeading(); #endif } #pragma endregion }; #pragma endregion #pragma region _wrapper methods_ SimulatedOdometry::SimulatedOdometry() { m_simulator = std::make_shared<SimulatedOdometry_Internal>(); } void SimulatedOdometry::Init(const Framework::Base::asset_manager* props) { m_simulator->Init(props); } void SimulatedOdometry::ResetPos() { m_simulator->ResetPos(); } void SimulatedOdometry::Shutdown() { m_simulator->ShutDown(); } void SimulatedOdometry::SetVoltageCallback(std::function<SwerveVelocities()> callback) { m_simulator->SetVoltageCallback(callback); } void SimulatedOdometry::TimeSlice(double d_time_s) { m_simulator->TimeSlice(d_time_s); } const SwerveVelocities &SimulatedOdometry::GetCurrentVelocities() const { return m_simulator->GetCurrentVelocities(); } bool SimulatedOdometry::Sim_SupportVision() const { return m_simulator->Sim_SupportVision(); } Vec2D SimulatedOdometry::Vision_GetCurrentPosition() const { return m_simulator->Vision_GetCurrentPosition(); } bool SimulatedOdometry::Sim_SupportHeading() const { return m_simulator->Sim_SupportHeading(); } double SimulatedOdometry::GyroMag_GetCurrentHeading() const { return m_simulator->GyroMag_GetCurrentHeading(); } #pragma endregion }}
[ "james_killian@hotmail.com" ]
james_killian@hotmail.com
02a871905e68e0bc3231e96181785f2003a6341d
52c66eb8770a6c4da6a7a884553cacc1bd9c8aa4
/src/qt/guiutil.cpp
67bc52b504cb6fd45dcc705abff340add9746d7e
[ "MIT" ]
permissive
PassionLTC/testcoin
29fb16bcc46e779619fe4c15518866f58e4b02f8
7c13771ed4d2c3509f26503bf4dc8de4fdfa522a
refs/heads/master
2016-09-11T00:25:53.274098
2013-05-11T00:20:03
2013-05-11T00:20:03
null
0
0
null
null
null
null
UTF-8
C++
false
false
13,477
cpp
#include "guiutil.h" #include "bitcoinaddressvalidator.h" #include "walletmodel.h" #include "bitcoinunits.h" #include "util.h" #include "init.h" #include "base58.h" #include <QString> #include <QDateTime> #include <QDoubleValidator> #include <QFont> #include <QLineEdit> #include <QUrl> #include <QTextDocument> // For Qt::escape #include <QAbstractItemView> #include <QApplication> #include <QClipboard> #include <QFileDialog> #include <QDesktopServices> #include <QThread> #include <boost/filesystem.hpp> #include <boost/filesystem/fstream.hpp> #ifdef WIN32 #ifdef _WIN32_WINNT #undef _WIN32_WINNT #endif #define _WIN32_WINNT 0x0501 #ifdef _WIN32_IE #undef _WIN32_IE #endif #define _WIN32_IE 0x0501 #define WIN32_LEAN_AND_MEAN 1 #ifndef NOMINMAX #define NOMINMAX #endif #include "shlwapi.h" #include "shlobj.h" #include "shellapi.h" #endif namespace GUIUtil { QString dateTimeStr(const QDateTime &date) { return date.date().toString(Qt::SystemLocaleShortDate) + QString(" ") + date.toString("hh:mm"); } QString dateTimeStr(qint64 nTime) { return dateTimeStr(QDateTime::fromTime_t((qint32)nTime)); } QFont bitcoinAddressFont() { QFont font("Monospace"); font.setStyleHint(QFont::TypeWriter); return font; } void setupAddressWidget(QLineEdit *widget, QWidget *parent) { widget->setMaxLength(BitcoinAddressValidator::MaxAddressLength); widget->setValidator(new BitcoinAddressValidator(parent)); widget->setFont(bitcoinAddressFont()); } void setupAmountWidget(QLineEdit *widget, QWidget *parent) { QDoubleValidator *amountValidator = new QDoubleValidator(parent); amountValidator->setDecimals(8); amountValidator->setBottom(0.0); widget->setValidator(amountValidator); widget->setAlignment(Qt::AlignRight|Qt::AlignVCenter); } bool parseBitcoinURI(const QUrl &uri, SendCoinsRecipient *out) { if(uri.scheme() != QString("netcent")) return false; // check if the address is valid CBitcoinAddress addressFromUri(uri.path().toStdString()); if (!addressFromUri.IsValid()) return false; SendCoinsRecipient rv; rv.address = uri.path(); rv.amount = 0; QList<QPair<QString, QString> > items = uri.queryItems(); for (QList<QPair<QString, QString> >::iterator i = items.begin(); i != items.end(); i++) { bool fShouldReturnFalse = false; if (i->first.startsWith("req-")) { i->first.remove(0, 4); fShouldReturnFalse = true; } if (i->first == "label") { rv.label = i->second; fShouldReturnFalse = false; } else if (i->first == "amount") { if(!i->second.isEmpty()) { if(!BitcoinUnits::parse(BitcoinUnits::BTC, i->second, &rv.amount)) { return false; } } fShouldReturnFalse = false; } if (fShouldReturnFalse) return false; } if(out) { *out = rv; } return true; } bool parseBitcoinURI(QString uri, SendCoinsRecipient *out) { // Convert netcent:// to netcent: // // Cannot handle this later, because netcent:// will cause Qt to see the part after // as host, // which will lowercase it (and thus invalidate the address). if(uri.startsWith("netcent://")) { uri.replace(0, 11, "netcent:"); } QUrl uriInstance(uri); return parseBitcoinURI(uriInstance, out); } QString HtmlEscape(const QString& str, bool fMultiLine) { QString escaped = Qt::escape(str); if(fMultiLine) { escaped = escaped.replace("\n", "<br>\n"); } return escaped; } QString HtmlEscape(const std::string& str, bool fMultiLine) { return HtmlEscape(QString::fromStdString(str), fMultiLine); } void copyEntryData(QAbstractItemView *view, int column, int role) { if(!view || !view->selectionModel()) return; QModelIndexList selection = view->selectionModel()->selectedRows(column); if(!selection.isEmpty()) { // Copy first item QApplication::clipboard()->setText(selection.at(0).data(role).toString()); } } QString getSaveFileName(QWidget *parent, const QString &caption, const QString &dir, const QString &filter, QString *selectedSuffixOut) { QString selectedFilter; QString myDir; if(dir.isEmpty()) // Default to user documents location { myDir = QDesktopServices::storageLocation(QDesktopServices::DocumentsLocation); } else { myDir = dir; } QString result = QFileDialog::getSaveFileName(parent, caption, myDir, filter, &selectedFilter); /* Extract first suffix from filter pattern "Description (*.foo)" or "Description (*.foo *.bar ...) */ QRegExp filter_re(".* \\(\\*\\.(.*)[ \\)]"); QString selectedSuffix; if(filter_re.exactMatch(selectedFilter)) { selectedSuffix = filter_re.cap(1); } /* Add suffix if needed */ QFileInfo info(result); if(!result.isEmpty()) { if(info.suffix().isEmpty() && !selectedSuffix.isEmpty()) { /* No suffix specified, add selected suffix */ if(!result.endsWith(".")) result.append("."); result.append(selectedSuffix); } } /* Return selected suffix if asked to */ if(selectedSuffixOut) { *selectedSuffixOut = selectedSuffix; } return result; } Qt::ConnectionType blockingGUIThreadConnection() { if(QThread::currentThread() != QCoreApplication::instance()->thread()) { return Qt::BlockingQueuedConnection; } else { return Qt::DirectConnection; } } bool checkPoint(const QPoint &p, const QWidget *w) { QWidget *atW = qApp->widgetAt(w->mapToGlobal(p)); if (!atW) return false; return atW->topLevelWidget() == w; } bool isObscured(QWidget *w) { return !(checkPoint(QPoint(0, 0), w) && checkPoint(QPoint(w->width() - 1, 0), w) && checkPoint(QPoint(0, w->height() - 1), w) && checkPoint(QPoint(w->width() - 1, w->height() - 1), w) && checkPoint(QPoint(w->width() / 2, w->height() / 2), w)); } void openDebugLogfile() { boost::filesystem::path pathDebug = GetDataDir() / "debug.log"; /* Open debug.log with the associated application */ if (boost::filesystem::exists(pathDebug)) QDesktopServices::openUrl(QUrl::fromLocalFile(QString::fromStdString(pathDebug.string()))); } ToolTipToRichTextFilter::ToolTipToRichTextFilter(int size_threshold, QObject *parent) : QObject(parent), size_threshold(size_threshold) { } bool ToolTipToRichTextFilter::eventFilter(QObject *obj, QEvent *evt) { if(evt->type() == QEvent::ToolTipChange) { QWidget *widget = static_cast<QWidget*>(obj); QString tooltip = widget->toolTip(); if(tooltip.size() > size_threshold && !tooltip.startsWith("<qt/>") && !Qt::mightBeRichText(tooltip)) { // Prefix <qt/> to make sure Qt detects this as rich text // Escape the current message as HTML and replace \n by <br> tooltip = "<qt/>" + HtmlEscape(tooltip, true); widget->setToolTip(tooltip); return true; } } return QObject::eventFilter(obj, evt); } #ifdef WIN32 boost::filesystem::path static StartupShortcutPath() { return GetSpecialFolderPath(CSIDL_STARTUP) / "NetCent.lnk"; } bool GetStartOnSystemStartup() { // check for NetCent.lnk return boost::filesystem::exists(StartupShortcutPath()); } bool SetStartOnSystemStartup(bool fAutoStart) { // If the shortcut exists already, remove it for updating boost::filesystem::remove(StartupShortcutPath()); if (fAutoStart) { CoInitialize(NULL); // Get a pointer to the IShellLink interface. IShellLink* psl = NULL; HRESULT hres = CoCreateInstance(CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER, IID_IShellLink, reinterpret_cast<void**>(&psl)); if (SUCCEEDED(hres)) { // Get the current executable path TCHAR pszExePath[MAX_PATH]; GetModuleFileName(NULL, pszExePath, sizeof(pszExePath)); TCHAR pszArgs[5] = TEXT("-min"); // Set the path to the shortcut target psl->SetPath(pszExePath); PathRemoveFileSpec(pszExePath); psl->SetWorkingDirectory(pszExePath); psl->SetShowCmd(SW_SHOWMINNOACTIVE); psl->SetArguments(pszArgs); // Query IShellLink for the IPersistFile interface for // saving the shortcut in persistent storage. IPersistFile* ppf = NULL; hres = psl->QueryInterface(IID_IPersistFile, reinterpret_cast<void**>(&ppf)); if (SUCCEEDED(hres)) { WCHAR pwsz[MAX_PATH]; // Ensure that the string is ANSI. MultiByteToWideChar(CP_ACP, 0, StartupShortcutPath().string().c_str(), -1, pwsz, MAX_PATH); // Save the link by calling IPersistFile::Save. hres = ppf->Save(pwsz, TRUE); ppf->Release(); psl->Release(); CoUninitialize(); return true; } psl->Release(); } CoUninitialize(); return false; } return true; } #elif defined(LINUX) // Follow the Desktop Application Autostart Spec: // http://standards.freedesktop.org/autostart-spec/autostart-spec-latest.html boost::filesystem::path static GetAutostartDir() { namespace fs = boost::filesystem; char* pszConfigHome = getenv("XDG_CONFIG_HOME"); if (pszConfigHome) return fs::path(pszConfigHome) / "autostart"; char* pszHome = getenv("HOME"); if (pszHome) return fs::path(pszHome) / ".config" / "autostart"; return fs::path(); } boost::filesystem::path static GetAutostartFilePath() { return GetAutostartDir() / "netcent.desktop"; } bool GetStartOnSystemStartup() { boost::filesystem::ifstream optionFile(GetAutostartFilePath()); if (!optionFile.good()) return false; // Scan through file for "Hidden=true": std::string line; while (!optionFile.eof()) { getline(optionFile, line); if (line.find("Hidden") != std::string::npos && line.find("true") != std::string::npos) return false; } optionFile.close(); return true; } bool SetStartOnSystemStartup(bool fAutoStart) { if (!fAutoStart) boost::filesystem::remove(GetAutostartFilePath()); else { char pszExePath[MAX_PATH+1]; memset(pszExePath, 0, sizeof(pszExePath)); if (readlink("/proc/self/exe", pszExePath, sizeof(pszExePath)-1) == -1) return false; boost::filesystem::create_directories(GetAutostartDir()); boost::filesystem::ofstream optionFile(GetAutostartFilePath(), std::ios_base::out|std::ios_base::trunc); if (!optionFile.good()) return false; // Write a netcent.desktop file to the autostart directory: optionFile << "[Desktop Entry]\n"; optionFile << "Type=Application\n"; optionFile << "Name=NetCent\n"; optionFile << "Exec=" << pszExePath << " -min\n"; optionFile << "Terminal=false\n"; optionFile << "Hidden=false\n"; optionFile.close(); } return true; } #else // TODO: OSX startup stuff; see: // https://developer.apple.com/library/mac/#documentation/MacOSX/Conceptual/BPSystemStartup/Articles/CustomLogin.html bool GetStartOnSystemStartup() { return false; } bool SetStartOnSystemStartup(bool fAutoStart) { return false; } #endif HelpMessageBox::HelpMessageBox(QWidget *parent) : QMessageBox(parent) { header = tr("NetCent-Qt") + " " + tr("version") + " " + QString::fromStdString(FormatFullVersion()) + "\n\n" + tr("Usage:") + "\n" + " netcent-qt [" + tr("command-line options") + "] " + "\n"; coreOptions = QString::fromStdString(HelpMessage()); uiOptions = tr("UI options") + ":\n" + " -lang=<lang> " + tr("Set language, for example \"de_DE\" (default: system locale)") + "\n" + " -min " + tr("Start minimized") + "\n" + " -splash " + tr("Show splash screen on startup (default: 1)") + "\n"; setWindowTitle(tr("NetCent-Qt")); setTextFormat(Qt::PlainText); // setMinimumWidth is ignored for QMessageBox so put in nonbreaking spaces to make it wider. setText(header + QString(QChar(0x2003)).repeated(50)); setDetailedText(coreOptions + "\n" + uiOptions); } void HelpMessageBox::printToConsole() { // On other operating systems, the expected action is to print the message to the console. QString strUsage = header + "\n" + coreOptions + "\n" + uiOptions; fprintf(stderr, "%s", strUsage.toStdString().c_str()); } void HelpMessageBox::showOrPrint() { #if defined(WIN32) // On windows, show a message box, as there is no stderr/stdout in windowed applications exec(); #else // On other operating systems, print help text to console printToConsole(); #endif } } // namespace GUIUtil
[ "passionltc@googlemail.com" ]
passionltc@googlemail.com
5d00735a9e823c52719d1a92177053791c8253ce
753635524b4b4d3e99fc3700a0cf9ed62d191b72
/commons/sources/rtype/client/NetworkState.cpp
0f105bdbb323b968bfd66ba5d5719d7e03a988ed
[]
no_license
EtienneGuillet/RType
b983c640e10421235f59154fd5d2eb7ae4147a52
1f47cd5b7f82025d21a3fd2eee40d25d3f98384b
refs/heads/master
2022-12-17T14:26:28.037453
2019-12-01T22:11:33
2019-12-01T22:11:33
291,720,028
0
0
null
null
null
null
UTF-8
C++
false
false
4,709
cpp
/* ** EPITECH PROJECT, 2022 ** NetworkState.cpp ** File description: ** Created by tpautier, */ #include "NetworkState.hpp" #include "exception/GameStateException.hpp" rtype::NetworkState::NetworkState() : _lostConnection(false) , _tryToConnect(false) , _isConnected(false) , _connectionErrorMessage("") , _serverInfoChanged(false) , _serverHost("") , _serverPort(0) , _charge(0) , _inputs() , _entities() , _lobbyState() , _scores() , _inGame(false) , _playAgain(false) { } void rtype::NetworkState::addEntity(const rtype::EntitiesState &entity) { _entities.push_back(entity); } void rtype::NetworkState::removeEntity(std::uint32_t id) { for (auto it = _entities.begin(); it != _entities.end(); ++it) { if (it->getId() != id) continue; _entities.erase(it); return; } } rtype::EntitiesState& rtype::NetworkState::getEntity(std::uint32_t id) { for (unsigned long int i = 0; i < _entities.size(); i++) { if (_entities[i].getId() != id) continue; return _entities[i]; } throw GameStateException("The id invalid.", WHERE); } std::vector<rtype::EntitiesState>& rtype::NetworkState::getEntities() { return _entities; } std::vector<rtype::EntitiesState> rtype::NetworkState::getEntities(const std::vector<std::uint32_t> &ids) { std::vector<rtype::EntitiesState> vector; for (auto & entity : _entities) { for (unsigned int id : ids) { if (entity.getId() == id) vector.push_back(entity); } } return vector; } bool rtype::NetworkState::comparePositionZ(rtype::EntitiesState entity1, rtype::EntitiesState entity2) { return (entity1.getPos().z < entity2.getPos().z); } void rtype::NetworkState::sortByZindex() { std::sort(_entities.begin(), _entities.end(), comparePositionZ); } void rtype::NetworkState::setInputs(const std::map<NetworkStateKeys, bool> &keys) { _inputs = keys; } const std::map<NetworkStateKeys, bool>& rtype::NetworkState::getInputs() { return _inputs; } void rtype::NetworkState::setInput(NetworkStateKeys key, bool state) { _inputs[key] = state; } void rtype::NetworkState::setCharge(uint8_t charge) { _charge = charge; } uint8_t rtype::NetworkState::getCharge() const { return _charge; } rtype::LobbyState &rtype::NetworkState::getLobbyState() { return _lobbyState; } const std::string &rtype::NetworkState::getServerHost() const { return _serverHost; } void rtype::NetworkState::setServerHost(const std::string &serverHost) { if (_serverHost != serverHost) _serverInfoChanged = true; _serverHost = serverHost; } unsigned short rtype::NetworkState::getServerPort() const { return _serverPort; } void rtype::NetworkState::setServerPort(unsigned short serverPort) { if (_serverPort != serverPort) _serverInfoChanged = true; _serverPort = serverPort; } bool rtype::NetworkState::hasServerInfoChanged() { auto ret = _serverInfoChanged; _serverInfoChanged = false; return ret; } bool rtype::NetworkState::isTryingToConnected() const { return _tryToConnect; } void rtype::NetworkState::connect(const std::string &username) { if (_tryToConnect || _isConnected) { _connectionErrorMessage = "You are already connected / trying to connected"; return; } _tryToConnect = true; _connectionErrorMessage.clear(); _lobbyState.setUsername(username); } bool rtype::NetworkState::isConnnected() const { return _isConnected; } bool rtype::NetworkState::failedToConnect() const { return !_connectionErrorMessage.empty(); } const std::string &rtype::NetworkState::getConnectionErrorMessage() const { return _connectionErrorMessage; } void rtype::NetworkState::setConnectionStatus(bool isSuccess, const std::string &errorMessage) { _isConnected = isSuccess; _tryToConnect = false; _connectionErrorMessage = errorMessage; _lostConnection = isSuccess; } bool rtype::NetworkState::hasLostConnection() const { return _lostConnection; } void rtype::NetworkState::setLostConnection(bool value) { _lostConnection = value; _isConnected = !value; } const std::tuple<int, int, int, int> &rtype::NetworkState::getScores() const { return _scores; } void rtype::NetworkState::setScores(const std::tuple<int, int, int, int> &scores) { _scores = scores; } bool rtype::NetworkState::isInGame() const { return _inGame; } void rtype::NetworkState::setInGame(bool inGame) { _inGame = inGame; } bool rtype::NetworkState::isPlayAgain() const { return _playAgain; } void rtype::NetworkState::setPlayAgain(bool playAgain) { _playAgain = playAgain; }
[ "julian.frabel@epitech.eu" ]
julian.frabel@epitech.eu
85f77111b40c5f01ffeb337ecd09cf0b8ae63e47
de4ba05ade2ef91ef8e401df73194abee3c657d9
/imam9ais/spoj/FCTRL2/FCTRL2-12953001.cpp
4435c87cc1cfb1c22307affc08effcb89972b174
[]
no_license
IMAM9AIS/SPOJ_SOLUTIONS
bed576afb2b7cc0518162574f15bc2026ce75aa1
d43481399696a8a7e4a52060a43b8d08f2272e41
refs/heads/master
2021-01-01T16:25:07.801813
2015-07-04T00:26:58
2015-07-04T00:26:58
38,515,348
0
0
null
null
null
null
UTF-8
C++
false
false
819
cpp
#include<bits/stdc++.h> using namespace std; int main() { int t; cin>>t; while(t--){ int ar[200]; memset(ar,0,sizeof(ar)); ar[199]=1; int num; cin>>num; int i;int count=0; for(i=1;i<=num;i++) { int k;int c=0; for(k=199;k>=1;k--) { int n1=ar[k]; int mul=n1*i+c; ar[k]=mul%10; c=mul/10; } while(c!=0) { int te=c%10; ar[k]=te; k--;c=c/10; } } int k=0; while(ar[k]==0) k++; while(k<200) { cout<<ar[k];k++;} cout<<endl; } }
[ "imamkhursheed@gmail.com" ]
imamkhursheed@gmail.com
fcde33784b2d3dd17c8ab5415da8e00b9739bbdd
569bef7d1f1f5847794eeda357ad226e2d427685
/src/animated_sprite.h
ec659dca63ef75e893d99ca578b9f8afbd133baa
[]
no_license
wmillar/mr
e35129337e6da2827a9dcda96610881415fb1452
a390da7b134231ea502c5c81ef4799e150ef3c6f
refs/heads/master
2021-05-30T00:03:27.978060
2015-10-29T23:50:24
2015-10-29T23:50:24
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,008
h
#pragma once #include "constants.h" #include "drawable.h" #include "sdl_header.h" #include <string> #include <utility> #include <vector> class Canvas; class AnimatedSprite : public Drawable { public: AnimatedSprite() {} virtual ~AnimatedSprite() {} virtual void update(const Constants::float_type) = 0; virtual void reset(void) = 0; }; class AnimatedSpriteSource { public: AnimatedSpriteSource() {} virtual ~AnimatedSpriteSource() {} void setImageName(const std::string& n) {imgName = n;} const std::string& getImageName() const {return imgName;} private: std::string imgName; }; // Animation with fixed frame dimensions class UniformAnimatedSpriteSource : public AnimatedSpriteSource { public: UniformAnimatedSpriteSource() = default; ~UniformAnimatedSpriteSource(); void setTexture(SDL_Texture*); // does not take ownership of texture void setSize(const int, const int); void setDuration(const Constants::float_type); void add(const int, const int); // UniformAnimatedSprite methods void update(const Constants::float_type, Constants::float_type&, std::size_t&) const; SDL_Texture* getTexture(void); SDL_Rect* getTextureBounds(const std::size_t); int getDrawWidth(void) const; int getDrawHeight(void) const; private: std::vector<std::pair<int, int>> frames; SDL_Rect bounds; SDL_Texture* tex = nullptr; Constants::float_type frameDur; // duration of each frame }; // Every SDL_Rect is same size and all frame duration are same number of ticks. class UniformAnimatedSprite : public AnimatedSprite { public: void update(const Constants::float_type) override; void reset(void) override; void setSource(UniformAnimatedSpriteSource*); // Drawable SDL_Texture* getTexture(void) override; SDL_Rect* getTextureBounds(void) override; int getDrawWidth(void) const override; int getDrawHeight(void) const override; private: UniformAnimatedSpriteSource* src = nullptr; std::size_t index = 0; Constants::float_type frameTimeRem = 0; // time remaining for current frame };
[ "wesleykmillar@gmail.com" ]
wesleykmillar@gmail.com
0cb6474598c130825be850e86e570f1246492963
34eeecfb2c027f8bdc600656eee77ec7948b9276
/Samples/System/MouseCursor/MouseCursor.cpp
df29232b67abbcacd53a0223a9984fdb2b4c8f50
[ "MIT" ]
permissive
OhGameKillers/Xbox-ATG-Samples
bfe80ccbc74d96a67d6fa4fb5d2c12c9f3bfee91
615d94ea64f4fb929b1342de44925e6689bbf73b
refs/heads/master
2020-12-26T03:45:05.368567
2016-04-28T21:03:45
2016-04-28T21:03:45
59,704,706
1
0
null
2016-05-25T23:32:23
2016-05-25T23:32:22
null
UTF-8
C++
false
false
17,152
cpp
//-------------------------------------------------------------------------------------- // MouseCursor.cpp // // MouseCursor UWP sample // // Advanced Technology Group (ATG) // Copyright (C) Microsoft Corporation. All rights reserved. //-------------------------------------------------------------------------------------- #include "pch.h" #include "MouseCursor.h" using namespace DirectX; using namespace DirectX::SimpleMath; using Microsoft::WRL::ComPtr; #define ROTATION_GAIN 0.004f // sensitivity adjustment Sample::Sample() : m_isAbsolute(true), m_isRelative(false), m_isClipCursor(false), m_highlightFPS(false), m_highlightRTS(false), m_eyeFPS( 0.f, 20.f, -20.f ), m_targetFPS( 0.f, 20.f, 0.f ), m_eyeRTS( 0.f, 300.f, 0.f ), m_targetRTS( 0.01f, 300.1f, 0.01f ), m_eye( 0.f, 20.f, 0.f ), m_target( 0.01f, 20.1f, 0.01f ), m_pitch( 0 ), m_yaw( 0 ) { m_deviceResources = std::make_unique<DX::DeviceResources>(); m_deviceResources->RegisterDeviceNotify(this); } // Initialize the Direct3D resources required to run. void Sample::Initialize( IUnknown* window, int width, int height, DXGI_MODE_ROTATION rotation ) { m_deviceResources->SetWindow(window, width, height, rotation); m_deviceResources->CreateDeviceResources(); CreateDeviceDependentResources(); m_deviceResources->CreateWindowSizeDependentResources(); CreateWindowSizeDependentResources(); } #pragma region Frame Update // Executes basic render loop. void Sample::Tick() { m_timer.Tick( [ & ] () { Update( m_timer ); } ); Render(); } // Updates the world. void Sample::Update( DX::StepTimer const&) { PIXBeginEvent(PIX_COLOR_DEFAULT, L"Update"); // In clip cursor mode implement screen scrolling when the mouse is near the edge of the screen if (m_isClipCursor) { if (m_screenLocation.X < 20.f) MoveRight(-25.f); else if (m_screenLocation.X > m_deviceResources->GetOutputSize().right - m_deviceResources->GetOutputSize().left - 20.f) MoveRight(25.f); if (m_screenLocation.Y < 20.f) MoveForward(25.f); else if (m_screenLocation.Y > m_deviceResources->GetOutputSize().bottom - m_deviceResources->GetOutputSize().top - 20.f) MoveForward(-25.f); } PIXEndEvent(); } #pragma endregion #pragma region Frame Render // Draws the scene. void Sample::Render() { // Don't try to render anything before the first Update. if ( m_timer.GetFrameCount() == 0 ) { return; } Clear(); auto context = m_deviceResources->GetD3DDeviceContext(); PIXBeginEvent(context, PIX_COLOR_DEFAULT, L"Render"); m_spriteBatch->Begin(); std::wstring text = L"+"; const wchar_t* output = text.c_str(); Vector2 origin = m_font->MeasureString( output ) / 2.f; m_fontPos.x = m_screenLocation.X; m_fontPos.y = m_screenLocation.Y; if ( m_isAbsolute ) { m_spriteBatch->Draw( m_texture_background.Get(), m_fullscreenRect ); m_spriteBatch->Draw( m_texture_tile.Get(), m_FPStile ); m_spriteBatch->Draw( m_texture_tile.Get(), m_RTStile ); if ( m_highlightFPS ) { m_spriteBatch->Draw( m_texture_tile_border.Get(), m_FPStile ); } else if ( m_highlightRTS ) { m_spriteBatch->Draw( m_texture_tile_border.Get(), m_RTStile ); } std::wstring text1 = L"Mouse Cursor Sample"; const wchar_t* outputTitle = text1.c_str(); Vector2 originTitle = m_font64->MeasureString( outputTitle ) / 2.f; std::wstring text2 = L"Choose a game mode"; const wchar_t* outputSubtitle = text2.c_str(); Vector2 originSubtitle = m_font32->MeasureString( outputSubtitle ) / 2.f; std::wstring text3 = L"First-person \n Shooter"; const wchar_t* outputFPS = text3.c_str(); Vector2 originFPS = m_font28->MeasureString( outputFPS ) / 2.f; std::wstring text4 = L"Real-time \n Strategy"; const wchar_t* outputRTS = text4.c_str(); Vector2 originRTS = m_font28->MeasureString( outputRTS ) / 2.f; m_font64->DrawString( m_spriteBatch.get(), outputTitle, m_fontPosTitle, Colors::White, 0.f, originTitle ); m_font32->DrawString( m_spriteBatch.get(), outputSubtitle, m_fontPosSubtitle, Colors::White, 0.f, originSubtitle ); m_font28->DrawString( m_spriteBatch.get(), outputFPS, m_fontPosFPS, Colors::White, 0.f, originFPS ); m_font28->DrawString( m_spriteBatch.get(), outputRTS, m_fontPosRTS, Colors::White, 0.f, originRTS ); } else { m_font->DrawString( m_spriteBatch.get(), output, m_fontPos, Colors::White, 0.f, origin ); if ( m_isRelative ) { m_modelFPS->Draw( m_deviceResources->GetD3DDeviceContext(), *m_states, m_world, m_view, m_proj ); } else if ( m_isClipCursor ) { m_modelRTS->Draw( m_deviceResources->GetD3DDeviceContext(), *m_states, m_world, m_view, m_proj ); } } m_spriteBatch->End(); PIXEndEvent(context); // Show the new frame. PIXBeginEvent(PIX_COLOR_DEFAULT, L"Present"); m_deviceResources->Present(); PIXEndEvent(); } // Helper method to clear the back buffers. void Sample::Clear() { auto context = m_deviceResources->GetD3DDeviceContext(); PIXBeginEvent(context, PIX_COLOR_DEFAULT, L"Clear"); // Clear the views auto renderTarget = m_deviceResources->GetBackBufferRenderTargetView(); auto depthStencil = m_deviceResources->GetDepthStencilView(); context->ClearRenderTargetView(renderTarget, Colors::CornflowerBlue); context->ClearDepthStencilView(depthStencil, D3D11_CLEAR_DEPTH | D3D11_CLEAR_STENCIL, 1.0f, 0); context->OMSetRenderTargets(1, &renderTarget, depthStencil); // Set the viewport. auto viewport = m_deviceResources->GetScreenViewport(); context->RSSetViewports(1, &viewport); PIXEndEvent(context); } #pragma endregion #pragma region Message Handlers // Message handlers void Sample::OnActivated() { } void Sample::OnDeactivated() { } void Sample::OnSuspending() { auto context = m_deviceResources->GetD3DDeviceContext(); context->ClearState(); m_deviceResources->Trim(); } void Sample::OnResuming() { m_timer.ResetElapsedTime(); } void Sample::OnWindowSizeChanged( int width, int height, DXGI_MODE_ROTATION rotation ) { if ( !m_deviceResources->WindowSizeChanged( width, height, rotation ) ) return; CreateWindowSizeDependentResources(); } void Sample::ValidateDevice() { m_deviceResources->ValidateDevice(); } // Properties void Sample::GetDefaultSize( int& width, int& height ) const { width = 1280; height = 720; } #pragma endregion #pragma region Direct3D Resources // These are the resources that depend on the device. void Sample::CreateDeviceDependentResources() { auto context = m_deviceResources->GetD3DDeviceContext(); auto device = m_deviceResources->GetD3DDevice(); // Device dependent object initialization ( independent of window size ) m_font = std::make_unique<SpriteFont>(device, L"Courier_36.spritefont"); m_font64 = std::make_unique<SpriteFont>(device, L"SegoeUI_34.spritefont"); m_font32 = std::make_unique<SpriteFont>(device, L"SegoeUI_24.spritefont"); m_font28 = std::make_unique<SpriteFont>(device, L"SegoeUI_22.spritefont"); m_spriteBatch = std::make_unique<SpriteBatch>(context); m_states = std::make_unique<CommonStates>(device); m_fxFactory = std::make_unique<EffectFactory>(device); m_modelFPS = Model::CreateFromSDKMESH( device, L"FPSRoom.sdkmesh", *m_fxFactory, true ); // Note that this model uses 32-bit index buffers so it can't be used w/ Feature Level 9.1 m_modelRTS = Model::CreateFromSDKMESH(device, L"3DRTSMap.sdkmesh", *m_fxFactory, true ); DX::ThrowIfFailed( CreateWICTextureFromFile(device, L"Assets//background_flat.png", nullptr, m_texture_background.ReleaseAndGetAddressOf() ) ); DX::ThrowIfFailed( CreateWICTextureFromFile(device, L"Assets//green_tile.png", nullptr, m_texture_tile.ReleaseAndGetAddressOf() ) ); DX::ThrowIfFailed( CreateWICTextureFromFile(device, L"Assets//green_tile_border.png", nullptr, m_texture_tile_border.ReleaseAndGetAddressOf() ) ); m_world = Matrix::Identity; } // Allocate all memory resources that change on a window SizeChanged event. void Sample::CreateWindowSizeDependentResources() { // Initialization of background image m_fullscreenRect = m_deviceResources->GetOutputSize(); UINT backBufferWidth = static_cast<UINT>(m_fullscreenRect.right - m_fullscreenRect.left); UINT backBufferHeight = static_cast<UINT>(m_fullscreenRect.bottom - m_fullscreenRect.top); // Update pointer location if (m_isRelative) { m_screenLocation.X = backBufferWidth / 2.f; m_screenLocation.Y = backBufferHeight / 2.f; } // Initialize UI tiles and font locations m_FPStile.left = ( LONG ) ( 0.325f*backBufferWidth ); m_FPStile.top = ( LONG ) ( 0.44f*backBufferHeight ); m_FPStile.right = ( LONG ) ( 0.495f*backBufferWidth ); m_FPStile.bottom = ( LONG ) ( 0.66f*backBufferHeight ); m_FPStile.bottom = std::max( m_FPStile.bottom, m_FPStile.top + 150 ); m_FPStile.left = std::min( m_FPStile.left, ( LONG ) ( m_FPStile.right - ( ( m_FPStile.bottom - m_FPStile.top ) * 4 / 3.f ) ) ); m_RTStile.left = ( LONG ) ( 0.505f*backBufferWidth ); m_RTStile.top = m_FPStile.top; m_RTStile.right = ( LONG ) ( 0.675f*backBufferWidth ); m_RTStile.bottom = m_FPStile.bottom; m_RTStile.right = std::max( m_RTStile.right, ( LONG )( m_RTStile.left + ( ( m_RTStile.bottom - m_RTStile.top ) * 4 / 3.f ) ) ); m_fontPos.x = backBufferWidth / 2.f; m_fontPos.y = backBufferHeight / 2.f; m_fontPosTitle.x = backBufferWidth / 2.f; m_fontPosTitle.y = backBufferHeight * 0.27f; m_fontPosSubtitle.x = backBufferWidth / 2.f; m_fontPosSubtitle.y = backBufferHeight * 0.36f; m_fontPosFPS.x = m_FPStile.left + ( m_FPStile.right - m_FPStile.left )/2.f; m_fontPosFPS.y = m_FPStile.top + ( m_FPStile.bottom - m_FPStile.top ) / 2.f; m_fontPosRTS.x = m_RTStile.left + ( m_RTStile.right - m_RTStile.left )/2.f; m_fontPosRTS.y = m_fontPosFPS.y; m_spriteBatch->SetRotation( m_deviceResources->GetRotation() ); } void Sample::OnDeviceLost() { m_font.reset(); m_font64.reset(); m_font32.reset(); m_font28.reset(); m_spriteBatch.reset(); m_states.reset(); m_fxFactory.reset(); m_modelFPS.reset(); m_modelRTS.reset(); m_texture_background.Reset(); m_texture_tile.Reset(); m_texture_tile_border.Reset(); } void Sample::OnDeviceRestored() { CreateDeviceDependentResources(); CreateWindowSizeDependentResources(); } #pragma endregion // Update the pointer location in clip cursor mode void Sample::UpdatePointer( Windows::Foundation::Point screen ) { m_screenLocation = screen; } // Change the target value based on the mouse movement for move-look/relative mouse mode void Sample::UpdateCamera( Vector3 movement ) { // Adjust pitch and yaw based on the mouse movement Vector3 rotationDelta = movement * ROTATION_GAIN; m_pitch += rotationDelta.y; m_yaw += rotationDelta.x; // Limit to avoid looking directly up or down float limit = XM_PI / 2.0f - 0.01f; m_pitch = std::max( -limit, m_pitch ); m_pitch = std::min( +limit, m_pitch ); if ( m_yaw > XM_PI ) { m_yaw -= XM_PI * 2.f; } else if ( m_yaw < -XM_PI ) { m_yaw += XM_PI * 2.f; } float y = sinf( m_pitch ); float r = cosf( m_pitch ); float z = r*cosf( m_yaw ); float x = r*sinf( m_yaw ); m_target = m_eye + Vector3( x, y, z ); SetView(); } // Move the camera forward or backward void Sample::MoveForward( float amount ) { Vector3 movement = m_target - m_eye; movement.y = 0.f; Vector3 m_eye_temp = m_eye - amount*movement; if ( ( m_eye_temp.z < -1*m_eye_temp.x + 400 ) && ( m_eye_temp.z < m_eye_temp.x + 800 ) && ( m_eye_temp.z > -1 * m_eye_temp.x - 300 ) && ( m_eye_temp.z > m_eye_temp.x - 800 ) ) { m_eye = m_eye_temp; m_target = m_target - amount*movement; SetView(); } } // Move the camera to the right or left void Sample::MoveRight( float amount ) { Vector3 movement1 = m_target - m_eye; movement1.y = 0.f; Vector3 movement; movement.x = -movement1.z; movement.y = 0.f; movement.z = movement1.x; Vector3 m_eye_temp = m_eye + amount*movement; if ( ( m_eye_temp.z < ( -1 * m_eye_temp.x + 400 ) ) && ( m_eye_temp.z < ( m_eye_temp.x + 800 ) ) && ( m_eye_temp.z > ( -1 * m_eye_temp.x - 300 ) ) && ( m_eye_temp.z > ( m_eye_temp.x - 800 ) ) ) { m_eye = m_eye_temp; m_target = m_target + amount*movement; SetView(); } } // Update the viewport based on the updated eye and target values void Sample::SetView() { UINT backBufferWidth = static_cast<UINT>( m_deviceResources->GetOutputSize().right - m_deviceResources->GetOutputSize().left ); UINT backBufferHeight = static_cast<UINT>( m_deviceResources->GetOutputSize().bottom - m_deviceResources->GetOutputSize().top ); m_view = Matrix::CreateLookAt( m_eye, m_target, Vector3::UnitY ); Matrix proj = XMMatrixPerspectiveFovLH( XM_PI / 4.f, float( backBufferWidth ) / float( backBufferHeight ), 0.1f, 10000.f ); m_proj = proj * m_deviceResources->GetOrientationTransform3D(); } // Set mode to relative ( 1 ), absolute ( 0 ), or clip cursor ( 2 ) Sample::MouseMode Sample::SetMode( Windows::Foundation::Point mouseLocation ) { // If entering FPS or relative mode if ( mouseLocation.X < m_FPStile.right && mouseLocation.X > m_FPStile.left && mouseLocation.Y > m_FPStile.top && mouseLocation.Y < m_FPStile.bottom ) { UINT backBufferWidth = static_cast<UINT>( m_deviceResources->GetOutputSize().right - m_deviceResources->GetOutputSize().left ); UINT backBufferHeight = static_cast<UINT>( m_deviceResources->GetOutputSize().bottom - m_deviceResources->GetOutputSize().top ); m_screenLocation.X = backBufferWidth / 2.f; m_screenLocation.Y = backBufferHeight / 2.f; m_isRelative = true; m_isAbsolute = false; m_isClipCursor = false; m_highlightFPS = false; m_highlightRTS = false; m_world = Matrix::CreateRotationX( XM_PI / 2.f )*Matrix::CreateRotationY( XM_PI ); m_eye = m_eyeFPS; m_target = m_targetFPS; UpdateCamera( Vector3::Zero ); SetView(); return RELATIVE_MOUSE; } // If entering RTS or clipCursor mode else if ( mouseLocation.X < m_RTStile.right && mouseLocation.X > m_RTStile.left && mouseLocation.Y > m_RTStile.top && mouseLocation.Y < m_RTStile.bottom ) { m_isRelative = false; m_isAbsolute = false; m_isClipCursor = true; m_highlightFPS = false; m_highlightRTS = false; m_world = Matrix::CreateRotationX( XM_PI / 2.f )*Matrix::CreateRotationY( 5 * XM_PI / 4 ); m_eye = m_eyeRTS; m_target = m_targetRTS; SetView(); return CLIPCURSOR_MOUSE; } // Entering absolute mode else { if ( m_isClipCursor ) { m_eyeRTS = m_eye; m_targetRTS = m_target; } m_isRelative = false; m_isAbsolute = true; m_isClipCursor = false; return ABSOLUTE_MOUSE; } } // When the mouse moves, check to see if it is on top of the FPS or RTS selection tiles void Sample::CheckLocation( Windows::Foundation::Point mouseLocation ) { if ( m_isAbsolute ) { // If hovering over FPS or relative selection if ( mouseLocation.X < m_FPStile.right && mouseLocation.X > m_FPStile.left && mouseLocation.Y > m_FPStile.top && mouseLocation.Y < m_FPStile.bottom ) { m_highlightFPS = true; m_highlightRTS = false; } // If hovering over RTS or clipCursor selection else if ( mouseLocation.X < m_RTStile.right && mouseLocation.X > m_RTStile.left && mouseLocation.Y > m_RTStile.top && mouseLocation.Y < m_RTStile.bottom ) { m_highlightRTS = true; m_highlightFPS = false; } else { m_highlightFPS = false; m_highlightRTS = false; } } }
[ "chuckw@windows.microsoft.com" ]
chuckw@windows.microsoft.com
1de44e9b565c1d93c928d039eaa7b478ba3780f2
fc7d5b988d885bd3a5ca89296a04aa900e23c497
/Programming/mbed-os-example-sockets/mbed-os/storage/blockdevice/include/blockdevice/MBRBlockDevice.h
959c64d6f786ea2ee59ca0275fdc32dbe89a6476
[ "Apache-2.0" ]
permissive
AlbinMartinsson/master_thesis
52746f035bc24e302530aabde3cbd88ea6c95b77
495d0e53dd00c11adbe8114845264b65f14b8163
refs/heads/main
2023-06-04T09:31:45.174612
2021-06-29T16:35:44
2021-06-29T16:35:44
334,069,714
3
1
Apache-2.0
2021-03-16T16:32:16
2021-01-29T07:28:32
C++
UTF-8
C++
false
false
8,260
h
/* mbed Microcontroller Library * Copyright (c) 2017-2020 ARM Limited * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** \addtogroup storage */ /** @{*/ #ifndef MBED_MBR_BLOCK_DEVICE_H #define MBED_MBR_BLOCK_DEVICE_H #include "BlockDevice.h" namespace mbed { /** Additional error codes used for MBR records */ enum { BD_ERROR_INVALID_MBR = -3101, BD_ERROR_INVALID_PARTITION = -3102, }; /** Block device for managing a Master Boot Record * https://en.wikipedia.org/wiki/Master_boot_record * * @note * The MBR partition table is relatively limited: * - At most 4 partitions are supported * - Extended partitions are currently not supported and will error during init */ class MBRBlockDevice : public BlockDevice { public: /** Format the MBR to contain the following partition * * @param bd Block device to partition * @param part Partition to use, 1-4 * @param type 8-bit partition type to specify the filesystem to use in this partition. * It can be found in the filesystem documentation or refer to * https://en.wikipedia.org/wiki/Partition_type#List_of_partition_IDs * @param start Start block address to map to block 0 of partition. * Negative addresses are calculated from the end of the * underlying block devices. Block 0 is implicitly ignored * from the range to store the MBR. * @return 0 on success or a negative error code on failure. * @note This is the same as partition(bd, part, type, start, bd->size()) */ static int partition(BlockDevice *bd, int part, uint8_t type, bd_addr_t start); /** Format the MBR to contain the following partition * * @param bd Block device to partition * @param part Partition to use, 1-4 * @param type 8-bit partition type to specify the filesystem to use in this partition. * It can be found in the filesystem documentation or refer to * https://en.wikipedia.org/wiki/Partition_type#List_of_partition_IDs * @param start Start block address to map to block 0 of partition, * negative addresses are calculated from the end of the * underlying block devices. Block 0 is implicitly ignored * from the range to store the MBR. * @param stop End block address to mark the end of the partition. * This block is not mapped: negative addresses are calculated * from the end of the underlying block device. * @return 0 on success or a negative error code on failure. */ static int partition(BlockDevice *bd, int part, uint8_t type, bd_addr_t start, bd_addr_t stop); /** Lifetime of the block device * * @param bd Block device to back the MBRBlockDevice * @param part Partition to use, 1-4 */ MBRBlockDevice(BlockDevice *bd, int part); /** Lifetime of the block device */ virtual ~MBRBlockDevice() {}; /** Initialize a block device * * @return 0 on success or a negative error code on failure */ virtual int init(); /** Deinitialize a block device * * @return 0 on success or a negative error code on failure */ virtual int deinit(); /** Ensure data on storage is in sync with the driver * * @return 0 on success or a negative error code on failure */ virtual int sync(); /** Read blocks from a block device * * @param buffer Buffer to read blocks into * @param addr Address of block to begin reading from * @param size Size to read in bytes, must be a multiple of read block size * @return 0 on success or a negative error code on failure */ virtual int read(void *buffer, bd_addr_t addr, bd_size_t size); /** Program blocks to a block device * * The blocks must have been erased prior to being programmed * * @param buffer Buffer of data to write to blocks * @param addr Address of block to begin writing to * @param size Size to write in bytes, must be a multiple of program block size * @return 0 on success or a negative error code on failure */ virtual int program(const void *buffer, bd_addr_t addr, bd_size_t size); /** Erase blocks on a block device * * The state of an erased block is undefined until it has been programmed, * unless get_erase_value returns a non-negative byte value * * @param addr Address of block to begin erasing * @param size Size to erase in bytes, must be a multiple of erase block size * @return 0 on success or a negative error code on failure */ virtual int erase(bd_addr_t addr, bd_size_t size); /** Get the size of a readable block * * @return Size of a readable block in bytes */ virtual bd_size_t get_read_size() const; /** Get the size of a programmable block * * @return Size of a programmable block in bytes * @note Must be a multiple of the read size */ virtual bd_size_t get_program_size() const; /** Get the size of an erasable block * * @return Size of an erasable block in bytes * @note Must be a multiple of the program size */ virtual bd_size_t get_erase_size() const; /** Get the size of an erasable block given address * * @param addr Address within the erasable block * @return Size of an erasable block in bytes * @note Must be a multiple of the program size */ virtual bd_size_t get_erase_size(bd_addr_t addr) const; /** Get the value of storage when erased * * If get_erase_value returns a non-negative byte value, the underlying * storage is set to that value when erased, and storage containing * that value can be programmed without another erase. * * @return The value of storage when erased, or -1 if you can't * rely on the value of erased storage */ virtual int get_erase_value() const; /** Get the total size of the underlying device * * @return Size of the underlying device in bytes */ virtual bd_size_t size() const; /** Get the offset of the partition on the underlying block device * @return Offset of the partition on the underlying device */ virtual bd_addr_t get_partition_start() const; /** Get size of partition on underlying block device * @return Size of the partition on the underlying device */ virtual bd_addr_t get_partition_stop() const; /** Get 8-bit type of the partition * @return 8-bit type of partition assigned during format */ virtual uint8_t get_partition_type() const; /** Get the partition number * @return The partition number, 1-4 */ virtual int get_partition_number() const; /** Get the BlockDevice class type. * * @return A string represent the BlockDevice class type. */ virtual const char *get_type() const; protected: BlockDevice *_bd; bd_size_t _offset; bd_size_t _size; uint8_t _type; uint8_t _part; uint32_t _init_ref_count; bool _is_initialized; }; } // namespace mbed // Added "using" for backwards compatibility #ifndef MBED_NO_GLOBAL_USING_DIRECTIVE using mbed::MBRBlockDevice; #endif #endif /** @}*/
[ "albmar-6@student.ltu.se" ]
albmar-6@student.ltu.se
ec941fb95b6705c1b8ae9220322e34551545ac83
46bced23cd4a64eaecbd51a541f35e6361c6af02
/cpp_STL学习/cpp_STL学习/vector存储内置数据类型.h
b6d74467c74bc858aa734c98cc785728d5b631da
[ "MIT" ]
permissive
Magicboomliu/Cplus_plus_Basic
0a1091b08978862614cc2b37a214a4e7f10322bc
74ba7e760ea94418dbec685ee5a09c65c5c977a3
refs/heads/master
2023-03-22T20:41:56.334534
2021-03-12T04:07:58
2021-03-12T04:07:58
296,007,238
2
0
null
null
null
null
GB18030
C++
false
false
1,127
h
#pragma once #include<iostream> #include<vector> #include<algorithm> using namespace std; void myprint(int val) { cout << val<<endl; } void test01() { //STEP1 : 声明一个Vector,类型为int vector<int> V1; //可以不指定vector的长度 vector<int>v2(10, 0); // 可以指定vector的长度为10,第一个元素为0 // STEP2: 向Vector中添加内置的数据类型 // 使用push_back 函数进行 V1.push_back(10); V1.push_back(20); V1.push_back(30); // 直接循环赋值 for (int i = 0;i < 10;i++) { v2[i] = i; } //使用Insert 函数在某个位置进行插值操作 //V1.insert(V1.begin() + 3, 100); //在第四个位置插入100这个元素 // STEP 3 遍历vector数组 //需要使用迭代器 // 方法一:使用迭代器 vector<int>::iterator itbeigin = v2.begin(); vector<int>::iterator itEnd = v2.end(); while (itbeigin != itEnd) { cout << *itbeigin << endl; itbeigin++; } cout << v2.size() << endl; //方法2: 直接使用 for (int i = 0;i < v2.size(); i++) { cout << v2[i] << endl; } //使用内置算法 for_each(v2.begin(), v2.end(), myprint); }
[ "Luke-Liu2020@qq.com" ]
Luke-Liu2020@qq.com
b60cf53f2cf12f55e054115ea6711843123a992b
66fad47ebc33fb401e75948620004671643c26f3
/src/test/transaction_tests.cpp
5582987e98d3147243f4adffd45e32e273bdb384
[ "MIT" ]
permissive
TheQuantumCoin/QuantumCoin
903c4ef204ac61aad4cddbadf7ef4500d55c4f54
740a549bc0e9eee1d64ccde221af2d5250455986
refs/heads/master
2021-01-22T06:44:17.882676
2014-03-08T17:42:04
2014-03-08T17:42:04
17,347,677
0
1
null
null
null
null
UTF-8
C++
false
false
11,159
cpp
#include <map> #include <string> #include <boost/test/unit_test.hpp> #include "json/json_spirit_writer_template.h" #include "main.h" #include "wallet.h" using namespace std; using namespace json_spirit; // In script_tests.cpp extern Array read_json(const std::string& filename); extern CScript ParseScript(string s); BOOST_AUTO_TEST_SUITE(transaction_tests) BOOST_AUTO_TEST_CASE(tx_valid) { // Read tests from test/data/tx_valid.json // Format is an array of arrays // Inner arrays are either [ "comment" ] // or [[[prevout hash, prevout index, prevout scriptPubKey], [input 2], ...],"], serializedTransaction, enforceP2SH // ... where all scripts are stringified scripts. Array tests = read_json("tx_valid.json"); BOOST_FOREACH(Value& tv, tests) { Array test = tv.get_array(); string strTest = write_string(tv, false); if (test[0].type() == array_type) { if (test.size() != 3 || test[1].type() != str_type || test[2].type() != bool_type) { BOOST_ERROR("Bad test: " << strTest); continue; } map<COutPoint, CScript> mapprevOutScriptPubKeys; Array inputs = test[0].get_array(); bool fValid = true; BOOST_FOREACH(Value& input, inputs) { if (input.type() != array_type) { fValid = false; break; } Array vinput = input.get_array(); if (vinput.size() != 3) { fValid = false; break; } mapprevOutScriptPubKeys[COutPoint(uint256(vinput[0].get_str()), vinput[1].get_int())] = ParseScript(vinput[2].get_str()); } if (!fValid) { BOOST_ERROR("Bad test: " << strTest); continue; } string transaction = test[1].get_str(); CDataStream stream(ParseHex(transaction), SER_NETWORK, PROTOCOL_VERSION); CTransaction tx; stream >> tx; CValidationState state; BOOST_CHECK_MESSAGE(tx.CheckTransaction(state), strTest); BOOST_CHECK(state.IsValid()); for (unsigned int i = 0; i < tx.vin.size(); i++) { if (!mapprevOutScriptPubKeys.count(tx.vin[i].prevout)) { BOOST_ERROR("Bad test: " << strTest); break; } BOOST_CHECK_MESSAGE(VerifyScript(tx.vin[i].scriptSig, mapprevOutScriptPubKeys[tx.vin[i].prevout], tx, i, test[2].get_bool() ? SCRIPT_VERIFY_P2SH : SCRIPT_VERIFY_NONE, 0), strTest); } } } } BOOST_AUTO_TEST_CASE(tx_invalid) { // Read tests from test/data/tx_invalid.json // Format is an array of arrays // Inner arrays are either [ "comment" ] // or [[[prevout hash, prevout index, prevout scriptPubKey], [input 2], ...],"], serializedTransaction, enforceP2SH // ... where all scripts are stringified scripts. Array tests = read_json("tx_invalid.json"); BOOST_FOREACH(Value& tv, tests) { Array test = tv.get_array(); string strTest = write_string(tv, false); if (test[0].type() == array_type) { if (test.size() != 3 || test[1].type() != str_type || test[2].type() != bool_type) { BOOST_ERROR("Bad test: " << strTest); continue; } map<COutPoint, CScript> mapprevOutScriptPubKeys; Array inputs = test[0].get_array(); bool fValid = true; BOOST_FOREACH(Value& input, inputs) { if (input.type() != array_type) { fValid = false; break; } Array vinput = input.get_array(); if (vinput.size() != 3) { fValid = false; break; } mapprevOutScriptPubKeys[COutPoint(uint256(vinput[0].get_str()), vinput[1].get_int())] = ParseScript(vinput[2].get_str()); } if (!fValid) { BOOST_ERROR("Bad test: " << strTest); continue; } string transaction = test[1].get_str(); CDataStream stream(ParseHex(transaction), SER_NETWORK, PROTOCOL_VERSION); CTransaction tx; stream >> tx; CValidationState state; fValid = tx.CheckTransaction(state) && state.IsValid(); for (unsigned int i = 0; i < tx.vin.size() && fValid; i++) { if (!mapprevOutScriptPubKeys.count(tx.vin[i].prevout)) { BOOST_ERROR("Bad test: " << strTest); break; } fValid = VerifyScript(tx.vin[i].scriptSig, mapprevOutScriptPubKeys[tx.vin[i].prevout], tx, i, test[2].get_bool() ? SCRIPT_VERIFY_P2SH : SCRIPT_VERIFY_NONE, 0); } BOOST_CHECK_MESSAGE(!fValid, strTest); } } } BOOST_AUTO_TEST_CASE(basic_transaction_tests) { // Random real transaction (e2769b09e784f32f62ef849763d4f45b98e07ba658647343b915ff832b110436) unsigned char ch[] = {0x01, 0x00, 0x00, 0x00, 0x01, 0x6b, 0xff, 0x7f, 0xcd, 0x4f, 0x85, 0x65, 0xef, 0x40, 0x6d, 0xd5, 0xd6, 0x3d, 0x4f, 0xf9, 0x4f, 0x31, 0x8f, 0xe8, 0x20, 0x27, 0xfd, 0x4d, 0xc4, 0x51, 0xb0, 0x44, 0x74, 0x01, 0x9f, 0x74, 0xb4, 0x00, 0x00, 0x00, 0x00, 0x8c, 0x49, 0x30, 0x46, 0x02, 0x21, 0x00, 0xda, 0x0d, 0xc6, 0xae, 0xce, 0xfe, 0x1e, 0x06, 0xef, 0xdf, 0x05, 0x77, 0x37, 0x57, 0xde, 0xb1, 0x68, 0x82, 0x09, 0x30, 0xe3, 0xb0, 0xd0, 0x3f, 0x46, 0xf5, 0xfc, 0xf1, 0x50, 0xbf, 0x99, 0x0c, 0x02, 0x21, 0x00, 0xd2, 0x5b, 0x5c, 0x87, 0x04, 0x00, 0x76, 0xe4, 0xf2, 0x53, 0xf8, 0x26, 0x2e, 0x76, 0x3e, 0x2d, 0xd5, 0x1e, 0x7f, 0xf0, 0xbe, 0x15, 0x77, 0x27, 0xc4, 0xbc, 0x42, 0x80, 0x7f, 0x17, 0xbd, 0x39, 0x01, 0x41, 0x04, 0xe6, 0xc2, 0x6e, 0xf6, 0x7d, 0xc6, 0x10, 0xd2, 0xcd, 0x19, 0x24, 0x84, 0x78, 0x9a, 0x6c, 0xf9, 0xae, 0xa9, 0x93, 0x0b, 0x94, 0x4b, 0x7e, 0x2d, 0xb5, 0x34, 0x2b, 0x9d, 0x9e, 0x5b, 0x9f, 0xf7, 0x9a, 0xff, 0x9a, 0x2e, 0xe1, 0x97, 0x8d, 0xd7, 0xfd, 0x01, 0xdf, 0xc5, 0x22, 0xee, 0x02, 0x28, 0x3d, 0x3b, 0x06, 0xa9, 0xd0, 0x3a, 0xcf, 0x80, 0x96, 0x96, 0x8d, 0x7d, 0xbb, 0x0f, 0x91, 0x78, 0xff, 0xff, 0xff, 0xff, 0x02, 0x8b, 0xa7, 0x94, 0x0e, 0x00, 0x00, 0x00, 0x00, 0x19, 0x76, 0xa9, 0x14, 0xba, 0xde, 0xec, 0xfd, 0xef, 0x05, 0x07, 0x24, 0x7f, 0xc8, 0xf7, 0x42, 0x41, 0xd7, 0x3b, 0xc0, 0x39, 0x97, 0x2d, 0x7b, 0x88, 0xac, 0x40, 0x94, 0xa8, 0x02, 0x00, 0x00, 0x00, 0x00, 0x19, 0x76, 0xa9, 0x14, 0xc1, 0x09, 0x32, 0x48, 0x3f, 0xec, 0x93, 0xed, 0x51, 0xf5, 0xfe, 0x95, 0xe7, 0x25, 0x59, 0xf2, 0xcc, 0x70, 0x43, 0xf9, 0x88, 0xac, 0x00, 0x00, 0x00, 0x00, 0x00}; vector<unsigned char> vch(ch, ch + sizeof(ch) -1); CDataStream stream(vch, SER_DISK, CLIENT_VERSION); CTransaction tx; stream >> tx; CValidationState state; BOOST_CHECK_MESSAGE(tx.CheckTransaction(state) && state.IsValid(), "Simple deserialized transaction should be valid."); // Check that duplicate txins fail tx.vin.push_back(tx.vin[0]); BOOST_CHECK_MESSAGE(!tx.CheckTransaction(state) || !state.IsValid(), "Transaction with duplicate txins should be invalid."); } // // Helper: create two dummy transactions, each with // two outputs. The first has 11 and 50 CENT outputs // paid to a TX_PUBKEY, the second 21 and 22 CENT outputs // paid to a TX_PUBKEYHASH. // static std::vector<CTransaction> SetupDummyInputs(CBasicKeyStore& keystoreRet, CCoinsView & coinsRet) { std::vector<CTransaction> dummyTransactions; dummyTransactions.resize(2); // Add some keys to the keystore: CKey key[4]; for (int i = 0; i < 4; i++) { key[i].MakeNewKey(i % 2); keystoreRet.AddKey(key[i]); } // Create some dummy input transactions dummyTransactions[0].vout.resize(2); dummyTransactions[0].vout[0].nValue = 11*CENT; dummyTransactions[0].vout[0].scriptPubKey << key[0].GetPubKey() << OP_CHECKSIG; dummyTransactions[0].vout[1].nValue = 50*CENT; dummyTransactions[0].vout[1].scriptPubKey << key[1].GetPubKey() << OP_CHECKSIG; coinsRet.SetCoins(dummyTransactions[0].GetHash(), CCoins(dummyTransactions[0], 0)); dummyTransactions[1].vout.resize(2); dummyTransactions[1].vout[0].nValue = 21*CENT; dummyTransactions[1].vout[0].scriptPubKey.SetDestination(key[2].GetPubKey().GetID()); dummyTransactions[1].vout[1].nValue = 22*CENT; dummyTransactions[1].vout[1].scriptPubKey.SetDestination(key[3].GetPubKey().GetID()); coinsRet.SetCoins(dummyTransactions[1].GetHash(), CCoins(dummyTransactions[1], 0)); return dummyTransactions; } BOOST_AUTO_TEST_CASE(test_Get) { CBasicKeyStore keystore; CCoinsView coinsDummy; CCoinsViewCache coins(coinsDummy); std::vector<CTransaction> dummyTransactions = SetupDummyInputs(keystore, coins); CTransaction t1; t1.vin.resize(3); t1.vin[0].prevout.hash = dummyTransactions[0].GetHash(); t1.vin[0].prevout.n = 1; t1.vin[0].scriptSig << std::vector<unsigned char>(65, 0); t1.vin[1].prevout.hash = dummyTransactions[1].GetHash(); t1.vin[1].prevout.n = 0; t1.vin[1].scriptSig << std::vector<unsigned char>(65, 0) << std::vector<unsigned char>(33, 4); t1.vin[2].prevout.hash = dummyTransactions[1].GetHash(); t1.vin[2].prevout.n = 1; t1.vin[2].scriptSig << std::vector<unsigned char>(65, 0) << std::vector<unsigned char>(33, 4); t1.vout.resize(2); t1.vout[0].nValue = 90*CENT; t1.vout[0].scriptPubKey << OP_1; BOOST_CHECK(t1.AreInputsStandard(coins)); BOOST_CHECK_EQUAL(t1.GetValueIn(coins), (50+21+22)*CENT); // Adding extra junk to the scriptSig should make it non-standard: t1.vin[0].scriptSig << OP_11; BOOST_CHECK(!t1.AreInputsStandard(coins)); // ... as should not having enough: t1.vin[0].scriptSig = CScript(); BOOST_CHECK(!t1.AreInputsStandard(coins)); } BOOST_AUTO_TEST_CASE(test_IsStandard) { CBasicKeyStore keystore; CCoinsView coinsDummy; CCoinsViewCache coins(coinsDummy); std::vector<CTransaction> dummyTransactions = SetupDummyInputs(keystore, coins); CTransaction t; t.vin.resize(1); t.vin[0].prevout.hash = dummyTransactions[0].GetHash(); t.vin[0].prevout.n = 1; t.vin[0].scriptSig << std::vector<unsigned char>(65, 0); t.vout.resize(1); t.vout[0].nValue = 90*CENT; CKey key; key.MakeNewKey(true); t.vout[0].scriptPubKey.SetDestination(key.GetPubKey().GetID()); BOOST_CHECK(t.IsStandard()); t.vout[0].nValue = 5011; // dust // Quantumcoin does not enforce isDust(). Per dust fees are considered sufficient as deterrant. // BOOST_CHECK(!t.IsStandard()); t.vout[0].nValue = 6011; // not dust BOOST_CHECK(t.IsStandard()); t.vout[0].scriptPubKey = CScript() << OP_1; BOOST_CHECK(!t.IsStandard()); } BOOST_AUTO_TEST_SUITE_END()
[ "username@computername.(none)" ]
username@computername.(none)
03ca13762d0b54cd052f450e838417cc48e9c08e
af849c8a38bc1f3932708b534c82aee0614e94a5
/android-utils/crypto/crypto-headers/dx_sha1.h
f6d3db53fa8ad8b728f6e4cbc77b4a0668be58b5
[]
no_license
losenineai/Dev-Tools
851d7f3c5e7f708071a6417d394059d8a941e6f4
55fbd1c1c3be713d81dd6a7ea7c09352b448be87
refs/heads/master
2023-05-21T06:45:19.935753
2021-06-05T04:50:33
2021-06-05T04:50:33
null
0
0
null
null
null
null
UTF-8
C++
false
false
355
h
// // Created by blue on 2018/10/15. // #ifndef CRYPTO_AS_PROJECT_DX_SHA1_H #define CRYPTO_AS_PROJECT_DX_SHA1_H #include "dx_api_prefix.h" /** * SHA1运算 */ std::string DX_SHA1(const std::string &src); /** * 带Key的SHA1运算 */ std::string DX_SHA1WithKey(const std::string &src, const std::string &key); #endif //CRYPTO_AS_PROJECT_DX_SHA1_H
[ "gimwhite@gmail.com" ]
gimwhite@gmail.com