blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
3
264
content_id
stringlengths
40
40
detected_licenses
listlengths
0
85
license_type
stringclasses
2 values
repo_name
stringlengths
5
140
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
986 values
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
3.89k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
23 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
145 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
3
10.4M
extension
stringclasses
122 values
content
stringlengths
3
10.4M
authors
listlengths
1
1
author_id
stringlengths
0
158
cd3c07c14ca2847f72938142221099bb3ef950c5
dfd7839ae278804d6639cbb770407fa3a1346c73
/4_singleton/SingletonA.h
1f825f1637f7f4c53aeed764d57469a9da773309
[]
no_license
BobLiao1987/designpattern
fa6d753d01708f5c350ccfab43add89f8c6d4332
de2425699632d0614ace6dc9946180045bc8d75a
refs/heads/master
2021-01-18T18:42:27.386619
2016-08-15T16:54:17
2016-08-15T16:54:17
65,748,359
0
1
null
null
null
null
UTF-8
C++
false
false
184
h
#pragma once #include "Singleton.h" class SingletonA: public Singleton { friend class Singleton; public: void Show(){cout<<"SingletonA"<<endl;} private: SingletonA(){} };
[ "liaofangbo@163.com" ]
liaofangbo@163.com
ba1e39fc010d67160abfdd217bc4c8fea11afdcb
9a3b9d80afd88e1fa9a24303877d6e130ce22702
/src/Providers/UNIXProviders/ReplicaPairView/UNIX_ReplicaPairViewProvider.cpp
e9e2df0a8ee2adaf8644d7ccb74fe2a2ddb11a8c
[ "MIT" ]
permissive
brunolauze/openpegasus-providers
3244b76d075bc66a77e4ed135893437a66dd769f
f24c56acab2c4c210a8d165bb499cd1b3a12f222
refs/heads/master
2020-04-17T04:27:14.970917
2015-01-04T22:08:09
2015-01-04T22:08:09
19,707,296
0
0
null
null
null
null
UTF-8
C++
false
false
8,047
cpp
//%LICENSE//////////////////////////////////////////////////////////////// // // Licensed to The Open Group (TOG) under one or more contributor license // agreements. Refer to the OpenPegasusNOTICE.txt file distributed with // this work for additional information regarding copyright ownership. // Each contributor licenses this file to you under the OpenPegasus Open // Source License; you may not use this file except in compliance with the // License. // // 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 "UNIX_ReplicaPairViewProvider.h" using PROVIDER_LIB_NS::CIMHelper; UNIX_ReplicaPairViewProvider::UNIX_ReplicaPairViewProvider() { } UNIX_ReplicaPairViewProvider::~UNIX_ReplicaPairViewProvider() { } CIMInstance UNIX_ReplicaPairViewProvider::constructInstance( const CIMName &className, const CIMNamespaceName &nameSpace, const UNIX_ReplicaPairView &instanceObject) const { CIMProperty p; CIMInstance inst(className); // Set path inst.setPath(CIMObjectPath(String(""), // hostname nameSpace, className, constructKeyBindings(instanceObject))); //CIM_ManagedElement Properties if (instanceObject.getInstanceID(p)) inst.addProperty(p); if (instanceObject.getCaption(p)) inst.addProperty(p); if (instanceObject.getDescription(p)) inst.addProperty(p); if (instanceObject.getElementName(p)) inst.addProperty(p); if (instanceObject.getGeneration(p)) inst.addProperty(p); if (className.equal("CIM_ManagedElement")) return inst; //CIM_View Properties if (className.equal("CIM_View")) return inst; //CIM_LogicalDeviceView Properties if (className.equal("CIM_LogicalDeviceView")) return inst; //CIM_ReplicaPairView Properties if (instanceObject.getSVSourceSystemCreationClassName(p)) inst.addProperty(p); if (instanceObject.getSVSourceSystemName(p)) inst.addProperty(p); if (instanceObject.getSVSourceCreationClassName(p)) inst.addProperty(p); if (instanceObject.getSVSourceDeviceID(p)) inst.addProperty(p); if (instanceObject.getSVSourceName(p)) inst.addProperty(p); if (instanceObject.getSVSourceNameFormat(p)) inst.addProperty(p); if (instanceObject.getSVSourceNameNamespace(p)) inst.addProperty(p); if (instanceObject.getSVSourceExtentStatus(p)) inst.addProperty(p); if (instanceObject.getSVSourceOperationalStatus(p)) inst.addProperty(p); if (instanceObject.getSVSourceBlockSize(p)) inst.addProperty(p); if (instanceObject.getSVSourceNumberOfBlocks(p)) inst.addProperty(p); if (instanceObject.getSVSourceConsumableBlocks(p)) inst.addProperty(p); if (instanceObject.getSVSourcePrimordial(p)) inst.addProperty(p); if (instanceObject.getSVSourceIsBasedOnUnderlyingRedundancy(p)) inst.addProperty(p); if (instanceObject.getSVSourceNoSinglePointOfFailure(p)) inst.addProperty(p); if (instanceObject.getSVSourceDataRedundancy(p)) inst.addProperty(p); if (instanceObject.getSVSourcePackageRedundancy(p)) inst.addProperty(p); if (instanceObject.getSVSourceDeltaReservation(p)) inst.addProperty(p); if (instanceObject.getSVSourceExtentDiscriminator(p)) inst.addProperty(p); if (instanceObject.getSVSourceOtherIdentifyingInfo(p)) inst.addProperty(p); if (instanceObject.getSVSourceIdentifyingDescriptions(p)) inst.addProperty(p); if (instanceObject.getSVSourceElementName(p)) inst.addProperty(p); if (instanceObject.getSVSourceUsage(p)) inst.addProperty(p); if (instanceObject.getSVSourceOtherUsageDescription(p)) inst.addProperty(p); if (instanceObject.getSVSourceClientSettableUsage(p)) inst.addProperty(p); if (instanceObject.getSSWhenSynced(p)) inst.addProperty(p); if (instanceObject.getSSSyncMaintained(p)) inst.addProperty(p); if (instanceObject.getSSCopyType(p)) inst.addProperty(p); if (instanceObject.getSSSyncState(p)) inst.addProperty(p); if (instanceObject.getSSCopyPriority(p)) inst.addProperty(p); if (instanceObject.getSSSyncType(p)) inst.addProperty(p); if (instanceObject.getSSMode(p)) inst.addProperty(p); if (instanceObject.getSSProgressStatus(p)) inst.addProperty(p); if (instanceObject.getSVTargetSystemCreationClassName(p)) inst.addProperty(p); if (instanceObject.getSVTargetSystemName(p)) inst.addProperty(p); if (instanceObject.getSVTargetCreationClassName(p)) inst.addProperty(p); if (instanceObject.getSVTargetDeviceID(p)) inst.addProperty(p); if (instanceObject.getSVTargetName(p)) inst.addProperty(p); if (instanceObject.getSVTargetNameFormat(p)) inst.addProperty(p); if (instanceObject.getSVTargetNameNamespace(p)) inst.addProperty(p); if (instanceObject.getSVTargetExtentStatus(p)) inst.addProperty(p); if (instanceObject.getSVTargetOperationalStatus(p)) inst.addProperty(p); if (instanceObject.getSVTargetBlockSize(p)) inst.addProperty(p); if (instanceObject.getSVTargetNumberOfBlocks(p)) inst.addProperty(p); if (instanceObject.getSVTargetConsumableBlocks(p)) inst.addProperty(p); if (instanceObject.getSVTargetPrimordial(p)) inst.addProperty(p); if (instanceObject.getSVTargetIsBasedOnUnderlyingRedundancy(p)) inst.addProperty(p); if (instanceObject.getSVTargetNoSinglePointOfFailure(p)) inst.addProperty(p); if (instanceObject.getSVTargetDataRedundancy(p)) inst.addProperty(p); if (instanceObject.getSVTargetPackageRedundancy(p)) inst.addProperty(p); if (instanceObject.getSVTargetDeltaReservation(p)) inst.addProperty(p); if (instanceObject.getSVTargetExtentDiscriminator(p)) inst.addProperty(p); if (instanceObject.getSVTargetOtherIdentifyingInfo(p)) inst.addProperty(p); if (instanceObject.getSVTargetIdentifyingDescriptions(p)) inst.addProperty(p); if (instanceObject.getSVTargetElementName(p)) inst.addProperty(p); if (instanceObject.getSVTargetUsage(p)) inst.addProperty(p); if (instanceObject.getSVTargetOtherUsageDescription(p)) inst.addProperty(p); if (instanceObject.getSVTargetClientSettableUsage(p)) inst.addProperty(p); return inst; } Array<CIMKeyBinding> UNIX_ReplicaPairViewProvider::constructKeyBindings(const UNIX_ReplicaPairView& instanceObject) const { Array<CIMKeyBinding> keys; keys.append(CIMKeyBinding( PROPERTY_S_V_TARGET_SYSTEM_CREATION_CLASS_NAME, instanceObject.getSVTargetSystemCreationClassName(), CIMKeyBinding::STRING)); keys.append(CIMKeyBinding( PROPERTY_S_V_TARGET_SYSTEM_NAME, instanceObject.getSVTargetSystemName(), CIMKeyBinding::STRING)); keys.append(CIMKeyBinding( PROPERTY_S_V_TARGET_CREATION_CLASS_NAME, instanceObject.getSVTargetCreationClassName(), CIMKeyBinding::STRING)); keys.append(CIMKeyBinding( PROPERTY_S_V_TARGET_DEVICE_ID, instanceObject.getSVTargetDeviceID(), CIMKeyBinding::STRING)); return keys; } #define UNIX_PROVIDER UNIX_ReplicaPairViewProvider #define UNIX_PROVIDER_NAME "UNIX_ReplicaPairViewProvider" #define CLASS_IMPLEMENTATION UNIX_ReplicaPairView #define CLASS_IMPLEMENTATION_NAME "UNIX_ReplicaPairView" #define BASE_CLASS_NAME "CIM_ReplicaPairView" #define NUMKEYS_CLASS_IMPLEMENTATION 4 #include "UNIXProviderBase.hpp"
[ "brunolauze@msn.com" ]
brunolauze@msn.com
864f28789aa3b32ce4ac57671d90f455b42456f6
70d160671ef29470ce17debfe786400f02fbeb73
/cpp/include/cudf/dictionary/dictionary_column_view.hpp
16c7250f4b83124f9cff40539f9a28c900d28e2c
[ "Apache-2.0" ]
permissive
benfred/cudf
1c3d0b0e3c9d7879c329bb9ea1b8b7d1c6eb8be7
3cd4c9f0602840dddb9a0e247d5a0bcf3d7266e1
refs/heads/branch-0.14
2023-07-10T05:26:54.971778
2020-04-09T19:29:29
2020-04-09T19:29:29
254,483,116
1
0
Apache-2.0
2020-04-09T21:34:52
2020-04-09T21:34:50
null
UTF-8
C++
false
false
2,307
hpp
/* * Copyright (c) 2020, NVIDIA CORPORATION. * * 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. */ #pragma once #include <cudf/column/column_view.hpp> #include <cudf/column/column.hpp> namespace cudf { /** * @brief A wrapper class for operations on a dictionary column. * * A dictionary column contains a set of keys and a column of indices. * The keys are a sorted set of unique values for the column. * The indices represent the corresponding positions of each element's * value in the keys. */ class dictionary_column_view : private column_view { public: dictionary_column_view( column_view const& dictionary_column ); dictionary_column_view( dictionary_column_view&& dictionary_view ) = default; dictionary_column_view( const dictionary_column_view& dictionary_view ) = default; ~dictionary_column_view() = default; dictionary_column_view& operator=(dictionary_column_view const&) = default; dictionary_column_view& operator=(dictionary_column_view&&) = default; using column_view::size; using column_view::null_mask; using column_view::null_count; using column_view::has_nulls; using column_view::offset; /** * @brief Returns the parent column. */ column_view parent() const noexcept; /** * @brief Returns the column of indices */ column_view indices() const noexcept; /** * @brief Returns a column_view combining the indices data * with offset, size, and nulls from the parent. */ column_view get_indices_annotated() const noexcept; /** * @brief Returns the column of keys */ column_view keys() const noexcept; /** * @brief Returns the number of rows in the keys column. */ size_type keys_size() const noexcept; }; } // namespace cudf
[ "dwendt@nvidia.com" ]
dwendt@nvidia.com
1ddadb3bd66285939c9241fd5d6b2c1db4ef09c2
3a39b41a8f76d7d51b48be3c956a357cc183ffae
/Codeforces/EducationalRound/E71_D2/A.cpp
bd3e09566fe84f3d98b1a775a9f46367c717ec28
[]
no_license
Acka1357/ProblemSolving
411facce03d6bf7fd4597dfe99ef58eb7724ac65
17ef7606af8386fbd8ecefcc490a336998a90b86
refs/heads/master
2020-05-05T10:27:43.356584
2019-11-07T06:23:11
2019-11-07T06:23:11
179,933,949
0
0
null
null
null
null
UTF-8
C++
false
false
391
cpp
#include <cstdio> #include <algorithm> using namespace std; int main() { int tc; for(scanf("%d", &tc); tc--;){ int B, P, F, H, C; scanf("%d %d %d %d %d", &B, &P, &F, &H, &C); int ans = 0; for(int i = 0; i <= P; i++){ int pcnt = min(B / 2, i); int s1 = pcnt * H; int s2 = min((B - pcnt * 2) / 2, F) * C; ans = max(ans, s1 + s2); } printf("%d\n", ans); } return 0; }
[ "Acka1357@gmail.com" ]
Acka1357@gmail.com
d4d7b36422da6c5b71e8cb6a4d86f55ecd8e436a
6902f31f69e00a1a6c5dd99a7512566ced96f0b2
/cutRod.cpp
bf0b5891bbb3e48981b813c775afebeb3f5a99e9
[]
no_license
AnusreeK-2000/ADA_1BM18CS017
6b820bcf1ebffd7925a321721fda336f1a366314
1e8c70af12dc406351b42ceb03f6db76f9e0cfeb
refs/heads/master
2020-12-23T12:36:39.410343
2020-05-02T07:41:39
2020-05-02T07:41:39
237,154,864
0
3
null
null
null
null
UTF-8
C++
false
false
1,380
cpp
/* Given a rod of length ‘n’ inches and an array of prices that contains prices of all pieces of size smaller than ‘n’. Determine the maximum value obtainable by cutting up the rod and selling the pieces. For example, if length of the rod is 8 and the values of different pieces are given as following, then the maximum obtainable value is 22 (by cutting in two pieces of lengths 2 and 6) ‌ length | 1 2 3 4 5 6 7 8 price | 1 5 8 9 10 17 17 20 ‌ And if the prices are as following, then the maximum obtainable value is 24 (by cutting in eight pieces of length 1) ‌ length | 1 2 3 4 5 6 7 8 price | 3 5 8 9 10 17 17 20 ‌*/ #include<bits/stdc++.h> using namespace std; int cutRod(int price[], int n) { int val[n+1]; val[0] = 0; int i, j; for (i = 1; i<=n; i++) { int maximum = -99; for (j = 0; j < i; j++) maximum = max(maximum, price[j] + val[i-j-1]); val[i] = maximum; } return val[n]; } int main() { int n; cout<<"Enter the length of the rod"<<endl; cin>>n; int price[n]; cout<<"Enter the price of each piece"<<endl; for(int i=0;i<n;i++) cin>>price[i]; cout<<"The maximum obtainable value is : "<<cutRod(price,n)<<endl; return 0; } /*output Enter the length of the rod 8 Enter the price of each piece 1 5 8 9 10 17 17 20 The maximum obtainable value is : 22 */
[ "noreply@github.com" ]
AnusreeK-2000.noreply@github.com
298011ae6766e0eda483299abbf9eae11fa874c1
99d3989754840d95b316a36759097646916a15ea
/tags/2011_09_07_to_baoxin_gpd_0.1/ferrylibs/src/ferry/cv_geometry/Camera.h
a925ad8f7c346848a3d6e35356fc590127df3113
[]
no_license
svn2github/ferryzhouprojects
5d75b3421a9cb8065a2de424c6c45d194aeee09c
482ef1e6070c75f7b2c230617afe8a8df6936f30
refs/heads/master
2021-01-02T09:20:01.983370
2011-10-20T11:39:38
2011-10-20T11:39:38
11,786,263
1
0
null
null
null
null
UTF-8
C++
false
false
6,767
h
#pragma once #include <vector> #include "highgui.h" #include "cv.h" #include "CvMatUtil.h" using namespace std; using namespace ferry::cv_mat; namespace ferry { namespace cv_geometry { class Camera { public: //P = K[R|t], t = -RC Camera(double f, const CvPoint3D32f& origin, const CvPoint3D32f& viewDirection, const CvPoint3D32f& upDirection) { R = calcR(viewDirection, upDirection); o = origin; C = CvMatUtil::matFromPoint3D(origin); HC = CvMatUtil::hmatFromMat(C); t = cvCreateMat(3, 1, CV_64FC1); cvMatMul(R, C, t); cvScale(t, t, -1); //cout<<"R "<<CvMatUtil::matString(R)<<endl; //cout<<"C "<<CvMatUtil::matString(C)<<endl; //cout<<"t "<<CvMatUtil::matString(t)<<endl; NP = cvCreateMat(3, 4, CV_64FC1); CvMatUtil::setSubRect(NP, R, cvRect(0, 0, 3, 3)); CvMatUtil::setCol(NP, t, 3); //cout<<"[R|t]: \r\n"<<CvMatUtil::matString(NP)<<endl; K = createCalibrationMatrix(f); //cout<<"K "<<K<<endl; P = cvCreateMat(3, 4, CV_64FC1); cvMatMul(K, NP, P); cout<<"Camera Matrix: \r\n"<<CvMatUtil::matString(P)<<endl; } Camera(CvMat* K, CvMat* NP) { this->K = K; this->NP = NP; P = cvCreateMat(3, 4, CV_64FC1); cvMatMul(K, NP, P); R = cvCreateMat(3, 3, CV_64FC1); CvMatUtil::copyCols(NP, R, 0, 3); t = cvCreateMat(3, 1, CV_64FC1); CvMatUtil::copyCol(NP, t, 3); HC = CvMatUtil::null(P); C = CvMatUtil::hmatToMat(HC); o = CvMatUtil::hmatToPoint3D(HC); } Camera(CvMat* K, CvMat* R, CvMat* t) { this->K = K; NP = cvCreateMat(3, 4, CV_64FC1); setCols(NP, R, 0, 3); setCol(NP, t, 3); this->R = R; this->t = t; P = matMul(K, NP); HC = null(P); C = hmatToMat(HC); o = hmatToPoint3D(HC); } public: CvPoint2D32f calcImagePoint(CvPoint3D32f X) { return calcImagePoint(P, X); } vector<CvPoint2D32f> calcImagePoints(const vector<CvPoint3D32f>& Xs) { return calcImagePoints(P, Xs); } CvPoint2D32f calcImagePoint(CvMat* mX) { return calcImagePoint(P, mX); } CvPoint3D32f calcPoint3DWithDepth(CvPoint2D32f p, double depth) { return calcPoint3DWithDepth(P, p, depth); } //calc point coordinates in camera coordinates system //Xs: points in world coordinates system //out: points in camera coordinates system vector<CvPoint3D32f> calcCoordPoints(const vector<CvPoint3D32f>& Xs) { vector<CvPoint3D32f> nps; for (int i = 0; i < (int)Xs.size(); i++) { nps.push_back(calcCoordPoint(Xs[i])); } return nps; } CvPoint3D32f calcCoordPoint(const CvPoint3D32f& X) { CvMat* mX = CvMatUtil::hmatFromPoint3D(X); CvMat* mnX = CvMatUtil::matMul(NP, mX); CvPoint3D32f p = cvPoint3D32f(cvmGet(mnX, 0, 0), cvmGet(mnX, 1, 0), cvmGet(mnX, 2, 0)); cvReleaseMat(&mX); cvReleaseMat(&mnX); return p; } public: static vector<CvPoint2D32f> calcImagePoints(const CvMat* P, const vector<CvPoint3D32f>& Xs) { vector<CvPoint2D32f> xs; for (int i = 0; i < (int)Xs.size(); i++) { xs.push_back(calcImagePoint(P, Xs[i])); } return xs; } static CvPoint2D32f calcImagePoint(const CvMat* P, CvPoint3D32f X) { CvMat* mX = CvMatUtil::hmatFromPoint3D(X); CvPoint2D32f p = calcImagePoint(P, mX); cvReleaseMat(&mX); return p; } //mX: homogeneous static CvPoint2D32f calcImagePoint(const CvMat* P, const CvMat* mX) { CvMat* mp = cvCreateMat(3, 1, CV_64FC1); cvMatMul(P, mX, mp); CvPoint2D32f p = CvMatUtil::hmatToPoint2D(mp); cvReleaseMat(&mp); return p; } //p is in image coordinate system. in which the (0, 0) is the left-bottom point static CvPoint3D32f calcPoint3DWithDepth(const CvMat* P, CvPoint2D32f p, double depth) { double c0, c1, c2; double x, y, z = depth; double u = p.x; double v = p.y; c0 = z * cvmGet(P, 0, 2) + cvmGet(P, 0, 3); c1 = z * cvmGet(P, 1, 2) + cvmGet(P, 1, 3); c2 = z * cvmGet(P, 2, 2) + cvmGet(P, 2, 3); y = u * (c1 * cvmGet(P, 2, 0) - cvmGet(P, 1, 0) * c2) + v * (c2 * cvmGet(P, 0, 0) - cvmGet(P, 2, 0) * c0) + cvmGet(P, 1, 0) * c0 - c1 * cvmGet(P, 0, 0); y /= v * (cvmGet(P, 2, 0) * cvmGet(P, 0, 1) - cvmGet(P, 2, 1) * cvmGet(P, 0, 0)) + u * (cvmGet(P, 1, 0) * cvmGet(P, 2, 1) - cvmGet(P, 1, 1) * cvmGet(P, 2, 0)) + cvmGet(P, 0, 0) * cvmGet(P, 1, 1) - cvmGet(P, 1, 0) * cvmGet(P, 0, 1); x = y * (cvmGet(P, 0, 1) - cvmGet(P, 2, 1) * u) + c0 - c2 * u; x /= cvmGet(P, 2, 0) * u - cvmGet(P, 0, 0); return cvPoint3D32f(x, y, z); } //P = H * P //K = H * K void trans(CvMat* H) { P = matMul(H, P); //memory leak! K = matMul(H, K); } void transWithScale(double scale) { double mh[] = {scale, 0, 0, 0, scale, 0, 0, 0, 1}; CvMat MH = cvMat(3, 3, CV_64FC1, mh); trans(&MH); } void transWithFlipY(double h) { double mh[] = {1, 0, 0, 0, -1, h - 1, 0, 0, 1}; CvMat MH = cvMat(3, 3, CV_64FC1, mh); trans(&MH); } public: CvMat* getP() { return P; } CvMat* getK() { return K; } CvMat* getNP() { return NP; //memory leack! } CvMat* getC() { return C; } CvMat* getHC() { return HC; } CvMat* getR() { return R; } CvMat* gett() { return t; } CvPoint3D32f geto() { return o; } public: // l = l / ||l||; r = (l x u) / ||l x u||, s = r x l // R = [r, s, l]' static CvMat* calcR(const CvPoint3D32f& viewDirection, const CvPoint3D32f& upDirection) { CvMat* l = CvMatUtil::matFromPoint3D(viewDirection); CvMat* u = CvMatUtil::matFromPoint3D(upDirection); //cout<<"l "<<CvMatUtil::matString(l)<<endl; //cout<<"u "<<CvMatUtil::matString(u)<<endl; CvMatUtil::normalizeVector(l); CvMat* r = cvCreateMat(3, 1, CV_64FC1); cvCrossProduct(l, u, r); CvMatUtil::normalizeVector(r); CvMat* s = cvCreateMat(3, 1, CV_64FC1); cvCrossProduct(r, l, s); //cout<<"r "<<CvMatUtil::matString(r)<<endl; //cout<<"s "<<CvMatUtil::matString(s)<<endl; //cout<<"l "<<CvMatUtil::matString(l)<<endl; CvMat* Rt = cvCreateMat(3, 3, CV_64FC1); CvMatUtil::setCol(Rt, r, 0); CvMatUtil::setCol(Rt, s, 1); CvMatUtil::setCol(Rt, l, 2); CvMat* R = cvCreateMat(3, 3, CV_64FC1); cvTranspose(Rt, R); cvReleaseMat(&l); cvReleaseMat(&u); cvReleaseMat(&r); cvReleaseMat(&s); cvReleaseMat(&Rt); return R; } public: static CvMat* createCalibrationMatrix(double f) { CvMat* K = cvCreateMat(3, 3, CV_64FC1); cvZero(K); cvmSet(K, 0, 0, f); cvmSet(K, 1, 1, f); cvmSet(K, 2, 2, 1.0); return K; } private: CvMat* P; CvMat* NP; //normalized camera matrix. NP = [R|t] CvMat* K; CvMat* R; CvMat* C; CvMat* t; //C in homogeneous coordinates CvMat* HC; CvPoint3D32f o; }; } }
[ "ferryzhou@b6adba56-547e-11de-b413-c5e99dc0a8e2" ]
ferryzhou@b6adba56-547e-11de-b413-c5e99dc0a8e2
f5011d003534001cd3d6fb31c2f6d40f2eb3ebe4
6e6cfee5f92724f57897307f00cffff18a609c15
/intermittent.cpp
461ef236e5e700644f315e7a43463f05d4ed1372
[]
no_license
keithw/chansym
847b478186de112029a8667eda1ad289ac6a078a
86ba59ef0087f2d0f3457db6a7ef4030145b47cb
refs/heads/master
2020-12-25T18:20:38.157757
2011-12-06T17:15:37
2011-12-06T17:15:37
1,978,613
0
0
null
null
null
null
UTF-8
C++
false
false
1,291
cpp
#include <boost/functional/hash.hpp> #include <sstream> #include "intermittent.hpp" #include "container.hpp" Intermittent::Intermittent( double s_probability, double s_interval ) : Channel(), working( true ), probability( s_probability ), interval( s_interval ) {} void Intermittent::init( void ) { container->sleep_until( 0, addr, -1 ); /* sort first */ } void Intermittent::send( Packet pack ) { if ( working ) { container->receive( addr, pack ); } } void Intermittent::after_fork( bool is_other, ForkState x ) { if ( is_other && x.flip ) { working = !working; } forking = false; } void Intermittent::wakeup( void ) { assert( !forking ); ForkState *x = new ForkState( true ); container->sleep_until( container->time() + interval, addr ); container->fork( addr, 1 - probability, x ); } string Intermittent::identify( void ) const { ostringstream response; response << "Intermittent( "; response << (working ? "working" : "blocked"); response << ", "; response << interval; response << " )"; return response.str(); } size_t hash_value( Intermittent const & ch ) { size_t seed = 0; boost::hash_combine( seed, ch.working ); boost::hash_combine( seed, ch.probability ); boost::hash_combine( seed, ch.interval ); return seed; }
[ "keithw@mit.edu" ]
keithw@mit.edu
bdf750d96473649abf8807887030ee69bafd347c
f9ce3c2c3024d19207518db5ef6d2622fec3a67b
/Gomoku/GomokuController.cpp
e06c13993cd362f1495b64d483f4ac647e25a30c
[]
no_license
h26liu/gomoku
d3830a81fe5ce4f575687c11c0edb46e3c51b3f2
b7c52962c5935f48100dca6741cb05fc7daf3564
refs/heads/master
2022-11-28T02:44:01.654746
2020-08-03T19:37:50
2020-08-03T19:37:50
284,791,098
0
0
null
null
null
null
UTF-8
C++
false
false
13,719
cpp
/*! \author Haohan Liu \date 2019-04-15 \file GomokuController.cpp */ #include "GomokuController.hpp" bool applicationQuitting = false; bool CtrlHandler(DWORD ctrlType) { switch (ctrlType) { case CTRL_C_EVENT: applicationQuitting = true; return TRUE; } return FALSE; } GomokuController::GomokuController() { model = new GomokuModel(); hv = new HomeView(*model); tv = new TitleView(*model); bv = new BoardView(*model); sv = new ScoreView(*model); pv = new PlayerView(*model); mlv = new MoveListView(*model); model->Attach(hv); model->Attach(tv); model->Attach(bv); model->Attach(sv); model->Attach(pv); model->Attach(mlv); model->outer.SaveConsoleState(); model->outer.SetCtrlHandler(CtrlHandler, true); model->outer.SetConsoleWindowTitle("Gomoku"); model->outer.ResizeConsoleWindow(80, 30); //outerWrapper.HideConsoleWindowCursor(); model->outer.PaintConsoleBackground(BACKGROUND_WHITE); model->gs = GomokuModel::HOMEVIEW; model->Notify(); homeController(); //PlayerInfoView(); model->outer.HideConsoleWindowCursor(); model->outer.PaintConsoleBackground(BACKGROUND_WHITE); model->gs = GomokuModel::BOARDVIEW; model->Notify(); //model->DrawGomokuGameBoard(); model->AddCoordinates(); model->FillBoardVector(); model->gs = GomokuModel::TITLEVIEW; model->Notify(); //PrintGreetingMsg(); model->gs = GomokuModel::SCOREVIEW; model->Notify(); // while loop inside the function body gameController(); model->outer.RestoreConsoleState(); } void GomokuController::homeController() { // read input buffer repeatedly std::vector<INPUT_RECORD> inBuffer(128); while (!model->hasGameStarted) { DWORD numEvents; if (!ReadConsoleInput(model->outer.GetConsoleWindowInput(), inBuffer.data(), (DWORD)inBuffer.size(), &numEvents)) { //cerr << "Failed to read console input\n"; break; } for (size_t iEvent = 0; iEvent < numEvents; ++iEvent) { switch (inBuffer[iEvent].EventType) { case MOUSE_EVENT: MouseEventProc(inBuffer[iEvent].Event.MouseEvent); break; case KEY_EVENT: ProcessKeyEvent(inBuffer[iEvent].Event.KeyEvent); break; } } } } void GomokuController::gameController() { // logic here // read input buffer repeatedly std::vector<INPUT_RECORD> inBuffer(128); while (!applicationQuitting) { DWORD numEvents; if (!ReadConsoleInput(model->outer.GetConsoleWindowInput(), inBuffer.data(), (DWORD)inBuffer.size(), &numEvents)) { //cerr << "Failed to read console input\n"; break; } for (size_t iEvent = 0; iEvent < numEvents; ++iEvent) { switch (inBuffer[iEvent].EventType) { case MOUSE_EVENT: MouseEventProc(inBuffer[iEvent].Event.MouseEvent); break; case KEY_EVENT: ProcessKeyEvent(inBuffer[iEvent].Event.KeyEvent); break; } } } } void GomokuController::MouseEventProc(MOUSE_EVENT_RECORD const & mer) { #if !defined(MOUSE_HWHEELED) #define MOUSE_HWHEELED 0x0008 #endif // Mouse Location auto bufferLoc = mer.dwMousePosition; switch (mer.dwEventFlags) { case 0: // button pressed or released { if (mer.dwButtonState&FROM_LEFT_1ST_BUTTON_PRESSED && !model->gameOver && model->hasGameStarted) { if (bufferLoc.Y < 10 || bufferLoc.X >= 41 || bufferLoc.Y >= 28 || bufferLoc.X <= 3) break; if (model->aPieces[bufferLoc.Y][bufferLoc.X] != 0 || model->bPieces[bufferLoc.Y][bufferLoc.X] != 0) break; if (bufferLoc.X % 2 == 0) { if (model->clickCount % 2 == 0) { if (model->movesA.size() >= 21) { model->movesA.erase(model->movesA.begin()); } // add player A moves model->movesA.push_back(bufferLoc); model->gs = GomokuModel::MOVELISTVIEW; model->Notify(); //UpdateUserMoves(); model->scoreA++; model->gs = GomokuModel::SCOREVIEW; model->Notify(); //UpdateUserScores(); model->outer.PaintCellClicked(model->colorA, bufferLoc); model->aPieces[bufferLoc.Y][bufferLoc.X] = 1; if (model->FiveInRow(model->aPieces)) { model->gameOver = true; std::string msg = "[" + model->nameA + " Wins!]"; COORD loc; loc.X = (40 - (SHORT)msg.size()) / 2; loc.Y = 8; model->outer.WriteConsoleWindowMsg(msg.c_str(), (DWORD)msg.size(), loc); // paint move background for (size_t i = 0; i < msg.size(); i++) { model->outer.PaintCellClicked(model->colorA, loc); loc.X++; } } } else { if (model->movesB.size() >= 21) { model->movesB.erase(model->movesB.begin()); } // add player B moves model->movesB.push_back(bufferLoc); model->gs = GomokuModel::MOVELISTVIEW; model->Notify(); //UpdateUserMoves(); model->scoreB++; model->gs = GomokuModel::SCOREVIEW; model->Notify(); //UpdateUserScores(); model->outer.PaintCellClicked(model->colorB, bufferLoc); model->bPieces[bufferLoc.Y][bufferLoc.X] = 1; if (model->FiveInRow(model->bPieces)) { model->gameOver = true; std::string msg = "[" + model->nameB + " Wins!]"; COORD loc; loc.X = (40 - (SHORT)msg.size()) / 2; loc.Y = 8; model->outer.WriteConsoleWindowMsg(msg.c_str(), (DWORD)msg.size(), loc); // paint move background for (size_t i = 0; i < msg.size(); i++) { model->outer.PaintCellClicked(model->colorB, loc); loc.X++; } } } model->clickCount += 1; } } else if (mer.dwButtonState&RIGHTMOST_BUTTON_PRESSED && !model->gameOver && model->hasGameStarted) { // RIGHT-CLICK undo model->clickCount -= 1; if (model->clickCount % 2 == 0) { if (model->movesA.size() > 0) { bufferLoc.X = model->movesA.back().X; bufferLoc.Y = model->movesA.back().Y; model->outer.PaintCellClicked(BACKGROUND_WHITE, bufferLoc); model->aPieces[model->movesA.back().Y][model->movesA.back().X] = 0; model->movesA.erase(model->movesA.end() - 1); model->scoreA--; model->gs = GomokuModel::SCOREVIEW; model->Notify(); //UpdateUserScores(); model->gs = GomokuModel::MOVELISTVIEW; model->Notify(); //UpdateUserMoves(); } } else { if (model->movesB.size() > 0) { bufferLoc.X = model->movesB.back().X; bufferLoc.Y = model->movesB.back().Y; model->outer.PaintCellClicked(BACKGROUND_WHITE, bufferLoc); model->bPieces[model->movesB.back().Y][model->movesB.back().X] = 0; model->movesB.erase(model->movesB.end() - 1); model->scoreB--; model->gs = GomokuModel::SCOREVIEW; model->Notify(); //UpdateUserScores(); model->gs = GomokuModel::MOVELISTVIEW; model->Notify(); //UpdateUserMoves(); } } } else if (mer.dwButtonState&FROM_LEFT_1ST_BUTTON_PRESSED && !model->hasGameStarted) { if (bufferLoc.X > 14 && bufferLoc.X < 35 && bufferLoc.Y == model->inputLocA.Y) { model->inputLoc = model->inputLocA; // set cursor loc COORD cursorLoc{ model->inputLocA.X + (SHORT)model->nameA.size(), model->inputLocA.Y }; model->outer.SetCursorLocation(cursorLoc); } else if (bufferLoc.X > 20 && bufferLoc.X < 75 && bufferLoc.Y == model->inputLocA.Y) { model->inputLoc = model->inputLocB; // set cursor loc COORD cursorLoc{ model->inputLocB.X + (SHORT)model->nameB.size(), model->inputLocB.Y }; model->outer.SetCursorLocation(cursorLoc); } // color selection else if (bufferLoc.Y >= model->inputLocA.Y + 5 && bufferLoc.Y <= model->inputLocA.Y + 7) { //************************* // PLAYER A //************************* if (bufferLoc.X > model->inputLocA.X - 7 && bufferLoc.X < model->inputLocA.X - 2) { if (bufferLoc.Y == model->inputLocA.Y + 5 && model->colorB != model->RGB_R) model->colorA = model->RGB_R; else if (bufferLoc.Y == model->inputLocA.Y + 7 && model->colorB != model->RGB_C) model->colorA = model->RGB_C; model->UpdatePlayerColors(); } else if (bufferLoc.X > model->inputLocA.X - 1 && bufferLoc.X < model->inputLocA.X + 3) { if (bufferLoc.Y == model->inputLocA.Y + 5 && model->colorB != model->RGB_G) model->colorA = model->RGB_G; else if (bufferLoc.Y == model->inputLocA.Y + 7 && model->colorB != model->RGB_Y) model->colorA = model->RGB_Y; model->UpdatePlayerColors(); } else if (bufferLoc.X > model->inputLocA.X + 4 && bufferLoc.X < model->inputLocA.X + 9) { if (bufferLoc.Y == model->inputLocA.Y + 5 && model->colorB != model->RGB_B) model->colorA = model->RGB_B; else if (bufferLoc.Y == model->inputLocA.Y + 7 && model->colorB != model->RGB_M) model->colorA = model->RGB_M; model->UpdatePlayerColors(); } //************************* // PLAYER B //************************* if (bufferLoc.X > model->inputLocB.X - 7 && bufferLoc.X < model->inputLocB.X - 2) { if (bufferLoc.Y == model->inputLocB.Y + 5 && model->colorA != model->RGB_R) model->colorB = model->RGB_R; else if (bufferLoc.Y == model->inputLocB.Y + 7 && model->colorA != model->RGB_C) model->colorB = model->RGB_C; model->UpdatePlayerColors(); } else if (bufferLoc.X > model->inputLocB.X - 1 && bufferLoc.X < model->inputLocB.X + 3) { if (bufferLoc.Y == model->inputLocB.Y + 5 && model->colorA != model->RGB_G) model->colorB = model->RGB_G; else if (bufferLoc.Y == model->inputLocB.Y + 7 && model->colorA != model->RGB_Y) model->colorB = model->RGB_Y; model->UpdatePlayerColors(); } else if (bufferLoc.X > model->inputLocB.X + 4 && bufferLoc.X < model->inputLocB.X + 9) { if (bufferLoc.Y == model->inputLocB.Y + 5 && model->colorA != model->RGB_B) model->colorB = model->RGB_B; else if (bufferLoc.Y == model->inputLocB.Y + 7 && model->colorA != model->RGB_M) model->colorB = model->RGB_M; model->UpdatePlayerColors(); } } } break; } } } void GomokuController::ProcessKeyEvent(KEY_EVENT_RECORD const & ker) { if (model->hasGameStarted) { if (isgraph(ker.uChar.AsciiChar) && ker.uChar.AsciiChar == 'r') { model->clickCount = 0; model->outer.PaintConsoleBackground(BACKGROUND_WHITE); model->ResetBoardVector(); model->gs = GomokuModel::TITLEVIEW; model->Notify(); //PrintGreetingMsg(); //model->DrawGomokuGameBoard(); //model->AddCoordinates(); model->gs = GomokuModel::BOARDVIEW; model->Notify(); } } else { if (ker.wVirtualKeyCode == VK_RETURN && model->nameA != "" && model->nameB != "") { // start playing game model->hasGameStarted = true; } // BACKSPACE key pressed else if (ker.bKeyDown && ker.wVirtualKeyCode == VK_BACK) { if (model->inputLoc.X == model->inputLocA.X) { if (model->nameA.size() > 0) { for (size_t i = 0; i < model->nameA.size(); i++) { COORD paintLoc{ model->inputLoc.X + (SHORT)i, model->inputLoc.Y }; model->outer.RecoverCellClicked(BACKGROUND_WHITE, paintLoc); } model->nameA = model->nameA.substr(0, model->nameA.size() - 1); model->outer.WriteConsoleWindowMsg(model->nameA.c_str(), (DWORD)model->nameA.size(), model->inputLoc); // reset cursor location COORD cursorLoc{ model->inputLocA.X + (SHORT)model->nameA.size(), model->inputLocA.Y }; model->outer.SetCursorLocation(cursorLoc); } } else { if (model->nameB.size() > 0) { for (size_t i = 0; i < model->nameB.size(); i++) { COORD paintLoc{ model->inputLoc.X + (SHORT)i, model->inputLoc.Y }; model->outer.RecoverCellClicked(BACKGROUND_WHITE, paintLoc); } model->nameB = model->nameB.substr(0, model->nameB.size() - 1); model->outer.WriteConsoleWindowMsg(model->nameB.c_str(), (DWORD)model->nameB.size(), model->inputLoc); // reset cursor location COORD cursorLoc{ model->inputLocB.X + (SHORT)model->nameB.size(), model->inputLocB.Y }; model->outer.SetCursorLocation(cursorLoc); } } } // TAB key pressed else if (ker.bKeyDown && ker.wVirtualKeyCode == VK_TAB) { if (model->inputLoc.X == model->inputLocA.X) { model->inputLoc = model->inputLocB; // reset cursor location COORD cursorLoc{ model->inputLocB.X + (SHORT)model->nameB.size(), model->inputLocB.Y }; model->outer.SetCursorLocation(cursorLoc); } else { model->inputLoc = model->inputLocA; // reset cursor location COORD cursorLoc{ model->inputLocA.X + (SHORT)model->nameA.size(), model->inputLocA.Y }; model->outer.SetCursorLocation(cursorLoc); } } else if (ker.bKeyDown && ker.wVirtualKeyCode != VK_RETURN && ker.wVirtualKeyCode != VK_CAPITAL) { if (model->inputLoc.X == model->inputLocA.X) { model->nameA += ker.uChar.AsciiChar; model->outer.WriteConsoleWindowMsg(model->nameA.c_str(), (DWORD)model->nameA.size(), model->inputLoc); // reset cursor location COORD cursorLoc{ model->inputLocA.X + (SHORT)model->nameA.size(), model->inputLocA.Y }; model->outer.SetCursorLocation(cursorLoc); } else { model->nameB += ker.uChar.AsciiChar; model->outer.WriteConsoleWindowMsg(model->nameB.c_str(), (DWORD)model->nameB.size(), model->inputLoc); // reset cursor location COORD cursorLoc{ model->inputLocB.X + (SHORT)model->nameB.size(), model->inputLocB.Y }; model->outer.SetCursorLocation(cursorLoc); } } } }
[ "eric@tacobell-pro.local" ]
eric@tacobell-pro.local
45c6c1408abc78d3f802747580f3dbc6cd1aaba5
5625ec41afd5747567c0325f637ecedacf7ffd24
/White Belt/Week_4/Task_17/Task_17.cpp
93da96872f1787befe8ff4b739dbfde49a395928
[]
no_license
m3nf1s/Modern-Cplusplus
c2ea3c080804057756d26947a13212ca38338456
d29d94463d91a42b36b890316106723b2be422a1
refs/heads/master
2023-03-20T18:34:19.771170
2023-03-02T22:30:11
2023-03-02T22:30:11
170,276,288
28
10
null
null
null
null
UTF-8
C++
false
false
3,764
cpp
/* * Вам дана функция string AskTimeServer(), про которую известно следующее: * в процессе своей работы она обращается по сети к удалённому серверу, запрашивая текущее время; * если обращение к серверу прошло успешно, функция возвращает текущее время в виде строки; * если в процессе обращения к серверу возникла сетевая проблема, функция выбрасывает исключение system_error; * функция может выбрасывать другие исключения, чтобы сообщить о других проблемах. * Используя функцию AskTimeServer, напишите класс TimeServer со следующим интерфейсом: * class TimeServer { public: string GetCurrentTime(); private: string LastFetchedTime = "00:00:00"; }; * * Метод GetCurrentTime должен вести себя так: * он должен вызвать функцию AskTimeServer, записать её результат в поле LastFetchedTime и вернуть значение этого поля; * если AskTimeServer выбросила исключение system_error, метод GetCurrentTime должен его поймать и вернуть текущее значение поля LastFetchedTime. * Таким образом мы скрываем от пользователя сетевые проблемы, возвращая значение, которое было получено при последнем успешном обращении к серверу; * если AskTimeServer выбросила другое исключение, метод GetCurrentTime должен пробросить его дальше, * потому что в рамках класса TimeServer мы не знаем, как обрабатывать проблемы, не связанные со сбоями сети. */ #include <iostream> #include <exception> #include <string> using namespace std; string AskTimeServer() { /* Для тестирования повставляйте сюда код, реализующий различное поведение этой функии: * нормальный возврат строкового значения * выброс исключения system_error * выброс другого исключения с сообщением. */ } class TimeServer { public: string GetCurrentTime() { /* Реализуйте этот метод: * если AskTimeServer() вернула значение, запишите его в LastFetchedTime и верните * если AskTimeServer() бросила исключение system_error, верните текущее значение поля LastFetchedTime * если AskTimeServer() бросила другое исключение, пробросьте его дальше. */ try { string time = AskTimeServer(); LastFetchedTime = time; } catch (const system_error&) { return LastFetchedTime; } return LastFetchedTime; } private: string LastFetchedTime = "00:00:00"; }; int main() { // Меняя реализацию функции AskTimeServer, убедитесь, что это код работает корректно TimeServer ts; try { cout << ts.GetCurrentTime() << endl; } catch (exception& e) { cout << "Exception got: " << e.what() << endl; } return 0; }
[ "titan94@mail.ru" ]
titan94@mail.ru
da0ff53a91d0029ef86fb257d0f86a5cc6a5e4ca
df1b1ca52a2934d3c3495345692afb06926a1145
/Exec/src/hashqueue_exceptions.hpp
cd105b7f4de3fed652cf8908e3463f0d44597b9f
[ "MIT" ]
permissive
sashank6/HashQueue
fd6eb3957f834289ac75399d324b62d16526eeac
0b0c9afd2a1026981fc9bae317f6fbe07a1a820d
refs/heads/master
2021-01-15T22:51:37.384314
2017-08-27T19:52:36
2017-08-27T19:52:36
99,919,496
0
0
null
2017-08-27T19:52:37
2017-08-10T12:15:42
C++
UTF-8
C++
false
false
397
hpp
// // // #include<exception> #ifndef EXEC_EXCEPTIONS_H #define EXEC_EXCEPTIONS_H struct QueueEmptyException:public std::exception { const char* what() const throw() { return "Queue is Empty"; } }; struct InvalidPushException:public std::exception { const char* what() const throw() { return "Cannot push null memory bad_alloc"; } }; #endif //EXEC_EXCEPTIONS_H
[ "sashank.alladi@live.com" ]
sashank.alladi@live.com
9cdf98f2e327efd424d1476512594af23442de30
390c723171375b6c8034c4a074d9dc8df73e5a2d
/src/dllmain.cpp
c26f6334dded13fe14f9545f73f341195f2ca0a4
[ "MIT" ]
permissive
maple-ml/cinnamon
dfd37168f6e529125a685286450c620220d9e537
34b461fe75482753dec63bc2c7dbb81d21d064c8
refs/heads/master
2023-04-29T16:01:13.096421
2023-04-28T05:55:44
2023-04-28T05:55:44
339,519,179
6
0
null
null
null
null
UTF-8
C++
false
false
4,181
cpp
#define WIN32_LEAN_AND_MEAN #undef ERROR #include <windows.h> #include <stdio.h> #include <iostream> #include <filesystem> #include <thread> #include <cocos2d.h> #include <pybind11.h> #include <pybind11/embed.h> #include "core/utilities/path.h" #include "core/python.h" #include "core/logger.h" #include "core/module.h" // bindings (autogen) #include "bindings/geometry_dash_bindings.h" #include "bindings/cocos2d_bindings.h" #include "bindings/manual_bindings.h" // hooks #include "core/hooks/ModdedMenuLayer.h" namespace pybind = pybind11; USING_NS_CC; DWORD WINAPI dll_thread(void* hModule) { AllocConsole(); FILE* fDummy; freopen_s(&fDummy, "CONIN$", "r", stdin); freopen_s(&fDummy, "CONOUT$", "w", stderr); freopen_s(&fDummy, "CONOUT$", "w", stdout); cinnamon::logger::setLoggingLevel(cinnamon::logger::LoggingLevel::DEBUG); cinnamon::hooks::init(); pybind::scoped_interpreter python; std::string mod_path = cinnamon::utilities::getModsPath(); pybind::module_::import("sys").attr("path").attr("append")(mod_path); pybind::gil_scoped_acquire acquire; cinnamon::logger::log("Generating stubgen", "INFO"); try { pybind::exec( "from distutils.sysconfig import get_python_lib\n" "import pybind11_stubgen\n" "import logging\n" "logging.getLogger(\"pybind11_stubgen\").disabled = True\n" "pybind11_stubgen.main([\"cinnamon\", \"--ignore-invalid=all\", \"--output-dir\", get_python_lib(), \"--root-module-suffix\", \"\"])\n" "pybind11_stubgen.main([\"cocos2d\", \"--ignore-invalid=all\", \"--output-dir\", get_python_lib(), \"--root-module-suffix\", \"\"])\n" "pybind11_stubgen.main([\"geometry_dash\", \"--ignore-invalid=all\", \"--output-dir\", get_python_lib(), \"--root-module-suffix\", \"\"])\n" ); } catch (pybind::error_already_set& e) { cinnamon::logger::log("Failed to run stubgen: " + std::string(e.what()), "ERROR"); } cinnamon::logger::log("Stubgen generation complete", "DEBUG"); for (const auto& dirEntry : std::filesystem::directory_iterator(mod_path.c_str())) { std::string file = dirEntry.path().string(); if (dirEntry.is_directory()) { cinnamon::logger::log("Found directory: " + file, "INFO"); for (const auto& modDirEntry : std::filesystem::directory_iterator(dirEntry.path().string().c_str())) { std::string dirFile = modDirEntry.path().string(); if (modDirEntry.path().filename() == "main.py" | modDirEntry.path().filename() == "__main__.py" | modDirEntry.path().filename().string() == modDirEntry.path().parent_path().filename().string() + ".py") { cinnamon::logger::log("Found Python file: " + dirFile, "INFO"); if (cinnamon::python::runPythonFile(dirFile)) { cinnamon::logger::log("Python file started: " + dirFile, "INFO"); } } } } else if (cinnamon::utilities::hasEnding(file, ".py")) { cinnamon::logger::log("Found Python file: " + file, "INFO"); if (cinnamon::python::runPythonFile(file)) { cinnamon::logger::log("Python file started: " + file, "INFO"); } } } cinnamon::logger::log("All modules loaded!", "INFO"); // call on_modules_loaded for (auto const& [key, val] : cinnamon::module::modules) { if (pybind::hasattr(val, "on_modules_loaded")) { val.attr("on_modules_loaded")(); } } pybind::gil_scoped_release release; // enable hooks ModdedMenuLayer::enable(); return 0; } BOOL APIENTRY DllMain( HMODULE hModule, DWORD ul_reason_for_call, LPVOID lpReserved ) { switch (ul_reason_for_call) { case DLL_PROCESS_ATTACH: CreateThread(0, 0x1000, dll_thread, hModule, 0, 0); case DLL_THREAD_ATTACH: case DLL_THREAD_DETACH: case DLL_PROCESS_DETACH: break; } return TRUE; }
[ "50897638+spookybear0@users.noreply.github.com" ]
50897638+spookybear0@users.noreply.github.com
7419ad1a5d73574d3cc950b96c49618256bf6073
64895fff118ac407357a050861297a395fa2fbc6
/Hackerrank/University Codesprint/seperate_numbers.cpp
e4b9873d610d71e307154c0b1ea911041d6f3da4
[]
no_license
whiz-Tuhin/Competitve
38df5475ba8f9e4ecfa96071e1a0b639bb2ab41e
f5fd063e31f0e5b6addc26c83e007eeb5ae7b89f
refs/heads/master
2020-04-06T03:46:19.820666
2017-08-01T08:02:00
2017-08-01T08:02:00
68,317,364
4
0
null
null
null
null
UTF-8
C++
false
false
821
cpp
//TODO := i'm not able to figure out the logic as of now #include <iostream> #include <string> #include <math.h> #include <algorithm> #include <vector> using namespace std; typedef unsigned long long int ulli; vector<int> convert_to_vector(ulli num){ vector<int> digits; while(num > 0){ digits.push_back(num%10); num /= 10; } return digits; } int main(){ int q; cin>>q; for(int i = 0;i < q;i++){ int num; cin>>num; vector<int> digits = convert_to_vector(num); int i = 1; while(i < digits.size()){ if(digits[i] - digits[i-1] != 1){ } } } return 0; }
[ "tuhinkhare3@gmail.com" ]
tuhinkhare3@gmail.com
fe3b2646ed4e7fba39d1a907b3e5cb653e5e9306
10bf73993e6bf611f73c8b2a0125a5dafa3a2574
/software/binaryClock/binclock.cpp
f5b51198d42ab1759cfd8ceae607a22eac4a7b67
[]
no_license
cryptoluks/binaryclock
b407d8d72e2bb1dfe497a86a795bb607d5db656e
df80437817ca891fbebde23ccee4362ae14bfaf4
refs/heads/master
2020-06-28T21:59:04.537898
2019-08-02T19:18:23
2019-08-02T19:18:23
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,496
cpp
#include "binclock.h" #include "binclockHAL.h" #include "Arduino.h" #include <TimeLib.h> RTC_DS3231 BinaryClock::rtc; BinaryClock::BinaryClock(): state(STATES::SHOW_CLK), brightness(100), brighttype(STATIC){ } void BinaryClock::displayTick() { counter++; if(counter > 9) counter = 0; switch(state) { case SHOW_CLK: updateDisplay(hour(),minute(),second()); break; case SET_HOUR: updateDisplay(hour() + temp,0,0); break; case SET_MINUTE: updateDisplay(0,minute() + temp,0); break; case SET_BRIGHTNESS: updateDisplay(0,temp+1,temp+1); break; case MANUAL: updateDisplay(row[0],row[1],row[2]); break; default: break; } if(timeout > 0) { if(--timeout == 0) { state = SHOW_CLK; } } } void BinaryClock::manualMode(uint8_t row[], unsigned int timeout) { state = MANUAL; this->row[0] = row[0]; this->row[1] = row[1]; this->row[2] = row[2]; this->timeout = timeout * 10; } void BinaryClock::normalMode() { if(state == MANUAL) { state = SHOW_CLK; } } void BinaryClock::keyPress(SOFTKEY key) { switch(state) { case SHOW_CLK: switch(key) { case KEY_PLUS: state = SET_BRIGHTNESS; timeout = 30; temp = brightness/10; break; case KEY_SET: rtcGet(); state = SET_HOUR; temp = 0; break; } break; case SET_BRIGHTNESS: switch(key) { case KEY_PLUS: if(temp < 10) { ++temp; } break; case KEY_MINUS: if(temp > 0) { --temp; } break; } timeout = 30; setBrightness(temp*10); break; case SET_HOUR: switch(key) { case KEY_PLUS: ++temp; if(temp + hour() >= 24) temp -= 24; break; case KEY_MINUS: --temp; if(temp + hour() < 0) temp +=24; break; case KEY_SET: adjustTime((long) temp * 3600L); temp = 0; state = SET_MINUTE; break; } break; case SET_MINUTE: switch(key) { case KEY_PLUS: ++temp; if(temp + minute() >= 60) temp -=60; break; case KEY_MINUS: --temp; if(temp + minute() < 0) temp +=60; break; case KEY_SET: adjustTime(temp * 60); rtcSet(); temp = 0; state = SHOW_CLK; } break; case MANUAL: state = SHOW_CLK; break; } } void BinaryClock::updateDisplay(uint8_t row1, uint8_t row2, uint8_t row3) { boolean disp_on = effect == NORMAL; disp_on |= effect == BLINK && (counter < 5); disp_on |= effect == FLICKER && (counter & 1); disp_on |= effect == HEARTBEAT && (counter == 0 || counter == 2); if(!disp_on) BinaryClockHAL::display(0,0,0); else BinaryClockHAL::display(row1,row2,row3); } void BinaryClock::setBrightnessType(BRIGHTNESSTYPE type) { brighttype = type; } void BinaryClock::setAmbientLight(uint8_t val) { if(brighttype == AMBIENT) { BinaryClockHAL::setBrightness(val + brightness/10); } } void BinaryClock::setBrightness(uint8_t val) { if(val > 100) val = 100; brightness = val; if(brighttype == STATIC) { BinaryClockHAL::setBrightness(val); } } void BinaryClock::rtcGet() { setTime(rtc.now().unixtime()); } void BinaryClock::rtcSet() { rtc.adjust(DateTime(now())); } void BinaryClock::setDisplayEffect(DISPEFFECT effect) { this->effect = effect; } boolean BinaryClock::isSummerTime(unsigned int yyyy, uint8_t mnth, uint8_t dd, uint8_t hh, uint8_t tzHours) { // European Daylight Savings Time calculation by "jurs" for German Arduino Forum // input parameters: "normal time" for year, month, day, hour and tzHours (0=UTC, 1=MEZ) // return value: returns true during Daylight Saving Time, false otherwise { if (mnth < 3 || mnth > 10) return false; // keine Sommerzeit in Jan, Feb, Nov, Dez if (mnth > 3 && mnth < 10) return true; // Sommerzeit in Apr, Mai, Jun, Jul, Aug, Sep if (mnth == 3 && (hh + 24 * dd) >= (1 + tzHours + 24 * (31 - (5 * yyyy / 4 + 4) % 7)) || mnth == 10 && (hh + 24 * dd) < (1 + tzHours + 24 * (31 - (5 * yyyy / 4 + 1) % 7))) return true; else return false; } }
[ "email@kmkcl.de" ]
email@kmkcl.de
6efd989f1628c5386c4c785b8660220c7dd0222f
238e46a903cf7fac4f83fa8681094bf3c417d22d
/OCC/opencascade-7.2.0/x64/debug/inc/ShapePersistent_Geom2d.hxx
67b8131fcfbd5547c50cd36c525bd4e3d262508a
[ "BSD-3-Clause" ]
permissive
baojunli/FastCAE
da1277f90e584084d461590a3699b941d8c4030b
a3f99f6402da564df87fcef30674ce5f44379962
refs/heads/master
2023-02-25T20:25:31.815729
2021-02-01T03:17:33
2021-02-01T03:17:33
268,390,180
1
0
BSD-3-Clause
2020-06-01T00:39:31
2020-06-01T00:39:31
null
UTF-8
C++
false
false
6,585
hxx
// Copyright (c) 2015 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _ShapePersistent_Geom2d_HeaderFile #define _ShapePersistent_Geom2d_HeaderFile #include <StdObjMgt_TransientPersistentMap.hxx> #include <ShapePersistent_Geom.hxx> #include <Geom2d_CartesianPoint.hxx> #include <Geom2d_Direction.hxx> #include <Geom2d_VectorWithMagnitude.hxx> #include <Geom2d_AxisPlacement.hxx> #include <Geom2d_Transformation.hxx> #include <Geom2d_Curve.hxx> class ShapePersistent_Geom2d : public ShapePersistent_Geom { typedef geometryBase<Geom2d_Geometry> basic; public: typedef ShapePersistent_Geom::Geometry Geometry; typedef subBase_empty<basic> Point; typedef instance<Point, Geom2d_CartesianPoint, gp_Pnt2d> CartesianPoint; typedef subBase_gp<basic, gp_Vec2d> Vector; typedef instance<Vector, Geom2d_Direction , gp_Dir2d> Direction; typedef instance<Vector, Geom2d_VectorWithMagnitude, gp_Vec2d> VectorWithMagnitude; typedef instance<basic, Geom2d_AxisPlacement, gp_Ax2d> AxisPlacement; typedef instance <SharedBase<Geom2d_Transformation>, Geom2d_Transformation, gp_Trsf2d> Transformation; typedef geometryBase<Geom2d_Curve> Curve; public: //! Create a persistent object for a curve Standard_EXPORT static Handle(Curve) Translate (const Handle(Geom2d_Curve)& theCurve, StdObjMgt_TransientPersistentMap& theMap); }; //======================================================================= // Geometry //======================================================================= template<> Standard_CString ShapePersistent_Geom::geometryBase<Geom2d_Geometry> ::PName() const; //======================================================================= // Point //======================================================================= template<> Standard_CString ShapePersistent_Geom::subBase_empty< ShapePersistent_Geom2d::geometryBase<Geom2d_Geometry> > ::PName() const; //======================================================================= // CartesianPoint //======================================================================= template<> Standard_CString ShapePersistent_Geom::instance<ShapePersistent_Geom2d::Point, Geom2d_CartesianPoint, gp_Pnt2d> ::PName() const; template<> void ShapePersistent_Geom::instance<ShapePersistent_Geom2d::Point, Geom2d_CartesianPoint, gp_Pnt2d> ::Write(StdObjMgt_WriteData& theWriteData) const; //======================================================================= // Direction //======================================================================= template<> Standard_CString ShapePersistent_Geom::instance<ShapePersistent_Geom2d::Direction, Geom2d_Direction, gp_Dir2d> ::PName() const; template<> void ShapePersistent_Geom::instance<ShapePersistent_Geom2d::Direction, Geom2d_Direction, gp_Dir2d> ::Write(StdObjMgt_WriteData& theWriteData) const; //======================================================================= // VectorWithMagnitude //======================================================================= template<> Standard_CString ShapePersistent_Geom::instance<ShapePersistent_Geom2d::VectorWithMagnitude, Geom2d_VectorWithMagnitude, gp_Vec2d> ::PName() const; template<> void ShapePersistent_Geom::instance<ShapePersistent_Geom2d::VectorWithMagnitude, Geom2d_VectorWithMagnitude, gp_Vec2d> ::Write(StdObjMgt_WriteData& theWriteData) const; //======================================================================= // AxisPlacement //======================================================================= template<> Standard_CString ShapePersistent_Geom::instance<ShapePersistent_Geom2d::AxisPlacement, Geom2d_AxisPlacement, gp_Ax2d> ::PName() const; template<> void ShapePersistent_Geom::instance<ShapePersistent_Geom2d::AxisPlacement, Geom2d_AxisPlacement, gp_Ax2d> ::Write(StdObjMgt_WriteData& theWriteData) const; //======================================================================= // Transformation //======================================================================= template<> Standard_CString ShapePersistent_Geom::instance<ShapePersistent_Geom2d::Transformation, Geom2d_Transformation, gp_Trsf2d> ::PName() const; template<> void ShapePersistent_Geom::instance<ShapePersistent_Geom2d::Transformation, Geom2d_Transformation, gp_Trsf2d> ::PChildren(StdObjMgt_Persistent::SequenceOfPersistent& theChildren) const; template<> void ShapePersistent_Geom::instance<ShapePersistent_Geom2d::Transformation, Geom2d_Transformation, gp_Trsf2d> ::Write(StdObjMgt_WriteData& theWriteData) const; //======================================================================= // Curve //======================================================================= template<> Standard_CString ShapePersistent_Geom2d::geometryBase<Geom2d_Curve> ::PName() const; #endif
[ "l”ibaojunqd@foxmail.com“" ]
l”ibaojunqd@foxmail.com“
e90f31dd4aa7f445d4794d76367edfcc49d97bd3
3df49215f37c9e3f12f0504792cd07992f620f82
/codechef/codechef The Lead Game.cpp
623d068580f6471d5aa7b02efe3ba3f5367de295
[]
no_license
PushkarDhakad2505/Programming
906f30792761d0b3c91e8711d4129674324d60e1
e28cf89dd2865025ac900463e76ca3ba10997b52
refs/heads/main
2023-07-12T09:19:43.255208
2021-07-29T04:23:32
2021-07-29T04:23:32
390,586,130
0
0
null
null
null
null
UTF-8
C++
false
false
363
cpp
#include<bits/stdc++.h> using namespace std; int main() { int t,lead,max=0; cin>>t; int ar[t]; for (int i=0;i<t;i++) { int n,m,max=0; cin>>n>>m; lead=n-m; ar[i]=lead; } for (int i=0;i<t;i++) { if(abs(ar[i])>abs(max)) max=ar[i]; } if(max>0) cout<<"1"<<" "<<abs(max); else cout<<"2"<<" "<<abs(max); return 0; }
[ "noreply@github.com" ]
PushkarDhakad2505.noreply@github.com
58ef6856d0165cbf755e8b0a850b781814a3779e
8e38d2962162e9dc1b127d260def9d2ac6487089
/Week_07/Minimum Genetic Mutation.cpp
544d4637024558c20bdf62f0184ccb50b56758b4
[]
no_license
DeepJunJie/algorithm009-class02
4f8fefa17bfcdd85ad50416655fb0be2ccfa46c2
6401476358dd5848b0d15bada4b1c7993bf511fc
refs/heads/master
2022-11-23T20:15:59.436922
2020-07-26T06:11:46
2020-07-26T06:11:46
265,857,926
0
0
null
2020-05-21T13:38:29
2020-05-21T13:38:28
null
UTF-8
C++
false
false
899
cpp
class Solution { public: int minMutation(string start, string end, vector<string>& bank) { vector<set<string>> levels(bank.size()+2,set<string>()); vector<int>flag(bank.size(),0); levels[0].insert(start); for(int i=0;i<levels.size();i++) for(auto it=levels[i].begin();it!=levels[i].end();it++) for(int k=0;k<bank.size();k++){ if(flag[k]==1) continue; int j=0,cont=0; while(j<bank[k].length() && j<(*it).length()){ if(bank[k][j]!=(*it)[j])cont++; j++; } if(cont==1){ levels[i+1].insert(bank[k]); flag[k]=1; if(bank[k]==end) return i+1; } } return -1; } };
[ "lijj11@lzu.edu.cn" ]
lijj11@lzu.edu.cn
caf16b5e326e730daad7b02bcdc509dcd3482f8a
f0d7d208a2d2f93bf7cb5217e737ba066d31658f
/2019_2/10866_Deque.cpp
13814afb01245f7c8410f5be7921b95e940d5a82
[]
no_license
Aranch422/Algorithm_Study
c26f82bc7884886e1558edbb2c13799df946dddd
a61a546cc8ddce4fa51272aa9c42ba4933880a58
refs/heads/master
2023-07-23T17:13:13.827634
2023-07-07T15:53:56
2023-07-07T15:53:56
234,075,498
0
0
null
null
null
null
UHC
C++
false
false
2,202
cpp
#include <iostream> #include <string> using namespace std; class node { public: int key; node* next; node() { key = 0; next = NULL; } }; class Deque { public: int size=0; node* begin; node* end; //push void push_front(int x) { node* newnode = new node(); newnode->key = x; if (size != 0) { newnode->next = &(*begin); begin = newnode; } else { newnode->next = NULL; begin = newnode; end = newnode; } size++; } //pop 후 출력 void pop_front() { if (size!=0) { cout << begin->key << "\n"; node* temp = begin->next; delete(begin); begin = temp; size--; } else { cout << -1 << "\n"; } } //push void push_back(int x) { node* newnode = new node(); newnode->key = x; newnode->next = NULL; if (size!=0) { end->next = newnode; end = newnode; } else { end = newnode; begin = newnode; } size++; } //pop 후 출력 void pop_back() { if (size!=0) { cout << end->key << "\n"; node* temp = begin; for (int i = 1; i < size-1;i++) { temp = temp->next; } end = temp; temp->next = NULL; size--; } else { cout << -1 << "\n"; } } //원소개수 출력 void Size() { cout << size<<"\n"; } //empty 비어있으면 1 아니면 0 bool empty() { if (size == 0) { cout << 1 << "\n"; return true; } else { cout << 0 << "\n"; return false; } } //front void front() { if (size!=0) { cout << begin->key << "\n"; } else { cout << -1 << "\n"; } } //back void back() { if (size!=0) { cout << end->key << "\n"; } else { cout << -1 << "\n"; } } }; void solve(string s,Deque &myD) { int x; if (s == "push_back") { cin >> x; myD.push_back(x); } else if (s == "push_front") { cin >> x; myD.push_front(x); } else if (s == "pop_back") { myD.pop_back(); } else if (s == "pop_front") { myD.pop_front(); } else if (s == "empty") { myD.empty(); } else if (s == "front"){ myD.front(); } else if (s == "back") { myD.back(); } else if (s == "size") { myD.Size(); } } int main() { int n; Deque myD; cin >> n; while (n>0) { string s; cin >> s; solve(s,myD); n--; } return 0; }
[ "aranzh@yonsei.ac.kr" ]
aranzh@yonsei.ac.kr
192e83830d0d946d5734ae52a905000a517ecbd4
986c21d401983789d9b3e5255bcf9d76070f65ec
/src/util/network/networkdiskcache.cpp
50d1cb7468441645e9ae74bc94fb245e3612bc2a
[ "BSL-1.0" ]
permissive
0xd34df00d/leechcraft
613454669be3a0cecddd11504950372c8614c4c8
15c091d15262abb0a011db03a98322248b96b46f
refs/heads/master
2023-07-21T05:08:21.348281
2023-06-04T16:50:17
2023-06-04T16:50:17
119,854
149
71
null
2017-09-03T14:16:15
2009-02-02T13:52:45
C++
UTF-8
C++
false
false
2,806
cpp
/********************************************************************** * LeechCraft - modular cross-platform feature rich internet client. * Copyright (C) 2006-2014 Georg Rudoy * * Distributed under the Boost Software License, Version 1.0. * (See accompanying file LICENSE or copy at https://www.boost.org/LICENSE_1_0.txt) **********************************************************************/ #include "networkdiskcache.h" #include <QtDebug> #include <QDir> #include <QMutexLocker> #include <util/sys/paths.h> #include <util/threads/futures.h> #include "networkdiskcachegc.h" namespace LC::Util { namespace { QString GetCacheDir (const QString& subpath) { return GetUserDir (UserDir::Cache, "network/" + subpath).absolutePath (); } } NetworkDiskCache::NetworkDiskCache (const QString& subpath, QObject *parent) : QNetworkDiskCache (parent) , GcGuard_ (NetworkDiskCacheGC::Instance ().RegisterDirectory (GetCacheDir (subpath), [this] { return maximumCacheSize (); })) { setCacheDirectory (GetCacheDir (subpath)); } qint64 NetworkDiskCache::cacheSize () const { return CurrentSize_; } QIODevice* NetworkDiskCache::data (const QUrl& url) { QMutexLocker lock (&InsertRemoveMutex_); return QNetworkDiskCache::data (url); } void NetworkDiskCache::insert (QIODevice *device) { QMutexLocker lock (&InsertRemoveMutex_); if (!PendingDev2Url_.contains (device)) { qWarning () << Q_FUNC_INFO << "stall device detected"; return; } PendingUrl2Devs_ [PendingDev2Url_.take (device)].removeAll (device); CurrentSize_ += device->size (); QNetworkDiskCache::insert (device); } QNetworkCacheMetaData NetworkDiskCache::metaData (const QUrl& url) { QMutexLocker lock (&InsertRemoveMutex_); return QNetworkDiskCache::metaData (url); } QIODevice* NetworkDiskCache::prepare (const QNetworkCacheMetaData& metadata) { QMutexLocker lock (&InsertRemoveMutex_); const auto dev = QNetworkDiskCache::prepare (metadata); PendingDev2Url_ [dev] = metadata.url (); PendingUrl2Devs_ [metadata.url ()] << dev; return dev; } bool NetworkDiskCache::remove (const QUrl& url) { QMutexLocker lock (&InsertRemoveMutex_); for (const auto dev : PendingUrl2Devs_.take (url)) PendingDev2Url_.remove (dev); return QNetworkDiskCache::remove (url); } void NetworkDiskCache::updateMetaData (const QNetworkCacheMetaData& metaData) { QMutexLocker lock (&InsertRemoveMutex_); QNetworkDiskCache::updateMetaData (metaData); } qint64 NetworkDiskCache::expire () { if (CurrentSize_ < 0) { const auto& dir = cacheDirectory (); Util::Sequence (this, NetworkDiskCacheGC::Instance ().GetCurrentSize (dir)) >> [this] (qint64 res) { CurrentSize_ = res; }; return maximumCacheSize () * 8 / 10; } return CurrentSize_; } }
[ "0xd34df00d@gmail.com" ]
0xd34df00d@gmail.com
aff82bf70b4682da1f98f8d8d293225b528a3c9e
1519b6c8282eb1a624e1735e5564d270e970cfdd
/include/GUI/DialogWindowBuilder.h
9a488afb551fe1c06218135ff729f58fce0bc504
[]
no_license
SarandaGamez/DPS
94fc1c4c2c1c189df5a6a732577c79e2ceccfd92
d9d80716610703ec286ffd6dfe14c2d654200c0a
refs/heads/master
2022-11-12T10:01:46.160833
2020-07-10T14:40:12
2020-07-10T14:40:12
255,684,877
0
0
null
null
null
null
UTF-8
C++
false
false
1,050
h
#ifndef GUI_DIALOG_WINDOW_BUILDER_H #define GUI_DIALOG_WINDOW_BUILDER_H #include "GUI/Window.h" #include <SFML/Graphics/Font.hpp> #include "GUI/TextButton.h" #include "GUI/TextComponent.h" #include <memory> #include <vector> namespace gui { class DialogWindowBuilder{ public: DialogWindowBuilder(std::shared_ptr<gui::GraphicComponent> background); DialogWindowBuilder(std::shared_ptr<gui::Window> window); void Reset(std::shared_ptr<gui::Window> window); void Reset(std::shared_ptr<gui::GraphicComponent> background); void SetCaption(const std::string& caption, const sf::Font& font); std::shared_ptr<gui::TextButton> AddOption(const std::string& caption, const sf::Font& font, const sf::Texture& buttonTexture); std::shared_ptr<gui::Window> GetResult(); private: std::shared_ptr<gui::Window> window; std::shared_ptr<gui::TextComponent> caption; std::vector<std::shared_ptr<gui::TextButton>> buttons; void AlignButtons(); void AlignCaption(const std::string& caption); }; } #endif // !GUI_DIALOG_WINDOW_BUILDER_H
[ "bezifabr@gmail.com" ]
bezifabr@gmail.com
6fe2a6169fc42e12f6c9b9f6c92607fa9c521e18
19b6a8318f28da5ef621f17d3ec8e04a706c90c0
/uibase/src/tutorialcontrol.cpp
08698dd0a1f7a43624e59f8c21dc28aec2b962b2
[]
no_license
Holt59/mo2-merge
b10fa6ac545788d32d0a435ca07c3604b1e90f10
242ad876bb650d43bdd47b3a73c1650ab9f32a0f
refs/heads/master
2022-09-08T21:02:22.972613
2020-05-29T08:14:40
2020-05-29T08:14:40
267,673,908
0
1
null
null
null
null
UTF-8
C++
false
false
12,136
cpp
/* Copyright (C) 2012 Sebastian Herbord. All rights reserved. This file is part of Mod Organizer. Mod Organizer is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Mod Organizer 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with Mod Organizer. If not, see <http://www.gnu.org/licenses/>. */ #include "tutorialcontrol.h" #include "utility.h" #include "tutorialmanager.h" #include "report.h" #include "log.h" #include <boost/scoped_array.hpp> #include <QCoreApplication> #include <QQmlEngine> #include <QQmlContext> #include <QQuickItem> #include <QFile> #include <QDir> #include <QMouseEvent> #include <QToolBar> #include <QMenuBar> #include <QAction> #include <QGraphicsObject> #include <QTimer> #include <QAbstractButton> #include <QTableWidget> #include <QImage> #include <QBitmap> #include <QMetaObject> #include <QMetaMethod> #include <QMetaEnum> #include <qmetaobject.h> namespace MOBase { TutorialControl::TutorialControl(const TutorialControl &reference) : QObject(reference.parent()) , m_TargetControl(reference.m_TargetControl) , m_Name(reference.m_Name) , m_TutorialView(nullptr) , m_Manager(TutorialManager::instance()) , m_ExpectedTab(0) , m_CurrentClickControl(nullptr) { } TutorialControl::TutorialControl(QWidget *targetControl, const QString &name) : QObject(nullptr) , m_TargetControl(targetControl) , m_Name(name) , m_TutorialView(nullptr) , m_Manager(TutorialManager::instance()) , m_ExpectedTab(0) , m_CurrentClickControl(nullptr) { } TutorialControl::~TutorialControl() { m_Manager.unregisterControl(m_Name); finish(); } void TutorialControl::registerControl() { m_Manager.registerControl(m_Name, this); } void TutorialControl::resize(const QSize &size) { if (m_TutorialView != nullptr) { m_TutorialView->resize(size.width(), size.height()); } } void TutorialControl::expose(const QString &widgetName, QObject *widget) { m_ExposedObjects.push_back(std::make_pair(widgetName, widget)); } static QString canonicalPath(const QString &path) { boost::scoped_array<wchar_t> buffer(new wchar_t[32768]); DWORD res = ::GetShortPathNameW((wchar_t*)path.utf16(), buffer.get(), 32768); if (res == 0) { return path; } res = ::GetLongPathNameW(buffer.get(), buffer.get(), 32768); if (res == 0) { return path; } return QString::fromWCharArray(buffer.get()); } void TutorialControl::startTutorial(const QString &tutorial) { if (m_TutorialView == nullptr) { m_TutorialView = new QQuickWidget(m_TargetControl); m_TutorialView->setResizeMode(QQuickWidget::SizeRootObjectToView); m_TutorialView->setAttribute(Qt::WA_TranslucentBackground); m_TutorialView->setAttribute(Qt::WA_AlwaysStackOnTop); m_TutorialView->setClearColor(Qt::transparent); m_TutorialView->setStyleSheet("background: transparent"); m_TutorialView->setObjectName("tutorialView"); m_TutorialView->rootContext()->setContextProperty("manager", &m_Manager); QString qmlName = canonicalPath(QCoreApplication::applicationDirPath() + "/tutorials") + "/tutorials_" + m_Name.toLower() + ".qml"; QUrl qmlSource = QUrl::fromLocalFile(qmlName); m_TutorialView->setSource(qmlSource); m_TutorialView->resize(m_TargetControl->width(), m_TargetControl->height()); m_TutorialView->rootContext()->setContextProperty("scriptName", tutorial); m_TutorialView->rootContext()->setContextProperty("tutorialControl", this); m_TutorialView->rootContext()->setContextProperty("applicationWindow", m_TargetControl); m_TutorialView->rootContext()->setContextProperty("organizer", m_Manager.organizerCore()); for (std::vector<std::pair<QString, QObject*> >::const_iterator iter = m_ExposedObjects.begin(); iter != m_ExposedObjects.end(); ++iter) { m_TutorialView->rootContext()->setContextProperty(iter->first, iter->second); } m_TutorialView->show(); m_TutorialView->raise(); if (!QMetaObject::invokeMethod(m_TutorialView->rootObject(), "init")) { reportError(tr("Tutorial failed to start, please check \"mo_interface.log\" for details.")); m_TutorialView->close(); } } } void TutorialControl::lockUI(bool locked) { m_TutorialView->setAttribute(Qt::WA_TransparentForMouseEvents, !locked); QMetaObject::invokeMethod(m_TutorialView->rootObject(), "enableBackground", Q_ARG(QVariant, QVariant(locked))); } void TutorialControl::simulateClick(int x, int y) { bool wasTransparent = m_TutorialView->testAttribute(Qt::WA_TransparentForMouseEvents); if (!wasTransparent) { m_TutorialView->setAttribute(Qt::WA_TransparentForMouseEvents, true); } QWidget *hitControl = m_TargetControl->childAt(x, y); QPoint globalPos = m_TargetControl->mapToGlobal(QPoint(x, y)); QPoint hitPos = hitControl->mapFromGlobal(globalPos); QMouseEvent *downEvent= new QMouseEvent(QEvent::MouseButtonPress, hitPos, Qt::LeftButton, Qt::LeftButton, Qt::NoModifier); QMouseEvent *upEvent= new QMouseEvent(QEvent::MouseButtonRelease, hitPos, Qt::LeftButton, Qt::LeftButton, Qt::NoModifier); qApp->postEvent(hitControl, (QEvent*)downEvent); qApp->postEvent(hitControl, (QEvent*)upEvent); if (!wasTransparent) { m_TutorialView->setAttribute(Qt::WA_TransparentForMouseEvents, false); } } QWidget* TutorialControl::getChild(const QString &name) { if (m_TargetControl != nullptr) { return m_TargetControl->findChild<QWidget*>(name); } else { return nullptr; } } void TutorialControl::finish() { if (m_TutorialView != nullptr) { m_TutorialView->deleteLater(); } m_TutorialView = nullptr; m_TutorialView = nullptr; } QRect TutorialControl::getRect(const QString &widgetName) { if (m_TargetControl != nullptr) { QWidget *widget = m_TargetControl->findChild<QWidget*>(widgetName); if (widget != nullptr) { QRect res = widget->rect(); QPoint pos = widget->mapTo(m_TargetControl, res.topLeft()); res.moveTopLeft(pos); return res; } else { log::error("{} not found", widgetName); return QRect(); } } else { return QRect(); } } QRect TutorialControl::getActionRect(const QString &widgetName) { if (m_TargetControl != nullptr) { QToolBar *toolBar = m_TargetControl->findChild<QToolBar*>("toolBar"); foreach (QAction *action, toolBar->actions()) { if (action->objectName() == widgetName) { return toolBar->actionGeometry(action); } } } return QRect(); } QRect TutorialControl::getMenuRect(const QString&) { if (m_TargetControl != nullptr) { QMenuBar* menuBar = m_TargetControl->findChild<QMenuBar*>("menuBar"); return menuBar->geometry(); } return QRect(); } void TutorialControl::nextTutorialStepProxy() { if (m_TutorialView != nullptr) { QObject *background = m_TutorialView->rootObject(); QTimer::singleShot(1, background, SLOT(nextStep())); lockUI(true); bool success = false; if (sender()->inherits("QAction")) { success = disconnect(sender(), SIGNAL(triggered()), this, SLOT(nextTutorialStepProxy())); } else if (sender()->inherits("QMenu")) { success = disconnect(sender(), SIGNAL(aboutToShow()), this, SLOT(nextTutorialStepProxy())); } else { success = disconnect(sender(), SIGNAL(pressed()), this, SLOT(nextTutorialStepProxy())); } if (!success) { log::error("failed to disconnect tutorial proxy"); } } else { log::error("failed to proceed to next tutorial step"); finish(); } } void TutorialControl::tabChangedProxy(int selected) { if ((m_TutorialView != nullptr) && (selected == m_ExpectedTab)) { QObject *background = m_TutorialView->rootObject(); QTimer::singleShot(1, background, SLOT(nextStep())); lockUI(true); if (!disconnect(sender(), SIGNAL(currentChanged(int)), this, SLOT(tabChangedProxy(int)))) { log::error("failed to disconnect tab-changed proxy"); } } } bool TutorialControl::waitForAction(const QString &actionName) { if (m_TargetControl != nullptr) { QAction *action = m_TargetControl->findChild<QAction*>(actionName); if (action == nullptr) { log::error("no action \"{}\" in control \"{}\"", actionName, m_Name); return false; } if (action->isEnabled()) { if (action->menu() != nullptr) { connect(action->menu(), SIGNAL(aboutToShow()), this, SLOT(nextTutorialStepProxy())); } else { connect(action, SIGNAL(triggered()), this, SLOT(nextTutorialStepProxy())); } lockUI(false); return true; } else { return false; } } else { return false; } } bool TutorialControl::waitForButton(const QString &buttonName) { if (m_TargetControl != nullptr) { QAbstractButton *button = m_TargetControl->findChild<QAbstractButton*>(buttonName); if (button == nullptr) { log::error("no button \"{}\" in control \"{}\"", buttonName, m_Name); return false; } if (button->isEnabled()) { connect(button, SIGNAL(pressed()), this, SLOT(nextTutorialStepProxy())); lockUI(false); return true; } else { return false; } } else { return false; } } bool TutorialControl::waitForTabOpen(const QString &tabControlName, const QString &tab) { if (m_TargetControl != nullptr) { QTabWidget* tabWidget = m_TargetControl->findChild<QTabWidget*>(tabControlName); if (tabWidget == nullptr) { log::error("no tab widget \"{}\" in control \"{}\"", tabControlName, m_Name); return false; } if (tabWidget->findChild<QWidget*>(tab) == nullptr) { log::error("no widget \"{}\" found in tab widget \"{}\"", tab, tabControlName); return false; } int tabIndex = tabWidget->indexOf(tabWidget->findChild<QWidget*>(tab)); if (tabIndex == -1) { log::error( "widget \"{}\" does not appear to be a tab in tab widget \"{}\"", tab, tabControlName); return false; } if (tabWidget->isEnabled()) { if (tabWidget->currentIndex() != tabIndex) { m_ExpectedTab = tabIndex; connect(tabWidget, SIGNAL(currentChanged(int)), this, SLOT(tabChangedProxy(int))); lockUI(false); } else { QObject* background = m_TutorialView->rootObject(); QTimer::singleShot(1, background, SLOT(nextStep())); lockUI(true); } return true; } else { return false; } } else { return false; } } const QString TutorialControl::getTabName(const QString &tabControlName) { if (m_TargetControl != nullptr) { QTabWidget* tabWidget = m_TargetControl->findChild<QTabWidget*>(tabControlName); if (tabWidget == nullptr) { log::error("no tab widget \"{}\" in control \"{}\"", tabControlName, m_Name); return QString(); } if (tabWidget->currentIndex() == -1) { return QString(); } else { return tabWidget->currentWidget()->objectName(); } } else { return QString(); } } } // namespace MOBase
[ "capelle.mikael@gmail.com" ]
capelle.mikael@gmail.com
e156f3145a9d23bca33de7d4028ef3b6852063a6
2bd235464bca304fa8f992cbba55e4df96544fd0
/src/mack/callbacks/consoleoutput.h
1c3f2a587d2506d922ab25a5ee7d97c17db055e5
[]
no_license
queer1/mack
57f54c5e4ed10367ede08cac8b7eea8dd67bfca2
bc9e5c25bf3bb7bffb41ad05435a7a5ef54a0b97
refs/heads/master
2021-01-20T10:57:01.137007
2012-09-20T13:14:03
2012-09-20T13:14:03
null
0
0
null
null
null
null
UTF-8
C++
false
false
999
h
/* * consoleoutput.h * * Created on: 09.08.2012 * Author: Paul Kramer */ #ifndef CONSOLEOUTPUT_H_ #define CONSOLEOUTPUT_H_ #include <mack/callback.hpp> /** * @file mack/callbacks/consoleoutput.h */ namespace mack { namespace callbacks { /** * @class Console_Output * @is_of_type{callbacks} * @brief This callback prints the results to the console. * * @details Only the found targets will be printed in form: * found 'bla': 0x128ecf542a35ac5270a87dc740918404 * * @author Paul Kramer * @date 09.08.2012 * @version 0.1 */ class Console_Output : public Callback{ public: /** * @brief the callback constructor */ Console_Output(); /** * @brief the callback destructor */ virtual ~Console_Output(); /** * @brief The callback call. * @details This function prints a found statement on the console for all found targets. */ void call(unsigned char* target, mack::core::candidate* candidate, unsigned int targetlength); }; } } #endif /* CONSOLEOUTPUT_H_ */
[ "azzaroff@felux.fritz.box" ]
azzaroff@felux.fritz.box
5e1b9eca01ef2656488b44ec5fdac650c82d6e75
38c10c01007624cd2056884f25e0d6ab85442194
/third_party/pdfium/core/src/fpdfdoc/doc_viewerPreferences.cpp
50962b7d47a5cee4ad28d9b50731b769083386d9
[ "BSD-3-Clause", "LGPL-2.0-or-later", "GPL-1.0-or-later", "MIT", "Apache-2.0" ]
permissive
zenoalbisser/chromium
6ecf37b6c030c84f1b26282bc4ef95769c62a9b2
e71f21b9b4b9b839f5093301974a45545dad2691
refs/heads/master
2022-12-25T14:23:18.568575
2016-07-14T21:49:52
2016-07-23T08:02:51
63,980,627
0
2
BSD-3-Clause
2022-12-12T12:43:41
2016-07-22T20:14:04
null
UTF-8
C++
false
false
1,774
cpp
// Copyright 2014 PDFium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // Original code copyright 2014 Foxit Software Inc. http://www.foxitsoftware.com #include "../../include/fpdfdoc/fpdf_doc.h" CPDF_ViewerPreferences::CPDF_ViewerPreferences(CPDF_Document* pDoc) : m_pDoc(pDoc) {} CPDF_ViewerPreferences::~CPDF_ViewerPreferences() {} FX_BOOL CPDF_ViewerPreferences::IsDirectionR2L() const { CPDF_Dictionary* pDict = m_pDoc->GetRoot(); pDict = pDict->GetDict(FX_BSTRC("ViewerPreferences")); if (!pDict) { return FALSE; } return FX_BSTRC("R2L") == pDict->GetString(FX_BSTRC("Direction")); } FX_BOOL CPDF_ViewerPreferences::PrintScaling() const { CPDF_Dictionary* pDict = m_pDoc->GetRoot(); pDict = pDict->GetDict(FX_BSTRC("ViewerPreferences")); if (!pDict) { return TRUE; } return FX_BSTRC("None") != pDict->GetString(FX_BSTRC("PrintScaling")); } int32_t CPDF_ViewerPreferences::NumCopies() const { CPDF_Dictionary* pDict = m_pDoc->GetRoot(); pDict = pDict->GetDict(FX_BSTRC("ViewerPreferences")); if (!pDict) { return 1; } return pDict->GetInteger(FX_BSTRC("NumCopies")); } CPDF_Array* CPDF_ViewerPreferences::PrintPageRange() const { CPDF_Dictionary* pDict = m_pDoc->GetRoot(); CPDF_Array* pRange = NULL; pDict = pDict->GetDict(FX_BSTRC("ViewerPreferences")); if (!pDict) { return pRange; } pRange = pDict->GetArray(FX_BSTRC("PrintPageRange")); return pRange; } CFX_ByteString CPDF_ViewerPreferences::Duplex() const { CPDF_Dictionary* pDict = m_pDoc->GetRoot(); pDict = pDict->GetDict(FX_BSTRC("ViewerPreferences")); if (!pDict) { return FX_BSTRC("None"); } return pDict->GetString(FX_BSTRC("Duplex")); }
[ "zeno.albisser@hemispherian.com" ]
zeno.albisser@hemispherian.com
9f9c2f5edfd98866581a7ddf865c25a49b8faed0
6ab8afcd1de7d81529f239b614c29ba2019e3609
/DataStructure/src/queue.cpp
ed8127b16175aa22b3ec2d2aa775cb5fc3fd29a3
[]
no_license
wangfeng0301/Cpp_DataStructure_VS2010
a754eaebff97141b49418a3292e941d5abc6ca26
a4fe4a192c519fa48929f4815dbff497ee5e9e10
refs/heads/main
2023-05-06T01:38:45.915024
2021-05-22T14:49:22
2021-05-22T14:49:22
365,073,553
0
0
null
null
null
null
GB18030
C++
false
false
1,189
cpp
/************************************************************************ *队列:先进先出的一种数据结构 *参考资料:《数据结构与算法》张铭,王腾蛟,赵海燕等 *wangfeng *E-mail:fengwang0301@163.com *CSDN:https://blog.csdn.net/u013073067?spm=1001.2101.3001.5343 *GitHub:https://github.com/wangfeng0301 *2021.5.3 首次提交 *2021.5.12 将类模板的实现和类定义放在一个文件中,即放在头文件中实现 * 否则在某些时候调用时会出现错误 ************************************************************************/ #include <iostream> #include <stdlib.h> #include <string.h> #include "queue.h" using namespace std; void testQueue(void) { Queue<int> q(5); int dat; q.en(10); q.en(11); q.en(12); q.en(13); q.en(14); q.en(15); for(int i = 0;i<5;i++) { if(q.de(&dat)) cout << dat << endl; } q.clear(); if(q.de(&dat)) cout << dat << endl; } void testLinkQueue(void) { LinkQueue<int> q; int dat; q.en(10); q.en(11); q.en(12); q.en(13); q.en(14); q.en(15); for(int i = 0;i<5;i++) { if(q.de(&dat)) cout << dat << endl; } q.clear(); if(q.de(&dat)) cout << dat << endl; }
[ "fengwang0301@163.com" ]
fengwang0301@163.com
f47eb367de58e1a49d1092e30f18405097ba0f94
7ba00b5ddef44558b503419d53c44640b117adad
/modules/ext/yang/protobuf-c/protobuf-c/protoc-c/c_field.h
650ecc5e92ed9cbdce746d9d1706b5d20d4c177e
[ "Apache-2.0", "BSD-2-Clause" ]
permissive
agunturu/RIFT.ware
50a3d185843589215b5cdafba614fa0a3a199fb7
b1744f1e8d520b31b8df9f58a063e8e6dd80dec7
refs/heads/master
2021-01-22T14:24:49.976255
2016-03-10T22:46:16
2016-03-10T22:46:16
null
0
0
null
null
null
null
UTF-8
C++
false
false
7,328
h
// Protocol Buffers - Google's data interchange format // Copyright 2008 Google Inc. All rights reserved. // http://code.google.com/p/protobuf/ // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // Author: kenton@google.com (Kenton Varda) // Based on original Protocol Buffers design by // Sanjay Ghemawat, Jeff Dean, and others. // Copyright (c) 2008-2013, Dave Benson. 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. // Modified to implement C code by Dave Benson. #ifndef GOOGLE_PROTOBUF_COMPILER_C_FIELD_H__ #define GOOGLE_PROTOBUF_COMPILER_C_FIELD_H__ #include <string> #include <map> #include <google/protobuf/stubs/common.h> #include <google/protobuf/descriptor.h> namespace google { namespace protobuf { namespace io { class Printer; // printer.h } } struct riftfopts { int enforce; int ismsg; int agg; int flatinline; uint32_t inline_max; uint32_t string_max; uint32_t rw_flags; std::string c_type; std::string merge_behave; riftfopts() : enforce(0), ismsg(0), agg(0), flatinline(0), inline_max(0), string_max(0), rw_flags(0) {} }; namespace protobuf { namespace compiler { namespace c { class FieldGenerator { public: explicit FieldGenerator(const FieldDescriptor *descriptor) : descriptor_(descriptor) { rift_parseopts(descriptor_); } virtual ~FieldGenerator(); // Generate definitions to be included in the structure. virtual void GenerateStructMembers(io::Printer* printer) const = 0; // Generate a static initializer for this field. virtual void GenerateDescriptorInitializer(io::Printer* printer) const = 0; virtual void GenerateDefaultValueDeclarations(io::Printer* printer) const { } virtual void GenerateDefaultValueImplementations(io::Printer* printer) const { } virtual string GetDefaultValue() const = 0; virtual bool isCType(void) const; // Generate members to initialize this field from a static initializer virtual void GenerateStaticInit(io::Printer* printer) const = 0; virtual void AssignStructMembers(io::Printer* printer, int num) const = 0; virtual string GetTypeName() const = 0; virtual string GetPointerType() const = 0; // Generate MetaData Macro for this field. void GenerateMetaDataMacro(io::Printer* printer, unsigned index) const; struct riftfopts riftopts; void rift_parseopts(const FieldDescriptor *descriptor_); // Gi code generation support functions. virtual string GetGiTypeName(bool use_const = true) const = 0; string GetParentGiCIdentifier(const char *operation, const string& field) const; string GetParentGiCIdentifier(const char *operation) const; string GetGiCIdentifier(const char *operation) const; // pure virtual functions. virtual string GetGiReturnAnnotations() const = 0; virtual string GetGiGetterReturnType() const = 0; virtual string GetGiGetterParameterList() const = 0; virtual string GetGiParameterAnnotations() const = 0; virtual string GetGiSetterParameterList() const = 0; virtual void GenerateGiCGetterMethod(io::Printer* printer) const = 0; virtual void GenerateGiCSetterMethod(io::Printer* printer) const = 0; string GetGiBoxedFieldName() const; string GetQuantifierField() const; bool HasQuantifierField() const; void GenerateGiHSupportMethodDecls(io::Printer* printer) const; void GenerateGiCSupportMethodDefs(io::Printer* printer) const; virtual void GenerateGiCreateMethod(io::Printer* printer) const { }; virtual string GetGiCreateParameterList() const { }; virtual bool HasLengthOut() const; protected: void GenerateDescriptorInitializerGeneric(io::Printer* printer, bool optional_uses_has, const string &type_macro, const string &descriptor_addr) const; const FieldDescriptor *descriptor_; private: GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(FieldGenerator); }; // Convenience class which constructs FieldGenerators for a Descriptor. class FieldGeneratorMap { public: explicit FieldGeneratorMap(const Descriptor* descriptor); ~FieldGeneratorMap(); const FieldGenerator& get(const FieldDescriptor* field) const; private: const Descriptor* descriptor_; scoped_array<scoped_ptr<FieldGenerator> > field_generators_; static FieldGenerator* MakeGenerator(const FieldDescriptor* field); GOOGLE_DISALLOW_EVIL_CONSTRUCTORS(FieldGeneratorMap); }; } // namespace c } // namespace compiler } // namespace protobuf } // namespace google #endif // GOOGLE_PROTOBUF_COMPILER_C_FIELD_H__
[ "Wei.Wang@riftio.com" ]
Wei.Wang@riftio.com
9e3df8ba782761fcbef9bf569549b4ff1bc661a1
8daf331f2d97b5b2c50d281ef32301eed820ff91
/src/core/common.cpp
72f1bead87e41c55fca40e1d9eece0df90a17454
[]
no_license
Noughmad/Wobble
589b89c1ad9e1a747e21bb7c6a2b9e24753e6491
1d222efdd5c7260438072866f81ead27b7725cd1
refs/heads/master
2021-01-25T10:06:45.998458
2012-03-04T18:52:37
2012-03-04T18:52:37
3,169,158
0
0
null
null
null
null
UTF-8
C++
false
false
2,429
cpp
/* This file is part of Wobble, a code generation framework Copyright (C) 2012 Miha Čančula miha@noughmad.eu This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "common.h" #include "identifier.h" #include "type.h" #include "class.h" #include "variable.h" #include "view.h" #include <QMetaType> #include "function.h" using namespace Wobble; View* Common::detailView() { return 0; } View* Common::listDetailView() { return 0; } View* Common::listView() { return 0; } void Common::registerTypes() { qRegisterMetaType<Identifier*>("Identifier*"); qRegisterMetaType<Type*>("Type*"); qRegisterMetaType<View*>("View*"); qRegisterMetaType<Class*>("Class*"); qRegisterMetaType<ClassList>("ClassList"); qRegisterMetaType<Variable*>("Variable*"); qRegisterMetaType<VariableList>("VariableList"); qRegisterMetaType<Query*>("Query*"); qRegisterMetaType<QueryList>("QueryList"); qRegisterMetaType<Function*>("Function*"); qRegisterMetaType<FunctionList>("FunctionList"); } View* Common::classView(Class* c, bool editable) { /* * TODO: This may be unnecessary, or at least move to Outputs. * For example, Django has a ModelForm, maybe other tookits * have similar functionality. */ View* view = new View(c->name() + "View", c->topLevel()); foreach (Variable* var, c->findChildren<Variable*>()) { view->addSubView(variableView(var)); } return view; } View* Common::variableView(Variable* var, bool editable) { // TODO: Discover the appropriate StandardView from the variable's type View* v = new View(var->name() + "VariableView", var->topLevel()); v->setModel(var->type()); return v; }
[ "miha@noughmad.eu" ]
miha@noughmad.eu
0b436696f1f1aaf4f91b5d2ef7526fb67c0bee88
c09719111455e219f0055f6e5f6780b34bf6e915
/dbms/src/Dictionaries/MongoDBDictionarySource.cpp
ee14b15447aac4cc2d086d72f04e2d847a773c6f
[ "Apache-2.0" ]
permissive
StarWix/ClickHouse
0379ea22098977ebf781388f1bb513303c3188e7
6f106c748eed98ceb492768f0ca73cc51dc4da60
refs/heads/master
2021-01-21T06:59:56.012787
2017-02-27T07:01:52
2017-02-27T07:01:52
83,303,559
1
0
null
2017-02-27T11:35:36
2017-02-27T11:35:36
null
UTF-8
C++
false
false
8,910
cpp
#include <Poco/Util/AbstractConfiguration.h> #include <Poco/MD5Engine.h> #include <Poco/MongoDB/Connection.h> #include <Poco/MongoDB/Database.h> #include <Poco/MongoDB/Cursor.h> #include <Poco/MongoDB/Array.h> #include <Poco/Version.h> #include <DB/Dictionaries/MongoDBBlockInputStream.h> #include <DB/Dictionaries/MongoDBDictionarySource.h> #include <DB/Core/FieldVisitors.h> #include <ext/enumerate.hpp> namespace DB { namespace ErrorCodes { extern const int UNSUPPORTED_METHOD; extern const int WRONG_PASSWORD; extern const int MONGODB_CANNOT_AUTHENTICATE; } static const size_t max_block_size = 8192; /// See https://pocoproject.org/forum/viewtopic.php?f=10&t=6326&p=11426&hilit=mongodb+auth#p11485 static void authenticate(Poco::MongoDB::Connection & connection, const std::string & database, const std::string & user, const std::string & password) { Poco::MongoDB::Database db(database); /// Challenge-response authentication. std::string nonce; /// First step: request nonce. { auto command = db.createCommand(); command->setNumberToReturn(1); command->selector().add<Int32>("getnonce", 1); Poco::MongoDB::ResponseMessage response; connection.sendRequest(*command, response); if (response.documents().empty()) throw Exception("Cannot authenticate in MongoDB: server returned empty response for 'getnonce' command", ErrorCodes::MONGODB_CANNOT_AUTHENTICATE); auto doc = response.documents()[0]; try { double ok = doc->get<double>("ok", 0); if (ok != 1) throw Exception("Cannot authenticate in MongoDB: server returned response for 'getnonce' command that" " has field 'ok' missing or having wrong value", ErrorCodes::MONGODB_CANNOT_AUTHENTICATE); nonce = doc->get<std::string>("nonce", ""); if (nonce.empty()) throw Exception("Cannot authenticate in MongoDB: server returned response for 'getnonce' command that" " has field 'nonce' missing or empty", ErrorCodes::MONGODB_CANNOT_AUTHENTICATE); } catch (Poco::NotFoundException & e) { throw Exception("Cannot authenticate in MongoDB: server returned response for 'getnonce' command that has missing required field: " + e.displayText(), ErrorCodes::MONGODB_CANNOT_AUTHENTICATE); } } /// Second step: use nonce to calculate digest and send it back to the server. /// Digest is hex_md5(n.nonce + username + hex_md5(username + ":mongo:" + password)) { std::string first = user + ":mongo:" + password; Poco::MD5Engine md5; md5.update(first); std::string digest_first(Poco::DigestEngine::digestToHex(md5.digest())); std::string second = nonce + user + digest_first; md5.reset(); md5.update(second); std::string digest_second(Poco::DigestEngine::digestToHex(md5.digest())); auto command = db.createCommand(); command->setNumberToReturn(1); command->selector() .add<Int32>("authenticate", 1) .add<std::string>("user", user) .add<std::string>("nonce", nonce) .add<std::string>("key", digest_second); Poco::MongoDB::ResponseMessage response; connection.sendRequest(*command, response); if (response.empty()) throw Exception("Cannot authenticate in MongoDB: server returned empty response for 'authenticate' command", ErrorCodes::MONGODB_CANNOT_AUTHENTICATE); auto doc = response.documents()[0]; try { double ok = doc->get<double>("ok", 0); if (ok != 1) throw Exception("Cannot authenticate in MongoDB: server returned response for 'authenticate' command that" " has field 'ok' missing or having wrong value", ErrorCodes::MONGODB_CANNOT_AUTHENTICATE); } catch (Poco::NotFoundException & e) { throw Exception("Cannot authenticate in MongoDB: server returned response for 'authenticate' command that has missing required field: " + e.displayText(), ErrorCodes::MONGODB_CANNOT_AUTHENTICATE); } } } MongoDBDictionarySource::MongoDBDictionarySource( const DictionaryStructure & dict_struct, const std::string & host, UInt16 port, const std::string & user, const std::string & password, const std::string & method, const std::string & db, const std::string & collection, const Block & sample_block) : dict_struct{dict_struct}, host{host}, port{port}, user{user}, password{password}, method{method}, db{db}, collection{collection}, sample_block{sample_block}, connection{std::make_shared<Poco::MongoDB::Connection>(host, port)} { if (!user.empty()) { #if POCO_VERSION >= 0x01070800 Poco::MongoDB::Database poco_db(db); poco_db.authenticate(*connection, user, password, method.empty() ? Poco::MongoDB::Database::AUTH_SCRAM_SHA1 : method); #else authenticate(*connection, db, user, password); #endif } } MongoDBDictionarySource::MongoDBDictionarySource( const DictionaryStructure & dict_struct, const Poco::Util::AbstractConfiguration & config, const std::string & config_prefix, Block & sample_block) : MongoDBDictionarySource( dict_struct, config.getString(config_prefix + ".host"), config.getUInt(config_prefix + ".port"), config.getString(config_prefix + ".user", ""), config.getString(config_prefix + ".password", ""), config.getString(config_prefix + ".method", ""), config.getString(config_prefix + ".db", ""), config.getString(config_prefix + ".collection"), sample_block) { } MongoDBDictionarySource::MongoDBDictionarySource(const MongoDBDictionarySource & other) : MongoDBDictionarySource{ other.dict_struct, other.host, other.port, other.user, other.password, other.method, other.db, other.collection, other.sample_block} { } MongoDBDictionarySource::~MongoDBDictionarySource() = default; static std::unique_ptr<Poco::MongoDB::Cursor> createCursor( const std::string & database, const std::string & collection, const Block & sample_block_to_select) { auto cursor = std::make_unique<Poco::MongoDB::Cursor>(database, collection); /// Looks like selecting _id column is implicit by default. if (!sample_block_to_select.has("_id")) cursor->query().returnFieldSelector().add("_id", 0); for (const auto & column : sample_block_to_select.getColumns()) cursor->query().returnFieldSelector().add(column.name, 1); return cursor; } BlockInputStreamPtr MongoDBDictionarySource::loadAll() { return std::make_shared<MongoDBBlockInputStream>( connection, createCursor(db, collection, sample_block), sample_block, max_block_size); } BlockInputStreamPtr MongoDBDictionarySource::loadIds(const std::vector<UInt64> & ids) { if (!dict_struct.id) throw Exception{"'id' is required for selective loading", ErrorCodes::UNSUPPORTED_METHOD}; auto cursor = createCursor(db, collection, sample_block); /** NOTE: While building array, Poco::MongoDB requires passing of different unused element names, along with values. * In general, Poco::MongoDB is quite inefficient and bulky. */ Poco::MongoDB::Array::Ptr ids_array(new Poco::MongoDB::Array); for (const UInt64 id : ids) ids_array->add(DB::toString(id), Int32(id)); cursor->query().selector().addNewDocument(dict_struct.id.value().name) .add("$in", ids_array); return std::make_shared<MongoDBBlockInputStream>( connection, std::move(cursor), sample_block, max_block_size); } BlockInputStreamPtr MongoDBDictionarySource::loadKeys( const ConstColumnPlainPtrs & key_columns, const std::vector<std::size_t> & requested_rows) { if (!dict_struct.key) throw Exception{"'key' is required for selective loading", ErrorCodes::UNSUPPORTED_METHOD}; auto cursor = createCursor(db, collection, sample_block); Poco::MongoDB::Array::Ptr keys_array(new Poco::MongoDB::Array); for (const auto row_idx : requested_rows) { auto & key = keys_array->addNewDocument(DB::toString(row_idx)); for (const auto attr : ext::enumerate(*dict_struct.key)) { switch (attr.second.underlying_type) { case AttributeUnderlyingType::UInt8: case AttributeUnderlyingType::UInt16: case AttributeUnderlyingType::UInt32: case AttributeUnderlyingType::UInt64: case AttributeUnderlyingType::Int8: case AttributeUnderlyingType::Int16: case AttributeUnderlyingType::Int32: case AttributeUnderlyingType::Int64: key.add(attr.second.name, Int32(key_columns[attr.first]->get64(row_idx))); break; case AttributeUnderlyingType::Float32: case AttributeUnderlyingType::Float64: key.add(attr.second.name, applyVisitor(FieldVisitorConvertToNumber<Float64>(), (*key_columns[attr.first])[row_idx])); break; case AttributeUnderlyingType::String: key.add(attr.second.name, get<String>((*key_columns[attr.first])[row_idx])); break; } } } cursor->query().selector().add("$or", keys_array); return std::make_shared<MongoDBBlockInputStream>( connection, std::move(cursor), sample_block, max_block_size); } std::string MongoDBDictionarySource::toString() const { return "MongoDB: " + db + '.' + collection + ',' + (user.empty() ? " " : " " + user + '@') + host + ':' + DB::toString(port); } }
[ "milovidov@yandex-team.ru" ]
milovidov@yandex-team.ru
8f930e010e3b3aef41e41a74b65361cb0ed412d6
d3506a1dcca099154a11dc0fb9276c02487cc5a2
/wcm/shell.cpp
4ba6c353cccb04624cfc7c2bffcaf33bef7794ba
[ "MIT" ]
permissive
kvark/WalCommander
6fc00a3f91f2a144ca625280c45f2198fabd0921
86fbf1ce9f79d23b35abd1417c49ac4a2cf2d47a
refs/heads/master
2021-01-15T09:18:39.336865
2014-10-07T20:12:47
2014-10-07T20:12:55
24,912,101
2
0
null
null
null
null
UTF-8
C++
false
false
7,151
cpp
/* * Part of Wal Commander GitHub Edition * https://github.com/corporateshark/WalCommander * walcommander@linderdaum.com */ #include <sys/types.h> #include <signal.h> #include <sys/wait.h> #include <termios.h> #include <sys/ioctl.h> #include "shell.h" /* протокол внутреннего шела - синхронный (запрос - ответ) запрос: char - комманда char - количество параметров 0 - 127 параметры: строки strz ответ: char - код результата не 0 если ошибка char - количество параметров 0 - 127 параметры: строки strz */ enum CMDS { CMD_EXEC = 1, CMD_WAIT = 2, CMD_CD = 3 }; static void ShellProc( int in, int out ); Shell::Shell( const char* slave ) : pid( -1 ), in( -1 ), out( -1 ), slaveName( new_char_str( slave ) ) { Run(); } void Shell::Stop() { if ( pid > 0 ) { kill( pid, 9 ); int status = 0; waitpid( pid, &status, 0 ); pid = -1; } if ( in >= 0 ) { close( in ); in = -1; } if ( out >= 0 ) { close( out ); out = -1; } } void Shell::Run() { Stop(); int pipe1[2] = { -1, -1}; int pipe2[2] = { -1, -1}; if ( pipe( pipe1 ) || pipe( pipe2 ) ) { printf( "can`t create pipe\n" ); } pid_t p = fork(); if ( !p ) { close( pipe1[0] ); close( pipe2[1] ); setenv( "TERM", "xterm", 1 ); pid_t sid = setsid(); if ( sid < 0 ) { printf( "setsid error\n" ); } int slaveFd = open( slaveName.data(), O_RDWR ); if ( slaveFd < 0 ) { printf( "can`t open slave terminal file '%s'\n", slaveName.data() ); } //недоделано struct termios attr; if ( !tcgetattr( slaveFd, &attr ) ) { attr.c_lflag |= ECHO | ISIG | ICANON; attr.c_cc[VINTR] = 3; tcsetattr( slaveFd, TCSAFLUSH, &attr ); } dup2( slaveFd, 0 ); dup2( slaveFd, 1 ); dup2( slaveFd, 2 ); close( slaveFd ); //сделать терминал - контролирующим терминалом if ( ioctl( 0, TIOCSCTTY, 0 ) ) { printf( "ioctl(0, TIOCSCTTY, 0) error\n" ); } ShellProc( pipe2[0], pipe1[1] ); exit( 1 ); } in = pipe1[0]; out = pipe2[1]; close( pipe1[1] ); close( pipe2[0] ); fcntl( in, F_SETFD, long( FD_CLOEXEC ) ); fcntl( out, F_SETFD, long( FD_CLOEXEC ) ); pid = p; //printf(" run shell (pid=%i)\n", p); } Shell::~Shell() { Stop(); } static void ReadPipe( int fd, void* p, int size ) //throw int { int r = read( fd, p, size ); if ( r < 0 ) { throw int( 1 ); } if ( r != size ) { throw int( 2 ); } } static void WritePipe( int fd, void* p, int size ) //throw int { int r = write( fd, p, size ); if ( r < 0 ) { throw int( 1 ); } if ( r != size ) { throw int( 2 ); } } inline char ReadPipeChar( int fd ) { char c; ReadPipe( fd, &c, sizeof( c ) ); return c; } inline void WritePipeChar( int fd, char c ) { WritePipe( fd, &c, sizeof( c ) ); } static void WritePipeStr( int fd, const char* s ) { while ( true ) { WritePipeChar( fd, *s ); if ( !*s ) { break; } s++; } } static std::vector<char> ReadPipeStr( int fd ) { ccollect<char, 0x100> p; char c; while ( true ) { c = ReadPipeChar( fd ); p.append( c ); if ( !c ) { break; } } return p.grab(); } static bool ReadCmd( int fd, int* pCmd, ccollect<std::vector<char> >& params ) { try { *pCmd = ReadPipeChar( fd ); params.clear(); int count = ReadPipeChar( fd ); for ( int i = 0; i < count; i++ ) //!!! { params.append( ReadPipeStr( fd ) ); } } catch ( int n ) { return false; } return true; } static bool WriteCmd( int fd, int cmd, ccollect<char*>& list ) { try { WritePipeChar( fd, cmd ); WritePipeChar( fd, list.count() ); for ( int i = 0; i < list.count(); i++ ) { WritePipeStr( fd, list[i] ); } } catch ( int n ) { return false; } return true; } static bool WriteCmd( int fd, int cmd, ccollect<std::vector<char> >& list ) { try { WritePipeChar( fd, cmd ); WritePipeChar( fd, list.count() ); for ( int i = 0; i < list.count(); i++ ) { WritePipeStr( fd, list[i].data() ); } } catch ( int n ) { return false; } return true; } static bool WriteCmd( int fd, int cmd, const char* s ) { try { WritePipeChar( fd, cmd ); WritePipeChar( fd, 1 ); WritePipeStr( fd, s ); } catch ( int n ) { return false; } return true; } inline void AddInt( ccollect<std::vector<char> >& list, int n ) { char buf[64]; sprintf( buf, "%i", n ); list.append( new_char_str( buf ) ); } static void ShellProc( int in, int out ) { fcntl( in, F_SETFD, long( FD_CLOEXEC ) ); fcntl( out, F_SETFD, long( FD_CLOEXEC ) ); signal( SIGINT, SIG_IGN ); while ( true ) { ccollect<std::vector<char> > pList; int cmd = 0; if ( !ReadCmd( in, &cmd, pList ) ) { exit( 1 ); } switch ( cmd ) { case CMD_EXEC: { pid_t pid = fork(); if ( !pid ) { signal( SIGINT, SIG_DFL ); static char shell[] = "/bin/sh"; if ( pList.count() ) { const char* params[] = {shell, "-c", pList[0].data(), NULL}; execv( shell, ( char** ) params ); printf( "error execute %s\n", shell ); } else { printf( "internal err (no shall paremeters)\n" ); } exit( 1 ); } char buf[64]; sprintf( buf, "%i", int( pid ) ); if ( !WriteCmd( out, 0, buf ) ) { exit( 1 ); } } break; case CMD_WAIT: { if ( pList.count() <= 0 ) { printf( "intermnal error 1\n" ); exit( 1 ); } int status = 0; int ret = waitpid( atoi( pList[0].data() ), &status, 0 ); pList.clear(); AddInt( pList, ret ); AddInt( pList, status ); AddInt( pList, errno ); if ( !WriteCmd( out, 0, pList ) ) { exit( 1 ); } } break; case CMD_CD: { if ( pList.count() <= 0 ) { printf( "intermnal error 2\n" ); exit( 1 ); } int ret = chdir( pList[0].data() ); pList.clear(); AddInt( pList, ret ); AddInt( pList, errno ); if ( !WriteCmd( out, 0, pList ) ) { exit( 1 ); } } break; default: if ( !WriteCmd( out, 1, "unknown internal shell command" ) ) { exit( 1 ); } printf( "internal err (unknown shell command)\n" ); break; }; } } pid_t Shell::Exec( const char* cmd ) { if ( !WriteCmd( out, CMD_EXEC, cmd ) ) { Run(); return -1; } ccollect<std::vector<char> > list; int r; if ( !ReadCmd( in, &r, list ) ) { Run(); return -1; } if ( list.count() <= 0 ) { Run(); return -1; } return atoi( list[0].data() ); } int Shell::Wait( pid_t pid, int* pStatus ) { char buf[64]; sprintf( buf, "%i", pid ); if ( !WriteCmd( out, CMD_WAIT, buf ) ) { Run(); return -1; } ccollect<std::vector<char> > list; int r; if ( !ReadCmd( in, &r, list ) ) { Run(); return -1; } if ( list.count() <= 0 ) { Run(); return -1; } return atoi( list[0].data() ); } int Shell::CD( const char* path ) { if ( !WriteCmd( out, CMD_CD, path ) ) { Run(); return -1; } ccollect<std::vector<char> > list; int r; if ( !ReadCmd( in, &r, list ) ) { Run(); return -1; } if ( list.count() <= 0 ) { Run(); return -1; } return atoi( list[0].data() ); }
[ "sk@linderdaum.com" ]
sk@linderdaum.com
d9e76d9249eb273a282d957a443ad9c7c3a4434a
0b0aaa2c0b1f87112599b331e995df8c646895db
/Pratica/Pratica 3/4/4.cpp
fabab6f1cae993fb0c917cb98f9c472d0158809b
[]
no_license
VictorGeralt/ProgII
044679c172de5548b9ce082d3cf651a3bb2433bf
4eebdc4ccfa4f53c571c641f5229e788053a0524
refs/heads/master
2020-07-26T02:40:14.670116
2019-09-22T20:00:42
2019-09-22T20:00:42
207,871,882
0
0
null
null
null
null
UTF-8
C++
false
false
226
cpp
#include <iostream> #include <fstream> using namespace std; int main(){ int linha=0; char c; ifstream file("lab2.txt"); while (file.get(c)) { if (c=='\n') { linha++; } } cout<<"Linhas: "<<linha; }
[ "victor.vic2009@Hotmail.com" ]
victor.vic2009@Hotmail.com
8a61b8da856e0ff0bc90d0ed8ebd1e9adc31d4f8
41a76318e5b9eef2c69bbf922724f8b191d7d124
/kokkos/core/src/eti/HPX/Kokkos_HPX_ViewCopyETIInst_int64_t_double_LayoutStride_Rank8.cpp
c1e57d2db0458e9beb1048406c263057df930e13
[ "BSD-3-Clause", "BSD-2-Clause" ]
permissive
zishengye/compadre
d0ff10deca224284e7e153371a738e053e66012a
75b738a6a613c89e3c3232cbf7b2589a6b28d0a3
refs/heads/master
2021-06-25T06:16:38.327543
2021-04-02T02:08:48
2021-04-02T02:08:48
223,650,267
0
0
NOASSERTION
2019-11-23T20:41:03
2019-11-23T20:41:02
null
UTF-8
C++
false
false
2,720
cpp
//@HEADER // ************************************************************************ // // Kokkos v. 3.0 // Copyright (2020) National Technology & Engineering // Solutions of Sandia, LLC (NTESS). // // Under the terms of Contract DE-NA0003525 with NTESS, // the U.S. Government retains certain rights in this software. // // Kokkos is licensed under 3-clause BSD terms of use: // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // 1. Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // 2. Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // 3. Neither the name of the Corporation nor the names of the // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY SANDIA CORPORATION "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 SANDIA CORPORATION OR THE // 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. // // Questions? Contact Christian R. Trott (crtrott@sandia.gov) // // ************************************************************************ //@HEADER #define KOKKOS_IMPL_COMPILING_LIBRARY true #include <Kokkos_Core.hpp> namespace Kokkos { namespace Impl { KOKKOS_IMPL_VIEWCOPY_ETI_INST(double********, LayoutStride, LayoutRight, Experimental::HPX, int64_t) KOKKOS_IMPL_VIEWCOPY_ETI_INST(double********, LayoutStride, LayoutLeft, Experimental::HPX, int64_t) KOKKOS_IMPL_VIEWCOPY_ETI_INST(double********, LayoutStride, LayoutStride, Experimental::HPX, int64_t) KOKKOS_IMPL_VIEWFILL_ETI_INST(double********, LayoutStride, Experimental::HPX, int64_t) } // namespace Impl } // namespace Kokkos
[ "pakuber@sandia.gov" ]
pakuber@sandia.gov
ba9f5fbec1cae7dad0ad8f41239a7d93948b2f2c
037d518773420f21d74079ee492827212ba6e434
/blaze/util/mpl/Equal.h
c397dda77191b38c3a9d4889e87c7352318a83cc
[ "BSD-3-Clause", "BSD-2-Clause" ]
permissive
chkob/forked-blaze
8d228f3e8d1f305a9cf43ceaba9d5fcd603ecca8
b0ce91c821608e498b3c861e956951afc55c31eb
refs/heads/master
2021-09-05T11:52:03.715469
2018-01-27T02:31:51
2018-01-27T02:31:51
112,014,398
0
0
null
null
null
null
UTF-8
C++
false
false
3,599
h
//================================================================================================= /*! // \file blaze/util/mpl/Equal.h // \brief Header file for the Equal class template // // Copyright (C) 2012-2018 Klaus Iglberger - All Rights Reserved // // This file is part of the Blaze library. You can redistribute it and/or modify it under // the terms of the New (Revised) BSD License. Redistribution and use in source and binary // forms, with or without modification, are permitted provided that the following conditions // are met: // // 1. Redistributions of source code must retain the above copyright notice, this list of // conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright notice, this list // of conditions and the following disclaimer in the documentation and/or other materials // provided with the distribution. // 3. Neither the names of the Blaze development group nor the names of its contributors // may be used to endorse or promote products derived from this software without specific // prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES // OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT // SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED // TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR // BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN // ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH // DAMAGE. */ //================================================================================================= #ifndef _BLAZE_UTIL_MPL_EQUAL_H_ #define _BLAZE_UTIL_MPL_EQUAL_H_ //************************************************************************************************* // Includes //************************************************************************************************* #include <blaze/util/mpl/Bool.h> namespace blaze { //================================================================================================= // // CLASS DEFINITION // //================================================================================================= //************************************************************************************************* /*!\brief Compile time type comparison. // \ingroup mpl // // The Equal alias declaration compares the two given types using the equality operator ('=='). // In case \a T1::value is equal to \a T2::value, the nested \a value member is set to \a true. // Otherwise it is set to \a false. \code using namespace blaze; Equal< Int<3>, Int<3> >::value // Evaluates to true Equal< Int<5>, Long<5> >::value // Evaluates to true Equal< Long<0>, Int<4> >::value // Evaluates to false Equal< Int<1>, Int<2>::ValueType // Results in bool \endcode */ template< typename T1 // The type of the left-hand side operand , typename T2 > // The type of the right-hand side operand struct Equal : public Bool< ( T1::value == T2::value ) > {}; //************************************************************************************************* } // namespace blaze #endif
[ "klaus.iglberger@gmail.com" ]
klaus.iglberger@gmail.com
4a53fb3feb9e03df44f43630ce65cc09ad7ca502
67e17d140cd439e75a07cfb9f09c7bc73dcafc94
/Tests/ESP-Quadcopter-Codes/espcopter-ROS/src/libraries/ros_lib/stdr_msgs/AddSoundSource.h
617ae2c62abbc8ffef24f182f631173dd0293b93
[ "Apache-2.0" ]
permissive
ClockWorkKid/WiFi-Nano-Quadcopter
4f9419c0cd98348654cdbb7ff8f8d8c752f69ee7
d588c165e88de9661d2df484df7f02110dc36614
refs/heads/master
2022-12-27T13:01:43.943644
2020-10-12T07:09:38
2020-10-12T07:09:38
266,081,215
2
0
null
null
null
null
UTF-8
C++
false
false
2,900
h
#ifndef _ROS_SERVICE_AddSoundSource_h #define _ROS_SERVICE_AddSoundSource_h #include <stdint.h> #include <string.h> #include <stdlib.h> #include "ros/msg.h" #include "stdr_msgs/SoundSource.h" namespace stdr_msgs { static const char ADDSOUNDSOURCE[] = "stdr_msgs/AddSoundSource"; class AddSoundSourceRequest : public ros::Msg { public: typedef stdr_msgs::SoundSource _newSource_type; _newSource_type newSource; AddSoundSourceRequest(): newSource() { } virtual int serialize(unsigned char *outbuffer) const { int offset = 0; offset += this->newSource.serialize(outbuffer + offset); return offset; } virtual int deserialize(unsigned char *inbuffer) { int offset = 0; offset += this->newSource.deserialize(inbuffer + offset); return offset; } const char * getType(){ return ADDSOUNDSOURCE; }; const char * getMD5(){ return "c29faee1e29b2a8ababeae8f802069e9"; }; }; class AddSoundSourceResponse : public ros::Msg { public: typedef bool _success_type; _success_type success; typedef const char* _message_type; _message_type message; AddSoundSourceResponse(): success(0), message("") { } virtual int serialize(unsigned char *outbuffer) const { int offset = 0; union { bool real; uint8_t base; } u_success; u_success.real = this->success; *(outbuffer + offset + 0) = (u_success.base >> (8 * 0)) & 0xFF; offset += sizeof(this->success); uint32_t length_message = strlen(this->message); varToArr(outbuffer + offset, length_message); offset += 4; memcpy(outbuffer + offset, this->message, length_message); offset += length_message; return offset; } virtual int deserialize(unsigned char *inbuffer) { int offset = 0; union { bool real; uint8_t base; } u_success; u_success.base = 0; u_success.base |= ((uint8_t) (*(inbuffer + offset + 0))) << (8 * 0); this->success = u_success.real; offset += sizeof(this->success); uint32_t length_message; arrToVar(length_message, (inbuffer + offset)); offset += 4; for(unsigned int k= offset; k< offset+length_message; ++k){ inbuffer[k-1]=inbuffer[k]; } inbuffer[offset+length_message-1]=0; this->message = (char *)(inbuffer + offset-1); offset += length_message; return offset; } const char * getType(){ return ADDSOUNDSOURCE; }; const char * getMD5(){ return "937c9679a518e3a18d831e57125ea522"; }; }; class AddSoundSource { public: typedef AddSoundSourceRequest Request; typedef AddSoundSourceResponse Response; }; } #endif
[ "msmohammad90@gmail.com" ]
msmohammad90@gmail.com
d224a494a8f6efb930de4e3772ea1040a4d5e26e
e96dbc2964dabbc089a8a95ec69866f5bfd5e529
/projects/graduate/cs6V81-independent-research/project/Quaternion.cpp
6bcd597090f55f843deafe790c6a81bd1a921124
[]
no_license
umairsajid/my-random-cpp-libraries
871ba5a748732652438eda19ab1cc9ded25e9489
8c07ed3d4eba2bb5aeebe368a94c9b16676de819
refs/heads/master
2021-01-21T03:14:23.904870
2013-05-10T23:18:48
2013-05-10T23:18:48
null
0
0
null
null
null
null
UTF-8
C++
false
false
915
cpp
#include "Quaternion.h" Quaternion::Quaternion() : values(0.0, 0.0, 0.0, 0.0) { } Quaternion::Quaternion( float x, float y, float z, float w ) { values.x = x; values.y = y; values.z = z; values.w = w; } Quaternion::Quaternion( const Quaternion& rhs ) { values.x = rhs.values.x; values.y = rhs.values.y; values.z = rhs.values.z; values.w = rhs.values.w; } Quaternion::~Quaternion() { // nada } Quaternion& Quaternion::operator=( const Quaternion& rhs ) { if ( this == &rhs ) { return *this; } values.x = rhs.values.x; values.y = rhs.values.y; values.z = rhs.values.z; values.w = rhs.values.w; return *this; } XMMATRIX Quaternion::to_matrix() { XMMATRIX temp; // do some crazy math here return temp; } HRESULT Quaternion::from_matrix( const XMMATRIX& mat ) { HRESULT hr; // do some crazy math here return hr; }
[ "Flaming.Zelda@gmail.com@4324a9da-489b-ea18-4a0b-e0fe39f471b6" ]
Flaming.Zelda@gmail.com@4324a9da-489b-ea18-4a0b-e0fe39f471b6
c6ca38e472bca3d315108ae25bfd4bc6a3c98f82
6a3105ce63d0ca261a8c6a96ae34c54b034bafc2
/src/faceutil.hpp
13e4de03af3ea2a3c1306b96733df70f14ef6b79
[]
no_license
mincore/facealg
548180407a3c3106aee702d30f61548b94d5cd12
155a6e6760969eee786d1741db502c4662c65dfd
refs/heads/master
2021-07-25T12:03:54.275569
2017-11-07T16:50:10
2017-11-07T16:50:10
109,864,391
1
0
null
null
null
null
UTF-8
C++
false
false
7,681
hpp
/* =================================================== * Copyright (C) 2017 chenshuangping All Right Reserved. * Author: mincore@163.com * Filename: faceutil.hpp * Created: 2017-11-07 16:44 * Description: * =================================================== */ #ifndef _FACEUTIL_HPP_ #define _FACEUTIL_HPP_ #include <faceinfo.hpp> /* enum cmpType{SCORE, AREA, CENTER}; class cmpFunc { public: cmpFunc(cmpType c, int height, int width):cmptype(c),h(height),w(width) {} cmpFunc(cmpType c) {cmpFunc(c, 0, 0);} cmpFunc() {cmpFunc(SCORE);} bool operator () (const FaceInfo& a, const FaceInfo& b) { float area1, area2; float center_x, center_y; float center_x1, center_y1; float center_x2, center_y2; float distance_1, distance_2; switch(cmptype) { case SCORE: return a.bbox.score>b.bbox.score; case AREA: area1 = (a.bbox.x2 - a.bbox.x1) * (a.bbox.y2 - a.bbox.y1); area2 = (b.bbox.x2 - b.bbox.x1) * (b.bbox.y2 - b.bbox.y1); return area1 > area2; case CENTER: center_x = w / 2; center_y = h / 2; center_x1 = (a.bbox.x2 + a.bbox.x1)/2; center_y1 = (a.bbox.y2 + a.bbox.y1)/2; center_x2 = (b.bbox.x2 + b.bbox.x1)/2; center_y2 = (b.bbox.y2 + b.bbox.y1)/2; distance_1 = (center_x1 - center_x)*(center_x1 - center_x) + (center_y1 - center_y)*(center_y1-center_y); distance_2 = (center_x2 - center_x)*(center_x2 - center_x) + (center_y2 - center_y)*(center_y1-center_y); return distance_1 < distance_2; default: return a.bbox.score>b.bbox.score; } } private: cmpType cmptype; float h, w; }; */ bool cmpFunc_SCORE(const FaceInfo& a, const FaceInfo& b) { return a.bbox.score > b.bbox.score; } bool cmpFunc_AREA(const FaceInfo& a, const FaceInfo& b) { float area1 = (a.bbox.x2 - a.bbox.x1) * (a.bbox.y2 - a.bbox.y1); float area2 = (b.bbox.x2 - b.bbox.x1) * (b.bbox.y2 - b.bbox.y1); return area1 > area2; } std::vector<FaceInfo> NMS(std::vector<FaceInfo>& bboxes, float thresh,char nmstype){ std::vector<FaceInfo> bboxes_nms; std::sort(bboxes.begin(), bboxes.end(), cmpFunc_SCORE); int32_t select_idx = 0; int32_t num_bbox = static_cast<int32_t>(bboxes.size()); std::vector<bool> mask_merged(num_bbox, false); bool all_merged = false; while (!all_merged) { while (select_idx < num_bbox && mask_merged[select_idx]) select_idx++; if (select_idx == num_bbox) { all_merged = true; continue; } bboxes_nms.push_back(bboxes[select_idx]); mask_merged[select_idx] = true; FaceRect select_bbox = bboxes[select_idx].bbox; float area1 = static_cast<float>((select_bbox.x2-select_bbox.x1+1) * (select_bbox.y2-select_bbox.y1+1)); float x1 = static_cast<float>(select_bbox.x1); float y1 = static_cast<float>(select_bbox.y1); float x2 = static_cast<float>(select_bbox.x2); float y2 = static_cast<float>(select_bbox.y2); select_idx++; for (int32_t i = select_idx; i < num_bbox; i++) { if (mask_merged[i]) continue; FaceRect& bbox_i = bboxes[i].bbox; float x = std::max<float>(x1, static_cast<float>(bbox_i.x1)); float y = std::max<float>(y1, static_cast<float>(bbox_i.y1)); float w = std::min<float>(x2, static_cast<float>(bbox_i.x2)) - x + 1; float h = std::min<float>(y2, static_cast<float>(bbox_i.y2)) - y + 1; if (w <= 0 || h <= 0) continue; float area2 = static_cast<float>((bbox_i.x2-bbox_i.x1+1) * (bbox_i.y2-bbox_i.y1+1)); float area_intersect = w * h; switch (nmstype) { case 'u': if (static_cast<float>(area_intersect) / (area1 + area2 - area_intersect) > thresh) mask_merged[i] = true; break; case 'm': if (static_cast<float>(area_intersect) / std::min(area1 , area2) > thresh) mask_merged[i] = true; break; default: break; } } } return bboxes_nms; } // methodType : u is IoU(Intersection Over Union) // methodType : m is IoM(Intersection Over Minimum) enum nmsType{UNION, MINIMUM}; std::vector<FaceInfo> NMS(std::vector<FaceInfo>& bboxes, float thresh, nmsType nmstype){ std::vector<FaceInfo> bboxes_nms; std::sort(bboxes.begin(), bboxes.end(), cmpFunc_SCORE); int32_t select_idx = 0; int32_t num_bbox = static_cast<int32_t>(bboxes.size()); std::vector<bool> mask_merged(num_bbox, false); bool all_merged = false; while (!all_merged) { while (select_idx < num_bbox && mask_merged[select_idx]) select_idx++; if (select_idx == num_bbox) { all_merged = true; continue; } bboxes_nms.push_back(bboxes[select_idx]); mask_merged[select_idx] = true; FaceRect select_bbox = bboxes[select_idx].bbox; float area1 = static_cast<float>((select_bbox.x2-select_bbox.x1+1) * (select_bbox.y2-select_bbox.y1+1)); float x1 = static_cast<float>(select_bbox.x1); float y1 = static_cast<float>(select_bbox.y1); float x2 = static_cast<float>(select_bbox.x2); float y2 = static_cast<float>(select_bbox.y2); select_idx++; for (int32_t i = select_idx; i < num_bbox; i++) { if (mask_merged[i]) continue; FaceRect& bbox_i = bboxes[i].bbox; float x = std::max<float>(x1, static_cast<float>(bbox_i.x1)); float y = std::max<float>(y1, static_cast<float>(bbox_i.y1)); float w = std::min<float>(x2, static_cast<float>(bbox_i.x2)) - x + 1; float h = std::min<float>(y2, static_cast<float>(bbox_i.y2)) - y + 1; if (w <= 0 || h <= 0) continue; float area2 = static_cast<float>((bbox_i.x2-bbox_i.x1+1) * (bbox_i.y2-bbox_i.y1+1)); float area_intersect = w * h; switch (nmstype) { case UNION: if (static_cast<float>(area_intersect) / (area1 + area2 - area_intersect) > thresh) mask_merged[i] = true; break; case MINIMUM: if (static_cast<float>(area_intersect) / std::min(area1 , area2) > thresh) mask_merged[i] = true; break; default: break; } } } return bboxes_nms; } float OneOne(const std::vector<float>& fea1, const std::vector<float>& fea2, bool l2norm=true) { float dis = 0; if (fea1.empty()) { dis += -1; } if (fea2.empty()) { dis += -2; } if (dis) { return dis; } cv::Mat feam1(fea1), feam2(fea2); if (l2norm) { float norm1 = cv::norm(feam1); float norm2 = cv::norm(feam2); feam1 /= norm1; feam2 /= norm2; } dis = cv::norm(feam1, feam2); return dis; } template <typename T> cv::Mat Pointer2Mat(T* ptr, int height, int width, int type=CV_8UC3) { cv::Mat img(height, width, type, ptr); return img; } void drawFaceInfo(cv::Mat& img, const FaceInfo& faceInfo, bool drawPTs=true) { float x1 = faceInfo.bbox.x1; float y1 = faceInfo.bbox.y1; float x2 = faceInfo.bbox.x2; float y2 = faceInfo.bbox.y2; cv::rectangle(img, cv::Rect(x1, y1, x2-x1, y2-x1), cv::Scalar(0, 0, 255), 2); if (drawPTs) { for (int i = 0; i < 5; ++i) { cv::circle(img, cv::Point(faceInfo.facePts.x[i], faceInfo.facePts.y[i]), 2, cv::Scalar(0, 255, 0), -1); } } } void drawFaceInfo(cv::Mat& img, const std::vector<FaceInfo>& faceInfos, bool drawPTs=true) { for (int i = 0; i < faceInfos.size(); ++i) { drawFaceInfo(img, faceInfos[i], drawPTs); } } #endif // _FACEUTIL_HPP_
[ "mincore@163.com" ]
mincore@163.com
93ff4381a0b1ea7fc9667b88480fd3ee71d61e5b
966818603978f073d4f4ed85709ec1ad0c794be4
/INSIGHT_20191106/example/functional_test/protobuf/MDSubscribe.pb.cc
53029d841049cd67ae01a6fcb969aea4407fd416
[]
no_license
lastvangogh/YANGZE
c337743e29dafadbfb1ed532f6c9ce35ce7f24df
870eb6066b360036a49ebe40bd9435cdd31ff5ac
refs/heads/master
2020-09-01T13:43:02.027589
2019-11-06T08:40:09
2019-11-06T08:40:09
218,970,441
0
0
null
null
null
null
UTF-8
C++
false
true
116,953
cc
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: MDSubscribe.proto #define INTERNAL_SUPPRESS_PROTOBUF_FIELD_DEPRECATION #include "MDSubscribe.pb.h" #include <algorithm> #include <google/protobuf/stubs/common.h> #include <google/protobuf/stubs/port.h> #include <google/protobuf/stubs/once.h> #include <google/protobuf/io/coded_stream.h> #include <google/protobuf/wire_format_lite_inl.h> #include <google/protobuf/descriptor.h> #include <google/protobuf/generated_message_reflection.h> #include <google/protobuf/reflection_ops.h> #include <google/protobuf/wire_format.h> // @@protoc_insertion_point(includes) namespace com { namespace htsc { namespace mdc { namespace insight { namespace model { namespace { const ::google::protobuf::Descriptor* MDSubscribeRequest_descriptor_ = NULL; const ::google::protobuf::internal::GeneratedMessageReflection* MDSubscribeRequest_reflection_ = NULL; const ::google::protobuf::Descriptor* SubscribeAll_descriptor_ = NULL; const ::google::protobuf::internal::GeneratedMessageReflection* SubscribeAll_reflection_ = NULL; const ::google::protobuf::Descriptor* SubscribeByID_descriptor_ = NULL; const ::google::protobuf::internal::GeneratedMessageReflection* SubscribeByID_reflection_ = NULL; const ::google::protobuf::Descriptor* SubscribeByIDDetail_descriptor_ = NULL; const ::google::protobuf::internal::GeneratedMessageReflection* SubscribeByIDDetail_reflection_ = NULL; const ::google::protobuf::Descriptor* SubscribeBySourceType_descriptor_ = NULL; const ::google::protobuf::internal::GeneratedMessageReflection* SubscribeBySourceType_reflection_ = NULL; const ::google::protobuf::Descriptor* SubscribeBySourceTypeDetail_descriptor_ = NULL; const ::google::protobuf::internal::GeneratedMessageReflection* SubscribeBySourceTypeDetail_reflection_ = NULL; const ::google::protobuf::Descriptor* MDSubscribeResponse_descriptor_ = NULL; const ::google::protobuf::internal::GeneratedMessageReflection* MDSubscribeResponse_reflection_ = NULL; const ::google::protobuf::EnumDescriptor* ESubscribeActionType_descriptor_ = NULL; } // namespace void protobuf_AssignDesc_MDSubscribe_2eproto() GOOGLE_ATTRIBUTE_COLD; void protobuf_AssignDesc_MDSubscribe_2eproto() { protobuf_AddDesc_MDSubscribe_2eproto(); const ::google::protobuf::FileDescriptor* file = ::google::protobuf::DescriptorPool::generated_pool()->FindFileByName( "MDSubscribe.proto"); GOOGLE_CHECK(file != NULL); MDSubscribeRequest_descriptor_ = file->message_type(0); static const int MDSubscribeRequest_offsets_[4] = { GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(MDSubscribeRequest, subscribeactiontype_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(MDSubscribeRequest, subscribeall_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(MDSubscribeRequest, subscribebysourcetype_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(MDSubscribeRequest, subscribebyid_), }; MDSubscribeRequest_reflection_ = ::google::protobuf::internal::GeneratedMessageReflection::NewGeneratedMessageReflection( MDSubscribeRequest_descriptor_, MDSubscribeRequest::internal_default_instance(), MDSubscribeRequest_offsets_, -1, -1, -1, sizeof(MDSubscribeRequest), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(MDSubscribeRequest, _internal_metadata_)); SubscribeAll_descriptor_ = file->message_type(1); static const int SubscribeAll_offsets_[1] = { GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(SubscribeAll, marketdatatypes_), }; SubscribeAll_reflection_ = ::google::protobuf::internal::GeneratedMessageReflection::NewGeneratedMessageReflection( SubscribeAll_descriptor_, SubscribeAll::internal_default_instance(), SubscribeAll_offsets_, -1, -1, -1, sizeof(SubscribeAll), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(SubscribeAll, _internal_metadata_)); SubscribeByID_descriptor_ = file->message_type(2); static const int SubscribeByID_offsets_[2] = { GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(SubscribeByID, subscribebyiddetails_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(SubscribeByID, globalmarketdatatypes_), }; SubscribeByID_reflection_ = ::google::protobuf::internal::GeneratedMessageReflection::NewGeneratedMessageReflection( SubscribeByID_descriptor_, SubscribeByID::internal_default_instance(), SubscribeByID_offsets_, -1, -1, -1, sizeof(SubscribeByID), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(SubscribeByID, _internal_metadata_)); SubscribeByIDDetail_descriptor_ = file->message_type(3); static const int SubscribeByIDDetail_offsets_[2] = { GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(SubscribeByIDDetail, htscsecurityid_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(SubscribeByIDDetail, marketdatatypes_), }; SubscribeByIDDetail_reflection_ = ::google::protobuf::internal::GeneratedMessageReflection::NewGeneratedMessageReflection( SubscribeByIDDetail_descriptor_, SubscribeByIDDetail::internal_default_instance(), SubscribeByIDDetail_offsets_, -1, -1, -1, sizeof(SubscribeByIDDetail), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(SubscribeByIDDetail, _internal_metadata_)); SubscribeBySourceType_descriptor_ = file->message_type(4); static const int SubscribeBySourceType_offsets_[1] = { GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(SubscribeBySourceType, subscribebysourcetypedetail_), }; SubscribeBySourceType_reflection_ = ::google::protobuf::internal::GeneratedMessageReflection::NewGeneratedMessageReflection( SubscribeBySourceType_descriptor_, SubscribeBySourceType::internal_default_instance(), SubscribeBySourceType_offsets_, -1, -1, -1, sizeof(SubscribeBySourceType), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(SubscribeBySourceType, _internal_metadata_)); SubscribeBySourceTypeDetail_descriptor_ = file->message_type(5); static const int SubscribeBySourceTypeDetail_offsets_[2] = { GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(SubscribeBySourceTypeDetail, securitysourcetypes_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(SubscribeBySourceTypeDetail, marketdatatypes_), }; SubscribeBySourceTypeDetail_reflection_ = ::google::protobuf::internal::GeneratedMessageReflection::NewGeneratedMessageReflection( SubscribeBySourceTypeDetail_descriptor_, SubscribeBySourceTypeDetail::internal_default_instance(), SubscribeBySourceTypeDetail_offsets_, -1, -1, -1, sizeof(SubscribeBySourceTypeDetail), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(SubscribeBySourceTypeDetail, _internal_metadata_)); MDSubscribeResponse_descriptor_ = file->message_type(6); static const int MDSubscribeResponse_offsets_[2] = { GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(MDSubscribeResponse, issuccess_), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(MDSubscribeResponse, errorcontext_), }; MDSubscribeResponse_reflection_ = ::google::protobuf::internal::GeneratedMessageReflection::NewGeneratedMessageReflection( MDSubscribeResponse_descriptor_, MDSubscribeResponse::internal_default_instance(), MDSubscribeResponse_offsets_, -1, -1, -1, sizeof(MDSubscribeResponse), GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(MDSubscribeResponse, _internal_metadata_)); ESubscribeActionType_descriptor_ = file->enum_type(0); } namespace { GOOGLE_PROTOBUF_DECLARE_ONCE(protobuf_AssignDescriptors_once_); void protobuf_AssignDescriptorsOnce() { ::google::protobuf::GoogleOnceInit(&protobuf_AssignDescriptors_once_, &protobuf_AssignDesc_MDSubscribe_2eproto); } void protobuf_RegisterTypes(const ::std::string&) GOOGLE_ATTRIBUTE_COLD; void protobuf_RegisterTypes(const ::std::string&) { protobuf_AssignDescriptorsOnce(); ::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage( MDSubscribeRequest_descriptor_, MDSubscribeRequest::internal_default_instance()); ::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage( SubscribeAll_descriptor_, SubscribeAll::internal_default_instance()); ::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage( SubscribeByID_descriptor_, SubscribeByID::internal_default_instance()); ::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage( SubscribeByIDDetail_descriptor_, SubscribeByIDDetail::internal_default_instance()); ::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage( SubscribeBySourceType_descriptor_, SubscribeBySourceType::internal_default_instance()); ::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage( SubscribeBySourceTypeDetail_descriptor_, SubscribeBySourceTypeDetail::internal_default_instance()); ::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage( MDSubscribeResponse_descriptor_, MDSubscribeResponse::internal_default_instance()); } } // namespace void protobuf_ShutdownFile_MDSubscribe_2eproto() { MDSubscribeRequest_default_instance_.Shutdown(); delete MDSubscribeRequest_reflection_; SubscribeAll_default_instance_.Shutdown(); delete SubscribeAll_reflection_; SubscribeByID_default_instance_.Shutdown(); delete SubscribeByID_reflection_; SubscribeByIDDetail_default_instance_.Shutdown(); delete SubscribeByIDDetail_reflection_; SubscribeBySourceType_default_instance_.Shutdown(); delete SubscribeBySourceType_reflection_; SubscribeBySourceTypeDetail_default_instance_.Shutdown(); delete SubscribeBySourceTypeDetail_reflection_; MDSubscribeResponse_default_instance_.Shutdown(); delete MDSubscribeResponse_reflection_; } void protobuf_InitDefaults_MDSubscribe_2eproto_impl() { GOOGLE_PROTOBUF_VERIFY_VERSION; ::com::htsc::mdc::insight::model::protobuf_InitDefaults_SecuritySourceType_2eproto(); ::com::htsc::mdc::insight::model::protobuf_InitDefaults_EMarketDataType_2eproto(); ::com::htsc::mdc::insight::model::protobuf_InitDefaults_InsightErrorContext_2eproto(); MDSubscribeRequest_default_instance_.DefaultConstruct(); SubscribeAll_default_instance_.DefaultConstruct(); SubscribeByID_default_instance_.DefaultConstruct(); ::google::protobuf::internal::GetEmptyString(); SubscribeByIDDetail_default_instance_.DefaultConstruct(); SubscribeBySourceType_default_instance_.DefaultConstruct(); SubscribeBySourceTypeDetail_default_instance_.DefaultConstruct(); MDSubscribeResponse_default_instance_.DefaultConstruct(); MDSubscribeRequest_default_instance_.get_mutable()->InitAsDefaultInstance(); SubscribeAll_default_instance_.get_mutable()->InitAsDefaultInstance(); SubscribeByID_default_instance_.get_mutable()->InitAsDefaultInstance(); SubscribeByIDDetail_default_instance_.get_mutable()->InitAsDefaultInstance(); SubscribeBySourceType_default_instance_.get_mutable()->InitAsDefaultInstance(); SubscribeBySourceTypeDetail_default_instance_.get_mutable()->InitAsDefaultInstance(); MDSubscribeResponse_default_instance_.get_mutable()->InitAsDefaultInstance(); } GOOGLE_PROTOBUF_DECLARE_ONCE(protobuf_InitDefaults_MDSubscribe_2eproto_once_); void protobuf_InitDefaults_MDSubscribe_2eproto() { ::google::protobuf::GoogleOnceInit(&protobuf_InitDefaults_MDSubscribe_2eproto_once_, &protobuf_InitDefaults_MDSubscribe_2eproto_impl); } void protobuf_AddDesc_MDSubscribe_2eproto_impl() { GOOGLE_PROTOBUF_VERIFY_VERSION; protobuf_InitDefaults_MDSubscribe_2eproto(); ::google::protobuf::DescriptorPool::InternalAddGeneratedFile( "\n\021MDSubscribe.proto\022\032com.htsc.mdc.insigh" "t.model\032\030SecuritySourceType.proto\032\025EMark" "etDataType.proto\032\031InsightErrorContext.pr" "oto\"\267\002\n\022MDSubscribeRequest\022M\n\023subscribeA" "ctionType\030\001 \001(\01620.com.htsc.mdc.insight.m" "odel.ESubscribeActionType\022>\n\014subscribeAl" "l\030\002 \001(\0132(.com.htsc.mdc.insight.model.Sub" "scribeAll\022P\n\025subscribeBySourceType\030\003 \001(\013" "21.com.htsc.mdc.insight.model.SubscribeB" "ySourceType\022@\n\rsubscribeByID\030\004 \001(\0132).com" ".htsc.mdc.insight.model.SubscribeByID\"T\n" "\014SubscribeAll\022D\n\017marketDataTypes\030\001 \003(\0162+" ".com.htsc.mdc.insight.model.EMarketDataT" "ype\"\252\001\n\rSubscribeByID\022M\n\024subscribeByIDDe" "tails\030\001 \003(\0132/.com.htsc.mdc.insight.model" ".SubscribeByIDDetail\022J\n\025globalMarketData" "Types\030\002 \003(\0162+.com.htsc.mdc.insight.model" ".EMarketDataType\"s\n\023SubscribeByIDDetail\022" "\026\n\016htscSecurityID\030\001 \001(\t\022D\n\017marketDataTyp" "es\030\002 \003(\0162+.com.htsc.mdc.insight.model.EM" "arketDataType\"u\n\025SubscribeBySourceType\022\\" "\n\033subscribeBySourceTypeDetail\030\001 \003(\01327.co" "m.htsc.mdc.insight.model.SubscribeBySour" "ceTypeDetail\"\260\001\n\033SubscribeBySourceTypeDe" "tail\022K\n\023securitySourceTypes\030\001 \001(\0132..com." "htsc.mdc.insight.model.SecuritySourceTyp" "e\022D\n\017marketDataTypes\030\002 \003(\0162+.com.htsc.md" "c.insight.model.EMarketDataType\"o\n\023MDSub" "scribeResponse\022\021\n\tisSuccess\030\001 \001(\010\022E\n\014err" "orContext\030\002 \001(\0132/.com.htsc.mdc.insight.m" "odel.InsightErrorContext*G\n\024ESubscribeAc" "tionType\022\014\n\010COVERAGE\020\000\022\007\n\003ADD\020\001\022\014\n\010DECRE" "ASE\020\002\022\n\n\006CANCEL\020\003B4\n\032com.htsc.mdc.insigh" "t.modelB\021MDSubscribeProtosH\001\240\001\001b\006proto3", 1359); ::google::protobuf::MessageFactory::InternalRegisterGeneratedFile( "MDSubscribe.proto", &protobuf_RegisterTypes); ::com::htsc::mdc::insight::model::protobuf_AddDesc_SecuritySourceType_2eproto(); ::com::htsc::mdc::insight::model::protobuf_AddDesc_EMarketDataType_2eproto(); ::com::htsc::mdc::insight::model::protobuf_AddDesc_InsightErrorContext_2eproto(); ::google::protobuf::internal::OnShutdown(&protobuf_ShutdownFile_MDSubscribe_2eproto); } GOOGLE_PROTOBUF_DECLARE_ONCE(protobuf_AddDesc_MDSubscribe_2eproto_once_); void protobuf_AddDesc_MDSubscribe_2eproto() { ::google::protobuf::GoogleOnceInit(&protobuf_AddDesc_MDSubscribe_2eproto_once_, &protobuf_AddDesc_MDSubscribe_2eproto_impl); } // Force AddDescriptors() to be called at static initialization time. struct StaticDescriptorInitializer_MDSubscribe_2eproto { StaticDescriptorInitializer_MDSubscribe_2eproto() { protobuf_AddDesc_MDSubscribe_2eproto(); } } static_descriptor_initializer_MDSubscribe_2eproto_; const ::google::protobuf::EnumDescriptor* ESubscribeActionType_descriptor() { protobuf_AssignDescriptorsOnce(); return ESubscribeActionType_descriptor_; } bool ESubscribeActionType_IsValid(int value) { switch (value) { case 0: case 1: case 2: case 3: return true; default: return false; } } namespace { static void MergeFromFail(int line) GOOGLE_ATTRIBUTE_COLD GOOGLE_ATTRIBUTE_NORETURN; static void MergeFromFail(int line) { ::google::protobuf::internal::MergeFromFail(__FILE__, line); } } // namespace // =================================================================== #if !defined(_MSC_VER) || _MSC_VER >= 1900 const int MDSubscribeRequest::kSubscribeActionTypeFieldNumber; const int MDSubscribeRequest::kSubscribeAllFieldNumber; const int MDSubscribeRequest::kSubscribeBySourceTypeFieldNumber; const int MDSubscribeRequest::kSubscribeByIDFieldNumber; #endif // !defined(_MSC_VER) || _MSC_VER >= 1900 MDSubscribeRequest::MDSubscribeRequest() : ::google::protobuf::Message(), _internal_metadata_(NULL) { if (this != internal_default_instance()) protobuf_InitDefaults_MDSubscribe_2eproto(); SharedCtor(); // @@protoc_insertion_point(constructor:com.htsc.mdc.insight.model.MDSubscribeRequest) } void MDSubscribeRequest::InitAsDefaultInstance() { subscribeall_ = const_cast< ::com::htsc::mdc::insight::model::SubscribeAll*>( ::com::htsc::mdc::insight::model::SubscribeAll::internal_default_instance()); subscribebysourcetype_ = const_cast< ::com::htsc::mdc::insight::model::SubscribeBySourceType*>( ::com::htsc::mdc::insight::model::SubscribeBySourceType::internal_default_instance()); subscribebyid_ = const_cast< ::com::htsc::mdc::insight::model::SubscribeByID*>( ::com::htsc::mdc::insight::model::SubscribeByID::internal_default_instance()); } MDSubscribeRequest::MDSubscribeRequest(const MDSubscribeRequest& from) : ::google::protobuf::Message(), _internal_metadata_(NULL) { SharedCtor(); UnsafeMergeFrom(from); // @@protoc_insertion_point(copy_constructor:com.htsc.mdc.insight.model.MDSubscribeRequest) } void MDSubscribeRequest::SharedCtor() { subscribeall_ = NULL; subscribebysourcetype_ = NULL; subscribebyid_ = NULL; subscribeactiontype_ = 0; _cached_size_ = 0; } MDSubscribeRequest::~MDSubscribeRequest() { // @@protoc_insertion_point(destructor:com.htsc.mdc.insight.model.MDSubscribeRequest) SharedDtor(); } void MDSubscribeRequest::SharedDtor() { if (this != &MDSubscribeRequest_default_instance_.get()) { delete subscribeall_; delete subscribebysourcetype_; delete subscribebyid_; } } void MDSubscribeRequest::SetCachedSize(int size) const { GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _cached_size_ = size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); } const ::google::protobuf::Descriptor* MDSubscribeRequest::descriptor() { protobuf_AssignDescriptorsOnce(); return MDSubscribeRequest_descriptor_; } const MDSubscribeRequest& MDSubscribeRequest::default_instance() { protobuf_InitDefaults_MDSubscribe_2eproto(); return *internal_default_instance(); } ::google::protobuf::internal::ExplicitlyConstructed<MDSubscribeRequest> MDSubscribeRequest_default_instance_; MDSubscribeRequest* MDSubscribeRequest::New(::google::protobuf::Arena* arena) const { MDSubscribeRequest* n = new MDSubscribeRequest; if (arena != NULL) { arena->Own(n); } return n; } void MDSubscribeRequest::Clear() { // @@protoc_insertion_point(message_clear_start:com.htsc.mdc.insight.model.MDSubscribeRequest) subscribeactiontype_ = 0; if (GetArenaNoVirtual() == NULL && subscribeall_ != NULL) delete subscribeall_; subscribeall_ = NULL; if (GetArenaNoVirtual() == NULL && subscribebysourcetype_ != NULL) delete subscribebysourcetype_; subscribebysourcetype_ = NULL; if (GetArenaNoVirtual() == NULL && subscribebyid_ != NULL) delete subscribebyid_; subscribebyid_ = NULL; } bool MDSubscribeRequest::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { #define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:com.htsc.mdc.insight.model.MDSubscribeRequest) for (;;) { ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoff(127); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { // optional .com.htsc.mdc.insight.model.ESubscribeActionType subscribeActionType = 1; case 1: { if (tag == 8) { int value; DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< int, ::google::protobuf::internal::WireFormatLite::TYPE_ENUM>( input, &value))); set_subscribeactiontype(static_cast< ::com::htsc::mdc::insight::model::ESubscribeActionType >(value)); } else { goto handle_unusual; } if (input->ExpectTag(18)) goto parse_subscribeAll; break; } // optional .com.htsc.mdc.insight.model.SubscribeAll subscribeAll = 2; case 2: { if (tag == 18) { parse_subscribeAll: DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual( input, mutable_subscribeall())); } else { goto handle_unusual; } if (input->ExpectTag(26)) goto parse_subscribeBySourceType; break; } // optional .com.htsc.mdc.insight.model.SubscribeBySourceType subscribeBySourceType = 3; case 3: { if (tag == 26) { parse_subscribeBySourceType: DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual( input, mutable_subscribebysourcetype())); } else { goto handle_unusual; } if (input->ExpectTag(34)) goto parse_subscribeByID; break; } // optional .com.htsc.mdc.insight.model.SubscribeByID subscribeByID = 4; case 4: { if (tag == 34) { parse_subscribeByID: DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual( input, mutable_subscribebyid())); } else { goto handle_unusual; } if (input->ExpectAtEnd()) goto success; break; } default: { handle_unusual: if (tag == 0 || ::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) { goto success; } DO_(::google::protobuf::internal::WireFormatLite::SkipField(input, tag)); break; } } } success: // @@protoc_insertion_point(parse_success:com.htsc.mdc.insight.model.MDSubscribeRequest) return true; failure: // @@protoc_insertion_point(parse_failure:com.htsc.mdc.insight.model.MDSubscribeRequest) return false; #undef DO_ } void MDSubscribeRequest::SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:com.htsc.mdc.insight.model.MDSubscribeRequest) // optional .com.htsc.mdc.insight.model.ESubscribeActionType subscribeActionType = 1; if (this->subscribeactiontype() != 0) { ::google::protobuf::internal::WireFormatLite::WriteEnum( 1, this->subscribeactiontype(), output); } // optional .com.htsc.mdc.insight.model.SubscribeAll subscribeAll = 2; if (this->has_subscribeall()) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 2, *this->subscribeall_, output); } // optional .com.htsc.mdc.insight.model.SubscribeBySourceType subscribeBySourceType = 3; if (this->has_subscribebysourcetype()) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 3, *this->subscribebysourcetype_, output); } // optional .com.htsc.mdc.insight.model.SubscribeByID subscribeByID = 4; if (this->has_subscribebyid()) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 4, *this->subscribebyid_, output); } // @@protoc_insertion_point(serialize_end:com.htsc.mdc.insight.model.MDSubscribeRequest) } ::google::protobuf::uint8* MDSubscribeRequest::InternalSerializeWithCachedSizesToArray( bool deterministic, ::google::protobuf::uint8* target) const { (void)deterministic; // Unused // @@protoc_insertion_point(serialize_to_array_start:com.htsc.mdc.insight.model.MDSubscribeRequest) // optional .com.htsc.mdc.insight.model.ESubscribeActionType subscribeActionType = 1; if (this->subscribeactiontype() != 0) { target = ::google::protobuf::internal::WireFormatLite::WriteEnumToArray( 1, this->subscribeactiontype(), target); } // optional .com.htsc.mdc.insight.model.SubscribeAll subscribeAll = 2; if (this->has_subscribeall()) { target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageNoVirtualToArray( 2, *this->subscribeall_, false, target); } // optional .com.htsc.mdc.insight.model.SubscribeBySourceType subscribeBySourceType = 3; if (this->has_subscribebysourcetype()) { target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageNoVirtualToArray( 3, *this->subscribebysourcetype_, false, target); } // optional .com.htsc.mdc.insight.model.SubscribeByID subscribeByID = 4; if (this->has_subscribebyid()) { target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageNoVirtualToArray( 4, *this->subscribebyid_, false, target); } // @@protoc_insertion_point(serialize_to_array_end:com.htsc.mdc.insight.model.MDSubscribeRequest) return target; } size_t MDSubscribeRequest::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:com.htsc.mdc.insight.model.MDSubscribeRequest) size_t total_size = 0; // optional .com.htsc.mdc.insight.model.ESubscribeActionType subscribeActionType = 1; if (this->subscribeactiontype() != 0) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::EnumSize(this->subscribeactiontype()); } // optional .com.htsc.mdc.insight.model.SubscribeAll subscribeAll = 2; if (this->has_subscribeall()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual( *this->subscribeall_); } // optional .com.htsc.mdc.insight.model.SubscribeBySourceType subscribeBySourceType = 3; if (this->has_subscribebysourcetype()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual( *this->subscribebysourcetype_); } // optional .com.htsc.mdc.insight.model.SubscribeByID subscribeByID = 4; if (this->has_subscribebyid()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual( *this->subscribebyid_); } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _cached_size_ = cached_size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); return total_size; } void MDSubscribeRequest::MergeFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:com.htsc.mdc.insight.model.MDSubscribeRequest) if (GOOGLE_PREDICT_FALSE(&from == this)) MergeFromFail(__LINE__); const MDSubscribeRequest* source = ::google::protobuf::internal::DynamicCastToGenerated<const MDSubscribeRequest>( &from); if (source == NULL) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:com.htsc.mdc.insight.model.MDSubscribeRequest) ::google::protobuf::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:com.htsc.mdc.insight.model.MDSubscribeRequest) UnsafeMergeFrom(*source); } } void MDSubscribeRequest::MergeFrom(const MDSubscribeRequest& from) { // @@protoc_insertion_point(class_specific_merge_from_start:com.htsc.mdc.insight.model.MDSubscribeRequest) if (GOOGLE_PREDICT_TRUE(&from != this)) { UnsafeMergeFrom(from); } else { MergeFromFail(__LINE__); } } void MDSubscribeRequest::UnsafeMergeFrom(const MDSubscribeRequest& from) { GOOGLE_DCHECK(&from != this); if (from.subscribeactiontype() != 0) { set_subscribeactiontype(from.subscribeactiontype()); } if (from.has_subscribeall()) { mutable_subscribeall()->::com::htsc::mdc::insight::model::SubscribeAll::MergeFrom(from.subscribeall()); } if (from.has_subscribebysourcetype()) { mutable_subscribebysourcetype()->::com::htsc::mdc::insight::model::SubscribeBySourceType::MergeFrom(from.subscribebysourcetype()); } if (from.has_subscribebyid()) { mutable_subscribebyid()->::com::htsc::mdc::insight::model::SubscribeByID::MergeFrom(from.subscribebyid()); } } void MDSubscribeRequest::CopyFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:com.htsc.mdc.insight.model.MDSubscribeRequest) if (&from == this) return; Clear(); MergeFrom(from); } void MDSubscribeRequest::CopyFrom(const MDSubscribeRequest& from) { // @@protoc_insertion_point(class_specific_copy_from_start:com.htsc.mdc.insight.model.MDSubscribeRequest) if (&from == this) return; Clear(); UnsafeMergeFrom(from); } bool MDSubscribeRequest::IsInitialized() const { return true; } void MDSubscribeRequest::Swap(MDSubscribeRequest* other) { if (other == this) return; InternalSwap(other); } void MDSubscribeRequest::InternalSwap(MDSubscribeRequest* other) { std::swap(subscribeactiontype_, other->subscribeactiontype_); std::swap(subscribeall_, other->subscribeall_); std::swap(subscribebysourcetype_, other->subscribebysourcetype_); std::swap(subscribebyid_, other->subscribebyid_); _internal_metadata_.Swap(&other->_internal_metadata_); std::swap(_cached_size_, other->_cached_size_); } ::google::protobuf::Metadata MDSubscribeRequest::GetMetadata() const { protobuf_AssignDescriptorsOnce(); ::google::protobuf::Metadata metadata; metadata.descriptor = MDSubscribeRequest_descriptor_; metadata.reflection = MDSubscribeRequest_reflection_; return metadata; } #if PROTOBUF_INLINE_NOT_IN_HEADERS // MDSubscribeRequest // optional .com.htsc.mdc.insight.model.ESubscribeActionType subscribeActionType = 1; void MDSubscribeRequest::clear_subscribeactiontype() { subscribeactiontype_ = 0; } ::com::htsc::mdc::insight::model::ESubscribeActionType MDSubscribeRequest::subscribeactiontype() const { // @@protoc_insertion_point(field_get:com.htsc.mdc.insight.model.MDSubscribeRequest.subscribeActionType) return static_cast< ::com::htsc::mdc::insight::model::ESubscribeActionType >(subscribeactiontype_); } void MDSubscribeRequest::set_subscribeactiontype(::com::htsc::mdc::insight::model::ESubscribeActionType value) { subscribeactiontype_ = value; // @@protoc_insertion_point(field_set:com.htsc.mdc.insight.model.MDSubscribeRequest.subscribeActionType) } // optional .com.htsc.mdc.insight.model.SubscribeAll subscribeAll = 2; bool MDSubscribeRequest::has_subscribeall() const { return this != internal_default_instance() && subscribeall_ != NULL; } void MDSubscribeRequest::clear_subscribeall() { if (GetArenaNoVirtual() == NULL && subscribeall_ != NULL) delete subscribeall_; subscribeall_ = NULL; } const ::com::htsc::mdc::insight::model::SubscribeAll& MDSubscribeRequest::subscribeall() const { // @@protoc_insertion_point(field_get:com.htsc.mdc.insight.model.MDSubscribeRequest.subscribeAll) return subscribeall_ != NULL ? *subscribeall_ : *::com::htsc::mdc::insight::model::SubscribeAll::internal_default_instance(); } ::com::htsc::mdc::insight::model::SubscribeAll* MDSubscribeRequest::mutable_subscribeall() { if (subscribeall_ == NULL) { subscribeall_ = new ::com::htsc::mdc::insight::model::SubscribeAll; } // @@protoc_insertion_point(field_mutable:com.htsc.mdc.insight.model.MDSubscribeRequest.subscribeAll) return subscribeall_; } ::com::htsc::mdc::insight::model::SubscribeAll* MDSubscribeRequest::release_subscribeall() { // @@protoc_insertion_point(field_release:com.htsc.mdc.insight.model.MDSubscribeRequest.subscribeAll) ::com::htsc::mdc::insight::model::SubscribeAll* temp = subscribeall_; subscribeall_ = NULL; return temp; } void MDSubscribeRequest::set_allocated_subscribeall(::com::htsc::mdc::insight::model::SubscribeAll* subscribeall) { delete subscribeall_; subscribeall_ = subscribeall; if (subscribeall) { } else { } // @@protoc_insertion_point(field_set_allocated:com.htsc.mdc.insight.model.MDSubscribeRequest.subscribeAll) } // optional .com.htsc.mdc.insight.model.SubscribeBySourceType subscribeBySourceType = 3; bool MDSubscribeRequest::has_subscribebysourcetype() const { return this != internal_default_instance() && subscribebysourcetype_ != NULL; } void MDSubscribeRequest::clear_subscribebysourcetype() { if (GetArenaNoVirtual() == NULL && subscribebysourcetype_ != NULL) delete subscribebysourcetype_; subscribebysourcetype_ = NULL; } const ::com::htsc::mdc::insight::model::SubscribeBySourceType& MDSubscribeRequest::subscribebysourcetype() const { // @@protoc_insertion_point(field_get:com.htsc.mdc.insight.model.MDSubscribeRequest.subscribeBySourceType) return subscribebysourcetype_ != NULL ? *subscribebysourcetype_ : *::com::htsc::mdc::insight::model::SubscribeBySourceType::internal_default_instance(); } ::com::htsc::mdc::insight::model::SubscribeBySourceType* MDSubscribeRequest::mutable_subscribebysourcetype() { if (subscribebysourcetype_ == NULL) { subscribebysourcetype_ = new ::com::htsc::mdc::insight::model::SubscribeBySourceType; } // @@protoc_insertion_point(field_mutable:com.htsc.mdc.insight.model.MDSubscribeRequest.subscribeBySourceType) return subscribebysourcetype_; } ::com::htsc::mdc::insight::model::SubscribeBySourceType* MDSubscribeRequest::release_subscribebysourcetype() { // @@protoc_insertion_point(field_release:com.htsc.mdc.insight.model.MDSubscribeRequest.subscribeBySourceType) ::com::htsc::mdc::insight::model::SubscribeBySourceType* temp = subscribebysourcetype_; subscribebysourcetype_ = NULL; return temp; } void MDSubscribeRequest::set_allocated_subscribebysourcetype(::com::htsc::mdc::insight::model::SubscribeBySourceType* subscribebysourcetype) { delete subscribebysourcetype_; subscribebysourcetype_ = subscribebysourcetype; if (subscribebysourcetype) { } else { } // @@protoc_insertion_point(field_set_allocated:com.htsc.mdc.insight.model.MDSubscribeRequest.subscribeBySourceType) } // optional .com.htsc.mdc.insight.model.SubscribeByID subscribeByID = 4; bool MDSubscribeRequest::has_subscribebyid() const { return this != internal_default_instance() && subscribebyid_ != NULL; } void MDSubscribeRequest::clear_subscribebyid() { if (GetArenaNoVirtual() == NULL && subscribebyid_ != NULL) delete subscribebyid_; subscribebyid_ = NULL; } const ::com::htsc::mdc::insight::model::SubscribeByID& MDSubscribeRequest::subscribebyid() const { // @@protoc_insertion_point(field_get:com.htsc.mdc.insight.model.MDSubscribeRequest.subscribeByID) return subscribebyid_ != NULL ? *subscribebyid_ : *::com::htsc::mdc::insight::model::SubscribeByID::internal_default_instance(); } ::com::htsc::mdc::insight::model::SubscribeByID* MDSubscribeRequest::mutable_subscribebyid() { if (subscribebyid_ == NULL) { subscribebyid_ = new ::com::htsc::mdc::insight::model::SubscribeByID; } // @@protoc_insertion_point(field_mutable:com.htsc.mdc.insight.model.MDSubscribeRequest.subscribeByID) return subscribebyid_; } ::com::htsc::mdc::insight::model::SubscribeByID* MDSubscribeRequest::release_subscribebyid() { // @@protoc_insertion_point(field_release:com.htsc.mdc.insight.model.MDSubscribeRequest.subscribeByID) ::com::htsc::mdc::insight::model::SubscribeByID* temp = subscribebyid_; subscribebyid_ = NULL; return temp; } void MDSubscribeRequest::set_allocated_subscribebyid(::com::htsc::mdc::insight::model::SubscribeByID* subscribebyid) { delete subscribebyid_; subscribebyid_ = subscribebyid; if (subscribebyid) { } else { } // @@protoc_insertion_point(field_set_allocated:com.htsc.mdc.insight.model.MDSubscribeRequest.subscribeByID) } inline const MDSubscribeRequest* MDSubscribeRequest::internal_default_instance() { return &MDSubscribeRequest_default_instance_.get(); } #endif // PROTOBUF_INLINE_NOT_IN_HEADERS // =================================================================== #if !defined(_MSC_VER) || _MSC_VER >= 1900 const int SubscribeAll::kMarketDataTypesFieldNumber; #endif // !defined(_MSC_VER) || _MSC_VER >= 1900 SubscribeAll::SubscribeAll() : ::google::protobuf::Message(), _internal_metadata_(NULL) { if (this != internal_default_instance()) protobuf_InitDefaults_MDSubscribe_2eproto(); SharedCtor(); // @@protoc_insertion_point(constructor:com.htsc.mdc.insight.model.SubscribeAll) } void SubscribeAll::InitAsDefaultInstance() { } SubscribeAll::SubscribeAll(const SubscribeAll& from) : ::google::protobuf::Message(), _internal_metadata_(NULL) { SharedCtor(); UnsafeMergeFrom(from); // @@protoc_insertion_point(copy_constructor:com.htsc.mdc.insight.model.SubscribeAll) } void SubscribeAll::SharedCtor() { _cached_size_ = 0; } SubscribeAll::~SubscribeAll() { // @@protoc_insertion_point(destructor:com.htsc.mdc.insight.model.SubscribeAll) SharedDtor(); } void SubscribeAll::SharedDtor() { } void SubscribeAll::SetCachedSize(int size) const { GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _cached_size_ = size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); } const ::google::protobuf::Descriptor* SubscribeAll::descriptor() { protobuf_AssignDescriptorsOnce(); return SubscribeAll_descriptor_; } const SubscribeAll& SubscribeAll::default_instance() { protobuf_InitDefaults_MDSubscribe_2eproto(); return *internal_default_instance(); } ::google::protobuf::internal::ExplicitlyConstructed<SubscribeAll> SubscribeAll_default_instance_; SubscribeAll* SubscribeAll::New(::google::protobuf::Arena* arena) const { SubscribeAll* n = new SubscribeAll; if (arena != NULL) { arena->Own(n); } return n; } void SubscribeAll::Clear() { // @@protoc_insertion_point(message_clear_start:com.htsc.mdc.insight.model.SubscribeAll) marketdatatypes_.Clear(); } bool SubscribeAll::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { #define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:com.htsc.mdc.insight.model.SubscribeAll) for (;;) { ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoff(127); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { // repeated .com.htsc.mdc.insight.model.EMarketDataType marketDataTypes = 1; case 1: { if (tag == 10) { ::google::protobuf::uint32 length; DO_(input->ReadVarint32(&length)); ::google::protobuf::io::CodedInputStream::Limit limit = input->PushLimit(length); while (input->BytesUntilLimit() > 0) { int value; DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< int, ::google::protobuf::internal::WireFormatLite::TYPE_ENUM>( input, &value))); add_marketdatatypes(static_cast< ::com::htsc::mdc::insight::model::EMarketDataType >(value)); } input->PopLimit(limit); } else if (tag == 8) { int value; DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< int, ::google::protobuf::internal::WireFormatLite::TYPE_ENUM>( input, &value))); add_marketdatatypes(static_cast< ::com::htsc::mdc::insight::model::EMarketDataType >(value)); } else { goto handle_unusual; } if (input->ExpectAtEnd()) goto success; break; } default: { handle_unusual: if (tag == 0 || ::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) { goto success; } DO_(::google::protobuf::internal::WireFormatLite::SkipField(input, tag)); break; } } } success: // @@protoc_insertion_point(parse_success:com.htsc.mdc.insight.model.SubscribeAll) return true; failure: // @@protoc_insertion_point(parse_failure:com.htsc.mdc.insight.model.SubscribeAll) return false; #undef DO_ } void SubscribeAll::SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:com.htsc.mdc.insight.model.SubscribeAll) // repeated .com.htsc.mdc.insight.model.EMarketDataType marketDataTypes = 1; if (this->marketdatatypes_size() > 0) { ::google::protobuf::internal::WireFormatLite::WriteTag( 1, ::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED, output); output->WriteVarint32(_marketdatatypes_cached_byte_size_); } for (int i = 0; i < this->marketdatatypes_size(); i++) { ::google::protobuf::internal::WireFormatLite::WriteEnumNoTag( this->marketdatatypes(i), output); } // @@protoc_insertion_point(serialize_end:com.htsc.mdc.insight.model.SubscribeAll) } ::google::protobuf::uint8* SubscribeAll::InternalSerializeWithCachedSizesToArray( bool deterministic, ::google::protobuf::uint8* target) const { (void)deterministic; // Unused // @@protoc_insertion_point(serialize_to_array_start:com.htsc.mdc.insight.model.SubscribeAll) // repeated .com.htsc.mdc.insight.model.EMarketDataType marketDataTypes = 1; if (this->marketdatatypes_size() > 0) { target = ::google::protobuf::internal::WireFormatLite::WriteTagToArray( 1, ::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED, target); target = ::google::protobuf::io::CodedOutputStream::WriteVarint32ToArray( _marketdatatypes_cached_byte_size_, target); } for (int i = 0; i < this->marketdatatypes_size(); i++) { target = ::google::protobuf::internal::WireFormatLite::WriteEnumNoTagToArray( this->marketdatatypes(i), target); } // @@protoc_insertion_point(serialize_to_array_end:com.htsc.mdc.insight.model.SubscribeAll) return target; } size_t SubscribeAll::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:com.htsc.mdc.insight.model.SubscribeAll) size_t total_size = 0; // repeated .com.htsc.mdc.insight.model.EMarketDataType marketDataTypes = 1; { size_t data_size = 0; unsigned int count = this->marketdatatypes_size();for (unsigned int i = 0; i < count; i++) { data_size += ::google::protobuf::internal::WireFormatLite::EnumSize( this->marketdatatypes(i)); } if (data_size > 0) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::Int32Size(data_size); } int cached_size = ::google::protobuf::internal::ToCachedSize(data_size); GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _marketdatatypes_cached_byte_size_ = cached_size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); total_size += data_size; } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _cached_size_ = cached_size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); return total_size; } void SubscribeAll::MergeFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:com.htsc.mdc.insight.model.SubscribeAll) if (GOOGLE_PREDICT_FALSE(&from == this)) MergeFromFail(__LINE__); const SubscribeAll* source = ::google::protobuf::internal::DynamicCastToGenerated<const SubscribeAll>( &from); if (source == NULL) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:com.htsc.mdc.insight.model.SubscribeAll) ::google::protobuf::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:com.htsc.mdc.insight.model.SubscribeAll) UnsafeMergeFrom(*source); } } void SubscribeAll::MergeFrom(const SubscribeAll& from) { // @@protoc_insertion_point(class_specific_merge_from_start:com.htsc.mdc.insight.model.SubscribeAll) if (GOOGLE_PREDICT_TRUE(&from != this)) { UnsafeMergeFrom(from); } else { MergeFromFail(__LINE__); } } void SubscribeAll::UnsafeMergeFrom(const SubscribeAll& from) { GOOGLE_DCHECK(&from != this); marketdatatypes_.UnsafeMergeFrom(from.marketdatatypes_); } void SubscribeAll::CopyFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:com.htsc.mdc.insight.model.SubscribeAll) if (&from == this) return; Clear(); MergeFrom(from); } void SubscribeAll::CopyFrom(const SubscribeAll& from) { // @@protoc_insertion_point(class_specific_copy_from_start:com.htsc.mdc.insight.model.SubscribeAll) if (&from == this) return; Clear(); UnsafeMergeFrom(from); } bool SubscribeAll::IsInitialized() const { return true; } void SubscribeAll::Swap(SubscribeAll* other) { if (other == this) return; InternalSwap(other); } void SubscribeAll::InternalSwap(SubscribeAll* other) { marketdatatypes_.UnsafeArenaSwap(&other->marketdatatypes_); _internal_metadata_.Swap(&other->_internal_metadata_); std::swap(_cached_size_, other->_cached_size_); } ::google::protobuf::Metadata SubscribeAll::GetMetadata() const { protobuf_AssignDescriptorsOnce(); ::google::protobuf::Metadata metadata; metadata.descriptor = SubscribeAll_descriptor_; metadata.reflection = SubscribeAll_reflection_; return metadata; } #if PROTOBUF_INLINE_NOT_IN_HEADERS // SubscribeAll // repeated .com.htsc.mdc.insight.model.EMarketDataType marketDataTypes = 1; int SubscribeAll::marketdatatypes_size() const { return marketdatatypes_.size(); } void SubscribeAll::clear_marketdatatypes() { marketdatatypes_.Clear(); } ::com::htsc::mdc::insight::model::EMarketDataType SubscribeAll::marketdatatypes(int index) const { // @@protoc_insertion_point(field_get:com.htsc.mdc.insight.model.SubscribeAll.marketDataTypes) return static_cast< ::com::htsc::mdc::insight::model::EMarketDataType >(marketdatatypes_.Get(index)); } void SubscribeAll::set_marketdatatypes(int index, ::com::htsc::mdc::insight::model::EMarketDataType value) { marketdatatypes_.Set(index, value); // @@protoc_insertion_point(field_set:com.htsc.mdc.insight.model.SubscribeAll.marketDataTypes) } void SubscribeAll::add_marketdatatypes(::com::htsc::mdc::insight::model::EMarketDataType value) { marketdatatypes_.Add(value); // @@protoc_insertion_point(field_add:com.htsc.mdc.insight.model.SubscribeAll.marketDataTypes) } const ::google::protobuf::RepeatedField<int>& SubscribeAll::marketdatatypes() const { // @@protoc_insertion_point(field_list:com.htsc.mdc.insight.model.SubscribeAll.marketDataTypes) return marketdatatypes_; } ::google::protobuf::RepeatedField<int>* SubscribeAll::mutable_marketdatatypes() { // @@protoc_insertion_point(field_mutable_list:com.htsc.mdc.insight.model.SubscribeAll.marketDataTypes) return &marketdatatypes_; } inline const SubscribeAll* SubscribeAll::internal_default_instance() { return &SubscribeAll_default_instance_.get(); } #endif // PROTOBUF_INLINE_NOT_IN_HEADERS // =================================================================== #if !defined(_MSC_VER) || _MSC_VER >= 1900 const int SubscribeByID::kSubscribeByIDDetailsFieldNumber; const int SubscribeByID::kGlobalMarketDataTypesFieldNumber; #endif // !defined(_MSC_VER) || _MSC_VER >= 1900 SubscribeByID::SubscribeByID() : ::google::protobuf::Message(), _internal_metadata_(NULL) { if (this != internal_default_instance()) protobuf_InitDefaults_MDSubscribe_2eproto(); SharedCtor(); // @@protoc_insertion_point(constructor:com.htsc.mdc.insight.model.SubscribeByID) } void SubscribeByID::InitAsDefaultInstance() { } SubscribeByID::SubscribeByID(const SubscribeByID& from) : ::google::protobuf::Message(), _internal_metadata_(NULL) { SharedCtor(); UnsafeMergeFrom(from); // @@protoc_insertion_point(copy_constructor:com.htsc.mdc.insight.model.SubscribeByID) } void SubscribeByID::SharedCtor() { _cached_size_ = 0; } SubscribeByID::~SubscribeByID() { // @@protoc_insertion_point(destructor:com.htsc.mdc.insight.model.SubscribeByID) SharedDtor(); } void SubscribeByID::SharedDtor() { } void SubscribeByID::SetCachedSize(int size) const { GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _cached_size_ = size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); } const ::google::protobuf::Descriptor* SubscribeByID::descriptor() { protobuf_AssignDescriptorsOnce(); return SubscribeByID_descriptor_; } const SubscribeByID& SubscribeByID::default_instance() { protobuf_InitDefaults_MDSubscribe_2eproto(); return *internal_default_instance(); } ::google::protobuf::internal::ExplicitlyConstructed<SubscribeByID> SubscribeByID_default_instance_; SubscribeByID* SubscribeByID::New(::google::protobuf::Arena* arena) const { SubscribeByID* n = new SubscribeByID; if (arena != NULL) { arena->Own(n); } return n; } void SubscribeByID::Clear() { // @@protoc_insertion_point(message_clear_start:com.htsc.mdc.insight.model.SubscribeByID) subscribebyiddetails_.Clear(); globalmarketdatatypes_.Clear(); } bool SubscribeByID::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { #define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:com.htsc.mdc.insight.model.SubscribeByID) for (;;) { ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoff(127); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { // repeated .com.htsc.mdc.insight.model.SubscribeByIDDetail subscribeByIDDetails = 1; case 1: { if (tag == 10) { DO_(input->IncrementRecursionDepth()); parse_loop_subscribeByIDDetails: DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtualNoRecursionDepth( input, add_subscribebyiddetails())); } else { goto handle_unusual; } if (input->ExpectTag(10)) goto parse_loop_subscribeByIDDetails; input->UnsafeDecrementRecursionDepth(); if (input->ExpectTag(18)) goto parse_globalMarketDataTypes; break; } // repeated .com.htsc.mdc.insight.model.EMarketDataType globalMarketDataTypes = 2; case 2: { if (tag == 18) { parse_globalMarketDataTypes: ::google::protobuf::uint32 length; DO_(input->ReadVarint32(&length)); ::google::protobuf::io::CodedInputStream::Limit limit = input->PushLimit(length); while (input->BytesUntilLimit() > 0) { int value; DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< int, ::google::protobuf::internal::WireFormatLite::TYPE_ENUM>( input, &value))); add_globalmarketdatatypes(static_cast< ::com::htsc::mdc::insight::model::EMarketDataType >(value)); } input->PopLimit(limit); } else if (tag == 16) { int value; DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< int, ::google::protobuf::internal::WireFormatLite::TYPE_ENUM>( input, &value))); add_globalmarketdatatypes(static_cast< ::com::htsc::mdc::insight::model::EMarketDataType >(value)); } else { goto handle_unusual; } if (input->ExpectAtEnd()) goto success; break; } default: { handle_unusual: if (tag == 0 || ::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) { goto success; } DO_(::google::protobuf::internal::WireFormatLite::SkipField(input, tag)); break; } } } success: // @@protoc_insertion_point(parse_success:com.htsc.mdc.insight.model.SubscribeByID) return true; failure: // @@protoc_insertion_point(parse_failure:com.htsc.mdc.insight.model.SubscribeByID) return false; #undef DO_ } void SubscribeByID::SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:com.htsc.mdc.insight.model.SubscribeByID) // repeated .com.htsc.mdc.insight.model.SubscribeByIDDetail subscribeByIDDetails = 1; for (unsigned int i = 0, n = this->subscribebyiddetails_size(); i < n; i++) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 1, this->subscribebyiddetails(i), output); } // repeated .com.htsc.mdc.insight.model.EMarketDataType globalMarketDataTypes = 2; if (this->globalmarketdatatypes_size() > 0) { ::google::protobuf::internal::WireFormatLite::WriteTag( 2, ::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED, output); output->WriteVarint32(_globalmarketdatatypes_cached_byte_size_); } for (int i = 0; i < this->globalmarketdatatypes_size(); i++) { ::google::protobuf::internal::WireFormatLite::WriteEnumNoTag( this->globalmarketdatatypes(i), output); } // @@protoc_insertion_point(serialize_end:com.htsc.mdc.insight.model.SubscribeByID) } ::google::protobuf::uint8* SubscribeByID::InternalSerializeWithCachedSizesToArray( bool deterministic, ::google::protobuf::uint8* target) const { (void)deterministic; // Unused // @@protoc_insertion_point(serialize_to_array_start:com.htsc.mdc.insight.model.SubscribeByID) // repeated .com.htsc.mdc.insight.model.SubscribeByIDDetail subscribeByIDDetails = 1; for (unsigned int i = 0, n = this->subscribebyiddetails_size(); i < n; i++) { target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageNoVirtualToArray( 1, this->subscribebyiddetails(i), false, target); } // repeated .com.htsc.mdc.insight.model.EMarketDataType globalMarketDataTypes = 2; if (this->globalmarketdatatypes_size() > 0) { target = ::google::protobuf::internal::WireFormatLite::WriteTagToArray( 2, ::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED, target); target = ::google::protobuf::io::CodedOutputStream::WriteVarint32ToArray( _globalmarketdatatypes_cached_byte_size_, target); } for (int i = 0; i < this->globalmarketdatatypes_size(); i++) { target = ::google::protobuf::internal::WireFormatLite::WriteEnumNoTagToArray( this->globalmarketdatatypes(i), target); } // @@protoc_insertion_point(serialize_to_array_end:com.htsc.mdc.insight.model.SubscribeByID) return target; } size_t SubscribeByID::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:com.htsc.mdc.insight.model.SubscribeByID) size_t total_size = 0; // repeated .com.htsc.mdc.insight.model.SubscribeByIDDetail subscribeByIDDetails = 1; { unsigned int count = this->subscribebyiddetails_size(); total_size += 1UL * count; for (unsigned int i = 0; i < count; i++) { total_size += ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual( this->subscribebyiddetails(i)); } } // repeated .com.htsc.mdc.insight.model.EMarketDataType globalMarketDataTypes = 2; { size_t data_size = 0; unsigned int count = this->globalmarketdatatypes_size();for (unsigned int i = 0; i < count; i++) { data_size += ::google::protobuf::internal::WireFormatLite::EnumSize( this->globalmarketdatatypes(i)); } if (data_size > 0) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::Int32Size(data_size); } int cached_size = ::google::protobuf::internal::ToCachedSize(data_size); GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _globalmarketdatatypes_cached_byte_size_ = cached_size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); total_size += data_size; } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _cached_size_ = cached_size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); return total_size; } void SubscribeByID::MergeFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:com.htsc.mdc.insight.model.SubscribeByID) if (GOOGLE_PREDICT_FALSE(&from == this)) MergeFromFail(__LINE__); const SubscribeByID* source = ::google::protobuf::internal::DynamicCastToGenerated<const SubscribeByID>( &from); if (source == NULL) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:com.htsc.mdc.insight.model.SubscribeByID) ::google::protobuf::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:com.htsc.mdc.insight.model.SubscribeByID) UnsafeMergeFrom(*source); } } void SubscribeByID::MergeFrom(const SubscribeByID& from) { // @@protoc_insertion_point(class_specific_merge_from_start:com.htsc.mdc.insight.model.SubscribeByID) if (GOOGLE_PREDICT_TRUE(&from != this)) { UnsafeMergeFrom(from); } else { MergeFromFail(__LINE__); } } void SubscribeByID::UnsafeMergeFrom(const SubscribeByID& from) { GOOGLE_DCHECK(&from != this); subscribebyiddetails_.MergeFrom(from.subscribebyiddetails_); globalmarketdatatypes_.UnsafeMergeFrom(from.globalmarketdatatypes_); } void SubscribeByID::CopyFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:com.htsc.mdc.insight.model.SubscribeByID) if (&from == this) return; Clear(); MergeFrom(from); } void SubscribeByID::CopyFrom(const SubscribeByID& from) { // @@protoc_insertion_point(class_specific_copy_from_start:com.htsc.mdc.insight.model.SubscribeByID) if (&from == this) return; Clear(); UnsafeMergeFrom(from); } bool SubscribeByID::IsInitialized() const { return true; } void SubscribeByID::Swap(SubscribeByID* other) { if (other == this) return; InternalSwap(other); } void SubscribeByID::InternalSwap(SubscribeByID* other) { subscribebyiddetails_.UnsafeArenaSwap(&other->subscribebyiddetails_); globalmarketdatatypes_.UnsafeArenaSwap(&other->globalmarketdatatypes_); _internal_metadata_.Swap(&other->_internal_metadata_); std::swap(_cached_size_, other->_cached_size_); } ::google::protobuf::Metadata SubscribeByID::GetMetadata() const { protobuf_AssignDescriptorsOnce(); ::google::protobuf::Metadata metadata; metadata.descriptor = SubscribeByID_descriptor_; metadata.reflection = SubscribeByID_reflection_; return metadata; } #if PROTOBUF_INLINE_NOT_IN_HEADERS // SubscribeByID // repeated .com.htsc.mdc.insight.model.SubscribeByIDDetail subscribeByIDDetails = 1; int SubscribeByID::subscribebyiddetails_size() const { return subscribebyiddetails_.size(); } void SubscribeByID::clear_subscribebyiddetails() { subscribebyiddetails_.Clear(); } const ::com::htsc::mdc::insight::model::SubscribeByIDDetail& SubscribeByID::subscribebyiddetails(int index) const { // @@protoc_insertion_point(field_get:com.htsc.mdc.insight.model.SubscribeByID.subscribeByIDDetails) return subscribebyiddetails_.Get(index); } ::com::htsc::mdc::insight::model::SubscribeByIDDetail* SubscribeByID::mutable_subscribebyiddetails(int index) { // @@protoc_insertion_point(field_mutable:com.htsc.mdc.insight.model.SubscribeByID.subscribeByIDDetails) return subscribebyiddetails_.Mutable(index); } ::com::htsc::mdc::insight::model::SubscribeByIDDetail* SubscribeByID::add_subscribebyiddetails() { // @@protoc_insertion_point(field_add:com.htsc.mdc.insight.model.SubscribeByID.subscribeByIDDetails) return subscribebyiddetails_.Add(); } ::google::protobuf::RepeatedPtrField< ::com::htsc::mdc::insight::model::SubscribeByIDDetail >* SubscribeByID::mutable_subscribebyiddetails() { // @@protoc_insertion_point(field_mutable_list:com.htsc.mdc.insight.model.SubscribeByID.subscribeByIDDetails) return &subscribebyiddetails_; } const ::google::protobuf::RepeatedPtrField< ::com::htsc::mdc::insight::model::SubscribeByIDDetail >& SubscribeByID::subscribebyiddetails() const { // @@protoc_insertion_point(field_list:com.htsc.mdc.insight.model.SubscribeByID.subscribeByIDDetails) return subscribebyiddetails_; } // repeated .com.htsc.mdc.insight.model.EMarketDataType globalMarketDataTypes = 2; int SubscribeByID::globalmarketdatatypes_size() const { return globalmarketdatatypes_.size(); } void SubscribeByID::clear_globalmarketdatatypes() { globalmarketdatatypes_.Clear(); } ::com::htsc::mdc::insight::model::EMarketDataType SubscribeByID::globalmarketdatatypes(int index) const { // @@protoc_insertion_point(field_get:com.htsc.mdc.insight.model.SubscribeByID.globalMarketDataTypes) return static_cast< ::com::htsc::mdc::insight::model::EMarketDataType >(globalmarketdatatypes_.Get(index)); } void SubscribeByID::set_globalmarketdatatypes(int index, ::com::htsc::mdc::insight::model::EMarketDataType value) { globalmarketdatatypes_.Set(index, value); // @@protoc_insertion_point(field_set:com.htsc.mdc.insight.model.SubscribeByID.globalMarketDataTypes) } void SubscribeByID::add_globalmarketdatatypes(::com::htsc::mdc::insight::model::EMarketDataType value) { globalmarketdatatypes_.Add(value); // @@protoc_insertion_point(field_add:com.htsc.mdc.insight.model.SubscribeByID.globalMarketDataTypes) } const ::google::protobuf::RepeatedField<int>& SubscribeByID::globalmarketdatatypes() const { // @@protoc_insertion_point(field_list:com.htsc.mdc.insight.model.SubscribeByID.globalMarketDataTypes) return globalmarketdatatypes_; } ::google::protobuf::RepeatedField<int>* SubscribeByID::mutable_globalmarketdatatypes() { // @@protoc_insertion_point(field_mutable_list:com.htsc.mdc.insight.model.SubscribeByID.globalMarketDataTypes) return &globalmarketdatatypes_; } inline const SubscribeByID* SubscribeByID::internal_default_instance() { return &SubscribeByID_default_instance_.get(); } #endif // PROTOBUF_INLINE_NOT_IN_HEADERS // =================================================================== #if !defined(_MSC_VER) || _MSC_VER >= 1900 const int SubscribeByIDDetail::kHtscSecurityIDFieldNumber; const int SubscribeByIDDetail::kMarketDataTypesFieldNumber; #endif // !defined(_MSC_VER) || _MSC_VER >= 1900 SubscribeByIDDetail::SubscribeByIDDetail() : ::google::protobuf::Message(), _internal_metadata_(NULL) { if (this != internal_default_instance()) protobuf_InitDefaults_MDSubscribe_2eproto(); SharedCtor(); // @@protoc_insertion_point(constructor:com.htsc.mdc.insight.model.SubscribeByIDDetail) } void SubscribeByIDDetail::InitAsDefaultInstance() { } SubscribeByIDDetail::SubscribeByIDDetail(const SubscribeByIDDetail& from) : ::google::protobuf::Message(), _internal_metadata_(NULL) { SharedCtor(); UnsafeMergeFrom(from); // @@protoc_insertion_point(copy_constructor:com.htsc.mdc.insight.model.SubscribeByIDDetail) } void SubscribeByIDDetail::SharedCtor() { htscsecurityid_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); _cached_size_ = 0; } SubscribeByIDDetail::~SubscribeByIDDetail() { // @@protoc_insertion_point(destructor:com.htsc.mdc.insight.model.SubscribeByIDDetail) SharedDtor(); } void SubscribeByIDDetail::SharedDtor() { htscsecurityid_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } void SubscribeByIDDetail::SetCachedSize(int size) const { GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _cached_size_ = size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); } const ::google::protobuf::Descriptor* SubscribeByIDDetail::descriptor() { protobuf_AssignDescriptorsOnce(); return SubscribeByIDDetail_descriptor_; } const SubscribeByIDDetail& SubscribeByIDDetail::default_instance() { protobuf_InitDefaults_MDSubscribe_2eproto(); return *internal_default_instance(); } ::google::protobuf::internal::ExplicitlyConstructed<SubscribeByIDDetail> SubscribeByIDDetail_default_instance_; SubscribeByIDDetail* SubscribeByIDDetail::New(::google::protobuf::Arena* arena) const { SubscribeByIDDetail* n = new SubscribeByIDDetail; if (arena != NULL) { arena->Own(n); } return n; } void SubscribeByIDDetail::Clear() { // @@protoc_insertion_point(message_clear_start:com.htsc.mdc.insight.model.SubscribeByIDDetail) htscsecurityid_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); marketdatatypes_.Clear(); } bool SubscribeByIDDetail::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { #define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:com.htsc.mdc.insight.model.SubscribeByIDDetail) for (;;) { ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoff(127); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { // optional string htscSecurityID = 1; case 1: { if (tag == 10) { DO_(::google::protobuf::internal::WireFormatLite::ReadString( input, this->mutable_htscsecurityid())); DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->htscsecurityid().data(), this->htscsecurityid().length(), ::google::protobuf::internal::WireFormatLite::PARSE, "com.htsc.mdc.insight.model.SubscribeByIDDetail.htscSecurityID")); } else { goto handle_unusual; } if (input->ExpectTag(18)) goto parse_marketDataTypes; break; } // repeated .com.htsc.mdc.insight.model.EMarketDataType marketDataTypes = 2; case 2: { if (tag == 18) { parse_marketDataTypes: ::google::protobuf::uint32 length; DO_(input->ReadVarint32(&length)); ::google::protobuf::io::CodedInputStream::Limit limit = input->PushLimit(length); while (input->BytesUntilLimit() > 0) { int value; DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< int, ::google::protobuf::internal::WireFormatLite::TYPE_ENUM>( input, &value))); add_marketdatatypes(static_cast< ::com::htsc::mdc::insight::model::EMarketDataType >(value)); } input->PopLimit(limit); } else if (tag == 16) { int value; DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< int, ::google::protobuf::internal::WireFormatLite::TYPE_ENUM>( input, &value))); add_marketdatatypes(static_cast< ::com::htsc::mdc::insight::model::EMarketDataType >(value)); } else { goto handle_unusual; } if (input->ExpectAtEnd()) goto success; break; } default: { handle_unusual: if (tag == 0 || ::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) { goto success; } DO_(::google::protobuf::internal::WireFormatLite::SkipField(input, tag)); break; } } } success: // @@protoc_insertion_point(parse_success:com.htsc.mdc.insight.model.SubscribeByIDDetail) return true; failure: // @@protoc_insertion_point(parse_failure:com.htsc.mdc.insight.model.SubscribeByIDDetail) return false; #undef DO_ } void SubscribeByIDDetail::SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:com.htsc.mdc.insight.model.SubscribeByIDDetail) // optional string htscSecurityID = 1; if (this->htscsecurityid().size() > 0) { ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->htscsecurityid().data(), this->htscsecurityid().length(), ::google::protobuf::internal::WireFormatLite::SERIALIZE, "com.htsc.mdc.insight.model.SubscribeByIDDetail.htscSecurityID"); ::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased( 1, this->htscsecurityid(), output); } // repeated .com.htsc.mdc.insight.model.EMarketDataType marketDataTypes = 2; if (this->marketdatatypes_size() > 0) { ::google::protobuf::internal::WireFormatLite::WriteTag( 2, ::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED, output); output->WriteVarint32(_marketdatatypes_cached_byte_size_); } for (int i = 0; i < this->marketdatatypes_size(); i++) { ::google::protobuf::internal::WireFormatLite::WriteEnumNoTag( this->marketdatatypes(i), output); } // @@protoc_insertion_point(serialize_end:com.htsc.mdc.insight.model.SubscribeByIDDetail) } ::google::protobuf::uint8* SubscribeByIDDetail::InternalSerializeWithCachedSizesToArray( bool deterministic, ::google::protobuf::uint8* target) const { (void)deterministic; // Unused // @@protoc_insertion_point(serialize_to_array_start:com.htsc.mdc.insight.model.SubscribeByIDDetail) // optional string htscSecurityID = 1; if (this->htscsecurityid().size() > 0) { ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->htscsecurityid().data(), this->htscsecurityid().length(), ::google::protobuf::internal::WireFormatLite::SERIALIZE, "com.htsc.mdc.insight.model.SubscribeByIDDetail.htscSecurityID"); target = ::google::protobuf::internal::WireFormatLite::WriteStringToArray( 1, this->htscsecurityid(), target); } // repeated .com.htsc.mdc.insight.model.EMarketDataType marketDataTypes = 2; if (this->marketdatatypes_size() > 0) { target = ::google::protobuf::internal::WireFormatLite::WriteTagToArray( 2, ::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED, target); target = ::google::protobuf::io::CodedOutputStream::WriteVarint32ToArray( _marketdatatypes_cached_byte_size_, target); } for (int i = 0; i < this->marketdatatypes_size(); i++) { target = ::google::protobuf::internal::WireFormatLite::WriteEnumNoTagToArray( this->marketdatatypes(i), target); } // @@protoc_insertion_point(serialize_to_array_end:com.htsc.mdc.insight.model.SubscribeByIDDetail) return target; } size_t SubscribeByIDDetail::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:com.htsc.mdc.insight.model.SubscribeByIDDetail) size_t total_size = 0; // optional string htscSecurityID = 1; if (this->htscsecurityid().size() > 0) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::StringSize( this->htscsecurityid()); } // repeated .com.htsc.mdc.insight.model.EMarketDataType marketDataTypes = 2; { size_t data_size = 0; unsigned int count = this->marketdatatypes_size();for (unsigned int i = 0; i < count; i++) { data_size += ::google::protobuf::internal::WireFormatLite::EnumSize( this->marketdatatypes(i)); } if (data_size > 0) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::Int32Size(data_size); } int cached_size = ::google::protobuf::internal::ToCachedSize(data_size); GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _marketdatatypes_cached_byte_size_ = cached_size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); total_size += data_size; } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _cached_size_ = cached_size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); return total_size; } void SubscribeByIDDetail::MergeFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:com.htsc.mdc.insight.model.SubscribeByIDDetail) if (GOOGLE_PREDICT_FALSE(&from == this)) MergeFromFail(__LINE__); const SubscribeByIDDetail* source = ::google::protobuf::internal::DynamicCastToGenerated<const SubscribeByIDDetail>( &from); if (source == NULL) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:com.htsc.mdc.insight.model.SubscribeByIDDetail) ::google::protobuf::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:com.htsc.mdc.insight.model.SubscribeByIDDetail) UnsafeMergeFrom(*source); } } void SubscribeByIDDetail::MergeFrom(const SubscribeByIDDetail& from) { // @@protoc_insertion_point(class_specific_merge_from_start:com.htsc.mdc.insight.model.SubscribeByIDDetail) if (GOOGLE_PREDICT_TRUE(&from != this)) { UnsafeMergeFrom(from); } else { MergeFromFail(__LINE__); } } void SubscribeByIDDetail::UnsafeMergeFrom(const SubscribeByIDDetail& from) { GOOGLE_DCHECK(&from != this); marketdatatypes_.UnsafeMergeFrom(from.marketdatatypes_); if (from.htscsecurityid().size() > 0) { htscsecurityid_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.htscsecurityid_); } } void SubscribeByIDDetail::CopyFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:com.htsc.mdc.insight.model.SubscribeByIDDetail) if (&from == this) return; Clear(); MergeFrom(from); } void SubscribeByIDDetail::CopyFrom(const SubscribeByIDDetail& from) { // @@protoc_insertion_point(class_specific_copy_from_start:com.htsc.mdc.insight.model.SubscribeByIDDetail) if (&from == this) return; Clear(); UnsafeMergeFrom(from); } bool SubscribeByIDDetail::IsInitialized() const { return true; } void SubscribeByIDDetail::Swap(SubscribeByIDDetail* other) { if (other == this) return; InternalSwap(other); } void SubscribeByIDDetail::InternalSwap(SubscribeByIDDetail* other) { htscsecurityid_.Swap(&other->htscsecurityid_); marketdatatypes_.UnsafeArenaSwap(&other->marketdatatypes_); _internal_metadata_.Swap(&other->_internal_metadata_); std::swap(_cached_size_, other->_cached_size_); } ::google::protobuf::Metadata SubscribeByIDDetail::GetMetadata() const { protobuf_AssignDescriptorsOnce(); ::google::protobuf::Metadata metadata; metadata.descriptor = SubscribeByIDDetail_descriptor_; metadata.reflection = SubscribeByIDDetail_reflection_; return metadata; } #if PROTOBUF_INLINE_NOT_IN_HEADERS // SubscribeByIDDetail // optional string htscSecurityID = 1; void SubscribeByIDDetail::clear_htscsecurityid() { htscsecurityid_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } const ::std::string& SubscribeByIDDetail::htscsecurityid() const { // @@protoc_insertion_point(field_get:com.htsc.mdc.insight.model.SubscribeByIDDetail.htscSecurityID) return htscsecurityid_.GetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } void SubscribeByIDDetail::set_htscsecurityid(const ::std::string& value) { htscsecurityid_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), value); // @@protoc_insertion_point(field_set:com.htsc.mdc.insight.model.SubscribeByIDDetail.htscSecurityID) } void SubscribeByIDDetail::set_htscsecurityid(const char* value) { htscsecurityid_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(value)); // @@protoc_insertion_point(field_set_char:com.htsc.mdc.insight.model.SubscribeByIDDetail.htscSecurityID) } void SubscribeByIDDetail::set_htscsecurityid(const char* value, size_t size) { htscsecurityid_.SetNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), ::std::string(reinterpret_cast<const char*>(value), size)); // @@protoc_insertion_point(field_set_pointer:com.htsc.mdc.insight.model.SubscribeByIDDetail.htscSecurityID) } ::std::string* SubscribeByIDDetail::mutable_htscsecurityid() { // @@protoc_insertion_point(field_mutable:com.htsc.mdc.insight.model.SubscribeByIDDetail.htscSecurityID) return htscsecurityid_.MutableNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } ::std::string* SubscribeByIDDetail::release_htscsecurityid() { // @@protoc_insertion_point(field_release:com.htsc.mdc.insight.model.SubscribeByIDDetail.htscSecurityID) return htscsecurityid_.ReleaseNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } void SubscribeByIDDetail::set_allocated_htscsecurityid(::std::string* htscsecurityid) { if (htscsecurityid != NULL) { } else { } htscsecurityid_.SetAllocatedNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), htscsecurityid); // @@protoc_insertion_point(field_set_allocated:com.htsc.mdc.insight.model.SubscribeByIDDetail.htscSecurityID) } // repeated .com.htsc.mdc.insight.model.EMarketDataType marketDataTypes = 2; int SubscribeByIDDetail::marketdatatypes_size() const { return marketdatatypes_.size(); } void SubscribeByIDDetail::clear_marketdatatypes() { marketdatatypes_.Clear(); } ::com::htsc::mdc::insight::model::EMarketDataType SubscribeByIDDetail::marketdatatypes(int index) const { // @@protoc_insertion_point(field_get:com.htsc.mdc.insight.model.SubscribeByIDDetail.marketDataTypes) return static_cast< ::com::htsc::mdc::insight::model::EMarketDataType >(marketdatatypes_.Get(index)); } void SubscribeByIDDetail::set_marketdatatypes(int index, ::com::htsc::mdc::insight::model::EMarketDataType value) { marketdatatypes_.Set(index, value); // @@protoc_insertion_point(field_set:com.htsc.mdc.insight.model.SubscribeByIDDetail.marketDataTypes) } void SubscribeByIDDetail::add_marketdatatypes(::com::htsc::mdc::insight::model::EMarketDataType value) { marketdatatypes_.Add(value); // @@protoc_insertion_point(field_add:com.htsc.mdc.insight.model.SubscribeByIDDetail.marketDataTypes) } const ::google::protobuf::RepeatedField<int>& SubscribeByIDDetail::marketdatatypes() const { // @@protoc_insertion_point(field_list:com.htsc.mdc.insight.model.SubscribeByIDDetail.marketDataTypes) return marketdatatypes_; } ::google::protobuf::RepeatedField<int>* SubscribeByIDDetail::mutable_marketdatatypes() { // @@protoc_insertion_point(field_mutable_list:com.htsc.mdc.insight.model.SubscribeByIDDetail.marketDataTypes) return &marketdatatypes_; } inline const SubscribeByIDDetail* SubscribeByIDDetail::internal_default_instance() { return &SubscribeByIDDetail_default_instance_.get(); } #endif // PROTOBUF_INLINE_NOT_IN_HEADERS // =================================================================== #if !defined(_MSC_VER) || _MSC_VER >= 1900 const int SubscribeBySourceType::kSubscribeBySourceTypeDetailFieldNumber; #endif // !defined(_MSC_VER) || _MSC_VER >= 1900 SubscribeBySourceType::SubscribeBySourceType() : ::google::protobuf::Message(), _internal_metadata_(NULL) { if (this != internal_default_instance()) protobuf_InitDefaults_MDSubscribe_2eproto(); SharedCtor(); // @@protoc_insertion_point(constructor:com.htsc.mdc.insight.model.SubscribeBySourceType) } void SubscribeBySourceType::InitAsDefaultInstance() { } SubscribeBySourceType::SubscribeBySourceType(const SubscribeBySourceType& from) : ::google::protobuf::Message(), _internal_metadata_(NULL) { SharedCtor(); UnsafeMergeFrom(from); // @@protoc_insertion_point(copy_constructor:com.htsc.mdc.insight.model.SubscribeBySourceType) } void SubscribeBySourceType::SharedCtor() { _cached_size_ = 0; } SubscribeBySourceType::~SubscribeBySourceType() { // @@protoc_insertion_point(destructor:com.htsc.mdc.insight.model.SubscribeBySourceType) SharedDtor(); } void SubscribeBySourceType::SharedDtor() { } void SubscribeBySourceType::SetCachedSize(int size) const { GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _cached_size_ = size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); } const ::google::protobuf::Descriptor* SubscribeBySourceType::descriptor() { protobuf_AssignDescriptorsOnce(); return SubscribeBySourceType_descriptor_; } const SubscribeBySourceType& SubscribeBySourceType::default_instance() { protobuf_InitDefaults_MDSubscribe_2eproto(); return *internal_default_instance(); } ::google::protobuf::internal::ExplicitlyConstructed<SubscribeBySourceType> SubscribeBySourceType_default_instance_; SubscribeBySourceType* SubscribeBySourceType::New(::google::protobuf::Arena* arena) const { SubscribeBySourceType* n = new SubscribeBySourceType; if (arena != NULL) { arena->Own(n); } return n; } void SubscribeBySourceType::Clear() { // @@protoc_insertion_point(message_clear_start:com.htsc.mdc.insight.model.SubscribeBySourceType) subscribebysourcetypedetail_.Clear(); } bool SubscribeBySourceType::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { #define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:com.htsc.mdc.insight.model.SubscribeBySourceType) for (;;) { ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoff(127); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { // repeated .com.htsc.mdc.insight.model.SubscribeBySourceTypeDetail subscribeBySourceTypeDetail = 1; case 1: { if (tag == 10) { DO_(input->IncrementRecursionDepth()); parse_loop_subscribeBySourceTypeDetail: DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtualNoRecursionDepth( input, add_subscribebysourcetypedetail())); } else { goto handle_unusual; } if (input->ExpectTag(10)) goto parse_loop_subscribeBySourceTypeDetail; input->UnsafeDecrementRecursionDepth(); if (input->ExpectAtEnd()) goto success; break; } default: { handle_unusual: if (tag == 0 || ::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) { goto success; } DO_(::google::protobuf::internal::WireFormatLite::SkipField(input, tag)); break; } } } success: // @@protoc_insertion_point(parse_success:com.htsc.mdc.insight.model.SubscribeBySourceType) return true; failure: // @@protoc_insertion_point(parse_failure:com.htsc.mdc.insight.model.SubscribeBySourceType) return false; #undef DO_ } void SubscribeBySourceType::SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:com.htsc.mdc.insight.model.SubscribeBySourceType) // repeated .com.htsc.mdc.insight.model.SubscribeBySourceTypeDetail subscribeBySourceTypeDetail = 1; for (unsigned int i = 0, n = this->subscribebysourcetypedetail_size(); i < n; i++) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 1, this->subscribebysourcetypedetail(i), output); } // @@protoc_insertion_point(serialize_end:com.htsc.mdc.insight.model.SubscribeBySourceType) } ::google::protobuf::uint8* SubscribeBySourceType::InternalSerializeWithCachedSizesToArray( bool deterministic, ::google::protobuf::uint8* target) const { (void)deterministic; // Unused // @@protoc_insertion_point(serialize_to_array_start:com.htsc.mdc.insight.model.SubscribeBySourceType) // repeated .com.htsc.mdc.insight.model.SubscribeBySourceTypeDetail subscribeBySourceTypeDetail = 1; for (unsigned int i = 0, n = this->subscribebysourcetypedetail_size(); i < n; i++) { target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageNoVirtualToArray( 1, this->subscribebysourcetypedetail(i), false, target); } // @@protoc_insertion_point(serialize_to_array_end:com.htsc.mdc.insight.model.SubscribeBySourceType) return target; } size_t SubscribeBySourceType::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:com.htsc.mdc.insight.model.SubscribeBySourceType) size_t total_size = 0; // repeated .com.htsc.mdc.insight.model.SubscribeBySourceTypeDetail subscribeBySourceTypeDetail = 1; { unsigned int count = this->subscribebysourcetypedetail_size(); total_size += 1UL * count; for (unsigned int i = 0; i < count; i++) { total_size += ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual( this->subscribebysourcetypedetail(i)); } } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _cached_size_ = cached_size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); return total_size; } void SubscribeBySourceType::MergeFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:com.htsc.mdc.insight.model.SubscribeBySourceType) if (GOOGLE_PREDICT_FALSE(&from == this)) MergeFromFail(__LINE__); const SubscribeBySourceType* source = ::google::protobuf::internal::DynamicCastToGenerated<const SubscribeBySourceType>( &from); if (source == NULL) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:com.htsc.mdc.insight.model.SubscribeBySourceType) ::google::protobuf::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:com.htsc.mdc.insight.model.SubscribeBySourceType) UnsafeMergeFrom(*source); } } void SubscribeBySourceType::MergeFrom(const SubscribeBySourceType& from) { // @@protoc_insertion_point(class_specific_merge_from_start:com.htsc.mdc.insight.model.SubscribeBySourceType) if (GOOGLE_PREDICT_TRUE(&from != this)) { UnsafeMergeFrom(from); } else { MergeFromFail(__LINE__); } } void SubscribeBySourceType::UnsafeMergeFrom(const SubscribeBySourceType& from) { GOOGLE_DCHECK(&from != this); subscribebysourcetypedetail_.MergeFrom(from.subscribebysourcetypedetail_); } void SubscribeBySourceType::CopyFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:com.htsc.mdc.insight.model.SubscribeBySourceType) if (&from == this) return; Clear(); MergeFrom(from); } void SubscribeBySourceType::CopyFrom(const SubscribeBySourceType& from) { // @@protoc_insertion_point(class_specific_copy_from_start:com.htsc.mdc.insight.model.SubscribeBySourceType) if (&from == this) return; Clear(); UnsafeMergeFrom(from); } bool SubscribeBySourceType::IsInitialized() const { return true; } void SubscribeBySourceType::Swap(SubscribeBySourceType* other) { if (other == this) return; InternalSwap(other); } void SubscribeBySourceType::InternalSwap(SubscribeBySourceType* other) { subscribebysourcetypedetail_.UnsafeArenaSwap(&other->subscribebysourcetypedetail_); _internal_metadata_.Swap(&other->_internal_metadata_); std::swap(_cached_size_, other->_cached_size_); } ::google::protobuf::Metadata SubscribeBySourceType::GetMetadata() const { protobuf_AssignDescriptorsOnce(); ::google::protobuf::Metadata metadata; metadata.descriptor = SubscribeBySourceType_descriptor_; metadata.reflection = SubscribeBySourceType_reflection_; return metadata; } #if PROTOBUF_INLINE_NOT_IN_HEADERS // SubscribeBySourceType // repeated .com.htsc.mdc.insight.model.SubscribeBySourceTypeDetail subscribeBySourceTypeDetail = 1; int SubscribeBySourceType::subscribebysourcetypedetail_size() const { return subscribebysourcetypedetail_.size(); } void SubscribeBySourceType::clear_subscribebysourcetypedetail() { subscribebysourcetypedetail_.Clear(); } const ::com::htsc::mdc::insight::model::SubscribeBySourceTypeDetail& SubscribeBySourceType::subscribebysourcetypedetail(int index) const { // @@protoc_insertion_point(field_get:com.htsc.mdc.insight.model.SubscribeBySourceType.subscribeBySourceTypeDetail) return subscribebysourcetypedetail_.Get(index); } ::com::htsc::mdc::insight::model::SubscribeBySourceTypeDetail* SubscribeBySourceType::mutable_subscribebysourcetypedetail(int index) { // @@protoc_insertion_point(field_mutable:com.htsc.mdc.insight.model.SubscribeBySourceType.subscribeBySourceTypeDetail) return subscribebysourcetypedetail_.Mutable(index); } ::com::htsc::mdc::insight::model::SubscribeBySourceTypeDetail* SubscribeBySourceType::add_subscribebysourcetypedetail() { // @@protoc_insertion_point(field_add:com.htsc.mdc.insight.model.SubscribeBySourceType.subscribeBySourceTypeDetail) return subscribebysourcetypedetail_.Add(); } ::google::protobuf::RepeatedPtrField< ::com::htsc::mdc::insight::model::SubscribeBySourceTypeDetail >* SubscribeBySourceType::mutable_subscribebysourcetypedetail() { // @@protoc_insertion_point(field_mutable_list:com.htsc.mdc.insight.model.SubscribeBySourceType.subscribeBySourceTypeDetail) return &subscribebysourcetypedetail_; } const ::google::protobuf::RepeatedPtrField< ::com::htsc::mdc::insight::model::SubscribeBySourceTypeDetail >& SubscribeBySourceType::subscribebysourcetypedetail() const { // @@protoc_insertion_point(field_list:com.htsc.mdc.insight.model.SubscribeBySourceType.subscribeBySourceTypeDetail) return subscribebysourcetypedetail_; } inline const SubscribeBySourceType* SubscribeBySourceType::internal_default_instance() { return &SubscribeBySourceType_default_instance_.get(); } #endif // PROTOBUF_INLINE_NOT_IN_HEADERS // =================================================================== #if !defined(_MSC_VER) || _MSC_VER >= 1900 const int SubscribeBySourceTypeDetail::kSecuritySourceTypesFieldNumber; const int SubscribeBySourceTypeDetail::kMarketDataTypesFieldNumber; #endif // !defined(_MSC_VER) || _MSC_VER >= 1900 SubscribeBySourceTypeDetail::SubscribeBySourceTypeDetail() : ::google::protobuf::Message(), _internal_metadata_(NULL) { if (this != internal_default_instance()) protobuf_InitDefaults_MDSubscribe_2eproto(); SharedCtor(); // @@protoc_insertion_point(constructor:com.htsc.mdc.insight.model.SubscribeBySourceTypeDetail) } void SubscribeBySourceTypeDetail::InitAsDefaultInstance() { securitysourcetypes_ = const_cast< ::com::htsc::mdc::insight::model::SecuritySourceType*>( ::com::htsc::mdc::insight::model::SecuritySourceType::internal_default_instance()); } SubscribeBySourceTypeDetail::SubscribeBySourceTypeDetail(const SubscribeBySourceTypeDetail& from) : ::google::protobuf::Message(), _internal_metadata_(NULL) { SharedCtor(); UnsafeMergeFrom(from); // @@protoc_insertion_point(copy_constructor:com.htsc.mdc.insight.model.SubscribeBySourceTypeDetail) } void SubscribeBySourceTypeDetail::SharedCtor() { securitysourcetypes_ = NULL; _cached_size_ = 0; } SubscribeBySourceTypeDetail::~SubscribeBySourceTypeDetail() { // @@protoc_insertion_point(destructor:com.htsc.mdc.insight.model.SubscribeBySourceTypeDetail) SharedDtor(); } void SubscribeBySourceTypeDetail::SharedDtor() { if (this != &SubscribeBySourceTypeDetail_default_instance_.get()) { delete securitysourcetypes_; } } void SubscribeBySourceTypeDetail::SetCachedSize(int size) const { GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _cached_size_ = size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); } const ::google::protobuf::Descriptor* SubscribeBySourceTypeDetail::descriptor() { protobuf_AssignDescriptorsOnce(); return SubscribeBySourceTypeDetail_descriptor_; } const SubscribeBySourceTypeDetail& SubscribeBySourceTypeDetail::default_instance() { protobuf_InitDefaults_MDSubscribe_2eproto(); return *internal_default_instance(); } ::google::protobuf::internal::ExplicitlyConstructed<SubscribeBySourceTypeDetail> SubscribeBySourceTypeDetail_default_instance_; SubscribeBySourceTypeDetail* SubscribeBySourceTypeDetail::New(::google::protobuf::Arena* arena) const { SubscribeBySourceTypeDetail* n = new SubscribeBySourceTypeDetail; if (arena != NULL) { arena->Own(n); } return n; } void SubscribeBySourceTypeDetail::Clear() { // @@protoc_insertion_point(message_clear_start:com.htsc.mdc.insight.model.SubscribeBySourceTypeDetail) if (GetArenaNoVirtual() == NULL && securitysourcetypes_ != NULL) delete securitysourcetypes_; securitysourcetypes_ = NULL; marketdatatypes_.Clear(); } bool SubscribeBySourceTypeDetail::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { #define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:com.htsc.mdc.insight.model.SubscribeBySourceTypeDetail) for (;;) { ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoff(127); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { // optional .com.htsc.mdc.insight.model.SecuritySourceType securitySourceTypes = 1; case 1: { if (tag == 10) { DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual( input, mutable_securitysourcetypes())); } else { goto handle_unusual; } if (input->ExpectTag(18)) goto parse_marketDataTypes; break; } // repeated .com.htsc.mdc.insight.model.EMarketDataType marketDataTypes = 2; case 2: { if (tag == 18) { parse_marketDataTypes: ::google::protobuf::uint32 length; DO_(input->ReadVarint32(&length)); ::google::protobuf::io::CodedInputStream::Limit limit = input->PushLimit(length); while (input->BytesUntilLimit() > 0) { int value; DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< int, ::google::protobuf::internal::WireFormatLite::TYPE_ENUM>( input, &value))); add_marketdatatypes(static_cast< ::com::htsc::mdc::insight::model::EMarketDataType >(value)); } input->PopLimit(limit); } else if (tag == 16) { int value; DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< int, ::google::protobuf::internal::WireFormatLite::TYPE_ENUM>( input, &value))); add_marketdatatypes(static_cast< ::com::htsc::mdc::insight::model::EMarketDataType >(value)); } else { goto handle_unusual; } if (input->ExpectAtEnd()) goto success; break; } default: { handle_unusual: if (tag == 0 || ::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) { goto success; } DO_(::google::protobuf::internal::WireFormatLite::SkipField(input, tag)); break; } } } success: // @@protoc_insertion_point(parse_success:com.htsc.mdc.insight.model.SubscribeBySourceTypeDetail) return true; failure: // @@protoc_insertion_point(parse_failure:com.htsc.mdc.insight.model.SubscribeBySourceTypeDetail) return false; #undef DO_ } void SubscribeBySourceTypeDetail::SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:com.htsc.mdc.insight.model.SubscribeBySourceTypeDetail) // optional .com.htsc.mdc.insight.model.SecuritySourceType securitySourceTypes = 1; if (this->has_securitysourcetypes()) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 1, *this->securitysourcetypes_, output); } // repeated .com.htsc.mdc.insight.model.EMarketDataType marketDataTypes = 2; if (this->marketdatatypes_size() > 0) { ::google::protobuf::internal::WireFormatLite::WriteTag( 2, ::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED, output); output->WriteVarint32(_marketdatatypes_cached_byte_size_); } for (int i = 0; i < this->marketdatatypes_size(); i++) { ::google::protobuf::internal::WireFormatLite::WriteEnumNoTag( this->marketdatatypes(i), output); } // @@protoc_insertion_point(serialize_end:com.htsc.mdc.insight.model.SubscribeBySourceTypeDetail) } ::google::protobuf::uint8* SubscribeBySourceTypeDetail::InternalSerializeWithCachedSizesToArray( bool deterministic, ::google::protobuf::uint8* target) const { (void)deterministic; // Unused // @@protoc_insertion_point(serialize_to_array_start:com.htsc.mdc.insight.model.SubscribeBySourceTypeDetail) // optional .com.htsc.mdc.insight.model.SecuritySourceType securitySourceTypes = 1; if (this->has_securitysourcetypes()) { target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageNoVirtualToArray( 1, *this->securitysourcetypes_, false, target); } // repeated .com.htsc.mdc.insight.model.EMarketDataType marketDataTypes = 2; if (this->marketdatatypes_size() > 0) { target = ::google::protobuf::internal::WireFormatLite::WriteTagToArray( 2, ::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED, target); target = ::google::protobuf::io::CodedOutputStream::WriteVarint32ToArray( _marketdatatypes_cached_byte_size_, target); } for (int i = 0; i < this->marketdatatypes_size(); i++) { target = ::google::protobuf::internal::WireFormatLite::WriteEnumNoTagToArray( this->marketdatatypes(i), target); } // @@protoc_insertion_point(serialize_to_array_end:com.htsc.mdc.insight.model.SubscribeBySourceTypeDetail) return target; } size_t SubscribeBySourceTypeDetail::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:com.htsc.mdc.insight.model.SubscribeBySourceTypeDetail) size_t total_size = 0; // optional .com.htsc.mdc.insight.model.SecuritySourceType securitySourceTypes = 1; if (this->has_securitysourcetypes()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual( *this->securitysourcetypes_); } // repeated .com.htsc.mdc.insight.model.EMarketDataType marketDataTypes = 2; { size_t data_size = 0; unsigned int count = this->marketdatatypes_size();for (unsigned int i = 0; i < count; i++) { data_size += ::google::protobuf::internal::WireFormatLite::EnumSize( this->marketdatatypes(i)); } if (data_size > 0) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::Int32Size(data_size); } int cached_size = ::google::protobuf::internal::ToCachedSize(data_size); GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _marketdatatypes_cached_byte_size_ = cached_size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); total_size += data_size; } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _cached_size_ = cached_size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); return total_size; } void SubscribeBySourceTypeDetail::MergeFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:com.htsc.mdc.insight.model.SubscribeBySourceTypeDetail) if (GOOGLE_PREDICT_FALSE(&from == this)) MergeFromFail(__LINE__); const SubscribeBySourceTypeDetail* source = ::google::protobuf::internal::DynamicCastToGenerated<const SubscribeBySourceTypeDetail>( &from); if (source == NULL) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:com.htsc.mdc.insight.model.SubscribeBySourceTypeDetail) ::google::protobuf::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:com.htsc.mdc.insight.model.SubscribeBySourceTypeDetail) UnsafeMergeFrom(*source); } } void SubscribeBySourceTypeDetail::MergeFrom(const SubscribeBySourceTypeDetail& from) { // @@protoc_insertion_point(class_specific_merge_from_start:com.htsc.mdc.insight.model.SubscribeBySourceTypeDetail) if (GOOGLE_PREDICT_TRUE(&from != this)) { UnsafeMergeFrom(from); } else { MergeFromFail(__LINE__); } } void SubscribeBySourceTypeDetail::UnsafeMergeFrom(const SubscribeBySourceTypeDetail& from) { GOOGLE_DCHECK(&from != this); marketdatatypes_.UnsafeMergeFrom(from.marketdatatypes_); if (from.has_securitysourcetypes()) { mutable_securitysourcetypes()->::com::htsc::mdc::insight::model::SecuritySourceType::MergeFrom(from.securitysourcetypes()); } } void SubscribeBySourceTypeDetail::CopyFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:com.htsc.mdc.insight.model.SubscribeBySourceTypeDetail) if (&from == this) return; Clear(); MergeFrom(from); } void SubscribeBySourceTypeDetail::CopyFrom(const SubscribeBySourceTypeDetail& from) { // @@protoc_insertion_point(class_specific_copy_from_start:com.htsc.mdc.insight.model.SubscribeBySourceTypeDetail) if (&from == this) return; Clear(); UnsafeMergeFrom(from); } bool SubscribeBySourceTypeDetail::IsInitialized() const { return true; } void SubscribeBySourceTypeDetail::Swap(SubscribeBySourceTypeDetail* other) { if (other == this) return; InternalSwap(other); } void SubscribeBySourceTypeDetail::InternalSwap(SubscribeBySourceTypeDetail* other) { std::swap(securitysourcetypes_, other->securitysourcetypes_); marketdatatypes_.UnsafeArenaSwap(&other->marketdatatypes_); _internal_metadata_.Swap(&other->_internal_metadata_); std::swap(_cached_size_, other->_cached_size_); } ::google::protobuf::Metadata SubscribeBySourceTypeDetail::GetMetadata() const { protobuf_AssignDescriptorsOnce(); ::google::protobuf::Metadata metadata; metadata.descriptor = SubscribeBySourceTypeDetail_descriptor_; metadata.reflection = SubscribeBySourceTypeDetail_reflection_; return metadata; } #if PROTOBUF_INLINE_NOT_IN_HEADERS // SubscribeBySourceTypeDetail // optional .com.htsc.mdc.insight.model.SecuritySourceType securitySourceTypes = 1; bool SubscribeBySourceTypeDetail::has_securitysourcetypes() const { return this != internal_default_instance() && securitysourcetypes_ != NULL; } void SubscribeBySourceTypeDetail::clear_securitysourcetypes() { if (GetArenaNoVirtual() == NULL && securitysourcetypes_ != NULL) delete securitysourcetypes_; securitysourcetypes_ = NULL; } const ::com::htsc::mdc::insight::model::SecuritySourceType& SubscribeBySourceTypeDetail::securitysourcetypes() const { // @@protoc_insertion_point(field_get:com.htsc.mdc.insight.model.SubscribeBySourceTypeDetail.securitySourceTypes) return securitysourcetypes_ != NULL ? *securitysourcetypes_ : *::com::htsc::mdc::insight::model::SecuritySourceType::internal_default_instance(); } ::com::htsc::mdc::insight::model::SecuritySourceType* SubscribeBySourceTypeDetail::mutable_securitysourcetypes() { if (securitysourcetypes_ == NULL) { securitysourcetypes_ = new ::com::htsc::mdc::insight::model::SecuritySourceType; } // @@protoc_insertion_point(field_mutable:com.htsc.mdc.insight.model.SubscribeBySourceTypeDetail.securitySourceTypes) return securitysourcetypes_; } ::com::htsc::mdc::insight::model::SecuritySourceType* SubscribeBySourceTypeDetail::release_securitysourcetypes() { // @@protoc_insertion_point(field_release:com.htsc.mdc.insight.model.SubscribeBySourceTypeDetail.securitySourceTypes) ::com::htsc::mdc::insight::model::SecuritySourceType* temp = securitysourcetypes_; securitysourcetypes_ = NULL; return temp; } void SubscribeBySourceTypeDetail::set_allocated_securitysourcetypes(::com::htsc::mdc::insight::model::SecuritySourceType* securitysourcetypes) { delete securitysourcetypes_; securitysourcetypes_ = securitysourcetypes; if (securitysourcetypes) { } else { } // @@protoc_insertion_point(field_set_allocated:com.htsc.mdc.insight.model.SubscribeBySourceTypeDetail.securitySourceTypes) } // repeated .com.htsc.mdc.insight.model.EMarketDataType marketDataTypes = 2; int SubscribeBySourceTypeDetail::marketdatatypes_size() const { return marketdatatypes_.size(); } void SubscribeBySourceTypeDetail::clear_marketdatatypes() { marketdatatypes_.Clear(); } ::com::htsc::mdc::insight::model::EMarketDataType SubscribeBySourceTypeDetail::marketdatatypes(int index) const { // @@protoc_insertion_point(field_get:com.htsc.mdc.insight.model.SubscribeBySourceTypeDetail.marketDataTypes) return static_cast< ::com::htsc::mdc::insight::model::EMarketDataType >(marketdatatypes_.Get(index)); } void SubscribeBySourceTypeDetail::set_marketdatatypes(int index, ::com::htsc::mdc::insight::model::EMarketDataType value) { marketdatatypes_.Set(index, value); // @@protoc_insertion_point(field_set:com.htsc.mdc.insight.model.SubscribeBySourceTypeDetail.marketDataTypes) } void SubscribeBySourceTypeDetail::add_marketdatatypes(::com::htsc::mdc::insight::model::EMarketDataType value) { marketdatatypes_.Add(value); // @@protoc_insertion_point(field_add:com.htsc.mdc.insight.model.SubscribeBySourceTypeDetail.marketDataTypes) } const ::google::protobuf::RepeatedField<int>& SubscribeBySourceTypeDetail::marketdatatypes() const { // @@protoc_insertion_point(field_list:com.htsc.mdc.insight.model.SubscribeBySourceTypeDetail.marketDataTypes) return marketdatatypes_; } ::google::protobuf::RepeatedField<int>* SubscribeBySourceTypeDetail::mutable_marketdatatypes() { // @@protoc_insertion_point(field_mutable_list:com.htsc.mdc.insight.model.SubscribeBySourceTypeDetail.marketDataTypes) return &marketdatatypes_; } inline const SubscribeBySourceTypeDetail* SubscribeBySourceTypeDetail::internal_default_instance() { return &SubscribeBySourceTypeDetail_default_instance_.get(); } #endif // PROTOBUF_INLINE_NOT_IN_HEADERS // =================================================================== #if !defined(_MSC_VER) || _MSC_VER >= 1900 const int MDSubscribeResponse::kIsSuccessFieldNumber; const int MDSubscribeResponse::kErrorContextFieldNumber; #endif // !defined(_MSC_VER) || _MSC_VER >= 1900 MDSubscribeResponse::MDSubscribeResponse() : ::google::protobuf::Message(), _internal_metadata_(NULL) { if (this != internal_default_instance()) protobuf_InitDefaults_MDSubscribe_2eproto(); SharedCtor(); // @@protoc_insertion_point(constructor:com.htsc.mdc.insight.model.MDSubscribeResponse) } void MDSubscribeResponse::InitAsDefaultInstance() { errorcontext_ = const_cast< ::com::htsc::mdc::insight::model::InsightErrorContext*>( ::com::htsc::mdc::insight::model::InsightErrorContext::internal_default_instance()); } MDSubscribeResponse::MDSubscribeResponse(const MDSubscribeResponse& from) : ::google::protobuf::Message(), _internal_metadata_(NULL) { SharedCtor(); UnsafeMergeFrom(from); // @@protoc_insertion_point(copy_constructor:com.htsc.mdc.insight.model.MDSubscribeResponse) } void MDSubscribeResponse::SharedCtor() { errorcontext_ = NULL; issuccess_ = false; _cached_size_ = 0; } MDSubscribeResponse::~MDSubscribeResponse() { // @@protoc_insertion_point(destructor:com.htsc.mdc.insight.model.MDSubscribeResponse) SharedDtor(); } void MDSubscribeResponse::SharedDtor() { if (this != &MDSubscribeResponse_default_instance_.get()) { delete errorcontext_; } } void MDSubscribeResponse::SetCachedSize(int size) const { GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _cached_size_ = size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); } const ::google::protobuf::Descriptor* MDSubscribeResponse::descriptor() { protobuf_AssignDescriptorsOnce(); return MDSubscribeResponse_descriptor_; } const MDSubscribeResponse& MDSubscribeResponse::default_instance() { protobuf_InitDefaults_MDSubscribe_2eproto(); return *internal_default_instance(); } ::google::protobuf::internal::ExplicitlyConstructed<MDSubscribeResponse> MDSubscribeResponse_default_instance_; MDSubscribeResponse* MDSubscribeResponse::New(::google::protobuf::Arena* arena) const { MDSubscribeResponse* n = new MDSubscribeResponse; if (arena != NULL) { arena->Own(n); } return n; } void MDSubscribeResponse::Clear() { // @@protoc_insertion_point(message_clear_start:com.htsc.mdc.insight.model.MDSubscribeResponse) issuccess_ = false; if (GetArenaNoVirtual() == NULL && errorcontext_ != NULL) delete errorcontext_; errorcontext_ = NULL; } bool MDSubscribeResponse::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { #define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:com.htsc.mdc.insight.model.MDSubscribeResponse) for (;;) { ::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoff(127); tag = p.first; if (!p.second) goto handle_unusual; switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) { // optional bool isSuccess = 1; case 1: { if (tag == 8) { DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< bool, ::google::protobuf::internal::WireFormatLite::TYPE_BOOL>( input, &issuccess_))); } else { goto handle_unusual; } if (input->ExpectTag(18)) goto parse_errorContext; break; } // optional .com.htsc.mdc.insight.model.InsightErrorContext errorContext = 2; case 2: { if (tag == 18) { parse_errorContext: DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual( input, mutable_errorcontext())); } else { goto handle_unusual; } if (input->ExpectAtEnd()) goto success; break; } default: { handle_unusual: if (tag == 0 || ::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) == ::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) { goto success; } DO_(::google::protobuf::internal::WireFormatLite::SkipField(input, tag)); break; } } } success: // @@protoc_insertion_point(parse_success:com.htsc.mdc.insight.model.MDSubscribeResponse) return true; failure: // @@protoc_insertion_point(parse_failure:com.htsc.mdc.insight.model.MDSubscribeResponse) return false; #undef DO_ } void MDSubscribeResponse::SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:com.htsc.mdc.insight.model.MDSubscribeResponse) // optional bool isSuccess = 1; if (this->issuccess() != 0) { ::google::protobuf::internal::WireFormatLite::WriteBool(1, this->issuccess(), output); } // optional .com.htsc.mdc.insight.model.InsightErrorContext errorContext = 2; if (this->has_errorcontext()) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 2, *this->errorcontext_, output); } // @@protoc_insertion_point(serialize_end:com.htsc.mdc.insight.model.MDSubscribeResponse) } ::google::protobuf::uint8* MDSubscribeResponse::InternalSerializeWithCachedSizesToArray( bool deterministic, ::google::protobuf::uint8* target) const { (void)deterministic; // Unused // @@protoc_insertion_point(serialize_to_array_start:com.htsc.mdc.insight.model.MDSubscribeResponse) // optional bool isSuccess = 1; if (this->issuccess() != 0) { target = ::google::protobuf::internal::WireFormatLite::WriteBoolToArray(1, this->issuccess(), target); } // optional .com.htsc.mdc.insight.model.InsightErrorContext errorContext = 2; if (this->has_errorcontext()) { target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageNoVirtualToArray( 2, *this->errorcontext_, false, target); } // @@protoc_insertion_point(serialize_to_array_end:com.htsc.mdc.insight.model.MDSubscribeResponse) return target; } size_t MDSubscribeResponse::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:com.htsc.mdc.insight.model.MDSubscribeResponse) size_t total_size = 0; // optional bool isSuccess = 1; if (this->issuccess() != 0) { total_size += 1 + 1; } // optional .com.htsc.mdc.insight.model.InsightErrorContext errorContext = 2; if (this->has_errorcontext()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual( *this->errorcontext_); } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN(); _cached_size_ = cached_size; GOOGLE_SAFE_CONCURRENT_WRITES_END(); return total_size; } void MDSubscribeResponse::MergeFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:com.htsc.mdc.insight.model.MDSubscribeResponse) if (GOOGLE_PREDICT_FALSE(&from == this)) MergeFromFail(__LINE__); const MDSubscribeResponse* source = ::google::protobuf::internal::DynamicCastToGenerated<const MDSubscribeResponse>( &from); if (source == NULL) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:com.htsc.mdc.insight.model.MDSubscribeResponse) ::google::protobuf::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:com.htsc.mdc.insight.model.MDSubscribeResponse) UnsafeMergeFrom(*source); } } void MDSubscribeResponse::MergeFrom(const MDSubscribeResponse& from) { // @@protoc_insertion_point(class_specific_merge_from_start:com.htsc.mdc.insight.model.MDSubscribeResponse) if (GOOGLE_PREDICT_TRUE(&from != this)) { UnsafeMergeFrom(from); } else { MergeFromFail(__LINE__); } } void MDSubscribeResponse::UnsafeMergeFrom(const MDSubscribeResponse& from) { GOOGLE_DCHECK(&from != this); if (from.issuccess() != 0) { set_issuccess(from.issuccess()); } if (from.has_errorcontext()) { mutable_errorcontext()->::com::htsc::mdc::insight::model::InsightErrorContext::MergeFrom(from.errorcontext()); } } void MDSubscribeResponse::CopyFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:com.htsc.mdc.insight.model.MDSubscribeResponse) if (&from == this) return; Clear(); MergeFrom(from); } void MDSubscribeResponse::CopyFrom(const MDSubscribeResponse& from) { // @@protoc_insertion_point(class_specific_copy_from_start:com.htsc.mdc.insight.model.MDSubscribeResponse) if (&from == this) return; Clear(); UnsafeMergeFrom(from); } bool MDSubscribeResponse::IsInitialized() const { return true; } void MDSubscribeResponse::Swap(MDSubscribeResponse* other) { if (other == this) return; InternalSwap(other); } void MDSubscribeResponse::InternalSwap(MDSubscribeResponse* other) { std::swap(issuccess_, other->issuccess_); std::swap(errorcontext_, other->errorcontext_); _internal_metadata_.Swap(&other->_internal_metadata_); std::swap(_cached_size_, other->_cached_size_); } ::google::protobuf::Metadata MDSubscribeResponse::GetMetadata() const { protobuf_AssignDescriptorsOnce(); ::google::protobuf::Metadata metadata; metadata.descriptor = MDSubscribeResponse_descriptor_; metadata.reflection = MDSubscribeResponse_reflection_; return metadata; } #if PROTOBUF_INLINE_NOT_IN_HEADERS // MDSubscribeResponse // optional bool isSuccess = 1; void MDSubscribeResponse::clear_issuccess() { issuccess_ = false; } bool MDSubscribeResponse::issuccess() const { // @@protoc_insertion_point(field_get:com.htsc.mdc.insight.model.MDSubscribeResponse.isSuccess) return issuccess_; } void MDSubscribeResponse::set_issuccess(bool value) { issuccess_ = value; // @@protoc_insertion_point(field_set:com.htsc.mdc.insight.model.MDSubscribeResponse.isSuccess) } // optional .com.htsc.mdc.insight.model.InsightErrorContext errorContext = 2; bool MDSubscribeResponse::has_errorcontext() const { return this != internal_default_instance() && errorcontext_ != NULL; } void MDSubscribeResponse::clear_errorcontext() { if (GetArenaNoVirtual() == NULL && errorcontext_ != NULL) delete errorcontext_; errorcontext_ = NULL; } const ::com::htsc::mdc::insight::model::InsightErrorContext& MDSubscribeResponse::errorcontext() const { // @@protoc_insertion_point(field_get:com.htsc.mdc.insight.model.MDSubscribeResponse.errorContext) return errorcontext_ != NULL ? *errorcontext_ : *::com::htsc::mdc::insight::model::InsightErrorContext::internal_default_instance(); } ::com::htsc::mdc::insight::model::InsightErrorContext* MDSubscribeResponse::mutable_errorcontext() { if (errorcontext_ == NULL) { errorcontext_ = new ::com::htsc::mdc::insight::model::InsightErrorContext; } // @@protoc_insertion_point(field_mutable:com.htsc.mdc.insight.model.MDSubscribeResponse.errorContext) return errorcontext_; } ::com::htsc::mdc::insight::model::InsightErrorContext* MDSubscribeResponse::release_errorcontext() { // @@protoc_insertion_point(field_release:com.htsc.mdc.insight.model.MDSubscribeResponse.errorContext) ::com::htsc::mdc::insight::model::InsightErrorContext* temp = errorcontext_; errorcontext_ = NULL; return temp; } void MDSubscribeResponse::set_allocated_errorcontext(::com::htsc::mdc::insight::model::InsightErrorContext* errorcontext) { delete errorcontext_; errorcontext_ = errorcontext; if (errorcontext) { } else { } // @@protoc_insertion_point(field_set_allocated:com.htsc.mdc.insight.model.MDSubscribeResponse.errorContext) } inline const MDSubscribeResponse* MDSubscribeResponse::internal_default_instance() { return &MDSubscribeResponse_default_instance_.get(); } #endif // PROTOBUF_INLINE_NOT_IN_HEADERS // @@protoc_insertion_point(namespace_scope) } // namespace model } // namespace insight } // namespace mdc } // namespace htsc } // namespace com // @@protoc_insertion_point(global_scope)
[ "zhangzhuo@yangzeinvest.com" ]
zhangzhuo@yangzeinvest.com
2fd26235900dcfef693e1b3d887393bcdf6e630e
433918960a7a3c6b09d9b29a63ed1e8fb5de1050
/src/fuml/src_gen/fUML/Semantics/SemanticsPackage.cpp
0fb5e16b31b6306e53fb11a4ded98aaa4222dec2
[ "EPL-1.0", "MIT" ]
permissive
MDE4CPP/MDE4CPP
476709da6c9f0d92504c1539ee4b1012786e3254
24e8ef69956d2a3c6b04dca3a61a97223f6aa959
refs/heads/master
2023-08-31T03:15:56.104582
2023-01-05T14:45:37
2023-01-05T14:45:37
82,116,322
14
27
MIT
2023-06-23T09:23:01
2017-02-15T23:11:29
C++
UTF-8
C++
false
false
732
cpp
#include "fUML/Semantics/SemanticsPackage.hpp" #include "fUML/Semantics/impl/SemanticsPackageImpl.hpp" using namespace fUML::Semantics; //static initialisation const std::string SemanticsPackage::eNAME ="Semantics"; const std::string SemanticsPackage::eNS_URI ="http:///fUML_Semantics/Semantics.ecore"; const std::string SemanticsPackage::eNS_PREFIX ="fUML_Semantics.Semantics"; //Singleton std::shared_ptr<SemanticsPackage> SemanticsPackage::instance; std::shared_ptr<SemanticsPackage> SemanticsPackage::eInstance() { if(!instance) { //create a new Factoryimplementation instance.reset(SemanticsPackageImpl::create()); std::dynamic_pointer_cast<SemanticsPackageImpl>(instance)->init(instance); } return instance; }
[ "Ralph.Maschotta@tu-ilmenau.de" ]
Ralph.Maschotta@tu-ilmenau.de
2123c69f17c89c00c23eeae3acd9b9378fc42dae
98beeffab0570eb7e4bd2785fc195658e18aa6dd
/SRC/image/GRAINBDY/close.h
eabcdf630ba36435426d1eec5ad09c59c069ed17
[ "LicenseRef-scancode-warranty-disclaimer" ]
no_license
shkeshavarz/OOF2
27f59bb04775b76ad250ecfd76118b3760647bba
0f69f535d040875354cd34e8bbedeae142ff09a3
refs/heads/master
2021-01-15T15:32:10.713469
2016-01-13T14:44:20
2016-01-13T14:44:20
null
0
0
null
null
null
null
UTF-8
C++
false
false
956
h
// -*- C++ -*- // $RCSfile: close.h,v $ // $Revision: 1.5 $ // $Author: langer $ // $Date: 2014/09/27 21:41:28 $ /* This software was produced by NIST, an agency of the U.S. government, * and by statute is not subject to copyright in the United States. * Recipients of this software assume all responsibilities associated * with its operation, modification and maintenance. However, to * facilitate maintenance we ask that before distributing modified * versions of this software, you first contact the authors at * oof_manager@nist.gov. */ #include <oofconfig.h> #include "common/array.h" #include "common/boolarray.h" #include "common/doublearray.h" #ifndef CLOSERS_H #define CLOSERS_H class DoubleArray; class BoolArray; class CloserClass{ public: BoolArray dilate(const BoolArray & image, const DoubleArray & pattern); BoolArray erode(const BoolArray&, const DoubleArray&); BoolArray close(const BoolArray&,int); }; #endif //CLOSE_H
[ "lnz5@rosie.nist.gov" ]
lnz5@rosie.nist.gov
06c13cccdc4dab8be03cc1b856ed8cabf8752667
f57610ce330076f2ba95041bbf5f295a9ef40dfe
/Solution/794-valid-tic-tac-toe-state/valid-tic-tac-toe-state.cpp
f7dfbf502c0734801e6fbbf7f0b2a9b5c78cf165
[]
no_license
derek-zr/leetcode
095df86dd00c85b98a3f3ef51e784a65ab75c13d
ec7edcca6a63648d87bed6dd557738b89511368d
refs/heads/master
2021-01-21T21:07:07.114659
2020-11-27T09:29:35
2020-11-27T09:29:35
92,308,067
0
0
null
null
null
null
UTF-8
C++
false
false
3,132
cpp
// A Tic-Tac-Toe board is given as a string array board. Return True if and only if it is possible to reach this board position during the course of a valid tic-tac-toe game. // // The board is a 3 x 3 array, and consists of characters " ", "X", and "O".  The " " character represents an empty square. // // Here are the rules of Tic-Tac-Toe: // // // Players take turns placing characters into empty squares (" "). // The first player always places "X" characters, while the second player always places "O" characters. // "X" and "O" characters are always placed into empty squares, never filled ones. // The game ends when there are 3 of the same (non-empty) character filling any row, column, or diagonal. // The game also ends if all squares are non-empty. // No more moves can be played if the game is over. // // // // Example 1: // Input: board = ["O  ", "   ", "   "] // Output: false // Explanation: The first player always plays "X". // // Example 2: // Input: board = ["XOX", " X ", " "] // Output: false // Explanation: Players take turns making moves. // // Example 3: // Input: board = ["XXX", " ", "OOO"] // Output: false // // Example 4: // Input: board = ["XOX", "O O", "XOX"] // Output: true // // // Note: // // // board is a length-3 array of strings, where each string board[i] has length 3. // Each board[i][j] is a character in the set {" ", "X", "O"}. // // class Solution { public: bool validTicTacToe(vector<string>& board) { //判断传进来的board是否可能是下棋过程中出现的状态 //X:cnts+1 O:cnts-1 cnts最终只能为0或+1 //记录X win还是O win. 如果其中一个win了,则游戏已经结束 int cnts = 0; int X_Win = false,O_Win=false; for(int i=0;i<board.size();i++){ for(char a:board[i]){ if(a=='X') cnts++; else if(a=='O') cnts--; } } if(cnts!=0 && cnts!=1) return false; //记录胜负情况 for(string s:board){ if(s[0]==s[1] && s[1]==s[2] && s[0]=='X') X_Win=true; else if(s[0]==s[1] && s[1]==s[2] && s[0]=='O') O_Win=true; } //cout<<X_Win<<O_Win<<endl; string s0 =board[0]; string s1 =board[1]; string s2 =board[2]; for(int i=0;i<s0.size();i++){ if(s0[i]==s1[i] && s1[i]==s2[i] && s0[i]=='X') X_Win=true; else if(s0[i]==s1[i] && s1[i]==s2[i] && s0[i]=='O') O_Win=true; } if(s0[0]==s1[1] && s1[1]==s2[2] && s0[0]=='X') X_Win=true; else if(s0[0]==s1[1] && s1[1]==s2[2] && s0[0]=='O') O_Win=true; if(s0[2]==s1[1] && s1[1]==s2[0] && s0[2]=='X') X_Win=true; else if(s0[2]==s1[1] && s1[1]==s2[0] && s0[2]=='O') O_Win=true; //cout<<X_Win<<O_Win<<endl; if(X_Win && O_Win) return false; if(X_Win && cnts==0) return false; //X赢的时候,X的个数必然大于O一个 if(O_Win && cnts==1) return false; //O赢的时候,X的个数必然等于O return true; } };
[ "derek_zhengrui@foxmail.com" ]
derek_zhengrui@foxmail.com
3b86c2392fa257af93f8324f54fbe44a94688610
777a75e6ed0934c193aece9de4421f8d8db01aac
/src/Providers/UNIXProviders/ESPTransform/UNIX_ESPTransform.h
887df2472ff13028c4c0973b79c0cf0ad3db5752
[ "MIT" ]
permissive
brunolauze/openpegasus-providers-old
20fc13958016e35dc4d87f93d1999db0eae9010a
b00f1aad575bae144b8538bf57ba5fd5582a4ec7
refs/heads/master
2021-01-01T20:05:44.559362
2014-04-30T17:50:06
2014-04-30T17:50:06
19,132,738
1
0
null
null
null
null
UTF-8
C++
false
false
4,546
h
//%LICENSE//////////////////////////////////////////////////////////////// // // Licensed to The Open Group (TOG) under one or more contributor license // agreements. Refer to the OpenPegasusNOTICE.txt file distributed with // this work for additional information regarding copyright ownership. // Each contributor licenses this file to you under the OpenPegasus Open // Source License; you may not use this file except in compliance with the // License. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. // IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY // CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, // TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE // SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // ////////////////////////////////////////////////////////////////////////// // //%///////////////////////////////////////////////////////////////////////// #ifndef __UNIX_ESPTRANSFORM_H #define __UNIX_ESPTRANSFORM_H #include "CIM_SATransform.h" #include "UNIX_ESPTransformDeps.h" #define PROPERTY_INTEGRITY_TRANSFORM_ID "IntegrityTransformId" #define PROPERTY_OTHER_INTEGRITY_TRANSFORM_ID "OtherIntegrityTransformId" #define PROPERTY_CIPHER_TRANSFORM_ID "CipherTransformId" #define PROPERTY_OTHER_CIPHER_TRANSFORM_ID "OtherCipherTransformId" #define PROPERTY_CIPHER_KEY_LENGTH "CipherKeyLength" #define PROPERTY_CIPHER_KEY_ROUNDS "CipherKeyRounds" #define PROPERTY_USE_REPLAY_PREVENTION "UseReplayPrevention" #define PROPERTY_REPLAY_PREVENTION_WINDOW_SIZE "ReplayPreventionWindowSize" class UNIX_ESPTransform : public CIM_SATransform { public: UNIX_ESPTransform(); ~UNIX_ESPTransform(); virtual Boolean initialize(); virtual Boolean load(int&); virtual Boolean finalize(); virtual Boolean find(Array<CIMKeyBinding>&); virtual Boolean validateKey(CIMKeyBinding&) const; virtual void setScope(CIMName); virtual Boolean getInstanceID(CIMProperty&) const; virtual String getInstanceID() const; virtual Boolean getCaption(CIMProperty&) const; virtual String getCaption() const; virtual Boolean getDescription(CIMProperty&) const; virtual String getDescription() const; virtual Boolean getElementName(CIMProperty&) const; virtual String getElementName() const; virtual Boolean getChangeableType(CIMProperty&) const; virtual Uint16 getChangeableType() const; virtual Boolean getConfigurationName(CIMProperty&) const; virtual String getConfigurationName() const; virtual Boolean getMaxLifetimeSeconds(CIMProperty&) const; virtual Uint64 getMaxLifetimeSeconds() const; virtual Boolean getMaxLifetimeKilobytes(CIMProperty&) const; virtual Uint64 getMaxLifetimeKilobytes() const; virtual Boolean getVendorID(CIMProperty&) const; virtual String getVendorID() const; virtual Boolean getIntegrityTransformId(CIMProperty&) const; virtual Uint16 getIntegrityTransformId() const; virtual Boolean getOtherIntegrityTransformId(CIMProperty&) const; virtual String getOtherIntegrityTransformId() const; virtual Boolean getCipherTransformId(CIMProperty&) const; virtual Uint16 getCipherTransformId() const; virtual Boolean getOtherCipherTransformId(CIMProperty&) const; virtual String getOtherCipherTransformId() const; virtual Boolean getCipherKeyLength(CIMProperty&) const; virtual Uint16 getCipherKeyLength() const; virtual Boolean getCipherKeyRounds(CIMProperty&) const; virtual Uint16 getCipherKeyRounds() const; virtual Boolean getUseReplayPrevention(CIMProperty&) const; virtual Boolean getUseReplayPrevention() const; virtual Boolean getReplayPreventionWindowSize(CIMProperty&) const; virtual Uint32 getReplayPreventionWindowSize() const; private: CIMName currentScope; # include "UNIX_ESPTransformPrivate.h" }; #endif /* UNIX_ESPTRANSFORM */
[ "brunolauze@msn.com" ]
brunolauze@msn.com
9c607600df0ed480b6b8719b17a4ef2312d0653c
38af1e7e3ed5a993dc6db6bb172c2471ea9e192f
/symbol_table/ClassInfo.cpp
cb6b0af386f3081b8e84fbe15bc54f605468f341
[]
no_license
zhukovp0101/compilers
b87f118ae2b3874f51ab1a0bd0e2e4e8170ff28e
8299dcdd8f577538e4a83e03490d5f5eafef65f3
refs/heads/master
2022-07-14T20:43:05.809153
2020-05-22T01:16:36
2020-05-22T01:16:36
265,988,081
0
0
null
null
null
null
UTF-8
C++
false
false
68
cpp
// // Created by bevertax on 04.04.2020. // #include "ClassInfo.h"
[ "bevertax@gmail.com" ]
bevertax@gmail.com
910f844f5087e26f04c50b34c8e314cbd804072b
4f307eb085ad9f340aaaa2b6a4aa443b4d3977fe
/Roman.Miller/assignment5/Game.cpp
f854bdc77bf54544e4f5ea70befcfb2be0b75443
[]
no_license
Connellj99/GameArch
034f4a0f52441d6dde37956a9662dce452a685c7
5c95e9bdfce504c02c73a0c3cb566a010299a9b8
refs/heads/master
2020-12-28T10:29:19.935573
2020-02-04T19:41:09
2020-02-04T19:41:09
238,286,390
0
0
null
null
null
null
UTF-8
C++
false
false
3,976
cpp
#include "Event.h" #include "Game.h" #include <PerformanceTracker.h> #include "EventSystem.h" #include "GameEvent.h" Game* Game::mpsGameInstance = nullptr; void Game::render() { mSystem->getGraphicsSystem()->draw(Vector2D(0, 0), *mpWoodsSprite, WOODS_SCALE); mUnitManager.updateUnit(); mUnitManager.draw(); mSystem->getGraphicsSystem()->flip(); } void Game::update() { mpInputSystem->update(); mUnitManager.updateUnit(); } Game::Game() :EventListener(EventSystem::getInstance()) { mpWoodsSprite = nullptr; } Game::~Game() { cleanup(); } void Game::initInstance() { //as long as no other deal is there make one if (mpsGameInstance == nullptr) { mpsGameInstance = new Game(); } else { assert(mpsGameInstance != nullptr); } } void Game::cleanupInstance() { delete mpsGameInstance; mpsGameInstance = nullptr; } void Game::doLoop() { PerformanceTracker tracker = PerformanceTracker(); while (mLoopGame) { tracker.clearTracker(TRACKER); tracker.startTracking(TRACKER); mTimer.start(); //-- update(); render(); mTimer.sleepUntilElapsed(mframeTime); //-- tracker.stopTracking(TRACKER); cout << tracker.getElapsedTime(TRACKER) << endl; } } Game * Game::getInstance() { assert(mpsGameInstance); return mpsGameInstance; } void Game::init(Vector2D screenSize, float targetFrameRate) { mpInputSystem = new InputSystem(); mpInputTranslator = new InputTranslator(EventSystem::getInstance()); mSystem = new System(); mSystem->init(); mBufferManager = GraphicsBufferManager(); mUnitManager = UnitManager(); //Set screen and frame variables mScreenSize = screenSize; mframeTime = 1000 / targetFrameRate; //create buffers and add to manager mBufferManager.addBuffer(WOODS_KEY ,new GraphicsBuffer(SHARED_PATH + BACKGROUND_FILENAME)); mBufferManager.addBuffer(SMURF_KEY, new GraphicsBuffer(SHARED_PATH + SMURF_FILENAME)); mBufferManager.addBuffer(DEAN_KEY, new GraphicsBuffer(SHARED_PATH + DEAN_FILENAME)); mpWoodsSprite = new Sprite(mBufferManager.getBuffer(WOODS_KEY), Vector2D(0, 0), Vector2D(mBufferManager.getBuffer(WOODS_KEY)->getWidth(), mBufferManager.getBuffer(WOODS_KEY)->getHeight())); EventSystem::getInstance()->addListener((EventType)EXIT_GAME, this); EventSystem::getInstance()->addListener((EventType)CREATE, this); EventSystem::getInstance()->addListener((EventType)DESTROY, this); EventSystem::getInstance()->addListener((EventType)PAUSE_ANIMATIONS, this); EventSystem::getInstance()->addListener((EventType)SWAP_ANIMATIONS, this); } void Game::cleanup() { delete mpWoodsSprite; mpWoodsSprite = nullptr; mSystem->cleanup(); delete mSystem; mSystem = nullptr; delete mpInputTranslator; mpInputTranslator = nullptr; delete mpInputSystem; mpInputSystem = nullptr; } System* Game::getSystem() { return mSystem; } void Game::handleEvent(const Event & theEvent) { if (theEvent.getType() == EXIT_GAME) { exitDoloop(); } else if (theEvent.getType() == CREATE) { const UnitEvent& temp = static_cast<const UnitEvent&>(theEvent); createNewUnit(temp.getLocation()); } else if (theEvent.getType() == DESTROY) { const DestroyEvent& temp = static_cast<const DestroyEvent&>(theEvent); deleteUnitAtLoc(temp.getLocation()); } else if (theEvent.getType() == PAUSE_ANIMATIONS) { pauseAllAnimation(); } else if (theEvent.getType() == SWAP_ANIMATIONS) { swapAnimationOfLastUnit(); } } void Game::createNewUnit(Vector2D loc) { loc-= Vector2D(30, 30); vector<Animation> temp; temp.push_back(Animation(*mBufferManager.getBuffer(SMURF_KEY), SMURF_SPRITE_SIZE)); temp.push_back(Animation(*mBufferManager.getBuffer(DEAN_KEY), SMURF_SPRITE_SIZE)); mUnitManager.createUnit(temp, loc); } void Game::deleteUnitAtLoc(Vector2D loc) { mUnitManager.deleteByPosition(loc); } void Game::pauseAllAnimation() { mUnitManager.pausePlayAllUnits(); } void Game::swapAnimationOfLastUnit() { mUnitManager.getUnit()->swapAnimations(); } void Game::exitDoloop() { mLoopGame = false; }
[ "john.connelly@mymail.champlain.edu" ]
john.connelly@mymail.champlain.edu
26402dc115d9a7d1438a096420b6b5bb2b55d7a5
0daf0d997653db5759d5bd98308bad08a994b220
/src/qt/btcu/addnewaddressdialog.cpp
a69dbc56d9e5e82ad10aa2f4b15ccc830afcde53
[ "MIT" ]
permissive
dim4egster/btcu_coderev
5e5dbdbc4434f23b92d6322348e88af6c49f931d
75daa1a8ab6010c93939f8bdd6d71101fbc58c48
refs/heads/main
2023-02-28T08:40:27.318343
2021-02-03T14:47:31
2021-02-03T15:02:09
322,042,518
0
0
MIT
2021-02-02T22:31:39
2020-12-16T16:39:35
C++
UTF-8
C++
false
false
976
cpp
// Copyright (c) 2019 The PIVX developers // Copyright (c) 2020 The BTCU developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "qt/btcu/addnewaddressdialog.h" #include "qt/btcu/forms/ui_addnewaddressdialog.h" AddNewAddressDialog::AddNewAddressDialog(QWidget *parent) : QWidget(parent), ui(new Ui::AddNewAddressDialog) { ui->setupUi(this); // Stylesheet this->setStyleSheet(parent->styleSheet()); // Container ui->frameContainer->setProperty("cssClass", "container-dialog"); // Title ui->labelTitle->setText("New Address"); ui->labelTitle->setProperty("cssClass", "text-title-dialog"); // Buttons ui->btnCancel->setProperty("cssClass", "btn-dialog-cancel"); ui->btnSave->setText("SAVE"); ui->btnSave->setProperty("cssClass", "btn-primary"); } AddNewAddressDialog::~AddNewAddressDialog() { delete ui; }
[ "dim4egster@gmail.com" ]
dim4egster@gmail.com
8e3ca96ae3f29399e5545a971234a6067e49b80b
b2e21c4578ec8816220ab8af904e15b7cc31fd7e
/HORRIBLE.cpp
cc9fdd2e385a07cc6c1f42935f7cfec112700fc9
[]
no_license
vkthakur/spoj
70968b8ecd67208e33dd7d666a69047eb71b7e26
1731c05624a1eaed0fec3d84c31b4b2aaaea11b5
refs/heads/master
2016-09-10T01:10:34.977541
2015-01-19T20:18:33
2015-01-19T20:18:33
28,721,879
0
1
null
null
null
null
UTF-8
C++
false
false
1,321
cpp
#include <iostream> #include <stdio.h> #include <math.h> #include <utility> #include <algorithm> #include <set> #include <queue> #include <vector> #include <stack> #include <map> #include <stdlib.h> using namespace std; #define input(i) scanf("%lld",&i); long long int tree1[100001],maxval,tree2[100001]; long long int read(long long int tree[],long long int idx) { long long int sum=0; while(idx > 0) { sum=sum + tree[idx]; idx=idx - (idx & (-idx)); } return sum; } void update(long long int tree[],long long int idx,long long int val) { while(idx <=maxval) { tree[idx]=tree[idx] + val; idx=idx + (idx & (-idx)); } } int main() { long long int t; input(t); while(t--) { long long int n,c,i; input(n); input(c); maxval=n; for(i=0;i<=n;i++) { tree1[i]=0; tree2[i]=0; } while(c--) { long long int chck,p,q; long long int v; input(chck); input(p); input(q); if(chck==0) { input(v); update(tree1,p,v); if(q < n) update(tree1,q+1,(-1)*v); update(tree2,p,v*(p-1)); if(q < n) update(tree2,q+1,(-1)*v*q); } else { long long int sum1,sum2,sum; sum1=read(tree1,q)*q - read(tree2,q); p=p-1; sum2=read(tree1,p)*p - read(tree2,p); sum=sum1-sum2; printf("%lld\n",sum); } } } return 0; }
[ "me.vivekkrthakur@gmail.com" ]
me.vivekkrthakur@gmail.com
00d520454c4d4e3738a2d62025564d9247f2d328
41704dd9a57c4f84e639e7ee2610e5cd71a5826a
/Castlevania/BulletManager.h
be09a5283ef61ce65bd4b0ba0e9227f86652493e
[]
no_license
GameCastleVania/CSVNL
b373f213b720c316a5784e7506a7bfaa3edf7723
65a452d1b36c8c40ce754fcf5affcab2ac665f24
refs/heads/master
2020-06-11T10:12:56.490391
2017-01-04T20:28:26
2017-01-04T20:28:26
75,696,672
0
0
null
null
null
null
UTF-8
C++
false
false
1,206
h
#pragma once #include "FireBall.h" #include "Boss2Bullet.h" #include "SkeletonBullet.h" #include "Boss3Bullet.h" #include "Bullet.h" #include "keyboard.h" #include "psound.h" #include "utils.h" #include <vector> typedef vector<Bullet*> BulletList; class BulletManager { protected: Keyboard* kbd; PSound* psound; BulletList bList; BulletList bossBList; Direction direc; //Player bullet count int timeFire; //fire time between each bullet int fireRate; //bullet fire rate int timeLimit; //time limit between 3 bullet int nextbullet; //Bullet type temp Bullet bullet; FireBall fireball; SkeletonBullet boneBullet; Boss2Bullet boss2Bullet; Boss3Bullet boss3Bullet; public: BulletManager() {} BulletManager(LPDIRECT3DDEVICE9 _d3ddv, Keyboard* _keyboard, Explosion* _explosion, PSound* _psound); ~BulletManager(); void Draw(int vpx, int vpy); void Update(int vpx, int vpy); void Get(BulletType type, float x, float y, float vx, float vy, bool isPlayer); void Get(int boss, float x, float y, float vx, float vy); void LowerTimeLimit(); BulletList GetList(); BulletList GetBossList(); }; struct Point { float x; float y; };
[ "13520592@gm.uit.edu.vn" ]
13520592@gm.uit.edu.vn
04a10a2447cd6488bac678b43f54102de89c293c
769c03556677d81357cd980812cb4e0e610f09cb
/jeu-entreprise/entite.h
ec000a7bd77374394121c4cd9831734c59fc6bfb
[]
no_license
rcatajar/jeu-entreprise
f1c4df9a216df0c5d840105838ec687af3685b23
ba9b381998750452aef6b15d8fc237fec9158156
refs/heads/master
2021-01-18T01:47:56.990528
2016-02-02T11:22:17
2016-02-02T11:22:17
46,358,368
0
0
null
null
null
null
UTF-8
C++
false
false
890
h
// Classe (abstraite) representant une Entité. // Une entité est un acteur du marché (client ou entreprise) // avec: // - un nom (constant) // - une tresorerie (variable) // - un stock (vecteur d'Objets) #ifndef ENTITE_H #define ENTITE_H #include <vector> #include <QString> // forward-declaration de la classe. // On ne peux pas include "objet.h", car ça cause un import circulaire class Objet; class Entite { protected: QString nom; float tresorerie; std::vector <Objet*> stock; public: Entite(const QString &, float); const QString & get_nom() const; float get_tresorerie() const; void set_tresorerie(float); std::vector <Objet*> get_stock() const; void ajouter_au_stock(Objet*); void retirer_au_stock(Objet*); void gestion_des_stocks(); }; #endif // ENTITE_H
[ "rcatajar@gmail.com" ]
rcatajar@gmail.com
ebcd9765404c87f80d7356a83d9fd37266e7d0fa
8a659a42a51c301a56c1c7dfd6488f65022f2429
/libs/eos/eos/learn-eos/pca/main.cpp
533018eafeef22a445339ec915f164ead7f054ee
[ "Apache-2.0" ]
permissive
quanhua92/learning-notes
0aacf7873b44abf22af0c6721dba0c9f81753080
a9c50d3955c51bb58f4b012757c550b76c5309ef
refs/heads/master
2021-01-22T12:35:01.130145
2018-12-11T07:41:24
2018-12-11T07:41:24
102,350,672
0
0
null
null
null
null
UTF-8
C++
false
false
866
cpp
#include <iostream> #include <Eigen\Core> #include "pca.h" using namespace std; using Eigen::ArrayXXf; using Eigen::MatrixXf; using Eigen::VectorXf; using namespace eos::pca; int main(int argc, char** argv) { VectorXf eigenvalues; MatrixXf eigenvectors; MatrixXf meanfree_data = MatrixXf::Random(10, 50); // rows, cols cout << "meanfree_data: \n" << meanfree_data << endl; Eigen::RowVectorXf mean_data = meanfree_data.colwise().mean(); cout << "colwise().mean(): \n" << mean_data << endl; meanfree_data.rowwise() -= mean_data; cout << "meanfree_data: \n" << meanfree_data << endl; Covariance covariance_type = Covariance::AtA; std::tie(eigenvectors, eigenvalues) = pca(meanfree_data, covariance_type); cout << "Eigenvectors: \n" << eigenvectors << endl; cout << "Eigenvalues: \n" << eigenvalues << endl; system("pause"); return EXIT_SUCCESS; }
[ "quanhua92@gmail.com" ]
quanhua92@gmail.com
483959a2453a12413495a660a11a65008cb1df1f
ab0a8234e443a6aa152b9f7b135a1e2560e9db33
/Server/CGSF/LogicLayer/MOGame/account-server/flooritem.h
436dedbc71e56fbfec60c728d567a42a76668eb7
[]
no_license
zetarus/Americano
71c358d8d12b144c8858983c23d9236f7d0e941b
b62466329cf6f515661ef9fb9b9d2ae90a032a60
refs/heads/master
2023-04-08T04:26:29.043048
2018-04-19T11:21:14
2018-04-19T11:21:14
104,159,178
9
2
null
2023-03-23T12:10:51
2017-09-20T03:11:44
C++
UTF-8
C++
false
false
1,593
h
/* * The Mana Server * Copyright (C) 2011 The Mana Development Team * * This file is part of The Mana Server. * * The Mana Server is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * any later version. * * The Mana Server 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 The Mana Server. If not, see <http://www.gnu.org/licenses/>. */ #ifndef FLOOR_ITEM_H #define FLOOR_ITEM_H class FloorItem { public: FloorItem(): mItemId(0), mItemAmount(0), mPosX(0), mPosY(0) {} FloorItem(int itemId, int itemAmount, int posX, int posY): mItemId(itemId), mItemAmount(itemAmount), mPosX(posX), mPosY(posY) {} /** * Returns the item id */ int getItemId() const { return mItemId; } /** * Returns the amount of items */ int getItemAmount() const { return mItemAmount; } /** * Returns the position x of the item(s) */ int getPosX() const { return mPosX; } /** * Returns the position x of the item(s) */ int getPosY() const { return mPosY; } private: int mItemId; int mItemAmount; int mPosX; int mPosY; }; #endif // FLOOR_ITEM_H
[ "sinyonzzang@gmail.com" ]
sinyonzzang@gmail.com
940017fe8451a5352018a80725d35c7e7978960b
64ea78e9237ee9a96a28dfa73bab3aa295934b66
/gradebook/src/gradebook.cpp
91fa6333274cc9a4a5627dcb926647275618e448
[]
no_license
sccdyuyu/zhang_yushi
5fb8874fb108e65997e5d6f7cdf0360c15484f42
c63128ebfebbe080e6f58bf81ee57329f89cd345
refs/heads/master
2020-04-27T10:04:11.482951
2019-05-12T14:53:43
2019-05-12T14:53:43
174,238,598
0
0
null
null
null
null
UTF-8
C++
false
false
584
cpp
#include <iostream> #include<GradeBook.h> using namespace std; GradeBook::GradeBook (string cn,string tn) :courseName(cn),teacherName(tn) { } void GradeBook::setCourseName(string cn) { courseName=cn; } string GradeBook::getCourseName()const { return courseName; }void GradeBook::setTeacherName(string tn) { teacherName=tn; } string GradeBook::getTeacherName()const { return teacherName; } void GradeBook::displayMessage()const { cout<<"welcome to the grade book for\n"<<getCourseName()<<"!" <<"\nThis course is presented by\n"<<getTeacherName()<<"!"<<endl; }
[ "sccdyuyu@gmail.com" ]
sccdyuyu@gmail.com
105f29cdfa8a3709057f06143857ffbedd830a5e
3bbefab6c034154ae4724baf0fe9de1eb2008d82
/src/appleseed/renderer/kernel/texturing/texturecache.h
ba7b7ab760a98e3ab21710697854426077d0afba
[ "MIT" ]
permissive
johnhaddon/appleseed
e959a30ab24f80a4cb3639d22c1b16b58fc3373c
82eb4693f7a64fcaf238272a1ad62ff38c5b870b
refs/heads/master
2021-01-22T09:32:01.704121
2016-08-22T17:41:23
2016-08-22T17:41:23
17,192,177
1
0
null
2016-08-24T12:04:18
2014-02-25T23:36:11
C++
UTF-8
C++
false
false
5,667
h
// // This source file is part of appleseed. // Visit http://appleseedhq.net/ for additional information and resources. // // This software is released under the MIT license. // // Copyright (c) 2010-2013 Francois Beaune, Jupiter Jazz Limited // Copyright (c) 2014-2016 Francois Beaune, The appleseedhq Organization // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // #ifndef APPLESEED_RENDERER_KERNEL_TEXTURING_TEXTURECACHE_H #define APPLESEED_RENDERER_KERNEL_TEXTURING_TEXTURECACHE_H // appleseed.renderer headers. #include "renderer/kernel/texturing/texturestore.h" // appleseed.foundation headers. #include "foundation/core/concepts/noncopyable.h" #include "foundation/math/hash.h" #include "foundation/platform/types.h" #include "foundation/utility/cache.h" #include "foundation/utility/statistics.h" #include "foundation/utility/uid.h" // Standard headers. #include <cstddef> // Forward declarations. namespace foundation { class Tile; } namespace renderer { // // A thread-local cache of texture tiles. // class TextureCache : public foundation::NonCopyable { public: // Constructor. explicit TextureCache(TextureStore& store); // Get a tile from the cache. foundation::Tile& get( const foundation::UniqueID assembly_uid, const foundation::UniqueID texture_uid, const size_t tile_x, const size_t tile_y); // Retrieve performance statistics. foundation::StatisticsVector get_statistics() const; foundation::uint64 get_hit_count() const; foundation::uint64 get_miss_count() const; private: typedef TextureStore::TileKey TileKey; typedef TextureStore::TileRecord TileRecord; typedef TileRecord* TileRecordPtr; struct TileKeyHasher : public foundation::NonCopyable { // Hash a key into an integer. size_t operator()(const TileKey& key) const; }; class TileRecordSwapper : public foundation::NonCopyable { public: // Constructor. explicit TileRecordSwapper(TextureStore& store); // Load a cache line. void load(const TileKey& key, TileRecordPtr& record); // Unload a cache line. void unload(const TileKey& key, TileRecordPtr& record); private: TextureStore& m_store; }; typedef foundation::SACache< TileKey, TileKeyHasher, TileRecordPtr, TileRecordSwapper, 512, // number of cache lines 4 // number of ways > TileCache; TileKeyHasher m_tile_key_hasher; TileRecordSwapper m_tile_record_swapper; TileCache m_tile_cache; }; // // TextureCache class implementation. // inline TextureCache::TextureCache(TextureStore& store) : m_tile_record_swapper(store) , m_tile_cache(m_tile_key_hasher, m_tile_record_swapper, TileKey::invalid()) { } inline foundation::Tile& TextureCache::get( const foundation::UniqueID assembly_uid, const foundation::UniqueID texture_uid, const size_t tile_x, const size_t tile_y) { const TileKey key(assembly_uid, texture_uid, tile_x, tile_y); return *m_tile_cache.get(key)->m_tile; } inline foundation::StatisticsVector TextureCache::get_statistics() const { return foundation::StatisticsVector::make( "texture cache statistics", foundation::make_single_stage_cache_stats(m_tile_cache)); } inline foundation::uint64 TextureCache::get_hit_count() const { return m_tile_cache.get_hit_count(); } inline foundation::uint64 TextureCache::get_miss_count() const { return m_tile_cache.get_miss_count(); } // // TextureCache::TileKeyHasher class implementation. // inline size_t TextureCache::TileKeyHasher::operator()(const TileKey& key) const { return foundation::mix_uint32( static_cast<foundation::uint32>(key.m_assembly_uid), static_cast<foundation::uint32>(key.m_texture_uid), static_cast<foundation::uint32>(key.m_tile_xy)); } // // TextureCache::TileRecordSwapper class implementation. // inline TextureCache::TileRecordSwapper::TileRecordSwapper(TextureStore& store) : m_store(store) { } inline void TextureCache::TileRecordSwapper::load(const TileKey& key, TileRecordPtr& record) { record = &m_store.acquire(key); } inline void TextureCache::TileRecordSwapper::unload(const TileKey& key, TileRecordPtr& record) { m_store.release(*record); } } // namespace renderer #endif // !APPLESEED_RENDERER_KERNEL_TEXTURING_TEXTURECACHE_H
[ "beaune@aist.enst.fr" ]
beaune@aist.enst.fr
228c4b1524fa9ed820c22cd34ea93bade0d70a4a
df889323b01f408e0949b2592e2ef35371e67bac
/CS32/Homeworks/Homework2/mazestack.cpp
2e71f1a21a065f4cd3d397255e36839f43ff94bc
[]
no_license
thenathanyang/UCLA
0c750744b5bf283e16abac904a110850efab7fef
fc7781361c93370b80a265615189253995693070
refs/heads/master
2021-09-08T07:35:48.921714
2021-09-02T02:07:56
2021-09-02T02:14:01
57,343,142
1
1
null
null
null
null
UTF-8
C++
false
false
1,961
cpp
// mazestack.cpp Problem 1 #include <stack> #include <iostream> using namespace std; class Coord { public: Coord(int rr, int cc) : m_r(rr), m_c(cc) {} int r() const { return m_r; } int c() const { return m_c; } private: int m_r; int m_c; }; bool pathExists(string maze[], int nRows, int nCols, int sr, int sc, int er, int ec) { // Return true if there is a path from (sr,sc) to (er,ec) // through the maze; return false otherwise stack<Coord> coordStack; coordStack.push(Coord(sr, sc)); maze[sr][sc] = '*'; while (! coordStack.empty()) { Coord top = coordStack.top(); coordStack.pop(); int top_r = top.r(); int top_c = top.c(); if (top_r == er && top_c == ec) return true; if (top_r-1 >= 0 && top_r-1 < nRows && maze[top_r-1][top_c] == '.') // North { coordStack.push(Coord(top_r-1, top_c)); maze[top_r-1][top_c] = '*'; } if (top_c+1 >= 0 && top_c+1 < nCols && maze[top_r][top_c+1] == '.') // East { coordStack.push(Coord(top_r, top_c+1)); maze[top_r][top_c+1] = '*'; } if (top_r+1 >= 0 && top_r+1 < nRows && maze[top_r+1][top_c] == '.') // South { coordStack.push(Coord(top_r+1, top_c)); maze[top_r+1][top_c] = '*'; } if (top_c-1 >= 0 && top_c-1 < nCols && maze[top_r][top_c-1] == '.') // West { coordStack.push(Coord(top_r, top_c-1)); maze[top_r][top_c-1] = '*'; } } return false; } int main() { string maze[10] = { "XXXXXXXXXX", "X........X", "XX.X.XXXXX", "X..X.X...X", "X..X...X.X", "XXXX.XXX.X", "X.X....XXX", "X..XX.XX.X", "X...X....X", "XXXXXXXXXX" }; if (pathExists(maze, 10,10, 6,4, 1,1)) cout << "Solvable!" << endl; else cout << "Out of luck!" << endl; }
[ "thenathanyang@gmail.com" ]
thenathanyang@gmail.com
820825995a791125da8b3aa558e4c66a822195d2
e753f8ab10eb6732f272217169e48ab4754295ee
/www/chromium/files/patch-chrome_browser_safe__browsing_cloud__content__scanning_binary__upload__service.cc
da2a6a7844aef14fb4ef21cfa121aecac8acf1bc
[ "BSD-2-Clause", "BSD-3-Clause" ]
permissive
DragonFlyBSD/DPorts
dd2e68f0c11a5359bf1b3e456ab21cbcd9529e1c
4b77fb40db21fdbd8de66d1a2756ac1aad04d505
refs/heads/master
2023-08-12T13:54:46.709702
2023-07-28T09:53:12
2023-07-28T09:53:12
6,439,865
78
52
NOASSERTION
2023-09-02T06:27:16
2012-10-29T11:59:35
null
UTF-8
C++
false
false
1,090
cc
--- chrome/browser/safe_browsing/cloud_content_scanning/binary_upload_service.cc.orig 2023-05-31 08:12:17 UTC +++ chrome/browser/safe_browsing/cloud_content_scanning/binary_upload_service.cc @@ -18,7 +18,7 @@ #include "net/base/url_util.h" #include "third_party/abseil-cpp/absl/types/variant.h" -#if BUILDFLAG(IS_WIN) || BUILDFLAG(IS_MAC) || BUILDFLAG(IS_LINUX) +#if BUILDFLAG(IS_WIN) || BUILDFLAG(IS_MAC) || BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_BSD) #include "chrome/browser/enterprise/connectors/analysis/local_binary_upload_service_factory.h" #endif @@ -368,7 +368,7 @@ BinaryUploadService* BinaryUploadService::GetForProfil Profile* profile, const enterprise_connectors::AnalysisSettings& settings) { // Local content analysis is supported only on desktop platforms. -#if BUILDFLAG(IS_WIN) || BUILDFLAG(IS_MAC) || BUILDFLAG(IS_LINUX) +#if BUILDFLAG(IS_WIN) || BUILDFLAG(IS_MAC) || BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_BSD) if (settings.cloud_or_local_settings.is_cloud_analysis()) { return CloudBinaryUploadServiceFactory::GetForProfile(profile); } else {
[ "nobody@home.ok" ]
nobody@home.ok
0c7b3db9ea97c5ce35c38b6e7c75b284dac050af
495ddf1234614b60a4fee08b13a43c8cba9fd6db
/IO_SRV_PROJECTS/I7000_IO_SRV/SOURCES/INCLUDE/I7000_proto.h
bbc9218857caa1c3b902448ce1dfce7bcc5edfb8
[]
no_license
emenshoff/IO_SRV_2002
cea81e4e9eb684e84c2f51da540ccc17fb183dc3
9d185223f55e3ae15dc640160477a5caf331aa79
refs/heads/master
2020-04-16T00:03:57.492915
2019-01-13T20:18:20
2019-01-13T20:18:20
165,123,541
0
0
null
null
null
null
WINDOWS-1251
C++
false
false
11,797
h
/*********************************************************** Функции для формирования и разбора пакетов протокола I7000. Два типа функций (для асинхронной работы) : ф-я отсылки запроса(с префиксом "Out") и ф-я чтения ответа ("In"). created by M.E.N ***********************************************************/ #ifndef _I7000_proto_h_ #define _I7000_proto_h_ #define OK 1 #define CRC_ERROR -2 #define READ_ERROR -1 #define WRONG_PACKET -3 #define WRONG_ADDRESS -4 #define WRONG_COMMAND -5 #define WRONG_ADDR -6 #define IGNORED_COMMAND -7 class I7000_SerialPort; //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% /*class I7000_Proto { public:*/ //---------- Read Digital Input -------------------------- int OutDigitalIn(I7000_SerialPort *, unsigned char addr, //адрес модуля unsigned char crc_enable, //признак вычисления/проверки контрольной суммы unsigned short module_id, //идентификатор модуля unsigned not_used); //не используется int InDigitalIn(I7000_SerialPort *, unsigned char addr, //адрес модуля unsigned char crc_enable, //признак вычисления/проверки контрольной суммы unsigned short module_id, //идентификатор модуля unsigned &result); //4 - х байтовый результат //---------- Digital Output -------------------------- int OutDigitalOut(I7000_SerialPort *, unsigned char addr, //адрес модуля unsigned char crc_enable, //признак вычисления/проверки контрольной суммы unsigned short module_id, //идентификатор модуля unsigned out); //значения выходов int InDigitalOut(I7000_SerialPort *, unsigned char addr, //адрес модуля unsigned char crc_enable, //признак вычисления/проверки контрольной суммы unsigned short module_id, //идентификатор модуля unsigned &result); //4 - х байтовый результат //---------- Set Digital Output -------------------------- int OutSetDigitalOut(I7000_SerialPort *, unsigned char addr, //адрес модуля unsigned char crc_enable, //признак вычисления/проверки контрольной суммы unsigned short module_id, //идентификатор модуля unsigned out); //значения выходов int InSetDigitalOut(I7000_SerialPort *, unsigned char addr, //адрес модуля unsigned char crc_enable, //признак вычисления/проверки контрольной суммы unsigned short module_id, //идентификатор модуля unsigned &result); //4 - х байтовый результат //---------- Read Digital IO status ---------------------- int OutGetDigitalIOStatus(I7000_SerialPort *, unsigned char addr, //адрес модуля unsigned char crc_enable, //признак вычисления/проверки контрольной суммы unsigned short module_id, //идентификатор модуля unsigned out); //значения выходов int InGetDigitalIOStatus(I7000_SerialPort *, unsigned char addr, //адрес модуля unsigned char crc_enable, //признак вычисления/проверки контрольной суммы unsigned short module_id, //идентификатор модуля unsigned &result); //4 - х байтовый результат //-------- Read Config Status ---------------------------- int OutReadConfig(I7000_SerialPort *, unsigned char addr, //адрес модуля unsigned char crc_enable, //признак вычисления/проверки контрольной суммы unsigned short module_id, //идентификатор модуля unsigned not_used); // int InReadConfig(I7000_SerialPort *, unsigned char addr, //адрес модуля unsigned char crc_enable, //признак вычисления/проверки контрольной суммы unsigned short module_id, //идентификатор модуля unsigned &cfg); //конфигурация // cfg[0]: module Range Code // cfg[1]: module baudrate // cfg[2]: module data format //-------- Set Config ------------------------------------ int OutSetConfig(I7000_SerialPort *, unsigned char addr, //адрес модуля unsigned char crc_enable, //признак вычисления/проверки контрольной суммы unsigned short module_id, //идентификатор модуля unsigned cfg); //конфигурация // cfg[0]: new module adddress // cfg[1]: module Range Code // cfg[2]: module baudrate // cfg[3]: module data format int InSetConfig(I7000_SerialPort *, unsigned char addr, //адрес модуля unsigned char crc_enable, //признак вычисления/проверки контрольной суммы unsigned short module_id, //идентификатор модуля unsigned &result); //результат операции //-------- Read Reset Status ------------------------------ int OutReadResetStatus(I7000_SerialPort *, unsigned char addr, //адрес модуля unsigned char crc_enable, //признак вычисления/проверки контрольной суммы unsigned short module_id, //идентификатор модуля unsigned not_used); // int InReadResetStatus(I7000_SerialPort *, unsigned char addr, //адрес модуля unsigned char crc_enable, //признак вычисления/проверки контрольной суммы unsigned short module_id, //идентификатор модуля unsigned &result); //результат операции /*********** Host Watchdog Commands Set **************************************************/ //---------Широковещательный пакет "HOST Ok", ~** --------- int HostIsOK(I7000_SerialPort *,unsigned char crc_enable); int HostIsOK(I7000_SerialPort *, unsigned char addr, //адрес модуля unsigned char crc_enable, //признак вычисления/проверки контрольной суммы unsigned short module_id, //идентификатор модуля unsigned not_used); // //-------- Read Module Status ------------------------------ int OutReadModuleStatus(I7000_SerialPort *, unsigned char addr, //адрес модуля unsigned char crc_enable, //признак вычисления/проверки контрольной суммы unsigned short module_id, //идентификатор модуля unsigned not_used); // int InReadModuleStatus(I7000_SerialPort *, unsigned char addr, //адрес модуля unsigned char crc_enable, //признак вычисления/проверки контрольной суммы unsigned short module_id, //идентификатор модуля unsigned &result); //результат операции //-------- Reset Module Status ------------------------------ int OutResetModuleStatus(I7000_SerialPort *, unsigned char addr, //адрес модуля unsigned char crc_enable, //признак вычисления/проверки контрольной суммы unsigned short module_id, //идентификатор модуля unsigned not_used); // int InResetModuleStatus(I7000_SerialPort *, unsigned char addr, //адрес модуля unsigned char crc_enable, //признак вычисления/проверки контрольной суммы unsigned short module_id, //идентификатор модуля unsigned &result); //результат операции //-------- Read Watchdog Timeout Value----------------------- int OutReadWatchdogTimeoutValue(I7000_SerialPort *, unsigned char addr, //адрес модуля unsigned char crc_enable, //признак вычисления/проверки контрольной суммы unsigned short module_id, //идентификатор модуля unsigned not_used); // int InReadWatchdogTimeoutValue(I7000_SerialPort *, unsigned char addr, //адрес модуля unsigned char crc_enable, //признак вычисления/проверки контрольной суммы unsigned short module_id, //идентификатор модуля unsigned &result); //результат операции //-------- Set Watchdog Timeout Value----------------------- int OutSetWatchdogTimeoutValue(I7000_SerialPort *, unsigned char addr, //адрес модуля unsigned char crc_enable, //признак вычисления/проверки контрольной суммы unsigned short module_id, //идентификатор модуля unsigned value); // int InSetWatchdogTimeoutValue(I7000_SerialPort *, unsigned char addr, //адрес модуля unsigned char crc_enable, //признак вычисления/проверки контрольной суммы unsigned short module_id, //идентификатор модуля unsigned &result); //результат операции /* protected: private: };*/ //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% #endif //I7000_proto
[ "menshoff@MacBookMenshoff-3.local" ]
menshoff@MacBookMenshoff-3.local
7d212e3f7264ad55ca0cc9eeacf927f74d9a760f
0696a91b447ada7f384356acc1895283941f1ab7
/计蒜客/Out-out-control cars 计算几何 两三角形有速度判相交.cpp
dbdce370ed1658ef9e1a41a3f0f4790af84a347d
[]
no_license
sunhaotian0122/ACM
2b28226c3b4648be71386910ceeb130af97161eb
f24e9db6c1dffe1fe459f04ec6e03a4bb66424a1
refs/heads/master
2021-01-19T23:24:28.785529
2017-11-12T11:02:35
2017-11-12T11:02:35
88,972,559
0
0
null
null
null
null
GB18030
C++
false
false
2,342
cpp
#include <bits/stdc++.h> using namespace std; typedef long long ll; const double eps = 1e-8; const double PI = acos(-1); struct Point{ double x,y; Point(double x=0,double y=0):x(x),y(y){} //向量+ Point operator +(const Point &b)const { return Point(x+b.x,y+b.y); } //向量- Point operator -(const Point &b)const { return Point(x-b.x,y-b.y); } //点积 double operator *(const Point &b)const { return x*b.x + y*b.y; } //叉积 //P^Q>0,P在Q的顺时针方向;<0,P在Q的逆时针方向;=0,P,Q共线,可能同向或反向 double operator ^(const Point &b)const { return x*b.y - b.x*y; } }P1[5],P2[5],V1,V2; typedef Point Vector; //三态函数,判断两个double在eps精度下的大小关系 int dcmp(double x) { if(fabs(x)<eps) return 0; else return x<0?-1:1; } //判断点Q是否在P1和P2的线段上 bool OnSegment(Point P1,Point P2,Point Q) { return dcmp((P1-Q)^(P2-Q))==0&&dcmp((P1-Q)*(P2-Q))<=0; } int main() { int t; scanf("%d",&t); for(int ca=1;ca<=t;ca++) { for(int i=1;i<=3;i++) scanf("%lf %lf",&P1[i].x,&P1[i].y); scanf("%lf %lf",&V1.x,&V1.y); for(int i=1;i<=3;i++) scanf("%lf %lf",&P2[i].x,&P2[i].y); scanf("%lf %lf",&V2.x,&V2.y); //以P1为参考系 Vector V = V2-V1; bool flag = false; for(int k=1;k<=3;k++) { Point P = P2[k]; for(int i=1,j=3;i<=3;j=i++) { Vector S1 = P1[i]-P1[j]; Vector S2 = P-P1[j]; if(dcmp(S1^V)==0) { if(OnSegment(P1[i],P1[j],P)) { flag = true; break; } } else { if(dcmp((S2^S1)/(S1^V))<0) continue; Vector S3; S3.x = -S2.x-(S2^S1)*V.x/(S1^V); S3.y = -S2.y-(S2^S1)*V.y/(S1^V); if(dcmp((S1+S3)*S3)<=0) { flag = true; break; } } } if(flag) break; } if(flag) printf("Case #%d: YES\n",ca); else printf("Case #%d: NO\n",ca); } return 0; }
[ "1056572776@qq.com" ]
1056572776@qq.com
414407c3437dcbb6048adfa5b23b882289e4fa5c
d640d8890bab87a85c1b29cd8a6131196582031e
/WorldEditor/src/events.h
072a1cfee168121df316a0d964defa8e12164cef
[]
no_license
sjsimmo/PlatformerGame
f8a528f842779daee0e176b4acdfcf3b53a00152
a9cb9237a237d3ae761296459d9c5968349d9f3f
refs/heads/master
2023-01-23T11:05:46.718942
2020-11-29T02:42:09
2020-11-29T02:42:09
289,417,321
0
0
null
null
null
null
UTF-8
C++
false
false
591
h
#ifndef EVENTS_H #define EVENTS_H #include <SDL.h> class settings; class events { private: SDL_Event event; public: void manage(settings &Settings); //Control events bool quit_pressed = false; //Keyboard events bool s_pressed = false; bool left_pressed = false; bool right_pressed = false; bool up_pressed = false; bool down_pressed = false; int active_layer = 1; //Mouse events bool mouse_left_held = false; bool mouse_right_held = false; int mouse_x = 0; int mouse_y = 0; unsigned char scroll = 0; }; #endif
[ "sjsimmo123@gmail.com" ]
sjsimmo123@gmail.com
94059eeeb10d8b87fdd3b0af554859f0a0eb4312
86e57b906be05a581284cb0428d1da04e86d7b70
/Collector/CallStack_Win32.h
e5d700326ce1eb56e388819c55fade62ceb17599
[ "MIT", "BSD-2-Clause" ]
permissive
dakahler/alloclave
19861f96d9adc625932ef4cbd8cd513a88c1a61a
5f14f2341a9ec336782a4da1cdfda3438d703315
refs/heads/master
2021-01-23T19:13:01.055898
2016-01-30T22:29:32
2016-01-30T22:29:32
50,745,985
0
0
null
null
null
null
UTF-8
C++
false
false
343
h
#ifndef _ALLOCLAVE_CALLSTACK_WIN32_H #define _ALLOCLAVE_CALLSTACK_WIN32_H #include "CallStack.h" namespace Alloclave { // Win32-specific specialization of stack walking class CallStack_Win32 : public CallStack { public: CallStack_Win32(); virtual void Rebuild(); }; }; #endif // _ALLOCLAVE_CALLSTACK_WIN32_H
[ "dakahler@gmail.com" ]
dakahler@gmail.com
907add9ef47b7b96f155e8b2f66ef8a6e78999c7
4f7c53c128328f294e9b67a4eb00b72c459692e6
/app/Main/MainTabPurchaseItemController.cpp
f5be0551f30daab636fd2dabf7070dab28ed08dc
[]
no_license
milczarekIT/agila
a94d59c1acfe171eb361be67acda1c5babc69df6
ec0ddf53dfa54aaa21d48b5e7f334aabcba5227e
refs/heads/master
2021-01-10T06:39:56.117202
2013-08-24T20:15:22
2013-08-24T20:15:22
46,000,158
1
1
null
null
null
null
UTF-8
C++
false
false
8,997
cpp
#include "MainTabPurchaseItemController.h" MainTabPurchaseItemController::MainTabPurchaseItemController() { view = new MainTabPurchaseItem(this); purchaseInvoiceService = new PurchaseInvoiceService(); fzkService = new DocumentFZKService(); nkService = new DocumentNKService(); initModel(); initFilters(); initSelectingColumnVisibility(); restoreTableState(); } MainTabPurchaseItemController::~MainTabPurchaseItemController() { saveTableState(); delete documentTVModel; delete purchaseInvoiceService; delete fzkService; delete nkService; } MainTabItem *MainTabPurchaseItemController::getView() { return view; } void MainTabPurchaseItemController::addDocument(const int index) { switch(index) { case 0:{ dialogDocumentNKAdd();break; } case 1:{ dialogDocumentRRAdd();break; } case 2:{ dialogDocumentFZKAdd();break; } case 3:{ dialogDocumentFZAdd();break; } } } void MainTabPurchaseItemController::dialogDocumentFZAdd() { PurchaseInvoiceController *controller = new PurchaseInvoiceController(this,"FZ",0); controller->exec(); documentTVModel->getDocuments(); delete controller; } void MainTabPurchaseItemController::dialogDocumentRRAdd() { DocumentRRController dialog(this, "RR",0); dialog.exec(); documentTVModel->getDocuments(); } void MainTabPurchaseItemController::dialogDocumentFZKAdd() { DocumentFZKController dialog(this,0); dialog.exec(); documentTVModel->getDocuments(); } void MainTabPurchaseItemController::dialogDocumentNKAdd() { DocumentNKController *controller = new DocumentNKController(this); controller->exec(); documentTVModel->getDocuments(); delete controller; } void MainTabPurchaseItemController::removeDocument() { bool storeUpdate; MessageBox *msgBox; if(ApplicationManager::getInstance()->containsModule(ModuleManager::Warehouses)) { msgBox= new MessageBox(); msgBox->setText("Cofnąć skutek magazynowy?"); msgBox->addButton("Tak",QMessageBox::AcceptRole); msgBox->addButton("Nie",QMessageBox::RejectRole); storeUpdate = false; } if(view->getTableView()->getSymbol().contains("RR")||view->getTableView()->getSymbol().contains("FZ")) { if(purchaseInvoiceService->getPurchaseInvoice(view->getTableView()->getSymbol()).getStoreResult()) { if(ApplicationManager::getInstance()->containsModule(ModuleManager::Warehouses)) { if(msgBox->exec()==QMessageBox::AcceptRole) storeUpdate=true; } } purchaseInvoiceService->removePurchaseInvoice(view->getTableView()->getSymbol(),storeUpdate); documentTVModel->getDocuments(); } else if(view->getTableView()->getSymbol().contains("FZK")) { if(fzkService->getDocumentFZK(view->getTableView()->getSymbol()).getStoreResult()) { if(ApplicationManager::getInstance()->containsModule(ModuleManager::Warehouses)) { if(msgBox->exec()==QMessageBox::AcceptRole) storeUpdate=true; } } fzkService->removeDocumentFZK(view->getTableView()->getSymbol(),storeUpdate); documentTVModel->getDocuments(); } delete msgBox; } void MainTabPurchaseItemController::issuedFZK() { DocumentFZKController dialog(this,0); dialog.setFirst(true); dialog.insertInvoiceData(purchaseInvoiceService->getPurchaseInvoice(view->getTableView()->getSymbol())); dialog.exec(); documentTVModel->getDocuments(); } void MainTabPurchaseItemController::issuedKW() { CashDocumentController dialog("KW",false,this); dialog.insertInvoiceData(purchaseInvoiceService->getPurchaseInvoice(view->getTableView()->getSymbol())); dialog.exec(); emit issuedDocKW(); } void MainTabPurchaseItemController::changeDisabledMenuActions() { if(!(view->getTableView()->getSymbol().section("/",0,0)=="FZ")) { view->getTableView()->getExtendedMenu()->getMenuPurchase()->getActionIssuedFZK()->setDisabled(true); view->getTableView()->getExtendedMenu()->getMenuPurchase()->getActionIssuedKW()->setDisabled(true); } else { view->getTableView()->getExtendedMenu()->getMenuPurchase()->getActionIssuedFZK()->setDisabled(false); view->getTableView()->getExtendedMenu()->getMenuPurchase()->getActionIssuedKW()->setDisabled(false); } } void MainTabPurchaseItemController::dialogDocumentEdit() { if(view->getTableView()->getSymbol() == "") { MessageBox *messageBox = new MessageBox(); messageBox->createInfoBox("Zaznacz dokument do edycji"); delete messageBox; } else if(view->getTableView()->getSymbol().contains("RR")) { DocumentRRController dialog(this,"RR",1); dialog.exec(view->getTableView()->getSymbol()); documentTVModel->getDocuments(); } else if(view->getTableView()->getSymbol().contains("NK")) { DocumentNKController dialog(this); dialog.exec(view->getTableView()->getSymbol()); documentTVModel->getDocuments(); } else if(view->getTableView()->getSymbol().section("/",0,0)=="FZ") { PurchaseInvoiceController dialog(this,"FZ",1); dialog.exec(view->getTableView()->getSymbol()); documentTVModel->getDocuments(); } else if(view->getTableView()->getSymbol().contains("FZK")) { DocumentFZKController dialog(this,1); dialog.exec(view->getTableView()->getSymbol()); documentTVModel->getDocuments(); } } void MainTabPurchaseItemController::initModel() { documentTVModel = new PurchaseDocumentTVModel(); documentTVModel->getDocuments(); view->getTableView()->setPurchaseDocumentModel(documentTVModel); } void MainTabPurchaseItemController::initFilters() { documentTVModel->setFromDateFilter(view->getFilterWidget()->getFromDate()); documentTVModel->setToDateFilter(view->getFilterWidget()->getToDate()); documentTVModel->getDocuments(); } void MainTabPurchaseItemController::restoreTableState() { QByteArray state = tableStateManager->getState("MAIN_TAB_PURCHASE"); view->getTableView()->horizontalHeader()->restoreState(state); view->getTableView()->hideIdColumn(); // ukrywa id view->getTableView()->horizontalHeader()->setSortIndicatorShown(true); // pokazuje sortindicator int columnAtTable = view->getTableView()->horizontalHeader()->sortIndicatorSection(); documentTVModel->sortByColumn(columnAtTable, view->getTableView()->horizontalHeader()->sortIndicatorOrder()); documentTVModel->getDocuments(); } void MainTabPurchaseItemController::saveTableState() { QByteArray state = view->getTableView()->horizontalHeader()->saveState(); QByteArray oldState = tableStateManager->getState("MAIN_TAB_PURCHASE"); if(state != oldState) tableStateManager->saveState("MAIN_TAB_PURCHASE", state); } void MainTabPurchaseItemController::changeColumnVisiblity(QList<int> visibleColumns) { for(int column = 0; column < view->getTableView()->model()->columnCount(); column++) { if(visibleColumns.contains(column)) view->getTableView()->setColumnHidden(column, false); else view->getTableView()->setColumnHidden(column, true); } } void MainTabPurchaseItemController::printDocument() { PrintPurchaseDocumentController *pc = new PrintPurchaseDocumentController(view->getTableView()->getSymbol()); if(view->getTableView()->getSymbol() == "") { MessageBox *messageBox = new MessageBox(); messageBox->createInfoBox("Zaznacz dokument do druku"); delete messageBox; } else if(view->getTableView()->getSymbol().contains("FZK")) { DocumentFZK doc = fzkService->getDocumentFZK(view->getTableView()->getSymbol()); pc->print(&doc); } else if(view->getTableView()->getSymbol().contains("NK")) { DocumentNK doc = nkService->getDocumentNK(view->getTableView()->getSymbol()); pc->print(&doc); } else if(view->getTableView()->getSymbol().contains("RR") || view->getTableView()->getSymbol().contains("FZ")) { PurchaseInvoice doc = purchaseInvoiceService->getPurchaseInvoice(view->getTableView()->getSymbol()); pc->print(&doc); } delete pc; } void MainTabPurchaseItemController::initSelectingColumnVisibility() { selectColumnsDialog = new SelectVisibleColumns(view->getTableView(), this); connect(selectColumnsDialog, SIGNAL(selectedColumnsChanged(QList<int>)), this, SLOT(changeColumnVisiblity(QList<int>))); } void MainTabPurchaseItemController::sortByColumn(int column) { documentTVModel->sortByColumn(column, view->getTableView()->horizontalHeader()->sortIndicatorOrder()); } ModuleManager::Module MainTabPurchaseItemController::module() { return ModuleManager::Purchase; }
[ "milczarek@bluebraces.com" ]
milczarek@bluebraces.com
60b8ed0dcb99b5614837f083b19b7c15e059aa63
c46b55c0ec5120d8ff617e0a5cd2363fa73f66fa
/All Practice/pracloop-15.cpp
e988fc3e13b723e8c836bc5d84e3c442d8e42f67
[]
no_license
Nasir53/Practice-Programming-in-C
b382c8da07fb661b5d671245f636f9bfa3a75fa6
a4fb6dc6fd7d446f0c008e8370e87e19e7681b35
refs/heads/master
2020-03-19T05:30:57.687015
2018-06-05T18:44:15
2018-06-05T18:44:15
135,940,072
2
0
null
null
null
null
UTF-8
C++
false
false
167
cpp
#include<stdio.h> #include<conio.h> int main() { int i,j,sum=0; for(i=1,j=1;j<=100;i++) { sum=sum+j; j=j+i; } printf("sum is:%d",sum); getch(); }
[ "mahrajukhan@gmail.com" ]
mahrajukhan@gmail.com
f16624b42c9a1c507e096fc6c410e2a376204bf3
5bccf2d2118008c0af6a51a92a042e967e4f2abe
/Support/Modules/GSRoot/StartupManager.hpp
68abe779333e4791707182db95c5da915755db67
[ "Apache-2.0" ]
permissive
graphisoft-python/DGLib
fa42fadebedcd8daaddde1e6173bd8c33545041d
66d8717eb4422b968444614ff1c0c6c1bf50d080
refs/heads/master
2020-06-13T21:38:18.089834
2020-06-12T07:27:54
2020-06-12T07:27:54
194,795,808
3
0
Apache-2.0
2020-06-12T07:27:55
2019-07-02T05:45:00
C++
UTF-8
C++
false
false
1,434
hpp
// ***************************************************************************** // // Declaration of StartupManager class // // Module: GSRoot // Namespace: GS // Contact person: SN // // ***************************************************************************** #ifndef GS_STARTUPMANAGER_HPP #define GS_STARTUPMANAGER_HPP #pragma once // --- Includes ---------------------------------------------------------------- #include "PagedArray.hpp" #include "Singleton.hpp" #include "StartupListener.hpp" // --- StartupManager class ---------------------------------------------------- namespace GS { class GSROOT_DLL_EXPORT StartupManager { // Friend classes: friend class StaticInstantiationHelper<StartupManager>; // Construction / destruction: private: StartupManager (); StartupManager (const StartupManager&); // Disabled // Operator overloading: private: const StartupManager& operator = (const StartupManager&); // Disabled // Operations: public: USize GetAttachedStartupListeners (PagedArray<StartupListener*>& startupListeners) const; bool IsStartupListenerAttached (StartupListener* startupListener) const; void AttachStartupListener (StartupListener* startupListener); bool DetachStartupListener (StartupListener* startupListener); void DetachStartupListeners (); // Static operations: public: static StartupManager& GetInstance (); }; } #endif // GS_STARTUPMANAGER_HPP
[ "445212619@qqcom" ]
445212619@qqcom
3d75aeae2cbfb2865d3e7c4ba3a850064bfc3674
94cad258e538c567d46cf75ac4c289a3f6341bd6
/database_design/Bplus.cpp
6e6b73df1b5faacbc322dfb57242c75704da17d1
[]
no_license
XuBaozhao/database_create
ee047ba59ba258e063b9d6e9d28140b750e3a414
a0580937579f8f87f9444b0d05a80cb03d005e5f
refs/heads/master
2020-04-14T19:11:58.556985
2019-01-04T02:45:56
2019-01-04T02:45:56
164,048,930
0
0
null
null
null
null
GB18030
C++
false
false
3,799
cpp
#include <cstdlib> #include <iostream> #include <fstream> #include <string> #include <limits.h> using namespace std; // 定义B+树的阶数 #define M 4 // B+树结点定义 struct BPlusNode { int amount; // 该结点中已保存的键值个数 long key[M]; // 键值数组 long children[M]; // 子结点位置数组 long father; // 父结点位置 long left; // 同一层中的左结点位置 long right; // 同一层中的右结点位置 bool isactive; // 有效位 bool isleave; // 标志该结点是否叶结点 }; // 函数头定义 bool findkey (long key, long &position); // 查找包含给定键值的结点位置 bool insertkey (long key, long position); // 插入一个新键值 bool deletekey (long key, long position); // 删除给定的键值 void printkey (long mode); // 按照给定模式输出B+树 // 全局变量 static long pre; // 上一个被访问的结点 static long cur; // 当前指向的结点 static long root; // 根结点位置 static long smallest; // 保存最小关键值的叶结点 static long nodenewposition; // 新插入的结点位置 // 主函数 int main() { BPlusNode node; string command; fstream iofile; long keynumber; long position = -1; // 检测索引文件是否存在,若不存在则创建一个初始化的索引文件,其中包含根结点位置,最小键值位置和一个空结点 fstream infile ("BPlusTreeData.dat", ios::binary|ios::in); if (!infile) { node.amount = 1;//如果不存在,则创建根结点,且阶数M=4 for (int i = 0; i < M; ++i) { node.key[i] = 0; node.children[i] = 0; } node.father = 0; node.left = 0; node.right = 0; node.isactive = true; node.isleave = true; root = 8;//root为什么=8? smallest = 8; fstream outfile ("BPlusTreeData.dat", ios::binary|ios::out);//输出文件BPlusTreeData.dat outfile.seekp(0, ios::beg);//指针移到begin处,文件开头 outfile.write((char *)&root, sizeof(long));//输出根结点 outfile.write((char *)&smallest, sizeof(long));//输出最小关键字 outfile.write((char *)&node, sizeof(BPlusNode));//输出头指针? outfile.close(); } infile.close(); // 循环获取命令行,执行给定的命令 while (true) { cin >> command >> keynumber; // 插入一个新的键值,该值不能与已有关键值重复 if(command=="insert") { if (findkey(keynumber, position)) { cout << keynumber << " is already in this B+ tree" << endl; } else if (insertkey(keynumber, position)) { cout << "Successful inserted in ms" << endl; } else cout << "Action falled" << endl; } if(command=="delete"){ // 删除给定的键值 if (deletekey(keynumber, position)) cout << "Successful deleted" << endl;} if(command=="show") // 按照指定模式输出B+数 // 模式“1”输出整棵树结构 // 模式“2”按照从小到大的顺序输出所有键值 {printkey(keynumber);} // case 't': // testBtree(keynumber); // break; if(command=="exit") {return 0;} else cout << "Please make sure the command is correct" << endl; //continue; } }
[ "noreply@github.com" ]
XuBaozhao.noreply@github.com
c2090ce7e3e430fc65ef49fc06a9e37f71e32925
94a93e269c97a2dbc847dda05e3daab333787b58
/figura.cpp
39d7e47a51241e6625c25fccd4865b6474b8edd5
[]
no_license
PatrykGregorczyk/projekt
dd95ed4c560aaf87edf04eed35140715adfd8a9f
00fa80e7193ccfe56700f9ecb86e861183e17180
refs/heads/master
2020-06-15T13:01:49.164004
2017-01-19T12:51:32
2017-01-19T12:51:32
75,291,689
0
0
null
null
null
null
UTF-8
C++
false
false
13,655
cpp
#include "menu.hpp" // Wypelnia tablice bialymi znakami void czyszczenie(char **S) { // zastepuje kazdy element tablicy spacja for(int j = Y; j >= 0; j--) { for(int i = 0; i <= X; i++) { S[i][j] = ' '; } } } void wypiszTablice(char **S) { clear(); // czysci konsole // [04][14][24][34][44] for(int j = Y; j >= 0; j--) { // [03][13][23][33][43] for(int i = 0; i <= X; i++) { // [02][12][22][32][42] printw("%c", S[i][j]); // [01][11][21][31][41] } // x[00][10][20][30][40] } // y } // Sprawdza czy na granicy ekranu znajduje znak wybrany przez uzytkownika, wtedy zwraca blad (true) bool sprawdzGranice(obrotFigury granica, int p, Figura* F) { int a = 0; if(granica == lewo || granica == prawo) { if(granica == lewo) { a = 0; } else if(granica == prawo) { a = X; } for(int i = 0; i <= Y; i++) { if(F->S[a+p][i] == F->znak) { return true; } } } else if (granica == dol || granica == gora) { if(granica == dol) { a = 0; } else if(granica == gora) { a = Y; } for(int i = 0; i <= X; i++) { if(F->S[i][a+p] == F->znak) { return true; } } } } // wypisuje na ekranie tablice void rysuj(Figura* F) { wypiszTablice(F->S); int klawisz = getch(); switch(klawisz) { case 27: { // klawisz Esc F->stan = false; break; } case 106: { // klawisz [j] if(F->wzor == A) { F->wzor = V; } else if(F->wzor == V) { F->wzor = T; } else if(F->wzor == T) { F->wzor = M; } else if(F->wzor == M) { F->wzor = L; } else if(F->wzor == L) { F->wzor = H; } else if(F->wzor == H) { F->wzor = A; } break; } case 107: { // klawisz [k] if(F->obrot == gora) { if(!sprawdzGranice(dol, F->rozmiar/2-1, F) && !sprawdzGranice(gora, -F->rozmiar/2+1, F) && F->rozmiar < 12) { F->obrot = lewo; } else if(F->rozmiar%2) { if(!sprawdzGranice(dol, 0, F)) { F->obrot = dol; } } else { F->obrot = dol; } } else if(F->obrot == lewo) { if(!sprawdzGranice(lewo, F->rozmiar/2-1, F) && !sprawdzGranice(prawo, -F->rozmiar/2+1, F)) { F->obrot = dol; } } else if(F->obrot == dol) { if(!sprawdzGranice(dol, F->rozmiar/2-1, F) && !sprawdzGranice(gora, -F->rozmiar/2+1, F) && F->rozmiar < 12) { F->obrot = prawo; } else if(F->rozmiar%2) { if(!sprawdzGranice(gora, 0, F)) { F->obrot = gora; } } else { F->obrot = gora; } } else if(F->obrot == prawo) { if(!sprawdzGranice(lewo, F->rozmiar/2-1, F) && !sprawdzGranice(prawo, -F->rozmiar/2+1, F)) { F->obrot = gora; } } break; } case 108: { // klawisz [l] F->znak--; if(F->znak < 33) { F->znak = 126; } break; } case 105: { // klawisz [i] if(F->wzor == A) { F->wzor = H; } else if(F->wzor == H) { F->wzor = L; } else if(F->wzor == L) { F->wzor = M; } else if(F->wzor == M) { F->wzor = T; } else if(F->wzor == T) { F->wzor = V; } else if(F->wzor == V) { F->wzor = A; } break; } case 111: { // klawisz [o] if(F->obrot == gora) { if(!sprawdzGranice(dol, F->rozmiar/2-1, F) && !sprawdzGranice(gora, -F->rozmiar/2+1, F) && F->rozmiar < 12) { F->obrot = prawo; } else if(F->rozmiar%2) { if(!sprawdzGranice(dol, 0, F)) { F->obrot = dol; } } else { F->obrot = dol; } } else if(F->obrot == prawo) { if(!sprawdzGranice(lewo, F->rozmiar/2-1, F) && !sprawdzGranice(prawo, -F->rozmiar/2+1, F)) { F->obrot = dol; } } else if(F->obrot == dol) { if(!sprawdzGranice(dol, F->rozmiar/2-1, F) && !sprawdzGranice(gora, -F->rozmiar/2+1, F) && F->rozmiar <= 11) { F->obrot = lewo; } else if(F->rozmiar%2) { if(!sprawdzGranice(gora, 0, F)) { F->obrot = gora; } } else { F->obrot = gora; } } else if(F->obrot == lewo) { if(!sprawdzGranice(lewo, F->rozmiar/2-1, F) && !sprawdzGranice(prawo, -F->rozmiar/2+1, F)) { F->obrot = gora; } } break; } case 112: { // klawisz [p] F->znak++; if(F->znak > 126) { F->znak = 33; } break; } case 43: { // klawisz [+] if(!sprawdzGranice(dol, 0, F) && !sprawdzGranice(gora, 0, F) && !sprawdzGranice(lewo, 0, F) && !sprawdzGranice(prawo, 0, F)) { F->rozmiar++; } break; } case 45: { // klawisz [-] if(F->rozmiar > 0) { F->rozmiar--; } break; } case 258: { // strzalka w dol if(!sprawdzGranice(dol, 0, F)) { F->y--; } break; } case 259: { // strzalka w gore if(!sprawdzGranice(gora, 0, F)) { F->y++; } break; } case 260: { // strzalka w lewo if(!sprawdzGranice(lewo, 0, F)) { F->x--; } break; } case 261: { // strzalka w prawo if(!sprawdzGranice(prawo, 0, F)) { F->x++; } break; } default: { // domyslnie ustawia wcisniety klawisz jako znak rysowania figury F->znak = klawisz; } } } // wypelnia tablice znakami wg intrukcji void ustawieniaFigury(Figura* F) { int a = 0; int b = 0; int m = 0; int n = 0; int g = 0; int r = F->rozmiar; switch(F->obrot) { case dol: { a = F->x-r; // a=x+m*rozmiar; b = F->y+(r/2); // b=y+n*rozmiar; m = (-1); n = 1; g = F->x; break; } case gora: { a = F->x+r; // a=x+m*rozmiar; b = F->y-(r/2); // b=y+n*rozmiar; m = 1; n = (-1); g = F->x; break; } case lewo: { a = F->y-r; // a=y+m*rozmiar; b = F->x+(r/2); // b=x+n*rozmiar; m = (-1); n = 1; g = F->y; break; } case prawo: { a = F->y+r; // a=y+m*rozmiar; b = F->x-(r/2); // b=x+n*rozmiar; m = 1; n = (-1); g = F->y; break; } } switch(F->wzor) { case A: { while(a != g -m*r-m) { if(F->obrot == dol || F->obrot == gora) { F->S[a][b] = F->znak; if(a >= g-(r/2) && a <= g+(r/2)) { F->S[a][F->y] = F->znak; } } else { F->S[b][a] = F->znak; if(a >= g-(r/2) && a <= g+(r/2)) { F->S[F->x][a] = F->znak; } } a -= m; b -= n; if(a == g) { n = m; } } break; } case H: { int h; if(F->obrot == lewo || F->obrot == prawo) { h = F->x; } else { h = F->y; } while(b != h+m*(r/2)+m) { if(F->obrot == dol || F->obrot == gora) { if(r%2) { F->S[g-r][b+m] = F->znak; F->S[g+r][b+m] = F->znak; } F->S[g-r][b] = F->znak; F->S[g+r][b] = F->znak; } else if(F->obrot == lewo || F->obrot == prawo) { if(r%2) { F->S[b+m][g-r] = F->znak; F->S[b+m][g+r] = F->znak; } F->S[b][g-r] = F->znak; F->S[b][g+r] = F->znak; } b+=m; } while(a != g-m*r) { if(F->obrot == dol || F->obrot == gora) { F->S[a][F->y] = F->znak; } else if(F->obrot == lewo || F->obrot == prawo) { F->S[F->x][a] = F->znak; } a -= m; } break; } case L: { while(a != g-m*r-m) { if(F->obrot == dol || F->obrot == gora) { F->S[a][F->y-m*r/2] = F->znak; } else if(F->obrot == lewo || F->obrot == prawo) { F->S[F->x-m*r/2][a] = F->znak; } a -= m; } if(g == F->x) { g = F->y; } else if(g == F->y) { g = F->x; } while(b != g+m*r/2+m) { if(F->obrot == dol || F->obrot == gora) { if(r%2) { F->S[F->x-m*r][b+m] = F->znak; } F->S[F->x-m*r][b] = F->znak; } else if(F->obrot == lewo || F->obrot == prawo) { if(r%2) { F->S[b+m][F->y+m*r] = F->znak; } F->S[b][F->y+m*r]=F->znak; } b += m; } break; } case M: { if(F->obrot == gora || F->obrot == dol) { for(int i = 0; i <= r; i++) { F->S[g-i][b] = F->znak; F->S[g+i][b] = F->znak; F->S[g-r][b] = F->znak; F->S[g+r][b] = F->znak; b += m; } } else { for(int i = 0; i <= r; i++) { F->S[b][g-i] = F->znak; F->S[b][g+i] = F->znak; F->S[b][g-r] = F->znak; F->S[b][g+r] = F->znak; b += m; } } break; } case T: { while(a != g-m*r-m) { if(F->obrot == dol || F->obrot == gora) { if(r%2) { F->S[a][F->y+m*r/2+m] = F->znak; } else { F->S[a][F->y+m*r/2] = F->znak; } } else if(F->obrot == lewo || F->obrot==prawo) { if(r%2) { F->S[F->x+m*r/2+m][a] = F->znak; } else { F->S[F->x+m*r/2][a] = F->znak; } } a -= m; } if(g == F->x) { g = F->y; } else if(g == F->y) { g = F->x; } while(b != g+m*r/2+m) { if(F->obrot == dol || F->obrot == gora) { F->S[F->x][b] = F->znak; } else if(F->obrot == lewo || F->obrot == prawo) { F->S[b][F->y] = F->znak; } b += m; } break; } case V: { if(F->obrot == gora || F->obrot == dol) { for(int i = 0; i <= r; i++) { F->S[g-i][b] = F->znak; F->S[g+i][b] = F->znak; b += m; } } else { for(int i = 0; i <= r; i++) { F->S[b][g-i] = F->znak; F->S[b][g+i] = F->znak; b += m; } } break; } } }
[ "noreply@github.com" ]
PatrykGregorczyk.noreply@github.com
086ebff3d118f35efd2940c37c1085db4e20e8df
f553f5e7755f92de755e7f57c2eacf584d4c5cbe
/QT_Creator/Creador de figuras/square.h
9610206c4bc705c42dd1811f7e889468db94e7de
[]
no_license
Eduardojav/LP2
83b1651663d075e8039d5441ee7767002d7fe709
150b093a6d30bd363c240d0a91c520ac00c0300e
refs/heads/master
2020-05-01T14:58:55.950015
2019-06-20T19:02:01
2019-06-20T19:02:01
177,534,518
0
1
null
null
null
null
UTF-8
C++
false
false
479
h
#ifndef SQUARE_H #define SQUARE_H #include<iostream> #include<QMainWindow> #include<figure.h> #include<QColor> #include<QPainter> #include<QPixmap> #include<QPen> using namespace std; class square:public figure{ private: int x,y,h,w; public: square(int _x=0,int _y=0, int _h=0){ x=_x; y=_y; h=_h; } ~square(){} void draw(QPainter * painter); }; #endif // SQUARE_H
[ "noreply@github.com" ]
Eduardojav.noreply@github.com
abda2b050ecebb053ab3c1ed0902b8b9bc6500c8
a743e8b7acd8f1355431758e5050f15e73481106
/sketch_mar25a.ino
59005591db29f63ec064cfa84dd8f351397bd3c9
[]
no_license
el-gringo94/piezo-knock-detector
c0fcc9fbd2dd8f9a46ed50c8772da55e7715e07e
aa0825c35d85b78fb07861a419e8c475346a536b
refs/heads/master
2022-04-15T20:28:39.130441
2020-03-26T20:27:38
2020-03-26T20:27:38
250,364,459
0
0
null
null
null
null
UTF-8
C++
false
false
239
ino
// these constants won't change int wert = 0; void setup() { Serial.begin(9600); } void loop() { wert = analogRead(A0); // Serial.println(wert); if (wert >= 1) { Serial.println("Klopf Klopf"); Serial.println(wert); } }
[ "noreply@github.com" ]
el-gringo94.noreply@github.com
a61b684d493de069d3a9c8c9c021c924a75b94d3
6d86bfbca4c05dc5d5b40b54741d5fdca5912df7
/mpr/myImageLoader.cpp
a77bc61178c2893078d0bd31df23ea3f547d00d1
[]
no_license
geronimo-lisboa/estudo-mpr
cc59d27f3d149d97315d9e73e16629e0e88816b2
af3cf2758917a091c16e9f5896fc599383a76a2b
refs/heads/master
2021-07-04T22:36:37.407432
2017-09-25T13:31:30
2017-09-25T13:31:30
103,576,213
0
0
null
null
null
null
UTF-8
C++
false
false
2,478
cpp
#ifndef __myImageLoader_hxx #define __myImageLoader_hxx #include "myImageLoader.h" #include "itkObjectFactory.h" #include "itkImageRegionIterator.h" #include "itkImageRegionConstIterator.h" #include <itkImageFileReader.h> #include <itkImage.h> #include <itkRGBAPixel.h> #include <itkRGBToLuminanceImageFilter.h> #include <itkIntensityWindowingImageFilter.h> namespace itk { template< class TImage> void myImageLoader< TImage>::GenerateData() { if (m_FileName == "") throw itk::ExceptionObject("Must inform the filename"); //Carga do arquivo typedef unsigned char ComponentType; typedef itk::RGBPixel< ComponentType > InputPixelType; typedef itk::Image< InputPixelType, 2 > InputImageType; typedef itk::ImageFileReader< InputImageType > ReaderType; ReaderType::Pointer reader = ReaderType::New(); reader->SetFileName(m_FileName.c_str()); typedef itk::RGBToLuminanceImageFilter< InputImageType, typename TImage > RGBToLuminanceType; RGBToLuminanceType::Pointer filter = RGBToLuminanceType::New(); filter->SetInput(reader->GetOutput()); filter->Update(); typedef itk::IntensityWindowingImageFilter<typename TImage, typename TImage> IntensityFilter; IntensityFilter::Pointer normalizer = IntensityFilter::New(); normalizer->SetInput(filter->GetOutput()); normalizer->SetWindowMinimum(0); normalizer->SetWindowMaximum(255.0); normalizer->SetOutputMinimum(0); normalizer->SetOutputMaximum(1.0); normalizer->Update(); typename TImage::Pointer output = this->GetOutput(); typename TImage::RegionType region; typename TImage::IndexType start; start[0] = 0; start[1] = 0; if (output->ImageDimension == 3)start[1] = 0; typename TImage::SizeType size; size[0] = filter->GetOutput()->GetLargestPossibleRegion().GetSize()[0]; size[1] = filter->GetOutput()->GetLargestPossibleRegion().GetSize()[1]; if (output->ImageDimension==3) size[2] = filter->GetOutput()->GetLargestPossibleRegion().GetSize()[2]; region.SetSize(size); region.SetIndex(start); output->SetRegions(region); output->Allocate(); itk::ImageRegionIterator<TImage> outputIterator(output, output->GetLargestPossibleRegion()); itk::ImageRegionIterator<TImage> inputIterator(normalizer->GetOutput(), normalizer->GetOutput()->GetLargestPossibleRegion()); while (!outputIterator.IsAtEnd()) { outputIterator.Set(inputIterator.Get()); ++inputIterator; ++outputIterator; } } }// end namespace #endif
[ "luciano.geronimo.fnord@gmail.com" ]
luciano.geronimo.fnord@gmail.com
52539094a4143d21618d9f57da6eb529fe6ee209
298e9823887ae4ae62592163b83acecfe22c34e1
/Ch08/Postfix.cpp
3464488d52a0777debca5ef1b9a9407a60c16e91
[]
no_license
KarimEnien/cpp_templates
54ebf047541dba79528b7708bc30642d9bf27c65
d9a493131234b166e0be2db0bfbdf4c5eed1bd9b
refs/heads/master
2021-04-25T12:32:55.277416
2018-03-07T08:41:38
2018-03-07T08:41:38
124,051,896
2
0
null
null
null
null
UTF-8
C++
false
false
1,653
cpp
// postfix.cpp // overloaded ++ operator in both prefix and postfix #include <iostream> using namespace std; //////////////////////////////////////////////////////////////// class Counter { private: unsigned int count; //count public: Counter() : count(0) //constructor no args { } Counter(int c) : count(c) //constructor, one arg { } unsigned int get_count() const //return count { return count; } Counter operator ++ () //increment count (prefix) { //increment count, then return return Counter(++count); //an unnamed temporary object } //initialized to this count Counter operator ++ (int) //increment count (postfix) { //return an unnamed temporary return Counter(count++); //object initialized to this } //count, then increment count }; //////////////////////////////////////////////////////////////// int main() { Counter c1, c2; //c1=0, c2=0 cout << "\nc1=" << c1.get_count(); //display cout << "\nc2=" << c2.get_count(); ++c1; //c1=1 c2 = ++c1; //c1=2, c2=2 (prefix) cout << "\nc1=" << c1.get_count(); //display cout << "\nc2=" << c2.get_count(); c2 = c1++; //c1=3, c2=2 (postfix) cout << "\nc1=" << c1.get_count(); //display again cout << "\nc2=" << c2.get_count() << endl; return 0; }
[ "noreply@github.com" ]
KarimEnien.noreply@github.com
165541672f137c69f7fdd2df6ae79816018ec58b
493ac26ce835200f4844e78d8319156eae5b21f4
/flow_simulation/ideal_flow/0.13/p
29ddd5da401058c13b191c56f3c380eca196bb0e
[]
no_license
mohan-padmanabha/worm_project
46f65090b06a2659a49b77cbde3844410c978954
7a39f9384034e381d5f71191122457a740de3ff0
refs/heads/master
2022-12-14T14:41:21.237400
2020-08-21T13:33:10
2020-08-21T13:33:10
289,277,792
0
0
null
null
null
null
UTF-8
C++
false
false
46,979
/*--------------------------------*- C++ -*----------------------------------*\ | ========= | | | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox | | \\ / O peration | Version: v1912 | | \\ / A nd | Website: www.openfoam.com | | \\/ M anipulation | | \*---------------------------------------------------------------------------*/ FoamFile { version 2.0; format ascii; class volScalarField; location "0.13"; object p; } // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // dimensions [0 2 -2 0 0 0 0]; internalField nonuniform List<scalar> 5794 ( 97.3144 97.1167 80.0824 99.7371 90.3562 96.8446 97.6156 98.6481 89.685 91.7952 121.006 97.2701 98.0566 94.7155 94.288 96.8966 43.0947 98.3337 94.7816 97.7456 86.5271 97.4254 93.8277 96.0922 95.3919 41.4275 44.8736 99.3436 97.0935 92.3706 99.7487 86.6231 102.658 96.2117 95.9253 94.9668 95.2619 97.2584 98.116 92.1701 92.8575 97.1852 103.186 93.52 94.763 102.994 87.6538 99.8332 90.3519 94.6828 97.4694 85.8891 86.2375 93.6717 99.259 103.342 89.144 99.8658 103.898 37.8489 100.581 98.6974 99.7908 85.728 102.671 98.7035 78.7582 92.0516 98.7578 98.7746 86.7571 81.8925 18.9405 97.733 98.3985 99.2842 94.7078 46.6452 93.6771 98.2357 97.1228 98.0159 94.3635 98.3606 97.7847 99.9403 90.4567 102.799 96.9076 92.6133 105.808 93.5242 100.32 100.952 98.6103 87.382 102.653 100.323 93.3419 101.107 75.8523 88.8689 102.621 96.109 95.3423 99.7007 98.6394 119.899 88.4995 94.3793 98.7649 96.4901 66.958 98.5967 98.1597 100.062 96.0256 99.531 100.015 86.5397 99.6298 93.8097 99.6218 99.3426 95.677 113.743 92.2773 96.8207 82.2424 120.631 98.2096 98.5898 90.7017 51.1805 99.8649 93.4875 104.457 98.8064 97.5917 98.3763 96.2193 95.3891 96.2999 96.6168 97.6405 47.9893 99.6329 105.714 90.5712 97.3113 109.318 96.2191 99.7996 97.5315 46.0454 88.505 98.2749 99.6929 102.638 97.8308 93.6733 97.4694 97.9453 95.583 88.185 86.7424 95.9228 98.5176 98.6686 96.1877 91.684 88.8361 94.7931 95.3666 96.3706 95.047 94.4871 96.8192 97.0095 89.3806 98.4023 89.164 99.8929 102.457 98.9011 45.0461 88.3619 102.691 90.8615 88.9705 121.132 86.5848 102.644 99.7999 98.4661 98.0896 97.9781 98.1581 95.2455 100.415 96.4615 86.8659 99.8101 98.8018 87.1691 102.91 98.2554 119.622 79.3407 89.0412 97.6202 94.2594 95.6962 97.7348 95.4146 94.8124 94.472 92.6916 120.281 87.3496 94.425 97.4011 102.587 100.017 104.002 36.6328 81.539 92.3185 92.1553 93.4601 94.3812 94.1903 95.7297 87.5434 97.2232 53.1324 66.9739 103.412 97.506 96.3122 97.0565 117.581 91.4861 97.7546 97.276 98.8803 95.5717 90.164 103.132 100.319 93.4805 98.656 44.1437 98.3088 112.405 81.6837 100.87 105.62 119.935 95.2537 103.797 95.8349 98.0919 98.584 99.3328 98.365 97.5199 109.304 94.6178 102.753 86.7785 99.7662 95.19 85.3288 95.9443 94.1859 93.0508 97.1823 98.0408 97.3408 98.4023 100.064 93.8977 96.987 92.4922 100.533 92.4544 98.5098 100.905 99.7688 94.4725 94.4312 95.1129 94.0388 107.412 46.6666 93.8476 96.7441 94.0364 98.5782 97.8369 74.6788 97.2557 89.146 93.5274 105.805 98.2051 97.9891 102.711 86.9879 99.7444 102.408 89.991 98.5811 95.3452 97.6203 119.754 99.2155 88.7493 97.1459 99.3616 100.019 99.4196 89.7868 97.1387 97.9309 97.8093 97.6694 98.2426 120.792 88.2106 105.013 99.7022 102.685 87.3776 91.3567 92.2502 98.3865 90.5688 102.643 96.4404 96.0325 89.987 94.2191 95.4448 99.9392 102.24 91.0189 85.8056 97.2285 97.8941 48.7868 102.589 87.3883 99.8469 44.1548 95.1687 84.804 97.3566 98.4126 119.802 96.3553 103.648 96.5688 98.5187 91.4922 87.4723 103.118 88.0967 99.85 97.4934 98.6296 91.8116 98.3529 119.45 88.49 103.824 87.1337 99.8097 98.218 96.0652 97.8617 95.7869 95.261 96.6759 96.9688 97.4322 95.784 98.7623 96.1452 98.9491 97.3231 98.6625 98.5711 94.6527 94.282 96.2797 92.4396 92.795 94.5293 96.0566 95.7042 47.1907 98.8904 96.9002 105.793 92.3281 96.6546 98.3823 102.447 99.9632 93.1713 115.785 88.4815 102.781 87.7539 99.7718 99.8456 88.9399 102.533 93.4212 100.267 119.88 96.9403 95.1374 96.4411 97.0676 98.6088 97.6477 97.1796 87.8389 95.6541 97.3836 69.7887 95.1483 97.7504 98.1345 98.5414 95.3647 97.0212 97.4534 95.3686 98.7241 98.3494 97.9233 100.041 98.2424 97.4567 88.6411 91.9862 92.4163 97.7136 74.1788 97.4426 100.394 98.5821 102.367 82.201 98.5353 101.333 97.4518 97.5211 85.9448 98.7954 101.574 120.554 44.4386 89.0382 120.001 95.3601 98.5758 73.5647 114.482 92.271 90.7214 102.855 63.9439 99.2787 96.7206 97.577 86.2022 97.6254 91.981 92.1744 119.666 120.66 93.8946 98.2853 48.1407 97.2791 97.6322 99.4471 99.3298 89.4001 90.9392 98.5273 91.4801 97.8862 97.3373 104.735 85.834 62.608 97.3487 97.7505 97.4304 97.2395 97.1802 105.404 117.26 98.6644 87.8631 98.3047 95.2733 98.5574 98.5468 96.9914 100.293 98.5453 94.0305 46.4639 96.5386 98.2364 89.4051 99.7733 120.002 96.5758 96.9567 84.1702 97.8082 97.296 88.0088 98.5645 44.1778 98.1772 91.9563 84.6393 95.4313 105.073 120.353 105.124 97.316 69.2002 97.6506 93.7955 97.7506 97.1441 95.8501 96.2118 98.5766 96.932 96.039 97.8388 94.2686 95.7275 97.031 96.6804 88.4327 97.2493 97.9339 93.335 23.201 92.0087 108.514 96.0471 94.4792 97.7485 96.3718 79.294 96.9226 98.6243 101.94 87.969 100.39 98.1757 43.0898 92.2723 87.8606 94.3264 96.9836 93.5358 100.52 96.3059 113.588 49.8604 84.0541 103.428 98.614 100.261 93.4001 102.105 98.6524 96.9773 98.9244 100.039 97.5844 94.9253 98.4078 95.0284 98.0963 84.7915 97.2934 102.238 98.2826 99.927 98.574 116.728 47.8507 92.1955 99.2491 97.1937 86.8713 81.6842 93.9942 90.8294 98.4123 98.9754 104.036 117.845 99.1646 99.3679 98.3354 116.234 113.473 119.835 98.5023 96.6856 98.275 92.8168 116.819 98.608 96.8515 97.3729 97.9355 96.3124 98.5613 92.1165 66.6239 95.0727 91.966 99.0739 97.5371 102.6 119.731 93.1263 104.6 99.5718 98.4359 103.663 98.3236 99.2512 97.3006 96.9312 98.2748 99.2133 98.432 104.365 45.708 99.2117 43.5077 97.6492 98.4352 92.0159 97.666 86.35 97.6496 98.5001 100.722 100.796 92.6676 100.39 103.354 92.8134 38.8424 99.7283 98.1838 98.2893 99.836 97.8763 92.9844 96.1905 96.4602 119.386 96.06 97.3274 93.3861 104.721 97.1177 97.9664 97.812 98.5273 84.3818 102.065 73.6034 98.9519 93.0576 82.8844 119.601 97.5619 97.686 94.4723 90.5461 97.6811 98.5859 105.662 93.7151 101.96 98.4278 92.1835 98.228 114.099 105.197 101.62 98.6215 96.8137 115.01 93.3266 96.9201 42.7962 111.11 94.1096 118.277 66.2288 104.895 98.082 83.8521 92.9341 106.431 96.0211 115.322 98.6854 98.8198 70.3357 101.725 111.165 93.5232 82.4017 44.0995 118.802 93.3601 100.348 103.998 99.5206 96.8053 79.9726 95.3216 100.298 92.9209 100.933 89.2442 95.3717 96.8842 96.5885 96.1064 98.5714 98.117 100.095 96.6264 101.261 98.6718 103.407 97.8542 69.4196 100.717 98.4787 100.448 100.89 94.4963 105.845 93.4038 100.2 93.8273 102.366 93.1812 98.3478 92.1766 99.2246 96.5695 96.7104 93.1214 96.8602 119.536 44.7246 87.1409 97.1744 97.7913 100.663 94.903 119.441 100.316 97.0862 97.6772 110.932 101.944 92.2042 99.9801 95.7657 97.576 66.4197 97.3367 57.0038 93.1636 119.759 97.5074 98.1312 96.5774 95.4566 119.594 118.497 103.317 102.811 99.2229 96.8234 97.4017 102.38 83.2729 98.6776 96.2117 102.298 116.538 98.1104 96.9588 90.9954 105.23 52.42 98.5941 96.2806 96.6761 92.2548 92.2967 93.1756 100.328 102.143 94.9959 98.0572 99.387 92.2305 97.5771 39.1107 96.6973 97.9381 85.1523 98.6518 117.754 97.6524 96.8527 98.5369 97.1396 101.034 95.0746 76.0066 98.2572 99.7435 98.5013 99.3366 108.451 113.881 47.2962 84.3352 98.5318 99.2298 101.961 93.1376 96.2279 92.0713 102.607 98.9234 77.997 116.141 96.8086 98.2663 97.6261 94.7383 107.907 96.7089 49.5423 97.1989 98.1212 57.6998 103.023 94.3968 97.3805 98.4299 120.525 100.288 98.7431 98.152 80.3537 110.843 95.47 95.3374 114.386 90.1025 98.416 100.108 83.6188 88.8279 91.1773 97.1706 97.7506 93.0776 98.6167 98.4176 98.4765 96.5099 111.136 98.3274 95.1525 98.6407 92.045 74.8495 97.1811 91.8007 118.499 120.231 60.6174 96.4232 100.425 95.422 98.6504 57.1811 92.1958 88.5063 113.314 100.333 92.5961 98.4704 97.1762 100.226 100.21 90.9068 92.0744 91.2916 96.8534 99.1778 114.728 97.3882 99.3477 102.658 93.5974 100.201 95.5714 105.611 98.2561 96.631 91.5259 98.6024 79.2872 119.765 103.268 95.3731 99.469 69.1465 97.7296 97.4723 79.1945 42.5782 95.6391 92.8738 99.8375 83.258 92.7219 91.0755 98.8999 99.0326 98.3963 98.7906 98.7634 97.3153 98.1391 98.6383 98.6018 99.1987 95.1497 98.5129 95.8677 98.1089 98.6298 103.542 95.5959 93.7566 96.6827 94.0492 98.6688 119.632 97.5058 89.8483 98.9889 86.732 115.866 98.9681 95.3087 97.584 98.1397 95.3565 65.2097 94.6851 83.8233 91.5533 98.5387 95.9627 89.3888 97.5641 104.55 75.22 98.9692 101.904 96.8525 96.8456 98.6472 95.907 99.8445 93.5412 40.1774 101.305 98.3034 98.1994 98.3318 100.458 92.4401 99.6852 105.161 98.6295 97.5435 97.7685 87.1468 95.6199 97.1036 93.5544 97.705 94.839 95.5234 96.7409 98.6392 97.0069 96.8892 91.7614 98.8089 118.01 98.7491 95.3277 94.3514 98.5656 92.1898 97.4323 82.4962 119.667 98.5531 119.209 98.5153 97.3161 119.582 98.9167 90.5037 104.609 98.57 97.4 88.4009 98.5241 85.4977 88.0501 96.6182 97.8698 87.1923 98.4747 98.6778 94.6012 99.1291 98.4772 96.2607 95.5698 94.7561 87.4856 101.806 100.239 99.955 98.1429 98.4741 98.9609 90.0764 97.2884 93.9521 99.5943 98.4577 115.9 98.5417 87.4751 97.4893 113.699 97.6207 84.5837 90.2597 98.6086 96.3312 98.6345 97.5022 82.8736 95.0299 94.9524 95.6145 98.6052 96.1408 98.3882 98.63 86.4814 97.6162 97.0668 85.7473 97.153 120.417 92.4744 46.8579 98.2641 96.3382 98.1987 95.0989 98.1034 99.1765 97.0351 89.6448 94.3838 102.152 82.9636 94.5411 98.6144 97.6752 85.4043 96.6618 91.1462 95.7129 70.8502 83.4487 105.513 105.995 72.461 99.5595 98.8145 90.619 98.4621 98.9995 98.5306 32.3098 95.98 98.5486 96.5595 115.682 117.4 92.3353 96.3581 96.6569 95.2111 95.2559 98.7099 91.2568 97.098 91.4591 97.2031 95.0363 97.1953 98.1242 82.9992 86.2498 96.7303 91.917 97.7113 83.244 97.5453 85.1286 98.9924 98.2977 100.26 101.109 96.632 93.1661 95.2436 100.008 96.7903 94.0781 97.5088 101.255 98.0591 97.6999 96.9968 106.131 95.7052 104.258 98.9211 98.5053 100.812 81.9276 103.575 102.18 98.3501 99.1657 95.2474 105.611 98.5174 98.4775 98.3667 50.3448 98.5605 98.2305 86.2733 96.2712 98.7653 89.9304 92.1364 105.959 97.1839 95.9064 95.2656 101.138 90.6761 97.9037 99.0175 98.4278 98.8992 114.429 119.924 80.9117 95.4748 98.5285 98.4463 99.8244 85.8722 102.678 120.245 100.815 96.037 92.2305 98.622 99.0655 99.6301 95.2494 100.194 99.1441 98.752 99.2656 98.7955 73.0551 95.5688 46.004 97.0337 98.077 105.641 96.261 98.5218 98.5136 94.759 91.2225 98.1465 98.5104 97.7978 97.597 97.2758 85.5291 80.7594 99.187 98.5412 97.4092 88.8216 97.8188 81.7876 84.2552 106.597 94.3937 99.4112 98.2264 97.8437 102.113 94.4444 100.095 97.4595 91.9315 122.259 54.1779 81.2063 90.3166 98.3523 85.8779 98.1706 97.4317 86.0869 97.5685 81.8919 85.1186 96.5157 97.0254 97.8641 98.1377 97.9912 95.2562 96.3526 98.4305 97.6301 104.333 95.9914 119.595 118.011 94.4893 99.1598 80.2536 98.1362 118.969 90.1074 98.9546 98.4438 98.8006 97.5367 97.1972 85.5194 95.7597 90.7177 98.4453 98.3581 93.4228 47.4185 83.8002 44.3635 48.9962 92.689 95.0883 99.2786 94.828 97.446 88.2559 99.5062 98.0445 97.1591 85.7773 102.655 98.1035 100.728 98.3582 100.39 91.3532 91.9989 98.1512 97.2959 120.166 94.3793 99.5277 98.3754 98.1223 97.2717 104.487 97.5849 97.5976 86.1626 98.433 98.9836 92.4217 92.4061 99.2418 95.3716 96.463 122.739 120.47 98.5623 47.5443 118.695 98.3455 84.8212 97.7057 102.065 98.4668 97.71 96.4723 84.7315 10.3158 95.8546 99.8206 90.8457 102.905 49.6197 105.407 84.6023 97.0358 97.795 96.9448 97.3934 84.5164 97.7939 98.0321 96.7024 97.5267 97.2484 98.126 84.8112 97.0652 97.9678 97.4516 84.2956 97.5794 97.009 84.7467 97.9024 96.8881 97.8217 98.1105 97.5791 85.2161 98.7311 97.4052 97.3167 97.1174 85.0077 98.2499 98.0091 97.0648 97.3849 97.0147 97.2583 84.557 97.9157 97.4533 97.2263 98.0593 98.5676 84.6942 97.1769 98.1766 56.3681 98.3788 97.766 94.565 81.877 93.3863 98.205 98.5234 78.2623 98.0048 89.8154 99.4716 47.4374 89.9968 80.4909 91.0051 98.3916 98.4288 98.1341 97.4316 96.8243 95.242 98.1909 79.8176 83.3931 97.812 118.777 93.1771 97.4357 99.7292 100.532 44.9782 97.5423 95.6358 99.2504 102.149 99.1924 93.4084 86.3897 95.1722 110.23 92.6489 88.2814 98.559 98.2937 94.2391 93.2787 11.4793 97.9007 97.784 96.5787 97.3247 95.3111 96.8654 126.193 97.5137 97.9803 97.3303 97.912 84.5704 96.9866 97.2057 97.506 98.0339 97.162 97.3865 84.8076 98.4011 98.0763 84.6905 97.3093 84.7553 98.0086 97.9227 97.1587 97.0153 97.0427 84.7662 97.6172 95.4253 90.0989 120.196 103.881 96.5774 94.1682 94.9851 98.5382 104.687 93.579 92.1257 117.084 96.1957 97.0517 98.2889 96.4738 102.761 92.1135 72.0549 81.2018 97.6439 98.5181 98.7591 87.2617 95.9939 98.8465 83.115 96.7691 98.084 97.8393 97.2552 98.2916 97.0466 95.8551 89.307 98.241 81.4699 98.4883 79.1986 97.0913 98.1276 98.5022 99.4059 98.2441 98.254 97.5074 97.971 80.8391 95.4969 99.5071 71.0791 97.2175 84.7653 79.1832 99.2576 95.4494 93.3019 99.2638 111.228 85.3002 98.7069 97.0187 89.2257 98.3429 95.5102 98.0095 97.5118 97.9881 89.8394 98.6122 95.0851 92.8416 98.1272 97.7564 80.6221 81.7835 92.365 91.7333 86.2468 97.5087 98.1635 88.2607 95.4564 97.8942 99.2334 98.2555 97.2548 98.5201 84.7467 91.701 97.1686 105.531 98.3718 98.9623 92.1768 92.8583 97.0347 98.0523 98.0857 89.4934 95.2044 97.6389 103.372 100.043 92.6669 99.3164 86.6187 108.282 106.809 75.9296 94.827 91.4316 92.4363 97.4552 101.4 80.6234 125.907 97.1416 89.8009 97.2659 105.567 98.286 97.305 100.165 129.926 99.8863 103.093 91.0303 117.937 99.323 98.3434 28.2236 84.5015 87.2522 96.2323 97.9954 97.0395 84.4418 85.5417 97.0354 98.1028 83.1571 99.5254 99.6976 100.328 100.896 99.5802 100.436 99.8618 98.6212 99.4922 99.3523 100.517 100.909 99.4452 100.928 99.2676 99.2873 99.2348 98.5434 98.5486 98.0638 49.3414 98.7243 98.3851 98.4714 98.892 98.179 94.7689 100.723 100.416 97.4881 98.1492 97.9854 98.1684 100.597 97.6104 97.4006 98.4284 99.0336 98.4558 100.163 90.177 78.7435 110.527 103.101 81.6967 97.8172 76.4906 98.1852 96.9244 98.1524 97.6444 97.9053 98.1946 85.3152 99.0785 98.4824 99.0372 98.4691 95.1474 101.157 91.7982 92.5339 88.111 99.3249 98.6503 87.1923 94.0325 102.58 102.226 89.1961 85.9631 97.8875 92.4537 87.9477 102.55 102.535 93.4963 99.4693 102.473 87.5394 101.751 91.58 91.9372 93.4108 86.2176 99.6379 48.1214 93.0914 99.2233 97.7324 91.8348 86.7345 98.1041 99.5432 101.714 102.637 95.7841 48.5024 88.2319 93.5385 87.8874 92.5373 97.3324 95.6011 97.4755 103.354 99.7437 48.4718 95.4089 97.2373 97.3382 88.1572 46.1448 95.4199 130.995 87.694 74.1404 95.0881 96.4234 95.8363 99.8051 102.729 85.6177 87.2917 47.3694 49.4234 81.9469 97.0646 85.9429 75.3529 87.5167 96.04 98.5863 90.6388 97.1316 83.8356 98.1049 120.448 98.5107 75.8999 96.481 99.1314 85.2843 98.004 97.5368 98.1926 77.7043 98.4597 97.3595 97.5437 95.4517 94.6514 94.8735 95.9829 87.4836 86.0135 85.0374 97.8239 97.7153 83.5916 94.5929 98.1485 88.0454 98.2117 99.839 86.0164 102.717 97.7655 99.1912 98.4566 86.9596 98.1456 97.8795 81.3651 97.5869 97.6982 97.6492 83.3034 87.8306 96.5416 47.4061 97.9784 96.2272 97.5165 98.155 88.5842 91.4825 100.637 97.8498 97.6031 97.8777 97.6289 97.5747 87.448 92.0091 98.0363 100.339 98.1152 97.6591 97.918 97.9247 93.817 93.5478 92.9904 95.9071 98.0614 97.7889 97.7086 93.2669 98.4195 97.4376 98.082 84.5674 97.1044 98.224 86.3323 99.8482 102.769 99.2346 98.4121 97.6066 97.9976 98.1901 120.353 88.1001 96.0521 98.5091 98.0315 97.0811 94.123 95.0644 94.3235 98.1197 98.7687 98.2068 47.5087 104.595 95.6741 94.2387 92.979 96.2145 84.9515 97.0851 98.0514 120.174 96.5805 98.8175 93.7988 98.9269 84.9447 97.0417 98.0287 102.862 88.2424 99.8759 119.716 88.7826 97.8213 99.0911 104.184 47.3909 104.145 94.8386 93.627 100.854 101.399 96.5448 97.3383 99.1953 97.2621 97.0991 99.1767 84.6978 97.0589 98.0153 98.9618 102.71 99.1423 119.978 89.644 97.2755 48.2271 51.8205 97.9967 105.215 98.6731 98.3409 101.284 93.7035 96.2438 96.8099 96.7778 97.1818 99.0312 99.2645 91.3725 102.666 99.9061 115.273 97.1856 99.2212 99.1292 91.2597 92.2646 101.236 102.119 102.765 101.318 95.2306 93.2602 102.798 99.2933 97.0292 99.0056 84.2339 97.0195 97.9417 91.7007 102.229 99.9542 119.756 90.0592 88.2678 83.898 96.9813 99.3735 108.256 103.856 97.3413 51.5081 98.0025 102.58 91.3882 93.2459 105.221 84.0474 99.3957 95.6858 93.8873 94.1788 92.5608 86.0692 91.1007 79.9813 96.6202 97.1406 92.6775 91.9934 97.6455 94.9508 81.8361 82.6087 99.268 97.7284 97.8956 99.1395 83.8161 96.9911 97.9143 99.2693 99.5295 92.2168 98.3868 86.5909 81.8003 111.571 97.9929 91.8088 97.5399 99.6073 103.671 97.3946 48.3838 97.892 98.2765 92.0218 80.4527 86.3489 95.5613 83.8493 78.9771 100.141 98.0037 97.9045 98.3562 92.8291 95.474 98.1046 97.7992 97.9986 97.7214 101.052 91.417 81.0874 95.6717 92.504 100.406 92.1152 100.136 100.815 96.8092 97.7196 120.651 98.1921 98.2348 93.8148 98.6291 100.567 100.091 96.8842 99.3335 82.362 73.7423 74.0094 83.6448 97.8486 83.7387 96.9803 97.8431 97.9763 98.1271 98.0284 93.6704 102.101 100.011 99.0259 97.4299 87.7556 97.6936 98.3267 86.4339 97.9404 86.1574 97.7364 82.0318 96.8345 96.7116 88.1561 95.3924 98.3676 108.527 97.7541 97.7056 96.6976 119.45 87.1436 98.5324 99.6108 92.7 94.6312 101.356 84.9047 98.2956 97.3875 86.7274 79.168 100.221 85.3608 96.9978 98.0328 120.814 97.7767 96.319 85.0339 98.0667 95.8897 98.0461 97.9577 86.1237 95.8972 96.4258 98.9874 98.2395 97.6813 100.029 97.971 95.6208 97.1858 80.187 97.6359 101.891 82.4976 98.564 105.949 107.132 98.3447 77.7292 97.6551 82.3063 104.473 97.512 92.2568 97.6646 99.0187 102.465 80.8882 97.572 98.1871 96.9817 79.9214 88.8128 98.4479 97.964 100.529 99.1796 102.322 97.2343 73.9884 90.3169 116.972 86.6 98.3411 99.4273 87.2182 94.3245 97.8367 97.1706 88.3859 97.3342 84.5961 81.9413 101.738 102.173 95.1594 76.3923 96.5076 97.5006 92.8779 97.4649 89.6365 83.5693 96.9062 97.7559 93.4594 85.7555 101.571 78.9047 98.6422 89.1152 90.3477 92.1676 79.2874 98.6505 99.0912 94.2456 96.8396 94.3367 95.6467 97.4769 100.584 100.517 98.155 102.193 93.5729 99.1743 114.868 84.2903 101.33 99.2502 96.9779 88.6796 98.0478 80.6992 99.4855 86.1591 111.735 93.8317 101.561 100.182 98.1189 97.6184 97.3139 101.234 92.3012 98.1695 100.872 93.2462 98.6309 98.2277 99.1894 92.7128 88.9619 75.7737 97.2079 98.1045 119.306 91.1318 84.3292 76.4489 84.7468 49.4851 97.8813 98.6679 99.8811 100.68 97.7597 95.0486 88.6778 96.6796 98.1217 90.9669 98.4953 98.1715 99.99 99.1824 100.11 98.9546 52.3891 75.7107 97.3359 102.383 91.4585 82.5382 97.74 37.1714 99.608 91.8381 97.5002 78.3208 92.8629 120.214 91.9456 74.0726 98.1168 121.363 92.1707 85.424 99.1989 98.5771 83.5021 99.1513 99.0303 97.9012 93.3978 97.2183 83.6108 102.967 97.4946 100.812 86.084 98.6841 91.8885 97.763 97.801 94.4799 96.7014 96.6248 121.689 97.5657 100.111 94.9425 99.198 93.4283 94.4383 116.824 97.6955 75.0307 96.4479 97.4449 74.8932 117.839 97.8266 97.7118 99.2756 95.8836 98.3783 97.383 97.6648 87.2992 95.2503 96.772 87.3982 93.5053 98.5233 91.9643 86.6739 100.261 74.5841 100.355 80.7333 83 77.7005 83.7554 86.9899 98.9084 100.057 97.9517 98.1667 96.5921 94.3368 100.269 97.6077 99.3047 95.4904 98.5919 95.1911 98.4662 99.8455 99.6655 96.3389 94.3705 92.5001 97.7136 92.0648 95.2306 96.1939 76.1213 96.9297 97.5673 81.6276 87.8211 96.9973 97.8621 97.4057 99.2652 100.274 98.3166 86.7342 98.7827 92.3977 99.7397 82.129 96.2742 98.6001 91.7088 102.839 90.4625 88.1234 85.1426 76.5851 100.399 92.5894 98.5652 100.91 100.554 93.944 104.464 96.4221 96.1418 97.1879 83.4897 96.8992 97.6366 96.8227 96.9937 79.2892 93.1962 98.377 99.2675 79.585 97.3341 85.142 99.3924 93.1378 82.6404 98.1493 96.0207 93.5971 93.9076 96.761 83.9224 96.7025 97.4794 125.361 97.3955 82.7717 91.9288 88.9953 100.835 103.426 99.5244 98.9912 95.8843 79.2749 97.524 96.0058 95.4576 120.84 87.7178 97.7619 99.9152 89.6548 102.483 98.1283 96.8314 94.8635 100.037 97.4821 86.5532 97.0723 85.9109 46.104 76.4239 98.2883 91.4973 93.7808 96.8563 99.0871 97.2615 97.9857 97.0784 107.805 96.207 97.5051 87.1577 97.8832 96.8604 99.1963 83.512 88.3505 84.0158 88.8659 97.4898 97.394 99.614 116.641 98.7209 82.5943 88.0742 95.5147 116.021 115.258 97.8114 97.5518 95.7882 96.8109 85.8717 88.5557 19.3824 98.594 105.954 87.4696 98.6183 98.3031 93.0228 117.937 97.4795 84.6658 96.8148 97.2161 97.7293 105.631 98.4541 98.8965 98.4085 92.0922 99.0673 98.6089 97.3006 90.885 95.1497 120.607 93.2908 96.82 98.0056 97.2555 82.8219 97.5893 96.4692 96.8167 97.0805 97.3285 96.8511 98.2833 99.289 96.899 103.584 98.5052 97.6943 95.1564 81.204 41.5522 91.7929 97.4043 83.8462 96.7115 97.2936 101.309 98.6209 100.499 99.2752 92.2638 97.6929 98.6455 97.7321 97.5636 93.8403 96.3489 77.6728 99.5654 95.8009 76.9987 96.2028 97.4201 76.9481 100.046 97.731 77.2012 97.4065 84.7353 98.6287 95.2109 99.1166 97.0114 86.2602 107.107 106.477 90.2813 98.2907 97.6165 98.12 96.2548 78.4023 88.7713 92.3787 97.3181 96.705 89.4262 98.0913 75.1236 90.5376 97.1942 94.6713 98.5569 90.7094 98.9409 100.316 98.26 98.6286 97.5297 96.5829 98.8183 96.6467 96.3871 80.8977 97.3692 96.6927 94.9646 97.2617 85.0825 98.1736 93.5555 93.5433 98.5042 88.69 97.345 97.436 91.5176 95.537 94.7213 97.3226 87.9418 97.2182 98.5029 97.2286 86.9782 98.3928 74.2909 98.6173 97.0043 96.6514 98.4857 95.3815 96.158 97.1344 96.9867 95.8118 84.1713 96.119 97.8671 99.276 97.4906 90.2654 86.4889 98.1262 87.572 97.3478 94.0332 119.132 91.3216 45.2636 92.0979 97.8296 99.0491 93.6471 90.5621 96.6476 96.7999 98.3776 96.1328 96.5311 95.4231 93.2445 100.887 98.5652 95.9446 97.3525 75.9203 106.396 98.3088 98.2998 97.4544 95.465 107.22 93.1184 94.0531 95.9886 86.1172 119.359 95.8536 99.5709 98.1623 96.218 80.2634 92.4381 82.0371 96.9919 96.8659 97.1896 87.9681 97.033 97.9683 97.5169 98.594 92.9847 80.488 100.106 97.7774 98.1564 97.735 99.1529 75.0438 98.5607 97.7443 98.5151 76.4661 88.0358 96.7734 98.3794 90.9874 98.4468 104.841 74.868 95.2624 96.2389 42.9211 93.772 110.962 98.1556 75.2435 91.8368 99.2262 97.7302 95.7455 100.301 98.1457 99.3779 97.7031 98.236 102.784 95.8787 89.3755 96.8717 97.2528 123.951 98.3952 98.7884 98.0898 97.1686 90.45 76.5376 97.7555 95.8731 84.7095 96.3853 96.858 97.1358 85.084 97.1723 98.3642 92.9631 86.4043 99.4789 99.7317 99.869 57.1146 95.5392 102.472 99.649 77.1499 120.607 67.7139 96.1292 88.7052 84.8051 96.2509 97.0992 98.8224 98.8544 85.5954 97.4332 97.6808 97.9091 99.3582 103.116 126.992 95.8005 99.2946 76.6423 114.558 93.3821 84.2729 97.0243 87.8959 97.1712 97.6553 103.317 99.2077 98.5657 97.6758 98.134 119.226 95.3094 103.515 91.7987 99.846 99.6272 99.9533 96.9325 97.82 96.9869 83.7938 97.795 98.2143 88.9155 97.4359 85.7575 98.3761 98.7681 97.3535 88.412 95.8757 35.9089 119.309 98.5303 98.0824 99.0672 99.1998 97.8376 99.3538 83.254 94.0542 97.6777 93.636 70.9495 103.983 99.9331 91.8209 101.721 96.4279 96.7468 98.344 95.6622 30.966 99.7843 85.4335 102.693 93.7296 92.5297 97.2434 94.9402 92.5983 91.8775 93.9674 85.943 120.204 98.473 92.2734 98.4987 96.3427 39.6202 92.4959 97.44 89.0951 97.9935 97.5861 95.9415 98.4169 102.34 100.139 98.494 97.6321 104.194 99.7067 99.2559 96.0903 96.7054 96.306 97.6169 98.3347 98.4991 98.1291 96.9463 102.091 97.992 101.867 98.5364 98.1368 89.1207 89.3344 119.644 98.2614 99.1305 98.0727 102.564 94.5386 100.031 96.7753 95.7777 99.2469 91.0681 112.416 85.7363 89.8242 97.7995 81.515 90.7075 110.164 115.466 99.4127 81.8795 96.9547 78.2491 96.5094 96.9414 93.1938 91.013 96.5757 98.0994 98.4114 98.141 97.1461 80.7634 75.1968 114.062 85.6528 95.9028 97.5329 86.9212 92.8376 106.875 77.4047 96.3872 103.774 98.11 101.407 101.942 97.4617 111.788 97.9635 116.356 90.3386 96.3845 96.5877 97.9904 98.978 98.896 73.1578 96.2743 24.5562 98.4734 109.238 93.7654 99.8601 98.9581 100.461 94.9843 111.038 114.696 83.914 102.914 93.3873 84.9449 95.9417 98.3242 87.0595 97.6093 100.878 92.8102 101.645 101.012 97.0538 96.2 96.8304 120.361 99.9319 97.2942 96.846 94.7154 97.0663 95.6556 96.0977 97.4898 102.527 95.5061 97.1417 93.0553 99.2999 98.5544 103.858 119.159 97.3702 110.68 103.353 97.0013 98.4011 98.504 99.1949 97.4037 99.1887 117.29 94.8966 99.8283 92.8551 94.4981 103.263 92.0562 99.8404 99.1317 99.5993 91.3346 96.964 94.9957 81.5889 97.0623 94.9092 99.5497 99.214 97.7608 97.7659 110.312 97.6418 92.9399 99.2758 99.2065 99.6952 101.369 93.4882 98.0803 99.4449 98.3882 77.5565 93.074 98.0811 50.6026 75.0281 98.3831 93.4178 96.9757 84.3779 97.5542 112.97 97.9359 104.527 98.5576 97.7295 86.2782 85.2867 98.7989 98.6841 88.2042 99.1979 94.9236 102.131 100.165 97.1007 96.805 90.9836 99.2903 99.5188 49.972 49.2677 89.2776 98.5373 99.8413 99.4253 97.3059 95.5748 86.1197 99 96.3029 89.3437 83.8132 101.786 97.6997 100.201 99.9762 120.123 71.5821 99.6896 74.991 99.7177 100.588 98.1948 87.5428 97.093 92.5018 103.392 93.9979 100.002 99.042 79.5437 41.3912 96.3772 98.1587 94.5799 115.171 97.2172 92.3422 98.1326 97.2077 96.952 100.435 97.6251 92.5892 98.1172 95.2419 97.0046 84.2254 97.7721 97.7152 97.023 94.624 102.844 99.4811 99.0529 92.0832 96.1216 96.613 99.9371 96.7688 102.719 85.7581 99.7775 100.08 96.169 93.9799 99.5199 95.731 94.8741 97.259 98.7681 103.941 106.429 137.715 93.5925 90.7421 120.112 96.1498 96.9117 94.7739 107.033 97.7085 94.0733 8.95975 95.4045 99.6195 95.2079 98.6159 96.9304 97.231 84.7267 98.9426 89.0009 80.0053 96.2604 95.6938 94.4909 91.1415 119.78 77.0968 105.505 99.0499 98.4633 85.349 97.2755 97.109 98.6162 96.9236 95.7349 81.022 92.3675 33.1086 104.484 91.7029 100.023 91.642 94.9594 99.0109 97.7305 98.5471 101.242 95.0377 94.3367 98.6968 97.4961 93.3754 98.3665 98.0134 96.3288 91.4345 102.981 97.5764 97.0759 96.9371 96.755 96.1546 100.72 99.2394 94.6867 100.376 92.8398 93.9263 98.8225 93.04 98.5001 96.9822 94.9707 89.9976 94.6344 119.095 96.5553 96.493 121.163 97.3519 91.6613 98.0776 74.9197 96.856 96.6314 98.6656 94.1878 98.6612 94.1701 94.2447 97.4201 95.5922 97.4085 98.5324 99.0354 96.9321 92.9115 100.067 98.5191 98.5605 98.4808 84.748 82.2741 96.0862 97.7147 97.0804 91.6582 88.1895 97.2178 78.4516 98.3659 98.2209 85.2749 55.8632 85.8036 96.8942 96.6491 95.9401 97.6616 97.0243 84.5866 97.9041 97.3596 85.8911 97.0245 112.558 94.8747 98.4508 88.4169 95.4483 91.627 94.7718 85.6582 93.1498 95.0238 100.102 97.351 98.2299 94.075 101.82 102.787 93.3064 99.8983 98.2854 98.1564 98.4975 98.3832 99.667 120.865 96.5136 93.807 107.595 92.8808 98.4784 95.9853 98.6771 97.6467 88.46 98.4981 97.0622 99.6252 98.2115 91.3266 93.9505 92.3949 90.3992 123.173 94.1982 92.1818 97.9831 97.5859 97.1623 106.782 112.972 97.4471 98.8006 101.343 104.108 100.545 96.9614 98.0216 97.6963 84.0351 99.9807 98.2011 85.5819 80.0932 76.4778 99.7782 85.5525 102.677 98.4881 98.1253 98.8799 99.912 98.5948 93.8988 99.5931 100.815 99.3994 81.3439 97.6716 98.587 95.2548 86.0693 17.2701 75.2027 77.3221 100.026 98.2065 82.4521 97.3315 94.9923 98.0924 96.8716 98.071 96.7865 97.4297 121.276 95.1602 120.921 96.9501 96.2874 97.7891 96.7533 94.8199 91.6011 50.0745 103.015 95.0746 98.5116 97.0382 96.8473 89.2465 98.0004 91.7991 96.7651 95.5168 95.0957 96.7433 93.6156 41.6855 97.4202 84.7201 96.3714 100.34 97.8628 97.9049 99.1534 84.692 48.2007 99.3248 77.1449 99.9398 97.4814 97.0191 97.7343 98.413 98.6099 93.5159 104.533 80.9926 99.4769 98.1065 98.4148 99.0065 90.2833 97.9436 120.272 101.91 97.56 88.2138 97.6038 97.1418 85.6398 96.9332 99.0753 106.576 87.0503 99.9619 97.07 97.2134 100.239 99.1348 94.1484 76.8114 102.61 99.9404 92.8258 96.9939 97.9437 118.745 98.4383 97.6835 98.336 96.6927 99.3044 76.9336 40.6447 104.155 77.6806 97.7704 94.0849 94.0356 95.107 100.176 97.7085 96.7141 98.541 97.5214 96.8364 119.753 95.9316 96.1479 92.9363 97.6679 48.1561 95.0549 94.0191 102.027 99.6136 98.2658 95.6619 95.4473 97.4964 96.9365 96.8921 86.5129 96.9696 97.6029 99.5783 113.172 97.7542 98.2412 98.0664 96.9657 97.767 95.8926 98.9302 98.7453 99.7294 98.4973 97.0984 95.729 97.11 97.245 101.226 65.9339 98.6515 49.4743 96.762 96.7227 87.9949 87.0898 96.7877 97.4726 75.0755 95.7282 102.923 99.9491 92.2101 102.904 110.199 103.321 98.8571 97.4428 93.0914 79.6445 95.0335 86.8665 95.369 97.3577 97.7199 102.026 102.459 97.6839 93.1214 95.6574 93.5833 95.7106 98.4872 98.5554 91.4178 97.9864 97.2696 113.504 95.3215 96.0704 96.4666 100.687 98.3783 93.4831 88.8233 99.0445 97.0107 84.3916 97.895 98.2486 96.4439 98.4298 95.9002 97.4369 77.6916 87.8458 96.2554 96.8677 92.8197 103.103 97.5405 94.592 96.2144 97.5938 104.431 105.581 97.6884 96.2368 105.041 99.8883 97.4441 96.8317 97.5316 97.0104 97.9852 95.6461 98.421 98.3494 92.6857 97.7364 98.1891 121.354 98.7713 98.5717 93.4561 98.673 75.4742 96.5976 80.8121 97.2573 95.7823 94.9877 103.986 95.5091 96.9319 100.167 99.1523 99.2641 98.2497 97.9176 99.2936 95.451 99.0786 95.0381 97.4611 53.4493 81.43 120.196 97.5428 97.3045 99.1626 108.652 90.6124 49.3223 95.8541 98.7469 98.4308 99.0168 90.7105 98.0254 96.819 89.3123 99.1643 87.3849 96.159 97.6463 93.484 97.6908 95.7542 118.271 98.6505 93.6227 97.5973 97.6298 98.7118 96.999 102.662 87.6542 99.7265 95.2175 96.8491 81.4256 99.9692 95.1393 102.461 98.619 93.5948 98.1219 101.119 120.064 89.5863 98.3841 97.0278 98.7518 98.8422 97.6522 97.4554 121.175 98.1461 97.4489 96.5373 86.8426 95.7353 98.3802 100.15 98.9125 97.5943 98.1035 97.9272 45.899 97.3996 87.2863 102.801 119.881 77.6432 92.396 98.5875 119.487 98.2471 81.5623 85.9416 43.8841 52.6492 97.0741 47.194 98.5635 43.5677 101.827 104.37 93.1544 95.1021 98.5711 98.4633 98.2521 98.3511 96.7823 96.692 96.866 96.826 98.6648 96.7599 61.9573 98.7744 98.8115 99.0991 98.928 54.043 98.7664 100.341 95.0062 96.5645 95.8694 94.1764 68.98 45.8306 93.6259 80.0157 74.804 93.5214 98.6725 94.0466 94.089 94.0733 93.9568 100.239 96.7482 94.229 100.426 98.7378 100.322 100.21 100.471 100.21 94.7224 101.255 103.686 104.327 98.4916 101.419 101.035 93.6476 100.725 101.601 103.465 105.833 102.002 101.803 108.113 110.728 114.406 112.948 100.416 98.3154 100.193 100.09 100.416 98.213 93.6619 98.1632 99.2438 98.7969 98.8519 77.8977 96.8484 98.9069 98.9625 85.3174 103.377 104.449 93.0518 97.4835 85.7544 97.2123 95.0912 98.6089 98.1754 120.031 95.6375 95.6642 96.7864 74.0321 86.9439 96.8018 102.56 99.5886 101.195 98.0513 99.0064 97.37 97.0262 96.9017 97.0635 96.3147 99.8226 86.116 102.652 97.6592 97.3846 97.5857 67.681 97.2624 98.1639 89.5668 97.1553 45.2789 98.5842 98.2024 97.0114 83.8714 98.2419 98.047 97.2651 91.0724 97.3479 98.1745 102.697 99.614 88.2663 99.6994 97.0472 89.5024 86.2857 102.629 98.0056 84.0553 97.7096 96.7962 107.339 96.6364 96.8426 100.517 99.0828 97.9003 95.1792 48.5824 98.801 89.4995 99.8927 102.705 89.986 97.6692 97.6796 101.76 89.3715 97.5303 96.4643 87.8956 97.496 98.6137 96.9307 89.4205 84.8267 97.1277 98.0364 98.3038 76.3176 98.0994 77.9253 96.9282 91.5297 82.8867 98.3361 96.9908 97.3966 96.9002 96.7196 97.7517 120.615 97.3358 97.4008 97.7541 92.0638 97.3569 90.8148 86.1499 96.4148 97.6718 95.7054 81.6202 99.3081 82.3856 85.8481 97.4786 120.343 95.9788 90.6503 95.3562 98.3047 96.9738 98.0005 96.9416 97.8824 96.2774 92.0861 80.1401 98.6121 100.347 98.2982 95.9138 91.0092 48.2327 97.2022 98.779 94.8717 86.4194 100.129 98.1396 95.8484 98.7515 96.6134 93.4552 97.4048 90.2442 92.969 99.001 97.7956 81.6771 97.6093 97.1318 95.7408 98.7237 87.7587 46.8026 118.952 98.6039 100.96 92.7131 99.3026 98.5755 97.2914 97.278 97.8696 92.4325 97.3992 102.684 86.7078 99.2767 76.8069 99.0828 95.768 99.8217 99.2945 93.9347 97.5545 98.178 61.7105 98.361 78.0295 96.3417 96.624 95.1797 95.9207 98.4936 96.1003 93.3081 83.9606 97.8939 96.9332 98.0398 98.4765 117.063 116.326 99.533 95.5117 97.3568 91.7508 121.46 98.4409 97.5863 87.3394 100.069 91.815 103.006 102.838 102 99.4641 97.4221 98.6279 95.6428 117.566 98.9036 102.415 88.6172 99.418 101.648 111.535 97.6371 72.9844 97.3578 87.1818 97.6277 94.8892 95.6638 96.206 98.8162 93.6182 93.9353 95.4943 94.9364 97.4239 95.6889 91.2412 88.4909 43.6006 97.8529 96.1031 94.639 93.4287 98.6022 99.0259 96.2265 97.7992 97.2175 71.7716 80.6421 120.127 99.8093 86.1124 102.761 88.3764 92.8996 95.7512 96.6174 127.446 92.4513 88.0185 91.9511 97.486 95.1243 96.0006 104.811 100.141 97.8792 96.7251 98.0468 104.786 94.8236 104.821 92.0719 98.4518 96.8129 95.0682 100.164 93.4004 101.497 38.9864 99.046 98.4123 102.87 86.6927 99.8287 96.7819 93.4336 101.31 99.4358 77.6039 85.7899 97.5874 98.2023 98.5255 99.5 82.5933 77.2976 98.5003 98.2587 96.4687 91.5526 98.4891 84.8805 98.087 97.1685 88.5119 98.0353 92.4661 28.2529 98.4535 100.692 97.0977 86.8951 98.4215 97.7744 99.2326 100.387 97.8554 96.9747 43.1211 97.0219 84.2042 97.972 97.0059 80.3644 98.2447 76.4449 97.2678 94.4398 97.4773 97.1448 93.0134 104.389 119.44 87.0582 93.9579 97.5613 98.0353 95.5011 120.355 98.0663 119.137 97.1351 76.5638 99.7848 92.4875 92.3815 97.7464 85.0173 97.3883 98.1979 98.1147 96.5965 97.4565 84.3779 120.158 92.8788 94.9599 99.0145 98.1754 97.284 92.9548 100.28 101.431 100.09 52.1423 34.4141 102.724 100.181 98.0701 95.6036 97.7434 98.0353 98.7838 91.4857 97.7752 89.2956 97.471 97.0393 85.2935 97.0352 120.023 94.603 101.623 100.18 94.9621 99.0637 84.7417 98.0307 97.1142 119.892 99.8778 87.7446 102.615 98.6657 103.528 99.9712 93.0959 103.028 96.7002 88.9864 83.5378 97.0418 102.403 103.619 99.8028 93.8221 95.2039 112.416 94.1714 79.1833 99.6295 102.606 98.4822 93.34 78.1231 99.7815 100.162 36.1221 84.6758 98.0288 97.0633 99.5361 94.3118 84.1915 96.915 98.4963 94.4971 86.675 94.5442 94.7669 95.6363 97.5113 96.001 73.2183 98.135 92.4916 103.675 97.7094 91.0019 98.8147 109.893 95.4099 97.7197 87.7397 74.2985 102.24 118.339 95.3172 96.9755 97.6716 90.5326 76.8205 99.9215 89.8641 102.348 98.893 102.524 93.8513 100.265 101.296 98.369 99.1349 110.128 97.7519 96.3848 92.7246 119.981 96.3348 96.0693 94.4844 93.4514 97.3723 99.0249 98.3172 85.446 93.7616 95.499 95.6017 120.657 94.4377 93.9095 83.174 97.342 123.054 25.4551 18.3997 93.4624 96.7104 97.2488 96.465 93.9108 99.6358 102.449 88.2927 92.1806 98.44 72.2045 98.5079 94.3974 87.5288 101.807 47.7559 97.8 98.7017 102.866 99.9998 92.4978 90.6054 98.5604 96.4838 103.089 97.2708 93.3609 100.367 70.0995 95.4814 94.0039 98.4896 98.1411 95.9656 49.4348 92.7045 97.3388 97.1114 98.0928 92.3136 89.8188 101.478 98.6921 118.944 95.6325 115.83 81.7177 96.0262 95.9307 97.9849 97.3517 74.0797 105.638 97.8988 97.6646 47.6886 80.203 93.1506 120.699 95.1282 119.998 99.2735 96.8517 98.0867 72.0693 101.659 118.455 93.6684 108.583 97.9055 97.3634 91.0959 103.372 95.864 99.1037 94.3753 104.992 104.196 92.1334 98.518 57.078 92.1168 97.69 98.1144 119.869 98.1995 95.5322 98.6411 98.5091 93.6457 81.4115 96.7953 99.1574 6.96679 99.1039 96.0476 119.718 94.9016 99.6146 95.5553 110.183 93.0212 97.0192 97.9238 97.1076 96.5601 84.1373 95.7991 99.1195 120.247 44.6163 99.5937 60.5963 98.5898 97.6338 103.276 99.4453 101.977 96.8837 92.1457 99.0169 120.804 92.208 112.877 120.474 96.0681 98.175 118.318 87.3786 98.5105 88.1881 96.8275 97.2116 92.4185 95.1677 92.1947 97.7032 91.7533 96.1504 97.5196 97.1621 99.4166 98.1555 96.6282 92.4808 98.4719 108.286 94.3908 73.4194 103.681 120.126 98.5969 97.5053 97.0605 98.3882 96.0414 97.5987 117.408 76.1968 96.2591 96.1448 98.9406 96.8803 85.387 96.8676 99.5729 120.282 75.1498 99.7188 100.617 119.908 98.6397 99.1584 64.8779 90.1905 98.094 84.827 97.3896 120.596 98.2386 97.9275 96.2187 82.975 97.8824 97.3921 99.2549 93.186 53.9608 120.518 97.6313 52.9025 99.8196 99.1582 120.659 96.6218 99.5757 105.91 104.764 97.7557 54.7504 100.122 97.5534 120.148 120.395 120.088 120.263 65.1744 103.226 62.479 59.6459 51.1832 103.318 50.6835 49.4058 56.8064 120.054 120.354 49.6342 120.549 120.653 92.9993 104.593 104.458 92.8258 92.0934 92.1202 92.6149 91.9627 91.3444 97.6857 75.0845 84.8077 98.5995 74.7427 107.458 89.7657 99.2531 108.254 84.9918 76.1003 98.127 97.4462 97.3295 96.0584 120.337 98.5136 97.3021 98.1086 97.3398 98.0107 120.617 94.8035 101.054 97.1473 98.7592 97.5867 97.2551 96.4536 119.932 97.5003 74.7975 102.496 99.942 92.7665 91.9391 97.5961 97.1892 100.011 99.818 98.0541 95.8919 95.6249 97.503 98.194 92.8898 97.145 97.4181 96.3745 98.5342 100.076 98.345 98.2439 89.8998 98.5261 92.0148 109.562 95.4279 95.9248 98.9494 94.1287 93.8655 94.7423 96.082 99.1411 96.7131 85.5524 99.4844 100.007 118.179 96.8565 103.083 99.6113 121.619 97.5109 96.3102 98.1443 97.6215 97.0333 89.6533 96.4886 82.9694 98.628 94.6174 113.483 98.6152 99.0613 82.5338 93.1325 98.9421 98.1511 119.325 80.4753 93.1726 90.4982 85.2339 45.6629 104.041 104.143 99.0225 98.5148 100.594 98.3715 99.3361 107.828 118.882 97.4462 98.1473 97.8146 97.032 84.5035 97.7777 102.203 87.1842 97.4303 96.6851 97.6576 98.8465 94.0469 93.6254 89.849 97.3241 93.1245 31.8148 97.6404 98.6806 98.3252 92.2459 96.3778 92.3248 93.2533 100.176 102.638 96.4136 96.288 100.9 98.0508 94.5878 120.61 97.9188 75.4362 97.4883 110.531 90.1841 95.6189 98.7199 87.4987 102.577 87.0788 99.6249 97.0181 84.8162 97.3113 92.4667 103.472 106.688 79.2534 84.6641 98.313 102.889 86.8307 99.8538 98.7604 97.1741 85.6556 100.111 99.2873 96.1555 99.2253 114.015 97.3994 102.84 96.3158 99.4711 82.2535 77.82 99.8369 87.2207 98.7175 99.612 97.6169 97.2855 97.9401 99.8864 88.368 102.51 112.359 96.9838 84.6506 98.0078 83.9426 104.734 95.0849 97.3491 102.355 100.363 96.4601 96.4893 104.753 99.2382 16.5805 97.022 84.5803 97.5817 97.3579 97.1558 95.3094 100.001 95.1083 94.4281 93.9824 98.3329 89.2214 87.7176 97.0232 98.5805 93.821 40.2638 93.5915 7.54355 110.286 98.2216 103.508 103.767 91.1632 96.7223 98.1064 99.7368 83.8033 96.7555 94.6702 103.353 87.4974 106.452 96.8734 97.5377 98.4939 96.5434 117.646 91.205 90.9715 98.6978 99.2278 98.3737 48.8923 96.8 83.4034 97.5843 97.6557 117.866 102.56 89.3057 99.5905 124.363 96.8362 96.5505 97.1409 97.008 84.5049 97.9293 50.4911 98.5169 98.9307 96.2431 99.0493 98.0114 92.189 97.5797 97.2183 98.1757 90.6696 96.5657 96.4247 97.5887 85.2741 76.3324 94.6324 97.6167 91.346 95.9109 103.078 99.2574 69.2516 103.77 99.0497 102.368 100.038 92.9998 100.076 98.3852 77.3713 109.393 99.2501 96.2262 93.7134 98.5067 76.8281 97.5942 81.1858 97.0092 92.5684 95.4382 95.893 95.9519 86.006 98.5016 90.1191 99.0443 97.1702 97.4338 97.8294 95.7937 90.145 97.4655 98.3842 100.302 95.0102 99.2142 80.0365 64.9528 106.436 72.6958 84.6857 96.9157 96.406 86.8312 98.5916 86.1498 83.5665 96.8712 43.8692 79.2013 95.2968 102.981 95.0613 16.4212 81.7073 97.5371 98.4801 118.122 83.2715 97.3786 100.516 95.4108 83.7439 93.0878 94.0954 98.406 99.5845 98.3099 99.2553 96.638 96.9095 98.0968 97.4444 92.7084 89.6227 80.5271 84.1306 96.5739 100.19 87.8658 72.5025 97.4835 96.9475 73.0071 99.304 98.4607 82.9284 118.774 98.0493 96.0868 102.819 86.9103 99.8012 82.6325 97.2597 98.6581 97.9386 97.3446 98.2388 93.8387 98.0246 102.882 114.359 47.1893 98.4945 96.9636 98.697 96.9437 49.2409 86.1631 108.328 119.941 112.382 92.9862 96.4963 119.205 90.8516 87.0809 102.58 96.7341 108.441 110.635 108.172 96.863 94.444 98.5098 94.16 98.9826 97.1492 120.67 103.873 99.4114 82.6953 101.097 97.1561 86.9064 97.5229 64.9819 115.25 96.4165 103.399 98.3402 97.7118 80.9993 97.3852 92.7376 120.028 122.075 72.3678 97.5946 97.2706 95.5185 95.8098 86.4905 97.6121 98.9344 75.0026 97.7381 97.6235 84.9259 98.0831 97.2224 98.4485 43.1359 97.8457 99.263 99.265 96.9584 96.1883 98.5577 45.2394 98.1274 95.7912 99.8816 88.3601 103.059 91.4336 97.9823 43.2982 76.616 97.2894 94.5318 99.5061 104.2 94.1503 93.9162 96.2105 95.0999 99.8434 97.3987 97.1101 85.8282 91.2557 98.8288 99.9352 99.3433 97.2249 90.8656 105.075 97.5981 97.273 86.4547 97.3842 97.8751 95.0428 98.0804 101.181 100.194 98.3845 91.8147 96.7864 84.2437 91.2576 91.9694 49.0937 97.5157 90.5573 84.4473 96.7148 96.9385 97.7529 74.6061 96.5238 96.1826 86.6415 79.1227 84.1955 96.8898 87.5095 99.873 102.734 103.04 86.5817 99.8599 98.9238 96.9424 94.9738 98.5197 84.1598 91.7083 73.5045 98.2419 89.8095 96.7584 95.3653 92.6601 83.8354 112.391 92.4046 100.931 100.229 96.9228 54.5472 88.4798 99.0203 98.1081 95.1928 99.921 97.4574 88.5778 84.9792 99.2711 97.7602 84.5665 99.085 102.651 99.8525 86.7836 102.65 93.6099 98.138 97.6431 97.7246 91.8878 77.8526 95.9938 98.4965 99.1258 85.407 97.6427 95.45 91.6043 97.0032 98.458 91.9121 96.9399 98.0512 81.7167 97.1519 119.703 95.8534 93.6019 112.732 102.036 99.9454 91.0962 98.8973 94.8719 43.7381 96.9165 97.9932 96.7934 91.6577 99.2744 82.8132 101.112 95.8099 99.7602 96.5439 99.1456 95.7497 98.3798 99.7874 98.4756 115.485 95.6635 100.435 94.6261 102.967 90.9433 85.6922 93.6672 96.7911 98.1812 103.197 86.8461 99.8752 81.2962 112.938 98.3992 99.6915 96.7103 97.6369 119.635 70.994 92.2044 78.8419 76.7202 94.553 90.1464 30.1456 98.5158 119.064 91.584 87.4289 95.3496 97.5633 89.7268 93.1689 97.364 98.4054 99.4898 118.257 90.8637 98.3283 86.6101 93.5084 98.6038 66.3515 98.8695 93.6495 97.9028 87.0523 97.2567 91.7201 94.5702 99.2051 79.9856 98.3908 96.5418 99.7714 96.772 98.0561 95.8175 99.2546 93.6935 97.8388 89.3571 97.3916 97.7669 99.7001 99.9259 97.5601 96.0434 84.857 97.9792 102.157 89.4326 93.3351 93.7756 97.6839 98.6773 96.9474 97.9644 81.4018 86.3616 96.6563 96.5292 93.8332 89.2253 87.0805 95.5793 97.5339 91.977 95.6269 97.1361 95.709 80.1434 88.3304 90.2319 97.4403 120.5 88.4563 93.7554 97.5566 48.8842 98.9348 95.42 49.2436 97.6853 80.5856 98.5135 97.3588 85.9259 99.2077 93.5015 97.7863 95.6525 96.9999 96.6115 97.7447 96.4361 102.078 90.1339 99.1185 97.6631 119.579 96.8796 81.2304 97.1686 98.5496 96.9288 97.9802 79.1429 97.5884 96.8043 95.5864 102.54 99.3295 98.3335 88.2677 87.6816 91.8575 97.3078 107.446 98.4968 97.7818 93.9676 98.0905 94.9558 43.3663 94.8539 97.6382 96.5794 96.816 96.7044 97.623 95.1189 97.4366 97.1304 98.5069 97.3971 84.4632 97.84 97.5126 95.6618 96.0755 97.5414 98.1356 88.1548 97.4089 98.1232 97.3596 102.305 93.2644 99.8879 94.0411 94.1894 95.4651 99.6543 98.4507 67.973 98.6863 98.7416 99.7235 90.1109 121.432 84.3635 48.1408 89.3375 93.6764 120.258 82.7357 104.115 95.9319 97.4931 88.2103 97.0332 98.0612 97.5015 94.987 96.3992 95.9831 84.5475 92.0036 98.1824 97.9008 79.3669 100.369 97.2549 96.6065 97.2247 103.201 93.6517 99.8495 97.3836 98.0817 84.8682 97.248 93.533 98.2115 98.4809 98.8425 77.1465 96.2782 105.174 99.9761 94.8327 97.8897 84.5089 96.9196 102.181 99.3291 84.7802 93.3348 100.129 101.169 96.6154 68.9969 103.999 95.0468 92.4631 102.769 100.46 93.1733 97.7195 87.3074 97.4052 98.5905 101.208 47.9882 97.0079 107.376 97.547 82.7416 97.7436 94.4571 97.6808 80.8177 97.3196 99.826 85.9405 102.787 100.167 87.7219 98.0149 84.7335 97.0344 99.3052 94.8074 98.4319 51.1907 98.2307 100.006 93.7998 102.129 98.6582 100.536 98.1993 98.499 97.1837 98.1911 97.3291 49.057 97.7969 97.6286 99.9319 97.7034 84.6392 96.6531 97.5355 95.8693 98.4376 98.3891 97.2257 99.227 97.9832 84.579 96.9842 96.0785 97.9284 98.2421 93.8362 102.554 97.8114 39.0753 120.514 95.6024 99.3399 98.0935 98.79 98.0396 92.1747 119.859 97.4394 98.1986 84.0175 97.5172 73.0499 98.0625 97.203 84.8238 95.2155 96.875 96.8219 104.994 40.2755 90.4586 98.7305 98.1877 48.6556 97.8608 96.881 88.781 98.5252 95.4711 120.276 92.8259 96.9978 96.905 92.5669 91.3857 103.344 97.2513 119.824 50.6985 74.8683 98.4559 92.0684 98.0558 96.8566 97.854 99.1757 99.6648 84.5453 43.0139 105.985 98.1064 97.2851 98.0621 85.1224 97.1277 90.2413 97.5603 70.2699 98.8383 98.6225 98.2953 96.0545 98.8619 120.188 103.907 99.6481 90.0377 46.6367 97.572 96.3954 119.857 97.2242 98.6936 97.7603 84.832 95.6827 99.5213 98.6018 98.8054 100.322 98.2395 97.705 15.271 97.6704 99.304 97.1652 96.8599 98.0347 91.1631 90.9005 99.0483 98.3959 89.1594 120.382 98.399 99.3243 96.8255 120.618 82.7336 69.3301 92.1735 82.2928 98.5072 92.3967 87.0036 98.621 111.541 98.941 41.1322 112.809 98.4711 95.7098 81.5862 113.81 51.3484 98.5092 103.475 99.8231 86.8407 92.1463 120.66 113.321 97.6961 96.7393 98.6883 99.4073 96.7133 92.8145 100.137 111.431 49.3315 82.2547 95.9916 97.4132 92.6951 102.345 91.3919 99.3181 116.95 76.4614 97.7051 98.5139 109.596 112.213 98.5596 98.0879 97.7602 95.8903 86.6814 119.101 98.0548 98.5134 96.094 91.5694 120.174 110.241 91.4682 111.479 92.5149 86.228 97.3736 76.3309 93.7459 49.3602 120.281 93.1667 102.132 98.0595 84.8534 97.1779 91.5533 120.288 105.038 94.678 119.982 98.5714 99.1515 83.7869 115.025 88.6916 98.5155 98.8356 98.6021 99.6489 91.0513 93.9891 103.959 97.2052 117.709 82.9156 94.6929 96.3709 115.97 98.0428 97.1582 89.4515 91.5667 92.7569 97.5353 98.8727 98.7769 58.7044 119.857 50.1963 97.8541 96.9076 78.8639 92.7168 98.5273 96.7729 98.9025 83.5712 95.5813 95.9196 98.1973 99.3321 116.806 87.5697 88.4505 96.6258 85.8906 96.0978 97.5961 96.097 95.8934 94.8121 88.5514 97.1339 95.9862 86.9748 86.8253 97.8013 98.7411 98.6989 99.3636 98.5371 95.5639 93.9456 92.2697 100.199 98.317 87.2231 102.631 97.7407 99.0012 91.2208 96.8125 86.4892 95.7397 96.7908 97.8548 96.9807 98.3352 110.857 118.837 94.9695 100.435 98.2778 96.7206 93.7897 98.0585 96.9434 108.376 94.1907 100.446 100.657 98.5201 63.7936 100.409 98.419 103.16 96.0593 91.9351 99.2005 79.2045 102.256 99.8602 96.1903 91.9343 120.185 95.8878 92.5857 97.982 96.602 99.8531 87.0018 102.602 120.164 98.9104 92.1776 94.4234 76.5602 122.403 102.646 100.108 93.3343 110.833 94.6377 100.601 100.339 98.4738 92.1885 91.5216 60.9764 119.962 98.3852 96.7024 96.378 98.3532 96.721 51.4943 90.9792 97.299 92.7313 99.1161 96.8425 96.8397 86.3693 91.8342 97.1483 98.2287 96.2014 98.41 97.7716 99.4277 102.746 77.3157 89.9967 95.2227 94.8531 97.3953 96.7321 97.1826 96.5648 107.651 121.207 93.8442 102.724 95.2281 121.03 118.72 120.075 95.9477 95.0906 105.169 97.1533 98.837 95.7154 91.6242 98.7785 85.4781 110.692 98.1509 97.7201 98.4922 59.526 99.415 102.438 84.5311 98.8974 98.0515 90.1288 95.8861 90.1262 97.3927 90.7723 96.2282 102.307 48.617 77.18 95.3712 120.026 91.5803 90.7165 88.6915 97.3826 98.9039 97.5618 89.1877 91.6149 91.7008 97.3112 78.0567 102.03 97.0201 97.2061 99.2359 43.7883 95.3442 96.6622 81.4016 120.222 86.3493 81.5827 91.418 109.634 94.5644 95.0082 92.2946 77.9123 78.0316 101.257 92.9761 92.0748 98.7258 102.539 92.0431 97.2118 96.6231 97.1024 99.0277 99.1572 99.3125 98.5907 100.75 92.2154 97.0914 97.2789 94.6902 94.15 100.035 84.4549 93.0009 28.3696 49.6045 83.8161 105.329 88.4319 90.5963 91.7188 97.9957 101.439 97.6934 98.1928 100.009 100.618 99.5344 99.8038 100.955 97.6863 97.4993 98.822 104.93 103.514 101.542 101.747 114.236 126.298 104.901 101.213 99.3555 95.8222 95.5731 98.0094 97.4293 97.8663 92.0984 98.0458 99.4781 97.3162 97.4363 99.6196 99.593 102.422 97.9178 121.944 118.751 119.514 ) ; boundaryField { frontAndBack { type empty; } wallOuter { type zeroGradient; } inlet { type zeroGradient; } outlet { type fixedValue; value uniform 0; } wallInner { type zeroGradient; } } // ************************************************************************* //
[ "mohan.2611@gmail.com" ]
mohan.2611@gmail.com
82928f352658dd7f1df1a9ceca537555a2488b58
1e18176f4a2ee9c414119e6e5ae785212c2f521f
/compiler-rt/lib/sanitizer_common/sanitizer_stacktrace.h
72b1ad02e5a0e143a0d1e2925b7f1c073487ebbf
[ "LLVM-exception", "Apache-2.0", "NCSA", "MIT" ]
permissive
dawmlight/third_party_llvm-project
523ff2b43983ee742c3a5b35f5fc5c7d9f3f3d33
8f792f129c7aa42564701de4f9acb8771f05cca7
refs/heads/master
2023-08-09T22:43:19.872691
2021-08-06T07:39:58
2021-08-06T07:39:58
406,236,811
0
0
null
null
null
null
UTF-8
C++
false
false
5,814
h
//===-- sanitizer_stacktrace.h ----------------------------------*- C++ -*-===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // // This file is shared between AddressSanitizer and ThreadSanitizer // run-time libraries. //===----------------------------------------------------------------------===// #ifndef SANITIZER_STACKTRACE_H #define SANITIZER_STACKTRACE_H #include "sanitizer_internal_defs.h" #include "sanitizer_platform.h" namespace __sanitizer { struct BufferedStackTrace; static const u32 kStackTraceMax = 256; #if SANITIZER_LINUX && defined(__mips__) # define SANITIZER_CAN_FAST_UNWIND 0 #elif SANITIZER_WINDOWS # define SANITIZER_CAN_FAST_UNWIND 0 #elif SANITIZER_OPENBSD # define SANITIZER_CAN_FAST_UNWIND 0 #else # define SANITIZER_CAN_FAST_UNWIND 1 #endif // Fast unwind is the only option on Mac for now; we will need to // revisit this macro when slow unwind works on Mac, see // https://github.com/google/sanitizers/issues/137 #if SANITIZER_MAC || SANITIZER_OPENBSD || SANITIZER_RTEMS # define SANITIZER_CAN_SLOW_UNWIND 0 #else # define SANITIZER_CAN_SLOW_UNWIND 1 #endif struct StackTrace { const uptr *trace; u32 size; u32 tag; static const int TAG_UNKNOWN = 0; static const int TAG_ALLOC = 1; static const int TAG_DEALLOC = 2; static const int TAG_CUSTOM = 100; // Tool specific tags start here. StackTrace() : trace(nullptr), size(0), tag(0) {} StackTrace(const uptr *trace, u32 size) : trace(trace), size(size), tag(0) {} StackTrace(const uptr *trace, u32 size, u32 tag) : trace(trace), size(size), tag(tag) {} // Prints a symbolized stacktrace, followed by an empty line. void Print() const; static bool WillUseFastUnwind(bool request_fast_unwind) { if (!SANITIZER_CAN_FAST_UNWIND) return false; if (!SANITIZER_CAN_SLOW_UNWIND) return true; return request_fast_unwind; } static uptr GetCurrentPc(); static inline uptr GetPreviousInstructionPc(uptr pc); static uptr GetNextInstructionPc(uptr pc); typedef bool (*SymbolizeCallback)(const void *pc, char *out_buffer, int out_size); }; // Performance-critical, must be in the header. ALWAYS_INLINE uptr StackTrace::GetPreviousInstructionPc(uptr pc) { #if defined(__arm__) // T32 (Thumb) branch instructions might be 16 or 32 bit long, // so we return (pc-2) in that case in order to be safe. // For A32 mode we return (pc-4) because all instructions are 32 bit long. return (pc - 3) & (~1); #elif defined(__powerpc__) || defined(__powerpc64__) || defined(__aarch64__) // PCs are always 4 byte aligned. return pc - 4; #elif defined(__sparc__) || defined(__mips__) return pc - 8; #else return pc - 1; #endif } // StackTrace that owns the buffer used to store the addresses. struct BufferedStackTrace : public StackTrace { uptr trace_buffer[kStackTraceMax]; uptr top_frame_bp; // Optional bp of a top frame. BufferedStackTrace() : StackTrace(trace_buffer, 0), top_frame_bp(0) {} void Init(const uptr *pcs, uptr cnt, uptr extra_top_pc = 0); // Get the stack trace with the given pc and bp. // The pc will be in the position 0 of the resulting stack trace. // The bp may refer to the current frame or to the caller's frame. void Unwind(uptr pc, uptr bp, void *context, bool request_fast, u32 max_depth = kStackTraceMax) { top_frame_bp = (max_depth > 0) ? bp : 0; // Small max_depth optimization if (max_depth <= 1) { if (max_depth == 1) trace_buffer[0] = pc; size = max_depth; return; } UnwindImpl(pc, bp, context, request_fast, max_depth); } void Unwind(u32 max_depth, uptr pc, uptr bp, void *context, uptr stack_top, uptr stack_bottom, bool request_fast_unwind); void Reset() { *static_cast<StackTrace *>(this) = StackTrace(trace_buffer, 0); top_frame_bp = 0; } private: // Every runtime defines its own implementation of this method void UnwindImpl(uptr pc, uptr bp, void *context, bool request_fast, u32 max_depth); // UnwindFast/Slow have platform-specific implementations void UnwindFast(uptr pc, uptr bp, uptr stack_top, uptr stack_bottom, u32 max_depth); void UnwindSlow(uptr pc, u32 max_depth); void UnwindSlow(uptr pc, void *context, u32 max_depth); void PopStackFrames(uptr count); uptr LocatePcInTrace(uptr pc); BufferedStackTrace(const BufferedStackTrace &) = delete; void operator=(const BufferedStackTrace &) = delete; friend class FastUnwindTest; }; // Check if given pointer points into allocated stack area. static inline bool IsValidFrame(uptr frame, uptr stack_top, uptr stack_bottom) { return frame > stack_bottom && frame < stack_top - 2 * sizeof (uhwptr); } } // namespace __sanitizer // Use this macro if you want to print stack trace with the caller // of the current function in the top frame. #define GET_CALLER_PC_BP \ uptr bp = GET_CURRENT_FRAME(); \ uptr pc = GET_CALLER_PC(); #define GET_CALLER_PC_BP_SP \ GET_CALLER_PC_BP; \ uptr local_stack; \ uptr sp = (uptr)&local_stack // Use this macro if you want to print stack trace with the current // function in the top frame. #define GET_CURRENT_PC_BP \ uptr bp = GET_CURRENT_FRAME(); \ uptr pc = StackTrace::GetCurrentPc() #define GET_CURRENT_PC_BP_SP \ GET_CURRENT_PC_BP; \ uptr local_stack; \ uptr sp = (uptr)&local_stack #endif // SANITIZER_STACKTRACE_H
[ "pengzhuoli@huawei.com" ]
pengzhuoli@huawei.com
6d0180de82152149f12fa2452fd50c9a530a900c
c993b955f1d0e77952c53a2abfe8f582a32a802c
/ref-impl/src/impl/ImplAAFModule.h
15c2eefd614b44026b3198f93e00c7bc7ea2e113
[]
no_license
christianscheuer/aaf
6d67e767f439d6f43c3b7fba64336876bcbc0b8d
0b76dd5bf4f70b0e7b3c33fd6d923ce6f67c71aa
refs/heads/master
2020-05-01T03:08:19.586353
2019-05-01T09:34:40
2019-05-01T09:34:40
177,238,098
0
0
null
2019-03-23T03:12:02
2019-03-23T03:12:02
null
UTF-8
C++
false
false
18,025
h
//=---------------------------------------------------------------------= // // $Id$ $Name$ // // The contents of this file are subject to the AAF SDK Public Source // License Agreement Version 2.0 (the "License"); You may not use this // file except in compliance with the License. The License is available // in AAFSDKPSL.TXT, or you may obtain a copy of the License from the // Advanced Media Workflow Association, Inc., or its successor. // // Software distributed under the License is distributed on an "AS IS" // basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See // the License for the specific language governing rights and limitations // under the License. Refer to Section 3.3 of the License for proper use // of this Exhibit. // // WARNING: Please contact the Advanced Media Workflow Association, // Inc., for more information about any additional licenses to // intellectual property covering the AAF Standard that may be required // to create and distribute AAF compliant products. // (http://www.amwa.tv/policies). // // Copyright Notices: // The Original Code of this file is Copyright 1998-2009, licensor of the // Advanced Media Workflow Association. All rights reserved. // // The Initial Developer of the Original Code of this file and the // licensor of the Advanced Media Workflow Association is // Avid Technology. // All rights reserved. // //=---------------------------------------------------------------------= //////////////////////////////////////////////////////////////////////////////// // @doc // // @module AAFMODULE.CPP - AAF Factory functions for AAF DLL Module | // // Implementation of DLL Exports // // @end // // Tom Ransdell, Avid AAF Development Team // Plugin manager call added by Jeffrey Bedell. // //////////////////////////////////////////////////////////////////////////////// #include "AAFPrivate.h" #include "AAFResult.h" #include "ImplAAFPluginManager.h" #include "ImplAAFFile.h" #include "ImplAAFRawStorage.h" #include "ImplEnumAAFFileEncodings.h" //#include "ImplAAFObjectCreation.h" #include "AAFTypes.h" class ImplAAFFile; class ImplAAFPluginManager; //*********************************************************** // // AAFLoad() // // This is just a stub since the dll will already be loaded // if the client code has linked directly to the export library. // STDAPI ImplAAFLoad(const char * /*dllname*/); //*********************************************************** // // AAFUnload() // // This is just a stub since the dll will be unloaded // when the client code terminates if the client code has // linked directly to the export library. // STDAPI ImplAAFUnload(); //*********************************************************** // // AAFFileOpenExistingRead() // // Creates an object associated with with an existing // filesystem file that contains data which is only to be read. // Does the following: // - Opens the existing named file in the filesystem for reading. // - Associates an object with that filesystem file. // - Places the object into the Open-read-only state. // - This AAFFile object then can be used as the root of the // containment tree representing all AAF objects contained within // the file. // // Succeeds if: // - The pFileName argument is valid. // - Only valid flags have been specified. // - A valid combination of flags has been specified. // - The named file exists in the filesystem. // - The named filesystem file is readable. // - The named file represents itself as a valid AAF file. Even if // this succeeds, it is not guaranteed that the named file is in // fact a valid AAF file. // // This function will return the following codes. If more than one of // the listed errors is in effect, it will return the first one // encountered in the order given below: // // AAFRESULT_SUCCESS // - succeeded. (This is the only code indicating success.) // // AAFRESULT_NULL_PARAM // - the pFileName pointer arg is NULL. // // AAFRESULT_BAD_FLAGS // - one or more illegal flags were specified. // // AAFRESULT_BAD_FLAG_COMBINATION // - illegal combination of otherwise valid flags was specified. // // AAFRESULT_FILE_NOT_FOUND // - The named file does not exist in the filesystem. // // AAFRESULT_NOT_READABLE // - The named file cannot be read. // // AAFRESULT_NOT_AAF_FILE // - The named file does not claim to be a valid AAF file. // STDAPI ImplAAFFileOpenExistingRead ( // Null-terminated string containing name of filesystem file to be // opened for reading. Filename must be in a form that would be // acceptable to StgOpenStorage() for this platform. /*[in, string]*/ const aafCharacter * pFileName, // File open mode flags. May be any of the following ORed together. // All other bits must be set to zero. // - kAAFFileModeUnbuffered - to indicate buffered mode. Default // is buffered. /*[in]*/ aafUInt32 modeFlags, // Pointer to buffer to receive pointer to new file. /*[out]*/ ImplAAFFile ** ppFile); //*********************************************************** // // AAFFileOpenExistingModify() // // Creates an object associated with with an existing // filesystem file that contains data which is to be read and // written. Associates the given identification with it. // Does the following: // - Opens the existing named file in the filesystem for reading and // writing. // - Associates an object with that filesystem file. // - Places the object into the Open-read-write state. // - This AAFFile object then can be used as the root of the // containment tree representing all AAF objects contained within // the file. // // Succeeds if: // - This object is currently Closed. // - The pFileName argument is valid. // - The pIdent argument is valid. // - Only valid flags have been specified. // - A valid combination of flags has been specified. // - The named file exists in the filesystem. // - The named filesystem file is readable. // - The named filesystem file is writable. // - The named file represents itself as a valid AAF file. Even if // this succeeds, it is not guaranteed that the named file is in // fact a valid AAF file. // // This function will return the following codes. If more than one of // the listed errors is in effect, it will return the first one // encountered in the order given below: // // AAFRESULT_SUCCESS // - succeeded. (This is the only code indicating success.) // // AAFRESULT_NULL_PARAM // - either pFileName or pIdent pointer argument is NULL. // // AAFRESULT_BAD_FLAGS // - one or more illegal flags were specified. // // AAFRESULT_BAD_FLAG_COMBINATION // - illegal combination of otherwise valid flags was specified. // // AAFRESULT_FILE_NOT_FOUND // - The named file does not exist in the filesystem. // // AAFRESULT_NOT_READABLE // - The named file cannot be read. // // AAFRESULT_NOT_WRITEABLE // - The named file cannot be written. // // AAFRESULT_NOTAAFFILE // - The named file is not a valid AAF file. // STDAPI ImplAAFFileOpenExistingModify ( // Null-terminated string containing name of filesystem file to be // opened for modification. Filename must be in a form that would // be acceptable to StgOpenStorage() for this platform. /*[in, string]*/ const aafCharacter * pFileName, // File open mode flags. May be any of the following ORed together. // All other bits must be set to zero. // - kAAFFileModeUnbuffered - to indicate unbuffered mode. // Default is buffered. // - kAAFFileModeRevertable - to indicate that Revert is possible // on this file (for all changes except those to essence). /*[in]*/ aafUInt32 modeFlags, // Identification of the application which is modifying this file. /*[in]*/ aafProductIdentification_t * pIdent, // Pointer to buffer to receive pointer to new file. /*[out]*/ ImplAAFFile ** ppFile); //*********************************************************** // // AAFFileOpenNewModify() // // Creates an object associated with with a new // filesystem file that contains data which is to be read and // written. Associates the given identification with it. // Does the following: // - Creates a new file in the filesystem with the given name. // - Opens the filesystem file for reading and writing. // - Associates this object with that filesystem file. // - Places this object into the Open state. // - This AAFFile object then can be used as the root of the // containment tree representing all AAF objects contained within // the file. // // Succeeds if: // - The pFileName argument is valid. // - The pIdent argument is valid. // - Only valid flags have been specified. // - A valid combination of flags has been specified. // - The named file does not exists in the filesystem. // - There is sufficient space in the filesystem to create the file. // // This function will return the following codes. If more than one of // the listed errors is in effect, it will return the first one // encountered in the order given below: // // AAFRESULT_SUCCESS // - succeeded. (This is the only code indicating success.) // // AAFRESULT_NULL_PARAM // - either pFileName or pIdent pointer argument is NULL. // // AAFRESULT_BAD_FLAGS // - one or more illegal flags were specified. // // AAFRESULT_BAD_FLAG_COMBINATION // - illegal combination of otherwise valid flags was specified. // // AAFRESULT_FILE_EXISTS // - The named file already exists in the filesystem. // // AAFRESULT_INSUFFICIENT_SPACE // - There is insufficient space in the filesystem to create this // file. // STDAPI ImplAAFFileOpenNewModify ( // Null-terminated string containing name of filesystem file to be // opened for modification. Filename must be in a form that would // be acceptable to StgOpenStorage() for this platform. /*[in, string]*/ const aafCharacter * pFileName, // File open mode flags. May be any of the following ORed together. // All other bits must be set to zero. // - kAAFFileModeUnbuffered - to indicate unbuffered mode. // Default is buffered. // - kAAFFileModeRevertable - to indicate that Revert is possible // on this file (for all changes except those to essence). /*[in]*/ aafUInt32 modeFlags, // Identification of the application which is creating this file. /*[in]*/ aafProductIdentification_t * pIdent, // Pointer to buffer to receive pointer to new file. /*[out]*/ ImplAAFFile ** ppFile); //*********************************************************** // // AAFFileOpenNewModifyEx() // // Please see AAF.h for comments. // STDAPI ImplAAFFileOpenNewModifyEx ( const aafCharacter * pFileName, aafUID_constptr pFileKind, aafUInt32 modeFlags, aafProductIdentification_t * pIdent, ImplAAFFile ** ppFile); //*********************************************************** // // AAFFileOpenTransient() // // Creates an object associated with with a transient file, // meaning that it is not associated with any filesystem file but // may still be used to contain AAF objects as if it was associated // with a filesystem file. Associates the given identification with // this file. // // Transient files are never considered Revertable. // // NOTE! Stub only. Implementation not yet added. // // Succeeds if: // - This object has already been Initialize()d. // - The pIdent argument is valid. // - This object is currently closed. // // This function will return the following codes. If more than one of // the listed errors is in effect, it will return the first one // encountered in the order given below: // // AAFRESULT_SUCCESS // - succeeded. (This is the only code indicating success.) // // AAFRESULT_NOT_INITIALIZED // - This object has not yet had Initialize() called on it. // // AAFRESULT_ALREADY_OPEN // - This object is already open. // // AAFRESULT_NULL_PARAM // - the pIdent pointer argument is NULL. // STDAPI ImplAAFFileOpenTransient ( // Identification which is to be associated with this file. /*[in]*/ aafProductIdentification_t * pIdent, // Pointer to buffer to receive pointer to new file. /*[out]*/ ImplAAFFile ** ppFile); //*********************************************************** // // AAFFileIsAAFFile() // // Please see AAF.h for comments. // STDAPI ImplAAFFileIsAAFFile ( const aafCharacter * pFileName, aafUID_t * pAAFFileKind, aafBool * pFileIsAAFFile); //*********************************************************** // // AAFRawStorageIsAAFFile() // // Please see AAF.h for comments. // STDAPI ImplAAFRawStorageIsAAFFile ( IAAFRawStorage * pRawStorage, aafUID_t * pAAFFileKind, aafBool * pRawStorageIsAAFFile); //*********************************************************** // // ImplAAFFileIsAAFFileKind() // STDAPI ImplAAFFileIsAAFFileKind ( aafCharacter_constptr pFileName, aafUID_constptr pAAFFileKind, aafBool * pFileIsAAFFile); //*********************************************************** // // ImplAAFRawStorageIsAAFFileKind() // // STDAPI ImplAAFRawStorageIsAAFFileKind ( IAAFRawStorage * /*pRawStorage*/, aafUID_constptr /*pAAFFileKind*/, aafBool * /*pRawStorageIsAAFFile*/); //*********************************************************** // // AAFLoadPluginManager() // // Returns a instance of the singleton plugin manager. // // This function will return the following codes. If more than one of // the listed errors is in effect, it will return the first one // encountered in the order given below: // // AAFRESULT_SUCCESS // - succeeded. (This is the only code indicating success.) // // AAFRESULT_NULL_PARAM // - the pIdent pointer argument is NULL. // STDAPI ImplAAFGetPluginManager ( /*[out]*/ ImplAAFPluginManager ** ppManager); STDAPI ImplAAFCreateRawStorageMemory (aafFileAccess_t access, ImplAAFRawStorage ** ppNewRawStorage); STDAPI ImplAAFCreateRawStorageDisk (aafCharacter_constptr pFilename, aafFileExistence_t existence, aafFileAccess_t access, ImplAAFRawStorage ** ppNewRawStorage); STDAPI ImplAAFCreateRawStorageCachedDisk (aafCharacter_constptr pFilename, aafFileExistence_t existence, aafFileAccess_t access, aafUInt32 pageCount, aafUInt32 pageSize, ImplAAFRawStorage ** ppNewRawStorage); STDAPI ImplAAFCreateRawStorageCached (IAAFRawStorage * pRawStorage, aafUInt32 pageCount, aafUInt32 pageSize, ImplAAFRawStorage ** ppNewRawStorage); STDAPI ImplAAFCreateRawStorageCached2 (IAAFRawStorage * pRawStorage, aafUInt32 pageCount, aafUInt32 pageSize, IAAFCachePageAllocator * pCachePageAllocator, ImplAAFRawStorage ** ppNewRawStorage); STDAPI ImplAAFCreateAAFFileOnRawStorage (IAAFRawStorage * pRawStorage, aafFileExistence_t existence, aafFileAccess_t access, aafUID_constptr pFileKind, aafUInt32 modeFlags, aafProductIdentification_constptr pIdent, ImplAAFFile ** ppNewFile); STDAPI ImplAAFSetProgressCallback (IAAFProgress * pProgress); //*********************************************************** // // ImplAAFGetFileEncodings() // // Returns an enumeration of file encodings supported by this version // of the library. // // This method will succeed if the following are true: // - The ppFileEncodings pointer is valid. // // This method will return the following codes. If more than one of // the listed errors is in effect, it will return the first one // encountered in the order given below: // // AAFRESULT_SUCCESS // - succeeded. (This is the only code indicating success.) // // AAFRESULT_NULL_PARAM // - ppFileEncodings arg is NULL. // STDAPI ImplAAFGetFileEncodings (ImplEnumAAFFileEncodings** ppFileEncodings); //*********************************************************** // // ImplAAFSetDiagnosticOutput() // // Makes the specified stream the AAF Toolkit's diagnostic output stream // // This method will succeed if the following are true: // - The pOutput pointer is valid. // // This method will return the following codes. If more than one of // the listed errors is in effect, it will return the first one // encountered in the order given below: // // AAFRESULT_SUCCESS // - succeeded. (This is the only code indicating success.) // // AAFRESULT_NULL_PARAM // - pOutput arg is NULL. // STDAPI ImplAAFSetDiagnosticOutput (IAAFDiagnosticOutput* pOutput); //*********************************************************** // // ImplAAFGetLibraryVersion() // // Return the version of the AAF library currently // running on this machine\, which implements these interfaces. // // Succeeds if all of the following are true: // - the pVersion pointer is valid. // // If this method fails nothing is written to *pVersion. // // This method will return the following codes. If more than one of // the listed errors is in effect\, it will return the first one // encountered in the order given below: // // AAFRESULT_SUCCESS // - succeeded. (This is the only code indicating success.) // // AAFRESULT_NULL_PARAM // - pVersion is null. // STDAPI ImplAAFGetLibraryVersion (aafProductVersion_t * pVersion); extern const aafProductVersion_t AAFReferenceImplementationVersion; // The real AAFGetStaticLibraryVersion is implemented in aaflib. // This function is here for two reasons: // 1. The dodo machinery requires it // 2. If someone were to link directly to the AAF DLL (rather than load // via aaflib's functionality), then they have the corresponding // function. // Thus, this function is implemented with the second case in mind. // However, this function has no meaning in that context, thus NOT_IMPLEMENTED // is always returned. STDAPI ImplAAFGetStaticLibraryVersion (aafProductVersion_t * pVersion); STDAPI ImplAAFGetLibraryPathNameBufLen (aafUInt32 * pBufSize); STDAPI ImplAAFGetLibraryPathName (aafCharacter * pLibraryPathName, aafUInt32 bufSize); STDAPI ImplAAFResultToTextBufLen ( AAFRESULT result, aafUInt32 * pResultTextSize); STDAPI ImplAAFResultToText ( AAFRESULT result, aafCharacter * pResultText, aafUInt32 resultTextSize);
[ "" ]
26af8efe427529c77dc1fd7b34f8920d9dbf207a
880387c837ed0a6e0002bb0e549413d892fd432c
/src/qt/multisigdialog.cpp
16330b55898569b00a23c7c42d6a11e1555a27bc
[ "MIT" ]
permissive
bitcoin-token/Bitcoin-Turbo-Koin-Core
442bd64d7488487bffb15b6611ca4c85ee4ca2ff
4dcfed3192bb1085f685c86211ed08c68c20c7a3
refs/heads/master
2020-04-27T10:14:32.071751
2019-03-06T00:52:29
2019-03-06T00:52:29
174,245,608
5
6
null
null
null
null
UTF-8
C++
false
false
39,838
cpp
// Copyright (c) 2017-2018 The PIVX developers // Copyright (c) 2019 The BTK developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "multisigdialog.h" #include "forms/ui_multisigdialog.h" #include "askpassphrasedialog.h" #include "primitives/transaction.h" #include "addressbookpage.h" #include "utilstrencodings.h" #include "core_io.h" #include "script/script.h" #include "base58.h" #include "coins.h" #include "keystore.h" #include "init.h" #include "wallet.h" #include "script/sign.h" #include "script/interpreter.h" #include "utilmoneystr.h" #include "guiutil.h" #include "qvalidatedlineedit.h" #include "bitcoinamountfield.h" #include <QVariant> #include <QHBoxLayout> #include <QLabel> #include <QPushButton> #include <QToolButton> #include <QSpinBox> #include <QClipboard> #include <QDebug> #include <QArgument> #include <QtGlobal> #include <QString> MultisigDialog::MultisigDialog(QWidget* parent) : QDialog(parent, Qt::WindowSystemMenuHint | Qt::WindowTitleHint | Qt::WindowCloseButtonHint), ui(new Ui::MultisigDialog), model(0) { ui->setupUi(this); multisigTx = CMutableTransaction(); //flag to show keyScrollArea on first priv key added isFirstPrivKey = true; isFirstRawTx = true; ui->keyScrollArea->hide(); ui->txInputsScrollArea->hide(); connect(ui->commitButton, SIGNAL(clicked()), this, SLOT(commitMultisigTx())); //populate lists with initial objects on_addAddressButton_clicked(); on_addAddressButton_clicked(); on_addDestinationButton_clicked(); this->setStyleSheet(GUIUtil::loadStyleSheet()); } MultisigDialog::~MultisigDialog() { delete ui; } void MultisigDialog::setModel(WalletModel *model) { this->model = model; } void MultisigDialog::showTab(int index) { ui->multisigTabWidget->setCurrentIndex(index); this->show(); } void MultisigDialog::updateCoinControl(CAmount nAmount, unsigned int nQuantity) { ui->labelAmount_int->setText(QString::fromStdString(FormatMoney(nAmount))); ui->labelQuantity_int->setText(QString::number(nQuantity)); } /** * Private Slots */ //slot for pasting addresses void MultisigDialog::pasteText() { QWidget* pasteButton = qobject_cast<QWidget*>(sender()); if(!pasteButton)return; QFrame* addressFrame = qobject_cast<QFrame*>(pasteButton->parentWidget()); if(!addressFrame)return; QValidatedLineEdit* vle = addressFrame->findChild<QValidatedLineEdit*>("address"); if(!vle)return; vle->setText(QApplication::clipboard()->text()); } //slot for deleting QFrames with the delete buttons void MultisigDialog::deleteFrame() { QWidget *buttonWidget = qobject_cast<QWidget*>(sender()); if(!buttonWidget)return; //if deleting last raw input/priv key, hide scroll area if(buttonWidget->objectName() == "inputDeleteButton" && ui->inputsList->count() == 1){ isFirstRawTx = true; ui->txInputsScrollArea->hide(); }else if(buttonWidget->objectName() == "keyDeleteButton" && ui->keyList->count() == 1){ isFirstPrivKey = true; ui->keyScrollArea->hide(); } QFrame* frame = qobject_cast<QFrame*>(buttonWidget->parentWidget()); if(!frame)return; //figure out which frame was updated so we can update the correct list bool destinationFrame = false, addressFrame = false, keyFrame = false, txInputFrame = false; if (frame->objectName() == QString::fromStdString("destinationFrame")) destinationFrame = true; else if (frame->objectName() == QString::fromStdString("addressFrame")) addressFrame = true; else if (frame->objectName() == QString::fromStdString("keyFrame")) keyFrame = true; else if (frame->objectName() == QString::fromStdString("txInputFrame")) txInputFrame = true; delete frame; //update the correct list inputs //using else-if instead of else to stop accidental Seg faults //if method is called on a frame that isn't a destinationFrame, addressFrame, keyFrame, txInputFrame if (addressFrame) { for (int i = 0; i < ui->addressList->count(); i++) { QWidget *input = qobject_cast<QWidget *>(ui->addressList->itemAt(i)->widget()); QLabel *addressLabel = input->findChild<QLabel *>("addressLabel"); addressLabel->setText(QApplication::translate("MultisigDialog", strprintf("Address / Key %i:", i + 1).c_str(), 0)); } } else if (destinationFrame) { for (int i = 0; i < ui->destinationsList->count(); i++) { QWidget *input = qobject_cast<QWidget *>(ui->destinationsList->itemAt(i)->widget()); QLabel *destinationAddressLabel = input->findChild<QLabel *>("destinationAddressLabel"); destinationAddressLabel->setText(QApplication::translate("MultisigDialog", strprintf("%i. Address: ", i + 1).c_str(), 0)); } } else if (keyFrame) { for (int i = 0; i < ui->keyList->count(); i++) { QWidget *input = qobject_cast<QWidget *>(ui->keyList->itemAt(i)->widget()); QLabel *keyListLabel = input->findChild<QLabel *>("keyLabel"); keyListLabel->setText(QApplication::translate("MultisigDialog", strprintf("Key %i: ", i + 1).c_str(), 0)); } } else if (txInputFrame) { for (int i = 0; i < ui->inputsList->count(); i++) { QWidget *input = qobject_cast<QWidget *>(ui->inputsList->itemAt(i)->widget()); QLabel *txInputIdLabel = input->findChild<QLabel *>("txInputIdLabel"); txInputIdLabel->setText(QApplication::translate("MultisigDialog", strprintf("%i. Tx Hash: ", i + 1).c_str(), 0)); } } } //slot to open address book dialog void MultisigDialog::addressBookButtonReceiving() { QWidget* addressButton = qobject_cast<QWidget*>(sender()); if(!addressButton)return; QFrame* addressFrame = qobject_cast<QFrame*>(addressButton->parentWidget()); if(!addressFrame)return; QValidatedLineEdit* vle = addressFrame->findChild<QValidatedLineEdit*>("address"); if(!vle)return; if (model && model->getAddressTableModel()) { AddressBookPage dlg(AddressBookPage::ForSelection, AddressBookPage::ReceivingTab, this); dlg.setModel(model->getAddressTableModel()); if (dlg.exec()) { vle->setText(dlg.getReturnValue()); } } } //create address void MultisigDialog::on_addMultisigButton_clicked() { if(!model) return; int m = ui->enterMSpinbox->value(); vector<string> keys; for (int i = 0; i < ui->addressList->count(); i++) { QWidget* address = qobject_cast<QWidget*>(ui->addressList->itemAt(i)->widget()); QValidatedLineEdit* vle = address->findChild<QValidatedLineEdit*>("address"); if(!vle->text().isEmpty()){ keys.push_back(vle->text().toStdString()); } } addMultisig(m, keys); } void MultisigDialog::on_importAddressButton_clicked(){ if(!model) return; string sRedeem = ui->importRedeem->text().toStdString(); if(sRedeem.empty()){ ui->addMultisigStatus->setStyleSheet("QLabel { color: red; }"); ui->addMultisigStatus->setText("Import box empty!"); return; } vector<string> vRedeem; size_t pos = 0; //search redeem input delimited by space while ((pos = sRedeem.find(" ")) != std::string::npos) { vRedeem.push_back(sRedeem.substr(0, pos)); sRedeem.erase(0, pos + 1); } vector<string> keys(vRedeem.begin()+1, vRedeem.end()-1); addMultisig(stoi(vRedeem[0]), keys); // rescan to find txs associated with imported address pwalletMain->ScanForWalletTransactions(chainActive.Genesis(), true); pwalletMain->ReacceptWalletTransactions(); } bool MultisigDialog::addMultisig(int m, vector<string> keys){ try{ string error; CScript redeem; if(!createRedeemScript(m, keys, redeem, error)){ throw runtime_error(error.data()); } if (::IsMine(*pwalletMain, redeem) == ISMINE_SPENDABLE){ throw runtime_error("The wallet already contains this script"); } if(!pwalletMain->AddCScript(redeem)){ throw runtime_error("Failure: address invalid or already exists"); } CScriptID innerID(redeem); string label = ui->multisigAddressLabel->text().toStdString(); pwalletMain->SetAddressBook(innerID, label, "receive"); if (!pwalletMain->AddMultiSig(redeem)){ throw runtime_error("Failure: unable to add address as watch only"); } ui->addMultisigStatus->setStyleSheet("QLabel { color: black; }"); ui->addMultisigStatus->setText("Multisignature address " + QString::fromStdString(CBitcoinAddress(innerID).ToString()) + " has been added to the wallet.\nSend the redeem below for other owners to import:\n" + QString::fromStdString(redeem.ToString())); }catch(const runtime_error& e) { ui->addMultisigStatus->setStyleSheet("QLabel { color: red; }"); ui->addMultisigStatus->setText(tr(e.what())); return false; } return true; } //spend void MultisigDialog::on_createButton_clicked() { if(!model) return; vector<CTxIn> vUserIn; vector<CTxOut> vUserOut; try{ //Add inputs from Coin Control if any are selected if (CoinControlDialog::coinControl->HasSelected()) { vector<COutPoint> vSelected; CoinControlDialog::coinControl->ListSelected(vSelected); for (auto outpoint : vSelected) vUserIn.emplace_back(CTxIn(outpoint)); }else{//check for raw inputs for(int i = 0; i < ui->inputsList->count(); i++){ QWidget* input = qobject_cast<QWidget*>(ui->inputsList->itemAt(i)->widget()); QLineEdit* txIdLine = input->findChild<QLineEdit*>("txInputId"); if(txIdLine->text().isEmpty()){ ui->createButtonStatus->setStyleSheet("QLabel { color: red; }"); ui->createButtonStatus->setText(tr("Invalid Tx Hash.")); return; } QSpinBox* txVoutLine = input->findChild<QSpinBox*>("txInputVout"); int nOutput = txVoutLine->value(); if(nOutput < 0){ ui->createButtonStatus->setStyleSheet("QLabel { color: red; }"); ui->createButtonStatus->setText(tr("Vout position must be positive.")); return; } uint256 txid = uint256S(txIdLine->text().toStdString()); CTxIn in(COutPoint(txid, nOutput)); vUserIn.emplace_back(in); } } //validate destinations bool validInput = true; for(int i = 0; i < ui->destinationsList->count(); i++){ QWidget* dest = qobject_cast<QWidget*>(ui->destinationsList->itemAt(i)->widget()); QValidatedLineEdit* addr = dest->findChild<QValidatedLineEdit*>("destinationAddress"); BitcoinAmountField* amt = dest->findChild<BitcoinAmountField*>("destinationAmount"); CBitcoinAddress address; bool validDest = true; if(!model->validateAddress(addr->text())){ addr->setValid(false); validDest = false; }else{ address = CBitcoinAddress(addr->text().toStdString()); } if(!amt->validate()){ amt->setValid(false); validDest = false; } if(!validDest){ validInput = false; continue; } CScript scriptPubKey = GetScriptForDestination(address.Get()); CTxOut out(amt->value(), scriptPubKey); vUserOut.push_back(out); } //if all user data valid create a multisig tx if(validInput){ //clear member variable multisigTx = CMutableTransaction(); string error; string fee; if(!createMultisigTransaction(vUserIn, vUserOut, fee, error)){ throw runtime_error(error); } //display status string ui->createButtonStatus->setStyleSheet("QTextEdit{ color: black }"); QString status(strprintf("Transaction has successfully created with a fee of %s.\n" "The transaction has been automatically imported to the sign tab.\n" "Please continue on to sign the tx from this wallet, to access the hex to send to other owners.", fee).c_str()); ui->createButtonStatus->setText(status); ui->transactionHex->setText(QString::fromStdString(EncodeHexTx(multisigTx))); } }catch(const runtime_error& e){ ui->createButtonStatus->setStyleSheet("QTextEdit{ color: red }"); ui->createButtonStatus->setText(tr(e.what())); } } bool MultisigDialog::createMultisigTransaction(vector<CTxIn> vUserIn, vector<CTxOut> vUserOut, string& feeStringRet, string& errorRet) { try{ //attempt to access the given inputs CCoinsViewCache view = getInputsCoinsViewCache(vUserIn); //retrieve total input val and change dest CAmount totalIn = 0; vector<CAmount> vInputVals; CScript changePubKey; bool fFirst = true; for(CTxIn in : vUserIn){ const CCoins* coins = view.AccessCoins(in.prevout.hash); if(!coins->IsAvailable(in.prevout.n) || coins == NULL){ continue; } CTxOut prevout = coins->vout[in.prevout.n]; CScript privKey = prevout.scriptPubKey; vInputVals.push_back(prevout.nValue); totalIn += prevout.nValue; if(!fFirst){ if(privKey != changePubKey){ throw runtime_error("Address mismatch! Inputs must originate from the same multisignature address."); } }else{ fFirst = false; changePubKey = privKey; } } CAmount totalOut = 0; //retrieve total output val for(CTxOut out : vUserOut){ totalOut += out.nValue; } if(totalIn < totalOut){ throw runtime_error("Not enough BTK provided as input to complete transaction (including fee)."); } //calculate change amount CAmount changeAmount = totalIn - totalOut; CTxOut change(changeAmount, changePubKey); //generate random position for change unsigned int changeIndex = rand() % (vUserOut.size() + 1); //insert change into random position if(changeIndex < vUserOut.size()){ vUserOut.insert(vUserOut.begin() + changeIndex, change); }else{ vUserOut.emplace_back(change); } //populate tx CMutableTransaction tx; tx.vin = vUserIn; tx.vout = vUserOut; const CCoins* coins = view.AccessCoins(tx.vin[0].prevout.hash); if(coins == NULL || !coins->IsAvailable(tx.vin[0].prevout.n)){ throw runtime_error("Coins unavailable (unconfirmed/spent)"); } CScript prevPubKey = coins->vout[tx.vin[0].prevout.n].scriptPubKey; //get payment destination CTxDestination address; if(!ExtractDestination(prevPubKey, address)){ throw runtime_error("Could not find address for destination."); } CScriptID hash = boost::get<CScriptID>(address); CScript redeemScript; if (!pwalletMain->GetCScript(hash, redeemScript)){ throw runtime_error("could not redeem"); } txnouttype type; vector<CTxDestination> addresses; int nReq; if(!ExtractDestinations(redeemScript, type, addresses, nReq)){ throw runtime_error("Could not extract destinations from redeem script."); } for(CTxIn& in : tx.vin){ in.scriptSig.clear(); //scale estimate to account for multisig scriptSig for(unsigned int i = 0; i < 50*(nReq+addresses.size()); i++){ in.scriptSig << INT64_MAX; } } //calculate fee unsigned int nBytes = tx.GetSerializeSize(SER_NETWORK, PROTOCOL_VERSION); CAmount fee = ::minRelayTxFee.GetFee(nBytes); if(tx.vout.at(changeIndex).nValue > fee){ tx.vout.at(changeIndex).nValue -= fee; feeStringRet = strprintf("%d",((double)fee)/COIN).c_str(); }else{ throw runtime_error("Not enough BTK provided to cover fee"); } //clear junk from script sigs for(CTxIn& in : tx.vin){ in.scriptSig.clear(); } multisigTx = tx; }catch(const runtime_error& e){ errorRet = e.what(); return false; } return true; } //sign void MultisigDialog::on_signButton_clicked() { if(!model) return; try{ //parse tx hex CTransaction txRead; if(!DecodeHexTx(txRead, ui->transactionHex->text().toStdString())){ throw runtime_error("Failed to decode transaction hex!"); } CMutableTransaction tx(txRead); //check if transaction is already fully verified if(isFullyVerified(tx)){ this->multisigTx = tx; ui->commitButton->setEnabled(true); ui->signButtonStatus->setText("This transaction is ready to commit. \nThe commit button in now enabled."); return; } string errorOut = string(); bool fComplete = signMultisigTx(tx, errorOut, ui->keyList); if(!errorOut.empty()){ throw runtime_error(errorOut.data()); }else{ this->multisigTx = tx; } ui->signButtonStatus->setStyleSheet("QTextEdit{ color: black }"); ui->signButtonStatus->setText(buildMultisigTxStatusString(fComplete, tx)); }catch(const runtime_error& e){ ui->signButtonStatus->setStyleSheet("QTextEdit{ color: red }"); ui->signButtonStatus->setText(tr(e.what())); } } /*** *private helper functions */ QString MultisigDialog::buildMultisigTxStatusString(bool fComplete, const CMutableTransaction& tx) { string sTxHex = EncodeHexTx(tx); if(fComplete){ ui->commitButton->setEnabled(true); string sTxId = tx.GetHash().GetHex(); string sTxComplete = "Complete: true!\n" "The commit button has now been enabled for you to finalize the transaction.\n" "Once the commit button is clicked, the transaction will be published and coins transferred " "to their destinations.\nWARNING: THE ACTIONS OF THE COMMIT BUTTON ARE FINAL AND CANNOT BE REVERSED."; return QString(strprintf("%s\nTx Id:\n%s\nTx Hex:\n%s",sTxComplete, sTxId, sTxHex).c_str()); } else { string sTxIncomplete = "Complete: false.\n" "You may now send the hex below to another owner to sign.\n" "Keep in mind the transaction must be passed from one owner to the next for signing.\n" "Ensure all owners have imported the redeem before trying to sign. (besides creator)"; return QString(strprintf("%s\nTx Hex: %s", sTxIncomplete, sTxHex).c_str()); } } CCoinsViewCache MultisigDialog::getInputsCoinsViewCache(const vector<CTxIn>& vin) { CCoinsView viewDummy; CCoinsViewCache view(&viewDummy); { LOCK(mempool.cs); CCoinsViewCache& viewChain = *pcoinsTip; CCoinsViewMemPool viewMempool(&viewChain, mempool); view.SetBackend(viewMempool); // temporarily switch cache backend to db+mempool view for(const CTxIn& txin : vin) { const uint256& prevHash = txin.prevout.hash; view.AccessCoins(prevHash); // this is certainly allowed to fail } view.SetBackend(viewDummy); // switch back to avoid locking mempool for too long } return view; } bool MultisigDialog::signMultisigTx(CMutableTransaction& tx, string& errorOut, QVBoxLayout* keyList) { //will be set false if all inputs are not fully signed(valid) bool fComplete = true; //if keyslist is not default value AND has items in list then true bool fGivenKeys = (keyList != nullptr) && (keyList->count() > 0); try{ //copy of vin for reference before vin is mutated vector<CTxIn> oldVin(tx.vin); CBasicKeyStore privKeystore; //if keys were given, attempt to collect redeem and scriptpubkey if(fGivenKeys){ for(int i = 0; i < keyList->count(); i++){ QWidget* keyFrame = qobject_cast<QWidget*>(keyList->itemAt(i)->widget()); QLineEdit* key = keyFrame->findChild<QLineEdit*>("key"); CBitcoinSecret vchSecret; if (!vchSecret.SetString(key->text().toStdString())) throw runtime_error("Invalid private key"); CKey cKey = vchSecret.GetKey(); if (!cKey.IsValid()) throw runtime_error("Private key outside allowed range"); privKeystore.AddKey(cKey); } for(CTxIn& txin : tx.vin){ //get inputs CTransaction txVin; uint256 hashBlock; if (!GetTransaction(txin.prevout.hash, txVin, hashBlock, true)) throw runtime_error("txin could not be found"); if (hashBlock == 0) throw runtime_error("txin is unconfirmed"); //get pubkey from input CScript prevPubKey = txVin.vout[txin.prevout.n].scriptPubKey; //get payment destination CTxDestination address; if(!ExtractDestination(prevPubKey, address)){ throw runtime_error("Could not find address for destination."); } //get redeem script related to destination CScriptID hash = boost::get<CScriptID>(address); CScript redeemScript; if (!pwalletMain->GetCScript(hash, redeemScript)){ errorOut = "could not redeem"; } privKeystore.AddCScript(redeemScript); } }else{ if (model->getEncryptionStatus() == model->Locked) { if (!model->requestUnlock(AskPassphraseDialog::Context::Multi_Sig, true).isValid()) { // Unlock wallet was cancelled throw runtime_error("Error: Your wallet is locked. Please enter the wallet passphrase first."); } } } //choose between local wallet and provided const CKeyStore& keystore = fGivenKeys ? privKeystore : *pwalletMain; //attempt to sign each input from local wallet int nIn = 0; for(CTxIn& txin : tx.vin){ //get inputs CTransaction txVin; uint256 hashBlock; if (!GetTransaction(txin.prevout.hash, txVin, hashBlock, true)) throw runtime_error("txin could not be found"); if (hashBlock == 0) throw runtime_error("txin is unconfirmed"); txin.scriptSig.clear(); CScript prevPubKey = txVin.vout[txin.prevout.n].scriptPubKey; //sign what we can SignSignature(keystore, prevPubKey, tx, nIn); //merge in any previous signatures txin.scriptSig = CombineSignatures(prevPubKey, tx, nIn, txin.scriptSig, oldVin[nIn].scriptSig); if (!VerifyScript(txin.scriptSig, prevPubKey, STANDARD_SCRIPT_VERIFY_FLAGS, MutableTransactionSignatureChecker(&tx, nIn))){ fComplete = false; } nIn++; } ui->signButtonStatus->setText(buildMultisigTxStatusString(fComplete, tx)); }catch(const runtime_error& e){ errorOut = string(e.what()); fComplete = false; } return fComplete; } // quick check for an already fully signed tx bool MultisigDialog::isFullyVerified(CMutableTransaction& tx){ try{ int nIn = 0; for(CTxIn& txin : tx.vin){ CTransaction txVin; uint256 hashBlock; if (!GetTransaction(txin.prevout.hash, txVin, hashBlock, true)){ throw runtime_error("txin could not be found"); } if (hashBlock == 0){ throw runtime_error("txin is unconfirmed"); } //get pubkey from this input as output in last tx CScript prevPubKey = txVin.vout[txin.prevout.n].scriptPubKey; if (!VerifyScript(txin.scriptSig, prevPubKey, STANDARD_SCRIPT_VERIFY_FLAGS, MutableTransactionSignatureChecker(&tx, nIn))){ return false; } nIn++; } }catch(const runtime_error& e){ return false; } return true; } void MultisigDialog::commitMultisigTx() { CMutableTransaction tx(multisigTx); try{ #ifdef ENABLE_WALLET CWalletTx wtx(pwalletMain, tx); CReserveKey keyChange(pwalletMain); if (!pwalletMain->CommitTransaction(wtx, keyChange)) throw runtime_error(string("Transaction rejected - Failed to commit")); #else uint256 hashTx = tx.GetHash(); CCoinsViewCache& view = *pcoinsTip; const CCoins* existingCoins = view.AccessCoins(hashTx); bool fOverrideFees = false; bool fHaveMempool = mempool.exists(hashTx); bool fHaveChain = existingCoins && existingCoins->nHeight < 1000000000; if (!fHaveMempool && !fHaveChain) { // push to local node and sync with wallets CValidationState state; if (!AcceptToMemoryPool(mempool, state, tx, false, NULL, !fOverrideFees)) { if (state.IsInvalid()) throw runtime_error(strprintf("Transaction rejected - %i: %s", state.GetRejectCode(), state.GetRejectReason())); else throw runtime_error(string("Transaction rejected - ") + state.GetRejectReason()); } } else if (fHaveChain) { throw runtime_error("transaction already in block chain"); } RelayTransaction(tx); #endif //disable commit if successfully committed ui->commitButton->setEnabled(false); ui->signButtonStatus->setText(strprintf("Transaction has been successfully published with transaction ID:\n %s", tx.GetHash().GetHex()).c_str()); }catch(const runtime_error& e){ ui->signButtonStatus->setText(e.what()); } } bool MultisigDialog::createRedeemScript(int m, vector<string> vKeys, CScript& redeemRet, string& errorRet) { try{ int n = vKeys.size(); //gather pub keys if (n < 1) throw runtime_error("a Multisignature address must require at least one key to redeem"); if (n < m) throw runtime_error( strprintf("not enough keys supplied " "(got %d keys, but need at least %d to redeem)", m, n)); if (n > 15) throw runtime_error("Number of addresses involved in the Multisignature address creation > 15\nReduce the number"); vector<CPubKey> pubkeys; pubkeys.resize(n); int i = 0; for(vector<string>::iterator it = vKeys.begin(); it != vKeys.end(); ++it) { string keyString = *it; #ifdef ENABLE_WALLET // Case 1: BTK address and we have full public key: CBitcoinAddress address(keyString); if (pwalletMain && address.IsValid()) { CKeyID keyID; if (!address.GetKeyID(keyID)) { throw runtime_error( strprintf("%s does not refer to a key", keyString)); } CPubKey vchPubKey; if (!pwalletMain->GetPubKey(keyID, vchPubKey)) throw runtime_error( strprintf("no full public key for address %s", keyString)); if (!vchPubKey.IsFullyValid()){ string sKey = keyString.empty()?"(empty)":keyString; throw runtime_error(" Invalid public key: " + sKey ); } pubkeys[i++] = vchPubKey; } //case 2: hex pub key else #endif if (IsHex(keyString)) { CPubKey vchPubKey(ParseHex(keyString)); if (!vchPubKey.IsFullyValid()){ throw runtime_error(" Invalid public key: " + keyString); } pubkeys[i++] = vchPubKey; } else { throw runtime_error(" Invalid public key: " + keyString); } } //populate redeem script //OP_N for required signatures redeemRet << redeemRet.EncodeOP_N(m); //public keys for(CPubKey& key : pubkeys){ vector<unsigned char> vKey= ToByteVector(key); redeemRet << vKey; } //OP_N for total pubkeys redeemRet << redeemRet.EncodeOP_N(pubkeys.size()); redeemRet << OP_CHECKMULTISIG; return true; }catch(const runtime_error& e){ errorRet = string(e.what()); return false; } } /*** * Begin QFrame object creation methods */ //creates an address object on the create tab void MultisigDialog::on_addAddressButton_clicked() { //max addresses 15 if(ui->addressList->count() >= 15){ ui->addMultisigStatus->setStyleSheet("QLabel { color: red; }"); ui->addMultisigStatus->setText(tr("Maximum possible addresses reached. (15)")); return; } QSizePolicy sizePolicy(QSizePolicy::Preferred, QSizePolicy::Fixed); sizePolicy.setHorizontalStretch(0); sizePolicy.setVerticalStretch(0); QFrame* addressFrame = new QFrame(); sizePolicy.setHeightForWidth(addressFrame->sizePolicy().hasHeightForWidth()); addressFrame->setSizePolicy(sizePolicy); addressFrame->setFrameShape(QFrame::StyledPanel); addressFrame->setFrameShadow(QFrame::Raised); addressFrame->setObjectName(QStringLiteral("addressFrame")); QVBoxLayout* frameLayout = new QVBoxLayout(addressFrame); frameLayout->setSpacing(1); frameLayout->setObjectName(QStringLiteral("frameLayout")); frameLayout->setContentsMargins(6, 6, 6, 6); QHBoxLayout* addressLayout = new QHBoxLayout(); addressLayout->setSpacing(2); addressLayout->setObjectName(QStringLiteral("addressLayout")); QLabel* addressLabel = new QLabel(addressFrame); addressLabel->setObjectName(QStringLiteral("addressLabel")); addressLabel->setText(QApplication::translate("MultisigDialog", strprintf("Address / Key %i:", ui->addressList->count()+1).c_str() , 0)); addressLayout->addWidget(addressLabel); QValidatedLineEdit* address = new QValidatedLineEdit(addressFrame); address->setObjectName(QStringLiteral("address")); addressLayout->addWidget(address); QToolButton* addressBookButton = new QToolButton(addressFrame); addressBookButton->setObjectName(QStringLiteral("addressBookButton")); QIcon icon3; icon3.addFile(QStringLiteral(":/icons/address-book"), QSize(), QIcon::Normal, QIcon::Off); addressBookButton->setIcon(icon3); connect(addressBookButton, SIGNAL(clicked()), this, SLOT(addressBookButtonReceiving())); addressLayout->addWidget(addressBookButton); QToolButton* addressPasteButton = new QToolButton(addressFrame); addressPasteButton->setObjectName(QStringLiteral("addressPasteButton")); QIcon icon4; icon4.addFile(QStringLiteral(":/icons/editpaste"), QSize(), QIcon::Normal, QIcon::Off); addressPasteButton->setIcon(icon4); connect(addressPasteButton, SIGNAL(clicked()), this, SLOT(pasteText())); addressLayout->addWidget(addressPasteButton); QToolButton* addressDeleteButton = new QToolButton(addressFrame); addressDeleteButton->setObjectName(QStringLiteral("addressDeleteButton")); QIcon icon5; icon5.addFile(QStringLiteral(":/icons/remove"), QSize(), QIcon::Normal, QIcon::Off); addressDeleteButton->setIcon(icon5); connect(addressDeleteButton, SIGNAL(clicked()), this, SLOT(deleteFrame())); addressLayout->addWidget(addressDeleteButton); frameLayout->addLayout(addressLayout); ui->addressList->addWidget(addressFrame); } void MultisigDialog::on_pushButtonCoinControl_clicked() { CoinControlDialog coinControlDialog(this, true); coinControlDialog.setModel(model); coinControlDialog.exec(); } void MultisigDialog::on_addInputButton_clicked() { if(isFirstRawTx){ isFirstRawTx = false; ui->txInputsScrollArea->show(); } QSizePolicy sizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); sizePolicy.setHorizontalStretch(0); sizePolicy.setVerticalStretch(0); QFrame* txInputFrame = new QFrame(ui->txInputsWidget); sizePolicy.setHeightForWidth(txInputFrame->sizePolicy().hasHeightForWidth()); txInputFrame->setFrameShape(QFrame::StyledPanel); txInputFrame->setFrameShadow(QFrame::Raised); txInputFrame->setObjectName(QStringLiteral("txInputFrame")); QVBoxLayout* frameLayout = new QVBoxLayout(txInputFrame); frameLayout->setSpacing(1); frameLayout->setObjectName(QStringLiteral("txInputFrameLayout")); frameLayout->setContentsMargins(6, 6, 6, 6); QHBoxLayout* txInputLayout = new QHBoxLayout(); txInputLayout->setSpacing(2); txInputLayout->setObjectName(QStringLiteral("txInputLayout")); QLabel* txInputIdLabel = new QLabel(txInputFrame); txInputIdLabel->setObjectName(QStringLiteral("txInputIdLabel")); txInputIdLabel->setText(QApplication::translate("MultisigDialog", strprintf("%i. Tx Hash: ", ui->inputsList->count()+1).c_str(), 0)); txInputLayout->addWidget(txInputIdLabel); QLineEdit* txInputId = new QLineEdit(txInputFrame); txInputId->setObjectName(QStringLiteral("txInputId")); txInputLayout->addWidget(txInputId); QSpacerItem* horizontalSpacer = new QSpacerItem(10, 20, QSizePolicy::Fixed, QSizePolicy::Minimum); txInputLayout->addItem(horizontalSpacer); QLabel* txInputVoutLabel = new QLabel(txInputFrame); txInputVoutLabel->setObjectName(QStringLiteral("txInputVoutLabel")); txInputVoutLabel->setText(QApplication::translate("MultisigDialog", "Vout Position: ", 0)); txInputLayout->addWidget(txInputVoutLabel); QSpinBox* txInputVout = new QSpinBox(txInputFrame); txInputVout->setObjectName("txInputVout"); sizePolicy.setHeightForWidth(txInputVout->sizePolicy().hasHeightForWidth()); txInputVout->setSizePolicy(sizePolicy); txInputLayout->addWidget(txInputVout); QToolButton* inputDeleteButton = new QToolButton(txInputFrame); inputDeleteButton->setObjectName(QStringLiteral("inputDeleteButton")); QIcon icon; icon.addFile(QStringLiteral(":/icons/remove"), QSize(), QIcon::Normal, QIcon::Off); inputDeleteButton->setIcon(icon); connect(inputDeleteButton, SIGNAL(clicked()), this, SLOT(deleteFrame())); txInputLayout->addWidget(inputDeleteButton); frameLayout->addLayout(txInputLayout); ui->inputsList->addWidget(txInputFrame); } void MultisigDialog::on_addDestinationButton_clicked() { QFrame* destinationFrame = new QFrame(ui->destinationsScrollAreaContents); destinationFrame->setObjectName(QStringLiteral("destinationFrame")); destinationFrame->setFrameShape(QFrame::StyledPanel); destinationFrame->setFrameShadow(QFrame::Raised); QVBoxLayout* frameLayout = new QVBoxLayout(destinationFrame); frameLayout->setObjectName(QStringLiteral("destinationFrameLayout")); QHBoxLayout* destinationLayout = new QHBoxLayout(); destinationLayout->setSpacing(0); destinationLayout->setObjectName(QStringLiteral("destinationLayout")); QLabel* destinationAddressLabel = new QLabel(destinationFrame); destinationAddressLabel->setObjectName(QStringLiteral("destinationAddressLabel")); destinationLayout->addWidget(destinationAddressLabel); QValidatedLineEdit* destinationAddress = new QValidatedLineEdit(destinationFrame); destinationAddress->setObjectName(QStringLiteral("destinationAddress")); destinationLayout->addWidget(destinationAddress); QSpacerItem* horizontalSpacer = new QSpacerItem(10, 20, QSizePolicy::Fixed, QSizePolicy::Minimum); destinationLayout->addItem(horizontalSpacer); QLabel* destinationAmountLabel = new QLabel(destinationFrame); destinationAmountLabel->setObjectName(QStringLiteral("destinationAmountLabel")); destinationLayout->addWidget(destinationAmountLabel); BitcoinAmountField* destinationAmount = new BitcoinAmountField(destinationFrame); destinationAmount->setObjectName(QStringLiteral("destinationAmount")); destinationAddressLabel->setText(QApplication::translate("MultisigDialog", strprintf("%i. Address: ", ui->destinationsList->count()+1).c_str(), 0)); destinationAmountLabel->setText(QApplication::translate("MultisigDialog", "Amount: ", 0)); destinationLayout->addWidget(destinationAmount); QToolButton* destinationDeleteButton = new QToolButton(destinationFrame); destinationDeleteButton->setObjectName(QStringLiteral("destinationDeleteButton")); QIcon icon; icon.addFile(QStringLiteral(":/icons/remove"), QSize(), QIcon::Normal, QIcon::Off); destinationDeleteButton->setIcon(icon); connect(destinationDeleteButton, SIGNAL(clicked()), this, SLOT(deleteFrame())); destinationLayout->addWidget(destinationDeleteButton); frameLayout->addLayout(destinationLayout); ui->destinationsList->addWidget(destinationFrame); } void MultisigDialog::on_addPrivKeyButton_clicked() { if(isFirstPrivKey){//on first click the scroll area must show isFirstPrivKey = false; ui->keyScrollArea->show(); } if(ui->keyList->count() >= 15){ ui->signButtonStatus->setStyleSheet("QTextEdit{ color: red }"); ui->signButtonStatus->setText(tr("Maximum (15)")); return; } QFrame* keyFrame = new QFrame(ui->keyScrollAreaContents); keyFrame->setObjectName(QStringLiteral("keyFrame")); keyFrame->setFrameShape(QFrame::StyledPanel); keyFrame->setFrameShadow(QFrame::Raised); QHBoxLayout* keyLayout = new QHBoxLayout(keyFrame); keyLayout->setObjectName(QStringLiteral("keyLayout")); QLabel* keyLabel = new QLabel(keyFrame); keyLabel->setObjectName(QStringLiteral("keyLabel")); keyLabel->setText(QApplication::translate("MultisigDialog", strprintf("Key %i: ", (ui->keyList->count()+1)).c_str(), 0)); keyLayout->addWidget(keyLabel); QLineEdit* key = new QLineEdit(keyFrame); key->setObjectName(QStringLiteral("key")); key->setEchoMode(QLineEdit::Password); keyLayout->addWidget(key); QToolButton* keyDeleteButton = new QToolButton(keyFrame); keyDeleteButton->setObjectName(QStringLiteral("keyDeleteButton")); QIcon icon; icon.addFile(QStringLiteral(":/icons/remove"), QSize(), QIcon::Normal, QIcon::Off); keyDeleteButton->setIcon(icon); connect(keyDeleteButton, SIGNAL(clicked()), this, SLOT(deleteFrame())); keyLayout->addWidget(keyDeleteButton); ui->keyList->addWidget(keyFrame); }
[ "cryptojoehodler@gmail.com" ]
cryptojoehodler@gmail.com
b8dabc2712411eaac169ac245517a58ea8519d12
89bd59ee256ccaa70340b0443ca1b89db4568401
/BON2Component.cpp
0e37a2c5acc714740f9dbab72f5a694bd39ca955
[]
no_license
waijay1688/Garbled-Circuit-Interpreter
c756085404d55bb1bb117264fb40c63bb4b58bf2
e09e5f37d85f76f6afb5fd143699705702ca8fad
refs/heads/master
2021-01-10T01:31:44.677740
2015-11-02T02:23:22
2015-11-02T02:23:22
45,367,597
0
0
null
null
null
null
UTF-8
C++
false
false
10,281
cpp
//############################################################################################################################################### // // Meta and Builder Object Network V2.0 for GME // BON2Component.cpp // //############################################################################################################################################### /* Copyright (c) Vanderbilt University, 2000-2004 ALL RIGHTS RESERVED Vanderbilt University disclaims all warranties with regard to this software, including all implied warranties of merchantability and fitness. In no event shall Vanderbilt University be liable for any special, indirect or consequential damages or any damages whatsoever resulting from loss of use, data or profits, whether in an action of contract, negligence or other tortious action, arising out of or in connection with the use or performance of this software. */ #include "stdafx.h" #include <Console.h> #include "BON2Component.h" #include "CodeGenerator.h" #include "GarbledCircuitBonX.h" #include <fstream> //#include "CircuitVisitor.h" namespace BON { //############################################################################################################################################### // // C L A S S : BON::Component // //############################################################################################################################################### Component::Component() : m_bIsInteractive( false ) { } Component::~Component() { if ( m_project ) { m_project->finalizeObjects(); finalize( m_project ); m_project = NULL; } } // ==================================================== // This method is called after all the generic initialization is done // This should be empty unless application-specific initialization is needed void Component::initialize( Project& project ) { // ====================== // Insert application specific code here #ifdef GME_ADDON project->setAutoCommit( false); #endif } // ==================================================== // This method is called before the whole BON2 project released and disposed // This should be empty unless application-specific finalization is needed void Component::finalize( Project& project ) { // ====================== // Insert application specific code here } // ==================================================== // This is the obsolete component interface // This present implementation either tries to call InvokeEx, or does nothing except of a notification void Component::invoke( Project& project, const std::set<FCO>& setModels, long lParam ) { #ifdef SUPPORT_OLD_INVOKE Object focus; invokeEx( project, focus, setModels, lParam ); #else if ( m_bIsInteractive ) AfxMessageBox(_T("This BON2 Component does not support the obsolete invoke mechanism!")); #endif } // ==================================================== // This is the main component method for Interpereters and Plugins. // May also be used in case of invokeable Add-Ons void Component::invokeEx( Project& project, FCO& currentFCO, const std::set<FCO>& setSelectedFCOs, long lParam ) { #ifdef GME_ADDON project->setAutoCommit( false); #endif using namespace GMEConsole; //using namespace CircuitVisitor; Console::Out::WriteLine("Interpreter started..."); // ====================== // TODO: Insert application specific code here /* if (!currentFCO && setSelectedFCOs.empty()) { AfxMessageBox ("Interpretation must start from a TopLevelPackage, " "or an ImplementationArtifact, or a " "ComponentInterface, or a ComponentPackage, " "ComponentImplementation !"); return; } */ traversalProject(project); Console::Out::WriteLine("Interpreter completed..."); } // ==================================================== // GME currently does not use this function // You only need to implement it if other invokation mechanisms are used void Component::objectInvokeEx( Project& project, Object& currentObject, const std::set<Object>& setSelectedObjects, long lParam ) { if ( m_bIsInteractive ) AfxMessageBox(_T("This BON2 Component does not support objectInvokeEx method!")); } // ==================================================== // Implement application specific parameter-mechanism in these functions Util::Variant Component::getParameter( const std::string& strName ) { // ====================== // Insert application specific code here return Util::Variant(); } void Component::setParameter( const std::string& strName, const Util::Variant& varValue ) { // ====================== // Insert application specific code here } void Component::traversalProject(Project& p) { BON::Folder folder = p->getRootFolder(); std::set<BON::Model> models = folder->getChildModels(); for(auto it=models.begin(); it!=models.end(); it++) { GarbledCircuit_BON::Library l(*it); std::set<GarbledCircuit_BON::GarbledCircuit> gc = l->getGarbledCircuit(); for(auto i=gc.begin(); i!=gc.end(); i++) { traversalGarbledCircuit(*i); } } } void Component::traversalGarbledCircuit(const GarbledCircuit_BON::GarbledCircuit& gc) { //first get all the garbled gc std::set<GarbledCircuit_BON::GarbledCircuit> gcs = gc->getGarbledCircuit(); for(auto it=gcs.begin(); it!=gcs.end(); it++) { if(!(*it)->isClassAlreadyDefined()) traversalGarbledCircuit(*it); } setBasicInfo(gc); setInit(gc); setFixedValue(gc); setInputOutput(gc); setConnection(gc); string folderName = "codes\\"; std::string outputFile = currentJC.getFileContent(); ofstream outf(folderName+gc->getCircuitClassName()+"_Weijie"+".java"); outf<<outputFile; } void Component::setBasicInfo(const GarbledCircuit_BON::GarbledCircuit& gc) { //get the basic information of the current garbled circuit string className = gc->getCircuitClassName(); std::string componentNum = gc->getComponentNumber(); std::string inDegree = gc->getInDegree(); std::string outDegree =gc->getOutDegree(); std::string variable = gc->getVariable(); //CodeGeneratorNameSpace::GarbledClass ; //JavaClassNameSpace::JavaClass jc(CodeGeneratorNameSpace::GarbledClass(className, variable, inDegree, outDegree, componentNum)); CodeGeneratorNameSpace::GarbledClass garbledClass(className, variable, inDegree, outDegree, componentNum); currentJC.clear(); currentJC.insert(garbledClass); } void Component::setInit(const GarbledCircuit_BON::GarbledCircuit& gc) { //get initialtor std::set<InitialtorRef> crs = gc->getInitialtorRef(); for(auto crsIt=crs.begin(); crsIt!=crs.end(); crsIt++) { std::string arguments = (*crsIt)->getCircuitArgument(); std::string indexes = (*crsIt)->getCircuitIndexRange(); string referedType = (*crsIt)->getReferred()->getObjectMeta().name(); string className = ""; if("GarbledCircuit" == referedType) className = GarbledCircuit((*crsIt)->getReferred())->getCircuitClassName(); else className = referedType; //Console::Out::WriteLine(output.c_str()); CodeGeneratorNameSpace::Initialtor init(indexes, arguments, className); init.setDescription((*crsIt)->getDescription()); init.setIndexAlias((*crsIt)->getCircuitIndexAlias()); currentJC.insert(init); } } void Component::setFixedValue(const GarbledCircuit_BON::GarbledCircuit& gc) { //get fixed value? std::set<FixedWireRef> fwr = gc->getFixedWireRef(); for(auto fwrIt=fwr.begin(); fwrIt!=fwr.end(); fwrIt++) { std::string indexes = (*fwrIt)->getCircuitIndexRange(); std::string port = (*fwrIt)->getPortIndex(); std::string portStart = (*fwrIt)->getPortStartIndex(); FixedWireRefImpl::FixedValue_Type value = (*fwrIt)->getFixedValue(); string fixvalue = "0"; if(value == FixedWireRefImpl::FixedValue_Type::_1_FixedValue_Type) fixvalue = "1"; CodeGeneratorNameSpace::FixedWire fw(indexes, portStart, port, fixvalue); fw.setDescription((*fwrIt)->getDescription()); currentJC.insert(fw); } } void Component::setInputOutput(const GarbledCircuit_BON::GarbledCircuit& gc) { //generator? std::set<DefineInOutPut> gtc = gc->getDefineInOutPut(); for(auto gtcIt=gtc.begin(); gtcIt!=gtc.end(); gtcIt++) { std::string srcPort = (*gtcIt)->getSourcePortIndex(); std::string destPort = (*gtcIt)->getDestinationPortIndex(); GarbledCircuit_BON::InOutPut cd = (*gtcIt)->getSrc(); ConnectionRef ccr = (*gtcIt)->getDst(); std::string inputname = cd->getObjectMeta().name(); if("Input" == inputname) { CodeGeneratorNameSpace::InputConnection ic(((GarbledCircuit_BON::Input)cd)->getPortStartIndex(), srcPort, ccr->getComponent(destPort)); ic.setDescription((*gtcIt)->getDescription()); currentJC.insert(ic); } //output else { CodeGeneratorNameSpace::OutputConnection ic(((GarbledCircuit_BON::Output)cd)->getPortStartIndex(), srcPort, ccr->getComponent(destPort)); ic.setDescription((*gtcIt)->getDescription()); currentJC.insert(ic); } } } void Component::setConnection(const GarbledCircuit_BON::GarbledCircuit& gc) { //internal? std::set<InternalWire> iw = gc->getInternalWire(); for(auto iwIt=iw.begin(); iwIt!=iw.end(); iwIt++) { std::string srcPort = (*iwIt)->getSourcePortIndex(); std::string destPort = (*iwIt)->getDestinationPortIndex(); ConnectionRef srcCCR = (*iwIt)->getSrc(); ConnectionRef destCCR = (*iwIt)->getDst(); CodeGeneratorNameSpace::Connection conn(srcCCR->getComponent(srcPort), destCCR->getComponent(destPort)); conn.setDescription((*iwIt)->getDescription()); currentJC.insert(conn); } } #ifdef GME_ADDON // ==================================================== // If the component is an Add-On, then this method is called for every Global Event void Component::globalEventPerformed( globalevent_enum event ) { // ====================== // Insert application specific code here } // ==================================================== // If the component is an Add-On, then this method is called for every Object Event void Component::objectEventPerformed( Object& object, unsigned long event, VARIANT v ) { // ====================== // Insert application specific code here } #endif // GME_ADDON }; // namespace BON
[ "weijie.yu1992@gmail.com" ]
weijie.yu1992@gmail.com
0ef42adb3f48c471198cbb29e4320b39bd6dbc37
303be3bada0b3643abbf47423d54498558442c00
/src/settings.h
2e7d66ffa850600c13cf98285ef090a5b27dfaa8
[]
no_license
llelectronics/tuschbox
ecfd8208723a0cca8f9e3ad3f00182f01a779666
70caa260c5b57d21c8d13f3d44e90c46407a250e
refs/heads/master
2020-05-21T20:32:58.310103
2016-12-19T10:28:07
2016-12-19T10:28:07
65,725,357
1
1
null
2016-12-19T10:17:12
2016-08-15T10:48:05
QML
UTF-8
C++
false
false
416
h
#ifndef SETTINGS_H #define SETTINGS_H #include <QObject> #include <QSettings> class Settings : public QObject { Q_OBJECT public: explicit Settings(QObject *parent = 0); Q_INVOKABLE void setValue(const QString & key, const QVariant & value); Q_INVOKABLE QVariant value(const QString &key, const QVariant &defaultValue = QVariant()) const; private: QSettings settings_; }; #endif // SETTINGS_H
[ "martonmiklosqdev@gmail.com" ]
martonmiklosqdev@gmail.com
4697f2b5969b114b17e7b3e409b5971a6a8ed377
b27f95abb8d8bf08feb662d93b4d0f7aa834d84c
/lab10-11/GeneratedFiles/qrc_lab1011.cpp
c09a901f3619f493eac020ed3068818a9d2b725e
[]
no_license
skywallkee/ShopQt
dccbe36b2fb8701515f6ccf3640cea7c62fb4e6c
50e71ddddf81ecb5daccd67f474289ed9ca0dad2
refs/heads/master
2020-09-22T12:48:56.051231
2019-12-20T22:27:54
2019-12-20T22:27:54
225,202,389
0
0
null
null
null
null
UTF-8
C++
false
false
1,351
cpp
/**************************************************************************** ** Resource object code ** ** Created by: The Resource Compiler for Qt version 5.12.3 ** ** WARNING! All changes made in this file will be lost! *****************************************************************************/ #ifdef QT_NAMESPACE # define QT_RCC_PREPEND_NAMESPACE(name) ::QT_NAMESPACE::name # define QT_RCC_MANGLE_NAMESPACE0(x) x # define QT_RCC_MANGLE_NAMESPACE1(a, b) a##_##b # define QT_RCC_MANGLE_NAMESPACE2(a, b) QT_RCC_MANGLE_NAMESPACE1(a,b) # define QT_RCC_MANGLE_NAMESPACE(name) QT_RCC_MANGLE_NAMESPACE2( \ QT_RCC_MANGLE_NAMESPACE0(name), QT_RCC_MANGLE_NAMESPACE0(QT_NAMESPACE)) #else # define QT_RCC_PREPEND_NAMESPACE(name) name # define QT_RCC_MANGLE_NAMESPACE(name) name #endif #ifdef QT_NAMESPACE namespace QT_NAMESPACE { #endif #ifdef QT_NAMESPACE } #endif int QT_RCC_MANGLE_NAMESPACE(qInitResources_lab1011)(); int QT_RCC_MANGLE_NAMESPACE(qInitResources_lab1011)() { return 1; } int QT_RCC_MANGLE_NAMESPACE(qCleanupResources_lab1011)(); int QT_RCC_MANGLE_NAMESPACE(qCleanupResources_lab1011)() { return 1; } namespace { struct initializer { initializer() { QT_RCC_MANGLE_NAMESPACE(qInitResources_lab1011)(); } ~initializer() { QT_RCC_MANGLE_NAMESPACE(qCleanupResources_lab1011)(); } } dummy; }
[ "raduamaistroaie@gmail.com" ]
raduamaistroaie@gmail.com
c25e554f5f7e1b361af9ae5302e565c7d1fe28c0
a50dbf905ce4b51e2a89e894f6840e67d56d367c
/To insert node at Nth postion in linkedlist.cpp
29b97ce2a8240dfd374f90702d82d8a106b2f1d6
[]
no_license
hamzaiqbal2000/LinkedList
dbe1a43283c4cfeba543739c6934f878bb0ccd90
49f01cc46306d19867a2adeac90d2e506d476f3d
refs/heads/master
2020-07-25T20:16:49.484463
2019-09-28T15:44:01
2019-09-28T15:44:01
208,413,430
0
0
null
null
null
null
UTF-8
C++
false
false
758
cpp
#include <iostream> //linked list :: program to insert node at Nth postion struct Node { int data; Node* next; }; Node* head; void Insert(int data, int n) { Node* temp1 = new Node(); temp1->data = data; temp1->next = NULL; if (n == 1) { temp1->next = head; head = temp1; return; } Node* temp2 = head; for (int i = 0; i < n - 2; i++) { temp2 = temp2->next;//for getting at n-1 positon } temp1->next = temp2->next; temp2->next = temp1; } void Print() {//traversing Node* temp = head; while (temp != NULL) { std::cout <<" "<< temp->data; temp = temp->next; } std::cout << "\n"; } int main() { head = NULL; Insert(2, 1); Insert(3,2); Insert(4,1); Insert(5, 2); Insert(10, 1); Print(); }
[ "noreply@github.com" ]
hamzaiqbal2000.noreply@github.com
59c0dd037fc2e59deab9f31072be8b12d7158075
d8bff35df8373d81f9152a282666387032460f66
/ACU/auto_widget.cpp
e43589e2107ab3192717f60fb9893ffedc287150
[]
no_license
W-ang11/distal_warehouse
4e1aba43a0722c243b5448928b64cda9564224cf
5ef10b57bc57fa259e8a88beea4e62ef10579555
refs/heads/master
2020-09-13T21:13:53.690672
2019-11-21T08:14:46
2019-11-21T08:14:46
222,904,578
4
0
null
null
null
null
UTF-8
C++
false
false
5,261
cpp
#include "auto_widget.h" #include "ui_auto_widget.h" #include <QVector> #include <QTimer> #include <QTime> #include "deal_thread.h" extern Auto_Widget *a_w; Auto_Widget::Auto_Widget(QWidget *parent) : QWidget(parent), ui(new Ui::Auto_Widget) { ui->setupUi(this); setupRealtimeDataDemo(ui->customPlot_3); ui->customPlot_3->replot(); ui->checkBox_current_3->setChecked(true); ui->checkBox_reference_3->setChecked(true); a_w=this; } Auto_Widget::~Auto_Widget() { delete ui; } void Auto_Widget::updata_widget_data(SHOW s) { ui->label_cur_azm_4->setText(s.Cur_Azm); ui->label_cur_el_4->setText(s.Cur_El); ui->label_cur_pol_4->setText(s.Cur_Pol); ui->label_per_azm_4->setText(s.Pre_Azm); ui->label_per_el_4->setText(s.Pre_El); ui->label_per_pol_4->setText(s.Pre_Pol); } //画图初始化 void Auto_Widget::setupRealtimeDataDemo(QCustomPlot *customPlot) { //#if QT_VERSION < QT_VERSION_CHECK(4, 7, 0) //QMessageBox::critical(this, "", "You're using Qt < 4.7, the realtime data demo needs functions that are available with Qt 4.7 to work properly"); //#endif //demoName = "Real Time Data Demo"; // include this section to fully disable antialiasing for higher performance: /* customPlot->setNotAntialiasedElements(QCP::aeAll); QFont font; font.setStyleStrategy(QFont::NoAntialias); customPlot->xAxis->setTickLabelFont(font); customPlot->yAxis->setTickLabelFont(font); customPlot->legend->setFont(font); */ customPlot->addGraph(); // blue line customPlot->graph(0)->setPen(QPen(Qt::blue)); customPlot->graph(0)->setName("AGC current"); //customPlot->graph(0)->setBrush(QBrush(QColor(240, 255, 200))); //customPlot->graph(0)->setAntialiasedFill(false); customPlot->addGraph(); // red line customPlot->graph(1)->setPen(QPen(Qt::red)); customPlot->graph(1)->setName("AGC reference"); //customPlot->graph(0)->setChannelFillGraph(customPlot->graph(1)); customPlot->xAxis->setTickLabelType(QCPAxis::ltDateTime); customPlot->xAxis->setDateTimeFormat("hh:mm:ss"); customPlot->xAxis->setAutoTickStep(false); customPlot->xAxis->setTickStep(2); customPlot->axisRect()->setupFullAxesBox(); // make left and bottom axes transfer their ranges to right and top axes: //connect(customPlot->xAxis, SIGNAL(rangeChanged(QCPRange)), customPlot->xAxis2, SLOT(setRange(QCPRange))); //connect(customPlot->yAxis, SIGNAL(rangeChanged(QCPRange)), customPlot->yAxis2, SLOT(setRange(QCPRange))); // setup a timer that repeatedly calls MainWindow::realtimeDataSlot: connect(&dataTimer, SIGNAL(timeout()), this, SLOT(realtimeDataSlot())); dataTimer.start(10); // Interval 0 means to refresh as fast as possible customPlot->legend->setVisible(true); } extern struct STAR star; void Auto_Widget::realtimeDataSlot() { //key的单位是秒 double key = QDateTime::currentDateTime().toMSecsSinceEpoch()/1000.0; //qsrand(QTime::currentTime().msec() + QTime::currentTime().second() * 10000); //使用随机数产生两条曲线 double value0 = atof(show_info.AGC); //double value0 = qrand()%10; double value1 = atof(star.limit_info); if (ui->checkBox_current_3->isChecked()) ui->customPlot_3->graph(0)->addData(key, value0);//添加数据1到曲线1 if (ui->checkBox_reference_3->isChecked()) ui->customPlot_3->graph(1)->addData(key, value1);//添加数据2到曲线2 //删除8秒之前的数据。这里的8要和下面设置横坐标宽度的8配合起来 //才能起到想要的效果,可以调整这两个值,观察显示的效果。 ui->customPlot_3->graph(0)->removeDataBefore(key-8); ui->customPlot_3->graph(1)->removeDataBefore(key-8); //自动设定graph(1)曲线y轴的范围,如果不设定,有可能看不到图像 //也可以用ui->customPlot->yAxis->setRange(up,low)手动设定y轴范围 ui->customPlot_3->graph(0)->rescaleValueAxis(); ui->customPlot_3->graph(1)->rescaleValueAxis(true); //这里的8,是指横坐标时间宽度为8秒,如果想要横坐标显示更多的时间 //就把8调整为比较大到值,比如要显示60秒,那就改成60。 //这时removeDataBefore(key-8)中的8也要改成60,否则曲线显示不完整。 ui->customPlot_3->xAxis->setRange(key+0.25, 8, Qt::AlignRight);//设定x轴的范围 ui->customPlot_3->replot(); } #include <QSerialPort> extern QSerialPort serial; void Auto_Widget::on_pushButton_23_clicked() { //组包发送,复位 QString str =QString("$cmd,reset,*1f\r\n"); serial.write(str.toLatin1().data()); } void Auto_Widget::on_pushButton_24_clicked() { //组包发送,对星 QString str =QString("$cmd,search,*64\r\n"); serial.write(str.toLatin1().data()); } void Auto_Widget::on_pushButton_21_clicked() { //组包发送,收藏 QString str =QString("$cmd,stow,*75\r\n"); serial.write(str.toLatin1().data()); } void Auto_Widget::on_pushButton_22_clicked() { //组包发送,展开 //这里没有展开指令 } void Auto_Widget::on_pushButton_19_clicked() { //组包发送,停止 QString str =QString("$cmd,stop,*72\r\n"); serial.write(str.toLatin1().data()); }
[ "1962918321@qq.com" ]
1962918321@qq.com
8760a17039e0bbe699ba81584fef8534b6c1449a
71e1c30c4a120078e4a80d3617a34e0f1cf00a41
/Scratch/LowLevelGraphics/VulkanSample/AeVulkanLib/ae/base/FrameCounter.hpp
afda361d8744bceb9ffbafe700b91179c9aa68b7
[]
no_license
hoboaki/engineplan
26d7c1296670cc4c6bc875b175c1aff4857c9e8d
79e5a2e75540aebb00eaae3da6cdc04067207d19
refs/heads/main/master
2023-08-16T20:29:18.927297
2023-08-14T01:01:37
2023-08-14T01:01:37
100,376,204
2
0
null
2023-08-14T01:01:38
2017-08-15T12:43:00
C++
UTF-8
C++
false
false
1,736
hpp
// 文字コード:UTF-8 #if defined(AE_BASE_INCLUDED_FRAMECOUNTER_HPP) #else #define AE_BASE_INCLUDED_FRAMECOUNTER_HPP #include <ae/base/BuiltInTypes.hpp> //------------------------------------------------------------------------------ namespace ae::base { /// @addtogroup AeBase-Util //@{ /// フレームカウンター。 class FrameCounter { public: /// @name コンストラクタ //@{ FrameCounter(); ///< 総フレーム数0で作成。 FrameCounter(int totalFrame); ///< 総フレーム数を指定して作成。 //@{ /// @name リセット //@{ void Reset(); ///< 設定済みの総フレーム数でリセット。 void Reset(int totalFrame); ///< 新しい総フレーム数を指定してリセット。 //@} /// @name 更新 //@{ /// @brief フレームを1進める。 /// @details IsEnd() 状態なら何もしません。 void Advance(); /// @brief フレームを1進める。 /// @details IsEnd() 状態で呼ぶとエラーになります。 void AdvanceStrict(); /// @brief 最終フレームまで進める。 void ToEnd(); //@} /// @name 取得 //@{ int Frame() const; ///< 現在のフレーム数。 int TotalFrame() const; ///< 総フレーム数。 bool IsEnd() const; ///< 現在のフレームが総フレームに達しているか。 bool IsCounting() const; ///< 現在のフレームが総フレームに達していないか。 float RateFrame() const; ///< 0.0f <= 1.0f の範囲に正規化されたフレーム。 float InvRateFrame() const; ///< 1.0f - RateFrame()。 //@} private: int frame_; int totalFrame_; }; //@} } // namespace ae::base #endif // EOF
[ "hoboaki@10106.net" ]
hoboaki@10106.net
5a7f35c0225fdb6e63cead1c7990336e2136402d
9ac8e41b3ee4593e2d8a0eaf5c1cf8ac957a2c82
/src/bignum.h
cc2d48f343a2e65e93375fccfc2085442f92f8b6
[ "MIT" ]
permissive
northwoodlabs/flaxscript
3de5b764ec4505d4422f3d9fef89ed13f67b5138
1764ca06346c8cdb43b5a3217ce832a16e702b88
refs/heads/master
2021-01-01T18:08:55.623328
2018-01-07T11:13:40
2018-01-07T11:13:40
98,257,174
0
0
MIT
2018-01-07T03:47:54
2017-07-25T02:52:37
C++
UTF-8
C++
false
false
16,987
h
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2013 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef BITCOIN_BIGNUM_H #define BITCOIN_BIGNUM_H #include "serialize.h" #include "uint256.h" #include "version.h" #include <stdexcept> #include <stdint.h> #include <vector> #include <openssl/bn.h> /** Errors thrown by the bignum class */ class bignum_error : public std::runtime_error { public: explicit bignum_error(const std::string& str) : std::runtime_error(str) {} }; /** RAII encapsulated BN_CTX (OpenSSL bignum context) */ class CAutoBN_CTX { protected: BN_CTX* pctx; BN_CTX* operator=(BN_CTX* pnew) { return pctx = pnew; } public: CAutoBN_CTX() { pctx = BN_CTX_new(); if (pctx == NULL) throw bignum_error("CAutoBN_CTX : BN_CTX_new() returned NULL"); } ~CAutoBN_CTX() { if (pctx != NULL) BN_CTX_free(pctx); } operator BN_CTX*() { return pctx; } BN_CTX& operator*() { return *pctx; } BN_CTX** operator&() { return &pctx; } bool operator!() { return (pctx == NULL); } }; /** C++ wrapper for BIGNUM (OpenSSL bignum) */ class CBigNum : public BIGNUM { public: CBigNum() { BN_init(this); } CBigNum(const CBigNum& b) { BN_init(this); if (!BN_copy(this, &b)) { BN_clear_free(this); throw bignum_error("CBigNum::CBigNum(const CBigNum&) : BN_copy failed"); } } CBigNum& operator=(const CBigNum& b) { if (!BN_copy(this, &b)) throw bignum_error("CBigNum::operator= : BN_copy failed"); return (*this); } ~CBigNum() { BN_clear_free(this); } //CBigNum(char n) is not portable. Use 'signed char' or 'unsigned char'. CBigNum(signed char n) { BN_init(this); if (n >= 0) setulong(n); else setint64(n); } CBigNum(short n) { BN_init(this); if (n >= 0) setulong(n); else setint64(n); } CBigNum(int n) { BN_init(this); if (n >= 0) setulong(n); else setint64(n); } CBigNum(long n) { BN_init(this); if (n >= 0) setulong(n); else setint64(n); } CBigNum(long long n) { BN_init(this); setint64(n); } CBigNum(unsigned char n) { BN_init(this); setulong(n); } CBigNum(unsigned short n) { BN_init(this); setulong(n); } CBigNum(unsigned int n) { BN_init(this); setulong(n); } CBigNum(unsigned long n) { BN_init(this); setulong(n); } CBigNum(unsigned long long n) { BN_init(this); setuint64(n); } explicit CBigNum(uint256 n) { BN_init(this); setuint256(n); } explicit CBigNum(const std::vector<unsigned char>& vch) { BN_init(this); setvch(vch); } void setulong(unsigned long n) { if (!BN_set_word(this, n)) throw bignum_error("CBigNum conversion from unsigned long : BN_set_word failed"); } unsigned long getulong() const { return BN_get_word(this); } unsigned int getuint() const { return BN_get_word(this); } int getint() const { unsigned long n = BN_get_word(this); if (!BN_is_negative(this)) return (n > (unsigned long)std::numeric_limits<int>::max() ? std::numeric_limits<int>::max() : n); else return (n > (unsigned long)std::numeric_limits<int>::max() ? std::numeric_limits<int>::min() : -(int)n); } void setint64(int64_t sn) { unsigned char pch[sizeof(sn) + 6]; unsigned char* p = pch + 4; bool fNegative; uint64_t n; if (sn < (int64_t)0) { // Since the minimum signed integer cannot be represented as positive so long as its type is signed, // and it's not well-defined what happens if you make it unsigned before negating it, // we instead increment the negative integer by 1, convert it, then increment the (now positive) unsigned integer by 1 to compensate n = -(sn + 1); ++n; fNegative = true; } else { n = sn; fNegative = false; } bool fLeadingZeroes = true; for (int i = 0; i < 8; i++) { unsigned char c = (n >> 56) & 0xff; n <<= 8; if (fLeadingZeroes) { if (c == 0) continue; if (c & 0x80) *p++ = (fNegative ? 0x80 : 0); else if (fNegative) c |= 0x80; fLeadingZeroes = false; } *p++ = c; } unsigned int nSize = p - (pch + 4); pch[0] = (nSize >> 24) & 0xff; pch[1] = (nSize >> 16) & 0xff; pch[2] = (nSize >> 8) & 0xff; pch[3] = (nSize) & 0xff; BN_mpi2bn(pch, p - pch, this); } void setuint64(uint64_t n) { unsigned char pch[sizeof(n) + 6]; unsigned char* p = pch + 4; bool fLeadingZeroes = true; for (int i = 0; i < 8; i++) { unsigned char c = (n >> 56) & 0xff; n <<= 8; if (fLeadingZeroes) { if (c == 0) continue; if (c & 0x80) *p++ = 0; fLeadingZeroes = false; } *p++ = c; } unsigned int nSize = p - (pch + 4); pch[0] = (nSize >> 24) & 0xff; pch[1] = (nSize >> 16) & 0xff; pch[2] = (nSize >> 8) & 0xff; pch[3] = (nSize) & 0xff; BN_mpi2bn(pch, p - pch, this); } void setuint256(uint256 n) { unsigned char pch[sizeof(n) + 6]; unsigned char* p = pch + 4; bool fLeadingZeroes = true; unsigned char* pbegin = (unsigned char*)&n; unsigned char* psrc = pbegin + sizeof(n); while (psrc != pbegin) { unsigned char c = *(--psrc); if (fLeadingZeroes) { if (c == 0) continue; if (c & 0x80) *p++ = 0; fLeadingZeroes = false; } *p++ = c; } unsigned int nSize = p - (pch + 4); pch[0] = (nSize >> 24) & 0xff; pch[1] = (nSize >> 16) & 0xff; pch[2] = (nSize >> 8) & 0xff; pch[3] = (nSize >> 0) & 0xff; BN_mpi2bn(pch, p - pch, this); } uint256 getuint256() const { unsigned int nSize = BN_bn2mpi(this, NULL); if (nSize < 4) return 0; std::vector<unsigned char> vch(nSize); BN_bn2mpi(this, &vch[0]); if (vch.size() > 4) vch[4] &= 0x7f; uint256 n = 0; for (unsigned int i = 0, j = vch.size()-1; i < sizeof(n) && j >= 4; i++, j--) ((unsigned char*)&n)[i] = vch[j]; return n; } void setvch(const std::vector<unsigned char>& vch) { std::vector<unsigned char> vch2(vch.size() + 4); unsigned int nSize = vch.size(); // BIGNUM's byte stream format expects 4 bytes of // big endian size data info at the front vch2[0] = (nSize >> 24) & 0xff; vch2[1] = (nSize >> 16) & 0xff; vch2[2] = (nSize >> 8) & 0xff; vch2[3] = (nSize >> 0) & 0xff; // swap data to big endian reverse_copy(vch.begin(), vch.end(), vch2.begin() + 4); BN_mpi2bn(&vch2[0], vch2.size(), this); } std::vector<unsigned char> getvch() const { unsigned int nSize = BN_bn2mpi(this, NULL); if (nSize <= 4) return std::vector<unsigned char>(); std::vector<unsigned char> vch(nSize); BN_bn2mpi(this, &vch[0]); vch.erase(vch.begin(), vch.begin() + 4); reverse(vch.begin(), vch.end()); return vch; } // The "compact" format is a representation of a whole // number N using an unsigned 32bit number similar to a // floating point format. // The most significant 8 bits are the unsigned exponent of base 256. // This exponent can be thought of as "number of bytes of N". // The lower 23 bits are the mantissa. // Bit number 24 (0x800000) represents the sign of N. // N = (-1^sign) * mantissa * 256^(exponent-3) // // Satoshi's original implementation used BN_bn2mpi() and BN_mpi2bn(). // MPI uses the most significant bit of the first byte as sign. // Thus 0x1234560000 is compact (0x05123456) // and 0xc0de000000 is compact (0x0600c0de) // (0x05c0de00) would be -0x40de000000 // // Flaxscript only uses this "compact" format for encoding difficulty // targets, which are unsigned 256bit quantities. Thus, all the // complexities of the sign bit and using base 256 are probably an // implementation accident. // // This implementation directly uses shifts instead of going // through an intermediate MPI representation. CBigNum& SetCompact(unsigned int nCompact) { unsigned int nSize = nCompact >> 24; bool fNegative =(nCompact & 0x00800000) != 0; unsigned int nWord = nCompact & 0x007fffff; if (nSize <= 3) { nWord >>= 8*(3-nSize); BN_set_word(this, nWord); } else { BN_set_word(this, nWord); BN_lshift(this, this, 8*(nSize-3)); } BN_set_negative(this, fNegative); return *this; } unsigned int GetCompact() const { unsigned int nSize = BN_num_bytes(this); unsigned int nCompact = 0; if (nSize <= 3) nCompact = BN_get_word(this) << 8*(3-nSize); else { CBigNum bn; BN_rshift(&bn, this, 8*(nSize-3)); nCompact = BN_get_word(&bn); } // The 0x00800000 bit denotes the sign. // Thus, if it is already set, divide the mantissa by 256 and increase the exponent. if (nCompact & 0x00800000) { nCompact >>= 8; nSize++; } nCompact |= nSize << 24; nCompact |= (BN_is_negative(this) ? 0x00800000 : 0); return nCompact; } void SetHex(const std::string& str) { // skip 0x const char* psz = str.c_str(); while (isspace(*psz)) psz++; bool fNegative = false; if (*psz == '-') { fNegative = true; psz++; } if (psz[0] == '0' && tolower(psz[1]) == 'x') psz += 2; while (isspace(*psz)) psz++; // hex string to bignum *this = 0; int n; while ((n = HexDigit(*psz)) != -1) { *this <<= 4; *this += n; ++psz; } if (fNegative) *this = 0 - *this; } std::string ToString(int nBase=10) const { CAutoBN_CTX pctx; CBigNum bnBase = nBase; CBigNum bn0 = 0; std::string str; CBigNum bn = *this; BN_set_negative(&bn, false); CBigNum dv; CBigNum rem; if (BN_cmp(&bn, &bn0) == 0) return "0"; while (BN_cmp(&bn, &bn0) > 0) { if (!BN_div(&dv, &rem, &bn, &bnBase, pctx)) throw bignum_error("CBigNum::ToString() : BN_div failed"); bn = dv; unsigned int c = rem.getulong(); str += "0123456789abcdef"[c]; } if (BN_is_negative(this)) str += "-"; reverse(str.begin(), str.end()); return str; } std::string GetHex() const { return ToString(16); } unsigned int GetSerializeSize(int nType=0, int nVersion=PROTOCOL_VERSION) const { return ::GetSerializeSize(getvch(), nType, nVersion); } template<typename Stream> void Serialize(Stream& s, int nType=0, int nVersion=PROTOCOL_VERSION) const { ::Serialize(s, getvch(), nType, nVersion); } template<typename Stream> void Unserialize(Stream& s, int nType=0, int nVersion=PROTOCOL_VERSION) { std::vector<unsigned char> vch; ::Unserialize(s, vch, nType, nVersion); setvch(vch); } bool operator!() const { return BN_is_zero(this); } CBigNum& operator+=(const CBigNum& b) { if (!BN_add(this, this, &b)) throw bignum_error("CBigNum::operator+= : BN_add failed"); return *this; } CBigNum& operator-=(const CBigNum& b) { *this = *this - b; return *this; } CBigNum& operator*=(const CBigNum& b) { CAutoBN_CTX pctx; if (!BN_mul(this, this, &b, pctx)) throw bignum_error("CBigNum::operator*= : BN_mul failed"); return *this; } CBigNum& operator/=(const CBigNum& b) { *this = *this / b; return *this; } CBigNum& operator%=(const CBigNum& b) { *this = *this % b; return *this; } CBigNum& operator<<=(unsigned int shift) { if (!BN_lshift(this, this, shift)) throw bignum_error("CBigNum:operator<<= : BN_lshift failed"); return *this; } CBigNum& operator>>=(unsigned int shift) { // Note: BN_rshift segfaults on 64-bit if 2^shift is greater than the number // if built on ubuntu 9.04 or 9.10, probably depends on version of OpenSSL CBigNum a = 1; a <<= shift; if (BN_cmp(&a, this) > 0) { *this = 0; return *this; } if (!BN_rshift(this, this, shift)) throw bignum_error("CBigNum:operator>>= : BN_rshift failed"); return *this; } CBigNum& operator++() { // prefix operator if (!BN_add(this, this, BN_value_one())) throw bignum_error("CBigNum::operator++ : BN_add failed"); return *this; } const CBigNum operator++(int) { // postfix operator const CBigNum ret = *this; ++(*this); return ret; } CBigNum& operator--() { // prefix operator CBigNum r; if (!BN_sub(&r, this, BN_value_one())) throw bignum_error("CBigNum::operator-- : BN_sub failed"); *this = r; return *this; } const CBigNum operator--(int) { // postfix operator const CBigNum ret = *this; --(*this); return ret; } friend inline const CBigNum operator-(const CBigNum& a, const CBigNum& b); friend inline const CBigNum operator/(const CBigNum& a, const CBigNum& b); friend inline const CBigNum operator%(const CBigNum& a, const CBigNum& b); }; inline const CBigNum operator+(const CBigNum& a, const CBigNum& b) { CBigNum r; if (!BN_add(&r, &a, &b)) throw bignum_error("CBigNum::operator+ : BN_add failed"); return r; } inline const CBigNum operator-(const CBigNum& a, const CBigNum& b) { CBigNum r; if (!BN_sub(&r, &a, &b)) throw bignum_error("CBigNum::operator- : BN_sub failed"); return r; } inline const CBigNum operator-(const CBigNum& a) { CBigNum r(a); BN_set_negative(&r, !BN_is_negative(&r)); return r; } inline const CBigNum operator*(const CBigNum& a, const CBigNum& b) { CAutoBN_CTX pctx; CBigNum r; if (!BN_mul(&r, &a, &b, pctx)) throw bignum_error("CBigNum::operator* : BN_mul failed"); return r; } inline const CBigNum operator/(const CBigNum& a, const CBigNum& b) { CAutoBN_CTX pctx; CBigNum r; if (!BN_div(&r, NULL, &a, &b, pctx)) throw bignum_error("CBigNum::operator/ : BN_div failed"); return r; } inline const CBigNum operator%(const CBigNum& a, const CBigNum& b) { CAutoBN_CTX pctx; CBigNum r; if (!BN_mod(&r, &a, &b, pctx)) throw bignum_error("CBigNum::operator% : BN_div failed"); return r; } inline const CBigNum operator<<(const CBigNum& a, unsigned int shift) { CBigNum r; if (!BN_lshift(&r, &a, shift)) throw bignum_error("CBigNum:operator<< : BN_lshift failed"); return r; } inline const CBigNum operator>>(const CBigNum& a, unsigned int shift) { CBigNum r = a; r >>= shift; return r; } inline bool operator==(const CBigNum& a, const CBigNum& b) { return (BN_cmp(&a, &b) == 0); } inline bool operator!=(const CBigNum& a, const CBigNum& b) { return (BN_cmp(&a, &b) != 0); } inline bool operator<=(const CBigNum& a, const CBigNum& b) { return (BN_cmp(&a, &b) <= 0); } inline bool operator>=(const CBigNum& a, const CBigNum& b) { return (BN_cmp(&a, &b) >= 0); } inline bool operator<(const CBigNum& a, const CBigNum& b) { return (BN_cmp(&a, &b) < 0); } inline bool operator>(const CBigNum& a, const CBigNum& b) { return (BN_cmp(&a, &b) > 0); } #endif
[ "adamandshandra@server.local" ]
adamandshandra@server.local
16ba482d4125a0b622b96e664e06dfc854687398
2a5affbef27afd7f554272c3d1978255af91196b
/uos-F4DiscoveryTest/f4discovery-blinky-micro-os-plus/generated/micro-os-plus-iii/include/cmsis-plus/memory/malloc.h
8658b91d5672b3bdf4ceadfca9e164e1859077d0
[]
no_license
quzhi010/uos-F4DiscoveryTest
1112a74ffda596730cd92702d133e186d534d6c9
2b37e7376a3ef929e7ca642e99781a0add5f87bc
refs/heads/master
2020-05-01T12:37:45.306888
2019-04-11T06:03:41
2019-04-12T05:15:41
177,459,453
0
0
null
null
null
null
UTF-8
C++
false
false
8,993
h
/* * This file is part of the µOS++ distribution. * (https://github.com/micro-os-plus) * Copyright (c) 2016 Liviu Ionescu. * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, * copy, modify, merge, publish, distribute, sublicense, and/or * sell copies of the Software, and to permit persons to whom * the Software is furnished to do so, subject to the following * conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. */ #ifndef CMSIS_PLUS_MEMORY_MALLOC_H_ #define CMSIS_PLUS_MEMORY_MALLOC_H_ // ---------------------------------------------------------------------------- #if defined(__cplusplus) #include <cmsis-plus/rtos/os.h> // ---------------------------------------------------------------------------- namespace os { namespace memory { #pragma GCC diagnostic push #if defined(__clang__) #pragma clang diagnostic ignored "-Wweak-vtables" #endif // ======================================================================== /** * @headerfile os.h <cmsis-plus/memory/malloc.h> * @ingroup cmsis-plus-rtos-memres * @brief * A memory manager that allocates memory via * the system `std::malloc()` and deallocates via `std::free()`. * * It is the default memory manager when running on synthetic * POSIX platforms. * * @warning This memory manager is not thread safe. */ class malloc_memory_resource : public rtos::memory::memory_resource { public: /** * @name Constructors & Destructor * @{ */ /** * @brief Default constructor. Construct a memory manager object instance. */ malloc_memory_resource (); /** * @brief Construct a named memory manager object instance. */ malloc_memory_resource (const char* name); /** * @cond ignore */ malloc_memory_resource (const malloc_memory_resource&) = delete; malloc_memory_resource (malloc_memory_resource&&) = delete; malloc_memory_resource& operator= (const malloc_memory_resource&) = delete; malloc_memory_resource& operator= (malloc_memory_resource&&) = delete; /** * @endcond */ /** * @brief Destruct the memory manager object instance. */ ~malloc_memory_resource () override; /** * @} */ protected: /** * @name Private Member Functions * @{ */ /** * @brief Implementation of the memory allocator. * @param bytes Number of bytes to allocate. * @param alignment Alignment constraint (power of 2). * @return Pointer to newly allocated block, or `nullptr`. */ virtual void* do_allocate (std::size_t bytes, std::size_t alignment) override; /** * @brief Implementation of the memory deallocator. * @param addr Address of a previously allocated block to free. * @param bytes Number of bytes to deallocate (may be 0 if unknown). * @param alignment Alignment constraint (power of 2). * @par Returns * Nothing. */ virtual void do_deallocate (void* addr, std::size_t bytes, std::size_t alignment) noexcept override; /** * @} */ }; // ====================================================================== /** * @headerfile os.h <cmsis-plus/memory/malloc.h> * @ingroup cmsis-plus-rtos-memres * @brief * A memory manager that allocates memory via * the system `operator new` and deallocates via `operator delete`. * * This is a memory resource defined by the ISO C++ standard. * * @note This memory manager is thread safe. */ class new_delete_memory_resource : public rtos::memory::memory_resource { public: /** * @name Constructors & Destructor * @{ */ /** * @brief Destruct the memory manager object instance. */ ~new_delete_memory_resource () override = default; /** * @} */ protected: /** * @name Private Member Functions * @{ */ /** * @brief Implementation of the memory allocator. * @param bytes Number of bytes to allocate. * @param alignment Alignment constraint (power of 2). * @return Pointer to newly allocated block, or `nullptr`. */ virtual void* do_allocate (size_t bytes, size_t alignment) override; /** * @brief Implementation of the memory deallocator. * @param addr Address of a previously allocated block to free. * @param bytes Number of bytes to deallocate (may be 0 if unknown). * @param alignment Alignment constraint (power of 2). * @par Returns * Nothing. */ virtual void do_deallocate (void* addr, size_t bytes, size_t alignment) noexcept override; /** * @} */ }; #pragma GCC diagnostic pop // ------------------------------------------------------------------------- } /* namespace memory */ } /* namespace os */ // ===== Inline & template implementations ==================================== namespace os { namespace memory { // ======================================================================== inline malloc_memory_resource::malloc_memory_resource () { trace::printf ("%s() @%p %s\n", __func__, this, this->name ()); } inline malloc_memory_resource::malloc_memory_resource (const char* name) : rtos::memory::memory_resource { name } { trace::printf ("%s() @%p %s\n", __func__, this, this->name ()); } inline malloc_memory_resource::~malloc_memory_resource () { trace::printf ("%s() @%p %s\n", __func__, this, this->name ()); } #pragma GCC diagnostic push // Needed because 'alignment' is used only in trace calls. #pragma GCC diagnostic ignored "-Wunused-parameter" inline void* malloc_memory_resource::do_allocate (std::size_t bytes, std::size_t alignment) { // Ignore alignment for now. void* mem = std::malloc (bytes); #if defined(OS_TRACE_LIBCPP_MEMORY_RESOURCE) trace::printf ("%s(%u,%u)=%p @%p %s\n", __func__, bytes, alignment, mem, this, name ()); #endif return mem; } inline void malloc_memory_resource::do_deallocate (void* addr, std::size_t bytes, std::size_t alignment) noexcept { #if defined(OS_TRACE_LIBCPP_MEMORY_RESOURCE) trace::printf ("%s(%p,%u,%u) @%p %s\n", __func__, addr, bytes, alignment, this, name ()); #endif // Ignore size and alignment for now. std::free (addr); } #pragma GCC diagnostic pop // ======================================================================== #pragma GCC diagnostic push // Needed because 'alignment' is used only in trace calls. #pragma GCC diagnostic ignored "-Wunused-parameter" inline void* new_delete_memory_resource::do_allocate (size_t bytes, size_t alignment) { // Ignore alignment for now. void* mem = ::operator new (bytes); #if defined(OS_TRACE_LIBCPP_MEMORY_RESOURCE) trace::printf ("%s(%u,%u)=%p @%p %s\n", __func__, bytes, alignment, mem, this, name ()); #endif allocated_chunks_++; return mem; } inline void new_delete_memory_resource::do_deallocate (void* addr, size_t bytes, size_t alignment) noexcept { #if defined(OS_TRACE_LIBCPP_MEMORY_RESOURCE) trace::printf ("%s(%p,%u,%u) @%p %s\n", __func__, addr, bytes, alignment, this, name ()); #endif // Ignore size and alignment for now. ::operator delete (addr); allocated_chunks_--; } #pragma GCC diagnostic pop // ========================================================================== } /* namespace memory */ } /* namespace os */ // ---------------------------------------------------------------------------- #endif /* __cplusplus */ #endif /* CMSIS_PLUS_MEMORY_MALLOC_H_ */
[ "quzhi010@gmail.com" ]
quzhi010@gmail.com
45e5ea73ca05acea920cd0b3b5ceb17b71e2f791
33c664e99bdb4b5d7e0cd35e3bbe7dc43b4f9cdd
/embedded/polargraph_server_mega_mod/exec.ino
a3177b80c7cac8e98aabb102b819e882bba0027b
[]
no_license
airzone-sama/polargraph
6cdb04dad9005cf49b94471792f0ff470dba019d
1ca7f6f766bbf126ada58988a1b21d705196c6f8
refs/heads/master
2021-01-23T19:41:35.498416
2013-02-16T12:09:14
2013-02-16T12:09:14
8,235,250
1
0
null
null
null
null
UTF-8
C++
false
false
11,061
ino
/** * Polargraph Server. - CORE * Written by Sandy Noble * Released under GNU License version 3. * http://www.polargraph.co.uk * http://code.google.com/p/polargraph/ Exec. This is one of the core files for the polargraph server program. Purposes are getting a little more blurred here. This file contains the basic decision tree that branches based on command. It has a set of the most general-purpose drawing commands, but only methods that are directly called - none of the geometry or conversion routines are here. */ /** This method looks only for the basic command set */ boolean exec_executeBasicCommand(String &com) { boolean executed = true; if (com.startsWith(CMD_CHANGELENGTH)) exec_changeLength(); else if (com.startsWith(CMD_CHANGELENGTHDIRECT)) exec_changeLengthDirect(); else if (com.startsWith(CMD_CHANGEPENWIDTH)) exec_changePenWidth(); else if (com.startsWith(CMD_CHANGEMOTORSPEED)) exec_changeMotorSpeed(); else if (com.startsWith(CMD_CHANGEMOTORACCEL)) exec_changeMotorAcceleration(); else if (com.startsWith(CMD_SETMOTORSPEED)) exec_setMotorSpeed(); else if (com.startsWith(CMD_SETMOTORACCEL)) exec_setMotorAcceleration(); else if (com.startsWith(CMD_DRAWPIXEL)) pixel_drawSquarePixel(); else if (com.startsWith(CMD_DRAWSCRIBBLEPIXEL)) pixel_drawScribblePixel(); // else if (com.startsWith(CMD_DRAWRECT)) // drawRectangle(); else if (com.startsWith(CMD_CHANGEDRAWINGDIRECTION)) exec_changeDrawingDirection(); else if (com.startsWith(CMD_SETPOSITION)) exec_setPosition(); else if (com.startsWith(CMD_TESTPENWIDTHSQUARE)) pixel_testPenWidth(); else if (com.startsWith(CMD_PENDOWN)) penlift_penDown(); else if (com.startsWith(CMD_PENUP)) penlift_penUp(); else if (com.startsWith(CMD_SETMACHINESIZE)) exec_setMachineSizeFromCommand(); else if (com.startsWith(CMD_SETMACHINENAME)) exec_setMachineNameFromCommand(); else if (com.startsWith(CMD_SETMACHINEMMPERREV)) exec_setMachineMmPerRevFromCommand(); else if (com.startsWith(CMD_SETMACHINESTEPSPERREV)) exec_setMachineStepsPerRevFromCommand(); else if (com.startsWith(CMD_SETMACHINESTEPMULTIPLIER)) exec_setMachineStepMultiplierFromCommand(); else if (com.startsWith(CMD_GETMACHINEDETAILS)) exec_reportMachineSpec(); else if (com.startsWith(CMD_RESETEEPROM)) eeprom_resetEeprom(); else executed = false; return executed; } void exec_changeDrawingDirection() { globalDrawDirectionMode = asInt(inParam1); globalDrawDirection = asInt(inParam2); Michael_SerialPrint(F("Changed draw direction mode to be ")); Michael_SerialPrint(globalDrawDirectionMode); Michael_SerialPrint(F(" and direction is ")); Michael_SerialPrintln(globalDrawDirection); } void exec_reportMachineSpec() { eeprom_dumpEeprom(); Michael_SerialPrint(F("PGNAME,")); Michael_SerialPrint(machineName); Michael_SerialPrintln(CMD_END); Michael_SerialPrint(F("PGSIZE,")); Michael_SerialPrint(machineWidth); Michael_SerialPrint(COMMA); Michael_SerialPrint(machineHeight); Michael_SerialPrintln(CMD_END); Michael_SerialPrint(F("PGMMPERREV,")); Michael_SerialPrint(mmPerRev); Michael_SerialPrintln(CMD_END); Michael_SerialPrint(F("PGSTEPSPERREV,")); Michael_SerialPrint(motorStepsPerRev); Michael_SerialPrintln(CMD_END); Michael_SerialPrint(F("PGSTEPMULTIPLIER,")); Michael_SerialPrint(stepMultiplier); Michael_SerialPrintln(CMD_END); } void exec_setMachineSizeFromCommand() { int width = asInt(inParam1); int height = asInt(inParam2); if (width > 10) { eeprom_EEPROMWriteInt(EEPROM_MACHINE_WIDTH, width); } if (height > 10) { eeprom_EEPROMWriteInt(EEPROM_MACHINE_HEIGHT, height); } eeprom_loadMachineSpecFromEeprom(); } void exec_setMachineNameFromCommand() { String name = inParam1; if (name != DEFAULT_MACHINE_NAME) { for (int i = 0; i < 8; i++) { EEPROM.write(EEPROM_MACHINE_NAME+i, name[i]); } } eeprom_loadMachineSpecFromEeprom(); } void exec_setMachineMmPerRevFromCommand() { float mmPerRev = asFloat(inParam1); eeprom_EEPROMWriteInt(EEPROM_MACHINE_MM_PER_REV, mmPerRev); eeprom_loadMachineSpecFromEeprom(); } void exec_setMachineStepsPerRevFromCommand() { int stepsPerRev = asInt(inParam1); eeprom_EEPROMWriteInt(EEPROM_MACHINE_STEPS_PER_REV, stepsPerRev); eeprom_loadMachineSpecFromEeprom(); } void exec_setMachineStepMultiplierFromCommand() { eeprom_EEPROMWriteInt(EEPROM_MACHINE_STEP_MULTIPLIER, asInt(inParam1)); eeprom_loadMachineSpecFromEeprom(); } void exec_setMotorSpeed() { exec_setMotorSpeed(asFloat(inParam1)); } void exec_setMotorSpeed(float speed) { currentMaxSpeed = speed; motorA.setMaxSpeed(currentMaxSpeed); motorB.setMaxSpeed(currentMaxSpeed); Michael_SerialPrint(F("New max speed: ")); Michael_SerialPrintln(currentMaxSpeed); } void exec_changeMotorSpeed() { float speedChange = asFloat(inParam1); float newSpeed = currentMaxSpeed + speedChange; exec_setMotorSpeed(newSpeed); } void exec_setMotorAcceleration() { exec_setMotorAcceleration(asFloat(inParam1)); } void exec_setMotorAcceleration(float accel) { currentAcceleration = accel; motorA.setAcceleration(currentAcceleration); motorB.setAcceleration(currentAcceleration); Michael_SerialPrint(F("New acceleration: ")); Michael_SerialPrintln(currentAcceleration); } void exec_changeMotorAcceleration() { float speedChange = asFloat(inParam1); float newAccel = currentAcceleration + speedChange; exec_setMotorAcceleration(newAccel); } void exec_changePenWidth() { penWidth = asFloat(inParam1); Michael_SerialPrint(F("Changed Pen width to ")); Michael_SerialPrint(penWidth); Michael_SerialPrint(F("mm")); Michael_SerialPrintln(); } void exec_setPosition() { long targetA = multiplier(asLong(inParam1)); long targetB = multiplier(asLong(inParam2)); motorA.setCurrentPosition(targetA); motorB.setCurrentPosition(targetB); engageMotors(); reportPosition(); } void exec_changeLengthRelative() { long lenA = multiplier(asLong(inParam1)); long lenB = multiplier(asLong(inParam2)); changeLengthRelative(lenA, lenB); } void exec_changeLength() { float lenA = multiplier(asFloat(inParam1)); float lenB = multiplier(asFloat(inParam2)); changeLength(lenA, lenB); } void exec_changeLengthDirect() { float endA = multiplier(asFloat(inParam1)); float endB = multiplier(asFloat(inParam2)); int maxSegmentLength = asInt(inParam3); float startA = motorA.currentPosition(); float startB = motorB.currentPosition(); if (endA < 20 || endB < 20 || endA > getMaxLength() || endB > getMaxLength()) { Michael_SerialPrintln("This point falls outside the area of this machine. Skipping it."); } else { Michael_SerialPrintln("dr.5"); exec_drawBetweenPoints(startA, startB, endA, endB, maxSegmentLength); } } /** This moves the gondola in a straight line between p1 and p2. Both input coordinates are in the native coordinates system. The fidelity of the line is controlled by maxLength - this is the longest size a line segment is allowed to be. 1 is finest, slowest. Use higher values for faster, wobblier. */ void exec_drawBetweenPoints(float p1a, float p1b, float p2a, float p2b, int maxSegmentLength) { // ok, we're going to plot some dots between p1 and p2. Using maths. I know! Brave new world etc. // First, convert these values to cartesian coordinates // We're going to figure out how many segments the line // needs chopping into. float c1x = getCartesianXFP(p1a, p1b); float c1y = getCartesianYFP(c1x, p1a); float c2x = getCartesianXFP(p2a, p2b); float c2y = getCartesianYFP(c2x, p2a); // test to see if it's on the page if (c2x > 20 && c2x<pageWidth-20 && c2y > 20 && c2y <pageHeight-20) { reportingPosition = false; float deltaX = c2x-c1x; // distance each must move (signed) float deltaY = c2y-c1y; float totalDistance = sqrt(sq(deltaX) + sq(deltaY)); int linesegs = 1; // assume at least 1 line segment will get us there. if (abs(deltaX) > abs(deltaY)) { // slope <=1 case while ((abs(deltaX)/linesegs) > maxSegmentLength) { linesegs++; } } else { // slope >1 case while ((abs(deltaY)/linesegs) > maxSegmentLength) { linesegs++; } } // reduce delta to one line segments' worth. deltaX = deltaX/linesegs; deltaY = deltaY/linesegs; // render the line in N shorter segments long runSpeed = 0; usingAcceleration = false; while (linesegs > 0) { // compute next new location c1x = c1x + deltaX; c1y = c1y + deltaY; // convert back to machine space float pA = getMachineA(c1x, c1y); float pB = getMachineB(c1x, c1y); // do the move runSpeed = desiredSpeed(linesegs, runSpeed, currentAcceleration*4); // Serial.print("Runspeed:"); // Serial.println(runSpeed); motorA.setSpeed(runSpeed); motorB.setSpeed(runSpeed); changeLength(pA, pB); // one line less to do! linesegs--; } // do the end point in case theres been some rounding errors etc motorA.setSpeed(0); motorB.setSpeed(0); reportingPosition = true; changeLength(p2a, p2b); usingAcceleration = true; } else { Michael_SerialPrintln("Line is not on the page. Skipping it."); } outputAvailableMemory(); } // Work out and return a new speed. // Subclasses can override if they want // Implement acceleration, deceleration and max speed // Negative speed is anticlockwise // This is called: // after each step // after user changes: // maxSpeed // acceleration // target position (relative or absolute) float desiredSpeed(long distanceTo, float currentSpeed, float acceleration) { float requiredSpeed; if (distanceTo == 0) return 0.0f; // We're there // sqrSpeed is the signed square of currentSpeed. float sqrSpeed = sq(currentSpeed); if (currentSpeed < 0.0) sqrSpeed = -sqrSpeed; float twoa = 2.0f * acceleration; // 2ag // if v^^2/2as is the the left of target, we will arrive at 0 speed too far -ve, need to accelerate clockwise if ((sqrSpeed / twoa) < distanceTo) { // Accelerate clockwise // Need to accelerate in clockwise direction if (currentSpeed == 0.0f) requiredSpeed = sqrt(twoa); else requiredSpeed = currentSpeed + fabs(acceleration / currentSpeed); if (requiredSpeed > currentMaxSpeed) requiredSpeed = currentMaxSpeed; } else { // Decelerate clockwise, accelerate anticlockwise // Need to accelerate in clockwise direction if (currentSpeed == 0.0f) requiredSpeed = -sqrt(twoa); else requiredSpeed = currentSpeed - fabs(acceleration / currentSpeed); if (requiredSpeed < -currentMaxSpeed) requiredSpeed = -currentMaxSpeed; } //Serial.println(requiredSpeed); return requiredSpeed; }
[ "IRELANM@SYD0LT-210.goodrich.root.local" ]
IRELANM@SYD0LT-210.goodrich.root.local
7ff423bd8f5bc82373bea9989c83a63d8b15b053
bf0b58bcb5141fc3f0c5dbacae15d84c703e95ab
/Plugins/UnrealEnginePython/Source/UnrealEnginePython/Private/UEPySequencer.cpp
b7d189f83353f118719315e99dfaf75e86f936e0
[ "MIT" ]
permissive
mrG7/tensorflow-ue4-examples
9fa1a2475ea022c9b75f9d3f2bd106343e87dcce
94482eaa0576a812be66dd62795605afc3ee5bcf
refs/heads/master
2021-01-19T14:57:22.156420
2017-03-30T02:50:47
2017-03-30T02:50:47
86,651,659
3
1
null
null
null
null
UTF-8
C++
false
false
8,856
cpp
#include "UnrealEnginePythonPrivatePCH.h" #include "Runtime/MovieScene/Public/MovieScene.h" #include "Runtime/MovieScene/Public/MovieScenePossessable.h" #include "Runtime/MovieScene/Public/MovieSceneBinding.h" #include "Runtime/MovieScene/Public/MovieSceneTrack.h" #include "Runtime/MovieScene/Public/MovieSceneNameableTrack.h" #include "Runtime/LevelSequence/Public/LevelSequence.h" PyObject *py_ue_sequencer_possessable_tracks(ue_PyUObject *self, PyObject * args) { ue_py_check(self); char *guid; if (!PyArg_ParseTuple(args, "s:sequencer_possessable_tracks", &guid)) { return NULL; } if (!self->ue_object->IsA<ULevelSequence>()) return PyErr_Format(PyExc_Exception, "uobject is not a LevelSequence"); FGuid f_guid; if (!FGuid::Parse(FString(guid), f_guid)) { return PyErr_Format(PyExc_Exception, "invalid GUID"); } ULevelSequence *seq = (ULevelSequence *)self->ue_object; UMovieScene *scene = seq->GetMovieScene(); PyObject *py_tracks = PyList_New(0); FMovieScenePossessable *possessable = scene->FindPossessable(f_guid); if (!possessable) return PyErr_Format(PyExc_Exception, "GUID not found"); TArray<FMovieSceneBinding> bindings = scene->GetBindings(); for (FMovieSceneBinding binding : bindings) { if (binding.GetObjectGuid() != f_guid) continue; for (UMovieSceneTrack *track : binding.GetTracks()) { ue_PyUObject *ret = ue_get_python_wrapper((UObject *)track); if (!ret) { Py_DECREF(py_tracks); return PyErr_Format(PyExc_Exception, "PyUObject is in invalid state"); } PyList_Append(py_tracks, (PyObject *)ret); } break; } return py_tracks; } PyObject *py_ue_sequencer_find_possessable(ue_PyUObject *self, PyObject * args) { ue_py_check(self); char *guid; if (!PyArg_ParseTuple(args, "s:sequencer_find_possessable", &guid)) { return NULL; } if (!self->ue_object->IsA<ULevelSequence>()) return PyErr_Format(PyExc_Exception, "uobject is not a LevelSequence"); FGuid f_guid; if (!FGuid::Parse(FString(guid), f_guid)) { return PyErr_Format(PyExc_Exception, "invalid GUID"); } ULevelSequence *seq = (ULevelSequence *)self->ue_object; UObject *u_obj = seq->FindPossessableObject(f_guid, seq); if (!u_obj) return PyErr_Format(PyExc_Exception, "unable to find uobject with GUID \"%s\"", guid); PyObject *ret = (PyObject *) ue_get_python_wrapper(u_obj); if (!ret) return PyErr_Format(PyExc_Exception, "PyUObject is in invalid state"); Py_INCREF(ret); return ret; } PyObject *py_ue_sequencer_master_tracks(ue_PyUObject *self, PyObject * args) { ue_py_check(self); if (!self->ue_object->IsA<ULevelSequence>()) return PyErr_Format(PyExc_Exception, "uobject is not a LevelSequence"); ULevelSequence *seq = (ULevelSequence *)self->ue_object; UMovieScene *scene = seq->GetMovieScene(); PyObject *py_tracks = PyList_New(0); TArray<UMovieSceneTrack *> tracks = scene->GetMasterTracks(); for (UMovieSceneTrack *track : tracks) { ue_PyUObject *ret = ue_get_python_wrapper((UObject *)track); if (!ret) { Py_DECREF(py_tracks); return PyErr_Format(PyExc_Exception, "PyUObject is in invalid state"); } PyList_Append(py_tracks, (PyObject *)ret); } return py_tracks; } PyObject *py_ue_sequencer_possessables(ue_PyUObject *self, PyObject * args) { ue_py_check(self); if (!self->ue_object->IsA<ULevelSequence>()) return PyErr_Format(PyExc_Exception, "uobject is not a LevelSequence"); ULevelSequence *seq = (ULevelSequence *)self->ue_object; UMovieScene *scene = seq->GetMovieScene(); PyObject *py_possessables = PyList_New(0); for (int32 i = 0; i < scene->GetPossessableCount();i++) { FMovieScenePossessable possessable = scene->GetPossessable(i); PyObject *py_possessable = PyTuple_New(3); PyTuple_SetItem(py_possessable, 0, PyUnicode_FromString(TCHAR_TO_UTF8(*possessable.GetGuid().ToString()))); PyTuple_SetItem(py_possessable, 1, PyUnicode_FromString(TCHAR_TO_UTF8(*possessable.GetName()))); UClass *u_class = (UClass *)possessable.GetPossessedObjectClass(); ue_PyUObject *ret = ue_get_python_wrapper(u_class); if (!ret) { // here we will leak memory :( Py_DECREF(py_possessables); return PyErr_Format(PyExc_Exception, "PyUObject is in invalid state"); } PyTuple_SetItem(py_possessable, 2, (PyObject *)ret); PyList_Append(py_possessables, py_possessable); } return py_possessables; } #if WITH_EDITOR PyObject *py_ue_sequencer_folders(ue_PyUObject *self, PyObject * args) { ue_py_check(self); if (!self->ue_object->IsA<ULevelSequence>()) return PyErr_Format(PyExc_Exception, "uobject is not a LevelSequence"); ULevelSequence *seq = (ULevelSequence *)self->ue_object; UMovieScene *scene = seq->GetMovieScene(); PyObject *py_folders = PyList_New(0); TArray<UMovieSceneFolder *> folders = scene->GetRootFolders(); for (UMovieSceneFolder *folder : folders) { ue_PyUObject *ret = ue_get_python_wrapper((UObject *)folder); if (!ret) { Py_DECREF(py_folders); return PyErr_Format(PyExc_Exception, "PyUObject is in invalid state"); } PyList_Append(py_folders, (PyObject *)ret); } return py_folders; } #endif PyObject *py_ue_sequencer_sections(ue_PyUObject *self, PyObject * args) { ue_py_check(self); if (!self->ue_object->IsA<ULevelSequence>()) return PyErr_Format(PyExc_Exception, "uobject is not a LevelSequence"); ULevelSequence *seq = (ULevelSequence *)self->ue_object; UMovieScene *scene = seq->GetMovieScene(); PyObject *py_sections = PyList_New(0); TArray<UMovieSceneSection *> sections = scene->GetAllSections(); for (UMovieSceneSection *section : sections) { ue_PyUObject *ret = ue_get_python_wrapper((UObject *)section); if (!ret) { Py_DECREF(py_sections); return PyErr_Format(PyExc_Exception, "PyUObject is in invalid state"); } PyList_Append(py_sections, (PyObject *)ret); } return py_sections; } PyObject *py_ue_sequencer_track_sections(ue_PyUObject *self, PyObject * args) { ue_py_check(self); if (!self->ue_object->IsA<UMovieSceneTrack>()) return PyErr_Format(PyExc_Exception, "uobject is not a UMovieSceneTrack"); UMovieSceneTrack *track = (UMovieSceneTrack *)self->ue_object; PyObject *py_sections = PyList_New(0); TArray<UMovieSceneSection *> sections = track->GetAllSections(); for (UMovieSceneSection *section : sections) { ue_PyUObject *ret = ue_get_python_wrapper((UObject *)section); if (!ret) { Py_DECREF(py_sections); return PyErr_Format(PyExc_Exception, "PyUObject is in invalid state"); } PyList_Append(py_sections, (PyObject *)ret); } return py_sections; } PyObject *py_ue_sequencer_add_master_track(ue_PyUObject *self, PyObject * args) { ue_py_check(self); PyObject *obj; if (!PyArg_ParseTuple(args, "O:sequencer_add_master_track", &obj)) { return NULL; } if (!self->ue_object->IsA<ULevelSequence>()) return PyErr_Format(PyExc_Exception, "uobject is not a LevelSequence"); ULevelSequence *seq = (ULevelSequence *)self->ue_object; UMovieScene *scene = seq->GetMovieScene(); ue_PyUObject *py_obj = ue_is_pyuobject(obj); if (!py_obj) return PyErr_Format(PyExc_Exception, "argument is not a uobject"); if (!py_obj->ue_object->IsA<UClass>()) return PyErr_Format(PyExc_Exception, "uobject is not a UClass"); UClass *u_class = (UClass *)py_obj->ue_object; if (!u_class->IsChildOf<UMovieSceneTrack>()) return PyErr_Format(PyExc_Exception, "uobject is not a UMovieSceneTrack class"); UMovieSceneTrack *track = scene->AddMasterTrack(u_class); if (!track) return PyErr_Format(PyExc_Exception, "unable to create new master track"); PyObject *ret = (PyObject *)ue_get_python_wrapper(track); if (!ret) return PyErr_Format(PyExc_Exception, "PyUObject is in invalid state"); Py_INCREF(ret); return ret; } #if WITH_EDITOR // smart functions allowing the set/get of display names to various sequencer objects PyObject *py_ue_sequencer_set_display_name(ue_PyUObject *self, PyObject * args) { ue_py_check(self); char *name; if (!PyArg_ParseTuple(args, "s:sequencer_set_display_name", &name)) { return NULL; } if (self->ue_object->IsA<UMovieSceneNameableTrack>()) { UMovieSceneNameableTrack *track = (UMovieSceneNameableTrack *)self->ue_object; track->SetDisplayName(FText::FromString(UTF8_TO_TCHAR(name))); } else { return PyErr_Format(PyExc_Exception, "the uobject does not expose the SetDisplayName() method"); } Py_INCREF(Py_None); return Py_None; } PyObject *py_ue_sequencer_get_display_name(ue_PyUObject *self, PyObject * args) { ue_py_check(self); if (self->ue_object->IsA<UMovieSceneNameableTrack>()) { UMovieSceneNameableTrack *track = (UMovieSceneNameableTrack *)self->ue_object; FText name = track->GetDefaultDisplayName(); return PyUnicode_FromString(TCHAR_TO_UTF8(*name.ToString())); } return PyErr_Format(PyExc_Exception, "the uobject does not expose the GetDefaultDisplayName() method"); } #endif
[ "i.synapse@gmail.com" ]
i.synapse@gmail.com
40abae2ae74c0ce37546a37bb137f324a868b73b
d1ef3ea5961b19183ed4241f97faf5a26bdb64e3
/XenonResurrection/SimulatorXenon2/CicParserSim/indirect.h
577f925e95d80a22eddc31aa2af1ddfc2f726e05
[]
no_license
gabonator/Projects
d69fd88558d79b0104af708e374605a3d4b5d7f4
9d2fa11404ff0a362c876b43a519f4e2728d4d7d
refs/heads/master
2023-08-31T07:53:32.893768
2023-08-23T21:02:40
2023-08-23T21:02:40
139,358,974
24
12
null
2021-07-13T19:42:55
2018-07-01T20:14:01
C++
UTF-8
C++
false
false
6,481
h
// FIXED: first two trees not animating // TODO: cannot buy anything in shop // TODO: should blink white when hit // FIXED: two trees in front of first boss // TODO: worms coming out from wrong hole // FIXED: cannon does not work // FIXED: respawn position on map wrong void sub_1F2BA(); void sub_14311(); void sub_14759(); void sub_1480B(int pc); void sub_14759(); void sub_172C4(); void sub_1758F(); void sub_1655B(); void sub_1714A(); void sub_10853(); void sub_10761() { /* ret */ } void sub_17520(); void sub_170F1(); void sub_1705B(); void loc_135CE(); void sub_16F7F(); void loc_16F00(); void sub_16FE0(); void loc_1705B(); void sub_11E61(); void sub_107C0(); void sub_128DF(); void sub_16F00(); void sub_13B76(); void sub_16AAD(); void sub_13BDF(); void sub_16EEF() { _bx <<= 1; switch (_bx) { case 0: loc_135CE(); return; case 2: sub_16F7F(); return; case 4: sub_16F00(); return; case 6: sub_16FE0(); return; case 8: sub_1705B(); return; } } void sub_170F1(); void sub_141E2(); void sub_1480B(int pc); void sub_108B9(); void sub_107A0(); void sub_10F2B(); void sub_137CA(); void sub_128DF(); void sub_12AB2(); void sub_13AA7(); void sub_12A6E(); void sub_16D22(); void sub_13A39(); void sub_1308C(); void sub_139EE(); void sub_1091F(); void sub_10897(); void sub_137DF(); void sub_13998(); void sub_1655B(); void loc_1308C(); void sub_141FB(); void sub_11F4D(); void sub_13835(); void sub_16A0A(); void sub_125A8(); void sub_16AAD(); void sub_16696(); void sub_169D0(); void sub_166A6(); void sub_16AC7(); void sub_16BCA(); void sub_12AD0(); void sub_16E2C(); void sub_171DD(); void sub_12A48(); void sub_1714D(); void sub_169C8(); void sub_13246(); void sub_13A99(); void sub_17569(); void sub_1F732(); void sub_18CA7(); void sub_17F32(); void sub_18CA7(); void sub_17F79(); void sub_18E01(); void sub_189AE(); void sub_188A9(); void sub_18C3E(); void sub_17DDE(); void sub_19F02(); void sub_19F4E(); void sub_121E9(); void sub_1246D(); void sub_128B8(); void sub_14F96(); void sub_180CA(); void sub_12AA4(); void sub_1866D(); void sub_18114(); void sub_18126(); void sub_180F5(); void sub_187D5(); void sub_18783(); void _indirectCall(WORD seg, int ptr) { _ASSERT(ptr >= 0 && ptr <= 0xffff); // ma byt 4311 ale je 9f02 // if (ptr!=0x0853 && ptr != 0x7520) // std::cout << "indirect " << (int)ptr << "\n"; if (seg==_seg000 && ptr==0x002a) //0x000c) { sub_1F2BA(); return; } switch (ptr) { case 0x4311: sub_14311(); break; case 0x4759: sub_14759(); break; case 0x37df: // fire sub_137DF(); break; case 0x72c4: sub_172C4(); break; case 0x758f: sub_1758F(); break; case 0x655b: sub_1655B(); break; // enter shop case 0x0853: sub_10853(); break; // draw ship case 0x0761: sub_10761(); break; case 0x7520: sub_17520(); break; case 0x70f1: sub_170F1(); break; case 0x6EEF: sub_16EEF(); break; case 0x41E2: sub_141E2(); break; case 0x480b: sub_1480B(0); break; case 0x714A: sub_1714A(); break; case 0x08B9: /*sub_108B9();*/ break; // strom? case 0x0f2b: sub_10F2B(); break; case 0x37ca: sub_137CA(); break; // swingtail case 0x1e61: sub_11E61(); break; // hit2 case 0x28df: sub_128DF(); break; // hit3 case 0x2ab2: sub_12AB2(); break; // speed powerup case 0x3aa7: sub_13AA7(); break; // hit1 case 0x2a6e: sub_12A6E(); break; // power powerup case 0x6d22: sub_16D22(); break; // tree - animation case 0x3a39: sub_13A39(); break; // swingtail hit case 0x308C: sub_13246(); // gabo cannon combo! loc_1308C(); break; // rearshot powerup case 0x39ee: sub_139EE(); break; // draw fire case 0x091f: sub_1091F(); break; // draw fire case 0x0897:/* sub_10897();*/ break; // lv2 boss case 0x3998: sub_13998(); break; // explosion anim case 0x41fb: sub_141FB(); break; // explosion cleanup case 0x1f4d: sub_11F4D(); break; // tree bulet move case 0x3835: sub_13835(); break; case 0x3B76: sub_13B76(); break;// tree hit case 0x6a0a: sub_16A0A(); break;// case 0x25a8: sub_125A8(); break;// case 0x6aad: sub_16AAD(); break; case 0x3bdf: sub_13BDF(); break; case 0x6696: sub_16696(); break; // worm hit case 0x69D0: sub_169D0(); break; // worm segment fly case 0x66a6: sub_166A6(); break; case 0x6ac7: sub_16AC7(); break; case 0x6bca: sub_16BCA(); break; case 0x2ad0: sub_12AD0(); break; //case 0x5e2c: break; case 0x6e2c: sub_16E2C(); break; case 0x71dd: sub_171DD(); break; case 0x2a48: sub_12A48(); break; // small heart case 0x714d: sub_1714D(); break; // lv1 boss hit case 0x69C8: sub_169C8(); break; case 0x3246: sub_13246(); break; // powerup - cannon case 0x3a99: sub_13A99(); break; case 0x7569: sub_17569(); break; //case 0xf732: sub_1F732(); break; case 0x8ca7: sub_18CA7(); break; // zero! case 0x7f32: sub_17F32(); break; case 0x7f79: sub_17F79(); break; case 0x8e01: sub_18E01(); break; case 0x89AE: sub_189AE(); break; case 0x88A9: sub_188A9(); break; case 0x8C3E: sub_18C3E(); break; case 0x7DDE: sub_17DDE(); break; case 0x6284: break; // retn case 0x9f02: sub_19F02(); break; case 0x9f9A: case 0x9fe6: case 0x9f4E: sub_19F4E(); break; case 0x21e9: sub_121E9(); break; // cannon case 0x246d: sub_1246D(); break; // cannon case 0x28b8: sub_128B8(); break; // cannon fire //case 0x4f9d: break; // advise // level 2 case 0x4f96: sub_14F96(); break; // horse case 0x2aa4: sub_12AA4(); break; // autoshoot case 0x80ca: sub_180CA(); break; case 0x866d: sub_1866D(); break; // lv2 boss case 0x8114: sub_18114(); break; case 0x8126: sub_18126(); break; case 0x80f5: sub_180F5(); break; case 0x87D5: sub_187D5(); break; case 0x8783: sub_18783(); break; //7e87 default: // _ASSERT(0); std::cout << "Not implemented " << std::hex << (int)ptr << "\n"; //assert(0); } }
[ "gvalky@sygic.com" ]
gvalky@sygic.com
6d12fce89ccd03f83ae64c4f339c7f095d0ff86f
f933b3960ba73367d95b510c196a5e13d9e77ab9
/trx/inc/opencv/opencv2/contrib/detection_based_tracker.hpp
4b8a0277b35e061b2fa36756dcaee8fe880e21b9
[]
no_license
victorursu/walls
7ba50033c1ad28f66e8a97bcf37248e527c878a1
fab6c82714d837acdc5ecb95c7cb36a5d0cbc903
refs/heads/master
2021-01-21T14:17:21.934574
2017-02-19T23:58:52
2017-02-19T23:58:52
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,384
hpp
#pragma once #if defined(__linux__) || defined(LINUX) || defined(__APPLE__) || defined(__ANDROID__) #include <opencv2/core.hpp> #include <opencv2/objdetect.hpp> #include <vector> namespace cv { class CV_EXPORTS DetectionBasedTracker { public: struct Parameters { int maxTrackLifetime; int minDetectionPeriod; //the minimal time between run of the big object detector (on the whole frame) in ms (1000 mean 1 sec), default=0 Parameters(); }; class IDetector { public: IDetector(): minObjSize(96, 96), maxObjSize(INT_MAX, INT_MAX), minNeighbours(2), scaleFactor(1.1f) {} virtual void detect(const cv::Mat& image, std::vector<cv::Rect>& objects) = 0; void setMinObjectSize(const cv::Size& min) { minObjSize = min; } void setMaxObjectSize(const cv::Size& max) { maxObjSize = max; } cv::Size getMinObjectSize() const { return minObjSize; } cv::Size getMaxObjectSize() const { return maxObjSize; } float getScaleFactor() { return scaleFactor; } void setScaleFactor(float value) { scaleFactor = value; } int getMinNeighbours() { return minNeighbours; } void setMinNeighbours(int value) { minNeighbours = value; } virtual ~IDetector() {} protected: cv::Size minObjSize; cv::Size maxObjSize; int minNeighbours; float scaleFactor; }; DetectionBasedTracker(cv::Ptr<IDetector> mainDetector, cv::Ptr<IDetector> trackingDetector, const Parameters& params); virtual ~DetectionBasedTracker(); virtual bool run(); virtual void stop(); virtual void resetTracking(); virtual void process(const cv::Mat& imageGray); bool setParameters(const Parameters& params); const Parameters& getParameters() const; typedef std::pair<cv::Rect, int> Object; virtual void getObjects(std::vector<cv::Rect>& result) const; virtual void getObjects(std::vector<Object>& result) const; enum ObjectStatus { DETECTED_NOT_SHOWN_YET, DETECTED, DETECTED_TEMPORARY_LOST, WRONG_OBJECT }; struct ExtObject { int id; cv::Rect location; ObjectStatus status; ExtObject(int _id, cv::Rect _location, ObjectStatus _status) :id(_id), location(_location), status(_status) { } }; virtual void getObjects(std::vector<ExtObject>& result) const; virtual int addObject(const cv::Rect& location); //returns id of the new object protected: class SeparateDetectionWork; cv::Ptr<SeparateDetectionWork> separateDetectionWork; friend void* workcycleObjectDetectorFunction(void* p); struct InnerParameters { int numLastPositionsToTrack; int numStepsToWaitBeforeFirstShow; int numStepsToTrackWithoutDetectingIfObjectHasNotBeenShown; int numStepsToShowWithoutDetecting; float coeffTrackingWindowSize; float coeffObjectSizeToTrack; float coeffObjectSpeedUsingInPrediction; InnerParameters(); }; Parameters parameters; InnerParameters innerParameters; struct TrackedObject { typedef std::vector<cv::Rect> PositionsVector; PositionsVector lastPositions; int numDetectedFrames; int numFramesNotDetected; int id; TrackedObject(const cv::Rect& rect):numDetectedFrames(1), numFramesNotDetected(0) { lastPositions.push_back(rect); id=getNextId(); }; static int getNextId() { static int _id=0; return _id++; } }; int numTrackedSteps; std::vector<TrackedObject> trackedObjects; std::vector<float> weightsPositionsSmoothing; std::vector<float> weightsSizesSmoothing; cv::Ptr<IDetector> cascadeForTracking; void updateTrackedObjects(const std::vector<cv::Rect>& detectedObjects); cv::Rect calcTrackedObjectPositionToShow(int i) const; cv::Rect calcTrackedObjectPositionToShow(int i, ObjectStatus& status) const; void detectInRegion(const cv::Mat& img, const cv::Rect& r, std::vector<cv::Rect>& detectedObjectsInRegions); }; } //end of cv namespace #endif
[ "jedwards@fastmail.com" ]
jedwards@fastmail.com
18b1db7ad7d86393b2289bc1b5e6795227f1f19a
53c4e64c6c3f7e85dbb78b96fe4d53aef3524f7b
/Collision.h
f50bf4732a5234968835b1c83edf1d01a0861ac1
[]
no_license
ska9641/20151695
2d9feddf6dd237e7b79057a76620421945dd0255
ae972e10670e50879c680190acdf33e0f6c40672
refs/heads/master
2021-01-09T06:38:46.833097
2016-06-14T02:18:23
2016-06-14T02:18:23
61,084,266
0
0
null
null
null
null
UTF-8
C++
false
false
478
h
#pragma once #include "Boss.h" #include "Bullet.h" #include "Tank.h" #include "Wall.h" #include "Object.h" class Collision { private: public: Collision(); ~Collision(); static bool CollisionOBJ(CObject *_obj1,CObject *_obj2); static void CollisionBuObj(CBullet *_bu,CObject *_obj); static void CollisionTaWa(CTank *_ta,CWall *_wa); static void CollisionBuMap(CBullet *_bu, CWall *_wall); static bool CollisionOb(CObject * _obj1, CObject * _obj2); };
[ "noreply@github.com" ]
ska9641.noreply@github.com
d25247daad4b76a56b6b7f0249ae3b13a5d2c190
0b2c2179046bb8cf4d6d6cc9d736529fda603556
/plugins/MacVST/TransDesk/source/TransDeskProc.cpp
c8b45c2d561d6b869a41b067abb754237d13501c
[ "MIT" ]
permissive
benjohnson2001/airwindows
5730fc7e79c1e16e07b5950bb9c925e97c3d8caa
37719b99ec4d6882ab0e836d423cb69a86472aac
refs/heads/master
2022-04-24T08:25:50.677085
2020-04-25T06:07:00
2020-04-25T06:07:00
258,698,797
0
0
MIT
2020-04-25T05:56:15
2020-04-25T05:56:15
null
UTF-8
C++
false
false
15,618
cpp
/* ======================================== * TransDesk - TransDesk.h * Copyright (c) 2016 airwindows, All rights reserved * ======================================== */ #ifndef __TransDesk_H #include "TransDesk.h" #endif void TransDesk::processReplacing(float **inputs, float **outputs, VstInt32 sampleFrames) { float* in1 = inputs[0]; float* in2 = inputs[1]; float* out1 = outputs[0]; float* out2 = outputs[1]; double overallscale = 1.0; overallscale /= 44100.0; overallscale *= getSampleRate(); double intensity = 0.02198359; double depthA = 3.0; int offsetA = (int)(depthA * overallscale); if (offsetA < 1) offsetA = 1; if (offsetA > 8) offsetA = 8; double clamp; double thickness; double out; double gain = 0.130; double slewgain = 0.197; double prevslew = 0.255; double balanceB = 0.0001; slewgain *= overallscale; prevslew *= overallscale; balanceB /= overallscale; double balanceA = 1.0 - balanceB; double slew; double bridgerectifier; double combSample; long double inputSampleL; long double inputSampleR; long double drySampleL; long double drySampleR; while (--sampleFrames >= 0) { inputSampleL = *in1; inputSampleR = *in2; if (inputSampleL<1.2e-38 && -inputSampleL<1.2e-38) { static int noisesource = 0; //this declares a variable before anything else is compiled. It won't keep assigning //it to 0 for every sample, it's as if the declaration doesn't exist in this context, //but it lets me add this denormalization fix in a single place rather than updating //it in three different locations. The variable isn't thread-safe but this is only //a random seed and we can share it with whatever. noisesource = noisesource % 1700021; noisesource++; int residue = noisesource * noisesource; residue = residue % 170003; residue *= residue; residue = residue % 17011; residue *= residue; residue = residue % 1709; residue *= residue; residue = residue % 173; residue *= residue; residue = residue % 17; double applyresidue = residue; applyresidue *= 0.00000001; applyresidue *= 0.00000001; inputSampleL = applyresidue; } if (inputSampleR<1.2e-38 && -inputSampleR<1.2e-38) { static int noisesource = 0; noisesource = noisesource % 1700021; noisesource++; int residue = noisesource * noisesource; residue = residue % 170003; residue *= residue; residue = residue % 17011; residue *= residue; residue = residue % 1709; residue *= residue; residue = residue % 173; residue *= residue; residue = residue % 17; double applyresidue = residue; applyresidue *= 0.00000001; applyresidue *= 0.00000001; inputSampleR = applyresidue; //this denormalization routine produces a white noise at -300 dB which the noise //shaping will interact with to produce a bipolar output, but the noise is actually //all positive. That should stop any variables from going denormal, and the routine //only kicks in if digital black is input. As a final touch, if you save to 24-bit //the silence will return to being digital black again. } drySampleL = inputSampleL; drySampleR = inputSampleR; if (gcount < 0 || gcount > 9) {gcount = 9;} //begin L dL[gcount+9] = dL[gcount] = fabs(inputSampleL)*intensity; controlL += (dL[gcount] / offsetA); controlL -= (dL[gcount+offsetA] / offsetA); controlL -= 0.000001; clamp = 1; if (controlL < 0) {controlL = 0;} if (controlL > 1) {clamp -= (controlL - 1); controlL = 1;} if (clamp < 0.5) {clamp = 0.5;} //control = 0 to 1 thickness = ((1.0 - controlL) * 2.0) - 1.0; out = fabs(thickness); bridgerectifier = fabs(inputSampleL); if (bridgerectifier > 1.57079633) bridgerectifier = 1.57079633; //max value for sine function if (thickness > 0) bridgerectifier = sin(bridgerectifier); else bridgerectifier = 1-cos(bridgerectifier); //produce either boosted or starved version if (inputSampleL > 0) inputSampleL = (inputSampleL*(1-out))+(bridgerectifier*out); else inputSampleL = (inputSampleL*(1-out))-(bridgerectifier*out); //blend according to density control inputSampleL *= clamp; slew = inputSampleL - lastSampleL; lastSampleL = inputSampleL; //Set up direct reference for slew bridgerectifier = fabs(slew*slewgain); if (bridgerectifier > 1.57079633) bridgerectifier = 1.0; else bridgerectifier = sin(bridgerectifier); if (slew > 0) slew = bridgerectifier/slewgain; else slew = -(bridgerectifier/slewgain); inputSampleL = (lastOutSampleL*balanceA) + (lastSampleL*balanceB) + slew; //go from last slewed, but include some raw values lastOutSampleL = inputSampleL; //Set up slewed reference combSample = fabs(drySampleL*lastSampleL); if (combSample > 1.0) combSample = 1.0; //bailout for very high input gains inputSampleL -= (lastSlewL * combSample * prevslew); lastSlewL = slew; //slew interaction with previous slew inputSampleL *= gain; bridgerectifier = fabs(inputSampleL); if (bridgerectifier > 1.57079633) bridgerectifier = 1.0; else bridgerectifier = sin(bridgerectifier); if (inputSampleL > 0) inputSampleL = bridgerectifier; else inputSampleL = -bridgerectifier; //drive section inputSampleL /= gain; //end of Desk section //end L //begin R dR[gcount+9] = dR[gcount] = fabs(inputSampleR)*intensity; controlR += (dR[gcount] / offsetA); controlR -= (dR[gcount+offsetA] / offsetA); controlR -= 0.000001; clamp = 1; if (controlR < 0) {controlR = 0;} if (controlR > 1) {clamp -= (controlR - 1); controlR = 1;} if (clamp < 0.5) {clamp = 0.5;} //control = 0 to 1 thickness = ((1.0 - controlR) * 2.0) - 1.0; out = fabs(thickness); bridgerectifier = fabs(inputSampleR); if (bridgerectifier > 1.57079633) bridgerectifier = 1.57079633; //max value for sine function if (thickness > 0) bridgerectifier = sin(bridgerectifier); else bridgerectifier = 1-cos(bridgerectifier); //produce either boosted or starved version if (inputSampleR > 0) inputSampleR = (inputSampleR*(1-out))+(bridgerectifier*out); else inputSampleR = (inputSampleR*(1-out))-(bridgerectifier*out); //blend according to density control inputSampleR *= clamp; slew = inputSampleR - lastSampleR; lastSampleR = inputSampleR; //Set up direct reference for slew bridgerectifier = fabs(slew*slewgain); if (bridgerectifier > 1.57079633) bridgerectifier = 1.0; else bridgerectifier = sin(bridgerectifier); if (slew > 0) slew = bridgerectifier/slewgain; else slew = -(bridgerectifier/slewgain); inputSampleR = (lastOutSampleR*balanceA) + (lastSampleR*balanceB) + slew; //go from last slewed, but include some raw values lastOutSampleR = inputSampleR; //Set up slewed reference combSample = fabs(drySampleR*lastSampleR); if (combSample > 1.0) combSample = 1.0; //bailout for very high input gains inputSampleR -= (lastSlewR * combSample * prevslew); lastSlewR = slew; //slew interaction with previous slew inputSampleR *= gain; bridgerectifier = fabs(inputSampleR); if (bridgerectifier > 1.57079633) bridgerectifier = 1.0; else bridgerectifier = sin(bridgerectifier); if (inputSampleR > 0) inputSampleR = bridgerectifier; else inputSampleR = -bridgerectifier; //drive section inputSampleR /= gain; //end of Desk section //end R gcount--; //stereo 32 bit dither, made small and tidy. int expon; frexpf((float)inputSampleL, &expon); long double dither = (rand()/(RAND_MAX*7.737125245533627e+25))*pow(2,expon+62); inputSampleL += (dither-fpNShapeL); fpNShapeL = dither; frexpf((float)inputSampleR, &expon); dither = (rand()/(RAND_MAX*7.737125245533627e+25))*pow(2,expon+62); inputSampleR += (dither-fpNShapeR); fpNShapeR = dither; //end 32 bit dither *out1 = inputSampleL; *out2 = inputSampleR; *in1++; *in2++; *out1++; *out2++; } } void TransDesk::processDoubleReplacing(double **inputs, double **outputs, VstInt32 sampleFrames) { double* in1 = inputs[0]; double* in2 = inputs[1]; double* out1 = outputs[0]; double* out2 = outputs[1]; double overallscale = 1.0; overallscale /= 44100.0; overallscale *= getSampleRate(); double intensity = 0.02198359; double depthA = 3.0; int offsetA = (int)(depthA * overallscale); if (offsetA < 1) offsetA = 1; if (offsetA > 8) offsetA = 8; double clamp; double thickness; double out; double gain = 0.130; double slewgain = 0.197; double prevslew = 0.255; double balanceB = 0.0001; slewgain *= overallscale; prevslew *= overallscale; balanceB /= overallscale; double balanceA = 1.0 - balanceB; double slew; double bridgerectifier; double combSample; long double inputSampleL; long double inputSampleR; long double drySampleL; long double drySampleR; while (--sampleFrames >= 0) { inputSampleL = *in1; inputSampleR = *in2; if (inputSampleL<1.2e-38 && -inputSampleL<1.2e-38) { static int noisesource = 0; //this declares a variable before anything else is compiled. It won't keep assigning //it to 0 for every sample, it's as if the declaration doesn't exist in this context, //but it lets me add this denormalization fix in a single place rather than updating //it in three different locations. The variable isn't thread-safe but this is only //a random seed and we can share it with whatever. noisesource = noisesource % 1700021; noisesource++; int residue = noisesource * noisesource; residue = residue % 170003; residue *= residue; residue = residue % 17011; residue *= residue; residue = residue % 1709; residue *= residue; residue = residue % 173; residue *= residue; residue = residue % 17; double applyresidue = residue; applyresidue *= 0.00000001; applyresidue *= 0.00000001; inputSampleL = applyresidue; } if (inputSampleR<1.2e-38 && -inputSampleR<1.2e-38) { static int noisesource = 0; noisesource = noisesource % 1700021; noisesource++; int residue = noisesource * noisesource; residue = residue % 170003; residue *= residue; residue = residue % 17011; residue *= residue; residue = residue % 1709; residue *= residue; residue = residue % 173; residue *= residue; residue = residue % 17; double applyresidue = residue; applyresidue *= 0.00000001; applyresidue *= 0.00000001; inputSampleR = applyresidue; //this denormalization routine produces a white noise at -300 dB which the noise //shaping will interact with to produce a bipolar output, but the noise is actually //all positive. That should stop any variables from going denormal, and the routine //only kicks in if digital black is input. As a final touch, if you save to 24-bit //the silence will return to being digital black again. } drySampleL = inputSampleL; drySampleR = inputSampleR; if (gcount < 0 || gcount > 9) {gcount = 9;} //begin L dL[gcount+9] = dL[gcount] = fabs(inputSampleL)*intensity; controlL += (dL[gcount] / offsetA); controlL -= (dL[gcount+offsetA] / offsetA); controlL -= 0.000001; clamp = 1; if (controlL < 0) {controlL = 0;} if (controlL > 1) {clamp -= (controlL - 1); controlL = 1;} if (clamp < 0.5) {clamp = 0.5;} //control = 0 to 1 thickness = ((1.0 - controlL) * 2.0) - 1.0; out = fabs(thickness); bridgerectifier = fabs(inputSampleL); if (bridgerectifier > 1.57079633) bridgerectifier = 1.57079633; //max value for sine function if (thickness > 0) bridgerectifier = sin(bridgerectifier); else bridgerectifier = 1-cos(bridgerectifier); //produce either boosted or starved version if (inputSampleL > 0) inputSampleL = (inputSampleL*(1-out))+(bridgerectifier*out); else inputSampleL = (inputSampleL*(1-out))-(bridgerectifier*out); //blend according to density control inputSampleL *= clamp; slew = inputSampleL - lastSampleL; lastSampleL = inputSampleL; //Set up direct reference for slew bridgerectifier = fabs(slew*slewgain); if (bridgerectifier > 1.57079633) bridgerectifier = 1.0; else bridgerectifier = sin(bridgerectifier); if (slew > 0) slew = bridgerectifier/slewgain; else slew = -(bridgerectifier/slewgain); inputSampleL = (lastOutSampleL*balanceA) + (lastSampleL*balanceB) + slew; //go from last slewed, but include some raw values lastOutSampleL = inputSampleL; //Set up slewed reference combSample = fabs(drySampleL*lastSampleL); if (combSample > 1.0) combSample = 1.0; //bailout for very high input gains inputSampleL -= (lastSlewL * combSample * prevslew); lastSlewL = slew; //slew interaction with previous slew inputSampleL *= gain; bridgerectifier = fabs(inputSampleL); if (bridgerectifier > 1.57079633) bridgerectifier = 1.0; else bridgerectifier = sin(bridgerectifier); if (inputSampleL > 0) inputSampleL = bridgerectifier; else inputSampleL = -bridgerectifier; //drive section inputSampleL /= gain; //end of Desk section //end L //begin R dR[gcount+9] = dR[gcount] = fabs(inputSampleR)*intensity; controlR += (dR[gcount] / offsetA); controlR -= (dR[gcount+offsetA] / offsetA); controlR -= 0.000001; clamp = 1; if (controlR < 0) {controlR = 0;} if (controlR > 1) {clamp -= (controlR - 1); controlR = 1;} if (clamp < 0.5) {clamp = 0.5;} //control = 0 to 1 thickness = ((1.0 - controlR) * 2.0) - 1.0; out = fabs(thickness); bridgerectifier = fabs(inputSampleR); if (bridgerectifier > 1.57079633) bridgerectifier = 1.57079633; //max value for sine function if (thickness > 0) bridgerectifier = sin(bridgerectifier); else bridgerectifier = 1-cos(bridgerectifier); //produce either boosted or starved version if (inputSampleR > 0) inputSampleR = (inputSampleR*(1-out))+(bridgerectifier*out); else inputSampleR = (inputSampleR*(1-out))-(bridgerectifier*out); //blend according to density control inputSampleR *= clamp; slew = inputSampleR - lastSampleR; lastSampleR = inputSampleR; //Set up direct reference for slew bridgerectifier = fabs(slew*slewgain); if (bridgerectifier > 1.57079633) bridgerectifier = 1.0; else bridgerectifier = sin(bridgerectifier); if (slew > 0) slew = bridgerectifier/slewgain; else slew = -(bridgerectifier/slewgain); inputSampleR = (lastOutSampleR*balanceA) + (lastSampleR*balanceB) + slew; //go from last slewed, but include some raw values lastOutSampleR = inputSampleR; //Set up slewed reference combSample = fabs(drySampleR*lastSampleR); if (combSample > 1.0) combSample = 1.0; //bailout for very high input gains inputSampleR -= (lastSlewR * combSample * prevslew); lastSlewR = slew; //slew interaction with previous slew inputSampleR *= gain; bridgerectifier = fabs(inputSampleR); if (bridgerectifier > 1.57079633) bridgerectifier = 1.0; else bridgerectifier = sin(bridgerectifier); if (inputSampleR > 0) inputSampleR = bridgerectifier; else inputSampleR = -bridgerectifier; //drive section inputSampleR /= gain; //end of Desk section //end R gcount--; //stereo 64 bit dither, made small and tidy. int expon; frexp((double)inputSampleL, &expon); long double dither = (rand()/(RAND_MAX*7.737125245533627e+25))*pow(2,expon+62); dither /= 536870912.0; //needs this to scale to 64 bit zone inputSampleL += (dither-fpNShapeL); fpNShapeL = dither; frexp((double)inputSampleR, &expon); dither = (rand()/(RAND_MAX*7.737125245533627e+25))*pow(2,expon+62); dither /= 536870912.0; //needs this to scale to 64 bit zone inputSampleR += (dither-fpNShapeR); fpNShapeR = dither; //end 64 bit dither *out1 = inputSampleL; *out2 = inputSampleR; *in1++; *in2++; *out1++; *out2++; } }
[ "jinx6568@sover.net" ]
jinx6568@sover.net
9b4cea3c9dea6d4197fe3613fb332b23a30d05cc
7b8979bdabad9fd5c600272680ef030d1c14ffba
/Code/swGraphicAPI/DX11API/stdafx.h
74a304b6c5a58fdf628113b5670071d48fb9a5be
[ "LicenseRef-scancode-warranty-disclaimer" ]
no_license
armadi110/VoxelRenderer
2e67883b76f4632a477490d3cd35243d8c1952a5
fcf8aa8105d37638a21bca87fa56e294314a9548
refs/heads/master
2021-09-09T16:05:14.138595
2018-03-13T20:11:27
2018-03-13T20:11:27
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,347
h
#pragma once // stdafx.h : include file for standard system include files, // or project specific include files that are used frequently, but // are changed infrequently // /// @note You can disable all headers in precompiled header with one macro. /// All cpp files should be precompiled header independet and explicitly include needed headers. #ifndef DISABLE_PRECOMPILED_HEADER #include <cassert> #include <string> #include <DirectXMath.h> #pragma warning( disable : 4005 ) #include "d3dx11.h" #include "d3d11.h" #pragma warning( default : 4005 ) #include "swCommonLib/Common/RTTR.h" #include "swGraphicAPI/Resources/MeshResources.h" #include "DX11Resources/DX11PipelineState.h" #include "DX11Resources/DX11Buffer.h" #include "DX11Resources/DX11ComputeShader.h" #include "DX11Resources/DX11InputLayout.h" #include "DX11Resources/DX11InputLayoutDescriptor.h" #include "DX11Resources/DX11PixelShader.h" #include "DX11Resources/DX11RenderTarget.h" #include "DX11Resources/DX11SwapChain.h" #include "DX11Resources/DX11Texture.h" #include "DX11Resources/DX11VertexShader.h" #include "DX11Initializer/DX11APIObjects.h" #include "DX11Initializer/DX11ConstantsMapper.h" #include "DX11Initializer/DX11Initializer.h" #include "DX11Renderer/DX11Renderer.h" #undef min #undef max #undef RegisterClass #endif // !DISABLE_PRECOMPILED_HEADER
[ "nieznany.sprawiciel@gmail.com" ]
nieznany.sprawiciel@gmail.com
4fe2e4d115e1a6dd01503860ea46b10ac2d98375
9911cd289f63b8ad9e5d11f425eae528de32698d
/modules/svg/include/SkSVGTypes.h
e0ea73e44d6f3a51fd919b6617c5f2d9e0310284
[ "BSD-3-Clause" ]
permissive
udevbe/skia
0e74bda28a5479c02006877ec6e07b1482dfe7c2
b432d0b757655ae0f855a4f138b196d2da9ee8a1
refs/heads/master
2023-01-07T09:16:34.705268
2020-10-21T04:01:57
2020-10-21T04:56:01
283,236,350
0
0
NOASSERTION
2020-07-28T14:27:29
2020-07-28T14:27:28
null
UTF-8
C++
false
false
11,162
h
/* * Copyright 2016 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #ifndef SkSVGTypes_DEFINED #define SkSVGTypes_DEFINED #include "include/core/SkColor.h" #include "include/core/SkMatrix.h" #include "include/core/SkPath.h" #include "include/core/SkPoint.h" #include "include/core/SkRect.h" #include "include/core/SkScalar.h" #include "include/core/SkString.h" #include "include/core/SkTypes.h" #include "include/private/SkTDArray.h" using SkSVGColorType = SkColor; using SkSVGNumberType = SkScalar; using SkSVGStringType = SkString; using SkSVGViewBoxType = SkRect; using SkSVGTransformType = SkMatrix; using SkSVGPointsType = SkTDArray<SkPoint>; class SkSVGLength { public: enum class Unit { kUnknown, kNumber, kPercentage, kEMS, kEXS, kPX, kCM, kMM, kIN, kPT, kPC, }; constexpr SkSVGLength() : fValue(0), fUnit(Unit::kUnknown) {} explicit constexpr SkSVGLength(SkScalar v, Unit u = Unit::kNumber) : fValue(v), fUnit(u) {} SkSVGLength(const SkSVGLength&) = default; SkSVGLength& operator=(const SkSVGLength&) = default; bool operator==(const SkSVGLength& other) const { return fUnit == other.fUnit && fValue == other.fValue; } bool operator!=(const SkSVGLength& other) const { return !(*this == other); } const SkScalar& value() const { return fValue; } const Unit& unit() const { return fUnit; } private: SkScalar fValue; Unit fUnit; }; class SkSVGPaint { public: enum class Type { kNone, kCurrentColor, kColor, kInherit, kIRI, }; SkSVGPaint() : fType(Type::kInherit), fColor(SK_ColorBLACK) {} explicit SkSVGPaint(Type t) : fType(t), fColor(SK_ColorBLACK) {} explicit SkSVGPaint(const SkSVGColorType& c) : fType(Type::kColor), fColor(c) {} explicit SkSVGPaint(const SkString& iri) : fType(Type::kIRI), fColor(SK_ColorBLACK), fIRI(iri) {} SkSVGPaint(const SkSVGPaint&) = default; SkSVGPaint& operator=(const SkSVGPaint&) = default; bool operator==(const SkSVGPaint& other) const { return fType == other.fType && fColor == other.fColor && fIRI == other.fIRI; } bool operator!=(const SkSVGPaint& other) const { return !(*this == other); } Type type() const { return fType; } const SkSVGColorType& color() const { SkASSERT(fType == Type::kColor); return fColor; } const SkString& iri() const { SkASSERT(fType == Type::kIRI); return fIRI; } private: Type fType; // Logical union. SkSVGColorType fColor; SkString fIRI; }; class SkSVGClip { public: enum class Type { kNone, kInherit, kIRI, }; SkSVGClip() : fType(Type::kNone) {} explicit SkSVGClip(Type t) : fType(t) {} explicit SkSVGClip(const SkString& iri) : fType(Type::kIRI), fIRI(iri) {} SkSVGClip(const SkSVGClip&) = default; SkSVGClip& operator=(const SkSVGClip&) = default; bool operator==(const SkSVGClip& other) const { return fType == other.fType && fIRI == other.fIRI; } bool operator!=(const SkSVGClip& other) const { return !(*this == other); } Type type() const { return fType; } const SkString& iri() const { SkASSERT(fType == Type::kIRI); return fIRI; } private: Type fType; SkString fIRI; }; class SkSVGLineCap { public: enum class Type { kButt, kRound, kSquare, kInherit, }; constexpr SkSVGLineCap() : fType(Type::kInherit) {} constexpr explicit SkSVGLineCap(Type t) : fType(t) {} SkSVGLineCap(const SkSVGLineCap&) = default; SkSVGLineCap& operator=(const SkSVGLineCap&) = default; bool operator==(const SkSVGLineCap& other) const { return fType == other.fType; } bool operator!=(const SkSVGLineCap& other) const { return !(*this == other); } Type type() const { return fType; } private: Type fType; }; class SkSVGLineJoin { public: enum class Type { kMiter, kRound, kBevel, kInherit, }; constexpr SkSVGLineJoin() : fType(Type::kInherit) {} constexpr explicit SkSVGLineJoin(Type t) : fType(t) {} SkSVGLineJoin(const SkSVGLineJoin&) = default; SkSVGLineJoin& operator=(const SkSVGLineJoin&) = default; bool operator==(const SkSVGLineJoin& other) const { return fType == other.fType; } bool operator!=(const SkSVGLineJoin& other) const { return !(*this == other); } Type type() const { return fType; } private: Type fType; }; class SkSVGSpreadMethod { public: // These values must match Skia's SkShader::TileMode enum. enum class Type { kPad, // kClamp_TileMode kRepeat, // kRepeat_TileMode kReflect, // kMirror_TileMode }; constexpr SkSVGSpreadMethod() : fType(Type::kPad) {} constexpr explicit SkSVGSpreadMethod(Type t) : fType(t) {} SkSVGSpreadMethod(const SkSVGSpreadMethod&) = default; SkSVGSpreadMethod& operator=(const SkSVGSpreadMethod&) = default; bool operator==(const SkSVGSpreadMethod& other) const { return fType == other.fType; } bool operator!=(const SkSVGSpreadMethod& other) const { return !(*this == other); } Type type() const { return fType; } private: Type fType; }; class SkSVGFillRule { public: enum class Type { kNonZero, kEvenOdd, kInherit, }; constexpr SkSVGFillRule() : fType(Type::kInherit) {} constexpr explicit SkSVGFillRule(Type t) : fType(t) {} SkSVGFillRule(const SkSVGFillRule&) = default; SkSVGFillRule& operator=(const SkSVGFillRule&) = default; bool operator==(const SkSVGFillRule& other) const { return fType == other.fType; } bool operator!=(const SkSVGFillRule& other) const { return !(*this == other); } Type type() const { return fType; } SkPathFillType asFillType() const { SkASSERT(fType != Type::kInherit); // should never be called for unresolved values. return fType == Type::kEvenOdd ? SkPathFillType::kEvenOdd : SkPathFillType::kWinding; } private: Type fType; }; class SkSVGVisibility { public: enum class Type { kVisible, kHidden, kCollapse, kInherit, }; constexpr SkSVGVisibility() : fType(Type::kVisible) {} constexpr explicit SkSVGVisibility(Type t) : fType(t) {} SkSVGVisibility(const SkSVGVisibility&) = default; SkSVGVisibility& operator=(const SkSVGVisibility&) = default; bool operator==(const SkSVGVisibility& other) const { return fType == other.fType; } bool operator!=(const SkSVGVisibility& other) const { return !(*this == other); } Type type() const { return fType; } private: Type fType; }; class SkSVGDashArray { public: enum class Type { kNone, kDashArray, kInherit, }; SkSVGDashArray() : fType(Type::kNone) {} explicit SkSVGDashArray(Type t) : fType(t) {} explicit SkSVGDashArray(SkTDArray<SkSVGLength>&& dashArray) : fType(Type::kDashArray) , fDashArray(std::move(dashArray)) {} SkSVGDashArray(const SkSVGDashArray&) = default; SkSVGDashArray& operator=(const SkSVGDashArray&) = default; bool operator==(const SkSVGDashArray& other) const { return fType == other.fType && fDashArray == other.fDashArray; } bool operator!=(const SkSVGDashArray& other) const { return !(*this == other); } Type type() const { return fType; } const SkTDArray<SkSVGLength>& dashArray() const { return fDashArray; } private: Type fType; SkTDArray<SkSVGLength> fDashArray; }; class SkSVGStopColor { public: enum class Type { kColor, kCurrentColor, kICCColor, kInherit, }; SkSVGStopColor() : fType(Type::kColor), fColor(SK_ColorBLACK) {} explicit SkSVGStopColor(Type t) : fType(t), fColor(SK_ColorBLACK) {} explicit SkSVGStopColor(const SkSVGColorType& c) : fType(Type::kColor), fColor(c) {} SkSVGStopColor(const SkSVGStopColor&) = default; SkSVGStopColor& operator=(const SkSVGStopColor&) = default; bool operator==(const SkSVGStopColor& other) const { return fType == other.fType && fColor == other.fColor; } bool operator!=(const SkSVGStopColor& other) const { return !(*this == other); } Type type() const { return fType; } const SkSVGColorType& color() const { SkASSERT(fType == Type::kColor); return fColor; } private: Type fType; SkSVGColorType fColor; }; class SkSVGFontFamily { public: enum class Type { kFamily, kInherit, }; SkSVGFontFamily() : fType(Type::kInherit) {} explicit SkSVGFontFamily(const char family[]) : fType(Type::kFamily) , fFamily(family) {} bool operator==(const SkSVGFontFamily& other) const { return fType == other.fType && fFamily == other.fFamily; } bool operator!=(const SkSVGFontFamily& other) const { return !(*this == other); } Type type() const { return fType; } const SkString& family() const { return fFamily; } private: Type fType; SkString fFamily; }; class SkSVGFontStyle { public: enum class Type { kNormal, kItalic, kOblique, kInherit, }; SkSVGFontStyle() : fType(Type::kInherit) {} explicit SkSVGFontStyle(Type t) : fType(t) {} bool operator==(const SkSVGFontStyle& other) const { return fType == other.fType; } bool operator!=(const SkSVGFontStyle& other) const { return !(*this == other); } Type type() const { return fType; } private: Type fType; }; class SkSVGFontSize { public: enum class Type { kLength, kInherit, }; SkSVGFontSize() : fType(Type::kInherit), fSize(0) {} explicit SkSVGFontSize(const SkSVGLength& s) : fType(Type::kLength) , fSize(s) {} bool operator==(const SkSVGFontSize& other) const { return fType == other.fType && fSize == other.fSize; } bool operator!=(const SkSVGFontSize& other) const { return !(*this == other); } Type type() const { return fType; } const SkSVGLength& size() const { return fSize; } private: Type fType; SkSVGLength fSize; }; class SkSVGFontWeight { public: enum class Type { k100, k200, k300, k400, k500, k600, k700, k800, k900, kNormal, kBold, kBolder, kLighter, kInherit, }; SkSVGFontWeight() : fType(Type::kInherit) {} explicit SkSVGFontWeight(Type t) : fType(t) {} bool operator==(const SkSVGFontWeight& other) const { return fType == other.fType; } bool operator!=(const SkSVGFontWeight& other) const { return !(*this == other); } Type type() const { return fType; } private: Type fType; }; #endif // SkSVGTypes_DEFINED
[ "skia-commit-bot@chromium.org" ]
skia-commit-bot@chromium.org
ee2b151749ec59f48d4d98ff7259de564e3a1367
0f896bb9f7dbccfe7e42463350aec4e438303661
/vendors/XMSAALib.cpp
eedc87535753466dc28b588f18c956ff8bc5b9eb
[]
no_license
inCenter/work-proof
6ae6933217f9921641011223bd9b1314396720e9
1d2ce356b87c829b6512aa671138b5e71536c508
refs/heads/master
2021-01-15T13:18:12.839624
2013-11-13T00:44:26
2013-11-13T00:44:26
14,349,100
2
0
null
null
null
null
UTF-8
C++
false
false
9,107
cpp
// XMSAALib.cpp Version 1.0 - see article at CodeProject.com // // Author: Hans Dietrich // hdietrich@gmail.com // // Description: // XMSAALib implements a class to retrieve MSAA information from a window. // // History // Version 1.0 - 2009 February 10 // - Initial public release // // License: // This software is released under the Code Project Open License (CPOL), // which may be found here: http://www.codeproject.com/info/eula.aspx // You are free to use this software in any way you like, except that you // may not sell this source code. // // This software is provided "as is" with no expressed or implied warranty. // I accept no liability for any damage or loss of business that this // software may cause. // /////////////////////////////////////////////////////////////////////////////// #define _WIN32_WINNT 0x0502 #define WINVER 0x0502 #include <windows.h> #include <winuser.h> #include <tchar.h> #include "XMSAALib.h" #define SAFE_RELEASE(p_) { if (p_ != NULL) p_->Release(); p_ = NULL; } //============================================================================= CXMSAALib::CXMSAALib() : //============================================================================= m_eHook(0) { } //============================================================================= CXMSAALib::~CXMSAALib() //============================================================================= { } //============================================================================= BOOL CXMSAALib::GetObjectName(IAccessible *pAcc, VARIANT *pvarChild, BSTR &bstrNameOut, UINT cchName) //============================================================================= { BOOL bRet = FALSE; if (pAcc && pvarChild && bstrNameOut) { bstrNameOut = NULL; BSTR bstrName = NULL; HRESULT hr = pAcc->get_accName(*pvarChild, &bstrName); if (SUCCEEDED(hr) && bstrName) { bstrNameOut = bstrName; bRet = TRUE; } } return bRet; } //============================================================================= BOOL CXMSAALib::GetObjectValue(IAccessible *pAcc, VARIANT *pvarChild, BSTR &bstrValueOut, UINT cchValue) //============================================================================= { BOOL bRet = FALSE; if (pAcc && pvarChild && bstrValueOut) { bstrValueOut = NULL; BSTR bstrValue = NULL; HRESULT hr = pAcc->get_accValue(*pvarChild, &bstrValue); if (SUCCEEDED(hr) && bstrValue) { bstrValueOut = bstrValue; bRet = TRUE; } } return bRet; } //============================================================================= BOOL CXMSAALib::GetObjectDescription(IAccessible *pAcc, VARIANT *pvarChild, BSTR& bstrDescriptionOut, UINT cchDescription) //============================================================================= { BOOL bRet = FALSE; if (pAcc && pvarChild && bstrDescriptionOut) { bstrDescriptionOut = NULL; BSTR bstrDescription = NULL; HRESULT hr = pAcc->get_accDescription(*pvarChild, &bstrDescription); if (SUCCEEDED(hr) && bstrDescription) { bstrDescriptionOut = bstrDescription; bRet = TRUE; } } return bRet; } //============================================================================= BOOL CXMSAALib::GetObjectChildCount(IAccessible *pAcc, long& nCount) //============================================================================= { BOOL bRet = FALSE; if (pAcc) { HRESULT hr = pAcc->get_accChildCount(&nCount); if (SUCCEEDED(hr)) { bRet = TRUE; } } return bRet; } //============================================================================= BOOL CXMSAALib::GetObjectLocation(IAccessible *pAcc, VARIANT *pvarChild, RECT& rect) //============================================================================= { BOOL bRet = FALSE; if (pAcc && pvarChild) { HRESULT hr = pAcc->accLocation(&rect.left, &rect.top, &rect.right, &rect.bottom, *pvarChild); if (SUCCEEDED(hr)) { // accLocation returns width and height rect.right += rect.left; rect.bottom += rect.top; bRet = TRUE; } } return bRet; } //============================================================================= BOOL CXMSAALib::GetObjectRole(IAccessible *pAcc, VARIANT *pvarChild, UINT& nRole) //============================================================================= { BOOL bRet = FALSE; nRole = 0; if (pAcc && pvarChild) { VARIANT varRole; VariantInit(&varRole); HRESULT hr = pAcc->get_accRole(*pvarChild, &varRole); if (SUCCEEDED(hr) && (varRole.vt == VT_I4)) { nRole = varRole.lVal; bRet = TRUE; } VariantClear(&varRole); } return bRet; } //============================================================================= BOOL CXMSAALib::GetObjectState(IAccessible* pAcc, VARIANT* pvarChild, UINT& nState) //============================================================================= { BOOL bRet = FALSE; nState = 0; if (pAcc && pvarChild) { VARIANT varState; VariantInit(&varState); HRESULT hr = pAcc->get_accState(*pvarChild, &varState); if (SUCCEEDED(hr) && (varState.vt == VT_I4)) { nState = varState.lVal; bRet = TRUE; } VariantClear(&varState); } return bRet; } //============================================================================= BOOL CXMSAALib::EnumAccessible(HWND hwnd, XENUMACCESSIBLEPROC lpEnumAccessibleProc, LPARAM lParam) //============================================================================= { BOOL bRet = FALSE; if (::IsWindow(hwnd) && lpEnumAccessibleProc) { IAccessible *pIAcc = NULL; HRESULT hr = AccessibleObjectFromWindow(hwnd, OBJID_WINDOW, IID_IAccessible, (void**)&pIAcc); if (SUCCEEDED(hr) && pIAcc) { VARIANT varChild; VariantInit(&varChild); IAccessible *pIAccChild = NULL; FindChild(pIAcc, &pIAccChild, &varChild, lpEnumAccessibleProc, lParam, TRUE); SAFE_RELEASE(pIAcc); VariantClear(&varChild); bRet = TRUE; } } return bRet; } //============================================================================= BOOL CXMSAALib::FindChild(IAccessible *pIAccParent, IAccessible **pIAccChild, VARIANT *pvarChild, XENUMACCESSIBLEPROC lpEnumAccessibleProc, LPARAM lParam, BOOL bFirstTime) //============================================================================= { IEnumVARIANT *pEnum = NULL; VARIANT varChild; VariantInit(&varChild); IAccessible *pCAcc = NULL; BOOL bContinue = TRUE; static int nLevel = 0; if (bFirstTime) { nLevel = 0; varChild.vt = VT_I4; varChild.lVal = CHILDID_SELF; bContinue = lpEnumAccessibleProc(pIAccParent, &varChild, NULL, nLevel, lParam); } nLevel++; HRESULT hr = pIAccParent->QueryInterface(IID_IEnumVARIANT, (PVOID*) &pEnum); if (pEnum) pEnum->Reset(); // get child count long nChildren = 0; unsigned long nFetched = 0; pIAccParent->get_accChildCount(&nChildren); for (long index = 1; (index <= nChildren) && bContinue; index++) { VariantClear(&varChild); SAFE_RELEASE(pCAcc); if (pEnum) { hr = pEnum->Next(1, &varChild, &nFetched); if (!SUCCEEDED(hr)) { bContinue = FALSE; break; } } else { varChild.vt = VT_I4; varChild.lVal = index; } // get IDispatch interface for the child IDispatch *pDisp = NULL; if (varChild.vt == VT_I4) { hr = pIAccParent->get_accChild(varChild, &pDisp); } else if (varChild.vt == VT_DISPATCH) { pDisp = varChild.pdispVal; } // get IAccessible interface for the child if (pDisp) { hr = pDisp->QueryInterface(IID_IAccessible, (void**)&pCAcc); SAFE_RELEASE(pDisp); } // get information about the child if (pCAcc) { VariantInit(&varChild); varChild.vt = VT_I4; varChild.lVal = CHILDID_SELF; *pIAccChild = pCAcc; } else { *pIAccChild = pIAccParent; } HWND hwndChild = 0; WindowFromAccessibleObject(*pIAccChild, &hwndChild); // call enum callback bContinue = lpEnumAccessibleProc(*pIAccChild, &varChild, hwndChild, nLevel, lParam); if (bContinue && pCAcc) { bContinue = FindChild(pCAcc, pIAccChild, pvarChild, lpEnumAccessibleProc, lParam, FALSE); if (*pIAccChild != pCAcc) SAFE_RELEASE(pCAcc); } } SAFE_RELEASE(pCAcc); SAFE_RELEASE(pEnum); VariantClear(&varChild); nLevel--; return bContinue; }
[ "alexander-vgx@yandex.ru" ]
alexander-vgx@yandex.ru
b9eff68686da618d46616233ba1c062a79094367
22732cb593533e9134a7589e8f93597ce3790a4e
/Dwarves-vs-Zombies/render.h
ac6103754fa168c37c1c313b6ba468206392050d
[]
no_license
Fishandchips321/Dwarves-vs-Zombies
6f7116b10cd70b0d65224d9dde111c7d4eb15f8c
a4aff08c832ee09828c9b450bba7e5acfa48241c
refs/heads/master
2021-01-12T07:36:22.863110
2017-05-18T17:21:47
2017-05-18T17:21:47
76,985,989
0
0
null
null
null
null
UTF-8
C++
false
false
1,007
h
#pragma once #include <SDL.h> #include <SDL_image.h> #include <iostream> #include <vector> class render { public: render(); static bool init(); static bool update(); static bool drawScreen(); static bool drawTexture(SDL_Texture* texture, SDL_Rect* rect, SDL_Rect* viewport = NULL); static bool drawSurface(SDL_Surface* surface, SDL_Rect* rect, SDL_Rect* viewport); static bool drawLight(int x, int y, int radius); static bool setLight(int lightLevel); static bool drawSquare(SDL_Rect rect, Uint8 r, Uint8 g, Uint8 b, Uint8 a); static int screenWidth; //640 static int screenHeight; //480 static int xOffset, yOffset; static std::string windowTitle; static SDL_Window* window; static SDL_Surface* screenSurface; static SDL_Renderer* renderer; private: struct light { int x, y, radius; }; static SDL_Texture* lightSurface; //holds the shadow (a black rectangle). change the alpha to make it darker or lighter static int lightAlpha; static std::vector<light> lights; ~render(); };
[ "f10fox@yahoo.co.uk" ]
f10fox@yahoo.co.uk
5663965fed3faecdeabda3b63f43cb63fb23b73c
eefce09344d0e4f85056fd2f18aa28fee7da73be
/sqlite3command.h
af9042fc1c772fe5f5f5bf159ab4bf2802ec728a
[ "MIT" ]
permissive
itsPG/sqlite_fts_substring
9d1b02ca6e64ce93a3ca5602b18f50438051fb33
d66b82f3708bfd6837f04bece32a6cb80ca62e82
refs/heads/master
2021-01-01T16:25:07.854716
2014-05-24T16:35:06
2014-05-24T16:35:06
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,356
h
#include "sqlite3.h" #ifdef __cplusplus extern "C" { #endif #include "character_tokenizer.h" #ifdef __cplusplus } #endif #define DEBUGMSGRED(msg) cout << "\033[0;31m" << msg << "\033[0m" << endl; #define DEBUGMSGGREEN(msg) cout << "\033[0;32m" << msg << "\033[0m" << endl; #define DEBUGMSGBROWN(msg) cout << "\033[0;33m" << msg << "\033[0m" << endl; #define DEBUGMSGCYAN(msg) cout << "\033[0;36m" << msg << "\033[0m" << endl; #define DEBUGMSG(msg) cout << msg << endl; #define DEBUGMSGN(msg) cout << msg; #include <iostream> #include <cstdlib> #include <string> #include <vector> using namespace std; class SQLite3Command { public: SQLite3Command(); ~SQLite3Command(); struct EXEC_RESULT { vector<string> colsName; vector< vector<string> > records; }; int open(const string &path); int open(const string &path, int flag, const char *szVfs); int exec(const string &cmd); int exec(const string &cmd, vector< vector<string> > &data); int exec_and_show(const string &cmd); int exec(const string &cmd, int (*callback)(void*,int,char**,char**), void* pData); int execf(vector< vector<string> > *pData, const string cmd, ...); int execf_cmd_only(const string cmd, ...); int get_table(const string &query, int &rows, int &cols, vector< vector<string> > &result); int get_table(const string &query, vector< vector<string> > &result); int get_table_and_show(const string &query); int get_table(const string &query, int &rows, int &cols, char **&result); sqlite3 *getDB(); inline static void show_table(const vector< vector<string> > &data) { for (int i = 0; i < data.size(); i++) { for (int j = 0; j < data[i].size(); j++) { DEBUGMSGN(data[i][j] << "\t\033[0;33m|\033[0m") } DEBUGMSG(""); } } static int _execDefaultCallback(void *pData, int argc, char **cols, char **colsName) { EXEC_RESULT *result = (EXEC_RESULT*) pData; result->records.push_back(vector<string>()); for (int i = 0; i < argc; i++) { int pos = result->records.size() - 1; if (pos == 0) { result->colsName.push_back(colsName[i]); } result->records[pos].push_back(cols[i]); } return 0; } private: sqlite3 *db; int registerTokenizer( sqlite3 *db, const char *zName, const sqlite3_tokenizer_module *p ); int registerCharacterTokenizer(); inline void cmdFailed(const string &tag, const string &cmd, char *szErrMsg); };
[ "smartPG@gmail.com" ]
smartPG@gmail.com
4d8635d1fb8e249f9b837c7ae375ff641cf188ef
5c34abe10630b23da8ba7d1cbce38bda53a4b6fa
/G4HadronSim/G4HadronSim/G4PiKBuilder.hh
766a22fc17e2c518c8a0abeaf6ec586e5f895678
[]
no_license
fermi-lat/GlastRelease-scons-old
cde76202f706b1c8edbf47b52ff46fe6204ee608
95f1daa22299272314025a350f0c6ef66eceda08
refs/heads/master
2021-07-23T02:41:48.198247
2017-05-09T17:27:58
2017-05-09T17:27:58
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,988
hh
// // ******************************************************************** // * DISCLAIMER * // * * // * The following disclaimer summarizes all the specific disclaimers * // * of contributors to this software. The specific disclaimers,which * // * govern, are listed with their locations in: * // * http://cern.ch/geant4/license * // * * // * Neither the authors of this software system, nor their employing * // * institutes,nor the agencies providing financial support for this * // * work make any representation or warranty, express or implied, * // * regarding this software system or assume any liability for its * // * use. * // * * // * This code implementation is the intellectual property of the * // * GEANT4 collaboration. * // * By copying, distributing or modifying the Program (or any work * // * based on the Program) you indicate your acceptance of this * // * statement, and all its terms. * // ******************************************************************** // // $Id$ // GEANT4 tag $Name$ // //--------------------------------------------------------------------------- // // ClassName: G4PiKBuilder // // Author: 2002 J.P. Wellisch // // Modified: // 16.11.2005 G.Folger: don't keep processes as data members, but new these // //---------------------------------------------------------------------------- // #ifndef G4PiKBuilder_h #define G4PiKBuilder_h 1 #include "globals.hh" #include "G4HadronElasticProcess.hh" #include "G4ProtonInelasticProcess.hh" #include "G4VPiKBuilder.hh" #include <vector> class G4PiKBuilder { public: G4PiKBuilder(); virtual ~G4PiKBuilder(); public: void Build(); void RegisterMe(G4VPiKBuilder * aB) {theModelCollections.push_back(aB);} private: G4HadronElasticProcess* thePionPlusElasticProcess; G4HadronElasticProcess* thePionMinusElasticProcess; G4HadronElasticProcess* theKaonPlusElasticProcess; G4HadronElasticProcess* theKaonMinusElasticProcess; G4HadronElasticProcess* theKaonZeroLElasticProcess; G4HadronElasticProcess* theKaonZeroSElasticProcess; G4PionPlusInelasticProcess* thePionPlusInelastic; G4PionMinusInelasticProcess* thePionMinusInelastic; G4KaonPlusInelasticProcess* theKaonPlusInelastic; G4KaonMinusInelasticProcess* theKaonMinusInelastic; G4KaonZeroLInelasticProcess* theKaonZeroLInelastic; G4KaonZeroSInelasticProcess* theKaonZeroSInelastic; std::vector<G4VPiKBuilder *> theModelCollections; G4bool wasActivated; }; // 2002 by J.P. Wellisch #endif
[ "" ]
11843f6712cbe1ddb29494edb8f241f71c821e20
39cdab177f5e33db7e3113426f1817c012b9de9c
/src/main.cpp
189fa8b2fb15f2ec1345b735b52a6ed2c58af8d8
[]
no_license
VincentWells/CAST-Project
22f289e18ace70824efd857aba3c08d10af8af2b
bbfdfd3cef171f54c52fc0b7ecab6c27553301bc
refs/heads/master
2021-06-01T12:23:22.593872
2020-01-23T16:56:07
2020-01-23T16:56:07
79,065,798
0
0
null
null
null
null
UTF-8
C++
false
false
2,159
cpp
#include "graph.h" #include <iostream> #include <vector> #include <string> #include <fstream> #include <istream> using namespace std; //find the proportion of item in a vector inside a given range relative to that range double overlap(vector<int>& v, int s, int e){ int count = 0; for(int i = 0; i < v.size(); i++){ if(v[i] >= s && v[i] < e){ count ++; } } //cout << "count " << count << endl; return (double)(count) / (e - s); } //unused method double loose(vector<double>& v){ double d = 0; for(int i = 0; i < v.size(); i++){ d += v[i]; } return 1 - d; } //print comparison of results void print(graph& g, vector<int>& v){ cout << v.size() << endl; cout << "theta: " << g.theta << "\t\t\t"; for(int i = 0; i < g.cliques.size(); i++){ cout << "CAST cluster " << i + 1 << "\t"; } cout << endl; for(int j = 1; j < v.size(); j++){ cout << "real cluster " << j << "\t\t"; for(int k = 0; k < g.cliques.size(); k++){ //cout << "real " << v[j-1] << " thru " << v[j] << endl; cout << overlap(g.cliques[k], v[j-1], v[j]) * 100.0 << "\t\t"; } cout << endl; } } int main(){ string addr; cout << "provide file address: " << endl; cin >> addr; // "/home/me/C++ Projects/hw3/vincentWells/src/clusters.txt" ifstream file(addr.c_str()); if(!file.is_open()){ cout << "Error: invalid file address." << endl; return 0; } vector<vector<string> > v (1); vector<int> indices(0); int i = -1; int j = 0; for(string temp; getline(file, temp);){ //cout << "got line" << endl << flush; //cout << temp << endl << flush; if(temp.substr(0, 8) == "template"){ indices.push_back(j); i++; vector<string> u(0); v.push_back(u); } else if (temp.substr(0, 8) == "sequence"){ } else if(temp.size() > 2){ v[i].push_back(temp); j++; } } indices.push_back(j); file.close(); //cout << "pre graph" << endl << flush; graph g(v[0]); for(int i = 1; i < v.size(); i++){ g.add(v[i]); } g.enscore(); g.connect(); //cout << "graph built" << endl << flush; g.CAST(); //cout << "graph cliqued" << endl << flush; g.print(); //cout << "graph finished" << endl << flush; print(g, indices); return 0; }
[ "me@localhost.localdomain" ]
me@localhost.localdomain
6dc9e9ec38ca913de195b93cc20e3bf15878e366
a0c6c9428387083ca7d95ac66709d74d700be00d
/Pong/src/Texture2D.cpp
70c4dbeff5a46abd81fdfc50ead3890f2b83d8e0
[]
no_license
robot9706/Pong3D
60d0b7e729ffde21dcdf1d7a000b1f2776549114
8821eab3f0a7ca5dba7bb37948b51230f21bb888
refs/heads/master
2021-01-10T04:24:07.936894
2015-05-29T13:05:52
2015-05-29T13:05:52
35,967,662
0
0
null
null
null
null
ISO-8859-2
C++
false
false
2,378
cpp
//============================ //Nagygyörgy Bence 11.b - 2015 //============================ #include "Texture2D.h" #include <glew.h> #include <SDL.h> #include <SDL_image.h> #include <DataBlock.h> #include <iostream> #include <string> using namespace std; Texture2D::Texture2D() { glGenTextures(1, &_texture); } Texture2D::~Texture2D() { glDeleteTextures(1, &_texture); } bool Texture2D::Load(string file) { SDL_Surface* loadedImage = NULL; loadedImage = IMG_Load(file.c_str()); if(loadedImage == NULL) { cout << "A fájl nem létezik: \"" << file << "\"" << endl; return false; } else { Width = loadedImage->w; Height = loadedImage->h; glBindTexture(GL_TEXTURE_2D , _texture); glTexImage2D(GL_TEXTURE_2D , 0 , GL_RGBA , loadedImage->w , loadedImage->h , 0 , GL_RGBA , GL_UNSIGNED_BYTE , loadedImage->pixels); glTexParameteri(GL_TEXTURE_2D , GL_TEXTURE_MIN_FILTER , GL_NEAREST); glTexParameteri(GL_TEXTURE_2D , GL_TEXTURE_MAG_FILTER , GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); SDL_FreeSurface(loadedImage); loadedImage = NULL; } return true; } bool Texture2D::LoadMem(DataBlock data) { SDL_RWops *rw = SDL_RWFromMem(data.Data, data.Size); SDL_Surface *loadedImage = IMG_LoadPNG_RW(rw); if(loadedImage == NULL) { cout << "Hiba a kép betöltése közben!" << endl; return false; } else { Width = loadedImage->w; Height = loadedImage->h; glBindTexture(GL_TEXTURE_2D , _texture); glTexImage2D(GL_TEXTURE_2D , 0 , GL_RGBA , loadedImage->w , loadedImage->h , 0 , GL_RGBA , GL_UNSIGNED_BYTE , loadedImage->pixels); glTexParameteri(GL_TEXTURE_2D , GL_TEXTURE_MIN_FILTER , GL_NEAREST); glTexParameteri(GL_TEXTURE_2D , GL_TEXTURE_MAG_FILTER , GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); SDL_FreeSurface(loadedImage); loadedImage = NULL; } SDL_RWclose(rw); return true; } unsigned int Texture2D::GetID() { return _texture; }
[ "robot9706@gmail.com" ]
robot9706@gmail.com
52d1ac49929fbe3b4c99df33d542e12608945f26
006f035d65012b7c5af15d54716407a276a096a8
/dependencies/include/cgal/CGAL/Handle_with_policy.h
04f38c639cbc62f0a5252cac4caec9465514b945
[]
no_license
rosecodym/space-boundary-tool
4ce5b67fd96ec9b66f45aca60e0e69f4f8936e93
300db4084cd19b092bdf2e8432da065daeaa7c55
refs/heads/master
2020-12-24T06:51:32.828579
2016-08-12T16:13:51
2016-08-12T16:13:51
65,566,229
7
0
null
null
null
null
UTF-8
C++
false
false
57,070
h
// Copyright (c) 2001-2007 Max-Planck-Institute Saarbruecken (Germany). // All rights reserved. // // This file is part of CGAL (www.cgal.org); you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public License as // published by the Free Software Foundation; either version 3 of the License, // or (at your option) any later version. // // Licensees holding a valid commercial license may use this file in // accordance with the commercial license agreement provided with the software. // // This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE // WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. // // $URL: svn+ssh://scm.gforge.inria.fr/svn/cgal/branches/releases/CGAL-4.1-branch/STL_Extension/include/CGAL/Handle_with_policy.h $ // $Id: Handle_with_policy.h 67093 2012-01-13 11:22:39Z lrineau $ // // Author(s) : Michael Seel <seel@mpi-inf.mpg.de> // Arno Eigenwillig <arno@mpi-inf.mpg.de> // Lutz Kettner <kettner@mpi-inf.mpg.de> #ifndef CGAL_HANDLE_WITH_POLICY_H #define CGAL_HANDLE_WITH_POLICY_H #include <CGAL/basic.h> #include <CGAL/memory.h> #include <CGAL/type_traits.h> #include <CGAL/assertions.h> #include <boost/mpl/if.hpp> #include <cstddef> #ifdef CGAL_USE_LEDA # if CGAL_LEDA_VERSION < 500 # include <LEDA/memory.h> # else # include <LEDA/system/memory.h> # endif #endif namespace CGAL { /*! \brief <tt>\#include <CGAL/Handle_with_policy.h></tt> for handles with policy parameter for reference counting and union-find strategy. Uses \c LEDA_MEMORY if available. There are two fundamentally different usages of this base class: - with a single representation class. In this case the handle manages allocation and deallocation and the type \c T can be an arbitrary type---the handle adds the necessary reference counter internally. - with a hierarchy of representation classes. Type \c T will be the common base class of this hierarchy and it has to be derived itself from a specific base class, which can be accessed directly or generically from the policy class. The allocator in the handle will not be used in this scenario, since the handle class does not allocate any representations. Instead, the handle class derived from this handle base class is allocating the different representations with the \c new operator. In this case, the allocator in the base class of \c T is used. We give an example for each usage. See also the documentation of \c Handle_with_policy. \b Example We use a single representation class to store an integer. The second constructor makes use of one of the forwarding template constructors that simply forward their parameter list to the representation constructors. They exist for up to ten parameters. The third constructor illustrates how the \c USE_WITH_INITIALIZE_WITH can be used. It is useful if extensive computations are necessary before the representation can be created. \code struct Int_rep { int val; Int_rep( int i = 0) : val(i) {} Int_rep( int i, int j) : val(i+j) {} Int_rep( int i, int j, int k) : val(i+j+k) {} }; template < class Unify> struct Int_t : public Handle_with_policy< Int_rep, Unify > { typedef Handle_with_policy< Int_rep, Unify > Base; Int_t( int i = 0) : Base( i) {} Int_t( int i, int j) : Base( i, j) {} // template constructors Int_t( int i, int j, int k) : Base( Base::USE_WITH_INITIALIZE_WITH) { initialize_with( i, j + k); } int value() const { return ptr()->val; } void set_value( int i) { copy_on_write(); ptr()->val = i; } bool operator==( const Int_t<Unify>& i) const { bool equal = (value() == i.value()); if ( equal) Base::unify(i); return equal; } }; \endcode \b Example We use a class hierarchy of two representation classes: one base class for representing one integer, and a derived class to represent an additional integer. To also added virtual get and set functions to make this example similar to the one above. We use the generic solution to pick the base class for \c Int_vrep from the policy class. So all representations are class templates with a policy and an allocator as parameter and the handle class instantiates them. If this flexibility is not needed, one could derive directly from the appropriate base class, i.e., \c ::CGAL::Reference_counted_hierarchy<Alloc> or \c ::CGAL::Reference_counted_hierarchy_with_union<Alloc>. \c Alloc is an allocator of \c char's here. \code template <class Policy, class Alloc> struct Int_vrep : public Policy::Hierarchy_base< Alloc>::Type { int val; virtual ::CGAL::Reference_counted_hierarchy<Alloc>* clone() { return new Int_vrep( *this); } virtual int get_val() const { return val; } virtual void set_val( int i) { val = i; } Int_vrep( int i = 0) : val(i) {} }; template <class Policy, class Alloc> struct Int_vrep2 : public Int_vrep<Policy,Alloc> { int val2; virtual ::CGAL::Reference_counted_hierarchy<Alloc>* clone() { return new Int_vrep2( *this); } virtual int get_val() const { return val + val2; } virtual void set_val( int i) { val = i - val2; } Int_vrep2( int i, int j) : Int_vrep<Policy,Alloc>(i), val2(j) {} }; template < class Unify, class Alloc = CGAL_ALLOCATOR(char) > struct Int_vt : public Handle_with_policy< Int_vrep<Unify,Alloc>, Unify > { typedef Handle_with_policy< Int_vrep<Unify,Alloc>, Unify > Base; Int_vt( int i = 0) : Base( new Int_vrep<Unify,Alloc>(i)) {} Int_vt( int i, int j) : Base( new Int_vrep2<Unify,Alloc>(i,j)) {} int value() const { return ptr()->get_val(); } void set_value( int i) { copy_on_write(); ptr()->set_val(i); } bool operator==( const Int_vt<Unify>& i) const { bool equal = (value() == i.value()); if ( equal) Base::unify(i); return equal; } }; \endcode */ //@{ // Forward declarations of HandlePolicy classes class Handle_policy_in_place; class Handle_policy_no_union; class Handle_policy_union; class Handle_policy_union_and_reset; // Reference counted representation // ================================ //! the base class for bodies of reference counted representations \c T. template <class T_> class Reference_counted { public: typedef T_ rep_type; typedef Reference_counted<rep_type> Self; typedef rep_type* Rep_pointer; private: mutable unsigned int count; // reference counter rep_type rep; public: Reference_counted() : count(1) {} Reference_counted( const rep_type& t) : count(1), rep(t) {} Reference_counted( const Self& r) : count(1), rep(r.rep) {} void clear() { rep = rep_type(); } Rep_pointer base_ptr() { return &rep; } void add_reference() { ++count; } void remove_reference() { --count; } bool is_shared() const { return count > 1; } int union_size() const { return 1+count; } void add_union_size(int) {} }; /*!\brief * Base class for bodies of reference counted representations \c T * with a forwarding pointer for identical representations. */ template <class T_> class Reference_counted_with_forwarding { public: typedef T_ rep_type; typedef Reference_counted_with_forwarding<rep_type> Self; typedef rep_type* Rep_pointer; friend class Handle_policy_union; friend class Handle_policy_union_and_reset; private: mutable unsigned int count; // reference counter mutable Self* next; // forwarding pointer to valid rep or 0 mutable int u_size; // union set size incl this rep and its handle mutable rep_type rep; public: Reference_counted_with_forwarding() : count(1), next(0), u_size(2) {} Reference_counted_with_forwarding( const rep_type& t) : count(1), next(0), u_size(2), rep(t) {} Reference_counted_with_forwarding( const Self& r) : count(1), next(0), u_size(2), rep(r.rep) {} void clear() { rep = rep_type(); } Rep_pointer base_ptr() { return &rep; } void add_reference() { ++count; } void remove_reference() { --count; } bool is_shared() const { return count > 1; } bool is_forwarding() const { return next != 0; } int union_size() const { return u_size; } void add_union_size(int a) { CGAL_precondition( u_size + a > 0); u_size += a; } }; struct Reference_counted_hierarchy_base {}; /*!\brief Base class for reference counted representations with a class * hierarchy of different representations. Needs an allocator for \c char's * as parameter. */ template <class Allocator_ = CGAL_ALLOCATOR(char)> class Reference_counted_hierarchy : public Reference_counted_hierarchy_base { // make sure it's always a char allocator typedef typename Allocator_::template rebind< char> Char_alloc_rebind; typedef typename Char_alloc_rebind::other Char_allocator; static Char_allocator alloc; public: void* operator new(size_t bytes) { return alloc.allocate( bytes); } void operator delete(void* p, size_t bytes) { alloc.deallocate((char*)p, bytes); } public: typedef Allocator_ Allocator; typedef Reference_counted_hierarchy<Allocator> Self; typedef Self* Rep_pointer; private: mutable unsigned int count; // reference counter public: Reference_counted_hierarchy() : count(1) {} Reference_counted_hierarchy( const Self&) : count(1) {} Rep_pointer base_ptr() { return this; } void add_reference() { ++count; } void remove_reference() { --count; } bool is_shared() const { return count > 1; } int union_size() const { return 1+count; } void add_union_size(int) {} //! returns a copy of \c this. Can be implemented like //! <tt>return new Derived_type( *this);</tt> virtual Self* clone() = 0; //! the virtual destructor is essential for proper memory management here. virtual ~Reference_counted_hierarchy() {} //! can be used to minimize memory consumption once it is known that this //! representation is not used anymore and only needed to keep a fowarding //! pointer. One example would be cleaning up dynamically allocated //! data, or another example would be overwriting a \c leda::real with //! a default constructed value to free its old expression tree. However, //! this function can also be savely ignored and kept empty. virtual void clear() {} }; template <class Alloc> typename Reference_counted_hierarchy<Alloc>::Char_allocator Reference_counted_hierarchy<Alloc>::alloc; /*!\brief Base class for reference counted representations with a class * hierarchy of different representations. Needs an allocator for \c char's * as parameter. */ template <class Allocator_ = CGAL_ALLOCATOR(char)> class Reference_counted_hierarchy_with_union : public Reference_counted_hierarchy<Allocator_> { friend class Handle_policy_union; friend class Handle_policy_union_and_reset; public: typedef Allocator_ Allocator; typedef Reference_counted_hierarchy_with_union<Allocator> Self; private: mutable Self* next; // forwarding pointer to valid rep or 0 mutable int u_size; // union set size incl this rep and its handle public: Reference_counted_hierarchy_with_union() : Reference_counted_hierarchy<Allocator_>(), next(0), u_size(2) {} bool is_forwarding() const { return next != 0; } int union_size() const { return u_size; } void add_union_size(int a) { CGAL_precondition( u_size + a > 0); u_size += a; } }; // Handle for reference counted representation // =========================================== namespace Intern { // Some helper classes to select representation between single class // representations and class hierarchy representations. // the representation type including a reference counter. // The handle allocates objects of this type. This is the version // for the single representation type. template <class T, int HandleHierarchyPolicy> struct Rep_bind_reference_counted { typedef Reference_counted<T> Rep; }; // the representation type including a reference counter. // The handle allocates objects of this type. This is the version // for the class hierarchy of representation types. template <class T> struct Rep_bind_reference_counted<T, true> { typedef T Rep; }; // the two versions for Reference_counted_with_forwarding template <class T, int HandleHierarchyPolicy> struct Rep_bind_reference_counted_with_forwarding { typedef Reference_counted_with_forwarding<T> Rep; }; // the representation type including a reference counter. // The handle allocates objects of this type. This is the version // for the class hierarchy of representation types. template <class T> struct Rep_bind_reference_counted_with_forwarding<T, true> { Rep_bind_reference_counted_with_forwarding() { // make sure we derived from the right type typedef typename T::Allocator Alloc; typedef ::CGAL::Reference_counted_hierarchy_with_union<Alloc> Reference_counted_hierarchy_with_union; CGAL_static_assertion(( ::CGAL::is_same_or_derived< Reference_counted_hierarchy_with_union, T >::value )); } typedef T Rep; }; } /*! \brief Policy class for \c Handle_with_policy that stores the representation directly without reference counting and without dynamic memory allocation, is actually \e not a model of the \c HandlePolicy concept, but can be used instead of one. It selects a different specialized implementation of \c Handle_with_policy. It works only with the single representation type, not with a class hierarchy of representation types since they need the pointer in the handle for the polymorphy. */ class Handle_policy_in_place {}; /*!\brief * Policy class for \c Handle_with_policy<T> that ignores unifying of * identical representations \c T, is a model of the \c HandlePolicy concept. */ class Handle_policy_no_union { public: /*!\brief * A rebind mechanism to create the representation type. */ template <class T, int hierarchy> struct Rep_bind { //! the representation type including a reference counter. //! The handle allocates objects of this type. typedef typename Intern::Rep_bind_reference_counted<T,hierarchy>::Rep Rep; }; /*!\brief * A rebind mechanism to access the base class for class hierarchies * of representations. * * The base classes can be used directly, but this * rebind mechamism allows the implementation of handle-rep classes * that are parameterized with the policy class only and adapt to * the necessary base class. */ template <class Alloc> struct Hierarchy_base { //! type that can be used as base class for the representation type. typedef Reference_counted_hierarchy<Alloc> Type; }; /*! \brief unifies the representations of the two handles \a h and \a g. * The effect is void here. * * \pre The representations represent the same value and one could be * replaced by the other. */ template <class H> static void unify( const H& h, const H& g) { (void)h; // avoid warnings for unused parameters (void)g; // but keep the names in the definition for the doc. } //! finds the currently valid representation for the handle \a h //! and returns a pointer to its stored value of type \a T. template <class H> static typename H::Rep_pointer find( const H& h) { return h.ptr_->base_ptr(); } }; /*!\brief * Policy class for \c Handle_with_policy that implements unifying of * identical representations \c T with trees and path compression, is a * model of the \c HandlePolicy concept. */ class Handle_policy_union { public: /*!\brief * A rebind mechanism to create the representation type. */ template <class T, int hierarchy> struct Rep_bind { //! this default constructor contains some compile-time checks. Rep_bind() { //Intern::Rep_bind_reference_counted_with_forwarding<T, hierarchy> // check; // (void)check; (void)Intern::Rep_bind_reference_counted_with_forwarding<T, hierarchy>(); } //! the representation type including a reference counter. //! The handle allocates objects of this type. typedef typename Intern::Rep_bind_reference_counted_with_forwarding<T, hierarchy>::Rep Rep; }; /*!\brief * A rebind mechanism to access the base class for class hierarchies * of representations. * * The base classes can be used directly, but this * rebind mechamism allows the implementation of handle-rep classes * that are parameterized with the policy class only and adapt to * the necessary base class. */ template <class Alloc> struct Hierarchy_base { //! type that can be used as base class for the representation type. typedef Reference_counted_hierarchy_with_union<Alloc> Type; }; /*! \brief unifies the representations of the two handles \a h and \a g. Performs union. \pre The representations represent the same value and one can be replaced by the other. The handles \a h and \a g are already the representatives found by the find operation and \a h is not equal to \a g. The tree representing the union of \a h has size not smaller than the corresponding tree size of \a g. */ template <class H> static void unify_large_small( const H& h, const H& g) { typename H::Rep* hrep = h.ptr_; typename H::Rep* grep = g.ptr_; CGAL_precondition( ! grep->is_forwarding()); CGAL_precondition( hrep->union_size() >= grep->union_size()); grep->add_union_size(-1); // make g point to h's rep. if ( grep->is_shared()) { // grep survises the loss of one reference // and hrep gets one more reference grep->remove_reference(); hrep->add_reference(); hrep->add_union_size( grep->union_size()); grep->next = hrep; } else { g.delete_rep( grep); // did not survive loss of handle g } // redirect handle g and incr. hrep's counter g.ptr_ = hrep; hrep->add_reference(); hrep->add_union_size(1); } /*! \brief unifies the representations of the two handles \a h and \a g. Performs union with path compression. \pre The representations represent the same value and one can be replaced by the other. */ template <class H> static void unify( const H& h, const H& g) { if ( find(h) != find(g)) { if ( h.ptr_->union_size() > g.ptr_->union_size()) unify_large_small( h, g); // make g point to h's rep. else unify_large_small( g, h); // make h point to g's rep. } } /*! \brief finds the currently valid representation for the handle \a h and returns a pointer to its stored value of type \a T. Performs path-compression to speed-up later union operations. */ template <class H> static typename H::Rep_pointer find( const H& h) { typedef typename H::Rep Rep; if ( h.ptr_->is_forwarding()) { // find new valid representation Rep* new_rep = h.ptr_; while ( new_rep->next != 0) new_rep = static_cast<Rep*>(new_rep->next); // path compression: assign new rep to all reps seen on the path // update reference count properly: all reps on the path loose // one reference, and the new_rep gains all of them unless // the rep on the path get actually deleted. Rep* rep = h.ptr_; while ( rep != new_rep) { Rep* tmp = static_cast<Rep*>(rep->next); if ( rep->is_shared()) { // rep survives the loss of one reference // and new_rep gets one more reference rep->remove_reference(); if ( tmp != new_rep) { // re-link rep to the new_rep rep->next = new_rep; new_rep->add_reference(); } } else { h.delete_rep( rep); // we have to delete the current rep } rep = tmp; } // hook h to new_rep h.ptr_ = new_rep; new_rep->add_reference(); } return h.ptr_->base_ptr(); } }; /*!\brief Policy class for \c Handle_with_policy that implements unifying of * identical representations \c T with trees and path compression. * * It also * sets the unused representation immediately to the default constructed * representation \c T(), which can help to free memory if the * representation is dynamically allocated and potentially large, e.g., * \c leda::real. This class is a model of the \c HandlePolicy concept. */ class Handle_policy_union_and_reset { public: /*!\brief * A rebind mechanism to create the representation type. */ template <class T, int hierarchy> struct Rep_bind { //! this default constructor contains some compile-time checks. Rep_bind() { //Intern::Rep_bind_reference_counted_with_forwarding<T, hierarchy> // check; // (void)check; (void)Intern::Rep_bind_reference_counted_with_forwarding<T, hierarchy>(); } //! the representation type including a reference counter. //! The handle allocates objects of this type. typedef typename Intern::Rep_bind_reference_counted_with_forwarding<T, hierarchy>::Rep Rep; }; /*!\brief * A rebind mechanism to access the base class for class hierarchies * of representations. * * The base classes can be used directly, but this * rebind mechamism allows the implementation of handle-rep classes * that are parameterized with the policy class only and adapt to * the necessary base class. */ template <class Alloc> struct Hierarchy_base { //! type that can be used as base class for the representation type. typedef Reference_counted_hierarchy_with_union<Alloc> Type; }; // abbreviation to re-use its implementation below. typedef Handle_policy_union U; /*! \brief unifies the representations of the two handles \a h and \a g. Performs union with path compression and assigns a default constructed value of the representation type \c Rep to the superfluous representation. \pre The representations represent the same value and one can be replaced by the other. */ template <class H> static void unify( const H& h, const H& g) { if ( find(h) != find(g)) { if ( h.ptr_->union_size() > g.ptr_->union_size()) { // reset representation in g to default construction of T if ( g.ptr_->is_shared()) g.ptr_->clear(); U::unify_large_small( h, g); // make g point to h's rep. } else { // reset representation in h to default construction of T if ( h.ptr_->is_shared()) h.ptr_->clear(); U::unify_large_small( g, h); // make h point to g's rep. } } } /*! \brief finds the currently valid representation for the handle \a h and returns a pointer to its stored value of type \a T. Performs path-compression to speed-up later union operations. */ template <class H> static typename H::Rep_pointer find( const H& h) { return U::find(h); } }; /*! \brief the base class for handles of reference counted representations of \c T. There are two fundamentally different usages of this base class: - with a single representation class. In this case the handle manages allocation and deallocation and the type \c T can be an arbitrary type---the handle adds the necessary reference counter internally. - with a hierarchy of representation classes. Type \c T will be the common base class of this hierarchy and it has to be derived itself from either \c ::CGAL::Reference_counted_hierarchy or \c ::CGAL::Reference_counted_hierarchy_with_union, both parameterized with an allocator. The allocator in the handle will not be used in this scenario, since the handle class does not allocate any representations. Instead, the handle class derived from this handle base class is allocating the different representations with the \c new operator. In this case, the allocator in the base class of \c T is used. The handle class distinguishes between these two alternative usages by checking if \c T is derived from one of the two base classes mentioned for the second alternative. If not, it picks the first alternative. In the second alternative, the correct base class, \c ::CGAL::Reference_counted_hierarchy_with_union, has to be used if the policy class is one of \c class Handle_policy_union r \c Handle_policy_union_and_reset. Otherwise, the other base class can be used to save space. The policy class \c Handle_policy_in_place is incompatible with the class hierarchy for representation classes since the pointer in the handle class would be missing. The dependency of the base classes for \c T and the policy classes is also encoded in the policy classes and can be used to write generic handle-rep scheme classes. To do that one can derive \c T from the expressions \c Policy::Hierarchy_base<Alloc>::Type assuming that \c Policy is the handle policy and \c Alloc is the allocator. Btw, the allocator is used as an allocator of character arrays here. \see \link Handle Handle for Reference Counting\endlink for an example for each of the two alternative usages. The template parameters are: - \b T: is one of the two following: - an arbitrary type but it must be a model of the \c DefaultConstructible concept if the default constructor of the handle is used. - a type derived from \c Reference_counted_hierarchy<Alloc> or \c Reference_counted_hierarchy_with_union<Alloc> implementing their virtual member function interface, namely a \c clone() function. - \b HandlePolicy: a model of the \c HandlePolicy concept or the \c Handle_policy_in_place class template that selects a specialized implementation without reference counting. Has the default \c Handle_policy_no_union. - \b Allocator_: a model of the \c Allocator concept, has the default \c CGAL_ALLOCATOR(T). */ template <class T_, class HandlePolicy = Handle_policy_no_union, class Allocator_ = CGAL_ALLOCATOR(T_)> class Handle_with_policy { public: //! first template parameter typedef T_ Handled_type; //! the handle type itself. typedef Handle_with_policy< Handled_type, HandlePolicy, Allocator_> Self; //! the instantiated model of the \c HandlePolicy concept. typedef HandlePolicy Handle_policy; //! the allocator type. typedef Allocator_ Allocator; enum { is_class_hierarchy = ::CGAL::is_same_or_derived< Reference_counted_hierarchy_base, Handled_type>::value }; typedef typename Handle_policy::template Rep_bind< Handled_type, is_class_hierarchy > Bind; // instantiate Rep_bind to activate compile time check in there static Bind bind; // Define type that is used for function matching typedef typename ::boost::mpl::if_c< is_class_hierarchy, ::CGAL::Tag_true, ::CGAL::Tag_false >::type Class_hierarchy; //! the internal representation, i.e., \c T plus a reference count //! (if needed), or just \c T if we derived from the base class to //! support a class hierarchy for the representations. typedef typename Bind::Rep Rep; typedef typename Rep::Rep_pointer Rep_pointer; typedef typename Allocator_::template rebind<Rep>::other Rep_allocator; //! integer type for identifying a representation. typedef std::ptrdiff_t Id_type; friend class Handle_policy_no_union; friend class Handle_policy_union; friend class Handle_policy_union_and_reset; private: mutable Rep* ptr_; // We have to distinguish between allocating single representations // and where we have a class hierarchy of representations, where the // user is responsible for allocating the first representations // and we can just \c clone and delete them. static Rep_allocator allocator; static Rep* new_rep( const Rep& rep) { CGAL_static_assertion( !( ::CGAL::is_same_or_derived< Reference_counted_hierarchy_base, Handled_type >::value )); Rep* p = allocator.allocate(1); allocator.construct(p, rep); return p; } static void delete_rep( Rep* p, ::CGAL::Tag_false ) { allocator.destroy( p); allocator.deallocate( p, 1); } static void delete_rep( Rep* p, ::CGAL::Tag_true ) { delete p; } static void delete_rep( Rep* p) { delete_rep(p, Class_hierarchy()); } static Rep* clone_rep( Rep* p, ::CGAL::Tag_false ) { return new_rep( *p); } static Rep* clone_rep( Rep* p, ::CGAL::Tag_true ) { return static_cast<Rep*>(p->clone()); } static Rep* clone_rep( Rep* p) { return clone_rep( p, Class_hierarchy()); } void remove_reference() { // cleans up the possible chain of forwarding reps Handle_policy::find( *this); if ( ! is_shared()) { delete_rep( ptr_); } else { ptr_->remove_reference(); ptr_->add_union_size( -1); } } template <class TT> Rep* make_from_single_arg( const TT& t, ::CGAL::Tag_false ) { return new_rep( Rep( Handled_type(t))); } template <class TT> Rep* make_from_single_arg( TT t, ::CGAL::Tag_true ) { //Bind bind_; // trigger compile-time check // (void)bind_; (void)Bind(); // shouldn't this be enough to trigger? return t; // has to be a pointer convertible to Rep* } protected: //! protected access to the stored representation Handled_type* ptr() { return static_cast<Handled_type*>(Handle_policy::find(*this));} //! protected access to the stored representation const Handled_type* ptr() const { return static_cast<const Handled_type*>(Handle_policy::find( *this)); } //! unify two representations. \pre The two representations describe //! the same value and one can be replaced by the other, i.e., the //! values are immutable, or protected from changes with \c copy_on_write() //! calls! void unify( const Self& h) const { Handle_policy::unify( *this, h); } //! can be called before modifying a shared representation //! to get an own copy of the representation which avoids effecting the //! other sharing handles. Does nothing if representation is actually //! not shared. void copy_on_write() { Handle_policy::find( *this); if ( is_shared() ) { Rep* tmp_ptr = clone_rep( ptr_); ptr_->remove_reference(); ptr_->add_union_size( -1); ptr_ = tmp_ptr; } } //! used with special protected constructor enum Use_with_initialize_with { USE_WITH_INITIALIZE_WITH //!< used with special protected constructor //!< of \c Handle_with_policy. }; //! special constructor, postpones the construction of the representation //! to one of the \c initialize_with() functions. An object is in an //! invalid state (and will report a failed precondition later) if //! it is not initialized with an \c initialize_with() function call //! after this constructor. Applicable for single representation but //! also for a class hierarchy of representations. Handle_with_policy( Use_with_initialize_with) : ptr_( 0) {} //! constructor used for class hierarchies of representations, where //! the handle class derived from this handle creates the different //! representations itself with the \c new operator. Except for this //! constructor, the the one with the \c Use_with_initialize_with //! argument, and the single argument template constructor no other //! constructor will work for class hierarchies of representations. Handle_with_policy( Rep* p) : ptr_( p) { CGAL_static_assertion(( ::CGAL::is_same_or_derived< Reference_counted_hierarchy_base, Handled_type >::value )); //Bind bind_; // trigger compile-time check //(void)bind_; (void)Bind(); } //! initializes the representation after the constructor from //! \c USE_WITH_INITIALIZE_WITH has been used. Applicable for a //! class hierarchy of representations only, where the derived handle class //! created the representation \c p with the \c new operator. No other //! version of \c initialize_with is applicable in this case except //! the template version with one argument. void initialize_with( Rep* p) { CGAL_static_assertion(( ::CGAL::is_same_or_derived< Reference_counted_hierarchy_base, Handled_type >::value )); //Bind bind_; // trigger compile-time check //(void)bind_; (void)Bind(); CGAL_precondition_msg( ptr_ == 0, "Handle_with_policy::initialize_with(): the " "representation has already been initialized."); ptr_ = p; } //! initializes the representation after the constructor from //! \c USE_WITH_INITIALIZE_WITH has been used. //! In case of the class hierarchy of representation classes, //! this function is also chosen for pointers to newly allocated //! representations that are types derived from \c T. In that case, //! the pointer is just assigned to the internal pointer. template <class T1> void initialize_with( const T1& t1) { CGAL_precondition_msg( ptr_ == 0, "Handle_with_policy::initialize_with(): the " "representation has already been initialized."); ptr_ = make_from_single_arg( t1, Class_hierarchy()); } //! initializes the representation after the constructor from //! \c USE_WITH_INITIALIZE_WITH has been used. template <class T1, class T2> void initialize_with( const T1& t1, const T2& t2) { CGAL_precondition_msg( ptr_ == 0, "Handle_with_policy::initialize_with(): the " "representation has already been initialized."); ptr_ = new_rep( Rep( Handled_type(t1,t2))); } //! initializes the representation after the constructor from //! \c USE_WITH_INITIALIZE_WITH has been used. template <class T1, class T2, class T3> void initialize_with( const T1& t1, const T2& t2, const T3& t3) { CGAL_precondition_msg( ptr_ == 0, "Handle_with_policy::initialize_with(): the " "representation has already been initialized."); ptr_ = new_rep( Rep( Handled_type(t1,t2,t3))); } //! initializes the representation after the constructor from //! \c USE_WITH_INITIALIZE_WITH has been used. template <class T1, class T2, class T3, class T4> void initialize_with( const T1& t1, const T2& t2, const T3& t3, const T4& t4) { CGAL_precondition_msg( ptr_ == 0, "Handle_with_policy::initialize_with(): the " "representation has already been initialized."); ptr_ = new_rep( Rep( Handled_type(t1,t2,t3,t4))); } //! initializes the representation after the constructor from //! \c USE_WITH_INITIALIZE_WITH has been used. template <class T1, class T2, class T3, class T4, class T5> void initialize_with( const T1& t1, const T2& t2, const T3& t3, const T4& t4, const T5& t5) { CGAL_precondition_msg( ptr_ == 0, "Handle_with_policy::initialize_with(): the " "representation has already been initialized."); ptr_ = new_rep( Rep( Handled_type(t1,t2,t3,t4,t5))); } //! initializes the representation after the constructor from //! \c USE_WITH_INITIALIZE_WITH has been used. template <class T1, class T2, class T3, class T4, class T5, class T6> void initialize_with( const T1& t1, const T2& t2, const T3& t3, const T4& t4, const T5& t5, const T6& t6) { CGAL_precondition_msg( ptr_ == 0, "Handle_with_policy::initialize_with(): the " "representation has already been initialized."); ptr_ = new_rep( Rep( Handled_type(t1,t2,t3,t4,t5,t6))); } //! initializes the representation after the constructor from //! \c USE_WITH_INITIALIZE_WITH has been used. template <class T1, class T2, class T3, class T4, class T5, class T6, class T7> void initialize_with( const T1& t1, const T2& t2, const T3& t3, const T4& t4, const T5& t5, const T6& t6, const T7& t7) { CGAL_precondition_msg( ptr_ == 0, "Handle_with_policy::initialize_with(): the " "representation has already been initialized."); ptr_ = new_rep( Rep( Handled_type(t1,t2,t3,t4,t5,t6,t7))); } //! initializes the representation after the constructor from //! \c USE_WITH_INITIALIZE_WITH has been used. template <class T1, class T2, class T3, class T4, class T5, class T6, class T7, class T8> void initialize_with( const T1& t1, const T2& t2, const T3& t3, const T4& t4, const T5& t5, const T6& t6, const T7& t7, const T8& t8) { CGAL_precondition_msg( ptr_ == 0, "Handle_with_policy::initialize_with(): the " "representation has already been initialized."); ptr_ = new_rep( Rep( Handled_type(t1,t2,t3,t4,t5,t6,t7,t8))); } //! initializes the representation after the constructor from //! \c USE_WITH_INITIALIZE_WITH has been used. template <class T1, class T2, class T3, class T4, class T5, class T6, class T7, class T8, class T9> void initialize_with( const T1& t1, const T2& t2, const T3& t3, const T4& t4, const T5& t5, const T6& t6, const T7& t7, const T8& t8, const T9& t9) { CGAL_precondition_msg( ptr_ == 0, "Handle_with_policy::initialize_with(): the " "representation has already been initialized."); ptr_ = new_rep( Rep( Handled_type(t1,t2,t3,t4,t5,t6,t7,t8,t9))); } public: //! default constructor. Handle_with_policy() : ptr_( new_rep( Rep())) {} //! copy constructor, increments reference count. Handle_with_policy(const Self& h) { CGAL_precondition_msg( h.ptr_ != 0, "Handle_with_policy::Handle_with_policy( Self): probably " "used special protected constructor and not the " "'initialize_with()' function."); Handle_policy::find( h); ptr_ = h.ptr_; ptr_->add_reference(); ptr_->add_union_size( 1); } //! forwarding constructor passing its parameter to the representation //! constructor. In case of the class hierarchy of representation classes, //! this constructor is also chosen for pointers to newly allocated //! representations that are types derived from \c T. In that case, //! the pointer is just assigned to the internal pointer. template <class T1> explicit Handle_with_policy( const T1& t) : ptr_( make_from_single_arg( t, Class_hierarchy())) {} //! forwarding constructor passing its parameters to the representation //! constructor. template <class T1, class T2> Handle_with_policy( const T1& t1, const T2& t2) : ptr_( new_rep( Rep( Handled_type( t1, t2)))) {} //! forwarding constructor passing its parameters to the representation //! constructor. template <class T1, class T2, class T3> Handle_with_policy( const T1& t1, const T2& t2, const T3& t3) : ptr_( new_rep( Rep( Handled_type( t1, t2, t3)))) {} //! forwarding constructor passing its parameters to the representation //! constructor. template <class T1, class T2, class T3, class T4> Handle_with_policy( const T1& t1, const T2& t2, const T3& t3, const T4& t4) : ptr_( new_rep( Rep( Handled_type( t1, t2, t3, t4)))) {} //! forwarding constructor passing its parameters to the representation //! constructor. template <class T1, class T2, class T3, class T4, class T5> Handle_with_policy( const T1& t1, const T2& t2, const T3& t3, const T4& t4, const T5& t5) : ptr_( new_rep( Rep( Handled_type( t1, t2, t3, t4, t5)))) {} //! forwarding constructor passing its parameters to the representation //! constructor. template <class T1, class T2, class T3, class T4, class T5, class T6> Handle_with_policy( const T1& t1, const T2& t2, const T3& t3, const T4& t4, const T5& t5, const T6& t6) : ptr_( new_rep( Rep( Handled_type( t1, t2, t3, t4, t5, t6)))) {} //! forwarding constructor passing its parameters to the representation //! constructor. template <class T1, class T2, class T3, class T4, class T5, class T6, class T7> Handle_with_policy( const T1& t1, const T2& t2, const T3& t3, const T4& t4, const T5& t5, const T6& t6, const T7& t7) : ptr_( new_rep( Rep( Handled_type( t1, t2, t3, t4, t5, t6, t7)))) {} //! forwarding constructor passing its parameters to the representation //! constructor. template <class T1, class T2, class T3, class T4, class T5, class T6, class T7, class T8> Handle_with_policy( const T1& t1, const T2& t2, const T3& t3, const T4& t4, const T5& t5, const T6& t6, const T7& t7, const T8& t8) : ptr_( new_rep( Rep( Handled_type( t1, t2, t3, t4, t5, t6, t7, t8)))) {} //! forwarding constructor passing its parameters to the representation //! constructor. template <class T1, class T2, class T3, class T4, class T5, class T6, class T7, class T8, class T9> Handle_with_policy( const T1& t1, const T2& t2, const T3& t3, const T4& t4, const T5& t5, const T6& t6, const T7& t7, const T8& t8, const T9& t9) : ptr_( new_rep( Rep( Handled_type( t1, t2, t3, t4, t5, t6, t7, t8, t9)))) {} //! destructor, decrements reference count. ~Handle_with_policy() { //Bind bind_; // trigger compile-time check //(void)bind_; (void)Bind(); CGAL_precondition_msg( ptr_ != 0, "Handle_with_policy::~Handle_with_policy(): probably used " "special protected constructor and not the " "'initialize_with()' function."); remove_reference(); } //! assignment, updates reference count correspondingly. Self& operator=( const Self& h) { CGAL_precondition_msg( h.ptr_ != 0, "Handle_with_policy::operator=(): probably " "used special protected constructor and not the " "'initialize_with()' function."); Handle_policy::find( h); h.ptr_->add_reference(); h.ptr_->add_union_size( 1); remove_reference(); ptr_ = h.ptr_; return *this; } //! returns \c true if both share the same representation. bool is_identical( const Self& h) const { return ptr() == h.ptr(); } //! returns a unique id value. Two handles share their representation //! is their id values are identical. Id_type id() const { return reinterpret_cast<Id_type>(&*ptr()); } //! returns true if the representation is shared, i.e., the reference //! counter is greater than one. bool is_shared() const { return ptr_->is_shared(); } //! returns \c true if the representation is actually forwarding to //! another equivalent representation (happens only with the //! union-find policies). bool is_forwarding() const { return ptr_->is_forwarding(); } //! returns the size of the union set including all reference counts that //! have been accumulated so far for this representation. int union_size() const { return ptr_->union_size(); } // backwards compatible bool identical( const Self& h) const { return is_identical(h); } #ifdef CGAL_HANDLE_WITH_POLICY_INTERNAL_TEST // provide access to pointer for testing only!! const Rep* test_ptr() const { return ptr_; } // provide access to pointer for testing only!! bool test_identical_ptr( const Self& h) const { return ptr_ == h.ptr_; } #endif // CGAL_HANDLE_WITH_POLICY_INTERNAL_TEST }; // instantiate Rep_bind to activate compile time check in there template <class T, class Policy, class Alloc> typename Handle_with_policy<T,Policy,Alloc>::Bind Handle_with_policy<T,Policy,Alloc>::bind; //! alternative syntax for \c h.id() to allow use with LEDA /*! This is only provided for \c Handle_policy_no_union because * ID numbers have to be fixed throughout an object's lifetime. */ template <class T, class A> typename Handle_with_policy<T, Handle_policy_no_union, A>::Id_type ID_Number(const Handle_with_policy<T, Handle_policy_no_union, A>& h) { return h.id(); } template <class T, class Policy, class Alloc> typename Handle_with_policy<T, Policy, Alloc>::Rep_allocator Handle_with_policy<T, Policy, Alloc>::allocator; /*! \brief specialization of the base class for handles for non-reference counted representations. Uses \c LEDA_MEMORY if available. */ template <class T_, class Allocator_> class Handle_with_policy<T_, Handle_policy_in_place, Allocator_> { public: //! first template paramter typedef T_ Handled_type; //! the handle type itself. typedef Handle_with_policy< Handled_type, Handle_policy_in_place, Allocator_> Self; //! the model of the \c HandlePolicy concept. typedef Handle_policy_in_place Handle_policy; //! the allocator type. typedef Allocator_ Allocator; //! identify \c T with the internal representation \c Rep. typedef Handled_type Rep; //! integer type for identifying a representation. typedef std::ptrdiff_t Id_type; private: // store the rep in place Rep rep; protected: //! protected access to the stored representation Handled_type* ptr() { return &rep; } //! protected access to the stored representation const Handled_type* ptr() const { return &rep; } //! unify two representations, a null op here. void unify( const Self&) const {} //! can be called before modifying a shared representation //! to get an own copy of the representation, a null op here. void copy_on_write() {} //! used with special protected constructor enum Use_with_initialize_with { USE_WITH_INITIALIZE_WITH //!< used with special protected constructor }; //! special constructor, postpones the construction of the representation //! to one of the \c initialize_with() functions. Requires default //! constructor for \c T. Handle_with_policy( Use_with_initialize_with) {} //! initializes the representation after the constructor from //! \c USE_WITH_INITIALIZE_WITH has been used. template <class T1> void initialize_with( const T1& t1) { rep = Rep(t1); } //! initializes the representation after the constructor from //! \c USE_WITH_INITIALIZE_WITH has been used. template <class T1, class T2> void initialize_with( const T1& t1, const T2& t2) { rep = Rep(t1,t2); } //! initializes the representation after the constructor from //! \c USE_WITH_INITIALIZE_WITH has been used. template <class T1, class T2, class T3> void initialize_with( const T1& t1, const T2& t2, const T3& t3) { rep = Rep(t1,t2,t3); } //! initializes the representation after the constructor from //! \c USE_WITH_INITIALIZE_WITH has been used. template <class T1, class T2, class T3, class T4> void initialize_with( const T1& t1, const T2& t2, const T3& t3, const T4& t4) { rep = Rep(t1,t2,t3,t4); } //! initializes the representation after the constructor from //! \c USE_WITH_INITIALIZE_WITH has been used. template <class T1, class T2, class T3, class T4, class T5> void initialize_with( const T1& t1, const T2& t2, const T3& t3, const T4& t4, const T5& t5) { rep = Rep(t1,t2,t3,t4,t5); } //! initializes the representation after the constructor from //! \c USE_WITH_INITIALIZE_WITH has been used. template <class T1, class T2, class T3, class T4, class T5, class T6> void initialize_with( const T1& t1, const T2& t2, const T3& t3, const T4& t4, const T5& t5, const T6& t6) { rep = Rep(t1,t2,t3,t4,t5,t6); } //! initializes the representation after the constructor from //! \c USE_WITH_INITIALIZE_WITH has been used. template <class T1, class T2, class T3, class T4, class T5, class T6, class T7> void initialize_with( const T1& t1, const T2& t2, const T3& t3, const T4& t4, const T5& t5, const T6& t6, const T7& t7) { rep = Rep(t1,t2,t3,t4,t5,t6,t7); } //! initializes the representation after the constructor from //! \c USE_WITH_INITIALIZE_WITH has been used. template <class T1, class T2, class T3, class T4, class T5, class T6, class T7, class T8> void initialize_with( const T1& t1, const T2& t2, const T3& t3, const T4& t4, const T5& t5, const T6& t6, const T7& t7, const T8& t8) { rep = Rep(t1,t2,t3,t4,t5,t6,t7,t8); } //! initializes the representation after the constructor from //! \c USE_WITH_INITIALIZE_WITH has been used. template <class T1, class T2, class T3, class T4, class T5, class T6, class T7, class T8, class T9> void initialize_with( const T1& t1, const T2& t2, const T3& t3, const T4& t4, const T5& t5, const T6& t6, const T7& t7, const T8& t8, const T9& t9) { rep = Rep(t1,t2,t3,t4,t5,t6,t7,t8,t9); } public: //! default constructor. Handle_with_policy() {} //! copy constructor. Handle_with_policy(const Self& h) : rep( h.rep) {} //! forwarding constructor passing its parameter to the representation //! constructor. template <class T1> explicit Handle_with_policy( const T1& t) : rep( Rep(t)) {} //! forwarding constructor passing its parameters to the representation //! constructor. template <class T1, class T2> Handle_with_policy( const T1& t1, const T2& t2) : rep( Rep(t1,t2)) {} //! forwarding constructor passing its parameters to the representation //! constructor. template <class T1, class T2, class T3> Handle_with_policy( const T1& t1, const T2& t2, const T3& t3) : rep( Rep(t1,t2,t3)) {} //! forwarding constructor passing its parameters to the representation //! constructor. template <class T1, class T2, class T3, class T4> Handle_with_policy( const T1& t1, const T2& t2, const T3& t3, const T4& t4) : rep( Rep( t1, t2, t3, t4)) {} //! forwarding constructor passing its parameters to the representation //! constructor. template <class T1, class T2, class T3, class T4, class T5> Handle_with_policy( const T1& t1, const T2& t2, const T3& t3, const T4& t4, const T5& t5) : rep( Rep( t1, t2, t3, t4, t5)) {} //! forwarding constructor passing its parameters to the representation //! constructor. template <class T1, class T2, class T3, class T4, class T5, class T6> Handle_with_policy( const T1& t1, const T2& t2, const T3& t3, const T4& t4, const T5& t5, const T6& t6) : rep( Rep( t1, t2, t3, t4, t5, t6)) {} //! forwarding constructor passing its parameters to the representation //! constructor. template <class T1, class T2, class T3, class T4, class T5, class T6, class T7> Handle_with_policy( const T1& t1, const T2& t2, const T3& t3, const T4& t4, const T5& t5, const T6& t6, const T7& t7) : rep( Rep( t1, t2, t3, t4, t5, t6, t7)) {} //! forwarding constructor passing its parameters to the representation //! constructor. template <class T1, class T2, class T3, class T4, class T5, class T6, class T7, class T8> Handle_with_policy( const T1& t1, const T2& t2, const T3& t3, const T4& t4, const T5& t5, const T6& t6, const T7& t7, const T8& t8) : rep( Rep( t1, t2, t3, t4, t5, t6, t7, t8)) {} //! forwarding constructor passing its parameters to the representation //! constructor. template <class T1, class T2, class T3, class T4, class T5, class T6, class T7, class T8, class T9> Handle_with_policy( const T1& t1, const T2& t2, const T3& t3, const T4& t4, const T5& t5, const T6& t6, const T7& t7, const T8& t8, const T9& t9) : rep( Rep( t1, t2, t3, t4, t5, t6, t7, t8, t9)) {} //! returns \c true if both share the same representation. bool is_identical( const Self& h) const { return this == &h; } //! returns a unique id value. Two handles share their representation //! is their id values are identical. Id_type id() const { return ptr() - static_cast<Handled_type const*>(0); } //! returns \c false since the representation is not shared for //! this specialization. bool is_shared() const { return false; } //! returns \c false since the representation is not forwarding for //! this specialization. bool is_forwarding() const { return false; } //! returns \c 1 as the union size for this specialization. int union_size() const { return 1; } // backwards compatible bool identical( const Self& h) const { return is_identical(h); } #ifdef CGAL_HANDLE_WITH_POLICY_INTERNAL_TEST // provide access to pointer for testing only!! const Rep* test_ptr() const { return *rep; } // provide access to pointer for testing only!! bool test_identical_ptr( const Self& h) const { return this == &h; } #endif // CGAL_HANDLE_WITH_POLICY_INTERNAL_TEST #ifdef CGAL_USE_LEDA LEDA_MEMORY( Self) #endif }; template <class T, class HandlePolicy, class Allocator> inline bool identical(const Handle_with_policy<T,HandlePolicy,Allocator> &h1, const Handle_with_policy<T,HandlePolicy,Allocator> &h2) { return h1.is_identical(h2); } /*\brief * This class' function call operator test whether one handle's \c id is * less than the \c id of the other handle. * * "Less" is defined in terms of the second template argument, * which defaults to \c std::less<Handle::Id_type> */ template <class Handle, class Less = std::less<typename Handle::Id_type> > class Handle_id_less_than { public: //! result_type typedef bool result_type; //! type of first argument typedef Handle first_argument_type; //! type of second argument typedef Handle second_argument_type; //! returns \c true iff \c h1.id() < \c h2.id() bool operator () (Handle h1, Handle h2) { Less is_less; return is_less(h1.id(), h2.id()); } //! returns \c true iff \c h1.id() < \c h2.id() bool operator () (Handle h1, Handle h2) const { Less is_less; return is_less(h1.id(), h2.id()); } }; //@} } //namespace CGAL #endif // CGAL_HANDLE_WITH_POLICY_H
[ "cmrose@lbl.gov" ]
cmrose@lbl.gov
6509b75300d3a650b52967930adada458be19f20
e029e3cfddcf7051d2937600bd420da638ab0e04
/src/masternode-payments.cpp
e88daf4c987e98958ad112a89704cc655bb3c3ed
[ "MIT" ]
permissive
reflexcoin/core
d49e2fd8b7383d3fc101752dccf7fa45a4b26391
eeda5f3424d4eb8969580b5ac8787d350760d1f5
refs/heads/master
2020-06-12T04:45:26.910957
2019-07-10T03:10:20
2019-07-10T03:10:20
194,197,107
0
1
MIT
2019-07-10T03:10:21
2019-06-28T03:03:39
C++
UTF-8
C++
false
false
42,192
cpp
// Copyright (c) 2014-2017 The Dash Core developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "activemasternode.h" #include "governance-classes.h" #include "masternode-payments.h" #include "masternode-sync.h" #include "masternodeman.h" #include "messagesigner.h" #include "netfulfilledman.h" #include "spork.h" #include "util.h" #include <boost/lexical_cast.hpp> /** Object for who's going to get paid on which blocks */ CMasternodePayments mnpayments; CCriticalSection cs_vecPayees; CCriticalSection cs_mapMasternodeBlocks; CCriticalSection cs_mapMasternodePaymentVotes; /** * IsBlockValueValid * * Determine if coinbase outgoing created money is the correct value * * Why is this needed? * - In Dash some blocks are superblocks, which output much higher amounts of coins * - Otherblocks are 10% lower in outgoing value, so in total, no extra coins are created * - When non-superblocks are detected, the normal schedule should be maintained */ bool IsBlockValueValid(const CBlock& block, int nBlockHeight, CAmount blockReward, std::string &strErrorRet) { strErrorRet = ""; bool isBlockRewardValueMet = (block.vtx[0].GetValueOut() <= blockReward); if(fDebug) LogPrintf("block.vtx[0].GetValueOut() %lld <= blockReward %lld\n", block.vtx[0].GetValueOut(), blockReward); // we are still using budgets, but we have no data about them anymore, // all we know is predefined budget cycle and window const Consensus::Params& consensusParams = Params().GetConsensus(); if(nBlockHeight < consensusParams.nSuperblockStartBlock) { int nOffset = nBlockHeight % consensusParams.nBudgetPaymentsCycleBlocks; if(nBlockHeight >= consensusParams.nBudgetPaymentsStartBlock && nOffset < consensusParams.nBudgetPaymentsWindowBlocks) { // NOTE: make sure SPORK_13_OLD_SUPERBLOCK_FLAG is disabled when 12.1 starts to go live if(masternodeSync.IsSynced() && !sporkManager.IsSporkActive(SPORK_13_OLD_SUPERBLOCK_FLAG)) { // no budget blocks should be accepted here, if SPORK_13_OLD_SUPERBLOCK_FLAG is disabled LogPrint("gobject", "IsBlockValueValid -- Client synced but budget spork is disabled, checking block value against block reward\n"); if(!isBlockRewardValueMet) { strErrorRet = strprintf("coinbase pays too much at height %d (actual=%d vs limit=%d), exceeded block reward, budgets are disabled", nBlockHeight, block.vtx[0].GetValueOut(), blockReward); } return isBlockRewardValueMet; } LogPrint("gobject", "IsBlockValueValid -- WARNING: Skipping budget block value checks, accepting block\n"); // TODO: reprocess blocks to make sure they are legit? return true; } // LogPrint("gobject", "IsBlockValueValid -- Block is not in budget cycle window, checking block value against block reward\n"); if(!isBlockRewardValueMet) { strErrorRet = strprintf("coinbase pays too much at height %d (actual=%d vs limit=%d), exceeded block reward, block is not in budget cycle window", nBlockHeight, block.vtx[0].GetValueOut(), blockReward); } return isBlockRewardValueMet; } // superblocks started CAmount nSuperblockMaxValue = blockReward + CSuperblock::GetPaymentsLimit(nBlockHeight); bool isSuperblockMaxValueMet = (block.vtx[0].GetValueOut() <= nSuperblockMaxValue); LogPrint("gobject", "block.vtx[0].GetValueOut() %lld <= nSuperblockMaxValue %lld\n", block.vtx[0].GetValueOut(), nSuperblockMaxValue); if(!masternodeSync.IsSynced()) { // not enough data but at least it must NOT exceed superblock max value if(CSuperblock::IsValidBlockHeight(nBlockHeight)) { if(fDebug) LogPrintf("IsBlockPayeeValid -- WARNING: Client not synced, checking superblock max bounds only\n"); if(!isSuperblockMaxValueMet) { strErrorRet = strprintf("coinbase pays too much at height %d (actual=%d vs limit=%d), exceeded superblock max value", nBlockHeight, block.vtx[0].GetValueOut(), nSuperblockMaxValue); } return isSuperblockMaxValueMet; } if(!isBlockRewardValueMet) { strErrorRet = strprintf("coinbase pays too much at height %d (actual=%d vs limit=%d), exceeded block reward, only regular blocks are allowed at this height", nBlockHeight, block.vtx[0].GetValueOut(), blockReward); } // it MUST be a regular block otherwise return isBlockRewardValueMet; } // we are synced, let's try to check as much data as we can if(sporkManager.IsSporkActive(SPORK_9_SUPERBLOCKS_ENABLED)) { if(CSuperblockManager::IsSuperblockTriggered(nBlockHeight)) { if(CSuperblockManager::IsValid(block.vtx[0], nBlockHeight, blockReward)) { LogPrint("gobject", "IsBlockValueValid -- Valid superblock at height %d: %s", nBlockHeight, block.vtx[0].ToString()); // all checks are done in CSuperblock::IsValid, nothing to do here return true; } // triggered but invalid? that's weird LogPrintf("IsBlockValueValid -- ERROR: Invalid superblock detected at height %d: %s", nBlockHeight, block.vtx[0].ToString()); // should NOT allow invalid superblocks, when superblocks are enabled strErrorRet = strprintf("invalid superblock detected at height %d", nBlockHeight); return false; } LogPrint("gobject", "IsBlockValueValid -- No triggered superblock detected at height %d\n", nBlockHeight); if(!isBlockRewardValueMet) { strErrorRet = strprintf("coinbase pays too much at height %d (actual=%d vs limit=%d), exceeded block reward, no triggered superblock detected", nBlockHeight, block.vtx[0].GetValueOut(), blockReward); } } else { // should NOT allow superblocks at all, when superblocks are disabled LogPrint("gobject", "IsBlockValueValid -- Superblocks are disabled, no superblocks allowed\n"); if(!isBlockRewardValueMet) { strErrorRet = strprintf("coinbase pays too much at height %d (actual=%d vs limit=%d), exceeded block reward, superblocks are disabled", nBlockHeight, block.vtx[0].GetValueOut(), blockReward); } } // it MUST be a regular block return isBlockRewardValueMet; } bool IsBlockPayeeValid(const CTransaction& txNew, int nBlockHeight, CAmount blockReward) { if(!masternodeSync.IsSynced()) { //there is no budget data to use to check anything, let's just accept the longest chain if(fDebug) LogPrintf("IsBlockPayeeValid -- WARNING: Client not synced, skipping block payee checks\n"); return true; } // we are still using budgets, but we have no data about them anymore, // we can only check masternode payments const Consensus::Params& consensusParams = Params().GetConsensus(); if(nBlockHeight < consensusParams.nSuperblockStartBlock) { if(mnpayments.IsTransactionValid(txNew, nBlockHeight)) { LogPrint("mnpayments", "IsBlockPayeeValid -- Valid masternode payment at height %d: %s", nBlockHeight, txNew.ToString()); return true; } int nOffset = nBlockHeight % consensusParams.nBudgetPaymentsCycleBlocks; if(nBlockHeight >= consensusParams.nBudgetPaymentsStartBlock && nOffset < consensusParams.nBudgetPaymentsWindowBlocks) { if(!sporkManager.IsSporkActive(SPORK_13_OLD_SUPERBLOCK_FLAG)) { // no budget blocks should be accepted here, if SPORK_13_OLD_SUPERBLOCK_FLAG is disabled LogPrint("gobject", "IsBlockPayeeValid -- ERROR: Client synced but budget spork is disabled and masternode payment is invalid\n"); return false; } // NOTE: this should never happen in real, SPORK_13_OLD_SUPERBLOCK_FLAG MUST be disabled when 12.1 starts to go live LogPrint("gobject", "IsBlockPayeeValid -- WARNING: Probably valid budget block, have no data, accepting\n"); // TODO: reprocess blocks to make sure they are legit? return true; } if(sporkManager.IsSporkActive(SPORK_8_MASTERNODE_PAYMENT_ENFORCEMENT)) { LogPrintf("IsBlockPayeeValid -- ERROR: Invalid masternode payment detected at height %d: %s", nBlockHeight, txNew.ToString()); return false; } LogPrintf("IsBlockPayeeValid -- WARNING: Masternode payment enforcement is disabled, accepting any payee\n"); return true; } // superblocks started // SEE IF THIS IS A VALID SUPERBLOCK if(sporkManager.IsSporkActive(SPORK_9_SUPERBLOCKS_ENABLED)) { if(CSuperblockManager::IsSuperblockTriggered(nBlockHeight)) { if(CSuperblockManager::IsValid(txNew, nBlockHeight, blockReward)) { LogPrint("gobject", "IsBlockPayeeValid -- Valid superblock at height %d: %s", nBlockHeight, txNew.ToString()); return true; } LogPrintf("IsBlockPayeeValid -- ERROR: Invalid superblock detected at height %d: %s", nBlockHeight, txNew.ToString()); // should NOT allow such superblocks, when superblocks are enabled return false; } // continue validation, should pay MN LogPrint("gobject", "IsBlockPayeeValid -- No triggered superblock detected at height %d\n", nBlockHeight); } else { // should NOT allow superblocks at all, when superblocks are disabled LogPrint("gobject", "IsBlockPayeeValid -- Superblocks are disabled, no superblocks allowed\n"); } // IF THIS ISN'T A SUPERBLOCK OR SUPERBLOCK IS INVALID, IT SHOULD PAY A MASTERNODE DIRECTLY if(mnpayments.IsTransactionValid(txNew, nBlockHeight)) { LogPrint("mnpayments", "IsBlockPayeeValid -- Valid masternode payment at height %d: %s", nBlockHeight, txNew.ToString()); return true; } if(sporkManager.IsSporkActive(SPORK_8_MASTERNODE_PAYMENT_ENFORCEMENT)) { LogPrintf("IsBlockPayeeValid -- ERROR: Invalid masternode payment detected at height %d: %s", nBlockHeight, txNew.ToString()); return false; } LogPrintf("IsBlockPayeeValid -- WARNING: Masternode payment enforcement is disabled, accepting any payee\n"); return true; } void FillBlockPayments(CMutableTransaction& txNew, int nBlockHeight, CAmount blockReward, CTxOut& txoutMasternodeRet, std::vector<CTxOut>& voutSuperblockRet) { // only create superblocks if spork is enabled AND if superblock is actually triggered // (height should be validated inside) if(sporkManager.IsSporkActive(SPORK_9_SUPERBLOCKS_ENABLED) && CSuperblockManager::IsSuperblockTriggered(nBlockHeight)) { LogPrint("gobject", "FillBlockPayments -- triggered superblock creation at height %d\n", nBlockHeight); CSuperblockManager::CreateSuperblock(txNew, nBlockHeight, voutSuperblockRet); return; } // FILL BLOCK PAYEE WITH MASTERNODE PAYMENT OTHERWISE mnpayments.FillBlockPayee(txNew, nBlockHeight, blockReward, txoutMasternodeRet); LogPrint("mnpayments", "FillBlockPayments -- nBlockHeight %d blockReward %lld txoutMasternodeRet %s txNew %s", nBlockHeight, blockReward, txoutMasternodeRet.ToString(), txNew.ToString()); } std::string GetRequiredPaymentsString(int nBlockHeight) { // IF WE HAVE A ACTIVATED TRIGGER FOR THIS HEIGHT - IT IS A SUPERBLOCK, GET THE REQUIRED PAYEES if(CSuperblockManager::IsSuperblockTriggered(nBlockHeight)) { return CSuperblockManager::GetRequiredPaymentsString(nBlockHeight); } // OTHERWISE, PAY MASTERNODE return mnpayments.GetRequiredPaymentsString(nBlockHeight); } void CMasternodePayments::Clear() { LOCK2(cs_mapMasternodeBlocks, cs_mapMasternodePaymentVotes); mapMasternodeBlocks.clear(); mapMasternodePaymentVotes.clear(); } bool CMasternodePayments::CanVote(COutPoint outMasternode, int nBlockHeight) { LOCK(cs_mapMasternodePaymentVotes); if (mapMasternodesLastVote.count(outMasternode) && mapMasternodesLastVote[outMasternode] == nBlockHeight) { return false; } //record this masternode voted mapMasternodesLastVote[outMasternode] = nBlockHeight; return true; } /** * FillBlockPayee * * Fill Masternode ONLY payment block */ void CMasternodePayments::FillBlockPayee(CMutableTransaction& txNew, int nBlockHeight, CAmount blockReward, CTxOut& txoutMasternodeRet) { // make sure it's not filled yet txoutMasternodeRet = CTxOut(); CScript payee; if(!mnpayments.GetBlockPayee(nBlockHeight, payee)) { // no masternode detected... int nCount = 0; masternode_info_t mnInfo; if(!mnodeman.GetNextMasternodeInQueueForPayment(nBlockHeight, true, nCount, mnInfo)) { // ...and we can't calculate it on our own LogPrintf("CMasternodePayments::FillBlockPayee -- Failed to detect masternode to pay\n"); return; } // fill payee with locally calculated winner and hope for the best payee = GetScriptForDestination(mnInfo.pubKeyCollateralAddress.GetID()); } // GET MASTERNODE PAYMENT VARIABLES SETUP CAmount masternodePayment = GetMasternodePayment(nBlockHeight, blockReward); // split reward between miner ... txNew.vout[0].nValue -= masternodePayment; // ... and masternode txoutMasternodeRet = CTxOut(masternodePayment, payee); txNew.vout.push_back(txoutMasternodeRet); CTxDestination address1; ExtractDestination(payee, address1); CBitcoinAddress address2(address1); LogPrintf("CMasternodePayments::FillBlockPayee -- Masternode payment %lld to %s\n", masternodePayment, address2.ToString()); } int CMasternodePayments::GetMinMasternodePaymentsProto() { return sporkManager.IsSporkActive(SPORK_10_MASTERNODE_PAY_UPDATED_NODES) ? MIN_MASTERNODE_PAYMENT_PROTO_VERSION_2 : MIN_MASTERNODE_PAYMENT_PROTO_VERSION_1; } void CMasternodePayments::ProcessMessage(CNode* pfrom, std::string& strCommand, CDataStream& vRecv, CConnman& connman) { if(fLiteMode) return; // disable all Dash specific functionality if (strCommand == NetMsgType::MASTERNODEPAYMENTSYNC) { //Masternode Payments Request Sync // Ignore such requests until we are fully synced. // We could start processing this after masternode list is synced // but this is a heavy one so it's better to finish sync first. if (!masternodeSync.IsSynced()) return; int nCountNeeded; vRecv >> nCountNeeded; if(netfulfilledman.HasFulfilledRequest(pfrom->addr, NetMsgType::MASTERNODEPAYMENTSYNC)) { // Asking for the payments list multiple times in a short period of time is no good LogPrintf("MASTERNODEPAYMENTSYNC -- peer already asked me for the list, peer=%d\n", pfrom->id); Misbehaving(pfrom->GetId(), 20); return; } netfulfilledman.AddFulfilledRequest(pfrom->addr, NetMsgType::MASTERNODEPAYMENTSYNC); Sync(pfrom, connman); LogPrintf("MASTERNODEPAYMENTSYNC -- Sent Masternode payment votes to peer %d\n", pfrom->id); } else if (strCommand == NetMsgType::MASTERNODEPAYMENTVOTE) { // Masternode Payments Vote for the Winner CMasternodePaymentVote vote; vRecv >> vote; if(pfrom->nVersion < GetMinMasternodePaymentsProto()) return; uint256 nHash = vote.GetHash(); pfrom->setAskFor.erase(nHash); // TODO: clear setAskFor for MSG_MASTERNODE_PAYMENT_BLOCK too // Ignore any payments messages until masternode list is synced if(!masternodeSync.IsMasternodeListSynced()) return; { LOCK(cs_mapMasternodePaymentVotes); if(mapMasternodePaymentVotes.count(nHash)) { LogPrint("mnpayments", "MASTERNODEPAYMENTVOTE -- hash=%s, nHeight=%d seen\n", nHash.ToString(), nCachedBlockHeight); return; } // Avoid processing same vote multiple times mapMasternodePaymentVotes[nHash] = vote; // but first mark vote as non-verified, // AddPaymentVote() below should take care of it if vote is actually ok mapMasternodePaymentVotes[nHash].MarkAsNotVerified(); } int nFirstBlock = nCachedBlockHeight - GetStorageLimit(); if(vote.nBlockHeight < nFirstBlock || vote.nBlockHeight > nCachedBlockHeight+20) { LogPrint("mnpayments", "MASTERNODEPAYMENTVOTE -- vote out of range: nFirstBlock=%d, nBlockHeight=%d, nHeight=%d\n", nFirstBlock, vote.nBlockHeight, nCachedBlockHeight); return; } std::string strError = ""; if(!vote.IsValid(pfrom, nCachedBlockHeight, strError, connman)) { LogPrint("mnpayments", "MASTERNODEPAYMENTVOTE -- invalid message, error: %s\n", strError); return; } if(!CanVote(vote.vinMasternode.prevout, vote.nBlockHeight)) { LogPrintf("MASTERNODEPAYMENTVOTE -- masternode already voted, masternode=%s\n", vote.vinMasternode.prevout.ToStringShort()); return; } masternode_info_t mnInfo; if(!mnodeman.GetMasternodeInfo(vote.vinMasternode.prevout, mnInfo)) { // mn was not found, so we can't check vote, some info is probably missing LogPrintf("MASTERNODEPAYMENTVOTE -- masternode is missing %s\n", vote.vinMasternode.prevout.ToStringShort()); mnodeman.AskForMN(pfrom, vote.vinMasternode.prevout, connman); return; } int nDos = 0; if(!vote.CheckSignature(mnInfo.pubKeyMasternode, nCachedBlockHeight, nDos)) { if(nDos) { LogPrintf("MASTERNODEPAYMENTVOTE -- ERROR: invalid signature\n"); Misbehaving(pfrom->GetId(), nDos); } else { // only warn about anything non-critical (i.e. nDos == 0) in debug mode LogPrint("mnpayments", "MASTERNODEPAYMENTVOTE -- WARNING: invalid signature\n"); } // Either our info or vote info could be outdated. // In case our info is outdated, ask for an update, mnodeman.AskForMN(pfrom, vote.vinMasternode.prevout, connman); // but there is nothing we can do if vote info itself is outdated // (i.e. it was signed by a mn which changed its key), // so just quit here. return; } CTxDestination address1; ExtractDestination(vote.payee, address1); CBitcoinAddress address2(address1); LogPrint("mnpayments", "MASTERNODEPAYMENTVOTE -- vote: address=%s, nBlockHeight=%d, nHeight=%d, prevout=%s, hash=%s new\n", address2.ToString(), vote.nBlockHeight, nCachedBlockHeight, vote.vinMasternode.prevout.ToStringShort(), nHash.ToString()); if(AddPaymentVote(vote)){ vote.Relay(connman); masternodeSync.BumpAssetLastTime("MASTERNODEPAYMENTVOTE"); } } } bool CMasternodePaymentVote::Sign() { std::string strError; std::string strMessage = vinMasternode.prevout.ToStringShort() + boost::lexical_cast<std::string>(nBlockHeight) + ScriptToAsmStr(payee); if(!CMessageSigner::SignMessage(strMessage, vchSig, activeMasternode.keyMasternode)) { LogPrintf("CMasternodePaymentVote::Sign -- SignMessage() failed\n"); return false; } if(!CMessageSigner::VerifyMessage(activeMasternode.pubKeyMasternode, vchSig, strMessage, strError)) { LogPrintf("CMasternodePaymentVote::Sign -- VerifyMessage() failed, error: %s\n", strError); return false; } return true; } bool CMasternodePayments::GetBlockPayee(int nBlockHeight, CScript& payee) { if(mapMasternodeBlocks.count(nBlockHeight)){ return mapMasternodeBlocks[nBlockHeight].GetBestPayee(payee); } return false; } // Is this masternode scheduled to get paid soon? // -- Only look ahead up to 8 blocks to allow for propagation of the latest 2 blocks of votes bool CMasternodePayments::IsScheduled(CMasternode& mn, int nNotBlockHeight) { LOCK(cs_mapMasternodeBlocks); if(!masternodeSync.IsMasternodeListSynced()) return false; CScript mnpayee; mnpayee = GetScriptForDestination(mn.pubKeyCollateralAddress.GetID()); CScript payee; for(int64_t h = nCachedBlockHeight; h <= nCachedBlockHeight + 8; h++){ if(h == nNotBlockHeight) continue; if(mapMasternodeBlocks.count(h) && mapMasternodeBlocks[h].GetBestPayee(payee) && mnpayee == payee) { return true; } } return false; } bool CMasternodePayments::AddPaymentVote(const CMasternodePaymentVote& vote) { uint256 blockHash = uint256(); if(!GetBlockHash(blockHash, vote.nBlockHeight - 101)) return false; if(HasVerifiedPaymentVote(vote.GetHash())) return false; LOCK2(cs_mapMasternodeBlocks, cs_mapMasternodePaymentVotes); mapMasternodePaymentVotes[vote.GetHash()] = vote; if(!mapMasternodeBlocks.count(vote.nBlockHeight)) { CMasternodeBlockPayees blockPayees(vote.nBlockHeight); mapMasternodeBlocks[vote.nBlockHeight] = blockPayees; } mapMasternodeBlocks[vote.nBlockHeight].AddPayee(vote); return true; } bool CMasternodePayments::HasVerifiedPaymentVote(uint256 hashIn) { LOCK(cs_mapMasternodePaymentVotes); std::map<uint256, CMasternodePaymentVote>::iterator it = mapMasternodePaymentVotes.find(hashIn); return it != mapMasternodePaymentVotes.end() && it->second.IsVerified(); } void CMasternodeBlockPayees::AddPayee(const CMasternodePaymentVote& vote) { LOCK(cs_vecPayees); BOOST_FOREACH(CMasternodePayee& payee, vecPayees) { if (payee.GetPayee() == vote.payee) { payee.AddVoteHash(vote.GetHash()); return; } } CMasternodePayee payeeNew(vote.payee, vote.GetHash()); vecPayees.push_back(payeeNew); } bool CMasternodeBlockPayees::GetBestPayee(CScript& payeeRet) { LOCK(cs_vecPayees); if(!vecPayees.size()) { LogPrint("mnpayments", "CMasternodeBlockPayees::GetBestPayee -- ERROR: couldn't find any payee\n"); return false; } int nVotes = -1; BOOST_FOREACH(CMasternodePayee& payee, vecPayees) { if (payee.GetVoteCount() > nVotes) { payeeRet = payee.GetPayee(); nVotes = payee.GetVoteCount(); } } return (nVotes > -1); } bool CMasternodeBlockPayees::HasPayeeWithVotes(const CScript& payeeIn, int nVotesReq) { LOCK(cs_vecPayees); BOOST_FOREACH(CMasternodePayee& payee, vecPayees) { if (payee.GetVoteCount() >= nVotesReq && payee.GetPayee() == payeeIn) { return true; } } LogPrint("mnpayments", "CMasternodeBlockPayees::HasPayeeWithVotes -- ERROR: couldn't find any payee with %d+ votes\n", nVotesReq); return false; } bool CMasternodeBlockPayees::IsTransactionValid(const CTransaction& txNew) { LOCK(cs_vecPayees); int nMaxSignatures = 0; std::string strPayeesPossible = ""; CAmount nMasternodePayment = GetMasternodePayment(nBlockHeight, txNew.GetValueOut()); //require at least MNPAYMENTS_SIGNATURES_REQUIRED signatures BOOST_FOREACH(CMasternodePayee& payee, vecPayees) { if (payee.GetVoteCount() >= nMaxSignatures) { nMaxSignatures = payee.GetVoteCount(); } } // if we don't have at least MNPAYMENTS_SIGNATURES_REQUIRED signatures on a payee, approve whichever is the longest chain if(nMaxSignatures < MNPAYMENTS_SIGNATURES_REQUIRED) return true; BOOST_FOREACH(CMasternodePayee& payee, vecPayees) { if (payee.GetVoteCount() >= MNPAYMENTS_SIGNATURES_REQUIRED) { BOOST_FOREACH(CTxOut txout, txNew.vout) { if (payee.GetPayee() == txout.scriptPubKey && nMasternodePayment == txout.nValue) { LogPrint("mnpayments", "CMasternodeBlockPayees::IsTransactionValid -- Found required payment\n"); return true; } } CTxDestination address1; ExtractDestination(payee.GetPayee(), address1); CBitcoinAddress address2(address1); if(strPayeesPossible == "") { strPayeesPossible = address2.ToString(); } else { strPayeesPossible += "," + address2.ToString(); } } } LogPrintf("CMasternodeBlockPayees::IsTransactionValid -- ERROR: Missing required payment, possible payees: '%s', amount: %f DASH\n", strPayeesPossible, (float)nMasternodePayment/COIN); return false; } std::string CMasternodeBlockPayees::GetRequiredPaymentsString() { LOCK(cs_vecPayees); std::string strRequiredPayments = "Unknown"; BOOST_FOREACH(CMasternodePayee& payee, vecPayees) { CTxDestination address1; ExtractDestination(payee.GetPayee(), address1); CBitcoinAddress address2(address1); if (strRequiredPayments != "Unknown") { strRequiredPayments += ", " + address2.ToString() + ":" + boost::lexical_cast<std::string>(payee.GetVoteCount()); } else { strRequiredPayments = address2.ToString() + ":" + boost::lexical_cast<std::string>(payee.GetVoteCount()); } } return strRequiredPayments; } std::string CMasternodePayments::GetRequiredPaymentsString(int nBlockHeight) { LOCK(cs_mapMasternodeBlocks); if(mapMasternodeBlocks.count(nBlockHeight)){ return mapMasternodeBlocks[nBlockHeight].GetRequiredPaymentsString(); } return "Unknown"; } bool CMasternodePayments::IsTransactionValid(const CTransaction& txNew, int nBlockHeight) { LOCK(cs_mapMasternodeBlocks); if(mapMasternodeBlocks.count(nBlockHeight)){ return mapMasternodeBlocks[nBlockHeight].IsTransactionValid(txNew); } return true; } void CMasternodePayments::CheckAndRemove() { if(!masternodeSync.IsBlockchainSynced()) return; LOCK2(cs_mapMasternodeBlocks, cs_mapMasternodePaymentVotes); int nLimit = GetStorageLimit(); std::map<uint256, CMasternodePaymentVote>::iterator it = mapMasternodePaymentVotes.begin(); while(it != mapMasternodePaymentVotes.end()) { CMasternodePaymentVote vote = (*it).second; if(nCachedBlockHeight - vote.nBlockHeight > nLimit) { LogPrint("mnpayments", "CMasternodePayments::CheckAndRemove -- Removing old Masternode payment: nBlockHeight=%d\n", vote.nBlockHeight); mapMasternodePaymentVotes.erase(it++); mapMasternodeBlocks.erase(vote.nBlockHeight); } else { ++it; } } LogPrintf("CMasternodePayments::CheckAndRemove -- %s\n", ToString()); } bool CMasternodePaymentVote::IsValid(CNode* pnode, int nValidationHeight, std::string& strError, CConnman& connman) { masternode_info_t mnInfo; if(!mnodeman.GetMasternodeInfo(vinMasternode.prevout, mnInfo)) { strError = strprintf("Unknown Masternode: prevout=%s", vinMasternode.prevout.ToStringShort()); // Only ask if we are already synced and still have no idea about that Masternode if(masternodeSync.IsMasternodeListSynced()) { mnodeman.AskForMN(pnode, vinMasternode.prevout, connman); } return false; } int nMinRequiredProtocol; if(nBlockHeight >= nValidationHeight) { // new votes must comply SPORK_10_MASTERNODE_PAY_UPDATED_NODES rules nMinRequiredProtocol = mnpayments.GetMinMasternodePaymentsProto(); } else { // allow non-updated masternodes for old blocks nMinRequiredProtocol = MIN_MASTERNODE_PAYMENT_PROTO_VERSION_1; } if(mnInfo.nProtocolVersion < nMinRequiredProtocol) { strError = strprintf("Masternode protocol is too old: nProtocolVersion=%d, nMinRequiredProtocol=%d", mnInfo.nProtocolVersion, nMinRequiredProtocol); return false; } // Only masternodes should try to check masternode rank for old votes - they need to pick the right winner for future blocks. // Regular clients (miners included) need to verify masternode rank for future block votes only. if(!fMasterNode && nBlockHeight < nValidationHeight) return true; int nRank; if(!mnodeman.GetMasternodeRank(vinMasternode.prevout, nRank, nBlockHeight - 101, nMinRequiredProtocol)) { LogPrint("mnpayments", "CMasternodePaymentVote::IsValid -- Can't calculate rank for masternode %s\n", vinMasternode.prevout.ToStringShort()); return false; } if(nRank > MNPAYMENTS_SIGNATURES_TOTAL) { // It's common to have masternodes mistakenly think they are in the top 10 // We don't want to print all of these messages in normal mode, debug mode should print though strError = strprintf("Masternode is not in the top %d (%d)", MNPAYMENTS_SIGNATURES_TOTAL, nRank); // Only ban for new mnw which is out of bounds, for old mnw MN list itself might be way too much off if(nRank > MNPAYMENTS_SIGNATURES_TOTAL*2 && nBlockHeight > nValidationHeight) { strError = strprintf("Masternode is not in the top %d (%d)", MNPAYMENTS_SIGNATURES_TOTAL*2, nRank); LogPrintf("CMasternodePaymentVote::IsValid -- Error: %s\n", strError); Misbehaving(pnode->GetId(), 20); } // Still invalid however return false; } return true; } bool CMasternodePayments::ProcessBlock(int nBlockHeight, CConnman& connman) { // DETERMINE IF WE SHOULD BE VOTING FOR THE NEXT PAYEE if(fLiteMode || !fMasterNode) return false; // We have little chances to pick the right winner if winners list is out of sync // but we have no choice, so we'll try. However it doesn't make sense to even try to do so // if we have not enough data about masternodes. if(!masternodeSync.IsMasternodeListSynced()) return false; int nRank; if (!mnodeman.GetMasternodeRank(activeMasternode.outpoint, nRank, nBlockHeight - 101, GetMinMasternodePaymentsProto())) { LogPrint("mnpayments", "CMasternodePayments::ProcessBlock -- Unknown Masternode\n"); return false; } if (nRank > MNPAYMENTS_SIGNATURES_TOTAL) { LogPrint("mnpayments", "CMasternodePayments::ProcessBlock -- Masternode not in the top %d (%d)\n", MNPAYMENTS_SIGNATURES_TOTAL, nRank); return false; } // LOCATE THE NEXT MASTERNODE WHICH SHOULD BE PAID LogPrintf("CMasternodePayments::ProcessBlock -- Start: nBlockHeight=%d, masternode=%s\n", nBlockHeight, activeMasternode.outpoint.ToStringShort()); // pay to the oldest MN that still had no payment but its input is old enough and it was active long enough int nCount = 0; masternode_info_t mnInfo; if (!mnodeman.GetNextMasternodeInQueueForPayment(nBlockHeight, true, nCount, mnInfo)) { LogPrintf("CMasternodePayments::ProcessBlock -- ERROR: Failed to find masternode to pay\n"); return false; } LogPrintf("CMasternodePayments::ProcessBlock -- Masternode found by GetNextMasternodeInQueueForPayment(): %s\n", mnInfo.vin.prevout.ToStringShort()); CScript payee = GetScriptForDestination(mnInfo.pubKeyCollateralAddress.GetID()); CMasternodePaymentVote voteNew(activeMasternode.outpoint, nBlockHeight, payee); CTxDestination address1; ExtractDestination(payee, address1); CBitcoinAddress address2(address1); LogPrintf("CMasternodePayments::ProcessBlock -- vote: payee=%s, nBlockHeight=%d\n", address2.ToString(), nBlockHeight); // SIGN MESSAGE TO NETWORK WITH OUR MASTERNODE KEYS LogPrintf("CMasternodePayments::ProcessBlock -- Signing vote\n"); if (voteNew.Sign()) { LogPrintf("CMasternodePayments::ProcessBlock -- AddPaymentVote()\n"); if (AddPaymentVote(voteNew)) { voteNew.Relay(connman); return true; } } return false; } void CMasternodePayments::CheckPreviousBlockVotes(int nPrevBlockHeight) { if (!masternodeSync.IsWinnersListSynced()) return; std::string debugStr; debugStr += strprintf("CMasternodePayments::CheckPreviousBlockVotes -- nPrevBlockHeight=%d, expected voting MNs:\n", nPrevBlockHeight); CMasternodeMan::rank_pair_vec_t mns; if (!mnodeman.GetMasternodeRanks(mns, nPrevBlockHeight - 101, GetMinMasternodePaymentsProto())) { debugStr += "CMasternodePayments::CheckPreviousBlockVotes -- GetMasternodeRanks failed\n"; LogPrint("mnpayments", "%s", debugStr); return; } LOCK2(cs_mapMasternodeBlocks, cs_mapMasternodePaymentVotes); for (int i = 0; i < MNPAYMENTS_SIGNATURES_TOTAL && i < (int)mns.size(); i++) { auto mn = mns[i]; CScript payee; bool found = false; if (mapMasternodeBlocks.count(nPrevBlockHeight)) { for (auto &p : mapMasternodeBlocks[nPrevBlockHeight].vecPayees) { for (auto &voteHash : p.GetVoteHashes()) { if (!mapMasternodePaymentVotes.count(voteHash)) { debugStr += strprintf("CMasternodePayments::CheckPreviousBlockVotes -- could not find vote %s\n", voteHash.ToString()); continue; } auto vote = mapMasternodePaymentVotes[voteHash]; if (vote.vinMasternode.prevout == mn.second.vin.prevout) { payee = vote.payee; found = true; break; } } } } if (!found) { debugStr += strprintf("CMasternodePayments::CheckPreviousBlockVotes -- %s - no vote received\n", mn.second.vin.prevout.ToStringShort()); mapMasternodesDidNotVote[mn.second.vin.prevout]++; continue; } CTxDestination address1; ExtractDestination(payee, address1); CBitcoinAddress address2(address1); debugStr += strprintf("CMasternodePayments::CheckPreviousBlockVotes -- %s - voted for %s\n", mn.second.vin.prevout.ToStringShort(), address2.ToString()); } debugStr += "CMasternodePayments::CheckPreviousBlockVotes -- Masternodes which missed a vote in the past:\n"; for (auto it : mapMasternodesDidNotVote) { debugStr += strprintf("CMasternodePayments::CheckPreviousBlockVotes -- %s: %d\n", it.first.ToStringShort(), it.second); } LogPrint("mnpayments", "%s", debugStr); } void CMasternodePaymentVote::Relay(CConnman& connman) { // Do not relay until fully synced if(!masternodeSync.IsSynced()) { LogPrint("mnpayments", "CMasternodePayments::Relay -- won't relay until fully synced\n"); return; } CInv inv(MSG_MASTERNODE_PAYMENT_VOTE, GetHash()); connman.RelayInv(inv); } bool CMasternodePaymentVote::CheckSignature(const CPubKey& pubKeyMasternode, int nValidationHeight, int &nDos) { // do not ban by default nDos = 0; std::string strMessage = vinMasternode.prevout.ToStringShort() + boost::lexical_cast<std::string>(nBlockHeight) + ScriptToAsmStr(payee); std::string strError = ""; if (!CMessageSigner::VerifyMessage(pubKeyMasternode, vchSig, strMessage, strError)) { // Only ban for future block vote when we are already synced. // Otherwise it could be the case when MN which signed this vote is using another key now // and we have no idea about the old one. if(masternodeSync.IsMasternodeListSynced() && nBlockHeight > nValidationHeight) { nDos = 20; } return error("CMasternodePaymentVote::CheckSignature -- Got bad Masternode payment signature, masternode=%s, error: %s", vinMasternode.prevout.ToStringShort().c_str(), strError); } return true; } std::string CMasternodePaymentVote::ToString() const { std::ostringstream info; info << vinMasternode.prevout.ToStringShort() << ", " << nBlockHeight << ", " << ScriptToAsmStr(payee) << ", " << (int)vchSig.size(); return info.str(); } // Send only votes for future blocks, node should request every other missing payment block individually void CMasternodePayments::Sync(CNode* pnode, CConnman& connman) { LOCK(cs_mapMasternodeBlocks); if(!masternodeSync.IsWinnersListSynced()) return; int nInvCount = 0; for(int h = nCachedBlockHeight; h < nCachedBlockHeight + 20; h++) { if(mapMasternodeBlocks.count(h)) { BOOST_FOREACH(CMasternodePayee& payee, mapMasternodeBlocks[h].vecPayees) { std::vector<uint256> vecVoteHashes = payee.GetVoteHashes(); BOOST_FOREACH(uint256& hash, vecVoteHashes) { if(!HasVerifiedPaymentVote(hash)) continue; pnode->PushInventory(CInv(MSG_MASTERNODE_PAYMENT_VOTE, hash)); nInvCount++; } } } } LogPrintf("CMasternodePayments::Sync -- Sent %d votes to peer %d\n", nInvCount, pnode->id); connman.PushMessage(pnode, NetMsgType::SYNCSTATUSCOUNT, MASTERNODE_SYNC_MNW, nInvCount); } // Request low data/unknown payment blocks in batches directly from some node instead of/after preliminary Sync. void CMasternodePayments::RequestLowDataPaymentBlocks(CNode* pnode, CConnman& connman) { if(!masternodeSync.IsMasternodeListSynced()) return; LOCK2(cs_main, cs_mapMasternodeBlocks); std::vector<CInv> vToFetch; int nLimit = GetStorageLimit(); const CBlockIndex *pindex = chainActive.Tip(); while(nCachedBlockHeight - pindex->nHeight < nLimit) { if(!mapMasternodeBlocks.count(pindex->nHeight)) { // We have no idea about this block height, let's ask vToFetch.push_back(CInv(MSG_MASTERNODE_PAYMENT_BLOCK, pindex->GetBlockHash())); // We should not violate GETDATA rules if(vToFetch.size() == MAX_INV_SZ) { LogPrintf("CMasternodePayments::SyncLowDataPaymentBlocks -- asking peer %d for %d blocks\n", pnode->id, MAX_INV_SZ); connman.PushMessage(pnode, NetMsgType::GETDATA, vToFetch); // Start filling new batch vToFetch.clear(); } } if(!pindex->pprev) break; pindex = pindex->pprev; } std::map<int, CMasternodeBlockPayees>::iterator it = mapMasternodeBlocks.begin(); while(it != mapMasternodeBlocks.end()) { int nTotalVotes = 0; bool fFound = false; BOOST_FOREACH(CMasternodePayee& payee, it->second.vecPayees) { if(payee.GetVoteCount() >= MNPAYMENTS_SIGNATURES_REQUIRED) { fFound = true; break; } nTotalVotes += payee.GetVoteCount(); } // A clear winner (MNPAYMENTS_SIGNATURES_REQUIRED+ votes) was found // or no clear winner was found but there are at least avg number of votes if(fFound || nTotalVotes >= (MNPAYMENTS_SIGNATURES_TOTAL + MNPAYMENTS_SIGNATURES_REQUIRED)/2) { // so just move to the next block ++it; continue; } // DEBUG DBG ( // Let's see why this failed BOOST_FOREACH(CMasternodePayee& payee, it->second.vecPayees) { CTxDestination address1; ExtractDestination(payee.GetPayee(), address1); CBitcoinAddress address2(address1); printf("payee %s votes %d\n", address2.ToString().c_str(), payee.GetVoteCount()); } printf("block %d votes total %d\n", it->first, nTotalVotes); ) // END DEBUG // Low data block found, let's try to sync it uint256 hash; if(GetBlockHash(hash, it->first)) { vToFetch.push_back(CInv(MSG_MASTERNODE_PAYMENT_BLOCK, hash)); } // We should not violate GETDATA rules if(vToFetch.size() == MAX_INV_SZ) { LogPrintf("CMasternodePayments::SyncLowDataPaymentBlocks -- asking peer %d for %d payment blocks\n", pnode->id, MAX_INV_SZ); connman.PushMessage(pnode, NetMsgType::GETDATA, vToFetch); // Start filling new batch vToFetch.clear(); } ++it; } // Ask for the rest of it if(!vToFetch.empty()) { LogPrintf("CMasternodePayments::SyncLowDataPaymentBlocks -- asking peer %d for %d payment blocks\n", pnode->id, vToFetch.size()); connman.PushMessage(pnode, NetMsgType::GETDATA, vToFetch); } } std::string CMasternodePayments::ToString() const { std::ostringstream info; info << "Votes: " << (int)mapMasternodePaymentVotes.size() << ", Blocks: " << (int)mapMasternodeBlocks.size(); return info.str(); } bool CMasternodePayments::IsEnoughData() { float nAverageVotes = (MNPAYMENTS_SIGNATURES_TOTAL + MNPAYMENTS_SIGNATURES_REQUIRED) / 2; int nStorageLimit = GetStorageLimit(); return GetBlockCount() > nStorageLimit && GetVoteCount() > nStorageLimit * nAverageVotes; } int CMasternodePayments::GetStorageLimit() { return std::max(int(mnodeman.size() * nStorageCoeff), nMinBlocksToStore); } void CMasternodePayments::UpdatedBlockTip(const CBlockIndex *pindex, CConnman& connman) { if(!pindex) return; nCachedBlockHeight = pindex->nHeight; LogPrint("mnpayments", "CMasternodePayments::UpdatedBlockTip -- nCachedBlockHeight=%d\n", nCachedBlockHeight); int nFutureBlock = nCachedBlockHeight + 10; CheckPreviousBlockVotes(nFutureBlock - 1); ProcessBlock(nFutureBlock, connman); }
[ "glordcryptex@yandex.com" ]
glordcryptex@yandex.com
8a2a5693784592fc47b9cac7a38e5f015781261f
9c8b549af87c4d2b4648b454769f2c111199c5f6
/liblrc/lyrics.h
56c07e2015f8927f21c2e7eb246367ec3c7dc558
[ "MIT" ]
permissive
ywh233/LRC-Tools
bc4e800bd0789c166310b84503dd9832f36447d5
1fc3872320cd449933bffefc6527928262ee0629
refs/heads/master
2021-09-06T23:09:03.240811
2018-02-13T07:52:30
2018-02-13T07:52:30
17,500,048
1
0
null
null
null
null
UTF-8
C++
false
false
1,944
h
//****************************************** // Author : Yuwei Huang // Created On : Thu Feb 08 2018 // File : lyrics.h //****************************************** #ifndef LIBLRC_LYRICS_H #define LIBLRC_LYRICS_H #include <cstdint> #include <string> #include <vector> namespace lrc { class Lyrics { public: struct Metadata { std::string artist; std::string album; std::string title; std::string lyricsWriter; std::string fileCreator; int32_t adjustment; // in milliseconds, + shifts time up, - shifts down. }; static const int32_t kEndTimeNever; struct LyricLine { int32_t start_time; // in milliseconds. // kEndTimeNever if it is at the end of the song. int32_t end_time; std::string lyric; }; using ConstLyricIterator = std::vector<LyricLine>::const_iterator; // Lyric duration is not required and will be automatically filled. // Please DO NOT include offset adjustment in LyricLine. They will be adjusted // by this class. Lyrics(const Metadata& metadata, std::vector<LyricLine>&& lyrics); ~Lyrics(); const Metadata& GetMetadata() const; // Returns the LyricLine at the given offset. Returns a null LyricLine (all // fields are empty) if offset < 0 or offset >= kEndTimeNever. // Random position lookup cost is O(log(n)); lookup with linearly increasing // offset has a cost of O(1) for each lookup. const LyricLine& LyricAt(int32_t offset); // Returns the lyric iterator at the given offset. Caller can use it to query // lyrics before or after the current lyric. Returns IteratorEnd if offset < 0 // or offset >= kEndTimeNever. ConstLyricIterator LyricIteratorAt(int32_t offset); ConstLyricIterator IteratorBegin() const; ConstLyricIterator IteratorEnd() const; private: Metadata metadata_; std::vector<LyricLine> lyrics_; std::vector<LyricLine>::iterator current_lyric_; }; } // namespace lrc #endif // LIBLRC_LYRICS_H
[ "yuwaiw@gmail.com" ]
yuwaiw@gmail.com
5876542a94571933402642720d1d38f2da5af3f5
156d4f5c53d28d473083c0e8a3f4048c82365ded
/CPP/OSIP/Pipeline/inlet.hpp
461b36244cc722b7f698e4d013b45b3507014655
[]
no_license
amcelroy/Lepton
ee4ec9b03ee90716bc64c9c78799f88d52272123
f2efb60c3a96afbdff9bb9007a18ce4e26ea250b
refs/heads/master
2021-09-05T23:37:11.587886
2018-01-31T17:58:54
2018-01-31T17:58:54
115,148,552
0
0
null
null
null
null
UTF-8
C++
false
false
1,844
hpp
#ifndef INLET_H #define INLET_H #include <vector> #include <queue> #include "payload.hpp" #include <mutex> #include "boost/signals2.hpp" using namespace std; namespace OSIP { template<class I> class Inlet { private: boost::signals2::signal<void(int)> sig_ElementsInQueue; /** * @brief _InQueue Input queue to write / read data from */ queue<Payload<I>> _InQueue; /** * @brief _QueueLock Locks the queue when reading or writing data */ mutex _QueueLock; public: Inlet(){ } int getItemsInInlet() { return _InQueue.size(); } bool isEmpty(){ return _InQueue.empty(); } /** * @brief writeData Write data to the Inlet queue * @param data Data to be written * @return True if data is successfully written */ void writeData(Payload<I> data){ lock_guard<mutex> lock(_QueueLock); this->_InQueue.push(data); } /** * @brief readData Read data from the Inlet queue * @param data Data to be read, allocated by the caller * @return True if the data is successfully read */ Payload<I> readData(){ lock_guard<mutex> lock(_QueueLock); if(!_InQueue.empty()){ Payload<I> dataOut = _InQueue.front(); _InQueue.pop(); return dataOut; } return Payload<I>(); } /** * @brief notifyQueueSize Adds a subscriber that gets notified about the size of elements in the Inlet queue * @param sub Subscriber */ void subscribeQueueSize(const boost::signals2::signal<void(int)> &sub) { sig_ElementsInQueue.connect(sub); } }; } #endif // INLET_H
[ "mcelroy.austin@gmail.com" ]
mcelroy.austin@gmail.com
fc5a408be3c8cda5657b5bc1b9db67124a4fcedc
ba9322f7db02d797f6984298d892f74768193dcf
/emr/src/model/CreateClusterHostGroupResult.cc
d20ff2884111997388daae13ecbfb3b1bc30e717
[ "Apache-2.0" ]
permissive
sdk-team/aliyun-openapi-cpp-sdk
e27f91996b3bad9226c86f74475b5a1a91806861
a27fc0000a2b061cd10df09cbe4fff9db4a7c707
refs/heads/master
2022-08-21T18:25:53.080066
2022-07-25T10:01:05
2022-07-25T10:01:05
183,356,893
3
0
null
2019-04-25T04:34:29
2019-04-25T04:34:28
null
UTF-8
C++
false
false
1,612
cc
/* * Copyright 2009-2017 Alibaba Cloud 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 <alibabacloud/emr/model/CreateClusterHostGroupResult.h> #include <json/json.h> using namespace AlibabaCloud::Emr; using namespace AlibabaCloud::Emr::Model; CreateClusterHostGroupResult::CreateClusterHostGroupResult() : ServiceResult() {} CreateClusterHostGroupResult::CreateClusterHostGroupResult(const std::string &payload) : ServiceResult() { parse(payload); } CreateClusterHostGroupResult::~CreateClusterHostGroupResult() {} void CreateClusterHostGroupResult::parse(const std::string &payload) { Json::Reader reader; Json::Value value; reader.parse(payload, value); setRequestId(value["RequestId"].asString()); if(!value["ClusterId"].isNull()) clusterId_ = value["ClusterId"].asString(); if(!value["HostGroupId"].isNull()) hostGroupId_ = value["HostGroupId"].asString(); } std::string CreateClusterHostGroupResult::getHostGroupId()const { return hostGroupId_; } std::string CreateClusterHostGroupResult::getClusterId()const { return clusterId_; }
[ "haowei.yao@alibaba-inc.com" ]
haowei.yao@alibaba-inc.com
fd344163e726ce275f53e224be30c10aaac91bd3
30086c6f0eaac5e02115b5827a31254fb042d218
/GF5000_66/view/modifyadtablewidget.cpp
4435e2c9585773b9f420db68a6995ac16eda0008
[]
no_license
qinjiexiansheng/qinQtproject
364820bcd291edbdacbe2a775d8bafd4ec3599bd
06c5d89c7ff110a10aa075b4bcdc3934d9f87a53
refs/heads/master
2022-12-30T15:00:54.491908
2020-10-17T08:02:50
2020-10-17T08:02:50
304,822,226
0
0
null
null
null
null
UTF-8
C++
false
false
7,123
cpp
#include "modifyadtablewidget.h" ModifyAdTableWidget::ModifyAdTableWidget(QWidget *parent) : QWidget(parent){ mSatData = SatData::initance(); mModel = mSatData->getModel(); mView = new QTableView(this);//表格窗口 mView->horizontalHeader()->setResizeMode(QHeaderView::Stretch);//行表头均分 mView->verticalHeader()->hide();//竖表头隐藏 mView->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);//水平滑条隐藏 mView->installEventFilter(this); mView->setModel(mModel); QVBoxLayout *nLayout = new QVBoxLayout; int nGear = mSatData->getGearMode()==SatData::GEARONE?1:2; mSatTitleBar = new SatTitleBar(QString(tr("ModifyAdTable[%1]")).arg(nGear),this); nLayout->addWidget(mSatTitleBar); nLayout->addWidget(mView); nLayout->setMargin(1);//外边距为0 nLayout->setSpacing(0); this->setLayout(nLayout); this->setFixedSize(250,480);//设置窗口大小 this->setWindowFlags(Qt::FramelessWindowHint | Qt::CustomizeWindowHint | Qt::Window); mView->setCurrentIndex(mModel->index(0,1));//初始焦点在第一行第二列 SatControl *nSatControl = SatControl::initance(); connect(this,SIGNAL(operationSignal(int,QString)),nSatControl,SLOT(doService(int,QString))); } bool ModifyAdTableWidget::eventFilter(QObject *obj, QEvent *event){ if(obj == mView && event->type() == QEvent::KeyPress){ QKeyEvent* nKey = (QKeyEvent *)event; switch (nKey->key()){ case KEY_19: focusPrevious();//前一焦点 break; case KEY_20: focusNext();//下一焦点 break; case KEY_18://打开键盘修改数据 { QString nStr = mView->currentIndex().data().toString();//获取当前项的数据 HexadecimalKeyboard* nDialog = new HexadecimalKeyboard(nStr,this);//打开十六进制键盘 nDialog->move(80,80); if(nDialog->exec()){ if(nStr.isEmpty()){ nStr = "0"; } mView->model()->setData(mView->currentIndex(),nStr); } } break; case KEY_25://返回键,将关闭窗口 { emit operationSignal(Save_Model_Data,NULL); this->close();//关闭窗口 } default: break; } return true;//拦截其他按键,不需要上层处理 } return QWidget::eventFilter(obj,event); } void ModifyAdTableWidget::focusNext(){//下一焦点 int i = mView->currentIndex().row();//当前的行 int j = mView->currentIndex().column();//当前的列,其实就是第二列,因为第一列不列入焦点处理 i++; if(i >= mModel->rowCount()){ i = mModel->rowCount()-1;//不做循环 } mView->setCurrentIndex(mModel->index(i,j));//设置焦点 } void ModifyAdTableWidget::focusPrevious(){//前一焦点,同上 int i = mView->currentIndex().row(); int j = mView->currentIndex().column(); i--; if(i < 0){ i = 0; } mView->setCurrentIndex(mModel->index(i,j)); } void ModifyAdTableWidget::showEvent(QShowEvent *se){ mView->setCurrentIndex(mModel->index(0,1)); int nGear = mSatData->getGearMode()==SatData::GEARONE?1:2; mSatTitleBar->setTitle(QString(tr("ModifyAdTable[%1]")).arg(nGear)); QWidget::showEvent(se); } void ModifyAdTableWidget::paintEvent(QPaintEvent *event){ QPainter painter(this); QPen nPen; nPen.setColor(QColor("#888888")); nPen.setWidth(1); painter.setPen(nPen); painter.drawLine(0,0,0,height());//画左边线 painter.drawLine(0,0,width(),0);//画上线 painter.drawLine(width()-1,0,width()-1,height()-1);//画右线 painter.drawLine(0,height()-1,width()-1,height()-1);//画下线 QWidget::paintEvent(event); } /*================================================================================ ================================================================================*/ ShowAdTableWidget::ShowAdTableWidget(QWidget *parent) : QWidget(parent){ mView = new QTextBrowser(this);//文本浏览组件 mView->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);//水平滑条隐藏 mView->installEventFilter(this); QVBoxLayout *nLayout = new QVBoxLayout; mSatData = SatData::initance(); int nGear = mSatData->getGearMode()==SatData::GEARONE?1:2; mSatTitleBar = new SatTitleBar(this); mSatTitleBar->setTitle(QString(tr("ShowADTable[%1]")).arg(nGear)); nLayout->addWidget(mSatTitleBar); nLayout->addWidget(mView); nLayout->setMargin(1);//布局边框 nLayout->setSpacing(0); this->setLayout(nLayout); this->setFixedSize(250,480);//窗口大小 this->setWindowFlags(Qt::FramelessWindowHint | Qt::CustomizeWindowHint | Qt::Window); loadFile(); } bool ShowAdTableWidget::eventFilter(QObject *obj, QEvent *event){ if(obj == mView && event->type() == QEvent::KeyPress){ QKeyEvent* nKey = (QKeyEvent *)event; switch (nKey->key()){ case KEY_19: { QScrollBar *nBar = mView->verticalScrollBar(); nBar->setSliderPosition(nBar->value()-10);//滑块上移 } break; case KEY_20: { QScrollBar *nBar = mView->verticalScrollBar(); nBar->setSliderPosition(nBar->value()+10);//滑块下移 } break; case KEY_25: case KEY_18: this->close();//窗口关闭 break; default: break; } return true;//其他按键不需要上层处理 } return QWidget::eventFilter(obj,event); } void ShowAdTableWidget::loadFile(){ QString nFileStr = mSatData->getTmpAdFile(); if(nFileStr.isEmpty()){ nFileStr = QString("%1%2").arg(COF_DIR).arg(QString(TEMP_AD_TABLE).arg(1)); } QFile nFile(nFileStr); if(!nFile.open(QIODevice::ReadOnly | QIODevice::Text)){//打开文件 return ; } QTextStream in(&nFile); QString nAllStr = in.readAll();//读取全部 mView->clear(); mView->setText(nAllStr); nFile.close(); int nGear = mSatData->getGearMode()==SatData::GEARONE?1:2; mSatTitleBar->setTitle(QString(tr("ShowADTable[%1]")).arg(nGear)); } void ShowAdTableWidget::showEvent(QShowEvent *event){ loadFile(); QWidget::showEvent(event); } void ShowAdTableWidget::paintEvent(QPaintEvent *event){ QPainter painter(this); QPen nPen; nPen.setColor(QColor("#888888")); nPen.setWidth(1); painter.setPen(nPen); painter.drawLine(0,0,0,height());//画左边线 painter.drawLine(0,0,width(),0);//画上线 painter.drawLine(width()-1,0,width()-1,height()-1);//画右线 painter.drawLine(0,height()-1,width()-1,height()-1);//画下线 QWidget::paintEvent(event); }
[ "1042034984@qq.com" ]
1042034984@qq.com
c8baa0d4d6cefd5e15901554bb28093d7278455d
5387d1bc0bfd550c5aaa19f02928c58cd535003e
/ChatManager/log/winlog.h
e000fb0e117ac5c8bd3ff760e8d14d001ce9ee78
[]
no_license
StrokeAce/YunKa826
90e96f5627e7c70c895aa89c7256919d66fd8c6f
efa3cddd7b0347846a7156a627c452447e1b92b6
refs/heads/master
2020-07-03T19:03:18.098740
2017-03-13T03:10:56
2017-03-13T03:10:56
66,622,447
0
2
null
null
null
null
GB18030
C++
false
false
4,021
h
/************************************************************************ Submodule : log.h Depict : Write log Interface Language : ANSI C++ Version : 3.0 Compile : make Compat : Linux/Windows Editor : yanyg Time : 2007 07 15 ************************************************************************/ //log.h: interface for the CLog class. /************************************************************************ 使 用 说 明 1. 确保使用前初始化; 2. 可自动创建任意多级目录且不会更改程序工作目录; 2. 该日志类已经定义一份名为g_WriteLog实体对象; 3. 该类支持C/C++两种输入;例如: int iExample(19831107); string strExample("19831107"); g_WriteLog.WriteLog( C_LOG_SYSNOTICE , "日志类作者是闫永刚.以下是C用法案例:\r\n"); g_WriteLog.WriteLog( C_LOG_SYSNOTICE , "i = %d ; str = %s .\r\n" , iExample , strExample.c_str() ); g_WriteLog<<CPP_LOG_SYSNOTICE<<"日志类作者是闫永刚."; g_WriteLog<<CPP_LOG_SYSNOTICE<<"i = "<<iExample<<"; str = "<<strExample<<CPP_LOG_END; 注 : 必须以CPP_LOG_END结尾,否则死锁!!! 4. 经测试该类写日志效率为 200000条/秒(C++流式输入) 和 125000条/秒(C式输入) 测试信息: 系统配置 : CPU 2.4HZ / MEM 512M 每条字节 : 68Byte 操作系统 : Linux Redhat9 ************************************************************************/ #ifndef __WRITELOG_H_ #define __WRITELOG_H_ #include "utils/mutex.h" #include "chat_common/comenum.h" #include "chat_common/comdef.h" #include <string> #include <fstream> #define CPP_LOG_NONE CLogLevel<C_LOG_NONE>() // no any log will be write #define CPP_LOG_SYSNOTICE CLogLevel<C_LOG_SYSNOTICE>() // system informational notices #define CPP_LOG_FATAL CLogLevel<C_LOG_FATAL>() // fatal errors #define CPP_LOG_ERROR CLogLevel<C_LOG_ERROR>() // error! #define CPP_LOG_WARNING CLogLevel<C_LOG_WARNING>() // exceptional events #define CPP_LOG_NOTICE CLogLevel<C_LOG_NOTICE>() // informational notices #define CPP_LOG_DEBUG CLogLevel<C_LOG_DEBUG>() // full debugging #define CPP_LOG_TRACE CLogLevel<C_LOG_TRACE>() // program tracing #define CPP_LOG_ALL CLogLevel<C_LOG_ALL>() // everything #define CPP_LOG_END CLogUnLockType() // unLock the log stream #define CPP_LOG_FLUSH_END CLogFlushUnLockType() // flush and unLock the log stream template<int ilevel>struct CLogLevel{}; struct CLogUnLockType{}; struct CLogFlushUnLockType{}; class CLog { public: CLog():m_bWrite(false),m_iLogDay(-1),m_iFlush(C_LOG_ALL){} void SetLogLevel( unsigned int uiLogLevel ) { m_uiLogLevel = uiLogLevel <= C_LOG_ALL ? uiLogLevel : C_LOG_ALL; } bool InitLog( const std::string& strLogPath , const std::string& strLogName , unsigned int uiLogLevel ); void WriteLog( unsigned int uiLogLevel , const char* fmt , ... ); void WriteStr( const char* strerror ,unsigned int uiLogLevel); template< typename T > CLog& operator<<( const T& t ) { if(m_bWrite)m_LogStream<<t; return *this; } CLog& operator<<( const CLogUnLockType ) { return m_LogLock.Unlock(), *this; } CLog& operator<<( const CLogFlushUnLockType ) { return m_LogStream.flush(), m_LogLock.Unlock(), *this; } template<int iLevel> CLog& operator<<( const CLogLevel<iLevel> ) { return m_LogLock.Lock(),MakeLogTag(iLevel),*this; } private: void MakeLogTag(const unsigned int iLevel ); bool CreateDir( ); private: bool m_bWrite; unsigned int m_uiLogLevel; //日志级别 int m_iLogDay; //日期(天):每天更新一次 int m_iFlush; //刷新级别 std::string m_strLogPath; //日志路径 std::string m_strlogName; //日志名 std::string m_strAllName; //日志全名 : path+(year+month+day)+name std::string m_strBakeName; //第二天移动第一天日志到bake std::ofstream m_LogStream; //日志文件流 MMutex m_LogLock; //Linux日志文件锁 }; extern DLL_EXPORT CLog g_WriteLog, g_VisitLog; extern DLL_EXPORT int g_a; #endif
[ "gaowenbo123456tv@163.com" ]
gaowenbo123456tv@163.com
0cd89bc2c275755a97aeb691a6a3cbb98d0d7286
c279a2fcb56de70f5cac2c8e890f155e177e676e
/Source/Plugins/SubsystemPlugins/BladeGraphics/source/interface_imp/Shadows/DefaultShadowTechnique.h
8b38ecdd6ce97a95013d0df7b4b2e993c3cebac7
[ "MIT" ]
permissive
crazii/blade
b4abacdf36677e41382e95f0eec27d3d3baa20b5
7670a6bdf48b91c5e2dd2acd09fb644587407f03
refs/heads/master
2021-06-06T08:41:55.603532
2021-05-20T11:50:11
2021-05-20T11:50:11
160,147,322
161
34
NOASSERTION
2019-01-18T03:36:11
2018-12-03T07:07:28
C++
UTF-8
C++
false
false
3,871
h
/******************************************************************** created: 2017/06/21 filename: DefaultShadowTechnique.cc author: Crazii purpose: *********************************************************************/ #ifndef __Blade_DefaultShadowTechnique_h__ #define __Blade_DefaultShadowTechnique_h__ #include "IShadowTechnique.h" #include <math/Matrix44.h> #include <math/AxisAlignedBox.h> namespace Blade { class DefaultShadowTechnique : public IShadowTechnique, public Allocatable { public: DefaultShadowTechnique() {} ~DefaultShadowTechnique() {} /** @brief */ virtual void setupCulling(Camera* lightCam, const ICamera* sceneCam, const ILight* light, const PointList& pointsWS) { const Vector3& dir = light->getDirection(); //position doesn't matter since it used to calc bounding range, which is relative value Matrix44 lightView = Matrix44::generateViewMatrix(POINT3::ZERO, POINT3::ZERO + dir /*make point explict, not a dir*/, sceneCam->getLookAtDirection()); AABB boundingLS; for (size_t j = 0; j < pointsWS.size(); ++j) boundingLS.merge(pointsWS[j] * lightView); scalar w = boundingLS.getHalfSize().x * 2; scalar h = boundingLS.getHalfSize().y * 2; scalar z = boundingLS.getHalfSize().z * 2; Matrix44 invLightView = lightView.getInverse(); const POINT3 worldPos = boundingLS.getCenter()*invLightView; //clear fixed view projection lightCam->setViewMatrix(Matrix44::IDENTITY, false); lightCam->setProjectionMatrix(Matrix44::IDENTITY, false); //set view/projection matrix for culling: note that there are object behind the tight frustum casting shadows, so use a longer culling frustum lightCam->setOrthoMode(w, h); lightCam->setNearClipDistance((scalar)SHADOW_ORTHO_NEAR); lightCam->setFarClipDistance((scalar)SHADOW_CULLING_DISTANCE + z*0.5f + (scalar)SHADOW_ORTHO_NEAR); lightCam->setEyePosition(worldPos - dir*(scalar)SHADOW_CULLING_DISTANCE); lightCam->setRotation(static_cast<const Matrix33&>(invLightView)); lightCam->updateMatrix(); //override view projection matrix for rendering //lightCam->setViewMatrix(Matrix44::generateViewMatrix(worldPos - dir * (z*0.5f + (scalar)SHADOW_ORTHO_NEAR), static_cast<const Matrix33&>(invLightView)), true); //lightCam->setProjectionMatrix(Matrix44::generateOrthoProjectionMatrix(w, h, (scalar)SHADOW_ORTHO_NEAR, (scalar)SHADOW_ORTHO_NEAR + z), true); } /** @brief */ virtual void updateViewProjection(Camera* lightCam, Matrix44& depthMatrix, const ICamera* /*sceneCam*/, const ILight* light, const PointList& pointsWS) { ////view projection updated in setup culling, nothing to do. //update projection depth range so that depth clamp is not needed PointList points = pointsWS; const AABB& visibleSceneBounding = lightCam->getVisibleBounding(); if (!visibleSceneBounding.isNull()) IShadowTechnique::clipBounding(visibleSceneBounding, lightCam->getFrustum(), points); const Matrix44& lightView = lightCam->getViewMatrix(); AABB boundingLS; for (size_t j = 0; j < points.size(); ++j) boundingLS.merge(points[j] * lightView); scalar w = boundingLS.getHalfSize().x * 2; scalar h = boundingLS.getHalfSize().y * 2; scalar z = boundingLS.getHalfSize().z * 2; POINT3 pos = boundingLS.getCenter()*lightView.getInverse(); lightCam->setViewMatrix(Matrix44::generateViewMatrix(pos - light->getDirection() * (z*0.5f + (scalar)SHADOW_ORTHO_NEAR), lightCam->getRotation()), true); lightCam->setProjectionMatrix(Matrix44::generateOrthoProjectionMatrix(w, h, (scalar)SHADOW_ORTHO_NEAR, (scalar)SHADOW_ORTHO_NEAR + z), true); Matrix44 proj = lightCam->getProjectionMatrix(); depthMatrix = lightCam->getViewMatrix()*IGraphicsResourceManager::getSingleton().convertProjectionMatrix(proj);; } }; }//namespace Blade #endif//__Blade_DefaultShadowTechnique_h__
[ "xiaofeng.he@mihoyo.com" ]
xiaofeng.he@mihoyo.com
cd3bc566577bdef259d712ee418df8ecb59a9fa6
dcf8b9a8c0cd7a0cac742c7af9cc2d8cb06f7f69
/SymbolTable.h
704c34e615db2cca3ad2af21b5152ced498f9732
[]
no_license
saadabrar12/CSC512_HW4
a6dbbcbbbec2b0ef526c0d32f8b7a1c7df59e228
cea9eccecb8fa029668521b0b67301a1cb13c771
refs/heads/master
2022-11-30T07:58:42.747243
2020-08-06T01:01:43
2020-08-06T01:01:43
285,436,879
0
0
null
null
null
null
UTF-8
C++
false
false
585
h
#ifndef _SYMBOLTABLE_H #define _SYMBOLTABLE_H #include <string> #include <queue> #include "Variable.h" #include "Function.h" class SymbolTable { public: std::vector< std::pair<std::string, Variable*> > globalVariables; std::vector< std::pair<std::string, Function*> > functions; Function* curFunction; int lableCnt; int globalVarCnt; /*Used to keep track of number of global variables. In case of arrays, the size of the array is updated in this count*/ std::queue<Function*> functionQueue; SymbolTable() : lableCnt(0) , globalVarCnt(0) , curFunction(NULL) {} }; #endif
[ "saad6522@gmail.com" ]
saad6522@gmail.com
7dbd5d33f93ec9638f6fffe60ccb5419a8641c4f
6fe2aa21c7ec38f6789f3ff3eaa5c3efdc459fae
/Linux/51muduoBaseStudy/AsyncLogging.cpp
99f1de46526fde5bf45ddb30b3def7bb28684f47
[ "Apache-2.0" ]
permissive
ggwhsd/CPPStudy
192f83e9b8406b464b42ece656448e27895fd950
9661e231e1f9577bb85855c0ff1840f764c7b444
refs/heads/master
2023-06-29T10:49:50.984447
2023-05-12T13:45:24
2023-05-12T13:45:24
155,736,327
6
1
Apache-2.0
2023-06-14T22:32:46
2018-11-01T15:30:49
C++
UTF-8
C++
false
false
3,333
cpp
// Use of this source code is governed by a BSD-style license // that can be found in the License file. // // Author: Shuo Chen (chenshuo at chenshuo dot com) #include "AsyncLogging.h" #include "LogFile.h" #include "Timestamp.h" #include <stdio.h> using namespace muduo; AsyncLogging::AsyncLogging(const string& basename, off_t rollSize, int flushInterval) : flushInterval_(flushInterval), running_(false), basename_(basename), rollSize_(rollSize), thread_(std::bind(&AsyncLogging::threadFunc, this), "Logging"), latch_(1), mutex_(), cond_(mutex_), currentBuffer_(new Buffer), nextBuffer_(new Buffer), buffers_() { currentBuffer_->bzero(); nextBuffer_->bzero(); buffers_.reserve(16); } void AsyncLogging::append(const char* logline, int len) { muduo::MutexLockGuard lock(mutex_); if (currentBuffer_->avail() > len) { currentBuffer_->append(logline, len); } else { buffers_.push_back(std::move(currentBuffer_)); if (nextBuffer_) { currentBuffer_ = std::move(nextBuffer_); } else { currentBuffer_.reset(new Buffer); // Rarely happens } currentBuffer_->append(logline, len); cond_.notify(); } } void AsyncLogging::threadFunc() { assert(running_ == true); latch_.countDown(); LogFile output(basename_, rollSize_, false); BufferPtr newBuffer1(new Buffer); BufferPtr newBuffer2(new Buffer); newBuffer1->bzero(); newBuffer2->bzero(); BufferVector buffersToWrite; buffersToWrite.reserve(16); while (running_) { assert(newBuffer1 && newBuffer1->length() == 0); assert(newBuffer2 && newBuffer2->length() == 0); assert(buffersToWrite.empty()); { muduo::MutexLockGuard lock(mutex_); if (buffers_.empty()) // unusual usage! { cond_.waitForSeconds(flushInterval_); } buffers_.push_back(std::move(currentBuffer_)); currentBuffer_ = std::move(newBuffer1); buffersToWrite.swap(buffers_); if (!nextBuffer_) { nextBuffer_ = std::move(newBuffer2); } } assert(!buffersToWrite.empty()); if (buffersToWrite.size() > 25) { char buf[256]; snprintf(buf, sizeof buf, "Dropped log messages at %s, %zd larger buffers\n", Timestamp::now().toFormattedString().c_str(), buffersToWrite.size()-2); fputs(buf, stderr); output.append(buf, static_cast<int>(strlen(buf))); buffersToWrite.erase(buffersToWrite.begin()+2, buffersToWrite.end()); } for (const auto& buffer : buffersToWrite) { // FIXME: use unbuffered stdio FILE ? or use ::writev ? output.append(buffer->data(), buffer->length()); } if (buffersToWrite.size() > 2) { // drop non-bzero-ed buffers, avoid trashing buffersToWrite.resize(2); } if (!newBuffer1) { assert(!buffersToWrite.empty()); newBuffer1 = std::move(buffersToWrite.back()); buffersToWrite.pop_back(); newBuffer1->reset(); } if (!newBuffer2) { assert(!buffersToWrite.empty()); newBuffer2 = std::move(buffersToWrite.back()); buffersToWrite.pop_back(); newBuffer2->reset(); } buffersToWrite.clear(); output.flush(); } output.flush(); }
[ "ggw_hsd@hotmail.com" ]
ggw_hsd@hotmail.com
15410c11dffa3c6ac15cfc997c61f09987001e96
1f44fb3915f6b362464fe9c2b38b530c518b2f2a
/Proyecto Graficas/Example/Example/MeshGl.cpp
c9ba765384c5c5bce275e3bbbbc6e84b1c06ceb1
[]
no_license
MinusDelta21/Graficas-STL
33cdafc918cf72f2a705a1fab53dcaa271381fb8
d31a0cba312a77c8defeb9e1f6c81efd7007a90f
refs/heads/master
2021-05-07T18:57:59.341019
2017-12-08T04:08:27
2017-12-08T04:08:27
108,810,966
0
0
null
null
null
null
UTF-8
C++
false
false
16,852
cpp
#define STB_IMAGE_IMPLEMENTATION #include <stb_image.h> #include "MeshGl.h" #include "Matrix4D.h" #include <iostream> #include <fstream> #include <string> #include "D3DXTexture.h" using namespace std; #define BUFFER_OFFSET(i) ((char *)NULL + (i)) void MeshGL::SetDocName(char* docname) { docName = docname; } void MeshGL::setProps(SceneProps* props) { this->theProps = props; } void MeshGL::Create() { //Textures #ifdef USING_OPENGL_ES shaderID = glCreateProgram(); unsigned int glFiltering = 0; unsigned int glWrap = 0; glFiltering = GL_LINEAR_MIPMAP_LINEAR; glWrap = GL_CLAMP_TO_EDGE; glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, glFiltering); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, glFiltering); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, glWrap); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, glWrap); int Max = 1; glGetIntegerv(GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT, &Max); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAX_ANISOTROPY_EXT, Max); char *vsSourceP = file2string("VS_Mesh.glsl"); char *fsSourceP = file2string("FS_Mesh.glsl"); GLuint vshader_id = createShader(GL_VERTEX_SHADER, vsSourceP); GLuint fshader_id = createShader(GL_FRAGMENT_SHADER, fsSourceP); glAttachShader(shaderID, vshader_id); glAttachShader(shaderID, fshader_id); glLinkProgram(shaderID); glUseProgram(shaderID); vertexAttribLoc = glGetAttribLocation(shaderID, "Vertex"); normalAttribLoc = glGetAttribLocation(shaderID, "Normal"); uvAttribLoc = glGetAttribLocation(shaderID, "UV"); matWorldViewProjUniformLoc = glGetUniformLocation(shaderID, "WVP"); matWorldUniformLoc = glGetUniformLocation(shaderID, "World"); DiffuseLoc = glGetUniformLocation(shaderID, "Diffuse"); lightPosLoc = glGetUniformLocation(shaderID, "LightPos"); cameraPosLoc = glGetUniformLocation(shaderID, "CameraPos"); //AmbientLoc = glGetUniformLocation(shaderID, "Ambient"); #elif defined(USING_D3D11) HRESULT hr; tex = new D3DXTexture; char *vsSourceP = file2string("VS.hlsl"); char *fsSourceP = file2string("FS.hlsl"); if (!vsSourceP || !fsSourceP) exit(32); { VS_blob = nullptr; ComPtr<ID3DBlob> errorBlob = nullptr; hr = D3DCompile(vsSourceP, (UINT)strlen(vsSourceP), 0, 0, 0, "VS", "vs_5_0", 0, 0, &VS_blob, &errorBlob); if (hr != S_OK) { if (errorBlob) { printf("errorBlob shader[%s]", (char*)errorBlob->GetBufferPointer()); return; } if (VS_blob) { return; } } hr = D3D11Device->CreateVertexShader(VS_blob->GetBufferPointer(), VS_blob->GetBufferSize(), 0, &pVS); if (hr != S_OK) { printf("Error Creating Vertex Shader\n"); return; } } { FS_blob = nullptr; ComPtr<ID3DBlob> errorBlob = nullptr; hr = D3DCompile(fsSourceP, (UINT)strlen(fsSourceP), 0, 0, 0, "FS", "ps_5_0", 0, 0, &FS_blob, &errorBlob); if (hr != S_OK) { if (errorBlob) { printf("errorBlob shader[%s]", (char*)errorBlob->GetBufferPointer()); return; } if (FS_blob) { return; } } hr = D3D11Device->CreatePixelShader(FS_blob->GetBufferPointer(), FS_blob->GetBufferSize(), 0, &pFS); if (hr != S_OK) { printf("Error Creating Pixel Shader\n"); return; } } //free(vsSourceP); //free(fsSourceP); D3D11DeviceContext->VSSetShader(pVS.Get(), 0, 0); D3D11DeviceContext->PSSetShader(pFS.Get(), 0, 0); D3D11_INPUT_ELEMENT_DESC vertexDeclaration[] = { { "POSITION" , 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 }, { "NORMAL" , 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, 16, D3D11_INPUT_PER_VERTEX_DATA, 0 }, { "TEXCOORD" , 0, DXGI_FORMAT_R32G32_FLOAT, 0, 32, D3D11_INPUT_PER_VERTEX_DATA, 0 }, }; hr = D3D11Device->CreateInputLayout(vertexDeclaration, ARRAYSIZE(vertexDeclaration), VS_blob->GetBufferPointer(), VS_blob->GetBufferSize(), &Layout); if (hr != S_OK) { printf("Error Creating Input Layout\n"); return; } D3D11DeviceContext->IASetInputLayout(Layout.Get()); D3D11_BUFFER_DESC bdesc = { 0 }; bdesc.Usage = D3D11_USAGE_DEFAULT; bdesc.ByteWidth = sizeof(Buffers); bdesc.BindFlags = D3D11_BIND_CONSTANT_BUFFER; hr = D3D11Device->CreateBuffer(&bdesc, 0, pd3dConstantBuffer.GetAddressOf()); if (hr != S_OK) { printf("Error Creating Buffer Layout\n"); return; } D3D11DeviceContext->VSSetConstantBuffers(0, 1, pd3dConstantBuffer.GetAddressOf()); D3D11DeviceContext->PSSetConstantBuffers(0, 1, pd3dConstantBuffer.GetAddressOf()); D3DXTexture *texd3d = dynamic_cast<D3DXTexture*>(tex); D3D11DeviceContext->PSSetShaderResources(0, 1, texd3d->pSRVTex.GetAddressOf()); D3D11DeviceContext->PSSetSamplers(0, 1, texd3d->pSampler.GetAddressOf()); D3D11_SUBRESOURCE_DATA subData; #endif //Read X File string line; int diffuseCount = 0; ifstream myfile; int numNormals, numTex, numMat; Matrix FTMr; Mesh *myMesh; unsigned short matPos = -1; myfile.open(docName); if (myfile.is_open()) { if (myfile.is_open()) { while (getline(myfile, line)) { char c_temp; if (line == "xof 0303txt 0032") cout << line << endl; int PosM = line.find("FrameTransformMatrix relative {"); int PosV = line.find("Mesh mesh"); int PosN = line.find("MeshNormals normals"); int PosT = line.find("MeshTextureCoords tc"); int PosMat = line.find("MeshMaterialList mtls {"); int PosDif = line.find("diffuseMap"); if (PosM != -1) { myfile >> FTMr.myMatrix.v[0] >> c_temp >> FTMr.myMatrix.v[1] >> c_temp >> FTMr.myMatrix.v[2] >> c_temp >> FTMr.myMatrix.v[3] >> c_temp >> FTMr.myMatrix.v[4] >> c_temp >> FTMr.myMatrix.v[5] >> c_temp >> FTMr.myMatrix.v[6] >> c_temp >> FTMr.myMatrix.v[7] >> c_temp >> FTMr.myMatrix.v[8] >> c_temp >> FTMr.myMatrix.v[9] >> c_temp >> FTMr.myMatrix.v[10] >> c_temp >> FTMr.myMatrix.v[11] >> c_temp >> FTMr.myMatrix.v[12] >> c_temp >> FTMr.myMatrix.v[13] >> c_temp >> FTMr.myMatrix.v[14] >> c_temp >> FTMr.myMatrix.v[15] >> c_temp >> c_temp; } if (PosV != -1) { myMesh = new Mesh; getline(myfile, line); myMesh->num_Vertices = stoi(line); cout << "Vertices: " << myMesh->num_Vertices << endl; //Separar vertices myMesh->vertices = new MeshVertex[myMesh->num_Vertices]; for (int i = 0; i < myMesh->num_Vertices; i++) { myfile >> myMesh->vertices[i].x >> c_temp >> myMesh->vertices[i].y >> c_temp >> myMesh->vertices[i].z >> c_temp >> c_temp; myMesh->vertices[i].w = 1; } myfile >> myMesh->num_Indices >> c_temp; //n_Indices = myMesh->num_Indices; cout << "Indices: " << myMesh->num_Indices << endl; myMesh->indices = new unsigned short[myMesh->num_Indices * 3]; for (int i = 0; i < myMesh->num_Indices; i++) { float aux; myfile >> aux >> c_temp; for (int j = 0; j < aux; j++) { myfile >> myMesh->indices[(i * 3) + j] >> c_temp; } myfile >> c_temp; } } if (PosN != -1) { getline(myfile, line); numNormals = stoi(line); cout << "Normals: " << numNormals << endl; //Separar vertices for (int i = 0; i < numNormals; i++) { myfile >> myMesh->vertices[i].nx >> c_temp >> myMesh->vertices[i].ny >> c_temp >> myMesh->vertices[i].nz >> c_temp >> c_temp; myMesh->vertices[i].nw = 1; } } if (PosT != -1) { getline(myfile, line); numTex = stoi(line); cout << "Texture: " << numTex << endl; //Separar vertices for (int i = 0; i < numTex; i++) { myfile >> myMesh->vertices[i].u >> c_temp >> myMesh->vertices[i].v >> c_temp >> c_temp; } } if (PosMat != -1) { getline(myfile, line); numMat = stoi(line); totalMat = numMat; cout << "Materials: " << numMat << endl; int numLineas; getline(myfile, line); numLineas = stoi(line); cout << "Lineas: " << numLineas << endl; std::streampos it_init = myfile.tellg(); int temp; for (int i = 0; i < numMat; i++) { int matSize = 0; for (int j = 0; j < numLineas; ++j) { myfile >> temp >> c_temp; if (i == temp) { ++matSize; } } myfile.seekg(it_init); myMesh->MaterialList.resize(numMat); myMesh->MaterialList[i].Contenedor = new unsigned short[matSize*3]; myMesh->MaterialList[i].size = matSize * 3; int cont =0; for (int j = 0; j < numLineas; ++j) { myfile >> temp >> c_temp; if (i == temp) { myMesh->MaterialList[i].Contenedor[cont * 3] = myMesh->indices[j * 3]; myMesh->MaterialList[i].Contenedor[(cont * 3)+1] = myMesh->indices[(j * 3)+1]; myMesh->MaterialList[i].Contenedor[(cont * 3) + 2] = myMesh->indices[(j * 3) + 2]; cont++; } } myfile.seekg(it_init); } Meshes.push_back(myMesh); } if (PosDif != -1) { myfile >> myMesh->MaterialList[diffuseCount].Path; myMesh->MaterialList[diffuseCount].Path = myMesh->MaterialList[diffuseCount].Path.substr(1, myMesh->MaterialList[diffuseCount].Path.size() - 3); cout << "Path: " << myMesh->MaterialList[diffuseCount].Path << endl; if (myMesh->MaterialList[diffuseCount].Path == ";") myMesh->MaterialList[diffuseCount].Path.erase(); ++diffuseCount; } if (diffuseCount == totalMat) { diffuseCount = 0; while (diffuseCount < numMat) { string path = "Textures/"; path += myMesh->MaterialList[diffuseCount].Path; int x = 0, y = 0, channels = 0; unsigned char *buffer = stbi_load(path.c_str(), &x, &y, &channels, 0); #ifdef USING_OPENGL_ES glGenTextures(1, &myMesh->MaterialList[diffuseCount].TexID); glBindTexture(GL_TEXTURE_2D, myMesh->MaterialList[diffuseCount].TexID); glPixelStorei(GL_UNPACK_ALIGNMENT, 4); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, x, y, 0, GL_RGBA, GL_UNSIGNED_BYTE, (void*)(buffer)); glGenerateMipmap(GL_TEXTURE_2D); #elif defined(USING_D3D11) D3D11_TEXTURE2D_DESC desc = { 0 }; desc.Width = x; desc.Height = y; desc.ArraySize = 1; desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; desc.SampleDesc.Count = 1; desc.BindFlags = D3D11_BIND_SHADER_RESOURCE | D3D11_BIND_RENDER_TARGET; desc.MiscFlags = D3D11_RESOURCE_MISC_GENERATE_MIPS; D3D11_SUBRESOURCE_DATA initData{}; initData.pSysMem = buffer; initData.SysMemPitch = sizeof(unsigned char) * x * 4; D3D11_SHADER_RESOURCE_VIEW_DESC srvDesc{}; srvDesc.Format = desc.Format; srvDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D; srvDesc.Texture2D.MipLevels = -1; D3D11Device->CreateTexture2D(&desc, nullptr, myMesh->MaterialList[diffuseCount].Tex.GetAddressOf()); D3D11Device->CreateShaderResourceView(myMesh->MaterialList[diffuseCount].Tex.Get(), &srvDesc, myMesh->MaterialList[diffuseCount].pSRVTex.GetAddressOf()); D3D11DeviceContext->UpdateSubresource(myMesh->MaterialList[diffuseCount].Tex.Get(), 0, 0, buffer, initData.SysMemPitch, 0); D3D11DeviceContext->GenerateMips(myMesh->MaterialList[diffuseCount].pSRVTex.Get()); #endif ++diffuseCount; } diffuseCount = 0; } } myfile.close(); } else cout << "Unable to open file"; } for (int i = 0; i < Meshes.size(); i++) { cout << Meshes[i]->vertices->u << ", " << Meshes[i]->vertices->v << endl; } Info.resize(Meshes.size()); for (int i = 0; i < Meshes.size(); i++) { #ifdef USING_OPENGL_ES Info[i].num_Vertices = Meshes[i]->num_Vertices; Info[i].num_Indices = Meshes[i]->num_Indices; glGenBuffers(1, &Info[i].VB); glBindBuffer(GL_ARRAY_BUFFER, Info[i].VB); glBufferData(GL_ARRAY_BUFFER, Meshes[i]->num_Vertices * sizeof(MeshVertex), Meshes[i]->vertices, GL_STATIC_DRAW); glBindBuffer(GL_ARRAY_BUFFER, 0); #elif defined(USING_D3D11) Info[i].num_Vertices = Meshes[i]->num_Vertices; Info[i].num_Indices = Meshes[i]->num_Indices; bdesc = { 0 }; bdesc.ByteWidth = sizeof(MeshVertex) * Info[i].num_Vertices; bdesc.BindFlags = D3D11_BIND_VERTEX_BUFFER; subData = { Meshes[i]->vertices, 0, 0 }; // --> hr = D3D11Device->CreateBuffer(&bdesc, &subData, &Info[i].VB); if (hr != S_OK) { printf("Error Creating Vertex Buffer\n"); myfile.close(); // Finish return; } #endif for (int j = 0; j < Meshes[i]->MaterialList.size(); ++j) { #ifdef USING_OPENGL_ES glGenBuffers(1, &Meshes[i]->MaterialList[j].IB); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, Meshes[i]->MaterialList[j].IB); glBufferData(GL_ELEMENT_ARRAY_BUFFER, Meshes[i]->MaterialList[j].size * sizeof(unsigned short), Meshes[i]->MaterialList[j].Contenedor, GL_STATIC_DRAW); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); #elif defined(USING_D3D11) bdesc = { 0 }; bdesc.ByteWidth = Meshes[i]->MaterialList[j].size * sizeof(unsigned short); bdesc.BindFlags = D3D11_BIND_INDEX_BUFFER; subData = { Meshes[i]->MaterialList[j].Contenedor, 0, 0 }; hr = D3D11Device->CreateBuffer(&bdesc, &subData, &Meshes[i]->MaterialList[j].IB); if (hr != S_OK) { printf("Error Creating Index Buffer\n"); myfile.close(); // Finish return; } #endif } } transform.myMatrix = Identity(); } void MeshGL::Transform(float *t) { transform = t; } void MeshGL::Draw(float *t, float *vp) { #ifdef USING_OPENGL_ES glUseProgram(shaderID); if (t) transform = t; Matrix VP; VP = vp; Matrix WVP; WVP.myMatrix = transform.myMatrix*VP.myMatrix; glUniformMatrix4fv(matWorldUniformLoc, 1, GL_FALSE, &transform.myMatrix.m[0][0]); glUniformMatrix4fv(matWorldViewProjUniformLoc, 1, GL_FALSE, &WVP.myMatrix.m[0][0]); glUniform4fv(lightPosLoc, 1, &theProps->Lights[0].Position.v[0]); glUniform4fv(cameraPosLoc, 1, &theProps->pCameras[0]->Eye.v[0]); for (int i = 0; i < Meshes.size(); i++) { glBindBuffer(GL_ARRAY_BUFFER, Info[i].VB); glEnableVertexAttribArray(vertexAttribLoc); if (normalAttribLoc != -1) glEnableVertexAttribArray(normalAttribLoc); if (uvAttribLoc != -1) glEnableVertexAttribArray(uvAttribLoc); glVertexAttribPointer(vertexAttribLoc, 4, GL_FLOAT, GL_FALSE, sizeof(MeshVertex), BUFFER_OFFSET(0)); if (normalAttribLoc != -1) glVertexAttribPointer(normalAttribLoc, 4, GL_FLOAT, GL_FALSE, sizeof(MeshVertex), BUFFER_OFFSET(16)); if (uvAttribLoc != -1) glVertexAttribPointer(uvAttribLoc, 2, GL_FLOAT, GL_FALSE, sizeof(MeshVertex), BUFFER_OFFSET(32)); for (int j = 0; j < Meshes[i]->MaterialList.size(); ++j) { if (DiffuseLoc != -1) { glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, Meshes[i]->MaterialList[j].TexID); glUniform1i(DiffuseLoc, 0); } glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, Meshes[i]->MaterialList[j].IB); glDrawElements(GL_TRIANGLES, Meshes[i]->MaterialList[j].size * 3, GL_UNSIGNED_SHORT, 0); } glBindBuffer(GL_ARRAY_BUFFER, 0); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); glDisableVertexAttribArray(vertexAttribLoc); if (normalAttribLoc != -1) glDisableVertexAttribArray(normalAttribLoc); if (uvAttribLoc != -1) { glDisableVertexAttribArray(uvAttribLoc); } } #elif defined(USING_D3D11) if (t) transform = t; Matrix VP; VP = vp; Matrix WVP; WVP.myMatrix = transform.myMatrix*VP.myMatrix; CnstBuffer.WVP = WVP.myMatrix; CnstBuffer.World = transform.myMatrix; //Asignar posicion de luz CnstBuffer.Light0Pos = theProps->Lights[0].Position; //Asignar color de luz CnstBuffer.Light0Col = theProps->Lights[0].Color; //Asignar posicion de la camara CnstBuffer.CameraPos = theProps->pCameras[0]->Eye; //Asignar ambient color CnstBuffer.Ambient = theProps->AmbientColor; UINT stride = sizeof(MeshVertex); UINT offset = 0; D3D11DeviceContext->VSSetShader(pVS.Get(), 0, 0); D3D11DeviceContext->PSSetShader(pFS.Get(), 0, 0); D3D11DeviceContext->IASetInputLayout(Layout.Get()); D3D11DeviceContext->UpdateSubresource(pd3dConstantBuffer.Get(), 0, 0, &CnstBuffer, 0, 0); D3D11DeviceContext->VSSetConstantBuffers(0, 1, pd3dConstantBuffer.GetAddressOf()); D3D11DeviceContext->PSSetConstantBuffers(0, 1, pd3dConstantBuffer.GetAddressOf()); for (int i = 0; i < Meshes.size(); i++) { D3D11DeviceContext->IASetVertexBuffers(0, 1, Info[i].VB.GetAddressOf(), &stride, &offset); for (int j = 0; j < Meshes[i]->MaterialList.size(); ++j) { D3D11DeviceContext->PSSetShaderResources(0, 1, Meshes[i]->MaterialList[j].pSRVTex.GetAddressOf()); D3D11DeviceContext->PSSetSamplers(0, 1, Meshes[i]->MaterialList[j].pSampler.GetAddressOf()); D3D11DeviceContext->IASetIndexBuffer(Meshes[i]->MaterialList[j].IB.Get(), DXGI_FORMAT_R16_UINT, 0); D3D11DeviceContext->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST); D3D11DeviceContext->DrawIndexed(Meshes[i]->MaterialList[j].size, 0, 0); } } #endif #ifdef USING_OPENGL_ES glUseProgram(0); #elif defined(USING_D3D11) #endif } void MeshGL::Destroy() { #ifdef USING_OPENGL_ES glDeleteProgram(shaderID); #elif defined(USING_D3D11) #endif }
[ "idv16a.stoll@uartesdigitales.edu.mx" ]
idv16a.stoll@uartesdigitales.edu.mx