blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
2
247
content_id
stringlengths
40
40
detected_licenses
listlengths
0
57
license_type
stringclasses
2 values
repo_name
stringlengths
4
111
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringlengths
4
58
visit_date
timestamp[ns]date
2015-07-25 18:16:41
2023-09-06 10:45:08
revision_date
timestamp[ns]date
1970-01-14 14:03:36
2023-09-06 06:22:19
committer_date
timestamp[ns]date
1970-01-14 14:03:36
2023-09-06 06:22:19
github_id
int64
3.89k
689M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
25 values
gha_event_created_at
timestamp[ns]date
2012-06-07 00:51:45
2023-09-14 21:58:52
gha_created_at
timestamp[ns]date
2008-03-27 23:40:48
2023-08-24 19:49:39
gha_language
stringclasses
159 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
7
10.5M
extension
stringclasses
111 values
filename
stringlengths
1
195
text
stringlengths
7
10.5M
324f419308e621cbd2ec05a256066400c7115b62
a97cf6d1c69355a6364be3d1f2e8f79632850a8b
/BattleTank_Final/Source/BattleTank_Final/Public/MenuSwitchGameInstance.h
e479dab2476e9b7f19d37e9d650aed703a179d16
[]
no_license
KhudangAnish01/Final_Tank_Game
24bf8061649a9e3a0d91ac56bd353f1d15b92792
a41aee6fb240e9f51af4eafa795a6f1112c00652
refs/heads/master
2020-12-26T17:29:59.430465
2020-06-26T14:48:41
2020-06-26T14:48:41
237,575,272
0
0
null
null
null
null
UTF-8
C++
false
false
777
h
MenuSwitchGameInstance.h
// Fill out your copyright notice in the Description page of Project Settings. #pragma once #include "CoreMinimal.h" #include "Engine/GameInstance.h" #include "MenuSwitchGameInstance.generated.h" /** * */ UCLASS() class BATTLETANK_FINAL_API UMenuSwitchGameInstance : public UGameInstance { GENERATED_BODY() public: UPROPERTY(BlueprintReadWrite, Category = "LoadSwitch") bool LoadSwitch=false; UPROPERTY() class USaveProgress* SaveGameInstance; virtual void Init() override; void SavedPlayerStatus(); void LoadPlayerStatus(); UFUNCTION() void LoadGameDelegateFunction(const FString& SlotName, const int32 UserIndex,USaveGame* LoadedGameData); UFUNCTION() void SaveGameDelegateFunction(const FString& SlotName, const int32 UserIndex, bool bSuccess); };
8696b963e21650ba0f6e162aaee95348050c47f6
e5447f2f2437294b42e36302ba3d9b0ea1e224d5
/examples/HX8357_Padding_demo/HX8357_Padding_demo.ino
bd011ae4928781005e67cdf0eaf1b0b96e7ccd52
[ "BSD-3-Clause" ]
permissive
Bodmer/TFT_HX8357
69ef939d8a3827e8f4105b791fee6cb5188688e6
ada4701c8cfd4fe0f8e23d3cddccfc5703e9a967
refs/heads/master
2023-07-08T08:11:11.982112
2023-06-30T13:29:03
2023-06-30T13:29:03
48,673,247
122
61
null
2023-06-30T08:40:16
2015-12-28T04:10:18
C
UTF-8
C++
false
false
6,430
ino
HX8357_Padding_demo.ino
/* Example to show how text padding and setting the datum works. Drawing a numbers at a location can leave the remains of previous numbers. for example drawing 999 then 17 may display as: 179 for left datum or 917 for right datum. By setting the correct text padding width and setting a background colour then the plotted numbers will overprint old values. The padding width must be set to be large enough to cover the old text. This sketch shows drawing numbers and text both with and without padding. Unpadded text and numbers plot in red. Padded text and numbers plot in green. Padding works with all plotting datums set by setTextDatum() The height of the padded area is set automatically by the font used. ######################################################################### ###### DON'T FORGET TO UPDATE THE User_Setup.h FILE IN THE LIBRARY ###### ######################################################################### */ #include <TFT_HX8357.h> // Hardware-specific library TFT_HX8357 tft = TFT_HX8357(); // Invoke custom library unsigned long drawTime = 0; void setup(void) { tft.begin(); tft.setRotation(1); } void loop() { int x = 240; int y = 60; byte decimal_places = 1; byte font = 8; tft.fillScreen(TFT_BLACK); header("Right datum padding demo"); tft.setTextColor(TFT_RED, TFT_BLUE); tft.setTextDatum(TR_DATUM); // Top Right is datum, so decimal point stays in same place // any datum could be used //>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> // The value on screen will be wrong as not all digits are over-printed tft.setTextPadding(0); // Setting to zero switches off padding // Print all numbers from 49.9 to 0.0 in font 8 to show the problem for (int i = 499; i >= 0; i--) { tft.drawFloat(i/10.0, decimal_places, x, y, font); } //>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> // Now set padding width to be 3 digits plus decimal point wide in font 8 // Padding height is set automatically, all numeric digits are the same width // in fonts 1 to 8. The value on screen will now be correct as all digits are over-printed int padding = tft.textWidth("99.9", font); // get the width of the text in pixels tft.setTextColor(TFT_GREEN, TFT_BLUE); tft.setTextPadding(padding); for (int i = 499; i >= 0; i--) { tft.drawFloat(i/10.0, decimal_places, x, y + 140, font); // Use 1 decimal place } delay(5000); //>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> // Now use integers // The value on screen will be wrong as not all digits are over-printed tft.fillScreen(TFT_BLACK); header("Left datum padding demo"); tft.setTextColor(TFT_RED, TFT_BLUE); tft.setTextDatum(TL_DATUM); // Top Left is datum // any datum could be used tft.setTextPadding(0); // Setting to zero switches off padding // Print all numbers from 49.9 to 0.0 in font 8 to show the problem for (int i = 499; i >= 0; i--) { tft.drawNumber(i, x, y, font); } //>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> // Now set padding width to be 3 digits wide in font 8 // Padding height is set automatically, all numeric digits are the same width // in fonts 1 to 8 // The value on screen will now be correct as all digits are over-printed padding = tft.textWidth("999", font); // get the width of the text in pixels tft.setTextColor(TFT_GREEN, TFT_BLUE); tft.setTextPadding(padding); for (int i = 499; i >= 0; i--) { tft.drawNumber(i, x, y + 140, font); // Use 1 decimal place } delay(5000); //>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> // Now use integers with a centred datum // The value on screen will be wrong as not all digits are over-printed tft.fillScreen(TFT_BLACK); header("Centre datum padding demo"); tft.setTextColor(TFT_RED, TFT_BLUE); tft.setTextDatum(TC_DATUM); // Top Centre is datum // any datum could be used tft.setTextPadding(0); // Setting to zero switches off padding // Print all numbers from 49.9 to 0.0 in font 8 to show the problem for (int i = 499; i >= 0; i--) { tft.drawNumber(i, x, y, font); } //>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> // Now set padding width to be 3 digits wide in font 8 // Padding height is set automatically, all numeric digits are the same width // in fonts 1 to 8 // The value on screen will now be correct as all digits are over-printed padding = tft.textWidth("999", font); // get the width of the text in pixels tft.setTextColor(TFT_GREEN, TFT_BLUE); tft.setTextPadding(padding); for (int i = 499; i >= 0; i--) { tft.drawNumber(i, x, y + 140, font); // Use 1 decimal place } delay(5000); //>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> // Now use text over-printing by setting the padding value // Previous text is not wiped by a shorter string tft.fillScreen(TFT_LIGHTGREY); header("Centred datum text padding demo"); tft.setTextSize(2); // Any text size muliplier will work tft.setTextColor(TFT_RED, TFT_BLUE); tft.setTextDatum(TC_DATUM); // Top Centre is datum // any datum could be used tft.setTextPadding(0); // Setting to zero switches off padding tft.drawString("Quick brown", x, y, 4); delay(2000); tft.drawString("fox", x, y, 4); delay(2000); // Now set padding width to longest string // Previous text will automatically be wiped by a shorter string! font = 4; padding = tft.textWidth("Quick brown", font); // get the width of the widest text in pixels // could set this to any number up to screen width tft.setTextPadding(padding); tft.setTextColor(TFT_GREEN, TFT_BLUE); tft.drawString("Quick brown", x, y+80, font); delay(2000); tft.drawString("fox", x, y+80, font); delay(5000); } // Print the header for a display screen void header(char *string) { tft.setTextSize(1); tft.setTextColor(TFT_MAGENTA, TFT_BLACK); tft.setTextDatum(TC_DATUM); tft.drawString(string, 240, 10, 4); }
34475c9d8ca8ebd9567c38c67ee356b0d792fa29
c76db678bfb9010e6e8fd1bf737da483798ac2c9
/Personnage.h
d02f6f2eb825982151e37cdeec7db0c14044186e
[]
no_license
scapel/tutoC-
75ec00269751d08f5967b2bf1ea178feae639541
649d03d21a8325b087ee780aef11a2e5bbf1cf8c
refs/heads/master
2021-01-12T09:31:46.619215
2016-12-11T18:10:53
2016-12-11T18:10:53
76,181,903
0
0
null
null
null
null
UTF-8
C++
false
false
434
h
Personnage.h
/* * Personnage.h * * Created on: 11 déc. 2016 * Author: magalie */ #ifndef PERSONNAGE_H_ #define PERSONNAGE_H_ #include <string> class Personnage { private: int m_vie; std::string m_nom; public: Personnage(); Personnage(std::string nom,int vie); void recevoirAttaque(int degat); void coupDePoing(Personnage& adversaire)const; void sePresenter(void)const; virtual ~Personnage(); }; #endif /* PERSONNAGE_H_ */
6be86a65f085c2994894b4f10de688539c601b9d
25530bb0da97911d147a6d29ae9bc332566cbe55
/FluidEngine/Engine/Math/MatrixExpression.h
1dc36933b67c3ff62992931216a20aeff9e9cac2
[]
no_license
LCM1999/FluidEngine
579a84702dce2a33ed2803a5acb701750389b916
0814ef8e4f740a170351ae4c3b90f23856020104
refs/heads/master
2022-05-05T05:12:56.179735
2019-10-31T03:38:27
2019-10-31T03:38:27
null
0
0
null
null
null
null
UTF-8
C++
false
false
20,796
h
MatrixExpression.h
#pragma once #include "Size2.h" #include "../Utils/Macros.h" #include "../Utils/MathUtils.h" #include "VectorExpression.h" namespace Engine { // MARK: MatrixExpression //! //! \brief Base class for matrix expression. //! //! Matrix expression is a meta type that enables template expression pattern. //! //! \tparam T Real number type. //! \tparam E Subclass type. //! template <typename T, typename E> class MatrixExpression { public: //! Size of the matrix. Size2 size() const; //! Number of rows. size_t rows() const; //! Number of columns. size_t cols() const; //! Returns actual implementation (the subclass). const E& operator()() const; }; //! //! \brief Constant matrix expression. //! //! This matrix expression represents a constant matrix. //! //! \tparam T Real number type. //! template <typename T> class MatrixConstant : public MatrixExpression<T, MatrixConstant<T>> { public: //! Constructs m x n constant matrix expression. MatrixConstant(size_t m, size_t n, const T& c); //! Size of the matrix. Size2 size() const; //! Number of rows. size_t rows() const; //! Number of columns. size_t cols() const; //! Returns matrix element at (i, j). T operator()(size_t i, size_t j) const; private: size_t _m; size_t _n; T _c; }; //! //! \brief Identity matrix expression. //! //! This matrix expression represents an identity matrix. //! //! \tparam T Real number type. //! template <typename T> class MatrixIdentity : public MatrixExpression<T, MatrixIdentity<T>> { public: //! Constructs m x m identity matrix expression. MatrixIdentity(size_t m); //! Size of the matrix. Size2 size() const; //! Number of rows. size_t rows() const; //! Number of columns. size_t cols() const; //! Returns matrix element at (i, j). T operator()(size_t i, size_t j) const; private: size_t _m; }; // MARK: MatrixUnaryOp //! //! \brief Matrix expression for unary operation. //! //! This matrix expression represents an unary matrix operation that takes //! single input matrix expression. //! //! \tparam T Real number type. //! \tparam E Input expression type. //! \tparam Op Unary operation. //! template <typename T, typename E, typename Op> class MatrixUnaryOp : public MatrixExpression<T, MatrixUnaryOp<T, E, Op>> { public: //! Constructs unary operation expression for given input expression. MatrixUnaryOp(const E& u); //! Size of the matrix. Size2 size() const; //! Number of rows. size_t rows() const; //! Number of columns. size_t cols() const; //! Returns matrix element at (i, j). T operator()(size_t i, size_t j) const; private: const E& _u; Op _op; }; //! //! \brief Diagonal matrix expression. //! //! This matrix expression represents a diagonal matrix for given input matrix //! expression. //! //! \tparam T Real number type. //! \tparam E Input expression type. //! template <typename T, typename E> class MatrixDiagonal : public MatrixExpression<T, MatrixDiagonal<T, E>> { public: //! Constructs diagonal matrix expression for given input expression. //! \param isDiag - True for diagonal matrix, false for off-diagonal. MatrixDiagonal(const E& u, bool isDiag); //! Size of the matrix. Size2 size() const; //! Number of rows. size_t rows() const; //! Number of columns. size_t cols() const; //! Returns matrix element at (i, j). T operator()(size_t i, size_t j) const; private: const E& _u; bool _isDiag; }; //! //! \brief Triangular matrix expression. //! //! This matrix expression represents a triangular matrix for given input matrix //! expression. //! //! \tparam T Real number type. //! \tparam E Input expression type. //! template <typename T, typename E> class MatrixTriangular : public MatrixExpression<T, MatrixTriangular<T, E>> { public: //! Constructs triangular matrix expression for given input expression. //! \param isUpper - True for upper tri matrix, false for lower tri matrix. //! \param isStrict - True for strictly upper/lower triangular matrix. MatrixTriangular(const E& u, bool isUpper, bool isStrict); //! Size of the matrix. Size2 size() const; //! Number of rows. size_t rows() const; //! Number of columns. size_t cols() const; //! Returns matrix element at (i, j). T operator()(size_t i, size_t j) const; private: const E& _u; bool _isUpper; bool _isStrict; }; // MARK: MatrixUnaryOp Aliases //! Matrix expression for type casting. template <typename T, typename E, typename U> using MatrixTypeCast = MatrixUnaryOp<T, E, TypeCast<U, T>>; // MARK: MatrixBinaryOp //! //! \brief Matrix expression for binary operation. //! //! This matrix expression represents a binary matrix operation that takes //! two input matrix expressions. //! //! \tparam T Real number type. //! \tparam E1 First input expression type. //! \tparam E2 Second input expression type. //! \tparam Op Binary operation. //! template <typename T, typename E1, typename E2, typename Op> class MatrixBinaryOp : public MatrixExpression<T, MatrixBinaryOp<T, E1, E2, Op>> { public: //! Constructs binary operation expression for given input matrix //! expressions. MatrixBinaryOp(const E1& u, const E2& v); //! Size of the matrix. Size2 size() const; //! Number of rows. size_t rows() const; //! Number of columns. size_t cols() const; //! Returns matrix element at (i, j). T operator()(size_t i, size_t j) const; private: const E1& _u; const E2& _v; Op _op; }; //! //! \brief Matrix expression for matrix-scalar binary operation. //! //! This matrix expression represents a binary matrix operation that takes //! one input matrix expression and one scalar. //! //! \tparam T Real number type. //! \tparam E Input expression type. //! \tparam Op Binary operation. //! template <typename T, typename E, typename Op> class MatrixScalarBinaryOp : public MatrixExpression<T, MatrixScalarBinaryOp<T, E, Op>> { public: //! Constructs a binary expression for given matrix and scalar. MatrixScalarBinaryOp(const E& u, const T& v); //! Size of the matrix. Size2 size() const; //! Number of rows. size_t rows() const; //! Number of columns. size_t cols() const; //! Returns matrix element at (i, j). T operator()(size_t i, size_t j) const; private: const E& _u; T _v; Op _op; }; //! //! \brief Vector expression for matrix-vector multiplication. //! //! This vector expression represents a matrix-vector operation that takes //! one input matrix expression and one vector expression. //! //! \tparam T Element value type. //! \tparam ME Matrix expression. //! \tparam VE Vector expression. //! template <typename T, typename ME, typename VE> class MatrixVectorMul : public VectorExpression<T, MatrixVectorMul<T, ME, VE>> { public: MatrixVectorMul(const ME& m, const VE& v); //! Size of the vector. size_t size() const; //! Returns vector element at i. T operator[](size_t i) const; private: const ME& _m; const VE& _v; }; //! //! \brief Matrix expression for matrix-matrix multiplication. //! //! This matrix expression represents a matrix-matrix operation that takes //! two input matrices. //! //! \tparam T Element value type. //! \tparam ME Matrix expression. //! \tparam VE Vector expression. //! template <typename T, typename E1, typename E2> class MatrixMul : public MatrixExpression<T, MatrixMul<T, E1, E2>> { public: //! Constructs matrix-matrix multiplication expression for given two input //! matrices. MatrixMul(const E1& u, const E2& v); //! Size of the matrix. Size2 size() const; //! Number of rows. size_t rows() const; //! Number of columns. size_t cols() const; //! Returns matrix element at (i, j). T operator()(size_t i, size_t j) const; private: const E1& _u; const E2& _v; }; // MARK: MatrixBinaryOp Aliases //! Matrix-matrix addition expression. template <typename T, typename E1, typename E2> using MatrixAdd = MatrixBinaryOp<T, E1, E2, std::plus<T>>; //! Matrix-scalar addition expression. template <typename T, typename E> using MatrixScalarAdd = MatrixScalarBinaryOp<T, E, std::plus<T>>; //! Matrix-matrix subtraction expression. template <typename T, typename E1, typename E2> using MatrixSub = MatrixBinaryOp<T, E1, E2, std::minus<T>>; //! Matrix-scalar subtraction expression. template <typename T, typename E> using MatrixScalarSub = MatrixScalarBinaryOp<T, E, std::minus<T>>; //! Matrix-matrix subtraction expression with inversed order. template <typename T, typename E> using MatrixScalarRSub = MatrixScalarBinaryOp<T, E, RMinus<T>>; //! Matrix-scalar multiplication expression. template <typename T, typename E> using MatrixScalarMul = MatrixScalarBinaryOp<T, E, std::multiplies<T>>; //! Matrix-scalar division expression. template <typename T, typename E> using MatrixScalarDiv = MatrixScalarBinaryOp<T, E, std::divides<T>>; //! Matrix-scalar division expression with inversed order. template <typename T, typename E> using MatrixScalarRDiv = MatrixScalarBinaryOp<T, E, RDivides<T>>; // MARK: Operator overloadings //! Returns a matrix with opposite sign. template <typename T, typename E> MatrixScalarMul<T, E> operator-(const MatrixExpression<T, E>& a); //! Returns a + b (element-size). template <typename T, typename E1, typename E2> MatrixAdd<T, E1, E2> operator+(const MatrixExpression<T, E1>& a, const MatrixExpression<T, E2>& b); //! Returns a + b', where every element of matrix b' is b. template <typename T, typename E> MatrixScalarAdd<T, E> operator+(const MatrixExpression<T, E>& a, T b); //! Returns a' + b, where every element of matrix a' is a. template <typename T, typename E> MatrixScalarAdd<T, E> operator+(T a, const MatrixExpression<T, E>& b); //! Returns a - b (element-size). template <typename T, typename E1, typename E2> MatrixSub<T, E1, E2> operator-(const MatrixExpression<T, E1>& a, const MatrixExpression<T, E2>& b); //! Returns a - b', where every element of matrix b' is b. template <typename T, typename E> MatrixScalarSub<T, E> operator-(const MatrixExpression<T, E>& a, T b); //! Returns a' - b, where every element of matrix a' is a. template <typename T, typename E> MatrixScalarRSub<T, E> operator-(T a, const MatrixExpression<T, E>& b); //! Returns a * b', where every element of matrix b' is b. template <typename T, typename E> MatrixScalarMul<T, E> operator*(const MatrixExpression<T, E>& a, T b); //! Returns a' * b, where every element of matrix a' is a. template <typename T, typename E> MatrixScalarMul<T, E> operator*(T a, const MatrixExpression<T, E>& b); //! Returns a * b. template <typename T, typename ME, typename VE> MatrixVectorMul<T, ME, VE> operator*(const MatrixExpression<T, ME>& a, const VectorExpression<T, VE>& b); //! Returns a * b. template <typename T, typename E1, typename E2> MatrixMul<T, E1, E2> operator*(const MatrixExpression<T, E1>& a, const MatrixExpression<T, E2>& b); //! Returns a' / b, where every element of matrix a' is a. template <typename T, typename E> MatrixScalarDiv<T, E> operator/(const MatrixExpression<T, E>& a, T b); //! Returns a / b', where every element of matrix b' is b. template <typename T, typename E> MatrixScalarRDiv<T, E> operator/(T a, const MatrixExpression<T, E>& b); //! ---------------------------Definition--------------------------------- // MARK: MatrixExpression template <typename T, typename E> Size2 MatrixExpression<T, E>::size() const { return static_cast<const E&>(*this).size(); } template <typename T, typename E> size_t MatrixExpression<T, E>::rows() const { return static_cast<const E&>(*this).rows(); } template <typename T, typename E> size_t MatrixExpression<T, E>::cols() const { return static_cast<const E&>(*this).cols(); } template <typename T, typename E> const E& MatrixExpression<T, E>::operator()() const { return static_cast<const E&>(*this); } // template <typename T> MatrixConstant<T>::MatrixConstant(size_t m, size_t n, const T& c) : _m(m), _n(n), _c(c) {} template <typename T> Size2 MatrixConstant<T>::size() const { return Size2(rows(), cols()); } template <typename T> size_t MatrixConstant<T>::rows() const { return _m; } template <typename T> size_t MatrixConstant<T>::cols() const { return _n; } template <typename T> T MatrixConstant<T>::operator()(size_t, size_t) const { return _c; } // template <typename T> MatrixIdentity<T>::MatrixIdentity(size_t m) : _m(m) {} template <typename T> Size2 MatrixIdentity<T>::size() const { return Size2(_m, _m); } template <typename T> size_t MatrixIdentity<T>::rows() const { return _m; } template <typename T> size_t MatrixIdentity<T>::cols() const { return _m; } template <typename T> T MatrixIdentity<T>::operator()(size_t i, size_t j) const { return (i == j) ? 1 : 0; } // MARK: MatrixUnaryOp template <typename T, typename E, typename Op> MatrixUnaryOp<T, E, Op>::MatrixUnaryOp(const E& u) : _u(u) {} template <typename T, typename E, typename Op> Size2 MatrixUnaryOp<T, E, Op>::size() const { return _u.size(); } template <typename T, typename E, typename Op> size_t MatrixUnaryOp<T, E, Op>::rows() const { return _u.rows(); } template <typename T, typename E, typename Op> size_t MatrixUnaryOp<T, E, Op>::cols() const { return _u.cols(); } template <typename T, typename E, typename Op> T MatrixUnaryOp<T, E, Op>::operator()(size_t i, size_t j) const { return _op(_u(i, j)); } // template <typename T, typename E> MatrixDiagonal<T, E>::MatrixDiagonal(const E& u, bool isDiag) : _u(u), _isDiag(isDiag) {} template <typename T, typename E> Size2 MatrixDiagonal<T, E>::size() const { return _u.size(); } template <typename T, typename E> size_t MatrixDiagonal<T, E>::rows() const { return _u.rows(); } template <typename T, typename E> size_t MatrixDiagonal<T, E>::cols() const { return _u.cols(); } template <typename T, typename E> T MatrixDiagonal<T, E>::operator()(size_t i, size_t j) const { if (_isDiag) return (i == j) ? _u(i, j) : 0; else return (i != j) ? _u(i, j) : 0; } // template <typename T, typename E> MatrixTriangular<T, E>::MatrixTriangular(const E& u, bool isUpper, bool isStrict) : _u(u), _isUpper(isUpper), _isStrict(isStrict) {} template <typename T, typename E> Size2 MatrixTriangular<T, E>::size() const { return _u.size(); } template <typename T, typename E> size_t MatrixTriangular<T, E>::rows() const { return _u.rows(); } template <typename T, typename E> size_t MatrixTriangular<T, E>::cols() const { return _u.cols(); } template <typename T, typename E> T MatrixTriangular<T, E>::operator()(size_t i, size_t j) const { if (i < j) return (_isUpper) ? _u(i, j) : 0; else if (i > j) return (!_isUpper) ? _u(i, j) : 0; else return (!_isStrict) ? _u(i, j) : 0; } // MARK: MatrixBinaryOp template <typename T, typename E1, typename E2, typename Op> MatrixBinaryOp<T, E1, E2, Op>::MatrixBinaryOp(const E1& u, const E2& v) : _u(u), _v(v) { assert(u.size() == v.size()); } template <typename T, typename E1, typename E2, typename Op> Size2 MatrixBinaryOp<T, E1, E2, Op>::size() const { return _v.size(); } template <typename T, typename E1, typename E2, typename Op> size_t MatrixBinaryOp<T, E1, E2, Op>::rows() const { return _v.rows(); } template <typename T, typename E1, typename E2, typename Op> size_t MatrixBinaryOp<T, E1, E2, Op>::cols() const { return _v.cols(); } template <typename T, typename E1, typename E2, typename Op> T MatrixBinaryOp<T, E1, E2, Op>::operator()(size_t i, size_t j) const { return _op(_u(i, j), _v(i, j)); } // MARK: MatrixScalarBinaryOp template <typename T, typename E, typename Op> MatrixScalarBinaryOp<T, E, Op>::MatrixScalarBinaryOp(const E& u, const T& v) : _u(u), _v(v) {} template <typename T, typename E, typename Op> Size2 MatrixScalarBinaryOp<T, E, Op>::size() const { return _u.size(); } template <typename T, typename E, typename Op> size_t MatrixScalarBinaryOp<T, E, Op>::rows() const { return _u.rows(); } template <typename T, typename E, typename Op> size_t MatrixScalarBinaryOp<T, E, Op>::cols() const { return _u.cols(); } template <typename T, typename E, typename Op> T MatrixScalarBinaryOp<T, E, Op>::operator()(size_t i, size_t j) const { return _op(_u(i, j), _v); } // template <typename T, typename ME, typename VE> MatrixVectorMul<T, ME, VE>::MatrixVectorMul(const ME& m, const VE& v) : _m(m), _v(v) { assert(_m.cols() == _v.size()); } template <typename T, typename ME, typename VE> size_t MatrixVectorMul<T, ME, VE>::size() const { return _v.size(); } template <typename T, typename ME, typename VE> T MatrixVectorMul<T, ME, VE>::operator[](size_t i) const { T sum = 0; const size_t n = _m.cols(); for (size_t j = 0; j < n; ++j) sum += _m(i, j) * _v[j]; return sum; } // MARK: MatrixMul template <typename T, typename E1, typename E2> MatrixMul<T, E1, E2>::MatrixMul(const E1& u, const E2& v) : _u(u), _v(v) { assert(_u.cols() == _v.rows()); } template <typename T, typename E1, typename E2> Size2 MatrixMul<T, E1, E2>::size() const { return Size2(_u.rows(), _v.cols()); } template <typename T, typename E1, typename E2> size_t MatrixMul<T, E1, E2>::rows() const { return _u.rows(); } template <typename T, typename E1, typename E2> size_t MatrixMul<T, E1, E2>::cols() const { return _v.cols(); } template <typename T, typename E1, typename E2> T MatrixMul<T, E1, E2>::operator()(size_t i, size_t j) const { // Unoptimized mat-mat-mul T sum = 0; const size_t n = _u.cols(); for (size_t k = 0; k < n; ++k) sum += _u(i, k) * _v(k, j); return sum; } // MARK: Operator overloadings template <typename T, typename E> MatrixScalarMul<T, E> operator-(const MatrixExpression<T, E>& a) { return MatrixScalarMul<T, E>(a(), T(-1)); } template <typename T, typename E1, typename E2> MatrixAdd<T, E1, E2> operator+(const MatrixExpression<T, E1>& a, const MatrixExpression<T, E2>& b) { return MatrixAdd<T, E1, E2>(a(), b()); } template <typename T, typename E> MatrixScalarAdd<T, E> operator+(const MatrixExpression<T, E>& a, T b) { return MatrixScalarAdd<T, E>(a(), b); } template <typename T, typename E> MatrixScalarAdd<T, E> operator+(T a, const MatrixExpression<T, E>& b) { return MatrixScalarAdd<T, E>(b(), a); } template <typename T, typename E1, typename E2> MatrixSub<T, E1, E2> operator-(const MatrixExpression<T, E1>& a, const MatrixExpression<T, E2>& b) { return MatrixSub<T, E1, E2>(a(), b()); } template <typename T, typename E> MatrixScalarSub<T, E> operator-(const MatrixExpression<T, E>& a, T b) { return MatrixScalarSub<T, E>(a(), b); } template <typename T, typename E> MatrixScalarRSub<T, E> operator-(T a, const MatrixExpression<T, E>& b) { return MatrixScalarRSub<T, E>(b(), a); } template <typename T, typename E> MatrixScalarMul<T, E> operator*(const MatrixExpression<T, E>& a, T b) { return MatrixScalarMul<T, E>(a(), b); } template <typename T, typename E> MatrixScalarMul<T, E> operator*(T a, const MatrixExpression<T, E>& b) { return MatrixScalarMul<T, E>(b(), a); } template <typename T, typename ME, typename VE> MatrixVectorMul<T, ME, VE> operator*(const MatrixExpression<T, ME>& a, const VectorExpression<T, VE>& b) { return MatrixVectorMul<T, ME, VE>(a(), b()); } template <typename T, typename E1, typename E2> MatrixMul<T, E1, E2> operator*(const MatrixExpression<T, E1>& a, const MatrixExpression<T, E2>& b) { return MatrixMul<T, E1, E2>(a(), b()); } template <typename T, typename E> MatrixScalarDiv<T, E> operator/(const MatrixExpression<T, E>& a, T b) { return MatrixScalarDiv<T, E>(a(), b); } template <typename T, typename E> MatrixScalarRDiv<T, E> operator/(T a, const MatrixExpression<T, E>& b) { return MatrixScalarRDiv<T, E>(a(), b); } }
6b0f8c6b949ed9077629fca98a041d1759311114
30bdd8ab897e056f0fb2f9937dcf2f608c1fd06a
/contest/1542551197.cpp
505df4c4f1048978f62e300c36aee6b91b0afbd6
[]
no_license
thegamer1907/Code_Analysis
0a2bb97a9fb5faf01d983c223d9715eb419b7519
48079e399321b585efc8a2c6a84c25e2e7a22a61
refs/heads/master
2020-05-27T01:20:55.921937
2019-11-20T11:15:11
2019-11-20T11:15:11
188,403,594
2
1
null
null
null
null
UTF-8
C++
false
false
475
cpp
1542551197.cpp
#include<bits/stdc++.h> using namespace std; int main(){ double h,m,s,t,t2; cin>>h>>m>>s>>t>>t2; if(t>t2) swap(t,t2); s/=(double)5; m/=(double)5; int cont=0; if(s>t&&s<t2) cont++; if(m>=t&&m<t2) cont++; if(h>=t&&h<t2) cont++; if(cont==3||cont==0) cout<<"yes"; else cout<<"no"; return 0; }
bd16a3e0177e5fe1216a610be8cd781a0ad0a92a
694f0572136d8383c1f8a533513ab1b6cf5f1ebe
/ch8/prb82/b_my_find.cc
85eec7beea8135aff5a40517ff56d8554f5f39ef
[]
no_license
kmad1729/acpp_progs
663b81ea922c0998cf40f0e6395d18fe29ee0ea3
d55ae7439e7a6c36ecbede9ea09da7692a0a498d
refs/heads/master
2021-01-19T07:41:03.826521
2016-06-25T06:30:17
2016-06-25T06:30:17
8,615,547
0
0
null
null
null
null
UTF-8
C++
false
false
950
cc
b_my_find.cc
#include <iostream> #include <algorithm> #include <string> #include <vector> using std::vector; using std::string; using std::cout; using std::endl; template <class In, class Elem> In my_find(In b, In e, const Elem& x) { while(b != e) { if(*b == x) return b; b++; } return e; } int main() { vector<string> v; v.push_back("metallica"); v.push_back("coldplay"); v.push_back("imagine_dragons"); v.push_back("pink_floyd"); v.push_back("beatles"); vector<string> test_str; test_str.push_back("jal"); test_str.push_back("metallica"); test_str.push_back("pritam"); for(vector<string>::size_type i = 0; i < test_str.size(); i++) { cout << "is " << test_str[i] << " in list of band? "; if(my_find(v.begin(), v.end(), test_str[i]) != v.end()) { cout << "yes"; } else { cout << "no"; } cout << endl; } }
797d13dbb6219383f20b99998c722259093d500d
e16de0260783b679f9fc1437477fff2960049ddc
/4_gyro/main.cpp
2d810eb031602948b3cf058c49b226de1e89c94a
[]
no_license
CoppaMan/Pinballs
050f8fb089a09dbfc1d0a2c1343c38c822ce2039
19a9640727a7bdfca275f3bbd0484b2aa168cb0c
refs/heads/master
2020-04-17T00:33:15.285208
2018-12-19T15:47:39
2018-12-19T15:47:39
166,053,958
1
0
null
null
null
null
UTF-8
C++
false
false
2,650
cpp
main.cpp
#include <deque> #include "Gui.h" #include "GyroSim.h" #include "Simulator.h" class GyroGui : public Gui { public: // simulation parameters Eigen::Vector3f m_w; Eigen::Vector3f m_diag; float m_mass = 1.0; float m_dt = 0.03; int m_maxHistory = 200; std::vector<float> m_energy_history; const vector<char const *> m_integrators = { "Semi Implicit", "Implicit"}; int m_selected_integrator = 0; GyroSim *p_gyroSim = NULL; bool use_gyro = true; GyroGui() { m_w << 0.1, 10, 0; m_diag << 24.1449, 28.436, 118.812; m_energy_history.clear(); p_gyroSim = new GyroSim(); setSimulation(p_gyroSim); // show vertex velocity instead of normal callback_clicked_vertex = [&](int clickedVertexIndex, int clickedObjectIndex, Eigen::Vector3d &pos, Eigen::Vector3d &dir) { RigidObject &o = p_gyroSim->getObjects()[clickedObjectIndex]; pos = o.getVertexPosition(clickedVertexIndex); dir = o.getVelocity(pos); }; start(); } virtual void updateSimulationParameters() override { // change all parameters of the simulation to the values that are set in // the GUI p_gyroSim->setTimestep(m_dt); p_gyroSim->setAngularVelocity(m_w.cast<double>()); p_gyroSim->setDiagonal(m_diag.cast<double>()); p_gyroSim->setMethod(m_selected_integrator); } virtual void drawSimulationParameterMenu() override { ImGui::Combo("Integrator", &m_selected_integrator, m_integrators.data(), m_integrators.size()); ImGui::InputFloat3("Angular Velocity", m_w.data(), 4); ImGui::InputFloat3("I_diag", m_diag.data(), 4); ImGui::InputFloat("dt", &m_dt, 0, 0); } virtual void drawSimulationStats() override { Eigen::Vector3d E = p_gyroSim->getRotationalEnergy(); m_energy_history.push_back(E.cast<float>().cwiseAbs().sum()); if (m_energy_history.size() > m_maxHistory) m_energy_history.erase(m_energy_history.begin(), m_energy_history.begin() + 1); ImGui::Text("E_x: %.3f", E(0)); ImGui::Text("E_y: %.3f", E(1)); ImGui::Text("E_z: %.3f", E(2)); ImGui::PlotLines("Total Energy", &m_energy_history[0], m_energy_history.size(), 0, NULL, 0, 300, ImVec2(0, 100)); } }; int main(int argc, char *argv[]) { // create a new instance of the GUI for the spinning simulation new GyroGui(); return 0; }
4b8b7dbfff190c7f2a0f4e389de747d2fb99b54a
c7ac597f22011a6beba1e8c4d723e5771cb8092c
/Test/GraphicsEngine.cpp
e86da7eab5c0e9d5bda524a5b1b94db526667810
[]
no_license
jamessmith119/Test
33e02f4a2fb617b1668cbd7997cd98a0e5472312
af2f044f6ad237d46aafbd2b7155a50efad8785e
refs/heads/master
2021-01-01T05:36:08.351551
2014-11-04T20:45:18
2014-11-04T20:45:18
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,029
cpp
GraphicsEngine.cpp
#include "GraphicsEngine.h" D3D_FEATURE_LEVEL featureLevels[] = { D3D_FEATURE_LEVEL_11_1, D3D_FEATURE_LEVEL_11_0, D3D_FEATURE_LEVEL_10_1, D3D_FEATURE_LEVEL_10_0, D3D_FEATURE_LEVEL_9_3, D3D_FEATURE_LEVEL_9_2, D3D_FEATURE_LEVEL_9_1 }; GraphicsEngine::GraphicsEngine() { device = nullptr; backBuffer = nullptr; renderTargetView = nullptr; ZeroMemory(&swapChainDescription, sizeof(swapChainDescription)); } GraphicsEngine::~GraphicsEngine() { Shutdown(); } HRESULT GraphicsEngine::InitializeDevice(HWND window) { HRESULT hr; //Fill out the swap chain parameters. swapChainDescription.BufferCount = 1; swapChainDescription.BufferDesc.Width = 800; swapChainDescription.BufferDesc.Height = 600; swapChainDescription.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; swapChainDescription.BufferDesc.RefreshRate.Numerator = 60; swapChainDescription.BufferDesc.RefreshRate.Denominator = 1; swapChainDescription.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT; swapChainDescription.OutputWindow = window; swapChainDescription.SampleDesc.Count = 1; swapChainDescription.SampleDesc.Quality = 0; swapChainDescription.Windowed = TRUE; //Try to create the device and swap chain using Direct3D 11.1 features. if(FAILED(hr = D3D11CreateDeviceAndSwapChain(nullptr, D3D_DRIVER_TYPE_HARDWARE, nullptr, 0, featureLevels, _countof(featureLevels), D3D11_SDK_VERSION, &swapChainDescription, &swapChain, &device, &featureLevelsSupported, &deviceContext))) { return E_FAIL; } if (hr == E_INVALIDARG) { //The machine does not have the 11.1 runtime. UINT createDeviceFlags = 0; #ifdef _DEBUG createDeviceFlags |= D3D11_CREATE_DEVICE_DEBUG; #endif if(FAILED(hr = D3D11CreateDeviceAndSwapChain(nullptr, D3D_DRIVER_TYPE_HARDWARE, nullptr, createDeviceFlags, &featureLevels[1], _countof(featureLevels) - 1, D3D11_SDK_VERSION, &swapChainDescription, &swapChain, &device, &featureLevelsSupported, &deviceContext))) { return E_FAIL; } } //Get a pointer to the backbuffer hr = swapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), (LPVOID*)&backBuffer); if(hr == S_OK) { //Only do next steps if we have a backbuffer. //Create the render target view. device->CreateRenderTargetView(backBuffer, NULL, &renderTargetView); //Bind the view. deviceContext->OMSetRenderTargets(1, &renderTargetView, NULL); //Create the viewport CreateViewport(); } return hr; } void GraphicsEngine::ClearScene() { deviceContext->ClearRenderTargetView(renderTargetView, DirectX::Colors::Black); } void GraphicsEngine::Render() { swapChain->Present(0, 0); } void GraphicsEngine::Shutdown() { if(deviceContext) { deviceContext->Release(); deviceContext = 0; } if(backBuffer) { backBuffer->Release(); backBuffer = 0; } if(renderTargetView) { renderTargetView->Release(); renderTargetView = 0; } if(adapter) { adapter->Release(); adapter = 0; } if(swapChain) { swapChain->Release(); swapChain = 0; } if(deviceContext) { deviceContext->Release(); deviceContext = 0; } if(device) { device->Release(); device = 0; } } //Properties or getter/setter section ID3D11Device * GraphicsEngine::GetGraphicsDevice() { return device; } ID3D11DeviceContext * GraphicsEngine::GetGraphicsDeviceContext() { return deviceContext; } IDXGIAdapter * GraphicsEngine::GetDefaultGraphicsAdapter() { IDXGIFactory * factory; if(FAILED(CreateDXGIFactory(__uuidof(IDXGIFactory), (void**)&factory))) { return nullptr; } for(int i = 0; factory->EnumAdapters(i, &adapter) != DXGI_ERROR_NOT_FOUND; ++i) { } if(factory) { factory->Release(); } return adapter; } //Private methods section void GraphicsEngine::CreateViewport() { // Setup the viewport D3D11_VIEWPORT viewPort; viewPort.Width = 800; viewPort.Height = 600; viewPort.MinDepth = 0.0f; viewPort.MaxDepth = 1.0f; viewPort.TopLeftX = 0; viewPort.TopLeftY = 0; deviceContext->RSSetViewports(1, &viewPort); }
aff67aad7dedc9d99925d549994061874b56ed08
86a6a7947494b0bf71a64f93e358130c85b3ba98
/Ciphers/Common/cipherTools.cpp
52cc749bb7c39b574d33b12a5a01f0aeb33dce61
[]
no_license
christsmith/ZooKeyclue_CipherTools
68f93d5ee995d8156ebe8b976ebc9f24609644a6
cd7f0c21843edb3baeb95f80073bb4286d7ecd9c
refs/heads/master
2016-08-11T16:46:35.454076
2016-01-09T22:45:25
2016-01-09T22:45:25
43,655,559
0
0
null
null
null
null
UTF-8
C++
false
false
1,544
cpp
cipherTools.cpp
#include <fstream> #include <vector> #include <string> #include <sstream> #include <iterator> #include <iostream> #include "cipherTools.h" char value_to_ascii(int v, letter_case_t letter_case) { char c; switch (letter_case) { case LETTER_CASE_UPPER: c = (char)(v + 'A'); break; case LETTER_CASE_LOWER: c = (char)(v + 'a'); break; case LETTER_CASE_SPECIAL: c = (char)v; break; default: c = (char)v; break; } return c; } int ascii_to_value(char c, letter_case_t &letter_case) { int v; if(isUpper(c)) { letter_case = LETTER_CASE_UPPER; v = (int)(c - 'A'); } else if(isLower(c)) { letter_case = LETTER_CASE_LOWER; v = (int)(c - 'a'); } else { letter_case = LETTER_CASE_SPECIAL; v = (int)c; } return v; } int ascii_to_value(char c) { int v; if(isUpper(c)) { v = (int)(c - 'A'); } else if(isLower(c)) { v = (int)(c - 'a'); } else { v = (int)c; } return v; } bool isUpper(char l) { return (l >= 'A' && l <= 'Z'); } bool isLower(char l) { return (l >= 'a' && l <= 'z'); } int fileIn(const char * fileName, std::string &input) { std::ifstream iFile(fileName); std::stringstream buffer; if(!iFile.is_open()) return 1; buffer << iFile.rdbuf(); input = buffer.str(); iFile.close(); return 0; }
4afecb8dfedeb3d10597a8581294d955e8dc8541
ed1b1e2f35e18569aa19b63568431c65493b4fbe
/archsim/src/abi/devices/arm/core/ARMv6-MMU.cpp
5b38616c8f5f087a711ae1ce6e7dd6720a7e5ef9
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
yczheng-hit/gensim
cd215c6efc6357f1e375a90d7bda003e8288ed55
1c2c608d97ef8a90253b6f0567b43724ba553c6b
refs/heads/master
2022-12-31T21:00:50.851259
2020-10-16T11:52:19
2020-10-16T11:52:19
null
0
0
null
null
null
null
UTF-8
C++
false
false
21,048
cpp
ARMv6-MMU.cpp
/* This file is Copyright University of Edinburgh 2018. For license details, see LICENSE. */ /* * ARMv6-MMU.cpp * * Created on: 12 Jan 2016 * Author: kuba */ //#include "abi/devices/arm/core/ARMv6-MMU.h" #include "abi/devices/MMU.h" #include "abi/devices/arm/core/ArmControlCoprocessorv6.h" #include "abi/memory/MemoryModel.h" #include "core/thread/ThreadInstance.h" #include "util/ComponentManager.h" #include "util/LogContext.h" UseLogContext(LogArmCoreDevice); DeclareChildLogContext(LogArmMMUv6, LogArmCoreDevice, "MMUv6"); DeclareChildLogContext(LogArmMMUTlbv6, LogArmMMUv6, "TLBv6"); DeclareChildLogContext(LogArmMMUTxlnv6, LogArmMMUv6, "TXLNv6"); DeclareChildLogContext(LogArmMMUFaultv6, LogArmMMUv6, "Faultv6"); DeclareChildLogContext(LogArmMMUAccessv6, LogArmMMUv6, "Accessv6"); DeclareChildLogContext(LogArmMMUInfov6, LogArmMMUv6, "Infov6"); #define GETINFO_CHECK 0 class ARMv6MMU; namespace archsim { namespace abi { namespace devices { class tx_l1_descriptor { public: explicit tx_l1_descriptor(uint32_t data) : Bits(data), AP(0), Domain(0), C(false), B(false), BaseAddr(-1), Type(TXE_FAULT) { switch(data & 0x3) { case 0: ConstructFault(data); break; case 1: ConstructCoarse(data); break; case 2: ConstructSection(data); break; case 3: ConstructFault(data); break; default: assert(false && "Unknown translation type"); } } enum TxEntryType { TXE_FAULT, TXE_Coarse, TXE_Section, TXE_Supersection }; std::string Print() const { std::stringstream str; str << "L1D " << std::hex << Bits << " = "; switch(Type) { case TXE_FAULT: str << "FAULT"; break; case TXE_Coarse: str << "Coarse"; break; case TXE_Section: str << "Section"; break; case TXE_Supersection: str << "Supersection"; break; default: assert(false); } str << " 0x" << std::hex << std::setfill('0') << std::setw(8) << BaseAddr << " Domain:" << std::dec << std::setw(1) << (uint32_t) Domain << " AP:" << (uint32_t)AP; return str.str(); } TxEntryType Type; uint32_t BaseAddr; uint32_t Bits; uint8_t Domain; uint8_t AP; uint8_t SBZ0, SBZ1; uint8_t P; uint8_t NS; uint8_t TEX; uint8_t XN; uint8_t NG; uint8_t S; uint8_t APX; uint8_t Supersection; bool C, B; private: void ConstructFault(uint32_t data) { Type = TXE_FAULT; BaseAddr = 0; Domain = 0; AP = 0; C = 0; B = 0; LC_DEBUG3(LogArmMMUAccessv6) << "Constructed fault descriptor " << Print(); } void ConstructCoarse(uint32_t data) { Type = TXE_Coarse; BaseAddr = data & 0xfffffc00; P = (data >> 8) & 1; Domain = (data >> 5) & 0xf; SBZ0 = (data >> 4) & 1; NS = (data >> 3) & 1; SBZ1 = (data >> 2) & 1; LC_DEBUG3(LogArmMMUAccessv6) << "Constructed coarse descriptor " << Print(); } void ConstructSection(uint32_t data) { Type = TXE_Section; BaseAddr = data & 0xfff00000; NS = (data >> 19) & 1; Supersection = (data >> 17) & 1; NG = (data >> 17) & 1; S = (data >> 16) & 1; APX = (data >> 15) & 1; TEX = (data >> 12) & 0x7; AP = (data >> 10) & 0x3; Domain = (data >> 5) & 0xf; P = (data >> 9) & 1; XN = (data >> 4) & 1; C = data & 0x8; B = data & 0x4; AP = AP | (APX << 2); if(Supersection) assert(false && "Supersections unimplemented"); LC_DEBUG3(LogArmMMUAccessv6) << "Constructed section descriptor " << Print(); } void ConstructSupersection(uint32_t data) { Type = TXE_Section; BaseAddr = data & 0xff000000; SBZ0 = (data >> 20) & 0x8; NS = (data >> 19) & 1; Supersection = 1; NG = (data >> 17) & 1; S = (data >> 16) & 1; APX = (data >> 15) & 1; TEX = (data >> 12) & 0x7; AP = (data >> 10) & 0x3; Domain = (data >> 5) & 0xf; P = (data >> 9) & 1; XN = (data >> 4) & 1; C = data & 0x8; B = data & 0x4; LC_DEBUG3(LogArmMMUAccessv6) << "Constructed supersection descriptor " << Print(); } }; class tx_l2_descriptor { public: enum TxEntryType { TXE_FAULT, TXE_Large, TXE_Small, TXE_Tiny }; explicit tx_l2_descriptor(uint32_t data) : bits(data) { switch(data & 0x3) { case 0x0: base_addr = bits = xn = s = ng = ap = apx = tex = sbz = c = b = 0; type = TXE_FAULT; return; case 0x1: ConstructLarge(data); return; case 0x2: case 0x3: ConstructSmall(data); return; default: LC_DEBUG3(LogArmMMUFaultv6) << "data: " << std::hex << data; assert(false); } } void ConstructLarge(uint32_t data) { type = TXE_Large; base_addr = data & 0xffff0000; xn = (data >> 15) & 1; tex = (data >> 12) & 0x7; ng = (data >> 11) & 1; s = (data >> 10) & 1; apx = (data >> 9) & 1; ap = (data >> 4) & 0x3; ap |= apx << 2; c = data & 0x8; b = data & 0x4; } void ConstructSmall(uint32_t data) { type = TXE_Small; base_addr = data & 0xfffff000; xn = (data >> 0) & 1; tex = (data >> 6) & 0x7; ng = (data >> 11) & 1; s = (data >> 10) & 1; apx = (data >> 9) & 1; ap = (data >> 4) & 0x3; ap |= apx << 2; c = data & 0x8; b = data & 0x4; } void ConstructTiny(uint32_t data) { assert(false); } std::string Print() const { std::stringstream str; str << "L2D " << std::hex << bits << " = "; switch(type) { case TXE_FAULT: str << "FAULT"; break; case TXE_Large: str << "Large"; break; case TXE_Small: str << "Small"; break; case TXE_Tiny: str << "Tiny"; break; default: assert(false); } str << " 0x" << std::hex << std::setw(8) << std::setfill('0') << base_addr << " AP0:" << std::dec << std::setw(1) << (uint32_t)ap; return str.str(); } TxEntryType type; uint32_t base_addr; uint32_t bits; uint8_t xn, s, ng; uint8_t ap, apx; uint8_t tex, sbz; bool c, b; }; class ARMv6MMU : public MMU { public: uint32_t faulting_domain; bool Initialise() override { FlushCaches(); cocoprocessor = (ArmControlCoprocessorv6*)Manager->GetDeviceByName("coprocessor"); assert(cocoprocessor); return true; } const PageInfo GetInfo(Address virt_addr) override { LC_DEBUG1(LogArmMMUInfov6) << "Getting info for MVA " << std::hex << virt_addr; if(!is_enabled()) { LC_DEBUG1(LogArmMMUInfov6) << " - MMU is disabled. Returning identity mapping."; PageInfo pi; pi.phys_addr = virt_addr; pi.mask = 0xf; pi.UserCanRead = true; pi.UserCanWrite = true; pi.KernelCanRead = true; pi.KernelCanWrite = true; pi.Present = true; return pi; } tx_l1_descriptor first_level_lookup = get_l1_descriptor(virt_addr.Get()); LC_DEBUG4(LogArmMMUInfov6) << "GetInfo"; switch(first_level_lookup.Type) { case tx_l1_descriptor::TXE_FAULT: { PageInfo pi; pi.Present = false; return pi; } case tx_l1_descriptor::TXE_Section: return GetSectionInfo(first_level_lookup); case tx_l1_descriptor::TXE_Coarse: return GetCoarseInfo(virt_addr.Get(), first_level_lookup); default: assert(!"Unimplemented"); __builtin_unreachable(); } } const PageInfo GetSectionInfo(const tx_l1_descriptor &descriptor) { PageInfo pi; pi.Present = 1; pi.phys_addr = Address(descriptor.BaseAddr); pi.mask = 0x000fffff; uint32_t dacr = get_dacr(); dacr >>= descriptor.Domain*2; dacr &= 0x3; switch(dacr) { case 0: pi.KernelCanRead = pi.KernelCanWrite = pi.UserCanRead = pi.UserCanWrite = 0; break; case 1: fill_access_perms(pi, descriptor.AP); break; case 3: pi.KernelCanRead = pi.KernelCanWrite = pi.UserCanRead = pi.UserCanWrite = 1; break; default: assert(!"Unimplemented"); } return pi; } const PageInfo GetCoarseInfo(uint32_t mva, const tx_l1_descriptor &descriptor) { PageInfo pi; LC_DEBUG4(LogArmMMUInfov6) << "GetCoarseInfo"; const tx_l2_descriptor l2_descriptor = get_l2_descriptor_coarse(mva, descriptor); if(l2_descriptor.type == tx_l2_descriptor::TXE_FAULT) { pi.Present = false; return pi; } pi.Present = true; uint32_t dacr = get_dacr(); dacr >>= descriptor.Domain*2; dacr &= 0x3; switch(dacr) { case 0: pi.KernelCanRead = pi.KernelCanWrite = pi.UserCanRead = pi.UserCanWrite = 0; break; case 1: fill_access_perms(pi, l2_descriptor.ap); break; case 3: pi.KernelCanRead = pi.KernelCanWrite = pi.UserCanRead = pi.UserCanWrite = 1; break; default: assert(false); } switch(l2_descriptor.type) { case tx_l2_descriptor::TXE_Large: LC_DEBUG2(LogArmMMUTxlnv6) << "L2 lookup resulted in large page descriptor"; pi.phys_addr = Address((l2_descriptor.base_addr & 0xffff0000) | (mva & 0x0000ffff)); pi.mask = 0xffff; break; case tx_l2_descriptor::TXE_Small: LC_DEBUG2(LogArmMMUTxlnv6) << "L2 lookup resulted in small page descriptor"; pi.phys_addr = Address((l2_descriptor.base_addr & 0xfffff000) | (mva & 0x00000fff)); pi.mask = 0xfff; break; default: assert(false); } return pi; } void fill_access_perms(PageInfo &pi, uint32_t AP) { pi.UserCanRead = pi.UserCanWrite = pi.KernelCanRead = pi.KernelCanWrite = 0; switch(AP) { case 0: // no access break; case 1: pi.KernelCanRead = pi.KernelCanWrite = 1; break; case 2: pi.KernelCanRead = pi.KernelCanWrite = pi.UserCanRead = 1; break; case 3: pi.KernelCanRead = pi.KernelCanWrite = pi.UserCanRead = pi.UserCanWrite = 1; break; case 4: // no access break; case 5: pi.KernelCanRead = 1; break; case 6: pi.KernelCanRead = pi.UserCanRead = 1; break; case 7: pi.KernelCanRead = pi.UserCanRead = 1; break; default: assert(!"Unknown access type"); } } TranslateResult Translate(archsim::core::thread::ThreadInstance *cpu, Address va, Address &phys_addr, AccessInfo info) override { uint32_t virt_addr = va.Get(); //Canary value to catch invalid accesses phys_addr = Address(0xf0f0f0f0); LC_DEBUG4(LogArmMMUv6) << "Translating MVA " << std::hex << virt_addr; if(!is_enabled()) { phys_addr = va; return TXLN_OK; } TranslateResult result = TXLN_FAULT_OTHER; /* First-level descriptor indicates whether the access is to a section or to a page table. * If the access is to a page table, the MMU determines the page table type and fetches * a second-level descriptor. */ tx_l1_descriptor first_level_lookup = get_l1_descriptor(virt_addr); faulting_domain = first_level_lookup.Domain; switch(first_level_lookup.Type) { case tx_l1_descriptor::TXE_FAULT: LC_DEBUG4(LogArmMMUFaultv6) << "L1 lookup resulted in section fault when translating " << std::hex << virt_addr << " (" << first_level_lookup.Bits << ")"; result = TXLN_FAULT_SECTION; break; case tx_l1_descriptor::TXE_Section: LC_DEBUG4(LogArmMMUTxlnv6) << "L1 lookup resulted in section descriptor " << std::hex << virt_addr << " (" << info << ")"; result = translate_section(virt_addr, first_level_lookup, phys_addr, info); break; case tx_l1_descriptor::TXE_Supersection: LC_DEBUG4(LogArmMMUTxlnv6) << "mmu-v6: we do not support supersections\n"; assert(false); break; case tx_l1_descriptor::TXE_Coarse: LC_DEBUG4(LogArmMMUTxlnv6) << "L1 lookup resulted in coarse page descriptor " << std::hex << virt_addr << " (" << info << ")"; result = translate_coarse(virt_addr, first_level_lookup, phys_addr, info); break; default: assert(false && "Unknown access type"); } if(info.SideEffects) handle_result(result, cpu, virt_addr, info); return result; } void handle_result(TranslateResult result, archsim::core::thread::ThreadInstance *cpu, uint32_t mva, const struct AccessInfo info) { uint32_t new_fsr = 0; if(result != TXLN_OK) { LC_DEBUG1(LogArmMMUv6) << "Handling result " << result << " for access to " << std::hex << std::setw(8) << std::setfill('0') << mva << " for access " << info << " " << cpu->GetExecutionRing(); } // bool is_kernel = permissions & 0x2; bool is_write = info.Write; if(is_write) new_fsr |= 0x800; if(!info.Fetch) new_fsr |= (faulting_domain & 0xf) << 4; switch(result) { case TXLN_OK: return; case TXLN_FAULT_SECTION: new_fsr |= 0x5; break; case TXLN_FAULT_PAGE: new_fsr |= 0x7; break; case TXLN_ACCESS_DOMAIN_SECTION: new_fsr |= 0x9; break; case TXLN_ACCESS_DOMAIN_PAGE: new_fsr |= 0xb; break; case TXLN_ACCESS_PERMISSION_SECTION: new_fsr |= 0xd; break; case TXLN_ACCESS_PERMISSION_PAGE: new_fsr |= 0xf; break; default: assert(false); } LC_DEBUG1(LogArmMMUFaultv6) << "MVA: " << std::hex << std::setw(8) << std::setfill('0') << mva << " FSR: " << new_fsr << " Info: " << info; LC_DEBUG2(LogArmMMUv6) << "Writing fault status bits"; if(info.Fetch) { cocoprocessor->set_ifsr(new_fsr); cocoprocessor->set_ifar(mva); } else { cocoprocessor->set_dfsr(new_fsr); cocoprocessor->set_dfar(mva); } } private: ArmControlCoprocessorv6 *cocoprocessor; tx_l1_descriptor get_l1_descriptor(uint32_t mva) { uint32_t tx_table_base = get_tx_table_base(mva); uint32_t table_idx = (mva & 0xfff00000) >> 20; uint32_t descriptor_addr = tx_table_base | (table_idx << 2); uint32_t data; LC_DEBUG4(LogArmMMUv6) << "Reading L1 descriptor from " << std::hex << descriptor_addr; GetPhysMem()->Read32(Address(descriptor_addr), data); LC_DEBUG4(LogArmMMUv6) << "Descriptor data"<< data; tx_l1_descriptor descriptor(data); LC_DEBUG4(LogArmMMUv6) << "Got descriptor "<< descriptor.Print(); return descriptor; } uint32_t get_tx_table_base(uint32_t mva) const { assert(cocoprocessor); return cocoprocessor->get_ttbr() & ~0x3fff; } TranslateResult translate_section(uint32_t mva, tx_l1_descriptor &section_descriptor, Address &out_phys_addr, const struct AccessInfo info) { uint32_t section_base_addr = section_descriptor.BaseAddr; uint32_t section_index = mva & 0xfffff; //TODO: Access permissions //Check domain uint8_t region_domain = section_descriptor.Domain; uint32_t dacr = get_dacr(); // DACR - Domain Access Control Register dacr >>= region_domain*2; dacr &= 0x3; bool kernel_mode = info.Ring != 0; bool is_write = info.Write; LC_DEBUG3(LogArmMMUAccessv6) << "Translate Section DACR: " << dacr; switch(dacr) { case 2: LC_DEBUG1(LogArmMMUAccessv6) << "A section domain access fault was triggered"; faulting_domain = section_descriptor.Domain; return TXLN_ACCESS_DOMAIN_SECTION; case 1: //Check access permissions LC_DEBUG2(LogArmMMUAccessv6) << "Regular permission checks were performed with AP " << std::hex << section_descriptor.AP; if(!allow_access(section_descriptor, info)) { LC_DEBUG1(LogArmMMUAccessv6) << "A section access fault was triggered, AP:" << (uint32_t)section_descriptor.AP << ", K:" << kernel_mode << ", W:" << is_write; faulting_domain = section_descriptor.Domain; return TXLN_ACCESS_PERMISSION_SECTION; } break; } out_phys_addr = Address(section_base_addr | section_index); // update_tlb_entry(mva, out_phys_addr, kernel_mode, !is_write); return TXLN_OK; } TranslateResult translate_coarse(uint32_t mva, tx_l1_descriptor &l1_descriptor, Address &out_phys_addr, const struct AccessInfo info) { tx_l2_descriptor l2_desc = get_l2_descriptor_coarse(mva, l1_descriptor); uint8_t region_domain = l1_descriptor.Domain; faulting_domain = region_domain; if(l2_desc.type == tx_l2_descriptor::TXE_FAULT) { LC_DEBUG2(LogArmMMUFaultv6) << "L2 lookup resulted in page fault when mapping " << std::hex << mva; LC_DEBUG3(LogArmMMUFaultv6) << "L1 descriptor: " << std::hex << l1_descriptor.Print(); LC_DEBUG3(LogArmMMUFaultv6) << "L2 descriptor: " << std::hex << l2_desc.Print(); return TXLN_FAULT_PAGE; } //Check domain uint32_t dacr = get_dacr(); uint32_t full_dacr = get_dacr(); dacr >>= region_domain*2; dacr &= 0x3; bool kernel_mode = info.Ring != 0; bool is_write = info.Write; bool is_fetch = info.Fetch; LC_DEBUG1(LogArmMMUAccessv6) << "Translate Coarse DACR: " << dacr; switch(dacr) { case 2: return TranslateResult::TXLN_ACCESS_DOMAIN_PAGE; } switch(l2_desc.type) { case tx_l2_descriptor::TXE_FAULT: LC_DEBUG1(LogArmMMUAccessv6) << "L2 lookup results in page fault."; return TranslateResult::TXLN_FAULT_PAGE; case tx_l2_descriptor::TXE_Small: LC_DEBUG2(LogArmMMUTxlnv6) << "L2 lookup resulted in small page descriptor"; if (dacr == 1) { if (!allow_access(l2_desc, info)) { return TranslateResult::TXLN_ACCESS_PERMISSION_PAGE; } } out_phys_addr = Address((l2_desc.base_addr & 0xfffff000) | (mva & 0x00000fff)); break; case tx_l2_descriptor::TXE_Large: LC_DEBUG2(LogArmMMUTxlnv6) << "L2 lookup resulted in large page descriptor"; if (dacr == 1) { if (!allow_access(l2_desc, info)) { return TranslateResult::TXLN_ACCESS_PERMISSION_PAGE; } } out_phys_addr = Address((l2_desc.base_addr & 0xffff0000) | (mva & 0x0000ffff)); break; default: assert(false); } // update_tlb_entry(mva, out_phys_addr, kernel_mode, !is_write); return TXLN_OK; } uint32_t get_dacr() const { return cocoprocessor->get_dacr(); } bool allow_access(tx_l2_descriptor &desc, const struct AccessInfo &info) { if(info.Fetch && desc.xn) return false; switch(desc.ap) { case 0: // if(cocoprocessor->get_cp1_R()) return !is_write; // else if(cocoprocessor->get_cp1_S()) return kernel_mode && !is_write; return false; case 1: return info.Ring; case 2: return info.Ring || (!info.Write); case 3: return true; case 4: return false; case 5: return info.Ring && !info.Write; case 6: return !info.Write; case 7: return !info.Write; default: assert(!"Unknown access permission type"); return false; } } bool allow_access(tx_l1_descriptor &desc, const struct AccessInfo &info) { if(info.Fetch && desc.XN) return false; switch(desc.AP) { case 0: // if(cocoprocessor->get_cp1_R()) return !is_write; // else if(cocoprocessor->get_cp1_S()) return kernel_mode && !is_write; return false; case 1: return info.Ring; case 2: return info.Ring || (!info.Write); case 3: return true; case 4: return false; case 5: return info.Ring && !info.Write; case 6: return !info.Write; case 7: return !info.Write; default: assert(!"Unknown access permission type"); return false; } } tx_l2_descriptor get_l2_descriptor_coarse(uint32_t mva, const tx_l1_descriptor &l1_descriptor) { uint32_t base_addr = l1_descriptor.BaseAddr; uint32_t l2_table_index = (mva >> 12) & 0xff; uint32_t l2_desc_addr = (base_addr & 0xfffffc00) | (l2_table_index << 2); uint32_t data; LC_DEBUG4(LogArmMMUv6) << "Reading Coarse L2 descriptor from " << std::hex << l2_desc_addr; GetPhysMem()->Read32(Address(l2_desc_addr), data); LC_DEBUG4(LogArmMMUv6) << "Descriptor data: " << std::hex << data; tx_l2_descriptor descriptor(data); LC_DEBUG4(LogArmMMUv6) << "Got descriptor " << descriptor.Print(); return descriptor; } }; RegisterComponent(Device, ARMv6MMU, "ARMv6MMU", "MMU"); } } }
938d1a2243561f5579963a4326a295b5c9b8b3ae
c92b2b4c795a569530abf64495f45e08f92573d0
/K173722A2P3.cpp
0b7b46ded15e49423b1198080b06ab82d8709189
[]
no_license
Murad1893/Simulation-of-Queuing-Systems
c9618d0aae383aafae4331dc85a4f53834af9fd3
c8508edb8a52350206cb6b4c8c664feee3627bf4
refs/heads/master
2022-02-23T18:10:34.944125
2019-10-02T15:23:33
2019-10-02T15:23:33
212,374,677
0
0
null
null
null
null
UTF-8
C++
false
false
7,417
cpp
K173722A2P3.cpp
#include <iostream> #include <windows.h> #include <time.h> #include <fstream> using namespace std; static int customer_count=0; //to store the customer count in order to print each customer with a different integer like "Customer 1,Customer 2..." etc class customer{ private: int arrival_hr; int arrival_min; int mins; //this is the hrs+min in mins int service_time; int wait_time; public: customer(){ service_time=0; wait_time=0; } void setarrivaltime(int min){ arrival_hr=min/60; arrival_min=min%60; mins=min; } int getarrivaltime(){ return mins; } int getarrivalhr(){ return arrival_hr; } int getarrivalmin(){ return arrival_min; } void setservicetime(int a){ service_time=a; } void setwaittime(int a){ wait_time=a; } int getwaittime(){ return wait_time; } int getservicetime(){ return service_time; } void print(){ //print the customer info cout<<"\nCustomer "<<++customer_count<<": "; if(arrival_hr/10==0){ if(arrival_min/10==0) cout<<"\nArrived at: 0"<<arrival_hr<<":0"<<arrival_min; else cout<<"\nArrived at: 0"<<arrival_hr<<":"<<arrival_min; } else cout<<"\nArrived at: "<<arrival_hr<<":"<<arrival_min; cout<<"\nService time: "<<service_time; cout<<"\nWait time: "<<wait_time; cout<<endl<<endl; } }; int random_number(int min,int max){ //generate random number based within a range return (rand())%(max-min+1)+min; } void simulator(int e){ //runs the simulator for the specified number of hours fstream obj; obj.open("A2P3-out.txt",ios::out|ios::trunc); int end_time=e; //this is end time of the program. This can be user specified. As the POS is 18*7 hence for a particular day runs for 18 hours and so done for 18 hours srand(time(0)); //this is done in order to generate pseudo random numbers int clock_time=random_number(0,10); //clock time here denotes that at what time the customer arrives at the POS. at the start can be anytime between 0 - 10 mins after opening of the POS int prevclock_hr=0; //this variable assists in checking whether one hour mark has passed or not int i=0; //total number of customers int k=0; //this count the customers uptil the 1 hour mark bool ishour=false; //this variable assists in checking whether one hour mark has passed or not customer c[250]; //maximum of a 250 customer count made should be increased if the running time of the POS is greater than 18 but is fine if below equal to 24 float average_waittime=0; //this is to calculate the avg.waiting time per hour float average_servicetime=0; //average service time for POS utilization int hour_count=0; //for statistic end_time=end_time*60; //program made in number of minutes srand(time(0)); while(clock_time+c[i].getwaittime()<=end_time-8){ //the program terminates when the arrival time of last customer is greater the max service time + endtime in order to give him proper service before the end time of the shop //Sleep(100); can be used to see simulation if(ishour){ //if the hour mark is reached average_waittime=0; cout<<"\n***************************************\n"; obj<<"***************************************\n"; cout<<"Statistics: from "<<hour_count-1<<":00"<<"-"<<++hour_count<<":00"<<"\n"; obj<<"Statistics: from "<<hour_count-1<<":00"<<"-"<<hour_count<<":00"<<"\n"; for(int j=k;j<=i;j++){ //loop for the customers uptil the hour mark average_waittime+=c[j].getwaittime(); } if((average_waittime/(i-k))>3){ //busy hour identification cout<<"\nBUSY HOUR. Average waiting time > 3\n"; obj<<"\nBUSY HOUR. Average waiting time > 3\n"; } cout<<"\nAverage waiting time: "<<average_waittime/(i-k); obj<<"\nAverage waiting time: "<<average_waittime/(i-k)<<" mins/customer"; cout<<"\nNumber of customers in this hour: "<<i-k; obj<<"\nNumber of customers in this hour: "<<i-k; cout<<"\n***************************************\n"; obj<<"\n***************************************\n\n"; cout<<"\n\n"; k=i; //so that now k is initialized to next customer number after the hour mark ishour=false; //both the checking variables are reset prevclock_hr=0; } cout<<"\t---------------------------------------------------\n"; cout<<"\t\t\tEND TIME: "<<end_time/60<<":0"<<end_time%60<<endl; if((clock_time/60)/10==0){ if((clock_time%60)/10==0) cout<<"\t\t\tCLOCK: 0"<<clock_time/60<<":0"<<clock_time%60<<"\n"; else cout<<"\t\t\tCLOCK: 0"<<clock_time/60<<":"<<clock_time%60<<"\n"; } else cout<<"\t\t\tCLOCK: "<<clock_time/60<<":"<<clock_time%60<<"\n"; cout<<"\t---------------------------------------------------"; prevclock_hr=clock_time/60; c[i].setarrivaltime(clock_time); //the arrival time of the customer is the recent time on the clock clock_time+=random_number(0,15); //this condition implies that the maximum gap between two customer arrivals can be 15 mins that another customer will come after 15 mins. 0<=Interarrival time<=15 prevclock_hr=clock_time/60-prevclock_hr; //difference between the clock_times in hours to ensure whether an hour has passed or not if(prevclock_hr==1){ ishour=true; } c[i].setservicetime(random_number(3,8)); //random service time allocated between 3-8 if(i==0){ c[i].setwaittime(0); //if the first customer comes than he does not have to wait } else{ //this incoorporates that wait time for the new customer is the (service+wait) time of the previous arrived customer subtracted from the difference in the arrival times of both int wait=(c[i-1].getwaittime()+c[i-1].getservicetime())-(c[i].getarrivaltime()-c[i-1].getarrivaltime()); if(wait<=0){ //if wait time is negative means no need to wait then set to zero c[i].setwaittime(0); } else c[i].setwaittime(wait); } c[i].print(); i++; } average_waittime=0; cout<<"\n***************************************\n"; obj<<"***************************************\n"; cout<<"Statistics: from "<<hour_count-1<<":00"<<"-"<<++hour_count<<":00"<<"\n"; obj<<"Statistics: from "<<hour_count-1<<":00"<<"-"<<hour_count<<":00"<<"\n"; for(int j=k;j<=i;j++){ average_waittime+=c[j].getwaittime(); } if((average_waittime/(i-k))>3){ cout<<"\nBUSY HOUR. Average waiting time > 3\n"; obj<<"\nBUSY HOUR. Average waiting time > 3\n"; } cout<<"\nAverage waiting time: "<<average_waittime/(i-k); obj<<"\nAverage waiting time: "<<average_waittime/(i-k)<<" mins/customer"; cout<<"\nNumber of customers in this hour: "<<i-k; obj<<"\nNumber of customers in this hour: "<<i-k; for(int j=0;j<i;j++){ average_servicetime+=c[j].getservicetime(); } cout<<"\n***************************************\n"; obj<<"\n***************************************\n\n"; cout<<"\nxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\n"; cout<<"Average POS utilization time: "<<average_servicetime/i; obj<<"Average POS utilization time: "<<average_servicetime/i<<" mins/customer"; cout<<""; cout<<"\nTotal customers: "<<i; obj<<"\nTotal customers: "<<i; cout<<"\nxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\n"; } int main(){ int end_time=18; //user can input number of hours to be run from here simulator(end_time); }
deaa27ea45e80ba88cc940873bbb417695f0546c
dc81c76a02995eb140d10a62588e3791a8c7de0d
/PortfolioTrading/TradeStation/charsetconvert.cpp
4ca8a327623c9d01004f52af458affee816bdc66
[]
no_license
xbotuk/cpp-proto-net
ab971a94899da7749b35d6586202bb4c52991461
d685bee57c8bf0e4ec2db0bfa21d028fa90240fd
refs/heads/master
2023-08-17T00:52:03.883886
2016-08-20T03:40:36
2016-08-20T03:40:36
null
0
0
null
null
null
null
GB18030
C++
false
false
1,902
cpp
charsetconvert.cpp
#include "StdAfx.h" #include "charsetconvert.h" #include <Windows.h> void UTF_8ToUnicode(wchar_t* pOut,char *pText) { char* uchar = (char *)pOut; uchar[1] = ((pText[0] & 0x0F) << 4) + ((pText[1] >> 2) & 0x0F); uchar[0] = ((pText[1] & 0x03) << 6) + (pText[2] & 0x3F); } void UnicodeToUTF_8(char* pOut,wchar_t* pText) { // 注意 WCHAR高低字的顺序,低字节在前,高字节在后 char* pchar = (char *)pText; pOut[0] = (0xE0 | ((pchar[1] & 0xF0) >> 4)); pOut[1] = (0x80 | ((pchar[1] & 0x0F) << 2)) + ((pchar[0] & 0xC0) >> 6); pOut[2] = (0x80 | (pchar[0] & 0x3F)); } void UnicodeToGB2312(char* pOut,wchar_t uData) { ::WideCharToMultiByte(CP_ACP,NULL,&uData,1,pOut,sizeof(wchar_t),NULL,NULL); } void Gb2312ToUnicode(wchar_t* pOut,char *gbBuffer) { ::MultiByteToWideChar(CP_ACP,MB_PRECOMPOSED,gbBuffer,2,pOut,1); } void GB2312ToUTF_8(std::string& pOut, const char *gb2312) { int len = MultiByteToWideChar(CP_ACP, 0, gb2312, -1, NULL, 0); wchar_t* wstr = new wchar_t[len+1]; memset(wstr, 0, len+1); MultiByteToWideChar(CP_ACP, 0, gb2312, -1, wstr, len); len = WideCharToMultiByte(CP_UTF8, 0, wstr, -1, NULL, 0, NULL, NULL); char* str = new char[len+1]; memset(str, 0, len+1); WideCharToMultiByte(CP_UTF8, 0, wstr, -1, str, len, NULL, NULL); if(wstr) delete[] wstr; pOut = str; delete []str; } void UTF_8ToGB2312(std::string &pOut, const char *utf8) { int len = MultiByteToWideChar(CP_UTF8, 0, utf8, -1, NULL, 0); wchar_t* wstr = new wchar_t[len+1]; memset(wstr, 0, len+1); MultiByteToWideChar(CP_UTF8, 0, utf8, -1, wstr, len); len = WideCharToMultiByte(CP_ACP, 0, wstr, -1, NULL, 0, NULL, NULL); char* str = new char[len+1]; memset(str, 0, len+1); WideCharToMultiByte(CP_ACP, 0, wstr, -1, str, len, NULL, NULL); if(wstr) delete[] wstr; pOut = str; delete []str; }
c5ee95cc63149ded7c3a2e3bd3dbd4718a10a76a
cfdfa665d16ac9f732b21369f031c35450dbea9f
/src/academy/src/MindFLfull.cpp
3999fb35c719761b98a95f9fc224736e36e7f5b9
[]
no_license
lazyrun/kenay
7df8e143b8ab69891087d0af887d757297fbb2da
4ec4d686185c8f3307de23d526004af2649aac40
refs/heads/master
2016-09-06T15:37:38.890401
2013-03-30T08:53:57
2013-03-30T08:53:57
null
0
0
null
null
null
null
WINDOWS-1251
C++
false
false
50,053
cpp
MindFLfull.cpp
#include "MindFLfull.h" #include "GlobVars.h" // Категории игроков по VPIP #define MANIAK 44. #define LOOSE 32. #define MODERATE 24. #define TIGHT 18. #define EXTRATIGHT 1. //Порог по PFR #define PFR_PASSIVE 8.// меньше, значит пассив #define PFR_AGGRESIVE 12. //порог по лимпу #define LIMP_PASSIVE 16. MindFLfull::MindFLfull(CardProcessing * const proc, Session * const session) : Mind(proc, session), tightThreshold_(28.) { pCareful_ = qMakePair(0., 18.); pTight_ = qMakePair(18., 24.); pModerate_ = qMakePair(24., 32.); pLoose_ = qMakePair(32., 44.); pManiak_ = qMakePair(44., 100.); ranCareful_ = "66+,A5s+,K9s+,Q9s+,J9s+,ATo+,KTo+,QTo+"; ranTight_ = "66+,A2s+,K6s+,Q8s+,J8s+,T9s,A8o+,K9o+,QTo+,JTo"; ranModerate_ = "55+,A2s+,K4s+,Q7s+,J8s+,T8s+,98s,A5o+,K8o+,Q9o+,J9o+,T9o"; ranLoose_ = "22+,A2s+,K2s+,Q4s+,J6s+,T6s+,97s+,87s,A2o+,K6o+,Q8o+,J8o+,T8o+,98o"; ranManiak_ = "22+,A2s+,K2s+,Q2s+,J4s+,T6s+,96s+,86s+,76s,65s,A2o+,K5o+,Q7o+,J7o+,T8o+,98o"; CGlobal::Instance().SetDbg(2); } Solution MindFLfull::preflopSolution() { CGlobal::Instance().ap2(QString("suited: %1 nominal: %2") .arg(hole_.suitedName()).arg(hole_.nominalName())); //определить позицию preflopPosition(); //определить круг торговли int trade = tradeInPreflop(); if (trade == 0) { return round0Solution(); } else//не первый, т.е. был рейз после меня { return roundASolution(); } return Solution(); } Solution MindFLfull::round0Solution() { const qreal tightThreshold = 28.; //количество тайтовых оппонентов int tight = 0, live = 0; foreach (Opp opp, oppList_) { if (!opp.isInGame()) continue; if (opp.vpip() > 1. && opp.vpip() < tightThreshold ) { tight++; } live++; } //процентное выражение тайтовости qreal tightPercent = qreal(tight) * 100. / qreal(live); //использовать рекомендации для тайтовой игры useTight_ = false; //первый круг if (preflopPos_ == HighJack || preflopPos_ == Button) { if ((limpers_ + raisers_ <= 3) && (raisers_ > 0) && preflopPos_ == Button) { //1, 2 лимпера и 1 рейзер useTight_ = true; } else if ((limpers_ + raisers_ <= 3) && (raisers_ > 0) && preflopPos_ == HighJack) { useTight_ = true; } else if (limpers_ + raisers_ == 0) { //играть лузовее useTight_ = false; } else//больше трех уже { //в зависимости от тайтовости стола if (tightPercent > 50.) { useTight_ = true; } } } else//какие-то другие позиции UTG, Middle, sb, bb { //в зависимости от тайтовости стола if (tightPercent > 50.) { useTight_ = true; } } //для теста //return tightPreflop(); CGlobal::Instance().ap1(QString("Tight opps: %1%").arg(tightPercent)); CGlobal::Instance().ap1(QString("Raisers: %1").arg(raisers_)); CGlobal::Instance().ap1(QString("Limpers: %1").arg(limpers_)); if (useTight_) { CGlobal::Instance().ap1(QString("tightPreflop()")); return tightPreflop(); } CGlobal::Instance().ap1(QString("loosePreflop()")); return loosePreflop(); } Solution MindFLfull::roundASolution() { CGlobal::Instance().ap1(QString("roundASolution()")); CGlobal::Instance().ap1(QString("Raisers: %1").arg(raisers_)); CGlobal::Instance().ap1(QString("Limpers: %1").arg(limpers_)); QString suited = hole_.suitedName(); QString nominal = hole_.nominalName(); QStringList limpRange; QStringList raiseRange; raiseRange << parseRangeList("QQ+,AKs"); limpRange << parseRangeList("88+,AQs,AQo,AJs"); CGlobal::Instance().ap2(QString("Raise Range: %1").arg(raiseRange.join(", "))); CGlobal::Instance().ap2(QString("Limp Range: %1").arg(limpRange.join(", "))); Solution sol; if (raiseRange.contains(suited) || raiseRange.contains(nominal)) { CGlobal::Instance().ap1(QString("Solution::Raise")); sol.setAction(Solution::Raise); } else if (raisers_ == 1) { CGlobal::Instance().ap1(QString("Solution::Call")); sol.setAction(Solution::Call); } else if (raisers_ > 1) { if (limpRange.contains(suited) || limpRange.contains(nominal)) { CGlobal::Instance().ap1(QString("Solution::Call")); sol.setAction(Solution::Call); } else { CGlobal::Instance().ap1(QString("Solution::Fold")); sol.setAction(Solution::Fold); } } else { CGlobal::Instance().ap1(QString("Solution::Call")); sol.setAction(Solution::Call); } return sol; } void MindFLfull::preflopPosition() { if (proc_->isDealer()) { CGlobal::Instance().ap1(QString("Position: Button")); preflopPos_ = Button; } else { //количество живых игроков QList<Opp> liveOpps; foreach (Opp opp, oppList_) { if (opp.isInGame()) { liveOpps << opp; } } CGlobal::Instance().ap1(QString("Opps In Game: %1").arg(liveOpps.count())); //позиция дилера int dpos = -1; for (int i = 0; i < liveOpps.count(); i++) { if (liveOpps.at(i).isDealer()) { dpos = i; break; } } Q_ASSERT_X(dpos != -1, "preflopPosition", "Dealer position isn't found!"); int me = liveOpps.count() - dpos; if (me == 1) { CGlobal::Instance().ap1(QString("Position: SmallBlind")); preflopPos_ = SmallBlind; } else if (me == 2) { CGlobal::Instance().ap1(QString("Position: BigBlind")); preflopPos_ = BigBlind; } else if (me == liveOpps.count()) { CGlobal::Instance().ap1(QString("Position: HighJack")); preflopPos_ = HighJack; } else if (me < liveOpps.count() && me >= liveOpps.count() - 3) { CGlobal::Instance().ap1(QString("Position: Middle")); preflopPos_ = Middle; } else { CGlobal::Instance().ap1(QString("Position: UTG")); preflopPos_ = UTG; } } } int MindFLfull::tradeInPreflop() { int r = session_->preflopRound(); CGlobal::Instance().ap1(QString("Trade Round: %1").arg(r)); return r; } Solution MindFLfull::tightPreflop() { switch (preflopPos_) { case SmallBlind: return sbTight(); case BigBlind: return bbTight(); case UTG: return utgTight(); case Middle: return mTight(); case HighJack: case Button: return buTight(); } return Solution(); } // /* ----------SB Tight----------------- */ // Solution MindFLfull::sbTight() { /* Не было рейза лимп рейз Был рейз лимп рейз Был рейз и ререйз лимп рейз */ Solution sol; if (raisers_ == 0) { CGlobal::Instance().ap2(QString("sbTightNoRaise()")); sol = sbTightNoRaise(); } else if (raisers_ == 1) { CGlobal::Instance().ap2(QString("sbTightOneRaise()")); sol = sbTightOneRaise(); } else if (raisers_ >= 1) { CGlobal::Instance().ap2(QString("sbTightMoreRaise()")); sol = sbTightMoreRaise(); } //учесть что рейзер может быть лузовым - тогда играть шире //также учесть как долго я не играю return sol; } Solution MindFLfull::sbTightNoRaise() { QString suited = hole_.suitedName(); QString nominal = hole_.nominalName(); QStringList limpRange; QStringList raiseRange; raiseRange << parseRangeList("99+,ATs+,KJs+,AQo+"); limpRange << parseRangeList("22+,A2s+,K9s+,Q9s+,J9s+,ATo+,T9s,98s,87s,76s,65s,54s,JTo,QTo+,KTo+"); CGlobal::Instance().ap2(QString("Raise Range: %1").arg(raiseRange.join(", "))); CGlobal::Instance().ap2(QString("Limp Range: %1").arg(limpRange.join(", "))); Solution sol; if (raiseRange.contains(suited) || raiseRange.contains(nominal)) { CGlobal::Instance().ap1(QString("Solution::Raise")); sol.setAction(Solution::Raise); } else if (limpRange.contains(suited) || limpRange.contains(nominal)) { CGlobal::Instance().ap1(QString("Solution::Call")); sol.setAction(Solution::Call); } else if (hole_.isSuited()) { CGlobal::Instance().ap1(QString("isSuited()==true -> Solution::Call")); sol.setAction(Solution::Call); } else { CGlobal::Instance().ap1(QString("Solution::Fold")); sol.setAction(Solution::Fold); } return sol; } Solution MindFLfull::sbTightOneRaise() { QString suited = hole_.suitedName(); QString nominal = hole_.nominalName(); QStringList limpRange; QStringList raiseRange; raiseRange << parseRangeList("TT+,AKs,AKo"); limpRange << parseRangeList("AJs+,AKo,KQs"); Solution sol; //решение с учетом агрессивности оппов sol = pfrVpipSolution(); if (sol.action() != Solution::Nope) return sol; CGlobal::Instance().ap2(QString("Raise Range: %1").arg(raiseRange.join(", "))); CGlobal::Instance().ap2(QString("Limp Range: %1").arg(limpRange.join(", "))); if (raiseRange.contains(suited) || raiseRange.contains(nominal)) { CGlobal::Instance().ap1(QString("Solution::Raise")); sol.setAction(Solution::Raise); } else if (limpRange.contains(suited) || limpRange.contains(nominal)) { CGlobal::Instance().ap1(QString("Solution::Call")); sol.setAction(Solution::Call); } else if (raisers_ == 1 && limpers_ >= 1) { CGlobal::Instance().ap1(QString("(raisers_ == 1 && limpers_ >= 1)")); limpRange.clear(); limpRange << parseRange("22+"); if (limpRange.contains(suited) || limpRange.contains(nominal)) { CGlobal::Instance().ap1(QString("Solution::Call")); sol.setAction(Solution::Call); } else { CGlobal::Instance().ap1(QString("Solution::Fold")); sol.setAction(Solution::Fold); } } else { CGlobal::Instance().ap1(QString("Solution::Fold")); sol.setAction(Solution::Fold); } return sol; } Solution MindFLfull::sbTightMoreRaise() { QString suited = hole_.suitedName(); QString nominal = hole_.nominalName(); QStringList raiseRange; raiseRange << parseRangeList("QQ+,AKs"); CGlobal::Instance().ap2(QString("Raise Range: %1").arg(raiseRange.join(", "))); Solution sol; if (raiseRange.contains(suited) || raiseRange.contains(nominal)) { CGlobal::Instance().ap1(QString("Solution::Raise")); sol.setAction(Solution::Raise); } else { CGlobal::Instance().ap1(QString("Solution::Fold")); sol.setAction(Solution::Fold); } return sol; } // /* ----------BB Tight----------------- */ // Solution MindFLfull::bbTight() { Solution sol; if (raisers_ == 0) { CGlobal::Instance().ap2(QString("bbTightNoRaise()")); sol = bbTightNoRaise(); } else if (raisers_ == 1) { CGlobal::Instance().ap2(QString("bbTightOneRaise()")); sol = bbTightOneRaise(); } else if (raisers_ > 1) { CGlobal::Instance().ap2(QString("bbTightMoreRaise()")); sol = bbTightMoreRaise(); } //учесть что рейзер может быть лузовым - тогда играть шире //также учесть как долго я не играю return sol; } Solution MindFLfull::bbTightNoRaise() { QString suited = hole_.suitedName(); QString nominal = hole_.nominalName(); QStringList limpRange; QStringList raiseRange; raiseRange << parseRangeList("99+,ATs+,KJs+,AQo+"); CGlobal::Instance().ap2(QString("Raise Range: %1").arg(raiseRange.join(", "))); CGlobal::Instance().ap2(QString("Limp Range: %1").arg(limpRange.join(", "))); Solution sol; if (raiseRange.contains(suited) || raiseRange.contains(nominal)) { CGlobal::Instance().ap1(QString("Solution::Raise")); sol.setAction(Solution::Raise); } else { CGlobal::Instance().ap1(QString("Solution::Check")); sol.setAction(Solution::Check); } return sol; } Solution MindFLfull::bbTightOneRaise() { QString suited = hole_.suitedName(); QString nominal = hole_.nominalName(); QStringList limpRange; QStringList raiseRange; raiseRange << parseRangeList("TT+,AKs,AKo"); limpRange << parseRangeList("22+,ATs+,JTs,QTs+,KTs+,AJo+,KQo"); //решение с учетом агрессивности оппов Solution sol = pfrVpipSolution(); if (sol.action() != Solution::Nope) return sol; CGlobal::Instance().ap2(QString("Raise Range: %1").arg(raiseRange.join(", "))); CGlobal::Instance().ap2(QString("Limp Range: %1").arg(limpRange.join(", "))); if (raiseRange.contains(suited) || raiseRange.contains(nominal)) { CGlobal::Instance().ap1(QString("Solution::Raise")); sol.setAction(Solution::Raise); } else if (limpRange.contains(suited) || limpRange.contains(nominal)) { CGlobal::Instance().ap1(QString("Solution::Call")); sol.setAction(Solution::Call); } else { CGlobal::Instance().ap1(QString("Solution::Fold")); sol.setAction(Solution::Fold); } return sol; } Solution MindFLfull::bbTightMoreRaise() { QString suited = hole_.suitedName(); QString nominal = hole_.nominalName(); QStringList raiseRange; raiseRange << parseRangeList("QQ+,AKs"); CGlobal::Instance().ap2(QString("Raise Range: %1").arg(raiseRange.join(", "))); Solution sol; if (raiseRange.contains(suited) || raiseRange.contains(nominal)) { CGlobal::Instance().ap1(QString("Solution::Raise")); sol.setAction(Solution::Raise); } else { CGlobal::Instance().ap1(QString("Solution::Fold")); sol.setAction(Solution::Fold); } return sol; } // /* ----------UTG Tight----------------- */ // Solution MindFLfull::utgTight() { Solution sol; if (raisers_ == 0) { CGlobal::Instance().ap2(QString("utgTightNoRaise()")); sol = utgTightNoRaise(); } else if (raisers_ == 1) { CGlobal::Instance().ap2(QString("utgTightOneRaise()")); sol = utgTightOneRaise(); } else if (raisers_ > 1) { CGlobal::Instance().ap2(QString("utgTightMoreRaise()")); sol = utgTightMoreRaise(); } //учесть что рейзер может быть лузовым - тогда играть шире //также учесть как долго я не играю return sol; } Solution MindFLfull::utgTightNoRaise() { QString suited = hole_.suitedName(); QString nominal = hole_.nominalName(); QStringList limpRange; QStringList raiseRange; raiseRange << parseRangeList("TT+,AJs+,AQo+"); limpRange << parseRangeList("77+,AJo+,JTs,QTs+,KTs+,ATs+,KQo"); CGlobal::Instance().ap2(QString("Raise Range: %1").arg(raiseRange.join(", "))); CGlobal::Instance().ap2(QString("Limp Range: %1").arg(limpRange.join(", "))); Solution sol; if (raiseRange.contains(suited) || raiseRange.contains(nominal)) { CGlobal::Instance().ap1(QString("Solution::Raise")); sol.setAction(Solution::Raise); } else if (limpRange.contains(suited) || limpRange.contains(nominal)) { CGlobal::Instance().ap1(QString("Solution::Call")); sol.setAction(Solution::Call); } else { CGlobal::Instance().ap1(QString("Solution::Fold")); sol.setAction(Solution::Fold); } return sol; } Solution MindFLfull::utgTightOneRaise() { QString suited = hole_.suitedName(); QString nominal = hole_.nominalName(); QStringList limpRange; QStringList raiseRange; raiseRange << parseRangeList("TT+,AKs,AKo"); limpRange << parseRangeList("AJs+,AKo,KQs"); Solution sol; //решение с учетом агрессивности оппов sol = pfrVpipSolution(); if (sol.action() != Solution::Nope) return sol; CGlobal::Instance().ap2(QString("Raise Range: %1").arg(raiseRange.join(", "))); CGlobal::Instance().ap2(QString("Limp Range: %1").arg(limpRange.join(", "))); if (raiseRange.contains(suited) || raiseRange.contains(nominal)) { CGlobal::Instance().ap1(QString("Solution::Raise")); sol.setAction(Solution::Raise); } else if (limpRange.contains(suited) || limpRange.contains(nominal)) { CGlobal::Instance().ap1(QString("Solution::Call")); sol.setAction(Solution::Call); } else { CGlobal::Instance().ap1(QString("Solution::Fold")); sol.setAction(Solution::Fold); } return sol; } Solution MindFLfull::utgTightMoreRaise() { QString suited = hole_.suitedName(); QString nominal = hole_.nominalName(); QStringList raiseRange; raiseRange << parseRangeList("QQ+,AKs"); CGlobal::Instance().ap2(QString("Raise Range: %1").arg(raiseRange.join(", "))); Solution sol; if (raiseRange.contains(suited) || raiseRange.contains(nominal)) { CGlobal::Instance().ap1(QString("Solution::Raise")); sol.setAction(Solution::Raise); } else { CGlobal::Instance().ap1(QString("Solution::Fold")); sol.setAction(Solution::Fold); } return sol; } // /* ----------Middle Tight----------------- */ // Solution MindFLfull::mTight() { Solution sol; if (raisers_ == 0) { CGlobal::Instance().ap2(QString("mTightNoRaise()")); sol = mTightNoRaise(); } else if (raisers_ == 1) { CGlobal::Instance().ap2(QString("mTightOneRaise()")); sol = mTightOneRaise(); } else if (raisers_ > 1) { CGlobal::Instance().ap2(QString("mTightMoreRaise()")); sol = mTightMoreRaise(); } //учесть что рейзер может быть лузовым - тогда играть шире //также учесть как долго я не играю return sol; } Solution MindFLfull::mTightNoRaise() { QString suited = hole_.suitedName(); QString nominal = hole_.nominalName(); QStringList limpRange; QStringList raiseRange; raiseRange << parseRangeList("99+,ATs+,KJs+,AJo+,KQo"); limpRange << parseRangeList("22+,A2s+,K9s+,Q9s+,J9s+,ATo+,KJo+,T9s,98s"); CGlobal::Instance().ap2(QString("Raise Range: %1").arg(raiseRange.join(", "))); CGlobal::Instance().ap2(QString("Limp Range: %1").arg(limpRange.join(", "))); Solution sol; if (raiseRange.contains(suited) || raiseRange.contains(nominal)) { CGlobal::Instance().ap1(QString("Solution::Raise")); sol.setAction(Solution::Raise); } else if (limpRange.contains(suited) || limpRange.contains(nominal)) { CGlobal::Instance().ap1(QString("Solution::Call")); sol.setAction(Solution::Call); } else { CGlobal::Instance().ap1(QString("Solution::Fold")); sol.setAction(Solution::Fold); } return sol; } Solution MindFLfull::mTightOneRaise() { QString suited = hole_.suitedName(); QString nominal = hole_.nominalName(); QStringList limpRange; QStringList raiseRange; raiseRange << parseRangeList("TT+,AKs,AKo"); limpRange << parseRangeList("AJs+,AKo,KQs"); Solution sol; //решение с учетом агрессивности оппов sol = pfrVpipSolution(); if (sol.action() != Solution::Nope) return sol; CGlobal::Instance().ap2(QString("Raise Range: %1").arg(raiseRange.join(", "))); CGlobal::Instance().ap2(QString("Limp Range: %1").arg(limpRange.join(", "))); if (raiseRange.contains(suited) || raiseRange.contains(nominal)) { CGlobal::Instance().ap1(QString("Solution::Raise")); sol.setAction(Solution::Raise); } else if (limpRange.contains(suited) || limpRange.contains(nominal)) { CGlobal::Instance().ap1(QString("Solution::Call")); sol.setAction(Solution::Call); } else { CGlobal::Instance().ap1(QString("Solution::Fold")); sol.setAction(Solution::Fold); } return sol; } Solution MindFLfull::mTightMoreRaise() { QString suited = hole_.suitedName(); QString nominal = hole_.nominalName(); QStringList raiseRange; raiseRange << parseRangeList("QQ+,AKs"); CGlobal::Instance().ap2(QString("Raise Range: %1").arg(raiseRange.join(", "))); Solution sol; if (raiseRange.contains(suited) || raiseRange.contains(nominal)) { CGlobal::Instance().ap1(QString("Solution::Raise")); sol.setAction(Solution::Raise); } else { CGlobal::Instance().ap1(QString("Solution::Fold")); sol.setAction(Solution::Fold); } return sol; } // /* ----------Button, HJ Tight----------------- */ // Solution MindFLfull::buTight() { Solution sol; if (raisers_ == 0) { CGlobal::Instance().ap2(QString("buTightNoRaise()")); sol = buTightNoRaise(); } else if (raisers_ == 1) { CGlobal::Instance().ap2(QString("buTightOneRaise()")); sol = buTightOneRaise(); } else if (raisers_ > 1) { CGlobal::Instance().ap2(QString("buTightMoreRaise()")); sol = buTightMoreRaise(); } //учесть что рейзер может быть лузовым - тогда играть шире //также учесть как долго я не играю return sol; } Solution MindFLfull::buTightNoRaise() { QString suited = hole_.suitedName(); QString nominal = hole_.nominalName(); QStringList limpRange; QStringList raiseRange; raiseRange << parseRangeList("99+,A8s+,KTs+,ATo+,QJs,KQo"); limpRange << parseRangeList("22+,A2s+,K9s+,Q9s+,J9s+,ATo+,T9s,98s,87s,76s,65s,54s,JTo,QTo+,KTo+"); CGlobal::Instance().ap2(QString("Raise Range: %1").arg(raiseRange.join(", "))); CGlobal::Instance().ap2(QString("Limp Range: %1").arg(limpRange.join(", "))); Solution sol; if (raiseRange.contains(suited) || raiseRange.contains(nominal)) { CGlobal::Instance().ap1(QString("Solution::Raise")); sol.setAction(Solution::Raise); } else if (limpRange.contains(suited) || limpRange.contains(nominal)) { CGlobal::Instance().ap1(QString("Solution::Call")); sol.setAction(Solution::Call); } else { CGlobal::Instance().ap1(QString("Solution::Fold")); sol.setAction(Solution::Fold); } return sol; } Solution MindFLfull::buTightOneRaise() { QString suited = hole_.suitedName(); QString nominal = hole_.nominalName(); QStringList limpRange; QStringList raiseRange; raiseRange << parseRangeList("TT+,AKs,AKo"); limpRange << parseRangeList("AJs+,AKo,KQs"); Solution sol; //решение с учетом агрессивности оппов sol = pfrVpipSolution(); if (sol.action() != Solution::Nope) return sol; CGlobal::Instance().ap2(QString("Raise Range: %1").arg(raiseRange.join(", "))); CGlobal::Instance().ap2(QString("Limp Range: %1").arg(limpRange.join(", "))); if (raiseRange.contains(suited) || raiseRange.contains(nominal)) { CGlobal::Instance().ap1(QString("Solution::Raise")); sol.setAction(Solution::Raise); } else if (limpRange.contains(suited) || limpRange.contains(nominal)) { CGlobal::Instance().ap1(QString("Solution::Call")); sol.setAction(Solution::Call); } else if (limpers_ == 2 && raisers_ == 1) { CGlobal::Instance().ap1(QString("(limpers_ == 2 && raisers_ == 1)")); limpRange.clear(); limpRange << parseRangeList("22+,QJs,JTs,T9s"); CGlobal::Instance().ap2(QString("Limp Range: %1").arg(limpRange.join(", "))); if (limpRange.contains(suited) || limpRange.contains(nominal)) { CGlobal::Instance().ap1(QString("Solution::Call")); sol.setAction(Solution::Call); } else { CGlobal::Instance().ap1(QString("Solution::Fold")); sol.setAction(Solution::Fold); } } else { CGlobal::Instance().ap1(QString("Solution::Fold")); sol.setAction(Solution::Fold); } return sol; } Solution MindFLfull::buTightMoreRaise() { QString suited = hole_.suitedName(); QString nominal = hole_.nominalName(); QStringList raiseRange; raiseRange << parseRangeList("QQ+,AKs"); CGlobal::Instance().ap2(QString("Raise Range: %1").arg(raiseRange.join(", "))); Solution sol; if (raiseRange.contains(suited) || raiseRange.contains(nominal)) { CGlobal::Instance().ap1(QString("Solution::Raise")); sol.setAction(Solution::Raise); } else { CGlobal::Instance().ap1(QString("Solution::Fold")); sol.setAction(Solution::Fold); } return sol; } // // Loose Preflop // Solution MindFLfull::loosePreflop() { switch (preflopPos_) { case SmallBlind: return sbLoose(); case BigBlind: return bbLoose(); case UTG: return utgLoose(); case Middle: return mLoose(); case HighJack: case Button: return buLoose(); } return Solution(); } // /* ----------UTG Loose----------------- */ // Solution MindFLfull::utgLoose() { Solution sol; if (raisers_ == 0) { CGlobal::Instance().ap2(QString("utgLooseNoRaise()")); sol = utgLooseNoRaise(); } else if (raisers_ == 1) { CGlobal::Instance().ap2(QString("utgLooseOneRaise()")); sol = utgLooseOneRaise(); } else if (raisers_ >= 1) { CGlobal::Instance().ap2(QString("utgLooseMoreRaise()")); sol = utgLooseMoreRaise(); } //учесть что рейзер может быть лузовым - тогда играть шире //также учесть как долго я не играю return sol; } Solution MindFLfull::utgLooseNoRaise() { QString suited = hole_.suitedName(); QString nominal = hole_.nominalName(); QStringList limpRange; QStringList raiseRange; raiseRange << parseRangeList("99+,ATs+,KJs+,AJo+,KQo"); limpRange << parseRangeList("22+,A2s+,K9s+,Q9s+,J9s+,ATo+,KJo+,T9s,98s"); CGlobal::Instance().ap2(QString("Raise Range: %1").arg(raiseRange.join(", "))); CGlobal::Instance().ap2(QString("Limp Range: %1").arg(limpRange.join(", "))); Solution sol; if (raiseRange.contains(suited) || raiseRange.contains(nominal)) { CGlobal::Instance().ap1(QString("Solution::Raise")); sol.setAction(Solution::Raise); } else if (limpRange.contains(suited) || limpRange.contains(nominal)) { CGlobal::Instance().ap1(QString("Solution::Call")); sol.setAction(Solution::Call); } else { CGlobal::Instance().ap1(QString("Solution::Fold")); sol.setAction(Solution::Fold); } return sol; } Solution MindFLfull::utgLooseOneRaise() { QString suited = hole_.suitedName(); QString nominal = hole_.nominalName(); QStringList limpRange; QStringList raiseRange; raiseRange << parseRangeList("99+,AKs,AQs,AKo,AQo"); limpRange << parseRangeList("22+,ATs+,KTs+,QJs,JTs"); Solution sol; //решение с учетом агрессивности оппов sol = pfrVpipSolution(); if (sol.action() != Solution::Nope) return sol; CGlobal::Instance().ap2(QString("Raise Range: %1").arg(raiseRange.join(", "))); CGlobal::Instance().ap2(QString("Limp Range: %1").arg(limpRange.join(", "))); if (raiseRange.contains(suited) || raiseRange.contains(nominal)) { CGlobal::Instance().ap1(QString("Solution::Raise")); sol.setAction(Solution::Raise); } else if (limpRange.contains(suited) || limpRange.contains(nominal)) { CGlobal::Instance().ap1(QString("Solution::Call")); sol.setAction(Solution::Call); } else { CGlobal::Instance().ap1(QString("Solution::Fold")); sol.setAction(Solution::Fold); } return sol; } Solution MindFLfull::utgLooseMoreRaise() { QString suited = hole_.suitedName(); QString nominal = hole_.nominalName(); QStringList limpRange; QStringList raiseRange; raiseRange << parseRangeList("QQ+,AKs"); limpRange << parseRangeList("TT+,AJs+,KQs,AKo"); CGlobal::Instance().ap2(QString("Raise Range: %1").arg(raiseRange.join(", "))); CGlobal::Instance().ap2(QString("Limp Range: %1").arg(limpRange.join(", "))); Solution sol; if (raiseRange.contains(suited) || raiseRange.contains(nominal)) { CGlobal::Instance().ap1(QString("Solution::Raise")); sol.setAction(Solution::Raise); } else if (limpRange.contains(suited) || limpRange.contains(nominal)) { CGlobal::Instance().ap1(QString("Solution::Call")); sol.setAction(Solution::Call); } else { CGlobal::Instance().ap1(QString("Solution::Fold")); sol.setAction(Solution::Fold); } return sol; } // /* ----------Middle Loose----------------- */ // Solution MindFLfull::mLoose() { Solution sol; if (raisers_ == 0) { CGlobal::Instance().ap2(QString("mLooseNoRaise()")); sol = mLooseNoRaise(); } else if (raisers_ == 1) { CGlobal::Instance().ap2(QString("mLooseOneRaise()")); sol = mLooseOneRaise(); } else if (raisers_ >= 1) { CGlobal::Instance().ap2(QString("mLooseMoreRaise()")); sol = mLooseMoreRaise(); } //учесть что рейзер может быть лузовым - тогда играть шире //также учесть как долго я не играю return sol; } Solution MindFLfull::mLooseNoRaise() { QString suited = hole_.suitedName(); QString nominal = hole_.nominalName(); QStringList limpRange; QStringList raiseRange; raiseRange << parseRangeList("99+,ATs+,KJs+,AJo+,KQo"); limpRange << parseRangeList("22+,A2s+,K9s+,Q9s+,J9s+,ATo+,KJo+,T9s,98s"); CGlobal::Instance().ap2(QString("Raise Range: %1").arg(raiseRange.join(", "))); CGlobal::Instance().ap2(QString("Limp Range: %1").arg(limpRange.join(", "))); Solution sol; if (raiseRange.contains(suited) || raiseRange.contains(nominal)) { CGlobal::Instance().ap1(QString("Solution::Raise")); sol.setAction(Solution::Raise); } else if (limpRange.contains(suited) || limpRange.contains(nominal)) { CGlobal::Instance().ap1(QString("Solution::Call")); sol.setAction(Solution::Call); } else { CGlobal::Instance().ap1(QString("Solution::Fold")); sol.setAction(Solution::Fold); } return sol; } Solution MindFLfull::mLooseOneRaise() { QString suited = hole_.suitedName(); QString nominal = hole_.nominalName(); QStringList limpRange; QStringList raiseRange; raiseRange << parseRangeList("99+,AKs,AQs,AKo,AQo"); limpRange << parseRangeList("22+,ATs+,KTs+,QJs,JTs"); Solution sol; //решение с учетом агрессивности оппов sol = pfrVpipSolution(); if (sol.action() != Solution::Nope) return sol; CGlobal::Instance().ap2(QString("Raise Range: %1").arg(raiseRange.join(", "))); CGlobal::Instance().ap2(QString("Limp Range: %1").arg(limpRange.join(", "))); if (raiseRange.contains(suited) || raiseRange.contains(nominal)) { CGlobal::Instance().ap1(QString("Solution::Raise")); sol.setAction(Solution::Raise); } else if (limpRange.contains(suited) || limpRange.contains(nominal)) { CGlobal::Instance().ap1(QString("Solution::Call")); sol.setAction(Solution::Call); } else { CGlobal::Instance().ap1(QString("Solution::Fold")); sol.setAction(Solution::Fold); } return sol; } Solution MindFLfull::mLooseMoreRaise() { QString suited = hole_.suitedName(); QString nominal = hole_.nominalName(); QStringList limpRange; QStringList raiseRange; raiseRange << parseRangeList("QQ+,AKs"); limpRange << parseRangeList("TT+,AJs+,KQs,AKo"); CGlobal::Instance().ap2(QString("Raise Range: %1").arg(raiseRange.join(", "))); CGlobal::Instance().ap2(QString("Limp Range: %1").arg(limpRange.join(", "))); Solution sol; if (raiseRange.contains(suited) || raiseRange.contains(nominal)) { CGlobal::Instance().ap1(QString("Solution::Raise")); sol.setAction(Solution::Raise); } else if (limpRange.contains(suited) || limpRange.contains(nominal)) { CGlobal::Instance().ap1(QString("Solution::Call")); sol.setAction(Solution::Call); } else { CGlobal::Instance().ap1(QString("Solution::Fold")); sol.setAction(Solution::Fold); } return sol; } // /* ----------Button, HJ Loose----------------- */ // Solution MindFLfull::buLoose() { Solution sol; if (raisers_ == 0) { CGlobal::Instance().ap2(QString("buLooseNoRaise()")); sol = buLooseNoRaise(); } else if (raisers_ == 1) { CGlobal::Instance().ap2(QString("buLooseOneRaise()")); sol = buLooseOneRaise(); } else if (raisers_ >= 1) { CGlobal::Instance().ap2(QString("buLooseMoreRaise()")); sol = buLooseMoreRaise(); } //учесть что рейзер может быть лузовым - тогда играть шире //также учесть как долго я не играю return sol; } Solution MindFLfull::buLooseNoRaise() { QString suited = hole_.suitedName(); QString nominal = hole_.nominalName(); QStringList limpRange; QStringList raiseRange; raiseRange << parseRangeList("88+,A8s+,K9s+,QTs+,JTs,AJo+,KQo"); limpRange << parseRangeList("22+,A2s+,K2s+,Q8s+,J7s+,ATo+,KTo+,QTo+,JTo,T9s," "98s,87s,76s,65s,54s,43s,T8s,97s,86s,75s,64s,53s"); CGlobal::Instance().ap2(QString("Raise Range: %1").arg(raiseRange.join(", "))); CGlobal::Instance().ap2(QString("Limp Range: %1").arg(limpRange.join(", "))); Solution sol; if (raiseRange.contains(suited) || raiseRange.contains(nominal)) { CGlobal::Instance().ap1(QString("Solution::Raise")); sol.setAction(Solution::Raise); } else if (limpRange.contains(suited) || limpRange.contains(nominal)) { CGlobal::Instance().ap1(QString("Solution::Call")); sol.setAction(Solution::Call); } else { CGlobal::Instance().ap1(QString("Solution::Fold")); sol.setAction(Solution::Fold); } return sol; } Solution MindFLfull::buLooseOneRaise() { if (limpers_ + raisers_ < 4) { CGlobal::Instance().ap1(QString("(limpers_ + raisers_ < 4) => buTightOneRaise()")); return buTightOneRaise(); } QString suited = hole_.suitedName(); QString nominal = hole_.nominalName(); QStringList limpRange; QStringList raiseRange; raiseRange << parseRangeList("TT+,AJs+,AKo,KQs"); limpRange << parseRangeList("22+,A2s+,KTs+,QTs+,JTs,T9s,98s,87s,76s,AKo,AQo"); Solution sol; //решение с учетом агрессивности оппов sol = pfrVpipSolution(); if (sol.action() != Solution::Nope) return sol; CGlobal::Instance().ap2(QString("Raise Range: %1").arg(raiseRange.join(", "))); CGlobal::Instance().ap2(QString("Limp Range: %1").arg(limpRange.join(", "))); if (raiseRange.contains(suited) || raiseRange.contains(nominal)) { CGlobal::Instance().ap1(QString("Solution::Raise")); sol.setAction(Solution::Raise); } else if (limpRange.contains(suited) || limpRange.contains(nominal)) { CGlobal::Instance().ap1(QString("Solution::Call")); sol.setAction(Solution::Call); } else { CGlobal::Instance().ap1(QString("Solution::Fold")); sol.setAction(Solution::Fold); } return sol; } Solution MindFLfull::buLooseMoreRaise() { QString suited = hole_.suitedName(); QString nominal = hole_.nominalName(); QStringList limpRange; QStringList raiseRange; raiseRange << parseRangeList("QQ+,AKs"); limpRange << parseRangeList("TT+,AJs+,AKo,KQs"); CGlobal::Instance().ap2(QString("Raise Range: %1").arg(raiseRange.join(", "))); CGlobal::Instance().ap2(QString("Limp Range: %1").arg(limpRange.join(", "))); Solution sol; if (raiseRange.contains(suited) || raiseRange.contains(nominal)) { CGlobal::Instance().ap1(QString("Solution::Raise")); sol.setAction(Solution::Raise); } else if (limpRange.contains(suited) || limpRange.contains(nominal)) { CGlobal::Instance().ap1(QString("Solution::Call")); sol.setAction(Solution::Call); } else { CGlobal::Instance().ap1(QString("Solution::Fold")); sol.setAction(Solution::Fold); } return sol; } // /* ----------SB Loose----------------- */ // Solution MindFLfull::sbLoose() { Solution sol; if (raisers_ == 0) { CGlobal::Instance().ap2(QString("sbLooseNoRaise()")); sol = sbLooseNoRaise(); } else if (raisers_ == 1) { CGlobal::Instance().ap2(QString("sbLooseOneRaise()")); sol = sbLooseOneRaise(); } else if (raisers_ >= 1) { CGlobal::Instance().ap2(QString("sbLooseMoreRaise()")); sol = sbLooseMoreRaise(); } //учесть что рейзер может быть лузовым - тогда играть шире //также учесть как долго я не играю return sol; } Solution MindFLfull::sbLooseNoRaise() { QString suited = hole_.suitedName(); QString nominal = hole_.nominalName(); QStringList limpRange; QStringList raiseRange; raiseRange << parseRangeList("99+,ATs+,KJs+,AQo+"); limpRange << parseRangeList("22+,A2s+,K2s+,Q8s+,J7s+,ATo+,KTo+,QTo+,JTo," "T9s,98s,87s,76s,65s,54s,43s,T8s,97s,86s,75s,64s,53s"); CGlobal::Instance().ap2(QString("Raise Range: %1").arg(raiseRange.join(", "))); CGlobal::Instance().ap2(QString("Limp Range: %1").arg(limpRange.join(", "))); Solution sol; if (raiseRange.contains(suited) || raiseRange.contains(nominal)) { CGlobal::Instance().ap1(QString("Solution::Raise")); sol.setAction(Solution::Raise); } else if (limpRange.contains(suited) || limpRange.contains(nominal)) { CGlobal::Instance().ap1(QString("Solution::Call")); sol.setAction(Solution::Call); } else if (hole_.isSuited()) { CGlobal::Instance().ap1(QString("hole_.isSuited() == true")); CGlobal::Instance().ap1(QString("Solution::Call")); sol.setAction(Solution::Call); } else { CGlobal::Instance().ap1(QString("Solution::Fold")); sol.setAction(Solution::Fold); } return sol; } Solution MindFLfull::sbLooseOneRaise() { QString suited = hole_.suitedName(); QString nominal = hole_.nominalName(); QStringList limpRange; QStringList raiseRange; raiseRange << parseRangeList("TT+,AJs+,AKo,KQs"); limpRange << parseRangeList("22+,ATs+,KTs+,AKo,AQo"); Solution sol; //решение с учетом агрессивности оппов sol = pfrVpipSolution(); if (sol.action() != Solution::Nope) return sol; CGlobal::Instance().ap2(QString("Raise Range: %1").arg(raiseRange.join(", "))); CGlobal::Instance().ap2(QString("Limp Range: %1").arg(limpRange.join(", "))); if (raiseRange.contains(suited) || raiseRange.contains(nominal)) { CGlobal::Instance().ap1(QString("Solution::Raise")); sol.setAction(Solution::Raise); } else if (limpRange.contains(suited) || limpRange.contains(nominal)) { CGlobal::Instance().ap1(QString("Solution::Call")); sol.setAction(Solution::Call); } else { CGlobal::Instance().ap1(QString("Solution::Fold")); sol.setAction(Solution::Fold); } return sol; } Solution MindFLfull::sbLooseMoreRaise() { QString suited = hole_.suitedName(); QString nominal = hole_.nominalName(); QStringList limpRange; QStringList raiseRange; raiseRange << parseRangeList("QQ+,AKs"); limpRange << parseRangeList("TT+,AJs+,KQs,AKo"); CGlobal::Instance().ap2(QString("Raise Range: %1").arg(raiseRange.join(", "))); CGlobal::Instance().ap2(QString("Limp Range: %1").arg(limpRange.join(", "))); Solution sol; if (raiseRange.contains(suited) || raiseRange.contains(nominal)) { CGlobal::Instance().ap1(QString("Solution::Raise")); sol.setAction(Solution::Raise); } else if (limpRange.contains(suited) || limpRange.contains(nominal)) { CGlobal::Instance().ap1(QString("Solution::Call")); sol.setAction(Solution::Call); } else { CGlobal::Instance().ap1(QString("Solution::Fold")); sol.setAction(Solution::Fold); } return sol; } // /* ----------BB Loose----------------- */ // Solution MindFLfull::bbLoose() { Solution sol; if (raisers_ == 0) { CGlobal::Instance().ap2(QString("bbLooseNoRaise()")); sol = bbLooseNoRaise(); } else if (raisers_ == 1) { CGlobal::Instance().ap2(QString("bbLooseOneRaise()")); sol = bbLooseOneRaise(); } else if (raisers_ > 1) { CGlobal::Instance().ap2(QString("bbLooseMoreRaise()")); sol = bbLooseMoreRaise(); } //учесть что рейзер может быть лузовым - тогда играть шире //также учесть как долго я не играю return sol; } Solution MindFLfull::bbLooseNoRaise() { QString suited = hole_.suitedName(); QString nominal = hole_.nominalName(); QStringList limpRange; QStringList raiseRange; raiseRange << parseRangeList("99+,ATs+,KJs+,AQo+"); CGlobal::Instance().ap2(QString("Raise Range: %1").arg(raiseRange.join(", "))); CGlobal::Instance().ap2(QString("Limp Range: %1").arg(limpRange.join(", "))); Solution sol; if (raiseRange.contains(suited) || raiseRange.contains(nominal)) { CGlobal::Instance().ap1(QString("Solution::Raise")); sol.setAction(Solution::Raise); } else { CGlobal::Instance().ap1(QString("Solution::Check")); sol.setAction(Solution::Check); } return sol; } Solution MindFLfull::bbLooseOneRaise() { QString suited = hole_.suitedName(); QString nominal = hole_.nominalName(); QStringList limpRange; QStringList raiseRange; raiseRange << parseRangeList("TT+,AJs+,AKo,KQs"); limpRange << parseRangeList("22+,ATs+,JTs,QTs+,KTs+,AJo+,KQo"); //решение с учетом агрессивности оппов Solution sol = pfrVpipSolution(); if (sol.action() != Solution::Nope) return sol; CGlobal::Instance().ap2(QString("Raise Range: %1").arg(raiseRange.join(", "))); CGlobal::Instance().ap2(QString("Limp Range: %1").arg(limpRange.join(", "))); if (raiseRange.contains(suited) || raiseRange.contains(nominal)) { CGlobal::Instance().ap1(QString("Solution::Raise")); sol.setAction(Solution::Raise); } else if (limpRange.contains(suited) || limpRange.contains(nominal)) { CGlobal::Instance().ap1(QString("Solution::Call")); sol.setAction(Solution::Call); } else { CGlobal::Instance().ap1(QString("Solution::Fold")); sol.setAction(Solution::Fold); } return sol; } Solution MindFLfull::bbLooseMoreRaise() { QString suited = hole_.suitedName(); QString nominal = hole_.nominalName(); QStringList limpRange; QStringList raiseRange; raiseRange << parseRangeList("QQ+,AKs"); limpRange << parseRangeList("TT+,AJs+,KQs,AKo"); CGlobal::Instance().ap2(QString("Raise Range: %1").arg(raiseRange.join(", "))); Solution sol; if (raiseRange.contains(suited) || raiseRange.contains(nominal)) { CGlobal::Instance().ap1(QString("Solution::Raise")); sol.setAction(Solution::Raise); } else if (limpRange.contains(suited) || limpRange.contains(nominal)) { CGlobal::Instance().ap1(QString("Solution::Call")); sol.setAction(Solution::Call); } else { CGlobal::Instance().ap1(QString("Solution::Fold")); sol.setAction(Solution::Fold); } return sol; } Solution MindFLfull::pfrVpipSolution() { //решение для одного рейзера //raisers_ == 1 QString suited = hole_.suitedName(); QString nominal = hole_.nominalName(); QStringList limpRange; QStringList raiseRange; CGlobal::Instance().ap2(QString("pfrVpipSolution()")); //кто рейзит qreal raiserVpip = 0., raiserPfr = 0.; QList<Opp> beforeLimp, afterLimp, raisers; bool after = false; foreach (Opp opp, oppList_) { if (opp.action() == Opp::Raise || opp.action() == Opp::Bet) { raiserVpip = opp.vpip(); raiserPfr = opp.pfr(); after = true; } else if (opp.action() == Opp::Call) { if (!after) { beforeLimp << opp; } else { afterLimp << opp; } } } CGlobal::Instance().ap1(QString("Raiser VPIP %1").arg(raiserVpip)); CGlobal::Instance().ap1(QString("Raiser PFR %1").arg(raiserPfr)); Solution sol; sol.setAction(Solution::Nope); //оценка опасности при которой нужна осторожность //опасность первая - опп который редко рейзит внезапно рейзанул //здесь нужно сваливать if (raiserPfr < PFR_PASSIVE) { CGlobal::Instance().ap1(QString("DANGER: raiserPfr < PFR_PASSIVE")); //88+,ATs+,KTs+,QJs,AJo+ raiseRange.clear(); limpRange.clear(); //здесь можно учесть позицию и тайтовость стола raiseRange << parseRangeList("QQ+,AKs"); if (raiseRange.contains(suited) || raiseRange.contains(nominal)) { CGlobal::Instance().ap1(QString("Solution::Raise")); sol.setAction(Solution::Raise); } else { CGlobal::Instance().ap1(QString("Solution::Fold")); sol.setAction(Solution::Fold); } return sol; } //опасность вторая //опп который редко лимпит колирует рейз raiseRange.clear(); limpRange.clear(); foreach (Opp opp, afterLimp) { if (opp.limp() < LIMP_PASSIVE) { CGlobal::Instance().ap1(QString("DANGER: opp.limp() < LIMP_PASSIVE")); raiseRange << parseRangeList("QQ+,AKs"); limpRange << parseRangeList("JJ+,AQs+"); if (raiseRange.contains(suited) || raiseRange.contains(nominal)) { CGlobal::Instance().ap1(QString("Solution::Raise")); sol.setAction(Solution::Raise); } else if (limpRange.contains(suited) || limpRange.contains(nominal)) { CGlobal::Instance().ap1(QString("Solution::Call")); sol.setAction(Solution::Call); } else { CGlobal::Instance().ap1(QString("Solution::Fold")); sol.setAction(Solution::Fold); } return sol; } } //оценка ситуации когда опасность не так велика //1) опп часто рейзит в принципе //при этом лимперов не больше двух и они все были до рейзера raiseRange.clear(); limpRange.clear(); if (raiserPfr > PFR_AGGRESIVE) { if (limpers_ <= 2) { //посмотреть насколько опасны лимперы после рейзера bool isLooseLimpers = true; foreach (Opp opp, afterLimp) { if (opp.vpip() < LOOSE) { isLooseLimpers = false; } } if (afterLimp.isEmpty() || isLooseLimpers) { CGlobal::Instance().ap1(QString("RELAX: raiserPfr > PFR_AGGRESIVE &&" " (limpers_ <= 2 && (afterLimp.isEmpty() || isLooseLimpers))")); //слегка расширим диапазон raiseRange << parseRangeList("JJ+,ATs+,KJs+,AQo+"); limpRange << parseRangeList("TT+,A9s+,KTs+,QTs+,AJo+,KQo"); if (raiseRange.contains(suited) || raiseRange.contains(nominal)) { CGlobal::Instance().ap1(QString("Solution::Raise")); sol.setAction(Solution::Raise); } else if (limpRange.contains(suited) || limpRange.contains(nominal)) { CGlobal::Instance().ap1(QString("Solution::Call")); sol.setAction(Solution::Call); } } return sol; } } //else if (raiserVpip > MANIAK ) //{ // CGlobal::Instance().ap1(QString("Raiser is MANIAK")); // raiseRange.clear(); // limpRange.clear(); // raiseRange << parseRangeList("88+,ATs+,KTs+,QJs,AJo+"); // limpRange << parseRangeList("55+,A5s+,K9s+,Q9s+,J9s+,T9s,A9o+,KTo+,QTo+,JTo"); //} //else if (raiserVpip > LOOSE) //{ // CGlobal::Instance().ap1(QString("Raiser is LOOSE")); // raiseRange.clear(); // limpRange.clear(); // raiseRange << parseRangeList("99+,ATs+,KTs+,AQo+"); // limpRange << parseRangeList("55+,A9s+,K9s+,QTs+,ATo+,KQo,QJo"); //} return sol; } // // FLOP // Solution MindFLfull::flopSolution() { QStringList board = proc_->board(); CGlobal::Instance().ap1(board.join(" ")); //proc_->save("sshot/acad_fr/flop/" + hole_.fullName() + ".bmp"); Solution sol; sol.setAction(Solution::Nope); return sol; } Solution MindFLfull::turnSolution() { return Solution(); } Solution MindFLfull::riverSolution() { return Solution(); }
6de1e1a8853ebab706a4f38b077f1166abbca884
f5b936c57a82a479983a2adc71c2abe7d6b3ec9b
/Codeforces/round431/b.cpp
4d017fcc6c075618605b3952cd6b565e27c8ace1
[]
no_license
FranciscoThiesen/OldProblems
002e2099fcb7f0c874f3d8927a60d1644521bbdf
809747fceb5a75127aae832697d6f91b63d234f5
refs/heads/master
2021-08-31T16:20:28.969377
2017-12-22T02:07:05
2017-12-22T02:07:05
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,132
cpp
b.cpp
/*input 5 1000000000 0 0 0 0 */ #include <bits/stdc++.h> using namespace std; #define fr(i,a,b) for(int (i) = (a); (i) < (b); ++(i)) #define rp(i,n) fr(i,0,n) #define fi first #define se second #define all(v) (v).begin(), (v).end() #define pb push_back #define mt make_tuple #define mp make_pair #define sz(a) (int)(a.size()) typedef unsigned long long ull; typedef long long ll; typedef pair<int, int> ii; typedef vector<int> vi; const int inf = 0x3f3f3f3f; const int neginf = 0xc0c0c0c0; bool ok(vector<pair<ll, ll> >& v, ll C1, ll C2, ll C3){ if(v.size() == 0) return false; if(v.size() <= 1) return true; else{ auto p1 = v[0]; auto p2 = v[1]; ll c1 = (p1.se - p2.se); ll c2 = (p2.fi - p1.fi); ll k = p1.fi * p2.se - p1.se * p2.fi; if(p1.se == p2.se){ c1 = 0; c2 = 1; k = -p2.se; } if((c1 == 0 && C1 != 0) || (c1 != 0 && C1 == 0)) return false; else if(c1 != 0 && C1 != 0){ if(c1*C2 != c2*C1) return false; } for(int i = 2; i < (int)v.size(); ++i){ if(v[i].fi * c1 + v[i].se * c2 + k != 0){ return false; } } } return true; } int main(){ int n; cin >> n; vector<pair<ll, ll> > pts; rp(i, n){ ll x; cin >> x; pts.pb(mp(i+1, x)); } rp(i, 1){ fr(j, i+1, n){ vector<pair<ll, ll> > nope; ll c1 = (pts[i].se - pts[j].se); ll c2 = (pts[j].fi - pts[i].fi); ll k = (pts[i].fi * pts[j].se - pts[i].se * pts[j].fi); if(pts[i].se == pts[j].se){ c1 = 0; c2 = 1; k = -pts[i].se; } rp(q, n){ if(pts[q].fi * c1 + pts[q].se * c2 + k != 0){ nope.pb(pts[q]); } } if(ok(nope, c1, c2, k)){ cout << "Yes" << endl; return 0; } } } rp(i, 2){ fr(j, i+1, n){ vector<pair<ll, ll> > nope; ll c1 = (pts[i].se - pts[j].se); ll c2 = (pts[j].fi - pts[i].fi); ll k = (pts[i].fi * pts[j].se - pts[i].se * pts[j].fi); if(pts[i].se == pts[j].se){ c1 = 0; c2 = 1; k = -pts[i].se; } rp(q, n){ if(pts[q].fi * c1 + pts[q].se * c2 + k != 0){ nope.pb(pts[q]); } } if(ok(nope, c1, c2, k)){ cout << "Yes" << endl; return 0; } } } cout << "No" << endl; return 0; }
7a27c1288f7266ef2dc94fcb51865e2f752de46b
3201e8242e06e563b80f467e5324112d36d1241e
/C++ lanuage/03_Function/0_defination.cpp
ed348b9766ffa91d4a10613905491a44b64bc2ad
[]
no_license
AnuragJiMahan/Code-Notes
14df238e4460cfb21de7b3137ca55fb675162f79
b27443cc355b229060079a610f515844994561c4
refs/heads/main
2023-09-02T07:34:34.184410
2021-11-21T11:30:20
2021-11-21T11:30:20
430,345,875
0
0
null
null
null
null
UTF-8
C++
false
false
317
cpp
0_defination.cpp
/*Function:- Function are two type in c++; 1. library function --> cout<<,clrscr(),gets()... 2. user difine function : user define function are four type in c++; 1. simple function 2. return function 3. parameter no return function 4. parameter with return function */ // 4===>all // 3--->1,3
ab287521aa2fac30e4a48d00668f66ced7a9eb65
647a494d78469d625e06e8872ea7c183d12505a5
/silly/src/comm.c
9db245dab65e3264cac0ec831fcea7ab9f7106cd
[ "BSD-4-Clause-UC", "MIT", "DOC" ]
permissive
okeuday/sillymud
df735f383fbc2daf3b39e6619896075e136c79f8
d94fbe39df8e5b3807ad049cc39d2d6f77926b25
refs/heads/master
2023-07-09T04:45:28.180595
2023-06-22T02:35:42
2023-06-22T02:35:42
16,369,185
8
2
null
2014-08-16T04:06:25
2014-01-30T05:28:13
C
UTF-8
C++
false
false
39,132
c
comm.c
/*-*-Mode:C;coding:utf-8;tab-width:8;c-basic-offset:2;indent-tabs-mode:()-*- * ex: set ft=cpp fenc=utf-8 sts=2 ts=8 sw=2 et: SillyMUD Distribution V1.1b (c) 1993 SillyMUD Developement See license.doc for distribution terms. SillyMUD is based on DIKUMUD */ #include <errno.h> #include <stdio.h> #include <stdlib.h> #include <ctype.h> #include <string.h> #include <strings.h> #include <time.h> #include <sys/types.h> #include <sys/socket.h> #include <sys/wait.h> #include <arpa/inet.h> #include <arpa/telnet.h> #include <netinet/in.h> #include <netdb.h> #include <sys/time.h> #include <fcntl.h> #include <sys/resource.h> #include <unistd.h> #include "protos.h" #define DFLT_PORT 4000 /* default port */ #define MAX_NAME_LENGTH 15 #define MAX_HOSTNAME 256 #if 1 #define OPT_USEC 250000 /* time delay corresponding to 4 passes/sec */ #else #if TITAN #define OPT_USEC 125000 /* lets see if this changes the lag any */ #else #define OPT_USEC 250000 /* time delay corresponding to 4 passes/sec */ #endif #endif #define STATE(d) ((d)->connected) extern int errno; extern char *sector_types[]; /* extern struct char_data *character_list; */ #if HASH extern struct hash_header room_db; /* In db.c */ #else extern struct room_data *room_db; /* In db.c */ #endif extern int top_of_world; /* In db.c */ extern struct time_info_data time_info; /* In db.c */ extern char help[]; extern char login[]; extern char *room_bits[]; struct descriptor_data *descriptor_list, *next_to_process; int lawful = 0; /* work like the game regulator */ int slow_death = 0; /* Shut her down, Martha, she's sucking mud */ int mudshutdown = 0; /* clean shutdown */ int reboot = 0; /* reboot the game after a shutdown */ int no_specials = 0; /* Suppress ass. of special routines */ long Uptime; /* time that the game has been up */ int pulse = 0; #if SITELOCK char hostlist[MAX_BAN_HOSTS][30]; /* list of sites to ban */ int numberhosts; #endif int maxdesc, avail_descs; int tics = 0; /* for extern checkpointing */ static unsigned char echo_on[] = {IAC, WONT, TELOPT_ECHO, '\r', '\n', '\0'}; static unsigned char echo_off[] = {IAC, WILL, TELOPT_ECHO, '\0'}; /* ********************************************************************* * main game loop and related stuff * ********************************************************************* */ int __main () { return(1); } /* jdb code - added to try to handle all the different ways the connections can die, and try to keep these 'invalid' sockets from getting to select */ int close_socket_fd( int desc) { struct descriptor_data *d; extern struct descriptor_data *descriptor_list; for (d = descriptor_list;d;d=d->next) { if (d->descriptor == desc) { close_socket(d); } } } int main (int argc, char **argv) { int cloudi = 0; /* run within CloudI */ int port, pos=1; char buf[512], *dir; extern int WizLock; port = DFLT_PORT; dir = DFLT_DIR; while ((pos < argc) && (*(argv[pos]) == '-')) { switch (*(argv[pos] + 1)) { case 'c': cloudi = 1; logE("CloudI mode selected."); break; case 'l': lawful = 1; logE("Lawful mode selected."); break; case 'd': if (*(argv[pos] + 2)) dir = argv[pos] + 2; else if (++pos < argc) dir = argv[pos]; else { logE("Directory arg expected after option -d."); assert(0); } break; case 's': no_specials = 1; logE("Suppressing assignment of special routines."); break; default: sprintf(buf, "Unknown option -% in argument string.", *(argv[pos] + 1)); logE(buf); break; } pos++; } if (pos < argc) if (!isdigit(*argv[pos])) { fprintf(stderr, "Usage: %s [-l] [-s] [-d pathname] [ port # ]\n", argv[0]); assert(0); } else if ((port = atoi(argv[pos])) <= 1024) { printf("Illegal port #\n"); assert(0); } Uptime = time(0); sprintf(buf, "Running game on port %d.", port); logE(buf); if (chdir(dir) < 0) { perror("chdir"); assert(0); } sprintf(buf, "Using %s as data directory.", dir); logE(buf); srandom(time(0)); WizLock = FALSE; #if SITELOCK log("Blanking denied hosts."); for(a = 0 ; a<= MAX_BAN_HOSTS ; a++) strcpy(hostlist[a]," \0\0\0\0"); numberhosts = 0; #if LOCKGROVE log("Locking out Host: oak.grove.iup.edu."); strcpy(hostlist[0],"oak.grove.iup.edu"); numberhosts = 1; log("Locking out Host: everest.rutgers.edu."); strcpy(hostlist[1],"everest.rutgers.edu"); numberhosts = 2; #endif /* LOCKGROVE */ #endif /* close stdin */ close(0); if (cloudi) run_the_game_with_cloudi(); else run_the_game(port); return(0); } #define PROFILE(x) /* Init sockets, run game, and cleanup sockets */ int run_the_game(int port) { int s; PROFILE(extern etext();) void signal_setup(void); int load(void); PROFILE(monstartup((int) 2, etext);) descriptor_list = NULL; logE("Signal trapping."); signal_setup(); logE("Opening mother connection."); s = init_socket(port); if (lawful && load() >= 6) { logE("System load too high at startup."); coma(1); } boot_db(); logE("Entering game loop."); game_loop(s); close_sockets(s); PROFILE(monitor(0);) if (reboot) { logE("Rebooting."); assert(52); /* what's so great about HHGTTG, anyhow? */ } logE("Normal termination of game."); } /* Accept new connects, relay commands, and call 'heartbeat-functs' */ int game_loop(int s) { fd_set input_set, output_set, exc_set; #if 0 fd_set tin, tout, tex; fd_set mtin, mtout, mtex; #endif static int cap; struct timeval last_time, now, timespent, timeout, null_time; static struct timeval opt_time; char comm[MAX_STRING_LENGTH]; char promptbuf[80]; struct descriptor_data *point, *next_point; struct room_data *rm; extern struct descriptor_data *descriptor_list; extern int pulse; extern int maxdesc; null_time.tv_sec = 0; null_time.tv_usec = 0; opt_time.tv_usec = OPT_USEC; /* Init time values */ opt_time.tv_sec = 0; gettimeofday(&last_time, (struct timezone *) 0); maxdesc = s; /* !! Change if more needed !! */ avail_descs = getdtablesize() -2; /* Main loop */ while (!mudshutdown) { /* Check what's happening out there */ FD_ZERO(&input_set); FD_ZERO(&output_set); FD_ZERO(&exc_set); FD_SET(s, &input_set); #if TITAN maxdesc = 0; if (cap < 20) cap = 20; for (point = descriptor_list; point; point = point->next) { if (point->descriptor <= cap && point->descriptor >= cap-20) { FD_SET(point->descriptor, &input_set); FD_SET(point->descriptor, &exc_set); FD_SET(point->descriptor, &output_set); } if (maxdesc < point->descriptor) maxdesc = point->descriptor; } if (cap > maxdesc) cap = 0; else cap += 20; #else for (point = descriptor_list; point; point = point->next) { FD_SET(point->descriptor, &input_set); FD_SET(point->descriptor, &exc_set); FD_SET(point->descriptor, &output_set); if (maxdesc < point->descriptor) maxdesc = point->descriptor; } #endif /* check out the time */ gettimeofday(&now, (struct timezone *) 0); timespent = timediff(&now, &last_time); timeout = timediff(&opt_time, &timespent); last_time.tv_sec = now.tv_sec + timeout.tv_sec; last_time.tv_usec = now.tv_usec + timeout.tv_usec; if (last_time.tv_usec >= 1000000) { last_time.tv_usec -= 1000000; last_time.tv_sec++; } signals_block(); if (select(maxdesc + 1, &input_set, &output_set, &exc_set, &null_time) < 0) { perror("Select poll"); /* one of the descriptors is broken... */ for (point = descriptor_list; point; point = next_point) { next_point = point->next; write_to_descriptor(point->descriptor, "\n\r"); } } if (select(0, (fd_set *) 0, (fd_set *) 0, (fd_set *) 0, &timeout) < 0) { perror("Select sleep"); /*assert(0);*/ } signals_unblock(); /* Respond to whatever might be happening */ /* New connection? */ if (FD_ISSET(s, &input_set)) if (new_descriptor(s) < 0) { perror("New connection"); } /* kick out the freaky folks */ for (point = descriptor_list; point; point = next_point) { next_point = point->next; if (FD_ISSET(point->descriptor, &exc_set)) { FD_CLR(point->descriptor, &input_set); FD_CLR(point->descriptor, &output_set); close_socket(point); } } for (point = descriptor_list; point; point = next_point) { next_point = point->next; if (FD_ISSET(point->descriptor, &input_set)) if (process_input(point) < 0) close_socket(point); } /* process_commands; */ for (point = descriptor_list; point; point = next_to_process){ next_to_process = point->next; if ((--(point->wait) <= 0) && get_from_q(&point->input, comm)) { if (point->character && point->connected == CON_PLYNG && point->character->specials.was_in_room != NOWHERE) { point->character->specials.was_in_room = NOWHERE; act("$n has returned.", TRUE, point->character, 0, 0, TO_ROOM); } point->wait = 1; if (point->character) point->character->specials.timer = 0; point->prompt_mode = 1; if (point->str) string_add(point, comm); else if (!point->connected) { if (point->showstr_point) show_string(point, comm); else command_interpreter(point->character, comm); } else if(point->connected == CON_EDITING) RoomEdit(point->character, comm); else nanny(point, comm); } } /* either they are out of the game */ /* or they want a prompt. */ for (point = descriptor_list; point; point = next_point) { next_point = point->next; if (FD_ISSET(point->descriptor, &output_set) && point->output.head) if (process_output(point) < 0) close_socket(point); else point->prompt_mode = 1; } /* give the people some prompts */ for (point = descriptor_list; point; point = point->next) if (point->prompt_mode) { if (point->str) write_to_descriptor(point->descriptor, "-> "); else if (!point->connected) if (point->showstr_point) write_to_descriptor(point->descriptor, "[Return to continue/Q to quit]"); else { struct char_data *ch; ch = point->character; if(point->character->term == VT100) { int update = 0; if(GET_MOVE(ch) != ch->last.move) { SET_BIT(update, INFO_MOVE); ch->last.move = GET_MOVE(ch); } if(GET_MAX_MOVE(ch) != ch->last.mmove) { SET_BIT(update, INFO_MOVE); ch->last.mmove = GET_MAX_MOVE(ch); } if(GET_HIT(ch) != ch->last.hit) { SET_BIT(update, INFO_HP); ch->last.hit = GET_HIT(ch); } if(GET_MAX_HIT(ch) != ch->last.mhit) { SET_BIT(update, INFO_HP); ch->last.mhit = GET_MAX_HIT(ch); } if(GET_MANA(ch) != ch->last.mana) { SET_BIT(update, INFO_MANA); ch->last.mana = GET_MANA(ch); } if(GET_MAX_MANA(ch) != ch->last.mmana) { SET_BIT(update, INFO_MANA); ch->last.mmana = GET_MAX_MANA(ch); } if(GET_GOLD(ch) != ch->last.gold) { SET_BIT(update, INFO_GOLD); ch->last.gold = GET_GOLD(ch); } if(GET_EXP(ch) != ch->last.exp) { SET_BIT(update, INFO_EXP); ch->last.exp = GET_EXP(ch); } if(update) UpdateScreen(ch, update); } if (point->character->term != VT100) { if (IS_IMMORTAL(point->character)) { rm = real_roomp(point->character->in_room); if (!rm) { char_to_room(point->character, 0); rm = real_roomp(point->character->in_room); } if(IS_SET(ch->specials.prompt, PROMPT_R)) { sprintf(promptbuf,"<Rm: %d ", rm->number); write_to_descriptor(point->descriptor, promptbuf); } if(IS_SET(ch->specials.prompt, PROMPT_S)) { sprinttype(rm->sector_type,sector_types,promptbuf); write_to_descriptor(point->descriptor, promptbuf); write_to_descriptor(point->descriptor, " "); } if(IS_SET(ch->specials.prompt, PROMPT_F)) { sprintbit((unsigned long)rm->room_flags,room_bits,promptbuf); write_to_descriptor(point->descriptor, promptbuf); } sprintf(promptbuf, "> "); write_to_descriptor(point->descriptor, promptbuf); } else { if(IS_SET(ch->specials.prompt, PROMPT_H)) { sprintf(promptbuf,"H:%d ", point->character->points.hit); write_to_descriptor(point->descriptor, promptbuf); } if(IS_SET(ch->specials.prompt, PROMPT_M)) { sprintf(promptbuf,"M:%d ", point->character->points.mana); write_to_descriptor(point->descriptor, promptbuf); } if(IS_SET(ch->specials.prompt, PROMPT_V)) { sprintf(promptbuf,"V:%d ", point->character->points.move); write_to_descriptor(point->descriptor, promptbuf); } sprintf(promptbuf, "> "); write_to_descriptor(point->descriptor, promptbuf); } } else { sprintf(promptbuf, "> "); write_to_descriptor(point->descriptor, promptbuf); } } point->prompt_mode = 0; } /* handle heartbeat stuff */ /* Note: pulse now changes every 1/4 sec */ pulse++; if (!(pulse % PULSE_ZONE)) { zone_update(); if (lawful) gr(s); } if (!(pulse % PULSE_RIVER)) { RiverPulseStuff(pulse); } if (!(pulse % PULSE_TELEPORT)) { TeleportPulseStuff(pulse); } if (!(pulse % PULSE_VIOLENCE)) perform_violence( pulse ); if (!(pulse % (SECS_PER_MUD_HOUR*4))){ weather_and_time(1); affect_update(pulse); /* things have been sped up by combining */ if ( time_info.hours == 1 ) update_time(); } if (pulse >= 2400) { pulse = 0; if (lawful) night_watchman(); check_reboot(); } tics++; /* tics since last checkpoint signal */ } } /* ****************************************************************** * general utility stuff (for local use) * ****************************************************************** */ int get_from_q(struct txt_q *queue, char *dest) { struct txt_block *tmp; /* Q empty? */ if (!queue->head) return(0); if (!dest) { log_sev("Sending message to null destination.", 5); return(0); } tmp = queue->head; if (dest && queue->head->text) { strncpy(dest, queue->head->text, MAX_STRING_LENGTH); dest[MAX_STRING_LENGTH - 1] = '\0'; } queue->head = queue->head->next; if (!queue->head) queue->tail = 0; free(tmp->text); free(tmp); return(1); } void write_to_q(char *txt, struct txt_q *queue) { struct txt_block *new; int strl; if (!queue) { logE("Output message to non-existant queue"); return; } CREATE(new, struct txt_block, 1); strl = strlen(txt); if (strl < 0 || strl > 15000) { logE("strlen returned bogus length in write_to_q"); free(new); return; } #if 0 /* Changed for test */ CREATE(new->text, char, strl+1); strcpy(new->text, txt); #else new->text = (char *)strdup(txt); #endif new->next = NULL; /* Q empty? */ if (!queue->head) { queue->head = queue->tail = new; } else { queue->tail->next = new; queue->tail = new; } } struct timeval timediff(struct timeval *a, struct timeval *b) { struct timeval rslt, tmp; tmp = *a; if ((rslt.tv_usec = tmp.tv_usec - b->tv_usec) < 0) { rslt.tv_usec += 1000000; --(tmp.tv_sec); } if ((rslt.tv_sec = tmp.tv_sec - b->tv_sec) < 0) { rslt.tv_usec = 0; rslt.tv_sec =0; } return(rslt); } /* Empty the queues before closing connection */ void flush_queues(struct descriptor_data *d) { char dummy[MAX_STRING_LENGTH]; while (get_from_q(&d->output, dummy)); while (get_from_q(&d->input, dummy)); } /* ****************************************************************** * socket handling * ****************************************************************** */ int init_socket(int port) { int s; char *opt; char hostname[MAX_HOSTNAME+1]; struct sockaddr_in sa; struct hostent *hp; struct linger ld; bzero(&sa, sizeof(struct sockaddr_in)); gethostname(hostname, MAX_HOSTNAME); hp = gethostbyname(hostname); if (hp == NULL) { perror("gethostbyname"); assert(0); } sa.sin_family = hp->h_addrtype; sa.sin_port = htons(port); s = socket(AF_INET, SOCK_STREAM, 0); if (s < 0) { perror("Init-socket"); assert(0); } if (setsockopt (s, SOL_SOCKET, SO_REUSEADDR, (char *) &opt, sizeof (opt)) < 0) { perror ("setsockopt REUSEADDR"); exit (1); } ld.l_onoff = 1; ld.l_linger = 100; if (setsockopt(s, SOL_SOCKET, SO_LINGER, &ld, sizeof(ld)) < 0) { perror("setsockopt LINGER"); assert(0); } if (bind(s, (struct sockaddr *)&sa, sizeof(sa)) < 0) { perror("bind"); exit(0); } listen(s, 5); return(s); } int new_connection(int s) { struct sockaddr_in isa; #ifdef sun struct sockaddr peer; #endif int i; int t; char buf[100]; i = sizeof(isa); #if 0 getsockname(s, &isa, &i); #endif if ((t = accept(s, (struct sockaddr *)&isa, &i)) < 0){ perror("Accept"); return(-1); } nonblock(t); #if 0 #ifdef sun i = sizeof(peer); if (!getpeername(t, &peer, &i)) { if (i > 0) { *(peer.sa_data + 49) = '\0'; sprintf(buf, "New connection from addr %s.", peer.sa_data); log(buf); } } #endif #endif return(t); } /* print an internet host address prettily */ static void printhost(addr, buf) struct in_addr *addr; char *buf; { struct hostent *h; char *s; h = gethostbyaddr(addr, sizeof(struct in_addr),AF_INET); s = (h==NULL) ? NULL : h->h_name; if (s) { strcpy(buf, s); } else { strcpy(buf, (const char *)inet_ntoa(*addr)); } } /* print an internet host address prettily */ static void printhostaddr(addr, buf) struct in_addr *addr; char *buf; { struct hostent *h; char *s; h = gethostbyaddr(addr, sizeof(*addr),AF_INET); s = (h==NULL) ? "1.1.1.1" : h->h_name; strcpy(buf, s); } int new_descriptor(int s) { int desc; struct descriptor_data *newd; int size; struct sockaddr_in sock; char buf[200]; if ((desc = new_connection(s)) < 0) return (-1); if ((desc + 1) >= 64) { struct descriptor_data *d; write_to_descriptor(desc, "Sorry.. The game is full. Try again later\n\r"); close(desc); for (d = descriptor_list; d; d = d->next) { if (!d->character) close_socket(d); } return(0); } else if (desc > maxdesc) maxdesc = desc; CREATE(newd, struct descriptor_data, 1); /* find info */ size = sizeof(sock); if (getpeername(desc, (struct sockaddr *) &sock, &size) < 0) { perror("getpeername"); newd->port = 0; *newd->host = '\0'; } else { newd->port = sock.sin_port; strncpy(newd->host, inet_ntoa(sock.sin_addr), 49); *(newd->host + 49) = '\0'; sprintf(buf, "New connection from addr %s: %d: %d", newd->host, desc, maxdesc); log_sev(buf,3); } /* init desc data */ newd->descriptor = desc; newd->connected = CON_NME; newd->close = 0; newd->wait = 1; newd->prompt_mode = 0; *newd->buf = '\0'; newd->str = 0; newd->showstr_head = 0; newd->showstr_point = 0; *newd->last_input= '\0'; newd->output.head = NULL; newd->input.head = NULL; newd->next = descriptor_list; newd->character = 0; newd->original = 0; newd->snoop.snooping = 0; newd->snoop.snoop_by = 0; /* prepend to list */ descriptor_list = newd; SEND_TO_Q(login, newd); SEND_TO_Q("What is thy name? ", newd); return(0); } int process_output(struct descriptor_data *t) { char i[MAX_STRING_LENGTH + MAX_STRING_LENGTH]; if (!t->prompt_mode && !t->connected) if (write_to_descriptor(t->descriptor, "\n\r") < 0) return(-1); /* Cycle thru output queue */ while (get_from_q(&t->output, i)) { if ((t->snoop.snoop_by) && (t->snoop.snoop_by->desc)) { write_to_q("% ",&t->snoop.snoop_by->desc->output); write_to_q(i,&t->snoop.snoop_by->desc->output); } if (write_to_descriptor(t->descriptor, i)) return(-1); } if (!t->connected && !(t->character && !IS_NPC(t->character) && IS_SET(t->character->specials.act, PLR_COMPACT))) if (write_to_descriptor(t->descriptor, "\n\r") < 0) return(-1); return(1); } int write_to_descriptor(int desc, char *txt) { int sofar, thisround, total; total = strlen(txt); sofar = 0; do { thisround = write(desc, txt + sofar, total - sofar); if (thisround < 0) { if (errno == EWOULDBLOCK) break; perror("Write to socket"); close_socket_fd(desc); return(-1); } sofar += thisround; } while (sofar < total); return(0); } int write_to_descriptor_echo_on(struct descriptor_data *d) { if (d->descriptor == 0) { /* disable for websocket connections SEND_TO_Q(echo_on, d); */ return 0; } return write(d->descriptor, echo_on, 6); } int write_to_descriptor_echo_off(struct descriptor_data *d) { if (d->descriptor == 0) { /* disable for websocket connections SEND_TO_Q(echo_off, d); */ return 0; } return write(d->descriptor, echo_off, 4); } int process_input(struct descriptor_data *t) { int sofar, thisround, begin, squelch, i, k, flag; char tmp[MAX_INPUT_LENGTH+2], buffer[MAX_INPUT_LENGTH + 60]; sofar = 0; flag = 0; begin = strlen(t->buf); /* Read in some stuff */ do { if ((thisround = read(t->descriptor, t->buf + begin + sofar, MAX_STRING_LENGTH - (begin + sofar) - 1)) > 0) { sofar += thisround; } else { if (thisround < 0) { if (errno != EWOULDBLOCK) { perror("Read1 - ERROR"); return(-1); } else { break; } } else { logE("EOF encountered on socket read."); return(-1); } } } while (!ISNEWL(*(t->buf + begin + sofar - 1))); *(t->buf + begin + sofar) = 0; /* if no newline is contained in input, return without proc'ing */ for (i = begin; !ISNEWL(*(t->buf + i)); i++) if (!*(t->buf + i)) return(0); /* input contains 1 or more newlines; process the stuff */ for (i = 0, k = 0; *(t->buf + i);) { if (!ISNEWL(*(t->buf + i)) && !(flag=(k>=(MAX_INPUT_LENGTH - 2)))) if (*(t->buf + i) == '\b') { /* backspace */ if (k) { /* more than one char ? */ if (*(tmp + --k) == '$') k--; i++; } else { i++; /* no or just one char.. Skip backsp */ } } else { if (isascii(*(t->buf + i)) && isprint(*(t->buf + i))) { /* trans char, double for '$' (printf) */ if ((*(tmp + k) = *(t->buf + i)) == '$') *(tmp + ++k) = '$'; k++; i++; } else { i++; } } else { *(tmp + k) = 0; if(*tmp == '!') strcpy(tmp,t->last_input); else strcpy(t->last_input,tmp); write_to_q(tmp, &t->input); if ((t->snoop.snoop_by) && (t->snoop.snoop_by->desc)){ write_to_q("% ",&t->snoop.snoop_by->desc->output); write_to_q(tmp,&t->snoop.snoop_by->desc->output); write_to_q("\n\r",&t->snoop.snoop_by->desc->output); } if (flag) { sprintf(buffer, "Line too long. Truncated to:\n\r%s\n\r", tmp); if (write_to_descriptor(t->descriptor, buffer) < 0) return(-1); /* skip the rest of the line */ for (; !ISNEWL(*(t->buf + i)); i++); } /* find end of entry */ for (; ISNEWL(*(t->buf + i)); i++); /* squelch the entry from the buffer */ for (squelch = 0;; squelch++) if ((*(t->buf + squelch) = *(t->buf + i + squelch)) == '\0') break; k = 0; i = 0; } } return(1); } void close_sockets(int s) { logE("Closing all sockets."); while (descriptor_list) close_socket(descriptor_list); close(s); } void close_socket(struct descriptor_data *d) { struct descriptor_data *tmp; char buf[100]; struct txt_block *txt, *txt2; void do_save(struct char_data *ch, char *argument, int cmd); if (!d) return; if (d->descriptor == 0) { d->close = 1; return; } close(d->descriptor); flush_queues(d); if (d->descriptor == maxdesc) --maxdesc; /* Forget snooping */ if (d->snoop.snooping) d->snoop.snooping->desc->snoop.snoop_by = 0; if (d->snoop.snoop_by) { send_to_char("Your victim is no longer among us.\n\r",d->snoop.snoop_by); d->snoop.snoop_by->desc->snoop.snooping = 0; } if (d->character) if (d->connected == CON_PLYNG) { do_save(d->character, "", 0); act("$n has lost $s link.", TRUE, d->character, 0, 0, TO_ROOM); sprintf(buf, "Closing link to: %s.", GET_NAME(d->character)); logE(buf); if (IS_NPC(d->character)) { /* poly, or switched god */ if (d->character->desc) d->character->orig = d->character->desc->original; } d->character->desc = 0; d->character->invis_level = LOW_IMMORTAL; if (!IS_AFFECTED(d->character, AFF_CHARM)) { if (d->character->master) { stop_follower(d->character); } } } else { if (GET_NAME(d->character)) { sprintf(buf, "Losing player: %s.", GET_NAME(d->character)); logE(buf); } free_char(d->character); } else logE("Losing descriptor without char."); if (next_to_process == d) /* to avoid crashing the process loop */ next_to_process = next_to_process->next; if (d == descriptor_list) /* this is the head of the list */ descriptor_list = descriptor_list->next; else /* This is somewhere inside the list */ { /* Locate the previous element */ for (tmp = descriptor_list; tmp && (tmp->next != d); tmp = tmp->next); if (tmp) tmp->next = d->next; else { /* die a slow death you motherfucking piece of shit machine */ /* :-) */ } } #if 0 if (d->showstr_head) /* this piece of code causes core dumps on */ free(d->showstr_head); /* ardent titans */ #endif /* free the input and output queues. */ txt = d->output.head; while(txt) { if (txt->text) { free(txt->text); txt2 = txt; txt = txt2->next; free(txt2); } } txt = d->input.head; while(txt) { if (txt->text) { free(txt->next); txt2 = txt; txt = txt->next; free(txt2); } } free(d); } void nonblock(int s) { if (fcntl(s, F_SETFL, O_NONBLOCK) == -1) { perror("Noblock"); assert(0); } } #define COMA_SIGN \ "\n\r\ DikuMUD is currently inactive due to excessive load on the host machine.\n\r\ Please try again later.\n\r\n\ \n\r\ Sadly,\n\r\ \n\r\ the DikuMUD system operators\n\r\n\r" /* sleep while the load is too high */ void coma(int s) { fd_set input_set; static struct timeval timeout = { 60, 0 }; int conn; int workhours(void); int load(void); logE("Entering comatose state."); signals_block(); while (descriptor_list) close_socket(descriptor_list); FD_ZERO(&input_set); do { FD_SET(s, &input_set); if (select(64, &input_set, 0, 0, &timeout) < 0){ perror("coma select"); assert(0); } if (FD_ISSET(s, &input_set)) { if (load() < 6){ logE("Leaving coma with visitor."); signals_clear(); return; } if ((conn = new_connection(s)) >= 0) { write_to_descriptor(conn, COMA_SIGN); sleep(2); close(conn); } } tics = 1; if (workhours()) { logE("Working hours collision during coma. Exit."); assert(0); } } while (load() >= 6); logE("Leaving coma."); signals_unblock(); } /* **************************************************************** * Public routines for system-to-player-communication * **************************************************************** */ void send_to_char(char *messg, struct char_data *ch) { if (ch) if (ch->desc && messg) write_to_q(messg, &ch->desc->output); } void save_all() { struct descriptor_data *i; for (i = descriptor_list; i; i = i->next) if (i->character) save_char(i->character,AUTO_RENT); } void send_to_all(char *messg) { struct descriptor_data *i; if (messg) for (i = descriptor_list; i; i = i->next) if (!i->connected) write_to_q(messg, &i->output); } void send_to_outdoor(char *messg) { struct descriptor_data *i; if (messg) for (i = descriptor_list; i; i = i->next) if (!i->connected) if (OUTSIDE(i->character) ) write_to_q(messg, &i->output); } void send_to_desert(char *messg) { struct descriptor_data *i; struct room_data *rp; extern struct zone_data *zone_table; if (messg) { for (i = descriptor_list; i; i = i->next) { if (!i->connected) { if (OUTSIDE(i->character)) { if ((rp = real_roomp(i->character->in_room))!=NULL) { if (IS_SET(zone_table[rp->zone].reset_mode, ZONE_DESERT) || rp->sector_type == SECT_DESERT) { write_to_q(messg, &i->output); } } } } } } } void send_to_out_other(char *messg) { struct descriptor_data *i; struct room_data *rp; extern struct zone_data *zone_table; if (messg) { for (i = descriptor_list; i; i = i->next) { if (!i->connected) { if (OUTSIDE(i->character)) { if ((rp = real_roomp(i->character->in_room))!=NULL) { if (!IS_SET(zone_table[rp->zone].reset_mode, ZONE_DESERT) && !IS_SET(zone_table[rp->zone].reset_mode, ZONE_ARCTIC) && rp->sector_type != SECT_DESERT) { write_to_q(messg, &i->output); } } } } } } } void send_to_arctic(char *messg) { struct descriptor_data *i; struct room_data *rp; extern struct zone_data *zone_table; if (messg) { for (i = descriptor_list; i; i = i->next) { if (!i->connected) { if (OUTSIDE(i->character)) { if ((rp = real_roomp(i->character->in_room))!=NULL) { if (IS_SET(zone_table[rp->zone].reset_mode, ZONE_ARCTIC)) { write_to_q(messg, &i->output); } } } } } } } void send_to_except(char *messg, struct char_data *ch) { struct descriptor_data *i; if (messg) for (i = descriptor_list; i; i = i->next) if (ch->desc != i && !i->connected) write_to_q(messg, &i->output); } void send_to_zone(char *messg, struct char_data *ch) { struct descriptor_data *i; if (messg) for (i = descriptor_list; i; i = i->next) if (ch->desc != i && !i->connected) if (real_roomp(i->character->in_room)->zone == real_roomp(ch->in_room)->zone) write_to_q(messg, &i->output); } void send_to_room(char *messg, int room) { struct char_data *i; if (messg) for (i = real_roomp(room)->people; i; i = i->next_in_room) if (i->desc) write_to_q(messg, &i->desc->output); } void send_to_room_except(char *messg, int room, struct char_data *ch) { struct char_data *i; if (messg) for (i = real_roomp(room)->people; i; i = i->next_in_room) if (i != ch && i->desc) write_to_q(messg, &i->desc->output); } void send_to_room_except_two (char *messg, int room, struct char_data *ch1, struct char_data *ch2) { struct char_data *i; if (messg) for (i = real_roomp(room)->people; i; i = i->next_in_room) if (i != ch1 && i != ch2 && i->desc) write_to_q(messg, &i->desc->output); } /* higher-level communication */ void act(char *str, int hide_invisible, struct char_data *ch, struct obj_data *obj, void *vict_obj, int type) { register char *strp, *point, *i; struct char_data *to; char buf[MAX_STRING_LENGTH]; if (!str) return; if (!*str) return; if (ch->in_room <= -1) return; /* can't do it. in room -1 */ if (type == TO_VICT) to = (struct char_data *) vict_obj; else if (type == TO_CHAR) to = ch; else to = real_roomp(ch->in_room)->people; for (; to; to = to->next_in_room) { if (to->desc && ((to != ch) || (type == TO_CHAR)) && (can_see(to, ch) || !hide_invisible) && AWAKE(to) && !((type == TO_NOTVICT)&&(to==(struct char_data *) vict_obj))){ for (strp = str, point = buf;;) if (*strp == '$') { switch (*(++strp)) { case 'n': i = PERS(ch, to); break; case 'N': i = PERS((struct char_data *) vict_obj, to); break; case 'm': i = HMHR(ch); break; case 'M': i = HMHR((struct char_data *) vict_obj); break; case 's': i = HSHR(ch); break; case 'S': i = HSHR((struct char_data *) vict_obj); break; case 'e': i = HSSH(ch); break; case 'E': i = HSSH((struct char_data *) vict_obj); break; case 'o': i = OBJN(obj, to); break; case 'O': i = OBJN((struct obj_data *) vict_obj, to); break; case 'p': i = OBJS(obj, to); break; case 'P': i = OBJS((struct obj_data *) vict_obj, to); break; case 'a': i = SANA(obj); break; case 'A': i = SANA((struct obj_data *) vict_obj); break; case 'T': i = (char *) vict_obj; break; case 'F': i = fname((char *) vict_obj); break; case '$': i = "$"; break; default: logE("Illegal $-code to act():"); logE(str); break; } while (*point = *(i++)) ++point; ++strp; } else if (!(*(point++) = *(strp++))) break; *(--point) = '\n'; *(++point) = '\r'; *(++point) = '\0'; write_to_q(CAP(buf), &to->desc->output); } if ((type == TO_VICT) || (type == TO_CHAR)) return; } } int raw_force_all( char *to_force) { struct descriptor_data *i; char buf[400]; for (i = descriptor_list; i; i = i->next) if (!i->connected) { sprintf(buf, "The game has forced you to '%s'.\n\r", to_force); send_to_char(buf, i->character); command_interpreter(i->character, to_force); } } void UpdateScreen(struct char_data *ch, int update) { char buf[255]; int size; size = ch->size; if(IS_SET(update, INFO_MANA)) { sprintf(buf, VT_CURSAVE); write_to_descriptor(ch->desc->descriptor, buf); sprintf(buf, VT_CURSPOS, size - 2, 7); write_to_descriptor(ch->desc->descriptor, buf); sprintf(buf, " "); write_to_descriptor(ch->desc->descriptor, buf); sprintf(buf, VT_CURSPOS, size - 2, 7); write_to_descriptor(ch->desc->descriptor, buf); sprintf(buf, "%d(%d)", GET_MANA(ch), GET_MAX_MANA(ch)); write_to_descriptor(ch->desc->descriptor, buf); sprintf(buf, VT_CURREST); write_to_descriptor(ch->desc->descriptor, buf); } if(IS_SET(update, INFO_MOVE)) { sprintf(buf, VT_CURSAVE); write_to_descriptor(ch->desc->descriptor, buf); sprintf(buf, VT_CURSPOS, size - 3, 58); write_to_descriptor(ch->desc->descriptor, buf); sprintf(buf, " "); write_to_descriptor(ch->desc->descriptor, buf); sprintf(buf, VT_CURSPOS, size - 3, 58); write_to_descriptor(ch->desc->descriptor, buf); sprintf(buf, "%d(%d)", GET_MOVE(ch), GET_MAX_MOVE(ch)); write_to_descriptor(ch->desc->descriptor, buf); sprintf(buf, VT_CURREST); write_to_descriptor(ch->desc->descriptor, buf); } if(IS_SET(update, INFO_HP)) { sprintf(buf, VT_CURSAVE); write_to_descriptor(ch->desc->descriptor, buf); sprintf(buf, VT_CURSPOS, size - 3, 13); write_to_descriptor(ch->desc->descriptor, buf); sprintf(buf, " "); write_to_descriptor(ch->desc->descriptor, buf); sprintf(buf, VT_CURSPOS, size - 3, 13); write_to_descriptor(ch->desc->descriptor, buf); sprintf(buf, "%d(%d)", GET_HIT(ch), GET_MAX_HIT(ch)); write_to_descriptor(ch->desc->descriptor, buf); sprintf(buf, VT_CURREST); write_to_descriptor(ch->desc->descriptor, buf); } if(IS_SET(update, INFO_GOLD)) { sprintf(buf, VT_CURSAVE); write_to_descriptor(ch->desc->descriptor, buf); sprintf(buf, VT_CURSPOS, size - 2, 47); write_to_descriptor(ch->desc->descriptor, buf); sprintf(buf, " "); write_to_descriptor(ch->desc->descriptor, buf); sprintf(buf, VT_CURSPOS, size - 2, 47); write_to_descriptor(ch->desc->descriptor, buf); sprintf(buf, "%d", GET_GOLD(ch)); write_to_descriptor(ch->desc->descriptor, buf); sprintf(buf, VT_CURREST); write_to_descriptor(ch->desc->descriptor, buf); } if(IS_SET(update, INFO_EXP)) { sprintf(buf, VT_CURSAVE); write_to_descriptor(ch->desc->descriptor, buf); sprintf(buf, VT_CURSPOS, size - 1, 20); write_to_descriptor(ch->desc->descriptor, buf); sprintf(buf, " "); write_to_descriptor(ch->desc->descriptor, buf); sprintf(buf, VT_CURSPOS, size - 1, 20); write_to_descriptor(ch->desc->descriptor, buf); sprintf(buf, "%d", GET_EXP(ch)); write_to_descriptor(ch->desc->descriptor, buf); sprintf(buf, VT_CURREST); write_to_descriptor(ch->desc->descriptor, buf); } } void InitScreen(struct char_data *ch) { char buf[255]; int size; size = ch->size; sprintf(buf, VT_HOMECLR); send_to_char(buf, ch); sprintf(buf, VT_MARGSET, 0, size - 5); send_to_char(buf, ch); sprintf(buf, VT_CURSPOS, size - 4, 1); send_to_char(buf, ch); sprintf(buf, "-===========================================================================-"); send_to_char(buf, ch); sprintf(buf, VT_CURSPOS, size - 3, 1); send_to_char(buf, ch); sprintf(buf, "Hit Points: "); send_to_char(buf, ch); sprintf(buf, VT_CURSPOS, size - 3, 40); send_to_char(buf, ch); sprintf(buf, "Movement Points: "); send_to_char(buf, ch); sprintf(buf, VT_CURSPOS, size - 2, 1); send_to_char(buf, ch); sprintf(buf, "Mana: "); send_to_char(buf, ch); sprintf(buf, VT_CURSPOS, size - 2, 40); send_to_char(buf, ch); sprintf(buf, "Gold: "); send_to_char(buf, ch); sprintf(buf, VT_CURSPOS, size - 1, 1); send_to_char(buf, ch); sprintf(buf, "Experience Points: "); send_to_char(buf, ch); ch->last.mana = GET_MANA(ch); ch->last.mmana = GET_MAX_MANA(ch); ch->last.hit = GET_HIT(ch); ch->last.mhit = GET_MAX_HIT(ch); ch->last.move = GET_MOVE(ch); ch->last.mmove = GET_MAX_MOVE(ch); ch->last.exp = GET_EXP(ch); ch->last.gold = GET_GOLD(ch); /* Update all of the info parts */ sprintf(buf, VT_CURSPOS, size - 3, 13); send_to_char(buf, ch); sprintf(buf, "%d(%d)", GET_HIT(ch), GET_MAX_HIT(ch)); send_to_char(buf, ch); sprintf(buf, VT_CURSPOS, size - 3, 58); send_to_char(buf, ch); sprintf(buf, "%d(%d)", GET_MOVE(ch), GET_MAX_MOVE(ch)); send_to_char(buf, ch); sprintf(buf, VT_CURSPOS, size - 2, 7); send_to_char(buf, ch); sprintf(buf, "%d(%d)", GET_MANA(ch), GET_MAX_MANA(ch)); send_to_char(buf, ch); sprintf(buf, VT_CURSPOS, size - 2, 47); send_to_char(buf, ch); sprintf(buf, "%d", GET_GOLD(ch)); send_to_char(buf, ch); sprintf(buf, VT_CURSPOS, size - 1, 20); send_to_char(buf, ch); sprintf(buf, "%d", GET_EXP(ch)); send_to_char(buf, ch); sprintf(buf, VT_CURSPOS, 0, 0); send_to_char(buf, ch); }
66f209839bee290a6bd45d2cf662fb9cd706adbc
803b3156ad1d29ad2d88e67fb7d7e66225efe06b
/CCBase/CCBase/CrimeCraft_MiniSDK/CrimeCraft/ACCCLTGameInfo.h
d5b931398195a846c62a1ba0ed270cdaa72ead12
[]
no_license
x4l4/HaveFun
892f12b354ddab88e31d3ea7c1c73a41f2f30f8b
58e9206d2561b6fc96f55e173b6cf776123ce58e
refs/heads/master
2020-03-13T20:24:17.730442
2018-04-28T09:45:36
2018-04-28T09:45:36
131,273,488
0
0
null
null
null
null
UTF-8
C++
false
false
9,931
h
ACCCLTGameInfo.h
///////////////////////////////////////////////////////////////////////////// // Unreal Engine MiniSDK Generator by uNrEaL // Game: CrimeCraft // File: ACCCLTGameInfo.h // Date: 06/16/2011 @ 05:19:40.938 ///////////////////////////////////////////////////////////////////////////// #ifdef _MSC_VER #pragma pack( push, 4 ) #endif struct ACCCLTGameInfo_execCheckWinner_Parms { int ReturnValue; // CPF_ReturnParm }; struct ACCCLTGameInfo_execCheckCLTGameEnd_Parms { unsigned long ReturnValue : 1; // CPF_ReturnParm }; struct ACCCLTGameInfo_execFindTeamWinner_Parms { int TeamID; class APawn* ReturnValue; // CPF_ReturnParm }; struct ACCCLTGameInfo_execEndGame_Parms { class APlayerReplicationInfo* Winner; struct FString Reason; }; struct ACCCLTGameInfo_execCheckEndGame_Parms { class APlayerReplicationInfo* Winner; struct FString Reason; unsigned long ReturnValue : 1; // CPF_ReturnParm }; struct ACCCLTGameInfo_execRatePlayerStart_Parms { void* P; unsigned char Team; class AController* Player; float ReturnValue; // CPF_ReturnParm }; struct ACCCLTGameInfo_execNeedSuddenDeath_Parms { unsigned long ReturnValue : 1; // CPF_ReturnParm }; struct ACCCLTGameInfo_eventScorePoint_Parms { TArray< class ACCInstancePawn* > ScorersList; class ACCCLTPoint* ThePoint; };// FUNC_Event struct ACCCLTGameInfo_eventSpawnNextPoint_Parms { };// FUNC_Event struct ACCCLTGameInfo_execTick_Parms { float DeltaTime; }; struct ACCCLTGameInfo_execStartMatch_Parms { }; struct ACCCLTGameInfo_execSetNextPoint_Parms { class ACCCLTPoint* NextPoint; }; struct ACCCLTGameInfo_execFindNextPoint_Parms { class ACCCLTPoint* ReturnValue; // CPF_ReturnParm }; struct ACCCLTGameInfo_eventPostBeginPlay_Parms { };// FUNC_Event struct ACCCLTGameInfo_eventInitGame_Parms { struct FString Options; struct FString ErrorMessage; // CPF_OutParm };// FUNC_Event // (0xD3C - 0xD64) class ACCCLTGameInfo : public ACCTeamInstanceGameInfo { public: TArray< class ACCCLTPoint* > CLTPointsList; // 0x0D3C (0x000C) class ACCCLTPoint* CurrPoint; // 0x0D48 (0x0004) class ACCCLTPoint* prevpoint; // 0x0D4C (0x0004) float PStartPointScore; // 0x0D50 (0x0004) int CapturePointScore; // 0x0D54 (0x0004) int CaptureKillScore; // 0x0D58 (0x0004) int DefendKillScore; // 0x0D5C (0x0004) int TeamCaptureScore; // 0x0D60 (0x0004) // RoundOver // MatchInProgress // MatchOver private: static UClass* ClassPointer; public: static UClass* StaticClass () { if ( !ClassPointer ) ClassPointer = UObject::FindClass( "Class CrimeCraft.CCCLTGameInfo" ); return ClassPointer; }; public: int CheckWinner () { static UFunction* pfnCheckWinner = NULL; if ( !pfnCheckWinner ) pfnCheckWinner = UObject::FindObject< UFunction >( "Function CrimeCraft.CCCLTGameInfo.CheckWinner" ); ACCCLTGameInfo_execCheckWinner_Parms CheckWinner_Parms; this->ProcessEvent( pfnCheckWinner, &CheckWinner_Parms, NULL ); return CheckWinner_Parms.ReturnValue; }; bool CheckCLTGameEnd () { static UFunction* pfnCheckCLTGameEnd = NULL; if ( !pfnCheckCLTGameEnd ) pfnCheckCLTGameEnd = UObject::FindObject< UFunction >( "Function CrimeCraft.CCCLTGameInfo.CheckCLTGameEnd" ); ACCCLTGameInfo_execCheckCLTGameEnd_Parms CheckCLTGameEnd_Parms; this->ProcessEvent( pfnCheckCLTGameEnd, &CheckCLTGameEnd_Parms, NULL ); return CheckCLTGameEnd_Parms.ReturnValue; }; class APawn* FindTeamWinner ( int TeamID ) { static UFunction* pfnFindTeamWinner = NULL; if ( !pfnFindTeamWinner ) pfnFindTeamWinner = UObject::FindObject< UFunction >( "Function CrimeCraft.CCCLTGameInfo.FindTeamWinner" ); ACCCLTGameInfo_execFindTeamWinner_Parms FindTeamWinner_Parms; FindTeamWinner_Parms.TeamID = TeamID; this->ProcessEvent( pfnFindTeamWinner, &FindTeamWinner_Parms, NULL ); return FindTeamWinner_Parms.ReturnValue; }; void EndGame ( class APlayerReplicationInfo* Winner, struct FString Reason ) { static UFunction* pfnEndGame = NULL; if ( !pfnEndGame ) pfnEndGame = UObject::FindObject< UFunction >( "Function CrimeCraft.CCCLTGameInfo.EndGame" ); ACCCLTGameInfo_execEndGame_Parms EndGame_Parms; EndGame_Parms.Winner = Winner; memcpy( &EndGame_Parms.Reason, &Reason, 0xC ); this->ProcessEvent( pfnEndGame, &EndGame_Parms, NULL ); }; bool CheckEndGame ( class APlayerReplicationInfo* Winner, struct FString Reason ) { static UFunction* pfnCheckEndGame = NULL; if ( !pfnCheckEndGame ) pfnCheckEndGame = UObject::FindObject< UFunction >( "Function CrimeCraft.CCCLTGameInfo.CheckEndGame" ); ACCCLTGameInfo_execCheckEndGame_Parms CheckEndGame_Parms; CheckEndGame_Parms.Winner = Winner; memcpy( &CheckEndGame_Parms.Reason, &Reason, 0xC ); this->ProcessEvent( pfnCheckEndGame, &CheckEndGame_Parms, NULL ); return CheckEndGame_Parms.ReturnValue; }; float RatePlayerStart ( void* P, unsigned char Team, class AController* Player ) { static UFunction* pfnRatePlayerStart = NULL; if ( !pfnRatePlayerStart ) pfnRatePlayerStart = UObject::FindObject< UFunction >( "Function CrimeCraft.CCCLTGameInfo.RatePlayerStart" ); ACCCLTGameInfo_execRatePlayerStart_Parms RatePlayerStart_Parms; RatePlayerStart_Parms.P = P; RatePlayerStart_Parms.Team = Team; RatePlayerStart_Parms.Player = Player; this->ProcessEvent( pfnRatePlayerStart, &RatePlayerStart_Parms, NULL ); return RatePlayerStart_Parms.ReturnValue; }; bool NeedSuddenDeath () { static UFunction* pfnNeedSuddenDeath = NULL; if ( !pfnNeedSuddenDeath ) pfnNeedSuddenDeath = UObject::FindObject< UFunction >( "Function CrimeCraft.CCCLTGameInfo.NeedSuddenDeath" ); ACCCLTGameInfo_execNeedSuddenDeath_Parms NeedSuddenDeath_Parms; this->ProcessEvent( pfnNeedSuddenDeath, &NeedSuddenDeath_Parms, NULL ); return NeedSuddenDeath_Parms.ReturnValue; }; void eventScorePoint ( TArray< class ACCInstancePawn* > ScorersList, class ACCCLTPoint* ThePoint ) { static UFunction* pfnScorePoint = NULL; if ( !pfnScorePoint ) pfnScorePoint = UObject::FindObject< UFunction >( "Function CrimeCraft.CCCLTGameInfo.ScorePoint" ); ACCCLTGameInfo_eventScorePoint_Parms ScorePoint_Parms; ScorePoint_Parms.ScorersList = ScorersList; ScorePoint_Parms.ThePoint = ThePoint; this->ProcessEvent( pfnScorePoint, &ScorePoint_Parms, NULL ); }; void eventSpawnNextPoint () { static UFunction* pfnSpawnNextPoint = NULL; if ( !pfnSpawnNextPoint ) pfnSpawnNextPoint = UObject::FindObject< UFunction >( "Function CrimeCraft.CCCLTGameInfo.SpawnNextPoint" ); ACCCLTGameInfo_eventSpawnNextPoint_Parms SpawnNextPoint_Parms; this->ProcessEvent( pfnSpawnNextPoint, &SpawnNextPoint_Parms, NULL ); }; void Tick ( float DeltaTime ) { static UFunction* pfnTick = NULL; if ( !pfnTick ) pfnTick = UObject::FindObject< UFunction >( "Function CrimeCraft.CCCLTGameInfo.Tick" ); ACCCLTGameInfo_execTick_Parms Tick_Parms; Tick_Parms.DeltaTime = DeltaTime; this->ProcessEvent( pfnTick, &Tick_Parms, NULL ); }; void StartMatch () { static UFunction* pfnStartMatch = NULL; if ( !pfnStartMatch ) pfnStartMatch = UObject::FindObject< UFunction >( "Function CrimeCraft.CCCLTGameInfo.StartMatch" ); ACCCLTGameInfo_execStartMatch_Parms StartMatch_Parms; this->ProcessEvent( pfnStartMatch, &StartMatch_Parms, NULL ); }; void SetNextPoint ( class ACCCLTPoint* NextPoint ) { static UFunction* pfnSetNextPoint = NULL; if ( !pfnSetNextPoint ) pfnSetNextPoint = UObject::FindObject< UFunction >( "Function CrimeCraft.CCCLTGameInfo.SetNextPoint" ); ACCCLTGameInfo_execSetNextPoint_Parms SetNextPoint_Parms; SetNextPoint_Parms.NextPoint = NextPoint; this->ProcessEvent( pfnSetNextPoint, &SetNextPoint_Parms, NULL ); }; class ACCCLTPoint* FindNextPoint () { static UFunction* pfnFindNextPoint = NULL; if ( !pfnFindNextPoint ) pfnFindNextPoint = UObject::FindObject< UFunction >( "Function CrimeCraft.CCCLTGameInfo.FindNextPoint" ); ACCCLTGameInfo_execFindNextPoint_Parms FindNextPoint_Parms; this->ProcessEvent( pfnFindNextPoint, &FindNextPoint_Parms, NULL ); return FindNextPoint_Parms.ReturnValue; }; void eventPostBeginPlay () { static UFunction* pfnPostBeginPlay = NULL; if ( !pfnPostBeginPlay ) pfnPostBeginPlay = UObject::FindObject< UFunction >( "Function CrimeCraft.CCCLTGameInfo.PostBeginPlay" ); ACCCLTGameInfo_eventPostBeginPlay_Parms PostBeginPlay_Parms; this->ProcessEvent( pfnPostBeginPlay, &PostBeginPlay_Parms, NULL ); }; void eventInitGame ( struct FString Options, struct FString* ErrorMessage ) { static UFunction* pfnInitGame = NULL; if ( !pfnInitGame ) pfnInitGame = UObject::FindObject< UFunction >( "Function CrimeCraft.CCCLTGameInfo.InitGame" ); ACCCLTGameInfo_eventInitGame_Parms InitGame_Parms; memcpy( &InitGame_Parms.Options, &Options, 0xC ); this->ProcessEvent( pfnInitGame, &InitGame_Parms, NULL ); if ( ErrorMessage ) memcpy( ErrorMessage, &InitGame_Parms.ErrorMessage, 0xC ); // CPF_OutParm }; }; UClass* ACCCLTGameInfo::ClassPointer = NULL; #ifdef _MSC_VER #pragma pack( pop ) #endif
a11e50292444b1090a1df4803569afea29577dc5
710f7d2951c7af722d8e8ea896c5e6733e155860
/zDataServer_X/zDataServer/zzzitem.h
9d47ad1c3c3a9d30315861f8be48c76fd1bf4e14
[]
no_license
lnsurgent/X-MU_Community_Server
5cda542a5cbd6d73ade156ca8354eeab2909da91
e576e30a0222789b2d02506569e5b435dd696e2f
refs/heads/master
2016-09-06T07:50:10.870481
2016-02-11T06:56:20
2016-02-11T06:56:20
29,187,243
12
8
null
2015-01-18T15:23:14
2015-01-13T11:40:29
C++
UHC
C++
false
false
4,937
h
zzzitem.h
#ifndef __ZZZITEM_H__ #define __ZZZITEM_H__ #include "ItemDef.h" class CItem { public : DWORD m_Number; char m_serial; short m_Type; short m_Level; BYTE m_Part; BYTE m_Class; bool m_TwoHand; BYTE m_AttackSpeed; BYTE m_WalkSpeed; WORD m_DamageMin; WORD m_DamageMax; BYTE m_SuccessfulBlocking; WORD m_Defense; WORD m_MagicDefense; BYTE m_Speed; WORD m_DamageMinOrigin; WORD m_DefenseOrigin; WORD m_Magic; //BYTE m_Durability; float m_Durability; WORD m_DurabilitySmall; float m_BaseDurability; BYTE m_SpecialNum; BYTE m_Special [MAX_ITEM_SPECIAL]; BYTE m_SpecialValue[MAX_ITEM_SPECIAL]; // 레벨 WORD m_RequireStrength; WORD m_RequireDexterity; WORD m_RequireEnergy; WORD m_RequireLevel; WORD m_RequireVitality; WORD m_RequireLeaderShip; WORD m_Leadership; BYTE m_RequireClass[MAX_CLASSTYPE]; BYTE m_Resistance[MAX_RESISTANCE]; int m_Value; DWORD m_SellMoney; // 팔때 값 DWORD m_BuyMoney; // 살때 값 int m_iPShopValue; int m_OldSellMoney; int m_OldBuyMoney; BYTE m_Option1; // 아이템 옵션 1 세팅되었는지? BYTE m_Option2; // 아이템 옵션 2 세팅되었는지? BYTE m_Option3; // 아이템 옵션 3 세팅되었는지? BYTE m_NewOption; // float m_DurabilityState[4]; float m_CurrentDurabilityState; BYTE m_SkillChange; BYTE m_QuestItem; BYTE m_SetOption; BYTE m_SetAddStat; bool m_IsValidItem; BYTE m_SkillResistance[MAX_RESISTANCE]; int m_IsLoadPetItemInfo; int m_PetItem_Level; int m_PetItem_Exp; public : CItem(); void Convert( int type, BYTE Option1=0, BYTE Option2=0, BYTE Option3=0, BYTE Attribute2=0, BYTE SetOption=0, BYTE DbVersion=3); void Value(); void OldValue(); BOOL GetSize(int &w, int &h); void Clear(); BOOL IsItem(); int IsSetItem(); int GetAddStatType(); void SetPetItemInfo(int petlevel, int petexp); BOOL AddPetItemExp(int petexp); int DecPetItemExp(int percent); void PetValue(); int PetItemLevelDown(int exp); int ItemDamageMin(); int ItemDefense(); BOOL IsClass(char aClass, int ChangeUP); char *GetName(); int GetLevel(void); void PlusSpecial(int *Value,int Special); void PlusSpecialPercent(int* Value,int Special, WORD Percent); void PlusSpecialPercentEx(int* Value, int SourceValue, int Special); void SetItemPlusSpecialStat(short* Value, int Special); int GetWeaponType(); void PlusSpecialSetRing(BYTE* Value); DWORD GetNumber(); int IsExtItem(); int IsExtLifeAdd(); int IsExtManaAdd(); int IsExtDamageMinus(); int IsExtDamageReflect(); int IsExtDefenseSuccessfull(); int IsExtMonsterMoney(); int IsExtExcellentDamage(); int IsExtAttackRate(); int IsExtAttackRate2(); int IsExtAttackSpeed(); int IsExtMonsterDieLife(); int IsExtMonsterDieMana(); int IsWingOpGetOnePercentDamage(); int IsWingOpGetLifeToMonster(); int IsWingOpGetManaToMoster(); int IsDinorantReduceAttackDamaege(); int IsFenrirIncLastAttackDamage(); int IsFenrirDecLastAttackDamage(); int SimpleDurabilityDown(int iDur); int DurabilityDown(int dur, int aIndex); int DurabilityDown2(int dur, int aIndex); int NormalWeaponDurabilityDown(int defence, int aIndex); int BowWeaponDurabilityDown(int defence, int aIndex); int StaffWeaponDurabilityDown(int defence, int aIndex); int ArmorDurabilityDown(int damagemin, int aIndex); int CheckDurabilityState(); }; class CPetItemExp { public: int m_DarkSpiritExpTable[52]; int m_DarkHorseExpTable[52]; public: CPetItemExp(); }; extern CPetItemExp gPetItemExp; extern int g_MaxItemIndexOfEachItemType[MAX_ITEM_INDEX]; extern int IsItem(int item_num); extern ITEM_ATTRIBUTE* GetItemAttr(int item_num); extern BOOL OpenItemScript(char *FileName); extern BOOL OpenItemNameScript(char* FileName); extern int ItemGetNumberMake(int type, int index ); extern void ItemGetSize(int index, int & width, int & height); extern void ItemByteConvert7(LPBYTE buf, CItem item[], int maxitem); extern void ItemByteConvert10(LPBYTE buf, CItem item[], int maxitem); extern void ItemByteConvert16(LPBYTE buf, CItem item[], int maxitem); extern void ItemByteConvert(LPBYTE buf, CItem item); extern void ItemByteConvert(LPBYTE buf, int type, BYTE Option1, BYTE Option2, BYTE Option3, BYTE level, BYTE dur, BYTE Noption, BYTE SetOption); extern int GetLevelItem(int type, int index, int level); extern BOOL zzzItemLevel(int type, int index, int level); extern int GetSerialItem(int type); extern void BufferItemtoConvert3(LPBYTE buf, int & type, BYTE & level, BYTE & op1, BYTE & op2, BYTE & op3, BYTE & dur); extern BOOL HasItemDurability(int index); extern int ItemGetDurability(int index, int itemLevel, int ExcellentItem, int SetItem); extern int ItemGetAttackDurability(int index); extern int ItemGetDefenseDurability(int index); extern float GetRepairItemRate(int index); extern float GetAllRepairItemRate(int index); extern void CalRepairRate( int itemtype, int itemsubtype, ITEM_ATTRIBUTE* p); #endif
c468e7bedb14d350ecc00ea3c433eb9a75558497
2f8d6f68b0926594177abd79d48462ef3d0595cc
/projectTrain/MyHOGSVM/main.cpp
285006431cd60cfb7864ad033ebd1c2073adf300
[]
no_license
pobin6/graduation_project
53fbd9ae5c2aee88596951b56543f0c06989605c
5cb765bca34762352542214eb6811ee58348419a
refs/heads/master
2021-09-15T00:52:50.564969
2018-05-23T03:58:13
2018-05-23T03:58:13
117,124,206
1
0
null
null
null
null
UTF-8
C++
false
false
7,281
cpp
main.cpp
#include <QCoreApplication> #include "cv.h" #include"cxcore.h" #include"highgui.h" #include <opencv2/core/core.hpp> #include <opencv2/highgui/highgui.hpp> #include <ml.h> using namespace std; using namespace cv; int test(int posSam[], int negSam[]); int train(int posSam[], int negSam[]); #define Posnum 240 //正样本个数 #define Negnum 120 //负样本个数 #define PosTrainnum 2160 //正样本个数 #define NegTrainnum 1080 //负样本个数 char classifierSavePath[256] = "pedestrianDetect-peopleFlow.txt"; int main(int argc, char *argv[]) { //posTestSam 测试正样本 //negTestSam 测试负样本 //posTrainSam 训练正样本 //negTrainSam 训练负样本 int posTestSam[Posnum],negTestSam[Negnum], posTrainSam[PosTrainnum], negTrainSam[NegTrainnum]; //posSam 所有正样本 negSam 所有负样本 int posSam[Posnum+PosTrainnum], negSam[Negnum+NegTrainnum]; //将所有正样本随机分为十份 int i; for(i=0; i<Posnum+PosTrainnum; i++) { posSam[i]=i; } for(i=0; i<Negnum+NegTrainnum; i++) { negSam[i]=i; } srand((unsigned)time(NULL)); for(i=0; i<Posnum+PosTrainnum; i++) { int r = rand() % (Posnum+PosTrainnum); int t = posSam[i]; posSam[i] = posSam[r]; posSam[r]=t; } //将所有负样本随机分为十份 for(i=0; i<Negnum+NegTrainnum; i++) { negSam[i]=i; } srand((unsigned)time(NULL)); for(i=0; i<Negnum+NegTrainnum; i++) { int r = rand() % (Negnum+NegTrainnum); int t = negSam[i]; negSam[i] = negSam[r]; negSam[r]=t; } //轮流十组数据,一组检验,九组训练 int n=0, m=0, x=0, y=0,j; for(i=0; i<10; i++) { for(j=0; j<Posnum+PosTrainnum; j++) { if(j>=Posnum*i&&j<Posnum*(i+1)) { posTestSam[n] = j+1; n++; } else { posTrainSam[m] = j+1; m++; } } for(j=0; j<Negnum+NegTrainnum; j++) { if( j>=Negnum*i && j<Negnum*(i+1) ) { negTestSam[x] = j+1; x++; } else { negTrainSam[y] = j+1; y++; } } int resTrain = train(posTrainSam, negTrainSam); if( resTrain==1 ) { int resTest = test(posTestSam, negTestSam); if( resTest==0 ) {cout<< "Test error!!!!" <<endl;break;} else {cout<< "the " << i << " group success" <<endl;} } else { cout<<"Train error!!!!"<<endl; break; } m=0, n=0, x=0, y=0; } system("pause"); return 0; } int test(int posSam[],int negSam[]) { // step 1: //训练数据的分类标记,即4类 char adpos[128],adneg[128]; HOGDescriptor hog(Size(64,64),Size(16,16),Size(8,8),Size(8,8),9);//利用构造函数,给对象赋值。 int DescriptorDim=1764;//HOG描述子的维数 Mat samFeatureMat, samLabelMat; samFeatureMat = Mat::zeros(1 , DescriptorDim, CV_32FC1); samLabelMat = Mat::zeros(1 , 1, CV_32FC1); CvSVM svm; svm.load(classifierSavePath); //依次读取正样本图片,生成HOG描述子 float P = 0; for (int i = 1;i <= Posnum ;i++) { sprintf(adpos, "../Train/pos/1 (%d).png", posSam[i-1]); Mat src = imread(adpos);//读取图片 if(src.data == NULL) { cout<<adpos<<endl; return 0; } vector<float> descriptors;//HOG描述子向量 hog.compute(src,descriptors,Size(8,8)); DescriptorDim = descriptors.size(); for(int j=0; j<DescriptorDim; j++) { samFeatureMat.at<float>(0,j) = descriptors[j]; } CvMat feature = samFeatureMat; float res = svm.predict(&feature); if(res>0) P+=1; } P=P/Posnum; cout << "Presult: " << P << endl; P=0; for (int i = 1;i <= Negnum ;i++) { sprintf(adneg, "../Train/neg/1 (%d).png", negSam[i-1]); Mat src = imread(adneg);//读取图片 if(src.data == NULL) { cout<<adneg<<endl; return 0; } vector<float> descriptors;//HOG描述子向量 hog.compute(src,descriptors,Size(8,8)); DescriptorDim = descriptors.size(); for(int j=0; j<DescriptorDim; j++) { samFeatureMat.at<float>(0,j) = descriptors[j]; } CvMat feature = samFeatureMat; float res = svm.predict(&feature); if(res<0) P+=1; } P/=Negnum; cout << "Nresult: " << P << endl; return 1; } int train(int posSam[],int negSam[]) { // step 1: //训练数据的分类标记,即4类 char adpos[128],adneg[128]; HOGDescriptor hog(Size(64,64),Size(16,16),Size(8,8),Size(8,8),9);//利用构造函数,给对象赋值。 int DescriptorDim=1764;//HOG描述子的维数 Mat samFeatureMat, samLabelMat; samFeatureMat = Mat::zeros(PosTrainnum + NegTrainnum , DescriptorDim, CV_32FC1); samLabelMat = Mat::zeros(PosTrainnum + NegTrainnum , 1, CV_32FC1); // //依次读取正样本图片,生成HOG描述子 //依次读取负样本图片,生成HOG描述子 for (int k=1; k<=NegTrainnum; k++) { sprintf(adneg, "../Train/neg/1 (%d).png", negSam[k-1]); Mat src = imread(adneg);//读取图片 cout<<adneg<<endl; if(src.data == NULL) { cout<<adneg<<endl; return 0; } vector<float> descriptors;//HOG描述子向量 hog.compute(src,descriptors,Size(16,16)); DescriptorDim = descriptors.size(); for(int l=0; l<DescriptorDim; l++) { samFeatureMat.at<float>(k+PosTrainnum-1,l) = descriptors[l]; samLabelMat.at<float>(k+PosTrainnum-1,0) = -1; } } cout<<"==============1"<<endl; for (int i = 1;i <= PosTrainnum ;i++) { sprintf(adpos, "../Train/pos/1 (%d).png", posSam[i-1]); Mat src = imread(adpos);//读取图片 if(src.data == NULL) { cout<<adpos<<endl; return 0; } vector<float> descriptors;//HOG描述子向量 hog.compute(src,descriptors,Size(16,16)); DescriptorDim = descriptors.size(); for(int j=0; j<DescriptorDim; j++) { samFeatureMat.at<float>(i-1,j) = descriptors[j]; samLabelMat.at<float>(i-1,0) = 1; } } cout<<"==============2"<<endl; // step 2: //训练参数设定 CvSVMParams params; params.svm_type = CvSVM::C_SVC; //SVM类型 params.kernel_type = CvSVM::LINEAR; //核函数的类型 //SVM训练过程的终止条件, max_iter:最大迭代次数 epsilon:结果的精确性 params.term_crit = cvTermCriteria(CV_TERMCRIT_ITER, 100, FLT_EPSILON ); // step 3: //启动训练过程 CvSVM svm; CvMat label = samLabelMat; CvMat feature = samFeatureMat; svm.train(&feature, &label, NULL,NULL, params); svm.save(classifierSavePath); return 1; }
6dc29e9d529416e747d67a25caf441c7a7dcbcb9
33a82980352cf366b9c288cf8a74d2740272d90b
/avstream/avscamera/sys/Synthesizer.cpp
2598f4693a722118cba8581d0f53e0b74309f250
[ "MS-PL" ]
permissive
microkatz/Windows-driver-samples
d249ecb8ab1be5a05bf8644ebeaca0bf13db1dad
98a43841cb18b034c7808bc570c47556e332df2f
refs/heads/master
2022-05-09T17:42:10.796047
2022-04-20T20:47:03
2022-04-20T20:47:03
161,238,613
2
0
MS-PL
2022-04-20T20:47:03
2018-12-10T21:28:00
C
UTF-8
C++
false
false
50,434
cpp
Synthesizer.cpp
/************************************************************************** A/V Stream Camera Sample Copyright (c) 2014, Microsoft Corporation. File: Synthesizer.cpp Abstract: This file contains the implementation of CSynthesizer. The base image synthesis and overlay class. These classes provide image synthesis (pixel, color-bar, etc...) onto buffers of various formats. Internally, all CSynthesizer objects represent a pixel as a 32 bit quantity with 8 bits per sample. The base CSynthesizer implements all rendering functionality with this assumption in mind. It simplifies rendering substantially and means we do not need to re- implement rendering functions for each format. Most end formats can be synthesized from this uncompressed format with overhead that is slightly worse than a copy. Color spaces are handled by using a rendering palette that is unique for each. History: created 04/14/2014 **************************************************************************/ #include "Common.h" /************************************************************************** PAGED CODE **************************************************************************/ #ifdef ALLOC_PRAGMA #pragma code_seg("PAGE") #endif // ALLOC_PRAGMA /************************************************************************** Constants **************************************************************************/ // // Standard definition of EIA-189-A color bars. The actual color definitions // are either in CRGB24Synthesizer or CYUVSynthesizer. // const COLOR CSynthesizer::m_ColorBars[8] = {MAGENTA, BLUE, GREEN, BLACK, WHITE, YELLOW, RED, CYAN }; // // Corner registration block colors. // const COLOR g_TopLeft = GREY; const COLOR g_TopRight = BLUE; const COLOR g_BotLeft = RED; const COLOR g_BotRight = GREEN; // // The following is an 8x8 bitmapped font for use in the text overlay // code. // const UCHAR CSynthesizer:: m_FontData [2][256][8] = { { {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, {0x7e, 0x81, 0xa5, 0x81, 0xbd, 0x99, 0x81, 0x7e}, {0x7e, 0xff, 0xdb, 0xff, 0xc3, 0xe7, 0xff, 0x7e}, {0x6c, 0xfe, 0xfe, 0xfe, 0x7c, 0x38, 0x10, 0x00}, {0x10, 0x38, 0x7c, 0xfe, 0x7c, 0x38, 0x10, 0x00}, {0x38, 0x7c, 0x38, 0xfe, 0xfe, 0x7c, 0x38, 0x7c}, {0x10, 0x10, 0x38, 0x7c, 0xfe, 0x7c, 0x38, 0x7c}, {0x00, 0x00, 0x18, 0x3c, 0x3c, 0x18, 0x00, 0x00}, {0xff, 0xff, 0xe7, 0xc3, 0xc3, 0xe7, 0xff, 0xff}, {0x00, 0x3c, 0x66, 0x42, 0x42, 0x66, 0x3c, 0x00}, {0xff, 0xc3, 0x99, 0xbd, 0xbd, 0x99, 0xc3, 0xff}, {0x0f, 0x07, 0x0f, 0x7d, 0xcc, 0xcc, 0xcc, 0x78}, {0x3c, 0x66, 0x66, 0x66, 0x3c, 0x18, 0x7e, 0x18}, {0x3f, 0x33, 0x3f, 0x30, 0x30, 0x70, 0xf0, 0xe0}, {0x7f, 0x63, 0x7f, 0x63, 0x63, 0x67, 0xe6, 0xc0}, {0x99, 0x5a, 0x3c, 0xe7, 0xe7, 0x3c, 0x5a, 0x99}, {0x80, 0xe0, 0xf8, 0xfe, 0xf8, 0xe0, 0x80, 0x00}, {0x02, 0x0e, 0x3e, 0xfe, 0x3e, 0x0e, 0x02, 0x00}, {0x18, 0x3c, 0x7e, 0x18, 0x18, 0x7e, 0x3c, 0x18}, {0x66, 0x66, 0x66, 0x66, 0x66, 0x00, 0x66, 0x00}, {0x7f, 0xdb, 0xdb, 0x7b, 0x1b, 0x1b, 0x1b, 0x00}, {0x3e, 0x63, 0x38, 0x6c, 0x6c, 0x38, 0xcc, 0x78}, {0x00, 0x00, 0x00, 0x00, 0x7e, 0x7e, 0x7e, 0x00}, {0x18, 0x3c, 0x7e, 0x18, 0x7e, 0x3c, 0x18, 0xff}, {0x18, 0x3c, 0x7e, 0x18, 0x18, 0x18, 0x18, 0x00}, {0x18, 0x18, 0x18, 0x18, 0x7e, 0x3c, 0x18, 0x00}, {0x00, 0x18, 0x0c, 0xfe, 0x0c, 0x18, 0x00, 0x00}, {0x00, 0x30, 0x60, 0xfe, 0x60, 0x30, 0x00, 0x00}, {0x00, 0x00, 0xc0, 0xc0, 0xc0, 0xfe, 0x00, 0x00}, {0x00, 0x24, 0x66, 0xff, 0x66, 0x24, 0x00, 0x00}, {0x00, 0x18, 0x3c, 0x7e, 0xff, 0xff, 0x00, 0x00}, {0x00, 0xff, 0xff, 0x7e, 0x3c, 0x18, 0x00, 0x00}, {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, {0x30, 0x78, 0x78, 0x30, 0x30, 0x00, 0x30, 0x00}, {0x6c, 0x6c, 0x6c, 0x00, 0x00, 0x00, 0x00, 0x00}, {0x6c, 0x6c, 0xfe, 0x6c, 0xfe, 0x6c, 0x6c, 0x00}, {0x30, 0x7c, 0xc0, 0x78, 0x0c, 0xf8, 0x30, 0x00}, {0x00, 0xc6, 0xcc, 0x18, 0x30, 0x66, 0xc6, 0x00}, {0x38, 0x6c, 0x38, 0x76, 0xdc, 0xcc, 0x76, 0x00}, {0x60, 0x60, 0xc0, 0x00, 0x00, 0x00, 0x00, 0x00}, {0x18, 0x30, 0x60, 0x60, 0x60, 0x30, 0x18, 0x00}, {0x60, 0x30, 0x18, 0x18, 0x18, 0x30, 0x60, 0x00}, {0x00, 0x66, 0x3c, 0xff, 0x3c, 0x66, 0x00, 0x00}, {0x00, 0x30, 0x30, 0xfc, 0x30, 0x30, 0x00, 0x00}, {0x00, 0x00, 0x00, 0x00, 0x00, 0x30, 0x30, 0x60}, {0x00, 0x00, 0x00, 0xfc, 0x00, 0x00, 0x00, 0x00}, {0x00, 0x00, 0x00, 0x00, 0x00, 0x30, 0x30, 0x00}, {0x06, 0x0c, 0x18, 0x30, 0x60, 0xc0, 0x80, 0x00}, {0x7c, 0xc6, 0xce, 0xde, 0xf6, 0xe6, 0x7c, 0x00}, {0x30, 0x70, 0x30, 0x30, 0x30, 0x30, 0xfc, 0x00}, {0x78, 0xcc, 0x0c, 0x38, 0x60, 0xcc, 0xfc, 0x00}, {0x78, 0xcc, 0x0c, 0x38, 0x0c, 0xcc, 0x78, 0x00}, {0x1c, 0x3c, 0x6c, 0xcc, 0xfe, 0x0c, 0x1e, 0x00}, {0xfc, 0xc0, 0xf8, 0x0c, 0x0c, 0xcc, 0x78, 0x00}, {0x38, 0x60, 0xc0, 0xf8, 0xcc, 0xcc, 0x78, 0x00}, {0xfc, 0xcc, 0x0c, 0x18, 0x30, 0x30, 0x30, 0x00}, {0x78, 0xcc, 0xcc, 0x78, 0xcc, 0xcc, 0x78, 0x00}, {0x78, 0xcc, 0xcc, 0x7c, 0x0c, 0x18, 0x70, 0x00}, {0x00, 0x30, 0x30, 0x00, 0x00, 0x30, 0x30, 0x00}, {0x00, 0x30, 0x30, 0x00, 0x00, 0x30, 0x30, 0x60}, {0x18, 0x30, 0x60, 0xc0, 0x60, 0x30, 0x18, 0x00}, {0x00, 0x00, 0xfc, 0x00, 0x00, 0xfc, 0x00, 0x00}, {0x60, 0x30, 0x18, 0x0c, 0x18, 0x30, 0x60, 0x00}, {0x78, 0xcc, 0x0c, 0x18, 0x30, 0x00, 0x30, 0x00}, {0x7c, 0xc6, 0xde, 0xde, 0xde, 0xc0, 0x78, 0x00}, {0x30, 0x78, 0xcc, 0xcc, 0xfc, 0xcc, 0xcc, 0x00}, {0xfc, 0x66, 0x66, 0x7c, 0x66, 0x66, 0xfc, 0x00}, {0x3c, 0x66, 0xc0, 0xc0, 0xc0, 0x66, 0x3c, 0x00}, {0xf8, 0x6c, 0x66, 0x66, 0x66, 0x6c, 0xf8, 0x00}, {0xfe, 0x62, 0x68, 0x78, 0x68, 0x62, 0xfe, 0x00}, {0xfe, 0x62, 0x68, 0x78, 0x68, 0x60, 0xf0, 0x00}, {0x3c, 0x66, 0xc0, 0xc0, 0xce, 0x66, 0x3e, 0x00}, {0xcc, 0xcc, 0xcc, 0xfc, 0xcc, 0xcc, 0xcc, 0x00}, {0x78, 0x30, 0x30, 0x30, 0x30, 0x30, 0x78, 0x00}, {0x1e, 0x0c, 0x0c, 0x0c, 0xcc, 0xcc, 0x78, 0x00}, {0xe6, 0x66, 0x6c, 0x78, 0x6c, 0x66, 0xe6, 0x00}, {0xf0, 0x60, 0x60, 0x60, 0x62, 0x66, 0xfe, 0x00}, {0xc6, 0xee, 0xfe, 0xfe, 0xd6, 0xc6, 0xc6, 0x00}, {0xc6, 0xe6, 0xf6, 0xde, 0xce, 0xc6, 0xc6, 0x00}, {0x38, 0x6c, 0xc6, 0xc6, 0xc6, 0x6c, 0x38, 0x00}, {0xfc, 0x66, 0x66, 0x7c, 0x60, 0x60, 0xf0, 0x00}, {0x78, 0xcc, 0xcc, 0xcc, 0xdc, 0x78, 0x1c, 0x00}, {0xfc, 0x66, 0x66, 0x7c, 0x6c, 0x66, 0xe6, 0x00}, {0x78, 0xcc, 0xe0, 0x70, 0x1c, 0xcc, 0x78, 0x00}, {0xfc, 0xb4, 0x30, 0x30, 0x30, 0x30, 0x78, 0x00}, {0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0xfc, 0x00}, {0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0x78, 0x30, 0x00}, {0xc6, 0xc6, 0xc6, 0xd6, 0xfe, 0xee, 0xc6, 0x00}, {0xc6, 0xc6, 0x6c, 0x38, 0x38, 0x6c, 0xc6, 0x00}, {0xcc, 0xcc, 0xcc, 0x78, 0x30, 0x30, 0x78, 0x00}, {0xfe, 0xc6, 0x8c, 0x18, 0x32, 0x66, 0xfe, 0x00}, {0x78, 0x60, 0x60, 0x60, 0x60, 0x60, 0x78, 0x00}, {0xc0, 0x60, 0x30, 0x18, 0x0c, 0x06, 0x02, 0x00}, {0x78, 0x18, 0x18, 0x18, 0x18, 0x18, 0x78, 0x00}, {0x10, 0x38, 0x6c, 0xc6, 0x00, 0x00, 0x00, 0x00}, {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff}, {0x30, 0x30, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00}, {0x00, 0x00, 0x78, 0x0c, 0x7c, 0xcc, 0x76, 0x00}, {0xe0, 0x60, 0x60, 0x7c, 0x66, 0x66, 0xdc, 0x00}, {0x00, 0x00, 0x78, 0xcc, 0xc0, 0xcc, 0x78, 0x00}, {0x1c, 0x0c, 0x0c, 0x7c, 0xcc, 0xcc, 0x76, 0x00}, {0x00, 0x00, 0x78, 0xcc, 0xfc, 0xc0, 0x78, 0x00}, {0x38, 0x6c, 0x60, 0xf0, 0x60, 0x60, 0xf0, 0x00}, {0x00, 0x00, 0x76, 0xcc, 0xcc, 0x7c, 0x0c, 0xf8}, {0xe0, 0x60, 0x6c, 0x76, 0x66, 0x66, 0xe6, 0x00}, {0x30, 0x00, 0x70, 0x30, 0x30, 0x30, 0x78, 0x00}, {0x0c, 0x00, 0x0c, 0x0c, 0x0c, 0xcc, 0xcc, 0x78}, {0xe0, 0x60, 0x66, 0x6c, 0x78, 0x6c, 0xe6, 0x00}, {0x70, 0x30, 0x30, 0x30, 0x30, 0x30, 0x78, 0x00}, {0x00, 0x00, 0xcc, 0xfe, 0xfe, 0xd6, 0xc6, 0x00}, {0x00, 0x00, 0xf8, 0xcc, 0xcc, 0xcc, 0xcc, 0x00}, {0x00, 0x00, 0x78, 0xcc, 0xcc, 0xcc, 0x78, 0x00}, {0x00, 0x00, 0xdc, 0x66, 0x66, 0x7c, 0x60, 0xf0}, {0x00, 0x00, 0x76, 0xcc, 0xcc, 0x7c, 0x0c, 0x1e}, {0x00, 0x00, 0xdc, 0x76, 0x66, 0x60, 0xf0, 0x00}, {0x00, 0x00, 0x7c, 0xc0, 0x78, 0x0c, 0xf8, 0x00}, {0x10, 0x30, 0x7c, 0x30, 0x30, 0x34, 0x18, 0x00}, {0x00, 0x00, 0xcc, 0xcc, 0xcc, 0xcc, 0x76, 0x00}, {0x00, 0x00, 0xcc, 0xcc, 0xcc, 0x78, 0x30, 0x00}, {0x00, 0x00, 0xc6, 0xd6, 0xfe, 0xfe, 0x6c, 0x00}, {0x00, 0x00, 0xc6, 0x6c, 0x38, 0x6c, 0xc6, 0x00}, {0x00, 0x00, 0xcc, 0xcc, 0xcc, 0x7c, 0x0c, 0xf8}, {0x00, 0x00, 0xfc, 0x98, 0x30, 0x64, 0xfc, 0x00}, {0x1c, 0x30, 0x30, 0xe0, 0x30, 0x30, 0x1c, 0x00}, {0x18, 0x18, 0x18, 0x00, 0x18, 0x18, 0x18, 0x00}, {0xe0, 0x30, 0x30, 0x1c, 0x30, 0x30, 0xe0, 0x00}, {0x76, 0xdc, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, {0x00, 0x10, 0x38, 0x6c, 0xc6, 0xc6, 0xfe, 0x00}, {0x78, 0xcc, 0xc0, 0xcc, 0x78, 0x18, 0x0c, 0x78}, {0x00, 0xcc, 0x00, 0xcc, 0xcc, 0xcc, 0x7e, 0x00}, {0x1c, 0x00, 0x78, 0xcc, 0xfc, 0xc0, 0x78, 0x00}, {0x7e, 0xc3, 0x3c, 0x06, 0x3e, 0x66, 0x3f, 0x00}, {0xcc, 0x00, 0x78, 0x0c, 0x7c, 0xcc, 0x7e, 0x00}, {0xe0, 0x00, 0x78, 0x0c, 0x7c, 0xcc, 0x7e, 0x00}, {0x30, 0x30, 0x78, 0x0c, 0x7c, 0xcc, 0x7e, 0x00}, {0x00, 0x00, 0x78, 0xc0, 0xc0, 0x78, 0x0c, 0x38}, {0x7e, 0xc3, 0x3c, 0x66, 0x7e, 0x60, 0x3c, 0x00}, {0xcc, 0x00, 0x78, 0xcc, 0xfc, 0xc0, 0x78, 0x00}, {0xe0, 0x00, 0x78, 0xcc, 0xfc, 0xc0, 0x78, 0x00}, {0xcc, 0x00, 0x70, 0x30, 0x30, 0x30, 0x78, 0x00}, {0x7c, 0xc6, 0x38, 0x18, 0x18, 0x18, 0x3c, 0x00}, {0xe0, 0x00, 0x70, 0x30, 0x30, 0x30, 0x78, 0x00}, {0xc6, 0x38, 0x6c, 0xc6, 0xfe, 0xc6, 0xc6, 0x00}, {0x30, 0x30, 0x00, 0x78, 0xcc, 0xfc, 0xcc, 0x00}, {0x1c, 0x00, 0xfc, 0x60, 0x78, 0x60, 0xfc, 0x00}, {0x00, 0x00, 0x7f, 0x0c, 0x7f, 0xcc, 0x7f, 0x00}, {0x3e, 0x6c, 0xcc, 0xfe, 0xcc, 0xcc, 0xce, 0x00}, {0x78, 0xcc, 0x00, 0x78, 0xcc, 0xcc, 0x78, 0x00}, {0x00, 0xcc, 0x00, 0x78, 0xcc, 0xcc, 0x78, 0x00}, {0x00, 0xe0, 0x00, 0x78, 0xcc, 0xcc, 0x78, 0x00}, {0x78, 0xcc, 0x00, 0xcc, 0xcc, 0xcc, 0x7e, 0x00}, {0x00, 0xe0, 0x00, 0xcc, 0xcc, 0xcc, 0x7e, 0x00}, {0x00, 0xcc, 0x00, 0xcc, 0xcc, 0x7c, 0x0c, 0xf8}, {0xc3, 0x18, 0x3c, 0x66, 0x66, 0x3c, 0x18, 0x00}, {0xcc, 0x00, 0xcc, 0xcc, 0xcc, 0xcc, 0x78, 0x00}, {0x18, 0x18, 0x7e, 0xc0, 0xc0, 0x7e, 0x18, 0x18}, {0x38, 0x6c, 0x64, 0xf0, 0x60, 0xe6, 0xfc, 0x00}, {0xcc, 0xcc, 0x78, 0xfc, 0x30, 0xfc, 0x30, 0x30}, {0xf8, 0xcc, 0xcc, 0xfa, 0xc6, 0xcf, 0xc6, 0xc7}, {0x0e, 0x1b, 0x18, 0x3c, 0x18, 0x18, 0xd8, 0x70}, {0x1c, 0x00, 0x78, 0x0c, 0x7c, 0xcc, 0x7e, 0x00}, {0x38, 0x00, 0x70, 0x30, 0x30, 0x30, 0x78, 0x00}, {0x00, 0x1c, 0x00, 0x78, 0xcc, 0xcc, 0x78, 0x00}, {0x00, 0x1c, 0x00, 0xcc, 0xcc, 0xcc, 0x7e, 0x00}, {0x00, 0xf8, 0x00, 0xf8, 0xcc, 0xcc, 0xcc, 0x00}, {0xfc, 0x00, 0xcc, 0xec, 0xfc, 0xdc, 0xcc, 0x00}, {0x3c, 0x6c, 0x6c, 0x3e, 0x00, 0x7e, 0x00, 0x00}, {0x38, 0x6c, 0x6c, 0x38, 0x00, 0x7c, 0x00, 0x00}, {0x30, 0x00, 0x30, 0x60, 0xc0, 0xcc, 0x78, 0x00}, {0x00, 0x00, 0x00, 0xfc, 0xc0, 0xc0, 0x00, 0x00}, {0x00, 0x00, 0x00, 0xfc, 0x0c, 0x0c, 0x00, 0x00}, {0xc3, 0xc6, 0xcc, 0xde, 0x33, 0x66, 0xcc, 0x0f}, {0xc3, 0xc6, 0xcc, 0xdb, 0x37, 0x6f, 0xcf, 0x03}, {0x18, 0x18, 0x00, 0x18, 0x18, 0x18, 0x18, 0x00}, {0x00, 0x33, 0x66, 0xcc, 0x66, 0x33, 0x00, 0x00}, {0x00, 0xcc, 0x66, 0x33, 0x66, 0xcc, 0x00, 0x00}, {0x22, 0x88, 0x22, 0x88, 0x22, 0x88, 0x22, 0x88}, {0x55, 0xaa, 0x55, 0xaa, 0x55, 0xaa, 0x55, 0xaa}, {0xdb, 0x77, 0xdb, 0xee, 0xdb, 0x77, 0xdb, 0xee}, {0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18}, {0x18, 0x18, 0x18, 0x18, 0xf8, 0x18, 0x18, 0x18}, {0x18, 0x18, 0xf8, 0x18, 0xf8, 0x18, 0x18, 0x18}, {0x36, 0x36, 0x36, 0x36, 0xf6, 0x36, 0x36, 0x36}, {0x00, 0x00, 0x00, 0x00, 0xfe, 0x36, 0x36, 0x36}, {0x00, 0x00, 0xf8, 0x18, 0xf8, 0x18, 0x18, 0x18}, {0x36, 0x36, 0xf6, 0x06, 0xf6, 0x36, 0x36, 0x36}, {0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36}, {0x00, 0x00, 0xfe, 0x06, 0xf6, 0x36, 0x36, 0x36}, {0x36, 0x36, 0xf6, 0x06, 0xfe, 0x00, 0x00, 0x00}, {0x36, 0x36, 0x36, 0x36, 0xfe, 0x00, 0x00, 0x00}, {0x18, 0x18, 0xf8, 0x18, 0xf8, 0x00, 0x00, 0x00}, {0x00, 0x00, 0x00, 0x00, 0xf8, 0x18, 0x18, 0x18}, {0x18, 0x18, 0x18, 0x18, 0x1f, 0x00, 0x00, 0x00}, {0x18, 0x18, 0x18, 0x18, 0xff, 0x00, 0x00, 0x00}, {0x00, 0x00, 0x00, 0x00, 0xff, 0x18, 0x18, 0x18}, {0x18, 0x18, 0x18, 0x18, 0x1f, 0x18, 0x18, 0x18}, {0x00, 0x00, 0x00, 0x00, 0xff, 0x00, 0x00, 0x00}, {0x18, 0x18, 0x18, 0x18, 0xff, 0x18, 0x18, 0x18}, {0x18, 0x18, 0x1f, 0x18, 0x1f, 0x18, 0x18, 0x18}, {0x36, 0x36, 0x36, 0x36, 0x37, 0x36, 0x36, 0x36}, {0x36, 0x36, 0x37, 0x30, 0x3f, 0x00, 0x00, 0x00}, {0x00, 0x00, 0x3f, 0x30, 0x37, 0x36, 0x36, 0x36}, {0x36, 0x36, 0xf7, 0x00, 0xff, 0x00, 0x00, 0x00}, {0x00, 0x00, 0xff, 0x00, 0xf7, 0x36, 0x36, 0x36}, {0x36, 0x36, 0x37, 0x30, 0x37, 0x36, 0x36, 0x36}, {0x00, 0x00, 0xff, 0x00, 0xff, 0x00, 0x00, 0x00}, {0x36, 0x36, 0xf7, 0x00, 0xf7, 0x36, 0x36, 0x36}, {0x18, 0x18, 0xff, 0x00, 0xff, 0x00, 0x00, 0x00}, {0x36, 0x36, 0x36, 0x36, 0xff, 0x00, 0x00, 0x00}, {0x00, 0x00, 0xff, 0x00, 0xff, 0x18, 0x18, 0x18}, {0x00, 0x00, 0x00, 0x00, 0xff, 0x36, 0x36, 0x36}, {0x36, 0x36, 0x36, 0x36, 0x3f, 0x00, 0x00, 0x00}, {0x18, 0x18, 0x1f, 0x18, 0x1f, 0x00, 0x00, 0x00}, {0x00, 0x00, 0x1f, 0x18, 0x1f, 0x18, 0x18, 0x18}, {0x00, 0x00, 0x00, 0x00, 0x3f, 0x36, 0x36, 0x36}, {0x36, 0x36, 0x36, 0x36, 0xff, 0x36, 0x36, 0x36}, {0x18, 0x18, 0xff, 0x18, 0xff, 0x18, 0x18, 0x18}, {0x18, 0x18, 0x18, 0x18, 0xf8, 0x00, 0x00, 0x00}, {0x00, 0x00, 0x00, 0x00, 0x1f, 0x18, 0x18, 0x18}, {0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff}, {0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff}, {0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0}, {0x0f, 0x0f, 0x0f, 0x0f, 0x0f, 0x0f, 0x0f, 0x0f}, {0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00}, {0x00, 0x00, 0x76, 0xdc, 0xc8, 0xdc, 0x76, 0x00}, {0x00, 0x78, 0xcc, 0xf8, 0xcc, 0xf8, 0xc0, 0xc0}, {0x00, 0xfc, 0xcc, 0xc0, 0xc0, 0xc0, 0xc0, 0x00}, {0x00, 0xfe, 0x6c, 0x6c, 0x6c, 0x6c, 0x6c, 0x00}, {0xfc, 0xcc, 0x60, 0x30, 0x60, 0xcc, 0xfc, 0x00}, {0x00, 0x00, 0x7e, 0xd8, 0xd8, 0xd8, 0x70, 0x00}, {0x00, 0x66, 0x66, 0x66, 0x66, 0x7c, 0x60, 0xc0}, {0x00, 0x76, 0xdc, 0x18, 0x18, 0x18, 0x18, 0x00}, {0xfc, 0x30, 0x78, 0xcc, 0xcc, 0x78, 0x30, 0xfc}, {0x38, 0x6c, 0xc6, 0xfe, 0xc6, 0x6c, 0x38, 0x00}, {0x38, 0x6c, 0xc6, 0xc6, 0x6c, 0x6c, 0xee, 0x00}, {0x1c, 0x30, 0x18, 0x7c, 0xcc, 0xcc, 0x78, 0x00}, {0x00, 0x00, 0x7e, 0xdb, 0xdb, 0x7e, 0x00, 0x00}, {0x06, 0x0c, 0x7e, 0xdb, 0xdb, 0x7e, 0x60, 0xc0}, {0x38, 0x60, 0xc0, 0xf8, 0xc0, 0x60, 0x38, 0x00}, {0x78, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0x00}, {0x00, 0xfc, 0x00, 0xfc, 0x00, 0xfc, 0x00, 0x00}, {0x30, 0x30, 0xfc, 0x30, 0x30, 0x00, 0xfc, 0x00}, {0x60, 0x30, 0x18, 0x30, 0x60, 0x00, 0xfc, 0x00}, {0x18, 0x30, 0x60, 0x30, 0x18, 0x00, 0xfc, 0x00}, {0x0e, 0x1b, 0x1b, 0x18, 0x18, 0x18, 0x18, 0x18}, {0x18, 0x18, 0x18, 0x18, 0x18, 0xd8, 0xd8, 0x70}, {0x30, 0x30, 0x00, 0xfc, 0x00, 0x30, 0x30, 0x00}, {0x00, 0x76, 0xdc, 0x00, 0x76, 0xdc, 0x00, 0x00}, {0x38, 0x6c, 0x6c, 0x38, 0x00, 0x00, 0x00, 0x00}, {0x00, 0x00, 0x00, 0x18, 0x18, 0x00, 0x00, 0x00}, {0x00, 0x00, 0x00, 0x00, 0x18, 0x00, 0x00, 0x00}, {0x0f, 0x0c, 0x0c, 0x0c, 0xec, 0x6c, 0x3c, 0x1c}, {0x78, 0x6c, 0x6c, 0x6c, 0x6c, 0x00, 0x00, 0x00}, {0x70, 0x18, 0x30, 0x60, 0x78, 0x00, 0x00, 0x00}, {0x00, 0x00, 0x3c, 0x3c, 0x3c, 0x3c, 0x00, 0x00}, {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00} }, { {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, {0x7e, 0x81, 0xa9, 0x8d, 0x8d, 0xa9, 0x81, 0x7e}, {0x7e, 0xff, 0xd7, 0xf3, 0xf3, 0xd7, 0xff, 0x7e}, {0x00, 0x70, 0xf8, 0xfc, 0x7e, 0xfc, 0xf8, 0x70}, {0x00, 0x10, 0x38, 0x7c, 0xfe, 0x7c, 0x38, 0x10}, {0x00, 0x18, 0x5d, 0xff, 0xff, 0xff, 0x5d, 0x18}, {0x00, 0x08, 0x1d, 0x3f, 0xff, 0x3f, 0x1d, 0x08}, {0x00, 0x00, 0x18, 0x3c, 0x3c, 0x18, 0x00, 0x00}, {0xff, 0xff, 0xe7, 0xc3, 0xc3, 0xe7, 0xff, 0xff}, {0x00, 0x3c, 0x66, 0x42, 0x42, 0x66, 0x3c, 0x00}, {0xff, 0xc3, 0x99, 0xbd, 0xbd, 0x99, 0xc3, 0xff}, {0xf0, 0xe0, 0xfe, 0xbf, 0x11, 0x11, 0x1f, 0x0e}, {0x00, 0x72, 0xfa, 0x8f, 0x8f, 0xfa, 0x72, 0x00}, {0xe0, 0xe0, 0xa0, 0xa0, 0xfe, 0xff, 0x07, 0x03}, {0xfc, 0xfe, 0xa6, 0xa0, 0xa0, 0xfe, 0xff, 0x03}, {0x99, 0x5a, 0x3c, 0xe7, 0xe7, 0x3c, 0x5a, 0x99}, {0x00, 0x10, 0x10, 0x38, 0x38, 0x7c, 0x7c, 0xfe}, {0x00, 0xfe, 0x7c, 0x7c, 0x38, 0x38, 0x10, 0x10}, {0x00, 0x24, 0x66, 0xff, 0xff, 0x66, 0x24, 0x00}, {0x00, 0xfa, 0xfa, 0x00, 0x00, 0xfa, 0xfa, 0x00}, {0xfe, 0xfe, 0x80, 0xfe, 0xfe, 0x90, 0xf0, 0x60}, {0x40, 0xc0, 0x9a, 0xbf, 0xa5, 0xfd, 0x5b, 0x02}, {0x00, 0x0e, 0x0e, 0x0e, 0x0e, 0x0e, 0x0e, 0x00}, {0x01, 0x29, 0x6d, 0xff, 0xff, 0x6d, 0x29, 0x01}, {0x00, 0x20, 0x60, 0xfe, 0xfe, 0x60, 0x20, 0x00}, {0x00, 0x08, 0x0c, 0xfe, 0xfe, 0x0c, 0x08, 0x00}, {0x00, 0x10, 0x38, 0x7c, 0x54, 0x10, 0x10, 0x10}, {0x00, 0x10, 0x10, 0x10, 0x54, 0x7c, 0x38, 0x10}, {0x00, 0x04, 0x04, 0x04, 0x04, 0x04, 0x3c, 0x3c}, {0x10, 0x38, 0x7c, 0x10, 0x10, 0x7c, 0x38, 0x10}, {0x0c, 0x1c, 0x3c, 0x7c, 0x7c, 0x3c, 0x1c, 0x0c}, {0x60, 0x70, 0x78, 0x7c, 0x7c, 0x78, 0x70, 0x60}, {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, {0x00, 0x00, 0x00, 0x60, 0xfa, 0xfa, 0x60, 0x00}, {0x00, 0x00, 0xe0, 0xe0, 0x00, 0xe0, 0xe0, 0x00}, {0x00, 0x28, 0xfe, 0xfe, 0x28, 0xfe, 0xfe, 0x28}, {0x00, 0x00, 0x48, 0x5c, 0xd6, 0xd6, 0x74, 0x24}, {0x00, 0x46, 0x66, 0x30, 0x18, 0x0c, 0x66, 0x62}, {0x00, 0x12, 0x5e, 0xec, 0xba, 0xf2, 0x5e, 0x0c}, {0x00, 0x00, 0x00, 0x00, 0x00, 0xc0, 0xe0, 0x20}, {0x00, 0x00, 0x00, 0x82, 0xc6, 0x7c, 0x38, 0x00}, {0x00, 0x00, 0x00, 0x38, 0x7c, 0xc6, 0x82, 0x00}, {0x10, 0x54, 0x7c, 0x38, 0x38, 0x7c, 0x54, 0x10}, {0x00, 0x00, 0x10, 0x10, 0x7c, 0x7c, 0x10, 0x10}, {0x00, 0x00, 0x00, 0x00, 0x06, 0x07, 0x01, 0x00}, {0x00, 0x00, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10}, {0x00, 0x00, 0x00, 0x00, 0x06, 0x06, 0x00, 0x00}, {0x00, 0x80, 0xc0, 0x60, 0x30, 0x18, 0x0c, 0x06}, {0x00, 0x7c, 0xfe, 0xb2, 0x9a, 0x8e, 0xfe, 0x7c}, {0x00, 0x00, 0x02, 0x02, 0xfe, 0xfe, 0x42, 0x02}, {0x00, 0x00, 0x66, 0xf6, 0x92, 0x9a, 0xce, 0x46}, {0x00, 0x00, 0x6c, 0xfe, 0x92, 0x92, 0xc6, 0x44}, {0x00, 0x0a, 0xfe, 0xfe, 0xca, 0x68, 0x38, 0x18}, {0x00, 0x00, 0x9c, 0xbe, 0xa2, 0xa2, 0xe6, 0xe4}, {0x00, 0x00, 0x0c, 0x9e, 0x92, 0xd2, 0x7e, 0x3c}, {0x00, 0x00, 0xe0, 0xf0, 0x9e, 0x8e, 0xc0, 0xc0}, {0x00, 0x00, 0x6c, 0xfe, 0x92, 0x92, 0xfe, 0x6c}, {0x00, 0x00, 0x78, 0xfc, 0x96, 0x92, 0xf2, 0x60}, {0x00, 0x00, 0x00, 0x00, 0x66, 0x66, 0x00, 0x00}, {0x00, 0x00, 0x00, 0x00, 0x66, 0x67, 0x01, 0x00}, {0x00, 0x00, 0x00, 0x82, 0xc6, 0x6c, 0x38, 0x10}, {0x00, 0x00, 0x24, 0x24, 0x24, 0x24, 0x24, 0x24}, {0x00, 0x00, 0x10, 0x38, 0x6c, 0xc6, 0x82, 0x00}, {0x00, 0x00, 0x60, 0xf0, 0x9a, 0x8a, 0xc0, 0x40}, {0x00, 0x78, 0xf8, 0xba, 0xba, 0x82, 0xfe, 0x7c}, {0x00, 0x00, 0x3e, 0x7e, 0xc8, 0xc8, 0x7e, 0x3e}, {0x00, 0x6c, 0xfe, 0x92, 0x92, 0xfe, 0xfe, 0x82}, {0x00, 0x44, 0xc6, 0x82, 0x82, 0xc6, 0x7c, 0x38}, {0x00, 0x38, 0x7c, 0xc6, 0x82, 0xfe, 0xfe, 0x82}, {0x00, 0xc6, 0x82, 0xba, 0x92, 0xfe, 0xfe, 0x82}, {0x00, 0xc0, 0x80, 0xb8, 0x92, 0xfe, 0xfe, 0x82}, {0x00, 0x4e, 0xce, 0x8a, 0x82, 0xc6, 0x7c, 0x38}, {0x00, 0x00, 0xfe, 0xfe, 0x10, 0x10, 0xfe, 0xfe}, {0x00, 0x00, 0x00, 0x82, 0xfe, 0xfe, 0x82, 0x00}, {0x00, 0x80, 0xfc, 0xfe, 0x82, 0x02, 0x0e, 0x0c}, {0x00, 0xc6, 0xee, 0x38, 0x10, 0xfe, 0xfe, 0x82}, {0x00, 0x0e, 0x06, 0x02, 0x82, 0xfe, 0xfe, 0x82}, {0x00, 0xfe, 0xfe, 0x70, 0x38, 0x70, 0xfe, 0xfe}, {0x00, 0xfe, 0xfe, 0x18, 0x30, 0x60, 0xfe, 0xfe}, {0x00, 0x38, 0x7c, 0xc6, 0x82, 0xc6, 0x7c, 0x38}, {0x00, 0x60, 0xf0, 0x90, 0x92, 0xfe, 0xfe, 0x82}, {0x00, 0x00, 0x7a, 0xfe, 0x8e, 0x84, 0xfc, 0x78}, {0x00, 0x66, 0xfe, 0x98, 0x90, 0xfe, 0xfe, 0x82}, {0x00, 0x00, 0x4c, 0xce, 0x9a, 0xb2, 0xf6, 0x64}, {0x00, 0x00, 0xc0, 0x82, 0xfe, 0xfe, 0x82, 0xc0}, {0x00, 0x00, 0xfe, 0xfe, 0x02, 0x02, 0xfe, 0xfe}, {0x00, 0x00, 0xf8, 0xfc, 0x06, 0x06, 0xfc, 0xf8}, {0x00, 0xfe, 0xfe, 0x0c, 0x18, 0x0c, 0xfe, 0xfe}, {0x00, 0xc2, 0xe6, 0x3c, 0x18, 0x3c, 0xe6, 0xc2}, {0x00, 0x00, 0xe0, 0xf2, 0x1e, 0x1e, 0xf2, 0xe0}, {0x00, 0xce, 0xe6, 0xb2, 0x9a, 0x8e, 0xc6, 0xe2}, {0x00, 0x00, 0x00, 0x82, 0x82, 0xfe, 0xfe, 0x00}, {0x00, 0x06, 0x0c, 0x18, 0x30, 0x60, 0xc0, 0x80}, {0x00, 0x00, 0x00, 0xfe, 0xfe, 0x82, 0x82, 0x00}, {0x00, 0x10, 0x30, 0x60, 0xc0, 0x60, 0x30, 0x10}, {0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01}, {0x00, 0x00, 0x00, 0x20, 0xe0, 0xc0, 0x00, 0x00}, {0x00, 0x02, 0x1e, 0x3c, 0x2a, 0x2a, 0x2e, 0x04}, {0x00, 0x0c, 0x1e, 0x12, 0x12, 0xfc, 0xfe, 0x82}, {0x00, 0x00, 0x14, 0x36, 0x22, 0x22, 0x3e, 0x1c}, {0x00, 0x02, 0xfe, 0xfc, 0x92, 0x12, 0x1e, 0x0c}, {0x00, 0x00, 0x18, 0x3a, 0x2a, 0x2a, 0x3e, 0x1c}, {0x00, 0x00, 0x40, 0xc0, 0x92, 0xfe, 0x7e, 0x12}, {0x00, 0x20, 0x3e, 0x1f, 0x25, 0x25, 0x3d, 0x19}, {0x00, 0x1e, 0x3e, 0x20, 0x10, 0xfe, 0xfe, 0x82}, {0x00, 0x00, 0x00, 0x02, 0xbe, 0xbe, 0x22, 0x00}, {0x00, 0x00, 0xbe, 0xbf, 0x01, 0x01, 0x07, 0x06}, {0x00, 0x22, 0x36, 0x1c, 0x08, 0xfe, 0xfe, 0x82}, {0x00, 0x00, 0x00, 0x02, 0xfe, 0xfe, 0x82, 0x00}, {0x00, 0x1e, 0x3e, 0x38, 0x1c, 0x18, 0x3e, 0x3e}, {0x00, 0x00, 0x1e, 0x3e, 0x20, 0x20, 0x3e, 0x3e}, {0x00, 0x00, 0x1c, 0x3e, 0x22, 0x22, 0x3e, 0x1c}, {0x00, 0x18, 0x3c, 0x24, 0x25, 0x1f, 0x3f, 0x21}, {0x00, 0x21, 0x3f, 0x1f, 0x25, 0x24, 0x3c, 0x18}, {0x00, 0x18, 0x38, 0x20, 0x32, 0x1e, 0x3e, 0x22}, {0x00, 0x00, 0x24, 0x2e, 0x2a, 0x2a, 0x3a, 0x12}, {0x00, 0x00, 0x24, 0x22, 0xfe, 0x7c, 0x20, 0x00}, {0x00, 0x02, 0x3e, 0x3c, 0x02, 0x02, 0x3e, 0x3c}, {0x00, 0x00, 0x38, 0x3c, 0x06, 0x06, 0x3c, 0x38}, {0x00, 0x3c, 0x3e, 0x0e, 0x1c, 0x0e, 0x3e, 0x3c}, {0x00, 0x22, 0x36, 0x1c, 0x08, 0x1c, 0x36, 0x22}, {0x00, 0x00, 0x3e, 0x3f, 0x05, 0x05, 0x3d, 0x39}, {0x00, 0x00, 0x26, 0x32, 0x3a, 0x2e, 0x26, 0x32}, {0x00, 0x00, 0x82, 0x82, 0xee, 0x7c, 0x10, 0x10}, {0x00, 0x00, 0x00, 0xee, 0xee, 0x00, 0x00, 0x00}, {0x00, 0x00, 0x10, 0x10, 0x7c, 0xee, 0x82, 0x82}, {0x00, 0x80, 0xc0, 0x40, 0xc0, 0x80, 0xc0, 0x40}, {0x00, 0x0e, 0x1e, 0x32, 0x62, 0x32, 0x1e, 0x0e}, {0x00, 0x00, 0x52, 0xdf, 0x8d, 0x89, 0xf9, 0x70}, {0x00, 0x02, 0x5e, 0x5e, 0x02, 0x02, 0x5e, 0x5c}, {0x00, 0x00, 0x98, 0xba, 0xaa, 0x2a, 0x3e, 0x1c}, {0x42, 0xde, 0xbe, 0xaa, 0xaa, 0xae, 0xc4, 0x40}, {0x00, 0x02, 0x9e, 0xbe, 0x2a, 0x2a, 0xae, 0x84}, {0x00, 0x02, 0x1e, 0x3e, 0x2a, 0xaa, 0xae, 0x84}, {0x00, 0x02, 0x1e, 0x3e, 0xea, 0xea, 0x2e, 0x04}, {0x00, 0x00, 0x02, 0x27, 0x25, 0x25, 0x3c, 0x18}, {0x40, 0xd8, 0xba, 0xaa, 0xaa, 0xbe, 0xdc, 0x40}, {0x00, 0x00, 0x98, 0xba, 0x2a, 0x2a, 0xbe, 0x9c}, {0x00, 0x00, 0x18, 0x3a, 0x2a, 0xaa, 0xbe, 0x9c}, {0x00, 0x00, 0x80, 0x82, 0x3e, 0x3e, 0xa2, 0x80}, {0x00, 0x40, 0xc2, 0xbe, 0xbe, 0xa2, 0xc0, 0x40}, {0x00, 0x00, 0x00, 0x02, 0x3e, 0xbe, 0xa2, 0x80}, {0x00, 0x9e, 0xbe, 0x68, 0x48, 0x68, 0xbe, 0x9e}, {0x00, 0x00, 0x0e, 0x1e, 0xd4, 0xd4, 0x1e, 0x0e}, {0x00, 0x00, 0xa2, 0xaa, 0xaa, 0x3e, 0x3e, 0x22}, {0x2a, 0x2a, 0x3e, 0x3e, 0x2a, 0x2a, 0x2e, 0x04}, {0x00, 0x92, 0xfe, 0xfe, 0x90, 0xd0, 0x7e, 0x3e}, {0x00, 0x00, 0x4c, 0xde, 0x92, 0x92, 0xde, 0x4c}, {0x00, 0x00, 0x4c, 0x5e, 0x12, 0x12, 0x5e, 0x4c}, {0x00, 0x00, 0x0c, 0x1e, 0x12, 0x52, 0x5e, 0x4c}, {0x00, 0x02, 0x5e, 0xde, 0x82, 0x82, 0xde, 0x5c}, {0x00, 0x02, 0x1e, 0x1e, 0x02, 0x42, 0x5e, 0x5c}, {0x00, 0x00, 0x5e, 0x5f, 0x05, 0x05, 0x5d, 0x59}, {0x80, 0x98, 0x3c, 0x66, 0x66, 0x3c, 0x98, 0x80}, {0x00, 0x00, 0xbc, 0xbe, 0x02, 0x02, 0xbe, 0xbc}, {0x00, 0x24, 0x24, 0xe7, 0xe7, 0x24, 0x3c, 0x18}, {0x00, 0x04, 0x66, 0xc2, 0x92, 0xfe, 0x7e, 0x16}, {0x00, 0x00, 0xd4, 0xf4, 0x3f, 0x3f, 0xf4, 0xd4}, {0x05, 0x1f, 0x6f, 0xf4, 0x90, 0x90, 0xff, 0xff}, {0x40, 0xc0, 0x90, 0xfe, 0x7f, 0x11, 0x03, 0x02}, {0x00, 0x02, 0x9e, 0xbe, 0xaa, 0x2a, 0x2e, 0x04}, {0x00, 0x00, 0x00, 0x82, 0xbe, 0xbe, 0x22, 0x00}, {0x00, 0x00, 0x4c, 0x5e, 0x52, 0x12, 0x1e, 0x0c}, {0x00, 0x02, 0x5e, 0x5e, 0x42, 0x02, 0x1e, 0x1c}, {0x00, 0x00, 0x0e, 0x5e, 0x50, 0x50, 0x5e, 0x5e}, {0x00, 0x00, 0xbe, 0xbe, 0x8c, 0x98, 0xbe, 0xbe}, {0x00, 0x14, 0xf4, 0xf4, 0x94, 0xf4, 0x64, 0x00}, {0x00, 0x00, 0x64, 0xf4, 0x94, 0xf4, 0x64, 0x00}, {0x00, 0x00, 0x04, 0x06, 0xa2, 0xb2, 0x1e, 0x0c}, {0x00, 0x00, 0x10, 0x10, 0x10, 0x10, 0x1c, 0x1c}, {0x00, 0x00, 0x1c, 0x1c, 0x10, 0x10, 0x10, 0x10}, {0x89, 0xdd, 0x77, 0x33, 0x18, 0x0c, 0xf6, 0xf2}, {0x9f, 0xdf, 0x6e, 0x36, 0x18, 0x0c, 0xf6, 0xf2}, {0x00, 0x00, 0x00, 0xde, 0xde, 0x00, 0x00, 0x00}, {0x44, 0x6c, 0x38, 0x10, 0x44, 0x6c, 0x38, 0x10}, {0x10, 0x38, 0x6c, 0x44, 0x10, 0x38, 0x6c, 0x44}, {0x00, 0xaa, 0x00, 0x55, 0x00, 0xaa, 0x00, 0x55}, {0xaa, 0x55, 0xaa, 0x55, 0xaa, 0x55, 0xaa, 0x55}, {0xee, 0xff, 0x55, 0xbb, 0xee, 0x55, 0xff, 0xbb}, {0x00, 0x00, 0x00, 0xff, 0xff, 0x00, 0x00, 0x00}, {0x00, 0x00, 0x00, 0xff, 0xff, 0x08, 0x08, 0x08}, {0x00, 0x00, 0x00, 0xff, 0xff, 0x28, 0x28, 0x28}, {0x00, 0xff, 0xff, 0x00, 0xff, 0xff, 0x08, 0x08}, {0x00, 0x0f, 0x0f, 0x08, 0x0f, 0x0f, 0x08, 0x08}, {0x00, 0x00, 0x00, 0x3f, 0x3f, 0x28, 0x28, 0x28}, {0x00, 0xff, 0xff, 0x00, 0xef, 0xef, 0x28, 0x28}, {0x00, 0xff, 0xff, 0x00, 0xff, 0xff, 0x00, 0x00}, {0x00, 0x3f, 0x3f, 0x20, 0x2f, 0x2f, 0x28, 0x28}, {0x00, 0xf8, 0xf8, 0x08, 0xe8, 0xe8, 0x28, 0x28}, {0x00, 0xf8, 0xf8, 0x08, 0xf8, 0xf8, 0x08, 0x08}, {0x00, 0x00, 0x00, 0xf8, 0xf8, 0x28, 0x28, 0x28}, {0x00, 0x00, 0x00, 0x0f, 0x0f, 0x08, 0x08, 0x08}, {0x08, 0x08, 0x08, 0xf8, 0xf8, 0x00, 0x00, 0x00}, {0x08, 0x08, 0x08, 0xf8, 0xf8, 0x08, 0x08, 0x08}, {0x08, 0x08, 0x08, 0x0f, 0x0f, 0x08, 0x08, 0x08}, {0x08, 0x08, 0x08, 0xff, 0xff, 0x00, 0x00, 0x00}, {0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08}, {0x08, 0x08, 0x08, 0xff, 0xff, 0x08, 0x08, 0x08}, {0x28, 0x28, 0x28, 0xff, 0xff, 0x00, 0x00, 0x00}, {0x08, 0xff, 0xff, 0x00, 0xff, 0xff, 0x00, 0x00}, {0x28, 0xe8, 0xe8, 0x08, 0xf8, 0xf8, 0x00, 0x00}, {0x28, 0x2f, 0x2f, 0x20, 0x3f, 0x3f, 0x00, 0x00}, {0x28, 0xe8, 0xe8, 0x08, 0xe8, 0xe8, 0x28, 0x28}, {0x28, 0x2f, 0x2f, 0x20, 0x2f, 0x2f, 0x28, 0x28}, {0x28, 0xef, 0xef, 0x00, 0xff, 0xff, 0x00, 0x00}, {0x28, 0x28, 0x28, 0x28, 0x28, 0x28, 0x28, 0x28}, {0x28, 0xef, 0xef, 0x00, 0xef, 0xef, 0x28, 0x28}, {0x28, 0x28, 0x28, 0xe8, 0xe8, 0x28, 0x28, 0x28}, {0x08, 0xf8, 0xf8, 0x08, 0xf8, 0xf8, 0x08, 0x08}, {0x28, 0x28, 0x28, 0x2f, 0x2f, 0x28, 0x28, 0x28}, {0x08, 0x0f, 0x0f, 0x08, 0x0f, 0x0f, 0x08, 0x08}, {0x08, 0xf8, 0xf8, 0x08, 0xf8, 0xf8, 0x00, 0x00}, {0x28, 0x28, 0x28, 0xf8, 0xf8, 0x00, 0x00, 0x00}, {0x28, 0x28, 0x28, 0x3f, 0x3f, 0x00, 0x00, 0x00}, {0x08, 0x0f, 0x0f, 0x08, 0x0f, 0x0f, 0x00, 0x00}, {0x08, 0xff, 0xff, 0x08, 0xff, 0xff, 0x08, 0x08}, {0x28, 0x28, 0x28, 0xff, 0xff, 0x28, 0x28, 0x28}, {0x00, 0x00, 0x00, 0xf8, 0xf8, 0x08, 0x08, 0x08}, {0x08, 0x08, 0x08, 0x0f, 0x0f, 0x00, 0x00, 0x00}, {0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff}, {0x0f, 0x0f, 0x0f, 0x0f, 0x0f, 0x0f, 0x0f, 0x0f}, {0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff}, {0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00}, {0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0, 0xf0}, {0x00, 0x22, 0x36, 0x1c, 0x36, 0x22, 0x3e, 0x1c}, {0x00, 0x00, 0x28, 0x7c, 0x54, 0x54, 0x7f, 0x3f}, {0x00, 0x00, 0x60, 0x60, 0x40, 0x40, 0x7e, 0x7e}, {0x00, 0x40, 0x7e, 0x7e, 0x40, 0x7e, 0x7e, 0x40}, {0x00, 0x00, 0xc6, 0xc6, 0x92, 0xba, 0xee, 0xc6}, {0x00, 0x20, 0x20, 0x3c, 0x3e, 0x22, 0x3e, 0x1c}, {0x00, 0x78, 0x7c, 0x04, 0x04, 0x7e, 0x7f, 0x01}, {0x00, 0x40, 0x60, 0x3e, 0x7e, 0x40, 0x60, 0x20}, {0x00, 0x00, 0x99, 0xbd, 0xe7, 0xe7, 0xbd, 0x99}, {0x00, 0x38, 0x7c, 0xd6, 0x92, 0xd6, 0x7c, 0x38}, {0x00, 0x32, 0x7e, 0xce, 0x80, 0xce, 0x7e, 0x32}, {0x00, 0x00, 0x9c, 0xbe, 0xf2, 0x52, 0x1e, 0x0c}, {0x18, 0x3c, 0x24, 0x3c, 0x3c, 0x24, 0x3c, 0x18}, {0x18, 0xbc, 0xe4, 0x7c, 0x3c, 0x26, 0x3f, 0x19}, {0x00, 0x00, 0x00, 0x92, 0x92, 0xd6, 0x7c, 0x38}, {0x00, 0x00, 0x7e, 0xfe, 0x80, 0x80, 0xfe, 0x7e}, {0x00, 0x00, 0x54, 0x54, 0x54, 0x54, 0x54, 0x54}, {0x00, 0x00, 0x22, 0x22, 0xfa, 0xfa, 0x22, 0x22}, {0x00, 0x00, 0x02, 0x22, 0x72, 0xda, 0x8a, 0x02}, {0x00, 0x00, 0x02, 0x8a, 0xda, 0x72, 0x22, 0x02}, {0x60, 0xe0, 0x80, 0xff, 0x7f, 0x00, 0x00, 0x00}, {0x00, 0x00, 0x00, 0xfe, 0xff, 0x01, 0x07, 0x06}, {0x00, 0x00, 0x10, 0x10, 0xd6, 0xd6, 0x10, 0x10}, {0x00, 0x48, 0x6c, 0x24, 0x6c, 0x48, 0x6c, 0x24}, {0x00, 0x00, 0x60, 0xf0, 0x90, 0xf0, 0x60, 0x00}, {0x00, 0x00, 0x00, 0x18, 0x18, 0x00, 0x00, 0x00}, {0x00, 0x00, 0x00, 0x08, 0x08, 0x00, 0x00, 0x00}, {0x80, 0x80, 0xff, 0xff, 0x03, 0x0e, 0x0c, 0x08}, {0x00, 0x00, 0x78, 0xf8, 0x80, 0xf8, 0xf8, 0x00}, {0x00, 0x00, 0x00, 0x48, 0xe8, 0xb8, 0x98, 0x00}, {0x00, 0x00, 0x3c, 0x3c, 0x3c, 0x3c, 0x00, 0x00}, {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00} } }; BOOLEAN CSynthesizer:: Initialize() /*++ Routine Description: Class initialization. Set the buffer the synthesizer generates images to. Override to do any additional processing you think is needed. Arguments: none Return Value: TRUE - success. --*/ { PAGED_CODE(); m_StartTime = KeQueryPerformanceCounter(&m_Frequency).QuadPart; // Capture the working palette. // Recast it to a point to an array of primaries. if( !(m_Colors = GetPalette()) ) { return FALSE; } // Clear the globals. This occurs redundantly, but hey ... // ... test output doesn't make sense if we don't do this. for( ULONG i=0; i<MAX_Attribute; i++ ) { m_Attrib[i]=0; } // // Allocate a scratch buffer for the synthesizer. // NT_ASSERT(m_Length); if( !m_Length ) { return FALSE; } m_Buffer = new (PagedPool) UCHAR[m_Length]; NT_ASSERT(m_Buffer); if( !m_Buffer ) { return FALSE; } // // Allocate a scratch buffer for the Gradient. // m_GradientBmp = new (PagedPool) CKsRgbQuad[m_Width * MAX_COLOR]; NT_ASSERT(m_GradientBmp); if( !m_GradientBmp ) { SAFE_DELETE_ARRAY( m_Buffer ); return FALSE; } return TRUE; } LONGLONG ConvertPerfTime( _In_ LONGLONG Freq, _In_ LONGLONG Time ) { PAGED_CODE(); LARGE_INTEGER tL ; tL.QuadPart = Time; return KSCONVERT_PERFORMANCE_TIME( Freq, tL ); } void CSynthesizer:: Destroy() /*++ Routine Description: Clean up from initialize. Note: A good place to generate synthesis stats. Arguments: none Return Value: void. --*/ { PAGED_CODE(); SAFE_DELETE_ARRAY( m_Buffer ); SAFE_DELETE_ARRAY( m_GradientBmp ); LONGLONG EndTime = KeQueryPerformanceCounter(NULL).QuadPart; LONGLONG FPS = ((LONGLONG)m_SynthesisCount * NANOSECONDS) / ( ConvertPerfTime( m_Frequency.QuadPart, (EndTime - m_StartTime) ) + (NANOSECONDS/2) ); // Report rendering times. DBG_TRACE( "%s(%d,%d)", m_FormatName, m_Width, m_Height ); DBG_TRACE( "Synthesis Time - Total = %lld", ConvertPerfTime( m_Frequency.QuadPart, m_SynthesisTime ) ); DBG_TRACE( " Count = %d", m_SynthesisCount ); DBG_TRACE( " Avg = %lld", ConvertPerfTime( m_Frequency.QuadPart, m_SynthesisCount ? m_SynthesisTime / m_SynthesisCount : 0 ) ); DBG_TRACE( " Commit Time - Total = %lld", ConvertPerfTime( m_Frequency.QuadPart, m_CommitTime ) ); DBG_TRACE( " Count = %d", m_CommitCount ); DBG_TRACE( " Avg = %lld", ConvertPerfTime( m_Frequency.QuadPart, m_CommitCount ? m_CommitTime / m_CommitCount : 0 ) ); DBG_TRACE( " FPS = %lld", FPS ); } NTSTATUS CSynthesizer:: SynthesizeBars() /*++ Routine Description: Synthesize EIA-189-A standard color bars onto the Image. The image in question is the current synthesis buffer. Arguments: None Return Value: success / failure --*/ { PAGED_CODE(); if( !m_Buffer ) { return STATUS_INVALID_DEVICE_STATE; } const COLOR *CurColor = m_ColorBars; ULONG ColorCount = SIZEOF_ARRAY (m_ColorBars); // // Set the default cursor... // GetImageLocation (0, 0); // // Synthesize a single line. // PUCHAR ImageStart = m_Cursor; for (ULONG x = 0; x < m_Width; x++) { PutPixel (m_ColorBars [((x * ColorCount) / m_Width)]); } PUCHAR ImageEnd = m_Cursor; // // Copy the synthesized line to all subsequent lines. // for (ULONG line = 0; line < m_Height; line++) { GetImageLocation (0, line); RtlCopyMemory ( m_Cursor, ImageStart, ImageEnd - ImageStart ); } // Paint the top left and top right registrations boxes. GetImageLocation(0,0); ImageStart = m_Cursor; for(ULONG x =0; x < m_Width; x++) { if(x < (m_Height/16)) { PutPixel(g_TopLeft); } else if(x > (m_Width - (m_Height / 16))) { PutPixel(g_TopRight); } else { PutPixel (m_ColorBars [((x * ColorCount) / m_Width)]); } } ImageEnd = m_Cursor; for (ULONG line = 0; line < m_Height/16; line++) { GetImageLocation (0, line); RtlCopyMemory ( m_Cursor, ImageStart, ImageEnd - ImageStart ); } // Paint the bottom left and bottom right registrations boxes. GetImageLocation(0, (15*m_Height) / 16); ImageStart = m_Cursor; for(ULONG x =0; x < m_Width; x++) { if(x < (m_Height/16)) { PutPixel(g_BotLeft); } else if(x > (m_Width - (m_Height / 16))) { PutPixel(g_BotRight); } else { PutPixel (m_ColorBars [((x * ColorCount) / m_Width)]); } } ImageEnd = m_Cursor; for (ULONG line = 0; line < m_Height/16; line++) { GetImageLocation (0, line+(15*m_Height) / 16); RtlCopyMemory ( m_Cursor, ImageStart, ImageEnd - ImageStart ); } return STATUS_SUCCESS; } void CSynthesizer:: EncodeNumber( _In_ ULONG LocY, _In_ UINT32 Number, _In_ COLOR LowColor, _In_ COLOR HighColor ) /* Routine Description: Overlays an encoded number over the synthesized image. The image buffer used is the set synthesis buffer. The pattern is scaled to fit the image. Arguments: LocY - The row on the image to begin the overlay. This must be inside the image. Number - The number to encode LowColor - The color to represent 0 (a clear bit) HighColor - The color to represent 1 (a set bit) Return Value: void */ { PAGED_CODE(); if( !m_Buffer ) { return; } NT_ASSERT(LocY <= m_Height); GetImageLocation(0, LocY); UINT32 mask = 0x1; PUCHAR ImageStart = m_Cursor; for(ULONG i = 0; i < 32; i++) { for(ULONG j = 0; j < m_Width/32; j++) { if(Number & mask) { PutPixel(HighColor); } else { PutPixel(LowColor); } } mask = mask << 1; } PUCHAR ImageEnd = m_Cursor; // // Copy the synthesized line to all subsequent lines. // for (ULONG line = 1; line < m_Height/16; line++) { RtlCopyMemory ( GetImageLocation (0, line + LocY), ImageStart, ImageEnd - ImageStart ); } } void CSynthesizer:: OverlayText ( _In_ ULONG LocX, _In_ ULONG LocY, _In_ ULONG Scaling, _In_ LPSTR Text, _In_ COLOR BgColor, _In_ COLOR FgColor ) /*++ Routine Description: Overlay text onto the synthesized image. Clip to fit the image if the overlay does not fit. The image buffer used is the set synthesis buffer. Arguments: LocX - The X location on the image to begin the overlay. This MUST be inside the image or no text will be rendered. POSITION_CENTER may be used to indicate horizontal centering. LocY - The Y location on the image to begin the overlay. This MUST be inside the image or no text will be rendered. POSITION_CENTER may be used to indicate vertical centering. Scaling - Normally, the overlay is done in an 8x8 font. A scaling of 2 indicates 16x16, 3 indicates 24x24 and so forth. Text - A null terminated character string containing the information to overlay BgColor - The background color of the overlay window. For transparency, indicate TRANSPARENT here. FgColor - The foreground color for the text overlay. Return Value: None --*/ { PAGED_CODE(); // Validate internal state. if( !m_Buffer ) { return; } NT_ASSERT( (LocX <= m_Width || LocX == POSITION_CENTER) && (LocY <= m_Height || LocY == POSITION_CENTER) && Text !=nullptr && (BgColor < MAX_COLOR || BgColor == TRANSPARENT) && (FgColor < MAX_COLOR || FgColor == TRANSPARENT) ); // Validate parameters. if( !( (LocX <= m_Width || LocX == POSITION_CENTER) && (LocY <= m_Height || LocY == POSITION_CENTER) && Text !=nullptr && (BgColor < MAX_COLOR || BgColor == TRANSPARENT) && (FgColor < MAX_COLOR || FgColor == TRANSPARENT) ) ) { return; } size_t StrLen = 0; PUCHAR CurChar; // // Determine the character length of the string. // if( !NT_SUCCESS( RtlStringCchLengthA( Text, m_Width, &StrLen ) ) ) { // Invalid parameter. return; } // // Determine the physical size of the string plus border. There is // a definable NO_CHARACTER_SEPARATION. If this is defined, there will // be no added space between font characters. Otherwise, one empty pixel // column is added between characters. // #ifndef NO_CHARACTER_SEPARATION ULONG LenX = (ULONG) ((StrLen * (((size_t)Scaling) << 3)) + 1 + StrLen); #else // NO_CHARACTER_SEPARATION ULONG LenX = (ULONG) ((StrLen * (((size_t_)Scaling) << 3)) + 2); #endif // NO_CHARACTER_SEPARATION ULONG LenY = 2 + (Scaling << 3); // // Adjust for center overlays. // // NOTE: If the overlay doesn't fit into the synthesis buffer, this // merely left aligns the overlay and clips off the right side. // if (LocX == POSITION_CENTER) { //LocX = min( 0, ((LONG)m_Width - (LONG)LenX) >> 1); if (LenX >= m_Width) { LocX = 0; } else { LocX = (m_Width - LenX) >> 1; } } if (LocY == POSITION_CENTER) { //LocY = min( 0, ((LONG)m_Width - (LONG)LenY) >> 1); if (LenY >= m_Height) { LocY = 0; } else { LocY = (m_Height - LenY) >> 1; } } // // Determine the amount of space available on the synthesis buffer. // We will clip anything that finds itself outside the synthesis buffer. // ULONG SpaceX = m_Width - LocX; ULONG SpaceY = m_Height - LocY; // // Set the default cursor position. // GetImageLocation (LocX, LocY); // // Overlay a background color row. // if( SpaceY ) { if( BgColor != TRANSPARENT ) { for (ULONG x = 0; x < LenX && x < SpaceX; x++) { PutPixel (BgColor); } } SpaceY--; } LocY++; // // Loop across each row of the image. // for (ULONG row = 0; row < 8 && SpaceY; row++) { // // Generate a line. // GetImageLocation (LocX, LocY++); PUCHAR ImageStart = m_Cursor; ULONG CurSpaceX = SpaceX; if (CurSpaceX) { PutPixel (BgColor); CurSpaceX--; } // // Generate the row'th row of the overlay. // CurChar = (PUCHAR) Text; while( *CurChar ) { UCHAR CharBase = m_FontData [m_Rotation==AcpiPldRotation90][*CurChar++][row]; for (ULONG mask = 0x80; mask && CurSpaceX; mask >>= 1) { for (ULONG scale = 0; scale < Scaling && CurSpaceX; scale++) { if (CharBase & mask) { PutPixel (FgColor); } else { PutPixel (BgColor); } CurSpaceX--; } } // // Separate each character by one space. Account for the border // space at the end by placing the separator after the last // character also. // #ifndef NO_CHARACTER_SEPARATION if (CurSpaceX) { PutPixel (BgColor); CurSpaceX--; } #endif // NO_CHARACTER_SEPARATION } // // If there is no separation character defined, account for the // border. // #ifdef NO_CHARACTER_SEPARATION if (CurSpaceX) { PutPixel (BgColor); CurSpaceX--; } #endif // NO_CHARACTER_SEPARATION PUCHAR ImageEnd = m_Cursor; // // Copy the line downward scale times. // for (ULONG scale = 1; scale < Scaling && SpaceY; scale++) { GetImageLocation (LocX, LocY++); RtlCopyMemory (m_Cursor, ImageStart, ImageEnd - ImageStart); SpaceY--; } } // // Add the bottom section of the overlay. // GetImageLocation (LocX, LocY); if (BgColor != TRANSPARENT && SpaceY) { for (ULONG x = 0; x < LenX && x < SpaceX; x++) { PutPixel (BgColor); } } } void CSynthesizer::ApplyGradient( _In_ ULONG LocY, _In_ COLOR Gradient ) /*++ Routine Description: Synthesize a horizontal gradient bar from a given color Arguments: LocY - row Gradient - A starting color Return Value: void --*/ { PAGED_CODE(); if( !m_Buffer ) { return; } NT_ASSERT(LocY <= m_Height); PUCHAR Image = GetImageLocation(0, LocY); PUCHAR RowBmp = reinterpret_cast<PUCHAR>(&m_GradientBmp[Gradient*m_Width]); ULONG Stride = m_Width * sizeof(CKsRgbQuad); // // Copy the synthesized line to all lines. // for (ULONG line = 0; line < m_Height/16; line++) { RtlCopyMemory ( Image, RowBmp, Stride ); Image += Stride; } } // // Synthesize // // Fill the image buffer with some base image. All h/w simulations will // call this function to generate a base image - even for jpeg. // NTSTATUS CSynthesizer:: Synthesize() /*++ Routine Description: Fill the image buffer with some base image. All h/w simulations will call this function to generate a base image. Arguments: None Return Value: Success / failure --*/ { PAGED_CODE(); if( !m_Buffer ) { return STATUS_INVALID_DEVICE_STATE; } // // Generate a "time stamp" just to overlay it onto the capture image. // It makes it more exciting than bars that do nothing. // SynthesizeBars(); ApplyGradient( (m_Height)/16, RED); ApplyGradient( (2*m_Height)/16, GREEN); ApplyGradient( (3*m_Height)/16, BLUE); ApplyGradient( (4*m_Height)/16, WHITE); EncodeNumber((5*m_Height)/16, (UINT32)m_Attrib[FrameNumber], BLACK, WHITE); EncodeNumber((6*m_Height)/16, (UINT32)m_Attrib[QpcTime], BLACK, WHITE); CHAR Text [256]; (void)RtlStringCbPrintfA(Text, sizeof(Text), "Frame: %lld", m_Attrib[FrameNumber]); // // Overlay the frame # onto the scratch space image. // OverlayText ( POSITION_CENTER, (m_Height - 28), 1, Text, BLACK, TEXT_COLOR ); // // Add a description of the frame type/width/height. // (void)RtlStringCbPrintfA(Text, sizeof(Text), "%s (%dx%d)", m_FormatName, m_Width, m_Height); OverlayText ( 0, (m_Height - 28), 1, Text, TRANSPARENT, TEXT_COLOR ); // // Add a description of the mounting. // (void)RtlStringCbPrintfA(Text, sizeof(Text), "%d\370 Mounting", DbgRotation2Degrees(m_Rotation)); size_t len = 0; (void)RtlStringCchLengthA(Text, sizeof(Text), &len); OverlayText ( (m_Width - (((ULONG)len*8))), // right-adjust text. (m_Height - 28), 1, Text, TRANSPARENT, TEXT_COLOR ); return STATUS_SUCCESS; } void CSynthesizer::PutPixel ( COLOR Color ) /*++ Routine Description: Place a pixel at the default cursor location. The cursor location must be set via GetImageLocation(x, y). Arguments: Color - The pixel color to render Return Value: void --*/ { PAGED_CODE(); PKS_RGBQUAD &pPixel = (PKS_RGBQUAD &) m_Cursor; if (Color != TRANSPARENT) { *pPixel = CKsRgbQuad( m_Colors[Color][2], m_Colors[Color][1], m_Colors[Color][0] ); } // Next pixel pPixel++; } // // PutPixel(): // // Place a pixel at the default cursor location. The cursor location // must be set via GetImageLocation(x, y). // void CSynthesizer::PutPixel ( UCHAR colorR, UCHAR colorB, UCHAR colorG ) /*++ Routine Description: Place a pixel at the default cursor location. The cursor location must be set via GetImageLocation(x, y). TODO: Remove. This function appears to be dead code. Arguments: colorR - The first color primary of the pixel. colorB - The third color primary of the pixel. colorG - The second color primary of the pixel. Return Value: void --*/ { PAGED_CODE(); PKS_RGBQUAD &pPixel = (PKS_RGBQUAD &) m_Cursor; *pPixel++ = CKsRgbQuad( colorR, colorG, colorB ); } // // Synthesize // // Fill the image buffer with some base image. All h/w simulations will // call this function to generate a base image - even for jpeg. // NTSTATUS CSynthesizer:: DoSynthesize() { PAGED_CODE(); LARGE_INTEGER StartTime = {0}; LARGE_INTEGER EndTime = {0}; StartTime = KeQueryPerformanceCounter(NULL); NTSTATUS Status = Synthesize(); m_SynthesisTime += KeQueryPerformanceCounter(NULL).QuadPart - StartTime.QuadPart; m_SynthesisCount++; return Status; } // // Commit // // Copy (and reformat, if necessary) pixels from the internal scratch // buffer. If the output format decimates chrominance, do it here. // _Success_(return > 0) ULONG CSynthesizer:: DoCommit( _Out_writes_bytes_(Size) PUCHAR Buffer, _In_ ULONG Size, _In_ ULONG Stride ) { PAGED_CODE(); LARGE_INTEGER StartTime = KeQueryPerformanceCounter(NULL); ULONG n = Commit( Buffer, Size, Stride ); m_CommitTime += KeQueryPerformanceCounter(NULL).QuadPart - StartTime.QuadPart; m_CommitCount++; return n; } // // DoCommit // // Note: The stride needs to be a function of the bits per pixel of the // OUTPUT format - not the format we store it in. The class ctor // must initialize m_OutputStride to a default stride value. // _Success_(return > 0) ULONG CSynthesizer:: DoCommit( _Out_writes_bytes_(Size) PUCHAR Buffer, _In_ ULONG Size ) { PAGED_CODE(); LARGE_INTEGER StartTime = KeQueryPerformanceCounter(NULL); ULONG n = Commit( Buffer, Size ); m_CommitTime += KeQueryPerformanceCounter(NULL).QuadPart - StartTime.QuadPart; m_CommitCount++; return n; } #define CLEAR_HISTOGRAM( H ) \ if( H ) \ { \ RtlZeroMemory( H, 256*sizeof(*H) ); \ } #define BUMP_HISTOGRAM_PRIMARY( H, C ) \ if( H ) \ { \ H[C]++; \ } // // Histogram // // Fill an array with histogram data. // void CSynthesizer:: Histogram( _Out_writes_opt_(256) PULONG HistogramP0, // rgbRed _Out_writes_opt_(256) PULONG HistogramP1, // rgbGreen _Out_writes_opt_(256) PULONG HistogramP2 // rgbBlue ) /*++ Routine Description: Fill array(s) with histogram data. Arguments: HistogramP0 - Stats on the first primary. HistogramP1 - Stats on the second primary. HistogramP2 - Stats on the third primary. Return Value: void --*/ { PAGED_CODE(); CLEAR_HISTOGRAM( HistogramP0 ); CLEAR_HISTOGRAM( HistogramP1 ); CLEAR_HISTOGRAM( HistogramP2 ); ULONG row, col; for( row=0; row<m_Height; row++ ) { PKS_RGBQUAD pPixel = (PKS_RGBQUAD) GetImageLocation(0, row); for( col=0; col<m_Width; col++ ) { BUMP_HISTOGRAM_PRIMARY( HistogramP0, pPixel->rgbRed ); BUMP_HISTOGRAM_PRIMARY( HistogramP1, pPixel->rgbGreen ); BUMP_HISTOGRAM_PRIMARY( HistogramP2, pPixel->rgbBlue ); } } }
d603eac39332c2e38b873cbf6b9d1fd27f0c890d
21a8693d5827ffe7017f07432cf8a33abce9ad32
/rosplan_knowledge_base/include/rosplan_knowledge_base/RDDLUtils.h
4677ae56be966f03acd8b5dbd7854ad3c3ee708b
[ "BSD-2-Clause" ]
permissive
KCL-Planning/ROSPlan
c0f4bd63a05857c511d4ad3708a50fee50877502
639037230073997d3ed3fea7391f1e1b3c6b1ffa
refs/heads/master
2023-06-22T08:42:48.827676
2022-09-07T14:19:41
2022-09-07T14:19:41
21,421,114
337
169
BSD-2-Clause
2023-06-13T20:37:31
2014-07-02T11:04:22
C++
UTF-8
C++
false
false
5,753
h
RDDLUtils.h
// // Created by Gerard Canal <gcanal@iri.upc.edu> on 25/09/18. // #ifndef ROSPLAN_KNOWLEDGE_BASE_RDDLOPERATORUTILS_H #define ROSPLAN_KNOWLEDGE_BASE_RDDLOPERATORUTILS_H #define NOT_IMPLEMENTED(str) ROS_WARN_STREAM(__FILE__ << ":" << __LINE__ << ": " << str) #define NOT_IMPLEMENTED_OPERATOR NOT_IMPLEMENTED("Unknown or unsupported operand type for the action preconditions.") #include <rosplan_knowledge_msgs/DomainFormula.h> #include <rosplan_knowledge_msgs/DomainAssignment.h> #include <rosplan_knowledge_msgs/ProbabilisticEffect.h> #include <rosplan_knowledge_msgs/KnowledgeItem.h> #include "RDDLParser.h" namespace KCL_rosplan { typedef std::vector<rosplan_knowledge_msgs::DomainFormula> vectorDF; typedef std::vector<rosplan_knowledge_msgs::DomainAssignment> vectorDA; typedef std::vector<rosplan_knowledge_msgs::DomainAssignment> vectorDA; typedef std::vector<rosplan_knowledge_msgs::ProbabilisticEffect> vectorPE; typedef std::vector<rosplan_knowledge_msgs::KnowledgeItem> vectorKI; struct PosNegDomainFormula { vectorDF pos; // Positive or add formulas vectorDF neg; // Negative or delete formulas }; struct EffectDomainFormula { vectorDF add; // Add formulas vectorDF del; // Delete formulas vectorPE prob; // Probabilistic effects }; class RDDLUtils { private: /* joints a and b, leaving the result in a. b is not valid anymore! */ static inline void join(PosNegDomainFormula &a, PosNegDomainFormula &b); static inline void join(vectorDA &a, vectorDA &b); static inline void join(EffectDomainFormula &a, EffectDomainFormula &b); static inline void join(vectorKI &a, vectorKI &b); /* negates p by swapping positive formulas by negative ones */ static inline void negate(PosNegDomainFormula& p); static inline void negate(EffectDomainFormula& p); /* Returns an assignment of the parameters of the op_var to the parmeters of the op_head, to match all the params for the operator */ static std::map<std::string, std::string> getParamReplacement(const rosplan_knowledge_msgs::DomainFormula &op_head, const ParametrizedVariable* op_var); static PosNegDomainFormula toDomainFormula(const LogicalExpression *expr, const std::map<std::string, std::string>& assign); static PosNegDomainFormula getOperatorPrecondition(const rosplan_knowledge_msgs::DomainFormula &op_head, const LogicalExpression *SAC); static PosNegDomainFormula getOperatorPrecondition(const rosplan_knowledge_msgs::DomainFormula &op_head, const Connective *SAC); static PosNegDomainFormula getOperatorPrecondition(const rosplan_knowledge_msgs::DomainFormula &op_head, const Negation *SAC); static EffectDomainFormula getOperatorEffects(const rosplan_knowledge_msgs::DomainFormula &op_head, const ParametrizedVariable *pVariable, const LogicalExpression *exp, std::map<std::string, std::string>& assign, bool& action_found, bool& exogenous); static EffectDomainFormula getOperatorEffects(const rosplan_knowledge_msgs::DomainFormula &op_head, const ParametrizedVariable *pVariable, const IfThenElseExpression *exp, std::map<std::string, std::string>& assign, bool& action_found, bool& exogenous); static EffectDomainFormula getOperatorEffects(const ParametrizedVariable *pVariable, const BernoulliDistribution *exp, const std::map<std::string, std::string>& assign, bool& action_found, bool& exogenous); static EffectDomainFormula getOperatorEffects(const ParametrizedVariable *pVariable, const DiscreteDistribution *exp, const std::map<std::string, std::string>& assign, bool& action_found, bool& exogenous); static void fillForAllEffect(const rosplan_knowledge_msgs::DomainFormula &op_head, const ParametrizedVariable *pVariable, const UniversalQuantification *exp, EffectDomainFormula& out, size_t paramid, std::map<std::string, std::string> &assign, bool& action_found, bool& exogenous); static vectorDA getOperatorAssignEffects(const rosplan_knowledge_msgs::DomainFormula &op_head, const ParametrizedVariable *pVariable, const IfThenElseExpression *exp); static vectorKI getGoals(const LogicalExpression *exp, bool is_negative, std::map<std::string, std::string> &assign); static void fillForAllGoal(const UniversalQuantification *exp, vectorKI& out, size_t paramid, bool is_negative, std::map<std::string, std::string> &assign); public: /** * A precondition is only considered when it is in state-action constraint and has the form: * actionfluent_name => (precondition) * Only conjunctions will be considered in the precondition part, which is the one that will be returned. * @param op_name Name of the operator * @param SACs Action-State Constraints * @return Preconditions */ static PosNegDomainFormula getOperatorPreconditions(const rosplan_knowledge_msgs::DomainFormula &op_head, const std::vector<LogicalExpression *> &SACs); static EffectDomainFormula getOperatorEffects(const rosplan_knowledge_msgs::DomainFormula &op_head, const std::map<ParametrizedVariable*, LogicalExpression*>& CPFs); static vectorDA getOperatorAssignEffects(const rosplan_knowledge_msgs::DomainFormula &op_head, const std::map<ParametrizedVariable *, LogicalExpression *> &CPFs); static vectorKI getGoals(const std::map<ParametrizedVariable*, LogicalExpression*>& CPFs, const std::vector<LogicalExpression *> &SACs); }; } #endif //ROSPLAN_KNOWLEDGE_BASE_RDDLOPERATORUTILS_H
d0fb46f87dc41a782be181966a2afb22b1c28077
5ab80e7479327b14cc6b7adb36bc1e7ff22d8c74
/z_RunoobC/C++_Lessons/05_Class/main.cpp
dfe53860a8c47922671d2e87cfeef3ca8b42ddcd
[]
no_license
kiasher0099/C
8f738cf6b0845e6e85d4d8c9f5e51df07a922384
0fee4b4b3f7408cbf497b98d37121c819f69f6fc
refs/heads/master
2022-04-14T07:11:38.056288
2020-04-14T04:00:05
2020-04-14T04:00:05
210,148,849
0
0
null
null
null
null
UTF-8
C++
false
false
1,105
cpp
main.cpp
/************************************************************************* > File Name: main.cpp > Author: kiasher > Mail: kiasher@sina.com > Created Time: Mon 02 Dec 2019 03:48:20 PM CST ************************************************************************/ #include<iostream> using namespace std; class Box { public: double length; double breadth; double height; double getVolume(void); void setLength(double len); void setBreadth(double bre); void setHeight(double hei); }; double Box::getVolume(void) { return length * breadth * height; } void Box::setLength(double len) { length = len; } void Box::setBreadth(double bre) { breadth = bre; } void Box::setHeight(double hei) { height = hei; } int main() { Box Box1; Box Box2; double volume = 0.0; Box1.setLength(6.0); Box1.setBreadth(7.0); Box1.setHeight(5.0); Box2.setLength(12.0); Box2.setBreadth(13.0); Box2.setHeight(10.0); volume = Box1.getVolume(); cout << "The Volume of Box1 is: " << volume << endl; volume = Box2.getVolume(); cout << "The Volume of Box2 is: " << volume << endl; return 0; }
e9efb2e8d274ddd80572a0aa275a4d6ff5988027
868778cfaff0103c350abbb7af2aaddb62eae40c
/Chapter 18/18-1/main.cpp
35628644b1ecc101894b17f4ba0eff8d48f1a5ce
[]
no_license
Jerrydepon/C_plus_plus_Practice
a1f3287f98a0fb625218cfccfb9228d040186f13
d75a4d3be64c6030d020c10a5bbb86e8313415c1
refs/heads/master
2020-07-06T16:36:38.765385
2019-08-19T02:03:19
2019-08-19T02:03:19
203,080,358
0
0
null
null
null
null
UTF-8
C++
false
false
710
cpp
main.cpp
#include <iostream> #include "IntStack.h" using namespace std; int main() { IntStack stack(5); int catchVar; cout << "Pushing 5\n"; stack.push(5); cout << "Pushing 10\n"; stack.push(10); cout << "Pushing 15\n"; stack.push(15); cout << "Pushing 20\n"; stack.push(20); cout << "Pushing 25\n"; stack.push(25); cout << "Popping...\n"; stack.pop(catchVar); cout << catchVar << endl; stack.pop(catchVar); cout << catchVar << endl; stack.pop(catchVar); cout << catchVar << endl; stack.pop(catchVar); cout << catchVar << endl; stack.pop(catchVar); cout << catchVar << endl; stack.pop(catchVar); cout << catchVar << endl; return 0; }
c1f4760b49dbc34b2e1a029a3e45af295b619535
e344a762c2edda8c3b5406143a0bc1df79871937
/string/test.cpp
0d39c4113127fa9bd0a24d97cccf34cc7a12a9ef
[]
no_license
Presageee/STL-IMPL
f413420772a08bb6f316071edeeb8067cb8b20ff
5150f2f739a611ad9538dd388aacfdf1df17f09d
refs/heads/master
2020-05-22T00:40:31.359668
2017-03-19T10:40:47
2017-03-19T10:40:47
84,656,512
0
0
null
null
null
null
UTF-8
C++
false
false
489
cpp
test.cpp
#include "string.h" #include <iostream> using namespace std; using namespace lib; int main(int args, char* argv) { lib::string str; lib::string str1("abcde"); lib::string str2("12345678901234567"); lib::string str3(str1); lib::string str4 = str3 + str1; lib::string str5 = str4 + str2; lib::string str6(str2); str6.append(str3); int b = 0; cout << str1 << endl; cout << str2 << endl; cout << str3 << endl; cout << str4 << endl; cout << str5 << endl; cout << str6 << endl; }
311abfe89f3f5a86942ce5f9dfca6c95a2f91413
8cddfd85a78adcb43f181a2cae8aefaa51fbefa8
/task_4_8/dict_editor_window.cpp
180a22dfad95593071e0789b60aa8d7b8d288795
[]
no_license
floatint/cxx_tasks_sm
81d0f77818718eb3c7b8e64bd4083ac9e6931891
4b49cb28184dc9647c44b086f2e4a55055aa021a
refs/heads/master
2022-11-11T11:34:33.987575
2020-06-28T18:11:21
2020-06-28T18:11:21
274,197,145
0
1
null
null
null
null
WINDOWS-1251
C++
false
false
7,518
cpp
dict_editor_window.cpp
#include "dict_editor_window.h" #include "dictionary_helper.h" #include "declension.h" #include "messages.h" #include <set> DictEditorWindow::DictEditorWindow(Dictionary& dict, QWidget *parent) : QDialog(parent), m_dict(dict) { m_dictNode = nullptr; ui.setupUi(this); this->setWindowTitle(DIALOG_TITLE); //обновляем список слов updateWordsList(); //рисуем комбобоксы ui.declSelect_2->setModel(qobject_cast<QStandardItemModel*>(ui.declSelect_1->model())); ui.declSelect_3->setModel(qobject_cast<QStandardItemModel*>(ui.declSelect_1->model())); ui.declSelect_4->setModel(qobject_cast<QStandardItemModel*>(ui.declSelect_1->model())); ui.declSelect_5->setModel(qobject_cast<QStandardItemModel*>(ui.declSelect_1->model())); ui.declSelect_6->setModel(qobject_cast<QStandardItemModel*>(ui.declSelect_1->model())); //подключаем логику setupSlots(); } void DictEditorWindow::setupSlots() { connect(ui.wordsList, &QListWidget::currentItemChanged, this, &DictEditorWindow::wordListItemChanged); connect(ui.newButton, &QPushButton::clicked, this, &DictEditorWindow::newWord); connect(ui.saveButton, &QPushButton::clicked, this, &DictEditorWindow::saveWord); connect(ui.deleteButton, &QPushButton::clicked, this, &DictEditorWindow::deleteWord); } void DictEditorWindow::newWord() { if (m_dictNode != nullptr) delete m_dictNode; //создаем временный объект m_dictNode = new DictionaryNode(); //зануляем поля ввода ui.prefixEdit_1->clear(); ui.prefixEdit_2->clear(); ui.prefixEdit_3->clear(); ui.prefixEdit_4->clear(); ui.prefixEdit_5->clear(); ui.prefixEdit_6->clear(); //отменяем предыдущий индекс, и установим флаг чтобы не войти в рекурсию m_isUpdated = true; ui.wordsList->setCurrentIndex(QModelIndex()); m_isUpdated = false; //обновим шапку this->setWindowTitle(DIALOG_TITLE + " - New Word"); } void DictEditorWindow::saveWord() { if (m_dictNode == nullptr && ui.wordsList->currentIndex().row() < 0) { Messages::info("Please, select word or add new"); return; } //проверим, чтобы все поля были заполнены if (ui.prefixEdit_1->text().isEmpty() || ui.prefixEdit_2->text().isEmpty() || ui.prefixEdit_3->text().isEmpty() || ui.prefixEdit_4->text().isEmpty() || ui.prefixEdit_5->text().isEmpty() || ui.prefixEdit_6->text().isEmpty() ) { Messages::info("Please, fill all input fields"); return; } else { //проверим, что комбобоксы указывают на разные падежи и нет дубликатов std::vector<int> declIndexes; declIndexes.push_back(ui.declSelect_1->currentIndex()); declIndexes.push_back(ui.declSelect_2->currentIndex()); declIndexes.push_back(ui.declSelect_3->currentIndex()); declIndexes.push_back(ui.declSelect_4->currentIndex()); declIndexes.push_back(ui.declSelect_5->currentIndex()); declIndexes.push_back(ui.declSelect_6->currentIndex()); //проверим при помощи конвертирования в set, есть ли дубликаты падежей auto tmp = std::set<int>(declIndexes.cbegin(), declIndexes.cend()); if (tmp.size() != declIndexes.size()) { Messages::info("Declensions must by unique"); return; } //получим базовое слово std::vector<QString> words; words.push_back(ui.prefixEdit_1->text()); words.push_back(ui.prefixEdit_2->text()); words.push_back(ui.prefixEdit_3->text()); words.push_back(ui.prefixEdit_4->text()); words.push_back(ui.prefixEdit_5->text()); words.push_back(ui.prefixEdit_6->text()); QString baseWord = DictionaryHelper::getBase(words); //базовое слово есть, далее для каждого получим префикс и падеж //заполняем запись в словаре for (int i = 0; i < words.size(); i++) { //получаем префикс auto prefix = words[i].right(words[i].size() - baseWord.size()); Declension decl = (Declension)declIndexes[i]; m_dictNode->addDeclension(prefix, decl); } //добавляем запись в словарь m_dict.addNode(baseWord, *m_dictNode); //обновим список слов updateWordsList(); //установим фокус на последний элемент ui.wordsList->setCurrentRow(ui.wordsList->count() - 1); } } void DictEditorWindow::deleteWord() { //если ничего не выбрано if (ui.wordsList->currentIndex().row() < 0) return; auto dictNode = m_wordsList[ui.wordsList->currentIndex().row()]; //удаляем из словаря m_dict.removeNode(dictNode.first); //обновляем ui updateWordsList(); //нулим поля ввода ui.prefixEdit_1->clear(); ui.prefixEdit_2->clear(); ui.prefixEdit_3->clear(); ui.prefixEdit_4->clear(); ui.prefixEdit_5->clear(); ui.prefixEdit_6->clear(); } void DictEditorWindow::wordListItemChanged(QListWidgetItem *curr, QListWidgetItem *prev) { //сбрасываем шапку this->setWindowTitle(DIALOG_TITLE); //если в процессе обновления, то просто выйдем if (m_isUpdated) return; if (m_dictNode != nullptr) { delete m_dictNode; } //если выбрано слово if (curr != nullptr) { //получим его индекс в списке auto i = ui.wordsList->row(curr); //получаем все префиксы, и устанавливаем ui ui.prefixEdit_1->setText(m_wordsList[i].first + m_wordsList[i].second.getPrefix(Declension::Nominative)); ui.declSelect_1->setCurrentIndex((int)Declension::Nominative); ui.prefixEdit_2->setText(m_wordsList[i].first + m_wordsList[i].second.getPrefix(Declension::Genetive)); ui.declSelect_2->setCurrentIndex((int)Declension::Genetive); ui.prefixEdit_3->setText(m_wordsList[i].first + m_wordsList[i].second.getPrefix(Declension::Dative)); ui.declSelect_3->setCurrentIndex((int)Declension::Dative); ui.prefixEdit_4->setText(m_wordsList[i].first + m_wordsList[i].second.getPrefix(Declension::Accusative)); ui.declSelect_4->setCurrentIndex((int)Declension::Accusative); ui.prefixEdit_5->setText(m_wordsList[i].first + m_wordsList[i].second.getPrefix(Declension::Instrumental)); ui.declSelect_5->setCurrentIndex((int)Declension::Instrumental); ui.prefixEdit_6->setText(m_wordsList[i].first + m_wordsList[i].second.getPrefix(Declension::Prepositional)); ui.declSelect_6->setCurrentIndex((int)Declension::Prepositional); //создаем временную запись m_dictNode = new DictionaryNode(); this->setWindowTitle(DIALOG_TITLE + " - " + m_wordsList[i].first + m_wordsList[i].second.getPrefix(Declension::Nominative)); } } void DictEditorWindow::updateWordsList() { m_isUpdated = true; //очистим список слов m_wordsList.clear(); //далее опять заполним его for (int i = 0; i < m_dict.size(); i++) { auto bases = m_dict.getBases(); DictionaryNode node; m_dict.getNode(bases[i], node); m_wordsList.push_back({ bases[i], node }); } //очищаем визуал ui.wordsList->clear(); //заполняем снова for (int i = 0; i < m_wordsList.size(); i++) { //в списке слова в именительном падеже ui.wordsList->addItem(m_wordsList[i].first + m_wordsList[i].second.getPrefix(Declension::Nominative)); } m_isUpdated = false; }
25e958326ca06f2676b449731952b54177486f64
d64fdcbd9ce18d4e124c3bb9dc4eaa343a771154
/code459_重复的字符串.cpp
0d50ba25f0d0ba86620cae036a984e1b88f5d587
[]
no_license
luanjianbing/leetcode
c61d8a80128b35d22c891a597df19c5dd1b3c331
edaafb8b86ac32878ba7582e06c668a7136f918f
refs/heads/master
2022-12-13T03:14:33.227682
2020-09-11T01:58:53
2020-09-11T01:58:53
282,830,965
0
0
null
null
null
null
GB18030
C++
false
false
714
cpp
code459_重复的字符串.cpp
#include <iostream> #include <sstream> using namespace std; //给定一个非空的字符串,判断它是否可以由它的一个子串重复多次构成。 //给定的字符串只含有小写英文字母,并且长度不超过10000。 class Solution { public: bool repeatedSubstringPattern(string s) { int n = s.size(); for (int i = 1; i * 2 <= n; ++i) { if (n % i == 0) { bool match = true; for (int j = i; j < n; ++j) { if (s[j] != s[j - i]) { match = false; break; } } if (match) { return true; } } } return false; } }; int main() { string str = "abcabcabcac"; Solution s; cout << s.repeatedSubstringPattern(str) << endl; return 0; }
36f2b111a2f0f00266e703fb5ff1b6448cc1e886
3825145e1bcf1d8fd2c888c6b113b9bd81e84fbd
/ROS/camina12/src/Nodo2_parametrizacion.cpp
d7000e2f22a86f98c37dc04ec33e0691bdc3e954
[]
no_license
mau25rojas/tesis-hexapodo
9bc29361fd70d28d60de01c40b4916e7d590da1b
b2a573f13efffe8487948c9cb3a13c8fb55d1b82
refs/heads/master
2020-05-18T18:22:04.826463
2014-10-01T15:25:30
2014-10-01T15:25:30
32,201,978
1
1
null
null
null
null
UTF-8
C++
false
false
8,937
cpp
Nodo2_parametrizacion.cpp
#include "ros/ros.h" #include "math.h" #include "string.h" //Librerias propias usadas #include "camina12/v_repConst.h" #include "camina12/constantes.hpp" #include "camina12/vector3d.hpp" // Used data structures: #include "camina12/DatosTrayectoriaPata.h" #include "camina12/AngulosMotor.h" //#include "camina12/CinversaParametros.h" // Used API services: #include "vrep_common/VrepInfo.h" //-- Global variables (modified by topic subscribers): bool simulationRunning=true; bool sensorTrigger=false; float simulationTime=0.0f; bool Inicio=true; //-- Calculo de trayectoria int tripode[Npatas]; float velocidadApoyo=0.0, dh=0.0,phi[Npatas]; punto3d Offset, P0[Npatas], FinApoyo[Npatas], FinTranfer[Npatas]; camina12::AngulosMotor qMotor; ros::Publisher chatter_pub; FILE *fp1,*fp2,*fp3,*fp4,*fp5,*fp6; //-- Funciones punto3d Trayectoria_FaseApoyo(float t_Trayectoria,punto3d PInicio); punto3d Trayectoria_FaseTrans_Eliptica(float t_Trayectoria,punto3d PInicio, punto3d PFin); void CinematicaInversa(float *Qs,punto3d P_in); // Topic subscriber callbacks: void infoCallback(const vrep_common::VrepInfo::ConstPtr& info) { simulationTime=info->simulationTime.data; simulationRunning=(info->simulatorState.data&1)!=0; } /* Callback que escucha el topico DatosDeTrayectoria calcula la trayectoria deseaday cinematica inversa para de motores y los publica */ void datosCallback(const camina12::DatosTrayectoriaPata msg_datoTrayectoria) { int correccion_ID, cambioEstado, Estado; float t_Trayectoria,alfa=0.0, T=0.0; float correccion_x,correccion_y; punto3d P1, PInicio, PFin, InicioApoyo; for(int k=0;k<Npatas;k++){ T = msg_datoTrayectoria.T[tripode[k]-1]; t_Trayectoria = msg_datoTrayectoria.t_Trayectoria[tripode[k]-1]; alfa = msg_datoTrayectoria.alfa; Estado = msg_datoTrayectoria.vector_estados[tripode[k]-1]; cambioEstado = msg_datoTrayectoria.cambio_estado[tripode[k]-1]; correccion_x = msg_datoTrayectoria.correccion_x[k]; correccion_y = msg_datoTrayectoria.correccion_y[k]; correccion_ID = msg_datoTrayectoria.correccion_ID[k]; InicioApoyo.x = (Offset.y-FinEspacioTrabajo_y)-lambda_maximo+correccion_y; InicioApoyo.y = 0.0; if(correccion_ID==Correccion_menosX){ InicioApoyo.y = -correccion_x; } else if (correccion_ID==Correccion_masX){ InicioApoyo.y = correccion_x; } if(cambioEstado==1){ FinApoyo[k] = P0[k]; FinTranfer[k] = InicioApoyo; } if(Inicio){ if(k==Npatas-1) Inicio=false; InicioApoyo.x=(Offset.y-FinEspacioTrabajo_y)-lambda_maximo; InicioApoyo.y=0.0; FinApoyo[k].x=Offset.y-FinEspacioTrabajo_y; FinApoyo[k].y=0.0; FinTranfer[k] = InicioApoyo; } //-----Parametrizacion de trayectoria eliptica en Sistema de Robot switch (Estado){ case Apoyo: PInicio=InicioApoyo; P0[k] = Trayectoria_FaseApoyo(t_Trayectoria,PInicio); break; case Transferencia: // Elipsis PInicio=FinApoyo[k]; PFin=FinTranfer[k]; P0[k] = Trayectoria_FaseTrans_Eliptica(t_Trayectoria/T,PInicio,PFin); break; default: ROS_ERROR("Nodo2: Error en estados"); break; } //-----Transformacion de trayectoria a Sistema de Pata P1 = TransformacionHomogenea(P0[k],Offset,phi[k]+alfa); //-----Cinematica Inversa float q[Neslabones]; CinematicaInversa(q,P1); qMotor.q1[k] = q[0]; qMotor.q2[k] = q[1]; qMotor.q3[k] = q[2]; switch (k){ case 0: fprintf(fp1,"%.3f\t%.3f\t%.3f\t%.3f\t%.3f\t%.3f\t%.3f\n",qMotor.q1[k],qMotor.q2[k],qMotor.q3[k],t_Trayectoria,P1.x,P1.y,P1.z); break; case 1: fprintf(fp2,"%.3f\t%.3f\t%.3f\t%.3f\t%.3f\t%.3f\t%.3f\n",qMotor.q1[k],qMotor.q2[k],qMotor.q3[k],t_Trayectoria,P1.x,P1.y,P1.z); break; case 2: fprintf(fp3,"%.3f\t%.3f\t%.3f\t%.3f\t%.3f\t%.3f\t%.3f\n",qMotor.q1[k],qMotor.q2[k],qMotor.q3[k],t_Trayectoria,P1.x,P1.y,P1.z); break; case 3: fprintf(fp4,"%.3f\t%.3f\t%.3f\t%.3f\t%.3f\t%.3f\t%.3f\n",qMotor.q1[k],qMotor.q2[k],qMotor.q3[k],t_Trayectoria,P1.x,P1.y,P1.z); break; case 4: fprintf(fp5,"%.3f\t%.3f\t%.3f\t%.3f\t%.3f\t%.3f\t%.3f\n",qMotor.q1[k],qMotor.q2[k],qMotor.q3[k],t_Trayectoria,P1.x,P1.y,P1.z); break; case 5: fprintf(fp6,"%.3f\t%.3f\t%.3f\t%.3f\t%.3f\t%.3f\t%.3f\n",qMotor.q1[k],qMotor.q2[k],qMotor.q3[k],t_Trayectoria,P1.x,P1.y,P1.z); break; } } //fin for Npatas //---Publica angulos motores---- chatter_pub.publish(qMotor); } int main(int argc, char **argv){ if (argc>=17) { dh=atof(argv[1]); Offset.x=atof(argv[2]); Offset.y=atof(argv[3]); Offset.z=atof(argv[4]); velocidadApoyo=atof(argv[5]); for(int k=0;k<Npatas;k++) phi[k]=atof(argv[6+k])*pi/180; for(int k=0;k<Npatas;k++) tripode[k] = atoi(argv[6+Npatas+k]); } else { ROS_ERROR("Nodo 2::Indique argumentos!\n"); sleep(5000); return 0; } /*Inicio nodo de ROS*/ std::string nodeName("Nodo2_Parametrizacion"); ros::init(argc,argv,nodeName.c_str()); ros::NodeHandle node; ROS_INFO("Nodo2_Parametrizacion just started\n"); //-- Topicos susbcritos y publicados chatter_pub = node.advertise<camina12::AngulosMotor>("DatosDeMotores", 100); ros::Subscriber subInfo = node.subscribe("/vrep/info",1,infoCallback); //-- Recibe topico ros::Subscriber sub = node.subscribe("datosTrayectoria", 100, datosCallback); fp1 = fopen("../fuerte_workspace/sandbox/TesisMaureen/ROS/camina12/datos/QXEnviada_Pata1.txt","w+"); fp2 = fopen("../fuerte_workspace/sandbox/TesisMaureen/ROS/camina12/datos/QXEnviada_Pata2.txt","w+"); fp3 = fopen("../fuerte_workspace/sandbox/TesisMaureen/ROS/camina12/datos/QXEnviada_Pata3.txt","w+"); fp4 = fopen("../fuerte_workspace/sandbox/TesisMaureen/ROS/camina12/datos/QXEnviada_Pata4.txt","w+"); fp5 = fopen("../fuerte_workspace/sandbox/TesisMaureen/ROS/camina12/datos/QXEnviada_Pata5.txt","w+"); fp6 = fopen("../fuerte_workspace/sandbox/TesisMaureen/ROS/camina12/datos/QXEnviada_Pata6.txt","w+"); //-- Datos de envio for(int k=0;k<Npatas;k++){ qMotor.q1.push_back(0); qMotor.q2.push_back(0); qMotor.q3.push_back(0); } while (ros::ok() && simulationRunning) { ros::spinOnce(); } fclose(fp1); fclose(fp2); fclose(fp3); fclose(fp4); fclose(fp5); fclose(fp6); //ROS_INFO("Adios2!"); ros::shutdown(); return 0; } //---Caso parte 1 trayectoria---- //-- Periodo A-B punto3d Trayectoria_FaseApoyo(float t_Trayectoria,punto3d PInicio){ punto3d salida; salida.x = PInicio.x + velocidadApoyo*t_Trayectoria; salida.y = PInicio.y; salida.z = PInicio.z; return(salida); } //---Caso parte 2 trayectoria---- //-- Elipsis punto3d Trayectoria_FaseTrans_Eliptica(float t_Trayectoria,punto3d PInicio, punto3d PFin){ punto3d salida, Po; float teta, dL; float L, Lx, Ly, gamma; Lx = PFin.x - PInicio.x; Ly = PFin.y - PInicio.y; L = sqrt(Lx*Lx + Ly*Ly); gamma = atan(Ly/Lx); Po.x = PInicio.x + Lx/2; Po.y = PInicio.y + Ly/2; Po.z = 0.0; // t_aux = t_Trayectoria/T_in; teta = pi*t_Trayectoria; dL = (L/2)*cos(teta); // if(Npata_arg==1) ROS_INFO("Pi.x=%.4f\t Pi.y=%.4f\t Pf.x=%.4f\t Pf.y=%.4f\t",PInicio.x,PInicio.y,PFin.x,PFin.y); salida.x = Po.x + dL*cos(gamma); salida.y = Po.y + dL*sin(gamma); salida.z = Po.z + dh*sin(teta); return(salida); } //---Cinematica inversa--- void CinematicaInversa(float *Qs,punto3d P_in){ float L23=0.0, L23_aux=0.0, beta=0.0, teta=0.0, gamma1=0.0, arg=0; //------calculo q1------ //p[0] = atan2(px,py); Qs[0] = atan2(P_in.y,P_in.x)-pi/2; //---------------------- L23_aux = sqrt(P_in.x*P_in.x + P_in.y*P_in.y) - L1; L23 = sqrt(L23_aux*L23_aux + P_in.z*P_in.z); //------calculo q3------ arg = (L2*L2 + L3*L3 - L23*L23)/(2*L2*L3); if (fabs(arg)>1) { ROS_ERROR("ERROR Cinversa_server acos q3"); return; } beta = acos(arg); //El ajuste de pi se hace para coincidir con eje de D-H //p[2] = pi - beta; Qs[2] = beta-pi/2; //---------------------- //------calculo q2------ arg = (L3/L23)*sin(beta); if (fabs(arg)>1) { ROS_ERROR("ERROR Cinversa_server asin q2"); return; } teta = atan(-P_in.z/L23_aux); gamma1 = asin(arg); //El ajuste de pi/2 se hace para coincidir con eje de D-H //p[1] = pi/2 - (teta-gamma); Qs[1] = teta-gamma1; }
c0f698d099be20b17b97868f3957c598827e5a62
b42b4c4b6bb01c79f2b3214d5ffd05a735b4d823
/games/nibbler/Fruit.cpp
272a35baa70a9c2f38e39ca276fe6e3786e95dd4
[]
no_license
overnxt/retromania
a8e73df181c8b725d130ed24f2c67eed463b2f33
065b63181a11f087e1f40f7582c6f5d82b557ed7
refs/heads/master
2021-06-20T02:54:41.750477
2017-07-31T16:08:56
2017-07-31T16:08:56
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,375
cpp
Fruit.cpp
#include <algorithm> #include <random> #include "Nibbler.hpp" namespace retromania { void Nibbler::manageFruits() { eatFruit(); checkFruits(); if (_fruits == 0) spawnFruit(); if ( _fruits < 3) { std::mt19937 rng; rng.seed(std::random_device()()); std::uniform_int_distribution<std::mt19937::result_type> randomizator(0, 100); if (randomizator(rng) == 50) { spawnFruit(); } } } void Nibbler::spawnFruit() { int fruitPos; int randMax = _map->height * _map->width; std::mt19937 rng; rng.seed(std::random_device()()); std::uniform_int_distribution<std::mt19937::result_type> randomizator(0, (unsigned long) randMax - 1); do { fruitPos = (int) randomizator(rng); } while (_map->tiles.at(fruitPos) != EMPTY); _map->tiles.at(fruitPos) = FRUIT; _fruits++; } void Nibbler::eatFruit() { if (_map->tiles.at(_hero->getPositionAt(0)) == FRUIT) { _score.setValue(_score.getValue() + 10); _fruits--; _justEaten = true; _queue = _hero->getPositionAt(_hero->getPosition().size() - 1); } } void Nibbler::feedSnake() { if (_justEaten) { ACharacter::Pos tmp = _hero->getPosition(); tmp.push_back(_queue); _hero->setPosition(tmp); } _justEaten = false; } void Nibbler::checkFruits() { _fruits = 0; for (auto& it : _map->tiles) { if (it == FRUIT) { _fruits++; } } } }
28b4012b8291cc8da87ebd5f1cbcd97f23cdeafe
a27c13c55680e95a0cfe375dd02daae9d8e64d04
/mods/android/bionic/tests/time_test.cpp
b3192c82b2afdce1c09748d909f18f227c5747df
[ "LicenseRef-scancode-unicode", "Apache-2.0" ]
permissive
NaiveTorch/ARC
4572ed94d01f3b237492579be4091f3874a8dfe0
4007a4e72f742bb50de5615b2adb7e46d569b7ed
refs/heads/master
2021-01-22T06:38:12.078262
2014-10-22T15:43:28
2014-10-22T15:43:28
25,082,433
3
0
null
null
null
null
UTF-8
C++
false
false
6,405
cpp
time_test.cpp
/* * Copyright (C) 2013 The Android Open Source Project * * 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 <sys/cdefs.h> #include <features.h> #include <gtest/gtest.h> // ARC MOD BEGIN #include <errno.h> #include <sys/time.h> // ARC MOD END #include <time.h> #ifdef __BIONIC__ // mktime_tz is a bionic extension. #include <libc/private/bionic_time.h> // ARC MOD BEGIN // Neither NaCl nor Bare Metal can open tzdata. #if !defined(__native_client__) && !defined(BARE_METAL_BIONIC) // ARC MOD END TEST(time, mktime_tz) { struct tm epoch; memset(&epoch, 0, sizeof(tm)); epoch.tm_year = 1970 - 1900; epoch.tm_mon = 1; epoch.tm_mday = 1; // Alphabetically first. Coincidentally equivalent to UTC. ASSERT_EQ(2678400, mktime_tz(&epoch, "Africa/Abidjan")); // Alphabetically last. Coincidentally equivalent to UTC. ASSERT_EQ(2678400, mktime_tz(&epoch, "Zulu")); // Somewhere in the middle, not UTC. ASSERT_EQ(2707200, mktime_tz(&epoch, "America/Los_Angeles")); // Missing. Falls back to UTC. ASSERT_EQ(2678400, mktime_tz(&epoch, "PST")); } // ARC MOD BEGIN #endif // ARC MOD END #endif TEST(time, gmtime) { time_t t = 0; tm* broken_down = gmtime(&t); ASSERT_TRUE(broken_down != NULL); ASSERT_EQ(0, broken_down->tm_sec); ASSERT_EQ(0, broken_down->tm_min); ASSERT_EQ(0, broken_down->tm_hour); ASSERT_EQ(1, broken_down->tm_mday); ASSERT_EQ(0, broken_down->tm_mon); ASSERT_EQ(1970, broken_down->tm_year + 1900); } #ifdef __BIONIC__ TEST(time, mktime_10310929) { struct tm t; memset(&t, 0, sizeof(tm)); t.tm_year = 200; t.tm_mon = 2; t.tm_mday = 10; ASSERT_EQ(-1, mktime(&t)); // ARC MOD BEGIN // Temporarily disabled the test. // TODO(yusukes): Investigate why this crashes and re-enable it. // ASSERT_EQ(-1, mktime_tz(&t, "UTC")); // ARC MOD END } #endif // ARC MOD BEGIN UPSTREAM bionic-add-time-test namespace { double GetDoubleTimeFromTimeval(struct timeval* tv) { return tv->tv_sec + tv->tv_usec * 1e-6; } double GetDoubleTimeFromTimespec(struct timespec* ts) { return ts->tv_sec + ts->tv_nsec * 1e-9; } } // namespace TEST(time, test_CLOCK_REALTIME) { struct timespec ts; struct timeval tv; ASSERT_EQ(0, gettimeofday(&tv, NULL)); ASSERT_EQ(0, clock_gettime(CLOCK_REALTIME, &ts)); static const int kMaxAcceptableTimeDiff = 3; EXPECT_NEAR(tv.tv_sec, ts.tv_sec, kMaxAcceptableTimeDiff); } TEST(time, test_CLOCK_PROCESS_CPUTIME_ID) { struct timespec ts = {-1, -1}; ASSERT_EQ(0, clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &ts)); ASSERT_NE(-1, ts.tv_sec); ASSERT_NE(-1, ts.tv_nsec); } TEST(time, test_CLOCK_THREAD_CPUTIME_ID) { struct timespec ts = {-1, -1}; ASSERT_EQ(0, clock_gettime(CLOCK_THREAD_CPUTIME_ID, &ts)); ASSERT_NE(-1, ts.tv_sec); ASSERT_NE(-1, ts.tv_nsec); } TEST(time, nanosleep) { struct timespec ts; struct timeval tv; ASSERT_EQ(0, gettimeofday(&tv, NULL)); double gettimeofday_time = GetDoubleTimeFromTimeval(&tv); ASSERT_EQ(0, clock_gettime(CLOCK_REALTIME, &ts)); double clock_realtime_time = GetDoubleTimeFromTimespec(&ts); ASSERT_EQ(0, clock_gettime(CLOCK_MONOTONIC, &ts)); double clock_monotonic_time = GetDoubleTimeFromTimespec(&ts); static const double kMaxAcceptableTimeDiff = 3.0; EXPECT_NEAR(gettimeofday_time, clock_realtime_time, kMaxAcceptableTimeDiff); // 100 msecs. ts.tv_sec = 0; ts.tv_nsec = 100000000; ASSERT_EQ(0, nanosleep(&ts, NULL)); // We test we sleep at least 50 msecs and at most 2 secs. static const double kMinElapsedTime = 0.05; static const double kMaxElapsedTime = 3.0; ASSERT_EQ(0, gettimeofday(&tv, NULL)); double gettimeofday_elapsed = GetDoubleTimeFromTimeval(&tv) - gettimeofday_time; EXPECT_LT(kMinElapsedTime, gettimeofday_elapsed); EXPECT_GT(kMaxElapsedTime, gettimeofday_elapsed); ASSERT_EQ(0, clock_gettime(CLOCK_REALTIME, &ts)); double clock_realtime_elapsed = GetDoubleTimeFromTimespec(&ts) - clock_realtime_time; EXPECT_LT(kMinElapsedTime, clock_realtime_elapsed); EXPECT_GT(kMaxElapsedTime, clock_realtime_elapsed); ASSERT_EQ(0, clock_gettime(CLOCK_MONOTONIC, &ts)); double clock_monotonic_elapsed = GetDoubleTimeFromTimespec(&ts) - clock_monotonic_time; EXPECT_LT(kMinElapsedTime, clock_monotonic_elapsed); EXPECT_GT(kMaxElapsedTime, clock_monotonic_elapsed); } TEST(time, gettimeofday_NULL) { ASSERT_EQ(0, gettimeofday(NULL, NULL)); } TEST(time, gettimeofday_timezone) { struct timezone tz; ASSERT_EQ(0, gettimeofday(NULL, &tz)); // As of now, fields in |tz| are always zero on NaCl, but this can // be changed in future? } TEST(time, clock_gettime_NULL) { ASSERT_NE(0, clock_gettime(CLOCK_REALTIME, NULL)); EXPECT_EQ(EFAULT, errno); ASSERT_NE(0, clock_gettime(CLOCK_MONOTONIC, NULL)); EXPECT_EQ(EFAULT, errno); ASSERT_NE(0, clock_gettime(CLOCK_PROCESS_CPUTIME_ID, NULL)); EXPECT_EQ(EFAULT, errno); ASSERT_NE(0, clock_gettime(CLOCK_THREAD_CPUTIME_ID, NULL)); EXPECT_EQ(EFAULT, errno); } TEST(time, clock_getres) { struct timespec ts = { 99, 99 }; ASSERT_EQ(0, clock_getres(CLOCK_REALTIME, &ts)); // It would be safe to assume the time resolution is <1 sec. EXPECT_EQ(0, ts.tv_sec); EXPECT_NE(0, ts.tv_nsec); ts.tv_sec = 99; ASSERT_EQ(0, clock_getres(CLOCK_MONOTONIC, &ts)); EXPECT_EQ(0, ts.tv_sec); EXPECT_NE(0, ts.tv_nsec); ts.tv_sec = 99; ASSERT_EQ(0, clock_getres(CLOCK_PROCESS_CPUTIME_ID, &ts)); EXPECT_EQ(0, ts.tv_sec); EXPECT_NE(0, ts.tv_nsec); ts.tv_sec = 99; ASSERT_EQ(0, clock_getres(CLOCK_THREAD_CPUTIME_ID, &ts)); EXPECT_EQ(0, ts.tv_sec); EXPECT_NE(0, ts.tv_nsec); } TEST(time, clock_getres_NULL) { ASSERT_EQ(0, clock_getres(CLOCK_REALTIME, NULL)); ASSERT_EQ(0, clock_getres(CLOCK_MONOTONIC, NULL)); ASSERT_EQ(0, clock_getres(CLOCK_PROCESS_CPUTIME_ID, NULL)); ASSERT_EQ(0, clock_getres(CLOCK_THREAD_CPUTIME_ID, NULL)); } // ARC MOD END UPSTREAM
f7f5b43d56c657ddeae967afeaf2fa5450131176
5e5d3b9a20bf0ec666990a2bea9ec9caec75e02a
/TestGraph.c++
5aa290e4a127836db8b226317c34c9639f87f023
[]
no_license
lclg21/cs378-graph
697faf2f09ae33ae2d1d0d4c031dc077c853ac59
b57a7a50439094b8c040c908b5f06f8f305a0340
refs/heads/master
2021-01-18T06:09:20.998989
2015-07-27T02:22:36
2015-07-27T02:22:36
39,175,971
0
0
null
null
null
null
UTF-8
C++
false
false
11,402
TestGraph.c++
// -------------------------------- // projects/g++/graph/TestGraph.c++ // Copyright (C) 2015 // Glenn P. Downing // -------------------------------- // -------- // includes // -------- #include <iostream> // cout, endl #include <iterator> // ostream_iterator #include <sstream> // ostringstream #include <utility> // pair #include "boost/graph/adjacency_list.hpp" // adjacency_list #include "boost/graph/topological_sort.hpp"// topological_sort #include "gtest/gtest.h" #include "Graph.h" using namespace std; using testing::Test; using testing::Types; // --------- // TestGraph // --------- template <typename G> struct TestGraph : Test { // -------- // typedefs // -------- typedef G graph_type; typedef typename G::vertex_descriptor vertex_descriptor; typedef typename G::edge_descriptor edge_descriptor; typedef typename G::vertex_iterator vertex_iterator; typedef typename G::edge_iterator edge_iterator; typedef typename G::adjacency_iterator adjacency_iterator; typedef typename G::vertices_size_type vertices_size_type; typedef typename G::edges_size_type edges_size_type; }; // directed, sparse, unweighted // possibly connected // possibly cyclic typedef Types< boost::adjacency_list<boost::setS, boost::vecS, boost::directedS>, Graph> graph_types; /* typedef Types<boost::adjacency_list<boost::setS, boost::vecS, boost::directedS>> graph_types; */ TYPED_TEST_CASE(TestGraph, graph_types); // -------- // add_edge // -------- TYPED_TEST(TestGraph, add_edge1) { typedef typename TestFixture::graph_type graph_type; typedef typename TestFixture::vertex_descriptor vertex_descriptor; graph_type g; vertex_descriptor vdA = add_vertex(g); vertex_descriptor vdB = add_vertex(g); bool b = add_edge(vdA, vdB, g).second; ASSERT_TRUE(b);} TYPED_TEST(TestGraph, add_edge2) { typedef typename TestFixture::graph_type graph_type; typedef typename TestFixture::vertex_descriptor vertex_descriptor; graph_type g; vertex_descriptor vdA = add_vertex(g); vertex_descriptor vdB = add_vertex(g); vertex_descriptor vdC = add_vertex(g); bool b = add_edge(vdA, vdB, g).second; ASSERT_TRUE(b); bool c = add_edge(vdA, vdC, g).second; ASSERT_TRUE(c); bool d = add_edge(vdA, vdC, g).second; ASSERT_FALSE(d);} TYPED_TEST(TestGraph, add_edge3) { typedef typename TestFixture::graph_type graph_type; graph_type g; bool a = add_edge(9, 10, g).second; ASSERT_EQ(num_vertices(g), 11); ASSERT_TRUE(a); bool b = add_edge(9, 10, g).second; ASSERT_FALSE(b);} // ---------- // add_vertex // ---------- TYPED_TEST(TestGraph, add_vertex_1) { typedef typename TestFixture::graph_type graph_type; graph_type g; add_vertex(g); ASSERT_EQ(1, num_vertices(g)); } TYPED_TEST(TestGraph, add_vertex_2) { typedef typename TestFixture::graph_type graph_type; graph_type g; auto v1 = add_vertex(g); auto v2 = add_vertex(g); ASSERT_EQ(2, num_vertices(g)); ASSERT_NE(v1, v2); } TYPED_TEST(TestGraph, add_vertex_3) { typedef typename TestFixture::graph_type graph_type; graph_type g; add_vertex(g); add_vertex(g); add_vertex(g); add_vertex(g); ASSERT_EQ(4, num_vertices(g)); } // ---- // edge // ---- TYPED_TEST(TestGraph, edge_1) { typedef typename TestFixture::graph_type graph_type; graph_type g; auto u = add_vertex(g); auto v = add_vertex(g); auto p = edge(u, v, g); ASSERT_FALSE(p.second); } TYPED_TEST(TestGraph, edge_2) { typedef typename TestFixture::graph_type graph_type; typedef typename TestFixture::vertex_descriptor vertex_descriptor; graph_type g; vertex_descriptor u = 0; vertex_descriptor v = 1; auto p1 = add_edge(u, v, g); auto p2 = edge(u, v, g); ASSERT_EQ(p2.first, p1.first); } TYPED_TEST(TestGraph, edge_3) { typedef typename TestFixture::graph_type graph_type; typedef typename TestFixture::vertex_descriptor vertex_descriptor; graph_type g; vertex_descriptor u = 0; vertex_descriptor v = 1; vertex_descriptor w = 2; add_edge(u, v, g); add_edge(v, w, g); auto p = edge(u, w, g); ASSERT_FALSE(p.second); } // ----- // edges // ----- TYPED_TEST(TestGraph, edges_1) { typedef typename TestFixture::graph_type graph_type; typedef typename TestFixture::vertex_descriptor vertex_descriptor; graph_type g; vertex_descriptor u = 0; vertex_descriptor v = 1; add_edge(u, v, g); auto p = edges(g); ASSERT_EQ(p.second, ++p.first); } TYPED_TEST(TestGraph, edges_2) { typedef typename TestFixture::graph_type graph_type; graph_type g; add_vertex(g); add_vertex(g); auto p = edges(g); ASSERT_EQ(p.second, p.first); } TYPED_TEST(TestGraph, edges_3) { typedef typename TestFixture::graph_type graph_type; typedef typename TestFixture::vertex_descriptor vertex_descriptor; graph_type g; vertex_descriptor u = 0; vertex_descriptor v = 1; vertex_descriptor w = 2; vertex_descriptor x = 3; add_edge(u, v, g); add_edge(v, w, g); add_edge(w, x, g); add_edge(x, u, g); auto p = edges(g); int i = 4; while (i-- > 0) { ++p.first; } ASSERT_EQ(p.second, p.first); } // --------- // num_edges // --------- TYPED_TEST(TestGraph, num_edges_1) { typedef typename TestFixture::graph_type graph_type; graph_type g; auto u = add_vertex(g); auto v = add_vertex(g); add_edge(u, v, g); auto n = num_edges(g); ASSERT_EQ(1, n); } TYPED_TEST(TestGraph, num_edges_2) { typedef typename TestFixture::graph_type graph_type; graph_type g; auto n = num_edges(g); ASSERT_EQ(0, n); } TYPED_TEST(TestGraph, num_edges_3) { typedef typename TestFixture::graph_type graph_type; graph_type g; auto u = add_vertex(g); auto v = add_vertex(g); add_edge(u, v, g); add_edge(v, u, g); auto n = num_edges(g); ASSERT_EQ(2, n); } // ------------ // num_vertices // ------------ TYPED_TEST(TestGraph, num_vertices_1) { typedef typename TestFixture::graph_type graph_type; graph_type g; auto n = num_vertices(g); ASSERT_EQ(0, n); } TYPED_TEST(TestGraph, num_vertices_2) { typedef typename TestFixture::graph_type graph_type; graph_type g; add_vertex(g); add_vertex(g); add_vertex(g); auto n = num_vertices(g); ASSERT_EQ(3, n); } TYPED_TEST(TestGraph, num_vertices_3) { typedef typename TestFixture::graph_type graph_type; typedef typename TestFixture::vertex_descriptor vertex_descriptor; graph_type g; vertex_descriptor u = 0; vertex_descriptor v = 1; add_edge(u, v, g); auto n = num_vertices(g); ASSERT_EQ(2, n); } TYPED_TEST(TestGraph, num_vertices_4) { typedef typename TestFixture::graph_type graph_type; typedef typename TestFixture::vertex_descriptor vertex_descriptor; graph_type g; vertex_descriptor u = 0; vertex_descriptor v = 1; add_edge(u, v, g); add_edge(v, u, g); auto n = num_vertices(g); ASSERT_EQ(2, n); } // ------ // source // ------ TYPED_TEST(TestGraph, source_1) { typedef typename TestFixture::graph_type graph_type; graph_type g; auto u = add_vertex(g); auto v = add_vertex(g); auto p = add_edge(u, v, g); auto ud = source(p.first, g); ASSERT_EQ(u, ud); } TYPED_TEST(TestGraph, source_2) { typedef typename TestFixture::graph_type graph_type; graph_type g; auto u = add_vertex(g); auto v = add_vertex(g); auto p = add_edge(u, v, g); auto ud = source(p.first, g); ASSERT_NE(v, ud); } TYPED_TEST(TestGraph, source_3) { typedef typename TestFixture::graph_type graph_type; graph_type g; auto u = add_vertex(g); auto v = add_vertex(g); auto w = add_vertex(g); auto p1 = add_edge(u, v, g); auto p2 = add_edge(v, w, g); auto ud = source(p1.first, g); auto vd = source(p2.first, g); ASSERT_EQ(u, ud); ASSERT_EQ(v, vd); } // ------ // target // ------ TYPED_TEST(TestGraph, target_1) { typedef typename TestFixture::graph_type graph_type; graph_type g; auto u = add_vertex(g); auto v = add_vertex(g); auto p = add_edge(u, v, g); auto vd = target(p.first, g); ASSERT_EQ(v, vd); } TYPED_TEST(TestGraph, target_2) { typedef typename TestFixture::graph_type graph_type; graph_type g; auto u = add_vertex(g); auto v = add_vertex(g); auto p = add_edge(u, v, g); auto vd = target(p.first, g); ASSERT_NE(u, vd); } TYPED_TEST(TestGraph, target_3) { typedef typename TestFixture::graph_type graph_type; graph_type g; auto u = add_vertex(g); auto v = add_vertex(g); auto w = add_vertex(g); auto p1 = add_edge(u, v, g); auto p2 = add_edge(v, w, g); auto vd = target(p1.first, g); auto wd = target(p2.first, g); ASSERT_EQ(v, vd); ASSERT_EQ(w, wd); } // ------ // vertex // ------ TYPED_TEST(TestGraph, vertex_1) { typedef typename TestFixture::graph_type graph_type; graph_type g; auto u = add_vertex(g); ASSERT_EQ(u, vertex(0, g)); } TYPED_TEST(TestGraph, vertex_2) { typedef typename TestFixture::graph_type graph_type; graph_type g; add_vertex(g); add_vertex(g); add_vertex(g); ASSERT_EQ(2, vertex(2, g)); } TYPED_TEST(TestGraph, vertex_3) { typedef typename TestFixture::graph_type graph_type; graph_type g; add_vertex(g); add_vertex(g); add_vertex(g); add_vertex(g); add_vertex(g); auto u = add_vertex(g); add_vertex(g); add_vertex(g); ASSERT_EQ(u, vertex(5, g)); } // -------- // vertices // -------- TYPED_TEST(TestGraph, vertices_1) { typedef typename TestFixture::graph_type graph_type; graph_type g; auto p = vertices(g); ASSERT_EQ(p.first, p.second); } TYPED_TEST(TestGraph, vertices_2) { typedef typename TestFixture::graph_type graph_type; graph_type g; add_vertex(g); add_vertex(g); auto p = vertices(g); ASSERT_EQ(p.second, ++++p.first); } TYPED_TEST(TestGraph, vertices_3) { typedef typename TestFixture::graph_type graph_type; graph_type g; add_vertex(g); add_vertex(g); add_vertex(g); auto p = vertices(g); ASSERT_EQ(p.second, ++++++p.first); } // ----------- // constructor // ----------- TYPED_TEST(TestGraph, constructor) { typedef typename TestFixture::graph_type graph_type; graph_type g; ASSERT_EQ(0, num_vertices(g)); } // ----------------- // adjacent_vertices // ----------------- TYPED_TEST(TestGraph, test_adjacent_vertices) { typedef typename TestFixture::graph_type graph_type; typedef typename TestFixture::vertex_descriptor vertex_descriptor; typedef typename TestFixture::adjacency_iterator adjacency_iterator; graph_type g; vertex_descriptor vdA = add_vertex(g); vertex_descriptor vdB = add_vertex(g); vertex_descriptor vdC = add_vertex(g); add_edge(vdA, vdB, g); add_edge(vdA, vdC, g); pair<adjacency_iterator, adjacency_iterator> p = adjacent_vertices(vdA, g); adjacency_iterator b = p.first; adjacency_iterator e = p.second; if (b != e) { vertex_descriptor vd = *b; ASSERT_EQ(vdB, vd);} ++b; if (b != e) { vertex_descriptor vd = *b; ASSERT_EQ(vdC, vd);} ++b; ASSERT_EQ(e, b);}
9702a8f0defccdc61132b74cce4b3cd8788bc4ac
72e3e602546bc94a392ed7a485a948aa3895218e
/Engine/cameraclass.cpp
e927be66fd949e4ce137ea47c9d1f1ac9578ebd5
[]
no_license
fromasmtodisasm/DirectXCpp
b3c304c9c0748313e33d4994db59dc58d0b0e580
3026189a07af7567d83ee69ca651969ebb5446bc
refs/heads/master
2021-06-12T09:41:32.160190
2017-03-21T22:19:17
2017-03-21T22:19:17
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,979
cpp
cameraclass.cpp
#include "cameraclass.h" CameraClass::CameraClass() { positionX = 0.0f; positionY = 0.0f; positionZ = 0.0f; rotationX = 0.0f; rotationY = 0.0f; rotationZ = 0.0f; } CameraClass::CameraClass(const CameraClass& other) { } CameraClass::~CameraClass() { } void CameraClass::SetPosition(float x, float y, float z) { positionX = x; positionY = y; positionZ = z; } void CameraClass::SetRotation(float x, float y, float z) { rotationX = x; rotationY = y; rotationZ = z; } XMFLOAT3 CameraClass::GetPosition() { return XMFLOAT3(positionX, positionY, positionZ); } XMFLOAT3 CameraClass::GetRotation() { return XMFLOAT3(rotationX, rotationY, rotationZ); } void CameraClass::Render() { XMFLOAT3 up, lookAt, position; XMVECTOR upVector, positionVector, lookAtVector; float yaw, pitch, roll; XMMATRIX rotationMatrix; //Setup the vectors up.x = 0.0f; up.y = 1.0f; up.z = 0.0f; //Load into structures upVector = XMLoadFloat3(&up); //setup the the position of camera position.x = positionX; position.y = positionY; position.z = positionZ; positionVector = XMLoadFloat3(&position); //setup where the camera is looking by default lookAt.x = 0.0f; lookAt.y = 0.0f; lookAt.z = 1.0f; lookAtVector = XMLoadFloat3(&lookAt); pitch = rotationX * 0.0174532925f; yaw = rotationY * 0.0174532925f; roll = rotationZ * 0.0174532925f; //Create rotation matrix rotationMatrix = XMMatrixRotationRollPitchYaw(pitch, yaw, roll); //Trasform the lookAt and up vector by the rotation matrix so the view is correctly rotated at the origin lookAtVector = XMVector3TransformCoord(lookAtVector, rotationMatrix); upVector = XMVector3TransformCoord(upVector, rotationMatrix); lookAtVector = XMVectorAdd(positionVector, lookAtVector); //Finally create the view matrix from the three updated vectors this->viewMatrix = XMMatrixLookAtLH(positionVector, lookAtVector, upVector); } void CameraClass::GetViewMatrix(XMMATRIX& viewMatrix) { viewMatrix = this->viewMatrix; }
06a5476af504cd4e71fd24df3fcf58ac7b993866
681e5578721dabbc517262463cdb48f3630b7c29
/src/programs/Simulation/mcsmear/MyProcessor.cc
320c7a7b703d8e8e08848683976e9dd1a596b335
[]
no_license
JeffersonLab/sim-recon
d7a76e03887cfee255e1309ade73edb5a4f3bd87
de076695f16956fe649366b53959c7582285001f
refs/heads/master
2020-04-12T09:00:00.639534
2018-07-30T20:26:51
2018-07-30T20:26:51
39,176,669
15
20
null
2018-07-30T20:26:52
2015-07-16T04:35:19
C++
UTF-8
C++
false
false
16,375
cc
MyProcessor.cc
// Author: David Lawrence Sat Jan 29 09:37:37 EST 2011 // // // MyProcessor.cc // #include <iostream> #include <cmath> #include <vector> #include <map> using namespace std; #include <strings.h> #include "MyProcessor.h" #include "hddm_s_merger.h" #include <JANA/JEvent.h> #include <HDDM/DEventSourceHDDM.h> #include <TRACKING/DMCThrown.h> #include <DRandom2.h> extern char *OUTFILENAME; extern std::map<hddm_s::istream*,double> files2merge; extern std::map<hddm_s::istream*,hddm_s::streamposition> start2merge; extern std::map<hddm_s::istream*,int> skip2merge; static pthread_mutex_t output_file_mutex; static pthread_t output_file_mutex_last_owner; static pthread_mutex_t input_file_mutex; static pthread_t input_file_mutex_last_owner; #include <JANA/JCalibration.h> //static JCalibration *jcalib=NULL; static bool locCheckCCDBContext = true; //----------- // PrintCCDBWarning //----------- static void PrintCCDBWarning(string context) { jout << endl; jout << "===============================================================================" << endl; jout << " !!!!! WARNING !!!!!" << endl; jout << "You have either not specified a CCDB variation, or specified a variation" << endl; jout << "that appears inconsistent with processing simulated data." << endl; jout << "Be sure that this is what you want to do!" << endl; jout << endl; jout << " JANA_CALIB_CONTEXT = " << context << endl; jout << endl; jout << "For a more detailed list of CCDB variations used for simulations" << endl; jout << "see the following wiki page:" << endl; jout << endl; jout << " https://halldweb.jlab.org/wiki/index.php/Simulations#Simulation_Conditions" << endl; jout << "===============================================================================" << endl; jout << endl; } void mcsmear_thread_HUP_sighandler(int sig) { jerr<<" Caught HUP signal for thread 0x"<<hex<<pthread_self()<<dec<<" thread exiting..."<<endl; // We use output_file_mutex_owner to keep track (sort of) // of which thread has the mutex locked. This mutex is only // locked at the end of the evnt method. Once the lock is // obtained, this value is set to hold the id of the thread // that locked it. It may help in debugging to know the last // known thread to have locked the mutex when the signal // handler was called jerr<<endl; jerr<<" Last thread to lock output file mutex: 0x"<<hex<<pthread_self()<<dec<<endl; jerr<<" Attempting to unlock mutex to avoid deadlock." <<endl; jerr<<" However, the output file is likely corrupt at" <<endl; jerr<<" this point and the process should be restarted ..." <<endl; jerr<<endl; pthread_mutex_unlock(&output_file_mutex); pthread_exit(NULL); } //------------------------------------------------------------------ // init -Open output file //------------------------------------------------------------------ jerror_t MyProcessor::init(void) { // open HDDM file ofs = new ofstream(OUTFILENAME); if (!ofs->is_open()){ cout<<" Error opening output file \""<<OUTFILENAME<<"\"!"<<endl; exit(-1); } fout = new hddm_s::ostream(*ofs); Nevents_written = 0; HDDM_USE_COMPRESSION = 2; gPARMS->SetDefaultParameter("HDDM:USE_COMPRESSION", HDDM_USE_COMPRESSION, "Turn on/off compression of the output HDDM stream." " \"0\"=no compression, \"1\"=bz2 compression, \"2\"=z compression (default)"); HDDM_USE_INTEGRITY_CHECKS = true; gPARMS->SetDefaultParameter("HDDM:USE_INTEGRITY_CHECKS", HDDM_USE_INTEGRITY_CHECKS, "Turn on/off automatic integrity checking on the" " output HDDM stream." " Set to \"0\" to turn off (it's on by default)"); // enable on-the-fly bzip2 compression on output stream if (HDDM_USE_COMPRESSION == 0) { jout << " HDDM compression disabled" << std::endl; } else if (HDDM_USE_COMPRESSION == 1) { jout << " Enabling bz2 compression of output HDDM file stream" << std::endl; fout->setCompression(hddm_s::k_bz2_compression); } else { jout << " Enabling z compression of output HDDM file stream (default)" << std::endl; fout->setCompression(hddm_s::k_z_compression); } // enable a CRC data integrity check at the end of each event record if (HDDM_USE_INTEGRITY_CHECKS) { jout << " Enabling CRC data integrity check in output HDDM file stream" << std::endl; fout->setIntegrityChecks(hddm_s::k_crc32_integrity); } else { jout << " HDDM integrity checks disabled" << std::endl; } // We set the mutex type to "ERRORCHECK" so that if the // signal handler is called, we can unlock the mutex // safely whether we have it locked or not. pthread_mutexattr_t attr; pthread_mutexattr_init(&attr); pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_ERRORCHECK); pthread_mutex_init(&output_file_mutex, NULL); pthread_mutex_init(&input_file_mutex, NULL); // pthreads does not provide an "invalid" value for // a pthread_t that we can initialize with. Furthermore, // the pthread_t may be a simple as an integer or as // a complicated structure. Hence, to make this portable // we clear it with bzero. bzero(&output_file_mutex_last_owner, sizeof(pthread_t)); bzero(&input_file_mutex_last_owner, sizeof(pthread_t)); return NOERROR; } jerror_t MyProcessor::brun(JEventLoop *loop, int locRunNumber) { // Generally, simulations should be generated and analyzed with a non-default // set of calibrations, since the calibrations needed for simulations are // different than those needed for data. // Conventionally, the CCDB variations needed for simulations start with the // string "mc". To guard against accidentally not setting the variation correctly // we check to see if the variation is set and if it contains the string "mc". // Note that for now, we only print a warning and do not exit immediately. // It might be advisable to apply some tougher love. if(locCheckCCDBContext) { // only do this once locCheckCCDBContext = false; // load the CCDB context DApplication* locDApp = dynamic_cast<DApplication*>(japp); //DGeometry *dgeom=locDApp->GetDGeometry(locRunNumber); JCalibration* jcalib = locDApp->GetJCalibration(locRunNumber); string context = jcalib->GetContext(); jout << "checking context = " << context << endl; // Really we should parse the context string, but since "mc" shouldn't show up // outside of the context, we just search the whole string. // Also make sure that the variation is being set if( (context.find("variation") == string::npos) || (context.find("mc") == string::npos) ) { PrintCCDBWarning(context); } std::map<string, float> parms; jcalib->Get("TOF/tof_parms", parms); hddm_s_merger::set_ftof_min_delta_t_ns(parms.at("TOF_TWO_HIT_RESOL")); jcalib->Get("FDC/fdc_parms", parms); hddm_s_merger::set_fdc_wires_min_delta_t_ns(parms.at("FDC_TWO_HIT_RESOL")); jcalib->Get("START_COUNTER/start_parms", parms); hddm_s_merger::set_stc_min_delta_t_ns(parms.at("START_TWO_HIT_RESOL")); jcalib->Get("BCAL/bcal_parms", parms); hddm_s_merger::set_bcal_min_delta_t_ns(parms.at("BCAL_TWO_HIT_RESOL")); jcalib->Get("FCAL/fcal_parms", parms); hddm_s_merger::set_fcal_min_delta_t_ns(parms.at("FCAL_TWO_HIT_RESOL")); } // load configuration parameters for all the detectors if(smearer != NULL) delete smearer; smearer = new Smear(config, loop); #ifdef HAVE_RCDB // Pull configuration parameters from RCDB config->ParseRCDBConfigFile(locRunNumber); const double fadc250_period_ns(4.); const double fadc125_period_ns(8.); // hits merging / truncation parameters for the CDC hddm_s_merger::set_cdc_max_hits(config->readout["CDC"].at("NPEAK")); double cdc_ie = config->readout["CDC"].at("IE"); double cdc_pg = config->readout["CDC"].at("PG"); double cdc_gate = (cdc_ie + cdc_pg) * fadc125_period_ns; hddm_s_merger::set_cdc_integration_window_ns(cdc_gate); // hits merging / truncation parameters for the FDC hddm_s_merger::set_fdc_wires_max_hits(config->readout["FDC"].at("NHITS")); double fdc_width = config->readout["FDC"].at("WIDTH"); hddm_s_merger::set_fdc_wires_min_delta_t_ns(fdc_width + 5.); hddm_s_merger::set_fdc_strips_max_hits(config->readout["FDC"].at("NPEAK")); double fdc_ie = config->readout["FDC"].at("IE"); double fdc_pg = config->readout["FDC"].at("PG"); double fdc_gate = (fdc_ie + fdc_pg) * fadc125_period_ns; hddm_s_merger::set_fdc_strips_integration_window_ns(fdc_gate); // hits merging / truncation parameters for the STC hddm_s_merger::set_stc_adc_max_hits(config->readout["ST"].at("NPEAK")); hddm_s_merger::set_stc_tdc_max_hits(config->readout["ST"].at("NHITS")); double stc_width = config->readout["ST"].at("WIDTH"); hddm_s_merger::set_stc_min_delta_t_ns(stc_width + 5.); double stc_nsa = config->readout["ST"].at("NSA"); double stc_nsb = config->readout["ST"].at("NSB"); double stc_gate = (stc_nsa + stc_nsb) * fadc250_period_ns; hddm_s_merger::set_stc_integration_window_ns(stc_gate); // hits merging / truncation parameters for the BCAL hddm_s_merger::set_bcal_adc_max_hits(config->readout["BCAL"].at("NPEAK")); hddm_s_merger::set_bcal_tdc_max_hits(config->readout["BCAL"].at("NHITS")); double bcal_width = config->readout["BCAL"].at("WIDTH"); hddm_s_merger::set_bcal_min_delta_t_ns(bcal_width + 5.); double bcal_nsa = config->readout["BCAL"].at("NSA"); double bcal_nsb = config->readout["BCAL"].at("NSB"); double bcal_gate = (bcal_nsa + bcal_nsb) * fadc250_period_ns; hddm_s_merger::set_bcal_integration_window_ns(bcal_gate); // hits merging / truncation parameters for the TOF hddm_s_merger::set_ftof_adc_max_hits(config->readout["TOF"].at("NPEAK")); hddm_s_merger::set_ftof_tdc_max_hits(config->readout["TOF"].at("NHITS")); double ftof_width = config->readout["TOF"].at("WIDTH"); hddm_s_merger::set_ftof_min_delta_t_ns(ftof_width + 5.); double tof_nsa = config->readout["TOF"].at("NSA"); double tof_nsb = config->readout["TOF"].at("NSB"); double tof_gate = (tof_nsa + tof_nsb) * fadc250_period_ns; hddm_s_merger::set_ftof_integration_window_ns(tof_gate); // hits merging / truncation parameters for the FCAL hddm_s_merger::set_fcal_max_hits(config->readout["FCAL"].at("NPEAK")); double fcal_nsa = config->readout["FCAL"].at("NSA"); double fcal_nsb = config->readout["FCAL"].at("NSB"); double fcal_gate = (fcal_nsa + fcal_nsb) * fadc250_period_ns; hddm_s_merger::set_fcal_integration_window_ns(fcal_gate); // hits merging / truncation parameters for the CCAL hddm_s_merger::set_ccal_max_hits(config->readout["FCAL"].at("NPEAK")); hddm_s_merger::set_ccal_integration_window_ns(fcal_gate); // hits merging / truncation parameters for the PS hddm_s_merger::set_ps_max_hits(config->readout["PS"].at("NPEAK")); double ps_nsa = config->readout["PS"].at("NSA"); double ps_nsb = config->readout["PS"].at("NSB"); double ps_gate = (ps_nsa + ps_nsb) * fadc250_period_ns; hddm_s_merger::set_ps_integration_window_ns(ps_gate); hddm_s_merger::set_psc_adc_max_hits(config->readout["PSC"].at("NPEAK")); hddm_s_merger::set_psc_tdc_max_hits(config->readout["PSC"].at("NHITS")); double psc_width = config->readout["PSC"].at("WIDTH"); hddm_s_merger::set_psc_min_delta_t_ns(psc_width + 5.); double psc_nsa = config->readout["PSC"].at("NSA"); double psc_nsb = config->readout["PSC"].at("NSB"); double psc_gate = (psc_nsa + psc_nsb) * fadc250_period_ns; hddm_s_merger::set_psc_integration_window_ns(psc_gate); // hits merging / truncation parameters for the TAGM/TAGH hddm_s_merger::set_tag_adc_max_hits(config->readout["TAGM"].at("NPEAK")); hddm_s_merger::set_tag_tdc_max_hits(config->readout["TAGM"].at("NHITS")); double tag_width = config->readout["TAGM"].at("WIDTH"); hddm_s_merger::set_tag_min_delta_t_ns(tag_width + 5.); double tag_nsa = config->readout["TAGM"].at("NSA"); double tag_nsb = config->readout["TAGM"].at("NSB"); double tag_gate = (tag_nsa + tag_nsb) * fadc250_period_ns; hddm_s_merger::set_tag_integration_window_ns(tag_gate); // hits merging / truncation parameters for the TPOL hddm_s_merger::set_tpol_max_hits(config->readout["TPOL"].at("NPEAK")); #endif // HAVE_RCDB // fast forward any merger input files over skipped events std::map<hddm_s::istream*,hddm_s::streamposition>::iterator iter; for (iter = start2merge.begin(); iter != start2merge.end(); ++iter) { hddm_s::HDDM record2; for (int i=0; i < skip2merge[iter->first]; ++i) { if (!(*iter->first >> record2)) { //pthread_mutex_lock(&input_file_mutex); //input_file_mutex_last_owner = pthread_self(); iter->first->setPosition(start2merge.at(iter->first)); if (!(*iter->first >> record2)) { //pthread_mutex_unlock(&input_file_mutex); std::cerr << "Trying to merge from empty input file, " << "cannot continue!" << std::endl; exit(-1); } //pthread_mutex_unlock(&input_file_mutex); } } skip2merge[iter->first] = 0; } return NOERROR; } //------------------------------------------------------------------ // evnt - Do processing for each event here //------------------------------------------------------------------ jerror_t MyProcessor::evnt(JEventLoop *loop, uint64_t eventnumber) { JEvent& event = loop->GetJEvent(); JEventSource *source = event.GetJEventSource(); DEventSourceHDDM *hddm_source = dynamic_cast<DEventSourceHDDM*>(source); if (!hddm_source) { cerr << " This program MUST be used with an HDDM file as input!" << endl; exit(-1); } hddm_s::HDDM *record = (hddm_s::HDDM*)event.GetRef(); if (!record) return NOERROR; // Smear values smearer->SmearEvent(record); // Load any external events to be merged during smearing std::map<hddm_s::istream*,double>::iterator iter; for (iter = files2merge.begin(); iter != files2merge.end(); ++ iter) { int count = iter->second; if (count != iter->second) { count = gDRandom.Poisson(iter->second); } for (int i=0; i < count; ++i) { hddm_s::HDDM record2; if (!(*iter->first >> record2)) { //pthread_mutex_lock(&input_file_mutex); //input_file_mutex_last_owner = pthread_self(); iter->first->setPosition(start2merge.at(iter->first)); if (!(*iter->first >> record2)) { //pthread_mutex_unlock(&input_file_mutex); std::cerr << "Trying to merge from empty input file, " << "cannot continue!" << std::endl; exit(-1); } //pthread_mutex_unlock(&input_file_mutex); } hddm_s_merger::set_t_shift_ns(0); hddm_s::RFsubsystemList RFtimes = record2.getRFsubsystems(); hddm_s::RFsubsystemList::iterator RFiter; for (RFiter = RFtimes.begin(); RFiter != RFtimes.end(); ++RFiter) if (RFiter->getJtag() == "TAGH") hddm_s_merger::set_t_shift_ns(-RFiter->getTsync()); *record += record2; } } // Apply DAQ truncation to hit lists if (config->APPLY_HITS_TRUNCATION) hddm_s_merger::truncate_hits(*record); // Write event to output file //pthread_mutex_lock(&output_file_mutex); //output_file_mutex_last_owner = pthread_self(); *fout << *record; Nevents_written++; //pthread_mutex_unlock(&output_file_mutex); return NOERROR; } //------------------------------------------------------------------ // fini -Close output file here //------------------------------------------------------------------ jerror_t MyProcessor::fini(void) { if (fout) delete fout; if (ofs) { ofs->close(); cout << endl << "Closed HDDM file" << endl; } cout << " " << Nevents_written << " event written to " << OUTFILENAME << endl; return NOERROR; }
8742755f19a1af47af5f7cf7d612d7dd931f1a30
6b40e9dccf2edc767c44df3acd9b626fcd586b4d
/NT/enduser/netmeeting/core/setupdd.cpp
6c70bbc03bbee75563bf6ffed0fdd57a7ec31cd0
[]
no_license
jjzhang166/WinNT5_src_20201004
712894fcf94fb82c49e5cd09d719da00740e0436
b2db264153b80fbb91ef5fc9f57b387e223dbfc2
refs/heads/Win2K3
2023-08-12T01:31:59.670176
2021-10-14T15:14:37
2021-10-14T15:14:37
586,134,273
1
0
null
2023-01-07T03:47:45
2023-01-07T03:47:44
null
UTF-8
C++
false
false
5,494
cpp
setupdd.cpp
// File: setupdd.cpp // The code to install the NM display driver for Windows NT. // TODO: NM-specific HRESULT codes #include "precomp.h" #include "resource.h" #ifdef NMDLL_HACK inline HINSTANCE GetInstanceHandle() { return g_hInst; } #endif const TCHAR g_pcszDisplayCPLName[] = TEXT("DESK.CPL"); const CHAR g_pcszInstallDriverAPIName[] = "InstallGraphicsDriver"; const WCHAR g_pcwszDefaultModelName[] = L"Microsoft NetMeeting graphics driver"; const WCHAR g_pcwszDefaultINFName[] = L"MNMDD.INF"; // Maxmimum size of the model name string const int NAME_BUFFER_SIZE = 128; // Prototype for the function installed by the Display CPL typedef DWORD (*PFNINSTALLGRAPHICSDRIVER)( HWND hwnd, LPCWSTR pszSourceDirectory, LPCWSTR pszModel, LPCWSTR pszInf ); /* C A N I N S T A L L N T D I S P L A Y D R I V E R */ /*------------------------------------------------------------------------- %%Function: CanInstallNTDisplayDriver This function determines whether the entry point for installing the NT display driver is availalble (i.e. NT 4.0 SP3 or later). -------------------------------------------------------------------------*/ HRESULT CanInstallNTDisplayDriver(void) { if (!IsWindowsNT()) { return E_FAIL; } // We verify that the major version number is exactly 4 and either // the minor version number is greater than 0 or the service pack // number (which is stored in the high byte of the low word of the // CSD version) is 3 or greater. OSVERSIONINFO osvi; osvi.dwOSVersionInfoSize = sizeof(osvi); if (FALSE == ::GetVersionEx(&osvi)) { ERROR_OUT(("CanInstallNTDisplayDriver: GetVersionEx failed")); return E_FAIL; } HRESULT hr = E_FAIL; if (4 == osvi.dwMajorVersion) { if (0 == osvi.dwMinorVersion) { RegEntry re(NT_WINDOWS_SYSTEM_INFO_KEY, HKEY_LOCAL_MACHINE, FALSE); DWORD dwCSDVersion = re.GetNumber(REGVAL_NT_CSD_VERSION, 0); if (3 <= HIBYTE(LOWORD(dwCSDVersion))) { // This is NT 4.0, SP 3 or later hr = S_OK; } } else { // We assume that any future version of Windows NT 4.x (x > 0) // will support this. hr = S_OK; } } return hr; } /* I N S T A L L A P P S H A R I N G D D */ /*------------------------------------------------------------------------- %%Function: InstallAppSharingDD This function attempts to install the NT display driver. If it succeeds the machine MUST BE RESTARTED before it can be used. -------------------------------------------------------------------------*/ HRESULT InstallAppSharingDD(HWND hwnd) { HRESULT hr; CUSTRING custrPath; TCHAR szDir[MAX_PATH]; LPWSTR pwszSourcePath = NULL; LPWSTR pwszSourcePathEnd; WCHAR pwszModelNameBuffer[NAME_BUFFER_SIZE]; LPCWSTR pcwszModelName; WCHAR pwszINFNameBuffer[MAX_PATH]; LPCWSTR pcwszINFName; PFNINSTALLGRAPHICSDRIVER pfnInstallGraphicsDriver; // REVIEW: Need NM-specific HRESULTS for all of these if (!IsWindowsNT()) { return E_FAIL; } if (!CanInstallNTDisplayDriver()) { return E_FAIL; } // The driver files are located in the NM directory. if (!GetInstallDirectory(szDir)) { ERROR_OUT(("GetInstallDirectory() fails")); return E_FAIL; } // Convert the install directory to Unicode, if necessary custrPath.AssignString(szDir); pwszSourcePath = custrPath; if (NULL == pwszSourcePath) { ERROR_OUT(("AnsiToUnicode() fails")); return E_FAIL; } // Strip the trailing backslash that GetInstallDirectory appends pwszSourcePathEnd = pwszSourcePath + lstrlenW(pwszSourcePath); // Handle X:\, just to be safe if (pwszSourcePathEnd - pwszSourcePath > 3) { ASSERT(L'\\' == *(pwszSourcePathEnd - 1)); *--pwszSourcePathEnd = L'\0'; } // Read the model name string from the resource file if (0 != ::LoadStringW(::GetInstanceHandle(), IDS_NMDD_DISPLAYNAME, pwszModelNameBuffer, CCHMAX(pwszModelNameBuffer))) { pcwszModelName = pwszModelNameBuffer; } else { ERROR_OUT(("LoadStringW() fails, err=%lu", GetLastError())); pcwszModelName = g_pcwszDefaultModelName; } // Read the INF name string from the resource file if (0 < ::LoadStringW(::GetInstanceHandle(), IDS_NMDD_INFNAME, pwszINFNameBuffer, CCHMAX(pwszINFNameBuffer))) { pcwszINFName = pwszINFNameBuffer; } else { ERROR_OUT(("LoadStringW() fails, err=%lu", GetLastError())); pcwszINFName = g_pcwszDefaultINFName; } // Get the entry point for display driver installation HMODULE hDll = NmLoadLibrary(g_pcszDisplayCPLName,TRUE); if (NULL == hDll) { ERROR_OUT(("NmLoadLibrary failed on %s", g_pcszDisplayCPLName)); return E_FAIL; } pfnInstallGraphicsDriver = (PFNINSTALLGRAPHICSDRIVER) GetProcAddress(hDll, g_pcszInstallDriverAPIName); if (NULL == pfnInstallGraphicsDriver) { ERROR_OUT(("GetInstallDisplayDriverEntryPoint() fails")); hr = E_FAIL; } else { // Now we're set to call the actual installation function DWORD dwErr = (*pfnInstallGraphicsDriver)(hwnd, pwszSourcePath, pcwszModelName, pcwszINFName); if (0 != dwErr) { ERROR_OUT(("InstallGraphicsDriver() fails, err=%lu", dwErr)); hr = E_FAIL; } else { WARNING_OUT(("InstallGraphicsDriver() succeeded")); hr = S_OK; } } // Cleanup ASSERT(NULL != hDll); FreeLibrary(hDll); return hr; }
0d79b88d3f363b0334f14504e0ad60dfda26635c
3b9513b1e62b7aa9c9527cc69e4dbbae44d23feb
/blimp/src/core/object/object.h
d4245fbe51450d4cc31844ce7d5fa05afb35467a
[ "MIT" ]
permissive
3dgo/blimp
cf2500402f96c6602f36b6823c090b20b6c6e9c2
70ab20f235add5a10c6288c72498456b1b9214ce
refs/heads/master
2020-08-05T22:38:40.595031
2020-02-18T06:03:36
2020-02-18T06:03:36
212,737,117
0
0
null
null
null
null
UTF-8
C++
false
false
1,480
h
object.h
#pragma once // Operator Overloads and uuid implemented by Matt Warner /// <summary> /// Object Class /// </summary> namespace blimp { class Object { DECLARE_ABSTRACT_BASE_CLASS(Object) private: std::string name = ""; UUID uuid = ""; // holds the uuid struct STRCODE uuid_strcode = 0; // holds the uuid hashCode used for comparisions public: Object(); virtual ~Object(); virtual void initialize(); virtual void destroy(); const std::string& get_name() const { return name; } STRCODE get_uuid_strcode() const { return uuid_strcode; } bool operator==(const Object& rhs) const { return uuid_strcode == rhs.get_uuid_strcode(); } bool operator!=(const Object& rhs) const { return uuid_strcode == rhs.get_uuid_strcode(); } bool operator<(const Object& rhs) const { return uuid_strcode < rhs.get_uuid_strcode(); } bool operator<=(const Object& rhs) const { return uuid_strcode <= rhs.get_uuid_strcode(); } bool operator>(const Object& rhs) const { return uuid_strcode > rhs.get_uuid_strcode(); } bool operator>=(const Object& rhs) const { return uuid_strcode >= rhs.get_uuid_strcode(); } }; }
23440f0a63b063a1006a25005a69986a706fbfa8
9a526e11888f2a65b3b26125c73f675ec4c695e5
/array/coding-interviews/PrintMinNumber.h
9ba4e9cc652f8e1e3e6cacfbe171f5c66ac0afea
[]
no_license
GeekSprite/iOS-Algorithm
04c3c4aef269cbcdebf5584699edf0fb85effe28
e821e39bb141639ae48f8e6041a517f8319646bf
refs/heads/master
2023-01-28T00:03:21.197888
2020-12-02T14:33:34
2020-12-02T14:33:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,171
h
PrintMinNumber.h
// // PrintMinNumber.h // array // // Created by junlongj on 2019/8/3. // Copyright © 2019 junl. All rights reserved. // #ifndef PrintMinNumber_hpp #define PrintMinNumber_hpp #include <stdio.h> #include <string> #include <vector> #include <math.h> /* 剑指Offer(三十二):把数组排成最小的数 输入一个正整数数组,把数组里所有数字拼接起来排成一个数,打印能拼接出的所有数字中最小的一个。例如输入数组{3,32,321},则打印出这三个数字能排成的最小数字为321323。 https://www.nowcoder.com/practice/8fecd3f8ba334add803bf2a06af1b993?tpId=13&tqId=11185&tPage=2&rp=1&ru=%2Fta%2Fcoding-interviews&qru=%2Fta%2Fcoding-interviews%2Fquestion-ranking */ namespace codinginterviews { /* 这个解题思路可以转换为,我们把整个数组看成是一个整数,现在的认为是把数组排好序,然后顺序组合起来的数字最小。 在这里我们自己定义一个规则,对拼接后的字符串进行比较。 排序规则如下: 若ab > ba 则 a 大于 b, 若ab < ba 则 a 小于 b, 若ab = ba 则 a 等于 b; 根据上述规则,我们需要先将数字转换成字符串再进行比较,因为需要串起来进行比较。比较完之后,按顺序输出即可。 */ #pragma mark - v1 #define NUMBER_SIZE 10 char p_strCombine1[NUMBER_SIZE * 2 + 1]; char p_strCombine2[NUMBER_SIZE * 2 + 1]; int compare(const void *num1, const void *num2){ strcpy(p_strCombine1, *(const char **)num1); strcat(p_strCombine1, *(const char **)num2); strcpy(p_strCombine2, *(const char **)num2); strcat(p_strCombine2, *(const char **)num1); return strcmp(p_strCombine1, p_strCombine2); } char* minNumber(int* nums, int numsSize){ if (nums == NULL || numsSize <= 0) return NULL; char **numstrs = (char **)malloc(sizeof(char *) * numsSize); int i, len = 0; for(i =0; i < numsSize; i++){ numstrs[i] = (char *)malloc(sizeof(char) * (NUMBER_SIZE * 2 + 1)); sprintf(numstrs[i], "%d", nums[i]); len += strlen(numstrs[i]); } //排序 qsort(numstrs, numsSize, sizeof(char *), compare); char *result = (char *)malloc(sizeof(char) * (len+1)); result[0] = '\0'; for(i=0; i < numsSize; i++){ strcat(result, numstrs[i]); free(numstrs[i]); numstrs[i] = NULL; } result[len] = '\0'; free(numstrs); return result; } #pragma mark - v2 by STL static bool Compare(int a, int b){ std::string A = std::to_string(a) + std::to_string(b); std::string B = std::to_string(b) + std::to_string(a); return A < B;//说明b比a大 } std::string PrintMinNumber(std::vector<int> numbers) { std::sort(numbers.begin(), numbers.end(), Compare); std::string s; for (auto it = numbers.begin(); it != numbers.end(); it++) { s+=std::to_string(*it); } return s; } #pragma mark - v3 全排列 using namespace std; vector<string> results; void permutation(vector<int> &numbers, string str, vector<bool> st, int level){ if (level == numbers.size()){ results.push_back(str); return; } for (int i=0;i<numbers.size();i++){ if (st[i]) continue; st[i] = true; permutation(numbers, str+to_string(numbers[i]), st, level + 1); st[i] = false; } } string PrintMinNumber2(vector<int> numbers) { if (numbers.empty()) return ""; vector<bool> st; st.resize(numbers.size()); fill(st.begin(), st.end(), false); string str; permutation(numbers, str, st, 0); sort(results.begin(), results.end()); return results[0]; } void test_PrintMinNumber(){ std::vector<int> a{3,32,321}; std::cout << "test_PrintMinNumber starting........" << std::endl; std::cout << PrintMinNumber2(a) << std::endl; int nums[] = {10,2}; char *result = minNumber(nums, 2); puts(result); } } #endif /* PrintMinNumber_hpp */
afb9802275782182ac20740fcc774e0c5e785f11
c3192020e560076ef8af3dce5355f7ab0ff685be
/pinocchio/include/pinocchio/spatial/motion-ref.hpp
eba6a23c72ffa6500285352afd6deb040cf5c85c
[ "BSD-2-Clause", "BSD-3-Clause" ]
permissive
CiaranZ/CIaran
604c93b1126643fcf6fd6f34e5b420b7a4c41ab4
185624ce371482820eba3d59fd0122e9d332bfde
refs/heads/master
2023-06-11T11:21:30.667753
2023-05-30T10:27:39
2023-05-30T10:27:39
123,782,966
0
0
null
null
null
null
UTF-8
C++
false
false
64
hpp
motion-ref.hpp
/mnt/nvme1n1p7/HKUST_ws/src/pinocchio/src/spatial/motion-ref.hpp
a42211f9f48e7be7f2cc409a8bc0521dd914a558
c0cae871847dd7f3e247cadfab6af72782f01072
/mainwindow.h
3a34d9320b7e205a4a37949f18f0ea436ad4dd56
[]
no_license
wangxg2github/TestMangemment
a30c93d982f38696ce9740c672c08e7dfdfb5f83
795fb7b0d7115ff8273bfc7acf45b06885d3d6e5
refs/heads/master
2021-05-14T01:51:03.008798
2018-01-07T15:44:06
2018-01-07T15:44:06
116,576,486
0
0
null
null
null
null
UTF-8
C++
false
false
444
h
mainwindow.h
#ifndef MAINWINDOW_H #define MAINWINDOW_H #include <QMainWindow> #include <QHBoxLayout> #include <QLabel> #include "qnavigationwidget.h" #include "modelview/qshowwidget.h" class MainWindow : public QMainWindow { Q_OBJECT public: MainWindow(QMainWindow *parent=0); ~MainWindow(); private: QWidget *mainWidget; QHBoxLayout *mainLayout; QNavigationWidget *navigationWidget; QShowWidget* showWidget; }; #endif
1b311b94db10a0f1d215d93013c97013bb0e9e7f
141cd086b082772f39cd6ea937f9d54cf7d1c4be
/tf/model/ner/NER_LSTM.hpp
f8ee315aaf28a2f2071039cc677b8f10f36604d8
[]
no_license
phylieac/TF-NER
45e9d46e213d0aa1a545977f984bf1401fc55c54
a5024a00ca32389bea93535b01ca63bf68ac8397
refs/heads/master
2022-10-06T21:27:09.048553
2020-06-10T06:36:40
2020-06-10T06:36:40
270,534,630
2
0
null
null
null
null
UTF-8
C++
false
false
2,078
hpp
NER_LSTM.hpp
// // NER_LSTM.hpp // NER // // Created by 潘洪岩 on 2020/1/5. // Copyright © 2020 潘洪岩. All rights reserved. // #ifndef NER_LSTM_hpp #define NER_LSTM_hpp #include <stdio.h> #include <iostream> #include <tensorflow/core/public/session.h> #include <tensorflow/core/platform/env.h> #include <tensorflow/cc/saved_model/loader.h> #include <tensorflow/cc/saved_model/signature_constants.h> #include <tensorflow/core/kernels/lookup_table_init_op.h> #include <tensorflow/core/kernels/lookup_table_op.h> #include "encoder/Encoder.h" #include "decoder/Decoder.h" using namespace tensorflow; using namespace encoder; class NER_LSTM { private: std::string model; Tensor dropout; float dropout_value=1.0; string kSavedModelTagServe = "serve"; encoder::SequenceEncoder encoder; decoder::Decoder decoder; std::unique_ptr<tensorflow::Session> sess; tensorflow::SessionOptions sess_options; tensorflow::RunOptions run_options; tensorflow::SavedModelBundle bundle; tensorflow::Status status; public: NER_LSTM(std::string &model_path,SequenceEncoder &encoder):model(model_path),encoder(encoder){ Tensor dropout(DT_FLOAT,TensorShape({1})); auto data=dropout.flat<float>().data(); std::vector<float> d({dropout_value}); copy_n(d.begin(),1,data); bool s = NER_LSTM::dropout.CopyFrom(dropout, TensorShape({1})); if(s) LOG(INFO) << "Dropout set:" <<dropout_value; } bool LoadModel() { status=tensorflow::LoadSavedModel(sess_options, run_options, model, { NER_LSTM::kSavedModelTagServe }, &bundle); LOG(INFO) << "Model: "<<model<<" Load Status "<<status.ToString(); sess=std::move(bundle.session); return status.ok(); } Tensor ConvOneTensor(std::vector<int> &s_codes); std::map<std::string,std::string> Predict(std::string &sentence); ~NER_LSTM() { status = sess->Close(); LOG(INFO)<< "Close TFSession:"<<status.ToString(); } }; #endif /* NER_LSTM_hpp */
20ff564a200f0ef6d1c7132203e0bdffccc7f102
37f41843d2751015e6b6938eb96e8e28a25ccd8c
/trajectory_tracker/include/trajectory_tracker/eigen_line.h
eca6446bddd03ac661fca7e4d977e9187cc37ff6
[ "BSD-3-Clause" ]
permissive
at-wat/neonavigation
16b499b1361c67929ff3ec3685b6aed504122a7e
a9d14309198b5893b981c5976ce0467588f1f05c
refs/heads/master
2023-08-31T21:08:41.495171
2023-08-30T04:09:51
2023-08-30T04:09:51
67,018,317
257
91
NOASSERTION
2023-09-14T10:13:52
2016-08-31T08:23:10
C++
UTF-8
C++
false
false
3,455
h
eigen_line.h
/* * Copyright (c) 2014, ATR, Atsushi Watanabe * Copyright (c) 2014-2018, the neonavigation authors * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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. */ #ifndef TRAJECTORY_TRACKER_EIGEN_LINE_H #define TRAJECTORY_TRACKER_EIGEN_LINE_H #include <cmath> #include <Eigen/Core> namespace trajectory_tracker { inline float curv3p( const Eigen::Vector2d& a, const Eigen::Vector2d& b, const Eigen::Vector2d& c) { float ret; ret = 2 * (a[0] * b[1] + b[0] * c[1] + c[0] * a[1] - a[0] * c[1] - b[0] * a[1] - c[0] * b[1]); ret /= std::sqrt((b - a).squaredNorm() * (b - c).squaredNorm() * (c - a).squaredNorm()); return ret; } inline float cross2(const Eigen::Vector2d& a, const Eigen::Vector2d& b) { return a[0] * b[1] - a[1] * b[0]; } inline float lineDistance( const Eigen::Vector2d& a, const Eigen::Vector2d& b, const Eigen::Vector2d& c) { return cross2((b - a), (c - a)) / (b - a).norm(); } // lineStripDistanceSigned returns signed distance from the line strip. // If c is behind a, negative value will be returned. [ (c) (a)---(b) ] // Otherwise, positive value will be returned. [ (a)---(b) (c) ] [ (a)--(c)--(b) ] inline float lineStripDistanceSigned( const Eigen::Vector2d& a, const Eigen::Vector2d& b, const Eigen::Vector2d& c) { if ((b - a).dot(c - a) <= 0) return -(c - a).norm(); if ((a - b).dot(c - b) <= 0) return (c - b).norm(); return std::abs(lineDistance(a, b, c)); } inline float lineStripDistance( const Eigen::Vector2d& a, const Eigen::Vector2d& b, const Eigen::Vector2d& c) { return std::abs(lineStripDistanceSigned(a, b, c)); } inline Eigen::Vector2d projection2d( const Eigen::Vector2d& a, const Eigen::Vector2d& b, const Eigen::Vector2d& c) { const float r = (b - a).dot(c - a) / (b - a).squaredNorm(); return b * r + a * (1.0 - r); } } // namespace trajectory_tracker #endif // TRAJECTORY_TRACKER_EIGEN_LINE_H
06608bfc2bb0c54e40de76b9e60adea591162d69
fd82c48fcf02ee09f0753f7d7571d93530953d2f
/Languages/cpp/1_cin_cout/code/cout_quiz.cpp
5a751b59e68d0aa14f72ca47cc26f4dc7b28da08
[]
no_license
Hahnnz/Computer_Science_Summary
ac8bce5be226dd8bf52221b8974557d7d6bba5ff
1458766969704ebfc1fe68f1ef80f8b4deb3be35
refs/heads/master
2020-03-18T16:15:11.787218
2018-06-23T05:38:32
2018-06-23T05:38:32
134,955,675
1
0
null
null
null
null
UTF-8
C++
false
false
321
cpp
cout_quiz.cpp
#include <iostream> using namespace std; int main(){ cout<<"[안내]"<<endl; cout<<"인터넷 변경하세요"<<endl; cout<<"통신사 관계없이"<<endl; cout<<"현금 등 40만원 +"<<endl; cout<<"할인 37%"<<endl; cout<<"<최대> \"2천 ~ 9천\" 가능"<<endl; cout<<"통화버튼 눌러주세요"<<endl; }
9700d16ab0d83fccbfa6b8e68e560f3595649955
48ca31dbd1ec7b9399b0ce81d26aaa6242b13ac3
/AGVControlSystem/CAGVConfigPane.cpp
b9ff3bd25ebc3dbc778303b6b1c5aa1c14b352d9
[]
no_license
qqsskk/AGVMapCreate
ccc7c93be6d9bccb540f1444b784d14db0862da5
5257f49a24a065644104c6192bbbc7085d4d3a8b
refs/heads/master
2020-12-12T23:47:01.657410
2019-12-02T10:44:53
2019-12-02T10:44:53
234,260,501
2
0
null
2020-01-16T07:26:39
2020-01-16T07:26:39
null
UTF-8
C++
false
false
1,219
cpp
CAGVConfigPane.cpp
// CAGVConfigPane.cpp: 实现文件 // #include "stdafx.h" #include "AGVControlSystem.h" #include "CAGVConfigPane.h" // CAGVConfigPane IMPLEMENT_DYNAMIC(CAGVConfigPane, CDockablePane) CAGVConfigPane::CAGVConfigPane() { } CAGVConfigPane::~CAGVConfigPane() { } BEGIN_MESSAGE_MAP(CAGVConfigPane, CDockablePane) ON_WM_CREATE() ON_WM_SIZE() ON_WM_DESTROY() END_MESSAGE_MAP() // CAGVConfigPane 消息处理程序 int CAGVConfigPane::OnCreate(LPCREATESTRUCT lpCreateStruct) { if (CDockablePane::OnCreate(lpCreateStruct) == -1) return -1; // TODO: 在此添加您专用的创建代码 if (!m_dlgAGVConfig.Create(IDD_AGVCONFIG_DIALOG, this)) { TRACE0("未能创建输出选项卡窗口/n"); return -1; // 未能创建 } m_dlgAGVConfig.ShowWindow(SW_SHOW); return 0; } void CAGVConfigPane::OnSize(UINT nType, int cx, int cy) { CDockablePane::OnSize(nType, cx, cy); // TODO: 在此处添加消息处理程序代码 if (m_dlgAGVConfig.GetSafeHwnd()) { CRect rect; GetClientRect(rect); m_dlgAGVConfig.MoveWindow(rect); } } void CAGVConfigPane::OnDestroy() { CDockablePane::OnDestroy(); // TODO: 在此处添加消息处理程序代码 m_dlgAGVConfig.DestroyWindow(); }
a33a58b40df25bd13f1497e5951c654a35669535
333b58a211c39f7142959040c2d60b69e6b20b47
/Include/CTTables/EVCPolicyRecord.h
0cd7df3bf7e62867b6343cc04007eb3e126a04a8
[]
no_license
JoeAltmaier/Odyssey
d6ef505ade8be3adafa3740f81ed8d03fba3dc1a
121ea748881526b7787f9106133589c7bd4a9b6d
refs/heads/master
2020-04-11T08:05:34.474250
2015-09-09T20:03:29
2015-09-09T20:03:29
42,187,845
0
0
null
null
null
null
UTF-8
C++
false
false
6,063
h
EVCPolicyRecord.h
/*************************************************************************/ // This material is a confidential trade secret and proprietary // information of ConvergeNet Technologies, Inc. which may not be // reproduced, used, sold or transferred to any third party without the // prior written consent of ConvergeNet Technologies, Inc. This material // is also copyrighted as an unpublished work under sections 104 and 408 // of Title 17 of the United States Code. Law prohibits unauthorized // use, copying or reproduction. // // Description: // This file keeps the default low/hi ranges for Environmental Values // // Update Log: // // $Log: /Gemini/Include/CTTables/EVCPolicyRecord.h $ // // 1 12/13/99 1:30p Vnguyen // Initial check-in for Environment Ddm. // /*************************************************************************/ #ifndef __EVCPolicyRecord_h #define __EVCPolicyRecord_h #pragma pack(4) #include "PtsCommon.h" #include "PtsRecordBase.h" // NTW means change state from NORMAL to WARNING // WTN WARNING to NORMAL // WTA WARNING to ALARM // ATW ALARM to WARNING // IMPORTANT: For IOP Temperature (EVC, IOP, DDH, etc) to change state between // NORMAL, WARNING, and ALARM, we use the threshold values returned from the // CMB Master: TemperatureHiThreshold and TemperatureNormThreshold. However, // the Temperature is subject to the following system wide limits. // SLOT (degree C) starts at normal state #define SLOT_TEMPERATURE_NTW 70 // > #define SLOT_TEMPERATURE_WTN 63 // < #define SLOT_TEMPERATURE_WTA 80 // > #define SLOT_TEMPERATURE_ATW 72 // < // Here is the state transition rule for Temperature: // NTW: Temperature >= TemperatureHiThreshold or > SLOT_TEMPERATURE_NTW // WTN: Temperature <= TemperatureNormThreshold and < SLOT_TEMPERATURE_WTN // WTA: Temperature > SLOT_TEMPERATURE_WTA // ATW: Temperature < SLOT_TEMPERATURE_ATW // The Exception Master is expected to figure out the fan speed for the entire // system given that each IOP may be in different temperature state. // EM should wire-or the higher fan speed. // FANSPEED (RPM) starts at normal #define FANSPEED_NTA 10 // < #define FANSPEED_ATN 100 // > // fInputOK // fOutputOK // fFanFailOrOverTemp // fPrimaryEnable // fDCtoDCEnable // KeyPosition // (degree C) starts at normal #define DC_DC_TEMPERATURE_NTW 70 // > #define DC_DC_TEMPERATURE_WTN 63 // < #define DC_DC_TEMPERATURE_WTA 100 // > #define DC_DC_TEMPERATURE_ATW 90 // < // (0.1 Volt) starts at normal state // This range is wide enough to cover float and charge // 13.5 * 4 = 54, 13.8 * 4 = 55.2 (float) // 14.4 * 4 = 57.6, 15 * 4 = 60 (cycle) #define SMP48V_NORM_NTA1 530 // < || #define SMP48V_NORM_NTA2 630 // > #define SMP48V_NORM_ATN1 540 // > && #define SMP48V_NORM_ATN2 600 // < // (0.1 Volt) starts at normal state // 1.75 * 6 * 4 = 42 (10% left) #define SMP48V_DISCHARGE_NTA1 420 // < || #define SMP48V_DISCHARGE_NTA2 630 // > #define SMP48V_DISCHARGE_ATN1 540 // > && #define SMP48V_DISCHARGE_ATN2 600 // < // (0.001 Volt) starts at normal #define DC3_NTA1 3000 // < || #define DC3_NTA2 3600 // > #define DC3_ATN1 3100 // > && #define DC3_ATN2 3500 // < // (0.01 Volt) starts at normal #define DC5_NTA1 475 // < || #define DC5_NTA2 540 // > #define DC5_ATN1 485 // > && #define DC5_ATN2 530 // < // (0.01 Volt) starts at normal #define DC12_NTA1 1140 // < || #define DC12_NTA2 1280 // > #define DC12_ATN1 1160 // > && #define DC12_ATN2 1260 // < // (0.001 A) starts at normal #define BATT_CURRENT_CHARGE_NTA 5000 // > #define BATT_CURRENT_CHARGE_ATN 4500 // < #define BATT_CURRENT_DISCHARGE_NTW -100 // < #define BATT_CURRENT_DISCHARGE_WTN 0 // >= // (degree C) starts at normal #define BATT_TEMPERATURE_NORM_NTW 45 // > #define BATT_TEMPERATURE_NORM_WTN 42 // < #define BATT_TEMPERATURE_NORM_WTA 50 // > #define BATT_TEMPERATURE_NORM_ATW 47 // < // (degree C) starts at normal #define BATT_TEMPERATURE_DISCHARGE_NTW 55 // > #define BATT_TEMPERATURE_DISCHARGE_WTN 51 // < #define BATT_TEMPERATURE_DISCHARGE_WTA 60 // > #define BATT_TEMPERATURE_DISCHARGE_ATW 56 // < // #define BATT_PRESENT_TEMPERATURE 0 // battery presents if temperature is hotter than this #define EVC_POLICY_TABLE (EVCpolicyRecord::TableName()) #define EVC_POLICY_TABLE_VER (1) /* current struct version */ // // EVC Policy Table - Data detailing valid range of temperature, power supplies, fans. etc. // // There are exactly 13 records: // SlotTemperature // FanSpeed // DC_To_DC_Temperature // SMP48V_Norm // SMP48V_Discharge // DC3[2] // DC5[2] // Battery_Current // Battery_Temp_Norm // Battery_Temp_Discharge // Battery_Present_Temp class EVCPolicyRecord : public CPtsRecordBase { public: String32 SensorName; S32 NormalToWarning; S32 WarningToNormal; S32 WarningToAlarm; S32 AlarmToWarning; S32 NormalToAlarm; S32 AlarmToNormal; // constructor for basic initialization EVCPolicyRecord(); // members used to access our record field definition // here is the standard table which defines EVC Status table PTS fields static const fieldDef *FieldDefs(); // and here is the size, in bytes, of the EVC Status table field defs static const U32 FieldDefsSize(); // here is the name of the PTS table whose rows we define static const char *TableName(); }; /* end of class EVCPolicyRecord */ #define CT_EVCST_SENSORNAME "SensorName" #define CT_EVCST_NTW "NormalToWarning" #define CT_EVCST_WTN "WarningToNormal" #define CT_EVCST_WTA "WarningToAlarm" #define CT_EVCST_ATW "AlarmToWarning" #define CT_EVCST_NTA "NormalToAlarm" #define CT_EVCST_ATN "AlarmToNormal" #endif // __EVCPolicyRecord_h
0c073e0f9f4b34d916b3480e9fbee6837f07516c
9042399d3d135b9cf80904e0f180dd0a974041de
/refs/async/epoll_io_op.h
24b5d79b12e25357212880bdb647658f4dcd7f92
[]
no_license
thibetabc/xxsocket
9a5a29f683fcbdc66b06bafc9c1c68390b610668
be754ed415804ff33a6bcf99dd250c03ac3e8288
refs/heads/master
2021-01-18T07:17:40.213843
2016-06-04T09:37:06
2016-06-04T09:37:06
60,538,625
0
1
null
2016-06-06T15:22:53
2016-06-06T15:22:53
null
UTF-8
C++
false
false
504
h
epoll_io_op.h
#ifndef _EPOLL_IO_OP_H_ #define _EPOLL_IO_OP_H_ #include "epoll_fwd.h" class epoll_io_op { typedef void (*func_type)(epoll_io_service*, epoll_io_op*, u_long ec, size_t bytes_transferred); public: epoll_io_op(func_type func) : func_(func) { } void complete(epoll_io_service& owner, u_long ec, size_t bytes_transferred) { this->func_(&owner, this, ec, bytes_transferred); } private: func_type func_; }; #endif
f18561f070c94df2bf7b1a47c6c95335eec1fc24
37e2a3e18dc74e26a46e6f62f65d9aa3cbf6a2bf
/include/caffe/layers/scatter_nd_layer.hpp
7bb915fc9af2a7d0cdf366ee67c3ffdae164783a
[ "LicenseRef-scancode-generic-cla", "BSD-2-Clause" ]
permissive
foss-for-synopsys-dwc-arc-processors/synopsys-caffe
bc5d91e81575460137fa22623ba01816413d3bf0
63123ca6c80b72365c87332bbb3de2995e063065
refs/heads/main
2023-09-02T10:25:17.991467
2023-08-02T11:01:05
2023-08-02T11:01:05
103,567,504
27
20
NOASSERTION
2023-08-02T10:44:05
2017-09-14T18:28:41
C++
UTF-8
C++
false
false
1,343
hpp
scatter_nd_layer.hpp
#ifndef CAFFE_SCATTER_ND_LAYER_HPP_ #define CAFFE_SCATTER_ND_LAYER_HPP_ #include <vector> #include "caffe/blob.hpp" #include "caffe/layer.hpp" #include "caffe/proto/caffe.pb.h" namespace caffe { template <typename Dtype> class ScatterNDLayer : public Layer<Dtype> { public: explicit ScatterNDLayer(const LayerParameter& param) : Layer<Dtype>(param) {} virtual void LayerSetUp(const vector<Blob<Dtype> *> &bottom, const vector<Blob<Dtype> *> &top); virtual void Reshape(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top); virtual inline const char* type() const { return "ScatterND"; } virtual inline int MinBottomBlobs() const { return 0; } virtual inline int MaxBottomBlobs() const { return 3; } virtual inline int ExactNumTopBlobs() const { return 1; } protected: virtual void Forward_cpu(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top); virtual void Backward_cpu(const vector<Blob<Dtype>*>& top, const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom) { NOT_IMPLEMENTED; } bool is_data_param_; bool is_indices_param_; bool is_updates_param_; int Q_; // rank of indices int K_; // each entry of indices tensor is a K-tuple = partial-index of data tensor }; } // namespace caffe #endif // CAFFE_SCATTER_ND_LAYER_HPP_
5546ca4b74d0c643dd7ced8225b2c8a3a2ff57a7
0687f997984b71293ba896862758f46103901b36
/data_generation/compute_prediction/c_packetprocessing/apps/env/test7.cc
c708d36b5104108159a2cc6f63acfd62188551b3
[ "Apache-2.0" ]
permissive
XinYao1994/Clara
28b6ad41428301a49401d60d36d15741857dbbdc
eea38c52beb17600dd325f465a3740f267bab2e5
refs/heads/master
2023-08-29T22:01:17.451714
2021-11-01T04:08:25
2021-11-01T04:08:25
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,321
cc
test7.cc
/* yarpgen version 2.0 (build 7edd86d on 2021:04:18) Seed: 4145813097 Invocation: ./build/yarpgen -n test7 */ #include <click/config.h> #include <click/args.hh> #include <click/glue.hh> #include <clicknet/ip.h> #include <clicknet/tcp.h> #include <clicknet/udp.h> #include <clicknet/icmp.h> #include <algorithm> #include "test7.hh" CLICK_DECLS test7::test7(): _active(true) { } test7::~test7() { } int test7::configure(Vector<String> &conf, ErrorHandler *errh) { return Args(conf, this, errh) .read("ACTIVE", _active).complete(); } #pragma clang diagnostic ignored "-Wparentheses-equality" #pragma clang diagnostic ignored "-Wtautological-constant-out-of-range-compare" #pragma clang diagnostic ignored "-Wconstant-conversion" Packet * test7::simple_action(Packet *p) { assert(p->has_network_header()); if (!_active) { return p; } WritablePacket *q = p->uniqueify(); if (!q) { return 0; } volatile uint32_t l_var_17 = 2504330348U; volatile uint32_t l_var_18 = 1299611281U; volatile uint32_t l_var_19 = 1713139719U; volatile uint32_t l_var_20 = 80688835U; volatile uint32_t l_var_21 = 3043270119U; volatile uint32_t l_var_22 = 2270839550U; volatile uint32_t l_var_23 = 423064615U; click_ip *ip = q->ip_header(); click_tcp *tcp; click_udp *udp; if (ip->ip_p==6) { tcp = q->tcp_header(); } else { udp = q->udp_header(); } //packet header manipulations if ((159 >= g_var_0)) { if ((115 == l_var_23)) { g_var_2 += 1447453409U; } l_var_23 = 1379087563U; } if ((ip->ip_p < 11)) { l_var_22 = ++(l_var_18); } else { if (!(g_var_15)) { l_var_17 = 2098815445U; } } if ((ip->ip_tos <= 156)) { g_var_2 = 938181375U; g_var_0 = l_var_19; g_var_5 = (ip->ip_p + 94); } // to keep all local variables alive ip->ip_src.s_addr = 8888 |l_var_17 | l_var_18 | l_var_19 | l_var_20 | l_var_21 | l_var_22 | l_var_23 | 6666; } void test7::add_handlers() { add_data_handlers("active", Handler::OP_READ | Handler::OP_WRITE | Handler::CHECKBOX, &_active); } CLICK_ENDDECLS EXPORT_ELEMENT(test7) ELEMENT_MT_SAFE(test7)
50463ef9d7c1ca29677af4980089790407f90dbd
05f024a2efdc5f77dabb31e94259bbf557c67c67
/week12/src/ofApp.cpp
b167bb554121d6c17964342b626d0e9b2d78a715
[]
no_license
cocosy/sheny082_dtOF_2018
3894440398b3ff863b7d8d60242a1fbfe5435bd2
2928c5a6ff6e7ab24d16790fee71d4ca7eb9d59e
refs/heads/master
2021-08-19T00:43:53.423089
2018-12-12T01:40:49
2018-12-12T01:40:49
146,523,280
0
0
null
null
null
null
UTF-8
C++
false
false
5,500
cpp
ofApp.cpp
#include "ofApp.h" //-------------------------------------------------------------- void ofApp::setup(){ ofBackground(0); body.loadModel("woman.obj",true); body.setPosition(ofGetWidth()/20, (float)ofGetHeight() * -0.3 , 0); //position // body.setRotation(0, 180, 1, 0, 0); //rotate to face the front // body.setRotation(0, 180, 0, 1, 0); body.setRotation(0, 180, 0, 0, 1); meshBody = body.getMesh(0); //create meshBody //change position of meshBody int numVerts = meshBody.getNumVertices(); for (int i=0; i<numVerts; ++i) { glm::vec3 vert = meshBody.getVertex(i); vert.y -= 30; vert.z += 480; meshBody.setVertex(i, vert); } //load image img.load("fish.png"); img.resize(200, 133); float intensityThreshold = 150.0; int w = img.getWidth(); int h = img.getHeight(); for (int x=0; x<w; ++x) { for (int y=0; y<h; ++y) { ofColor c = img.getColor(x, y); float intensity = c.getLightness(); if (intensity >= intensityThreshold) { //glm::vec3 pos(x*5, y*5, 0.0); //meshBody.addVertex(pos); // When addColor(...), the mesh will automatically convert // the ofColor to an ofFloatColor meshBody.addColor(c); offsets.push_back(glm::vec3(ofRandom(0,100000), ofRandom(0,100000), ofRandom(0,100000))); } } } gui.setup(); //set up three drawing methods gui.add( drawFaces.set("draw faces", true) ); gui.add( drawWireframes.set("draw wires", false) ); gui.add( drawVertices.set("draw vertices", false) ); // gui.add(scale.set("scale",1.0, 0.0, 3.0)); } //-------------------------------------------------------------- void ofApp::update(){ // body.setScale(scale,scale, scale); //ofMesh mesh = body.getMesh(0); int numVerts = meshBody.getNumVertices(); for (int i=0; i<numVerts; ++i) { glm::vec3 vert = meshBody.getVertex(i); float time = ofGetElapsedTimef(); float timeScale = 3.0; float displacementScale = 0.25; glm::vec3 timeOffsets = offsets[i]; // A typical design pattern for using Perlin noise uses a couple parameters: // ofSignedNoise(time*timeScale+timeOffset)*displacementScale // ofSignedNoise(time) gives us noise values that change smoothly over // time // ofSignedNoise(time*timeScale) allows us to control the smoothness of // our noise (smaller timeScale, smoother values) // ofSignedNoise(time+timeOffset) allows us to use the same Perlin noise // function to control multiple things and have them look as if they // are moving independently // ofSignedNoise(time)*displacementScale allows us to change the bounds // of the noise from [-1, 1] to whatever we want // Combine all of those parameters together, and you've got some nice // control over your noise vert.x += (ofSignedNoise(time*timeScale+timeOffsets.x)) * displacementScale; vert.y += (ofSignedNoise(time*timeScale+timeOffsets.y)) * displacementScale; vert.z += (ofSignedNoise(time*timeScale+timeOffsets.z)) * displacementScale; meshBody.setVertex(i, vert); } } void ofApp::draw(){ mesh.draw(); //cout << mesh.getNumVertices() << endl; cam.begin(); ofEnableDepthTest(); if (drawFaces){ // body.drawFaces(); meshBody.drawFaces(); } if (drawWireframes){ // body.drawWireframe(); meshBody.drawWireframe(); } if (drawVertices){ //body.enableColors(); // body.drawVertices(); meshBody.drawVertices(); //meshBody.disableColors(); } ofDisableDepthTest(); cam.end(); gui.draw(); } //-------------------------------------------------------------- void ofApp::keyPressed(int key){ if(key == ' '){ cout << "t:" << body.getPosition()<< endl; } } //-------------------------------------------------------------- void ofApp::keyReleased(int key){ } //-------------------------------------------------------------- void ofApp::mouseMoved(int x, int y ){ } //-------------------------------------------------------------- void ofApp::mouseDragged(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::mousePressed(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::mouseReleased(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::mouseEntered(int x, int y){ } //-------------------------------------------------------------- void ofApp::mouseExited(int x, int y){ } //-------------------------------------------------------------- void ofApp::windowResized(int w, int h){ } //-------------------------------------------------------------- void ofApp::gotMessage(ofMessage msg){ } //-------------------------------------------------------------- void ofApp::dragEvent(ofDragInfo dragInfo){ }
f78c81ec6ce7c31f596c49b211f917262cc04ef1
76bc8a0073fcbf97c53f48984e6ae037a934da90
/Parcial 2/Proyecto 2 Parcial/Funcion.h
85dc767792794a36aaec5f717cb05bb20c96f501
[ "MIT" ]
permissive
Adrian-Garcia/ObjectOrientedProgramming
1555800490db4e8a581deaed2ecfe9ee11bc2548
a37f8cfb68a9d2a4067b148ab34232c6d1012438
refs/heads/master
2020-04-05T18:52:15.010299
2018-11-11T20:25:25
2018-11-11T20:25:25
157,115,483
0
0
null
null
null
null
UTF-8
C++
false
false
2,096
h
Funcion.h
#include <string> #include "Hora.h" using namespace std; //Clase Funcion de la pelicula class Funcion { //Atributos private: string sCveFuncion; int iNumPeli; Hora hora; int iSala; //Metodos public: //Constructor default y con parametros Funcion(); Funcion(string sCveFuncion, int iNumPeli, Hora hora, int iSala); //Metodos de obtencion string getCveFuncion(); int getNumPeli(); Hora getHora(); int getSala(); //Metodos de modificacion void setCveFuncion(string sKey); void setNumPeli(int iNumMov); void setHora(Hora hour); void setSala(int iSalon); //Metodo muestra void Muestra(); }; //Contructor Default con valores = 0 Funcion::Funcion() { sCveFuncion = "0"; iNumPeli = 0; hora; iSala = 0; } //Contructor con parametros Funcion::Funcion(string sCveFuncion, int iNumPeli, Hora hora, int iSala){ this->sCveFuncion = sCveFuncion; this->iNumPeli = iNumPeli; this->hora = hora; this->iSala = iSala; } //Metodo que obtiene la clave de funcion string Funcion::getCveFuncion() { return sCveFuncion; } //Metodo que obtiene el numero de funcion int Funcion::getNumPeli() { return iNumPeli; } //Metodo que obtiene la hora de la funcion Hora Funcion::getHora() { return hora; } //Metodo que obtiene la sala de la funcion int Funcion::getSala() { return iSala; } //Metodo que modifica la sala de la funcion void Funcion::setCveFuncion(string sKey) { sCveFuncion = sKey; } //Metodo que modifica el numero de la funcion void Funcion::setNumPeli(int iNumMov) { iNumPeli = iNumMov; } //Metodo que modifica la hora de la funcion void Funcion::setHora(Hora hour) { hora = hour; } //Metodo que modifica la sala de la funcion void Funcion::setSala(int iSalon) { iSala = iSalon; } //Metodo que muestra los resultados void Funcion::Muestra() { //Desplegamos datos cout << "Clave: " << sCveFuncion << endl; cout << "Numero: " << iNumPeli << endl; cout << "Hora: "; hora.Muestra(); cout << endl; cout << "Sala: " << iSala << endl; }
ed006bfaf50badf42add67a76e1784389b0b6daf
e01f56ce91eb3a20707344bb4cb5535848058df8
/src/validators/claims/listclaimvalidator.cpp
222cf1afafd62bbf27928d3090a48b9ec46397ce
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
martindederer/jwt-cpp
e613523f1f98de75b0dc41db3821101a9050a779
eb9f3b5afc43f679c6bdc44196e6d3fc59ac6396
refs/heads/master
2021-01-01T18:24:11.740704
2017-07-19T23:51:16
2017-07-19T23:51:16
98,326,940
1
0
null
2017-07-25T16:20:20
2017-07-25T16:20:20
null
UTF-8
C++
false
false
3,040
cpp
listclaimvalidator.cpp
// Copyright (c) 2015 Erwin Jansen // // MIT 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 <string.h> #include <string> #include <sstream> #include <vector> #include "jwt/listclaimvalidator.h" #include "jwt/jwt_error.h" ListClaimValidator::ListClaimValidator(const char *property, std::vector<std::string> accepted) : ClaimValidator(property), accepted_(accepted) { } ListClaimValidator::ListClaimValidator(const char *property, const char *const *lst_accepted, const size_t num_accepted) : ClaimValidator(property) { for (int i = 0; i < num_accepted; i++) { accepted_.push_back(std::string(lst_accepted[i])); } } bool ListClaimValidator::IsValid(const json_t *claim) const { json_t *object = json_object_get(claim, property_); if (!json_is_string(object)) { throw InvalidClaimError(std::string("Missing: ") += property_); } const char *value = json_string_value(object); for (auto accept : accepted_) { if (accept == value) return true; } throw InvalidClaimError(std::string("Invalid: ") += property_); } std::string ListClaimValidator::toJson() const { std::ostringstream msg; msg << "{ \"" << property() << "\" : ["; int last = accepted_.size(); for (auto accept : accepted_) { msg << "\"" << accept << "\""; if (--last != 0) msg << ", "; } msg << "] }"; return msg.str(); } bool AudValidator::IsValid(const json_t *claim) const { json_t *object = json_object_get(claim, property_); if (json_is_string(object)) { return ListClaimValidator::IsValid(claim); } if (!json_is_array(object)) { throw InvalidClaimError(std::string("aud not a string/array: ")); } size_t idx; json_t *elem; json_array_foreach(object, idx, elem) { const char *value = json_string_value(elem); if (value) { for (auto accept : accepted_) { if (accept == value) return true; } } } throw InvalidClaimError(std::string("Invalid: ") += property_); }
057282565ec3a0b51f818df2bb0c55ad106eb661
50ffd9891ed0a2c99e216e0f1484815f0cbe9d3c
/src/Astronauta.cpp
041e2bf3d7bd4f2ff64c7efb9736db5c94e3661b
[]
no_license
KrustyN/Defender1980
847dd4ede5320418f88bf4823daf97f0944360f7
e058233b34b393df13b748f972d4723ac2cea341
refs/heads/master
2022-07-02T20:16:46.936722
2020-05-15T06:03:16
2020-05-15T06:03:16
259,112,524
0
0
null
null
null
null
UTF-8
C++
false
false
118
cpp
Astronauta.cpp
#include "Astronauta.h" Astronauta::Astronauta() { //ctor } Astronauta::~Astronauta() { //dtor }
ef8f3b9ece8e61ac6cd16605e6e43c32fdeaed71
74482f41ed55fcfd9b0dbde50b7dd245894dcc08
/SetPass.h
f0389c1aad66b7cc63a14e3d5c4ba37ca0e87290
[]
no_license
github188/digivideo
a9e487541e3f4ea2a994d0d4d11fdf1f70da8909
5de603d07ac4ba4794a724ecdcf699d074fd53ad
refs/heads/master
2021-01-21T19:20:53.655380
2015-01-22T03:24:01
2015-01-22T03:24:01
null
0
0
null
null
null
null
GB18030
C++
false
false
450
h
SetPass.h
#pragma once // CSetPass 对话框 class CSetPass : public CDialogEx { DECLARE_DYNAMIC(CSetPass) public: CSetPass(CWnd* pParent = NULL); // 标准构造函数 virtual ~CSetPass(); // 对话框数据 enum { IDD = IDD_A_SETPASS }; protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV 支持 DECLARE_MESSAGE_MAP() public: afx_msg void OnBnClickedOk(); CString m_oldpass; CString m_newpass; CString m_newpass1; };
5c844587ea1d498d44ecd405c4f5fee729c17590
a07fb51d7d4a9faf30ed7fb7ef811334befd67ba
/06.프로그래밍언어(C++)/7주차/3교시_구조체_공용체/arraystruct.cpp
d81ac7a499de79f97080a497b35cf92bcfe07801
[]
no_license
Jnkim/CPP
d90955aa0fa42146bc3ad97351e3cfcd5dac517a
af39850190d119cc5ff6eda1ab13aaab1129f7d5
refs/heads/master
2023-02-04T15:15:21.902451
2020-12-29T18:28:47
2020-12-29T18:28:47
325,350,916
0
0
null
null
null
null
UHC
C++
false
false
714
cpp
arraystruct.cpp
#include <iostream> #include <iomanip> using namespace std; struct Student{ char hakbun[11]; // 학번 char name[20]; // 이름 int c; // C교과 점수 int cpp; // C++교과점수 int web; // Web 교과점수 }; int main(){ struct Student student[] = { {"2020620038" , "김진남" , 88 , 99 , 95 } ,{"2020620039" , "박진남" , 89 , 98 , 96 } ,{"2020620040" , "최진남" , 90 , 97 , 97 } }; for( int i = 0 ; i < 3; i++ ){ cout << setw(11) << student[i].hakbun; cout << setw(8) << student[i].name; cout << setw(6) << student[i].c; cout << setw(6) << student[i].cpp; cout << setw(6) << student[i].web << endl; }; return 0; }
0ded2b682b84be98af6dd84b199cac408a3af396
c279a2fcb56de70f5cac2c8e890f155e177e676e
/Source/Plugins/SubsystemPlugins/BladeGraphics/source/interface_imp/RenderHelper/AABBRenderer.cc
24bc49cc91a5411865755fd2e76f0bf5b10db50c
[ "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,846
cc
AABBRenderer.cc
/******************************************************************** created: 2011/05/21 filename: AABBRenderer.cc author: Crazii purpose: *********************************************************************/ #include <BladePCH.h> #include "AABBRenderer.h" #include <interface/public/graphics/IGraphicsResourceManager.h> #include <interface/IGraphicsSystem.h> #include <interface/ISpaceCoordinator.h> #include <interface/public/graphics/IGraphicsScene.h> namespace Blade { ////////////////////////////////////////////////////////////////////////// AABBRenderer::AABBRenderer() { } ////////////////////////////////////////////////////////////////////////// AABBRenderer::~AABBRenderer() { } /************************************************************************/ /* IAABBRenderer interface */ /************************************************************************/ ////////////////////////////////////////////////////////////////////////// bool AABBRenderer::addAABB(ISpaceContent* content, const Color& color) { //only should be called in async run state from other sub systems //if within graphics system thread, any state is allowed BLADE_TS_VERITY_GRAPHICS_PUBLIC_ACCESS(); if(content == NULL ) return false; ScopedLock lock(mSyncLock); return mColoredInstances.addContent(content, color); } ////////////////////////////////////////////////////////////////////////// bool AABBRenderer::removeAABB(ISpaceContent* content) { //only should be called in async run state from other sub systems //if within graphics system thread, any state is allowed BLADE_TS_VERITY_GRAPHICS_PUBLIC_ACCESS(); if (content == NULL) return false; ScopedLock lock(mSyncLock); return mColoredInstances.removeContent(content); } ////////////////////////////////////////////////////////////////////////// bool AABBRenderer::changeAABBColor(ISpaceContent* content, const Color& color) { //only should be called in async run state from other sub systems //if within graphics system thread, any state is allowed BLADE_TS_VERITY_GRAPHICS_PUBLIC_ACCESS(); if (content == NULL) return false; ScopedLock lock(mSyncLock); return mColoredInstances.changeColor(content, color); } ////////////////////////////////////////////////////////////////////////// bool AABBRenderer::addAABB(IAABBTarget* target) { //only should be called in async run state from other sub systems //if within graphics system thread, any state is allowed BLADE_TS_VERITY_GRAPHICS_PUBLIC_ACCESS(); if (target != NULL) { ScopedLock lock(mSyncLock); return mColoredInstances.addTarget(target); } return false; } ////////////////////////////////////////////////////////////////////////// bool AABBRenderer::removeAABB(IAABBTarget* target) { //only should be called in async run state from other sub systems //if within graphics system thread, any state is allowed BLADE_TS_VERITY_GRAPHICS_PUBLIC_ACCESS(); if (target != NULL) { ScopedLock lock(mSyncLock); return mColoredInstances.removeTarget(target); } return false; } /************************************************************************/ /* custom methods */ /************************************************************************/ ////////////////////////////////////////////////////////////////////////// void AABBRenderer::initialize(IGraphicsScene* scene, IGraphicsUpdater* updater) { ISpaceCoordinator* coord = static_cast<ISpaceCoordinator*>(scene->getSpaceCoordinator()); assert( coord !=NULL ); mColoredInstances.setupRenderResource(); coord->addContent( &mColoredInstances ); mColoredInstances.initialize(updater); } }//namespace Blade
a89f231367c219e4f959bfb1a37f6ddecc515fc2
5380b60ffee90107f38e815d62263a920276f0d4
/mm.h
8f843b3c1045c6936b091a0e3070cd30a1da5d8a
[]
no_license
ennorehling/MemoryManager
8f3f8f7baa8c01fdec6cc31b8e310bdd344cdd44
76439bb87e134a6d058f2772dfe05777e1739aab
refs/heads/master
2020-05-20T23:11:24.521267
2015-06-18T23:08:25
2015-06-18T23:08:25
37,645,256
1
0
null
null
null
null
UTF-8
C++
false
false
6,871
h
mm.h
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <type_traits> #define INITIAL_SIZE 5 #ifndef _MSC_VER inline static void fopen_s(FILE **F, const char *filename, const char *options) { *F = fopen(filename, options); } #endif template< typename T> struct hasInit { template<typename U> static std::true_type Check(void (U::*)()) { return std::true_type(); } template <typename U> static decltype(Check(&U::Init)) Check(decltype(&U::Init), void *) { typedef decltype(Check(&U::Init)) return_type; return return_type(); } template<typename U> static std::false_type Check(...) { return std::false_type(); } typedef decltype(Check<T>(0, 0)) type; static const bool value = type::value; static void Call_Optional(T & t, std::true_type) { t.Init(); } static void Call_Optional(...){ } static void Call_Optional(T & t) { Call_Optional(t, type()); } }; template<class T> void mmInitialize(T & val) { hasInit<T>::Call_Optional(val); } template< typename T> struct hasDestroy { template<typename U> static std::true_type Check(void (U::*)()) { return std::true_type(); } template <typename U> static decltype(Check(&U::Destroy)) Check(decltype(&U::Destroy), void *) { typedef decltype(Check(&U::Destroy)) return_type; return return_type(); } template<typename U> static std::false_type Check(...) { return std::false_type(); } typedef decltype(Check<T>(0, 0)) type; static const bool value = type::value; static void Call_Optional(T & t, std::true_type) { t.Destroy(); } static void Call_Optional(...){ } static void Call_Optional(T & t) { Call_Optional(t, type()); } }; template<class T> void mmDestroy(T & val) { hasDestroy<T>::Call_Optional(val); } template <class T> class Pointer { friend class Pointer < T >; private: int index; int size; void Set(int i); int GetIndex() const{ return index; } int GetSize() const{ return size; } public: Pointer(){ Init(); } void Init(){ index = -1; size = sizeof(T); } ~Pointer(){ if (IsGood()) { mmDestroy(Get()); } Set(-1); } void Clear() { Set(-1); } bool IsGood(){ if (size > 0 && index >= 0) return true; return false; } Pointer& operator=(const Pointer& param) { if (this == &param) return *this; Set(param.GetIndex()); return *this; } operator bool(){ return (IsGood()); } void Allocate(); T& operator* (); T* operator& (); T& Get(); }; class mm { template <class T> friend class Pointer; private: char** tables; int* sizes; int* goodIndex; int NumTables; void GrowTable(int index){ int newsize = sizes[index] * 2; if (newsize == 0) { newsize = INITIAL_SIZE; } char* newtable = new(char[(index + sizeof(int))*newsize]); memset(newtable, 0, (index + sizeof(int))*newsize); if (sizes[index] > 0){ memcpy(newtable, tables[index], (index + sizeof(int))*sizes[index]); delete [] tables[index]; } tables[index] = newtable; int oldsize = sizes[index]; sizes[index] = newsize; for (int i = oldsize; i < newsize; ++i) { *((int*)(GetObject(i, index)) + (sizeof(void*) / sizeof(int))) = i + 1; } *((int*)(GetObject(newsize - 1, index)) + (sizeof(void*) / sizeof(int))) = -1; goodIndex[index] = oldsize; } void GrowTables(int NewTable){ if (NewTable < NumTables) { return; } char** temp = new(char*[NewTable + 1]); memset(temp, 0, (NewTable + 1) * sizeof(int)); if (NumTables > 0) memcpy(temp, tables, sizeof(int) * (NumTables)); delete tables; tables = temp; int* tempsizes = new(int[NewTable + 1]); memset(tempsizes, 0, (NewTable + 1) * sizeof(int)); if (NumTables > 0) memcpy(tempsizes, sizes, sizeof(int) * (NumTables)); delete sizes; sizes = tempsizes; int* tempGoodIndex = new(int[NewTable + 1]); memset(tempGoodIndex, 0, (NewTable + 1)*sizeof(int)); if (NumTables > 0) memcpy(tempGoodIndex, goodIndex, sizeof(int) * (NumTables)); delete goodIndex; goodIndex = tempGoodIndex; NumTables = NewTable + 1; } mm(){ tables = 0; sizes = 0; NumTables = 0; } int Allocate(int size){ if (NumTables == 0 || NumTables < size) { GrowTables(size); GrowTable(size); } if (sizes[size] == 0) { GrowTable(size); } //Find free memory if (size < 4) { //not bothering with optimization for objects of 1-3 bytes int i = 0; while (i < sizes[size]) { if (*((int*)&tables[size][i*(sizeof(int) + size)]) == 0) break; ++i; } if (i < sizes[size]) { memset(&tables[size][i*(sizeof(int) + size)], 0, sizeof(int) + size); return i; } else { GrowTable(size); return Allocate(size); } } else { if (goodIndex[size] == -1) { GrowTable(size); return Allocate(size); } else { int index = goodIndex[size]; goodIndex[size] = *(((int*)(GetObject(goodIndex[size], size))) + 1); memset(&tables[size][index*(sizeof(int) + size)], 0, sizeof(int) + size); return index; } } } void* GetObject(int index, int size) { if (index < 0) return 0; if (size < 1) return 0; if (tables == 0) return 0; if (sizes == 0) return 0; if (sizes[size] <= index) return 0; if (tables[size] == 0) return 0; return (void*)&tables[size][index*(size + sizeof(int))]; } void GC(int index, int size) { if (size >= 4) { int* obj = (int*)GetObject(index, size); if (obj && *obj == 0) { *(obj + (sizeof(void*) / sizeof(int))) = goodIndex[size]; goodIndex[size] = index; } } } ~mm() { FILE * out; fopen_s(&out, "Memory Stats.txt", "w"); fprintf(out, "Memory Use:\n"); for (int i = 1; i < NumTables; ++i) { if (sizes[i]) fprintf(out, "Objects of size %i bytes: %i\n", i, sizes[i]); } fprintf(out, "\nLost objects:\n"); for (int i = 1; i < NumTables; ++i) { int k; k = 0; for (int j = 0; j < sizes[i]; ++j) { if (*((int*)GetObject(j, i)) != 0) { k++; } } if (sizes[i]) fprintf(out, "Objects of size %i bytes: %i\n", i, k); } fclose(out); } public: static mm& get() { static mm instance; return instance; } }; template<class T> void Pointer<T>::Set(int i) { int* count = (int*)mm::get().GetObject(index, size); if (count != 0) { (*count)--; mm::get().GC(index, size); } index = i; count = (int*)mm::get().GetObject(index, size); if (count != 0) (*count)++; } template<class T> void Pointer<T>::Allocate() { Set(mm::get().Allocate(size)); if (IsGood()) { T* t = &Get(); mmInitialize<T>(*t); } } template<class T> T& Pointer<T>::operator* () { return *((T*)(((int*)(mm::get().GetObject(index, size))) + 1)); } template<class T> T* Pointer<T>::operator& () { return ((T*)(((int*)(mm::get().GetObject(index, size))) + 1)); } template<class T> T& Pointer<T>::Get() { return *((T*)(((int*)(mm::get().GetObject(index, size))) + 1)); }
a600a4d1eb68ffc30fcdd773735e3109452ffc4f
87942051269beacf8f2af60c091a384b4cfd23c5
/Rtp/RtpSend.h
80f1cdd7405f40aefb057420af9cadecf7cd0d42
[]
no_license
codeape123/IPTest
a261e655b0702d5388b523f9bc33e04616368ae4
93df0a1df6aec33972e0d24ce2c988a9c6a41181
refs/heads/master
2020-04-08T02:48:23.888008
2018-11-24T18:32:57
2018-11-24T18:32:57
158,949,670
0
0
null
null
null
null
UTF-8
C++
false
false
666
h
RtpSend.h
#pragma once #include "RtpBase.h" /// class RTP_EXP CRtpSend : public CRtpBase { public: CRtpSend(); ~CRtpSend(); public: void BeginSend(); void StopSend(); void PushData(); public: //lparam: 1: clip info BOOL OnTaskNotify(WPARAM wParam = NULL, LPARAM lParam = NULL); protected: HANDLE m_hSendThread; CIPEvent m_eventStop; CIPEvent m_eventSend; CIPEvent m_eventTimer; static unsigned int __stdcall ThreadSendFrameProc(void* in_pThreadParameter); static void CALLBACK TimerRoutine(PVOID lpParam, BOOLEAN TimerOrWaitFired); unsigned int SendFrameRoutine(); HANDLE m_hTimerQueue; HANDLE m_hTimerSend; };
9802a198353aa7cdefe9e5c8a30aa4d4f12a0d97
bf839d1e59fe714e589e3497c4f00104780e1b18
/debugblock/TopkListGenerator.cpp
1e2e95e24fb3b9716bb8c7507e7668587d580fb5
[]
no_license
hanli91/debug_blocking
9eefb00a53d26b3685948859b80937c644b00b6f
a58b447809d5b87a91a66cd2d9e568d1eedf164d
refs/heads/master
2021-07-05T13:03:49.473473
2017-09-29T21:24:27
2017-09-29T21:24:27
105,079,277
0
0
null
null
null
null
UTF-8
C++
false
false
15,345
cpp
TopkListGenerator.cpp
#include "TopkListGenerator.h" TopkListGenerator::TopkListGenerator() { } TopkListGenerator::~TopkListGenerator() { } double init_topk_list_calc_sim(const vector<int>& ltoken_list, const vector<int>& rtoken_list) { int overlap = 0; unordered_set<int> rset; unsigned long denom = 0; for (int i = 0; i < rtoken_list.size(); ++i) { rset.insert(rtoken_list[i]); } for (int i = 0; i < ltoken_list.size(); ++i) { if (rset.count(ltoken_list[i])) { ++overlap; } } denom = ltoken_list.size() + rtoken_list.size() - overlap; if (denom== 0) { return 0.0; } return overlap * 1.0 / denom; } void save_topk_list_to_file(const vector<int>& field_list, const string& output_path, Heap topk_heap) { string path = output_path + "topk_"; char buf[10]; for (int i = 0; i <field_list.size(); ++i) { sprintf(buf, "%d", field_list[i]); if (i != 0) { path.append(string("_")); } path.append(buf); } path += ".txt"; cout << "in save_topk_list_to_file: topk heap size " << topk_heap.size() << endl; FILE* fp = fopen(path.c_str(), "w+"); while (topk_heap.size() > 0) { TopPair pair = topk_heap.top(); topk_heap.pop(); fprintf(fp, "%.16f %d %d\n", pair.sim, pair.l_rec, pair.r_rec); } fclose(fp); } void init_topk_list(const Table& ltoken_vector, const Table& rtoken_vector, Heap& old_heap, vector<TopPair>& new_heap) { while (old_heap.size() > 0) { TopPair pair = old_heap.top(); old_heap.pop(); double new_sim = init_topk_list_calc_sim(ltoken_vector[pair.l_rec], rtoken_vector[pair.r_rec]); if (new_sim > 0) { new_heap.push_back(TopPair(new_sim, pair.l_rec, pair.r_rec)); } } return; } void TopkListGenerator::generate_topklist_for_config(const Table& ltoken_vector, const Table& rtoken_vector, const Table& lindex_vector, const Table& rindex_vector, const Table& lfield_vector, const Table& rfield_vector, const vector<int>& ltoken_sum_vector, const vector<int>& rtoken_sum_vector, const vector<int>& field_list, const int max_field_num, const int removed_field, const bool first_run, Signal& signal, CandSet& cand_set, ReuseSet& reuse_set, vector<Heap>& heap_vector, const Heap& init_topk_heap, const int prefix_match_max_size, const int rec_ave_len_thres, const int output_size, const int activate_reusing_module, const int topk_type, const string& output_path) { char buf[10]; string info = string("current configuration: ["); for (int i = 0; i <field_list.size(); ++i) { sprintf(buf, "%d", field_list[i]); if (i != 0) { info.append(string(", ")); } info.append(buf); } info.append("]"); cout << info << endl; int ltoken_total_sum = 0, rtoken_total_sum = 0; for (int i = 0; i < field_list.size(); ++i) { ltoken_total_sum += ltoken_sum_vector[field_list[i]]; rtoken_total_sum += rtoken_sum_vector[field_list[i]]; } double lrec_ave_len = ltoken_total_sum * 1.0 / ltoken_vector.size(); double rrec_ave_len = rtoken_total_sum * 1.0 / rtoken_vector.size(); unordered_set<int> remained_set; for (int i = 0; i < field_list.size(); ++i) { remained_set.insert(field_list[i]); } vector<int> removed_fields; for (int i = 0; i < max_field_num; ++i) { if (!remained_set.count(i)) { removed_fields.push_back(i); } } bool use_remain = false; if (field_list.size() < removed_fields.size()) { use_remain = true; } Heap return_topk_heap; Heap copy_init_topk_heap = init_topk_heap; vector<TopPair> updated_init_topk_list; init_topk_list(ltoken_vector, rtoken_vector, copy_init_topk_heap, updated_init_topk_list); int select_param_size = 50; if (activate_reusing_module == 0) { if (lrec_ave_len >= rec_ave_len_thres) { if (first_run) { if (prefix_match_max_size > 0) { return_topk_heap = new_topk_sim_join_plain_first(ltoken_vector, rtoken_vector, signal, cand_set, prefix_match_max_size, select_param_size, output_size); } else { return_topk_heap = original_topk_sim_join_plain_first(ltoken_vector, rtoken_vector, signal, cand_set, select_param_size, output_size); } } else { if (prefix_match_max_size > 0) { return_topk_heap = new_topk_sim_join_plain(ltoken_vector, rtoken_vector, cand_set, prefix_match_max_size, output_size); } else { return_topk_heap = original_topk_sim_join_plain(ltoken_vector, rtoken_vector, cand_set, output_size); } } } else { if (first_run) { if (prefix_match_max_size > 0) { return_topk_heap = new_topk_sim_join_plain_first(ltoken_vector, rtoken_vector, signal, cand_set, prefix_match_max_size, select_param_size, output_size); } else { return_topk_heap = original_topk_sim_join_plain_first(ltoken_vector, rtoken_vector, signal, cand_set, select_param_size, output_size); } } else { if (prefix_match_max_size > 0) { return_topk_heap = new_topk_sim_join_plain(ltoken_vector, rtoken_vector, cand_set, prefix_match_max_size, output_size); } else { return_topk_heap = original_topk_sim_join_plain(ltoken_vector, rtoken_vector, cand_set, output_size); } } } // return_topk_heap = original_topk_sim_join_plain(ltoken_vector, rtoken_vector, cand_set, output_size); } else { if (lrec_ave_len >= rec_ave_len_thres || rrec_ave_len >= rec_ave_len_thres) { if (topk_type == 0) { if (field_list.size() <= 1) { return_topk_heap = new_topk_sim_join_reuse(ltoken_vector, rtoken_vector, max_field_num, use_remain, field_list, removed_fields, updated_init_topk_list, cand_set, reuse_set, prefix_match_max_size, output_size); } else { if (first_run) { if (prefix_match_max_size > 0) { return_topk_heap = new_topk_sim_join_record_first(ltoken_vector, rtoken_vector, lindex_vector, rindex_vector, lfield_vector, rfield_vector, field_list, removed_fields, max_field_num, use_remain, heap_vector, signal, cand_set, reuse_set, prefix_match_max_size, select_param_size, output_size); } else { return_topk_heap = original_topk_sim_join_record_first(ltoken_vector, rtoken_vector, lindex_vector, rindex_vector, lfield_vector, rfield_vector, field_list, removed_fields, max_field_num, use_remain, heap_vector, signal, cand_set, reuse_set, select_param_size, output_size); } } else { return_topk_heap = new_topk_sim_join_record(ltoken_vector, rtoken_vector, lindex_vector, rindex_vector, lfield_vector, rfield_vector, field_list, removed_fields, max_field_num, use_remain, heap_vector, updated_init_topk_list, cand_set, reuse_set, prefix_match_max_size, output_size); } } } else if (topk_type == 1) { return_topk_heap = new_topk_sim_join_reuse(ltoken_vector, rtoken_vector, max_field_num, use_remain, field_list, removed_fields, updated_init_topk_list, cand_set, reuse_set, prefix_match_max_size, output_size); } } else { if (topk_type == 0) { if (remained_set.size() <= 1) { // return_topk_heap = original_topk_sim_join_reuse(ltoken_vector, rtoken_vector, max_field_num, use_remain, // field_list, removed_fields, updated_init_topk_list, // cand_set, reuse_set, output_size); if (prefix_match_max_size > 0) { return_topk_heap = new_topk_sim_join_reuse(ltoken_vector, rtoken_vector, max_field_num, use_remain, field_list, removed_fields, updated_init_topk_list, cand_set, reuse_set, prefix_match_max_size, output_size); } else { return_topk_heap = original_topk_sim_join_reuse(ltoken_vector, rtoken_vector, max_field_num, use_remain, field_list, removed_fields, updated_init_topk_list, cand_set, reuse_set, output_size); } } else { // return_topk_heap = original_topk_sim_join_record(ltoken_vector, rtoken_vector, lindex_vector, rindex_vector, // lfield_vector, rfield_vector, field_list, removed_fields, // max_field_num, use_remain, heap_vector, updated_init_topk_list, // cand_set, reuse_set, output_size); if (first_run) { if (prefix_match_max_size > 0) { return_topk_heap = new_topk_sim_join_record_first(ltoken_vector, rtoken_vector, lindex_vector, rindex_vector, lfield_vector, rfield_vector, field_list, removed_fields, max_field_num, use_remain, heap_vector, signal, cand_set, reuse_set, prefix_match_max_size, select_param_size, output_size); } else { return_topk_heap = original_topk_sim_join_record_first(ltoken_vector, rtoken_vector, lindex_vector, rindex_vector, lfield_vector, rfield_vector, field_list, removed_fields, max_field_num, use_remain, heap_vector, signal, cand_set, reuse_set, select_param_size, output_size); } } else { if (prefix_match_max_size > 0) { return_topk_heap = new_topk_sim_join_record(ltoken_vector, rtoken_vector, lindex_vector, rindex_vector, lfield_vector, rfield_vector, field_list, removed_fields, max_field_num, use_remain, heap_vector, updated_init_topk_list, cand_set, reuse_set, prefix_match_max_size, output_size); } else { return_topk_heap = original_topk_sim_join_record(ltoken_vector, rtoken_vector, lindex_vector, rindex_vector, lfield_vector, rfield_vector, field_list, removed_fields, max_field_num, use_remain, heap_vector, updated_init_topk_list, cand_set, reuse_set, output_size); } } } } else if (topk_type == 1) { // return_topk_heap = original_topk_sim_join_reuse(ltoken_vector, rtoken_vector, max_field_num, use_remain, // field_list, removed_fields, updated_init_topk_list, // cand_set, reuse_set, output_size); if (prefix_match_max_size > 0) { return_topk_heap = new_topk_sim_join_reuse(ltoken_vector, rtoken_vector, max_field_num, use_remain, field_list, removed_fields, updated_init_topk_list, cand_set, reuse_set, prefix_match_max_size, output_size); } else { return_topk_heap = original_topk_sim_join_reuse(ltoken_vector, rtoken_vector, max_field_num, use_remain, field_list, removed_fields, updated_init_topk_list, cand_set, reuse_set, output_size); } } } } if (first_run) { if (signal.value == prefix_match_max_size) { save_topk_list_to_file(field_list, output_path, return_topk_heap); } } else { save_topk_list_to_file(field_list, output_path, return_topk_heap); } cout << "finish" << endl; }
d531df27745c7cdb69dd87927f5b6f8fb3d3d7a3
9030ce2789a58888904d0c50c21591632eddffd7
/SDK/ARKSurvivalEvolved_Buff_Companion_BaseBP_classes.hpp
a7bd39cf0f059d718cd5603f744c3d055f5df299
[ "MIT" ]
permissive
2bite/ARK-SDK
8ce93f504b2e3bd4f8e7ced184980b13f127b7bf
ce1f4906ccf82ed38518558c0163c4f92f5f7b14
refs/heads/master
2022-09-19T06:28:20.076298
2022-09-03T17:21:00
2022-09-03T17:21:00
232,411,353
14
5
null
null
null
null
UTF-8
C++
false
false
892
hpp
ARKSurvivalEvolved_Buff_Companion_BaseBP_classes.hpp
#pragma once // ARKSurvivalEvolved (332.8) SDK #ifdef _MSC_VER #pragma pack(push, 0x8) #endif #include "ARKSurvivalEvolved_Buff_Companion_BaseBP_structs.hpp" namespace sdk { //--------------------------------------------------------------------------- //Classes //--------------------------------------------------------------------------- // BlueprintGeneratedClass Buff_Companion_BaseBP.Buff_Companion_BaseBP_C // 0x0000 (0x1130 - 0x1130) class ABuff_Companion_BaseBP_C : public APrimalBuff_Companion { public: static UClass* StaticClass() { static auto ptr = UObject::FindClass("BlueprintGeneratedClass Buff_Companion_BaseBP.Buff_Companion_BaseBP_C"); return ptr; } void BPInstigatorPossessed(class AController** ByController); void UserConstructionScript(); void ExecuteUbergraph_Buff_Companion_BaseBP(int EntryPoint); }; } #ifdef _MSC_VER #pragma pack(pop) #endif
45b00a9dc8e8dd9a82906301178b13ef8514ae78
6b2a8dd202fdce77c971c412717e305e1caaac51
/solutions_5738606668808192_1/C++/hiaatcnd/c.cpp
c87c755b11d4ed864092ff8e7816a78e6b35fcb6
[]
no_license
alexandraback/datacollection
0bc67a9ace00abbc843f4912562f3a064992e0e9
076a7bc7693f3abf07bfdbdac838cb4ef65ccfcf
refs/heads/master
2021-01-24T18:27:24.417992
2017-05-23T09:23:38
2017-05-23T09:23:38
84,313,442
2
4
null
null
null
null
UTF-8
C++
false
false
900
cpp
c.cpp
#include <bits/stdc++.h> using namespace std; const int N = 32, M = 500; const int pri[25] = {2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97}; int a[60]; bool check(){ vector<int> ans; for(int k = 2; k <= 10; k++){ bool flag = 0; for(int j = 0; j < 25 && !flag; j++){ int cnt = 0; for(int i = N - 1; i >= 0; i--){ cnt = cnt * k + a[i]; cnt %= pri[j]; } if(cnt == 0) ans.push_back(pri[j]), flag = 1; } if(!flag) return 0; } for(int i = N - 1; i >= 0; i--) printf("%d", a[i]); for(auto v : ans) printf(" %d", v); printf("\n"); return 1; } int main(){ freopen("c.in", "r", stdin); freopen("c.out", "w", stdout); int ans = 0; printf("Case #1:\n"); for(int i = 1; ; i += 2){ for(int j = 0; j < N; j++) a[j] = (i >> j) & 1; a[N - 1] = 1; if(check()) ans++; if(ans == M) break; } return 0; }
b9e0eaa7896ed856bd2a8be7f2a0b9616e07cd7e
169a82b7b07a7d101bcf53ab45ff7fccfa5b801e
/ConfigServer.hpp
7b57d7caa7896158e554a745b6cc29e27cce70fb
[]
no_license
toastedcode/Roboxes
efd51fa53a1bafb416b45d50761948c3623bbeff
753a8ef3545402ea7d7cdab247517eba634a3c7b
refs/heads/master
2021-01-11T16:17:52.080789
2017-02-02T04:13:27
2017-02-02T04:13:27
80,058,794
0
0
null
2017-02-02T04:13:27
2017-01-25T21:17:20
C++
UTF-8
C++
false
false
241
hpp
ConfigServer.hpp
#pragma once #include <ESP8266WebServer.h> class ConfigServer { public: static void begin(); static void run(); private: static void handleRoot(); static void handleNotFound(); static ESP8266WebServer server; };
408c69bd02c32f3ed19f14385c5f6f4bc44be707
0bf8cdde9562a400fe1604237a658fae5a170982
/ext/openMVG/dependencies/osi_clp/CoinUtils/src/CoinAlloc.cpp
120277da0a0ad141b998fa48b1b6a3e1248ed3b1
[ "LicenseRef-scancode-free-unknown", "EPL-1.0", "BSD-3-Clause" ]
permissive
AIBluefisher/EGSfM
64c2108c037a7e730a81690598022586d6ae90aa
e2e505353cdc525b8e814e0019bd0dc67be75fea
refs/heads/master
2021-06-19T02:06:22.904219
2021-02-28T03:11:14
2021-02-28T03:11:14
187,424,684
91
19
BSD-3-Clause
2020-03-03T07:33:47
2019-05-19T02:20:18
C++
UTF-8
C++
false
false
4,524
cpp
CoinAlloc.cpp
/* $Id: CoinAlloc.cpp 1373 2011-01-03 23:57:44Z lou $ */ // Copyright (C) 2007, International Business Machines // Corporation and others. All Rights Reserved. // This code is licensed under the terms of the Eclipse Public License (EPL). #include <cassert> #include <cstdlib> #include <new> #include "CoinAlloc.hpp" #if (COINUTILS_MEMPOOL_MAXPOOLED >= 0) //============================================================================= CoinMempool::CoinMempool(size_t entry) : #if (COIN_MEMPOOL_SAVE_BLOCKHEADS==1) block_heads_(NULL), block_num_(0), max_block_num_(0), #endif last_block_size_(0), first_free_(NULL), entry_size_(entry) { #if defined(COINUTILS_PTHREADS) && (COINUTILS_PTHREAD == 1) pthread_mutex_init(&mutex_, NULL); #endif assert((entry_size_/COINUTILS_MEMPOOL_ALIGNMENT)*COINUTILS_MEMPOOL_ALIGNMENT == entry_size_); } //============================================================================= CoinMempool::~CoinMempool() { #if (COIN_MEMPOOL_SAVE_BLOCKHEADS==1) for (size_t i = 0; i < block_num_; ++i) { free(block_heads_[i]); } #endif #if defined(COINUTILS_PTHREADS) && (COINUTILS_PTHREAD == 1) pthread_mutex_destroy(&mutex_); #endif } //============================================================================== char* CoinMempool::alloc() { lock_mutex(); if (first_free_ == NULL) { unlock_mutex(); char* block = allocate_new_block(); lock_mutex(); #if (COIN_MEMPOOL_SAVE_BLOCKHEADS==1) // see if we can record another block head. If not, then resize // block_heads if (max_block_num_ == block_num_) { max_block_num_ = 2 * block_num_ + 10; char** old_block_heads = block_heads_; block_heads_ = (char**)malloc(max_block_num_ * sizeof(char*)); CoinMemcpyN( old_block_heads,block_num_,block_heads_); free(old_block_heads); } // save the new block block_heads_[block_num_++] = block; #endif // link in the new block *(char**)(block+((last_block_size_-1)*entry_size_)) = first_free_; first_free_ = block; } char* p = first_free_; first_free_ = *(char**)p; unlock_mutex(); return p; } //============================================================================= char* CoinMempool::allocate_new_block() { last_block_size_ = static_cast<int>(1.5 * last_block_size_ + 32); char* block = static_cast<char*>(std::malloc(last_block_size_*entry_size_)); // link the entries in the new block together for (int i = last_block_size_-2; i >= 0; --i) { *(char**)(block+(i*entry_size_)) = block+((i+1)*entry_size_); } // terminate the linked list with a null pointer *(char**)(block+((last_block_size_-1)*entry_size_)) = NULL; return block; } //############################################################################# CoinAlloc CoinAllocator; CoinAlloc::CoinAlloc() : pool_(NULL), maxpooled_(COINUTILS_MEMPOOL_MAXPOOLED) { const char* maxpooled = std::getenv("COINUTILS_MEMPOOL_MAXPOOLED"); if (maxpooled) { maxpooled_ = std::atoi(maxpooled); } const size_t poolnum = maxpooled_ / COINUTILS_MEMPOOL_ALIGNMENT; maxpooled_ = poolnum * COINUTILS_MEMPOOL_ALIGNMENT; if (maxpooled_ > 0) { pool_ = (CoinMempool*)malloc(sizeof(CoinMempool)*poolnum); for (int i = poolnum-1; i >= 0; --i) { new (&pool_[i]) CoinMempool(i*COINUTILS_MEMPOOL_ALIGNMENT); } } } //############################################################################# #if defined(COINUTILS_MEMPOOL_OVERRIDE_NEW) && (COINUTILS_MEMPOOL_OVERRIDE_NEW == 1) void* operator new(std::size_t sz) throw (std::bad_alloc) { return CoinAllocator.alloc(sz); } void* operator new[](std::size_t sz) throw (std::bad_alloc) { return CoinAllocator.alloc(sz); } void operator delete(void* p) throw() { CoinAllocator.dealloc(p); } void operator delete[](void* p) throw() { CoinAllocator.dealloc(p); } void* operator new(std::size_t sz, const std::nothrow_t&) throw() { void *p = NULL; try { p = CoinAllocator.alloc(sz); } catch (std::bad_alloc &ba) { return NULL; } return p; } void* operator new[](std::size_t sz, const std::nothrow_t&) throw() { void *p = NULL; try { p = CoinAllocator.alloc(sz); } catch (std::bad_alloc &ba) { return NULL; } return p; } void operator delete(void* p, const std::nothrow_t&) throw() { CoinAllocator.dealloc(p); } void operator delete[](void* p, const std::nothrow_t&) throw() { CoinAllocator.dealloc(p); } #endif #endif /*(COINUTILS_MEMPOOL_MAXPOOLED >= 0)*/
675727041a2b719ba2f12021577d9c545a4fdde1
1ec58232eb5b7d092b58fffeaf79814992322b2e
/108.cpp
6a7f325567eb8a640f7ccfaf8d895867bf5d12d2
[]
no_license
linkouth/acm-univer
f6490911866e07bc6e7343c21a4dd476ebcd3e15
d9adf9ee7d666a064fc8ee034cf379da6ba1aafa
refs/heads/master
2020-04-09T06:09:27.941820
2019-09-16T04:40:19
2019-09-16T04:40:19
160,100,708
0
0
null
null
null
null
UTF-8
C++
false
false
1,040
cpp
108.cpp
#include <iostream> #include <vector> using namespace std; const int INF = INT32_MAX; int main() { int N, M, v1, v2; cin >> N >> M >> v1 >> v2; v1--; v2--; vector < vector < pair<int, int> > > g(N); for (int i = 0; i < M; ++i) { int start, end, length; cin >> start >> end >> length; start--; end--; g[start].push_back(make_pair(end, length)); g[end].push_back(make_pair(start, length)); } vector<int> d(N, INF); d[v1] = 0; vector<char> u(N); for (int i = 0; i < N; ++i) { int v = -1; for (int j = 0; j < N; ++j) if (!u[j] && (v == -1 || d[j] < d[v])) v = j; if (d[v] == INF) break; u[v] = true; for (size_t j = 0; j<g[v].size(); ++j) { int to = g[v][j].first, len = g[v][j].second; if (d[v] + len < d[to]) { d[to] = d[v] + len; } } } if (d[v2] < INF) { cout << d[v2] << '\n'; } else { cout << -1 << '\n'; } /*for (int i = 0; i < N; ++i) { cout << i << ": "; for (auto pair : g[i]) { cout << pair.first << ' ' << pair.second; } cout << '\n'; }*/ }
70902ffd63672bde940f1b42a21b15435224a2c0
2944427265e7ac86292a1f0d51b770944656f59a
/mission/sdv.TANOA/dialog/settings.hpp
2e51c47bbed2bc78119cd8baab43fa0a88218ad8
[ "CC0-1.0" ]
permissive
PC-Gamercom/pcg_tanoa
939d0856c9aa2f16ea72771b756bc309b93030c0
36df0ebdcb5cc46af61536d9850b5f8c0c15265e
refs/heads/master
2020-12-19T06:02:41.209072
2016-08-09T11:01:00
2016-08-09T11:01:00
61,654,721
14
6
null
null
null
null
UTF-8
C++
false
false
4,724
hpp
settings.hpp
class SettingsMenu { idd = 2900; name = "SettingsMenu"; movingEnable = 1; enableSimulation = 1; class controlsBackground { class RscTitleBackground : life_RscText { colorBackground[] = {"(profilenamespace getvariable ['GUI_BCG_RGB_R',0.3843])", "(profilenamespace getvariable ['GUI_BCG_RGB_G',0.7019])", "(profilenamespace getvariable ['GUI_BCG_RGB_B',0.8862])", "(profilenamespace getvariable ['GUI_BCG_RGB_A',0.7])"}; idc = -1; x = 0.3; y = 0.2; w = 0.5; h = (1 / 25); }; class RscMainBackground : life_RscText { colorBackground[] = {0,0,0,0.7}; idc = -1; x = 0.3; y = 0.2 + (11 / 250); w = 0.5; h = 0.43 - (22 / 250); }; class PlayerTagsHeader : Life_RscText { idc = -1; text = "$STR_SM_PlayerTags"; colorBackground[] = {"(profilenamespace getvariable ['GUI_BCG_RGB_R',0.3843])", "(profilenamespace getvariable ['GUI_BCG_RGB_G',0.7019])", "(profilenamespace getvariable ['GUI_BCG_RGB_B',0.8862])", "(profilenamespace getvariable ['GUI_BCG_RGB_A',0.7])"}; x = 0.30; y = 0.43; w = 0.35; h = (1 / 25); }; class SideChatHeader : PlayerTagsHeader { idc = -1; text = "$STR_SM_SC"; y = 0.48; }; class RevealNearestHeader : PlayerTagsHeader { idc = -1; text = "$STR_SM_RNObj"; y = 0.53; }; class Title : life_RscTitle { idc = -1; colorBackground[] = {0,0,0,0}; text = "$STR_SM_Title"; x = 0.3; y = 0.2; w = 0.5; h = (1 / 25); }; }; class controls { class VDonFoot : life_RscText { idc = -1; text = "$STR_SM_onFoot"; x = 0.32; y = 0.258; w = 0.275; h = 0.04; }; class VDinCar : life_RscText { idc = -1; text = "$STR_SM_inCar"; x = 0.32; y = 0.305; w = 0.275; h = 0.04; }; class VDinAir : life_RscText { idc = -1; text = "$STR_SM_inAir"; x = 0.32; y = 0.355; w = 0.275; h = 0.04; }; class VD_onfoot_slider : life_RscXSliderH { idc = 2901; text = ""; onSliderPosChanged = "[0,_this select 1] call life_fnc_s_onSliderChange;"; tooltip = "$STR_SM_ToolTip1"; x = 0.42; y = 0.30 - (1 / 25); w = "9 * ( ((safezoneW / safezoneH) min 1.2) / 40)"; h = "1 * ( ( ((safezoneW / safezoneH) min 1.2) / 1.2) / 25)"; }; class VD_onfoot_value : Life_RscEdit { idc = 2902; text = ""; onChar = "[_this select 0, _this select 1,'ground',false] call life_fnc_s_onChar;"; onKeyUp = "[_this select 0, _this select 1,'ground',true] call life_fnc_s_onChar;"; x = .70; y = .258; w = .08; h = .04; }; class VD_car_slider : life_RscXSliderH { idc = 2911; text = ""; onSliderPosChanged = "[1,_this select 1] call life_fnc_s_onSliderChange;"; tooltip = "$STR_SM_ToolTip2"; x = 0.42; y = 0.35 - (1 / 25); w = "9 * ( ((safezoneW / safezoneH) min 1.2) / 40)"; h = "1 * ( ( ((safezoneW / safezoneH) min 1.2) / 1.2) / 25)"; }; class VD_car_value : Life_RscEdit { idc = 2912; text = ""; onChar = "[_this select 0, _this select 1,'vehicle',false] call life_fnc_s_onChar;"; onKeyUp = "[_this select 0, _this select 1,'vehicle',true] call life_fnc_s_onChar;"; x = .70; y = .31; w = .08; h = .04; }; class VD_air_slider : life_RscXSliderH { idc = 2921; text = ""; onSliderPosChanged = "[2,_this select 1] call life_fnc_s_onSliderChange;"; tooltip = "$STR_SM_ToolTip3"; x = 0.42; y = 0.40 - (1 / 25); w = "9 * ( ((safezoneW / safezoneH) min 1.2) / 40)"; h = "1 * ( ( ((safezoneW / safezoneH) min 1.2) / 1.2) / 25)"; }; class VD_air_value : Life_RscEdit { idc = 2922; text = ""; onChar = "[_this select 0, _this select 1,'air',false] call life_fnc_s_onChar;"; onKeyUp = "[_this select 0, _this select 1,'air',true] call life_fnc_s_onChar;"; x = 0.70; y = 0.36; w = .08; h = .04; }; class PlayerTagsONOFF : Life_Checkbox { tooltip = "$STR_GUI_PlayTags"; idc = 2970; sizeEx = 0.04; onCheckedChanged = "['tags',_this select 1] call life_fnc_s_onCheckedChange;"; x = 0.65; y = 0.43; }; class SideChatONOFF : PlayerTagsONOFF { idc = 2971; tooltip = "$STR_GUI_SideSwitch"; onCheckedChanged = "['sidechat',_this select 1] call life_fnc_s_onCheckedChange;"; y = 0.48; }; class RevealONOFF : PlayerTagsONOFF { idc = 2972; tooltip = "$STR_GUI_PlayerReveal"; onCheckedChanged = "['objects',_this select 1] call life_fnc_s_onCheckedChange;"; y = 0.53; }; class ButtonClose : life_RscButtonMenu { idc = -1; //shortcuts[] = {0x00050000 + 2}; text = "$STR_Global_Close"; onButtonClick = "closeDialog 0;"; x = 0.48; y = 0.63 - (1 / 25); w = (6.25 / 40); h = (1 / 25); }; }; };
0220c73925421ab836b0a5fa68f81d7c01162be0
5359506484bde1255e15e1a94c1cbabafdda1112
/src/menu/WaitingMenu.cpp
3f6f6ac83ad1ba92ad69c6f742417b02899d8579
[]
no_license
siwon/projetBomberman
49e59e1470cf259107987696f077ca2fdee379a0
38a05ac81c17f3c6f49b8ccfb066b0fd218c374f
refs/heads/master
2016-09-05T14:35:50.475687
2012-06-07T16:11:12
2012-06-07T16:11:12
3,461,125
2
1
null
null
null
null
UTF-8
C++
false
false
4,502
cpp
WaitingMenu.cpp
/*! * \file WaitingMenu.cpp * \brief Gestionnaire du menu d'attente de début de partie * \author Maxime GUIHAL */ #include "menu/WaitingMenu.hpp" #include "PolyBomberApp.hpp" namespace PolyBomber { WaitingMenu::WaitingMenu(SMenuConfig* menuConfig) : title("Resume de la partie", TITLEFONT, 50), ip("Adresse IP du serveur : ", TEXTFONT, 150), cancel("Annuler", 500, GAMEMENU), start("Jouer !", 500, RUNGAME), menuConfig(menuConfig) { ISkin* skin = PolyBomberApp::getISkin(); title.setColor(skin->getColor(TITLECOLOR)); ip.setColor(skin->getColor(TEXTCOLOR)); this->network = PolyBomberApp::getINetworkToMenu(); ip.setString(ip.getString() + this->network->getIpAddress()); ip.move(-80, 0); cancel.move(-100, 0); start.move(100, 0); cancel.setSelected(true); cancel.setNext(&start); start.setNext(&cancel); this->widgets.push_back(&title); this->widgets.push_back(&ip); this->widgets.push_back(&cancel); this->widgets.push_back(&start); for (int i=0; i<4; i++) { this->pictures[i] = new ImageWidget(); this->pictures[i]->setPosition(300, 200 + 60*i); this->pictures[i]->setImage(skin->loadImage((EImage)(PLAYER1 + i))); this->names[i] = new TextWidget("...", TEXTFONT, 210 + 60*i); this->names[i]->setColor(skin->getColor(TEXTCOLOR)); this->names[i]->move(100, 0); this->widgets.push_back(this->pictures[i]); this->widgets.push_back(this->names[i]); } } void WaitingMenu::leftPressed() { start.goNext(); } void WaitingMenu::rightPressed() { cancel.goNext(); } void WaitingMenu::validPressed(EMenuScreen* nextScreen) { if (cancel.getSelected()) { this->network->cancel(); *nextScreen = cancel.activate(); } if (start.getSelected()) { this->network->startGame(); *nextScreen = start.activate(); } } void WaitingMenu::backPressed(EMenuScreen* nextScreen) { this->network->cancel(); *nextScreen = cancel.activate(); } void WaitingMenu::update() { std::string names[4] = {"", "", "", ""}; this->network->getPlayersName(names); if (!menuConfig->isServer) { // On remet à jour le nombre de joueurs de la partie unsigned int nb = 0; while (nb < 4 && names[nb].compare("") != 0) nb++; this->menuConfig->gameConfig.nbPlayers = nb; } for (unsigned int i=0; i<4; i++) { menuConfig->gameConfig.playersName[i] = names[i]; this->pictures[i]->setVisible(i < this->menuConfig->gameConfig.nbPlayers); this->names[i]->setVisible(i < this->menuConfig->gameConfig.nbPlayers); } for (unsigned int i=0; i<this->menuConfig->gameConfig.nbPlayers; i++) { if (names[i].compare("None") == 0 || names[i].compare("") == 0) this->names[i]->setString("..."); else this->names[i]->setString(names[i]); } } EMenuScreen WaitingMenu::run(MainWindow& window, EMenuScreen) { IControllerToMenu* controller = PolyBomberApp::getIControllerToMenu(); EMenuScreen nextScreen = NONEMENU; try { initWidgets(); sf::Clock clock; while (nextScreen == NONEMENU) { window.clear(); window.display(this->widgets); EMenuKeys key = MENU_NONE; while ((key = controller->getKeyPressed()) == MENU_NONE && window.isOpen()) { // On raffraichit les noms if (clock.getElapsedTime().asMilliseconds() > 250) { clock.restart(); update(); window.clear(); window.display(this->widgets); // On teste si la partie commence if (this->network->isStarted()) { nextScreen = start.activate(); break; } } } switch(key) { case MENU_DOWN: downPressed(); break; case MENU_UP: upPressed(); break; case MENU_LEFT: leftPressed(); break; case MENU_RIGHT: rightPressed(); break; case MENU_VALID: validPressed(&nextScreen); break; case MENU_BACK: backPressed(&nextScreen); break; default: break; } if (!window.isOpen()) nextScreen = EXIT; } } catch(PolyBomberException& e) { std::cerr << e.what() << std::endl; this->network->cancel(); nextScreen = GAMEMENU; } return nextScreen; } void WaitingMenu::initWidgets() { ip.setVisible(this->menuConfig->isServer && !this->menuConfig->gameConfig.isLocal); start.setVisible(this->menuConfig->isServer); if (this->menuConfig->isServer) cancel.setNext(&start); else cancel.setNext(NULL); } }
f78d11d53f90350d4a79c98736729d738ef37004
b22588340d7925b614a735bbbde1b351ad657ffc
/athena/DetectorDescription/GeoModel/GeoModelKernel/src/GeoVPhysVol.cxx
e1a965ea0c885f3c7be852ed46df34cbaf584612
[]
no_license
rushioda/PIXELVALID_athena
90befe12042c1249cbb3655dde1428bb9b9a42ce
22df23187ef85e9c3120122c8375ea0e7d8ea440
refs/heads/master
2020-12-14T22:01:15.365949
2020-01-19T03:59:35
2020-01-19T03:59:35
234,836,993
1
0
null
null
null
null
UTF-8
C++
false
false
4,591
cxx
GeoVPhysVol.cxx
/* Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration */ //## begin module%1.5%.codegen_version preserve=yes // Read the documentation to learn more about C++ code generator // versioning. //## end module%1.5%.codegen_version //## begin module%3CD3E93F00F9.cm preserve=no // %X% %Q% %Z% %W% //## end module%3CD3E93F00F9.cm //## begin module%3CD3E93F00F9.cp preserve=no //## end module%3CD3E93F00F9.cp //## Module: GeoVPhysVol%3CD3E93F00F9; Pseudo Package body //## Source file: /home/atlas/GEO/GeoModelKernel/GeoVPhysVol.cxx //## begin module%3CD3E93F00F9.additionalIncludes preserve=no //## end module%3CD3E93F00F9.additionalIncludes //## begin module%3CD3E93F00F9.includes preserve=yes #include "GeoModelKernel/GeoAccessVolumeAction.h" #include "GeoModelKernel/GeoVolumeAction.h" //## end module%3CD3E93F00F9.includes // GeoVPhysVol #include "GeoModelKernel/GeoVPhysVol.h" //## begin module%3CD3E93F00F9.additionalDeclarations preserve=yes //## end module%3CD3E93F00F9.additionalDeclarations // Class GeoVPhysVol GeoVPhysVol::GeoVPhysVol (const GeoLogVol* LogVol) //## begin GeoVPhysVol::GeoVPhysVol%3CD403D2012C.hasinit preserve=no //## end GeoVPhysVol::GeoVPhysVol%3CD403D2012C.hasinit //## begin GeoVPhysVol::GeoVPhysVol%3CD403D2012C.initialization preserve=yes :m_parentPtr (NULL), m_logVol (LogVol) //## end GeoVPhysVol::GeoVPhysVol%3CD403D2012C.initialization { //## begin GeoVPhysVol::GeoVPhysVol%3CD403D2012C.body preserve=yes if(m_logVol) m_logVol->ref(); //## end GeoVPhysVol::GeoVPhysVol%3CD403D2012C.body } GeoVPhysVol::~GeoVPhysVol() { //## begin GeoVPhysVol::~GeoVPhysVol%3CD3E93F00F9_dest.body preserve=yes if(m_logVol) m_logVol->unref(); //## end GeoVPhysVol::~GeoVPhysVol%3CD3E93F00F9_dest.body } //## Other Operations (implementation) Query<unsigned int> GeoVPhysVol::indexOf (PVConstLink daughter) const { //## begin GeoVPhysVol::indexOf%3CDE97BC00B9.body preserve=yes for (unsigned int i = 0; i < getNChildVols (); i++) { if (getChildVol (i) == daughter) return i; } return Query <unsigned int >(); //## end GeoVPhysVol::indexOf%3CDE97BC00B9.body } PVConstLink GeoVPhysVol::getParent () const { //## begin GeoVPhysVol::getParent%3CDE6F5903B1.body preserve=yes if (m_parentPtr && m_parentPtr != this) return m_parentPtr; return NULL; //## end GeoVPhysVol::getParent%3CDE6F5903B1.body } const GeoLogVol* GeoVPhysVol::getLogVol () const { //## begin GeoVPhysVol::getLogVol%3CDE67950290.body preserve=yes return m_logVol; //## end GeoVPhysVol::getLogVol%3CDE67950290.body } void GeoVPhysVol::apply (GeoVolumeAction *action) const { //## begin GeoVPhysVol::apply%3CE238BB0078.body preserve=yes if (action->getType () == GeoVolumeAction::TOP_DOWN) { action->handleVPhysVol (this); if (action->shouldTerminate ()) return; action->getState ()->nextLevel (this); int nVols = getNChildVols (); for (int d = 0; d < nVols; d++) { GeoAccessVolumeAction av (d); exec (&av); action->getState ()->setTransform (av.getTransform ()); action->getState ()->setDefTransform (av.getDefTransform ()); action->getState ()->setId(av.getId()); action->getState ()->setName(av.getName()); av.getVolume ()->apply (action); if(action->shouldTerminate ()) break; } action->getState ()->previousLevel (); } else if (action->getType () == GeoVolumeAction::BOTTOM_UP) { action->getState ()->nextLevel (this); int nVols = getNChildVols (); for (int d = 0; d < nVols; d++) { GeoAccessVolumeAction av (d); exec (&av); action->getState ()->setTransform (av.getTransform ()); action->getState ()->setDefTransform (av.getDefTransform ()); action->getState ()->setId(av.getId()); action->getState ()->setName(av.getName()); av.getVolume ()->apply (action); if(action->shouldTerminate ()) break; } action->getState ()->previousLevel (); action->handleVPhysVol (this); if (action->shouldTerminate ()) return; } //## end GeoVPhysVol::apply%3CE238BB0078.body } void GeoVPhysVol::dockTo (GeoVPhysVol* parent) { //## begin GeoVPhysVol::dockTo%3DB85BC00025.body preserve=yes if(m_parentPtr) m_parentPtr = this; else m_parentPtr = parent; //## end GeoVPhysVol::dockTo%3DB85BC00025.body } // Additional Declarations //## begin GeoVPhysVol%3CD3E93F00F9.declarations preserve=yes //## end GeoVPhysVol%3CD3E93F00F9.declarations //## begin module%3CD3E93F00F9.epilog preserve=yes //## end module%3CD3E93F00F9.epilog
35f02f9437c45b8268a37197fa8e776d7e23f174
ca892d28aa68a3d7b6ee2a03ba71a6b5ad85f91f
/cpp/cpp/16_ExercicioAvaliacao_3/src/Veiculo.cpp
436476952852977d1f7c1c147fdc80972b80d381
[]
no_license
SamuelCarneiroSilveira/College_Classes
5a0449a598ee06217b6e4b4e940181df820195d0
11da3546b1e2c4f2a966775f0672fa0a7c1546c8
refs/heads/main
2023-08-25T01:54:15.389105
2021-09-28T01:27:53
2021-09-28T01:27:53
411,095,295
0
0
null
null
null
null
UTF-8
C++
false
false
1,604
cpp
Veiculo.cpp
#include "Veiculo.h" Veiculo::Veiculo() { //ctor } Veiculo::~Veiculo() { //dtor } void Veiculo::setCor(string cor) { this->cor = cor; } void Veiculo::setAno(int ano) { this->ano = ano; } void Veiculo::setFabricante(string fabricante) { this->fabricante = fabricante; } void Veiculo::setModelo(string modelo) { this->modelo = modelo; } void Veiculo::setPlaca(string placa) { this->placa = placa; } string Veiculo::getCor() { return cor; } string Veiculo::getModelo() { return modelo; } string Veiculo::getFabricante() { return fabricante; } string Veiculo::getPlaca() { return placa; } int Veiculo::getAno() { return ano; } void Veiculo::cadastrarDadosVeiculo() { cout << "Informe o Ano de fabricacao: " << endl; cin >> ano; cout << "Informe o modelo:" << endl; cin >> modelo; cout << "Informe a cor:" << endl; cin >> cor; cout << "Informe o fabricante:" << endl; cin >> fabricante; cout << "Informe a placa:" << endl; cin >> placa; } void Veiculo::imprimirDadosVeiculo() { cout << "Ano de fabricacao: " << ano << endl; cout << "Modelo: " << modelo << endl; cout << "Cor: " << cor << endl; cout << "Fabricante: " << fabricante << endl; cout << "Placa: " << placa << endl; cout << "Dono: " << dono->getNome() << endl; cout << "-----------------------------------" << endl; } void Veiculo::setDono(Proprietario* dono) { this->dono = dono; } Proprietario* Veiculo::getDono() { return dono; }
bdc348b0ac40f28d7e77e6b857e59a96fa218621
e0548caf7bd8153f8d991b7d7c1bed487402f0bc
/semestr-5/Algorytmy i struktury danych 1/PRO/programy-z-cwiczen/2019/C12/ID03P04/C12_ID03P04_0001/src/Application.cpp
c482981b7b53ae707a6157e7e0238d918ae37425
[]
no_license
Ch3shireDev/WIT-Zajecia
58d9ca03617ba07bd25ce439aeeca79533f0bcb6
3cd4f7dea6abdf7126c44a1d856ca5b6002813ca
refs/heads/master
2023-09-01T11:32:12.636305
2023-08-28T16:48:03
2023-08-28T16:48:03
224,985,239
19
24
null
2023-07-02T20:54:18
2019-11-30T08:57:27
C
UTF-8
C++
false
false
1,371
cpp
Application.cpp
#include "Application.h" ///****************************************************** void Application::Run(){ srand(time(0)); Main05(); } ///****************************************************** void Application::Main01(){ Animal an01("Kajtek"); cout<<an01.AnimalName()<<endl; } ///****************************************************** void Application::Main02(){ Cat an01("Mruczek"); cout<<an01.AnimalName()<<endl; } ///****************************************************** void Application::Main03(){ Animal* an01 = new Cat("Mruczek"); cout<<an01->AnimalName()<<endl; an01->Test(); } ///****************************************************** void Application::Main04(){ Animal* an01 = new Dog("Burek"); cout<<an01->AnimalName()<<endl; an01->Test(); } ///****************************************************** void Application::Main05(){ unsigned s =10; Animal** ZOO = new Animal*[s]; for(unsigned i =0,c=0,d=0; i<s;++i) if(1==rand()%2) ZOO[i] = new Cat("Mruczek" + to_string(++c)); else ZOO[i] = new Dog("Burek" + to_string(++d)); for(unsigned i =0; i<s;++i) cout<<ZOO[i]->AnimalName()<<endl; } ///******************************************************
8b24fe6b0e8e8cc251ce38ace26727e15f06d463
729141e43e5188aa97569cc66b7016abe26f55aa
/software/arduino/integration/integration.ino
8ebe4a9204ee2909b1548e8f69de0b1489a77e6b
[]
no_license
opensensinglab/iteration8a
3da393eea85fd29154a77db3d54147b7e846bb7f
0e26665fa96f4cb6f95161af33ee7902abdc3046
refs/heads/master
2020-07-26T02:11:12.808914
2019-09-21T07:37:36
2019-09-21T07:37:36
208,498,778
0
0
null
2019-10-30T05:59:54
2019-09-14T20:19:39
C++
UTF-8
C++
false
false
2,001
ino
integration.ino
#include <Wire.h> #include <sps30.h> #include "SPS30Interface.h" #include "SparkFun_SCD30_Arduino_Library.h" #include "SensorBuffer.h" #include "SensorRadiation.h" SCD30 airSensor; // SCD30 CO2 Sensor SPS30Interface sps30; // SPS30 Air Particle Sensor // Radiation Watch Type 5 radiation sensor SensorBuffer sbRad(100); SensorRadiation sensorRadiation(&sbRad); /* * Sensirion SCD30 CO2 sensor */ void exportSCD30JSON(SCD30 scd30) { // Ensure that data is available to send if (!airSensor.dataAvailable()) { return; } Serial.print("{\"co2\": {"); // Sensor Serial.print("\"sensor\": \"SCD30\", "); // CO2 (PPM) Serial.print("\"co2ppm\": "); Serial.print(airSensor.getCO2()); Serial.print(", "); // Air temperature Serial.print("\"temp\": "); Serial.print(airSensor.getTemperature(), 1); Serial.print(", "); // Humidity Serial.print("\"humidity\": "); Serial.print(airSensor.getHumidity(), 1); // End Serial.print("} }"); Serial.println(""); } /* * Radiation sensor with digipot backpack */ void initializeRadiationSensor() { // Initialize the digipot sensorRadiation.initDigipot(); delay(10); //setDigipot(10); sensorRadiation.setDigipotAbsolute(55); delay(10); // Initialize radiation sensor setupRadiationISR(&sensorRadiation); // MUST be called before begin() sensorRadiation.begin(); } /* * Main Program */ void setup() { Wire.begin(); Serial.begin(115200); // Initialize SCD30 CO2 sensor airSensor.begin(); //This will cause readings to occur every two seconds // Initialize SPS30 air particle sensor sps30.setup(); // Initialize radiation sensor initializeRadiationSensor(); } void loop() { // SCD30 CO2 sensor exportSCD30JSON(airSensor); // SPS30 air particle sensor sps30.readMeasurements(); sps30.exportJSON(); // Radiation Watch Type 5 radiation sensor w/digipot backpack sensorRadiation.exportJSON(); delay(1000); }
94d4ba978b220d5baaa816b66dfb673d422913b4
727c574f0b5d84ae485b852ccf318063cc51772e
/ZOJ/ACM answer/1584_S.CPP
694f48d69cfd1af1e945b9083f108b5d76ec5293
[]
no_license
cowtony/ACM
36cf2202e3878a3dac1f15265ba8f902f9f67ac8
307707b2b2a37c58bc2632ef872dfccdee3264ce
refs/heads/master
2023-09-01T01:21:28.777542
2023-08-04T03:10:23
2023-08-04T03:10:23
245,681,952
7
3
null
null
null
null
UTF-8
C++
false
false
2,171
cpp
1584_S.CPP
/* 138394 2003-05-02 10:31:49 Wrong Answer 1584 C++ 00:00.00 31<<12K just for play 138430 2003-05-02 11:30:43 Runtime Error SIGSEGV 1584 C++ 00:00.04 392K just for play 138431 2003-05-02 11:32:53 Wrong Answer 1584 C++ 00:00.24 408K just for play 138437 2003-05-02 11:38:21 Accepted 1584 C++ 00:00.24 408K just for play 138953 2003-05-02 21:27:53 Wrong Answer 1584 C++ 00:00.00 416K just for play */ #include <stdio.h> #include <string.h> char d[1<<12]; struct num_type { int num[4000]; int total; void initial() { memset(num,0,sizeof(num)); total=0; } void print() { if(total==0) printf("0\n"); else { printf("%d",num[total-1]); int pt=total-2; while(pt>=0) { printf("%04d",num[pt]); pt--; } printf("\n"); } } void clear() { while(total>0&&num[total-1]==0) total--; } void convert(char* str) { total=0; int len=strlen(str); int i,j; for(i=len-1;i>=0;i=i-4) { int temp=0; for(j=i-3;j<=i;j++) { if(j<0) continue; temp=temp*10+str[j]-'0'; } num[total++]=temp; } clear(); } }; num_type fir,sec,result; const int max_num=10000; void multiply() { result.initial(); if(fir.total==0||sec.total==0) return; int i,j; result.total =fir.total +sec.total ; for(i=0;i<sec.total ;i++) { int left=0;int temp; for(j=0;j<fir.total ;j++) { temp=result.num[j]+sec.num[i]*fir.num[j]+left; result.num[j]=temp%max_num; left=temp/max_num; } while(left) { temp=result.num[j]+left; result.num[j]=temp%max_num; left=temp/max_num; j++; } } result.clear(); } int main() { // freopen("in.txt","r",stdin); // freopen("out.txt","w",stdout); while(fgets(d,1<<12,stdin)) { int N=strlen(d); d[--N]=0; if(N>1<<12-2) { printf("0\n"); continue; } if(N-(N>>1)-(N>>1)) { d[N++]='0';d[N]=0; } char str_fir[1<<12];char str_sec[1<<12]; int i;int pt=0; for(i=(N>>1)-1;i>=0;i--) str_fir[pt++]=d[i]; str_fir[N>>1]=0; pt=0; for(i=N>>1;i<N;i++) str_sec[pt++]=d[i]; str_sec[N>>1]=0; fir.initial();sec.initial(); fir.convert (str_fir); sec.convert (str_sec); multiply(); result.print (); } return 0; }
71a8b03f0dc912a212e1dca11487a9610fe202ad
655202725f7b5eac7bd45a415b333042cd33ef6b
/Physics/Algorithms.cpp
39d18bde7965f14e69538deff04cb5ff415eae8a
[]
no_license
BarabasGitHub/DogDealer
8c6aac914b1dfa54b6e89b0a3727a83d4ab61706
41b7d6bdbc6b9c2690695612ff8828f08b1403c7
refs/heads/master
2022-12-08T04:25:50.257398
2022-11-19T19:31:07
2022-11-19T19:31:07
121,017,925
1
2
null
null
null
null
WINDOWS-1252
C++
false
false
19,158
cpp
Algorithms.cpp
#include "Algorithms.h" #include "Movement.h" #include "Inertia.h" #include "BodyID.h" #include "BodyEntityMappingFunctions.h" #include <Conventions\Velocity.h> #include <Math\MathFunctions.h> #include <Math\SSEFloatFunctions.h> #include <Math\SSEMatrixFunctions.h> #include <Math\SSEMathConversions.h> #include <Math\TransformFunctions.h> #include <Utilities\VectorHelper.h> #include <Utilities\IndexedHelp.h> #include <Utilities\IntegerRange.h> using namespace Math; using namespace Physics; namespace { Orientation UpdateOrientation( Orientation orientation, Movement const & movement, Inertia const & inverse_inertia, const float time_step ) { auto const velocity = movement.momentum * inverse_inertia.mass; auto const angular_velocity = inverse_inertia.moment * movement.angular_momentum; orientation.position += velocity * time_step; orientation.rotation = UpdateRotationWithAngularVelocity(orientation.rotation, angular_velocity, time_step); return orientation; } } Quaternion Physics::UpdateRotationWithAngularVelocity( Quaternion const & rotation, Float3 const & angular_velocity, float const time_step ) { auto norm = Norm(angular_velocity); if(norm != 0) { auto angle = norm * time_step; return NormalAndAngleToQuaternion(angular_velocity / norm, angle) * rotation; } else { return rotation; } //auto spin = (Quaternion(angular_velocity, 0) * rotation); //return Normalize(rotation + rotation + spin * time_step); } Quaternion Physics::UpdateQuaternionWithAngularVelocity( Quaternion const & quaternion, Float3 const & angular_velocity, float const time_step ) { auto spin = (Quaternion(angular_velocity, 0) * quaternion); return (quaternion + spin * time_step / 2); } void Physics::AddGravity( Math::Float3 const gravity, Range<Inertia const *> inverse_inertias, Range<Math::Float3 * > forces ) { assert(Size(inverse_inertias) == Size(forces)); for(auto i = 0u; i < Size(inverse_inertias); ++i) { forces[i] += gravity / inverse_inertias[i].mass; } } void Physics::AddForces( EntityForces const & entity_forces, BodyEntityMapping const & mapping, Range<uint32_t const *> indices, Range<Math::Float3 * > forces ) { assert(Size(entity_forces.entity_ids) == Size(entity_forces.forces)); for(auto i = 0u; i < Size(entity_forces.entity_ids); ++i) { auto entity = entity_forces.entity_ids[i]; // TODO: First or all? auto body = First(Bodies(entity, mapping)); auto index = body.index; if(index < Size(indices)) { index = indices[index]; if(index < Size(forces)) { forces[index] += entity_forces.forces[i]; } } } } void Physics::ApplyMovement( Range<Orientation*> new_orientation, Range<Orientation const *> original_orientation, Range<Movement const*> movement, Range<Inertia const*> inverse_inertia, float const time_step ) { // I assume the ranges have the same length assert(Size(new_orientation) == Size(original_orientation)); assert(Size(new_orientation) == Size(movement)); assert(Size(new_orientation) == Size(inverse_inertia)); for(auto i = 0u; i < Size(new_orientation); ++i) { new_orientation[i] = UpdateOrientation(original_orientation[i], movement[i], inverse_inertia[i], time_step); } } void Physics::UpdateOrientations( Range<Orientation*> const orientation_range, Range<uint32_t const*> const indices, Range<Math::Float3 const *> const new_entity_positions, Range<EntityID const*> const position_entity_ids ) { assert(Size(new_entity_positions) == Size(position_entity_ids)); for(auto i : CreateIntegerRange(Size(new_entity_positions))) { auto const entity_id = position_entity_ids[i]; if(entity_id.index < Size(indices)) { auto const index = indices[entity_id.index]; if(index < Size(orientation_range)) { orientation_range[index].position = new_entity_positions[i]; } } } } void Physics::UpdateOrientations( Range<Orientation*> const orientation_range, Range<uint32_t const*> const body_to_element, BodyEntityMapping const & mapping, Range<Math::Float3 const *> const new_entity_positions, Range<EntityID const*> const position_entity_ids ) { assert(Size(new_entity_positions) == Size(position_entity_ids)); for(auto i : CreateIntegerRange(Size(new_entity_positions))) { auto const entity_id = position_entity_ids[i]; auto body_id = First(Bodies(entity_id, mapping)); if(body_id.index < Size(body_to_element)) { auto const index = body_to_element[body_id.index]; if(index < Size(orientation_range)) { orientation_range[index].position = new_entity_positions[i]; } } } } void Physics::UpdateOrientations( Range<Orientation*> const orientation_range, Range<uint32_t const*> const body_to_element, BodyEntityMapping const & mapping, Range<Math::Quaternion const *> const new_entity_rotations, Range<EntityID const*> const entity_ids ) { assert(Size(new_entity_rotations) == Size(entity_ids)); for(auto i : CreateIntegerRange(Size(new_entity_rotations))) { auto const entity_id = entity_ids[i]; auto body_id = First(Bodies(entity_id, mapping)); if(body_id.index < Size(body_to_element)) { auto const index = body_to_element[body_id.index]; if(index < Size(orientation_range)) { orientation_range[index].rotation = new_entity_rotations[i]; } } } } void Physics::UpdateOrientations( Range<Orientation*> const orientation_range, Range<uint32_t const*> const indices, Range<Math::Quaternion const *> const new_entity_rotations, Range<EntityID const*> const entity_ids ) { assert(Size(new_entity_rotations) == Size(entity_ids)); for(auto i : CreateIntegerRange(Size(new_entity_rotations))) { auto const entity_id = entity_ids[i]; if(entity_id.index < Size(indices)) { auto const index = indices[entity_id.index]; if(index < Size(orientation_range)) { orientation_range[index].rotation = new_entity_rotations[i]; } } } } void Physics::CorrectForCenterOfMassBackward( Range<Math::Float3 const *> center_of_mass, Range<Orientation *> orientations ) { assert(Size(center_of_mass) == Size(orientations)); if(IsEmpty(center_of_mass)) return; std::transform(begin(center_of_mass), end(center_of_mass), begin(orientations), begin(orientations), [] (Math::Float3 center_of_mass, Orientation orientation) { orientation.position -= Rotate(center_of_mass, orientation.rotation); return orientation; }); } void Physics::CorrectForCenterOfMassForward( Range<Math::Float3 const *> center_of_mass, Range<Orientation *> orientations ) { assert(Size(center_of_mass) == Size(orientations)); if(IsEmpty(center_of_mass)) return; std::transform(begin(center_of_mass), end(center_of_mass), begin(orientations), begin(orientations), [] (Math::Float3 center_of_mass, Orientation orientation) { orientation.position += Rotate(center_of_mass, orientation.rotation); return orientation; }); } void Physics::CorrectForCenterOfMassForward( Range<EntityID const *> ids, Range<uint32_t const *> entity_to_data, Range<Math::Float3 const *> center_of_mass, Range<Orientation const *> orientation, Range<Math::Float3 *> position ) { assert(Size(ids) == Size(position)); assert(Size(center_of_mass) == Size(orientation)); for(auto i = 0u; i < Size(ids); ++i) { auto index = entity_to_data[ids[i].index]; position[i] += Rotate(center_of_mass[index], orientation[index].rotation); } } void Physics::ApplyForces( Range<Movement const *> movements, Range<Force const *> forces, float const time_step, Range<Movement *> result_movements ) { assert(Size(movements) == Size(forces)); assert(Size(movements) == Size(result_movements)); for(auto i = 0u; i < Size(movements); ++i) { auto movement = movements[i]; movement.momentum += forces[i] * time_step; result_movements[i] = movement; } } std::vector<Movement> Physics::ApplyForces( std::vector<Movement> movements, std::vector<uint32_t> const & indices, std::vector<Force> const & forces, std::vector<EntityID> const & entity_ids, float const time_step ) { assert(forces.size() == entity_ids.size()); auto const size = forces.size(); for(size_t i = 0u; i < size; ++i) { auto const entity_id = entity_ids[i]; auto const movement_index = indices[entity_id.index]; movements[movement_index].momentum += forces[i] * time_step; } return movements; } void Physics::ApplyTorques( Range<Movement const *> movements, Range<uint32_t const *> indices, Range<Torque const *> torques, Range<EntityID const *> entity_ids, BodyEntityMapping const & mapping, float const time_step, Range<Movement *> result_movements ) { assert(Size(torques) == Size(entity_ids)); assert(Size(movements) == Size(result_movements)); for(auto i = 0u; i < Size(entity_ids); ++i) { auto entity_id = entity_ids[i]; // TODO: First or all? auto index = First(Bodies(entity_id, mapping)).index; auto movement_index = indices[index]; auto movement = movements[movement_index]; movement.angular_momentum += torques[i] * time_step; result_movements[movement_index] = movement; } } Math::Float3 Physics::AngularVelocityFromRotation( Math::Quaternion new_rotation, Math::Quaternion original_rotation, float time_step ) { auto diff = new_rotation * Conjugate(original_rotation); return ConditionalNormalize(GetAxis(diff)) * (GetAngle(diff) / time_step); } void Physics::UpdateVelocities( std::vector<Velocity>& velocities, std::vector<Math::Float3>& angular_velocities, std::vector<EntityID> & velocity_entity_ids, std::vector<uint32_t>& entity_to_element, Range<Orientation const * > orientations, Range<Orientation const * > previous_orientations, Range<EntityID const * > entity_ids, const float time_step ) { // Assuming orientations are in sync with entity_ids assert(Size(orientations) == Size(previous_orientations)); assert(Size(orientations) == Size(entity_ids)); for(auto i : CreateIntegerRange(Size(orientations))) { // Compare current and previous rotation auto offset = orientations[i].position - previous_orientations[i].position; // or - ? auto const current_rotation = orientations[i].rotation; auto const previous_rotation = previous_orientations[i].rotation; // Ignore if no movement if(Math::Equal(offset, Float3{0}, 0.001f) && Math::Equal(GetAngle(current_rotation), GetAngle(previous_rotation), 0.001f)) { continue; } auto const index = uint32_t(velocities.size()); auto entity_id = entity_ids[i]; AddIndexToIndices(entity_to_element, entity_id.index, index); velocity_entity_ids.push_back(entity_id); Velocity velocity = offset / time_step; velocities.push_back(velocity); auto angular_velocity = AngularVelocityFromRotation(current_rotation, previous_rotation, time_step); angular_velocities.push_back(angular_velocity); } } void Physics::UpdateVelocities( std::vector<Velocity>& velocities, std::vector<Math::Float3>& angular_velocities, std::vector<EntityID> & velocity_entity_ids, std::vector<uint32_t>& entity_to_element, Range<Orientation const * > orientations, Range<Orientation const * > previous_orientations, Range<BodyID const * > body_ids, BodyEntityMapping const & mapping, const float time_step ) { // Assuming orientations are in sync with entity_ids assert(Size(orientations) == Size(previous_orientations)); assert(Size(orientations) == Size(body_ids)); for(auto i : CreateIntegerRange(Size(orientations))) { // Compare current and previous rotation auto offset = orientations[i].position - previous_orientations[i].position; // or - ? auto const current_rotation = orientations[i].rotation; auto const previous_rotation = previous_orientations[i].rotation; // Ignore if no movement if(Math::Equal(offset, Float3{0}, 0.001f) && Math::Equal(GetAngle(current_rotation), GetAngle(previous_rotation), 0.001f)) { continue; } auto const index = uint32_t(velocities.size()); auto const entity_id = Entity(body_ids[i], mapping); // only process the first body if(First(Bodies(entity_id, mapping)) == body_ids[i]) { AddIndexToIndices(entity_to_element, entity_id.index, index); velocity_entity_ids.push_back(entity_id); Velocity velocity = offset / time_step; velocities.push_back(velocity); auto angular_velocity = AngularVelocityFromRotation(current_rotation, previous_rotation, time_step); angular_velocities.push_back(angular_velocity); } } } void Physics::UpdateVelocities( std::vector<Velocity>& velocities, std::vector<Math::Float3>& angular_velocities, std::vector<EntityID> & velocity_entity_ids, std::vector<uint32_t>& entity_to_elements, Range<Movement const*> movements, Range<Inertia const *> inverse_inertia, Range<BodyID const *> body_ids, BodyEntityMapping const & mapping ) { for(auto i = 0u; i < Size(movements); ++i) { auto const & movement = movements[i]; if(Math::Equal(movement.momentum, Float3{0}, 0.001f) && Math::Equal(movement.angular_momentum, Float3{0}, 0.001f)) { continue; } auto const index = uint32_t(velocities.size()); auto const entity_id = Entity(body_ids[i], mapping); // only process the first body if(First(Bodies(entity_id, mapping)) == body_ids[i]) { AddIndexToIndices(entity_to_elements, entity_id.index, index); velocity_entity_ids.push_back(entity_id); velocities.emplace_back(movement.momentum * inverse_inertia[i].mass); angular_velocities.emplace_back(movement.angular_momentum * inverse_inertia[i].moment); } } } Math::Float3 Physics::ImpulseFromMovement( Movement const & movement, Math::Float3 const & position ) { // return movement.momentum + Cross(movement.angular_momentum, position); using namespace Math::SSE; auto p = SSEFromFloat3(position); auto momentum = LoadFloat32Vector(begin(movement.momentum)); auto angular_momentum = SSEFromFloat3(movement.angular_momentum); return Float3FromSSE(SSE::Add(momentum, Cross(angular_momentum, p))); } Movement Physics::MovementFromImpulse( Math::Float3 const impulse, Math::Float3 const position ) { return{impulse, Cross(position, impulse)}; } Movement Physics::ApplyImpulse( Movement movement, Math::Float3 const impulse, Math::Float3 const position ) { movement.momentum += impulse; movement.angular_momentum += Cross(position, impulse); return movement; } void Physics::AddMovements( Range<Movement const *> movements1, Range<Movement *> movements2, float const angular_fraction ) { assert(Size(movements1) == Size(movements2)); if(IsEmpty(movements1)) return; std::transform(begin(movements2), end(movements2), begin(movements1), begin(movements2), [angular_fraction](Movement a, Movement b) { a.momentum += b.momentum; a.angular_momentum = a.angular_momentum * angular_fraction + b.angular_momentum; return a; }); } // position has to be in body coordinates // Math::Float3 CalculateVelocity( Movement const & movement, Inertia const & inverse_inertia, Math::Float3 const position ) // { // auto linear = inverse_inertia.mass * movement.momentum; // [m s-¹] // auto angular_velocity = inverse_inertia.moment * movement.angular_momentum; // [s-¹] // auto rotational = Cross(angular_velocity, position); // [m s-¹] // return linear + rotational; // } // position has to be in body coordinates Math::Float3 Physics::CalculateVelocity( Movement const & movement, Inertia const & inverse_inertia, Math::Float3 const position ) { using namespace Math; using namespace SSE; auto linear = Multiply(SetAll(inverse_inertia.mass), SSEFromFloat3(movement.momentum)); // [m s-¹] FloatMatrix moment = SSEFromFloat3x3(inverse_inertia.moment); auto angular_velocity = Multiply3D(moment, SSEFromFloat3(movement.angular_momentum)); // [s-¹] auto rotational = Cross(angular_velocity, SSEFromFloat3(position)); // [m s-¹] return Float3FromSSE(SSE::Add(linear, rotational)); } float Physics::CombineRestitutionFactors( float factor1, float factor2 ) { return Math::Sqrt(factor1 * factor2); } float Physics::CalculateInverseEffectiveMass( Math::Float3 relative_position, Math::Float3 normal, Inertia const & inverse_inertia ) { auto torque = Cross(relative_position, normal); // [m] auto angular_component = inverse_inertia.moment * torque; // [kg-¹ m-¹] // triple scalar product //auto angular_velocity = Cross( angular_component, relative_position ); //auto angular_inertia_factor = Dot( normal, angular_velocity ); // can also write as Dot( angular_component, Cross( relative_position, normal ) ) -> Dot( angular_component, torque) auto angular_inertia_factor = Dot(angular_component, torque); // [kg-¹] return angular_inertia_factor + inverse_inertia.mass; // [kg-¹] }
63eeeeeb13566fb2408965edca0d78a68956fc00
aeeb9442e954f6955dd832637bd4991503c20377
/src/au_uav_ros/src/planeObject.cpp
aa15ae0ebeee1a9f28f2d483afce47b47d4b5b60
[]
no_license
Idianale/au_uav_pkg
8ad46b04c72e320bc58333ae5371ef58188635b9
e38b06eef33d34c96a2d32ea2f6aed735a0d73d8
refs/heads/master
2021-05-31T22:46:18.812867
2016-06-07T16:10:25
2016-06-07T16:10:25
null
0
0
null
null
null
null
UTF-8
C++
false
false
12,804
cpp
planeObject.cpp
#include "au_uav_ros/planeObject.h" using namespace au_uav_ros; /* Implementation of the default constructor: Member variables are set to zero */ PlaneObject::PlaneObject(void) { this->id = 0; this->currentLoc.altitude = 0.0; this->currentLoc.latitude = 0.0; this->currentLoc.longitude = 0.0; this->previousLoc.altitude = 0.0; this->previousLoc.latitude = 0.0; this->previousLoc.longitude = 0.0; this->targetBearing = 0.0; this->currentBearing = 0.0; this->distanceToDestination = 0.0; this->speed = 0.0; this->lastUpdateTime = ros::Time::now().toSec(); this->currentWaypointIndex = 0; this->currentDest = INVALID_WP; this->MAX_NUMBER_OF_WAYPOINTS = 0; } PlaneObject::PlaneObject(struct waypoint wp) { this->id = wp.planeID; this->currentLoc.altitude = 0.0; this->currentLoc.latitude = 0.0; this->currentLoc.longitude = 0.0; this->previousLoc.altitude = 0.0; this->previousLoc.latitude = 0.0; this->previousLoc.longitude = 0.0; this->targetBearing = 0.0; this->currentBearing = 0.0; this->distanceToDestination = 0.0; this->speed = 0.0; this->lastUpdateTime = ros::Time::now().toSec(); this->normalPath.push_back(wp); this->currentWaypointIndex = 0; this->currentDest = normalPath.front(); this->MAX_NUMBER_OF_WAYPOINTS = 1; } PlaneObject::PlaneObject(int _id) { this->id = _id; } /* Explicit value constructor using Telemetry */ PlaneObject::PlaneObject(const Telemetry &msg) { this->id = msg.planeID; this->currentLoc.altitude = msg.currentAltitude; this->currentLoc.latitude = msg.currentLatitude; this->currentLoc.longitude = msg.currentLongitude; this->previousLoc.altitude = 0.0; this->previousLoc.latitude = 0.0; this->previousLoc.longitude = 0.0; this->targetBearing = msg.targetBearing; this->currentBearing = 0.0; this->distanceToDestination = 0.0; this->speed = msg.groundSpeed; waypoint wp; wp.latitude = msg.destLatitude; wp.longitude = msg.destLongitude; wp.altitude = msg.destAltitude; this->normalPath.push_back(wp); this->currentDest = normalPath.front(); this->lastUpdateTime = ros::Time::now().toSec(); this->currentWaypointIndex = 0; } /* mutator functions to update member variables */ void PlaneObject::setID(int id){ this->id = id; } void PlaneObject::setPreviousLoc(double lat, double lon, double alt) { this->previousLoc.latitude = lat; this->previousLoc.longitude = lon; this->previousLoc.altitude = alt; } void PlaneObject::setCurrentLoc(double lat, double lon, double alt) { this->currentLoc.latitude = lat; this->currentLoc.longitude = lon; this->currentLoc.altitude = alt; } void PlaneObject::setCurrentDest(double lat, double lon, double alt) { this->currentDest.latitude = lat; this->currentDest.longitude = lon; this->currentDest.altitude = alt; } void PlaneObject::setTargetBearing(double tBearing) { this->targetBearing = tBearing; } void PlaneObject::setCurrentBearing(double cBearing) { this->currentBearing = cBearing; } void PlaneObject::setSpeed(double speed) { this->speed = speed; } void PlaneObject::updateTime(void) { this->lastUpdateTime = ros::Time::now().toSec(); } //used to keep up with wp index for real UAVs void PlaneObject::incrementCurrentWaypointIndex(void) { this->currentWaypointIndex++; } void PlaneObject::populatePlaneInfo(const Telemetry &msg) { //Update previous and current position this->setPreviousLoc(this->currentLoc.latitude, this->currentLoc.longitude, this->currentLoc.altitude); this->setCurrentLoc(msg.currentLatitude, msg.currentLongitude, msg.currentAltitude); this->setCurrentDest(msg.destLatitude, msg.destLongitude, msg.destAltitude); // Changed from cardinal to cartesian. // TODO: Get rid of those DELTA_LXX_TO_METERS constants double numerator = (this->currentLoc.latitude - this->previousLoc.latitude); double denominator = (this->currentLoc.longitude - this->previousLoc.longitude); double angle = atan2(numerator*DELTA_LAT_TO_METERS,denominator*DELTA_LON_TO_METERS)*180/PI; if (numerator != 0 || denominator != 0) { this->setCurrentBearing(angle); } else { this->setCurrentBearing(0); } // Update everything else this->setTargetBearing(msg.targetBearing); this->setSpeed(msg.groundSpeed); this->updateTime(); this->currentWaypointIndex = normalPath.size() % MAX_NUMBER_OF_WAYPOINTS; } bool PlaneObject::isWaypointHit(const Telemetry &msg, Command &newCommand) { //this bool is set true only if there is something available to be sent to the UAV bool isCommand = false; //execute logic to see if we have hit a waypoint //check to see if distanceToDest is < than WPThreshold if(this->currentDest != INVALID_WP && msg.distanceToDestination > -WAYPOINT_THRESHOLD && msg.distanceToDestination < WAYPOINT_THRESHOLD) { //ROS_ERROR("Plane %d hit a waypoint", this->id); //we've hit a waypoint, is it a normalWP or an avoidanceWP? if (distanceBetween(this->currentDest, normalPath.front()) > -WAYPOINT_THRESHOLD && distanceBetween(this->currentDest, normalPath.front()) < WAYPOINT_THRESHOLD) { //we've hit a normal waypoint, but only pop it if we have more wp's to send //i.e. don't pop the last wp //if (this->id == 24 && normalPath.size() < 8) { // ROS_ERROR("%d", normalPath.size()); //} if (normalPath.size() > 1) { normalPath.pop_front(); isCommand = true; } } else { //we've hit an avoidanceWP, so continue the mission isCommand = true; } } //DIRTY AVOIDANCE FIX: simply pop the avoidance waypoint immediately once we receive the telemetry message following when the avoidance WP was sent. // else { // if (distanceBetween(this->currentDest, normalPath.front()) < -WAYPOINT_THRESHOLD && // distanceBetween(this->currentDest, normalPath.front()) > WAYPOINT_THRESHOLD) { //we're going to an avoidance WP //isCommand = true; //} //if we have a command to process, process it if(isCommand) { if (!normalPath.empty()) { newCommand.commandID = COMMAND_NORMAL_WP; newCommand.commandHeader.stamp = ros::Time::now(); newCommand.planeID = id; newCommand.latitude = normalPath.front().latitude; newCommand.longitude = normalPath.front().longitude; newCommand.altitude = normalPath.front().altitude; return true; } } else { //if we get here, then nothing to avoid and no new wps need to be sent for normal path return false; } } bool PlaneObject::update(const Telemetry &msg, Command &cmd) { //keep this planeObject up-to-date so store telemetry info populatePlaneInfo(msg); return isWaypointHit(msg, cmd); } /* accessor functions */ int PlaneObject::getID(void) const { return this->id; } int PlaneObject::getCurrentWaypointIndex(void) { return this->currentWaypointIndex; } waypoint PlaneObject::getPreviousLoc(void) const { return this->previousLoc; } waypoint PlaneObject::getCurrentLoc(void) const { return this->currentLoc; } double PlaneObject::getTargetBearing(void) const { return this->targetBearing; } double PlaneObject::getCurrentBearing(void) const { return this->currentBearing; } double PlaneObject::getSpeed(void) const { return this->speed; } double PlaneObject::getLastUpdateTime(void) const { return this->lastUpdateTime; } waypoint PlaneObject::getDestination(void) const { //if (!plannedPath.empty()) { // return plannedPath.front(); //} else if (currentDest != INVALID_WP) { return currentDest; } else { return normalPath.front(); } } double PlaneObject::getSimSpeed(void) const { return 0; } /* Find distance between this plane and another plane, returns in meters */ double PlaneObject::findDistance(const PlaneObject& plane) const { return this->findDistance(plane.currentLoc.latitude, plane.currentLoc.longitude); } /* Find distance between this plane and another pair of coordinates, returns value in meters */ double PlaneObject::findDistance(double lat2, double lon2) const { double xdiff = (lon2 - this->currentLoc.longitude)*DELTA_LON_TO_METERS; double ydiff = (lat2 - this->currentLoc.latitude)*DELTA_LAT_TO_METERS; return sqrt(pow(xdiff, 2) + pow(ydiff, 2)); } /* Find Cartesian angle between this plane and another plane, using this plane as the origin */ double PlaneObject::findAngle(const PlaneObject& plane) const { return this->findAngle(plane.currentLoc.latitude, plane.currentLoc.longitude); } /* Find Cartesian angle between this plane and another plane's latitude/longitude using this plane as the origin */ double PlaneObject::findAngle(double lat2, double lon2) const { double xdiff = (lon2 - this->currentLoc.longitude)*DELTA_LON_TO_METERS; double ydiff = (lat2 - this->currentLoc.latitude)*DELTA_LAT_TO_METERS; return atan2(ydiff, xdiff); } PlaneObject& PlaneObject::operator=(const PlaneObject& plane) { this->id = plane.id; this->currentLoc.altitude = plane.currentLoc.altitude; this->currentLoc.latitude = plane.currentLoc.latitude; this->currentLoc.longitude = plane.currentLoc.longitude; this->previousLoc.altitude = plane.previousLoc.altitude; this->previousLoc.latitude = plane.previousLoc.latitude; this->previousLoc.longitude = plane.previousLoc.longitude; //this->plannedPath = plane.plannedPath; this->normalPath = plane.normalPath; this->targetBearing = plane.targetBearing; this->currentBearing = plane.currentBearing; this->speed = plane.speed; this->lastUpdateTime = plane.lastUpdateTime; return *this; } /* void PlaneObject::setPlannedPath(std::vector<waypoint> path) { plannedPath.clear(); plannedPath.insert(plannedPath.begin(), path.begin(), path.end()); } */ void PlaneObject::addNormalWp(struct au_uav_ros::waypoint wp) { normalPath.push_back(wp); if (normalPath.size() > this->MAX_NUMBER_OF_WAYPOINTS) MAX_NUMBER_OF_WAYPOINTS = normalPath.size(); } void PlaneObject::addAvoidanceWp(struct au_uav_ros::waypoint wp) { //ROS_ERROR("ID#%d (called after ca.avoid) d2d: %f",wp.planeID, distanceBetween(this->currentLoc, wp)); //this->currentDest = wp; } void PlaneObject::removeNormalWp(struct au_uav_ros::waypoint wp) { std::list<waypoint>::iterator i; for (i = normalPath.begin(); i != normalPath.end(); i++) { if (wp == *i) { break; } } if (i != normalPath.end()) { normalPath.erase(i); } else { ROS_ERROR("Waypoint not found"); } } Command PlaneObject::getPriorityCommand(void) { //start with defaults Command ret; ret.planeID = -1; ret.latitude = -1000; ret.longitude = -1000; ret.altitude = -1000; //check avoidance queue if(currentDest != INVALID_WP) { //we have an avoidance point, get that one ret.planeID = this->id; ret.latitude = currentDest.latitude; ret.longitude = currentDest.longitude; ret.altitude = currentDest.altitude; if (currentDest == normalPath.front()) ret.commandID = COMMAND_NORMAL_WP; else ret.commandID = COMMAND_AVOID_WP; } // else if (!plannedPath.empty()) // { // //we have a point from the planning algorithm // ret.planeID = this->id; // ret.latitude = plannedPath.front().latitude; // ret.longitude = plannedPath.front().longitude; // ret.altitude = plannedPath.front().altitude; // ret.commandID = COMMAND_AVOID_WP; // } else if (!normalPath.empty()) { //we have a normal path point at least, fill it out ret.planeID = this->id; ret.latitude = normalPath.front().latitude; ret.longitude = normalPath.front().longitude; ret.altitude = normalPath.front().altitude; ret.commandID = COMMAND_NORMAL_WP; currentDest = normalPath.front(); } //fill out our header and return this bad boy ret.commandHeader.stamp = ros::Time::now(); return ret; } /* //user for distributed CA std::vector<waypoint> PlaneObject::getNormalPath(void) { std::vector<waypoint> allWaypoints; // md // Something in A* code causes Coordinator node to crash // if it doesn't get any waypoints if (normalPath.size() == 0) { ROS_ERROR("No normal waypoints! Adding current location..."); normalPath.push_back(currentLoc); } allWaypoints.reserve(normalPath.size()); allWaypoints.insert(allWaypoints.begin(), normalPath.begin(), normalPath.end()); return allWaypoints; } */
5a04945e78fd2ec838b65bc1ec1c91005d85c845
46bf6fc69231692b467f50eba2299db7f1784ace
/Proj/hfview_facade.cpp
f2e1b2ab62fbf0ca55cd68711334a800ecc56392
[]
no_license
RabbitChenc/crasherror
5080c6629659a04721e27a04a5100d982c264ff6
2b3c589f00e60fc32b0715d795d6ac5070126113
refs/heads/master
2022-09-17T13:19:21.198554
2020-06-03T09:03:28
2020-06-03T09:03:28
269,039,710
0
0
null
null
null
null
UTF-8
C++
false
false
347
cpp
hfview_facade.cpp
#include "hfview_facade.h" #include <QDebug> //外观类的处理 HFViewFacade::HFViewFacade(QWidget *parent):QWidget(parent) { qDebug()<<"控件外观基类的构造函数"; } HFViewFacade::~HFViewFacade() { qDebug()<<"控件外观基类的西沟函数"; } HFviewFacadeAttrs& HFViewFacade::vistViewAttri() { return mViewAttri; }
afd49d3fd02d44e53d417a404d0810a5dca9bb75
d8ac31ea897f5dee083e0823a78f53d7b61ddd15
/src/compress/Gststreamercontrl.cpp
a16a52a3e61f62e4c2d5b1d28f954881b3205a9d
[]
no_license
tianxiejack/qr_pro_360pano_main
51a7974b569747b2baf8d167c3e4aa5c7eeac9b7
d924573b25e4f316407d6da9a1e90f2dfc38bc85
refs/heads/master
2020-06-02T23:46:32.783513
2019-11-11T01:49:57
2019-11-11T01:49:57
191,347,495
1
1
null
null
null
null
UTF-8
C++
false
false
2,083
cpp
Gststreamercontrl.cpp
#include "Gststreamercontrl.hpp" #include "videorecord.hpp" #include "Queuebuffer.hpp" #include "debug.h" extern int gst_videnc_create(void); extern int gst_videnc_enable(int bEnable); extern int gst_shotenc_record(void); GstreaemerContrl* GstreaemerContrl::instance=NULL; GstreaemerContrl::GstreaemerContrl() { } GstreaemerContrl::~GstreaemerContrl() { } void GstreaemerContrl::create() { vedioing = 0; // HDv4l_cam::read_frame push data-gst enc-gst save mp4 gstreamer_mp4 = new SaveVideoByGST(); gstreamer_mp4->init(); // Queue::DISPALYTORTP push data-gst enc-live555 rtsp gst_videnc_create(); } void GstreaemerContrl::gstputmux(cv::Mat src,Privatedata *privatedata) { if(should_video()) { vedioing = 1; gstreamer_mp4->SaveAsMp4(&src); save_gyro_data(privatedata); set_data_cnt(get_data_cnt() + 1); } else { stop_video(); } } GstreaemerContrl*GstreaemerContrl::getinstance() { if(instance==NULL) instance=new GstreaemerContrl(); return instance; } int GstreaemerContrl::should_video() { VideoRecord::getinstance()->heldrecord(); if(VideoRecord::getinstance()->getrecordflag()) { return 1; } else { return 0; } } int GstreaemerContrl::stop_video() { if(vedioing == 1) { if(get_video_cnt()>0) { remove_last_video(); //gstreamer_mp4->SetEos(); set_video_cnt(0); } set_data_cnt(0); vedioing = 0; } } int GstreaemerContrl::save_gyro_data(Privatedata *privatedata) { VideoRecord::getinstance()->mydata.write(privatedata->event, privatedata->gyrox, privatedata->gyroy, privatedata->gyroz); } void GstreaemerContrl::remove_last_video() { char buf[sizeof(filename_bak) + 16]={0}; sprintf(buf,"sudo rm %s",filename_bak); system(buf); VideoRecord::getinstance()->mydata.close(); sprintf(buf,"%s",filename_gyro_bak); remove(buf); } void GstreaemerContrl::setLiveVideo(int bEnable) { gst_videnc_enable(bEnable); } void GstreaemerContrl::setLivePhoto(void) { gst_shotenc_record(); }
05a646fa40be353a153e4d82247c1c0c8453f5f7
0c6ad83017727a71da52800e5d648eaaa646f43b
/Src/Engine/Public/Base/Allocators/ueFixedBlockAllocator.h
98c80ec90847567cb7c8171bf801cc1c98168b62
[]
no_license
macieks/uberengine
4a7f707d7dad226bed172ecf9173ab72e7c37c71
090a5e4cf160da579f2ea46b839ece8e1928c724
refs/heads/master
2021-06-06T05:14:16.729673
2018-06-20T21:21:43
2018-06-20T21:21:43
18,791,692
3
0
null
null
null
null
UTF-8
C++
false
false
559
h
ueFixedBlockAllocator.h
#ifndef UE_FIXED_BLOCK_ALLOCATOR_H #define UE_FIXED_BLOCK_ALLOCATOR_H #include "Base/Containers/ueGenericPool.h" //! Fixed block size allocator; super fast and zero per-allocation overhead class ueFixedBlockAllocator : public ueAllocator { public: static ueSize CalcMemReq(ueSize blockSize, u32 numBlocks, ueSize blockAlignment); void InitMem(void* memory, ueSize memorySize, ueSize blockSize, u32 numBlocks, ueSize blockAlignment); UE_DECLARE_ALLOC_FUNCS(ueFixedBlockAllocator) private: ueGenericPool m_pool; }; #endif // UE_FIXED_BLOCK_ALLOCATOR_H
a1d4c4d7b26ec882e563121b4f230cc30f882494
9e36aa7bb2abcf133aa53eb965a0096bb9513487
/11960 - Divisor Game.cpp
d05a9292e3ad45052f42183e1692710bd645ca2a
[]
no_license
Nil0ofar/UVa_Solutions
c260f913e0c723ddfab36119fc002669a8b96b53
7cd4e83967a1cc6e49df7ea971ca8fe9e6057fa0
refs/heads/master
2023-02-21T13:15:40.432746
2021-01-20T16:39:37
2021-01-20T16:39:37
331,358,652
0
0
null
null
null
null
UTF-8
C++
false
false
1,096
cpp
11960 - Divisor Game.cpp
#include<bits/stdc++.h> #include <ext/pb_ds/detail/standard_policies.hpp> #include <ext/pb_ds/assoc_container.hpp> #include <ext/pb_ds/tree_policy.hpp> using namespace std; using namespace __gnu_pbds; #define fi first #define se second #define ll long long #define pll pair<ll , ll> #define pii pair<int , int> #define pbl pair<bool , ll> #define pb push_back #define pdd pair<double , double> #define N 1000000 + 5 #define mod 1000000007 #define Base 3002 #define double long double #define ret(x) return cout << x << endl , 0 #define ordered_set tree<pll, null_type, less<pll>, rb_tree_tag,tree_order_statistics_node_update> #define pci pair<char , int> #define double long double int cnt[N] ; int ans[N] ; int main(){ ios_base :: sync_with_stdio(false); for(int i = 1 ; i < N ; i++){ for(int j = i ; j < N ; j += i) cnt[j]++; } for(int i = 1 ; i < N ; i++) ans[i] = (cnt[ans[i - 1]] <= cnt[i] ? i : ans[i - 1]); int t; cin >> t; while(t--){ int n ; cin >> n; cout << ans[n] << endl; } return 0; }
3af2912a195d190de589e0832641cca9a095c213
e8cecef34c5c54b11f6fc007ed21e1e012384bfb
/Chapter15/QueryResult.h
7af71947131951a404546eebf64d25efb0c8ab81
[]
no_license
cdh981009/CppPrimer
1eac8c4bf59467b949892dd401bf1903d1ee80cb
f47c45bb5c0758b0b2dc8a230ad7b2d62891cb86
refs/heads/master
2022-11-20T01:35:16.020830
2020-07-16T11:56:47
2020-07-16T11:56:47
259,614,307
0
0
null
null
null
null
UTF-8
C++
false
false
744
h
QueryResult.h
#pragma once #include <iostream> #include "TextQuery.h" class QueryResult { friend std::ostream& operator<<(std::ostream&, const QueryResult&); public: using line_no = TextQuery::line_no; QueryResult(std::string s, std::shared_ptr<std::set<line_no>> p, std::shared_ptr<std::vector<std::string>> f): sought(s), lines(p), file(f) { } std::set<line_no>::iterator begin() { return lines->begin(); } std::set<line_no>::iterator end() { return lines->end(); } std::shared_ptr<std::vector<std::string>> get_file() { return file; } private: std::string sought; std::shared_ptr<std::set<line_no>> lines; std::shared_ptr<std::vector<std::string>> file; }; std::ostream& operator<<(std::ostream& os, const QueryResult& qr);
630763997db037e85a0e6a0fbd8d0fa1cf68ab0a
6d4f619664992a8a752a5e1e82e9ddb46bd805b1
/SegImage.h
cff3a249ff64cd1e6f8262a44c543e0164f97861
[]
no_license
Earlvik/ImageSegmentor
19dfb9e9e75c39a8e5736256a7ccd5a1293c7df3
3a1b8174f0c4b07e0aed260e2e258f68abafd181
refs/heads/master
2021-01-01T04:50:13.661714
2016-05-14T16:31:09
2016-05-14T16:31:09
58,818,239
0
0
null
null
null
null
UTF-8
C++
false
false
1,524
h
SegImage.h
#pragma once class SegImage { public: SegImage(int numRows, int numCols, int numSlices, bool init); ~SegImage(); void setVoxel(int x, int y, int z, unsigned char value) const; unsigned char getVoxel(int x, int y, int z) const; void getSize(int &x, int &y, int &z) const; // Get a sub-image // ulc - upper left closest voxel, ltf - lower right farthest voxel of an image region SegImage* getRegion(int ulcx, int ulcy, int lrfx, int lrfy, int ulcz, int lrfz) const; static SegImage* deserialize(char* filename); void serialize(char* filename) const; void saveSlice(int slice, const char* filename) const; void saveSeries(const char* name) const; void threshold(unsigned char level); bool inNarrowBounds(int x, int y, int z) const; int getVolume(); SegImage* copy() const; private: bool inBounds(int x, int y, int z) const; int rows, cols, slices, volume; unsigned char ***values; }; //#pragma pack( push, 2 ) // //struct BITMAPFILEHEADER //{ // unsigned short bfType; // unsigned int bfSize; // unsigned short bfReserved1; // unsigned short bfReserved2; // unsigned int bfOffBits; //}; // //struct BITMAPINFOHEADER //{ // unsigned int biSize; // int biWidth; // int biHeight; // unsigned short biPlanes; // unsigned short biBitCount; // unsigned int biCompression; // unsigned int biSizeImage; // int biXPelsPerMeter; // int biYPelsPerMeter; // unsigned int biClrUsed; // unsigned int biClrImportant; //}; // //#pragma pack()
a7faa440da2c8fe1f2283d1e158fb84605c5bd61
403c3ac652d9a3cb9dcfe66afad9b0f3027cdbd3
/codes/Registration.cpp
e9b674d52455574bdf5e8c44c45d82e84e22e258
[]
no_license
alex10151/seg-reg
e32f7b2b2ce076fc848c66eafa6728229a960ffd
7eda029980209ea6d010b689c30e11e6e6df46ec
refs/heads/master
2020-04-07T06:41:51.642235
2018-12-03T07:07:47
2018-12-03T07:07:47
158,147,214
0
0
null
2018-12-03T07:07:48
2018-11-19T01:52:42
C++
UTF-8
C++
false
false
4,197
cpp
Registration.cpp
#include"Registration.h" #include"PreDef.h" #include"CmdIterationUpdate.h" #include"RegistrationInterfaceCommand.h" using namespace predef; int OptimizeStepPipe(FixedImageType::Pointer fix,MovingImageType::Pointer mov, RegistrationType::Pointer registration) { //registration components def TransformType::Pointer transform = TransformType::New(); OptimizerType::Pointer optimizer = OptimizerType::New(); InterpolatorType::Pointer interpolator = InterpolatorType::New(); MetricType::Pointer metric = MetricType::New(); FixedImagePyramidType::Pointer fixedImagePyramid = FixedImagePyramidType::New(); MovingImagePyramidType::Pointer movingImagePyramid = MovingImagePyramidType::New(); registration->SetOptimizer(optimizer); registration->SetTransform(transform); registration->SetInterpolator(interpolator); registration->SetMetric(metric); registration->SetFixedImagePyramid(fixedImagePyramid); registration->SetMovingImagePyramid(movingImagePyramid); //cast inputs to internal type FixedCastFilterType::Pointer fixedCaster = FixedCastFilterType::New(); MovingCastFilterType::Pointer movingCaster = MovingCastFilterType::New(); fixedCaster->SetInput(fix); movingCaster->SetInput(mov); registration->SetFixedImage(fixedCaster->GetOutput()); registration->SetMovingImage(movingCaster->GetOutput()); fixedCaster->Update(); movingCaster->Update(); //set registration params registration->SetFixedImageRegion(fixedCaster->GetOutput()->GetLargestPossibleRegion()); //ParametersType initialParameters(transform->GetNumberOfParameters()); //for (unsigned int i = 0; i < transform->GetNumberOfParameters(); i++) // initialParameters[i] = 1; TransformInitializeType::Pointer initializer = TransformInitializeType::New(); initializer->SetTransform(transform); initializer->SetFixedImage(fixedCaster->GetOutput()); initializer->SetMovingImage(movingCaster->GetOutput()); initializer->MomentsOn(); initializer->InitializeTransform(); //registration->SetInitialTransformParameters(initialParameters); registration->SetInitialTransformParameters(transform->GetParameters()); metric->SetNumberOfSpatialSamples(fix->GetLargestPossibleRegion().GetNumberOfPixels()*0.001); metric->SetNumberOfHistogramBins(NB_OF_BINS); metric->ReinitializeSeed(REINIT_SEED); metric->SetUseExplicitPDFDerivatives(USE_PDF_DERIVATIVE); optimizer->SetNumberOfIterations(NB_ITERATION); optimizer->SetRelaxationFactor(RELAX_FACTOR); CommandIterationUpdate::Pointer observer = CommandIterationUpdate::New(); optimizer->AddObserver(itk::IterationEvent(), observer); RegInterfaceCommand<RegistrationType>::Pointer command = RegInterfaceCommand<RegistrationType>::New(); registration->AddObserver(itk::IterationEvent(), command); registration->SetNumberOfLevels(NB_OF_LEVELS); try { cout << "===============Start registration:" << endl; registration->Update(); std::cout << "Optimizer stop condition: " << registration->GetOptimizer()->GetStopConditionDescription() << std::endl; } catch (itk::ExceptionObject & err) { std::cout << "ExceptionObject caught !" << std::endl; std::cout << err << std::endl; return EXIT_FAILURE; } return EXIT_SUCCESS; } int ResamplePipe(RegistrationType::Pointer registration,FixedImageType::Pointer fix,MovingImageType::Pointer mov, ResampleFilterType::Pointer resample) { //resample process TransformType::Pointer finalTransform =TransformType::New(); finalTransform->SetParameters(registration->GetLastTransformParameters()); finalTransform->SetFixedParameters(registration->GetTransform()->GetFixedParameters()); resample->SetTransform(finalTransform); resample->SetInput(mov); resample->SetSize(fix->GetLargestPossibleRegion().GetSize()); resample->SetOutputOrigin(fix->GetOrigin()); resample->SetOutputSpacing(fix->GetSpacing()); resample->SetOutputDirection(fix->GetDirection()); resample->SetDefaultPixelValue(BACKGROUD_GRAY_LEVEL); try { cout << "===============Start resample:" << endl; resample->Update(); } catch (itk::ExceptionObject & err) { std::cout << "ExceptionObject caught !" << std::endl; std::cout << err << std::endl; return EXIT_FAILURE; } return EXIT_SUCCESS; }
eda0713e5e9b54aaa48235fc4fdf8eb13ae82f11
30e528120996eac586e7276e9474d0a831fc82ad
/src/main.cpp
c7aecd1c827733b9f76c66a8f2653430bd46c7ee
[]
no_license
FotiadisM/ecosystem-simulation
8c26d38b1d38e2cbf50d679556b540e54e3888d7
5faa52a797fd47c0e1dd622698c6faf269dcbd59
refs/heads/master
2020-04-22T21:39:49.172980
2019-10-17T10:20:22
2019-10-17T10:20:22
170,680,174
0
0
null
null
null
null
UTF-8
C++
false
false
516
cpp
main.cpp
#include <iostream> #include <cstdlib> #include <ctime> #include <string> #include "../include/classes.h" using namespace std; int main(int argc, char const *argv[]) { string numOfDays; ecosystem* myEcosystem; srand((int)time(NULL)); myEcosystem = new ecosystem(10, 180); // myEcosystem->PrintMap(); cout << "Enter the number of days you wish the program to run for!" << endl; getline(cin, numOfDays); myEcosystem->RunEcosystem(atoi(numOfDays.c_str())); return 0; }
8a00bed312bc33b71b674a2deccfefb82077ec3c
2e27b44b1e0ef1e0a7a6b83392481d2094e4dc80
/automated-tests/src/dali-toolkit/utc-Dali-ToggleButton.cpp
6d3424ebfd20986b1d34e3a35c6e1c565d80e358
[ "Apache-2.0", "BSD-3-Clause" ]
permissive
elishateng/dali-toolkit
1c3ce96eb204307ed48d2ede853fd2314a472ef8
3cc49ee528659b670f46b43be6a9de552f282724
refs/heads/master
2023-04-20T01:18:39.054662
2021-05-21T09:26:13
2021-05-21T09:26:13
null
0
0
null
null
null
null
UTF-8
C++
false
false
13,473
cpp
utc-Dali-ToggleButton.cpp
/* * Copyright (c) 2020 Samsung Electronics Co., Ltd. * * 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 <iostream> #include <stdlib.h> #include <dali-toolkit-test-suite-utils.h> #include <dali-toolkit/dali-toolkit.h> #include <dali/integration-api/events/touch-event-integ.h> #include <dali-toolkit/devel-api/controls/buttons/toggle-button.h> using namespace Dali; using namespace Dali::Toolkit; void dali_toggle_button_startup(void) { test_return_value = TET_UNDEF; } void dali_toggle_button_cleanup(void) { test_return_value = TET_PASS; } namespace { static const char* TEST_IMAGE_ONE = TEST_RESOURCE_DIR "/icon-delete.png"; static const char* TEST_IMAGE_TWO = TEST_RESOURCE_DIR "/icon-edit.png"; static const char* TEST_IMAGE_THREE = TEST_RESOURCE_DIR "/popup_tail_down.png"; static const char* TEST_IMAGE_FOUR = TEST_RESOURCE_DIR "/popup_tail_up.png"; static const Vector2 INSIDE_TOUCH_POINT_POSITON = Vector2( 240, 400 ); static const Vector3 BUTTON_POSITON_TO_GET_INSIDE_TOUCH_EVENTS = Vector3( 200, 360, 0 ); static const Size BUTTON_SIZE_TO_GET_INSIDE_TOUCH_EVENTS = Size( 100, 100 ); static bool gObjectCreatedCallBackCalled; static void TestCallback(BaseHandle handle) { gObjectCreatedCallBackCalled = true; } Dali::Integration::Point GetPointDownInside() { Dali::Integration::Point point; point.SetState( PointState::DOWN ); point.SetScreenPosition( INSIDE_TOUCH_POINT_POSITON ); return point; } Dali::Integration::Point GetPointUpInside() { Dali::Integration::Point point; point.SetState( PointState::UP ); point.SetScreenPosition( INSIDE_TOUCH_POINT_POSITON ); return point; } } int UtcDaliToggleButtonConstructorP(void) { ToolkitTestApplication application; tet_infoline(" UtcDaliToggleButtonConstructorP"); ToggleButton button; DALI_TEST_CHECK( !button ); END_TEST; } int UtcDaliToggleButtonCopyConstructorP(void) { ToolkitTestApplication application; tet_infoline(" UtcDaliToggleButtonCopyConstructorP"); // Initialize an object, ref count == 1 ToggleButton button = ToggleButton::New(); ToggleButton copy( button ); DALI_TEST_CHECK( copy ); END_TEST; } int UtcDaliToggleButtonAssignmentOperatorP(void) { ToolkitTestApplication application; tet_infoline(" UtcDaliToggleButtonAssignmentOperatorP"); ToggleButton button = ToggleButton::New(); ToggleButton copy( button ); DALI_TEST_CHECK( copy ); DALI_TEST_CHECK( button == copy ); END_TEST; } int UtcDaliToggleButtonNewP(void) { ToolkitTestApplication application; tet_infoline(" UtcDaliToggleButtonNewP"); // Create the Slider actor ToggleButton toggleButton; DALI_TEST_CHECK( !toggleButton ); toggleButton = ToggleButton::New(); DALI_TEST_CHECK( toggleButton ); ToggleButton toggleButton2(toggleButton); DALI_TEST_CHECK( toggleButton2 == toggleButton ); //Additional check to ensure object is created by checking if it's registered ObjectRegistry registry = application.GetCore().GetObjectRegistry(); DALI_TEST_CHECK( registry ); gObjectCreatedCallBackCalled = false; registry.ObjectCreatedSignal().Connect( &TestCallback ); { ToggleButton toggleButton = ToggleButton::New(); } DALI_TEST_CHECK( gObjectCreatedCallBackCalled ); END_TEST; } int UtcDaliToggleButtonDestructorP(void) { ToolkitTestApplication application; tet_infoline("UtcDaliToggleButtonDestructorP"); ToggleButton* toggleButton = new ToggleButton(); delete toggleButton; DALI_TEST_CHECK( true ); END_TEST; } int UtcDaliToggleButtonDownCast(void) { ToolkitTestApplication application; tet_infoline("UtcDaliToggleButtonDownCast"); Handle handle = ToggleButton::New(); ToggleButton toggleButton = ToggleButton::DownCast( handle ); DALI_TEST_CHECK( toggleButton == handle ); END_TEST; } int UtcDaliToggleButtonToggleStatesProperty(void) { ToolkitTestApplication application; // Exceptions require ToolkitTestApplication tet_infoline(" UtcDaliToggleButtonToggleStatesProperty"); // Create the ToggleButton actor ToggleButton toggleButton = ToggleButton::New(); application.GetScene().Add( toggleButton ); toggleButton.SetProperty( Actor::Property::PARENT_ORIGIN,ParentOrigin::TOP_LEFT); toggleButton.SetProperty( Actor::Property::ANCHOR_POINT,ParentOrigin::TOP_LEFT); toggleButton.SetProperty( Actor::Property::POSITION, Vector2( 0.0f, 0.0f )); {// Check empty array Property::Array toggleIcons; toggleButton.SetProperty( Toolkit::ToggleButton::Property::STATE_VISUALS, toggleIcons ); application.SendNotification(); application.Render(); Property::Array resultIcons; resultIcons = toggleButton.GetProperty( Toolkit::ToggleButton::Property::STATE_VISUALS ).Get<Property::Array>(); DALI_TEST_CHECK( resultIcons.Count() == 0 ); } {// Check non-empty Array Property::Array toggleIcons; toggleIcons.PushBack( TEST_IMAGE_ONE ); //Icons path toggleIcons.PushBack( TEST_IMAGE_TWO ); toggleIcons.PushBack( TEST_IMAGE_THREE ); toggleIcons.PushBack( TEST_IMAGE_FOUR ); toggleButton.SetProperty( Toolkit::ToggleButton::Property::STATE_VISUALS, toggleIcons ); application.SendNotification(); application.Render(); Property::Array resultIcons; resultIcons = toggleButton.GetProperty( Toolkit::ToggleButton::Property::STATE_VISUALS ).Get<Property::Array>(); // Check that the result is the same as DALI_TEST_EQUALS( toggleIcons.Count(), resultIcons.Count(), TEST_LOCATION ); DALI_TEST_CHECK( toggleIcons[0].Get<std::string>() == resultIcons[0].Get<std::string>() ); DALI_TEST_CHECK( toggleIcons[1].Get<std::string>() == resultIcons[1].Get<std::string>() ); DALI_TEST_CHECK( toggleIcons[2].Get<std::string>() == resultIcons[2].Get<std::string>() ); DALI_TEST_CHECK( toggleIcons[3].Get<std::string>() == resultIcons[3].Get<std::string>() ); } {// Check property::map Property::Map propertyMap1; Vector4 testColor1( 1.f, 0.5f, 0.3f, 0.2f ); propertyMap1.Insert( Toolkit::Visual::Property::TYPE, Toolkit::Visual::COLOR); propertyMap1.Insert(Toolkit::ColorVisual::Property::MIX_COLOR, testColor1); Property::Map propertyMap2; Vector4 testColor2( 0.5f, 1.f, 0.3f, 0.2f ); propertyMap2.Insert(Toolkit::Visual::Property::TYPE, Toolkit::Visual::COLOR); propertyMap2.Insert(Toolkit::ColorVisual::Property::MIX_COLOR, testColor2); Property::Map propertyMap3; Vector4 testColor3( 1.f, 0.5f, 1.f, 0.2f ); propertyMap3.Insert(Toolkit::Visual::Property::TYPE, Toolkit::Visual::COLOR); propertyMap3.Insert(Toolkit::ColorVisual::Property::MIX_COLOR, testColor3); Property::Array toggleMaps; toggleMaps.Add( propertyMap1 ); toggleMaps.Add( propertyMap2 ); toggleMaps.Add( propertyMap3 ); toggleButton.SetProperty( Toolkit::ToggleButton::Property::STATE_VISUALS, toggleMaps ); application.SendNotification(); application.Render(); Property::Array resultMaps; resultMaps = toggleButton.GetProperty( Toolkit::ToggleButton::Property::STATE_VISUALS ).Get<Property::Array>(); // Check that the result DALI_TEST_EQUALS( toggleMaps.Count(), resultMaps.Count(), TEST_LOCATION ); } END_TEST; } int UtcDaliToggleButtonToggleTipsProperty( void ) { ToolkitTestApplication application; // Exceptions require ToolkitTestApplication tet_infoline(" UtcDaliToggleButtonToggleTipsProperty"); // Create the ToggleButton actor ToggleButton toggleButton = ToggleButton::New(); application.GetScene().Add( toggleButton ); toggleButton.SetProperty( Actor::Property::PARENT_ORIGIN,ParentOrigin::TOP_LEFT); toggleButton.SetProperty( Actor::Property::ANCHOR_POINT,ParentOrigin::TOP_LEFT); toggleButton.SetProperty( Actor::Property::POSITION, Vector2( 0.0f, 0.0f )); { // Check empty tip array Property::Array toggleIcons; toggleIcons.PushBack( TEST_IMAGE_ONE ); //Icons path toggleIcons.PushBack( TEST_IMAGE_TWO ); toggleIcons.PushBack( TEST_IMAGE_THREE ); toggleButton.SetProperty( Toolkit::ToggleButton::Property::STATE_VISUALS, toggleIcons ); Property::Array toggleTips; toggleButton.SetProperty( Toolkit::ToggleButton::Property::TOOLTIPS, toggleTips ); application.SendNotification(); application.Render(); Property::Array resultTips; resultTips = toggleButton.GetProperty( Toolkit::ToggleButton::Property::TOOLTIPS ).Get<Property::Array>(); DALI_TEST_CHECK( resultTips.Count() == 0 ); } { // Check non-empty tip array Property::Array toggleIcons; toggleIcons.PushBack( TEST_IMAGE_ONE ); //Icons path toggleIcons.PushBack( TEST_IMAGE_TWO ); toggleIcons.PushBack( TEST_IMAGE_THREE ); toggleButton.SetProperty( Toolkit::ToggleButton::Property::STATE_VISUALS, toggleIcons ); Property::Array toggleTips; toggleTips.PushBack( "Button State A" ); //Tooltip string toggleTips.PushBack( "Button State B" ); toggleTips.PushBack( "Button State C" ); toggleButton.SetProperty( Toolkit::ToggleButton::Property::TOOLTIPS, toggleTips ); application.SendNotification(); application.Render(); Property::Array resultTips; resultTips = toggleButton.GetProperty( Toolkit::ToggleButton::Property::TOOLTIPS ).Get<Property::Array>(); //Check that the result is the same as DALI_TEST_EQUALS( toggleTips.Count(), resultTips.Count(), TEST_LOCATION ); DALI_TEST_CHECK( toggleTips[0].Get<std::string>() == resultTips[0].Get<std::string>() ); DALI_TEST_CHECK( toggleTips[1].Get<std::string>() == resultTips[1].Get<std::string>() ); DALI_TEST_CHECK( toggleTips[2].Get<std::string>() == resultTips[2].Get<std::string>() ); DALI_TEST_CHECK( toggleTips[3].Get<std::string>() == resultTips[3].Get<std::string>() ); } END_TEST; } int UtcDaliToggleButtonStateChange(void) { ToolkitTestApplication application; // Exceptions require ToolkitTestApplication tet_infoline(" UtcDaliToggleButtonStateChange"); // Create the ToggleButton actor ToggleButton toggleButton = ToggleButton::New(); application.GetScene().Add( toggleButton ); toggleButton.SetProperty( Actor::Property::PARENT_ORIGIN,ParentOrigin::TOP_LEFT); toggleButton.SetProperty( Actor::Property::ANCHOR_POINT,ParentOrigin::TOP_LEFT); toggleButton.SetProperty( Actor::Property::POSITION, BUTTON_POSITON_TO_GET_INSIDE_TOUCH_EVENTS ); toggleButton.SetProperty( Actor::Property::SIZE, BUTTON_SIZE_TO_GET_INSIDE_TOUCH_EVENTS ); Property::Array toggleIcons; toggleIcons.PushBack( TEST_IMAGE_ONE ); //Icons path toggleIcons.PushBack( TEST_IMAGE_TWO ); toggleIcons.PushBack( TEST_IMAGE_THREE ); toggleButton.SetProperty( Toolkit::ToggleButton::Property::STATE_VISUALS, toggleIcons ); Property::Array toggleTips; toggleTips.PushBack( "Button State A" ); //Tooltip string toggleTips.PushBack( "Button State B" ); toggleTips.PushBack( "Button State C" ); toggleButton.SetProperty( Toolkit::ToggleButton::Property::TOOLTIPS, toggleTips ); application.SendNotification(); application.Render(); Property::Array resultIcons; resultIcons = toggleButton.GetProperty( Toolkit::ToggleButton::Property::STATE_VISUALS ).Get<Property::Array>(); DALI_TEST_EQUALS( toggleIcons.Count(), resultIcons.Count(), TEST_LOCATION ); Property::Array resultTips; resultTips = toggleButton.GetProperty( Toolkit::ToggleButton::Property::TOOLTIPS ).Get<Property::Array>(); DALI_TEST_EQUALS( toggleTips.Count(), resultTips.Count(), TEST_LOCATION ); int index; DALI_TEST_CHECK( toggleButton.GetProperty( Toolkit::ToggleButton::Property::CURRENT_STATE_INDEX ).Get( index ) ); DALI_TEST_EQUALS( index, 0, TEST_LOCATION ); Dali::Integration::TouchEvent event; // Touch point down and up inside the button 3 times. event = Dali::Integration::TouchEvent(); event.AddPoint( GetPointDownInside() ); application.ProcessEvent( event ); event = Dali::Integration::TouchEvent(); event.AddPoint( GetPointUpInside() ); application.ProcessEvent( event ); DALI_TEST_CHECK( toggleButton.GetProperty( Toolkit::ToggleButton::Property::CURRENT_STATE_INDEX ).Get( index ) ); DALI_TEST_EQUALS( index, 1, TEST_LOCATION ); event = Dali::Integration::TouchEvent(); event.AddPoint( GetPointDownInside() ); application.ProcessEvent( event ); event = Dali::Integration::TouchEvent(); event.AddPoint( GetPointUpInside() ); application.ProcessEvent( event ); DALI_TEST_CHECK( toggleButton.GetProperty( Toolkit::ToggleButton::Property::CURRENT_STATE_INDEX ).Get( index ) ); DALI_TEST_EQUALS( index, 2, TEST_LOCATION ); event = Dali::Integration::TouchEvent(); event.AddPoint( GetPointDownInside() ); application.ProcessEvent( event ); event = Dali::Integration::TouchEvent(); event.AddPoint( GetPointUpInside() ); application.ProcessEvent( event ); DALI_TEST_CHECK( toggleButton.GetProperty( Toolkit::ToggleButton::Property::CURRENT_STATE_INDEX ).Get( index ) ); DALI_TEST_EQUALS( index, 0, TEST_LOCATION ); END_TEST; }
003a2d2b01086369e43dc56dce9dd6d194f0b7b2
d687b9cd2e43f7eef4c1c4d8142cd9db1ec1e41e
/10055.cpp
d03c60b2416493ac12a2b0eca7cc98d3314bdd22
[]
no_license
MehediMubin/UVA-Solutions
4a1d501d1490b67dd6dfcb8923308a3d14606ab4
07a80ee491460f1e2fc3a3d8f134bb1d5fd5684f
refs/heads/master
2020-06-27T01:24:24.620713
2020-02-07T15:32:50
2020-02-07T15:32:50
199,809,188
0
0
null
null
null
null
UTF-8
C++
false
false
285
cpp
10055.cpp
#include<iostream> #include<cstdio> using namespace std; int main() { long long int a, b; while(scanf("%lld %lld", &a, &b) != EOF){ if(a > b) cout << (a - b) << endl; else cout << (b - a) << endl; } return 0; }
35e21390d83522872690e45a5aa0e9ab0c10f07c
c24cd343d2736f15aa4583e3057a9e1a715f9481
/queue.cpp
d4be8aa974aebd33925e34b1955cf776fe674446
[]
no_license
blpearson26/COP4534-Project2
8e2100e5dad481dc5bc1b5162969fa5ad7b9d8c5
a1ba1d7bc789c6fdcad2e850c0dea81e7338d801
refs/heads/main
2023-07-31T10:29:07.856489
2021-10-07T20:18:43
2021-10-07T20:18:43
412,893,382
0
0
null
null
null
null
UTF-8
C++
false
false
558
cpp
queue.cpp
#include "queue.hpp" Queue::Queue() { head = NULL; tail = NULL; size = 0; } void Queue::PushBack(float data) { isEmpty = false; Customer *newNode = new Customer(data); if(tail == NULL) { tail = head = newNode; return; } tail->nextCust = newNode; tail = newNode; ++size; } Customer Queue::Pop() { if(head == NULL) tail = NULL; Customer *temp = head; head = head->nextCust; --size; return *temp; } bool Queue::IsEmpty() { if(this->size > 0) return false; else return true; } int Queue::GetSize() { return this->size; }
73facd11733311b4f96d8cce729ffe5471bcbed5
e7f4c25dc251fd6b74efa7014c3d271724536797
/src/util/u32lim.h
ad20a3f6944dfd225f50aaea4f215c705c80d72a
[ "LicenseRef-scancode-warranty-disclaimer", "LicenseRef-scancode-public-domain" ]
permissive
nightlark/re2c
163cc308e9023b290e08cc82cc704a8ae5b90114
96104a652622c63ca2cc0b1d2b1d3dad8c34aae6
refs/heads/master
2023-08-08T18:35:31.715463
2023-07-21T21:23:56
2023-07-21T21:29:45
100,122,233
1
0
null
2017-08-12T15:51:24
2017-08-12T15:51:24
null
UTF-8
C++
false
false
1,662
h
u32lim.h
#ifndef _RE2C_UTIL_U32LIM_ #define _RE2C_UTIL_U32LIM_ #include <stdint.h> namespace re2c { // uint32_t truncated to LIMIT. Any overflow (either result of a binary operation or conversion from // another type) results in LIMIT (LIMIT is a fixpoint). template<uint32_t LIMIT> class u32lim_t { uint32_t value; explicit u32lim_t(uint32_t x): value(x < LIMIT ? x : LIMIT) {} explicit u32lim_t(uint64_t x): value(x < LIMIT ? static_cast<uint32_t>(x) : LIMIT) {} public: // Implicit conversion is forbidden, because operands should be converted before operation: // uint32_t x, y; ... u32lim_t z = x + y; // would result in 32-bit addition and may overflow. Don't export overloaded constructors: it // breaks OS X builds (size_t causes resolution ambiguity). static u32lim_t from32(uint32_t x) { return u32lim_t(x); } static u32lim_t from64(uint64_t x) { return u32lim_t(x); } static u32lim_t limit() { return u32lim_t(LIMIT); } uint32_t uint32() const { return value; } bool overflow() const { return value == LIMIT; } friend u32lim_t operator+(u32lim_t x, u32lim_t y) { const uint64_t z = static_cast<uint64_t>(x.value) + static_cast<uint64_t>(y.value); return z < LIMIT ? u32lim_t(z): u32lim_t(LIMIT); } friend u32lim_t operator * (u32lim_t x, u32lim_t y) { const uint64_t z = static_cast<uint64_t>(x.value) * static_cast<uint64_t>(y.value); return z < LIMIT ? u32lim_t(z) : u32lim_t(LIMIT); } friend bool operator < (u32lim_t x, u32lim_t y) { return x.value < y.value; } }; } // namespace re2c #endif // _RE2C_UTIL_U32LIM_
90556fca86f6ba47ac17fc3ebada1461de2b8a56
71cbc64910807ceab826a6c54e0fea8d96104506
/DBServer/LoongDB.cpp
8a2374615280c716e79ad82b287a658107e1c2be
[]
no_license
adrianolls/ll
385580143dfc2365428469a51c220da08bfea8ec
9c7d480036b1e6f1e3bdffe93b44bd5c70bd944a
refs/heads/master
2022-12-26T07:06:13.260844
2020-09-16T04:36:17
2020-09-16T04:36:17
null
0
0
null
null
null
null
GB18030
C++
false
false
45,811
cpp
LoongDB.cpp
//------------------------------------------------------------------------------------------------------- // Copyright (c) 2004 TENGWU Entertainment All rights reserved. // filename: LoongDB.cpp // author: Sxg // actor: // data: 2008-05-12 // last: // brief: 数据库操作应用层实现 //------------------------------------------------------------------------------------------------------- #include "StdAfx.h" #include "../WorldDefine/RoleDefine.h" #include "../ServerDefine/role_data.h" #include "../ServerDefine/msg_mall.h" #include "../ServerDefine/base_define.h" #include "../ServerDefine/msg_leftmsg.h" #include "../ServerDefine/item_define.h" #include "LoongDB.h" #include "../WorldDefine/msg_external_links.h" #include "../ServerDefine/msg_olinfo.h" TBetonCallback CLoongDB::m_pDBCallback = NULL; VOID CLoongDB::SetDBCallback(TBetonCallback func) { m_pDBCallback = func; } VOID WINAPI CLoongDB::BetonLoginCallback(Beton::DataBase* pDB,INT Reason,INT Param,LPVOID p) { if( P_VALID(p) ) { CLoongDB * pThis = (CLoongDB*)p; if(pThis->m_pDBCallback) { if( pDB == pThis->m_pDBLoong ) pThis->m_pDBCallback(Reason,Param,_T("gamedb")); else if( pDB == pThis->m_pDBLog ) pThis->m_pDBCallback(Reason,Param,_T("logdb")); else if( pDB == pThis->m_pDBLogin ) pThis->m_pDBCallback(Reason,Param,_T("logindb")); else pThis->m_pDBCallback(Reason,Param,_T("db")); } } } //------------------------------------------------------------------------------------------------------- // 构造函数 //------------------------------------------------------------------------------------------------------- CLoongDB::CLoongDB() { m_pDBLoong = new Beton::DataBase; m_pDBLog = new Beton::DataBase; m_pDBLogin = new Beton::DataBase; m_bInitOK = FALSE; m_dwMaxPetID = MIN_PET_ID; m_nPetNum = 0; m_dwMaxRoleID = 0; m_nRoleNum = 0; m_nLoadNumLim = 0; m_dwReadTimes = 0; m_dwWriteTimes = 0; m_dwTempChannelID = 0; //m_bOpenShengLing = true; m_pDBLoong->SetWarningCallBack(BetonLoginCallback,this); m_pDBLog->SetWarningCallBack(BetonLoginCallback,this); m_pDBLogin->SetWarningCallBack(BetonLoginCallback,this); m_hKoreaLogFile = INVALID_HANDLE_VALUE; } //------------------------------------------------------------------------------------------------------- // 析构函数 //------------------------------------------------------------------------------------------------------- CLoongDB::~CLoongDB() { SAFE_DEL(m_pDBLoong); SAFE_DEL(m_pDBLog); SAFE_DEL(m_pDBLogin); CloseHandle(m_hKoreaLogFile); m_hKoreaLogFile = INVALID_HANDLE_VALUE; } //------------------------------------------------------------------------------------------------------- // 读取配置文件,并初始化数据库连接 //------------------------------------------------------------------------------------------------------- BOOL CLoongDB::Init(LPCTSTR szIniFileName,BOOL bReload) { // 创建容器,并载入配置文件 if( !bReload ) { CreateObj("LoongDBVar", "VarContainer"); TObjRef<VarContainer> pVar = "LoongDBVar"; if(!P_VALID(pVar)) { ERR(_T("Create LoongDBVar(VarContainer) obj failed!")); return FALSE; } pVar->Load("VirtualFileSys", szIniFileName); // 创建并初始化游戏数据库引擎 /*if(!m_pDBLoong->Init(_T("172.17.1.201"), _T("root"), _T("kungfu"), _T("loong_base"), 3306))*/ if(!m_pDBLoong->Init(pVar->GetString(_T("host_name db_game")), pVar->GetString(_T("user_name db_game")), pVar->GetString(_T("password db_game")), pVar->GetString(_T("db_name db_game")), (INT)pVar->GetDword(_T("port db_game")))) { ERR(_T("Game Database initialize failed! Please check profile...")); SAFE_DEL(m_pDBLoong); return FALSE; } // 创建并初始化log数据库引擎 if(!m_pDBLog->Init(pVar->GetString(_T("host_name db_log")), pVar->GetString(_T("user_name db_log")), pVar->GetString(_T("password db_log")), pVar->GetString(_T("db_name db_log")), (INT)pVar->GetDword(_T("port db_log")))) { ERR(_T("Log Database initialize failed! Please check profile...")); SAFE_DEL(m_pDBLoong); SAFE_DEL(m_pDBLog); return FALSE; } //创建并初始化login游戏数据库引擎 if(!m_pDBLogin->Init(pVar->GetString(_T("host_name db_login")), pVar->GetString(_T("user_name db_login")), pVar->GetString(_T("password db_login")), pVar->GetString(_T("db_name db_login")), (INT)pVar->GetDword(_T("port db_login")))) { ERR(_T("Login Database initialize failed! Please check profile...")); SAFE_DEL(m_pDBLoong); SAFE_DEL(m_pDBLog); SAFE_DEL(m_pDBLogin); return FALSE; } //m_bOpenShengLing = pVar->GetInt(_T("open open_shengling")); // 清空容器 pVar->Clear(); // 销毁容器 KillObj("LoongDBVar"); } else { do { if( P_VALID(m_pDBLoong) ) m_bInitOK = m_pDBLoong->Reconnect(FALSE); if( !m_bInitOK ) break; if( P_VALID(m_pDBLog) ) m_bInitOK = m_pDBLog->Reconnect(FALSE); if( !m_bInitOK ) break; if( P_VALID(m_pDBLogin) ) m_bInitOK = m_pDBLogin->Reconnect(FALSE); if( !m_bInitOK ) break; } while (0); if( !m_bInitOK ) { SAFE_DEL(m_pDBLoong); SAFE_DEL(m_pDBLog); SAFE_DEL(m_pDBLogin); return FALSE; } } GetRoleCountAndMaxRoleID(m_nRoleNum, m_dwMaxRoleID); GetYBAccountNum(m_nAccountNum); GetYBOrderNum(m_nOrderNum); GetActivityNum(m_nActivityNum); GetActivityRankNum(m_nActivityRankNum); GetMaxOrderIndex(m_dwMaxOrderIndex); GetPetCountAndMaxPetID(m_nPetNum, m_dwMaxPetID); GetGPInfoNumAndSize(m_nGroupPurchaseInfoNum, m_nGroupPurchaseInfoSize); GetLimitItemInfoNumAndSize(m_nLimitItemInfoNum,m_nLimitItemInfoSize); m_dwReadTimes = 0; m_dwWriteTimes = 0; m_bInitOK = TRUE; return TRUE; } //------------------------------------------------------------------------------------------------------- // 资源回收函数 //------------------------------------------------------------------------------------------------------- VOID CLoongDB::Destroy() { if(m_bInitOK) { m_dwReadTimes = 0; m_dwWriteTimes = 0; m_bInitOK = FALSE; m_pDBLoong->ShutDown(); m_pDBLog->ShutDown(); m_pDBLogin->ShutDown(); return; } } //------------------------------------------------------------------------------------------------------- // 获取roledata记录条数和最大RoleID //------------------------------------------------------------------------------------------------------- VOID CLoongDB::GetRoleCountAndMaxRoleID(INT32 &nCount, DWORD &dwMaxRoleID) { nCount = 0; dwMaxRoleID = 0; // 获取流 Beton::MyStream* pStream = m_pDBLoong->GetStream(); // 格式化 pStream->SetSelect("roledata", "count(RoleID),max(RoleID)"); // 查询数据库 Beton::QueryResult* pResult = m_pDBLoong->Query(pStream); if(P_VALID(pResult) && pResult->GetRowCount() > 0) { nCount = (*pResult)[0].GetInt(); dwMaxRoleID = (*pResult)[1].GetDword(); } ++m_dwReadTimes; // 释放流和结果 m_pDBLoong->ReturnStream(pStream); m_pDBLoong->FreeQueryResult(pResult); } //------------------------------------------------------------------------------------------------------- // 获取roledata记录条数和最大RoleID //------------------------------------------------------------------------------------------------------- VOID CLoongDB::GetMaxMinSerial(INT64 &n64Max, INT64 &n64Min) { INT64 n64MaxSerial = MIN_ITEM_SERIAL_INTERNAL; INT64 n64MinSerial = MAX_ITEM_SERIAL_OUTTER; n64Max = n64MaxSerial; n64Min = n64MinSerial; GetMaxMinSerial("item", n64MaxSerial, n64MinSerial); n64Max = max(n64MaxSerial, n64Max); n64Min = min(n64MinSerial, n64Min); GetMaxMinSerial("item_baibao", n64MaxSerial, n64MinSerial); n64Max = max(n64MaxSerial, n64Max); n64Min = min(n64MinSerial, n64Min); GetMaxMinSerial("item_del", n64MaxSerial, n64MinSerial); n64Max = max(n64MaxSerial, n64Max); n64Min = min(n64MinSerial, n64Min); } //------------------------------------------------------------------------------------------------------- // 获取roledata记录条数和最大RoleID //------------------------------------------------------------------------------------------------------- VOID CLoongDB::GetMaxMinSerial(const char* pTable, INT64 &n64Max, INT64 &n64Min) { // 获取流 Beton::MyStream* pStream = m_pDBLoong->GetStream(); // 格式化 pStream->SetSelect(pTable, "max(SerialNum),min(SerialNum)"); pStream->SetWhere(); pStream->FillString("SerialNum>") << 0; // 查询数据库 Beton::QueryResult* pResult = m_pDBLoong->Query(pStream); if(P_VALID(pResult) && pResult->GetRowCount() > 0) { n64Max = (*pResult)[0].GetLong(); n64Min = (*pResult)[1].GetLong(); } ++m_dwReadTimes; // 释放流和结果 m_pDBLoong->ReturnStream(pStream); m_pDBLoong->FreeQueryResult(pResult); } //在longinDB插入角色名字 BOOL CLoongDB::InsertRoleName(DWORD dwID, LPVOID pNameData) { LPCTSTR pName = (LPCTSTR)pNameData; // 获取流和连接 Beton::MyStream* pStream = m_pDBLogin->GetStream(); Beton::Connection* pCon = m_pDBLogin->GetFreeConnection(); // 格式化角色数据 pStream->SetInsert("role_name"); pStream->FillString("name='").FillString(pName, pCon).FillString("'"); // 释放连接 m_pDBLogin->ReturnConnection(pCon); // 插入到数据库 BOOL bRet = m_pDBLogin->Execute(pStream); m_pDBLogin->ReturnStream(pStream); ++m_dwWriteTimes; return bRet; } //在longinDB插入帮派名字 BOOL CLoongDB::InsertGuildName(DWORD dwID,LPVOID pNameData) { LPCTSTR pName = (LPCTSTR)pNameData; // 获取流和连接 Beton::MyStream* pStream = m_pDBLogin->GetStream(); Beton::Connection* pCon = m_pDBLogin->GetFreeConnection(); // 格式化角色数据 pStream->SetInsert("guild_name"); pStream->FillString("name='").FillString(pName, pCon).FillString("'"); // 释放连接 m_pDBLogin->ReturnConnection(pCon); // 插入到数据库 BOOL bRet = m_pDBLogin->Execute(pStream); m_pDBLogin->ReturnStream(pStream); ++m_dwWriteTimes; return bRet; } //------------------------------------------------------------------------------------------------------- // 创建角色 //------------------------------------------------------------------------------------------------------- BOOL CLoongDB::CreateRole(OUT DWORD &dwNewRoleID, DWORD dwAccountID, const tagCreateRoleInfo &RoleInfo, DWORD &dwRoleNameCrc) { // 获取流和连接 Beton::MyStream* pStream = m_pDBLoong->GetStream(); Beton::Connection* pCon = m_pDBLoong->GetFreeConnection(); // 格式化角色数据 pStream->SetInsert("roledata"); pStream->FillString("AccountID=") << dwAccountID; pStream->FillString(",RoleID=") << m_dwMaxRoleID + 1; pStream->FillString(",RoleName='").FillString(RoleInfo.szRoleName, pCon); // 转成小写计算CRC32 int cpylen = min(sizeof(RoleInfo.szRoleName),sizeof(m_szRoleName)); _tcscpy_s(m_szRoleName, cpylen, RoleInfo.szRoleName); _tcslwr(m_szRoleName); dwRoleNameCrc = m_pUtil->Crc32(m_szRoleName); pStream->FillString("',RoleNameCrc=") << dwRoleNameCrc; pStream->FillString(",Sex=") << RoleInfo.Avatar.bySex; pStream->FillString(",HairModelID=") << RoleInfo.Avatar.wHairMdlID; pStream->FillString(",HairColorID=") << RoleInfo.Avatar.wHairTexID; pStream->FillString(",FaceModelID=") << RoleInfo.Avatar.wFaceMdlID; pStream->FillString(",FaceDetailID=") << RoleInfo.Avatar.wFaceDetailTexID; pStream->FillString(",DressModelID=") << RoleInfo.Avatar.wDressMdlID; pStream->FillString(",MapID=") << RoleInfo.dwMapID; pStream->FillString(",X=") << RoleInfo.fX; // 坐标 pStream->FillString(",Y=") << RoleInfo.fY; pStream->FillString(",Z=") << RoleInfo.fZ; pStream->FillString(",FaceX=") << RoleInfo.fFaceX; // 朝向 pStream->FillString(",FaceY=") << RoleInfo.fFaceY; pStream->FillString(",FaceZ=") << RoleInfo.fFaceZ; pStream->FillString(",Level=") << RoleInfo.byLevel; // LoongDB设置时间 if(DwordTime2DataTime(m_szTime, sizeof(m_szTime), RoleInfo.CreateTime)) { pStream->FillString(",CreateTime='").FillString(m_szTime); pStream->FillString("'"); } else { IMSG(_T("Error: Func DwordTime2DataTime() run error in CLoongDB::CreateRole()!!!!!\r\n")); ASSERT(0); } // 释放连接 m_pDBLoong->ReturnConnection(pCon); // 插入到数据库 BOOL bRet = m_pDBLoong->Execute(pStream); m_pDBLoong->ReturnStream(pStream); if(bRet) { ++m_dwMaxRoleID; ++m_nRoleNum; dwNewRoleID = m_dwMaxRoleID; } ++m_dwWriteTimes; return bRet; } //------------------------------------------------------------------------------------------------------- // 恢复角色 //------------------------------------------------------------------------------------------------------- BOOL CLoongDB::ResumeRole(DWORD dwRoleID) { //?? 目前不提供支持 return TRUE; } //------------------------------------------------------------------------------------------------------- // 备份角色相关数据//??其它相关表数据 //------------------------------------------------------------------------------------------------------- // DWORD CLoongDB::BackupRole(DWORD dwAccountID, DWORD dwRoleID) // { // DWORD dwErrorCode; // // // 备份roledata表中相关数据 // dwErrorCode = BackupRoleData(dwAccountID, dwRoleID); // if(E_Success != dwErrorCode) // { // return dwErrorCode; // } // // // 备份item表中相关数据 // dwErrorCode = BackupItem(dwRoleID); // if(E_Success != dwErrorCode) // { // return dwErrorCode; // } // // return dwErrorCode; // } //********************************** 备份数据(部分表,删除角色用) *************************************** //------------------------------------------------------------------------------------------------------- // 备份角色属性信息 //------------------------------------------------------------------------------------------------------- BOOL CLoongDB::BackupRoleData(DWORD dwAccountID, DWORD dwRoleID) { BOOL bRet = TRUE; // 获取流 Beton::MyStream* pStream = m_pDBLoong->GetStream(); ASSERT(P_VALID(pStream)); // 格式化数据库操作语句 pStream->Clear(); pStream->FillString("insert into roledata_del select * from roledata where AccountID=") << dwAccountID; pStream->FillString(" and RoleID=") << dwRoleID; // 执行 bRet = m_pDBLoong->Execute(pStream); // 释放流 m_pDBLoong->ReturnStream(pStream); ++m_dwWriteTimes; return bRet; } //------------------------------------------------------------------------------------------------------- // 备份角色物品信息 //------------------------------------------------------------------------------------------------------- // BOOL CLoongDB::BackupItem(DWORD dwRoleID) // { // BOOL bRet = TRUE; // // // 获取流 // Beton::MyStream* pStream = m_pDBLoong->GetStream(); // ASSERT(P_VALID(pStream)); // // // 格式化数据库操作语句 // pStream->Clear(); // pStream->FillString("insert into item_del select * from item where OwnerID=") << dwRoleID; // // // 执行 // bRet = m_pDBLoong->Execute(pStream); // // // 释放流 // m_pDBLoong->ReturnStream(pStream); // // ++m_dwWriteTimes; // // return bRet; // } //************************************* 删除角色所有相关数据 ******************************************** //------------------------------------------------------------------------------------------------------- // 删除角色//??其它相关表数据 //------------------------------------------------------------------------------------------------------- DWORD CLoongDB::DelRole(DWORD dwAccountID, DWORD dwRoleID) { if(DelRoleData(dwAccountID, dwRoleID)) { // 删除buff或物品若失败, 不做处理//?? DelRoleBuff(dwRoleID); DelRoleItem(dwRoleID); } else { return E_DBDelete_RoleFailed; } return E_Success; } //------------------------------------------------------------------------------------------------------- // 删除角色属性信息 //------------------------------------------------------------------------------------------------------- BOOL CLoongDB::DelRoleData(DWORD dwAccountID, DWORD dwRoleID) { BOOL bRet = TRUE; // 获取流 Beton::MyStream* pStream = m_pDBLoong->GetStream(); ASSERT(P_VALID(pStream)); // 格式化数据库操作语句 pStream->SetDelete("roledata"); pStream->SetWhere(); pStream->FillString("RoleID=") << dwRoleID; pStream->FillString(" and AccountID=") << dwAccountID; // 执行 bRet = m_pDBLoong->Execute(pStream); // 释放流 m_pDBLoong->ReturnStream(pStream); ++m_dwWriteTimes; return bRet; } //------------------------------------------------------------------------------------------------------- // 删除角色buff信息 //------------------------------------------------------------------------------------------------------- BOOL CLoongDB::DelRoleBuff(DWORD dwRoleID) { BOOL bRet = TRUE; // 获取流 Beton::MyStream* pStream = m_pDBLoong->GetStream(); ASSERT(P_VALID(pStream)); // 格式化数据库操作语句 pStream->SetDelete("buff"); pStream->SetWhere(); pStream->FillString("RoleID=") << dwRoleID; // 执行 bRet = m_pDBLoong->Execute(pStream); // 释放流 m_pDBLoong->ReturnStream(pStream); ++m_dwWriteTimes; return bRet; } //------------------------------------------------------------------------------------------------------- // 删除角色物品信息 //------------------------------------------------------------------------------------------------------- BOOL CLoongDB::DelRoleItem(DWORD dwRoleID) { BOOL bRet = TRUE; // 获取流 Beton::MyStream* pStream = m_pDBLoong->GetStream(); ASSERT(P_VALID(pStream)); // 格式化数据库操作语句 pStream->SetDelete("item"); pStream->SetWhere(); pStream->FillString("OwnerID=") << dwRoleID; pStream->FillString(" and (ContainerTypeID!=") << EICT_RoleWare; pStream->FillString(" or (ContainerTypeID=") << EICT_RoleWare; pStream->FillString(" and Bind=") << EBS_Bind; pStream->FillString("))"); // 执行 bRet = m_pDBLoong->Execute(pStream); // 释放流 m_pDBLoong->ReturnStream(pStream); ++m_dwWriteTimes; return bRet; } //------------------------------------------------------------------------------------------------------- // 记录删除角色时的角色名称,Crc,时间及IP等 //------------------------------------------------------------------------------------------------------- BOOL CLoongDB::RecordInfoDelRole(DWORD dwAccountID, DWORD dwRoleID, LPCTSTR szRoleName, LPCSTR szIP) { BOOL bRet = TRUE; // 获取流和连接 Beton::MyStream* pStream = m_pDBLoong->GetStream(); Beton::Connection* pCon = m_pDBLoong->GetFreeConnection(); ASSERT(P_VALID(pStream)); ASSERT(P_VALID(pCon)); // 记录删除操作相关信息 pStream->SetInsert("role_del"); pStream->FillString("AccountID=") << dwAccountID; pStream->FillString(",RoleName='").FillString(szRoleName, pCon); pStream->FillString("',RoleID=") << dwRoleID; pStream->FillString(",IP='").FillString(szIP); pStream->FillString("',DeleteTime=now()"); // 释放连接 m_pDBLoong->ReturnConnection(pCon); // 执行 bRet = m_pDBLoong->Execute(pStream); m_pDBLoong->ReturnStream(pStream); ++m_dwWriteTimes; return bRet; } //------------------------------------------------------------------------------------------------------- // 物品冷却 //------------------------------------------------------------------------------------------------------- BOOL CLoongDB::ReplaceItemCDTime(DWORD dwRoleID, LPVOID pData, INT32 nNum, OUT LPVOID *ppOutPointer) { BOOL bRet = TRUE; // 获取流和连接 Beton::MyStream* pStream = m_pDBLoong->GetStream(); Beton::Connection* pCon = m_pDBLoong->GetFreeConnection(); *ppOutPointer = pData; // 格式化数据 pStream->SetReplace("item_cdtime"); pStream->FillString("RoleID=") << dwRoleID; if(nNum > 0) { pStream->FillString(",CDTime='"); pStream->FillBlob(pData, sizeof(tagCDTime) * nNum, pCon); pStream->FillString("'"); *ppOutPointer = (BYTE*)pData + sizeof(tagCDTime) * nNum; } // 释放连接 m_pDBLoong->ReturnConnection(pCon); // 执行 bRet = m_pDBLoong->Execute(pStream); // 释放流 m_pDBLoong->ReturnStream(pStream); ++m_dwWriteTimes; return bRet; } //------------------------------------------------------------------------------------------------------- // 获取YBAccount记录的数量 //------------------------------------------------------------------------------------------------------- VOID CLoongDB::GetYBAccountNum(INT32 &nAccountNum) { nAccountNum = 0; // 获取流 Beton::MyStream* pStream = m_pDBLoong->GetStream(); // 格式化 pStream->SetSelect("ybaccount", "count(RoleID)"); // 查询数据库 Beton::QueryResult* pResult = m_pDBLoong->Query(pStream); if(P_VALID(pResult) && pResult->GetRowCount() > 0) { nAccountNum = (*pResult)[0].GetInt(); } ++m_dwReadTimes; // 释放流和结果 m_pDBLoong->ReturnStream(pStream); m_pDBLoong->FreeQueryResult(pResult); } //------------------------------------------------------------------------------------------------------- // 获取yuanbaoorder的委托订单记录的数量 //------------------------------------------------------------------------------------------------------- VOID CLoongDB::GetYBOrderNum(INT32 &nOrderNum) { nOrderNum = 0; // 获取流 Beton::MyStream* pStream = m_pDBLoong->GetStream(); // 格式化 pStream->SetSelect("yuanbaoorder", "count(dwID)"); pStream->SetWhere(); pStream->FillString("OrderMode=") << 0; // 查询数据库 Beton::QueryResult* pResult = m_pDBLoong->Query(pStream); if(P_VALID(pResult) && pResult->GetRowCount() > 0) { nOrderNum = (*pResult)[0].GetInt(); } ++m_dwReadTimes; // 释放流和结果 m_pDBLoong->ReturnStream(pStream); m_pDBLoong->FreeQueryResult(pResult); } //------------------------------------------------------------------------------------------------------- // 获取一个玩家yuanbaoorder记录的数量 //------------------------------------------------------------------------------------------------------- VOID CLoongDB::GetRoleYBOrderNum(DWORD dwRoleID, INT32 &nOrderNum) { nOrderNum = 0; // 获取流 Beton::MyStream* pStream = m_pDBLoong->GetStream(); // 格式化 pStream->SetSelect("yuanbaoorder", "count(dwID)"); pStream->SetWhere(); pStream->FillString("RoleID=") << dwRoleID; // 查询数据库 Beton::QueryResult* pResult = m_pDBLoong->Query(pStream); if(P_VALID(pResult) && pResult->GetRowCount() > 0) { nOrderNum = (*pResult)[0].GetInt(); } ++m_dwReadTimes; // 释放流和结果 m_pDBLoong->ReturnStream(pStream); m_pDBLoong->FreeQueryResult(pResult); } //------------------------------------------------------------------------------------------------------- // 获得固定活动数量 //------------------------------------------------------------------------------------------------------- VOID CLoongDB::GetActivityNum(INT32 &nActivityNum) { nActivityNum = 0; // 获取流 Beton::MyStream* pStream = m_pDBLoong->GetStream(); // 格式化 pStream->SetSelect("activity", "count(dwID)"); // 查询数据库 Beton::QueryResult* pResult = m_pDBLoong->Query(pStream); if(P_VALID(pResult) && pResult->GetRowCount() > 0) { nActivityNum = (*pResult)[0].GetInt(); } ++m_dwReadTimes; // 释放流和结果 m_pDBLoong->ReturnStream(pStream); m_pDBLoong->FreeQueryResult(pResult); } VOID CLoongDB::GetActivityRankNum(INT32 &nActivityRankNum) { nActivityRankNum = 0 ; // 获取流 Beton::MyStream* pStream = m_pDBLoong->GetStream(); if( !P_VALID(pStream) ) return; pStream->Clear(); // 格式化 pStream->SetSelect("activity_rankdata", "count(role_id)"); // 查询数据库 Beton::QueryResult* pResult = m_pDBLoong->Query(pStream); if(P_VALID(pResult) && pResult->GetRowCount() > 0) { nActivityRankNum = (*pResult)[0].GetInt(); } ++m_dwReadTimes; // 释放流和结果 m_pDBLoong->ReturnStream(pStream); m_pDBLoong->FreeQueryResult(pResult); } //------------------------------------------------------------------------------------------------------- // 获取一个玩家yuanbaoorder记录最大Index //------------------------------------------------------------------------------------------------------- VOID CLoongDB::GetMaxOrderIndex( DWORD& dwMaxIndex ) { dwMaxIndex = 0; // 获取流 Beton::MyStream* pStream = m_pDBLoong->GetStream(); // 格式化 pStream->SetSelect("yuanbaoorder", "max(dwID)"); // 查询数据库 Beton::QueryResult* pResult = m_pDBLoong->Query(pStream); if(P_VALID(pResult) && pResult->GetRowCount() > 0) { dwMaxIndex = (*pResult)[0].GetDword(); } ++m_dwReadTimes; // 释放流和结果 m_pDBLoong->ReturnStream(pStream); m_pDBLoong->FreeQueryResult(pResult); } VOID CLoongDB::GetPetCountAndMaxPetID( INT32 &nCount, DWORD &dwMaxPetID ) { nCount = 0; dwMaxPetID = MIN_PET_ID; // 获取流 Beton::MyStream* pStream = m_pDBLoong->GetStream(); // 格式化 pStream->SetSelect("pet_data", "count(pet_id),max(pet_id)"); // 查询数据库 Beton::QueryResult* pResult = m_pDBLoong->Query(pStream); if(P_VALID(pResult) && pResult->GetRowCount() > 0) { nCount = (*pResult)[0].GetInt(); dwMaxPetID = (*pResult)[1].GetDword(); if (!IS_PET(dwMaxPetID)) { dwMaxPetID = MIN_PET_ID; } } ++m_dwReadTimes; // 释放流和结果 m_pDBLoong->ReturnStream(pStream); m_pDBLoong->FreeQueryResult(pResult); } //------------------------------------------------------------------------------------------------------- // 获取所有限量商品信息的数量 //------------------------------------------------------------------------------------------------------- VOID CLoongDB::GetLimitItemInfoNumAndSize(INT32 &nInfoNum, INT32 &nDataSize) { nInfoNum = 0; nDataSize = 0; // 获取流 Beton::MyStream* pStream = m_pDBLoong->GetStream(); // 格式化 pStream->SetSelect("LimitNumItemInfo", "Id"); // 查询数据库 Beton::QueryResult* pResult = m_pDBLoong->Query(pStream); if(P_VALID(pResult) && (pResult->GetRowCount() > 0)) { nInfoNum = pResult->GetRowCount(); } ++m_dwReadTimes; // 释放流和结果 m_pDBLoong->ReturnStream(pStream); m_pDBLoong->FreeQueryResult(pResult); } //------------------------------------------------------------------------------------------------------- // 获取所有帮派团购信息的数量 //------------------------------------------------------------------------------------------------------- VOID CLoongDB::GetGPInfoNumAndSize( INT32 &nGPInfoNum, INT32 &nDataSize ) { nGPInfoNum = 0; nDataSize = 0; // 获取流 Beton::MyStream* pStream = m_pDBLoong->GetStream(); // 格式化 pStream->SetSelect("group_purchase", "ParticipatorList"); // 查询数据库 Beton::QueryResult* pResult = m_pDBLoong->Query(pStream); if(P_VALID(pResult) && pResult->GetRowCount() > 0) { nGPInfoNum = pResult->GetRowCount(); nDataSize = (sizeof(tagGPInfo)-sizeof(DWORD)) * nGPInfoNum; for (int i=0; i<nGPInfoNum; i++) { nDataSize += (*pResult)[0].GetLen(); pResult->NextRow(); } } ++m_dwReadTimes; // 释放流和结果 m_pDBLoong->ReturnStream(pStream); m_pDBLoong->FreeQueryResult(pResult); } BOOL CLoongDB::LoadLeftMsg( DWORD dwRoleID, PVOID pLeftMsg, DWORD &dwSize ) { INT nMsgNum = 0; PVOID pData = pLeftMsg; BOOL bRtv = Load(pData, &nMsgNum, GT_INVALID, dwRoleID, &CLoongDB::FormatLoadLeftMsg, &CLoongDB::ProcResLoadLeftMsg); if (bRtv) { dwSize = (BYTE*)pData - (BYTE*)pLeftMsg; } return bRtv; } VOID CLoongDB::FormatLoadLeftMsg( Beton::MyStream *pStream, DWORD dwDumy, DWORD dwRoleID ) { pStream->Clear(); pStream->FillString("select msg_data from left_msg where roleid=") << dwRoleID; pStream->FillString(" order by msg_id asc"); } VOID CLoongDB::ProcResLoadLeftMsg( OUT LPVOID &pData, OUT INT32 *pNum, Beton::QueryResult *pRes ) { if(!P_VALID(pRes) || pRes->GetRowCount() <= 0) return; INT nRowNum = pRes->GetRowCount(); INT i; for (i=0; i<nRowNum; ++i) { UINT uLen = (*pRes)[0].GetLen(); BOOL bRtv = (*pRes)[0].GetBlob(pData, uLen); if (!bRtv) continue; pData = (BYTE*) pData + uLen; pRes->NextRow(); } if (P_VALID(pNum)) { *pNum = i; } } BOOL CLoongDB::DelLeftMsg( DWORD dwRoleID, DWORD dwDateTime ) { return Update(dwRoleID, (LPVOID)&dwDateTime, 1, sizeof(DWORD), &CLoongDB::FormatDelLeftMsg, NULL); } VOID CLoongDB::FormatDelLeftMsg( Beton::MyStream *pStream, DWORD dwRoleID, LPVOID pDumy ) { DWORD dwDateTime = *((DWORD*)pDumy); pStream->Clear(); pStream->FillString("delete from left_msg where roleid=") << dwRoleID; pStream->FillString(" and msg_id=") << dwDateTime; } BOOL CLoongDB::InsertLeftMsg( DWORD dwRoleID, DWORD dwDateTime, PVOID pLeftMsg ) { return Update(dwRoleID, pLeftMsg, 1, 0,&CLoongDB::FormatInsertLeftMsg, NULL); } VOID CLoongDB::FormatInsertLeftMsg( Beton::MyStream *pStream, DWORD dwRoleID, LPVOID pData ) { MTRANS_POINTER(pMsgInsert, pData, tagDBLeftMsg); Beton::Connection* con = m_pDBLoong->GetFreeConnection(); pStream->Clear(); pStream->FillString("insert into left_msg set roleid=") << pMsgInsert->dwRoleID; pStream->FillString(", msg_id=")<< pMsgInsert->dwDateTime; tagNetCmd* pCmd = (tagNetCmd*)(pMsgInsert->byData); pStream->FillString(", msg_data='"); pStream->FillBlob(pCmd, pCmd->dwSize, con); pStream->FillString("'"); m_pDBLoong->ReturnConnection(con); } VOID CLoongDB::FormatClearLeftMsg( Beton::MyStream *pStream, DWORD dwRoleID, LPVOID pData ) { pStream->Clear(); pStream->FillString("delete from left_msg where roleid=")<<dwRoleID; } BOOL CLoongDB::ClearLeftMsg( DWORD dwRoleID ) { return Update(dwRoleID, NULL, 1, 0, &CLoongDB::FormatClearLeftMsg); } BOOL CLoongDB::LoadLeftMsgIndexes( DWORD* pIndexes, DWORD dwRoleID, INT &nNum ) { LPVOID pData = (LPVOID)pIndexes; return Load(pData, &nNum, GT_INVALID, dwRoleID, &CLoongDB::FormatLoadLeftMsgIndexes, &CLoongDB::ProcResLoadLeftMsgIndexes); } VOID CLoongDB::FormatLoadLeftMsgIndexes( Beton::MyStream *pStream, DWORD dwDumy, DWORD dwRoleID ) { pStream->FillString("select msg_id from left_msg where roleid=") << dwRoleID; pStream->FillString(" order by msg_id asc"); } VOID CLoongDB::ProcResLoadLeftMsgIndexes( OUT LPVOID &pData, OUT INT32 *pNum, Beton::QueryResult *pRes ) { if (!P_VALID(pRes)) return; DWORD* pIndexes = (DWORD*)pData; INT nNum = pRes->GetRowCount(); INT i; for (i=0; i<nNum; ++i) { pIndexes[i] = (*pRes)[0].GetDword(); pRes->NextRow(); } if (P_VALID(pNum)) { *pNum = i; } } BOOL CLoongDB::UpdateRoleAtt( DWORD dwRoleID, PVOID pData ) { return Update(dwRoleID, pData, 1, sizeof(tagNDBC_UpdateRoleAtt), &CLoongDB::FormateUpdateRoleAtt); } BOOL CLoongDB::UpdateRoleAttPoint( DWORD dwRoleID, LPVOID pMsg ) { return Update(dwRoleID, pMsg, 1, sizeof(tagNDBC_UpdateRoleAttPoint), &CLoongDB::FormateUpdateRoleAttPoint); } BOOL CLoongDB::UpdateRoleTalentPoint( DWORD dwRoleID, LPVOID pMsg ) { return Update(dwRoleID, pMsg, 1, sizeof(tagNDBC_UpdateRoleTalentPoint), &CLoongDB::FormateUpdateRoleTalentPoint); } BOOL CLoongDB::UpdateRoleItemTranport( DWORD dwRoleID, LPVOID pMsg ) { return Update(dwRoleID, pMsg, 1, sizeof(tagNDBC_UpdateRoleItemTransport), &CLoongDB::FormateUpdateRoleItemTransport); } VOID CLoongDB::FormateUpdateRoleAtt( Beton::MyStream* pStream, DWORD dwRoleID, PVOID pData ) { MTRANS_POINTER(pRecv, pData, tagNDBC_UpdateRoleAtt); pStream->Clear(); pStream->SetUpdate("roledata"); switch(pRecv->nType) { case ERTSA_Exp: pStream->FillString("ExpCurLevel"); break; case ERTSA_Level: pStream->FillString("Level"); break; default: ASSERT(0); break; } pStream->FillString("=") << pRecv->nValue; pStream->SetWhere(); pStream->FillString("RoleID=") << dwRoleID; } VOID CLoongDB::FormateUpdateRoleAttPoint( Beton::MyStream* pStream, DWORD dwRoleID, PVOID pData ) { MTRANS_POINTER(pRecv, pData, tagNDBC_UpdateRoleAttPoint); pStream->Clear(); pStream->SetUpdate("roledata"); pStream->FillString("AttPtAvail=") << pRecv->nAttPointLeft; pStream->FillString(",PhysiqueAdded=") << pRecv->nAttPointAdd[0]; pStream->FillString(",StrengthAdded=") << pRecv->nAttPointAdd[1]; pStream->FillString(",PneumaAdded=") << pRecv->nAttPointAdd[2]; pStream->FillString(",InnerforceAdded=") << pRecv->nAttPointAdd[3]; pStream->FillString(",TechniqueAdded=") << pRecv->nAttPointAdd[4]; pStream->FillString(",AgilityAdded=") << pRecv->nAttPointAdd[5]; pStream->SetWhere(); pStream->FillString("RoleID=") << dwRoleID; } VOID CLoongDB::FormateUpdateRoleTalentPoint( Beton::MyStream* pStream, DWORD dwRoleID, PVOID pData ) { MTRANS_POINTER(pRecv, pData, tagNDBC_UpdateRoleTalentPoint); pStream->Clear(); pStream->SetUpdate("roledata"); std::stringstream str; str << "TalentType" << pRecv->nIndex+1 << "=" << pRecv->Talent.eType; str << ",TalentVal" << pRecv->nIndex+1 << "=" << pRecv->Talent.nPoint; pStream->FillString(str.str().c_str()); pStream->SetWhere(); pStream->FillString("RoleID=") << dwRoleID; } VOID CLoongDB::FormateUpdateRoleItemTransport( Beton::MyStream* pStream, DWORD dwRoleID, PVOID pData ) { MTRANS_POINTER(pRecv, pData, tagNDBC_UpdateRoleItemTransport); pStream->Clear(); pStream->SetUpdate("roledata"); pStream->FillString("ItemTransportMapID=") << pRecv->dwMapID; pStream->FillString(",ItemTransportX=") << pRecv->fX; pStream->FillString(",ItemTransportZ=") << pRecv->fZ; pStream->FillString(",ItemTransportY=") << pRecv->fY; pStream->SetWhere(); pStream->FillString("RoleID=") << dwRoleID; } INT32 CLoongDB::TestDBReadFunction() { // 获取流 Beton::MyStream* pStream = m_pDBLoong->GetStream(); // 格式化 pStream->SetSelect("roledata", "*"); pStream->SetWhere(); pStream->FillString("RoleID=") << m_dwMaxRoleID; // 查询数据库 Beton::QueryResult* pResult = m_pDBLoong->Query(pStream); if(P_VALID(pResult) && pResult->GetRowCount() > 0) { } else { // 释放流和结果 m_pDBLoong->ReturnStream(pStream); m_pDBLoong->FreeQueryResult(pResult); return E_SystemError; } // 释放流和结果 m_pDBLoong->ReturnStream(pStream); m_pDBLoong->FreeQueryResult(pResult); return E_Success; } BOOL CLoongDB::LoadRoleItemSerial( DWORD dwRoleID, PVOID &pData, INT &nNum, DWORD dwConType ) { return Load(pData, &nNum, dwConType, dwRoleID, &CLoongDB::FormatLoadRoleItemSerials, &CLoongDB::ProcResLoadRoleItemSerials); } // Jason 外部链接 v1.3.1 BOOL CLoongDB::LoadExtLinks(tagExternalLink *& links,int & num) { BOOL bRet = TRUE; num = 0; do { Beton::MyStream* pStream = m_pDBLoong->GetStream(); //ASSERT(P_VALID(pStream)); if( !P_VALID(pStream) ) break; pStream->Clear(); pStream->FillString ("select LinkName,LinkURL from external_links order by ID desc"); // 查询数据库 Beton::QueryResult* pResult = m_pDBLoong->Query(pStream); if(!P_VALID(pResult)) { bRet = FALSE; m_pDBLoong->ReturnStream(pStream); break; } num = pResult->GetRowCount(); if (num > 0) { void * p = g_MemPoolSafe.Alloc ( sizeof(tagExternalLink) * num ); memset(p,0, sizeof(tagExternalLink) * num ); tagExternalLink * pLink = (tagExternalLink *)p; links = pLink; int l = 8; LPCTSTR pStr = NULL; Util util; num = num > 6 ? 6 : num; for(int i = 0; i < num ; ++i) { pStr = util.Unicode8ToUnicode ((*pResult)[0].GetString()); if( _tcslen(pStr) > 8 - 1 ) l = 8 - 1; else l = _tcslen(pStr); _tcsncpy(pLink[i].linkName , pStr, l) ; pStr = util.Unicode8ToUnicode ((*pResult)[1].GetString()); if( _tcslen(pStr) > X_LONG_NAME - 1 ) l = X_LONG_NAME - 1; else l = _tcslen(pStr); _tcsncpy(pLink[i].linkValue , pStr, l) ; pResult->NextRow (); } } else { bRet = FALSE; } // 释放流和结果 m_pDBLoong->ReturnStream(pStream); m_pDBLoong->FreeQueryResult(pResult); } while (0); return bRet; } VOID CLoongDB::FormatLoadRoleItemSerials( Beton::MyStream *pStream, DWORD dwMisc, DWORD dwRoleID ) { DWORD dwConType = dwMisc & 0xff; DWORD dwBind = (dwMisc >> 16) & 0xff; pStream->Clear(); pStream->SetSelect("item", "SerialNum, TypeID"); pStream->SetWhere(); pStream->FillString("OwnerID=") << dwRoleID; pStream->FillString(" and ContainerTypeID=") << dwConType; pStream->FillString(" and Bind=") << dwBind; } VOID CLoongDB::ProcResLoadRoleItemSerials( OUT LPVOID &pData, OUT INT32 *pNum, Beton::QueryResult *pRes ) { if (!P_VALID(pRes)) return; tagItemData* pItemData = (tagItemData*)pData; INT nNum = pRes->GetRowCount(); INT i = 0; for (i=0; i<nNum; ++i) { pItemData[i].n64Serial = (*pRes)[0].GetLong(); pItemData[i].dwTypeID = (*pRes)[1].GetDword(); pRes->NextRow(); } if (P_VALID(pNum)) { *pNum = i; } } // Jason 2010-1-15 v1.3.2 离线挂机 VOID CLoongDB::OfflineExperienceReward(DWORD AccountID,DWORD RoleID) { #if 0 Beton::MyStream* pStream = m_pDBLoong->GetStream(); //ASSERT(P_VALID(pStream)); if( P_VALID(pStream) ) { //for(int i = 0; i < 3; ++i) //{ pStream->Clear(); pStream->FillString ("update roledata set OfflineExperienceRewardFlag=0 where AccountID = ") << AccountID ; pStream->FillString( " and RoleID != " ) << RoleID; m_pDBLoong->Execute(pStream); //if( m_pDBLoong->Execute(pStream) ) // break; //} //for(int i = 0; i < 3; ++i) //{ pStream->Clear(); pStream->FillString ("update roledata set OfflineExperienceRewardFlag=1 where AccountID = ") << AccountID ; pStream->FillString( " and RoleID = " ) << RoleID; m_pDBLoong->Execute(pStream); //if( m_pDBLoong->Execute(pStream) ) // break; //} } #endif } DWORD CLoongDB::GetAccountInfo( DWORD dwAccountID,tagDWORDTime& timeLastLogin,tagDWORDTime& timeLastLogout, tagDWORDTime& timeLastReceiveDailyOfflineReward, tagDWORDTime& timeLastReceiveRegression ) { Beton::MyStream* pStream = m_pDBLoong->GetStream(); //ASSERT(P_VALID(pStream)); if( P_VALID(pStream) ) { pStream->Clear(); pStream->FillString ("select LastLoginTime ,LastLogoutTime ,LastReceiveDailyOfflineRewardTime ,LastReceiveRegressionTime from account_common where AccountID = ") << dwAccountID ; Beton::QueryResult* Query = m_pDBLoong->Query(pStream); if( P_VALID(Query) ) { if( Query->GetRowCount() > 0 ) { timeLastLogin = (*Query)[0].GetDword(); timeLastLogout = (*Query)[1].GetDword(); timeLastReceiveDailyOfflineReward = (*Query)[2].GetDword(); timeLastReceiveRegression = (*Query)[3].GetDword(); m_pDBLoong->FreeQueryResult(Query); if( timeLastLogin == 0 || timeLastLogout == 0 ) { pStream->Clear(); pStream->FillString ("select LoginTime ,LogoutTime from roledata where AccountID = ") << dwAccountID ; pStream->FillString (" order by LogoutTime desc"); Beton::QueryResult* Query1 = m_pDBLoong->Query(pStream); if( P_VALID(Query1) ) { if( Query1->GetRowCount () > 0 ) { tagDWORDTime tem; const CHAR * buf = (*Query1)[0].GetString(); if( DataTime2DwordTime(tem,buf,strlen(buf)) ) timeLastLogin = tem; buf = (*Query1)[1].GetString(); if( DataTime2DwordTime(tem,buf,strlen(buf)) ) timeLastLogout = tem; } m_pDBLoong->FreeQueryResult(Query1); } } m_pDBLoong->ReturnStream(pStream); return 0; } m_pDBLoong->FreeQueryResult(Query); } m_pDBLoong->ReturnStream(pStream); } return GT_INVALID; } DWORD CLoongDB::SaveAccountInfo( DWORD dwAccountID,tagDWORDTime timeLastLogin,tagDWORDTime timeLastLogout, tagDWORDTime timeLastReceiveDailyOfflineReward, tagDWORDTime timeLastReceiveRegression ) { Beton::MyStream* pStream = m_pDBLoong->GetStream(); //ASSERT(P_VALID(pStream)); if( P_VALID(pStream) ) { pStream->Clear(); pStream->FillString ("update account_common set LastLoginTime = ") << timeLastLogin; pStream->FillString(",LastLogoutTime = ") << timeLastLogout; pStream->FillString(",LastReceiveDailyOfflineRewardTime = ") << timeLastReceiveDailyOfflineReward; pStream->FillString(",LastReceiveRegressionTime = ") << timeLastReceiveRegression; pStream->FillString(" where AccountID = ") << dwAccountID ; if( m_pDBLoong->Execute ( pStream ) ) { m_pDBLoong->ReturnStream(pStream); return 0; } m_pDBLoong->ReturnStream(pStream); } return GT_INVALID; } VOID CLoongDB::DoWhenWorldCrashDown( ) { //Beton::MyStream* pStream = m_pDBLoong->GetStream(); ////ASSERT(P_VALID(pStream)); //if( P_VALID(pStream) ) //{ // pStream->Clear(); // pStream->FillString ("update account_common set LastLogoutTime = ") << (DWORD)GetCurrentDWORDTime(); // pStream->FillString(" where LastLoginTime > LastLogoutTime"); // m_pDBLoong->Execute ( pStream ); // m_pDBLoong->ReturnStream(pStream); //} } // 取所有仇敌列表中有角色ID为dwRoleID的角色的ID BOOL CLoongDB::GetRoleListOfEnemy(DWORD dwRoleID, DWORD dwRoleIDList[], DWORD &dwRoleCnt) { Beton::MyStream* pStream = m_pDBLoong->GetStream(); //ASSERT(P_VALID(pStream)); if( !P_VALID(pStream) ) { return FALSE; } pStream->Clear(); pStream->FillString ("select RoleID from enemy where EnemyID=") << dwRoleID; Beton::QueryResult* pResult = m_pDBLoong->Query(pStream); if(!P_VALID(pResult)) { // 释放流 m_pDBLoong->ReturnStream(pStream); dwRoleCnt = 0; return FALSE; } if( pResult->GetRowCount() > 0 ) { dwRoleCnt = (pResult->GetRowCount() > dwRoleCnt) ? dwRoleCnt : pResult->GetRowCount(); for (int nCnt = 0; nCnt < dwRoleCnt; nCnt++) { dwRoleIDList[nCnt] = (*pResult)[0].GetDword(); pResult->NextRow(); } } else { dwRoleCnt = 0; } // 释放流 m_pDBLoong->ReturnStream(pStream); m_pDBLoong->FreeQueryResult(pResult); return TRUE; } DWORD CLoongDB::SaveOlInfo(INT num,VOID * pData) { if( num <= 0 || !P_VALID(pData)) return GT_INVALID; tagWorldMapOnlineInfo * pOlData = (tagWorldMapOnlineInfo*)pData; Beton::MyStream* pStream = m_pDBLoong->GetStream(); //ASSERT(P_VALID(pStream)); if( P_VALID(pStream) ) { while( num-- > 0 ) { pStream->Clear(); pStream->FillString ("REPLACE mapolinfo SET MapID = ") << pOlData->dwMapID; pStream->FillString(",IsInst = ") << pOlData->bIsInst; pStream->FillString(",OnlineNum = ") << pOlData->nOnlineNum; pStream->FillString(",OpenNum = ") << pOlData->nOpenNum; pStream->FillString(" ,RecTime = now()") ; m_pDBLoong->Execute ( pStream ) ; ++pOlData; } m_pDBLoong->ReturnStream(pStream); return 0; } return GT_INVALID; } //------------------------------------------------------------------------------ DWORD CLoongDB::DelOneBuff( DWORD dwRoleID, DWORD dwBuffID ) { Beton::MyStream* pStream = m_pDBLoong->GetStream(); if(!P_VALID(pStream)) return FALSE; pStream->Clear(); pStream->SetDelete("buff"); pStream->SetWhere(); pStream->FillString("RoleID=") << dwRoleID; pStream->FillString(" and BuffID=") << dwBuffID; BOOL bRes = m_pDBLoong->Execute(pStream); m_pDBLoong->ReturnStream(pStream); return bRes; } //------------------------------------------------------------------------------ DWORD CLoongDB::InsertBuffDirectly(DWORD dwRoleID,tagBuffSave * pBuffSave) { if( !P_VALID(pBuffSave) ) return GT_INVALID; Beton::MyStream* pStream = m_pDBLoong->GetStream(); if( P_VALID(pStream) ) { pStream->Clear(); pStream->FillString ("INSERT INTO buff set RoleID = ") << dwRoleID; pStream->FillString(",SrcUnitID = ") << pBuffSave->dwSrcUnitID; pStream->FillString(",SrcSkillID = ") << pBuffSave->dwSrcSkillID; pStream->FillString(",ItemTypeID = ") << pBuffSave->dwItemTypeID; pStream->FillString(",ItemSerialID = ") << pBuffSave->n64Serial ; pStream->FillString(",BuffID = ") << pBuffSave->dwBuffID; pStream->FillString(",CurTick = ") << pBuffSave->nPersistTick ; pStream->FillString(",Level = ") << pBuffSave->n8Level; pStream->FillString(",CurLapTimes = ") << pBuffSave->n8CurLapTimes ; if( m_pDBLoong->Execute ( pStream ) ) { m_pDBLoong->ReturnStream(pStream); return E_Success; } m_pDBLoong->ReturnStream(pStream); } return GT_INVALID; } //----------------------------------------------------------------- DWORD CLoongDB::DelItemdelByTime(const CHAR *pszTime) { if( !P_VALID(pszTime) ) return GT_INVALID; if(DelEquipDel(pszTime)) { return E_Success; } return GT_INVALID; } //----------------------------------------------------------------- DWORD CLoongDB::DelEquipdelByTime(const CHAR *pszTime) { if( !P_VALID(pszTime) ) return GT_INVALID; if( DelEquipDel(pszTime) ) { if(DelItemDel(pszTime)) { return E_Success; } } return GT_INVALID; } //----------------------------------------------------------------- // VOID CLoongDB::IsLoadShengLing(Beton::MyStream *pStream) // { // if(!isOpenShengLing()) // { // //这个不要了 // //pStream->FillString(" and TypeID not in (9800001,9800002,9800003,9800004,9850001,9850002,9850003,9850004,9850005,9850006,9850007,9850008,9850101,9850102,9850103,9850104,9850105,9850106,9850107,9850108,9850201,9850202,9850203,9850204,9850205,9850206,9850207,9850208,3500001,3500002,3500003,3500004,3500005,3500010,3500011,3500012,3500013,3500014,3500015,3500021,3500022,3500031)"); // } // } VOID CLoongDB::GetYuanBaoDaiBiNum(INT32 &nNum, DWORD dwRoleID) { nNum = 0; // 获取流 Beton::MyStream* pStream = m_pDBLoong->GetStream(); // 格式化 pStream->SetSelect("ReciveYuanBaoDaiBi", "Num"); pStream->SetWhere(); pStream->FillString("RoleID=") << dwRoleID; // 查询数据库 Beton::QueryResult* pResult = m_pDBLoong->Query(pStream); if(P_VALID(pResult) && pResult->GetRowCount() > 0) { nNum = (*pResult)[0].GetInt(); } //++m_dwReadTimes; BOOL bRet = TRUE; // 获取流 Beton::MyStream* pStream1 = m_pDBLoong->GetStream(); ASSERT(P_VALID(pStream1)); // 格式化数据库操作语句 pStream1->SetDelete("ReciveYuanBaoDaiBi"); pStream1->SetWhere(); pStream1->FillString("RoleID=") << dwRoleID; // 执行 bRet = m_pDBLoong->Execute(pStream1); // 释放流 m_pDBLoong->ReturnStream(pStream1); }
5d304c74819944c4f7275c2b60ff06e6d8ba0046
6a66d041994187166eb3ea74762f82bca100aa3c
/src/entities/PhysicalSensor.hpp
72ed662307b0c35a29cc647b04a6e267a1abbdac
[ "BSD-3-Clause" ]
permissive
TheTosters/Home-Control-Base-Station
932aca2636d69a93f7f3604dabecd0acf611a51d
c9f33918c3b35f5a0666c9c6d097e9e1313e9e0a
refs/heads/dev
2021-01-13T13:40:56.842584
2017-05-08T08:49:07
2017-05-08T08:49:07
76,362,550
1
0
null
2017-05-08T08:49:07
2016-12-13T13:47:20
C++
UTF-8
C++
false
false
3,458
hpp
PhysicalSensor.hpp
// // PhysicalSensor.hpp // HomeControl // // Created by Bartłomiej on 30/12/16. // Copyright © 2016 Imagination Systems. All rights reserved. // #ifndef PhysicalSensor_hpp #define PhysicalSensor_hpp #include <stdio.h> #include <string> #include <vector> #include <inttypes.h> #include "entities/Entity.hpp" #include "entities/SensorValue.hpp" #include <unordered_set> using namespace std; enum PhysicalSensorType { PhysicalSensorType_TEMPERATURE = 1U << 0, PhysicalSensorType_POWER_SOURCE_LEVEL = 1U << 8, PhysicalSensorType_HUMIDITY, PhysicalSensorType_POWER_CONSUMPTION, }; enum PhysicalSensorPowerSaveMode { PhysicalSensorPowerSaveMode_1 }; enum PhysicalSensorPowerSaveActivity { PhysicalSensorPowerSaveActivity_1 }; extern const unordered_set<PhysicalSensorType, hash<int>> KNOWN_PHYSICAL_SENSOR_TYPES; class PhysicalSensorMetaData { public: string softwareVersion; PhysicalSensorPowerSaveMode powerMode; PhysicalSensorPowerSaveActivity powerActivity; int powerPeroid; int temperatureResolution; int temperaturePeriod; uint64_t nodeSystemTime; PhysicalSensorMetaData(); }; /** * This class is for having instance of other physical device which we can contact to get measurements. * It's not this same as Sensor, which is more like logical representation of Physical sensor in rooms. * This object should have all properties needed to communicate with physical device, such as encryption keys etc. * NOTE: Id is retrieved from physical device (same as address) it is possible to have collisions, this is * communication/logic layer resposibility to not allow such situation. Since this object id is used in SensorValue * this can bring total mess in db. Be warned. */ class PhysicalSensor : public Entity { public: PhysicalSensor(); virtual ~PhysicalSensor(); void setName(string const& name); string& getName(); void setAddress(string const& address); string& getAddress(); void addType(PhysicalSensorType type); vector<PhysicalSensorType>& getType(); void setLastFetchTime(time_t value); time_t getLastFetchTime(); void setDesiredFetchDelay(time_t value); time_t getDesiredFetchDelay(); void setLastMeasurements(MeasurementMap data); MeasurementList& getLastMeasurements(); bool isType(PhysicalSensorType type); shared_ptr<Measurement> getLastMeasurement(PhysicalSensorType type); PhysicalSensorMetaData* getMetadata(); protected: string name; string address; //it can be MAC, Bluetooth address, or other protocol dependent vector<PhysicalSensorType> types; /** Timestamp of last connection to physical device with request for measurements */ time_t lastFetchTime; /** Config related value, informs about intervals in which communication with Physical device should be done. It's minimal value which should be waited before new fetch is tried */ time_t desiredFetchDelay; /** List with the newest values fetch from physical device */ MeasurementList lastMeasurements; PhysicalSensorMetaData* metaData; void updateLastMeasurement(SensorValueType valType, double value, time_t time); }; typedef vector<shared_ptr<PhysicalSensor>> PhysicalSensorVector; typedef shared_ptr<PhysicalSensorVector> PhysicalSensorList; #endif /* PhysicalSensor_hpp */
a601d62d6a051a3cf4e6b7bdf49c82d2a49c0965
9074ea06744314cf8dce2134872eed0609a3670f
/TD4/Exercice3PileFile/CFile.cpp
c2f773d00c912be064e0953076002ea0ee5eb434
[]
no_license
Nambrok/IN505_Langages_Avancees
dae474a167999b67d06d8b507a54711634b5486a
4032b09b42b3da824ccaa03dad5272032c24b2fb
refs/heads/master
2021-01-13T08:17:59.012758
2016-12-13T15:18:23
2016-12-13T15:18:23
69,956,323
0
0
null
null
null
null
UTF-8
C++
false
false
325
cpp
CFile.cpp
using namespace std; class CFile: public CList{ public: CFile(); ~CFile(); CFile& operator<(int i); }; CFile& CFile::operator<(int i){ if(tete != NULL){ Noeud* act = tete; while(act->getNext() != NULL){ act = act->getNext(); } act->setNext(new Noeud(i)); taille++; return *this; } }
c8ad7e2ea247c0fa0aa5607188c84bcd5a1f638d
da9af0a8a815bb11e03ac70f9f0930afb7a173e1
/code/main.cpp
fa813dc1ab19e53e1bfc46879a9c3546482a2b08
[]
no_license
zhuxiaoyou2011qp/ChangeDesktopBackground
ad61d17ce9179035ba13e48fec3ca5789841767a
2fc396005b7b97613f6e3b425ab7f95afe92883e
refs/heads/master
2020-12-24T18:14:04.515647
2017-02-20T12:36:59
2017-02-20T12:36:59
56,961,181
0
0
null
null
null
null
GB18030
C++
false
false
6,939
cpp
main.cpp
//--------------------------------------------------------------------------- #pragma hdrstop //--------------------------------------------------------------------------- #include <iostream> //for string #include <fstream> //for fstream #include <winsock2.h> //for SOCKET #include <io.h> //for access #include "cJSON.h" //for JSON #include <jpeg.hpp> //for TJPEGImage // TODO:use libjpeg djpeg get the BMP using namespace std; char host[500]; //主机域名 char othPath[800]; //资源地址 SOCKET sock; //建立的socket实例 #define JSON_FILE_NAME "BIN.json" bool analyUrl(char *url)//仅支持http协议,解析出主机和IP地址 { char *pos = strstr(url, "http://"); if(pos == NULL) return false; else pos +=7; sscanf(pos, "%[^/]%s", host, othPath); cout<<"host:"<<host<<" repath:"<<othPath<<endl; return true; } void preConnect() //socket进行网络连接 { WSADATA wd; WSAStartup(MAKEWORD(2, 2), &wd); sock = socket(AF_INET, SOCK_STREAM, 0); if(sock == INVALID_SOCKET) { cout<<"建立socket失败!错误码:"<<WSAGetLastError()<<endl; return; } sockaddr_in sa = { AF_INET }; int n = bind(sock, (sockaddr*)&sa, sizeof(sa)); if(n == SOCKET_ERROR) { cout<<"bind函数失败!错误码:"<<WSAGetLastError()<<endl; return; } struct hostent *p = gethostbyname(host); //TODO: declare host if(p == NULL) { cout<<"主机无法解析ip!错误码:"<<WSAGetLastError()<<endl; return; } sa.sin_port = htons(80); memcpy(&sa.sin_addr, p->h_addr, 4); //cout<<*(p->h_addr_list)<<endl; n = connect(sock, (sockaddr*)&sa, sizeof(sa)); if(n == SOCKET_ERROR) { cout<<"Connect函数失败!错误码:"<<WSAGetLastError()<<endl; return; } //向服务器发起GET请求,下载图片 string reqInfo = "GET "+(string)othPath + " HTTP/1.1\r\nHost: "+(string)host + "\r\nConnection:Close\r\n\r\n"; if(SOCKET_ERROR == send(sock, reqInfo.c_str(), reqInfo.size(), 0)) { cout<<"send error!错误码:"<<WSAGetLastError()<<endl; return; } } void outImage(string imageUrl) { char cImageUrl[800] = {0}; strcpy(cImageUrl, imageUrl.c_str()); analyUrl(cImageUrl); preConnect(); string photoname; size_t iPos = imageUrl.rfind('/'); photoname = imageUrl.substr(iPos+1, imageUrl.length()-iPos); /* photoname.resize(imageUrl.size()); int k = 0; for(int i=0; i<imageUrl.length(); i++) { char ch = imageUrl[i]; if( ch!='\\' && ch!=':' && ch!='/'&& ch!='*' && ch!='?' && ch!='"' && ch!='<' && ch!='>' && ch!='|' ) { photoname[k++] = ch; } } photoname = "./img/"+photoname.substr(0, k)+".jpg";*/ photoname = "img//"+photoname; if(access(photoname.c_str(), 0) == 0) { try { //Windows的SystemParametersInfo接口对图片图片特别挑剔,一定要BMP格式的,本处则先把jpeg转换为BMP,然后在转回jpeg,这样也能设置成功 if(photoname.substr(photoname.length()-4,4)==".jpg" ); { Graphics::TBitmap *pBitmap = new Graphics::TBitmap(); TJPEGImage * aJpeg=new TJPEGImage(); aJpeg->LoadFromFile(photoname.c_str()); pBitmap->Assign(aJpeg); aJpeg->Assign(pBitmap); aJpeg->CompressionQuality = 80; aJpeg->SaveToFile(photoname.c_str()); } if(SystemParametersInfo(SPI_SETDESKWALLPAPER, 0, (PVOID)photoname.c_str(), SPIF_UPDATEINIFILE | SPIF_SENDCHANGE)== false) { DWORD DWLastError = GetLastError(); cout << "\nError: "<< DWLastError; cout<<"设置桌面背景失败"<<endl; } }catch(...) { ; } return; //如果存在直接返回 } fstream file; file.open(photoname.c_str(), ios::out | ios::binary); char buf[1024]; memset(buf, 0, sizeof(buf)); int n = recv(sock, buf, sizeof(buf)-1, 0); char *cpos = strstr(buf, "\r\n\r\n"); file.write(cpos+strlen("\r\n\r\n"), n- (cpos - buf) - strlen("\r\n\r\n")); while( (n = recv(sock, buf, sizeof(buf)-1, 0)) > 0) { file.write(buf, n); } file.close(); try { SystemParametersInfoA(SPI_SETDESKWALLPAPER, 0, (PVOID)photoname.c_str(), SPIF_UPDATEINIFILE | SPIF_SENDCHANGE); }catch(...) { ; } } void outJson(string jsonUrl) { char cJsonUrl[800] = {0}; strcpy(cJsonUrl, jsonUrl.c_str()); analyUrl(cJsonUrl); preConnect(); string jsonname = JSON_FILE_NAME; fstream file; file.open(jsonname.c_str(), ios::out | ios::binary); char buf[2048]; memset(buf, 0, sizeof(buf)); int n = recv(sock, buf, sizeof(buf)-1, 0); char *cpos = strstr(buf, "\r\n\r\n"); file.write(cpos+strlen("\r\n\r\n"), n- (cpos - buf) - strlen("\r\n\r\n")); while( (n = recv(sock, buf, sizeof(buf)-1, 0)) > 0) { file.write(buf, n); } file.close(); } bool GetImageURLFromJsonFile(string jsonname, char *cOut) { bool bRet = true; FILE *f; long len;char *data; f = fopen(jsonname.c_str(), "rb");fseek(f, 0, SEEK_END); len=ftell(f);fseek(f, 0, SEEK_SET); data = (char *)malloc(len+1); fread(data, 1, len, f); fclose(f); //读取文件 char *out; cJSON *json;cJSON *image;cJSON *url; json = cJSON_Parse(data); //解析 image = cJSON_GetObjectItem(json, "images"); url = cJSON_GetObjectItem(cJSON_GetArrayItem(image, 0), "url"); printf("%s", cJSON_Print(url)); char cTemp[256] = {0}; // strcpy(cOut, cJSON_Print(url)); //因为存在'"',不能直接拷贝 strcpy(cTemp, cJSON_Print(url)); // remove the '"' int k=0; for(int i=0; i<=strlen(cTemp); i++) { if(cTemp[i]!='"') { cOut[k++] = cTemp[i]; } } cOut[k] = '\0'; if(!json) { printf("Error before: [%s]\n", cJSON_GetErrorPtr()); bRet = false;} else { bRet = false; } free(data); return bRet; } #pragma argsused int main(int argc, char* argv[]) { if (access("./img", 0)!=0) { CreateDirectory("./img", 0); //在工程下创建文件夹 } string startURL = "http://cn.bing.com/HPImageArchive.aspx?format=js&idx=0&n=1&nc=1439260838289&pid=hp&video=1"; outJson(startURL); //下载startUrl对应的Json文件 //获取BIN图片的路径 char cPath[256] = {0}; GetImageURLFromJsonFile(JSON_FILE_NAME, cPath); string bingImageUrl = "http://"+string(host)+ string(cPath); outImage(bingImageUrl.c_str()); // outImage("http://cn.bing.com/az/hprichbg/rb/Vieste_ZH-CN7832914637_1920x1080.jpg"); return 0; } //---------------------------------------------------------------------------
48ef50bfe50c6507a24874e87eb4e4d5abb3a985
12e2bae461c22579785453f6676cfe375e3de6e2
/FileSearchUtility/FileSearchUtility.h
30d482a27e05de59cd332489abbaab148d48ab1b
[ "MIT" ]
permissive
koronabora/FileSearchUtility
952dab7cee47fd342903ae21e2fbd61ba6120330
8e7df67f0f38cb098f278e5f46fb915c41db42be
refs/heads/master
2021-05-17T15:50:41.947304
2020-04-30T08:02:55
2020-04-30T08:02:55
250,854,629
0
0
null
null
null
null
UTF-8
C++
false
false
1,964
h
FileSearchUtility.h
#pragma once #include <QtWidgets/QMainWindow> #include <QPointer> #include <QPushButton> #include <QLineEdit> #include <QGroupBox> #include <QPlainTextEdit> #include <QTableView> #include <QFileDialog> #include <QTimer> #include <QColor> #include "ui_FileSearchUtility.h" #include "Structs.h" #include "FilesModel.h" #define REGEXP_PARSING_DELAY 1000 // delay before starting to parse regexp after user input static const QColor REGEXP_IS_VALID_COLOR = QColor(102, 255, 51, 51); static const QColor REGEXP_IS_INVALID_COLOR = QColor(255, 153, 51, 51); //#define ALLOW_EMPTY_CONDIION class FileSearchUtility : public QMainWindow { Q_OBJECT public: FileSearchUtility(QWidget *parent = Q_NULLPTR); ~FileSearchUtility(); public slots: void setStatus(const QString& text); void regexpValidated(RegexpValidateData data); void haveSomeFile(const QString& path, const quint64& size); void searchFinished(); private slots: void conditionTextChanged(); void selectFolderButtonClicked(); void searchButtonClicked(); void testRegex(); private: Ui::FileSearchUtilityClass ui; bool searchState = false; void updateTranslations(); QVector<quint64> pendigRegexps; QPointer<QTimer> regexpParseTimer; quint64 lastId = 0; RegexpValidateData currentRegexp; // path QPointer<QGroupBox> folderGroupBox; QPointer<QLineEdit> searchPathEdit; QPointer<QPushButton> selectPathButton; // condition QPointer<QGroupBox> conditionGroupBox; QPointer<QPlainTextEdit> conditionEdit; QPointer<QPushButton> searchButton; void setConditionFieldColor(const QColor& v); void updateSearchButtonText(); // results QPointer<QGroupBox> resultsGroupBox; QPointer<QTableView> resultsTable; QPointer<FilesModel> model; QPointer<FileSortProxyModel> proxyModel; // status bar QPointer<QStatusBar> statusBar; signals: void validateRegexp(RegexpValidateData data); void searchForFiles(const QString& path, const RegexpValidateData& regexp); void stopSearch(); };
6406cfddd2eec863a33bfc6cc80cd1df7f48df67
2d361696ad060b82065ee116685aa4bb93d0b701
/src/gui/packages/pkg_sequence_edit/indexer_app_mode.hpp
31134cb9f5a3f0ad1bf3b0e99afd99a4cd3237ea
[ "LicenseRef-scancode-public-domain" ]
permissive
AaronNGray/GenomeWorkbench
5151714257ce73bdfb57aec47ea3c02f941602e0
7156b83ec589e0de8f7b0a85699d2a657f3e1c47
refs/heads/master
2022-11-16T12:45:40.377330
2020-07-10T00:54:19
2020-07-10T00:54:19
278,501,064
1
1
null
null
null
null
UTF-8
C++
false
false
2,357
hpp
indexer_app_mode.hpp
#ifndef PKG_SEQUENCE_EDIT___INDEXER_APP_MODE__HPP #define PKG_SEQUENCE_EDIT___INDEXER_APP_MODE__HPP /* $Id: indexer_app_mode.hpp 39241 2017-08-28 15:44:36Z katargir $ * =========================================================================== * * PUBLIC DOMAIN NOTICE * National Center for Biotechnology Information * * This software/database is a "United States Government Work" under the * terms of the United States Copyright Act. It was written as part of * the author's official duties as a United States Government employee and * thus cannot be copyrighted. This software/database is freely available * to the public for use. The National Library of Medicine and the U.S. * Government have not placed any restriction on its use or reproduction. * * Although all reasonable efforts have been taken to ensure the accuracy * and reliability of the software and data, the NLM and the U.S. * Government do not and cannot warrant the performance or results that * may be obtained by using this software or data. The NLM and the U.S. * Government disclaim all warranties, express or implied, including * warranties of performance, merchantability or fitness for any particular * purpose. * * Please cite the author in any work or product based on this material. * * =========================================================================== * * Authors: Roman Katargin * * File Description: * */ #include <corelib/ncbistd.hpp> #include <corelib/ncbiobj.hpp> #include <gui/framework/app_mode_extension.hpp> #include <gui/utils/extension.hpp> class wxCommandEvent; BEGIN_NCBI_SCOPE class CWorkbench; class CIndexerAppModeExtension : public CObject, public IAppModeExtension, public IExtension { public: CIndexerAppModeExtension(); /// @name IExtension interface implementation /// @{ virtual string GetExtensionIdentifier() const; virtual string GetExtensionLabel() const; /// @} /// @name IAppModeExtension interface implementation /// @{ virtual string GetModeName() const; virtual void SetWorkbench(CWorkbench* wb); /// @} void OnFileOpen(wxCommandEvent& event); void OnCloseWorkspace(wxCommandEvent& event); private: CWorkbench* m_Workbench; }; END_NCBI_SCOPE #endif // PKG_SEQUENCE_EDIT___INDEXER_APP_MODE__HPP
821a87c1eaba71de0f3868ee98d5286f65ee2588
24dec428c42a4835208950cef330016419ce06fc
/src/trienode.hpp
9d18b374dc88ae648e0e7b31dc0a089b3ef0e524
[]
no_license
tmager/COMP150-lzw
7c134ccbdf168e8d9193855463eb0342d24eaec0
f76c4efb2ad2a63f3bbe24ece08da5c11afe1f53
refs/heads/master
2021-01-20T09:55:13.872474
2017-05-13T20:22:58
2017-05-13T20:22:58
90,301,684
0
0
null
null
null
null
UTF-8
C++
false
false
741
hpp
trienode.hpp
#include <stdint.h> #ifndef __TRIENODE_HPP__ #define __TRIENODE_HPP__ #define NCHILDREN (256) class TrieNode { public: TrieNode(uint8_t _sym, uint64_t _code, uint64_t _data, TrieNode *_parent); ~TrieNode(); uint8_t getSymbol(); uint64_t getCode(); uint64_t getData(); bool isLeaf(); bool hasChild(uint8_t childsym); TrieNode *getChild(uint8_t childsym); TrieNode *getParent(); void setCode(uint64_t _code); void setData(uint64_t _data); void addChild(TrieNode *child); void removeChild(uint8_t childsym); private: uint8_t sym; uint64_t code, data; int nchildren; TrieNode *parent; TrieNode *children[NCHILDREN]; }; #endif /* __TRIENODE_HPP__ */
87eb646e449df1254155d8fd56de6ddd6f5bbdad
193f6b964b1a030d1e819ca4932fb2b829e2e41c
/Framework/Render/Material.h
a609aa7e290bb7cae2e975551d7d8f0ae3a86a0a
[]
no_license
fkem79/DX11_Team_HomeSweetHome
cef13f869bee16fb2bbfe401364a2d4293925b2f
27b5b45ddcaaa407eb7e385f0ac63bdbd75c46e2
refs/heads/master
2021-05-18T20:34:29.754175
2020-05-10T16:37:20
2020-05-10T16:37:20
251,392,881
1
0
null
2020-05-08T12:57:25
2020-03-30T18:25:32
C++
UTF-8
C++
false
false
1,111
h
Material.h
#pragma once class Material { public: class MaterialBuffer : public ConstBuffer { public: struct Data { Float4 diffuse; Float4 specular; Float4 ambient; }data; MaterialBuffer() : ConstBuffer(&data, sizeof(Data)) { data.diffuse = Float4(1, 1, 1, 1); data.specular = Float4(1, 1, 1, 1); data.ambient = Float4(1, 1, 1, 1); } }; string name; private: Shader* shader; MaterialBuffer* buffer; Texture* diffuseMap; Texture* specularMap; Texture* normalMap; public: Material(); Material(wstring shaderFile); ~Material(); void Set(); MaterialBuffer* GetBuffer() { return buffer; } void SetShader(Shader* shader) { this->shader = shader; } void SetShader(wstring file) { shader = Shader::Add(file); } void SetDiffuseMap(wstring file) { diffuseMap = Texture::Add(file); } void SetSpecularMap(wstring file) { specularMap = Texture::Add(file); } void SetNormalMap(wstring file) { normalMap = Texture::Add(file); } Texture* GetDiffuseMap() { return diffuseMap; } Texture* GetSpecularMap() { return specularMap; } Texture* GetNormalMap() { return normalMap; } };
7f56baecd426a3e8c88e58224bef8067bebba590
0ae19202ccf1aec551a5d875d4a1ee99e891e0d4
/1.Classes&Inheritance/Hero.cpp
4f89a2b803502355118cd5ee449e7a96ff66e7c5
[]
no_license
JamGrif/Computer-Games-Programming-Exercises
442ad2404d63232f100879bfeef4550f8ea66630
5f15e4e2eb38614e4dd8a59c01a6d078de192a15
refs/heads/master
2020-07-31T14:38:29.358668
2019-10-07T20:41:12
2019-10-07T20:41:12
210,635,287
0
0
null
null
null
null
UTF-8
C++
false
false
692
cpp
Hero.cpp
#include "Hero.h" Hero::Hero(int x, int y, std::string Name, int Lives) :Creature(x,y,Name) { m_Lives = Lives; m_Score = 0; } void Hero::display() { Creature::display(); std::cout << m_Name << " has " << m_Lives << " lives" << std::endl; //std::cout << m_Name << " score is " << m_Score << std::endl; } int Hero::GetLives() { return m_Lives; } void Hero::Respawn() { //random x between -50 and 50 int Range = (50 - -50) + 1; m_Xpos = -50 + rand() % Range; //random y between -50 and 50 Range = (50 - -50) + 1; m_Ypos = -50 + rand() % Range; std::cout << m_Name << " has respawned at " << m_Xpos << " and " << m_Ypos << std::endl; } void Hero::LoseLife() { m_Lives--; }
101e81d29f73d43bac2c02ec86a221ecd37d6e4f
eda4e88a12782648cab63618865067aa489d89b9
/CodeSprint2014_Qualification1/4bigger-is-greater-English.cpp
5df11738496da04e2b67657f7facff4f8266e9e8
[]
no_license
ajayporwal/Hacker_Rank
bec2fb0d4fe7df3dd79840d9add164e5624a5f9f
5de607be030fcd1e4098f5fdd502add74eaae41a
refs/heads/master
2016-09-06T00:28:11.119510
2014-09-19T06:26:56
2014-09-19T06:26:56
null
0
0
null
null
null
null
UTF-8
C++
false
false
383
cpp
4bigger-is-greater-English.cpp
/*https://www.hackerrank.com/ajayporwal www.hackerrank.com/indian__*/ #include <stdio.h> #include<string.h> #include<algorithm> #include<iostream> using namespace std; int main() { int t; char w[110], z[110]; cin>>t; while(t--) { cin>>w; strcpy(z,w); next_permutation(w,w+strlen(w)); if(strcmp(w,z)<=0) printf("no answer\n"); else cout<<w<<endl; } return 0; }
1f7e81023d8861e0b412d88b829e1f173b074375
e5a2eed530086b4b3772886f1daad8ed6d6b5152
/projects/app/src/mvc/pokemonstoragemodel.cpp
9e365e4918ef3bbd6959312384ca6af751b991c0
[ "Apache-2.0" ]
permissive
junebug12851/pokered-save-editor-2
f7cf5013652737ef24f0c7a400c6520e4df5f54b
af883fd4c12097d408e1756c7181709cf2b797d8
refs/heads/master
2020-06-06T09:17:16.194569
2020-03-18T09:45:34
2020-03-18T09:45:34
192,697,866
0
0
null
null
null
null
UTF-8
C++
false
false
13,897
cpp
pokemonstoragemodel.cpp
/* * Copyright 2020 June Hanabi * * 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 <algorithm> #include <QCollator> #include <QDebug> #include "./pokemonstoragemodel.h" #include "../bridge/router.h" #include <pse-db/pokemon.h> #include <pse-savefile/expanded/storage.h> #include <pse-savefile/expanded/player/playerpokemon.h> #include <pse-savefile/expanded/fragments/item.h> #include <pse-savefile/expanded/fragments/pokemonbox.h> #include <pse-savefile/expanded/fragments/pokemonparty.h> #include <pse-savefile/expanded/fragments/itemstoragebox.h> #include <pse-savefile/expanded/fragments/pokemonstoragebox.h> PokemonStorageModel::PokemonStorageModel( Router* router, Storage* storage, PlayerPokemon* party) : router(router), storage(storage), party(party) { connect(this->router, &Router::closeNonModal, this, &PokemonStorageModel::pageClosing); connect(this->router, &Router::goHome, this, &PokemonStorageModel::pageClosing); connect(this, &PokemonStorageModel::hasCheckedChanged, this, &PokemonStorageModel::checkStateDirty); connect(this, &PokemonStorageModel::curBoxChanged, this, &PokemonStorageModel::onReset); // Do an initial setup switchBox(curBox, true); } void PokemonStorageModel::switchBox(int newBox, bool force) { // Do nothing if it's the same box if(!force && curBox == newBox) return; // Remove all checks if(checkedStateDirty) clearCheckedState(); // Get old current box auto box = getCurBox(); // Disconnect from it disconnect(box, &PokemonStorageBox::pokemonMoveChange, this, &PokemonStorageModel::onMove); disconnect(box, &PokemonStorageBox::pokemonRemoveChange, this, &PokemonStorageModel::onRemove); disconnect(box, &PokemonStorageBox::pokemonInsertChange, this, &PokemonStorageModel::onReset); disconnect(box, &PokemonStorageBox::pokemonResetChange, this, &PokemonStorageModel::onReset); disconnect(box, &PokemonStorageBox::beforePokemonRelocate, this, &PokemonStorageModel::onBeforeRelocate); // Change boxes and retrieve new box curBox = newBox; box = getCurBox(); // Connect to it connect(box, &PokemonStorageBox::pokemonMoveChange, this, &PokemonStorageModel::onMove); connect(box, &PokemonStorageBox::pokemonRemoveChange, this, &PokemonStorageModel::onRemove); connect(box, &PokemonStorageBox::pokemonInsertChange, this, &PokemonStorageModel::onReset); connect(box, &PokemonStorageBox::pokemonResetChange, this, &PokemonStorageModel::onReset); connect(box, &PokemonStorageBox::beforePokemonRelocate, this, &PokemonStorageModel::onBeforeRelocate); // Announce change curBoxChanged(); } PokemonStorageBox* PokemonStorageModel::getCurBox() const { return getBox(curBox); } PokemonStorageBox* PokemonStorageModel::getBox(int box) const { if(box == PartyBox) return party; else return storage->boxAt(box); } int PokemonStorageModel::rowCount(const QModelIndex& parent) const { // Not a tree, just a list, there's no parent Q_UNUSED(parent) // Return list count return (getCurBox()->isFull()) ? getCurBox()->pokemon.size() : getCurBox()->pokemon.size() + 1; } QVariant PokemonStorageModel::data(const QModelIndex& index, int role) const { // If index is invalid in any way, return nothing if (!index.isValid()) return QVariant(); if (index.row() > getCurBox()->pokemon.size()) return QVariant(); if(index.row() == (getCurBox()->pokemon.size())) return getPlaceHolderData(role); // Get Item from Item List Cache auto mon = getCurBox()->pokemon.at(index.row()); auto monData = mon->toData(); // Even for glitch Pokemon, there should still be a data entry if(mon == nullptr || monData == nullptr) return QVariant(); // Now return requested information if (role == IndRole) return monData->ind; else if (role == DexRole) return (monData->pokedex) ? *monData->pokedex : -1; else if (role == NameRole) return monData->readable; else if (role == CheckedRole) return mon->property(isCheckedKey).toBool(); else if (role == PlaceholderRole) return false; else if (role == NicknameRole) return mon->nickname; else if (role == LevelRole) return mon->level; else if (role == IsShinyRole) return mon->isShiny(); else if (role == IsPartyRole) return !mon->isBoxMon(); // All else fails, return nothing return QVariant(); } QHash<int, QByteArray> PokemonStorageModel::roleNames() const { QHash<int, QByteArray> roles; roles[IndRole] = "itemInd"; roles[DexRole] = "itemDex"; roles[NameRole] = "itemName"; roles[CheckedRole] = "itemChecked"; roles[PlaceholderRole] = "itemIsPlaceholder"; roles[NicknameRole] = "itemNickname"; roles[LevelRole] = "itemLevel"; roles[IsShinyRole] = "itemIsShiny"; roles[IsPartyRole] = "itemIsParty"; return roles; } bool PokemonStorageModel::setData(const QModelIndex& index, const QVariant& value, int role) { if(!index.isValid()) return false; if(index.row() >= getCurBox()->pokemon.size()) return false; auto mon = getCurBox()->pokemon.at(index.row()); if(mon == nullptr) return false; // Now set requested information if(role == CheckedRole) { mon->setProperty(isCheckedKey, value.toBool()); hasCheckedChanged(); dataChanged(index, index); return true; } return false; } QVariant PokemonStorageModel::getPlaceHolderData(int role) const { if (role == IndRole) return -1; else if (role == DexRole) return -1; else if (role == NameRole) return ""; else if (role == CheckedRole) return false; else if (role == PlaceholderRole) return true; return QVariant(); } // QML ListView is the worst I've ever used in any language, so many hours and // days have been lost fixing ListView issues, bugs, and gotchas // // beginMoveRows is the only way to move rows and it's terminology is different // than other Qt terminology. // "to" is 1 past the item to move to, elsewhere in Qt "to" is the index to move // to. This creates all kinds of havoc as the two cannot properly communicate // and translation is very error prone leading to all my problems. void PokemonStorageModel::onMove(int from, int to) { // I'm convinced I'm never going to be able to remove these for the life of // the entire program because I'm convinced that seeking out ListView bugs // specifically and only related to beginMoveRow bugs will never end. Ever! //qDebug() << "[Pre-Move] From" << from << "to" << to; if(from == to) return; if(to > from) to++; //qDebug() << "[To-Move] From" << from << "to" << to; beginMoveRows(QModelIndex(), from, from, QModelIndex(), to); endMoveRows(); } void PokemonStorageModel::onRemove(int ind) { beginRemoveRows(QModelIndex(), ind, ind); endRemoveRows(); hasCheckedChanged(); } void PokemonStorageModel::onInsert() { // Doesn't work, no idea why beginInsertRows(QModelIndex(), getCurBox()->pokemon.size()+1, getCurBox()->pokemon.size()+1); endInsertRows(); } void PokemonStorageModel::onReset() { beginResetModel(); endResetModel(); hasCheckedChanged(); } bool PokemonStorageModel::hasChecked() { bool ret = false; for(auto el : getCurBox()->pokemon) { if(el->property(isCheckedKey).toBool() == true) ret = true; } return ret; } bool PokemonStorageModel::hasCheckedCached() { return checkedStateDirty; } QVector<PokemonBox*> PokemonStorageModel::getChecked() { QVector<PokemonBox*> ret; for(auto el : getCurBox()->pokemon) { if(el->property(isCheckedKey).toBool() == true) ret.append(el); } return ret; } void PokemonStorageModel::clearCheckedState() { for(auto el : getCurBox()->pokemon) { el->setProperty(isCheckedKey, false); } hasCheckedChanged(); } void PokemonStorageModel::clearCheckedStateGone() { for(int i = 0; i < getCurBox()->pokemon.size(); i++) { auto el = getCurBox()->pokemon.at(i); el->setProperty(isCheckedKey, false); dataChanged(index(i), index(i)); } hasCheckedChanged(); } void PokemonStorageModel::checkedMoveToTop() { for(auto el : getChecked()) { int ind = getCurBox()->pokemon.indexOf(el); getCurBox()->pokemonMove(ind, 0); } } void PokemonStorageModel::checkedMoveUp() { for(auto el : getChecked()) { int ind = getCurBox()->pokemon.indexOf(el); getCurBox()->pokemonMove(ind, ind - 1); } } void PokemonStorageModel::checkedMoveDown() { auto checkedItems = getChecked(); // For stupid ListView, these need to be done in reverse // If moving down for(int i = checkedItems.size() - 1; i >= 0; i--) { auto el = checkedItems.at(i); int ind = getCurBox()->pokemon.indexOf(el); getCurBox()->pokemonMove(ind, ind + 1); } } void PokemonStorageModel::checkedMoveToBottom() { auto checkedItems = getChecked(); // For stupid ListView, these need to be done in reverse // If moving down for(int i = checkedItems.size() - 1; i >= 0; i--) { auto el = checkedItems.at(i); int ind = getCurBox()->pokemon.indexOf(el); getCurBox()->pokemonMove(ind, getCurBox()->pokemon.size() - 1); } } void PokemonStorageModel::checkedDelete() { bool annPlaceholder = getCurBox()->pokemonCount() == getCurBox()->pokemonMax(); for(auto el : getChecked()) { // Stop if the party is down to one Pokemon if(getCurBox() == party && party->pokemonCount() <= 1) break; int ind = getCurBox()->pokemon.indexOf(el); getCurBox()->pokemonRemove(ind); } // Announce the opening of the placeholder if(annPlaceholder) { beginInsertRows(QModelIndex(), getCurBox()->pokemonCount(), getCurBox()->pokemonCount()); endInsertRows(); } } void PokemonStorageModel::checkedTransfer() { // Stop if both models refer to the same box, this is not suppose to happen if(getCurBox() == otherModel->getCurBox()) return; for(auto el : getChecked()) { // We don't want to convert to and from data structures if we can't move // the pokemon. Perform checks to make sure it's possible. // Stop if the party is down to one Pokemon if(getCurBox() == party && party->pokemonCount() <= 1) break; // Stop here if the other side is full if(otherModel->getCurBox()->isFull()) break; // Get index int ind = getCurBox()->pokemon.indexOf(el); // If we're converting to a PokemonParty we auto-destroy the box pokemon and // produce the same Pokemon with the PokemonParty extensions. If the other // way around, we can't auto-destroy it so we manually do the conversion and // destroying // We also have to replace the newly converted Pokemon in the array before // relocating it if(otherModel->getCurBox()->isParty) { el = PokemonParty::convertToParty(el); getCurBox()->pokemon.replace(ind, el); } else if(!otherModel->getCurBox()->isParty && getCurBox()->isParty) { auto partyEl = (PokemonParty*)el; el = partyEl->toBoxData(); partyEl->deleteLater(); getCurBox()->pokemon.replace(ind, el); } // Now do the relocate getCurBox()->relocateOne(otherModel->getCurBox(), ind); } hasCheckedChanged(); } void PokemonStorageModel::checkedToggleAll() { if(getCurBox()->pokemon.size() == 0) return; bool allValue = !getCurBox()->pokemon.at(0)->property(isCheckedKey).toBool(); for(int i = 0; i < getCurBox()->pokemon.size(); i++) { auto el = getCurBox()->pokemon.at(i); el->setProperty(isCheckedKey, allValue); } // As far as I can tell there is no way to force a ListView row to be // re-created. This means dataChanged is completely and utterly useless. I've // tried all kinds of tricks, I've searched Google for hours, I've even tried // a hack where I remove and re-insert all rows to force the rows to be // re-created. I'm left with no other option but to completely destroy the // model and re-create it. // // The issue stems from another Qt gotcha. Models are expected to change only // from their delegates, they are never expected to externally change and as // such any external changes have no way of being reflected in the model // without a reset. beginResetModel(); endResetModel(); hasCheckedChanged(); } void PokemonStorageModel::onBeforeRelocate(PokemonBox* mon) { mon->setProperty(isCheckedKey, false); hasCheckedChanged(); } void PokemonStorageModel::checkStateDirty() { bool _val = hasChecked(); if(checkedStateDirty == _val) return; checkedStateDirty = _val; hasCheckedChangedCached(); } void PokemonStorageModel::pageClosing() { if(checkedStateDirty) clearCheckedState(); } PokemonBox* PokemonStorageModel::getBoxMon(int index) { return getCurBox()->pokemon.at(index); } PokemonParty* PokemonStorageModel::getPartyMon(int index) { auto mon = getCurBox()->pokemon.at(index); if(mon->isBoxMon()) return nullptr; return (PokemonParty*)mon; }
8550b7786bee06c91a82c774fba96a98645b2abc
abbb664b47373bf0546a02ec2595af0be190c108
/1-Algorithmic-Toolbox/1.4-divide-and-conquer/assignment/majority_element.cpp
38171c06becd1e403f773b37018b350c0dc0815d
[]
no_license
mcitoler/data-structures-algorithms
6f72e5ced4e10b49877969fa4efc3ffb886a7faa
4dc7160a67570b78a03beae66644b0fa0e46dd7f
refs/heads/master
2021-10-11T00:48:18.770763
2018-05-26T18:30:39
2018-05-26T18:30:39
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,507
cpp
majority_element.cpp
#include <algorithm> #include <cstdlib> #include <iostream> #include <vector> using std::vector; int get_count(vector<int> &vec, int x, int lo, int hi) { int count{0}; for (int i = lo; i <= hi; ++i) { if (vec[i] == x) count++; } return count; } int get_majority_element(vector<int> &a, int left, int right) { if ((left + 1 == right && a[left] == a[right]) || left == right) return a[left]; if (left + 1 == right && a[left] != a[right]) return -1; // write your code here int mid = (int)(right + left) / 2; // std::cout << "mid = " << mid << "\t" << a[mid] << std::endl; int left_result = get_majority_element(a, left, mid); int right_result = get_majority_element(a, mid + 1, right); // std::cout << left_result << "\t" << right_result << std::endl; if (left_result == right_result) { return left_result; } else { if (left_result != -1) { int count = get_count(a, left_result, left, right); if (count > (int)(right - left + 1) / 2) return left_result; } if (right_result != -1) { int count = get_count(a, right_result, left, right); if (count > (int)(right - left + 1) / 2) return right_result; } } return -1; } int get_majority_element_quadratic(vector<int> &a) { for (auto curr : a) { int count = get_count(a, curr, 0, (int)a.size() - 1); if (count > (int)a.size() / 2) return curr; } return -1; } void test_solution() { while (true) { int n = rand() % 100 + 1; vector<int> a(n); for (size_t i = 0; i < a.size(); ++i) { a[i] = rand() % 10 + 1; } int res = get_majority_element(a, 0, n - 1); int naive = get_majority_element_quadratic(a); if (res != naive) { std::cout << "Fail!" << std::endl; std::cout << n << std::endl; for (auto e : a) { std::cout << e << " "; } break; } else { std::cout << "Ok!" << std::endl; } } } int main() { int n; std::cin >> n; vector<int> a(n); for (size_t i = 0; i < a.size(); ++i) { std::cin >> a[i]; } // std::cout << (get_majority_element_quadratic(a) != -1) << '\n'; // test_solution(); std::cout << (get_majority_element(a, 0, a.size() - 1) != -1) << '\n'; // std::cin >> n; }
e34e7a3473aa4e4d3048bea903c36ba8c4d788f1
23f988531f6b59d5e2639d14d7c3183a94360cef
/util/util.cpp
9f0e85b22f8423c52b291319fa3241e675208db6
[]
no_license
AthallahDzaki/SAMPMobile
0f883ed25396dca6841f3c2002500c2824efb33c
165673b0d853ede42a94ec0f09180869809aaa6e
refs/heads/master
2023-08-01T19:41:05.482866
2021-10-01T00:38:32
2021-10-01T00:38:32
267,602,721
20
16
null
null
null
null
UTF-8
C++
false
false
4,618
cpp
util.cpp
#include "util.h" uintptr_t FindLibrary(const char* library) { char filename[0xFF] = {0}, buffer[2048] = {0}; FILE *fp = 0; uintptr_t address = 0; sprintf( filename, "/proc/%d/maps", getpid() ); fp = fopen( filename, "rt" ); if(fp == 0) { Log("ERROR: can't open file %s", filename); goto done; } while(fgets(buffer, sizeof(buffer), fp)) { if( strstr( buffer, library ) ) { address = (uintptr_t)strtoul( buffer, 0, 16 ); break; } } done: if(fp) fclose(fp); return address; } void cp1251_to_utf8(char *out, const char *in, unsigned int len) { static const int table[128] = { // 80 0x82D0, 0x83D0, 0x9A80E2, 0x93D1, 0x9E80E2, 0xA680E2, 0xA080E2, 0xA180E2, 0xAC82E2, 0xB080E2, 0x89D0, 0xB980E2, 0x8AD0, 0x8CD0, 0x8BD0, 0x8FD0, // 90 0x92D1, 0x9880E2, 0x9980E2, 0x9C80E2, 0x9D80E2, 0xA280E2, 0x9380E2, 0x9480E2, 0, 0xA284E2, 0x99D1, 0xBA80E2, 0x9AD1, 0x9CD1, 0x9BD1, 0x9FD1, // A0 0xA0C2, 0x8ED0, 0x9ED1, 0x88D0, 0xA4C2, 0x90D2, 0xA6C2, 0xA7C2, 0x81D0, 0xA9C2, 0x84D0, 0xABC2, 0xACC2, 0xADC2, 0xAEC2, 0x87D0, // B0 0xB0C2, 0xB1C2, 0x86D0, 0x96D1, 0x91D2, 0xB5C2, 0xB6C2, 0xB7C2, 0x91D1, 0x9684E2, 0x94D1, 0xBBC2, 0x98D1, 0x85D0, 0x95D1, 0x97D1, // C0 0x90D0, 0x91D0, 0x92D0, 0x93D0, 0x94D0, 0x95D0, 0x96D0, 0x97D0, 0x98D0, 0x99D0, 0x9AD0, 0x9BD0, 0x9CD0, 0x9DD0, 0x9ED0, 0x9FD0, // D0 0xA0D0, 0xA1D0, 0xA2D0, 0xA3D0, 0xA4D0, 0xA5D0, 0xA6D0, 0xA7D0, 0xA8D0, 0xA9D0, 0xAAD0, 0xABD0, 0xACD0, 0xADD0, 0xAED0, 0xAFD0, // E0 0xB0D0, 0xB1D0, 0xB2D0, 0xB3D0, 0xB4D0, 0xB5D0, 0xB6D0, 0xB7D0, 0xB8D0, 0xB9D0, 0xBAD0, 0xBBD0, 0xBCD0, 0xBDD0, 0xBED0, 0xBFD0, // F0 0x80D1, 0x81D1, 0x82D1, 0x83D1, 0x84D1, 0x85D1, 0x86D1, 0x87D1, 0x88D1, 0x89D1, 0x8AD1, 0x8BD1, 0x8CD1, 0x8DD1, 0x8ED1, 0x8FD1 }; int count = 0; while (*in) { if(len && (count >= len)) break; if (*in & 0x80) { register int v = table[(int)(0x7f & *in++)]; if (!v) continue; *out++ = (char)v; *out++ = (char)(v >> 8); if (v >>= 16) *out++ = (char)v; } else // ASCII *out++ = *in++; count++; } *out = 0; } // Выбор сервера из пунктов меню диалога, для дальнейшего подключения void SelectServerToJoin(uint8_t m_iSelectedItem) { switch (m_iSelectedItem) { // Luxury 01 case 0: initCNetGame(cryptor::create("s1.gta-server.ru", 17).decrypt(), atoi(cryptor::create("7777", 4).decrypt())); break; // Luxury 02 case 1: initCNetGame(cryptor::create("s2.gta-server.ru", 17).decrypt(), atoi(cryptor::create("7777", 4).decrypt())); break; // Luxury 03 case 2: initCNetGame(cryptor::create("s3.gta-server.ru", 17).decrypt(), atoi(cryptor::create("7777", 4).decrypt())); break; // Luxury 04 case 3: initCNetGame(cryptor::create("s4.gta-server.ru", 17).decrypt(), atoi(cryptor::create("7777", 4).decrypt())); break; // Если какой-то другой пункт выбран, подключаемся всё равно к первому default: initCNetGame(cryptor::create("s1.gta-server.ru", 17).decrypt(), atoi(cryptor::create("7777", 4).decrypt())); break; } } void Log(const char *fmt, ...) { char buffer[0xFF]; static FILE* flLog = nullptr; if(flLog == nullptr && g_pszStorage != nullptr) { sprintf(buffer, "%sSAMP/samp.log", g_pszStorage); flLog = fopen(buffer, "w"); } memset(buffer, 0, sizeof(buffer)); va_list arg; va_start(arg, fmt); vsnprintf(buffer, sizeof(buffer), fmt, arg); va_end(arg); __android_log_write(ANDROID_LOG_INFO, "AXL", buffer); if(pDebug) pDebug->AddMessage(buffer); if(flLog == nullptr) return; fprintf(flLog, "%s\n", buffer); fflush(flLog); return; } uint32_t GetTickCount() { struct timeval tv; gettimeofday(&tv, nullptr); return (tv.tv_sec*1000+tv.tv_usec/1000); }
22023ad18f2f4616ecc8765262c849abe6108794
5d513922371951e68767dbd0a89b92dcd2f7ecdf
/solution242.cpp
616bff4d4d166067e16a5721fbb944d2ec99185f
[]
no_license
lazur5566/Leetcode
2f7809e8d554f429b7824d183f57fd6523544110
08a227fb3ea35c61a42d7e5bc698acd329d0bd29
refs/heads/master
2020-03-22T00:17:29.094869
2018-09-20T03:01:08
2018-09-20T03:01:08
139,235,644
0
0
null
null
null
null
UTF-8
C++
false
false
754
cpp
solution242.cpp
// // solution242.cpp // LEETCODE // // Created by lazur on 2018/4/8. // Copyright © 2018年 lazur. All rights reserved. // #include <stdio.h> #include <vector> #include <string> class Solution242 { public: bool isAnagram(std::string s, std::string t) { if(s.size()!=t.size()) { return false; } std::vector<int> chars(256,0); for(int i=0;i<s.size();i++) { chars[s.at(i)]++; } for(int j=0;j<t.size();j++) { chars[t.at(j)]--; } for(int k=0;k<chars.size();k++) { if(chars[k]!=0) { return false; } } return true; } };
d29c23739429cadb3601eaa4fe0ae70ec626d25e
f82349a360e808e0f139d3c688afc38dd6d356bf
/Prism.Engine/include/Renderer/Graphics/VertexArrayObject.h
256f139ee1ff37be865e6637e6776e87921fbbe0
[]
no_license
Vinno97/prism
7f71cf27d37d4e993dc1c530be349e855ecb362e
7207e67d2331fba5096996d6d85b9b5e3bc79b8c
refs/heads/master
2020-03-28T03:44:39.231736
2018-12-19T23:21:18
2018-12-19T23:21:18
147,668,071
2
1
null
2018-12-19T23:21:19
2018-09-06T12:10:47
C
UTF-8
C++
false
false
1,198
h
VertexArrayObject.h
#pragma once #include <glm/glm.hpp> #include <SDL2/SDL_opengl.h> #include "Renderer/Graphics/VertexBuffer.h" #include <iostream> #include <memory> namespace Renderer { namespace Graphics { class VertexArrayObject { public: VertexArrayObject()=default; /// <summary> /// adds a vertexbuffer to the VAO. /// </summary> /// <remarks> /// Right now this class does not support intervals between strides and different storage types. This may be added when necessary. /// </remarks> /// <param name="vertexBuffer">Buffer to add to VAO</param> /// <param name="index">Position of input variable in the vertex shader</param> /// <param name="size">Size of each block of data</param> /// <param name="start">Start of the input within the vbo</param> /// <param name="stride">Length of the block of data</param> virtual void addVertexBuffer(VertexBuffer* vertexBuffer, int index, long long size, int start, int stride) = 0; /// <summary> /// Make this the current active VAO /// </summary> virtual void bind() = 0; /// <summary> /// Deactive the current active VAO /// </summary> virtual void unbind() = 0; GLuint vaoID; }; } }
3d2c6a00e6768899cddc498850b5a719d8640ab3
97086e933088f069c92a53443e63585be06a1630
/source/details/settings.cpp
807e6c71177e20f65a31d92ecf5de496f454b790
[]
no_license
light0222/BotUI
20e1f9668f420680840356d6b8d9a1709e31189a
9b8e2b5dc7eaf0b2d1d428f51b4951ad0df56969
refs/heads/master
2021-08-19T08:26:14.743472
2017-11-25T13:21:31
2017-11-25T13:21:31
112,004,483
0
0
null
null
null
null
UTF-8
C++
false
false
245
cpp
settings.cpp
#include "details/settings.hh" #include "ui_settings.h" DetailsSettings::DetailsSettings(QWidget *parent) : QWidget(parent), ui(new Ui::DetailsSettings) { ui->setupUi(this); } DetailsSettings::~DetailsSettings() { delete ui; }
f77f19abfdb7add665274d354bff19edb6a0b283
88bcc2419c678a156c444a1f93b9993e1e1d9760
/include/experimental/kernel/mha_core_attention/mha_core_attn.hpp
780b95f8c2970443bdcc9ebbe0e7a21d4a57ec41
[ "Apache-2.0", "LicenseRef-scancode-warranty-disclaimer" ]
permissive
intel/xetla
e2014e6ca1cae37e4092f83923791226a1936093
d644c2144590adcfe9b1aca206da35a408db3506
refs/heads/main
2023-08-30T23:54:16.063035
2023-08-28T08:01:59
2023-08-28T08:01:59
627,110,514
34
5
Apache-2.0
2023-09-11T06:05:49
2023-04-12T20:02:17
C++
UTF-8
C++
false
false
85,350
hpp
mha_core_attn.hpp
/******************************************************************************* * Copyright (c) 2022-2023 Intel 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 "common/common.hpp" #include "group/group.hpp" #include "subgroup/subgroup.hpp" namespace gpu::xetla::kernel { #define list_width 16 #define rand_threshold_const 0x80000000 #define SIGN_BIT_DW 0x80000000 #define SIGN_BIT_W16 0x8000 #define SIGN_BIT_B8 0x80 /// @brief /// /// @tparam dtype_bin_ /// @tparam dtype_bot_ /// @tparam dtype_sfx_ /// @tparam dtype_acc_ /// @tparam HWThreadNum /// @tparam Dopt_RandGenflag /// @tparam RandSIMD /// @tparam Max_SeqLen template <typename dtype_bin_, typename dtype_bot_, typename dtype_sfx_, typename dtype_acc_, int HWThreadNum, bool Dopt_RandGenflag = true, uint16_t RandSIMD = 16, int Max_SeqLen = 512> struct xetla_mha_core_attn_fwd_t { using dtype_bin = dtype_bin_; using dtype_bot = dtype_bot_; using dtype_sfx = dtype_sfx_; using dtype_acc = dtype_acc_; static constexpr int ThreadNum = HWThreadNum; static constexpr int max_seqlen = Max_SeqLen; static constexpr mem_space mem_space_a = mem_space::global; static constexpr mem_space mem_space_b = mem_space::global; static constexpr mem_space mem_space_c = mem_space::global; static constexpr uint16_t Rand_SIMD = RandSIMD; static constexpr mem_layout mem_layout_a = mem_layout::row_major; static constexpr mem_layout mem_layout_QKT_b = mem_layout::col_major; static constexpr mem_layout mem_layout_out_b = mem_layout::row_major; static constexpr mem_layout mem_layout_c = mem_layout::row_major; static constexpr mem_space brgemm_mem_space_a = mem_space_a; static constexpr mem_layout brgemm_mem_layout_a = mem_layout_a; static constexpr mem_space brgemm_mem_space_b = mem_space_b; static constexpr mem_layout brgemm_mem_layout_QKT_b = mem_layout_QKT_b; static constexpr mem_layout brgemm_mem_layout_out_b = mem_layout_out_b; static constexpr uint32_t periodic_sync_interval = 0; static constexpr uint32_t prefetch_distance = 3; static constexpr uint32_t k_stride = 32 / sizeof(dtype_bin); //brgemm_config::k_stride; using bgm_perf_tuning_knob = group::perf_tuning_knob_t<k_stride, prefetch_distance, periodic_sync_interval>; using tile_attr_128x128 = group::tile_shape_t<128, 128, 32, 16>; using tile_attr_128x256 = group::tile_shape_t<256, 128, 32, 32>; using tile_attr_128x64 = group::tile_shape_t<64, 128, 16, 16>; using mem_desc_a_QKT = mem_desc_t<dtype_bin, brgemm_mem_layout_a, brgemm_mem_space_a>; using mem_desc_b_QKT = mem_desc_t<dtype_bin, brgemm_mem_layout_QKT_b, brgemm_mem_space_b>; using compute_policy_QKT = group::compute_policy_default_xmx< group::compute_attr_t<dtype_bin, dtype_bin, dtype_acc>, bgm_perf_tuning_knob, gpu_arch::Xe>; using mem_desc_a_out = mem_desc_t<dtype_sfx, brgemm_mem_layout_a, brgemm_mem_space_a>; using mem_desc_b_out = mem_desc_t<dtype_bin, brgemm_mem_layout_out_b, brgemm_mem_space_b>; using compute_policy_out = group::compute_policy_default_xmx< group::compute_attr_t<dtype_sfx, dtype_bin, dtype_acc>, bgm_perf_tuning_knob, gpu_arch::Xe>; using arch_attr = arch_attr_t<gpu_arch::Xe>; static constexpr uint32_t l3_kslicing = 1; static constexpr uint16_t sfx_type_size = sizeof(dtype_sfx); static_assert((sfx_type_size == 1) || (sfx_type_size == 2) || (sfx_type_size == 4)); using work_group_t = work_group_t<ThreadNum>; using pre_processing_128x128 = group::pre_processing_default_t<tile_attr_128x128, gpu_arch::Xe>; using pre_processing_128x256 = group::pre_processing_default_t<tile_attr_128x256, gpu_arch::Xe>; using pre_processing_128x64 = group::pre_processing_matA_neg_filter_t<tile_attr_128x64, gpu_arch::Xe>; using brgemm_op_128x128_t = group::brgemm_t<compute_policy_QKT, tile_attr_128x128, mem_desc_a_QKT, mem_desc_b_QKT, pre_processing_128x128>; using brgemm_op_128x256_t = group::brgemm_t<compute_policy_QKT, tile_attr_128x256, mem_desc_a_QKT, mem_desc_b_QKT, pre_processing_128x256>; using brgemm_op_128x64_t = group::brgemm_t<compute_policy_out, tile_attr_128x64, mem_desc_a_out, mem_desc_b_out, pre_processing_128x64>; using brgemm_arguments_128x128 = typename brgemm_op_128x128_t::arguments_t; using brgemm_arguments_128x256 = typename brgemm_op_128x256_t::arguments_t; using brgemm_arguments_128x64 = typename brgemm_op_128x64_t::arguments_t; using matAcc_128x128_t = typename brgemm_op_128x128_t::matAcc_t; using matAcc_128x256_t = typename brgemm_op_128x256_t::matAcc_t; using matAcc_128x64_t = typename brgemm_op_128x64_t::matAcc_t; using matC_128x128_tile_desc_t = subgroup::tile_desc_t<matAcc_128x128_t::tile_desc::tile_size_x, matAcc_128x128_t::tile_desc::tile_size_y, matAcc_128x128_t::tile_desc::block_size_x, matAcc_128x128_t::tile_desc::block_size_y, reg_layout::tiled>; using matC_128x256_tile_desc_t = subgroup::tile_desc_t<matAcc_128x256_t::tile_desc::tile_size_x, matAcc_128x256_t::tile_desc::tile_size_y, matAcc_128x256_t::tile_desc::block_size_x, matAcc_128x256_t::tile_desc::block_size_y, reg_layout::tiled>; using matC_128x64_tile_desc_t = subgroup::tile_desc_t<matAcc_128x64_t::tile_desc::tile_size_x, matAcc_128x64_t::tile_desc::tile_size_y, matAcc_128x64_t::tile_desc::block_size_x, matAcc_128x64_t::tile_desc::block_size_y, reg_layout::tiled>; using matC_128x128_t = subgroup::tile_t<dtype_sfx, matC_128x128_tile_desc_t>; using matC_128x256_t = subgroup::tile_t<dtype_sfx, matC_128x256_tile_desc_t>; using matC_128x64_t = subgroup::tile_t<dtype_bot, matC_128x64_tile_desc_t>; using matC_128x128_payload_t = subgroup::mem_payload_t<dtype_sfx, matC_128x128_tile_desc_t, (l3_kslicing > 1) ? msg_type::atomic_add : msg_type::block_2d, mem_layout_c, mem_space_c, gpu_arch::Xe>; using matC_128x256_payload_t = subgroup::mem_payload_t<dtype_sfx, matC_128x256_tile_desc_t, (l3_kslicing > 1) ? msg_type::atomic_add : msg_type::block_2d, mem_layout_c, mem_space_c, gpu_arch::Xe>; using matC_128x64_payload_t = subgroup::mem_payload_t<dtype_bot, matC_128x64_tile_desc_t, (l3_kslicing > 1) ? msg_type::atomic_add : msg_type::block_2d, mem_layout_c, mem_space_c, gpu_arch::Xe>; //512 = 16x32 or 8x64 using matElem_tile_desc_t = gpu::xetla::subgroup::tile_desc_t<64 / sfx_type_size, 8 * sfx_type_size, 64 / sfx_type_size, 8 * sfx_type_size, reg_layout::tiled>; using matElem_ld_t = gpu::xetla::subgroup::tile_t<dtype_sfx, matElem_tile_desc_t>; using matElem_ld_payload_t = gpu::xetla::subgroup::mem_payload_t<dtype_sfx, matElem_tile_desc_t, subgroup::msg_type_v<matElem_tile_desc_t, mem_space::global>, mem_layout::row_major, mem_space::global, gpu_arch::Xe>; using matElem_st_t = gpu::xetla::subgroup::tile_t<dtype_sfx, matElem_tile_desc_t>; using matElem_st_payload_t = gpu::xetla::subgroup::mem_payload_t<dtype_sfx, matElem_tile_desc_t, subgroup::msg_type_v<matElem_tile_desc_t, mem_space::global>, mem_layout::row_major, mem_space::global, gpu_arch::Xe>; using matElem_reg_t = gpu::xetla::subgroup::tile_t<float, gpu::xetla::subgroup::tile_desc_t<32, 16, 32, 16, reg_layout::tiled>>; /// @brief Arguments for xetla_softmax_fwd_t::run. /// User should prepare matQ_ptr, matK_ptr, matQKT_ptr, ... /// struct arguments_t { // assume base address, surface width, height, pitch, start coordinate was set uint32_t *mList_ptr; dtype_bin *matQ_ptr; dtype_bin *matK_ptr; dtype_bin *matV_ptr; uint32_t *matMkin_ptr; uint32_t *matMkdpot_ptr; dtype_sfx *matQKT_ptr; dtype_bot *matOut_ptr; float Pinv; float Scaling; }; /// @brief Main execution function for fused mha softmax. /// The basic process is BRGEMM -> Softmax -> BRGEMM. /// /// @param ei /// @param args Includes base descriptors and tid info. /// @return __XETLA_API static void call(xetla_exec_item<3> &ei, arguments_t *args) { int tru_seqlen = 0; int tru_seqlen_ex = 0; int seqlen_entry = 0; int groupid = ei.get_group(0); int hiddensize = 1024; int numhead = 16; int hdsz = 64; int wg_tile_QKT_k = hdsz; //args->matrix_k; int wg_tile_out_k; int batchid = groupid / numhead; int headid = groupid % numhead; work_group_t g_thd32_tid; int tid_linear = ei.get_local_linear_id(); g_thd32_tid.init(tid_linear); uint32_t batch_offset = sizeof(uint32_t) * list_width * batchid; xetla_vector<uint32_t, list_width> list_offsets = xetla_vector_gen<uint32_t, list_width>(0, 1); list_offsets *= sizeof(uint32_t); list_offsets += batch_offset; xetla_vector<uint32_t, list_width> list_vec = xetla_load_global<uint32_t, 1, data_size::default_size, cache_hint::read_invalidate, cache_hint::cached, list_width>(args->mList_ptr, list_offsets); tru_seqlen = list_vec[0]; seqlen_entry = list_vec[1]; wg_tile_out_k = tru_seqlen; tru_seqlen_ex = tru_seqlen; //DW align if (sfx_type_size == 2) tru_seqlen_ex = (((tru_seqlen + 1) >> 1) << 1); else if (sfx_type_size == 1) tru_seqlen_ex = (((tru_seqlen + 3) >> 2) << 2); //float totalscaling = args->Pinv * args->Scaling; xetla_rand_t<Rand_SIMD> Rand_Gen; uint32_t rand_threshold = rand_threshold_const; if constexpr (Dopt_RandGenflag == true) { uint64_t rand_seed = 67280421310721; uint64_t rand_subseq = (groupid * ThreadNum + tid_linear) * Rand_SIMD; uint64_t rand_offset = list_vec.xetla_format<uint64_t>()[1]; if (list_vec[4] != 0) rand_threshold = list_vec[4]; if (rand_offset == 0) { xetla_vector<uint32_t, 4> time_stamp = get_time_stamp(); rand_offset = time_stamp.xetla_format<uint64_t>()[0]; } Rand_Gen.init(rand_seed, rand_subseq, rand_offset); } //std_leqlen = 256 int all_vert_loop_num = 2; int blk_128x128_one = 0; int blk_128x256_loop_num = 1; int offset_blk_128x128 = 0; int std_seqlen; if (tru_seqlen <= 128) { std_seqlen = 128; all_vert_loop_num = 1; blk_128x128_one = 1; blk_128x256_loop_num = 0; } else if (tru_seqlen <= 256) std_seqlen = 256; else if (tru_seqlen <= 384) { std_seqlen = 384; all_vert_loop_num = 3; blk_128x128_one = 1; blk_128x256_loop_num = 1; offset_blk_128x128 = 256; } else { std_seqlen = 512; all_vert_loop_num = 4; blk_128x128_one = 0; blk_128x256_loop_num = 2; } xetla_nbarrier_t<32, 32> first_nbarr; xetla_nbarrier_t<32, 32> second_nbarr; first_nbarr.init_nbarrier(0, nbarrier_role::producer_consumer); second_nbarr.init_nbarrier(1, nbarrier_role::producer_consumer); for (int all_vert128_loop = 0; all_vert128_loop < all_vert_loop_num; all_vert128_loop++) { for (int hor_256_loop = 0; hor_256_loop < blk_128x256_loop_num; hor_256_loop++) { brgemm_arguments_128x256 brgemm_arg_128x256; matAcc_128x256_t matAcc_128x256; matC_128x256_t matC_128x256; matC_128x256_payload_t matC_128x256_payload; uint32_t width_a = (headid + 1) * hdsz; uint32_t height_a = tru_seqlen + seqlen_entry; uint32_t pitch_a = hiddensize; int start_x_a = headid * hdsz; int start_y_a = all_vert128_loop * 128 + seqlen_entry; brgemm_arg_128x256.matA_base_desc.init({args->matQ_ptr}, {width_a, height_a, pitch_a}, {start_x_a, start_y_a}); uint32_t width_b = (headid + 1) * hdsz; uint32_t height_b = tru_seqlen + seqlen_entry; uint32_t pitch_b = hiddensize; int start_x_b = headid * hdsz; int start_y_b = hor_256_loop * 256 + seqlen_entry; //B transpose brgemm_arg_128x256.matB_base_desc.init({args->matK_ptr}, {height_b, width_b, pitch_b}, {start_y_b, start_x_b}); brgemm_arg_128x256.inner_loop_count = (wg_tile_QKT_k + k_stride - 1) / k_stride; matAcc_128x256.init(0); brgemm_op_128x256_t brgemm_op_128x256; brgemm_op_128x256( g_thd32_tid, matAcc_128x256, brgemm_arg_128x256); uint32_t width_c = max_seqlen; uint32_t height_c = max_seqlen * (batchid * numhead + headid + 1); uint32_t pitch_c = max_seqlen; int start_x_c = brgemm_op_128x256_t::get_matC_offset_x(g_thd32_tid) + hor_256_loop * 256; int start_y_c = (batchid * numhead + headid) * max_seqlen + all_vert128_loop * 128 + brgemm_op_128x256_t::get_matC_offset_y(g_thd32_tid); matC_128x256_payload.init(args->matQKT_ptr, width_c, height_c, pitch_c, start_x_c, start_y_c); subgroup::elemwise_cvt<matC_128x256_t, matAcc_128x256_t>( matC_128x256, matAcc_128x256); subgroup::tile_store(matC_128x256, matC_128x256_payload); xetla_fence<memory_kind::untyped_global>(); } for (int blk_128x128_loop = 0; blk_128x128_loop < blk_128x128_one; blk_128x128_loop++) { brgemm_arguments_128x128 brgemm_arg_128x128; matAcc_128x128_t matAcc_128x128; matC_128x128_t matC_128x128; matC_128x128_payload_t matC_128x128_payload; uint32_t width_a = (headid + 1) * hdsz; uint32_t height_a = tru_seqlen + seqlen_entry; uint32_t pitch_a = hiddensize; int start_x_a = headid * hdsz; int start_y_a = all_vert128_loop * 128 + seqlen_entry; brgemm_arg_128x128.matA_base_desc.init({args->matQ_ptr}, {width_a, height_a, pitch_a}, {start_x_a, start_y_a}); uint32_t width_b = (headid + 1) * hdsz; uint32_t height_b = tru_seqlen + seqlen_entry; uint32_t pitch_b = hiddensize; int start_x_b = headid * hdsz; int start_y_b = offset_blk_128x128 + seqlen_entry; //B transpose brgemm_arg_128x128.matB_base_desc.init({args->matK_ptr}, {height_b, width_b, pitch_b}, {start_y_b, start_x_b}); brgemm_arg_128x128.inner_loop_count = (wg_tile_QKT_k + k_stride - 1) / k_stride; matAcc_128x128.init(0); brgemm_op_128x128_t brgemm_op_128x128; brgemm_op_128x128( g_thd32_tid, matAcc_128x128, brgemm_arg_128x128); uint32_t width_c = max_seqlen; uint32_t height_c = max_seqlen * (batchid * numhead + headid + 1); uint32_t pitch_c = max_seqlen; int start_x_c = offset_blk_128x128 + brgemm_op_128x128_t::get_matC_offset_x(g_thd32_tid); int start_y_c = (batchid * numhead + headid) * max_seqlen + all_vert128_loop * 128 + brgemm_op_128x128_t::get_matC_offset_y(g_thd32_tid); matC_128x128_payload.init(args->matQKT_ptr, width_c, height_c, pitch_c, start_x_c, start_y_c); subgroup::elemwise_cvt<matC_128x128_t, matAcc_128x128_t>( matC_128x128, matAcc_128x128); subgroup::tile_store(matC_128x128, matC_128x128_payload); xetla_fence<memory_kind::untyped_global>(); } //fwd softmax { int elem_Ln512_loop_num = 4; int height_8x64_512 = 8 * sfx_type_size; int width_8x16_512 = 64 / sfx_type_size; int height_elem_offset = (max_seqlen * (batchid * numhead + headid) + (all_vert128_loop * 128) + (tid_linear * 4)) * height_8x64_512; int width_elem = width_8x16_512; int height_elem; int pitch_elem = width_elem; int start_x_elem = 0; int start_y_elem; int bndy_mk_lp_start = (tru_seqlen + 31) >> 5; //32 int bndy_mk_lp_shift = 32 - (bndy_mk_lp_start << 5) + tru_seqlen; xetla_vector<uint32_t, 16> mkin_vec16; uint32_t mk_attn_all = sizeof(uint32_t) * (max_seqlen / 32) * (batchid); xetla_vector<uint32_t, 16> mk_attn_offsets = xetla_vector_gen<uint32_t, 16>(0, 1); mk_attn_offsets *= sizeof(uint32_t); mk_attn_offsets += mk_attn_all; mkin_vec16 = xetla_load_global<uint32_t, 1, data_size::default_size, cache_hint::read_invalidate, cache_hint::cached, 16>( args->matMkin_ptr, mk_attn_offsets); uint32_t mk_offset_all = sizeof(uint32_t) * (max_seqlen / 32) * ((batchid * numhead + headid) * max_seqlen + (all_vert128_loop * 128) + tid_linear * 4); xetla_vector<uint32_t, 16> mk_offsets = xetla_vector_gen<uint32_t, 16>(0, 1); mk_offsets *= sizeof(uint32_t); mk_offsets += mk_offset_all; first_nbarr.arrive(); first_nbarr.wait(); for (int elem_Ln512_loop = 0; elem_Ln512_loop < elem_Ln512_loop_num; elem_Ln512_loop++) { matElem_ld_t matQKT_rd; matElem_ld_payload_t matQKT_rd_payload; matElem_st_t matQKT_st; matElem_st_payload_t matQKT_st_payload; matElem_reg_t matQKT_reg16x32; xetla_vector<uint32_t, 16> mkdpot_vec16; start_y_elem = height_elem_offset + elem_Ln512_loop * height_8x64_512; height_elem = start_y_elem + ((std_seqlen * sfx_type_size) / 64); matQKT_rd_payload.init(args->matQKT_ptr, width_elem, height_elem, pitch_elem, start_x_elem, start_y_elem); matQKT_st_payload.init(args->matQKT_ptr, width_elem, height_elem, pitch_elem, start_x_elem, start_y_elem); subgroup::tile_load<cache_hint::cached, cache_hint::cached>( matQKT_rd, matQKT_rd_payload); if constexpr (Dopt_RandGenflag == false) { mkdpot_vec16 = xetla_load_global<uint32_t, 1, data_size::default_size, cache_hint::read_invalidate, cache_hint::cached, 16>(args->matMkdpot_ptr, mk_offsets); } mk_offsets += sizeof(uint32_t) * (max_seqlen / 32); for (int j = bndy_mk_lp_start; j < 16; j++) mkin_vec16[j] = 0xFFFFFFFF; if (bndy_mk_lp_shift < 32) { uint32_t tmp = 0xFFFFFFFF; tmp >>= bndy_mk_lp_shift; tmp <<= bndy_mk_lp_shift; mkin_vec16[bndy_mk_lp_start - 1] |= tmp; //mkin_vec16[bndy_mk_lp_start - 1] <<= bndy_mk_lp_shift; //mkin_vec16[bndy_mk_lp_start - 1] >>= bndy_mk_lp_shift; } matQKT_reg16x32.reg = xetla_cvt<float, dtype_sfx>(matQKT_rd.reg); matQKT_reg16x32.reg = matQKT_reg16x32.reg * args->Pinv; #pragma unroll for (int j = 0; j < 16; j++) { uint32_t mkdata_i = mkin_vec16[j]; xetla_mask_int<32> mkdata = xetla_mask_int_gen<32>(mkdata_i); matQKT_reg16x32.reg.xetla_format<float>() .xetla_select<32, 1>(j * 32) .xetla_merge(-1e32, matQKT_reg16x32.reg .xetla_format<float>() .xetla_select<32, 1>(j * 32), mkdata); } xetla_vector<float, 16> QKT_reg16_f; QKT_reg16_f = -1e32; #pragma unroll for (int j = 0; j < 32; j++) { xetla_mask<16> filter_max = (QKT_reg16_f > matQKT_reg16x32.reg.xetla_format<float>() .xetla_select<16, 1>(j * 16)); QKT_reg16_f.xetla_merge(QKT_reg16_f, matQKT_reg16x32.reg.xetla_format<float>() .xetla_select<16, 1>(j * 16), filter_max); } xetla_mask<8> filter_max8 = (QKT_reg16_f.xetla_select<8, 1>(0) > QKT_reg16_f.xetla_select<8, 1>(8)); QKT_reg16_f.xetla_select<8, 1>(0).xetla_merge( QKT_reg16_f.select<8, 1>(0), QKT_reg16_f.select<8, 1>(8), filter_max8); xetla_mask<4> filter_max4 = (QKT_reg16_f.xetla_select<4, 1>(0) > QKT_reg16_f.xetla_select<4, 1>(4)); QKT_reg16_f.xetla_select<4, 1>(0).xetla_merge( QKT_reg16_f.select<4, 1>(0), QKT_reg16_f.select<4, 1>(4), filter_max4); xetla_mask<2> filter_max2 = (QKT_reg16_f.xetla_select<2, 1>(0) > QKT_reg16_f.xetla_select<2, 1>(2)); QKT_reg16_f.xetla_select<2, 1>(0).xetla_merge( QKT_reg16_f.select<2, 1>(0), QKT_reg16_f.select<2, 1>(2), filter_max2); xetla_mask<1> filter_max1 = (QKT_reg16_f.xetla_select<1, 1>(0) > QKT_reg16_f.xetla_select<1, 1>(1)); QKT_reg16_f.xetla_select<1, 1>(0).xetla_merge( QKT_reg16_f.xetla_select<1, 1>(0), QKT_reg16_f.xetla_select<1, 1>(1), filter_max1); { float tmp_max = QKT_reg16_f[0]; matQKT_reg16x32.reg = matQKT_reg16x32.reg - tmp_max; } #pragma unroll for (int j = 0; j < 16; j++) matQKT_reg16x32.reg.xetla_format<float>() .xetla_select<32, 1>(j * 32) = xetla_exp<float, 32>( matQKT_reg16x32.reg .xetla_format<float>() .xetla_select<32, 1>(j * 32)); QKT_reg16_f = matQKT_reg16x32.reg.xetla_format<float>() .xetla_select<16, 1>(0) + matQKT_reg16x32.reg.xetla_format<float>() .xetla_select<16, 1>(16); #pragma unroll for (int j = 2; j < 32; j++) QKT_reg16_f = QKT_reg16_f + matQKT_reg16x32.reg.xetla_format<float>() .xetla_select<16, 1>(j * 16); QKT_reg16_f.xetla_select<8, 1>(0) += QKT_reg16_f.xetla_select<8, 1>(8); QKT_reg16_f.xetla_select<4, 1>(0) += QKT_reg16_f.xetla_select<4, 1>(4); QKT_reg16_f.xetla_select<2, 1>(0) += QKT_reg16_f.xetla_select<2, 1>(2); QKT_reg16_f.xetla_select<1, 1>(0) += QKT_reg16_f.xetla_select<1, 1>(1); QKT_reg16_f.xetla_select<1, 1>(0) = xetla_inv<float, 1>( QKT_reg16_f.xetla_select<1, 1>(0)); { float tmp = QKT_reg16_f[0]; QKT_reg16_f = tmp; } #pragma unroll for (int j = 0; j < 32; j++) matQKT_reg16x32.reg.xetla_format<float>() .xetla_select<16, 1>(j * 16) *= QKT_reg16_f; xetla_mask<(Max_SeqLen >> 2)> rand_bit; xetla_vector<uint32_t, 4 * RandSIMD> rand_data; matQKT_reg16x32.reg = matQKT_reg16x32.reg * args->Scaling; using matElem_reg_w_t = subgroup::tile_t<uint16_t, subgroup::tile_desc_t<32, 1, 32, 1, reg_layout::tiled>>; using matElem_reg_b_t = subgroup::tile_t<uint8_t, subgroup::tile_desc_t<32, 1, 32, 1, reg_layout::tiled>>; matElem_reg_w_t drop_mk_w; matElem_reg_b_t drop_mk_b; if constexpr (Dopt_RandGenflag == true) { matQKT_st.reg = xetla_cvt<dtype_sfx, float>( matQKT_reg16x32.reg); using matElem_reg_w_t = gpu::xetla::subgroup::tile_t<uint16_t, gpu::xetla::subgroup::tile_desc_t<32, 1, 32, 1, reg_layout::tiled>>; using matElem_reg_b_t = gpu::xetla::subgroup::tile_t<uint8_t, gpu::xetla::subgroup::tile_desc_t<32, 1, 32, 1, reg_layout::tiled>>; matElem_reg_w_t drop_mk_w; matElem_reg_b_t drop_mk_b; #pragma unroll for (int i = 0; i < (Max_SeqLen / (4 * 4 * RandSIMD)); i++) { rand_data = Rand_Gen.rand(); rand_bit.xetla_select<4 * RandSIMD, 1>( i * (4 * RandSIMD)) = rand_data > rand_threshold; } #pragma unroll for (int j = 0; j < 4; j++) { if constexpr (sfx_type_size == 2) { drop_mk_w.reg.xetla_select<32, 1>(0) .xetla_merge(SIGN_BIT_W16, 0, rand_bit.xetla_select<32, 1>( j * 32)); matQKT_st.reg.xetla_format<uint16_t>() .xetla_select<32, 1>(j * 32) |= drop_mk_w.reg.xetla_select<32, 1>(0); } if constexpr (sfx_type_size == 1) { drop_mk_b.reg.xetla_select<32, 1>(0) .xetla_merge(SIGN_BIT_B8, 0, rand_bit.xetla_select<32, 1>( j * 32)); matQKT_st.reg.xetla_format<uint8_t>() .xetla_select<32, 1>(j * 32) |= drop_mk_b.reg.xetla_select<32, 1>(0); } } if (std_seqlen > 128) { #pragma unroll for (int i = 0; i < (Max_SeqLen / (4 * 4 * RandSIMD)); i++) { rand_data = Rand_Gen.rand(); rand_bit.xetla_select<4 * RandSIMD, 1>( i * (4 * RandSIMD)) = rand_data > rand_threshold; } #pragma unroll for (int j = 4; j < 8; j++) { if constexpr (sfx_type_size == 2) { drop_mk_w.reg.xetla_select<32, 1>(0) .xetla_merge(SIGN_BIT_W16, 0, rand_bit.xetla_select<32, 1>((j - 4) * 32)); matQKT_st.reg.xetla_format<uint16_t>() .xetla_select<32, 1>(j * 32) |= drop_mk_w.reg .xetla_select<32, 1>(0); } if constexpr (sfx_type_size == 1) { drop_mk_b.reg.xetla_select<32, 1>(0) .xetla_merge(SIGN_BIT_B8, 0, rand_bit.xetla_select<32, 1>((j - 4) * 32)); matQKT_st.reg.xetla_format<uint8_t>() .xetla_select<32, 1>(j * 32) |= drop_mk_b.reg .xetla_select<32, 1>(0); } } if (std_seqlen > 256) { #pragma unroll for (int i = 0; i < (Max_SeqLen / (4 * 4 * RandSIMD)); i++) { rand_data = Rand_Gen.rand(); rand_bit.xetla_select<4 * RandSIMD, 1>( i * (4 * RandSIMD)) = rand_data > rand_threshold; } #pragma unroll for (int j = 8; j < 12; j++) { if constexpr (sfx_type_size == 2) { drop_mk_w.reg.xetla_select<32, 1>(0) .xetla_merge(SIGN_BIT_W16, 0, rand_bit.xetla_select< 32, 1>( (j - 8) * 32)); matQKT_st.reg.xetla_format<uint16_t>() .xetla_select<32, 1>(j * 32) |= drop_mk_w.reg .xetla_select<32, 1>( 0); } if constexpr (sfx_type_size == 1) { drop_mk_b.reg.xetla_select<32, 1>(0) .xetla_merge(SIGN_BIT_B8, 0, rand_bit.xetla_select< 32, 1>( (j - 8) * 32)); matQKT_st.reg.xetla_format<uint8_t>() .xetla_select<32, 1>(j * 32) |= drop_mk_b.reg .xetla_select<32, 1>( 0); } } if (std_seqlen > 384) { #pragma unroll for (int i = 0; i < (Max_SeqLen / (4 * 4 * RandSIMD)); i++) { rand_data = Rand_Gen.rand(); rand_bit.xetla_select<4 * RandSIMD, 1>( i * (4 * RandSIMD)) = rand_data > rand_threshold; } #pragma unroll for (int j = 12; j < 16; j++) { if constexpr (sfx_type_size == 2) { drop_mk_w.reg.xetla_select<32, 1>(0) .xetla_merge(SIGN_BIT_W16, 0, rand_bit.xetla_select< 32, 1>( (j - 12) * 32)); matQKT_st.reg .xetla_format<uint16_t>() .xetla_select<32, 1>(j * 32) |= drop_mk_w.reg .xetla_select<32, 1>(0); } if constexpr (sfx_type_size == 1) { drop_mk_b.reg.xetla_select<32, 1>(0) .xetla_merge(SIGN_BIT_B8, 0, rand_bit.xetla_select< 32, 1>( (j - 12) * 32)); matQKT_st.reg .xetla_format<uint8_t>() .xetla_select<32, 1>(j * 32) |= drop_mk_b.reg .xetla_select<32, 1>(0); } } } } } } else { matQKT_st.reg = xetla_cvt<dtype_sfx, float>( matQKT_reg16x32.reg); #pragma unroll for (int j = 0; j < 16; j++) { uint32_t mkdata_i = mkdpot_vec16[j]; xetla_mask_int<32> mkdata = xetla_mask_int_gen<32>(mkdata_i); if constexpr (sfx_type_size == 2) { drop_mk_w.reg.xetla_select<32, 1>(0) .xetla_merge(SIGN_BIT_W16, 0, mkdata); matQKT_st.reg.xetla_format<uint16_t>() .xetla_select<32, 1>(j * 32) |= drop_mk_w.reg.xetla_select<32, 1>(0); } if constexpr (sfx_type_size == 1) { drop_mk_b.reg.xetla_select<32, 1>(0) .xetla_merge(SIGN_BIT_B8, 0, mkdata); matQKT_st.reg.xetla_format<uint8_t>() .xetla_select<32, 1>(j * 32) |= drop_mk_b.reg.xetla_select<32, 1>(0); } } matQKT_st.reg = xetla_cvt<dtype_sfx, float>( matQKT_reg16x32.reg); } subgroup::tile_store(matQKT_st, matQKT_st_payload); xetla_fence<memory_kind::untyped_global>(); } second_nbarr.arrive(); second_nbarr.wait(); } //QKtV { brgemm_arguments_128x64 brgemm_arg_128x64; matAcc_128x64_t matAcc_128x64; matC_128x64_t matC_128x64; matC_128x64_payload_t matC_128x64_payload; uint32_t width_a = tru_seqlen_ex; uint32_t height_a = (batchid * numhead + headid) * max_seqlen + tru_seqlen; uint32_t pitch_a = max_seqlen; int start_x_a = 0; int start_y_a = (batchid * numhead + headid) * max_seqlen + all_vert128_loop * 128; brgemm_arg_128x64.matA_base_desc.init({args->matQKT_ptr}, {width_a, height_a, pitch_a}, {start_x_a, start_y_a}); uint32_t width_b = (headid + 1) * hdsz; uint32_t height_b = tru_seqlen + seqlen_entry; uint32_t pitch_b = hiddensize; int start_x_b = headid * hdsz; int start_y_b = seqlen_entry; brgemm_arg_128x64.matB_base_desc.init({args->matV_ptr}, {width_b, height_b, pitch_b}, {start_x_b, start_y_b}); brgemm_arg_128x64.inner_loop_count = (wg_tile_out_k + k_stride - 1) / k_stride; matAcc_128x64.init(0); brgemm_op_128x64_t brgemm_op_128x64; brgemm_op_128x64(g_thd32_tid, matAcc_128x64, brgemm_arg_128x64); uint32_t width_c = (headid + 1) * hdsz; uint32_t height_c = tru_seqlen + seqlen_entry; uint32_t pitch_c = hiddensize; int start_x_c = headid * hdsz + brgemm_op_128x64_t::get_matC_offset_x(g_thd32_tid); int start_y_c = all_vert128_loop * 128 + seqlen_entry + brgemm_op_128x64_t::get_matC_offset_y(g_thd32_tid); matC_128x64_payload.init(args->matOut_ptr, width_c, height_c, pitch_c, start_x_c, start_y_c); subgroup::elemwise_cvt<matC_128x64_t, matAcc_128x64_t>( matC_128x64, matAcc_128x64); subgroup::tile_store(matC_128x64, matC_128x64_payload); } } //all_vert128_loop } //xetla_softmax_fwd_t::call() }; //struct xetla_softmax_fwd_t /// @brief /// /// @tparam dtype_bwd_bin_ /// @tparam dtype_bwd_bot_ /// @tparam dtype_bwd_sfx_ /// @tparam dtype_bwd_acc_ /// @tparam HWThreadNum /// @tparam Dopt_RandGenflag /// @tparam Mkin_flag template <typename dtype_bwd_bin_, typename dtype_bwd_bot_, typename dtype_bwd_sfx_, typename dtype_bwd_acc_, int HWThreadNum, bool Dopt_RandGenflag = true, bool Mkin_flag = false> struct xetla_mha_core_attn_bwd_t { using dtype_bin = dtype_bwd_bin_; using dtype_bot = dtype_bwd_bot_; using dtype_sfx = dtype_bwd_sfx_; using dtype_acc = dtype_bwd_acc_; static constexpr int ThreadNum = HWThreadNum; static_assert(ThreadNum == 32); static constexpr mem_space mem_space_a = mem_space::global; static constexpr mem_space mem_space_b = mem_space::global; static constexpr mem_space mem_space_c = mem_space::global; static constexpr mem_layout mem_layout_a = mem_layout::row_major; static constexpr mem_layout mem_layout_trnp_a = mem_layout::col_major; static constexpr mem_layout mem_layout_QKT_b = mem_layout::col_major; static constexpr mem_layout mem_layout_out_b = mem_layout::row_major; static constexpr mem_layout mem_layout_c = mem_layout::row_major; static constexpr mem_space brgemm_mem_space_a = mem_space_a; static constexpr mem_space brgemm_mem_space_trnp_a = mem_space_a; static constexpr mem_layout brgemm_mem_layout_a = mem_layout_a; static constexpr mem_layout brgemm_mem_layout_trnp_a = mem_layout_trnp_a; static constexpr mem_space brgemm_mem_space_b = mem_space_b; static constexpr mem_layout brgemm_mem_layout_QKT_b = mem_layout_QKT_b; static constexpr mem_layout brgemm_mem_layout_out_b = mem_layout_out_b; static constexpr uint32_t periodic_sync_interval = 0; static constexpr uint32_t prefetch_distance = 3; static constexpr uint32_t k_stride = 32 / sizeof(dtype_bin); //brgemm_config::k_stride; using bgm_perf_tuning_knob = group::perf_tuning_knob_t<k_stride, prefetch_distance, periodic_sync_interval>; using tile_attr_128x128 = group::tile_shape_t<128, 128, 32, 16>; using tile_attr_128x256 = group::tile_shape_t<256, 128, 32, 32>; using tile_attr_256x64 = group::tile_shape_t<64, 256, 16, 32>; using tile_attr_128x64 = group::tile_shape_t<64, 128, 16, 16>; using mem_desc_a_QKT = mem_desc_t<dtype_bin, brgemm_mem_layout_a, brgemm_mem_space_a>; using mem_desc_b_QKT = mem_desc_t<dtype_bin, brgemm_mem_layout_QKT_b, brgemm_mem_space_b>; using compute_policy_QKT = group::compute_policy_default_xmx< group::compute_attr_t<dtype_bin, dtype_bin, dtype_acc>, bgm_perf_tuning_knob, gpu_arch::Xe>; using mem_desc_a_out = mem_desc_t<dtype_sfx, brgemm_mem_layout_a, brgemm_mem_space_a>; using mem_desc_b_out = mem_desc_t<dtype_bin, brgemm_mem_layout_out_b, brgemm_mem_space_b>; using compute_policy_out = group::compute_policy_default_xmx< group::compute_attr_t<dtype_sfx, dtype_bin, dtype_acc>, bgm_perf_tuning_knob, gpu_arch::Xe>; using mem_desc_a_out_b_trnp_a = mem_desc_t<dtype_sfx, brgemm_mem_layout_trnp_a, brgemm_mem_space_trnp_a>; using mem_desc_b_out_b_trnp_a = mem_desc_t<dtype_bin, brgemm_mem_layout_out_b, brgemm_mem_space_b>; using compute_policy_out_b_trnp_a = group::compute_policy_default_xmx< group::compute_attr_t<dtype_sfx, dtype_bin, dtype_acc>, bgm_perf_tuning_knob, gpu_arch::Xe>; using arch_attr = arch_attr_t<gpu_arch::Xe>; static constexpr uint32_t l3_kslicing = 1; static constexpr uint16_t sfx_type_size = sizeof(dtype_sfx); static_assert((sfx_type_size == 1) || (sfx_type_size == 2) || (sfx_type_size == 4)); using work_group_t = work_group_t<ThreadNum>; using pre_processing_128x128 = group::pre_processing_default_t<tile_attr_128x128, gpu_arch::Xe>; using pre_processing_128x256 = group::pre_processing_default_t<tile_attr_128x256, gpu_arch::Xe>; using pre_processing_128x64 = group::pre_processing_default_t<tile_attr_128x64, gpu_arch::Xe>; using pre_processing_256x64 = group::pre_processing_default_t<tile_attr_256x64, gpu_arch::Xe>; using pre_processing_128x64_af = group::pre_processing_matA_neg_filter_t<tile_attr_128x64, gpu_arch::Xe>; using pre_processing_256x64_af = group::pre_processing_matA_neg_filter_t<tile_attr_256x64, gpu_arch::Xe>; using brgemm_op_128x128_t = group::brgemm_t<compute_policy_QKT, tile_attr_128x128, mem_desc_a_QKT, mem_desc_b_QKT, pre_processing_128x128>; using brgemm_op_128x256_t = group::brgemm_t<compute_policy_QKT, tile_attr_128x256, mem_desc_a_QKT, mem_desc_b_QKT, pre_processing_128x256>; using brgemm_op_128x64_t = group::brgemm_t<compute_policy_out, tile_attr_128x64, mem_desc_a_out, mem_desc_b_out, pre_processing_128x64>; using brgemm_op_128x64_trnp_a_t = group::brgemm_t<compute_policy_out_b_trnp_a, tile_attr_128x64, mem_desc_a_out_b_trnp_a, mem_desc_b_out_b_trnp_a, pre_processing_128x64>; using brgemm_op_256x64_trnp_a_t = group::brgemm_t<compute_policy_out_b_trnp_a, tile_attr_256x64, mem_desc_a_out_b_trnp_a, mem_desc_b_out_b_trnp_a, pre_processing_256x64>; using brgemm_op_128x64_trnp_af_t = group::brgemm_t<compute_policy_out_b_trnp_a, tile_attr_128x64, mem_desc_a_out_b_trnp_a, mem_desc_b_out_b_trnp_a, pre_processing_128x64_af>; using brgemm_op_256x64_trnp_af_t = group::brgemm_t<compute_policy_out_b_trnp_a, tile_attr_256x64, mem_desc_a_out_b_trnp_a, mem_desc_b_out_b_trnp_a, pre_processing_256x64_af>; using brgemm_arguments_128x128 = typename brgemm_op_128x128_t::arguments_t; using brgemm_arguments_128x256 = typename brgemm_op_128x256_t::arguments_t; using brgemm_arguments_128x64 = typename brgemm_op_128x64_t::arguments_t; using brgemm_arguments_128x64_trnp_a = typename brgemm_op_128x64_trnp_a_t::arguments_t; using brgemm_arguments_256x64_trnp_a = typename brgemm_op_256x64_trnp_a_t::arguments_t; using brgemm_arguments_128x64_trnp_af = typename brgemm_op_128x64_trnp_af_t::arguments_t; using brgemm_arguments_256x64_trnp_af = typename brgemm_op_256x64_trnp_af_t::arguments_t; using matAcc_128x128_t = typename brgemm_op_128x128_t::matAcc_t; using matAcc_128x256_t = typename brgemm_op_128x256_t::matAcc_t; using matAcc_128x64_t = typename brgemm_op_128x64_t::matAcc_t; using matAcc_128x64_trnp_a_t = typename brgemm_op_128x64_trnp_a_t::matAcc_t; using matAcc_256x64_trnp_a_t = typename brgemm_op_256x64_trnp_a_t::matAcc_t; using matAcc_128x64_trnp_af_t = typename brgemm_op_128x64_trnp_af_t::matAcc_t; using matAcc_256x64_trnp_af_t = typename brgemm_op_256x64_trnp_af_t::matAcc_t; using matC_128x128_tile_desc_t = subgroup::tile_desc_t<matAcc_128x128_t::tile_desc::tile_size_x, matAcc_128x128_t::tile_desc::tile_size_y, matAcc_128x128_t::tile_desc::block_size_x, matAcc_128x128_t::tile_desc::block_size_y, reg_layout::tiled>; using matC_128x256_tile_desc_t = subgroup::tile_desc_t<matAcc_128x256_t::tile_desc::tile_size_x, matAcc_128x256_t::tile_desc::tile_size_y, matAcc_128x256_t::tile_desc::block_size_x, matAcc_128x256_t::tile_desc::block_size_y, reg_layout::tiled>; using matC_128x64_tile_desc_t = subgroup::tile_desc_t<matAcc_128x64_t::tile_desc::tile_size_x, matAcc_128x64_t::tile_desc::tile_size_y, matAcc_128x64_t::tile_desc::block_size_x, matAcc_128x64_t::tile_desc::block_size_y, reg_layout::tiled>; using matC_128x64_trnp_a_tile_desc_t = subgroup::tile_desc_t< matAcc_128x64_trnp_a_t::tile_desc::tile_size_x, matAcc_128x64_trnp_a_t::tile_desc::tile_size_y, matAcc_128x64_trnp_a_t::tile_desc::block_size_x, matAcc_128x64_trnp_a_t::tile_desc::block_size_y, reg_layout::tiled>; using matC_256x64_trnp_a_tile_desc_t = subgroup::tile_desc_t< matAcc_256x64_trnp_a_t::tile_desc::tile_size_x, matAcc_256x64_trnp_a_t::tile_desc::tile_size_y, matAcc_256x64_trnp_a_t::tile_desc::block_size_x, matAcc_256x64_trnp_a_t::tile_desc::block_size_y, reg_layout::tiled>; using matC_128x64_trnp_af_tile_desc_t = subgroup::tile_desc_t< matAcc_128x64_trnp_af_t::tile_desc::tile_size_x, matAcc_128x64_trnp_af_t::tile_desc::tile_size_y, matAcc_128x64_trnp_af_t::tile_desc::block_size_x, matAcc_128x64_trnp_af_t::tile_desc::block_size_y, reg_layout::tiled>; using matC_256x64_trnp_af_tile_desc_t = subgroup::tile_desc_t< matAcc_256x64_trnp_af_t::tile_desc::tile_size_x, matAcc_256x64_trnp_af_t::tile_desc::tile_size_y, matAcc_256x64_trnp_af_t::tile_desc::block_size_x, matAcc_256x64_trnp_af_t::tile_desc::block_size_y, reg_layout::tiled>; using matC_128x128_t = subgroup::tile_t<dtype_sfx, matC_128x128_tile_desc_t>; using matC_128x256_t = subgroup::tile_t<dtype_sfx, matC_128x256_tile_desc_t>; using matC_128x64_t = subgroup::tile_t<dtype_bot, matC_128x64_tile_desc_t>; using matC_128x64_trnp_a_t = subgroup::tile_t<dtype_bot, matC_128x64_trnp_a_tile_desc_t>; using matC_256x64_trnp_a_t = subgroup::tile_t<dtype_bot, matC_256x64_trnp_a_tile_desc_t>; using matC_128x64_trnp_af_t = subgroup::tile_t<dtype_bot, matC_128x64_trnp_af_tile_desc_t>; using matC_256x64_trnp_af_t = subgroup::tile_t<dtype_bot, matC_256x64_trnp_af_tile_desc_t>; using matC_128x128_payload_t = subgroup::mem_payload_t<dtype_sfx, matC_128x128_tile_desc_t, (l3_kslicing > 1) ? msg_type::atomic_add : subgroup::msg_type_v<matC_128x128_tile_desc_t, mem_space_c>, mem_layout_c, mem_space_c, gpu_arch::Xe>; using matC_128x256_payload_t = subgroup::mem_payload_t<dtype_sfx, matC_128x256_tile_desc_t, (l3_kslicing > 1) ? msg_type::atomic_add : subgroup::msg_type_v<matC_128x256_tile_desc_t, mem_space_c>, mem_layout_c, mem_space_c, gpu_arch::Xe>; using matC_128x64_payload_t = subgroup::mem_payload_t<dtype_bot, matC_128x64_tile_desc_t, (l3_kslicing > 1) ? msg_type::atomic_add : subgroup::msg_type_v<matC_128x64_tile_desc_t, mem_space_c>, mem_layout_c, mem_space_c, gpu_arch::Xe>; using matC_128x64_trnp_a_payload_t = subgroup::mem_payload_t<dtype_bot, matC_128x64_trnp_a_tile_desc_t, (l3_kslicing > 1) ? msg_type::atomic_add : subgroup::msg_type_v<matC_128x64_trnp_a_tile_desc_t, mem_space_c>, mem_layout_c, mem_space_c, gpu_arch::Xe>; using matC_256x64_trnp_a_payload_t = subgroup::mem_payload_t<dtype_bot, matC_256x64_trnp_a_tile_desc_t, (l3_kslicing > 1) ? msg_type::atomic_add : subgroup::msg_type_v<matC_256x64_trnp_a_tile_desc_t, mem_space_c>, mem_layout_c, mem_space_c, gpu_arch::Xe>; using matC_128x64_trnp_af_payload_t = subgroup::mem_payload_t<dtype_bot, matC_128x64_trnp_af_tile_desc_t, (l3_kslicing > 1) ? msg_type::atomic_add : subgroup::msg_type_v<matC_128x64_trnp_af_tile_desc_t, mem_space_c>, mem_layout_c, mem_space_c, gpu_arch::Xe>; using matC_256x64_trnp_af_payload_t = subgroup::mem_payload_t<dtype_bot, matC_256x64_trnp_af_tile_desc_t, (l3_kslicing > 1) ? msg_type::atomic_add : subgroup::msg_type_v<matC_256x64_trnp_af_tile_desc_t, mem_space_c>, mem_layout_c, mem_space_c, gpu_arch::Xe>; //512 = 16x32 or 8x64 using matElem_tile_desc_t = gpu::xetla::subgroup::tile_desc_t<64 / sfx_type_size, 8 * sfx_type_size, 64 / sfx_type_size, 8 * sfx_type_size, reg_layout::tiled>; using matElem_ld_t = gpu::xetla::subgroup::tile_t<dtype_sfx, matElem_tile_desc_t>; using matElem_st_t = gpu::xetla::subgroup::tile_t<dtype_sfx, matElem_tile_desc_t>; using matElem_ld_payload_t = gpu::xetla::subgroup::mem_payload_t<dtype_sfx, matElem_tile_desc_t, subgroup::msg_type_v<matElem_tile_desc_t, mem_space::global>, mem_layout::row_major, mem_space::global, gpu_arch::Xe>; using matElem_st_payload_t = gpu::xetla::subgroup::mem_payload_t<dtype_sfx, matElem_tile_desc_t, msg_type::block_2d, mem_layout::row_major, mem_space::global, gpu_arch::Xe>; using matElem_reg_t = gpu::xetla::subgroup::tile_t<float, gpu::xetla::subgroup::tile_desc_t<32, 16, 32, 16, reg_layout::tiled>>; /// @brief Arguments for xetla_softmax_bwd_t::run. /// User should prepare matQ_ptr, matK_ptr, matV_ptr, ... struct arguments_t { // assume base address, surface width, height, pitch, start coordinate was set uint32_t *mList_ptr; dtype_bin *matQ_ptr; dtype_bin *matK_ptr; dtype_bin *matV_ptr; uint32_t *matMkin_ptr; uint32_t *matMkdpot_ptr; dtype_bin *matdO_ptr; dtype_sfx *matW_ptr; dtype_sfx *matdW_ptr; dtype_bot *matdV_ptr; dtype_bot *matdQ_ptr; dtype_bot *matdK_ptr; float Pinv; float Scaling; }; /// @brief Main execution function for fused mha softmax. /// The basic process is BRGEMM -> Softmax -> BRGEMM. /// /// @param ei /// @param args Includes base descriptors and tid info. /// @return __XETLA_API static void call(xetla_exec_item<3> &ei, arguments_t *args) { int tru_seqlen = 0; int tru_seqlen_ex = 0; int seqlen_entry = 0; int hiddensize = 1024; int numhead = 16; int hdsz = 64; int max_seqlen = 512; int wg_tile_QKT_k = hdsz; //args->matrix_k; int wg_tile_out_k; int groupid = ei.get_group(0); int batchid = groupid / numhead; int headid = groupid % numhead; //float totalscaling = args->Pinv * args->Scaling; uint32_t batch_offset = sizeof(uint32_t) * list_width * batchid; xetla_vector<uint32_t, list_width> list_offsets = xetla_vector_gen<uint32_t, list_width>(0, 1); list_offsets *= sizeof(uint32_t); list_offsets += batch_offset; xetla_vector<uint32_t, list_width> list_vec = xetla_load_global<uint32_t, 1, data_size::default_size, cache_hint::read_invalidate, cache_hint::cached, list_width>(args->mList_ptr, list_offsets); tru_seqlen = list_vec[0]; seqlen_entry = list_vec[1]; wg_tile_out_k = tru_seqlen; tru_seqlen_ex = tru_seqlen; //4: dw aligned if (sfx_type_size == 2) tru_seqlen_ex = ((tru_seqlen + 1) >> 1) << 1; else if (sfx_type_size == 1) tru_seqlen_ex = ((tru_seqlen + 3) >> 2) << 2; //reset for all std_seqlen int all_vert_loop_num = 0; int transp128_loop_num = 0; int transp256_loop_num = 0; int blk_128x128_one = 0; int blk_128x256_loop_num = 0; int offset_blk_128x128 = 0; int std_seqlen; if (tru_seqlen <= 128) { std_seqlen = 128; all_vert_loop_num = 1; transp128_loop_num = 1; blk_128x128_one = 1; } else if (tru_seqlen <= 256) { std_seqlen = 256; all_vert_loop_num = 2; transp256_loop_num = 1; blk_128x256_loop_num = 1; } else if (tru_seqlen <= 384) { std_seqlen = 384; all_vert_loop_num = 3; transp128_loop_num = 1; transp256_loop_num = 1; blk_128x128_one = 1; blk_128x256_loop_num = 1; offset_blk_128x128 = 256; } else { std_seqlen = 512; all_vert_loop_num = 4; transp256_loop_num = 2; blk_128x256_loop_num = 2; } work_group_t g_thd32_tid; int tid_linear = ei.get_local_linear_id(); g_thd32_tid.init(tid_linear); static_assert(ThreadNum == 32, "All Thread Sync"); xetla_nbarrier_t<ThreadNum, ThreadNum> first_nbarr; xetla_nbarrier_t<ThreadNum, ThreadNum> second_nbarr; int max_2d_nbar_id = ThreadNum >> 1; first_nbarr.init_nbarrier( max_2d_nbar_id, nbarrier_role::producer_consumer); second_nbarr.init_nbarrier( max_2d_nbar_id + 1, nbarrier_role::producer_consumer); xetla_nbarrier_t<ThreadNum, ThreadNum> all_nbarr; all_nbarr.init_nbarrier( ThreadNum - 1, nbarrier_role::producer_consumer); for (int transp128_loop = 0; transp128_loop < transp128_loop_num; transp128_loop++) { brgemm_arguments_128x64_trnp_af brgemm_arg_128x64; matAcc_128x64_trnp_af_t matAcc_128x64; matC_128x64_trnp_af_t matC_128x64; matC_128x64_trnp_af_payload_t matC_128x64_payload; uint32_t width_a = tru_seqlen_ex; uint32_t height_a = (batchid * numhead + headid) * max_seqlen + tru_seqlen; uint32_t pitch_a = max_seqlen; int start_x_a = transp128_loop * 128 + offset_blk_128x128; int start_y_a = (batchid * numhead + headid) * max_seqlen; brgemm_arg_128x64.matA_base_desc.init({args->matW_ptr}, {height_a, width_a, pitch_a}, {start_y_a, start_x_a}); uint32_t width_b = (headid + 1) * hdsz; uint32_t height_b = tru_seqlen + seqlen_entry; uint32_t pitch_b = hiddensize; int start_x_b = headid * hdsz; int start_y_b = seqlen_entry; brgemm_arg_128x64.matB_base_desc.init({args->matdO_ptr}, {width_b, height_b, pitch_b}, {start_x_b, start_y_b}); brgemm_arg_128x64.inner_loop_count = (wg_tile_out_k + k_stride - 1) / k_stride; matAcc_128x64.init(0); brgemm_op_128x64_trnp_af_t brgemm_op_128x64_trnp_af; brgemm_op_128x64_trnp_af( g_thd32_tid, matAcc_128x64, brgemm_arg_128x64); int width_c = (headid + 1) * hdsz; int height_c = tru_seqlen + seqlen_entry; int pitch_c = hiddensize; int start_x_c = headid * hdsz + brgemm_op_128x64_trnp_af_t::get_matC_offset_x( g_thd32_tid); int start_y_c = transp128_loop * 128 + seqlen_entry + offset_blk_128x128 + brgemm_op_128x64_trnp_af_t::get_matC_offset_y( g_thd32_tid); matC_128x64_payload.init(args->matdV_ptr, width_c, height_c, pitch_c, start_x_c, start_y_c); subgroup::elemwise_cvt<matC_128x64_trnp_af_t, matAcc_128x64_trnp_af_t>(matC_128x64, matAcc_128x64); subgroup::tile_store(matC_128x64, matC_128x64_payload); //add global sync if nbarr used inside brgemm all_nbarr.arrive(); all_nbarr.wait(); } for (int transp256_loop = 0; transp256_loop < transp256_loop_num; transp256_loop++) { brgemm_arguments_256x64_trnp_af brgemm_arg_256x64; matAcc_256x64_trnp_af_t matAcc_256x64; matC_256x64_trnp_af_t matC_256x64; matC_256x64_trnp_af_payload_t matC_256x64_payload; uint32_t width_a = tru_seqlen_ex; uint32_t height_a = (batchid * numhead + headid) * max_seqlen + tru_seqlen; uint32_t pitch_a = max_seqlen; int start_x_a = transp256_loop * 256; int start_y_a = (batchid * numhead + headid) * max_seqlen; brgemm_arg_256x64.matA_base_desc.init({args->matW_ptr}, {height_a, width_a, pitch_a}, {start_y_a, start_x_a}); uint32_t width_b = (headid + 1) * hdsz; uint32_t height_b = tru_seqlen + seqlen_entry; uint32_t pitch_b = hiddensize; int start_x_b = headid * hdsz; int start_y_b = seqlen_entry; brgemm_arg_256x64.matB_base_desc.init({args->matdO_ptr}, {width_b, height_b, pitch_b}, {start_x_b, start_y_b}); brgemm_arg_256x64.inner_loop_count = (wg_tile_out_k + k_stride - 1) / k_stride; matAcc_256x64.init(0); brgemm_op_256x64_trnp_af_t brgemm_op_256x64_trnp_af; brgemm_op_256x64_trnp_af( g_thd32_tid, matAcc_256x64, brgemm_arg_256x64); int width_c = (headid + 1) * hdsz; int height_c = tru_seqlen + seqlen_entry; int pitch_c = hiddensize; int start_x_c = headid * hdsz + brgemm_op_256x64_trnp_af_t::get_matC_offset_x( g_thd32_tid); int start_y_c = transp256_loop * 256 + seqlen_entry + brgemm_op_256x64_trnp_af_t::get_matC_offset_y( g_thd32_tid); matC_256x64_payload.init(args->matdV_ptr, width_c, height_c, pitch_c, start_x_c, start_y_c); subgroup::elemwise_cvt<matC_256x64_trnp_af_t, matAcc_256x64_trnp_af_t>(matC_256x64, matAcc_256x64); subgroup::tile_store(matC_256x64, matC_256x64_payload); //add global sync if nbarr used inside brgemm all_nbarr.arrive(); all_nbarr.wait(); } for (int all_vert128_loop = 0; all_vert128_loop < all_vert_loop_num; all_vert128_loop++) { //dW for (int hor_256_loop = 0; hor_256_loop < blk_128x256_loop_num; hor_256_loop++) { brgemm_arguments_128x256 brgemm_arg_128x256; matAcc_128x256_t matAcc_128x256; matC_128x256_t matC_128x256; matC_128x256_payload_t matC_128x256_payload; uint32_t width_a = (headid + 1) * hdsz; uint32_t height_a = tru_seqlen + seqlen_entry; uint32_t pitch_a = hiddensize; int start_x_a = headid * hdsz; int start_y_a = all_vert128_loop * 128 + seqlen_entry; brgemm_arg_128x256.matA_base_desc.init({args->matdO_ptr}, {width_a, height_a, pitch_a}, {start_x_a, start_y_a}); uint32_t width_b = (headid + 1) * hdsz; uint32_t height_b = tru_seqlen + seqlen_entry; uint32_t pitch_b = hiddensize; int start_x_b = headid * hdsz; int start_y_b = hor_256_loop * 256 + seqlen_entry; //B transpose, be swapped in init brgemm_arg_128x256.matB_base_desc.init({args->matV_ptr}, {height_b, width_b, pitch_b}, {start_y_b, start_x_b}); brgemm_arg_128x256.inner_loop_count = (wg_tile_QKT_k + k_stride - 1) / k_stride; matAcc_128x256.init(0); brgemm_op_128x256_t brgemm_op_128x256; brgemm_op_128x256( g_thd32_tid, matAcc_128x256, brgemm_arg_128x256); int width_c = max_seqlen; int height_c = max_seqlen * (batchid * numhead + headid + 1); int pitch_c = max_seqlen; int start_x_c = brgemm_op_128x256_t::get_matC_offset_x(g_thd32_tid) + hor_256_loop * 256; int start_y_c = (batchid * numhead + headid) * max_seqlen + all_vert128_loop * 128 + brgemm_op_128x256_t::get_matC_offset_y(g_thd32_tid); matC_128x256_payload.init(args->matdW_ptr, width_c, height_c, pitch_c, start_x_c, start_y_c); subgroup::elemwise_cvt<matC_128x256_t, matAcc_128x256_t>( matC_128x256, matAcc_128x256); subgroup::tile_store(matC_128x256, matC_128x256_payload); xetla_fence<memory_kind::untyped_global>(); } for (int blk_128x128_loop = 0; blk_128x128_loop < blk_128x128_one; blk_128x128_loop++) { brgemm_arguments_128x128 brgemm_arg_128x128; matAcc_128x128_t matAcc_128x128; matC_128x128_t matC_128x128; matC_128x128_payload_t matC_128x128_payload; uint32_t width_a = (headid + 1) * hdsz; uint32_t height_a = tru_seqlen + seqlen_entry; uint32_t pitch_a = hiddensize; int start_x_a = headid * hdsz; int start_y_a = all_vert128_loop * 128 + seqlen_entry; brgemm_arg_128x128.matA_base_desc.init({args->matdO_ptr}, {width_a, height_a, pitch_a}, {start_x_a, start_y_a}); uint32_t width_b = (headid + 1) * hdsz; uint32_t height_b = tru_seqlen + seqlen_entry; uint32_t pitch_b = hiddensize; int start_x_b = headid * hdsz; int start_y_b = offset_blk_128x128 + seqlen_entry; //B transpose, be swapped in init brgemm_arg_128x128.matB_base_desc.init({args->matV_ptr}, {height_b, width_b, pitch_b}, {start_y_b, start_x_b}); brgemm_arg_128x128.inner_loop_count = (wg_tile_QKT_k + k_stride - 1) / k_stride; matAcc_128x128.init(0); brgemm_op_128x128_t brgemm_op_128x128; brgemm_op_128x128( g_thd32_tid, matAcc_128x128, brgemm_arg_128x128); int width_c = max_seqlen; int height_c = max_seqlen * (batchid * numhead + headid + 1); int pitch_c = max_seqlen; int start_x_c = offset_blk_128x128 + brgemm_op_128x128_t::get_matC_offset_x(g_thd32_tid); int start_y_c = (batchid * numhead + headid) * max_seqlen + all_vert128_loop * 128 + brgemm_op_128x128_t::get_matC_offset_y(g_thd32_tid); matC_128x128_payload.init(args->matdW_ptr, width_c, height_c, pitch_c, start_x_c, start_y_c); subgroup::elemwise_cvt<matC_128x128_t, matAcc_128x128_t>( matC_128x128, matAcc_128x128); subgroup::tile_store(matC_128x128, matC_128x128_payload); xetla_fence<memory_kind::untyped_global>(); } int elem_Ln512_loop_num = 4; int height_8x64_512 = 8 * sfx_type_size; int width_8x16_512 = 64 / sfx_type_size; int height_elem_offset = (max_seqlen * (batchid * numhead + headid) + (all_vert128_loop * 128) + (tid_linear * 4)) * height_8x64_512; int width_elem = width_8x16_512; int height_elem; int pitch_elem = width_elem; int start_x_elem = 0; int start_y_elem; xetla_vector<uint32_t, 16> mkin_vec16; if constexpr (Mkin_flag == true) { uint32_t mk_attn_all = sizeof(uint32_t) * (max_seqlen / 32) * (batchid); xetla_vector<uint32_t, 16> mk_attn_offsets = xetla_vector_gen<uint32_t, 16>(0, 1); mk_attn_offsets *= sizeof(uint32_t); mk_attn_offsets += mk_attn_all; mkin_vec16 = xetla_load_global<uint32_t, 1, data_size::default_size, cache_hint::read_invalidate, cache_hint::cached, 16>( args->matMkin_ptr, mk_attn_offsets); } uint32_t mk_offset_all; xetla_vector<uint32_t, 16> mk_offsets = xetla_vector_gen<uint32_t, 16>(0, 1); if constexpr (Dopt_RandGenflag == false) { mk_offset_all = sizeof(uint32_t) * (max_seqlen / 32) * ((batchid * numhead + headid) * max_seqlen + (all_vert128_loop * 128) + tid_linear * 4); mk_offsets *= sizeof(uint32_t); mk_offsets += mk_offset_all; } first_nbarr.arrive(); first_nbarr.wait(); for (int elem_Ln512_loop = 0; elem_Ln512_loop < elem_Ln512_loop_num; elem_Ln512_loop++) { matElem_ld_t matdW_rd; matElem_ld_payload_t matdW_rd_payload; matElem_ld_t matW_rd; matElem_ld_payload_t matW_rd_payload; matElem_st_t matdW_st; matElem_st_payload_t matdW_st_payload; matElem_reg_t matdW_reg16x32; matElem_reg_t matW_reg16x32; xetla_vector<uint32_t, 16> mkdpot_vec16; start_y_elem = height_elem_offset + elem_Ln512_loop * height_8x64_512; height_elem = start_y_elem + ((std_seqlen * sfx_type_size) / 64); matdW_rd_payload.init(args->matdW_ptr, width_elem, height_elem, pitch_elem, start_x_elem, start_y_elem); matW_rd_payload.init(args->matW_ptr, width_elem, height_elem, pitch_elem, start_x_elem, start_y_elem); matdW_st_payload.init(args->matdW_ptr, width_elem, height_elem, pitch_elem, start_x_elem, start_y_elem); subgroup::tile_load<cache_hint::cached, cache_hint::cached>( matdW_rd, matdW_rd_payload); subgroup::tile_load<cache_hint::cached, cache_hint::cached>( matW_rd, matW_rd_payload); if constexpr (Dopt_RandGenflag == false) { mkdpot_vec16 = xetla_load_global<uint32_t, 1, data_size::default_size, cache_hint::read_invalidate, cache_hint::cached, 16>(args->matMkdpot_ptr, mk_offsets); mk_offsets += sizeof(uint32_t) * (max_seqlen / 32); } matdW_reg16x32.reg = xetla_cvt<float, dtype_sfx>(matdW_rd.reg); matW_reg16x32.reg = xetla_cvt<float, dtype_sfx>(matW_rd.reg); if constexpr (Dopt_RandGenflag == false) { #pragma unroll for (int j = 0; j < 16; j++) { uint32_t mkdata_i = mkdpot_vec16[j]; xetla_mask_int<32> mkdata = xetla_mask_int_gen<32>(mkdata_i); matdW_reg16x32.reg.xetla_format<float>() .xetla_select<32, 1>(j * 32) .xetla_merge(0.0, matdW_reg16x32.reg.xetla_format<float>() .xetla_select<32, 1>(j * 32), mkdata); } matdW_reg16x32.reg = matW_reg16x32.reg * matdW_reg16x32.reg; } else { #pragma unroll for (int j = 0; j < 16; j++) { xetla_mask<32> mask; if constexpr (sfx_type_size == 2) { mask = matW_rd.reg.xetla_format<int16_t>() .xetla_select<32, 1>(j * 32) < 0; matW_rd.reg.xetla_format<uint16_t>() .xetla_select<32, 1>(j * 32) &= 0x7FFF; } if constexpr (sfx_type_size == 1) { mask = matW_rd.reg.xetla_format<int8_t>() .xetla_select<32, 1>(j * 32) < 0; matW_rd.reg.xetla_format<uint8_t>() .xetla_select<32, 1>(j * 32) &= 0x7F; } matW_reg16x32.reg.xetla_format<float>() .xetla_select<32, 1>(j * 32) .xetla_merge(0.0, mask); } matdW_reg16x32.reg = matW_reg16x32.reg * matdW_reg16x32.reg; matW_reg16x32.reg = xetla_cvt<float, dtype_sfx>(matW_rd.reg); matW_reg16x32.reg *= args->Scaling; } xetla_vector<float, 16> mdw_sum = matdW_reg16x32.reg.xetla_select<16, 1>(0); #pragma unroll for (int j = 1; j < 32; j++) mdw_sum = mdw_sum + matdW_reg16x32.reg.xetla_select<16, 1>(j * 16); mdw_sum.xetla_select<8, 1>(0) = mdw_sum.xetla_select<8, 1>(0) + mdw_sum.xetla_select<8, 1>(8); mdw_sum.xetla_select<4, 1>(0) = mdw_sum.xetla_select<4, 1>(0) + mdw_sum.xetla_select<4, 1>(4); mdw_sum.xetla_select<2, 1>(0) = mdw_sum.xetla_select<2, 1>(0) + mdw_sum.xetla_select<2, 1>(2); mdw_sum.xetla_select<1, 1>(0) = mdw_sum.xetla_select<1, 1>(0) + mdw_sum.xetla_select<1, 1>(1); { float sumtmp = mdw_sum[0]; matW_reg16x32.reg = matW_reg16x32.reg * sumtmp; } matdW_reg16x32.reg -= matW_reg16x32.reg; matdW_reg16x32.reg = matdW_reg16x32.reg * args->Pinv; if constexpr (Mkin_flag == true) { #pragma unroll for (int j = 0; j < 16; j++) { uint32_t mkdata_i = mkin_vec16[j]; xetla_mask_int<32> mkdata = xetla_mask_int_gen<32>(mkdata_i); matdW_reg16x32.reg.xetla_format<float>() .xetla_select<32, 1>(j * 32) .xetla_merge(0.0, matdW_reg16x32.reg.xetla_format<float>() .xetla_select<32, 1>(j * 32), mkdata); } } matdW_st.reg = xetla_cvt<dtype_sfx, float>(matdW_reg16x32.reg); subgroup::tile_store(matdW_st, matdW_st_payload); xetla_fence<memory_kind::untyped_global>(); } second_nbarr.arrive(); second_nbarr.wait(); { //dQ brgemm_arguments_128x64 brgemm_arg_128x64; matAcc_128x64_t matAcc_128x64; matC_128x64_t matC_128x64; matC_128x64_payload_t matC_128x64_payload; uint32_t width_a = tru_seqlen_ex; uint32_t height_a = (batchid * numhead + headid) * max_seqlen + tru_seqlen; uint32_t pitch_a = max_seqlen; int start_x_a = 0; int start_y_a = (batchid * numhead + headid) * max_seqlen + all_vert128_loop * 128; brgemm_arg_128x64.matA_base_desc.init({args->matdW_ptr}, {width_a, height_a, pitch_a}, {start_x_a, start_y_a}); uint32_t width_b = (headid + 1) * hdsz; uint32_t height_b = tru_seqlen + seqlen_entry; uint32_t pitch_b = hiddensize; int start_x_b = headid * hdsz; int start_y_b = seqlen_entry; brgemm_arg_128x64.matB_base_desc.init({args->matK_ptr}, {width_b, height_b, pitch_b}, {start_x_b, start_y_b}); brgemm_arg_128x64.inner_loop_count = (wg_tile_out_k + k_stride - 1) / k_stride; matAcc_128x64.init(0); brgemm_op_128x64_t brgemm_op_128x64; brgemm_op_128x64(g_thd32_tid, matAcc_128x64, brgemm_arg_128x64); int width_c = (headid + 1) * hdsz; int height_c = tru_seqlen + seqlen_entry; int pitch_c = hiddensize; int start_x_c = headid * hdsz + brgemm_op_128x64_t::get_matC_offset_x(g_thd32_tid); int start_y_c = all_vert128_loop * 128 + seqlen_entry + brgemm_op_128x64_t::get_matC_offset_y(g_thd32_tid); matC_128x64_payload.init(args->matdQ_ptr, width_c, height_c, pitch_c, start_x_c, start_y_c); subgroup::elemwise_cvt<matC_128x64_t, matAcc_128x64_t>( matC_128x64, matAcc_128x64); subgroup::tile_store(matC_128x64, matC_128x64_payload); } } //all_vert128_loop for (int transp256_loop = 0; transp256_loop < transp256_loop_num; transp256_loop++) { brgemm_arguments_256x64_trnp_a brgemm_arg_256x64; matAcc_256x64_trnp_a_t matAcc_256x64; matC_256x64_trnp_a_t matC_256x64; matC_256x64_trnp_a_payload_t matC_256x64_payload; uint32_t width_a = tru_seqlen_ex; uint32_t height_a = (batchid * numhead + headid) * max_seqlen + tru_seqlen; uint32_t pitch_a = max_seqlen; int start_x_a = transp256_loop * 256; int start_y_a = (batchid * numhead + headid) * max_seqlen; brgemm_arg_256x64.matA_base_desc.init({args->matdW_ptr}, {height_a, width_a, pitch_a}, {start_y_a, start_x_a}); uint32_t width_b = (headid + 1) * hdsz; uint32_t height_b = tru_seqlen + seqlen_entry; uint32_t pitch_b = hiddensize; int start_x_b = headid * hdsz; int start_y_b = seqlen_entry; brgemm_arg_256x64.matB_base_desc.init({args->matQ_ptr}, {width_b, height_b, pitch_b}, {start_x_b, start_y_b}); brgemm_arg_256x64.inner_loop_count = (wg_tile_out_k + k_stride - 1) / k_stride; matAcc_256x64.init(0); brgemm_op_256x64_trnp_a_t brgemm_op_256x64_trnp_a; brgemm_op_256x64_trnp_a( g_thd32_tid, matAcc_256x64, brgemm_arg_256x64); int width_c = (headid + 1) * hdsz; int height_c = tru_seqlen + seqlen_entry; int pitch_c = hiddensize; int start_x_c = headid * hdsz + brgemm_op_256x64_trnp_a_t::get_matC_offset_x(g_thd32_tid); int start_y_c = transp256_loop * 256 + seqlen_entry + brgemm_op_256x64_trnp_a_t::get_matC_offset_y(g_thd32_tid); matC_256x64_payload.init(args->matdK_ptr, width_c, height_c, pitch_c, start_x_c, start_y_c); subgroup::elemwise_cvt<matC_256x64_trnp_a_t, matAcc_256x64_trnp_a_t>(matC_256x64, matAcc_256x64); subgroup::tile_store(matC_256x64, matC_256x64_payload); all_nbarr.arrive(); all_nbarr.wait(); } for (int transp128_loop = 0; transp128_loop < transp128_loop_num; transp128_loop++) { brgemm_arguments_128x64_trnp_a brgemm_arg_128x64; matAcc_128x64_trnp_a_t matAcc_128x64; matC_128x64_trnp_a_t matC_128x64; matC_128x64_trnp_a_payload_t matC_128x64_payload; uint32_t width_a = tru_seqlen_ex; uint32_t height_a = (batchid * numhead + headid) * max_seqlen + tru_seqlen; uint32_t pitch_a = max_seqlen; int start_x_a = transp128_loop * 128 + offset_blk_128x128; int start_y_a = (batchid * numhead + headid) * max_seqlen; brgemm_arg_128x64.matA_base_desc.init({args->matdW_ptr}, {height_a, width_a, pitch_a}, {start_y_a, start_x_a}); uint32_t width_b = (headid + 1) * hdsz; uint32_t height_b = tru_seqlen + seqlen_entry; uint32_t pitch_b = hiddensize; int start_x_b = headid * hdsz; int start_y_b = seqlen_entry; brgemm_arg_128x64.matB_base_desc.init({args->matQ_ptr}, {width_b, height_b, pitch_b}, {start_x_b, start_y_b}); brgemm_arg_128x64.inner_loop_count = (wg_tile_out_k + k_stride - 1) / k_stride; matAcc_128x64.init(0); brgemm_op_128x64_trnp_a_t brgemm_op_128x64_trnp_a; brgemm_op_128x64_trnp_a( g_thd32_tid, matAcc_128x64, brgemm_arg_128x64); int width_c = (headid + 1) * hdsz; int height_c = tru_seqlen + seqlen_entry; int pitch_c = hiddensize; int start_x_c = headid * hdsz + brgemm_op_128x64_trnp_a_t::get_matC_offset_x(g_thd32_tid); int start_y_c = transp128_loop * 128 + seqlen_entry + offset_blk_128x128 + brgemm_op_128x64_trnp_a_t::get_matC_offset_y(g_thd32_tid); matC_128x64_payload.init(args->matdK_ptr, width_c, height_c, pitch_c, start_x_c, start_y_c); subgroup::elemwise_cvt<matC_128x64_trnp_a_t, matAcc_128x64_trnp_a_t>(matC_128x64, matAcc_128x64); subgroup::tile_store(matC_128x64, matC_128x64_payload); all_nbarr.arrive(); all_nbarr.wait(); } //transp128_loop } //xetla_softmax_bwd_t::call }; //struct xetla_softmax_bwd_t } // namespace gpu::xetla::kernel
be7eecd0c1a853f9f68cafd318b50e93d063f2cc
0306b7dcdfb1c9b7f7f620425771957b68cd76fc
/syscall/write_syscall.cpp
86f50acf98f746665a772dadd2948c66364160c8
[]
no_license
golsana7/test-for-skua
3db6893312b924360f07ed10f272738c4232b92a
23587fbbed3436afb95c7cc767423e1522b4c0af
refs/heads/master
2020-06-04T15:47:11.916832
2019-07-08T16:14:42
2019-07-08T16:14:42
192,089,172
0
0
null
null
null
null
UTF-8
C++
false
false
2,036
cpp
write_syscall.cpp
// C program to illustrate // write system Call #include <fcntl.h> #include <iostream> #include <unistd.h> #include <time.h> //asm volatile #include <stdio.h> #include <inttypes.h> #include <stdlib.h> //gettimeofday #include <bits/stdc++.h> #include <sys/time.h> using namespace std; main() { int sz; unsigned cycles_low, cycles_high, cycles_low1, cycles_high1; uint64_t start,end; uint64_t diff=0; uint64_t total_diff=0; int N = 1000; double time_taken; struct timeval start1, end1; uint64_t buf = 17266355879; // buf[0] = 17266355879; // buf[1] = 673886778992; int fd = open("foo.txt", O_WRONLY | O_CREAT | O_TRUNC, 0644); if (fd < 0) { perror("r1"); exit(1); } //measuring write() syscall time and clock // start timer. gettimeofday(&start1, NULL); // unsync the I/O of C and C++. ios_base::sync_with_stdio(false); //start counter asm volatile ( "RDTSC\n\t" "mov %%edx, %0\n\t" "mov %%eax, %1\n\t": "=r" (cycles_high), "=r" (cycles_low)); while (N) { sz = write(fd, &buf, sizeof(uint64_t)); N=N-1; } //end of clock counter asm volatile ( "RDTSC\n\t" "mov %%edx, %0\n\t" "mov %%eax, %1\n\t": "=r" (cycles_high1), "=r" (cycles_low1)); // stop timer. gettimeofday(&end1, NULL); //for clock counter start = ( ((uint64_t)cycles_high << 32) | cycles_low ); end = ( ((uint64_t)cycles_high1 << 32) | cycles_low1 ); diff = end-start; //calculating total time taken by write syscall for 1000 times time_taken = ((end1.tv_sec * 1000000 + end1.tv_usec) - (start1.tv_sec * 1000000 + start1.tv_usec)); //for checking that start time is smaller than end time cout<<"start time "<<(start1.tv_sec * 1000000 + start1.tv_usec)<<" end time "<<(end1.tv_sec * 1000000 + end1.tv_usec) <<endl; //printing final result cout<<"clock: "<<diff<<" clokcs " <<" time: "<<time_taken<< " micro sec "<<endl; close(fd); }
664c046511f38b17f86695508978982526a48059
d13087f57817c024176920f3513188a16d5214cc
/src/plane_detection.cpp
281691ae938a121262a0715d16e4b5614c81f09d
[]
no_license
RhysMcK/Beam-Detector
b99e4c6748f0f49879ff7dc974088f4f6921fed0
3db8ed4d81c58ad28c7791b00fa355fb76cf2b89
refs/heads/master
2020-04-04T21:31:03.681504
2018-11-12T07:33:26
2018-11-12T07:33:26
156,289,061
0
0
null
null
null
null
UTF-8
C++
false
false
3,706
cpp
plane_detection.cpp
#include <cstdlib> #include <ctime> #include <string> #include <iostream> #include <pcl/console/parse.h> #include <pcl/filters/extract_indices.h> #include <pcl/io/pcd_io.h> #include <pcl/point_types.h> #include <pcl/sample_consensus/ransac.h> #include <pcl/sample_consensus/sac_model_plane.h> #include <pcl/sample_consensus/sac_model_sphere.h> #include <pcl/sample_consensus/sac_model_parallel_plane.h> #include <pcl/visualization/pcl_visualizer.h> #include <boost/thread/thread.hpp> boost::shared_ptr<pcl::visualization::PCLVisualizer> simpleVis (pcl::PointCloud<pcl::PointXYZ>::ConstPtr cloud) { // -------------------------------------------- // -----Open 3D viewer and add point cloud----- // -------------------------------------------- boost::shared_ptr<pcl::visualization::PCLVisualizer> viewer (new pcl::visualization::PCLVisualizer ("3D Viewer")); viewer->setBackgroundColor (0, 0, 0); viewer->addPointCloud<pcl::PointXYZ> (cloud, "sample cloud"); viewer->setPointCloudRenderingProperties (pcl::visualization::PCL_VISUALIZER_POINT_SIZE, 3, "sample cloud"); //viewer->addCoordinateSystem (1.0, "global"); viewer->initCameraParameters (); return (viewer); } int main(int argc, char** argv) { std::string user_name(std::getenv("USER")); //get computer user name for file path below // initialize PointClouds pcl::PointCloud<pcl::PointXYZ>::Ptr cloud_in(new pcl::PointCloud<pcl::PointXYZ>); pcl::PointCloud<pcl::PointXYZ>::Ptr cloud (new pcl::PointCloud<pcl::PointXYZ>); pcl::PointCloud<pcl::PointXYZ>::Ptr final (new pcl::PointCloud<pcl::PointXYZ>); //load point cloud if (pcl::io::loadPCDFile<pcl::PointXYZ> ("/home/"+user_name+"/Beam-Detector/src/PCD/beam_2.pcd", *cloud_in) == -1) //* load the file { PCL_ERROR ("Couldn't read file beam_1.pcd \n"); return (-1); } //make copy of cloud to manipulate pcl::copyPointCloud(*cloud_in, *cloud); pcl::ModelCoefficients::Ptr coefficients (new pcl::ModelCoefficients); pcl::PointIndices::Ptr inliers (new pcl::PointIndices); // Create the segmentation object pcl::SACSegmentation<pcl::PointXYZ> seg; // Optional seg.setOptimizeCoefficients (true); // Mandatory seg.setModelType (pcl::SACMODEL_NORMAL_PLANE); seg.setMethodType (pcl::SAC_RANSAC); seg.setDistanceThreshold (0.01); seg.setInputCloud (cloud); seg.segment (*inliers, *coefficients); if (inliers->indices.size () == 0) { PCL_ERROR ("Could not estimate a planar model for the given dataset."); return (-1); } std::vector<int> inliers; // created RandomSampleConsensus object and compute the appropriated model pcl::SampleConsensusModelParallelPlane<pcl::PointXYZ>::Ptr model_p (new pcl::SampleConsensusModelParallelPlane<pcl::PointXYZ> (cloud)); pcl::RandomSampleConsensus<pcl::PointXYZ> ransac (model_p); ransac.setDistanceThreshold (.01); ransac.computeModel(); ransac.getInliers(inliers); // copies all inliers of the model computed to another PointCloud pcl::copyPointCloud<pcl::PointXYZ>(*cloud, inliers, *final); //View pointcloud boost::shared_ptr<pcl::visualization::PCLVisualizer> viewer (new pcl::visualization::PCLVisualizer ("3D Viewer")); viewer->setBackgroundColor (0, 0, 0); viewer->addPointCloud<pcl::PointXYZ> (cloud_in, "Cloud_in"); pcl::visualization::PointCloudColorHandlerCustom<pcl::PointXYZ> colour_rgb (final, 0, 0, 255); viewer->addPointCloud<pcl::PointXYZ> (final, colour_rgb, "plane"); viewer->addCoordinateSystem (0.5); viewer->initCameraParameters (); //display while (!viewer->wasStopped ()) { viewer->spinOnce (100); boost::this_thread::sleep (boost::posix_time::microseconds (100000)); } return (0); }