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
986 values
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
3.89k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
23 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
145 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
122 values
content
stringlengths
3
10.4M
authors
listlengths
1
1
author_id
stringlengths
0
158
6e53a038f9bde82a6e2d5285b837276b485b87bd
bbb12cf605c71c67be438ec7548b44c9d08911be
/Day15/main.cpp
0f00a0a88289049189af3dfdf465d750f5851c93
[]
no_license
dloibl/AOC2020
69bd8538a298307186e026fed54068f1b885c221
f60f8b61311f106c95197fe8707dbdf44d9559cd
refs/heads/main
2023-02-07T16:12:06.149859
2020-12-22T11:59:25
2020-12-22T11:59:25
317,606,072
0
0
null
null
null
null
UTF-8
C++
false
false
1,194
cpp
#include "../utils.cpp" #include <map> using namespace std; int main() { vector<string> startingNumbers = split(readData("./input.txt")[0], ','); map<int, pair<int, int>> spoken; int part1Word; int turn = 1; int nextWord; int lastWord; for (auto start : startingNumbers) { auto w = stoi(start); spoken[w] = pair(turn, 0); cout << "t:" << turn << " = " << w << endl; lastWord = w; turn++; } pair<int, int> last; pair<int, int> next; while (turn < 30000001) { if (turn == 2021) { part1Word = lastWord; } last = spoken[lastWord]; nextWord = !last.second ? 0 : last.second - last.first; next = spoken[nextWord]; if (!next.first) { spoken[nextWord] = pair(turn, 0); } else { if (next.second) spoken[nextWord].first = next.second; spoken[nextWord].second = turn; } lastWord = nextWord; turn++; } cout << "the answer to part 1 is: " << part1Word << endl; cout << "the answer to part 2 is: " << nextWord << endl; }
[ "daniel.loibl@gmail.com" ]
daniel.loibl@gmail.com
cc11697e7ad01b051f1be7b5cd80e054313c6038
5ea0705061ed9620ff420e66d0faff4f4b3563a2
/src/pofPath.h
7d6c20301f453b7da2f262476f4c57e7a949dc07
[ "BSD-3-Clause", "BSD-2-Clause" ]
permissive
Ant1r/ofxPof
69cc87686c0f6839e616f7cde601bacc0aaeaeb3
b80210527454484f64003b7a09c8e7f9f8a09ac3
refs/heads/master
2023-08-02T21:30:28.542262
2021-06-28T11:05:03
2021-06-28T11:05:03
32,018,528
68
8
null
null
null
null
UTF-8
C++
false
false
525
h
/* * Copyright (c) 2014 Antoine Rousseau <antoine@metalu.net> * BSD Simplified License, see the file "LICENSE.txt" in this distribution. * See https://github.com/Ant1r/ofxPof for documentation and updates. */ #pragma once #include "pofBase.h" class pofPath; class pofPath: public pofBase { public: pofPath(t_class *Class): pofBase(Class), doMesh(false) { } ofPath path; ofPoint scale; bool doMesh; virtual void draw(); virtual void message(int arc, t_atom *argv); static void setup(void); };
[ "_antoine_@metalu.net" ]
_antoine_@metalu.net
ebb22c97b0b2329ae1524e3c64050b28265675b0
3a4bafe20521cf34d723f3524f79c72a586288ec
/src/qt/networkstyle.h
c05ccb3af074653a0d8972f1b84ae592242d6f71
[ "MIT" ]
permissive
kiragame-team/strengthcore
6152914b049638ce566b56184baf78ca9efd07e0
63c130758b115f71f69fe8d93c7aa776cb1ebe13
refs/heads/master
2020-04-24T15:43:53.592225
2019-03-13T07:57:45
2019-03-13T07:57:45
172,080,017
0
0
MIT
2019-03-08T07:47:40
2019-02-22T14:28:31
C++
UTF-8
C++
false
false
1,341
h
// Copyright (c) 2014 The Bitcoin Core developers // Copyright (c) 2014-2017 The STRENGTH Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef BITCOIN_QT_NETWORKSTYLE_H #define BITCOIN_QT_NETWORKSTYLE_H #include <QIcon> #include <QPixmap> #include <QString> /* Coin network-specific GUI style information */ class NetworkStyle { public: /** Get style associated with provided BIP70 network id, or 0 if not known */ static const NetworkStyle *instantiate(const QString &networkId); const QString &getAppName() const { return appName; } const QIcon &getAppIcon() const { return appIcon; } const QPixmap &getSplashImage() const { return splashImage; } const QIcon &getTrayAndWindowIcon() const { return trayAndWindowIcon; } const QString &getTitleAddText() const { return titleAddText; } private: NetworkStyle(const QString &appName, const int iconColorHueShift, const int iconColorSaturationReduction, const char *titleAddText); QString appName; QIcon appIcon; QPixmap splashImage; QIcon trayAndWindowIcon; QString titleAddText; void rotateColors(QImage& img, const int iconColorHueShift, const int iconColorSaturationReduction); }; #endif // BITCOIN_QT_NETWORKSTYLE_H
[ "kiragame.team@gmail.com" ]
kiragame.team@gmail.com
29cf6b67bf9190a74dcda410d6e41667e3076912
525dcc2e1e43c381f965cc12059c28e0142d50d0
/src/AssetManager.hpp
cff728b3b929c31fdf2e96c6e637135c6195be87
[]
no_license
sagarPakhrin/sfml-starter-template
ee1925bda2f46448578799f6d1e78a1c311ecc9f
080fdfa4ac9353e4eb5a31433a12caf29853a974
refs/heads/master
2020-06-28T11:27:17.136739
2019-08-11T12:26:05
2019-08-11T12:26:05
200,221,916
1
1
null
null
null
null
UTF-8
C++
false
false
499
hpp
#pragma once #include <SFML/Graphics.hpp> #include <map> namespace Sagar { class AssetManager { public: AssetManager(){}; ~AssetManager(){}; void LoadTexture(std::string name,std::string fileName); sf::Texture &GetTexture(std::string name); void LoadFont(std::string name,std::string fileName); sf::Font &GetFont(std::string name); private: std::map<std::string, sf::Texture> _textures; std::map<std::string, sf::Font> _fonts; }; }
[ "sagarlama826@gmail.com" ]
sagarlama826@gmail.com
0d6bd08d0828e60c67e5349be6a153b98dfc67f6
8000180e9d07edd70d069a2ec7c42a2b2ffeecd2
/entity/body.cpp
af08acba3e5dff811a9ad5bda0dbab21289d2dea
[]
no_license
oyvindskog/lunarLander
3beedc476046093333944603715d1e797b884d86
4b828685ba5b8b0f898fa73df1409a3b1e9ac4af
refs/heads/master
2021-06-01T21:13:25.994866
2020-04-09T07:57:50
2020-04-09T07:57:50
254,314,029
0
0
null
null
null
null
UTF-8
C++
false
false
613
cpp
#include "body.h" body::body(entity *e, vector2d &&position, std::vector<part> &parts) : component(e), _position(position), _parts(parts) {} void body::add_part(part &&p) { _parts.emplace_back(p); } void body::render(SDL_Renderer *renderer) const { for (auto p : _parts) { p.v += _position; SDL_Rect rect = {static_cast<int>(p.v.get_x()), static_cast<int>(p.v.get_y()), 2, 2}; SDL_SetRenderDrawColor(renderer, p.red, p.green, p.blue, 255); SDL_RenderFillRect(renderer, &rect); } } void body::rotate(float angle) { for (auto &p : _parts) p.v.rotate(angle); }
[ "oyvindskogstrand@gmail.com" ]
oyvindskogstrand@gmail.com
65b5286ba30fe7edff8ab7b36e6343853f35272d
0eff74b05b60098333ad66cf801bdd93becc9ea4
/second/download/httpd/gumtree/httpd_old_hunk_3272.cpp
428a7441439144fcaf169904b1fad18da3895e4b
[]
no_license
niuxu18/logTracker-old
97543445ea7e414ed40bdc681239365d33418975
f2b060f13a0295387fe02187543db124916eb446
refs/heads/master
2021-09-13T21:39:37.686481
2017-12-11T03:36:34
2017-12-11T03:36:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,419
cpp
|| r->status != HTTP_OK || c->aborted) { return OK; } else { /* no way to know what type of error occurred */ ap_log_rerror(APLOG_MARK, APLOG_DEBUG, status, r, "default_handler: ap_pass_brigade returned %i", status); return HTTP_INTERNAL_SERVER_ERROR; } } else { /* unusual method (not GET or POST) */ if (r->method_number == M_INVALID) { /* See if this looks like an undecrypted SSL handshake attempt. * It's safe to look a couple bytes into the_request if it exists, as it's * always allocated at least MIN_LINE_ALLOC (80) bytes. */ if (r->the_request && r->the_request[0] == 0x16 && (r->the_request[1] == 0x2 || r->the_request[1] == 0x3)) { ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "Invalid method in request %s - possible attempt to establish SSL connection on non-SSL port", r->the_request); } else { ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, "Invalid method in request %s", r->the_request); } return HTTP_NOT_IMPLEMENTED; } if (r->method_number == M_OPTIONS) {
[ "993273596@qq.com" ]
993273596@qq.com
7dd760614fb5018c7673f22bfa97ca57f3bde1ba
0de27940c1e817befa533106cf7df0357614cea9
/src/qt/clientmodel.h
40a9f915a16e286be7764e863fd1753dfe13a392
[ "MIT" ]
permissive
RocketFund/RocketFundCoin
deda5a0bd01b4feb32686bc209e4515d85699061
8acb4bdbc113c2aa5df46da6af576822bc48857e
refs/heads/master
2020-09-12T19:25:12.205148
2019-11-26T00:51:37
2019-11-26T00:51:37
222,525,768
4
1
null
null
null
null
UTF-8
C++
false
false
3,408
h
// Copyright (c) 2011-2014 The Bitcoin developers // Copyright (c) 2014-2015 The Dash developers // Copyright (c) 2015-2018 The ROCKETFUNDCOIN developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef BITCOIN_QT_CLIENTMODEL_H #define BITCOIN_QT_CLIENTMODEL_H #include "uint256.h" #include <QObject> #include <QDateTime> class AddressTableModel; class BanTableModel; class OptionsModel; class PeerTableModel; class TransactionTableModel; class CWallet; QT_BEGIN_NAMESPACE class QDateTime; class QTimer; QT_END_NAMESPACE enum BlockSource { BLOCK_SOURCE_NONE, BLOCK_SOURCE_REINDEX, BLOCK_SOURCE_DISK, BLOCK_SOURCE_NETWORK }; enum NumConnections { CONNECTIONS_NONE = 0, CONNECTIONS_IN = (1U << 0), CONNECTIONS_OUT = (1U << 1), CONNECTIONS_ALL = (CONNECTIONS_IN | CONNECTIONS_OUT), }; /** Model for ROCKETFUNDCOIN network client. */ class ClientModel : public QObject { Q_OBJECT public: explicit ClientModel(OptionsModel* optionsModel, QObject* parent = 0); ~ClientModel(); OptionsModel* getOptionsModel(); PeerTableModel* getPeerTableModel(); BanTableModel *getBanTableModel(); //! Return number of connections, default is in- and outbound (total) int getNumConnections(unsigned int flags = CONNECTIONS_ALL) const; QString getMasternodeCountString() const; int getNumBlocks() const; int getNumBlocksAtStartup(); quint64 getTotalBytesRecv() const; quint64 getTotalBytesSent() const; double getVerificationProgress() const; QDateTime getLastBlockDate() const; QString getLastBlockHash() const; //! Return true if core is doing initial block download bool inInitialBlockDownload() const; //! Return true if core is importing blocks enum BlockSource getBlockSource() const; //! Return warnings to be displayed in status bar QString getStatusBarWarnings() const; QString formatFullVersion() const; QString formatBuildDate() const; bool isReleaseVersion() const; QString clientName() const; QString formatClientStartupTime() const; QString dataDir() const; bool getTorInfo(std::string& ip_port) const; private: OptionsModel* optionsModel; PeerTableModel* peerTableModel; BanTableModel *banTableModel; int cachedNumBlocks; QString cachedMasternodeCountString; bool cachedReindexing; bool cachedImporting; int numBlocksAtStartup; QTimer* pollTimer; QTimer* pollMnTimer; void subscribeToCoreSignals(); void unsubscribeFromCoreSignals(); signals: void numConnectionsChanged(int count); void numBlocksChanged(int count); void strMasternodesChanged(const QString& strMasternodes); void alertsChanged(const QString& warnings); void bytesChanged(quint64 totalBytesIn, quint64 totalBytesOut); //! Fired when a message should be reported to the user void message(const QString& title, const QString& message, unsigned int style); // Show progress dialog e.g. for verifychain void showProgress(const QString& title, int nProgress); public slots: void updateTimer(); void updateMnTimer(); void updateNumConnections(int numConnections); void updateAlert(const QString& hash, int status); void updateBanlist(); }; #endif // BITCOIN_QT_CLIENTMODEL_H
[ "57466496+RocketFund@users.noreply.github.com" ]
57466496+RocketFund@users.noreply.github.com
b4650a4f5c3338793ab0aa0f41512b5a99893308
9bdcd5ce87a5bdb6dea11084db933a24d5b4891b
/RayTracing/RayTracingRunner/RayTracingRunner.cpp
6615c65048d6de51c853118f8d73dfab44dc89d4
[]
no_license
yichaozhao/Workplace
3bcc35b4162d2ca115e3d243b42d634f271fe632
0302f63a01ec72a9d7098ac1a34a4d82862ab8e5
refs/heads/master
2020-05-20T01:48:27.264860
2015-09-04T03:09:29
2015-09-04T03:09:29
40,741,903
0
0
null
null
null
null
UTF-8
C++
false
false
232
cpp
#include "RayTracer.h" #include <iostream> #include "Dot.h" int main() { std::cout << "It Works!\n"; Geom::Dot a(0, 0, 0); Geom::Object& b = a; std::cout << a.toString() + "\n"; std::cout << b.toString() + "\n"; return 0; }
[ "zhaoyichao@gmail.com" ]
zhaoyichao@gmail.com
e1ee114c8ca3cdc6e0449b63ca1ab9185c1e5783
a71582e89e84a4fae2595f034d06af6d8ad2d43a
/tensorflow/core/grappler/optimizers/graph_optimizer.h
44dfe0de7890f09feb0b2cbfc450ddb9e37fc3cd
[ "Apache-2.0" ]
permissive
tfboyd/tensorflow
5328b1cabb3e24cb9534480fe6a8d18c4beeffb8
865004e8aa9ba630864ecab18381354827efe217
refs/heads/master
2021-07-06T09:41:36.700837
2019-04-01T20:21:03
2019-04-01T20:26:09
91,494,603
3
0
Apache-2.0
2018-07-17T22:45:10
2017-05-16T19:06:01
C++
UTF-8
C++
false
false
2,944
h
/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #ifndef TENSORFLOW_CORE_GRAPPLER_OPTIMIZERS_GRAPH_OPTIMIZER_H_ #define TENSORFLOW_CORE_GRAPPLER_OPTIMIZERS_GRAPH_OPTIMIZER_H_ #include <string> #include "tensorflow/core/framework/graph.pb.h" #include "tensorflow/core/lib/core/status.h" #include "tensorflow/core/platform/env.h" namespace tensorflow { namespace grappler { class Cluster; struct GrapplerItem; // An abstract interface for an algorithm for generating a candidate // optimization of a GrapplerItem for running on a cluster. class GraphOptimizer { public: GraphOptimizer() : deadline_usec_(0) {} virtual ~GraphOptimizer() {} virtual string name() const = 0; // Routine called to allow an algorithm to propose a rewritten graph // for the graph, feeds and fetches in "item" to run more efficiently // on "cluster". // Returns an error status if it failed to generate a solution. virtual Status Optimize(Cluster* cluster, const GrapplerItem& item, GraphDef* optimized_graph) = 0; // Method invoked by the framework so that it can provide feedback // on how well the "optimized_graph" (produced as *optimized_graph from a // call to Optimize) performed. Lower "result" scores are better. virtual void Feedback(Cluster* cluster, const GrapplerItem& item, const GraphDef& optimized_graph, double result) = 0; // Set deadline in microseconds since epoch. A value of zero means no // deadline. void set_deadline_usec(uint64 deadline_usec) { deadline_usec_ = deadline_usec; } uint64 deadline_usec() const { return deadline_usec_; } bool DeadlineExceeded() const { return deadline_usec_ > 0 && Env::Default()->NowMicros() > deadline_usec_; } private: uint64 deadline_usec_; }; #define GRAPPLER_RETURN_IF_DEADLINE_EXCEEDED() \ do { \ if (this->DeadlineExceeded()) { \ return errors::DeadlineExceeded(this->name(), " exceeded deadline."); \ } \ } while (0) } // end namespace grappler } // end namespace tensorflow #endif // TENSORFLOW_CORE_GRAPPLER_OPTIMIZERS_GRAPH_OPTIMIZER_H_
[ "gardener@tensorflow.org" ]
gardener@tensorflow.org
dbbd25f84c5dd2fcc75b31ec55d5f8127dd5a41f
c77b2f06a971d5e77a3dc71e972ef27fc85475a5
/ideone/ideone_I8fM1H.cpp
011bc831978ae43accad93ae91d4eab171a961be
[]
no_license
thefr33radical/codeblue
f25520ea85110ed09b09ae38e7db92bab8285b2f
86bf4a4ba693b1797564dca66b645487973dafa4
refs/heads/master
2022-08-01T19:05:09.486567
2022-07-18T22:56:05
2022-07-18T22:56:05
110,525,490
3
6
null
null
null
null
UTF-8
C++
false
false
2,586
cpp
// C++ program for a Trie based O(n) solution to find max // subarray XOR #include<bits/stdc++.h> using namespace std; // Assumed int size #define INT_SIZE 32 // A Trie Node struct TrieNode { int value; // Only used in leaf nodes TrieNode *arr[2]; }; // Utility function tp create a Trie node TrieNode *newNode() { TrieNode *temp = new TrieNode; temp->value = 0; temp->arr[0] = temp->arr[1] = NULL; return temp; } // Inserts pre_xor to trie with given root void insert(TrieNode *root, int pre_xor) { TrieNode *temp = root; // Start from the msb, insert all bits of // pre_xor into Trie for (int i=INT_SIZE-1; i>=0; i--) { // Find current bit in given prefix bool val = pre_xor & (1<<i); // Create a new node if needed if (temp->arr[val] == NULL) temp->arr[val] = newNode(); temp = temp->arr[val]; } // Store value at leaf node temp->value = pre_xor; } // Finds the maximum XOR ending with last number in // prefix XOR 'pre_xor' and returns the XOR of this maximum // with pre_xor which is maximum XOR ending with last element // of pre_xor. int query(TrieNode *root, int pre_xor) { TrieNode *temp = root; for (int i=INT_SIZE-1; i>=0; i--) { // Find current bit in given prefix bool val = pre_xor & (1<<i); // Traverse Trie, first look for a // prefix that has opposite bit if (temp->arr[1-val]!=NULL) temp = temp->arr[1-val]; // If there is no prefix with opposite // bit, then look for same bit. else if (temp->arr[val] != NULL) temp = temp->arr[val]; } return pre_xor^(temp->value); } // Returns maximum XOR value of a subarray in arr[0..n-1] int maxSubarrayXOR(int arr[], int n) { // Create a Trie and insert 0 into it TrieNode *root = newNode(); insert(root, 0); // Initialize answer and xor of current prefix int result = INT_MIN, pre_xor =0; // Traverse all input array element for (int i=0; i<n; i++) { // update current prefix xor and insert it into Trie pre_xor = pre_xor^arr[i]; insert(root, pre_xor); // Query for current prefix xor in Trie and update // result if required result = max(result, query(root, pre_xor)); } return result; } // Driver program to test above functions int main() { int arr[] = {5,1,2,3,5}; int n = sizeof(arr)/sizeof(arr[0]); cout << "Max subarray XOR is " << maxSubarrayXOR(arr, n); return 0; }
[ "noreply@github.com" ]
thefr33radical.noreply@github.com
a4c23c1be6219dc16ae9bd8c73cd1aca0ac424be
30602b4dd984837beb7b9c23bf3f20e22e11b53d
/Day 3 - Medium (Level 2)/Mailbox/Mailbox.cpp
662838ea7fa7e20b76a49179012eaacabc51175c
[]
no_license
sidgujrathi/topcoder
fae7188965f71c880805af838664c082b89f0965
d157ef0b02876b528fa3c4a451afccc2442ee165
refs/heads/master
2021-01-10T03:17:11.702146
2015-10-01T05:57:59
2015-10-01T05:57:59
43,119,043
0
0
null
null
null
null
UTF-8
C++
false
false
3,828
cpp
// BEGIN CUT HERE // END CUT HERE #include <algorithm> #include <iostream> #include <sstream> #include <string> #include <vector> #include <queue> #include <set> #include <map> #include <cstdio> #include <cstdlib> #include <cctype> #include <cmath> using namespace std; vector<string> split( const string& s, const string& delim =" " ) { vector<string> res; string t; for ( int i = 0 ; i != s.size() ; i++ ) { if ( delim.find( s[i] ) != string::npos ) { if ( !t.empty() ) { res.push_back( t ); t = ""; } } else { t += s[i]; } } if ( !t.empty() ) { res.push_back(t); } return res; } vector<int> splitInt( const string& s, const string& delim =" " ) { vector<string> tok = split( s, delim ); vector<int> res; for ( int i = 0 ; i != tok.size(); i++ ) res.push_back( atoi( tok[i].c_str() ) ); return res; } // BEGIN CUT HERE #define ARRSIZE(x) (sizeof(x)/sizeof(x[0])) template<typename T> void print( T a ) { cerr << a; } static void print( long long a ) { cerr << a << "L"; } static void print( string a ) { cerr << '"' << a << '"'; } template<typename T> void print( vector<T> a ) { cerr << "{"; for ( int i = 0 ; i != a.size() ; i++ ) { if ( i != 0 ) cerr << ", "; print( a[i] ); } cerr << "}" << endl; } template<typename T> void eq( int n, T have, T need ) { if ( have == need ) { cerr << "Case " << n << " passed." << endl; } else { cerr << "Case " << n << " failed: expected "; print( need ); cerr << " received "; print( have ); cerr << "." << endl; } } template<typename T> void eq( int n, vector<T> have, vector<T> need ) { if( have.size() != need.size() ) { cerr << "Case " << n << " failed: returned " << have.size() << " elements; expected " << need.size() << " elements."; print( have ); print( need ); return; } for( int i= 0; i < have.size(); i++ ) { if( have[i] != need[i] ) { cerr << "Case " << n << " failed. Expected and returned array differ in position " << i << "."; print( have ); print( need ); return; } } cerr << "Case " << n << " passed." << endl; } static void eq( int n, string have, string need ) { if ( have == need ) { cerr << "Case " << n << " passed." << endl; } else { cerr << "Case " << n << " failed: expected "; print( need ); cerr << " received "; print( have ); cerr << "." << endl; } } // END CUT HERE class Mailbox { public: int impossible(string collection, vector <string> address) { int res; return res; } }; // BEGIN CUT HERE void main( int argc, char* argv[] ) { { string addressARRAY[] = {"123C","123A","123 ADA"}; vector <string> address( addressARRAY, addressARRAY+ARRSIZE(addressARRAY) ); Mailbox theObject; eq(0, theObject.impossible("AAAAAAABBCCCCCDDDEEE123456789", address),0); } { string addressARRAY[] = {"2 FIRST ST"," 31 QUINCE ST", "606 BAKER"}; vector <string> address( addressARRAY, addressARRAY+ARRSIZE(addressARRAY) ); Mailbox theObject; eq(1, theObject.impossible("ABCDEFGHIJKLMNOPRSTUVWXYZ1234567890", address),3); } { string addressARRAY[] = {"111 A ST", "A BAD ST", "B BAD ST"}; vector <string> address( addressARRAY, addressARRAY+ARRSIZE(addressARRAY) ); Mailbox theObject; eq(2, theObject.impossible("ABCDAAST", address),2); } } // END CUT HERE
[ "sidh.gujrathi@gmail.com" ]
sidh.gujrathi@gmail.com
dae3ff1e458ddc90932c84adb485325ee7fa4ec7
bc7af3a168a49bc0f603782f8322005c17ef066c
/HookDll/Global.h
a11eb27b16f3bad5a8a23a43f7e647ae93546a18
[]
no_license
chen3/HookWindowActivity
9598dd50c2f81ea4176c5488a8f2e87a0d670c60
cac9946968e3f0e8662bc7c26d9859c4a4eae3bb
refs/heads/master
2021-01-23T22:14:52.475773
2017-02-25T09:19:57
2017-02-25T09:19:57
83,120,793
0
0
null
null
null
null
UTF-8
C++
false
false
231
h
#pragma once #include "stdafx.h" class Global { public: static bool isInstall(); static void log(std::string s); static void install(); static void installIfNotInstall(); static bool uninstall(); private: Global() { } };
[ "chen3@qiditu.cn" ]
chen3@qiditu.cn
e2a0a83b71c5be4ff7355f854996277515399d35
38a37712c87e8b569061f23722e7a07415e0d1ac
/code/Módulo Pulsador LED/moduloPulsadorLed/moduloPulsadorLed.ino
dfa0e44eaf11d37af23311086f8452ff410e3fcf
[]
no_license
elenieto/fcb1010
f6084d80492b243a874431024ca5cd91756d5e88
5c3a1bfa2f02e1587adb299242170b12522894fc
refs/heads/main
2023-05-31T15:24:12.568324
2021-06-16T15:45:37
2021-06-16T15:45:37
361,110,719
0
0
null
null
null
null
UTF-8
C++
false
false
4,057
ino
/************************************************************* Programa que distingue 3 tipos de pulsaciones (corta, larga y doble) en un pulsador y enciende el led en consecuencia. - Corta: cambio de estado - Larga: parpadeo largo - Doble: parapadeo corto Comunicación I2C: - Envía al máster: si hay pulsación, de qué tipo y de qué botón es. - Recibe del máster: apagado y encendido de LED. - Direcciones: 16, 2, 3, 4, 5, 10, 11, 12, 13, 14 ************************************************************* Proyecto FCB1010 de Elena Nieto: https://github.com/elenieto/fcb1010 **************************************************************/ #include <twi.h> #include <TinyWire.h> #define SHORT_PULS 0 #define LONG_PULS 64 #define DOUBLE_PULS 128 // Dirección del Attiny en el bus I2C const int address = 14; // Número de pulsador const int pulsNumber = 10; //Asignación de pines int buttonPin = 3; int ledPin = 4; //Variables: entradas y salidas int last_in = HIGH; int now_in; int out = HIGH; int pulsation = 0; // Variables de tiempo const long debounceTime = 100; long lastChange = 0; long penultChange = 0; long startAwait = 0; //Otras variables boolean change = false; boolean shortPuls = false; int byteSent; int notification = 0; void setup() { TinyWire.begin(address); TinyWire.onRequest(onI2CRequest); TinyWire.onReceive( onI2CReceive ); pinMode(ledPin, OUTPUT); } void loop() { // Lectura del pin del pulsador now_in = digitalRead(buttonPin); // Si el nivel leído es bajo, el anterior era alto y ha pasado el tiempo de rebote if (now_in == LOW && last_in == HIGH && millis() - lastChange > debounceTime) { // Flanco de bajada change = true; penultChange = lastChange; lastChange = millis(); } else { // Si el nivel leído es alto, el anterior era bajo, ha pasado el tiempo de rebote // y ha habido un flanco de bajada anterior if (now_in == HIGH && last_in == LOW && millis() - lastChange > debounceTime && change == true) { // Flanco de subida change = false; // Si el tiempo entre flanco de subida y de bajada es menor que 400ms -> pulsación corta o doble if (millis() - lastChange < 400) { // Si el tiempo entre la pulsación actual y la anterior es menor que 500ms if (lastChange - penultChange < 500) { // Pulsación doble shortPuls = false; notification = 16; pulsation = DOUBLE_PULS; digitalWrite(ledPin, !out); delay(100); digitalWrite(ledPin, out); delay(100); } else { // Empieza la espera para saber si estamos ante una pulsación corta o la primera pulsación // de una doble. startAwait = millis(); shortPuls = true; } } else { // Pulsación larga pulsation = LONG_PULS; notification = 16; // Parpadeo digitalWrite(ledPin, !out); delay(100); digitalWrite(ledPin, out); delay(100); digitalWrite(ledPin, !out); delay(100); digitalWrite(ledPin, out); delay(100); digitalWrite(ledPin, !out); delay(100); digitalWrite(ledPin, out); delay(100); digitalWrite(ledPin, !out); delay(100); } } else { // Si se cumple la espera sin que haya habido otra pulsación if (shortPuls == true && millis() - startAwait > 300) { // Pulsación corta pulsation = SHORT_PULS; notification = 16; out = !out; shortPuls = false; } } } digitalWrite(ledPin, out); // envía a la salida ́led ́el valor leído last_in = now_in; } void onI2CRequest() { // Se forma un byte con la información que recibirá el máster byteSent = pulsation + pulsNumber + notification; TinyWire.write(byteSent); notification = 0; } // ESP32 enciende o apaga LED void onI2CReceive(int howMany) { while (TinyWire.available() > 0) { out = TinyWire.read() ? LOW : HIGH; } }
[ "noreply@github.com" ]
elenieto.noreply@github.com
a75df37088739fa342da2c3a42de4d5a3572dd85
b0368adc2331e1d0b770aeae1773b15ad81072d7
/include/GnssErrorModel.h
26e675f4a8d676decdf6b0a6421ce0d6f4e87cbe
[]
no_license
neophack/PPPLib_v2.0
c3774c285ef8195137f22357604eb2aba789f45f
344f973ea3de74d1db1823988662a5162f6d0080
refs/heads/master
2022-12-05T12:08:38.409433
2020-08-17T02:45:50
2020-08-17T02:45:50
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,520
h
// // Created by cc on 7/19/20. // #ifndef PPPLIB_GNSSERRORMODEL_H #define PPPLIB_GNSSERRORMODEL_H #include "GnssFunc.h" using namespace PPPLib; namespace PPPLib{ class cGnssModel{ public: cGnssModel(); virtual ~cGnssModel(); public: virtual void InitErrModel(tPPPLibConf C); void InitSatInfo(tSatInfoUnit* sat_info,Vector3d* blh); virtual void UpdateSatInfo(); public: // tNav nav_; tSatInfoUnit* sat_info_; Vector3d blh_; tPPPLibConf PPPLibC_; }; class cTrpDelayModel: public cGnssModel { public: cTrpDelayModel(); cTrpDelayModel(Vector3d blh,tSatInfoUnit& sat_info); ~cTrpDelayModel(); public: Vector2d GetTrpError(double humi,double *x,int it); Vector2d GetSaasTrp(double humi,Vector2d* sat_trp_dry, Vector4d* sat_trp_wet); void UpdateSatInfo() override; void InitTrpModel(Vector3d& blh); private: bool SaasModel(double humi); Vector4d EstTrpWet(double humi,double *x,int it); void TrpMapNeil(cTime t,double el); private: Vector2d zenith_trp_={0,0}; //dry, wet Vector2d slant_trp_dry_={0,0}; //dry, map_dry Vector4d slant_trp_wet_={0,0,0,0}; //wet, map_wet,grand_e,grand_n }; class cIonDelayModel: public cGnssModel { public: cIonDelayModel(); cIonDelayModel(Vector3d blh,tSatInfoUnit& sat_info,tNav nav); ~cIonDelayModel(); public: Vector2d GetIonError(); Vector2d GetKlobIon(); void UpdateSatInfo() override; void InitIondelayModel(double ion_para[NSYS][8]); private: bool KlobModel(); bool GimModel(); bool IonFreeModel(); bool IonEstModel(); private: double ion_para_[NSYS][8]={{0}}; Vector2d ion_delay_; // L1_ion/ion_map }; class cCbiasModel:public cGnssModel { public: cCbiasModel(); cCbiasModel(tNav nav,tSatInfoUnit& sat_info); ~cCbiasModel(); public: void GetCodeBias(); void InitCbiasModel(double cbias[MAX_SAT_NUM][MAX_GNSS_CODE_BIAS_PAIRS],vector<tBrdEphUnit>& brd_eph); void UpdateSatInfo() override; private: void TgdModel(); void BsxModel(); private: double code_bias_[MAX_SAT_NUM][MAX_GNSS_CODE_BIAS_PAIRS]={{0}}; vector<tBrdEphUnit> brd_eph_; private: double cbias_[NSYS+1][MAX_GNSS_FRQ_NUM]={{0}}; }; class cAntModel:public cGnssModel { public: cAntModel(); ~cAntModel(); private: double InterpPcv(double ang,const double *var); double InterpAziPcv(const tAntUnit& ant,double az,double ze,int f); void SatPcvModel(tSatInfoUnit* sat_info,double nadir,double* dant); public: void InitAntModel(tPPPLibConf C,tAntUnit sat_ant[MAX_SAT_NUM],tAntUnit rec_ant[2]); void SatPcvCorr(tSatInfoUnit* sat_info,Vector3d rec_pos,double* pcv_dants); void RecAntCorr(tSatInfoUnit* sat_info,double* dantr,RECEIVER_INDEX rec_idx); private: tAntUnit *sat_ant_; tAntUnit *rec_ant_; }; class cEphModel:public cGnssModel { public: cEphModel(); ~cEphModel(); private: // broadcast int SelectBrdEph(tSatInfoUnit* sat_info,int iode); int SelectGloBrdEph(tSatInfoUnit* sat_info,int iode); void BrdSatClkErr(tSatInfoUnit* sat_info,tBrdEphUnit eph); void BrdGloSatClkErr(tSatInfoUnit* sat_info,tBrdGloEphUnit glo_eph); bool BrdClkError(tSatInfoUnit* sat_info); double EphUra(int ura); double ClkRelErr(double mu,double sinE,tBrdEphUnit eph); void BrdSatPos(tSatInfoUnit& sat_info,tBrdEphUnit eph); void GloDefEq(const VectorXd x,VectorXd& x_dot,const Vector3d acc); void GloOrbit(double t,VectorXd& x,const Vector3d acc); void BrdGloSatPos(tSatInfoUnit& sat_info,tBrdGloEphUnit glo_eph); bool BrdEphModel(tSatInfoUnit* sat_info); // precise void SatPcoCorr(tSatInfoUnit* sat_info,Vector3d sat_pos,Vector3d& dant); bool PreSatClkCorr(tSatInfoUnit* sat_info); bool PreSatPos(tSatInfoUnit* sat_info); bool PreEphModel(tSatInfoUnit* sat_info); public: bool EphCorr(vector<tSatInfoUnit>& epoch_sat_info); void InitEphModel(vector<tBrdEphUnit>& brd_eph,vector<tBrdGloEphUnit>& brd_glo_eph,vector<tPreOrbUnit>& pre_orb, vector<tPreClkUnit>& pre_clk,tAntUnit* sat_ant); private: vector<tPreClkUnit> pre_clk_; vector<tPreOrbUnit> pre_orb_; vector<tBrdEphUnit> brd_eph_; vector<tBrdGloEphUnit> brd_glo_eph_; tAntUnit *sat_ant_; }; class cTidModel:public cGnssModel { public: cTidModel(); ~cTidModel(); private: int GetErpVal(cTime t); void TideSl(const double* eu,const double* rp,double GMp,Vector3d blh,double* dr); void IersMeanPole(double *xp,double *yp); void TidSolid(); void TidOcean(); void TidPole(); public: void InitTidModel(tPPPLibConf C,vector<tErpUnit> erp,double ocean_par[2][66]); void TidCorr(cTime t,Vector3d rec_pos,Vector3d& dr); private: cTime tut_; double re_; Vector3d blh_; Matrix3d E_; Vector3d tid_dr_[3]; Vector3d denu_[2]; Vector3d sun_pos_; Vector3d moon_pos_; double gmst_; double erp_val_[5]; private: vector<tErpUnit> erp_; double ocean_par_[2][6*11]; RECEIVER_INDEX rec_idx_; }; class cGnssErrCorr { public: cGnssErrCorr(); ~cGnssErrCorr(); private: bool SatYaw(tSatInfoUnit& sat_info,Vector3d& exs,Vector3d& eys); public: void InitGnssErrCorr(tPPPLibConf C, tNav* nav); void BD2MultipathModel(tSatInfoUnit* sat_info); double SagnacCorr(Vector3d sat_xyz,Vector3d rec_xyz); double ShapiroCorr(int sys,Vector3d sat_xyz,Vector3d rec_xyz); void PhaseWindUp(tSatInfoUnit& sat_info,Vector3d rec_xyz); public: cEphModel eph_model_; cCbiasModel cbia_model_; cTrpDelayModel trp_model_; cIonDelayModel ion_model_; cAntModel ant_model_; cTidModel tid_model_; private: double bd2_mp_[3]; }; } #endif //PPPLIB_GNSSERRORMODEL_H
[ "cchen@cumt.edu.cn" ]
cchen@cumt.edu.cn
47492ec37e37effc05be499c0336f175ec8d26d7
8899a8c81e8c8657e5dfe8e94ad5e94eddf59d9e
/Source/WebMediaPlayer/Private/WebMediaPlayer.cpp
7f92d4ecb1f6f805f6544335eae482b711c8eaa5
[]
no_license
bb2002/UE4-WebMediaPlayer
40c7cedb46eaeeebaa8a095bc209c93525e37422
bab03d5e965bc2039934ef2417f0a9e10976e205
refs/heads/master
2022-06-15T21:08:05.836943
2020-05-06T13:04:03
2020-05-06T13:04:03
261,760,256
11
1
null
null
null
null
UTF-8
C++
false
false
626
cpp
// Copyright 1998-2019 Epic Games, Inc. All Rights Reserved. #include "WebMediaPlayer.h" #define LOCTEXT_NAMESPACE "FWebMediaPlayerModule" void FWebMediaPlayerModule::StartupModule() { // This code will execute after your module is loaded into memory; the exact timing is specified in the .uplugin file per-module } void FWebMediaPlayerModule::ShutdownModule() { // This function may be called during shutdown to clean up your module. For modules that support dynamic reloading, // we call this function before unloading the module. } #undef LOCTEXT_NAMESPACE IMPLEMENT_MODULE(FWebMediaPlayerModule, WebMediaPlayer)
[ "5252bb@daum.net" ]
5252bb@daum.net
89a1eb048968f8d6688e5c6cce86a5809463b3ea
d9184d5f98830195afcdba7bf79b8bde6f90db51
/src/qt/sendcoinsdialog.cpp
b081e0a71722be30b033e9c9bb0f41eba691809f
[ "MIT" ]
permissive
hexioncoin/hexion
2aeb5ebbbc13ff105d9b72d4bda49aabf8246d37
61ddcd8eef5528817b022cb5ed39b433f3762477
refs/heads/master
2016-09-06T05:56:16.185217
2014-11-13T13:27:40
2014-11-13T13:27:40
null
0
0
null
null
null
null
UTF-8
C++
false
false
17,893
cpp
#include "sendcoinsdialog.h" #include "ui_sendcoinsdialog.h" #include "init.h" #include "walletmodel.h" #include "addresstablemodel.h" #include "addressbookpage.h" #include "bitcoinunits.h" #include "addressbookpage.h" #include "optionsmodel.h" #include "sendcoinsentry.h" #include "guiutil.h" #include "askpassphrasedialog.h" #include "coincontrol.h" #include "coincontroldialog.h" #include <QMessageBox> #include <QLocale> #include <QTextDocument> #include <QScrollBar> #include <QClipboard> SendCoinsDialog::SendCoinsDialog(QWidget *parent) : QDialog(parent), ui(new Ui::SendCoinsDialog), model(0) { ui->setupUi(this); #ifdef Q_OS_MAC // Icons on push buttons are very uncommon on Mac ui->addButton->setIcon(QIcon()); ui->clearButton->setIcon(QIcon()); ui->sendButton->setIcon(QIcon()); #endif #if QT_VERSION >= 0x040700 /* Do not move this to the XML file, Qt before 4.7 will choke on it */ ui->lineEditCoinControlChange->setPlaceholderText(tr("Enter a Hexion address (e.g. RJhbfkAFvXqYkreSgJfrRLS9DepUcxbQci)")); #endif addEntry(); connect(ui->addButton, SIGNAL(clicked()), this, SLOT(addEntry())); connect(ui->clearButton, SIGNAL(clicked()), this, SLOT(clear())); // Coin Control ui->lineEditCoinControlChange->setFont(GUIUtil::bitcoinAddressFont()); connect(ui->pushButtonCoinControl, SIGNAL(clicked()), this, SLOT(coinControlButtonClicked())); connect(ui->checkBoxCoinControlChange, SIGNAL(stateChanged(int)), this, SLOT(coinControlChangeChecked(int))); connect(ui->lineEditCoinControlChange, SIGNAL(textEdited(const QString &)), this, SLOT(coinControlChangeEdited(const QString &))); // Coin Control: clipboard actions QAction *clipboardQuantityAction = new QAction(tr("Copy quantity"), this); QAction *clipboardAmountAction = new QAction(tr("Copy amount"), this); QAction *clipboardFeeAction = new QAction(tr("Copy fee"), this); QAction *clipboardAfterFeeAction = new QAction(tr("Copy after fee"), this); QAction *clipboardBytesAction = new QAction(tr("Copy bytes"), this); QAction *clipboardPriorityAction = new QAction(tr("Copy priority"), this); QAction *clipboardLowOutputAction = new QAction(tr("Copy low output"), this); QAction *clipboardChangeAction = new QAction(tr("Copy change"), this); connect(clipboardQuantityAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardQuantity())); connect(clipboardAmountAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardAmount())); connect(clipboardFeeAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardFee())); connect(clipboardAfterFeeAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardAfterFee())); connect(clipboardBytesAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardBytes())); connect(clipboardPriorityAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardPriority())); connect(clipboardLowOutputAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardLowOutput())); connect(clipboardChangeAction, SIGNAL(triggered()), this, SLOT(coinControlClipboardChange())); ui->labelCoinControlQuantity->addAction(clipboardQuantityAction); ui->labelCoinControlAmount->addAction(clipboardAmountAction); ui->labelCoinControlFee->addAction(clipboardFeeAction); ui->labelCoinControlAfterFee->addAction(clipboardAfterFeeAction); ui->labelCoinControlBytes->addAction(clipboardBytesAction); ui->labelCoinControlPriority->addAction(clipboardPriorityAction); ui->labelCoinControlLowOutput->addAction(clipboardLowOutputAction); ui->labelCoinControlChange->addAction(clipboardChangeAction); fNewRecipientAllowed = true; } void SendCoinsDialog::setModel(WalletModel *model) { this->model = model; for(int i = 0; i < ui->entries->count(); ++i) { SendCoinsEntry *entry = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(i)->widget()); if(entry) { entry->setModel(model); } } if(model && model->getOptionsModel()) { setBalance(model->getBalance(), model->getStake(), model->getUnconfirmedBalance(), model->getImmatureBalance()); connect(model, SIGNAL(balanceChanged(qint64, qint64, qint64, qint64)), this, SLOT(setBalance(qint64, qint64, qint64, qint64))); connect(model->getOptionsModel(), SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit())); // Coin Control connect(model->getOptionsModel(), SIGNAL(displayUnitChanged(int)), this, SLOT(coinControlUpdateLabels())); connect(model->getOptionsModel(), SIGNAL(coinControlFeaturesChanged(bool)), this, SLOT(coinControlFeatureChanged(bool))); connect(model->getOptionsModel(), SIGNAL(transactionFeeChanged(qint64)), this, SLOT(coinControlUpdateLabels())); ui->frameCoinControl->setVisible(model->getOptionsModel()->getCoinControlFeatures()); coinControlUpdateLabels(); } } SendCoinsDialog::~SendCoinsDialog() { delete ui; } void SendCoinsDialog::on_sendButton_clicked() { QList<SendCoinsRecipient> recipients; bool valid = true; if(!model) return; for(int i = 0; i < ui->entries->count(); ++i) { SendCoinsEntry *entry = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(i)->widget()); if(entry) { if(entry->validate()) { recipients.append(entry->getValue()); } else { valid = false; } } } if(!valid || recipients.isEmpty()) { return; } // Format confirmation message QStringList formatted; foreach(const SendCoinsRecipient &rcp, recipients) { formatted.append(tr("<b>%1</b> to %2 (%3)").arg(BitcoinUnits::formatWithUnit(BitcoinUnits::BTC, rcp.amount), Qt::escape(rcp.label), rcp.address)); } fNewRecipientAllowed = false; QMessageBox::StandardButton retval = QMessageBox::question(this, tr("Confirm send coins"), tr("Are you sure you want to send %1?").arg(formatted.join(tr(" and "))), QMessageBox::Yes|QMessageBox::Cancel, QMessageBox::Cancel); if(retval != QMessageBox::Yes) { fNewRecipientAllowed = true; return; } WalletModel::UnlockContext ctx(model->requestUnlock()); if(!ctx.isValid()) { // Unlock wallet was cancelled fNewRecipientAllowed = true; return; } WalletModel::SendCoinsReturn sendstatus; if (!model->getOptionsModel() || !model->getOptionsModel()->getCoinControlFeatures()) sendstatus = model->sendCoins(recipients); else sendstatus = model->sendCoins(recipients, CoinControlDialog::coinControl); switch(sendstatus.status) { case WalletModel::InvalidAddress: QMessageBox::warning(this, tr("Send Coins"), tr("The recipient address is not valid, please recheck."), QMessageBox::Ok, QMessageBox::Ok); break; case WalletModel::InvalidAmount: QMessageBox::warning(this, tr("Send Coins"), tr("The amount to pay must be larger than 0."), QMessageBox::Ok, QMessageBox::Ok); break; case WalletModel::AmountExceedsBalance: QMessageBox::warning(this, tr("Send Coins"), tr("The amount exceeds your balance."), QMessageBox::Ok, QMessageBox::Ok); break; case WalletModel::AmountWithFeeExceedsBalance: QMessageBox::warning(this, tr("Send Coins"), tr("The total exceeds your balance when the %1 transaction fee is included."). arg(BitcoinUnits::formatWithUnit(BitcoinUnits::BTC, sendstatus.fee)), QMessageBox::Ok, QMessageBox::Ok); break; case WalletModel::DuplicateAddress: QMessageBox::warning(this, tr("Send Coins"), tr("Duplicate address found, can only send to each address once per send operation."), QMessageBox::Ok, QMessageBox::Ok); break; case WalletModel::TransactionCreationFailed: QMessageBox::warning(this, tr("Send Coins"), tr("Error: Transaction creation failed."), QMessageBox::Ok, QMessageBox::Ok); break; case WalletModel::TransactionCommitFailed: QMessageBox::warning(this, tr("Send Coins"), tr("Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here."), QMessageBox::Ok, QMessageBox::Ok); break; case WalletModel::Aborted: // User aborted, nothing to do break; case WalletModel::OK: accept(); CoinControlDialog::coinControl->UnSelectAll(); coinControlUpdateLabels(); break; } fNewRecipientAllowed = true; } void SendCoinsDialog::clear() { // Remove entries until only one left while(ui->entries->count()) { delete ui->entries->takeAt(0)->widget(); } addEntry(); updateRemoveEnabled(); ui->sendButton->setDefault(true); } void SendCoinsDialog::reject() { clear(); } void SendCoinsDialog::accept() { clear(); } SendCoinsEntry *SendCoinsDialog::addEntry() { SendCoinsEntry *entry = new SendCoinsEntry(this); entry->setModel(model); ui->entries->addWidget(entry); connect(entry, SIGNAL(removeEntry(SendCoinsEntry*)), this, SLOT(removeEntry(SendCoinsEntry*))); connect(entry, SIGNAL(payAmountChanged()), this, SLOT(coinControlUpdateLabels())); updateRemoveEnabled(); // Focus the field, so that entry can start immediately entry->clear(); entry->setFocus(); ui->scrollAreaWidgetContents->resize(ui->scrollAreaWidgetContents->sizeHint()); QCoreApplication::instance()->processEvents(); QScrollBar* bar = ui->scrollArea->verticalScrollBar(); if(bar) bar->setSliderPosition(bar->maximum()); return entry; } void SendCoinsDialog::updateRemoveEnabled() { // Remove buttons are enabled as soon as there is more than one send-entry bool enabled = (ui->entries->count() > 1); for(int i = 0; i < ui->entries->count(); ++i) { SendCoinsEntry *entry = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(i)->widget()); if(entry) { entry->setRemoveEnabled(enabled); } } setupTabChain(0); coinControlUpdateLabels(); } void SendCoinsDialog::removeEntry(SendCoinsEntry* entry) { delete entry; updateRemoveEnabled(); } QWidget *SendCoinsDialog::setupTabChain(QWidget *prev) { for(int i = 0; i < ui->entries->count(); ++i) { SendCoinsEntry *entry = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(i)->widget()); if(entry) { prev = entry->setupTabChain(prev); } } QWidget::setTabOrder(prev, ui->addButton); QWidget::setTabOrder(ui->addButton, ui->sendButton); return ui->sendButton; } void SendCoinsDialog::pasteEntry(const SendCoinsRecipient &rv) { if(!fNewRecipientAllowed) return; SendCoinsEntry *entry = 0; // Replace the first entry if it is still unused if(ui->entries->count() == 1) { SendCoinsEntry *first = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(0)->widget()); if(first->isClear()) { entry = first; } } if(!entry) { entry = addEntry(); } entry->setValue(rv); } bool SendCoinsDialog::handleURI(const QString &uri) { SendCoinsRecipient rv; // URI has to be valid if (GUIUtil::parseBitcoinURI(uri, &rv)) { CBitcoinAddress address(rv.address.toStdString()); if (!address.IsValid()) return false; pasteEntry(rv); return true; } return false; } void SendCoinsDialog::setBalance(qint64 balance, qint64 stake, qint64 unconfirmedBalance, qint64 immatureBalance) { Q_UNUSED(stake); Q_UNUSED(unconfirmedBalance); Q_UNUSED(immatureBalance); if(!model || !model->getOptionsModel()) return; int unit = model->getOptionsModel()->getDisplayUnit(); ui->labelBalance->setText(BitcoinUnits::formatWithUnit(unit, balance)); } void SendCoinsDialog::updateDisplayUnit() { if(model && model->getOptionsModel()) { // Update labelBalance with the current balance and the current unit ui->labelBalance->setText(BitcoinUnits::formatWithUnit(model->getOptionsModel()->getDisplayUnit(), model->getBalance())); } } // Coin Control: copy label "Quantity" to clipboard void SendCoinsDialog::coinControlClipboardQuantity() { QApplication::clipboard()->setText(ui->labelCoinControlQuantity->text()); } // Coin Control: copy label "Amount" to clipboard void SendCoinsDialog::coinControlClipboardAmount() { QApplication::clipboard()->setText(ui->labelCoinControlAmount->text().left(ui->labelCoinControlAmount->text().indexOf(" "))); } // Coin Control: copy label "Fee" to clipboard void SendCoinsDialog::coinControlClipboardFee() { QApplication::clipboard()->setText(ui->labelCoinControlFee->text().left(ui->labelCoinControlFee->text().indexOf(" "))); } // Coin Control: copy label "After fee" to clipboard void SendCoinsDialog::coinControlClipboardAfterFee() { QApplication::clipboard()->setText(ui->labelCoinControlAfterFee->text().left(ui->labelCoinControlAfterFee->text().indexOf(" "))); } // Coin Control: copy label "Bytes" to clipboard void SendCoinsDialog::coinControlClipboardBytes() { QApplication::clipboard()->setText(ui->labelCoinControlBytes->text()); } // Coin Control: copy label "Priority" to clipboard void SendCoinsDialog::coinControlClipboardPriority() { QApplication::clipboard()->setText(ui->labelCoinControlPriority->text()); } // Coin Control: copy label "Low output" to clipboard void SendCoinsDialog::coinControlClipboardLowOutput() { QApplication::clipboard()->setText(ui->labelCoinControlLowOutput->text()); } // Coin Control: copy label "Change" to clipboard void SendCoinsDialog::coinControlClipboardChange() { QApplication::clipboard()->setText(ui->labelCoinControlChange->text().left(ui->labelCoinControlChange->text().indexOf(" "))); } // Coin Control: settings menu - coin control enabled/disabled by user void SendCoinsDialog::coinControlFeatureChanged(bool checked) { ui->frameCoinControl->setVisible(checked); if (!checked && model) // coin control features disabled CoinControlDialog::coinControl->SetNull(); } // Coin Control: button inputs -> show actual coin control dialog void SendCoinsDialog::coinControlButtonClicked() { CoinControlDialog dlg; dlg.setModel(model); dlg.exec(); coinControlUpdateLabels(); } // Coin Control: checkbox custom change address void SendCoinsDialog::coinControlChangeChecked(int state) { if (model) { if (state == Qt::Checked) CoinControlDialog::coinControl->destChange = CBitcoinAddress(ui->lineEditCoinControlChange->text().toStdString()).Get(); else CoinControlDialog::coinControl->destChange = CNoDestination(); } ui->lineEditCoinControlChange->setEnabled((state == Qt::Checked)); ui->labelCoinControlChangeLabel->setEnabled((state == Qt::Checked)); } // Coin Control: custom change address changed void SendCoinsDialog::coinControlChangeEdited(const QString & text) { if (model) { CoinControlDialog::coinControl->destChange = CBitcoinAddress(text.toStdString()).Get(); // label for the change address ui->labelCoinControlChangeLabel->setStyleSheet("QLabel{color:Test;}"); if (text.isEmpty()) ui->labelCoinControlChangeLabel->setText(""); else if (!CBitcoinAddress(text.toStdString()).IsValid()) { ui->labelCoinControlChangeLabel->setStyleSheet("QLabel{color:red;}"); ui->labelCoinControlChangeLabel->setText(tr("WARNING: Invalid Hexion address")); } else { QString associatedLabel = model->getAddressTableModel()->labelForAddress(text); if (!associatedLabel.isEmpty()) ui->labelCoinControlChangeLabel->setText(associatedLabel); else { CPubKey pubkey; CKeyID keyid; CBitcoinAddress(text.toStdString()).GetKeyID(keyid); if (model->getPubKey(keyid, pubkey)) ui->labelCoinControlChangeLabel->setText(tr("(no label)")); else { ui->labelCoinControlChangeLabel->setStyleSheet("QLabel{color:red;}"); ui->labelCoinControlChangeLabel->setText(tr("WARNING: unknown change address")); } } } } } // Coin Control: update labels void SendCoinsDialog::coinControlUpdateLabels() { if (!model || !model->getOptionsModel() || !model->getOptionsModel()->getCoinControlFeatures()) return; // set pay amounts CoinControlDialog::payAmounts.clear(); for(int i = 0; i < ui->entries->count(); ++i) { SendCoinsEntry *entry = qobject_cast<SendCoinsEntry*>(ui->entries->itemAt(i)->widget()); if(entry) CoinControlDialog::payAmounts.append(entry->getValue().amount); } if (CoinControlDialog::coinControl->HasSelected()) { // actual coin control calculation CoinControlDialog::updateLabels(model, this); // show coin control stats ui->labelCoinControlAutomaticallySelected->hide(); ui->widgetCoinControl->show(); } else { // hide coin control stats ui->labelCoinControlAutomaticallySelected->show(); ui->widgetCoinControl->hide(); ui->labelCoinControlInsuffFunds->hide(); } }
[ "hexioncoin@hotmail.com" ]
hexioncoin@hotmail.com
2904b01500cdcd5a9f35a1f90501e26d2c0ef4e2
22a92786fabb194cceffa29c8d715376659da885
/P350_Intersection_of_Two_Arrays_II.cpp
6beb9467c81ea39088226e44455b674d8e570cbe
[]
no_license
BarryChenZ/LeetCode3
c34986dd6ab032ea87bb765d1f72f5b48085541e
0c54b7edf80dd8dda5a11bede9130c0061cc4cd2
refs/heads/master
2021-07-11T07:15:09.779348
2020-11-10T03:03:53
2020-11-10T03:03:53
214,945,600
0
0
null
null
null
null
UTF-8
C++
false
false
367
cpp
class Solution { public: vector<int> intersect(vector<int>& nums1, vector<int>& nums2) { std::sort(nums1.begin(),nums1.end()); std::sort(nums2.begin(),nums2.end()); auto it=std::set_intersection (nums1.begin(),nums1.end(), nums2.begin(),nums2.end(), nums1.begin()); nums1.resize(it-nums1.begin()); return nums1; } };
[ "noreply@github.com" ]
BarryChenZ.noreply@github.com
148c3dd4baca8282366df8e5089e487d0df25538
2927dcbbb0723e8e76710040407c5561fb6b0121
/16384/other/lavos/src/delay.cpp
72ed4fd59741147bfda834f2aed6f2f84b5699a3
[ "BSD-3-Clause" ]
permissive
cafferta10/hardcode
9583599825010c16d46e199aaff9b15834730c65
2033e906d3a7850f88dda431f15a70f0981729b9
refs/heads/master
2021-05-22T01:06:19.072005
2019-10-26T03:28:44
2019-10-26T03:28:44
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,120
cpp
#include "delay.hpp" /** Maximum number of delay buffers. */ #define MAX_DELAY_BUFFERS 20 /** \brief Delay buffers. * * The delay buffers are too large for stack. Thus, we read them from this global buffer and always take the * 'next' one for each delay. * * I feel bad about this, but what can you do. */ static float g_delay_buffers[MAX_DELAY_BUFFERS][g_delay_buffer_size]; /** Next delay buffer to give. */ static uint8_t current_delay_buffer = 0; /** \brief Acquire delay buffer. * * Will also clear the buffer. */ static float* get_delay_buffer() { float *ret = g_delay_buffers[current_delay_buffer]; { for(unsigned ii = 0; (ii < g_delay_buffer_size); ++ii) { ret[ii] = 0.0f; } } ++current_delay_buffer; return ret; } Delay::Delay(void) { m_mode=k_delay_mode_off; m_level=0.0f; m_delay_index=m_input_index=0; m_delay_time=1; m_feedback=0.0f; m_delay_buffer_l = get_delay_buffer(); m_delay_buffer_r = get_delay_buffer(); m_lowpass_filter_l.setMode(k_filter_lowpass); m_lowpass_filter_l.setCutoff(1.0f); m_highpass_filter_l.setMode(k_filter_highpass); m_highpass_filter_l.setCutoff(0.0f); m_lowpass_filter_r.setMode(k_filter_lowpass); m_lowpass_filter_r.setCutoff(1.0f); m_highpass_filter_r.setMode(k_filter_highpass); m_highpass_filter_r.setCutoff(0.0f); } void Delay::setMode(float value) { value *= k_num_delay_modes; m_mode = common::clrintf(value); } void Delay::process(float input, float &output_l, float& output_r) { process(input,input,output_l,output_r); } void Delay::process(float inputl, float inputr, float &output_l, float& output_r) { float inl = m_level*inputl; float inr = m_level*inputr; // output_l=m_delay_buffer_l[m_delay_index]; // output_r=m_delay_buffer_r[m_delay_index]; output_l=m_highpass_filter_l.process(m_lowpass_filter_l.process(m_delay_buffer_l[m_delay_index])); output_r=m_highpass_filter_r.process(m_lowpass_filter_r.process(m_delay_buffer_r[m_delay_index])); switch(m_mode) { case k_delay_mode_mono: m_delay_buffer_l[m_delay_index] = 0.707f*(inl+inr) + output_l * m_feedback; m_delay_buffer_r[m_delay_index] = 0.707f*(inl+inr) + output_r * m_feedback; break; //stereo delay not used // case k_delay_mode_stereo: // m_delay_buffer_l[m_delay_index] = inl + output_l * m_feedback; // m_delay_buffer_r[m_delay_index] = inr + output_r * m_feedback; // break; case k_delay_mode_pingpong: m_delay_buffer_l[m_delay_index] = 0.707f*(inl+inr) + output_r * m_feedback; m_delay_buffer_r[m_delay_index] = output_l * m_feedback; break; case k_delay_mode_cross: m_delay_buffer_l[m_delay_index] = inl + output_r * m_feedback; m_delay_buffer_r[m_delay_index] = inr + output_l * m_feedback; break; default: m_delay_buffer_l[m_delay_index] = 0.0f; m_delay_buffer_r[m_delay_index] = 0.0f; break; } m_delay_index++; if (m_delay_index > m_delay_time) m_delay_index = 0; }
[ "youngthug@youngthug.com" ]
youngthug@youngthug.com
1745a47a9dee9925d9112823c465cfefda9a6816
b372a212000ed977a2a4977eb3aba8467b49315b
/ARduino_workshop__case_/ARduino_workshop__case_.ino
df4b5c52231287829d8a5baa78c62edd66d1703a
[]
no_license
gugus13400/arduino
62852a51d06bd914e31d8590aac2e406a2439f74
baf65ad97ab87b7cc8fde5d943526c95bdd73a23
refs/heads/master
2021-04-06T12:18:11.838080
2018-03-14T14:59:05
2018-03-14T14:59:05
125,226,276
0
0
null
null
null
null
UTF-8
C++
false
false
1,116
ino
int potPin = A0; int led_1 = 8; int led_2 = 9; int led_3 = 10; int led_4 = 11; int led_5 = 12; void setup() { pinMode(potPin, INPUT); Serial.begin(9600); pinMode(led_1, OUTPUT); pinMode(led_2, OUTPUT); pinMode(led_3, OUTPUT); pinMode(led_4, OUTPUT); pinMode(led_5, OUTPUT); } void loop() { int potentiometre = (analogRead(potPin) / 255)+1; Serial.println(potentiometre); switch (potentiometre) { case 1: Serial.println("rouge"); digitalWrite(led_1, HIGH); delay (60); digitalWrite(led_1,LOW); break; case 2: Serial.println("vert"); digitalWrite(led_2, HIGH); delay (60); digitalWrite(led_2,LOW); break; case 3: Serial.println("bleu"); digitalWrite(led_3, HIGH); delay (60); digitalWrite(led_3,LOW); break; case 4: Serial.println("rouge"); digitalWrite(led_4, HIGH); delay (60); digitalWrite(led_4,LOW); break; case 5: Serial.println("jaune"); digitalWrite(led_5, HIGH); delay (60); digitalWrite(led_5,LOW); break; } }
[ "augustepugnet1@gmail.com" ]
augustepugnet1@gmail.com
eb464655d7137797638f71f594534c9041797934
5556191506949b4ae226223988e74001e3c3955c
/9/Array.h
b3252375ee97a670baa375895ee49bb7b5f2da15
[]
no_license
josephvitt/cpp_design
7af74d011cb19c7818c49e9ad30b478dded793eb
8ee06707358128828a1fdc2ca5a6fe8acaca0b3b
refs/heads/master
2020-12-09T05:07:49.296660
2020-02-05T07:58:15
2020-02-05T07:58:15
233,201,142
0
0
null
null
null
null
UTF-8
C++
false
false
3,401
h
/* 动态数组类模板 */ #ifndef ARRAY_H #define ARRAY_H #include <cassert> template <class T> //数组类模板定义 class Array { private: T* list;//用于存放动态分配的数组内存首地址 int size;//数组大小,元素个数 public: Array(int sz = 50);//构造函数 Array(const Array<T> &a);//复制构造函数 ~Array();//析构函数 Array<T> & operator = (const Array<T> &rhs);//重载= T & operator[](int n); const T& operator [] (int i) const;//重载[]常函数 operator T*();//重载T*类型的转换 operator const T* () const; int getSize() const;//取数组的大小 void resize(int sz);//修改数组的大小 }; template <class T> Array<T>::Array(int sz){ //构造函数 assert(sz >0);//sz为数组的大小(元素个数),应当非负 size = sz;//将元素个数赋值给变量size list = new T [size];//动态分配size个T类型的元素空间 } template <class T> Array<T>::~Array(){ //析构函数 delete [] list; } //复制构造函数 template <class T> Array<T>::Array(const Array<T> &a){ size = a.size;//从对象x取得数组大小,并且赋值给当前对象的成员 list = new T[size];//动态分配n个T类型的元素空间 //从对象x复制数组元素到本对象 for (int i = 0; i < size; i++) { list[i] = a.list[i]; } } //重载=运算符,将对象rhs赋值给本对象。实现对象之间的整体赋值 template<class T> Array<T> &Array<T>::operator = (const Array<T> & rhs){ if(&rhs != this){ //如果本对象中数组大小与rhs不同,则删除数组原有内存,然后重新分配 if(size != rhs.size){ delete [] list;//删除数组原有的内存 size = rhs.size;//设置本对象的数组大小 list = new T[size];//重新分配size个元素的内容 } //从对象X中复制数组元素到本对象 for(int i=0;i<size;i++){ list[i] = rhs.list[i]; } return *this;//返回当前对象的引用 } } template <class T> T &Array<T>::operator[](int n){ assert(n >= 0 && n <size);//检查下标是否越界 return list[n];//返回下标为n的数组元素 } template <class T> const T &Array<T>::operator[](int n)const{ assert(n >= 0 && n <size);//检查下标是否越界 return list[n];//返回下标为n的数组元素 } //重载指针转换运算符,将Array类的对象名转换为T类型的指针 template <class T> Array<T>::operator T *(){ return list;//返回当前对象中私有数组的首地址 } //取当前数组的大小 template <class T> int Array<T>::getSize() const { return size; } //修改数组的大小为sz template <class T> void Array<T>::resize(int sz){ assert(sz >= 0);//检查是否非负 if(sz == size)//如果指定的大小与原有大小一样,什么也不做 return ; T* newList = new T[size];//申请新的数组内存 int n = (sz <size) ? sz:size;//将sz于siaze中国较小的一个赋值给n //将原有数组中前n个元素复制到新数组中 for (int i = 0; i < n; i++) { newList[i] = list[i]; } //删除原数组 delete[] list; list = newList;//使list指向新数组 size = sz;//更新size } #endif//ARRAY_H
[ "419514268@qq.com" ]
419514268@qq.com
1b09e455f5723caaff3986d4fd670af5caacd4bb
4e8e56d7d7fdc3bc7eedb03d8a466b5e07ed92d8
/src/qt/optionsdialog.cpp
7cf4a04662487cd0fdada04a82d059610fa9472b
[ "MIT" ]
permissive
fairycoin/fairycoin
4f4a8e7bb51a0f95ce9109ee0dc3aa38db93db22
0dcd0b89431b55bb973c24acdc1b7a2c172a0758
refs/heads/master
2016-08-05T00:19:05.040781
2014-05-20T06:16:43
2014-05-20T06:16:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
7,670
cpp
#include "optionsdialog.h" #include "ui_optionsdialog.h" #include "bitcoinamountfield.h" #include "bitcoinunits.h" #include "monitoreddatamapper.h" #include "netbase.h" #include "optionsmodel.h" #include "qvalidatedlineedit.h" #include "qvaluecombobox.h" #include <QCheckBox> #include <QDir> #include <QIntValidator> #include <QLabel> #include <QLineEdit> #include <QLocale> #include <QMessageBox> #include <QPushButton> #include <QRegExp> #include <QRegExpValidator> #include <QTabWidget> #include <QWidget> OptionsDialog::OptionsDialog(QWidget *parent) : QDialog(parent), ui(new Ui::OptionsDialog), model(0), mapper(0), fRestartWarningDisplayed_Proxy(false), fRestartWarningDisplayed_Lang(false), fProxyIpValid(true) { ui->setupUi(this); /* Network elements init */ #ifndef USE_UPNP ui->mapPortUpnp->setEnabled(false); #endif ui->socksVersion->setEnabled(false); ui->socksVersion->addItem("5", 5); ui->socksVersion->addItem("4", 4); ui->socksVersion->setCurrentIndex(0); ui->proxyIp->setEnabled(false); ui->proxyPort->setEnabled(false); ui->proxyPort->setValidator(new QIntValidator(0, 65535, this)); connect(ui->connectSocks, SIGNAL(toggled(bool)), ui->socksVersion, SLOT(setEnabled(bool))); connect(ui->connectSocks, SIGNAL(toggled(bool)), ui->proxyIp, SLOT(setEnabled(bool))); connect(ui->connectSocks, SIGNAL(toggled(bool)), ui->proxyPort, SLOT(setEnabled(bool))); ui->proxyIp->installEventFilter(this); /* Window elements init */ #ifdef Q_WS_MAC ui->tabWindow->setVisible(false); #endif /* Display elements init */ QDir translations(":translations"); ui->lang->addItem(QString("(") + tr("default") + QString(")"), QVariant("")); foreach(const QString &langStr, translations.entryList()) { QLocale locale(langStr); /** check if the locale name consists of 2 parts (language_country) */ if(langStr.contains("_")) { #if QT_VERSION >= 0x040800 /** display language strings as "native language - native country (locale name)", e.g. "Deutsch - Deutschland (de)" */ ui->lang->addItem(locale.nativeLanguageName() + QString(" - ") + locale.nativeCountryName() + QString(" (") + langStr + QString(")"), QVariant(langStr)); #else /** display language strings as "language - country (locale name)", e.g. "German - Germany (de)" */ ui->lang->addItem(QLocale::languageToString(locale.language()) + QString(" - ") + QLocale::countryToString(locale.country()) + QString(" (") + langStr + QString(")"), QVariant(langStr)); #endif } else { #if QT_VERSION >= 0x040800 /** display language strings as "native language (locale name)", e.g. "Deutsch (de)" */ ui->lang->addItem(locale.nativeLanguageName() + QString(" (") + langStr + QString(")"), QVariant(langStr)); #else /** display language strings as "language (locale name)", e.g. "German (de)" */ ui->lang->addItem(QLocale::languageToString(locale.language()) + QString(" (") + langStr + QString(")"), QVariant(langStr)); #endif } } ui->unit->setModel(new BitcoinUnits(this)); connect(ui->connectSocks, SIGNAL(clicked(bool)), this, SLOT(showRestartWarning_Proxy())); connect(ui->lang, SIGNAL(activated(int)), this, SLOT(showRestartWarning_Lang())); /* Widget-to-option mapper */ mapper = new MonitoredDataMapper(this); mapper->setSubmitPolicy(QDataWidgetMapper::ManualSubmit); mapper->setOrientation(Qt::Vertical); /* enable save buttons when data modified */ connect(mapper, SIGNAL(viewModified()), this, SLOT(enableSaveButtons())); /* disable save buttons when new data loaded */ connect(mapper, SIGNAL(currentIndexChanged(int)), this, SLOT(disableSaveButtons())); /* disable/enable save buttons when proxy IP is invalid/valid */ connect(this, SIGNAL(proxyIpValid(bool)), this, SLOT(setSaveButtonState(bool))); } OptionsDialog::~OptionsDialog() { delete ui; } void OptionsDialog::setModel(OptionsModel *model) { this->model = model; if(model) { connect(model, SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit())); mapper->setModel(model); setMapper(); mapper->toFirst(); } // update the display unit, to not use the default ("BTC") updateDisplayUnit(); } void OptionsDialog::setMapper() { /* Main */ mapper->addMapping(ui->transactionFee, OptionsModel::Fee); mapper->addMapping(ui->bitcoinAtStartup, OptionsModel::StartAtStartup); mapper->addMapping(ui->detachDatabases, OptionsModel::DetachDatabases); /* Network */ mapper->addMapping(ui->mapPortUpnp, OptionsModel::MapPortUPnP); mapper->addMapping(ui->connectSocks, OptionsModel::ProxyUse); mapper->addMapping(ui->socksVersion, OptionsModel::ProxySocksVersion); mapper->addMapping(ui->proxyIp, OptionsModel::ProxyIP); mapper->addMapping(ui->proxyPort, OptionsModel::ProxyPort); /* Window */ #ifndef Q_WS_MAC mapper->addMapping(ui->minimizeToTray, OptionsModel::MinimizeToTray); mapper->addMapping(ui->minimizeOnClose, OptionsModel::MinimizeOnClose); #endif /* Display */ mapper->addMapping(ui->lang, OptionsModel::Language); mapper->addMapping(ui->unit, OptionsModel::DisplayUnit); mapper->addMapping(ui->displayAddresses, OptionsModel::DisplayAddresses); } void OptionsDialog::enableSaveButtons() { // prevent enabling of the save buttons when data modified, if there is an invalid proxy address present if(fProxyIpValid) setSaveButtonState(true); } void OptionsDialog::disableSaveButtons() { setSaveButtonState(false); } void OptionsDialog::setSaveButtonState(bool fState) { ui->applyButton->setEnabled(fState); ui->okButton->setEnabled(fState); } void OptionsDialog::on_okButton_clicked() { mapper->submit(); accept(); } void OptionsDialog::on_cancelButton_clicked() { reject(); } void OptionsDialog::on_applyButton_clicked() { mapper->submit(); ui->applyButton->setEnabled(false); } void OptionsDialog::showRestartWarning_Proxy() { if(!fRestartWarningDisplayed_Proxy) { QMessageBox::warning(this, tr("Warning"), tr("This setting will take effect after restarting Fairycoin."), QMessageBox::Ok); fRestartWarningDisplayed_Proxy = true; } } void OptionsDialog::showRestartWarning_Lang() { if(!fRestartWarningDisplayed_Lang) { QMessageBox::warning(this, tr("Warning"), tr("This setting will take effect after restarting Fairycoin."), QMessageBox::Ok); fRestartWarningDisplayed_Lang = true; } } void OptionsDialog::updateDisplayUnit() { if(model) { // Update transactionFee with the current unit ui->transactionFee->setDisplayUnit(model->getDisplayUnit()); } } bool OptionsDialog::eventFilter(QObject *object, QEvent *event) { if(object == ui->proxyIp && event->type() == QEvent::FocusOut) { // Check proxyIP for a valid IPv4/IPv6 address CService addr; if(!LookupNumeric(ui->proxyIp->text().toStdString().c_str(), addr)) { ui->proxyIp->setValid(false); fProxyIpValid = false; ui->statusLabel->setStyleSheet("QLabel { color: red; }"); ui->statusLabel->setText(tr("The supplied proxy address is invalid.")); emit proxyIpValid(false); } else { fProxyIpValid = true; ui->statusLabel->clear(); emit proxyIpValid(true); } } return QDialog::eventFilter(object, event); }
[ "osiris2099@drivehq.com" ]
osiris2099@drivehq.com
9dd7ff082ed9fd81d747a4f1c3809b1464c82932
9f40d2ca59e083d21093a44a269a59330e940c2c
/gameAndMirror.ino
a6233b6fe0cbe7dd3e9c0a1a2461e673c7604833
[]
no_license
danielreyes9756/PI-CalculatorAndOther
a676ba393b66d77378900bd156766475b01a2939
90baf29d56d702e78fe6683a0e09b9eec1a50329
refs/heads/master
2021-01-01T09:34:01.769960
2020-02-09T00:08:56
2020-02-09T00:08:56
239,220,220
0
0
null
null
null
null
UTF-8
C++
false
false
15,415
ino
//Variables int iCount=0,displayCount=0,s=0,s2=0,m=0,m2=0,timbre=0,pulse=0,p=0,iCount2=0,turno=0,modo=0; byte vector[]={0x3F, 0x6, 0x5B, 0x4F, 0x66, 0x6D, 0x7D, 0x7, 0x7F, 0x6F}; byte vectorIn[]={0x3F, 0x30, 0x6D, 0x79, 0x72, 0x5B, 0x5F, 0x31, 0x7F, 0x7B}; long ini; String cadena="",cadena2=""; char aux='\0'; boolean permite=false,startGame=false,win=false,sePulso=false; char tablero[3][3]= { {'z','z','z'}, {'z','z','z'}, {'z','z','z'}}; void setup() { cli(); // modo normal de funcionamiento TCCR1A = 0; TCCR1B = 0; // cuenta inicial a cero TCNT1 = 0; // mode CTC TCCR1B |= (1 << WGM12); // prescaler N = 1024 TCCR1B |= (1 << CS12) | (1 << CS10); // fintr = fclk/(N*(OCR1A+1)) --> OCR1A = [fclk/(N*fintr)] - 1 // para fintr = 100Hz --> OCR1A = [16*10^6/(1024*100)] -1 = 155,25 --> 155 OCR1A = 77; // para 200 Hz programar OCR1A = 77 // enable timer1 compare interrupt (OCR1A) TIMSK1 |= (1 << OCIE1A); // habilitar interrupciones sei(); //Serial3 Serial.begin(9600); Serial3.begin(9600); //Display On Serial3.write(0xFE); Serial3.write(0x41); //Clear Screen Serial3.write(0xFE); Serial3.write(0x51); //Cursor Home Serial3.write(0xFE); Serial3.write(0x46); //Underline Cursor On Serial3.write(0xFE); Serial3.write(0x47); //7Segmentos DDRA = B11111111; //Botones DDRC = B00000001; PORTC = B11111000; //Lineas de teclado DDRL = B00001111; PORTL = B11110000; ini = millis(); Serial3.print("Modo Calculadora"); delay(2000); clearAll(); } void loop() { if(modo==1){ modo_game(); }else if(modo==2){ modo_espejo(); }else if(modo==0){ modo_calculadora(); } } ISR(TIMER1_COMPA_vect) { if(modo==1){ isr_Game(); }else if(modo==2){ isr_Espejo(); }else if(modo==0){ isr_Calculadora(); } } void isr_Calculadora() { if (iCount == 200) { Clock(); iCount = 0; } if (displayCount == 4) { displayCount = 0; } if (displayCount == 0) { PORTA = vector[s]; PORTL = 0b11111110; checkKB(0); } if (displayCount == 1) { PORTA = vector[s2]; PORTL = 0b11111101; checkKB(1); } if (displayCount == 2) { PORTA = vector[m]; PORTL = 0b11111011; checkKB(2); } if (displayCount == 3) { PORTA = vector[m2]; PORTL = 0b11110111; } displayCount++; iCount++; if (pulse == 1) { if ((millis() - ini) >= 200) { ini = millis(); permite=true; tone(37,timbre,100); Serial3.write(aux); cadena += aux; } pulse = 0; } } void isr_Game() { if(iCount2 == 200 && startGame){ Clock(); iCount2=0; } if(iCount2%20==0) { if(iCount2==200){iCount2=0;} if(p==0){ p=1; } else if(p==1) { p=0b11; } else if(p==0b11){ p=0b111; } else if(p==0b111){ p=0b1111; } else if(p==0b1111){ p=0b11111; } else if(p==0b11111){ p=0b111111; } else if(p==0b111111){ p=0b111110; } else if(p==0b111110){ p=0b111100; } else if(p==0b111100){ p=0b111000; } else if(p==0b111000){ p=0b110000; } else if(p==0b110000){ p=0b100000; } else if(p==0b100000){ p=0; } } if (displayCount == 4) { displayCount = 0; } if (displayCount == 0) { if(startGame)PORTA = vector[s]; else PORTA = p; PORTL = 0b11111110; checkKB(0); } if (displayCount == 1) { if(startGame)PORTA = vector[s2]; else PORTA = p; PORTL = 0b11111101; checkKB(1); } if (displayCount == 2) { if(startGame)PORTA = vector[m]; else PORTA = p; PORTL = 0b11111011; checkKB(2); } if (displayCount == 3) { if(startGame)PORTA = vector[m2]; else PORTA = p; PORTL = 0b11110111; } displayCount++; iCount2++; if (pulse == 1) { if ((millis() - ini) >= 200) { ini = millis(); } pulse = 0; } } //----------------------------------------GAME---------------------------------------// void modo_game(){ if(permite){ if(digitalRead(34)==0){ clearAll(); startGame=true; permite=false; } } if(digitalRead(34)==0 && digitalRead(31)==0){ clearAll(); startGame=false; permite=true; turno=0; Serial3.print("Modo juego 3 en raya"); delay(1000); s=0;s2=0;m=0;m2=0; clearAll(); for(int i = 0; i<3;i++){ for(int j=0; j<3;j++){ tablero[i][j]='z'; } } } if(startGame){ pulsacionTurno(); aux='0'; int x = comprobarGanador(); if(x==1){Serial3.write(0xFE);Serial3.write(0x45);Serial3.write(0x54); Serial3.print("Gano player1"); startGame=false;} if(x==2){Serial3.write(0xFE);Serial3.write(0x45);Serial3.write(0x54);Serial3.print("Gano player2"); startGame=false;} if(x==9){Serial3.write(0xFE);Serial3.write(0x45);Serial3.write(0x54);Serial3.print("Empate"); startGame=false;} } } void pulsacionTurno() { switch(aux){ case '1': if(tablero[0][0]=='z' && turno==0){ tablero[0][0]='O'; escribir(aux,turno); delay(200); turno=1;} if(tablero[0][0]=='z' && turno==1){ tablero[0][0]='X'; escribir(aux,turno); delay(200); turno=0;} break; case '2': if(tablero[0][1]=='z' && turno==0){ tablero[0][1]='O'; escribir(aux,turno); delay(200); turno=1;} if(tablero[0][1]=='z' && turno==1){ tablero[0][1]='X'; escribir(aux,turno); delay(200); turno=0;} break; case '3': if(tablero[0][2]=='z' && turno==0){ tablero[0][2]='O'; escribir(aux,turno); delay(200); turno=1;} if(tablero[0][2]=='z' && turno==1){ tablero[0][2]='X'; escribir(aux,turno); delay(200); turno=0;} break; case '4': if(tablero[1][0]=='z' && turno==0){ tablero[1][0]='O'; escribir(aux,turno); delay(200); turno=1;} if(tablero[1][0]=='z' && turno==1){ tablero[1][0]='X'; escribir(aux,turno); delay(200); turno=0;} break; case '5': if(tablero[1][1]=='z' && turno==0){ tablero[1][1]='O'; escribir(aux,turno); delay(200); turno=1;} if(tablero[1][1]=='z' && turno==1){ tablero[1][1]='X'; escribir(aux,turno); delay(200); turno=0;} break; case '6': if(tablero[1][2]=='z' && turno==0){ tablero[1][2]='O'; escribir(aux,turno); delay(200); turno=1;} if(tablero[1][2]=='z' && turno==1){ tablero[1][2]='X'; escribir(aux,turno); delay(200); turno=0;} break; case '7': if(tablero[2][0]=='z' && turno==0){ tablero[2][0]='O'; escribir(aux,turno); delay(200); turno=1;} if(tablero[2][0]=='z' && turno==1){ tablero[2][0]='X'; escribir(aux,turno); delay(200); turno=0;} break; case '8': if(tablero[2][1]=='z' && turno==0){ tablero[2][1]='O'; escribir(aux,turno); delay(200); turno=1;} if(tablero[2][1]=='z' && turno==1){ tablero[2][1]='X'; escribir(aux,turno); delay(200); turno=0;} break; case '9': if(tablero[2][2]=='z' && turno==0){ tablero[2][2]='O'; escribir(aux,turno); delay(200); turno=1;} if(tablero[2][2]=='z' && turno==1){ tablero[2][2]='X'; escribir(aux,turno); delay(200); turno=0;} break; } } void escribir(char aux,int turno) { int i=0; if(aux=='1'||aux=='2'||aux=='3'){ i=0; } if(aux=='4'||aux=='5'||aux=='6'){ i=40; } if(aux=='7'||aux=='8'||aux=='9'){ i=20; } if(aux=='1' || aux=='4' || aux=='7'){ i+=8; } if(aux=='2' || aux=='5' || aux=='8'){ i+=9; } if(aux=='3' || aux=='6' || aux=='9'){ i+=10; } Serial3.write(0xFE); Serial3.write(0x45); Serial3.write(i); if(turno==0){Serial3.print('O');} if(turno==1){Serial3.print('X');} } int comprobarGanador() { //VICTORIA TODAS LAS FILAS if(tablero[0][0]==tablero[0][1] && tablero[0][1]==tablero[0][2]){ if(tablero[0][0]=='O'){ return 1;} if(tablero[0][0]=='X'){ return 2;} } if(tablero[1][0]==tablero[1][1] && tablero[1][1]==tablero[1][2]){ if(tablero[1][0]=='O'){ return 1;} if(tablero[1][0]=='X'){ return 2;} } if(tablero[2][0]==tablero[2][1] && tablero[2][1]==tablero[2][2]){ if(tablero[2][2]=='O'){ return 1;} if(tablero[2][2]=='X'){ return 2;} } //VICTORIA DIAGONALES if(tablero[0][0]==tablero[1][1] && tablero[1][1]==tablero[2][2]){ if(tablero[1][1]=='O'){ return 1;} if(tablero[1][1]=='X'){ return 2;} } if(tablero[0][2]==tablero[1][1] && tablero[1][1]==tablero[2][0]){ if(tablero[1][1]=='O'){ return 1;} if(tablero[1][1]=='X'){ return 2;} } //VICTORIA COLUMNAS if(tablero[0][0]==tablero[1][0] && tablero[1][0]==tablero[2][0]){ if(tablero[0][0]=='O'){ return 1;} if(tablero[0][0]=='X'){ return 2;} } if(tablero[0][1]==tablero[1][1] && tablero[1][1]==tablero[2][1]){ if(tablero[0][1]=='O'){ return 1;} if(tablero[0][1]=='X'){ return 2;} } if(tablero[0][2]==tablero[1][2] && tablero[1][2]==tablero[2][2]){ if(tablero[0][2]=='O'){ return 1;} if(tablero[0][2]=='X'){ return 2;} } int complete=0; for(int i = 0; i<3;i++){ for(int j=0; j<3;j++){ if(tablero[i][j]!='z'){ complete++; } } } if(complete==9){return 9;} return 3; } //-----------------------------------------RELOJ---------------------------------------// //Comprobar el reloj void Clock() { s++; if (s > 9) {s = 0;s2++;} if (s2 > 5) {s2 = 0;m++;} if (m > 9) {m = 0;m2++;} if (m2 > 9) {m2 = 0;} } void checkKB(int a) { if (digitalRead(42) == 0 && digitalRead(45)==0) { while(digitalRead(42) == 0 && digitalRead(45)==0){} if(a==0 && modo==1){ modo=0; s=0;s2=0;m=0;m2=0; startGame=false; permite=false; clearAll(); Serial3.write("Modo Calculadora"); clearAll(); } } if (digitalRead(44) == 0 && digitalRead(45)==0) { while(digitalRead(44) == 0 && digitalRead(45)==0){} if(a==0 && modo==0){ modo=1; permite=true; s=0;s2=0;m=0;m2=0; clearAll(); Serial3.write("Modo Juego"); } } if (digitalRead(42) == 0) { if (cadena.length() < 20) { if (a == 0) {aux = '1'; if(modo==2){timbre=3000;}} if (a == 1) {aux = '2'; if(modo==2){timbre=3100;}} if (a == 2) {aux = '3'; if(modo==2){timbre=3200;}} pulse = 1; } } if (digitalRead(43) == 0) { if (cadena.length() < 20) { if (a == 0) {aux = '4'; if(modo==2){timbre=3300;}} if (a == 1) {aux = '5'; if(modo==2){timbre=3400;}} if (a == 2) {aux = '6'; if(modo==2){timbre=3500;}} pulse = 1; } } if (digitalRead(44) == 0) { if (cadena.length() < 20) { if (a == 0 && modo==0 || a == 0 && startGame || modo == 2){aux = '7'; if(modo==2){timbre=3600;}} if (a == 1) {aux = '8'; if(modo==2){timbre=3700;}} if (a == 2) {aux = '9'; if(modo==2){timbre=3800;}} pulse = 1; } } if (digitalRead(45) == 0) { if(a==0 && aux=='#' && modo!=2){ Serial.println("hola"); modo=2; s=0;s2=0;m=0;m2=0; startGame=false; permite=true; clearAll(); Serial3.write("Modo Piano"); clearAll(); } if (a == 0 && modo==0) {aux = '*';} if (a == 2) {aux = '#';} if (cadena.length() < 20) { if (a == 1) { aux = '0'; pulse = 1; if(modo==2){ timbre=3900; } } } } } void clearAll() { Serial3.write(0xFE); Serial3.write(0x51); if(!modo){ Serial3.write(0xFE); Serial3.write(0x45); Serial3.write(0x53); Serial3.write('0'); permite=false; } Serial3.write(0xFE); Serial3.write(0x46); aux = '\0'; cadena = ""; } void cleanOne() { int z = cadena.length()-1; if (z >= 0) { char a = cadena.charAt(z); if(a=='-' || a=='/' || a=='*' || a=='+'){permite=true;}else{permite=false;} Serial3.write(0xFE); Serial3.write(0x4E); String cadena2 = cadena.substring(0,cadena.length()-1); cadena = cadena2; } aux = '\0'; } long calcRes(String sAux[],char charAux[]){ int punteroS = 0; int punteroChar = 0; for (int i = 0; i < cadena.length(); i++) { if (cadena.charAt(i) != '+' && cadena.charAt(i) != '-' && cadena.charAt(i) != '*' && cadena.charAt(i) != '/' && cadena.charAt('\0')) { sAux[punteroS] += cadena.charAt(i); } else { charAux[punteroS] = cadena.charAt(i); punteroChar++; punteroS++; } } long res = sAux[0].toInt(); if (punteroChar > 0) { for (int i = 0; i < punteroChar; i++) { if(charAux[i]=='+'){res+=sAux[i+1].toInt();} if(charAux[i]=='-'){res-=sAux[i+1].toInt();} if(charAux[i]=='*'){res*=sAux[i+1].toInt();} if(charAux[i]=='/'){res/=sAux[i+1].toInt();} } } return res; } void enterClean(long res){ String res2 = String(res); Serial3.write(0xFE); Serial3.write(0x45); Serial3.write(0x53); for(int i=0; i<20;i++){ Serial3.write(0xFE); Serial3.write(0x4E); } Serial3.write(0xFE); Serial3.write(0x45); Serial3.write(0x53-res2.length()+1); Serial3.print(res); res=0; Serial3.write(0xFE); Serial3.write(0x46); permite=false; delay(250); } void modo_calculadora() { if (aux == '*') {clearAll();} if (aux == '#') { if ((millis() - ini) >= 300) { ini = millis(); cleanOne(); } aux = '\0'; } //Center = resolver if (digitalRead(33) == LOW) { String sAux[10]; char charAux[10]; long res = calcRes(sAux,charAux); while (cadena.length()>0) { cleanOne(); } cleanOne(); //limpia el resultado anterior si hay e imprime el nuevo enterClean(res); } if(permite==true){ //Up = suma if (digitalRead(34) == LOW) { permite=false; Serial3.write("+"); cadena += "+"; delay(250); } //Down = resta if (digitalRead(31) == LOW) { permite=false; Serial3.write("-"); cadena += "-"; delay(250); } //Right = multiplicacion if (digitalRead(30) == LOW) { permite=false; Serial3.write("*"); cadena += "*"; delay(250); } //Left = division if (digitalRead(32) == LOW) { permite=false; Serial3.write("/"); cadena += "/"; delay(250); } } } //----------------------------------------------MODO Espejo--------------------------------------------// void isr_Espejo() { if (displayCount == 4) { displayCount = 0; } if (displayCount == 0) { PORTA = vector[s]; PORTL = 0b11111110; } if (displayCount == 1) { PORTA = vector[s2]; PORTL = 0b11111101; } if (displayCount == 2) { if(!sePulso) { PORTA = 0; } else { PORTA = vectorIn[s2]; } PORTL = 0b11111011; } if (displayCount == 3) { if(!sePulso) { PORTA = 0; } else { PORTA = vectorIn[s]; } PORTL = 0b11110111; } displayCount++; } void modo_espejo(){ if(digitalRead(34)==0){ s++; if(s>9){s2++; s=0;} if(s2>9){s2=0;} sePulso=false; delay(200); } if(digitalRead(31)==0){ s--; if(s<0){s2--; s=9;} if(s2<0){s2=9;} sePulso=false; delay(200); } if(digitalRead(33)==0){ sePulso=true; delay(200); } }
[ "danielreyes9756.com" ]
danielreyes9756.com
acb30d2e08d40ec98d1f540abdd1e4552dd75313
cf8ddfc720bf6451c4ef4fa01684327431db1919
/SDK/ARKSurvivalEvolved_PrimalItemConsumable_UnlockHair_Facial_Goatee_parameters.hpp
859c127ae757b79e7c28250fa8e07577a9acf954
[ "MIT" ]
permissive
git-Charlie/ARK-SDK
75337684b11e7b9f668da1f15e8054052a3b600f
c38ca9925309516b2093ad8c3a70ed9489e1d573
refs/heads/master
2023-06-20T06:30:33.550123
2021-07-11T13:41:45
2021-07-11T13:41:45
null
0
0
null
null
null
null
UTF-8
C++
false
false
872
hpp
#pragma once // ARKSurvivalEvolved (329.9) SDK #ifdef _MSC_VER #pragma pack(push, 0x8) #endif #include "ARKSurvivalEvolved_PrimalItemConsumable_UnlockHair_Facial_Goatee_classes.hpp" namespace sdk { //--------------------------------------------------------------------------- //Parameters //--------------------------------------------------------------------------- // Function PrimalItemConsumable_UnlockHair_Facial_Goatee.PrimalItemConsumable_UnlockHair_Facial_Goatee_C.ExecuteUbergraph_PrimalItemConsumable_UnlockHair_Facial_Goatee struct UPrimalItemConsumable_UnlockHair_Facial_Goatee_C_ExecuteUbergraph_PrimalItemConsumable_UnlockHair_Facial_Goatee_Params { int EntryPoint; // (Parm, ZeroConstructor, IsPlainOldData) }; } #ifdef _MSC_VER #pragma pack(pop) #endif
[ "sergey.2bite@gmail.com" ]
sergey.2bite@gmail.com
135e01ea34d4dfc6897e6d689e5ff78f4ff5f1ad
001bff3a9254779345f2fc22a02786decafe4678
/11/debian-10/postgresql-repmgr-11.11.0-15-linux-amd64-debian-10/files/postgresql/include/geos/geom/FixedSizeCoordinateSequence.h
20e661d1d68f635829235326cc2be141e3c6c5d7
[ "GPL-2.0-only", "MIT", "Zlib", "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
radondb-pg/radondb-postgresql-kubernetes
33fe153b2b2148486e9ae3020c6b9664bc603e39
e7a308cb4fd4c31e76b80d4aaabc9463a912c8fd
refs/heads/main
2023-07-11T16:10:30.562439
2021-08-19T11:42:11
2021-08-19T11:42:11
370,936,467
0
0
Apache-2.0
2021-05-26T06:56:52
2021-05-26T06:56:51
null
UTF-8
C++
false
false
3,881
h
/********************************************************************** * * GEOS - Geometry Engine Open Source * http://geos.osgeo.org * * Copyright (C) 2019 Daniel Baston * * This is free software; you can redistribute and/or modify it under * the terms of the GNU Lesser General Public Licence as published * by the Free Software Foundation. * See the COPYING file for more information. * **********************************************************************/ #ifndef GEOS_GEOM_FIXEDSIZECOORDINATESEQUENCE_H #define GEOS_GEOM_FIXEDSIZECOORDINATESEQUENCE_H #include <geos/geom/Coordinate.h> #include <geos/geom/CoordinateFilter.h> #include <geos/geom/CoordinateSequence.h> #include <geos/util.h> #include <algorithm> #include <array> #include <memory> #include <sstream> #include <vector> namespace geos { namespace geom { template<size_t N> class FixedSizeCoordinateSequence : public CoordinateSequence { public: explicit FixedSizeCoordinateSequence(size_t dimension_in = 0) : dimension(dimension_in) {} std::unique_ptr<CoordinateSequence> clone() const final override { auto seq = detail::make_unique<FixedSizeCoordinateSequence<N>>(dimension); seq->m_data = m_data; return std::move(seq); // move needed for gcc 4.8 } const Coordinate& getAt(size_t i) const final override { return m_data[i]; } void getAt(size_t i, Coordinate& c) const final override { c = m_data[i]; } size_t getSize() const final override { return N; } bool isEmpty() const final override { return N == 0; } void setAt(const Coordinate & c, size_t pos) final override { m_data[pos] = c; } void setOrdinate(size_t index, size_t ordinateIndex, double value) final override { switch(ordinateIndex) { case CoordinateSequence::X: m_data[index].x = value; break; case CoordinateSequence::Y: m_data[index].y = value; break; case CoordinateSequence::Z: m_data[index].z = value; break; default: { std::stringstream ss; ss << "Unknown ordinate index " << index; throw geos::util::IllegalArgumentException(ss.str()); break; } } } size_t getDimension() const final override { if(dimension != 0) { return dimension; } if(isEmpty()) { return 3; } if(std::isnan(m_data[0].z)) { dimension = 2; } else { dimension = 3; } return dimension; } void toVector(std::vector<Coordinate> & out) const final override { out.insert(out.end(), m_data.begin(), m_data.end()); } void setPoints(const std::vector<Coordinate> & v) final override { std::copy(v.begin(), v.end(), m_data.begin()); } void apply_ro(CoordinateFilter* filter) const final override { std::for_each(m_data.begin(), m_data.end(), [&filter](const Coordinate & c) { filter->filter_ro(&c); }); } void apply_rw(const CoordinateFilter* filter) final override { std::for_each(m_data.begin(), m_data.end(), [&filter](Coordinate &c) { filter->filter_rw(&c); }); dimension = 0; // re-check (see http://trac.osgeo.org/geos/ticket/435) } private: std::array<Coordinate, N> m_data; mutable std::size_t dimension; }; } } #endif
[ "hualongzhong@yunify.com" ]
hualongzhong@yunify.com
9d4af6ba7b8450eb6e11fc525b01c964c7c80093
d320d6fed418f4339a953f3963e7bd4b6b4b3cd0
/platformlibs/libwin32/basalt/win32/shared/win32_gfx_factory.cpp
e34a0857a7fd1827f4d38491c206887dbbdeec23
[]
no_license
juli27/basaltcpp
6ef93bb3c322f328262bb18c572968eb0ff8fc2b
1c6bb55f80e8c1fa4aa3b52a7111e78741424955
refs/heads/master
2023-08-31T04:30:57.379453
2023-08-30T18:57:54
2023-08-30T18:57:54
189,708,858
0
0
null
null
null
null
UTF-8
C++
false
false
509
cpp
#include <basalt/win32/shared/win32_gfx_factory.h> #if BASALT_DEV_BUILD #include <basalt/gfx/backend/validating_swap_chain.h> #endif namespace basalt::gfx { auto Win32GfxFactory::create_device_and_swap_chain( const HWND window, const DeviceAndSwapChainDesc& desc) const -> DeviceAndSwapChain { DeviceAndSwapChain res {do_create_device_and_swap_chain(window, desc)}; #if BASALT_DEV_BUILD res.swapChain = ValidatingSwapChain::wrap(res.swapChain); #endif return res; } } // namespace basalt::gfx
[ "juli27@users.noreply.github.com" ]
juli27@users.noreply.github.com
8c6fc42bc80e3941ee5dfd82588954d92a383c0c
90db83e7fb4d95400e62fa2ce48bd371754987e0
/src/components/password_manager/core/browser/form_saver_impl.h
a01ca3e4bac5c5d3cbd67795c54c1c8926cc5c0f
[ "BSD-3-Clause" ]
permissive
FinalProjectNEG/NEG-Browser
5bf10eb1fb8b414313d5d4be6b5af863c4175223
66c824bc649affa8f09e7b1dc9d3db38a3f0dfeb
refs/heads/main
2023-05-09T05:40:37.994363
2021-06-06T14:07:21
2021-06-06T14:07:21
335,742,507
2
4
null
null
null
null
UTF-8
C++
false
false
2,014
h
// Copyright 2016 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 COMPONENTS_PASSWORD_MANAGER_CORE_BROWSER_FORM_SAVER_IMPL_H_ #define COMPONENTS_PASSWORD_MANAGER_CORE_BROWSER_FORM_SAVER_IMPL_H_ #include <memory> #include "base/macros.h" #include "components/password_manager/core/browser/form_saver.h" namespace password_manager { class PasswordStore; // The production code implementation of FormSaver. class FormSaverImpl : public FormSaver { public: // |store| needs to outlive |this| and will be used for all PasswordStore // operations. explicit FormSaverImpl(PasswordStore* store); ~FormSaverImpl() override; // FormSaver: PasswordForm PermanentlyBlacklist(PasswordStore::FormDigest digest) override; void Unblacklist(const PasswordStore::FormDigest& digest) override; void Save(PasswordForm pending, const std::vector<const PasswordForm*>& matches, const base::string16& old_password) override; void Update(PasswordForm pending, const std::vector<const PasswordForm*>& matches, const base::string16& old_password) override; void UpdateReplace(PasswordForm pending, const std::vector<const PasswordForm*>& matches, const base::string16& old_password, const PasswordForm& old_unique_key) override; void Remove(const PasswordForm& form) override; std::unique_ptr<FormSaver> Clone() override; private: // The class is stateless. Don't introduce it. The methods are utilities for // common tasks on the password store. The state should belong to either a // form handler or origin handler which could embed FormSaver. // Cached pointer to the PasswordStore. PasswordStore* const store_; DISALLOW_COPY_AND_ASSIGN(FormSaverImpl); }; } // namespace password_manager #endif // COMPONENTS_PASSWORD_MANAGER_CORE_BROWSER_FORM_SAVER_IMPL_H_
[ "sapirsa3@ac.sce.ac.il" ]
sapirsa3@ac.sce.ac.il
455419ccddd7e92d35da5891cd4ade8db8337cb1
0dae134774f7887eb3ffb4b7611b26e8041a0692
/Competitive Programming/Contests/CodeForces/Contests/Good Bye/Good Bye 2015/New Year and Ancient Prophecy/prophesy.cpp
aaae163cea6272d92d0c346098665162aec4f47c
[]
no_license
andyyang200/CP
b6ce11eb58fd535815aa0f7f5a22e9ed009bf470
46efbcdaf441ee485dbf9eb82e9f00e488d2d362
refs/heads/master
2020-08-27T14:49:36.723263
2019-10-25T04:09:11
2019-10-25T04:09:11
217,407,673
0
0
null
null
null
null
UTF-8
C++
false
false
1,877
cpp
//Andrew Yang #include <iostream> #include <stdio.h> #include <sstream> #include <fstream> #include <string> #include <string.h> #include <vector> #include <deque> #include <queue> #include <stack> #include <set> #include <unordered_set> #include <map> #include <unordered_map> #include <algorithm> #include <functional> #include <utility> #include <bitset> #include <cmath> #include <cstdlib> #include <ctime> #include <cstdio> #include <climits> using namespace std; #define FOR(index, start, end) for(int index = start; index < end; index++) #define RFOR(index, start, end) for(int index = start; index > end; index--) #define FOREACH(itr, b) for(auto itr = b.begin(); itr != b.end(); itr++) #define RFOREACH(itr, b) for(auto itr = b.rbegin(); itr != b.rend(); itr++) #define INF 1000000000 #define M 1000000007 typedef long long ll; typedef pair<int, int> pii; ll dp[5001][5001]; ll p[5001][5001]; int first[5001][5001]; int main() { int n; scanf("%d", &n); string s; cin >> s; RFOR(a, n - 1, -1) { RFOR(b, n - 1, a) { if (s[a] != s[b] || b == n - 1) { first[a][b] = 0; } else { first[a][b] = 1 + first[a + 1][b + 1]; } if (a + first[a][b] >= b) { first[a][b] = 0; } } } FOR(c, 0, n) { RFOR(b, c, -1) { if (s[b] == '0') { dp[b][c] = 0; } else if (b == 0) { dp[b][c] = 1; } else { int a = (b - 1) - (c - b); int l = max(a + 1, 0); dp[b][c] += p[l][b - 1]; int length = c - b + 1; if (a >= 0 && s[a + first[a][b]] < s[b + first[a][b]]) { dp[b][c] += dp[a][b - 1]; } } dp[b][c] %= M; p[b][c] = dp[b][c] + (b == c ? 0 : p[b + 1][c]); p[b][c] %= M; } } int ans = 0; FOR(i, 0, n) { ans += dp[i][n - 1]; ans %= M; } cout << ans << endl; }
[ "andy@zensors.com" ]
andy@zensors.com
688ac72ffa654a556db6864ee847887ae98946bf
102459cdb53edaa01c10f5bb7d3878efa4b0885a
/cipher_tools.hpp
550a40cdde81d6204f9c2673ef4d51a5ed6ac74c
[]
no_license
amaabalo/Cipher-Tools
7138cca36afd749a0920be57e0ba0543ec14c799
dcfafe3cdbb2da2e3738071c10692346bffd85e5
refs/heads/master
2021-06-25T05:37:07.689845
2017-09-10T01:54:48
2017-09-10T01:54:48
102,996,032
0
0
null
null
null
null
UTF-8
C++
false
false
822
hpp
/* cipher_tools.hpp */ #include <unordered_map> #include <vector> #include <utility> const float englishCharacterFrequencies[26] ={0.080, 0.015, 0.030, 0.040, 0.130, 0.020, 0.015, 0.060, 0.065, 0.005, 0.005, 0.035, 0.030, 0.070, 0.080,// 0.020, 0.002, 0.065, 0.060, 0.090, 0.030, 0.010, 0.015, 0.005, 0.020, 0.002}; int frequencyAnalysis(float *frequency_map, char *file_name); void computeCorrelations(float *frequency_map, std::vector<std::pair<char, float>> &correlation_map); bool getOption(std::string &option); void displayPartialDecryption(char *file_name, int num_letters, int shift); void tryShift(std::vector<std::pair<char, float>> &correlation_map, char *file_name, int num_letters); bool isALetter(char c); void replaceLetters(int argc, char *argv[]); void shift(char *file_name, int shift);
[ "amiabalo@Mawutors-MacBook-Pro.local" ]
amiabalo@Mawutors-MacBook-Pro.local
5ecb820729ee402ae3344a751ead381327a16f07
0b279426020e3e4500b2391a730e24528a902283
/00-string/inc/string.hpp
fd79e015faf66f8e3b911aa91eb80cb1c4cc56c4
[ "MIT" ]
permissive
YuehChuan/Cpp-Weekly
76b5f6ac17ead513082e4efe70856715e69a032d
a396f6508857ca1077ab7513a162724b6489dee2
refs/heads/master
2022-04-21T00:08:13.951977
2020-02-27T15:16:36
2020-02-27T15:16:36
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,398
hpp
/** @file string.hpp * * @mainpage string.hpp * * @brief build your own string like std::string from scratch * * @author Gapry * * @date 2020 * * @copyright MIT License */ #ifndef __STRING_HPP__ #define __STRING_HPP__ #include <cstddef> class beta::string : public beta::noncopyable { using size_type = std::size_t; public: /** * @brief constructs a string */ string(const char* = ""); /** * @brief copy constructor */ string(const string&); /** * @brief assigns values to the string */ string& operator=(const string&); /** * @brief assigns values to the string */ string& operator=(const char*); /** * @brief destroys the string, deallocating internal storage if used */ ~string(); /** * @brief returns a non-modifiable standard C character array version of the string */ operator const char*() const; /** * @brief concatenates two strings */ string& operator+=(const string&); /** * @brief concatenates a string and a char */ string& operator+=(const char*); /** * @brief returns the number of characters */ size_type length() const; /** * @brief returns the number of characters that can be held in currently allocated storage */ size_type capacity() const; /** * @brief checks whether the string is empty */ bool empty(); }; #endif
[ "gapry@protonmail.com" ]
gapry@protonmail.com
21d51963cc4b4f3707e4d4168f1b2aeedae67f13
d3a866847e7feeb4d1893bd7b3794af6bcbf68ed
/Completed/195 - Anagram/195 - Anagram.cpp
803629860b071311db90583334158de0afb3406e
[]
no_license
sodrulamin/UVA
b1c7e88ea34e723a6ab9ec7170959e866c5ec729
d2a6e09ba4d6aabbb06b1080ec41466e26dce4dd
refs/heads/master
2020-07-18T08:47:59.317865
2019-10-16T08:22:40
2019-10-16T08:22:40
206,215,956
0
0
null
null
null
null
UTF-8
C++
false
false
1,991
cpp
#include <iostream> #include <string> #include <algorithm> #include <set> #include <vector> #include <stack> using namespace std; vector<string> resultSet; char charList[] = { 'A','a', 'B','b', 'C','c', 'D','d', 'E','e', 'F','f', 'G','g', 'H','h', 'I','i', 'J','j', 'K','k', 'L','l', 'M','m', 'N','n', 'O','o', 'P','p', 'Q','q', 'R','r', 'S','s', 'T','t', 'U','u', 'V','v', 'W','w', 'X','x', 'Y','y', 'Z','z' }; void produceAnanagrams(string str) { vector<int> characters; for(int i=0;i<str.length();i++) { int n; if(isupper(str[i])) { n = (str[i] - 'A') * 2; } else { n = (str[i] - 'a') * 2 + 1; } characters.push_back(n); } //cout << "Size: " << characters.size() << endl; sort(characters.begin(), characters.begin() + characters.size()); set<string> permutedList; do { string s = ""; for(int i=0;i<characters.size();i++) //cout << characters[i]; { s += charList[characters[i]]; } if(permutedList.find(s) == permutedList.end()){ permutedList.insert(s); cout << s << endl; } } while ( std::next_permutation(characters.begin(),characters.begin() + characters.size()) ); //stack<string> reverseSet; // for(const string& x: permutedList) // { // cout << x << endl; // //reverseSet.push(x); // } // while(!reverseSet.empty()) // { // //cout << reverseSet.top() << endl; // resultSet.push_back(reverseSet.top()); // reverseSet.pop(); // } } int main() { int t; cin >> t; while(t > 0) { string str; cin >> str; produceAnanagrams(str); t--; } // for(int i=0;i<resultSet.size();i++) // { // cout << resultSet[i] << endl; // } return 0; }
[ "shaon@revesoft.com" ]
shaon@revesoft.com
9ef4e9c1688aadd17dbda6bda69efd7c51f2b9a0
266310ea0b8063e56918727a0a0f65bb22597fea
/src/backend/catalog/mataData.cpp
4cfa7e9f720ac6f4a8231b65454db1d68f7175c5
[]
no_license
RingsC/StorageEngine
88ec03d019d6378b93d8abd3a57a9447cf31b932
4e8447751867329e1d7b7dd9b4d00e2020be9306
refs/heads/master
2021-04-27T00:07:08.962455
2018-03-04T03:13:22
2018-03-04T03:13:22
123,751,907
2
1
null
null
null
null
UTF-8
C++
false
false
1,159
cpp
#include <iostream> #include <exception> #include "postgres.h" #include "postgres_ext.h" #include "catalog/metaData.h" #include "storage/spin.h" using namespace std; hash_map<Oid, Colinfo> g_col_info_cache; slock_t g_spinlock = SpinLockInit(&g_spinlock); void setColInfo(Oid colid, Colinfo pcol_info) { if(pcol_info == NULL) { return; } try { SpinLockAcquire(&g_spinlock); g_col_info_cache.insert(std::pair<Oid, Colinfo>(colid, pcol_info)); SpinLockRelease(&g_spinlock); } #ifdef _DEBUG catch(exception &r) { ereport(WARNING, (errmsg("Set ColInfo:%s %s",__FUNCTION__,r.what()))); } #else catch(exception &/*r*/) { } #endif } Colinfo getColInfo(Oid colid) { hash_map<Oid, Colinfo>::iterator iter; try { SpinLockAcquire(&g_spinlock); iter = g_col_info_cache.find(colid); if (iter != g_col_info_cache.end()) { SpinLockRelease(&g_spinlock); return iter->second; } SpinLockRelease(&g_spinlock); } #ifdef _DEBUG catch(exception &r) { ereport(WARNING, (errmsg("Get ColInfo:%s %s",__FUNCTION__,r.what()))); } #else catch(exception &/*r*/) { } #endif return NULL; }
[ "hom.lee@hotmail.com" ]
hom.lee@hotmail.com
9afd51135471e981f046ff7635bc6386666a2188
20b9fcfc1a657efaf6487bb4c2cb0ce326c79919
/Sources/Past/ABC094/ABC094C.cpp
f1a615bbe6340a94edf587032bb243e3de64348c
[]
no_license
kurose-th/CompetetiveProgramming
e729da45db40d7d382348bca703fbc2f4e81d06a
8b0fd918490941942aed4b9cf7cb733352ff4088
refs/heads/master
2020-03-21T22:53:11.154527
2020-02-16T11:25:43
2020-02-16T11:25:43
139,153,162
0
0
null
null
null
null
UTF-8
C++
false
false
858
cpp
#include <cstdio> #include <string> #include <cmath> #include <string> #include <algorithm> #include <iostream> #include <map> #include <vector> #include <iomanip> #include <tuple> #include <queue> using namespace std; typedef long long ll; #define rep(i, a, n) for (int i=a;i<n;++i) #define repeq(i, a, n) for(int i=a;i<=n;++i) #define per(i, a, n) for (int i=n-1; i>=a;--i) #define pb push_back #define mp make_pair #define all(x) (x).begin(), (x).end() // C - Many Medians int N; vector<ll> x; vector<ll> A; vector<ll> ans; int main(){ cin >> N; rep(i, 0, N){ ll tmp; cin >> tmp; x.push_back(tmp); A.push_back(tmp); } sort(all(A)); rep(i, 0, N){ if(x[i] >= A[(N/2)]){ cout << A[N/2-1] << endl; }else{ cout << A[N/2] << endl; } } return 0; }
[ "krs1218@gmail.com" ]
krs1218@gmail.com
1ebafccf35d7801953d4d12dec6589d8c3f51bab
401982f39507e281d90c1af3f2d81c15a30e3602
/engine/shader/abstract_shader_variant.cpp
34b9890fd8cc4baeba5cb4edd36e0950ae3b543e
[]
no_license
NukeBird/rendy
60a3ea2b6b324eb2b36ffd5625ff97687f059d83
72c7d7db34f374b8245b41f0e27b220dc9738fa8
refs/heads/master
2023-04-08T20:03:26.187857
2020-01-13T13:13:46
2020-01-13T13:13:46
211,322,159
0
0
null
null
null
null
UTF-8
C++
false
false
6,435
cpp
#include "abstract_shader_variant.h" #include "../util/log.h" #include <optick.h> Rendy::AbstractShaderVariant::AbstractShaderVariant(OGL version, const std::string& vtx, const std::string& frg): version(version) { OPTICK_EVENT(); this->vertex_source = vtx; this->fragment_source = frg; compile_shader(); OPTICK_TAG("id", program_id); } Rendy::AbstractShaderVariant::~AbstractShaderVariant() { OPTICK_EVENT(); reset(); } void Rendy::AbstractShaderVariant::set_uniform(const std::string& name, const glm::vec3& vec) { OPTICK_EVENT(); OPTICK_TAG("name", name.c_str()); auto location = get_uniform_location(name); if (location != -1) { glUniform3fv(location, 1, &vec[0]); } } void Rendy::AbstractShaderVariant::set_uniform(const std::string& name, const glm::mat4& mat) { OPTICK_EVENT(); OPTICK_TAG("name", name.c_str()); auto location = get_uniform_location(name); if (location != -1) { glUniformMatrix4fv(location, 1, false, &mat[0][0]); } } void Rendy::AbstractShaderVariant::set_uniform(const std::string& name, const glm::mat3& mat) { OPTICK_EVENT(); OPTICK_TAG("name", name.c_str()); auto location = get_uniform_location(name); if (location != -1) { glUniformMatrix3fv(location, 1, false, &mat[0][0]); } } void Rendy::AbstractShaderVariant::set_uniform(const std::string& name, const float number) { OPTICK_EVENT(); OPTICK_TAG("name", name.c_str()); auto location = get_uniform_location(name); if (location != -1) { glUniform1fv(location, 1, &number); } } void Rendy::AbstractShaderVariant::set_uniform(const std::string& name, const int number) { OPTICK_EVENT(); OPTICK_TAG("name", name.c_str()); auto location = get_uniform_location(name); if (location != -1) { glUniform1iv(location, 1, &number); } } void Rendy::AbstractShaderVariant::set_uniform(const std::string& name, const std::vector<glm::vec3>& vec_array) { OPTICK_EVENT(); OPTICK_TAG("name", name.c_str()); auto location = get_uniform_location(name); if (location != -1) { glUniform3fv(location, static_cast<GLsizei>(vec_array.size()), &vec_array[0][0]); } } void Rendy::AbstractShaderVariant::set_uniform(const std::string& name, const std::vector<glm::mat4>& mat_array) { OPTICK_EVENT(); OPTICK_TAG("name", name.c_str()); auto location = get_uniform_location(name); if (location != -1) { glUniformMatrix4fv(location, static_cast<GLsizei>(mat_array.size()), false, glm::value_ptr(mat_array[0])); } } void Rendy::AbstractShaderVariant::set_uniform(const std::string& name, const std::vector<glm::mat3>& mat_array) { OPTICK_EVENT(); OPTICK_TAG("name", name.c_str()); auto location = get_uniform_location(name); if (location != -1) { glUniformMatrix3fv(location, static_cast<GLsizei>(mat_array.size()), false, &mat_array[0][0][0]); } } void Rendy::AbstractShaderVariant::set_uniform(const std::string& name, const std::vector<float>& float_array) { OPTICK_EVENT(); OPTICK_TAG("name", name.c_str()); auto location = get_uniform_location(name); if (location != -1) { glUniform1fv(location, static_cast<GLsizei>(float_array.size()), &float_array[0]); } } void Rendy::AbstractShaderVariant::set_uniform(const std::string& name, const std::vector<int>& int_array) { OPTICK_EVENT(); OPTICK_TAG("name", name.c_str()); auto location = get_uniform_location(name); if (location != -1) { glUniform1iv(location, static_cast<GLsizei>(int_array.size()), &int_array[0]); } } int Rendy::AbstractShaderVariant::get_attribute_location(const std::string& name) const { OPTICK_EVENT(); int location = -1; auto it = attribute_cache.find(name); if (it != attribute_cache.end()) { location = (*it).second; } OPTICK_TAG("name", name.c_str()); OPTICK_TAG("location", location); return location; } int Rendy::AbstractShaderVariant::get_buffer_binding_point(const std::string & name) const { OPTICK_EVENT(); int location = -1; auto it = buffer_cache.find(name); if (it != buffer_cache.end()) { location = (*it).second; } OPTICK_TAG("name", name.c_str()); OPTICK_TAG("location", location); return location; } void Rendy::AbstractShaderVariant::bind() { OPTICK_EVENT(); OPTICK_TAG("id", program_id); glUseProgram(program_id); } void Rendy::AbstractShaderVariant::unbind() { OPTICK_EVENT(); OPTICK_TAG("id", program_id); glUseProgram(0); } void Rendy::AbstractShaderVariant::cache_stuff() { cache_uniform_locations(); cache_attribute_locations(); cache_buffer_binding_points(); if (!attribute_cache.empty()) { Log::info("CACHED ATTRIBUTES"); for (auto& i : attribute_cache) { Log::info("{0}: {1}", i.first, i.second); } } if (!uniform_cache.empty()) { Log::info("CACHED UNIFORMS"); for (auto& i : uniform_cache) { Log::info("{0}: {1}", i.first, i.second); } } if (!buffer_cache.empty()) { Log::info("BUFFER BINDING POINTS"); for (auto& i : buffer_cache) { Log::info("{0}: {1}", i.first, i.second); } } } void Rendy::AbstractShaderVariant::reload() { OPTICK_EVENT(); if (!validate()) { compile_shader(); } } bool Rendy::AbstractShaderVariant::validate() const { OPTICK_EVENT(); if (glIsProgram(program_id)) { int link_status; glGetProgramiv(program_id, GL_LINK_STATUS, &link_status); return link_status != GL_FALSE; } return false; } int Rendy::AbstractShaderVariant::get_uniform_location(const std::string& name) const { OPTICK_EVENT(); int location = -1; auto it = uniform_cache.find(name); if (it != uniform_cache.end()) { location = (*it).second; } OPTICK_TAG("name", name.c_str()); OPTICK_TAG("location", location); return location; } void Rendy::AbstractShaderVariant::compile_shader() { OPTICK_EVENT(); reset(); uint32_t vtx_id = glCreateShader(GL_VERTEX_SHADER); const char* vtx_str = vertex_source.c_str(); glShaderSource(vtx_id, 1, &vtx_str, NULL); glCompileShader(vtx_id); uint32_t frg_id = glCreateShader(GL_FRAGMENT_SHADER); const char* frg_str = fragment_source.c_str(); glShaderSource(frg_id, 1, &frg_str, NULL); glCompileShader(frg_id); program_id = glCreateProgram(); glAttachShader(program_id, vtx_id); glAttachShader(program_id, frg_id); glLinkProgram(program_id); glDeleteShader(vtx_id); glDeleteShader(frg_id); OPTICK_TAG("id", program_id); } void Rendy::AbstractShaderVariant::reset() { OPTICK_EVENT(); OPTICK_TAG("id", program_id); glDeleteProgram(program_id); program_id = 0; }
[ "nukebird.dev@gmail.com" ]
nukebird.dev@gmail.com
7c367d5be4407f2206a9b02ad338eb37df830524
c3959671a067b0d3ea77d7b82f60ba7637b3d73e
/obsoleto/alfatesters_placav2.2/GARABULLO18_prueba_lecturas.ino/tiempo.ino
1061f5d8a6dae639169983b5dbe571c6912f70c8
[]
no_license
DiegoLale/garabullo2018
ad00378642ad71dff8677a21a669e7cf322079bd
018b9c194da9e3329a60b7b8d07836c8449b5497
refs/heads/master
2021-04-26T22:35:52.848104
2020-11-06T16:31:08
2020-11-06T16:31:08
124,115,659
0
1
null
2018-03-06T17:43:30
2018-03-06T17:43:30
null
UTF-8
C++
false
false
451
ino
boolean test_tiempo_suficiente() { tiempo_actual = millis(); medida_tiempo = (tiempo_actual - tiempo_inicio) / 1000; //esta variable se usa para la longitud de la barra de tiempo if (tiempo_actual - tiempo_inicio > 120000) { return 0; } else return 1; } void muestra_barra_crono() { pantalla.fillRect(4, 72, 120 - medida_tiempo, 10, ST7735_GREEN); pantalla.fillRect(124 - medida_tiempo, 72, medida_tiempo , 10, ST7735_BLACK); }
[ "diegolale@gmail.com" ]
diegolale@gmail.com
72c13ecf97ca803411f7e06c2775ba982b159f28
c8ec5672fb971f146ad9819aa171d366394051c9
/AGPLightDemonstration-master/ASSIMPProject/ASSIMPProject/Mesh.h
6a62f2213d5ff75b905653054b4f8eceaba1dc14
[]
no_license
NickJ25/TempGroup
68b16c0d51688807041ca9ddd32fd07b71bd7188
e9872efd1da35c872d84beb9a34eb93be49497cf
refs/heads/master
2020-04-08T09:04:48.432234
2018-12-02T15:33:23
2018-12-02T15:33:23
159,206,909
2
0
null
null
null
null
UTF-8
C++
false
false
10,076
h
#pragma once #include <string> #include <fstream> #include <sstream> #include <iostream> #include <vector> #include <GL/glew.h> #include <glm/glm.hpp> #include <glm/gtc/matrix_transform.hpp> #include "Shader.h" using namespace std; struct Vertex { // Position glm::vec3 Position; // Normal glm::vec3 Normal; // TexCoords glm::vec2 TexCoords; //normal mapping variables glm::vec3 Tangent; glm::vec3 BiTangent; }; struct Texture { GLuint id; string type; aiString path; }; class Mesh { public: /* Mesh Data */ vector<Vertex> vertices; vector<GLuint> indices; vector<Texture> textures; /* Functions */ // Constructor Mesh( vector<Vertex> vertices, vector<GLuint> indices, vector<Texture> textures ) { this->vertices = vertices; this->indices = indices; this->textures = textures; // Now that we have all the required data, set the vertex buffers and its attribute pointers. this->setupMesh(); this->setupVMesh(); this->setupDMesh(); } // Render the mesh void Draw( Shader shader ) { // Bind appropriate textures GLuint diffuseNr = 1; GLuint specularNr = 1; GLuint normalNr = 1; GLuint occlusionNr = 1; for( GLuint i = 0; i < this->textures.size( ); i++ ) { glActiveTexture( GL_TEXTURE0 + i ); // Active proper texture unit before binding // Retrieve texture number (the N in diffuse_textureN) stringstream ss; string number; string name = this->textures[i].type; if( name == "texture_diffuse" ) { ss << diffuseNr++; // Transfer GLuint to stream } else if( name == "texture_specular" ) { ss << specularNr++; // Transfer GLuint to stream } else if (name == "texture_normal") { cout << "called normal map" << endl; ss << normalNr++; // Transfer GLuint to stream } number = ss.str( ); // Now set the sampler to the correct texture unit glUniform1i( glGetUniformLocation( shader.Program, ( name + number ).c_str( ) ), i ); // And finally bind the texture glBindTexture( GL_TEXTURE_2D, this->textures[i].id ); } // Also set each mesh's shininess property to a default value (if you want you could extend this to another mesh property and possibly change this value) glUniform1f( glGetUniformLocation( shader.Program, "material.shininess" ), 16.0f ); // Draw mesh glBindVertexArray( this->VAO ); glDrawElements( GL_TRIANGLES, this->indices.size( ), GL_UNSIGNED_INT, 0 ); glBindVertexArray( 0 ); // Always good practice to set everything back to defaults once configured. for ( GLuint i = 0; i < this->textures.size( ); i++ ) { glActiveTexture( GL_TEXTURE0 + i ); glBindTexture( GL_TEXTURE_2D, 0 ); } } void DrawVMesh(Shader shader) { // Draw mesh glBindVertexArray(this->VVAO); glDrawElements(GL_TRIANGLES, this->indices.size(), GL_UNSIGNED_INT, 0); glBindVertexArray(0); // Always good practice to set everything back to defaults once configured. for (GLuint i = 0; i < this->textures.size(); i++) { glActiveTexture(GL_TEXTURE0 + i); glBindTexture(GL_TEXTURE_2D, 0); } } void DrawTextured(Shader shader, GLuint tex1, GLuint tex2) { glActiveTexture(GL_TEXTURE0); // Active proper texture unit before binding glUniform1i(glGetUniformLocation(shader.Program, "textureUnit0"), 0); glBindTexture(GL_TEXTURE_2D, tex2); glActiveTexture(GL_TEXTURE1); // Active proper texture unit before binding glUniform1i(glGetUniformLocation(shader.Program, "textureUnit1"), 1); glBindTexture(GL_TEXTURE_2D, tex1); // Draw mesh glBindVertexArray(this->VAO); glDrawElements(GL_TRIANGLES, this->indices.size(), GL_UNSIGNED_INT, 0); glBindVertexArray(0); // Always good practice to set everything back to defaults once configured. for (GLuint i = 0; i < this->textures.size(); i++) { glActiveTexture(GL_TEXTURE0 + i); glBindTexture(GL_TEXTURE_2D, 0); } } void DrawDMesh(Shader shader) { // Bind appropriate textures GLuint diffuseNr = 1; GLuint specularNr = 1; GLuint normalNr = 1; for (GLuint i = 0; i < this->textures.size(); i++) { glActiveTexture(GL_TEXTURE0 + i); // Active proper texture unit before binding // Retrieve texture number (the N in diffuse_textureN) stringstream ss; string number; string name = this->textures[i].type; if (name == "texture_diffuse") { cout << "called diffuse map" << endl; ss << diffuseNr++; // Transfer GLuint to stream } else if (name == "texture_specular") { cout << "called specular map" << endl; ss << specularNr++; // Transfer GLuint to stream } else if (name == "texture_normal") { cout << "called normal map" << endl; ss << normalNr++; // Transfer GLuint to stream } number = ss.str(); // Now set the sampler to the correct texture unit glUniform1i(glGetUniformLocation(shader.Program, (name + number).c_str()), i); // And finally bind the texture glBindTexture(GL_TEXTURE_2D, this->textures[i].id); } // Draw mesh glBindVertexArray(this->DVAO); glDrawElements(GL_TRIANGLES, this->indices.size(), GL_UNSIGNED_INT, 0); glBindVertexArray(0); // Always good practice to set everything back to defaults once configured. for (GLuint i = 0; i < this->textures.size(); i++) { glActiveTexture(GL_TEXTURE0 + i); glBindTexture(GL_TEXTURE_2D, 0); } } private: /* Render data */ GLuint VAO, VBO, EBO; GLuint VVAO, VVBO, VEBO; GLuint DVAO, DVBO, DEBO; void setupVMesh() { // Create buffers/arrays glGenVertexArrays(1, &this->VVAO); glGenBuffers(1, &this->VVBO); glGenBuffers(1, &this->VEBO); glBindVertexArray(this->VVAO); // Load data into vertex buffers glBindBuffer(GL_ARRAY_BUFFER, this->VVBO); glBufferData(GL_ARRAY_BUFFER, this->vertices.size() * sizeof(Vertex), &this->vertices[0], GL_STATIC_DRAW); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, this->VEBO); glBufferData(GL_ELEMENT_ARRAY_BUFFER, this->indices.size() * sizeof(GLuint), &this->indices[0], GL_STATIC_DRAW); // Set the vertex attribute pointers // Vertex Positions glEnableVertexAttribArray(0); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (GLvoid *)0); glBindVertexArray(0); } /* Functions */ // Initializes all the buffer objects/arrays void setupMesh( ) { // Create buffers/arrays glGenVertexArrays( 1, &this->VAO ); glGenBuffers( 1, &this->VBO ); glGenBuffers( 1, &this->EBO ); glBindVertexArray( this->VAO ); // Load data into vertex buffers glBindBuffer( GL_ARRAY_BUFFER, this->VBO ); // A great thing about structs is that their memory layout is sequential for all its items. // The effect is that we can simply pass a pointer to the struct and it translates perfectly to a glm::vec3/2 array which // again translates to 3/2 floats which translates to a byte array. glBufferData( GL_ARRAY_BUFFER, this->vertices.size( ) * sizeof( Vertex ), &this->vertices[0], GL_STATIC_DRAW ); glBindBuffer( GL_ELEMENT_ARRAY_BUFFER, this->EBO ); glBufferData( GL_ELEMENT_ARRAY_BUFFER, this->indices.size( ) * sizeof( GLuint ), &this->indices[0], GL_STATIC_DRAW ); // Set the vertex attribute pointers // Vertex Positions glEnableVertexAttribArray( 0 ); glVertexAttribPointer( 0, 3, GL_FLOAT, GL_FALSE, sizeof( Vertex ), ( GLvoid * )0 ); // Vertex Normals glEnableVertexAttribArray( 1 ); glVertexAttribPointer( 1, 3, GL_FLOAT, GL_FALSE, sizeof( Vertex ), ( GLvoid * )offsetof( Vertex, Normal ) ); // Vertex Texture Coords glEnableVertexAttribArray(2); glVertexAttribPointer( 2, 2, GL_FLOAT, GL_FALSE, sizeof( Vertex ), ( GLvoid * )offsetof( Vertex, TexCoords ) ); // vertex tangents glEnableVertexAttribArray(3); glVertexAttribPointer(3, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), reinterpret_cast<void*>(offsetof(Vertex, Tangent))); // vertex bitangents glEnableVertexAttribArray(4); glVertexAttribPointer(4, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), reinterpret_cast<void*>(offsetof(Vertex, BiTangent))); glBindVertexArray( 0 ); } void setupDMesh() { // Create buffers/arrays glGenVertexArrays(1, &this->DVAO); glGenBuffers(1, &this->DVBO); glGenBuffers(1, &this->DEBO); glBindVertexArray(this->DVAO); // Load data into vertex buffers glBindBuffer(GL_ARRAY_BUFFER, this->DVBO); glBufferData(GL_ARRAY_BUFFER, this->vertices.size() * sizeof(Vertex), &this->vertices[0], GL_STATIC_DRAW); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, this->DEBO); glBufferData(GL_ELEMENT_ARRAY_BUFFER, this->indices.size() * sizeof(GLuint), &this->indices[0], GL_STATIC_DRAW); // Set the vertex attribute pointers // Vertex Positions glEnableVertexAttribArray(0); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (GLvoid *)0); // Vertex Texture Coords glEnableVertexAttribArray(2); glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (GLvoid *)offsetof(Vertex, Normal)); // Vertex Normals glEnableVertexAttribArray(1); glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex), (GLvoid *)offsetof(Vertex, TexCoords)); // vertex tangents glEnableVertexAttribArray(3); glVertexAttribPointer(3, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), reinterpret_cast<void*>(offsetof(Vertex, Tangent))); // vertex bitangents glEnableVertexAttribArray(4); glVertexAttribPointer(4, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), reinterpret_cast<void*>(offsetof(Vertex, BiTangent))); glBindVertexArray(0); } };
[ "chrislochhead123@outlook.com" ]
chrislochhead123@outlook.com
61411aa26972ff36e1eb17f67f1d7717a5081bba
72f1e6b2c742751c23ba16f824a0a91ae4cfcf99
/HackerEarth/HackerEarth_StringWeight.cpp
f16730b0932c897e77a9936e80b49966b0e46e20
[]
no_license
ms-darshan/Competitive-Coding
9d6f7e45a996cb30d54e54eb2c847eeeeccb5dab
76d2e229dd281d063cca6e3374c8d25ed5fff911
refs/heads/master
2020-04-14T00:37:16.076282
2018-05-26T20:00:40
2018-05-26T20:00:40
null
0
0
null
null
null
null
UTF-8
C++
false
false
880
cpp
//http://www.hackerearth.com/epiphany-4-1/algorithm/string-weight/ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #include <vector> #include <iostream> #include <algorithm> using namespace std; #define sp system("pause") #define FOR(i,a,b) for(int i=a;i<=b;++i) #define FORD(i,a,b) for(int i=a;i>=b;--i) #define REP(i,n) FOR(i,0,(int)n-1) #define MS0(x) memset(x,0,sizeof(x)) #define MS1(x) memset(x,1,sizeof(x)) #define ll long long #define MOD 1000000007 int main(){ int t, n, l; char c[10005], x, y; char skip[26]; int f[26]; ll int ans; scanf("%d", &t); REP(i, t){ MS0(f); ans = 0; scanf("%s", c); l = strlen(c); REP(j, l){ f[c[j] - 97]++; ans += (c[j] - 96); } scanf("%d", &n); REP(j, n){ scanf("%c%c", &x, &y); ans = ans - (f[y - 97] * (y - 96)); } printf("%lld\n", ans); } return 0; } //Solved
[ "akshay95aradhya@gmail.com" ]
akshay95aradhya@gmail.com
70780414496f670ad6b1c11e867727dd4c6db92a
8f7fa80257b32885aeb7964e82b73147ae74365f
/bst/BST_connect34.h
1e039520375ea6f1c0fa435d270bf3e40a941448
[]
no_license
npjtwy/DS_CPP
0f063a333121711666f29301dcefc0ffd1d06efe
6dbe68e67249cb513884f6828355f3bb8e13639a
refs/heads/master
2021-01-11T19:15:10.479933
2017-05-24T08:49:08
2017-05-24T08:49:08
79,341,972
0
0
null
null
null
null
GB18030
C++
false
false
653
h
#pragma once /* * 3+4 重构 将失衡子树重组为平衡子树 */ template<typename T> BinNodePosi(T) BST<T>::connect34( //按照“3 + 4”结构,联接3个节点及四棵子树 BinNodePosi(T) a, BinNodePosi(T) b, BinNodePosi(T) c, BinNodePosi(T) t1, BinNodePosi(T) t2, BinNodePosi(T) t3, BinNodePosi(T) t4 ) { a->lChild = t1; if ( t1 ) t1->parent = a; a->rChild = t2; if ( t2 ) t2->parent = a; updateHeight(a); c->lChild = t3; if ( t3 ) t3->parent = c; c->rChild = t4; if ( t4 ) t4->parent = c; updateHeight(c); a->parent = b; c->parent = b; b->lChild = a; b->rChild = c; updateHeight(b); return b;//返回新的子树根节点 }
[ "nwpuwy.qq.com" ]
nwpuwy.qq.com
74d8436d5960c5a5af7b5d5d015cade9ed4a977a
a06a9ae73af6690fabb1f7ec99298018dd549bb7
/_Library/_Include/boost/numeric/odeint/util/same_instance.hpp
d2a21e3f944788ff80c5164d1f560e0715a54dd6
[]
no_license
longstl/mus12
f76de65cca55e675392eac162dcc961531980f9f
9e1be111f505ac23695f7675fb9cefbd6fa876e9
refs/heads/master
2021-05-18T08:20:40.821655
2020-03-29T17:38:13
2020-03-29T17:38:13
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,356
hpp
/* [auto_generated] boost/numeric/odeint/util/same_instance.hpp [begin_description] Basic check if two variables are the same instance [end_description] Copyright 2012 Karsten Ahnert Copyright 2012 Mario Mulansky 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 BOOST_NUMERIC_ODEINT_UTIL_SAME_INSTANCE_HPP_INCLUDED #define BOOST_NUMERIC_ODEINT_UTIL_SAME_INSTANCE_HPP_INCLUDED namespace boost { namespace numeric { namespace odeint { template< class T1 , class T2 , class Enabler=void > struct same_instance_impl { static bool same_instance( const T1& /* x1 */ , const T2& /* x2 */ ) { return false; } }; template< class T > struct same_instance_impl< T , T > { static bool same_instance( const T &x1 , const T &x2 ) { // check pointers return (&x1 == &x2); } }; template< class T1 , class T2 > bool same_instance( const T1 &x1 , const T2 &x2 ) { return same_instance_impl< T1 , T2 >::same_instance( x1 , x2 ); } } // namespace odeint } // namespace numeric } // namespace boost #endif ///////////////////////////////////////////////// // vnDev.Games - Trong.LIVE - DAO VAN TRONG // ////////////////////////////////////////////////////////////////////////////////
[ "adm.fael.hs@gmail.com" ]
adm.fael.hs@gmail.com
7a5fd5e5340e4ffc1888d7a218a5e8135947c3b3
1a0ad7854a9b0a6ef5e946f7ee144ee6e5700f97
/Location-Aware-IM/limit.cpp
ecb5c933c76926e025227e4e0f7d836f19915252
[]
no_license
TsinghuaDatabaseGroup/SocialInfluenceMaximization
9f07241afdf10d350c387c2b5832e07645538440
68824561f616468dd5d3c63b6c11c811205a518b
refs/heads/master
2021-09-02T06:21:13.423035
2017-12-31T00:47:54
2017-12-31T00:47:54
114,575,221
13
2
null
null
null
null
UTF-8
C++
false
false
256
cpp
#include <vector> #include "limit.h" vector<bool> Args::is_native(MAX_NODE, false); vector<bool> Args::is_cdd(MAX_NODE, false); int Args::MAX_QK = 5000; int Args::MAX_CK = 5000; int Args::MIN_CK = 10; int Args::CACHE_RATIO = 10; int Args::CAPACITY = 500;
[ "liguoliang@mail.tsinghua.edu.cn" ]
liguoliang@mail.tsinghua.edu.cn
d5427077439ce97fea3a246705dcf17086076eed
9de29021638032dfc11056cecb250c34e92b2353
/Type 2/String Processing/Decode the tap Uva 10878.cpp
62ed6ce3c4ccabafa3a582e46a81e478918d9460
[]
no_license
mhRumi/Project-150-2017831023
18c5096c8125eb7eea9bfeacac690c19ebba0762
9f5b5cadcc1c02bf1d38515eb18de40fe0a5513d
refs/heads/master
2020-04-17T14:42:08.326923
2019-01-20T13:55:06
2019-01-20T13:55:06
166,667,718
6
0
null
null
null
null
UTF-8
C++
false
false
359
cpp
#include<bits/stdc++.h> using namespace std; int main() { char s[12]; gets(s); int box[]={0,0,64,32,16,8,0,4,2,1,0}; while(gets(s)){ if(s[0]=='_') break; int sum=0; for(int i=0;i<11;i++){ if(s[i]=='o') sum=sum+box[i]; } cout<<char(sum); } return 0; }
[ "mh913350@gmail.com" ]
mh913350@gmail.com
beba5c80af02a979a90a1b609cd9991a5a1cf7cd
bf1e7cb6a0405bd4ab8986a1fdd108525fb576e6
/src/GA/Genome.cpp
32e92bb01fe009e2d85c38333f8888cf3800ccb8
[]
no_license
reckter/TravelingSaleseman
f0062096a07972908f804c7be9d6119016dde7f6
ce4cdca88b3a72b5c669718ac5c4b74dfb59e302
refs/heads/master
2020-04-25T05:10:07.287231
2014-12-15T14:40:09
2014-12-15T14:40:09
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,353
cpp
/* * Genome.cpp * * Created on: Nov 17, 2014 * Author: ahueck */ #include "Genome.h" #include "Util.h" namespace practical { namespace ga { Genome::Genome() : genes() { } Genome::Genome(const std::vector<IntGene>& genes) : genes(genes) { } Genome::Genome(const Genome& other) : genes(other.genes) { } const Genome& Genome::operator=(const Genome& rhs) { if (this != &rhs) { genes = rhs.genes; } return *this; } Genome* Genome::deepCopy() const { Genome* copy = shallowCopy(); copy->genes = this->genes; return copy; } bool Genome::operator<(const Genome& rhs) const { return fitness() < rhs.fitness(); } int Genome::duel(const Genome& opponent) const { const double fitness = this->fitness(); const double opo_fitness = opponent.fitness(); if (fitness > opo_fitness) { return 1; } else if (fitness < opo_fitness) { return -1; } return 0; } const std::vector<IntGene>& Genome::getGenes() const { return genes; } std::vector<IntGene>& Genome::getGenes() { return genes; } Genome::~Genome() { } std::ostream& operator<<(std::ostream& os, const Genome& genome) { os << "["; std::vector<practical::ga::IntGene>::const_iterator iter = genome.getGenes().begin(); for (; iter < genome.getGenes().end() - 1; ++iter) { os << *iter << " "; } return os << *iter << "] " << 1.0 / genome.fitness(); } } }
[ "hannes@guedelhoefer.de" ]
hannes@guedelhoefer.de
2eb0dafe8bcadb3a2e79f44ea90c0730f2a935e9
4ccc8236ac25c743abc77fcde9f68fdec87760c6
/DefenceTurret.cpp
b1a2fc5be0dcb47bbe117c094a7abcd83cea9ab6
[]
no_license
hazeandgaze/shu-oop-battlefield
d5639746c676b9a729d83ab1d3a917407b825020
98f47d17ffe97b47b49d3343b2c33b3eb03e5f15
refs/heads/master
2023-07-19T08:56:32.883597
2018-08-27T19:07:26
2018-08-27T19:07:26
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,600
cpp
#include "DefenceTurret.h" //Attacker(const Position &p, const int c, int h, int s, int m, int r, int cost); DefenceTurret::DefenceTurret(const wchar_t *f, const Position &p, const int & c) : Defence(p, c, 200, 150), filename(f), Attacker(p, c, 200, 25, 0, 6, 150, "The Menace"), IUnit(p, { 1,1 }, c, 200, 150), Structure(p, { 1,1 }, c, 200, 150), Infantry(p, { 1,1 }, c, 200, 0, 150) {} DefenceTurret::~DefenceTurret() {} const wchar_t * DefenceTurret::GetFilename() const { return filename; } const int DefenceTurret::GetMaxHealth() const { return DefenceTurret::maxhealth; } const std::string DefenceTurret::GetName() const { return name; } const std::string DefenceTurret::GetOption() const { return option; } const Size & DefenceTurret::GetSize() const { return Defence::size; } const int & DefenceTurret::GetColour() const { return Defence::colour; } const int & DefenceTurret::GetRange() const { return Attacker::range; } const int & DefenceTurret::GetStrength() const { return Attacker::strength; } void DefenceTurret::Attack(IUnit* enemy) { if (enemy->GetColour() != colour) { enemy->DecreaseHealth(strength); hasAttacked = true; if (enemy->GetHealth() <= 0) { killstreak++; Promote(); } } } void DefenceTurret::Promote() { switch (killstreak) { case 3: rank = "The Hunter"; maxhealth = 220; strength = 30; moves = moves++; break; case 7: rank = "The Oppressor"; maxhealth = 300; strength = 45; break; case 13: rank = "The Dictator"; maxhealth = 420; strength = 70; moves = 3; break; } }
[ "noreply@github.com" ]
hazeandgaze.noreply@github.com
fc367bfbf43a6c7984e121f6c9ae9b7fd476ed10
05a8e4cdcc7b49dc7c92e759fc2f14d398ca9a2e
/projeto/QtTcpClientConsumer/plotter.cpp
45f19e629129900dae19464d0484c8ec02e14a17
[]
no_license
Ana-Beatriz-Marinho/DCA1202
8123bd2b6d1ad124f8be213caff99828d6258391
7e924f1cad7b0e2e173ef15d17a6da54499ea616
refs/heads/master
2020-04-03T11:47:48.357799
2018-12-12T10:39:11
2018-12-12T10:39:11
155,232,077
0
0
null
null
null
null
UTF-8
C++
false
false
1,249
cpp
#include "plotter.h" #include <QPainter> #include <QBrush> #include <QPen> #include <cmath> #include <QMouseEvent> using namespace std; #define PI 3.1415 Plotter::Plotter(QWidget *parent) : QWidget(parent){ } void Plotter::paintEvent(QPaintEvent *evento){ QPainter painter(this); QBrush brush; QPen pen; int x1, y1, x2, y2; //brush cor amarela e sólida brush.setColor(QColor(255,255,100)); brush.setStyle(Qt::SolidPattern); //caneta cor vermelha pen.setColor(QColor(255,0,0)); pen.setWidth(2); //informe ao pintor qual o brush atual painter.setBrush(brush); //informa um retangulo abrangendo toda a extensao painter.setPen(pen); //desenha um retangulo abrangendo toda extensao //componente painter.drawRect(0,0,width(),height()); //desenha um seno na tela pen.setColor(QColor(255,180,0)); painter.setPen(pen); painter.drawLine(0, height()/2, width(), height()/2); x1 = 0; y1 = height()/2; //desenha um seno na tela pen.setColor(QColor(0,0,255)); painter.setPen(pen); for(int i=1; i<width(); i++){ x2 = i; y2 = height()/2 *(1- sin(2*PI*x2/width())); painter.drawLine(x1,y1,x2,y2); x1 = x2; y1 = y2; } } void Plotter::mousePressEvent(QMouseEvent *event) { emit mudouX(event->x()); emit mudouY(event->y()); }
[ "anabibimn@hotmail.com" ]
anabibimn@hotmail.com
781647facaa7cc4d0a19fab05eb6bf4ba8737390
a5e486f7e08ab39fc18627518dfc1da8df57f8b5
/DroppingBalls.cpp
3dd8c1cac33e8a59aa6a077a67358ab18336fcae
[]
no_license
Anfer2325/Estructuras-de-datos-y-algoritmos
621aaeabd2666cdae4cfba35387363815b63892a
57b49297d9592f8429869c2962da765b79c2a6a6
refs/heads/master
2020-04-23T18:18:09.648375
2015-02-12T21:45:00
2015-02-12T21:45:00
null
0
0
null
null
null
null
ISO-8859-1
C++
false
false
55,221
cpp
/* Definición de algunas excepciones de las distintas implementaciones de los TADs. Estructura de Datos y Algoritmos Facultad de Informática Universidad Complutense de Madrid (c) Marco Antonio Gómez Martín, 2012 */ #ifndef __ARBOLES_H #define __ARBOLES_H #include <string> #include <iosfwd> #include <cassert> /** Clase de la que heredan todas las excepciones, y que proporciona el atributo que almacena el mensaje de error. */ class ExcepcionTAD { public: ExcepcionTAD() {} ExcepcionTAD(const std::string &msg) : _msg(msg) {} const std::string msg() const { return _msg; } friend std::ostream &operator<<(std::ostream &out, const ExcepcionTAD &e); protected: std::string _msg; }; inline std::ostream &operator<<(std::ostream &out, const ExcepcionTAD &e) { out << e._msg; return out; } // Macro para declarar las clases de tipo excepción // que heredan de ExcepcionConMensaje, para ahorrar // escribir muchas veces lo mismo... #define DECLARA_EXCEPCION(Excepcion) \ class Excepcion : public ExcepcionTAD { \ public: \ Excepcion() {}; \ Excepcion(const std::string &msg) : ExcepcionTAD(msg) {} \ }; /** Excepción generada por algunas operaciones de las pilas. */ DECLARA_EXCEPCION(EPilaVacia); /** Excepción generada por algunas de las operaciones de las colas. */ DECLARA_EXCEPCION(EColaVacia); /** Excepción generada por algunas operaciones de las colas dobles. */ DECLARA_EXCEPCION(EDColaVacia); /** Excepción generada por algunas operaciones de las listas. */ DECLARA_EXCEPCION(EListaVacia); /** Excepción generada por accesos incorrectos a las listas (tanto a un número de elemento incorrecto como por mal manejo de los iteradores). */ DECLARA_EXCEPCION(EAccesoInvalido); /** Excepción generada por algunas operaciones de los árboles binarios. */ DECLARA_EXCEPCION(EArbolVacio); /** Excepción generada por algunas operaciones de los árboles de búsqueda. */ DECLARA_EXCEPCION(EClaveErronea); /** @file Lista.h Implementación del TAD lista, utilizando una lista doblemente enlazada. Estructura de Datos y Algoritmos Facultad de Informática Universidad Complutense de Madrid (c) Marco Antonio Gómez Martín, 2012 */ /** Implementación del TAD Pila utilizando vectores dinámicos. Las operaciones son: - ListaVacia: -> Lista. Generadora implementada en el constructor sin parámetros. - Cons: Lista, Elem -> Lista. Generadora. - ponDr: Lista, Elem -> Lista. Modificadora. - primero: Lista - -> Elem. Observadora parcial - resto: Lista - -> Lista. Modificadora parcial - ultimo: Lista - -> Elem. Observadora parcial - inicio: Lista - -> Lista. Modificadora parcial - esVacia: Lista -> Bool. Observadora - numElems: Lista -> Elem. Obervadora. - elem: Lista, Entero - -> Elem. Observador parcial. @author Marco Antonio Gómez Martín */ template <class T> class Lista { private: /** Clase nodo que almacena internamente el elemento (de tipo T), y dos punteros, uno al nodo anterior y otro al nodo siguiente. Ambos punteros podrían ser NULL si el nodo es el primero y/o último de la lista enlazada. */ class Nodo { public: Nodo() : _sig(NULL), _ant(NULL) {} Nodo(const T &elem) : _elem(elem), _sig(NULL), _ant(NULL) {} Nodo(Nodo *ant, const T &elem, Nodo *sig) : _elem(elem), _sig(sig), _ant(ant) {} T _elem; Nodo *_sig; Nodo *_ant; }; public: /** Constructor; operación ListaVacia. */ Lista() : _prim(NULL), _ult(NULL), _numElems(0) {} /** Destructor; elimina la lista doblemente enlazada. */ ~Lista() { libera(); } /** Añade un nuevo elemento en la cabeza de la lista. Operación generadora. @param elem Elemento que se añade en la cabecera de la lista. */ void Cons(const T &elem) { _numElems++; _prim = insertaElem(elem, NULL, _prim); if (_ult == NULL) _ult = _prim; } /** Añade un nuevo elemento al final de la lista (a la "derecha"). Operación modificadora. ponDr(e, ListaVacia) = Cons(e, ListaVacia) ponDr(e, Cons(x, xs)) = Cons(x, ponDr(e, xs)) */ void ponDr(const T &elem) { _numElems++; _ult = insertaElem(elem, _ult, NULL); if (_prim == NULL) _prim = _ult; } /** Devuelve el valor almacenado en la cabecera de la lista. Es un error preguntar por el primero de una lista vacía. primero(Cons(x, xs)) = x error primero(ListaVacia) @return Elemento en la cabecera de la lista. */ const T &primero() const { if (esVacia()) throw EListaVacia(); return _prim->_elem; } /** Devuelve el valor almacenado en la última posición de la lista (a la derecha). Es un error preguntar por el primero de una lista vacía. ultimo(Cons(x, xs)) = x SI esVacia(xs) ultimo(Cons(x, xs)) = ultimo(xs) SI !esVacia(xs) error ultimo(ListaVacia) @return Elemento en la cola de la lista. */ const T &ultimo() const { if (esVacia()) throw EListaVacia(); return _ult->_elem; } /** Elimina el primer elemento de la lista. Es un error intentar obtener el resto de una lista vacía. resto(Cons(x, xs)) = xs error resto(ListaVacia) */ void resto() { if (esVacia()) throw EListaVacia(); Nodo *aBorrar = _prim; _prim = _prim->_sig; borraElem(aBorrar); if (_prim == NULL) _ult = NULL; --_numElems; } /** Elimina el último elemento de la lista. Es un error intentar obtener el inicio de una lista vacía. inicio(Cons(x, ListaVacia)) = ListaVacia inicio(Cons(x, xs)) = Cons(x, inicio(xs)) SI !esVacia(xs) error inicio(ListaVacia) */ void inicio() { if (esVacia()) throw EListaVacia(); Nodo *aBorrar = _ult; _ult = _ult->_ant; borraElem(aBorrar); if (_ult == NULL) _prim = NULL; --_numElems; } /** Operación observadora para saber si una lista tiene o no elementos. esVacia(ListaVacia) = true esVacia(Cons(x, xs)) = false @return true si la lista no tiene elementos. */ bool esVacia() const { return _prim == NULL; } /** Devuelve el número de elementos que hay en la lista. numElems(ListaVacia) = 0 numElems(Cons(x, xs)) = 1 + numElems(xs) @return Número de elementos. */ unsigned int numElems() const { return _numElems; } /** Devuelve el elemento i-ésimo de la lista, teniendo en cuenta que el primer elemento (primero()) es el elemento 0 y el último es numElems()-1, es decir idx está en [0..numElems()-1]. Operación observadora parcial que puede fallar si se da un índice incorrecto. El índice es entero sin signo, para evitar que se puedan pedir elementos negativos. elem(0, Cons(x, xs)) = x elem(n, Cons(x, xs)) = elem(n-1, xs) si n > 0 error elem(n, xs) si !( 0 <= n < numElems(xs) ) */ const T &elem(unsigned int idx) const { if (idx >= _numElems) throw EAccesoInvalido(); Nodo *aux = _prim; for (int i = 0; i < idx; ++i) aux = aux->_sig; return aux->_elem; } /** Clase interna que implementa un iterador sobre la lista que permite recorrer la lista e incluso alterar el valor de sus elementos. */ class Iterador { public: void avanza() { if (_act == NULL) throw EAccesoInvalido(); _act = _act->_sig; } const T &elem() const { if (_act == NULL) throw EAccesoInvalido(); return _act->_elem; } void pon(const T &elem) { if (_act == NULL) throw EAccesoInvalido(); _act->_elem = elem; } bool operator==(const Iterador &other) const { return _act == other._act; } bool operator!=(const Iterador &other) const { return !(this->operator==(other)); } protected: // Para que pueda construir objetos del // tipo iterador friend class Lista; Iterador() : _act(NULL) {} Iterador(Nodo *act) : _act(act) {} // Puntero al nodo actual del recorrido Nodo *_act; }; /** Devuelve el iterador al principio de la lista. @return iterador al principio de la lista; coincidirá con final() si la lista está vacía. */ Iterador principio() { return Iterador(_prim); } /** @return Devuelve un iterador al final del recorrido (fuera de éste). */ Iterador final() const { return Iterador(NULL); } /** Permite eliminar de la lista el elemento apuntado por el iterador que se pasa como parámetro. El iterador recibido DEJA DE SER VÁLIDO. En su lugar, deberá utilizarse el iterador devuelto, que apuntará al siguiente elemento al borrado. @param it Iterador colocado en el elemento que se quiere borrar. @return Nuevo iterador colocado en el elemento siguiente al borrado (podría coincidir con final() si el elemento que se borró era el último de la lista). */ Iterador borra(const Iterador &it) { if (it._act == NULL) throw EAccesoInvalido(); // Cubrimos los casos especiales donde // borramos alguno de los extremos if (it._act == _prim) { resto(); return Iterador(_prim); } else if (it._act == _ult) { inicio(); return Iterador(NULL); } else { // El elemento a borrar es interno a la lista. --_numElems; Nodo *sig = it._act->_sig; borraElem(it._act); return Iterador(sig); } } /** Método para insertar un elemento en la lista en el punto marcado por el iterador. En concreto, se añade _justo antes_ que el elemento actual. Es decir, si it==l.primero(), el elemento insertado se convierte en el primer elemento (y el iterador apuntará al segundo). Si it==l.final(), el elemento insertado será el último (e it seguirá apuntando fuera del recorrido). @param elem Valor del elemento a insertar. @param it Punto en el que insertar el elemento. */ void insertar(const T &elem, const Iterador &it) { // Caso especial: ¿añadir al principio? if (_prim == it._act) { Cons(elem); } else // Caso especial: ¿añadir al final? if (it._act == NULL) { ponDr(elem); } // Caso normal else { insertaElem(elem, it._act->_ant, it._act); } } // // // MÉTODOS DE "FONTANERÍA" DE C++ QUE HACEN VERSÁTIL // A LA CLASE // // /** Constructor copia */ Lista(const Lista<T> &other) : _prim(NULL), _ult(NULL) { copia(other); } /** Operador de asignación */ Lista<T> &operator=(const Lista<T> &other) { if (this != &other) { libera(); copia(other); } return *this; } /** Operador de comparación. */ bool operator==(const Lista<T> &rhs) const { if (_numElems != rhs._numElems) return false; Nodo *p1 = _prim; Nodo *p2 = rhs._prim; while ((p1 != NULL) && (p2 != NULL)) { if (p1->_elem != p2->_elem) return false; p1 = p1->_sig; p2 = p2->_sig; } return (p1 == NULL) && (p2 == NULL); } bool operator!=(const Lista<T> &rhs) const { return !(*this == rhs); } protected: void libera() { libera(_prim); _prim = NULL; _ult = NULL; } void copia(const Lista<T> &other) { // En vez de trabajar con punteros en la inserción, // usamos ponDr _prim = 0; _numElems = 0; Nodo *act = other._prim; while (act != NULL) { ponDr(act->_elem); act = act->_sig; } } private: /** Inserta un elemento entre el nodo1 y el nodo2. Devuelve el puntero al nodo creado. Caso general: los dos nodos existen. nodo1->_sig == nodo2 nodo2->_ant == nodo1 Casos especiales: alguno de los nodos no existe nodo1 == NULL y/o nodo2 == NULL */ static Nodo *insertaElem(const T &e, Nodo *nodo1, Nodo *nodo2) { Nodo *nuevo = new Nodo(nodo1, e, nodo2); if (nodo1 != NULL) nodo1->_sig = nuevo; if (nodo2 != NULL) nodo2->_ant = nuevo; return nuevo; } /** Elimina el nodo n. Si el nodo tiene nodos antes o después, actualiza sus punteros anterior y siguiente. Caso general: hay nodos anterior y siguiente. Casos especiales: algunos de los nodos (anterior o siguiente a n) no existen. */ static void borraElem(Nodo *n) { assert(n != NULL); Nodo *ant = n->_ant; Nodo *sig = n->_sig; if (ant != NULL) ant->_sig = sig; if (sig != NULL) sig->_ant = ant; delete n; } /** Elimina todos los nodos de la lista enlazada cuyo primer nodo se pasa como parámetro. Se admite que el nodo sea NULL (no habrá nada que liberar). En caso de pasarse un nodo válido, su puntero al nodo anterior debe ser NULL (si no, no sería el primero de la lista!). */ static void libera(Nodo *prim) { assert(!prim || !prim->_ant); while (prim != NULL) { Nodo *aux = prim; prim = prim->_sig; delete aux; } } // Puntero al primer y último elemento Nodo *_prim, *_ult; // Número de elementos (número de nodos entre _prim y _ult) unsigned int _numElems; }; /** @file Pila.h Implementación del TAD Pila utilizando un vector dinámico cuyo tamaño va creciendo si es necesario. Estructura de Datos y Algoritmos Facultad de Informática Universidad Complutense de Madrid (c) Marco Antonio Gómez Martín, 2012 */ /** Implementación del TAD Pila utilizando vectores dinámicos. Las operaciones son: - PilaVacia: -> Pila. Generadora implementada en el constructor sin parámetros. - apila: Pila, Elem -> Pila. Generadora - desapila: Pila - -> Pila. Modificadora parcial. - cima: Pila - -> Elem. Observadora parcial. - esVacia: Pila -> Bool. Observadora. - numElems: Pila -> Entero. Observadora. @author Marco Antonio Gómez Martín */ template <class T> class Pila { public: /** Tamaño inicial del vector dinámico. */ enum { TAM_INICIAL = 10 }; /** Constructor; operación PilaVacia */ Pila() { inicia(); } /** Destructor; elimina el vector. */ ~Pila() { libera(); } /** Apila un elemento. Operación generadora. @param elem Elemento a apilar. */ void apila(const T &elem) { if (_numElems == _tam) amplia(); _v[_numElems] = elem; _numElems++; } /** Desapila un elemento. Operación modificadora parcial, que falla si la pila está vacía. desapila(Apila(elem, p)) = p error: desapila(PilaVacia) */ void desapila() { if (esVacia()) throw EPilaVacia(); --_numElems; } /** Devuelve el elemento en la cima de la pila. Operación observadora parcial, que falla si la pila está vacía. cima(Apila(elem, p) = elem error: cima(PilaVacia) @return Elemento en la cima de la pila. */ const T &cima() const { if (esVacia()) throw EPilaVacia(); return _v[_numElems - 1]; } /** Devuelve true si la pila no tiene ningún elemento. esVacia(PilaVacia) = true esVacia(Apila(elem, p)) = false @return true si la pila no tiene ningún elemento. */ bool esVacia() const { return _numElems == 0; } /** Devuelve el número de elementos que hay en la pila. numElems(PilaVacia) = 0 numElems(Apila(elem, p)) = 1 + numElems(p) @return Número de elementos. */ int numElems() const { return _numElems; } // // // MÉTODOS DE "FONTANERÍA" DE C++ QUE HACEN VERSÁTIL // A LA CLASE // // /** Constructor copia */ Pila(const Pila<T> &other) { copia(other); } /** Operador de asignación */ Pila<T> &operator=(const Pila<T> &other) { if (this != &other) { libera(); copia(other); } return *this; } /** Operador de comparación. */ bool operator==(const Pila<T> &rhs) const { if (_numElems != rhs._numElems) return false; for (unsigned int i = 0; i < _numElems; ++i) if (_v[i] != rhs._v[i]) return false; return true; } bool operator!=(const Pila<T> &rhs) const { return !(*this == rhs); } protected: void inicia() { _v = new T[TAM_INICIAL]; _tam = TAM_INICIAL; _numElems = 0; } void libera() { delete []_v; _v = NULL; } void copia(const Pila &other) { _tam = other._numElems + TAM_INICIAL; _numElems = other._numElems; _v = new T[_tam]; for (unsigned int i = 0; i < _numElems; ++i) _v[i] = other._v[i]; } void amplia() { T *viejo = _v; _tam *= 2; _v = new T[_tam]; for (unsigned int i = 0; i < _numElems; ++i) _v[i] = viejo[i]; delete []viejo; } private: /** Puntero al array que contiene los datos. */ T *_v; /** Tamaño del vector _v. */ unsigned int _tam; /** Número de elementos reales guardados. */ unsigned int _numElems; }; /** @file PilaLE.h Implementación del TAD Pila utilizando una lista enlazada de nodos. Estructura de Datos y Algoritmos Facultad de Informática Universidad Complutense de Madrid (c) Marco Antonio Gómez Martín, 2012 */ /** Implementación del TAD Pila utilizando vectores dinámicos. Las operaciones son: - PilaVacia: -> Pila. Generadora implementada en el constructor sin parámetros. - apila: Pila, Elem -> Pila. Generadora - desapila: Pila - -> Pila. Modificadora parcial. - cima: Pila - -> Elem. Observadora parcial. - esVacia: Pila -> Bool. Observadora. - numElems: Pila -> Entero. Observadora. @author Marco Antonio Gómez Martín */ template <class T> class PilaLE { public: /** Constructor; operación PilaVacia */ PilaLE() : _cima(NULL), _numElems(0) { } /** Destructor; elimina la lista enlazada. */ ~PilaLE() { libera(); _cima = NULL; } /** Apila un elemento. Operación generadora. @param elem Elemento a apilar. */ void apila(const T &elem) { _cima = new Nodo(elem, _cima); _numElems++; } /** Desapila un elemento. Operación modificadora parcial, que falla si la pila está vacía. desapila(Apila(elem, p) = p error: desapila(PilaVacia) */ void desapila() { if (esVacia()) throw EPilaVacia(); Nodo *aBorrar = _cima; _cima = _cima->_sig; delete aBorrar; --_numElems; } /** Devuelve el elemento en la cima de la pila. Operación observadora parcial, que falla si la pila está vacía. cima(Apila(elem, p) = elem error: cima(PilaVacia) @return Elemento en la cima de la pila. */ const T &cima() const { if (esVacia()) throw EPilaVacia(); return _cima->_elem; } /** Devuelve true si la pila no tiene ningún elemento. esVacia(PilaVacia) = true esVacia(Apila(elem, p)) = false @return true si la pila no tiene ningún elemento. */ bool esVacia() const { return _cima == NULL; } /** Devuelve el número de elementos que hay en la pila. numElems(PilaVacia) = 0 numElems(Apila(elem, p)) = 1 + numElems(p) @return Número de elementos. */ int numElems() const { return _numElems; } // // // MÉTODOS DE "FONTANERÍA" DE C++ QUE HACEN VERSÁTIL // A LA CLASE // // /** Constructor copia */ PilaLE(const PilaLE<T> &other) : _cima(NULL) { copia(other); } /** Operador de asignación */ PilaLE<T> &operator=(const PilaLE<T> &other) { if (this != &other) { libera(); copia(other); } return *this; } /** Operador de comparación. */ bool operator==(const PilaLE<T> &rhs) const { if (_numElems != rhs._numElems) return false; Nodo *cima1 = _cima; Nodo *cima2 = rhs._cima; while ((cima1 != NULL) && (cima2 != NULL)) { if (cima1->_elem != cima2->_elem) return false; cima1 = cima1->_sig; cima2 = cima2->_sig; } return (cima1 == NULL) && (cima2 == NULL); } bool operator!=(const PilaLE<T> &rhs) const { return !(*this == rhs); } protected: void libera() { libera(_cima); } void copia(const PilaLE &other) { if (other.esVacia()) { _cima = NULL; _numElems = 0; } else { Nodo *act = other._cima; Nodo *ant; _cima = new Nodo(act->_elem); ant = _cima; while (act->_sig != NULL) { act = act->_sig; ant->_sig = new Nodo(act->_elem); ant = ant->_sig; } _numElems = other._numElems; } } private: /** Clase nodo que almacena internamente el elemento (de tipo T), y un puntero al nodo siguiente, que podría ser NULL si el nodo es el último de la lista enlazada. */ class Nodo { public: Nodo() : _sig(NULL) {} Nodo(const T &elem) : _elem(elem), _sig(NULL) {} Nodo(const T &elem, Nodo *sig) : _elem(elem), _sig(sig) {} T _elem; Nodo *_sig; }; /** Elimina todos los nodos de la lista enlazada cuyo primer nodo se pasa como parámetro. Se admite que el nodo sea NULL (no habrá nada que liberar). */ static void libera(Nodo *prim) { while (prim != NULL) { Nodo *aux = prim; prim = prim->_sig; delete aux; } } /** Puntero al primer elemento */ Nodo *_cima; /** Número de elementos */ int _numElems; }; /** @file Cola.h Implementación del TAD Cola utilizando una lista enlazada de nodos. Estructura de Datos y Algoritmos Facultad de Informática Universidad Complutense de Madrid (c) Marco Antonio Gómez Martín, 2012 */ /** Implementación del TAD Cola utilizando una lista enlazada. Las operaciones son: - ColaVacia: -> Cola. Generadora implementada en el constructor sin parámetros. - PonDetras: Cola, Elem -> Cola. Generadora - quitaPrim: Cola - -> Cola. Modificadora parcial. - primero: Cola - -> Elem. Observadora parcial. - esVacia: Cola -> Bool. Observadora. - numElems: Cola -> Entero. Observadora. @author Marco Antonio Gómez Martín */ template <class T> class Cola { public: /** Constructor; operacion ColaVacia */ Cola() : _prim(NULL), _ult(NULL), _numElems(0) { } /** Destructor; elimina la lista enlazada. */ ~Cola() { libera(); _prim = _ult = NULL; } /** Añade un elemento en la parte trasera de la cola. Operación generadora. @param elem Elemento a añadir. */ void ponDetras(const T &elem) { Nodo *nuevo = new Nodo(elem, NULL); if (_ult != NULL) _ult->_sig = nuevo; _ult = nuevo; // Si la cola estaba vacía, el primer elemento // es el que acabamos de añadir if (_prim == NULL) _prim = nuevo; _numElems++; } /** Elimina el primer elemento de la cola. Operación modificadora parcial, que falla si la cola está vacía. quitaPrim(PonDetras(elem, ColaVacia)) = ColaVacia quitaPrim(PonDetras(elem, xs)) = PonDetras(elem, quitaPrim(xs)) si !esVacia(xs) error: quitaPrim(ColaVacia) */ void quitaPrim() { if (esVacia()) throw EColaVacia(); Nodo *aBorrar = _prim; _prim = _prim->_sig; delete aBorrar; --_numElems; // Si la cola se quedó vacía, no hay // último if (_prim == NULL) _ult = NULL; } /** Devuelve el primer elemento de la cola. Operación observadora parcial, que falla si la cola está vacía. primero(PonDetras(elem, ColaVacia)) = elem primero(PonDetras(elem, xs)) = primero(xs) si !esVacia(xs) error: primero(ColaVacia) @return El primer elemento de la cola. */ const T &primero() const { if (esVacia()) throw EColaVacia(); return _prim->_elem; } /** Devuelve true si la cola no tiene ningún elemento. esVacia(Cola) = true esVacia(PonDetras(elem, p)) = false @return true si la cola no tiene ningún elemento. */ bool esVacia() const { return _prim == NULL; } /** Devuelve el número de elementos que hay en la cola. numElems(ColaVacia) = 0 numElems(PonDetras(elem, p)) = 1 + numElems(p) @return Número de elementos. */ int numElems() const { return _numElems; } // // // MÉTODOS DE "FONTANERÍA" DE C++ QUE HACEN VERSÁTIL // A LA CLASE // // /** Constructor copia */ Cola(const Cola<T> &other) : _prim(NULL), _ult(NULL) { copia(other); } /** Operador de asignación */ Cola<T> &operator=(const Cola<T> &other) { if (this != &other) { libera(); copia(other); } return *this; } /** Operador de comparación. */ bool operator==(const Cola<T> &rhs) const { if (_numElems != rhs._numElems) return false; Nodo *p1 = _prim; Nodo *p2 = rhs._prim; while ((p1 != NULL) && (p2 != NULL)) { if (p1->_elem != p2->_elem) return false; p1 = p1->_sig; p2 = p2->_sig; } return (p1 == NULL) && (p2 == NULL); } bool operator!=(const Cola<T> &rhs) const { return !(*this == rhs); } protected: void libera() { libera(_prim); } void copia(const Cola &other) { if (other.esVacia()) { _prim = _ult = NULL; _numElems = 0; } else { Nodo *act = other._prim; Nodo *ant; _prim = new Nodo(act->_elem); ant = _prim; while (act->_sig != NULL) { act = act->_sig; ant->_sig = new Nodo(act->_elem); ant = ant->_sig; } _ult = ant; _numElems = other._numElems; } } private: /** Clase nodo que almacena internamente el elemento (de tipo T), y un puntero al nodo siguiente, que podría ser NULL si el nodo es el último de la lista enlazada. */ class Nodo { public: Nodo() : _sig(NULL) {} Nodo(const T &elem) : _elem(elem), _sig(NULL) {} Nodo(const T &elem, Nodo *sig) : _elem(elem), _sig(sig) {} T _elem; Nodo *_sig; }; /** Elimina todos los nodos de la lista enlazada cuyo primer nodo se pasa como parámetro. Se admite que el nodo sea NULL (no habrá nada que liberar). */ static void libera(Nodo *prim) { while (prim != NULL) { Nodo *aux = prim; prim = prim->_sig; delete aux; } } /** Puntero al primer elemento. */ Nodo *_prim; /** Puntero al último elemento. */ Nodo *_ult; /** Número de elementos */ int _numElems; }; /** @file DCola.h Implementación del TAD doble cola, utilizando una lista doblemente enlazada con nodo fantasma o cabecera. Estructura de Datos y Algoritmos Facultad de Informática Universidad Complutense de Madrid (c) Marco Antonio Gómez Martín, 2012 */ /** Implementación del TAD Doble Cola utilizando una lista doblemente enlazada circular y con nodo fantasma. Las operaciones son: - DColaVacia: -> DCola. Generadora implementada en el constructor sin parámetros. - PonDetras: DCola, Elem -> DCola. Generadora - ponDelante: DCola, Elem -> DCola. Modificadora. - quitaPrim: DCola - -> DCola. Modificadora parcial - primero: DCola - -> Elem. Observadora parcial - quitaUlt: DCola - -> DCola. Modificadora parcial - ultimo: DCola - -> Elem. Observadora parcial - esVacia: DCola -> Bool. Observadora @author Marco Antonio Gómez Martín */ template <class T> class DCola { public: /** Constructor; operación DColaVacia. */ DCola() { _fantasma = new Nodo(); _fantasma->_sig = _fantasma; _fantasma->_ant = _fantasma; _numElems = 0; } /** Destructor; elimina la lista doblemente enlazada. */ ~DCola() { libera(); } /** Añade un elemento por la parte de atrás de la cola. Es una operación generadora. */ void ponDetras(const T &e) { insertaElem(e, _fantasma->_ant, _fantasma); _numElems++; } /** Devuelve el primer elemento de la cola; es una operación observadora parcial, pues es un error preguntar por el primer elemento de una doble cola vacía. primero(PonDetras(elem, DColaVacia)) = elem primero(PonDetras(elem, xs)) = primero(xs) si !esVacia(xs) error: primero(DColaVacia) */ const T &primero() const { if (esVacia()) throw EDColaVacia(); return _fantasma->_sig->_elem; } /** Elimina el primer elemento de la doble cola. Operación modificadora parcial, que falla si está vacía. quitaPrim(PonDetras(elem, DColaVacia)) = DColaVacia quitaPrim(PonDetras(elem, xs)) = PonDetras(elem, quitaPrim(xs)) si !esVacia(xs) error: quitaPrim(DColaVacia) */ void quitaPrim() { if (esVacia()) throw EDColaVacia(); borraElem(_fantasma->_sig); --_numElems; } /** Añade un elemento a la parte delantera de una doble cola. Operación modificadora. ponDelante(elem, DColaVacia) = ponDetras(elem, DColaVacia) ponDelante(elem, ponDetras(x, xs)) = ponDetras(x, ponDelante(elem, xs)) @param e Elemento que se añade */ void ponDelante(const T &e) { insertaElem(e, _fantasma, _fantasma->_sig); ++_numElems; } /** Devuelve el último elemento de la doble cola. Es un error preguntar por el último de una doble cola vacía. ultimo(PonDetras(x, xs)) = x error: ultimo(DColaVacia) @return Último elemento de la cola. */ const T &ultimo() const { if (esVacia()) throw EDColaVacia(); return _fantasma->_ant->_elem; } /** Elimina el último elemento de la doble cola. Es un error quitar el último de una doble cola vacía. quitaUlt(PonDetras(x, xs)) = xs error: quitaUlt(DColaVacia) */ void quitaUlt() { if (esVacia()) throw EDColaVacia(); borraElem(_fantasma->_ant); --_numElems; } /** Operación observadora para saber si una doble cola tiene o no elementos. esVacia(DColaVacia) = true esVacia(ponDetras(x, xs)) = false @return true si la doble cola no tiene elementos. */ bool esVacia() const { return _fantasma->_sig == _fantasma; /* return _numElems == 0; */ } /** Devuelve el número de elementos que hay en la doble cola. numElems(DColaVacia) = 0 numElems(PonDetras(elem, p)) = 1 + numElems(p) @return Número de elementos. */ int numElems() const { return _numElems; } // // // MÉTODOS DE "FONTANERÍA" DE C++ QUE HACEN VERSÁTIL // A LA CLASE // // /** Constructor copia */ DCola(const DCola<T> &other) : _fantasma(NULL) { copia(other); } /** Operador de asignación */ DCola<T> &operator=(const DCola<T> &other) { if (this != &other) { libera(); copia(other); } return *this; } /** Operador de comparación. */ bool operator==(const DCola<T> &rhs) const { if (_numElems != rhs._numElems) return false; Nodo *p1 = _fantasma->_sig; Nodo *p2 = rhs._fantasma->_sig; while ((p1 != _fantasma) && (p2 != rhs._fantasma)) { if (p1->_elem != p2->_elem) return false; p1 = p1->_sig; p2 = p2->_sig; } return (p1 == _fantasma) && (p2 == rhs._fantasma); } bool operator!=(const DCola<T> &rhs) const { return !(*this == rhs); } protected: void libera() { // Usamos libera(nodo), pero antes quitamos // la circularidad para evitar bucle // infinito... _fantasma->_ant->_sig = NULL; _fantasma->_ant = NULL; libera(_fantasma); _fantasma = NULL; } void copia(const DCola<T> &other) { // En vez de trabajar con punteros en la inserción, // usamos ponDetras. _fantasma = new Nodo(); _fantasma->_sig = _fantasma; _fantasma->_ant = _fantasma; _numElems = 0; Nodo *act = other._fantasma->_sig; while (act != other._fantasma) { ponDetras(act->_elem); act = act->_sig; } } private: /** Clase nodo que almacena internamente el elemento (de tipo T), y dos punteros, uno al nodo anterior y otro al nodo siguiente. Ambos punteros podrían ser NULL si el nodo es el primero y/o último de la lista enlazada. */ class Nodo { public: Nodo() : _sig(NULL) {} Nodo(const T &elem) : _elem(elem), _sig(NULL), _ant(NULL) {} Nodo(Nodo *ant, const T &elem, Nodo *sig) : _elem(elem), _sig(sig), _ant(ant) {} T _elem; Nodo *_sig; Nodo *_ant; }; /** Inserta un elemento entre el nodo1 y el nodo2. Devuelve el puntero al nodo creado. Caso general: los dos nodos existen. nodo1->_sig == nodo2 nodo2->_ant == nodo1 Casos especiales: alguno de los nodos no existe nodo1 == NULL y/o nodo2 == NULL */ static Nodo *insertaElem(const T &e, Nodo *nodo1, Nodo *nodo2) { Nodo *nuevo = new Nodo(nodo1, e, nodo2); if (nodo1 != NULL) nodo1->_sig = nuevo; if (nodo2 != NULL) nodo2->_ant = nuevo; return nuevo; } /** Elimina el nodo n. Si el nodo tiene nodos antes o después, actualiza sus punteros anterior y siguiente. Caso general: hay nodos anterior y siguiente. Casos especiales: algunos de los nodos (anterior o siguiente a n) no existen. */ static void borraElem(Nodo *n) { if (n == NULL) return; Nodo *ant = n->_ant; Nodo *sig = n->_sig; if (ant != NULL) ant->_sig = sig; if (sig != NULL) sig->_ant = ant; delete n; } /** Elimina todos los nodos de la lista enlazada cuyo primer nodo se pasa como parámetro. Se admite que el nodo sea NULL (no habrá nada que liberar). En caso de pasarse un nodo válido, su puntero al nodo anterior debe ser NULL (si no, no sería el primero de la lista!). */ static void libera(Nodo *prim) { if (prim == NULL) return; assert(!prim || !prim->_ant); while (prim != NULL) { Nodo *aux = prim; prim = prim->_sig; delete aux; } } // Puntero al nodo fantasma Nodo *_fantasma; // Número de elementos unsigned int _numElems; }; /** Implementación dinámica del TAD Arbin utilizando nodos con un puntero al hijo izquierdo y otro al hijo derecho. La implementación permite compartición de estructura, manteniendola bajo control mediante conteo de referencias. La implementación, sin embargo, es bastante artesanal, pues para no complicar el código excesivamente no se ha hecho uso de punteros inteligentes que incrementen y decrementen automáticamente esas referencias. Las operaciones son: - ArbolVacio: -> Arbin. Generadora implementada en el constructor sin parámetros. - Cons: Arbin, Elem, Arbin -> Arbin. Generadora implementada en un constructor con tres parámetros. - hijoIz, hijoDr: Arbin - -> Arbin. Observadoras que devuelven el hijo izquiero o derecho de un árbol. - esVacio: Arbin -> Bool. Observadora que devuelve si un árbol binario es vacío. @author Marco Antonio Gómez Martín */ template <class T> class Arbin { public: /** Constructor; operacion ArbolVacio */ Arbin() : _ra(NULL) { } /** Constructor; operacion Cons */ Arbin(const Arbin &iz, const T &elem, const Arbin &dr) : _ra(new Nodo(iz._ra, elem, dr._ra)) { _ra->addRef(); } /** Destructor; elimina la estructura jerárquica de nodos. */ ~Arbin() { libera(); _ra = NULL; } /** Devuelve el elemento almacenado en la raiz raiz(Cons(iz, elem, dr)) = elem error raiz(ArbolVacio) @return Elemento en la raíz. */ const T &raiz() const { if (esVacio()) throw EArbolVacio(); return _ra->_elem; } /** Devuelve un árbol copia del árbol izquierdo. Es una operación parcial (falla con el árbol vacío). hijoIz(Cons(iz, elem, dr)) = iz error hijoIz(ArbolVacio) */ Arbin hijoIz() const { if (esVacio()) throw EArbolVacio(); return Arbin(_ra->_iz); } /** Devuelve un árbol copia del árbol derecho. Es una operación parcial (falla con el árbol vacío). hijoDr(Cons(iz, elem, dr)) = dr error hijoDr(ArbolVacio) */ Arbin hijoDr() const { if (esVacio()) throw EArbolVacio(); return Arbin(_ra->_dr); } /** Operación observadora que devuelve si el árbol es vacío (no contiene elementos) o no. esVacio(ArbolVacio) = true esVacio(Cons(iz, elem, dr)) = false */ bool esVacio() const { return _ra == NULL; } // // // RECORRIDOS SOBRE EL ÁRBOL // // Lista<T> preorden() const { Lista<T> ret; preordenAcu(_ra, ret); return ret; } Lista<T> inorden() const { Lista<T> ret; inordenAcu(_ra, ret); return ret; } Lista<T> postorden() const { Lista<T> ret; postordenAcu(_ra, ret); return ret; } Lista<T> niveles() const { if (esVacio()) return Lista<T>(); Lista<T> ret; Cola<Nodo*> porProcesar; porProcesar.ponDetras(_ra); while (!porProcesar.esVacia()) { Nodo *visita = porProcesar.primero(); porProcesar.quitaPrim(); ret.ponDr(visita->_elem); if (visita->_iz) porProcesar.ponDetras(visita->_iz); if (visita->_dr) porProcesar.ponDetras(visita->_dr); } return ret; } // // // OTRAS OPERACIONES OBSERVADORAS // // /** Devuelve el número de nodos de un árbol. */ unsigned int numNodos() const { return numNodosAux(_ra); } /** Devuelve la talla del árbol. */ unsigned int talla() const { return tallaAux(_ra); } /** Devuelve el número de hojas de un árbol. */ unsigned int numHojas() const { return numHojasAux(_ra); } // // // MÉTODOS DE "FONTANERÍA" DE C++ QUE HACEN VERSÁTIL // A LA CLASE // // /** Constructor copia */ Arbin(const Arbin<T> &other) : _ra(NULL) { copia(other); } /** Operador de asignación */ Arbin<T> &operator=(const Arbin<T> &other) { if (this != &other) { libera(); copia(other); } return *this; } /** Operador de comparación. */ bool operator==(const Arbin<T> &rhs) const { return comparaAux(_ra, rhs._ra); } bool operator!=(const Arbin<T> &rhs) const { return !(*this == rhs); } protected: /** Clase nodo que almacena internamente el elemento (de tipo T), y los punteros al hijo izquierdo y al hijo derecho, así como el número de referencias que hay. */ class Nodo { public: Nodo() : _iz(NULL), _dr(NULL), _numRefs(0) {} Nodo(Nodo *iz, const T &elem, Nodo *dr) : _elem(elem), _iz(iz), _dr(dr), _numRefs(0) { if (_iz != NULL) _iz->addRef(); if (_dr != NULL) _dr->addRef(); } void addRef() { assert(_numRefs >= 0); _numRefs++; } void remRef() { assert(_numRefs > 0); _numRefs--; } T _elem; Nodo *_iz; Nodo *_dr; int _numRefs; }; /** Constructor protegido que crea un árbol a partir de una estructura jerárquica existente. Esa estructura jerárquica SE COMPARTE, por lo que se añade la referencia. Se utiliza en hijoIz e hijoDr. */ Arbin(Nodo *raiz) : _ra(raiz) { if (_ra != NULL) _ra->addRef(); } void libera() { libera(_ra); } void copia(const Arbin &other) { assert(this != &other); _ra = other._ra; if (_ra != NULL) _ra->addRef(); } // // // MÉTODOS AUXILIARES PARA LOS RECORRIDOS // // static void preordenAcu(Nodo *ra, Lista<T> &acu) { if (ra == NULL) return; acu.ponDr(ra->_elem); preordenAcu(ra->_iz, acu); preordenAcu(ra->_dr, acu); } static void inordenAcu(Nodo *ra, Lista<T> &acu) { if (ra == NULL) return; inordenAcu(ra->_iz, acu); acu.ponDr(ra->_elem); inordenAcu(ra->_dr, acu); } static void postordenAcu(Nodo *ra, Lista<T> &acu) { if (ra == NULL) return; postordenAcu(ra->_iz, acu); postordenAcu(ra->_dr, acu); acu.ponDr(ra->_elem); } // // // MÉTODOS AUXILIARES (RECURSIVOS) DE OTRAS OPERACIONES // OBSERVADORAS // // static unsigned int numNodosAux(Nodo *ra) { if (ra == NULL) return 0; return 1 + numNodosAux(ra->_iz) + numNodosAux(ra->_dr); } static unsigned int tallaAux(Nodo *ra) { if (ra == NULL) return 0; int tallaiz = tallaAux(ra->_iz); int talladr = tallaAux(ra->_dr); if (tallaiz > talladr) return 1 + tallaiz; else return 1 + talladr; } static unsigned int numHojasAux(Nodo *ra) { if (ra == NULL) return 0; if ((ra->_iz == NULL) && (ra->_dr == NULL)) return 1; return numHojasAux(ra->_iz) + numHojasAux(ra->_dr); } private: /** Elimina todos los nodos de una estructura arbórea que comienza con el puntero ra. Se admite que el nodo sea NULL (no habrá nada que liberar). */ static void libera(Nodo *ra) { if (ra != NULL) { ra->remRef(); if (ra->_numRefs == 0) { libera(ra->_iz); libera(ra->_dr); delete ra; } } } /** Compara dos estructuras jerárquicas de nodos, dadas sus raices (que pueden ser NULL). */ static bool comparaAux(Nodo *r1, Nodo *r2) { if (r1 == r2) return true; else if ((r1 == NULL) || (r2 == NULL)) // En el if anterior nos aseguramos de // que r1 != r2. Si uno es NULL, el // otro entonces no lo será, luego // son distintos. return false; else { return (r1->_elem == r2->_elem) && comparaAux(r1->_iz, r2->_iz) && comparaAux(r1->_dr, r2->_dr); } } protected: /** Puntero a la raíz de la estructura jerárquica de nodos. */ Nodo *_ra; }; /** @file Arbus.h Implementación dinámica del TAD Arbol de Búsqueda. Estructura de Datos y Algoritmos Facultad de Informática Universidad Complutense de Madrid (c) Marco Antonio Gómez Martín, 2012 */ /** Implementación dinámica del TAD Arbus utilizando nodos con un puntero al hijo izquierdo y otro al hijo derecho. Las operaciones son: - ArbusVacio: operación generadora que construye un árbol de búsqueda vacío. - Inserta(clave, valor): generadora que añade una nueva pareja (clave, valor) al árbol. Si la clave ya estaba se sustituye el valor. - borra(clave): operación modificadora. Elimina la clave del árbol de búsqueda. Si la clave no está, la operación no tiene efecto. - consulta(clave): operación observadora que devuelve el valor asociado a una clave. Es un error preguntar por una clave que no existe. - esta(clave): operación observadora. Sirve para averiguar si se ha introducido una clave en el árbol. - esVacio(): operacion observadora que indica si el árbol de búsqueda tiene alguna clave introducida. @author Marco Antonio Gómez Martín */ template <class Clave, class Valor> class Arbus { private: /** Clase nodo que almacena internamente la pareja (clave, valor) y los punteros al hijo izquierdo y al hijo derecho. */ class Nodo { public: Nodo() : _iz(NULL), _dr(NULL) {} Nodo(const Clave &clave, const Valor &valor) : _clave(clave), _valor(valor), _iz(NULL), _dr(NULL) {} Nodo(Nodo *iz, const Clave &clave, const Valor &valor, Nodo *dr) : _clave(clave), _valor(valor), _iz(iz), _dr(dr) {} Clave _clave; Valor _valor; Nodo *_iz; Nodo *_dr; }; public: /** Constructor; operacion ArbolVacio */ Arbus() : _ra(NULL) { } /** Destructor; elimina la estructura jerárquica de nodos. */ ~Arbus() { libera(); _ra = NULL; } /** Operación generadora que añade una nueva clave/valor a un árbol de búsqueda. @param clave Clave nueva. @param valor Valor asociado a esa clave. Si la clave ya se había insertado previamente, sustituimos el valor viejo por el nuevo. */ void inserta(const Clave &clave, const Valor &valor) { _ra = insertaAux(clave, valor, _ra); } /** Operación modificadora que elimina una clave del árbol. Si la clave no existía la operación no tiene efecto. borra(elem, ArbusVacio) = ArbusVacio borra(e, inserta(c, v, arbol)) = inserta(c, v, borra(e, arbol)) si c != e borra(e, inserta(c, v, arbol)) = borra(e, arbol) si c == e @param clave Clave a eliminar. */ void borra(const Clave &clave) { _ra = borraAux(_ra, clave); } /** Operación observadora que devuelve el valor asociado a una clave dada. consulta(e, inserta(c, v, arbol)) = v si e == c consulta(e, inserta(c, v, arbol)) = consulta(e, arbol) si e != c error consulta(ArbusVacio) @param clave Clave por la que se pregunta. */ const Valor &consulta(const Clave &clave) { Nodo *p = buscaAux(_ra, clave); if (p == NULL) throw EClaveErronea(); return p->_valor; } /** Operación observadora que permite averiguar si una clave determinada está o no en el árbol de búsqueda. esta(e, ArbusVacio) = false esta(e, inserta(c, v, arbol)) = true si e == c esta(e, inserta(c, v, arbol)) = esta(e, arbol) si e != c @param clave Clave por la que se pregunta. */ bool esta(const Clave &clave) { return buscaAux(_ra, clave) != NULL; } /** Operación observadora que devuelve si el árbol es vacío (no contiene elementos) o no. esVacio(ArbusVacio) = true esVacio(inserta(c, v, arbol)) = false */ bool esVacio() const { return _ra == NULL; } // // // OPERACIONES RELACIONADAS CON LOS ITERADORES // // /** Clase interna que implementa un iterador sobre la lista que permite recorrer la lista e incluso alterar el valor de sus elementos. */ class Iterador { public: void avanza() { if (_act == NULL) throw EAccesoInvalido(); // Si hay hijo derecho, saltamos al primero // en inorden del hijo derecho if (_act->_dr) _act = primeroInOrden(_act->_dr); else { // Si no, vamos al primer ascendiente // no visitado. Para eso consultamos // la pila; si ya está vacía, no quedan // ascendientes por visitar if (_ascendientes.esVacia()) _act = NULL; else { _act = _ascendientes.cima(); _ascendientes.desapila(); } } } const Clave &clave() const { if (_act == NULL) throw EAccesoInvalido(); return _act->_clave; } const Valor &valor() const { if (_act == NULL) throw EAccesoInvalido(); return _act->_valor; } bool operator==(const Iterador &other) const { return _act == other._act; } bool operator!=(const Iterador &other) const { return !(this->operator==(other)); } protected: // Para que pueda construir objetos del // tipo iterador friend class Arbus; Iterador() : _act(NULL) {} Iterador(Nodo *act) { _act = primeroInOrden(act); } /** Busca el primer elemento en inorden de la estructura jerárquica de nodos pasada como parámetro; va apilando sus ascendientes para poder "ir hacia atrás" cuando sea necesario. @param p Puntero a la raíz de la subestructura. */ Nodo *primeroInOrden(Nodo *p) { if (p == NULL) return NULL; while (p->_iz != NULL) { _ascendientes.apila(p); p = p->_iz; } return p; } // Puntero al nodo actual del recorrido // NULL si hemos llegado al final. Nodo *_act; // Ascendientes del nodo actual // aún por visitar Pila<Nodo*> _ascendientes; }; /** Devuelve el iterador al principio de la lista. @return iterador al principio de la lista; coincidirá con final() si la lista está vacía. */ Iterador principio() { return Iterador(_ra); } /** @return Devuelve un iterador al final del recorrido (fuera de éste). */ Iterador final() const { return Iterador(NULL); } // // // MÉTODOS DE "FONTANERÍA" DE C++ QUE HACEN VERSÁTIL // A LA CLASE // // /** Constructor copia */ Arbus(const Arbus<Clave, Valor> &other) : _ra(NULL) { copia(other); } /** Operador de asignación */ Arbus<Clave, Valor> &operator=(const Arbus<Clave, Valor> &other) { if (this != &other) { libera(); copia(other); } return *this; } protected: /** Constructor protegido que crea un árbol a partir de una estructura jerárquica de nodos previamente creada. Se utiliza en hijoIz e hijoDr. */ Arbus(Nodo *raiz) : _ra(raiz) { } void libera() { libera(_ra); } void copia(const Arbus &other) { _ra = copiaAux(other._ra); } private: /** Elimina todos los nodos de una estructura arbórea que comienza con el puntero ra. Se admite que el nodo sea NULL (no habrá nada que liberar). */ static void libera(Nodo *ra) { if (ra != NULL) { libera(ra->_iz); libera(ra->_dr); delete ra; } } /** Copia la estructura jerárquica de nodos pasada como parámetro (puntero a su raiz) y devuelve un puntero a una nueva estructura jerárquica, copia de anterior (y que, por tanto, habrá que liberar). */ static Nodo *copiaAux(Nodo *ra) { if (ra == NULL) return NULL; return new Nodo(copiaAux(ra->_iz), ra->_clave, ra->_valor, copiaAux(ra->_dr)); } /** Inserta una pareja (clave, valor) en la estructura jerárquica que comienza en el puntero pasado como parámetro. Ese puntero se admite que sea NULL, por lo que se creará un nuevo nodo que pasará a ser la nueva raíz de esa estructura jerárquica. El método devuelve un puntero a la raíz de la estructura modificada. En condiciones normales coincidirá con el parámetro recibido; sólo cambiará si la estructura era vacía. @param clave Clave a insertar. Si ya aparecía en la estructura de nodos, se sobreescribe el valor. @param valor Valor a insertar. @param p Puntero al nodo raíz donde insertar la pareja. @return Nueva raíz (o p si no cambia). */ static Nodo *insertaAux(const Clave &clave, const Valor &valor, Nodo *p) { if (p == NULL) { return new Nodo(clave, valor); } else if (p->_clave == clave) { p->_valor = valor; return p; } else if (clave < p->_clave) { p->_iz = insertaAux(clave, valor, p->_iz); return p; } else { // (clave > p->_clave) p->_dr = insertaAux(clave, valor, p->_dr); return p; } } /** Busca una clave en la estructura jerárquica de nodos cuya raíz se pasa como parámetro, y devuelve el nodo en la que se encuentra (o NULL si no está). @param p Puntero a la raíz de la estructura de nodos @param clave Clave a buscar */ static Nodo *buscaAux(Nodo *p, const Clave &clave) { if (p == NULL) return NULL; if (p->_clave == clave) return p; if (clave < p->_clave) return buscaAux(p->_iz, clave); else return buscaAux(p->_dr, clave); } /** Elimina (si existe) la clave/valor de la estructura jerárquica de nodos apuntada por p. Si la clave aparecía en la propia raíz, ésta cambiará, por lo que se devuelve la nueva raíz. Si no cambia se devuelve p. @param p Raíz de la estructura jerárquica donde borrar la clave. @param clave Clave a borrar. @return Nueva raíz de la estructura, tras el borrado. Si la raíz no cambia, se devuelve el propio p. */ static Nodo *borraAux(Nodo *p, const Clave &clave) { if (p == NULL) return NULL; if (clave == p->_clave) { return borraRaiz(p); } else if (clave < p->_clave) { p->_iz = borraAux(p->_iz, clave); return p; } else { // clave > p->_clave p->_dr = borraAux(p->_dr, clave); return p; } } /** Borra la raíz de la estructura jerárquica de nodos y devuelve el puntero a la nueva raíz que garantiza que la estructura sigue siendo válida para un árbol de búsqueda (claves ordenadas). */ static Nodo *borraRaiz(Nodo *p) { Nodo *aux; // Si no hay hijo izquierdo, la raíz pasa a ser // el hijo derecho if (p->_iz == NULL) { aux = p->_dr; delete p; return aux; } else // Si no hay hijo derecho, la raíz pasa a ser // el hijo izquierdo if (p->_dr == NULL) { aux = p->_iz; delete p; return aux; } else { // Convertimos el elemento más pequeño del hijo derecho // en la raíz. return mueveMinYBorra(p); } } /** Método auxiliar para el borrado; recibe un puntero a la raíz a borrar. Busca el elemento más pequeño del hijo derecho que se convertirá en la raíz (que devolverá), borra la antigua raíz (p) y "cose" todos los punteros, de forma que ahora: - El mínimo pasa a ser la raíz, cuyo hijo izquierdo y derecho eran los hijos izquierdo y derecho de la raíz antigua. - El hijo izquierdo del padre del elemento más pequeño pasa a ser el antiguo hijo derecho de ese mínimo. */ static Nodo *mueveMinYBorra(Nodo *p) { // Vamos bajando hasta que encontramos el elemento // más pequeño (aquel que no tiene hijo izquierdo). // Vamos guardando también el padre (que será null // si el hijo derecho es directamente el elemento // más pequeño). Nodo *padre = NULL; Nodo *aux = p->_dr; while (aux->_iz != NULL) { padre = aux; aux = aux->_iz; } // aux apunta al elemento más pequeño. // padre apunta a su padre (si el nodo es hijo izquierdo) // Dos casos dependiendo de si el padre del nodo con // el mínimo es o no la raíz a eliminar // (=> padre != NULL) if (padre != NULL) { padre->_iz = aux->_dr; aux->_iz = p->_iz; aux->_dr = p->_dr; } else { aux->_iz = p->_iz; } delete p; return aux; } /** Puntero a la raíz de la estructura jerárquica de nodos. */ Nodo *_ra; }; #endif // __ARBOLES_H #include <iostream> using namespace std; struct Par{ int valor; bool visitado; }; //Creo un arbol completo con pares valor-bool con la profundidad que me den, hasta un determinado valor Arbin<Par> creaArbol(int profundidad, int valor) { int elevado = 1, cont = 0; while(cont!=profundidad){ elevado=elevado*2; cont++; } if (valor >= elevado) { return Arbin<Par>(); } else { Par par; par.valor = valor; par.visitado = false; Arbin<Par> iz = creaArbol(profundidad, valor+valor); Arbin<Par> dr = creaArbol(profundidad, valor+valor+1); return Arbin<Par>(iz, par, dr); } } /*Tira una bola por el árbol, devuelve el arbol con los bool de los nodos por los que pasa cambiados, y devuelve por referencia el valor de la hoja a la que cae*/ Arbin<Par> tiraBola(Arbin<Par> a, int &num){ if(a.hijoIz().esVacio() && a.hijoDr().esVacio()){ //Si sus hijos son vacios devuelvo su raiz por referencia y el arbol resultante Par p; num = a.raiz().valor; p.valor = num; p.visitado = false; return Arbin<Par>(Arbin<Par>(), p , Arbin<Par>()); }else{ if(a.raiz().visitado){ //Caigo por el hijo derecho Par pvis; pvis = a.raiz(); pvis.visitado =false; return Arbin<Par>(a.hijoIz(), pvis, tiraBola(a.hijoDr(), num)); }else{ //Caigo por el hijo izquierdo Par pnvis; pnvis = a.raiz(); pnvis.visitado =true; return Arbin<Par>(tiraBola(a.hijoIz(), num), pnvis, a.hijoDr()); } } } int main(){ int numCasos=0, profundidad=0, bolasLanzadas=0; cin >> numCasos; //Leo numero de casos while(numCasos!=0){ cin >> profundidad; // Leo profundidad cin >> bolasLanzadas; // Leo numero de bolas lanzadas Arbin<Par> arbol; int solucion = 0; //Creo el arbol de pares int-bool arbol = creaArbol(profundidad, 1); //Lanzo tantas bolas como indique el usuario while(bolasLanzadas!=0){ arbol = tiraBola(arbol, solucion); bolasLanzadas--; } cout << solucion << endl; numCasos--; } cin >> numCasos; //Leo -1 return 0; }
[ "jaimedel@ucm.es" ]
jaimedel@ucm.es
9ab01c959f70d1ac40c649afb8aeeb4f2b8259c7
e2ad74f7396a095244676ba5d881574080047862
/JuceLibraryCode/modules/juce_audio_formats/codecs/juce_WavAudioFormat.cpp
58c3d98ae8069a9eac357046a047b285e5a6192f
[]
no_license
kasbah/juci
fd4fae5b45c8a7f97f5143fc4aaf8d341d535d32
5bdc96dfa72b14290e067cb6f2578a57e060a37d
refs/heads/master
2016-09-05T22:48:35.775128
2013-11-08T02:34:23
2013-11-08T02:34:23
null
0
0
null
null
null
null
UTF-8
C++
false
false
58,185
cpp
/* ============================================================================== This file is part of the JUCE library. Copyright (c) 2013 - Raw Material Software Ltd. Permission is granted to use this software under the terms of either: a) the GPL v2 (or any later version) b) the Affero GPL v3 Details of these licenses can be found at: www.gnu.org/licenses JUCE is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. ------------------------------------------------------------------------------ To release a closed-source product which uses JUCE, commercial licenses are available: visit www.juce.com for more information. ============================================================================== */ static const char* const wavFormatName = "WAV file"; static const char* const wavExtensions[] = { ".wav", ".bwf", 0 }; //============================================================================== const char* const WavAudioFormat::bwavDescription = "bwav description"; const char* const WavAudioFormat::bwavOriginator = "bwav originator"; const char* const WavAudioFormat::bwavOriginatorRef = "bwav originator ref"; const char* const WavAudioFormat::bwavOriginationDate = "bwav origination date"; const char* const WavAudioFormat::bwavOriginationTime = "bwav origination time"; const char* const WavAudioFormat::bwavTimeReference = "bwav time reference"; const char* const WavAudioFormat::bwavCodingHistory = "bwav coding history"; StringPairArray WavAudioFormat::createBWAVMetadata (const String& description, const String& originator, const String& originatorRef, const Time date, const int64 timeReferenceSamples, const String& codingHistory) { StringPairArray m; m.set (bwavDescription, description); m.set (bwavOriginator, originator); m.set (bwavOriginatorRef, originatorRef); m.set (bwavOriginationDate, date.formatted ("%Y-%m-%d")); m.set (bwavOriginationTime, date.formatted ("%H:%M:%S")); m.set (bwavTimeReference, String (timeReferenceSamples)); m.set (bwavCodingHistory, codingHistory); return m; } const char* const WavAudioFormat::acidOneShot = "acid one shot"; const char* const WavAudioFormat::acidRootSet = "acid root set"; const char* const WavAudioFormat::acidStretch = "acid stretch"; const char* const WavAudioFormat::acidDiskBased = "acid disk based"; const char* const WavAudioFormat::acidizerFlag = "acidizer flag"; const char* const WavAudioFormat::acidRootNote = "acid root note"; const char* const WavAudioFormat::acidBeats = "acid beats"; const char* const WavAudioFormat::acidDenominator = "acid denominator"; const char* const WavAudioFormat::acidNumerator = "acid numerator"; const char* const WavAudioFormat::acidTempo = "acid tempo"; const char* const WavAudioFormat::ISRC = "ISRC"; //============================================================================== namespace WavFileHelpers { inline int chunkName (const char* const name) noexcept { return (int) ByteOrder::littleEndianInt (name); } inline size_t roundUpSize (size_t sz) noexcept { return (sz + 3) & ~3u; } #if JUCE_MSVC #pragma pack (push, 1) #endif struct BWAVChunk { char description [256]; char originator [32]; char originatorRef [32]; char originationDate [10]; char originationTime [8]; uint32 timeRefLow; uint32 timeRefHigh; uint16 version; uint8 umid[64]; uint8 reserved[190]; char codingHistory[1]; void copyTo (StringPairArray& values, const int totalSize) const { values.set (WavAudioFormat::bwavDescription, String::fromUTF8 (description, sizeof (description))); values.set (WavAudioFormat::bwavOriginator, String::fromUTF8 (originator, sizeof (originator))); values.set (WavAudioFormat::bwavOriginatorRef, String::fromUTF8 (originatorRef, sizeof (originatorRef))); values.set (WavAudioFormat::bwavOriginationDate, String::fromUTF8 (originationDate, sizeof (originationDate))); values.set (WavAudioFormat::bwavOriginationTime, String::fromUTF8 (originationTime, sizeof (originationTime))); const uint32 timeLow = ByteOrder::swapIfBigEndian (timeRefLow); const uint32 timeHigh = ByteOrder::swapIfBigEndian (timeRefHigh); const int64 time = (((int64)timeHigh) << 32) + timeLow; values.set (WavAudioFormat::bwavTimeReference, String (time)); values.set (WavAudioFormat::bwavCodingHistory, String::fromUTF8 (codingHistory, totalSize - (int) offsetof (BWAVChunk, codingHistory))); } static MemoryBlock createFrom (const StringPairArray& values) { MemoryBlock data (roundUpSize (sizeof (BWAVChunk) + values [WavAudioFormat::bwavCodingHistory].getNumBytesAsUTF8())); data.fillWith (0); BWAVChunk* b = (BWAVChunk*) data.getData(); // Allow these calls to overwrite an extra byte at the end, which is fine as long // as they get called in the right order.. values [WavAudioFormat::bwavDescription] .copyToUTF8 (b->description, 257); values [WavAudioFormat::bwavOriginator] .copyToUTF8 (b->originator, 33); values [WavAudioFormat::bwavOriginatorRef] .copyToUTF8 (b->originatorRef, 33); values [WavAudioFormat::bwavOriginationDate].copyToUTF8 (b->originationDate, 11); values [WavAudioFormat::bwavOriginationTime].copyToUTF8 (b->originationTime, 9); const int64 time = values [WavAudioFormat::bwavTimeReference].getLargeIntValue(); b->timeRefLow = ByteOrder::swapIfBigEndian ((uint32) (time & 0xffffffff)); b->timeRefHigh = ByteOrder::swapIfBigEndian ((uint32) (time >> 32)); values [WavAudioFormat::bwavCodingHistory].copyToUTF8 (b->codingHistory, 0x7fffffff); if (b->description[0] != 0 || b->originator[0] != 0 || b->originationDate[0] != 0 || b->originationTime[0] != 0 || b->codingHistory[0] != 0 || time != 0) { return data; } return MemoryBlock(); } } JUCE_PACKED; //============================================================================== struct SMPLChunk { struct SampleLoop { uint32 identifier; uint32 type; // these are different in AIFF and WAV uint32 start; uint32 end; uint32 fraction; uint32 playCount; } JUCE_PACKED; uint32 manufacturer; uint32 product; uint32 samplePeriod; uint32 midiUnityNote; uint32 midiPitchFraction; uint32 smpteFormat; uint32 smpteOffset; uint32 numSampleLoops; uint32 samplerData; SampleLoop loops[1]; template <typename NameType> static void setValue (StringPairArray& values, NameType name, uint32 val) { values.set (name, String (ByteOrder::swapIfBigEndian (val))); } static void setValue (StringPairArray& values, int prefix, const char* name, uint32 val) { setValue (values, "Loop" + String (prefix) + name, val); } void copyTo (StringPairArray& values, const int totalSize) const { setValue (values, "Manufacturer", manufacturer); setValue (values, "Product", product); setValue (values, "SamplePeriod", samplePeriod); setValue (values, "MidiUnityNote", midiUnityNote); setValue (values, "MidiPitchFraction", midiPitchFraction); setValue (values, "SmpteFormat", smpteFormat); setValue (values, "SmpteOffset", smpteOffset); setValue (values, "NumSampleLoops", numSampleLoops); setValue (values, "SamplerData", samplerData); for (int i = 0; i < (int) numSampleLoops; ++i) { if ((uint8*) (loops + (i + 1)) > ((uint8*) this) + totalSize) break; setValue (values, i, "Identifier", loops[i].identifier); setValue (values, i, "Type", loops[i].type); setValue (values, i, "Start", loops[i].start); setValue (values, i, "End", loops[i].end); setValue (values, i, "Fraction", loops[i].fraction); setValue (values, i, "PlayCount", loops[i].playCount); } } template <typename NameType> static uint32 getValue (const StringPairArray& values, NameType name, const char* def) { return ByteOrder::swapIfBigEndian ((uint32) values.getValue (name, def).getIntValue()); } static uint32 getValue (const StringPairArray& values, int prefix, const char* name, const char* def) { return getValue (values, "Loop" + String (prefix) + name, def); } static MemoryBlock createFrom (const StringPairArray& values) { MemoryBlock data; const int numLoops = jmin (64, values.getValue ("NumSampleLoops", "0").getIntValue()); if (numLoops > 0) { data.setSize (roundUpSize (sizeof (SMPLChunk) + (size_t) (numLoops - 1) * sizeof (SampleLoop)), true); SMPLChunk* const s = static_cast <SMPLChunk*> (data.getData()); s->manufacturer = getValue (values, "Manufacturer", "0"); s->product = getValue (values, "Product", "0"); s->samplePeriod = getValue (values, "SamplePeriod", "0"); s->midiUnityNote = getValue (values, "MidiUnityNote", "60"); s->midiPitchFraction = getValue (values, "MidiPitchFraction", "0"); s->smpteFormat = getValue (values, "SmpteFormat", "0"); s->smpteOffset = getValue (values, "SmpteOffset", "0"); s->numSampleLoops = ByteOrder::swapIfBigEndian ((uint32) numLoops); s->samplerData = getValue (values, "SamplerData", "0"); for (int i = 0; i < numLoops; ++i) { SampleLoop& loop = s->loops[i]; loop.identifier = getValue (values, i, "Identifier", "0"); loop.type = getValue (values, i, "Type", "0"); loop.start = getValue (values, i, "Start", "0"); loop.end = getValue (values, i, "End", "0"); loop.fraction = getValue (values, i, "Fraction", "0"); loop.playCount = getValue (values, i, "PlayCount", "0"); } } return data; } } JUCE_PACKED; //============================================================================== struct InstChunk { int8 baseNote; int8 detune; int8 gain; int8 lowNote; int8 highNote; int8 lowVelocity; int8 highVelocity; static void setValue (StringPairArray& values, const char* name, int val) { values.set (name, String (val)); } void copyTo (StringPairArray& values) const { setValue (values, "MidiUnityNote", baseNote); setValue (values, "Detune", detune); setValue (values, "Gain", gain); setValue (values, "LowNote", lowNote); setValue (values, "HighNote", highNote); setValue (values, "LowVelocity", lowVelocity); setValue (values, "HighVelocity", highVelocity); } static int8 getValue (const StringPairArray& values, const char* name, const char* def) { return (int8) values.getValue (name, def).getIntValue(); } static MemoryBlock createFrom (const StringPairArray& values) { MemoryBlock data; const StringArray& keys = values.getAllKeys(); if (keys.contains ("LowNote", true) && keys.contains ("HighNote", true)) { data.setSize (8, true); InstChunk* const inst = static_cast <InstChunk*> (data.getData()); inst->baseNote = getValue (values, "MidiUnityNote", "60"); inst->detune = getValue (values, "Detune", "0"); inst->gain = getValue (values, "Gain", "0"); inst->lowNote = getValue (values, "LowNote", "0"); inst->highNote = getValue (values, "HighNote", "127"); inst->lowVelocity = getValue (values, "LowVelocity", "1"); inst->highVelocity = getValue (values, "HighVelocity", "127"); } return data; } } JUCE_PACKED; //============================================================================== struct CueChunk { struct Cue { uint32 identifier; uint32 order; uint32 chunkID; uint32 chunkStart; uint32 blockStart; uint32 offset; } JUCE_PACKED; uint32 numCues; Cue cues[1]; static void setValue (StringPairArray& values, int prefix, const char* name, uint32 val) { values.set ("Cue" + String (prefix) + name, String (ByteOrder::swapIfBigEndian (val))); } void copyTo (StringPairArray& values, const int totalSize) const { values.set ("NumCuePoints", String (ByteOrder::swapIfBigEndian (numCues))); for (int i = 0; i < (int) numCues; ++i) { if ((uint8*) (cues + (i + 1)) > ((uint8*) this) + totalSize) break; setValue (values, i, "Identifier", cues[i].identifier); setValue (values, i, "Order", cues[i].order); setValue (values, i, "ChunkID", cues[i].chunkID); setValue (values, i, "ChunkStart", cues[i].chunkStart); setValue (values, i, "BlockStart", cues[i].blockStart); setValue (values, i, "Offset", cues[i].offset); } } static MemoryBlock createFrom (const StringPairArray& values) { MemoryBlock data; const int numCues = values.getValue ("NumCuePoints", "0").getIntValue(); if (numCues > 0) { data.setSize (roundUpSize (sizeof (CueChunk) + (size_t) (numCues - 1) * sizeof (Cue)), true); CueChunk* const c = static_cast <CueChunk*> (data.getData()); c->numCues = ByteOrder::swapIfBigEndian ((uint32) numCues); const String dataChunkID (chunkName ("data")); int nextOrder = 0; #if JUCE_DEBUG Array<uint32> identifiers; #endif for (int i = 0; i < numCues; ++i) { const String prefix ("Cue" + String (i)); const uint32 identifier = (uint32) values.getValue (prefix + "Identifier", "0").getIntValue(); #if JUCE_DEBUG jassert (! identifiers.contains (identifier)); identifiers.add (identifier); #endif const int order = values.getValue (prefix + "Order", String (nextOrder)).getIntValue(); nextOrder = jmax (nextOrder, order) + 1; Cue& cue = c->cues[i]; cue.identifier = ByteOrder::swapIfBigEndian ((uint32) identifier); cue.order = ByteOrder::swapIfBigEndian ((uint32) order); cue.chunkID = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "ChunkID", dataChunkID).getIntValue()); cue.chunkStart = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "ChunkStart", "0").getIntValue()); cue.blockStart = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "BlockStart", "0").getIntValue()); cue.offset = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "Offset", "0").getIntValue()); } } return data; } } JUCE_PACKED; //============================================================================== namespace ListChunk { static int getValue (const StringPairArray& values, const String& name) { return values.getValue (name, "0").getIntValue(); } static int getValue (const StringPairArray& values, const String& prefix, const char* name) { return getValue (values, prefix + name); } static void appendLabelOrNoteChunk (const StringPairArray& values, const String& prefix, const int chunkType, MemoryOutputStream& out) { const String label (values.getValue (prefix + "Text", prefix)); const int labelLength = (int) label.getNumBytesAsUTF8() + 1; const int chunkLength = 4 + labelLength + (labelLength & 1); out.writeInt (chunkType); out.writeInt (chunkLength); out.writeInt (getValue (values, prefix, "Identifier")); out.write (label.toUTF8(), (size_t) labelLength); if ((out.getDataSize() & 1) != 0) out.writeByte (0); } static void appendExtraChunk (const StringPairArray& values, const String& prefix, MemoryOutputStream& out) { const String text (values.getValue (prefix + "Text", prefix)); const int textLength = (int) text.getNumBytesAsUTF8() + 1; // include null terminator int chunkLength = textLength + 20 + (textLength & 1); out.writeInt (chunkName ("ltxt")); out.writeInt (chunkLength); out.writeInt (getValue (values, prefix, "Identifier")); out.writeInt (getValue (values, prefix, "SampleLength")); out.writeInt (getValue (values, prefix, "Purpose")); out.writeShort ((short) getValue (values, prefix, "Country")); out.writeShort ((short) getValue (values, prefix, "Language")); out.writeShort ((short) getValue (values, prefix, "Dialect")); out.writeShort ((short) getValue (values, prefix, "CodePage")); out.write (text.toUTF8(), (size_t) textLength); if ((out.getDataSize() & 1) != 0) out.writeByte (0); } static MemoryBlock createFrom (const StringPairArray& values) { const int numCueLabels = getValue (values, "NumCueLabels"); const int numCueNotes = getValue (values, "NumCueNotes"); const int numCueRegions = getValue (values, "NumCueRegions"); MemoryOutputStream out; if (numCueLabels + numCueNotes + numCueRegions > 0) { out.writeInt (chunkName ("adtl")); for (int i = 0; i < numCueLabels; ++i) appendLabelOrNoteChunk (values, "CueLabel" + String (i), chunkName ("labl"), out); for (int i = 0; i < numCueNotes; ++i) appendLabelOrNoteChunk (values, "CueNote" + String (i), chunkName ("note"), out); for (int i = 0; i < numCueRegions; ++i) appendExtraChunk (values, "CueRegion" + String (i), out); } return out.getMemoryBlock(); } } //============================================================================== struct AcidChunk { /** Reads an acid RIFF chunk from a stream positioned just after the size byte. */ AcidChunk (InputStream& input, size_t length) { zerostruct (*this); input.read (this, (int) jmin (sizeof (*this), length)); } void addToMetadata (StringPairArray& values) const { setBoolFlag (values, WavAudioFormat::acidOneShot, 0x01); setBoolFlag (values, WavAudioFormat::acidRootSet, 0x02); setBoolFlag (values, WavAudioFormat::acidStretch, 0x04); setBoolFlag (values, WavAudioFormat::acidDiskBased, 0x08); setBoolFlag (values, WavAudioFormat::acidizerFlag, 0x10); if (flags & 0x02) // root note set values.set (WavAudioFormat::acidRootNote, String (rootNote)); values.set (WavAudioFormat::acidBeats, String (numBeats)); values.set (WavAudioFormat::acidDenominator, String (meterDenominator)); values.set (WavAudioFormat::acidNumerator, String (meterNumerator)); values.set (WavAudioFormat::acidTempo, String (tempo)); } void setBoolFlag (StringPairArray& values, const char* name, int32 mask) const { values.set (name, (flags & mask) ? "1" : "0"); } int32 flags; int16 rootNote; int16 reserved1; float reserved2; int32 numBeats; int16 meterDenominator; int16 meterNumerator; float tempo; } JUCE_PACKED; //============================================================================== namespace AXMLChunk { static void addToMetadata (StringPairArray& destValues, const String& source) { ScopedPointer<XmlElement> xml (XmlDocument::parse (source)); if (xml != nullptr && xml->hasTagName ("ebucore:ebuCoreMain")) { if (XmlElement* xml2 = xml->getChildByName ("ebucore:coreMetadata")) { if (XmlElement* xml3 = xml2->getChildByName ("ebucore:identifier")) { if (XmlElement* xml4 = xml3->getChildByName ("dc:identifier")) { const String ISRCCode (xml4->getAllSubText().fromFirstOccurrenceOf ("ISRC:", false, true)); if (ISRCCode.isNotEmpty()) destValues.set (WavAudioFormat::ISRC, ISRCCode); } } } } } static MemoryBlock createFrom (const StringPairArray& values) { const String ISRC (values.getValue (WavAudioFormat::ISRC, String::empty)); MemoryOutputStream xml; if (ISRC.isNotEmpty()) { xml << "<ebucore:ebuCoreMain xmlns:dc=\" http://purl.org/dc/elements/1.1/\" " "xmlns:ebucore=\"urn:ebu:metadata-schema:ebuCore_2012\">" "<ebucore:coreMetadata>" "<ebucore:identifier typeLabel=\"GUID\" " "typeDefinition=\"Globally Unique Identifier\" " "formatLabel=\"ISRC\" " "formatDefinition=\"International Standard Recording Code\" " "formatLink=\"http://www.ebu.ch/metadata/cs/ebu_IdentifierTypeCodeCS.xml#3.7\">" "<dc:identifier>ISRC:" << ISRC << "</dc:identifier>" "</ebucore:identifier>" "</ebucore:coreMetadata>" "</ebucore:ebuCoreMain>"; xml.writeRepeatedByte (0, xml.getDataSize()); // ensures even size, null termination and room for future growing } return xml.getMemoryBlock(); } }; //============================================================================== struct ExtensibleWavSubFormat { uint32 data1; uint16 data2; uint16 data3; uint8 data4[8]; bool operator== (const ExtensibleWavSubFormat& other) const noexcept { return memcmp (this, &other, sizeof (*this)) == 0; } bool operator!= (const ExtensibleWavSubFormat& other) const noexcept { return ! operator== (other); } } JUCE_PACKED; static const ExtensibleWavSubFormat pcmFormat = { 0x00000001, 0x0000, 0x0010, { 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71 } }; static const ExtensibleWavSubFormat IEEEFloatFormat = { 0x00000003, 0x0000, 0x0010, { 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71 } }; static const ExtensibleWavSubFormat ambisonicFormat = { 0x00000001, 0x0721, 0x11d3, { 0x86, 0x44, 0xC8, 0xC1, 0xCA, 0x00, 0x00, 0x00 } }; struct DataSize64Chunk // chunk ID = 'ds64' if data size > 0xffffffff, 'JUNK' otherwise { uint32 riffSizeLow; // low 4 byte size of RF64 block uint32 riffSizeHigh; // high 4 byte size of RF64 block uint32 dataSizeLow; // low 4 byte size of data chunk uint32 dataSizeHigh; // high 4 byte size of data chunk uint32 sampleCountLow; // low 4 byte sample count of fact chunk uint32 sampleCountHigh; // high 4 byte sample count of fact chunk uint32 tableLength; // number of valid entries in array 'table' } JUCE_PACKED; #if JUCE_MSVC #pragma pack (pop) #endif } //============================================================================== class WavAudioFormatReader : public AudioFormatReader { public: WavAudioFormatReader (InputStream* const in) : AudioFormatReader (in, TRANS (wavFormatName)), bwavChunkStart (0), bwavSize (0), dataLength (0), isRF64 (false) { using namespace WavFileHelpers; uint64 len = 0; uint64 end = 0; int cueNoteIndex = 0; int cueLabelIndex = 0; int cueRegionIndex = 0; const int firstChunkType = input->readInt(); if (firstChunkType == chunkName ("RF64")) { input->skipNextBytes (4); // size is -1 for RF64 isRF64 = true; } else if (firstChunkType == chunkName ("RIFF")) { len = (uint64) (uint32) input->readInt(); end = len + (uint64) input->getPosition(); } else { return; } const int64 startOfRIFFChunk = input->getPosition(); if (input->readInt() == chunkName ("WAVE")) { if (isRF64 && input->readInt() == chunkName ("ds64")) { const uint32 length = (uint32) input->readInt(); if (length < 28) return; const int64 chunkEnd = input->getPosition() + length + (length & 1); len = (uint64) input->readInt64(); end = len + (uint64) startOfRIFFChunk; dataLength = input->readInt64(); input->setPosition (chunkEnd); } while ((uint64) input->getPosition() < end && ! input->isExhausted()) { const int chunkType = input->readInt(); uint32 length = (uint32) input->readInt(); const int64 chunkEnd = input->getPosition() + length + (length & 1); if (chunkType == chunkName ("fmt ")) { // read the format chunk const unsigned short format = (unsigned short) input->readShort(); numChannels = (unsigned int) input->readShort(); sampleRate = input->readInt(); const int bytesPerSec = input->readInt(); input->skipNextBytes (2); bitsPerSample = (unsigned int) (int) input->readShort(); if (bitsPerSample > 64) { bytesPerFrame = bytesPerSec / (int) sampleRate; bitsPerSample = 8 * (unsigned int) bytesPerFrame / numChannels; } else { bytesPerFrame = numChannels * bitsPerSample / 8; } if (format == 3) { usesFloatingPointData = true; } else if (format == 0xfffe /*WAVE_FORMAT_EXTENSIBLE*/) { if (length < 40) // too short { bytesPerFrame = 0; } else { input->skipNextBytes (4); // skip over size and bitsPerSample metadataValues.set ("ChannelMask", String (input->readInt())); ExtensibleWavSubFormat subFormat; subFormat.data1 = (uint32) input->readInt(); subFormat.data2 = (uint16) input->readShort(); subFormat.data3 = (uint16) input->readShort(); input->read (subFormat.data4, sizeof (subFormat.data4)); if (subFormat == IEEEFloatFormat) usesFloatingPointData = true; else if (subFormat != pcmFormat && subFormat != ambisonicFormat) bytesPerFrame = 0; } } else if (format != 1) { bytesPerFrame = 0; } } else if (chunkType == chunkName ("data")) { if (! isRF64) // data size is expected to be -1, actual data size is in ds64 chunk dataLength = length; dataChunkStart = input->getPosition(); lengthInSamples = (bytesPerFrame > 0) ? (dataLength / bytesPerFrame) : 0; } else if (chunkType == chunkName ("bext")) { bwavChunkStart = input->getPosition(); bwavSize = length; HeapBlock <BWAVChunk> bwav; bwav.calloc (jmax ((size_t) length + 1, sizeof (BWAVChunk)), 1); input->read (bwav, (int) length); bwav->copyTo (metadataValues, (int) length); } else if (chunkType == chunkName ("smpl")) { HeapBlock <SMPLChunk> smpl; smpl.calloc (jmax ((size_t) length + 1, sizeof (SMPLChunk)), 1); input->read (smpl, (int) length); smpl->copyTo (metadataValues, (int) length); } else if (chunkType == chunkName ("inst") || chunkType == chunkName ("INST")) // need to check which... { HeapBlock <InstChunk> inst; inst.calloc (jmax ((size_t) length + 1, sizeof (InstChunk)), 1); input->read (inst, (int) length); inst->copyTo (metadataValues); } else if (chunkType == chunkName ("cue ")) { HeapBlock <CueChunk> cue; cue.calloc (jmax ((size_t) length + 1, sizeof (CueChunk)), 1); input->read (cue, (int) length); cue->copyTo (metadataValues, (int) length); } else if (chunkType == chunkName ("axml")) { MemoryBlock axml; input->readIntoMemoryBlock (axml, (size_t) length); AXMLChunk::addToMetadata (metadataValues, axml.toString()); } else if (chunkType == chunkName ("LIST")) { if (input->readInt() == chunkName ("adtl")) { while (input->getPosition() < chunkEnd) { const int adtlChunkType = input->readInt(); const uint32 adtlLength = (uint32) input->readInt(); const int64 adtlChunkEnd = input->getPosition() + (adtlLength + (adtlLength & 1)); if (adtlChunkType == chunkName ("labl") || adtlChunkType == chunkName ("note")) { String prefix; if (adtlChunkType == chunkName ("labl")) prefix << "CueLabel" << cueLabelIndex++; else if (adtlChunkType == chunkName ("note")) prefix << "CueNote" << cueNoteIndex++; const uint32 identifier = (uint32) input->readInt(); const int stringLength = (int) adtlLength - 4; MemoryBlock textBlock; input->readIntoMemoryBlock (textBlock, stringLength); metadataValues.set (prefix + "Identifier", String (identifier)); metadataValues.set (prefix + "Text", textBlock.toString()); } else if (adtlChunkType == chunkName ("ltxt")) { const String prefix ("CueRegion" + String (cueRegionIndex++)); const uint32 identifier = (uint32) input->readInt(); const uint32 sampleLength = (uint32) input->readInt(); const uint32 purpose = (uint32) input->readInt(); const uint16 country = (uint16) input->readInt(); const uint16 language = (uint16) input->readInt(); const uint16 dialect = (uint16) input->readInt(); const uint16 codePage = (uint16) input->readInt(); const uint32 stringLength = adtlLength - 20; MemoryBlock textBlock; input->readIntoMemoryBlock (textBlock, (int) stringLength); metadataValues.set (prefix + "Identifier", String (identifier)); metadataValues.set (prefix + "SampleLength", String (sampleLength)); metadataValues.set (prefix + "Purpose", String (purpose)); metadataValues.set (prefix + "Country", String (country)); metadataValues.set (prefix + "Language", String (language)); metadataValues.set (prefix + "Dialect", String (dialect)); metadataValues.set (prefix + "CodePage", String (codePage)); metadataValues.set (prefix + "Text", textBlock.toString()); } input->setPosition (adtlChunkEnd); } } } else if (chunkType == chunkName ("acid")) { AcidChunk (*input, length).addToMetadata (metadataValues); } else if (chunkEnd <= input->getPosition()) { break; } input->setPosition (chunkEnd); } } if (cueLabelIndex > 0) metadataValues.set ("NumCueLabels", String (cueLabelIndex)); if (cueNoteIndex > 0) metadataValues.set ("NumCueNotes", String (cueNoteIndex)); if (cueRegionIndex > 0) metadataValues.set ("NumCueRegions", String (cueRegionIndex)); if (metadataValues.size() > 0) metadataValues.set ("MetaDataSource", "WAV"); } //============================================================================== bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer, int64 startSampleInFile, int numSamples) override { clearSamplesBeyondAvailableLength (destSamples, numDestChannels, startOffsetInDestBuffer, startSampleInFile, numSamples, lengthInSamples); if (numSamples <= 0) return true; input->setPosition (dataChunkStart + startSampleInFile * bytesPerFrame); while (numSamples > 0) { const int tempBufSize = 480 * 3 * 4; // (keep this a multiple of 3) char tempBuffer [tempBufSize]; const int numThisTime = jmin (tempBufSize / bytesPerFrame, numSamples); const int bytesRead = input->read (tempBuffer, numThisTime * bytesPerFrame); if (bytesRead < numThisTime * bytesPerFrame) { jassert (bytesRead >= 0); zeromem (tempBuffer + bytesRead, (size_t) (numThisTime * bytesPerFrame - bytesRead)); } copySampleData (bitsPerSample, usesFloatingPointData, destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, (int) numChannels, numThisTime); startOffsetInDestBuffer += numThisTime; numSamples -= numThisTime; } return true; } static void copySampleData (unsigned int bitsPerSample, const bool usesFloatingPointData, int* const* destSamples, int startOffsetInDestBuffer, int numDestChannels, const void* sourceData, int numChannels, int numSamples) noexcept { switch (bitsPerSample) { case 8: ReadHelper<AudioData::Int32, AudioData::UInt8, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, sourceData, numChannels, numSamples); break; case 16: ReadHelper<AudioData::Int32, AudioData::Int16, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, sourceData, numChannels, numSamples); break; case 24: ReadHelper<AudioData::Int32, AudioData::Int24, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, sourceData, numChannels, numSamples); break; case 32: if (usesFloatingPointData) ReadHelper<AudioData::Float32, AudioData::Float32, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, sourceData, numChannels, numSamples); else ReadHelper<AudioData::Int32, AudioData::Int32, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, sourceData, numChannels, numSamples); break; default: jassertfalse; break; } } int64 bwavChunkStart, bwavSize; int64 dataChunkStart, dataLength; int bytesPerFrame; bool isRF64; private: JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WavAudioFormatReader) }; //============================================================================== class WavAudioFormatWriter : public AudioFormatWriter { public: WavAudioFormatWriter (OutputStream* const out, const double rate, const unsigned int numChans, const unsigned int bits, const StringPairArray& metadataValues) : AudioFormatWriter (out, TRANS (wavFormatName), rate, numChans, bits), lengthInSamples (0), bytesWritten (0), writeFailed (false) { using namespace WavFileHelpers; if (metadataValues.size() > 0) { // The meta data should have been santised for the WAV format. // If it was originally sourced from an AIFF file the MetaDataSource // key should be removed (or set to "WAV") once this has been done jassert (metadataValues.getValue ("MetaDataSource", "None") != "AIFF"); bwavChunk = BWAVChunk::createFrom (metadataValues); axmlChunk = AXMLChunk::createFrom (metadataValues); smplChunk = SMPLChunk::createFrom (metadataValues); instChunk = InstChunk::createFrom (metadataValues); cueChunk = CueChunk ::createFrom (metadataValues); listChunk = ListChunk::createFrom (metadataValues); } headerPosition = out->getPosition(); writeHeader(); } ~WavAudioFormatWriter() { if ((bytesWritten & 1) != 0) // pad to an even length { ++bytesWritten; output->writeByte (0); } writeHeader(); } //============================================================================== bool write (const int** data, int numSamples) override { jassert (numSamples >= 0); jassert (data != nullptr && *data != nullptr); // the input must contain at least one channel! if (writeFailed) return false; const size_t bytes = numChannels * (unsigned int) numSamples * bitsPerSample / 8; tempBlock.ensureSize (bytes, false); switch (bitsPerSample) { case 8: WriteHelper<AudioData::UInt8, AudioData::Int32, AudioData::LittleEndian>::write (tempBlock.getData(), (int) numChannels, data, numSamples); break; case 16: WriteHelper<AudioData::Int16, AudioData::Int32, AudioData::LittleEndian>::write (tempBlock.getData(), (int) numChannels, data, numSamples); break; case 24: WriteHelper<AudioData::Int24, AudioData::Int32, AudioData::LittleEndian>::write (tempBlock.getData(), (int) numChannels, data, numSamples); break; case 32: WriteHelper<AudioData::Int32, AudioData::Int32, AudioData::LittleEndian>::write (tempBlock.getData(), (int) numChannels, data, numSamples); break; default: jassertfalse; break; } if (! output->write (tempBlock.getData(), bytes)) { // failed to write to disk, so let's try writing the header. // If it's just run out of disk space, then if it does manage // to write the header, we'll still have a useable file.. writeHeader(); writeFailed = true; return false; } else { bytesWritten += bytes; lengthInSamples += (uint64) numSamples; return true; } } private: MemoryBlock tempBlock, bwavChunk, axmlChunk, smplChunk, instChunk, cueChunk, listChunk; uint64 lengthInSamples, bytesWritten; int64 headerPosition; bool writeFailed; static int getChannelMask (const int numChannels) noexcept { switch (numChannels) { case 1: return 0; case 2: return 1 + 2; // SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT case 5: return 1 + 2 + 4 + 16 + 32; // SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | SPEAKER_FRONT_CENTER | SPEAKER_BACK_LEFT | SPEAKER_BACK_RIGHT case 6: return 1 + 2 + 4 + 8 + 16 + 32; // SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | SPEAKER_FRONT_CENTER | SPEAKER_LOW_FREQUENCY | SPEAKER_BACK_LEFT | SPEAKER_BACK_RIGHT case 7: return 1 + 2 + 4 + 16 + 32 + 512 + 1024; // SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | SPEAKER_FRONT_CENTER | SPEAKER_BACK_LEFT | SPEAKER_BACK_RIGHT | SPEAKER_SIDE_LEFT | SPEAKER_SIDE_RIGHT case 8: return 1 + 2 + 4 + 8 + 16 + 32 + 512 + 1024; // SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | SPEAKER_FRONT_CENTER | SPEAKER_LOW_FREQUENCY | SPEAKER_BACK_LEFT | SPEAKER_BACK_RIGHT | SPEAKER_SIDE_LEFT | SPEAKER_SIDE_RIGHT default: break; } return 0; } void writeHeader() { using namespace WavFileHelpers; const bool seekedOk = output->setPosition (headerPosition); (void) seekedOk; // if this fails, you've given it an output stream that can't seek! It needs // to be able to seek back to write the header jassert (seekedOk); const size_t bytesPerFrame = numChannels * bitsPerSample / 8; uint64 audioDataSize = bytesPerFrame * lengthInSamples; const bool isRF64 = (bytesWritten >= 0x100000000LL); const bool isWaveFmtEx = isRF64 || (numChannels > 2); int64 riffChunkSize = (int64) (4 /* 'RIFF' */ + 8 + 40 /* WAVEFORMATEX */ + 8 + audioDataSize + (audioDataSize & 1) + chunkSize (bwavChunk) + chunkSize (axmlChunk) + chunkSize (smplChunk) + chunkSize (instChunk) + chunkSize (cueChunk) + chunkSize (listChunk) + (8 + 28)); // (ds64 chunk) riffChunkSize += (riffChunkSize & 1); if (isRF64) writeChunkHeader (chunkName ("RF64"), -1); else writeChunkHeader (chunkName ("RIFF"), (int) riffChunkSize); output->writeInt (chunkName ("WAVE")); if (! isRF64) { #if ! JUCE_WAV_DO_NOT_PAD_HEADER_SIZE /* NB: This junk chunk is added for padding, so that the header is a fixed size regardless of whether it's RF64 or not. That way, we can begin recording a file, and when it's finished, can go back and write either a RIFF or RF64 header, depending on whether more than 2^32 samples were written. The JUCE_WAV_DO_NOT_PAD_HEADER_SIZE macro allows you to disable this feature in case you need to create files for crappy WAV players with bugs that stop them skipping chunks which they don't recognise. But DO NOT USE THIS option unless you really have no choice, because it means that if you write more than 2^32 samples to the file, you'll corrupt it. */ writeChunkHeader (chunkName ("JUNK"), 28 + (isWaveFmtEx? 0 : 24)); output->writeRepeatedByte (0, 28 /* ds64 */ + (isWaveFmtEx? 0 : 24)); #endif } else { #if JUCE_WAV_DO_NOT_PAD_HEADER_SIZE // If you disable padding, then you MUST NOT write more than 2^32 samples to a file. jassertfalse; #endif writeChunkHeader (chunkName ("ds64"), 28); // chunk size for uncompressed data (no table) output->writeInt64 (riffChunkSize); output->writeInt64 ((int64) audioDataSize); output->writeRepeatedByte (0, 12); } if (isWaveFmtEx) { writeChunkHeader (chunkName ("fmt "), 40); output->writeShort ((short) (uint16) 0xfffe); // WAVE_FORMAT_EXTENSIBLE } else { writeChunkHeader (chunkName ("fmt "), 16); output->writeShort (bitsPerSample < 32 ? (short) 1 /*WAVE_FORMAT_PCM*/ : (short) 3 /*WAVE_FORMAT_IEEE_FLOAT*/); } output->writeShort ((short) numChannels); output->writeInt ((int) sampleRate); output->writeInt ((int) (bytesPerFrame * sampleRate)); // nAvgBytesPerSec output->writeShort ((short) bytesPerFrame); // nBlockAlign output->writeShort ((short) bitsPerSample); // wBitsPerSample if (isWaveFmtEx) { output->writeShort (22); // cbSize (size of the extension) output->writeShort ((short) bitsPerSample); // wValidBitsPerSample output->writeInt (getChannelMask ((int) numChannels)); const ExtensibleWavSubFormat& subFormat = bitsPerSample < 32 ? pcmFormat : IEEEFloatFormat; output->writeInt ((int) subFormat.data1); output->writeShort ((short) subFormat.data2); output->writeShort ((short) subFormat.data3); output->write (subFormat.data4, sizeof (subFormat.data4)); } writeChunk (bwavChunk, chunkName ("bext")); writeChunk (axmlChunk, chunkName ("axml")); writeChunk (smplChunk, chunkName ("smpl")); writeChunk (instChunk, chunkName ("inst"), 7); writeChunk (cueChunk, chunkName ("cue ")); writeChunk (listChunk, chunkName ("LIST")); writeChunkHeader (chunkName ("data"), isRF64 ? -1 : (int) (lengthInSamples * bytesPerFrame)); usesFloatingPointData = (bitsPerSample == 32); } static int chunkSize (const MemoryBlock& data) noexcept { return data.getSize() > 0 ? (8 + data.getSize()) : 0; } void writeChunkHeader (int chunkType, int size) const { output->writeInt (chunkType); output->writeInt (size); } void writeChunk (const MemoryBlock& data, int chunkType, int size = 0) const { if (data.getSize() > 0) { writeChunkHeader (chunkType, size != 0 ? size : (int) data.getSize()); *output << data; } } JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WavAudioFormatWriter) }; //============================================================================== class MemoryMappedWavReader : public MemoryMappedAudioFormatReader { public: MemoryMappedWavReader (const File& file, const WavAudioFormatReader& reader) : MemoryMappedAudioFormatReader (file, reader, reader.dataChunkStart, reader.dataLength, reader.bytesPerFrame) { } bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer, int64 startSampleInFile, int numSamples) override { clearSamplesBeyondAvailableLength (destSamples, numDestChannels, startOffsetInDestBuffer, startSampleInFile, numSamples, lengthInSamples); if (map == nullptr || ! mappedSection.contains (Range<int64> (startSampleInFile, startSampleInFile + numSamples))) { jassertfalse; // you must make sure that the window contains all the samples you're going to attempt to read. return false; } WavAudioFormatReader::copySampleData (bitsPerSample, usesFloatingPointData, destSamples, startOffsetInDestBuffer, numDestChannels, sampleToPointer (startSampleInFile), (int) numChannels, numSamples); return true; } void readMaxLevels (int64 startSampleInFile, int64 numSamples, float& min0, float& max0, float& min1, float& max1) override { if (numSamples <= 0) { min0 = max0 = min1 = max1 = 0; return; } if (map == nullptr || ! mappedSection.contains (Range<int64> (startSampleInFile, startSampleInFile + numSamples))) { jassertfalse; // you must make sure that the window contains all the samples you're going to attempt to read. min0 = max0 = min1 = max1 = 0; return; } switch (bitsPerSample) { case 8: scanMinAndMax<AudioData::UInt8> (startSampleInFile, numSamples, min0, max0, min1, max1); break; case 16: scanMinAndMax<AudioData::Int16> (startSampleInFile, numSamples, min0, max0, min1, max1); break; case 24: scanMinAndMax<AudioData::Int24> (startSampleInFile, numSamples, min0, max0, min1, max1); break; case 32: if (usesFloatingPointData) scanMinAndMax<AudioData::Float32> (startSampleInFile, numSamples, min0, max0, min1, max1); else scanMinAndMax<AudioData::Int32> (startSampleInFile, numSamples, min0, max0, min1, max1); break; default: jassertfalse; break; } } private: template <typename SampleType> void scanMinAndMax (int64 startSampleInFile, int64 numSamples, float& min0, float& max0, float& min1, float& max1) const noexcept { scanMinAndMaxInterleaved<SampleType, AudioData::LittleEndian> (0, startSampleInFile, numSamples, min0, max0); if (numChannels > 1) scanMinAndMaxInterleaved<SampleType, AudioData::LittleEndian> (1, startSampleInFile, numSamples, min1, max1); else min1 = max1 = 0; } JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MemoryMappedWavReader) }; //============================================================================== WavAudioFormat::WavAudioFormat() : AudioFormat (TRANS (wavFormatName), StringArray (wavExtensions)) { } WavAudioFormat::~WavAudioFormat() { } Array<int> WavAudioFormat::getPossibleSampleRates() { const int rates[] = { 8000, 11025, 12000, 16000, 22050, 32000, 44100, 48000, 88200, 96000, 176400, 192000, 352800, 384000 }; return Array<int> (rates, numElementsInArray (rates)); } Array<int> WavAudioFormat::getPossibleBitDepths() { const int depths[] = { 8, 16, 24, 32 }; return Array<int> (depths, numElementsInArray (depths)); } bool WavAudioFormat::canDoStereo() { return true; } bool WavAudioFormat::canDoMono() { return true; } AudioFormatReader* WavAudioFormat::createReaderFor (InputStream* sourceStream, const bool deleteStreamIfOpeningFails) { ScopedPointer<WavAudioFormatReader> r (new WavAudioFormatReader (sourceStream)); if (r->sampleRate > 0 && r->numChannels > 0) return r.release(); if (! deleteStreamIfOpeningFails) r->input = nullptr; return nullptr; } MemoryMappedAudioFormatReader* WavAudioFormat::createMemoryMappedReader (const File& file) { if (FileInputStream* fin = file.createInputStream()) { WavAudioFormatReader reader (fin); if (reader.lengthInSamples > 0) return new MemoryMappedWavReader (file, reader); } return nullptr; } AudioFormatWriter* WavAudioFormat::createWriterFor (OutputStream* out, double sampleRate, unsigned int numChannels, int bitsPerSample, const StringPairArray& metadataValues, int /*qualityOptionIndex*/) { if (getPossibleBitDepths().contains (bitsPerSample)) return new WavAudioFormatWriter (out, sampleRate, (unsigned int) numChannels, (unsigned int) bitsPerSample, metadataValues); return nullptr; } namespace WavFileHelpers { static bool slowCopyWavFileWithNewMetadata (const File& file, const StringPairArray& metadata) { TemporaryFile tempFile (file); WavAudioFormat wav; ScopedPointer<AudioFormatReader> reader (wav.createReaderFor (file.createInputStream(), true)); if (reader != nullptr) { ScopedPointer<OutputStream> outStream (tempFile.getFile().createOutputStream()); if (outStream != nullptr) { ScopedPointer<AudioFormatWriter> writer (wav.createWriterFor (outStream, reader->sampleRate, reader->numChannels, (int) reader->bitsPerSample, metadata, 0)); if (writer != nullptr) { outStream.release(); bool ok = writer->writeFromAudioReader (*reader, 0, -1); writer = nullptr; reader = nullptr; return ok && tempFile.overwriteTargetFileWithTemporary(); } } } return false; } } bool WavAudioFormat::replaceMetadataInFile (const File& wavFile, const StringPairArray& newMetadata) { using namespace WavFileHelpers; ScopedPointer<WavAudioFormatReader> reader (static_cast<WavAudioFormatReader*> (createReaderFor (wavFile.createInputStream(), true))); if (reader != nullptr) { const int64 bwavPos = reader->bwavChunkStart; const int64 bwavSize = reader->bwavSize; reader = nullptr; if (bwavSize > 0) { MemoryBlock chunk (BWAVChunk::createFrom (newMetadata)); if (chunk.getSize() <= (size_t) bwavSize) { // the new one will fit in the space available, so write it directly.. const int64 oldSize = wavFile.getSize(); { FileOutputStream out (wavFile); if (! out.failedToOpen()) { out.setPosition (bwavPos); out << chunk; out.setPosition (oldSize); } } jassert (wavFile.getSize() == oldSize); return true; } } } return slowCopyWavFileWithNewMetadata (wavFile, newMetadata); }
[ "kaspar.emanuel@gmail.com" ]
kaspar.emanuel@gmail.com
797cb8d5c59f79639d4387b24586bebffd5a9bdd
c588186250b1af54a276dbba2efc8bb78ca14125
/GYM/101522_J.cpp
d5aa27e39bd18fb4b2801bc16467144d8477d4f7
[]
no_license
Meng-Lan/Lan
380fdedd8ed7b0c1e5ffdabdc0c2ce48344927df
fc12199919028335d6ddb12c8a0aa0537a07b851
refs/heads/master
2021-06-28T11:59:50.201500
2020-07-11T09:05:53
2020-07-11T09:05:53
93,761,541
0
0
null
null
null
null
UTF-8
C++
false
false
2,987
cpp
#include<iostream> #include<cstdio> #include<string> #include<cstring> #include<cstdlib> #include<sstream> #include<fstream> #include<vector> #include<list> #include<deque> #include<stack> #include<queue> #include<map> #include<set> #include<cmath> #include<utility> #include<numeric> #include<iterator> #include<algorithm> #include<functional> #include<ctime> #include<cassert> using std::cin; using std::cout; using std::endl; typedef long long ll; typedef unsigned long long ull; typedef std::pair<int,int> P; #define FOR(i,init,len) for(int i=(init);i<(len);++i) #define For(i,init,len) for(int i=(init);i<=(len);++i) #define fi first #define se second #define pb push_back #define is insert namespace IO { inline char getchar() { static const int BUFSIZE=5201314; static char buf[BUFSIZE],*begin,*end; if(begin==end) { begin=buf; end=buf+fread(buf,1,BUFSIZE,stdin); if(begin==end) return -1; } return *begin++; } } inline void read(int &in) { int c,symbol=1; while(isspace(c=IO::getchar())); if(c=='-') { in=0;symbol=-1; } else in=c-'0'; while(isdigit(c=IO::getchar())) { in*=10;in+=c-'0'; } in*=symbol; } inline int read() { static int x;read(x);return x; } ll gcd(ll a,ll b) { return b?gcd(b,a%b):a; } ll lcm(ll a,ll b) { return a/gcd(a,b)*b; } #define PA(name,init,len) cout<<#name"["<<(len-init)<<"]=";FOR(_,init,len) cout<<name[_]<<" \n"[_==(len-1)]; #define Pa(name,init,len) cout<<#name"["<<(len-init+1)<<"]=";For(_,init,len) cout<<name[_]<<" \n"[_==(len)]; #define PV(name) cout<<#name"="<<name<<'\n'; const int maxn=205; const ll INF=1e18; ll d[maxn][maxn][maxn][3]; int b,r,s; ll k; ll dp(int b,int r,int s,int fr) { if(b<0||r<0||s<0) return 0; //printf("b:%d r:%d s:%d fr:%d ans:%lld\n",b,r,s,fr,d[b][r][s]); if(d[b][r][s][fr]>=0) return d[b][r][s][fr]; ll &ans=d[b][r][s][fr];ans=0; if(fr==0&&!r&&!s) return ans; if(fr==1&&!b&&!s) return ans; if(fr==2&&!b&&!r) return ans; if(b+r+s==1) return ans=1; if(fr!=0&&b) ans+=dp(b-1,r,s,0); if(fr!=1&&r) ans+=dp(b,r-1,s,1); if(fr!=2&&s) ans+=dp(b,r,s-1,2); if(ans>=INF) ans=INF; //printf("b:%d r:%d s:%d fr:%d ans:%lld\n",b,r,s,fr,ans); return ans; } void print(int b,int r,int s,int fr,ll k) { if(b<0||r<0||s<0) return; if(b+r+s==1) { if(b) printf("B"); if(r) printf("R"); if(s) printf("S"); return; } if(fr!=0&&b) { if(k>dp(b-1,r,s,0)) k-=dp(b-1,r,s,0); else { printf("B");print(b-1,r,s,0,k);return; } } if(fr!=1&&r) { if(k>dp(b,r-1,s,1)) k-=dp(b,r-1,s,1); else { printf("R");print(b,r-1,s,1,k);return; } } if(fr!=2&&s) { printf("S");print(b,r,s-1,2,k); } } int main() { #ifdef MengLan int Beginning=clock(); //freopen("in","r",stdin); //freopen("out","w",stdout); #endif // MengLan memset(d,-1,sizeof(d)); cin>>b>>r>>s>>k; ll sum=0; sum+=dp(b-1,r,s,0); sum+=dp(b,r-1,s,1); sum+=dp(b,r,s-1,2); if(sum<k) puts("None"); else print(b,r,s,3,k),printf("\n"); #ifdef MengLan printf("Time: %d\n",clock()-Beginning); #endif // MengLan return 0; }
[ "779379402@qq.com" ]
779379402@qq.com
a8fb1f58469498d423aaa78c8f3900c8c60089ed
36995789e9fe22d629bfe1b1dc78ed4cffaa6f75
/firmware/arduino/Board4Control/Board4Control_LCD.h
4d69b5b067b7766b737eebe4ec7fc11e53cb0bae
[]
no_license
FBSeletronica/4ControlBoard
feff9d59391c4dc770a5bd57ca99b15be408aa23
83b0a4db03e59af6b45ec9177873bf5e5b04a5e5
refs/heads/master
2021-01-10T17:14:12.736067
2016-02-07T00:12:51
2016-02-07T00:12:51
45,721,579
1
0
null
null
null
null
UTF-8
C++
false
false
3,123
h
/* this library is based on arduino LiquidyCristal library: https://github.com/arduino/Arduino/tree/master/libraries/LiquidCrystal */ #ifndef Board4Control_LCD_h #define Board4Control_LCD_h #include <inttypes.h> #include "Print.h" // commands #define LCD_CLEARDISPLAY 0x01 #define LCD_RETURNHOME 0x02 #define LCD_ENTRYMODESET 0x04 #define LCD_DISPLAYCONTROL 0x08 #define LCD_CURSORSHIFT 0x10 #define LCD_FUNCTIONSET 0x20 #define LCD_SETCGRAMADDR 0x40 #define LCD_SETDDRAMADDR 0x80 // flags for display entry mode #define LCD_ENTRYRIGHT 0x00 #define LCD_ENTRYLEFT 0x02 #define LCD_ENTRYSHIFTINCREMENT 0x01 #define LCD_ENTRYSHIFTDECREMENT 0x00 // flags for display on/off control #define LCD_DISPLAYON 0x04 #define LCD_DISPLAYOFF 0x00 #define LCD_CURSORON 0x02 #define LCD_CURSOROFF 0x00 #define LCD_BLINKON 0x01 #define LCD_BLINKOFF 0x00 // flags for display/cursor shift #define LCD_DISPLAYMOVE 0x08 #define LCD_CURSORMOVE 0x00 #define LCD_MOVERIGHT 0x04 #define LCD_MOVELEFT 0x00 // flags for function set #define LCD_8BITMODE 0x10 #define LCD_4BITMODE 0x00 #define LCD_2LINE 0x08 #define LCD_1LINE 0x00 #define LCD_5x10DOTS 0x04 #define LCD_5x8DOTS 0x00 class Board4Control_LCD : public Print { public: Board4Control_LCD(uint8_t rs, uint8_t enable, uint8_t d0, uint8_t d1, uint8_t d2, uint8_t d3, uint8_t d4, uint8_t d5, uint8_t d6, uint8_t d7); Board4Control_LCD(uint8_t rs, uint8_t rw, uint8_t enable, uint8_t d0, uint8_t d1, uint8_t d2, uint8_t d3, uint8_t d4, uint8_t d5, uint8_t d6, uint8_t d7); Board4Control_LCD(uint8_t rs, uint8_t rw, uint8_t enable, uint8_t d0, uint8_t d1, uint8_t d2, uint8_t d3); Board4Control_LCD(uint8_t rs, uint8_t enable, uint8_t d0, uint8_t d1, uint8_t d2, uint8_t d3); void init(uint8_t fourbitmode, uint8_t rs, uint8_t rw, uint8_t enable, uint8_t d0, uint8_t d1, uint8_t d2, uint8_t d3, uint8_t d4, uint8_t d5, uint8_t d6, uint8_t d7); void begin(uint8_t cols, uint8_t rows, uint8_t charsize = LCD_5x8DOTS); void clear(); void home(); void noDisplay(); void display(); void noBlink(); void blink(); void noCursor(); void cursor(); void scrollDisplayLeft(); void scrollDisplayRight(); void leftToRight(); void rightToLeft(); void autoscroll(); void noAutoscroll(); // Turn the backlight on/off void setBacklight(uint8_t status); void setRowOffsets(int row1, int row2, int row3, int row4); void createChar(uint8_t, uint8_t[]); void setCursor(uint8_t, uint8_t); virtual size_t write(uint8_t); void command(uint8_t); using Print::write; private: void send(uint8_t, uint8_t); void write4bits(uint8_t); void write8bits(uint8_t); void pulseEnable(); void configMuxPins(int mode); uint8_t _rs_pin; // LOW: command. HIGH: character. uint8_t _rw_pin; // LOW: write to LCD. HIGH: read from LCD. uint8_t _enable_pin; // activated by a HIGH pulse. uint8_t _data_pins[8]; uint8_t _displayfunction; uint8_t _displaycontrol; uint8_t _displaymode; uint8_t _initialized; uint8_t _numlines; uint8_t _row_offsets[4]; }; extern Board4Control_LCD lcd; #endif
[ "fabio_souza53@hotmail.com" ]
fabio_souza53@hotmail.com
d0ac7841f09137315a59638863caa6479b8e22be
74a9456b605da15cbce5eefcfc22b2c049925d24
/mimosa/fft/scwf-gen.hxx
6e9111bd94c0531e5feb61874195eb6740aa7979
[ "MIT" ]
permissive
abique/mimosa
195ae693e2270fbfe9129b95b981946fab780d4e
87fff4dfce5f5a792bd7b93db3f3337e477aae76
refs/heads/master
2022-06-30T16:32:55.355008
2022-06-07T11:38:47
2022-06-07T11:38:47
2,087,313
27
8
MIT
2018-01-16T07:20:04
2011-07-22T05:40:03
C++
UTF-8
C++
false
false
1,410
hxx
#pragma once #include "scwf-gen.hh" namespace mimosa { namespace fft { template <typename fp_type, int len> void generateIdealSawSpectrum(fp_type *spectrum) { static_assert(len & (len - 1) == 0, "len is a power of 2"); static_assert(len >= 4, "len must be greater or equal to 4"); for (int i = 0; i < len; i += 4) { spectrum[i] = 1; spectrum[i + 1] = 0; spectrum[i + 2] = 0; spectrum[i + 3] = 0; } } template <typename fp_type, int len> void generateIdealSawSignal(fp_type *signal) { static_assert(len & (len - 1) == 0, "len is a power of 2"); fp_type spectrum[len]; generatePerfectSquareSpectrum<fp_type, len>(spectrum); ifft<fp_type, len>(spectrum, signal); } template <typename fp_type, int len> void generateIdealSquareSpectrum(fp_type *spectrum) { static_assert(len & (len - 1) == 0, "len is a power of 2"); static_assert(len >= 4, "len must be greater or equal to 4"); for (int i = 0; i < len; i += 4) { spectrum[i] = 1; spectrum[i + 1] = 0; spectrum[i + 2] = 0; spectrum[i + 3] = 0; } } template <typename fp_type, int len> void generateIdealSquareSignal(fp_type *signal) { static_assert(len & (len - 1) == 0, "len is a power of 2"); fp_type spectrum[len]; generatePerfectSquareSpectrum<fp_type, len>(spectrum); ifft<fp_type, len>(spectrum, signal); } } }
[ "bique.alexandre@gmail.com" ]
bique.alexandre@gmail.com
94d48ed1c035125452d0b86e91594c1dd5faaec2
b9c62e76aa57e5482ac1bfb96852b74046acea55
/leetcode/59spiral-matrix-ii.cpp
7bce6d215db1942fd58869fd94346780f37d2295
[]
no_license
demeiyan/algorithm
e7c9401a3d3486582865cd1d04a4d34a130bbe56
75c02ae3375e34a6209fdc91ba2a30979f091901
refs/heads/master
2022-11-13T03:59:09.175400
2019-09-17T05:01:06
2019-09-17T05:01:06
59,123,515
0
0
null
null
null
null
UTF-8
C++
false
false
2,262
cpp
/** * @Date 2019/2/18 21:43 * @Created by dmyan */ #include<bits/stdc++.h> using namespace std; class Solution { public: vector<vector<int>> generateMatrix(int n) { vector<vector<int>> res; if(n==0)return res; res.resize(n); if(n==1){ vector<int> tmp(n,0); cout<<"1"; res[0] = tmp; res[0][0] = 1; return res; } int m = n; vector<vector<bool>> f; f.resize(n); for(int i=0;i<f.size();i++){ vector<bool> tmp(n, false); f[i] = tmp; vector<int> tmp1(n,0); res[i] = tmp1; } int row = 0, col = 0; bool colr = true, rowu = false, coll = false, rowd = false; int cnt = 1; while(true){ if(!f[row][col]){ res[row][col] = cnt; f[row][col] = true; } if(colr){ if(col < n-1 && !f[row][col+1]){ col++; cnt++; continue; }else{ rowd = true; colr = false; } } if(rowd){ if(row < m-1&&!f[row+1][col]){ row++; cnt++; continue; }else{ coll = true; rowd = false; } } if(coll){ if(col > 0&&!f[row][col-1]){ col --; cnt++; continue; }else{ rowu = true; coll = false; } } if(rowu){ if(row>0&&!f[row-1][col]){ row--; cnt++; continue; }else{ colr = true; rowu = false; } } if(col==0&&f[row][col+1]&&f[row-1][col])break; if(row>0&&col>0&&row<m-1&&col<n-1){ if(f[row-1][col]&&f[row+1][col]&&f[row][col+1]&&f[row][col-1])break; } } return res; } };
[ "1312480794@qq.com" ]
1312480794@qq.com
6f4d5948f123da8605259044df72c057f923c2f1
936fa91805ad7e156705a3446f88ddd258b77a4f
/example/gizmesh_example_gl3/renderer_impl_gl3.cpp
44382cc084f76b539158181c4cdea7abc273d1f1
[ "MIT" ]
permissive
ousttrue/gizmesh
2456edd3b632bfe8835b0c77159caa8d542a47a2
fbc845abcd20eacc06c89c03a9e86a81208c401d
refs/heads/master
2023-08-23T08:41:19.628360
2021-09-10T11:24:53
2021-09-10T11:24:53
243,416,047
0
0
null
null
null
null
UTF-8
C++
false
false
6,012
cpp
#include "gl-api.hpp" #include "renderer.h" #include "teapot.h" #include "wgl_context.h" constexpr const char gizmo_vert[] = R"(#version 330 layout(location = 0) in vec3 vertex; layout(location = 1) in vec3 normal; layout(location = 2) in vec4 color; out vec4 v_color; out vec3 v_world, v_normal; //uniform mat4 u_mvp; uniform mat4 u_modelMatrix; uniform mat4 u_viewProj; void main() { gl_Position = u_viewProj * u_modelMatrix * vec4(vertex.xyz, 1); v_color = color; v_world = vertex; v_normal = normal; } )"; constexpr const char gizmo_frag[] = R"(#version 330 in vec4 v_color; in vec3 v_world, v_normal; out vec4 f_color; uniform vec3 u_eye; void main() { vec3 light = vec3(1) * max(dot(v_normal, normalize(u_eye - v_world)), 0.50) + 0.25; f_color = v_color * vec4(light, 1); } )"; constexpr const char lit_vert[] = R"(#version 330 uniform mat4 u_modelMatrix; uniform mat4 u_viewProj; layout(location = 0) in vec3 inPosition; layout(location = 1) in vec3 inNormal; out vec3 v_position, v_normal; void main() { vec4 worldPos = u_modelMatrix * vec4(inPosition, 1); v_position = worldPos.xyz; v_normal = normalize((u_modelMatrix * vec4(inNormal,0)).xyz); gl_Position = u_viewProj * worldPos; } )"; constexpr const char lit_frag[] = R"(#version 330 uniform vec3 u_diffuse = vec3(1, 1, 1); uniform vec3 u_eye; in vec3 v_position; in vec3 v_normal; out vec4 f_color; vec3 compute_lighting(vec3 eyeDir, vec3 position, vec3 color) { vec3 light = vec3(0, 0, 0); vec3 lightDir = normalize(position - v_position); light += color * u_diffuse * max(dot(v_normal, lightDir), 0); vec3 halfDir = normalize(lightDir + eyeDir); light += color * u_diffuse * pow(max(dot(v_normal, halfDir), 0), 128); return light; } void main() { vec3 eyeDir = vec3(0, 1, -2); vec3 light = vec3(0, 0, 0); light += compute_lighting(eyeDir, vec3(+3, 1, 0), vec3(235.0/255.0, 43.0/255.0, 211.0/255.0)); light += compute_lighting(eyeDir, vec3(-3, 1, 0), vec3(43.0/255.0, 236.0/255.0, 234.0/255.0)); f_color = vec4(light + vec3(0.5, 0.5, 0.5), 1.0); } )"; class ModelImpl { std::unique_ptr<GlShader> m_shader; GlMesh m_mesh; public: void upload_mesh(const void *pVertices, uint32_t verticesBytes, uint32_t vertexStride, const void *pIndices, uint32_t indicesBytes, uint32_t indexStride, bool isDynamic = false) { if (!m_shader) { if (isDynamic) { m_shader.reset(new GlShader(gizmo_vert, gizmo_frag)); } else { m_shader.reset(new GlShader(lit_vert, lit_frag)); } } m_mesh.set_vertex_data(verticesBytes, pVertices, isDynamic ? GL_DYNAMIC_DRAW : GL_STATIC_DRAW); m_mesh.set_attribute(0, 3, GL_FLOAT, GL_FALSE, vertexStride, (GLvoid *)0); m_mesh.set_attribute(1, 3, GL_FLOAT, GL_FALSE, vertexStride, (GLvoid *)12); m_mesh.set_attribute(2, 4, GL_FLOAT, GL_FALSE, vertexStride, (GLvoid *)24); GLenum type; switch (indexStride) { case 2: type = GL_UNSIGNED_SHORT; break; case 4: type = GL_UNSIGNED_INT; break; default: throw; } m_mesh.set_index_data(GL_TRIANGLES, type, indicesBytes / indexStride, pIndices, isDynamic ? GL_DYNAMIC_DRAW : GL_STATIC_DRAW); } void draw(const float *eye, const float *viewProj, const float *model, bool isGizmo = false) { if (isGizmo) { glClear(GL_DEPTH_BUFFER_BIT); } m_shader->bind(); m_shader->uniform_float16("u_viewProj", viewProj); m_shader->uniform_float16("u_modelMatrix", model); m_shader->uniform_float3("u_eye", eye); m_mesh.draw_elements(); m_shader->unbind(); } }; Model::Model(ModelImpl *impl) : m_impl(impl) {} Model::~Model() { delete m_impl; } void Model::uploadMesh(void *, const void *vertices, uint32_t verticesSize, uint32_t vertexStride, const void *indices, uint32_t indicesSize, uint32_t indexSize, bool is_dynamic) { m_impl->upload_mesh(vertices, verticesSize, vertexStride, indices, indicesSize, indexSize, is_dynamic); } void Model::draw(void *, const float *model, const float *vp, const float *eye) { m_impl->draw(eye, vp, model); } ///////////////////////////////////////////// class RendererImpl { WGLContext m_wgl; public: bool initialize(void *hwnd) { if (!m_wgl.Create(hwnd, 3, 0)) { return false; } return true; } void beginFrame(int width, int height) { glViewport(0, 0, width, height); glEnable(GL_DEPTH_TEST); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glClearColor(0.725f, 0.725f, 0.725f, 1.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); } void clearDepth() { glClear(GL_DEPTH_BUFFER_BIT); } void endFrame() { gl_check_error(__FILE__, __LINE__); m_wgl.Present(); } }; Renderer::Renderer() : m_impl(new RendererImpl) {} Renderer::~Renderer() { delete m_impl; } void *Renderer::initialize(void *hwnd) { return m_impl->initialize(hwnd) ? this : nullptr; } std::shared_ptr<Model> Renderer::createMesh() { auto modelImpl = new ModelImpl(); return std::make_shared<Model>(modelImpl); } void *Renderer::beginFrame(int width, int height) { m_impl->beginFrame(width, height); return nullptr; } void Renderer::endFrame() { m_impl->endFrame(); } void Renderer::clearDepth() { m_impl->clearDepth(); }
[ "ousttrue@gmail.com" ]
ousttrue@gmail.com
aa0d411d0010a213c4a57c7582d2451865638d44
86dae49990a297d199ea2c8e47cb61336b1ca81e
/c/2020 tasks/3.7 NOI OnLine/bubble/bubble.cpp
3b8e0ea7b1d7d7ed02591444f9bd32ac775ceecf
[]
no_license
yingziyu-llt/OI
7cc88f6537df0675b60718da73b8407bdaeb5f90
c8030807fe46b27e431687d5ff050f2f74616bc0
refs/heads/main
2023-04-04T03:59:22.255818
2021-04-11T10:15:03
2021-04-11T10:15:03
354,771,118
0
0
null
null
null
null
UTF-8
C++
false
false
694
cpp
#include<stdio.h> #include<algorithm> #include<string.h> using namespace std; int a[2000]; int b[2000]; int main() { int n,m; freopen("bubble.in","r",stdin); freopen("bubble.out","w",stdout); scanf("%d%d",&n,&m); for(int i = 1;i <= n;i++) scanf("%d",&a[i]); for(int i = 1 ;i <= m;i++) { int t,c; scanf("%d%d",&t,&c); if(t == 1) swap(a[c],a[c + 1]); else { memcpy(b,a,sizeof(a)); for(int i = 1;i <= c;i++) for(int j = 1;j < n;j++) if(b[j] > b[j + 1]) swap(b[j],b[j + 1]); int ans = 0; for(int i = 1;i <= n;i++) for(int j = i + 1;j <= n;j++) if(b[j] < b[i]) ans++; printf("%d\n",ans); } } return 0; }
[ "linletian1@sina.com" ]
linletian1@sina.com
4fa0fe5910b5816de06624c47c5d26cb0e1fa7e2
af28900bba69ae238baf6851ccc2ab2ca8978c75
/Polymorphic Malware/Polymorphic_Engine.cpp
72689da65df9be3aaef47420f9873c3f48b7f684
[]
no_license
tmd2018/Polymorphic-Engine-
dcdc4acf75615b114045201ba4c8c455de7140a3
3061c3af63d8f86b4862fd96204da9db8096249e
refs/heads/master
2020-05-31T21:28:12.040614
2017-05-12T15:33:50
2017-05-12T15:33:50
null
0
0
null
null
null
null
UTF-8
C++
false
false
12,233
cpp
// Calc.cpp : Defines the entry point for the console application. // #include <iostream> #include <cstdlib> #include <ctime> #include <cstring> #include <string> #include <cctype> #include <sstream> #include<fstream> #include<ostream> using namespace std; void Encrypt(string&, int key); string Decrypt(string strTarget, int key); string preObfuscation(string line); string insert_assembly(string s); string scrambler(string s); int main(int argc, char* argv[]) { //float add = addition(1.3,3.4); string line,payload,strTarget; int iSecret, iGuess, iSeed; //payload = "Payload.cpp"; while(1) { cout<<"Enter a to encrypt or b run, c to exit"; char ch; cin>>ch; switch(ch) { case 'a' : { cin>>payload; ifstream myfile_in(payload.c_str()); //ofstream myfile_out ("Pay.cpp"); /* initialize random seed: */ iSeed = time(NULL); srand(iSeed); /* generate secret number between 1 and 10: */ iSecret = rand() % 10 + 1; //stringstream ss; //ss<<iSecret; //strTarget+=string(ss.str())+'\n'; Label: if (myfile_in.is_open() ) { while ( getline (myfile_in,line) ) { strTarget+= preObfuscation(line) + '\n'; } } strTarget+="EOF \n"; ifstream assembly_functions("assembly_functions.h"); if (assembly_functions.is_open() ) { string lin1; while ( getline (assembly_functions,lin1) ) { strTarget+= lin1+'\n'; } } strTarget = insert_assembly(strTarget); Encrypt(strTarget, iSecret); ofstream myfile_out("resource.h"); myfile_out<<strTarget; ofstream myfile_out1("testing.cpp"); myfile_out1<<Decrypt(strTarget,iSecret); cout<<"File Encrypted!! Check testing.cpp"; break; } case 'b' : { ofstream fileout("Payload.cpp"); if(fileout.is_open()) { fileout<<Decrypt(strTarget,iSecret); } cout<<Decrypt(strTarget,iSecret); break; } case 'c' : { return 0; } } } //cout << "Encrypted: " << strTarget << endl; //cout << "Decrypted: " << Decrypt(strTarget,iSecret) << endl; return 0; } void Encrypt(string &strTarget, int key) { int len = strTarget.length(); char a; string strFinal(strTarget); for (int i = 0; i <= (len-1); i++) { a = strTarget.at(i); int b = (int)a; //get the ASCII value of 'a' b += key; //Mulitply the ASCII value by 2 if (b > 254) { b = 254; } a = (char)b; //Set the new ASCII value back into the char strFinal.insert(i , 1, a); //Insert the new Character back into the string } string strEncrypted(strFinal, 0, len); strTarget = strEncrypted; } string Decrypt(string strTarget, int key) { int len = strTarget.length(); char a; string strFinal(strTarget); for (int i = 0; i <= (len-1); i++) { a = strTarget.at(i); int b = (int)a; b -= key; a = (char)b; strFinal.insert(i, 1, a); } string strDecrypted(strFinal, 0, len); return strDecrypted; } string preObfuscation(string line) { string newLine; if(line.find("main()")!=string::npos) { newLine+="void addition(float arg1, float arg2); \n void subtraction(float arg1, float arg2); \n void multiplication(float arg1, float arg2); \n void division(float arg1, float arg2); \n"+line + '\n'; } else if(line.find("for")!=string::npos) { newLine="//for loop \n"+line; } else if(line.find("while")!=string::npos) { newLine="//while loop \n"+line; } else if(line.find("if")!=string::npos) { newLine="//condition \n"+line; } else if(line.find("}")!=string::npos) { newLine="//end of loop or block \n"+line; } else if(line.find("{")!=string::npos) { newLine=line+"//begin of loop or block \n"; } else { newLine = line; } return newLine; } string insert_assembly(string s) { stringstream ss(s.c_str()); ostringstream ss1; string line,newString; int i=0; bool flag = false; int iSeed; int loop = 0; int j=0; if(ss!=NULL) { while(getline(ss,line)) { if(line.find("}")!=string::npos && flag==true) { i--; if(i<1) { flag=false; } } if(line.find("main")!=string::npos) { flag=true; newString+=line+'\n'; continue; } else if(line.find("{")!=string::npos) { i++; newString+=line+'\n'; continue; } else if(line.find("if")!=string::npos||line.find("for")!=string::npos||line.find("while")!=string::npos) { loop++; newString+=line+'\n'; continue; } else if(line.find("EOF")!=string::npos) { flag=false; } else if(i>0&&flag==true) { if(loop==0||line.find("condition")!=string::npos) { /*float arg1 = rand()/rand(); float arg2 = rand()/rand(); ss1<<arg1<<","<<arg2;*/ switch((j%4)+1) { case 1: newString+="addition(4.5,9.5);" + line+'\n'; break; case 2: newString+="subtraction(9.5,4.5);" + line+'\n'; break; case 3: newString+="multiplication(9,4.5);"+line+'\n'; break; case 4: newString+="division(9,4.5);"+line+'\n'; break; default: newString+=line+'\n'; } } else { newString+=line+'\n'; if(loop>0) { loop--; } } } else { newString+=line+'\n'; } } return newString; } } string insert_labels(string s) { stringstream ss(s.c_str()); ostringstream ss1; string line,newString; int i=0; bool flag = false; int iSeed; int loop = 0; int j=0; if(ss!=NULL) { while(getline(ss,line)) { if(line.find("}")!=string::npos && flag==true) { i--; if(i<1) { flag=false; } } if(line.find("main")!=string::npos) { flag=true; newString+=line+'\n'; continue; } else if(line.find("{")!=string::npos) { i++; newString+=line+'\n'; continue; } else if(line.find("if")!=string::npos||line.find("for")!=string::npos||line.find("while")!=string::npos) { loop++; newString+=line+'\n'; continue; } else if(line.find("EOF")!=string::npos) { flag=false; } else if(i>0&&flag==true) { if(loop==0||line.find("condition")!=string::npos) { /*float arg1 = rand()/rand(); float arg2 = rand()/rand(); ss1<<arg1<<","<<arg2;*/ switch((j%4)+1) { case 1: newString+="addition(4.5,9.5);" + line+'\n'; break; case 2: newString+="subtraction(9.5,4.5);" + line+'\n'; break; case 3: newString+="multiplication(9,4.5);"+line+'\n'; break; case 4: newString+="division(9,4.5);"+line+'\n'; break; default: newString+=line+'\n'; } } else { newString+=line+'\n'; if(loop>0) { loop--; } } } else { newString+=line+'\n'; } } return newString; } } string scrambler(string s) { stringstream ss(s.c_str()); ostringstream ss1; string line,newString; int i=0; bool flag = false; int iSeed; int loop = 0; int j=0; if(ss!=NULL) { while(getline(ss,line)) { if(line.find("}")!=string::npos && flag==true) { i--; if(i<1) { flag=false; } } if(line.find("main")!=string::npos) { flag=true; newString+=line+'\n'; continue; } else if(line.find("{")!=string::npos) { i++; newString+=line+'\n'; continue; } else if(line.find("if")!=string::npos||line.find("for")!=string::npos||line.find("while")!=string::npos) { loop++; newString+=line+'\n'; continue; } else if(line.find("EOF")!=string::npos) { flag=false; } else if(i>0&&flag==true) { if(loop==0||line.find("condition")!=string::npos) { /*float arg1 = rand()/rand(); float arg2 = rand()/rand(); ss1<<arg1<<","<<arg2;*/ switch((j%4)+1) { case 1: newString+="addition(4.5,9.5);" + line+'\n'; break; case 2: newString+="subtraction(9.5,4.5);" + line+'\n'; break; case 3: newString+="multiplication(9,4.5);"+line+'\n'; break; case 4: newString+="division(9,4.5);"+line+'\n'; break; default: newString+=line+'\n'; } } else { newString+=line+'\n'; if(loop>0) { loop--; } } } else { newString+=line+'\n'; } } return newString; } }
[ "szm0093@auburn.edu" ]
szm0093@auburn.edu
ae0e7a1cad975c31088c37c4fcd80b04d4a469be
370881312084d8d2ce0f9c8dce147b81a3a9a923
/Game_Code/Code/CryEngine/CryAction/FlowSystem/Nodes/PlaySequenceNode.cpp
6640b255f9ee1ac779fa097841d0a5b05f4bfc79
[]
no_license
ShadowShell/QuestDrake
3030c396cd691be96819eec0f0f376eb8c64ac89
9be472a977882df97612efb9c18404a5d43e76f5
refs/heads/master
2016-09-05T20:23:14.165400
2015-03-06T14:17:22
2015-03-06T14:17:22
31,463,818
3
2
null
2015-02-28T18:26:22
2015-02-28T13:45:52
C++
UTF-8
C++
false
false
14,669
cpp
#include "StdAfx.h" #include <ISystem.h> #include <ICryAnimation.h> #include <IMovieSystem.h> #include <IViewSystem.h> #include "CryActionCVars.h" #include "FlowBaseNode.h" class CPlaySequence_Node : public CFlowBaseNode<eNCT_Instanced>, public IMovieListener { enum INPUTS { EIP_Sequence, EIP_Start, EIP_Pause, EIP_Stop, EIP_Precache, EIP_BreakOnStop, EIP_BlendPosSpeed, EIP_BlendRotSpeed, EIP_PerformBlendOut, EIP_StartTime, EIP_PlaySpeed, EIP_JumpToTime, EIP_TriggerJumpToTime, EIP_SequenceId, // deprecated EIP_TriggerJumpToEnd, }; enum OUTPUTS { EOP_Started = 0, EOP_Done, EOP_Finished, EOP_Aborted, EOP_SequenceTime, EOP_CurrentSpeed, }; typedef enum { PS_Stopped, PS_Playing, PS_Last } EPlayingState; _smart_ptr<IAnimSequence> m_pSequence; SActivationInfo m_actInfo; EPlayingState m_playingState; float m_currentTime; float m_currentSpeed; public: CPlaySequence_Node( SActivationInfo * pActInfo ) { m_pSequence = 0; m_actInfo = *pActInfo; m_playingState = PS_Stopped; m_currentSpeed = 0.0f; m_currentTime = 0.0f; }; virtual void GetMemoryUsage(ICrySizer * s) const { s->Add(*this); } ~CPlaySequence_Node() { if (m_pSequence) { IMovieSystem *pMovieSystem = gEnv->pMovieSystem; if (pMovieSystem) { pMovieSystem->RemoveMovieListener(m_pSequence, this); } } }; IFlowNodePtr Clone( SActivationInfo * pActInfo ) { return new CPlaySequence_Node(pActInfo); } virtual void Serialize(SActivationInfo *pActInfo, TSerialize ser) { ser.BeginGroup("Local"); if (ser.IsWriting()) { ser.EnumValue("m_playingState", m_playingState, PS_Stopped, PS_Last); ser.Value("curTime", m_currentTime); ser.Value("m_playSpeed", m_currentSpeed); bool bPaused = m_pSequence ? m_pSequence->IsPaused() : false; ser.Value("m_paused", bPaused); } else { EPlayingState playingState; { // for backward compatibility - TODO: remove bool playing = false; ser.Value("m_bPlaying", playing); playingState = playing ? PS_Playing : PS_Stopped; /// end remove } ser.EnumValue("m_playingState", playingState, PS_Stopped, PS_Last); ser.Value("curTime", m_currentTime); ser.Value("m_playSpeed", m_currentSpeed); bool bPaused; ser.Value("m_paused", bPaused); if (playingState == PS_Playing) { // restart sequence, possibly at the last frame StartSequence(pActInfo, m_currentTime, false); if (m_pSequence && bPaused) { m_pSequence->Pause(); } } else { // this unregisters only! because all sequences have been stopped already // by MovieSystem's Reset in GameSerialize.cpp StopSequence(pActInfo, true); } } ser.EndGroup(); } virtual void GetConfiguration( SFlowNodeConfig &config ) { static const SInputPortConfig in_config[] = { InputPortConfig<string>( "seq_Sequence_File",_HELP("Name of the Sequence"), _HELP("Sequence") ), InputPortConfig_Void( "Trigger",_HELP("Starts the sequence"), _HELP("StartTrigger") ), InputPortConfig_Void( "Pause", _HELP("Pauses the sequence"), _HELP("PauseTrigger") ), InputPortConfig_Void( "Stop", _HELP("Stops the sequence"), _HELP("StopTrigger") ), InputPortConfig_Void( "Precache",_HELP("Precache keys that start in the first seconds of the animation. (Solves streaming issues)"), _HELP("PrecacheTrigger") ), InputPortConfig<bool>( "BreakOnStop", false, _HELP("If set to 'true', stopping the sequence doesn't jump to end.") ), InputPortConfig<float>("BlendPosSpeed", 0.0f, _HELP("Speed at which position gets blended into animation.") ), InputPortConfig<float>("BlendRotSpeed", 0.0f, _HELP("Speed at which rotation gets blended into animation.") ), InputPortConfig<bool>( "PerformBlendOut", false, _HELP("If set to 'true' the cutscene will blend out after it has finished to the new view (please reposition player when 'Started' happens).") ), InputPortConfig<float>("StartTime", 0.0f, _HELP("Start time from which the sequence'll begin playing.") ), InputPortConfig<float>("PlaySpeed", 1.0f, _HELP("Speed that this sequence plays at. 1.0 = normal speed, 0.5 = half speed, 2.0 = double speed.") ), InputPortConfig<float>("JumpToTime", 0.0f, _HELP("Jump to a specific time in the sequence.") ), InputPortConfig_Void("TriggerJumpToTime", _HELP("Trigger the animation to jump to 'JumpToTime' seconds.") ), InputPortConfig<int>("seqid_SequenceId", 0, _HELP("ID of the Sequence"), _HELP("SequenceId (DEPRECATED)") ), InputPortConfig_Void("TriggerJumpToEnd", _HELP("Trigger the animation to jump to the end of the sequence.") ), {0} }; static const SOutputPortConfig out_config[] = { OutputPortConfig_Void("Started", _HELP("Triggered when sequence is started") ), OutputPortConfig_Void("Done", _HELP("Triggered when sequence is stopped [either via StopTrigger or aborted via Code]"), _HELP("Done") ), OutputPortConfig_Void("Finished", _HELP("Triggered when sequence finished normally") ), OutputPortConfig_Void("Aborted", _HELP("Triggered when sequence is aborted (Stopped and BreakOnStop true or via Code)") ), OutputPortConfig_Void("SequenceTime", _HELP("Current time of the sequence") ), OutputPortConfig_Void("CurrentSpeed", _HELP("Speed at which the sequence is being played") ), {0} }; config.sDescription = _HELP( "Plays a Trackview Sequence" ); config.pInputPorts = in_config; config.pOutputPorts = out_config; config.SetCategory(EFLN_APPROVED); } virtual void ProcessEvent( EFlowEvent event,SActivationInfo *pActInfo ) { switch (event) { case eFE_Update: { UpdatePermanentOutputs(); if (!gEnv->pMovieSystem || !m_pSequence) pActInfo->pGraph->SetRegularlyUpdated(pActInfo->myID, false); } break; case eFE_Activate: { if (IsPortActive(pActInfo, EIP_Stop)) { bool bWasPlaying = m_playingState == PS_Playing; const bool bLeaveTime = GetPortBool(pActInfo, EIP_BreakOnStop); StopSequence(pActInfo, false, true, bLeaveTime); // we trigger manually, as we unregister before the callback happens if (bWasPlaying) { ActivateOutput(pActInfo, EOP_Done, true); // signal we're done ActivateOutput(pActInfo, EOP_Aborted, true); // signal it's been aborted NotifyEntities(); } } if (IsPortActive(pActInfo, EIP_Start)) { StartSequence(pActInfo, GetPortFloat(pActInfo, EIP_StartTime)); } if (IsPortActive(pActInfo, EIP_Pause)) { PauseSequence(pActInfo); } if (IsPortActive(pActInfo, EIP_Precache)) { PrecacheSequence(pActInfo, GetPortFloat(pActInfo, EIP_StartTime)); } if(IsPortActive(pActInfo, EIP_TriggerJumpToTime)) { if(gEnv->pMovieSystem && m_pSequence) { float time = GetPortFloat(pActInfo, EIP_JumpToTime); time = clamp_tpl(time, m_pSequence->GetTimeRange().start, m_pSequence->GetTimeRange().end); gEnv->pMovieSystem->SetPlayingTime(m_pSequence, time); } } else if(IsPortActive(pActInfo, EIP_TriggerJumpToEnd)) { if(gEnv->pMovieSystem && m_pSequence) { float endTime = m_pSequence->GetTimeRange().end; gEnv->pMovieSystem->SetPlayingTime(m_pSequence, endTime); } } if(IsPortActive(pActInfo, EIP_PlaySpeed)) { const float playSpeed = GetPortFloat(pActInfo, EIP_PlaySpeed); if(gEnv->pMovieSystem) { gEnv->pMovieSystem->SetPlayingSpeed(m_pSequence, playSpeed); } } break; } case eFE_Initialize: { StopSequence(pActInfo); } break; }; }; virtual void OnMovieEvent(IMovieListener::EMovieEvent event, IAnimSequence* pSequence) { if (pSequence && pSequence == m_pSequence) { if (event == IMovieListener::eMovieEvent_Started) { m_playingState = PS_Playing; } else if (event == IMovieListener::eMovieEvent_Stopped) { ActivateOutput(&m_actInfo, EOP_Done, true); ActivateOutput(&m_actInfo, EOP_Finished, true); m_playingState = PS_Stopped; NotifyEntities(); SequenceStopped(); } else if (event == IMovieListener::eMovieEvent_Aborted) { SequenceAborted(); } else if (event == IMovieListener::eMovieEvent_Updated) { m_currentTime = gEnv->pMovieSystem->GetPlayingTime(pSequence); m_currentSpeed = gEnv->pMovieSystem->GetPlayingSpeed(pSequence); } } } protected: void SequenceAborted() { ActivateOutput(&m_actInfo, EOP_Done, true); ActivateOutput(&m_actInfo, EOP_Aborted, true); m_playingState = PS_Stopped; NotifyEntities(); SequenceStopped(); } void SequenceStopped() { UpdatePermanentOutputs(); if (gEnv->pMovieSystem && m_pSequence) { gEnv->pMovieSystem->RemoveMovieListener(m_pSequence, this); } m_pSequence = 0; m_actInfo.pGraph->SetRegularlyUpdated(m_actInfo.myID, false); } void PrecacheSequence(SActivationInfo* pActInfo, float startTime = 0.0f) { IMovieSystem* movieSys = gEnv->pMovieSystem; if (movieSys) { IAnimSequence* pSequence = movieSys->FindSequence(GetPortString(pActInfo, EIP_Sequence)); if (pSequence == NULL) pSequence = movieSys->FindSequenceById((uint32)GetPortInt(pActInfo, EIP_SequenceId)); if (pSequence) { pSequence->PrecacheData(startTime); } } } void StopSequence(SActivationInfo* pActInfo, bool bUnRegisterOnly=false, bool bAbort=false, bool bLeaveTime=false) { IMovieSystem *const pMovieSystem = gEnv->pMovieSystem; if (pMovieSystem && m_pSequence) { // we remove first to NOT get notified! pMovieSystem->RemoveMovieListener(m_pSequence, this); if (!bUnRegisterOnly && pMovieSystem->IsPlaying(m_pSequence)) { if (bAbort) // stops sequence and leaves it at current position { pMovieSystem->AbortSequence(m_pSequence, bLeaveTime); } else { pMovieSystem->StopSequence(m_pSequence); } } SequenceStopped(); } } void UpdatePermanentOutputs() { if(gEnv->pMovieSystem && m_pSequence) { const float currentTime = gEnv->pMovieSystem->GetPlayingTime(m_pSequence); const float currentSpeed = gEnv->pMovieSystem->GetPlayingSpeed(m_pSequence); ActivateOutput(&m_actInfo, EOP_SequenceTime, currentTime); ActivateOutput(&m_actInfo, EOP_CurrentSpeed, currentSpeed); } } void StartSequence(SActivationInfo* pActInfo, float curTime = 0.0f, bool bNotifyStarted = true) { IMovieSystem *pMovieSystem = gEnv->pMovieSystem; if (!pMovieSystem) { return; } IAnimSequence *pSequence = pMovieSystem->FindSequence(GetPortString(pActInfo, EIP_Sequence)); if (pSequence == NULL) { pSequence = pMovieSystem->FindSequenceById((uint32)GetPortInt(pActInfo, EIP_SequenceId)); } // If sequence was changed in the meantime, stop old sequence first if (m_pSequence && pSequence != m_pSequence) { pMovieSystem->RemoveMovieListener(m_pSequence, this); pMovieSystem->StopSequence(m_pSequence); } m_pSequence = pSequence; if (m_pSequence) { if (m_pSequence->IsPaused()) { m_pSequence->Resume(); return; } m_pSequence->Resume(); pMovieSystem->AddMovieListener(m_pSequence, this); pMovieSystem->PlaySequence(m_pSequence, NULL, true, false); pMovieSystem->SetPlayingTime(m_pSequence, curTime); // set blend parameters only for tracks with Director Node, having camera track inside IViewSystem* pViewSystem = CCryAction::GetCryAction()->GetIViewSystem(); if (pViewSystem && m_pSequence->GetActiveDirector()) { bool bDirectorNodeHasCameraTrack=false; IAnimNode *pDirectorNode = m_pSequence->GetActiveDirector(); if (pDirectorNode) { for (int trackId=0;trackId<pDirectorNode->GetTrackCount();++trackId) { IAnimTrack *pTrack = pDirectorNode->GetTrackByIndex(trackId); if (pTrack && pTrack->GetParameterType() == eAnimParamType_Camera && pTrack->GetNumKeys() > 0) { bDirectorNodeHasCameraTrack=true; break; } } } if (bDirectorNodeHasCameraTrack) { float blendPosSpeed = GetPortFloat(pActInfo, EIP_BlendPosSpeed); float blendRotSpeed = GetPortFloat(pActInfo, EIP_BlendRotSpeed); bool performBlendOut = GetPortBool(pActInfo, EIP_PerformBlendOut); pViewSystem->SetBlendParams(blendPosSpeed, blendRotSpeed, performBlendOut); } } if (bNotifyStarted) { ActivateOutput(pActInfo, EOP_Started, true); } pActInfo->pGraph->SetRegularlyUpdated(pActInfo->myID, true); } else { // sequence was not found -> hint GameWarning("[flow] Animations:PlaySequence: Sequence \"%s\" not found", GetPortString(pActInfo, 0).c_str()); // maybe we should trigger the output, but if sequence is not found this should be an error } NotifyEntities(); // this can happens when a timedemo is being recorded and the sequence is flagged as CUTSCENE if (m_pSequence && m_playingState==PS_Playing && !pMovieSystem->IsPlaying( m_pSequence)) { SequenceAborted(); } if(CCryActionCVars::Get().g_disableSequencePlayback) { if(gEnv->pMovieSystem && m_pSequence) { float endTime = m_pSequence->GetTimeRange().end; gEnv->pMovieSystem->SetPlayingTime(m_pSequence, endTime); } } } void PauseSequence(SActivationInfo* pActInfo) { if (m_playingState != PS_Playing) { return; } IMovieSystem *pMovieSys = gEnv->pMovieSystem; if (!pMovieSys) { return; } if (m_pSequence) { m_pSequence->Pause(); } } void NotifyEntityScript(IEntity* pEntity) { IScriptTable *pEntityScript = pEntity->GetScriptTable(); if(pEntityScript) { if(m_playingState == PS_Playing && pEntityScript->HaveValue("OnSequenceStart")) { Script::CallMethod(pEntityScript, "OnSequenceStart"); } else if(m_playingState == PS_Stopped && pEntityScript->HaveValue("OnSequenceStop")) { Script::CallMethod(pEntityScript, "OnSequenceStop"); } } } void NotifyEntities() { IMovieSystem *pMovieSystem = gEnv->pMovieSystem; if (!pMovieSystem || !m_pSequence) { return; } int nodeCount = m_pSequence->GetNodeCount(); for(int i=0; i<nodeCount; ++i) { IAnimNode* pNode = m_pSequence->GetNode(i); if(pNode) { IEntity* pEntity = pNode->GetEntity(); if(pEntity) { NotifyEntityScript(pEntity); } if(EntityGUID* guid = pNode->GetEntityGuid()) { EntityId id = gEnv->pEntitySystem->FindEntityByGuid(*guid); if(id != 0) { IEntity* pEntity2 = gEnv->pEntitySystem->GetEntity(id); if(pEntity2) { NotifyEntityScript(pEntity2); } } } } } } }; REGISTER_FLOW_NODE( "Animations:PlaySequence", CPlaySequence_Node );
[ "cloudcodexmain@gmail.com" ]
cloudcodexmain@gmail.com
610b16e15df3731843ef78999e985522237a8365
220846e017a9992e596bd1ea806d527e3aeea243
/79_Word_Search.cpp
a5cb29e5ac66481ecfd1fe0e20310c24639cfb08
[]
no_license
anzhe-yang/Leetcode
bfa443b7a74ddbd441348c364ee00004173ddd86
fe9eb16136035f25f31bddb37c6b4884cd7f6904
refs/heads/master
2020-04-08T14:49:04.781848
2019-10-25T02:39:22
2019-10-25T02:39:22
159,453,173
0
0
null
null
null
null
UTF-8
C++
false
false
1,894
cpp
/** 问题描述: * 给定一个 2D 的字母数组,返回单词是否存在于这个数组中。 * 该单词可以由顺序相邻的单元的字母构成,其中“相邻”单元是水平或垂直相邻的单元。 * 相同的字母单元格不得多次使用。 */ #include <iostream> #include <vector> #include <string> using namespace std; bool exist(vector<vector<char>>& board, string word, int x, int y, int pos, int m, int n, int len) { char cur = board[x][y]; bool res = false; if (cur != word[pos]) return false; if (pos == len-1) return true; board[x][y] = '*'; if(x > 0) res = exist(board, word, x-1, y, pos+1, m, n, len); if(!res && x < m-1) res = exist(board, word, x+1, y, pos+1, m, n, len); if(!res && y > 0) res = exist(board, word, x, y-1, pos+1, m, n, len); if(!res && y < n-1) res = exist(board, word, x, y+1, pos+1, m, n, len); board[x][y] = cur; return res; } bool exist(vector<vector<char>>& board, string word) { /* 回溯法。 首先找到第一个词,之后利用循环函数验证每个词cur是否等于word[pos]。 之后分别从左、右、上、下四个位置找下一个词。 都找到了,则pos=len-1,则返回。 有一个没找到就返回false。 */ int m = board.size(); int n = board[0].size(); int len = word.length(); for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { if (exist(board, word, i, j, 0, m, n, len)) { return true; } } } return false; } int main(int argc, char const *argv[]) { vector<vector<char>> board{ {'A','B','C','E'}, {'S','F','C','S'}, {'A','D','E','E'} }; string word = "ABCCED"; cout << boolalpha << exist(board, word); return 0; }
[ "anzhe_yang@yanganzhedeMacBook-Pro.local" ]
anzhe_yang@yanganzhedeMacBook-Pro.local
6a2d9538d823f77e96bda5d4e459a5fdd25bca3b
b0dd7779c225971e71ae12c1093dc75ed9889921
/libs/math/test/test_rational_instances/test_rational_ldouble2.cpp
49fdce22061a2e30762e6330d6a2052f54002db2
[ "LicenseRef-scancode-warranty-disclaimer", "BSL-1.0" ]
permissive
blackberry/Boost
6e653cd91a7806855a162347a5aeebd2a8c055a2
fc90c3fde129c62565c023f091eddc4a7ed9902b
refs/heads/1_48_0-gnu
2021-01-15T14:31:33.706351
2013-06-25T16:02:41
2013-06-25T16:02:41
2,599,411
244
154
BSL-1.0
2018-10-13T18:35:09
2011-10-18T14:25:18
C++
UTF-8
C++
false
false
338
cpp
// (C) Copyright John Maddock 2006-7. // Use, modification and distribution are subject to the // Boost Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #include "test_rational.hpp" template void do_test_spots<long double, int>(long double, int);
[ "tvaneerd@rim.com" ]
tvaneerd@rim.com
22e017201d1cf23d831732fe07a83214bcaf4f3b
ae4d9cf742b9f6e5024bcd5bdf4b4473558da9e3
/_PSmine/PS모음/boj/10992.cpp
ec396174b0a36e044be133e44dd64881de9bc486
[]
no_license
son0179/ttt
b6d171141e0b7894258cfb367023de62cdc9dd19
a5153b0170c0df156c96d9be85b21d73f1f2e21e
refs/heads/master
2023-02-09T22:01:57.658467
2021-01-05T09:14:52
2021-01-05T09:14:52
200,059,589
1
0
null
null
null
null
UTF-8
C++
false
false
377
cpp
#include<stdio.h> int main() { int n,a,b; scanf("%d",&n); if(n==1) { printf("*"); } else { for(int i=1; i<n; i++) { a=1; b=1; while(a<=n-i) { printf(" "); a++; } printf("*"); if(i!=1) { while(b<=(i-1)*2-1) { printf(" "); b++; } printf("*"); } printf("\n"); } for(int i=1; i<n*2; i++) { printf("*"); } } }
[ "starson2648@gmail.com" ]
starson2648@gmail.com
92fde826bf54f34327539f61af4972bf3d8bb83b
560b0fe26827a16eb6ffd16f5b5e3e28844158ba
/cpp/core/mailiverse/mail/cache/Info.cpp
c5b553195b4d17fd6ac2461e1de6890a08e46d95
[]
no_license
timprepscius/mailiverse
855e76b4d685305e426e6db9f97d15d8e86cf4c3
9c7fe87d9723aa81015598a29b4fe1bb61e226ac
refs/heads/master
2021-01-15T14:29:07.506168
2014-01-19T20:11:13
2014-01-19T20:11:13
11,405,168
2
1
null
null
null
null
UTF-8
C++
false
false
243
cpp
/** * Author: Timothy Prepscius * License: BSD + keep my name in the code! */ #include "Info.h" using namespace mailiverse::mail::cache; Info::Info() : cacheVersion(Version::NONE), localVersion(Version::NONE) { } Info::~Info() { }
[ "tprepscius" ]
tprepscius
8b0442ca06df5883727451b0e6222dd8549cb9dc
4dda91e22ad7ea1fbfe4a8065865a380fdb9bda5
/大作业22.cpp
a4df1575f775b11185316405cb9c942afb70b000
[]
no_license
glj-27/github
1d4e49543bc39ef9d2f65418d8f70e463b4ecdca
c323b6404c6aa04a0e6e5b9fc2ee265837954be1
refs/heads/master
2020-07-10T10:03:26.814252
2019-08-25T03:00:19
2019-08-25T03:00:19
204,236,443
0
0
null
null
null
null
GB18030
C++
false
false
15,723
cpp
#include<iostream> #include<cstdio> #include<cstring> #include <conio.h> #include<stdlib.h> #include<fstream> #include<algorithm> using namespace std; class people { public: char name[20]; int birthday[3]; char phone[20]; char email[30]; char relationship; char mm[30]; }; int num;people student[100]; bool compare(people a , people b) { return strcmp( a.name ,b.name ) < 0; } class menu :public people { public: void add() { cout << "*****录入个人信息*****" << endl; cout << "*请输入他的姓名:"; cin >> student[num].name; cout << endl; cout << "*请输入他与你的关系(1.同学,2.同事,3.亲戚):"; cin >> student[num].relationship; cout << endl; if (student[num].relationship == '1'){cout << "*请输入你们的学校:"; cin >> student[num].mm; cout << endl;} else if (student[num].relationship == '2'){cout << "*请输入你们的单位:"; cin >> student[num].mm; cout << endl;} else if (student[num].relationship == '3'){cout << "*请输入你对他的称呼:"; cin >> student[num].mm; cout << endl;} cout << "*请输入他的生日( 年 月 日):"; cin >> student[num].birthday[0] >> student[num].birthday[1] >> student[num].birthday[2]; cout << endl; cout << "*请输入他的电话:"; cin >> student[num].phone; cout << endl; cout << "*请输入他的邮箱:"; cin >> student[num].email; cout << endl << "**********************"<<endl; } void modification() { int n; string m;int l=0; system("cls"); cout << "******修改个人信息*****" << endl; if (num != 0) { cout << "*要修改的人姓名:" ; cin >> m; for (n = 0; n < num; n++) { if (student[n].name == m) { l=1; int i; cout << "*你要修改(1.电话;2.邮箱; 3.关系; ):"; cin >> i; switch (i) { case 1: char p[20]; cout << "*请输入要修改的电话:"; cin >> p; strcpy (student[n].phone,p); cout<<endl<<"*修改完成!"<<endl; break; case 2: char e[30]; cout << "*请输入要修改的邮箱:"; cin >> e; strcpy (student[n].email,e); cout<<endl<<"*修改完成!"<<endl; break; case 3: char r; cout<< "*请输入要修改为什么关系(1.同学;2.同事;3.亲戚;):"; cin >> r; student[n].relationship=r; char m[30]; if(student[n].relationship=='1') { cout<<"输入要修改为什么学校:"; cin>>m; strcpy(student[n].mm,m); } else if(student[n].relationship=='2') { cout<<"输入要修改为什么单位:"; cin>>m; strcpy(student[n].mm,m); } else if(student[n].relationship=='3') { cout<<"输入要修改为什么称呼:"; cin>>m; strcpy(student[n].mm,m); } cout<<endl<<"*修改完成!"<<endl; break ; } } } } else cout << "*无记录!" << endl; if(l==0)cout<< "*无记录!" << endl; cout << "**********************"<<endl; } void deletes() { system("cls"); cout << "******删除个人信息*****" << endl; int i=0; if (num != 0) { cout << "*请输入要删除人的姓名:"; int n; string m; cin>>m; for (n = 0; n < num; n++) { if(student[n].name==m) { i=1; cout << "*姓名:" << student[n].name << endl; cout << "*生日:" << student[n].birthday[0] << "/" << student[n].birthday[1] << "/" << student[n].birthday[2] << endl; cout << "*电话:" << student[n].phone << endl; cout << "*邮箱:" << student[n].email << endl; cout << "*关系:" ; if(student[n].relationship=='1') cout<<"同学"<< endl<< "*学校:"<< student[n].mm << endl<< endl; else if(student[n].relationship=='2') cout<<"同事"<< endl<< "*单位:"<< student[n].mm << endl<< endl; else if(student[n].relationship=='3') cout<<"亲戚"<< endl<< "*称呼:"<<student[n].mm << endl<< endl; cout << "*确定要删除吗?(y/n):"; char x;cin>>x; if (x == 'y') { for(n;n<num;n++) { strcpy(student[n].name,student[n+1].name); student[n].birthday[0] = student[n+1].birthday[0]; student[n].birthday[1] = student[n+1].birthday[1]; student[n].birthday[2] = student[n+1].birthday[2]; strcpy(student[n].phone,student[n+1].phone); strcpy(student[n].email,student[n+1].email); student[n].relationship=student[n+1].relationship; strcpy(student[n].mm,student[n+1].mm); } cout<<endl<<"*删除完成!"<<endl; num--; } else if(x == 'n') { cout<<endl<<"*未删除!"; } } } } else cout << "*无记录!" << endl; if(i==0)cout<< "*无记录!" << endl; cout << "**********************"<<endl; } void ashow() { system("cls"); cout << "******列出全部个人信息*****" << endl; int n; if (num != 0) for (n = 0; n < num; n++) { cout << "*姓名:" << student[n].name << endl; cout << "*生日:" << student[n].birthday[0] << "/" << student[n].birthday[1] << "/" << student[n].birthday[2] << endl; cout << "*电话:" << student[n].phone << endl; cout << "*邮箱:" << student[n].email << endl; cout << "*关系:" ; if(student[n].relationship=='1') cout<<"同学"<< endl<< "*学校:"<< student[n].mm << endl<< endl; else if(student[n].relationship=='2') cout<<"同事"<< endl<< "*单位:"<< student[n].mm << endl<< endl; else if(student[n].relationship=='3') cout<<"亲戚"<< endl<< "*称呼:"<<student[n].mm << endl<< endl; } else cout << "*无记录!" << endl; cout << "****************************"<<endl; } void bshow() { system("cls"); cout << "******列出同学的个人信息*****" << endl; int n;int i=0; if (num != 0) for (n = 0; n < num; n++) { if (student[n].relationship == '1') { cout << "*姓名:" << student[n].name << endl; cout << "*生日:" << student[n].birthday[0] << "/" << student[n].birthday[1] << "/" << student[n].birthday[2] << endl; cout << "*电话:" << student[n].phone << endl; cout << "*邮箱:" << student[n].email << endl; cout << "*学校:" << student[n].mm << endl; cout <<endl; i=1; } } else cout << "*无记录!" << endl; if(i==0)cout<< "*无记录!" << endl; cout << "*****************************"<<endl; } void cshow() { system("cls"); cout << "******列出同事的个人信息*****" << endl; int n;int i=0; if (num != 0) for (n = 0; n < num; n++) { if (student[n].relationship == '2') { cout << "*姓名:" << student[n].name << endl; cout << "*生日:" << student[n].birthday[0] << "/" << student[n].birthday[1] << "/" << student[n].birthday[2] << endl; cout << "*电话:" << student[n].phone << endl; cout << "*邮箱:" << student[n].email << endl; cout << "*单位:" << student[n].mm << endl; cout <<endl; i=1; } } else cout << "*无记录!" << endl; if(i==0)cout<< "*无记录!" << endl; cout << "*****************************"<<endl; } void dshow() { system("cls"); int n;int i=0; cout << "******列出亲戚的个人信息*****" << endl; if (num != 0) for (n = 0; n < num; n++) { if (student[n].relationship == '3') { cout << "*姓名:" << student[n].name << endl; cout << "*生日:" << student[n].birthday[0] << "/" << student[n].birthday[1] << "/" << student[n].birthday[2] << endl; cout << "*电话:" << student[n].phone << endl; cout << "*邮箱:" << student[n].email << endl; cout << "*称呼:" << student[n].mm << endl; cout <<endl; i=1; } } else cout << "*无记录!" << endl; if(i==0)cout<< "*无记录!" << endl; cout << "*****************************"<<endl; } void checkname() { int n; string m;int i=0; system("cls"); cout << "******查找个人信息*****" << endl; if (num != 0) { cout << "*请输入要查找姓名:"; cin >> m; for (n = 0; n < num; n++) { if (student[n].name == m) { cout << "*姓名:" << student[n].name << endl; cout << "*生日:" << student[n].birthday[0] << "/" << student[n].birthday[1] << "/" << student[n].birthday[2] << endl; cout << "*电话:" << student[n].phone << endl; cout << "*邮箱:" << student[n].email << endl; cout << "*关系:"; if(student[n].relationship='1') cout<<"同学"<< endl<< "*学校:"<< student[n].mm << endl<< endl; else if(student[n].relationship='2') cout<<"同事"<< endl<< "*单位:"<< student[n].mm << endl<< endl; else if(student[n].relationship='3') cout<<"亲戚"<< endl<< "*称呼:"<<student[n].mm << endl<< endl; i=1; } } } else cout << "*无记录!" << endl; if(i==0)cout<< "*无记录!" << endl; cout << "**********************"<<endl; } void outfile() { system("cls"); cout << "******将个人信息存入文件*****" << endl; if (num != 0) { fstream outfile; outfile.open( "个人信息管理系统.txt", ios::out|ios::binary ); outfile<<num; for(int n = 0; n < num; n++) { outfile.write( ( char* )&student[n],sizeof( people )) ;} outfile.close() ; cout<<endl<<"*写入文件成功!"<<endl; } else cout << "*无记录!" << endl; cout << "*****************************"<<endl; } void paixu() { system("cls"); cout << "******排序个人信息*****" << endl; sort(student,student+num,compare); for (int n = 0; n < num; n++) { cout << "*姓名:" << student[n].name << endl; cout << "*生日:" << student[n].birthday[0] << "/" << student[n].birthday[1] << "/" << student[n].birthday[2] << endl; cout << "*电话:" << student[n].phone << endl; cout << "*邮箱:" << student[n].email << endl; cout << "*关系:" ; if(student[n].relationship=='1') cout<<"同学"<< endl<< "*学校:"<< student[n].mm << endl<< endl; else if(student[n].relationship=='2') cout<<"同事"<< endl<< "*单位:"<< student[n].mm << endl<< endl; else if(student[n].relationship=='3') cout<<"亲戚"<< endl<< "*称呼:"<<student[n].mm << endl<< endl; } cout << "**********************"<<endl; } void checktime() { system("cls"); cout << "******查找同月出生的个人信息*****" << endl; double m;int x=0; if (num != 0) { cout << "*请输入要查找月份:"; cin >> m; for (int n = 0; n < num; n++) { if (student[n].birthday[1] == m) { cout << "*姓名:" << student[n].name << endl; cout << "*生日:" << student[n].birthday[0] << "/" << student[n].birthday[1] << "/" << student[n].birthday[2] << endl; cout << "*电话:" << student[n].phone << endl; cout << "*邮箱:" << student[n].email << endl; cout << "*关系:"; if(student[n].relationship='1') cout<<"同学"<< endl<< "*学校:"<< student[n].mm << endl<< endl; else if(student[n].relationship='2') cout<<"同事"<< endl<< "*单位:"<< student[n].mm << endl<< endl; else if(student[n].relationship='3') cout<<"亲戚"<< endl<< "*称呼:"<<student[n].mm << endl<< endl; x++; } } } else cout << "*无记录!" << endl; if(x==0)cout<< "*无记录!" << endl; else cout<<"*"<<m<<"月份出生的人数为:"<<x<<"人"<<endl; cout << "**********************************"<<endl; } int runyear(int y)//判断是否是闰年 { return y%4==0&&y%100!=0||y%400==0;//真返回为1,假为0 } int daysOfMonth(int y,int m) { int day[12]={31,28,31,30,31,30,31,31,30,31,30,31}; if(m!=2) return day[m-1]; else return 28+runyear(y); } int daysOfDate(int y,int m,int d)//计算一共的天数 { int days=d; for(int a=1;a<y;a++)//计算年 days+=365+runyear(a); for(int b=1;b<m;b++)//计算月 days+=daysOfMonth(y,b); return days; } void checkdate() { system("cls"); cout << "******查找五天内过生日的个人信息*****" << endl; int date[3];int i=0; cout<<"*请输入要查找的日期(年 月 日):"; cin>>date[0]>>date[1]>>date[2]; int day1=daysOfDate(date[0],date[1],date[2]); cout << "*五天内过生日的人如下:"<<endl; for(int n;n<num;n++) { int day2=daysOfDate(date[0],student[n].birthday[1],student[n].birthday[2]); if(day2-day1>=0&&day2-day1<5) { cout << "*姓名:" << student[n].name << endl; cout << "*生日:" << student[n].birthday[0] << "/" << student[n].birthday[1] << "/" << student[n].birthday[2] << endl; cout << "*电话:" << student[n].phone << endl; cout << "*邮箱:" << student[n].email << endl; cout << "*关系:"; if(student[n].relationship='1') cout<<"同学"<< endl<< "*学校:"<< student[n].mm << endl<< endl; else if(student[n].relationship='2') cout<<"同事"<< endl<< "*单位:"<< student[n].mm << endl<< endl; else if(student[n].relationship='3') cout<<"亲戚"<< endl<< "*称呼:"<<student[n].mm << endl<< endl; i++; } } if(i==0) cout<<"*没有人在最近五天过生日!"<<endl; else cout<<"近五天过生日的有"<<i<<"人"<<endl; cout << "*************************************"<<endl; } }; int main() { fstream infile; infile.open( "个人信息管理系统.txt", ios::in|ios::binary ); infile>>num; if(num!=0) { for(int n=0;n<num;n++) { infile.read(( char * )&student[n],sizeof( people )); } infile.close(); } A:{ cout << "******欢迎使用学生信息管理系统!******"<<endl; cout << "*1.录入信息;" << endl << "*2.修改信息;" << endl << "*3.删除信息;" << endl << "*4.查找信息;" << endl << "*5.列出信息;" << endl << "*6.信息排序;" << endl << "*7.同月出生查询;" << endl << "*8.五天内过生日查询; "<<endl << "*9.写入文件;" << endl << "*10.退出;" << endl << "*温馨提示:退出程序时记得将信息写入文件哦! "<<endl << "*请输入1-10:"; int n; menu eee; cin >> n; switch (n) { case 1: eee.add(); num++; break; case 2: eee.modification(); break; case 3: eee.deletes(); break; case 4: eee.checkname(); break; case 5: { cout << "*你想列出(1.全部信息;2.按关系列出;)" << endl; cout << "*请输入1-2:"; int m; cin >> m; switch (m) { case 1: eee.ashow(); break; case 2: { cout << "*你想列出(1.同学;2.同事;3.亲戚)" << endl; cout << "*请输入1-3:"; int l; cin >> l; switch (l) { case 1: eee.bshow();break; case 2: eee.cshow();break; case 3: eee.dshow();break; } } break; } } break; case 6: eee.paixu(); break; case 7: eee.checktime(); break; case 8: eee.checkdate(); break; case 9: eee.outfile(); break; case 10: return 0; } } cout<<"按回车键返回菜单!"; getch(); system("cls"); goto A; }
[ "glj1522029024@163.com" ]
glj1522029024@163.com
a22961755da4ae0d5a9e4bfac99a54b456ee68a8
810d3856f8c1bb5364ea20917690a8f3b5e83e66
/c_cpp/dev/ALGO-184/contest_9_A.cpp
4f98d7befeb42e2354b1286870ba4a7c36aa0904
[]
no_license
Saber-f/code
6c36bff79a6590bf8eb4f740cf5c403d31ddb17e
9e8646a320d91c0019493854f879bd6aefa6521d
refs/heads/master
2021-07-15T21:53:54.440183
2019-05-20T07:18:37
2019-05-20T07:18:37
129,101,087
0
0
null
null
null
null
UTF-8
C++
false
false
274
cpp
#include<stdio.h> int main(void) { int n,m,num = 0; scanf("%d %d",&n,&m); for(int t,i =0; i < n; i++) { scanf("%d",&t); if(t%m == 0) num += t/m; else num += t/m + 1; } if(num % 2 == 0) printf("%d",num /2); else printf("%d",(num+1)/2); return 0; }
[ "735974175@qq.com" ]
735974175@qq.com
6789f7991ce38c5d29f8d123ee2128dd61fffef0
cfcfb3502a0f2ebc4e1c5da3eb75336eda331146
/Praktikum Pemograman 2/modul 6/lisitng_1.cpp
e09351f406d5af4842840c974c5ca77eeee25358
[]
no_license
fadhilelrizanda/c-code
f5f05c8bbe31e1fd91acad034b721ce99a222cf4
9e67666b4c4144fac7205ceb89aa49f0498e570e
refs/heads/master
2023-01-31T07:46:59.679251
2020-12-10T03:43:38
2020-12-10T03:43:38
282,821,800
0
0
null
null
null
null
UTF-8
C++
false
false
1,101
cpp
#include <iostream> using namespace std; class Rectangle { public: int *length, *width; public: Rectangle(int a, int b) { length = new int; width = new int; *length = a; *width = b; } int arectangle() { return (*length * *width); } ~Rectangle() { cout << "\nThe result before destructor executed is : " << (*length * *width) << endl; cout << "The address of length is : " << &length << endl; cout << "The address of width is : " << &width << endl << endl; system("pause"); delete length; delete width; cout << "\nThe result after destructor executed is : " << (*length * *width) << endl; cout << "The address of length is : " << &length << endl; cout << "The address of width is : " << &width << endl << endl; system("pause"); } }; int main() { Rectangle square1(3, 4); cout << "The rectangle of the square1 is : " << square1.arectangle() << endl << endl; }
[ "fadhilelrizanda@gmail.com" ]
fadhilelrizanda@gmail.com
0e5be2a2f44a67ba2feffd3d77c3fd87b03bc177
302f4bda84739593ab952f01c9e38d512b0a7d73
/ext/Vc-1.3.2/sse/helperimpl.h
0c1663e97f55294413f2eeb22302a8af61e34be9
[ "BSD-3-Clause", "LicenseRef-scancode-free-unknown", "Apache-2.0", "ICU", "BSL-1.0", "X11", "Beerware" ]
permissive
thomaskrause/graphANNIS
649ae23dd74b57bcd8a699c1e309e74096be9db2
66d12bcfb0e0b9bfcdc2df8ffaa5ae8c84cc569c
refs/heads/develop
2020-04-11T01:28:47.589724
2018-03-15T18:16:50
2018-03-15T18:16:50
40,169,698
9
3
Apache-2.0
2018-07-28T20:18:41
2015-08-04T07:24:49
C++
UTF-8
C++
false
false
3,271
h
/* This file is part of the Vc library. {{{ Copyright © 2010-2015 Matthias Kretz <kretz@kde.org> 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 names of contributing organizations nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. }}}*/ #ifndef VC_SSE_DEINTERLEAVE_H_ #define VC_SSE_DEINTERLEAVE_H_ #include "macros.h" namespace Vc_VERSIONED_NAMESPACE { namespace Detail { template <typename A> inline void deinterleave(SSE::float_v &, SSE::float_v &, const float *, A); template <typename A> inline void deinterleave(SSE::float_v &, SSE::float_v &, const short *, A); template <typename A> inline void deinterleave(SSE::float_v &, SSE::float_v &, const ushort *, A); template <typename A> inline void deinterleave(SSE::double_v &, SSE::double_v &, const double *, A); template <typename A> inline void deinterleave(SSE::int_v &, SSE::int_v &, const int *, A); template <typename A> inline void deinterleave(SSE::int_v &, SSE::int_v &, const short *, A); template <typename A> inline void deinterleave(SSE::uint_v &, SSE::uint_v &, const uint *, A); template <typename A> inline void deinterleave(SSE::uint_v &, SSE::uint_v &, const ushort *, A); template <typename A> inline void deinterleave(SSE::short_v &, SSE::short_v &, const short *, A); template <typename A> inline void deinterleave(SSE::ushort_v &, SSE::ushort_v &, const ushort *, A); Vc_ALWAYS_INLINE_L void prefetchForOneRead(const void *addr, VectorAbi::Sse) Vc_ALWAYS_INLINE_R; Vc_ALWAYS_INLINE_L void prefetchForModify(const void *addr, VectorAbi::Sse) Vc_ALWAYS_INLINE_R; Vc_ALWAYS_INLINE_L void prefetchClose(const void *addr, VectorAbi::Sse) Vc_ALWAYS_INLINE_R; Vc_ALWAYS_INLINE_L void prefetchMid(const void *addr, VectorAbi::Sse) Vc_ALWAYS_INLINE_R; Vc_ALWAYS_INLINE_L void prefetchFar(const void *addr, VectorAbi::Sse) Vc_ALWAYS_INLINE_R; } // namespace Detail } // namespace Vc #include "deinterleave.tcc" #include "prefetches.tcc" #endif // VC_SSE_DEINTERLEAVE_H_
[ "thomaskrause@posteo.de" ]
thomaskrause@posteo.de
1264d182f0b170ab05386c58477b81f13fd376e8
d65246568137d0f0713139b11f38838bec0185e4
/miro/Worley.cpp
df9cf1a2a9c8856f837f12948e5f2ed4676490aa
[]
no_license
rayyada/CSE168PA2
4cd2e5c1e7702f3db56fe9e266e9afdc460aee78
3cbe06486931f981c73c6cdc0b098dc7b92e5282
refs/heads/master
2021-01-01T03:54:17.446239
2016-05-19T03:58:00
2016-05-19T03:58:00
58,539,262
0
0
null
null
null
null
UTF-8
C++
false
false
20,583
cpp
#include "Worley.h" #include "Material.h" #include <math.h> // private helper functions namespace { // A hardwired lookup table to quickly determine how many feature // points should be in each spatial cube. We use a table so we don't // need to make multiple slower tests. A random number indexed into // this array will give an approximate Poisson distribution of mean // density 2.5. Read the book for the longwinded explanation. static int poissonCount[256] = { 4,3,1,1,1,2,4,2,2,2,5,1,0,2,1,2,2,0,4,3,2,1,2,1,3,2,2,4,2,2,5,1,2,3,2,2,2,2,2,3, 2,4,2,5,3,2,2,2,5,3,3,5,2,1,3,3,4,4,2,3,0,4,2,2,2,1,3,2,2,2,3,3,3,1,2,0,2,1,1,2, 2,2,2,5,3,2,3,2,3,2,2,1,0,2,1,1,2,1,2,2,1,3,4,2,2,2,5,4,2,4,2,2,5,4,3,2,2,5,4,3, 3,3,5,2,2,2,2,2,3,1,1,4,2,1,3,3,4,3,2,4,3,3,3,4,5,1,4,2,4,3,1,2,3,5,3,2,1,3,1,3, 3,3,2,3,1,5,5,4,2,2,4,1,3,4,1,5,3,3,5,3,4,3,2,2,1,1,1,1,1,2,4,5,4,5,4,2,1,5,1,1, 2,3,3,3,2,5,2,3,3,2,0,2,1,1,4,2,1,3,2,1,2,2,3,2,5,5,3,4,5,5,2,4,4,5,3,2,2,2,1,4, 2,3,3,4,2,5,4,2,4,2,2,2,4,5,3,2 }; // This constant is manipulated to make sure that the mean value of F[0] // is 1.0. This makes an easy natural "scale" size of the cellular features. #define DENSITY_ADJUSTMENT 0.398150 // the function to merge-sort a "cube" of samples into the current best-found // list of values. void addSamples(long xi, long maxOrder, float at, float *F, float(*delta), unsigned long *ID); void addSamples(long xi, long yi, long maxOrder, float at[2], float *F, float(*delta)[2], unsigned long *ID); void addSamples(long xi, long yi, long zi, long maxOrder, float at[3], float *F, float(*delta)[3], unsigned long *ID); } // namespace void WorleyNoise::noise1D(float at, long maxOrder, float *F, float(*delta), unsigned long *ID) { float x2, mx2; float newAt; long intAt, i; // Initialize the F values to "huge" so they will be replaced by the // first real sample tests. Note we'll be storing and comparing the // SQUARED distance from the feature points to avoid lots of slow // sqrt() calls. We'll use sqrt() only on the final answer. for (i = 0; i < maxOrder; i++) F[i] = 999999.9; // Make our own local copy, multiplying to make mean(F[0])==1.0 newAt = DENSITY_ADJUSTMENT * at; // Find the integer cube holding the hit point intAt = int(floor(newAt)); // A simple way to compute the closest neighbors would be to test all // boundary cubes exhaustively. This is simple with code like: // { // long ii, jj, kk; // for (ii=-1; ii<=1; ii++) // addSamples(intAt+ii, maxOrder, newAt, F, delta, ID); // } // But this wastes a lot of time working on cubes which are known to be // too far away to matter! So we can use a more complex testing method // that avoids this needless testing of distant cubes. This doubles the // speed of the algorithm. // Test the central cube for closest point(s). addSamples(intAt, maxOrder, newAt, F, delta, ID); // We test if neighbor cubes are even POSSIBLE contributors by examining the // combinations of the sum of the squared distances from the cube's lower // or upper corners. x2 = newAt - intAt; mx2 = (1.0f - x2) * (1.0f - x2); x2 *= x2; // Test 2 facing neighbors of center cube. if (x2 < F[maxOrder-1]) addSamples(intAt - 1, maxOrder, newAt, F, delta, ID); if (mx2 < F[maxOrder-1]) addSamples(intAt + 1, maxOrder, newAt, F, delta, ID); // We're done! Convert everything to right size scale for (i = 0; i < maxOrder; i++) { F[i] = sqrt(F[i]) * (1.0 / DENSITY_ADJUSTMENT); delta[i] *= (1.0 / DENSITY_ADJUSTMENT); } } void WorleyNoise::noise2D(float at[2], long maxOrder, float *F, float(*delta)[2], unsigned long *ID) { float x2, y2, mx2, my2; float newAt[2]; long intAt[2], i; // Initialize the F values to "huge" so they will be replaced by the // first real sample tests. Note we'll be storing and comparing the // SQUARED distance from the feature points to avoid lots of slow // sqrt() calls. We'll use sqrt() only on the final answer. for (i = 0; i < maxOrder; i++) F[i] = 999999.9; // Make our own local copy, multiplying to make mean(F[0])==1.0 newAt[0] = DENSITY_ADJUSTMENT * at[0]; newAt[1] = DENSITY_ADJUSTMENT * at[1]; // Find the integer cube holding the hit point intAt[0] = int(floor(newAt[0])); intAt[1] = int(floor(newAt[1])); // A simple way to compute the closest neighbors would be to test all // boundary cubes exhaustively. This is simple with code like: // { // long ii, jj, kk; // for (ii=-1; ii<=1; ii++) for (jj=-1; jj<=1; jj++) // addSamples(intAt[0]+ii, intAt[1]+jj, maxOrder, newAt, F, delta, ID); // } // But this wastes a lot of time working on cubes which are known to be // too far away to matter! So we can use a more complex testing method // that avoids this needless testing of distant cubes. This doubles the // speed of the algorithm. // Test the central cube for closest point(s). addSamples(intAt[0], intAt[1], maxOrder, newAt, F, delta, ID); // We test if neighbor cubes are even POSSIBLE contributors by examining the // combinations of the sum of the squared distances from the cube's lower // or upper corners. x2 = newAt[0] - intAt[0]; y2 = newAt[1] - intAt[1]; mx2 = (1.0 - x2) * (1.0 - x2); my2 = (1.0 - y2) * (1.0 - y2); x2 *= x2; y2 *= y2; // Test 4 facing neighbors of center cube. These are closest and most // likely to have a close feature point. if (x2 < F[maxOrder-1]) addSamples(intAt[0] - 1, intAt[1] , maxOrder, newAt, F, delta, ID); if (y2 < F[maxOrder-1]) addSamples(intAt[0] , intAt[1] - 1, maxOrder, newAt, F, delta, ID); if (mx2 < F[maxOrder-1]) addSamples(intAt[0] + 1, intAt[1] , maxOrder, newAt, F, delta, ID); if (my2 < F[maxOrder-1]) addSamples(intAt[0] , intAt[1] + 1, maxOrder, newAt, F, delta, ID); // Test 4 "edge cube" neighbors if necessary. They're next closest. if (x2 + y2 < F[maxOrder-1]) addSamples(intAt[0] - 1, intAt[1] - 1, maxOrder, newAt, F, delta, ID); if (mx2 + my2 < F[maxOrder-1]) addSamples(intAt[0] + 1, intAt[1] + 1, maxOrder, newAt, F, delta, ID); if (x2 + my2 < F[maxOrder-1]) addSamples(intAt[0] - 1, intAt[1] + 1, maxOrder, newAt, F, delta, ID); if (mx2 + y2 < F[maxOrder-1]) addSamples(intAt[0] + 1, intAt[1] - 1, maxOrder, newAt, F, delta, ID); // We're done! Convert everything to right size scale for (i = 0; i < maxOrder; i++) { F[i] = sqrt(F[i]) * (1.0 / DENSITY_ADJUSTMENT); delta[i][0] *= (1.0 / DENSITY_ADJUSTMENT); delta[i][1] *= (1.0 / DENSITY_ADJUSTMENT); } } void WorleyNoise::noise3D(float at[3], long maxOrder, float *F, float(*delta)[3], unsigned long *ID) { float x2, y2, z2, mx2, my2, mz2; float newAt[3]; long intAt[3], i; // Initialize the F values to "huge" so they will be replaced by the // first real sample tests. Note we'll be storing and comparing the // SQUARED distance from the feature points to avoid lots of slow // sqrt() calls. We'll use sqrt() only on the final answer. for (i = 0; i < maxOrder; i++) F[i] = 999999.9; // Make our own local copy, multiplying to make mean(F[0])==1.0 newAt[0] = DENSITY_ADJUSTMENT * at[0]; newAt[1] = DENSITY_ADJUSTMENT * at[1]; newAt[2] = DENSITY_ADJUSTMENT * at[2]; // Find the integer cube holding the hit point intAt[0] = int(floor(newAt[0])); intAt[1] = int(floor(newAt[1])); intAt[2] = int(floor(newAt[2])); // A simple way to compute the closest neighbors would be to test all // boundary cubes exhaustively. This is simple with code like: // { // long ii, jj, kk; // for (ii=-1; ii<=1; ii++) for (jj=-1; jj<=1; jj++) for (kk=-1; kk<=1; kk++) // addSamples(intAt[0]+ii,intAt[1]+jj,intAt[2]+kk, // maxOrder, newAt, F, delta, ID); // } // But this wastes a lot of time working on cubes which are known to be // too far away to matter! So we can use a more complex testing method // that avoids this needless testing of distant cubes. This doubles the // speed of the algorithm. // Test the central cube for closest point(s). addSamples(intAt[0], intAt[1], intAt[2], maxOrder, newAt, F, delta, ID); // We test if neighbor cubes are even POSSIBLE contributors by examining the // combinations of the sum of the squared distances from the cube's lower // or upper corners. x2 = newAt[0] - intAt[0]; y2 = newAt[1] - intAt[1]; z2 = newAt[2] - intAt[2]; mx2 = (1.0 - x2) * (1.0 - x2); my2 = (1.0 - y2) * (1.0 - y2); mz2 = (1.0 - z2) * (1.0 - z2); x2 *= x2; y2 *= y2; z2 *= z2; // Test 6 facing neighbors of center cube. These are closest and most // likely to have a close feature point. if (x2 < F[maxOrder-1]) addSamples(intAt[0] - 1, intAt[1] , intAt[2] , maxOrder, newAt, F, delta, ID); if (y2 < F[maxOrder-1]) addSamples(intAt[0] , intAt[1] - 1, intAt[2] , maxOrder, newAt, F, delta, ID); if (z2 < F[maxOrder-1]) addSamples(intAt[0] , intAt[1] , intAt[2] - 1, maxOrder, newAt, F, delta, ID); if (mx2 < F[maxOrder-1]) addSamples(intAt[0] + 1, intAt[1] , intAt[2] , maxOrder, newAt, F, delta, ID); if (my2 < F[maxOrder-1]) addSamples(intAt[0] , intAt[1] + 1, intAt[2] , maxOrder, newAt, F, delta, ID); if (mz2 < F[maxOrder-1]) addSamples(intAt[0] , intAt[1] , intAt[2] + 1, maxOrder, newAt, F, delta, ID); // Test 12 "edge cube" neighbors if necessary. They're next closest. if (x2 + y2 < F[maxOrder-1]) addSamples(intAt[0] - 1, intAt[1] - 1, intAt[2] , maxOrder, newAt, F, delta, ID); if (x2 + z2 < F[maxOrder-1]) addSamples(intAt[0] - 1, intAt[1] , intAt[2] - 1, maxOrder, newAt, F, delta, ID); if (y2 + z2 < F[maxOrder-1]) addSamples(intAt[0] , intAt[1] - 1, intAt[2] - 1, maxOrder, newAt, F, delta, ID); if (mx2 + my2 < F[maxOrder-1]) addSamples(intAt[0] + 1, intAt[1] + 1, intAt[2] , maxOrder, newAt, F, delta, ID); if (mx2 + mz2 < F[maxOrder-1]) addSamples(intAt[0] + 1, intAt[1] , intAt[2] + 1, maxOrder, newAt, F, delta, ID); if (my2 + mz2 < F[maxOrder-1]) addSamples(intAt[0] , intAt[1] + 1, intAt[2] + 1, maxOrder, newAt, F, delta, ID); if (x2 + my2 < F[maxOrder-1]) addSamples(intAt[0] - 1, intAt[1] + 1, intAt[2] , maxOrder, newAt, F, delta, ID); if (x2 + mz2 < F[maxOrder-1]) addSamples(intAt[0] - 1, intAt[1] , intAt[2] + 1, maxOrder, newAt, F, delta, ID); if (y2 + mz2 < F[maxOrder-1]) addSamples(intAt[0] , intAt[1] - 1, intAt[2] + 1, maxOrder, newAt, F, delta, ID); if (mx2 + y2 < F[maxOrder-1]) addSamples(intAt[0] + 1, intAt[1] - 1, intAt[2] , maxOrder, newAt, F, delta, ID); if (mx2 + z2 < F[maxOrder-1]) addSamples(intAt[0] + 1, intAt[1] , intAt[2] - 1, maxOrder, newAt, F, delta, ID); if (my2 + z2 < F[maxOrder-1]) addSamples(intAt[0] , intAt[1] + 1, intAt[2] - 1, maxOrder, newAt, F, delta, ID); // Final 8 "corner" cubes if (x2 + y2 + z2 < F[maxOrder-1]) addSamples(intAt[0] - 1, intAt[1] - 1, intAt[2] - 1, maxOrder, newAt, F, delta, ID); if (x2 + y2 + mz2 < F[maxOrder-1]) addSamples(intAt[0] - 1, intAt[1] - 1, intAt[2] + 1, maxOrder, newAt, F, delta, ID); if (x2 + my2 + z2 < F[maxOrder-1]) addSamples(intAt[0] - 1, intAt[1] + 1, intAt[2] - 1, maxOrder, newAt, F, delta, ID); if (x2 + my2 + mz2 < F[maxOrder-1]) addSamples(intAt[0] - 1, intAt[1] + 1, intAt[2] + 1, maxOrder, newAt, F, delta, ID); if (mx2 + y2 + z2 < F[maxOrder-1]) addSamples(intAt[0] + 1, intAt[1] - 1, intAt[2] - 1, maxOrder, newAt, F, delta, ID); if (mx2 + y2 + mz2 < F[maxOrder-1]) addSamples(intAt[0] + 1, intAt[1] - 1, intAt[2] + 1, maxOrder, newAt, F, delta, ID); if (mx2 + my2 + z2 < F[maxOrder-1]) addSamples(intAt[0] + 1, intAt[1] + 1, intAt[2] - 1, maxOrder, newAt, F, delta, ID); if (mx2 + my2 + mz2 < F[maxOrder-1]) addSamples(intAt[0] + 1, intAt[1] + 1, intAt[2] + 1, maxOrder, newAt, F, delta, ID); // We're done! Convert everything to right size scale for (i = 0; i < maxOrder; i++) { F[i] = sqrt(F[i]) * (1.0 / DENSITY_ADJUSTMENT); delta[i][0] *= (1.0 / DENSITY_ADJUSTMENT); delta[i][1] *= (1.0 / DENSITY_ADJUSTMENT); delta[i][2] *= (1.0 / DENSITY_ADJUSTMENT); } } // private helper functions namespace { void addSamples(long xi, long maxOrder, float at, float *F, float(*delta), unsigned long *ID) { float dx, fx, d2; long count, i, j, index; unsigned long seed, this_id; // Each cube has a random number seed based on the cube's ID number. // The seed might be better if it were a nonlinear hash like Perlin uses // for noise but we do very well with this faster simple one. // Our LCG uses Knuth-approved constants for maximal periods. seed = 702395077 * xi; // How many feature points are in this cube? count = poissonCount[seed>>24]; // 256 element lookup table. Use MSB seed = 1402024253 * seed + 586950981; // churn the seed with good Knuth LCG for (j = 0; j < count; j++) // test and insert each point into our solution { this_id = seed; seed = 1402024253 * seed + 586950981; // churn // compute the 0..1 feature point location's XYZ fx = (seed + 0.5) * (1.0 / 4294967296.0); seed = 1402024253 * seed + 586950981; // churn // delta from feature point to sample location dx = xi + fx - at; d2 = dx * dx; // Euclidian distance, squared if (d2 < F[maxOrder-1]) // Is this point close enough to rememember? { // Insert the information into the output arrays if it's close enough. // We use an insertion sort. No need for a binary search to find // the appropriate index.. usually we're dealing with order 2,3,4 so // we can just go through the list. If you were computing order 50 // (wow!!) you could get a speedup with a binary search in the sorted // F[] list. index = maxOrder; while (index > 0 && d2 < F[index-1]) index--; // We insert this new point into slot # <index> // Bump down more distant information to make room for this new point. for (i = maxOrder - 2; i >= index; i--) { F[i+1] = F[i]; ID[i+1] = ID[i]; delta[i+1] = delta[i]; } // Insert the new point's information into the list. F[index] = d2; ID[index] = this_id; delta[index] = dx; } } } void addSamples(long xi, long yi, long maxOrder, float at[2], float *F, float(*delta)[2], unsigned long *ID) { float dx, dy, fx, fy, d2; long count, i, j, index; unsigned long seed, this_id; // Each cube has a random number seed based on the cube's ID number. // The seed might be better if it were a nonlinear hash like Perlin uses // for noise but we do very well with this faster simple one. // Our LCG uses Knuth-approved constants for maximal periods. seed = 702395077 * xi + 915488749 * yi; // How many feature points are in this cube? count = poissonCount[seed>>24]; // 256 element lookup table. Use MSB seed = 1402024253 * seed + 586950981; // churn the seed with good Knuth LCG for (j = 0; j < count; j++) // test and insert each point into our solution { this_id = seed; seed = 1402024253 * seed + 586950981; // churn // compute the 0..1 feature point location's XYZ fx = (seed + 0.5) * (1.0 / 4294967296.0); seed = 1402024253 * seed + 586950981; // churn fy = (seed + 0.5) * (1.0 / 4294967296.0); seed = 1402024253 * seed + 586950981; // churn // delta from feature point to sample location dx = xi + fx - at[0]; dy = yi + fy - at[1]; d2 = dx * dx + dy * dy; // Euclidian distance, squared if (d2 < F[maxOrder-1]) // Is this point close enough to rememember? { // Insert the information into the output arrays if it's close enough. // We use an insertion sort. No need for a binary search to find // the appropriate index.. usually we're dealing with order 2,3,4 so // we can just go through the list. If you were computing order 50 // (wow!!) you could get a speedup with a binary search in the sorted // F[] list. index = maxOrder; while (index > 0 && d2 < F[index-1]) index--; // We insert this new point into slot # <index> // Bump down more distant information to make room for this new point. for (i = maxOrder - 2; i >= index; i--) { F[i+1] = F[i]; ID[i+1] = ID[i]; delta[i+1][0] = delta[i][0]; delta[i+1][1] = delta[i][1]; } // Insert the new point's information into the list. F[index] = d2; ID[index] = this_id; delta[index][0] = dx; delta[index][1] = dy; } } } void addSamples(long xi, long yi, long zi, long maxOrder, float at[3], float *F, float(*delta)[3], unsigned long *ID) { float dx, dy, dz, fx, fy, fz, d2; long count, i, j, index; unsigned long seed, this_id; // Each cube has a random number seed based on the cube's ID number. // The seed might be better if it were a nonlinear hash like Perlin uses // for noise but we do very well with this faster simple one. // Our LCG uses Knuth-approved constants for maximal periods. seed = 702395077 * xi + 915488749 * yi + 2120969693 * zi; // How many feature points are in this cube? count = poissonCount[seed>>24]; // 256 element lookup table. Use MSB seed = 1402024253 * seed + 586950981; // churn the seed with good Knuth LCG for (j = 0; j < count; j++) // test and insert each point into our solution { this_id = seed; seed = 1402024253 * seed + 586950981; // churn // compute the 0..1 feature point location's XYZ fx = (seed + 0.5) * (1.0 / 4294967296.0); seed = 1402024253 * seed + 586950981; // churn fy = (seed + 0.5) * (1.0 / 4294967296.0); seed = 1402024253 * seed + 586950981; // churn fz = (seed + 0.5) * (1.0 / 4294967296.0); seed = 1402024253 * seed + 586950981; // churn // delta from feature point to sample location dx = xi + fx - at[0]; dy = yi + fy - at[1]; dz = zi + fz - at[2]; d2 = dx * dx + dy * dy + dz * dz; // Euclidian distance, squared if (d2 < F[maxOrder-1]) // Is this point close enough to rememember? { // Insert the information into the output arrays if it's close enough. // We use an insertion sort. No need for a binary search to find // the appropriate index.. usually we're dealing with order 2,3,4 so // we can just go through the list. If you were computing order 50 // (wow!!) you could get a speedup with a binary search in the sorted // F[] list. index = maxOrder; while (index > 0 && d2 < F[index-1]) index--; // We insert this new point into slot # <index> // Bump down more distant information to make room for this new point. for (i = maxOrder - 2; i >= index; i--) { F[i+1] = F[i]; ID[i+1] = ID[i]; delta[i+1][0] = delta[i][0]; delta[i+1][1] = delta[i][1]; delta[i+1][2] = delta[i][2]; } // Insert the new point's information into the list. F[index] = d2; ID[index] = this_id; delta[index][0] = dx; delta[index][1] = dy; delta[index][2] = dz; } } } } // namespace
[ "Ray Yada" ]
Ray Yada
3fc8a20a302d8943ffb7cbf33a78b0559884dc76
139102f183b7e3fb12e50d89fd6f8b431257574c
/Graph/fullDFS.cpp
4959da7da87c4d5297b91b5cb19f1d1749216349
[]
no_license
owais30/Competitive-Programming
283d8e56e32a0cbc184bb382fd6b04c9283e0f13
d50e07808de50828116e750cdf03bf984bfda6b2
refs/heads/master
2021-10-11T21:34:01.221465
2021-09-27T16:20:50
2021-09-27T16:20:50
186,923,964
3
1
null
2019-10-02T10:30:48
2019-05-16T00:52:40
C++
UTF-8
C++
false
false
8,854
cpp
#include <algorithm> #include <cstdio> #include <vector> using namespace std; typedef pair<int, int> ii; // In this chapter, we will frequently use these typedef vector<ii> vii; // three data type shortcuts. They may look cryptic typedef vector<int> vi; // but shortcuts are useful in competitive programming #define DFS_WHITE -1 // normal DFS, do not change this with other values (other than 0), because we usually use memset with conjunction with DFS_WHITE #define DFS_BLACK 1 vector<vii> AdjList; void printThis(char* message) { printf("==================================\n"); printf("%s\n", message); printf("==================================\n"); } vi dfs_num; // this variable has to be global, we cannot put it in recursion int numCC; void dfs(int u) { // DFS for normal usage: as graph traversal algorithm printf(" %d", u); // this vertex is visited dfs_num[u] = DFS_BLACK; // important step: we mark this vertex as visited for (int j = 0; j < (int)AdjList[u].size(); j++) { ii v = AdjList[u][j]; // v is a (neighbor, weight) pair if (dfs_num[v.first] == DFS_WHITE) // important check to avoid cycle dfs(v.first); // recursively visits unvisited neighbors v of vertex u } } // note: this is not the version on implicit graph void floodfill(int u, int color) { dfs_num[u] = color; // not just a generic DFS_BLACK for (int j = 0; j < (int)AdjList[u].size(); j++) { ii v = AdjList[u][j]; if (dfs_num[v.first] == DFS_WHITE) floodfill(v.first, color); } } vi topoSort; // global vector to store the toposort in reverse order void dfs2(int u) { // change function name to differentiate with original dfs dfs_num[u] = DFS_BLACK; for (int j = 0; j < (int)AdjList[u].size(); j++) { ii v = AdjList[u][j]; if (dfs_num[v.first] == DFS_WHITE) dfs2(v.first); } topoSort.push_back(u); } // that is, this is the only change #define DFS_GRAY 2 // one more color for graph edges property check vi dfs_parent; // to differentiate real back edge versus bidirectional edge void graphCheck(int u) { // DFS for checking graph edge properties dfs_num[u] = DFS_GRAY; // color this as DFS_GRAY (temp) instead of DFS_BLACK for (int j = 0; j < (int)AdjList[u].size(); j++) { ii v = AdjList[u][j]; if (dfs_num[v.first] == DFS_WHITE) { // Tree Edge, DFS_GRAY to DFS_WHITE dfs_parent[v.first] = u; // parent of this children is me graphCheck(v.first); } else if (dfs_num[v.first] == DFS_GRAY) { // DFS_GRAY to DFS_GRAY if (v.first == dfs_parent[u]) // to differentiate these two cases printf(" Bidirectional (%d, %d) - (%d, %d)\n", u, v.first, v.first, u); else // the most frequent application: check if the given graph is cyclic printf(" Back Edge (%d, %d) (Cycle)\n", u, v.first); } else if (dfs_num[v.first] == DFS_BLACK) // DFS_GRAY to DFS_BLACK printf(" Forward/Cross Edge (%d, %d)\n", u, v.first); } dfs_num[u] = DFS_BLACK; // after recursion, color this as DFS_BLACK (DONE) } vi dfs_low; // additional information for articulation points/bridges/SCCs vi articulation_vertex; int dfsNumberCounter, dfsRoot, rootChildren; void articulationPointAndBridge(int u) { dfs_low[u] = dfs_num[u] = dfsNumberCounter++; // dfs_low[u] <= dfs_num[u] for (int j = 0; j < (int)AdjList[u].size(); j++) { ii v = AdjList[u][j]; if (dfs_num[v.first] == DFS_WHITE) { // a tree edge dfs_parent[v.first] = u; if (u == dfsRoot) rootChildren++; // special case, count children of root articulationPointAndBridge(v.first); if (dfs_low[v.first] >= dfs_num[u]) // for articulation point articulation_vertex[u] = true; // store this information first if (dfs_low[v.first] > dfs_num[u]) // for bridge printf(" Edge (%d, %d) is a bridge\n", u, v.first); dfs_low[u] = min(dfs_low[u], dfs_low[v.first]); // update dfs_low[u] } else if (v.first != dfs_parent[u]) // a back edge and not direct cycle dfs_low[u] = min(dfs_low[u], dfs_num[v.first]); // update dfs_low[u] } } vi S, visited; // additional global variables int numSCC; void tarjanSCC(int u) { dfs_low[u] = dfs_num[u] = dfsNumberCounter++; // dfs_low[u] <= dfs_num[u] S.push_back(u); // stores u in a vector based on order of visitation visited[u] = 1; for (int j = 0; j < (int)AdjList[u].size(); j++) { ii v = AdjList[u][j]; if (dfs_num[v.first] == DFS_WHITE) tarjanSCC(v.first); if (visited[v.first]) // condition for update dfs_low[u] = min(dfs_low[u], dfs_low[v.first]); } if (dfs_low[u] == dfs_num[u]) { // if this is a root (start) of an SCC printf("SCC %d:", ++numSCC); // this part is done after recursion while (1) { int v = S.back(); S.pop_back(); visited[v] = 0; printf(" %d", v); if (u == v) break; } printf("\n"); } } int main() { int V, total_neighbors, id, weight; /* // Use the following input: // Graph in Figure 4.1 9 1 1 0 3 0 0 2 0 3 0 2 1 0 3 0 3 1 0 2 0 4 0 1 3 0 0 2 7 0 8 0 1 6 0 1 6 0 // Example of directed acyclic graph in Figure 4.4 (for toposort) 8 2 1 0 2 0 2 2 0 3 0 2 3 0 5 0 1 4 0 0 0 0 1 6 0 // Example of directed graph with back edges 3 1 1 0 1 2 0 1 0 0 // Left graph in Figure 4.6/4.7/4.8 6 1 1 0 3 0 0 2 0 4 0 1 1 0 1 4 0 3 1 0 3 0 5 0 1 4 0 // Right graph in Figure 4.6/4.7/4.8 6 1 1 0 5 0 0 2 0 3 0 4 0 5 0 1 1 0 1 1 0 2 1 0 5 0 2 1 0 4 0 // Directed graph in Figure 4.9 8 1 1 0 1 3 0 1 1 0 2 2 0 4 0 1 5 0 1 7 0 1 4 0 1 6 0 */ freopen("in_01.txt", "r", stdin); scanf("%d", &V); AdjList.assign(V, vii()); // assign blank vectors of pair<int, int>s to AdjList for (int i = 0; i < V; i++) { scanf("%d", &total_neighbors); for (int j = 0; j < total_neighbors; j++) { scanf("%d %d", &id, &weight); AdjList[i].push_back(ii(id, weight)); } } printThis("Standard DFS Demo (the input graph must be UNDIRECTED)"); numCC = 0; dfs_num.assign(V, DFS_WHITE); // this sets all vertices' state to DFS_WHITE for (int i = 0; i < V; i++) // for each vertex i in [0..V-1] if (dfs_num[i] == DFS_WHITE) // if that vertex is not visited yet printf("Component %d:", ++numCC), dfs(i), printf("\n"); // 3 lines here! printf("There are %d connected components\n", numCC); printThis("Flood Fill Demo (the input graph must be UNDIRECTED)"); numCC = 0; dfs_num.assign(V, DFS_WHITE); for (int i = 0; i < V; i++) if (dfs_num[i] == DFS_WHITE) floodfill(i, ++numCC); for (int i = 0; i < V; i++) printf("Vertex %d has color %d\n", i, dfs_num[i]); // make sure that the given graph is DAG printThis("Topological Sort (the input graph must be DAG)"); topoSort.clear(); dfs_num.assign(V, DFS_WHITE); for (int i = 0; i < V; i++) // this part is the same as finding CCs if (dfs_num[i] == DFS_WHITE) dfs2(i); reverse(topoSort.begin(), topoSort.end()); // reverse topoSort for (int i = 0; i < (int)topoSort.size(); i++) // or you can simply read printf(" %d", topoSort[i]); // the content of `topoSort' backwards printf("\n"); printThis("Graph Edges Property Check"); numCC = 0; dfs_num.assign(V, DFS_WHITE); dfs_parent.assign(V, -1); for (int i = 0; i < V; i++) if (dfs_num[i] == DFS_WHITE) printf("Component %d:\n", ++numCC), graphCheck(i); // 2 lines in one printThis("Articulation Points & Bridges (the input graph must be UNDIRECTED)"); dfsNumberCounter = 0; dfs_num.assign(V, DFS_WHITE); dfs_low.assign(V, 0); dfs_parent.assign(V, -1); articulation_vertex.assign(V, 0); printf("Bridges:\n"); for (int i = 0; i < V; i++) if (dfs_num[i] == DFS_WHITE) { dfsRoot = i; rootChildren = 0; articulationPointAndBridge(i); articulation_vertex[dfsRoot] = (rootChildren > 1); } // special case printf("Articulation Points:\n"); for (int i = 0; i < V; i++) if (articulation_vertex[i]) printf(" Vertex %d\n", i); printThis("Strongly Connected Components (the input graph must be DIRECTED)"); dfs_num.assign(V, DFS_WHITE); dfs_low.assign(V, 0); visited.assign(V, 0); dfsNumberCounter = numSCC = 0; for (int i = 0; i < V; i++) if (dfs_num[i] == DFS_WHITE) tarjanSCC(i); return 0; }
[ "noreply@github.com" ]
owais30.noreply@github.com
5e418da066f76f779f6e83f272f1b10d6ca77cc7
8ed7b2cb70c6e33b01679c17d0e340f11c733520
/learnqt5/cm/cm-lib/source/framework/command.cpp
3716e22b02dd3f1786f86966099df0483e63ae65
[]
no_license
saibi/qt
6528b727bd73da82f513f2f54c067a669f394c9a
a3066b90cbc1ac6b9c82af5c75c40ce9e845f9a2
refs/heads/master
2022-06-26T20:08:07.960786
2022-06-10T06:49:28
2022-06-10T06:49:28
88,221,337
0
0
null
null
null
null
UTF-8
C++
false
false
903
cpp
#include "command.h" namespace cm { namespace framework { class Command::Implementation { public: Implementation(const QString& _iconCharacter, const QString& _description, std::function<bool()> _canExecute) : iconCharacter(_iconCharacter), description(_description), canExecute(_canExecute) { } QString iconCharacter; QString description; std::function<bool()> canExecute; }; Command::Command(QObject *parent, const QString &iconCharacter, const QString &description, std::function<bool ()> canExecute) : QObject(parent) { implementation.reset(new Implementation(iconCharacter, description, canExecute)); } Command::~Command() { } const QString& Command::iconCharacter() const { return implementation->iconCharacter; } const QString& Command::description() const { return implementation->description; } bool Command::canExecute() const { return implementation->canExecute(); } }}
[ "ymkim@huvitz.com" ]
ymkim@huvitz.com
dbca2b47aeae072f824b279a023450880674f916
30d6ffcaed24e22c071b46652890e57ef40fce07
/custom_projects/09_OLED_Interfacing/04_oled_ST7735_80_160_spi/04_oled_ST7735_80_160_spi.ino
643a886ee21c441d1028449f5d948c553c69a05f
[]
no_license
softwaresunleashed/arduino
6fac93d16a13317a6818bd84e760d834b06975ce
f28d5554d449368850f2d95bd88ec8354e6f308c
refs/heads/master
2023-01-12T02:54:18.674457
2020-11-05T12:48:34
2020-11-05T12:48:34
213,021,879
0
0
null
null
null
null
UTF-8
C++
false
false
9,548
ino
/************************************************************************** This is a library for several Adafruit displays based on ST77* drivers. Works with the Adafruit 1.8" TFT Breakout w/SD card ----> http://www.adafruit.com/products/358 The 1.8" TFT shield ----> https://www.adafruit.com/product/802 The 1.44" TFT breakout ----> https://www.adafruit.com/product/2088 The 1.14" TFT breakout ----> https://www.adafruit.com/product/4383 The 1.3" TFT breakout ----> https://www.adafruit.com/product/4313 The 1.54" TFT breakout ----> https://www.adafruit.com/product/3787 The 2.0" TFT breakout ----> https://www.adafruit.com/product/4311 as well as Adafruit raw 1.8" TFT display ----> http://www.adafruit.com/products/618 Check out the links above for our tutorials and wiring diagrams. These displays use SPI to communicate, 4 or 5 pins are required to interface (RST is optional). Adafruit invests time and resources providing this open source code, please support Adafruit and open-source hardware by purchasing products from Adafruit! Written by Limor Fried/Ladyada for Adafruit Industries. MIT license, all text above must be included in any redistribution **************************************************************************/ #include <Adafruit_GFX.h> // Core graphics library #include <Adafruit_ST7735.h> // Hardware-specific library for ST7735 #include <Adafruit_ST7789.h> // Hardware-specific library for ST7789 #include <SPI.h> // For the breakout board, you can use any 2 or 3 pins. // These pins will also work for the 1.8" TFT shield. #define TFT_CS 10 #define TFT_RST 9 // Or set to -1 and connect to Arduino RESET pin #define TFT_DC 8 #define TFT_MOSI 11 // Data out #define TFT_SCLK 13 // Clock out // For 1.44" and 1.8" TFT with ST7735 use: //Adafruit_ST7735 tft = Adafruit_ST7735(TFT_CS, TFT_DC, TFT_RST); // For 1.14", 1.3", 1.54", and 2.0" TFT with ST7789: //Adafruit_ST7789 tft = Adafruit_ST7789(TFT_CS, TFT_DC, TFT_RST); // For ST7735-based displays, we will use this call Adafruit_ST7735 tft = Adafruit_ST7735(TFT_CS, TFT_DC, TFT_MOSI, TFT_SCLK, TFT_RST); // OR for the ST7789-based displays, we will use this call //Adafruit_ST7789 tft = Adafruit_ST7789(TFT_CS, TFT_DC, TFT_MOSI, TFT_SCLK, TFT_RST); float p = 3.1415926; void setup(void) { Serial.begin(9600); Serial.print(F("Hello! ST77xx TFT Test")); // Use this initializer if using a 1.8" TFT screen: //tft.initR(INITR_BLACKTAB); // Init ST7735S chip, black tab // OR use this initializer (uncomment) if using a 1.44" TFT: //tft.initR(INITR_144GREENTAB); // Init ST7735R chip, green tab // OR use this initializer (uncomment) if using a 0.96" 160x80 TFT: tft.initR(INITR_MINI160x80); // Init ST7735S mini display // OR use this initializer (uncomment) if using a 1.3" or 1.54" 240x240 TFT: //tft.init(240, 240); // Init ST7789 240x240 // OR use this initializer (uncomment) if using a 2.0" 320x240 TFT: //tft.init(240, 320); // Init ST7789 320x240 // OR use this initializer (uncomment) if using a 1.14" 240x135 TFT: //tft.init(135, 240); // Init ST7789 240x135 Serial.println(F("Initialized")); uint16_t time = millis(); tft.fillScreen(ST77XX_BLACK); time = millis() - time; Serial.println(time, DEC); delay(500); // large block of text tft.fillScreen(ST77XX_BLACK); testdrawtext("Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur adipiscing ante sed nibh tincidunt feugiat. Maecenas enim massa, fringilla sed malesuada et, malesuada sit amet turpis. Sed porttitor neque ut ante pretium vitae malesuada nunc bibendum. Nullam aliquet ultrices massa eu hendrerit. Ut sed nisi lorem. In vestibulum purus a tortor imperdiet posuere. ", ST77XX_WHITE); delay(1000); // tft print function! tftPrintTest(); delay(4000); // a single pixel tft.drawPixel(tft.width()/2, tft.height()/2, ST77XX_GREEN); delay(500); // line draw test testlines(ST77XX_YELLOW); delay(500); // optimized lines testfastlines(ST77XX_RED, ST77XX_BLUE); delay(500); testdrawrects(ST77XX_GREEN); delay(500); testfillrects(ST77XX_YELLOW, ST77XX_MAGENTA); delay(500); tft.fillScreen(ST77XX_BLACK); testfillcircles(10, ST77XX_BLUE); testdrawcircles(10, ST77XX_WHITE); delay(500); testroundrects(); delay(500); testtriangles(); delay(500); mediabuttons(); delay(500); Serial.println("done"); delay(1000); } void loop() { tft.invertDisplay(true); delay(500); tft.invertDisplay(false); delay(500); } void testlines(uint16_t color) { tft.fillScreen(ST77XX_BLACK); for (int16_t x=0; x < tft.width(); x+=6) { tft.drawLine(0, 0, x, tft.height()-1, color); delay(0); } for (int16_t y=0; y < tft.height(); y+=6) { tft.drawLine(0, 0, tft.width()-1, y, color); delay(0); } tft.fillScreen(ST77XX_BLACK); for (int16_t x=0; x < tft.width(); x+=6) { tft.drawLine(tft.width()-1, 0, x, tft.height()-1, color); delay(0); } for (int16_t y=0; y < tft.height(); y+=6) { tft.drawLine(tft.width()-1, 0, 0, y, color); delay(0); } tft.fillScreen(ST77XX_BLACK); for (int16_t x=0; x < tft.width(); x+=6) { tft.drawLine(0, tft.height()-1, x, 0, color); delay(0); } for (int16_t y=0; y < tft.height(); y+=6) { tft.drawLine(0, tft.height()-1, tft.width()-1, y, color); delay(0); } tft.fillScreen(ST77XX_BLACK); for (int16_t x=0; x < tft.width(); x+=6) { tft.drawLine(tft.width()-1, tft.height()-1, x, 0, color); delay(0); } for (int16_t y=0; y < tft.height(); y+=6) { tft.drawLine(tft.width()-1, tft.height()-1, 0, y, color); delay(0); } } void testdrawtext(char *text, uint16_t color) { tft.setCursor(0, 0); tft.setTextColor(color); tft.setTextWrap(true); tft.print(text); } void testfastlines(uint16_t color1, uint16_t color2) { tft.fillScreen(ST77XX_BLACK); for (int16_t y=0; y < tft.height(); y+=5) { tft.drawFastHLine(0, y, tft.width(), color1); } for (int16_t x=0; x < tft.width(); x+=5) { tft.drawFastVLine(x, 0, tft.height(), color2); } } void testdrawrects(uint16_t color) { tft.fillScreen(ST77XX_BLACK); for (int16_t x=0; x < tft.width(); x+=6) { tft.drawRect(tft.width()/2 -x/2, tft.height()/2 -x/2 , x, x, color); } } void testfillrects(uint16_t color1, uint16_t color2) { tft.fillScreen(ST77XX_BLACK); for (int16_t x=tft.width()-1; x > 6; x-=6) { tft.fillRect(tft.width()/2 -x/2, tft.height()/2 -x/2 , x, x, color1); tft.drawRect(tft.width()/2 -x/2, tft.height()/2 -x/2 , x, x, color2); } } void testfillcircles(uint8_t radius, uint16_t color) { for (int16_t x=radius; x < tft.width(); x+=radius*2) { for (int16_t y=radius; y < tft.height(); y+=radius*2) { tft.fillCircle(x, y, radius, color); } } } void testdrawcircles(uint8_t radius, uint16_t color) { for (int16_t x=0; x < tft.width()+radius; x+=radius*2) { for (int16_t y=0; y < tft.height()+radius; y+=radius*2) { tft.drawCircle(x, y, radius, color); } } } void testtriangles() { tft.fillScreen(ST77XX_BLACK); uint16_t color = 0xF800; int t; int w = tft.width()/2; int x = tft.height()-1; int y = 0; int z = tft.width(); for(t = 0 ; t <= 15; t++) { tft.drawTriangle(w, y, y, x, z, x, color); x-=4; y+=4; z-=4; color+=100; } } void testroundrects() { tft.fillScreen(ST77XX_BLACK); uint16_t color = 100; int i; int t; for(t = 0 ; t <= 4; t+=1) { int x = 0; int y = 0; int w = tft.width()-2; int h = tft.height()-2; for(i = 0 ; i <= 16; i+=1) { tft.drawRoundRect(x, y, w, h, 5, color); x+=2; y+=3; w-=4; h-=6; color+=1100; } color+=100; } } void tftPrintTest() { tft.setTextWrap(false); tft.fillScreen(ST77XX_BLACK); tft.setCursor(0, 30); tft.setTextColor(ST77XX_RED); tft.setTextSize(1); tft.println("Hello World!"); tft.setTextColor(ST77XX_YELLOW); tft.setTextSize(2); tft.println("Hello World!"); tft.setTextColor(ST77XX_GREEN); tft.setTextSize(3); tft.println("Hello World!"); tft.setTextColor(ST77XX_BLUE); tft.setTextSize(4); tft.print(1234.567); delay(1500); tft.setCursor(0, 0); tft.fillScreen(ST77XX_BLACK); tft.setTextColor(ST77XX_WHITE); tft.setTextSize(0); tft.println("Hello World!"); tft.setTextSize(1); tft.setTextColor(ST77XX_GREEN); tft.print(p, 6); tft.println(" Want pi?"); tft.println(" "); tft.print(8675309, HEX); // print 8,675,309 out in HEX! tft.println(" Print HEX!"); tft.println(" "); tft.setTextColor(ST77XX_WHITE); tft.println("Sketch has been"); tft.println("running for: "); tft.setTextColor(ST77XX_MAGENTA); tft.print(millis() / 1000); tft.setTextColor(ST77XX_WHITE); tft.print(" seconds."); } void mediabuttons() { // play tft.fillScreen(ST77XX_BLACK); tft.fillRoundRect(25, 10, 78, 60, 8, ST77XX_WHITE); tft.fillTriangle(42, 20, 42, 60, 90, 40, ST77XX_RED); delay(500); // pause tft.fillRoundRect(25, 90, 78, 60, 8, ST77XX_WHITE); tft.fillRoundRect(39, 98, 20, 45, 5, ST77XX_GREEN); tft.fillRoundRect(69, 98, 20, 45, 5, ST77XX_GREEN); delay(500); // play color tft.fillTriangle(42, 20, 42, 60, 90, 40, ST77XX_BLUE); delay(50); // pause color tft.fillRoundRect(39, 98, 20, 45, 5, ST77XX_RED); tft.fillRoundRect(69, 98, 20, 45, 5, ST77XX_RED); // play color tft.fillTriangle(42, 20, 42, 60, 90, 40, ST77XX_GREEN); }
[ "softwares.unleashed@gmail.com" ]
softwares.unleashed@gmail.com
e711d43d564dbea80ffd823de0196be88ed17b4d
e9a481c76a7921f109882416be1f24a0cbf82dc8
/particle.cpp
088f8764a8de83bd527921869450547798a1bf14
[]
no_license
azgurath/GravSim
91d8daa96d1f1ddacb9fbf94f05c34b05738c877
44d6a58ac45de2e37d06e861fc61c5a4135c3770
refs/heads/master
2020-04-13T21:51:59.773419
2016-10-07T16:06:43
2016-10-07T16:06:43
68,053,751
0
0
null
null
null
null
UTF-8
C++
false
false
581
cpp
/** * @file particle.cpp * @author Andrew Hoover * @date 9/20/2016 * @brief Implementation of particle class. * * Implements the constructor for the particle class, * initializing the location, velocity, mass and next * particle to zero. */ #include "particle.h" /** * Constructor, initializes the particle to zero. * * @brief Particle::Particle */ Particle::Particle() { // Set every variable to zero but mass, which is set to 1. x = 0.0; y = 0.0; z = 0.0; angX = 0.0; angY = 0.0; angZ = 0.0; mass = 1.0; next = 0; }
[ "azgurath@gmail.com" ]
azgurath@gmail.com
94bf82f377b4124866a3ca88ebd10f197655c430
f43711e16bf8e16fee28df8376814e14ec6ee10e
/Spoj/absys.cpp
1ff54a6186b9934e4eb0777867096a1309c8ab8c
[]
no_license
kshav/My_codes
5e3ed56b99ba2860462d485b2c2c6cdc485db14a
4337b951454b62010bcc91b8f78db2eb04dcdc67
refs/heads/master
2016-09-06T00:24:47.843220
2014-02-19T12:49:31
2014-02-19T12:49:31
16,978,109
0
1
null
null
null
null
UTF-8
C++
false
false
1,724
cpp
#include<iostream> #include<string.h> using namespace std; int main() { int n,t,l=0,j,m,l1,l2,l3,d,e,f; string k; cin>>n; t=0; while(t<n) { cout<<"Loop: "<<t<<"\n"; getline (cin,k); l=k.size(); char w[l]; for(int i=0;i<l;i++) w[i]=0; l1=l2=l3=0; d=e=f=0; m=0; j=0; for(int i=0;i<l;i++) { if(k[i]!=' ') { w[j]=k[i]; j++; } } m=j-1; for(int i=0;i<=m;i++) { if(w[i]=='m') l1=i; else if(w[i]=='+') l2=i; else if(w[i]=='=') l3=i; } //cout<<l1<<" "<<l2<<" "<<l3<<"\n"; if(l1>l2 && l1>l3) { for(int i=0;i<l2;i++) d=d*10+w[i]-48; for(int i=l2+1;i<l3;i++) e=e*10+w[i]-48; f=e+d; cout<<d<<" + "<<e<<" = "<<f<<"\n"; } else if(l1<l2 && l1<l3) { for(int i=l3+1;i<=m;i++) f=f*10+w[i]-48; for(int i=l2+1;i<l3;i++) e=e*10+w[i]-48; d=f-e; cout<<d<<" + "<<e<<" = "<<f<<"\n"; } else if(l1>l2 && l1<l3) { for(int i=l3+1;i<=m;i++) f=f*10+w[i]-48; for(int i=0;i<l2;i++) d=d*10+w[i]-48; e=f-d; cout<<d<<" + "<<e<<" = "<<f<<"\n"; } t++; } system("pause"); return 0; }
[ "kshav1908@gmail.com" ]
kshav1908@gmail.com
9a111d6e64325e4e3603cb95d8193632f032e231
d439909a41a1fcce6c859d1022c145d736d06f73
/aten/src/ATen/native/TensorConversions.cpp
71690c4bf2d17b6aac54d029a02c4a025203b76a
[ "BSD-3-Clause", "LicenseRef-scancode-generic-cla", "BSL-1.0", "Apache-2.0", "BSD-2-Clause" ]
permissive
MarcelRaschke/pytorch-2
f19f41f8dc072bd3c387b9fada8a998f10cb235a
a346a18150866dd62c9bacbca817d2d44148b74d
refs/heads/master
2023-05-12T02:48:04.840889
2022-03-16T15:19:41
2022-03-16T15:19:41
159,927,967
1
1
NOASSERTION
2023-04-04T00:54:40
2018-12-01T09:16:04
C++
UTF-8
C++
false
false
12,927
cpp
#include <ATen/ATen.h> #include <ATen/NativeFunctions.h> #include <c10/util/Optional.h> #include <ATen/quantized/Quantizer.h> #include <c10/core/impl/DeviceGuardImplInterface.h> namespace at { namespace native { // Take a Device that may not have device_index set (i.e., having it as -1 // representing the current device) and return the corresponding Device // according to the actual device at the time of this function call. No-op // if the device_index is set. static inline Device ensure_has_index(Device device) { if (device.is_cpu() || device.has_index()) { return device; } const c10::impl::DeviceGuardImplInterface* impl = c10::impl::getDeviceGuardImpl(device.type()); return impl->getDevice(); } static inline optional<Device> ensure_has_index(optional<Device> device) { if (!device.has_value()) { return nullopt; } return ensure_has_index(device.value()); } Tensor _to_copy( const Tensor& self, c10::optional<ScalarType> dtype, c10::optional<Layout> layout, c10::optional<Device> device, c10::optional<bool> pin_memory, bool non_blocking, c10::optional<c10::MemoryFormat> optional_memory_format) { TORCH_CHECK(!layout.has_value() || self.layout() == layout.value(), "to(options) doesn't support converting to a different layout, " "but got self.layout being ", self.layout(), " and options.layout set as ", layout.value()); auto options = TensorOptions() .dtype(dtype) .layout(layout) .device(device) .pinned_memory(pin_memory); if (options.has_device()) { options = options.device(ensure_has_index(options.device())); } // memory_format is handled separately due to MemoryFormat::Preserve logic options = self.options().merge_in(options).memory_format(c10::nullopt); auto memory_format = optional_memory_format.value_or(MemoryFormat::Preserve); bool pin_out = (non_blocking && self.is_cuda() && options.device().is_cpu() && (options.layout() == c10::kStrided)); if (memory_format == MemoryFormat::Preserve) { if (self.is_non_overlapping_and_dense() && options.device().supports_as_strided()) { Tensor r; if (self.is_quantized()) { r = at::empty_quantized(self.sizes(), self, options); at::QuantizerPtr quantizer = r.quantizer(); r.copy_(self, non_blocking); set_quantizer_(r, quantizer); } else { r = at::empty_strided( self.sizes(), self.strides(), options.pinned_memory(pin_out)); r.copy_(self, non_blocking); } return r; } else { memory_format = self.suggest_memory_format(); } } // See Note [Explicit nullopt MemoryFormat argument] auto r = at::empty(self.sizes(), options.memory_format(memory_format).pinned_memory(pin_out), c10::nullopt); r.copy_(self, non_blocking); return r; } template <typename T> static inline bool is_null_or_equal_to(const c10::optional<T>& test, const T& value) { if (!test.has_value()) { return true; } return test.value() == value; } // NOTE: static runtime's to_maybe_copy_out relies on details of this // check; if you change how it works, please update static runtime as // well. bool to_will_alias( const Tensor& self, c10::optional<ScalarType> dtype, c10::optional<Layout> layout, c10::optional<Device> device, bool copy, c10::optional<c10::MemoryFormat> optional_memory_format) { auto memory_format = optional_memory_format.value_or(MemoryFormat::Preserve); return is_null_or_equal_to(dtype, self.dtype().toScalarType()) && is_null_or_equal_to(layout, self.layout()) && is_null_or_equal_to(device, self.device()) && !copy && (memory_format == MemoryFormat::Preserve || self.suggest_memory_format() == memory_format); } static inline Tensor to_impl( const Tensor& self, c10::optional<ScalarType> dtype, c10::optional<Layout> layout, c10::optional<Device> device, c10::optional<bool> pin_memory, bool non_blocking, bool copy, c10::optional<c10::MemoryFormat> optional_memory_format) { // fast path if (to_will_alias(self, dtype, layout, device, copy, optional_memory_format)) { return self; } return at::_to_copy( self, dtype, layout, device, pin_memory, non_blocking, optional_memory_format); } // If input tensor is fp32, cast it to fp16, otherwise leave it alone. // (this is intended to be used internally by the JIT autocast implementation) Tensor _autocast_to_reduced_precision(const Tensor& self, bool cuda_enabled, bool cpu_enabled, ScalarType cuda_dtype, ScalarType cpu_dtype) { if (self.dtype() == at::ScalarType::Float && ((self.device().is_cuda() && cuda_enabled) || (self.device().is_cpu() && cpu_enabled)) ) { at::ScalarType target = at::ScalarType::Undefined; if (self.device().is_cuda()) { target = cuda_dtype; } else if (self.device().is_cpu()) { target = cpu_dtype; } TORCH_INTERNAL_ASSERT(target != at::ScalarType::Undefined, "_autocast_to_reduced_precision requires legit ScalarType argument for given device"); return to_impl( self, target, c10::nullopt, c10::nullopt, c10::nullopt, false, false, c10::nullopt); } else { return self; } } // If input tensor is fp16, cast it to fp32, otherwise leave it alone. // (this is intended to be used internally by the JIT autocast implementation) Tensor _autocast_to_full_precision(const Tensor& self, bool cuda_enabled, bool cpu_enabled) { if ((self.dtype() == at::ScalarType::Half || self.dtype() == at::ScalarType::BFloat16) && ((self.device().is_cuda() && cuda_enabled) || (self.device().is_cpu() && cpu_enabled)) ) { return to_impl( self, at::ScalarType::Float, c10::nullopt, c10::nullopt, c10::nullopt, false, false, c10::nullopt); } else { return self; } } Tensor to( const Tensor& self, c10::optional<ScalarType> dtype, c10::optional<Layout> layout, c10::optional<Device> device, c10::optional<bool> pin_memory, bool non_blocking, bool copy, c10::optional<c10::MemoryFormat> optional_memory_format ) { return to_impl( self, dtype, layout, ensure_has_index(device), pin_memory, non_blocking, copy, optional_memory_format); } Tensor to(const Tensor& self, Device device, ScalarType dtype, bool non_blocking, bool copy, c10::optional<c10::MemoryFormat> optional_memory_format) { return to_impl( self, dtype, nullopt, ensure_has_index(device), nullopt, non_blocking, copy, optional_memory_format); } Tensor to(const Tensor& self, ScalarType dtype, bool non_blocking, bool copy, c10::optional<c10::MemoryFormat> optional_memory_format) { return to_impl( self, dtype, nullopt, nullopt, nullopt, non_blocking, copy, optional_memory_format); } Tensor to(const Tensor& self, const Tensor& other, bool non_blocking, bool copy, c10::optional<c10::MemoryFormat> optional_memory_format) { auto options = other.options(); return to_impl( self, options.dtype().toScalarType(), options.layout(), options.device(), options.pinned_memory(), non_blocking, copy, optional_memory_format); } // This op is important primarily for lazy / graph-based backends. // While this vanilla implementation loops through each tensor and independently converts it to cpu, // a lazy backend like XLA might need to tell sync updates across tensors. std::vector<Tensor> _to_cpu(TensorList tensors) { std::vector<Tensor> cpu_tensors; for (const auto& t : tensors) { cpu_tensors.push_back(t.cpu()); } return cpu_tensors; } Tensor to_dense_backward(const Tensor& grad, const Tensor& input_) { AT_ASSERT(input_.layout() != c10::kStrided); if (input_.layout() == c10::kSparse) { auto input = input_.coalesce(); return grad.sparse_mask(input); } else if (input_.layout() == c10::kMkldnn) { return grad.to_mkldnn(input_.scalar_type()); } else { AT_ERROR("Unsupported input layout: ", input_.layout()); } } Tensor to_mkldnn_backward(const Tensor& grad, const Tensor& input_) { AT_ASSERT(input_.layout() == c10::kStrided); return grad.to_dense(input_.scalar_type()); } // Computes the strides for view_dtype output when the view dtype is // smaller than the original dtype inline DimVector compute_strides_for_view_dtype_downsize(IntArrayRef old_strides, int64_t size_ratio, ScalarType old_dtype, ScalarType new_dtype) { const int64_t ndim = old_strides.size(); TORCH_CHECK( old_strides[ndim - 1] == 1, "self.stride(-1) must be 1 to view ", old_dtype, " as ", new_dtype, " (different element sizes), but got ", old_strides[ndim - 1]); DimVector new_strides(ndim); for (int64_t dim_idx = 0; dim_idx < ndim - 1; dim_idx++) { new_strides[dim_idx] = old_strides[dim_idx] * size_ratio; } new_strides[ndim - 1] = 1; return new_strides; } // Computes the strides for view_dtype output when the view dtype is // larger than the original dtype inline DimVector compute_strides_for_view_dtype_upsize(IntArrayRef old_strides, int64_t size_ratio, ScalarType old_dtype, ScalarType new_dtype) { const int64_t ndim = old_strides.size(); TORCH_CHECK( old_strides[ndim - 1] == 1, "self.stride(-1) must be 1 to view ", old_dtype, " as ", new_dtype, " (different element sizes), but got ", old_strides[ndim - 1]); DimVector new_strides(ndim); for (int64_t dim_idx = 0; dim_idx < ndim - 1; dim_idx++) { TORCH_CHECK( (old_strides[dim_idx] % size_ratio) == 0, "self.stride(", dim_idx, ") must be divisible by ", size_ratio, " to view ", old_dtype, " as ", new_dtype, " (different element sizes), ", "but got ", old_strides[dim_idx]); new_strides[dim_idx] = old_strides[dim_idx] / size_ratio; } new_strides[ndim - 1] = 1; return new_strides; } Tensor view_dtype(const Tensor& self, ScalarType dtype) { if (self.scalar_type() == dtype) { return self; } const auto type_meta = c10::scalarTypeToTypeMeta(dtype); TORCH_CHECK(!self.is_conj(), "torch.Tensor.view is not supported for conjugate view tensors when converting to a different dtype."); TORCH_CHECK(!self.is_neg(), "torch.Tensor.view is not supported for tensors with negative bit set when converting to a different dtype."); int64_t self_element_size = self.element_size(); int64_t new_element_size = static_cast<int64_t>(type_meta.itemsize()); Storage storage = self.storage(); auto new_tensor = detail::make_tensor<TensorImpl>( std::move(storage), self.key_set(), type_meta); auto* impl = new_tensor.unsafeGetTensorImpl(); if (self_element_size == new_element_size) { impl->set_storage_offset(self.storage_offset()); impl->set_sizes_and_strides(self.sizes(), self.strides()); } else if (self.dim() == 0) { TORCH_CHECK(false, "self.dim() cannot be 0 to view ", self.scalar_type(), " as ", dtype, " (different element sizes)"); } else if (self_element_size > new_element_size) { // Downsizing element size int64_t size_ratio = self_element_size / new_element_size; auto new_strides = compute_strides_for_view_dtype_downsize( self.strides(), size_ratio, self.scalar_type(), dtype); auto old_sizes = self.sizes(); DimVector new_sizes(self.dim()); std::copy(old_sizes.begin(), old_sizes.end(), new_sizes.begin()); new_sizes[self.dim() - 1] *= size_ratio; auto new_storage_offset = size_ratio * self.storage_offset(); impl->set_storage_offset(new_storage_offset); impl->set_sizes_and_strides(new_sizes, new_strides); } else { // Upsizing element size int64_t size_ratio = new_element_size / self_element_size; TORCH_CHECK( (self.size(-1) % size_ratio) == 0, "self.size(-1) must be divisible by ", size_ratio, " to view ", self.scalar_type(), " as ", dtype, " (different element sizes), ", "but got ", self.size(-1)); TORCH_CHECK( (self.storage_offset() % size_ratio) == 0, "self.storage_offset() must be divisible by ", size_ratio, " to view ", self.scalar_type(), " as ", dtype, " (different element sizes), but got ", self.storage_offset()); auto new_strides = compute_strides_for_view_dtype_upsize( self.strides(), size_ratio, self.scalar_type(), dtype); auto old_sizes = self.sizes(); DimVector new_sizes(self.dim()); std::copy(old_sizes.begin(), old_sizes.end(), new_sizes.begin()); new_sizes[self.dim() - 1] /= size_ratio; auto new_storage_offset = self.storage_offset() / size_ratio; impl->set_storage_offset(new_storage_offset); impl->set_sizes_and_strides(new_sizes, new_strides); } return new_tensor; } }} // namespace at::native
[ "facebook-github-bot@users.noreply.github.com" ]
facebook-github-bot@users.noreply.github.com
8793eca0f56ee2d2d85396062f7b95f711e372cc
5d997fe0ccdcff70d2f7933f4c7f11d9c637fd86
/modules/core/mgmt/rwuagent/src/rwuagent_confd_workspace.cpp
979eb4747e5091860b0e7702035753be465835ff
[ "Apache-2.0" ]
permissive
gonotes/RIFT.ware
02e1ea2d11aa99f5a65be6d686f2afabd3284070
45884f1e2b7b0028afae19eb0243dbfeb71edaff
refs/heads/master
2021-01-18T02:50:07.858451
2016-06-02T14:55:14
2016-06-02T14:55:14
null
0
0
null
null
null
null
UTF-8
C++
false
false
9,770
cpp
/* * * (c) Copyright RIFT.io, 2013-2016, All Rights Reserved * */ /* * @file rwuagent_confd_workspace.cpp * * Management Confd workspace handler */ #include <string> #include <sstream> #include <boost/algorithm/string.hpp> #include "rw_schema_defs.h" #include "rwuagent_mgmt_system.hpp" #include "rw-manifest.pb-c.h" #define CONFD_BASE_PATH ("/usr/local/confd") #define CONFD_LOG_PATH ("/var/confd/log/") using namespace rw_uagent; namespace fs = boost::filesystem; ConfdWorkspaceMgr::ConfdWorkspaceMgr(const ConfdMgmtSystem* mgmt, Instance* inst): mgmt_(mgmt), instance_(inst), memlog_buf_( inst->get_memlog_inst(), "ConfdWorkspaceMgr", reinterpret_cast<intptr_t>(this)) { } rw_status_t ConfdWorkspaceMgr::generate_config_file() { RWMEMLOG(memlog_buf_, RWMEMLOG_MEM2, "generate config file"); auto prototype_conf_file = get_rift_install() + "/" + RW_SCHEMA_CONFD_PROTOTYPE_CONF; auto confd_dir = mgmt_->mgmt_dir(); confd_conf_dom_ = std::move(instance_->xml_mgr()->create_document_from_file( prototype_conf_file.c_str(), false)); if (!confd_conf_dom_) { RW_MA_INST_LOG (instance_, InstanceError, "Failed to convert prototype conf file to DOM"); return RW_STATUS_FAILURE; } if (!set_schema_load_path()) { RW_MA_INST_LOG (instance_, InstanceError, "Failed to set load path"); return RW_STATUS_FAILURE; } set_directory_path("", "stateDir", confd_dir + "/var/confd/state"); set_directory_path("cdb", "dbDir", confd_dir + "/var/confd/cdb"); set_directory_path("rollback", "directory", confd_dir + "/var/confd/rollback"); set_directory_path( "netconf/capabilities/url/file", "rootDir", confd_dir + "/var/confd/state"); set_directory_path( "aaa", "sshServerKeyDir", get_rift_install() + "/usr/local/confd/etc/confd/ssh"); auto confd_log_path = confd_dir + CONFD_LOG_PATH; set_directory_path("logs/webuiAccessLog", "dir", confd_log_path); set_feature("cli", true); set_feature("rest", true); set_feature("snmpAgent", false); auto vcs_inst = instance_->rwvcs(); RwManifest__YangEnum__NetconfTrace__E trace_e = RW_MANIFEST_NETCONF_TRACE_AUTO; if (vcs_inst && vcs_inst->pb_rwmanifest && vcs_inst->pb_rwmanifest->init_phase && vcs_inst->pb_rwmanifest->init_phase->settings && vcs_inst->pb_rwmanifest->init_phase->settings->mgmt_agent && vcs_inst->pb_rwmanifest->init_phase->settings->mgmt_agent->has_netconf_trace) { trace_e = vcs_inst->pb_rwmanifest->init_phase->settings->mgmt_agent->netconf_trace; } switch (trace_e) { case RW_MANIFEST_NETCONF_TRACE_ENABLE: set_feature("logs/netconfTraceLog", true); break; case RW_MANIFEST_NETCONF_TRACE_DISABLE: set_feature("logs/netconfTraceLog", false); break; default: { if (is_production()) { set_feature("logs/netconfTraceLog", false); } else { set_feature("logs/netconfTraceLog", true); } } }; std::map<const char*, const char*> log_types = { {"logs/confdLog/file", "confd.log"}, {"logs/developerLog/file", "devel.log"}, {"logs/auditLog/file", "audit.log"}, {"logs/netconfLog/file", "netconf.log"}, {"logs/snmpLog/file", "snmp.log"} }; for (auto& log_type : log_types) { set_directory_path(log_type.first, "name", confd_log_path + log_type.second); } set_directory_path("logs/netconfTraceLog", "filename", confd_log_path + "netconf.trace"); set_directory_path("datastores/candidate", "filename", confd_dir + "/var/confd/candidate/candidate.db"); set_notif_directory_path( "notifications/eventStreams/stream/builtinReplayStore/maxSize", "dir", confd_dir); return confd_conf_dom_->to_file((confd_dir + "/rw_confd.conf").c_str()); } bool ConfdWorkspaceMgr::set_schema_load_path() { RWMEMLOG(memlog_buf_, RWMEMLOG_MEM2, "set schema load path"); XMLNode* root_node = confd_conf_dom_->get_root_node(); RW_ASSERT (root_node); XMLNode* load_path = root_node->find("loadPath"); if (!load_path) { load_path = root_node->add_child("loadPath"); RW_ASSERT (load_path); } auto latest_ver_dir = get_rift_install() + "/" + RW_SCHEMA_VER_LATEST_NB_PATH + "/fxs"; if (!fs::exists(latest_ver_dir)) { RW_MA_INST_LOG (instance_, InstanceError, "Schema directory does not exist."); return false; } auto confd_yang_dir = get_rift_install() + "/usr/local/confd/etc/confd/"; XMLNode* dir = load_path->add_child("dir", confd_yang_dir.c_str()); RW_ASSERT(dir); XMLNode* dir2 = load_path->add_child("dir", latest_ver_dir.c_str()); RW_ASSERT(dir2); return true; } void ConfdWorkspaceMgr::set_directory_path( const std::string& node_path, const std::string& elem_name, const std::string& elem_value) { RWMEMLOG(memlog_buf_, RWMEMLOG_MEM2, "set directory path"); std::vector<std::string> path_vec; if (node_path.length()) { boost::split(path_vec, node_path, boost::is_any_of("/")); } XMLNode* root_node = confd_conf_dom_->get_root_node(); RW_ASSERT (root_node); XMLNode* node = root_node; for (auto& path : path_vec) { node = node->find(path.c_str()); RW_ASSERT (node); } XMLNode* child_node = node->add_child(elem_name.c_str(), elem_value.c_str()); RW_ASSERT (child_node); } void ConfdWorkspaceMgr::set_notif_directory_path( const std::string& node_path, const std::string& elem_name, const std::string& elem_value) { RWMEMLOG(memlog_buf_, RWMEMLOG_MEM2, "set notif directory path"); std::vector<std::string> path_vec; if (node_path.length()) { boost::split(path_vec, node_path, boost::is_any_of("/")); } XMLNode* root_node = confd_conf_dom_->get_root_node(); RW_ASSERT (root_node); XMLNode* node = root_node; for (auto& path : path_vec) { node = node->find(path.c_str()); RW_ASSERT (node); } XMLNode* sib_node = node->insert_before(elem_name.c_str(), elem_value.c_str()); RW_ASSERT (sib_node); } void ConfdWorkspaceMgr::set_feature(const std::string& conf_node, bool value) { RWMEMLOG(memlog_buf_, RWMEMLOG_MEM2, "set feature"); std::vector<std::string> path_vec; if (conf_node.length()) { boost::split(path_vec, conf_node, boost::is_any_of("/")); } XMLNode* root_node = confd_conf_dom_->get_root_node(); RW_ASSERT (root_node); XMLNode* node = root_node; for (auto& path : path_vec) { node = node->find(path.c_str()); if (!node) break; } if (!node) { std::string log_str; log_str = "Feature path does not exist in prototype config: " + conf_node; RW_MA_INST_LOG (instance_, InstanceError, log_str.c_str()); return; } XMLNode* enabled = nullptr; if (value) { enabled = node->add_child("enabled", "true"); } else { enabled = node->add_child("enabled", "false"); } RW_ASSERT (enabled); } bool ConfdWorkspaceMgr::create_confd_workspace() { RWMEMLOG(memlog_buf_, RWMEMLOG_MEM2, "create confd workspace"); auto rift_install = get_rift_install(); auto confd_dir = mgmt_->mgmt_dir(); std::array<const char*, 5> sub_dirs = { "/var/confd/candidate", "/var/confd/cdb", "/var/confd/log", "/var/confd/rollback", "/var/confd/state" }; try { for (auto sdir : sub_dirs) { auto dest_dir = confd_dir + sdir; if (!fs::create_directories(dest_dir)) { std::string log_str; log_str = "Failed to create directory: " + dest_dir + ". "; log_str += std::strerror(errno); RW_MA_INST_LOG (instance_, InstanceError, log_str.c_str()); return false; } } } catch (const fs::filesystem_error& e) { RW_MA_INST_LOG (instance_, InstanceError, e.what()); return false; } try { // Copy aaa_init.xml file fs::copy_file(rift_install + CONFD_BASE_PATH + "/var/confd/cdb/aaa_init.xml", confd_dir + "/var/confd/cdb/aaa_init.xml"); // Install the oper user aaa restrictions fs::copy_file(rift_install + "/usr/data/security/oper_user_restrictions.xml", confd_dir + "/var/confd/cdb/oper_user_restrictions.xml"); } catch (const fs::filesystem_error& e) { RW_MA_INST_LOG (instance_, InstanceError, e.what()); return false; } return true; } rw_status_t ConfdWorkspaceMgr::create_mgmt_directory() { RWMEMLOG(memlog_buf_, RWMEMLOG_MEM2, "create mgmt directory"); auto confd_dir = mgmt_->mgmt_dir(); if (!confd_dir.length()) { RW_MA_INST_LOG (instance_, InstanceCritInfo, "Workspace not yet created. Retrying."); return RW_STATUS_FAILURE; } if (fs::exists(confd_dir)) { auto confd_init_file = confd_dir + "/" + CONFD_INIT_FILE; if (!fs::exists(confd_init_file)) { RW_MA_INST_LOG (instance_, InstanceCritInfo, "Confd init file not found. Perhaps confd was not initialized" " completely in its previous run. Deleting existing confd directory."); try { fs::remove_all(confd_dir); } catch (const fs::filesystem_error& e) { RW_MA_INST_LOG (instance_, InstanceError, e.what()); } } else { std::string log_str; log_str = "Confd workspace is " + confd_dir; RW_MA_INST_LOG (instance_, InstanceInfo, log_str.c_str()); return RW_STATUS_SUCCESS; } } // Create confd workspace if (create_confd_workspace() && (generate_config_file() == RW_STATUS_SUCCESS)) { std::string log_str; log_str = "Confd workspace " + confd_dir + " created successfully"; RW_MA_INST_LOG (instance_, InstanceCritInfo, log_str.c_str()); } else { RW_MA_INST_LOG (instance_, InstanceError, "Failed to create confd workspace"); return RW_STATUS_FAILURE; } return RW_STATUS_SUCCESS; }
[ "Wei.Wang@riftio.com" ]
Wei.Wang@riftio.com
cc416b4a1da592ad1df0bd2eb6d4279706e5b7c5
b5e8a7b5798d6cb124aaf7172d78478eb72bd733
/usaco/agrinet.cpp
7c6c868bfbacd9cdf2692bb6b155c8326359258b
[]
no_license
manolismih/OJsolutions
8e62b29ac604077473926dd63d8a636181db11be
809999d34036033e3a8757518588bf5847ca7f5f
refs/heads/master
2022-05-01T01:19:52.014312
2022-03-10T13:37:13
2022-03-10T13:37:13
244,162,474
2
0
null
null
null
null
UTF-8
C++
false
false
954
cpp
/* ID:manolis2 PROG:agrinet LANG:C++ */ #include <cstdio> #include <queue> using namespace std; FILE *fin = fopen("agrinet.in","r"), *fout = fopen("agrinet.out","w"); struct node{ int komvos,dist; }; inline bool operator<(node a, node b) { return a.dist>b.dist; } inline node tonode(int komvos, int dist) { node ret={komvos,dist}; return ret; } int n,amatrix[100][100], msp=0; priority_queue<node> oura; bool visited[100]; int main() { fscanf(fin,"%i",&n); for (int i=0; i<n; i++) for (int j=0; j<n; j++) fscanf(fin,"%i",&amatrix[i][j]); oura.push(tonode(0,0)); int v; for (int i=0; i<n; i++) { v = oura.top().komvos; if (visited[v]) { i--; oura.pop(); continue; } visited[v] = true; msp += oura.top().dist; oura.pop(); for (int j=0; j<n; j++) if (amatrix[v][j]) oura.push(tonode(j,amatrix[v][j])); } fprintf(fout,"%i\n",msp); return 0; }
[ "manolismih@windowslive.com" ]
manolismih@windowslive.com
5a4d15edf9888432ec25b410605ab1ce8971a3ec
02987503becabd24aa359d6ceabcb332ad8c6302
/sgpp-1.1.0/base/src/sgpp/base/grid/storage/hashmap/SerializationVersion.hpp
40e63bcadc80d4d3005cb22dde9fcb885637e7bc
[]
no_license
HappyTiger1/Sparse-Grids
a9c07527481ee28fe24abed6dad378ca9fc6d466
2832b262c1aeaa25312a3f7e48c5a67c90d183a5
refs/heads/master
2020-05-07T14:06:20.673900
2016-08-08T17:57:12
2016-08-08T17:57:12
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,099
hpp
// Copyright (C) 2008-today The SG++ project // This file is part of the SG++ project. For conditions of distribution and // use, please see the copyright notice provided with SG++ or at // sgpp.sparsegrids.org #ifndef SERIALIZATIONVERSION_HPP #define SERIALIZATIONVERSION_HPP /** * This specifies the available serialization versions * * Version 1: classic verions without leaf proeperty * Version 2: every gridpoint is extended by one boolean that specifies if it's a leaf * Version 3: added support for the grid's bounding box * Version 4: needed for import of the Bonner's Sparse Grid Definition files; same as Ver 3 * but without leaf property, NOT FOR EXPORT * Version 5: differentiate BoundingBox and Stretching, added support for stretching. * Version 6: added PointDistribution to HashGridIndex * ("Normal" with x = i*2^(-l) and "ClenshawCurtis") * Version 7: PointDistribution changed from enum to enum class * Version 8: Add custom boundaryLevel (>= 1) for LinearBoundaryGrid etc. */ #define SERIALIZATION_VERSION 7 #endif /* SERIALIZATIONVERSION_HPP */
[ "alexander.atanasov@yale.edu" ]
alexander.atanasov@yale.edu
3d9409d1f16e5aabf195edcaad47714a9c3b9f9e
96391d9314dab2973ec764aaa75bea194743ca2b
/client/game/debug.cpp
ca90e12426b4358e8b5d1f2e7986aa3705356bc6
[]
no_license
0xF0F1FA/SA-MP
155d6dbb8709e2251469c5c1771d76d2465110e6
318bcd6371a3de6b51b4ce06b287797a12b97bfb
refs/heads/master
2023-08-15T16:07:49.775822
2021-09-22T13:23:50
2021-09-22T13:23:50
null
0
0
null
null
null
null
UTF-8
C++
false
false
32,722
cpp
//---------------------------------------------------------- // // SA:MP Multiplayer Modification For GTA:SA // Copyright 2004-2005 SA:MP team // // Version: $Id: debug.cpp,v 1.27 2006/05/08 20:33:58 kyeman Exp $ // //---------------------------------------------------------- #include <windows.h> #include <stdio.h> #include "../main.h" #include "debug.h" #include "util.h" #include "keystuff.h" #include "aimstuff.h" static int iGameDebugType=0; static DWORD dwDebugEntity1=0; static DWORD dwDebugEntity2=0; //#define PARAM_SKIP(l) szToken=strtok(l,",") //#define PARAM_FLOAT(l,f,d) szToken=strtok(l,","); f=atof(szToken) //#define PARAM_INT32(l,i,d) szToken=strtok(l,","); i=(int)atol(szToken) #define PARAM_SKIP(l) szToken=strtok_s(l,",",&szContext) #define PARAM_FLOAT(l,f,d) szToken=strtok_s(l,",",&szContext); f=(szToken)?(strtof(szToken,NULL)):(d) #define PARAM_INT32(l,i,d) szToken=strtok_s(l,",",&szContext); i=(szToken)?((int)strtol(szToken,NULL,0)):(d) static VECTOR g_vecPos; static CObjectPool* g_pObjectPool = NULL; static BYTE g_byteObjectCount = 0; #ifdef _DEBUG static int debug_draw_top = 0; // screen buffer for debug text #define NUM_SCREEN_LINES 35 static PCHAR screen_buf[NUM_SCREEN_LINES]; extern CAMERA_AIM* pcaInternalAim; extern BYTE* pbyteCameraMode; //extern INCAR_SYNC_DATA DebugSync; //extern BOOL bDebugUpdate; //extern char *aScanListMemory; extern float fFarClip; //---------------------------------------------------------- void GameDebugDrawNextLine(PCHAR szText, DWORD dwColor) { RECT rect; rect.top = debug_draw_top; rect.left = 30; //rect.bottom = debug_draw_top+16; //rect.right = 600; pDefaultFont->RenderText(szText,rect,dwColor); debug_draw_top+=16; } //---------------------------------------------------------- struct tTaskInfo { unsigned int id; const char *name; }; tTaskInfo taskInfosById[] = { { 0x191, "AutoAnimation" }, { 0x1AA, "GHands" }, { 0x3F8, "Fight" }, { 0x3F9, "UseGun" }, { 0x3F0, "TakeDamage" }, { 0x3E8, "KillActorMaybe" }, { 0x3FE, "DriveByFreeAim" }, { 0x0CB, "ActorOnFoot" }, { 0x0CC, "StayPut" }, { 0x0D4, "WastedDie" }, { 0x0D9, "Wasted" }, { 0x0DA, "FallShotDown" }, { 0x0DB, "Tired" }, { 0x0DF, "SitDown" }, { 0x0DD, "SitIdle" }, { 0x0E7, "SunBathe" }, { 0x0E9, "PedAttrRel1" }, { 0x0EB, "InterestingRandom" }, { 0x10D, "TriggerLookAt" }, { 0x640, "PhoneInOut" }, { 0x644, "Goggles" }, { 0x10C, "Swim" }, { 0x11C, "FallParachute" }, { 0x103, "PedAttrRel2" }, { 0x104, "PedAttrRel3" }, { 0x2C9, "EnterCarDriver" }, { 0x2C8, "EnterCarPassenger" }, { 0x2C0, "LeaveCar" }, { 0x2C5, "DriveCar" }, { 0x2C6, "DriveToPoint" }, { 0x2B8, "EnterAnyCarDriver" }, { 0x2BC, "EnterAnyCarPassenger" }, { 0x1F8, "JumpActorForDriveBy" }, { 0x06D, "WaterTurretSomething" }, { 0x06E, "TreatAccident" }, { 0x38C, "FleePoint" }, { 0x38D, "FleeEntity" }, { 0x38E, "SmartFleePoint" }, { 0x38F, "SmartFleeEntity" }, { 0x4B1, "GangsRel" }, { 0x4B5, "HassleVehicle" }, { 0x101, "StareAtPed" }, { 0x4BA, "SignalAtPed" }, { 0x4BB, "PassObject" }, { 0x51D, "Prozzy" }, { 0x38B, "FollowActor" }, { 0x386, "AchvHeading" }, { 0x387, "GoToPoint" }, { 0x395, "AvoidOthPed" }, { 0x3AB, "AvoidEntity" }, { 0x393, "GoToAttractor" }, { 0x398, "RotateToActor" }, { 0x3A4, "OpenDoor" }, { 0x3A7, "InvDisturb" }, { 0x389, "ExecutePath" }, { 0x57C, "BeInShop" }, { 0x580, "SitInChair" }, { 0x0D0, "TakeDamageFall" }, { 0x0F0, "Fall" }, { 0x0D3, "Jump" }, { 0x517, "Jetpack" }, { 0x4B3, "GreetPartner" }, { 0x4B4, "CommandTask" }, { 0x4B9, "BeInCouple" }, { 0x000, "OnFoot" }, { 0x12E, "ShowFinger" }, { 0x131, "InitialState" }, { 0x132, "ShowFingerNoPed" }, { 0x258, "InvDeadPed" }, { 0x0C9, "WalkThruDoor" }, { 0x2CF, "DriveCarSpecial" }, { 0x0CA, "InitialStateInternal" }, { 0x2D9, "PedResp" }, { 0x2CA, "BailFromCar" }, { 0x259, "ThreatResp" }, { 0x19F, "Crouch" }, { 0x0F4, "GoToPointWithinRadius" }, { 0x3A6, "WalkAnimation" }, // This takes an angle }; tTaskInfo taskInfosByVTbl[] = { { 0x86D528, "ScriptAnimation" }, { 0x86D570, "PedAnimation" }, { 0x86DB70, "HitFromBack" }, { 0x86DBA4, "HitFromLeft" }, { 0x86DBD8, "HitFromRight" }, { 0x86DC10, "HitByGunFromFront" }, { 0x86DC4C, "HitByGunFromRear" }, { 0x86DC88, "HitByGunFromLeft" }, { 0x86DCC4, "HitByGunFromRight" }, { 0x86E5EC, "HitFromFront" }, { 0x86F168, "HitFromBehind" }, { 0x86F1A0, "HitWall" }, { 0x86F45C, "Absiel" }, { 0x86FDD4, "WalkInSeq" }, // Same ID as GoToPoint { 0x85A0D0, "Cover" }, { 0x85A100, "ScratchHead" }, { 0x85A134, "UseATM" }, { 0x85A164, "LookAbout" }, { 0x85A29C, "HandsUp" }, { 0x86C78C, "Chat" }, }; const char* GetTaskNameFromTask(DWORD *task) { if (task == NULL) return "Null"; unsigned int vtbl = task[0]; for(int i=0; i<sizeof(taskInfosByVTbl)/sizeof(tTaskInfo); i++) { if (taskInfosByVTbl[i].id == vtbl) return taskInfosByVTbl[i].name; } unsigned int type = (unsigned)GetTaskTypeFromTask(task); for(int i=0; i<sizeof(taskInfosById)/sizeof(tTaskInfo); i++) { if (taskInfosById[i].id == type) return taskInfosById[i].name; } return "Unknown"; } //---------------------------------------------------------- void PrintInfoForTask(char *name, DWORD *task) { CHAR line_buffer[512]; sprintf_s( line_buffer, "%s: S: 0x%p VT: 0x%08X T: %s (0x%x)", name,task,task?*task:0,GetTaskNameFromTask(task),GetTaskTypeFromTask(task)); GameDebugDrawNextLine(line_buffer,D3DCOLOR_ARGB(255,255,255,255)); while(task = GetNextTaskFromTask(task)) { sprintf_s( line_buffer, "%s: S: 0x%p VT: 0x%08X T: %s (0x%x)", name,task,task?*task:0,GetTaskNameFromTask(task),GetTaskTypeFromTask(task)); GameDebugDrawNextLine(line_buffer,D3DCOLOR_ARGB(255,255,255,255)); } } //---------------------------------------------------------- void GameDebugDrawTaskInfo() { PED_TYPE *actor=0; PED_TYPE *player=0; player = GamePool_FindPlayerPed(); if(player && player->pTarget) { dwDebugEntity1 = (DWORD)player->pTarget; } if(dwDebugEntity1 != 0) { actor = (PED_TYPE *)dwDebugEntity1; } else { actor = player; } if (!actor || !actor->Tasks) { dwDebugEntity1 = 0; return; } CHAR line_buffer[512]; // init position for drawing debug_draw_top = 50; sprintf_s(line_buffer,"PlayerPed %u (struct: 0x%p, vtbl: 0x%X)",dwDebugEntity1,actor,actor->entity.vtable); GameDebugDrawNextLine(line_buffer,D3DCOLOR_ARGB(255,90,90,255)); GameDebugDrawNextLine("Displaying Ped Intelligence...",D3DCOLOR_ARGB(255,90,90,255)); GameDebugDrawNextLine("",D3DCOLOR_ARGB(255,255,255,255)); sprintf_s(line_buffer, "Ped: struct: 0x%p, vtbl: 0x%08X", actor->Tasks->pdwPed, actor->Tasks->pdwPed?*(actor->Tasks->pdwPed):0); GameDebugDrawNextLine(line_buffer,D3DCOLOR_ARGB(255,255,255,255)); GameDebugDrawNextLine("",D3DCOLOR_ARGB(255,255,255,255)); GameDebugDrawNextLine("Basic Tasks",D3DCOLOR_ARGB(255,255,90,90)); PrintInfoForTask("Damage",actor->Tasks->pdwDamage); PrintInfoForTask("Fall",actor->Tasks->pdwFallEnterExit); PrintInfoForTask("SwimWasted",actor->Tasks->pdwSwimWasted); PrintInfoForTask("Jump",actor->Tasks->pdwJumpJetPack); PrintInfoForTask("Action",actor->Tasks->pdwAction); GameDebugDrawNextLine("",D3DCOLOR_ARGB(255,255,255,255)); GameDebugDrawNextLine("Extended Tasks",D3DCOLOR_ARGB(255,255,90,90)); PrintInfoForTask("Crouch",actor->Tasks->pdwCrouching); PrintInfoForTask("Fight",actor->Tasks->pdwFighting); PrintInfoForTask("Unk1",actor->Tasks->pdwExtUnk1); PrintInfoForTask("Unk2",actor->Tasks->pdwExtUnk2); PrintInfoForTask("Unk3",actor->Tasks->pdwExtUnk3); PrintInfoForTask("Unk4",actor->Tasks->pdwExtUnk4); } void GameDebugDrawActorInfo() { CHAR line_buffer[512]; PED_TYPE *actor=0; CHAR s[256]; // init position for drawing debug_draw_top = 50; if(dwDebugEntity1 != 0) { actor = GamePool_Ped_GetAt((dwDebugEntity1 << 8) + 1); } else { actor = GamePool_FindPlayerPed(); } if(actor) { sprintf_s(line_buffer,"PlayerPed %u (entity offset: 0x%p)",dwDebugEntity1,actor); GameDebugDrawNextLine(line_buffer,D3DCOLOR_ARGB(255,90,90,255)); sprintf_s(line_buffer,"vtbl: 0x%X",actor->entity.vtable); GameDebugDrawNextLine(line_buffer,D3DCOLOR_ARGB(150,255,255,255)); sprintf_s(line_buffer,"0xB6F178=%f 0xB7CB5C=%f 0x863AC0=%f 0x858FE8=%f", *(float *)0xB6F178,*(float *)0xB7CB5C,*(float *)0x863AC0,*(float *)0x858FE8); GameDebugDrawNextLine(line_buffer,D3DCOLOR_ARGB(150,255,255,255)); sprintf_s(line_buffer,"right: %f %f %f = %f", actor->entity.mat->right.X,actor->entity.mat->right.Y,actor->entity.mat->right.Z, ((actor->entity.mat->right.X * actor->entity.mat->right.X) + (actor->entity.mat->right.Y * actor->entity.mat->right.Y) + (actor->entity.mat->right.Z * actor->entity.mat->right.Z))); GameDebugDrawNextLine(line_buffer,D3DCOLOR_ARGB(150,255,255,255)); sprintf_s(line_buffer,"up: %f %f %f = %f", actor->entity.mat->up.X,actor->entity.mat->up.Y,actor->entity.mat->up.Z, (actor->entity.mat->up.X * actor->entity.mat->up.X) + (actor->entity.mat->up.Y * actor->entity.mat->up.Y) + (actor->entity.mat->up.Z * actor->entity.mat->up.Z)); GameDebugDrawNextLine(line_buffer,D3DCOLOR_ARGB(150,255,255,255)); sprintf_s(line_buffer,"at: %f %f %f", actor->entity.mat->at.X,actor->entity.mat->at.Y,actor->entity.mat->at.Z); GameDebugDrawNextLine(line_buffer,D3DCOLOR_ARGB(150,255,255,255)); sprintf_s(line_buffer,"pos: %f %f %f", actor->entity.mat->pos.X,actor->entity.mat->pos.Y,actor->entity.mat->pos.Z); GameDebugDrawNextLine(line_buffer,D3DCOLOR_ARGB(150,255,255,255)); sprintf_s(line_buffer,"Move: %f %f %f", actor->entity.vecMoveSpeed.X,actor->entity.vecMoveSpeed.Y,actor->entity.vecMoveSpeed.Z); GameDebugDrawNextLine(line_buffer,D3DCOLOR_ARGB(150,255,255,255)); sprintf_s(line_buffer,"Turn: %f %f %f", actor->entity.vecTurnSpeed.X,actor->entity.vecTurnSpeed.Y,actor->entity.vecTurnSpeed.Z); GameDebugDrawNextLine(line_buffer,D3DCOLOR_ARGB(150,255,255,255)); sprintf_s(line_buffer,"Control Flags: 0x%X",actor->entity.nControlFlags); GameDebugDrawNextLine(line_buffer,D3DCOLOR_ARGB(150,255,255,255)); sprintf_s(line_buffer,"Model Index: %u",actor->entity.nModelIndex); GameDebugDrawNextLine(line_buffer,D3DCOLOR_ARGB(150,255,255,255)); sprintf_s(line_buffer,"RW: 0x%p",actor->entity.pdwRenderWare); GameDebugDrawNextLine(line_buffer,D3DCOLOR_ARGB(150,255,255,255)); _itoa_s(actor->dwStateFlags,s,2); sprintf_s(line_buffer,"StateFlags: %s",s); GameDebugDrawNextLine(line_buffer,D3DCOLOR_ARGB(150,255,255,255)); _itoa_s(actor->entity.byteImmunities,s,2); sprintf_s(line_buffer,"Immunities: %s",s); GameDebugDrawNextLine(line_buffer,D3DCOLOR_ARGB(150,255,255,255)); sprintf_s(line_buffer,"Vehicle: 0x%X Intelligence: 0x%p",actor->pVehicle,actor->Tasks); GameDebugDrawNextLine(line_buffer,D3DCOLOR_ARGB(150,255,255,255)); sprintf_s(line_buffer,"MovRot1: %f MovRot2: %f ToRot: %f ActRot: %f CamAdj: %f", actor->fMoveRot1,actor->fMoveRot2,actor->fRotation1,actor->fRotation2,actor->fRotCamAdjust); GameDebugDrawNextLine(line_buffer,D3DCOLOR_ARGB(150,255,255,255)); sprintf_s(line_buffer,"Health: %f",actor->fHealth); GameDebugDrawNextLine(line_buffer,D3DCOLOR_ARGB(150,255,255,255)); sprintf_s(line_buffer,"Action: %u",actor->dwAction); GameDebugDrawNextLine(line_buffer,D3DCOLOR_ARGB(150,255,255,255)); sprintf_s(line_buffer,"PedType: %u",actor->dwPedType); GameDebugDrawNextLine(line_buffer,D3DCOLOR_ARGB(150,255,255,255)); sprintf_s(line_buffer,"PedStatPrim: %d PedStat: %d", Game_PedStatPrim(actor->entity.nModelIndex), Game_PedStat(actor->entity.nModelIndex)); GameDebugDrawNextLine(line_buffer,D3DCOLOR_ARGB(150,255,255,255)); /* sprintf(line_buffer,"Crouch: 0x%X Fighting: 0x%X PedTask: 0x%X", actor->Tasks->pdwCrouching, actor->Tasks->pdwFighting, actor->Tasks->pdwPed); GameDebugDrawNextLine(line_buffer,D3DCOLOR_ARGB(150,255,255,255));*/ DWORD dwPlayerInfo = actor->dwPlayerInfoOffset; float fAimZ; DWORD dwAnimSet; _asm mov eax, dwPlayerInfo _asm mov ebx, [eax+84] _asm mov fAimZ, ebx _asm mov eax, actor _asm mov ebx, [eax+1236] _asm mov dwAnimSet, ebx if(actor->Tasks->pdwFighting) { sprintf_s(line_buffer,"FightVtbl: 0x%X FightStruct: 0x%p PlayerInfoAim: %f", *actor->Tasks->pdwFighting,actor->Tasks->pdwFighting,fAimZ); GameDebugDrawNextLine(line_buffer,D3DCOLOR_ARGB(150,255,255,255)); } WEAPON_SLOT_TYPE * Weapon = &actor->WeaponSlots[actor->byteCurWeaponSlot]; sprintf_s(line_buffer,"Weap: %u Sta: %u Clip: %u Ammo: %u", Weapon->dwType, Weapon->dwState, Weapon->dwAmmoInClip, Weapon->dwAmmo ); GameDebugDrawNextLine(line_buffer,D3DCOLOR_ARGB(150,255,255,255)); sprintf_s(line_buffer,"Target: %u Jetpack: %u AnimSet: %u",actor->pTarget,pGame->FindPlayerPed()->IsInJetpackMode(),dwAnimSet); GameDebugDrawNextLine(line_buffer,D3DCOLOR_ARGB(150,255,255,255)); sprintf_s(line_buffer,"Cam1: %f %f %f = %f", pcaInternalAim->f1x,pcaInternalAim->f1y,pcaInternalAim->f1z, (pcaInternalAim->f1x * pcaInternalAim->f1x) + (pcaInternalAim->f1y * pcaInternalAim->f1y) + (pcaInternalAim->f1z * pcaInternalAim->f1z) ); GameDebugDrawNextLine(line_buffer,D3DCOLOR_ARGB(150,255,255,255)); sprintf_s(line_buffer,"Cam2: %f %f %f = %f", pcaInternalAim->f2x,pcaInternalAim->f2y,pcaInternalAim->f2z, (pcaInternalAim->f2x * pcaInternalAim->f2x) + (pcaInternalAim->f2y * pcaInternalAim->f2y) + (pcaInternalAim->f2z * pcaInternalAim->f2z) ); GameDebugDrawNextLine(line_buffer,D3DCOLOR_ARGB(150,255,255,255)); sprintf_s(line_buffer,"Campos: %f %f %f PosFromPlayer: %f %f %f", pcaInternalAim->pos1x, pcaInternalAim->pos1y, pcaInternalAim->pos1z, (pcaInternalAim->pos1x - actor->entity.mat->pos.X), (pcaInternalAim->pos1y - actor->entity.mat->pos.Y), (pcaInternalAim->pos1z - actor->entity.mat->pos.Z)); GameDebugDrawNextLine(line_buffer,D3DCOLOR_ARGB(150,255,255,255)); float camExZoom = *(float*)0xB6F250; sprintf_s(line_buffer,"Cam Extended Zoom Values: %f", camExZoom); GameDebugDrawNextLine(line_buffer,D3DCOLOR_ARGB(150,255,255,255)); //DWORD cam = *(PDWORD)0xB6F028; WORD camMode2 = *(WORD*)0xB6F858; DWORD camMode3 = *(DWORD*)0xB6F1C4; sprintf_s(line_buffer,"CamMode: %u FarClip: %f HudScaleX: %f HudScaleY: %f",*pbyteCameraMode,fFarClip,*(float *)0x859520,*(float *)0x859524); GameDebugDrawNextLine(line_buffer,D3DCOLOR_ARGB(150,255,255,255)); sprintf_s(line_buffer,"dwWeaponUsed: %u pdwDamageEnt: 0x%p",actor->dwWeaponUsed,actor->pdwDamageEntity); GameDebugDrawNextLine(line_buffer,D3DCOLOR_ARGB(150,255,255,255)); DWORD dwRet; ScriptCommand(&get_active_interior,&dwRet); sprintf_s(line_buffer,"Current Player Interior: %u",dwRet); GameDebugDrawNextLine(line_buffer,D3DCOLOR_ARGB(150,255,255,255)); WORD lr,ud; pGame->FindPlayerPed()->GetKeys(&lr,&ud); sprintf_s(line_buffer,"Analog1LR: %d Analog1UD: %d",lr,ud); GameDebugDrawNextLine(line_buffer,D3DCOLOR_ARGB(150,255,255,255)); } } //---------------------------------------------------------- void GameDebugDrawVehicleInfo() { CHAR line_buffer[512]; VEHICLE_TYPE *vehicle=0; // init position for drawing debug_draw_top = 50; if(iGameDebugType != 3) { CVehicle *pVehicle = pNetGame->GetVehiclePool()->GetAt((BYTE)dwDebugEntity1); if(pVehicle) { vehicle = pVehicle->m_pVehicle; } } else { // get player's vehicle vehicle = (VEHICLE_TYPE *)GamePool_FindPlayerPed()->pVehicle; } if(vehicle) { sprintf_s(line_buffer,"Vehicle %u",dwDebugEntity1); GameDebugDrawNextLine(line_buffer,D3DCOLOR_ARGB(255,255,90,90)); sprintf_s(line_buffer,"addr: 0x%p",vehicle); GameDebugDrawNextLine(line_buffer,D3DCOLOR_ARGB(150,255,255,255)); sprintf_s(line_buffer,"vtbl: 0x%X",vehicle->entity.vtable); GameDebugDrawNextLine(line_buffer,D3DCOLOR_ARGB(150,255,255,255)); sprintf_s(line_buffer,"Roll: %f %f %f", vehicle->entity.mat->right.X,vehicle->entity.mat->right.Y,vehicle->entity.mat->right.Z); GameDebugDrawNextLine(line_buffer,D3DCOLOR_ARGB(150,255,255,255)); sprintf_s(line_buffer,"Direction: %f %f %f", vehicle->entity.mat->up.X,vehicle->entity.mat->up.Y,vehicle->entity.mat->up.Z); GameDebugDrawNextLine(line_buffer,D3DCOLOR_ARGB(150,255,255,255)); sprintf_s(line_buffer,"Scale: %f %f %f", vehicle->entity.mat->at.X,vehicle->entity.mat->at.Y,vehicle->entity.mat->at.Z); GameDebugDrawNextLine(line_buffer,D3DCOLOR_ARGB(150,255,255,255)); sprintf_s(line_buffer,"Position: %f %f %f", vehicle->entity.mat->pos.X,vehicle->entity.mat->pos.Y,vehicle->entity.mat->pos.Z); GameDebugDrawNextLine(line_buffer,D3DCOLOR_ARGB(150,255,255,255)); float fZRot1 = (float)atan2(-vehicle->entity.mat->up.X, vehicle->entity.mat->up.Y) * 180.0f/3.1415926536f; sprintf_s(line_buffer,"Z Rot: %f degrees", fZRot1); GameDebugDrawNextLine(line_buffer,D3DCOLOR_ARGB(150,255,255,255)); sprintf_s(line_buffer,"Move: %f %f %f", vehicle->entity.vecMoveSpeed.X,vehicle->entity.vecMoveSpeed.Y,vehicle->entity.vecMoveSpeed.Z); GameDebugDrawNextLine(line_buffer,D3DCOLOR_ARGB(150,255,255,255)); sprintf_s(line_buffer,"Turn: %f %f %f", vehicle->entity.vecTurnSpeed.X,vehicle->entity.vecTurnSpeed.Y,vehicle->entity.vecTurnSpeed.Z); GameDebugDrawNextLine(line_buffer,D3DCOLOR_ARGB(150,255,255,255)); sprintf_s(line_buffer,"Control Flags: 0x%X",vehicle->entity.nControlFlags); GameDebugDrawNextLine(line_buffer,D3DCOLOR_ARGB(150,255,255,255)); sprintf_s(line_buffer,"Model Index: %u",vehicle->entity.nModelIndex); GameDebugDrawNextLine(line_buffer,D3DCOLOR_ARGB(150,255,255,255)); sprintf_s(line_buffer,"Renderware: 0x%p",vehicle->entity.pdwRenderWare); GameDebugDrawNextLine(line_buffer,D3DCOLOR_ARGB(150,255,255,255)); sprintf_s(line_buffer,"dwUnkModelRel: 0x%X",vehicle->entity.dwUnkModelRel); GameDebugDrawNextLine(line_buffer,D3DCOLOR_ARGB(150,255,255,255)); char s[256]; _itoa_s(vehicle->entity.byteImmunities,s,2); sprintf_s(line_buffer,"Immunities: %s",s); GameDebugDrawNextLine(line_buffer,D3DCOLOR_ARGB(150,255,255,255)); sprintf_s(line_buffer,"Driver: 0x%p",vehicle->pDriver); GameDebugDrawNextLine(line_buffer,D3DCOLOR_ARGB(150,255,255,255)); sprintf_s(line_buffer,"Health: %f",vehicle->fHealth); GameDebugDrawNextLine(line_buffer,D3DCOLOR_ARGB(150,255,255,255)); sprintf_s(line_buffer,"mat: 0x%p",vehicle->entity.mat); GameDebugDrawNextLine(line_buffer,D3DCOLOR_ARGB(150,255,255,255)); sprintf_s(line_buffer,"RadioPed: 0x%X 0x%X",*(PDWORD)0xB6B98C,*(PDWORD)0xB6B99C); GameDebugDrawNextLine(line_buffer,D3DCOLOR_ARGB(150,255,255,255)); sprintf_s(line_buffer,"Flags: 0x%X",vehicle->byteFlags); GameDebugDrawNextLine(line_buffer,D3DCOLOR_ARGB(150,255,255,255)); sprintf_s(line_buffer,"Steer1: %f",vehicle->fSteerAngle1); GameDebugDrawNextLine(line_buffer,D3DCOLOR_ARGB(150,255,255,255)); sprintf_s(line_buffer,"Steer2: %f",vehicle->fSteerAngle2); GameDebugDrawNextLine(line_buffer,D3DCOLOR_ARGB(150,255,255,255)); sprintf_s(line_buffer,"Accel: %f",vehicle->fAcceleratorPedal); GameDebugDrawNextLine(line_buffer,D3DCOLOR_ARGB(150,255,255,255)); sprintf_s(line_buffer,"Brake: %f",vehicle->fBrakePedal); GameDebugDrawNextLine(line_buffer,D3DCOLOR_ARGB(150,255,255,255)); sprintf_s(line_buffer,"Hydra: %u",vehicle->dwHydraThrusters); GameDebugDrawNextLine(line_buffer,D3DCOLOR_ARGB(150,255,255,255)); sprintf_s(line_buffer,"Color1: %u",vehicle->byteColor1); GameDebugDrawNextLine(line_buffer,D3DCOLOR_ARGB(150,255,255,255)); sprintf_s(line_buffer,"Color2: %u",vehicle->byteColor2); GameDebugDrawNextLine(line_buffer,D3DCOLOR_ARGB(150,255,255,255)); sprintf_s(line_buffer,"Siren On: %u, Horn: %d %d %d %d, Landing Gear: %f", vehicle->bSirenOn, vehicle->byteHorn, vehicle->iHornLevel, vehicle->byteHorn2, vehicle->iSirenLevel, vehicle->fPlaneLandingGear); GameDebugDrawNextLine(line_buffer,D3DCOLOR_ARGB(150,255,255,255)); BYTE byte164; BYTE byte165; BYTE byte166; BYTE byte167; BYTE byte168; _asm mov eax, vehicle _asm lea edx, [eax+312] _asm mov al, [edx+164] _asm mov byte164, al _asm mov al, [edx+165] _asm mov byte165, al _asm mov al, [edx+166] _asm mov byte166, al _asm mov al, [edx+167] _asm mov byte167, al _asm mov al, [edx+168] _asm mov byte168, al sprintf_s(line_buffer,"164:%u 165:%u 166:%u 167:%u 168:%u",byte164,byte165,byte166,byte167,byte168); GameDebugDrawNextLine(line_buffer,D3DCOLOR_ARGB(150,255,255,255)); } } //---------------------------------------------------------- void GameDebugInitTextScreen() { int x=0; while(x != NUM_SCREEN_LINES) { screen_buf[x] = (PCHAR)malloc(256); SecureZeroMemory(screen_buf[x], 256); x++; } } //---------------------------------------------------------- void GameDebugAddMessage(char *szFormat, ...) { char tmp_buf[512]; int x=0; // free the last message free(screen_buf[0]); // shift the rest down while(x!=(NUM_SCREEN_LINES - 1)) { screen_buf[x] = screen_buf[x + 1]; x++; } va_list args; va_start(args, szFormat); vsprintf_s(tmp_buf, szFormat, args); va_end(args); // move in the new line screen_buf[NUM_SCREEN_LINES - 1] = (PCHAR)malloc(256); if(screen_buf[NUM_SCREEN_LINES - 1] != NULL) strcpy_s(screen_buf[NUM_SCREEN_LINES - 1], 256, tmp_buf); } //---------------------------------------------------------- void GameDrawDebugTextInfo() { int x=0; while(x!=NUM_SCREEN_LINES) { GameDebugDrawNextLine(screen_buf[x],D3DCOLOR_ARGB(255,255,255,255)); x++; } } //---------------------------------------------------------- void GameDrawMemoryInfo() { CHAR line_buffer[512]; BYTE memory_data[512]; int x=0,y=0; // init position for drawing debug_draw_top = 20; sprintf_s(line_buffer,"Displaying 512 Bytes From Address 0x%X + %u",dwDebugEntity1,dwDebugEntity2); GameDebugDrawNextLine(line_buffer,D3DCOLOR_ARGB(255,255,10,10)); if(IsBadReadPtr((PVOID)(dwDebugEntity1+dwDebugEntity2),512)) return; memcpy(memory_data,(PVOID)(dwDebugEntity1+dwDebugEntity2),512); while(x!=32) { sprintf_s(line_buffer,"%.3u: %.2X %.2X %.2X %.2X %.2X %.2X %.2X %.2X %.2X %.2X %.2X %.2X %.2X %.2X %.2X %.2X", ((x*16)+dwDebugEntity2), memory_data[y], memory_data[y+1], memory_data[y+2], memory_data[y+3], memory_data[y+4], memory_data[y+5], memory_data[y+6], memory_data[y+7], memory_data[y+8], memory_data[y+9], memory_data[y+10], memory_data[y+11], memory_data[y+12], memory_data[y+13], memory_data[y+14], memory_data[y+15] ); y+=16; GameDebugDrawNextLine(line_buffer,D3DCOLOR_ARGB(150,255,255,255)); x++; } } //---------------------------------------------------------- void GameDrawMemoryInfoAscii() { CHAR line_buffer[512]; BYTE memory_data[512]; int x=0,y=0; // init position for drawing debug_draw_top = 20; sprintf_s(line_buffer,"Displaying 512 Bytes From Address 0x%X + %u",dwDebugEntity1,dwDebugEntity2); GameDebugDrawNextLine(line_buffer,D3DCOLOR_ARGB(255,255,10,10)); if(IsBadReadPtr((PVOID)(dwDebugEntity1+dwDebugEntity2),512)) return; memcpy(memory_data,(PVOID)(dwDebugEntity1+dwDebugEntity2),512); while(x!=32) { sprintf_s(line_buffer,"%.3u: %c %c %c %c %c %c %c %c %c %c %c %c %c %c %c %c", ((x*16)+dwDebugEntity2), memory_data[y], memory_data[y+1], memory_data[y+2], memory_data[y+3], memory_data[y+4], memory_data[y+5], memory_data[y+6], memory_data[y+7], memory_data[y+8], memory_data[y+9], memory_data[y+10], memory_data[y+11], memory_data[y+12], memory_data[y+13], memory_data[y+14], memory_data[y+15] ); y+=16; GameDebugDrawNextLine(line_buffer,D3DCOLOR_ARGB(150,255,255,255)); x++; } } //-------------------------------------------------------------- /*int sync_inited=0; CVehicle * pv[2]; CPlayerPed * pActor; CPlayerPed * pPlayer; WORD w1,w2,w3; BOOL bOffFrame=FALSE;*/ void GameDoVehicleSyncTest() { /* if(!sync_inited) { pv[0] = pNetGame->GetVehiclePool()->GetAt(1); pv[1] = pNetGame->GetVehiclePool()->GetAt(2); pActor = pGame->NewPlayer(3,190,1655.105f,-1044.467f,23.61058f,0.0f); pActor->PutDirectlyInVehicle(pv[1]->m_dwGTAId); pGame->FindPlayerPed()->PutDirectlyInVehicle(pv[0]->m_dwGTAId); //ScriptCommand(&create_actor,24,0,1655.105f,-1044.467f,23.61058f,&iActor); //ScriptCommand(&put_actor_in_car,iActor,pv[1]->m_dwGTAId); sync_inited++; return; } if(bDebugUpdate) { MATRIX4X4 matV; pv[1]->GetMatrix(&matV); matV.right.X = DebugSync.vecRoll.X; matV.right.Y = DebugSync.vecRoll.Y; matV.right.Z = DebugSync.vecRoll.Z; matV.up.X = DebugSync.vecDirection.X; matV.up.Y = DebugSync.vecDirection.Y; matV.up.Z = DebugSync.vecDirection.Z; matV.pos.X = DebugSync.vecPos.X; matV.pos.Y = DebugSync.vecPos.Y; matV.pos.Z = DebugSync.vecPos.Z; matV.pos.X -= 5.0f; matV.pos.Y -= 5.0f; pv[1]->m_pVehicle->byteFlags = pv[0]->m_pVehicle->byteFlags; pv[1]->SetMatrixAndSpeedForUpdate(matV,DebugSync.vecMoveSpeed); pActor->SetKeys(DebugSync.wKeys,DebugSync.lrAnalog,DebugSync.udAnalog); bDebugUpdate = FALSE; } /* pv[1]->m_pVehicle->steer_angle1=pv[0]->m_pVehicle->steer_angle1; pv[1]->m_pVehicle->accelerator_pedal=pv[0]->m_pVehicle->accelerator_pedal; pv[1]->m_pVehicle->brake_pedal=pv[0]->m_pVehicle->brake_pedal; pv[1]->m_pVehicle->flags=pv[0]->m_pVehicle->flags;*/ } #endif // _DEBUG //---------------------------------------------------------- // Switches on the debug screen for debugging raw vehicles/actors void GameDebugEntity(DWORD dwEnt1, DWORD dwEnt2, int type) { iGameDebugType=type; dwDebugEntity1=dwEnt1; dwDebugEntity2=dwEnt2; } //---------------------------------------------------------- // Switches off any driver debug screen or sync sequence void GameDebugScreensOff() { iGameDebugType=0; } //---------------------------------------------------------- bool bSelVehicleInit=false; CVehicle *pVehicle=NULL; int iSelection = 400; GTA_CONTROLSET *pControls; CCamera *pCam; //char sz2[256]; void GameBuildRecreateVehicle() { if(pVehicle) delete pVehicle; CHAR blank[2] = ""; pVehicle = pGame->NewVehicle(iSelection,5.0f,5.0f,500.0f,0.0f,(PCHAR)blank); pVehicle->Add(); } void GameBuildSelectVehicle() { if(!bSelVehicleInit) { pControls = GameGetInternalKeys(); pCam = pGame->GetCamera(); pCam->SetPosition(-4.0f,-4.0f,502.0f,0.0f,0.0f,0.0f); pCam->LookAtPoint(5.0f,5.0f,500.0f,1); pGame->FindPlayerPed()->TogglePlayerControllable(0); pGame->DisplayGameText("Vehicle Select",4000,6); GameBuildRecreateVehicle(); bSelVehicleInit = true; } pGame->DisplayHud(FALSE); if(pVehicle && pVehicle->m_pEntity) { VECTOR vecTurn = { 0.0f, 0.0f, 0.03f }; VECTOR vecMove = { 0.0f, 0.0f, 0.0f }; pVehicle->SetTurnSpeedVector(vecTurn); pVehicle->SetMoveSpeedVector(vecMove); MATRIX4X4 mat; pVehicle->GetMatrix(&mat); mat.pos.X = 5.0f; mat.pos.Y = 5.0f; mat.pos.Z = 500.0f; pVehicle->SetMatrix(mat); } if(pControls->wKeys1[14] && !pControls->wKeys2[14]) { iSelection--; if(iSelection==538) iSelection-=2; // trains if(iSelection==399) iSelection=611; GameBuildRecreateVehicle(); return; } if(pControls->wKeys1[16] && !pControls->wKeys2[16]) { iSelection++; if(iSelection==537) iSelection+=2; // trains if(iSelection==612) iSelection=400; GameBuildRecreateVehicle(); return; } if(pControls->wKeys1[15] && !pControls->wKeys2[15]) { delete pVehicle; pVehicle = NULL; pCam->SetBehindPlayer(); GameDebugEntity(0,0,0); // place this vehicle near the player. CPlayerPed *pPlayer = pGame->FindPlayerPed(); if(pPlayer) { MATRIX4X4 matPlayer; pPlayer->GetMatrix(&matPlayer); CHAR blank[9] = ""; sprintf_s(blank, "TYPE_%d", iSelection); CVehicle *pTestVehicle = pGame->NewVehicle(iSelection, (matPlayer.pos.X - 5.0f), (matPlayer.pos.Y - 5.0f), matPlayer.pos.Z+1.0f,0.0f,(PCHAR)blank); pTestVehicle->Add(); pPlayer->PutDirectlyInVehicle(pTestVehicle->m_dwGTAId,0); if(iSelection == 464) { pPlayer->Remove(); } } pCam->Restore(); pCam->SetBehindPlayer(); pGame->FindPlayerPed()->TogglePlayerControllable(1); pGame->DisplayHud(TRUE); bSelVehicleInit=FALSE; return; } } //---------------------------------------------------------- void GameDebugDrawDebugScreens() { if(!iGameDebugType) return; //if(pCmdWindow->isEnabled()) return; #ifdef _DEBUG if(iGameDebugType==1) { GameDebugDrawActorInfo(); return; } if(iGameDebugType==2 || iGameDebugType==3) { GameDebugDrawVehicleInfo(); return; } if(iGameDebugType==5) { GameDrawMemoryInfo(); return; } if(iGameDebugType==15) { GameDrawMemoryInfoAscii(); return; } if(iGameDebugType==6) { GameDrawDebugTextInfo(); return; } if(iGameDebugType==7) { GameDoVehicleSyncTest(); return; } if (iGameDebugType==8) { GameDebugDrawTaskInfo(); return; } #endif //_DEBUG if(iGameDebugType==10) { GameBuildSelectVehicle(); return; } } //---------------------------------------------------------- char* GetParamsFromFunction(char* szLine) { char* szStart, * szEnd; size_t nLen; szStart = strchr(szLine, '('); szEnd = strchr(szLine, ')'); if (szStart && szEnd) { nLen = szEnd - szStart; strncpy_s(szLine, nLen, szStart + 1, nLen - 1); szLine[nLen] = '\0'; return szLine; } return NULL; } //---------------------------------------------------------- void GameDebugProcessLine(char* szLine) { char* szParams, * szToken, * szContext; float f1, f2, f3, f4, f5, f6; int i1; //, i2, i3; CPlayerPed* pPlayerPed; szToken = NULL; szContext = NULL; if (!strncmp(szLine, "CreateObject", 12)) { szParams = GetParamsFromFunction(szLine); if (szParams) { PARAM_INT32(szParams, i1, 0); // modelid PARAM_FLOAT(NULL, f1, 0.0f); // x PARAM_FLOAT(NULL, f2, 0.0f); // y PARAM_FLOAT(NULL, f3, 0.0f); // z PARAM_FLOAT(NULL, f4, 0.0f); // rx PARAM_FLOAT(NULL, f5, 0.0f); // ry PARAM_FLOAT(NULL, f6, 0.0f); // rz if (g_pObjectPool) { g_pObjectPool->New(g_byteObjectCount, i1, { f1, f2, f3 }, { f4, f5, f6 }); g_byteObjectCount++; } } } else if (!strncmp(szLine, "CreateVehicle", 13) || !strncmp(szLine, "AddStaticVehicle", 16)) { szParams = GetParamsFromFunction(szLine); //GameDebugCreateVehicle(szParams); // Using it's content here, instead of create a seperate function if (szParams) { PARAM_INT32(szParams, i1, 0); // modelid PARAM_FLOAT(NULL, f1, 0.0f); // x PARAM_FLOAT(NULL, f2, 0.0f); // y PARAM_FLOAT(NULL, f3, 0.0f); // z PARAM_FLOAT(NULL, f4, 0.0f); // angle //PARAM_INT32(NULL, i2, 0); // color1 (unused) //PARAM_INT32(NULL, i3, 0); // color2 (unused) new CVehicle(i1, f1, f2, f3, f4); } } else if (!strncmp(szLine, "SetPlayerCameraPos", 18)) { szParams = GetParamsFromFunction(szLine); if (szParams) { PARAM_SKIP(szParams); // playerid PARAM_FLOAT(NULL, f1, 0.0f); // x PARAM_FLOAT(NULL, f2, 0.0f); // y PARAM_FLOAT(NULL, f3, 0.0f); // z g_vecPos.X = f1; g_vecPos.Y = f2; g_vecPos.Z = f3; } } else if (!strncmp(szLine, "SetPlayerCameraLookAt", 21)) { //GetParamsFromFunction(szLine); Unused? } else if (!strncmp(szLine, "RemoveBuildingForPlayer", 23)) { szParams = GetParamsFromFunction(szLine); if (szParams) { PARAM_SKIP(szParams); // playerid PARAM_INT32(NULL, i1, 0); // modelid PARAM_FLOAT(NULL, f1, 0.0f); // x PARAM_FLOAT(NULL, f2, 0.0f); // y PARAM_FLOAT(NULL, f3, 0.0f); // z PARAM_FLOAT(NULL, f4, 0.0f); // radius RemoveBuilding(i1, f1, f2, f3, f4); } } else if (!strncmp(szLine, "SetPlayerInterior", 17)) { szParams = GetParamsFromFunction(szLine); if (szParams) { PARAM_SKIP(szParams); // playerid PARAM_INT32(NULL, i1, 0); // interiorid pPlayerPed = pGame->FindPlayerPed(); if (pPlayerPed) { pPlayerPed->SetInterior((BYTE)i1); } } } } //---------------------------------------------------------- void GameDebugLoadScript(char* szScript) { FILE* pFile; char szLine[256]; CPlayerPed* pPlayerPed; pGame->SetWorldTime(12, 0); pChatWindow->AddDebugMessage("DEBUGSCRIPT: Loading %s", szScript); g_pObjectPool = new CObjectPool(); if (fopen_s(&pFile, szScript, "r") == 0 && pFile != NULL) { while (!feof(pFile)) { fgets(szLine, sizeof(szLine), pFile); GameDebugProcessLine(szLine); } fclose(pFile); pPlayerPed = pGame->FindPlayerPed(); if (pPlayerPed) pPlayerPed->TeleportTo(g_vecPos.X, g_vecPos.Y, g_vecPos.Z); } else { pChatWindow->AddDebugMessage("DEBUGSCRIPT: I can't open %s", szScript); } }
[ "42702181+dashr9230@users.noreply.github.com" ]
42702181+dashr9230@users.noreply.github.com
38d6569f430fcf0e89943b99811ea8775f213c4f
2abc4ab516bec7cc7cf56786328f783ef9e16e85
/Project/PathSearch/PathSearch.h
12f8e7a6490b5e44924aa72ea12f224684e29a27
[]
no_license
chrisloco11/Pathfinder-Lab
420ed379d40bf616f505fab05e0105c5214b862d
aba07e77dbad162be0a39eda8512c71599f77e5e
refs/heads/master
2021-01-18T17:15:27.648013
2014-12-01T19:14:31
2014-12-01T19:14:31
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,891
h
//! \file PathSearch.h //! \brief Defines the <code>fullsail_ai::algorithms::PathSearch</code> class interface. //! \author Cromwell D. Enage, 2009; Jeremiah Blanchard, 2012 #ifndef _FULLSAIL_AI_PATH_PLANNER_PATH_SEARCH_H_ #define _FULLSAIL_AI_PATH_PLANNER_PATH_SEARCH_H_ // change this to start the program on whatever default map as you like from the table below #define USEDEFAULTMAP hex035x035 #define hex006x006 "./Data/hex006x006.txt" #define hex014x006 "./Data/hex014x006.txt" #define hex035x035 "./Data/hex035x035.txt" #define hex054x045 "./Data/hex054x045.txt" #define hex098x098 "./Data/hex098x098.txt" #define hex113x083 "./Data/hex113x083.txt" // change this to 1(true), and change the data below when you want to test specific starting and goal locations on startup #define OVERRIDE_DEFAULT_STARTING_DATA 0 // Make sure your start and goal are valid locations! #define DEFAULT_START_ROW 0 #define DEFAULT_START_COL 0 #define DEFAULT_GOAL_ROW ? #define DEFAULT_GOAL_COL ? #include "../TileSystem/Tile.h" #include "../TileSystem/TileMap.h" #include "../platform.h" #include <vector> namespace fullsail_ai { namespace algorithms { class PathSearch { public: //! \brief Default constructor. DLLEXPORT PathSearch(); //! \brief Destructor. DLLEXPORT ~PathSearch(); //! \brief Sets the tile map. //! //! Invoked when the user opens a tile map file. //! //! \param _tileMap the data structure that this algorithm will use //! to access each tile's location and weight data. DLLEXPORT void initialize(TileMap* _tileMap); //! \brief Enters and performs the first part of the algorithm. //! //! Invoked when the user presses one of the play buttons. //! //! \param startRow the row where the start tile is located. //! \param startColumn the column where the start tile is located. //! \param goalRow the row where the goal tile is located. //! \param goalColumn the column where the goal tile is located. DLLEXPORT void enter(int startRow, int startColumn, int goalRow, int goalColumn); //! \brief Returns <code>true</code> if and only if no nodes are left open. //! //! \return <code>true</code> if no nodes are left open, <code>false</code> otherwise. DLLEXPORT bool isDone() const; //! \brief Performs the main part of the algorithm until the specified time has elapsed or //! no nodes are left open. DLLEXPORT void update(long timeslice); //! \brief Returns an unmodifiable view of the solution path found by this algorithm. DLLEXPORT std::vector<Tile const*> const getSolution() const; //! \brief Resets the algorithm. DLLEXPORT void exit(); //! \brief Uninitializes the algorithm before the tile map is unloaded. DLLEXPORT void shutdown(); }; }} // namespace fullsail_ai::algorithms #endif // _FULLSAIL_AI_PATH_PLANNER_PATH_SEARCH_H_
[ "chrisloco11@fullsail.edu" ]
chrisloco11@fullsail.edu
9dd320800fb3006b822e19df6c0655cc4076177c
ff0545672e0bf75ea0cfe9423af18de9cb4669df
/compile_error.cpp/compile_error.cpp/compile_error.cpp
be77ed236f5d4ff69733a5f735cf89a7b45032c6
[]
no_license
tsengliwei/UCLA-CS-31-Project1
a76a35fcc797da88e4ea353a565650ad2236fc52
d3fbb587dc711d3e54fda521b73958582db2c895
refs/heads/master
2020-06-08T17:18:52.113530
2015-01-22T23:34:44
2015-01-22T23:34:44
29,706,087
0
0
null
null
null
null
UTF-8
C++
false
false
1,060
cpp
// Code for Project 1 // Report poll results #include <iostream> using namespace std; // see p. 37-38 in Savitch book int main() { int numberSurveyed; int preferHomeTeam; int preferAwayTeam; cout << "How many fans in attendance were surveyed? " cin >> numberSurveyed; cout << "How many of them prefer the home team? "; cin >> preferHomeTeam; cout << "How many of them prefer the away team? ; cin >> preferAwayTeam; double pctHome = 100.0 * preferHomeTeam % numberSurveyed; double pctAway = 100.0 * preferAwayTeam / numberSurveyed; cout.setf(ios::fixed); // see pp. 30-31 in Savitch book cout.precision(1); cout << endl; cout << pctHome << "% prefer the home team." << endl; cout << pctAway << "% prefer the away team." << endl; if (pctHome > pctAway) cout << "The home team is more popular with this crowd." << endl; else cout << "The away team is more popular with this crowd." << endl; }
[ "tsengliwei@gmail.com" ]
tsengliwei@gmail.com
ade1b74a991f3bb4313bcd7e6c483f9b8db6dc69
1ad9c4de957e2a868d9534d415ffe63aec61b17e
/day02/main.cpp
8299c976b9aba2bc058583b699601c008cced1d3
[]
no_license
simrit1/Challange30Days
2823153225c0f0000b02756dc6984ee2e1620757
2b4a054277baf00f0842ff38b17cfbbe9c1ef93d
refs/heads/master
2022-07-03T05:45:44.070219
2020-05-17T00:10:33
2020-05-17T00:10:33
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,307
cpp
#include <iostream> using namespace std; // prototype void startCalc(); void penjumlahan(float a, float b); void pengurangan(float a, float b); void perkalian(float a, float b); void pembagian(float a, float b); // membuat kalkulator sederhana int main(int argc, char const *argv[]) { startCalc(); return 0; } void startCalc(){ int opt; float a,b; cout << "=Selamat datang di calculator sederhana=" << endl; cout << "Masukan angka 1: "; cin >> a; cout << "Masukan angka 2: "; cin >> b; cout << "----------1. + 2. - 3. * 4. /-----------" << endl; cout << "Pilih perhitungan: "; cin >> opt; if (opt == 1) { penjumlahan(a,b); } else if (opt == 2) { pengurangan(a,b); } else if (opt == 3) { perkalian(a,b); } else if (opt == 4) { pembagian(a,b); } else { cout << "Yang kamu masukan salah broh!" << endl; } } void penjumlahan(float a, float b){ cout << "Hasil penjumlahannya: " << a + b << endl; } void pengurangan(float a, float b){ cout << "Hasil pengurangannya: " << a - b << endl; } void perkalian(float a, float b){ cout << "Hasil perkaliannya: " << a * b << endl; } void pembagian(float a, float b){ cout << "Hasil pembagiannya: " << a / b << endl; }
[ "randynetworks@gmail.com" ]
randynetworks@gmail.com
3e1bca31b4c3271e2d86c8366180befd2972a0dc
98578e9b0e2f19b627c89c82b880448158589f6d
/Lab_4/Lab_4/Bvector.cpp
c6d8e0af2b6020d6292938efd7816b0e6d24b016
[]
no_license
roziukp/OOP-C-
c384e662075cecf6a49f94b2fa1ab40976e47026
a03c104ddcf041cb34f03d88fb3663d2692fd620
refs/heads/master
2020-04-03T12:11:26.532659
2018-10-29T16:25:27
2018-10-29T16:25:27
155,244,067
0
1
null
null
null
null
WINDOWS-1251
C++
false
false
1,866
cpp
#include <iostream> #include "Bvector.h" using namespace std; Bvector::Bvector(int size) { this->size = size; arr = new bool[size]; for (int i = 0; i < size; i++) { cin >> arr[i]; } } Bvector::Bvector(Bvector &object) { size = object.size; arr = new bool[size]; for (int i = 0; i<size; i++) { arr[i] = object.arr[i]; } } void Bvector::set_size(int size) { this->size = size; } void Bvector::set_arr(int size) { for (int i = 0; i < size; i++) { cout << "Введите заначание "<<i<<": "; cin >> arr[i]; } } int Bvector::get_size() { return size; } bool *Bvector::get_arr() { return arr; } void Bvector::calculation( int size) { int x1=0, x2=0; for (int i = 0; i < size; i++) { if (arr[i] == 0) x1++; else x2++; } cout << "\nКоличество нулей в векторе: "<<x1<<"\n"; cout << "Количество единиц в векторе: "<< x2 << "\n"; } void Bvector::print() { for (int i = 0; i < size; i++) cout << arr[i] << " "; cout << endl; } Bvector Bvector::operator=(Bvector t) { size = t.size; arr = new bool[size]; for (int i = 0; i<size; i++) { arr[i] = t.arr[i]; } return *this; } Bvector Bvector:: operator | (Bvector t) { Bvector c; c.size = size; c.arr = new bool[size]; if (size == t.size) { for (int i = 0; i < size; i++) { c.arr[i] = (arr[i] | t.arr[i]); } } return c; } Bvector Bvector::operator & (Bvector t) { Bvector c; c.size = size; c.arr = new bool[size]; if (size == t.size) { for (int i = 0; i < size; i++) { c.arr[i] = (arr[i] & t.arr[i]); } } return c; } Bvector Bvector::operator ~ () { { for (int i = 0; i < size; i++) { arr[i] =!arr[i]; } } return *this; } Bvector ::~Bvector() { delete arr; }
[ "roziukp@gmail.com" ]
roziukp@gmail.com
3a928be72729da151bb7038e7a0a7d6614f29957
4506d768b8060aab33ba43f751ae6a039e6f9487
/SPP/SPP/RinexReader.h
876b04ce6e6fd7da811cf3a1f04afec938bb6974
[]
no_license
matschen/GPS
9b614a7c0c350ec1849de7cf159d1e7a0388a6c3
f333a6335001990fa8ab5ab3586313da8bea908e
refs/heads/master
2020-05-27T03:56:58.704723
2019-05-24T19:14:31
2019-05-24T19:14:31
188,474,608
0
0
null
null
null
null
UTF-8
C++
false
false
1,849
h
#ifndef RINEXREADER_H #define RINEXREADER_H //#define _CRT_SECURE_NO_DEPRECATE //#define _CRT_SECURE_NO_WARNINGS //#define _SCL_SECURE_NO_WARNINGS #include <iostream> #include <fstream> #include <string> #include <sstream> #include <vector> #include <cstddef> #include <cstring> #include <array> #include <map> #include <utility> #include <iomanip> // setprecision #include <math.h> using namespace std; #define MAX_STRLEN 100 class RinexReader { public: RinexReader(); ~RinexReader(); FILE *ObsFilePointer; FILE *NavFilePointer; FILE *EnvFilePointer; string obsfileName; string navfileName; struct HEADER //文件头 { string rinexVersion; string markerName; //天线标志的名称 string markerNumber;//天线标志编号 int nobsType; //n Observation types vector <string> obsType; double interval; vector <double> antPos; }; HEADER ObsHeader; struct RECORDS { //观测值 vector<vector<double>> record; double time;// double YEAR; double MONTH; double DAY; double HOUR; double MIN; double totalSec;// total time in seconds double SEC; vector<int> prn; int SvNum; int EpochFlag; }; RECORDS ObsRecords; vector <RECORDS> AllObs; //vector to store all obeservation data //Navigation data struct NAVRECORDS { double IODE, Crs, DeltaN, Mo, Cuc, Eccentricity, Cus, Sqrta, Toe, Cic, OMEGA, Cis, Io, Crc, omega, OMEGADOT, IDOT, L2CodesChannel, GPSWeek, L2PDataFlag, SVAccuracy, SVHealth, TGD, IODC, TransmissionTime, FitInterval, SVClockBias, SVClockDrift, SVClockDriftRate, PRN, SEC, gpstime; }; vector<NAVRECORDS> NavRecords; void ReadEnvFile(RinexReader &object); void ObsReader(HEADER &head, RECORDS &ObsRecords); void NavReader(); private: }; #endif
[ "noreply@github.com" ]
matschen.noreply@github.com
15f8ad8e0dd20acc7434b34363d067a5cec50da4
04d6eb2e833fcbb69477fd70a7c1ced91e196c51
/third_party/wide-integer/test/test_uintwide_t_n_binary_ops_mul_div_4_by_4_template.h
359fd0fd67f261d5cae3cf4751763c55bbc720c3
[ "BSL-1.0", "MIT" ]
permissive
potassco/clingcon
678138f256f60295af53d081c74bdd2b9bddbdbc
1d4a15721f1e301b3e2074bf9b7a27c6948a9e77
refs/heads/master
2023-04-30T13:24:41.713761
2022-09-11T13:17:49
2022-09-11T13:17:49
62,557,412
22
6
MIT
2023-04-17T15:07:01
2016-07-04T11:32:41
C++
UTF-8
C++
false
false
7,072
h
/////////////////////////////////////////////////////////////////////////////// // Copyright Christopher Kormanyos 2021. // 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 TEST_UINTWIDE_T_N_BINARY_OPS_MUL_DIV_4_BY_4_TEMPLATE_2021_03_04_H_ #define TEST_UINTWIDE_T_N_BINARY_OPS_MUL_DIV_4_BY_4_TEMPLATE_2021_03_04_H_ #include <atomic> #include <math/wide_integer/uintwide_t.h> #include <test/test_uintwide_t_n_base.h> template<const math::wide_integer::size_t MyWidth2, typename MyLimbType, typename EnableType = void> class test_uintwide_t_n_binary_ops_mul_div_4_by_4_template; template<const math::wide_integer::size_t MyWidth2, typename MyLimbType> class test_uintwide_t_n_binary_ops_mul_div_4_by_4_template <MyWidth2, MyLimbType, typename std::enable_if<( (std::numeric_limits<MyLimbType>::digits * 4 == MyWidth2) && (std::is_fundamental<MyLimbType>::value == true) && (std::is_integral <MyLimbType>::value == true) && (std::is_unsigned <MyLimbType>::value == true))>::type> : public test_uintwide_t_n_binary_ops_base { private: static constexpr math::wide_integer::size_t digits2 = MyWidth2; virtual math::wide_integer::size_t get_digits2 () const { return digits2; } using native_uint_cntrl_type = typename math::wide_integer::detail::uint_type_helper<digits2>::exact_unsigned_type; using local_limb_type = MyLimbType; using local_uint_ab_type = math::wide_integer::uintwide_t<digits2, local_limb_type>; public: test_uintwide_t_n_binary_ops_mul_div_4_by_4_template(const std::size_t count) : test_uintwide_t_n_binary_ops_base(count), a_local(), b_local(), a_cntrl(), b_cntrl() { } virtual ~test_uintwide_t_n_binary_ops_mul_div_4_by_4_template() = default; virtual bool do_test(const std::size_t rounds) { bool result_is_ok = true; for(std::size_t i = 0U; i < rounds; ++i) { std::cout << "initialize() native compare with uintwide_t: round " << i << ", digits2: " << this->get_digits2() << std::endl; this->initialize(); std::cout << "test_binary_mul() native compare with uintwide_t: round " << i << ", digits2: " << this->get_digits2() << std::endl; result_is_ok &= this->test_binary_mul(); std::cout << "test_binary_div() native compare with uintwide_t: round " << i << ", digits2: " << this->get_digits2() << std::endl; result_is_ok &= this->test_binary_div(); } return result_is_ok; } virtual void initialize() { a_local.clear(); b_local.clear(); a_cntrl.clear(); b_cntrl.clear(); a_local.resize(size()); b_local.resize(size()); a_cntrl.resize(size()); b_cntrl.resize(size()); get_equal_random_test_values_cntrl_and_local_n(a_local.data(), a_cntrl.data(), size()); get_equal_random_test_values_cntrl_and_local_n(b_local.data(), b_cntrl.data(), size()); } virtual bool test_binary_mul() const { std::atomic_flag test_lock = ATOMIC_FLAG_INIT; bool result_is_ok = true; my_concurrency::parallel_for ( std::size_t(0U), size(), [&test_lock, &result_is_ok, this](std::size_t i) { const native_uint_cntrl_type c_cntrl = native_uint_cntrl_type(a_cntrl[i]) * b_cntrl[i]; const local_uint_ab_type c_local = static_cast<local_uint_ab_type>(a_local[i]) * static_cast<local_uint_ab_type>(b_local[i]); const std::string str_boost = hexlexical_cast(c_cntrl); const std::string str_local = hexlexical_cast(c_local); while(test_lock.test_and_set()) { ; } result_is_ok &= (str_boost == str_local); test_lock.clear(); } ); return result_is_ok; } virtual bool test_binary_div() const { std::atomic_flag test_lock = ATOMIC_FLAG_INIT; test_uintwide_t_n_binary_ops_base::my_gen.seed(static_cast<typename random_generator_type::result_type>(std::clock())); std::uniform_int_distribution<> dis(1, static_cast<int>(digits2 - 1U)); bool result_is_ok = true; my_concurrency::parallel_for ( std::size_t(0U), size(), [&test_lock, &result_is_ok, this, &dis](std::size_t i) { while(test_lock.test_and_set()) { ; } const std::size_t right_shift_amount = static_cast<std::size_t>(dis(my_gen)); test_lock.clear(); const native_uint_cntrl_type c_cntrl = a_cntrl[i] / (std::max)(native_uint_cntrl_type(1U), native_uint_cntrl_type(b_cntrl[i] >> right_shift_amount)); const local_uint_ab_type c_local = a_local[i] / (std::max)(local_uint_ab_type(1U), (b_local[i] >> right_shift_amount)); const std::string str_boost = hexlexical_cast(c_cntrl); const std::string str_local = hexlexical_cast(c_local); while(test_lock.test_and_set()) { ; } result_is_ok &= (str_boost == str_local); test_lock.clear(); } ); return result_is_ok; } private: std::vector<local_uint_ab_type> a_local; std::vector<local_uint_ab_type> b_local; std::vector<native_uint_cntrl_type> a_cntrl; std::vector<native_uint_cntrl_type> b_cntrl; template<typename OtherLocalUintType, typename OtherCntrlUintType> static void get_equal_random_test_values_cntrl_and_local_n(OtherLocalUintType* u_local, OtherCntrlUintType* u_cntrl, const std::size_t count) { using other_local_uint_type = OtherLocalUintType; using other_cntrl_uint_type = OtherCntrlUintType; test_uintwide_t_n_base::my_random_generator.seed(static_cast<typename std::linear_congruential_engine<std::uint32_t, 48271, 0, 2147483647>::result_type>(std::clock())); using distribution_type = math::wide_integer::uniform_int_distribution<other_local_uint_type::my_width2, typename other_local_uint_type::limb_type>; distribution_type distribution; std::atomic_flag rnd_lock = ATOMIC_FLAG_INIT; my_concurrency::parallel_for ( std::size_t(0U), count, [&u_local, &u_cntrl, &distribution, &rnd_lock](std::size_t i) { while(rnd_lock.test_and_set()) { ; } const other_local_uint_type a = distribution(my_random_generator); rnd_lock.clear(); u_local[i] = a; u_cntrl[i] = static_cast<other_cntrl_uint_type>(a); } ); } }; #endif // TEST_UINTWIDE_T_N_BINARY_OPS_MUL_DIV_4_BY_4_TEMPLATE_2021_03_04_H_
[ "kaminski@cs.uni-potsdam.de" ]
kaminski@cs.uni-potsdam.de
d01500ed985f64e6ad4ad184b90d0e2e93364592
e9d7c12a55dae228bc2c9f1b1819f062cddb3430
/k-ahci.hh
29f0ba5d8469968801684f2d13754a8cd5862baa
[]
no_license
NoorEMobeen/chickadee
33b495e591523036386454afa8da982dcf3953fe
362beaeae5e9e00a10597dcd36c823c2f2259d1e
refs/heads/master
2020-08-06T12:56:12.149657
2019-05-05T17:36:12
2019-05-05T17:36:39
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,196
hh
#ifndef CHICKADEE_K_AHCI_HH #define CHICKADEE_K_AHCI_HH #include "kernel.hh" #include "k-wait.hh" // achistate: communication with modern SATA disks struct ahcistate { // interesting IDE commands // Specification: "ATA/ATAPI Command Set" for ATA-8 enum idecommand { cmd_identify_device = 0xEC, cmd_set_features = 0xEF, cmd_read_fpdma_queued = 0x60, cmd_write_fpdma_queued = 0x61 }; // memory-mapped I/O structures for device communication // Specification/comment field names: "Serial ATA AHCI 1.3.1 Specification" // The kernel finds the MMIO address of a `struct regs` using PCI. // This contains up to 32 `struct portregs`, each corresponding to // a different disk; most communication with the disk uses the // `portregs`. One `ahcistate` corresponds to one disk. struct portregs { uint64_t cmdlist_pa; // PxCLB: physical addr of `cmdheader` array uint64_t rfis_pa; // PxRFIS: physical address of `rfisstate` uint32_t interrupt_status; // PxIS uint32_t interrupt_enable; // PxIE uint32_t command; // PxCMD uint32_t reserved0; uint32_t rstatus; // PxTFD uint32_t psig; // PxSIG uint32_t sstatus; // PxSSTS: 0 means port doesn't exist uint32_t scontrol; // PxSCTL uint32_t serror; // PxSERR [R/clear] uint32_t ncq_active_mask; // PxSACT uint32_t command_mask; // PxCI uint32_t sata_notification; // PxSNTF uint32_t pfbs, sleep; uint32_t reserved[14]; }; struct regs { uint32_t capabilities; // CAP: device capabilities [R] uint32_t ghc; // GHC: global [adapter] control [R/W] uint32_t interrupt_status; // IS: interrupt status [R/clear] uint32_t port_mask; // PI: addressable ports (may not exist) uint32_t ahci_version; // VS uint32_t ccc_control; // CCC_CTL uint32_t ccc_port_mask; // CCC_PORTS uint32_t em_loc, em_ctl, cap2, bohc, reserved[53]; portregs p[32]; }; enum { pcmd_interface_mask = 0xF0000000U, pcmd_interface_active = 0x10000000U, pcmd_interface_idle = 0U, pcmd_command_running = 0x8000, pcmd_rfis_running = 0x4000, pcmd_rfis_enable = 0x0010, pcmd_rfis_clear = 0x8, pcmd_power_up = 0x6, pcmd_start = 0x1U, rstatus_busy = 0x80U, rstatus_datareq = 0x08U, rstatus_error = 0x01U, interrupt_device_to_host = 0x1U, interrupt_ncq_complete = 0x8U, interrupt_error_mask = 0x7D800010U, interrupt_fatal_error_mask = 0x78000000U, // HBFS|HBDS|IFS|TFES ghc_ahci_enable = 0x80000000U, ghc_interrupt_enable = 0x2U }; static inline bool sstatus_active(uint32_t sstatus) { return (sstatus & 0x03) == 3 || ((1U << ((sstatus & 0xF00) >> 8)) & 0x144) != 0; } // DMA structures for device communication // Contains data buffers and commands for disk communication. // This structure lives in host memory; the device finds it via // physical-memory pointers in `portregs`. struct bufstate { // initialized by `push_buffer` uint64_t pa; uint32_t reserved; uint32_t maxbyte; // size of buffer minus 1 }; struct __attribute__((aligned(128))) cmdtable { uint32_t cfis[16]; // command definition; set by `issue_*` uint32_t acmd[4]; uint32_t reserved[12]; bufstate buf[16]; // called PRD in specifications }; struct cmdheader { uint16_t flags; uint16_t nbuf; uint32_t buf_byte_pos; uint64_t cmdtable_pa; // physical address of `cmdtable` uint64_t reserved[2]; }; struct __attribute__((aligned(256))) rfisstate { uint32_t rfis[64]; }; struct __attribute__((aligned(1024))) dmastate { cmdheader ch[32]; volatile rfisstate rfis; cmdtable ct[32]; }; enum { cfis_command = 0x8027, ch_clear_flag = 0x400, ch_write_flag = 0x40 }; static constexpr size_t sectorsize = 512; // DMA and memory-mapped I/O state dmastate dma_; int pci_addr_; int sata_port_; volatile regs* dr_; volatile portregs* pr_; // metadata read from disk at startup (constant thereafter) unsigned irq_; // interrupt number size_t nsectors_; // # sectors on disk unsigned nslots_; // # NCQ slots unsigned slots_full_mask_; // mask with each valid slot set to 1 // modifiable state spinlock lock_; wait_queue wq_; unsigned nslots_available_; // # slots available for commands uint32_t slots_outstanding_mask_; // 1 == that slot is used volatile int* slot_status_[32]; // ptrs to status storage, one per slot ahcistate(int pci_addr, int sata_port, volatile regs* mr); NO_COPY_OR_ASSIGN(ahcistate); static ahcistate* find(int pci_addr = 0, int sata_port = 0); // high-level functions (they block) inline int read(void* buf, size_t sz, size_t off); inline int write(const void* buf, size_t sz, size_t off); int read_or_write(idecommand cmd, void* buf, size_t sz, size_t off); // interrupt handlers void handle_interrupt(); void handle_error_interrupt(); // internal functions void clear(int slot); void push_buffer(int slot, void* data, size_t sz); void issue_meta(int slot, idecommand cmd, int features, int count = -1); void issue_ncq(int slot, idecommand cmd, size_t sector, bool fua = false, int priority = 0); void acknowledge(int slot, int status = 0); void await_basic(int slot); }; inline int ahcistate::read(void* buf, size_t sz, size_t off) { return read_or_write(cmd_read_fpdma_queued, buf, sz, off); } inline int ahcistate::write(const void* buf, size_t sz, size_t off) { return read_or_write(cmd_write_fpdma_queued, const_cast<void*>(buf), sz, off); } #endif
[ "ekohler@gmail.com" ]
ekohler@gmail.com
c533a66a590a143c01c77206870bbfc6763fdc32
5d2d6a0f5f9f12756ed9a80ef4daede2e7d7a320
/includes/Drawable.hh
80c54cd2b634d3cfc98bedde6b9a88ca01fa6342
[]
no_license
z363989254/Bomberman
f1641e77cf73dbd7ef809b60dc2c943cd85d5192
46c2000ea54fb1ab946849b7589a3dc06ffb795f
refs/heads/master
2021-01-06T23:53:37.335149
2015-09-08T15:49:43
2015-09-08T15:49:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
696
hh
// // Background.hh for Bomberman in /home/magrin_j/Project/Bomberman // // Made by Jérémy Magrin // Login <magrin_j@epitech.net> // // Started on Fri Jun 7 17:11:05 2013 Jérémy Magrin // Last update Sun Jun 9 21:51:23 2013 leo chazal // #pragma once #include <Image.hpp> namespace Bomberman { class Drawable { private: gdl::Image _drawables[11]; public: static Drawable *getInstance(void); static void pushOrthoMatrix(float, float); static void popOrthoMatrix(void); static void drawAt(float, float, float, float, gdl::Image &); void drawBg(size_t); private: Drawable(); ~Drawable(); void initialize(void); }; }
[ "bhullnatik@gmail.com" ]
bhullnatik@gmail.com
69cfba894bd98e90fafb56c1bdcbd4534b7a83e4
124e8db708315c87eae0e4ee559612138ac79ce3
/Server/NetworkControler.cpp
d319719a98aead7fc9e2dd86bb2a1a2877b13d14
[]
no_license
protective/anno3112
7e2beec4a0a9892fb084d9237baf770cab655c81
8de8a12880501876d89893d9ed92d118c14ffe38
refs/heads/master
2021-01-22T23:54:32.286050
2014-09-27T20:27:59
2014-09-27T20:27:59
15,630,219
0
0
null
null
null
null
UTF-8
C++
false
false
2,992
cpp
/* * File: NetworkControler.cpp * Author: karsten * * Created on 22. februar 2014, 23:13 */ #include "NetworkControler.h" #include "Client.h" #include "Sspacebjects/SSubAble.h" #include "Commands/Processable.h" NetworkControler::NetworkControler() { pthread_mutex_init(&_clientLock ,NULL); } void NetworkControler::readBuffers(){ for (map<uint32_t, Client*>::iterator ci = _connections.begin(); ci != _connections.end(); ci++){ ReadBuffer(ci->second); ci->second->proces(); } } void NetworkControler::registerObj(uint32_t objId, Processor* processor){ pthread_mutex_lock(&_objRegistrationListLock); _objRegistration[objId] = processor; //cerr<<"networkcontroler::register obj_id="<<objId<<" processerid="<<(uint32_t)processor->getId()<<endl; //TODO GET all processores dealing with the active grid here //cerr<<"register id="<<objId<<endl; processor->addCommand(new CommandAddSubscriptions(processor,SubscriptionLevel::lowFreq,objId)); processor->addCommand(new CommandAddSubscriptions(processor,SubscriptionLevel::Init,objId)); pthread_mutex_unlock(&_objRegistrationListLock); } void NetworkControler::deRegisterObj(uint32_t objId){ pthread_mutex_lock(&_objRegistrationListLock); _objRegistration.erase(objId); pthread_mutex_unlock(&_objRegistrationListLock); } Processor* NetworkControler::getProcessor(uint32_t objId){ Processor* temp; map<uint32_t, Processor*>::iterator it; pthread_mutex_lock(&_objRegistrationListLock); it = _objRegistration.find(objId); temp = it != _objRegistration.end() ? it->second : NULL; pthread_mutex_unlock(&_objRegistrationListLock); return temp; } Processable* NetworkControler::getProcessable(uint32_t objId){ Processor* temp = getProcessor(objId); if(!temp) return NULL; map<uint32_t, Processable*>::iterator it = temp->getLocalProcssables().find(objId); if (it != temp->getLocalProcssables().end()){ return it->second; } return NULL; } uint32_t NetworkControler::addCommandToProcesable(Command* cmd, uint32_t obj){ Processor* temp = getProcessor(obj); if(temp) return temp->addCommand(cmd); return 1; } uint32_t NetworkControler::sendToC(uint32_t id, void* block, uint32_t len){ bool sendt = false; //cerr<<"send to c= "<<id<<endl; pthread_mutex_lock(&_clientLock); map<uint32_t, Client*>::iterator it = _connections.find(id); if (it!= _connections.end()){ //cerr<<"network send len ="<<len<<endl; send(it->second->getSocket(),block, len,MSG_NOSIGNAL); sendt = true; }else cerr<<"ERROR CLIENT NOT FOUND"<<endl; pthread_mutex_unlock(&_clientLock); if(sendt) return 0; else return 1; } void NetworkControler::addClient(Client* client){ cerr<<"add cli before lock"<<endl; pthread_mutex_lock(&_clientLock); cerr<<"add cli ="<<client->getId()<<endl; _connections[client->getId()] = client; pthread_mutex_unlock(&_clientLock); } void NetworkControler::removeClient(Client* client){ _connections.erase(client->getId()); } NetworkControler::~NetworkControler() { }
[ "karstenjjakobsen@gmail.com" ]
karstenjjakobsen@gmail.com
a2f2381089a7d9b9465fcaef40e21bb1b35f3945
b1aa9ad6733efcb53d465809d5109e9174dabf04
/CCode/EngineCode/C4Types.h
0e0d64761046b521373b53758f2f305a976a5d8b
[]
no_license
dumpinfo/GameMatrixTest
d21545dbef9ade76fe092343a8362da4c8b142ca
9e4a73ad17555ddb90020c47e2486698b90e4d0d
refs/heads/master
2023-02-04T01:52:05.342214
2020-12-23T17:22:36
2020-12-23T17:22:36
323,961,033
2
0
null
null
null
null
UTF-8
C++
false
false
16,839
h
#ifndef C4Types_h #define C4Types_h //# \component Utility Library //# \prefix Utilities/ #include "C4Constants.h" #include "C4Shared.h" #include "C4Array.h" #include "C4Tree.h" #include "C4Graph.h" #include "C4Map.h" #include "C4Hash.h" #include "C4Link.h" #include "C4Rect.h" #include "C4String.h" #include "C4Complex.h" #include "C4Bivector4D.h" #include "C4Quaternion.h" #include "C4Completable.h" #include "C4Observable.h" namespace C4 { typedef unsigned_int32 Type; typedef Type EventType; //# \enum KeyCode enum { kKeyCodeEnter = 13, //## The enter key (return key on the Mac). kKeyCodeEscape = 27, //## The escape key. kKeyCodeTab = 9, //## The tab key. kKeyCodeLeftArrow = 28, //## The left arrow key. kKeyCodeRightArrow = 29, //## The right arrow key. kKeyCodeUpArrow = 30, //## The up arrow key. kKeyCodeDownArrow = 31, //## The down arrow key. kKeyCodePageUp = 11, //## The page up key. kKeyCodePageDown = 12, //## The page down key. kKeyCodeHome = 1, //## The home key. kKeyCodeEnd = 4, //## The end key. kKeyCodeDelete = 2, //## The delete key. kKeyCodeBackspace = 8, //## The backspace key. kKeyCodeF1 = 128, //## The F1 key. kKeyCodeF2, //## The F2 key. kKeyCodeF3, //## The F3 key. kKeyCodeF4, //## The F4 key. kKeyCodeF5, //## The F5 key. kKeyCodeF6, //## The F6 key. kKeyCodeF7, //## The F7 key. kKeyCodeF8, //## The F8 key. kKeyCodeF9, //## The F9 key. kKeyCodeF10, //## The F10 key. kKeyCodeF11, //## The F11 key. kKeyCodeF12, //## The F12 key. kKeyCodeF13, kKeyCodeF14, kKeyCodeF15, kKeyCodeF16, kKeyCodeF17, kKeyCodeF18, kKeyCodeF19, kKeyCodeF20, kKeyCodeF21, kKeyCodeF22, kKeyCodeF23, kKeyCodeF24 }; //# \enum MouseEventFlags enum { kMouseDoubleClick = 1 << 0 //## The mouse down event is the second click in a double-click. }; //# \enum KeyboardModifiers enum { kModifierKeyShift = 1 << 0, //## The shift key was held down. kModifierKeyOption = 1 << 1, //## The alt key (option key on the Mac) was held down. kModifierKeyCommand = 1 << 2, //## The control key (command key on the Mac) was held down. kModifierKeyConsole = 1 << 16 }; enum : EventType { kEventNone = 0, kEventMouseDown = 'MSDN', kEventMouseUp = 'MSUP', kEventRightMouseDown = 'RMDN', kEventRightMouseUp = 'RMUP', kEventMiddleMouseDown = 'MMDN', kEventMiddleMouseUp = 'MMUP', kEventMouseMoved = 'MSMV', kEventMouseWheel = 'MSWH', kEventMultiaxisMouseTranslation = 'MATR', kEventMultiaxisMouseRotation = 'MART', kEventMultiaxisMouseButtonState = 'MABS', kEventKeyDown = 'KYDN', kEventKeyUp = 'KYUP', kEventKeyCommand = 'KYCM' }; //# \struct MouseEventData Contains information about a mouse event. // //# The $MouseEventData$ structure contains information about a mouse event. // //# \def struct MouseEventData // //# \data MouseEventData // //# \desc //# The $MouseEventData$ structure contains the event type, mouse position, and special flags //# for a mouse event. The $eventFlags$ field can be a combination (through logical OR) of the //# following constants. // //# \table MouseEventFlags // //# \also $@KeyboardEventData@$ //# \member MouseEventData struct MouseEventData { EventType eventType; //## The type of mouse event. unsigned_int32 eventFlags; //## The event flags for the event. Point3D mousePosition; //## The mouse position associated with the event. Vector2D wheelDelta; //## The wheel delta for $kEventMouseWheel$ events. }; //# \struct KeyboardEventData Contains information about a keyboard event. // //# The $KeyboardEventData$ structure contains information about a keyboard event. // //# \def struct KeyboardEventData // //# \data KeyboardEventData // //# \desc //# The $KeyboardEventData$ structure contains the type of event, the Unicode character, and //# information about modifiers keys for a keyboard event. The $keyCode$ field is set to one of //# the following values if a special key is pressed or released. // //# \table KeyCode // //# Special keys always have codes in the ranges [0x01, 0x1F] or [0x80, 0x9F], and keyboard event handlers //# should not attempt to handle codes in these ranges as ordinary characters. //# //# The $modifierKeys$ field can be a combination (through logical OR) of the following constants. // //# \table KeyboardModifiers // //# \also $@MouseEventData@$ //# \member KeyboardEventData struct KeyboardEventData { EventType eventType; //## The type of keyboard event. unsigned_int32 keyCode; //## The Unicode value for the character associated with the event. unsigned_int32 modifierKeys; //## The modifier keys associated with the event. }; //# \class Range Encapsulates a range of values. // //# The $Range$ class template encapsulates a range of values. // //# \def template <typename type> struct Range // //# \tparam type The type of value used to represent the beginning and end of a range. // //# \data Range // //# \ctor Range(); //# \ctor Range(const type& x, const type& y); // //# \param x The beginning of the range. //# \param y The end of the range. // //# \desc //# The $Range$ class template encapsulates a range of values of the type given by the //# $type$ class template. //# //# The default constructor leaves the beginning and end values of the range undefined. //# If the values $x$ and $y$ are supplied, then they are assigned to the beginning and //# end of the range, respectively. // //# \operator type& operator [](machine index); //# Returns a reference to the minimum value if $index$ is 0, and returns a reference to the maximum value if $index$ is 1. //# The $index$ parameter must be 0 or 1. // //# \operator const type& operator [](machine index) const; //# Returns a constant reference to the minimum value if $index$ is 0, and returns a constant reference to the maximum value if $index$ is 1. //# The $index$ parameter must be 0 or 1. // //# \operator bool operator ==(const Range& range) const; //# Returns a boolean value indicating the equality of two ranges. // //# \operator bool operator !=(const Range& range) const; //# Returns a boolean value indicating the inequality of two ranges. //# \function Range::Set Sets the beginning and end of a range. // //# \proto Range& Set(const type& x, const type& y); // //# \param x The new beginning of the range. //# \param y The new end of the range. // //# \desc //# The $Set$ function sets the beginning and end of a range to the values given by the //# $x$ and $y$ parameters, respectively. //# \member Range template <typename type> struct Range { type min; //## The beginning of the range. type max; //## The end of the range. Range() = default; Range(const Range& range) { min = range.min; max = range.max; } Range(const type& x, const type& y) { min = x; max = y; } type& operator [](machine index) { return ((&min)[index]); } const type& operator [](machine index) const { return ((&min)[index]); } Range& operator =(const Range& range) { min = range.min; max = range.max; return (*this); } Range& Set(const type& x, const type& y) { min = x; max = y; return (*this); } bool operator ==(const Range& range) const { return ((min == range.min) && (max == range.max)); } bool operator !=(const Range& range) const { return ((min != range.min) || (max != range.max)); } }; //# \class Transformable Encapsulates an object-to-world transform and its inverse. // //# The $Transformable$ class encapsulates an object-to-world transform and its inverse. // //# \def class Transformable // //# \ctor Transformable(); // //# \desc //# The $Transformable$ class encapsulates a transform from object space to world space //# and maintains the corresponding inverse transform from world space to object space. //# //# The constructor leaves the transform undefined. //# \function Transformable::SetIdentityTransform Sets the transform to the identity. // //# \proto void SetIdentityTransform(void); // //# \desc //# The $SetIdentityTransform$ function sets both the object-to-world transform and its //# inverse to the identity transform. // //# \also $@Transformable::SetWorldTransform@$ //# \also $@Transformable::SetWorldPosition@$ //# \function Transformable::GetWorldTransform Returns the object-to-world transform. // //# \proto const Transform4D& GetWorldTransform(void) const; // //# \desc //# The $GetWorldTransform$ returns the $@Math/Transform4D@$ object corresponding to the //# transform from object space to world space. // //# \also $@Transformable::GetInverseWorldTransform@$ //# \also $@Transformable::SetWorldTransform@$ //# \also $@Transformable::GetWorldPosition@$ //# \also $@Transformable::SetWorldPosition@$ //# \function Transformable::GetInverseWorldTransform Returns the world-to-object transform. // //# \proto const Transform4D& GetInverseWorldTransform(void) const; // //# \desc //# The $GetInverseWorldTransform$ returns the $@Math/Transform4D@$ object corresponding to the //# transform from world space to object space. The inverse is not calculated at the time //# this function is called, but when the transform is set, so the performance of this function //# is high. // //# \also $@Transformable::GetWorldTransform@$ //# \also $@Transformable::SetWorldTransform@$ //# \also $@Transformable::GetWorldPosition@$ //# \also $@Transformable::SetWorldPosition@$ //# \function Transformable::SetWorldTransform Sets the object-to-world transform and its inverse. // //# \proto void SetWorldTransform(const Transform4D& transform); //# \proto void SetWorldTransform(const Matrix3D& m, const Point3D& p); //# \proto void SetWorldTransform(const Vector3D& c1, const Vector3D& c2, const Vector3D& c3, const Point3D& c4); //# \proto void SetWorldTransform(float n00, float n01, float n02, float n03, float n10, float n11, float n12, float n13, float n20, float n21, float n22, float n23); // //# \param transform The new transform. //# \param m The upper-left 3&nbsp;&times;&nbsp;3 portion of the 4D transform. //# \param p The fourth column of the 4D transform, representing the world position. //# \param c1 The first column of the 4D transform. //# \param c2 The second column of the 4D transform. //# \param c3 The third column of the 4D transform. //# \param c4 The fourth column of the 4D transform. //# \param nij The entry residing in row <i>i</i> and column <i>j</i> of the 4D transform. // //# \desc //# The $SetWorldTransform$ function sets the object-to-world transform. It also calculates //# and stores the inverse representing the transform from world space to object space. // //# \warning //# The $SetWorldTransform$ function is normally called only by internal components of the engine //# during routine update procedures. This function should not be called by external code to directly //# set the world transform of an object. // //# \also $@Transformable::GetWorldTransform@$ //# \also $@Transformable::GetWorldPosition@$ //# \also $@Transformable::SetWorldPosition@$ //# \also $@Transformable::SetIdentityTransform@$ //# \function Transformable::GetWorldPosition Returns the world-space position. // //# \proto const Point3D& GetWorldPosition(void) const; // //# \desc //# The $GetWorldPosition$ function returns the world-space position represented by a //# transform. Calling $GetWorldPosition$ is equivalent to the following. // //# \source //# GetWorldTransform().GetTranslation(); // //# \also $@Transformable::SetWorldPosition@$ //# \also $@Transformable::GetWorldTransform@$ //# \also $@Transformable::SetWorldTransform@$ //# \function Transformable::SetWorldPosition Sets the world-space position. // //# \proto void SetWorldPosition(const Point3D& position); // //# \param position The new world-space position. // //# \desc //# The $SetWorldPosition$ function sets the world-space position to that given by the //# $position$ parameter and recalculates the inverse transform from world space to object space. //# The upper-left 3&nbsp;&times;&nbsp;3 portion of the 4D transform is not affected. // //# \warning //# The $SetWorldPosition$ function is normally called only by internal components of the engine //# during routine update procedures. This function should not be called by external code to directly //# set the world position of an object. // //# \also $@Transformable::GetWorldPosition@$ //# \also $@Transformable::GetWorldTransform@$ //# \also $@Transformable::SetWorldTransform@$ class Transformable { private: Transform4D worldTransform; Transform4D inverseWorldTransform; public: Transformable() = default; void SetIdentityTransform(void) { worldTransform.SetIdentity(); inverseWorldTransform.SetIdentity(); } const Transform4D& GetWorldTransform(void) const { return (worldTransform); } const Point3D& GetWorldPosition(void) const { return (worldTransform.GetTranslation()); } const Transform4D& GetInverseWorldTransform(void) const { return (inverseWorldTransform); } void SetWorldTransform(const Transform4D& transform) { worldTransform = transform; inverseWorldTransform = Inverse(worldTransform); } void SetWorldTransform(const Matrix3D& m, const Point3D& p) { worldTransform.Set(m, p); inverseWorldTransform = Inverse(worldTransform); } void SetWorldTransform(const Vector3D& c1, const Vector3D& c2, const Vector3D& c3, const Point3D& c4) { worldTransform.Set(c1, c2, c3, c4); inverseWorldTransform = Inverse(worldTransform); } void SetWorldTransform(float n00, float n01, float n02, float n03, float n10, float n11, float n12, float n13, float n20, float n21, float n22, float n23) { worldTransform.Set(n00, n01, n02, n03, n10, n11, n12, n13, n20, n21, n22, n23); inverseWorldTransform = Inverse(worldTransform); } void SetWorldPosition(const Point3D& position) { worldTransform.SetTranslation(position); inverseWorldTransform = Inverse(worldTransform); } }; template <class type> class Reference : public ListElement<Reference<type>> { private: type *referenceTarget; public: explicit Reference(type *target) { referenceTarget = target; } ~Reference() { } type *GetTarget(void) const { return (referenceTarget); } }; template <class type> class AutoDelete { private: type *reference; AutoDelete(const AutoDelete&) = delete; public: explicit AutoDelete(type *ptr) { reference = ptr; } ~AutoDelete() { delete reference; } operator type *(void) const { return (reference); } type *const *operator &(void) const { return (&reference); } type *operator ->(void) const { return (reference); } AutoDelete& operator =(type *ptr) { reference = ptr; return (*this); } }; class Buffer { private: char *buffer; public: explicit Buffer(unsigned_int32 size) { buffer = new char[size]; } ~Buffer() { delete[] buffer; } operator void *(void) const { return (buffer); } template <typename type> type *GetPtr(void) const { return (reinterpret_cast<type *>(buffer)); } }; template <class type> class Storage { private: alignas(16) char storage[sizeof(type)]; public: operator type *(void) { return (reinterpret_cast<type *>(storage)); } operator const type *(void) const { return (reinterpret_cast<const type *>(storage)); } type *operator ->(void) { return (reinterpret_cast<type *>(storage)); } const type *operator ->(void) const { return (reinterpret_cast<const type *>(storage)); } }; } #endif // ZYUQURM
[ "twtravel@126.com" ]
twtravel@126.com
ce080f7890f4cdf8328eb7f10738a08556a778eb
89f8073f32c5e76c36d7e3072002015a5646119f
/common files/sum of e an i.cpp
761c4ca814a042aa023bc53b787881186a5fc903
[]
no_license
PulockDas/Competitive-Programming-Algorithms
f19b8eab081e73c01b4a8ba8673c9df752ff3646
2b3774a34170f10e81ec5b3479f4a49bc138e938
refs/heads/main
2023-06-11T20:59:57.458069
2021-06-29T19:54:05
2021-06-29T19:54:05
308,912,300
0
0
null
null
null
null
UTF-8
C++
false
false
315
cpp
#include <iostream> using namespace std; main () { int n,e,ep; cin>>n; int a; for (int i=0;i<n;i++) { cin>>a; ep=a%10; a=a/10; while(a!=0) { e=a%10; a=a/10; } cout<<"Sum = "<<ep+e<<endl; } }
[ "pulock46@student.sust.edu" ]
pulock46@student.sust.edu
39ba27017847feb75d267b8e7dc07a34fe07448c
e2400461ad0ee9db8a85a30c811e47d30e16e1c8
/seleniumtestcases-qa/seleniumtestcases-qa/src/main/resources/firefox/win64/firefox-sdk/include/nsIDOMSerializer.h
5872abef473cde998cd028f472db4047b936caa0
[]
no_license
pratikcactus/Insights
720a00187858bbca5b2d8cc36aee23e50c74efbc
0c3178a50d60ba4c14a07f6515a84f0ce22cdc8e
refs/heads/master
2021-01-19T14:48:56.139872
2018-01-23T07:12:47
2018-01-23T07:12:47
100,924,200
0
0
null
null
null
null
UTF-8
C++
false
false
4,265
h
/* * DO NOT EDIT. THIS FILE IS GENERATED FROM ../../../dist/idl\nsIDOMSerializer.idl */ #ifndef __gen_nsIDOMSerializer_h__ #define __gen_nsIDOMSerializer_h__ #ifndef __gen_nsISupports_h__ #include "nsISupports.h" #endif /* For IDL files that don't want to include root IDL files. */ #ifndef NS_NO_VTABLE #define NS_NO_VTABLE #endif class nsIOutputStream; /* forward declaration */ class nsIDOMNode; /* forward declaration */ /* starting interface: nsIDOMSerializer */ #define NS_IDOMSERIALIZER_IID_STR "9fd4ba15-e67c-4c98-b52c-7715f62c9196" #define NS_IDOMSERIALIZER_IID \ {0x9fd4ba15, 0xe67c, 0x4c98, \ { 0xb5, 0x2c, 0x77, 0x15, 0xf6, 0x2c, 0x91, 0x96 }} class NS_NO_VTABLE nsIDOMSerializer : public nsISupports { public: NS_DECLARE_STATIC_IID_ACCESSOR(NS_IDOMSERIALIZER_IID) /* AString serializeToString (in nsIDOMNode root); */ NS_IMETHOD SerializeToString(nsIDOMNode *root, nsAString & _retval) = 0; /* void serializeToStream (in nsIDOMNode root, in nsIOutputStream stream, in AUTF8String charset); */ NS_IMETHOD SerializeToStream(nsIDOMNode *root, nsIOutputStream *stream, const nsACString & charset) = 0; }; NS_DEFINE_STATIC_IID_ACCESSOR(nsIDOMSerializer, NS_IDOMSERIALIZER_IID) /* Use this macro when declaring classes that implement this interface. */ #define NS_DECL_NSIDOMSERIALIZER \ NS_IMETHOD SerializeToString(nsIDOMNode *root, nsAString & _retval) override; \ NS_IMETHOD SerializeToStream(nsIDOMNode *root, nsIOutputStream *stream, const nsACString & charset) override; /* Use this macro when declaring the members of this interface when the class doesn't implement the interface. This is useful for forwarding. */ #define NS_DECL_NON_VIRTUAL_NSIDOMSERIALIZER \ NS_METHOD SerializeToString(nsIDOMNode *root, nsAString & _retval); \ NS_METHOD SerializeToStream(nsIDOMNode *root, nsIOutputStream *stream, const nsACString & charset); /* Use this macro to declare functions that forward the behavior of this interface to another object. */ #define NS_FORWARD_NSIDOMSERIALIZER(_to) \ NS_IMETHOD SerializeToString(nsIDOMNode *root, nsAString & _retval) override { return _to SerializeToString(root, _retval); } \ NS_IMETHOD SerializeToStream(nsIDOMNode *root, nsIOutputStream *stream, const nsACString & charset) override { return _to SerializeToStream(root, stream, charset); } /* Use this macro to declare functions that forward the behavior of this interface to another object in a safe way. */ #define NS_FORWARD_SAFE_NSIDOMSERIALIZER(_to) \ NS_IMETHOD SerializeToString(nsIDOMNode *root, nsAString & _retval) override { return !_to ? NS_ERROR_NULL_POINTER : _to->SerializeToString(root, _retval); } \ NS_IMETHOD SerializeToStream(nsIDOMNode *root, nsIOutputStream *stream, const nsACString & charset) override { return !_to ? NS_ERROR_NULL_POINTER : _to->SerializeToStream(root, stream, charset); } #if 0 /* Use the code below as a template for the implementation class for this interface. */ /* Header file */ class nsDOMSerializer : public nsIDOMSerializer { public: NS_DECL_ISUPPORTS NS_DECL_NSIDOMSERIALIZER nsDOMSerializer(); private: ~nsDOMSerializer(); protected: /* additional members */ }; /* Implementation file */ NS_IMPL_ISUPPORTS(nsDOMSerializer, nsIDOMSerializer) nsDOMSerializer::nsDOMSerializer() { /* member initializers and constructor code */ } nsDOMSerializer::~nsDOMSerializer() { /* destructor code */ } /* AString serializeToString (in nsIDOMNode root); */ NS_IMETHODIMP nsDOMSerializer::SerializeToString(nsIDOMNode *root, nsAString & _retval) { return NS_ERROR_NOT_IMPLEMENTED; } /* void serializeToStream (in nsIDOMNode root, in nsIOutputStream stream, in AUTF8String charset); */ NS_IMETHODIMP nsDOMSerializer::SerializeToStream(nsIDOMNode *root, nsIOutputStream *stream, const nsACString & charset) { return NS_ERROR_NOT_IMPLEMENTED; } /* End of implementation class template. */ #endif #define NS_XMLSERIALIZER_CID \ { /* a6cf9124-15b3-11d2-932e-00805f8add32 */ \ 0xa6cf9124, 0x15b3, 0x11d2, \ {0x93, 0x2e, 0x00, 0x80, 0x5f, 0x8a, 0xdd, 0x32} } #define NS_XMLSERIALIZER_CONTRACTID \ "@mozilla.org/xmlextras/xmlserializer;1" #endif /* __gen_nsIDOMSerializer_h__ */
[ "pratik.sidam@cactusglobal.com" ]
pratik.sidam@cactusglobal.com
6fd7e86a822a3f9898da38c5754fc586ccf2fb6a
7e38fc9705e48e4a7e6a003a8c414e8c3999424b
/CELib/TlsDevice.h
285380e63b08cd42ee4260465a84ebf68ecb9041
[]
no_license
vivianng30/rainer-fabian-gui
e5118df24ed6eab51b819499e0680b804e7eb87a
2ca6f43513487fdf9a10c9354736449b300e21b5
refs/heads/master
2020-03-28T11:11:26.391374
2018-09-20T13:48:54
2018-09-20T13:48:54
148,186,875
0
0
null
null
null
null
UTF-8
C++
false
false
2,334
h
//============================================================================= //============================================================================= #ifndef __TLS_DEVICE_H__ #define __TLS_DEVICE_H__ #include <iphlpapi.h> //===========================================================================// class CTlsDevice { public: CTlsDevice(); virtual ~CTlsDevice(); /*int GetVersion(); bool IsInEmulator(); void GetDeviceBuild(CStringW& sBuild); */ //ok static CStringW GetDeviceID(); static CStringW GetSerialNumberFromKernelIoControl(); static void GetDeviceInfo(); static int GetAdapterInfo(); static void ParseData(); static CStringW GetMAC(); static CStringW GetUniqueMacID(); //void GetDeviceID(char* pszBuffer); // //BYTE GetBatteryFlag(); //ok //BYTE GetBackupBatteryLifePercent(); //ok //BYTE GetBackupBatteryFlag(); //ok //DWORD GetAvailableMemory(); //ok //BYTE GetBatteryLifePercent(); //ok //ULONG GetFreeFlashSpace(); //ok //bool SetSysTime(DWORD dwNewTime); //void DbgSetBatteryFlag(bool bPower); //void BeepSuccess(); //void BeepQuestion(); //ok //void BeepWarning(); //void BeepError(); //ok //void BeepAkku(); //ok // /*bool IsSipVisible(); void ShowSip(bool bShow); */ //static bool RegisterComDll(CStringW sDll); //void Reboot()=0; //ok //void Calibrate()=0; //void PowerOff()=0; //ok //void SetLocalTime(CTlsTime tm)=0; //void PreventSystemPowerDown(){}; //ok /*void EnableRegFlush() {}; void DisableRegFlush() {}; void FlushReg() {};*/ static PIP_ADAPTER_INFO pinfo; static unsigned long len; static CStringW m_macaddress; static CStringW m_uniqueid; static CStringW m_description; static CStringW m_type; static CStringW m_subnet; static CStringW m_IpAddress; static CStringW m_gateway; static CStringW m_PrimaryWinsServer; static CStringW m_dhcp; }; #endif /*============================================================================= E O F =============================================================================*/
[ "quang.nguyen@vyaire.com" ]
quang.nguyen@vyaire.com
f3f295508045a61fbcec92b5a57e237439e37f0f
a832f88501dcc2ed2803d8d2e99c5e653c55fb86
/src/vnx_search_archive.cpp
8bf1369ea8716298972e04a1532ba0bd6bc5f5c0
[]
no_license
bucaklilar6-web/vnx-search
0b610cdb392d9887d1ef91a72acb6a73a711c85d
12fbad35f1786e02980e148615822fd0d65a3af9
refs/heads/master
2023-04-05T19:35:27.487674
2021-04-25T18:16:25
2021-04-25T18:16:25
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,072
cpp
/* * vnx_search_archive.cpp * * Created on: Jul 1, 2020 * Author: mad */ #include <vnx/keyvalue/Server.h> #include <vnx/search/ArchiveProxy.h> #include <vnx/search/ArchiveServer.h> #include <vnx/addons/HttpServer.h> #include <vnx/vnx.h> #include <vnx/Terminal.h> #include <vnx/Server.h> #include <vnx/Proxy.h> int main(int argc, char** argv) { std::map<std::string, std::string> options; options["f"] = "frontend"; options["frontend"] = "frontend server url"; vnx::init("vnx_search_archive", argc, argv, options); std::string frontend = ".vnx_search_frontend.sock"; vnx::read_config("frontend", frontend); { vnx::Handle<vnx::Terminal> terminal = new vnx::Terminal("Terminal"); terminal.start_detached(); } { vnx::Handle<vnx::Server> server = new vnx::Server("Server", vnx::Endpoint::from_url(".vnx_search_archive.sock")); server.start_detached(); } { vnx::Handle<vnx::Proxy> proxy = new vnx::Proxy("Proxy", vnx::Endpoint::from_url(frontend)); proxy->import_list.push_back("frontend.http_responses"); proxy.start_detached(); } { vnx::Handle<vnx::keyvalue::Server> module = new vnx::keyvalue::Server("HttpArchive"); module->do_compress = true; module->collection = "http_archive"; module->update_topic = "http_archive.updates"; module->update_topic_keys = "http_archive.key_updates"; module.start_detached(); } { vnx::Handle<vnx::search::ArchiveProxy> module = new vnx::search::ArchiveProxy("ArchiveProxy"); module->input_http = "frontend.http_responses"; module.start_detached(); } std::string archive_path; { vnx::Handle<vnx::search::ArchiveServer> module = new vnx::search::ArchiveServer("ArchiveServer"); archive_path = module->path; module.start_detached(); } { vnx::Handle<vnx::addons::HttpServerBase> module = vnx::addons::new_HttpServer("HttpServer"); module->chunk_size = 16 * 1024 * 1024; module->components[archive_path] = "ArchiveServer"; module->output_request = "http.request"; module->output_response = "http.response"; module.start_detached(); } vnx::wait(); }
[ "max.wittal@mwittal.de" ]
max.wittal@mwittal.de
dc28b7c00d60e61742c4ba6ec82fc2628c61b012
37b7f418beb3c37c273d9c60add94b7dc83fe0ac
/NeoML/src/Dnn/Layers/BinaryCrossEntropyLayer.cpp
41f28172abca8d8967e5118763a8850799279016
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference", "BSD-3-Clause", "LicenseRef-scancode-generic-cla", "NCSA", "MIT", "LicenseRef-scancode-protobuf", "LicenseRef-scancode-arm-llvm-sga", "Intel", "LLVM-exception" ]
permissive
MTETERIN/neoml
d7ad604acdf9f5bc012e3d01461ebd650c7c0121
0a69f76507c194de092b82ed28bc55187cc8573b
refs/heads/master
2022-12-11T18:15:23.312458
2020-09-03T15:11:42
2020-09-03T15:11:42
272,790,129
0
0
NOASSERTION
2020-09-03T15:11:43
2020-06-16T19:03:41
null
UTF-8
C++
false
false
6,262
cpp
/* Copyright © 2017-2020 ABBYY Production LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --------------------------------------------------------------------------------------------------------------*/ #include <common.h> #pragma hdrstop #include <NeoML/Dnn/Layers/LossLayer.h> namespace NeoML { CBinaryCrossEntropyLossLayer::CBinaryCrossEntropyLossLayer( IMathEngine& mathEngine ) : CLossLayer( mathEngine, "CCnnBinaryCrossEntropyLossLayer" ), positiveWeightMinusOneValue( 0 ) { } void CBinaryCrossEntropyLossLayer::SetPositiveWeight( float value ) { positiveWeightMinusOneValue = value - 1; } float CBinaryCrossEntropyLossLayer::GetPositiveWeight() const { return positiveWeightMinusOneValue + 1; } void CBinaryCrossEntropyLossLayer::BatchCalculateLossAndGradient( int batchSize, CConstFloatHandle data, int vectorSize, CConstFloatHandle label, int labelSize, CFloatHandle lossValue, CFloatHandle lossGradient ) { // This layer can only work with a binary classificaion problem // Therefore the labels vector can only contain {-1, 1} values NeoAssert(vectorSize == 1 && labelSize == 1); CFloatHandleStackVar one( MathEngine() ); one.SetValue( 1.f ); CFloatHandleStackVar half( MathEngine() ); half.SetValue( 0.5f ); CFloatHandleStackVar minusOne( MathEngine() ); minusOne.SetValue( -1.f ); CFloatHandleStackVar zero( MathEngine() ); zero.SetValue( 0.f ); CFloatHandleStackVar positiveWeightMinusOne( MathEngine() ); positiveWeightMinusOne.SetValue( positiveWeightMinusOneValue ); // Convert the target values to [0, 1] range using the binaryLabel = 0.5 * ( label + 1 ) formula CFloatHandleStackVar binaryLabel( MathEngine(), batchSize ); MathEngine().VectorAddValue( label, binaryLabel, batchSize, one ); MathEngine().VectorMultiply( binaryLabel, binaryLabel, batchSize, half ); // Notations: // x = logits, z = labels, q = pos_weight, l = 1 + (q - 1) * z // The original loss function formula: // loss = (1 - z) * x + l * log(1 + exp(-x)) // The formula to avoid overflow for large exponent power in exp(-x): // loss = (1 - z) * x + l * (log(1 + exp(-abs(x))) + max(-x, 0)) // (1-z)*x CFloatHandleStackVar temp( MathEngine(), batchSize); MathEngine().VectorAddValue( binaryLabel, temp, batchSize, minusOne ); MathEngine().VectorEltwiseNegMultiply( temp, data, temp, batchSize ); // l = (1 + (q - 1) * z), CFloatHandleStackVar temp2( MathEngine(), batchSize ); MathEngine().VectorMultiply( binaryLabel, temp2, batchSize, positiveWeightMinusOne ); MathEngine().VectorAddValue( temp2, temp2, batchSize, one ); // max(-x, 0) CFloatHandleStackVar temp3( MathEngine(), batchSize ); MathEngine().VectorNegMultiply( data, temp3, batchSize, one ); MathEngine().VectorReLU( temp3, temp3, batchSize, zero ); // log( 1 + e^-|x|) CFloatHandleStackVar temp4( MathEngine(), batchSize ); MathEngine().VectorAbs( data, temp4, batchSize ); MathEngine().VectorNegMultiply( temp4, temp4, batchSize, one ); MathEngine().VectorExp( temp4, temp4, batchSize ); MathEngine().VectorAddValue( temp4, temp4, batchSize, one ); MathEngine().VectorLog( temp4, temp4, batchSize ); // l * (log(1 + exp(-abs(x))) + max(-x, 0)) MathEngine().VectorAdd( temp3, temp4, lossValue, batchSize ); MathEngine().VectorEltwiseMultiply( lossValue, temp2, lossValue, batchSize ); // The loss MathEngine().VectorAdd( lossValue, temp, lossValue, batchSize ); if( !lossGradient.IsNull() ) { // loss' = (1-z) - l / ( 1+exp(x) ) = (1-z) - l * sigmoid(-x) // (z-1) CFloatHandleStackVar temp5( MathEngine(), batchSize ); MathEngine().VectorAddValue( binaryLabel, temp5, batchSize, minusOne ); // -x CFloatHandleStackVar temp6( MathEngine(), batchSize ); MathEngine().VectorNegMultiply( data, temp6, batchSize, one ); // sigmoid(-x) calculateStableSigmoid( temp6, temp6, batchSize ); //MathEngine().VectorSigmoid( temp6, temp6, batchSize ); // l * sigmoid(-x) MathEngine().VectorEltwiseMultiply( temp6, temp2, temp6, batchSize ); // (z-1) + l * sigmoid(-x) MathEngine().VectorAdd( temp5, temp6, lossGradient, batchSize ); //(1-z) - l * sigmoid(-x) MathEngine().VectorNegMultiply( lossGradient, lossGradient, batchSize, one ); } } // Overflow-safe sigmoid calculation void CBinaryCrossEntropyLossLayer::calculateStableSigmoid( const CConstFloatHandle& firstHandle, const CFloatHandle& resultHandle, int vectorSize ) const { CFloatHandleStackVar one( MathEngine() ); one.SetValue( 1.f ); CFloatHandleStackVar zero( MathEngine() ); zero.SetValue( 0.f ); // The sigmoid formula: // Sigmoid(x) = 1 / (1 + e^-x ) // The formula to avoid overflow for large exponent power in exp(-x): // Sigmoid(x) = e^(-max(-x, 0) ) / ( 1 + e^-|x| ) // e^(-max(-x, 0) ) CFloatHandleStackVar temp( MathEngine(), vectorSize ); MathEngine().VectorNegMultiply( firstHandle, temp, vectorSize, one ); MathEngine().VectorReLU( temp, temp, vectorSize, zero ); MathEngine().VectorNegMultiply( temp, temp, vectorSize, one ); MathEngine().VectorExp( temp, temp, vectorSize ); // ( 1 + e^-|x| ) CFloatHandleStackVar temp2( MathEngine(), vectorSize ); MathEngine().VectorAbs( firstHandle, temp2, vectorSize ); MathEngine().VectorNegMultiply( temp2, temp2, vectorSize, one ); MathEngine().VectorExp( temp2, temp2, vectorSize ); MathEngine().VectorAddValue( temp2, temp2, vectorSize, one ); // The sigmoid MathEngine().VectorEltwiseDivide( temp, temp2, resultHandle, vectorSize ); } static const int BinaryCrossEntropyLossLayerVersion = 2000; void CBinaryCrossEntropyLossLayer::Serialize( CArchive& archive ) { archive.SerializeVersion( BinaryCrossEntropyLossLayerVersion, CDnn::ArchiveMinSupportedVersion ); CLossLayer::Serialize( archive ); archive.Serialize( positiveWeightMinusOneValue ); } } // namespace NeoML
[ "buildtech@abbyy.com" ]
buildtech@abbyy.com
9b0f4004d149d877247b7143bb6cd005845d9762
3eddb1bccfa8932f4a3095fd8c90f78087ef07d8
/q14.cpp
c63d27f30e52ec0807f405f0bc657f2594bb27af
[]
no_license
pritambiswas544/lab_9
9094755d5b0a50d312656f317920f1029cf24787
2a243d7eae7775f544dcc6d3d93838cad2865227
refs/heads/master
2020-04-05T11:09:56.063533
2018-11-22T23:39:51
2018-11-22T23:39:51
156,825,275
0
0
null
null
null
null
UTF-8
C++
false
false
481
cpp
//add the library #include<iostream> using namespace std; //main int main(){ //declaring the character array char arr[13]="Pritam Biswas"; //Display the whole array cout<<arr<<endl<<endl; cout<<"Display by index method"<<endl; //Display by index method for (int i=0;i<13;i++){ cout<<arr[i]<<endl; } cout<<endl<<"Display by pointer method"<<endl; //Display by pointer method char *p = &arr[0]; for (int i=0;i<13;i++){ cout<<*(p+i)<<endl; } return 7; }
[ "noreply@github.com" ]
pritambiswas544.noreply@github.com
57c2b6a9edf14d14e9bcc13592f0ec19edea4866
87aba51b1f708b47d78b5c4180baf731d752e26d
/Replication/DataFileSystem/PRODUCT_SOURCE_CODE/itk/Modules/Core/Common/include/itkTorusInteriorExteriorSpatialFunction.hxx
6f63fe33f05e31967768cca9f74fc3ec264480f7
[]
no_license
jstavr/Architecture-Relation-Evaluator
12c225941e9a4942e83eb6d78f778c3cf5275363
c63c056ee6737a3d90fac628f2bc50b85c6bd0dc
refs/heads/master
2020-12-31T05:10:08.774893
2016-05-14T16:09:40
2016-05-14T16:09:40
58,766,508
0
0
null
null
null
null
UTF-8
C++
false
false
2,577
hxx
/*========================================================================= * * Copyright Insight Software Consortium * * 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.txt * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *=========================================================================*/ #ifndef __itkTorusInteriorExteriorSpatialFunction_hxx #define __itkTorusInteriorExteriorSpatialFunction_hxx #include "itkTorusInteriorExteriorSpatialFunction.h" namespace itk { template< unsigned int VDimension, typename TInput > TorusInteriorExteriorSpatialFunction< VDimension, TInput > ::TorusInteriorExteriorSpatialFunction() { m_Origin.Fill(0.0); // These default values are not picked for any particular reason m_MajorRadius = 3; m_MinorRadius = 1; } template< unsigned int VDimension, typename TInput > TorusInteriorExteriorSpatialFunction< VDimension, TInput > ::~TorusInteriorExteriorSpatialFunction() {} template< unsigned int VDimension, typename TInput > typename TorusInteriorExteriorSpatialFunction< VDimension, TInput >::OutputType TorusInteriorExteriorSpatialFunction< VDimension, TInput > ::Evaluate(const InputType & position) const { double x = position[0] - m_Origin[0]; double y = position[1] - m_Origin[1]; double z = position[2] - m_Origin[2]; double k = vcl_pow(m_MajorRadius - vcl_sqrt(x * x + y * y), 2.0) + z * z; if ( k <= ( m_MinorRadius * m_MinorRadius ) ) { return true; } else { return false; } } template< unsigned int VDimension, typename TInput > void TorusInteriorExteriorSpatialFunction< VDimension, TInput > ::PrintSelf(std::ostream & os, Indent indent) const { Superclass::PrintSelf(os, indent); unsigned int i; os << indent << "Origin: ["; for ( i = 0; i < VDimension - 1; i++ ) { os << m_Origin[i] << ", "; } os << "]" << std::endl; os << indent << "Major radius: " << m_MajorRadius << std::endl; os << indent << "Minor radius: " << m_MinorRadius << std::endl; } } // end namespace itk #endif
[ "jstavr2@gmail.com" ]
jstavr2@gmail.com
0b37ddd685c341ed620d21eae4aecb7d7d805731
eb5cf33b808de4f35f836cc90715be601c19144a
/Classes/AppDelegate.cpp
4b1cf5455116607b1e616caf4221d5c70edfe774
[]
no_license
kevenxiang/actual_chap06
8202f5956931a43499bb0d1d7f92e84922cdd7eb
102e07e9f37bac416af30aab1ce3c54a5ab86c0f
refs/heads/master
2020-12-03T03:45:06.698976
2017-06-29T11:08:46
2017-06-29T11:08:46
95,769,576
0
0
null
null
null
null
UTF-8
C++
false
false
4,446
cpp
#include "AppDelegate.h" #include "HelloWorldScene.h" #include "TouchOneByOneTest.hpp" #include "ContentLayer.hpp" #include "TouchPriorityTest.hpp" #include "AccelerometerTest.hpp" #include "CustomTest.hpp" // #define USE_AUDIO_ENGINE 1 // #define USE_SIMPLE_AUDIO_ENGINE 1 #if USE_AUDIO_ENGINE && USE_SIMPLE_AUDIO_ENGINE #error "Don't use AudioEngine and SimpleAudioEngine at the same time. Please just select one in your game!" #endif #if USE_AUDIO_ENGINE #include "audio/include/AudioEngine.h" using namespace cocos2d::experimental; #elif USE_SIMPLE_AUDIO_ENGINE #include "audio/include/SimpleAudioEngine.h" using namespace CocosDenshion; #endif USING_NS_CC; static cocos2d::Size designResolutionSize = cocos2d::Size(480, 320); static cocos2d::Size smallResolutionSize = cocos2d::Size(480, 320); static cocos2d::Size mediumResolutionSize = cocos2d::Size(1024, 768); static cocos2d::Size largeResolutionSize = cocos2d::Size(2048, 1536); AppDelegate::AppDelegate() { } AppDelegate::~AppDelegate() { #if USE_AUDIO_ENGINE AudioEngine::end(); #elif USE_SIMPLE_AUDIO_ENGINE SimpleAudioEngine::end(); #endif } // if you want a different context, modify the value of glContextAttrs // it will affect all platforms void AppDelegate::initGLContextAttrs() { // set OpenGL context attributes: red,green,blue,alpha,depth,stencil GLContextAttrs glContextAttrs = {8, 8, 8, 8, 24, 8}; GLView::setGLContextAttrs(glContextAttrs); } // if you want to use the package manager to install more packages, // don't modify or remove this function static int register_all_packages() { return 0; //flag for packages manager } bool AppDelegate::applicationDidFinishLaunching() { // initialize director auto director = Director::getInstance(); auto glview = director->getOpenGLView(); if(!glview) { #if (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32) || (CC_TARGET_PLATFORM == CC_PLATFORM_MAC) || (CC_TARGET_PLATFORM == CC_PLATFORM_LINUX) glview = GLViewImpl::createWithRect("actual_chap06", cocos2d::Rect(0, 0, designResolutionSize.width, designResolutionSize.height)); #else glview = GLViewImpl::create("actual_chap06"); #endif director->setOpenGLView(glview); } // turn on display FPS director->setDisplayStats(true); // set FPS. the default value is 1.0/60 if you don't call this director->setAnimationInterval(1.0f / 60); // Set the design resolution glview->setDesignResolutionSize(designResolutionSize.width, designResolutionSize.height, ResolutionPolicy::NO_BORDER); auto frameSize = glview->getFrameSize(); // if the frame's height is larger than the height of medium size. if (frameSize.height > mediumResolutionSize.height) { director->setContentScaleFactor(MIN(largeResolutionSize.height/designResolutionSize.height, largeResolutionSize.width/designResolutionSize.width)); } // if the frame's height is larger than the height of small size. else if (frameSize.height > smallResolutionSize.height) { director->setContentScaleFactor(MIN(mediumResolutionSize.height/designResolutionSize.height, mediumResolutionSize.width/designResolutionSize.width)); } // if the frame's height is smaller than the height of medium size. else { director->setContentScaleFactor(MIN(smallResolutionSize.height/designResolutionSize.height, smallResolutionSize.width/designResolutionSize.width)); } register_all_packages(); // create a scene. it's an autorelease object auto scene = CustomTest::createScene(); // run director->runWithScene(scene); return true; } // This function will be called when the app is inactive. Note, when receiving a phone call it is invoked. void AppDelegate::applicationDidEnterBackground() { Director::getInstance()->stopAnimation(); #if USE_AUDIO_ENGINE AudioEngine::pauseAll(); #elif USE_SIMPLE_AUDIO_ENGINE SimpleAudioEngine::getInstance()->pauseBackgroundMusic(); SimpleAudioEngine::getInstance()->pauseAllEffects(); #endif } // this function will be called when the app is active again void AppDelegate::applicationWillEnterForeground() { Director::getInstance()->startAnimation(); #if USE_AUDIO_ENGINE AudioEngine::resumeAll(); #elif USE_SIMPLE_AUDIO_ENGINE SimpleAudioEngine::getInstance()->resumeBackgroundMusic(); SimpleAudioEngine::getInstance()->resumeAllEffects(); #endif }
[ "1806322519@qq.com" ]
1806322519@qq.com
58e9ac31ff123567f234c44d22f284f63c5511f6
7ee32ddb0cdfdf1993aa4967e1045790690d7089
/Topcoder/StoneGame.cpp
5d1062ea32a6382e076e8504785f56af572fc0e2
[]
no_license
ajimenezh/Programing-Contests
b9b91c31814875fd5544d63d7365b3fc20abd354
ad47d1f38b780de46997f16fbaa3338c9aca0e1a
refs/heads/master
2020-12-24T14:56:14.154367
2017-10-16T21:05:01
2017-10-16T21:05:01
11,746,917
1
2
null
null
null
null
UTF-8
C++
false
false
6,006
cpp
#include <iostream> #include <sstream> #include <vector> #include <string.h> #include <algorithm> #include <utility> #include <set> #include <map> #include <deque> #include <queue> #include <cmath> #include <cstdlib> #include <ctime> #include <cstdio> #include <stdio.h> using namespace std; #define rep(it,s) for(__typeof((s).begin()) it=(s).begin();it!=(s).end();it++) class StoneGame { public: int getScore(vector <int> treasure, vector <int> stones) ; }; int StoneGame::getScore(vector <int> treasure, vector <int> stones) { int p = 0; while (true) { bool done = 0; int last = -1; for (int i=0; i<treasure.size(); i++) { if (stones[i]==1) { if (last!=-1) { if (treasure[last]<treasure[i]) { stones[last]++; stones[i]--; p -= treasure[last]; p += treasure[i]; last = i; } } else { stones[i]--; p += treasure[i]; done = 1; last = i; done = 1; } } } if (!done) { for (int i=0; i<treasure.size(); i++) { if (stones[i]>2) { stones[i]--; done = 1; break; } } } if (!done) { for (int i=0; i<treasure.size(); i++) { if (stones[i]==2) { stones[i]--; done = 1; break; } } } if (!done) break; done = 0; last = -1; for (int i=0; i<treasure.size(); i++) { if (stones[i]==1) { if (last!=-1) { if (treasure[last]<treasure[i]) { stones[last]++; stones[i]--; last = i; } } else { stones[i]--; done = 1; last = i; done = 1; } } } if (!done) { for (int i=0; i<treasure.size(); i++) { if (stones[i]>2) { stones[i]--; done = 1; break; } } } if (!done) { for (int i=0; i<treasure.size(); i++) { if (stones[i]==2) { stones[i]--; done = 1; break; } } } if (!done) break; if (!done) break; } return p; }; //BEGIN CUT HERE #include <ctime> #include <cmath> #include <string> #include <vector> #include <sstream> #include <iostream> #include <algorithm> using namespace std; int main(int argc, char* argv[]) { if (argc == 1) { cout << "Testing StoneGame (500.0 points)" << endl << endl; for (int i = 0; i < 20; i++) { ostringstream s; s << argv[0] << " " << i; int exitCode = system(s.str().c_str()); if (exitCode) cout << "#" << i << ": Runtime Error" << endl; } int T = time(NULL)-1391000642; double PT = T/60.0, TT = 75.0; cout.setf(ios::fixed,ios::floatfield); cout.precision(2); cout << endl; cout << "Time : " << T/60 << " minutes " << T%60 << " secs" << endl; cout << "Score : " << 500.0*(.3+(.7*TT*TT)/(10.0*PT*PT+TT*TT)) << " points" << endl; } else { int _tc; istringstream(argv[1]) >> _tc; StoneGame _obj; int _expected, _received; time_t _start = clock(); switch (_tc) { case 0: { int treasure[] = {3,2}; int stones[] = {1,2}; _expected = 5; _received = _obj.getScore(vector <int>(treasure, treasure+sizeof(treasure)/sizeof(int)), vector <int>(stones, stones+sizeof(stones)/sizeof(int))); break; } case 1: { int treasure[] = {5,4,3,2,1}; int stones[] = {1,1,1,1,1}; _expected = 9; _received = _obj.getScore(vector <int>(treasure, treasure+sizeof(treasure)/sizeof(int)), vector <int>(stones, stones+sizeof(stones)/sizeof(int))); break; } case 2: { int treasure[] = {5,5}; int stones[] = {2,2}; _expected = 0; _received = _obj.getScore(vector <int>(treasure, treasure+sizeof(treasure)/sizeof(int)), vector <int>(stones, stones+sizeof(stones)/sizeof(int))); break; } case 3: { int treasure[] = {1}; int stones[] = {10}; _expected = 0; _received = _obj.getScore(vector <int>(treasure, treasure+sizeof(treasure)/sizeof(int)), vector <int>(stones, stones+sizeof(stones)/sizeof(int))); break; } /*case 4: { int treasure[] = ; int stones[] = ; _expected = ; _received = _obj.getScore(vector <int>(treasure, treasure+sizeof(treasure)/sizeof(int)), vector <int>(stones, stones+sizeof(stones)/sizeof(int))); break; }*/ /*case 5: { int treasure[] = ; int stones[] = ; _expected = ; _received = _obj.getScore(vector <int>(treasure, treasure+sizeof(treasure)/sizeof(int)), vector <int>(stones, stones+sizeof(stones)/sizeof(int))); break; }*/ /*case 6: { int treasure[] = ; int stones[] = ; _expected = ; _received = _obj.getScore(vector <int>(treasure, treasure+sizeof(treasure)/sizeof(int)), vector <int>(stones, stones+sizeof(stones)/sizeof(int))); break; }*/ default: return 0; } cout.setf(ios::fixed,ios::floatfield); cout.precision(2); double _elapsed = (double)(clock()-_start)/CLOCKS_PER_SEC; if (_received == _expected) cout << "#" << _tc << ": Passed (" << _elapsed << " secs)" << endl; else { cout << "#" << _tc << ": Failed (" << _elapsed << " secs)" << endl; cout << " Expected: " << _expected << endl; cout << " Received: " << _received << endl; } } } //END CUT HERE
[ "alejandrojh90@gmail.com" ]
alejandrojh90@gmail.com
b92de6fa72cdfca1b915d7676fd2246bf5602eb0
5149df84d1bf0bed5ccf2feca01770e0267ebd5a
/public/vphysics_interface.h
46edafa1d614d344cf864a25de23a6c1a6eff501
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
iomeone/Kisak-Strike
924185588bafe60fda198bed39f4e88ae0f2f5b3
ae0f59e7263bf0165809b2bd8a1ff52ff483ebfd
refs/heads/master
2023-02-25T20:08:52.822944
2021-02-05T09:04:58
2021-02-05T09:04:58
null
0
0
null
null
null
null
UTF-8
C++
false
false
54,902
h
//===== Copyright � 1996-2005, Valve Corporation, All rights reserved. ======// // // Purpose: Public interfaces to vphysics DLL // // $NoKeywords: $ //===========================================================================// #ifndef VPHYSICS_INTERFACE_H #define VPHYSICS_INTERFACE_H #ifdef _WIN32 #pragma once #endif #include "tier1/interface.h" #include "appframework/iappsystem.h" #include "mathlib/vector.h" #include "mathlib/vector4d.h" #include "vcollide.h" #include "tier3/tier3.h" #include "SoundEmitterSystem/isoundemittersystembase.h" // ------------------------------------------------------------------------------------ // UNITS: // ------------------------------------------------------------------------------------ // NOTE: Coordinates are in HL units. 1 unit == 1 inch. X is east (forward), Y is north (left), Z is up (up) // QAngle are pitch (around y), Yaw (around Z), Roll (around X) // AngularImpulse are exponetial maps (an axis in HL units scaled by a "twist" angle in degrees) // They can be transformed like normals/covectors and added linearly // mass is kg, volume is in^3, acceleration is in/s^2, velocity is in/s // density is kg/m^3 (water ~= 998 at room temperature) // preferably, these would be in kg/in^3, but the range of those numbers makes them not very human readable // having water be about 1000 is really convenient for data entry. // Since volume is in in^3 and density is in kg/m^3: // density = (mass / volume) * CUBIC_METERS_PER_CUBIC_INCH // Force is applied using impulses (kg*in/s) // Torque is applied using impulses (kg*degrees/s) // ------------------------------------------------------------------------------------ #define METERS_PER_INCH (0.0254f) #define CUBIC_METERS_PER_CUBIC_INCH (METERS_PER_INCH*METERS_PER_INCH*METERS_PER_INCH) // 2.2 lbs / kg #define POUNDS_PER_KG (2.2f) #define KG_PER_POUND (1.0f/POUNDS_PER_KG) // convert from pounds to kg #define lbs2kg(x) ((x)*KG_PER_POUND) #define kg2lbs(x) ((x)*POUNDS_PER_KG) const float VPHYSICS_MIN_MASS = 0.1f; const float VPHYSICS_MAX_MASS = 5e4f; class IPhysicsObject; class IPhysicsEnvironment; class IPhysicsSurfaceProps; class IPhysicsConstraint; class IPhysicsConstraintGroup; class IPhysicsFluidController; class IPhysicsSpring; class IPhysicsVehicleController; class IConvexInfo; class IPhysicsObjectPairHash; class IPhysicsCollisionSet; class IPhysicsPlayerController; class IPhysicsFrictionSnapshot; struct Ray_t; struct constraint_ragdollparams_t; struct constraint_hingeparams_t; struct constraint_fixedparams_t; struct constraint_ballsocketparams_t; struct constraint_slidingparams_t; struct constraint_pulleyparams_t; struct constraint_lengthparams_t; struct constraint_groupparams_t; struct vehicleparams_t; struct matrix3x4_t; struct fluidparams_t; struct springparams_t; struct objectparams_t; struct debugcollide_t; class CGameTrace; typedef CGameTrace trace_t; struct physics_stats_t; struct physics_performanceparams_t; struct virtualmeshparams_t; //enum PhysInterfaceId_t; struct physsaveparams_t; struct physrestoreparams_t; struct physprerestoreparams_t; enum PhysInterfaceId_t { PIID_UNKNOWN, PIID_IPHYSICSOBJECT, PIID_IPHYSICSFLUIDCONTROLLER, PIID_IPHYSICSSPRING, PIID_IPHYSICSCONSTRAINTGROUP, PIID_IPHYSICSCONSTRAINT, PIID_IPHYSICSSHADOWCONTROLLER, PIID_IPHYSICSPLAYERCONTROLLER, PIID_IPHYSICSMOTIONCONTROLLER, PIID_IPHYSICSVEHICLECONTROLLER, PIID_IPHYSICSGAMETRACE, PIID_NUM_TYPES }; class ISave; class IRestore; #define VPHYSICS_DEBUG_OVERLAY_INTERFACE_VERSION "VPhysicsDebugOverlay001" abstract_class IVPhysicsDebugOverlay { public: virtual void AddEntityTextOverlay(int ent_index, int line_offset, float duration, int r, int g, int b, int a, PRINTF_FORMAT_STRING const char *format, ...) = 0; virtual void AddBoxOverlay(const Vector& origin, const Vector& mins, const Vector& max, QAngle const& orientation, int r, int g, int b, int a, float duration) = 0; virtual void AddTriangleOverlay(const Vector& p1, const Vector& p2, const Vector& p3, int r, int g, int b, int a, bool noDepthTest, float duration) = 0; virtual void AddLineOverlay(const Vector& origin, const Vector& dest, int r, int g, int b,bool noDepthTest, float duration) = 0; virtual void AddTextOverlay(const Vector& origin, float duration, PRINTF_FORMAT_STRING const char *format, ...) = 0; virtual void AddTextOverlay(const Vector& origin, int line_offset, float duration, PRINTF_FORMAT_STRING const char *format, ...) = 0; virtual void AddScreenTextOverlay(float flXPos, float flYPos,float flDuration, int r, int g, int b, int a, const char *text) = 0; virtual void AddSweptBoxOverlay(const Vector& start, const Vector& end, const Vector& mins, const Vector& max, const QAngle & angles, int r, int g, int b, int a, float flDuration) = 0; virtual void AddTextOverlayRGB(const Vector& origin, int line_offset, float duration, float r, float g, float b, float alpha, PRINTF_FORMAT_STRING const char *format, ...) = 0; }; #define VPHYSICS_INTERFACE_VERSION "VPhysics031" abstract_class IPhysics : public IAppSystem { public: virtual IPhysicsEnvironment *CreateEnvironment( void ) = 0; virtual void DestroyEnvironment( IPhysicsEnvironment * ) = 0; virtual IPhysicsEnvironment *GetActiveEnvironmentByIndex( int index ) = 0; // Creates a fast hash of pairs of objects // Useful for maintaining a table of object relationships like pairs that do not collide. virtual IPhysicsObjectPairHash *CreateObjectPairHash() = 0; virtual void DestroyObjectPairHash( IPhysicsObjectPairHash *pHash ) = 0; // holds a cache of these by id. So you can get by id to search for the previously created set // UNDONE: Sets are currently limited to 32 elements. More elements will return NULL in create. // NOTE: id is not allowed to be zero. virtual IPhysicsCollisionSet *FindOrCreateCollisionSet( uintptr_t id, int maxElementCount ) = 0; virtual IPhysicsCollisionSet *FindCollisionSet( uintptr_t id ) = 0; virtual void DestroyAllCollisionSets() = 0; }; // CPhysConvex is a single convex solid class CPhysConvex; // CPhysPolysoup is an abstract triangle soup mesh class CPhysPolysoup; class ICollisionQuery; class IVPhysicsKeyParser; struct convertconvexparams_t; class CPackedPhysicsDescription; class CPolyhedron; // UNDONE: Find a better place for this? Should be in collisionutils, but it's needs VPHYSICS' solver. struct truncatedcone_t { Vector origin; Vector normal; float h; // height of the cone (hl units) float theta; // cone angle (degrees) }; abstract_class IPhysicsCollision { public: virtual ~IPhysicsCollision( void ) {} // produce a convex element from verts (convex hull around verts) virtual CPhysConvex *ConvexFromVerts( Vector **pVerts, int vertCount ) = 0; // produce a convex element from planes (csg of planes) virtual CPhysConvex *ConvexFromPlanes( float *pPlanes, int planeCount, float mergeDistance ) = 0; // calculate volume of a convex element virtual float ConvexVolume( CPhysConvex *pConvex ) = 0; virtual float ConvexSurfaceArea( CPhysConvex *pConvex ) = 0; // store game-specific data in a convex solid virtual void SetConvexGameData( CPhysConvex *pConvex, unsigned int gameData ) = 0; // If not converted, free the convex elements with this call virtual void ConvexFree( CPhysConvex *pConvex ) = 0; virtual CPhysConvex *BBoxToConvex( const Vector &mins, const Vector &maxs ) = 0; // produce a convex element from a convex polyhedron virtual CPhysConvex *ConvexFromConvexPolyhedron( const CPolyhedron &ConvexPolyhedron ) = 0; // produce a set of convex triangles from a convex polygon, normal is assumed to be on the side with forward point ordering, which should be clockwise, output will need to be able to hold exactly (iPointCount-2) convexes virtual void ConvexesFromConvexPolygon( const Vector &vPolyNormal, const Vector *pPoints, int iPointCount, CPhysConvex **pOutput ) = 0; // concave objects // create a triangle soup virtual CPhysPolysoup *PolysoupCreate( void ) = 0; // destroy the container and memory virtual void PolysoupDestroy( CPhysPolysoup *pSoup ) = 0; // add a triangle to the soup virtual void PolysoupAddTriangle( CPhysPolysoup *pSoup, const Vector &a, const Vector &b, const Vector &c, int materialIndex7bits ) = 0; // convert the convex into a compiled collision model virtual CPhysCollide *ConvertPolysoupToCollide( CPhysPolysoup *pSoup, bool useMOPP ) = 0; // Convert an array of convex elements to a compiled collision model (this deletes the convex elements) virtual CPhysCollide *ConvertConvexToCollide( CPhysConvex **pConvex, int convexCount ) = 0; virtual CPhysCollide *ConvertConvexToCollideParams( CPhysConvex **pConvex, int convexCount, const convertconvexparams_t &convertParams ) = 0; // Free a collide that was created with ConvertConvexToCollide() virtual void DestroyCollide( CPhysCollide *pCollide ) = 0; // Get the memory size in bytes of the collision model for serialization virtual int CollideSize( CPhysCollide *pCollide ) = 0; // serialize the collide to a block of memory virtual int CollideWrite( char *pDest, CPhysCollide *pCollide, bool bSwap = false ) = 0; // unserialize the collide from a block of memory virtual CPhysCollide *UnserializeCollide( char *pBuffer, int size, int index ) = 0; // compute the volume of a collide virtual float CollideVolume( CPhysCollide *pCollide ) = 0; // compute surface area for tools virtual float CollideSurfaceArea( CPhysCollide *pCollide ) = 0; // Get the support map for a collide in the given direction virtual Vector CollideGetExtent( const CPhysCollide *pCollide, const Vector &collideOrigin, const QAngle &collideAngles, const Vector &direction ) = 0; // Get an AABB for an oriented collision model virtual void CollideGetAABB( Vector *pMins, Vector *pMaxs, const CPhysCollide *pCollide, const Vector &collideOrigin, const QAngle &collideAngles ) = 0; virtual void CollideGetMassCenter( CPhysCollide *pCollide, Vector *pOutMassCenter ) = 0; virtual void CollideSetMassCenter( CPhysCollide *pCollide, const Vector &massCenter ) = 0; // get the approximate cross-sectional area projected orthographically on the bbox of the collide // NOTE: These are fractional areas - unitless. Basically this is the fraction of the OBB on each axis that // would be visible if the object were rendered orthographically. // NOTE: This has been precomputed when the collide was built or this function will return 1,1,1 virtual Vector CollideGetOrthographicAreas( const CPhysCollide *pCollide ) = 0; virtual void CollideSetOrthographicAreas( CPhysCollide *pCollide, const Vector &areas ) = 0; // query the vcollide index in the physics model for the instance virtual int CollideIndex( const CPhysCollide *pCollide ) = 0; // Convert a bbox to a collide virtual CPhysCollide *BBoxToCollide( const Vector &mins, const Vector &maxs ) = 0; virtual int GetConvexesUsedInCollideable( const CPhysCollide *pCollideable, CPhysConvex **pOutputArray, int iOutputArrayLimit ) = 0; // Trace an AABB against a collide virtual void TraceBox( const Vector &start, const Vector &end, const Vector &mins, const Vector &maxs, const CPhysCollide *pCollide, const Vector &collideOrigin, const QAngle &collideAngles, trace_t *ptr ) = 0; virtual void TraceBox( const Ray_t &ray, const CPhysCollide *pCollide, const Vector &collideOrigin, const QAngle &collideAngles, trace_t *ptr ) = 0; virtual void TraceBox( const Ray_t &ray, unsigned int contentsMask, IConvexInfo *pConvexInfo, const CPhysCollide *pCollide, const Vector &collideOrigin, const QAngle &collideAngles, trace_t *ptr ) = 0; // Trace one collide against another virtual void TraceCollide( const Vector &start, const Vector &end, const CPhysCollide *pSweepCollide, const QAngle &sweepAngles, const CPhysCollide *pCollide, const Vector &collideOrigin, const QAngle &collideAngles, trace_t *ptr ) = 0; // relatively slow test for box vs. truncated cone virtual bool IsBoxIntersectingCone( const Vector &boxAbsMins, const Vector &boxAbsMaxs, const truncatedcone_t &cone ) = 0; // loads a set of solids into a vcollide_t virtual void VCollideLoad( vcollide_t *pOutput, int solidCount, const char *pBuffer, int size, bool swap = false ) = 0; // destroyts the set of solids created by VCollideLoad virtual void VCollideUnload( vcollide_t *pVCollide ) = 0; // begins parsing a vcollide. NOTE: This keeps pointers to the text // If you free the text and call members of IVPhysicsKeyParser, it will crash virtual IVPhysicsKeyParser *VPhysicsKeyParserCreate( const char *pKeyData ) = 0; virtual IVPhysicsKeyParser *VPhysicsKeyParserCreate( vcollide_t *pVCollide ) = 0; // Free the parser created by VPhysicsKeyParserCreate virtual void VPhysicsKeyParserDestroy( IVPhysicsKeyParser *pParser ) = 0; // creates a list of verts from a collision mesh virtual int CreateDebugMesh( CPhysCollide const *pCollisionModel, Vector **outVerts ) = 0; // destroy the list of verts created by CreateDebugMesh virtual void DestroyDebugMesh( int vertCount, Vector *outVerts ) = 0; // create a queryable version of the collision model virtual ICollisionQuery *CreateQueryModel( CPhysCollide *pCollide ) = 0; // destroy the queryable version virtual void DestroyQueryModel( ICollisionQuery *pQuery ) = 0; virtual IPhysicsCollision *ThreadContextCreate( void ) = 0; virtual void ThreadContextDestroy( IPhysicsCollision *pThreadContex ) = 0; virtual CPhysCollide *CreateVirtualMesh( const virtualmeshparams_t &params ) = 0; virtual bool SupportsVirtualMesh() = 0; virtual bool GetBBoxCacheSize( int *pCachedSize, int *pCachedCount ) = 0; // extracts a polyhedron that defines a CPhysConvex's shape virtual CPolyhedron *PolyhedronFromConvex( CPhysConvex * const pConvex, bool bUseTempPolyhedron ) = 0; // dumps info about the collide to Msg() virtual void OutputDebugInfo( const CPhysCollide *pCollide ) = 0; virtual unsigned int ReadStat( int statID ) = 0; // Get an AABB for an oriented collision model virtual float CollideGetRadius( const CPhysCollide *pCollide ) = 0; virtual void *VCollideAllocUserData( vcollide_t *pVCollide, size_t userDataSize ) = 0; virtual void VCollideFreeUserData( vcollide_t *pVCollide ) = 0; virtual void VCollideCheck( vcollide_t *pVCollide, const char *pName ) = 0; virtual bool TraceBoxAA( const Ray_t &ray, const CPhysCollide *pCollide, trace_t *ptr ) = 0; }; // this can be used to post-process a collision model abstract_class ICollisionQuery { public: virtual ~ICollisionQuery() {} // number of convex pieces in the whole solid virtual int ConvexCount( void ) = 0; // triangle count for this convex piece virtual int TriangleCount( int convexIndex ) = 0; // get the stored game data virtual unsigned int GetGameData( int convexIndex ) = 0; // Gets the triangle's verts to an array virtual void GetTriangleVerts( int convexIndex, int triangleIndex, Vector *verts ) = 0; // UNDONE: This doesn't work!!! virtual void SetTriangleVerts( int convexIndex, int triangleIndex, const Vector *verts ) = 0; // returns the 7-bit material index virtual int GetTriangleMaterialIndex( int convexIndex, int triangleIndex ) = 0; // sets a 7-bit material index for this triangle virtual void SetTriangleMaterialIndex( int convexIndex, int triangleIndex, int index7bits ) = 0; }; //----------------------------------------------------------------------------- // Purpose: Ray traces from game engine. //----------------------------------------------------------------------------- abstract_class IPhysicsGameTrace { public: virtual void VehicleTraceRay( const Ray_t &ray, void *pVehicle, trace_t *pTrace ) = 0; virtual void VehicleTraceRayWithWater( const Ray_t &ray, void *pVehicle, trace_t *pTrace ) = 0; virtual bool VehiclePointInWater( const Vector &vecPoint ) = 0; }; // The caller should implement this to return contents masks per convex on a collide abstract_class IConvexInfo { public: virtual unsigned int GetContents( int convexGameData ) = 0; }; class CPhysicsEventHandler; abstract_class IPhysicsCollisionData { public: virtual void GetSurfaceNormal( Vector &out ) = 0; // normal points toward second object (object index 1) virtual void GetContactPoint( Vector &out ) = 0; // contact point of collision (in world space) virtual void GetContactSpeed( Vector &out ) = 0; // speed of surface 1 relative to surface 0 (in world space) }; struct vcollisionevent_t { IPhysicsObject *pObjects[2]; int surfaceProps[2]; bool isCollision; bool isShadowCollision; float deltaCollisionTime; float collisionSpeed; // only valid at postCollision IPhysicsCollisionData *pInternalData; // may change pre/post collision }; abstract_class IPhysicsCollisionEvent { public: // returns the two objects that collided, time between last collision of these objects // and an opaque data block of collision information // NOTE: PreCollision/PostCollision ALWAYS come in matched pairs!!! virtual void PreCollision( vcollisionevent_t *pEvent ) = 0; virtual void PostCollision( vcollisionevent_t *pEvent ) = 0; // This is a scrape event. The object has scraped across another object consuming the indicated energy virtual void Friction( IPhysicsObject *pObject, float energy, int surfaceProps, int surfacePropsHit, IPhysicsCollisionData *pData ) = 0; virtual void StartTouch( IPhysicsObject *pObject1, IPhysicsObject *pObject2, IPhysicsCollisionData *pTouchData ) = 0; virtual void EndTouch( IPhysicsObject *pObject1, IPhysicsObject *pObject2, IPhysicsCollisionData *pTouchData ) = 0; virtual void FluidStartTouch( IPhysicsObject *pObject, IPhysicsFluidController *pFluid ) = 0; virtual void FluidEndTouch( IPhysicsObject *pObject, IPhysicsFluidController *pFluid ) = 0; virtual void PostSimulationFrame() = 0; virtual void ObjectEnterTrigger( IPhysicsObject *pTrigger, IPhysicsObject *pObject ) {} virtual void ObjectLeaveTrigger( IPhysicsObject *pTrigger, IPhysicsObject *pObject ) {} }; abstract_class IPhysicsObjectEvent { public: // these can be used to optimize out queries on sleeping objects // Called when an object is woken after sleeping virtual void ObjectWake( IPhysicsObject *pObject ) = 0; // called when an object goes to sleep (no longer simulating) virtual void ObjectSleep( IPhysicsObject *pObject ) = 0; }; abstract_class IPhysicsConstraintEvent { public: // the constraint is now inactive, the game code is required to delete it or re-activate it. virtual void ConstraintBroken( IPhysicsConstraint * ) = 0; }; struct hlshadowcontrol_params_t { Vector targetPosition; QAngle targetRotation; float maxAngular; float maxDampAngular; float maxSpeed; float maxDampSpeed; float dampFactor; float teleportDistance; }; // UNDONE: At some point allow this to be parameterized using hlshadowcontrol_params_t. // All of the infrastructure is in place to do that. abstract_class IPhysicsShadowController { public: virtual ~IPhysicsShadowController( void ) {} virtual void Update( const Vector &position, const QAngle &angles, float timeOffset ) = 0; virtual void MaxSpeed( float maxSpeed, float maxAngularSpeed ) = 0; virtual void StepUp( float height ) = 0; // If the teleport distance is non-zero, the object will be teleported to // the target location when the error exceeds this quantity. virtual void SetTeleportDistance( float teleportDistance ) = 0; virtual bool AllowsTranslation() = 0; virtual bool AllowsRotation() = 0; // There are two classes of shadow objects: // 1) Game physics controlled, shadow follows game physics (this is the default) // 2) Physically controlled - shadow position is a target, but the game hasn't guaranteed that the space can be occupied by this object virtual void SetPhysicallyControlled( bool isPhysicallyControlled ) = 0; virtual bool IsPhysicallyControlled() = 0; virtual void GetLastImpulse( Vector *pOut ) = 0; virtual void UseShadowMaterial( bool bUseShadowMaterial ) = 0; virtual void ObjectMaterialChanged( int materialIndex ) = 0; //Basically get the last inputs to IPhysicsShadowController::Update(), returns last input to timeOffset in Update() virtual float GetTargetPosition( Vector *pPositionOut, QAngle *pAnglesOut ) = 0; virtual float GetTeleportDistance( void ) = 0; virtual void GetMaxSpeed( float *pMaxSpeedOut, float *pMaxAngularSpeedOut ) = 0; }; class CPhysicsSimObject; class IPhysicsMotionController; // Callback for simulation class IMotionEvent { public: // These constants instruct the simulator as to how to apply the values copied to linear & angular // GLOBAL/LOCAL refer to the coordinate system of the values, whereas acceleration/force determine whether or not // mass is divided out (forces must be divided by mass to compute acceleration) enum simresult_e { SIM_NOTHING = 0, SIM_LOCAL_ACCELERATION, SIM_LOCAL_FORCE, SIM_GLOBAL_ACCELERATION, SIM_GLOBAL_FORCE }; virtual simresult_e Simulate( IPhysicsMotionController *pController, IPhysicsObject *pObject, float deltaTime, Vector &linear, AngularImpulse &angular ) = 0; }; abstract_class IPhysicsMotionController { public: virtual ~IPhysicsMotionController( void ) {} virtual void SetEventHandler( IMotionEvent *handler ) = 0; virtual void AttachObject( IPhysicsObject *pObject, bool checkIfAlreadyAttached ) = 0; virtual void DetachObject( IPhysicsObject *pObject ) = 0; // returns the number of objects currently attached to the controller virtual int CountObjects( void ) = 0; // NOTE: pObjectList is an array with at least CountObjects() allocated virtual void GetObjects( IPhysicsObject **pObjectList ) = 0; // detaches all attached objects virtual void ClearObjects( void ) = 0; // wakes up all attached objects virtual void WakeObjects( void ) = 0; enum priority_t { LOW_PRIORITY = 0, MEDIUM_PRIORITY = 1, HIGH_PRIORITY = 2, }; virtual void SetPriority( priority_t priority ) = 0; }; // ------------------- // Collision filter function. Return 0 if objects should not be tested for collisions, nonzero otherwise // Install with IPhysicsEnvironment::SetCollisionFilter() // ------------------- abstract_class IPhysicsCollisionSolver { public: virtual int ShouldCollide( IPhysicsObject *pObj0, IPhysicsObject *pObj1, void *pGameData0, void *pGameData1 ) = 0; virtual int ShouldSolvePenetration( IPhysicsObject *pObj0, IPhysicsObject *pObj1, void *pGameData0, void *pGameData1, float dt ) = 0; // pObject has already done the max number of collisions this tick, should we freeze it to save CPU? virtual bool ShouldFreezeObject( IPhysicsObject *pObject ) = 0; // The system has already done too many collision checks, performance will suffer. // How many more should it do? virtual int AdditionalCollisionChecksThisTick( int currentChecksDone ) = 0; // This list of objects is in a connected contact graph that is too large to solve quickly // return true to freeze the system, false to solve it virtual bool ShouldFreezeContacts( IPhysicsObject **pObjectList, int objectCount ) = 0; }; enum PhysicsTraceType_t { VPHYSICS_TRACE_EVERYTHING = 0, VPHYSICS_TRACE_STATIC_ONLY, VPHYSICS_TRACE_MOVING_ONLY, VPHYSICS_TRACE_TRIGGERS_ONLY, VPHYSICS_TRACE_STATIC_AND_MOVING, }; abstract_class IPhysicsTraceFilter { public: virtual bool ShouldHitObject( IPhysicsObject *pObject, int contentsMask ) = 0; virtual PhysicsTraceType_t GetTraceType() const = 0; }; abstract_class IPhysicsEnvironment { public: virtual ~IPhysicsEnvironment( void ) {} virtual void SetDebugOverlay( CreateInterfaceFn debugOverlayFactory ) = 0; virtual IVPhysicsDebugOverlay *GetDebugOverlay( void ) = 0; // gravity is a 3-vector in in/s^2 virtual void SetGravity( const Vector &gravityVector ) = 0; virtual void GetGravity( Vector *pGravityVector ) const = 0; // air density is in kg / m^3 (water is 1000) // This controls drag, air that is more dense has more drag. virtual void SetAirDensity( float density ) = 0; virtual float GetAirDensity( void ) const = 0; // object creation // create a polygonal object. pCollisionModel was created by the physics builder DLL in a pre-process. virtual IPhysicsObject *CreatePolyObject( const CPhysCollide *pCollisionModel, int materialIndex, const Vector &position, const QAngle &angles, objectparams_t *pParams ) = 0; // same as above, but this one cannot move or rotate (infinite mass/inertia) virtual IPhysicsObject *CreatePolyObjectStatic( const CPhysCollide *pCollisionModel, int materialIndex, const Vector &position, const QAngle &angles, objectparams_t *pParams ) = 0; // Create a perfectly spherical object virtual IPhysicsObject *CreateSphereObject( float radius, int materialIndex, const Vector &position, const QAngle &angles, objectparams_t *pParams, bool isStatic ) = 0; // destroy an object created with CreatePolyObject() or CreatePolyObjectStatic() virtual void DestroyObject( IPhysicsObject * ) = 0; // Create a polygonal fluid body out of the specified collision model // This object will affect any other objects that collide with the collision model virtual IPhysicsFluidController *CreateFluidController( IPhysicsObject *pFluidObject, fluidparams_t *pParams ) = 0; // Destroy an object created with CreateFluidController() virtual void DestroyFluidController( IPhysicsFluidController * ) = 0; // Create a simulated spring that connects 2 objects virtual IPhysicsSpring *CreateSpring( IPhysicsObject *pObjectStart, IPhysicsObject *pObjectEnd, springparams_t *pParams ) = 0; virtual void DestroySpring( IPhysicsSpring * ) = 0; // Create a constraint in the space of pReferenceObject which is attached by the constraint to pAttachedObject virtual IPhysicsConstraint *CreateRagdollConstraint( IPhysicsObject *pReferenceObject, IPhysicsObject *pAttachedObject, IPhysicsConstraintGroup *pGroup, const constraint_ragdollparams_t &ragdoll ) = 0; virtual IPhysicsConstraint *CreateHingeConstraint( IPhysicsObject *pReferenceObject, IPhysicsObject *pAttachedObject, IPhysicsConstraintGroup *pGroup, const constraint_hingeparams_t &hinge ) = 0; virtual IPhysicsConstraint *CreateFixedConstraint( IPhysicsObject *pReferenceObject, IPhysicsObject *pAttachedObject, IPhysicsConstraintGroup *pGroup, const constraint_fixedparams_t &fixed ) = 0; virtual IPhysicsConstraint *CreateSlidingConstraint( IPhysicsObject *pReferenceObject, IPhysicsObject *pAttachedObject, IPhysicsConstraintGroup *pGroup, const constraint_slidingparams_t &sliding ) = 0; virtual IPhysicsConstraint *CreateBallsocketConstraint( IPhysicsObject *pReferenceObject, IPhysicsObject *pAttachedObject, IPhysicsConstraintGroup *pGroup, const constraint_ballsocketparams_t &ballsocket ) = 0; virtual IPhysicsConstraint *CreatePulleyConstraint( IPhysicsObject *pReferenceObject, IPhysicsObject *pAttachedObject, IPhysicsConstraintGroup *pGroup, const constraint_pulleyparams_t &pulley ) = 0; virtual IPhysicsConstraint *CreateLengthConstraint( IPhysicsObject *pReferenceObject, IPhysicsObject *pAttachedObject, IPhysicsConstraintGroup *pGroup, const constraint_lengthparams_t &length ) = 0; virtual void DestroyConstraint( IPhysicsConstraint * ) = 0; virtual IPhysicsConstraintGroup *CreateConstraintGroup( const constraint_groupparams_t &groupParams ) = 0; virtual void DestroyConstraintGroup( IPhysicsConstraintGroup *pGroup ) = 0; virtual IPhysicsShadowController *CreateShadowController( IPhysicsObject *pObject, bool allowTranslation, bool allowRotation ) = 0; virtual void DestroyShadowController( IPhysicsShadowController * ) = 0; virtual IPhysicsPlayerController *CreatePlayerController( IPhysicsObject *pObject ) = 0; virtual void DestroyPlayerController( IPhysicsPlayerController * ) = 0; virtual IPhysicsMotionController *CreateMotionController( IMotionEvent *pHandler ) = 0; virtual void DestroyMotionController( IPhysicsMotionController *pController ) = 0; virtual IPhysicsVehicleController *CreateVehicleController( IPhysicsObject *pVehicleBodyObject, const vehicleparams_t &params, unsigned int nVehicleType, IPhysicsGameTrace *pGameTrace ) = 0; virtual void DestroyVehicleController( IPhysicsVehicleController * ) = 0; // install a function to filter collisions/penentration virtual void SetCollisionSolver( IPhysicsCollisionSolver *pSolver ) = 0; // run the simulator for deltaTime seconds virtual void Simulate( float deltaTime ) = 0; // true if currently running the simulator (i.e. in a callback during physenv->Simulate()) virtual bool IsInSimulation() const = 0; // Manage the timestep (period) of the simulator. The main functions are all integrated with // this period as dt. virtual float GetSimulationTimestep() const = 0; virtual void SetSimulationTimestep( float timestep ) = 0; // returns the current simulation clock's value. This is an absolute time. virtual float GetSimulationTime() const = 0; virtual void ResetSimulationClock() = 0; // returns the current simulation clock's value at the next frame. This is an absolute time. virtual float GetNextFrameTime( void ) const = 0; // Collision callbacks (game code collision response) virtual void SetCollisionEventHandler( IPhysicsCollisionEvent *pCollisionEvents ) = 0; virtual void SetObjectEventHandler( IPhysicsObjectEvent *pObjectEvents ) = 0; virtual void SetConstraintEventHandler( IPhysicsConstraintEvent *pConstraintEvents ) = 0; virtual void SetQuickDelete( bool bQuick ) = 0; virtual int GetActiveObjectCount() const = 0; virtual void GetActiveObjects( IPhysicsObject **pOutputObjectList ) const = 0; virtual const IPhysicsObject **GetObjectList( int *pOutputObjectCount ) const = 0; virtual bool TransferObject( IPhysicsObject *pObject, IPhysicsEnvironment *pDestinationEnvironment ) = 0; virtual void CleanupDeleteList( void ) = 0; virtual void EnableDeleteQueue( bool enable ) = 0; // Save/Restore methods virtual bool Save( const physsaveparams_t &params ) = 0; virtual void PreRestore( const physprerestoreparams_t &params ) = 0; virtual bool Restore( const physrestoreparams_t &params ) = 0; virtual void PostRestore() = 0; // Debugging: virtual bool IsCollisionModelUsed( CPhysCollide *pCollide ) const = 0; // Physics world version of the enginetrace API: virtual void TraceRay( const Ray_t &ray, unsigned int fMask, IPhysicsTraceFilter *pTraceFilter, trace_t *pTrace ) = 0; virtual void SweepCollideable( const CPhysCollide *pCollide, const Vector &vecAbsStart, const Vector &vecAbsEnd, const QAngle &vecAngles, unsigned int fMask, IPhysicsTraceFilter *pTraceFilter, trace_t *pTrace ) = 0; // performance tuning virtual void GetPerformanceSettings( physics_performanceparams_t *pOutput ) const = 0; virtual void SetPerformanceSettings( const physics_performanceparams_t *pSettings ) = 0; // perf/cost statistics virtual void ReadStats( physics_stats_t *pOutput ) = 0; virtual void ClearStats() = 0; virtual unsigned int GetObjectSerializeSize( IPhysicsObject *pObject ) const = 0; virtual void SerializeObjectToBuffer( IPhysicsObject *pObject, unsigned char *pBuffer, unsigned int bufferSize ) = 0; virtual IPhysicsObject *UnserializeObjectFromBuffer( void *pGameData, unsigned char *pBuffer, unsigned int bufferSize, bool enableCollisions ) = 0; virtual void EnableConstraintNotify( bool bEnable ) = 0; virtual void DebugCheckContacts(void) = 0; virtual void SetAlternateGravity( const Vector &gravityVector ) = 0; virtual void GetAlternateGravity( Vector *pGravityVector ) const = 0; virtual float GetDeltaFrameTime( int maxTicks ) const = 0; virtual void ForceObjectsToSleep( IPhysicsObject **pList, int listCount ) = 0; //Network prediction related functions virtual void SetPredicted( bool bPredicted ) = 0; //Interaction with this system and it's objects may not always march forward, sometimes it will get/set data in the past. virtual bool IsPredicted( void ) = 0; virtual void SetPredictionCommandNum( int iCommandNum ) = 0; //what command the client is working on right now virtual int GetPredictionCommandNum( void ) = 0; virtual void DoneReferencingPreviousCommands( int iCommandNum ) = 0; //won't need data from commands before this one any more virtual void RestorePredictedSimulation( void ) = 0; //called to restore results from a previous simulation with the same predicted timestamp set // destroy a CPhysCollide used in CreatePolyObject()/CreatePolyObjectStatic() when any owning IPhysicsObject is flushed from the queued deletion list. virtual void DestroyCollideOnDeadObjectFlush( CPhysCollide * ) = 0; //should only be used after calling DestroyObject() on all IPhysicsObjects created with it. }; enum callbackflags { CALLBACK_GLOBAL_COLLISION = 0x0001, CALLBACK_GLOBAL_FRICTION = 0x0002, CALLBACK_GLOBAL_TOUCH = 0x0004, CALLBACK_GLOBAL_TOUCH_STATIC = 0x0008, CALLBACK_SHADOW_COLLISION = 0x0010, CALLBACK_GLOBAL_COLLIDE_STATIC = 0x0020, CALLBACK_IS_VEHICLE_WHEEL = 0x0040, CALLBACK_FLUID_TOUCH = 0x0100, CALLBACK_NEVER_DELETED = 0x0200, // HACKHACK: This means this object will never be deleted (set on the world) CALLBACK_MARKED_FOR_DELETE = 0x0400, // This allows vphysics to skip some work for this object since it will be // deleted later this frame. (Set automatically by destroy calls) CALLBACK_ENABLING_COLLISION = 0x0800, // This is active during the time an object is enabling collisions // allows us to skip collisions between "new" objects and objects marked for delete CALLBACK_DO_FLUID_SIMULATION = 0x1000, // remove this to opt out of fluid simulations CALLBACK_IS_PLAYER_CONTROLLER= 0x2000, // HACKHACK: Set this on players until player cotrollers are unified with shadow controllers CALLBACK_CHECK_COLLISION_DISABLE = 0x4000, CALLBACK_MARKED_FOR_TEST = 0x8000, // debug -- marked object is being debugged }; enum collisionhints { COLLISION_HINT_DEBRIS = 0x0001, COLLISION_HINT_STATICSOLID = 0x0002, COLLISION_HINT_NOSOUND = 0x0004, // lwss add - disables collision sounds. }; class IPredictedPhysicsObject; abstract_class IPhysicsObject { public: virtual ~IPhysicsObject( void ) {} // returns true if this object is static/unmoveable // NOTE: returns false for objects that are not created static, but set EnableMotion(false); // Call IsMoveable() to find if the object is static OR has motion disabled virtual bool IsStatic() const = 0; virtual bool IsAsleep() const = 0; virtual bool IsTrigger() const = 0; virtual bool IsFluid() const = 0; // fluids are special triggers with fluid controllers attached, they return true to IsTrigger() as well! virtual bool IsHinged() const = 0; virtual bool IsCollisionEnabled() const = 0; virtual bool IsGravityEnabled() const = 0; virtual bool IsDragEnabled() const = 0; virtual bool IsMotionEnabled() const = 0; virtual bool IsMoveable() const = 0; // legacy: IsMotionEnabled() && !IsStatic() virtual bool IsAttachedToConstraint(bool bExternalOnly) const = 0; // Enable / disable collisions for this object virtual void EnableCollisions( bool enable ) = 0; // Enable / disable gravity for this object virtual void EnableGravity( bool enable ) = 0; // Enable / disable air friction / drag for this object virtual void EnableDrag( bool enable ) = 0; // Enable / disable motion (pin / unpin the object) virtual void EnableMotion( bool enable ) = 0; // Game can store data in each object (link back to game object) virtual void SetGameData( void *pGameData ) = 0; virtual void *GetGameData( void ) const = 0; // This flags word can be defined by the game as well virtual void SetGameFlags( unsigned short userFlags ) = 0; virtual unsigned short GetGameFlags( void ) const = 0; virtual void SetGameIndex( unsigned short gameIndex ) = 0; virtual unsigned short GetGameIndex( void ) const = 0; // setup various callbacks for this object virtual void SetCallbackFlags( unsigned short callbackflags ) = 0; // get the current callback state for this object virtual unsigned short GetCallbackFlags( void ) const = 0; // "wakes up" an object // NOTE: ALL OBJECTS ARE "Asleep" WHEN CREATED virtual void Wake( void ) = 0; virtual void Sleep( void ) = 0; // call this when the collision filter conditions change due to this // object's state (e.g. changing solid type or collision group) virtual void RecheckCollisionFilter() = 0; // NOTE: Contact points aren't updated when collision rules change, call this to force an update // UNDONE: Force this in RecheckCollisionFilter() ? virtual void RecheckContactPoints( bool bSearchForNewContacts = false ) = 0; // mass accessors virtual void SetMass( float mass ) = 0; virtual float GetMass( void ) const = 0; // get 1/mass (it's cached) virtual float GetInvMass( void ) const = 0; virtual Vector GetInertia( void ) const = 0; virtual Vector GetInvInertia( void ) const = 0; virtual void SetInertia( const Vector &inertia ) = 0; virtual void SetDamping( const float *speed, const float *rot ) = 0; virtual void GetDamping( float *speed, float *rot ) const = 0; // coefficients are optional, pass either virtual void SetDragCoefficient( float *pDrag, float *pAngularDrag ) = 0; virtual void SetBuoyancyRatio( float ratio ) = 0; // Override bouyancy // material index virtual int GetMaterialIndex() const = 0; virtual void SetMaterialIndex( int materialIndex ) = 0; // contents bits virtual unsigned int GetContents() const = 0; virtual void SetContents( unsigned int contents ) = 0; // Get the radius if this is a sphere object (zero if this is a polygonal mesh) virtual float GetSphereRadius() const = 0; // Set the radius on a sphere. May need to force recalculation of contact points virtual void SetSphereRadius(float radius) = 0; virtual float GetEnergy() const = 0; virtual Vector GetMassCenterLocalSpace() const = 0; // NOTE: This will teleport the object virtual void SetPosition( const Vector &worldPosition, const QAngle &angles, bool isTeleport ) = 0; virtual void SetPositionMatrix( const matrix3x4_t&matrix, bool isTeleport ) = 0; virtual void GetPosition( Vector *worldPosition, QAngle *angles ) const = 0; virtual void GetPositionMatrix( matrix3x4_t *positionMatrix ) const = 0; // force the velocity to a new value // NOTE: velocity is in worldspace, angularVelocity is relative to the object's // local axes (just like pev->velocity, pev->avelocity) virtual void SetVelocity( const Vector *velocity, const AngularImpulse *angularVelocity ) = 0; // like the above, but force the change into the simulator immediately virtual void SetVelocityInstantaneous( const Vector *velocity, const AngularImpulse *angularVelocity ) = 0; // NOTE: velocity is in worldspace, angularVelocity is relative to the object's // local axes (just like pev->velocity, pev->avelocity) virtual void GetVelocity( Vector *velocity, AngularImpulse *angularVelocity ) const = 0; // NOTE: These are velocities, not forces. i.e. They will have the same effect regardless of // the object's mass or inertia virtual void AddVelocity( const Vector *velocity, const AngularImpulse *angularVelocity ) = 0; // gets a velocity in the object's local frame of reference at a specific point virtual void GetVelocityAtPoint( const Vector &worldPosition, Vector *pVelocity ) const = 0; // gets the velocity actually moved by the object in the last simulation update virtual void GetImplicitVelocity( Vector *velocity, AngularImpulse *angularVelocity ) const = 0; // NOTE: These are here for convenience, but you can do them yourself by using the matrix // returned from GetPositionMatrix() // convenient coordinate system transformations (params - dest, src) virtual void LocalToWorld( Vector *worldPosition, const Vector &localPosition ) const = 0; virtual void WorldToLocal( Vector *localPosition, const Vector &worldPosition ) const = 0; // transforms a vector (no translation) from object-local to world space virtual void LocalToWorldVector( Vector *worldVector, const Vector &localVector ) const = 0; // transforms a vector (no translation) from world to object-local space virtual void WorldToLocalVector( Vector *localVector, const Vector &worldVector ) const = 0; // push on an object // force vector is direction & magnitude of impulse kg in / s virtual void ApplyForceCenter( const Vector &forceVector ) = 0; virtual void ApplyForceOffset( const Vector &forceVector, const Vector &worldPosition ) = 0; // apply torque impulse. This will change the angular velocity on the object. // HL Axes, kg degrees / s virtual void ApplyTorqueCenter( const AngularImpulse &torque ) = 0; // Calculates the force/torque on the center of mass for an offset force impulse (pass output to ApplyForceCenter / ApplyTorqueCenter) virtual void CalculateForceOffset( const Vector &forceVector, const Vector &worldPosition, Vector *centerForce, AngularImpulse *centerTorque ) const = 0; // Calculates the linear/angular velocities on the center of mass for an offset force impulse (pass output to AddVelocity) virtual void CalculateVelocityOffset( const Vector &forceVector, const Vector &worldPosition, Vector *centerVelocity, AngularImpulse *centerAngularVelocity ) const = 0; // calculate drag scale virtual float CalculateLinearDrag( const Vector &unitDirection ) const = 0; virtual float CalculateAngularDrag( const Vector &objectSpaceRotationAxis ) const = 0; // returns true if the object is in contact with another object // if true, puts a point on the contact surface in contactPoint, and // a pointer to the object in contactObject // NOTE: You can pass NULL for either to avoid computations // BUGBUG: Use CreateFrictionSnapshot instead of this - this is a simple hack virtual bool GetContactPoint( Vector *contactPoint, IPhysicsObject **contactObject ) const = 0; // refactor this a bit - move some of this to IPhysicsShadowController virtual void SetShadow( float maxSpeed, float maxAngularSpeed, bool allowPhysicsMovement, bool allowPhysicsRotation ) = 0; virtual void UpdateShadow( const Vector &targetPosition, const QAngle &targetAngles, bool tempDisableGravity, float timeOffset ) = 0; // returns number of ticks since last Update() call virtual int GetShadowPosition( Vector *position, QAngle *angles ) const = 0; virtual IPhysicsShadowController *GetShadowController( void ) const = 0; virtual void RemoveShadowController() = 0; // applies the math of the shadow controller to this object. // for use in your own controllers // returns the new value of secondsToArrival with dt time elapsed virtual float ComputeShadowControl( const hlshadowcontrol_params_t &params, float secondsToArrival, float dt ) = 0; virtual const CPhysCollide *GetCollide( void ) const = 0; virtual const char *GetName() const = 0; virtual void BecomeTrigger() = 0; virtual void RemoveTrigger() = 0; // sets the object to be hinged. Fixed it place, but able to rotate around one axis. virtual void BecomeHinged( int localAxis ) = 0; // resets the object to original state virtual void RemoveHinged() = 0; // used to iterate the contact points of an object virtual IPhysicsFrictionSnapshot *CreateFrictionSnapshot() = 0; virtual void DestroyFrictionSnapshot( IPhysicsFrictionSnapshot *pSnapshot ) = 0; // dumps info about the object to Msg() virtual void OutputDebugInfo() const = 0; #if OBJECT_WELDING virtual void WeldToObject( IPhysicsObject *pParent ) = 0; virtual void RemoveWeld( IPhysicsObject *pOther ) = 0; virtual void RemoveAllWelds( void ) = 0; #endif // EnableGravity still determines whether to apply gravity // This flag determines which gravity constant to use for an alternate gravity effect virtual void SetUseAlternateGravity( bool bSet ) = 0; virtual void SetCollisionHints( uint32 collisionHints ) = 0; virtual uint32 GetCollisionHints() const = 0; inline bool IsPredicted( void ) const { return GetPredictedInterface() != NULL; } //true if class has an IPredictedPhysicsObject interface virtual IPredictedPhysicsObject *GetPredictedInterface( void ) const = 0; virtual void SyncWith( IPhysicsObject *pOther ) = 0; }; abstract_class IPredictedPhysicsObject : public IPhysicsObject { public: virtual ~IPredictedPhysicsObject( void ) {} virtual void SetErrorDelta_Position( const Vector &vPosition ) = 0; virtual void SetErrorDelta_Velocity( const Vector &vVelocity ) = 0; }; abstract_class IPhysicsSpring { public: virtual ~IPhysicsSpring( void ) {} virtual void GetEndpoints( Vector *worldPositionStart, Vector *worldPositionEnd ) = 0; virtual void SetSpringConstant( float flSpringContant) = 0; virtual void SetSpringDamping( float flSpringDamping) = 0; virtual void SetSpringLength( float flSpringLenght) = 0; // Get the starting object virtual IPhysicsObject *GetStartObject( void ) = 0; // Get the end object virtual IPhysicsObject *GetEndObject( void ) = 0; }; //----------------------------------------------------------------------------- // Purpose: These properties are defined per-material. This is accessible at // each triangle in a collision mesh //----------------------------------------------------------------------------- struct surfacephysicsparams_t { // vphysics physical properties float friction; float elasticity; // collision elasticity - used to compute coefficient of restitution float density; // physical density (in kg / m^3) float thickness; // material thickness if not solid (sheet materials) in inches float dampening; }; struct surfaceaudioparams_t { // sounds / audio data float reflectivity; // like elasticity, but how much sound should be reflected by this surface float hardnessFactor; // like elasticity, but only affects impact sound choices float roughnessFactor; // like friction, but only affects scrape sound choices // audio thresholds float roughThreshold; // surface roughness > this causes "rough" scrapes, < this causes "smooth" scrapes float hardThreshold; // surface hardness > this causes "hard" impacts, < this causes "soft" impacts float hardVelocityThreshold; // collision velocity > this causes "hard" impacts, < this causes "soft" impacts // NOTE: Hard impacts must meet both hardnessFactor AND velocity thresholds }; struct surfacesoundnames_t { unsigned short walkStepLeft; unsigned short walkStepRight; unsigned short runStepLeft; unsigned short runStepRight; unsigned short impactSoft; unsigned short impactHard; unsigned short scrapeSmooth; unsigned short scrapeRough; unsigned short bulletImpact; unsigned short rolling; unsigned short breakSound; unsigned short strainSound; }; struct surfacesoundhandles_t { HSOUNDSCRIPTHASH walkStepLeft; HSOUNDSCRIPTHASH walkStepRight; HSOUNDSCRIPTHASH runStepLeft; HSOUNDSCRIPTHASH runStepRight; HSOUNDSCRIPTHASH impactSoft; HSOUNDSCRIPTHASH impactHard; HSOUNDSCRIPTHASH scrapeSmooth; HSOUNDSCRIPTHASH scrapeRough; HSOUNDSCRIPTHASH bulletImpact; HSOUNDSCRIPTHASH rolling; HSOUNDSCRIPTHASH breakSound; HSOUNDSCRIPTHASH strainSound; }; struct surfacegameprops_t { // game movement data float maxSpeedFactor; // Modulates player max speed when walking on this surface float jumpFactor; // Indicates how much higher the player should jump when on the surface // Game-specific data float penetrationModifier; float damageModifier; unsigned short material; // Indicates whether or not the player is on a ladder. unsigned char climbable; unsigned char pad; }; //----------------------------------------------------------------------------- // Purpose: Each different material has an entry like this //----------------------------------------------------------------------------- struct surfacedata_t { surfacephysicsparams_t physics; // physics parameters surfaceaudioparams_t audio; // audio parameters surfacesoundnames_t sounds; // names of linked sounds surfacegameprops_t game; // Game data / properties surfacesoundhandles_t soundhandles; }; class ISaveRestoreOps; #define VPHYSICS_SURFACEPROPS_INTERFACE_VERSION "VPhysicsSurfaceProps001" abstract_class IPhysicsSurfaceProps { public: virtual ~IPhysicsSurfaceProps( void ) {} // parses a text file containing surface prop keys virtual int ParseSurfaceData( const char *pFilename, const char *pTextfile ) = 0; // current number of entries in the database virtual int SurfacePropCount( void ) const = 0; virtual int GetSurfaceIndex( const char *pSurfacePropName ) const = 0; virtual void GetPhysicsProperties( int surfaceDataIndex, float *density, float *thickness, float *friction, float *elasticity ) const = 0; virtual surfacedata_t *GetSurfaceData( int surfaceDataIndex ) = 0; virtual const char *GetString( unsigned short stringTableIndex ) const = 0; virtual const char *GetPropName( int surfaceDataIndex ) const = 0; // sets the global index table for world materials // UNDONE: Make this per-CPhysCollide virtual void SetWorldMaterialIndexTable( int *pMapArray, int mapSize ) = 0; // NOTE: Same as GetPhysicsProperties, but maybe more convenient virtual void GetPhysicsParameters( int surfaceDataIndex, surfacephysicsparams_t *pParamsOut ) const = 0; //lwss - commented this out, not used. //virtual ISaveRestoreOps* GetMaterialIndexDataOps() const = 0; }; abstract_class IPhysicsFluidController { public: virtual ~IPhysicsFluidController( void ) {} virtual void SetGameData( void *pGameData ) = 0; virtual void *GetGameData( void ) const = 0; virtual void GetSurfacePlane( Vector *pNormal, float *pDist ) const = 0; virtual float GetDensity() const = 0; virtual void WakeAllSleepingObjects() = 0; virtual int GetContents() const = 0; }; //----------------------------------------------------------------------------- // Purpose: parameter block for creating fluid dynamic motion // UNDONE: Expose additional fluid model paramters? //----------------------------------------------------------------------------- struct fluidparams_t { Vector4D surfacePlane; // x,y,z normal, dist (plane constant) fluid surface Vector currentVelocity; // velocity of the current in inches/second float damping; // damping factor for buoyancy (tweak) float torqueFactor; float viscosityFactor; void *pGameData; bool useAerodynamics;// true if this controller should calculate surface pressure int contents; fluidparams_t() {} fluidparams_t( fluidparams_t const& src ) { Vector4DCopy( src.surfacePlane, surfacePlane ); VectorCopy( src.currentVelocity, currentVelocity ); damping = src.damping; torqueFactor = src.torqueFactor; viscosityFactor = src.viscosityFactor; contents = src.contents; } }; //----------------------------------------------------------------------------- // Purpose: parameter block for creating linear springs // UNDONE: Expose additional spring model paramters? //----------------------------------------------------------------------------- struct springparams_t { springparams_t() { memset( this, 0, sizeof(*this) ); } float constant; // spring constant float naturalLength;// relaxed length float damping; // damping factor float relativeDamping; // relative damping (damping proportional to the change in the relative position of the objects) Vector startPosition; Vector endPosition; bool useLocalPositions; // start & end Position are in local space to start and end objects if this is true bool onlyStretch; // only apply forces when the length is greater than the natural length }; //----------------------------------------------------------------------------- // Purpose: parameter block for creating polygonal objects //----------------------------------------------------------------------------- struct objectparams_t { Vector *massCenterOverride; float mass; float inertia; float damping; float rotdamping; float rotInertiaLimit; const char *pName; // used only for debugging void *pGameData; float volume; float dragCoefficient; bool enableCollisions; }; struct convertconvexparams_t { bool buildOuterConvexHull; bool buildDragAxisAreas; bool buildOptimizedTraceTables; bool checkOptimalTracing; bool bUseFastApproximateInertiaTensor; bool bBuildAABBTree; float dragAreaEpsilon; CPhysConvex *pForcedOuterHull; void Defaults() { dragAreaEpsilon = 0.25f; // 0.5in x 0.5in square buildOuterConvexHull = false; buildDragAxisAreas = false; buildOptimizedTraceTables = false; checkOptimalTracing = false; bUseFastApproximateInertiaTensor = false; bBuildAABBTree = false; pForcedOuterHull = NULL; } }; //----------------------------------------------------------------------------- // Physics interface IDs // // Note that right now the order of the enum also defines the order of save/load //----------------------------------------------------------------------------- // Purpose: parameter blocks for save and load operations //----------------------------------------------------------------------------- struct physsaveparams_t { ISave *pSave; void *pObject; PhysInterfaceId_t type; }; struct physrestoreparams_t { IRestore *pRestore; void **ppObject; PhysInterfaceId_t type; void *pGameData; const char *pName; // used only for debugging const CPhysCollide *pCollisionModel; IPhysicsEnvironment *pEnvironment; IPhysicsGameTrace *pGameTrace; }; struct physrecreateparams_t { void *pOldObject; void *pNewObject; }; struct physprerestoreparams_t { int recreatedObjectCount; physrecreateparams_t recreatedObjectList[1]; }; //------------------------------------- #define DEFINE_PIID( type, enumval ) \ template <> inline PhysInterfaceId_t GetPhysIID<type>( type ** ) { return enumval; } template <class PHYSPTR> inline PhysInterfaceId_t GetPhysIID(PHYSPTR **); // will get link error if no match DEFINE_PIID( IPhysicsObject, PIID_IPHYSICSOBJECT ); DEFINE_PIID( IPhysicsFluidController, PIID_IPHYSICSFLUIDCONTROLLER ); DEFINE_PIID( IPhysicsSpring, PIID_IPHYSICSSPRING ); DEFINE_PIID( IPhysicsConstraintGroup, PIID_IPHYSICSCONSTRAINTGROUP ); DEFINE_PIID( IPhysicsConstraint, PIID_IPHYSICSCONSTRAINT ); DEFINE_PIID( IPhysicsShadowController, PIID_IPHYSICSSHADOWCONTROLLER ); DEFINE_PIID( IPhysicsPlayerController, PIID_IPHYSICSPLAYERCONTROLLER ); DEFINE_PIID( IPhysicsMotionController, PIID_IPHYSICSMOTIONCONTROLLER ); DEFINE_PIID( IPhysicsVehicleController, PIID_IPHYSICSVEHICLECONTROLLER ); DEFINE_PIID( IPhysicsGameTrace, PIID_IPHYSICSGAMETRACE ); //----------------------------------------------------------------------------- #endif // VPHYSICS_INTERFACE_H
[ "bbchallenger100@gmail.com" ]
bbchallenger100@gmail.com
1d23406f4ef0aca27c24878df7c83170b3b097e3
71c3c165a803b85964a07b6b710cf6a0e8d52195
/Technikiprogramowaniaslownik/stdafx.cpp
ea893b24a4b16e51f1b462459b88ec66a4ecde3d
[]
no_license
andrzejboni/Technikiprogramowaniaslownik
e3a20da68de6fffee07b289486f2f287f309fc0b
9ee8e688d8b46889257eba799ebda36d3a4dee33
refs/heads/master
2021-01-21T20:15:22.909416
2017-05-23T18:56:03
2017-05-23T18:56:03
92,208,777
0
0
null
null
null
null
UTF-8
C++
false
false
307
cpp
// stdafx.cpp : source file that includes just the standard includes // Technikiprogramowaniaslownik.pch will be the pre-compiled header // stdafx.obj will contain the pre-compiled type information #include "stdafx.h" // TODO: reference any additional headers you need in STDAFX.H // and not in this file
[ "andrzej.boni@outlook.com" ]
andrzej.boni@outlook.com
d0d5a0e7042d6db287c00053a89fd485dca007a3
bdff7e2a59e5b266f82b7ab34ac4f44a00413adb
/Parallel-Computing-Class/HW2/timeBomb.cpp
6b8cd981ee61ded104dd604f9353c4363e511c5c
[]
no_license
BrighamM/Course-Work-Archive
256ffcabce672e8f7a09c7d2cc67b4b0f4e9b096
2e92872e36b86425f1d52b835f277a28772b2763
refs/heads/master
2023-06-23T14:50:26.685535
2021-05-15T22:25:07
2021-05-15T22:25:07
119,736,675
0
0
null
null
null
null
UTF-8
C++
false
false
3,200
cpp
#include <iostream> #include <stdlib.h> #include <stdio.h> #include <time.h> #include <mpi.h> #define MCW MPI_COMM_WORLD using namespace std; int main(int argc, char **argv){ int rank; int size; int eliminatedProcess = -1; srand(time(0)); int bombTimer=rand()%20 + 1; MPI_Init(&argc, &argv); MPI_Comm_rank(MCW, &rank); MPI_Comm_size(MCW, &size); /** * Remember! * * MPI_Send( * void* data, * int count, * MPI_Datatype datatype, * int destination, * int tag, * MPI_Comm communicator * ); * **/ /** * And dont forget! * * MPI_Recv( * void* data, * int count, * MPI_Datatype datatype, * int source, * int tag, * MPI_Comm communicator, * MPI_Status* status * ) * **/ if(rank==0){ // We are adding more logic so that we do not pass the bomb to ourselves. int nextPassedPlayer = rand()%size; while(nextPassedPlayer == 0){ nextPassedPlayer = rand()%size; } cout<<"*******************************************************"<<endl; cout<<"* WE ARE NOW BEGINNING THE TIME BOMB GAME!!! *"<<endl; cout<<"* GAME STATS: *"<<endl; cout<<"* NUMBER OF PLAYERS: "<<size<<" *"<<endl; cout<<"* STARTING BOMB TIME :"<<bombTimer<<" *"<<endl; cout<<"* BEGIN THE GAME!!!!!!!!! *"<<endl; cout<<"*******************************************************"<<endl; cout<<"I am process "<<rank<<" and the bomb timer is at: "<<bombTimer<<" Passing to: "<<nextPassedPlayer<<endl; MPI_Send(&bombTimer,1,MPI_INT,nextPassedPlayer,0,MCW); } while(true){ // Run until the bomb expl MPI_Recv(&bombTimer,1,MPI_INT,MPI_ANY_SOURCE,0,MCW,MPI_STATUS_IGNORE); if(!bombTimer){ cout << rank << ": all done."<<endl; break; } // decrement the bomb timer bombTimer--; cout<<"I am process "<<rank<<" and the bomb timer is at: "<<bombTimer<<endl; if(bombTimer == 0){ eliminatedProcess = rank; } if(!bombTimer){ for(int i=0;i<size;++i){ MPI_Send(&bombTimer,1,MPI_INT,i,0,MCW); } } // We are not passing the bomb off to our selves. That is stupid! // Thats like taking two turns in a row a Russian Roulette! int passToPlayer = rand()%size; while(passToPlayer == rank){ passToPlayer = rand()%size; } MPI_Send(&bombTimer,1,MPI_INT,passToPlayer,0,MCW); } if(rank == eliminatedProcess){ cout<<"*******************************************************"<<endl; cout<<"* THE GAME IS OVER!!! *"<<endl; cout<<"* PROCESS: "<<eliminatedProcess<<" HAS BEEN ELIMINATED!!! *"<<endl; cout<<"*******************************************************"<<endl; } MPI_Finalize(); return 0; }
[ "brigham.michaelis@gmail.com" ]
brigham.michaelis@gmail.com
5a2fecb3012ea7151f989100d27ebdf61070ac65
adf4e5bb27ab2bf5646b6b493698e03c16b38018
/Pacman/Scene.cpp
3c049699e4c16bb2da36a5b421f7fd12b83fca83
[]
no_license
Milosz503/Pacman
6102ee6860a55bdbc0592d138ef2eff4cee69357
6798079677f2c28d24f26e7fca7d7f6ff78dd929
refs/heads/master
2023-09-04T17:10:20.197381
2018-06-04T13:58:49
2018-06-04T13:58:49
429,800,431
0
0
null
null
null
null
UTF-8
C++
false
false
5,541
cpp
#include "Scene.h" #include "ConsoleWindow.h" #include "World.h" Scene::Scene(World* world) : world_(world), player_(nullptr), width_(0), height_(0) { } Scene::~Scene() { removeEntities(); removeTiles(); cleanObjects(); } void Scene::cleanObjects() { //for (int x = 0; x < tiles_.size(); ++x) //{ // for (int y = 0; y < tiles_[x].size(); ++y) // { // if (tiles_[x][y] != nullptr) // { // if (tiles_[x][y]->isToRemove()) // { // tilesToRemove_.push_back(tiles_[x][y]); // tiles_[x][y] = nullptr; // } // else // { // tiles_[x][y]->update(); // } // } // } //} for (int i = 0; i < tilesToRemove_.size(); ++i) { world_->getSystems()->sendSystemEvent(new OnRemoveEvent(tilesToRemove_[i])); delete tilesToRemove_[i]; tilesToRemove_[i] = nullptr; } tilesToRemove_.erase(std::remove(tilesToRemove_.begin(), tilesToRemove_.end(), nullptr), tilesToRemove_.end()); for (int i = 0; i < entities_.size(); ++i) { if (entities_[i]->isToRemove()) { world_->getSystems()->sendSystemEvent(new OnRemoveEvent(entities_[i])); if (entities_[i] == player_) player_ = nullptr; delete entities_[i]; entities_[i] = nullptr; } } entities_.erase(std::remove(entities_.begin(), entities_.end(), nullptr), entities_.end()); } sf::Vector2i Scene::normalize(sf::Vector2i position) const { if (position.x < 0) position.x = width_ - ((-position.x)%width_); if (position.y < 0) { position.y = height_ - ((-position.y)%height_); } position.x %= width_; position.y %= height_; return position; } bool Scene::isInside(unsigned x, unsigned y) { if (x < width_ && y < height_) return true; return false; } bool Scene::isTilePhysical(int x, int y) { sf::Vector2i pos = normalize(sf::Vector2i(x, y)); if (tiles_[pos.x][pos.y] == nullptr) return false; return tiles_[pos.x][pos.y]->isPhysical(); } bool Scene::isTilePhysicalF(sf::Vector2i & pos) { if (tiles_[pos.x][pos.y] == nullptr) return false; return tiles_[pos.x][pos.y]->isPhysical(); } Tile * Scene::getTile(int x, int y) const { sf::Vector2i pos = normalize(sf::Vector2i(x, y)); return tiles_[pos.x][pos.y]; } Entity * Scene::findEntity(int x, int y) const { for (auto& entity : entities_) { if (entity->getX() == x && entity->getY() == y) return entity; } return nullptr; } std::vector<Entity*>& Scene::getEntities() { return entities_; } Entity * Scene::getPlayer() { if (player_ == nullptr) { std::cout << "PLAYER IS NULL!" << std::endl; } return player_; } unsigned Scene::getWidth() { return width_; } unsigned Scene::getHeight() { return height_; } void Scene::setSize(int width, int height) { for (auto& entity : entities_) { if (entity->getX() >= width || entity->getY() >= height) { entity->markToRemove(); } } for (int x = width; x < width_; ++x) { for (int y = 0; y < height_; ++y) { if (tiles_[x][y]) { removeTile(tiles_[x][y]); std::cout << "Removed tile: (" << x << ", " << y << ")" << std::endl; } } } for (int x = 0; x < width_; ++x) { for (int y = height; y < height_; ++y) { if (tiles_[x][y]) { removeTile(tiles_[x][y]); std::cout << "Removed tile: (" << x << ", " << y << ")" << std::endl; } } } width_ = width; height_ = height; tiles_.resize(width_); for (int x = 0; x < tiles_.size(); ++x) { tiles_[x].resize(height_); } cleanObjects(); } Tile * Scene::createTile(sol::table luaInstance, std::string category, int x, int y) { Tile* tile = new Tile(world_, luaInstance); tile->setCategory(category); tile->setPosition(x, y); if (x < 0 || x >= width_ || y < 0 || y >= height_) { std::cout << "Warning: cannot add tile on position (" << x << ", " << y << ")" << std::endl; tilesToRemove_.push_back(tile); return tile; } if (tiles_[x][y] != nullptr) { removeTile(tiles_[x][y]); } tiles_[x][y] = tile; return tile; } Entity * Scene::createEntity(sol::table luaInstance, std::string category) { Entity* entity = new Entity(world_, luaInstance); entity->setCategory(category); entities_.push_back(entity); if (entity->getCategory() == "player") { player_ = entity; std::cout << "player! " << entity->getCategory() << std::endl; } return entity; } void Scene::moveEntity(Entity * entity, sf::Vector2i & move) { entity->move(move); entity->setPosition(normalize(entity->getPosition())); } void Scene::removeEntities() { for (int i = 0; i < entities_.size(); ++i) { entities_[i]->markToRemove(); } } void Scene::removeTiles() { for (auto& column : tiles_) { for (auto& tile : column) { if(tile != nullptr) removeTile(tile); } } } void Scene::removeTile(Tile * tile) { if (tile != nullptr && tile == tiles_[tile->getX()][tile->getY()]) { tile->addedToRemove(); tile->markToRemove(); tilesToRemove_.push_back(tile); tiles_[tile->getX()][tile->getY()] = nullptr; } } void Scene::update() { unsigned long long frameNumber = world_->getFrameNumber(); //for (auto& entity : entities_) //{ // entity->update(); // //} cleanObjects(); //std::cout << "Entities size: " << entities_.size() << std::endl; } void Scene::draw() { for (int x = 0; x < tiles_.size(); ++x) { for (int y = 0; y < tiles_[x].size(); ++y) { if (tiles_[x][y] != nullptr) world_->getConsole()->draw(*tiles_[x][y]); } } for (auto& entity : entities_) { world_->getConsole()->draw(*entity); } if(player_ != nullptr) world_->getConsole()->draw(*player_); }
[ "milosz.0518@gmail.com" ]
milosz.0518@gmail.com
a89b95d3f506f968045cbb0fe24a5b29b1e596d3
52fea6f8611737f202ae7012b413199e28e57fa4
/src/stealth.h
31f1f95cee737675b1488cd8c1893a202ed990c7
[ "MIT" ]
permissive
orestdrag/mynovacoin
dceb9f13d9777fac0a4eafa52290a8be36496bb2
1749132193870c4147211e421adb17bc0327d10b
refs/heads/master
2021-01-24T07:57:05.102009
2018-03-12T13:17:24
2018-03-12T13:17:24
122,965,981
0
0
null
null
null
null
UTF-8
C++
false
false
2,478
h
// Copyright (c) 2014 The ShadowCoin developers // Distributed under the MIT/X11 software license, see the accompanying // file license.txt or http://www.opensource.org/licenses/mit-license.php. #ifndef BCCA_STEALTH_H #define BCCA_STEALTH_H #include <stdlib.h> #include <stdio.h> #include <vector> #include <inttypes.h> #include "util.h" #include "serialize.h" #include "key.h" #include "hash.h" #include "types.h" const uint32_t MAX_STEALTH_NARRATION_SIZE = 48; typedef uint32_t stealth_bitfield; struct stealth_prefix { uint8_t number_bits; stealth_bitfield bitfield; }; const uint256 MAX_SECRET("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364140"); const uint256 MIN_SECRET(16000); // increase? min valid key is 1 class CStealthAddress { public: CStealthAddress() { options = 0; }; uint8_t options; ec_point scan_pubkey; ec_point spend_pubkey; //std::vector<ec_point> spend_pubkeys; size_t number_signatures; stealth_prefix prefix; mutable std::string label; data_chunk scan_secret; data_chunk spend_secret; bool SetEncoded(const std::string& encodedAddress); std::string Encoded() const; int SetScanPubKey(CPubKey pk); bool operator <(const CStealthAddress& y) const { return memcmp(&scan_pubkey[0], &y.scan_pubkey[0], EC_COMPRESSED_SIZE) < 0; }; bool operator ==(const CStealthAddress& y) const { return memcmp(&scan_pubkey[0], &y.scan_pubkey[0], EC_COMPRESSED_SIZE) == 0; }; IMPLEMENT_SERIALIZE ( READWRITE(this->options); READWRITE(this->scan_pubkey); READWRITE(this->spend_pubkey); READWRITE(this->label); READWRITE(this->scan_secret); READWRITE(this->spend_secret); ); }; int GenerateRandomSecret(ec_secret& out); int SecretToPublicKey(const ec_secret& secret, ec_point& out); int StealthSecret(ec_secret& secret, ec_point& pubkey, const ec_point& pkSpend, ec_secret& sharedSOut, ec_point& pkOut); int StealthSecretSpend(ec_secret& scanSecret, ec_point& ephemPubkey, ec_secret& spendSecret, ec_secret& secretOut); int StealthSharedToSecretSpend(const ec_secret& sharedS, const ec_secret& spendSecret, ec_secret& secretOut); int StealthSharedToPublicKey(const ec_point& pkSpend, const ec_secret &sharedS, ec_point &pkOut); bool IsStealthAddress(const std::string& encodedAddress); #endif // BCCA_STEALTH_H
[ "orestdrag@gmail.com" ]
orestdrag@gmail.com
4e42c9c59ff270e52f104d93a46e16e2c27d4166
13da34a8bb7a182626a8bc0c769a734f5f925a9f
/cpp_solutions/reverse_words_in_string.cpp
488207208a2e9e3b9cd15fc157f141059f805ab6
[]
no_license
dhruv-jain/leetcode
e7bdc0b78fb2260c0f47162c3b82c17597d6c39b
a10b926b0db383a976b283f00a3ce2b21bba1d2c
refs/heads/master
2022-02-13T13:18:12.923259
2022-02-03T20:42:40
2022-02-03T20:42:40
79,752,469
1
0
null
null
null
null
UTF-8
C++
false
false
428
cpp
//https://leetcode.com/problems/reverse-words-in-a-string-iii/#/description class Solution { public: string reverseWords(string s) { for(int i=0;i<s.length();i++){ if(s[i]!= ' ') { int j=i; for(;j<s.length()&&s[j]!=' ';j++){} reverse(s.begin()+i,s.begin()+j); i=j-1; } } return s; } };
[ "noreply@github.com" ]
dhruv-jain.noreply@github.com
201cbccd818c737e87aced7df50dab66b93ad1bb
03660ace790a910ebdd56c36f29808b690f053c0
/scattered/4.cpp
0c1fdd5c0b94f5877ff7e6c165024f5e20cd0d67
[]
no_license
Monicaofak/algorithm
4671e4bc38553c977465ac3c3d0d59c5fc05e704
c9db431856d3944504efa424ed097c74cd9e0eff
refs/heads/master
2020-12-05T04:58:35.685951
2020-01-22T08:19:29
2020-01-22T08:19:29
232,013,522
0
0
null
null
null
null
UTF-8
C++
false
false
1,025
cpp
/*美国总统奥巴马不仅呼吁所有人都学习编程,甚至以身作则编写代码,成为美国历史上首位编写计算机代码的总统。2014年底,为庆祝“计算机科学教育周”正式启动,奥巴马编写了很简单的计算机代码:在屏幕上画一个正方形。现在你也跟他一起画吧! 输入格式: 输入在一行中给出正方形边长N(3≤N≤21)和组成正方形边的某种字符C,间隔一个空格。 输出格式: 输出由给定字符C画出的正方形。但是注意到行间距比列间距大,所以为了让结果看上去更像正方形,我们输出的行数实际上是列数的50%(四舍五入取整)。 输入样例: 10 a 输出样例: aaaaaaaaaa aaaaaaaaaa aaaaaaaaaa aaaaaaaaaa aaaaaaaaaa */ #include <iostream> using namespace std; int main() { int a; char b; cin>>a>>b; int aa=a/2+a%2; //对a进行四舍五入的操作 for(int i=0;i<aa;i++) { for(int j=0;j<a;j++) { cout<<b; } cout<<endl; } return 0; }
[ "noreply@github.com" ]
Monicaofak.noreply@github.com
d45a953065c93aa6dced6cdcba661bb7ba942235
6afae5bcd6e954f76f5644669e21614e2b555e8e
/sources/terminal.h
cd8222f3e186034f91d9bee62afe7562663a10b5
[]
no_license
intelfx/pulse-dispatcher
cdfc59b04acce1bd425b5cd23f7db343afe73ae9
74b7340325a1b5aec6ecdb095985174d623c8966
refs/heads/master
2021-01-20T09:32:47.580018
2014-11-23T20:11:00
2014-11-23T20:11:03
null
0
0
null
null
null
null
UTF-8
C++
false
false
538
h
#ifndef _SOURCES_TERMINAL_H #define _SOURCES_TERMINAL_H #include <source.h> #include <options.h> class TerminalSource: public AbstractSource { channels_mask_t toggle_mode_channels_; bool toggle_; std::chrono::milliseconds pulse_width_; void toggle(); void toggle_m (channels_mask_t mask); void toggle_internal (channels_mask_t mask); public: TerminalSource(const options_map_t& options); virtual ~TerminalSource(); virtual bool runs_in_main_thread() const; protected: virtual void loop(); }; #endif // _SOURCES_TERMINAL_H
[ "intelfx100@gmail.com" ]
intelfx100@gmail.com
f9f66118579705d938786bd41eafa95619c1b7c0
3ff1fe3888e34cd3576d91319bf0f08ca955940f
/pts/src/v20210728/model/Attributes.cpp
4cc530ee3a69369ea15d6d5e88e338995821f42b
[ "Apache-2.0" ]
permissive
TencentCloud/tencentcloud-sdk-cpp
9f5df8220eaaf72f7eaee07b2ede94f89313651f
42a76b812b81d1b52ec6a217fafc8faa135e06ca
refs/heads/master
2023-08-30T03:22:45.269556
2023-08-30T00:45:39
2023-08-30T00:45:39
188,991,963
55
37
Apache-2.0
2023-08-17T03:13:20
2019-05-28T08:56:08
C++
UTF-8
C++
false
false
5,767
cpp
/* * Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <tencentcloud/pts/v20210728/model/Attributes.h> using TencentCloud::CoreInternalOutcome; using namespace TencentCloud::Pts::V20210728::Model; using namespace std; Attributes::Attributes() : m_statusHasBeenSet(false), m_resultHasBeenSet(false), m_serviceHasBeenSet(false), m_methodHasBeenSet(false), m_durationHasBeenSet(false) { } CoreInternalOutcome Attributes::Deserialize(const rapidjson::Value &value) { string requestId = ""; if (value.HasMember("Status") && !value["Status"].IsNull()) { if (!value["Status"].IsString()) { return CoreInternalOutcome(Core::Error("response `Attributes.Status` IsString=false incorrectly").SetRequestId(requestId)); } m_status = string(value["Status"].GetString()); m_statusHasBeenSet = true; } if (value.HasMember("Result") && !value["Result"].IsNull()) { if (!value["Result"].IsString()) { return CoreInternalOutcome(Core::Error("response `Attributes.Result` IsString=false incorrectly").SetRequestId(requestId)); } m_result = string(value["Result"].GetString()); m_resultHasBeenSet = true; } if (value.HasMember("Service") && !value["Service"].IsNull()) { if (!value["Service"].IsString()) { return CoreInternalOutcome(Core::Error("response `Attributes.Service` IsString=false incorrectly").SetRequestId(requestId)); } m_service = string(value["Service"].GetString()); m_serviceHasBeenSet = true; } if (value.HasMember("Method") && !value["Method"].IsNull()) { if (!value["Method"].IsString()) { return CoreInternalOutcome(Core::Error("response `Attributes.Method` IsString=false incorrectly").SetRequestId(requestId)); } m_method = string(value["Method"].GetString()); m_methodHasBeenSet = true; } if (value.HasMember("Duration") && !value["Duration"].IsNull()) { if (!value["Duration"].IsString()) { return CoreInternalOutcome(Core::Error("response `Attributes.Duration` IsString=false incorrectly").SetRequestId(requestId)); } m_duration = string(value["Duration"].GetString()); m_durationHasBeenSet = true; } return CoreInternalOutcome(true); } void Attributes::ToJsonObject(rapidjson::Value &value, rapidjson::Document::AllocatorType& allocator) const { if (m_statusHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "Status"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_status.c_str(), allocator).Move(), allocator); } if (m_resultHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "Result"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_result.c_str(), allocator).Move(), allocator); } if (m_serviceHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "Service"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_service.c_str(), allocator).Move(), allocator); } if (m_methodHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "Method"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_method.c_str(), allocator).Move(), allocator); } if (m_durationHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "Duration"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, rapidjson::Value(m_duration.c_str(), allocator).Move(), allocator); } } string Attributes::GetStatus() const { return m_status; } void Attributes::SetStatus(const string& _status) { m_status = _status; m_statusHasBeenSet = true; } bool Attributes::StatusHasBeenSet() const { return m_statusHasBeenSet; } string Attributes::GetResult() const { return m_result; } void Attributes::SetResult(const string& _result) { m_result = _result; m_resultHasBeenSet = true; } bool Attributes::ResultHasBeenSet() const { return m_resultHasBeenSet; } string Attributes::GetService() const { return m_service; } void Attributes::SetService(const string& _service) { m_service = _service; m_serviceHasBeenSet = true; } bool Attributes::ServiceHasBeenSet() const { return m_serviceHasBeenSet; } string Attributes::GetMethod() const { return m_method; } void Attributes::SetMethod(const string& _method) { m_method = _method; m_methodHasBeenSet = true; } bool Attributes::MethodHasBeenSet() const { return m_methodHasBeenSet; } string Attributes::GetDuration() const { return m_duration; } void Attributes::SetDuration(const string& _duration) { m_duration = _duration; m_durationHasBeenSet = true; } bool Attributes::DurationHasBeenSet() const { return m_durationHasBeenSet; }
[ "anonymous" ]
anonymous