blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
3
264
content_id
stringlengths
40
40
detected_licenses
sequencelengths
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
sequencelengths
1
1
author_id
stringlengths
0
158
c8111236d062930b5e61856f0a3747a673c9cf63
4c25432a6d82aaebd82fd48e927317b15a6bf6ab
/data/dataset_2017/dataset_2017_8_formatted/Thanabhat/3264486_5633382285312000_Thanabhat.cpp
5095464bfeffa3cc6d7421623d9f84183213d56d
[]
no_license
wzj1988tv/code-imitator
dca9fb7c2e7559007e5dbadbbc0d0f2deeb52933
07a461d43e5c440931b6519c8a3f62e771da2fc2
refs/heads/master
2020-12-09T05:33:21.473300
2020-01-09T15:29:24
2020-01-09T15:29:24
231,937,335
1
0
null
2020-01-05T15:28:38
2020-01-05T15:28:37
null
UTF-8
C++
false
false
708
cpp
#include <iostream> using namespace std; int solve(int cc) { string str; cin >> str; int p = 0; while (p < str.length() - 1) { if (str[p] > str[p + 1]) { break; } p++; } if (p == str.length() - 1) { cout << "Case #" << cc << ": " << str << endl; return 1; } while (p > 0 && str[p - 1] == str[p]) { p--; } str[p] = str[p] - 1; for (int i = p + 1; i < str.length(); i++) { str[i] = '9'; } if (str[0] == '0') { str.erase(str.begin()); } cout << "Case #" << cc << ": " << str << endl; return 1; } int main() { int t; cin >> t; for (int i = 0; i < t; i++) { solve(i + 1); } return 0; }
0b129b2d869eccaf30b3c41d050e274f6904081c
97ca456c57dd3e5e4e05c8ec23f61efb744431c7
/.bak/SbrXXX05.h
a0dbe21562d9f8a9cfc1c49b4da3b7bc18315478
[]
no_license
kwokhung/testESP32
870b807749b7ff3b77dbb91d6e4bb61f675b9953
0005d5b8e131b86cda8d29c1be6325d58b86d3ab
refs/heads/master
2020-12-30T11:02:32.516155
2019-03-18T04:56:37
2019-03-18T04:56:37
98,839,362
0
0
null
null
null
null
UTF-8
C++
false
false
1,185
h
#ifndef SbrXXX05_h #define SbrXXX05_h #include <Kalman.h> #include "SbrBase.h" #define RESTRICT_PITCH // Comment out to restrict roll to ±90deg instead - please read: http://www.freescale.com/files/sensors/doc/app_note/AN3461.pdf #define IMUAddress 0x68 #define I2C_TIMEOUT 1000 class SbrXXX05 : public SbrBase<SbrXXX05> { public: friend class SbrBase; uint8_t mpuWrite(uint8_t registerAddress, uint8_t data, bool sendStop); uint8_t mpuWrite(uint8_t registerAddress, uint8_t *data, uint8_t length, bool sendStop); uint8_t mpuRead(uint8_t registerAddress, uint8_t *data, uint8_t nbytes); private: SbrXXX05(std::string name) : SbrBase(name) { } void setup() override; void loop() override; Kalman kalmanX; // Create the Kalman instances Kalman kalmanY; /* IMU Data */ double accX, accY, accZ; double gyroX, gyroY, gyroZ; int16_t tempRaw; double gyroXangle, gyroYangle; // Angle calculate using the gyro only double compAngleX, compAngleY; // Calculated angle using a complementary filter double kalAngleX, kalAngleY; // Calculated angle using a Kalman filter uint32_t timer; uint8_t i2cData[14]; // Buffer for I2C data }; #endif
dd88d9c91fd171bd0c105ecc3f7386a7bef8b76c
bd5673632d9d65808d81e1e6f45ccd1899b4267a
/src/Ludum/Common.cpp
16bd372948503d3973cfa8f1d2c8b3a7112986d9
[]
no_license
gingerBill/LD-30
6b2676f5cb5ca45979bd5347cfb462ad2ef06b01
875dcc17cb4b87af08b22de0d5a7a8d3fb0e22cd
refs/heads/master
2020-07-03T16:52:55.938626
2016-11-19T23:29:58
2016-11-19T23:29:58
74,241,619
1
0
null
null
null
null
UTF-8
C++
false
false
1,428
cpp
#include <Ludum/Common.hpp> #ifdef __APPLE__ #include <CoreFoundation/CoreFoundation.h> #endif namespace gb { std::string resourcePath() { #ifdef __APPLE__ CFBundleRef mainBundle = CFBundleGetMainBundle(); CFURLRef resourcesURL = CFBundleCopyResourcesDirectoryURL(mainBundle); char path[PATH_MAX]; if (!CFURLGetFileSystemRepresentation(resourcesURL, TRUE, (UInt8 *)path, PATH_MAX)) { // error! } CFRelease(resourcesURL); return std::string(path) + "/"; #elif return ""; #endif } bool getFileContents(const std::string& filename, std::vector<char>& buffer) { std::ifstream file(filename.c_str(), std::ios_base::binary); if (file) { file.seekg(0, std::ios_base::end); std::streamsize size = file.tellg(); if (size > 0) { file.seekg(0, std::ios_base::beg); buffer.resize(static_cast<std::size_t>(size)); file.read(&buffer[0], size); } buffer.push_back('\0'); return true; } else { return false; } } glm::vec4 getTextureCoords(int positionNumber, int width, int height) { // hex // 0 1 2 3 .. F // 10 11 12 13 .. 1F // .. // F0 F1 F2 F3 .. FF // 16 x 16 tiles in texture glm::vec4 uv(0, 0, 0, 0); uv[0] = (positionNumber % 16) / 16.0f; uv[1] = 1.0f - (positionNumber / 16) / 16.0f; uv[2] = uv[0] + width*(1.0f / 16.0f); uv[3] = uv[1] - height*(1.0f / 16.0f); return glm::vec4(uv[0], uv[3], uv[2], uv[1]); } }
934fd98cbc4049b477ddb436ee6c44ca5c543c28
44db3381986906baa858e4012a21f20cb6dfe9a6
/src/intersim2/outputset.cpp
8a9d2cf10155e25071d7cf26eb532ca888bf1c94
[ "BSD-3-Clause" ]
permissive
lakshmankollipara/gpu_current
457da2e5c4e9e1d08d6d1eb520c0d4f45442e1eb
10889439f3fbbe9f8576f8e8bbb0be2602a6d687
refs/heads/master
2021-01-13T08:58:08.992168
2016-09-29T19:45:57
2016-09-29T19:45:57
69,601,629
0
0
null
null
null
null
UTF-8
C++
false
false
3,869
cpp
// $Id: outputset.cpp 5188 2012-08-30 00:31:31Z dub $ /* Copyright (c) 2007-2012, Trustees of The Leland Stanford Junior University All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /*outputset.cpp * *output set assigns a flit which output to go to in a router *used by the VC class *the output assignment is done by the routing algorithms.. * */ #include <cassert> #include "booksim.hpp" #include "outputset.hpp" void OutputSet::Clear( ) { _outputs.clear( ); } void OutputSet::Add( int output_port, int vc, int pri ) { AddRange( output_port, vc, vc, pri ); } void OutputSet::AddRange( int output_port, int vc_start, int vc_end, int pri ) { sSetElement s; s.vc_start = vc_start; s.vc_end = vc_end; s.pri = pri; s.output_port = output_port; _outputs.insert( s ); } //legacy support, for performance, just use GetSet() int OutputSet::NumVCs( int output_port ) const { int total = 0; set<sSetElement>::const_iterator i = _outputs.begin( ); while (i != _outputs.end( )) { if (i->output_port == output_port) { total += (i->vc_end - i->vc_start + 1); } i++; } return total; } bool OutputSet::OutputEmpty( int output_port ) const { set<sSetElement>::const_iterator i = _outputs.begin( ); while (i != _outputs.end( )) { if (i->output_port == output_port) { return false; } i++; } return true; } const set<OutputSet::sSetElement> & OutputSet::GetSet() const { return _outputs; } //legacy support, for performance, just use GetSet() int OutputSet::GetVC( int output_port, int vc_index, int *pri ) const { int range; int remaining = vc_index; int vc = -1; if ( pri ) { *pri = -1; } set<sSetElement>::const_iterator i = _outputs.begin( ); while (i != _outputs.end( )) { if (i->output_port == output_port) { range = i->vc_end - i->vc_start + 1; if ( remaining >= range ) { remaining -= range; } else { vc = i->vc_start + remaining; if ( pri ) { *pri = i->pri; } break; } } i++; } return vc; } //legacy support, for performance, just use GetSet() bool OutputSet::GetPortVC( int *out_port, int *out_vc ) const { bool single_output = false; int used_outputs = 0; set<sSetElement>::const_iterator i = _outputs.begin( ); if (i != _outputs.end( )) { used_outputs = i->output_port; } while (i != _outputs.end( )) { if ( i->vc_start == i->vc_end ) { *out_vc = i->vc_start; *out_port = i->output_port; single_output = true; } else { // multiple vc's selected break; } if (used_outputs != i->output_port) { // multiple outputs selected single_output = false; break; } i++; } return single_output; }
ce18e24fa44b888a0de50bc95a7a727a0d107d0e
32cb04fde0f2c857b6fdbad9ff601b967c588727
/DS-Foundation/timespacecomplex/012.cpp
ae35671d5312257e4fb88704bccf638d083760cb
[]
no_license
ashutoshsidhar/pepcoding
9839ff41c866034c07a741014f4804b59af7b21c
246062e2f6911ae0f0a6cc3d475391627c3cdaa3
refs/heads/master
2023-05-27T23:19:30.049337
2021-06-20T14:21:23
2021-06-20T14:21:23
326,162,829
1
0
null
null
null
null
UTF-8
C++
false
false
973
cpp
#include <iostream> #include <vector> using namespace std; void input(vector<int> &arr) { for (int i = 0; i < arr.size(); i++) { cin >> arr[i]; } } void print(vector<int> &arr) { for (int i = 0; i < arr.size(); i++) { cout << arr[i] << endl; } cout << endl; } // used for swapping ith and jth elements of array void swap(vector<int> &arr, int i, int j) { cout << ("Swapping index " + to_string(i) + " and index " + to_string(j)) << endl; int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } void sort012(vector<int> &arr) { int n = arr.size(); int pt1 = 0 , itr = 0 , pt2 = n - 1 ; while(itr <= pt2){ if(arr[itr] == 0) swap(arr,itr++,pt1++); else if(arr[itr] == 2) swap(arr, itr , pt2--); else itr++; } } int main() { int n, m; cin >> n; vector<int> A(n, 0); input(A); sort012(A); print(A); return 0; }
c2cffe098429e136aba0db297196bda85f5b0b46
4bcc9806152542ab43fc2cf47c499424f200896c
/tensorflow/core/kernels/mlir_generated/gpu_op_complex_abs.cc
69f45d58b18eac44f019aa12060ae83a812a3a57
[ "Apache-2.0", "LicenseRef-scancode-generic-cla", "BSD-2-Clause" ]
permissive
tensorflow/tensorflow
906276dbafcc70a941026aa5dc50425ef71ee282
a7f3934a67900720af3d3b15389551483bee50b8
refs/heads/master
2023-08-25T04:24:41.611870
2023-08-25T04:06:24
2023-08-25T04:14:08
45,717,250
208,740
109,943
Apache-2.0
2023-09-14T20:55:50
2015-11-07T01:19:20
C++
UTF-8
C++
false
false
1,130
cc
/* Copyright 2021 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. ==============================================================================*/ #include <complex> #include "third_party/eigen3/unsupported/Eigen/CXX11/Tensor" #include "tensorflow/core/kernels/mlir_generated/base_gpu_op.h" namespace tensorflow { GENERATE_UNARY_GPU_KERNEL2(ComplexAbs, DT_COMPLEX64, DT_FLOAT); REGISTER_COMPLEX_GPU_KERNEL(ComplexAbs, DT_COMPLEX64, DT_FLOAT); GENERATE_UNARY_GPU_KERNEL2(ComplexAbs, DT_COMPLEX128, DT_DOUBLE); REGISTER_COMPLEX_GPU_KERNEL(ComplexAbs, DT_COMPLEX128, DT_DOUBLE); } // namespace tensorflow
427030fa8994144e2db76c609e19052443f368ab
634f95f90230b0f7e11158dc271cba5a3bc703c7
/tkEngine/Input/tkKeyInput.h
968b58afea87d65993e5c2afdfe40c0485c52f15
[]
no_license
TakayukiKiyohara/Sandbox
55c7e2051bcb55b7765a9f367c3ee47d33f473de
99c354eb91c501d8a10d09806aa4acdcf5d26dcb
refs/heads/master
2021-01-18T01:06:30.462238
2016-11-11T13:43:58
2016-11-11T13:43:58
68,387,195
4
0
null
null
null
null
SHIFT_JIS
C++
false
false
2,275
h
/*! * @brief キー入力。 */ #ifndef _TKKEYINPUT_H_ #define _TKKEYINPUT_H_ #include "tkEngine/Input/tkPad.h" namespace tkEngine{ class CKeyInput{ public: static const int NUM_PAD = 4; //パッドの数。 enum EnKey { enKeyUp, enKeyDown, enKeyRight, enKeyLeft, enKeyA, enKeyB, enKeyNum, }; /*! * @brief コンストラクタ。 */ CKeyInput(); /*! * @brief デストラクタ。 */ ~CKeyInput(); /*! * @brief キー情報の更新。 */ void Update(); /*! * @brief 上キーが押されている。 */ bool IsUpPress() const { return m_keyPressFlag[enKeyUp]; } /*! * @brief 右キーが押されている。 */ bool IsRightPress() const { return m_keyPressFlag[enKeyRight]; } /*! * @brief 左キーが押されている。 */ bool IsLeftPress() const { return m_keyPressFlag[enKeyLeft]; } /*! * @brief 下キーが押されている。 */ bool IsDownPress() const { return m_keyPressFlag[enKeyDown]; } /*! * @brief キーのプレス判定。 */ bool IsPress(EnKey key) const { return m_keyPressFlag[key]; } /*! * @brief キーのトリガー判定。 */ bool IsTrgger(EnKey key) const { return m_keyTrigerFlag[key]; } /*! * @brief マウスの左ボタンが離されたときの処理。 */ void OnMouseLButtonUp(int x, int y) { m_mousePositionX = x; m_mousePositionY = y; m_isMouseUp[1] = true; } /*! * @brief マウスの左ボタンが離されたときか判定。 */ bool IsMouseLButtonUp() const { return m_isMouseUp[0]; } /*! * @brief マウスのX座標を取得。 */ int GetMousePositionX() const { return m_mousePositionX; } /*! * @brief マウスのY座標を取得。 */ int GetMousePositionY() const { return m_mousePositionY; } /*! * @brief ゲームパッドを取得。 */ const CPad& GetPad(int padNo) const { TK_ASSERT(padNo < NUM_PAD, "padNo is invalid"); return m_pad[padNo]; } private: bool m_keyPressFlag[enKeyNum]; bool m_keyTrigerFlag[enKeyNum]; bool m_isMouseUp[2]; int m_mousePositionX; int m_mousePositionY; CPad m_pad[NUM_PAD]; //!<パッド。 }; } #endif //_TKKEYINPUT_H_
0c6fb22f031020cc96911c76f01331c6f100cf4b
f7a177c84dc08f016ff81fe558ffb1311b2afbf7
/PolyIntegrator 2.cpp
c8a8f97d12102494f8b077fa261b12d410d5bd6f
[]
no_license
roods29/proj-
6f949f7ffda244792a6db677530fb3e91e7ab51e
469bc08b3ec737b4fa6bbaaf24b7eac4b5e14443
refs/heads/master
2020-05-16T01:43:59.966193
2019-04-22T02:38:13
2019-04-22T02:38:13
182,609,981
0
0
null
null
null
null
UTF-8
C++
false
false
8,645
cpp
/*** Gives a string representation of this polynomial in standard * form where zero terms, coefficients 1 or -1, and exponents 1 * are not displayed. * @param poly a degree-coefficients array representation of a* polynomial. * @return a string representation of this polynomial */ #include <iostream> #include <string> #include <sstream> #include <math.h> using namespace std; int main() { string polyToString (const double poly[]); double polyEval(const double poly[],double x); double nIntegrate(const double poly[], double x1, double x2, double delX); void print_polynomial(double poly[], int n); double* integrate(const double poly[], double c); int n; string spoly; cout<<" Enter the degree of a Polynomial -> "; cin>>n; double poly [n+2]; poly[0] = n; cout<<endl<<"Enter the coefficients -> "; cin.ignore(); getline(cin, spoly); //from here std::string delimiter = " "; size_t pos = 0; //"2 2 2" std::string token; if(n+1 == 1){poly[1] = std::stoi(spoly);} else{ for(int i = 1; i <= n+1; i++){ pos = spoly.find(delimiter); token = spoly.substr(0, pos); poly[i] = std::stoi( token ); spoly.erase(0, pos+1); } } cout << "f(x) = " << polyToString(poly) << endl; int x; cout <<endl<< "Enter x at which to evaluate f (x) -> "; cin >> x; cout << "f(" << x << ") = " << polyEval(poly, x); cout << endl << "Enter the lower and upper limits for the integrals -> "; //catch input for upper and lower, send to integral cin.ignore(); getline(cin, spoly); pos = spoly.find(delimiter); token = spoly.substr(0, pos); double x1 = std::stoi( token ); spoly.erase(0, pos+1); double x2 = std::stoi( spoly ); double c = 2; cout << endl << "I[f(x), dx] = ";// << polyToString(integrate(poly,c)); double delX = .0000001; cout << endl << "Exact:" <<endl << "I[" << polyToString(poly) << " dx, " << x1 << ", " << x2 << "] = "<< nIntegrate(poly, x1, x2, delX)<<endl; cout << endl << "Trapezoid Rule:" <<endl << "I[" << polyToString(poly) << ", deltax = 1E-7, " << x1 << ", " << x2 << "] = "<< nIntegrate(poly, x1, x2, delX)<<endl; //cout << endl << "Error Calculation: "; } /** * Gives a string representation of this polynomial in standard * form where zero terms, coefficients 1 or -1, and exponents 1 * are not displayed. * <pre> * Note: Rules for Representing a Polynomial in Normalized Form: * 1. If the degree of the polynomial is 0, return a string * representing the number. * 2. If the degree of the polynomial is 1, return a string * representing the polynomial in the form ax + b, where when * b is zero it should not be displayed and when a is -1 or 1 * it should not be displayed as a coefficient of x. * 3. If the degree of the polynomial is 2 or more, follow these * steps: * A. Generate the string representation of the highest order * term without using 1, -1 as its coefficient. * B. Generate the string representations of all other, but * the last two, terms beginning from the second highest * order term without the use of 1 and -1 as coefficients * and without including a zero term. Then deal with the * last two terms: * i. If its linear term is non-zero, generate and append * the linear term but without the use of 1 and -1 as * its coefficient and 1 as its exponent. * ii. Finally, append the constant term, the lowest order * term, if it is non-zero. * eg: [6, 3, 0, -1, 0, 1, 1, 0] -> 3x^6 - x^4 + x^2 + x * [5, -1, 0, 3, 0, -1, 1] -> -x^5 + 3x^3 - x + 1 * </pre> * @param poly a degree-coefficients array representation of a * polynomial. * @return a string representation of this polynomial */ string polyToString(const double poly[]) { stringstream ss; double degree = poly[0]; if(degree==0) { ss << poly[1]; } else if(degree==1) { int a = poly[1]; int b = poly[2]; if (b > 0) { if (a == 1) ss << "x + " << b; else if ( a == -1) ss << "-x + " << b; else ss << a << "x + " << b; } else if (b < 0) { if (a == 1) ss << "x " << b; else if ( a == -1 ) ss << "-x " << b; else ss << a << "x" << b; } else if (a == 1) ss << "x"; else if (a == -1) ss << "-x"; else ss << a << "x"; } else if(degree > 1) { int i; if (poly[1] == 1) ss << "x^" << degree; else if (poly[1] == -1) ss << "-x^" << degree; else ss << poly[1] << "x^" << degree << " "; for (i = 2; i <= degree-1; i++) { if (poly[i] > 0) { if (poly[i] == 1) ss << "+" << "x^" << degree - i+1 << " "; else if (poly[i] == -1) ss << "+" << "x^" << degree - i+1 << " "; else ss << "+" << poly[i] << "x^" << degree - i+1 << " "; } else if (poly[i] < 0) { if(poly[i] == 1) ss << "-" << "x^" << degree - i+1 << " "; else if (poly[i] == -1) ss << "-" << "x^" << degree - i+1 << " "; else ss << " " << poly[i] << "x^" << degree - i+1 << " "; } else ; } int a = poly[i]; int b = poly[i + 1]; if(b > 0) { if (a > 0) { if (a == 1) ss << "+ x + " << b; else ss << "+ " << a << "x + " << b; } else if (a < 0) { if (a == -1) ss << "- x + " << b; else ss << a << "x + " << b; } else ss << "+ " << b; } else if (b < 0) { { if (a > 0) { if (a == 1) ss << "+ x +- " << b; else ss << "+ " << a << "x - " << b; } else ss << b; } } else { if (a > 0) { if (a == 1) ss << "+ x"; else ss << "+" << a << "x"; } else if (a < 0) { if(a == -1) ss << "-x"; else ss << a << "x"; } else ; } } return ss.str(); } /** * Computes an indefinite integral for the specified * polynomial * @param poly a degree-coefficients array representation of a * polynomial. * @param c the constant term * @return the array representation of the integeral of the * specified * polynomial with the specified constant term. */ double* integrate(const double poly[], double c) { return 0; } /** * Evaluates the polynomial represented by the array at the * specified value. * @param poly a degree-coefficients array representation of a * polynomial. * @param x numeric value at which the polynomial is to be * evaluated. * @return the value of the polynomial when evaluated with x */ double polyEval(const double poly[],double x) { int degree = poly[0]; double result = 0; int n = 1; int i; for (i=degree; i > 0; i--){ result += poly[i]*pow(x,n); n++; } result += poly[degree+1]; return result; } /** * Computes a definite integral for the specified * polynomial using the trapezoidal rule. * @param poly a degree-coefficients array representation of a * polynomial. * @param x1 the lower limit * @param x2 the upper limit * @return the area under the curve in the interval [x1, x2] */ double nIntegrate(const double poly[], double x1, double x2, double delX) { double integral = 0; while (x1 < x2) { integral = integral + delX + ((polyEval(poly, x1) + polyEval(poly, x1 + delX))/2); x1 = x1 + delX; } return integral; }
b4a2064657b3ade632cff70ed8c387cd2a4ddfe2
bca6236c6950504749735db6bf0652876a5afde4
/external/tesseract/classify/mfoutline.cpp
623d1174f145e5e62de4f681837f0158612c7542
[ "LicenseRef-scancode-warranty-disclaimer", "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ]
permissive
XiangGen/galaxy
3ef02dc84aeb38243284770023d6c7e17bcac3d2
ffb382e6f7f7786df7ff2324eb3f7f0f870b8048
refs/heads/master
2022-10-05T05:52:51.942323
2020-06-07T12:48:18
2020-06-07T12:48:18
null
0
0
null
null
null
null
UTF-8
C++
false
false
34,218
cpp
/****************************************************************************** ** Filename: mfoutline.c ** Purpose: Interface to outline struct used for extracting features ** Author: Dan Johnson ** History: Thu May 17 08:14:18 1990, DSJ, Created. ** ** (c) Copyright Hewlett-Packard Company, 1988. ** 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 Files and Type Defines ----------------------------------------------------------------------------**/ #include "clusttool.h" //If remove you get cought in a loop somewhere #include "emalloc.h" #include "mfoutline.h" #include "hideedge.h" #include "blobs.h" #include "const.h" #include "mfx.h" #include "varable.h" #include <math.h> #include <stdio.h> #define MIN_INERTIA (0.00001) /**---------------------------------------------------------------------------- Global Data Definitions and Declarations ----------------------------------------------------------------------------**/ /* center of current blob being processed - used when "unexpanding" expanded blobs */ static TPOINT BlobCenter; /**---------------------------------------------------------------------------- Variables ----------------------------------------------------------------------------**/ /* control knobs used to control normalization of outlines */ INT_VAR(classify_norm_method, character, "Normalization Method ..."); /* PREV DEFAULT "baseline" */ double_VAR(classify_char_norm_range, 0.2, "Character Normalization Range ..."); double_VAR(classify_min_norm_scale_x, 0.0, "Min char x-norm scale ..."); /* PREV DEFAULT 0.1 */ double_VAR(classify_max_norm_scale_x, 0.325, "Max char x-norm scale ..."); /* PREV DEFAULT 0.3 */ double_VAR(classify_min_norm_scale_y, 0.0, "Min char y-norm scale ..."); /* PREV DEFAULT 0.1 */ double_VAR(classify_max_norm_scale_y, 0.325, "Max char y-norm scale ..."); /* PREV DEFAULT 0.3 */ /**---------------------------------------------------------------------------- Public Code ----------------------------------------------------------------------------**/ /*---------------------------------------------------------------------------*/ void ComputeBlobCenter(TBLOB *Blob, TPOINT *BlobCenter) { /* ** Parameters: ** Blob blob to compute centerpoint of ** BlobCenter data struct to place results in ** Globals: none ** Operation: ** This routine computes the center point of the specified ** blob using the bounding box of all top level outlines in the ** blob. The center point is computed in a coordinate system ** which is scaled up by VECSCALE from the page coordinate ** system. ** Return: none ** Exceptions: none ** History: Fri Sep 8 10:45:39 1989, DSJ, Created. */ TPOINT TopLeft; TPOINT BottomRight; blob_bounding_box(Blob, &TopLeft, &BottomRight); BlobCenter->x = ((TopLeft.x << VECSCALE) + (BottomRight.x << VECSCALE)) / 2; BlobCenter->y = ((TopLeft.y << VECSCALE) + (BottomRight.y << VECSCALE)) / 2; } /* ComputeBlobCenter */ /*---------------------------------------------------------------------------*/ LIST ConvertBlob(TBLOB *Blob) { /* ** Parameters: ** Blob blob to be converted ** Globals: none ** Operation: Convert Blob into a list of outlines. ** Return: List of outlines representing blob. ** Exceptions: none ** History: Thu Dec 13 15:40:17 1990, DSJ, Created. */ LIST ConvertedOutlines = NIL; if (Blob != NULL) { SettupBlobConversion(Blob); //ComputeBlobCenter (Blob, &BlobCenter); ConvertedOutlines = ConvertOutlines (Blob->outlines, ConvertedOutlines, outer); } return (ConvertedOutlines); } /* ConvertBlob */ /*---------------------------------------------------------------------------*/ MFOUTLINE ConvertOutline(TESSLINE *Outline) { /* ** Parameters: ** Outline outline to be converted ** Globals: ** BlobCenter pre-computed center of current blob ** Operation: ** This routine converts the specified outline into a special ** data structure which is used for extracting micro-features. ** If the outline has been pre-normalized by the splitter, ** then it is assumed to be in expanded form and all we must ** do is copy the points. Otherwise, ** if the outline is expanded, then the expanded form is used ** and the coordinates of the points are returned to page ** coordinates using the global variable BlobCenter and the ** scaling factor REALSCALE. If the outline is not expanded, ** then the compressed form is used. ** Return: Outline converted into special micro-features format. ** Exceptions: none ** History: 8/2/89, DSJ, Created. ** 9/8/89, DSJ, Added ability to convert expanded blobs. ** 1/11/90, DSJ, Changed to use REALSCALE instead of VECSCALE ** to eliminate round-off problems. ** 2/21/91, DSJ, Added ability to work with pre-normalized ** blobs. ** 4/30/91, DSJ, Added concept of "hidden" segments. */ register BYTEVEC *Vector; TPOINT Position; TPOINT StartPosition; MFEDGEPT *NewPoint; MFOUTLINE MFOutline = NIL; EDGEPT *EdgePoint; EDGEPT *StartPoint; EDGEPT *NextPoint; if (Outline == NULL || (Outline->compactloop == NULL && Outline->loop == NULL)) return (MFOutline); /* have outlines been prenormalized */ if (classify_baseline_normalized) { StartPoint = Outline->loop; EdgePoint = StartPoint; do { NextPoint = EdgePoint->next; /* filter out duplicate points */ if (EdgePoint->pos.x != NextPoint->pos.x || EdgePoint->pos.y != NextPoint->pos.y) { NewPoint = NewEdgePoint (); ClearMark(NewPoint); NewPoint->Hidden = is_hidden_edge (EdgePoint) ? TRUE : FALSE; NewPoint->Point.x = EdgePoint->pos.x; NewPoint->Point.y = EdgePoint->pos.y; MFOutline = push (MFOutline, NewPoint); } EdgePoint = NextPoint; } while (EdgePoint != StartPoint); } /* use compressed version of outline */ else if (Outline->loop == NULL) { Position.x = StartPosition.x = Outline->start.x; Position.y = StartPosition.y = Outline->start.y; Vector = Outline->compactloop; do { if (Vector->dx != 0 || Vector->dy != 0) { NewPoint = NewEdgePoint (); ClearMark(NewPoint); /* all edges are visible */ NewPoint->Hidden = FALSE; NewPoint->Point.x = Position.x; NewPoint->Point.y = Position.y; MFOutline = push (MFOutline, NewPoint); } Position.x += Vector->dx; Position.y += Vector->dy; Vector++; } while (Position.x != StartPosition.x || (Position.y != StartPosition.y)); } else { /* use expanded version of outline */ StartPoint = Outline->loop; EdgePoint = StartPoint; do { NextPoint = EdgePoint->next; /* filter out duplicate points */ if (EdgePoint->pos.x != NextPoint->pos.x || EdgePoint->pos.y != NextPoint->pos.y) { NewPoint = NewEdgePoint (); ClearMark(NewPoint); NewPoint->Hidden = is_hidden_edge (EdgePoint) ? TRUE : FALSE; NewPoint->Point.x = (EdgePoint->pos.x + BlobCenter.x) / REALSCALE; NewPoint->Point.y = (EdgePoint->pos.y + BlobCenter.y) / REALSCALE; MFOutline = push (MFOutline, NewPoint); } EdgePoint = NextPoint; } while (EdgePoint != StartPoint); } MakeOutlineCircular(MFOutline); return (MFOutline); } /* ConvertOutline */ /*---------------------------------------------------------------------------*/ LIST ConvertOutlines(TESSLINE *Outline, LIST ConvertedOutlines, OUTLINETYPE OutlineType) { /* ** Parameters: ** Outline first outline to be converted ** ConvertedOutlines list to add converted outlines to ** OutlineType are the outlines outer or holes? ** Globals: none ** Operation: ** This routine converts all given outlines into a new format. ** of outlines. Outline points to a list of the top level ** outlines to be converted. The children of these outlines ** are also recursively converted. All converted outlines ** are added to ConvertedOutlines. This is a list of outlines, ** one for each outline that was converted. ** Return: Updated list of converted outlines. ** Exceptions: none ** History: Thu Dec 13 15:57:38 1990, DSJ, Created. */ MFOUTLINE MFOutline; while (Outline != NULL) { if (Outline->child != NULL) { if (OutlineType == outer) ConvertedOutlines = ConvertOutlines (Outline->child, ConvertedOutlines, hole); else ConvertedOutlines = ConvertOutlines (Outline->child, ConvertedOutlines, outer); } MFOutline = ConvertOutline (Outline); ConvertedOutlines = push (ConvertedOutlines, MFOutline); Outline = Outline->next; } return (ConvertedOutlines); } /* ConvertOutlines */ /*---------------------------------------------------------------------------*/ void ComputeOutlineStats(LIST Outlines, OUTLINE_STATS *OutlineStats) { /* ** Parameters: ** Outlines list of outlines to compute stats for ** OutlineStats place to put results ** Globals: none ** Operation: This routine computes several statistics about the outlines ** in Outlines. These statistics are usually used to perform ** anistropic normalization of all of the outlines. The ** statistics generated are: ** first moments about x and y axes ** total length of all outlines ** center of mass of all outlines ** second moments about center of mass axes ** radius of gyration about center of mass axes ** Return: none (results are returned in OutlineStats) ** Exceptions: none ** History: Fri Dec 14 08:32:03 1990, DSJ, Created. */ MFOUTLINE Outline; MFOUTLINE EdgePoint; MFEDGEPT *Current; MFEDGEPT *Last; InitOutlineStats(OutlineStats); iterate(Outlines) { Outline = (MFOUTLINE) first_node (Outlines); Last = PointAt (Outline); Outline = NextPointAfter (Outline); EdgePoint = Outline; do { Current = PointAt (EdgePoint); UpdateOutlineStats (OutlineStats, Last->Point.x, Last->Point.y, Current->Point.x, Current->Point.y); Last = Current; EdgePoint = NextPointAfter (EdgePoint); } while (EdgePoint != Outline); } FinishOutlineStats(OutlineStats); } /* ComputeOutlineStats */ /*---------------------------------------------------------------------------*/ void FilterEdgeNoise(MFOUTLINE Outline, FLOAT32 NoiseSegmentLength) { /* ** Parameters: ** Outline outline to be filtered ** NoiseSegmentLength maximum length of a "noise" segment ** Globals: none ** Operation: Filter out noise from the specified outline. This is ** done by changing the direction of short segments of the ** outline to the same direction as the preceding outline ** segment. ** Return: none ** Exceptions: none ** History: Fri May 4 10:23:45 1990, DSJ, Created. */ MFOUTLINE Current; MFOUTLINE Last; MFOUTLINE First; FLOAT32 Length; int NumFound = 0; DIRECTION DirectionOfFirst = north; if (DegenerateOutline (Outline)) return; /* find 2 segments of different orientation which are long enough to not be filtered. If two cannot be found, leave the outline unchanged. */ First = NextDirectionChange (Outline); Last = First; do { Current = NextDirectionChange (Last); Length = DistanceBetween ((PointAt (Current)->Point), PointAt (Last)->Point); if (Length >= NoiseSegmentLength) { if (NumFound == 0) { NumFound = 1; DirectionOfFirst = PointAt (Last)->Direction; } else if (DirectionOfFirst != PointAt (Last)->Direction) break; } Last = Current; } while (Last != First); if (Current == Last) return; /* find each segment and filter it out if it is too short. Note that the above code guarantees that the initial direction change will not be removed, therefore the loop will terminate. */ First = Last; do { Current = NextDirectionChange (Last); Length = DistanceBetween (PointAt (Current)->Point, PointAt (Last)->Point); if (Length < NoiseSegmentLength) ChangeDirection (Last, Current, PointAt (Last)->PreviousDirection); Last = Current; } while (Last != First); } /* FilterEdgeNoise */ /*---------------------------------------------------------------------------*/ void FindDirectionChanges(MFOUTLINE Outline, FLOAT32 MinSlope, FLOAT32 MaxSlope) { /* ** Parameters: ** Outline micro-feature outline to analyze ** MinSlope controls "snapping" of segments to horizontal ** MaxSlope controls "snapping" of segments to vertical ** Globals: none ** Operation: ** This routine searches thru the specified outline, computes ** a slope for each vector in the outline, and marks each ** vector as having one of the following directions: ** N, S, E, W, NE, NW, SE, SW ** This information is then stored in the outline and the ** outline is returned. ** Return: none ** Exceptions: none ** History: 7/21/89, DSJ, Created. */ MFEDGEPT *Current; MFEDGEPT *Last; MFOUTLINE EdgePoint; if (DegenerateOutline (Outline)) return; Last = PointAt (Outline); Outline = NextPointAfter (Outline); EdgePoint = Outline; do { Current = PointAt (EdgePoint); ComputeDirection(Last, Current, MinSlope, MaxSlope); Last = Current; EdgePoint = NextPointAfter (EdgePoint); } while (EdgePoint != Outline); } /* FindDirectionChanges */ /*---------------------------------------------------------------------------*/ void FreeMFOutline(void *arg) { //MFOUTLINE Outline) /* ** Parameters: ** Outline micro-feature outline to be freed ** Globals: none ** Operation: ** This routine deallocates all of the memory consumed by ** a micro-feature outline. ** Return: none ** Exceptions: none ** History: 7/27/89, DSJ, Created. */ MFOUTLINE Start; MFOUTLINE Outline = (MFOUTLINE) arg; /* break the circular outline so we can use std. techniques to deallocate */ Start = rest (Outline); set_rest(Outline, NIL); while (Start != NULL) { free_struct (first_node (Start), sizeof (MFEDGEPT), "MFEDGEPT"); Start = pop (Start); } } /* FreeMFOutline */ /*---------------------------------------------------------------------------*/ void FreeOutlines(LIST Outlines) { /* ** Parameters: ** Outlines list of mf-outlines to be freed ** Globals: none ** Operation: Release all memory consumed by the specified list ** of outlines. ** Return: none ** Exceptions: none ** History: Thu Dec 13 16:14:50 1990, DSJ, Created. */ destroy_nodes(Outlines, FreeMFOutline); } /* FreeOutlines */ /*---------------------------------------------------------------------------*/ void MarkDirectionChanges(MFOUTLINE Outline) { /* ** Parameters: ** Outline micro-feature outline to analyze ** Globals: none ** Operation: ** This routine searches thru the specified outline and finds ** the points at which the outline changes direction. These ** points are then marked as "extremities". This routine is ** used as an alternative to FindExtremities(). It forces the ** endpoints of the microfeatures to be at the direction ** changes rather than at the midpoint between direction ** changes. ** Return: none ** Exceptions: none ** History: 6/29/90, DSJ, Created. */ MFOUTLINE Current; MFOUTLINE Last; MFOUTLINE First; if (DegenerateOutline (Outline)) return; First = NextDirectionChange (Outline); Last = First; do { Current = NextDirectionChange (Last); MarkPoint (PointAt (Current)); Last = Current; } while (Last != First); } /* MarkDirectionChanges */ /*---------------------------------------------------------------------------*/ MFEDGEPT *NewEdgePoint() { /* ** Parameters: none ** Globals: none ** Operation: ** This routine allocates and returns a new edge point for ** a micro-feature outline. ** Return: New edge point. ** Exceptions: none ** History: 7/21/89, DSJ, Created. */ return ((MFEDGEPT *) alloc_struct (sizeof (MFEDGEPT), "MFEDGEPT")); } /* NewEdgePoint */ /*---------------------------------------------------------------------------*/ MFOUTLINE NextExtremity(MFOUTLINE EdgePoint) { /* ** Parameters: ** EdgePoint start search from this point ** Globals: none ** Operation: ** This routine returns the next point in the micro-feature ** outline that is an extremity. The search starts after ** EdgePoint. The routine assumes that the outline being ** searched is not a degenerate outline (i.e. it must have ** 2 or more edge points). ** Return: Next extremity in the outline after EdgePoint. ** Exceptions: none ** History: 7/26/89, DSJ, Created. */ EdgePoint = NextPointAfter (EdgePoint); while (!PointAt (EdgePoint)->ExtremityMark) EdgePoint = NextPointAfter (EdgePoint); return (EdgePoint); } /* NextExtremity */ /*---------------------------------------------------------------------------*/ void NormalizeOutline(MFOUTLINE Outline, LINE_STATS *LineStats, FLOAT32 XOrigin) { /* ** Parameters: ** Outline outline to be normalized ** LineStats statistics for text line normalization ** XOrigin x-origin of text ** Globals: none ** Operation: ** This routine normalizes the coordinates of the specified ** outline so that the outline is deskewed down to the ** baseline, translated so that x=0 is at XOrigin, and scaled ** so that the height of a character cell from descender to ** ascender is 1. Of this height, 0.25 is for the descender, ** 0.25 for the ascender, and 0.5 for the x-height. The ** y coordinate of the baseline is 0. ** Return: none ** Exceptions: none ** History: 8/2/89, DSJ, Created. ** 10/23/89, DSJ, Added ascender/descender stretching. ** 11/89, DSJ, Removed ascender/descender stretching. */ MFEDGEPT *Current; MFOUTLINE EdgePoint; FLOAT32 ScaleFactor; FLOAT32 AscStretch; FLOAT32 DescStretch; if (Outline != NIL) { ScaleFactor = ComputeScaleFactor (LineStats); AscStretch = 1.0; DescStretch = 1.0; EdgePoint = Outline; do { Current = PointAt (EdgePoint); Current->Point.y = ScaleFactor * (Current->Point.y - BaselineAt (LineStats, XPositionOf (Current))); if (Current->Point.y > NORMAL_X_HEIGHT) Current->Point.y = NORMAL_X_HEIGHT + (Current->Point.y - NORMAL_X_HEIGHT) / AscStretch; else if (Current->Point.y < NORMAL_BASELINE) Current->Point.y = NORMAL_BASELINE + (Current->Point.y - NORMAL_BASELINE) / DescStretch; Current->Point.x = ScaleFactor * (Current->Point.x - XOrigin); EdgePoint = NextPointAfter (EdgePoint); } while (EdgePoint != Outline); } } /* NormalizeOutline */ /*---------------------------------------------------------------------------*/ void NormalizeOutlines(LIST Outlines, LINE_STATS *LineStats, FLOAT32 *XScale, FLOAT32 *YScale) { /* ** Parameters: ** Outlines list of outlines to be normalized ** LineStats statistics for text line normalization ** XScale x-direction scale factor used by routine ** YScale y-direction scale factor used by routine ** Globals: ** classify_norm_method method being used for normalization ** classify_char_norm_range map radius of gyration to this value ** Operation: This routine normalizes every outline in Outlines ** according to the currently selected normalization method. ** It also returns the scale factors that it used to do this ** scaling. The scale factors returned represent the x and ** y sizes in the normalized coordinate system that correspond ** to 1 pixel in the original coordinate system. ** Return: none (Outlines are changed and XScale and YScale are updated) ** Exceptions: none ** History: Fri Dec 14 08:14:55 1990, DSJ, Created. */ MFOUTLINE Outline; OUTLINE_STATS OutlineStats; FLOAT32 BaselineScale; switch (classify_norm_method) { case character: ComputeOutlineStats(Outlines, &OutlineStats); /* limit scale factor to avoid overscaling small blobs (.,`'), thin blobs (l1ift), and merged blobs */ *XScale = *YScale = BaselineScale = ComputeScaleFactor (LineStats); *XScale *= OutlineStats.Ry; *YScale *= OutlineStats.Rx; if (*XScale < classify_min_norm_scale_x) *XScale = classify_min_norm_scale_x; if (*YScale < classify_min_norm_scale_y) *YScale = classify_min_norm_scale_y; if (*XScale > classify_max_norm_scale_x && *YScale <= classify_max_norm_scale_y) *XScale = classify_max_norm_scale_x; *XScale = classify_char_norm_range * BaselineScale / *XScale; *YScale = classify_char_norm_range * BaselineScale / *YScale; iterate(Outlines) { Outline = (MFOUTLINE) first_node (Outlines); CharNormalizeOutline (Outline, OutlineStats.x, OutlineStats.y, *XScale, *YScale); } break; case baseline: iterate(Outlines) { Outline = (MFOUTLINE) first_node (Outlines); NormalizeOutline (Outline, LineStats, 0.0); } *XScale = *YScale = ComputeScaleFactor (LineStats); break; } } /* NormalizeOutlines */ /*---------------------------------------------------------------------------*/ void SettupBlobConversion(TBLOB *Blob) { /* ** Parameters: ** Blob blob that is to be converted ** Globals: ** BlobCenter center of blob to be converted ** Operation: Compute the center of the blob's bounding box and save ** it in a global variable. This routine must be called before ** any calls to ConvertOutline. It must be called once per ** blob. ** Return: none ** Exceptions: none ** History: Thu May 17 11:06:17 1990, DSJ, Created. */ ComputeBlobCenter(Blob, &BlobCenter); } /* SettupBlobConversion */ /*---------------------------------------------------------------------------*/ void SmearExtremities(MFOUTLINE Outline, FLOAT32 XScale, FLOAT32 YScale) { /* ** Parameters: ** Outline outline whose extremities are to be smeared ** XScale factor used to normalize outline in x dir ** YScale factor used to normalize outline in y dir ** Globals: none ** Operation: ** This routine smears the extremities of the specified outline. ** It does this by adding a random number between ** -0.5 and 0.5 pixels (that is why X/YScale are needed) to ** the x and y position of the point. This is done so that ** the discrete nature of the original scanned image does not ** affect the statistical clustering used during training. ** Return: none ** Exceptions: none ** History: 1/11/90, DSJ, Created. */ MFEDGEPT *Current; MFOUTLINE EdgePoint; FLOAT32 MinXSmear; FLOAT32 MaxXSmear; FLOAT32 MinYSmear; FLOAT32 MaxYSmear; if (Outline != NIL) { MinXSmear = -0.5 * XScale; MaxXSmear = 0.5 * XScale; MinYSmear = -0.5 * YScale; MaxYSmear = 0.5 * YScale; EdgePoint = Outline; do { Current = PointAt (EdgePoint); if (Current->ExtremityMark) { Current->Point.x += UniformRandomNumber(MinXSmear, MaxXSmear); Current->Point.y += UniformRandomNumber(MinYSmear, MaxYSmear); } EdgePoint = NextPointAfter (EdgePoint); } while (EdgePoint != Outline); } } /* SmearExtremities */ /**---------------------------------------------------------------------------- Private Code ----------------------------------------------------------------------------**/ /*---------------------------------------------------------------------------*/ void ChangeDirection(MFOUTLINE Start, MFOUTLINE End, DIRECTION Direction) { /* ** Parameters: ** Start, End defines segment of outline to be modified ** Direction new direction to assign to segment ** Globals: none ** Operation: Change the direction of every vector in the specified ** outline segment to Direction. The segment to be changed ** starts at Start and ends at End. Note that the previous ** direction of End must also be changed to reflect the ** change in direction of the point before it. ** Return: none ** Exceptions: none ** History: Fri May 4 10:42:04 1990, DSJ, Created. */ MFOUTLINE Current; for (Current = Start; Current != End; Current = NextPointAfter (Current)) PointAt (Current)->Direction = Direction; PointAt (End)->PreviousDirection = Direction; } /* ChangeDirection */ /*---------------------------------------------------------------------------*/ void CharNormalizeOutline(MFOUTLINE Outline, FLOAT32 XCenter, FLOAT32 YCenter, FLOAT32 XScale, FLOAT32 YScale) { /* ** Parameters: ** Outline outline to be character normalized ** XCenter, YCenter center point for normalization ** XScale, YScale scale factors for normalization ** Globals: none ** Operation: This routine normalizes each point in Outline by ** translating it to the specified center and scaling it ** anisotropically according to the given scale factors. ** Return: none ** Exceptions: none ** History: Fri Dec 14 10:27:11 1990, DSJ, Created. */ MFOUTLINE First, Current; MFEDGEPT *CurrentPoint; if (Outline == NIL) return; First = Outline; Current = First; do { CurrentPoint = PointAt (Current); CurrentPoint->Point.x = (CurrentPoint->Point.x - XCenter) * XScale; CurrentPoint->Point.y = (CurrentPoint->Point.y - YCenter) * YScale; Current = NextPointAfter (Current); } while (Current != First); } /* CharNormalizeOutline */ /*---------------------------------------------------------------------------*/ void ComputeDirection(MFEDGEPT *Start, MFEDGEPT *Finish, FLOAT32 MinSlope, FLOAT32 MaxSlope) { /* ** Parameters: ** Start starting point to compute direction from ** Finish finishing point to compute direction to ** MinSlope slope below which lines are horizontal ** MaxSlope slope above which lines are vertical ** Globals: none ** Operation: ** This routine computes the slope from Start to Finish and ** and then computes the approximate direction of the line ** segment from Start to Finish. The direction is quantized ** into 8 buckets: ** N, S, E, W, NE, NW, SE, SW ** Both the slope and the direction are then stored into ** the appropriate fields of the Start edge point. The ** direction is also stored into the PreviousDirection field ** of the Finish edge point. ** Return: none ** Exceptions: none ** History: 7/25/89, DSJ, Created. */ FVECTOR Delta; Delta.x = Finish->Point.x - Start->Point.x; Delta.y = Finish->Point.y - Start->Point.y; if (Delta.x == 0) if (Delta.y < 0) { Start->Slope = -MAX_FLOAT32; Start->Direction = south; } else { Start->Slope = MAX_FLOAT32; Start->Direction = north; } else { Start->Slope = Delta.y / Delta.x; if (Delta.x > 0) if (Delta.y > 0) if (Start->Slope > MinSlope) if (Start->Slope < MaxSlope) Start->Direction = northeast; else Start->Direction = north; else Start->Direction = east; else if (Start->Slope < -MinSlope) if (Start->Slope > -MaxSlope) Start->Direction = southeast; else Start->Direction = south; else Start->Direction = east; else if (Delta.y > 0) if (Start->Slope < -MinSlope) if (Start->Slope > -MaxSlope) Start->Direction = northwest; else Start->Direction = north; else Start->Direction = west; else if (Start->Slope > MinSlope) if (Start->Slope < MaxSlope) Start->Direction = southwest; else Start->Direction = south; else Start->Direction = west; } Finish->PreviousDirection = Start->Direction; } /* ComputeDirection */ /*---------------------------------------------------------------------------*/ void FinishOutlineStats(register OUTLINE_STATS *OutlineStats) { /* ** Parameters: ** OutlineStats statistics about a set of outlines ** Globals: none ** Operation: Use the preliminary statistics accumulated in OutlineStats ** to compute the final statistics. ** (see Dan Johnson's Tesseract lab ** notebook #2, pgs. 74-78). ** Return: none ** Exceptions: none ** History: Fri Dec 14 10:13:36 1990, DSJ, Created. */ OutlineStats->x = 0.5 * OutlineStats->My / OutlineStats->L; OutlineStats->y = 0.5 * OutlineStats->Mx / OutlineStats->L; OutlineStats->Ix = (OutlineStats->Ix / 3.0 - OutlineStats->y * OutlineStats->Mx + OutlineStats->y * OutlineStats->y * OutlineStats->L); OutlineStats->Iy = (OutlineStats->Iy / 3.0 - OutlineStats->x * OutlineStats->My + OutlineStats->x * OutlineStats->x * OutlineStats->L); /* Ix and/or Iy could possibly be negative due to roundoff error */ if (OutlineStats->Ix < 0.0) OutlineStats->Ix = MIN_INERTIA; if (OutlineStats->Iy < 0.0) OutlineStats->Iy = MIN_INERTIA; OutlineStats->Rx = sqrt (OutlineStats->Ix / OutlineStats->L); OutlineStats->Ry = sqrt (OutlineStats->Iy / OutlineStats->L); OutlineStats->Mx *= 0.5; OutlineStats->My *= 0.5; } /* FinishOutlineStats */ /*---------------------------------------------------------------------------*/ void InitOutlineStats(OUTLINE_STATS *OutlineStats) { /* ** Parameters: ** OutlineStats stats data structure to be initialized ** Globals: none ** Operation: Initialize the outline statistics data structure so ** that it is ready to start accumulating statistics. ** Return: none ** Exceptions: none ** History: Fri Dec 14 08:55:22 1990, DSJ, Created. */ OutlineStats->Mx = 0.0; OutlineStats->My = 0.0; OutlineStats->L = 0.0; OutlineStats->x = 0.0; OutlineStats->y = 0.0; OutlineStats->Ix = 0.0; OutlineStats->Iy = 0.0; OutlineStats->Rx = 0.0; OutlineStats->Ry = 0.0; } /* InitOutlineStats */ /*---------------------------------------------------------------------------*/ MFOUTLINE NextDirectionChange(MFOUTLINE EdgePoint) { /* ** Parameters: ** EdgePoint start search from this point ** Globals: none ** Operation: ** This routine returns the next point in the micro-feature ** outline that has a direction different than EdgePoint. The ** routine assumes that the outline being searched is not a ** degenerate outline (i.e. it must have 2 or more edge points). ** Return: Point of next direction change in micro-feature outline. ** Exceptions: none ** History: 7/25/89, DSJ, Created. */ DIRECTION InitialDirection; InitialDirection = PointAt (EdgePoint)->Direction; do EdgePoint = NextPointAfter (EdgePoint); while (PointAt (EdgePoint)->Direction == InitialDirection); return (EdgePoint); } /* NextDirectionChange */ /*---------------------------------------------------------------------------*/ void UpdateOutlineStats(register OUTLINE_STATS *OutlineStats, register FLOAT32 x1, register FLOAT32 x2, register FLOAT32 y1, register FLOAT32 y2) { /* ** Parameters: ** OutlineStats statistics to add this segment to ** x1, y1, x2, y2 segment to be added to statistics ** Globals: none ** Operation: This routine adds the statistics for the specified ** line segment to OutlineStats. The statistics that are ** kept are: ** sum of length of all segments ** sum of 2*Mx for all segments ** sum of 2*My for all segments ** sum of 2*Mx*(y1+y2) - L*y1*y2 for all segments ** sum of 2*My*(x1+x2) - L*x1*x2 for all segments ** These numbers, once collected can later be used to easily ** compute the center of mass, first and second moments, ** and radii of gyration. (see Dan Johnson's Tesseract lab ** notebook #2, pgs. 74-78). ** Return: none ** Exceptions: none ** History: Fri Dec 14 08:59:17 1990, DSJ, Created. */ register FLOAT64 L; register FLOAT64 Mx2; register FLOAT64 My2; /* compute length of segment */ L = sqrt ((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1)); OutlineStats->L += L; /* compute 2Mx and 2My components */ Mx2 = L * (y1 + y2); My2 = L * (x1 + x2); OutlineStats->Mx += Mx2; OutlineStats->My += My2; /* compute second moment component */ OutlineStats->Ix += Mx2 * (y1 + y2) - L * y1 * y2; OutlineStats->Iy += My2 * (x1 + x2) - L * x1 * x2; } /* UpdateOutlineStats */
3928eb77c278b8d8ecd694d8572f0fac20abe7b8
606d9876af16153b24a79714b9a8b078633c991b
/3rdparty/mylib/TextureUtil.h
9aecbb9448b3604ab504fb9a090cd095913dcb03
[]
no_license
cntlb/Opengl-linux
7c4355f10d33271019c263477a022c8c4c6e2369
2743388939846d2b4c9a082a55ef6f5c466ff280
refs/heads/master
2021-01-25T13:25:23.840707
2018-03-14T11:01:18
2018-03-14T11:01:18
123,571,974
0
0
null
null
null
null
UTF-8
C++
false
false
1,534
h
// // Created by jmu on 18-3-9. // #ifndef INC_2_4_TEXTURE_TEXTURE_H #define INC_2_4_TEXTURE_TEXTURE_H #include "common.h" #define LOG_TAG "TextureUtil.h" class TextureUtil{ public: static GLuint load(const char* path, void (*texParamFunc)()=TextureUtil::texFunc){ GLuint texture; glGenTextures(1, &texture); glBindTexture(GL_TEXTURE_2D, texture); int w,h,channels; std::string pathName = std::string("../res/")+std::string(path); stbi_uc* image = stbi_load(pathName.c_str(), &w, &h, &channels, 0); GLint format; if(channels == 1){ format = GL_RED; }else if(channels == 3){ format = GL_RGB; }else if(channels == 4){ format = GL_RGBA; } if(image){ glTexImage2D(GL_TEXTURE_2D, 0, format, w, h, 0, format, GL_UNSIGNED_BYTE, image); glGenerateMipmap(GL_TEXTURE_2D); texParamFunc(); stbi_image_free(image); }else{ LOGE("load texture error! file: %s", pathName.c_str()); stbi_image_free(image); } return texture; } private: static void texFunc(){ glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); } }; #endif //INC_2_4_TEXTURE_TEXTURE_H
14a55e7680b9ea8f28a7d925049089d87171111a
e07e3f41c9774c9684c4700a9772712bf6ac3533
/app/Temp/StagingArea/Data/il2cppOutput/mscorlib_System_Collections_Generic_Dictionary_2_T2874325086.h
ada49fe52b40246ad6a1db2105b77f055e8f04f4
[]
no_license
gdesmarais-gsn/inprocess-mobile-skill-client
0171a0d4aaed13dbbc9cca248aec646ec5020025
2499d8ab5149a306001995064852353c33208fc3
refs/heads/master
2020-12-03T09:22:52.530033
2017-06-27T22:08:38
2017-06-27T22:08:38
95,603,544
0
0
null
null
null
null
UTF-8
C++
false
false
974
h
#pragma once #include "il2cpp-config.h" #ifndef _MSC_VER # include <alloca.h> #else # include <malloc.h> #endif #include <stdint.h> // System.Object struct Il2CppObject; // System.IAsyncResult struct IAsyncResult_t1999651008; // System.AsyncCallback struct AsyncCallback_t163412349; #include "mscorlib_System_MulticastDelegate3201952435.h" #include "mscorlib_System_Collections_DictionaryEntry3048875398.h" #include "Json_NET_Newtonsoft_Json_Serialization_DefaultSeri3055062677.h" #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Winvalid-offsetof" #pragma clang diagnostic ignored "-Wunused-variable" #endif // System.Collections.Generic.Dictionary`2/Transform`1<Newtonsoft.Json.Serialization.DefaultSerializationBinder/TypeNameKey,System.Object,System.Collections.DictionaryEntry> struct Transform_1_t2874325086 : public MulticastDelegate_t3201952435 { public: public: }; #ifdef __clang__ #pragma clang diagnostic pop #endif
bd9d7f247a7d597761f1ebafce2893606c1142e5
4c4135fcb4d33344b5904642e26ebe9393253c64
/charactersheetwriter.cpp
a0149aa75666c00dc3a5e0da356854b83c19e243
[]
no_license
mzawislak94/DnDCharacterCreator
131e64d50dac785817a974cf9fa2a68d09d12ef1
d25a3df2735ac007721e511b932e07adba6c10d7
refs/heads/master
2020-04-13T02:50:52.641551
2018-12-23T18:12:33
2018-12-23T18:12:33
162,913,416
0
0
null
null
null
null
UTF-8
C++
false
false
379
cpp
#include "charactersheetwriter.h" charactersheetwriter::charactersheetwriter() { } void charactersheetwriter::writeToFile(QFile *file, QStringList options) { if (NULL != file->open(QIODevice::Append)) { QTextStream out(file); for (int i = 0; i < options.length(); i++) { out << options[i]; } file->close(); } }
4c7e07e9ac5824873d6d278a22c30a51c94db70f
6a11d2e56eda699ff63e56ac87d69934cd48740c
/mstl_eat.hpp
c78b0b9cf87264acd6ddb5363b825e4298722807
[]
no_license
halsten/my-toolkit
727152c9aa480a3d989ac97cc29849555d9db54d
4d37e920ed66f045f2866c98549617de4d9817d3
refs/heads/master
2023-03-26T01:33:45.513547
2017-07-16T14:40:46
2017-07-16T14:40:46
351,218,795
2
0
null
null
null
null
UTF-8
C++
false
false
2,615
hpp
#pragma once #include "mstl_image_dir.hpp" /* @Address - pointer to function pointer @hash_t - djb2 hash of name */ using export_t = std::pair<Address, hash_t>; using exports_t = std::vector<export_t>; class EAT : public IMAGE_DIR<IMAGE_DIRECTORY_ENTRY_EXPORT> { private: exports_t m_exports; public: __forceinline EAT() : IMAGE_DIR{}, m_exports{} {} __forceinline ~EAT() {} EAT(Address image_base): IMAGE_DIR<IMAGE_DIRECTORY_ENTRY_EXPORT>(image_base) { // sometimes there are no imports or exports for a module.. if(m_ptr) init(image_base); } __forceinline void init(uintptr_t image_base) { IMAGE_EXPORT_DIRECTORY *ed; uint32_t *names, *fn_ptrs; uint16_t *name_ordinals; // get export directory ed = as<IMAGE_EXPORT_DIRECTORY*>(); // first see if there are any exports if (ed->NumberOfFunctions == 0 || ed->NumberOfNames == 0) return; // get arrays from rva names = RVA<uint32_t*>(image_base, ed->AddressOfNames); fn_ptrs = RVA<uint32_t*>(image_base, ed->AddressOfFunctions); name_ordinals = RVA<uint16_t*>(image_base, ed->AddressOfNameOrdinals); // check if ( names == nullptr || fn_ptrs == nullptr || name_ordinals == nullptr) return; // stuff for (size_t i{}; i < ed->NumberOfNames; ++i) { m_exports.push_back( export_t{ RVA(image_base, fn_ptrs[name_ordinals[i]]), hash::djb2(RVA<const char*>(image_base, names[i])) }); } } __forceinline exports_t& get_exports() { return m_exports; } __forceinline bool get_export(hash_t export_hash, export_t& out) { auto needle = std::find_if( m_exports.begin(), m_exports.end(), [ & ](const export_t& it) { return it.second == export_hash; }); if (needle >= m_exports.end()) return false; out = *needle; return true; } __forceinline void hook_method(hash_t method_hash, Address hook) { export_t ret; if (!get_export(method_hash, ret)) return; return ret.first.set(hook); } template<typename _T = Address> __forceinline _T get_method(hash_t method_hash) { export_t ret; if (!get_export(method_hash, ret)) return _T{}; return ret.first.as<_T>(); } };
a4794f52e99d698050bccd1e49588ae5e515ee94
e5cd80fd89480cbc27a177b9608ec93359cca5f8
/672.cpp
07caad7963df1c2d034639b114122854b9577e0d
[]
no_license
higsyuhing/leetcode_middle
c5db8dd2e64f1b0a879b54dbd140117a8616c973
405c4fabd82ed1188d89851b4df35b28c5cb0fa6
refs/heads/master
2023-01-28T20:40:52.865658
2023-01-12T06:15:28
2023-01-12T06:15:28
139,873,993
0
0
null
null
null
null
UTF-8
C++
false
false
351
cpp
class Solution { public: int flipLights(int n, int m) { // first 3 generates 4 state, the last one has 2 states.. n = (n > 3) ? 3 : n; if (m == 0) return 1; if (m == 1) return n == 1 ? 2 : n == 2 ? 3 : 4; if (m == 2) return n == 1 ? 2 : n == 2 ? 4 : 7; return n == 1 ? 2 : n == 2 ? 4 : 8; } };
393172f3df8ccfb8630ffa3220d37dae81d2c57c
77ff0d5fe2ec8057f465a3dd874d36c31e20b889
/problems/POJ/POJ3273.cpp
6d6f177b5e614849f9a99784553332f13f4de290
[]
no_license
kei1107/algorithm
cc4ff5fe6bc52ccb037966fae5af00c789b217cc
ddf5911d6678d8b110d42957f15852bcd8fef30c
refs/heads/master
2021-11-23T08:34:48.672024
2021-11-06T13:33:29
2021-11-06T13:33:29
105,986,370
2
1
null
null
null
null
UTF-8
C++
false
false
1,825
cpp
#include <cstdio> #include <cstdlib> #include <cmath> #include <climits> #include <cfloat> #include <map> #include <utility> #include <set> #include <bitset> #include <iostream> #include <memory> #include <string> #include <vector> #include <list> #include <numeric> #include <algorithm> #include <functional> #include <sstream> #include <complex> #include <stack> #include <queue> #include <deque> using namespace std; typedef long long ll; typedef pair<int, int> pii; typedef pair<ll, ll> pll; #define INF 1<<30 #define LINF 1LL<<60 /* <url:http://poj.org/problem?id=3273> 問題文============================================================ 要素数Nの数列{a_i}が与えられる. この数列をM個の連続した部分に分け,各部分の要素の合計の最大値を最小化したい. ================================================================= 解説============================================================= 合計の最大値についてにぶたんすれば良い 最大値をmと定めた時、合計がm以下となるような部分列の個数がM以下かどうかで判定 ================================================================ */ ll N,M; vector<ll> S; bool ok(ll m){ ll Sum = 0; ll cnt = 1; for(int i = 0; i < N;i++){ if(Sum + S[i] <= m){ Sum += S[i]; }else{ cnt++; Sum = S[i]; } } return cnt <= M; } int main(void) { cin.tie(0); ios::sync_with_stdio(false); cin >> N >> M; S.resize(N); ll l = 0, r = LINF; for(int i = 0; i < N;i++){ cin >> S[i]; l = max(l,S[i]); } l--; while(r - l > 1){ ll m = (l+r)/2; if(ok(m)){ r = m; }else{ l = m ; } } cout << r << endl; return 0; }
5b573fdcfe5cbdfffcb07574c1225c2ed774ee35
92640ec261e7875a5e65e95d6408be2df3cdd9a3
/temp/1148.cpp
b9991a863a1a255ad37592b1d7cdfcf02401bf7d
[]
no_license
gaolichen/contest
c20c79d1a05ea6c015329bc2068a3bbb946de775
4ac5112f150210c6345312922dc96494327cbf55
refs/heads/master
2021-01-19T04:45:59.100014
2017-04-06T06:46:09
2017-04-06T06:46:09
87,392,728
0
0
null
null
null
null
UTF-8
C++
false
false
2,047
cpp
#include<stdio.h> #include<string.h> char map[80][80]; int mark[80][80],dis[80][80],w,h; int sx,sy,ex,ey; void run() { int i,j,find,k; for(i=0;i<=w+1;i++) for(j=0;j<=h+1;j++) mark[i][j]=0; mark[sx][sy]=1;dis[sx][sy]=0; do { find=0; for(i=0;i<=w+1;i++) for(j=0;j<=h+1;j++) if(mark[i][j]) { for(k=i+1;k<=w+1;k++) { if(map[k][j]!=' '&&(k!=ex||j!=ey)) break; if(!mark[k][j]) { dis[k][j]=dis[i][j]+1; if(!find)find=1; if(k==ex&&j==ey) { printf("%d segments.\n",dis[k][j]); return; } mark[k][j]=1; } } for(k=j+1;k<=h+1;k++) { if(map[i][k]!=' '&&(i!=ex||k!=ey)) break; if(!mark[i][k]) { dis[i][k]=dis[i][j]+1; if(!find)find=1; if(i==ex&&k==ey) { printf("%d segments.\n",dis[i][k]); return; } mark[i][k]=1; } } for(k=i-1;k>=0;k--) { if(map[k][j]!=' '&&(k!=ex||j!=ey)) break; if(!mark[k][j]) { dis[k][j]=dis[i][j]+1; if(!find)find=1; if(k==ex&&j==ey) { printf("%d segments.\n",dis[k][j]); return; } mark[k][j]=1; } } for(k=j-1;k>=0;k--) { if(map[i][k]!=' '&&(i!=ex||k!=ey)) break; if(!mark[i][k]) { dis[i][k]=dis[i][j]+1; if(!find)find=1; if(i==ex&&k==ey) { printf("%d segments.\n",dis[i][k]); return; } mark[i][k]=1; } } } }while(find); printf("impossible.\n"); } void main() { int i,j,count=0,tot=0; char ch; scanf("%d%d",&w,&h); while(w&&h) { ch=getchar(); memset(map,' ',sizeof(map)); for(i=1;i<=h;i++) { while(ch=='\n')ch=getchar(); for(j=1;j<=w;j++) { map[j][i]=ch; ch=getchar(); } } count=0; scanf("%d%d%d%d",&sx,&sy,&ex,&ey); while(sx||sy||ex||ey) { if(!count) printf("Board #%d:\n",++tot); printf("Pair %d: ",++count); run(); scanf("%d%d%d%d",&sx,&sy,&ex,&ey); } putchar('\n'); scanf("%d%d",&w,&h); } }
0f75945ecc44ba757c0b02fde9a256fd522858d5
a8822501e1a017273abb4638328d7b2be1088baf
/WapMap/states/imageDetails.h
f2896560368f86a25f8376fa3c6e2552c64470ca
[]
no_license
pejti/WapMap
b05748cda08d0c76603bbe28dc2f4f2f3d3e5209
19a5d56ff24cae1279e414568bd564ae661b3a44
refs/heads/master
2020-12-23T09:50:09.173873
2020-01-31T21:15:34
2020-01-31T21:15:34
237,115,263
0
0
null
2020-01-30T01:12:31
2020-01-30T01:12:31
null
UTF-8
C++
false
false
1,329
h
#ifndef H_STATE_IMGDETAILS #define H_STATE_IMGDETAILS #include "../../shared/cStateMgr.h" #include "../../shared/gcnWidgets/wWin.h" #include "../../shared/gcnWidgets/wButton.h" #include "../../shared/gcnWidgets/wLabel.h" #include "../../shared/gcnWidgets/wScrollArea.h" #include "../../shared/gcnWidgets/wSlider.h" #include "guichan.hpp" #include "../wViewport.h" class cImage; namespace State { class ImageDetails : public SHR::cState, public gcn::ActionListener, public WIDG::VpCallback/*, public gcn::ListModel*/ { public: ImageDetails(cImage *phImage); ~ImageDetails(); virtual bool Opaque(); virtual void Init(); virtual void Destroy(); virtual bool Think(); virtual bool Render(); virtual void GainFocus(int iReturnCode, bool bFlipped); void action(const gcn::ActionEvent &actionEvent); virtual void Draw(int piCode); private: gcn::Gui *gui; SHR::Win *myWin; SHR::ScrollArea *saPreview; SHR::Contener *conPreview; SHR::But *butReturn; SHR::Slider *sliZoom; float fZoomMod; WIDG::Viewport *vpOverlay; cImage *hImage; //virtual std::string getElementAt(int i); //virtual int getNumberOfElements(); }; }; #endif
04ee77bd12b2b7e85595cc5bc4c9862a6a2e1eaf
212380b8070b2f4b9a2ee9db88d8ef71301f500b
/Number.cpp
e5378c72dec1a0e8fd3e011ad9ebbba87e746b17
[]
no_license
SeanTo/My3D
379976f02434100dcb5e7cf37b06eca1fc20e60c
b2e13e7582d072b70574b5630ae6f1abbda6423d
refs/heads/master
2020-04-16T11:33:00.343386
2019-01-14T17:36:22
2019-01-14T17:36:22
165,540,600
0
0
null
null
null
null
GB18030
C++
false
false
7,265
cpp
#include "stdafx.h" #include "Number.h" //////////////////////////////////////////////////////////////////////////////// // static member // 奇偶、大小、质合形态 const CString C3D::strModality[3][8] = { { _T("偶偶偶"), _T("偶偶奇"), _T("偶奇偶"), _T("偶奇奇"), _T("奇偶偶"), _T("奇偶奇"), _T("奇奇偶"), _T("奇奇奇") }, { _T("小小小"), _T("小小大"), _T("小大小"), _T("小大大"), _T("大小小"), _T("大小大"), _T("大大小"), _T("大大大") }, { _T("合合合"), _T("合合质"), _T("合质合"), _T("合质质"), _T("质合合"), _T("质合质"), _T("质质合"), _T("质质质") } }; // 012 路 const CString C3D::str012[27] = { _T("000"), _T("001"), _T("002"), _T("010"), _T("011"), _T("012"), _T("020"), _T("021"), _T("022"), _T("100"), _T("101"), _T("102"), _T("110"), _T("111"), _T("112"), _T("120"), _T("121"), _T("122"), _T("200"), _T("201"), _T("202"), _T("210"), _T("211"), _T("212"), _T("220"), _T("221"), _T("222") }; //////////////////////////////////////////////////////////////////////////////// // implementation /* * 返回数字 n 在号码中出现的位置,未找到返回 -1 */ int C3D::Find(int n, int st/* =0 */) const { IS_ONE(n); IS_INDEX(st); for(int i = st; i < 3; ++i) { if( GetAt(i) == n ) return i; } return -1; } /* * 两码差:百位、十位、个位 */ void C3D::Swing(const C3D &obj, int *pSwing) const { pSwing[0] = Hun() - obj.Hun(); // 百位 pSwing[1] = Ten() - obj.Ten(); // 十位 pSwing[2] = Ent() - obj.Ent(); // 个位 } /* * 邻码判断 */ BOOL C3D::IsNeighbor(int n) const { ASSERT(0 <= n && n <= 9); if( IsMember(n) ) return FALSE; for(int i = 0; i < 3; ++i) { if( 1 == abs(n - GetAt(i)) || 9 == abs(n - GetAt(i))) return TRUE; } return FALSE; } /* * 给定两码是否在当前号码中 */ BOOL C3D::IsMember2(int iTwo, BOOL bOrder/* = TRUE*/) const { ASSERT( 0 <= iTwo && iTwo <= 99); int n1 = iTwo / 10 % 10; int n2 = iTwo % 10; if( Hun()==n1 && (Ten()==n2 || Ent()==n2) || Ten()==n1 && Ent()==n2 ) return TRUE; if( bOrder ) return FALSE; else n1 ^= n2 ^= n1 ^= n2; return Hun()==n1 && (Ten()==n2 || Ent()==n2) || Ten()==n1 && Ent()==n2; } /* * 号码在 str 中出现的次数 */ int C3D::CountInStr(const CString &str, BOOL bOnce /* = FALSE */) const { if( IsG1() ) return !EMFC::IsInArray(Hun(), str) ? 0 : (bOnce ? 1 : 3); int cnt = 0; for(int i = 0; i < 3; ++i) cnt += EMFC::IsInArray(GetAt(i), str); if( bOnce && IsG3() ) { if(3 == cnt) cnt = 2; else cnt -= EMFC::IsInArray(Same(), str); } return cnt; } //////////////////////////////////////////////////////////////////////////////// // static method /* * 排除两码 */ int C3D::ExcludeTwo(CUIntArray &arr, BOOL bOrder /* = TRUE */) { EMFC::ExcludeSame(arr); if( !bOrder ) { UINT n; int i = arr.GetSize() - 1; while( i > 0 ) { n = (arr[i] % 10) * 10 + arr[i] / 10 % 10; if( EMFC::IsInArray(n, arr, i) ) arr.RemoveAt(i); --i; } } return arr.GetSize(); } /* * 字符串转和值(两码)数组 */ int C3D::Str2Sum(const CString &str, CUIntArray &arrSum, BOOL bConti /* = TRUE */, int iMax /* = 27 */) { arrSum.RemoveAll(); if(str.IsEmpty()) return 0; CString st(str); st.TrimLeft(); st.TrimRight(); // 删除尾部非数字字符 while( !st.IsEmpty() && !_istdigit(st.GetAt(st.GetLength() - 1)) ) st.Delete(st.GetLength() - 1); CString sDigit = _T("0123456789"); if(0 == st.GetLength() || -1 == st.FindOneOf(sDigit)) return 0; int iDigit = 0, iSepar = 0; int i = 0; int n = 0; int num = iMax + 1; BOOL bContinue = FALSE; CString ss; while( 0 < st.GetLength() ) { // 查找下一个数字 iDigit = st.FindOneOf(sDigit); if(-1 != iDigit) { st = st.Mid(iDigit); // 从第一个数字截取到尾部 ss = st.SpanIncluding(sDigit); // 截取头部数字串 st = st.Mid(ss.GetLength()); ss = ss.Left(2); num = _ttoi(ss); if(iMax >= num && ! EMFC::IsInArray((UINT)num, arrSum)) { n = arrSum.GetSize(); if(!bContinue || 0 == n) { arrSum.Add(num); } else { if((UINT)num > arrSum[n - 1]) { for(int i = arrSum[n - 1] + 1; i <= num; ++i) arrSum.Add(i); } else arrSum.Add(num); bContinue = FALSE; } } st.TrimLeft(); if(bConti) { if(0 < st.GetLength() && st.GetAt(0) == _T('-')) { bContinue = TRUE; } } } } if(n > 0) EMFC::SortArray(arrSum); return arrSum.GetSize(); } /* * 和值(两码)数组转字符串 */ CString C3D::Sum2Str(const CUIntArray &arrSum, BOOL bTwo /* = FALSE */, BOOL bConti /* = TRUE */) { CString str = _T(""); const int len = arrSum.GetSize(); if(0 == len) return str; CString sFmt = bTwo ? _T("%02d") : _T("%d"); CString ss; ss.Format(sFmt, arrSum[0]); str += ss; for(int i = 1, k = 0; i < len; ++i) { k = 0; if(bConti) { while(i + k < len) { if( arrSum[i + k] == arrSum[i + k -1] + 1 ) ++k; else break; } } else k = 0; if(0 == k) { sFmt = bTwo ? _T(",%02d") : _T(",%d"); ss.Format(sFmt, arrSum[i]); str += ss; } else { sFmt = bTwo ? _T(",%02d") : _T("-%d"); ss.Format(sFmt, arrSum[i + k - 1]); str += ss; i += k - 1; k = 0; } } return str; } /* * 字符串转数组 */ int C3D::Str2Array(const CString &str, CUIntArray &arr, BOOL bSort/* = TRUE*/) { arr.RemoveAll(); int len = str.GetLength(); if(0 == len) return 0; int B[3], j = 0, num; for(int i = 0; i < len && arr.GetSize() < 1000; ++i) { if(_istdigit(str.GetAt(i))) B[j++] = str.GetAt(i) - _T('0'); if(3 == j) { j = 0; num = B[0] * 100 + B[1] * 10 + B[2]; if( !EMFC::IsInArray((UINT)num, arr) ) arr.Add(num); } } j = arr.GetSize(); if(j > 1 && bSort) EMFC::SortArray(arr); return j; } /* * 数组转字符串 */ CString& C3D::Array2Str(const CUIntArray &arr, CString &str, const CString &sFmt /* = _T("%03d ") */) { str.Empty(); CString ss = _T(""); int cnt = arr.GetSize(); for(int i = 0; i < cnt; ++i) { ss.Format(sFmt, arr[i]); str += ss; } return str; } /* * 单转组 */ int C3D::S2G(CUIntArray &arr) { C3D CNum; int i = 0; while(i < arr.GetSize() ) { CNum = arr[i]; arr[i] = CNum.Min() * 100 + CNum.Mid() * 10 + CNum.Max(); if( EMFC::IsInArray(arr[i], arr, i) ) arr.RemoveAt(i); else ++i; } EMFC::SortArray(arr); return arr.GetSize(); } /* * 组转单 */ int C3D::G2S(CUIntArray &arr) { C3D CNum; int A[3], B[6]; int i = 0; while(i < arr.GetSize() ) { CNum = arr[i]; A[0] = CNum.Min(); A[1] = CNum.Mid(); A[2] = CNum.Max(); B[0] = A[0] * 100 + A[1] * 10 + A[2]; B[1] = A[0] * 100 + A[2] * 10 + A[1]; B[2] = A[1] * 100 + A[0] * 10 + A[2]; B[3] = A[1] * 100 + A[2] * 10 + A[0]; B[4] = A[2] * 100 + A[0] * 10 + A[1]; B[5] = A[2] * 100 + A[1] * 10 + A[0]; for(int j = 0; j < 6; ++j) { if( !EMFC::IsInArray((UINT)B[j], arr, i) ) { arr.InsertAt(0, B[j]); ++i; } } arr.RemoveAt(i); } EMFC::SortArray(arr); return arr.GetSize(); } ////////////////////////////////////////////////////////////////////////////////
f01eeb55ff44d8aef19ea697fa75fc8f5cec10ea
3ded37602d6d303e61bff401b2682f5c2b52928c
/ml/030/Classes/scenes/FavScene.h
4749b0ce50b538a9405ae51578d131bf057caece
[]
no_license
CristinaBaby/Demo_CC
8ce532dcf016f21b442d8b05173a7d20c03d337e
6f6a7ff132e93271b8952b8da6884c3634f5cb59
refs/heads/master
2021-05-02T14:58:52.900119
2018-02-09T11:48:02
2018-02-09T11:48:02
120,727,659
0
0
null
null
null
null
UTF-8
C++
false
false
432
h
// // FavScene.h // OreoMaker // // Created by wusonglin1 on 14-10-24. // // #ifndef __OreoMaker__FavScene__ #define __OreoMaker__FavScene__ #include <iostream> #include "cocos2d.h" #include "../Depends/base/BaseScene.h" USING_NS_CC; class FavScene: public BaseScene{ private: FavScene(); virtual ~FavScene(); public: virtual bool init(); CREATE_FUNC(FavScene); }; #endif /* defined(__OreoMaker__FavScene__) */
617aed85fb927cfe96710d1be9cfc6c9614e509b
09b37a937dba38b8dfd21e07066aa9485c15de7c
/overtimeinspection.cpp
1e4a0eedaff7bd2e95a0a748af66e662877a90b6
[]
no_license
Juncc19/LMS
68e069bb3fadab4834122d6bdfebaf1a367937f5
55128c8065d16fe6350a9419151f604ff55ff6ee
refs/heads/master
2022-11-12T02:55:13.043557
2020-06-22T08:06:55
2020-06-22T08:06:55
270,684,118
1
0
null
2020-06-22T06:12:03
2020-06-08T13:43:38
C++
UTF-8
C++
false
false
3,067
cpp
#include "overtimeinspection.h" overtimeInspection::overtimeInspection(QObject *parent) : QObject(parent) { recordModel=new QSqlTableModel(this); recordModel->setTable("record"); overtimeRecordModel=new QSqlTableModel(this); overtimeRecordModel->setTable("overtimeRecord"); overtimeCheck(); timer = new QTimer(this); timer->setSingleShot(1); timer->setTimerType(Qt::PreciseTimer); connect(timer,&QTimer::timeout,this,&overtimeInspection::repeatCheck); int msec=QTime::currentTime().msec(); //time calibration timer->start(24*3600*1000+2000-msec); //execute at around 0:00:02 } void overtimeInspection::repeatCheck() { overtimeCheck(); delete timer; //create a new timer timer = new QTimer(this); timer->setSingleShot(1); timer->setTimerType(Qt::PreciseTimer); connect(timer,&QTimer::timeout,this,&overtimeInspection::repeatCheck); //check repeatly int msec=QTime::currentTime().msec(); //time calibration timer->start(24*3600*1000+2000-msec); //execute at around 0:00:02 } void overtimeInspection::overtimeCheck() { QString currentDate=QDate::currentDate().toString(); recordModel->setFilter("recordState = 0"); recordModel->select(); recordModel->setSort(8,Qt::AscendingOrder); //select the nearest returnDate recordModel->select(); if(recordModel->rowCount()==0) return; //compare the returnDate with current date int cnt=0; while(recordModel->record(cnt).value(8).toString()<=currentDate) { recordModel->setData(recordModel->index(cnt,9),1); if(!recordModel->submitAll()) { qCritical().noquote() << QString("Overtime-check:record failed"); return; } QSqlRecord recordRecord = recordModel->record(cnt); //add an overtime-record int row=overtimeRecordModel->rowCount(); QSqlRecord overtimerecordRecord = overtimeRecordModel->record(); overtimerecordRecord.setValue("bookId",recordRecord.value("bookId")); overtimerecordRecord.setValue("bookName",recordRecord.value("bookName")); overtimerecordRecord.setValue("author",recordRecord.value("author")); overtimerecordRecord.setValue("genre",recordRecord.value("genre")); overtimerecordRecord.setValue("userId",recordRecord.value("userId")); overtimerecordRecord.setValue("userName",recordRecord.value("userName")); overtimerecordRecord.setValue("borrowDate",recordRecord.value("borrowDate")); overtimerecordRecord.setValue("returnDate",recordRecord.value("returnDate")); overtimeRecordModel->insertRecord(row,overtimerecordRecord); if(!overtimeRecordModel->submitAll()) { qCritical().noquote() << QString("Overtime-check:overtimeRecord failed"); return; } ++cnt; if(cnt==recordModel->rowCount()) break; //break the checking function if all of the record are already checked } }
0f99530316907bba4194a9922d48fabdd747e7ee
db19ea383c96b1a8605bb719efeeae688e2acdb1
/FirstClass/main.cpp
fd8145b751a0ecc091a6f7ff4ec7da094959191e
[]
no_license
Ryzempt/FirstClass
dcd7c577dbe31bf2fac86f9126a00bd67ad851f1
f00d0cb02046c30c25ee96def17dd6786af7b859
refs/heads/master
2020-04-18T08:16:30.599615
2019-01-24T15:31:04
2019-01-24T15:31:04
167,390,530
0
0
null
null
null
null
UTF-8
C++
false
false
272
cpp
// // main.cpp // FirstClass // // Created by Kaufman, Robert on 1/24/19. // Copyright © 2019 CTEC. All rights reserved. // #include <iostream> int main(int argc, const char * argv[]) { // insert code here... std::cout << "Hello, World!\n"; return 0; }
c165744a256746d0b13e866584d781e16bc4796d
55fc0e953ddd07963d290ed56ab25ff3646fe111
/StiGame/events/TableClickEventArgs.h
6d1ec525f85e79d47c97e5c2dfa0e904cf0c67cc
[ "MIT" ]
permissive
jordsti/stigame
71588674640a01fd37336238126fb4500f104f42
6ac0ae737667b1c77da3ef5007f5c4a3a080045a
refs/heads/master
2020-05-20T12:54:58.985367
2015-06-10T20:55:41
2015-06-10T20:55:41
22,086,407
12
3
null
null
null
null
UTF-8
C++
false
false
715
h
#ifndef TABLECLICKEVENTARGS_H #define TABLECLICKEVENTARGS_H namespace StiGame { namespace Gui { class Table; class TableRow; class TableCell; class TableClickEventArgs { public: TableClickEventArgs(int m_rowIndex, int m_columnIndex); TableClickEventArgs(Table *m_table, TableRow *m_row, TableCell *m_cell, int m_rowIndex, int m_columnIndex); virtual ~TableClickEventArgs(); TableRow* getRow(void); Table* getTable(void); TableCell* getCell(void); int getRowIndex(void); int getColumnIndex(void); bool isHeaderClicked(void); private: TableRow *row; TableCell *cell; Table *table; int rowIndex; int columnIndex; }; } } #endif // TABLECLICKEVENTARGS_H
843390bb822f5a19dbbf43b5ba31545e90771ada
0f051d3cfb4d06ad795624f84e711ddaa348e6a8
/mazeTraverse (1).ino
395d713dc6a338b6a3f6a4671c7c9d43942387c3
[]
no_license
Zinc-Gao/Group10_codes
c681829aa339bf7192c8d7568742743e51b5d707
f918640a5108d1fe0db67e0ee7b9b17bb1bff6f6
refs/heads/main
2023-01-18T21:32:53.541907
2020-11-20T12:16:33
2020-11-20T12:16:33
314,544,400
0
0
null
null
null
null
UTF-8
C++
false
false
8,351
ino
// Bluetooth initialisation #include <SoftwareSerial.h> //Software Serial Port #define RxD 7 #define TxD 6 #define ConnStatus A1 #define DEBUG_ENABLED 1 int shieldPairNumber = 17; String slaveNameCmd = "\r\n+STNA=Slave";\ SoftwareSerial blueToothSerial(RxD,TxD); // Servo initialisation #include <Servo.h> // Include servo library Servo servoLeft; // Declare left and right servos Servo servoRight; String path = ""; void setup() // Built-in initialization block { pinMode(10, INPUT); pinMode(9, OUTPUT); // Left IR LED & Receiver pinMode(3, INPUT); pinMode(2, OUTPUT); // Right IR LED & Receiver pinMode(5, INPUT); pinMode(4, OUTPUT); // Front IR LED & Receiver servoLeft.attach(13); // Attach left signal to pin 13 servoRight.attach(12); // Attach right signal to pin 12 Serial.begin(9600); blueToothSerial.begin(38400); // Set Bluetooth module to default baud rate 38400 pinMode(RxD, INPUT); pinMode(TxD, OUTPUT); pinMode(ConnStatus, INPUT); Serial.println("Checking Slave-Master connection status."); if (digitalRead(ConnStatus)==1) { Serial.println("Already connected to Master - remove USB cable if reboot of Master Bluetooth required."); } else { Serial.println("Not connected to Master."); setupBlueToothConnection(); // Set up the local (slave) Bluetooth module delay(1000); // Wait one second and flush the serial buffers Serial.flush(); blueToothSerial.flush(); } } void loop() { int irLeft = irDetect(9, 10, 38000); // Check for object on left int irRight = irDetect(2, 3, 40000); // Check for object on right int irFront = irDetect(4, 5, 27000); // Check for object in front // // print (Left, right, front) // Serial.print("("); Serial.print(irLeft); Serial.print(", "); // Serial.print(irRight); Serial.print(", "); // Serial.print(irFront); Serial.println(")"); // *************** Bluetooth ******************* // Check if there's any data sent from the remote Bluetooth shield if (blueToothSerial.available()) { char recvChar = blueToothSerial.read(); Serial.println(recvChar); if (recvChar == 'f') { moveTowards("front"); } else if (recvChar == 'l') { moveTowards("left"); } else if (recvChar == 'r') { moveTowards("right"); } else if (recvChar == 'b') { moveTowards("back"); } } // both left and right sides see the maze wall -> move foward if ((irLeft == 0) && (irRight == 0) && (irFront == 1)) { moveTowards("front"); } // dead end -> pick up ball and trace back to start else if ((irLeft == 0) && (irRight == 0) && (irFront == 0)) { // sent data from the local serial terminal String str = "find the ball"; for (int i = 0; i < sizeof(str) - 1; i++) { blueToothSerial.print(str[i]); } blueToothSerial.print('\n'); // Wait for 500 ms -> for picking up ball? toMove(0, 0, 500); // move backwards towards start int pathLength = sizeof(path) - 2; for (int i = pathLength; i >= 0; i--) { String direction = reverseOf(path[i]); moveTowards(direction); } // stop servo signal servoLeft.detach(); servoRight.detach(); } // front and left side sees the maze wall -> turn right else if ((irLeft == 0) && (irRight == 1) && (irFront == 0)) { moveTowards("right"); moveTowards("front"); } // front and right side sees the maze wall -> turn left else if ((irLeft == 1) && (irRight == 0) && (irFront == 0)) { moveTowards("left"); moveTowards("front"); } // only left side sees the maze wall -> choose right or front else if ((irLeft == 0) && (irRight == 1) && (irFront == 1)) { int choice = random(2); // choose from 0 or 1 // turn right if 0 if (choice == 0) { moveTowards("right"); moveTowards("front"); } // move forward if 1 if (choice == 1) { // move forward for 3000 ms (a block's distance) for (int i = 0; i < 6; i++) { moveTowards("front"); } } } // only right side sees the maze wall -> choose right or front else if ((irLeft == 1) && (irRight == 0) && (irFront == 1)) { int choice = random(2); // choose from 0 or 1 // turn left if 0 if (choice == 0) { moveTowards("left"); moveTowards("front"); } // move forward if 1 else if (choice == 1) { // move forward for 3000 ms (a block's distance) for (int i = 0; i < 6; i++) { moveTowards("front"); } } } // only front side sees the maze wall -> choose right or front else if ((irLeft == 1) && (irRight == 0) && (irFront == 1)){ int choice = random(2); // choose from 0 or 1 if (choice == 0) { // turn left if 0 moveTowards("left"); moveTowards("front"); } else if (choice == 1) { // turn right if 1 moveTowards("right"); moveTowards("front"); } } // no obstacle at any direction -> choose front, left or right else { int choice = random(3); // choose from 0 to 2 if (choice == 0) { // turn left if 0 moveTowards("left"); moveTowards("front"); } else if (choice == 1) { // turn right if 1 moveTowards("right"); moveTowards("front"); } else if (choice == 2) { // move forward if 2 for (int i = 0; i < 6; i++) { moveTowards("front"); } } } delay(100); } int irDetect(int irLedPin, int irReceiverPin, long frequency) { tone(irLedPin, frequency, 8); // turn on IR LED for 1 ms delay(1); int ir = digitalRead(irReceiverPin); // 1 if no detect, 0 detect delay(1); // Down time before recheck return ir; } // Backward Linear Stop Linear Forward // -200 -100 0 100 200 void toMove(int speedLeft, int speedRight, int duration) { // left wheel clockwise, right wheel anti-clockwise servoLeft.writeMicroseconds(1500 + speedLeft); // Set Left servo speed servoRight.writeMicroseconds(1500 - speedRight); // Set right servo speed delay(duration); // keep moving according to duration } void moveTowards(String direction) { if (direction.equals("front")) { toMove(-200, -200, 500); path += "f"; } else if (direction.equals("left")) { toMove(-200, 200, 775); path += "l"; } else if (direction.equals("right")) { toMove(200, -200, 775); path += "r"; } else if (direction.equals("back")) { toMove(200, 200, 20); path += "b"; } } String reverseOf(char direction) { if (direction == 'f') { return "back"; } if (direction == 'l') { return "right"; } if (direction == 'r') { return "left"; } if (direction == 'b') { return "front"; } } void setupBlueToothConnection() { Serial.println("Setting up the local (slave) Bluetooth module."); slaveNameCmd += shieldPairNumber; slaveNameCmd += "\r\n"; blueToothSerial.print("\r\n+STWMOD=0\r\n"); // Set the Bluetooth to work in slave mode blueToothSerial.print(slaveNameCmd); // Set the Bluetooth name using slaveNameCmd blueToothSerial.print("\r\n+STAUTO=0\r\n"); // Auto-connection should be forbidden here blueToothSerial.print("\r\n+STOAUT=1\r\n"); // Permit paired device to connect me blueToothSerial.flush(); delay(2000); // This delay is required blueToothSerial.print("\r\n+INQ=1\r\n"); // Make the slave Bluetooth inquirable blueToothSerial.flush(); delay(2000); // This delay is required Serial.println("The slave bluetooth is inquirable!"); }
bd77b26109c819eef2b8d0a74087297c1f092ddc
ab7a412d64cc2bf2b2446c0c770f31c50ceb6819
/BGE/SoundSystem.cpp
76d945d2d734495f6f64407144a1d1d038d61d61
[ "MIT" ]
permissive
PocketRocketRoche/GamesEngines1Assignment
856790e9f171cfa03b21e9f52cc16210de60a75f
2b402cb45387eb64f34c8a648fd68c3cd1df0118
refs/heads/master
2021-01-10T21:46:04.364814
2013-12-13T15:26:55
2013-12-13T15:26:55
13,859,413
0
0
MIT
2020-09-12T11:53:35
2013-10-25T12:02:33
C
UTF-8
C++
false
false
2,958
cpp
#include "SoundSystem.h" #include <fmod.hpp> #include <fmod_errors.h> #include "Exception.h" #include "Content.h" #include "Utils.h" using namespace BGE; void CheckFMODResult( FMOD_RESULT res ) { if (res != FMOD_OK) { const char * error = FMOD_ErrorString(res); throw BGE::Exception(error); } } // Doesnt work... so dont call it void SoundSystem::Vibrate(int millis, float power) { SDL_Haptic *haptic; // Open the device SDL_Joystick * joy; joy = SDL_JoystickOpen(0); haptic = SDL_HapticOpenFromJoystick( joy ); if (haptic == NULL) { return; } if (SDL_HapticRumbleInit( haptic ) != 0) { return; } if (SDL_HapticRumblePlay( haptic, power, millis ) != 0) { return; } // Clean up SDL_JoystickClose(joy); SDL_HapticClose( haptic ); } SoundSystem::SoundSystem(void) { enabled = true; } SoundSystem::~SoundSystem(void) { } void SoundSystem::Initialise() { FMOD_SPEAKERMODE speakerMode; FMOD_CAPS caps; CheckFMODResult(FMOD::System_Create(& fmodSystem)); CheckFMODResult(fmodSystem->getDriverCaps(0, &caps, 0, &speakerMode)); CheckFMODResult(fmodSystem->setSpeakerMode(speakerMode)); CheckFMODResult(fmodSystem->init(1000, FMOD_INIT_NORMAL, 0)); } void SoundSystem::PlayHitSoundIfReady(GameComponent * object, int interval) { if (! enabled) { return; } long now = SDL_GetTicks(); // Has this object already played a sound? map<GameComponent *, SoundEvent>::iterator it = soundEvents.find(object); SoundEvent soundEvent; bool isPlaying = false; if (it != soundEvents.end()) { if (now - it->second.last > interval) { // Is the sound already playing? soundEvent = it->second; soundEvent.channel->isPlaying(& isPlaying); if (isPlaying) { return; } } else { // Its too soon to play this object's sound return; } } else { int which = rand() % NUM_HIT_SOUNDS; stringstream ss; ss << "Hit" << which; soundEvent.sound = Content::LoadSound(ss.str()); } fmodSystem->playSound(FMOD_CHANNEL_FREE, soundEvent.sound, false, & soundEvent.channel); if (soundEvent.channel != NULL) { if (isPlaying) { soundEvent.channel->set3DAttributes(& GLToFMODVector(object->position), & GLToFMODVector(glm::vec3(0))); } } soundEvent.last = now; soundEvents[object] = soundEvent; } void BGE::SoundSystem::Update() { if (! enabled) { return; } shared_ptr<Camera> camera = Game::Instance()->camera; fmodSystem->set3DListenerAttributes(0, & GLToFMODVector(camera->position) , & GLToFMODVector(glm::vec3(0)) , & GLToFMODVector(camera->look) , & GLToFMODVector(camera->up) ); fmodSystem->update(); } void SoundSystem::PlaySound(string name, glm::vec3 pos) { if (! enabled) { return; } FMOD::Sound * sound = Content::LoadSound(name); FMOD::Channel * channel; fmodSystem->playSound(FMOD_CHANNEL_FREE, sound, false, & channel); if (channel != NULL) { channel->set3DAttributes(& GLToFMODVector(pos), & GLToFMODVector(glm::vec3(0))); } }
d7dfffb495fa5c317267506351d08a8f8a1cb8ff
41336673d4112c3025546b927cfb279d40ede2f2
/compilerProject/ST/object.h
f0de2cfa282417250929f581b24ca28a7056f453
[]
no_license
BlueBrains/compiler-project
6f5e05f0d908defa941910d165e8592c93dcbec0
6d3045621fa21c9b4220bccf98e91d9ba23fd5b4
refs/heads/master
2021-01-20T18:54:56.494693
2015-01-13T10:11:09
2015-01-13T10:11:09
65,128,243
1
0
null
null
null
null
UTF-8
C++
false
false
70
h
using namespace std; class object { public: object(); ~object(); };
14c8acdad973ce34a520e6f44147334b20531bf9
4b8fde910bf00294ea21ce4d1aade7dff921498a
/dev/src/builtins.cpp
071faeb21589f52444ce65a38fd45276dfad4bfe
[ "Apache-2.0" ]
permissive
DawidvC/lobster
f4db968a78e9969ab8c57dc1ed511e8cf4d8abfb
ca6fae4b308664e61ce5d745aec1f610429b297d
refs/heads/master
2020-04-06T05:32:27.947474
2014-09-06T22:15:31
2014-09-06T22:15:31
null
0
0
null
null
null
null
UTF-8
C++
false
false
31,135
cpp
// Copyright 2014 Wouter van Oortmerssen. 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 "stdafx.h" #include "vmdata.h" #include "natreg.h" #include "unicode.h" static MersenneTwister rnd; int KeyCompare(const Value &a, const Value &b, bool rec = false) { if (a.type != b.type) g_vm->BuiltinError("binary search: key type doesn't match type of vector elements"); switch (a.type) { case V_INT: return a.ival < b.ival ? -1 : a.ival > b.ival; case V_FLOAT: return a.fval < b.fval ? -1 : a.fval > b.fval; case V_STRING: return strcmp(a.sval->str(), b.sval->str()); case V_VECTOR: if (a.vval->len && b.vval->len && !rec) return KeyCompare(a.vval->at(0), b.vval->at(0), true); // fall thru: default: g_vm->BuiltinError("binary search: illegal key type"); return 0; } } void AddBuiltins() { STARTDECL(print) (Value &a) { ProgramOutput(a.ToString(g_vm->programprintprefs).c_str()); return a; } ENDDECL1(print, "x", "A", "A", "output any value to the console (with linefeed). returns its argument."); STARTDECL(printnl) (Value &a) { ProgramOutput(a.ToString(g_vm->programprintprefs).c_str()); return a; } ENDDECL1(printnl, "x", "A", "A", "output any value to the console (no linefeed). returns its argument."); STARTDECL(set_print_depth) (Value &a) { g_vm->programprintprefs.depth = a.ival; return a; } ENDDECL1(set_print_depth, "a", "I", "", "for printing / string conversion: sets max vectors/objects recursion depth (default 10)"); STARTDECL(set_print_length) (Value &a) { g_vm->programprintprefs.budget = a.ival; return a; } ENDDECL1(set_print_length, "a", "I", "", "for printing / string conversion: sets max string length (default 10000)"); STARTDECL(set_print_quoted) (Value &a) { g_vm->programprintprefs.quoted = a.ival != 0; return a; } ENDDECL1(set_print_quoted, "a", "I", "", "for printing / string conversion: if the top level value is a string, whether to convert it with escape codes" " and quotes (default false)"); STARTDECL(set_print_decimals) (Value &a) { g_vm->programprintprefs.decimals = a.ival; return a; } ENDDECL1(set_print_decimals, "a", "I", "", "for printing / string conversion: number of decimals for any floating point output (default -1, meaning all)"); STARTDECL(getline) () { const int MAXSIZE = 1000; char buf[MAXSIZE]; fgets(buf, MAXSIZE, stdin); buf[MAXSIZE - 1] = 0; for (int i = 0; i < MAXSIZE; i++) if (buf[i] == '\n') { buf[i] = 0; break; } return Value(g_vm->NewString(buf, strlen(buf))); } ENDDECL0(getline, "", "", "S", "reads a string from the console if possible (followed by enter)"); STARTDECL(if) (Value &c, Value &t, Value &e) { return c.DEC().True() ? t : e; // e may be nil } ENDDECL3CONT(if, "cond,then,else", "ACc", "A", "evaluates then or else depending on cond, else is optional"); #define BWHILE(INIT, BRET) \ Value accum = g_vm->Pop(); \ Value lv = g_vm->LoopVal(0); \ if (accum.type == V_UNKNOWN) \ { \ accum = INIT; \ } \ else \ { \ auto lv2 = g_vm->LoopVal(1); \ BRET; \ } \ if (lv.True()) \ { \ g_vm->Push(accum); \ g_vm->Push(c); \ g_vm->Push(b); \ } \ else \ { \ g_vm->Push(accum); \ } \ return lv; STARTDECL(while) (Value &c, Value &b) { BWHILE(Value(0, V_NIL), { accum.DEC(); accum = lv2; }); // FIXME: if the condition contains another while loop (thru a function call), // then lv1 will have already been overwritten } ENDDECL2WHILE(while, "cond,body", "EC", "A", "evaluates body while cond (converted to a function) holds true, returns last body value"); STARTDECL(collectwhile) (Value &c, Value &b) { BWHILE(Value(g_vm->NewVector(4, V_VECTOR)), { assert(accum.type == V_VECTOR); accum.vval->push(lv2); }); } ENDDECL2WHILE(collectwhile, "cond,body", "EC", "V", "evaluates body while cond holds true, returns a vector of all return values of body"); #define BLOOP(INIT, BRET) \ int nargs = body.Nargs(); \ int len = IterLen(iter); \ auto i = g_vm->Pop(); \ assert(i.type == V_INT); \ i.ival++; \ Value accum; \ if (i.ival) \ { \ auto lv = g_vm->LoopVal(0); \ accum = g_vm->Pop(); \ BRET; \ } \ else \ { \ accum = INIT; \ } \ if (i.ival < len) \ { \ g_vm->Push(accum); \ g_vm->Push(i); \ g_vm->Push(iter); \ g_vm->Push(body); \ if (nargs) { g_vm->Push(GetIter(iter, i.ival)); if (nargs > 1) g_vm->Push(i); } \ g_vm->Push(body); \ return Value(true); \ } \ else \ { \ iter.DEC(); \ g_vm->Push(accum); \ return Value(false); \ } STARTDECL(for) (Value &iter, Value &body) { BLOOP(Value(0), { assert(accum.type == V_INT); if (lv.DEC().True()) accum.ival++; }); } ENDDECL2LOOP(for, "iter,body", "AC", "I", "iterates over int/vector/string, body may take [ element [ , index ] ] arguments," " returns number of evaluations that returned true"); STARTDECL(filter) (Value &iter, Value &body) { // TODO: assumes the filtered vector is close to the original, can we do better? BLOOP(Value(g_vm->NewVector(len, V_VECTOR)), { assert(accum.type == V_VECTOR); if (lv.DEC().True()) accum.vval->push(GetIter(iter, i.ival - 1)); }); } ENDDECL2LOOP(filter, "iter,body", "AC", "V", "iterates over int/vector/string, body may take [ element [ , index ] ] arguments," " returns vector of elements for which body returned true"); STARTDECL(exists) (Value &iter, Value &body) { BLOOP(Value(false), { assert(accum.type == V_INT); if (lv.True()) { iter.DEC(); g_vm->Push(lv); return Value(false); }; lv.DEC(); }); } ENDDECL2LOOP(exists, "iter,body", "AC", "I", "iterates over int/vector/string, body may take [ element [ , index ] ] arguments," " returns true upon first element where body returns true, else false"); STARTDECL(map) (Value &iter, Value &body) { BLOOP(Value(g_vm->NewVector(len, V_VECTOR)), { assert(accum.type == V_VECTOR); accum.vval->push(lv); }); } ENDDECL2LOOP(map, "iter,body", "AC", "V", "iterates over int/vector/string, body may take [ element [ , index ] ] arguments," " returns vector of return values of body"); STARTDECL(append) (Value &v1, Value &v2) { auto nv = g_vm->NewVector(v1.vval->len + v2.vval->len, V_VECTOR); nv->append(v1.vval, 0, v1.vval->len); v1.DEC(); nv->append(v2.vval, 0, v2.vval->len); v2.DEC(); return Value(nv); } ENDDECL2(append, "xs,ys", "VV", "V", "creates new vector by appending all elements of 2 input vectors"); STARTDECL(length) (Value &a) { int len; switch (a.type) { case V_VECTOR: case V_STRING: len = a.lobj->len; break; default: return g_vm->BuiltinError("illegal type passed to length"); } a.DECRT(); return Value(len); } ENDDECL1(length, "xs", "A", "I", "length of vector/string"); STARTDECL(equal) (Value &a, Value &b) { bool eq = a.Equal(b, true); a.DEC(); b.DEC(); return Value(eq); } ENDDECL2(equal, "a,b", "AA", "I", "structural equality between any two values (recurses into vectors/objects," " unlike == which is only true for vectors/objects if they are the same object)"); STARTDECL(push) (Value &l, Value &x) { l.vval->push(x); return l; } ENDDECL2(push, "xs,x", "VA", "V", "appends one element to a vector, returns existing vector"); STARTDECL(pop) (Value &l) { if (!l.vval->len) { l.DEC(); g_vm->BuiltinError("pop: empty vector"); } auto v = l.vval->pop(); l.DEC(); return v; } ENDDECL1(pop, "xs", "V", "A", "removes last element from vector and returns it"); STARTDECL(top) (Value &l) { if (!l.vval->len) { l.DEC(); g_vm->BuiltinError("top: empty vector"); } auto v = l.vval->top(); l.DEC(); return v.INC(); } ENDDECL1(top, "xs", "V", "A", "returns last element from vector"); STARTDECL(replace) (Value &l, Value &i, Value &a) { if (i.ival < 0 || i.ival >= l.vval->len) g_vm->BuiltinError("replace: index out of range"); auto nv = g_vm->NewVector(l.vval->len, l.vval->type); nv->append(l.vval, 0, l.vval->len); l.DECRT(); Value &dest = nv->at(i.ival); dest.DEC(); dest = a; return Value(nv); } ENDDECL3(replace, "xs,i,x", "VIA", "V", "returns a copy of a vector with the element at i replaced by x"); STARTDECL(insert) (Value &l, Value &i, Value &a, Value &n) { int amount = n.type == V_INT ? n.ival : 1; if (amount <= 0 || i.ival < 0 || i.ival > l.vval->len) g_vm->BuiltinError("insert: index or n out of range"); // note: i==len is legal l.vval->insert(a, i.ival, amount); return l; } ENDDECL4(insert, "xs,i,x,n", "VIAi", "V", "inserts n copies (default 1) of x into a vector at index i, existing elements shift upward," " returns original vector"); STARTDECL(remove) (Value &l, Value &i, Value &n) { int amount = n.type == V_INT ? n.ival : 1; if (amount <= 0 || amount > l.vval->len || i.ival < 0 || i.ival > l.vval->len - amount) g_vm->BuiltinError("remove: index or n out of range"); auto v = l.vval->remove(i.ival, amount); l.DEC(); return v; } ENDDECL3(remove, "xs,i,n", "VIi", "A", "remove element(s) at index i, following elements shift down. pass the number of elements to remove" " as an optional argument, default 1. returns the first element removed."); STARTDECL(removeobj) (Value &l, Value &o) { int removed = 0; for (int i = 0; i < l.vval->len; i++) if (l.vval->at(i).Equal(o, false)) { l.vval->remove(i--, 1).DEC(); removed++; } o.DEC(); l.DEC(); return Value(removed); } ENDDECL2(removeobj, "xs,obj", "VA", "I", "remove all elements equal to obj (==), returns amount of elements removed."); STARTDECL(binarysearch) (Value &l, Value &key) { ValueRef lref(l), kref(key); int size = l.vval->len; int i = 0; for (;;) { if (!size) break; int mid = size / 2; int comp = KeyCompare(key, l.vval->at(i + mid)); if (comp) { if (comp < 0) size = mid; else { mid++; i += mid; size -= mid; } } else { i += mid; size = 1; while (i && !KeyCompare(key, l.vval->at(i - 1 ))) { i--; size++; } while (i + size < l.vval->len && !KeyCompare(key, l.vval->at(i + size))) { size++; } break; } } g_vm->Push(Value(size)); return Value(i); } ENDDECL2(binarysearch, "xs,key", "VA", "II", "does a binary search for key in a sorted vector, returns as first return value how many matches were found," " and as second the index in the array where the matches start (so you can read them, overwrite them," " or remove them), or if none found, where the key could be inserted such that the vector stays sorted." " As key you can use a int/float/string value, or if you use a vector, the first element of it will be used" " as the search key (allowing you to model a set/map/multiset/multimap using this one function). "); STARTDECL(copy) (Value &v) { auto nv = g_vm->NewVector(v.vval->len, v.vval->type); nv->append(v.vval, 0, v.vval->len); v.DECRT(); return Value(nv); } ENDDECL1(copy, "xs", "V", "V", "makes a shallow copy of vector/object."); STARTDECL(slice) (Value &l, Value &s, Value &e) { int size = e.ival; if (size < 0) size = l.vval->len + size; int start = s.ival; if (start < 0) start = l.vval->len + start; if (start < 0 || start + size > (int)l.vval->len) g_vm->BuiltinError("slice: values out of range"); auto nv = g_vm->NewVector(size, V_VECTOR); nv->append(l.vval, start, size); l.DECRT(); return Value(nv); } ENDDECL3(slice, "xs,start,size", "VII", "V", "returns a sub-vector of size elements from index start." " start & size can be negative to indicate an offset from the vector length."); STARTDECL(any) (Value &v) { Value r(0, V_NIL); for (int i = 0; i < v.vval->len; i++) { if (v.vval->at(i).True()) { r = v.vval->at(i); r.INC(); break; } } v.DECRT(); return r; } ENDDECL1(any, "xs", "V", "A", "returns the first true element of the vector, or nil"); STARTDECL(all) (Value &v) { Value r(true); for (int i = 0; i < v.vval->len; i++) { if (!v.vval->at(i).True()) { r = Value(false); break; } } v.DECRT(); return r; } ENDDECL1(all, "xs", "V", "I", "returns wether all elements of the vector are true values"); STARTDECL(substring) (Value &l, Value &s, Value &e) { int size = e.ival; if (size < 0) size = l.vval->len + size; int start = s.ival; if (start < 0) start = l.vval->len + start; if (start < 0 || start + size > (int)l.vval->len) g_vm->BuiltinError("substring: values out of range"); auto ns = g_vm->NewString(l.sval->str() + start, size); l.DECRT(); return Value(ns); } ENDDECL3(substring, "s,start,size", "SII", "S", "returns a substring of size characters from index start." " start & size can be negative to indicate an offset from the string length."); STARTDECL(tokenize) (Value &s, Value &delims, Value &whitespace) { auto v = g_vm->NewVector(0, V_VECTOR); auto ws = whitespace.sval->str(); auto dl = delims.sval->str(); auto p = s.sval->str(); p += strspn(p, ws); auto strspn1 = [](char c, const char *set) { while (*set) if (*set == c) return 1; return 0; }; while (*p) { auto delim = p + strcspn(p, dl); auto end = delim; while (end > p && strspn1(end[-1], ws)) end--; v->push(g_vm->NewString(p, end - p)); p = delim + strspn(delim, dl); p += strspn(p, ws); } s.DECRT(); delims.DECRT(); whitespace.DECRT(); return Value(v); } ENDDECL3(tokenize, "s,delimiters,whitespace", "SSS", "V", "splits a string into a vector of strings, by splitting into segments upon each dividing or terminating" " delimiter. Segments are stripped of leading and trailing whitespace." " Example: \"; A ; B C; \" becomes [ \"\", \"A\", \"B C\" ] with \";\" as delimiter and \" \" as whitespace." ); STARTDECL(unicode2string) (Value &v) { ValueRef vref(v); char buf[7]; string s; for (int i = 0; i < v.vval->len; i++) { auto &c = v.vval->at(i); if (c.type != V_INT) g_vm->BuiltinError("unicode2string: vector contains non-int values."); ToUTF8(c.ival, buf); s += buf; } return Value(g_vm->NewString(s)); } ENDDECL1(unicode2string, "us", "V", "S", "converts a vector of ints representing unicode values to a UTF-8 string."); STARTDECL(string2unicode) (Value &s) { ValueRef sref(s); auto v = g_vm->NewVector(s.sval->len, V_VECTOR); ValueRef vref((Value(v))); const char *p = s.sval->str(); while (*p) { int u = FromUTF8(p); if (u < 0) return Value(0, V_NIL); v->push(u); } return Value(v).INC(); } ENDDECL1(string2unicode, "s", "S", "V", "converts a UTF-8 string into a vector of unicode values, or nil upon a decoding error"); STARTDECL(number2string) (Value &n, Value &b, Value &mc) { if (b.ival < 2 || b.ival > 36 || mc.ival > 32) g_vm->BuiltinError("number2string: values out of range"); uint i = (uint)n.ival; string s; const char *from = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"; while (i || (int)s.length() < mc.ival) { s.insert(0, 1, from[i % b.ival]); i /= b.ival; } return Value(g_vm->NewString(s)); } ENDDECL3(number2string, "number,base,minchars", "III", "S", "converts the (unsigned version) of the input integer number to a string given the base (2..36, e.g. 16 for" " hex) and outputting a minimum of characters (padding with 0)."); #define VECTOROP(name, op, otype, typen) \ if (a.type == otype) { auto f = a; return Value(op); } \ if (otype == V_FLOAT && a.type == V_INT) { Value f(float(a.ival)); return Value(op); } \ if (a.type == V_VECTOR) { \ auto v = g_vm->NewVector(a.vval->len, a.vval->type); \ for (int i = 0; i < a.vval->len; i++) { \ auto f = a.vval->at(i); \ if (otype == V_FLOAT && f.type == V_INT) f = Value(float(f.ival)); \ if (f.type != otype) { a.DECRT(); v->deleteself(); goto err; } \ v->push(Value(op)); \ } \ a.DECRT(); \ return Value(v); \ } \ err: g_vm->BuiltinError(#name " requires " typen " or vector argument"); \ return Value(); #define VECTOROPF(name, op) VECTOROP(name, op, V_FLOAT, "numeric") #define VECTOROPI(name, op) VECTOROP(name, op, V_INT, "integer") STARTDECL(pow) (Value &a, Value &b) { return Value(powf(a.fval, b.fval)); } ENDDECL2(pow, "a,b", "FF", "F", "a raised to the power of b"); STARTDECL(log) (Value &a) { return Value(logf(a.fval)); } ENDDECL1(log, "a", "F", "F", "natural logaritm of a"); STARTDECL(sqrt) (Value &a) { return Value(sqrtf(a.fval)); } ENDDECL1(sqrt, "f", "F", "F", "square root"); STARTDECL(and) (Value &a, Value &b) { return Value(a.ival & b.ival); } ENDDECL2(and, "a,b", "II", "I", "bitwise and"); STARTDECL(or) (Value &a, Value &b) { return Value(a.ival | b.ival); } ENDDECL2(or, "a,b", "II", "I", "bitwise or"); STARTDECL(xor) (Value &a, Value &b) { return Value(a.ival ^ b.ival); } ENDDECL2(xor, "a,b", "II", "I", "bitwise exclusive or"); STARTDECL(not) (Value &a) { return Value(~a.ival); } ENDDECL1(not, "a", "I", "I", "bitwise negation"); STARTDECL(shl) (Value &a, Value &b) { return Value(a.ival << b.ival); } ENDDECL2(shl, "a,b", "II", "I", "bitwise shift left"); STARTDECL(shr) (Value &a, Value &b) { return Value(a.ival >> b.ival); } ENDDECL2(shr, "a,b", "II", "I", "bitwise shift right"); STARTDECL(ceiling) (Value &a) { VECTOROPF(ceiling, int(ceilf(f.fval))); } ENDDECL1(ceiling, "f", "A", "A", "the nearest int >= f (or vector of numbers)"); STARTDECL(floor) (Value &a) { VECTOROPF(floor, int(floorf(f.fval))); } ENDDECL1(floor, "f", "A", "A", "the nearest int <= f (or vector of numbers)"); STARTDECL(truncate)(Value &a) { VECTOROPF(truncate, int(f.fval)); } ENDDECL1(truncate, "f", "A", "A", "converts a number (or vector of numbers) to an integer by dropping the fraction"); STARTDECL(round) (Value &a) { VECTOROPF(round, int(f.fval + 0.5f)); } ENDDECL1(round, "f", "A", "A", "converts a number (or vector of numbers) to the closest integer"); STARTDECL(fraction)(Value &a) { VECTOROPF(fraction, f.fval - floorf(f.fval)); } ENDDECL1(fraction, "f", "A", "A", "returns the fractional part of a number (or vector of numbers): short for f - floor(f)"); STARTDECL(sin) (Value &a) { return Value(sinf(a.fval * RAD)); } ENDDECL1(sin, "angle", "F", "F", "the y coordinate of the normalized vector indicated by angle (in degrees)"); STARTDECL(cos) (Value &a) { return Value(cosf(a.fval * RAD)); } ENDDECL1(cos, "angle", "F", "F", "the x coordinate of the normalized vector indicated by angle (in degrees)"); STARTDECL(sincos) (Value &a) { return ToValue(float3(cosf(a.fval * RAD), sinf(a.fval * RAD), 0.0f)); } ENDDECL1(sincos, "angle", "F", "V", "the normalized vector indicated by angle (in degrees), same as [ cos(angle), sin(angle), 0 ]"); STARTDECL(arcsin) (Value &y) { return Value(asinf(y.fval) / RAD); } ENDDECL1(arcsin, "y", "F", "F", "the angle (in degrees) indicated by the y coordinate projected to the unit circle"); STARTDECL(arccos) (Value &x) { return Value(acosf(x.fval) / RAD); } ENDDECL1(arccos, "x", "F", "F", "the angle (in degrees) indicated by the x coordinate projected to the unit circle"); STARTDECL(atan2) (Value &vec) { auto v = ValueDecTo<float3>(vec); return Value(atan2f(v.y(), v.x()) / RAD); } ENDDECL1(atan2, "vec", "V" , "F", "the angle (in degrees) corresponding to a normalized 2D vector"); STARTDECL(normalize) (Value &vec) { auto v = ValueDecTo<float3>(vec); return ToValue(v == float3_0 ? v : normalize(v)); } ENDDECL1(normalize, "vec", "V" , "V", "returns a vector of unit length"); STARTDECL(dot) (Value &a, Value &b) { return Value(dot(ValueDecTo<float4>(a), ValueDecTo<float4>(b))); } ENDDECL2(dot, "a,b", "VV", "F", "the length of vector a when projected onto b (or vice versa)"); STARTDECL(magnitude) (Value &a) { return Value(length(ValueDecTo<float4>(a))); } ENDDECL1(magnitude, "a", "V", "F", "the geometric length of a vector"); STARTDECL(cross) (Value &a, Value &b) { return ToValue(cross(ValueDecTo<float3>(a), ValueDecTo<float3>(b))); } ENDDECL2(cross, "a,b", "VV", "V", "a perpendicular vector to the 2D plane defined by a and b (swap a and b for its inverse)"); STARTDECL(rnd) (Value &a) { VECTOROPI(rnd, rnd(max(1, f.ival))); } ENDDECL1(rnd, "max", "A", "A", "a random value [0..max) or a random vector from an input vector. Uses the Mersenne Twister algorithm."); STARTDECL(rndseed) (Value &seed) { rnd.ReSeed(seed.ival); return Value(); } ENDDECL1(rndseed, "seed", "I", "", "explicitly set a random seed for reproducable randomness"); STARTDECL(rndfloat)() { return Value((float)rnd.rnddouble()); } ENDDECL0(rndfloat, "", "", "F", "a random float [0..1)"); STARTDECL(div) (Value &a, Value &b) { return Value(float(a.ival) / float(b.ival)); } ENDDECL2(div, "a,b", "II", "F", "forces two ints to be divided as floats"); STARTDECL(clamp) (Value &a, Value &b, Value &c) { if (a.type == V_INT && b.type == V_INT && c.type == V_INT) { return Value(max(min(a.ival, c.ival), b.ival)); } else { g_vm->BuiltinCheck(a, V_FLOAT, "clamp"); g_vm->BuiltinCheck(b, V_FLOAT, "clamp"); g_vm->BuiltinCheck(c, V_FLOAT, "clamp"); return Value(max(min(a.fval, c.fval), b.fval)); } } ENDDECL3(clamp, "x,min,max", "AAA", "A", "forces a number to be in the range between min and max (inclusive)"); STARTDECL(abs) (Value &a) { switch (a.type) { case V_INT: return Value(a.ival >= 0 ? a.ival : -a.ival); case V_FLOAT: return Value(a.fval >= 0 ? a.fval : -a.fval); case V_VECTOR: { auto v = g_vm->NewVector(a.vval->len, a.vval->type); for (int i = 0; i < a.vval->len; i++) { auto f = a.vval->at(i); switch (f.type) { case V_INT: v->push(Value(abs(f.ival))); break; case V_FLOAT: v->push(Value(fabsf(f.fval))); break; default: v->deleteself(); goto err; } } a.DECRT(); return Value(v); } default: break; } err: a.DECRT(); return g_vm->BuiltinError("abs() needs a numerical value or numerical vector"); } ENDDECL1(abs, "x", "A", "A", "absolute value of int/float/vector"); #define MINMAX(op) \ switch (x.type) \ { \ case V_INT: \ if (y.type == V_INT) return Value(x.ival op y.ival ? x.ival : y.ival); \ else if (y.type == V_FLOAT) return Value(x.ival op y.fval ? x.ival : y.fval); \ break; \ case V_FLOAT: \ if (y.type == V_INT) return Value(x.fval op y.ival ? x.fval : y.ival); \ else if (y.type == V_FLOAT) return Value(x.fval op y.fval ? x.fval : y.fval); \ break; \ default: ; \ } \ return g_vm->BuiltinError("illegal arguments to min/max"); STARTDECL(min) (Value &x, Value &y) { MINMAX(<) } ENDDECL2(min, "x,y", "AA", "A", "smallest of 2 values"); STARTDECL(max) (Value &x, Value &y) { MINMAX(>) } ENDDECL2(max, "x,y", "AA", "A", "largest of 2 values"); #undef MINMAX STARTDECL(cardinalspline) (Value &z, Value &a, Value &b, Value &c, Value &f, Value &t) { return ToValue(cardinalspline(ValueDecTo<float3>(z), ValueDecTo<float3>(a), ValueDecTo<float3>(b), ValueDecTo<float3>(c), f.fval, t.fval)); } ENDDECL6(cardinalspline, "z,a,b,c,f,tension", "VVVVFF", "V", "computes the position between a and b with factor f [0..1], using z (before a) and c (after b) to form a" " cardinal spline (tension at 0.5 is a good default)"); STARTDECL(lerp) (Value &x, Value &y, Value &f) { if (x.type == y.type) { switch (x.type) { case V_FLOAT: return Value(mix(x.fval, y.fval, f.fval)); case V_INT: return Value(mix((float)x.ival, (float)y.ival, f.fval)); // should this do any size vecs? case V_VECTOR: return ToValue(mix(ValueDecTo<float4>(x), ValueDecTo<float4>(y), f.fval)); default: ; } } g_vm->BuiltinError("illegal arguments passed to lerp()"); return Value(); } ENDDECL3(lerp, "x,y,f", "AAF", "A", "linearly interpolates between x and y (float/int/vector) with factor f [0..1]"); STARTDECL(resume) (Value &co, Value &ret) { g_vm->CoResume(co.cval); return ret; } ENDDECL2(resume, "coroutine,returnvalue", "Ra", "A", "resumes execution of a coroutine, passing a value back or nil"); STARTDECL(returnvalue) (Value &co) { Value &rv = co.cval->Current().INC(); co.DECRT(); return rv; } ENDDECL1(returnvalue, "coroutine", "R", "A", "gets the last return value of a coroutine"); STARTDECL(active) (Value &co) { bool active = co.cval->active; co.DECRT(); return Value(active); } ENDDECL1(active, "coroutine", "R", "I", "wether the given coroutine is still active"); STARTDECL(program_name) () { return Value(g_vm->NewString(g_vm->GetProgramName())); } ENDDECL0(program_name, "", "", "S", "returns the name of the main program (e.g. \"foo.lobster\"."); STARTDECL(caller_id) () { return Value(g_vm->CallerId()); } ENDDECL0(caller_id, "", "", "I", "returns an int that uniquely identifies the caller to the current function."); STARTDECL(seconds_elapsed) () { return Value(g_vm->Time()); } ENDDECL0(seconds_elapsed, "", "", "F", "seconds since program start as a float, unlike gl_time() it is calculated every time it is called"); STARTDECL(assert) (Value &c) { if (!c.True()) g_vm->BuiltinError("assertion failed"); c.DEC(); return Value(); } ENDDECL1(assert, "condition", "A", "", "halts the program with an assertion failure if passed false"); STARTDECL(trace_bytecode) (Value &i) { g_vm->Trace(i.ival != 0); return Value(); } ENDDECL1(trace_bytecode, "on", "I", "", "tracing shows each bytecode instruction as it is being executed, not very useful unless you are trying to" " isolate a compiler bug"); STARTDECL(collect_garbage) () { return Value(g_vm->GC()); } ENDDECL0(collect_garbage, "", "", "I", "forces a garbage collection to re-claim cycles. slow and not recommended to be used. instead, write code" " to clear any back pointers before abandoning data structures. Watch for a \"LEAKS FOUND\" message in the" " console upon program exit to know when you've created a cycle. returns amount of objects collected."); STARTDECL(set_max_stack_size) (Value &max) { g_vm->SetMaxStack(max.ival * 1024 * 1024 / sizeof(Value)); return max; } ENDDECL1(set_max_stack_size, "max", "I", "", "size in megabytes the stack can grow to before an overflow error occurs. defaults to 1"); } AutoRegister __abi("builtins", AddBuiltins);
fbfec0150f387079e4c6bfabf1215be241417d56
438089df0a020dc8205a4b0df2a08e510f40fd3c
/extern/renderdoc/util/test/demos/gl/gl_test.h
b7900315cd2b3e4ca12d9376f844a0465014b7b3
[ "LicenseRef-scancode-unknown-license-reference", "MIT", "BSD-3-Clause", "Apache-2.0", "CC-BY-3.0" ]
permissive
minh0722/basic-directx11
59b5bbcc5de6ccf5f26fa68493d11512b20e5971
9e0b24d42497688fd5193327110432ab262234cf
refs/heads/master
2021-08-16T03:11:48.626639
2021-01-20T23:45:33
2021-01-20T23:45:33
72,579,642
0
0
null
null
null
null
UTF-8
C++
false
false
2,543
h
/****************************************************************************** * The MIT License (MIT) * * Copyright (c) 2019-2020 Baldur Karlsson * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. ******************************************************************************/ #pragma once #include "../test_common.h" #include "3rdparty/glad/glad.h" #include <vector> struct OpenGLGraphicsTest : public GraphicsTest { static const TestAPI API = TestAPI::OpenGL; void Prepare(int argc, char **argv); bool Init(); void Shutdown(); GraphicsWindow *MakeWindow(int width, int height, const char *title); void *MakeContext(GraphicsWindow *win, void *share); void DestroyContext(void *ctx); void ActivateContext(GraphicsWindow *win, void *ctx); void PostInit(); GLuint MakeProgram(std::string vertSrc, std::string fragSrc, std::string geomSrc = ""); GLuint MakeProgram(std::string compSrc); GLuint MakeProgram(); GLuint MakePipeline(); GLuint MakeBuffer(); GLuint MakeTexture(); GLuint MakeVAO(); GLuint MakeFBO(); void pushMarker(const std::string &name); void setMarker(const std::string &name); void popMarker(); bool Running(); void Present(GraphicsWindow *window); void Present() { Present(mainWindow); } int glMajor = 4; int glMinor = 3; bool coreProfile = true; bool gles = false; GraphicsWindow *mainWindow = NULL; void *mainContext = NULL; bool inited = false; struct { std::vector<GLuint> bufs, texs, progs, pipes, vaos, fbos; } managedResources; };
7920fcbbc6b4d2ed2817de8454b6d5836d4efd17
d603ec4bbca216691a886f382d43997f2277b5f5
/src/iccf.cc
03c6e2e88eacaa8b1aae8ee61ec66e24d83a4884
[ "MIT" ]
permissive
argv-minus-one/iconv-corefoundation
6d843e68472343b066beccb5af5cb037659729b8
05394f04940a83431749c1672747eebcc8fae8ac
refs/heads/master
2023-05-10T17:05:37.184906
2021-11-28T22:56:11
2021-11-28T22:56:11
190,135,783
0
1
MIT
2023-05-01T06:54:15
2019-06-04T05:33:32
C++
UTF-8
C++
false
false
2,232
cc
#include "iccf.hh" #include "StringEncoding.hh" #include "transcode.hh" #include "napi.hh" #include <sstream> static Napi::Value encodingExists(const Napi::CallbackInfo &info) { auto jsEncodingName = info[0].As<Napi::String>(); auto encodingName = NapiStringToCFString(jsEncodingName); auto encoding = CFStringConvertIANACharSetNameToEncoding(encodingName); return Napi::Boolean::New(info.Env(), encoding != kCFStringEncodingInvalidId); } static Napi::Object init(Napi::Env env, Napi::Object exports) { return Napi::Function::New(env, [] (const Napi::CallbackInfo &info) { const auto env = info.Env(); const auto exports = Napi::Object::New(env); const auto iccf = new Iccf(info[0].ToObject(), exports); napi_add_env_cleanup_hook(env, [] (void *arg) { delete reinterpret_cast<Iccf *>(arg); }, iccf); return exports; }, ""); } NODE_API_MODULE(NODE_GYP_MODULE_NAME, init) static Napi::FunctionReference funcRef(Napi::Object imports, const char *name) { Napi::Value value = imports[name]; if (value.IsUndefined()) { std::stringstream ss; ss << "Property \"" << name << "\" is missing from imports object."; throw Napi::TypeError::New(imports.Env(), ss.str()); } else if (value.IsFunction()) { auto ref = Napi::Persistent(value.As<Napi::Function>()); ref.SuppressDestruct(); return ref; } else { std::stringstream ss; ss << "Property \"" << name << "\" of imports object is not a function. Instead, it is: " << value.ToString().Utf8Value(); throw Napi::TypeError::New(imports.Env(), ss.str()); } } Iccf::Iccf(Napi::Object imports, Napi::Object exports) : InvalidEncodedTextError(funcRef(imports, "InvalidEncodedTextError")) , NotRepresentableError(funcRef(imports, "NotRepresentableError")) , UnrecognizedEncodingError(funcRef(imports, "UnrecognizedEncodingError")) , _newFormattedTypeError(funcRef(imports, "newFormattedTypeError")) , StringEncoding(imports.Env(), this) { const auto env = imports.Env(); exports.DefineProperties({ Napi::PropertyDescriptor::Value("StringEncoding", StringEncoding.constructor(), napi_enumerable), Napi::PropertyDescriptor::Function(env, exports, "encodingExists", encodingExists, napi_enumerable) }); TranscodeInit(env, exports, this); }
8f23fe12ea6419e6668d995c63975ed59e2b6943
5299049902e3cf75de755eb4e76ee9af194529f8
/HeapSort.cpp
c5bcf3dcfccf7e09b656a3a26b7bb707ca230f16
[]
no_license
iPrayerr/Algorithm-Methods
9d93a000db58a1e6e16bd5bfd98055d12b3374e2
a0ba94a12b08f57ea624fb373071495e578ad83b
refs/heads/master
2020-04-24T23:07:56.155261
2019-04-23T11:31:13
2019-04-23T11:31:13
172,333,429
0
0
null
2019-04-22T11:01:05
2019-02-24T12:13:35
C++
UTF-8
C++
false
false
4,145
cpp
/* heap sort: 1. 对数组按照堆的定义建立完全二叉树 2. 将二叉树作一次调整,变成大顶堆 3. 将大顶堆的根和最后一个树叶交换,并剔除交换后的树叶 4. 重复23,直至所有元素被剔除,则得到sorted array */ //树的核心:recurrence //测试数据为n个无序伪随机数,n为人工设定 #include <iostream> #include <stdlib.h> #include <time.h> #include <vector> using namespace std; struct BTree{ int value; struct BTree *parent,*left,*right; }*bt; vector<int> a; int n; void Heap_Sort(); void CreateTree(BTree* &b,int i); void Big_Heap(BTree* &b); void Exchange(int length); int main(){ srand(time(0)); cin >> n; for(int i=0;i<n;i++) { a.push_back(rand()%500); cout << a[i] << " "; } cout << endl; Heap_Sort(); for(int i=0;i<n;i++) cout << a[i] << " "; return 0; } void Heap_Sort(){ CreateTree(bt,1); Exchange(n); } void CreateTree(BTree* &b,int i){ if(i<=n){ b = new BTree; BTree* pos; pos = bt; //寻找父节点 int temp = i; if(i>3){ vector<int> mov; //轨迹算法:对于堆构建的完全二叉树,可以用i不断模2得到逆序的查找轨迹 //0:当前查找中为左孩子;1:当前查找中为右孩子 while(temp>1){ mov.push_back(temp%2); temp/=2; } for(int j=mov.size()-1;j>=1;j--){ if(!mov[j]) pos = pos->left; else pos = pos->right; } } b->parent = pos; b->value = a[i-1]; CreateTree(b->left,2*i); CreateTree(b->right,2*i+1); } else b = NULL; } bool fin = true; //调整完成标志 void Big_Heap(BTree* &b){ //大顶堆应该从下往上调 //左孩子NULL, 右孩子必定NULL int temp; //两数值交换的中间变量 if((b->left)!=NULL) Big_Heap(b->left); //compare if((b->parent->left)==b&&(b->parent->right)!=NULL){ //是左孩子且右孩子不为空 if((b->value)>(b->parent->right->value)&&(b->value)>(b->parent->value)){ temp = b->parent->value; b->parent->value = b->value; b->value = temp; fin = false; }//左孩子的swap else if((b->value)<=(b->parent->right->value)&&(b->parent->right->value)>(b->parent->value)){ temp = b->parent->value; b->parent->value = b->parent->right->value; b->parent->right->value = temp; fin = false; }//右孩子的swap } else if((b->parent->right)==b&&(b->parent->left)!=NULL){ //是右孩子且左孩子不为空 if((b->value)>(b->parent->left->value)&&(b->value)>(b->parent->value)){ temp = b->parent->value; b->parent->value = b->value; b->value = temp; fin = false; }//左孩子的swap else if((b->value)<=(b->parent->left->value)&&(b->parent->left->value)>(b->parent->value)){ temp = b->parent->value; b->parent->value = b->parent->left->value; b->parent->left->value = temp; fin = false; }//右孩子的swap } else if((b->parent->left)==NULL||(b->parent->right)==NULL){ if((b->value)>(b->parent->value)){ temp = b->parent->value; b->parent->value = b->value; b->value = temp; fin = false; } } if(b->right!=NULL) Big_Heap(b->right); if(fin==false){ fin = true; Big_Heap(bt); } } void Exchange(int length) { Big_Heap(bt); int temp = length; vector<int> mov; while(temp>1){ mov.push_back(temp%2); temp/=2; } //seek: 0 to left BTree *pos; pos = bt; int signal; //表示最后一个节点是其父节点的左孩子or右孩子 for(int j=mov.size()-1;j>=0;j--){ if(j==0) signal = mov[j]; //记录最后一次转弯方向 if(!mov[j]) pos = pos->left; else pos = pos->right; } //exchange int swap = bt->value; bt->value = pos->value; pos->value = swap; //delete node&save the biggest pos = pos->parent; if(!signal) pos->left = NULL; else pos->right = NULL; a[length-1] = swap; //未处理部分的最末尾存最大数 //next recurrence if(length>1){ length--; Exchange(length); } else a[0] = bt->value; }
def8a0b06a653d36ddc99d0b99029e3a4bb0412a
e642d93b39d8dd3892ea3a237cdf941060b25baf
/fire_detector_3.0.ino
1fb12fb1d301294df97d962e49d6c710aa667afe
[]
no_license
Carlos74520/Fire-Detection
c907ff6495c412acc0f7390aa362bcbcce5cdc1c
086c82fd0fe9a03539a9efe82f38ac622a9ed45a
refs/heads/master
2020-12-21T23:44:24.444175
2020-02-11T17:21:26
2020-02-11T17:21:26
236,603,005
0
0
null
null
null
null
UTF-8
C++
false
false
1,183
ino
#include <Wire.h> #include <Adafruit_AMG88xx.h> Adafruit_AMG88xx amg; float pixels[AMG88xx_PIXEL_ARRAY_SIZE]; int usedPixels[63]; int counter = 0; int middle = 0; //int pixels[] = {10, 10, 10, 10, 80, 10, 10, 10, 10, 10, 10, 10, 80, 10, 10, 10, 10, 10, 10, 10, 80, 10, 10, 10, 10, 10, 10, 10, 80, 10, 10, 10, 10, 10, 10, 10, 80, 10, 10, 10, 10, 10, 10, 10, 80, 10, 10, 10, 10, 10, 10, 10, 80, 10, 10, 10, 10, 10, 10, 10, 80, 10, 10, 10}; void setup() { Serial.begin(9600); bool status; status = amg.begin(); delay(100); // let sensor boot up } void loop() { //reset variables counter = 0; int usedPixels[63]; //read all the pixels amg.readPixels(pixels); for (int x = 0; x <= 63; x++) { if (pixels[x] > 40) { counter += 1; usedPixels[counter] = x; } } Serial.println(""); //find where the middle is if (counter > 0) { middle = (usedPixels[round(counter / 2)]) % 8; if (middle < 3 ) Serial.print("FIRE ON LEFT"); else if (middle > 4) Serial.print("FIRE ON RIGHT"); else Serial.print("FIRE IS IN FRONT"); } else Serial.print("NO FIRE DETECTED"); delay(500); }
7285b0929c8d4ee5545cc690ab65d2fb0cd30ad5
dc2f794ce06dce6eb1d69a42fd8861b2edaffa97
/apriluiparticle/src/ParticleBase.cpp
0dab3c81f09b518ccb4357f5a1a07ac615bf5062
[]
no_license
Ryex/libaprilparticle
d6500f0d927845d267d53db7776fe42fb1c7b7ae
7a8556fb0e843ef2f61c8313071f2094a08c2dfd
refs/heads/master
2021-01-01T05:30:43.116293
2014-04-04T07:35:59
2014-04-04T07:35:59
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,678
cpp
/// @file /// @author Boris Mikic /// @version 2.0 /// /// @section LICENSE /// /// This program is free software; you can redistribute it and/or modify it under /// the terms of the BSD license: http://www.opensource.org/licenses/bsd-license.php #include <april/Color.h> #include <aprilparticle/aprilparticle.h> #include <aprilparticle/Emitter.h> #include <aprilparticle/Space.h> #include <aprilparticle/System.h> #include <aprilui/aprilui.h> #include <aprilui/Dataset.h> #include <gtypes/Rectangle.h> #include <gtypes/Vector2.h> #include <gtypes/Vector3.h> #include <hltypes/hdir.h> #include <hltypes/hstring.h> #include "apriluiparticle.h" #include "apriluiparticleUtil.h" #include "ParticleSpace.h" #include "ParticleBase.h" namespace apriluiparticle { ParticleBase::ParticleBase(chstr name, grect rect) : aprilui::Object(name, rect) { this->system = NULL; } ParticleBase::~ParticleBase() { this->stopSystem(); } aprilui::Object* ParticleBase::createInstance(chstr name, grect rect) { return new ParticleBase(name, rect); } bool ParticleBase::isRunning() { return (this->system != NULL && this->system->isRunning()); } bool ParticleBase::isExpired() { return (this->system != NULL && this->system->isExpired()); } void ParticleBase::load(chstr filename) { this->filename = filename; this->stopSystem(); if ((this->filename != "" || this->filepath != "") && apriluiparticle::isEnabled()) { this->_load(); } } void ParticleBase::notifyEvent(chstr name, void* params) { if (name == "SettingsChanged") { if ((this->filename != "" || this->filepath != "") && apriluiparticle::isEnabled()) { this->_load(); } else { this->stopSystem(); } } else if (name == "Resized") { this->_resize(); } aprilui::Object::notifyEvent(name, params); } void ParticleBase::_load() { if (this->system != NULL) { return; } hstr filepath = this->filepath; if (filepath == "") // if no forced file path exists { filepath = this->filename; hstr defaultPath = apriluiparticle::getDefaultPath(); if (defaultPath != "") { filepath = hdir::join_path(defaultPath, filepath, false); } } hstr datasetPath = this->getDataset()->getFilePath(); if (datasetPath != "") { filepath = hdir::join_path(datasetPath, filepath, false); } filepath = hdir::normalize(filepath); this->system = aprilparticle::loadSystem(filepath); this->_resize(); } void ParticleBase::_resize() { if (this->system != NULL) { apriluiparticle::resizeEmitters(this->getSize(), this->system->getEmitters()); } } void ParticleBase::finishSystem() { if (this->system != NULL) { this->system->finish(); } } void ParticleBase::stopSystem() { if (this->system != NULL) { delete this->system; this->system = NULL; } } void ParticleBase::resetSystem() { if (this->system != NULL) { this->system->reset(); } } hstr ParticleBase::getProperty(chstr name, bool* property_exists) { if (property_exists != NULL) { *property_exists = true; } if (name == "filename") return this->getFilename(); if (name == "filepath") return this->getFilepath(); return aprilui::Object::getProperty(name, property_exists); } bool ParticleBase::setProperty(chstr name, chstr value) { if (name == "filename") { this->setFilename(value); this->setFilepath(""); this->notifyEvent("SettingsChanged", NULL); } else if (name == "filepath") { this->setFilepath(value); this->setFilename(""); this->notifyEvent("SettingsChanged", NULL); } else return aprilui::Object::setProperty(name, value); return true; } }
[ "kspes@f2b9c05d-7056-4c2f-abec-aec71e0497c1" ]
kspes@f2b9c05d-7056-4c2f-abec-aec71e0497c1
b59ea7f21ff0f4578505079040dc8e2587012d33
5d83739af703fb400857cecc69aadaf02e07f8d1
/Archive/5662f313779a1b2aa3f4cf81f184d232-f674c1a6d04c632b71a62362c0ccfc51/main.cpp
303372ad92ad06c047a22bb3209ad4dd03976053
[]
no_license
WhiZTiM/coliru
3a6c4c0bdac566d1aa1c21818118ba70479b0f40
2c72c048846c082f943e6c7f9fa8d94aee76979f
refs/heads/master
2021-01-01T05:10:33.812560
2015-08-24T19:09:22
2015-08-24T19:09:22
56,789,706
3
0
null
null
null
null
UTF-8
C++
false
false
378
cpp
#include <iostream> #include <string> #include <vector> template<typename T> std::ostream& operator<<(std::ostream& os, const std::vector<T>& vec) { for (auto& el : vec) { os << el << ' '; } return os; } int main() { std::vector<std::string> words = { "Hello", "from", "GCC", __VERSION__, "!" }; std::cout << words << std::endl;
[ "francis.rammeloo@36614edc-3e3a-acb8-9062-c8ae0e4185df" ]
francis.rammeloo@36614edc-3e3a-acb8-9062-c8ae0e4185df
3ea9a95f12d06f3b4caf94c03ac048c9b8ba8db0
8dedc2459417ca9be0f47d14d517c76e62f008ed
/Volume 002/231 - Testing the CATCHER/231 - Testing the CATCHER.cpp
6045471fb8051565ceea28a213ad8a307ea2ff0c
[]
no_license
MrGolden1/UVA
015375ee9e4004097544370cd0a51b04ffb43699
6f5cbb1fa68e123251c8943a53919c7e514b0135
refs/heads/master
2020-05-22T15:42:41.669232
2019-08-16T21:04:15
2019-08-16T21:04:15
186,413,776
0
0
null
null
null
null
UTF-8
C++
false
false
1,144
cpp
#include <iostream> #include <string> #include <string.h> #include <algorithm> #include <stdio.h> #include <map> #include <stack> #include <queue> #include <math.h> #include <iomanip> using namespace std; #define ull unsigned long long #define infinite 2147483647 #define md 1000000007 int main() { ios::sync_with_stdio(false); int t = 1; int a; while (true) { vector < int > v; cin >> a; if (a == -1) return 0; v.push_back(a); while (true) { cin >> a; if (a == -1) break; v.push_back(a); } int n = v.size(); vector <int> dp(n, 1); int maxi = 1; for (int i = 0; i < n; i++) { for (int j = 0; j < i; j++) { if (v[i] <= v[j]) dp[i] = max(dp[j] + 1, dp[i]); } maxi = max(dp[i], maxi); } if (t != 1) cout << "" + '\n'; printf("Test #%d:\n", t); printf(" maximum possible interceptions: %d\n", maxi); t++; } return 0; }
5798c4360a486eb29efa7cbd512695432d3f7a2a
0d2eab2c7aaf0b78c32c30e7ab484b91e115e8a5
/nicolas/ch4/trajectoryError/include/trajectoryError.h
b62f89e9b75b043dc1ea439f4f8e88eb924654f4
[ "MIT" ]
permissive
nicolasrosa-forks/slambook2
08275c8680e24f3c473667ca8ee595b425ef0d3d
9cae572378fc5da758b6404e45d443b0bde71853
refs/heads/master
2023-05-15T17:52:06.421885
2021-05-12T00:56:31
2021-05-12T00:56:31
312,411,541
0
1
MIT
2021-04-15T14:55:56
2020-11-12T22:31:16
C++
UTF-8
C++
false
false
909
h
/* =========== */ /* Libraries */ /* =========== */ /* System Libraries */ #include <iostream> #include <fstream> #include <unistd.h> #include <iomanip> // std::fixed, std::setprecision /* Eigen3 Libraries */ #include <eigen3/Eigen/Core> #include <eigen3/Eigen/Geometry> /* Sophus Libraries */ #include <sophus/se3.hpp> #include <sophus/so3.hpp> /* Pangolin Library */ #include <pangolin/pangolin.h> /* Custom Libraries */ #include "../../../common/libUtils_basic.h" #include "../../../common/libUtils_eigen.h" /* ===================== */ /* Function Prototypes */ /* ===================== */ typedef vector<Sophus::SE3d, Eigen::aligned_allocator<Sophus::SE3d>> TrajectoryType; typedef vector<double, Eigen::aligned_allocator<double>> TimeStamp; TrajectoryType ReadTrajectory(TimeStamp &timestamps, const string &path); void DrawTrajectory(const TrajectoryType &est, const TrajectoryType &gt);
02f1dcd80682763ef6fa7597b9908346867d99bf
b066028fea8c16eb9134bf94024a3962ca14ca97
/lib/libgsmo/gmb_cols.cc
2e0952b3ad395048b6a60eb4658e36d67f92cb0c
[ "MIT" ]
permissive
elifesciences-publications/bpps-sipris-code
9afa7646079f1da44f82539e8b8f472e46286374
3c5382489c5e6aeca20c93b7ba2907b19fad3cf7
refs/heads/master
2021-05-14T03:59:31.629499
2017-10-04T19:12:20
2017-10-04T19:12:20
116,630,816
0
0
null
null
null
null
UTF-8
C++
false
false
15,460
cc
/****************************************************************************************** Copyright (C) 1997-2014 Andrew F. Neuwald, Cold Spring Harbor Laboratory and the University of Maryland School of Medicine. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. For further information contact: Andrew F. Neuwald Institute for Genome Sciences and Department of Biochemistry & Molecular Biology University of Maryland School of Medicine 801 West Baltimore St. BioPark II, Room 617 Baltimore, MD 21201 Tel: 410-706-6724; Fax: 410-706-1482; E-mail: [email protected] ******************************************************************************************/ #include "gmb_typ.h" #define Debug_FB 0 char *gmb_typ::FindBlocks(ssx_typ *ssx, char mode, double cutoff, double bild_cut,Int4 Limit) { // ssx->InitNDL(0.0); // initialize model parameters. cma_typ cma=ssx->RtnCMA(),rcma=0,xcma=cma; assert(nBlksCMSA(cma) == 1); FILE *efp=0; // efp=stderr; Int4 blk=1,i,j,*N_INS,*INS_RES,n_ins,n_del,ins_res; char *Report,c; double *BILD,d,D,*deleted,BS,BSps,TotalWtSq=ssx->TotalWtSeq(); enum location { start, middle, end, stop }; BooLean trigger; //=============== 1. Allocate memory. ================ location *SITE; NEW(SITE,LengthCMSA(blk,cma) +3, location); NEW(Report,LengthCMSA(blk,cma) +3, char); NEW(BILD,LengthCMSA(blk,cma) +3, double); NEW(N_INS,LengthCMSA(blk,cma) +3, Int4); NEW(INS_RES,LengthCMSA(blk,cma) +3, Int4); //=============== 2. Compute data. ================ double **xBS=BILD_ScoresCMSA(ssx),*BldSc=xBS[1]; free(xBS); for(SITE[0]=end, i=1; i <= LengthCMSA(blk,cma); i++){ Report[i]=' '; #if 0 BILD[i]=ssx->BildScore(blk,i); #else BILD[i]=ssx->ContextBildScore(blk,i,BldSc); #endif n_ins=NumInsertsCMSA(blk,i,cma,ins_res); N_INS[i]=n_ins; INS_RES[i]=ins_res; #if Debug_FB if(n_ins > 0){ d=(double)n_ins/(double)NumAlnSeqsCMSA(cma); fprintf(stderr,"%d. n_ins=%d; ins_res=%d (%.2f vs %.2f)\n",i,n_ins,ins_res,d,cutoff); } #endif if(mode == 'A'){ // AddColumns() mode. d=(double)n_ins/(double)NumAlnSeqsCMSA(cma); // d=(double)n_ins/(double)NumSeqsCMSA(cma); if(d >= cutoff) trigger=TRUE; else trigger=FALSE; } else if(mode =='R'){ // RmColumns() mode; treat this as start of a "block". if(ins_res > 10) trigger=TRUE; else trigger=FALSE; } else { // RmShortBlk() mode. if(ins_res > 10) trigger=TRUE; else trigger=FALSE; } if(trigger){ SITE[i]=end; SITE[i+1]=start; } else if(SITE[i-1]==end) SITE[i]=start; else SITE[i]=middle; } i=LengthCMSA(blk,cma); SITE[i]=end; SITE[i+1]=stop; Report[0]=Report[i+1]=' '; free(BldSc); if(mode== 'A'){ // for AddColumns() //=============== 3. Find columns next to insertions. ================ for(i=1; i <= LengthCMSA(blk,cma); i++){ if(SITE[i] == middle) continue; switch (SITE[i]) { case start: Report[i]='B'; break; // insert column before.. case end: Report[i]='A'; break; // insert column after... default: print_error("FindBlocks(): This should not happen"); } } } else if(mode == 'R'){ // for RmColumns() //=============== 3. Label bad columns at start or end of blocks. ================ Int4 *NDEL=0; if(cutoff > 0){ NEW(NDEL, LengthCMSA(blk,cma)+9, Int4); for(i=1; i <= LengthCMSA(blk,cma); i++) NDEL[i]=NumDeletionsCMSA(blk,i,cma); } #if 1 // avoid removing all columns... double Cutoff=cutoff, Bild_cut=bild_cut,mfact=0.0,inc=0.05,dfact=1.0; do { Int4 num_cols=0,ndel=0,nbild=0,nboth=0; for(i=1; i <= LengthCMSA(blk,cma); i++){ d=(double)NDEL[i]/(double)NumAlnSeqsCMSA(cma); if(BILD[i] >= bild_cut && d <= cutoff){ nboth++; num_cols++; } if(BILD[i] >= bild_cut){ nbild++; } if(d <= cutoff){ ndel++; } } if(efp) fprintf(stderr,"%d columns retained; nbild=%d; ndel=%d; NumSeqs=%d (%.3g; %.3g; %d)\n", num_cols,nbild,ndel,NumAlnSeqsCMSA(cma),bild_cut,cutoff,Limit); if(num_cols < Limit){ // Limit == 3 by default... if(nbild < ndel){ // fewer BILD-signifcant columns than filled columns. mfact = mfact + inc; // mfact = 0.05, 0.10, 0.15, 0.25...10.0 d=fabs(bild_cut)*mfact; bild_cut = Bild_cut - d; } else { // fewer filled columns than BILD-signifcant columns. dfact = dfact + inc; // mfact = 0.50, 0.55, 0.60, ... 0.75 cutoff = Cutoff * dfact; // e.g., cutoff = 0.50 ... 0.75 } if(efp){ // WriteCMSA("junk.cma",cma); fprintf(stderr,"%d high deletion columns retained\n",ndel); fprintf(stderr,"%d BILD scored columns retained\n",nbild); fprintf(stderr,"Too many columns removed; adjusting BILD parameter (%.3g)\n",bild_cut); } } else break; } while(mfact < 10.0 && cutoff <= 0.75); #endif for(i=1; i <= LengthCMSA(blk,cma); i++){ if(BILD[i] >= bild_cut) continue; if(SITE[i] == middle) continue; switch (SITE[i]) { case start: do { Report[i]='*'; i++; } while(BILD[i] < bild_cut && SITE[i] != stop); break; case end: j=i; do { Report[j]='*'; j--; } while(j > 0 && BILD[j] < bild_cut && Report[j] == ' '); break; default: print_error("FindBlocks(): This should not happen"); } } #if 1 // if fraction of deletions > cutoff then remove the column. if(cutoff > 0){ for(i=1; i <= LengthCMSA(blk,cma); i++){ d=(double)NDEL[i]/(double)NumAlnSeqsCMSA(cma); if(d > cutoff) Report[i]='*'; } } free(NDEL); #endif } else { // for RmShortBlk() ... //=============== 4. Label short blocks. ================ #if 0 for(j=0,i=1; i <= LengthCMSA(blk,cma); i++){ if(SITE[i] == start) j=0; if(Report[i]==' '){ j++; continue; } if(Report[i]=='*'){ if(j < 3){ while(j > 0){ Report[i-j]='*'; j--; } } j=0; } } #else // New: remove all short blocks... for(j=0, i=1; i <= LengthCMSA(blk,cma); i++){ if(SITE[i] == start) j=1; else if(SITE[i] == end){ if(j < 3){ while(j >= 0){ Report[i-j]='*'; j--; } } j=0; } else { assert(SITE[i] == middle); j++; } } #endif } //=============== 4. Print out results. ================ if(0){ // for testing... this->RtnMap(); for(i=1; i <= LengthCMSA(blk,cma); i++){ BS=BILD[i]; BSps=BS/TotalWtSq; n_del=NumDeletionsCMSA(blk,i,cma); n_ins=N_INS[i]; ins_res=INS_RES[i]; switch (SITE[i]) { case start: c='S'; break; case middle: c=' '; break; case end: c='E'; break; default: print_error("FindBlocks(): This should not happen"); } fprintf(stderr,"%c%c%d: bild=%.1f (%.2f npws); ins=%d (%d) del=%d (%.1f%c).\n", c,Report[i],i,BS,BSps,n_ins,ins_res,n_del,100.0*FractDeletionsCMSA(blk,i,cma),'%'); if(ins_res > 10) ssx->PutPenalties(stderr,blk,i); else if(cutoff <= 0 && c==' ' && ins_res > 0) ssx->PutPenalties(stderr,blk,i); } fprintf(stderr,"\n\n %s\n",Report+1); } free(BILD); free(N_INS); free(INS_RES); free(SITE); return Report; } #define debug_AC 0 cma_typ gmb_typ::AddColumns(double bild_cut, BooLean Widen, set_typ InSet, double MinMatchFrq, BooLean EndsOnly) { Int4 blk=1,i,j,x,startA,endA,startB,endB,numcol,maxcols=4; cma_typ cma=SSX->RtnCMA(),rcma=0,xcma=cma,bcma,acma; double d,BS,bBS,aBS,prior_wt=SSX->GetPriorWt(); BooLean improved,found; str_typ *head = new str_typ('E'),*Str=head,*tail; if(this->AddOp){ x=strlen(this->AddOp); assert(x == (LengthCMSA(blk,cma)+2)); for(i=1; i <= LengthCMSA(blk,cma); i++){ Str->Append(AddOp[i]); Str=Str->Next(); } } else for(i=1; i <= LengthCMSA(blk,cma); i++){ Str->Append('m'); Str=Str->Next(); } Str->Append('E'); tail=Str->Next(); // head->Print(stderr); // if(EndsOnly) Widen=TRUE; SSX->InitNDL(0.0); // initialize model parameters. do { improved=FALSE; gmb_typ *xgmb= new gmb_typ(aa_per_io,aa_per_do,exp_ie,exp_de,xcma,dms_mode,prior_wt); char *BeforeOrAfter=this->FindBlocks(xgmb->RtnSSX(),'A',MinMatchFrq,bild_cut); delete xgmb; if(Widen){ endA=LengthCMSA(blk,xcma); startA=1; endB=endA; startB=1; } else { endA=LengthCMSA(blk,xcma)-1; startA=1; endB=endA+1; startB=startA+1; } for(Str=tail->Prev(),i=LengthCMSA(blk,xcma); i >= 0; Str=Str->Prev(),i--) // for(Str=tail->Prev(),i=105; i >= 100; Str=Str->Prev(),i--) { for(found=FALSE,numcol=1; numcol <= maxcols; numcol++){ j=i+1; BS=-999999999; #if debug_AC fprintf(stderr,"%d. Try adding %d cols: BOA[j=%d]=%c; BOA[i=%d]=%c.\n", i,numcol,j,BeforeOrAfter[j],i,BeforeOrAfter[i]); #endif if(BeforeOrAfter[j] == 'B' || BeforeOrAfter[i] == 'A'){ if(i > endA || i < startA){ acma=0; aBS=-99999999; } else { // Add column AFTER position i. if(i == LengthCMSA(blk,xcma)) acma=ExtendBlkCMSA(xcma, blk,0,numcol); else acma=InsertColumnsCMSA(xcma,blk,i,numcol); xgmb=new gmb_typ(aa_per_io,aa_per_do,exp_ie,exp_de,acma,dms_mode,prior_wt); // xgmb->SetPriorWt(prior_wt); aBS=xgmb->ScoreBILD(blk,i+numcol); ssx_typ *xssx=xgmb->RtnSSX(); d=xssx->RtnPercentGaps(blk,i+numcol); #if debug_AC fprintf(stderr,"A %d: BS=%.2f(cut=%.2f)[%d] ", i+numcol,aBS,bild_cut,NumAlnSeqsCMSA(acma)); xssx->PutWtCnts(stderr,blk,i+numcol); #endif delete xgmb; if(d >= 50.0){ if(acma) NilCMSA(acma); acma=0; aBS = -9999999.0; } } if(j > endB || j < startB){ bcma=0; bBS=-9999999; } else { // add column before position j. if(j == 1) bcma=ExtendBlkCMSA(xcma, blk,numcol,0); else bcma=InsertColumnsCMSA(xcma,blk,j,-numcol); xgmb=new gmb_typ(aa_per_io,aa_per_do,exp_ie,exp_de,bcma,dms_mode,prior_wt); bBS=xgmb->ScoreBILD(blk,i+1); ssx_typ *xssx=xgmb->RtnSSX(); d=xssx->RtnPercentGaps(blk,i+1); #if debug_AC fprintf(stderr,"B %d: BS=%.2f(cut=%.2f)[%d] ", i+1,bBS,bild_cut,NumAlnSeqsCMSA(bcma)); xssx=xgmb->RtnSSX(); xssx->PutWtCnts(stderr,blk,i+1); #endif delete xgmb; if(d >= 50.0){ if(bcma) NilCMSA(bcma); bcma=0; bBS = -9999999.0; } } if(aBS > bBS){ if(bcma) NilCMSA(bcma); bcma=0; BS=aBS; rcma=acma; } else { if(acma) NilCMSA(acma); acma=0; BS=bBS; rcma=bcma; } if(rcma==0){ numcol=maxcols; continue; } // Need not lengthen any further. if(BS < bild_cut){ if(rcma) NilCMSA(rcma); rcma=0; continue; } else { // if(bcma) for(x=1; x <= numcol; x++){ Str=Str->Prev(); Str->Append('d'); } else for(x=1; x <= numcol; x++){ Str->Append('d'); } found=TRUE; } } if(found){ #if debug_AC if(bcma) fprintf(stderr,"Added %d columns before position %d\n",numcol,j); if(acma) fprintf(stderr,"Added %d column after position %d\n",numcol,i); #endif if(xcma != cma) NilCMSA(xcma); xcma=rcma; improved=TRUE; Str=Str->Next(); i++; break; // break from numcol loop... } } if(found) break; // break from i loop. } free(BeforeOrAfter); } while(improved); // head->Print(); if(AddOp) free(AddOp); AddOp=head->Return(); AddOp[1]=toupper(AddOp[1]); // fprintf(stderr,"%s\n",AddOp); // exit(1); delete head; if(xcma != cma) return xcma; else return 0; } cma_typ gmb_typ::RmColumns(double bild_cut,BooLean Shrink,double MinDelFrq) { SSX->InitNDL(0.0); // initialize model parameters. cma_typ cma=SSX->RtnCMA(),rcma=0,xcma=cma; Int4 limit=3,i,j,blk=1,start,end,Len=LengthCMSA(blk,xcma); char c,*ToRm=this->FindBlocks(this->RtnSSX(),'R',MinDelFrq,bild_cut,limit); #if 0 str_typ *head = new str_typ('E'),*Str=head,*tail; assert(this->AddOp == 0); // free up before using this!! if(this->AddOp){ x=strlen(this->AddOp); assert(x == (LengthCMSA(blk,cma)+2)); for(i=1; i <= LengthCMSA(blk,cma); i++){ Str->Append(AddOp[i]); Str=Str->Next(); } } else for(i=1; i <= LengthCMSA(blk,cma); i++){ Str->Append('m'); Str=Str->Next(); } Str->Append('E'); tail=Str->Next(); // head->Print(stderr); #else assert(this->AddOp == 0); // free up before using this!! #endif if(Shrink){ end=LengthCMSA(blk,xcma); start=0; } else { end=LengthCMSA(blk,xcma)-1; start=1; } for(i=end; i > start; i--){ if(ToRm[i] != '*') continue; for(j=i; ToRm[j-1] == '*'; ) j--; if(i == LengthCMSA(blk,xcma)){ // assert(LengthCMSA(blk,xcma) >= ((i-j+1)+limit)); rcma=TrimBlkCMSA(xcma,blk,0,i-j+1,limit); i=j; // Blk=1; RmLeft=0; RmRight=i-j+1. if(rcma==0) print_error("gmb_typ::RmColumns(): too many aligned columns removed"); } else if(j==1){ // fprintf(stderr,"'%s'\n",ToRm); // assert(LengthCMSA(blk,xcma) >= (i+limit)); rcma=TrimBlkCMSA(xcma,blk,i,0,limit); i=j; // Blk=1; RmLeft=i; RmRight=0. if(rcma==0) print_error("gmb_typ::RmColumns(): too many columns removed from alignment"); } else { rcma=ConvertColsToInsertsCMSA(xcma,1,j,i); i=j; } if(xcma != cma) NilCMSA(xcma); xcma=rcma; } if(!Shrink){ // this->AddOp=rtn... char *rtn; NEW(rtn, Len+5, char); this->AddOp=rtn; rtn[0]='E'; rtn[1]='M'; for(j=2; j <= end && (c=ToRm[j]); j++){ if(c=='*') rtn[j]='d'; else rtn[j]='m'; } rtn[j]='m'; j++; rtn[j]='E'; j++; rtn[j]=0; // assume extra length added by FindBlocks(); } free(ToRm); assert(NumColumnsCMSA(xcma) >= 3); if(xcma != cma) return xcma; else return 0; } cma_typ gmb_typ::RmShortBlks(double bild_cut,BooLean Shrink) { // return 0; SSX->InitNDL(0.0); // initialize model parameters. cma_typ cma=SSX->RtnCMA(),rcma=0,xcma=cma; char *ToRm=this->FindBlocks(this->RtnSSX(),'S',-1.0,bild_cut); Int4 i,j,blk=1,start,end; double BS; if(Shrink){ end=LengthCMSA(blk,xcma); start=0; } else { end=LengthCMSA(blk,xcma)-1; start=1; } for(i=end; i > start; i--){ if(ToRm[i] != '*') continue; for(j=i; ToRm[j-1] == '*'; ) j--; if(i == LengthCMSA(blk,xcma)){ rcma=TrimBlkCMSA(xcma,1,0,i-j+1,1); i=j; // Blk=1; RmLeft=0; RmRight=i-j+1; limit=1. if(rcma==0) print_error("TrimBlkCMSA(): too many columns removed from alignment"); } else if(j==1){ rcma=TrimBlkCMSA(xcma,1,i,0,1); i=j; // Blk=1; RmLeft=i; RmRight=0; limit=1. if(rcma==0) print_error("TrimBlkCMSA(): too many columns removed from alignment"); } else { rcma=ConvertColsToInsertsCMSA(xcma,1,j,i); i=j; } if(xcma != cma) NilCMSA(xcma); xcma=rcma; } free(ToRm); if(xcma != cma) return xcma; else return 0; }
[ "aneuwald@bf312fdc-5263-4627-9904-0a588619bb94" ]
aneuwald@bf312fdc-5263-4627-9904-0a588619bb94
5232b9a2a12dbfaa52334c8bac040f055a1252fc
dcec9c2353abd339b42ca7b2d2c799dc7135624c
/BinaryGenerator/bgSymbol.h
83cc589d7145dd9f6eeb75e2062a46220a93a5dd
[]
no_license
gitmesam/BinaryGenerator
2fe5f878b93aa9ddf36e382c6326719a22cea29e
cec4a2316e368bf052c267be5be9a998f8b3333e
refs/heads/master
2022-01-20T22:56:44.818991
2019-05-10T02:29:40
2019-05-10T02:29:40
null
0
0
null
null
null
null
UTF-8
C++
false
false
461
h
#pragma once namespace bg { class SymbolTable { public: using Symbols = std::vector<Symbol>; public: SymbolTable(Context *ctx); SymbolTable(Context *ctx, const SymbolTable& base); Symbols& getSymbols(); Symbol& addSymbol(const Symbol& sym); Symbol* getSymbol(size_t i); Symbol* findSymbol(const char *name); uint32 getVirtualAddress(const char *name); private: Context *m_ctx; Symbols m_symbols; }; } // namespace bg
df1b7be62418a1774597d738a17742f639cb8434
7bb1cd3b6ab160eef592e7d7d14120d299b61ee4
/codeforces/A/501A.cpp
6b289b94b6d9eb2c891a4531d1332635cd664d6a
[]
no_license
naveenchopra9/cp
d986a3e8c650903b8bec8c4b0665c3ef664e251a
0f271204b2675a366f0b92081ec67a97efc5883a
refs/heads/master
2020-05-16T12:38:25.063272
2019-04-23T16:12:46
2019-04-23T16:12:46
183,051,510
0
0
null
null
null
null
UTF-8
C++
false
false
737
cpp
#include "/Users/naveen/stdc++.h" //#include <bits/stdc++.h> using namespace std; #define MAXV 2147483647 #define MINV -2147483647 #define SYC ios_base::sync_with_stdio(0); cin.tie(0) #define ll unsigned long long int #define For(i,n) for(int i =0 ; i< n ; i++) #define M 1000000007 #define FR freopen("/Users/naveen/Documents/online_code/input.txt","r",stdin) #define FW freopen("/Users/naveen/Documents/online_code/output.txt","w",stdout) int a[100000+5]; int main(){ int a,b,c,d; cin>>a>>b>>c>>d; int aa=max((3*a)/10,a-((a/250)*c)); int bb=max((3*b)/10,b-((b/250)*d)); if(aa==bb)cout<<"Tie"<<endl; else if(aa<bb){ cout<<"Vasya"<<endl; } else{ cout<<"Misha"<<endl; } return 0; }
b47bcba10189080e95bd734c29e23b2298c136bb
5fcc718e15e951bb0ef3fae7816ee2f33cfced82
/bankrobbery.cpp
3aafc5019b444f8ee9738747701cc21fae8fa579
[]
no_license
Shubhamsingh147/Codechef-Hackerrank-Hackerearth-etc
27ec108b05350222829450d9da8f66bfe1ebd085
8974aa238d3609a61f0003bee5fb56c3e2b31b01
refs/heads/master
2021-01-19T04:24:32.494028
2016-06-01T09:21:58
2016-06-01T09:21:58
60,162,140
0
0
null
null
null
null
UTF-8
C++
false
false
359
cpp
#include <iostream> #include <iomanip> #include <cmath> using namespace std; int main(){ int t,m; double p; cin>>t; while(t--){ cin>>m>>p; if(m%2 == 1) cout<<"1000000000.0 0.0"<<endl; else{ double two = 1000000000.0 * p; cout << setprecision(1) << fixed << 1000000000.0 - two<<" "; cout << setprecision(1) << fixed << two<<endl; } } }
c5236df6c142ef8a86120f1c2008fd6bf0de6eae
fe39e4d1bca62d7bff7b6713b8b596d88f8aa354
/src/plugins/3rdparty/LLVM/tools/clang/include/clang/Basic/ObjCRuntime.h
a805299fd70a35e669b7fb4b17c32060d6acdb90
[]
no_license
panpanSun/opencor
a29a806475f43adb0f64047631d4dc044f05e030
71449e1ecaa988ea8b6cfea7875d9f3593a8dc26
refs/heads/master
2020-12-24T11:53:33.902565
2013-04-20T18:59:29
2013-04-20T18:59:29
null
0
0
null
null
null
null
UTF-8
C++
false
false
8,739
h
//===--- ObjCRuntime.h - Objective-C Runtime Configuration ------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// /// /// \file /// \brief Defines types useful for describing an Objective-C runtime. /// //===----------------------------------------------------------------------===// #ifndef LLVM_CLANG_OBJCRUNTIME_H #define LLVM_CLANG_OBJCRUNTIME_H #include "clang/Basic/VersionTuple.h" #include "llvm/ADT/Triple.h" #include "llvm/Support/ErrorHandling.h" namespace clang { /// \brief The basic abstraction for the target Objective-C runtime. class ObjCRuntime { public: /// \brief The basic Objective-C runtimes that we know about. enum Kind { /// 'macosx' is the Apple-provided NeXT-derived runtime on Mac OS /// X platforms that use the non-fragile ABI; the version is a /// release of that OS. MacOSX, /// 'macosx-fragile' is the Apple-provided NeXT-derived runtime on /// Mac OS X platforms that use the fragile ABI; the version is a /// release of that OS. FragileMacOSX, /// 'ios' is the Apple-provided NeXT-derived runtime on iOS or the iOS /// simulator; it is always non-fragile. The version is a release /// version of iOS. iOS, /// 'gcc' is the Objective-C runtime shipped with GCC, implementing a /// fragile Objective-C ABI GCC, /// 'gnustep' is the modern non-fragile GNUstep runtime. GNUstep, /// 'objfw' is the Objective-C runtime included in ObjFW ObjFW }; private: Kind TheKind; VersionTuple Version; public: /// A bogus initialization of the runtime. ObjCRuntime() : TheKind(MacOSX) {} ObjCRuntime(Kind kind, const VersionTuple &version) : TheKind(kind), Version(version) {} void set(Kind kind, VersionTuple version) { TheKind = kind; Version = version; } Kind getKind() const { return TheKind; } const VersionTuple &getVersion() const { return Version; } /// \brief Does this runtime follow the set of implied behaviors for a /// "non-fragile" ABI? bool isNonFragile() const { switch (getKind()) { case FragileMacOSX: return false; case GCC: return false; case MacOSX: return true; case GNUstep: return true; case ObjFW: return false; case iOS: return true; } llvm_unreachable("bad kind"); } /// The inverse of isNonFragile(): does this runtime follow the set of /// implied behaviors for a "fragile" ABI? bool isFragile() const { return !isNonFragile(); } /// The default dispatch mechanism to use for the specified architecture bool isLegacyDispatchDefaultForArch(llvm::Triple::ArchType Arch) { // The GNUstep runtime uses a newer dispatch method by default from // version 1.6 onwards if (getKind() == GNUstep && getVersion() >= VersionTuple(1, 6)) { if (Arch == llvm::Triple::arm || Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64) return false; // Mac runtimes use legacy dispatch everywhere except x86-64 } else if (isNeXTFamily() && isNonFragile()) return Arch != llvm::Triple::x86_64; return true; } /// \brief Is this runtime basically of the GNUstep family of runtimes? bool isGNUFamily() const { switch (getKind()) { case FragileMacOSX: case MacOSX: case iOS: return false; case GCC: case GNUstep: case ObjFW: return true; } llvm_unreachable("bad kind"); } /// \brief Is this runtime basically of the NeXT family of runtimes? bool isNeXTFamily() const { // For now, this is just the inverse of isGNUFamily(), but that's // not inherently true. return !isGNUFamily(); } /// \brief Does this runtime allow ARC at all? bool allowsARC() const { switch (getKind()) { case FragileMacOSX: return false; case MacOSX: return true; case iOS: return true; case GCC: return false; case GNUstep: return true; case ObjFW: return true; } llvm_unreachable("bad kind"); } /// \brief Does this runtime natively provide the ARC entrypoints? /// /// ARC cannot be directly supported on a platform that does not provide /// these entrypoints, although it may be supportable via a stub /// library. bool hasNativeARC() const { switch (getKind()) { case FragileMacOSX: return false; case MacOSX: return getVersion() >= VersionTuple(10, 7); case iOS: return getVersion() >= VersionTuple(5); case GCC: return false; case GNUstep: return getVersion() >= VersionTuple(1, 6); case ObjFW: return true; } llvm_unreachable("bad kind"); } /// \brief Does this runtime supports optimized setter entrypoints? bool hasOptimizedSetter() const { switch (getKind()) { case MacOSX: return getVersion() >= VersionTuple(10, 8); case iOS: return (getVersion() >= VersionTuple(6)); default: return false; } } /// Does this runtime allow the use of __weak? bool allowsWeak() const { return hasNativeWeak(); } /// \brief Does this runtime natively provide ARC-compliant 'weak' /// entrypoints? bool hasNativeWeak() const { // Right now, this is always equivalent to whether the runtime // natively supports ARC decision. return hasNativeARC(); } /// \brief Does this runtime directly support the subscripting methods? /// /// This is really a property of the library, not the runtime. bool hasSubscripting() const { switch (getKind()) { case FragileMacOSX: return false; case MacOSX: return getVersion() >= VersionTuple(10, 8); case iOS: return getVersion() >= VersionTuple(6); // This is really a lie, because some implementations and versions // of the runtime do not support ARC. Probably -fgnu-runtime // should imply a "maximal" runtime or something? case GCC: return true; case GNUstep: return true; case ObjFW: return true; } llvm_unreachable("bad kind"); } /// \brief Does this runtime allow sizeof or alignof on object types? bool allowsSizeofAlignof() const { return isFragile(); } /// \brief Does this runtime allow pointer arithmetic on objects? /// /// This covers +, -, ++, --, and (if isSubscriptPointerArithmetic() /// yields true) []. bool allowsPointerArithmetic() const { switch (getKind()) { case FragileMacOSX: case GCC: return true; case MacOSX: case iOS: case GNUstep: case ObjFW: return false; } llvm_unreachable("bad kind"); } /// \brief Is subscripting pointer arithmetic? bool isSubscriptPointerArithmetic() const { return allowsPointerArithmetic(); } /// \brief Does this runtime provide an objc_terminate function? /// /// This is used in handlers for exceptions during the unwind process; /// without it, abort() must be used in pure ObjC files. bool hasTerminate() const { switch (getKind()) { case FragileMacOSX: return getVersion() >= VersionTuple(10, 8); case MacOSX: return getVersion() >= VersionTuple(10, 8); case iOS: return getVersion() >= VersionTuple(5); case GCC: return false; case GNUstep: return false; case ObjFW: return false; } llvm_unreachable("bad kind"); } /// \brief Does this runtime support weakly importing classes? bool hasWeakClassImport() const { switch (getKind()) { case MacOSX: return true; case iOS: return true; case FragileMacOSX: return false; case GCC: return true; case GNUstep: return true; case ObjFW: return true; } llvm_unreachable("bad kind"); } /// \brief Does this runtime use zero-cost exceptions? bool hasUnwindExceptions() const { switch (getKind()) { case MacOSX: return true; case iOS: return true; case FragileMacOSX: return false; case GCC: return true; case GNUstep: return true; case ObjFW: return true; } llvm_unreachable("bad kind"); } /// \brief Try to parse an Objective-C runtime specification from the given /// string. /// /// \return true on error. bool tryParse(StringRef input); std::string getAsString() const; friend bool operator==(const ObjCRuntime &left, const ObjCRuntime &right) { return left.getKind() == right.getKind() && left.getVersion() == right.getVersion(); } friend bool operator!=(const ObjCRuntime &left, const ObjCRuntime &right) { return !(left == right); } }; raw_ostream &operator<<(raw_ostream &out, const ObjCRuntime &value); } // end namespace clang #endif
6d3c81346d026c98c1674c5cdb92017e83c381af
5b07de510fd36829ccec2704340d6aa4e2d88bb7
/src/wallet.cpp
6793b587ecf98502fd90289521860ba958356be5
[]
no_license
wyh136/DECENT
b12f8222b4d803b526ebcdf6076891cfd06b4fa1
9785af7faab5e834463999959ce85e5287b96ca4
refs/heads/master
2021-01-20T11:34:53.214816
2016-09-06T17:11:42
2016-09-06T17:11:42
null
0
0
null
null
null
null
UTF-8
C++
false
false
94,419
cpp
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2012 The Bitcoin developers // Copyright (c) 2011-2013 The Peercoin developers // Copyright (c) 2015-2015 The Decent developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "wallet.h" #include "walletdb.h" #include "crypter.h" #include "ui_interface.h" #include "kernel.h" #include "bitcoinrpc.h" #include "encryptionutils.h" using namespace std; ////////////////////////////////////////////////////////////////////////////// // // mapWallet // std::vector<unsigned char> CWallet::GenerateNewKey() { bool fCompressed = CanSupportFeature(FEATURE_COMPRPUBKEY); // default to compressed public keys if we want 0.6.0 wallets RandAddSeedPerfmon(); CKey key; key.MakeNewKey(fCompressed); // Compressed public keys were introduced in version 0.6.0 if (fCompressed) SetMinVersion(FEATURE_COMPRPUBKEY); if (!AddKey(key)) throw std::runtime_error("CWallet::GenerateNewKey() : AddKey failed"); return key.GetPubKey(); } bool CWallet::AddKey(const CKey& key) { if (!CCryptoKeyStore::AddKey(key)) return false; if (!fFileBacked) return true; if (!IsCrypted()) return CWalletDB(strWalletFile).WriteKey(key.GetPubKey(), key.GetPrivKey()); return true; } bool CWallet::AddCryptedKey(const vector<unsigned char> &vchPubKey, const vector<unsigned char> &vchCryptedSecret) { if (!CCryptoKeyStore::AddCryptedKey(vchPubKey, vchCryptedSecret)) return false; if (!fFileBacked) return true; { LOCK(cs_wallet); if (pwalletdbEncryption) return pwalletdbEncryption->WriteCryptedKey(vchPubKey, vchCryptedSecret); else return CWalletDB(strWalletFile).WriteCryptedKey(vchPubKey, vchCryptedSecret); } return false; } bool CWallet::AddCScript(const CScript& redeemScript) { if (!CCryptoKeyStore::AddCScript(redeemScript)) return false; if (!fFileBacked) return true; return CWalletDB(strWalletFile).WriteCScript(Hash160(redeemScript), redeemScript); } // peercoin: optional setting to unlock wallet for block minting only; // serves to disable the trivial sendmoney when OS account compromised bool fWalletUnlockMintOnly = false; bool CWallet::Unlock(const SecureString& strWalletPassphrase) { if (!IsLocked()) return false; CCrypter crypter; CKeyingMaterial vMasterKey; { LOCK(cs_wallet); BOOST_FOREACH(const MasterKeyMap::value_type& pMasterKey, mapMasterKeys) { if(!crypter.SetKeyFromPassphrase(strWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod)) return false; if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, vMasterKey)) return false; if (CCryptoKeyStore::Unlock(vMasterKey)) return true; } } return false; } bool CWallet::ChangeWalletPassphrase(const SecureString& strOldWalletPassphrase, const SecureString& strNewWalletPassphrase) { bool fWasLocked = IsLocked(); { LOCK(cs_wallet); Lock(); CCrypter crypter; CKeyingMaterial vMasterKey; BOOST_FOREACH(MasterKeyMap::value_type& pMasterKey, mapMasterKeys) { if(!crypter.SetKeyFromPassphrase(strOldWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod)) return false; if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, vMasterKey)) return false; if (CCryptoKeyStore::Unlock(vMasterKey)) { int64 nStartTime = GetTimeMillis(); crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod); pMasterKey.second.nDeriveIterations = pMasterKey.second.nDeriveIterations * (100 / ((double)(GetTimeMillis() - nStartTime))); nStartTime = GetTimeMillis(); crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod); pMasterKey.second.nDeriveIterations = (pMasterKey.second.nDeriveIterations + pMasterKey.second.nDeriveIterations * 100 / ((double)(GetTimeMillis() - nStartTime))) / 2; if (pMasterKey.second.nDeriveIterations < 25000) pMasterKey.second.nDeriveIterations = 25000; printf("Portfolio passphrase changed to an nDeriveIterations of %i\n", pMasterKey.second.nDeriveIterations); if (!crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod)) return false; if (!crypter.Encrypt(vMasterKey, pMasterKey.second.vchCryptedKey)) return false; CWalletDB(strWalletFile).WriteMasterKey(pMasterKey.first, pMasterKey.second); if (fWasLocked) Lock(); return true; } } } return false; } void CWallet::SetBestChain(const CBlockLocator& loc) { CWalletDB walletdb(strWalletFile); walletdb.WriteBestBlock(loc); } // This class implements an addrIncoming entry that causes pre-0.4 // clients to crash on startup if reading a private-key-encrypted wallet. class CCorruptAddress { public: IMPLEMENT_SERIALIZE ( if (nType & SER_DISK) READWRITE(nVersion); ) }; bool CWallet::SetMinVersion(enum WalletFeature nVersion, CWalletDB* pwalletdbIn, bool fExplicit) { if (nWalletVersion >= nVersion) return true; // when doing an explicit upgrade, if we pass the max version permitted, upgrade all the way if (fExplicit && nVersion > nWalletMaxVersion) nVersion = FEATURE_LATEST; nWalletVersion = nVersion; if (nVersion > nWalletMaxVersion) nWalletMaxVersion = nVersion; if (fFileBacked) { CWalletDB* pwalletdb = pwalletdbIn ? pwalletdbIn : new CWalletDB(strWalletFile); if (nWalletVersion >= 40000) { // Versions prior to 0.4.0 did not support the "minversion" record. // Use a CCorruptAddress to make them crash instead. CCorruptAddress corruptAddress; pwalletdb->WriteSetting("addrIncoming", corruptAddress); } if (nWalletVersion > 40000) pwalletdb->WriteMinVersion(nWalletVersion); if (!pwalletdbIn) delete pwalletdb; } return true; } bool CWallet::SetMaxVersion(int nVersion) { // cannot downgrade below current version if (nWalletVersion > nVersion) return false; nWalletMaxVersion = nVersion; return true; } bool CWallet::EncryptWallet(const SecureString& strWalletPassphrase) { if (IsCrypted()) return false; CKeyingMaterial vMasterKey; RandAddSeedPerfmon(); vMasterKey.resize(WALLET_CRYPTO_KEY_SIZE); RAND_bytes(&vMasterKey[0], WALLET_CRYPTO_KEY_SIZE); CMasterKey kMasterKey; RandAddSeedPerfmon(); kMasterKey.vchSalt.resize(WALLET_CRYPTO_SALT_SIZE); RAND_bytes(&kMasterKey.vchSalt[0], WALLET_CRYPTO_SALT_SIZE); CCrypter crypter; int64 nStartTime = GetTimeMillis(); crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, 25000, kMasterKey.nDerivationMethod); kMasterKey.nDeriveIterations = 2500000 / ((double)(GetTimeMillis() - nStartTime)); nStartTime = GetTimeMillis(); crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod); kMasterKey.nDeriveIterations = (kMasterKey.nDeriveIterations + kMasterKey.nDeriveIterations * 100 / ((double)(GetTimeMillis() - nStartTime))) / 2; if (kMasterKey.nDeriveIterations < 25000) kMasterKey.nDeriveIterations = 25000; printf("Encrypting portfolio with an nDeriveIterations of %i\n", kMasterKey.nDeriveIterations); if (!crypter.SetKeyFromPassphrase(strWalletPassphrase, kMasterKey.vchSalt, kMasterKey.nDeriveIterations, kMasterKey.nDerivationMethod)) return false; if (!crypter.Encrypt(vMasterKey, kMasterKey.vchCryptedKey)) return false; { LOCK(cs_wallet); mapMasterKeys[++nMasterKeyMaxID] = kMasterKey; if (fFileBacked) { pwalletdbEncryption = new CWalletDB(strWalletFile); if (!pwalletdbEncryption->TxnBegin()) return false; pwalletdbEncryption->WriteMasterKey(nMasterKeyMaxID, kMasterKey); } if (!EncryptKeys(vMasterKey)) { if (fFileBacked) pwalletdbEncryption->TxnAbort(); exit(1); //We now probably have half of our keys encrypted in memory, and half not...die and let the user reload their unencrypted wallet. } // Encryption was introduced in version 0.4.0 SetMinVersion(FEATURE_WALLETCRYPT, pwalletdbEncryption, true); if (fFileBacked) { if (!pwalletdbEncryption->TxnCommit()) exit(1); //We now have keys encrypted in memory, but no on disk...die to avoid confusion and let the user reload their unencrypted wallet. delete pwalletdbEncryption; pwalletdbEncryption = NULL; } Lock(); Unlock(strWalletPassphrase); NewKeyPool(); Lock(); // Need to completely rewrite the wallet file; if we don't, bdb might keep // bits of the unencrypted private key in slack space in the database file. CDB::Rewrite(strWalletFile); } return true; } void CWallet::WalletUpdateSpent(const CTransaction &tx) { // Anytime a signature is successfully verified, it's proof the outpoint is spent. // Update the wallet spent flag if it doesn't know due to wallet.dat being // restored from backup or the user making copies of wallet.dat. { LOCK(cs_wallet); BOOST_FOREACH(const CTxIn& txin, tx.vin) { map<uint256, CWalletTx>::iterator mi = mapWallet.find(txin.prevout.hash); if (mi != mapWallet.end()) { CWalletTx& wtx = (*mi).second; // Decent: skip empty TX if (wtx.vout.empty()) continue; if (!wtx.IsSpent(txin.prevout.n) && IsMine(wtx.vout[txin.prevout.n])) { printf("WalletUpdateSpent found spent unit %sDCT %s\n", FormatMoney(wtx.GetCredit()).c_str(), wtx.GetHash().ToString().c_str()); wtx.MarkSpent(txin.prevout.n); wtx.WriteToDisk(); vWalletUpdated.push_back(txin.prevout.hash); } } } } } void CWallet::MarkDirty() { { LOCK(cs_wallet); BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet) item.second.MarkDirty(); } } bool CWallet::AddToWallet(const CWalletTx& wtxIn) { uint256 hash = wtxIn.GetHash(); { LOCK(cs_wallet); // Inserts only if not already there, returns tx inserted or tx found pair<map<uint256, CWalletTx>::iterator, bool> ret = mapWallet.insert(make_pair(hash, wtxIn)); CWalletTx& wtx = (*ret.first).second; wtx.BindWallet(this); bool fInsertedNew = ret.second; if (fInsertedNew) wtx.nTimeReceived = GetAdjustedTime(); bool fUpdated = false; if (!fInsertedNew) { // Merge if (wtxIn.hashBlock != 0 && wtxIn.hashBlock != wtx.hashBlock) { wtx.hashBlock = wtxIn.hashBlock; fUpdated = true; } if (wtxIn.nIndex != -1 && (wtxIn.vMerkleBranch != wtx.vMerkleBranch || wtxIn.nIndex != wtx.nIndex)) { wtx.vMerkleBranch = wtxIn.vMerkleBranch; wtx.nIndex = wtxIn.nIndex; fUpdated = true; } if (wtxIn.fFromMe && wtxIn.fFromMe != wtx.fFromMe) { wtx.fFromMe = wtxIn.fFromMe; fUpdated = true; } fUpdated |= wtx.UpdateSpent(wtxIn.vfSpent); } //// debug print printf("AddToWallet %s %s%s\n", wtxIn.GetHash().ToString().substr(0,10).c_str(), (fInsertedNew ? "new" : ""), (fUpdated ? "update" : "")); // Write to disk if (fInsertedNew || fUpdated) if (!wtx.WriteToDisk()) return false; #ifndef QT_GUI // If default receiving address gets used, replace it with a new one CScript scriptDefaultKey; scriptDefaultKey.SetBitcoinAddress(vchDefaultKey); BOOST_FOREACH(const CTxOut& txout, wtx.vout) { if (txout.scriptPubKey == scriptDefaultKey) { std::vector<unsigned char> newDefaultKey; if (GetKeyFromPool(newDefaultKey, false)) { SetDefaultKey(newDefaultKey); SetAddressBookName(CBitcoinAddress(vchDefaultKey), ""); } } } #endif // Notify UI vWalletUpdated.push_back(hash); // since AddToWallet is called directly for self-originating transactions, check for consumption of own coins WalletUpdateSpent(wtx); } // Refresh UI MainFrameRepaint(); return true; } // Add a transaction to the wallet, or update it. // pblock is optional, but should be provided if the transaction is known to be in a block. // If fUpdate is true, existing transactions will be updated. bool CWallet::AddToWalletIfInvolvingMe(const CTransaction& tx, const CBlock* pblock, bool fUpdate, bool fFindBlock) { uint256 hash = tx.GetHash(); { LOCK(cs_wallet); bool fExisted = mapWallet.count(hash); if (fExisted && !fUpdate) return false; if (fExisted || IsMine(tx) || IsFromMe(tx)) { CWalletTx wtx(this,tx); // Get merkle branch if transaction was found in a block if (pblock) wtx.SetMerkleBranch(pblock); return AddToWallet(wtx); } else WalletUpdateSpent(tx); } return false; } bool CWallet::EraseFromWallet(uint256 hash) { if (!fFileBacked) return false; { LOCK(cs_wallet); if (mapWallet.erase(hash)) CWalletDB(strWalletFile).EraseTx(hash); } return true; } bool CWallet::IsMine(const CTxIn &txin) const { { LOCK(cs_wallet); map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash); if (mi != mapWallet.end()) { const CWalletTx& prev = (*mi).second; if (txin.prevout.n < prev.vout.size()) if (IsMine(prev.vout[txin.prevout.n])) return true; } } return false; } int64 CWallet::GetDebit(const CTxIn &txin) const { { LOCK(cs_wallet); map<uint256, CWalletTx>::const_iterator mi = mapWallet.find(txin.prevout.hash); if (mi != mapWallet.end()) { const CWalletTx& prev = (*mi).second; if (txin.prevout.n < prev.vout.size()) if (IsMine(prev.vout[txin.prevout.n])) return prev.vout[txin.prevout.n].nValue; } } return 0; } bool CWallet::IsChange(const CTxOut& txout) const { CBitcoinAddress address; // TODO: fix handling of 'change' outputs. The assumption is that any // payment to a TX_PUBKEYHASH that is mine but isn't in the address book // is change. That assumption is likely to break when we implement multisignature // wallets that return change back into a multi-signature-protected address; // a better way of identifying which outputs are 'the send' and which are // 'the change' will need to be implemented (maybe extend CWalletTx to remember // which output, if any, was change). if (ExtractAddress(txout.scriptPubKey, address) && HaveKey(address)) { LOCK(cs_wallet); if (!mapAddressBook.count(address)) return true; } return false; } int64 CWalletTx::GetTxTime() const { return nTimeReceived; } int CWalletTx::GetRequestCount() const { // Returns -1 if it wasn't being tracked int nRequests = -1; { LOCK(pwallet->cs_wallet); if (IsCoinBase() || IsCoinStake()) { // Generated block if (hashBlock != 0) { map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock); if (mi != pwallet->mapRequestCount.end()) nRequests = (*mi).second; } } else { // Did anyone request this transaction? map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(GetHash()); if (mi != pwallet->mapRequestCount.end()) { nRequests = (*mi).second; // How about the block it's in? if (nRequests == 0 && hashBlock != 0) { map<uint256, int>::const_iterator mi = pwallet->mapRequestCount.find(hashBlock); if (mi != pwallet->mapRequestCount.end()) nRequests = (*mi).second; else nRequests = 1; // If it's in someone else's block it must have got out } } } } return nRequests; } void CWalletTx::GetAmounts(int64& nGeneratedImmature, int64& nGeneratedMature, list<pair<CBitcoinAddress, int64> >& listReceived, list<pair<CBitcoinAddress, int64> >& listSent, int64& nFee, string& strSentAccount) const { nGeneratedImmature = nGeneratedMature = nFee = 0; listReceived.clear(); listSent.clear(); strSentAccount = strFromAccount; if (IsCoinBase() || IsCoinStake()) { if (GetBlocksToMaturity() > 0) nGeneratedImmature = pwallet->GetCredit(*this) - pwallet->GetDebit(*this); else nGeneratedMature = GetCredit() - GetDebit(); return; } // Compute fee: int64 nDebit = GetDebit(); if (nDebit > 0) // debit>0 means we signed/sent this transaction { int64 nValueOut = GetValueOut(); nFee = nDebit - nValueOut; } // Sent/received. BOOST_FOREACH(const CTxOut& txout, vout) { CBitcoinAddress address; vector<unsigned char> vchPubKey; if (!ExtractAddress(txout.scriptPubKey, address)) { printf("CWalletTx::GetAmounts: Unknown transaction type found, txid %s\n", this->GetHash().ToString().c_str()); address = " unknown "; } // Don't report 'change' txouts if (nDebit > 0 && pwallet->IsChange(txout)) continue; if (nDebit > 0) listSent.push_back(make_pair(address, txout.nValue)); if (pwallet->IsMine(txout)) listReceived.push_back(make_pair(address, txout.nValue)); } } void CWalletTx::GetAccountAmounts(const string& strAccount, int64& nGenerated, int64& nReceived, int64& nSent, int64& nFee) const { nGenerated = nReceived = nSent = nFee = 0; int64 allGeneratedImmature, allGeneratedMature, allFee; allGeneratedImmature = allGeneratedMature = allFee = 0; string strSentAccount; list<pair<CBitcoinAddress, int64> > listReceived; list<pair<CBitcoinAddress, int64> > listSent; GetAmounts(allGeneratedImmature, allGeneratedMature, listReceived, listSent, allFee, strSentAccount); if (strAccount == "") nGenerated = allGeneratedMature; if (strAccount == strSentAccount) { BOOST_FOREACH(const PAIRTYPE(CBitcoinAddress,int64)& s, listSent) nSent += s.second; nFee = allFee; } { LOCK(pwallet->cs_wallet); BOOST_FOREACH(const PAIRTYPE(CBitcoinAddress,int64)& r, listReceived) { if (pwallet->mapAddressBook.count(r.first)) { map<CBitcoinAddress, string>::const_iterator mi = pwallet->mapAddressBook.find(r.first); if (mi != pwallet->mapAddressBook.end() && ((*mi).second == strAccount || (*mi).first.ToString() == strAccount)) nReceived += r.second; } else if (strAccount.empty()) { nReceived += r.second; } } } } void CWalletTx::AddSupportingTransactions(CTxDB& txdb) { vtxPrev.clear(); const int COPY_DEPTH = 3; if (SetMerkleBranch() < COPY_DEPTH) { vector<uint256> vWorkQueue; BOOST_FOREACH(const CTxIn& txin, vin) vWorkQueue.push_back(txin.prevout.hash); // This critsect is OK because txdb is already open { LOCK(pwallet->cs_wallet); map<uint256, const CMerkleTx*> mapWalletPrev; set<uint256> setAlreadyDone; for (unsigned int i = 0; i < vWorkQueue.size(); i++) { uint256 hash = vWorkQueue[i]; if (setAlreadyDone.count(hash)) continue; setAlreadyDone.insert(hash); CMerkleTx tx; map<uint256, CWalletTx>::const_iterator mi = pwallet->mapWallet.find(hash); if (mi != pwallet->mapWallet.end()) { tx = (*mi).second; BOOST_FOREACH(const CMerkleTx& txWalletPrev, (*mi).second.vtxPrev) mapWalletPrev[txWalletPrev.GetHash()] = &txWalletPrev; } else if (mapWalletPrev.count(hash)) { tx = *mapWalletPrev[hash]; } else if (!fClient && txdb.ReadDiskTx(hash, tx)) { ; } else { printf("ERROR: AddSupportingTransactions() : unsupported transaction\n"); continue; } int nDepth = tx.SetMerkleBranch(); vtxPrev.push_back(tx); if (nDepth < COPY_DEPTH) { BOOST_FOREACH(const CTxIn& txin, tx.vin) vWorkQueue.push_back(txin.prevout.hash); } } } } reverse(vtxPrev.begin(), vtxPrev.end()); } bool CWalletTx::WriteToDisk() { return CWalletDB(pwallet->strWalletFile).WriteTx(GetHash(), *this); } // Scan the block chain (starting in pindexStart) for transactions // from or to us. If fUpdate is true, found transactions that already // exist in the wallet will be updated. int CWallet::ScanForWalletTransactions(CBlockIndex* pindexStart, bool fUpdate) { int ret = 0; CBlockIndex* pindex = pindexStart; { LOCK(cs_wallet); while (pindex) { CBlock block; block.ReadFromDisk(pindex, true); BOOST_FOREACH(CTransaction& tx, block.vtx) { if (AddToWalletIfInvolvingMe(tx, &block, fUpdate)) ret++; } pindex = pindex->pnext; } } return ret; } int CWallet::ScanForWalletTransaction(const uint256& hashTx) { CTransaction tx; tx.ReadFromDisk(COutPoint(hashTx, 0)); if (AddToWalletIfInvolvingMe(tx, NULL, true, true)) return 1; return 0; } void CWallet::ReacceptWalletTransactions() { CTxDB txdb("r"); bool fRepeat = true; while (fRepeat) { LOCK(cs_wallet); fRepeat = false; vector<CDiskTxPos> vMissingTx; BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet) { CWalletTx& wtx = item.second; if ((wtx.IsCoinBase() && wtx.IsSpent(0)) || (wtx.IsCoinStake() && wtx.IsSpent(1))) continue; CTxIndex txindex; bool fUpdated = false; if (txdb.ReadTxIndex(wtx.GetHash(), txindex)) { // Update fSpent if a tx got spent somewhere else by a copy of wallet.dat if (txindex.vSpent.size() != wtx.vout.size()) { printf("ERROR: ReacceptWalletTransactions() : txindex.vSpent.size() %d != wtx.vout.size() %d\n", txindex.vSpent.size(), wtx.vout.size()); continue; } for (unsigned int i = 0; i < txindex.vSpent.size(); i++) { if (wtx.IsSpent(i)) continue; if (!txindex.vSpent[i].IsNull() && IsMine(wtx.vout[i])) { wtx.MarkSpent(i); fUpdated = true; vMissingTx.push_back(txindex.vSpent[i]); } } if (fUpdated) { printf("ReacceptWalletTransactions found spent coin %sppc %s\n", FormatMoney(wtx.GetCredit()).c_str(), wtx.GetHash().ToString().c_str()); wtx.MarkDirty(); wtx.WriteToDisk(); } } else { // Reaccept any txes of ours that aren't already in a block if (!(wtx.IsCoinBase() || wtx.IsCoinStake())) wtx.AcceptWalletTransaction(txdb, false); } } if (!vMissingTx.empty()) { // TODO: optimize this to scan just part of the block chain? if (ScanForWalletTransactions(pindexGenesisBlock)) fRepeat = true; // Found missing transactions: re-do Reaccept. } } } void CWalletTx::RelayWalletTransaction(CTxDB& txdb) { BOOST_FOREACH(const CMerkleTx& tx, vtxPrev) { if (!(tx.IsCoinBase() || tx.IsCoinStake())) { uint256 hash = tx.GetHash(); if (!txdb.ContainsTx(hash)) RelayMessage(CInv(MSG_TX, hash), (CTransaction)tx); } } if (!(IsCoinBase() || IsCoinStake())) { uint256 hash = GetHash(); if (!txdb.ContainsTx(hash)) { printf("Relaying wtx %s\n", hash.ToString().substr(0,10).c_str()); RelayMessage(CInv(MSG_TX, hash), (CTransaction)*this); } } } void CWalletTx::RelayWalletTransaction() { CTxDB txdb("r"); RelayWalletTransaction(txdb); } void CWallet::ResendWalletTransactions() { // Do this infrequently and randomly to avoid giving away // that these are our transactions. static int64 nNextTime; if (GetTime() < nNextTime) return; bool fFirst = (nNextTime == 0); nNextTime = GetTime() + GetRand(30 * 60); if (fFirst) return; // Only do it if there's been a new block since last time static int64 nLastTime; if (nTimeBestReceived < nLastTime) return; nLastTime = GetTime(); // Rebroadcast any of our txes that aren't in a block yet printf("ResendWalletTransactions()\n"); CTxDB txdb("r"); { LOCK(cs_wallet); // Sort them in chronological order multimap<unsigned int, CWalletTx*> mapSorted; BOOST_FOREACH(PAIRTYPE(const uint256, CWalletTx)& item, mapWallet) { CWalletTx& wtx = item.second; // Don't rebroadcast until it's had plenty of time that // it should have gotten in already by now. if (nTimeBestReceived - (int64)wtx.nTimeReceived > 5 * 60) mapSorted.insert(make_pair(wtx.nTimeReceived, &wtx)); } BOOST_FOREACH(PAIRTYPE(const unsigned int, CWalletTx*)& item, mapSorted) { CWalletTx& wtx = *item.second; if (wtx.CheckTransaction()) wtx.RelayWalletTransaction(txdb); else printf("ResendWalletTransactions() : CheckTransaction failed for transaction %s\n", wtx.GetHash().ToString().c_str()); } } } ////////////////////////////////////////////////////////////////////////////// // // Actions // int64 CWallet::GetBalance() const { int64 nTotal = 0; { LOCK(cs_wallet); for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) { const CWalletTx* pcoin = &(*it).second; if (!pcoin->IsFinal() || !pcoin->IsConfirmed()) continue; nTotal += pcoin->GetAvailableCredit(); } } return nTotal; } int64 CWallet::GetUnconfirmedBalance() const { int64 nTotal = 0; { LOCK(cs_wallet); for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) { const CWalletTx* pcoin = &(*it).second; if (pcoin->IsFinal() && pcoin->IsConfirmed()) continue; nTotal += pcoin->GetAvailableCredit(); } } return nTotal; } // peercoin: total coins staked (non-spendable until maturity) int64 CWallet::GetStake() const { int64 nTotal = 0; LOCK(cs_wallet); for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) { const CWalletTx* pcoin = &(*it).second; if (pcoin->IsCoinStake() && pcoin->GetBlocksToMaturity() > 0 && pcoin->GetDepthInMainChain() > 0) nTotal += CWallet::GetCredit(*pcoin); } return nTotal; } int64 CWallet::GetNewMint() const { int64 nTotal = 0; LOCK(cs_wallet); for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) { const CWalletTx* pcoin = &(*it).second; if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0 && pcoin->GetDepthInMainChain() > 0) nTotal += CWallet::GetCredit(*pcoin); } return nTotal; } bool CWallet::SelectCoinsMinConf(int64 nTargetValue, unsigned int nSpendTime, int nConfMine, int nConfTheirs, list<pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet) const { setCoinsRet.clear(); nValueRet = 0; // List of values less than target pair<int64, pair<const CWalletTx*,unsigned int> > coinLowestLarger; coinLowestLarger.first = std::numeric_limits<int64>::max(); coinLowestLarger.second.first = NULL; vector<pair<int64, pair<const CWalletTx*,unsigned int> > > vValue; int64 nTotalLower = 0; { LOCK(cs_wallet); vector<const CWalletTx*> vCoins; vCoins.reserve(mapWallet.size()); for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) vCoins.push_back(&(*it).second); random_shuffle(vCoins.begin(), vCoins.end(), GetRandInt); BOOST_FOREACH(const CWalletTx* pcoin, vCoins) { if (!pcoin->IsFinal() || !pcoin->IsConfirmed()) continue; if ((pcoin->IsCoinBase() || pcoin->IsCoinStake()) && pcoin->GetBlocksToMaturity() > 0) continue; int nDepth = pcoin->GetDepthInMainChain(); if (nDepth < (pcoin->IsFromMe() ? nConfMine : nConfTheirs)) continue; for (unsigned int i = 0; i < pcoin->vout.size(); i++) { if (pcoin->IsSpent(i) || !IsMine(pcoin->vout[i])) continue; if (pcoin->nTime > nSpendTime) continue; // peercoin: timestamp must not exceed spend time int64 n = pcoin->vout[i].nValue; if (n <= 0) continue; pair<int64,pair<const CWalletTx*,unsigned int> > coin = make_pair(n,make_pair(pcoin,i)); if (n == nTargetValue) { setCoinsRet.push_back(coin.second); nValueRet += coin.first; return true; } else if (n < nTargetValue + CENT) { vValue.push_back(coin); nTotalLower += n; } else if (n < coinLowestLarger.first) { coinLowestLarger = coin; } } } } if (nTotalLower == nTargetValue || nTotalLower == nTargetValue + CENT) { for (unsigned int i = 0; i < vValue.size(); ++i) { setCoinsRet.push_back(vValue[i].second); nValueRet += vValue[i].first; } return true; } if (nTotalLower < nTargetValue + (coinLowestLarger.second.first ? CENT : 0)) { if (coinLowestLarger.second.first == NULL) return false; setCoinsRet.push_back(coinLowestLarger.second); nValueRet += coinLowestLarger.first; return true; } if (nTotalLower >= nTargetValue + CENT) nTargetValue += CENT; // Solve subset sum by stochastic approximation sort(vValue.rbegin(), vValue.rend()); vector<char> vfIncluded; vector<char> vfBest(vValue.size(), true); int64 nBest = nTotalLower; for (int nRep = 0; nRep < 1000 && nBest != nTargetValue; nRep++) { vfIncluded.assign(vValue.size(), false); int64 nTotal = 0; bool fReachedTarget = false; for (int nPass = 0; nPass < 2 && !fReachedTarget; nPass++) { for (unsigned int i = 0; i < vValue.size(); i++) { if (nPass == 0 ? rand() % 2 : !vfIncluded[i]) { nTotal += vValue[i].first; vfIncluded[i] = true; if (nTotal >= nTargetValue) { fReachedTarget = true; if (nTotal < nBest) { nBest = nTotal; vfBest = vfIncluded; } nTotal -= vValue[i].first; vfIncluded[i] = false; } } } } } // If the next larger is still closer, return it if (coinLowestLarger.second.first && coinLowestLarger.first - nTargetValue <= nBest - nTargetValue) { setCoinsRet.push_back(coinLowestLarger.second); nValueRet += coinLowestLarger.first; } else { for (unsigned int i = 0; i < vValue.size(); i++) if (vfBest[i]) { setCoinsRet.push_back(vValue[i].second); nValueRet += vValue[i].first; } //// debug print if (fDebug && GetBoolArg("-printselectcoin")) { printf("SelectCoins() best subset: "); for (unsigned int i = 0; i < vValue.size(); i++) if (vfBest[i]) printf("%s ", FormatMoney(vValue[i].first).c_str()); printf("total %s\n", FormatMoney(nBest).c_str()); } } return true; } bool CWallet::SelectCoins(int64 nTargetValue, unsigned int nSpendTime, list<pair<const CWalletTx*,unsigned int> >& setCoinsRet, int64& nValueRet) const { return (SelectCoinsMinConf(nTargetValue, nSpendTime, 1, 6, setCoinsRet, nValueRet) || SelectCoinsMinConf(nTargetValue, nSpendTime, 1, 1, setCoinsRet, nValueRet) || SelectCoinsMinConf(nTargetValue, nSpendTime, 0, 1, setCoinsRet, nValueRet)); } // Decent: populate vCoins with vector of available CTxOut void CWallet::AvailableCoins(vector<CTxOut>& vCoins) const { bool fIncludeZeroValue = true; vCoins.clear(); { LOCK2(cs_main, cs_wallet); for (map<uint256, CWalletTx>::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) { const CWalletTx* pcoin = &(*it).second; if (!(*pcoin).IsFinal()) continue; if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0) continue; int nDepth = pcoin->GetDepthInMainChain(); if (nDepth < 0) continue; for (unsigned int i = 0; i < pcoin->vout.size(); i++) { bool mine = IsMine(pcoin->vout[i]); if (!pcoin->IsSpent(i) && mine && (pcoin->vout[i].nValue > 0 || fIncludeZeroValue)) vCoins.push_back(pcoin->vout[i]); } } } } bool CWallet::CreateTransaction(const vector<pair<CScript, int64> >& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet) { int64 nValue = 0; BOOST_FOREACH (const PAIRTYPE(CScript, int64)& s, vecSend) { if (nValue < 0) return error("create tx : nValue < 0"); nValue += s.second; } if (vecSend.empty() || nValue < 0) return error("create tx : vecSend.empty()"); wtxNew.BindWallet(this); { LOCK2(cs_main, cs_wallet); // txdb must be opened before the mapWallet lock CTxDB txdb("r"); { nFeeRet = MIN_TX_FEE; loop { wtxNew.vin.clear(); wtxNew.vout.clear(); wtxNew.fFromMe = true; int64 nTotalValue = nValue + nFeeRet; double dPriority = 0; // vouts to the payees BOOST_FOREACH (const PAIRTYPE(CScript, int64)& s, vecSend) wtxNew.vout.push_back(CTxOut(s.second, s.first)); // Choose coins to use list<pair<const CWalletTx*,unsigned int> > setCoins; int64 nValueIn = 0; if (!SelectCoins(nTotalValue, wtxNew.nTime, setCoins, nValueIn)) return error("create tx : SelectCoins() failed"); CScript scriptChange; BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins) { int64 nCredit = pcoin.first->vout[pcoin.second].nValue; dPriority += (double)nCredit * pcoin.first->GetDepthInMainChain(); scriptChange = pcoin.first->vout[pcoin.second].scriptPubKey; } int64 nChange = nValueIn - nValue - nFeeRet; // if sub-cent change is required, the fee must be raised to at least MIN_TX_FEE // or until nChange becomes zero // NOTE: this depends on the exact behaviour of GetMinFee if (nFeeRet < MIN_TX_FEE && nChange > 0 && nChange < CENT) { int64 nMoveToFee = min(nChange, MIN_TX_FEE - nFeeRet); nChange -= nMoveToFee; nFeeRet += nMoveToFee; } // peercoin: sub-cent change is moved to fee if (nChange > 0 && nChange < MIN_TXOUT_AMOUNT) { nFeeRet += nChange; nChange = 0; } if (nChange > 0) { // Note: We use a new key here to keep it from being obvious which side is the change. // The drawback is that by not reusing a previous key, the change may be lost if a // backup is restored, if the backup doesn't have the new private key for the change. // If we reused the old key, it would be possible to add code to look for and // rediscover unknown transactions that were written with keys of ours to recover // post-backup change. if (!GetBoolArg("-avatar", true)) // peercoin: not avatar mode; peershares: avatar mode enabled by default to avoid change being sent to hidden address { // Reserve a new key pair from key pool vector<unsigned char> vchPubKey = reservekey.GetReservedKey(); // assert(mapKeys.count(vchPubKey)); // Fill a vout to ourself // TODO: pass in scriptChange instead of reservekey so // change transaction isn't always pay-to-bitcoin-address scriptChange.SetBitcoinAddress(vchPubKey); } else reservekey.ReturnKey(); // return key in avatar mode // Insert change txn at random position: vector<CTxOut>::iterator position = wtxNew.vout.begin()+GetRandInt(wtxNew.vout.size()); wtxNew.vout.insert(position, CTxOut(nChange, scriptChange)); } else reservekey.ReturnKey(); // Fill vin BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins) wtxNew.vin.push_back(CTxIn(coin.first->GetHash(),coin.second)); // Sign int nIn = 0; BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins) if (!SignSignature(*this, *coin.first, wtxNew, nIn++)) return error("create tx : SignSignature() failed"); // Limit size unsigned int nBytes = ::GetSerializeSize(*(CTransaction*)&wtxNew, SER_NETWORK, PROTOCOL_VERSION); if (nBytes >= MAX_BLOCK_SIZE/4) return error("create tx : nBytes >= MAX_BLOCK_SIZE/4"); dPriority /= nBytes; // Check that enough fee is included int64 nPayFee = MIN_TX_FEE * (1 + (int64)nBytes / 1000); int64 nMinFee = wtxNew.GetMinFee(1, false, GMF_SEND); if (nFeeRet < max(nPayFee, nMinFee)) { nFeeRet = max(nPayFee, nMinFee); continue; } // Fill vtxPrev by copying from previous transactions vtxPrev wtxNew.AddSupportingTransactions(txdb); wtxNew.fTimeReceivedIsTxTime = true; break; } } } return true; } // Decent: create content_submit TX bool CWallet::CreateContentSubmitTX(const vector<pair<CScript, int64> >& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, int64 custodyPayment, int64& nFeeRet) { int64 nValue = custodyPayment; wtxNew.BindWallet(this); { LOCK2(cs_main, cs_wallet); // txdb must be opened before the mapWallet lock CTxDB txdb("r"); { nFeeRet = MIN_TX_FEE; loop { wtxNew.vin.clear(); wtxNew.vout.clear(); wtxNew.fFromMe = true; int64 nTotalValue = nValue + nFeeRet; double dPriority = 0; // vouts to the payees BOOST_FOREACH (const PAIRTYPE(CScript, int64)& s, vecSend) wtxNew.vout.push_back(CTxOut(s.second, s.first)); // Choose coins to use list<pair<const CWalletTx*,unsigned int> > setCoins; int64 nValueIn = 0; if (!SelectCoins(nTotalValue, wtxNew.nTime, setCoins, nValueIn)) return false; CScript scriptChange; BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins) { int64 nCredit = pcoin.first->vout[pcoin.second].nValue; dPriority += (double)nCredit * pcoin.first->GetDepthInMainChain(); scriptChange = pcoin.first->vout[pcoin.second].scriptPubKey; } int64 nChange = nValueIn - nValue - nFeeRet; // if sub-cent change is required, the fee must be raised to at least MIN_TX_FEE // or until nChange becomes zero // NOTE: this depends on the exact behaviour of GetMinFee if (nFeeRet < MIN_TX_FEE && nChange > 0 && nChange < CENT) { int64 nMoveToFee = min(nChange, MIN_TX_FEE - nFeeRet); nChange -= nMoveToFee; nFeeRet += nMoveToFee; } // peercoin: sub-cent change is moved to fee if (nChange > 0 && nChange < MIN_TXOUT_AMOUNT) { nFeeRet += nChange; nChange = 0; } if (nChange > 0) { if (!GetBoolArg("-avatar", true)) // peercoin: not avatar mode; peershares: avatar mode enabled by default to avoid change being sent to hidden address { // Reserve a new key pair from key pool vector<unsigned char> vchPubKey = reservekey.GetReservedKey(); // assert(mapKeys.count(vchPubKey)); // Fill a vout to ourself // TODO: pass in scriptChange instead of reservekey so // change transaction isn't always pay-to-bitcoin-address scriptChange.SetBitcoinAddress(vchPubKey); } else reservekey.ReturnKey(); // return key in avatar mode // Insert change txn at random position: Decent: TODO // vector<CTxOut>::iterator position = wtxNew.vout.begin()+GetRandInt(wtxNew.vout.size()); wtxNew.vout.insert(wtxNew.vout.begin(), CTxOut(nChange, scriptChange)); } else reservekey.ReturnKey(); // Fill vin BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins) wtxNew.vin.push_back(CTxIn(coin.first->GetHash(),coin.second)); // Sign int nIn = 0; BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins) if (!SignSignature(*this, *coin.first, wtxNew, nIn++)) return false; // Limit size unsigned int nBytes = ::GetSerializeSize(*(CTransaction*)&wtxNew, SER_NETWORK, PROTOCOL_VERSION); if (nBytes >= MAX_BLOCK_SIZE/4) return false; dPriority /= nBytes; // Check that enough fee is included int64 nPayFee = MIN_TX_FEE * (1 + (int64)nBytes / 1000); int64 nMinFee = wtxNew.GetMinFee(1, false, GMF_SEND); if (nFeeRet < max(nPayFee, nMinFee)) { nFeeRet = max(nPayFee, nMinFee); continue; } // Fill vtxPrev by copying from previous transactions vtxPrev wtxNew.AddSupportingTransactions(txdb); wtxNew.fTimeReceivedIsTxTime = true; break; } } } return true; } //Decent: build TX to "spend" from OP_PROMISE_TO_PAY output bool CWallet::CreateRequestToBuyTX(const vector<pair<CScript, int64> >& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet, COutPoint& content) { int64 nValue = 0; BOOST_FOREACH (const PAIRTYPE(CScript, int64)& s, vecSend) { if (nValue < 0) return false; nValue += s.second; } if (vecSend.empty() || nValue < 0) return false; wtxNew.BindWallet(this); { LOCK2(cs_main, cs_wallet); // txdb must be opened before the mapWallet lock CTxDB txdb("r"); { nFeeRet = MIN_TX_FEE; loop { wtxNew.vin.clear(); wtxNew.vout.clear(); wtxNew.fFromMe = true; int64 nTotalValue = nValue + nFeeRet; double dPriority = 0; // vouts to the payees BOOST_FOREACH (const PAIRTYPE(CScript, int64)& s, vecSend) if (!s.first.empty()) // Decent: skip price out, payment shall be destroyed wtxNew.vout.push_back(CTxOut(s.second, s.first)); // Choose coins to use list<pair<const CWalletTx*,unsigned int> > setCoins; int64 nValueIn = 0; if (!SelectCoins(nTotalValue, wtxNew.nTime, setCoins, nValueIn)) return false; CScript scriptChange; BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins) { int64 nCredit = pcoin.first->vout[pcoin.second].nValue; dPriority += (double)nCredit * pcoin.first->GetDepthInMainChain(); scriptChange = pcoin.first->vout[pcoin.second].scriptPubKey; } // Decent: just for count pair<const CWalletTx*,unsigned int> emptyCoin; setCoins.push_front(emptyCoin); int64 nChange = nValueIn - nValue - nFeeRet; // if sub-cent change is required, the fee must be raised to at least MIN_TX_FEE // or until nChange becomes zero // NOTE: this depends on the exact behaviour of GetMinFee if (nFeeRet < MIN_TX_FEE && nChange > 0 && nChange < CENT) { int64 nMoveToFee = min(nChange, MIN_TX_FEE - nFeeRet); nChange -= nMoveToFee; nFeeRet += nMoveToFee; } // peercoin: sub-cent change is moved to fee if (nChange > 0 && nChange < MIN_TXOUT_AMOUNT) { nFeeRet += nChange; nChange = 0; } if (nChange > 0) { // Note: We use a new key here to keep it from being obvious which side is the change. // The drawback is that by not reusing a previous key, the change may be lost if a // backup is restored, if the backup doesn't have the new private key for the change. // If we reused the old key, it would be possible to add code to look for and // rediscover unknown transactions that were written with keys of ours to recover // post-backup change. if (!GetBoolArg("-avatar", true)) // peercoin: not avatar mode; peershares: avatar mode enabled by default to avoid change being sent to hidden address { // Reserve a new key pair from key pool vector<unsigned char> vchPubKey = reservekey.GetReservedKey(); // assert(mapKeys.count(vchPubKey)); // Fill a vout to ourself // TODO: pass in scriptChange instead of reservekey so // change transaction isn't always pay-to-bitcoin-address scriptChange.SetBitcoinAddress(vchPubKey); } else reservekey.ReturnKey(); // return key in avatar mode // Insert change txn at random position: vector<CTxOut>::iterator position = wtxNew.vout.begin(); wtxNew.vout.insert(position, CTxOut(nChange, scriptChange)); } else reservekey.ReturnKey(); // Fill vin BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins) { if(!coin.first) { // Decent: here is "spend" from OP_PROMISETOPAY output wtxNew.vin.push_back(CTxIn(content.hash,content.n)); } else wtxNew.vin.push_back(CTxIn(coin.first->GetHash(),coin.second)); } // Sign int nIn = 0; BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins) if(coin.first) { if (!SignSignature(*this, *coin.first, wtxNew, nIn++)) return false; } else nIn++; // Limit size unsigned int nBytes = ::GetSerializeSize(*(CTransaction*)&wtxNew, SER_NETWORK, PROTOCOL_VERSION); if (nBytes >= MAX_BLOCK_SIZE/4) return false; dPriority /= nBytes; // Check that enough fee is included int64 nPayFee = MIN_TX_FEE * (1 + (int64)nBytes / 1000); int64 nMinFee = wtxNew.GetMinFee(1, false, GMF_SEND); if (nFeeRet < max(nPayFee, nMinFee)) { nFeeRet = max(nPayFee, nMinFee); continue; } // Fill vtxPrev by copying from previous transactions vtxPrev wtxNew.AddSupportingTransactions(txdb); wtxNew.fTimeReceivedIsTxTime = true; break; } } } return true; } //Decent: proof_of_custody TX bool CWallet::CreateTxWithProof(CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet, COutPoint& prevPoint, valtype& proof) { int64 nValue = 0; wtxNew.BindWallet(this); { LOCK2(cs_main, cs_wallet); // txdb must be opened before the mapWallet lock CTxDB txdb("r"); { nFeeRet = MIN_TX_FEE; loop { wtxNew.vin.clear(); wtxNew.vout.clear(); wtxNew.fFromMe = true; int64 nTotalValue = nValue + nFeeRet; // Decent: it will returned as change, to avoid empty vout nTotalValue += 1; double dPriority = 0; // Choose coins to use list<pair<const CWalletTx*,unsigned int> > setCoins; int64 nValueIn = 0; if (!SelectCoins(nTotalValue, wtxNew.nTime, setCoins, nValueIn)) return false; CScript scriptChange; BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins) { int64 nCredit = pcoin.first->vout[pcoin.second].nValue; dPriority += (double)nCredit * pcoin.first->GetDepthInMainChain(); scriptChange = pcoin.first->vout[pcoin.second].scriptPubKey; } // Decent: CWalletTx prevTx; if (!prevTx.SetByHash(prevPoint.hash)) return error("Create tx : read prevPoint failed"); setCoins.push_front(make_pair(&prevTx, prevPoint.n)); int64 nChange = nValueIn - nValue - nFeeRet; // if sub-cent change is required, the fee must be raised to at least MIN_TX_FEE // or until nChange becomes zero // NOTE: this depends on the exact behaviour of GetMinFee if (nFeeRet < MIN_TX_FEE && nChange > 0 && nChange < CENT) { int64 nMoveToFee = min(nChange, MIN_TX_FEE - nFeeRet); nChange -= nMoveToFee; nFeeRet += nMoveToFee; } // peercoin: sub-cent change is moved to fee if (nChange > 0 && nChange < MIN_TXOUT_AMOUNT) { nFeeRet += nChange; nChange = 0; } if (nChange > 0) { if (!GetBoolArg("-avatar", true)) // peercoin: not avatar mode; peershares: avatar mode enabled by default to avoid change being sent to hidden address { // Reserve a new key pair from key pool vector<unsigned char> vchPubKey = reservekey.GetReservedKey(); // assert(mapKeys.count(vchPubKey)); // Fill a vout to ourself // TODO: pass in scriptChange instead of reservekey so // change transaction isn't always pay-to-bitcoin-address scriptChange.SetBitcoinAddress(vchPubKey); } else reservekey.ReturnKey(); // return key in avatar mode // Insert change txout, must be before special_decent outs wtxNew.vout.insert(wtxNew.vout.begin(), CTxOut(nChange, scriptChange)); } else reservekey.ReturnKey(); // Fill vin BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins) { wtxNew.vin.push_back(CTxIn(coin.first->GetHash(),coin.second)); } // Sign int nIn = 0; BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins) if(wtxNew.vin[nIn].prevout == prevPoint) { wtxNew.vin[nIn].scriptSig << proof; if (!SignSignature(*this, *coin.first, wtxNew, nIn++, SIGHASH_WITHPROOF)) return false; } else { if (!SignSignature(*this, *coin.first, wtxNew, nIn++)) return false; } // Limit size unsigned int nBytes = ::GetSerializeSize(*(CTransaction*)&wtxNew, SER_NETWORK, PROTOCOL_VERSION); if (nBytes >= MAX_BLOCK_SIZE/4) return false; dPriority /= nBytes; // Check that enough fee is included int64 nPayFee = MIN_TX_FEE * (1 + (int64)nBytes / 1000); int64 nMinFee = wtxNew.GetMinFee(1, false, GMF_SEND); if (nFeeRet < max(nPayFee, nMinFee)) { nFeeRet = max(nPayFee, nMinFee); continue; } if (!(wtxNew.IsProofOfCustody() || wtxNew.IsLeaveRating())) return error("Create tx: invalid type"); // Fill vtxPrev by copying from previous transactions vtxPrev wtxNew.AddSupportingTransactions(txdb); wtxNew.fTimeReceivedIsTxTime = true; break; } } } return true; } //Decent: delivery_keys TX bool CWallet::CreateDeliveryTX(CWalletTx& wtxNew, CReserveKey& reservekey, COutPoint& prevPoint, valtype &encryptedKey, valtype& proof) { int64 nFee = 0; int64 nValue = 0; wtxNew.BindWallet(this); { LOCK2(cs_main, cs_wallet); // txdb must be opened before the mapWallet lock CTxDB txdb("r"); { nFee = MIN_TX_FEE; loop { wtxNew.vin.clear(); wtxNew.vout.clear(); wtxNew.fFromMe = true; int64 nTotalValue = nValue + nFee; // Decent: it will returned as change, to avoid empty vout nTotalValue += 1; double dPriority = 0; // Choose coins to use list<pair<const CWalletTx*,unsigned int> > setCoins; int64 nValueIn = 0; if (!SelectCoins(nTotalValue, wtxNew.nTime, setCoins, nValueIn)) return false; CScript scriptChange; BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins) { int64 nCredit = pcoin.first->vout[pcoin.second].nValue; dPriority += (double)nCredit * pcoin.first->GetDepthInMainChain(); scriptChange = pcoin.first->vout[pcoin.second].scriptPubKey; } // Decent: CWalletTx prevTx; if (!prevTx.SetByHash(prevPoint.hash)) return error("Create tx : read prevPoint failed"); setCoins.push_front(make_pair(&prevTx, prevPoint.n)); int64 nChange = nValueIn - nValue - nFee; // if sub-cent change is required, the fee must be raised to at least MIN_TX_FEE // or until nChange becomes zero // NOTE: this depends on the exact behaviour of GetMinFee if (nFee < MIN_TX_FEE && nChange > 0 && nChange < CENT) { int64 nMoveToFee = min(nChange, MIN_TX_FEE - nFee); nChange -= nMoveToFee; nFee += nMoveToFee; } // peercoin: sub-cent change is moved to fee if (nChange > 0 && nChange < MIN_TXOUT_AMOUNT) { nFee += nChange; nChange = 0; } if (nChange > 0) { if (!GetBoolArg("-avatar", true)) // peercoin: not avatar mode; peershares: avatar mode enabled by default to avoid change being sent to hidden address { // Reserve a new key pair from key pool vector<unsigned char> vchPubKey = reservekey.GetReservedKey(); // assert(mapKeys.count(vchPubKey)); // Fill a vout to ourself // TODO: pass in scriptChange instead of reservekey so // change transaction isn't always pay-to-bitcoin-address scriptChange.SetBitcoinAddress(vchPubKey); } else reservekey.ReturnKey(); // return key in avatar mode // Insert change txout, must be before special_decent outs wtxNew.vout.insert(wtxNew.vout.begin(), CTxOut(nChange, scriptChange)); } else reservekey.ReturnKey(); // Fill vin BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins) { wtxNew.vin.push_back(CTxIn(coin.first->GetHash(),coin.second)); } // Sign int nIn = 0; BOOST_FOREACH(const PAIRTYPE(const CWalletTx*,unsigned int)& coin, setCoins) if(wtxNew.vin[nIn].prevout == prevPoint) { wtxNew.vin[nIn].scriptSig << encryptedKey << proof; if (!SignSignature(*this, *coin.first, wtxNew, nIn++, SIGHASH_WITHPROOF)) return false; } else { if (!SignSignature(*this, *coin.first, wtxNew, nIn++)) return false; } // Limit size unsigned int nBytes = ::GetSerializeSize(*(CTransaction*)&wtxNew, SER_NETWORK, PROTOCOL_VERSION); if (nBytes >= MAX_BLOCK_SIZE/4) return false; dPriority /= nBytes; // Check that enough fee is included int64 nPayFee = MIN_TX_FEE * (1 + (int64)nBytes / 1000); int64 nMinFee = wtxNew.GetMinFee(1, false, GMF_SEND); if (nFee < max(nPayFee, nMinFee)) { nFee = max(nPayFee, nMinFee); continue; } if (!wtxNew.CheckDeliverKeys()) return error("Create tx: invalid type"); // Fill vtxPrev by copying from previous transactions vtxPrev wtxNew.AddSupportingTransactions(txdb); wtxNew.fTimeReceivedIsTxTime = true; break; } } } return true; } bool CWallet::CreateTransaction(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, CReserveKey& reservekey, int64& nFeeRet) { vector< pair<CScript, int64> > vecSend; vecSend.push_back(make_pair(scriptPubKey, nValue)); return CreateTransaction(vecSend, wtxNew, reservekey, nFeeRet); } // peercoin: create coin stake transaction bool CWallet::CreateCoinStake(unsigned int nBits, int64 nSearchInterval, CTransaction& txNew, int64 rewardForBlockCreator) { // The following split & combine thresholds are important to security // Should not be adjusted if you don't understand the consequences static unsigned int nStakeSplitAge = (60 * 60 * 24 * 90); int64 nCombineThreshold = GetProofOfWorkReward(GetLastBlockIndex(pindexBest, false)->nBits) / 3; CBigNum bnTargetPerCoinDay; bnTargetPerCoinDay.SetCompact(nBits); LOCK2(cs_main, cs_wallet); txNew.vin.clear(); txNew.vout.clear(); // Mark coin stake transaction CScript scriptEmpty; scriptEmpty.clear(); txNew.vout.push_back(CTxOut(0, scriptEmpty)); // Choose coins to use int64 nBalance = GetBalance(); int64 nReserveBalance = 0; if (mapArgs.count("-reservebalance") && !ParseMoney(mapArgs["-reservebalance"], nReserveBalance)) return error("CreateCoinStake : invalid reserve balance amount"); if (nBalance <= nReserveBalance) return false; list<pair<const CWalletTx*,unsigned int> > setCoins; vector<const CWalletTx*> vwtxPrev; int64 nValueIn = 0; if (!SelectCoins(nBalance - nReserveBalance, txNew.nTime, setCoins, nValueIn)) return false; if (setCoins.empty()) return false; int64 nCredit = 0; CScript scriptPubKeyKernel; BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins) { CTxDB txdb("r"); CTxIndex txindex; if (!txdb.ReadTxIndex(pcoin.first->GetHash(), txindex)) continue; // Read block header CBlock block; if (!block.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos, false)) continue; static int nMaxStakeSearchInterval = 60; if (block.GetBlockTime() + nStakeMinAge > txNew.nTime - nMaxStakeSearchInterval) continue; // only count coins meeting min age requirement bool fKernelFound = false; for (unsigned int n=0; n<min(nSearchInterval,(int64)nMaxStakeSearchInterval) && !fKernelFound && !fShutdown; n++) { // Search backward in time from the given txNew timestamp // Search nSearchInterval seconds back up to nMaxStakeSearchInterval uint256 hashProofOfStake = 0; COutPoint prevoutStake = COutPoint(pcoin.first->GetHash(), pcoin.second); if (CheckStakeKernelHash(nBits, block, txindex.pos.nTxPos - txindex.pos.nBlockPos, *pcoin.first, prevoutStake, txNew.nTime - n, hashProofOfStake)) { // Found a kernel if (fDebug && GetBoolArg("-printcoinstake")) printf("CreateCoinStake : kernel found\n"); vector<valtype> vSolutions; txnouttype whichType; CScript scriptPubKeyOut; scriptPubKeyKernel = pcoin.first->vout[pcoin.second].scriptPubKey; if (!Solver(scriptPubKeyKernel, whichType, vSolutions)) { if (fDebug && GetBoolArg("-printcoinstake")) printf("CreateCoinStake : failed to parse kernel\n", whichType); break; } if (fDebug && GetBoolArg("-printcoinstake")) printf("CreateCoinStake : parsed kernel type=%d\n", whichType); if (whichType != TX_PUBKEY && whichType != TX_PUBKEYHASH) { if (fDebug && GetBoolArg("-printcoinstake")) printf("CreateCoinStake : no support for kernel type=%d\n", whichType); break; // only support pay to public key and pay to address } if (whichType == TX_PUBKEYHASH) // pay to address type { // convert to pay to public key type CKey key; if (!this->GetKey(uint160(vSolutions[0]), key)) { if (fDebug && GetBoolArg("-printcoinstake")) printf("CreateCoinStake : failed to get key for kernel type=%d\n", whichType); break; // unable to find corresponding public key } scriptPubKeyOut << key.GetPubKey() << OP_CHECKSIG; } else scriptPubKeyOut = scriptPubKeyKernel; txNew.nTime -= n; txNew.vin.push_back(CTxIn(pcoin.first->GetHash(), pcoin.second)); nCredit += pcoin.first->vout[pcoin.second].nValue; vwtxPrev.push_back(pcoin.first); txNew.vout.push_back(CTxOut(0, scriptPubKeyOut)); // Decent: for reward txNew.vout.push_back(CTxOut(0, scriptPubKeyOut)); if (block.GetBlockTime() + nStakeSplitAge > txNew.nTime) txNew.vout.push_back(CTxOut(0, scriptPubKeyOut)); //split stake if (fDebug && GetBoolArg("-printcoinstake")) printf("CreateCoinStake : added kernel type=%d\n", whichType); fKernelFound = true; break; } } if (fKernelFound || fShutdown) break; // if kernel is found stop searching } if (nCredit == 0 || nCredit > nBalance - nReserveBalance) return false; BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins) { // Attempt to add more inputs // Only add coins of the same key/address as kernel if (txNew.vout.size() == 2 && ((pcoin.first->vout[pcoin.second].scriptPubKey == scriptPubKeyKernel || pcoin.first->vout[pcoin.second].scriptPubKey == txNew.vout[1].scriptPubKey)) && pcoin.first->GetHash() != txNew.vin[0].prevout.hash) { // Stop adding more inputs if already too many inputs if (txNew.vin.size() >= 100) break; // Stop adding more inputs if value is already pretty significant if (nCredit > nCombineThreshold) break; // Stop adding inputs if reached reserve limit if (nCredit + pcoin.first->vout[pcoin.second].nValue > nBalance - nReserveBalance) break; // Do not add additional significant input if (pcoin.first->vout[pcoin.second].nValue > nCombineThreshold) continue; // Do not add input that is still too young if (pcoin.first->nTime + STAKE_MAX_AGE > txNew.nTime) continue; txNew.vin.push_back(CTxIn(pcoin.first->GetHash(), pcoin.second)); nCredit += pcoin.first->vout[pcoin.second].nValue; vwtxPrev.push_back(pcoin.first); } } // Calculate coin age reward // { // uint64 nCoinAge; // CTxDB txdb("r"); // if (!txNew.GetCoinAge(txdb, nCoinAge)) // return error("CreateCoinStake : failed to calculate coin age"); // nCredit += GetProofOfStakeReward(nCoinAge); // } int64 nMinFee = 0; loop { // Set output amount if (txNew.vout.size() == 4) { txNew.vout[1].nValue = rewardForBlockCreator; // Decent: set reward for block creator txNew.vout[2].nValue = ((nCredit - nMinFee) / 2 / CENT) * CENT; txNew.vout[3].nValue = nCredit - nMinFee - txNew.vout[2].nValue; } else txNew.vout[2].nValue = nCredit - nMinFee; //You can put your own extra vouts inside Stake transaction in such way, but it will have //consequences.First, you shouldn't hardcode any determined address here, because we have //seen strange thing.All stake money, used for coinstake transaction, will be returned to //this determined address regardless of person, who minted it.But money, which we sent //to this address, were delivered to address of person, who minted it.We don't know, why it //was happend, but it looked like this outputs exchanged their delivery addresses. //In conclusion, you should find out with coinstake transaction building process or you //should never ever touch this process. // CScript Script; // CBitcoinAddress address = CBitcoinAddress("SU6AncdVHCpDAiG9yj9BdNscb83XeLTpcj"); // Script.SetBitcoinAddress(address); // txNew.vout.push_back(CTxOut(100000000, Script)); // Sign int nIn = 0; BOOST_FOREACH(const CWalletTx* pcoin, vwtxPrev) { if (!SignSignature(*this, *pcoin, txNew, nIn++)) return error("CreateCoinStake : failed to sign coinstake"); } // Limit size unsigned int nBytes = ::GetSerializeSize(txNew, SER_NETWORK, PROTOCOL_VERSION); if (nBytes >= MAX_BLOCK_SIZE_GEN/5) return error("CreateCoinStake : exceeded coinstake size limit"); // Check enough fee is paid if (nMinFee < txNew.GetMinFee() - MIN_TX_FEE) { nMinFee = txNew.GetMinFee() - MIN_TX_FEE; continue; // try signing again } else { if (fDebug && GetBoolArg("-printfee")) printf("CreateCoinStake : fee for coinstake %s\n", FormatMoney(nMinFee).c_str()); break; } } // Successfully generated coinstake return true; } // Call after CreateTransaction unless you want to abort bool CWallet::CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey) { { LOCK2(cs_main, cs_wallet); printf("CommitTransaction:\n%s", wtxNew.ToString().c_str()); { // This is only to keep the database open to defeat the auto-flush for the // duration of this scope. This is the only place where this optimization // maybe makes sense; please don't do it anywhere else. CWalletDB* pwalletdb = fFileBacked ? new CWalletDB(strWalletFile,"r") : NULL; // Take key pair from key pool so it won't be used again reservekey.KeepKey(); // Add tx to wallet, because if it has change it's also ours, // otherwise just for transaction history. AddToWallet(wtxNew); // Mark old coins as spent set<CWalletTx*> setCoins; BOOST_FOREACH(const CTxIn& txin, wtxNew.vin) { CWalletTx &coin = mapWallet[txin.prevout.hash]; coin.BindWallet(this); coin.MarkSpent(txin.prevout.n); coin.WriteToDisk(); vWalletUpdated.push_back(coin.GetHash()); } if (fFileBacked) delete pwalletdb; } // Track how many getdata requests our transaction gets mapRequestCount[wtxNew.GetHash()] = 0; // Broadcast if (!wtxNew.AcceptToMemoryPool()) { // This must not fail. The transaction has already been signed and recorded. printf("CommitTransaction() : Error: Transaction not valid"); return false; } wtxNew.RelayWalletTransaction(); } MainFrameRepaint(); return true; } bool CWallet::CommitDecentTX(CWalletTx& wtxNew, CReserveKey& reservekey) { printf("Commit Decent tx:\n%s", wtxNew.ToString().c_str()); mapRequestCount[wtxNew.GetHash()] = 0; if (!wtxNew.AcceptToMemoryPool()) { if (wtxNew.IsRedundant()) return true; printf("CommitTransaction() : Error: Transaction not valid"); return error("Decent tx is not valid"); } AddToWalletIfInvolvingMe(wtxNew, NULL, true, true); wtxNew.RelayWalletTransaction(); MainFrameRepaint(); return true; } string CWallet::SendMoney(CScript scriptPubKey, int64 nValue, CWalletTx& wtxNew, bool fAskFee) { CReserveKey reservekey(this); int64 nFeeRequired; if (IsLocked()) { string strError = _("Error: Portfolio locked, unable to create transaction "); printf("SendMoney() : %s", strError.c_str()); return strError; } if (fWalletUnlockMintOnly) { string strError = _("Error: Portfolio unlocked for block minting only, unable to create transaction."); printf("SendMoney() : %s", strError.c_str()); return strError; } if (!CreateTransaction(scriptPubKey, nValue, wtxNew, reservekey, nFeeRequired)) { string strError; if (nValue + nFeeRequired > GetBalance()) strError = strprintf(_("Error: This transaction requires a transaction fee of at least %s because of its amount, complexity, or use of recently received funds "), FormatMoney(nFeeRequired).c_str()); else strError = _("Error: Transaction creation failed "); printf("SendMoney() : %s", strError.c_str()); return strError; } if (fAskFee && !ThreadSafeAskFee(nFeeRequired, _("Sending..."))) return "ABORTED"; if (!CommitTransaction(wtxNew, reservekey)) return _("Error: The transaction was rejected. This might happen if some of the shares in your portfolio were already spent, such as if you used a copy of wallet.dat and shares were spent in the copy but not marked as spent here."); MainFrameRepaint(); return ""; } string CWallet::SendMoneyToBitcoinAddress(const CBitcoinAddress& address, int64 nValue, CWalletTx& wtxNew, bool fAskFee) { // Check amount if (nValue < 0) return _("Invalid amount"); if (nValue + MIN_TX_FEE > GetBalance()) return _("Insufficient funds"); // Parse bitcoin address CScript scriptPubKey; scriptPubKey.SetBitcoinAddress(address); return SendMoney(scriptPubKey, nValue, wtxNew, fAskFee); } int CWallet::LoadWallet(bool& fFirstRunRet) { if (!fFileBacked) return false; fFirstRunRet = false; int nLoadWalletRet = CWalletDB(strWalletFile,"cr+").LoadWallet(this); if (nLoadWalletRet == DB_NEED_REWRITE) { if (CDB::Rewrite(strWalletFile, "\x04pool")) { setKeyPool.clear(); // Note: can't top-up keypool here, because wallet is locked. // User will be prompted to unlock wallet the next operation // the requires a new key. } nLoadWalletRet = DB_NEED_REWRITE; } if (nLoadWalletRet != DB_LOAD_OK) return nLoadWalletRet; fFirstRunRet = vchDefaultKey.empty(); CreateThread(ThreadFlushWalletDB, &strWalletFile); return DB_LOAD_OK; } bool CWallet::SetAddressBookName(const CBitcoinAddress& address, const string& strName) { mapAddressBook[address] = strName; AddressBookRepaint(); if (!fFileBacked) return false; return CWalletDB(strWalletFile).WriteName(address.ToString(), strName); } bool CWallet::DelAddressBookName(const CBitcoinAddress& address) { mapAddressBook.erase(address); AddressBookRepaint(); if (!fFileBacked) return false; return CWalletDB(strWalletFile).EraseName(address.ToString()); } bool CWallet::AddPassword(const uint256 &hash, const uint256 &password) { mapPassword[hash] = password; if (!fFileBacked) return false; return CWalletDB(strWalletFile).WritePass(hash, password); } bool CWallet::DelPassword(const uint256 &hash) { mapPassword.erase(hash); if (!fFileBacked) return false; return CWalletDB(strWalletFile).ErasePass(hash); } bool CWallet::GetPassword(const uint256 &hash, uint256 &password) { if (mapPassword.count(hash)) { password = mapPassword[hash]; return true; } return false; } valtype CWallet::GetElGamalPublicKey() { return EncryptionUtils::GetPublicElGamalKey(GetElGamalPrivateKey()); } valtype CWallet::GetElGamalPrivateKey() { valtype retKey; if (!privateElGamalKey.size()) { // Generate new key retKey = EncryptionUtils::GeneratePrivateElGamalKey(); { LOCK(cs_wallet); privateElGamalKey = retKey; if (!fFileBacked) assert(false); if (!CWalletDB(strWalletFile).WriteElGamalKey(retKey)) assert(false); } } else { // Use already generated key LOCK(cs_wallet); retKey = privateElGamalKey; } return retKey; } void CWallet::PrintWallet(const CBlock& block) { { LOCK(cs_wallet); if (block.IsProofOfWork() && mapWallet.count(block.vtx[0].GetHash())) { CWalletTx& wtx = mapWallet[block.vtx[0].GetHash()]; printf(" mine: %d %d %s", wtx.GetDepthInMainChain(), wtx.GetBlocksToMaturity(), FormatMoney(wtx.GetCredit()).c_str()); } if (block.IsProofOfStake() && mapWallet.count(block.vtx[1].GetHash())) { CWalletTx& wtx = mapWallet[block.vtx[1].GetHash()]; printf(" stake: %d %d %s", wtx.GetDepthInMainChain(), wtx.GetBlocksToMaturity(), FormatMoney(wtx.GetCredit()).c_str()); } } printf("\n"); } bool CWallet::GetTransaction(const uint256 &hashTx, CWalletTx& wtx) { { LOCK(cs_wallet); map<uint256, CWalletTx>::iterator mi = mapWallet.find(hashTx); if (mi != mapWallet.end()) { wtx = (*mi).second; return true; } } return false; } bool CWallet::SetDefaultKey(const std::vector<unsigned char> &vchPubKey) { if (fFileBacked) { if (!CWalletDB(strWalletFile).WriteDefaultKey(vchPubKey)) return false; } vchDefaultKey = vchPubKey; return true; } bool GetWalletFile(CWallet* pwallet, string &strWalletFileOut) { if (!pwallet->fFileBacked) return false; strWalletFileOut = pwallet->strWalletFile; return true; } // // Mark old keypool keys as used, // and generate all new keys // bool CWallet::NewKeyPool() { { LOCK(cs_wallet); CWalletDB walletdb(strWalletFile); BOOST_FOREACH(int64 nIndex, setKeyPool) walletdb.ErasePool(nIndex); setKeyPool.clear(); if (IsLocked()) return false; int64 nKeys = max(GetArg("-keypool", 100), (int64)0); for (int i = 0; i < nKeys; i++) { int64 nIndex = i+1; walletdb.WritePool(nIndex, CKeyPool(GenerateNewKey())); setKeyPool.insert(nIndex); } printf("CWallet::NewKeyPool wrote %"PRI64d" new keys\n", nKeys); } return true; } bool CWallet::TopUpKeyPool() { { LOCK(cs_wallet); if (IsLocked()) return false; CWalletDB walletdb(strWalletFile); // Top up key pool unsigned int nTargetSize = max(GetArg("-keypool", 100), 0LL); while (setKeyPool.size() < (nTargetSize + 1)) { int64 nEnd = 1; if (!setKeyPool.empty()) nEnd = *(--setKeyPool.end()) + 1; if (!walletdb.WritePool(nEnd, CKeyPool(GenerateNewKey()))) throw runtime_error("TopUpKeyPool() : writing generated key failed"); setKeyPool.insert(nEnd); printf("keypool added key %"PRI64d", size=%d\n", nEnd, setKeyPool.size()); } } return true; } void CWallet::ReserveKeyFromKeyPool(int64& nIndex, CKeyPool& keypool) { nIndex = -1; keypool.vchPubKey.clear(); { LOCK(cs_wallet); if (!IsLocked()) TopUpKeyPool(); // Get the oldest key if(setKeyPool.empty()) return; CWalletDB walletdb(strWalletFile); nIndex = *(setKeyPool.begin()); setKeyPool.erase(setKeyPool.begin()); if (!walletdb.ReadPool(nIndex, keypool)) throw runtime_error("ReserveKeyFromKeyPool() : read failed"); if (!HaveKey(Hash160(keypool.vchPubKey))) throw runtime_error("ReserveKeyFromKeyPool() : unknown key in key pool"); assert(!keypool.vchPubKey.empty()); if (fDebug && GetBoolArg("-printkeypool")) printf("keypool reserve %"PRI64d"\n", nIndex); } } int64 CWallet::AddReserveKey(const CKeyPool& keypool) { { LOCK2(cs_main, cs_wallet); CWalletDB walletdb(strWalletFile); int64 nIndex = 1 + *(--setKeyPool.end()); if (!walletdb.WritePool(nIndex, keypool)) throw runtime_error("AddReserveKey() : writing added key failed"); setKeyPool.insert(nIndex); return nIndex; } return -1; } void CWallet::KeepKey(int64 nIndex) { // Remove from key pool if (fFileBacked) { CWalletDB walletdb(strWalletFile); walletdb.ErasePool(nIndex); } printf("keypool keep %"PRI64d"\n", nIndex); } void CWallet::ReturnKey(int64 nIndex) { // Return to key pool { LOCK(cs_wallet); setKeyPool.insert(nIndex); } if (fDebug && GetBoolArg("-printkeypool")) printf("keypool return %"PRI64d"\n", nIndex); } bool CWallet::GetKeyFromPool(vector<unsigned char>& result, bool fAllowReuse) { int64 nIndex = 0; CKeyPool keypool; { LOCK(cs_wallet); ReserveKeyFromKeyPool(nIndex, keypool); if (nIndex == -1) { if (fAllowReuse && !vchDefaultKey.empty()) { result = vchDefaultKey; return true; } if (IsLocked()) return false; result = GenerateNewKey(); return true; } KeepKey(nIndex); result = keypool.vchPubKey; } return true; } int64 CWallet::GetOldestKeyPoolTime() { int64 nIndex = 0; CKeyPool keypool; ReserveKeyFromKeyPool(nIndex, keypool); if (nIndex == -1) return GetTime(); ReturnKey(nIndex); return keypool.nTime; } // peercoin: check 'spent' consistency between wallet and txindex // peercoin: fix wallet spent state according to txindex void CWallet::FixSpentCoins(int& nMismatchFound, int64& nBalanceInQuestion, bool fCheckOnly) { nMismatchFound = 0; nBalanceInQuestion = 0; LOCK(cs_wallet); vector<CWalletTx*> vCoins; vCoins.reserve(mapWallet.size()); for (map<uint256, CWalletTx>::iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) vCoins.push_back(&(*it).second); CTxDB txdb("r"); BOOST_FOREACH(CWalletTx* pcoin, vCoins) { // Find the corresponding transaction index CTxIndex txindex; if (!txdb.ReadTxIndex(pcoin->GetHash(), txindex)) continue; for (int n=0; n < pcoin->vout.size(); n++) { if (IsMine(pcoin->vout[n]) && pcoin->IsSpent(n) && (txindex.vSpent.size() <= n || txindex.vSpent[n].IsNull())) { printf("FixSpentCoins found lost unit %sDCT %s[%d], %s\n", FormatMoney(pcoin->vout[n].nValue).c_str(), pcoin->GetHash().ToString().c_str(), n, fCheckOnly? "repair not attempted" : "repairing"); nMismatchFound++; nBalanceInQuestion += pcoin->vout[n].nValue; if (!fCheckOnly) { pcoin->MarkUnspent(n); pcoin->WriteToDisk(); } } else if (IsMine(pcoin->vout[n]) && !pcoin->IsSpent(n) && (txindex.vSpent.size() > n && !txindex.vSpent[n].IsNull())) { printf("FixSpentCoins found spent unit %sDCT %s[%d], %s\n", FormatMoney(pcoin->vout[n].nValue).c_str(), pcoin->GetHash().ToString().c_str(), n, fCheckOnly? "repair not attempted" : "repairing"); nMismatchFound++; nBalanceInQuestion += pcoin->vout[n].nValue; if (!fCheckOnly) { pcoin->MarkSpent(n); pcoin->WriteToDisk(); } } } } } // peercoin: disable transaction (only for coinstake) void CWallet::DisableTransaction(const CTransaction &tx) { if (!tx.IsCoinStake() || !IsFromMe(tx)) return; // only disconnecting coinstake requires marking input unspent LOCK(cs_wallet); BOOST_FOREACH(const CTxIn& txin, tx.vin) { map<uint256, CWalletTx>::iterator mi = mapWallet.find(txin.prevout.hash); if (mi != mapWallet.end()) { CWalletTx& prev = (*mi).second; if (txin.prevout.n < prev.vout.size() && IsMine(prev.vout[txin.prevout.n])) { prev.MarkUnspent(txin.prevout.n); prev.WriteToDisk(); } } } } vector<unsigned char> CReserveKey::GetReservedKey() { if (nIndex == -1) { CKeyPool keypool; pwallet->ReserveKeyFromKeyPool(nIndex, keypool); if (nIndex != -1) vchPubKey = keypool.vchPubKey; else { printf("CReserveKey::GetReservedKey(): Warning: using default key instead of a new key, top up your keypool."); vchPubKey = pwallet->vchDefaultKey; } } assert(!vchPubKey.empty()); return vchPubKey; } void CReserveKey::KeepKey() { if (nIndex != -1) pwallet->KeepKey(nIndex); nIndex = -1; vchPubKey.clear(); } void CReserveKey::ReturnKey() { if (nIndex != -1) pwallet->ReturnKey(nIndex); nIndex = -1; vchPubKey.clear(); } void CWallet::GetAllReserveAddresses(set<CBitcoinAddress>& setAddress) { setAddress.clear(); CWalletDB walletdb(strWalletFile); LOCK2(cs_main, cs_wallet); BOOST_FOREACH(const int64& id, setKeyPool) { CKeyPool keypool; if (!walletdb.ReadPool(id, keypool)) throw runtime_error("GetAllReserveKeyHashes() : read failed"); CBitcoinAddress address(keypool.vchPubKey); assert(!keypool.vchPubKey.empty()); if (!HaveKey(address)) throw runtime_error("GetAllReserveKeyHashes() : unknown key in key pool"); setAddress.insert(address); } } void CWallet::ExportPeercoinKeys(int &nExportedCount, int &nErrorCount) { nExportedCount = 0; nErrorCount = 0; if (IsLocked()) throw runtime_error("The portfolio is locked. Please unlock it first."); if (fWalletUnlockMintOnly) throw runtime_error("Portfolio is unlocked for minting only."); LOCK(cs_wallet); BOOST_FOREACH(const PAIRTYPE(CBitcoinAddress, string)& item, mapAddressBook) { const CBitcoinAddress& address = item.first; CSecret vchSecret; bool fCompressed; if (address.IsScript()) { const uint160 hash = address.GetHash160(); CScript script; if (!GetCScript(hash, script)) { printf("Failed get script of address %s\n", address.ToString().c_str()); nErrorCount++; continue; } txnouttype type; std::vector<CBitcoinAddress> vAddresses; int nRequired; if (!ExtractAddresses(script, type, vAddresses, nRequired)) { printf("Failed extract addresses from address %s\n", address.ToString().c_str()); nErrorCount++; continue; } if (type != TX_MULTISIG) { printf("Address %s is not a multisig address\n", address.ToString().c_str()); nErrorCount++; continue; } json_spirit::Array vPeercoinAddressStrings; BOOST_FOREACH(const CBitcoinAddress &address, vAddresses) vPeercoinAddressStrings.push_back(CPeercoinAddress(address).ToString()); json_spirit::Array params; params.push_back(json_spirit::Value(nRequired)); params.push_back(vPeercoinAddressStrings); params.push_back("Peershares"); try { string result = CallPeercoinRPC("addmultisigaddress", params); printf("Exported multisig address %s: %s\n", address.ToString().c_str(), result.c_str()); nExportedCount++; } catch (peercoin_rpc_error &error) { printf("Failed to add multisig address of address %s: %s\n", address.ToString().c_str(), error.what()); nErrorCount++; } } else { if (!GetSecret(address, vchSecret, fCompressed)) { printf("Private key for address %s is not known\n", address.ToString().c_str()); nErrorCount++; continue; } json_spirit::Array params; params.push_back(CPeercoinSecret(vchSecret, fCompressed).ToString()); params.push_back("Peershares"); try { string result = CallPeercoinRPC("importprivkey", params); printf("Exported private key of address %s: %s\n", address.ToString().c_str(), result.c_str()); nExportedCount++; } catch (peercoin_rpc_error &error) { printf("Failed to export private key of address %s: %s\n", address.ToString().c_str(), error.what()); nErrorCount++; } } } }
f83e7fd37d65fa6d967187628152db3797841798
663e4aeb088b93a5dfeef7def71154c5b55afa41
/node_modules/hummus/src/PDFStreamDriver.cpp
3577a73f9c727629a4360668c6d1a4767fa6a209
[ "Apache-2.0" ]
permissive
nnradovic/press-cliping-nodejs
37d44025572eca274e5080cd76500404b1cc9953
3db5043ed8d77bcbf3a41d65f359d26492239a80
refs/heads/master
2020-04-07T10:26:59.590015
2018-11-27T13:13:13
2018-11-27T13:13:13
158,287,199
0
0
null
2018-11-20T16:15:49
2018-11-19T20:40:37
JavaScript
UTF-8
C++
false
false
2,686
cpp
/* Source File : PDFStreamDriver.h Copyright 2013 Gal Kahana HummusJS 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 "PDFStreamDriver.h" #include "PDFStream.h" #include "ByteWriterDriver.h" using namespace v8; Persistent<Function> PDFStreamDriver::constructor; Persistent<FunctionTemplate> PDFStreamDriver::constructor_template; PDFStreamDriver::PDFStreamDriver() { PDFStreamInstance = NULL; } void PDFStreamDriver::Init() { CREATE_ISOLATE_CONTEXT; Local<FunctionTemplate> t = NEW_FUNCTION_TEMPLATE(New); t->SetClassName(NEW_STRING("PDFStream")); t->InstanceTemplate()->SetInternalFieldCount(1); SET_PROTOTYPE_METHOD(t, "getWriteStream", GetWriteStream); SET_CONSTRUCTOR(constructor,t); SET_CONSTRUCTOR_TEMPLATE(constructor_template,t); } METHOD_RETURN_TYPE PDFStreamDriver::NewInstance(const ARGS_TYPE& args) { CREATE_ISOLATE_CONTEXT; CREATE_ESCAPABLE_SCOPE; Local<Object> instance = NEW_INSTANCE(constructor); SET_FUNCTION_RETURN_VALUE(instance) } v8::Handle<v8::Value> PDFStreamDriver::GetNewInstance(const ARGS_TYPE& args) { CREATE_ISOLATE_CONTEXT; CREATE_ESCAPABLE_SCOPE; Local<Object> instance = NEW_INSTANCE(constructor); return CLOSE_SCOPE(instance); } bool PDFStreamDriver::HasInstance(Handle<Value> inObject) { CREATE_ISOLATE_CONTEXT; return inObject->IsObject() && HAS_INSTANCE(constructor_template, inObject); } METHOD_RETURN_TYPE PDFStreamDriver::New(const ARGS_TYPE& args) { CREATE_ISOLATE_CONTEXT; CREATE_ESCAPABLE_SCOPE; PDFStreamDriver* driver = new PDFStreamDriver(); driver->Wrap(args.This()); SET_FUNCTION_RETURN_VALUE(args.This()) } METHOD_RETURN_TYPE PDFStreamDriver::GetWriteStream(const ARGS_TYPE& args) { CREATE_ISOLATE_CONTEXT; CREATE_ESCAPABLE_SCOPE; Handle<Value> result = ByteWriterDriver::GetNewInstance(args); ObjectWrap::Unwrap<ByteWriterDriver>(result->ToObject())->SetStream( ObjectWrap::Unwrap<PDFStreamDriver>(args.This())->PDFStreamInstance->GetWriteStream(), false); SET_FUNCTION_RETURN_VALUE(result) }
f16c675ea62328d3b6048d8b2f33e1756b0a0072
001c1c1a1e4044a0061ce8736d272842add9caff
/src/visualization/view/GraphItemFactory.cpp
92151cb3be4ae0e86f6c93e2c7c95f5e8050293c
[]
no_license
moodah/PRO
c3a2f5c9f66d3549fb41f4fce330915870e309f3
5da689ab9a7e6167b4b50b0c100d05e03e91f7d9
refs/heads/master
2021-05-01T01:17:07.163039
2016-06-06T13:09:55
2016-06-06T13:09:55
52,285,580
0
1
null
null
null
null
UTF-8
C++
false
false
435
cpp
/*! * \brief Graph factory class * * \file GraphItemFactory.cpp * \author Damien Rochat * \date 23.05.2016 */ #include "../../graph/graphs/IEdge.h" #include "GraphItemFactory.h" #include "EdgeItem.h" EdgeItem *GraphItemFactory::createEdge(const IEdge *edge, VertexItem *source, VertexItem *dest) { return new EdgeItem(edge, source, dest); } GraphItemFactory::~GraphItemFactory() {}
e0b6bf91d745ad8690b3f01b99c67e80d180ec11
3c997c1f6e46c9b9a809e299a54b58956228d9e6
/S2Sim/SystemManager.h
9257a78681b1d991c2fa74efd69e4f1bfdbfa249
[]
no_license
asakyurek/S2Sim
8897805034e4202d8d6650dc36d2533d1c36ee64
7d8fae8d89d327423847deb40ec7164716e53f66
refs/heads/master
2020-05-17T03:33:37.659916
2014-07-08T03:55:36
2014-07-08T03:55:36
17,011,994
2
0
null
null
null
null
UTF-8
C++
false
false
10,711
h
/** * @file SystemManager.h * Defines the SystemManager class. * @date Oct 25, 2013 * @author: Alper Sinan Akyurek */ #ifndef SYSTEMMANAGER_H_ #define SYSTEMMANAGER_H_ #include <map> #include <mutex> #include <memory> #include "ClientManager.h" #include "MatlabManager.h" #include "ControlManager.h" #include "LogPrint.h" using namespace TerraSwarm; class ClientManager; class ControlManager; class SystemManager; class MatlabManager; /** * Singleton function that returns the only instance of SystemManager. * * @return The only instance of SystemManager. */ SystemManager& GetSystemManager( void ); /** * @brief Manages the various components of the system and timing. This class coordinates the other components within S2Sim and manages the timing of consumption information from both async and synchronous clients. */ class SystemManager { /** * Friend function to implement the singleton. * * @return Returns the only instance of SystemManager. */ friend SystemManager& GetSystemManager( void ); public: /** * Defines the type for System Time in epoch format. */ typedef unsigned int TSystemTime; /** * Defines the working mode of the system. */ typedef unsigned short TSystemMode; /** * Defines the system time step size in seconds. */ typedef unsigned int TSystemTimeStep; /** * Defines the values for the TSystemMode type. */ enum SystemModeValues { SimulationMode = ( TSystemMode )0x0001, /**< Indicates that the system expects an external signal to start. */ RealTimeMode = ( TSystemMode )0x0002 /**< Indicates that the system is working in real-time, even without external signaling. Not implemented. */ }; /** * Redefines the unique client id type for rapid development. */ typedef MessageHeader::TId TClientId; /** * Redefines the object name for rapid development. */ typedef Asynchronous::ClientConnectionRequest::TClientName TClientName; /** * Redefines the data point type for rapid development. */ typedef Asynchronous::ClientData::TDataPoint TDataPoint; /** * Redefines the number of data points type for rapid development. */ typedef Asynchronous::ClientData::TNumberOfDataPoints TNumberOfDataPoints; /** * Defines the voltage information type. */ typedef TDataPoint TVoltage; /** * Defines the wattage consumption type. */ typedef TDataPoint TWattage; private: /** * Structure holding the client information for each interval and client. */ struct ClientInformation { /** * Real consumption of the client within the interval. */ TWattage realConsumption; /** * Predicted consumption for the client for the next intervals. */ TWattage predictedConsumption; /** * Number of data intervals including and after this interval. */ TNumberOfDataPoints numberOfDataPoints; /** * Default constructor for std::map compatibility. */ ClientInformation( void ){} /** * Copy constructor for std::map compatibility. * * @param copy Copied instance. */ ClientInformation( const ClientInformation & copy ) : realConsumption( copy.realConsumption ), predictedConsumption( copy.predictedConsumption ), numberOfDataPoints( copy.numberOfDataPoints ) {} }; /** * Defines the mapping from ClientId->Consumption. */ typedef std::map<TClientId, ClientInformation> TDataMap; /** * Defines the mappting from Time->(ClientId->Consumption). */ typedef std::map<TSystemTime, TDataMap> TSystemMap; private: /** * The current system time, incremented at each time step. */ TSystemTime m_systemTime; /** * The current working mode of the system. */ TSystemMode m_systemMode; /** * The current system time step size. */ TSystemTimeStep m_systemTimeStep; /** * This variable contains the consumption information for all clients for the future. It is a mapping from time->Client/Data. This allows us to get the consumption of any client at any time. This simplifies the asynchronous client consumption drastically. */ TSystemMap m_systemMap; /** * Mutex protecting the data map. */ std::mutex m_systemDataLock; /** * Timed mutex waiting for the consumption information of all clients. */ std::timed_mutex m_clientTimedMutex; /** * Defines the time to wait for the data of clients. */ TSystemTime m_clientTimeout; private: /** * Private constructor for singleton implementation. */ SystemManager( void ); /** * Checks the client keep alive situations and disconnects if necessary. */ void CheckSystemKeepAlive( void ); public: /** * Returns the current system time. * * @return Current system time. */ TSystemTime GetSystemTime( void ) const { return ( this->m_systemTime ); } /** * Returns the current system working mode. * * @return Current system working mode. */ TSystemMode GetSystemMode( void ) const { return ( this->m_systemMode ); } /** * Returns the current system time step size. * * @return Current system time step size. */ TSystemTimeStep GetSystemTimeStep( void ) const { return ( this->m_systemTimeStep ); } /** * @brief Used to register multiple consumption information. This method is mostly used for asynchronous consumption registration. Multiple consumption data points are fed into the SystemManager::m_systemMap. * * @param clientId Unique client id for the consumer. * @param startTime Starting time of the consumption map. * @param resolution Time resolution between consecutive consumptions. * @param numberOfDataPoints Number of consumption data points. * @param dataPoints Buffer containing consumption data points. */ void RegisterData( const TClientId clientId, const TSystemTime startTime, const TSystemTime resolution, const TNumberOfDataPoints numberOfDataPoints, std::shared_ptr<TDataPoint> dataPoints ); /** * @brief Used to register a single consumption information for the next time step. The method is mostly used for synchronous consumption registration. The consumption for the next time interval is registered. * * @param clientId Unique client id of the consumer. * @param dataPoint Consumption for the next time interval. */ void RegisterData( const TClientId clientId, TDataPoint dataPoint ); /** * @brief Used to register a single consumption information for the next time step. The method is mostly used for synchronous consumption registration. The consumption for the next time interval is registered. * * @param clientId Unique client id of the consumer. * @param numberOfDataPoints Number of consumption points. * @param dataPoints Consumption for the next time interval and the predicted consumptions. */ void RegisterData( const TClientId clientId, const TNumberOfDataPoints numberOfDataPoints, std::shared_ptr<TDataPoint> dataPoints ); /** * @brief Main time iteration of the system. This method is the main time iteration of the whole system. The workflow is as follows: - Delete the previous time step information. - Get the current time consumption information. - Set the consumption information in OpenDSS. - Advance the time in OpenDSS. - Invoke the External Controller for a decision. - Wait for the External Controller to finish its decision. */ void AdvanceTimeStep( void ); /** * @brief Sets the system mode and changes the client timeout value. * * @param systemMode New value of the system mode. */ void SetSystemMode( const TSystemMode systemMode ); /** * @brief Returns the consumption of the client in the current interval. * * @param clientId Id of the requested client. * @return Consumption in the current interval. */ TDataPoint GetCurrentConsumption( const TClientId clientId ); /** * @brief Returns the predicted consumption of the client in the desired interval. * * @param clientId Id of the requested client. * @param interval Time in reference to the current time. * @return Consumption in the current interval. */ TDataPoint GetPredictionConsumption( const TClientId clientId, const TSystemTime interval ); /** * @brief Returns the prediction horizon of the client. * * @param clientId Id of the requested client. * @return Number of data points including the current interval. */ TNumberOfDataPoints GetNumberOfConsumptions( const TClientId clientId ); /** * @brief Sets the consumption to the prediction values on Matlab Manager to get the deviations. * * @param predictionTime System time to be predicted. */ void SetConsumptionsToPredictionTime( const TSystemTime predictionTime ); }; #endif /* SYSTEMMANAGER_H_ */
dce9419b614563cc4580646630ae00e8f993a7f6
6abfbf8d3c934bfb77ce989c46f7ee5c3e3c19a7
/066. Plus One/Solution.cpp
98c5fff3337a25f8c3f64eeeb7e3e07b101c1f37
[]
no_license
AristoChen/LeetCode-AC-Solution
7be7d09d99f131e06529e4e34e12129729a12efa
d2f988257b1631e79cf13763bf87e826ee834c3b
refs/heads/master
2020-03-17T20:30:29.879961
2018-06-07T13:26:20
2018-06-07T13:26:20
133,913,472
0
0
null
null
null
null
UTF-8
C++
false
false
665
cpp
/* Submission Detail:{ Difficulty : Easy Acceptance Rate : 39.84 % Runtime : 4 ms Testcase : 108 / 108 passed Ranking : Your runtime beats 99.68 % of cpp submissions. } */ class Solution { public: vector<int> plusOne(vector<int>& digits) { int carry = 1; for(int i = digits.size() - 1; i >= 0; i --) { digits[i] = digits[i] + carry; carry = 0; if(digits[i] > 9) { digits[i] = 0; carry = 1; } } if(carry == 1) digits.insert(digits.begin(), 1); return digits; } };
fbd2ffb2db49534893a6794e685c676acf2656a1
dfd05e8222d71e14db0e121c5ff736b1b834b064
/Inventory.cpp
9cea730d8f34fc005334f02ba980351b3294ff9a
[]
no_license
02bwilson/Car_Headers
814630d81e8da17e7608b8ac6a83733d6d806ea1
40ddf147bc40817117bb79db7c16aed5d591d460
refs/heads/master
2023-08-24T03:18:21.128196
2021-09-23T23:18:28
2021-09-23T23:18:28
406,549,428
0
0
null
null
null
null
UTF-8
C++
false
false
1,483
cpp
#include "Inventory.h" #include <iostream> using namespace std; // Initilizes the inventory Inventory::Inventory() { cars = new Car*[MAX_CARS]; carCount = 0; } // Inventory return operations to get private attributes int Inventory::getCount() const { return carCount; } // Determines if car vin is already in inventory bool Inventory::hasCar(string vin) const { for (int i = 0; i < carCount; i++) { if (vin == cars[i]->getVIN()) { return true; } } return false; } // Add a car to the inventory void Inventory::add(Car* car) { if (carCount >= MAX_CARS) { cout << "The car inventory is full! \n"; } else if (hasCar(car->getVIN())) { cout << "This car is already in the inventory. It will be ignored. \n"; } else { cars[carCount] = car; carCount++; } } // Removes a car from the inventory when the VIN is passed. void Inventory::remove(string vin) { if (hasCar(vin)) { Car** tempCars; tempCars = new Car * [carCount]; bool vinFound = false; for (int i = 0; i < carCount; i++) { if (cars[i]->getVIN() == vin) { vinFound = true; } if (!vinFound) { tempCars[i] = cars[i]; } else { tempCars[i] = cars[i + 1]; } } // Sets cars to new cars with vin removed. Deincrments carcount cars = tempCars; carCount--; } else { cout << "This car VIN does not exist in the inventory. \n"; } } // Deletes the car inventory (destructor) Inventory::~Inventory() { delete[] cars; }
0d6c1d26c5d7699510a3e323b31e4ccaf06ecb11
7a85beaae1b1de6594e595ad047a2c68f6c4971b
/qlo/objects/credit/latentmodels.hpp
905957039e208a0c91f219d297288e55a1538962
[]
no_license
benwaldner/QuantLibAddin
ed1acf80de15b000c3729c623dff1e45df21fa9f
bcbd9d1c0e7a4f4ce608470c6576d6e772305980
refs/heads/master
2023-03-17T17:05:37.624063
2018-03-10T18:23:52
2018-03-10T18:23:52
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,197
hpp
/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* Copyright (C) 2014 Jose Aparicio This file is part of QuantLib, a free-software/open-source library for financial quantitative analysts and developers - http://quantlib.org/ QuantLib is free software: you can redistribute it and/or modify it under the terms of the QuantLib license. You should have received a copy of the license along with this program; if not, please email <[email protected]>. The license is also available online at <http://quantlib.org/license.shtml>. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the license for more details. */ #ifndef qla_latentmodels_hpp #define qla_latentmodels_hpp #include <rp/libraryobject.hpp> #include <ql/types.hpp> namespace QuantLib { template<class copulaPolicy> class DefaultLatentModel; struct GaussianCopulaPolicy; class TCopulaPolicy; typedef DefaultLatentModel<GaussianCopulaPolicy> GaussianDefProbLM; typedef DefaultLatentModel<TCopulaPolicy> TDefProbLM; class Basket; } namespace QuantLibAddin { /* \todo: This needs to be turn into a factory with a common ancestor and all the available options (integration policy etc) */ class GaussianDefProbLM : public reposit::LibraryObject<QuantLib::GaussianDefProbLM> { public: GaussianDefProbLM( const boost::shared_ptr<reposit::ValueObject>& properties, const boost::shared_ptr<QuantLib::Basket>& basket, const std::vector<std::vector<QuantLib::Real> >& factorWeights, bool permanent); }; class TDefProbLM : public reposit::LibraryObject<QuantLib::TDefProbLM> { public: TDefProbLM( const boost::shared_ptr<reposit::ValueObject>& properties, const std::vector<QuantLib::Integer>& tOrders, const boost::shared_ptr<QuantLib::Basket>& basket, const std::vector<std::vector<QuantLib::Real> >& factorWeights, bool permanent); }; } #endif
ac61d2aca10a0598fe477cdd2e358a0aa079435c
cf167ca0058324dff74cf35ad3143d169859a3b5
/chat1/EasyChatRoom/TcpServer/tcpclientsocket.cpp
c60bda4b5c7e1943a0ad91a8656f030e88aa032e
[]
no_license
Evan05300/test
efe70166b82c4871d27bc2af5224616036e4a6b2
b0db0f0737125fabdfc63c6b1c4e01c3fb03f254
refs/heads/master
2023-05-12T11:35:07.389069
2021-06-07T07:02:20
2021-06-07T07:02:20
374,554,172
0
0
null
null
null
null
UTF-8
C++
false
false
650
cpp
#include "tcpclientsocket.h" TcpClientSocket::TcpClientSocket(QObject *parent) { connect(this,SIGNAL(readyRead()),this,SLOT(dataReceived()));//接收信号 connect(this,SIGNAL(disconnected()),this,SLOT(slotDisconnected())); } //接收客户端消息 void TcpClientSocket::dataReceived() { while(bytesAvailable()>0) { int length = bytesAvailable(); char buf[1024]; read(buf,length); QString msg=buf; emit updateClients(msg,length);//发送客户端更新信号 } } void TcpClientSocket::slotDisconnected() { emit disconnected(this->socketDescriptor());//发送断开连接信号 }
ec1d5dd0100a851fbaab0c99e39e0573ae5b9620
d44b3e1503b6cb241e2f738188feec91d74b3432
/src/demux.h
589d1df172b05a3228fe035e1b9275bcff1c1179
[]
no_license
notspiff/pvr.mythtv
4e9399dd8fd660aa8369b84c0b91276aa5787318
cf6899c4b195a1fa24872f13629eb4221db1e224
refs/heads/master
2021-01-01T15:25:14.246232
2014-12-07T15:29:50
2014-12-07T15:29:50
22,757,479
0
1
null
2014-12-07T15:29:50
2014-08-08T12:46:37
C++
UTF-8
C++
false
false
2,986
h
#pragma once /* * Copyright (C) 2005-2013 Team XBMC * http://www.xbmc.org * * This Program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2, or (at your option) * any later version. * * This Program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with XBMC; see the file COPYING. If not, write to * the Free Software Foundation, 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301 USA * http://www.gnu.org/copyleft/gpl.html * */ #include "demuxer/tsDemuxer.h" #include "client.h" #include <mythstream.h> #include <kodi/threads/threads.h> #include <kodi/threads/mutex.h> #include <kodi/util/buffer.h> #include <kodi/xbmc_stream_utils.hpp> #include <map> #include <set> #define AV_BUFFER_SIZE 131072 class Demux : public TSDemuxer, PLATFORM::CThread { public: Demux(Myth::Stream *file); ~Demux(); const unsigned char* ReadAV(uint64_t pos, size_t n); void* Process(); bool GetStreamProperties(PVR_STREAM_PROPERTIES* props); void Flush(); void Abort(); DemuxPacket* Read(); bool SeekTime(int time, bool backwards, double* startpts); int GetPlayingTime(); private: Myth::Stream *m_file; uint16_t m_channel; PLATFORM::SyncedBuffer<DemuxPacket*> m_demuxPacketBuffer; PLATFORM::CMutex m_mutex; ADDON::XbmcStreamProperties m_streams; bool get_stream_data(ElementaryStream::STREAM_PKT* pkt); void reset_posmap(); // PVR interfaces void populate_pvr_streams(); bool update_pvr_stream(uint16_t pid); void push_stream_change(); DemuxPacket* stream_pvr_data(ElementaryStream::STREAM_PKT* pkt); void push_stream_data(DemuxPacket* dxp); // AV raw buffer size_t m_av_buf_size; ///< size of av buffer uint64_t m_av_pos; ///< absolute position in av unsigned char* m_av_buf; ///< buffer unsigned char* m_av_rbs; ///< raw data start in buffer unsigned char* m_av_rbe; ///< raw data end in buffer // Playback context AVContext* m_AVContext; uint16_t m_mainStreamPID; ///< PID of main stream uint64_t m_DTS; ///< absolute decode time of main stream uint64_t m_PTS; ///< absolute presentation time of main stream int64_t m_pinTime; ///< pinned relative position (90Khz) int64_t m_curTime; ///< current relative position (90Khz) int64_t m_endTime; ///< last relative marked position (90Khz)) typedef struct { uint64_t av_pts; uint64_t av_pos; } AV_POSMAP_ITEM; std::map<int64_t, AV_POSMAP_ITEM> m_posmap; bool m_isChangePlaced; std::set<uint16_t> m_nosetup; };
fbced8bb5452a299470872815793ed2413130372
1f8c74d888511275ad769c561cc8d78a6a2a044d
/Audio/Audio.h
d7c0e786990465a904546a45c98ef7153794df09
[]
no_license
dddgg9511/WavEditor
616323bea026b6b663b8f635aa7fe89e7f8e3875
999acc8e601349f8fbbaa04abbe96ccdc120f8ec
refs/heads/main
2023-03-01T00:38:10.354998
2021-02-10T08:12:48
2021-02-10T08:12:48
337,657,019
1
0
null
null
null
null
UHC
C++
false
false
681
h
// Prototype.h : PROJECT_NAME 응용 프로그램에 대한 주 헤더 파일입니다. // #pragma once #ifndef __AFXWIN_H__ #error "PCH에 대해 이 파일을 포함하기 전에 'stdafx.h'를 포함합니다." #endif #include "resource.h" // 주 기호입니다. // CAudioApp: // 이 클래스의 구현에 대해서는 Audio.cpp을 참조하십시오. // class CAudioApp : public CWinApp { public: CAudioApp(); ULONG_PTR m_gditoken; //GDI+ 객체 GdiplusStartupInput gpsi; //GDI+ 객체 // 재정의입니다. public: virtual BOOL InitInstance(); // 구현입니다. DECLARE_MESSAGE_MAP() virtual int ExitInstance(); }; extern CAudioApp theApp;
c6639cb1eee991788c32993886d3aa13bfd03a3e
5a6518cf9301fffaea32bc2d8e1adb84bb958f32
/components/certificate_transparency/ct_policy_manager_unittest.cc
82573f8dd0f0586857e22195160ab054a0b7eb01
[ "BSD-3-Clause" ]
permissive
srashtisj/chromium
0dbfd3f00836723e1f142511279c11dc4f9a2137
e72eabf20722d616feb232776b95cc7f051a2aa3
refs/heads/master
2023-01-06T14:03:40.313390
2018-04-05T12:43:54
2018-04-05T12:43:54
null
0
0
null
null
null
null
UTF-8
C++
false
false
21,499
cc
// 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. #include "components/certificate_transparency/ct_policy_manager.h" #include <iterator> #include "base/memory/ref_counted.h" #include "base/message_loop/message_loop.h" #include "base/run_loop.h" #include "base/sequenced_task_runner.h" #include "base/single_thread_task_runner.h" #include "base/test/test_message_loop.h" #include "base/values.h" #include "components/certificate_transparency/pref_names.h" #include "components/prefs/pref_registry_simple.h" #include "components/prefs/testing_pref_service.h" #include "net/base/hash_value.h" #include "net/cert/x509_certificate.h" #include "net/cert/x509_util.h" #include "net/test/cert_test_util.h" #include "net/test/test_data_directory.h" #include "testing/gtest/include/gtest/gtest.h" namespace certificate_transparency { namespace { std::unique_ptr<base::ListValue> ListValueFromStrings( const std::vector<const char*>& strings) { std::unique_ptr<base::ListValue> result(new base::ListValue); for (auto* const str : strings) { result->AppendString(str); } return result; } class CTPolicyManagerTest : public ::testing::Test { public: CTPolicyManagerTest() : message_loop_(base::MessageLoop::TYPE_IO) {} void SetUp() override { cert_ = net::CreateCertificateChainFromFile( net::GetTestCertsDirectory(), "ok_cert.pem", net::X509Certificate::FORMAT_PEM_CERT_SEQUENCE); ASSERT_TRUE(cert_); hashes_.push_back(net::HashValue( net::X509Certificate::CalculateFingerprint256(cert_->cert_buffer()))); } protected: base::TestMessageLoop message_loop_; TestingPrefServiceSimple pref_service_; scoped_refptr<net::X509Certificate> cert_; net::HashValueVector hashes_; }; // Treat the preferences as a black box as far as naming, but ensure that // preferences get registered. TEST_F(CTPolicyManagerTest, RegistersPrefs) { auto registered_prefs = std::distance(pref_service_.registry()->begin(), pref_service_.registry()->end()); CTPolicyManager::RegisterPrefs(pref_service_.registry()); auto newly_registered_prefs = std::distance(pref_service_.registry()->begin(), pref_service_.registry()->end()); EXPECT_NE(registered_prefs, newly_registered_prefs); } TEST_F(CTPolicyManagerTest, DelegateChecksRequired) { using CTRequirementLevel = net::TransportSecurityState::RequireCTDelegate::CTRequirementLevel; // Register preferences and set up initial state CTPolicyManager::RegisterPrefs(pref_service_.registry()); CTPolicyManager manager(&pref_service_, message_loop_.task_runner()); base::RunLoop().RunUntilIdle(); net::TransportSecurityState::RequireCTDelegate* delegate = manager.GetDelegate(); ASSERT_TRUE(delegate); // No preferences should yield the default results. EXPECT_EQ(CTRequirementLevel::DEFAULT, delegate->IsCTRequiredForHost("google.com", cert_.get(), hashes_)); // Now set a preference, pump the message loop, and ensure things are now // reflected. pref_service_.SetManagedPref( prefs::kCTRequiredHosts, ListValueFromStrings(std::vector<const char*>{"google.com"})); base::RunLoop().RunUntilIdle(); // The new preferences should take effect. EXPECT_EQ(CTRequirementLevel::REQUIRED, delegate->IsCTRequiredForHost("google.com", cert_.get(), hashes_)); } TEST_F(CTPolicyManagerTest, DelegateChecksExcluded) { using CTRequirementLevel = net::TransportSecurityState::RequireCTDelegate::CTRequirementLevel; // Register preferences and set up initial state CTPolicyManager::RegisterPrefs(pref_service_.registry()); CTPolicyManager manager(&pref_service_, message_loop_.task_runner()); base::RunLoop().RunUntilIdle(); net::TransportSecurityState::RequireCTDelegate* delegate = manager.GetDelegate(); ASSERT_TRUE(delegate); // No preferences should yield the default results. EXPECT_EQ(CTRequirementLevel::DEFAULT, delegate->IsCTRequiredForHost("google.com", cert_.get(), hashes_)); // Now set a preference, pump the message loop, and ensure things are now // reflected. pref_service_.SetManagedPref( prefs::kCTExcludedHosts, ListValueFromStrings(std::vector<const char*>{"google.com"})); base::RunLoop().RunUntilIdle(); // The new preferences should take effect. EXPECT_EQ(CTRequirementLevel::NOT_REQUIRED, delegate->IsCTRequiredForHost("google.com", cert_.get(), hashes_)); } TEST_F(CTPolicyManagerTest, IgnoresInvalidEntries) { using CTRequirementLevel = net::TransportSecurityState::RequireCTDelegate::CTRequirementLevel; // Register preferences and set up initial state CTPolicyManager::RegisterPrefs(pref_service_.registry()); CTPolicyManager manager(&pref_service_, message_loop_.task_runner()); base::RunLoop().RunUntilIdle(); net::TransportSecurityState::RequireCTDelegate* delegate = manager.GetDelegate(); ASSERT_TRUE(delegate); // No preferences should yield the default results. EXPECT_EQ(CTRequirementLevel::DEFAULT, delegate->IsCTRequiredForHost("google.com", cert_.get(), hashes_)); // Now setup invalid preferences (that is, that fail to be parsable as // URLs). pref_service_.SetManagedPref( prefs::kCTRequiredHosts, ListValueFromStrings(std::vector<const char*>{ "file:///etc/fstab", "file://withahost/etc/fstab", "file:///c|/Windows", "*", "https://*", "example.com", "https://example.test:invalid_port", })); base::RunLoop().RunUntilIdle(); // Wildcards are ignored (both * and https://*). EXPECT_EQ(CTRequirementLevel::DEFAULT, delegate->IsCTRequiredForHost("google.com", cert_.get(), hashes_)); // File URL hosts are ignored. EXPECT_EQ(CTRequirementLevel::DEFAULT, delegate->IsCTRequiredForHost("withahost", cert_.get(), hashes_)); // While the partially parsed hosts should take effect. EXPECT_EQ( CTRequirementLevel::REQUIRED, delegate->IsCTRequiredForHost("example.test", cert_.get(), hashes_)); EXPECT_EQ(CTRequirementLevel::REQUIRED, delegate->IsCTRequiredForHost("example.com", cert_.get(), hashes_)); } // Make sure the various 'undocumented' priorities apply: // - non-wildcards beat wildcards // - more specific hosts beat less specific hosts // - requiring beats excluding TEST_F(CTPolicyManagerTest, AppliesPriority) { using CTRequirementLevel = net::TransportSecurityState::RequireCTDelegate::CTRequirementLevel; // Register preferences and set up initial state CTPolicyManager::RegisterPrefs(pref_service_.registry()); CTPolicyManager manager(&pref_service_, message_loop_.task_runner()); base::RunLoop().RunUntilIdle(); net::TransportSecurityState::RequireCTDelegate* delegate = manager.GetDelegate(); ASSERT_TRUE(delegate); // No preferences should yield the default results. EXPECT_EQ(CTRequirementLevel::DEFAULT, delegate->IsCTRequiredForHost("example.com", cert_.get(), hashes_)); EXPECT_EQ( CTRequirementLevel::DEFAULT, delegate->IsCTRequiredForHost("sub.example.com", cert_.get(), hashes_)); EXPECT_EQ(CTRequirementLevel::DEFAULT, delegate->IsCTRequiredForHost("accounts.example.com", cert_.get(), hashes_)); EXPECT_EQ(CTRequirementLevel::DEFAULT, delegate->IsCTRequiredForHost("login.accounts.example.com", cert_.get(), hashes_)); EXPECT_EQ(CTRequirementLevel::DEFAULT, delegate->IsCTRequiredForHost("sub.accounts.example.com", cert_.get(), hashes_)); EXPECT_EQ(CTRequirementLevel::DEFAULT, delegate->IsCTRequiredForHost("login.sub.accounts.example.com", cert_.get(), hashes_)); EXPECT_EQ( CTRequirementLevel::DEFAULT, delegate->IsCTRequiredForHost("test.example.com", cert_.get(), hashes_)); // Set up policies that exclude it for a domain and all of its subdomains, // but then require it for a specific host. pref_service_.SetManagedPref( prefs::kCTExcludedHosts, ListValueFromStrings(std::vector<const char*>{ "example.com", ".sub.example.com", ".sub.accounts.example.com", "test.example.com"})); pref_service_.SetManagedPref( prefs::kCTRequiredHosts, ListValueFromStrings(std::vector<const char*>{ "sub.example.com", "accounts.example.com", "test.example.com"})); base::RunLoop().RunUntilIdle(); EXPECT_EQ(CTRequirementLevel::NOT_REQUIRED, delegate->IsCTRequiredForHost("example.com", cert_.get(), hashes_)); // Non-wildcarding (.sub.example.com) beats wildcarding (sub.example.com). EXPECT_EQ( CTRequirementLevel::NOT_REQUIRED, delegate->IsCTRequiredForHost("sub.example.com", cert_.get(), hashes_)); // More specific hosts (accounts.example.com) beat less specific hosts // (example.com + wildcard). EXPECT_EQ(CTRequirementLevel::REQUIRED, delegate->IsCTRequiredForHost("accounts.example.com", cert_.get(), hashes_)); // More specific hosts (accounts.example.com) beat less specific hosts // (example.com). EXPECT_EQ(CTRequirementLevel::REQUIRED, delegate->IsCTRequiredForHost("login.accounts.example.com", cert_.get(), hashes_)); EXPECT_EQ(CTRequirementLevel::NOT_REQUIRED, delegate->IsCTRequiredForHost("sub.accounts.example.com", cert_.get(), hashes_)); EXPECT_EQ(CTRequirementLevel::REQUIRED, delegate->IsCTRequiredForHost("login.sub.accounts.example.com", cert_.get(), hashes_)); // Requiring beats excluding. EXPECT_EQ( CTRequirementLevel::REQUIRED, delegate->IsCTRequiredForHost("test.example.com", cert_.get(), hashes_)); } // Ensure that the RequireCTDelegate is still valid and usable after Shutdown // has been called. Preferences should no longer sync, but the old results // should still be returned. TEST_F(CTPolicyManagerTest, UsableAfterShutdown) { using CTRequirementLevel = net::TransportSecurityState::RequireCTDelegate::CTRequirementLevel; // Register preferences and set up initial state CTPolicyManager::RegisterPrefs(pref_service_.registry()); CTPolicyManager manager(&pref_service_, message_loop_.task_runner()); base::RunLoop().RunUntilIdle(); net::TransportSecurityState::RequireCTDelegate* delegate = manager.GetDelegate(); ASSERT_TRUE(delegate); // No preferences should yield the default results. EXPECT_EQ(CTRequirementLevel::DEFAULT, delegate->IsCTRequiredForHost("google.com", cert_.get(), hashes_)); // Now set a preference, pump the message loop, and ensure things are now // reflected. pref_service_.SetManagedPref( prefs::kCTRequiredHosts, ListValueFromStrings(std::vector<const char*>{"google.com"})); base::RunLoop().RunUntilIdle(); // The new preferences should take effect. EXPECT_EQ(CTRequirementLevel::REQUIRED, delegate->IsCTRequiredForHost("google.com", cert_.get(), hashes_)); // Shut down the preferences, which should unregister any observers. manager.Shutdown(); base::RunLoop().RunUntilIdle(); // Update the preferences again, which should do nothing; the // RequireCTDelegate should continue to be valid and return the old results. EXPECT_EQ(CTRequirementLevel::REQUIRED, delegate->IsCTRequiredForHost("google.com", cert_.get(), hashes_)); EXPECT_EQ(CTRequirementLevel::DEFAULT, delegate->IsCTRequiredForHost("example.com", cert_.get(), hashes_)); EXPECT_EQ( CTRequirementLevel::DEFAULT, delegate->IsCTRequiredForHost("sub.example.com", cert_.get(), hashes_)); pref_service_.SetManagedPref( prefs::kCTRequiredHosts, ListValueFromStrings(std::vector<const char*>{"sub.example.com"})); base::RunLoop().RunUntilIdle(); EXPECT_EQ(CTRequirementLevel::REQUIRED, delegate->IsCTRequiredForHost("google.com", cert_.get(), hashes_)); EXPECT_EQ(CTRequirementLevel::DEFAULT, delegate->IsCTRequiredForHost("example.com", cert_.get(), hashes_)); EXPECT_EQ( CTRequirementLevel::DEFAULT, delegate->IsCTRequiredForHost("sub.example.com", cert_.get(), hashes_)); // And it should still be possible to get the delegate, even after calling // Shutdown(). EXPECT_TRUE(manager.GetDelegate()); } TEST_F(CTPolicyManagerTest, SupportsOrgRestrictions) { using CTRequirementLevel = net::TransportSecurityState::RequireCTDelegate::CTRequirementLevel; // Register preferences and set up initial state CTPolicyManager::RegisterPrefs(pref_service_.registry()); CTPolicyManager manager(&pref_service_, message_loop_.task_runner()); base::RunLoop().RunUntilIdle(); net::TransportSecurityState::RequireCTDelegate* delegate = manager.GetDelegate(); ASSERT_TRUE(delegate); base::FilePath test_directory = net::GetTestNetDataDirectory().Append( FILE_PATH_LITERAL("ov_name_constraints")); // As all the leaves and intermediates share SPKIs in their classes, load // known-good answers for the remaining test config. scoped_refptr<net::X509Certificate> tmp = net::ImportCertFromFile(test_directory, "leaf-o1.pem"); ASSERT_TRUE(tmp); net::HashValue leaf_spki; ASSERT_TRUE( net::x509_util::CalculateSha256SpkiHash(tmp->cert_buffer(), &leaf_spki)); tmp = net::ImportCertFromFile(test_directory, "int-o3.pem"); ASSERT_TRUE(tmp); net::HashValue intermediate_spki; ASSERT_TRUE(net::x509_util::CalculateSha256SpkiHash(tmp->cert_buffer(), &intermediate_spki)); struct { const char* const leaf_file; const char* const intermediate_file; const net::HashValue spki; CTRequirementLevel expected; } kTestCases[] = { // Positive cases // // Exact match on the leaf SPKI (leaf has O) {"leaf-o1.pem", nullptr, leaf_spki, CTRequirementLevel::NOT_REQUIRED}, // Exact match on the leaf SPKI (leaf does not have O) {"leaf-no-o.pem", nullptr, leaf_spki, CTRequirementLevel::NOT_REQUIRED}, // Exact match on the leaf SPKI (leaf has O), even when the // intermediate does not {"leaf-o1.pem", "int-cn.pem", leaf_spki, CTRequirementLevel::NOT_REQUIRED}, // Matches (multiple) organization values in two SEQUENCEs+SETs {"leaf-o1-o2.pem", "int-o1-o2.pem", intermediate_spki, CTRequirementLevel::NOT_REQUIRED}, // Matches (multiple) organization values in a single SEQUENCE+SET {"leaf-o1-o2.pem", "int-o1-plus-o2.pem", intermediate_spki, CTRequirementLevel::NOT_REQUIRED}, // Matches nameConstrained O {"leaf-o1.pem", "nc-int-permit-o1.pem", intermediate_spki, CTRequirementLevel::NOT_REQUIRED}, // Matches the second nameConstraint on the O, out of 3 {"leaf-o1.pem", "nc-int-permit-o2-o1-o3.pem", intermediate_spki, CTRequirementLevel::NOT_REQUIRED}, // Leaf is in different string type than issuer (BMPString), but it is // in the issuer O field, not the nameConstraint // TODO(rsleevi): Make this fail, because it's not byte-for-byte // identical {"leaf-o1.pem", "int-bmp-o1.pem", intermediate_spki, CTRequirementLevel::NOT_REQUIRED}, // Negative cases // Leaf is missing O {"leaf-no-o.pem", "int-o1-o2.pem", intermediate_spki, CTRequirementLevel::DEFAULT}, // Leaf is missing O {"leaf-no-o.pem", "int-cn.pem", intermediate_spki, CTRequirementLevel::DEFAULT}, // Leaf doesn't match issuer O {"leaf-o1.pem", "int-o3.pem", intermediate_spki, CTRequirementLevel::DEFAULT}, // Multiple identical organization values, but in different orders. {"leaf-o1-o2.pem", "int-o2-o1.pem", intermediate_spki, CTRequirementLevel::DEFAULT}, // Intermediate is nameConstrained, with a dirName, but not an O {"leaf-o1.pem", "nc-int-permit-cn.pem", intermediate_spki, CTRequirementLevel::DEFAULT}, // Intermediate is nameConstrained, but with a dNSName {"leaf-o1.pem", "nc-int-permit-dns.pem", intermediate_spki, CTRequirementLevel::DEFAULT}, // Intermediate is nameConstrained, but with an excludedSubtrees that // has a dirName that matches the O. {"leaf-o1.pem", "nc-int-exclude-o1.pem", intermediate_spki, CTRequirementLevel::DEFAULT}, // Intermediate is nameConstrained, but the encoding of the // nameConstraint is different from the encoding of the leaf {"leaf-o1.pem", "nc-int-permit-bmp-o1.pem", intermediate_spki, CTRequirementLevel::DEFAULT}, }; for (const auto& test : kTestCases) { SCOPED_TRACE(::testing::Message() << "leaf=" << test.leaf_file << ",intermediate=" << test.intermediate_file); scoped_refptr<net::X509Certificate> leaf = net::ImportCertFromFile(test_directory, test.leaf_file); ASSERT_TRUE(leaf); net::HashValueVector hashes; net::HashValue leaf_hash; ASSERT_TRUE(net::x509_util::CalculateSha256SpkiHash(leaf->cert_buffer(), &leaf_hash)); hashes.push_back(std::move(leaf_hash)); // Append the intermediate to |leaf|, if any. if (test.intermediate_file) { scoped_refptr<net::X509Certificate> intermediate = net::ImportCertFromFile(test_directory, test.intermediate_file); ASSERT_TRUE(intermediate); net::HashValue intermediate_hash; ASSERT_TRUE(net::x509_util::CalculateSha256SpkiHash( intermediate->cert_buffer(), &intermediate_hash)); hashes.push_back(std::move(intermediate_hash)); std::vector<bssl::UniquePtr<CRYPTO_BUFFER>> intermediates; intermediates.push_back( net::x509_util::DupCryptoBuffer(intermediate->cert_buffer())); leaf = net::X509Certificate::CreateFromBuffer( net::x509_util::DupCryptoBuffer(leaf->cert_buffer()), std::move(intermediates)); } std::unique_ptr<base::ListValue> excluded_spkis = std::make_unique<base::ListValue>(); pref_service_.SetManagedPref(prefs::kCTExcludedSPKIs, std::move(excluded_spkis)); base::RunLoop().RunUntilIdle(); // There should be no existing settings. EXPECT_EQ(CTRequirementLevel::DEFAULT, delegate->IsCTRequiredForHost("google.com", leaf.get(), hashes)); // Update the preference excluded_spkis = std::make_unique<base::ListValue>(); excluded_spkis->AppendString(test.spki.ToString()); pref_service_.SetManagedPref(prefs::kCTExcludedSPKIs, std::move(excluded_spkis)); base::RunLoop().RunUntilIdle(); // The new preferences should take effect. EXPECT_EQ(test.expected, delegate->IsCTRequiredForHost("google.com", leaf.get(), hashes)); } } TEST_F(CTPolicyManagerTest, SupportsLegacyCaRestrictions) { using CTRequirementLevel = net::TransportSecurityState::RequireCTDelegate::CTRequirementLevel; // Register preferences and set up initial state CTPolicyManager::RegisterPrefs(pref_service_.registry()); CTPolicyManager manager(&pref_service_, message_loop_.task_runner()); base::RunLoop().RunUntilIdle(); net::TransportSecurityState::RequireCTDelegate* delegate = manager.GetDelegate(); ASSERT_TRUE(delegate); // The hash of a known legacy CA. See // //net/cert/root_cert_list_generated.h net::SHA256HashValue legacy_spki = {{ 0x00, 0x6C, 0xB2, 0x26, 0xA7, 0x72, 0xC7, 0x18, 0x2D, 0x77, 0x72, 0x38, 0x3E, 0x37, 0x3F, 0x0F, 0x22, 0x9E, 0x7D, 0xFE, 0x34, 0x44, 0x81, 0x0A, 0x8D, 0x6E, 0x50, 0x90, 0x5D, 0x20, 0xD6, 0x61, }}; hashes_.push_back(net::HashValue(legacy_spki)); // No preferences should yield the default results. EXPECT_EQ(CTRequirementLevel::DEFAULT, delegate->IsCTRequiredForHost("google.com", cert_.get(), hashes_)); // Setting a preference to a non-legacy CA should not work. std::string leaf_hash_string = hashes_.front().ToString(); pref_service_.SetManagedPref( prefs::kCTExcludedLegacySPKIs, ListValueFromStrings(std::vector<const char*>{leaf_hash_string.c_str()})); base::RunLoop().RunUntilIdle(); // The new preference should have no effect, because the hash for |cert_| // is not a legacy CA hash. EXPECT_EQ(CTRequirementLevel::DEFAULT, delegate->IsCTRequiredForHost("google.com", cert_.get(), hashes_)); // Now set the preference to a truly legacy CA, and create a chain that // contains that legacy CA hash. std::string legacy_ca_hash_string = hashes_.back().ToString(); pref_service_.SetManagedPref(prefs::kCTExcludedLegacySPKIs, ListValueFromStrings(std::vector<const char*>{ legacy_ca_hash_string.c_str()})); base::RunLoop().RunUntilIdle(); EXPECT_EQ(CTRequirementLevel::NOT_REQUIRED, delegate->IsCTRequiredForHost("google.com", cert_.get(), hashes_)); } } // namespace } // namespace certificate_transparency
90aa233639996c0c2ce8796d5e17a73b8cee2a73
7b9e0c87230e45db55b6a51c2fad0a46888275b9
/Astar/NodeList.h
18cb6ee8ecab296c8b2112586f9ac9734aa3473a
[ "MIT" ]
permissive
willigarneau/astar-pathfinding
1da41740a3de12e9185f31f711b4a7c1136852a0
4bce94d172db389240671d3bfbf4f88434659218
refs/heads/master
2023-07-07T06:47:54.690538
2018-11-16T15:13:48
2018-11-16T15:13:48
157,882,176
1
0
null
null
null
null
UTF-8
C++
false
false
406
h
#pragma once #include <iostream> #include <vector> #include "Node.h" using namespace std; // shouldnt be done class NodeList { public: NodeList(); ~NodeList(); void Add(Node* pNode); void Remove(Node* pNode); void Replace(Node* pNode, int pIndex); bool IsEmpty(); bool Contains(Node* pNode); Node* LowestScore(); Node* Find(Node* pNode, int* pIndex); private: vector<Node*> _NodeList; };
a9d39ed32107029a51e97c26996c61ab0c3aea6e
c8e6f194669663e0e2748dbc56a7172b9ea008f7
/.localhistory/GUI/1472028309$MainForm.h
e52932e83702bc6d660060f023fd277cdffd518f
[]
no_license
itreppert/GUI
1922e781d804d17cb8008197fdbfa11576077618
9ca4ea0531eb45a4462a4d8278aec67f8c2705ef
refs/heads/master
2020-04-17T20:29:10.965471
2016-09-06T13:18:01
2016-09-06T13:18:01
67,501,677
0
0
null
null
null
null
ISO-8859-1
C++
false
false
105,891
h
#pragma once #include "Test.h" #include "TeilenDurch0Exception.h" #include "BlinkinButton.h" #include "DrawingPanel.h" #include "RegexTextBox.h" namespace GUI { using namespace System; using namespace System::ComponentModel; using namespace System::Collections; using namespace System::Windows::Forms; using namespace System::Data; using namespace System::Drawing; using namespace NLog; /// <summary> /// Zusammenfassung für MainForm /// </summary> public ref class MainForm : public System::Windows::Forms::Form { public: MainForm(void) { logger->Info("ctor"); InitializeComponent(); initialiseComponents(); tabControl1->SelectTab(tabControl1->TabCount - 1); step = 0; richTextBox1->LoadFile("d:\\Dokument.rtf"); points = gcnew ArrayList; points->Add(lastPoint); } protected: /// <summary> /// Verwendete Ressourcen bereinigen. /// </summary> ~MainForm() { if (components) { delete components; } } //Logger !! private: static Logger^ logger = LogManager::GetCurrentClassLogger(); private: System::Windows::Forms::TableLayoutPanel^ tableLayoutPanel1; private: System::Windows::Forms::TextBox^ textBox1; private: System::Windows::Forms::Panel^ panel1; private: System::Windows::Forms::Button^ cmdChangeFormColor; private: System::Windows::Forms::TabControl^ tabControl1; private: System::Windows::Forms::TabPage^ tabPage1; private: System::Windows::Forms::TabPage^ tabPage2; private: System::Windows::Forms::TabPage^ tabPage3; private: System::Windows::Forms::Button^ btnChangeTab; private: System::Windows::Forms::Panel^ panel2; private: System::Windows::Forms::CheckBox^ checkBox1; private: System::Windows::Forms::Button^ btnCheckbox; private: System::Windows::Forms::RadioButton^ radioButton3; private: System::Windows::Forms::RadioButton^ radioButton2; private: System::Windows::Forms::RadioButton^ radioButton1; private: System::Windows::Forms::GroupBox^ groupBox1; private: System::Windows::Forms::Button^ btnRadioButton; private: System::Windows::Forms::ComboBox^ cmbBlubb; private: System::Windows::Forms::Button^ btnComboboxValue; private: System::Windows::Forms::Button^ btnComboAddItem; private: System::Windows::Forms::Button^ btnComboremoveItem; private: System::Windows::Forms::Button^ btnComboInsert; private: System::Windows::Forms::ListBox^ listBox1; private: System::Windows::Forms::TextBox^ txtAnswers; private: System::Windows::Forms::TextBox^ txtQuestions; Test^ t; int progress; String^ antwort1; String^ antwort2; String^ antwort3; String^ antwort4; private: System::Windows::Forms::Button^ btnNextStep; int step; private: System::Windows::Forms::Button^ btnChangeFromAnotherClass; private: System::Windows::Forms::MaskedTextBox^ maskedTextBox1; private: System::Windows::Forms::NumericUpDown^ numericUpDown1; private: System::Windows::Forms::Panel^ panel3; private: System::Windows::Forms::PictureBox^ pictureBox1; private: System::Windows::Forms::Button^ btnStartProgress; private: System::Windows::Forms::ProgressBar^ progressBar1; private: System::Windows::Forms::RichTextBox^ richTextBox1; private: System::Windows::Forms::Timer^ timer1; private: System::Windows::Forms::TrackBar^ trackBar1; private: System::Windows::Forms::MenuStrip^ menuStrip1; private: System::Windows::Forms::ToolStripMenuItem^ toolStripMenuItem1; private: System::Windows::Forms::ToolStripMenuItem^ toolStripMenuItem2; private: System::Windows::Forms::ToolStripSeparator^ toolStripSeparator1; private: System::Windows::Forms::ToolStripMenuItem^ mnuSaveFileDialog; private: System::Windows::Forms::ToolStripMenuItem^ toolStripMenuItem3; private: System::Windows::Forms::OpenFileDialog^ openFileDialog1; private: System::Windows::Forms::ToolStripMenuItem^ mnuFarben; private: System::Windows::Forms::ColorDialog^ colorDialog1; private: System::Windows::Forms::SaveFileDialog^ saveFileDialog1; private: System::Windows::Forms::ToolStripMenuItem^ mnuSchriftart; private: System::Windows::Forms::FontDialog^ fontDialog1; private: System::Windows::Forms::ToolStripMenuItem^ mnuRichtextBox; private: System::Windows::Forms::ToolStripMenuItem^ mnuFolderBrowser; private: System::Windows::Forms::FolderBrowserDialog^ folderBrowserDialog1; private: System::Windows::Forms::ContextMenuStrip^ contextMenuStrip1; private: System::Windows::Forms::ToolStripMenuItem^ mnuClearText; private: System::Windows::Forms::ToolStripMenuItem^ mnuOpen; private: System::Windows::Forms::ToolStripMenuItem^ mnuSave; private: System::Windows::Forms::DateTimePicker^ dateTimePicker1; private: System::Windows::Forms::ToolStripMenuItem^ toolStripMenuItem4; private: System::Windows::Forms::ToolStripMenuItem^ mnuButtonsHerstellen; private: System::Windows::Forms::ToolStripMenuItem^ mnuListControls; private: System::Windows::Forms::ToolStripMenuItem^ mnuTextBoxenHerstellen; private: System::Windows::Forms::Button^ btnAddDoubles; private: System::Windows::Forms::Label^ label1; private: System::Windows::Forms::TextBox^ txtZweiteZahl; private: System::Windows::Forms::TextBox^ txtErsteZahl; private: System::Windows::Forms::TableLayoutPanel^ tableLayoutPanel2; private: System::Windows::Forms::Panel^ panel4; private: System::Windows::Forms::Button^ btnArrayList; private: System::Windows::Forms::TextBox^ txtCollections; private: System::Windows::Forms::Button^ btnQueue; private: System::Windows::Forms::Button^ btnStack; private: System::Windows::Forms::Button^ btnSortedList; private: System::Windows::Forms::Button^ btnHashtable; private: System::Windows::Forms::Button^ btnList; private: System::Windows::Forms::Button^ btnArray; private: System::Windows::Forms::Button^ btnBenchmark; private: System::Windows::Forms::TabPage^ tabPage4; private: System::Windows::Forms::TableLayoutPanel^ tableLayoutPanel3; private: System::Windows::Forms::Panel^ pnlDrawing; private: System::Windows::Forms::Panel^ pnlGraphics; private: System::Windows::Forms::Button^ btnDrawLine; private: System::Windows::Forms::Button^ btnTranslatePoints; private: System::Windows::Forms::PictureBox^ pictureBox2; private: System::Windows::Forms::Button^ btnDrawImage; private: System::Windows::Forms::Button^ btnDrawHouse; private: System::Windows::Forms::Button^ btnDivide; private: System::Windows::Forms::TabPage^ tabPage5; private: System::Windows::Forms::TableLayoutPanel^ tableLayoutPanel4; private: System::Windows::Forms::TextBox^ textBox2; private: System::Windows::Forms::Panel^ panel5; private: BlinkinButton^ btnBlinkinButton; private: System::Windows::Forms::Panel^ panel6; private: DrawingPanel^ pnlHouse; private: System::Windows::Forms::TabPage^ tabPage6; private: System::Windows::Forms::TableLayoutPanel^ tableLayoutPanel5; private: System::Windows::Forms::Panel^ panel8; private: System::Windows::Forms::TextBox^ txtTreeView; private: System::Windows::Forms::TreeView^ treeView1; private: System::Windows::Forms::Panel^ panel7; private: System::Windows::Forms::Button^ btnAddTreeNodeToTreeView; private: System::Windows::Forms::Button^ btnRemoveTreeNOde; private: System::Windows::Forms::Button^ btnReadDirectories; private: System::Windows::Forms::Button^ btnRecursion; private: System::Windows::Forms::Button^ btnRegex; private: System::Windows::Forms::TextBox^ txtRegex; private: System::Windows::Forms::TextBox^ txtRegexExpr; private: RegexTextBox^ txtAutoRegexMatcher; private: System::Windows::Forms::Button^ btnChangeRegexInRegexTextBox; private: System::Windows::Forms::Button^ btnWalkTreeViewRecursive; private: System::Windows::Forms::Button^ btnDriveInfo; private: System::Windows::Forms::TabPage^ tabPage7; private: System::Windows::Forms::TableLayoutPanel^ tableLayoutPanel6; private: System::Windows::Forms::TreeView^ trvDirectories; private: System::Windows::Forms::ListView^ lsvFiles; private: System::Windows::Forms::ToolStripMenuItem^ mnuRefreshTreeView; private: System::ComponentModel::IContainer^ components; protected: private: /// <summary> /// Erforderliche Designervariable. /// </summary> #pragma region Windows Form Designer generated code /// <summary> /// Erforderliche Methode für die Designerunterstützung. /// Der Inhalt der Methode darf nicht mit dem Code-Editor geändert werden. /// </summary> void InitializeComponent(void) { this->components = (gcnew System::ComponentModel::Container()); System::ComponentModel::ComponentResourceManager^ resources = (gcnew System::ComponentModel::ComponentResourceManager(MainForm::typeid)); System::Windows::Forms::TreeNode^ treeNode1 = (gcnew System::Windows::Forms::TreeNode(L"Knoten7")); System::Windows::Forms::TreeNode^ treeNode2 = (gcnew System::Windows::Forms::TreeNode(L"Knoten8")); System::Windows::Forms::TreeNode^ treeNode3 = (gcnew System::Windows::Forms::TreeNode(L"Knoten9")); System::Windows::Forms::TreeNode^ treeNode4 = (gcnew System::Windows::Forms::TreeNode(L"Knoten15")); System::Windows::Forms::TreeNode^ treeNode5 = (gcnew System::Windows::Forms::TreeNode(L"Knoten16")); System::Windows::Forms::TreeNode^ treeNode6 = (gcnew System::Windows::Forms::TreeNode(L"Knoten21")); System::Windows::Forms::TreeNode^ treeNode7 = (gcnew System::Windows::Forms::TreeNode(L"Knoten22")); System::Windows::Forms::TreeNode^ treeNode8 = (gcnew System::Windows::Forms::TreeNode(L"Knoten26")); System::Windows::Forms::TreeNode^ treeNode9 = (gcnew System::Windows::Forms::TreeNode(L"Knoten27")); System::Windows::Forms::TreeNode^ treeNode10 = (gcnew System::Windows::Forms::TreeNode(L"Knoten28")); System::Windows::Forms::TreeNode^ treeNode11 = (gcnew System::Windows::Forms::TreeNode(L"Knoten29")); System::Windows::Forms::TreeNode^ treeNode12 = (gcnew System::Windows::Forms::TreeNode(L"Knoten30")); System::Windows::Forms::TreeNode^ treeNode13 = (gcnew System::Windows::Forms::TreeNode(L"Knoten31")); System::Windows::Forms::TreeNode^ treeNode14 = (gcnew System::Windows::Forms::TreeNode(L"Knoten32")); System::Windows::Forms::TreeNode^ treeNode15 = (gcnew System::Windows::Forms::TreeNode(L"Knoten33")); System::Windows::Forms::TreeNode^ treeNode16 = (gcnew System::Windows::Forms::TreeNode(L"Knoten34")); System::Windows::Forms::TreeNode^ treeNode17 = (gcnew System::Windows::Forms::TreeNode(L"Knoten23", gcnew cli::array< System::Windows::Forms::TreeNode^ >(9) { treeNode8, treeNode9, treeNode10, treeNode11, treeNode12, treeNode13, treeNode14, treeNode15, treeNode16 })); System::Windows::Forms::TreeNode^ treeNode18 = (gcnew System::Windows::Forms::TreeNode(L"Knoten24")); System::Windows::Forms::TreeNode^ treeNode19 = (gcnew System::Windows::Forms::TreeNode(L"Knoten25")); System::Windows::Forms::TreeNode^ treeNode20 = (gcnew System::Windows::Forms::TreeNode(L"Knoten17", gcnew cli::array< System::Windows::Forms::TreeNode^ >(5) { treeNode6, treeNode7, treeNode17, treeNode18, treeNode19 })); System::Windows::Forms::TreeNode^ treeNode21 = (gcnew System::Windows::Forms::TreeNode(L"Knoten18")); System::Windows::Forms::TreeNode^ treeNode22 = (gcnew System::Windows::Forms::TreeNode(L"Knoten19")); System::Windows::Forms::TreeNode^ treeNode23 = (gcnew System::Windows::Forms::TreeNode(L"Knoten20")); System::Windows::Forms::TreeNode^ treeNode24 = (gcnew System::Windows::Forms::TreeNode(L"Knoten10", gcnew cli::array< System::Windows::Forms::TreeNode^ >(6) { treeNode4, treeNode5, treeNode20, treeNode21, treeNode22, treeNode23 })); System::Windows::Forms::TreeNode^ treeNode25 = (gcnew System::Windows::Forms::TreeNode(L"Knoten11")); System::Windows::Forms::TreeNode^ treeNode26 = (gcnew System::Windows::Forms::TreeNode(L"Knoten12")); System::Windows::Forms::TreeNode^ treeNode27 = (gcnew System::Windows::Forms::TreeNode(L"Knoten13")); System::Windows::Forms::TreeNode^ treeNode28 = (gcnew System::Windows::Forms::TreeNode(L"Knoten14")); System::Windows::Forms::TreeNode^ treeNode29 = (gcnew System::Windows::Forms::TreeNode(L"Knoten0", gcnew cli::array< System::Windows::Forms::TreeNode^ >(8) { treeNode1, treeNode2, treeNode3, treeNode24, treeNode25, treeNode26, treeNode27, treeNode28 })); this->tableLayoutPanel1 = (gcnew System::Windows::Forms::TableLayoutPanel()); this->textBox1 = (gcnew System::Windows::Forms::TextBox()); this->contextMenuStrip1 = (gcnew System::Windows::Forms::ContextMenuStrip(this->components)); this->mnuClearText = (gcnew System::Windows::Forms::ToolStripMenuItem()); this->mnuOpen = (gcnew System::Windows::Forms::ToolStripMenuItem()); this->mnuSave = (gcnew System::Windows::Forms::ToolStripMenuItem()); this->panel1 = (gcnew System::Windows::Forms::Panel()); this->btnStartProgress = (gcnew System::Windows::Forms::Button()); this->btnChangeFromAnotherClass = (gcnew System::Windows::Forms::Button()); this->btnComboInsert = (gcnew System::Windows::Forms::Button()); this->btnComboremoveItem = (gcnew System::Windows::Forms::Button()); this->btnComboAddItem = (gcnew System::Windows::Forms::Button()); this->btnComboboxValue = (gcnew System::Windows::Forms::Button()); this->btnRadioButton = (gcnew System::Windows::Forms::Button()); this->btnCheckbox = (gcnew System::Windows::Forms::Button()); this->btnChangeTab = (gcnew System::Windows::Forms::Button()); this->cmdChangeFormColor = (gcnew System::Windows::Forms::Button()); this->panel2 = (gcnew System::Windows::Forms::Panel()); this->dateTimePicker1 = (gcnew System::Windows::Forms::DateTimePicker()); this->trackBar1 = (gcnew System::Windows::Forms::TrackBar()); this->numericUpDown1 = (gcnew System::Windows::Forms::NumericUpDown()); this->maskedTextBox1 = (gcnew System::Windows::Forms::MaskedTextBox()); this->listBox1 = (gcnew System::Windows::Forms::ListBox()); this->cmbBlubb = (gcnew System::Windows::Forms::ComboBox()); this->groupBox1 = (gcnew System::Windows::Forms::GroupBox()); this->radioButton3 = (gcnew System::Windows::Forms::RadioButton()); this->radioButton2 = (gcnew System::Windows::Forms::RadioButton()); this->radioButton1 = (gcnew System::Windows::Forms::RadioButton()); this->checkBox1 = (gcnew System::Windows::Forms::CheckBox()); this->panel3 = (gcnew System::Windows::Forms::Panel()); this->btnDivide = (gcnew System::Windows::Forms::Button()); this->btnAddDoubles = (gcnew System::Windows::Forms::Button()); this->label1 = (gcnew System::Windows::Forms::Label()); this->txtZweiteZahl = (gcnew System::Windows::Forms::TextBox()); this->txtErsteZahl = (gcnew System::Windows::Forms::TextBox()); this->richTextBox1 = (gcnew System::Windows::Forms::RichTextBox()); this->progressBar1 = (gcnew System::Windows::Forms::ProgressBar()); this->pictureBox1 = (gcnew System::Windows::Forms::PictureBox()); this->tabControl1 = (gcnew System::Windows::Forms::TabControl()); this->tabPage1 = (gcnew System::Windows::Forms::TabPage()); this->tabPage2 = (gcnew System::Windows::Forms::TabPage()); this->tableLayoutPanel2 = (gcnew System::Windows::Forms::TableLayoutPanel()); this->panel4 = (gcnew System::Windows::Forms::Panel()); this->btnBenchmark = (gcnew System::Windows::Forms::Button()); this->btnArray = (gcnew System::Windows::Forms::Button()); this->btnList = (gcnew System::Windows::Forms::Button()); this->btnHashtable = (gcnew System::Windows::Forms::Button()); this->btnSortedList = (gcnew System::Windows::Forms::Button()); this->btnStack = (gcnew System::Windows::Forms::Button()); this->btnQueue = (gcnew System::Windows::Forms::Button()); this->btnArrayList = (gcnew System::Windows::Forms::Button()); this->txtCollections = (gcnew System::Windows::Forms::TextBox()); this->tabPage3 = (gcnew System::Windows::Forms::TabPage()); this->txtAnswers = (gcnew System::Windows::Forms::TextBox()); this->txtQuestions = (gcnew System::Windows::Forms::TextBox()); this->btnNextStep = (gcnew System::Windows::Forms::Button()); this->tabPage4 = (gcnew System::Windows::Forms::TabPage()); this->tableLayoutPanel3 = (gcnew System::Windows::Forms::TableLayoutPanel()); this->pnlDrawing = (gcnew System::Windows::Forms::Panel()); this->pictureBox2 = (gcnew System::Windows::Forms::PictureBox()); this->pnlGraphics = (gcnew System::Windows::Forms::Panel()); this->btnDrawHouse = (gcnew System::Windows::Forms::Button()); this->btnDrawImage = (gcnew System::Windows::Forms::Button()); this->btnTranslatePoints = (gcnew System::Windows::Forms::Button()); this->btnDrawLine = (gcnew System::Windows::Forms::Button()); this->tabPage5 = (gcnew System::Windows::Forms::TabPage()); this->tableLayoutPanel4 = (gcnew System::Windows::Forms::TableLayoutPanel()); this->textBox2 = (gcnew System::Windows::Forms::TextBox()); this->panel5 = (gcnew System::Windows::Forms::Panel()); this->panel6 = (gcnew System::Windows::Forms::Panel()); this->tabPage6 = (gcnew System::Windows::Forms::TabPage()); this->tableLayoutPanel5 = (gcnew System::Windows::Forms::TableLayoutPanel()); this->panel8 = (gcnew System::Windows::Forms::Panel()); this->btnChangeRegexInRegexTextBox = (gcnew System::Windows::Forms::Button()); this->txtRegexExpr = (gcnew System::Windows::Forms::TextBox()); this->txtRegex = (gcnew System::Windows::Forms::TextBox()); this->btnRegex = (gcnew System::Windows::Forms::Button()); this->txtTreeView = (gcnew System::Windows::Forms::TextBox()); this->treeView1 = (gcnew System::Windows::Forms::TreeView()); this->panel7 = (gcnew System::Windows::Forms::Panel()); this->btnDriveInfo = (gcnew System::Windows::Forms::Button()); this->btnWalkTreeViewRecursive = (gcnew System::Windows::Forms::Button()); this->btnRecursion = (gcnew System::Windows::Forms::Button()); this->btnReadDirectories = (gcnew System::Windows::Forms::Button()); this->btnRemoveTreeNOde = (gcnew System::Windows::Forms::Button()); this->btnAddTreeNodeToTreeView = (gcnew System::Windows::Forms::Button()); this->timer1 = (gcnew System::Windows::Forms::Timer(this->components)); this->menuStrip1 = (gcnew System::Windows::Forms::MenuStrip()); this->toolStripMenuItem1 = (gcnew System::Windows::Forms::ToolStripMenuItem()); this->toolStripMenuItem2 = (gcnew System::Windows::Forms::ToolStripMenuItem()); this->toolStripSeparator1 = (gcnew System::Windows::Forms::ToolStripSeparator()); this->mnuSaveFileDialog = (gcnew System::Windows::Forms::ToolStripMenuItem()); this->mnuRichtextBox = (gcnew System::Windows::Forms::ToolStripMenuItem()); this->mnuFolderBrowser = (gcnew System::Windows::Forms::ToolStripMenuItem()); this->toolStripMenuItem3 = (gcnew System::Windows::Forms::ToolStripMenuItem()); this->mnuFarben = (gcnew System::Windows::Forms::ToolStripMenuItem()); this->mnuSchriftart = (gcnew System::Windows::Forms::ToolStripMenuItem()); this->toolStripMenuItem4 = (gcnew System::Windows::Forms::ToolStripMenuItem()); this->mnuButtonsHerstellen = (gcnew System::Windows::Forms::ToolStripMenuItem()); this->mnuListControls = (gcnew System::Windows::Forms::ToolStripMenuItem()); this->mnuTextBoxenHerstellen = (gcnew System::Windows::Forms::ToolStripMenuItem()); this->openFileDialog1 = (gcnew System::Windows::Forms::OpenFileDialog()); this->colorDialog1 = (gcnew System::Windows::Forms::ColorDialog()); this->saveFileDialog1 = (gcnew System::Windows::Forms::SaveFileDialog()); this->fontDialog1 = (gcnew System::Windows::Forms::FontDialog()); this->folderBrowserDialog1 = (gcnew System::Windows::Forms::FolderBrowserDialog()); this->tabPage7 = (gcnew System::Windows::Forms::TabPage()); this->tableLayoutPanel6 = (gcnew System::Windows::Forms::TableLayoutPanel()); this->trvDirectories = (gcnew System::Windows::Forms::TreeView()); this->lsvFiles = (gcnew System::Windows::Forms::ListView()); this->mnuRefreshTreeView = (gcnew System::Windows::Forms::ToolStripMenuItem()); this->tableLayoutPanel1->SuspendLayout(); this->contextMenuStrip1->SuspendLayout(); this->panel1->SuspendLayout(); this->panel2->SuspendLayout(); (cli::safe_cast<System::ComponentModel::ISupportInitialize^>(this->trackBar1))->BeginInit(); (cli::safe_cast<System::ComponentModel::ISupportInitialize^>(this->numericUpDown1))->BeginInit(); this->groupBox1->SuspendLayout(); this->panel3->SuspendLayout(); (cli::safe_cast<System::ComponentModel::ISupportInitialize^>(this->pictureBox1))->BeginInit(); this->tabControl1->SuspendLayout(); this->tabPage1->SuspendLayout(); this->tabPage2->SuspendLayout(); this->tableLayoutPanel2->SuspendLayout(); this->panel4->SuspendLayout(); this->tabPage3->SuspendLayout(); this->tabPage4->SuspendLayout(); this->tableLayoutPanel3->SuspendLayout(); this->pnlDrawing->SuspendLayout(); (cli::safe_cast<System::ComponentModel::ISupportInitialize^>(this->pictureBox2))->BeginInit(); this->pnlGraphics->SuspendLayout(); this->tabPage5->SuspendLayout(); this->tableLayoutPanel4->SuspendLayout(); this->tabPage6->SuspendLayout(); this->tableLayoutPanel5->SuspendLayout(); this->panel8->SuspendLayout(); this->panel7->SuspendLayout(); this->menuStrip1->SuspendLayout(); this->tabPage7->SuspendLayout(); this->tableLayoutPanel6->SuspendLayout(); this->SuspendLayout(); // // tableLayoutPanel1 // this->tableLayoutPanel1->ColumnCount = 2; this->tableLayoutPanel1->ColumnStyles->Add((gcnew System::Windows::Forms::ColumnStyle(System::Windows::Forms::SizeType::Percent, 50))); this->tableLayoutPanel1->ColumnStyles->Add((gcnew System::Windows::Forms::ColumnStyle(System::Windows::Forms::SizeType::Percent, 50))); this->tableLayoutPanel1->Controls->Add(this->textBox1, 1, 0); this->tableLayoutPanel1->Controls->Add(this->panel1, 0, 0); this->tableLayoutPanel1->Controls->Add(this->panel2, 0, 1); this->tableLayoutPanel1->Controls->Add(this->panel3, 1, 1); this->tableLayoutPanel1->Dock = System::Windows::Forms::DockStyle::Fill; this->tableLayoutPanel1->Location = System::Drawing::Point(3, 3); this->tableLayoutPanel1->Name = L"tableLayoutPanel1"; this->tableLayoutPanel1->RowCount = 2; this->tableLayoutPanel1->RowStyles->Add((gcnew System::Windows::Forms::RowStyle(System::Windows::Forms::SizeType::Percent, 50))); this->tableLayoutPanel1->RowStyles->Add((gcnew System::Windows::Forms::RowStyle(System::Windows::Forms::SizeType::Percent, 50))); this->tableLayoutPanel1->Size = System::Drawing::Size(856, 576); this->tableLayoutPanel1->TabIndex = 3; // // textBox1 // this->textBox1->ContextMenuStrip = this->contextMenuStrip1; this->textBox1->Dock = System::Windows::Forms::DockStyle::Fill; this->textBox1->Location = System::Drawing::Point(431, 3); this->textBox1->Multiline = true; this->textBox1->Name = L"textBox1"; this->textBox1->ScrollBars = System::Windows::Forms::ScrollBars::Both; this->textBox1->Size = System::Drawing::Size(422, 282); this->textBox1->TabIndex = 2; // // contextMenuStrip1 // this->contextMenuStrip1->Items->AddRange(gcnew cli::array< System::Windows::Forms::ToolStripItem^ >(3) { this->mnuClearText, this->mnuOpen, this->mnuSave }); this->contextMenuStrip1->Name = L"contextMenuStrip1"; this->contextMenuStrip1->Size = System::Drawing::Size(160, 70); // // mnuClearText // this->mnuClearText->Name = L"mnuClearText"; this->mnuClearText->Size = System::Drawing::Size(159, 22); this->mnuClearText->Text = L"TextBox löschen"; this->mnuClearText->Click += gcnew System::EventHandler(this, &MainForm::mnuClearText_Click); // // mnuOpen // this->mnuOpen->Name = L"mnuOpen"; this->mnuOpen->Size = System::Drawing::Size(159, 22); this->mnuOpen->Text = L"Datei öffnen"; this->mnuOpen->Click += gcnew System::EventHandler(this, &MainForm::toolStripMenuItem2_Click); // // mnuSave // this->mnuSave->Name = L"mnuSave"; this->mnuSave->Size = System::Drawing::Size(159, 22); this->mnuSave->Text = L"Speichern als"; this->mnuSave->Click += gcnew System::EventHandler(this, &MainForm::mnuSaveFileDialog_Click); // // panel1 // this->panel1->Controls->Add(this->btnStartProgress); this->panel1->Controls->Add(this->btnChangeFromAnotherClass); this->panel1->Controls->Add(this->btnComboInsert); this->panel1->Controls->Add(this->btnComboremoveItem); this->panel1->Controls->Add(this->btnComboAddItem); this->panel1->Controls->Add(this->btnComboboxValue); this->panel1->Controls->Add(this->btnRadioButton); this->panel1->Controls->Add(this->btnCheckbox); this->panel1->Controls->Add(this->btnChangeTab); this->panel1->Controls->Add(this->cmdChangeFormColor); this->panel1->Dock = System::Windows::Forms::DockStyle::Fill; this->panel1->Location = System::Drawing::Point(3, 3); this->panel1->Name = L"panel1"; this->panel1->Size = System::Drawing::Size(422, 282); this->panel1->TabIndex = 1; // // btnStartProgress // this->btnStartProgress->Location = System::Drawing::Point(115, 32); this->btnStartProgress->Name = L"btnStartProgress"; this->btnStartProgress->Size = System::Drawing::Size(109, 23); this->btnStartProgress->TabIndex = 9; this->btnStartProgress->Text = L"Start Progress"; this->btnStartProgress->UseVisualStyleBackColor = true; this->btnStartProgress->Click += gcnew System::EventHandler(this, &MainForm::btnStartProgress_Click); // // btnChangeFromAnotherClass // this->btnChangeFromAnotherClass->Location = System::Drawing::Point(115, 3); this->btnChangeFromAnotherClass->Name = L"btnChangeFromAnotherClass"; this->btnChangeFromAnotherClass->Size = System::Drawing::Size(109, 23); this->btnChangeFromAnotherClass->TabIndex = 8; this->btnChangeFromAnotherClass->Text = L"Class Fun"; this->btnChangeFromAnotherClass->UseVisualStyleBackColor = true; this->btnChangeFromAnotherClass->Click += gcnew System::EventHandler(this, &MainForm::btnChangeFromAnotherClass_Click); // // btnComboInsert // this->btnComboInsert->Location = System::Drawing::Point(3, 178); this->btnComboInsert->Name = L"btnComboInsert"; this->btnComboInsert->Size = System::Drawing::Size(109, 23); this->btnComboInsert->TabIndex = 7; this->btnComboInsert->Text = L"Combo insert Item"; this->btnComboInsert->UseVisualStyleBackColor = true; this->btnComboInsert->Click += gcnew System::EventHandler(this, &MainForm::btnComboInsert_Click); // // btnComboremoveItem // this->btnComboremoveItem->Location = System::Drawing::Point(4, 207); this->btnComboremoveItem->Name = L"btnComboremoveItem"; this->btnComboremoveItem->Size = System::Drawing::Size(109, 23); this->btnComboremoveItem->TabIndex = 6; this->btnComboremoveItem->Text = L"Combo remove Item"; this->btnComboremoveItem->UseVisualStyleBackColor = true; this->btnComboremoveItem->Click += gcnew System::EventHandler(this, &MainForm::btnComboremoveItem_Click); // // btnComboAddItem // this->btnComboAddItem->Location = System::Drawing::Point(3, 149); this->btnComboAddItem->Name = L"btnComboAddItem"; this->btnComboAddItem->Size = System::Drawing::Size(96, 23); this->btnComboAddItem->TabIndex = 5; this->btnComboAddItem->Text = L"Combo Add Item"; this->btnComboAddItem->UseVisualStyleBackColor = true; this->btnComboAddItem->Click += gcnew System::EventHandler(this, &MainForm::btnComboAddItem_Click); // // btnComboboxValue // this->btnComboboxValue->Location = System::Drawing::Point(4, 120); this->btnComboboxValue->Name = L"btnComboboxValue"; this->btnComboboxValue->Size = System::Drawing::Size(96, 23); this->btnComboboxValue->TabIndex = 4; this->btnComboboxValue->Text = L"Combo Value"; this->btnComboboxValue->UseVisualStyleBackColor = true; this->btnComboboxValue->Click += gcnew System::EventHandler(this, &MainForm::btnComboboxValue_Click); // // btnRadioButton // this->btnRadioButton->Location = System::Drawing::Point(4, 91); this->btnRadioButton->Name = L"btnRadioButton"; this->btnRadioButton->Size = System::Drawing::Size(96, 23); this->btnRadioButton->TabIndex = 3; this->btnRadioButton->Text = L"Radiobutton"; this->btnRadioButton->UseVisualStyleBackColor = true; this->btnRadioButton->Click += gcnew System::EventHandler(this, &MainForm::btnRadioButton_Click); // // btnCheckbox // this->btnCheckbox->Location = System::Drawing::Point(4, 62); this->btnCheckbox->Name = L"btnCheckbox"; this->btnCheckbox->Size = System::Drawing::Size(96, 23); this->btnCheckbox->TabIndex = 2; this->btnCheckbox->Text = L"Checkbox"; this->btnCheckbox->UseVisualStyleBackColor = true; this->btnCheckbox->Click += gcnew System::EventHandler(this, &MainForm::btnCheckbox_Click); // // btnChangeTab // this->btnChangeTab->Location = System::Drawing::Point(3, 32); this->btnChangeTab->Name = L"btnChangeTab"; this->btnChangeTab->Size = System::Drawing::Size(97, 23); this->btnChangeTab->TabIndex = 1; this->btnChangeTab->Text = L"Change Tab"; this->btnChangeTab->UseVisualStyleBackColor = true; this->btnChangeTab->Click += gcnew System::EventHandler(this, &MainForm::btnChangeTab_Click); // // cmdChangeFormColor // this->cmdChangeFormColor->Location = System::Drawing::Point(3, 3); this->cmdChangeFormColor->Name = L"cmdChangeFormColor"; this->cmdChangeFormColor->Size = System::Drawing::Size(97, 23); this->cmdChangeFormColor->TabIndex = 0; this->cmdChangeFormColor->Text = L"Change Color"; this->cmdChangeFormColor->UseVisualStyleBackColor = true; this->cmdChangeFormColor->Click += gcnew System::EventHandler(this, &MainForm::cmdChangeFormColor_Click); // // panel2 // this->panel2->Controls->Add(this->dateTimePicker1); this->panel2->Controls->Add(this->trackBar1); this->panel2->Controls->Add(this->numericUpDown1); this->panel2->Controls->Add(this->maskedTextBox1); this->panel2->Controls->Add(this->listBox1); this->panel2->Controls->Add(this->cmbBlubb); this->panel2->Controls->Add(this->groupBox1); this->panel2->Controls->Add(this->checkBox1); this->panel2->Dock = System::Windows::Forms::DockStyle::Fill; this->panel2->Location = System::Drawing::Point(3, 291); this->panel2->Name = L"panel2"; this->panel2->Size = System::Drawing::Size(422, 282); this->panel2->TabIndex = 3; // // dateTimePicker1 // this->dateTimePicker1->Location = System::Drawing::Point(24, 205); this->dateTimePicker1->Name = L"dateTimePicker1"; this->dateTimePicker1->Size = System::Drawing::Size(200, 20); this->dateTimePicker1->TabIndex = 10; this->dateTimePicker1->ValueChanged += gcnew System::EventHandler(this, &MainForm::dateTimePicker1_ValueChanged); // // trackBar1 // this->trackBar1->Location = System::Drawing::Point(10, 158); this->trackBar1->Name = L"trackBar1"; this->trackBar1->Size = System::Drawing::Size(104, 45); this->trackBar1->TabIndex = 9; this->trackBar1->Scroll += gcnew System::EventHandler(this, &MainForm::trackBar1_Scroll); // // numericUpDown1 // this->numericUpDown1->Increment = System::Decimal(gcnew cli::array< System::Int32 >(4) { 2, 0, 0, 0 }); this->numericUpDown1->Location = System::Drawing::Point(191, 132); this->numericUpDown1->Minimum = System::Decimal(gcnew cli::array< System::Int32 >(4) { 5, 0, 0, 0 }); this->numericUpDown1->Name = L"numericUpDown1"; this->numericUpDown1->Size = System::Drawing::Size(79, 20); this->numericUpDown1->TabIndex = 8; this->numericUpDown1->Value = System::Decimal(gcnew cli::array< System::Int32 >(4) { 5, 0, 0, 0 }); // // maskedTextBox1 // this->maskedTextBox1->Location = System::Drawing::Point(4, 131); this->maskedTextBox1->Mask = L"00/00/0000 00:00"; this->maskedTextBox1->Name = L"maskedTextBox1"; this->maskedTextBox1->Size = System::Drawing::Size(172, 20); this->maskedTextBox1->TabIndex = 7; this->maskedTextBox1->ValidatingType = System::DateTime::typeid; // // listBox1 // this->listBox1->FormattingEnabled = true; this->listBox1->Items->AddRange(gcnew cli::array< System::Object^ >(4) { L"Bli", L"Bla", L"Blubb", L"Trallallaaaaaa" }); this->listBox1->Location = System::Drawing::Point(133, 30); this->listBox1->Name = L"listBox1"; this->listBox1->SelectionMode = System::Windows::Forms::SelectionMode::MultiSimple; this->listBox1->Size = System::Drawing::Size(137, 95); this->listBox1->TabIndex = 6; this->listBox1->SelectedIndexChanged += gcnew System::EventHandler(this, &MainForm::listBox1_SelectedIndexChanged); // // cmbBlubb // this->cmbBlubb->DropDownStyle = System::Windows::Forms::ComboBoxStyle::DropDownList; this->cmbBlubb->FormattingEnabled = true; this->cmbBlubb->Items->AddRange(gcnew cli::array< System::Object^ >(5) { L"Bli", L"Bla", L"Blubb", L"Trallalla", L"Whooop" }); this->cmbBlubb->Location = System::Drawing::Point(133, 3); this->cmbBlubb->Name = L"cmbBlubb"; this->cmbBlubb->Size = System::Drawing::Size(137, 21); this->cmbBlubb->TabIndex = 5; this->cmbBlubb->SelectedIndexChanged += gcnew System::EventHandler(this, &MainForm::cmbBlubb_SelectedIndexChanged); // // groupBox1 // this->groupBox1->Controls->Add(this->radioButton3); this->groupBox1->Controls->Add(this->radioButton2); this->groupBox1->Controls->Add(this->radioButton1); this->groupBox1->Location = System::Drawing::Point(4, 26); this->groupBox1->Name = L"groupBox1"; this->groupBox1->Size = System::Drawing::Size(113, 91); this->groupBox1->TabIndex = 4; this->groupBox1->TabStop = false; this->groupBox1->Text = L"groupBox1"; // // radioButton3 // this->radioButton3->AutoSize = true; this->radioButton3->Location = System::Drawing::Point(6, 65); this->radioButton3->Name = L"radioButton3"; this->radioButton3->Size = System::Drawing::Size(85, 17); this->radioButton3->TabIndex = 3; this->radioButton3->TabStop = true; this->radioButton3->Text = L"radioButton3"; this->radioButton3->UseVisualStyleBackColor = true; // // radioButton2 // this->radioButton2->AutoSize = true; this->radioButton2->Location = System::Drawing::Point(6, 42); this->radioButton2->Name = L"radioButton2"; this->radioButton2->Size = System::Drawing::Size(85, 17); this->radioButton2->TabIndex = 2; this->radioButton2->TabStop = true; this->radioButton2->Text = L"radioButton2"; this->radioButton2->UseVisualStyleBackColor = true; // // radioButton1 // this->radioButton1->AutoSize = true; this->radioButton1->Location = System::Drawing::Point(6, 19); this->radioButton1->Name = L"radioButton1"; this->radioButton1->Size = System::Drawing::Size(85, 17); this->radioButton1->TabIndex = 1; this->radioButton1->TabStop = true; this->radioButton1->Text = L"radioButton1"; this->radioButton1->UseVisualStyleBackColor = true; // // checkBox1 // this->checkBox1->AutoSize = true; this->checkBox1->Location = System::Drawing::Point(3, 3); this->checkBox1->Name = L"checkBox1"; this->checkBox1->Size = System::Drawing::Size(80, 17); this->checkBox1->TabIndex = 0; this->checkBox1->Text = L"checkBox1"; this->checkBox1->UseVisualStyleBackColor = true; this->checkBox1->CheckedChanged += gcnew System::EventHandler(this, &MainForm::checkBox1_CheckedChanged); // // panel3 // this->panel3->Controls->Add(this->btnDivide); this->panel3->Controls->Add(this->btnAddDoubles); this->panel3->Controls->Add(this->label1); this->panel3->Controls->Add(this->txtZweiteZahl); this->panel3->Controls->Add(this->txtErsteZahl); this->panel3->Controls->Add(this->richTextBox1); this->panel3->Controls->Add(this->progressBar1); this->panel3->Controls->Add(this->pictureBox1); this->panel3->Dock = System::Windows::Forms::DockStyle::Fill; this->panel3->Location = System::Drawing::Point(431, 291); this->panel3->Name = L"panel3"; this->panel3->Size = System::Drawing::Size(422, 282); this->panel3->TabIndex = 4; // // btnDivide // this->btnDivide->Location = System::Drawing::Point(107, 196); this->btnDivide->Name = L"btnDivide"; this->btnDivide->Size = System::Drawing::Size(30, 23); this->btnDivide->TabIndex = 11; this->btnDivide->Text = L"/"; this->btnDivide->UseVisualStyleBackColor = true; this->btnDivide->Click += gcnew System::EventHandler(this, &MainForm::btnDivide_Click); // // btnAddDoubles // this->btnAddDoubles->Location = System::Drawing::Point(240, 167); this->btnAddDoubles->Name = L"btnAddDoubles"; this->btnAddDoubles->Size = System::Drawing::Size(30, 23); this->btnAddDoubles->TabIndex = 10; this->btnAddDoubles->Text = L"="; this->btnAddDoubles->UseVisualStyleBackColor = true; this->btnAddDoubles->Click += gcnew System::EventHandler(this, &MainForm::btnAddDoubles_Click); // // label1 // this->label1->AutoSize = true; this->label1->Location = System::Drawing::Point(124, 173); this->label1->Name = L"label1"; this->label1->Size = System::Drawing::Size(13, 13); this->label1->TabIndex = 5; this->label1->Text = L"+"; // // txtZweiteZahl // this->txtZweiteZahl->Location = System::Drawing::Point(138, 170); this->txtZweiteZahl->Name = L"txtZweiteZahl"; this->txtZweiteZahl->Size = System::Drawing::Size(100, 20); this->txtZweiteZahl->TabIndex = 4; // // txtErsteZahl // this->txtErsteZahl->Location = System::Drawing::Point(18, 170); this->txtErsteZahl->Name = L"txtErsteZahl"; this->txtErsteZahl->Size = System::Drawing::Size(100, 20); this->txtErsteZahl->TabIndex = 3; // // richTextBox1 // this->richTextBox1->Location = System::Drawing::Point(93, 29); this->richTextBox1->Name = L"richTextBox1"; this->richTextBox1->Size = System::Drawing::Size(177, 88); this->richTextBox1->TabIndex = 2; this->richTextBox1->Text = L""; // // progressBar1 // this->progressBar1->Location = System::Drawing::Point(93, 3); this->progressBar1->Name = L"progressBar1"; this->progressBar1->Size = System::Drawing::Size(177, 14); this->progressBar1->Style = System::Windows::Forms::ProgressBarStyle::Continuous; this->progressBar1->TabIndex = 1; this->progressBar1->Value = 40; // // pictureBox1 // this->pictureBox1->Image = (cli::safe_cast<System::Drawing::Image^>(resources->GetObject(L"pictureBox1.Image"))); this->pictureBox1->Location = System::Drawing::Point(3, 3); this->pictureBox1->Name = L"pictureBox1"; this->pictureBox1->Size = System::Drawing::Size(84, 82); this->pictureBox1->SizeMode = System::Windows::Forms::PictureBoxSizeMode::StretchImage; this->pictureBox1->TabIndex = 0; this->pictureBox1->TabStop = false; // // tabControl1 // this->tabControl1->Controls->Add(this->tabPage1); this->tabControl1->Controls->Add(this->tabPage2); this->tabControl1->Controls->Add(this->tabPage3); this->tabControl1->Controls->Add(this->tabPage4); this->tabControl1->Controls->Add(this->tabPage5); this->tabControl1->Controls->Add(this->tabPage6); this->tabControl1->Controls->Add(this->tabPage7); this->tabControl1->Dock = System::Windows::Forms::DockStyle::Fill; this->tabControl1->Location = System::Drawing::Point(0, 24); this->tabControl1->Name = L"tabControl1"; this->tabControl1->SelectedIndex = 0; this->tabControl1->Size = System::Drawing::Size(870, 608); this->tabControl1->TabIndex = 4; // // tabPage1 // this->tabPage1->Controls->Add(this->tableLayoutPanel1); this->tabPage1->Location = System::Drawing::Point(4, 22); this->tabPage1->Name = L"tabPage1"; this->tabPage1->Padding = System::Windows::Forms::Padding(3); this->tabPage1->Size = System::Drawing::Size(862, 582); this->tabPage1->TabIndex = 0; this->tabPage1->Text = L"Basics"; this->tabPage1->UseVisualStyleBackColor = true; // // tabPage2 // this->tabPage2->Controls->Add(this->tableLayoutPanel2); this->tabPage2->Location = System::Drawing::Point(4, 22); this->tabPage2->Name = L"tabPage2"; this->tabPage2->Padding = System::Windows::Forms::Padding(3); this->tabPage2->Size = System::Drawing::Size(862, 582); this->tabPage2->TabIndex = 1; this->tabPage2->Text = L"Other"; this->tabPage2->UseVisualStyleBackColor = true; // // tableLayoutPanel2 // this->tableLayoutPanel2->ColumnCount = 2; this->tableLayoutPanel2->ColumnStyles->Add((gcnew System::Windows::Forms::ColumnStyle(System::Windows::Forms::SizeType::Percent, 50))); this->tableLayoutPanel2->ColumnStyles->Add((gcnew System::Windows::Forms::ColumnStyle(System::Windows::Forms::SizeType::Percent, 50))); this->tableLayoutPanel2->Controls->Add(this->panel4, 0, 0); this->tableLayoutPanel2->Controls->Add(this->txtCollections, 1, 0); this->tableLayoutPanel2->Dock = System::Windows::Forms::DockStyle::Fill; this->tableLayoutPanel2->Location = System::Drawing::Point(3, 3); this->tableLayoutPanel2->Name = L"tableLayoutPanel2"; this->tableLayoutPanel2->RowCount = 1; this->tableLayoutPanel2->RowStyles->Add((gcnew System::Windows::Forms::RowStyle(System::Windows::Forms::SizeType::Percent, 50))); this->tableLayoutPanel2->Size = System::Drawing::Size(856, 576); this->tableLayoutPanel2->TabIndex = 0; // // panel4 // this->panel4->Controls->Add(this->btnBenchmark); this->panel4->Controls->Add(this->btnArray); this->panel4->Controls->Add(this->btnList); this->panel4->Controls->Add(this->btnHashtable); this->panel4->Controls->Add(this->btnSortedList); this->panel4->Controls->Add(this->btnStack); this->panel4->Controls->Add(this->btnQueue); this->panel4->Controls->Add(this->btnArrayList); this->panel4->Dock = System::Windows::Forms::DockStyle::Fill; this->panel4->Location = System::Drawing::Point(3, 3); this->panel4->Name = L"panel4"; this->panel4->Size = System::Drawing::Size(422, 570); this->panel4->TabIndex = 0; // // btnBenchmark // this->btnBenchmark->Location = System::Drawing::Point(4, 207); this->btnBenchmark->Name = L"btnBenchmark"; this->btnBenchmark->Size = System::Drawing::Size(121, 23); this->btnBenchmark->TabIndex = 8; this->btnBenchmark->Text = L"Benchmark"; this->btnBenchmark->UseVisualStyleBackColor = true; this->btnBenchmark->Click += gcnew System::EventHandler(this, &MainForm::btnBenchmark_Click); // // btnArray // this->btnArray->Location = System::Drawing::Point(4, 178); this->btnArray->Name = L"btnArray"; this->btnArray->Size = System::Drawing::Size(121, 23); this->btnArray->TabIndex = 7; this->btnArray->Text = L"array"; this->btnArray->UseVisualStyleBackColor = true; this->btnArray->Click += gcnew System::EventHandler(this, &MainForm::btnArray_Click); // // btnList // this->btnList->Location = System::Drawing::Point(4, 149); this->btnList->Name = L"btnList"; this->btnList->Size = System::Drawing::Size(121, 23); this->btnList->TabIndex = 6; this->btnList->Text = L"List"; this->btnList->UseVisualStyleBackColor = true; this->btnList->Click += gcnew System::EventHandler(this, &MainForm::btnList_Click); // // btnHashtable // this->btnHashtable->Location = System::Drawing::Point(4, 120); this->btnHashtable->Name = L"btnHashtable"; this->btnHashtable->Size = System::Drawing::Size(121, 23); this->btnHashtable->TabIndex = 4; this->btnHashtable->Text = L"HashTable"; this->btnHashtable->UseVisualStyleBackColor = true; this->btnHashtable->Click += gcnew System::EventHandler(this, &MainForm::btnHashtable_Click); // // btnSortedList // this->btnSortedList->Location = System::Drawing::Point(4, 91); this->btnSortedList->Name = L"btnSortedList"; this->btnSortedList->Size = System::Drawing::Size(121, 23); this->btnSortedList->TabIndex = 3; this->btnSortedList->Text = L"SortedList"; this->btnSortedList->UseVisualStyleBackColor = true; this->btnSortedList->Click += gcnew System::EventHandler(this, &MainForm::btnSortedList_Click); // // btnStack // this->btnStack->Location = System::Drawing::Point(4, 62); this->btnStack->Name = L"btnStack"; this->btnStack->Size = System::Drawing::Size(121, 23); this->btnStack->TabIndex = 2; this->btnStack->Text = L"Stack"; this->btnStack->UseVisualStyleBackColor = true; this->btnStack->Click += gcnew System::EventHandler(this, &MainForm::btnStack_Click); // // btnQueue // this->btnQueue->Location = System::Drawing::Point(4, 33); this->btnQueue->Name = L"btnQueue"; this->btnQueue->Size = System::Drawing::Size(121, 23); this->btnQueue->TabIndex = 1; this->btnQueue->Text = L"Queue"; this->btnQueue->UseVisualStyleBackColor = true; this->btnQueue->Click += gcnew System::EventHandler(this, &MainForm::btnQueue_Click); // // btnArrayList // this->btnArrayList->Location = System::Drawing::Point(4, 4); this->btnArrayList->Name = L"btnArrayList"; this->btnArrayList->Size = System::Drawing::Size(121, 23); this->btnArrayList->TabIndex = 0; this->btnArrayList->Text = L"ArrayList"; this->btnArrayList->UseVisualStyleBackColor = true; this->btnArrayList->Click += gcnew System::EventHandler(this, &MainForm::btnArrayList_Click); // // txtCollections // this->txtCollections->Dock = System::Windows::Forms::DockStyle::Fill; this->txtCollections->Location = System::Drawing::Point(431, 3); this->txtCollections->Multiline = true; this->txtCollections->Name = L"txtCollections"; this->txtCollections->Size = System::Drawing::Size(422, 570); this->txtCollections->TabIndex = 1; // // tabPage3 // this->tabPage3->Controls->Add(this->txtAnswers); this->tabPage3->Controls->Add(this->txtQuestions); this->tabPage3->Controls->Add(this->btnNextStep); this->tabPage3->Location = System::Drawing::Point(4, 22); this->tabPage3->Name = L"tabPage3"; this->tabPage3->Padding = System::Windows::Forms::Padding(3); this->tabPage3->Size = System::Drawing::Size(862, 582); this->tabPage3->TabIndex = 2; this->tabPage3->Text = L"Quiz"; this->tabPage3->UseVisualStyleBackColor = true; // // txtAnswers // this->txtAnswers->Location = System::Drawing::Point(288, 231); this->txtAnswers->Multiline = true; this->txtAnswers->Name = L"txtAnswers"; this->txtAnswers->Size = System::Drawing::Size(268, 203); this->txtAnswers->TabIndex = 2; // // txtQuestions // this->txtQuestions->Location = System::Drawing::Point(288, 4); this->txtQuestions->Multiline = true; this->txtQuestions->Name = L"txtQuestions"; this->txtQuestions->Size = System::Drawing::Size(268, 203); this->txtQuestions->TabIndex = 1; // // btnNextStep // this->btnNextStep->Location = System::Drawing::Point(7, 7); this->btnNextStep->Name = L"btnNextStep"; this->btnNextStep->Size = System::Drawing::Size(75, 23); this->btnNextStep->TabIndex = 0; this->btnNextStep->Text = L"Next"; this->btnNextStep->UseVisualStyleBackColor = true; this->btnNextStep->Click += gcnew System::EventHandler(this, &MainForm::btnNextStep_Click); // // tabPage4 // this->tabPage4->Controls->Add(this->tableLayoutPanel3); this->tabPage4->Location = System::Drawing::Point(4, 22); this->tabPage4->Name = L"tabPage4"; this->tabPage4->Padding = System::Windows::Forms::Padding(3); this->tabPage4->Size = System::Drawing::Size(862, 582); this->tabPage4->TabIndex = 3; this->tabPage4->Text = L"Graphics"; this->tabPage4->UseVisualStyleBackColor = true; // // tableLayoutPanel3 // this->tableLayoutPanel3->ColumnCount = 2; this->tableLayoutPanel3->ColumnStyles->Add((gcnew System::Windows::Forms::ColumnStyle(System::Windows::Forms::SizeType::Percent, 50))); this->tableLayoutPanel3->ColumnStyles->Add((gcnew System::Windows::Forms::ColumnStyle(System::Windows::Forms::SizeType::Percent, 50))); this->tableLayoutPanel3->Controls->Add(this->pnlDrawing, 1, 0); this->tableLayoutPanel3->Controls->Add(this->pnlGraphics, 0, 0); this->tableLayoutPanel3->Dock = System::Windows::Forms::DockStyle::Fill; this->tableLayoutPanel3->Location = System::Drawing::Point(3, 3); this->tableLayoutPanel3->Name = L"tableLayoutPanel3"; this->tableLayoutPanel3->RowCount = 1; this->tableLayoutPanel3->RowStyles->Add((gcnew System::Windows::Forms::RowStyle(System::Windows::Forms::SizeType::Percent, 50))); this->tableLayoutPanel3->Size = System::Drawing::Size(856, 576); this->tableLayoutPanel3->TabIndex = 0; // // pnlDrawing // this->pnlDrawing->BackColor = System::Drawing::Color::Gainsboro; this->pnlDrawing->Controls->Add(this->pictureBox2); this->pnlDrawing->Dock = System::Windows::Forms::DockStyle::Fill; this->pnlDrawing->Location = System::Drawing::Point(431, 3); this->pnlDrawing->Name = L"pnlDrawing"; this->pnlDrawing->Size = System::Drawing::Size(422, 570); this->pnlDrawing->TabIndex = 0; this->pnlDrawing->Click += gcnew System::EventHandler(this, &MainForm::pnlDrawing_Click); // // pictureBox2 // this->pictureBox2->Dock = System::Windows::Forms::DockStyle::Fill; this->pictureBox2->Image = (cli::safe_cast<System::Drawing::Image^>(resources->GetObject(L"pictureBox2.Image"))); this->pictureBox2->Location = System::Drawing::Point(0, 0); this->pictureBox2->Name = L"pictureBox2"; this->pictureBox2->Size = System::Drawing::Size(422, 570); this->pictureBox2->TabIndex = 0; this->pictureBox2->TabStop = false; this->pictureBox2->Click += gcnew System::EventHandler(this, &MainForm::pnlDrawing_Click); this->pictureBox2->Paint += gcnew System::Windows::Forms::PaintEventHandler(this, &MainForm::pnlDrawing_Paint); // // pnlGraphics // this->pnlGraphics->Controls->Add(this->btnDrawHouse); this->pnlGraphics->Controls->Add(this->btnDrawImage); this->pnlGraphics->Controls->Add(this->btnTranslatePoints); this->pnlGraphics->Controls->Add(this->btnDrawLine); this->pnlGraphics->Dock = System::Windows::Forms::DockStyle::Fill; this->pnlGraphics->Location = System::Drawing::Point(3, 3); this->pnlGraphics->Name = L"pnlGraphics"; this->pnlGraphics->Size = System::Drawing::Size(422, 570); this->pnlGraphics->TabIndex = 1; // // btnDrawHouse // this->btnDrawHouse->Location = System::Drawing::Point(3, 90); this->btnDrawHouse->Name = L"btnDrawHouse"; this->btnDrawHouse->Size = System::Drawing::Size(75, 23); this->btnDrawHouse->TabIndex = 3; this->btnDrawHouse->Text = L"Draw House"; this->btnDrawHouse->UseVisualStyleBackColor = true; this->btnDrawHouse->Click += gcnew System::EventHandler(this, &MainForm::btnDrawHouse_Click); // // btnDrawImage // this->btnDrawImage->Location = System::Drawing::Point(3, 61); this->btnDrawImage->Name = L"btnDrawImage"; this->btnDrawImage->Size = System::Drawing::Size(75, 23); this->btnDrawImage->TabIndex = 2; this->btnDrawImage->Text = L"Draw Image"; this->btnDrawImage->UseVisualStyleBackColor = true; this->btnDrawImage->Click += gcnew System::EventHandler(this, &MainForm::btnDrawImage_Click); // // btnTranslatePoints // this->btnTranslatePoints->Location = System::Drawing::Point(3, 32); this->btnTranslatePoints->Name = L"btnTranslatePoints"; this->btnTranslatePoints->Size = System::Drawing::Size(75, 23); this->btnTranslatePoints->TabIndex = 1; this->btnTranslatePoints->Text = L"Zoom"; this->btnTranslatePoints->UseVisualStyleBackColor = true; this->btnTranslatePoints->Click += gcnew System::EventHandler(this, &MainForm::btnTranslatePoints_Click); // // btnDrawLine // this->btnDrawLine->Location = System::Drawing::Point(3, 3); this->btnDrawLine->Name = L"btnDrawLine"; this->btnDrawLine->Size = System::Drawing::Size(75, 23); this->btnDrawLine->TabIndex = 0; this->btnDrawLine->Text = L"Draw Line"; this->btnDrawLine->UseVisualStyleBackColor = true; this->btnDrawLine->Click += gcnew System::EventHandler(this, &MainForm::btnDrawLine_Click); // // tabPage5 // this->tabPage5->Controls->Add(this->tableLayoutPanel4); this->tabPage5->Location = System::Drawing::Point(4, 22); this->tabPage5->Name = L"tabPage5"; this->tabPage5->Padding = System::Windows::Forms::Padding(3); this->tabPage5->Size = System::Drawing::Size(862, 582); this->tabPage5->TabIndex = 4; this->tabPage5->Text = L"Own Components"; this->tabPage5->UseVisualStyleBackColor = true; // // tableLayoutPanel4 // this->tableLayoutPanel4->ColumnCount = 2; this->tableLayoutPanel4->ColumnStyles->Add((gcnew System::Windows::Forms::ColumnStyle(System::Windows::Forms::SizeType::Percent, 50))); this->tableLayoutPanel4->ColumnStyles->Add((gcnew System::Windows::Forms::ColumnStyle(System::Windows::Forms::SizeType::Percent, 50))); this->tableLayoutPanel4->Controls->Add(this->textBox2, 1, 0); this->tableLayoutPanel4->Controls->Add(this->panel5, 0, 0); this->tableLayoutPanel4->Controls->Add(this->panel6, 0, 1); this->tableLayoutPanel4->Dock = System::Windows::Forms::DockStyle::Fill; this->tableLayoutPanel4->Location = System::Drawing::Point(3, 3); this->tableLayoutPanel4->Name = L"tableLayoutPanel4"; this->tableLayoutPanel4->RowCount = 2; this->tableLayoutPanel4->RowStyles->Add((gcnew System::Windows::Forms::RowStyle(System::Windows::Forms::SizeType::Percent, 22.91667F))); this->tableLayoutPanel4->RowStyles->Add((gcnew System::Windows::Forms::RowStyle(System::Windows::Forms::SizeType::Percent, 77.08334F))); this->tableLayoutPanel4->Size = System::Drawing::Size(856, 576); this->tableLayoutPanel4->TabIndex = 0; // // textBox2 // this->textBox2->Dock = System::Windows::Forms::DockStyle::Fill; this->textBox2->Location = System::Drawing::Point(431, 3); this->textBox2->Multiline = true; this->textBox2->Name = L"textBox2"; this->textBox2->Size = System::Drawing::Size(422, 125); this->textBox2->TabIndex = 0; // // panel5 // this->panel5->Dock = System::Windows::Forms::DockStyle::Fill; this->panel5->Location = System::Drawing::Point(3, 3); this->panel5->Name = L"panel5"; this->panel5->Size = System::Drawing::Size(422, 125); this->panel5->TabIndex = 1; // // panel6 // this->panel6->Dock = System::Windows::Forms::DockStyle::Fill; this->panel6->Location = System::Drawing::Point(3, 134); this->panel6->Name = L"panel6"; this->panel6->Size = System::Drawing::Size(422, 439); this->panel6->TabIndex = 2; // // tabPage6 // this->tabPage6->Controls->Add(this->tableLayoutPanel5); this->tabPage6->Location = System::Drawing::Point(4, 22); this->tabPage6->Name = L"tabPage6"; this->tabPage6->Padding = System::Windows::Forms::Padding(3); this->tabPage6->Size = System::Drawing::Size(862, 582); this->tabPage6->TabIndex = 5; this->tabPage6->Text = L"Trees"; this->tabPage6->UseVisualStyleBackColor = true; // // tableLayoutPanel5 // this->tableLayoutPanel5->ColumnCount = 2; this->tableLayoutPanel5->ColumnStyles->Add((gcnew System::Windows::Forms::ColumnStyle(System::Windows::Forms::SizeType::Percent, 50))); this->tableLayoutPanel5->ColumnStyles->Add((gcnew System::Windows::Forms::ColumnStyle(System::Windows::Forms::SizeType::Percent, 50))); this->tableLayoutPanel5->Controls->Add(this->panel8, 0, 1); this->tableLayoutPanel5->Controls->Add(this->txtTreeView, 1, 0); this->tableLayoutPanel5->Controls->Add(this->treeView1, 0, 0); this->tableLayoutPanel5->Controls->Add(this->panel7, 1, 1); this->tableLayoutPanel5->Dock = System::Windows::Forms::DockStyle::Fill; this->tableLayoutPanel5->Location = System::Drawing::Point(3, 3); this->tableLayoutPanel5->Name = L"tableLayoutPanel5"; this->tableLayoutPanel5->RowCount = 2; this->tableLayoutPanel5->RowStyles->Add((gcnew System::Windows::Forms::RowStyle(System::Windows::Forms::SizeType::Percent, 55.20833F))); this->tableLayoutPanel5->RowStyles->Add((gcnew System::Windows::Forms::RowStyle(System::Windows::Forms::SizeType::Percent, 44.79167F))); this->tableLayoutPanel5->Size = System::Drawing::Size(856, 576); this->tableLayoutPanel5->TabIndex = 1; // // panel8 // this->panel8->Controls->Add(this->btnChangeRegexInRegexTextBox); this->panel8->Controls->Add(this->txtRegexExpr); this->panel8->Controls->Add(this->txtRegex); this->panel8->Controls->Add(this->btnRegex); this->panel8->Dock = System::Windows::Forms::DockStyle::Fill; this->panel8->Location = System::Drawing::Point(3, 320); this->panel8->Name = L"panel8"; this->panel8->Size = System::Drawing::Size(422, 253); this->panel8->TabIndex = 2; // // btnChangeRegexInRegexTextBox // this->btnChangeRegexInRegexTextBox->Location = System::Drawing::Point(3, 72); this->btnChangeRegexInRegexTextBox->Name = L"btnChangeRegexInRegexTextBox"; this->btnChangeRegexInRegexTextBox->Size = System::Drawing::Size(103, 23); this->btnChangeRegexInRegexTextBox->TabIndex = 4; this->btnChangeRegexInRegexTextBox->Text = L"Change Regex"; this->btnChangeRegexInRegexTextBox->UseVisualStyleBackColor = true; this->btnChangeRegexInRegexTextBox->Click += gcnew System::EventHandler(this, &MainForm::btnChangeRegexInRegexTextBox_Click); // // txtRegexExpr // this->txtRegexExpr->Location = System::Drawing::Point(3, 6); this->txtRegexExpr->Name = L"txtRegexExpr"; this->txtRegexExpr->Size = System::Drawing::Size(416, 20); this->txtRegexExpr->TabIndex = 6; this->txtRegexExpr->Text = L"^([\\+][0-9]{1,3}[ \\.\\-])\?([\\(]{1}[0-9]{1,6}[\\)])\?([0-9 \\.\\-\\/]{3,20})((x|ext|exte" L"nsion)[ ]\?[0-9]{1,4})\?$"; // // txtRegex // this->txtRegex->Location = System::Drawing::Point(112, 43); this->txtRegex->Name = L"txtRegex"; this->txtRegex->Size = System::Drawing::Size(307, 20); this->txtRegex->TabIndex = 5; this->txtRegex->Text = L"+49 (0) 123 456789"; // // btnRegex // this->btnRegex->Location = System::Drawing::Point(3, 43); this->btnRegex->Name = L"btnRegex"; this->btnRegex->Size = System::Drawing::Size(103, 23); this->btnRegex->TabIndex = 4; this->btnRegex->Text = L"Regex"; this->btnRegex->UseVisualStyleBackColor = true; this->btnRegex->Click += gcnew System::EventHandler(this, &MainForm::btnRegex_Click); // // txtTreeView // this->txtTreeView->Dock = System::Windows::Forms::DockStyle::Fill; this->txtTreeView->Location = System::Drawing::Point(431, 3); this->txtTreeView->Multiline = true; this->txtTreeView->Name = L"txtTreeView"; this->txtTreeView->Size = System::Drawing::Size(422, 311); this->txtTreeView->TabIndex = 0; // // treeView1 // this->treeView1->Dock = System::Windows::Forms::DockStyle::Fill; this->treeView1->Location = System::Drawing::Point(3, 3); this->treeView1->Name = L"treeView1"; treeNode1->Name = L"Knoten7"; treeNode1->Text = L"Knoten7"; treeNode2->Name = L"Knoten8"; treeNode2->Text = L"Knoten8"; treeNode3->Name = L"Knoten9"; treeNode3->Text = L"Knoten9"; treeNode4->Name = L"Knoten15"; treeNode4->Text = L"Knoten15"; treeNode5->Name = L"Knoten16"; treeNode5->Text = L"Knoten16"; treeNode6->Name = L"Knoten21"; treeNode6->Text = L"Knoten21"; treeNode7->Name = L"Knoten22"; treeNode7->Text = L"Knoten22"; treeNode8->Name = L"Knoten26"; treeNode8->Text = L"Knoten26"; treeNode9->Name = L"Knoten27"; treeNode9->Text = L"Knoten27"; treeNode10->Name = L"Knoten28"; treeNode10->Text = L"Knoten28"; treeNode11->Name = L"Knoten29"; treeNode11->Text = L"Knoten29"; treeNode12->Name = L"Knoten30"; treeNode12->Text = L"Knoten30"; treeNode13->Name = L"Knoten31"; treeNode13->Text = L"Knoten31"; treeNode14->Name = L"Knoten32"; treeNode14->Text = L"Knoten32"; treeNode15->Name = L"Knoten33"; treeNode15->Text = L"Knoten33"; treeNode16->Name = L"Knoten34"; treeNode16->Text = L"Knoten34"; treeNode17->Name = L"Knoten23"; treeNode17->Text = L"Knoten23"; treeNode18->Name = L"Knoten24"; treeNode18->Text = L"Knoten24"; treeNode19->Name = L"Knoten25"; treeNode19->Text = L"Knoten25"; treeNode20->Name = L"Knoten17"; treeNode20->Text = L"Knoten17"; treeNode21->Name = L"Knoten18"; treeNode21->Text = L"Knoten18"; treeNode22->Name = L"Knoten19"; treeNode22->Text = L"Knoten19"; treeNode23->Name = L"Knoten20"; treeNode23->Text = L"Knoten20"; treeNode24->Name = L"Knoten10"; treeNode24->Text = L"Knoten10"; treeNode25->Name = L"Knoten11"; treeNode25->Text = L"Knoten11"; treeNode26->Name = L"Knoten12"; treeNode26->Text = L"Knoten12"; treeNode27->Name = L"Knoten13"; treeNode27->Text = L"Knoten13"; treeNode28->Name = L"Knoten14"; treeNode28->Text = L"Knoten14"; treeNode29->Name = L"Knoten0"; treeNode29->Text = L"Knoten0"; this->treeView1->Nodes->AddRange(gcnew cli::array< System::Windows::Forms::TreeNode^ >(1) { treeNode29 }); this->treeView1->Size = System::Drawing::Size(422, 311); this->treeView1->TabIndex = 3; this->treeView1->AfterSelect += gcnew System::Windows::Forms::TreeViewEventHandler(this, &MainForm::treeView1_AfterSelect); // // panel7 // this->panel7->Controls->Add(this->btnDriveInfo); this->panel7->Controls->Add(this->btnWalkTreeViewRecursive); this->panel7->Controls->Add(this->btnRecursion); this->panel7->Controls->Add(this->btnReadDirectories); this->panel7->Controls->Add(this->btnRemoveTreeNOde); this->panel7->Controls->Add(this->btnAddTreeNodeToTreeView); this->panel7->Dock = System::Windows::Forms::DockStyle::Fill; this->panel7->Location = System::Drawing::Point(431, 320); this->panel7->Name = L"panel7"; this->panel7->Size = System::Drawing::Size(422, 253); this->panel7->TabIndex = 4; // // btnDriveInfo // this->btnDriveInfo->Location = System::Drawing::Point(3, 119); this->btnDriveInfo->Name = L"btnDriveInfo"; this->btnDriveInfo->Size = System::Drawing::Size(103, 23); this->btnDriveInfo->TabIndex = 5; this->btnDriveInfo->Text = L"DriveInfo"; this->btnDriveInfo->UseVisualStyleBackColor = true; this->btnDriveInfo->Click += gcnew System::EventHandler(this, &MainForm::btnDriveInfo_Click); // // btnWalkTreeViewRecursive // this->btnWalkTreeViewRecursive->Location = System::Drawing::Point(3, 72); this->btnWalkTreeViewRecursive->Name = L"btnWalkTreeViewRecursive"; this->btnWalkTreeViewRecursive->Size = System::Drawing::Size(103, 23); this->btnWalkTreeViewRecursive->TabIndex = 4; this->btnWalkTreeViewRecursive->Text = L"Tree Recursive"; this->btnWalkTreeViewRecursive->UseVisualStyleBackColor = true; this->btnWalkTreeViewRecursive->Click += gcnew System::EventHandler(this, &MainForm::btnWalkTreeViewRecursive_Click); // // btnRecursion // this->btnRecursion->Location = System::Drawing::Point(220, 3); this->btnRecursion->Name = L"btnRecursion"; this->btnRecursion->Size = System::Drawing::Size(88, 23); this->btnRecursion->TabIndex = 3; this->btnRecursion->Text = L"recursion"; this->btnRecursion->UseVisualStyleBackColor = true; this->btnRecursion->Click += gcnew System::EventHandler(this, &MainForm::btnRecursion_Click); // // btnReadDirectories // this->btnReadDirectories->Location = System::Drawing::Point(97, 32); this->btnReadDirectories->Name = L"btnReadDirectories"; this->btnReadDirectories->Size = System::Drawing::Size(103, 23); this->btnReadDirectories->TabIndex = 2; this->btnReadDirectories->Text = L"Read Directrories"; this->btnReadDirectories->UseVisualStyleBackColor = true; this->btnReadDirectories->Click += gcnew System::EventHandler(this, &MainForm::btnReadDirectories_Click); // // btnRemoveTreeNOde // this->btnRemoveTreeNOde->Location = System::Drawing::Point(97, 3); this->btnRemoveTreeNOde->Name = L"btnRemoveTreeNOde"; this->btnRemoveTreeNOde->Size = System::Drawing::Size(117, 23); this->btnRemoveTreeNOde->TabIndex = 1; this->btnRemoveTreeNOde->Text = L"Remove TreeNode"; this->btnRemoveTreeNOde->UseVisualStyleBackColor = true; this->btnRemoveTreeNOde->Click += gcnew System::EventHandler(this, &MainForm::btnRemoveTreeNOde_Click); // // btnAddTreeNodeToTreeView // this->btnAddTreeNodeToTreeView->Location = System::Drawing::Point(3, 3); this->btnAddTreeNodeToTreeView->Name = L"btnAddTreeNodeToTreeView"; this->btnAddTreeNodeToTreeView->Size = System::Drawing::Size(88, 23); this->btnAddTreeNodeToTreeView->TabIndex = 0; this->btnAddTreeNodeToTreeView->Text = L"Add TreeNode"; this->btnAddTreeNodeToTreeView->UseVisualStyleBackColor = true; this->btnAddTreeNodeToTreeView->Click += gcnew System::EventHandler(this, &MainForm::btnAddTreeNodeToTreeView_Click); // // timer1 // this->timer1->Interval = 1000; this->timer1->Tick += gcnew System::EventHandler(this, &MainForm::timer1_Tick); // // menuStrip1 // this->menuStrip1->Items->AddRange(gcnew cli::array< System::Windows::Forms::ToolStripItem^ >(3) { this->toolStripMenuItem1, this->toolStripMenuItem3, this->toolStripMenuItem4 }); this->menuStrip1->Location = System::Drawing::Point(0, 0); this->menuStrip1->Name = L"menuStrip1"; this->menuStrip1->Size = System::Drawing::Size(870, 24); this->menuStrip1->TabIndex = 5; this->menuStrip1->Text = L"menuStrip1"; // // toolStripMenuItem1 // this->toolStripMenuItem1->DropDownItems->AddRange(gcnew cli::array< System::Windows::Forms::ToolStripItem^ >(5) { this->toolStripMenuItem2, this->toolStripSeparator1, this->mnuSaveFileDialog, this->mnuRichtextBox, this->mnuFolderBrowser }); this->toolStripMenuItem1->Name = L"toolStripMenuItem1"; this->toolStripMenuItem1->Size = System::Drawing::Size(46, 20); this->toolStripMenuItem1->Text = L"Datei"; // // toolStripMenuItem2 // this->toolStripMenuItem2->Name = L"toolStripMenuItem2"; this->toolStripMenuItem2->Size = System::Drawing::Size(190, 22); this->toolStripMenuItem2->Text = L"Öffnen"; this->toolStripMenuItem2->Click += gcnew System::EventHandler(this, &MainForm::toolStripMenuItem2_Click); // // toolStripSeparator1 // this->toolStripSeparator1->Name = L"toolStripSeparator1"; this->toolStripSeparator1->Size = System::Drawing::Size(187, 6); // // mnuSaveFileDialog // this->mnuSaveFileDialog->Name = L"mnuSaveFileDialog"; this->mnuSaveFileDialog->Size = System::Drawing::Size(190, 22); this->mnuSaveFileDialog->Text = L"Speichern"; this->mnuSaveFileDialog->Click += gcnew System::EventHandler(this, &MainForm::mnuSaveFileDialog_Click); // // mnuRichtextBox // this->mnuRichtextBox->Name = L"mnuRichtextBox"; this->mnuRichtextBox->Size = System::Drawing::Size(190, 22); this->mnuRichtextBox->Text = L"Richtextbox Speichern"; this->mnuRichtextBox->Click += gcnew System::EventHandler(this, &MainForm::mnuRichtextBox_Click); // // mnuFolderBrowser // this->mnuFolderBrowser->Name = L"mnuFolderBrowser"; this->mnuFolderBrowser->Size = System::Drawing::Size(190, 22); this->mnuFolderBrowser->Text = L"FolderBrowserDialog"; this->mnuFolderBrowser->Click += gcnew System::EventHandler(this, &MainForm::mnuFolderBrowser_Click); // // toolStripMenuItem3 // this->toolStripMenuItem3->DropDownItems->AddRange(gcnew cli::array< System::Windows::Forms::ToolStripItem^ >(2) { this->mnuFarben, this->mnuSchriftart }); this->toolStripMenuItem3->Name = L"toolStripMenuItem3"; this->toolStripMenuItem3->Size = System::Drawing::Size(90, 20); this->toolStripMenuItem3->Text = L"Einstellungen"; // // mnuFarben // this->mnuFarben->Name = L"mnuFarben"; this->mnuFarben->Size = System::Drawing::Size(122, 22); this->mnuFarben->Text = L"Farben"; this->mnuFarben->Click += gcnew System::EventHandler(this, &MainForm::mnuFarben_Click); // // mnuSchriftart // this->mnuSchriftart->Name = L"mnuSchriftart"; this->mnuSchriftart->Size = System::Drawing::Size(122, 22); this->mnuSchriftart->Text = L"Schriftart"; this->mnuSchriftart->Click += gcnew System::EventHandler(this, &MainForm::mnuSchriftart_Click); // // toolStripMenuItem4 // this->toolStripMenuItem4->DropDownItems->AddRange(gcnew cli::array< System::Windows::Forms::ToolStripItem^ >(4) { this->mnuButtonsHerstellen, this->mnuListControls, this->mnuTextBoxenHerstellen, this->mnuRefreshTreeView }); this->toolStripMenuItem4->Name = L"toolStripMenuItem4"; this->toolStripMenuItem4->Size = System::Drawing::Size(54, 20); this->toolStripMenuItem4->Text = L"Debug"; // // mnuButtonsHerstellen // this->mnuButtonsHerstellen->Name = L"mnuButtonsHerstellen"; this->mnuButtonsHerstellen->Size = System::Drawing::Size(198, 22); this->mnuButtonsHerstellen->Text = L"Buttons herstellen"; this->mnuButtonsHerstellen->Click += gcnew System::EventHandler(this, &MainForm::mnuButtonsHerstellen_Click); // // mnuListControls // this->mnuListControls->Name = L"mnuListControls"; this->mnuListControls->Size = System::Drawing::Size(198, 22); this->mnuListControls->Text = L"Liste Controls tabPage2"; this->mnuListControls->Click += gcnew System::EventHandler(this, &MainForm::mnuListControls_Click); // // mnuTextBoxenHerstellen // this->mnuTextBoxenHerstellen->Name = L"mnuTextBoxenHerstellen"; this->mnuTextBoxenHerstellen->Size = System::Drawing::Size(198, 22); this->mnuTextBoxenHerstellen->Text = L"TextBoxen herstellen"; this->mnuTextBoxenHerstellen->Click += gcnew System::EventHandler(this, &MainForm::mnuTextBoxenHerstellen_Click); // // openFileDialog1 // this->openFileDialog1->FileName = L"openFileDialog1"; // // fontDialog1 // this->fontDialog1->ShowColor = true; // // tabPage7 // this->tabPage7->Controls->Add(this->tableLayoutPanel6); this->tabPage7->Location = System::Drawing::Point(4, 22); this->tabPage7->Name = L"tabPage7"; this->tabPage7->Padding = System::Windows::Forms::Padding(3); this->tabPage7->Size = System::Drawing::Size(862, 582); this->tabPage7->TabIndex = 6; this->tabPage7->Text = L"Explorer"; this->tabPage7->UseVisualStyleBackColor = true; // // tableLayoutPanel6 // this->tableLayoutPanel6->ColumnCount = 2; this->tableLayoutPanel6->ColumnStyles->Add((gcnew System::Windows::Forms::ColumnStyle(System::Windows::Forms::SizeType::Percent, 49.41589F))); this->tableLayoutPanel6->ColumnStyles->Add((gcnew System::Windows::Forms::ColumnStyle(System::Windows::Forms::SizeType::Percent, 50.58411F))); this->tableLayoutPanel6->Controls->Add(this->trvDirectories, 0, 0); this->tableLayoutPanel6->Controls->Add(this->lsvFiles, 1, 0); this->tableLayoutPanel6->Dock = System::Windows::Forms::DockStyle::Fill; this->tableLayoutPanel6->Location = System::Drawing::Point(3, 3); this->tableLayoutPanel6->Name = L"tableLayoutPanel6"; this->tableLayoutPanel6->RowCount = 1; this->tableLayoutPanel6->RowStyles->Add((gcnew System::Windows::Forms::RowStyle(System::Windows::Forms::SizeType::Percent, 50))); this->tableLayoutPanel6->Size = System::Drawing::Size(856, 576); this->tableLayoutPanel6->TabIndex = 0; // // trvDirectories // this->trvDirectories->Dock = System::Windows::Forms::DockStyle::Fill; this->trvDirectories->Location = System::Drawing::Point(3, 3); this->trvDirectories->Name = L"trvDirectories"; this->trvDirectories->Size = System::Drawing::Size(417, 570); this->trvDirectories->TabIndex = 0; // // lsvFiles // this->lsvFiles->Dock = System::Windows::Forms::DockStyle::Fill; this->lsvFiles->Location = System::Drawing::Point(426, 3); this->lsvFiles->Name = L"lsvFiles"; this->lsvFiles->Size = System::Drawing::Size(427, 570); this->lsvFiles->TabIndex = 1; this->lsvFiles->UseCompatibleStateImageBehavior = false; // // mnuRefreshTreeView // this->mnuRefreshTreeView->Name = L"mnuRefreshTreeView"; this->mnuRefreshTreeView->Size = System::Drawing::Size(198, 22); this->mnuRefreshTreeView->Text = L"Refresh ExplorerTree"; this->mnuRefreshTreeView->Click += gcnew System::EventHandler(this, &MainForm::mnuRefreshTreeView_Click); // // MainForm // this->AutoScaleDimensions = System::Drawing::SizeF(6, 13); this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font; this->ClientSize = System::Drawing::Size(870, 632); this->Controls->Add(this->tabControl1); this->Controls->Add(this->menuStrip1); this->MainMenuStrip = this->menuStrip1; this->Name = L"MainForm"; this->Text = L"MainForm"; this->tableLayoutPanel1->ResumeLayout(false); this->tableLayoutPanel1->PerformLayout(); this->contextMenuStrip1->ResumeLayout(false); this->panel1->ResumeLayout(false); this->panel2->ResumeLayout(false); this->panel2->PerformLayout(); (cli::safe_cast<System::ComponentModel::ISupportInitialize^>(this->trackBar1))->EndInit(); (cli::safe_cast<System::ComponentModel::ISupportInitialize^>(this->numericUpDown1))->EndInit(); this->groupBox1->ResumeLayout(false); this->groupBox1->PerformLayout(); this->panel3->ResumeLayout(false); this->panel3->PerformLayout(); (cli::safe_cast<System::ComponentModel::ISupportInitialize^>(this->pictureBox1))->EndInit(); this->tabControl1->ResumeLayout(false); this->tabPage1->ResumeLayout(false); this->tabPage2->ResumeLayout(false); this->tableLayoutPanel2->ResumeLayout(false); this->tableLayoutPanel2->PerformLayout(); this->panel4->ResumeLayout(false); this->tabPage3->ResumeLayout(false); this->tabPage3->PerformLayout(); this->tabPage4->ResumeLayout(false); this->tableLayoutPanel3->ResumeLayout(false); this->pnlDrawing->ResumeLayout(false); (cli::safe_cast<System::ComponentModel::ISupportInitialize^>(this->pictureBox2))->EndInit(); this->pnlGraphics->ResumeLayout(false); this->tabPage5->ResumeLayout(false); this->tableLayoutPanel4->ResumeLayout(false); this->tableLayoutPanel4->PerformLayout(); this->tabPage6->ResumeLayout(false); this->tableLayoutPanel5->ResumeLayout(false); this->tableLayoutPanel5->PerformLayout(); this->panel8->ResumeLayout(false); this->panel8->PerformLayout(); this->panel7->ResumeLayout(false); this->menuStrip1->ResumeLayout(false); this->menuStrip1->PerformLayout(); this->tabPage7->ResumeLayout(false); this->tableLayoutPanel6->ResumeLayout(false); this->ResumeLayout(false); this->PerformLayout(); } #pragma endregion void initialiseComponents() { this->btnBlinkinButton = gcnew BlinkinButton(250, System::Drawing::Color::Coral, System::Drawing::Color::CornflowerBlue); // // btnBlinkinButton // this->btnBlinkinButton->Location = System::Drawing::Point(3, 3); this->btnBlinkinButton->Name = L"btnBlinkinButton"; this->btnBlinkinButton->Size = System::Drawing::Size(75, 23); this->btnBlinkinButton->TabIndex = 0; this->btnBlinkinButton->Text = L"button1"; this->btnBlinkinButton->UseVisualStyleBackColor = true; this->btnBlinkinButton->Click += gcnew System::EventHandler(this, &GUI::MainForm::BlinkinButtonOnClick); this->btnBlinkinButton->MouseHover += gcnew System::EventHandler(this, &GUI::MainForm::BlinkinButtonOnMouseHover); this->panel5->Controls->Add(this->btnBlinkinButton); this->pnlHouse = (gcnew DrawingPanel); // // pnlHouse // this->pnlHouse->Location = System::Drawing::Point(25, 25); this->pnlHouse->Name = L"pnlHouse"; this->pnlHouse->Size = System::Drawing::Size(300, 300); this->pnlHouse->TabIndex = 0; this->panel6->Controls->Add(this->pnlHouse); this->txtAutoRegexMatcher = (gcnew RegexTextBox); // // txtAutoRegexMatcher // this->txtAutoRegexMatcher->Location = System::Drawing::Point(3, 117); this->txtAutoRegexMatcher->Name = L"txtAutoRegexMatcher"; this->txtAutoRegexMatcher->Size = System::Drawing::Size(307, 20); this->txtAutoRegexMatcher->TabIndex = 7; this->txtAutoRegexMatcher->Text = L"+49 (0) 123 456789"; this->panel8->Controls->Add(this->txtAutoRegexMatcher); } private: System::Void BlinkinButtonOnMouseHover(System::Object^ sender, System::EventArgs^ e) { logger->Debug("I got hovered from the form !!!"); } private: System::Void BlinkinButtonOnClick(System::Object^ sender, System::EventArgs^ e) { this->btnBlinkinButton->changeConfig(125, Color::Yellow, Color::OrangeRed); } private: System::Void cmdChangeFormColor_Click(System::Object^ sender, System::EventArgs^ e) { cmdChangeFormColor->BackColor = System::Drawing::Color(Color::HotPink); this->BackColor = System::Drawing::Color(Color::GreenYellow); } private: System::Void btnChangeTab_Click(System::Object^ sender, System::EventArgs^ e) { textBox1->AppendText(tabControl1->SelectedIndex.ToString()); tabControl1->SelectedIndex = 1; tabControl1->SelectTab(1); textBox1->AppendText(textBox1->GetType()->ToString()); } private: System::Void btnCheckbox_Click(System::Object^ sender, System::EventArgs^ e) { textBox1->AppendText(checkBox1->Checked.ToString()); if (checkBox1->Checked) { System::Windows::Forms::DialogResult dR = MessageBox::Show("Oh nooooo, I'm checked !\r\n", "Please click !", MessageBoxButtons::YesNoCancel, MessageBoxIcon::Warning); if (dR == System::Windows::Forms::DialogResult::Cancel) { System::Diagnostics::Debug::WriteLine("User clicked cancel"); textBox1->AppendText("User cancelled the action !\r\n"); } else if (dR == System::Windows::Forms::DialogResult::Yes) { System::Diagnostics::Debug::WriteLine("User clicked yes"); textBox1->AppendText("You're amazing !!\r\n"); } else if (dR == System::Windows::Forms::DialogResult::No) { System::Diagnostics::Debug::WriteLine("User clicked no"); textBox1->AppendText("Whaaaaat ??!!\r\n"); } } else { MessageBox::Show("Pleaseeeeee check me !\r\n"); } } private: System::Void checkBox1_CheckedChanged(System::Object^ sender, System::EventArgs^ e) { textBox1->AppendText("You changed the checkBox1 to " + checkBox1->Checked.ToString() + "\r\n"); } RadioButton^ gimmeActiveRadioButton() { if (radioButton1->Checked) { return radioButton1; } else if (radioButton2->Checked) { return radioButton2; } else if (radioButton3->Checked) { return radioButton3; } } private: System::Void btnRadioButton_Click(System::Object^ sender, System::EventArgs^ e) { textBox1->AppendText("Radiobutton : " + gimmeActiveRadioButton()->Name); } private: System::Void btnComboboxValue_Click(System::Object^ sender, System::EventArgs^ e) { } private: System::Void cmbBlubb_SelectedIndexChanged(System::Object^ sender, System::EventArgs^ e) { textBox1->AppendText(cmbBlubb->Text); } private: System::Void btnComboAddItem_Click(System::Object^ sender, System::EventArgs^ e) { cmbBlubb->Items->Add("WoW"); } private: System::Void btnComboremoveItem_Click(System::Object^ sender, System::EventArgs^ e) { cmbBlubb->Items->RemoveAt(2); } private: System::Void btnComboInsert_Click(System::Object^ sender, System::EventArgs^ e) { cmbBlubb->Items->Insert(2, "Test"); } private: System::Void listBox1_SelectedIndexChanged(System::Object^ sender, System::EventArgs^ e) { int selectedItemsCount = listBox1->SelectedItems->Count; for (int i = 0;i < selectedItemsCount;i++) { textBox1->AppendText(listBox1->SelectedItems[i]->ToString() + "\r\n"); } } private: System::Void btnNextStep_Click(System::Object^ sender, System::EventArgs^ e) { if (step == 0) { txtQuestions->Clear(); txtQuestions->AppendText("Wie heisst Du ?\r\n"); txtAnswers->Clear(); } else if (step == 1) { txtQuestions->AppendText("Du heisst also " + txtAnswers->Text + " !\r\n"); antwort1 = txtAnswers->Text; txtQuestions->AppendText("Wie alt bist Du ?\r\n"); txtAnswers->Clear(); } else if (step == 2) { txtQuestions->AppendText("Du bist also " + txtAnswers->Text + " alt !\r\n"); antwort2 = txtAnswers->Text; txtQuestions->AppendText("Was ist Deine Lieblingsfarbe ?\r\n"); txtAnswers->Clear(); } else if (step == 3) { txtQuestions->AppendText("Deine Lieblingsfarbe ist also " + txtAnswers->Text + " !\r\n"); antwort3 = txtAnswers->Text; txtQuestions->AppendText("Danke für's Gespräch !\r\n"); txtAnswers->Clear(); } step++; } private: System::Void btnChangeFromAnotherClass_Click(System::Object^ sender, System::EventArgs^ e) { t = gcnew Test(); //t->changeTextBoxText(this); } private: System::Void btnStartProgress_Click(System::Object^ sender, System::EventArgs^ e) { //for(int counter = 0;counter <=100 ;counter++){ // System::Threading::Thread::Sleep(500); // progressBar1->Value = counter; //} progress = 0; timer1->Enabled = true; } private: System::Void timer1_Tick(System::Object^ sender, System::EventArgs^ e) { if (progress <= 100) { progressBar1->Value = progress; progress += 5; } else { timer1->Enabled = false; } } private: System::Void trackBar1_Scroll(System::Object^ sender, System::EventArgs^ e) { textBox1->AppendText(trackBar1->Value + "\r\n"); } private: System::Void toolStripMenuItem2_Click(System::Object^ sender, System::EventArgs^ e) { openFileDialog1->Filter = "Solution Files|*.sln;*.vcxproj|Text Files|*.txt|Image Files(*.BMP;*.JPG;*.GIF)|*.BMP;*.JPG;*.GIF|All files (*.*)|*.*"; openFileDialog1->FilterIndex = 2; openFileDialog1->InitialDirectory = "d:\\"; System::Windows::Forms::DialogResult dialogResult = openFileDialog1->ShowDialog(); if (dialogResult == System::Windows::Forms::DialogResult::OK) { if (openFileDialog1->Multiselect == true) { for each(String^ einFileName in openFileDialog1->FileNames) { textBox1->AppendText(einFileName + "\r\n"); } } else { textBox1->AppendText(openFileDialog1->FileName + "\r\n"); String^ inhaltDerDatei = System::IO::File::ReadAllText(openFileDialog1->FileName); textBox1->AppendText(inhaltDerDatei); } } else { textBox1->AppendText("Datei auswählen !\r\n"); } } private: System::Void mnuFarben_Click(System::Object^ sender, System::EventArgs^ e) { System::Windows::Forms::DialogResult dialogResult = colorDialog1->ShowDialog(); if (dialogResult == System::Windows::Forms::DialogResult::OK) { textBox1->BackColor = colorDialog1->Color; } } private: System::Void mnuSaveFileDialog_Click(System::Object^ sender, System::EventArgs^ e) { saveFileDialog1->Filter = "Solution Files|*.sln;*.vcxproj|Text Files|*.txt|Image Files(*.BMP;*.JPG;*.GIF)|*.BMP;*.JPG;*.GIF|All files (*.*)|*.*"; saveFileDialog1->FilterIndex = 2; saveFileDialog1->InitialDirectory = "d:\\"; System::Windows::Forms::DialogResult dialogResult = saveFileDialog1->ShowDialog(); if (dialogResult == System::Windows::Forms::DialogResult::OK) { System::IO::File::WriteAllText(saveFileDialog1->FileName, textBox1->Text); } } private: System::Void mnuSchriftart_Click(System::Object^ sender, System::EventArgs^ e) { System::Windows::Forms::DialogResult dialogResult = fontDialog1->ShowDialog(); if (dialogResult == System::Windows::Forms::DialogResult::OK) { textBox1->Font = fontDialog1->Font; textBox1->ForeColor = fontDialog1->Color; } } private: System::Void mnuRichtextBox_Click(System::Object^ sender, System::EventArgs^ e) { richTextBox1->SaveFile("d:\\richtexttest.rtf"); } private: System::Void mnuFolderBrowser_Click(System::Object^ sender, System::EventArgs^ e) { folderBrowserDialog1->ShowDialog(); } private: System::Void mnuClearText_Click(System::Object^ sender, System::EventArgs^ e) { textBox1->Clear(); } private: System::Void dateTimePicker1_ValueChanged(System::Object^ sender, System::EventArgs^ e) { DateTime t = dateTimePicker1->Value; DateTime aktuelleZeit = DateTime::Now; textBox1->AppendText(t.ToLongDateString() + "\n"); textBox1->AppendText(aktuelleZeit.ToLongTimeString() + "\n"); TimeSpan dauer(10, 10, 10, 10); DateTime summe = t.Add(dauer); } private: System::Void mnuButtonsHerstellen_Click(System::Object^ sender, System::EventArgs^ e) { for (int counter = 0; counter < 10;counter++) { System::Windows::Forms::Button^ btnDynamicButton = gcnew System::Windows::Forms::Button; btnDynamicButton->Location = System::Drawing::Point(0, 0 + 25 * counter); btnDynamicButton->Name = L"btnDynamicButton" + counter; btnDynamicButton->Size = System::Drawing::Size(109, 23); btnDynamicButton->TabIndex = 8; btnDynamicButton->Text = L"I'm dynamic " + counter; btnDynamicButton->UseVisualStyleBackColor = true; btnDynamicButton->Click += gcnew System::EventHandler(this, &MainForm::dynamicButtonsClick); tabPage2->Controls->Add(btnDynamicButton); } } private: System::Void mnuListControls_Click(System::Object^ sender, System::EventArgs^ e) { for each(Control^ control in tabPage2->Controls) { textBox1->AppendText(control->Name + "\n"); } } private: System::Void dynamicButtonsClick(System::Object^ sender, System::EventArgs^ e) { textBox1->AppendText("Dynamic Button clicked !\t" + ((Button^)sender)->Name + "\n"); if (((Button^)sender)->Name == "btnDynamicButton3") { MessageBox::Show("Du hast den richtigen Button gedrückt !"); } } private: System::Void mnuTextBoxenHerstellen_Click(System::Object^ sender, System::EventArgs^ e) { createTextBoxes(); } void createTextBoxes() { for (int counter = 0;counter < 10;counter++) { TextBox^ dynamicTextBox = gcnew TextBox; dynamicTextBox->Location = System::Drawing::Point(200, 0 + 25 * counter); dynamicTextBox->Name = L"textBox" + counter; dynamicTextBox->ScrollBars = System::Windows::Forms::ScrollBars::Both; dynamicTextBox->TabIndex = 67; dynamicTextBox->TextChanged += gcnew System::EventHandler(this, &MainForm::dynamicTextBoxesTextChanged); tabPage2->Controls->Add(dynamicTextBox); } } private: System::Void dynamicTextBoxesTextChanged(System::Object^ sender, System::EventArgs^ e) { textBox1->AppendText(((TextBox^)sender)->Name + " TextChanged : " + ((TextBox^)sender)->Text + "\n"); } private: System::Void btnAddDoubles_Click(System::Object^ sender, System::EventArgs^ e) { double ersteZahl = Double::Parse(txtErsteZahl->Text); double zweiteZahl = Double::Parse(txtZweiteZahl->Text); double ergebnis = ersteZahl + zweiteZahl; textBox1->AppendText(ergebnis.ToString("N2")); } private: System::Void btnArrayList_Click(System::Object^ sender, System::EventArgs^ e) { ArrayList^ listeVonElementen = gcnew ArrayList; listeVonElementen->Add("Bli"); txtCollections->AppendText("\n:::" + listeVonElementen[0]->ToString() + "\n"); listeVonElementen->Add("Bla"); listeVonElementen->Add("Blubb"); listeVonElementen->Add("Yeah"); listeVonElementen->Add(this); listeVonElementen->Add(3); listeVonElementen->Add(gcnew Button); listeVonElementen->Remove("Bli"); txtCollections->AppendText(listeVonElementen->IndexOf("Yeah").ToString()); listeVonElementen->Insert(3, "Blubbbbbb"); listeVonElementen->Reverse(); for each(Object^ o in listeVonElementen) { txtCollections->AppendText(o->GetType() + " | " + o->ToString() + "\r\n"); } } private: System::Void btnQueue_Click(System::Object^ sender, System::EventArgs^ e) { System::Collections::Queue^ queue = gcnew System::Collections::Queue; queue->Enqueue("1"); queue->Enqueue("3"); queue->Enqueue("2"); queue->Enqueue("4"); txtCollections->Text += queue->Count.ToString(); int count = queue->Count; for (int counter = 1;counter <= count;counter++) { txtCollections->AppendText(queue->Dequeue()->ToString()); //NICHT rausnehmen, nur drauf schauen //txtCollections->AppendText(queue->Peek()->ToString()); } } private: System::Void btnStack_Click(System::Object^ sender, System::EventArgs^ e) { Stack^ stack = gcnew Stack; stack->Push("1"); //stack->Push(1); //stack->Push(this); stack->Push("2"); stack->Push("3"); stack->Push("4"); stack->Push("5"); int count = stack->Count; for (int counter = 0;counter < count;counter++) { txtCollections->AppendText((String^)stack->Pop()); } } private: System::Void btnSortedList_Click(System::Object^ sender, System::EventArgs^ e) { SortedList^ sortedList = gcnew SortedList; sortedList->Add(1, "Sieger"); //sortedList->Add(1, "Sieger"); -> Fehler, existiert schon sortedList->Add(3, "Drittplatzierter"); sortedList->Add(2, "Zweiter Sieger"); for each(int key in sortedList->Keys) { txtCollections->AppendText(key + " | " + sortedList[key] + "\r\n"); } SortedList^ sortedList1 = gcnew SortedList; DateTime d = DateTime(1971, 12, 12); sortedList1->Add(d, "Sieger3"); sortedList1->Add(DateTime(1970, 12, 12), "Sieger2"); sortedList1->Add(DateTime(1968, 12, 12), "Sieger1"); for each(DateTime key in sortedList1->Keys) { txtCollections->AppendText(key + " | " + sortedList1[key] + "\r\n"); } } private: System::Void btnHashtable_Click(System::Object^ sender, System::EventArgs^ e) { Hashtable^ openWith = gcnew Hashtable; // Add some elements to the hash table. There are no // duplicate keys, but some of the values are duplicates. openWith->Add("txt", "notepad.exe"); //openWith->Add("txt", "notepad.exe"); -> Fehler openWith->Add("bmp", "paint.exe"); openWith->Add("dib", "paint.exe"); openWith->Add("rtf", "wordpad.exe"); txtCollections->AppendText(openWith["txt"] + "\r\n"); openWith["rtf"] = "winword.exe"; //If the key "ht" doesn't exist, add entry to our Hashtable if (!openWith->ContainsKey("ht")) { openWith->Add("ht", "hypertrm.exe"); } for each(DictionaryEntry de in openWith) { txtCollections->AppendText(de.Key + " | " + de.Value + "\r\n"); } } private: System::Void btnList_Click(System::Object^ sender, System::EventArgs^ e) { //Fully qualified |Diamantoperator System::Collections::Generic::List<String^>^ phrases = gcnew System::Collections::Generic::List<String^>(); phrases->Add("Text"); phrases->Add("Text1"); phrases->Add("Text2"); phrases->Add("Text3"); //phrases->Add(34);-> Fehler for each(String^ oneElement in phrases) { txtCollections->AppendText(oneElement); } } private: System::Void btnArray_Click(System::Object^ sender, System::EventArgs^ e) { array<String^>^ myArr = { L"The", L"quick", L"brown", L"fox", L"jumps", L"over", L"the", L"lazy", L"dog" }; Array::Resize(myArr, myArr->Length + 5); array<Byte>^ buffer = gcnew array<Byte>(1024); ArrayList^ l = gcnew ArrayList(myArr); l->AddRange(myArr); array<String ^, 3> ^ my3DArray = gcnew array<String ^, 3>(3, 5, 6); my3DArray[0, 0, 0] = "Bla"; ArrayList^ zeile = gcnew ArrayList; ArrayList^ spalte = gcnew ArrayList; spalte->Add(zeile); ((ArrayList^)spalte[0])[0] = "j"; } private: System::Void btnBenchmark_Click(System::Object^ sender, System::EventArgs^ e) { int size = 10000000; ArrayList^ numbers = gcnew ArrayList; DateTime startTime = DateTime::Now; for (int counter = 0; counter < size; counter++) { numbers->Add(counter); } DateTime endTime = DateTime::Now; txtCollections->AppendText("\r\nCreation of 1M int in ArrayList :" + endTime.Subtract(startTime).TotalMilliseconds); ////////////////////////////////////////////////////////// startTime = DateTime::Now; array<int>^ intArray = gcnew array<int>(size); for (int counter = 0; counter < size; counter++) { intArray[counter] = counter; } endTime = DateTime::Now; txtCollections->AppendText("\r\nCreation of 1M int in array :" + endTime.Subtract(startTime).TotalMilliseconds); ////////////////////////////////////////////////////////// startTime = DateTime::Now; for (int counter = 0;counter < size;counter++) { int temp = (int)numbers[counter]; } endTime = DateTime::Now; txtCollections->AppendText("\r\nAccessing 1M int in ArrayList :" + endTime.Subtract(startTime).TotalMilliseconds); ////////////////////////////////////////////////////////// startTime = DateTime::Now; for (int counter = 0;counter < size;counter++) { int temp = intArray[counter]; } endTime = DateTime::Now; txtCollections->AppendText("\r\nAccessing 1M int in array :" + endTime.Subtract(startTime).TotalMilliseconds); } private: System::Void btnDrawLine_Click(System::Object^ sender, System::EventArgs^ e) { System::Drawing::Graphics^ graphics = pictureBox2->CreateGraphics(); System::Drawing::Pen^ penRed = gcnew System::Drawing::Pen(Color::Red); System::Drawing::Pen^ penBlue = gcnew System::Drawing::Pen(Color::Blue); System::Drawing::Pen^ penGreen = gcnew System::Drawing::Pen(Color::Green); System::Drawing::Brush^ brushYellow = gcnew System::Drawing::SolidBrush(Color::Yellow); graphics->DrawLine(penRed, 0, 0, 100, 300); graphics->DrawLine(penBlue, 100, 200, 0, 0); graphics->DrawEllipse(penGreen, 20, 90, 40, 20); graphics->FillRectangle(brushYellow, 70, 70, 30, 60); } System::Drawing::Point lastPoint = Point(0, 0); ArrayList^ points; private: System::Void pnlDrawing_Click(System::Object^ sender, System::EventArgs^ e) { System::Drawing::Graphics^ graphics = pictureBox2->CreateGraphics(); System::Drawing::Pen^ penBlack = gcnew System::Drawing::Pen(Color::Black, 4); // |Umrechnung |aktuelle Mouseposition Bildschirm System::Drawing::Point actualPosition = pnlDrawing->PointToClient(this->Cursor->Position); graphics->DrawLine(penBlack, lastPoint, actualPosition); lastPoint = actualPosition; points->Add(lastPoint); System::Diagnostics::Debug::WriteLine(actualPosition.ToString()); } private: System::Void pnlDrawing_Paint(System::Object^ sender, System::Windows::Forms::PaintEventArgs^ e) { drawLinesByPoints(e->Graphics); } void drawLinesByPoints(Graphics^ g) { System::Drawing::Pen^ penBlack = gcnew System::Drawing::Pen(Color::Black, 4); int pointsCount = points->Count; logger->Info("Amount of points in points :" + pointsCount); for (int counter = 0; counter < pointsCount - 1;counter++) { logger->Debug((Point)points[counter]); g->DrawLine(penBlack, (Point)points[counter], (Point)points[counter + 1]); } } void translatePoints(int factor) { logger->Debug("factor =" + factor); int pointsCount = points->Count; logger->Info("Amount of points in points :" + pointsCount); for (int counter = 0; counter < pointsCount - 1;counter++) { logger->Trace("old point:" + (Point)points[counter]); Point newPoint = Point(((Point)points[counter]).X * factor, ((Point)points[counter]).Y * factor); points[counter] = newPoint; logger->Trace("new point:" + newPoint); } } private: System::Void btnTranslatePoints_Click(System::Object^ sender, System::EventArgs^ e) { translatePoints(2); pnlDrawing->CreateGraphics()->Clear(Color::Gainsboro); pnlDrawing->Refresh(); } private: System::Void btnDrawImage_Click(System::Object^ sender, System::EventArgs^ e) { System::Drawing::Pen^ penBlack = gcnew System::Drawing::Pen(Color::Black, 4); System::Drawing::Image^ image = Image::FromFile("d:\\spaghettimonster.jpg"); Graphics^ imageGraphics = Graphics::FromImage(image); imageGraphics->DrawLine(penBlack, 0, 0, 200, 200); Point ulCorner = Point(100, 0); pnlGraphics->CreateGraphics()->DrawImage(image, ulCorner); image->Save("d:\\spaghettimonster12.jpg"); } private: System::Void btnDrawHouse_Click(System::Object^ sender, System::EventArgs^ e) { for (double counter = 0.1;counter < 1;counter += 0.1) { drawHouse(pnlGraphics->CreateGraphics(), 0 + 20 * counter, 0 + 20 * counter, counter, counter); } } void drawHouse(Graphics^ graphics, int startPositionX, int startPositionY, double scaleFactorX, double scaleFactorY) { System::Drawing::Pen^ penBlue = gcnew System::Drawing::Pen(Color::Blue); drawSpecialLine(graphics, penBlue, startPositionX, startPositionY, 0, 300, 0, 100, scaleFactorX, scaleFactorY); drawSpecialLine(graphics, penBlue, startPositionX, startPositionY, 0, 100, 200, 100, scaleFactorX, scaleFactorY); drawSpecialLine(graphics, penBlue, startPositionX, startPositionY, 200, 100, 200, 300, scaleFactorX, scaleFactorY); drawSpecialLine(graphics, penBlue, startPositionX, startPositionY, 200, 300, 0, 300, scaleFactorX, scaleFactorY); drawSpecialLine(graphics, penBlue, startPositionX, startPositionY, 0, 100, 100, 20, scaleFactorX, scaleFactorY); drawSpecialLine(graphics, penBlue, startPositionX, startPositionY, 100, 20, 200, 100, scaleFactorX, scaleFactorY); drawSpecialLine(graphics, penBlue, startPositionX, startPositionY, 100, 20, 300, 20, scaleFactorX, scaleFactorY); drawSpecialLine(graphics, penBlue, startPositionX, startPositionY, 300, 20, 400, 100, scaleFactorX, scaleFactorY); drawSpecialLine(graphics, penBlue, startPositionX, startPositionY, 400, 100, 200, 100, scaleFactorX, scaleFactorY); drawSpecialLine(graphics, penBlue, startPositionX, startPositionY, 400, 300, 400, 100, scaleFactorX, scaleFactorY); drawSpecialLine(graphics, penBlue, startPositionX, startPositionY, 200, 300, 400, 300, scaleFactorX, scaleFactorY); } void drawSpecialLine(Graphics^ graphics, Pen^ pen, float startPositionX, float startPositionY, float x1, float y1, float x2, float y2, float scaleFactorX, float scaleFactorY) { graphics->DrawLine(pen, startPositionX + x1 * scaleFactorX, startPositionY + y1 * scaleFactorY, startPositionX + x2 * scaleFactorX, startPositionY + y2 * scaleFactorY); } private: System::Void btnDivide_Click(System::Object^ sender, System::EventArgs^ e) { double ersteZahl = double::Parse(txtErsteZahl->Text); double zweiteZahl = double::Parse(txtZweiteZahl->Text); try { divide(ersteZahl, zweiteZahl); } catch (TeilenDurch0Exception^ ex) { logger->Fatal(ex->Message); logger->Fatal("Zähler war : " + ex->zaehler); txtZweiteZahl->BackColor = Color::LightSalmon; } catch (Exception^ ex) { logger->Fatal(ex->Message); } finally{ //Aufräumarbeiten } } private: /// <summary>Divides two numbers (number1, number2) and returns the result as int /// </summary> /// <param name="number1">Is the numerator as <code>int</code></param> /// <param name="number2">Is the denominator as <code>int</code></param> /// <returns>The result of the division</returns> /// <exception cref="Notepad.TeilenDurch0Exception">Thrown when number2 == 0</exception> int divide(int number1, int number2) { if (number2 == 0) { TeilenDurch0Exception^ ex = gcnew TeilenDurch0Exception("Teilen durch 0 is nich !", number1); throw ex; } return number1 / number2; } private: System::Void btnAddTreeNodeToTreeView_Click(System::Object^ sender, System::EventArgs^ e) { treeView1->ExpandAll(); TreeNode^ anotherNode = gcnew TreeNode("I'm amazingly dynamic!"); anotherNode->Name = "I'm amazingly dynamic!"; treeView1->Nodes[0]->Nodes->Add(anotherNode); } private: System::Void treeView1_AfterSelect(System::Object^ sender, System::Windows::Forms::TreeViewEventArgs^ e) { txtTreeView->AppendText(e->Node->Name + "\r\n"); txtTreeView->AppendText("Parent : " + e->Node->Parent + "\r\n"); e->Node->BackColor = Color::LightSalmon; } private: System::Void btnRemoveTreeNOde_Click(System::Object^ sender, System::EventArgs^ e) { if (treeView1->SelectedNode) { treeView1->Nodes->Remove(treeView1->SelectedNode); } } private: System::Void btnReadDirectories_Click(System::Object^ sender, System::EventArgs^ e) { TreeNode^ root = gcnew TreeNode("d:\\"); for each(String^ oneDirectory in System::IO::Directory::GetDirectories("d:\\")) { TreeNode^ directoryNode = gcnew TreeNode(oneDirectory); root->Nodes->Add(directoryNode); } treeView1->Nodes->Add(root); } int fakultaet(int n) { logger->Trace("Einsprung"); logger->Trace("n=" + n); if (n == 1) { logger->Trace("Raussprung"); logger->Trace("n=" + n); return 1; } int result = n*fakultaet(n - 1); logger->Trace("result=" + result); logger->Trace("Raussprung"); return result; } //Fakultät 5! //5! = 5 * 4 * 3 * 2 * 1 private: System::Void btnRecursion_Click(System::Object^ sender, System::EventArgs^ e) { txtTreeView->AppendText(fakultaet(4).ToString()); } private: System::Void btnRegex_Click(System::Object^ sender, System::EventArgs^ e) { System::Text::RegularExpressions::Regex^ regex = gcnew System::Text::RegularExpressions::Regex(txtRegexExpr->Text); if (regex->IsMatch(txtRegex->Text)) { txtRegex->BackColor = Color::White; } else { txtRegex->BackColor = Color::LightSalmon; } } private: System::Void btnChangeRegexInRegexTextBox_Click(System::Object^ sender, System::EventArgs^ e) { this->txtAutoRegexMatcher->reconfigure(txtRegexExpr->Text, Color::LightPink); } private: System::Void btnWalkTreeViewRecursive_Click(System::Object^ sender, System::EventArgs^ e) { showTreeNodes(treeView1->Nodes[0], 0); } //Rekursion void showTreeNodes(TreeNode^ t, int level) { level++; logger->Trace(level + " : " + t->Name); for each(TreeNode^ tn in t->Nodes) { showTreeNodes(tn, level); } } private: System::Void btnDriveInfo_Click(System::Object^ sender, System::EventArgs^ e) { for each(System::IO::DriveInfo^ d in System::IO::DriveInfo::GetDrives()) { txtTreeView->AppendText(d->Name + "\r\n"); } } private: System::Void mnuRefreshTreeView_Click(System::Object^ sender, System::EventArgs^ e) { Type^ treeNodeType = TreeNode::typeid; treeView1->Nodes->AddRange(getDriveInfoTreeNodes()->ToArray(TreeNode)); } ArrayList^ getDriveInfoTreeNodes() { ArrayList^ driveInfoTreeNodes = gcnew ArrayList; for each(System::IO::DriveInfo^ d in System::IO::DriveInfo::GetDrives()) { TreeNode^ driveInfoTreeNode = gcnew TreeNode(d->Name); driveInfoTreeNodes->Add(driveInfoTreeNode); logger->Trace(d->Name); } return driveInfoTreeNodes; } }; }
[ "Alfa-Dozent@SB-U03-001" ]
Alfa-Dozent@SB-U03-001
431ff081938c8641e6dae688879a3a241a6cfd83
26df6604faf41197c9ced34c3df13839be6e74d4
/src/org/apache/poi/ss/usermodel/charts/LayoutMode.hpp
f7576880bb2756388e335833b7309e0dcb3648ff
[ "Apache-2.0" ]
permissive
pebble2015/cpoi
58b4b1e38a7769b13ccfb2973270d15d490de07f
6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6
refs/heads/master
2021-07-09T09:02:41.986901
2017-10-08T12:12:56
2017-10-08T12:12:56
105,988,119
0
0
null
null
null
null
UTF-8
C++
false
false
1,582
hpp
// Generated from /POI/java/org/apache/poi/ss/usermodel/charts/LayoutMode.java #pragma once #include <java/io/fwd-POI.hpp> #include <java/lang/fwd-POI.hpp> #include <org/apache/poi/ss/usermodel/charts/fwd-POI.hpp> #include <java/lang/Enum.hpp> template<typename ComponentType, typename... Bases> struct SubArray; namespace java { namespace io { typedef ::SubArray< ::java::io::Serializable, ::java::lang::ObjectArray > SerializableArray; } // io namespace lang { typedef ::SubArray< ::java::lang::Comparable, ObjectArray > ComparableArray; typedef ::SubArray< ::java::lang::Enum, ObjectArray, ComparableArray, ::java::io::SerializableArray > EnumArray; } // lang } // java namespace poi { namespace ss { namespace usermodel { namespace charts { typedef ::SubArray< ::poi::ss::usermodel::charts::LayoutMode, ::java::lang::EnumArray > LayoutModeArray; } // charts } // usermodel } // ss } // poi struct default_init_tag; class poi::ss::usermodel::charts::LayoutMode final : public ::java::lang::Enum { public: typedef ::java::lang::Enum super; public: /* package */ static LayoutMode *EDGE; static LayoutMode *FACTOR; // Generated public: LayoutMode(::java::lang::String* name, int ordinal); protected: LayoutMode(const ::default_init_tag&); public: static ::java::lang::Class *class_(); static LayoutMode* valueOf(::java::lang::String* a0); static LayoutModeArray* values(); private: virtual ::java::lang::Class* getClass0(); };
d7127e15eed5731c748aa028140f9f0605a1f879
3751d5701b0ec5fe8e2fe5e955aa278c3e53e87d
/GLProject_ModelNormalMap/GLProject_model/MyModel.cpp
4b3532ab1733a75c61b511aff5658d4572595bcb
[]
no_license
liuxuanhai/Cplus_Cplus_OpenGL_test
72fbe6d3a73fe7d7881490c5d76ae1d052ce0e0e
441f6d8043920dd44dc68704768ef6f62bae3924
refs/heads/master
2020-05-15T18:01:11.891474
2016-12-08T07:32:33
2016-12-08T07:32:33
null
0
0
null
null
null
null
GB18030
C++
false
false
9,117
cpp
#include "Utility.h" #include "MyCamera.h" #include "MyMesh.h" #include "MyModel.h" map<string, GLuint> CMyModel::m_textures; D_LIGHT CMyModel::directLight; CMyModel::CMyModel() { } CMyModel::~CMyModel() { } CMyModel::CMyModel(GLchar * _path) :m_dirty(true), m_matView(nullptr), m_matProjection(nullptr), m_scale(1.0f), m_position(0.0f) { Assimp::Importer importer; const aiScene * scene = importer.ReadFile(_path, aiProcess_Triangulate | aiProcess_FlipUVs | aiProcess_CalcTangentSpace); if (!scene || scene->mFlags == AI_SCENE_FLAGS_INCOMPLETE || !scene->mRootNode) { printf_s("Read model failed\n"); return; } m_directory = _path; m_directory = m_directory.substr(0, m_directory.find_last_of('/')); this->ProcessNode(scene, scene->mRootNode); int a = 1; } void CMyModel::SetCamera(CMyCamera * _camera) { m_camera = _camera; m_matView = _camera->GetView(); m_matProjection = _camera->GetProjection(); m_dirty = true; } void CMyModel::Update(GLfloat _dt) { if (m_dirty) { m_matModel = glm::mat4(); m_matModel = glm::translate(m_matModel, m_position); m_matModel = glm::rotate(m_matModel, glm::radians(m_degree), m_rotateAxis); m_matModel = glm::scale(m_matModel, m_scale); m_dirty = false; } } void CMyModel::Draw(GLuint _shaderProgram) { glUseProgram(_shaderProgram); glUniformMatrix4fv(glGetUniformLocation(_shaderProgram, "matModel"), 1, GL_FALSE, glm::value_ptr(m_matModel)); glUniformMatrix4fv(glGetUniformLocation(_shaderProgram, "matView"), 1, GL_FALSE, glm::value_ptr(*m_matView)); glUniformMatrix4fv(glGetUniformLocation(_shaderProgram, "matProjection"), 1, GL_FALSE, glm::value_ptr(*m_matProjection)); glUniform3fv(glGetUniformLocation(_shaderProgram, "viewPos"), 1, glm::value_ptr(*m_camera->GetPosition())); glUniform3fv(glGetUniformLocation(_shaderProgram, "lightDir"), 1, glm::value_ptr(m_lightDir)); //d light //glUniform3fv(glGetUniformLocation(_shaderProgram, "dLight.lightDir"), 1, glm::value_ptr(directLight.direction)); //glUniform3fv(glGetUniformLocation(_shaderProgram, "dLight.ambient"), 1, glm::value_ptr(directLight.ambient)); //glUniform3fv(glGetUniformLocation(_shaderProgram, "dLight.diffuse"), 1, glm::value_ptr(directLight.diffuse)); //glUniform3fv(glGetUniformLocation(_shaderProgram, "dLight.specular"), 1, glm::value_ptr(directLight.specular)); //glUniform1f(glGetUniformLocation(_shaderProgram, "shiniess"), 128); //pt light //char name[128] = {}; //for (int i = 0; i < m_ptLights.size(); ++i) //{ // //sprintf_s(name, sizeof(name), "ptLights[%d].lightPosition", i); // //glUniform3fv(glGetUniformLocation(_shaderProgram, name), 1, glm::value_ptr(m_ptLights[i].position)); // //sprintf_s(name, sizeof(name), "ptLights[%d].ambient", i); // //glUniform3fv(glGetUniformLocation(_shaderProgram, name), 1, glm::value_ptr(m_ptLights[i].ambient)); // //sprintf_s(name, sizeof(name), "ptLights[%d].diffuse", i); // //glUniform3fv(glGetUniformLocation(_shaderProgram, name), 1, glm::value_ptr(m_ptLights[i].diffuse)); // //sprintf_s(name, sizeof(name), "ptLights[%d].specular", i); // //glUniform3fv(glGetUniformLocation(_shaderProgram, name), 1, glm::value_ptr(m_ptLights[i].specular)); // //sprintf_s(name, sizeof(name), "ptLights[%d].constant", i); // //glUniform1f(glGetUniformLocation(_shaderProgram, name), m_ptLights[i].constant); // //sprintf_s(name, sizeof(name), "ptLights[%d].linear", i); // //glUniform1f(glGetUniformLocation(_shaderProgram, name), m_ptLights[i].linear); // //sprintf_s(name, sizeof(name), "ptLights[%d].quadratic", i); // //glUniform1f(glGetUniformLocation(_shaderProgram, name), m_ptLights[i].quadratic); //} ////Spot light ////glUniform3fv(glGetUniformLocation(_shaderProgram, "spotLight.position") ,1, glm::value_ptr(*m_camera->GetPosition())); ////glUniform3fv(glGetUniformLocation(_shaderProgram, "spotLight.faceTo"), 1, glm::value_ptr(*m_camera->GetFaceTo())); ////glUniform3fv(glGetUniformLocation(_shaderProgram, "spotLight.ambient"), 1, glm::value_ptr(m_spotLight.ambient)); ////glUniform3fv(glGetUniformLocation(_shaderProgram, "spotLight.diffuse"), 1, glm::value_ptr(m_spotLight.diffuse)); ////glUniform3fv(glGetUniformLocation(_shaderProgram, "spotLight.specular"), 1, glm::value_ptr(m_spotLight.specular)); ////glUniform1f(glGetUniformLocation(_shaderProgram, "spotLight.constant"), m_spotLight.constant); ////glUniform1f(glGetUniformLocation(_shaderProgram, "spotLight.linear"), m_spotLight.linear); ////glUniform1f(glGetUniformLocation(_shaderProgram, "spotLight.quadratic"), m_spotLight.quadratic); ////glUniform1f(glGetUniformLocation(_shaderProgram, "spotLight.cutoff"), m_spotLight.cutoff); ////glUniform1f(glGetUniformLocation(_shaderProgram, "spotLight.outCutoff"), m_spotLight.outCutoff); for (auto mesh : m_meshes) { mesh->Draw(_shaderProgram); } } void CMyModel::ProcessNode(const aiScene * _scene, aiNode * _node) { //处理自己的网格 for (int i = 0; i < _node->mNumMeshes; ++i) { auto mesh = this->ProcessMesh(_scene, _scene->mMeshes[_node->mMeshes[i]]); m_meshes.push_back(mesh); } //遍历子节点 for (int i = 0; i < _node->mNumChildren; ++i) { this->ProcessNode(_scene, _node->mChildren[i]); } } CMyMesh * CMyModel::ProcessMesh(const aiScene * _scene, aiMesh * _mesh) { vector<VERTEX> vertices; vector<GLuint> indices; vector<TEXTURE> textures; for (int i = 0; i < _mesh->mNumVertices; ++i) { VERTEX vertex; vertex.position.x = _mesh->mVertices[i].x; vertex.position.y = _mesh->mVertices[i].y; vertex.position.z = _mesh->mVertices[i].z; vertex.normal2.x = _mesh->mNormals[i].x; vertex.normal2.y = _mesh->mNormals[i].y; vertex.normal2.z = _mesh->mNormals[i].z; //直接读取 vertex.tangent.x = _mesh->mTangents[i].x; vertex.tangent.y = _mesh->mTangents[i].y; vertex.tangent.z = _mesh->mTangents[i].z; vertex.tangent = glm::normalize(vertex.tangent); vertex.bitangent.x = _mesh->mBitangents[i].x; vertex.bitangent.y = _mesh->mBitangents[i].y; vertex.bitangent.z = _mesh->mBitangents[i].z; vertex.bitangent = glm::normalize(vertex.bitangent); vertex.normal = glm::cross(vertex.tangent, vertex.bitangent); if (_mesh->mTextureCoords[0]) { vertex.texcoords.x = _mesh->mTextureCoords[0][i].x; vertex.texcoords.y = _mesh->mTextureCoords[0][i].y; } vertices.push_back(vertex); } for (int i = 0; i < _mesh->mNumFaces; i++) { aiFace face = _mesh->mFaces[i]; for (int j = 0; j < face.mNumIndices; j++) { indices.push_back(face.mIndices[j]); } } if (_mesh->mMaterialIndex >= 0) { this->ProcessMaterial(_scene, _mesh->mMaterialIndex, textures); } CMyMesh * mesh = new CMyMesh(vertices, indices, textures); return mesh; } void CMyModel::ProcessMaterial(const aiScene * _scene, GLint _materialIdx, vector<TEXTURE> & _textures) { if (_materialIdx < 0) return; aiMaterial * material = _scene->mMaterials[_materialIdx]; vector<TEXTURE> texDiff = LoadMaterialTextures(material, aiTextureType_DIFFUSE, "tex_diffuse"); _textures.insert(_textures.end(), texDiff.begin(), texDiff.end()); vector<TEXTURE> texSpec = LoadMaterialTextures(material, aiTextureType_SPECULAR, "tex_specular"); _textures.insert(_textures.end(), texSpec.begin(), texSpec.end()); vector<TEXTURE> texNormalMap = LoadMaterialTextures(material, aiTextureType_HEIGHT, "tex_normalMap"); _textures.insert(_textures.end(), texNormalMap.begin(), texNormalMap.end()); vector<TEXTURE> texReflect = LoadMaterialTextures(material, aiTextureType_AMBIENT, "tex_reflect"); _textures.insert(_textures.end(), texReflect.begin(), texReflect.end()); } vector<TEXTURE> CMyModel::LoadMaterialTextures(aiMaterial * _material, aiTextureType _type, string _typeName) { vector<TEXTURE> vec; aiString name; for (int i = 0; i < _material->GetTextureCount(_type); i++) { if (_type == aiTextureType_REFLECTION) { int a = 1; } //获取纹理名称 _material->GetTexture(_type, i, &name); TEXTURE tex; tex.type = _typeName; tex.path = m_directory + '/' + name.C_Str(); tex.id = this->GetLocalTexture(tex.path.c_str()); vec.push_back(tex); } return vec; } GLuint CMyModel::GetLocalTexture(const GLchar * _texName) { //从map中找 if (m_textures.count(_texName)) return m_textures[_texName]; //没有 GLuint texture = 0; GLubyte * source = nullptr; int texWidth, texHeight; glGenTextures(1, &texture); source = SOIL_load_image(_texName, &texWidth, &texHeight, nullptr, SOIL_LOAD_RGB); glBindTexture(GL_TEXTURE_2D, texture); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, texWidth, texHeight, 0, GL_RGB, GL_UNSIGNED_BYTE, source); glGenerateMipmap(GL_TEXTURE_2D); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); glBindTexture(GL_TEXTURE_2D, 0); SOIL_free_image_data(source); source = nullptr; m_textures.emplace(make_pair(_texName, texture)); return texture; } void CMyModel::AddPointLight(PT_LIGHT _ptLight) { m_ptLights.push_back(_ptLight); }
5c4094a13025c1386e27ef8cd55d813003e90afd
a60ff43808d79e528b76f62ad44598827cb95d60
/cameronet.h
6e3b0fc0727e0f8824c42559236e13cce60dc24d
[]
no_license
yyyly/cameronet
93f1f8ce2f1f29677aa449b2c663ba884aa6d14f
c400cd55a0a0caec83b3d6649180367ff1792bac
refs/heads/master
2020-12-02T13:07:05.931854
2020-08-22T02:27:15
2020-08-22T02:27:15
231,015,624
0
0
null
null
null
null
UTF-8
C++
false
false
3,190
h
#ifndef CAMERONET_H #define CAMERONET_H #include<QObject> #include<QWidget> #include<QMultiMap> #include<QThread> #include<QMap> #include "HCNetSDK.h" #include "cameronet_global.h" #include "enums.h" #include "cameradeviceimf.h" #include "screen.h" #include "soundpushbutton.h" #include "dhnetsdk.h" #include "dhwork.h" #include "dummy.h" class CAMERONETSHARED_EXPORT CameroNet : public QObject { Q_OBJECT private: explicit CameroNet(QObject *p =nullptr); public: static CameroNet* getInstance() { static CameroNet * instance; if(instance == nullptr) { instance = new CameroNet(); } return instance; } ~CameroNet(); public slots: /*登陆函数*/ void login(CameraDeviceImf &i); /*播放函数,默认采用主码流,TCP连接方式*/ LLONG realPlay(CameraDeviceImf *info, LONG channel, Screen &screen); /*停止播放,函数的错误信息留给调用模块处理*/ DWORD stopPlay(CameraDeviceImf &info, Screen *screen); DWORD stopPlay(LONG realHandle); /*登出,函数的错误信息留给调用模块处理*/ DWORD loginOut(CameraDeviceImf *info); /*抓图函数*/ DWORD capPic(CameraDeviceImf &info); /*声音控制函数*/ DWORD changeSoundState(CameraDeviceImf& info,SoundCommond c); DWORD opendSound(CameraDeviceImf *info); DWORD closeSound(CameraDeviceImf *info); /*只录像,不播放*/ LONG recordVedio(CameraDeviceImf *info,LONG channel,QString *fileName,Screen *screen = nullptr); /*云台控制*/ bool PtzControl(CameraDeviceImf &info,Camero::PTZcommond c,int start,int step = 4,int channal = 1);//start = 1 开始,start = 0,结束 //DH private slots: void dhLoginResut(const CameraDeviceImf& info,int state,int err); signals: void signalDeviceStatusChanged(CameraDeviceImf* camero,Camero::LineState state); void dhLogin(const CameraDeviceImf* imf); protected: bool event(QEvent *event); private: static QMap<LONG,QString> fileNameMap; //HK static void CALLBACK hkLoginResutCallback(LONG lUserID,DWORD dwResult, LPNET_DVR_DEVICEINFO_V30 lpDeviceInfo,void *pUser); static void CALLBACK g_RealDataCallBack_V30(LONG lRealHandle, DWORD dwDataType, BYTE *pBuffer,DWORD dwBufSize,void* dwUser); static void CALLBACK fExceptionCallBack(DWORD dwType,LONG lUserID, LONG lHandle,void *pUser); //DH static void CALLBACK autoConnectFunc(LONG lLoginID,char *pchDVRIP,LONG nDVRPort,DWORD dwUser); static void CALLBACK fDisConnect( LLONG lLoginID,char *pchDVRIP,LONG nDVRPort,LDWORD dwUser);//设备断线回调函数 static QList<CameraDeviceImf *> HKPinfoList;//存储登陆信息,析构函数使用 static QMap<LLONG,CameraDeviceImf *> pImfByUserIdMap; static QMultiMap<LONG,Screen *> pScreenByUserMap; //DH static QMap<LLONG,CameraDeviceImf *> dhImfByUserIdMap; static void CALLBACK fRealDataCallBack( LLONG lRealHandle,DWORD dwDataType, BYTE *pBuffer, DWORD dwBufsize, LDWORD dwUser); }; #endif // CAMERONET_H
59f3fb1f681c088aa465cfb3181d42a497331212
1de5dbf9d55db225dcea0703c2686c05b5ad6044
/CLONE_client/CLONE_client/Code/Frustum.cpp
ebfeb1ae8f1c25d5fd5766770ddb6ea6bdbf13cd
[]
no_license
RYUHYEONGSEOK/CLONE
4e48c8307445402a8fb656b599090513e63786ab
3a3d3e18e84fe7fea3667ab9f9d2123b8246a2fe
refs/heads/master
2021-01-15T13:18:40.409938
2017-08-17T01:42:46
2017-08-17T01:42:46
78,752,257
0
0
null
null
null
null
UTF-8
C++
false
false
2,072
cpp
#include "stdafx.h" #include "Frustum.h" //Objact #include "Camera.h" IMPLEMENT_SINGLETON(CFrustum) CFrustum::CFrustum(void) { } CFrustum::~CFrustum(void) { } HRESULT CFrustum::UpdateFrustum(CObj* pCam) { D3DXMATRIX viewProjection; D3DXMatrixMultiply(&viewProjection, &(*((CCamera*)pCam)->GetViewMatrix()), &(*((CCamera*)pCam)->GetProjMatrix())); // Left plane m_Plane[0].a = viewProjection._14 + viewProjection._11; m_Plane[0].b = viewProjection._24 + viewProjection._21; m_Plane[0].c = viewProjection._34 + viewProjection._31; m_Plane[0].d = viewProjection._44 + viewProjection._41; // Right plane m_Plane[1].a = viewProjection._14 - viewProjection._11; m_Plane[1].b = viewProjection._24 - viewProjection._21; m_Plane[1].c = viewProjection._34 - viewProjection._31; m_Plane[1].d = viewProjection._44 - viewProjection._41; // Top plane m_Plane[2].a = viewProjection._14 - viewProjection._12; m_Plane[2].b = viewProjection._24 - viewProjection._22; m_Plane[2].c = viewProjection._34 - viewProjection._32; m_Plane[2].d = viewProjection._44 - viewProjection._42; // Bottom plane m_Plane[3].a = viewProjection._14 + viewProjection._12; m_Plane[3].b = viewProjection._24 + viewProjection._22; m_Plane[3].c = viewProjection._34 + viewProjection._32; m_Plane[3].d = viewProjection._44 + viewProjection._42; // Near plane m_Plane[4].a = viewProjection._13; m_Plane[4].b = viewProjection._23; m_Plane[4].c = viewProjection._33; m_Plane[4].d = viewProjection._43; // Far plane m_Plane[5].a = viewProjection._14 - viewProjection._13; m_Plane[5].b = viewProjection._24 - viewProjection._23; m_Plane[5].c = viewProjection._34 - viewProjection._33; m_Plane[5].d = viewProjection._44 - viewProjection._43; // Normalize planes for (int i = 0; i < 6; i++) { D3DXPlaneNormalize(&m_Plane[i], &m_Plane[i]); } return S_OK; } bool CFrustum::SphereInFrustum(const D3DXVECTOR3* pCenter, const float& fRadius) { for (int i = 0; i < 6; ++i) { if (D3DXPlaneDotCoord(&m_Plane[i], pCenter) + fRadius < 0) return false; } return true; }
9a47fd0adfe4fa39086cf6a822d89ce85ebf388f
5307162e2cb27a7256a2d88ad2f84b33ca5e43e5
/ball_detection/src/CTrajectory.cpp
df4de177afffbe171161f77c68376a174c0dfdcb
[]
no_license
lengagne/rws2016_pkumars
01814daaa409b1891a0908ba93b653dd601d9098
4d8f861b91be741fe39dd5097627da5a484789b8
refs/heads/master
2023-03-22T00:49:56.612961
2019-03-07T12:21:03
2019-03-07T12:21:03
null
0
0
null
null
null
null
UTF-8
C++
false
false
13,366
cpp
/*********************************************************************************** Name: CTrajectory.cpp Revision: Date: 25-02-2013 Author: Paulo Dias Comments: Class with all info needed for ballistic trajectory estimation (using simple quadratic: parabolic movement) images Revision: Libraries: Notes: Code generated under Ubuntu using openCV, VTK and PCL (for reading clouds) Compiled using CMake ***********************************************************************************/ #include "CTrajectory.h" /************************************************************************************************* * Constructor *************************************************************************************************/ CTrajectory::CTrajectory() { // Initialization for (int i=0;i<HISTORY;i++) { previous_pose[i][0] = 0; previous_pose[i][1] = 0; previous_pose[i][2] = 0; trajecto_pose[i] = -1; } c(0)=c(1)=c(2)=0; origin[0]=origin[1]=origin[2]=0; has_trajectory = 0; } /************************************************************************************************* * Destructor *************************************************************************************************/ CTrajectory::~CTrajectory() { } /************************************************************************************************* * update_list * if ball detected check if it is supporting previous trajectory and update trajecto_pose accordingly *************************************************************************************************/ void CTrajectory::update_list(double *ball_centre_coord3D) { Eigen::Vector3f temp; Eigen::Vector3f temporigin; double coords[3]; for (int i=1;i<HISTORY;i++) { previous_pose[i-1] = previous_pose[i]; trajecto_pose[i-1] = trajecto_pose[i]; } if (ball_centre_coord3D[0] != 0) { previous_pose[HISTORY-1][0] = ball_centre_coord3D[0]; previous_pose[HISTORY-1][1] = ball_centre_coord3D[1]; previous_pose[HISTORY-1][2] = ball_centre_coord3D[2]; // check if new position support actual trajectory if (has_trajectory) { temp = previous_pose[HISTORY-1]; temp[2]=0; temporigin = origin; temporigin[2]=0; double d = (temp-temporigin).norm(); compute_3D_from_1D(d,coords); if ( sqrt ( (coords[0]-previous_pose[HISTORY-1][0]) * (coords[0]-previous_pose[HISTORY-1][0]) +(coords[1]-previous_pose[HISTORY-1][1]) * (coords[1]-previous_pose[HISTORY-1][1]) +(coords[2]-previous_pose[HISTORY-1][2]) * (coords[2]-previous_pose[HISTORY-1][2]) ) < MIN_DISTANCE_TRAJECTORY ) //if (fabs(ball_centre_coord3D[2] - (c(0)*d*d +c(1)*d +c(2) ) ) < MIN_DISTANCE_TRAJECTORY) trajecto_pose[HISTORY-1] = 1; else trajecto_pose[HISTORY-1] = 0; } else trajecto_pose[HISTORY-1] = 0; } else { previous_pose[HISTORY-1][0] = 0; previous_pose[HISTORY-1][1] = 0; previous_pose[HISTORY-1][2] = 0; trajecto_pose[HISTORY-1] = -1; } } /************************************************************************************************* * compute_trajectory_from_last_three * Compute trajectory from last three positions if valid ball pos, otherwise c(0)=0 (no trajectory) *************************************************************************************************/ void CTrajectory::compute_trajectory_from_last_four() { Eigen::Vector3f temp; Eigen::Vector3f temporigin; double coords1[3],coords2[3],coords3[3],coords4[3]; has_trajectory = 0; c(0)=0; origin(0) = origin(1)=origin(2)=0; if (trajecto_pose[HISTORY-4]>=0 && trajecto_pose[HISTORY-3]>=0 && trajecto_pose[HISTORY-2]>=0 && trajecto_pose[HISTORY-1]>=0) { double d1,d2,d3,d4; origin = previous_pose[HISTORY-4]; temporigin = origin; // set orgin in ground plane temporigin[2]=0; d4 = 0; temp = previous_pose[HISTORY-3]; temp[2]=0; d3 = (temp-temporigin).norm(); temp = previous_pose[HISTORY-2]; temp[2]=0; d2 = (temp-temporigin).norm(); temp = previous_pose[HISTORY-1]; temp[2]=0; d1 = (temp-temporigin).norm(); //Eigen::Matrix3f A; Eigen::MatrixXf A(4,3); //A << d1*d1,d1,1,d2*d2,d2,1,d3*d3,d3,1; A << d4*d4,d4,1,d3*d3,d3,1,d2*d2,d2,1,d1*d1,d1,1; Eigen::VectorXf b(4,1); //Eigen::Vector3f b(previous_pose[HISTORY-3][2],previous_pose[HISTORY-2][2],previous_pose[HISTORY-1][2]); b << previous_pose[HISTORY-4][2],previous_pose[HISTORY-3][2],previous_pose[HISTORY-2][2],previous_pose[HISTORY-1][2]; c = A.colPivHouseholderQr().solve(b); // check if all three points fits well to curve compute_3D_from_1D(d4,coords4); compute_3D_from_1D(d3,coords3); compute_3D_from_1D(d2,coords2); compute_3D_from_1D(d1,coords1); if ( sqrt ( (coords4[0]-previous_pose[HISTORY-4][0]) * (coords4[0]-previous_pose[HISTORY-4][0]) +(coords4[1]-previous_pose[HISTORY-4][1]) * (coords4[1]-previous_pose[HISTORY-4][1]) +(coords4[2]-previous_pose[HISTORY-4][2]) * (coords4[2]-previous_pose[HISTORY-4][2]) ) > MIN_DISTANCE_TRAJECTORY || sqrt ( (coords3[0]-previous_pose[HISTORY-3][0]) * (coords3[0]-previous_pose[HISTORY-3][0]) +(coords3[1]-previous_pose[HISTORY-3][1]) * (coords3[1]-previous_pose[HISTORY-3][1]) +(coords3[2]-previous_pose[HISTORY-3][2]) * (coords3[2]-previous_pose[HISTORY-3][2]) ) > MIN_DISTANCE_TRAJECTORY || sqrt ( (coords2[0]-previous_pose[HISTORY-2][0]) * (coords2[0]-previous_pose[HISTORY-2][0]) +(coords2[1]-previous_pose[HISTORY-2][1]) * (coords2[1]-previous_pose[HISTORY-2][1]) +(coords2[2]-previous_pose[HISTORY-2][2]) * (coords2[2]-previous_pose[HISTORY-2][2]) ) > MIN_DISTANCE_TRAJECTORY || sqrt ( (coords1[0]-previous_pose[HISTORY-1][0]) * (coords1[0]-previous_pose[HISTORY-1][0]) +(coords1[1]-previous_pose[HISTORY-1][1]) * (coords1[1]-previous_pose[HISTORY-1][1]) +(coords1[2]-previous_pose[HISTORY-1][2]) * (coords1[2]-previous_pose[HISTORY-1][2]) ) > MIN_DISTANCE_TRAJECTORY) /* if ( fabs(previous_pose[HISTORY-4][2] - (c(0)*d4*d4 +c(1)*d4 +c(2) ) ) > MIN_DISTANCE_TRAJECTORY || fabs(previous_pose[HISTORY-3][2] - (c(0)*d3*d3 +c(1)*d3 +c(2) ) ) > MIN_DISTANCE_TRAJECTORY || fabs(previous_pose[HISTORY-2][2] - (c(0)*d2*d2 +c(1)*d2 +c(2) ) ) > MIN_DISTANCE_TRAJECTORY || fabs(previous_pose[HISTORY-1][2] - (c(0)*d1*d1 +c(1)*d1 +c(2) ) ) > MIN_DISTANCE_TRAJECTORY )*/ { has_trajectory = 0; c(0)=0; origin(0) = origin(1)=origin(2)=0; } else { has_trajectory = 1; trajecto_pose[HISTORY-4]=1; trajecto_pose[HISTORY-3]=1; trajecto_pose[HISTORY-2]=1; trajecto_pose[HISTORY-1]=1; origin = previous_pose[HISTORY-4]; } } } /************************************************************************************************* * compute_trajectory_from_last_three * Compute trajectory from last three positions if valid ball pos, otherwise c(0)=0 (no trajectory) *************************************************************************************************/ void CTrajectory::compute_trajectory_from_last_three() { Eigen::Vector3f temp; Eigen::Vector3f temporigin; double coords1[3],coords2[3],coords3[3]; has_trajectory = 0; c(0)=0; origin(0) = origin(1)=origin(2)=0; if (trajecto_pose[HISTORY-3]>=0 && trajecto_pose[HISTORY-2]>=0 && trajecto_pose[HISTORY-1]>=0) { double d1,d2,d3; origin = previous_pose[HISTORY-3]; temporigin = origin; // set orgin in ground plane temporigin[2]=0; d3 = 0; temp = previous_pose[HISTORY-2]; temp[2]=0; d2 = (temp-temporigin).norm(); temp = previous_pose[HISTORY-1]; temp[2]=0; d1 = (temp-temporigin).norm(); //Eigen::Matrix3f A; Eigen::MatrixXf A(3,3); //A << d1*d1,d1,1,d2*d2,d2,1,d3*d3,d3,1; A << d3*d3,d3,1,d2*d2,d2,1,d1*d1,d1,1; Eigen::VectorXf b(3,1); //Eigen::Vector3f b(previous_pose[HISTORY-3][2],previous_pose[HISTORY-2][2],previous_pose[HISTORY-1][2]); b << previous_pose[HISTORY-3][2],previous_pose[HISTORY-2][2],previous_pose[HISTORY-1][2]; c = A.colPivHouseholderQr().solve(b); // check if all three points fits well to curve compute_3D_from_1D(d3,coords3); compute_3D_from_1D(d2,coords2); compute_3D_from_1D(d1,coords1); if ( sqrt ( (coords3[0]-previous_pose[HISTORY-3][0]) * (coords3[0]-previous_pose[HISTORY-3][0]) +(coords3[1]-previous_pose[HISTORY-3][1]) * (coords3[1]-previous_pose[HISTORY-3][1]) +(coords3[2]-previous_pose[HISTORY-3][2]) * (coords3[2]-previous_pose[HISTORY-3][2]) ) > MIN_DISTANCE_TRAJECTORY || sqrt ( (coords2[0]-previous_pose[HISTORY-2][0]) * (coords2[0]-previous_pose[HISTORY-2][0]) +(coords2[1]-previous_pose[HISTORY-2][1]) * (coords2[1]-previous_pose[HISTORY-2][1]) +(coords2[2]-previous_pose[HISTORY-2][2]) * (coords2[2]-previous_pose[HISTORY-2][2]) ) > MIN_DISTANCE_TRAJECTORY || sqrt ( (coords1[0]-previous_pose[HISTORY-1][0]) * (coords1[0]-previous_pose[HISTORY-1][0]) +(coords1[1]-previous_pose[HISTORY-1][1]) * (coords1[1]-previous_pose[HISTORY-1][1]) +(coords1[2]-previous_pose[HISTORY-1][2]) * (coords1[2]-previous_pose[HISTORY-1][2]) ) > MIN_DISTANCE_TRAJECTORY) /* if ( fabs(previous_pose[HISTORY-4][2] - (c(0)*d4*d4 +c(1)*d4 +c(2) ) ) > MIN_DISTANCE_TRAJECTORY || fabs(previous_pose[HISTORY-3][2] - (c(0)*d3*d3 +c(1)*d3 +c(2) ) ) > MIN_DISTANCE_TRAJECTORY || fabs(previous_pose[HISTORY-2][2] - (c(0)*d2*d2 +c(1)*d2 +c(2) ) ) > MIN_DISTANCE_TRAJECTORY || fabs(previous_pose[HISTORY-1][2] - (c(0)*d1*d1 +c(1)*d1 +c(2) ) ) > MIN_DISTANCE_TRAJECTORY )*/ { has_trajectory = 0; c(0)=0; origin(0) = origin(1)=origin(2)=0; } else { has_trajectory = 1; trajecto_pose[HISTORY-3]=1; trajecto_pose[HISTORY-2]=1; trajecto_pose[HISTORY-1]=1; origin = previous_pose[HISTORY-3]; } } } /************************************************************************************************* * refine_trajectory * Compute trajectory from all the valid positions *************************************************************************************************/ void CTrajectory::refine_trajectory() { Eigen::Vector3f temp; Eigen::Vector3f temporigin; Eigen::MatrixXf A(HISTORY,3); Eigen::VectorXf b(HISTORY,1); //origin(0)=0; for(int k=0;k<HISTORY;k++) if (trajecto_pose[k]==1) { // if (origin(0)==0) // { // origin = previous_pose[k]; // temporigin = origin; // temporigin[2]=0; // } double d; temp = previous_pose[k]; temp[2]=0; temporigin = origin; temporigin[2]=0; d = (temp-temporigin).norm(); A(k,0) = d*d; A(k,1) = d; A(k,2) = 1; b(k,0) = previous_pose[k][2]; } else { A(k,0) = 0; A(k,1) = 0; A(k,2) = 1; b(k,0) = origin[2]; } c = A.colPivHouseholderQr().solve(b); } /************************************************************************************************* * get_roots * compute the roots of the current quadratic using vtkMath * Solves a quadratic equation c1*t^2 + c2*t + c3 = height * Return array contains number of (real) roots (counting multiple roots as one) followed by roots themselves * Return null if no trajectory is estimated *************************************************************************************************/ void CTrajectory::get_roots(double *roots, double height) { if (!has_trajectory) roots[0]=0; double *rootst; rootst = vtkPolynomialSolversUnivariate::SolveQuadratic(c(0),c(1),c(2)-height); roots[0] = rootst[0]; roots[1] = rootst[1]; roots[2] = rootst[2]; } /************************************************************************************************* * compute_3D_from_1D * compute the 3D coordinate of a point, from the x coordinate in the quadratic * based on the quadratic equation and the 3D origin used for computing the quadratic *************************************************************************************************/ void CTrajectory::compute_3D_from_1D(double x,double *coords) { double vx,vy,d; Eigen::Vector3f temp; Eigen::Vector3f temporigin; int index; index = get_last_supporting_ball_index(); vx = previous_pose[index][0]-origin[0]; vy = previous_pose[index][1]-origin[1]; temp = previous_pose[index]; temp[2]=0; temporigin = origin; temporigin[2]=0; d = (temp-temporigin).norm(); coords[0] = x*(vx/d) + origin[0]; coords[1] = x*(vy/d) + origin[1]; coords[2] = c(0)*x*x + c(1)*x+ c(2); } /************************************************************************************************* * get_last_supporting_ball_index * return the index of the last ball that supports trajectory * if no trajectory, return -1 *************************************************************************************************/ int CTrajectory::get_last_supporting_ball_index() { int i; if (!has_trajectory) return 0; for (i = HISTORY-1; i >= 0; i--) if (trajecto_pose[i] == 1) return i; return 0; }
b580f76b808ab439bf920ea1ece279f55fdca944
1970e7a25704834502153d0f8b851fe8dd89aae2
/C Programs/C Programs - 1/Sum of Primes.cpp
5f6e398e3fbfb603f0c0bb5723236598696b3884
[]
no_license
MathProgrammer/Hacker-Earth
6a5eb4e1e15b140ead0105d1a00db505f7334660
e72d88e72caedffefbdb5c47ef6f447c1a8cbc42
refs/heads/master
2023-07-11T05:50:44.382305
2023-07-01T10:36:01
2023-07-01T10:36:01
88,396,435
53
54
null
2022-07-08T14:32:30
2017-04-16T06:49:03
C++
UTF-8
C++
false
false
880
cpp
#include <stdio.h> #include <vector> using namespace std; vector <long long> prime_sum(1e6 + 1, 0); void precompute_prime_sum() { vector <int> is_prime(1e6 + 1, true); is_prime[0] = is_prime[1] = false; for(int i = 2; i <= 1e6; i++) { if(is_prime[i]) { for(int j = 2*i ; j <= 1e6; j += i) { is_prime[j] = false; } } } for(int i = 2; i <= 1e6; i++) { prime_sum[i] = prime_sum[i - 1] + (is_prime[i] ? i : 0); } } int main() { int no_of_test_cases; scanf("%d", &no_of_test_cases); precompute_prime_sum(); while(no_of_test_cases--) { int left, right; scanf("%d %d", &left, &right); printf("%lld\n", prime_sum[right] - prime_sum[left - 1]); } return 0; }
4572afe3191a3f42ee577600df794017dd07d198
cf99281f2660ed447312f5e821abed448e8b4fc3
/connectedComponents.cpp
89607f2adbb30e6544b3618df80929d4cb308ce1
[]
no_license
abhisehekkumr/tree
69c439ef4ffb6f7055ec52fff31606ee19dc5212
67697f5280b728ba16422a385bd84edbfd6971ad
refs/heads/master
2022-01-04T14:40:13.793257
2019-08-17T08:23:06
2019-08-17T08:23:06
156,063,456
0
0
null
null
null
null
UTF-8
C++
false
false
1,488
cpp
#include<iostream> #include<vector> #include<algorithm> using namespace std; void getDfs(int **edges, int n, bool *visited, vector<int> &k, int start){ k.push_back(start); visited[start] = true; for(int i = 0; i < n; i++){ if(i == start) continue; if(edges[start][i] && !visited[i]) getDfs(edges,n,visited,k,i); } } void getConnectedComponents(int **edges, int n, vector<vector<int>> &v){ bool *visited = new bool[n]; for(int i = 0; i < n; i++) visited[i] = false; for(int i = 0; i < n; i++){ vector<int> k; if(!visited[i]){ getDfs(edges,n,visited,k,i); v.push_back(k); } } delete [] visited; } int main(){ int n,e; cin >> n >> e; int **edges = new int*[n]; for(int i = 0; i < n; i++){ edges[i] = new int[n]; for(int j = 0; j < n; j++) edges[i][j] = 0; } for(int i = 0; i < e; i++){ int f,s; cin >> f >> s; edges[f][s] = 1; edges[s][f] = 1; } vector<vector<int>> v; getConnectedComponents(edges,n,v); for(int i = 0; i < v.size(); i++){ sort(v[i].begin(),v[i].end()); for(int j = 0; j < v[i].size(); j++) std::cout << v[i][j] << ' '; std::cout << '\n'; } for(int i = 0; i < n; i++) delete [] edges[i]; delete [] edges; }
21816a20e0f94d8b0329ba886aa6d1b2c56effd5
ab570cfbba5d90e73727dca01008e43029a42eae
/bonus6.cpp
78bf05e380abbe8bf02ab8139a613c6c7f6f5ba7
[]
no_license
rileym65/Casino
3adfbdf4501f0c55191c031a0ffe3615b30b8cfc
6b73002fdfebbda9ca490774b941f561cb73a049
refs/heads/master
2020-08-08T22:08:40.508213
2019-10-09T13:49:34
2019-10-09T13:49:34
213,931,230
0
0
null
null
null
null
UTF-8
C++
false
false
29,136
cpp
#include <stdlib.h> #include "header.h" #include "poker.h" #include "bonus6.h" #ifdef GRAPHIC #include "images/bonus6.xpm" #endif Bonus6::Bonus6(int decks,int jokers,float minbet): Poker(decks,jokers,minbet) { betAmount=1; } void Bonus6::clearBets(int p) { #ifdef GRAPHIC rcs_GC gc; gc=rcs_openGC(display,mainScreen); rcs_namedForeground(display,gc,"black"); rcs_copyArea(display,table,mainScreen,gc,playerBetX(p)-80,playerBetY(p)-90, 140,217,playerBetX(p)-80,playerBetY(p)-90); rcs_closeGC(display,gc); #endif } int Bonus6::playerX(int p) { #ifdef GRAPHIC switch (p) { case 0:return 9; case 1:return 166; case 2:return 334; case 3:return 504; case 4:return 662; case 99:return 360; } #endif #ifdef CONSOLE switch (p) { case 0:return 60; case 1:return 60; case 2:return 30; case 3:return 1; case 4:return 1; case 99:return 30; } #endif return 325; } int Bonus6::playerY(int p) { #ifdef GRAPHIC switch (p) { case 0:return 464; case 1:return 488; case 2:return 509; case 3:return 488; case 4:return 464; case 99:return 21; } #endif #ifdef CONSOLE switch (p) { case 0:return 3; case 1:return 14; case 2:return 17; case 3:return 14; case 4:return 3; case 99:return 5; } #endif return 21; } int Bonus6::playerBetX(int p) { #ifdef GRAPHIC switch (p) { case 0:return 82; case 1:return 239; case 2:return 408; case 3:return 579; case 4:return 736; case 99:return 33; } #endif #ifdef CONSOLE switch (p) { case 0:return 63; case 1:return 63; case 2:return 33; case 3:return 4; case 4:return 4; case 99:return 33; } #endif return 33; } int Bonus6::playerBetY(int p) { #ifdef GRAPHIC switch (p) { case 0:return 213; case 1:return 240; case 2:return 262; case 3:return 240; case 4:return 213; case 99:return 5; case 98:return 8; } #endif #ifdef CONSOLE switch (p) { case 0:return 2; case 1:return 13; case 2:return 16; case 3:return 13; case 4:return 2; case 99:return 5; case 98:return 8; } #endif return 5; } void Bonus6::showBetAmount() { rcs_GC gc; rcs_Font font; char buffer[80]; gc=rcs_openGC(display,mainScreen); rcs_namedForeground(display,gc,"darkgreen"); rcs_drawFilledBox(display,mainScreen,gc,377,565,99,32); rcs_namedForeground(display,gc,"yellow"); font=rcs_openFont(display,BET_FONT); rcs_setFont(display,gc,font); sprintf(buffer,"$%ld",betAmount); rcs_drawString(display,mainScreen,gc,385,586,buffer); rcs_closeFont(display,font); rcs_closeGC(display,gc); displayScreen(); } void Bonus6::showPlayers() { int i; #ifdef GRAPHIC rcs_GC gc; rcs_Font font; #endif for (i=0;i<PLAYERS_DSTUD;i++) if (players[i]!=NULL) { #ifdef GRAPHIC gc=rcs_openGC(display,mainScreen); font=rcs_openFont(display,PLAYER_FONT); rcs_setFont(display,gc,font); rcs_namedForeground(display,gc,"darkgreen"); rcs_drawFilledBox(display,mainScreen,gc,playerX(i),playerY(i),125,40); rcs_namedForeground(display,gc,"yellow"); rcs_drawString(display,mainScreen,gc,playerX(i),playerY(i), players[i]->getName()); sprintf(buffer,"Money $%12.2f",players[i]->money()); rcs_drawString(display,mainScreen,gc,playerX(i),playerY(i)+20,buffer); rcs_closeFont(display,font); rcs_closeGC(display,gc); #endif #ifdef CONSOLE GotoXY(playerX(i),playerY(i)); Output(players[i]->getName()); GotoXY(playerX(i),playerY(i)+1); Output("Money $"); sprintf(buffer,"%12.2f",players[i]->money()); Output(buffer); GotoXY(playerX(i),playerY(i)+2); Output("Comm: $"); sprintf(buffer,"%12.2f",comms[i]); Output(buffer); #endif } #ifdef GRAPHIC displayScreen(); #endif } float Bonus6::placeBet(int player) { float betReturn; char flag; char betFlags; #ifdef GRAPHIC rcs_Event event; rcs_GC gc; rcs_Font font; betFlags=0; gc=rcs_openGC(display,mainScreen); rcs_namedForeground(display,gc,"gray"); rcs_drawFilledBox(display,mainScreen,gc,10,566,80,29); rcs_namedForeground(display,gc,"black"); rcs_drawBox(display,mainScreen,gc,12,568,76,25); font=rcs_openFont(display,BET_FONT); rcs_setFont(display,gc,font); rcs_drawString(display,mainScreen,gc,32,587,"Exit"); rcs_namedForeground(display,gc,"gray"); rcs_drawFilledBox(display,mainScreen,gc,210,566,80,29); rcs_namedForeground(display,gc,"black"); rcs_drawBox(display,mainScreen,gc,212,568,76,25); rcs_drawString(display,mainScreen,gc,232,587,"Play"); rcs_closeFont(display,font); rcs_closeGC(display,gc); displayScreen(); flag=' '; while (flag==' ') { event=getEvent(display); switch(event.type) { case EVENT_BUTTON_PRESS: if (event.d1 == 1 && event.d3>=566 && event.d3<=598) { if (event.d1 == 1 && event.d2>=210 && event.d2<=290) { flag='P'; } if (event.d1 == 1 && event.d2>=10 && event.d2<=90) { flag='X'; betFlags=0; } if (event.d2>=490 && event.d2<516) { betAmount+=1; showBetAmount(); } if (event.d2>=522 && event.d2<546) { betAmount+=5; showBetAmount(); } if (event.d2>=553 && event.d2<578) { betAmount+=10; showBetAmount(); } if (event.d2>=584 && event.d2<609) { betAmount+=25; showBetAmount(); } if (event.d2>=615 && event.d2<640) { betAmount+=50; showBetAmount(); } if (event.d2>=645 && event.d2<671) { betAmount+=100; showBetAmount(); } if (event.d2>=676 && event.d2<701) { betAmount+=500; showBetAmount(); } if (event.d2>=708 && event.d2<733) { betAmount+=1000; showBetAmount(); } if (event.d2>=739 && event.d2<765) { betAmount+=5000; showBetAmount(); } if (event.d2>=771 && event.d2<796) { betAmount+=10000; showBetAmount(); } } if (event.d1 == 3 && event.d3>=566 && event.d3<=598) { if (event.d2>=490 && event.d2<516) { betAmount-=1; if (betAmount<1) betAmount=1; showBetAmount(); } if (event.d2>=522 && event.d2<546) { betAmount-=5; if (betAmount<1) betAmount=1; showBetAmount(); } if (event.d2>=553 && event.d2<578) { betAmount-=10; if (betAmount<1) betAmount=1; showBetAmount(); } if (event.d2>=584 && event.d2<609) { betAmount-=25; if (betAmount<1) betAmount=1; showBetAmount(); } if (event.d2>=615 && event.d2<640) { betAmount-=50; if (betAmount<1) betAmount=1; showBetAmount(); } if (event.d2>=645 && event.d2<671) { betAmount-=100; if (betAmount<1) betAmount=1; showBetAmount(); } if (event.d2>=676 && event.d2<701) { betAmount-=500; if (betAmount<1) betAmount=1; showBetAmount(); } if (event.d2>=708 && event.d2<733) { betAmount-=1000; if (betAmount<1) betAmount=1; showBetAmount(); } if (event.d2>=739 && event.d2<765) { betAmount-=5000; if (betAmount<1) betAmount=1; showBetAmount(); } if (event.d2>=771 && event.d2<796) { betAmount-=10000; if (betAmount<1) betAmount=1; showBetAmount(); } } if (event.d1 == 1 && (betFlags & 1) != 1 && event.d2>=playerBetX(player)-50 && event.d2<=playerBetX(player)+20 && event.d3>=playerBetY(player)-90 && event.d3<=playerBetY(player)-20 && (betAmount & 1) != 1) { betReturn=players[player]->placeBet(betAmount,0,playerBetX(player)-20,playerBetY(player)-50); betFlags |= 1; showPlayers(); players[i]->paintBets(); displayScreen(); if (betFlags == 3) flag='P'; } if (event.d1 == 1 && betFlags==1 && event.d2>=playerBetX(player)-80 && event.d2<=playerBetX(player)-10 && event.d3>=playerBetY(player)+50 && event.d3<=playerBetY(player)+120) { betReturn=players[player]->placeBet(players[player]->getHandBet(0)/2,3,playerBetX(player)-50,playerBetY(player)+85); betFlags |= 2; progressives[PROG_CARIB]+=.75; showPlayers(); players[i]->paintBets(); displayScreen(); if (betFlags == 3) flag='P'; } break; } } gc=rcs_openGC(display,mainScreen); rcs_namedForeground(display,gc,"darkgreen"); rcs_drawFilledBox(display,mainScreen,gc,10,566,80,29); rcs_drawFilledBox(display,mainScreen,gc,210,566,80,29); rcs_closeGC(display,gc); displayScreen(); #endif #ifdef CONSOLE GotoXY(playerX(i),playerY(i)+7); Output("Enter Bet :"); Input(buffer); sscanf(buffer,"%f",&bet); betReturn=players[i]->placeBet(bet,0,1,1); betReturn=players[i]->placeBet(bet,1,1,1); betReturn=players[i]->placeBet(bet,2,1,1); GotoXY(playerX(i),playerY(i)+7); Output(" "); GotoXY(playerX(i),playerY(i)+1); GotoXY(playerX(i),playerY(i)+7); Output("Tourn. Bet (y/n):"); Input(buffer); if (buffer[0]=='y') { betReturn=players[i]->placeBet(1,3,1,1); GotoXY(playerX(i)+17,playerY(i)+1); Output("*"); } GotoXY(playerX(i),playerY(i)+7); Output(" "); GotoXY(playerX(i),playerY(i)+6); sprintf(buffer,"%12.2f",players[i]->money()); Output("Money $"); Output(buffer); GotoXY(playerX(i),playerY(i)+1); sprintf(buffer,"%4.0f %4.0f %4.0f",bet,bet,bet); Output(buffer); #endif if (betFlags != 0) flag='P'; if (flag!='P' && flag!='D') return 0; else return betReturn; } void Bonus6::play() { float bet; float betReturn; #ifdef GRAPHIC rcs_GC gc; table=rcs_xpmToPixmap(display,mainWindow,bonus6_xpm); #endif bet=1; while (bet!=0) { #ifdef GRAPHIC gc=rcs_openGC(display,mainScreen); rcs_copyArea(display,table,mainScreen,gc,0,0,800,600,0,0); rcs_closeGC(display,gc); showBetAmount(); displayScreen(); #endif #ifdef CONSOLE ClrScr(); #endif deck->shuffle(); for (i=0;i<5;i++) if (players[i]!=NULL) players[i]->clearAllBets(); showPlayers(); for (i=0;i<5;i++) if (players[i]!=NULL) { if (players[i]->playerType()=='H') { bet=placeBet(i); } else { betReturn=players[i]->placeBet(minBet,0,playerBetX(i)-20,playerBetY(i)-50); if (rcs_random(10)<4) betReturn=players[i]->placeBet(minBet/2,3,playerBetX(i)-50,playerBetY(i)+85); #ifdef CONSOLE GotoXY(playerX(i)+17,playerY(i)+1); Output("*"); GotoXY(playerX(i),playerY(i)+6); sprintf(buffer,"%12.2f",players[i]->money()); Output("Money $"); Output(buffer); GotoXY(playerX(i),playerY(i)+1); sprintf(buffer,"%4.0f %4.0f %4.0f",minBet,minBet,minBet); Output(buffer); #endif } #ifdef GRAPHIC showPlayers(); players[i]->paintBets(); displayScreen(); #endif #ifdef CONSOLE players[i]->showBets(); #endif } if (betReturn) ; if (bet!=0) { round(); } } #ifdef GRAPHIC rcs_closePixmap(display,table); #endif } void Bonus6::round() { int i,j; Card *c1,*c2,*c3,*c4; Card *communityCard; unsigned long high; // float betReturn; int folded[5]; Hand* pHand; #ifdef GRAPHIC rcs_GC gc; #endif for (i=0;i<PLAYERS_BONUS6;i++) folded[i]=0; for (i=0;i<PLAYERS_BONUS6;i++) if (players[i]!=NULL) players[i]->newHand(0); for (i=0;i<PLAYERS_BONUS6;i++) if (players[i]!=NULL) { for (j=0;j<2;j++) { players[i]->newCard(deck->dealCard(),0); players[i]->getHand(0)->cards[j]->setPosition(playerX(i)+j*15,playerY(i)-120); } GotoXY(playerX(i),playerY(i)+3); if (players[i]->playerType()=='H') { #ifdef GRAPHIC gc=rcs_openGC(display,mainScreen); players[i]->getHand(0)->paint(display,mainScreen,gc,0); rcs_closeGC(display,gc); displayScreen(); #endif #ifdef CONSOLE players[i]->getHand(0)->display(0); #endif } else { #ifdef GRAPHIC gc=rcs_openGC(display,mainScreen); players[i]->getHand(0)->paint(display,mainScreen,gc,3); rcs_closeGC(display,gc); displayScreen(); #endif #ifdef CONSOLE players[i]->getHand(0)->display(3); #endif } Delay(1); } communityCard=deck->dealCard(); communityCard->setSide('F'); communityCard->setPosition(playerX(99),playerY(99)); gc=rcs_openGC(display,mainScreen); communityCard->paint(display,mainScreen,gc); rcs_closeGC(display,gc); displayScreen(); /* players[i]->newCard(deck->dealCard(),0); GotoXY(playerX(i),playerY(i)+3); if (players[i]->playerType()=='H') players[i]->getHand(0)->display(0); else players[i]->getHand(0)->display(3); Delay(1); } */ #ifdef GRAPHIC gc=rcs_openGC(display,mainScreen); rcs_closeGC(display,gc); displayScreen(); #endif #ifdef CONSOLE GotoXY(playerX(99),playerY(99)); #endif Delay(1); for (i=0;i<PLAYERS_BONUS6;i++) if (players[i]!=NULL && folded[i]==0) { if (players[i]->playerType()=='H') { #ifdef GRAPHIC if (actionBox(playerX(i),playerY(i),130,70,"Continue?","Yes","No")==0) { players[i]->placeBet(players[i]->getHandBet(0),1,playerBetX(i)-50,playerBetY(i)+15); } else { players[i]->loseHandBets(0); players[i]->loseHandBets(3); gc=rcs_openGC(display,mainScreen); rcs_copyArea(display,table,mainScreen,gc,playerX(i),playerY(i)-120,130,120,playerX(i),playerY(i)-120); rcs_closeGC(display,gc); folded[i]=1; } /* gc=rcs_openGC(display,mainScreen); rcs_copyArea(display,table,mainScreen,gc,playerX(i),playerY(i)-120,130,120,playerX(i),playerY(i)-120); rcs_closeGC(display,gc); */ #endif #ifdef CONSOLE GotoXY(playerX(i),playerY(i)+7); Output("Let it ride ? "); Input(buffer); if (buffer[0]=='N' || buffer[0]=='n') { players[i]->winHandBets(2,0); players[i]->loseHandBets(2); GotoXY(playerX(i),playerY(i)+1); sprintf(buffer,"%4.0f %4.0f %4.0f ",players[i]->getHandBet(0), players[i]->getHandBet(1),players[i]->getHandBet(2)); Output(buffer); GotoXY(playerX(i),playerY(i)+6); sprintf(buffer,"%12.2f",players[i]->money()); Output("Money $"); Output(buffer); } GotoXY(playerX(i),playerY(i)+7); Output(" "); #endif } else { pHand=players[i]->getHand(0); pHand->cards[2]=communityCard; pHand->numCards=3; c1=pHand->cards[0]; c2=pHand->cards[1]; high=pHand->pokerValue(5,0); pHand->numCards=2; pHand->cards[0]=c1; pHand->cards[1]=c2; if (high>PK_PAIR || (c1->getSuit()==c2->getSuit() && c2->getSuit()==communityCard->getSuit()) || (c1->value()>5 && c2->value()>5 && communityCard->value()>5) ) { players[i]->placeBet(players[i]->getHandBet(0),1,playerBetX(i)-50,playerBetY(i)+15); } else { players[i]->loseHandBets(0); players[i]->loseHandBets(3); gc=rcs_openGC(display,mainScreen); rcs_copyArea(display,table,mainScreen,gc,playerX(i),playerY(i)-120,130,120,playerX(i),playerY(i)-120); rcs_closeGC(display,gc); folded[i]=1; } } clearBets(i); #ifdef GRAPHIC showPlayers(); players[i]->paintBets(); displayScreen(); #endif Delay(1); } #ifdef GRAPHIC gc=rcs_openGC(display,mainScreen); rcs_closeGC(display,gc); displayScreen(); #endif #ifdef CONSOLE GotoXY(playerX(99),playerY(99)); #endif Delay(1); /* ******************* Deal first card **************** */ for (i=0;i<PLAYERS_BONUS6;i++) if (players[i]!=NULL && folded[i]==0) { players[i]->newCard(deck->dealCard(),0); players[i]->getHand(0)->cards[2]->setPosition(playerX(i)+2*15,playerY(i)-120); GotoXY(playerX(i),playerY(i)+3); if (players[i]->playerType()=='H') { #ifdef GRAPHIC gc=rcs_openGC(display,mainScreen); players[i]->getHand(0)->paint(display,mainScreen,gc,0); rcs_closeGC(display,gc); displayScreen(); #endif #ifdef CONSOLE players[i]->getHand(0)->display(0); #endif } else { #ifdef GRAPHIC gc=rcs_openGC(display,mainScreen); players[i]->getHand(0)->paint(display,mainScreen,gc,4); rcs_closeGC(display,gc); displayScreen(); #endif #ifdef CONSOLE players[i]->getHand(0)->display(3); #endif } Delay(1); } /* ***************** round 2 ************** */ for (i=0;i<PLAYERS_BONUS6;i++) if (players[i]!=NULL && folded[i]==0) { if (players[i]->playerType()=='H') { #ifdef GRAPHIC if (actionBox(playerX(i),playerY(i),130,70,"Continue?","Yes","No")==0) { players[i]->placeBet(players[i]->getHandBet(0),2,playerBetX(i)+20,playerBetY(i)+15); } else { players[i]->loseHandBets(0); players[i]->loseHandBets(1); players[i]->loseHandBets(3); gc=rcs_openGC(display,mainScreen); rcs_copyArea(display,table,mainScreen,gc,playerX(i),playerY(i)-120,130,120,playerX(i),playerY(i)-120); rcs_closeGC(display,gc); folded[i]=1; } /* gc=rcs_openGC(display,mainScreen); rcs_copyArea(display,table,mainScreen,gc,playerX(i),playerY(i)-120,130,120,playerX(i),playerY(i)-120); rcs_closeGC(display,gc); */ #endif #ifdef CONSOLE GotoXY(playerX(i),playerY(i)+7); Output("Let it ride ? "); Input(buffer); if (buffer[0]=='N' || buffer[0]=='n') { players[i]->winHandBets(2,0); players[i]->loseHandBets(2); GotoXY(playerX(i),playerY(i)+1); sprintf(buffer,"%4.0f %4.0f %4.0f ",players[i]->getHandBet(0), players[i]->getHandBet(1),players[i]->getHandBet(2)); Output(buffer); GotoXY(playerX(i),playerY(i)+6); sprintf(buffer,"%12.2f",players[i]->money()); Output("Money $"); Output(buffer); } GotoXY(playerX(i),playerY(i)+7); Output(" "); #endif } else { pHand=players[i]->getHand(0); pHand->cards[3]=communityCard; pHand->numCards=4; c1=pHand->cards[0]; c2=pHand->cards[1]; c3=pHand->cards[2]; high=pHand->pokerValue(5,0); pHand->numCards=3; pHand->cards[0]=c1; pHand->cards[1]=c2; pHand->cards[2]=c3; if (high>PK_PAIR || (c1->getSuit()==c2->getSuit() && c2->getSuit()==c3->getSuit() && c3->getSuit()==communityCard->getSuit()) || (abs((c1->value()>5)+(c2->value()>5)+(c3->value()>5)+ (communityCard->value()>5))>2) ) { players[i]->placeBet(players[i]->getHandBet(0),2,playerBetX(i)+20,playerBetY(i)+15); } else { players[i]->loseHandBets(0); players[i]->loseHandBets(1); players[i]->loseHandBets(3); gc=rcs_openGC(display,mainScreen); rcs_copyArea(display,table,mainScreen,gc,playerX(i),playerY(i)-120,130,120,playerX(i),playerY(i)-120); rcs_closeGC(display,gc); folded[i]=1; } } clearBets(i); #ifdef GRAPHIC showPlayers(); players[i]->paintBets(); displayScreen(); #endif Delay(1); } /* ******************* Deal Second card **************** */ for (i=0;i<PLAYERS_BONUS6;i++) if (players[i]!=NULL && folded[i]==0) { players[i]->newCard(deck->dealCard(),0); players[i]->getHand(0)->cards[3]->setPosition(playerX(i)+3*15,playerY(i)-120); GotoXY(playerX(i),playerY(i)+3); if (players[i]->playerType()=='H') { #ifdef GRAPHIC gc=rcs_openGC(display,mainScreen); players[i]->getHand(0)->paint(display,mainScreen,gc,0); rcs_closeGC(display,gc); displayScreen(); #endif #ifdef CONSOLE players[i]->getHand(0)->display(0); #endif } else { #ifdef GRAPHIC gc=rcs_openGC(display,mainScreen); players[i]->getHand(0)->paint(display,mainScreen,gc,5); rcs_closeGC(display,gc); displayScreen(); #endif #ifdef CONSOLE players[i]->getHand(0)->display(3); #endif } Delay(1); } /* now check for 6th cards */ for (i=0;i<PLAYERS_BONUS6;i++) if (players[i]!=NULL && folded[i]==0) { pHand=players[i]->getHand(0); c1=pHand->cards[0]; c2=pHand->cards[1]; c3=pHand->cards[2]; c4=pHand->cards[3]; pHand->cards[pHand->numCards++]=communityCard; high=pHand->pokerValue(5,0); pHand->cards[0]=c1; pHand->cards[1]=c2; pHand->cards[2]=c3; pHand->cards[3]=c4; pHand->numCards--; if (high<(PK_PAIR|(6<<24)|(6<<16)) && players[i]->getHandBet(3)>0) { if (players[i]->playerType()=='H') { if (actionBox(playerX(i),playerY(i),130,70,"6th Card?","Yes","No")==0) { players[i]->placeBet(players[i]->getHandBet(0),4,playerBetX(i)+20,playerBetY(i)+85); players[i]->newCard(deck->dealCard(),0); players[i]->getHand(0)->cards[4]->setPosition(playerX(i)+4*15,playerY(i)-120); gc=rcs_openGC(display,mainScreen); players[i]->getHand(0)->paint(display,mainScreen,gc,0); rcs_closeGC(display,gc); players[i]->paintBets(); displayScreen(); Delay(1); } } else { players[i]->newCard(deck->dealCard(),0); players[i]->getHand(0)->cards[4]->setPosition(playerX(i)+4*15,playerY(i)-120); gc=rcs_openGC(display,mainScreen); players[i]->getHand(0)->paint(display,mainScreen,gc,0); rcs_closeGC(display,gc); players[i]->paintBets(); displayScreen(); Delay(1); } } } #ifdef GRAPHIC gc=rcs_openGC(display,mainScreen); rcs_closeGC(display,gc); displayScreen(); #endif #ifdef CONSOLE GotoXY(playerX(99),playerY(99)); #endif Delay(1); for (i=0;i<PLAYERS_BONUS6;i++) if (players[i]!=NULL && folded[i]==0) { pHand=players[i]->getHand(0); #ifdef GRAPHIC gc=rcs_openGC(display,mainScreen); pHand->paint(display,mainScreen,gc,0); rcs_closeGC(display,gc); displayScreen(); #endif #ifdef CONSOLE GotoXY(playerX(i),playerY(i)+3); pHand->display(0); #endif pHand->cards[pHand->numCards++]=communityCard; high=pHand->pokerValue(5,0); /* GotoXY(playerX(i),playerY(i)+4); printf(">%ld ",(high>>28)&15); printf("%ld ",(high>>24)&15); printf("%ld ",(high>>20)&15); printf("%ld ",(high>>16)&15); printf("%ld ",(high>>12)&15); printf("%ld ",(high>>8)&15); */ #ifdef CONSOLE GotoXY(playerX(i),playerY(i)+2); #endif if (high>(PK_PAIR|(6<<24)) && high<PK_2_PAIR) { #ifdef GRAPHIC msgBox(playerX(i),playerY(i)-40,120,30,"Pair"); #endif #ifdef CONSOLE Output("*Pair*"); GotoXY(playerX(i),playerY(i)); sprintf(buffer,"%4.0f %4.0f %4.0f ",players[i]->getHandBet(0), players[i]->getHandBet(1),players[i]->getHandBet(2)); Output(buffer); #endif players[i]->winHandBets(0,1); players[i]->winHandBets(1,1); players[i]->winHandBets(2,1); players[i]->loseHandBets(4); players[i]->loseHandBets(3); } else if ((high&(15l<<28))==PK_2_PAIR) { #ifdef GRAPHIC msgBox(playerX(i),playerY(i)-40,120,30,"2 Pair"); #endif #ifdef CONSOLE Output("*2 Pair*"); GotoXY(playerX(i),playerY(i)); sprintf(buffer,"%4.0f %4.0f %4.0f ",players[i]->getHandBet(0)*2, players[i]->getHandBet(1)*2,players[i]->getHandBet(2)*2); Output(buffer); #endif players[i]->winHandBets(0,2); players[i]->winHandBets(1,2); players[i]->winHandBets(2,2); players[i]->loseHandBets(4); players[i]->loseHandBets(3); } else if ((high&(15l<<28))==PK_THREE) { #ifdef GRAPHIC msgBox(playerX(i),playerY(i)-40,120,30,"3 of a kind"); #endif #ifdef CONSOLE Output("*3 of a kind*"); GotoXY(playerX(i),playerY(i)); sprintf(buffer,"%4.0f %4.0f %4.0f ",players[i]->getHandBet(0)*3, players[i]->getHandBet(1)*3,players[i]->getHandBet(2)*3); Output(buffer); #endif players[i]->winHandBets(0,3); players[i]->winHandBets(1,3); players[i]->winHandBets(2,3); players[i]->loseHandBets(4); players[i]->loseHandBets(3); } else if ((high&(15l<<28))==PK_STRAIGHT) { #ifdef GRAPHIC msgBox(playerX(i),playerY(i)-40,120,30,"Straight"); #endif #ifdef CONSOLE Output("*Straight*"); GotoXY(playerX(i),playerY(i)); sprintf(buffer,"%4.0f %4.0f %4.0f ",players[i]->getHandBet(0)*5, players[i]->getHandBet(1)*5,players[i]->getHandBet(2)*5); Output(buffer); #endif players[i]->winHandBets(0,4); players[i]->winHandBets(1,4); players[i]->winHandBets(2,4); players[i]->loseHandBets(4); players[i]->loseHandBets(3); } else if ((high&(15l<<28))==PK_FLUSH) { #ifdef GRAPHIC msgBox(playerX(i),playerY(i)-40,120,30,"Flush"); #endif #ifdef CONSOLE Output("*Flush*"); GotoXY(playerX(i),playerY(i)); sprintf(buffer,"%4.0f %4.0f %4.0f ",players[i]->getHandBet(0)*8, players[i]->getHandBet(1)*8,players[i]->getHandBet(2)*8); Output(buffer); #endif players[i]->winHandBets(0,6); players[i]->winHandBets(1,6); players[i]->winHandBets(2,6); players[i]->loseHandBets(4); players[i]->loseHandBets(3); } else if ((high&(15l<<28))==PK_FULLHOUSE) { #ifdef GRAPHIC msgBox(playerX(i),playerY(i)-40,120,30,"Full House"); #endif #ifdef CONSOLE Output("*Full House*"); GotoXY(playerX(i),playerY(i)); sprintf(buffer,"%4.0f %4.0f %4.0f ",players[i]->getHandBet(0)*11, players[i]->getHandBet(1)*11,players[i]->getHandBet(2)*11); Output(buffer); #endif players[i]->winHandBets(0,20); players[i]->winHandBets(1,20); players[i]->winHandBets(2,20); players[i]->loseHandBets(4); players[i]->loseHandBets(3); } else if ((high&(15l<<28))==PK_FOUR) { #ifdef GRAPHIC msgBox(playerX(i),playerY(i)-40,120,30,"4 of a kind"); #endif #ifdef CONSOLE Output("*4 of a kind*"); GotoXY(playerX(i),playerY(i)); sprintf(buffer,"%4.0f %4.0f %4.0f ",players[i]->getHandBet(0)*50, players[i]->getHandBet(1)*50,players[i]->getHandBet(2)*50); Output(buffer); #endif players[i]->winHandBets(0,50); players[i]->winHandBets(1,50); players[i]->winHandBets(2,50); players[i]->loseHandBets(4); players[i]->loseHandBets(3); } else if ((high&(15l<<28))==PK_STFLUSH) { #ifdef GRAPHIC msgBox(playerX(i),playerY(i)-40,120,30,"Straight Flush"); #endif #ifdef CONSOLE Output("*Straight Flush*"); GotoXY(playerX(i),playerY(i)); sprintf(buffer,"%4.0f %4.0f %4.0f ",players[i]->getHandBet(0)*200, players[i]->getHandBet(1)*200,players[i]->getHandBet(2)*200); Output(buffer); #endif players[i]->winHandBets(0,100); players[i]->winHandBets(1,100); players[i]->winHandBets(2,100); players[i]->loseHandBets(4); players[i]->loseHandBets(3); } else if ((high&(15l<<28))==PK_ROYAL) { #ifdef GRAPHIC msgBox(playerX(i),playerY(i)-40,120,30,"Royal Flush"); #endif #ifdef CONSOLE Output("*Royal Flush*"); GotoXY(playerX(i),playerY(i)); sprintf(buffer,"%4.0f %4.0f %4.0f ",players[i]->getHandBet(0)*1000, players[i]->getHandBet(1)*1000,players[i]->getHandBet(2)*1000); Output(buffer); #endif players[i]->winHandBets(0,1000); players[i]->winHandBets(1,1000); players[i]->winHandBets(2,1000); players[i]->loseHandBets(4); players[i]->loseHandBets(3); } else { #ifdef CONSOLE Output("Game Over"); #endif players[i]->loseHandBets(0); players[i]->loseHandBets(1); players[i]->loseHandBets(2); players[i]->loseHandBets(3); players[i]->loseHandBets(4); players[i]->loseHandBets(5); } #ifdef GRAPHIC clearBets(i); players[i]->paintBets(); displayScreen(); showPlayers(); #endif #ifdef CONSOLE players[i]->showBets(); #endif Delay(1); } Delay(5); }
67598b9a309d261a8f0b418b6ae4cc923c326649
033c1fe882eb426a21b7b45aefae4f0aa59fe57e
/算法导论/CH02/Problem/pb_2_2__冒泡排序.cpp
7cb2e752b8c20910387bd5106d54c934618e9de8
[]
no_license
CN-DXTZ/CLRS
e30b128a8404c0588baf366a06108491a3ee0e5a
dfde7f25766d1cc81c2bc7f9a1d818fcb17d0766
refs/heads/master
2023-04-16T02:57:10.703923
2023-04-11T01:26:10
2023-04-11T01:26:10
196,676,637
0
0
null
null
null
null
UTF-8
C++
false
false
624
cpp
// 冒泡排序 #include <iostream> using namespace std; #define GET_LEN(array) (sizeof(array) / sizeof(array[0])) void bubble_sort(int A[], int length) { for (int i = 0; i < length; i++) { for (int j = length-1; j > i; j--) { if (A[j] < A[j - 1]) { int tmp = A[j]; A[j] = A[j - 1]; A[j - 1] = tmp; } } } } int main() { int A[] = {5, 2, 4, 7, 1, 3, 2, 6}; int length = GET_LEN(A); bubble_sort(A, length); for (int i = 0; i < length; i++) cout << A[i] << endl; return 0; }
b0992e8676f7969b54a97e78e2932b6fda899e65
e1bc05eee7ee3a46af7661cfe16d49710c683984
/lib/resourcemanager/textureload.cpp
8211b480a083f6417c17f45ca8e90aef61675f31
[]
no_license
TheAks999/Visualizer
55c706e327c0685f83f0a96a5ea1578e925c866c
1589aea26eb96ad114fc7287ec67d3d572265e6e
refs/heads/master
2016-09-06T14:14:32.117880
2011-06-16T04:39:33
2011-06-16T04:39:33
1,651,762
0
0
null
null
null
null
UTF-8
C++
false
false
6,670
cpp
/************** *This file may change between projects * ~Shep **************/ #ifndef TEXTURELOAD_CPP #define TEXTURELOAD_CPP #include "texture.h" #include <qgl.h> #include <GL/glu.h> #include <iostream> enum IMAGE_TYPE { IMG_NONE, IMG_TIFF, IMG_PNG, IMG_TGA, IMG_BMP }; IMAGE_TYPE getImageType(const QString & path) { if ( path.endsWith(".tif")) return IMG_TIFF; if ( path.endsWith(".png")) return IMG_PNG; if ( path.endsWith(".tga")) return IMG_TGA; if ( path.endsWith(".bmp")) return IMG_BMP; return IMG_NONE; } bool ResTexture::load( const QImage& img ) { QImage fixed( img.width(), img.height(), QImage::Format_ARGB32 ); QPainter painter(&fixed); painter.setCompositionMode(QPainter::CompositionMode_Source); painter.fillRect( fixed.rect(), Qt::transparent ); painter.setCompositionMode(QPainter::CompositionMode_SourceOver); painter.drawImage( 0, 0, img ); painter.end(); QImage texture = QGLWidget::convertToGLFormat( fixed ); glEnable( GL_TEXTURE ); glEnable( GL_TEXTURE_2D ); glGenTextures( 1, &texId ); glBindTexture( GL_TEXTURE_2D, texId ); glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR ); glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR ); glTexImage2D( GL_TEXTURE_2D, 0, 4, texture.width(), texture.height(), 0, GL_RGBA, GL_UNSIGNED_BYTE, texture.bits() ); return false; } #include <iostream> using namespace std; bool ResTexture::load( const std::string & path ) { glEnable( GL_TEXTURE ); glEnable( GL_TEXTURE_2D ); switch (getImageType(path.c_str())) { case IMG_TIFF: loadTIFF(path.c_str(),texId,texture); break; case IMG_PNG: loadPNG(path.c_str(),texId,texture); break; case IMG_TGA: loadTGA(path.c_str(),texId,texture); break; case IMG_BMP: loadBMP(path.c_str(),texId,texture); default: return false; } return true; } bool loadTIFF(const QString & path, unsigned int & texId, QImage & texture) { QImage buffer; if (!buffer.load( path )) { std::cout << "Load Texture Error: TIFF File would not load\n"; std::cout << "File: " << qPrintable(path) << std::endl; return false; } QImage fixed( buffer.width(), buffer.height(), QImage::Format_ARGB32 ); QPainter painter(&fixed); painter.setCompositionMode(QPainter::CompositionMode_Source); painter.fillRect( fixed.rect(), Qt::transparent ); painter.setCompositionMode(QPainter::CompositionMode_SourceOver); painter.drawImage( 0, 0, buffer ); painter.end(); texture = QGLWidget::convertToGLFormat( fixed ); glGenTextures( 1, &texId ); glBindTexture( GL_TEXTURE_2D, texId ); // glTexParameteri(GL_TEXTURE_2D, GL_GENERATE_MIPMAP, GL_TRUE); glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR ); glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexImage2D( GL_TEXTURE_2D, 0, 4, texture.width(), texture.height(), 0, GL_RGBA, GL_UNSIGNED_BYTE, texture.bits() ); //gluBuild2DMipmaps( GL_TEXTURE_2D, GL_RGBA, texture.width(),texture.height(), GL_RGBA, GL_UNSIGNED_BYTE, texture.bits() ); return true; } bool loadPNG(const QString & path, unsigned int & texId, QImage & texture) { QImage buffer; if (!buffer.load( path )) { std::cout << "Load Texture Error: PNG File would not load\n"; std::cout << "File: " << qPrintable(path) << std::endl; return false; } QImage fixed( buffer.width(), buffer.height(), QImage::Format_ARGB32 ); QPainter painter(&fixed); painter.setCompositionMode(QPainter::CompositionMode_Source); painter.fillRect( fixed.rect(), Qt::transparent ); painter.setCompositionMode(QPainter::CompositionMode_SourceOver); painter.drawImage( 0, 0, buffer ); painter.end(); texture = QGLWidget::convertToGLFormat( fixed ); glGenTextures( 1, &texId ); glBindTexture( GL_TEXTURE_2D, texId ); //glTexParameteri(GL_TEXTURE_2D, GL_GENERATE_MIPMAP, GL_TRUE); glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR ); glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexImage2D( GL_TEXTURE_2D, 0, 4, texture.width(), texture.height(), 0, GL_RGBA, GL_UNSIGNED_BYTE, texture.bits() ); //gluBuild2DMipmaps( GL_TEXTURE_2D, GL_RGBA, texture.width(),texture.height(), GL_RGBA, GL_UNSIGNED_BYTE, texture.bits() ); return true; } bool loadTGA(const QString & path, unsigned int & texId, QImage & texture) { QImage buffer; if (!buffer.load( path )) { std::cout << "Load Texture Error: TGA File would not load\n"; std::cout << "File: " << qPrintable(path) << std::endl; return false; } QImage fixed( buffer.width(), buffer.height(), QImage::Format_ARGB32 ); QPainter painter(&fixed); painter.setCompositionMode(QPainter::CompositionMode_Source); painter.fillRect( fixed.rect(), Qt::transparent ); painter.setCompositionMode(QPainter::CompositionMode_SourceOver); painter.drawImage( 0, 0, buffer ); painter.end(); texture = QGLWidget::convertToGLFormat( fixed ); glGenTextures( 1, &texId ); glBindTexture( GL_TEXTURE_2D, texId ); // glTexParameteri(GL_TEXTURE_2D, GL_GENERATE_MIPMAP, GL_TRUE); glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR ); glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexImage2D( GL_TEXTURE_2D, 0, 4, texture.width(), texture.height(), 0, GL_RGBA, GL_UNSIGNED_BYTE, texture.bits() ); //gluBuild2DMipmaps( GL_TEXTURE_2D, GL_RGBA, texture.width(),texture.height(), GL_RGBA, GL_UNSIGNED_BYTE, texture.bits() ); return true; } bool loadBMP(const QString & path, unsigned int & texId, QImage & texture) { QImage buffer; if (!buffer.load( path )) { std::cout << "Load Texture Error: BMP File would not load\n"; std::cout << "File: " << qPrintable(path) << std::endl; return false; } QImage fixed( buffer.width(), buffer.height(), QImage::Format_ARGB32 ); QPainter painter(&fixed); painter.setCompositionMode(QPainter::CompositionMode_Source); painter.fillRect( fixed.rect(), Qt::transparent ); painter.setCompositionMode(QPainter::CompositionMode_SourceOver); painter.drawImage( 0, 0, buffer ); painter.end(); texture = QGLWidget::convertToGLFormat( fixed ); glGenTextures( 1, &texId ); glBindTexture( GL_TEXTURE_2D, texId ); // glTexParameteri(GL_TEXTURE_2D, GL_GENERATE_MIPMAP, GL_TRUE); glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR ); glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexImage2D( GL_TEXTURE_2D, 0, 4, texture.width(), texture.height(), 0, GL_RGBA, GL_UNSIGNED_BYTE, texture.bits() ); //gluBuild2DMipmaps( GL_TEXTURE_2D, GL_RGBA, texture.width(),texture.height(), GL_RGBA, GL_UNSIGNED_BYTE, texture.bits() ); return true; } #endif
561fb5d6db284b75fd87e7d55d3a8e486f77f4ad
5d62cdda6593f2d14957997b4bf2b10e9e9ed717
/Demo/src/SmokeEffect.hpp
9d7f4477aa201376afb42d5ad60cdf08549058c2
[]
no_license
luoxz-ai/KetrazmEngine
d2daf6e66f090133075316c4c43bc14b1fd8d400
bc02d7627c409da7b06aa0a4d743d0b9d32d94e1
refs/heads/master
2021-05-30T21:37:04.887960
2015-09-02T21:08:44
2015-09-02T21:08:44
null
0
0
null
null
null
null
UTF-8
C++
false
false
755
hpp
#ifndef SMOKEEFFECT_HEADER #define SMOKEEFFECT_HEADER #include <Engine/Audio/Sound.hpp> #include <Engine/Graphics/ParticlesHandler.hpp> using namespace Engine; class SmokeEffect { private: std::shared_ptr<Graphics::ShaderProgram> _physicsProgram; std::shared_ptr<Graphics::ShaderProgram> _displayProgram; std::shared_ptr<Graphics::ParticlesHandler> _particlesHandler; std::shared_ptr<Audio::Sound> _sound; public: SmokeEffect(void); ~SmokeEffect(void); void init(const glm::vec3 &position, GLuint numParticles); void setPosition(const glm::vec3 &pos); const std::shared_ptr<Graphics::ParticlesHandler> &getParticlesHandler(void) const; const std::shared_ptr<Audio::Sound> &getSound(void) const; void updateParticles(void) const; }; #endif
cfa8e23bd7e65a2a113bf00228380ea04a99a037
3b1c7561c8d3b9452fc0cdefe299b208e0db1853
/src/shaders/SkTransformShader.h
4c6bcd28ab9f81ea7ba32a5ad1c5229767444e21
[ "BSD-3-Clause" ]
permissive
NearTox/Skia
dee04fc980bd40c1861c424b5643e7873f656b01
4d0cd2b6deca44eb2255651c4f04396963688761
refs/heads/master
2022-12-24T02:01:41.138176
2022-08-27T14:32:37
2022-08-27T14:32:37
153,816,056
0
0
BSD-3-Clause
2022-12-13T23:42:44
2018-10-19T17:05:47
C++
UTF-8
C++
false
false
1,809
h
/* * Copyright 2021 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #ifndef SkTextCoordShader_DEFINED #define SkTextCoordShader_DEFINED #include "src/core/SkVM.h" #include "src/shaders/SkShaderBase.h" // SkTransformShader allows the transform used by the shader to change without regenerating the // jitted code. This supports the drawVertices call to change the mapping as the texture // coordinates associated with each vertex change with each new triangle. class SkTransformShader : public SkUpdatableShader { public: explicit SkTransformShader(const SkShaderBase& shader); // Adds instructions to use the mapping stored in the uniforms represented by fMatrix. After // generating a new skvm::Coord, it passes the mapped coordinates to fShader's onProgram // along with the identity matrix. skvm::Color onProgram( skvm::Builder* b, skvm::Coord device, skvm::Coord local, skvm::Color color, const SkMatrixProvider& matrices, const SkMatrix* localM, const SkColorInfo& dst, skvm::Uniforms* uniforms, SkArenaAlloc* alloc) const override; // Add code to calculate a new coordinate given local using the mapping in fMatrix. skvm::Coord applyMatrix( skvm::Builder* b, const SkMatrix& matrix, skvm::Coord local, skvm::Uniforms* uniforms) const; void appendMatrix(const SkMatrix& matrix, SkRasterPipeline* p) const; // Change the values represented by the uniforms in fMatrix. bool update(const SkMatrix& ctm) const override; bool onAppendStages(const SkStageRec& rec) const override; private: const SkShaderBase& fShader; mutable SkScalar fMatrixStorage[9]; mutable skvm::Uniform fMatrix; mutable bool fProcessingAsPerspective{false}; }; #endif // SkTextCoordShader_DEFINED
20d49af522c7316cf4e2fadd99d6b65794be1392
554e6b73ed500172abe5fdef08fbc7caf4089f78
/Cpp/Practice/insertionSort.cpp
25b69261536a3ddcb24e182e10c1893819d54e8e
[]
no_license
Shandilier/Competitive-Programming-1
e65388adff421398d803b746635597b2fa5a53c2
c9d66f472aee2fd1fbd3e934e3efb2230dbeebd6
refs/heads/main
2023-06-25T09:33:46.317893
2021-07-28T03:06:16
2021-07-28T03:06:16
385,301,682
0
0
null
null
null
null
UTF-8
C++
false
false
454
cpp
#include<bits/stdc++.h> #define ll long long int using namespace std; int main() { ll n; cin>>n; ll arr[n]; for(ll i=0;i<n;i++) cin>>arr[i]; ll key; ll j; for(ll i=0;i<n;i++) { key = arr[i]; j=i-1; while(j>=0 && arr[j]>=key) { arr[j+1] = arr[j]; j--; } arr[j+1]=key; } for(ll i=0;i<n;i++) cout<<arr[i]<<" "; cout<<endl; }
ab5774960c8f3def583b2bf7bc2097ec6772edeb
115cd4d9eb0916772fa5622693a367663d5946f4
/cpp-HSDS/include/hsds/rank-index.hpp
50e807e9c63a55166eec5350cad54bbac63c4ad0
[ "MIT" ]
permissive
jasonjin22/BWA177
287e8704c5bf1f3edceb3ad8c118531917e155ac
a23542cc03802141f33382eafbd222fa0b219c6d
refs/heads/master
2020-05-17T10:30:56.696782
2019-05-16T15:15:24
2019-05-16T15:15:24
183,659,247
0
0
null
null
null
null
UTF-8
C++
false
false
4,192
hpp
/** * @file rank-index.hpp * @brief Implementation of RankIndex class * @author Hideaki Ohno */ #if !defined(HSDS_RANK_INDEX_H_) #define HSDS_RANK_INDEX_H_ #if !defined(_MSC_VER) #include <stdint.h> #endif // !defined(_MSC_VER) /** * @namespace hsds */ namespace hsds { /** * @class RankIndex * * @brief Index structure for rank operation. */ class RankIndex { public: /** * @brief Constructor */ RankIndex() : abs_(0), rel_(0) { } /** * @brief Destructor */ ~RankIndex() { } /** * @brief Setter method for absolute rank value. * * @param[in] value Absolute value of rank. */ void set_abs(uint32_t value) { abs_ = value; } /** * @brief Setter method for relative rank value at 1st block. * * @param[in] value Relative rank value. */ void set_rel1(uint64_t value) { rel_ = ((rel_ & ~0x7FULL) | (value & 0x7FULL)); } /** * @brief Setter method for relative rank value at 2nd block. * * @param[in] value Relative rank value. */ void set_rel2(uint64_t value) { rel_ = ((rel_ & ~(0xFFULL << 7)) | (value & 0xFFULL) << 7); } /** * @brief Setter method for relative rank value at 3rd block. * * @param[in] value Relative rank value. */ void set_rel3(uint64_t value) { rel_ = ((rel_ & ~(0xFFULL << 15)) | (value & 0xFFULL) << 15); } /** * @brief Setter method for relative rank value at 4th block. * * @param[in] value Relative rank value. */ void set_rel4(uint64_t value) { rel_ = ((rel_ & ~(0x1FFULL << 23)) | (value & 0x1FFULL) << 23); } /** * @brief Setter method for relative rank value at 5th block. * * @param[in] value Relative rank value. */ void set_rel5(uint64_t value) { rel_ = ((rel_ & ~(0x1FFULL << 32)) | (value & 0x1FFULL) << 32); } /** * @brief Setter method for relative rank value at 6th block. * * @param[in] value Relative rank value. */ void set_rel6(uint64_t value) { rel_ = ((rel_ & ~(0x1FFULL << 41)) | (value & 0x1FFULL) << 41); } /** * @brief Setter method for relative rank value at 7th block. * * @param[in] value Relative rank value. */ void set_rel7(uint64_t value) { rel_ = ((rel_ & ~(0x1FFULL << 50)) | (value & 0x1FFULL) << 50); } /** * @brief Getter method for absolute rank value. * * @return Absolute rank value. */ uint64_t abs() const { return abs_; } /** * @brief Getter method for relative value at 1st block. * * @return Relative value at 1st block. */ uint64_t rel1() const { return rel_ & 0x7FULL; } /** * @brief Getter method for relative value at 2nd block. * * @return Relative value at 1st block. */ uint64_t rel2() const { return (rel_ >> 7) & 0xFFULL; } /** * @brief Getter method for relative value at 3rd block. * * @return Relative value at 1st block. */ uint64_t rel3() const { return (rel_ >> 15) & 0xFFULL; } /** * @brief Getter method for relative value at 4th block. * * @return Relative value at 1st block. */ uint64_t rel4() const { return (rel_ >> 23) & 0x1FFULL; } /** * @brief Getter method for relative value at 5th block. * * @return Relative value at 1st block. */ uint64_t rel5() const { return (rel_ >> 32) & 0x1FFULL; } /** * @brief Getter method for relative value at 6th block. * * @return Relative value at 1st block. */ uint64_t rel6() const { return (rel_ >> 41) & 0x1FFULL; } /** * @brief Getter method for relative value at 7th block. * * @return Relative value at 1st block. */ uint64_t rel7() const { return (rel_ >> 50) & 0x1FFULL; } private: uint64_t abs_; ///< Absolute rank value uint64_t rel_; ///< Relative rank value container }; } #endif /* !defined(HSDS_RANK_INDEX_H_) */
8e44ecf6b779231c8bdab6a97bff52e9b160b933
be30e126df12d9ac6087ab8f82101c6b932121c8
/sdk/CPed.cpp
19f8ca3cce7ec415bb9aa8654dad04cd6a870235
[]
no_license
ArnCarveris/gta-sa-plugin-sdk
fc53265bbce06de9276ad2a289e50505aaea2d52
f64548b0f588856d2da6100cd1c69a5880f89fd2
refs/heads/master
2020-05-20T15:46:06.287895
2014-02-23T14:07:29
2014-02-23T14:07:29
34,955,493
1
0
null
null
null
null
UTF-8
C++
false
false
1,066
cpp
#include "CPed.h" NOINLINE CPed::CPed(ePedType type) { PREPARE_FOR_REDIRECTION(); //((void (__thiscall *)(CPed *, ePedType))0x5E8030)(this, type); } NOINLINE CPed::~CPed() { PREPARE_FOR_REDIRECTION(); //((void (__thiscall *)(CPed *))0x5E8620)(this); } void *CPed::operator new(unsigned int size) { return ((void *(__cdecl *)(unsigned int))0x5E4720)(size); } void CPed::operator delete(void *object) { ((void (__cdecl *)(void *))0x5E4760)(object); } void CPed::SetMoveAnim() { ((void (__thiscall *)(CPed *))this->vtable[23])(this); } bool CPed::Save() { return ((bool (__thiscall *)(CPed *))this->vtable[24])(this); } bool CPed::Load() { return ((bool (__thiscall *)(CPed *))this->vtable[25])(this); } void CPed::RemoveWeaponAnims(int weaponSlot, float blenDelta) { ((void (__thiscall *)(CPed *, int, float))0x5F0250)(this, weaponSlot, blenDelta); } unsigned char CPed::GetWeaponSkill(eWeaponType weaponType) { return ((unsigned char (__thiscall *)(CPed *, eWeaponType))0x5E3B60)(this, weaponType); }
[ "[email protected]@a08e2604-8956-8f2e-fb63-2a67f058b60e" ]
[email protected]@a08e2604-8956-8f2e-fb63-2a67f058b60e
515772bce22aad18260016de1ba2694f90d85119
2b54f128becb618435b1c1eaaae84608ecbcc594
/剔除A串中B串的字符.cpp
93d72d2072cb5997b879dd953ff3e51f4c765ad9
[]
no_license
waten1992/Interview_Questions_Collections
b4790c7da05f78016b60ee4ec1e71058e919ab71
ccae4a12ae2745b36a4f0def353d0e12bd75b2f3
refs/heads/master
2020-05-27T17:40:37.568490
2015-03-19T14:25:00
2015-03-19T14:25:00
25,059,705
0
0
null
null
null
null
UTF-8
C++
false
false
2,408
cpp
/* --描述:A 字符串 “hello world” , B 字符串 "er" ,默认都是小写字母 , 要求写一个函数在A中除去B字符,返回A --INPUT: hello world , er --OUTPUT:hllowold --要求空间复杂度为O(1),时间复杂度越低越好; ----方法:1-先对A HASH 到 一个临时int变量check中,相应位置1 ----------2-在对B HASH 的相应的位和check相与 ,把A置1的清零 ----------3-扫描A串 同时HASH 和check相与,判断是否为零,若是直接跳过. 若不是则赋值给一个临时串保存; ----------4-把A串的指针,指向临时串。同时return A串的指针; */ #include <iostream> using namespace std; void Print_Binary_Num(int Num) //输出二进制 , 按照小端序列输出 { int i = 32 ; while(i) { cout<<(Num&0X1); //总是输出第一个数 Num = Num>>1; //不断的右移 i--; if (i%4 == 0) cout<<'\t'; } } char * Handler(char *s1 , char *s2) { int i = 0 , Tmp = 0 , check = 0 , index = 0; char *Tmp_String = new char [10]; //临时数组 while (s1[i]) //HASH --- A 相应的位置1 { Tmp = (s1[i] - 'a') % 32 ; // HASH if (Tmp >= 0 && Tmp <=25) //排出其他字符 check = (1<<Tmp)|check; i++; } i = 0; //再次初始化 while (s2[i]) //HASH ---B ----把A 和 B中都存在的字符 都置0 { Tmp = (s2[i] - 'a') % 32 ; if (Tmp >= 0 && Tmp <=25) //排出其他字符 check = (~(1<<Tmp))&check;//---1 两种方式都可以,都是把相应的为清零 ; 推荐用第一种 //check = (1<<Tmp)^check; //----2 但是第二种有副作用,假若A不存在,而B存在; // 则check的相应位被置1,不过在本例中,没有影响,后面是相与 i++; } i = 0; //第3次初始化 while(s1[i]) //再次 扫描A 和check 位相与 。赋值给临时数组 { Tmp = (s1[i] - 'a') % 32 ; if ((1<<Tmp)&check) { Tmp_String[index] = s1[i]; index++; } i++; } s1 = Tmp_String; return s1; } int main() { char *s1 , *s2 ; s1 = "hello world " ; s2 = "re"; s1 = Handler(s1 , s2); cout<<s1<<endl; return 0; } /* THE Answer as follows----> hllowold Process returned 0 (0x0) execution time : 0.029 s Press any key to continue. */
dab92defd11f838f5543c8a92476c4aaa5e02d31
09403b9998277567edb91e237ef9a29e5265a279
/src/openlcb/BroadcastTimeDefs.hxx
f7a9d5be611f701c290dfccc127da0e97813024f
[ "BSD-2-Clause" ]
permissive
bakerstu/openmrn
9a07d3a72fad1d0447c1e59acfeeff61c9c76c5a
ca333ec4b35e1ffc1323aa62936db0bd043ef6df
refs/heads/master
2023-08-31T12:11:46.046315
2023-08-31T00:53:31
2023-08-31T00:54:05
6,500,256
45
42
BSD-2-Clause
2023-09-10T10:39:52
2012-11-02T02:20:12
C++
UTF-8
C++
false
false
15,520
hxx
/** @copyright * Copyright (c) 2018, Stuart W. Baker * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * @file BroadcastTimeDefs.hxx * * Static definitions for implementations of the OpenLCB Broadcast Time * Protocol. * * @author Stuart W. Baker * @date 14 October 2018 */ #ifndef _OPENLCB_BROADCASTTIMEDEFS_HXX_ #define _OPENLCB_BROADCASTTIMEDEFS_HXX_ #include <time.h> #include "openlcb/Defs.hxx" namespace openlcb { /// Static constants and helper functions for Broadcast Time Protocol. struct BroadcastTimeDefs { /// Unique identifier for the Default Fast Clock static constexpr NodeID DEFAULT_FAST_CLOCK_ID = 0x010100000100ULL; /// Unique identifier for the Default Real-Time Clock static constexpr NodeID DEFAULT_REALTIME_CLOCK_ID = 0x010100000101ULL; /// Unique identifier for Alternate Clock 1 static constexpr NodeID ALTERNATE_CLOCK_1_ID = 0x010100000102ULL; /// Unique identifier for Alternate Clock 2 static constexpr NodeID ALTERNATE_CLOCK_2_ID = 0x010100000103ULL; /// Type of event enum EventType { REPORT_TIME = 0, ///< report time event REPORT_DATE, ///< report date event REPORT_YEAR, ///< report year event REPORT_RATE, ///< report rate event SET_TIME, ///< set time event SET_DATE, ///< set date event SET_YEAR, ///< set year event SET_RATE, ///< set rate event QUERY, ///< query event STOP, ///< stop clock event START, ///< start clock event DATE_ROLLOVER, ///< date rollover event UNDEFINED, ///< undefined event }; enum { EVENT_ID_MASK = 0xFFFFFFFFFFFF0000, ///< Unique ID mask EVENT_SUFFIX_MASK = 0x000000000000FFFF, ///< suffix mask EVENT_TYPE_MASK = 0x000000000000F000, ///< type mask EVENT_HOURS_MASK = 0x0000000000001F00, ///< hours mask EVENT_MINUTES_MASK = 0x00000000000000FF, ///< minutes mask EVENT_MONTH_MASK = 0x0000000000000F00, ///< month mask EVENT_DAY_MASK = 0x00000000000000FF, ///< day mask EVENT_YEAR_MASK = 0x0000000000000FFF, ///< rate mask EVENT_RATE_MASK = 0x0000000000000FFF, ///< rate mask EVENT_HOURS_SHIFT = 8, ///< hours mask EVENT_MINUTES_SHIFT = 0, ///< minutes mask EVENT_MONTH_SHIFT = 8, ///< month mask EVENT_DAY_SHIFT = 0, ///< day mask EVENT_YEAR_SHIFT = 0, ///< year mask EVENT_RATE_SHIFT = 0, ///< rate mask TIME_EVENT_BASE_SUFFIX = 0x0000, ///< time event base suffix DATE_EVENT_BASE_SUFFIX = 0x2000, ///< date event base suffix YEAR_EVENT_BASE_SUFFIX = 0x3000, ///< year event base suffix RATE_EVENT_BASE_SUFFIX = 0x4000, ///< rate event base suffix QUERY_EVENT_SUFFIX = 0xF000, ///< query event suffix value STOP_EVENT_SUFFIX = 0xF001, ///< stop clock event suffix value START_EVENT_SUFFIX = 0xF002, ///< start clock event suffix value DATE_ROLLOVER_EVENT_SUFFIX = 0xF003, ///< rollover the date suffix value EVENT_SET_SUFFIX_MASK = 0x8000, ///< suffix max for setting a property }; enum { SUNDAY = 0, ///< Day of the week value Sunday MONDAY, ///< Day of the week value Monday TUESDAY, ///< Day of the week value Tuesday WEDNESDAY, ///< Day of the week value Wednesday THURSDAY, ///< Day of the week value Thursday FRIDAY, ///< Day of the week value Friday SATURDAY, ///< Day of the week value Saturday }; /// Get the EventTuype from the event suffix number. /// @param suffix 16-bit event suffix /// @return the EventType static EventType get_event_type(uint16_t suffix) { switch (suffix & EVENT_TYPE_MASK) { case 0x0000: case 0x1000: if (valid_time(suffix)) { return REPORT_TIME; } break; case 0x2000: if (valid_date(suffix)) { return REPORT_DATE; } break; case 0x3000: return REPORT_YEAR; case 0x4000: return REPORT_RATE; case 0x8000: case 0x9000: if (valid_time(suffix)) { return SET_TIME; } break; case 0xA000: if (valid_date(suffix)) { return SET_DATE; } break; case 0xB000: return SET_YEAR; case 0xC000: return SET_RATE; case 0xF000: switch (suffix & 0xFFF) { case 0x000: return QUERY; case 0x001: return STOP; case 0x002: return START; case 0x003: return DATE_ROLLOVER; default: break; } default: break; } return UNDEFINED; } /// Validate that this is a supported time event. Assume that the four most /// significant bits have been seperately validated. /// @return true of valid, else false static bool valid_time(uint16_t suffix) { return (((suffix & EVENT_HOURS_MASK) >> EVENT_HOURS_SHIFT) <= 23 && ((suffix & EVENT_MINUTES_MASK) >> EVENT_MINUTES_SHIFT) <= 59); } /// Validate that this is a supported date event. Assume that the four most /// significant bits have been seperately validated. /// @return true of valid, else false static bool valid_date(uint16_t suffix) { return (((suffix & EVENT_MONTH_MASK) >> EVENT_MONTH_SHIFT) >= 1 && ((suffix & EVENT_MONTH_MASK) >> EVENT_MONTH_SHIFT) <= 12 && ((suffix & EVENT_DAY_MASK) >> EVENT_DAY_SHIFT) >= 1 && ((suffix & EVENT_DAY_MASK) >> EVENT_DAY_SHIFT) <= 31); } /// Get the minutes from the event. To save logic, the event is assumed to /// be of type REPORT_TIME. /// @return -1 on error, else minute static int event_to_min(uint64_t event) { unsigned min = (event & EVENT_MINUTES_MASK) >> EVENT_MINUTES_SHIFT; if (min <= 59) { return min; } return -1; } /// Get the hour from the event. To save logic, the event is assumed to /// be of type REPORT_TIME. /// @return -1 on error, else hour static int event_to_hour(uint64_t event) { unsigned hour = (event & EVENT_HOURS_MASK) >> EVENT_HOURS_SHIFT; if (hour <= 23) { return hour; } return -1; } /// Get the day from the event. To save logic, the event is assumed to /// be of type REPORT_DATE. /// @return -1 on error, else day static int event_to_day(uint64_t event) { unsigned day = (event & EVENT_DAY_MASK) >> EVENT_DAY_SHIFT; if (day >= 1 && day <= 31) { return day; } return -1; } /// Get the month from the event. To save logic, the event is assumed to /// be of type REPORT_DATE. /// @return -1 on error, else month (January = 1) static int event_to_month(uint64_t event) { unsigned month = (event & EVENT_MONTH_MASK) >> EVENT_MONTH_SHIFT; if (month >= 1 && month <= 12) { return month; } return -1; } /// Get the year from the event. To save logic, the event is assumed to /// be of type REPORT_YEAR. /// @return years past 0AD static int event_to_year(uint64_t event) { return (event & EVENT_YEAR_MASK) >> EVENT_YEAR_SHIFT; } /// Get the rate from the event. To save logic, the event is assumed to /// be of type REPORT_RATE. /// @return signed 12-bit rate value. static int16_t event_to_rate(uint64_t event) { union Rate { uint16_t rate_; int16_t srate_; }; Rate rate; rate.rate_ = (event & EVENT_RATE_MASK) >> EVENT_RATE_SHIFT; if (rate.rate_ & 0x0800) { // sign extend negative value rate.rate_ |= 0xF000; } return rate.srate_; } /// Build an event from hours and minutes. /// @param event_base base event ID of the event pool /// @param hours hours (0 to 23) /// @param minutes minutes (0 to 59) /// @return resulting event ID static uint64_t time_to_event(uint64_t event_base, int hours, int minutes) { HASSERT(minutes >= 0 && minutes <= 59); HASSERT(hours >= 0 && hours <= 23); return event_base + TIME_EVENT_BASE_SUFFIX + (hours << EVENT_HOURS_SHIFT) + (minutes << EVENT_MINUTES_SHIFT); } /// Build an event from month and day. /// @param event_base base event ID of the event pool /// @param month month (1 to 12) /// @param day day of month (1 to 31) /// @return resulting event ID static uint64_t date_to_event(uint64_t event_base, int month, int day) { HASSERT(month >= 1 && month <= 12); HASSERT(day >= 1 && day <= 31); return event_base + DATE_EVENT_BASE_SUFFIX + (month << EVENT_MONTH_SHIFT) + (day << EVENT_DAY_SHIFT); } /// Build an event from year. /// @param event_base base event ID of the event pool /// @param year (0AD to 4095AD) /// @return resulting event ID static uint64_t year_to_event(uint64_t event_base, int year) { HASSERT(year >= 0 && year <= 4095); return event_base + YEAR_EVENT_BASE_SUFFIX + (year << EVENT_YEAR_SHIFT); } /// Build an event from rate. /// @param event_base base event ID of the event pool /// @param year (0AD to 4095AD) /// @return resulting event ID static uint64_t rate_to_event(uint64_t event_base, int16_t rate) { HASSERT(rate >= -2048 && rate < 2048); union Rate { uint16_t rate_; int16_t srate_; }; Rate r; r.srate_ = rate; return event_base + RATE_EVENT_BASE_SUFFIX + ((r.rate_ & EVENT_RATE_MASK) << EVENT_RATE_SHIFT); } /// Convert time in integer hours/minutes to a string ("hh:mm"). /// @param hour hours in integer form (0 to 23) /// @param min minutes in integer form (0 to 59) /// @return time represented in the form of a string ("hh:mm") static std::string time_to_string(int hour, int min); /// Convert rate in integer rate quarters to a string (float). /// @param rate rate in the form of rate quarters /// @return rate represented in the form of a string (float) static std::string rate_quarters_to_string(int16_t rate); /// Converts a date to a string "Mmm dd, yyyy". /// @param year 0 to 4095 /// @param month 1 to 12 (warning! struct tm has 0 to 11) /// @param day 1 to 31 static std::string date_to_string(int year, int month, int day); /// Convert a string (hh:mm) to hour and minute component integers. /// @param stime time in the form of a string /// @param hour resulting hour integer (0 to 23) /// @param min resulting minute integer (0 to 59) /// @return true on success, else false on fault static bool string_to_time(const std::string &stime, int *hour, int *min); /// Convert a string (float) to rate quarters. /// @param srate rate in the form of a string float /// @return Rate in the form of an int16_t in rate quarters. If a /// conversion error occurs, then the returned value will be 0, /// which is at least a valid rate. static int16_t string_to_rate_quarters(const std::string &srate); /// Converts a (user-provided) string "Mmm dd, yyyy" to date. Verifies that /// the values are in range for OpenLCB and for a real date. /// @param sdate the input string in "Mmm dd, yyyy" format. /// @param year will be filled in with the year (0 to 4095) /// @param month will be filled in with the month (1 to 12) (warning! /// struct tm has 0 to 11) /// @param day will be filled in with the day (1 to 31) /// @return true on success, false on parse error. Note that it is not /// fully specified what is a parse error; certain errors will be corrected /// (e.g. feb 30, 2001 will be fixed to march 2). static bool string_to_date( const std::string &sdate, int *year, int *month, int *day); /// Verifies that a user-provided string parses as time, and canonicalizes /// the string format. Parse errors get turned into "00:00". /// @param stime input-output argument. Input is the user-provided time /// (hh:mm), output is the canonicalized time. /// @return true if the string has changed during canonicalization. static bool canonicalize_time_string(std::string *stime); /// Verifies that a user-provided string parses as rate quarters, and /// canonicalizes the string format. Parse errors get turned into "0.00". /// @param srate input-output argument. Input is user-provided rate, output /// is the canonicalized rate. /// @return true if the string has changed during canonicalization. static bool canonicalize_rate_string(std::string* srate); /// Verifies that a user-provided string parses as date, and canonicalizes /// the string format. Parse errors get turned into "Jan 1, 1970". /// @param sdate input-output argument. Input is user-provided date in "Mmm /// dd, yyyy" format, output is the canonicalized date. /// @return true if the string has changed during canonicalization. static bool canonicalize_date_string(std::string* sdate); }; } // namespace openlcb #endif // _OPENLCB_BROADCASTTIMEDEFS_HXX_
ed4e1db9cc3e46558fa65a6a20bdaf3b04bff57e
caf6ae544fce3b332b40a03462c0646a32c913e1
/master/qtcplus/client/SWGStandardInitiateLoginResultData.cpp
03d47c7c24ee00f55370ce08e15926776b9168db
[ "Apache-2.0" ]
permissive
coinsecure/plugins
827eb0ce03a6a23b4819a618ee47600161bec1c7
ad6f08881020c268b530d5242d9deed8d2ec84de
refs/heads/master
2020-05-30T07:17:56.255709
2016-11-27T22:22:23
2016-11-27T22:22:23
63,496,663
3
5
null
null
null
null
UTF-8
C++
false
false
4,677
cpp
/** * Coinsecure Api Documentation * To generate an API key, please visit <a href='https://coinsecure.in/api' target='_new' class='homeapi'>https://coinsecure.in/api</a>.<br>Guidelines for use can be accessed at <a href='https://api.coinsecure.in/v1/guidelines'>https://api.coinsecure.in/v1/guidelines</a>.<br>Programming Language Libraries for use can be accessed at <a href='https://api.coinsecure.in/v1/code-libraries'>https://api.coinsecure.in/v1/code-libraries</a>. * * OpenAPI spec version: beta * * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. * * 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 "SWGStandardInitiateLoginResultData.h" #include "SWGHelpers.h" #include <QJsonDocument> #include <QJsonArray> #include <QObject> #include <QDebug> namespace Swagger { SWGStandardInitiateLoginResultData::SWGStandardInitiateLoginResultData(QString* json) { init(); this->fromJson(*json); } SWGStandardInitiateLoginResultData::SWGStandardInitiateLoginResultData() { init(); } SWGStandardInitiateLoginResultData::~SWGStandardInitiateLoginResultData() { this->cleanup(); } void SWGStandardInitiateLoginResultData::init() { success = false; message = new SWGSuccessInitiateLoginResponse(); method = new QString(""); title = new QString(""); time = NULL; } void SWGStandardInitiateLoginResultData::cleanup() { if(message != nullptr) { delete message; } if(method != nullptr) { delete method; } if(title != nullptr) { delete title; } if(time != nullptr) { delete time; } } SWGStandardInitiateLoginResultData* SWGStandardInitiateLoginResultData::fromJson(QString &json) { QByteArray array (json.toStdString().c_str()); QJsonDocument doc = QJsonDocument::fromJson(array); QJsonObject jsonObject = doc.object(); this->fromJsonObject(jsonObject); return this; } void SWGStandardInitiateLoginResultData::fromJsonObject(QJsonObject &pJson) { ::Swagger::setValue(&success, pJson["success"], "bool", ""); ::Swagger::setValue(&message, pJson["message"], "SWGSuccessInitiateLoginResponse", "SWGSuccessInitiateLoginResponse"); ::Swagger::setValue(&method, pJson["method"], "QString", "QString"); ::Swagger::setValue(&title, pJson["title"], "QString", "QString"); ::Swagger::setValue(&time, pJson["time"], "QDateTime", "QDateTime"); } QString SWGStandardInitiateLoginResultData::asJson () { QJsonObject* obj = this->asJsonObject(); QJsonDocument doc(*obj); QByteArray bytes = doc.toJson(); return QString(bytes); } QJsonObject* SWGStandardInitiateLoginResultData::asJsonObject() { QJsonObject* obj = new QJsonObject(); obj->insert("success", QJsonValue(success)); toJsonValue(QString("message"), message, obj, QString("SWGSuccessInitiateLoginResponse")); toJsonValue(QString("method"), method, obj, QString("QString")); toJsonValue(QString("title"), title, obj, QString("QString")); toJsonValue(QString("time"), time, obj, QString("QDateTime")); return obj; } bool SWGStandardInitiateLoginResultData::getSuccess() { return success; } void SWGStandardInitiateLoginResultData::setSuccess(bool success) { this->success = success; } SWGSuccessInitiateLoginResponse* SWGStandardInitiateLoginResultData::getMessage() { return message; } void SWGStandardInitiateLoginResultData::setMessage(SWGSuccessInitiateLoginResponse* message) { this->message = message; } QString* SWGStandardInitiateLoginResultData::getMethod() { return method; } void SWGStandardInitiateLoginResultData::setMethod(QString* method) { this->method = method; } QString* SWGStandardInitiateLoginResultData::getTitle() { return title; } void SWGStandardInitiateLoginResultData::setTitle(QString* title) { this->title = title; } QDateTime* SWGStandardInitiateLoginResultData::getTime() { return time; } void SWGStandardInitiateLoginResultData::setTime(QDateTime* time) { this->time = time; } } /* namespace Swagger */
302bc5ab25ac8330a4e74117432545491f959879
a3a8de60a97adc6279adbac65656f9fec5f2e8e6
/2017011507-陈昱宏-源代码/SearchOrder.h
3cb50f4674c961aeed4119f5b545d9e323f8bed2
[]
no_license
THU-Yu/Hotel-Booking-Application
5dec346f905848f19fb17f9ba7233d19304f8865
3abcc2e7c23a16ab0af94720f7f8a85b0e65549e
refs/heads/master
2021-05-18T08:18:00.872611
2020-03-30T03:44:04
2020-03-30T03:44:04
251,193,613
1
0
null
null
null
null
UTF-8
C++
false
false
1,505
h
#ifndef SEARCHORDER_H #define SEARCHORDER_H #include "normaluser.h" #include "hotaluser.h" #include "platformuser.h" #include "hotalorder.h" #include "orderdetail.h" #include "PinJiaMessage.h" #include "hotal.h" #include <QWidget> class QTableWidget; class QTableWidgetItem; class SearchOrder:public QWidget { Q_OBJECT public: SearchOrder(Hotal *hotalhead,Message *Messagehead, PinJiaMessage *pinjiahead,Room *roomhead, HotalOrder *Orderhead,NormalUser *MainAccount1,HotalUser *MainAccount2,PlatformUser *MainAccount3,QWidget *parent=0) :Hotalhead(hotalhead),Messagehead(Messagehead),PinJiahead(pinjiahead),Roomhead(roomhead),Orderhead(Orderhead),MainAccount1(MainAccount1),MainAccount2(MainAccount2),MainAccount3(MainAccount3),QWidget(parent){} void changeSearchOrder(NormalUser *Mainaccount1, HotalUser *Mainaccount2, PlatformUser *Mainccount3); void changeTable(NormalUser *Mainaccount1,HotalUser *Mainaccount2,PlatformUser *Mainaccount3); ~SearchOrder(){} signals: void back(); private slots: void ButtonClicked(QTableWidgetItem *item); void CheckCancelOrder(); void Back(); private: QTableWidget *MainTable; Hotal *Hotalhead; HotalOrder *Orderhead; Message *Messagehead; Room *Roomhead; PinJiaMessage *PinJiahead; NormalUser *MainAccount1; HotalUser *MainAccount2; PlatformUser *MainAccount3; OrderDetail *orderdetail; QPushButton *BackButton; QPushButton *CancelOrderButton; }; #endif // SEARCHORDER_H
47f539eb399e8414e29683a7771c0f51d605b728
d0f37e29d49d76f15773f7d48fe3fa5f426de8f0
/cocos2d-x-3.6/cocos/ui/UILayoutComponent.cpp
f33581f2df4aaee6b8b3c9f58b422a57d2cf4160
[ "LicenseRef-scancode-warranty-disclaimer", "Zlib", "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference", "Libpng", "BSD-2-Clause-Views", "FTL", "Apache-2.0", "BSD-2-Clause" ]
permissive
SakuyaPrs/kirikiroid2lite
6898334ccceb5c911662e8062101daab73e15887
ee5890cf5b9714a9348cb6dd8fdbb0a7304c2cbe
refs/heads/master
2022-12-07T08:54:18.618074
2020-09-02T04:17:21
2020-09-02T04:17:21
null
0
0
null
null
null
null
UTF-8
C++
false
false
20,599
cpp
/**************************************************************************** Copyright (c) 2013-2014 Chukong Technologies Inc. http://www.cocos2d-x.org Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ #include "UILayoutComponent.h" #include "2d/CCNode.h" #include "GUIDefine.h" #include "UIHelper.h" NS_CC_BEGIN namespace ui { LayoutComponent::LayoutComponent() :_horizontalEdge(HorizontalEdge::None) , _verticalEdge(VerticalEdge::None_) , _leftMargin(0) , _rightMargin(0) , _bottomMargin(0) , _topMargin(0) , _usingPositionPercentX(false) , _positionPercentX(0) , _usingPositionPercentY(false) , _positionPercentY(0) , _usingStretchWidth(false) , _usingStretchHeight(false) , _percentWidth(0) , _usingPercentWidth(false) , _percentHeight(0) , _usingPercentHeight(false) , _actived(true) , _isPercentOnly(false) { _name = __LAYOUT_COMPONENT_NAME; } LayoutComponent::~LayoutComponent() { } LayoutComponent* LayoutComponent::bindLayoutComponent(Node* node) { LayoutComponent * layout = (LayoutComponent*)node->getComponent(__LAYOUT_COMPONENT_NAME); if (layout != nullptr) return layout; layout = new (std::nothrow) LayoutComponent(); if (layout && layout->init()) { layout->autorelease(); node->addComponent(layout); return layout; } CC_SAFE_DELETE(layout); return nullptr; } bool LayoutComponent::init() { bool ret = true; do { if (!Component::init()) { ret = false; break; } //put layout component initalized code here } while (0); return ret; } Node* LayoutComponent::getOwnerParent() { Node* parent = _owner->getParent(); return parent; } void LayoutComponent::refreshHorizontalMargin() { Node* parent = this->getOwnerParent(); if (parent == nullptr) return; const Point& ownerPoint = _owner->getPosition(); const Point& ownerAnchor = _owner->getAnchorPoint(); const Size& ownerSize = _owner->getContentSize(); const Size& parentSize = parent->getContentSize(); _leftMargin = ownerPoint.x - ownerAnchor.x * ownerSize.width; _rightMargin = parentSize.width - (ownerPoint.x + (1 - ownerAnchor.x) * ownerSize.width); } void LayoutComponent::refreshVerticalMargin() { Node* parent = this->getOwnerParent(); if (parent == nullptr) return; const Point& ownerPoint = _owner->getPosition(); const Point& ownerAnchor = _owner->getAnchorPoint(); const Size& ownerSize = _owner->getContentSize(); const Size& parentSize = parent->getContentSize(); _bottomMargin = ownerPoint.y - ownerAnchor.y * ownerSize.height; _topMargin = parentSize.height - (ownerPoint.y + (1 - ownerAnchor.y) * ownerSize.height); } //OldVersion void LayoutComponent::setUsingPercentContentSize(bool isUsed) { _usingPercentWidth = _usingPercentHeight = isUsed; } bool LayoutComponent::getUsingPercentContentSize()const { return _usingPercentWidth && _usingPercentHeight; } void LayoutComponent::setPercentContentSize(const Vec2 &percent) { this->setPercentWidth(percent.x); this->setPercentHeight(percent.y); } Vec2 LayoutComponent::getPercentContentSize()const { Vec2 vec2=Vec2(_percentWidth,_percentHeight); return vec2; } //Position & Margin const Point& LayoutComponent::getAnchorPosition()const { return _owner->getAnchorPoint(); } void LayoutComponent::setAnchorPosition(const Point& point) { Rect oldRect = _owner->getBoundingBox(); _owner->setAnchorPoint(point); Rect newRect = _owner->getBoundingBox(); float offSetX = oldRect.origin.x - newRect.origin.x; float offSetY = oldRect.origin.y - newRect.origin.y; Point ownerPosition = _owner->getPosition(); ownerPosition.x += offSetX; ownerPosition.y += offSetY; this->setPosition(ownerPosition); } const Point& LayoutComponent::getPosition()const { return _owner->getPosition(); } void LayoutComponent::setPosition(const Point& position) { Node* parent = this->getOwnerParent(); if (parent != nullptr) { Point ownerPoint = position; const Size& parentSize = parent->getContentSize(); if (parentSize.width != 0) _positionPercentX = ownerPoint.x / parentSize.width; else { _positionPercentX = 0; if (_usingPositionPercentX) ownerPoint.x = 0; } if (parentSize.height != 0) _positionPercentY = ownerPoint.y / parentSize.height; else { _positionPercentY = 0; if (_usingPositionPercentY) ownerPoint.y = 0; } _owner->setPosition(ownerPoint); this->refreshHorizontalMargin(); this->refreshVerticalMargin(); } else _owner->setPosition(position); } bool LayoutComponent::isPositionPercentXEnabled()const { return _usingPositionPercentX; } void LayoutComponent::setPositionPercentXEnabled(bool isUsed) { _usingPositionPercentX = isUsed; if (_usingPositionPercentX) { _horizontalEdge = HorizontalEdge::None; } } float LayoutComponent::getPositionPercentX()const { return _positionPercentX; } void LayoutComponent::setPositionPercentX(float percentMargin) { _positionPercentX = percentMargin; Node* parent = this->getOwnerParent(); if (parent != nullptr) { _owner->setPositionX(parent->getContentSize().width * _positionPercentX); this->refreshHorizontalMargin(); } } bool LayoutComponent::isPositionPercentYEnabled()const { return _usingPositionPercentY; } void LayoutComponent::setPositionPercentYEnabled(bool isUsed) { _usingPositionPercentY = isUsed; if (_usingPositionPercentY) { _verticalEdge = VerticalEdge::None_; } } float LayoutComponent::getPositionPercentY()const { return _positionPercentY; } void LayoutComponent::setPositionPercentY(float percentMargin) { _positionPercentY = percentMargin; Node* parent = this->getOwnerParent(); if (parent != nullptr) { _owner->setPositionY(parent->getContentSize().height * _positionPercentY); this->refreshVerticalMargin(); } } LayoutComponent::HorizontalEdge LayoutComponent::getHorizontalEdge()const { return _horizontalEdge; } void LayoutComponent::setHorizontalEdge(HorizontalEdge hEage) { _horizontalEdge = hEage; if (_horizontalEdge != HorizontalEdge::None) { _usingPositionPercentX = false; } Node* parent = this->getOwnerParent(); if (parent != nullptr) { Point ownerPoint = _owner->getPosition(); const Size& parentSize = parent->getContentSize(); if (parentSize.width != 0) _positionPercentX = ownerPoint.x / parentSize.width; else { _positionPercentX = 0; ownerPoint.x = 0; if (_usingPositionPercentX) _owner->setPosition(ownerPoint); } this->refreshHorizontalMargin(); } } LayoutComponent::VerticalEdge LayoutComponent::getVerticalEdge()const { return _verticalEdge; } void LayoutComponent::setVerticalEdge(VerticalEdge vEage) { _verticalEdge = vEage; if (_verticalEdge != VerticalEdge::None_) { _usingPositionPercentY = false; } Node* parent = this->getOwnerParent(); if (parent != nullptr) { Point ownerPoint = _owner->getPosition(); const Size& parentSize = parent->getContentSize(); if (parentSize.height != 0) _positionPercentY = ownerPoint.y / parentSize.height; else { _positionPercentY = 0; ownerPoint.y = 0; if (_usingPositionPercentY) _owner->setPosition(ownerPoint); } this->refreshVerticalMargin(); } } float LayoutComponent::getLeftMargin()const { return _leftMargin; } void LayoutComponent::setLeftMargin(float margin) { _leftMargin = margin; } float LayoutComponent::getRightMargin()const { return _rightMargin; } void LayoutComponent::setRightMargin(float margin) { _rightMargin = margin; } float LayoutComponent::getTopMargin()const { return _topMargin; } void LayoutComponent::setTopMargin(float margin) { _topMargin = margin; } float LayoutComponent::getBottomMargin()const { return _bottomMargin; } void LayoutComponent::setBottomMargin(float margin) { _bottomMargin = margin; } //Size & Percent const Size& LayoutComponent::getSize()const { return this->getOwner()->getContentSize(); } void LayoutComponent::setSize(const Size& size) { Node* parent = this->getOwnerParent(); if (parent != nullptr) { Size ownerSize = size; const Size& parentSize = parent->getContentSize(); if (parentSize.width != 0) _percentWidth = ownerSize.width / parentSize.width; else { _percentWidth = 0; if (_usingPercentWidth) ownerSize.width = 0; } if (parentSize.height != 0) _percentHeight = ownerSize.height / parentSize.height; else { _percentHeight = 0; if (_usingPercentHeight) ownerSize.height = 0; } _owner->setContentSize(ownerSize); this->refreshHorizontalMargin(); this->refreshVerticalMargin(); } else _owner->setContentSize(size); } bool LayoutComponent::isPercentWidthEnabled()const { return _usingPercentWidth; } void LayoutComponent::setPercentWidthEnabled(bool isUsed) { _usingPercentWidth = isUsed; if (_usingPercentWidth) { _usingStretchWidth = false; } } float LayoutComponent::getSizeWidth()const { return _owner->getContentSize().width; } void LayoutComponent::setSizeWidth(float width) { Size ownerSize = _owner->getContentSize(); ownerSize.width = width; Node* parent = this->getOwnerParent(); if (parent != nullptr) { const Size& parentSize = parent->getContentSize(); if (parentSize.width != 0) _percentWidth = ownerSize.width / parentSize.width; else { _percentWidth = 0; if (_usingPercentWidth) ownerSize.width = 0; } _owner->setContentSize(ownerSize); this->refreshHorizontalMargin(); } else _owner->setContentSize(ownerSize); } float LayoutComponent::getPercentWidth()const { return _percentWidth; } void LayoutComponent::setPercentWidth(float percentWidth) { _percentWidth = percentWidth; Node* parent = this->getOwnerParent(); if (parent != nullptr) { Size ownerSize = _owner->getContentSize(); ownerSize.width = parent->getContentSize().width * _percentWidth; _owner->setContentSize(ownerSize); this->refreshHorizontalMargin(); } } bool LayoutComponent::isPercentHeightEnabled()const { return _usingPercentHeight; } void LayoutComponent::setPercentHeightEnabled(bool isUsed) { _usingPercentHeight = isUsed; if (_usingPercentHeight) { _usingStretchHeight = false; } } float LayoutComponent::getSizeHeight()const { return _owner->getContentSize().height; } void LayoutComponent::setSizeHeight(float height) { Size ownerSize = _owner->getContentSize(); ownerSize.height = height; Node* parent = this->getOwnerParent(); if (parent != nullptr) { const Size& parentSize = parent->getContentSize(); if (parentSize.height != 0) _percentHeight = ownerSize.height / parentSize.height; else { _percentHeight = 0; if (_usingPercentHeight) ownerSize.height = 0; } _owner->setContentSize(ownerSize); this->refreshVerticalMargin(); } else _owner->setContentSize(ownerSize); } float LayoutComponent::getPercentHeight()const { return _percentHeight; } void LayoutComponent::setPercentHeight(float percentHeight) { _percentHeight = percentHeight; Node* parent = this->getOwnerParent(); if (parent != nullptr) { Size ownerSize = _owner->getContentSize(); ownerSize.height = parent->getContentSize().height * _percentHeight; _owner->setContentSize(ownerSize); this->refreshVerticalMargin(); } } bool LayoutComponent::isStretchWidthEnabled()const { return _usingStretchWidth; } void LayoutComponent::setStretchWidthEnabled(bool isUsed) { _usingStretchWidth = isUsed; if (_usingStretchWidth) { _usingPercentWidth = false; } } bool LayoutComponent::isStretchHeightEnabled()const { return _usingStretchHeight; } void LayoutComponent::setStretchHeightEnabled(bool isUsed) { _usingStretchHeight = isUsed; if (_usingStretchHeight) { _usingPercentHeight = false; } } void LayoutComponent::refreshLayout() { if (!_actived) return; Node* parent = this->getOwnerParent(); if (parent == nullptr) return; const Size& parentSize = parent->getContentSize(); const Point& ownerAnchor = _owner->getAnchorPoint(); Size ownerSize = _owner->getContentSize(); Point ownerPosition = _owner->getPosition(); switch (this->_horizontalEdge) { case HorizontalEdge::None: if (_usingStretchWidth && !_isPercentOnly) { ownerSize.width = parentSize.width * _percentWidth; ownerPosition.x = _leftMargin + ownerAnchor.x * ownerSize.width; } else { if (_usingPositionPercentX) ownerPosition.x = parentSize.width * _positionPercentX; if (_usingPercentWidth) ownerSize.width = parentSize.width * _percentWidth; } break; case HorizontalEdge::Left: if (_isPercentOnly) break; if (_usingPercentWidth || _usingStretchWidth) ownerSize.width = parentSize.width * _percentWidth; ownerPosition.x = _leftMargin + ownerAnchor.x * ownerSize.width; break; case HorizontalEdge::Right: if (_isPercentOnly) break; if (_usingPercentWidth || _usingStretchWidth) ownerSize.width = parentSize.width * _percentWidth; ownerPosition.x = parentSize.width - (_rightMargin + (1 - ownerAnchor.x) * ownerSize.width); break; case HorizontalEdge::Center: if (_isPercentOnly) break; if (_usingStretchWidth) { ownerSize.width = parentSize.width - _leftMargin - _rightMargin; if (ownerSize.width < 0) ownerSize.width = 0; ownerPosition.x = _leftMargin + ownerAnchor.x * ownerSize.width; } else { if (_usingPercentWidth) ownerSize.width = parentSize.width * _percentWidth; ownerPosition.x = parentSize.width * _positionPercentX; } break; default: break; } switch (this->_verticalEdge) { case VerticalEdge::None_: if (_usingStretchHeight && !_isPercentOnly) { ownerSize.height = parentSize.height * _percentHeight; ownerPosition.y = _bottomMargin + ownerAnchor.y * ownerSize.height; } else { if (_usingPositionPercentY) ownerPosition.y = parentSize.height * _positionPercentY; if (_usingPercentHeight) ownerSize.height = parentSize.height * _percentHeight; } break; case VerticalEdge::Bottom: if (_isPercentOnly) break; if (_usingPercentHeight || _usingStretchHeight) ownerSize.height = parentSize.height * _percentHeight; ownerPosition.y = _bottomMargin + ownerAnchor.y * ownerSize.height; break; case VerticalEdge::Top: if (_isPercentOnly) break; if (_usingPercentHeight || _usingStretchHeight) ownerSize.height = parentSize.height * _percentHeight; ownerPosition.y = parentSize.height - (_topMargin + (1 - ownerAnchor.y) * ownerSize.height); break; case VerticalEdge::Center_: if (_isPercentOnly) break; if (_usingStretchHeight) { ownerSize.height = parentSize.height - _topMargin - _bottomMargin; if (ownerSize.height < 0) ownerSize.height = 0; ownerPosition.y = _bottomMargin + ownerAnchor.y * ownerSize.height; } else { if (_usingPercentHeight) ownerSize.height = parentSize.height * _percentHeight; ownerPosition.y = parentSize.height* _positionPercentY; } break; default: break; } _owner->setPosition(ownerPosition); _owner->setContentSize(ownerSize); ui::Helper::doLayout(_owner); } void LayoutComponent::setActiveEnabled(bool enable) { _actived = enable; } void LayoutComponent::setPercentOnlyEnabled(bool enable) { _isPercentOnly = enable; } } NS_CC_END
f08bd1e767445839e33cfa09ba50dd387365848a
da751f6efa8a66f6110673e0a0adfdca1a51387a
/C++/10071 - Trevor Philips Industries.cpp
5ac27493a83509bdea5e4f81afe1d6bc2909606c
[]
no_license
hi2tamzid/Outsbook
af12c2074c423014ae330a76e53b4a46e03850c8
cffa383946212e501f2319c33219149e1cfa9474
refs/heads/main
2023-01-23T23:32:17.835255
2020-11-26T10:45:09
2020-11-26T10:45:09
316,197,704
0
0
null
null
null
null
UTF-8
C++
false
false
351
cpp
#include <bits/stdc++.h> using namespace std; int main() { int t; cin >> t; while(t--) { long long m, t, n; cin >> m>> t >> n; double result = (double)n / (m * 4.0) ; result = ceil(result) * (double)t; cout <<fixed << setprecision(0) << result << endl; } return 0; }
34120f1b774b1d6a25064dd007ed62501b2a1db7
9da88ab805303c25bd9654ad45287a62a6c4710f
/Cpp/atcoder/abc/292/D.cpp
96addbbdd41b3cfb222cb285565917cda88fc5fd
[]
no_license
ms303956362/myexercise
7bb7be1ac0b8f40aeee8ca2df19255024c6d9bdc
4730c438354f0c7fc3bce54f8c1ade6e627586c9
refs/heads/master
2023-04-13T01:15:01.882780
2023-04-03T15:03:22
2023-04-03T15:03:22
232,984,051
2
0
null
2022-12-02T06:55:19
2020-01-10T06:47:00
C
UTF-8
C++
false
false
1,726
cpp
// IO #include <iostream> #include <iomanip> // std::setprecision #include <sstream> // ordered container #include <vector> #include <deque> #include <list> #include <forward_list> #include <string> #include <stack> #include <queue> // associative-container #include <map> #include <set> #include <unordered_map> #include <unordered_set> // algorithm #include <algorithm> #include <cmath> // utility #include <initializer_list> #include <iterator> #include <memory> #include <utility> // c #include <cstdio> #include <cstdlib> #include <cstring> // functional #include <functional> using namespace std; using ll = long long; int main(int argc, char const *argv[]) { ios::sync_with_stdio(false); cin.tie(0); int n, m; cin >> n >> m; vector<int> p(n); for (int i = 0; i < n; ++i) { p[i] = i; } function<int(int)> find = [&](int u) { return p[u] == u ? u : (p[u] = find(p[u])); }; auto merge = [&](int u, int v) { int pu = find(u), pv = find(v); if (pu == pv) { return false; } p[pu]= pv; return true; }; vector<pair<int, int>> edges; for (int i = 0; i < m; ++i) { int u, v; cin >> u >> v; --u; --v; merge(u, v); edges.emplace_back(u, v); } map<int, int> cntv, cnte; for (int i = 0; i < n; ++i) { ++cntv[find(i)]; } for (const auto& [u, v] : edges) { ++cnte[find(u)]; } auto check = [&]() { for (const auto& [u, c] : cntv) { if (c != cnte[u]) { return false; } } return true; }; cout << (check() ? "Yes" : "No") << '\n'; return 0; }
9c7fd64205e8276c5b9640622b0ad8537664886e
ae474c46e47d8e5084bbc2b8aad44a59c5effad7
/TestCasesInSuits/CaseAndSuitForRayRender.h
1a07918c69bb04e753ef16528707c0de4e1e2546
[]
no_license
181847/LearningFundamentalsOfComputerGraphic
9bb3bd325dffa1131d3a1743f588b2e91a8c4bde
c4215f710853ebbc7c73f233ddc1df7931ed2f62
refs/heads/master
2020-03-23T03:35:33.703762
2019-07-26T15:52:38
2019-07-26T15:52:38
141,038,418
1
0
null
null
null
null
UTF-8
C++
false
false
841
h
#pragma once #include "CommonHeaders.h" #define CASE_NAME_IN_RAY_RENDER(RestClassName) CaseFor##RestClassName #define DECLARE_CASE_IN_RAY_RENDER_FOR(RestClassName, CaseName) \ class CASE_NAME_IN_RAY_RENDER(RestClassName) : public CaseForPipline\ {\ public:\ CASE_NAME_IN_RAY_RENDER(RestClassName)() :CaseForPipline(CaseName) {}\ virtual void Run() override;\ virtual std::wstring GetStoragePath() const override {return Super::GetStoragePath() + SUB_FOLDER;}\ protected:\ const std::wstring SUB_FOLDER = L"RayRender/";\ } DECLARE_CASE_IN_RAY_RENDER_FOR(InsideBoxesAndSphere, "render inside boxes and sphere"); DECLARE_CASE_IN_RAY_RENDER_FOR(TrasparentMat, "transparent material"); using SuitForRayRender = SuitForPipline< //CASE_NAME_IN_RAY_RENDER(InsideBoxesAndSphere), CASE_NAME_IN_RAY_RENDER(TrasparentMat) >;
97777fd74e98e30d2eded7935885abaf559dbfbd
f11ed31357628473e0bfb89902bc9c94157c6c59
/Vending_machine/Vending_machine/Machine.h
7c2e10549535b9f92dae842bf8dc3225fe3aaa4d
[]
no_license
ChouJustice/WinForm-Project
06da737d6e31578b257955c3c8917691c1777e6f
e923d7c1a70e3420664574a9bd3bcee074aa7135
refs/heads/master
2020-03-15T19:56:18.445743
2018-08-20T06:41:49
2018-08-20T06:41:49
132,320,836
0
0
null
null
null
null
UTF-8
C++
false
false
468
h
#pragma once #include "Goods.h" ref class Machine { private: array<Goods^> ^Sale_goods; int money; int balance; public: Machine(void); void setMoney(int); void setBalance(int); void plus_100(); void plus_50(); void plus_10(); void machine_initialization(void); void setName(int,System::String^); void setStock(int,int); void setPrice(int,int); System::String^ getName(int); int getStock(int); int getPrice(int); int getMoney(); int getBalance(); };
fca5b2ab7b0b4e0c2793a765b5c84fea13e3c3e7
6e9b20902f4e232d12e865f192ea5128ae253ba7
/Fluid/7.4/uniform/time
815a736038b424044dd1a5297547ac9d34a00257
[]
no_license
abarcaortega/FSI_3
1de5ed06ca7731016e5136820aecdc0a74042723
016638757f56e7b8b33af4a1af8e0635b88ffbbc
refs/heads/master
2020-08-03T22:28:04.707884
2019-09-30T16:33:31
2019-09-30T16:33:31
211,905,379
0
0
null
null
null
null
UTF-8
C++
false
false
823
/*--------------------------------*- C++ -*----------------------------------*\ ========= | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox \\ / O peration | Website: https://openfoam.org \\ / A nd | Version: dev \\/ M anipulation | \*---------------------------------------------------------------------------*/ FoamFile { version 2.0; format ascii; class dictionary; location "7.4/uniform"; object time; } // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // value 7.39999999999988667; name "7.4"; index 740; deltaT 0.01; deltaT0 0.01; // ************************************************************************* //
0b6551bd116eb78cb7b0c5954d975e8fddad538c
3ffb5a515f1ea50f8c3467af3c9ee63a4b73f706
/src/qt/qrcodedialog.cpp
d6b86d1caf33d74540bf4e6871a5723059fdc962
[ "MIT" ]
permissive
sppl/iti
c75db061242c98983e5204fdaf4b68e61f2230fd
384c67784177ca5eb3d218f4276f00584a8b8743
refs/heads/master
2020-04-02T07:32:54.267090
2017-07-14T18:38:33
2017-07-14T18:38:33
61,468,392
3
2
null
null
null
null
UTF-8
C++
false
false
4,360
cpp
#include "qrcodedialog.h" #include "ui_qrcodedialog.h" #include "bitcoinunits.h" #include "dialogwindowflags.h" #include "guiconstants.h" #include "guiutil.h" #include "optionsmodel.h" #include <QPixmap> #include <QUrl> #include <qrencode.h> QRCodeDialog::QRCodeDialog(const QString &addr, const QString &label, bool enableReq, QWidget *parent) : QDialog(parent, DIALOGWINDOWHINTS), ui(new Ui::QRCodeDialog), model(0), address(addr) { ui->setupUi(this); setWindowTitle(QString("%1").arg(address)); ui->chkReqPayment->setVisible(enableReq); ui->lblAmount->setVisible(enableReq); ui->lnReqAmount->setVisible(enableReq); ui->lnLabel->setText(label); ui->btnSaveAs->setEnabled(false); genCode(); } QRCodeDialog::~QRCodeDialog() { delete ui; } void QRCodeDialog::setModel(OptionsModel *model) { this->model = model; if (model) connect(model, SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit())); // update the display unit, to not use the default ("BTC") updateDisplayUnit(); } void QRCodeDialog::genCode() { QString uri = getURI(); if (uri != "") { ui->lblQRCode->setText(""); QRcode *code = QRcode_encodeString(uri.toUtf8().constData(), 0, QR_ECLEVEL_L, QR_MODE_8, 1); if (!code) { ui->lblQRCode->setText(tr("Error encoding URI into QR Code.")); return; } myImage = QImage(code->width + 8, code->width + 8, QImage::Format_RGB32); myImage.fill(0xffffff); unsigned char *p = code->data; for (int y = 0; y < code->width; y++) { for (int x = 0; x < code->width; x++) { myImage.setPixel(x + 4, y + 4, ((*p & 1) ? 0x0 : 0xffffff)); p++; } } QRcode_free(code); ui->lblQRCode->setPixmap(QPixmap::fromImage(myImage).scaled(300, 300)); ui->outUri->setPlainText(uri); } } QString QRCodeDialog::getURI() { QString ret = QString("iticoin:%1").arg(address); int paramCount = 0; ui->outUri->clear(); if (ui->chkReqPayment->isChecked()) { if (ui->lnReqAmount->validate()) { // even if we allow a non BTC unit input in lnReqAmount, we generate the URI with BTC as unit (as defined in BIP21) ret += QString("?amount=%1").arg(BitcoinUnits::format(BitcoinUnits::BTC, ui->lnReqAmount->value())); paramCount++; } else { ui->btnSaveAs->setEnabled(false); ui->lblQRCode->setText(tr("The entered amount is invalid, please check.")); return QString(""); } } if (!ui->lnLabel->text().isEmpty()) { QString lbl(QUrl::toPercentEncoding(ui->lnLabel->text())); ret += QString("%1label=%2").arg(paramCount == 0 ? "?" : "&").arg(lbl); paramCount++; } if (!ui->lnMessage->text().isEmpty()) { QString msg(QUrl::toPercentEncoding(ui->lnMessage->text())); ret += QString("%1message=%2").arg(paramCount == 0 ? "?" : "&").arg(msg); paramCount++; } // limit URI length to prevent a DoS against the QR-Code dialog if (ret.length() > MAX_URI_LENGTH) { ui->btnSaveAs->setEnabled(false); ui->lblQRCode->setText(tr("Resulting URI too long, try to reduce the text for label / message.")); return QString(""); } ui->btnSaveAs->setEnabled(true); return ret; } void QRCodeDialog::on_lnReqAmount_textChanged() { genCode(); } void QRCodeDialog::on_lnLabel_textChanged() { genCode(); } void QRCodeDialog::on_lnMessage_textChanged() { genCode(); } void QRCodeDialog::on_btnSaveAs_clicked() { QString fn = GUIUtil::getSaveFileName(this, tr("Save QR Code"), QString(), tr("PNG Images (*.png)")); if (!fn.isEmpty()) myImage.scaled(EXPORT_IMAGE_SIZE, EXPORT_IMAGE_SIZE).save(fn); } void QRCodeDialog::on_chkReqPayment_toggled(bool fChecked) { if (!fChecked) // if chkReqPayment is not active, don't display lnReqAmount as invalid ui->lnReqAmount->setValid(true); genCode(); } void QRCodeDialog::updateDisplayUnit() { if (model) { // Update lnReqAmount with the current unit ui->lnReqAmount->setDisplayUnit(model->getDisplayUnit()); } }
4ce772be8fa1270aa9a014e408cd64137afb3a88
f92e90323339912314faf6475b988d26f679372b
/test_suite/dr_branch_12_locks_Yes.cpp
8f3cef3e6be168ca86b0686d746acc920fbf685b
[]
no_license
rutgers-apl/PTRacer
eea91b7606730565bf54524ce8bbb52b58529f1b
3624264c38302513f0d28fc22f875d9e3dd8fdcf
refs/heads/master
2020-12-25T13:51:17.473837
2017-06-06T06:11:27
2017-06-06T06:11:27
62,167,491
8
2
null
null
null
null
UTF-8
C++
false
false
18,198
cpp
#include<iostream> #include "t_debug_task.h" #include "tbb/mutex.h" using namespace std; using namespace tbb; #define NUM_TASKS 22 int shd[NUM_TASKS]; bool c; tbb::mutex x_mutex; tbb::mutex::scoped_lock myLock; class Task1: public t_debug_task { public: task* execute() { __exec_begin__(getTaskId()); RecordTExecute(get_cur_tid()); RecordTLockAcq(get_cur_tid(), &x_mutex); CaptureLockAcquire(get_cur_tid(), (ADDRINT)&x_mutex); myLock.acquire(x_mutex); int str_1 = 1; RecordTStore (get_cur_tid(), &c, &str_1); c = true; // READ & WRITE RecordTLoad (get_cur_tid(), &shd[getTaskId()]); int tmp = shd[getTaskId()] + 1; RecordTStore (get_cur_tid(), &shd[getTaskId()], &tmp); shd[getTaskId()]++; RecordTLockRel(get_cur_tid(), &x_mutex); CaptureLockRelease(get_cur_tid(), (ADDRINT)&x_mutex); myLock.release(); RecordTReturn(get_cur_tid()); __exec_end__(getTaskId()); return NULL; } }; class Task2: public t_debug_task { public: task* execute() { __exec_begin__(getTaskId()); RecordTExecute(get_cur_tid()); RecordTLockAcq(get_cur_tid(), &x_mutex); CaptureLockAcquire(get_cur_tid(), (ADDRINT)&x_mutex); myLock.acquire(x_mutex); RecordTLoad (get_cur_tid(), &c); if (c == true) { int str_2 = 1; RecordTBrCheck(get_cur_tid(), &c, &str_2, EQ); // READ & WRITE RecordTLoad (get_cur_tid(), &shd[1]); int tmp = shd[1] + 1; RecordTStore (get_cur_tid(), &shd[1], &tmp); shd[1]++; RecordTLockRel(get_cur_tid(), &x_mutex); CaptureLockRelease(get_cur_tid(), (ADDRINT)&x_mutex); myLock.release(); } else { int str_2 = 1; RecordTBrCheck(get_cur_tid(), &c, &str_2, NEQ); RecordTLockRel(get_cur_tid(), &x_mutex); CaptureLockRelease(get_cur_tid(), (ADDRINT)&x_mutex); myLock.release(); // READ & WRITE RecordTLoad (get_cur_tid(), &shd[1]); int tmp = shd[1] + 1; RecordTStore (get_cur_tid(), &shd[1], &tmp); shd[1]++; } RecordTReturn(get_cur_tid()); __exec_end__(getTaskId()); return NULL; } }; class Task3: public t_debug_task { public: task* execute() { __exec_begin__(getTaskId()); RecordTExecute(get_cur_tid()); RecordTLockAcq(get_cur_tid(), &x_mutex); CaptureLockAcquire(get_cur_tid(), (ADDRINT)&x_mutex); myLock.acquire(x_mutex); // READ & WRITE RecordTLoad (get_cur_tid(), &shd[getTaskId()]); int tmp = shd[getTaskId()] + 1; RecordTStore (get_cur_tid(), &shd[getTaskId()], &tmp); shd[getTaskId()]++; RecordTLockRel(get_cur_tid(), &x_mutex); CaptureLockRelease(get_cur_tid(), (ADDRINT)&x_mutex); myLock.release(); RecordTReturn(get_cur_tid()); __exec_end__(getTaskId()); return NULL; } }; class Task4: public t_debug_task { public: task* execute() { __exec_begin__(getTaskId()); RecordTExecute(get_cur_tid()); RecordTLockAcq(get_cur_tid(), &x_mutex); CaptureLockAcquire(get_cur_tid(), (ADDRINT)&x_mutex); myLock.acquire(x_mutex); RecordTLoad (get_cur_tid(), &shd[getTaskId()]); int tmp = shd[getTaskId()] + 1; RecordTStore (get_cur_tid(), &shd[getTaskId()], &tmp); shd[getTaskId()]++; RecordTLockRel(get_cur_tid(), &x_mutex); CaptureLockRelease(get_cur_tid(), (ADDRINT)&x_mutex); myLock.release(); RecordTReturn(get_cur_tid()); __exec_end__(getTaskId()); return NULL; } }; class Task5: public t_debug_task { public: task* execute() { __exec_begin__(getTaskId()); RecordTExecute(get_cur_tid()); RecordTLockAcq(get_cur_tid(), &x_mutex); CaptureLockAcquire(get_cur_tid(), (ADDRINT)&x_mutex); myLock.acquire(x_mutex); // READ & WRITE RecordTLoad (get_cur_tid(), &shd[getTaskId()]); int tmp = shd[getTaskId()] + 1; RecordTStore (get_cur_tid(), &shd[getTaskId()], &tmp); shd[getTaskId()]++; RecordTLockRel(get_cur_tid(), &x_mutex); CaptureLockRelease(get_cur_tid(), (ADDRINT)&x_mutex); myLock.release(); RecordTReturn(get_cur_tid()); __exec_end__(getTaskId()); return NULL; } }; class Task6: public t_debug_task { public: task* execute() { __exec_begin__(getTaskId()); RecordTExecute(get_cur_tid()); RecordTLockAcq(get_cur_tid(), &x_mutex); CaptureLockAcquire(get_cur_tid(), (ADDRINT)&x_mutex); myLock.acquire(x_mutex); // READ & WRITE RecordTLoad (get_cur_tid(), &shd[getTaskId()]); int tmp = shd[getTaskId()] + 1; RecordTStore (get_cur_tid(), &shd[getTaskId()], &tmp); shd[getTaskId()]++; RecordTLockRel(get_cur_tid(), &x_mutex); CaptureLockRelease(get_cur_tid(), (ADDRINT)&x_mutex); myLock.release(); RecordTReturn(get_cur_tid()); __exec_end__(getTaskId()); return NULL; } }; class Task7: public t_debug_task { public: task* execute() { __exec_begin__(getTaskId()); RecordTExecute(get_cur_tid()); RecordTLockAcq(get_cur_tid(), &x_mutex); CaptureLockAcquire(get_cur_tid(), (ADDRINT)&x_mutex); myLock.acquire(x_mutex); // READ & WRITE RecordTLoad (get_cur_tid(), &shd[getTaskId()]); int tmp = shd[getTaskId()] + 1; RecordTStore (get_cur_tid(), &shd[getTaskId()], &tmp); shd[getTaskId()]++; RecordTLockRel(get_cur_tid(), &x_mutex); CaptureLockRelease(get_cur_tid(), (ADDRINT)&x_mutex); myLock.release(); RecordTReturn(get_cur_tid()); __exec_end__(getTaskId()); return NULL; } }; class Task8: public t_debug_task { public: task* execute() { __exec_begin__(getTaskId()); RecordTExecute(get_cur_tid()); RecordTLockAcq(get_cur_tid(), &x_mutex); CaptureLockAcquire(get_cur_tid(), (ADDRINT)&x_mutex); myLock.acquire(x_mutex); // READ & WRITE RecordTLoad (get_cur_tid(), &shd[getTaskId()]); int tmp = shd[getTaskId()] + 1; RecordTStore (get_cur_tid(), &shd[getTaskId()], &tmp); shd[getTaskId()]++; RecordTLockRel(get_cur_tid(), &x_mutex); CaptureLockRelease(get_cur_tid(), (ADDRINT)&x_mutex); myLock.release(); RecordTReturn(get_cur_tid()); __exec_end__(getTaskId()); return NULL; } }; class Task9: public t_debug_task { public: task* execute() { __exec_begin__(getTaskId()); RecordTExecute(get_cur_tid()); RecordTLockAcq(get_cur_tid(), &x_mutex); CaptureLockAcquire(get_cur_tid(), (ADDRINT)&x_mutex); myLock.acquire(x_mutex); // READ & WRITE RecordTLoad (get_cur_tid(), &shd[getTaskId()]); int tmp = shd[getTaskId()] + 1; RecordTStore (get_cur_tid(), &shd[getTaskId()], &tmp); shd[getTaskId()]++; RecordTLockRel(get_cur_tid(), &x_mutex); CaptureLockRelease(get_cur_tid(), (ADDRINT)&x_mutex); myLock.release(); RecordTReturn(get_cur_tid()); __exec_end__(getTaskId()); return NULL; } }; class Task10: public t_debug_task { public: task* execute() { __exec_begin__(getTaskId()); RecordTExecute(get_cur_tid()); RecordTLockAcq(get_cur_tid(), &x_mutex); CaptureLockAcquire(get_cur_tid(), (ADDRINT)&x_mutex); myLock.acquire(x_mutex); // READ & WRITE RecordTLoad (get_cur_tid(), &shd[getTaskId()]); int tmp = shd[getTaskId()] + 1; RecordTStore (get_cur_tid(), &shd[getTaskId()], &tmp); shd[getTaskId()]++; RecordTLockRel(get_cur_tid(), &x_mutex); CaptureLockRelease(get_cur_tid(), (ADDRINT)&x_mutex); myLock.release(); RecordTReturn(get_cur_tid()); __exec_end__(getTaskId()); return NULL; } }; class Task11: public t_debug_task { public: task* execute() { __exec_begin__(getTaskId()); RecordTExecute(get_cur_tid()); RecordTLockAcq(get_cur_tid(), &x_mutex); CaptureLockAcquire(get_cur_tid(), (ADDRINT)&x_mutex); myLock.acquire(x_mutex); // READ & WRITE RecordTLoad (get_cur_tid(), &shd[getTaskId()]); int tmp = shd[getTaskId()] + 1; RecordTStore (get_cur_tid(), &shd[getTaskId()], &tmp); shd[getTaskId()]++; RecordTLockRel(get_cur_tid(), &x_mutex); CaptureLockRelease(get_cur_tid(), (ADDRINT)&x_mutex); myLock.release(); RecordTReturn(get_cur_tid()); __exec_end__(getTaskId()); return NULL; } }; class Task12: public t_debug_task { public: task* execute() { __exec_begin__(getTaskId()); RecordTExecute(get_cur_tid()); RecordTLockAcq(get_cur_tid(), &x_mutex); CaptureLockAcquire(get_cur_tid(), (ADDRINT)&x_mutex); myLock.acquire(x_mutex); // READ & WRITE RecordTLoad (get_cur_tid(), &shd[getTaskId()]); int tmp = shd[getTaskId()] + 1; RecordTStore (get_cur_tid(), &shd[getTaskId()], &tmp); shd[getTaskId()]++; RecordTLockRel(get_cur_tid(), &x_mutex); CaptureLockRelease(get_cur_tid(), (ADDRINT)&x_mutex); myLock.release(); RecordTReturn(get_cur_tid()); __exec_end__(getTaskId()); return NULL; } }; class Task13: public t_debug_task { public: task* execute() { __exec_begin__(getTaskId()); RecordTExecute(get_cur_tid()); RecordTLockAcq(get_cur_tid(), &x_mutex); CaptureLockAcquire(get_cur_tid(), (ADDRINT)&x_mutex); myLock.acquire(x_mutex); // READ & WRITE RecordTLoad (get_cur_tid(), &shd[getTaskId()]); int tmp = shd[getTaskId()] + 1; RecordTStore (get_cur_tid(), &shd[getTaskId()], &tmp); shd[getTaskId()]++; RecordTLockRel(get_cur_tid(), &x_mutex); CaptureLockRelease(get_cur_tid(), (ADDRINT)&x_mutex); myLock.release(); RecordTReturn(get_cur_tid()); __exec_end__(getTaskId()); return NULL; } }; class Task14: public t_debug_task { public: task* execute() { __exec_begin__(getTaskId()); RecordTExecute(get_cur_tid()); RecordTLockAcq(get_cur_tid(), &x_mutex); CaptureLockAcquire(get_cur_tid(), (ADDRINT)&x_mutex); myLock.acquire(x_mutex); // READ & WRITE RecordTLoad (get_cur_tid(), &shd[getTaskId()]); int tmp = shd[getTaskId()] + 1; RecordTStore (get_cur_tid(), &shd[getTaskId()], &tmp); shd[getTaskId()]++; RecordTLockRel(get_cur_tid(), &x_mutex); CaptureLockRelease(get_cur_tid(), (ADDRINT)&x_mutex); myLock.release(); RecordTReturn(get_cur_tid()); __exec_end__(getTaskId()); return NULL; } }; class Task15: public t_debug_task { public: task* execute() { __exec_begin__(getTaskId()); RecordTExecute(get_cur_tid()); RecordTLockAcq(get_cur_tid(), &x_mutex); CaptureLockAcquire(get_cur_tid(), (ADDRINT)&x_mutex); myLock.acquire(x_mutex); // READ & WRITE RecordTLoad (get_cur_tid(), &shd[getTaskId()]); int tmp = shd[getTaskId()] + 1; RecordTStore (get_cur_tid(), &shd[getTaskId()], &tmp); shd[getTaskId()]++; RecordTLockRel(get_cur_tid(), &x_mutex); CaptureLockRelease(get_cur_tid(), (ADDRINT)&x_mutex); myLock.release(); RecordTReturn(get_cur_tid()); __exec_end__(getTaskId()); return NULL; } }; class Task16: public t_debug_task { public: task* execute() { __exec_begin__(getTaskId()); RecordTExecute(get_cur_tid()); RecordTLockAcq(get_cur_tid(), &x_mutex); CaptureLockAcquire(get_cur_tid(), (ADDRINT)&x_mutex); myLock.acquire(x_mutex); // READ & WRITE RecordTLoad (get_cur_tid(), &shd[getTaskId()]); int tmp = shd[getTaskId()] + 1; RecordTStore (get_cur_tid(), &shd[getTaskId()], &tmp); shd[getTaskId()]++; RecordTLockRel(get_cur_tid(), &x_mutex); CaptureLockRelease(get_cur_tid(), (ADDRINT)&x_mutex); myLock.release(); RecordTReturn(get_cur_tid()); __exec_end__(getTaskId()); return NULL; } }; class Task17: public t_debug_task { public: task* execute() { __exec_begin__(getTaskId()); RecordTExecute(get_cur_tid()); RecordTLockAcq(get_cur_tid(), &x_mutex); CaptureLockAcquire(get_cur_tid(), (ADDRINT)&x_mutex); myLock.acquire(x_mutex); // READ & WRITE RecordTLoad (get_cur_tid(), &shd[getTaskId()]); int tmp = shd[getTaskId()] + 1; RecordTStore (get_cur_tid(), &shd[getTaskId()], &tmp); shd[getTaskId()]++; RecordTLockRel(get_cur_tid(), &x_mutex); CaptureLockRelease(get_cur_tid(), (ADDRINT)&x_mutex); myLock.release(); RecordTReturn(get_cur_tid()); __exec_end__(getTaskId()); return NULL; } }; class Task18: public t_debug_task { public: task* execute() { __exec_begin__(getTaskId()); RecordTExecute(get_cur_tid()); RecordTLockAcq(get_cur_tid(), &x_mutex); CaptureLockAcquire(get_cur_tid(), (ADDRINT)&x_mutex); myLock.acquire(x_mutex); // READ & WRITE RecordTLoad (get_cur_tid(), &shd[getTaskId()]); int tmp = shd[getTaskId()] + 1; RecordTStore (get_cur_tid(), &shd[getTaskId()], &tmp); shd[getTaskId()]++; RecordTLockRel(get_cur_tid(), &x_mutex); CaptureLockRelease(get_cur_tid(), (ADDRINT)&x_mutex); myLock.release(); RecordTReturn(get_cur_tid()); __exec_end__(getTaskId()); return NULL; } }; class Task19: public t_debug_task { public: task* execute() { __exec_begin__(getTaskId()); RecordTExecute(get_cur_tid()); RecordTLockAcq(get_cur_tid(), &x_mutex); CaptureLockAcquire(get_cur_tid(), (ADDRINT)&x_mutex); myLock.acquire(x_mutex); // READ & WRITE RecordTLoad (get_cur_tid(), &shd[getTaskId()]); int tmp = shd[getTaskId()] + 1; RecordTStore (get_cur_tid(), &shd[getTaskId()], &tmp); shd[getTaskId()]++; RecordTLockRel(get_cur_tid(), &x_mutex); CaptureLockRelease(get_cur_tid(), (ADDRINT)&x_mutex); myLock.release(); RecordTReturn(get_cur_tid()); __exec_end__(getTaskId()); return NULL; } }; class Task20: public t_debug_task { public: task* execute() { __exec_begin__(getTaskId()); RecordTExecute(get_cur_tid()); RecordTLockAcq(get_cur_tid(), &x_mutex); CaptureLockAcquire(get_cur_tid(), (ADDRINT)&x_mutex); myLock.acquire(x_mutex); // READ & WRITE RecordTLoad (get_cur_tid(), &shd[getTaskId()]); int tmp = shd[getTaskId()] + 1; RecordTStore (get_cur_tid(), &shd[getTaskId()], &tmp); shd[getTaskId()]++; RecordTLockRel(get_cur_tid(), &x_mutex); CaptureLockRelease(get_cur_tid(), (ADDRINT)&x_mutex); myLock.release(); RecordTReturn(get_cur_tid()); __exec_end__(getTaskId()); return NULL; } }; class Task21: public t_debug_task { public: task* execute() { __exec_begin__(getTaskId()); RecordTExecute(get_cur_tid()); RecordTLockAcq(get_cur_tid(), &x_mutex); CaptureLockAcquire(get_cur_tid(), (ADDRINT)&x_mutex); myLock.acquire(x_mutex); // READ & WRITE RecordTLoad (get_cur_tid(), &shd[getTaskId()]); int tmp = shd[getTaskId()] + 1; RecordTStore (get_cur_tid(), &shd[getTaskId()], &tmp); shd[getTaskId()]++; RecordTLockRel(get_cur_tid(), &x_mutex); CaptureLockRelease(get_cur_tid(), (ADDRINT)&x_mutex); myLock.release(); RecordTReturn(get_cur_tid()); __exec_end__(getTaskId()); return NULL; } }; int main( int argc, const char *argv[] ) { TD_Activate(); TraceGenActivate(); int str_1 = 0; RecordTStoreMain(&c, &str_1); c = false; t_debug_task& a = *new(task::allocate_root()) Task1(); t_debug_task::spawn(a); int a_cid = a.getTaskId(); RecordTSpawnMain(&a_cid); t_debug_task& b = *new(task::allocate_root()) Task2(); t_debug_task::spawn(b); int b_cid = b.getTaskId(); RecordTSpawnMain(&b_cid); t_debug_task& c = *new(task::allocate_root()) Task3(); t_debug_task::spawn(c); int c_cid = c.getTaskId(); RecordTSpawnMain(&c_cid); t_debug_task& d = *new(task::allocate_root()) Task4(); t_debug_task::spawn(d); int d_cid = d.getTaskId(); RecordTSpawnMain(&d_cid); t_debug_task& e = *new(task::allocate_root()) Task5(); t_debug_task::spawn(e); int e_cid = e.getTaskId(); RecordTSpawnMain(&e_cid); t_debug_task& f = *new(task::allocate_root()) Task6(); t_debug_task::spawn(f); int f_cid = f.getTaskId(); RecordTSpawnMain(&f_cid); t_debug_task& g = *new(task::allocate_root()) Task7(); t_debug_task::spawn(g); int g_cid = g.getTaskId(); RecordTSpawnMain(&g_cid); t_debug_task& h = *new(task::allocate_root()) Task8(); t_debug_task::spawn(h); int h_cid = h.getTaskId(); RecordTSpawnMain(&h_cid); t_debug_task& i = *new(task::allocate_root()) Task9(); t_debug_task::spawn(i); int i_cid = i.getTaskId(); RecordTSpawnMain(&i_cid); t_debug_task& j = *new(task::allocate_root()) Task10(); t_debug_task::spawn(j); int j_cid = j.getTaskId(); RecordTSpawnMain(&j_cid); t_debug_task& k = *new(task::allocate_root()) Task11(); t_debug_task::spawn(k); int k_cid = k.getTaskId(); RecordTSpawnMain(&k_cid); t_debug_task& l = *new(task::allocate_root()) Task12(); t_debug_task::spawn(l); int l_cid = l.getTaskId(); RecordTSpawnMain(&l_cid); t_debug_task& m = *new(task::allocate_root()) Task13(); t_debug_task::spawn(m); int m_cid = m.getTaskId(); RecordTSpawnMain(&m_cid); t_debug_task& n = *new(task::allocate_root()) Task14(); t_debug_task::spawn(n); int n_cid = n.getTaskId(); RecordTSpawnMain(&n_cid); t_debug_task& o = *new(task::allocate_root()) Task15(); t_debug_task::spawn(o); int o_cid = o.getTaskId(); RecordTSpawnMain(&o_cid); t_debug_task& p = *new(task::allocate_root()) Task16(); t_debug_task::spawn(p); int p_cid = p.getTaskId(); RecordTSpawnMain(&p_cid); t_debug_task& q = *new(task::allocate_root()) Task17(); t_debug_task::spawn(q); int q_cid = q.getTaskId(); RecordTSpawnMain(&q_cid); t_debug_task& s = *new(task::allocate_root()) Task18(); t_debug_task::spawn(s); int s_cid = s.getTaskId(); RecordTSpawnMain(&s_cid); t_debug_task& t = *new(task::allocate_root()) Task19(); t_debug_task::spawn(t); int t_cid = t.getTaskId(); RecordTSpawnMain(&t_cid); t_debug_task& u = *new(task::allocate_root()) Task20(); t_debug_task::spawn(u); int u_cid = u.getTaskId(); RecordTSpawnMain(&u_cid); t_debug_task& v = *new(task::allocate_root()) Task21(); t_debug_task::spawn_root_and_wait(v); int v_cid = v.getTaskId(); RecordTSpawnMain(&v_cid); for (size_t i = 0 ; i < 1000000000 ; i++); cout << "Addr of shd[1] " << (size_t)&shd[1] << std::endl; RecordTReturn(0); Fini(); }
05587762221d9f405c6f047aff1fba677658ba03
b958286bb016a56f5ddff5514f38fbd29f3e9072
/include/ublox/message/MgaGloEph.h
731a95cbae3ab84986c3e0854bce4db66f60c74f
[]
no_license
yxw027/cc.ublox.generated
abdda838945777a498f433b0d9624a567ab1ea80
a8bf468281d2d06e32d3e029c40bc6d38e4a34de
refs/heads/master
2021-01-14T23:03:20.722801
2020-02-20T06:24:46
2020-02-20T06:24:46
null
0
0
null
null
null
null
UTF-8
C++
false
false
16,098
h
// Generated by commsdsl2comms v3.3.2 /// @file /// @brief Contains definition of <b>"MGA-GLO-EPH"</b> message and its fields. #pragma once #include <cstdint> #include <tuple> #include "comms/MessageBase.h" #include "comms/field/IntValue.h" #include "comms/options.h" #include "ublox/MsgId.h" #include "ublox/field/FieldBase.h" #include "ublox/field/Res1.h" #include "ublox/field/Res4.h" #include "ublox/message/MgaGloEphCommon.h" #include "ublox/options/DefaultOptions.h" namespace ublox { namespace message { /// @brief Fields of @ref MgaGloEph. /// @tparam TOpt Extra options /// @see @ref MgaGloEph /// @headerfile "ublox/message/MgaGloEph.h" template <typename TOpt = ublox::options::DefaultOptions> struct MgaGloEphFields { /// @brief Definition of <b>"type"</b> field. struct Type : public comms::field::IntValue< ublox::field::FieldBase<>, std::uint8_t, comms::option::def::FailOnInvalid<>, comms::option::def::DefaultNumValue<1>, comms::option::def::ValidNumValue<1> > { /// @brief Name of the field. static const char* name() { return ublox::message::MgaGloEphFieldsCommon::TypeCommon::name(); } }; /// @brief Definition of <b>"version"</b> field. struct Version : public comms::field::IntValue< ublox::field::FieldBase<>, std::uint8_t, comms::option::def::ValidNumValue<0> > { /// @brief Name of the field. static const char* name() { return ublox::message::MgaGloEphFieldsCommon::VersionCommon::name(); } }; /// @brief Definition of <b>"svid"</b> field. struct Svid : public comms::field::IntValue< ublox::field::FieldBase<>, std::uint8_t > { /// @brief Name of the field. static const char* name() { return ublox::message::MgaGloEphFieldsCommon::SvidCommon::name(); } }; /// @brief Definition of <b>"reserved1"</b> field. struct Reserved1 : public ublox::field::Res1< TOpt > { /// @brief Name of the field. static const char* name() { return ublox::message::MgaGloEphFieldsCommon::Reserved1Common::name(); } }; /// @brief Definition of <b>"FT"</b> field. struct FT : public comms::field::IntValue< ublox::field::FieldBase<>, std::uint8_t > { /// @brief Name of the field. static const char* name() { return ublox::message::MgaGloEphFieldsCommon::FTCommon::name(); } }; /// @brief Definition of <b>"B"</b> field. struct B : public comms::field::IntValue< ublox::field::FieldBase<>, std::uint8_t > { /// @brief Name of the field. static const char* name() { return ublox::message::MgaGloEphFieldsCommon::BCommon::name(); } }; /// @brief Definition of <b>"M"</b> field. struct M : public comms::field::IntValue< ublox::field::FieldBase<>, std::uint8_t > { /// @brief Name of the field. static const char* name() { return ublox::message::MgaGloEphFieldsCommon::MCommon::name(); } }; /// @brief Definition of <b>"H"</b> field. struct H : public comms::field::IntValue< ublox::field::FieldBase<>, std::int8_t > { /// @brief Name of the field. static const char* name() { return ublox::message::MgaGloEphFieldsCommon::HCommon::name(); } }; /// @brief Definition of <b>"x"</b> field. struct X : public comms::field::IntValue< ublox::field::FieldBase<>, std::int32_t, comms::option::def::ScalingRatio<1, 2048>, comms::option::def::UnitsKilometers > { /// @brief Name of the field. static const char* name() { return ublox::message::MgaGloEphFieldsCommon::XCommon::name(); } }; /// @brief Definition of <b>"y"</b> field. struct Y : public comms::field::IntValue< ublox::field::FieldBase<>, std::int32_t, comms::option::def::ScalingRatio<1, 2048>, comms::option::def::UnitsKilometers > { /// @brief Name of the field. static const char* name() { return ublox::message::MgaGloEphFieldsCommon::YCommon::name(); } }; /// @brief Definition of <b>"z"</b> field. struct Z : public comms::field::IntValue< ublox::field::FieldBase<>, std::int32_t, comms::option::def::ScalingRatio<1, 2048>, comms::option::def::UnitsKilometers > { /// @brief Name of the field. static const char* name() { return ublox::message::MgaGloEphFieldsCommon::ZCommon::name(); } }; /// @brief Definition of <b>"dx"</b> field. struct Dx : public comms::field::IntValue< ublox::field::FieldBase<>, std::int32_t, comms::option::def::ScalingRatio<1, 1048576L>, comms::option::def::UnitsKilometersPerSecond > { /// @brief Name of the field. static const char* name() { return ublox::message::MgaGloEphFieldsCommon::DxCommon::name(); } }; /// @brief Definition of <b>"dy"</b> field. struct Dy : public comms::field::IntValue< ublox::field::FieldBase<>, std::int32_t, comms::option::def::ScalingRatio<1, 1048576L>, comms::option::def::UnitsKilometersPerSecond > { /// @brief Name of the field. static const char* name() { return ublox::message::MgaGloEphFieldsCommon::DyCommon::name(); } }; /// @brief Definition of <b>"dz"</b> field. struct Dz : public comms::field::IntValue< ublox::field::FieldBase<>, std::int32_t, comms::option::def::ScalingRatio<1, 1048576L>, comms::option::def::UnitsKilometersPerSecond > { /// @brief Name of the field. static const char* name() { return ublox::message::MgaGloEphFieldsCommon::DzCommon::name(); } }; /// @brief Definition of <b>"ddx"</b> field. struct Ddx : public comms::field::IntValue< ublox::field::FieldBase<>, std::int8_t, comms::option::def::ScalingRatio<1, 1073741824L> > { /// @brief Name of the field. static const char* name() { return ublox::message::MgaGloEphFieldsCommon::DdxCommon::name(); } }; /// @brief Definition of <b>"ddy"</b> field. struct Ddy : public comms::field::IntValue< ublox::field::FieldBase<>, std::int8_t, comms::option::def::ScalingRatio<1, 1073741824L> > { /// @brief Name of the field. static const char* name() { return ublox::message::MgaGloEphFieldsCommon::DdyCommon::name(); } }; /// @brief Definition of <b>"ddz"</b> field. struct Ddz : public comms::field::IntValue< ublox::field::FieldBase<>, std::int8_t, comms::option::def::ScalingRatio<1, 1073741824L> > { /// @brief Name of the field. static const char* name() { return ublox::message::MgaGloEphFieldsCommon::DdzCommon::name(); } }; /// @brief Definition of <b>"tb"</b> field. struct Tb : public comms::field::IntValue< ublox::field::FieldBase<>, std::uint8_t, comms::option::def::ScalingRatio<15, 1>, comms::option::def::UnitsMinutes > { /// @brief Name of the field. static const char* name() { return ublox::message::MgaGloEphFieldsCommon::TbCommon::name(); } }; /// @brief Definition of <b>"gamma"</b> field. struct Gamma : public comms::field::IntValue< ublox::field::FieldBase<>, std::int16_t, comms::option::def::ScalingRatio<1, 0x10000000000LL> > { /// @brief Name of the field. static const char* name() { return ublox::message::MgaGloEphFieldsCommon::GammaCommon::name(); } }; /// @brief Definition of <b>"E"</b> field. struct E : public comms::field::IntValue< ublox::field::FieldBase<>, std::uint8_t, comms::option::def::UnitsDays > { /// @brief Name of the field. static const char* name() { return ublox::message::MgaGloEphFieldsCommon::ECommon::name(); } }; /// @brief Definition of <b>"deltaTau"</b> field. struct DeltaTau : public comms::field::IntValue< ublox::field::FieldBase<>, std::int8_t, comms::option::def::ScalingRatio<1, 1073741824L>, comms::option::def::UnitsSeconds > { /// @brief Name of the field. static const char* name() { return ublox::message::MgaGloEphFieldsCommon::DeltaTauCommon::name(); } }; /// @brief Definition of <b>"tau"</b> field. struct Tau : public comms::field::IntValue< ublox::field::FieldBase<>, std::int32_t, comms::option::def::ScalingRatio<1, 1073741824L>, comms::option::def::UnitsSeconds > { /// @brief Name of the field. static const char* name() { return ublox::message::MgaGloEphFieldsCommon::TauCommon::name(); } }; /// @brief Definition of <b>"reserved2"</b> field. struct Reserved2 : public ublox::field::Res4< TOpt > { /// @brief Name of the field. static const char* name() { return ublox::message::MgaGloEphFieldsCommon::Reserved2Common::name(); } }; /// @brief All the fields bundled in std::tuple. using All = std::tuple< Type, Version, Svid, Reserved1, FT, B, M, H, X, Y, Z, Dx, Dy, Dz, Ddx, Ddy, Ddz, Tb, Gamma, E, DeltaTau, Tau, Reserved2 >; }; /// @brief Definition of <b>"MGA-GLO-EPH"</b> message class. /// @details /// See @ref MgaGloEphFields for definition of the fields this message contains. /// @tparam TMsgBase Base (interface) class. /// @tparam TOpt Extra options /// @headerfile "ublox/message/MgaGloEph.h" template <typename TMsgBase, typename TOpt = ublox::options::DefaultOptions> class MgaGloEph : public comms::MessageBase< TMsgBase, typename TOpt::message::MgaGloEph, comms::option::def::StaticNumIdImpl<ublox::MsgId_MgaGlo>, comms::option::def::FieldsImpl<typename MgaGloEphFields<TOpt>::All>, comms::option::def::MsgType<MgaGloEph<TMsgBase, TOpt> >, comms::option::def::HasName > { // Redefinition of the base class type using Base = comms::MessageBase< TMsgBase, typename TOpt::message::MgaGloEph, comms::option::def::StaticNumIdImpl<ublox::MsgId_MgaGlo>, comms::option::def::FieldsImpl<typename MgaGloEphFields<TOpt>::All>, comms::option::def::MsgType<MgaGloEph<TMsgBase, TOpt> >, comms::option::def::HasName >; public: /// @brief Provide names and allow access to internal fields. /// @details See definition of @b COMMS_MSG_FIELDS_NAMES macro /// related to @b comms::MessageBase class from COMMS library /// for details. /// /// The generated types and functions are: /// @li @b Field_type type and @b field_type() fuction /// for @ref MgaGloEphFields::Type field. /// @li @b Field_version type and @b field_version() fuction /// for @ref MgaGloEphFields::Version field. /// @li @b Field_svid type and @b field_svid() fuction /// for @ref MgaGloEphFields::Svid field. /// @li @b Field_reserved1 type and @b field_reserved1() fuction /// for @ref MgaGloEphFields::Reserved1 field. /// @li @b Field_fT type and @b field_fT() fuction /// for @ref MgaGloEphFields::FT field. /// @li @b Field_b type and @b field_b() fuction /// for @ref MgaGloEphFields::B field. /// @li @b Field_m type and @b field_m() fuction /// for @ref MgaGloEphFields::M field. /// @li @b Field_h type and @b field_h() fuction /// for @ref MgaGloEphFields::H field. /// @li @b Field_x type and @b field_x() fuction /// for @ref MgaGloEphFields::X field. /// @li @b Field_y type and @b field_y() fuction /// for @ref MgaGloEphFields::Y field. /// @li @b Field_z type and @b field_z() fuction /// for @ref MgaGloEphFields::Z field. /// @li @b Field_dx type and @b field_dx() fuction /// for @ref MgaGloEphFields::Dx field. /// @li @b Field_dy type and @b field_dy() fuction /// for @ref MgaGloEphFields::Dy field. /// @li @b Field_dz type and @b field_dz() fuction /// for @ref MgaGloEphFields::Dz field. /// @li @b Field_ddx type and @b field_ddx() fuction /// for @ref MgaGloEphFields::Ddx field. /// @li @b Field_ddy type and @b field_ddy() fuction /// for @ref MgaGloEphFields::Ddy field. /// @li @b Field_ddz type and @b field_ddz() fuction /// for @ref MgaGloEphFields::Ddz field. /// @li @b Field_tb type and @b field_tb() fuction /// for @ref MgaGloEphFields::Tb field. /// @li @b Field_gamma type and @b field_gamma() fuction /// for @ref MgaGloEphFields::Gamma field. /// @li @b Field_e type and @b field_e() fuction /// for @ref MgaGloEphFields::E field. /// @li @b Field_deltaTau type and @b field_deltaTau() fuction /// for @ref MgaGloEphFields::DeltaTau field. /// @li @b Field_tau type and @b field_tau() fuction /// for @ref MgaGloEphFields::Tau field. /// @li @b Field_reserved2 type and @b field_reserved2() fuction /// for @ref MgaGloEphFields::Reserved2 field. COMMS_MSG_FIELDS_NAMES( type, version, svid, reserved1, fT, b, m, h, x, y, z, dx, dy, dz, ddx, ddy, ddz, tb, gamma, e, deltaTau, tau, reserved2 ); // Compile time check for serialisation length. static const std::size_t MsgMinLen = Base::doMinLength(); static const std::size_t MsgMaxLen = Base::doMaxLength(); static_assert(MsgMinLen == 48U, "Unexpected min serialisation length"); static_assert(MsgMaxLen == 48U, "Unexpected max serialisation length"); /// @brief Name of the message. static const char* doName() { return ublox::message::MgaGloEphCommon::name(); } }; } // namespace message } // namespace ublox
4532a0dd142389699a8739a7ab431f4dc63474c2
9557a0940de8ee41cb814a4177e419e202ff9188
/binTree/tree/Tree.cpp
1999c2d83b0b026f4756bdba2ba1b94b548c416c
[]
no_license
ljt141421/DataStructure
416a85d1ae28d394a1e4d6fd44ed72969f8cdded
613de0582bd9a80735f4a7c1a73947e3cf7ac7fb
refs/heads/master
2022-11-18T02:25:02.145547
2022-11-05T15:51:52
2022-11-05T15:51:52
194,282,918
3
0
null
null
null
null
UTF-8
C++
false
false
1,469
cpp
#include"Tree.h" void initTree(Tree *tree,ElemType ref) { tree->root=NULL; tree->refValue=ref; } void createTree(Tree *tree,char *str) { createTree(tree,tree->root,str); } void createTree(Tree *tree,TreeNode *&t,char *&str) { if(*str == tree->refValue) t=NULL; else { t=(TreeNode*)malloc(sizeof(TreeNode)); assert(t != NULL); t->data=*str; createTree(tree,t->firstChild,++str); createTree(tree,t->nextSibling,++str); } } TreeNode* root(Tree *tree) { return tree->root; } TreeNode* firstChild(Tree *tree) { return firstChild(tree->root); } TreeNode* firstChild(TreeNode *t) { if(t == NULL) return NULL; return t->firstChild; } TreeNode* nextSibling(Tree *tree) { return nextSibling(tree->root); } TreeNode* nextSibling(TreeNode *t) { if(t == NULL) return NULL; return t->nextSibling; } TreeNode* find(Tree *tree,ElemType key) { return find(tree->root,key); } TreeNode* find(TreeNode *t,ElemType key) { if(t == NULL) return NULL; if(t->data == key) return t; TreeNode *p=find(t->firstChild,key); if(p != NULL) return p; return find(t->nextSibling,key); } TreeNode* parent(Tree *tree,TreeNode *p) { return parent(tree->root,p); } TreeNode* parent(TreeNode *t,TreeNode *p) { if(t == NULL || p == NULL) return NULL; TreeNode *q=t->firstChild; TreeNode *par;//parent while(q != NULL && q != p) { par=parent(q,p); if(par != NULL) return par; q=q->nextSibling; } if(q != NULL && q==p) return t; return NULL; }
818ed4a97462a87feed0dad29f49ead70ce9942f
5b0c1f4bfe523e55e9ad2f7842a08b31be0410d3
/bitsgintp1_hackerrank/RepeatedString.cpp
ae6aaec5aa255728b8d477acc69df53101258c3a
[]
no_license
palash1611/Competitive_Coding
ffc437740a197d8bb9777d00e0c1d0076590edd2
45783550b46e023dc45a276da3a8e085dc790a52
refs/heads/master
2020-03-19T05:13:19.087112
2018-06-09T12:42:25
2018-06-09T12:42:25
135,910,767
0
0
null
null
null
null
UTF-8
C++
false
false
1,251
cpp
//https://www.hackerrank.com/contests/bitsgintp1/challenges/repeated-string #include <bits/stdc++.h> using namespace std; #define V vector typedef long long LL; typedef long double LD; typedef pair<int, int> pii; typedef V<int> vi; typedef V<string> vs; typedef V<LL> vll; typedef V<double> vd; typedef V<pii> vpii; #define ll long long #define rep(i,a) for(int i=0; i<(a); ++i) #define fov(i,a) rep(i,(a).size()) #define nl cout<<endl; #define fs first #define sc second #define pb push_back #define mp make_pair // Complete the repeatedString function below. long repeatedString(string s, long n) { long res=0; int size=s.length(); int a=0; int t = n/size; //t=t*size; int rem = n-(t*size); //cout<<n<<" "<<size<<" "<<t<<" "<<rem;nl; for(char& c : s) { if (c=='a') a++; } res=a*t; //cout<<res;nl; for(char& c : s) { if(rem==0) break; if (c=='a') res++; rem--; } //cout<<res;nl; return res; } int main() { //ofstream fout(getenv("OUTPUT_PATH")); string s; getline(cin, s); long n; cin >> n; //cin.ignore(numeric_limits<streamsize>::max(), '\n'); long result = repeatedString(s, n); cout << result << "\n"; // fout.close(); return 0; }
33917c4c5aa6bca1045854a49a356723b24ca811
cc7661edca4d5fb2fc226bd6605a533f50a2fb63
/mscorlib/ImageFileMachine.h
ff2c5c5c2c668938b38d0c533c2e7130ba9c3303
[ "MIT" ]
permissive
g91/Rust-C-SDK
698e5b573285d5793250099b59f5453c3c4599eb
d1cce1133191263cba5583c43a8d42d8d65c21b0
refs/heads/master
2020-03-27T05:49:01.747456
2017-08-23T09:07:35
2017-08-23T09:07:35
146,053,940
1
0
null
2018-08-25T01:13:44
2018-08-25T01:13:44
null
UTF-8
C++
false
false
195
h
#pragma once namespace System { namespace Reflection { class ImageFileMachine : public Enum // 0x0 { public: int value__; // 0x10 (size: 0x4, flags: 0x606, type: 0x8) }; // size = 0x18 }
8fb5f252d6caa80ac889665bf468119687dc17f9
1cdf0777a01cc71e78f4482c25609de89eee1b67
/client_lib.cpp
ef57d5b8d83671e02ff0c6b6bc106b205fd9916f
[]
no_license
ogolosovskiy/speed_test
9ef3fa5f61e7ec268910c99dce6db0bf40bd6363
891c48feecc6c55aff46eddd5ca9cb88be595685
refs/heads/master
2020-03-30T23:45:27.246754
2018-10-10T10:10:23
2018-10-10T10:10:23
151,712,343
0
0
null
null
null
null
UTF-8
C++
false
false
7,527
cpp
// // Created by Oleg Golosovskiy on 08/10/2018. // #include "client_lib.h" #include <sys/types.h> #include <sys/socket.h> #include <netdb.h> to_print_callback* g_logger = 0; #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wformat-security" template<typename ... Args> static void print_log(char const* fmt, Args ... args) { if(!g_logger) return; size_t size = snprintf(nullptr, 0, fmt, args ...) + 1; std::unique_ptr<char[]> buf(new char[size]); snprintf(buf.get(), size, fmt, args ...); std::string formatted(buf.get(), buf.get() + size - 1); (*g_logger)(formatted.c_str()); } #pragma clang diagnostic pop client_lib::client_lib(to_print_callback* log) { g_logger = log; } int client_lib::run_test(char const* server) { struct addrinfo hints, *res0 = nullptr; memset(&hints, 0, sizeof(hints)); hints.ai_family = PF_UNSPEC; hints.ai_socktype = SOCK_DGRAM; hints.ai_protocol = IPPROTO_UDP; hints.ai_flags = AI_PASSIVE; int error = getaddrinfo(server, std::to_string(SERVER_PORT).c_str(), &hints, &res0); if (error) { print_log("find_interface: syscall getaddrinfo failed: %s(%d) %s\n", strerror(error), error, server); return error; } sockaddr* server_addr = res0->ai_addr; socklen_t server_addr_len = res0->ai_addrlen; print_log("UDP Speed Test 1.1"); int sock; if ((sock = socket(server_addr->sa_family, SOCK_DGRAM, 0)) < 0) { print_log("could not create socket"); return -1; } struct timeval tv; tv.tv_sec = 0; tv.tv_usec = 500000; if (setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO,&tv,sizeof(tv)) < 0) { print_log("Error setsockopt"); return -1; } int av_desync = 0; int av_rtt = 0; int av_delivery = 0; int av_packet_lost = 0; // measure RTT without load and clock desync { print_log("Measuring RTT ..."); packet out; out._type = ETimeSync; int rtt[RTT_MAX_ATTEMPTS]; int clock_desync[RTT_MAX_ATTEMPTS]; NEGATIVE_RESET(rtt); NEGATIVE_RESET(clock_desync); int position = 0; for (int attempt = 0; attempt < RTT_MAX_ATTEMPTS; ++attempt) { //print_log("."); std::chrono::time_point<std::chrono::system_clock> now; now = std::chrono::system_clock::now(); time_sync_payload* payload = reinterpret_cast<time_sync_payload*>(&out._payload[0]); payload->_client_time_stamp = std::chrono::duration_cast<std::chrono::milliseconds>(now.time_since_epoch()).count(); ::sendto(sock, &out, sizeof(packet), 0, server_addr, server_addr_len); char recv_buffer[2048]; sockaddr_storage in_addr; socklen_t in_addr_len = sizeof(sockaddr_in); int len = ::recvfrom(sock, recv_buffer, sizeof(recv_buffer), 0, (sockaddr *) &in_addr, &in_addr_len); if (len == -1) { int err = errno; if (err == ETIMEDOUT || err == EAGAIN) { now = std::chrono::system_clock::now(); long err_time = std::chrono::duration_cast<std::chrono::milliseconds>( now.time_since_epoch()).count(); print_log("\ntime out %s %d", strerror(err), (int) (err_time - payload->_client_time_stamp)); continue; } print_log("\ncould not read from socket %s", strerror(err)); return 1; } else if (len == sizeof(recv_buffer)) { print_log("read buffer overflow"); continue; } // printf("received: %d byte from server %s", len, inet_ntoa(((sockaddr_in *) &in_addr)->sin_addr)); now = std::chrono::system_clock::now(); long milisecs2 = std::chrono::duration_cast<std::chrono::milliseconds>(now.time_since_epoch()).count(); packet *recv_packet = reinterpret_cast<packet *> (&recv_buffer[0]); time_sync_payload *recv_payload = reinterpret_cast<time_sync_payload *> (recv_packet->_payload); long recv_server_milisec = recv_payload->_server_time_stamp; long recv_client_start_milisec = recv_payload->_client_time_stamp; rtt[position] = milisecs2 - recv_client_start_milisec; long approx_server_time = milisecs2 - (rtt[position] / 2); clock_desync[position] = recv_server_milisec - approx_server_time; //print_log("rtt: %d clock desync: %d", rtt[position], clock_desync[position]); ++position; std::this_thread::sleep_for(std::chrono::milliseconds(250)); } av_desync = mediana(clock_desync); av_rtt = mediana(rtt); print_log("Average RTT: %d ms\nAverage clock out of synchronization: %d ms", av_rtt, av_desync ); } // make socket non blocking bool blocking = true; int flags = fcntl(sock, F_GETFL, 0); if (flags == -1) return 0; flags = blocking ? (flags & ~O_NONBLOCK) : (flags | O_NONBLOCK); if (fcntl(sock, F_SETFL, flags) == -1) return 0; long global_seqence_count = 0; int received_reports = 0; // 1.5 Upload MBits test { print_log("1.5 MBits upload - Measuring packet lost and latency ..."); packet out; int delivery_time[MAX_REPORTS]; NEGATIVE_RESET(delivery_time); int packet_lost[MAX_REPORTS]; NEGATIVE_RESET(packet_lost); for(int attempt = 0; attempt<LOAD_SERIES; ++attempt) { // send Media Packet // how much packets we will send for this set int packets = load_bits / 8 /*bits->bytes*/ / /*bytes->packets*/ sizeof(packet) / /*4 times per second*/ packets_per_seconds; out.clear(); out._type = ELoad; load_payload* payload = reinterpret_cast<load_payload*>(&out._payload[0]); payload->_load_set_count = attempt; payload->_load_set_packets = packets; long time_stamp_ms = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now().time_since_epoch()).count(); time_stamp_ms += av_desync; payload->_set_start_time_stamp = time_stamp_ms; //printf("send %d packest by %lu size", packets, sizeof(packet)); //print_log("."); for(int num_packet = 0; num_packet<packets; ++num_packet) { payload->_seqence_number = global_seqence_count++; ::sendto(sock, &out, sizeof(packet), 0, server_addr, server_addr_len); } std::this_thread::sleep_for(std::chrono::milliseconds(1000/packets_per_seconds)); // check stats packet char recv_buffer[load_statistic_buffer]; sockaddr_storage in_addr; socklen_t in_addr_len = sizeof(sockaddr_in); while(true) { int len = ::recvfrom(sock, recv_buffer, sizeof(recv_buffer), 0, (sockaddr *) &in_addr, &in_addr_len); if (len == -1) { int err = errno; if (err != ETIMEDOUT && err != EAGAIN) { print_log("could not read stat packet %s", strerror(err)); return 1; } break; } else if (len == sizeof(recv_buffer)) { print_log("read buffer overflow"); return 1; } else { //printf("received: %d byte from server %s", len, inet_ntoa(((sockaddr_in *) &in_addr)->sin_addr)); packet *recv_packet = reinterpret_cast<packet *> (&recv_buffer[0]); if (recv_packet->_type == ELoadStatistics) { packet *recv_packet = reinterpret_cast<packet *> (&recv_buffer[0]); statistics_payload *recv_stats = reinterpret_cast<statistics_payload *> (recv_packet->_payload); //printf("ELoadStatistics: count: %d delivery time: %d ms", recv_stats->_packets_count, recv_stats->_delivery_time); assert(received_reports<MAX_REPORTS); delivery_time[received_reports] = recv_stats->_delivery_time; packet_lost[received_reports] = recv_stats->_packet_lost; received_reports++; } } } } av_delivery = mediana(delivery_time); av_packet_lost = mediana(packet_lost); } if(received_reports==0) print_log("Stat server not responce"); else print_log("Upload %f MBits/sec average latency: %d ms, packet lost: %.2f%%", (float)load_bits/1000000, av_delivery, av_packet_lost/100.00); return 0; }
c9e26336b698723eb09076a6793616a152dd2565
6f9d495e097bbfe2ebe1dc01dc2149ec4f8372e0
/cpp/cpp04/ex03/Character.hpp
7e8c74f73b9f100d291f083bb74b0bb3a658cfa5
[]
no_license
nirgoth/nirgoth
abc22e2a4810c979be66a590c142dbd76a5d6fa0
4cc2b8e60cfc50d4ca7ee3dff45f1f1603ca7a07
refs/heads/master
2021-06-23T07:42:20.373983
2021-05-03T13:49:55
2021-05-03T13:49:55
223,377,216
0
0
null
null
null
null
UTF-8
C++
false
false
463
hpp
#ifndef CHARACTER_HPP # define CHARACTER_HPP # include "AMateria.hpp" class Character { private: std::string _name; AMateria *_inv[4] = {NULL, NULL, NULL, NULL}; Character(); public: Character(std::string name); ~Character(); Character(Character const &el); Character &operator=(Character const &el); std::string const &getName() const; void equip(AMateria *m); void unequip(int idx); void use(int idx, ICharacter &target); }; #endif
34957995c11b2fe45b30ca916ac9c99b8076d1d5
28b7078f834d6a16ff0f0bffc2ddad50bbc43536
/Memory_Management_Header/static_allocator.h
2352ed6d857eba2b3471a13b71a3745aa72c6c35
[]
no_license
ccpang96/SGI_STL
89289b57395d90d9b9a6a63c81243b3feeb7f029
d63d4630b9d096357aae7a617ccf813220784014
refs/heads/master
2020-12-11T23:43:35.979492
2020-01-15T08:52:46
2020-01-15T08:52:46
233,987,129
1
0
null
null
null
null
GB18030
C++
false
false
843
h
#pragma once #include <string> namespace static_allocator { //设计allocator1类去封装malloc和delete class allocator1 { private: struct obj { struct obj*next; //嵌入式指针 embedded pointer }; public: void* allocate(size_t); void deallocate(void*, size_t); private: obj * freeStore = nullptr; const int CHUNK = 5; //小一些以便观察 }; //实现Foo类去测试上面的allocator1类 class Foo { public: long L; std::string str; static allocator1 myAlloc; public: Foo(long l) : L(l) {} //重载Foo类的operator new static void* operator new(size_t size) { return myAlloc.allocate(size); } //重载Foo类的operator delete static void operator delete(void* pdead, size_t size) { return myAlloc.deallocate(pdead, size); } }; void static_allocator_function(); }
457af226f09b9954407a70c35b4b6c4b688c3255
575527ccc679f5c2718bb35eb58a5e4f470b11eb
/include/message_wrap.h
c1b0cd4ddbf7f48df5b4b58a2162bde038d5144e
[]
no_license
wukong2016/wukong
dd4fd9d11b93aea0c7223d26bc513e61ef464a56
a053391c57863782579db5f25a6f0aa7e02237a3
refs/heads/master
2020-12-24T20:32:36.107846
2016-05-10T02:07:14
2016-05-10T02:07:14
58,422,145
0
0
null
null
null
null
UTF-8
C++
false
false
740
h
#pragma once #include "query_basic_types.h" #include "network_node.h" #include "rdma_resource.h" #include "thread_cfg.h" #include "global_cfg.h" void SendR(thread_cfg* cfg,int r_mid,int r_tid,request_or_reply& r); request_or_reply RecvR(thread_cfg* cfg); bool TryRecvR(thread_cfg* cfg,request_or_reply& r); template<typename T> void SendObject(thread_cfg* cfg,int r_mid,int r_tid,T& r){ std::stringstream ss; boost::archive::binary_oarchive oa(ss); oa << r; cfg->node->Send(r_mid,r_tid,ss.str()); } template<typename T> T RecvObject(thread_cfg* cfg){ std::string str; str=cfg->node->Recv(); std::stringstream s; s << str; boost::archive::binary_iarchive ia(s); T r; ia >> r; return r; }
6e2cd9be1190ed93729bffe4719a50fa05661319
c4cf06c5b7e8e27d80fe276016efd7da2115b449
/Light.cpp
534498139fe8a06fa8a6e11d0977cbe9541c869f
[]
no_license
uans3k/u3krender
93f94a5ee3b345e6d5efde6ac554a9f6dd9d267b
2841d81941facd9768174842bb1fb65da921b6a8
refs/heads/master
2021-01-10T02:03:59.761353
2019-05-10T11:23:29
2019-05-10T11:23:29
53,245,333
0
0
null
null
null
null
UTF-8
C++
false
false
1,823
cpp
#include "stdafx.h" #include "Light.h" void Light::init(Point4D *pos, Vector4D *dir, Color ambient, Color diffuse, Color specular, float kc, float kl, float kq, float spotInner, float, float pf, int attr) { this->ambient = ambient; this->diffuse = diffuse; this->specular = specular; this->kc = kc; this->kl = kl; this->kq = kq; this->spotInner = spotInner; this->spotOutter = spotOutter; this->pf = pf; this->attr = attr; if (pos) { Point4D_Init(&oPos,pos); Point4D_Init(&tPos, &oPos); } if (dir) { Vector4D_Init(&oDir, dir); Vector4D_Normalize(&oDir); Vector4D_Init(&tDir,&oDir); } } void Light::initAmbientLight(Color ambient) { this->ambient = ambient; this->attr = LIGHT_ATTR_AMBIENT; open(); } void Light::initInfinityLight(Vector4D *dir,Color diffuse, Color specular) { this->diffuse = diffuse; this->specular = specular; if (dir) { Vector4D_Init(&oDir, dir); Vector4D_Normalize(&oDir); Vector4D_Init(&tDir, &oDir); } this->attr = LIGHT_ATTR_INFINITY; open(); } void Light::initPointLight(Point4D *pos, Color diffuse, Color specular, float kc, float kl, float kq) { this->diffuse = diffuse; this->specular = specular; this->kc = kc; this->kl = kl; this->kq = kq; if (pos) { Point4D_Init(&oPos, pos); Point4D_Init(&tPos, &oPos); } this->attr = LIGHT_ATTR_POINT; open(); } void Light::initSpotLight(Point4D * pos, Vector4D * dir, Color diffuse, Color specular, float kc, float kl, float kq,float pf) { this->diffuse = diffuse; this->specular = specular; this->kc = kc; this->kl = kl; this->kq = kq; this->pf = pf; if (pos) { Point4D_Init(&oPos, pos); Point4D_Init(&tPos, &oPos); } if (dir) { Vector4D_Init(&oDir, dir); Vector4D_Normalize(&oDir); Vector4D_Init(&tDir, &oDir); } this->attr = LIGHT_ATTR_SPOT; open(); }
02d1973b51d370b7d2b701461066ff3d31094db9
834b551c9e17345d761bc54c6a56c2de9002d6ac
/problems/234. Palindrome Linked List/two_pointer.cpp
0c72fcee42c8dfdc6135830fd3bb120d76f67216
[]
no_license
nullscc/leetcode
15507aecbb256acff0506bbc2bdb4dada113553b
95fbe47252b6f5e88378719fcdf3ee6200c68de4
refs/heads/main
2023-03-20T08:36:22.313209
2021-03-02T08:40:20
2021-03-02T08:40:20
330,892,647
0
0
null
null
null
null
UTF-8
C++
false
false
791
cpp
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode() : val(0), next(nullptr) {} * ListNode(int x) : val(x), next(nullptr) {} * ListNode(int x, ListNode *next) : val(x), next(next) {} * }; */ class Solution { public: bool isPalindrome(ListNode* head) { ListNode *fast=head, *slow=head; vector<int> s; while(fast && fast->next) { s.push_back(slow->val); slow = slow->next; fast = fast->next->next; } if(fast) { slow = slow->next; } int n = s.size()-1; while(n >= 0) { if(s[n--] != slow->val) return false; slow = slow->next; } return true; } };
7b040c87258aa6fe094d601d6f589386390d4bd5
15612c6affbeb98781e19f7de0d3f1db72cf1db9
/include/utility/relation_node.hpp
97e5891a725439904d443bf8903a71bbf70d4c53
[ "Apache-2.0" ]
permissive
federeghe/chronovise
332ad62ab046a2ff8ed1d03cf7e66a366717b630
4b332f10669af73f33e00f8749040eed9601bfb2
refs/heads/master
2023-02-24T05:25:51.369574
2021-12-08T10:31:26
2021-12-08T10:31:26
111,384,255
3
5
null
null
null
null
UTF-8
C++
false
false
2,009
hpp
/* * chronovise - Copyright 2018 Politecnico di Milano * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @file utility/relation_node.hpp * @author Check commit authors * @brief File containing the RelationNode and related classes/types */ #ifndef UTILITY_RELATION_NODE_HPP_ #define UTILITY_RELATION_NODE_HPP_ #include <list> #include <memory> #include <numeric> namespace chronovise { typedef enum class relation_node_e { UKNOWN, /** Error value, it should not be used */ TEST, /** Statistical test */ OPERATOR, /** Operator */ } relation_node_t; class RelationNode { public: RelationNode(relation_node_t type) : type(type) { } virtual ~RelationNode() { } relation_node_t get_type() const noexcept { return this->type; } void add_child(std::shared_ptr<RelationNode> rn); std::list<std::shared_ptr<RelationNode>>::const_iterator cbegin() const noexcept { return this->children.cbegin(); } std::list<std::shared_ptr<RelationNode>>::const_iterator cend() const noexcept { return this->children.cend(); } const std::list<std::shared_ptr<RelationNode>> & get_children() const noexcept { return this->children; } size_t get_local_size() const noexcept { return this->children.size(); } size_t get_total_size() const noexcept; private: relation_node_t type; std::list<std::shared_ptr<RelationNode>> children; }; } // namespace chronovise #endif
a9e134c7dfa6d503ca6630a59bac4f97a3bded4d
ddad5e9ee062d18c33b9192e3db95b58a4a67f77
/util/uring/sliding_counter.h
861d4797670e511d9b977b0c35817b122e9a5291
[ "BSD-2-Clause" ]
permissive
romange/gaia
c7115acf55e4b4939f8111f08e5331dff964fd02
8ef14627a4bf42eba83bb6df4d180beca305b307
refs/heads/master
2022-01-11T13:35:22.352252
2021-12-28T16:11:13
2021-12-28T16:11:13
114,404,005
84
17
BSD-2-Clause
2021-12-28T16:11:14
2017-12-15T19:20:34
C++
UTF-8
C++
false
false
3,177
h
// Copyright 2020, Beeri 15. All rights reserved. // Author: Roman Gershman ([email protected]) // #pragma once #include <array> #include <cstdint> #include <memory> #include <numeric> #include "util/uring/proactor_pool.h" namespace util { namespace uring { namespace detail { class SlidingCounterTLBase { protected: // Returns the bin corresponding to the current timestamp. Has second precision. // updates last_ts_ according to the current timestamp and returns the latest bin. // has const semantics even though it updates mutable last_ts_. uint32_t MoveTsIfNeeded(size_t size, int32_t* dest) const; mutable uint32_t last_ts_ = 0; }; class SlidingCounterBase { protected: void InitInternal(ProactorPool* pp); void CheckInit() const; unsigned ProactorThreadIndex() const; ProactorPool* pp_ = nullptr; }; } // namespace detail /** * @brief Sliding window data structure that can aggregate moving statistics. * It's implmented using ring-buffer with size specified at compile time. * * @tparam NUM */ template <unsigned NUM> class SlidingCounterTL : protected detail::SlidingCounterTLBase { static_assert(NUM > 1, "Invalid window size"); using T = int32_t; mutable std::array<T, NUM> count_; public: SlidingCounterTL() { Reset(); } void Inc() { IncBy(1); } void IncBy(int32_t delta) { int32_t bin = MoveTsIfNeeded(NUM, count_.data()); count_[bin] += delta; } // Sums over bins not including the last bin that is currently being filled. T SumTail() const; T Sum() const { MoveTsIfNeeded(NUM, count_.data()); return std::accumulate(count_.begin(), count_.end(), 0); } void Reset() { count_.fill(0); } }; // Requires proactor_pool initialize all the proactors. template <unsigned NUM> class SlidingCounter : protected detail::SlidingCounterBase { using Counter = SlidingCounterTL<NUM>; public: enum {WIN_SIZE = NUM}; SlidingCounter() = default; void Init(ProactorPool* pp) { InitInternal(pp); sc_thread_map_.reset(new Counter[pp_->size()]); } void Inc() { sc_thread_map_[ProactorThreadIndex()].Inc(); } uint32_t Sum() const { CheckInit(); std::atomic_uint32_t res{0}; pp_->AwaitOnAll([&](unsigned i, Proactor*) { res.fetch_add(sc_thread_map_[i].Sum(), std::memory_order_relaxed); }); return res.load(std::memory_order_release); } uint32_t SumTail() const { CheckInit(); std::atomic_uint32_t res{0}; pp_->AwaitOnAll([&](unsigned i, Proactor*) { res.fetch_add(sc_thread_map_[i].SumTail(), std::memory_order_relaxed); }); return res.load(std::memory_order_release); } private: std::unique_ptr<Counter[]> sc_thread_map_; }; /********************************************* Implementation section. **********************************************/ template <unsigned NUM> auto SlidingCounterTL<NUM>::SumTail() const -> T { int32_t start = MoveTsIfNeeded(NUM, count_.data()) + 1; // the tail is one after head. T sum = 0; for (unsigned i = 0; i < NUM - 1; ++i) { sum += count_[(start + i) % NUM]; } return sum; } } // namespace uring } // namespace util
c6ae62bae17c0ec324ca0aa0d67cbb08a72dce4d
b08e948c33317a0a67487e497a9afbaf17b0fc4c
/Display/Font.h
03d4940ce4ff0bfd662810249e01fff5b4dea7da
[]
no_license
15831944/bastionlandscape
e1acc932f6b5a452a3bd94471748b0436a96de5d
c8008384cf4e790400f9979b5818a5a3806bd1af
refs/heads/master
2023-03-16T03:28:55.813938
2010-05-21T15:00:07
2010-05-21T15:00:07
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,208
h
#ifndef __FONT_H__ #define __FONT_H__ #include "../Display/Display.h" namespace ElixirEngine { //----------------------------------------------------------------------------------------------- //----------------------------------------------------------------------------------------------- //----------------------------------------------------------------------------------------------- class DisplayFontText : public DisplayObject { public: DisplayFontText(); virtual ~DisplayFontText(); virtual void SetText(const wstring& _wstrText) = 0; virtual void SetColor(const Vector4& _f4Color) = 0; }; //----------------------------------------------------------------------------------------------- //----------------------------------------------------------------------------------------------- //----------------------------------------------------------------------------------------------- class DisplayFont : public CoreObject { public: DisplayFont(DisplayFontManagerRef _rFontManager); virtual ~DisplayFont(); virtual DisplayFontTextPtr CreateText() = 0; virtual void ReleaseText(DisplayFontTextPtr _pText) = 0; virtual DisplayRef GetDisplay() = 0; protected: DisplayFontManagerRef m_rFontManager; }; //----------------------------------------------------------------------------------------------- //----------------------------------------------------------------------------------------------- //----------------------------------------------------------------------------------------------- class DisplayFontLoader : public CoreObject { public: DisplayFontLoader(DisplayFontManagerRef _rFontManager); virtual ~DisplayFontLoader(); virtual DisplayFontPtr Load(const string& _strFileName) = 0; virtual void Unload(DisplayFontPtr _pFont) = 0; protected: DisplayFontManagerRef m_rFontManager; }; //----------------------------------------------------------------------------------------------- //----------------------------------------------------------------------------------------------- //----------------------------------------------------------------------------------------------- class DisplayFontManager : public CoreObject { public: DisplayFontManager(DisplayRef _rDisplay); virtual ~DisplayFontManager(); virtual bool Create(const boost::any& _rConfig); virtual void Update(); virtual void Release(); bool Load(const Key& _uNameKey, const string& _strFileName); void Unload(const Key& _uNameKey); DisplayFontPtr Get(const Key& _uNameKey); DisplayRef GetDisplay(); protected: struct Link { Link(); Link(DisplayFontPtr _pFont, DisplayFontLoaderPtr _pLoader); DisplayFontPtr m_pFont; DisplayFontLoaderPtr m_pLoader; }; typedef map<Key, Link> LinkMap; protected: bool RegisterLoader(const Key& _uExtensionKey, DisplayFontLoaderPtr _pLoader); void UnregisterLoader(const Key& _uExtensionKey); DisplayFontLoaderPtr GetLoader(const Key& _uExtensionKey); protected: DisplayRef m_rDisplay; LinkMap m_mFonts; DisplayFontLoaderPtrMap m_mLoaders; }; } #endif
[ "voodoohaust@97c0069c-804f-11de-81da-11cc53ed4329" ]
voodoohaust@97c0069c-804f-11de-81da-11cc53ed4329
d7a556185663cc98990de49e3175279a6e05f520
37421955fdae8ab64fa65c4fa91a6b2622bc14ef
/common/camera.h
99fbafcb7fdf33da12cbd11b8b3e59f06dd905d0
[]
no_license
SasaWakaba/Stelemate
c8ac4f49e4116911c044a9f559437c9b82d464bd
20c003206ff3ba2b987ef978a98c8fe0514f87ab
refs/heads/master
2020-09-05T18:52:41.011485
2020-03-29T11:53:39
2020-03-29T11:53:39
220,181,236
0
0
null
null
null
null
SHIFT_JIS
C++
false
false
857
h
#pragma once #include "Game_Object.h" class CCamera:public CGameObject { private: XMMATRIX m_ViewMatrix; RECT m_Viewport; static XMFLOAT3 m_Eye; //カメラ座標 static XMFLOAT3 m_at; //見てる場所(注視点) XMFLOAT3 m_CameraFront; //カメラの正面、長さ1 XMFLOAT3 m_CameraRight; //カメラの右側、長さ1 XMFLOAT3 m_CameraUp; //カメラの上、長さ1 float m_Length; //見てる場所までの長さ static bool bMove; static XMFLOAT3 MoveLength; static int cnt; public: void Initialize(); void Finalize(); void Update(); void Draw(); XMMATRIX* GetView(); static void SetAt(XMFLOAT3 pos) { m_at = pos; } static void Move(XMFLOAT3 at) { MoveLength = XMFLOAT3(at.x - m_at.x, at.y - m_at.y, at.z - m_at.z); bMove = true; cnt = 0; } static XMFLOAT3 GetEye() { return m_Eye; } };
cf3d8362f23fa1b071612e055f47c7515d2de9b0
2348000ede440b3513010c29a154ca70b22eb88e
/src/CPP/src/epi/chapter17/IsPatternContainedInGrid.hpp
e5104c7c368eb4a77f2e4bad62dec24a0a54f491
[]
no_license
ZhenyingZhu/ClassicAlgorithms
76438e02ecc813b75646df87f56d9588ffa256df
86c90c23ea7ed91e8ce5278f334f0ce6e034a38c
refs/heads/master
2023-08-27T20:34:18.427614
2023-08-25T06:08:00
2023-08-25T06:08:00
24,016,875
2
1
null
null
null
null
UTF-8
C++
false
false
1,200
hpp
#ifndef SRC_EPI_CHAPTER17_ISPATTERNCONTAINEDINGRID_HPP_ #define SRC_EPI_CHAPTER17_ISPATTERNCONTAINEDINGRID_HPP_ #include "../../Solution.h" #include <vector> #include <unordered_set> #include <tuple> namespace epi { namespace chapter17 { class IsPatternContainedInGrid : public myutils::Solution { public: IsPatternContainedInGrid(): Solution("EPI Chapter 17.5", "Search for a sequence in a 2D array", "Start from a cell, check if it could be a start of " "a subarray. Use hash table to record previous results.") { } ~IsPatternContainedInGrid() { } bool isPatternContainedInGrid(const std::vector<std::vector<int>> &grid, const std::vector<int> &pattern); bool test(); private: typedef int Offset; struct TupleHash; bool patternChecker(int x, int y, Offset offset, const std::vector<std::vector<int>> &grid, const std::vector<int> &pattern, std::unordered_set<std::tuple<int, int, Offset>, TupleHash> &failedCells); }; } // chapter17 } // epi #endif /* SRC_EPI_CHAPTER17_ISPATTERNCONTAINEDINGRID_HPP_ */
6fdde89259ba407174c3281cdb9aaca262f2bfc0
4d682826c92a14c3d8bb12a213130b8a6814b738
/Wires/wires.cpp
7e9d429cce7ae2d21c9e37dbda9e3e9d0698fad7
[]
no_license
FilipKernan/adventOfCodeCpp
1cc84bec2da5ef33e633d781f48face146b8347d
e1eea76ef56d1371fbb8876a5f83113c59a981c1
refs/heads/master
2022-11-21T17:13:22.890686
2020-07-21T18:04:54
2020-07-21T18:04:54
277,353,000
0
0
null
null
null
null
UTF-8
C++
false
false
3,648
cpp
// // Created by filip on 7/7/20. // #include "wires.h" std::vector<intersection> findIntersections(std::string string,int &height,int &width){ // creates an array for the wires to exist on long** wireArray = new long *[height]; for (int l = 0; l < height; ++l) { wireArray[l] = new long[width]; } fill(wireArray, height, width); // splits the puzzle input std::size_t found = string.find("\n", 1); std::string stringArray[2] = {string.substr(1, found), string.substr(found + 1)}; // creates a log of intersections std::vector<intersection> intersections; // loops though each wire for (int i = 0; i < 2; ++i) { int x = height/2, y = width/2; int size = 0; // splits wire instructions appart std::vector<std::string> stringVector = split(stringArray[i], size); long pastLength = 0; for (int j = 0; j < size; ++j) { // parsing the wire instructions std::string currentInstruction = stringVector[j]; char direction = currentInstruction[0]; int lenght = std::stoi(currentInstruction.substr(1)); for (int k = 0; k < lenght; ++k) { if (wireArray[y][x] > 0 && i == 1) { // logs any intersections that are detected intersection section; section.x = x; section.y = y; section.xSteps = pastLength + k; section.ySteps = wireArray[y][x]; intersections.push_back(section); } else { if (i <= 0 && wireArray[y][x] == 0) { wireArray[y][x] = pastLength + k; } } switch (direction) { case 'U': y++; break; case 'D': y--; break; case 'R': x++; break; case 'L': x--; break; } } pastLength += lenght ; } } return intersections; } // splits appart a string of instuctions to individual instuctions std::vector<std::string> split(std::string string, int& size){ size = std::count(string.begin(), string.end(), ',') + 1; std::vector<std::string> turnList; int lastTurn = 0; for (int j = 0; j < size; ++j) { turnList.push_back( string.substr(lastTurn, string.find(",", lastTurn + 1) - (lastTurn))); lastTurn = string.find(",", lastTurn + 1) + 1; } return turnList; } intersection findClosestManhatten(std::vector<intersection> intersections){ std::sort(intersections.begin(), intersections.end(), compareManhattenDistance); return intersections[0]; } intersection findClosestWireDistance(std::vector<intersection> intersections){ std::sort(intersections.begin(), intersections.end(), compareWireDistance); return intersections[0]; } // fills an array with 0s void fill(long** wireArray, int height, int width) { for (int i = 0; i < height; ++i) { for (int j = 0; j < width; ++j) { wireArray[i][j] = 0; } } } bool compareManhattenDistance( intersection &a, intersection &b){ return (abs(a.x - (ARRAY_SIZE/2)) + abs(a.y - (ARRAY_SIZE/2))) < (abs(b.x - (ARRAY_SIZE/2)) + abs(b.y - (ARRAY_SIZE/2))); } bool compareWireDistance( intersection &a, intersection &b) { return a.xSteps + a.ySteps < b.xSteps + b.ySteps; }
c71c2e6fb4831bd3611b792147154dbc6ecd989b
20049d88e2e8f0e1904efc561103c1d84d21507a
/bessonov.alexandr/common/circle.cpp
3cc59c615221d4b7f7f2fa7b8df6b9fbfd60b722
[]
no_license
gogun/Labs-for-SPbSPU-C-course-during-2019
5442a69152add3e66f02a7541e8dc8dd817f38a1
16ade47b859517a48d0fdb2e9704464bce4cc355
refs/heads/master
2022-01-09T16:02:54.728830
2019-06-06T11:06:33
2019-06-06T11:06:33
null
0
0
null
null
null
null
UTF-8
C++
false
false
833
cpp
#define _USE_MATH_DEFINES #include "circle.hpp" #include <iostream> #include <stdexcept> #include <cmath> bessonov::Circle::Circle(const bessonov::point_t &newCenter, double radius) : center_(newCenter), radius_(radius) { if (radius <= 0) { throw std::invalid_argument("Problematic radius"); } } void bessonov::Circle::move(double dx, double dy) { center_.x += dx; center_.y += dy; } void bessonov::Circle::move(const point_t &newCenter) { center_ = newCenter; } double bessonov::Circle::getArea() const { return M_PI * radius_ * radius_; } bessonov::rectangle_t bessonov::Circle::getFrameRect() const { return { 2 * radius_, 2 * radius_, center_ }; } void bessonov::Circle::scale(double factor) { if (factor <= 0) { throw std::invalid_argument("Problematic factor"); } radius_ *= factor; }
cec6705e458eb24c34267b6b01a44a90e8b29c02
119828e4a5a7bd3cec7360d47765e68a780fe34d
/Framework/Core/D3D11/OMStage/BlendState.cpp
9ba9fdd85887f311af31d83522d5a3aed346be0d
[]
no_license
JoSungHun/TerrianEditor
4b5b11cf0d672b114e0ab7d7940f674e232beae2
fb8c57dfe270df7e52dfd04e9e81c7b00b29f458
refs/heads/master
2020-06-05T03:53:00.212549
2019-06-17T08:33:19
2019-06-17T08:33:19
192,304,158
1
0
null
null
null
null
UTF-8
C++
false
false
3,741
cpp
#include "Framework.h" #include "BlendState.h" std::map<Factor, D3D11_BLEND> BlendState::blend_factors { std::make_pair(Factor::ZERO , D3D11_BLEND_ZERO), std::make_pair(Factor::ONE , D3D11_BLEND_ONE), std::make_pair(Factor::SRC_COLOR , D3D11_BLEND_SRC_COLOR), std::make_pair(Factor::INV_SRC_COLOR , D3D11_BLEND_INV_SRC_COLOR), std::make_pair(Factor::SRC_ALPHA , D3D11_BLEND_SRC_ALPHA), std::make_pair(Factor::INV_SRC_ALPHA , D3D11_BLEND_INV_SRC_ALPHA), std::make_pair(Factor::DEST_ALPHA , D3D11_BLEND_DEST_ALPHA), std::make_pair(Factor::INV_DEST_ALPHA , D3D11_BLEND_INV_DEST_ALPHA), std::make_pair(Factor::DEST_COLOR , D3D11_BLEND_DEST_COLOR), std::make_pair(Factor::INV_DEST_COLOR , D3D11_BLEND_INV_DEST_COLOR), }; std::map<Operation, D3D11_BLEND_OP> BlendState::blend_operations { std::make_pair(Operation::ADD , D3D11_BLEND_OP_ADD), std::make_pair(Operation::SUBTRACT , D3D11_BLEND_OP_SUBTRACT), std::make_pair(Operation::REV_SUBTRACT , D3D11_BLEND_OP_REV_SUBTRACT), std::make_pair(Operation::MIN , D3D11_BLEND_OP_MIN), std::make_pair(Operation::MAX , D3D11_BLEND_OP_MAX), }; std::map<ColorMask, D3D11_COLOR_WRITE_ENABLE> BlendState::blend_color_masks { std::make_pair(ColorMask::RED , D3D11_COLOR_WRITE_ENABLE_RED), std::make_pair(ColorMask::GREEN , D3D11_COLOR_WRITE_ENABLE_GREEN), std::make_pair(ColorMask::BLUE , D3D11_COLOR_WRITE_ENABLE_BLUE), std::make_pair(ColorMask::ALPHA , D3D11_COLOR_WRITE_ENABLE_ALPHA), std::make_pair(ColorMask::ALL , D3D11_COLOR_WRITE_ENABLE_ALL), }; auto BlendState::GetBitMask(const bool & blend_enable, const Factor & src_blend, const Factor & dest_blend, const Operation & blend_op, const Factor & src_blend_alpha, const Factor & dest_blend_alpha, const Operation & blend_op_alpha, const ColorMask & color_mask) -> const uint { return static_cast<uint>(blend_enable) | static_cast<uint>(src_blend) | static_cast<uint>(dest_blend) | static_cast<uint>(blend_op) | static_cast<uint>(src_blend_alpha) | static_cast<uint>(dest_blend_alpha) | static_cast<uint>(blend_op_alpha) | static_cast<uint>(color_mask); } BlendState::BlendState(Context * context) : state(nullptr) { graphics = context->GetSubsystem<Graphics>(); } BlendState::~BlendState() { Clear(); } auto BlendState::Create(const bool & blend_enable, const Factor & src_blend, const Factor & dest_blend, const Operation & blend_op, const Factor & src_blend_alpha, const Factor & dest_blend_alpha, const Operation & blend_op_alpha, const ColorMask & color_mask) -> const uint { D3D11_BLEND_DESC desc; ZeroMemory(&desc, sizeof(D3D11_BLEND_DESC)); desc.AlphaToCoverageEnable = false; desc.IndependentBlendEnable = false; desc.RenderTarget[0].BlendEnable = blend_enable; desc.RenderTarget[0].SrcBlend = blend_factors[src_blend]; desc.RenderTarget[0].DestBlend = blend_factors[dest_blend]; desc.RenderTarget[0].BlendOp = blend_operations[blend_op]; desc.RenderTarget[0].SrcBlendAlpha = blend_factors[src_blend_alpha]; desc.RenderTarget[0].DestBlendAlpha = blend_factors[dest_blend_alpha]; desc.RenderTarget[0].BlendOpAlpha = blend_operations[blend_op_alpha]; desc.RenderTarget[0].RenderTargetWriteMask = blend_color_masks[color_mask]; auto result = SUCCEEDED(graphics->GetDevice()->CreateBlendState(&desc, &state)); if (!result) { LOG_ERROR("Failed to create blend state"); return 0; } return GetBitMask ( blend_enable, src_blend, dest_blend, blend_op, src_blend_alpha, dest_blend_alpha, blend_op_alpha, color_mask ); } void BlendState::Clear() { SAFE_RELEASE(state); } void BlendState::BindPipeline() { float blend_factor[4]{ 0.0f,0.0f,0.0f,0.0f }; graphics->GetDeviceContext()->OMSetBlendState(state, blend_factor, 0xffffffff); }
d22d8a8843200b30a97c610fe6081041957d9b54
a72916978618f0978974e58be661bb347a28bb10
/plugins/Project/vlSaveProject.h
d9281e79952cadbc2103fbfdd37a97b0270f159f
[]
no_license
Armida220/drv2.0
a77523c163ee6887cccb648b833de3bbe1c840fe
5b2610fd2159ad1408608c35f5d4bef4e64127ba
refs/heads/master
2020-04-10T10:03:12.552174
2018-07-19T02:40:40
2018-07-19T02:40:40
null
0
0
null
null
null
null
UTF-8
C++
false
false
851
h
#pragma once #include "UIPlugins.h" #include "x3py/module/classmacro.h" //#include "ProjectObserver.h" #include "UIPluginsEvents.h" USING_NAMESPACE_EARTHMATRIX const char* const clsidvlSaveProject = "00000000-6000-0000-0000-000000000002"; class CvlSaveProject : public IUICommon, public IUICommand, public IAnythingEventObserver { X3BEGIN_CLASS_DECLARE(CvlSaveProject, clsidvlSaveProject) X3DEFINE_INTERFACE_ENTRY(IUICommon) X3DEFINE_INTERFACE_ENTRY(IUICommand) X3END_CLASS_DECLARE() public: CvlSaveProject(void); ~CvlSaveProject(void); public: // IUICommon virtual bool Initialize(); virtual bool UnInitialize(); virtual bool SetBuddy(x3::IObject* val); virtual bool OnAnything2(x3::IObject* sender, const std::string& eventKey, const std::string& filename); // IUICommand virtual bool OnClick(); void SaveProject(); };
050df6bcfe398a091ab5348c45947ad92f8822eb
4441cd8e9c5049016c42f03d5c2da893ac294505
/include/demons.h
3ce5e25b0aaeb30b733d51ddbc8576d7e2de2fee
[]
no_license
yourDM-tristan-j/ex08-creatures
17372e78f6dbcdcd8cdfafd2ee91572226ab3586
43abaa3fdc15cd6b825024bcedb18f05775ed0eb
refs/heads/master
2020-04-10T00:56:00.028114
2018-12-06T17:49:12
2018-12-06T17:49:12
160,700,398
0
0
null
2018-12-06T16:16:49
2018-12-06T16:16:48
null
UTF-8
C++
false
false
1,395
h
class Demons : public Creature { private: } static const std::string CYBERDEMON_NAME = "CyberDemon"; static const std::string BALROG_NAME = "BALROG"; class Cyberdemon : public Demons{ private: int type = 1; int strength = DEFAULT_STRENGTH; int strength = DEFAULT_HIT_POINTS; const string &getSpecies() const { return CYBERDEMON_NAME; }; public : Creature( ); // Initialize to human, 10 strength, 10 hit points Creature( int newType, int newStrength, int newHit); // Initialize creature to new type, strength, hit points // Also add appropriate accessor and mutator functions // for type, strength, and hit points int getDamage(); // Returns amount of damage this creature // inflicts in one round of combat }; class Balrog : public Demons { private: int type = 2; int strength = DEFAULT_STRENGTH; int strength = DEFAULT_HIT_POINTS; const string &getSpecies() const { return BALROG_NAME; }; public : Creature( ); // Initialize to human, 10 strength, 10 hit points Creature( int newType, int newStrength, int newHit); // Initialize creature to new type, strength, hit points // Also add appropriate accessor and mutator functions // for type, strength, and hit points int getDamage(); // Returns amount of damage this creature // inflicts in one round of combat };
39f254028246b96f1f7f1493dd100052b2867c5f
8de91a1aebb00600a98a69b7b8c783cb6a020720
/cp/MaxFlow.cpp
05ef8dbcd14733a3b3738e3a9485ab2cd295f79c
[]
no_license
RenatoBrittoAraujo/Competitive-Programming
2148d5fc4b0ac4b8fdbadc8de2916b31a549e183
de641f129a1ce27deffb7bf7c1635d702d05bf3e
refs/heads/master
2020-05-22T21:17:41.420014
2019-05-17T00:39:20
2019-05-17T00:39:20
186,523,234
0
0
null
null
null
null
UTF-8
C++
false
false
1,340
cpp
#include <bits/stdc++.h> using namespace std; #define MAX_V 1500 //more than this and maxflow takes too long #define inf 1000000 using vi = vector<int>; int G[MAX_V][MAX_V]; vi p; int mf,f,s,t; void augment(int v,int me){ if(v==s){ f=me; return; }else if(p[v]!=-1){ augment(p[v],min(me,G[p[v]][v])); G[p[v]][v]-=f; G[v][p[v]]+=f; } } int main(){ //SET 't' (sink), 's' (source), and the 'G' graph to run max flow //print graph for(int i=0;i<n+2;i++){ for(int j=0;j<n+2;j++){ printf(" %5d",G[i][j]); }printf("\n"); } //MAX FLOW BFS LOOP mf=0; while(1){ f=0; vi dist(MAX_V, inf); dist[s]=0; queue<int> q; q.push(s); p.assign(MAX_V,-1); while(!q.empty()){ int u = q.front(); q.pop(); if(t==u)break; for(int v=0;v<MAX_V;v++) if(G[u][v]>0&&dist[v]==inf) dist[v]=dist[u]+1,q.push(v),p[v]=u; } augment(t,inf); if(f==0)break; mf+=f; } //mf is the maxflow value, n-mf=mcbm, in a bipartite graph mcbm = mis (max independent set) } return 0; }