blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
3
264
content_id
stringlengths
40
40
detected_licenses
sequencelengths
0
85
license_type
stringclasses
2 values
repo_name
stringlengths
5
140
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
905 values
visit_date
timestamp[us]date
2015-08-09 11:21:18
2023-09-06 10:45:07
revision_date
timestamp[us]date
1997-09-14 05:04:47
2023-09-17 19:19:19
committer_date
timestamp[us]date
1997-09-14 05:04:47
2023-09-06 06:22:19
github_id
int64
3.89k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
22 values
gha_event_created_at
timestamp[us]date
2012-06-07 00:51:45
2023-09-14 21:58:39
gha_created_at
timestamp[us]date
2008-03-27 23:40:48
2023-08-21 23:17:38
gha_language
stringclasses
141 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
3
10.4M
extension
stringclasses
115 values
content
stringlengths
3
10.4M
authors
sequencelengths
1
1
author_id
stringlengths
0
158
d2720bc1c6a542f36de4a9440acc1a5d519c81be
24d75ffa3af1b85325b39dc909343a8d945e9171
/SceniX/inc/nvsg/nvmath/Matnnt.h
215058459753de93edb8edfa3585f8ae79133983
[]
no_license
assafyariv/PSG
0c2bf874166c7a7df18e8537ae5841bf8805f166
ce932ca9a72a5553f8d1826f3058e186619a4ec8
refs/heads/master
2016-08-12T02:57:17.021428
2015-09-24T17:14:51
2015-09-24T17:14:51
43,080,715
0
0
null
null
null
null
UTF-8
C++
false
false
61,364
h
// Copyright NVIDIA Corporation 2002-2006 // TO THE MAXIMUM EXTENT PERMITTED BY APPLICABLE LAW, THIS SOFTWARE IS PROVIDED // *AS IS* AND NVIDIA AND ITS SUPPLIERS DISCLAIM ALL WARRANTIES, EITHER EXPRESS // OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, IMPLIED WARRANTIES OF MERCHANTABILITY // AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL NVIDIA OR ITS SUPPLIERS // BE LIABLE FOR ANY SPECIAL, INCIDENTAL, INDIRECT, OR CONSEQUENTIAL DAMAGES // WHATSOEVER (INCLUDING, WITHOUT LIMITATION, DAMAGES FOR LOSS OF BUSINESS PROFITS, // BUSINESS INTERRUPTION, LOSS OF BUSINESS INFORMATION, OR ANY OTHER PECUNIARY LOSS) // ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE, EVEN IF NVIDIA HAS // BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES #pragma once /** @file */ #include "nvsgcommon.h" #include "nvmath/Quatt.h" #include "nvmath/Vecnt.h" namespace nvmath { template<typename T> class Quatt; /*! \brief Matrix class of fixed size and type. * \remarks This class is templated by size and type. It holds \a n times \a n values of type \a * T. There are typedefs for the most common usage with 3 and 4 values of type \c float and \c * double: Mat33f, Mat33d, Mat44f, Mat44d. */ template<unsigned int n, typename T> class Matnnt { public: /*! \brief Default constructor. * \remarks For performance reasons, no initialization is performed. */ Matnnt(bool idmat = false); /*! \brief Copy constructor from a matrix of possibly different size and type. * \param rhs A matrix with \a m times \a m values of type \a S. * \remarks The minimum \a k of \a n and \a m is determined. The first \a k values of type \a * S in the first \a k rows from \a rhs are converted to type \a T and assigned as the first * \a k values in the first \a k rows of \c this. If \a k is less than \a n, the \a n - \a k * last values of the \a n - \a k last rows of \c this are not initialized. */ template<unsigned int m, typename S> explicit Matnnt( const Matnnt<m,S> & rhs ); /*! \brief Constructor for a 3 by 3 matrix out of 9 scalar values. * \param m00 First element of the first row of the matrix. * \param m01 Second element of the first row of the matrix. * \param m02 Third element of the first row of the matrix. * \param m10 First element of the second row of the matrix. * \param m11 Second element of the second row of the matrix. * \param m12 Third element of the second row of the matrix. * \param m20 First element of the third row of the matrix. * \param m21 Second element of the third row of the matrix. * \param m22 Third element of the third row of the matrix. * \remarks This constructor can only be used with 3 by 3 matrices, like Mat33f. * \par Example: * \code * Mat33f m33f( 1.0f, 2.0f, 3.0f, 4.0f, 5.0f, 6.0f, 7.0f, 8.0f, 9.0f ); * \endcode */ Matnnt( T m00, T m01, T m02 , T m10, T m11, T m12 , T m20, T m21, T m22 ); /*! \brief Constructor for a 3 by 3 matrix out of three vectors of three values each. * \param v0 First row of the matrix. * \param v1 Second row of the matrix. * \param v2 Third row of the matrix. * \remarks This constructor can only be used with 3 by 3 matrices, like Mat33f. * \par Example: * \code * Mat33f m33f( xAxis, yAxis, zAxis ); * \endcode */ Matnnt( const Vecnt<n,T> & v0, const Vecnt<n,T> & v1, const Vecnt<n,T> & v2 ); /*! \brief Constructor for a 4 by 4 matrix out of 16 scalar values. * \param m00 First element of the first row of the matrix. * \param m01 Second element of the first row of the matrix. * \param m02 Third element of the first row of the matrix. * \param m03 Fourth element of the first row of the matrix. * \param m10 First element of the second row of the matrix. * \param m11 Second element of the second row of the matrix. * \param m12 Third element of the second row of the matrix. * \param m13 Fourth element of the second row of the matrix. * \param m20 First element of the third row of the matrix. * \param m21 Second element of the third row of the matrix. * \param m22 Third element of the third row of the matrix. * \param m23 Fourth element of the third row of the matrix. * \param m30 First element of the fourth row of the matrix. * \param m31 Second element of the fourth row of the matrix. * \param m32 Third element of the fourth row of the matrix. * \param m33 Fourth element of the fourth row of the matrix. * \remarks This constructor can only be used with 4 by 4 matrices, like Mat44f. * \par Example: * \code * Mat44f m44f( 1.0f, 2.0f, 3.0f, 4.0f * , 5.0f, 6.0f, 7.0f, 8.0f * , 9.0f, 10.0f, 11.0f, 12.0f * , 13.0f, 14.0f, 15.0f, 16.0f ); * \endcode */ Matnnt( T m00, T m01, T m02, T m03 , T m10, T m11, T m12, T m13 , T m20, T m21, T m22, T m23 , T m30, T m31, T m32, T m33 ); /*! \brief Constructor for a 4 by 4 matrix out of four vectors of four values each. * \param v0 First row of the matrix. * \param v1 Second row of the matrix. * \param v2 Third row of the matrix. * \param v3 Fourth row of the matrix. * \remarks This constructor can only be used with 4 by 4 matrices, like Mat44f. * \par Example: * \code * Mat44f m44f( Vec3f( xAxis, 0.0f ) * , Vec4f( yAxis, 0.0f ) * , Vec4f( zAxis, 0.0f ) * , Vec4f( trans, 1.0f ) ); * \endcode */ Matnnt( const Vecnt<n,T> & v0, const Vecnt<n,T> & v1, const Vecnt<n,T> & v2, const Vecnt<n,T> & v3 ); /*! \brief Constructor for a 3 by 3 rotation matrix out of an axis and an angle. * \param axis A reference to the constant axis to rotate about. * \param angle The angle, in radians, to rotate. * \remarks The resulting 3 by 3 matrix is a pure rotation. * \note The behavior is undefined, if \a axis is not normalized. * \par Example: * \code * Mat33f rotZAxisBy45Degrees( Vec3f( 0.0f, 0.0f, 1.0f ), PI/4 ); * \endcode */ Matnnt( const Vecnt<n,T> & axis, T angle ); /*! \brief Constructor for a 3 by 3 rotation matrix out of a normalized quaternion. * \param ori A reference to the normalized quaternion representing the rotation. * \remarks The resulting 3 by 3 matrix is a pure rotation. * \note The behavior is undefined, if \a ori is not normalized. */ explicit Matnnt( const Quatt<T> & ori ); /*! \brief Constructor for a 4 by 4 transformation matrix out of a quaternion and a translation. * \param ori A reference to the normalized quaternion representing the rotational part. * \param trans A reference to the vector representing the translational part. * \note The behavior is undefined, if \ ori is not normalized. */ Matnnt( const Quatt<T> & ori, const Vecnt<n-1,T> & trans ); /*! \brief Constructor for a 4 by 4 transformation matrix out of a quaternion, a translation, * and a scaling. * \param ori A reference to the normalized quaternion representing the rotational part. * \param trans A reference to the vector representing the translational part. * \param scale A reference to the vector representing the scaling along the three axis directions. * \note The behavior is undefined, if \ ori is not normalized. */ Matnnt( const Quatt<T> & ori, const Vecnt<n-1,T> & trans, const Vecnt<n-1,T> & scale ); public: /*! \brief Get a constant pointer to the n times n values of the matrix. * \return A constant pointer to the matrix elements. * \remarks The matrix elements are stored in row-major order. This function returns the * address of the first element of the first row. It is assured, that the other elements of * the matrix follow linearly. * \par Example: * If \c m is a 3 by 3 matrix, m.getPtr() gives a pointer to the 9 elements m00, m01, m02, m10, * m11, m12, m20, m21, m22, in that order. */ const T * getPtr() const; /*! \brief Invert the matrix. * \return \c true, if the matrix was successfully inverted, otherwise \c false. */ bool invert(); /*! \brief Non-constant subscript operator. * \param i Index of the row to address. * \return A reference to the \a i th row of the matrix. */ template<typename S> Vecnt<n,T> & operator[]( S i ); /*! \brief Constant subscript operator. * \param i Index of the row to address. * \return A constant reference to the \a i th row of the matrix. */ template<typename S> const Vecnt<n,T> & operator[]( S i ) const; /*! \brief Matrix addition and assignment operator. * \param m A constant reference to the matrix to add. * \return A reference to \c this. * \remarks The matrix \a m has to be of the same size as \c this, but may hold values of a * different type. The matrix elements of type \a S of \a m are converted to type \a T and * added to the corresponding matrix elements of \c this. */ template<typename S> Matnnt<n,T> & operator+=( const Matnnt<n,S> & m ); /*! \brief Matrix subtraction and assignment operator. * \param m A constant reference to the matrix to subtract. * \return A reference to \c this. * \remarks The matrix \a m has to be of the same size as \c this, but may hold values of a * different type. The matrix elements of type \a S of \a m are converted to type \a T and * subtracted from the corresponding matrix elements of \c this. */ template<typename S> Matnnt<n,T> & operator-=( const Matnnt<n,S> & m ); /*! \brief Scalar multiplication and assignment operator. * \param s A scalar value to multiply with. * \return A reference to \c this. * \remarks The type of \a s may be of different type as the elements of the \c this. \a s is * converted to type \a T and each element of \c this is multiplied with it. */ template<typename S> Matnnt<n,T> & operator*=( S s ); /*! \brief Matrix multiplication and assignment operator. * \param m A constant reference to the matrix to multiply with. * \return A reference to \c this. * \remarks The matrix multiplication \code *this * m \endcode is calculated and assigned to * \c this. */ Matnnt<n,T> & operator*=( const Matnnt<n,T> & m ); /*! \brief Scalar division and assignment operator. * \param s A scalar value to divide by. * \return A reference to \c this. * \remarks The type of \a s may be of different type as the elements of the \c this. \a s is * converted to type \a T and each element of \c this is divided by it. * \note The behavior is undefined if \a s is very close to zero. */ template<typename S> Matnnt<n,T> & operator/=( S s ); private: Vecnt<n,T> m_mat[n]; }; // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // non-member functions // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - /*! \brief Determine the determinant of a matrix. * \param m A constant reference to the matrix to determine the determinant from. * \return The determinant of \a m. */ template<unsigned int n, typename T> T determinant( const Matnnt<n,T> & m ); /*! \brief Invert a matrix. * \param mIn A constant reference to the matrix to invert. * \param mOut A reference to the matrix to hold the inverse. * \return \c true, if the matrix \a m was successfully inverted, otherwise \c false. * \note If the mIn was not successfully inverted, the values in mOut are undefined. */ template<unsigned int n, typename T> bool invert( const Matnnt<n,T> & mIn, Matnnt<n,T> & mOut ); /*! \brief Test if a matrix is the identity. * \param m A constant reference to the matrix to test for identity. * \param eps An optional value giving the allowed epsilon. The default is a type dependent value. * \return \c true, if the matrix is the identity, otherwise \c false. * \remarks A matrix is considered to be the identity, if each of the diagonal elements differ * less than \a eps from one, and each of the other matrix elements differ less than \a eps from * zero. * \sa isNormalized, isNull, isOrthogonal, isSingular */ template<unsigned int n, typename T> bool isIdentity( const Matnnt<n,T> & m, T eps = std::numeric_limits<T>::epsilon() ) { bool identity = true; for ( unsigned int i=0 ; identity && i<n ; ++i ) { for ( unsigned int j=0 ; identity && j<i ; ++j ) { identity = ( abs( m[i][j] ) <= eps ); } if ( identity ) { identity = ( abs( m[i][i] - 1 ) <= eps ); } for ( unsigned int j=i+1 ; identity && j<n ; ++j ) { identity = ( abs( m[i][j] ) <= eps ); } } return( identity ); } /*! \brief Test if a matrix is normalized. * \param m A constant reference to the matrix to test. * \param eps An optional value giving the allowed epsilon. The default is a type dependent value. * \return \c true if the matrix is normalized, otherwise \c false. * \remarks A matrix is considered to be normalized, if each row and each column is normalized. * \sa isIdentity, isNull, isOrthogonal, isSingular */ template<unsigned int n, typename T> bool isNormalized( const Matnnt<n,T> & m, T eps = std::numeric_limits<T>::epsilon() ) { bool normalized = true; for ( unsigned int i=0 ; normalized && i<n ; ++i ) { normalized = isNormalized( m[i], eps ); } for ( unsigned int i=0 ; normalized && i<n ; ++i ) { Vecnt<n,T> v; for ( unsigned int j=0 ; j<n ; j++ ) { v[j] = m[j][i]; } normalized = isNormalized( v, eps ); } return( normalized ); } /*! \brief Test if a matrix is null. * \param m A constant reference to the matrix to test. * \param eps An optional value giving the allowed epsilon. The default is a type dependent value. * \return \c true if the matrix is null, otherwise \c false. * \remarks A matrix is considered to be null, if each row is null. * \sa isIdentity, isNormalized, isOrthogonal, isSingular */ template<unsigned int n, typename T> bool isNull( const Matnnt<n,T> & m, T eps = std::numeric_limits<T>::epsilon() ) { bool null = true; for ( unsigned int i=0 ; null && i<n ; ++i ) { null = isNull( m[i], eps ); } return( null ); } /*! \brief Test if a matrix is orthogonal. * \param m A constant reference to the matrix to test. * \param eps An optional value giving the allowed epsilon. The default is a type dependent value. * \return \c true, if the matrix is orthogonal, otherwise \c false. * \remarks A matrix is considered to be orthogonal, if each pair of rows and each pair of * columns are orthogonal to each other. * \sa isIdentity, isNormalized, isNull, isSingular */ template<unsigned int n, typename T> bool isOrthogonal( const Matnnt<n,T> & m, T eps = std::numeric_limits<T>::epsilon() ) { bool orthogonal = true; for ( unsigned int i=0 ; orthogonal && i+1<n ; ++i ) { for ( unsigned int j=i+1 ; orthogonal && j<n ; ++j ) { orthogonal = areOrthogonal( m[i], m[j], eps ); } } if ( orthogonal ) { Matnnt<n,T> tm = ~m; for ( unsigned int i=0 ; orthogonal && i+1<n ; ++i ) { for ( unsigned int j=i+1 ; orthogonal && j<n ; ++j ) { orthogonal = areOrthogonal( tm[i], tm[j], eps ); } } } return( orthogonal ); } /*! \brief Test if a matrix is singular. * \param m A constant reference to the matrix to test. * \param eps An optional value giving the allowed epsilon. The default is a type dependent value. * \return \c true, if the matrix is singular, otherwise \c false. * \remarks A matrix is considered to be singular, if its determinant is zero. * \sa isIdentity, isNormalized, isNull, isOrthogonal */ template<unsigned int n, typename T> bool isSingular( const Matnnt<n,T> & m, T eps = std::numeric_limits<T>::epsilon() ) { return( abs( determinant( m ) ) <= eps ); } /*! \brief Get the value of the maximal absolute element of a matrix. * \param m A constant reference to a matrix to get the maximal element from. * \return The value of the maximal absolute element of \a m. * \sa minElement */ template<unsigned int n, typename T> T maxElement( const Matnnt<n,T> & m ); /*! \brief Get the value of the minimal absolute element of a matrix. * \param m A constant reference to a matrix to get the minimal element from. * \return The value of the minimal absolute element of \a m. * \sa maxElement */ template<unsigned int n, typename T> T minElement( const Matnnt<n,T> & m ); /*! \brief Matrix equality operator. * \param m0 A constant reference to the first matrix to compare. * \param m1 A constant reference to the second matrix to compare. * \return \c true, if \a m0 and \a m1 are equal, otherwise \c false. * \remarks Two matrices are considered to be equal, if each element of \a m0 differs less than * the type dependent epsilon from the the corresponding element of \a m1. */ template<unsigned int n, typename T> bool operator==( const Matnnt<n,T> & m0, const Matnnt<n,T> & m1 ); /*! \brief Matrix inequality operator. * \param m0 A constant reference to the first matrix to compare. * \param m1 A constant reference to the second matrix to compare. * \return \c true, if \a m0 and \a m1 are not equal, otherwise \c false. * \remarks Two matrices are considered to be not equal, if at least one element of \a m0 differs * more than the type dependent epsilon from the the corresponding element of \a m1. */ template<unsigned int n, typename T> bool operator!=( const Matnnt<n,T> & m0, const Matnnt<n,T> & m1 ); /*! \brief Matrix transpose operator. * \param m A constant reference to the matrix to transpose. * \return The transposed version of \a m. */ template<unsigned int n, typename T> Matnnt<n,T> operator~( const Matnnt<n,T> & m ); /*! \brief Matrix addition operator. * \param m0 A constant reference to the first matrix to add. * \param m1 A constant reference to the second matrix to add. * \return A matrix representing the sum of \code m0 + m1 \endcode */ template<unsigned int n, typename T> Matnnt<n,T> operator+( const Matnnt<n,T> & m0, const Matnnt<n,T> & m1 ); /*! \brief Matrix negation operator. * \param m A constant reference to the matrix to negate. * \return A matrix representing the negation of \a m. */ template<unsigned int n, typename T> Matnnt<n,T> operator-( const Matnnt<n,T> & m ); /*! \brief Matrix subtraction operator. * \param m0 A constant reference to the first argument of the subtraction. * \param m1 A constant reference to the second argument of the subtraction. * \return A matrix representing the difference \code m0 - m1 \endcode */ template<unsigned int n, typename T> Matnnt<n,T> operator-( const Matnnt<n,T> & m0, const Matnnt<n,T> & m1 ); /*! \brief Scalar multiplication operator. * \param m A constant reference to the matrix to multiply. * \param s The scalar value to multiply with. * \return A matrix representing the product \code m * s \endcode */ template<unsigned int n, typename T> Matnnt<n,T> operator*( const Matnnt<n,T> & m, T s ); /*! \brief Scalar multiplication operator. * \param s The scalar value to multiply with. * \param m A constant reference to the matrix to multiply. * \return A matrix representing the product \code s * m \endcode */ template<unsigned int n, typename T> Matnnt<n,T> operator*( T s, const Matnnt<n,T> & m ); /*! \brief Vector multiplication operator. * \param m A constant reference to the matrix to multiply. * \param v A constant reference to the vector to multiply with. * \return A vector representing the product \code m * v \endcode */ template<unsigned int n, typename T> Vecnt<n,T> operator*( const Matnnt<n,T> & m, const Vecnt<n,T> & v ); /*! \brief Vector multiplication operator. * \param v A constant reference to the vector to multiply with. * \param m A constant reference to the matrix to multiply. * \return A vector representing the product \code v * m \endcode */ template<unsigned int n, typename T> Vecnt<n,T> operator*( const Vecnt<n,T> & v, const Matnnt<n,T> & m ); /*! \brief Matrix multiplication operator. * \param m0 A constant reference to the first operand of the multiplication. * \param m1 A constant reference to the second operand of the multiplication. * \return A matrix representing the product \code m0 * m1 \endcode */ template<unsigned int n, typename T> Matnnt<n,T> operator*( const Matnnt<n,T> & m0, const Matnnt<n,T> & m1 ); /*! \brief Scalar division operator. * \param m A constant reference to the matrix to divide. * \param s The scalar value to divide by. * \return A matrix representing the matrix \a m divided by \a s. */ template<unsigned int n, typename T> Matnnt<n,T> operator/( const Matnnt<n,T> & m, T s ); /*! \brief Set a matrix to be the identity. * \param m The matrix to set to identity. * \remarks Each diagonal element of \a m is set to one, each other element is set to zero. */ template<unsigned int n, typename T> void setIdentity( Matnnt<n,T> & m ); // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // non-member functions, specialized for n == 3 // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - /*! \brief Test if a 3 by 3 matrix represents a rotation. * \param m A constant reference to the matrix to test. * \param eps An optional value giving the allowed epsilon. The default is a type dependent value. * \return \c true, if the matrix represents a rotation, otherwise \c false. * \remarks A 3 by 3 matrix is considered to be a rotation, if it is normalized, orthogonal, and its * determinant is one. * \sa isIdentity, isNull, isNormalized, isOrthogonal */ template<typename T> bool isRotation( const Matnnt<3,T> & m, T eps = 9 * std::numeric_limits<T>::epsilon() ) { return( isNormalized( m, eps ) && isOrthogonal( m, eps ) && ( abs( determinant( m ) - 1 ) <= eps ) ); } /*! \brief Set the values of a 3 by 3 matrix by nine scalars * \param m A reference to the matrix to set with the nine values. * \param m00 The scalar for the first value in the first row. * \param m01 The scalar for the second value in the first row. * \param m02 The scalar for the third value in the first row. * \param m10 The scalar for the first value in the second row. * \param m11 The scalar for the second value in the second row. * \param m12 The scalar for the third value in the second row. * \param m20 The scalar for the first value in the third row. * \param m21 The scalar for the second value in the third row. * \param m22 The scalar for the third value in the third row. * \return A reference to \a m. */ template<typename T> Matnnt<3,T> & setMat( Matnnt<3,T> & m, T m00, T m01, T m02 , T m10, T m11, T m12 , T m20, T m21, T m22 ); /*! \brief Set the values of a 3 by 3 matrix by three vectors. * \param m A reference to the matrix to set with the three vectors. * \param v0 A constant reference to the vector to set as the first row of \a m. * \param v1 A constant reference to the vector to set as the second row of \a m. * \param v2 A constant reference to the vector to set as the third row of \a m. * \return A reference to \a m. */ template<typename T> Matnnt<3,T> & setMat( Matnnt<3,T> & m, const Vecnt<3,T> & v0 , const Vecnt<3,T> & v1 , const Vecnt<3,T> & v2 ); /*! \brief Set the values of a 3 by 3 matrix using a normalized quaternion. * \param m A reference to the matrix to set. * \param q A constant reference to the normalized quaternion to use. * \return A reference to \a m. * \remarks The matrix is set to represent the same rotation as the normalized quaternion \a q. * \note The behavior is undefined if \a q is not normalized. */ template<typename T> Matnnt<3,T> & setMat( Matnnt<3,T> & m, const Quatt<T> & q ); /*! \brief Set the values of a 3 by 3 matrix using a normalized rotation axis and an angle. * \param m A reference to the matrix to set. * \param axis A constant reference to the normalized rotation axis. * \param angle The angle in radians to rotate around \a axis. * \return A reference to \a m. * \remarks The matrix is set to represent the rotation by \a angle around \a axis. * \note The behavior is undefined if \a axis is not normalized. */ template<typename T> Matnnt<3,T> & setMat( Matnnt<3,T> & m, const Vecnt<3,T> & axis, T angle ); // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // non-member functions, specialized for n == 3, T == float // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - /*! \brief Decompose a 3 by 3 matrix. * \param m A constant reference to the matrix to decompose. * \param orientation A reference to the quaternion getting the rotational part of the matrix. * \param scaling A reference to the vector getting the scaling part of the matrix. * \param scaleOrientation A reference to the quaternion getting the orientation of the scaling. * \note The behavior is undefined, if the determinant of \a m is too small, or the rank of \a m * is less than three. */ NVSG_API void decompose( const Matnnt<3,float> &m, Quatt<float> &orientation , Vecnt<3,float> &scaling, Quatt<float> &scaleOrientation ); // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // non-member functions, specialized for n == 4 // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - /*! \brief Set the values of a 4 by 4 matrix by sixteen scalars * \param m A reference to the matrix to set with the sixteen values. * \param m00 The scalar for the first value in the first row. * \param m01 The scalar for the second value in the first row. * \param m02 The scalar for the third value in the first row. * \param m03 The scalar for the fourth value in the first row. * \param m10 The scalar for the first value in the second row. * \param m11 The scalar for the second value in the second row. * \param m12 The scalar for the third value in the second row. * \param m13 The scalar for the fourth value in the second row. * \param m20 The scalar for the first value in the third row. * \param m21 The scalar for the second value in the third row. * \param m22 The scalar for the third value in the third row. * \param m23 The scalar for the fourth value in the third row. * \param m30 The scalar for the first value in the fourth row. * \param m31 The scalar for the second value in the fourth row. * \param m32 The scalar for the third value in the fourth row. * \param m33 The scalar for the fourth value in the fourth row. * \return A reference to \a m. */ template<typename T> Matnnt<4,T> & setMat( Matnnt<4,T> & m, T m00, T m01, T m02, T m03 , T m10, T m11, T m12, T m13 , T m20, T m21, T m22, T m23 , T m30, T m31, T m32, T m33 ); /*! \brief Set the values of a 4 by 4 matrix by four vectors. * \param m A reference to the matrix to set with the four vectors. * \param v0 A constant reference to the vector to set as the first row of \a m. * \param v1 A constant reference to the vector to set as the second row of \a m. * \param v2 A constant reference to the vector to set as the third row of \a m. * \param v3 A constant reference to the vector to set as the fourth row of \a m. * \return A reference to \a m. */ template<typename T> Matnnt<4,T> & setMat( Matnnt<4,T> & m, const Vecnt<4,T> & v0 , const Vecnt<4,T> & v1 , const Vecnt<4,T> & v2 , const Vecnt<4,T> & v3 ); /*! \brief Set the values of a 4 by 4 matrix by the constituents of a transformation. * \param m A reference to the matrix to set. * \param ori A constant reference of the rotation part of the transformation. * \param trans An optional constant reference to the translational part of the transformation. The * default is a null vector. * \param scale An optional constant reference to the scaling part of the transformation. The default * is the identity scaling. * \return A reference to \a m. */ template<typename T> Matnnt<4,T> & setMat( Matnnt<4,T> & m, const Quatt<T> & ori , const Vecnt<3,T> & trans = Vecnt<3,T>(0,0,0) , const Vecnt<3,T> & scale = Vecnt<3,T>(1,1,1) ) { Matnnt<3,T> m3( ori ); m[0] = Vecnt<4,T>( scale[0] * m3[0], 0 ); m[1] = Vecnt<4,T>( scale[1] * m3[1], 0 ); m[2] = Vecnt<4,T>( scale[2] * m3[2], 0 ); m[3] = Vecnt<4,T>( trans, 1 ); return( m ); } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // non-member functions, specialized for n == 4, T == float // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - /*! \brief Decompose a 4 by 4 matrix of floats. * \param m A constant reference to the matrix to decompose. * \param translation A reference to the vector getting the translational part of the matrix. * \param orientation A reference to the quaternion getting the rotational part of the matrix. * \param scaling A reference to the vector getting the scaling part of the matrix. * \param scaleOrientation A reference to the quaternion getting the orientation of the scaling. * \note The behavior is undefined, if the determinant of \a m is too small. * \note Currently, the behavior is undefined, if the rank of \a m is less than three. */ NVSG_API void decompose( const Matnnt<4,float> &m, Vecnt<3,float> &translation , Quatt<float> &orientation, Vecnt<3,float> &scaling , Quatt<float> &scaleOrientation ); // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // Convenience type definitions // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - typedef Matnnt<3,float> Mat33f; typedef Matnnt<3,double> Mat33d; typedef Matnnt<4,float> Mat44f; typedef Matnnt<4,double> Mat44d; // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // inlined member functions // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - template<unsigned int n, typename T> inline Matnnt<n,T>::Matnnt(bool idmat) { if(idmat) { T zero = (T)0; T one = (T)1; for ( unsigned int i=0; i<n ; ++i ) { for( unsigned int j=0; j<i; ++j ) { m_mat[i][j] = zero; } m_mat[i][i] = one; for( unsigned int j=i+1; j<n; ++j ) { m_mat[i][j] = zero; } } } } template<unsigned int n, typename T> inline Matnnt<n,T>::Matnnt( T m00, T m01, T m02 , T m10, T m11, T m12 , T m20, T m21, T m22 ) { setMat( *this, m00, m01, m02 , m10, m11, m12 , m20, m21, m22 ); } template<unsigned int n, typename T> inline Matnnt<n,T>::Matnnt( const Vecnt<n,T> & v0, const Vecnt<n,T> & v1, const Vecnt<n,T> & v2 ) { setMat( *this, v0, v1, v2 ); } template<unsigned int n, typename T> inline Matnnt<n,T>::Matnnt( T m00, T m01, T m02, T m03 , T m10, T m11, T m12, T m13 , T m20, T m21, T m22, T m23 , T m30, T m31, T m32, T m33 ) { setMat( *this, m00, m01, m02, m03 , m10, m11, m12, m13 , m20, m21, m22, m23 , m30, m31, m32, m33 ); } template<unsigned int n, typename T> template<unsigned int m, typename S> inline Matnnt<n,T>::Matnnt( const Matnnt<m,S> & rhs ) { T zero = (T)0; T one = (T)1; unsigned int minn = std::min < unsigned int >( n, m ); for( unsigned int i=0; i<minn; i++ ) { m_mat[i] = Vecnt<n,T>(rhs[i]); } for( unsigned int i=minn; i<n; i++) { for(unsigned int j=0; j<i; j++) { m_mat[i][j] = zero; } m_mat[i][i] = one; for(unsigned int j=i+1; j<n; j++) { m_mat[i][j] = zero; } } } template<unsigned int n, typename T> inline Matnnt<n,T>::Matnnt( const Vecnt<n,T> & v0 , const Vecnt<n,T> & v1 , const Vecnt<n,T> & v2 , const Vecnt<n,T> & v3 ) { setMat( *this, v0, v1, v2, v3 ); } template<unsigned int n, typename T> inline Matnnt<n,T>::Matnnt( const Vecnt<n,T> & axis, T angle ) { setMat( *this, axis, angle ); } template<unsigned int n, typename T> inline Matnnt<n,T>::Matnnt( const Quatt<T> & ori ) { setMat( *this, ori ); } template<unsigned int n, typename T> inline Matnnt<n,T>::Matnnt( const Quatt<T> & ori, const Vecnt<n-1,T> & trans ) { setMat( *this, ori, trans ); } template<unsigned int n, typename T> inline Matnnt<n,T>::Matnnt( const Quatt<T> & ori, const Vecnt<n-1,T> & trans, const Vecnt<n-1,T> & scale ) { setMat( *this, ori, trans, scale ); } template<unsigned int n, typename T> inline const T * Matnnt<n,T>::getPtr() const { return( m_mat[0].getPtr() ); } template<unsigned int n, typename T> bool Matnnt<n,T>::invert() { Matnnt<n,T> tmp; bool ok = nvmath::invert( *this, tmp ); if ( ok ) { *this = tmp; } return( ok ); } template<unsigned int n, typename T> template<typename S> inline Vecnt<n,T> & Matnnt<n,T>::operator[]( S i ) { NVSG_CTASSERT( std::numeric_limits<S>::is_integer ); NVSG_ASSERT( i < n ); return( m_mat[i] ); } template<unsigned int n, typename T> template<typename S> inline const Vecnt<n,T> & Matnnt<n,T>::operator[]( S i ) const { NVSG_CTASSERT( std::numeric_limits<S>::is_integer ); NVSG_ASSERT( i < n ); return( m_mat[i] ); } template<unsigned int n, typename T> template<typename S> inline Matnnt<n,T> & Matnnt<n,T>::operator+=( const Matnnt<n,S> & rhs ) { for ( unsigned int i=0 ; i<n ; ++i ) { m_mat[i] += rhs[i]; } return( *this ); } template<unsigned int n, typename T> template<typename S> inline Matnnt<n,T> & Matnnt<n,T>::operator-=( const Matnnt<n,S> & rhs ) { for ( unsigned int i=0 ; i<n ; ++i ) { m_mat[i] -= rhs[i]; } return( *this ); } template<unsigned int n, typename T> template<typename S> inline Matnnt<n,T> & Matnnt<n,T>::operator*=( S s ) { for ( unsigned int i=0 ; i<n ; ++i ) { m_mat[i] *= s; } return( *this ); } template<unsigned int n, typename T> inline Matnnt<n,T> & Matnnt<n,T>::operator*=( const Matnnt<n,T> & rhs ) { *this = *this * rhs; return( *this ); } template<unsigned int n, typename T> template<typename S> inline Matnnt<n,T> & Matnnt<n,T>::operator/=( S s ) { for ( unsigned int i=0 ; i<n ; ++i ) { m_mat[i] /= s; } return( *this ); } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // inlined non-member functions // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - template<unsigned int n, typename T, unsigned int k> inline T calculateDeterminant( const Matnnt<n,T> & m, const Vecnt<k,unsigned int> & first, const Vecnt<k,unsigned int> & second ) { Vecnt<k-1,unsigned int> subFirst, subSecond; for ( unsigned int i=1 ; i<k ; i++ ) { subFirst[i-1] = first[i]; subSecond[i-1] = second[i]; } T sum(0); T sign(1); for ( unsigned int i=0 ; i<k ; i++ ) { sum += sign * m[first[0]][second[i]] * calculateDeterminant( m, subFirst, subSecond ); sign = - sign; if ( i < k-1 ) { subSecond[i] = second[i]; } } return( sum ); } template<unsigned int n, typename T> inline T calculateDeterminant( const Matnnt<n,T> & m, const Vecnt<1,unsigned int> & first, const Vecnt<1,unsigned int> & second ) { return( m[first[0]][second[0]] ); } template<unsigned n, typename T> inline T determinant( const Matnnt<n,T> & m ) { Vecnt<n,unsigned int> first, second; for ( unsigned int i=0 ; i<n ; i++) { first[i] = i; second[i] = i; } return( calculateDeterminant( m, first, second ) ); } template<unsigned int n, typename T> inline bool invert( const Matnnt<n,T> & mIn, Matnnt<n,T> & mOut ) { mOut = mIn; unsigned int p[n]; bool ok = true; for ( unsigned int k=0 ; ok && k<n ; ++k ) { T max<T>(0); p[k] = 0; for ( unsigned int i=k ; ok && i<n ; ++i ) { T s(0); for ( unsigned int j=k ; j<n ; ++j ) { s += abs( mOut[i][j] ); } ok = ( std::numeric_limits<T>::epsilon() < abs(s) ); if ( ok ) { T q = abs( mOut[i][k] ) / s; if ( q > max ) { max = q; p[k] = i; } } } ok = ( std::numeric_limits<T>::epsilon() < max ); if ( ok ) { if ( p[k] != k ) { for ( unsigned int j=0 ; j<n ; ++j ) { std::swap( mOut[k][j], mOut[p[k]][j] ); } } T pivot = mOut[k][k]; ok = ( std::numeric_limits<T>::epsilon() < abs( pivot ) ); if ( ok ) { for ( unsigned int j=0 ; j<n ; ++j ) { if ( j != k ) { mOut[k][j] /= - pivot; for ( unsigned int i=0 ; i<n ; ++i ) { if ( i != k ) { mOut[i][j] += mOut[i][k] * mOut[k][j]; } } } } for ( unsigned int i=0 ; i<n ; ++i ) { mOut[i][k] /= pivot; } mOut[k][k] = 1.0f / pivot; } } } if ( ok ) { for ( unsigned int k=n-2 ; k<n ; --k ) // NOTE: ( unsigned int k < n ) <=> ( int k >= 0 ) { if ( p[k] != k ) { for ( unsigned int i=0 ; i<n ; ++i ) { std::swap( mOut[i][k], mOut[i][p[k]] ); } } } } return( ok ); } template<unsigned int n, typename T> inline T maxElement( const Matnnt<n,T> & m ) { T me = maxElement( m[0] ); for ( unsigned int i=1 ; i<n ; ++i ) { T t = maxElement( m[i] ); if ( me < t ) { me = t; } } return( me ); } template<unsigned int n, typename T> inline T minElement( const Matnnt<n,T> & m ) { T me = minElement( m[0] ); for ( unsigned int i=1 ; i<n ; ++i ) { T t = minElement( m[i] ); if ( t < me ) { me = t; } } return( me ); } template<unsigned int n, typename T> inline bool operator==( const Matnnt<n,T> & m0, const Matnnt<n,T> & m1 ) { bool eq = true; for ( unsigned int i=0 ; i<n && eq ; ++i ) { eq = ( m0[i] == m1[i] ); } return( eq ); } template<unsigned int n, typename T> inline bool operator!=( const Matnnt<n,T> & m0, const Matnnt<n,T> & m1 ) { return( ! ( m0 == m1 ) ); } template<unsigned int n, typename T> inline Matnnt<n,T> operator~( const Matnnt<n,T> & m ) { Matnnt<n,T> ret; for ( unsigned int i=0 ; i<n ; ++i ) { for ( unsigned int j=0 ; j<n ; ++j ) { ret[i][j] = m[j][i]; } } return( ret ); } template<unsigned int n, typename T> inline Matnnt<n,T> operator+( const Matnnt<n,T> & m0, const Matnnt<n,T> & m1 ) { Matnnt<n,T> ret(m0); ret += m1; return( ret ); } template<unsigned int n, typename T> inline Matnnt<n,T> operator-( const Matnnt<n,T> & m ) { Matnnt<n,T> ret; for ( unsigned int i=0 ; i<n ; ++i ) { ret[i] = -m[i]; } return( ret ); } template<unsigned int n, typename T> inline Matnnt<n,T> operator-( const Matnnt<n,T> & m0, const Matnnt<n,T> & m1 ) { Matnnt<n,T> ret(m0); ret -= m1; return( ret ); } template<unsigned int n, typename T> inline Matnnt<n,T> operator*( const Matnnt<n,T> & m, T s ) { Matnnt<n,T> ret(m); ret *= s; return( ret ); } template<unsigned int n, typename T> inline Matnnt<n,T> operator*( T s, const Matnnt<n,T> & m ) { return( m * s ); } template<unsigned int n, typename T> inline Vecnt<n,T> operator*( const Matnnt<n,T> & m, const Vecnt<n,T> & v ) { Vecnt<n,T> ret; for ( unsigned int i=0 ; i<n ; ++i ) { ret[i] = m[i] * v; } return( ret ); } template<unsigned int n, typename T> inline Vecnt<n,T> operator*( const Vecnt<n,T> & v, const Matnnt<n,T> & m ) { Vecnt<n,T> ret; for ( unsigned int i=0 ; i<n ; ++i ) { ret[i] = 0; for ( unsigned int j=0 ; j<n ; ++j ) { ret[i] += v[j] * m[j][i]; } } return( ret ); } template<unsigned int n, typename T> inline Matnnt<n,T> operator*( const Matnnt<n,T> & m0, const Matnnt<n,T> & m1 ) { Matnnt<n,T> ret; for ( unsigned int i=0 ; i<n ; ++i ) { for ( unsigned int j=0 ; j<n ; ++j ) { ret[i][j] = 0; for ( unsigned int k=0 ; k<n ; ++k ) { ret[i][j] += m0[i][k] * m1[k][j]; } } } return( ret ); } template<unsigned int n, typename T> inline Matnnt<n,T> operator/( const Matnnt<n,T> & m, T s ) { Matnnt<n,T> ret(m); ret /= s; return( ret ); } template<unsigned int n, typename T> void setIdentity( Matnnt<n,T> & m ) { for ( unsigned int i=0 ; i<n ; ++i ) { for ( unsigned int j=0 ; j<i ; ++j ) { m[i][j] = T(0); } m[i][i] = T(1); for ( unsigned int j=i+1 ; j<n ; ++j ) { m[i][j] = T(0); } } } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // inlined non-member functions, specialized for n == 3 // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - template<typename T> inline T determinant( const Matnnt<3,T> & m ) { return( m[0] * ( m[1] ^ m[2] ) ); } template<typename T> inline bool invert( const Matnnt<3,T> & mIn, Matnnt<3,T> & mOut ) { double adj00 = ( mIn[1][1] * mIn[2][2] - mIn[1][2] * mIn[2][1] ); double adj10 = - ( mIn[1][0] * mIn[2][2] - mIn[1][2] * mIn[2][0] ); double adj20 = ( mIn[1][0] * mIn[2][1] - mIn[1][1] * mIn[2][0] ); double det = mIn[0][0] * adj00 + mIn[0][1] * adj10 + mIn[0][2] * adj20; bool ok = ( std::numeric_limits<double>::epsilon() < abs( det ) ); if ( ok ) { double invDet = 1.0 / det; mOut[0][0] = T( adj00 * invDet ); mOut[0][1] = T( - ( mIn[0][1] * mIn[2][2] - mIn[0][2] * mIn[2][1] ) * invDet ); mOut[0][2] = T( ( mIn[0][1] * mIn[1][2] - mIn[0][2] * mIn[1][1] ) * invDet ); mOut[1][0] = T( adj10 * invDet ); mOut[1][1] = T( ( mIn[0][0] * mIn[2][2] - mIn[0][2] * mIn[2][0] ) * invDet ); mOut[1][2] = T( - ( mIn[0][0] * mIn[1][2] - mIn[0][2] * mIn[1][0] ) * invDet ); mOut[2][0] = T( adj20 * invDet ); mOut[2][1] = T( - ( mIn[0][0] * mIn[2][1] - mIn[0][1] * mIn[2][0] ) * invDet ); mOut[2][2] = T( ( mIn[0][0] * mIn[1][1] - mIn[0][1] * mIn[1][0] ) * invDet ); } return( ok ); } template<typename T> inline Matnnt<3,T> & setMat( Matnnt<3,T> & m, T m00, T m01, T m02 , T m10, T m11, T m12 , T m20, T m21, T m22 ) { m[0][0] = m00; m[0][1] = m01; m[0][2] = m02; m[1][0] = m10; m[1][1] = m11; m[1][2] = m12; m[2][0] = m20; m[2][1] = m21; m[2][2] = m22; return( m ); } template<typename T> inline Matnnt<3,T> & setMat( Matnnt<3,T> & m, const Vecnt<3,T> & v0 , const Vecnt<3,T> & v1 , const Vecnt<3,T> & v2 ) { m[0] = v0; m[1] = v1; m[2] = v2; return( m ); } template<typename T> Matnnt<3,T> & setMat( Matnnt<3,T> & m, const Vecnt<3,T> & axis, T angle ) { NVSG_PRIVATE_ASSERT( isNormalized( axis ) ); T c = cos( angle ); T s = sin( angle ); NVSG_PRIVATE_ASSERT( abs( s * s + c * c - 1 ) <= std::numeric_limits<T>::epsilon() ); T t = 1 - c; T x = axis[0]; T y = axis[1]; T z = axis[2]; m[0] = Vecnt<3,T>( t * x * x + c, t * x * y + s * z, t * x * z - s * y ); m[1] = Vecnt<3,T>( t * x * y - s * z, t * y * y + c, t * y * z + s * x ); m[2] = Vecnt<3,T>( t * x * z + s * y, t * y * z - s * x, t * z * z + c ); NVSG_PRIVATE_ASSERT( isRotation( m ) ); return( m ); } template<typename T> inline Matnnt<3,T> & setMat( Matnnt<3,T> & m, const Quatt<T> & q ) { NVSG_PRIVATE_ASSERT( isNormalized( q ) ); T x = q[0]; T y = q[1]; T z = q[2]; T w = q[3]; m[0] = Vecnt<3,T>( 1 - 2 * ( y * y + z * z ), 2 * ( x * y + z * w ), 2 * ( x * z - y * w ) ); m[1] = Vecnt<3,T>( 2 * ( x * y - z * w ), 1 - 2 * ( x * x + z * z ), 2 * ( y * z + x * w ) ); m[2] = Vecnt<3,T>( 2 * ( x * z + y * w ), 2 * ( y * z - x * w ), 1 - 2 * ( x * x + y * y ) ); NVSG_PRIVATE_ASSERT( isRotation( m ) ); return( m ); } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // inlined non-member functions, specialized for n == 4 // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - template<typename T> inline T determinant( const Matnnt<4,T> & m ) { const T a0 = m[0][0]*m[1][1] - m[0][1]*m[1][0]; const T a1 = m[0][0]*m[1][2] - m[0][2]*m[1][0]; const T a2 = m[0][0]*m[1][3] - m[0][3]*m[1][0]; const T a3 = m[0][1]*m[1][2] - m[0][2]*m[1][1]; const T a4 = m[0][1]*m[1][3] - m[0][3]*m[1][1]; const T a5 = m[0][2]*m[1][3] - m[0][3]*m[1][2]; const T b0 = m[2][0]*m[3][1] - m[2][1]*m[3][0]; const T b1 = m[2][0]*m[3][2] - m[2][2]*m[3][0]; const T b2 = m[2][0]*m[3][3] - m[2][3]*m[3][0]; const T b3 = m[2][1]*m[3][2] - m[2][2]*m[3][1]; const T b4 = m[2][1]*m[3][3] - m[2][3]*m[3][1]; const T b5 = m[2][2]*m[3][3] - m[2][3]*m[3][2]; return( a0*b5 - a1*b4 + a2*b3 + a3*b2 - a4*b1 + a5*b0 ); } template<typename T> inline bool invert( const Matnnt<4,T> & mIn, Matnnt<4,T> & mOut ) { double s0 = mIn[0][0] * mIn[1][1] - mIn[0][1] * mIn[1][0]; double c5 = mIn[2][2] * mIn[3][3] - mIn[2][3] * mIn[3][2]; double s1 = mIn[0][0] * mIn[1][2] - mIn[0][2] * mIn[1][0]; double c4 = mIn[2][1] * mIn[3][3] - mIn[2][3] * mIn[3][1]; double s2 = mIn[0][0] * mIn[1][3] - mIn[0][3] * mIn[1][0]; double c3 = mIn[2][1] * mIn[3][2] - mIn[2][2] * mIn[3][1]; double s3 = mIn[0][1] * mIn[1][2] - mIn[0][2] * mIn[1][1]; double c2 = mIn[2][0] * mIn[3][3] - mIn[2][3] * mIn[3][0]; double s4 = mIn[0][1] * mIn[1][3] - mIn[0][3] * mIn[1][1]; double c1 = mIn[2][0] * mIn[3][2] - mIn[2][2] * mIn[3][0]; double s5 = mIn[0][2] * mIn[1][3] - mIn[0][3] * mIn[1][2]; double c0 = mIn[2][0] * mIn[3][1] - mIn[2][1] * mIn[3][0]; double det = s0 * c5 - s1 * c4 + s2 * c3 + s3 * c2 - s4 * c1 + s5 * c0; bool ok = ( std::numeric_limits<double>::epsilon() < abs( det ) ); if ( ok ) { double invDet = 1.0 / det; mOut[0][0] = T( ( mIn[1][1] * c5 - mIn[1][2] * c4 + mIn[1][3] * c3 ) * invDet ); mOut[0][1] = T( ( - mIn[0][1] * c5 + mIn[0][2] * c4 - mIn[0][3] * c3 ) * invDet ); mOut[0][2] = T( ( mIn[3][1] * s5 - mIn[3][2] * s4 + mIn[3][3] * s3 ) * invDet ); mOut[0][3] = T( ( - mIn[2][1] * s5 + mIn[2][2] * s4 - mIn[2][3] * s3 ) * invDet ); mOut[1][0] = T( ( - mIn[1][0] * c5 + mIn[1][2] * c2 - mIn[1][3] * c1 ) * invDet ); mOut[1][1] = T( ( mIn[0][0] * c5 - mIn[0][2] * c2 + mIn[0][3] * c1 ) * invDet ); mOut[1][2] = T( ( - mIn[3][0] * s5 + mIn[3][2] * s2 - mIn[3][3] * s1 ) * invDet ); mOut[1][3] = T( ( mIn[2][0] * s5 - mIn[2][2] * s2 + mIn[2][3] * s1 ) * invDet ); mOut[2][0] = T( ( mIn[1][0] * c4 - mIn[1][1] * c2 + mIn[1][3] * c0 ) * invDet ); mOut[2][1] = T( ( - mIn[0][0] * c4 + mIn[0][1] * c2 - mIn[0][3] * c0 ) * invDet ); mOut[2][2] = T( ( mIn[3][0] * s4 - mIn[3][1] * s2 + mIn[3][3] * s0 ) * invDet ); mOut[2][3] = T( ( - mIn[2][0] * s4 + mIn[2][1] * s2 - mIn[2][3] * s0 ) * invDet ); mOut[3][0] = T( ( - mIn[1][0] * c3 + mIn[1][1] * c1 - mIn[1][2] * c0 ) * invDet ); mOut[3][1] = T( ( mIn[0][0] * c3 - mIn[0][1] * c1 + mIn[0][2] * c0 ) * invDet ); mOut[3][2] = T( ( - mIn[3][0] * s3 + mIn[3][1] * s1 - mIn[3][2] * s0 ) * invDet ); mOut[3][3] = T( ( mIn[2][0] * s3 - mIn[2][1] * s1 + mIn[2][2] * s0 ) * invDet ); } return( ok ); } /*! \brief makeLookAt defines a viewing transformation. * \param eye The position of the eye point. * \param center The position of the reference point. * \param up The direction of the up vector. * \remarks The makeLookAt function creates a viewing matrix derived from an eye point, a reference point indicating the center * of the scene, and an up vector. The matrix maps the reference point to the negative z-axis and the eye point to the * origin, so that when you use a typical projection matrix, the center of the scene maps to the center of the viewport. * Similarly, the direction described by the up vector projected onto the viewing plane is mapped to the positive y-axis so that * it points upward in the viewport. The up vector must not be parallel to the line of sight from the eye to the reference point. * \note This documentation is adapted from gluLookAt, and is courtesy of SGI. */ template <typename T> inline Matnnt<4,T> makeLookAt( const Vecnt<3,T> & eye, const Vecnt<3,T> & center, const Vecnt<3,T> & up ) { Vecnt<3,T> f = center - eye; normalize( f ); #ifndef NDEBUG // assure up is not parallel to vector from eye to center Vecnt<3,T> nup = up; normalize( nup ); T dot = f * nup; NVSG_PRIVATE_ASSERT( dot != T(1) && dot != T(-1) ); #endif Vecnt<3,T> s = f ^ up; normalize( s ); Vecnt<3,T> u = s ^ f; Matnnt<4,T> transmat( T(1), T(0), T(0), T(0), T(0), T(1), T(0), T(0), T(0), T(0), T(1), T(0), -eye[0], -eye[1], -eye[2], T(1) ); Matnnt<4,T> orimat( s[0], u[0], -f[0], T(0), s[1], u[1], -f[1], T(0), s[2], u[2], -f[2], T(0), T(0), T(0), T(0), T(1) ); // must premultiply translation return transmat * orimat; } /*! \brief makeOrtho defines an orthographic projection matrix. * \param left Coordinate for the left vertical clipping plane. * \param right Coordinate for the right vertical clipping plane. * \param bottom Coordinate for the bottom horizontal clipping plane. * \param top Coordinate for the top horizontal clipping plane. * \param znear The distance to the near clipping plane. This distance is negative if the plane is behind the viewer. * \param zfar The distance to the far clipping plane. This distance is negative if the plane is behind the viewer. * \remarks The makeOrtho function describes a perspective matrix that produces a parallel projection. Assuming this function * will be used to build a camera's Projection matrix, the (left, bottom, znear) and (right, top, znear) parameters specify the * points on the near clipping plane that are mapped to the lower-left and upper-right corners of the window, respectively, * assuming that the eye is located at (0, 0, 0). The far parameter specifies the location of the far clipping plane. Both znear * and zfar can be either positive or negative. * \note This documentation is adapted from glOrtho, and is courtesy of SGI. */ template <typename T> inline Matnnt<4,T> makeOrtho( T left, T right, T bottom, T top, T znear, T zfar ) { NVSG_ASSERT( (left != right) && (bottom != top) && (znear != zfar) && (zfar > znear) ); return Matnnt<4,T>( T(2)/(right-left), T(0), T(0), T(0), T(0), T(2)/(top-bottom), T(0), T(0), T(0), T(0), T(-2)/(zfar-znear), T(0), -(right+left)/(right-left), -(top+bottom)/(top-bottom), -(zfar+znear)/(zfar-znear), T(1) ); } /*! \brief makeFrustum defines a perspective projection matrix. * \param left Coordinate for the left vertical clipping plane. * \param right Coordinate for the right vertical clipping plane. * \param bottom Coordinate for the bottom horizontal clipping plane. * \param top Coordinate for the top horizontal clipping plane. * \param znear The distance to the near clipping plane. The value must be greater than zero. * \param zfar The distance to the far clipping plane. The value must be greater than znear. * \remarks The makeFrustum function describes a perspective matrix that produces a perspective projection. Assuming this function * will be used to build a camera's Projection matrix, the (left, bottom, znear) and (right, top, znear) parameters specify the * points on the near clipping plane that are mapped to the lower-left and upper-right corners of the window, respectively, * assuming that the eye is located at (0,0,0). The zfar parameter specifies the location of the far clipping plane. Both znear * and zfar must be positive. * \note This documentation is adapted from glFrustum, and is courtesy of SGI. */ template <typename T> inline Matnnt<4,T> makeFrustum( T left, T right, T bottom, T top, T znear, T zfar ) { // near and far must be greater than zero NVSG_ASSERT( (znear > T(0)) && (zfar > T(0)) && (zfar > znear) ); NVSG_ASSERT( (left != right) && (bottom != top) && (znear != zfar) ); T v0 = (right+left)/(right-left); T v1 = (top+bottom)/(top-bottom); T v2 = -(zfar+znear)/(zfar-znear); T v3 = T(-2)*zfar*znear/(zfar-znear); T v4 = T(2)*znear/(right-left); T v5 = T(2)*znear/(top-bottom); return Matnnt<4,T>( v4, T(0), T(0), T(0), T(0), v5, T(0), T(0), v0, v1, v2, T(-1), T(0), T(0), v3, T(0) ); } /*! \brief makePerspective builds a perspective projection matrix. * \param fovy The vertical field of view, in degrees. * \param aspect The ratio of the viewport width / height. * \param znear The distance to the near clipping plane. The value must be greater than zero. * \param zfar The distance to the far clipping plane. The value must be greater than znear. * \remarks Assuming makePerspective will be used to build a camera's Projection matrix, it specifies a viewing frustum into the * world coordinate system. In general, the aspect ratio in makePerspective should match the aspect ratio of the associated * viewport. For example, aspect = 2.0 means the viewer's angle of view is twice as wide in x as it is in y. If the viewport * is twice as wide as it is tall, it displays the image without distortion. * \note This documentation is adapted from gluPerspective, and is courtesy of SGI. */ template <typename T> inline Matnnt<4,T> makePerspective( T fovy, T aspect, T znear, T zfar ) { NVSG_ASSERT( (znear > (T)0) && (zfar > (T)0) ); T tanfov = tan( nvmath::degToRad( fovy ) * (T)0.5 ); T r = tanfov * aspect * znear; T l = -r; T t = tanfov * znear; T b = -t; return makeFrustum<T>( l, r, b, t, znear, zfar ); } template<typename T> inline Vecnt<4,T> operator*( const Vecnt<4,T>& v, const Matnnt<4,T>& m) { return Vecnt<4,T> ( v[0] * m[0][0] + v[1]*m[1][0] + v[2]*m[2][0] + v[3]*m[3][0], v[0] * m[0][1] + v[1]*m[1][1] + v[2]*m[2][1] + v[3]*m[3][1], v[0] * m[0][2] + v[1]*m[1][2] + v[2]*m[2][2] + v[3]*m[3][2], v[0] * m[0][3] + v[1]*m[1][3] + v[2]*m[2][3] + v[3]*m[3][3] ); } template<typename T> inline Matnnt<4, T> operator*(const Matnnt<4,T> & m0, const Matnnt<4,T> & m1) { return Matnnt<4,T> ( m0[0][0]*m1[0][0] + m0[0][1]*m1[1][0] + m0[0][2]*m1[2][0] + m0[0][3]*m1[3][0], m0[0][0]*m1[0][1] + m0[0][1]*m1[1][1] + m0[0][2]*m1[2][1] + m0[0][3]*m1[3][1], m0[0][0]*m1[0][2] + m0[0][1]*m1[1][2] + m0[0][2]*m1[2][2] + m0[0][3]*m1[3][2], m0[0][0]*m1[0][3] + m0[0][1]*m1[1][3] + m0[0][2]*m1[2][3] + m0[0][3]*m1[3][3], m0[1][0]*m1[0][0] + m0[1][1]*m1[1][0] + m0[1][2]*m1[2][0] + m0[1][3]*m1[3][0], m0[1][0]*m1[0][1] + m0[1][1]*m1[1][1] + m0[1][2]*m1[2][1] + m0[1][3]*m1[3][1], m0[1][0]*m1[0][2] + m0[1][1]*m1[1][2] + m0[1][2]*m1[2][2] + m0[1][3]*m1[3][2], m0[1][0]*m1[0][3] + m0[1][1]*m1[1][3] + m0[1][2]*m1[2][3] + m0[1][3]*m1[3][3], m0[2][0]*m1[0][0] + m0[2][1]*m1[1][0] + m0[2][2]*m1[2][0] + m0[2][3]*m1[3][0], m0[2][0]*m1[0][1] + m0[2][1]*m1[1][1] + m0[2][2]*m1[2][1] + m0[2][3]*m1[3][1], m0[2][0]*m1[0][2] + m0[2][1]*m1[1][2] + m0[2][2]*m1[2][2] + m0[2][3]*m1[3][2], m0[2][0]*m1[0][3] + m0[2][1]*m1[1][3] + m0[2][2]*m1[2][3] + m0[2][3]*m1[3][3], m0[3][0]*m1[0][0] + m0[3][1]*m1[1][0] + m0[3][2]*m1[2][0] + m0[3][3]*m1[3][0], m0[3][0]*m1[0][1] + m0[3][1]*m1[1][1] + m0[3][2]*m1[2][1] + m0[3][3]*m1[3][1], m0[3][0]*m1[0][2] + m0[3][1]*m1[1][2] + m0[3][2]*m1[2][2] + m0[3][3]*m1[3][2], m0[3][0]*m1[0][3] + m0[3][1]*m1[1][3] + m0[3][2]*m1[2][3] + m0[3][3]*m1[3][3] ); } template<typename T> inline Matnnt<4,T> & setMat( Matnnt<4,T> & m, T m00, T m01, T m02, T m03 , T m10, T m11, T m12, T m13 , T m20, T m21, T m22, T m23 , T m30, T m31, T m32, T m33 ) { m[0][0] = m00; m[0][1] = m01; m[0][2] = m02; m[0][3] = m03; m[1][0] = m10; m[1][1] = m11; m[1][2] = m12; m[1][3] = m13; m[2][0] = m20; m[2][1] = m21; m[2][2] = m22; m[2][3] = m23; m[3][0] = m30; m[3][1] = m31; m[3][2] = m32; m[3][3] = m33; return( m ); } template<typename T> inline Matnnt<4,T> & setMat( Matnnt<4,T> & m, const Vecnt<4,T> & v0 , const Vecnt<4,T> & v1 , const Vecnt<4,T> & v2 , const Vecnt<4,T> & v3 ) { m[0] = v0; m[1] = v1; m[2] = v2; m[3] = v3; return( m ); } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // inlined non-member functions, specialized for n == 4, T == float // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - inline void decompose( const Matnnt<4,float> &m, Vecnt<3,float> &translation , Quatt<float> &orientation, Vecnt<3,float> &scaling , Quatt<float> &scaleOrientation ) { translation = Vecnt<3,float>( m[3] ); Matnnt<3,float> m33( m ); decompose( m33, orientation, scaling, scaleOrientation ); } //! global identity matrix. extern NVSG_API const Mat44f cIdentity44f; } // namespace nvmath
c759b107d81cd4bd370a59555341fb348043130f
01a24c90f7b7bd6b3031b9d39285e5f91da1bf16
/montecarlotrial/txImage.h
e4d86c6e0d75ca096ad079953004e2d8a96f3e94
[]
no_license
tianxiao/montecarlotrial
977a35c97e1989ac938dc37a8bbbf1f2d763d7e6
6c5d1073a215a64112ae2005805a2cc7b8a37976
refs/heads/master
2021-01-10T20:22:11.718795
2013-01-08T03:48:37
2013-01-08T03:48:37
null
0
0
null
null
null
null
UTF-8
C++
false
false
353
h
#pragma once class txRgb; class txImage { public: txImage(void); txImage(int width, int height, int ncomponents=3); ~txImage(void); // Manipulation void SetPixelRGB(int row, int column, const txRgb& rgb); int WriteJPEG(const char *filename)const ; private: int width; int height; int ncomponents; int rowsize; unsigned char *pixels; };
2968499410a4b2484239f49d9ec5d8037aed5c09
d00111316eaf4158a60ae9bd7491de2920dcb85c
/tasks/week3/ros_rviz/src/robot/src/sim_robot.cpp
e99c475f449a420971987470af81c8d48c15be93
[]
no_license
PumpkinJimmy/tutorial_2021
b4a36a94d6d9e9000b9567e54f3c992301f1f635
07717ba5afc44922e0efc2b55aec535d0f29860a
refs/heads/main
2023-07-17T19:02:43.011980
2021-09-04T06:13:23
2021-09-04T06:13:23
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,024
cpp
#include <ros/ros.h> #include <visualization_msgs/Marker.h> struct move_robot{ public: move_robot(int n); visualization_msgs::Marker head; visualization_msgs::Marker body; visualization_msgs::Marker hand; float pos_x,pos_y; int ori;//0-7对应0,45,90,135,180,225,270,315,180, int n; void move(); void pos_go(int t); private: //大小 const float head_scalex=0.4,head_scaley=0.4,head_scalez=0.4; const float body_scalex=0.2,body_scaley=0.2,body_scalez=1.0; const float hand_scalex=0.2,hand_scaley=0.8,hand_scalez=0.2; //组合位置 const float head_posx=0.0,head_posy=0.0,head_posz=1.2; const float body_posx=0.0,body_posy=0.0,body_posz=0.5; const float hand_posx=0.0,hand_posy=0.0,hand_posz=0.60; //姿态 }; move_robot::move_robot(int n){ this->n=n; head.header.frame_id = "/my_frame"; body.header.frame_id = "/my_frame"; hand.header.frame_id = "/my_frame"; head.ns = "head"; head.id = n; body.ns = "body"; body.id = n; hand.ns = "hand"; hand.id = n; //形状 head.type = visualization_msgs::Marker::SPHERE; body.type = visualization_msgs::Marker::CUBE; hand.type = visualization_msgs::Marker::CUBE; //动作 head.action = visualization_msgs::Marker::ADD; body.action = visualization_msgs::Marker::ADD; hand.action = visualization_msgs::Marker::ADD; //大小 head.scale.x = head_scalex; head.scale.y = head_scaley; head.scale.z = head_scalez; body.scale.x = body_scalex; body.scale.y = body_scaley; body.scale.z = body_scalez; hand.scale.x = hand_scalex; hand.scale.y = hand_scaley; hand.scale.z = hand_scalez; //颜色 head.color.r = 1.0f; head.color.g = 0.0f; head.color.b = 0.0f; head.color.a = 1.0; body.color.r = 0.0f; body.color.g = 1.0f; body.color.b = 0.0f; body.color.a = 1.0; hand.color.r = 0.0f; hand.color.g = 0.0f; hand.color.b = 1.0f; hand.color.a = 1.0; pos_x=rand()%12000/1000-6.00; pos_y=rand()%12000/1000-6.00; ori=rand()%8; } void move_robot::move(){ //更新时间戳 head.header.stamp = ros::Time::now(); body.header.stamp = ros::Time::now(); hand.header.stamp = ros::Time::now(); //更新方向角度 if(ori==0||ori==4){ hand.pose.orientation.w = 1; hand.pose.orientation.x = 0; hand.pose.orientation.y = 0; hand.pose.orientation.z = 0; } else if(ori==1||ori==5){ hand.pose.orientation.w = sqrt(2+sqrt(2))/2; hand.pose.orientation.x = 0; hand.pose.orientation.y = 0; hand.pose.orientation.z = -sqrt(2)/(4*sqrt(2+sqrt(2))/2); } else if(ori==2||ori==6){ hand.pose.orientation.w = sqrt(2-sqrt(2))/2; hand.pose.orientation.x = 0; hand.pose.orientation.y = 0; hand.pose.orientation.z = -sqrt(2)/(4*sqrt(2-sqrt(2))/2); } else if(ori==3||ori==7){ hand.pose.orientation.w = sqrt(2-sqrt(2))/2; hand.pose.orientation.x = 0; hand.pose.orientation.y = 0; hand.pose.orientation.z = sqrt(2)/(4*sqrt(2-sqrt(2))/2); } else { ori%=8; } //更新位置 head.pose.position.x = pos_x+head_posx; head.pose.position.y = pos_y+head_posy; head.pose.position.z = head_posz; body.pose.position.x = pos_x+body_posx; body.pose.position.y = pos_y+body_posy; body.pose.position.z = body_posz; hand.pose.position.x = pos_x+hand_posx; hand.pose.position.y = pos_y+hand_posy; hand.pose.position.z = hand_posz; head.lifetime = ros::Duration(); body.lifetime = ros::Duration(); hand.lifetime = ros::Duration(); }//姿态控制 //位置移动 void move_robot::pos_go(int t){ double noise[2]; noise[0] = rand()%100/800; //噪声 noise[2] = rand()%100/800; pos_x += noise[0]; pos_y += noise[1]; if(ori==0){ pos_x+=0.03; } else if(ori==1){ pos_x+=0.03/sqrt(2); pos_y+=0.03/sqrt(2); } else if(ori==2){ pos_y+=0.03; } else if(ori==3){ pos_y+=0.03/sqrt(2); pos_x-=0.03/sqrt(2); } else if(ori==4){ pos_x-=0.03; } else if(ori==5){ pos_x-=0.03/sqrt(2); pos_y-=0.03/sqrt(2); } else if(ori==6){ pos_y-=0.03; } else if(ori==7){ pos_y-=0.03/sqrt(2); pos_x+=0.03/sqrt(2); } else{ ori%=8; } if((t%(8+n))==0)ori+=2; }//加噪声 int main( int argc, char** argv ) { ros::init(argc, argv, "move_robot"); ros::NodeHandle n; ros::Rate r(10); srand((int)time(0)); // 产生随机种子 ros::Publisher marker_pub = n.advertise<visualization_msgs::Marker>("visualization_marker", 40); int t=0; move_robot m1(1); move_robot m2(2); move_robot m3(3); move_robot m4(4); move_robot m5(5); move_robot m6(6); move_robot m7(7); move_robot m8(8); move_robot m9(9); move_robot m10(10); while (ros::ok()) { // Publish the marker while (marker_pub.getNumSubscribers() < 1) { if (!ros::ok()) { return 0; } ROS_WARN_ONCE("Please create a subscriber to the marker"); sleep(1); } m1.pos_go(t);m2.pos_go(t);m3.pos_go(t);m4.pos_go(t);m5.pos_go(t);m6.pos_go(t);m7.pos_go(t);m8.pos_go(t);m9.pos_go(t);m10.pos_go(t); m1.move();m2.move();m3.move();m4.move();m5.move();m6.move();m7.move();m8.move();m9.move();m10.move(); marker_pub.publish(m1.head);marker_pub.publish(m1.body);marker_pub.publish(m1.hand); marker_pub.publish(m2.head);marker_pub.publish(m2.body);marker_pub.publish(m2.hand); marker_pub.publish(m3.head);marker_pub.publish(m3.body);marker_pub.publish(m3.hand); marker_pub.publish(m4.head);marker_pub.publish(m4.body);marker_pub.publish(m4.hand); marker_pub.publish(m5.head);marker_pub.publish(m5.body);marker_pub.publish(m5.hand); marker_pub.publish(m6.head);marker_pub.publish(m6.body);marker_pub.publish(m6.hand); marker_pub.publish(m7.head);marker_pub.publish(m7.body);marker_pub.publish(m7.hand); marker_pub.publish(m8.head);marker_pub.publish(m8.body);marker_pub.publish(m8.hand); marker_pub.publish(m9.head);marker_pub.publish(m9.body);marker_pub.publish(m9.hand); marker_pub.publish(m10.head);marker_pub.publish(m10.body);marker_pub.publish(m10.hand); t++; r.sleep(); } }
275ccecbe6d93c3fa97140a1fec01c26101b0142
5ec06dab1409d790496ce082dacb321392b32fe9
/clients/cpp-restbed-server/generated/model/ComAdobeCqSocialContentFragmentsServicesImplCommunitiesFragmenInfo.h
cd301e9ac182eb6f27b7569af87b91d23a19a331
[ "Apache-2.0" ]
permissive
shinesolutions/swagger-aem-osgi
e9d2385f44bee70e5bbdc0d577e99a9f2525266f
c2f6e076971d2592c1cbd3f70695c679e807396b
refs/heads/master
2022-10-29T13:07:40.422092
2021-04-09T07:46:03
2021-04-09T07:46:03
190,217,155
3
3
Apache-2.0
2022-10-05T03:26:20
2019-06-04T14:23:28
null
UTF-8
C++
false
false
2,291
h
/** * Adobe Experience Manager OSGI config (AEM) API * Swagger AEM OSGI is an OpenAPI specification for Adobe Experience Manager (AEM) OSGI Configurations API * * OpenAPI spec version: 1.0.0-pre.0 * Contact: [email protected] * * NOTE: This class is auto generated by OpenAPI-Generator 3.2.1-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ /* * ComAdobeCqSocialContentFragmentsServicesImplCommunitiesFragmenInfo.h * * */ #ifndef ComAdobeCqSocialContentFragmentsServicesImplCommunitiesFragmenInfo_H_ #define ComAdobeCqSocialContentFragmentsServicesImplCommunitiesFragmenInfo_H_ #include <string> #include "ComAdobeCqSocialContentFragmentsServicesImplCommunitiesFragmenProperties.h" #include <memory> namespace org { namespace openapitools { namespace server { namespace model { /// <summary> /// /// </summary> class ComAdobeCqSocialContentFragmentsServicesImplCommunitiesFragmenInfo { public: ComAdobeCqSocialContentFragmentsServicesImplCommunitiesFragmenInfo(); virtual ~ComAdobeCqSocialContentFragmentsServicesImplCommunitiesFragmenInfo(); std::string toJsonString(); void fromJsonString(std::string const& jsonString); ///////////////////////////////////////////// /// ComAdobeCqSocialContentFragmentsServicesImplCommunitiesFragmenInfo members /// <summary> /// /// </summary> std::string getPid() const; void setPid(std::string value); /// <summary> /// /// </summary> std::string getTitle() const; void setTitle(std::string value); /// <summary> /// /// </summary> std::string getDescription() const; void setDescription(std::string value); /// <summary> /// /// </summary> std::shared_ptr<ComAdobeCqSocialContentFragmentsServicesImplCommunitiesFragmenProperties> getProperties() const; void setProperties(std::shared_ptr<ComAdobeCqSocialContentFragmentsServicesImplCommunitiesFragmenProperties> value); protected: std::string m_Pid; std::string m_Title; std::string m_Description; std::shared_ptr<ComAdobeCqSocialContentFragmentsServicesImplCommunitiesFragmenProperties> m_Properties; }; } } } } #endif /* ComAdobeCqSocialContentFragmentsServicesImplCommunitiesFragmenInfo_H_ */
f282faf281cd29e4558d81bff90b9e78b33ad3ce
521786619e016ea5f30952f51425a8683554cb42
/search_cycle/src/ShortestPath.hpp
86bcb44558928ed9f7d60ac06086181ac07deb72
[]
no_license
TweakAESKS/TweakAESKS
ed22c386786590bde430a23553e07160e60d639c
b375695a0050fc0c7d9080862e62f06a0a4b53fe
refs/heads/master
2020-03-17T06:42:29.911452
2020-02-17T10:49:30
2020-02-17T10:49:30
133,366,233
1
1
null
null
null
null
UTF-8
C++
false
false
6,193
hpp
#ifndef HPP_SHORTESTPATH #define HPP_SHORTESTPATH #include <cstdint> #include "DicStateKey.hpp" class ShortestPath { public: ShortestPath (unsigned n_rounds = 0, unsigned n_conf = 0) : dec0 (n_conf), dec1 (n_conf*(n_rounds-1)) { shortest_path = new uint8_t [dec0*dec1]; }; ShortestPath (std::vector<std::vector<Subset>> const & transitions1r, unsigned bound_active, unsigned n_rounds, DicStateKey const & dic) { auto const & state_conf = dic.getStateConfs(); dec0 = state_conf.size(); dec1 = dec0*(n_rounds-1); shortest_path = new uint8_t [dec0*dec1]; for (unsigned i = 0; i < dec0*dec1; ++i) shortest_path[i] = bound_active; for (unsigned i0 = 0; i0 < dec0; ++i0) { for (unsigned i1 = 0; i1 < dec0; ++i1) { if (!transitions1r[i0][i1].empty()) (*this)(0,i0,i1) = fast_popcnt16(state_conf[i0]) + fast_popcnt16(state_conf[i1]); } } for (unsigned r = 1; r < n_rounds - 1; ++r) { for (unsigned i0 = 0; i0 < dec0; ++i0) { for (unsigned i1 = 0; i1 < dec0; ++i1) { auto const pathi0i1 = (*this)(r-1,i0,i1); if (pathi0i1 < bound_active) { auto const pop_i1 = fast_popcnt16(state_conf[i1]); for (unsigned i2 = 0; i2 < dec0; ++i2) { uint8_t const tmp = pathi0i1 - pop_i1 + (*this)(0,i1,i2); (*this)(r,i0,i2) = std::min((*this)(r,i0,i2), tmp); } } } } } } ShortestPath (ShortestPath const & s) : dec0(s.dec0), dec1(s.dec1) { auto const bound = dec0*dec1; shortest_path = new uint8_t [bound]; for (unsigned i = 0; i < bound; ++i) shortest_path[i] = s.shortest_path[i]; } ShortestPath (ShortestPath && s) : dec0(s.dec0), dec1(s.dec1), shortest_path(s.shortest_path) { s.shortest_path = nullptr; s.dec0 = 0; s.dec1 = 0; } ShortestPath & operator=(ShortestPath const & s) { dec0 = s.dec0; dec1 = s.dec1; delete[] shortest_path; auto const bound = dec0*dec1; shortest_path = new uint8_t [bound]; for (unsigned i = 0; i < bound; ++i) shortest_path[i] = s.shortest_path[i]; return *this; } ShortestPath & operator=(ShortestPath && s) { dec0 = s.dec0; dec1 = s.dec1; delete[] shortest_path; shortest_path = s.shortest_path; s.shortest_path = nullptr; s.dec0 = 0; s.dec1 = 0; return *this; } ~ShortestPath() {delete[] shortest_path;}; unsigned size() const {return dec0;}; unsigned deep() const {return dec1/dec0;}; uint8_t operator()(unsigned r, unsigned i0, unsigned i1) const {return shortest_path[dec1*i1 + dec0*r + i0];}; uint8_t & operator()(unsigned r, unsigned i0, unsigned i1) {return shortest_path[dec1*i1 + dec0*r + i0];}; private: unsigned dec0; unsigned dec1; uint8_t * shortest_path; }; uint64_t countPaths(ShortestPath const & s, unsigned i0, unsigned ir, unsigned bound_active, unsigned n_rounds, DicStateKey const & dic) { if (n_rounds == 2) return 1; auto const & state_conf = dic.getStateConfs(); uint64_t cpt = 0; for (unsigned i = 0; i < s.size(); ++i) { auto const pop_real_i = fast_popcnt16(state_conf[i]); if (s(0,i0,i) + s(n_rounds-3,i,ir) < bound_active + pop_real_i) cpt += countPaths(s, i, ir, bound_active + pop_real_i - s(0,i0,i), n_rounds - 1, dic); } return cpt; } std::vector<std::vector<Subset>> transitionsFromPaths(ShortestPath const & s, unsigned i0, unsigned ir, unsigned bound_active, unsigned n_rounds, DicStateKey const & dic, std::vector<std::vector<Subset>> const & transitions1r) { if (n_rounds < 2) return std::vector<std::vector<Subset>> (); if (n_rounds == 2) return std::vector<std::vector<Subset>> (1, std::vector<Subset> (1, transitions1r[i0][ir])); std::vector<std::vector<Subset>> res; auto const & state_conf = dic.getStateConfs(); for (unsigned i = 0; i < s.size(); ++i) { auto const pop_real_i = fast_popcnt16(state_conf[i]); if (s(0,i,ir) + s(n_rounds-3,i0,i) < bound_active + pop_real_i) { auto vec = transitionsFromPaths(s, i0, i, bound_active + pop_real_i - s(0,i,ir), n_rounds-1, dic, transitions1r); for (auto & v : vec) { v.emplace_back(transitions1r[i][ir]); res.emplace_back(move(v)); } } } return res; } bool transitions1rIsValid(unsigned const i0, unsigned const i1, ShortestPath const & s, unsigned const bound_active, unsigned const n_rounds, DicStateKey const & dic) { if (s(0,i0,i1) >= bound_active) return false; auto const & state_conf = dic.getStateConfs(); auto const n_conf = state_conf.size(); auto const pop_i0 = fast_popcnt16(state_conf[i0]); auto const pop_i1 = fast_popcnt16(state_conf[i1]); for (unsigned i = 0; i < n_conf; ++i) if (pop_i0 + s(n_rounds-3,i1,i) < bound_active) return true; for (unsigned i = 0; i < n_conf; ++i) if (pop_i1 + s(n_rounds-3,i,i0) < bound_active) return true; for (unsigned r = 0; r <= n_rounds-4; ++r) { auto min_i = s(r,0,i0); for (unsigned i = 1; i < n_conf; ++i) min_i = std::min(min_i, s(r,i,i0)); for (unsigned j = 0; j < n_conf; ++j) if (min_i + s(n_rounds-r-4,i1,j) < bound_active) return true; } return false; } bool transitions2rIsValid(unsigned const i0, unsigned const i1, unsigned const i2, ShortestPath const & s, unsigned const bound_active, unsigned const n_rounds, DicStateKey const & dic) { auto const & state_conf = dic.getStateConfs(); auto const n_conf = state_conf.size(); auto const a_2r = s(0,i0,i1) + s(0,i1,i2) - fast_popcnt16(state_conf[i1]); if (a_2r >= bound_active) return false; auto const pop_i2 = fast_popcnt16(state_conf[i2]); for (unsigned i = 0; i < n_conf; ++i) if (a_2r - pop_i2 + s(n_rounds-4,i2,i) < bound_active) return true; auto const pop_i0 = fast_popcnt16(state_conf[i0]); for (unsigned i = 0; i < n_conf; ++i) if (a_2r - pop_i0 + s(n_rounds-4,i,i0) < bound_active) return true; for (unsigned r = 0; n_rounds >= 5 + r; ++r) { for (unsigned i = 0; i < n_conf; ++i) { auto const a = a_2r - pop_i0 + s(r,i,i0); if (a < bound_active) { for (unsigned j = 0; j < n_conf; ++j) if (a - pop_i2 + s(n_rounds-(5+r),i2,j) < bound_active) return true; } } } return false; } #endif
be2412062f97639327c39174f0269ade840bef9a
07c0b01cc28bb11052ebd665dba2f9c4c32b9f71
/data_structures/binarytree/right_side_view.cpp
703aec2f61a182170d3263d591cc8a26e4d88ba6
[]
no_license
juniway/lint
52eb4f1f35e97badad09bb92211c7827932a57c8
0b53049c86940a262d42150004de70466f885188
refs/heads/master
2021-01-10T09:31:36.794439
2020-09-02T00:55:03
2020-09-02T00:55:03
50,222,610
0
0
null
null
null
null
UTF-8
C++
false
false
1,477
cpp
#include <iostream> #include <vector> #include <stack> #include <unordered_set> #include "tree.hpp" using namespace std; struct HashByLevelNumber { public: size_t operator()(pair<Node*, int> p) const { return std::hash<int>()(p.second); } }; struct EqualBySize { public: bool operator()(pair<Node*, int> p1, pair<Node*, int> p2) const { return p1.second == p2.second; } }; vector<int> rightSideView(Node *root) { if (root == nullptr) return {}; unordered_set<pair<Node*, int>, HashByLevelNumber, EqualBySize> visited; stack<pair<Node*, int>> s; s.push(make_pair(root, 0)); vector<int> res; while(!s.empty()) { auto nd_i = s.top(); s.pop(); if (visited.find(nd_i) == visited.end()) { // visit one level at one time visited.insert(nd_i); res.push_back(nd_i.first->data); } if (nd_i.first->left) s.push(make_pair(nd_i.first->left, nd_i.second + 1)); if (nd_i.first->right) s.push(make_pair(nd_i.first->right, nd_i.second + 1)); } return res; } void testRightSideView() { Node *root = new Node(1); root->left = new Node(2); root->right = new Node(3); root->left->right = new Node(5); root->right->right = new Node(4); auto res = rightSideView(root); for (auto x : res) cout << x << " "; cout << endl; } int main(int argc, char *argv[]) { testRightSideView(); return 0; }
207ad3084c3b778cfcbd19643c6c60c476830d34
696bf3a2fe56225acdac8d544d8d8c182ef248e3
/src/qt/rpcconsole.cpp
f5a168e63e3f94af14025cade3058573356bc328
[ "MIT" ]
permissive
IOEdev/IOEsource
89a491f828f43d639440d0147edb6e0fdf11fc61
bb754d6e997142e571b403264e634897458ca1d9
refs/heads/master
2020-07-04T21:20:16.259100
2016-11-18T14:31:38
2016-11-18T14:31:38
74,135,871
2
1
null
2017-03-10T19:56:13
2016-11-18T14:18:05
C++
UTF-8
C++
false
false
14,465
cpp
#include "rpcconsole.h" #include "ui_rpcconsole.h" #include "clientmodel.h" #include "bitcoinrpc.h" #include "guiutil.h" #include <QTime> #include <QTimer> #include <QThread> #include <QTextEdit> #include <QKeyEvent> #include <QUrl> #include <QScrollBar> #include <openssl/crypto.h> // TODO: make it possible to filter out categories (esp debug messages when implemented) // TODO: receive errors and debug messages through ClientModel const int CONSOLE_SCROLLBACK = 50; const int CONSOLE_HISTORY = 50; const QSize ICON_SIZE(24, 24); const struct { const char *url; const char *source; } ICON_MAPPING[] = { {"cmd-request", ":/icons/tx_input"}, {"cmd-reply", ":/icons/tx_output"}, {"cmd-error", ":/icons/tx_output"}, {"misc", ":/icons/tx_inout"}, {NULL, NULL} }; /* Object for executing console RPC commands in a separate thread. */ class RPCExecutor: public QObject { Q_OBJECT public slots: void start(); void request(const QString &command); signals: void reply(int category, const QString &command); }; #include "rpcconsole.moc" void RPCExecutor::start() { // Nothing to do } /** * Split shell command line into a list of arguments. Aims to emulate \c bash and friends. * * - Arguments are delimited with whitespace * - Extra whitespace at the beginning and end and between arguments will be ignored * - Text can be "double" or 'single' quoted * - The backslash \c \ is used as escape character * - Outside quotes, any character can be escaped * - Within double quotes, only escape \c " and backslashes before a \c " or another backslash * - Within single quotes, no escaping is possible and no special interpretation takes place * * @param[out] args Parsed arguments will be appended to this list * @param[in] strCommand Command line to split */ bool parseCommandLine(std::vector<std::string> &args, const std::string &strCommand) { enum CmdParseState { STATE_EATING_SPACES, STATE_ARGUMENT, STATE_SINGLEQUOTED, STATE_DOUBLEQUOTED, STATE_ESCAPE_OUTER, STATE_ESCAPE_DOUBLEQUOTED } state = STATE_EATING_SPACES; std::string curarg; foreach(char ch, strCommand) { switch(state) { case STATE_ARGUMENT: // In or after argument case STATE_EATING_SPACES: // Handle runs of whitespace switch(ch) { case '"': state = STATE_DOUBLEQUOTED; break; case '\'': state = STATE_SINGLEQUOTED; break; case '\\': state = STATE_ESCAPE_OUTER; break; case ' ': case '\n': case '\t': if(state == STATE_ARGUMENT) // Space ends argument { args.push_back(curarg); curarg.clear(); } state = STATE_EATING_SPACES; break; default: curarg += ch; state = STATE_ARGUMENT; } break; case STATE_SINGLEQUOTED: // Single-quoted string switch(ch) { case '\'': state = STATE_ARGUMENT; break; default: curarg += ch; } break; case STATE_DOUBLEQUOTED: // Double-quoted string switch(ch) { case '"': state = STATE_ARGUMENT; break; case '\\': state = STATE_ESCAPE_DOUBLEQUOTED; break; default: curarg += ch; } break; case STATE_ESCAPE_OUTER: // '\' outside quotes curarg += ch; state = STATE_ARGUMENT; break; case STATE_ESCAPE_DOUBLEQUOTED: // '\' in double-quoted text if(ch != '"' && ch != '\\') curarg += '\\'; // keep '\' for everything but the quote and '\' itself curarg += ch; state = STATE_DOUBLEQUOTED; break; } } switch(state) // final state { case STATE_EATING_SPACES: return true; case STATE_ARGUMENT: args.push_back(curarg); return true; default: // ERROR to end in one of the other states return false; } } void RPCExecutor::request(const QString &command) { std::vector<std::string> args; if(!parseCommandLine(args, command.toStdString())) { emit reply(RPCConsole::CMD_ERROR, QString("Parse error: unbalanced ' or \"")); return; } if(args.empty()) return; // Nothing to do try { std::string strPrint; // Convert argument list to JSON objects in method-dependent way, // and pass it along with the method name to the dispatcher. json_spirit::Value result = tableRPC.execute( args[0], RPCConvertValues(args[0], std::vector<std::string>(args.begin() + 1, args.end()))); // Format result reply if (result.type() == json_spirit::null_type) strPrint = ""; else if (result.type() == json_spirit::str_type) strPrint = result.get_str(); else strPrint = write_string(result, true); emit reply(RPCConsole::CMD_REPLY, QString::fromStdString(strPrint)); } catch (json_spirit::Object& objError) { try // Nice formatting for standard-format error { int code = find_value(objError, "code").get_int(); std::string message = find_value(objError, "message").get_str(); emit reply(RPCConsole::CMD_ERROR, QString::fromStdString(message) + " (code " + QString::number(code) + ")"); } catch(std::runtime_error &) // raised when converting to invalid type, i.e. missing code or message { // Show raw JSON object emit reply(RPCConsole::CMD_ERROR, QString::fromStdString(write_string(json_spirit::Value(objError), false))); } } catch (std::exception& e) { emit reply(RPCConsole::CMD_ERROR, QString("Error: ") + QString::fromStdString(e.what())); } } RPCConsole::RPCConsole(QWidget *parent) : QDialog(parent), ui(new Ui::RPCConsole), historyPtr(0) { ui->setupUi(this); #ifndef Q_OS_MAC ui->openDebugLogfileButton->setIcon(QIcon(":/icons/export")); ui->showCLOptionsButton->setIcon(QIcon(":/icons/options")); #endif // Install event filter for up and down arrow ui->lineEdit->installEventFilter(this); ui->messagesWidget->installEventFilter(this); connect(ui->clearButton, SIGNAL(clicked()), this, SLOT(clear())); // set OpenSSL version label ui->openSSLVersion->setText(SSLeay_version(SSLEAY_VERSION)); startExecutor(); clear(); } RPCConsole::~RPCConsole() { emit stopExecutor(); delete ui; } bool RPCConsole::eventFilter(QObject* obj, QEvent *event) { if(event->type() == QEvent::KeyPress) // Special key handling { QKeyEvent *keyevt = static_cast<QKeyEvent*>(event); int key = keyevt->key(); Qt::KeyboardModifiers mod = keyevt->modifiers(); switch(key) { case Qt::Key_Up: if(obj == ui->lineEdit) { browseHistory(-1); return true; } break; case Qt::Key_Down: if(obj == ui->lineEdit) { browseHistory(1); return true; } break; case Qt::Key_PageUp: /* pass paging keys to messages widget */ case Qt::Key_PageDown: if(obj == ui->lineEdit) { QApplication::postEvent(ui->messagesWidget, new QKeyEvent(*keyevt)); return true; } break; default: // Typing in messages widget brings focus to line edit, and redirects key there // Exclude most combinations and keys that emit no text, except paste shortcuts if(obj == ui->messagesWidget && ( (!mod && !keyevt->text().isEmpty() && key != Qt::Key_Tab) || ((mod & Qt::ControlModifier) && key == Qt::Key_V) || ((mod & Qt::ShiftModifier) && key == Qt::Key_Insert))) { ui->lineEdit->setFocus(); QApplication::postEvent(ui->lineEdit, new QKeyEvent(*keyevt)); return true; } } } return QDialog::eventFilter(obj, event); } void RPCConsole::setClientModel(ClientModel *model) { this->clientModel = model; if(model) { // Subscribe to information, replies, messages, errors connect(model, SIGNAL(numConnectionsChanged(int)), this, SLOT(setNumConnections(int))); connect(model, SIGNAL(numBlocksChanged(int,int)), this, SLOT(setNumBlocks(int,int))); // Provide initial values ui->clientVersion->setText(model->formatFullVersion()); ui->clientName->setText(model->clientName()); ui->buildDate->setText(model->formatBuildDate()); ui->startupTime->setText(model->formatClientStartupTime()); setNumConnections(model->getNumConnections()); ui->isTestNet->setChecked(model->isTestNet()); setNumBlocks(model->getNumBlocks(), model->getNumBlocksOfPeers()); } } static QString categoryClass(int category) { switch(category) { case RPCConsole::CMD_REQUEST: return "cmd-request"; break; case RPCConsole::CMD_REPLY: return "cmd-reply"; break; case RPCConsole::CMD_ERROR: return "cmd-error"; break; default: return "misc"; } } void RPCConsole::clear() { ui->messagesWidget->clear(); ui->lineEdit->clear(); ui->lineEdit->setFocus(); // Add smoothly scaled icon images. // (when using width/height on an img, Qt uses nearest instead of linear interpolation) for(int i=0; ICON_MAPPING[i].url; ++i) { ui->messagesWidget->document()->addResource( QTextDocument::ImageResource, QUrl(ICON_MAPPING[i].url), QImage(ICON_MAPPING[i].source).scaled(ICON_SIZE, Qt::IgnoreAspectRatio, Qt::SmoothTransformation)); } // Set default style sheet ui->messagesWidget->document()->setDefaultStyleSheet( "table { }" "td.time { color: #808080; padding-top: 3px; } " "td.message { font-family: Monospace; font-size: 12px; } " "td.cmd-request { color: #006060; } " "td.cmd-error { color: red; } " "b { color: #006060; } " ); message(CMD_REPLY, (tr("Welcome to the IOE RPC console.") + "<br>" + tr("Use up and down arrows to navigate history, and <b>Ctrl-L</b> to clear screen.") + "<br>" + tr("Type <b>help</b> for an overview of available commands.")), true); } void RPCConsole::message(int category, const QString &message, bool html) { QTime time = QTime::currentTime(); QString timeString = time.toString(); QString out; out += "<table><tr><td class=\"time\" width=\"65\">" + timeString + "</td>"; out += "<td class=\"icon\" width=\"32\"><img src=\"" + categoryClass(category) + "\"></td>"; out += "<td class=\"message " + categoryClass(category) + "\" valign=\"middle\">"; if(html) out += message; else out += GUIUtil::HtmlEscape(message, true); out += "</td></tr></table>"; ui->messagesWidget->append(out); } void RPCConsole::setNumConnections(int count) { ui->numberOfConnections->setText(QString::number(count)); } void RPCConsole::setNumBlocks(int count, int countOfPeers) { ui->numberOfBlocks->setText(QString::number(count)); ui->totalBlocks->setText(QString::number(countOfPeers)); if(clientModel) { // If there is no current number available display N/A instead of 0, which can't ever be true ui->totalBlocks->setText(clientModel->getNumBlocksOfPeers() == 0 ? tr("N/A") : QString::number(clientModel->getNumBlocksOfPeers())); ui->lastBlockTime->setText(clientModel->getLastBlockDate().toString()); } } void RPCConsole::on_lineEdit_returnPressed() { QString cmd = ui->lineEdit->text(); ui->lineEdit->clear(); if(!cmd.isEmpty()) { message(CMD_REQUEST, cmd); emit cmdRequest(cmd); // Remove command, if already in history history.removeOne(cmd); // Append command to history history.append(cmd); // Enforce maximum history size while(history.size() > CONSOLE_HISTORY) history.removeFirst(); // Set pointer to end of history historyPtr = history.size(); // Scroll console view to end scrollToEnd(); } } void RPCConsole::browseHistory(int offset) { historyPtr += offset; if(historyPtr < 0) historyPtr = 0; if(historyPtr > history.size()) historyPtr = history.size(); QString cmd; if(historyPtr < history.size()) cmd = history.at(historyPtr); ui->lineEdit->setText(cmd); } void RPCConsole::startExecutor() { QThread* thread = new QThread; RPCExecutor *executor = new RPCExecutor(); executor->moveToThread(thread); // Notify executor when thread started (in executor thread) connect(thread, SIGNAL(started()), executor, SLOT(start())); // Replies from executor object must go to this object connect(executor, SIGNAL(reply(int,QString)), this, SLOT(message(int,QString))); // Requests from this object must go to executor connect(this, SIGNAL(cmdRequest(QString)), executor, SLOT(request(QString))); // On stopExecutor signal // - queue executor for deletion (in execution thread) // - quit the Qt event loop in the execution thread connect(this, SIGNAL(stopExecutor()), executor, SLOT(deleteLater())); connect(this, SIGNAL(stopExecutor()), thread, SLOT(quit())); // Queue the thread for deletion (in this thread) when it is finished connect(thread, SIGNAL(finished()), thread, SLOT(deleteLater())); // Default implementation of QThread::run() simply spins up an event loop in the thread, // which is what we want. thread->start(); } void RPCConsole::on_tabWidget_currentChanged(int index) { if(ui->tabWidget->widget(index) == ui->tab_console) { ui->lineEdit->setFocus(); } } void RPCConsole::on_openDebugLogfileButton_clicked() { GUIUtil::openDebugLogfile(); } void RPCConsole::scrollToEnd() { QScrollBar *scrollbar = ui->messagesWidget->verticalScrollBar(); scrollbar->setValue(scrollbar->maximum()); } void RPCConsole::on_showCLOptionsButton_clicked() { GUIUtil::HelpMessageBox help; help.exec(); }
f6e0b7283e123fbe6b8557f3ed3e5715df00d133
cec005da6e7bd12ebf13011022296d09fbfe1e5e
/SR-Team/Client/Headers/ItemSlot_RedElixir.h
03f7efd4d206a24bb0925015cbfd28230a5fa425
[]
no_license
Turtle-Corder/SR-NewWorld
ea1efa952b2e6416dafccc144d57a5a3fa29f03b
4839e235c72871ea8f53e77ed56557634c1cd082
refs/heads/master
2023-01-11T15:14:19.557570
2020-11-12T05:50:20
2020-11-12T05:50:20
309,598,463
0
0
null
null
null
null
UHC
C++
false
false
934
h
#pragma once #ifndef __ITEMSLOT_REDELIXER_H__ #define __ITEMSLOT_REDELIXER_H__ #include "ItemSlot.h" USING(Engine) BEGIN(Client) class CItemSlot_RedElixir : public CItemSlot { public: explicit CItemSlot_RedElixir(LPDIRECT3DDEVICE9 _pDevice, LPD3DXSPRITE _pSprite, LPD3DXFONT _pFont); explicit CItemSlot_RedElixir(const CItemSlot_RedElixir& _rOther); virtual ~CItemSlot_RedElixir() = default; public: // CPlayerItem을(를) 통해 상속됨 virtual HRESULT Setup_GameObject_Prototype() override; virtual HRESULT Setup_GameObject(void * _pArg) override; virtual _int Update_GameObject(_float _fDeltaTime) override; virtual _int LateUpdate_GameObject(_float _fDeltaTime) override; public: static CItemSlot_RedElixir* Create(LPDIRECT3DDEVICE9 pDevice, LPD3DXSPRITE _pSprite, LPD3DXFONT _pFont); virtual CGameObject * Clone_GameObject(void * _pArg) override; public: virtual _bool Actual_UseItem() override; }; END #endif
cf705e81875279d1db42e7e21dc8cab5047d8d42
6540ac51373d533fc6bd88ff2b22c4e26f9960c3
/src/usb/ao/AoUsb1608hs.cpp
159375ec220a04bba3230b0da1de2e1e927f138a
[ "MIT" ]
permissive
mccdaq/uldaq
92e09dbe3d189f35156731ce09cf74a56d5336aa
1d8404159c0fb6d2665461b80acca5bbef5c610a
refs/heads/master
2022-05-02T14:49:01.623605
2022-03-22T01:52:43
2022-03-22T01:52:43
131,733,031
88
38
MIT
2020-05-11T21:48:24
2018-05-01T15:59:13
C
UTF-8
C++
false
false
6,977
cpp
/* * AoUsb1608hs.cpp * * Author: Measurement Computing Corporation */ #include "AoUsb1608hs.h" namespace ul { AoUsb1608hs::AoUsb1608hs(const UsbDaqDevice& daqDevice, int numChans) : AoUsbBase(daqDevice) { double minRate = 0.59604644775390625; mAoInfo.setAOutFlags(AOUT_FF_NOSCALEDATA | AOUT_FF_NOCALIBRATEDATA); mAoInfo.setAOutArrayFlags(AOUTARRAY_FF_NOSCALEDATA | AOUTARRAY_FF_NOCALIBRATEDATA); mAoInfo.setAOutScanFlags(AOUTSCAN_FF_NOSCALEDATA | AOUTSCAN_FF_NOCALIBRATEDATA); mAoInfo.setScanOptions(SO_DEFAULTIO|SO_CONTINUOUS|SO_BLOCKIO); // single i/o is not supported mAoInfo.hasPacer(true); mAoInfo.setNumChans(numChans); mAoInfo.setResolution(16); mAoInfo.setMinScanRate(minRate); mAoInfo.setMaxScanRate(76000); mAoInfo.setMaxThroughput(76000); mAoInfo.setFifoSize(FIFO_SIZE); mAoInfo.setCalCoefsStartAddr(0); mAoInfo.setCalDateAddr(0); mAoInfo.setCalCoefCount(0); mAoInfo.setSampleSize(2); mAoInfo.addRange(BIP10VOLTS); setScanEndpointAddr(0x01); setScanStopCmd(CMD_AOUTSTOP); memset(&mScanConfig, 0, sizeof(mScanConfig)); memset(mAOutVals, 0, sizeof(mAOutVals)); } AoUsb1608hs::~AoUsb1608hs() { } void AoUsb1608hs::initialize() { try { sendStopCmd(); readAOutVals(); } catch(UlException& e) { UL_LOG("Ul exception occurred: " << e.what()); } } void AoUsb1608hs::aOut(int channel, Range range, AOutFlag flags, double dataValue) { UlLock lock(mIoDeviceMutex); check_AOut_Args(channel, range, flags, dataValue); unsigned short calData = calibrateData(channel, range, flags, dataValue); unsigned short vals[2]; memcpy(vals, mAOutVals, sizeof(mAOutVals)); vals[channel] = calData; daqDev().sendCmd(CMD_AOUT, 0, 0, (unsigned char*) vals, sizeof(vals)); mAOutVals[channel] = vals[channel]; } double AoUsb1608hs::aOutScan(int lowChan, int highChan, Range range, int samplesPerChan, double rate, ScanOption options, AOutScanFlag flags, double data[]) { UlLock lock(mIoDeviceMutex); check_AOutScan_Args(lowChan, highChan, range, samplesPerChan, rate, options, flags, data); int epAddr = getScanEndpointAddr(); //setTransferMode(options, rate); mTransferMode = SO_BLOCKIO; int chanCount = highChan - lowChan + 1; int stageSize = calcStageSize(epAddr, rate, chanCount, samplesPerChan); std::vector<CalCoef> calCoefs = getScanCalCoefs(lowChan, highChan, range, flags); daqDev().clearHalt(epAddr); setScanInfo(FT_AO, chanCount, samplesPerChan, mAoInfo.getSampleSize(), mAoInfo.getResolution(), options, flags, calCoefs, data); setScanConfig(lowChan, highChan, samplesPerChan, rate, options); daqDev().scanTranserOut()->initilizeTransfers(this, epAddr, stageSize); try { daqDev().sendCmd(CMD_AOUTSCAN_START, 0, 0, NULL, 0, 1000); setScanState(SS_RUNNING); } catch(UlException& e) { stopBackground(); throw e; } return actualScanRate(); } void AoUsb1608hs::setScanConfig(int lowChan, int highChan, unsigned int scanCount, double rate, ScanOption options) { memset(&mScanConfig, 0, sizeof(mScanConfig)); calcPacerParams(rate, mScanConfig.prescale, mScanConfig.preload); mScanConfig.preload = Endian::cpu_to_le_ui16(mScanConfig.preload); mScanConfig.options = getOptionsCode(lowChan, highChan, options); mScanConfig.scan_count = Endian::cpu_to_le_ui32(scanCount); if(options & SO_CONTINUOUS) mScanConfig.scan_count = 0; daqDev().sendCmd(CMD_AOUTSCAN_CONFIG, 0, 0, (unsigned char*) &mScanConfig, sizeof(mScanConfig), 1000); } void AoUsb1608hs::calcPacerParams(double rate, unsigned char& prescale, unsigned short& preload) { long clk = CLK_FREQ; double freq= rate; double pl; double ps = 1; int ps_index = 0; pl = ((double) clk / (freq * ps)) - 1; while(pl > 65535.0) { ps *= 2; ps_index++; pl = ((double) clk / (freq * ps)) - 1; } if (ps_index > 8) { ps = 256; ps_index = 8; pl = ((double) clk / (freq * ps)) - 1; } else prescale = ps_index; if (pl < 0.0) preload = 0; else if (pl > 65535.0) preload = 65535; else preload = (unsigned short) pl; double actualrate = clk; actualrate /= ps; actualrate /= preload + 1; setActualScanRate(actualrate); } unsigned char AoUsb1608hs::getOptionsCode(int lowChan, int highChan, ScanOption options) const { unsigned char optcode = 0; unsigned char channelMask = getChannelMask(lowChan, highChan); optcode = channelMask; return optcode; } unsigned char AoUsb1608hs::getChannelMask(int lowChan, int highChan) const { unsigned char chanMask = 0; for(int chan = lowChan; chan <= highChan; chan++) chanMask |= (unsigned char) (0x01 << chan); return chanMask; } int AoUsb1608hs::getCalCoefIndex(int channel, Range range) const { int calCoefIndex = channel; return calCoefIndex; } void AoUsb1608hs::readAOutVals() { UlLock lock(mIoDeviceMutex); daqDev().queryCmd(CMD_AOUT, 0, 0, (unsigned char*) mAOutVals, sizeof(mAOutVals)); } UlError AoUsb1608hs::checkScanState(bool* scanDone) const { UlError err = ERR_NO_ERROR; unsigned char cmd = daqDev().getCmdValue(UsbDaqDevice::CMD_STATUS_KEY); unsigned char status =0; try { daqDev().queryCmd(cmd, 0, 0, (unsigned char*)&status, sizeof(status)); if((status & daqDev().getScanDoneBitMask()) || !(status & daqDev().getScanRunningBitMask(SD_OUTPUT))) *scanDone = true; if(status & daqDev().getUnderrunBitMask()) { err = ERR_UNDERRUN; } } catch(UlException& e) { err = e.getError(); } catch(...) { err = ERR_UNHANDLED_EXCEPTION; } return err; } void AoUsb1608hs::setCfg_SenseMode(int channel, AOutSenseMode mode) { if(!daqDev().isConnected()) throw UlException(ERR_DEV_NOT_CONNECTED); UlLock lock(mIoDeviceMutex); // acquire the lock so ALREADY_ACTIVE error can be detected correctly on multi-threaded processes if(getScanState() == SS_RUNNING) throw UlException(ERR_ALREADY_ACTIVE); if(channel < 0 || channel >= mAoInfo.getNumChans()) throw UlException(ERR_BAD_AO_CHAN); unsigned char mask = 0; daqDev().queryCmd(CMD_AOUT_CONFIG, 0, 0, (unsigned char*) &mask, sizeof(mask)); std::bitset<8> config = mask; if(mode == AOSM_ENABLED) config.set(channel); else config.reset(channel); mask = (unsigned char) config.to_ulong(); daqDev().sendCmd(CMD_AOUT_CONFIG, 0, 0, (unsigned char*) &mask, sizeof(mask)); } AOutSenseMode AoUsb1608hs::getCfg_SenseMode(int channel) const { AOutSenseMode mode = AOSM_DISABLED; if(!daqDev().isConnected()) throw UlException(ERR_DEV_NOT_CONNECTED); UlLock lock(const_cast<AoUsb1608hs*>(this)->mIoDeviceMutex); // acquire the lock so ALREADY_ACTIVE error can be detected correctly on multi-threaded processes if(getScanState() == SS_RUNNING) throw UlException(ERR_ALREADY_ACTIVE); if(channel < 0 || channel >= mAoInfo.getNumChans()) throw UlException(ERR_BAD_AO_CHAN); unsigned char mask = 0; daqDev().queryCmd(CMD_AOUT_CONFIG, 0, 0, (unsigned char*) &mask, sizeof(mask)); std::bitset<8> config = mask; if(config[channel]) mode = AOSM_ENABLED; return mode; } } /* namespace ul */
2b00b3ef29f078195981fbac97dd485ae44738cf
ae956d4076e4fc03b632a8c0e987e9ea5ca89f56
/SDK/TBP_VMP_TOR_F_HAIR_05_classes.h
d8256830065d7e9b873acf21ee58b477443b199d
[]
no_license
BrownBison/Bloodhunt-BASE
5c79c00917fcd43c4e1932bee3b94e85c89b6bc7
8ae1104b748dd4b294609717142404066b6bc1e6
refs/heads/main
2023-08-07T12:04:49.234272
2021-10-02T15:13:42
2021-10-02T15:13:42
638,649,990
1
0
null
2023-05-09T20:02:24
2023-05-09T20:02:23
null
UTF-8
C++
false
false
784
h
#pragma once // Name: bbbbbbbbbbbbbbbbbbbbbbblod, Version: 1 /*!!DEFINE!!*/ /*!!HELPER_DEF!!*/ /*!!HELPER_INC!!*/ #ifdef _MSC_VER #pragma pack(push, 0x01) #endif namespace CG { //--------------------------------------------------------------------------- // Classes //--------------------------------------------------------------------------- // BlueprintGeneratedClass TBP_VMP_TOR_F_HAIR_05.TBP_VMP_TOR_F_HAIR_05_C // 0x0000 (FullSize[0x0200] - InheritedSize[0x0200]) class UTBP_VMP_TOR_F_HAIR_05_C : public UTBP_HairCustomization_Master_C { public: static UClass* StaticClass() { static UClass* ptr = UObject::FindClass("BlueprintGeneratedClass TBP_VMP_TOR_F_HAIR_05.TBP_VMP_TOR_F_HAIR_05_C"); return ptr; } }; } #ifdef _MSC_VER #pragma pack(pop) #endif
ca89e1b39a9665fbdc086ae77faa894ad6807446
82defde286a2d48b2f670d5bffd8eb2e365ace35
/storage/steady_storage.h
b5dcdb778ec568bf858908dc46f0f718c60210b2
[ "MIT" ]
permissive
huimiao638/godex
4226f67f9a2c2db0aafd9e839dba2236f49eeafb
ea1a0460392bf997491c431c29dd260ccf08e251
refs/heads/main
2023-03-23T15:57:53.910557
2021-03-18T12:21:34
2021-03-18T12:21:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,293
h
#pragma once #include "core/templates/paged_allocator.h" #include "dense_vector.h" #include "storage.h" /// Storage that is a lot useful when it's necessary to store big components: /// in those cases, you don't want to reallocate the memory each time a new /// entity is added or removed. /// /// This storage is also useful when you are dealing with libraries like /// the physics engine, audio engine, etc... . /// With those libraries, it's usually necessary to create objects, so thanks /// to this storage it's possible to create components that are fixed in memory, /// so pass the pointer or internal component pointers is safe. /// /// Note: The allocated memory is contiguous, but fragmented. Internally the /// storage creates some pages within the components are stored contiguosly. template <class T> class SteadyStorage : public Storage<T> { PagedAllocator<T, false> allocator; DenseVector<T *> storage; public: virtual void configure(const Dictionary &p_config) override { clear(); allocator.configure(p_config.get("page_size", 200)); } virtual String get_type_name() const override { return "SteadyStorage[" + String(typeid(T).name()) + "]"; } virtual void insert(EntityID p_entity, const T &p_data) override { T *d = allocator.alloc(); *d = p_data; storage.insert(p_entity, d); StorageBase::notify_changed(p_entity); } virtual bool has(EntityID p_entity) const override { return storage.has(p_entity); } virtual T *get(EntityID p_entity, Space p_mode = Space::LOCAL) override { StorageBase::notify_changed(p_entity); return storage.get(p_entity); } virtual const T *get(EntityID p_entity, Space p_mode = Space::LOCAL) const override { return storage.get(p_entity); } virtual void remove(EntityID p_entity) override { ERR_FAIL_COND_MSG(storage.has(p_entity) == false, "No entity: " + itos(p_entity) + " in this storage."); T *d = storage.get(p_entity); storage.remove(p_entity); allocator.free(d); // Make sure to remove as changed. StorageBase::notify_updated(p_entity); } virtual void clear() override { allocator.reset(); storage.clear(); StorageBase::flush_changed(); } virtual EntitiesBuffer get_stored_entities() const { return { storage.get_entities().size(), storage.get_entities().ptr() }; } };
149bd20bf583e702cca5bd72fd3772e3a78fb3b1
08cbeb3db9317e892dc3ec683e4fbf9c3b0e86ac
/arc/016/a.cpp
38e860813918562c790c2c7676aa522886092aba
[]
no_license
wonda-tea-coffee/atcoder
0b7a8907d6b859e7b65bbf2829fb861e080e671a
5282f9915da773df3fd27c8570690d912b0bbd90
refs/heads/master
2020-12-21T09:57:41.187968
2020-04-19T12:33:48
2020-05-02T14:49:48
236,391,204
2
1
null
null
null
null
UTF-8
C++
false
false
1,604
cpp
#include <algorithm> #include <bitset> #include <cassert> #include <cmath> #include <ctime> #include <cstring> #include <functional> #include <iostream> #include <iomanip> #include <limits> #include <map> #include <queue> #include <set> #include <stack> #include <string> #include <vector> #define fix(n) cout<<fixed<<setprecision(n) #define rep(i,n) for (int i = 0; i < (n); ++i) #define sort(a) sort((a).begin(), (a).end()) #define uniq(a) SORT(a);(a).erase(unique((a).begin(), (a).end()), (a).end()) #define reverse(a) reverse((a).begin(), (a).end()) #define ctos(c) string(1, (c)) #define out(d) cout << (d) #define outl(d) std::cout<<(d)<<"\n" #define Yes() printf("Yes\n") #define No() printf("No\n") #define YES() printf("YES\n") #define NO() printf("NO\n") #define ceil(x, y) ((x + y - 1) / (y)) #define debug(x) cerr << #x << ": " << (x) << '\n' #define debug2(x, y) cerr << #x << ": " << (x) << ", " << #y << ": " << (y) << '\n' #define debug3(x, y, z) cerr << #x << ": " << (x) << ", " << #y << ": " << (y) << ", " << #z << ": " << (z) << '\n' #define dbg(v) for (size_t _ = 0; _ < v.size(); ++_){ cerr << #v << "[" << _ << "] : " << v[_] << '\n'; } using namespace std; using ll = long long; using P = pair<ll,ll>; const ll MOD = 1000000007; // 10^9 + 7 void solve() { int n, m; cin >> n >> m; if (m == n) outl(m - 1); else outl(m + 1); } int main() { cin.tie(0); ios::sync_with_stdio(false); srand((unsigned)time(NULL)); fix(12); solve(); }
a34cc9e607e6a3a2ab912e18347763700660a02d
d0c44dd3da2ef8c0ff835982a437946cbf4d2940
/cmake-build-debug/programs_tiling/function13847/function13847_schedule_14/function13847_schedule_14_wrapper.cpp
4c8b74bf40860c8242354638188a40299858dd44
[]
no_license
IsraMekki/tiramisu_code_generator
8b3f1d63cff62ba9f5242c019058d5a3119184a3
5a259d8e244af452e5301126683fa4320c2047a3
refs/heads/master
2020-04-29T17:27:57.987172
2019-04-23T16:50:32
2019-04-23T16:50:32
176,297,755
1
2
null
null
null
null
UTF-8
C++
false
false
858
cpp
#include "Halide.h" #include "function13847_schedule_14_wrapper.h" #include "tiramisu/utils.h" #include <cstdlib> #include <iostream> #include <time.h> #include <fstream> #include <chrono> #define MAX_RAND 200 int main(int, char **){Halide::Buffer<int32_t> buf0(64, 64, 64, 64); init_buffer(buf0, (int32_t)0); auto t1 = std::chrono::high_resolution_clock::now(); function13847_schedule_14(buf0.raw_buffer()); auto t2 = std::chrono::high_resolution_clock::now(); std::chrono::duration<double> diff = t2 - t1; std::ofstream exec_times_file; exec_times_file.open("../data/programs/function13847/function13847_schedule_14/exec_times.txt", std::ios_base::app); if (exec_times_file.is_open()){ exec_times_file << diff.count() * 1000000 << "us" <<std::endl; exec_times_file.close(); } return 0; }
b93170c88ac05e993de0bb4f71468930793bd5a5
2b69e13788344efdb659eb126ae5a2c392ff5d3c
/chrome/browser/ash/app_restore/full_restore_app_launch_handler.cc
1e3e5e612ebbdbf4a5f9adf743b18eaedbb8c78e
[ "BSD-3-Clause" ]
permissive
narens21/chromium
9624c670467a3da776689d2aa3e80a9fd6bc10fe
ff814f7e874e74eb807379332f7a6e5fa9342f08
refs/heads/master
2023-08-28T02:32:43.803173
2021-09-27T09:07:39
2021-09-27T09:07:39
null
0
0
null
null
null
null
UTF-8
C++
false
false
15,802
cc
// Copyright 2021 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ash/app_restore/full_restore_app_launch_handler.h" #include <set> #include <utility> #include "ash/constants/ash_switches.h" #include "base/bind.h" #include "base/command_line.h" #include "base/metrics/histogram_functions.h" #include "base/threading/thread_task_runner_handle.h" #include "chrome/browser/apps/app_service/app_platform_metrics.h" #include "chrome/browser/apps/app_service/app_service_proxy.h" #include "chrome/browser/apps/app_service/app_service_proxy_factory.h" #include "chrome/browser/ash/app_restore/app_restore_arc_task_handler.h" #include "chrome/browser/ash/app_restore/arc_app_launch_handler.h" #include "chrome/browser/ash/app_restore/full_restore_service.h" #include "chrome/browser/ash/login/session/user_session_manager.h" #include "chrome/browser/ash/profiles/profile_helper.h" #include "chrome/browser/prefs/session_startup_pref.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/sessions/session_restore.h" #include "chrome/browser/sessions/session_service_log.h" #include "chrome/common/chrome_switches.h" #include "components/app_restore/full_restore_read_handler.h" #include "components/app_restore/full_restore_save_handler.h" #include "extensions/common/constants.h" namespace ash { namespace full_restore { namespace { bool g_launch_browser_for_testing = false; constexpr char kRestoredAppLaunchHistogramPrefix[] = "Apps.RestoredAppLaunch"; constexpr char kRestoreBrowserResultHistogramPrefix[] = "Apps.RestoreBrowserResult"; constexpr char kSessionRestoreExitResultPrefix[] = "Apps.SessionRestoreExitResult"; constexpr char kSessionRestoreWindowCountPrefix[] = "Apps.SessionRestoreWindowCount"; } // namespace FullRestoreAppLaunchHandler::FullRestoreAppLaunchHandler( Profile* profile, bool should_init_service) : AppLaunchHandler(profile), should_init_service_(should_init_service) { // FullRestoreReadHandler reads the full restore data from the full restore // data file on a background task runner. ::full_restore::FullRestoreReadHandler::GetInstance()->ReadFromFile( profile->GetPath(), base::BindOnce(&FullRestoreAppLaunchHandler::OnGetRestoreData, weak_ptr_factory_.GetWeakPtr())); } FullRestoreAppLaunchHandler::~FullRestoreAppLaunchHandler() = default; void FullRestoreAppLaunchHandler::LaunchBrowserWhenReady( bool first_run_full_restore) { if (g_launch_browser_for_testing || base::CommandLine::ForCurrentProcess()->HasSwitch( switches::kForceLaunchBrowser)) { ForceLaunchBrowserForTesting(); return; } if (first_run_full_restore) { // Observe AppRegistryCache to get the notification when the app is ready. if (apps::AppServiceProxyFactory::IsAppServiceAvailableForProfile( profile())) { auto* cache = &apps::AppServiceProxyFactory::GetForProfile(profile()) ->AppRegistryCache(); Observe(cache); for (const auto app_type : cache->GetInitializedAppTypes()) { OnAppTypeInitialized(app_type); } } LaunchBrowserForFirstRunFullRestore(); return; } // If the restore data has been loaded, and the user has chosen to restore, // launch the browser. if (CanLaunchBrowser()) { LaunchBrowser(); // OS Setting should be launched after browser to have OS setting window in // front. UserSessionManager::GetInstance()->MaybeLaunchSettings(profile()); return; } UserSessionManager::GetInstance()->MaybeLaunchSettings(profile()); // If the restore data hasn't been loaded, or the user hasn't chosen to // restore, set `should_launch_browser_` as true, and wait the restore data // loaded, and the user selection, then we can launch the browser. should_launch_browser_ = true; } void FullRestoreAppLaunchHandler::SetShouldRestore() { should_restore_ = true; MaybePostRestore(); } bool FullRestoreAppLaunchHandler::IsRestoreDataLoaded() { return restore_data() != nullptr; } void FullRestoreAppLaunchHandler::OnAppUpdate(const apps::AppUpdate& update) { // If the restore flag `should_restore_` is true, launch the app for // restoration. if (should_restore_) AppLaunchHandler::OnAppUpdate(update); } void FullRestoreAppLaunchHandler::OnAppTypeInitialized( apps::mojom::AppType app_type) { if (app_type == apps::mojom::AppType::kExtension) { are_chrome_apps_initialized_ = true; return; } if (app_type != apps::mojom::AppType::kWeb) return; are_web_apps_initialized_ = true; // `are_web_apps_initialized_` is checked in MaybeStartSaveTimer to decide // whether start the save timer. So if web apps are ready, call // MaybeStartSaveTimer to start the save timer if possbile. MaybeStartSaveTimer(); if (first_run_full_restore_) { LaunchBrowserForFirstRunFullRestore(); return; } if (should_launch_browser_ && CanLaunchBrowser()) { LaunchBrowser(); should_launch_browser_ = false; } } void FullRestoreAppLaunchHandler::OnGotSession(Profile* session_profile, bool for_app, int window_count) { if (session_profile != profile()) return; if (for_app) browser_app_window_count_ = window_count; else browser_window_count_ = window_count; } void FullRestoreAppLaunchHandler::ForceLaunchBrowserForTesting() { ::full_restore::AddChromeBrowserLaunchInfoForTesting(profile()->GetPath()); UserSessionManager::GetInstance()->LaunchBrowser(profile()); UserSessionManager::GetInstance()->MaybeLaunchSettings(profile()); } void FullRestoreAppLaunchHandler::OnExtensionLaunching( const std::string& app_id) { ::full_restore::FullRestoreReadHandler::GetInstance() ->SetNextRestoreWindowIdForChromeApp(profile()->GetPath(), app_id); } base::WeakPtr<AppLaunchHandler> FullRestoreAppLaunchHandler::GetWeakPtrAppLaunchHandler() { return weak_ptr_factory_.GetWeakPtr(); } void FullRestoreAppLaunchHandler::OnGetRestoreData( std::unique_ptr<::app_restore::RestoreData> restore_data) { set_restore_data(std::move(restore_data)); LogRestoreData(); // FullRestoreAppLaunchHandler could be created multiple times in browser // tests, and used by the desk template. Only when it is created by // FullRestoreService, we need to init FullRestoreService. if (should_init_service_) FullRestoreService::GetForProfile(profile())->Init(); } void FullRestoreAppLaunchHandler::MaybePostRestore() { MaybeStartSaveTimer(); // If the restore flag `should_restore_` is not true, or reading the restore // data hasn't finished, don't restore. if (!should_restore_ || !restore_data()) return; base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::BindOnce(&FullRestoreAppLaunchHandler::MaybeRestore, weak_ptr_factory_.GetWeakPtr())); } void FullRestoreAppLaunchHandler::MaybeRestore() { restore_start_time_ = base::TimeTicks::Now(); ::full_restore::FullRestoreReadHandler::GetInstance()->SetCheckRestoreData( profile()->GetPath()); if (should_launch_browser_ && CanLaunchBrowser()) { LaunchBrowser(); should_launch_browser_ = false; } VLOG(1) << "Restore apps in " << profile()->GetPath(); if (auto* arc_task_handler = app_restore::AppRestoreArcTaskHandler::GetForProfile(profile())) { arc_task_handler->arc_app_launch_handler()->RestoreArcApps(this); } LaunchApps(); MaybeStartSaveTimer(); } bool FullRestoreAppLaunchHandler::CanLaunchBrowser() { return should_restore_ && restore_data() && (!restore_data()->HasAppTypeBrowser() || are_web_apps_initialized_); } void FullRestoreAppLaunchHandler::LaunchBrowser() { // If the browser is not launched before reboot, don't launch browser during // the startup phase. const auto& launch_list = restore_data()->app_id_to_launch_list(); if (launch_list.find(extension_misc::kChromeAppId) == launch_list.end()) return; SessionRestore::AddObserver(this); VLOG(1) << "Restore browser for " << profile()->GetPath(); RecordRestoredAppLaunch(apps::AppTypeName::kChromeBrowser); restore_data()->RemoveApp(extension_misc::kChromeAppId); if (profile()->GetLastSessionExitType() == Profile::EXIT_CRASHED) { base::CommandLine::ForCurrentProcess()->AppendSwitch( ::switches::kHideCrashRestoreBubble); } MaybeStartSaveTimer(); if (!::full_restore::HasBrowser(profile()->GetPath())) { // If there is no normal browsers before reboot, call session restore to // restore app type browsers only. SessionRestore::RestoreSession( profile(), nullptr, SessionRestore::RESTORE_APPS, std::vector<GURL>()); SessionRestore::RemoveObserver(this); return; } // Modify the command line to restore browser sessions. base::CommandLine::ForCurrentProcess()->AppendSwitch( ::switches::kRestoreLastSession); UserSessionManager::GetInstance()->LaunchBrowser(profile()); RecordLaunchBrowserResult(); SessionRestore::RemoveObserver(this); } void FullRestoreAppLaunchHandler::LaunchBrowserForFirstRunFullRestore() { first_run_full_restore_ = true; // Wait for the web apps initialized. Because the app type in AppRegistryCache // is checked when save the browser window. If the app doesn't exist in // AppRegistryCache, the web app window can't be saved in the full restore // file, which could affect the restoration next time after reboot. if (!are_web_apps_initialized_) return; first_run_full_restore_ = false; UserSessionManager::GetInstance()->LaunchBrowser(profile()); PrefService* prefs = profile()->GetPrefs(); DCHECK(prefs); SessionStartupPref session_startup_pref = SessionStartupPref::GetStartupPref(prefs); // If the system is upgrading from a crash, the app type browser window can be // restored, so we don't need to call session restore to restore app type // browsers. If the session restore setting is not restore, we don't need to // restore app type browser neither. if (profile()->GetLastSessionExitType() != Profile::EXIT_CRASHED && !::full_restore::HasAppTypeBrowser(profile()->GetPath()) && session_startup_pref.type == SessionStartupPref::LAST) { // Restore the app type browsers only when the web apps are ready. SessionRestore::RestoreSession( profile(), nullptr, SessionRestore::RESTORE_APPS, std::vector<GURL>()); } UserSessionManager::GetInstance()->MaybeLaunchSettings(profile()); } void FullRestoreAppLaunchHandler::RecordRestoredAppLaunch( apps::AppTypeName app_type_name) { base::UmaHistogramEnumeration(kRestoredAppLaunchHistogramPrefix, app_type_name); } void FullRestoreAppLaunchHandler::RecordLaunchBrowserResult() { RestoreTabResult result = RestoreTabResult::kNoTabs; int window_count = 0; int tab_count = 0; std::list<SessionServiceEvent> events = GetSessionServiceEvents(profile()); if (!events.empty()) { auto it = events.back(); if (it.type == SessionServiceEventLogType::kRestore) { window_count = it.data.restore.window_count; tab_count = it.data.exit.tab_count; if (tab_count > 0) result = RestoreTabResult::kHasTabs; } else { result = RestoreTabResult::kError; window_count = -1; tab_count = -1; } } VLOG(1) << "Browser is restored (windows=" << window_count << " tabs=" << tab_count << ")."; base::UmaHistogramEnumeration(kRestoreBrowserResultHistogramPrefix, result); if (result != RestoreTabResult::kNoTabs) return; SessionRestoreExitResult session_restore_exit = SessionRestoreExitResult::kNoExit; for (auto iter = events.rbegin(); iter != events.rend(); ++iter) { if (iter->type != SessionServiceEventLogType::kStart) continue; ++iter; if (iter != events.rend() && iter->type == SessionServiceEventLogType::kExit) { bool is_first_session_service = iter->data.exit.is_first_session_service; bool did_schedule_command = iter->data.exit.did_schedule_command; if (is_first_session_service) { session_restore_exit = did_schedule_command ? SessionRestoreExitResult::kIsFirstServiceDidSchedule : SessionRestoreExitResult::kIsFirstServiceNoSchedule; } else { session_restore_exit = did_schedule_command ? SessionRestoreExitResult::kNotFirstServiceDidSchedule : SessionRestoreExitResult::kNotFirstServiceNoSchedule; } } break; } base::UmaHistogramEnumeration(kSessionRestoreExitResultPrefix, session_restore_exit); SessionRestoreWindowCount restored_window_count; if (browser_app_window_count_ != 0) { restored_window_count = browser_window_count_ == 0 ? SessionRestoreWindowCount::kHasAppWindowNoNormalWindow : SessionRestoreWindowCount::kHasAppWindowHasNormalWindow; } else { restored_window_count = browser_window_count_ == 0 ? SessionRestoreWindowCount::kNoWindow : SessionRestoreWindowCount::kNoAppWindowHasNormalWindow; } base::UmaHistogramEnumeration(kSessionRestoreWindowCountPrefix, restored_window_count); } void FullRestoreAppLaunchHandler::LogRestoreData() { if (!restore_data() || restore_data()->app_id_to_launch_list().empty()) { VLOG(1) << "There is no restore data from " << profile()->GetPath(); return; } int arc_app_count = 0; int other_app_count = 0; for (const auto& it : restore_data()->app_id_to_launch_list()) { if (it.first == extension_misc::kChromeAppId || it.second.empty()) continue; if (it.second.begin()->second->event_flag.has_value()) { ++arc_app_count; continue; } ++other_app_count; } VLOG(1) << "There is restore data: Browser(" << (::full_restore::HasAppTypeBrowser(profile()->GetPath()) ? " has app type browser " : " no app type browser") << "," << (::full_restore::HasBrowser(profile()->GetPath()) ? " has normal browser " : " no normal ") << ") ARC(" << arc_app_count << ") other apps(" << other_app_count << ") in " << profile()->GetPath(); } void FullRestoreAppLaunchHandler::MaybeStartSaveTimer() { if (!should_restore_) { // FullRestoreService is responsible to handle all non restore processes. return; } if (!restore_data() || restore_data()->app_id_to_launch_list().empty()) { // If there is no restore data, start the timer. ::full_restore::FullRestoreSaveHandler::GetInstance()->AllowSave(); return; } if (base::Contains(restore_data()->app_id_to_launch_list(), extension_misc::kChromeAppId)) { // If the browser hasn't been restored yet, Wait for the browser // restoration. LaunchBrowser will call this function again to start the // save timer after restore the browser sessions. return; } // If both web apps and chrome apps has finished the initialization, start the // timer. if (are_chrome_apps_initialized_ && are_web_apps_initialized_) ::full_restore::FullRestoreSaveHandler::GetInstance()->AllowSave(); } ScopedLaunchBrowserForTesting::ScopedLaunchBrowserForTesting() { g_launch_browser_for_testing = true; } ScopedLaunchBrowserForTesting::~ScopedLaunchBrowserForTesting() { g_launch_browser_for_testing = false; } } // namespace full_restore } // namespace ash
60b6c8b2196645d510fe721d949fa2844c12ae6e
7d8627273662415b2cd64c3c32fb18c613dacd79
/include/hassan/project.h
f451dff34b1fef190f4c1e87231c5a565cad5887
[]
no_license
caomw/micmac
0a60d17341a353e645926e7bf7c03eee8f10a971
9233424efe81da6c710194eec4c58c20c35ee83e
refs/heads/master
2021-01-09T06:33:16.126905
2015-03-16T14:37:04
2015-03-16T14:37:04
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,477
h
/*Header-MicMac-eLiSe-25/06/2007 MicMac : Multi Image Correspondances par Methodes Automatiques de Correlation eLiSe : ELements of an Image Software Environnement www.micmac.ign.fr Copyright : Institut Geographique National Author : Marc Pierrot Deseilligny Contributors : Gregoire Maillet, Didier Boldo. [1] M. Pierrot-Deseilligny, N. Paparoditis. "A multiresolution and optimization-based image matching approach: An application to surface reconstruction from SPOT5-HRS stereo imagery." In IAPRS vol XXXVI-1/W41 in ISPRS Workshop On Topographic Mapping From Space (With Special Emphasis on Small Satellites), Ankara, Turquie, 02-2006. [2] M. Pierrot-Deseilligny, "MicMac, un lociel de mise en correspondance d'images, adapte au contexte geograhique" to appears in Bulletin d'information de l'Institut Geographique National, 2007. Francais : MicMac est un logiciel de mise en correspondance d'image adapte au contexte de recherche en information geographique. Il s'appuie sur la bibliotheque de manipulation d'image eLiSe. Il est distibue sous la licences Cecill-B. Voir en bas de fichier et http://www.cecill.info. English : MicMac is an open source software specialized in image matching for research in geographic information. MicMac is built on the eLiSe image library. MicMac is governed by the "Cecill-B licence". See below and http://www.cecill.info. Header-MicMac-eLiSe-25/06/2007*/ #ifndef _HASSAN_PROJECT_H #define _HASSAN_PROJECT_H class Project { public : double_t4 _niv0; double_t4 _niv1; Ori3D_Std _o3; Pt2di _p0ph; Pt2di _sz; Im2D_U_int1 _iphoto; Pt3dr _p0ph3d; Pt3dr _ori_lum; Project(Pt3dr, Pt3dr, Ori3D_Std); Project(Pt3dr, Pt3dr, double_t4, double_t4, Ori3D_Std); Im2D_U_int1 image(); void set_lum(Pt3dr ori_lum){_ori_lum = ori_lum/sqrt(scal(ori_lum,ori_lum));} void lancer_de_rayon(ElList<Batiment>,double_t4, double_t4, Video_Win); void l_d_r_s_o(ElList<Batiment>, double_t4, double_t4, Video_Win); bool l_d_r_s_o(ElList<Batiment>, double_t4, double_t4, int, int, Batiment&, Facette_3d&); void l_d_r_z(Video_Win); void l_d_r_z(Facette_3d, Video_Win); void l_d_r_z(ElList<Facette_3d>, Video_Win); void l_d_r_z(ElList<Batiment>, Video_Win); void affiche(Video_Win); private: void set_param(Pt3dr,Pt3dr); double_t4 const INFINI; }; #endif // _HASSAN_PROJECT_H /*Footer-MicMac-eLiSe-25/06/2007 Ce logiciel est un programme informatique servant à la mise en correspondances d'images pour la reconstruction du relief. Ce logiciel est régi par la licence CeCILL-B soumise au droit français et respectant les principes de diffusion des logiciels libres. Vous pouvez utiliser, modifier et/ou redistribuer ce programme sous les conditions de la licence CeCILL-B telle que diffusée par le CEA, le CNRS et l'INRIA sur le site "http://www.cecill.info". En contrepartie de l'accessibilité au code source et des droits de copie, de modification et de redistribution accordés par cette licence, il n'est offert aux utilisateurs qu'une garantie limitée. Pour les mêmes raisons, seule une responsabilité restreinte pèse sur l'auteur du programme, le titulaire des droits patrimoniaux et les concédants successifs. A cet égard l'attention de l'utilisateur est attirée sur les risques associés au chargement, à l'utilisation, à la modification et/ou au développement et à la reproduction du logiciel par l'utilisateur étant donné sa spécificité de logiciel libre, qui peut le rendre complexe à manipuler et qui le réserve donc à des développeurs et des professionnels avertis possédant des connaissances informatiques approfondies. Les utilisateurs sont donc invités à charger et tester l'adéquation du logiciel à leurs besoins dans des conditions permettant d'assurer la sécurité de leurs systèmes et ou de leurs données et, plus généralement, à l'utiliser et l'exploiter dans les mêmes conditions de sécurité. Le fait que vous puissiez accéder à cet en-tête signifie que vous avez pris connaissance de la licence CeCILL-B, et que vous en avez accepté les termes. Footer-MicMac-eLiSe-25/06/2007*/
9ec9456397effa489d37a71d2d3aec6fb7e343cd
12b25f17243552500bd6b5afb6b00e7be21bc7a2
/OpenGLisfun/OpenGLisfun/Mesh.h
9b2490c3be7e03e17d23d6db59ba57b230161975
[]
no_license
rveens/learnopengl
2efd3b53249feb1136d98d94d904e08915992e3b
67c04c61d70c23792c339692789c75b251f6d7c4
refs/heads/master
2020-04-06T07:10:38.561588
2016-08-25T10:59:25
2016-08-25T10:59:25
65,599,325
0
0
null
null
null
null
UTF-8
C++
false
false
677
h
#pragma once #include <glm/glm.hpp> #include <GL/glew.h> #include <iostream> #include <vector> #include <assimp/scene.h> #include "Shader.h" struct Vertex { glm::vec3 Position; glm::vec3 Normal; glm::vec2 TexCoords; }; struct Texture { GLuint id; std::string type; aiString path; }; class Mesh { public: /* Mesh Data */ std::vector<Vertex> vertices; std::vector<GLuint> indices; std::vector<Texture> textures; /* Functions */ Mesh(std::vector<Vertex> vertices, std::vector<GLuint> indices, std::vector<Texture> textures); virtual ~Mesh(); void Draw(GLuint program); private: /* Render data */ GLuint VAO, VBO, EBO; /* Functions */ void setupMesh(); };
129653390f100817bcd1f47a8eac418d392be7fe
b3091e900447227c611337e7f1d09113f1496282
/grafik/old/testing/stack.cpp
91f5f3171ebfdc97e3304caef0757f073e2139ed
[]
no_license
FinancialEngineerLab/documents
51285a6d13ea3a6a133f9b8af75782632ec46cf6
5ea97493d460dada421e7f04ad31a4d9419a44d1
refs/heads/master
2022-03-10T17:14:31.473383
2014-05-05T15:41:07
2014-05-05T15:41:07
null
0
0
null
null
null
null
UTF-8
C++
false
false
204
cpp
#include "stack.h" int main() { std::cout << "main -->" << std::endl; std::cout << "main <--" << std::endl; return 1; } void stack(); { } void push(int a); { } int pop(); { return 0; }
97fb67a0ea95399a11062daad433e3bdaaa2cb97
15f70e12f97c1098383a8a3b6d6ee13984bb79e7
/Classes/Battle/data/LQCastListInfoData.cpp
1a4625d992b01275a25650ecda1c644771616278
[]
no_license
Crasader/FightDemo
d02cb099a3684ef45ed13ecfb30f8e3248699e48
6d24ab80c5f745bc053efd687fcd0d984a607987
refs/heads/master
2021-02-19T09:47:01.498161
2016-04-13T03:16:38
2016-04-13T03:16:38
null
0
0
null
null
null
null
UTF-8
C++
false
false
516
cpp
// // LQCastListInfoData.cpp // SuperWarriors // //演员表数据文件 // Created by LequWorld Studio on 2016 // Copyright (c) 2013年 LequGame. All rights reserved. // #include "LQCastListInfoData.h" using namespace cocos2d; IMPLEMENT_CLASS(LQCastListInfoData) LQCastListInfoData::LQCastListInfoData():LQBaseData() { } LQCastListInfoData::~LQCastListInfoData() { //释放对象资源 }; const char* LQCastListInfoData::getAliasName() { return "CastListInfo"; };
[ "chenli@7ec0cbbf-2d8b-4450-83e2-257f523ed092" ]
chenli@7ec0cbbf-2d8b-4450-83e2-257f523ed092
96865a8619154c271697fd260017961ec5865df5
d6b4bdf418ae6ab89b721a79f198de812311c783
/cloudaudit/include/tencentcloud/cloudaudit/v20190319/model/ListAuditsRequest.h
87975a1e5001664fb4c3e32d7fc0d40dbb6af9b6
[ "Apache-2.0" ]
permissive
TencentCloud/tencentcloud-sdk-cpp-intl-en
d0781d461e84eb81775c2145bacae13084561c15
d403a6b1cf3456322bbdfb462b63e77b1e71f3dc
refs/heads/master
2023-08-21T12:29:54.125071
2023-08-21T01:12:39
2023-08-21T01:12:39
277,769,407
2
0
null
null
null
null
UTF-8
C++
false
false
1,513
h
/* * Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef TENCENTCLOUD_CLOUDAUDIT_V20190319_MODEL_LISTAUDITSREQUEST_H_ #define TENCENTCLOUD_CLOUDAUDIT_V20190319_MODEL_LISTAUDITSREQUEST_H_ #include <string> #include <vector> #include <map> #include <tencentcloud/core/AbstractModel.h> namespace TencentCloud { namespace Cloudaudit { namespace V20190319 { namespace Model { /** * ListAudits request structure. */ class ListAuditsRequest : public AbstractModel { public: ListAuditsRequest(); ~ListAuditsRequest() = default; std::string ToJsonString() const; private: }; } } } } #endif // !TENCENTCLOUD_CLOUDAUDIT_V20190319_MODEL_LISTAUDITSREQUEST_H_
b243cae7f22f4b9bc0670c8fd628c9fd4e6c692c
7fa844af70dd2b40b7c89b09c8147aef6b86bf0c
/src/lanarts/fov/impl/permissive-fov.cc
1a38fd5b4f25c13ee6d6fe6895160cc4ce7b3522
[ "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference" ]
permissive
ludamad/lanarts-engine
923f8b59227645eeed46f56c129e1161032c865e
fb2a2b784025ffc6e149e1de690a205eaf4b3171
refs/heads/master
2021-01-02T22:51:45.868886
2014-11-22T05:11:52
2014-11-22T05:11:52
19,651,704
1
0
null
null
null
null
UTF-8
C++
false
false
17,817
cc
// permissive-fov.cc /* Copyright (c) 2007, Jonathon Duerig. Licensed under the BSD license. See LICENSE.txt for details. */ #include <list> #include <iostream> #include <fstream> #include <algorithm> #include <string> #include "permissive-fov.h" using std::list; using std::max; using std::min; using std::string; #include "../fov.h" // Hacked in for Lanarts for performance reasons // TODO: See about moving to a more specialized impl static int isBlocked(short destX, short destY, void * context) { fov * typedContext = reinterpret_cast<fov *>(context); return typedContext->isBlocked(destX, destY); } static void visit(short destX, short destY, void * context) { fov * typedContext = reinterpret_cast<fov *>(context); typedContext->visit(destX, destY); } namespace { struct offsetT { public: offsetT(short newX = 0, short newY = 0) : x(newX) , y(newY) { } public: short x; short y; }; std::ostream & operator<<(std::ostream & stream, offsetT const & right) { stream << "(" << right.x << ", " << right.y << ")"; return stream; } struct fovStateT { offsetT source; permissiveMaskT * mask; isBlockedFunction __isBlocked; visitFunction __visit; void * context; offsetT quadrant; offsetT extent; }; struct lineT { lineT(offsetT newNear=offsetT(), offsetT newFar=offsetT()) : near(newNear) , far(newFar) { } bool isBelow(offsetT const & point) { return relativeSlope(point) > 0; } bool isBelowOrContains(offsetT const & point) { return relativeSlope(point) >= 0; } bool isAbove(offsetT const & point) { return relativeSlope(point) < 0; } bool isAboveOrContains(offsetT const & point) { return relativeSlope(point) <= 0; } bool doesContain(offsetT const & point) { return relativeSlope(point) == 0; } // negative if the line is above the point. // positive if the line is below the point. // 0 if the line is on the point. int relativeSlope(offsetT const & point) { return (far.y - near.y)*(far.x - point.x) - (far.y - point.y)*(far.x - near.x); } offsetT near; offsetT far; }; struct bumpT { bumpT() : parent(NULL) {} offsetT location; bumpT * parent; }; struct fieldT { fieldT() : steepBump(NULL), shallowBump(NULL) {} lineT steep; lineT shallow; bumpT * steepBump; bumpT * shallowBump; }; void visitSquare(fovStateT const * state, offsetT const & dest, list<fieldT>::iterator & currentField, list<bumpT> & steepBumps, list<bumpT> & shallowBumps, list<fieldT> & activeFields); list<fieldT>::iterator checkField(list<fieldT>::iterator currentField, list<fieldT> & activeFields); void addShallowBump(offsetT const & point, list<fieldT>::iterator currentField, list<bumpT> & steepBumps, list<bumpT> & shallowBumps); void addSteepBump(offsetT const & point, list<fieldT>::iterator currentField, list<bumpT> & steepBumps, list<bumpT> & shallowBumps); bool actIsBlocked(fovStateT const * state, offsetT const & pos); void calculateFovQuadrant(fovStateT const * state) { list<bumpT> steepBumps; list<bumpT> shallowBumps; // activeFields is sorted from shallow-to-steep. list<fieldT> activeFields; activeFields.push_back(fieldT()); activeFields.back().shallow.near = offsetT(0, 1); activeFields.back().shallow.far = offsetT(state->extent.x, 0); activeFields.back().steep.near = offsetT(1, 0); activeFields.back().steep.far = offsetT(0, state->extent.y); offsetT dest(0, 0); // Visit the source square exactly once (in quadrant 1). if (state->quadrant.x == 1 && state->quadrant.y == 1) { actIsBlocked(state, dest); } list<fieldT>::iterator currentField = activeFields.begin(); short i = 0; short j = 0; int maxI = state->extent.x + state->extent.y; // For each square outline for (i = 1; i <= maxI && ! activeFields.empty(); ++i) { int startJ = max(0, i - state->extent.x); int maxJ = min(i, state->extent.y); // Visit the nodes in the outline for (j = startJ; j <= maxJ && currentField != activeFields.end(); ++j) { dest.x = i-j; dest.y = j; visitSquare(state, dest, currentField, steepBumps, shallowBumps, activeFields); } currentField = activeFields.begin(); } } void visitSquare(fovStateT const * state, offsetT const & dest, list<fieldT>::iterator & currentField, list<bumpT> & steepBumps, list<bumpT> & shallowBumps, list<fieldT> & activeFields) { // The top-left and bottom-right corners of the destination square. offsetT topLeft(dest.x, dest.y + 1); offsetT bottomRight(dest.x + 1, dest.y); while (currentField != activeFields.end() && currentField->steep.isBelowOrContains(bottomRight)) { // case ABOVE // The square is in case 'above'. This means that it is ignored // for the currentField. But the steeper fields might need it. ++currentField; } if (currentField == activeFields.end()) { // The square was in case 'above' for all fields. This means that // we no longer care about it or any squares in its diagonal rank. return; } // Now we check for other cases. if (currentField->shallow.isAboveOrContains(topLeft)) { // case BELOW // The shallow line is above the extremity of the square, so that // square is ignored. return; } // The square is between the lines in some way. This means that we // need to visit it and determine whether it is blocked. bool isBlocked = actIsBlocked(state, dest); if (!isBlocked) { // We don't care what case might be left, because this square does // not obstruct. return; } if (currentField->shallow.isAbove(bottomRight) && currentField->steep.isBelow(topLeft)) { // case BLOCKING // Both lines intersect the square. This current field has ended. currentField = activeFields.erase(currentField); } else if (currentField->shallow.isAbove(bottomRight)) { // case SHALLOW BUMP // The square intersects only the shallow line. addShallowBump(topLeft, currentField, steepBumps, shallowBumps); currentField = checkField(currentField, activeFields); } else if (currentField->steep.isBelow(topLeft)) { // case STEEP BUMP // The square intersects only the steep line. addSteepBump(bottomRight, currentField, steepBumps, shallowBumps); currentField = checkField(currentField, activeFields); } else { // case BETWEEN // The square intersects neither line. We need to split into two fields. list<fieldT>::iterator steeperField = currentField; list<fieldT>::iterator shallowerField = activeFields.insert(currentField, *currentField); addSteepBump(bottomRight, shallowerField, steepBumps, shallowBumps); checkField(shallowerField, activeFields); addShallowBump(topLeft, steeperField, steepBumps, shallowBumps); currentField = checkField(steeperField, activeFields); } } list<fieldT>::iterator checkField(list<fieldT>::iterator currentField, list<fieldT> & activeFields) { list<fieldT>::iterator result = currentField; // If the two slopes are colinear, and if they pass through either // extremity, remove the field of view. if (currentField->shallow.doesContain(currentField->steep.near) && currentField->shallow.doesContain(currentField->steep.far) && (currentField->shallow.doesContain(offsetT(0, 1)) || currentField->shallow.doesContain(offsetT(1, 0)))) { result = activeFields.erase(currentField); } return result; } void addShallowBump(offsetT const & point, list<fieldT>::iterator currentField, list<bumpT> & steepBumps, list<bumpT> & shallowBumps) { // First, the far point of shallow is set to the new point. currentField->shallow.far = point; // Second, we need to add the new bump to the shallow bump list for // future steep bump handling. shallowBumps.push_back(bumpT()); shallowBumps.back().location = point; shallowBumps.back().parent = currentField->shallowBump; currentField->shallowBump = & shallowBumps.back(); // Now we have too look through the list of steep bumps and see if // any of them are below the line. // If there are, we need to replace near point too. bumpT * currentBump = currentField->steepBump; while (currentBump != NULL) { if (currentField->shallow.isAbove(currentBump->location)) { currentField->shallow.near = currentBump->location; } currentBump = currentBump->parent; } } void addSteepBump(offsetT const & point, list<fieldT>::iterator currentField, list<bumpT> & steepBumps, list<bumpT> & shallowBumps) { currentField->steep.far = point; steepBumps.push_back(bumpT()); steepBumps.back().location = point; steepBumps.back().parent = currentField->steepBump; currentField->steepBump = & steepBumps.back(); // Now look through the list of shallow bumps and see if any of them // are below the line. bumpT * currentBump = currentField->shallowBump; while (currentBump != NULL) { if (currentField->steep.isBelow(currentBump->location)) { currentField->steep.near = currentBump->location; } currentBump = currentBump->parent; } } bool actIsBlocked(fovStateT const * state, offsetT const & pos) { offsetT adjustedPos(pos.x*state->quadrant.x + state->source.x, pos.y*state->quadrant.y + state->source.y); bool result = isBlocked(adjustedPos.x, adjustedPos.y, state->context) == 1; if ((state->quadrant.x * state->quadrant.y == 1 && pos.x == 0 && pos.y != 0) || (state->quadrant.x * state->quadrant.y == -1 && pos.y == 0 && pos.x != 0) || doesPermissiveVisit(state->mask, pos.x*state->quadrant.x, pos.y*state->quadrant.y) == 0) { return result; } else { visit(adjustedPos.x, adjustedPos.y, state->context); return result; } } } void permissiveSquareFov(short sourceX, short sourceY, int inRadius, isBlockedFunction __isBlocked, visitFunction __visit, void * context) { int radius = max(inRadius, 0); permissiveMaskT mask; mask.north = radius; mask.south = radius; mask.east = radius; mask.west = radius; mask.width = 2*radius + 1; mask.height = 2*radius + 1; mask.mask = NULL; permissiveFov(sourceX, sourceY, &mask, __isBlocked, __visit, context); } void permissiveFov(short sourceX, short sourceY, permissiveMaskT * mask, isBlockedFunction __isBlocked, visitFunction __visit, void * context) { fovStateT state; state.source = offsetT(sourceX, sourceY); state.mask = mask; state.__isBlocked = __isBlocked; state.__visit = __visit; state.context = context; static const int quadrantCount = 4; static const offsetT quadrants[quadrantCount] = {offsetT(1, 1), offsetT(-1, 1), offsetT(-1, -1), offsetT(1, -1)}; offsetT extents[quadrantCount] = {offsetT(mask->east, mask->north), offsetT(mask->west, mask->north), offsetT(mask->west, mask->south), offsetT(mask->east, mask->south)}; int quadrantIndex = 0; for (; quadrantIndex < quadrantCount; ++quadrantIndex) { state.quadrant = quadrants[quadrantIndex]; state.extent = extents[quadrantIndex]; calculateFovQuadrant(&state); } } namespace { static const int BITS_PER_INT = sizeof(int)*8; #define GET_INT(x,y) (((x)+(y)*mask->width)/BITS_PER_INT) #define GET_BIT(x,y) (((x)+(y)*mask->width)%BITS_PER_INT) unsigned int * allocateMask(int width, int height) { int cellCount = width * height; int intCount = cellCount / BITS_PER_INT; if (cellCount % BITS_PER_INT != 0) { ++intCount; } return new unsigned int[intCount]; } } permissiveErrorT initPermissiveMask(permissiveMaskT * mask, int north, int south, int east, int west) { permissiveErrorT result = PERMISSIVE_NO_FAILURE; mask->north = max(north, 0); mask->south = max(south, 0); mask->east = max(east, 0); mask->west = max(west, 0); mask->width = mask->west + 1 + mask->east; mask->height = mask->south + 1 + mask->north; mask->mask = allocateMask(mask->width, mask->height); if (mask->mask == NULL) { result = PERMISSIVE_OUT_OF_MEMORY; } return result; } permissiveErrorT loadPermissiveMask(permissiveMaskT * mask, char const * fileName) { list<string> input; size_t maxLineSize = 1; std::ifstream file(fileName, std::ios::in); if (!file) { return PERMISSIVE_FAILED_TO_OPEN_FILE; } permissiveErrorT result = PERMISSIVE_NO_FAILURE; string line; getline(file, line); while (file) { maxLineSize = max(maxLineSize, line.size()); input.push_front(line); getline(file, line); } mask->width = static_cast<int>(maxLineSize); mask->height = static_cast<int>(input.size()); mask->mask = allocateMask(mask->width, mask->height); // TODO: Out of memory list<string>::iterator inputPos = input.begin(); unsigned int * intPos = mask->mask; int bitPos = 0; for (int i = 0; i < mask->height; ++i, ++inputPos) { for (int j = 0; j < mask->width; ++j) { char current = '#'; if (j < static_cast<int>(inputPos->size())) { current = (*inputPos)[j]; } int bit = 1; // TODO: Enforce input restrictions. switch (current) { case '#': bit = 0; break; case '!': bit = 0; // Deliberate fall-through. case '@': // Bit is already set properly. mask->south = i; mask->west = j; mask->north = mask->height - 1 - mask->south; mask->east = mask->width - 1 - mask->west; break; case '.': default: // bit is already 1 break; } if (bit == 1) { *intPos |= 0x1 << bitPos; } else { *intPos &= ~(0x1 << bitPos); } ++bitPos; if (bitPos == BITS_PER_INT) { bitPos = 0; ++intPos; } } } return result; } void cleanupPermissiveMask(permissiveMaskT * mask) { delete [] mask->mask; mask->mask = NULL; } permissiveErrorT savePermissiveMask(permissiveMaskT * mask, char const * fileName) { permissiveErrorT result = PERMISSIVE_NO_FAILURE; std::ofstream file(fileName, std::ios::out | std::ios::trunc); if (!file) { result = PERMISSIVE_FAILED_TO_OPEN_FILE; } else { for (int y = - mask->south; y <= mask->north && file; ++y) { for (int x = - mask->west; x <= mask->east && file; ++x) { if (x == 0 && y == 0) { if (doesPermissiveVisit(mask, x, y)) { file << '@'; } else { file << '!'; } } else { if (doesPermissiveVisit(mask, x, y)) { file << '.'; } else { file << '#'; } } } file << '\n'; } if (!file) { result = PERMISSIVE_SAVE_WRITE_FAILED; } } return result; } void setPermissiveVisit(permissiveMaskT * mask, int x, int y) { if (mask->mask != NULL) { int index = GET_INT(x + mask->west, y + mask->south); int shift = GET_BIT(x + mask->west, y + mask->south); mask->mask[index] |= 0x1 << shift; } } void clearPermissiveVisit(permissiveMaskT * mask, int x, int y) { if (mask->mask != NULL) { int index = GET_INT(x + mask->west, y + mask->south); int shift = GET_BIT(x + mask->west, y + mask->south); mask->mask[index] &= ~(0x1 << shift); } } int doesPermissiveVisit(permissiveMaskT * mask, int x, int y) { if (mask->mask == NULL) { return 1; } else { int index = GET_INT(x + mask->west, y + mask->south); int shift = GET_BIT(x + mask->west, y + mask->south); return (mask->mask[index] >> shift) & 0x1; } }
13e37be613bc168c62c3f767706f58ee79e65e53
42284951bf0c1aedff7118499b45268753ba83c1
/Electrical/Transistor/code/unused/RadioBuggyMega2013/steering.ino
a9a2adcf81533b7bd62d4e38ba8a574a3e782b99
[]
no_license
CMU-Robotics-Club/RoboBuggy
f0294dca561f9dddd548cbb2c6cbe3dbb7ab7d39
9465dbfe6afab721145a215b1f5e2934d3a7704f
refs/heads/master
2021-01-24T06:27:11.019759
2019-03-29T22:23:45
2019-03-29T22:23:45
23,744,385
26
7
null
2020-10-12T19:44:33
2014-09-06T20:20:03
Java
UTF-8
C++
false
false
704
ino
/** * @file steering.c * @brief Steering! * @author Haley Dalzell * @author Zach Dawson * @author Matt Sebek */ #include <Servo.h> Servo steer; // create servo object to control a servo static int s_angle; static int s_left, s_center, s_right; void steering_init(int SERVO_PIN, int left, int center, int right) { steer.attach(SERVO_PIN); // attaches the servo on pin 9 to the servo object s_left = left; s_center = center; s_right = right; } void steering_set(int servo_value) { //s_angle = servo_value; if(servo_value < s_left) { s_angle = s_left; } else if(servo_value > s_right) { s_angle = s_right; } else { s_angle = servo_value; } steer.write(s_angle); }
e7359171091b2464281f6e4153da843e50238c7a
698162d6d01f6eae3dba2d6ae6e100cb5dd2fef4
/Source/ExampleGame/MyPlayerState.cpp
819debd623af9f8ff0b14741213319b85a4bc404
[ "Apache-2.0" ]
permissive
Sparkness/ExampleGame
f7cffc5a56ffdfe608ac82aece5b8bb806b4bf13
b05364987163255ad54334420852ccbb7bff87dd
refs/heads/master
2023-06-25T22:58:03.184345
2021-07-23T22:10:27
2021-07-23T22:10:27
null
0
0
null
null
null
null
UTF-8
C++
false
false
25,054
cpp
// Fill out your copyright notice in the Description page of Project Settings. #include "MyPlayerState.h" #include "ProMMO.h" #include "Net/UnrealNetwork.h" #include "Runtime/ImageWrapper/Public/IImageWrapper.h" #include "Runtime/ImageWrapper/Public/IImageWrapperModule.h" #include "DDSLoader.h" #include "DynamicTextureStaticMeshActor.h" #include "UEtopiaPersistCharacter.h" #include "MyPlayerController.h" #include "MyGameInstance.h" // https://forums.unrealengine.com/community/community-content-tools-and-tutorials/116578-comprehensive-gameplayabilities-analysis-series FName AMyPlayerState::AbilitySystemName(TEXT("AbilitySystem")); AMyPlayerState::AMyPlayerState(const FObjectInitializer& ObjectInitializer) : Super(ObjectInitializer) { UE_LOG(LogTemp, Log, TEXT("[UETOPIA] [AMyPlayerState] Init ")); // https://forums.unrealengine.com/community/community-content-tools-and-tutorials/116578-comprehensive-gameplayabilities-analysis-series AbilitySystem = CreateDefaultSubobject<UMyAbilitySystemComponent>(AMyPlayerState::AbilitySystemName); // //ActionRPG also says it should be explicitly replicated AbilitySystem->SetIsReplicated(true); AttributeSet = CreateDefaultSubobject<UMyAttributeSet>(TEXT("AttributeSet")); // Prevent pickups on all maps unless specifically authorized allowPickup = false; AbilitySlotsPerRow = 6; } void AMyPlayerState::BeginPlay() { UE_LOG(LogTemp, Log, TEXT("[UETOPIA] [AMyPlayerState] BeginPlay")); Super::BeginPlay(); // Bind to delegates inside ability system AbilitySystem->OnActiveGameplayEffectAddedDelegateToSelf.AddUObject(this, &AMyPlayerState::OnGameplayEffectAppliedToSelf); AActor* thisOwner = GetOwner(); // Only on the server, grant cached abilities if (IsRunningDedicatedServer()) { AMyPlayerController* playerController = Cast<AMyPlayerController>(thisOwner); if (playerController) { UE_LOG(LogTemp, Log, TEXT("[UETOPIA] [AMyPlayerState] BeginPlay got playerController")); // This does not work because at this stage, the Character does not have access to the controller //playerController->GrantCachedAbilities(); } } // On the client only - bind the ability system // Retry if it fails if (!IsRunningDedicatedServer()) { AUEtopiaPersistCharacter* playerChar = Cast<AUEtopiaPersistCharacter>(thisOwner); if (playerChar) { UE_LOG(LogTemp, Log, TEXT("[UETOPIA] [AMyPlayerState] BeginPlay - found playerChar")); AbilitySystem->BindAbilityActivationToInputComponent(playerChar->InputComponent, FGameplayAbilityInputBinds("ConfirmInput", "CancelInput", "AbilityInput")); } else { UE_LOG(LogTemp, Log, TEXT("[UETOPIA] [AMyPlayerState] BeginPlay - DID NOT FIND playerChar->InputComponent")); AttemptBindInputToASCDel.BindUFunction(this, FName("AttemptBindInputToASC"), true); GetWorld()->GetTimerManager().SetTimer(AttemptBindInputToASCHandle, AttemptBindInputToASCDel, 1.f, false); } } } void AMyPlayerState::ClientInitialize(AController* C) { UE_LOG(LogTemp, Log, TEXT("[UETOPIA] [AMyPlayerState] ClientInitialize")); Super::ClientInitialize(C); SetOwner(C); // Testing putting this is begin play instead /* AUEtopiaPersistCharacter* playerChar = Cast<AUEtopiaPersistCharacter>(C->GetPawn()); if (playerChar) { UE_LOG(LogTemp, Log, TEXT("[UETOPIA] [AMyPlayerState] ClientInitialize - found playerChar")); AbilitySystem->BindAbilityActivationToInputComponent(playerChar->InputComponent, FGameplayAbilityInputBinds("ConfirmInput", "CancelInput", "AbilityInput")); } else { UE_LOG(LogTemp, Log, TEXT("[UETOPIA] [AMyPlayerState] ClientInitialize - DID NOT FIND playerChar->InputComponent")); AttemptBindInputToASCDel.BindUFunction(this, FName("AttemptBindInputToASC"), true); GetWorld()->GetTimerManager().SetTimer(AttemptBindInputToASCHandle, AttemptBindInputToASCDel, 1.f, false); } */ // Abilities are still not working after map travel // testing AMyPlayerController* playerController = Cast<AMyPlayerController>(C); if (playerController) { UE_LOG(LogTemp, Log, TEXT("[UETOPIA] [AMyPlayerState] ClientInitialize - found playerController")); playerController->GrantCachedAbilities(); } AUEtopiaPersistCharacter* playerChar = Cast<AUEtopiaPersistCharacter>(C->GetPawn()); if (playerChar) { UE_LOG(LogTemp, Log, TEXT("[UETOPIA] [AMyPlayerState] ClientInitialize - found playerChar")); playerChar->RemapAbilities(); } } void AMyPlayerState::OnGameplayEffectAppliedToSelf(class UAbilitySystemComponent* FromInstigator, const FGameplayEffectSpec& Spec, FActiveGameplayEffectHandle Handle) { UE_LOG(LogTemp, Log, TEXT("[UETOPIA]AMyPlayerState::OnGameplayEffectAppliedToSelf")); // RPC to client to trigger the delegate OnGameplayEffectsChanged(); } void AMyPlayerState::OnGameplayEffectRemoved(FActiveGameplayEffectHandle Handle) { UE_LOG(LogTemp, Log, TEXT("[UETOPIA]AMyPlayerState::OnGameplayEffectRemoved")); // RPC to client to trigger the delegate OnGameplayEffectsChanged(); } void AMyPlayerState::OnGameplayEffectsChanged_Implementation() { UE_LOG(LogTemp, Log, TEXT("[UETOPIA]AMyPlayerState::OnGameplayEffectsChanged_Implementation")); // just trigger the delegate OnGameplayEffectChangedDelegate.Broadcast(); } void AMyPlayerState::TriggerShowMatchResults_Implementation() { UE_LOG(LogTemp, Log, TEXT("[UETOPIA]AMyPlayerState::TriggerShowMatchResults_Implementation")); // just trigger the delegate FOnShowMatchResultsDelegate.Broadcast(); } void AMyPlayerState::OnRep_OnAbilityInterfaceChange_Implementation() { UE_LOG(LogTemp, Log, TEXT("[UETOPIA]AMyPlayerState::OnRep_OnAbilityInterfaceChange")); AUEtopiaPersistCharacter* playerChar = Cast<AUEtopiaPersistCharacter>(GetPawn()); if (playerChar) { UE_LOG(LogTemp, Log, TEXT("[UETOPIA]AMyPlayerState::OnRep_OnAbilityInterfaceChange got playerChar")); playerChar->RemapAbilities(); } OnAbilityInterfaceChanged.Broadcast(); } void AMyPlayerState::AttemptBindInputToASC() { UE_LOG(LogTemp, Log, TEXT("[UETOPIA]AMyPlayerState::AttemptBindInputToASC")); APawn* thisPawn = GetPawn(); if (thisPawn) { UE_LOG(LogTemp, Log, TEXT("[UETOPIA]AMyPlayerState::AttemptBindInputToASC got pawn")); if (thisPawn->IsLocallyControlled()) { UE_LOG(LogTemp, Log, TEXT("[UETOPIA]AMyPlayerState::AttemptBindInputToASC pawn is locally controlled")); AUEtopiaPersistCharacter* playerChar = Cast<AUEtopiaPersistCharacter>(thisPawn); if (playerChar) { UE_LOG(LogTemp, Log, TEXT("[UETOPIA]AMyPlayerState::AttemptBindInputToASC got player char")); if (playerChar->InputComponent) { UE_LOG(LogTemp, Log, TEXT("[UETOPIA] [AMyPlayerState] AttemptBindInputToASC - found playerChar->InputComponent")); AbilitySystem->BindAbilityActivationToInputComponent(playerChar->InputComponent, FGameplayAbilityInputBinds("ConfirmInput", "CancelInput", "AbilityInput")); return; } else { UE_LOG(LogTemp, Log, TEXT("[UETOPIA] [AMyPlayerState] AttemptBindInputToASC - DID NOT FIND playerChar->InputComponent")); } } } else { // not local return; } } UE_LOG(LogTemp, Log, TEXT("[UETOPIA] [AMyPlayerState] AttemptBindInputToASC - FAIL - Retrying")); AttemptBindInputToASCDel.BindUFunction(this, FName("AttemptBindInputToASC"), true); GetWorld()->GetTimerManager().SetTimer(AttemptBindInputToASCHandle, AttemptBindInputToASCDel, 1.f, false); } void AMyPlayerState::OnRep_OnCustomTextureChange_Implementation() { UE_LOG(LogTemp, Log, TEXT("[UETOPIA] [AMyPlayerController] OnRep_OnCustomTextureChange_Implementation.")); // First check to see if they are already loaded. // Since we're in player state, this should trigger on travel from lobby to game levels. // WE don't need to actually load them again. We just need to apply them. if (customTextures.Num() != LoadedTextures.Num()) { UE_LOG(LogTemp, Log, TEXT("[UETOPIA] [AMyPlayerController] OnRep_OnCustomTextureChange_Implementation. customTextures.Num != LoadedTextures.Num")); // loop over the custom textures // Make sure valid filename was specified for (int32 b = 0; b < customTextures.Num(); b++) { if (customTextures[b].IsEmpty() || customTextures[b].Contains(TEXT(" "))) { UE_LOG(LogTemp, Log, TEXT("[UETOPIA] [AMyPlayerController] OnRep_OnCustomTextureChange_Implementation. INVALID FILENAME")); customTextures[b] = "https://apitest-dot-ue4topia.appspot.com/img/groups/M_Banners_BaseColor.png"; } // Create the Http request and add to pending request list FHttpModule* Http = &FHttpModule::Get(); if (!Http) { return; } if (!Http->IsHttpEnabled()) { return; } // this changed in 4.26 TSharedRef < IHttpRequest, ESPMode::ThreadSafe > Request = Http->CreateRequest(); Request->SetVerb("GET"); Request->SetURL(customTextures[b]); Request->SetHeader("User-Agent", "UETOPIA_UE4_API_CLIENT/1.0"); Request->SetHeader("Content-Type", "application/x-www-form-urlencoded"); //TSharedRef<class IHttpRequest> HttpRequest = FHttpModule::Get().CreateRequest(); //FileRequests.Add(&HttpRequest.Get(), FPendingFileRequest(FileName)); //Request->OnProcessRequestComplete().BindUObject(this, delegateCallback); Request->OnProcessRequestComplete().BindUObject(this, &AMyPlayerState::ReadCustomTexture_HttpRequestComplete); //HttpRequest->SetURL(customTexture); //HttpRequest->SetVerb(TEXT("GET")); Request->ProcessRequest(); } } return; } void AMyPlayerState::ReadCustomTexture_HttpRequestComplete(FHttpRequestPtr HttpRequest, FHttpResponsePtr HttpResponse, bool bSucceeded) { UE_LOG(LogTemp, Log, TEXT("[UETOPIA] [AMyPlayerController] ReadCustomTexture_HttpRequestComplete.")); if (!HttpRequest.IsValid()) { UE_LOG(LogTemp, Log, TEXT("[UETOPIA] [AMyPlayerController] ReadCustomTexture_HttpRequestComplete REQUEST INVALID.")); return; } /* const FPendingFileRequest* PendingRequest = FileRequests.Find(HttpRequest.Get()); if (PendingRequest == nullptr) { return; } */ bool bResult = false; FString ResponseStr, ErrorStr; /* // Cloud file being operated on { FCloudFile* CloudFile = GetCloudFile(PendingRequest->FileName, true); CloudFile->AsyncState = EOnlineAsyncTaskState::Failed; CloudFile->Data.Empty(); } */ if (bSucceeded && HttpResponse.IsValid()) { UE_LOG(LogTemp, Log, TEXT("[UETOPIA] [AMyPlayerController] ReadCustomTexture_HttpRequestComplete. bSucceeded and IsValid ")); if (EHttpResponseCodes::IsOk(HttpResponse->GetResponseCode())) { UE_LOG(LogTemp, Log, TEXT("ReadFile request complete. url=%s code=%d"), *HttpRequest->GetURL(), HttpResponse->GetResponseCode()); // https://answers.unrealengine.com/questions/75929/is-it-possible-to-load-bitmap-or-jpg-files-at-runt.html // update the memory copy of the file with data that was just downloaded //FCloudFile* CloudFile = GetCloudFile(PendingRequest->FileName, true); // only tracking a single file.... // const FString& InFileName const FString& CloudFileTitle = "GroupTexture"; FCloudFile CloudFile = FCloudFile(CloudFileTitle); CloudFile.FileName = CloudFileTitle; CloudFile.AsyncState = EOnlineAsyncTaskState::Done; CloudFile.Data = HttpResponse->GetContent(); // cache to disk on successful download SaveCloudFileToDisk(CloudFile.FileName, CloudFile.Data); IImageWrapperModule& ImageWrapperModule = FModuleManager::LoadModuleChecked<IImageWrapperModule>(FName("ImageWrapper")); // Note: PNG format. Other formats are supported TSharedPtr<IImageWrapper> ImageWrapper = ImageWrapperModule.CreateImageWrapper(EImageFormat::PNG); //FString TexturePath = FPaths::GameContentDir() + TEXT("../Saved/Cloud/") + CloudFileTitle; FString TexturePath = FPaths::CloudDir() + CloudFileTitle; UE_LOG(LogTemp, Warning, TEXT("[UETOPIA] [AMyPlayerController] ReadCustomTexture_HttpRequestComplete. TexturePath: %s"), *TexturePath); TArray<uint8> FileData; if (FFileHelper::LoadFileToArray(FileData, *TexturePath)) { UE_LOG(LogTemp, Log, TEXT("[UETOPIA] [AMyPlayerController] ReadCustomTexture_HttpRequestComplete. LoadFileToArray ")); if (ImageWrapper.IsValid() && ImageWrapper->SetCompressed(FileData.GetData(), FileData.Num())) { UE_LOG(LogTemp, Log, TEXT("[UETOPIA] [AMyPlayerController] ReadCustomTexture_HttpRequestComplete. ImageWrapper->SetCompressed ")); //changed in 4.25 // const TArray<uint8>* UncompressedBGRA = NULL; TArray<uint8> UncompressedBGRA; if (ImageWrapper->GetRaw(ERGBFormat::BGRA, 8, UncompressedBGRA)) { UE_LOG(LogTemp, Log, TEXT("[UETOPIA] [AMyPlayerController] ReadCustomTexture_HttpRequestComplete. ImageWrapper->GetRaw ")); int32 LoadedTextureIndex; LoadedTextureIndex = LoadedTextures.Add(UTexture2D::CreateTransient(ImageWrapper->GetWidth(), ImageWrapper->GetHeight(), PF_B8G8R8A8)); // Changed in 4.24 //LoadedTextures[LoadedTextureIndex]->PlatformData->NumSlices = 1; LoadedTextures[LoadedTextureIndex]->PlatformData->SetNumSlices(1); LoadedTextures[LoadedTextureIndex]->NeverStream = true; void* TextureData = LoadedTextures[LoadedTextureIndex]->PlatformData->Mips[0].BulkData.Lock(LOCK_READ_WRITE); //changed in 4.25 //FMemory::Memcpy(TextureData, UncompressedBGRA->GetData(), UncompressedBGRA->Num()); FMemory::Memcpy(TextureData, UncompressedBGRA.GetData(), UncompressedBGRA.Num()); LoadedTextures[LoadedTextureIndex]->PlatformData->Mips[0].BulkData.Unlock(); LoadedTextures[LoadedTextureIndex]->UpdateResource(); } } // make sure all of the textures are loaded first. if (customTextures.Num() == LoadedTextures.Num()) { UE_LOG(LogTemp, Log, TEXT("[UETOPIA] [AMyPlayerController] OnRep_OnCustomTextureChange_Implementation. customTextures.Num == LoadedTextures.Num")); LoadTexturesOntoActors(); } } bResult = true; } else { ErrorStr = FString::Printf(TEXT("Invalid response. code=%d error=%s"), HttpResponse->GetResponseCode(), *HttpResponse->GetContentAsString()); UE_LOG(LogTemp, Log, TEXT("Invalid response. code=%d error=%sd"), HttpResponse->GetResponseCode(), *HttpRequest->GetURL()); } } else { ErrorStr = TEXT("No response"); } if (!ErrorStr.IsEmpty()) { UE_LOG(LogTemp, Warning, TEXT("ReadFile request failed. %s"), *ErrorStr); } } void AMyPlayerState::LoadTexturesOntoActors_Implementation() { UE_LOG(LogTemp, Log, TEXT("[UETOPIA] [AMyPlayerController] LoadTexturesOntoActors_Implementation.")); // now assign the textures to all of the banners // we want to loop over the actors first, // and loop over the textures inside. // Actor1 - Texture1 // Actor2 - Texture2 // Actor3 - Texture1 // Actor4 - Texture2 // ActorIndex % len(textures) = TextureIndex // I think... int32 ActorIndex = 0; int32 TextureIndex = 0; TActorIterator< ADynamicTextureStaticMeshActor > AllActorsItr = TActorIterator< ADynamicTextureStaticMeshActor >(GetWorld()); //While not reached end (overloaded bool operator) while (AllActorsItr) { UE_LOG(LogTemp, Log, TEXT("[UETOPIA] [AMyPlayerController] ReadCustomTexture_HttpRequestComplete. Found ADynamicTextureStaticMeshActor ")); if (AllActorsItr->MaterialInstance->IsValidLowLevel()) { UE_LOG(LogTemp, Log, TEXT("[UETOPIA] [AMyPlayerController] ReadCustomTexture_HttpRequestComplete. Material Instance IsValid ")); if (LoadedTextures.Num()) { TextureIndex = ActorIndex % LoadedTextures.Num(); UE_LOG(LogTemp, Warning, TEXT("[UETOPIA] [AMyPlayerState] LoadTexturesOntoActors_Implementation. TextureIndex: %d"), TextureIndex); AllActorsItr->MaterialInstance->SetTextureParameterValue(FName("BaseColor"), LoadedTextures[TextureIndex]); } } //next actor ++AllActorsItr; ++ActorIndex; } } void AMyPlayerState::SaveCloudFileToDisk(const FString& Filename, const TArray<uint8>& Data) { // save local disk copy as well FString LocalFilePath = GetLocalFilePath(Filename); bool bSavedLocal = FFileHelper::SaveArrayToFile(Data, *LocalFilePath); if (bSavedLocal) { UE_LOG(LogTemp, Verbose, TEXT("WriteUserFile request complete. Local file cache updated =%s"), *LocalFilePath); } else { UE_LOG(LogTemp, Warning, TEXT("WriteUserFile request complete. Local file cache failed to update =%s"), *LocalFilePath); } } void AMyPlayerState::OnRep_OnDropsChange() { UE_LOG(LogTemp, Log, TEXT("[UETOPIA] [AMyPlayerController] OnRep_OnDropsChange.")); AActor* ActorOwner = GetOwner(); AMyPlayerController* playerController = Cast<AMyPlayerController>(ActorOwner); if (playerController) { playerController->OnDropsChangedBP(); } } FString AMyPlayerState::GetLocalFilePath(const FString& FileName) { return FPaths::CloudDir() + FPaths::GetCleanFilename(FileName); } void AMyPlayerState::OnRep_OnInventoryChange() { UE_LOG(LogTemp, Log, TEXT("[UETOPIA]AMyPlayerState::OnRep_OnInventoryChange")); // MOved to Controller instead. Skipping the delegate for a direct call. AActor* ActorOwner = GetOwner(); AMyPlayerController* playerController = Cast<AMyPlayerController>(ActorOwner); if (playerController) { UE_LOG(LogTemp, Log, TEXT("[UETOPIA]AMyPlayerState::OnRep_OnInventoryChange Got Controller")); playerController->OnInventoryChangedBP(); } //FOnPlayerInventoryChangeDelegate.Broadcast(); } void AMyPlayerState::OnRep_OnEquipmentChange() { // This is running client side. UE_LOG(LogTemp, Log, TEXT("[UETOPIA]AMyPlayerState::OnRep_OnEquipmentChange")); // Attempting to do this without the MyEquipment copy inside of character. It's not getting found in gameInstance GetPlayerDataComplete for some reason // Another problem with this is that other players do not have access to the playerController, so they won't be able to respond to OnEquipmentChangedBP AActor* ActorOwner = GetOwner(); AMyPlayerController* playerController = Cast<AMyPlayerController>(ActorOwner); if (playerController) { // Trigger the bp native call. playerController->OnEquipmentChangedBP(); AUEtopiaPersistCharacter* playerChar = Cast<AUEtopiaPersistCharacter>(playerController->GetPawn()); if (playerChar) { UE_LOG(LogTemp, Log, TEXT("[UETOPIA] [AMyPlayerState] OnRep_OnEquipmentChange - found playerChar")); // TODO - Run the function to equip your items. } else { UE_LOG(LogTemp, Log, TEXT("[UETOPIA] [AMyPlayerState] OnRep_OnEquipmentChange - DID NOT FIND playerChar")); } } else { UE_LOG(LogTemp, Log, TEXT("[UETOPIA] [AMyPlayerState] OnRep_OnEquipmentChange - DID NOT FIND playerController")); } // Equipment can change the attributes too, so fire the delegate to refresh the UI // NOt sure why but inventory change effects are not getting caught by OnGameplayEffectAppliedToSelf OnGameplayEffectChangedDelegate.Broadcast(); // WE NEED THIS because of other players and non-local pawns. FOnPlayerEquipmentChangeDelegate.Broadcast(); } FMyGrantedAbility AMyPlayerState::GetGrantedAbilityByClassPath(FString classPathIn) { UE_LOG(LogTemp, Log, TEXT("[UETOPIA] [AMyPlayerState] GetGrantedAbilityByClassPath ")); // loop over GrantedAbilities for (int32 AIndex = 0; AIndex < GrantedAbilities.Num(); AIndex++) { if (classPathIn == GrantedAbilities[AIndex].classPath) { return GrantedAbilities[AIndex]; } } FMyGrantedAbility NotFoundAbility; return NotFoundAbility; } FMyGrantedAbility AMyPlayerState::RemoveGrantedAbilityByClassPath(FString classPathIn) { UE_LOG(LogTemp, Log, TEXT("[UETOPIA] [AMyPlayerState] GetGrantedAbilityByClassPath ")); // loop over GrantedAbilities for (int32 AIndex = 0; AIndex < GrantedAbilities.Num(); AIndex++) { if (classPathIn == GrantedAbilities[AIndex].classPath) { FMyGrantedAbility tempAbilityCopy = GrantedAbilities[AIndex]; GrantedAbilities.RemoveAt(AIndex); return tempAbilityCopy; } } FMyGrantedAbility NotFoundAbility; return NotFoundAbility; } void AMyPlayerState::OnRep_OnAbilitiesChange_Implementation() { UE_LOG(LogTemp, Log, TEXT("[UETOPIA]AMyPlayerState::OnRep_OnAbilitiesChange")); AActor* ActorOwner = GetOwner(); AMyPlayerController* playerController = Cast<AMyPlayerController>(ActorOwner); if (playerController) { UE_LOG(LogTemp, Log, TEXT("[UETOPIA]AMyPlayerState::OnRep_OnAbilitiesChange_Implementation Got Controller")); playerController->OnAbilitiesChanged.Broadcast(); } } void AMyPlayerState::OnRep_OnLootSettingsChange() { UE_LOG(LogTemp, Log, TEXT("[UETOPIA]AMyPlayerState::OnRep_OnLootSettingsChange")); AActor* ActorOwner = GetOwner(); AMyPlayerController* playerController = Cast<AMyPlayerController>(ActorOwner); if (playerController) { UE_LOG(LogTemp, Log, TEXT("[UETOPIA]AMyPlayerState::OnRep_OnLootSettingsChange Got Controller")); playerController->OnLootSettingsChangedBP(); } } void AMyPlayerState::GetLifetimeReplicatedProps(TArray< FLifetimeProperty > & OutLifetimeProps) const { Super::GetLifetimeReplicatedProps(OutLifetimeProps); DOREPLIFETIME(AMyPlayerState, playerTitle); DOREPLIFETIME_CONDITION(AMyPlayerState, serverTitle, COND_OwnerOnly); DOREPLIFETIME_CONDITION(AMyPlayerState, playerKeyId, COND_OwnerOnly); DOREPLIFETIME_CONDITION(AMyPlayerState, Currency, COND_OwnerOnly); //DOREPLIFETIME(AMyPlayerState, ServerPortalKeyIdsAuthorized); DOREPLIFETIME_CONDITION(AMyPlayerState, TeamId, COND_OwnerOnly); DOREPLIFETIME_CONDITION(AMyPlayerState, TeamPlayerIndex, COND_OwnerOnly); DOREPLIFETIME_CONDITION(AMyPlayerState, customTextures, COND_OwnerOnly); DOREPLIFETIME_CONDITION(AMyPlayerState, playerLoginFlowCompleted, COND_OwnerOnly); DOREPLIFETIME_CONDITION(AMyPlayerState, winningTeamTitle, COND_OwnerOnly); DOREPLIFETIME_CONDITION(AMyPlayerState, InventorySlots, COND_OwnerOnly); DOREPLIFETIME(AMyPlayerState, MyEquipment); DOREPLIFETIME(AMyPlayerState, Level); DOREPLIFETIME(AMyPlayerState, Experience); DOREPLIFETIME(AMyPlayerState, ExperienceThisLevel); DOREPLIFETIME(AMyPlayerState, MyAbilitySlots); DOREPLIFETIME(AMyPlayerState, AbilitySlotsPerRow); DOREPLIFETIME_CONDITION(AMyPlayerState, ServerLinksAuthorized, COND_OwnerOnly); DOREPLIFETIME_CONDITION(AMyPlayerState, allowPickup, COND_OwnerOnly); DOREPLIFETIME_CONDITION(AMyPlayerState, allowDrop, COND_OwnerOnly); DOREPLIFETIME_CONDITION(AMyPlayerState, MyDrops, COND_OwnerOnly); DOREPLIFETIME_CONDITION(AMyPlayerState, bCombatEnabled, COND_OwnerOnly); DOREPLIFETIME(AMyPlayerState, GrantedAbilities); DOREPLIFETIME_CONDITION(AMyPlayerState, bLootDropsEnabled, COND_OwnerOnly); DOREPLIFETIME_CONDITION(AMyPlayerState, bPartyLeaderCanChangeLootSettings, COND_OwnerOnly); DOREPLIFETIME_CONDITION(AMyPlayerState, LootThreshold, COND_OwnerOnly); DOREPLIFETIME_CONDITION(AMyPlayerState, LootSetting, COND_OwnerOnly); DOREPLIFETIME_CONDITION(AMyPlayerState, bCanBidOnLoot, COND_OwnerOnly); // replicate only to the owner DOREPLIFETIME_CONDITION(AMyPlayerState, gkpAmount, COND_OwnerOnly); DOREPLIFETIME_CONDITION(AMyPlayerState, gkpVettingThisRaid, COND_OwnerOnly); DOREPLIFETIME_CONDITION(AMyPlayerState, gkpVettingRemaining, COND_OwnerOnly); DOREPLIFETIME_CONDITION(AMyPlayerState, LootData, COND_OwnerOnly); DOREPLIFETIME_CONDITION(AMyPlayerState, PlayerTitles, COND_OwnerOnly); DOREPLIFETIME_CONDITION(AMyPlayerState, PlayerKeyIds, COND_OwnerOnly); } /* handles copying properties when we do seamless travel */ void AMyPlayerState::CopyProperties(class APlayerState* PlayerState) { Super::CopyProperties(PlayerState); AMyPlayerState* MyPlayerState = Cast<AMyPlayerState>(PlayerState); if (MyPlayerState) { MyPlayerState->playerTitle = playerTitle; MyPlayerState->playerKeyId = playerKeyId; MyPlayerState->Currency = Currency; MyPlayerState->TeamId = TeamId; MyPlayerState->TeamPlayerIndex = TeamPlayerIndex; MyPlayerState->customTextures = customTextures; MyPlayerState->playerLoginFlowCompleted = playerLoginFlowCompleted; MyPlayerState->CharacterSetup = CharacterSetup; MyPlayerState->Level = Level; MyPlayerState->Experience = Experience; MyPlayerState->ExperienceThisLevel = ExperienceThisLevel; MyPlayerState->winningTeamTitle = winningTeamTitle; MyPlayerState->InventorySlots = InventorySlots; MyPlayerState->MyEquipment = MyEquipment; MyPlayerState->MyAbilitySlots = MyAbilitySlots; MyPlayerState->AbilityCapacity = AbilityCapacity; MyPlayerState->AbilitySlotsPerRow = AbilitySlotsPerRow; MyPlayerState->allowPickup = allowPickup; MyPlayerState->allowDrop = allowDrop; MyPlayerState->MyDrops = MyDrops; MyPlayerState->bCombatEnabled = bCombatEnabled; MyPlayerState->GrantedAbilities = GrantedAbilities; MyPlayerState->CachedAbilities = CachedAbilities; MyPlayerState->bLootDropsEnabled = bLootDropsEnabled; MyPlayerState->bPartyLeaderCanChangeLootSettings = bPartyLeaderCanChangeLootSettings; MyPlayerState->LootThreshold = LootThreshold; MyPlayerState->LootSetting = LootSetting; MyPlayerState->bCanBidOnLoot = bCanBidOnLoot; MyPlayerState->gkpAmount = gkpAmount; MyPlayerState->gkpVettingThisRaid = gkpVettingThisRaid; MyPlayerState->gkpVettingRemaining = gkpVettingRemaining; } }
5d4d73cf21bc13549005df913a59b87281737a91
82d2738fb1e66ae2869eba15a32f3128e09b1f27
/Whisperwind/Whisperwind_Engine/include/Camera.h
4fb3d088ef4e2a9bd127158ceb15a0e470cdba51
[ "MIT" ]
permissive
harr999y/Whisperwind
a25326fa14c98f16ae8b451b3d96f64368c4d147
1171201f7cdcfe2e0043f305514dda66bf677f30
refs/heads/master
2021-06-01T11:34:50.562533
2020-06-25T11:50:30
2020-06-25T11:50:30
4,048,736
4
3
null
null
null
null
UTF-8
C++
false
false
2,813
h
/*------------------------------------------------------------------------- This source file is a part of Whisperwind.(GameEngine + GamePlay + GameTools) For the latest info, see http://lisuyong.com Copyright (c) 2012 Suyong Li ([email protected]) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE -------------------------------------------------------------------------*/ #ifndef _CAMERA_H_ #define _CAMERA_H_ #include "MathDefine.h" #include "EngineForwardDeclare.h" namespace Engine { enum MoveDirection { MD_LEFT = 1 << 1, MD_RIGHT = 1 << 2, MD_FORWARD = 1<<3, MD_BACK = 1 << 4 }; class WHISPERWIND_API Camera { public: Camera(Util::real nearCilp, Util::real farClip, const Util::UintPair & leftTop, const Util::UintPair & rightButtom); ~Camera() {} public: void move(Util::u_int moveDirection); void stopMove(Util::u_int moveDirection); void rotate(Util::real pitchAngle, Util::real yawAngle/*, Util::real zoom*/); void lookAt(FXMVECTOR destVec); void update(Util::time elapsedTime); void setPosition(FXMVECTOR pos) { XMStoreFloat3(&mPosition, pos); } XMVECTOR getPosition() { return XMLoadFloat3(&mPosition); } public: SET_GET_CONST_VALUE(Util::real, MoveSpeed); GET_VALUE(ViewportPtr, Viewport); GET_VALUE(FrustumPtr, Frustum); private: void doMove(Util::time deltaTime); private: XMFLOAT3 mPosition; XMFLOAT3 mLookAt; XMFLOAT3 mUpDirection; XMFLOAT4 mOrientation; XMFLOAT3 mPosLookDelta; bool mIsMoveDirection[4]; /// The sequence is forward,back,left,right. Util::real mMoveSpeed; Util::real mPitchRadians; Util::real mYawRadians; ViewportPtr mViewport; FrustumPtr mFrustum; bool mNeedUpdateView; private: DISALLOW_COPY_AND_ASSIGN(Camera); }; } #endif
2b51f553dbd6f883842bc90c62464f1ed3ef6269
9e749a1c009fe9d23613a8f90f6677801a0ae68b
/LeetCode/Minimum Depth of Binary Tree.cpp
844e25111162bf420a458bf5a5e57c5bc7e7e570
[]
no_license
ssliuyi/ACMCode
315c772573b94cf25748c45263f87bb1abc7ccab
3e3d34fa78c75f0af6f298855edd7288f81e7351
refs/heads/master
2016-09-05T12:56:49.334419
2014-05-17T02:46:09
2014-05-17T02:46:09
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,222
cpp
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: int minDepth(TreeNode *root) { // Note: The Solution object is instantiated only once and is reused by each test case. if(root == NULL) return 0; queue<TreeNode *> q; q.push(NULL); q.push(root); int level=0; while(q.size()>1) { if(q.front()==NULL) { level++; q.pop(); q.push(NULL); } else { if(q.front()->left == NULL && q.front()->right == NULL) return level; else { if(q.front()->left!=NULL) { q.push(q.front()->left); } if(q.front()->right!=NULL) { q.push(q.front()->right); } q.pop(); } } } } };
[ "liuyi@ENVY.(none)" ]
liuyi@ENVY.(none)
7ea0c37aa8c10d34eca0d0684b602f265713061a
d06a47ececf6b8439f06cdff4875d8ebd0fc5c7a
/388.文件的最长绝对路径.cpp
8f361b0d5dc442c18cff2fd3280e2b3eb33ded8a
[]
no_license
ColorlessBoy/leetcode
46b3ed12f3f3ec584b03f6e4f2639f671a92dc2b
04a6ef8bca8e372bf26415ad5143d43ffcc6ba20
refs/heads/master
2023-02-28T07:03:40.131953
2021-02-07T06:15:09
2021-02-07T06:15:09
283,479,605
0
0
null
null
null
null
UTF-8
C++
false
false
1,571
cpp
/* * @lc app=leetcode.cn id=388 lang=cpp * * [388] 文件的最长绝对路径 */ #include <bits/stdc++.h> using namespace std; // @lc code=start class Solution { public: int lengthLongestPath(string input) { vector<int> length = {-1};//第一层 bool isFile = false; int str_length = 0, deepth = 1, rst = 0; for(auto &ch: input) { if(ch == '\n') { if(isFile) { rst = max(rst, length[deepth-1] + 1 + str_length); } else { int tmp = length[deepth-1] + 1 + str_length; if(length.size() == deepth) { length.push_back(tmp); } else { length[deepth] = tmp; } } str_length = 0; deepth = 1; isFile = false; } else if(ch == '\t') { deepth++; } else if(ch == '.') { str_length++; isFile = true; } else { str_length++; } } if(isFile) { rst = max(rst, length[deepth-1] + 1 + str_length); } return rst; } }; // @lc code=end int main(int argc, char **argv) { Solution s; // string str = "dir\n\tsubdir1\n\tsubdir2\n\t\tfile.ext"; string str = "dir\n\t file.txt\n\tfile2.txt"; int rst = s.lengthLongestPath(str); return 0; }
caf9abb99fb099c9026f0fb5b094a6d0bea1e423
bc84c328d1cc2a318160d42ed1faa1961bdf1e87
/STL/stack/stack 类模板4/stacktp.cpp
1ff9bccd8f2124dd3de0ebf3bb6094f8e35e8c72
[ "MIT" ]
permissive
liangjisheng/C-Cpp
25d07580b5dd1ff364087c3cf8e13cebdc9280a5
8b33ba1f43580a7bdded8bb4ce3d92983ccedb81
refs/heads/master
2021-07-10T14:40:20.006051
2019-01-26T09:24:04
2019-01-26T09:24:04
136,299,205
7
2
null
null
null
null
UTF-8
C++
false
false
638
cpp
// tempparm.cpp -- template as parameters #include"iostream" #include"stacktp.h" template< template<class T> class Thing> class Crab { private: Thing<int> s1; Thing<double> s2; public: Crab() {} bool push(int a,double x) { return s1.push(a) && s2.push(x); } bool pop(int & a,double & x) { return s1.pop(a) && s2.pop(x); } }; int main() { using std::cout; using std::cin; using std::endl; Crab<Stack> ne; int ni; double nb; cout<<"Enter int double pairs(0 0 to end):"; while(cin>>ni>>nb && ni>0 && nb>0) { if(!ne.push(ni,nb)) break; } while(ne.pop(ni,nb)) cout<<ni<<","<<nb<<endl; cout<<"Bye!\n"; return 0; }
dabeca86aabb938cada23884fce9acb50cfd5c31
1890b475dc4e7b856f973252080814b14bb52d57
/aws_drive/aws/v7.1/Samples/netds/messagequeuing/mqapitst/RecvMDlg.h
40140d5c99ca9fe5e1e4597d464ac42747f01daa
[]
no_license
nfouka/InnoSetup5
065629007b00af7c14ae9b202011e12b46eea257
df39fc74995a6955d2d8ee12feed9cff9e5c37db
refs/heads/master
2020-04-20T02:51:58.072759
2019-01-31T21:53:45
2019-01-31T21:53:45
168,582,148
2
2
null
null
null
null
UTF-8
C++
false
false
1,972
h
// -------------------------------------------------------------------- // // Copyright (c) Microsoft Corporation. All rights reserved // // THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF // ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A // PARTICULAR PURPOSE. // // -------------------------------------------------------------------- // // RecvMDlg.h : header file // ///////////////////////////////////////////////////////////////////////////// // CReceiveMessageDialog dialog class CReceiveMessageDialog : public CDialog { // Construction public: CReceiveMessageDialog(CArray <ARRAYQ*, ARRAYQ*>*, CWnd* pParent = NULL); // standard constructor // Dialog Data //{{AFX_DATA(CReceiveMessageDialog) enum { IDD = IDD_RECEIVE_MESSAGE_DIALOG }; CComboBox m_PathNameCB; CString m_szPathName; int m_iTimeout; DWORD m_dwBodySize; //}}AFX_DATA /* pointer to the array with the strings for the combo box (Queues PathName). */ CArray <ARRAYQ*, ARRAYQ*>* m_pStrArray ; // Overrides // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CReceiveMessageDialog) protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support //}}AFX_VIRTUAL // Implementation protected: // Generated message map functions //{{AFX_MSG(CReceiveMessageDialog) virtual BOOL OnInitDialog(); //}}AFX_MSG DECLARE_MESSAGE_MAP() public: void GetPathName(TCHAR szPathName[BUFFERSIZE]) { ASSERT(szPathName != NULL); _tcsncpy_s(szPathName, BUFFERSIZE, m_szPathName, BUFFERSIZE-1); } DWORD GetTimeout() { if (m_iTimeout < 0) { m_iTimeout = INFINITE; } return (m_iTimeout); } DWORD GetBodySize() { if (m_dwBodySize == 0) { m_dwBodySize = BUFFERSIZE ; } return (m_dwBodySize) ; } };
[ "nadir.foukagmail.com" ]
nadir.foukagmail.com
7a18ac1b5922db845a84d80954e2ae18d61e88c5
ada5dc24bed029a1758bd83297567f6cd4b972a3
/StackLib/Stack.h
af83dcbf913cb4f1ef45ea244bf7557902994227
[]
no_license
DimaSilenko/3817061_Silenko_AllLabi
54749b27a4ad8e4a381757cf50d13abdd6eb0767
a58993d2571ab9a70af34f3a94f4c91dd83d5198
refs/heads/master
2020-03-30T12:41:43.238692
2019-05-09T11:34:19
2019-05-09T11:34:19
151,235,392
0
3
null
2019-05-12T20:00:46
2018-10-02T10:09:14
C++
UTF-8
C++
false
false
3,954
h
#pragma once #include <iostream> #include "ExceptionLib.h" using namespace std; template <class T> class TStack { protected: int length;// Длина стека T* elem;// Элементы стека int top;// Вершина стека public: TStack(int len = 0); TStack(TStack &st); virtual ~TStack(); void Put(T el); // Положить элемент T Top(); T Get();// Взять элемент int GetLength();// Получить длину стека bool IsFull();// Проверка на полноту bool IsEmpty();// Проверка на пустоту void PrintStack(); //Вывод стека на экран TStack& operator=(const TStack<T>& st); //Присваивание стека int operator==(const TStack<T>& st) const; //Проверка на равенство int operator!=(const TStack<T>& st) const; // Проверка на неравенство }; //--------------------------------------------------------------------------------------- template <class T> TStack<T>::TStack(int len) { if (len < 0) throw Exception("Error length"); else if (len == 0) { length = 0; elem = 0; top = 0; } else { elem = new T[len]; length = len; top = 0; } } //--------------------------------------------------------------------------------------- template <class T> TStack<T>::TStack(TStack<T> &st) { length = st.length; top = st.top; if (length == 0) elem = 0; else { elem = new T[length]; for (int i = 0; i < length; i++) elem[i] = st.elem[i]; } } //--------------------------------------------------------------------------------------- template <class T> TStack<T> :: ~TStack() { if (elem != 0) delete[] elem; top = 0; length = 0; } //--------------------------------------------------------------------------------------- template <class T> void TStack<T>::Put(T el) { if (IsFull()) throw Exception("Stack already Full"); else { elem[top] = el; top++; } } //--------------------------------------------------------------------------------------- template<class T> T TStack<T>::Top() { if (IsEmpty()) throw Exception("Stack already Empty"); else { return elem[top - 1]; } } //--------------------------------------------------------------------------------------- template <class T> T TStack<T>::Get() { if (IsEmpty()) throw Exception("Stack already Empty"); top--; return elem[top]; } //--------------------------------------------------------------------------------------- template <class T> int TStack<T>::GetLength() { return length; } //--------------------------------------------------------------------------------------- template <class T> bool TStack<T>::IsEmpty() { return (top == 0); } //--------------------------------------------------------------------------------------- template <class T> bool TStack<T>::IsFull() { return (top >= length); } //--------------------------------------------------------------------------------------- template <class T> void TStack<T>::PrintStack() { for (int i = top - 1; i >= 0; i--) cout << " " << elem[i]; } //--------------------------------------------------------------------------------------- template <class T> TStack<T>& TStack<T>::operator=(const TStack<T>& st) { if (this != &st) { delete[] elem; top = st.top; length = st.length; elem = new T[length]; for (int i = 0; i < length; i++) elem[i] = st.elem[i]; } return *this; } //--------------------------------------------------------------------------------------- template <class T> int TStack<T>::operator==(const TStack<T>& st) const { if (top != st.top) return 0; if (length != st.length) return 0; for (int i = 0; i < top; i++) if (elem[i] != st.elem[i]) return 0; return 1; } //--------------------------------------------------------------------------------------- template <class T> int TStack<T>::operator!=(const TStack<T>& st) const { return !(*this == st); }
bb8a14bb1301de448a38e5f68fff48b57540ae9c
fdfdbf1cdf09dcb9b49cd24197d9410a858b42b3
/QZXing/QZXing.cpp
9113bd1075b050a3ce721a483bd90e4482540b36
[ "Apache-2.0" ]
permissive
ilnuribat/scanning_barcode
3a4ba009b5e507b8f3a9efd7a35152dfa2bf99b4
5f2bd316c29ec888d984ae8ecc0b6c93f78b0c75
refs/heads/master
2021-07-13T22:51:11.356806
2017-10-18T22:51:06
2017-10-18T22:51:06
106,114,275
0
0
null
null
null
null
UTF-8
C++
false
false
14,990
cpp
#include "QZXing.h" #include <zxing/common/GlobalHistogramBinarizer.h> #include <zxing/Binarizer.h> #include <zxing/BinaryBitmap.h> #include <zxing/MultiFormatReader.h> #include <zxing/DecodeHints.h> #include "CameraImageWrapper.h" #include "ImageHandler.h" #include <QTime> #include <QUrl> #include <QFileInfo> #include <zxing/qrcode/encoder/Encoder.h> #include <zxing/qrcode/ErrorCorrectionLevel.h> #include <zxing/common/detector/WhiteRectangleDetector.h> #include <QColor> #if QT_VERSION >= 0x040700 && QT_VERSION < 0x050000 #include <QtDeclarative> #elif QT_VERSION >= 0x050000 #include <QtQml/qqml.h> #endif #ifdef QZXING_MULTIMEDIA #include "QZXingFilter.h" #endif //QZXING_MULTIMEDIA #ifdef QZXING_QML #include <QQmlEngine> #include <QQmlContext> #include <QQuickImageProvider> #include "QZXingImageProvider.h" #endif //QZXING_QML using namespace zxing; QZXing::QZXing(QObject *parent) : QObject(parent), tryHarder_(false) { decoder = new MultiFormatReader(); setDecoder(DecoderFormat_QR_CODE | DecoderFormat_DATA_MATRIX | DecoderFormat_UPC_E | DecoderFormat_UPC_A | DecoderFormat_UPC_EAN_EXTENSION | DecoderFormat_RSS_14 | DecoderFormat_RSS_EXPANDED | DecoderFormat_PDF_417 | DecoderFormat_MAXICODE | DecoderFormat_EAN_8 | DecoderFormat_EAN_13 | DecoderFormat_CODE_128 | DecoderFormat_CODE_93 | DecoderFormat_CODE_39 | DecoderFormat_CODABAR | DecoderFormat_ITF | DecoderFormat_Aztec); imageHandler = new ImageHandler(); } QZXing::~QZXing() { if (imageHandler) delete imageHandler; if (decoder) delete decoder; } QZXing::QZXing(QZXing::DecoderFormat decodeHints, QObject *parent) : QObject(parent) { decoder = new MultiFormatReader(); imageHandler = new ImageHandler(); setDecoder(decodeHints); } #ifdef QZXING_QML #if QT_VERSION >= 0x040700 void QZXing::registerQMLTypes() { qmlRegisterType<QZXing>("QZXing", 2, 3, "QZXing"); #ifdef QZXING_MULTIMEDIA qmlRegisterType<QZXingFilter>("QZXing", 2, 3, "QZXingFilter"); #endif //QZXING_MULTIMEDIA } #endif //QT_VERSION >= Qt 4.7 void QZXing::registerQMLTypes_() { qmlRegisterType<QZXing>("QZXing", 2, 3, "QZXing"); #ifdef QZXING_MULTIMEDIA qmlRegisterType<QZXingFilter>("QZXing", 2, 3, "QZXingFilter"); #endif //QZXING_MULTIMEDIA } #if QT_VERSION >= 0x050000 void QZXing::registerQMLImageProvider(QQmlEngine& engine) { engine.addImageProvider(QLatin1String("QZXing"), QZXingImageProvider::getInstance()); } #endif //QT_VERSION >= Qt 5.0 #endif //QZXING_QML void QZXing::setTryHarder(bool tryHarder) { tryHarder_ = tryHarder; } bool QZXing::getTryHarder() { return tryHarder_; } QString QZXing::decoderFormatToString(int fmt) { switch (fmt) { case DecoderFormat_Aztec: return "AZTEC"; case DecoderFormat_CODABAR: return "CODABAR"; case DecoderFormat_CODE_39: return "CODE_39"; case DecoderFormat_CODE_93: return "CODE_93"; case DecoderFormat_CODE_128: return "CODE_128"; case DecoderFormat_CODE_128_GS1: return "CODE_128_GS1"; case DecoderFormat_DATA_MATRIX: return "DATA_MATRIX"; case DecoderFormat_EAN_8: return "EAN_8"; case DecoderFormat_EAN_13: return "EAN_13"; case DecoderFormat_ITF: return "ITF"; case DecoderFormat_MAXICODE: return "MAXICODE"; case DecoderFormat_PDF_417: return "PDF_417"; case DecoderFormat_QR_CODE: return "QR_CODE"; case DecoderFormat_RSS_14: return "RSS_14"; case DecoderFormat_RSS_EXPANDED: return "RSS_EXPANDED"; case DecoderFormat_UPC_A: return "UPC_A"; case DecoderFormat_UPC_E: return "UPC_E"; case DecoderFormat_UPC_EAN_EXTENSION: return "UPC_EAN_EXTENSION"; } // switch return QString(); } QString QZXing::foundedFormat() const { return foundedFmt; } QString QZXing::charSet() const { return charSet_; } void QZXing::setDecoder(const uint &hint) { unsigned int newHints = 0; if(hint & DecoderFormat_Aztec) newHints |= DecodeHints::AZTEC_HINT; if(hint & DecoderFormat_CODABAR) newHints |= DecodeHints::CODABAR_HINT; if(hint & DecoderFormat_CODE_39) newHints |= DecodeHints::CODE_39_HINT; if(hint & DecoderFormat_CODE_93) newHints |= DecodeHints::CODE_93_HINT; if(hint & DecoderFormat_CODE_128) newHints |= DecodeHints::CODE_128_HINT; if(hint & DecoderFormat_DATA_MATRIX) newHints |= DecodeHints::DATA_MATRIX_HINT; if(hint & DecoderFormat_EAN_8) newHints |= DecodeHints::EAN_8_HINT; if(hint & DecoderFormat_EAN_13) newHints |= DecodeHints::EAN_13_HINT; if(hint & DecoderFormat_ITF) newHints |= DecodeHints::ITF_HINT; if(hint & DecoderFormat_MAXICODE) newHints |= DecodeHints::MAXICODE_HINT; if(hint & DecoderFormat_PDF_417) newHints |= DecodeHints::PDF_417_HINT; if(hint & DecoderFormat_QR_CODE) newHints |= DecodeHints::QR_CODE_HINT; if(hint & DecoderFormat_RSS_14) newHints |= DecodeHints::RSS_14_HINT; if(hint & DecoderFormat_RSS_EXPANDED) newHints |= DecodeHints::RSS_EXPANDED_HINT; if(hint & DecoderFormat_UPC_A) newHints |= DecodeHints::UPC_A_HINT; if(hint & DecoderFormat_UPC_E) newHints |= DecodeHints::UPC_E_HINT; if(hint & DecoderFormat_UPC_EAN_EXTENSION) newHints |= DecodeHints::UPC_EAN_EXTENSION_HINT; if(hint & DecoderFormat_CODE_128_GS1) { newHints |= DecodeHints::CODE_128_HINT; newHints |= DecodeHints::ASSUME_GS1; } enabledDecoders = newHints; emit enabledFormatsChanged(); } /*! * \brief getTagRec - returns rectangle containing the tag. * * To be able display tag rectangle regardless of the size of the bit matrix rect is in related coordinates [0; 1]. * \param resultPoints * \param bitMatrix * \return */ QRectF getTagRect(const ArrayRef<Ref<ResultPoint> > &resultPoints, const Ref<BitMatrix> &bitMatrix) { if (resultPoints->size() < 2) return QRectF(); int matrixWidth = bitMatrix->getWidth(); int matrixHeight = bitMatrix->getHeight(); // 1D barcode if (resultPoints->size() == 2) { WhiteRectangleDetector detector(bitMatrix); std::vector<Ref<ResultPoint> > resultRectPoints = detector.detect(); if (resultRectPoints.size() != 4) return QRectF(); qreal xMin = resultPoints[0]->getX(); qreal xMax = xMin; for (int i = 1; i < resultPoints->size(); ++i) { qreal x = resultPoints[i]->getX(); if (x < xMin) xMin = x; if (x > xMax) xMax = x; } qreal yMin = resultRectPoints[0]->getY(); qreal yMax = yMin; for (unsigned int i = 1; i < resultRectPoints.size(); ++i) { qreal y = resultRectPoints[i]->getY(); if (y < yMin) yMin = y; if (y > yMax) yMax = y; } return QRectF(QPointF(xMin / matrixWidth, yMax / matrixHeight), QPointF(xMax / matrixWidth, yMin / matrixHeight)); } // 2D QR code if (resultPoints->size() == 4) { qreal xMin = resultPoints[0]->getX(); qreal xMax = xMin; qreal yMin = resultPoints[0]->getY(); qreal yMax = yMin; for (int i = 1; i < resultPoints->size(); ++i) { qreal x = resultPoints[i]->getX(); qreal y = resultPoints[i]->getY(); if (x < xMin) xMin = x; if (x > xMax) xMax = x; if (y < yMin) yMin = y; if (y > yMax) yMax = y; } return QRectF(QPointF(xMin / matrixWidth, yMax / matrixHeight), QPointF(xMax / matrixWidth, yMin / matrixHeight)); } return QRectF(); } QString QZXing::decodeImage(const QImage &image, int maxWidth, int maxHeight, bool smoothTransformation) { QTime t; t.start(); Ref<Result> res; emit decodingStarted(); if(image.isNull()) { emit decodingFinished(false); processingTime = t.elapsed(); return ""; } CameraImageWrapper *ciw = NULL; if ((maxWidth > 0) || (maxHeight > 0)) ciw = CameraImageWrapper::Factory(image, maxWidth, maxHeight, smoothTransformation); else ciw = CameraImageWrapper::Factory(image, 999, 999, true); QString errorMessage = "Unknown"; try { Ref<LuminanceSource> imageRef(ciw); Ref<GlobalHistogramBinarizer> binz( new GlobalHistogramBinarizer(imageRef) ); Ref<BinaryBitmap> bb( new BinaryBitmap(binz) ); DecodeHints hints((int)enabledDecoders); bool hasSucceded = false; try { res = decoder->decode(bb, hints); hasSucceded = true; }catch(zxing::Exception &e){} if(!hasSucceded) { hints.setTryHarder(true); try { res = decoder->decode(bb, hints); hasSucceded = true; } catch(zxing::Exception &e) {} if (tryHarder_ && bb->isRotateSupported()) { Ref<BinaryBitmap> bbTmp = bb; for (int i=0; (i<3 && !hasSucceded); i++) { Ref<BinaryBitmap> rotatedImage(bbTmp->rotateCounterClockwise()); bbTmp = rotatedImage; try { res = decoder->decode(rotatedImage, hints); processingTime = t.elapsed(); hasSucceded = true; } catch(zxing::Exception &e) {} } } } if (hasSucceded) { QString string = QString(res->getText()->getText().c_str()); if (!string.isEmpty() && (string.length() > 0)) { int fmt = res->getBarcodeFormat().value; foundedFmt = decoderFormatToString(fmt); charSet_ = QString::fromStdString(res->getCharSet()); if (!charSet_.isEmpty()) { QTextCodec *codec = QTextCodec::codecForName(res->getCharSet().c_str()); if (codec) string = codec->toUnicode(res->getText()->getText().c_str()); } emit tagFound(string); emit tagFoundAdvanced(string, foundedFmt, charSet_); try { const QRectF rect = getTagRect(res->getResultPoints(), binz->getBlackMatrix()); emit tagFoundAdvanced(string, foundedFmt, charSet_, rect); }catch(zxing::Exception &/*e*/){} } emit decodingFinished(true); return string; } } catch(zxing::Exception &e) { errorMessage = QString(e.what()); } emit error(errorMessage); emit decodingFinished(false); processingTime = t.elapsed(); return ""; } QString QZXing::decodeImageFromFile(const QString& imageFilePath, int maxWidth, int maxHeight, bool smoothTransformation) { // used to have a check if this image exists // but was removed because if the image file path doesn't point to a valid image // then the QImage::isNull will return true and the decoding will fail eitherway. const QString header = "file://"; QString filePath = imageFilePath; if(imageFilePath.startsWith(header)) filePath = imageFilePath.right(imageFilePath.size() - header.size()); QUrl imageUrl = QUrl::fromLocalFile(filePath); QImage tmpImage = QImage(imageUrl.toLocalFile()); return decodeImage(tmpImage, maxWidth, maxHeight, smoothTransformation); } QString QZXing::decodeImageQML(QObject *item) { return decodeSubImageQML(item); } QString QZXing::decodeSubImageQML(QObject *item, const int offsetX, const int offsetY, const int width, const int height) { if(item == NULL) { processingTime = 0; emit decodingFinished(false); return ""; } QImage img = imageHandler->extractQImage(item, offsetX, offsetY, width, height); return decodeImage(img); } QString QZXing::decodeImageQML(const QUrl &imageUrl) { return decodeSubImageQML(imageUrl); } QString QZXing::decodeSubImageQML(const QUrl &imageUrl, const int offsetX, const int offsetY, const int width, const int height) { #ifdef QZXING_QML QString imagePath = imageUrl.path(); imagePath = imagePath.trimmed(); QImage img; if (imageUrl.scheme() == "image") { if (imagePath.startsWith("/")) imagePath = imagePath.right(imagePath.length() - 1); QQmlEngine *engine = QQmlEngine::contextForObject(this)->engine(); QQuickImageProvider *imageProvider = static_cast<QQuickImageProvider *>(engine->imageProvider(imageUrl.host())); QSize imgSize; img = imageProvider->requestImage(imagePath, &imgSize, QSize()); } else { QFileInfo fileInfo(imagePath); if (!fileInfo.exists()) { qDebug() << "[decodeSubImageQML()] The file" << imagePath << "does not exist."; emit decodingFinished(false); return ""; } img = QImage(imagePath); } if (offsetX || offsetY || width || height) img = img.copy(offsetX, offsetY, width, height); return decodeImage(img); #else return decodeImage(QImage()); #endif //QZXING_QML } QImage QZXing::encodeData(const QString& data) { QImage image; try { Ref<qrcode::QRCode> barcode = qrcode::Encoder::encode(data.toStdString(), qrcode::ErrorCorrectionLevel::L ); Ref<qrcode::ByteMatrix> bytesRef = barcode->getMatrix(); const std::vector< std::vector <zxing::byte> >& bytes = bytesRef->getArray(); image = QImage(bytesRef->getWidth(), bytesRef->getHeight(), QImage::Format_ARGB32); for(unsigned int i=0; i < bytesRef->getWidth(); i++) for(unsigned int j=0; j<bytesRef->getHeight(); j++) image.setPixel(i, j, bytes[i][j] ? qRgb(0,0,0) : qRgb(255,255,255)); image = image.scaled(240, 240); #ifdef QZXING_QML QZXingImageProvider::getInstance()->storeImage(image); #endif //QZXING_QML } catch (std::exception& e) { std::cout << "Error: " << e.what() << std::endl; } return image; } int QZXing::getProcessTimeOfLastDecoding() { return processingTime; } uint QZXing::getEnabledFormats() const { return enabledDecoders; }
8521a2690cf8af75727dbc935aff3dbd00ca0c30
ca291dee2da5b222e755e962ec139c25c5ee6c12
/ScrapEngine/ScrapEngine/Engine/LogicCore/Components/TriggerComponent/TriggerComponent.h
5920e5693d2c25b03e2a67459e267a952758bb85
[ "MIT" ]
permissive
ScrappyCocco/ScrapEngine
fed49a76cdadadb5ea6fa5a46464495df5e4a5d3
719c7f53795bdc9225669936dae552d1a38cc5b7
refs/heads/master
2022-02-01T22:42:54.146601
2022-01-04T16:21:18
2022-01-04T16:21:18
143,517,977
133
14
MIT
2020-02-25T21:19:21
2018-08-04T10:02:56
C++
UTF-8
C++
false
false
691
h
#pragma once #include <Engine/LogicCore/Components/SComponent.h> namespace ScrapEngine { namespace Physics { class CollisionBody; } } namespace ScrapEngine { namespace Core { class RigidBodyComponent; class TriggerComponent : public SComponent { private: Physics::CollisionBody* collisionbody_ = nullptr; public: TriggerComponent(Physics::CollisionBody* collisionbody); virtual ~TriggerComponent() = 0; void set_component_location(const SVector3& location) override; void set_component_rotation(const SVector3& rotation) override; bool test_collision(TriggerComponent* other) const; bool test_collision(RigidBodyComponent* other) const; }; } }
665d6c3356e3ade88b6c325145388cbfc9336da0
544fbe639a4d1f5bdf91c6bbf8568a37233e8546
/aws-cpp-sdk-auditmanager/include/aws/auditmanager/model/BatchCreateDelegationByAssessmentError.h
f27ec34fddf9e2f8ac61c2eaf01c7d2bc513d8cc
[ "MIT", "Apache-2.0", "JSON" ]
permissive
jweinst1/aws-sdk-cpp
833dbed4871a576cee3d7e37d93ce49e8d649ed5
fef0f65a49f08171cf6ebc8fbd357731d961ab0f
refs/heads/main
2023-07-14T03:42:55.080906
2021-08-29T04:07:48
2021-08-29T04:07:48
300,541,857
0
0
Apache-2.0
2020-10-02T07:53:42
2020-10-02T07:53:41
null
UTF-8
C++
false
false
6,784
h
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #pragma once #include <aws/auditmanager/AuditManager_EXPORTS.h> #include <aws/auditmanager/model/CreateDelegationRequest.h> #include <aws/core/utils/memory/stl/AWSString.h> #include <utility> namespace Aws { namespace Utils { namespace Json { class JsonValue; class JsonView; } // namespace Json } // namespace Utils namespace AuditManager { namespace Model { /** * <p> An error entity for the <code>BatchCreateDelegationByAssessment</code> API. * This is used to provide more meaningful errors than a simple string message. * </p><p><h3>See Also:</h3> <a * href="http://docs.aws.amazon.com/goto/WebAPI/auditmanager-2017-07-25/BatchCreateDelegationByAssessmentError">AWS * API Reference</a></p> */ class AWS_AUDITMANAGER_API BatchCreateDelegationByAssessmentError { public: BatchCreateDelegationByAssessmentError(); BatchCreateDelegationByAssessmentError(Aws::Utils::Json::JsonView jsonValue); BatchCreateDelegationByAssessmentError& operator=(Aws::Utils::Json::JsonView jsonValue); Aws::Utils::Json::JsonValue Jsonize() const; /** * <p> The API request to batch create delegations in Audit Manager. </p> */ inline const CreateDelegationRequest& GetCreateDelegationRequest() const{ return m_createDelegationRequest; } /** * <p> The API request to batch create delegations in Audit Manager. </p> */ inline bool CreateDelegationRequestHasBeenSet() const { return m_createDelegationRequestHasBeenSet; } /** * <p> The API request to batch create delegations in Audit Manager. </p> */ inline void SetCreateDelegationRequest(const CreateDelegationRequest& value) { m_createDelegationRequestHasBeenSet = true; m_createDelegationRequest = value; } /** * <p> The API request to batch create delegations in Audit Manager. </p> */ inline void SetCreateDelegationRequest(CreateDelegationRequest&& value) { m_createDelegationRequestHasBeenSet = true; m_createDelegationRequest = std::move(value); } /** * <p> The API request to batch create delegations in Audit Manager. </p> */ inline BatchCreateDelegationByAssessmentError& WithCreateDelegationRequest(const CreateDelegationRequest& value) { SetCreateDelegationRequest(value); return *this;} /** * <p> The API request to batch create delegations in Audit Manager. </p> */ inline BatchCreateDelegationByAssessmentError& WithCreateDelegationRequest(CreateDelegationRequest&& value) { SetCreateDelegationRequest(std::move(value)); return *this;} /** * <p> The error code returned by the * <code>BatchCreateDelegationByAssessment</code> API. </p> */ inline const Aws::String& GetErrorCode() const{ return m_errorCode; } /** * <p> The error code returned by the * <code>BatchCreateDelegationByAssessment</code> API. </p> */ inline bool ErrorCodeHasBeenSet() const { return m_errorCodeHasBeenSet; } /** * <p> The error code returned by the * <code>BatchCreateDelegationByAssessment</code> API. </p> */ inline void SetErrorCode(const Aws::String& value) { m_errorCodeHasBeenSet = true; m_errorCode = value; } /** * <p> The error code returned by the * <code>BatchCreateDelegationByAssessment</code> API. </p> */ inline void SetErrorCode(Aws::String&& value) { m_errorCodeHasBeenSet = true; m_errorCode = std::move(value); } /** * <p> The error code returned by the * <code>BatchCreateDelegationByAssessment</code> API. </p> */ inline void SetErrorCode(const char* value) { m_errorCodeHasBeenSet = true; m_errorCode.assign(value); } /** * <p> The error code returned by the * <code>BatchCreateDelegationByAssessment</code> API. </p> */ inline BatchCreateDelegationByAssessmentError& WithErrorCode(const Aws::String& value) { SetErrorCode(value); return *this;} /** * <p> The error code returned by the * <code>BatchCreateDelegationByAssessment</code> API. </p> */ inline BatchCreateDelegationByAssessmentError& WithErrorCode(Aws::String&& value) { SetErrorCode(std::move(value)); return *this;} /** * <p> The error code returned by the * <code>BatchCreateDelegationByAssessment</code> API. </p> */ inline BatchCreateDelegationByAssessmentError& WithErrorCode(const char* value) { SetErrorCode(value); return *this;} /** * <p> The error message returned by the * <code>BatchCreateDelegationByAssessment</code> API. </p> */ inline const Aws::String& GetErrorMessage() const{ return m_errorMessage; } /** * <p> The error message returned by the * <code>BatchCreateDelegationByAssessment</code> API. </p> */ inline bool ErrorMessageHasBeenSet() const { return m_errorMessageHasBeenSet; } /** * <p> The error message returned by the * <code>BatchCreateDelegationByAssessment</code> API. </p> */ inline void SetErrorMessage(const Aws::String& value) { m_errorMessageHasBeenSet = true; m_errorMessage = value; } /** * <p> The error message returned by the * <code>BatchCreateDelegationByAssessment</code> API. </p> */ inline void SetErrorMessage(Aws::String&& value) { m_errorMessageHasBeenSet = true; m_errorMessage = std::move(value); } /** * <p> The error message returned by the * <code>BatchCreateDelegationByAssessment</code> API. </p> */ inline void SetErrorMessage(const char* value) { m_errorMessageHasBeenSet = true; m_errorMessage.assign(value); } /** * <p> The error message returned by the * <code>BatchCreateDelegationByAssessment</code> API. </p> */ inline BatchCreateDelegationByAssessmentError& WithErrorMessage(const Aws::String& value) { SetErrorMessage(value); return *this;} /** * <p> The error message returned by the * <code>BatchCreateDelegationByAssessment</code> API. </p> */ inline BatchCreateDelegationByAssessmentError& WithErrorMessage(Aws::String&& value) { SetErrorMessage(std::move(value)); return *this;} /** * <p> The error message returned by the * <code>BatchCreateDelegationByAssessment</code> API. </p> */ inline BatchCreateDelegationByAssessmentError& WithErrorMessage(const char* value) { SetErrorMessage(value); return *this;} private: CreateDelegationRequest m_createDelegationRequest; bool m_createDelegationRequestHasBeenSet; Aws::String m_errorCode; bool m_errorCodeHasBeenSet; Aws::String m_errorMessage; bool m_errorMessageHasBeenSet; }; } // namespace Model } // namespace AuditManager } // namespace Aws
c6df4becf2c4cf82125228dd1df7ce4d69e974f4
4b42fae3479a99b3a1f6e16922e92809a0945c82
/content/public/renderer/content_renderer_client.h
a68f00aec37a0d42c9558497a138e3c3791f332e
[ "BSD-3-Clause" ]
permissive
Jtl12/browser-android-tabs
5eed5fc4d6c978057c910b58c3ea0445bb619ee9
f5406ad2a104d373062a86778d913e6b0a556e10
refs/heads/master
2023-04-02T05:20:33.277558
2018-07-20T12:56:19
2018-07-20T12:56:19
null
0
0
null
null
null
null
UTF-8
C++
false
false
18,924
h
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CONTENT_PUBLIC_RENDERER_CONTENT_RENDERER_CLIENT_H_ #define CONTENT_PUBLIC_RENDERER_CONTENT_RENDERER_CLIENT_H_ #include <stddef.h> #include <map> #include <memory> #include <string> #include <vector> #include "base/callback_forward.h" #include "base/files/file_path.h" #include "base/memory/ref_counted.h" #include "base/strings/string16.h" #include "base/task_scheduler/task_scheduler.h" #include "build/build_config.h" #include "content/public/common/content_client.h" #include "content/public/renderer/url_loader_throttle_provider.h" #include "media/base/decode_capabilities.h" #include "services/service_manager/public/mojom/service.mojom.h" #include "third_party/blink/public/mojom/page/page_visibility_state.mojom.h" #include "third_party/blink/public/platform/web_content_settings_client.h" #include "third_party/blink/public/web/web_navigation_policy.h" #include "third_party/blink/public/web/web_navigation_type.h" #include "ui/base/page_transition_types.h" #include "v8/include/v8.h" class GURL; class SkBitmap; namespace base { class FilePath; class SingleThreadTaskRunner; } namespace blink { class WebAudioDevice; class WebAudioLatencyHint; class WebClipboard; class WebFrame; class WebLocalFrame; class WebMIDIAccessor; class WebMIDIAccessorClient; class WebPlugin; class WebPrescientNetworking; class WebSocketHandshakeThrottle; class WebSpeechSynthesizer; class WebSpeechSynthesizerClient; class WebThemeEngine; class WebURL; class WebURLRequest; class WebURLResponse; struct WebPluginParams; struct WebURLError; } // namespace blink namespace media { class KeySystemProperties; } namespace content { class BrowserPluginDelegate; class MediaStreamRendererFactory; class RenderFrame; class RenderView; struct WebPluginInfo; // Embedder API for participating in renderer logic. class CONTENT_EXPORT ContentRendererClient { public: virtual ~ContentRendererClient() {} // Notifies us that the RenderThread has been created. virtual void RenderThreadStarted() {} // Notifies that a new RenderFrame has been created. virtual void RenderFrameCreated(RenderFrame* render_frame) {} // Notifies that a new RenderView has been created. virtual void RenderViewCreated(RenderView* render_view) {} // Returns the bitmap to show when a plugin crashed, or NULL for none. virtual SkBitmap* GetSadPluginBitmap(); // Returns the bitmap to show when a <webview> guest has crashed, or NULL for // none. virtual SkBitmap* GetSadWebViewBitmap(); // Allows the embedder to override creating a plugin. If it returns true, then // |plugin| will contain the created plugin, although it could be NULL. If it // returns false, the content layer will create the plugin. virtual bool OverrideCreatePlugin( RenderFrame* render_frame, const blink::WebPluginParams& params, blink::WebPlugin** plugin); // Creates a replacement plugin that is shown when the plugin at |file_path| // couldn't be loaded. This allows the embedder to show a custom placeholder. // This may return nullptr. However, if it does return a WebPlugin, it must // never fail to initialize. virtual blink::WebPlugin* CreatePluginReplacement( RenderFrame* render_frame, const base::FilePath& plugin_path); // Creates a delegate for browser plugin. virtual BrowserPluginDelegate* CreateBrowserPluginDelegate( RenderFrame* render_frame, const WebPluginInfo& info, const std::string& mime_type, const GURL& original_url); // Returns true if the embedder has an error page to show for the given http // status code. virtual bool HasErrorPage(int http_status_code); // Returns true if the embedder prefers not to show an error page for a failed // navigation to |url| in |render_frame|. virtual bool ShouldSuppressErrorPage(RenderFrame* render_frame, const GURL& url); // Returns false for new tab page activities, which should be filtered out in // UseCounter; returns true otherwise. virtual bool ShouldTrackUseCounter(const GURL& url); // Returns the information to display when a navigation error occurs. // If |error_html| is not null then it may be set to a HTML page // containing the details of the error and maybe links to more info. // If |error_description| is not null it may be set to contain a brief // message describing the error that has occurred. // Either of the out parameters may be not written to in certain cases // (lack of information on the error code) so the caller should take care to // initialize the string values with safe defaults before the call. virtual void PrepareErrorPage(content::RenderFrame* render_frame, const blink::WebURLRequest& failed_request, const blink::WebURLError& error, std::string* error_html, base::string16* error_description) {} virtual void PrepareErrorPageForHttpStatusError( content::RenderFrame* render_frame, const blink::WebURLRequest& failed_request, const GURL& unreachable_url, int http_status, std::string* error_html, base::string16* error_description) {} // Returns as |error_description| a brief description of the error that // ocurred. The out parameter may be not written to in certain cases (lack of // information on the error code) virtual void GetErrorDescription(const blink::WebURLRequest& failed_request, const blink::WebURLError& error, base::string16* error_description) {} // Allows the embedder to control when media resources are loaded. Embedders // can run |closure| immediately if they don't wish to defer media resource // loading. If |has_played_media_before| is true, the render frame has // previously started media playback (i.e. played audio and video). virtual void DeferMediaLoad(RenderFrame* render_frame, bool has_played_media_before, const base::Closure& closure); // Allows the embedder to override creating a WebMIDIAccessor. If it // returns NULL the content layer will create the MIDI accessor. virtual std::unique_ptr<blink::WebMIDIAccessor> OverrideCreateMIDIAccessor( blink::WebMIDIAccessorClient* client); // Allows the embedder to override creating a WebAudioDevice. If it // returns NULL the content layer will create the audio device. virtual std::unique_ptr<blink::WebAudioDevice> OverrideCreateAudioDevice( const blink::WebAudioLatencyHint& latency_hint); // Allows the embedder to override the blink::WebClipboard used. If it // returns NULL the content layer will handle clipboard interactions. virtual blink::WebClipboard* OverrideWebClipboard(); // Allows the embedder to override the WebThemeEngine used. If it returns NULL // the content layer will provide an engine. virtual blink::WebThemeEngine* OverrideThemeEngine(); // Allows the embedder to provide a WebSocketHandshakeThrottle. If it returns // NULL then none will be used. virtual std::unique_ptr<blink::WebSocketHandshakeThrottle> CreateWebSocketHandshakeThrottle(); // Allows the embedder to override the WebSpeechSynthesizer used. // If it returns NULL the content layer will provide an engine. virtual std::unique_ptr<blink::WebSpeechSynthesizer> OverrideSpeechSynthesizer(blink::WebSpeechSynthesizerClient* client); // Called on the main-thread immediately after the io thread is // created. virtual void PostIOThreadCreated( base::SingleThreadTaskRunner* io_thread_task_runner); // Called on the main-thread immediately after the compositor thread is // created. virtual void PostCompositorThreadCreated( base::SingleThreadTaskRunner* compositor_thread_task_runner); // Returns true if the renderer process should schedule the idle handler when // all widgets are hidden. virtual bool RunIdleHandlerWhenWidgetsHidden(); // Returns true if the renderer process should allow task suspension // after the process has been backgrounded. Defaults to false. virtual bool AllowStoppingWhenProcessBackgrounded(); // Returns true if a popup window should be allowed. virtual bool AllowPopup(); #if defined(OS_ANDROID) // TODO(sgurun) This callback is deprecated and will be removed as soon // as android webview completes implementation of a resource throttle based // shouldoverrideurl implementation. See crbug.com/325351 // // Returns true if the navigation was handled by the embedder and should be // ignored by WebKit. This method is used by CEF and android_webview. virtual bool HandleNavigation(RenderFrame* render_frame, bool is_content_initiated, bool render_view_was_created_by_renderer, blink::WebFrame* frame, const blink::WebURLRequest& request, blink::WebNavigationType type, blink::WebNavigationPolicy default_policy, bool is_redirect); // Indicates if the Android MediaPlayer should be used instead of Chrome's // built in media player for the given |url|. Defaults to false. virtual bool ShouldUseMediaPlayerForURL(const GURL& url); #endif // Returns true if we should fork a new process for the given navigation. // If |send_referrer| is set to false (which is the default), no referrer // header will be send for the navigation. Otherwise, the referrer header is // set according to the frame's referrer policy. virtual bool ShouldFork(blink::WebLocalFrame* frame, const GURL& url, const std::string& http_method, bool is_initial_navigation, bool is_server_redirect, bool* send_referrer); // Notifies the embedder that the given frame is requesting the resource at // |url|. If the function returns a valid |new_url|, the request must be // updated to use it. The |attach_same_site_cookies| output parameter // determines whether SameSite cookies should be attached to the request. // TODO(nasko): When moved over to Network Service, find a way to perform // this check on the browser side, so untrusted renderer processes cannot // influence whether SameSite cookies are attached. virtual void WillSendRequest(blink::WebLocalFrame* frame, ui::PageTransition transition_type, const blink::WebURL& url, const url::Origin* initiator_origin, GURL* new_url, bool* attach_same_site_cookies); // Returns true if the request is associated with a document that is in // ""prefetch only" mode, and will not be rendered. virtual bool IsPrefetchOnly(RenderFrame* render_frame, const blink::WebURLRequest& request); // See blink::Platform. virtual unsigned long long VisitedLinkHash(const char* canonical_url, size_t length); virtual bool IsLinkVisited(unsigned long long link_hash); virtual blink::WebPrescientNetworking* GetPrescientNetworking(); virtual bool ShouldOverridePageVisibilityState( const RenderFrame* render_frame, blink::mojom::PageVisibilityState* override_state); // Returns true if the given Pepper plugin is external (requiring special // startup steps). virtual bool IsExternalPepperPlugin(const std::string& module_name); // Returns true if the given Pepper plugin should process content from // different origins in different PPAPI processes. This is generally a // worthwhile precaution when the plugin provides an active scripting // language. virtual bool IsOriginIsolatedPepperPlugin(const base::FilePath& plugin_path); // Returns true if the page at |url| can use Pepper MediaStream APIs. virtual bool AllowPepperMediaStreamAPI(const GURL& url); // Allows an embedder to provide a MediaStreamRendererFactory. virtual std::unique_ptr<MediaStreamRendererFactory> CreateMediaStreamRendererFactory(); // Allows embedder to register the key system(s) it supports by populating // |key_systems|. virtual void AddSupportedKeySystems( std::vector<std::unique_ptr<media::KeySystemProperties>>* key_systems); // Signal that embedder has changed key systems. // TODO(chcunningham): Refactor this to a proper change "observer" API that is // less fragile (don't assume AddSupportedKeySystems has just one caller). virtual bool IsKeySystemsUpdateNeeded(); // Allows embedder to describe customized audio capabilities. virtual bool IsSupportedAudioConfig(const media::AudioConfig& config); // Allows embedder to describe customized video capabilities. virtual bool IsSupportedVideoConfig(const media::VideoConfig& config); // Return true if the bitstream format |codec| is supported by the audio sink. virtual bool IsSupportedBitstreamAudioCodec(media::AudioCodec codec); // Returns true if we should report a detailed message (including a stack // trace) for console [logs|errors|exceptions]. |source| is the WebKit- // reported source for the error; this can point to a page or a script, // and can be external or internal. virtual bool ShouldReportDetailedMessageForSource( const base::string16& source) const; // Creates a permission client for in-renderer worker. virtual std::unique_ptr<blink::WebContentSettingsClient> CreateWorkerContentSettingsClient(RenderFrame* render_frame); // Returns true if the page at |url| can use Pepper CameraDevice APIs. virtual bool IsPluginAllowedToUseCameraDeviceAPI(const GURL& url); // Returns true if the page at |url| can use Pepper Compositor APIs. virtual bool IsPluginAllowedToUseCompositorAPI(const GURL& url); // Returns true if dev channel APIs are available for plugins. virtual bool IsPluginAllowedToUseDevChannelAPIs(); // Records a sample string to a Rappor privacy-preserving metric. // See: https://www.chromium.org/developers/design-documents/rappor virtual void RecordRappor(const std::string& metric, const std::string& sample) {} // Records a domain and registry of a url to a Rappor privacy-preserving // metric. See: https://www.chromium.org/developers/design-documents/rappor virtual void RecordRapporURL(const std::string& metric, const GURL& url) {} // Gives the embedder a chance to add properties to the context menu. // Currently only called when the context menu is for an image. virtual void AddImageContextMenuProperties( const blink::WebURLResponse& response, bool is_image_in_context_a_placeholder_image, std::map<std::string, std::string>* properties) {} // Notifies that a document element has been inserted in the frame's document. // This may be called multiple times for the same document. This method may // invalidate the frame. virtual void RunScriptsAtDocumentStart(RenderFrame* render_frame) {} // Notifies that the DOM is ready in the frame's document. // This method may invalidate the frame. virtual void RunScriptsAtDocumentEnd(RenderFrame* render_frame) {} // Notifies that the window.onload event is about to fire. // This method may invalidate the frame. virtual void RunScriptsAtDocumentIdle(RenderFrame* render_frame) {} // Allows subclasses to enable some runtime features before Blink has // started. virtual void SetRuntimeFeaturesDefaultsBeforeBlinkInitialization() {} // Notifies that a service worker context has been created. This function // is called from the worker thread. virtual void DidInitializeServiceWorkerContextOnWorkerThread( v8::Local<v8::Context> context, int64_t service_worker_version_id, const GURL& service_worker_scope, const GURL& script_url) {} // Notifies that a service worker context will be destroyed. This function // is called from the worker thread. virtual void WillDestroyServiceWorkerContextOnWorkerThread( v8::Local<v8::Context> context, int64_t service_worker_version_id, const GURL& service_worker_scope, const GURL& script_url) {} // Whether this renderer should enforce preferences related to the WebRTC // routing logic, i.e. allowing multiple routes and non-proxied UDP. virtual bool ShouldEnforceWebRTCRoutingPreferences(); // Notifies that a worker context has been created. This function is called // from the worker thread. virtual void DidInitializeWorkerContextOnWorkerThread( v8::Local<v8::Context> context) {} // Overwrites the given URL to use an HTML5 embed if possible. // An empty URL is returned if the URL is not overriden. virtual GURL OverrideFlashEmbedWithHTML(const GURL& url); // Provides parameters for initializing the global task scheduler. Default // params are used if this returns nullptr. virtual std::unique_ptr<base::TaskScheduler::InitParams> GetTaskSchedulerInitParams(); // Whether the renderer allows idle media players to be automatically // suspended after a period of inactivity. virtual bool AllowIdleMediaSuspend(); // Called when a resource at |url| is loaded using an otherwise-valid legacy // Symantec certificate that will be distrusted in future. Allows the embedder // to override the message that is added to the console to inform developers // that their certificate will be distrusted in future. If the method returns // true, then |*console_message| will be printed to the console; otherwise a // generic mesage will be used. virtual bool OverrideLegacySymantecCertConsoleMessage( const GURL& url, std::string* console_messsage); // Asks the embedder to bind |service_request| to its renderer-side service // implementation. virtual void CreateRendererService( service_manager::mojom::ServiceRequest service_request) {} virtual std::unique_ptr<URLLoaderThrottleProvider> CreateURLLoaderThrottleProvider(URLLoaderThrottleProviderType provider_type); // Called when Blink cannot find a frame with the given name in the frame's // browsing instance. This gives the embedder a chance to return a frame // from outside of the browsing instance. virtual blink::WebFrame* FindFrame(blink::WebLocalFrame* relative_to_frame, const std::string& name); }; } // namespace content #endif // CONTENT_PUBLIC_RENDERER_CONTENT_RENDERER_CLIENT_H_
bf4130a81f51de400354cd402e376f301cdb3c00
477c8309420eb102b8073ce067d8df0afc5a79b1
/Plugins/PointSprite/ParaViewPlugin/Qvis/QvisColorGridWidget.h
5b075262c161ff6a4221fb609a7656a68ab86756
[ "LicenseRef-scancode-paraview-1.2" ]
permissive
aashish24/paraview-climate-3.11.1
e0058124e9492b7adfcb70fa2a8c96419297fbe6
c8ea429f56c10059dfa4450238b8f5bac3208d3a
refs/heads/uvcdat-master
2021-07-03T11:16:20.129505
2013-05-10T13:14:30
2013-05-10T13:14:30
4,238,077
1
0
NOASSERTION
2020-10-12T21:28:23
2012-05-06T02:32:44
C++
UTF-8
C++
false
false
5,510
h
/***************************************************************************** * * Copyright (c) 2000 - 2007, The Regents of the University of California * Produced at the Lawrence Livermore National Laboratory * All rights reserved. * * This file is part of VisIt. For details, see http://www.llnl.gov/visit/. The * full copyright notice is contained in the file COPYRIGHT located at the root * of the VisIt distribution or at http://www.llnl.gov/visit/copyright.html. * * 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 disclaimer below. * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the disclaimer (as noted below) in the * documentation and/or materials provided with the distribution. * - Neither the name of the UC/LLNL 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 REGENTS OF THE UNIVERSITY OF * CALIFORNIA, THE U.S. DEPARTMENT OF ENERGY 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 QVIS_COLOR_GRID_WIDGET_H #define QVIS_COLOR_GRID_WIDGET_H #include <QWidget> class QPixmap; class QPainter; // **************************************************************************** // Class: QvisColorGridWidget // // Purpose: // This widget contains an array of colors from which the user may choose. // // Notes: // // Programmer: Brad Whitlock // Creation: Mon Dec 4 14:30:50 PST 2000 // // Modifications: // Brad Whitlock, Tue Mar 12 19:07:21 PST 2002 // Added an internal method for drawing the button edges. // // Brad Whitlock, Fri Apr 26 11:35:04 PDT 2002 // I fixed a drawing error that cropped up on windows. // // Brad Whitlock, Thu Nov 21 10:41:40 PDT 2002 // I added more signals. // // Brad Whitlock, Wed Feb 26 12:37:09 PDT 2003 // I made it capable of having empty color slots. // // **************************************************************************** class QvisColorGridWidget : public QWidget { Q_OBJECT public: QvisColorGridWidget(QWidget *parent = 0, const char *name = 0); virtual ~QvisColorGridWidget(); virtual QSize sizeHint () const; virtual QSize minimumSize() const; void setPaletteColors(const QColor *c, int nColors, int suggestedColumns=6); void setPaletteColor(const QColor &c, int index); void setSelectedColor(const QColor &c); void setActiveColorIndex(int index); void setSelectedColorIndex(int index); void setFrame(bool val); void setBoxSize(int val); void setBoxPadding(int val); int rows() const; int columns() const; QColor selectedColor() const; int selectedColorIndex() const; QColor paletteColor(int index) const; bool containsColor(const QColor &color) const; int boxSize() const; int boxPadding() const; int activeColorIndex() const; signals: void selectedColor(const QColor &c); void selectedColor(const QColor &c, int colorIndex); void selectedColor(const QColor &c, int row, int column); void activateMenu(const QColor &c, int row, int column, const QPoint &); protected: virtual void enterEvent(QEvent *); virtual void keyPressEvent(QKeyEvent *e); virtual void leaveEvent(QEvent *); virtual void mousePressEvent(QMouseEvent *e); virtual void mouseMoveEvent(QMouseEvent *e); virtual void mouseReleaseEvent(QMouseEvent *e); virtual void paintEvent(QPaintEvent *); virtual void resizeEvent(QResizeEvent *); void drawColorArray(); void drawColor(QPainter &paint, int index); QRegion drawHighlightedColor(QPainter *paint, int index); QRegion drawUnHighlightedColor(QPainter *paint, int index); QRegion drawSelectedColor(QPainter *paint, int index); private: void getColorRect(int index, int &x, int &y, int &w, int &h); int getColorIndex(int x, int y) const; int getIndex(int row, int col) const; void getRowColumnFromIndex(int index, int &row, int &column) const; void drawBox(QPainter &p, const QRect &r, const QColor &light, const QColor &dark, int lw = 2); QColor *paletteColors; int numPaletteColors; int numRows; int numColumns; int currentActiveColor; int currentSelectedColor; bool drawFrame; int boxSizeValue; int boxPaddingValue; QPixmap *drawPixmap; }; #endif
22b4fffdff6e1397e10d9ffa01f51e71be277d93
6c4e391046022177244aeade63b03fc0824a4c50
/ash/login/ui/login_test_base.h
846529580ec2f8c8b9b2b29f0657d9c7c1bc98e8
[ "BSD-3-Clause" ]
permissive
woshihoujinxin/chromium-2
d17cae43153d14673778bbdf0b739886d2461902
71aec55e801f801f89a81cfb219a219d953a5d5c
refs/heads/master
2022-11-15T00:18:39.821920
2017-07-14T19:59:33
2017-07-14T19:59:33
97,331,019
1
0
null
2017-07-15T17:16:35
2017-07-15T17:16:35
null
UTF-8
C++
false
false
1,687
h
// Copyright 2017 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef ASH_LOGIN_UI_LOGIN_TEST_BASE_H_ #define ASH_LOGIN_UI_LOGIN_TEST_BASE_H_ #include "ash/login/ui/login_data_dispatcher.h" #include "ash/public/interfaces/user_info.mojom.h" #include "ash/test/ash_test_base.h" #include "base/macros.h" namespace views { class View; class Widget; } // namespace views namespace ash { // Base test fixture for testing the views-based login and lock screens. This // class provides easy access to types which the login/lock frequently need. class LoginTestBase : public test::AshTestBase { public: LoginTestBase(); ~LoginTestBase() override; // Creates and displays a widget containing |content|. void ShowWidgetWithContent(views::View* content); views::Widget* widget() const { return widget_; } // Utility method to create a new |mojom::UserInfoPtr| instance. mojom::UserInfoPtr CreateUser(const std::string& name) const; // Changes the active number of users. Fires an event on |data_dispatcher()|. void SetUserCount(size_t count); const std::vector<ash::mojom::UserInfoPtr>& users() const { return users_; } LoginDataDispatcher* data_dispatcher() { return &data_dispatcher_; } // test::AshTestBase: void TearDown() override; private: class WidgetDelegate; views::Widget* widget_ = nullptr; std::unique_ptr<WidgetDelegate> delegate_; std::vector<ash::mojom::UserInfoPtr> users_; LoginDataDispatcher data_dispatcher_; DISALLOW_COPY_AND_ASSIGN(LoginTestBase); }; } // namespace ash #endif // ASH_LOGIN_UI_LOGIN_TEST_BASE_H_
15026e30a20cbb54cde203105de9e250b3ed6043
c8c5b33404786915c7e230e75c1f70e145203fbb
/cotson/src/network/slirp_acceptor.cpp
10e8d34f0f3dac4a0b729ab55caee5a289c8f072
[ "MIT", "LicenseRef-scancode-warranty-disclaimer" ]
permissive
adityabhopale95/COTSON_Simulator_multinode
82b4e5a914b20083aaeacc6684b9ed300f5c55b2
4131d59fe83a6756caa00fb46164982cb490619e
refs/heads/master
2020-03-24T14:30:57.285733
2018-08-03T03:30:16
2018-08-03T03:30:16
142,770,484
1
1
null
null
null
null
UTF-8
C++
false
false
3,055
cpp
// -*- C++ -*- // (C) Copyright 2006-2009 Hewlett-Packard Development Company, L.P. // // 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. // // $Id: slirp_acceptor.cpp 77 2010-02-11 17:44:07Z paolofrb $ #include "reactor.h" #include "packet_processor.h" #include "slirp_acceptor.h" #include "../slirp/libslirp.h" #include <iostream> #include <stdlib.h> #include <stdio.h> #include <sys/types.h> #include <sys/socket.h> #include <sys/un.h> using namespace std; SlirpAcceptor::SlirpAcceptor() : EventHandler(SLIRP),reactor_(0),processor_(0), null_addr_(Sockaddr::null<sockaddr>()) {} SlirpAcceptor::~SlirpAcceptor() {} void SlirpAcceptor::init(const char *n, Reactor *r, PacketProcessor* p) { network_ = n; reactor_ = r; processor_ = p; } void SlirpAcceptor::redir(uint32_t n, uint16_t p1, uint16_t p2) { if (n && p1 && p2) { struct in_addr guest_addr = inet_makeaddr(ntohl(inet_addr(network_)),n); if (slirp_redir(false,p2,guest_addr,p1)) { cerr << "ERROR: cannot redirect tcp " << inet_ntoa(guest_addr) << ":" << p1 << " to localhost:" << p2 << endl; } if (slirp_redir(true,p2,guest_addr,p1)) { cerr << "ERROR: cannot redirect udp " << inet_ntoa(guest_addr) << ":" << p1 << " to localhost:" << p2 << endl; } else { cout << "Redirected " << inet_ntoa(guest_addr) << ":" << p1 << " to localhost:" << p2 << endl; } } } int SlirpAcceptor::open_acceptor(int pid) { ::strcpy(slirp_hostname,"slirp.cotson.com"); slirp_init(false,network_); reactor_->register_handler(this); cout << "slirp connection started" << endl; return 0; } int SlirpAcceptor::close_acceptor(void) { return 0; } int SlirpAcceptor::fill(int maxfd, fd_set* r,fd_set* w,fd_set* e) { int mx = maxfd; slirp_select_fill(&mx,r,w,e); return mx; } int SlirpAcceptor::poll(fd_set* r,fd_set* w,fd_set* e) { slirp_select_poll(r,w,e); return 0; } int SlirpAcceptor::sendto(const void* buf, size_t len,const sockaddr* to, size_t tolen) { // cout << "### SLIRP SEND [" << len << "]\n"; slirp_input(reinterpret_cast<const uint8_t*>(buf),len); return len; } int SlirpAcceptor::handle_input(const uint8_t* buf, int len) { if (processor_) { processor_->packet(buf,len); return processor_->process(this); } return -1; } // ########### LIBSLIRP INTERFACE ############ extern "C" void slirp_output(const uint8_t *pkt, int pkt_len) { // cout << "### SLIRP OUTPUT [" << pkt_len << "]\n"; SlirpAcceptor::get().handle_input(pkt,pkt_len); } extern "C" int slirp_can_output(void) { return 1; }
7352f4e1fe332b4400cacc433110c3f7d4048105
601ef8f84521f8d99786fa530ab97b4a7a6fbf49
/algoritmos/binary_search/binary_search.cpp
e2df5067d19b9550490034c12dabe26eb9c8563c
[]
no_license
HugoAlejandro2002/Algoritmica-2
4cfe1adb3cdff9758c43ae0c3887cc992548661a
1252965bb8ce0a4ab7f8740eebab6e81f10b9a2a
refs/heads/main
2023-07-15T21:43:40.637203
2021-09-02T13:34:17
2021-09-02T13:34:17
null
0
0
null
null
null
null
UTF-8
C++
false
false
925
cpp
#include <bits/stdc++.h> #define input freopen("in.txt", "r", stdin) #define output freopen("out.txt", "w", stdout) using namespace std; int n, x; int arreglo[100000+1]; bool f(int mid) { return x > arreglo[mid]; } int binarySearch() { int ini = 0; int fin = n; int ans = -1; while(fin - ini > 1) { int mid = (fin + ini)/2; if(x > arreglo[mid]) { //la izquierda es mas pequena que mid ini = mid + 1; } else{ if(x < arreglo[mid]){ //la derecha es mas pequeno que mid fin = mid - 1; }else{ // Le medio es igual al numero ans = mid; break; } } } return ans; } int main() { cin >> n; for(int i = 0; i < n; i ++) { cin>>arreglo[i]; } cin >> x; cout<<binarySearch()<<endl; return 0; } /* 10 2 4 6 8 10 12 14 16 18 20 12 */
f216f0f0bde364847c8cb0253da70b82dd24d8e4
8cb8ec98155a606e0798d1597d92fa5b417a43e9
/WNLogging.h
26ed1d05098b329023729be4786ef56581ca3de6
[]
no_license
korovkin/WNLogging
f95b513f937fc55faa14878224521825f69b0563
fe9ec7bd1a4f1d1f0a99dca189c45c79ae2686e3
refs/heads/master
2021-06-30T05:36:07.399866
2021-06-07T21:17:17
2021-06-07T21:17:17
80,579,222
2
0
null
null
null
null
UTF-8
C++
false
false
8,063
h
#pragma once ///////////////////////////////////////////////////////////////// /// Mostly inspired by: https://github.com/google/glog ///////////////////////////////////////////////////////////////// #include <errno.h> #include <inttypes.h> #include <stdint.h> #include <string.h> #include <sys/types.h> #include <time.h> #include <unistd.h> #include <cmath> #include <iosfwd> #include <ostream> #include <sstream> #include <string> #include <vector> #define __FILENAME__ \ (strrchr(__FILE__, '/') ? strrchr(__FILE__, '/') + 1 : __FILE__) #define LOG(severity) \ wn::LogMessage(__FILENAME__ , "", __LINE__, wn::LogSeverity_##severity) \ .stream() #define VLOG(severity) \ wn::LogMessage(__FILENAME__, __FUNCTION__, __LINE__, wn::LogSeverity::NEVER).stream() namespace wn { enum LogSeverity { LogSeverity_NEVER = -1, LogSeverity_DEBUG = 0, LogSeverity_TESTS, LogSeverity_INFO, LogSeverity_WARNING, LogSeverity_ERROR, LogSeverity_FATAL }; void SetCurrentLogFilename(const char* filename); namespace wn_base_logging { // LogMessage::LogStream is a std::ostream backed by this streambuf. // This class ignores overflow and leaves two bytes at the end of the // buffer to allow for a '\n' and '\0'. class LogStreamBuf : public std::streambuf { public: // REQUIREMENTS: "len" must be >= 2 to account for the '\n' and '\n'. LogStreamBuf(char* buf, int len) { setp(buf, buf + len - 2); } virtual int_type overflow(int_type ch) { return ch; } size_t pcount() const { return pptr() - pbase(); } char* pbase() const { return std::streambuf::pbase(); } }; } class LogMessage { public: enum { // Passing kNoLogPrefix for the line number disables the // log-message prefix. Useful for using the LogMessage // infrastructure as a printing utility. See also the --log_prefix // flag for controlling the log-message prefix on an // application-wide basis. kNoLogPrefix = -1 }; class LogStream : public std::ostream { public: LogStream(char* buf, int len) : std::ostream(NULL) , streambuf_(buf, len) , self_(this) { rdbuf(&streambuf_); } LogStream* self() const { return self_; } // Legacy std::streambuf methods. size_t pcount() const { return streambuf_.pcount(); } char* pbase() const { return streambuf_.pbase(); } char* str() const { return pbase(); } private: LogStream(const LogStream&); LogStream& operator=(const LogStream&); wn_base_logging::LogStreamBuf streambuf_; LogStream* self_; // Consistency check hack }; public: // icc 8 requires this typedef to avoid an internal compiler error. typedef void (LogMessage::*SendMethod)(); LogMessage(const char* file, int line); LogMessage(const char* file, const char* function, int line, wn::LogSeverity severity); ~LogMessage(); void Flush(); void SendToLog(); std::ostream& stream(); int preserved_errno() const; struct LogMessageData; protected: void Init(const char* file, const char* function, int line, wn::LogSeverity severity, void (LogMessage::*send_method)()); LogMessageData* data_; LogMessage(const LogMessage&); void operator=(const LogMessage&); }; } namespace wn { extern const double DELTA_DOUBLE; extern const double DELTA_FLOAT; inline bool check_eq(int val1, int val2) { return (val1 == val2); } inline bool check_eq(double val1, double val2) { return std::abs(val1 - val2) < DELTA_DOUBLE; } inline bool check_eq(float val1, float val2) { return std::abs(val1 - val2) < DELTA_FLOAT; } template <typename T> bool check_eq(const T& val1, const T& val2) { return val1 == val2; } } #define CHECK_SEV(_cond, _severity) \ for (unsigned int __CHECK_EQ_SEV_C__ = 0; \ __CHECK_EQ_SEV_C__ < 1 && (!(_cond)); \ ++__CHECK_EQ_SEV_C__) \ wn::LogMessage(__FILE__, __FUNCTION__, __LINE__, _severity).stream() \ << "check " \ << ", failed, cond, " << _cond << " ; " #define CHECK_EQ_SEV(_val1, _val2, _severity) \ for (unsigned int __CHECK_EQ_SEV_C__ = 0; \ __CHECK_EQ_SEV_C__ < 1 && !wn::check_eq(_val1, _val2); \ ++__CHECK_EQ_SEV_C__) \ wn::LogMessage(__FILE__, __FUNCTION__, __LINE__, _severity).stream() \ << "check_eq" \ << ", failed, val1, " << _val1 << ", val2, " << _val2 << " ; " #define CHECK_NE_SEV(_val1, _val2, _severity) \ for (unsigned int __CHECK_EQ_SEV_C__ = 0; \ __CHECK_EQ_SEV_C__ < 1 && wn::check_eq(_val1, _val2); \ ++__CHECK_EQ_SEV_C__) \ wn::LogMessage(__FILE__, __FUNCTION__, __LINE__, _severity).stream() \ << "check_ne" \ << ", failed, val1, " << _val1 << ", val2, " << _val2 << " ; " #define CHECK_LE_SEV(_val1, _val2, _severity) \ for (unsigned int __CHECK_EQ_SEV_C__ = 0; \ __CHECK_EQ_SEV_C__ < 1 && !((_val1) <= (_val2)); \ ++__CHECK_EQ_SEV_C__) \ wn::LogMessage(__FILE__, __FUNCTION__, __LINE__, _severity).stream() \ << "check_le" \ << ", failed, val1, " << _val1 << ", val2, " << _val2 << " ; " #define CHECK_LT_SEV(_val1, _val2, _severity) \ for (unsigned int __CHECK_EQ_SEV_C__ = 0; \ __CHECK_EQ_SEV_C__ < 1 && !((_val1) < (_val2)); \ ++__CHECK_EQ_SEV_C__) \ wn::LogMessage(__FILE__, __FUNCTION__, __LINE__, _severity).stream() \ << "check " \ << "check_lt" \ << ", failed, val1, " << _val1 << ", val2, " << _val2 << " ; " #define CHECK_GE_SEV(_val1, _val2, _severity) \ for (unsigned int __CHECK_EQ_SEV_C__ = 0; \ __CHECK_EQ_SEV_C__ < 1 && !((_val1) >= (_val2)); \ ++__CHECK_EQ_SEV_C__) \ wn::LogMessage(__FILE__, __FUNCTION__, __LINE__, _severity).stream() \ << "check_ge" \ << ", failed, val1, " << _val1 << ", val2, " << _val2 << " ; " #define CHECK_GT_SEV(_val1, _val2, _severity) \ for (unsigned int __CHECK_EQ_SEV_C__ = 0; \ __CHECK_EQ_SEV_C__ < 1 && !((_val1) > (_val2)); \ ++__CHECK_EQ_SEV_C__) \ wn::LogMessage(__FILE__, __FUNCTION__, __LINE__, _severity).stream() \ << "check_gt" \ << ", failed, val1, " << _val1 << ", val2, " << _val2 << " ; " #define CHECK_EQ(_val1, _val2) \ CHECK_EQ_SEV(_val1, _val2, wn::LogSeverity_FATAL) #define CHECK_NE(_val1, _val2) \ CHECK_NE_SEV(_val1, _val2, wn::LogSeverity_FATAL) #define CHECK_LT(_val1, _val2) \ CHECK_LT_SEV(_val1, _val2, wn::LogSeverity_FATAL) #define CHECK_GE(_val1, _val2) \ CHECK_GE_SEV(_val1, _val2, wn::LogSeverity_FATAL) #define CHECK_GT(_val1, _val2) \ CHECK_GT_SEV(_val1, _val2, wn::LogSeverity_FATAL) #define CHECK_FATAL(_cond) CHECK_SEV((_cond), wn::LogSeverity_FATAL) #define CHECK(_cond) CHECK_SEV((_cond), wn::LogSeverity_ERROR)
e45a981d074dce7cccaa2ef8c3aed88b74817d5d
abaa86b60befa876b858194b5f6c372c4efa096c
/Intermediate/Build/Win64/UE4Editor/Inc/FirebaseHelper/FirestoreValue.gen.cpp
8effba3bfb3adf343ea0db5ba4a8527afed5d13a
[]
no_license
JICA98/FirebaseHelper
afc5db65949fabe8e049f987547980923d620ebd
54268d41b12a47724c3a0f25d7a5a338c314b26e
refs/heads/main
2023-01-30T12:40:43.393446
2020-12-11T07:35:57
2020-12-11T07:35:57
316,012,440
0
0
null
null
null
null
UTF-8
C++
false
false
43,207
cpp
// Copyright Epic Games, Inc. All Rights Reserved. /*=========================================================================== Generated code exported from UnrealHeaderTool. DO NOT modify this manually! Edit the corresponding .h files instead! ===========================================================================*/ #include "UObject/GeneratedCppIncludes.h" #include "FirebaseHelper/Public/FirestoreValue.h" #ifdef _MSC_VER #pragma warning (push) #pragma warning (disable : 4883) #endif PRAGMA_DISABLE_DEPRECATION_WARNINGS void EmptyLinkFunctionForGeneratedCodeFirestoreValue() {} // Cross Module References FIREBASEHELPER_API UClass* Z_Construct_UClass_UFirestoreValue_NoRegister(); FIREBASEHELPER_API UClass* Z_Construct_UClass_UFirestoreValue(); ENGINE_API UClass* Z_Construct_UClass_UBlueprintFunctionLibrary(); UPackage* Z_Construct_UPackage__Script_FirebaseHelper(); FIREBASEHELPER_API UScriptStruct* Z_Construct_UScriptStruct_FJsonValueB(); FIREBASEHELPER_API UScriptStruct* Z_Construct_UScriptStruct_FGeoPoint(); // End Cross Module References DEFINE_FUNCTION(UFirestoreValue::execMapValue) { P_GET_STRUCT(FJsonValueB,Z_Param_Value); P_FINISH; P_NATIVE_BEGIN; *(TMap<FString,FJsonValueB>*)Z_Param__Result=UFirestoreValue::MapValue(Z_Param_Value); P_NATIVE_END; } DEFINE_FUNCTION(UFirestoreValue::execArrayValue) { P_GET_STRUCT(FJsonValueB,Z_Param_Value); P_FINISH; P_NATIVE_BEGIN; *(TArray<FJsonValueB>*)Z_Param__Result=UFirestoreValue::ArrayValue(Z_Param_Value); P_NATIVE_END; } DEFINE_FUNCTION(UFirestoreValue::execGeoPointValue) { P_GET_STRUCT(FJsonValueB,Z_Param_Value); P_FINISH; P_NATIVE_BEGIN; *(FGeoPoint*)Z_Param__Result=UFirestoreValue::GeoPointValue(Z_Param_Value); P_NATIVE_END; } DEFINE_FUNCTION(UFirestoreValue::execReferenceValue) { P_GET_STRUCT(FJsonValueB,Z_Param_Value); P_FINISH; P_NATIVE_BEGIN; *(FString*)Z_Param__Result=UFirestoreValue::ReferenceValue(Z_Param_Value); P_NATIVE_END; } DEFINE_FUNCTION(UFirestoreValue::execBytesValue) { P_GET_STRUCT(FJsonValueB,Z_Param_Value); P_FINISH; P_NATIVE_BEGIN; *(FString*)Z_Param__Result=UFirestoreValue::BytesValue(Z_Param_Value); P_NATIVE_END; } DEFINE_FUNCTION(UFirestoreValue::execStringValue) { P_GET_STRUCT(FJsonValueB,Z_Param_Value); P_FINISH; P_NATIVE_BEGIN; *(FString*)Z_Param__Result=UFirestoreValue::StringValue(Z_Param_Value); P_NATIVE_END; } DEFINE_FUNCTION(UFirestoreValue::execTimestampValue) { P_GET_STRUCT(FJsonValueB,Z_Param_Value); P_FINISH; P_NATIVE_BEGIN; *(FString*)Z_Param__Result=UFirestoreValue::TimestampValue(Z_Param_Value); P_NATIVE_END; } DEFINE_FUNCTION(UFirestoreValue::execFloatValue) { P_GET_STRUCT(FJsonValueB,Z_Param_Value); P_FINISH; P_NATIVE_BEGIN; *(float*)Z_Param__Result=UFirestoreValue::FloatValue(Z_Param_Value); P_NATIVE_END; } DEFINE_FUNCTION(UFirestoreValue::execIntegerValue) { P_GET_STRUCT(FJsonValueB,Z_Param_Value); P_FINISH; P_NATIVE_BEGIN; *(int64*)Z_Param__Result=UFirestoreValue::IntegerValue(Z_Param_Value); P_NATIVE_END; } DEFINE_FUNCTION(UFirestoreValue::execBooleanValue) { P_GET_STRUCT(FJsonValueB,Z_Param_Value); P_FINISH; P_NATIVE_BEGIN; *(bool*)Z_Param__Result=UFirestoreValue::BooleanValue(Z_Param_Value); P_NATIVE_END; } void UFirestoreValue::StaticRegisterNativesUFirestoreValue() { UClass* Class = UFirestoreValue::StaticClass(); static const FNameNativePtrPair Funcs[] = { { "ArrayValue", &UFirestoreValue::execArrayValue }, { "BooleanValue", &UFirestoreValue::execBooleanValue }, { "BytesValue", &UFirestoreValue::execBytesValue }, { "FloatValue", &UFirestoreValue::execFloatValue }, { "GeoPointValue", &UFirestoreValue::execGeoPointValue }, { "IntegerValue", &UFirestoreValue::execIntegerValue }, { "MapValue", &UFirestoreValue::execMapValue }, { "ReferenceValue", &UFirestoreValue::execReferenceValue }, { "StringValue", &UFirestoreValue::execStringValue }, { "TimestampValue", &UFirestoreValue::execTimestampValue }, }; FNativeFunctionRegistrar::RegisterFunctions(Class, Funcs, UE_ARRAY_COUNT(Funcs)); } struct Z_Construct_UFunction_UFirestoreValue_ArrayValue_Statics { struct FirestoreValue_eventArrayValue_Parms { FJsonValueB Value; TArray<FJsonValueB> ReturnValue; }; static const UE4CodeGen_Private::FStructPropertyParams NewProp_Value; static const UE4CodeGen_Private::FStructPropertyParams NewProp_ReturnValue_Inner; static const UE4CodeGen_Private::FArrayPropertyParams NewProp_ReturnValue; static const UE4CodeGen_Private::FPropertyParamsBase* const PropPointers[]; #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam Function_MetaDataParams[]; #endif static const UE4CodeGen_Private::FFunctionParams FuncParams; }; const UE4CodeGen_Private::FStructPropertyParams Z_Construct_UFunction_UFirestoreValue_ArrayValue_Statics::NewProp_Value = { "Value", nullptr, (EPropertyFlags)0x0010000000000080, UE4CodeGen_Private::EPropertyGenFlags::Struct, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(FirestoreValue_eventArrayValue_Parms, Value), Z_Construct_UScriptStruct_FJsonValueB, METADATA_PARAMS(nullptr, 0) }; const UE4CodeGen_Private::FStructPropertyParams Z_Construct_UFunction_UFirestoreValue_ArrayValue_Statics::NewProp_ReturnValue_Inner = { "ReturnValue", nullptr, (EPropertyFlags)0x0000000000000000, UE4CodeGen_Private::EPropertyGenFlags::Struct, RF_Public|RF_Transient|RF_MarkAsNative, 1, 0, Z_Construct_UScriptStruct_FJsonValueB, METADATA_PARAMS(nullptr, 0) }; const UE4CodeGen_Private::FArrayPropertyParams Z_Construct_UFunction_UFirestoreValue_ArrayValue_Statics::NewProp_ReturnValue = { "ReturnValue", nullptr, (EPropertyFlags)0x0010000000000580, UE4CodeGen_Private::EPropertyGenFlags::Array, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(FirestoreValue_eventArrayValue_Parms, ReturnValue), EArrayPropertyFlags::None, METADATA_PARAMS(nullptr, 0) }; const UE4CodeGen_Private::FPropertyParamsBase* const Z_Construct_UFunction_UFirestoreValue_ArrayValue_Statics::PropPointers[] = { (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UFunction_UFirestoreValue_ArrayValue_Statics::NewProp_Value, (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UFunction_UFirestoreValue_ArrayValue_Statics::NewProp_ReturnValue_Inner, (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UFunction_UFirestoreValue_ArrayValue_Statics::NewProp_ReturnValue, }; #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UFunction_UFirestoreValue_ArrayValue_Statics::Function_MetaDataParams[] = { { "Category", "CloudFirestore" }, { "Comment", "//Object (ArrayValue) An array value. Cannot directly contain another array value, though can contain an map which contains another array.\n" }, { "DisplayName", "Get Array of Firestore Values" }, { "Keywords", "Cloud Firestore Boolean" }, { "ModuleRelativePath", "Public/FirestoreValue.h" }, { "ToolTip", "Object (ArrayValue) An array value. Cannot directly contain another array value, though can contain an map which contains another array." }, }; #endif const UE4CodeGen_Private::FFunctionParams Z_Construct_UFunction_UFirestoreValue_ArrayValue_Statics::FuncParams = { (UObject*(*)())Z_Construct_UClass_UFirestoreValue, nullptr, "ArrayValue", nullptr, nullptr, sizeof(FirestoreValue_eventArrayValue_Parms), Z_Construct_UFunction_UFirestoreValue_ArrayValue_Statics::PropPointers, UE_ARRAY_COUNT(Z_Construct_UFunction_UFirestoreValue_ArrayValue_Statics::PropPointers), RF_Public|RF_Transient|RF_MarkAsNative, (EFunctionFlags)0x04022401, 0, 0, METADATA_PARAMS(Z_Construct_UFunction_UFirestoreValue_ArrayValue_Statics::Function_MetaDataParams, UE_ARRAY_COUNT(Z_Construct_UFunction_UFirestoreValue_ArrayValue_Statics::Function_MetaDataParams)) }; UFunction* Z_Construct_UFunction_UFirestoreValue_ArrayValue() { static UFunction* ReturnFunction = nullptr; if (!ReturnFunction) { UE4CodeGen_Private::ConstructUFunction(ReturnFunction, Z_Construct_UFunction_UFirestoreValue_ArrayValue_Statics::FuncParams); } return ReturnFunction; } struct Z_Construct_UFunction_UFirestoreValue_BooleanValue_Statics { struct FirestoreValue_eventBooleanValue_Parms { FJsonValueB Value; bool ReturnValue; }; static const UE4CodeGen_Private::FStructPropertyParams NewProp_Value; static void NewProp_ReturnValue_SetBit(void* Obj); static const UE4CodeGen_Private::FBoolPropertyParams NewProp_ReturnValue; static const UE4CodeGen_Private::FPropertyParamsBase* const PropPointers[]; #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam Function_MetaDataParams[]; #endif static const UE4CodeGen_Private::FFunctionParams FuncParams; }; const UE4CodeGen_Private::FStructPropertyParams Z_Construct_UFunction_UFirestoreValue_BooleanValue_Statics::NewProp_Value = { "Value", nullptr, (EPropertyFlags)0x0010000000000080, UE4CodeGen_Private::EPropertyGenFlags::Struct, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(FirestoreValue_eventBooleanValue_Parms, Value), Z_Construct_UScriptStruct_FJsonValueB, METADATA_PARAMS(nullptr, 0) }; void Z_Construct_UFunction_UFirestoreValue_BooleanValue_Statics::NewProp_ReturnValue_SetBit(void* Obj) { ((FirestoreValue_eventBooleanValue_Parms*)Obj)->ReturnValue = 1; } const UE4CodeGen_Private::FBoolPropertyParams Z_Construct_UFunction_UFirestoreValue_BooleanValue_Statics::NewProp_ReturnValue = { "ReturnValue", nullptr, (EPropertyFlags)0x0010000000000580, UE4CodeGen_Private::EPropertyGenFlags::Bool | UE4CodeGen_Private::EPropertyGenFlags::NativeBool, RF_Public|RF_Transient|RF_MarkAsNative, 1, sizeof(bool), sizeof(FirestoreValue_eventBooleanValue_Parms), &Z_Construct_UFunction_UFirestoreValue_BooleanValue_Statics::NewProp_ReturnValue_SetBit, METADATA_PARAMS(nullptr, 0) }; const UE4CodeGen_Private::FPropertyParamsBase* const Z_Construct_UFunction_UFirestoreValue_BooleanValue_Statics::PropPointers[] = { (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UFunction_UFirestoreValue_BooleanValue_Statics::NewProp_Value, (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UFunction_UFirestoreValue_BooleanValue_Statics::NewProp_ReturnValue, }; #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UFunction_UFirestoreValue_BooleanValue_Statics::Function_MetaDataParams[] = { { "Category", "CloudFirestore" }, { "Comment", "//A boolean value.\n" }, { "DisplayName", "Get Boolean Value" }, { "Keywords", "Cloud Firestore Boolean" }, { "ModuleRelativePath", "Public/FirestoreValue.h" }, { "ToolTip", "A boolean value." }, }; #endif const UE4CodeGen_Private::FFunctionParams Z_Construct_UFunction_UFirestoreValue_BooleanValue_Statics::FuncParams = { (UObject*(*)())Z_Construct_UClass_UFirestoreValue, nullptr, "BooleanValue", nullptr, nullptr, sizeof(FirestoreValue_eventBooleanValue_Parms), Z_Construct_UFunction_UFirestoreValue_BooleanValue_Statics::PropPointers, UE_ARRAY_COUNT(Z_Construct_UFunction_UFirestoreValue_BooleanValue_Statics::PropPointers), RF_Public|RF_Transient|RF_MarkAsNative, (EFunctionFlags)0x04022401, 0, 0, METADATA_PARAMS(Z_Construct_UFunction_UFirestoreValue_BooleanValue_Statics::Function_MetaDataParams, UE_ARRAY_COUNT(Z_Construct_UFunction_UFirestoreValue_BooleanValue_Statics::Function_MetaDataParams)) }; UFunction* Z_Construct_UFunction_UFirestoreValue_BooleanValue() { static UFunction* ReturnFunction = nullptr; if (!ReturnFunction) { UE4CodeGen_Private::ConstructUFunction(ReturnFunction, Z_Construct_UFunction_UFirestoreValue_BooleanValue_Statics::FuncParams); } return ReturnFunction; } struct Z_Construct_UFunction_UFirestoreValue_BytesValue_Statics { struct FirestoreValue_eventBytesValue_Parms { FJsonValueB Value; FString ReturnValue; }; static const UE4CodeGen_Private::FStructPropertyParams NewProp_Value; static const UE4CodeGen_Private::FStrPropertyParams NewProp_ReturnValue; static const UE4CodeGen_Private::FPropertyParamsBase* const PropPointers[]; #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam Function_MetaDataParams[]; #endif static const UE4CodeGen_Private::FFunctionParams FuncParams; }; const UE4CodeGen_Private::FStructPropertyParams Z_Construct_UFunction_UFirestoreValue_BytesValue_Statics::NewProp_Value = { "Value", nullptr, (EPropertyFlags)0x0010000000000080, UE4CodeGen_Private::EPropertyGenFlags::Struct, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(FirestoreValue_eventBytesValue_Parms, Value), Z_Construct_UScriptStruct_FJsonValueB, METADATA_PARAMS(nullptr, 0) }; const UE4CodeGen_Private::FStrPropertyParams Z_Construct_UFunction_UFirestoreValue_BytesValue_Statics::NewProp_ReturnValue = { "ReturnValue", nullptr, (EPropertyFlags)0x0010000000000580, UE4CodeGen_Private::EPropertyGenFlags::Str, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(FirestoreValue_eventBytesValue_Parms, ReturnValue), METADATA_PARAMS(nullptr, 0) }; const UE4CodeGen_Private::FPropertyParamsBase* const Z_Construct_UFunction_UFirestoreValue_BytesValue_Statics::PropPointers[] = { (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UFunction_UFirestoreValue_BytesValue_Statics::NewProp_Value, (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UFunction_UFirestoreValue_BytesValue_Statics::NewProp_ReturnValue, }; #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UFunction_UFirestoreValue_BytesValue_Statics::Function_MetaDataParams[] = { { "Category", "CloudFirestore" }, { "Comment", "//String (bytes format). A bytes value. Must not exceed 1 MiB - 89 bytes. Only the first 1,500 bytes are considered by queries. A base64-encoded string.\n" }, { "DisplayName", "Get Bytes Value" }, { "Keywords", "Cloud Firestore Boolean" }, { "ModuleRelativePath", "Public/FirestoreValue.h" }, { "ToolTip", "String (bytes format). A bytes value. Must not exceed 1 MiB - 89 bytes. Only the first 1,500 bytes are considered by queries. A base64-encoded string." }, }; #endif const UE4CodeGen_Private::FFunctionParams Z_Construct_UFunction_UFirestoreValue_BytesValue_Statics::FuncParams = { (UObject*(*)())Z_Construct_UClass_UFirestoreValue, nullptr, "BytesValue", nullptr, nullptr, sizeof(FirestoreValue_eventBytesValue_Parms), Z_Construct_UFunction_UFirestoreValue_BytesValue_Statics::PropPointers, UE_ARRAY_COUNT(Z_Construct_UFunction_UFirestoreValue_BytesValue_Statics::PropPointers), RF_Public|RF_Transient|RF_MarkAsNative, (EFunctionFlags)0x04022401, 0, 0, METADATA_PARAMS(Z_Construct_UFunction_UFirestoreValue_BytesValue_Statics::Function_MetaDataParams, UE_ARRAY_COUNT(Z_Construct_UFunction_UFirestoreValue_BytesValue_Statics::Function_MetaDataParams)) }; UFunction* Z_Construct_UFunction_UFirestoreValue_BytesValue() { static UFunction* ReturnFunction = nullptr; if (!ReturnFunction) { UE4CodeGen_Private::ConstructUFunction(ReturnFunction, Z_Construct_UFunction_UFirestoreValue_BytesValue_Statics::FuncParams); } return ReturnFunction; } struct Z_Construct_UFunction_UFirestoreValue_FloatValue_Statics { struct FirestoreValue_eventFloatValue_Parms { FJsonValueB Value; float ReturnValue; }; static const UE4CodeGen_Private::FStructPropertyParams NewProp_Value; static const UE4CodeGen_Private::FFloatPropertyParams NewProp_ReturnValue; static const UE4CodeGen_Private::FPropertyParamsBase* const PropPointers[]; #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam Function_MetaDataParams[]; #endif static const UE4CodeGen_Private::FFunctionParams FuncParams; }; const UE4CodeGen_Private::FStructPropertyParams Z_Construct_UFunction_UFirestoreValue_FloatValue_Statics::NewProp_Value = { "Value", nullptr, (EPropertyFlags)0x0010000000000080, UE4CodeGen_Private::EPropertyGenFlags::Struct, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(FirestoreValue_eventFloatValue_Parms, Value), Z_Construct_UScriptStruct_FJsonValueB, METADATA_PARAMS(nullptr, 0) }; const UE4CodeGen_Private::FFloatPropertyParams Z_Construct_UFunction_UFirestoreValue_FloatValue_Statics::NewProp_ReturnValue = { "ReturnValue", nullptr, (EPropertyFlags)0x0010000000000580, UE4CodeGen_Private::EPropertyGenFlags::Float, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(FirestoreValue_eventFloatValue_Parms, ReturnValue), METADATA_PARAMS(nullptr, 0) }; const UE4CodeGen_Private::FPropertyParamsBase* const Z_Construct_UFunction_UFirestoreValue_FloatValue_Statics::PropPointers[] = { (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UFunction_UFirestoreValue_FloatValue_Statics::NewProp_Value, (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UFunction_UFirestoreValue_FloatValue_Statics::NewProp_ReturnValue, }; #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UFunction_UFirestoreValue_FloatValue_Statics::Function_MetaDataParams[] = { { "Category", "CloudFirestore" }, { "Comment", "//number - A double value.\n" }, { "DisplayName", "Get Float Value" }, { "Keywords", "Cloud Firestore Boolean" }, { "ModuleRelativePath", "Public/FirestoreValue.h" }, { "ToolTip", "number - A double value." }, }; #endif const UE4CodeGen_Private::FFunctionParams Z_Construct_UFunction_UFirestoreValue_FloatValue_Statics::FuncParams = { (UObject*(*)())Z_Construct_UClass_UFirestoreValue, nullptr, "FloatValue", nullptr, nullptr, sizeof(FirestoreValue_eventFloatValue_Parms), Z_Construct_UFunction_UFirestoreValue_FloatValue_Statics::PropPointers, UE_ARRAY_COUNT(Z_Construct_UFunction_UFirestoreValue_FloatValue_Statics::PropPointers), RF_Public|RF_Transient|RF_MarkAsNative, (EFunctionFlags)0x04022401, 0, 0, METADATA_PARAMS(Z_Construct_UFunction_UFirestoreValue_FloatValue_Statics::Function_MetaDataParams, UE_ARRAY_COUNT(Z_Construct_UFunction_UFirestoreValue_FloatValue_Statics::Function_MetaDataParams)) }; UFunction* Z_Construct_UFunction_UFirestoreValue_FloatValue() { static UFunction* ReturnFunction = nullptr; if (!ReturnFunction) { UE4CodeGen_Private::ConstructUFunction(ReturnFunction, Z_Construct_UFunction_UFirestoreValue_FloatValue_Statics::FuncParams); } return ReturnFunction; } struct Z_Construct_UFunction_UFirestoreValue_GeoPointValue_Statics { struct FirestoreValue_eventGeoPointValue_Parms { FJsonValueB Value; FGeoPoint ReturnValue; }; static const UE4CodeGen_Private::FStructPropertyParams NewProp_Value; static const UE4CodeGen_Private::FStructPropertyParams NewProp_ReturnValue; static const UE4CodeGen_Private::FPropertyParamsBase* const PropPointers[]; #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam Function_MetaDataParams[]; #endif static const UE4CodeGen_Private::FFunctionParams FuncParams; }; const UE4CodeGen_Private::FStructPropertyParams Z_Construct_UFunction_UFirestoreValue_GeoPointValue_Statics::NewProp_Value = { "Value", nullptr, (EPropertyFlags)0x0010000000000080, UE4CodeGen_Private::EPropertyGenFlags::Struct, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(FirestoreValue_eventGeoPointValue_Parms, Value), Z_Construct_UScriptStruct_FJsonValueB, METADATA_PARAMS(nullptr, 0) }; const UE4CodeGen_Private::FStructPropertyParams Z_Construct_UFunction_UFirestoreValue_GeoPointValue_Statics::NewProp_ReturnValue = { "ReturnValue", nullptr, (EPropertyFlags)0x0010000000000580, UE4CodeGen_Private::EPropertyGenFlags::Struct, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(FirestoreValue_eventGeoPointValue_Parms, ReturnValue), Z_Construct_UScriptStruct_FGeoPoint, METADATA_PARAMS(nullptr, 0) }; const UE4CodeGen_Private::FPropertyParamsBase* const Z_Construct_UFunction_UFirestoreValue_GeoPointValue_Statics::PropPointers[] = { (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UFunction_UFirestoreValue_GeoPointValue_Statics::NewProp_Value, (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UFunction_UFirestoreValue_GeoPointValue_Statics::NewProp_ReturnValue, }; #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UFunction_UFirestoreValue_GeoPointValue_Statics::Function_MetaDataParams[] = { { "Category", "CloudFirestore" }, { "Comment", "//Object (LatLng) A geo point value representing a point on the surface of Earth.\n" }, { "DisplayName", "Get GeoPoint Value" }, { "Keywords", "Cloud Firestore Boolean" }, { "ModuleRelativePath", "Public/FirestoreValue.h" }, { "ToolTip", "Object (LatLng) A geo point value representing a point on the surface of Earth." }, }; #endif const UE4CodeGen_Private::FFunctionParams Z_Construct_UFunction_UFirestoreValue_GeoPointValue_Statics::FuncParams = { (UObject*(*)())Z_Construct_UClass_UFirestoreValue, nullptr, "GeoPointValue", nullptr, nullptr, sizeof(FirestoreValue_eventGeoPointValue_Parms), Z_Construct_UFunction_UFirestoreValue_GeoPointValue_Statics::PropPointers, UE_ARRAY_COUNT(Z_Construct_UFunction_UFirestoreValue_GeoPointValue_Statics::PropPointers), RF_Public|RF_Transient|RF_MarkAsNative, (EFunctionFlags)0x04022401, 0, 0, METADATA_PARAMS(Z_Construct_UFunction_UFirestoreValue_GeoPointValue_Statics::Function_MetaDataParams, UE_ARRAY_COUNT(Z_Construct_UFunction_UFirestoreValue_GeoPointValue_Statics::Function_MetaDataParams)) }; UFunction* Z_Construct_UFunction_UFirestoreValue_GeoPointValue() { static UFunction* ReturnFunction = nullptr; if (!ReturnFunction) { UE4CodeGen_Private::ConstructUFunction(ReturnFunction, Z_Construct_UFunction_UFirestoreValue_GeoPointValue_Statics::FuncParams); } return ReturnFunction; } struct Z_Construct_UFunction_UFirestoreValue_IntegerValue_Statics { struct FirestoreValue_eventIntegerValue_Parms { FJsonValueB Value; int64 ReturnValue; }; static const UE4CodeGen_Private::FStructPropertyParams NewProp_Value; static const UE4CodeGen_Private::FInt64PropertyParams NewProp_ReturnValue; static const UE4CodeGen_Private::FPropertyParamsBase* const PropPointers[]; #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam Function_MetaDataParams[]; #endif static const UE4CodeGen_Private::FFunctionParams FuncParams; }; const UE4CodeGen_Private::FStructPropertyParams Z_Construct_UFunction_UFirestoreValue_IntegerValue_Statics::NewProp_Value = { "Value", nullptr, (EPropertyFlags)0x0010000000000080, UE4CodeGen_Private::EPropertyGenFlags::Struct, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(FirestoreValue_eventIntegerValue_Parms, Value), Z_Construct_UScriptStruct_FJsonValueB, METADATA_PARAMS(nullptr, 0) }; const UE4CodeGen_Private::FInt64PropertyParams Z_Construct_UFunction_UFirestoreValue_IntegerValue_Statics::NewProp_ReturnValue = { "ReturnValue", nullptr, (EPropertyFlags)0x0010000000000580, UE4CodeGen_Private::EPropertyGenFlags::Int64, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(FirestoreValue_eventIntegerValue_Parms, ReturnValue), METADATA_PARAMS(nullptr, 0) }; const UE4CodeGen_Private::FPropertyParamsBase* const Z_Construct_UFunction_UFirestoreValue_IntegerValue_Statics::PropPointers[] = { (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UFunction_UFirestoreValue_IntegerValue_Statics::NewProp_Value, (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UFunction_UFirestoreValue_IntegerValue_Statics::NewProp_ReturnValue, }; #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UFunction_UFirestoreValue_IntegerValue_Statics::Function_MetaDataParams[] = { { "Category", "CloudFirestore" }, { "Comment", "//string (int64 format) An integer value.\n" }, { "DisplayName", "Get Integer Value" }, { "Keywords", "Cloud Firestore Boolean" }, { "ModuleRelativePath", "Public/FirestoreValue.h" }, { "ToolTip", "string (int64 format) An integer value." }, }; #endif const UE4CodeGen_Private::FFunctionParams Z_Construct_UFunction_UFirestoreValue_IntegerValue_Statics::FuncParams = { (UObject*(*)())Z_Construct_UClass_UFirestoreValue, nullptr, "IntegerValue", nullptr, nullptr, sizeof(FirestoreValue_eventIntegerValue_Parms), Z_Construct_UFunction_UFirestoreValue_IntegerValue_Statics::PropPointers, UE_ARRAY_COUNT(Z_Construct_UFunction_UFirestoreValue_IntegerValue_Statics::PropPointers), RF_Public|RF_Transient|RF_MarkAsNative, (EFunctionFlags)0x04022401, 0, 0, METADATA_PARAMS(Z_Construct_UFunction_UFirestoreValue_IntegerValue_Statics::Function_MetaDataParams, UE_ARRAY_COUNT(Z_Construct_UFunction_UFirestoreValue_IntegerValue_Statics::Function_MetaDataParams)) }; UFunction* Z_Construct_UFunction_UFirestoreValue_IntegerValue() { static UFunction* ReturnFunction = nullptr; if (!ReturnFunction) { UE4CodeGen_Private::ConstructUFunction(ReturnFunction, Z_Construct_UFunction_UFirestoreValue_IntegerValue_Statics::FuncParams); } return ReturnFunction; } struct Z_Construct_UFunction_UFirestoreValue_MapValue_Statics { struct FirestoreValue_eventMapValue_Parms { FJsonValueB Value; TMap<FString,FJsonValueB> ReturnValue; }; static const UE4CodeGen_Private::FStructPropertyParams NewProp_Value; static const UE4CodeGen_Private::FStructPropertyParams NewProp_ReturnValue_ValueProp; static const UE4CodeGen_Private::FStrPropertyParams NewProp_ReturnValue_Key_KeyProp; static const UE4CodeGen_Private::FMapPropertyParams NewProp_ReturnValue; static const UE4CodeGen_Private::FPropertyParamsBase* const PropPointers[]; #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam Function_MetaDataParams[]; #endif static const UE4CodeGen_Private::FFunctionParams FuncParams; }; const UE4CodeGen_Private::FStructPropertyParams Z_Construct_UFunction_UFirestoreValue_MapValue_Statics::NewProp_Value = { "Value", nullptr, (EPropertyFlags)0x0010000000000080, UE4CodeGen_Private::EPropertyGenFlags::Struct, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(FirestoreValue_eventMapValue_Parms, Value), Z_Construct_UScriptStruct_FJsonValueB, METADATA_PARAMS(nullptr, 0) }; const UE4CodeGen_Private::FStructPropertyParams Z_Construct_UFunction_UFirestoreValue_MapValue_Statics::NewProp_ReturnValue_ValueProp = { "ReturnValue", nullptr, (EPropertyFlags)0x0000000000000000, UE4CodeGen_Private::EPropertyGenFlags::Struct, RF_Public|RF_Transient|RF_MarkAsNative, 1, 1, Z_Construct_UScriptStruct_FJsonValueB, METADATA_PARAMS(nullptr, 0) }; const UE4CodeGen_Private::FStrPropertyParams Z_Construct_UFunction_UFirestoreValue_MapValue_Statics::NewProp_ReturnValue_Key_KeyProp = { "ReturnValue_Key", nullptr, (EPropertyFlags)0x0000000000000000, UE4CodeGen_Private::EPropertyGenFlags::Str, RF_Public|RF_Transient|RF_MarkAsNative, 1, 0, METADATA_PARAMS(nullptr, 0) }; const UE4CodeGen_Private::FMapPropertyParams Z_Construct_UFunction_UFirestoreValue_MapValue_Statics::NewProp_ReturnValue = { "ReturnValue", nullptr, (EPropertyFlags)0x0010000000000580, UE4CodeGen_Private::EPropertyGenFlags::Map, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(FirestoreValue_eventMapValue_Parms, ReturnValue), EMapPropertyFlags::None, METADATA_PARAMS(nullptr, 0) }; const UE4CodeGen_Private::FPropertyParamsBase* const Z_Construct_UFunction_UFirestoreValue_MapValue_Statics::PropPointers[] = { (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UFunction_UFirestoreValue_MapValue_Statics::NewProp_Value, (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UFunction_UFirestoreValue_MapValue_Statics::NewProp_ReturnValue_ValueProp, (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UFunction_UFirestoreValue_MapValue_Statics::NewProp_ReturnValue_Key_KeyProp, (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UFunction_UFirestoreValue_MapValue_Statics::NewProp_ReturnValue, }; #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UFunction_UFirestoreValue_MapValue_Statics::Function_MetaDataParams[] = { { "Category", "CloudFirestore" }, { "Comment", "//Object (MapValue). A map value.\n" }, { "DisplayName", "Get Map of String-Firestore Value" }, { "Keywords", "Cloud Firestore Boolean" }, { "ModuleRelativePath", "Public/FirestoreValue.h" }, { "ToolTip", "Object (MapValue). A map value." }, }; #endif const UE4CodeGen_Private::FFunctionParams Z_Construct_UFunction_UFirestoreValue_MapValue_Statics::FuncParams = { (UObject*(*)())Z_Construct_UClass_UFirestoreValue, nullptr, "MapValue", nullptr, nullptr, sizeof(FirestoreValue_eventMapValue_Parms), Z_Construct_UFunction_UFirestoreValue_MapValue_Statics::PropPointers, UE_ARRAY_COUNT(Z_Construct_UFunction_UFirestoreValue_MapValue_Statics::PropPointers), RF_Public|RF_Transient|RF_MarkAsNative, (EFunctionFlags)0x04022401, 0, 0, METADATA_PARAMS(Z_Construct_UFunction_UFirestoreValue_MapValue_Statics::Function_MetaDataParams, UE_ARRAY_COUNT(Z_Construct_UFunction_UFirestoreValue_MapValue_Statics::Function_MetaDataParams)) }; UFunction* Z_Construct_UFunction_UFirestoreValue_MapValue() { static UFunction* ReturnFunction = nullptr; if (!ReturnFunction) { UE4CodeGen_Private::ConstructUFunction(ReturnFunction, Z_Construct_UFunction_UFirestoreValue_MapValue_Statics::FuncParams); } return ReturnFunction; } struct Z_Construct_UFunction_UFirestoreValue_ReferenceValue_Statics { struct FirestoreValue_eventReferenceValue_Parms { FJsonValueB Value; FString ReturnValue; }; static const UE4CodeGen_Private::FStructPropertyParams NewProp_Value; static const UE4CodeGen_Private::FStrPropertyParams NewProp_ReturnValue; static const UE4CodeGen_Private::FPropertyParamsBase* const PropPointers[]; #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam Function_MetaDataParams[]; #endif static const UE4CodeGen_Private::FFunctionParams FuncParams; }; const UE4CodeGen_Private::FStructPropertyParams Z_Construct_UFunction_UFirestoreValue_ReferenceValue_Statics::NewProp_Value = { "Value", nullptr, (EPropertyFlags)0x0010000000000080, UE4CodeGen_Private::EPropertyGenFlags::Struct, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(FirestoreValue_eventReferenceValue_Parms, Value), Z_Construct_UScriptStruct_FJsonValueB, METADATA_PARAMS(nullptr, 0) }; const UE4CodeGen_Private::FStrPropertyParams Z_Construct_UFunction_UFirestoreValue_ReferenceValue_Statics::NewProp_ReturnValue = { "ReturnValue", nullptr, (EPropertyFlags)0x0010000000000580, UE4CodeGen_Private::EPropertyGenFlags::Str, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(FirestoreValue_eventReferenceValue_Parms, ReturnValue), METADATA_PARAMS(nullptr, 0) }; const UE4CodeGen_Private::FPropertyParamsBase* const Z_Construct_UFunction_UFirestoreValue_ReferenceValue_Statics::PropPointers[] = { (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UFunction_UFirestoreValue_ReferenceValue_Statics::NewProp_Value, (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UFunction_UFirestoreValue_ReferenceValue_Statics::NewProp_ReturnValue, }; #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UFunction_UFirestoreValue_ReferenceValue_Statics::Function_MetaDataParams[] = { { "Category", "CloudFirestore" }, { "Comment", "//A reference to a document. For example: projects/{project_id}/databases/{database_id}/documents/{document_path}.\n" }, { "DisplayName", "Get Reference Value" }, { "Keywords", "Cloud Firestore Boolean" }, { "ModuleRelativePath", "Public/FirestoreValue.h" }, { "ToolTip", "A reference to a document. For example: projects/{project_id}/databases/{database_id}/documents/{document_path}." }, }; #endif const UE4CodeGen_Private::FFunctionParams Z_Construct_UFunction_UFirestoreValue_ReferenceValue_Statics::FuncParams = { (UObject*(*)())Z_Construct_UClass_UFirestoreValue, nullptr, "ReferenceValue", nullptr, nullptr, sizeof(FirestoreValue_eventReferenceValue_Parms), Z_Construct_UFunction_UFirestoreValue_ReferenceValue_Statics::PropPointers, UE_ARRAY_COUNT(Z_Construct_UFunction_UFirestoreValue_ReferenceValue_Statics::PropPointers), RF_Public|RF_Transient|RF_MarkAsNative, (EFunctionFlags)0x04022401, 0, 0, METADATA_PARAMS(Z_Construct_UFunction_UFirestoreValue_ReferenceValue_Statics::Function_MetaDataParams, UE_ARRAY_COUNT(Z_Construct_UFunction_UFirestoreValue_ReferenceValue_Statics::Function_MetaDataParams)) }; UFunction* Z_Construct_UFunction_UFirestoreValue_ReferenceValue() { static UFunction* ReturnFunction = nullptr; if (!ReturnFunction) { UE4CodeGen_Private::ConstructUFunction(ReturnFunction, Z_Construct_UFunction_UFirestoreValue_ReferenceValue_Statics::FuncParams); } return ReturnFunction; } struct Z_Construct_UFunction_UFirestoreValue_StringValue_Statics { struct FirestoreValue_eventStringValue_Parms { FJsonValueB Value; FString ReturnValue; }; static const UE4CodeGen_Private::FStructPropertyParams NewProp_Value; static const UE4CodeGen_Private::FStrPropertyParams NewProp_ReturnValue; static const UE4CodeGen_Private::FPropertyParamsBase* const PropPointers[]; #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam Function_MetaDataParams[]; #endif static const UE4CodeGen_Private::FFunctionParams FuncParams; }; const UE4CodeGen_Private::FStructPropertyParams Z_Construct_UFunction_UFirestoreValue_StringValue_Statics::NewProp_Value = { "Value", nullptr, (EPropertyFlags)0x0010000000000080, UE4CodeGen_Private::EPropertyGenFlags::Struct, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(FirestoreValue_eventStringValue_Parms, Value), Z_Construct_UScriptStruct_FJsonValueB, METADATA_PARAMS(nullptr, 0) }; const UE4CodeGen_Private::FStrPropertyParams Z_Construct_UFunction_UFirestoreValue_StringValue_Statics::NewProp_ReturnValue = { "ReturnValue", nullptr, (EPropertyFlags)0x0010000000000580, UE4CodeGen_Private::EPropertyGenFlags::Str, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(FirestoreValue_eventStringValue_Parms, ReturnValue), METADATA_PARAMS(nullptr, 0) }; const UE4CodeGen_Private::FPropertyParamsBase* const Z_Construct_UFunction_UFirestoreValue_StringValue_Statics::PropPointers[] = { (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UFunction_UFirestoreValue_StringValue_Statics::NewProp_Value, (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UFunction_UFirestoreValue_StringValue_Statics::NewProp_ReturnValue, }; #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UFunction_UFirestoreValue_StringValue_Statics::Function_MetaDataParams[] = { { "Category", "CloudFirestore" }, { "Comment", "//A string value. The string, represented as UTF-8, must not exceed 1 MiB - 89 bytes. Only the first 1,500 bytes of the UTF-8 representation are considered by queries.\n" }, { "DisplayName", "Get String Value" }, { "Keywords", "Cloud Firestore Boolean" }, { "ModuleRelativePath", "Public/FirestoreValue.h" }, { "ToolTip", "A string value. The string, represented as UTF-8, must not exceed 1 MiB - 89 bytes. Only the first 1,500 bytes of the UTF-8 representation are considered by queries." }, }; #endif const UE4CodeGen_Private::FFunctionParams Z_Construct_UFunction_UFirestoreValue_StringValue_Statics::FuncParams = { (UObject*(*)())Z_Construct_UClass_UFirestoreValue, nullptr, "StringValue", nullptr, nullptr, sizeof(FirestoreValue_eventStringValue_Parms), Z_Construct_UFunction_UFirestoreValue_StringValue_Statics::PropPointers, UE_ARRAY_COUNT(Z_Construct_UFunction_UFirestoreValue_StringValue_Statics::PropPointers), RF_Public|RF_Transient|RF_MarkAsNative, (EFunctionFlags)0x04022401, 0, 0, METADATA_PARAMS(Z_Construct_UFunction_UFirestoreValue_StringValue_Statics::Function_MetaDataParams, UE_ARRAY_COUNT(Z_Construct_UFunction_UFirestoreValue_StringValue_Statics::Function_MetaDataParams)) }; UFunction* Z_Construct_UFunction_UFirestoreValue_StringValue() { static UFunction* ReturnFunction = nullptr; if (!ReturnFunction) { UE4CodeGen_Private::ConstructUFunction(ReturnFunction, Z_Construct_UFunction_UFirestoreValue_StringValue_Statics::FuncParams); } return ReturnFunction; } struct Z_Construct_UFunction_UFirestoreValue_TimestampValue_Statics { struct FirestoreValue_eventTimestampValue_Parms { FJsonValueB Value; FString ReturnValue; }; static const UE4CodeGen_Private::FStructPropertyParams NewProp_Value; static const UE4CodeGen_Private::FStrPropertyParams NewProp_ReturnValue; static const UE4CodeGen_Private::FPropertyParamsBase* const PropPointers[]; #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam Function_MetaDataParams[]; #endif static const UE4CodeGen_Private::FFunctionParams FuncParams; }; const UE4CodeGen_Private::FStructPropertyParams Z_Construct_UFunction_UFirestoreValue_TimestampValue_Statics::NewProp_Value = { "Value", nullptr, (EPropertyFlags)0x0010000000000080, UE4CodeGen_Private::EPropertyGenFlags::Struct, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(FirestoreValue_eventTimestampValue_Parms, Value), Z_Construct_UScriptStruct_FJsonValueB, METADATA_PARAMS(nullptr, 0) }; const UE4CodeGen_Private::FStrPropertyParams Z_Construct_UFunction_UFirestoreValue_TimestampValue_Statics::NewProp_ReturnValue = { "ReturnValue", nullptr, (EPropertyFlags)0x0010000000000580, UE4CodeGen_Private::EPropertyGenFlags::Str, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(FirestoreValue_eventTimestampValue_Parms, ReturnValue), METADATA_PARAMS(nullptr, 0) }; const UE4CodeGen_Private::FPropertyParamsBase* const Z_Construct_UFunction_UFirestoreValue_TimestampValue_Statics::PropPointers[] = { (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UFunction_UFirestoreValue_TimestampValue_Statics::NewProp_Value, (const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UFunction_UFirestoreValue_TimestampValue_Statics::NewProp_ReturnValue, }; #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UFunction_UFirestoreValue_TimestampValue_Statics::Function_MetaDataParams[] = { { "Category", "CloudFirestore" }, { "Comment", "//string (Timestamp format) A timestamp value. Precise only to microseconds. When stored, any additional precision is rounded down. A timestamp in RFC3339 UTC \"Zulu\" format, with nanosecond resolution and up to nine fractional digits. Examples: \"2014-10-02T15:01:23Z\" and \"2014-10-02T15:01:23.045123456Z\".\n" }, { "DisplayName", "Get TimeStamp Value" }, { "Keywords", "Cloud Firestore Boolean" }, { "ModuleRelativePath", "Public/FirestoreValue.h" }, { "ToolTip", "string (Timestamp format) A timestamp value. Precise only to microseconds. When stored, any additional precision is rounded down. A timestamp in RFC3339 UTC \"Zulu\" format, with nanosecond resolution and up to nine fractional digits. Examples: \"2014-10-02T15:01:23Z\" and \"2014-10-02T15:01:23.045123456Z\"." }, }; #endif const UE4CodeGen_Private::FFunctionParams Z_Construct_UFunction_UFirestoreValue_TimestampValue_Statics::FuncParams = { (UObject*(*)())Z_Construct_UClass_UFirestoreValue, nullptr, "TimestampValue", nullptr, nullptr, sizeof(FirestoreValue_eventTimestampValue_Parms), Z_Construct_UFunction_UFirestoreValue_TimestampValue_Statics::PropPointers, UE_ARRAY_COUNT(Z_Construct_UFunction_UFirestoreValue_TimestampValue_Statics::PropPointers), RF_Public|RF_Transient|RF_MarkAsNative, (EFunctionFlags)0x04022401, 0, 0, METADATA_PARAMS(Z_Construct_UFunction_UFirestoreValue_TimestampValue_Statics::Function_MetaDataParams, UE_ARRAY_COUNT(Z_Construct_UFunction_UFirestoreValue_TimestampValue_Statics::Function_MetaDataParams)) }; UFunction* Z_Construct_UFunction_UFirestoreValue_TimestampValue() { static UFunction* ReturnFunction = nullptr; if (!ReturnFunction) { UE4CodeGen_Private::ConstructUFunction(ReturnFunction, Z_Construct_UFunction_UFirestoreValue_TimestampValue_Statics::FuncParams); } return ReturnFunction; } UClass* Z_Construct_UClass_UFirestoreValue_NoRegister() { return UFirestoreValue::StaticClass(); } struct Z_Construct_UClass_UFirestoreValue_Statics { static UObject* (*const DependentSingletons[])(); static const FClassFunctionLinkInfo FuncInfo[]; #if WITH_METADATA static const UE4CodeGen_Private::FMetaDataPairParam Class_MetaDataParams[]; #endif static const FCppClassTypeInfoStatic StaticCppClassTypeInfo; static const UE4CodeGen_Private::FClassParams ClassParams; }; UObject* (*const Z_Construct_UClass_UFirestoreValue_Statics::DependentSingletons[])() = { (UObject* (*)())Z_Construct_UClass_UBlueprintFunctionLibrary, (UObject* (*)())Z_Construct_UPackage__Script_FirebaseHelper, }; const FClassFunctionLinkInfo Z_Construct_UClass_UFirestoreValue_Statics::FuncInfo[] = { { &Z_Construct_UFunction_UFirestoreValue_ArrayValue, "ArrayValue" }, // 3256336308 { &Z_Construct_UFunction_UFirestoreValue_BooleanValue, "BooleanValue" }, // 4216417958 { &Z_Construct_UFunction_UFirestoreValue_BytesValue, "BytesValue" }, // 1440306507 { &Z_Construct_UFunction_UFirestoreValue_FloatValue, "FloatValue" }, // 3733167329 { &Z_Construct_UFunction_UFirestoreValue_GeoPointValue, "GeoPointValue" }, // 3678119697 { &Z_Construct_UFunction_UFirestoreValue_IntegerValue, "IntegerValue" }, // 123206592 { &Z_Construct_UFunction_UFirestoreValue_MapValue, "MapValue" }, // 976439700 { &Z_Construct_UFunction_UFirestoreValue_ReferenceValue, "ReferenceValue" }, // 1783429181 { &Z_Construct_UFunction_UFirestoreValue_StringValue, "StringValue" }, // 3661644672 { &Z_Construct_UFunction_UFirestoreValue_TimestampValue, "TimestampValue" }, // 497164297 }; #if WITH_METADATA const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UClass_UFirestoreValue_Statics::Class_MetaDataParams[] = { { "BlueprintType", "true" }, { "IncludePath", "FirestoreValue.h" }, { "IsBlueprintBase", "true" }, { "ModuleRelativePath", "Public/FirestoreValue.h" }, }; #endif const FCppClassTypeInfoStatic Z_Construct_UClass_UFirestoreValue_Statics::StaticCppClassTypeInfo = { TCppClassTypeTraits<UFirestoreValue>::IsAbstract, }; const UE4CodeGen_Private::FClassParams Z_Construct_UClass_UFirestoreValue_Statics::ClassParams = { &UFirestoreValue::StaticClass, nullptr, &StaticCppClassTypeInfo, DependentSingletons, FuncInfo, nullptr, nullptr, UE_ARRAY_COUNT(DependentSingletons), UE_ARRAY_COUNT(FuncInfo), 0, 0, 0x000000A0u, METADATA_PARAMS(Z_Construct_UClass_UFirestoreValue_Statics::Class_MetaDataParams, UE_ARRAY_COUNT(Z_Construct_UClass_UFirestoreValue_Statics::Class_MetaDataParams)) }; UClass* Z_Construct_UClass_UFirestoreValue() { static UClass* OuterClass = nullptr; if (!OuterClass) { UE4CodeGen_Private::ConstructUClass(OuterClass, Z_Construct_UClass_UFirestoreValue_Statics::ClassParams); } return OuterClass; } IMPLEMENT_CLASS(UFirestoreValue, 1094212672); template<> FIREBASEHELPER_API UClass* StaticClass<UFirestoreValue>() { return UFirestoreValue::StaticClass(); } static FCompiledInDefer Z_CompiledInDefer_UClass_UFirestoreValue(Z_Construct_UClass_UFirestoreValue, &UFirestoreValue::StaticClass, TEXT("/Script/FirebaseHelper"), TEXT("UFirestoreValue"), false, nullptr, nullptr, nullptr); DEFINE_VTABLE_PTR_HELPER_CTOR(UFirestoreValue); PRAGMA_ENABLE_DEPRECATION_WARNINGS #ifdef _MSC_VER #pragma warning (pop) #endif
42e35f5546425e4448c7ff3687be5b0774a74fda
6019c9ad21a9f73becf2d4a3a3789d1b9cc2f45d
/Poker/Poker/node.h
78d57e857cdacdd4c4fa2ae7c71a808cab7adb45
[]
no_license
theshwetapatil/Poker-CPP
261088291a7aa3c19afa07a3bb69b0a9a38e4dfc
438e6d4508f76fcda08f297ec0b864b51c6d0d0a
refs/heads/master
2020-03-15T23:35:24.880229
2018-05-07T14:08:11
2018-05-07T14:08:11
132,397,025
0
0
null
null
null
null
WINDOWS-1252
C++
false
false
851
h
// node.cpp : Defines the node header for the console application. // C++ Game: Poker // Gameplay features: hand draw, poker hand match, card shuffle- Fisher Yates Algorithm, sort- Quicksort Algorithm, cards swap // Author: Shweta Patil // Copyright: Shweta Patil © 2018 #pragma once #define _CRTDBG_MAP_ALLOC #define _CRTDBG_MAP_ALLOC_NEW #include <cstdlib> #include <crtdbg.h> #ifdef _DEBUG #ifndef DBG_NEW #define DBG_NEW new ( _NORMAL_BLOCK , __FILE__ ,__LINE__) #define new DBG_NEW #endif #endif #include "card_type.h" typedef struct node { card_type *data; node *next; node(); node(card_type *data); node(const node& n); bool is_empty(); bool is_equal_suit(card_suit suit); bool is_equal_rank(card_rank rank); bool is_equal_data(card_type *data); void display_node(); std::string get_suit(); std::string get_rank(); ~node(); };
8c50f6ad603d34edb1d53cd999bb79e8605dc067
a993b98793857e93de978a6ef55103a37b414bbf
/components/proximity_auth/messenger_impl_unittest.cc
84a16315bda448ec4d9782afcf54480bbb62ad81
[ "BSD-3-Clause" ]
permissive
goby/chromium
339e6894f9fb38cc324baacec8d6f38fe016ec80
07aaa7750898bf9bdbff8163959d96a0bc1fe038
refs/heads/master
2023-01-10T18:22:31.622284
2017-01-09T11:22:55
2017-01-09T11:22:55
47,946,272
1
0
null
2017-01-09T11:22:56
2015-12-14T01:57:57
null
UTF-8
C++
false
false
15,640
cc
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "components/proximity_auth/messenger_impl.h" #include <memory> #include "base/callback.h" #include "base/macros.h" #include "base/memory/ptr_util.h" #include "components/cryptauth/remote_device.h" #include "components/proximity_auth/connection.h" #include "components/proximity_auth/fake_connection.h" #include "components/proximity_auth/fake_secure_context.h" #include "components/proximity_auth/messenger_observer.h" #include "components/proximity_auth/proximity_auth_test_util.h" #include "components/proximity_auth/remote_status_update.h" #include "components/proximity_auth/wire_message.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" using testing::_; using testing::AllOf; using testing::Eq; using testing::Field; using testing::NiceMock; using testing::Pointee; using testing::Return; using testing::StrictMock; namespace proximity_auth { namespace { const char kChallenge[] = "a most difficult challenge"; class MockMessengerObserver : public MessengerObserver { public: explicit MockMessengerObserver(Messenger* messenger) : messenger_(messenger) { messenger_->AddObserver(this); } virtual ~MockMessengerObserver() { messenger_->RemoveObserver(this); } MOCK_METHOD1(OnUnlockEventSent, void(bool success)); MOCK_METHOD1(OnRemoteStatusUpdate, void(const RemoteStatusUpdate& status_update)); MOCK_METHOD1(OnDecryptResponseProxy, void(const std::string& decrypted_bytes)); MOCK_METHOD1(OnUnlockResponse, void(bool success)); MOCK_METHOD0(OnDisconnected, void()); virtual void OnDecryptResponse(const std::string& decrypted_bytes) { OnDecryptResponseProxy(decrypted_bytes); } private: // The messenger that |this| instance observes. Messenger* const messenger_; DISALLOW_COPY_AND_ASSIGN(MockMessengerObserver); }; class TestMessenger : public MessengerImpl { public: TestMessenger() : MessengerImpl(base::MakeUnique<FakeConnection>( CreateClassicRemoteDeviceForTest()), base::MakeUnique<FakeSecureContext>()) {} ~TestMessenger() override {} // Simple getters for the mock objects owned by |this| messenger. FakeConnection* GetFakeConnection() { return static_cast<FakeConnection*>(connection()); } FakeSecureContext* GetFakeSecureContext() { return static_cast<FakeSecureContext*>(GetSecureContext()); } private: DISALLOW_COPY_AND_ASSIGN(TestMessenger); }; } // namespace TEST(ProximityAuthMessengerImplTest, SupportsSignIn_ProtocolVersionThreeZero) { TestMessenger messenger; messenger.GetFakeSecureContext()->set_protocol_version( SecureContext::PROTOCOL_VERSION_THREE_ZERO); EXPECT_FALSE(messenger.SupportsSignIn()); } TEST(ProximityAuthMessengerImplTest, SupportsSignIn_ProtocolVersionThreeOne) { TestMessenger messenger; messenger.GetFakeSecureContext()->set_protocol_version( SecureContext::PROTOCOL_VERSION_THREE_ONE); EXPECT_TRUE(messenger.SupportsSignIn()); } TEST(ProximityAuthMessengerImplTest, OnConnectionStatusChanged_ConnectionDisconnects) { TestMessenger messenger; MockMessengerObserver observer(&messenger); EXPECT_CALL(observer, OnDisconnected()); messenger.GetFakeConnection()->Disconnect(); } TEST(ProximityAuthMessengerImplTest, DispatchUnlockEvent_SendsExpectedMessage) { TestMessenger messenger; messenger.DispatchUnlockEvent(); WireMessage* message = messenger.GetFakeConnection()->current_message(); ASSERT_TRUE(message); EXPECT_EQ(std::string(), message->permit_id()); EXPECT_EQ( "{" "\"name\":\"easy_unlock\"," "\"type\":\"event\"" "}, but encoded", message->payload()); } TEST(ProximityAuthMessengerImplTest, DispatchUnlockEvent_SendMessageFails) { TestMessenger messenger; MockMessengerObserver observer(&messenger); messenger.DispatchUnlockEvent(); EXPECT_CALL(observer, OnUnlockEventSent(false)); messenger.GetFakeConnection()->FinishSendingMessageWithSuccess(false); } TEST(ProximityAuthMessengerImplTest, DispatchUnlockEvent_SendMessageSucceeds) { TestMessenger messenger; MockMessengerObserver observer(&messenger); messenger.DispatchUnlockEvent(); EXPECT_CALL(observer, OnUnlockEventSent(true)); messenger.GetFakeConnection()->FinishSendingMessageWithSuccess(true); } TEST(ProximityAuthMessengerImplTest, RequestDecryption_SignInUnsupported_DoesntSendMessage) { TestMessenger messenger; messenger.GetFakeSecureContext()->set_protocol_version( SecureContext::PROTOCOL_VERSION_THREE_ZERO); messenger.RequestDecryption(kChallenge); EXPECT_FALSE(messenger.GetFakeConnection()->current_message()); } TEST(ProximityAuthMessengerImplTest, RequestDecryption_SendsExpectedMessage) { TestMessenger messenger; messenger.RequestDecryption(kChallenge); WireMessage* message = messenger.GetFakeConnection()->current_message(); ASSERT_TRUE(message); EXPECT_EQ(std::string(), message->permit_id()); EXPECT_EQ( "{" "\"encrypted_data\":\"YSBtb3N0IGRpZmZpY3VsdCBjaGFsbGVuZ2U=\"," "\"type\":\"decrypt_request\"" "}, but encoded", message->payload()); } TEST(ProximityAuthMessengerImplTest, RequestDecryption_SendsExpectedMessage_UsingBase64UrlEncoding) { TestMessenger messenger; messenger.RequestDecryption("\xFF\xE6"); WireMessage* message = messenger.GetFakeConnection()->current_message(); ASSERT_TRUE(message); EXPECT_EQ(std::string(), message->permit_id()); EXPECT_EQ( "{" "\"encrypted_data\":\"_-Y=\"," "\"type\":\"decrypt_request\"" "}, but encoded", message->payload()); } TEST(ProximityAuthMessengerImplTest, RequestDecryption_SendMessageFails) { TestMessenger messenger; MockMessengerObserver observer(&messenger); messenger.RequestDecryption(kChallenge); EXPECT_CALL(observer, OnDecryptResponseProxy(std::string())); messenger.GetFakeConnection()->FinishSendingMessageWithSuccess(false); } TEST(ProximityAuthMessengerImplTest, RequestDecryption_SendSucceeds_WaitsForReply) { TestMessenger messenger; MockMessengerObserver observer(&messenger); messenger.RequestDecryption(kChallenge); EXPECT_CALL(observer, OnDecryptResponseProxy(_)).Times(0); messenger.GetFakeConnection()->FinishSendingMessageWithSuccess(true); } TEST(ProximityAuthMessengerImplTest, RequestDecryption_SendSucceeds_NotifiesObserversOnReply_NoData) { TestMessenger messenger; MockMessengerObserver observer(&messenger); messenger.RequestDecryption(kChallenge); messenger.GetFakeConnection()->FinishSendingMessageWithSuccess(true); EXPECT_CALL(observer, OnDecryptResponseProxy(std::string())); messenger.GetFakeConnection()->ReceiveMessageWithPayload( "{\"type\":\"decrypt_response\"}, but encoded"); } TEST(ProximityAuthMessengerImplTest, RequestDecryption_SendSucceeds_NotifiesObserversOnReply_InvalidData) { TestMessenger messenger; MockMessengerObserver observer(&messenger); messenger.RequestDecryption(kChallenge); messenger.GetFakeConnection()->FinishSendingMessageWithSuccess(true); EXPECT_CALL(observer, OnDecryptResponseProxy(std::string())); messenger.GetFakeConnection()->ReceiveMessageWithPayload( "{" "\"type\":\"decrypt_response\"," "\"data\":\"not a base64-encoded string\"" "}, but encoded"); } TEST(ProximityAuthMessengerImplTest, RequestDecryption_SendSucceeds_NotifiesObserversOnReply_ValidData) { TestMessenger messenger; MockMessengerObserver observer(&messenger); messenger.RequestDecryption(kChallenge); messenger.GetFakeConnection()->FinishSendingMessageWithSuccess(true); EXPECT_CALL(observer, OnDecryptResponseProxy("a winner is you")); messenger.GetFakeConnection()->ReceiveMessageWithPayload( "{" "\"type\":\"decrypt_response\"," "\"data\":\"YSB3aW5uZXIgaXMgeW91\"" // "a winner is you", base64-encoded "}, but encoded"); } // Verify that the messenger correctly parses base64url encoded data. TEST(ProximityAuthMessengerImplTest, RequestDecryption_SendSucceeds_ParsesBase64UrlEncodingInReply) { TestMessenger messenger; MockMessengerObserver observer(&messenger); messenger.RequestDecryption(kChallenge); messenger.GetFakeConnection()->FinishSendingMessageWithSuccess(true); EXPECT_CALL(observer, OnDecryptResponseProxy("\xFF\xE6")); messenger.GetFakeConnection()->ReceiveMessageWithPayload( "{" "\"type\":\"decrypt_response\"," "\"data\":\"_-Y=\"" // "\0xFF\0xE6", base64url-encoded. "}, but encoded"); } TEST(ProximityAuthMessengerImplTest, RequestUnlock_SignInUnsupported_DoesntSendMessage) { TestMessenger messenger; messenger.GetFakeSecureContext()->set_protocol_version( SecureContext::PROTOCOL_VERSION_THREE_ZERO); messenger.RequestUnlock(); EXPECT_FALSE(messenger.GetFakeConnection()->current_message()); } TEST(ProximityAuthMessengerImplTest, RequestUnlock_SendsExpectedMessage) { TestMessenger messenger; messenger.RequestUnlock(); WireMessage* message = messenger.GetFakeConnection()->current_message(); ASSERT_TRUE(message); EXPECT_EQ(std::string(), message->permit_id()); EXPECT_EQ("{\"type\":\"unlock_request\"}, but encoded", message->payload()); } TEST(ProximityAuthMessengerImplTest, RequestUnlock_SendMessageFails) { TestMessenger messenger; MockMessengerObserver observer(&messenger); messenger.RequestUnlock(); EXPECT_CALL(observer, OnUnlockResponse(false)); messenger.GetFakeConnection()->FinishSendingMessageWithSuccess(false); } TEST(ProximityAuthMessengerImplTest, RequestUnlock_SendSucceeds_WaitsForReply) { TestMessenger messenger; MockMessengerObserver observer(&messenger); messenger.RequestUnlock(); EXPECT_CALL(observer, OnUnlockResponse(_)).Times(0); messenger.GetFakeConnection()->FinishSendingMessageWithSuccess(true); } TEST(ProximityAuthMessengerImplTest, RequestUnlock_SendSucceeds_NotifiesObserversOnReply) { TestMessenger messenger; MockMessengerObserver observer(&messenger); messenger.RequestUnlock(); messenger.GetFakeConnection()->FinishSendingMessageWithSuccess(true); EXPECT_CALL(observer, OnUnlockResponse(true)); messenger.GetFakeConnection()->ReceiveMessageWithPayload( "{\"type\":\"unlock_response\"}, but encoded"); } TEST(ProximityAuthMessengerImplTest, OnMessageReceived_RemoteStatusUpdate_Invalid) { TestMessenger messenger; MockMessengerObserver observer(&messenger); // Receive a status update message that's missing all the data. EXPECT_CALL(observer, OnRemoteStatusUpdate(_)).Times(0); messenger.GetFakeConnection()->ReceiveMessageWithPayload( "{\"type\":\"status_update\"}, but encoded"); } TEST(ProximityAuthMessengerImplTest, OnMessageReceived_RemoteStatusUpdate_Valid) { TestMessenger messenger; MockMessengerObserver observer(&messenger); EXPECT_CALL(observer, OnRemoteStatusUpdate( AllOf(Field(&RemoteStatusUpdate::user_presence, USER_PRESENT), Field(&RemoteStatusUpdate::secure_screen_lock_state, SECURE_SCREEN_LOCK_ENABLED), Field(&RemoteStatusUpdate::trust_agent_state, TRUST_AGENT_UNSUPPORTED)))); messenger.GetFakeConnection()->ReceiveMessageWithPayload( "{" "\"type\":\"status_update\"," "\"user_presence\":\"present\"," "\"secure_screen_lock\":\"enabled\"," "\"trust_agent\":\"unsupported\"" "}, but encoded"); } TEST(ProximityAuthMessengerImplTest, OnMessageReceived_InvalidJSON) { TestMessenger messenger; StrictMock<MockMessengerObserver> observer(&messenger); messenger.RequestUnlock(); messenger.GetFakeConnection()->FinishSendingMessageWithSuccess(true); // The StrictMock will verify that no observer methods are called. messenger.GetFakeConnection()->ReceiveMessageWithPayload( "Not JSON, but encoded"); } TEST(ProximityAuthMessengerImplTest, OnMessageReceived_MissingTypeField) { TestMessenger messenger; StrictMock<MockMessengerObserver> observer(&messenger); messenger.RequestUnlock(); messenger.GetFakeConnection()->FinishSendingMessageWithSuccess(true); // The StrictMock will verify that no observer methods are called. messenger.GetFakeConnection()->ReceiveMessageWithPayload( "{\"some key that's not 'type'\":\"some value\"}, but encoded"); } TEST(ProximityAuthMessengerImplTest, OnMessageReceived_UnexpectedReply) { TestMessenger messenger; StrictMock<MockMessengerObserver> observer(&messenger); // The StrictMock will verify that no observer methods are called. messenger.GetFakeConnection()->ReceiveMessageWithPayload( "{\"type\":\"unlock_response\"}, but encoded"); } TEST(ProximityAuthMessengerImplTest, OnMessageReceived_MismatchedReply_UnlockInReplyToDecrypt) { TestMessenger messenger; StrictMock<MockMessengerObserver> observer(&messenger); messenger.RequestDecryption(kChallenge); messenger.GetFakeConnection()->FinishSendingMessageWithSuccess(true); // The StrictMock will verify that no observer methods are called. messenger.GetFakeConnection()->ReceiveMessageWithPayload( "{\"type\":\"unlock_response\"}, but encoded"); } TEST(ProximityAuthMessengerImplTest, OnMessageReceived_MismatchedReply_DecryptInReplyToUnlock) { TestMessenger messenger; StrictMock<MockMessengerObserver> observer(&messenger); messenger.RequestUnlock(); messenger.GetFakeConnection()->FinishSendingMessageWithSuccess(true); // The StrictMock will verify that no observer methods are called. messenger.GetFakeConnection()->ReceiveMessageWithPayload( "{" "\"type\":\"decrypt_response\"," "\"data\":\"YSB3aW5uZXIgaXMgeW91\"" "}, but encoded"); } TEST(ProximityAuthMessengerImplTest, BuffersMessages_WhileSending) { TestMessenger messenger; MockMessengerObserver observer(&messenger); // Initiate a decryption request, and then initiate an unlock request before // the decryption request is even finished sending. messenger.RequestDecryption(kChallenge); messenger.RequestUnlock(); EXPECT_CALL(observer, OnDecryptResponseProxy(std::string())); messenger.GetFakeConnection()->FinishSendingMessageWithSuccess(false); EXPECT_CALL(observer, OnUnlockResponse(false)); messenger.GetFakeConnection()->FinishSendingMessageWithSuccess(false); } TEST(ProximityAuthMessengerImplTest, BuffersMessages_WhileAwaitingReply) { TestMessenger messenger; MockMessengerObserver observer(&messenger); // Initiate a decryption request, and allow the message to be sent. messenger.RequestDecryption(kChallenge); messenger.GetFakeConnection()->FinishSendingMessageWithSuccess(true); // At this point, the messenger is awaiting a reply to the decryption message. // While it's waiting, initiate an unlock request. messenger.RequestUnlock(); // Now simulate a response arriving for the original decryption request. EXPECT_CALL(observer, OnDecryptResponseProxy("a winner is you")); messenger.GetFakeConnection()->ReceiveMessageWithPayload( "{" "\"type\":\"decrypt_response\"," "\"data\":\"YSB3aW5uZXIgaXMgeW91\"" "}, but encoded"); // The unlock request should have remained buffered, and should only now be // sent. EXPECT_CALL(observer, OnUnlockResponse(false)); messenger.GetFakeConnection()->FinishSendingMessageWithSuccess(false); } } // namespace proximity_auth
0b6e64709ad1f045a3d5d42cafbaf041008f4bef
1b4f9a242a41cfb57890022fd5cd7cac374654c7
/11000-11999/11743/creditCheck_11743.cpp
e0bc20684645d6723f902e58ff61f6cadaac4bf7
[]
no_license
msanchezzg/UVaOnlineJudge
821a88838294a4a7d9cca13829343bbfde4f1627
0814335643bab76c592c25987bd75f3d8728d8fd
refs/heads/master
2021-10-24T21:22:40.188474
2021-10-21T16:10:19
2021-10-21T16:10:19
236,212,542
0
0
null
null
null
null
UTF-8
C++
false
false
905
cpp
#include <iostream> #include <vector> #include <string> using namespace std; int sumOfDigits(int n) { string s = to_string(n); int total = 0; for (char c : s) total += c - 48; // 48 is ASCII value of 0 return total; } int main(){ int cases, oddNumsSum, pairNumsSum, total, n, n2; string s, card; bool oddPosition; vector<string> creditCard; cin >> cases; cin.ignore(); while(cases--) { getline(cin, card); creditCard.clear(); oddNumsSum = 0; pairNumsSum = 0; oddPosition = false; for(char num : card) { if (! isdigit(num)) continue; if (oddPosition) { n = num - 48; oddNumsSum += n; } else { n = num - 48; n2 = n*2; pairNumsSum += sumOfDigits(n2); } oddPosition = !oddPosition; } total = pairNumsSum + oddNumsSum; s = to_string(total); if (s[s.length()-1] == '0') cout << "Valid\n"; else cout << "Invalid\n"; } return 0; }
6b63ccedd52109e75cb10d241ccdb88ed7200ae3
1d1fc9b7cd13c70c83b89c885b80e72fff626fe9
/mytest.cpp
235a72eb2540fb47e770cb4b063cf8a9752e9f21
[]
no_license
lijiunderstand/PCA-1
164100ae5df23948babe00eb4fd3c5e50ebbae80
d23f66f8bff032a11493687bdbed3d9466fc9805
refs/heads/master
2022-01-20T11:48:37.068007
2019-03-23T04:44:11
2019-03-23T04:44:11
null
0
0
null
null
null
null
UTF-8
C++
false
false
423
cpp
// C++ program to demonstrate default behaviour of // sort() in STL. #include <bits/stdc++.h> using namespace std; int main() { int arr[] = {1, 5, 8, 9, 6, 7, 3, 4, 2, 0}; // int n = sizeof(arr)/sizeof(arr[0]); sort(arr, arr+n); cout << "\nArray after sorting using " "default sort is : \n"; for (int i = 0; i < n; ++i) cout << arr[i] << " "; return 0; }
1cd86afbfc6eae34d07c7d1369cb027d3a6fb691
3ff1fe3888e34cd3576d91319bf0f08ca955940f
/lcic/include/tencentcloud/lcic/v20220817/model/MessageList.h
4d5ff4bc08264c07826f8bf955b5fa3fd1a18b32
[ "Apache-2.0" ]
permissive
TencentCloud/tencentcloud-sdk-cpp
9f5df8220eaaf72f7eaee07b2ede94f89313651f
42a76b812b81d1b52ec6a217fafc8faa135e06ca
refs/heads/master
2023-08-30T03:22:45.269556
2023-08-30T00:45:39
2023-08-30T00:45:39
188,991,963
55
37
Apache-2.0
2023-08-17T03:13:20
2019-05-28T08:56:08
C++
UTF-8
C++
false
false
6,947
h
/* * Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef TENCENTCLOUD_LCIC_V20220817_MODEL_MESSAGELIST_H_ #define TENCENTCLOUD_LCIC_V20220817_MODEL_MESSAGELIST_H_ #include <string> #include <vector> #include <map> #include <tencentcloud/core/utils/rapidjson/document.h> #include <tencentcloud/core/utils/rapidjson/writer.h> #include <tencentcloud/core/utils/rapidjson/stringbuffer.h> #include <tencentcloud/core/AbstractModel.h> #include <tencentcloud/lcic/v20220817/model/MessageItem.h> namespace TencentCloud { namespace Lcic { namespace V20220817 { namespace Model { /** * 历史消息列表 */ class MessageList : public AbstractModel { public: MessageList(); ~MessageList() = default; void ToJsonObject(rapidjson::Value &value, rapidjson::Document::AllocatorType& allocator) const; CoreInternalOutcome Deserialize(const rapidjson::Value &value); /** * 获取消息时间戳 注意:此字段可能返回 null,表示取不到有效值。 * @return Timestamp 消息时间戳 注意:此字段可能返回 null,表示取不到有效值。 * */ int64_t GetTimestamp() const; /** * 设置消息时间戳 注意:此字段可能返回 null,表示取不到有效值。 * @param _timestamp 消息时间戳 注意:此字段可能返回 null,表示取不到有效值。 * */ void SetTimestamp(const int64_t& _timestamp); /** * 判断参数 Timestamp 是否已赋值 * @return Timestamp 是否已赋值 * */ bool TimestampHasBeenSet() const; /** * 获取消息发送者 注意:此字段可能返回 null,表示取不到有效值。 * @return FromAccount 消息发送者 注意:此字段可能返回 null,表示取不到有效值。 * */ std::string GetFromAccount() const; /** * 设置消息发送者 注意:此字段可能返回 null,表示取不到有效值。 * @param _fromAccount 消息发送者 注意:此字段可能返回 null,表示取不到有效值。 * */ void SetFromAccount(const std::string& _fromAccount); /** * 判断参数 FromAccount 是否已赋值 * @return FromAccount 是否已赋值 * */ bool FromAccountHasBeenSet() const; /** * 获取消息序列号,当前课堂内唯一且单调递增 注意:此字段可能返回 null,表示取不到有效值。 * @return Seq 消息序列号,当前课堂内唯一且单调递增 注意:此字段可能返回 null,表示取不到有效值。 * */ int64_t GetSeq() const; /** * 设置消息序列号,当前课堂内唯一且单调递增 注意:此字段可能返回 null,表示取不到有效值。 * @param _seq 消息序列号,当前课堂内唯一且单调递增 注意:此字段可能返回 null,表示取不到有效值。 * */ void SetSeq(const int64_t& _seq); /** * 判断参数 Seq 是否已赋值 * @return Seq 是否已赋值 * */ bool SeqHasBeenSet() const; /** * 获取历史消息列表 注意:此字段可能返回 null,表示取不到有效值。 * @return MessageBody 历史消息列表 注意:此字段可能返回 null,表示取不到有效值。 * */ std::vector<MessageItem> GetMessageBody() const; /** * 设置历史消息列表 注意:此字段可能返回 null,表示取不到有效值。 * @param _messageBody 历史消息列表 注意:此字段可能返回 null,表示取不到有效值。 * */ void SetMessageBody(const std::vector<MessageItem>& _messageBody); /** * 判断参数 MessageBody 是否已赋值 * @return MessageBody 是否已赋值 * */ bool MessageBodyHasBeenSet() const; private: /** * 消息时间戳 注意:此字段可能返回 null,表示取不到有效值。 */ int64_t m_timestamp; bool m_timestampHasBeenSet; /** * 消息发送者 注意:此字段可能返回 null,表示取不到有效值。 */ std::string m_fromAccount; bool m_fromAccountHasBeenSet; /** * 消息序列号,当前课堂内唯一且单调递增 注意:此字段可能返回 null,表示取不到有效值。 */ int64_t m_seq; bool m_seqHasBeenSet; /** * 历史消息列表 注意:此字段可能返回 null,表示取不到有效值。 */ std::vector<MessageItem> m_messageBody; bool m_messageBodyHasBeenSet; }; } } } } #endif // !TENCENTCLOUD_LCIC_V20220817_MODEL_MESSAGELIST_H_
42fc523614e390dab48fd4521831cf8a9d139b32
1f5d0e985ff92a4695e7aefb897974c921b798e7
/Sources/AIntegrator/Ai_Main/Src/Parameters/LineEditParameter.cpp
52acca0d1428de0f643548b9fdcbbf1327d36848
[]
no_license
denis-fatkulin/aintegrator
77be9e282d9a613a50103a8affc17287ed87a59a
380c98295c500712f028f739dd51b97af1a3297e
refs/heads/master
2022-08-12T07:54:50.546839
2017-01-26T06:59:45
2017-01-26T06:59:45
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,441
cpp
//////////////////////////////////////////////////////////////////////////////////////////////////// /// A-Integrator /// (c) 2016 - Denis Fatkulin - [email protected] //////////////////////////////////////////////////////////////////////////////////////////////////// #include "LineEditParameter.h" #include "host/Ai_PostParameters.pb.h" #include <limits> #include <QIntValidator> using namespace ai::main; LineEditParameter::LineEditParameter(QObject* parent) : BaseParameter(parent) , _type(Unknown) , _maxSymbols(100) , _validator(nullptr) , _lineEdit(nullptr) { } void LineEditParameter::update(ai::proto::Parameter* parameter) { if(!parameter->has_line_edit()) return; _lineEdit = parameter->mutable_line_edit(); if(_lineEdit->has_max_symbols()) { _maxSymbols = _lineEdit->max_symbols(); } auto type = static_cast<ParameterType>(_lineEdit->ui_type()); if(_type != type) { _type = type; delete _validator; _validator = nullptr; switch(_type) { case SignedInt: _validator = new QRegExpValidator(QRegExp("[+-]?\\d+"), this); break; case UnsignedInt: _validator = new QRegExpValidator(QRegExp("\\d+"), this); break; case SignedDouble: _validator = new QRegExpValidator(QRegExp("[+-]?\\d*\\.?\\d+"), this); break; case StringValue: { auto regExp = QRegExp(QString(".{0,%1}").arg(_maxSymbols)); _validator = new QRegExpValidator(regExp, this); break; } } emit changed(); } if(_type == SignedInt && _lineEdit->has_signed_int()) { setValue(QString::number(_lineEdit->signed_int())); } if(_type == UnsignedInt && _lineEdit->has_unsigned_int()) { setValue(QString::number(_lineEdit->unsigned_int())); } if(_type == SignedDouble && _lineEdit->has_signed_double()) { setValue(QString::number(_lineEdit->signed_double())); } if(_type == StringValue && _lineEdit->has_string_value()) { setValue(QString::fromStdString(_lineEdit->string_value())); } } void LineEditParameter::setValue(const QString& value) { if(_lineEdit) { if(_type == SignedInt) { _lineEdit->set_signed_int(value.toInt()); } if(_type == UnsignedInt) { _lineEdit->set_unsigned_int(value.toUInt()); } if(_type == SignedDouble) { _lineEdit->set_signed_double(value.toDouble()); } if(_type == StringValue) { _lineEdit->set_string_value(value.toStdString()); } } if(_value != value) { _value = value; emit changed(); } }
e0f9645e0911b6e17fc5420de28da06656c341be
bf78b310cc6276edc749a2b3b8514fcc2c333c5c
/src/NoWarning/mpi.hpp
e3368db48f5dcc20a817021ce0cbd05c6bbff6b7
[]
no_license
Charmworks/ExaM2M
62a1a25e47dc19ead740e073bb5694d5c87ecdac
d9a0f3b6b208fd6875a1c091f3fe44c3d11b9d04
refs/heads/main
2023-08-16T01:22:39.344766
2022-05-10T16:24:58
2022-05-10T16:24:58
246,621,911
3
1
null
2023-07-04T14:15:35
2020-03-11T16:23:22
C++
UTF-8
C++
false
false
832
hpp
// ***************************************************************************** /*! \file src/NoWarning/mpi.hpp \copyright 2020 Charmworks, Inc. All rights reserved. See the LICENSE file for details. \brief Include mpi.h with turning off specific compiler warnings */ // ***************************************************************************** #ifndef nowarning_mpi_h #define nowarning_mpi_h #include "Macro.hpp" #if defined(__clang__) #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wundef" #elif defined(STRICT_GNUC) #pragma GCC diagnostic push // #pragma GCC diagnostic ignored "-Wredundant-decls" #endif #include <mpi.h> #if defined(__clang__) #pragma clang diagnostic pop #elif defined(STRICT_GNUC) #pragma GCC diagnostic pop #endif #endif // nowarning_mpi_h
725d4cece5b50124ed58bf3b881c3896ec91d7e4
76704671ba2b44498489d46864728c02bc90889d
/MeetingCodes/Meeting9/Nelli_Tags.cpp
4490c51b33db7570a2e6807ad233e17117e3a2f1
[ "MIT" ]
permissive
knelli2/spectre-cpp-basics
5750725ed78aea139de1c510333e2b328b2196eb
9ac3f192a3673e708e8cd33efce0b3eba13f46fc
refs/heads/main
2023-05-14T17:50:29.787566
2021-06-10T15:08:39
2021-06-10T15:08:39
373,907,837
0
0
MIT
2021-06-04T16:57:18
2021-06-04T16:57:17
null
UTF-8
C++
false
false
877
cpp
#include <iostream> #include <tuple> #include <utility> template <typename T, size_t Extra> T sum(const T& lhs, const T& rhs) noexcept { return lhs + rhs + static_cast<double>(Extra); } namespace Rect { struct Width {}; struct Height {}; } // namespace Rect template <typename T> double area(const T& box) noexcept { return std::get<std::pair<Rect::Width, double>>(box).second * std::get<std::pair<Rect::Height, double>>(box).second; } int main() { for (double x = 0.0; x < 1.0; x += 0.1) { std::cout << sum<double, 4>(x, x + 1.0) << "\n"; } // std::pair example std::pair<Rect::Width, double> width{{}, 4.0}; std::pair<Rect::Height, double> height{{}, 4.0}; // std::tuple example std::tuple<std::pair<Rect::Width, double>, std::pair<Rect::Height, double>> box{{{}, 4.0}, {{}, 5.0}}; std::cout << area(box) << "\n"; return 0; }
35a2526a8c6fe2ae19a03d74f833cf78d720dc4a
9c046eeda11be532cc0017e6da316e7ddfd16283
/Telecomm/SharedLib/qtav/include/QtAVWidgets/VideoPreviewWidget.h
f0a72837989843c70d743adb580b2027f51587c2
[ "BSD-3-Clause" ]
permissive
telecommai/windows
83cd3ac4dec7742c6e038689689ac7ec9cde842a
30e34ffe0bc81f39c25be7624d16856bf42e03eb
refs/heads/master
2023-01-12T02:10:59.904541
2019-04-23T11:42:07
2019-04-23T11:42:07
180,726,308
3
0
BSD-3-Clause
2023-01-03T19:52:20
2019-04-11T06:12:20
C++
UTF-8
C++
false
false
3,637
h
/****************************************************************************** VideoRendererTypes: type id and manually id register function Copyright (C) 2015 Wang Bin <[email protected]> * This file is part of QtAV This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA ******************************************************************************/ #ifndef QTAV_VIDEOPREVIEWWIDGET_H #define QTAV_VIDEOPREVIEWWIDGET_H #include <QtAVWidgets/global.h> #if QT_VERSION >= QT_VERSION_CHECK(5, 0, 0) #include <QtWidgets/QWidget> #else #include <QtGui/QWidget> #endif namespace QtAV { class VideoFrame; class VideoOutput; class VideoFrameExtractor; class Q_AVWIDGETS_EXPORT VideoPreviewWidget : public QWidget { Q_OBJECT public: explicit VideoPreviewWidget(QWidget *parent = 0); void setTimestamp(qint64 msec); qint64 timestamp() const; void preview(); void setFile(const QString& file); QString file() const; // default is false void setKeepAspectRatio(bool value = true) { m_keep_ar = value; } bool isKeepAspectRatio() const { return m_keep_ar; } /// AutoDisplayFrame -- default is true. if true, new frames from underlying extractor will update display widget automatically. bool isAutoDisplayFrame() const { return m_auto_display; } /// If false, new frames (or frame errors) won't automatically update widget /// (caller must ensure to call displayFrame()/displayFrame(frame) for this if false). /// set to false only if you want to do your own frame caching magic with preview frames. void setAutoDisplayFrame(bool b=true); public Q_SLOTS: // these were previously private but made public to allow calling code to cache some preview frames and directly display frames to this class void displayFrame(const QtAV::VideoFrame& frame); //parameter VideoFrame void displayNoFrame(); Q_SIGNALS: void timestampChanged(); void fileChanged(); /// emitted on real decode error -- in that case displayNoFrame() will be automatically called void gotError(const QString &); /// usually emitted when a new request for a frame came in and current request was aborted. displayNoFrame() will be automatically called void gotAbort(const QString &); /// useful if calling code is interested in keeping stats on good versus bad frame counts, /// or if it wants to cache preview frames. Keeping counts helps caller decide if /// preview is working reliably or not for the designated file. /// parameter frame will always have: frame.isValid() == true, and will be /// already-scaled and in the right format to fit in the preview widget void gotFrame(const QtAV::VideoFrame & frame); protected: virtual void resizeEvent(QResizeEvent *); private: bool m_keep_ar, m_auto_display; QString m_file; VideoFrameExtractor *m_extractor; VideoOutput *m_out; }; } //namespace QtAV #endif // QTAV_VIDEOPREVIEWWIDGET_H
7cab9f3b80d49f89ca8c38c7b19327052ac56117
fde2964c7284308711d863e9b825b06569677f59
/AlgoCourse4/Week4/2SAT.cpp
70542a1a37a3d7531fdff46ed9167b729cb84e29
[]
no_license
NitkPallavik/Algorithm---Courseera
7a1bda1d6c7a48a0efbd4c0d7b44d8bfdfbf7023
f29d63bcbf05fa58ce7b441c54b6562547486c5d
refs/heads/master
2021-01-21T21:26:18.831968
2017-07-31T04:12:31
2017-07-31T04:12:31
94,842,717
0
0
null
null
null
null
UTF-8
C++
false
false
2,712
cpp
#include <bits/stdc++.h> using namespace std; vector <int> reverse_count(3000001); vector <int> forward_count(3000001); vector <long> fintime(3000001); int finish_time =1; bool satisfiable = true; void GraphForward(long variables,long track, vector < vector<int> > &graph, long index){ if (forward_count[track] != 0) return ; if (forward_count[track] == 0){ forward_count[track] = index; if(track > variables){ if(forward_count[track -variables] == index) satisfiable= false; } if(track <= variables){ if(forward_count[track + variables] == index) satisfiable = false; } for (int y=0; y < graph[track].size(); y++) GraphForward(variables,graph[track][y], graph,index); forward_count[track] = index; return; } } void GraphRev(long r, vector < vector<int> > &graph_rev){ if (reverse_count[r] == 1) return; if (reverse_count[r] != 1){ reverse_count[r] = 1; for (int z=0; z < graph_rev[r].size(); z++) GraphRev(graph_rev[r][z] , graph_rev); fintime[finish_time] = r; finish_time++; return; } } void readclauses(long variables,vector < vector<int> > &graph,vector < vector<int> > &graph_rev){ // Variables int variable1,variable2,firstedge,secondedge; //Read the clauses for(int i = 1;i <= variables;i++){ scanf("%d %d",&variable1,&variable2); if(variable1 < 0) variable1 = variables + abs(variable1); if(variable2 < 0) variable2 = variables + abs(variable2); if(variable1 > variables) firstedge = variable1 -variables; else firstedge = variables + variable1; if(variable2 > variables) secondedge = variable2 -variables; else secondedge = variables + variable2; graph[firstedge].push_back(variable2); graph[secondedge].push_back(variable1); graph_rev[variable2].push_back(firstedge); graph_rev[variable1].push_back(secondedge); } } int main (){ // Read the File FILE *fp = freopen("2sat6.txt","r",stdin); // variables long variables; // Graph and Graph Rev vector < vector<int> > graph,graph_rev; // holds the edges based on index of the original graph scanf("%ld",&variables); // Initialize the vectors for(int i = 0; i <= 2 * variables; i++){ vector <int> row; graph.push_back(row); graph_rev.push_back(row); } readclauses(variables,graph,graph_rev); // Rev for(long i = 1; i < graph_rev.size(); i++) GraphRev(i, graph_rev); // Forward for(long i = finish_time-1; i > 0; i--){ long track = fintime[i]; GraphForward(variables,track, graph,i); } if(satisfiable == false) cout << "Not satisfiable" << endl; else cout << "Satisfiable" << endl; fclose(fp); return 0; }
2dbf8aceafa3e4122f3aa03ba1abef759d160ba4
0de08d45ca05f1eb31bf5d9fa44c7dfbfd3778f2
/Cam16bitTest/nkcOpenCV.cpp
09ef1cdf91af83394e3a637c7b151fb6e9ff6808
[]
no_license
nakaguchi/Cam16bitTest
3f601e32340bab4049968be90ff6aa800f6070ba
6b2349403b7a64a1a99ce589cea843c8b3d9ca79
refs/heads/master
2022-12-12T20:40:44.380414
2020-09-08T06:01:06
2020-09-08T06:01:06
293,715,928
0
0
null
null
null
null
SHIFT_JIS
C++
false
false
2,679
cpp
#include "nkcOpenCV.h" #include <Windows.h> namespace nkc { namespace ocv { // 待たないwaitKey() int noWaitKey() { MSG msg; while (::PeekMessage(&msg, NULL, 0, 0, PM_NOREMOVE)) { if (::GetMessage(&msg, NULL, 0, 0) == 0) { // WM_QUIT ::PostQuitMessage(msg.wParam); return 0; } if (msg.message == WM_CHAR) return (int)msg.wParam; ::TranslateMessage(&msg); ::DispatchMessage(&msg); } return -1; } // 複数画像を縦横に連結表示 void imShowMulti( cv::String winname, std::vector<cv::Mat>& imgs, // 全ての表示画像(8bit 3ch or 8bit 1chのみ) unsigned int cols, // 横の連結数 unsigned int rows, // 縦の連結数 cv::Size imgsize, // 表示する画像サイズ unsigned int border) { if (imgs.size() < 1 || cols < 1 || rows < 1) return; unsigned int w = imgsize.width + border, h = imgsize.height + border; cv::Mat board(h * rows + border, w * cols + border, CV_8UC3, CV_RGB(128, 128, 128)); for (unsigned int r = 0, i = 0; r < rows; r++) { for (unsigned int c = 0; c < cols; c++, i++) { cv::Rect roi_rect = cv::Rect(c * w + border, r * h + border, imgsize.width, imgsize.height); cv::Mat roi(board, roi_rect); if (i < imgs.size()) { if (imgs[i].type() == CV_8UC3) { resize(imgs[i], roi, imgsize); } else if (imgs[i].type() == CV_8UC1) { cv::Mat c3; cvtColor(imgs[i], c3, cv::COLOR_GRAY2BGR); resize(c3, roi, imgsize); } else { putText(roi, "Color mode not matched", cv::Point(20, 20), cv::FONT_HERSHEY_COMPLEX, 0.5, CV_RGB(0, 0, 0)); } } else { putText(roi, "No image", cv::Point(20, 20), cv::FONT_HERSHEY_COMPLEX, 0.5, CV_RGB(0, 0, 0)); } } } imshow(winname, board); } // 縦横比を保ったリサイズ cv::Mat KeepAspectResize(cv::Mat& img, int width, int height) { cv::Size outputSize; if (width > 0) { if (height > 0) { // 縦横指定(両サイズに収まるようにする) outputSize = cv::Size(height * img.cols / img.rows, width * img.rows / img.cols); if (outputSize.width > width) outputSize.width = width; else outputSize.height = height; } else { // 横幅指定 outputSize = cv::Size(width, width * img.rows / img.cols); } } else { if (height > 0) { // 縦幅指定 outputSize = cv::Size(height * img.cols / img.rows, height); } else { // 縦横どちらも指定無い場合は入力のコピーを返す return img.clone(); } } cv::Mat resized; cv::resize(img, resized, outputSize); return resized; } // ウインドウハンドルを取得 HANDLE getWindowHandle(cv::String winname) { return ::FindWindowA(NULL, winname.c_str()); } }; // namespace ocv }; // namespace nkc
907c7428441aad126168710bc9dfaec7cff02382
6a6b61f3b3d74c871d6202b9f61d79b81e757b2e
/GraphIO.h
3a3d570f6bfcddfe43a0e838cbcf1b6359eddab4
[]
no_license
raminzahedi/Network-Simulator
42ae57c2cf4aeec426180fd9f85c5dc1b056a4fc
0fcac3ef58dfef744184ca4ac67018807d53da71
refs/heads/main
2023-01-14T13:36:13.842727
2020-11-17T18:16:09
2020-11-17T18:16:09
313,699,364
1
0
null
null
null
null
UTF-8
C++
false
false
451
h
#include <iostream> #include <sstream> #include <string> #include <fstream> #include <cstdio> #include <cstdlib> #include <ctime> #include "Graph.h" #ifndef GRAPH_IO_HEADER #define GRAPH_IO_HEADER using namespace std; class GraphIO : public Graph { public: GraphIO ( ); ~GraphIO ( ); int read ( string ); int write ( string ); private: long getNumber ( ifstream& ); }; #endif
5c44c9cc04e9737f06a094f615a4f9bdd0487bf0
a6bfdf4d2dd1ea4ae285215c651c2b64479b6b6a
/bench/function/simd/acosh.cpp
57c6308ae25a47ed90a34a3452b27a8269ea9289
[ "BSL-1.0" ]
permissive
jeffamstutz/boost.simd
fb62210c30680c3cb2ffcc8ed80f8a0050f675fd
8afe9673c2a806976a77bc8bbca4cb1116a710cb
refs/heads/develop
2021-01-13T04:06:02.762442
2017-01-05T02:56:52
2017-01-06T16:11:47
77,879,665
6
1
null
2017-01-03T03:08:57
2017-01-03T03:08:57
null
UTF-8
C++
false
false
771
cpp
// ------------------------------------------------------------------------------------------------- // Copyright 2016 - NumScale SAS // // Distributed under the Boost Software License, Version 1.0. // See accompanying file LICENSE.txt or copy at // http://www.boost.org/LICENSE_1_0.txt // ------------------------------------------------------------------------------------------------- #include <simd_bench.hpp> #include <boost/simd/function/simd/acosh.hpp> #include <boost/simd/pack.hpp> namespace nsb = ns::bench; namespace bs = boost::simd; DEFINE_SIMD_BENCH(simd_acosh, bs::acosh); DEFINE_BENCH_MAIN() { nsb::for_each<simd_acosh, NS_BENCH_IEEE_TYPES>(1, 10); }
85b1537202d8da46a61b3887b57a872041026fa8
8d5fe26b90cf4115cb6ba1c702502b507cf4f40b
/iPrintableDocumentDeal/MsOffice/Word2010/CFrames.h
4ec756c313dfa9ab5d3a374e648ba09d5d209393
[]
no_license
radtek/vs2015PackPrj
c6c6ec475014172c1dfffab98dd03bd7e257b273
605b49fab23cb3c4a427d48080ffa5e0807d79a7
refs/heads/master
2022-04-03T19:50:37.865876
2020-01-16T10:09:37
2020-01-16T10:09:37
null
0
0
null
null
null
null
GB18030
C++
false
false
1,736
h
// 从类型库向导中用“添加类”创建的计算机生成的 IDispatch 包装类 #import "C:\\Program Files (x86)\\Microsoft Office\\Office14\\MSWORD.OLB" no_namespace // CFrames 包装类 class CFrames : public COleDispatchDriver { public: CFrames(){} // 调用 COleDispatchDriver 默认构造函数 CFrames(LPDISPATCH pDispatch) : COleDispatchDriver(pDispatch) {} CFrames(const CFrames& dispatchSrc) : COleDispatchDriver(dispatchSrc) {} // 属性 public: // 操作 public: // Frames 方法 public: LPDISPATCH get_Application() { LPDISPATCH result; InvokeHelper(0x3e8, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&result, NULL); return result; } long get_Creator() { long result; InvokeHelper(0x3e9, DISPATCH_PROPERTYGET, VT_I4, (void*)&result, NULL); return result; } LPDISPATCH get_Parent() { LPDISPATCH result; InvokeHelper(0x3ea, DISPATCH_PROPERTYGET, VT_DISPATCH, (void*)&result, NULL); return result; } LPUNKNOWN get__NewEnum() { LPUNKNOWN result; InvokeHelper(0xfffffffc, DISPATCH_PROPERTYGET, VT_UNKNOWN, (void*)&result, NULL); return result; } long get_Count() { long result; InvokeHelper(0x1, DISPATCH_PROPERTYGET, VT_I4, (void*)&result, NULL); return result; } LPDISPATCH Item(long Index) { LPDISPATCH result; static BYTE parms[] = VTS_I4 ; InvokeHelper(0x0, DISPATCH_METHOD, VT_DISPATCH, (void*)&result, parms, Index); return result; } LPDISPATCH Add(LPDISPATCH Range) { LPDISPATCH result; static BYTE parms[] = VTS_DISPATCH ; InvokeHelper(0x64, DISPATCH_METHOD, VT_DISPATCH, (void*)&result, parms, Range); return result; } void Delete() { InvokeHelper(0x65, DISPATCH_METHOD, VT_EMPTY, NULL, NULL); } // Frames 属性 public: };
0cca1b5510fc3baf09b73c9668e4223d8e27ff05
9bf237b47591f0faae6ef3935be2012584eff1cb
/Common/Application.h
7940a2bf52ed9eb4bed6cf0c758405f550309a11
[]
no_license
Alex-Chang/FileAnlayzer
d1492e94a912c50325e0857c1735989ec5b6c459
65e74fd7300cd77027ad6b708d273be314130270
refs/heads/master
2020-04-05T23:26:48.565619
2012-10-09T12:46:12
2012-10-09T12:46:12
null
0
0
null
null
null
null
UTF-8
C++
false
false
550
h
#include "Plugin.h" #include <map> #include "FileHelper.h" using namespace std; class Application { private: typedef map<string, Plugin*> PluginList; typedef PluginList::iterator PluginIterator; PluginList mPluginMap; FileList mCurrentFileList; map<HINSTANCE, string> mDllList; protected: void backDictionary(); void enterDictionary(string subFolder); public: void initialise(); void shutdown(); void run(); void printAboutInfo(); void printHelpInfo(); void printMenu(); void fillCurrentFileList(); void printCurrentPath(); };
8566972fecc079210eff75e19630ebb0bc2fd010
321451b3cfe1535b45f756383f4a4efe7733c14d
/reinforcement_learning/rlclientlib/utility/config_collection.cc
420d9e20952d99e6dad3e218fad69918539eae38
[]
no_license
movableink/vowpal_wabbit
ea471c16e08ea00a789c1725babac6af74b05785
277484317b8e09e5bda4cb4952ea8ad67961a80f
refs/heads/master
2020-03-17T15:23:17.820811
2018-07-21T12:39:26
2018-07-21T12:39:26
133,709,047
0
0
null
2018-05-16T18:41:18
2018-05-16T18:41:17
null
UTF-8
C++
false
false
2,120
cc
#include "config_collection.h" #include "str_util.h" namespace reinforcement_learning { namespace utility { config_collection::config_collection():_pmap(new map_type()) {} config_collection::~config_collection() { delete _pmap; } config_collection::config_collection(const config_collection& other) { _pmap = new map_type(*( other._pmap )); } config_collection& config_collection::operator=(const config_collection& rhs) { if ( this != &rhs ) { _pmap = new map_type(*(rhs._pmap)); } return *this; } config_collection& config_collection::operator=(config_collection&& temp) noexcept { if ( this != &temp ) { auto& map = *_pmap; temp._pmap->swap(map); } return *this; } config_collection::config_collection(config_collection&& temp) noexcept { _pmap = temp._pmap; temp._pmap = nullptr; } void config_collection::set(const char* name, const char* value) { auto& map = *_pmap; map[name] = value; } const char* config_collection::get(const char* name, const char* defval) const { auto& map = *_pmap; const auto it = map.find(name); if (it != map.end()) return it->second.c_str(); return defval; } int config_collection::get_int(const char* name, const int defval) const { auto& map = *_pmap; const auto it = map.find(name); if (it != map.end()) return atoi(it->second.c_str()); return defval; } bool config_collection::get_bool(const char* name, const bool defval) const { auto& map = *_pmap; const auto it = map.find(name); if ( it != map.end() ) { auto sval = it->second; str_util::trim(str_util::to_lower(sval)); if ( sval == "true" ) return true; else if ( sval == "false" ) return false; else return defval; // value string is neither true nor false. return default } return defval; } float config_collection::get_float(const char* name, float defval) const { auto& map = *_pmap; const auto it = map.find(name); if ( it != map.end() ) return atof(it->second.c_str()); return defval; } }}
3f8cc59310a4ba08f704a354d2a414a77f6587ce
b5aa98a43c376af64e7d7f4b761ea549f9783e5f
/app/Components/Shaders/DiffuseMaterial.cpp
25ca867984be281e3b5661db5b090614aaeab03a
[ "MIT" ]
permissive
mohammadt3anii/MobileRayTracer
319319a7162ca3ae97714a577df0cef43ebe4375
794cfba707e1c6a7fde8809b41b7adc8deef3d40
refs/heads/master
2020-04-04T16:09:18.419293
2018-11-03T19:09:35
2018-11-03T19:09:35
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,307
cpp
// // Created by puscas on 31/07/17. // #include "Components/Shaders/DiffuseMaterial.hpp" using ::Components::DiffuseMaterial; using ::MobileRT::Intersection; using ::MobileRT::Ray; using ::MobileRT::Scene; DiffuseMaterial::DiffuseMaterial(Scene &&scene, const Accelerator accelerator) noexcept : Shader{::std::move(scene), 0, accelerator} { } bool DiffuseMaterial::shade( ::glm::vec3 *const rgb, const Intersection &intersection, const Ray &/*ray*/) noexcept { if (intersection.material_ != nullptr) { const ::glm::vec3 &Le {intersection.material_->Le_}; const ::glm::vec3 &kD {intersection.material_->Kd_}; const ::glm::vec3 &kS {intersection.material_->Ks_}; const ::glm::vec3 &kT {intersection.material_->Kt_}; if (::glm::any(::glm::greaterThan(kD, ::glm::vec3 {0}))) { *rgb = kD; } else if (::glm::any(::glm::greaterThan(kS, ::glm::vec3 {0}))) { *rgb = kS; } else if (::glm::any(::glm::greaterThan(kT, ::glm::vec3 {0}))) { *rgb = kT; } else if (::glm::any(::glm::greaterThan(Le, ::glm::vec3 {0}))) { *rgb = Le; } } else { const ::glm::vec3 &primitiveColor {intersection.primitiveColor_}; *rgb = primitiveColor; } return false; }
55df084f1bd0200328b23538dee32fa35fe00126
1ae40287c5705f341886bbb5cc9e9e9cfba073f7
/Osmium/SDK/FN_ItemInspectUpgradePopupMenu_functions.cpp
65b9ab491fc21f230a03239e9145edb0fa0eb46c
[]
no_license
NeoniteDev/Osmium
183094adee1e8fdb0d6cbf86be8f98c3e18ce7c0
aec854e60beca3c6804f18f21b6a0a0549e8fbf6
refs/heads/master
2023-07-05T16:40:30.662392
2023-06-28T23:17:42
2023-06-28T23:17:42
340,056,499
14
8
null
null
null
null
UTF-8
C++
false
false
10,575
cpp
// Fortnite (4.5-CL-4159770) SDK #ifdef _MSC_VER #pragma pack(push, 0x8) #endif #include "../SDK.hpp" namespace SDK { //--------------------------------------------------------------------------- //Functions //--------------------------------------------------------------------------- // Function ItemInspectUpgradePopupMenu.ItemInspectUpgradePopupMenu_C.InitalizeButtonNavigation // (Public, BlueprintCallable, BlueprintEvent) void UItemInspectUpgradePopupMenu_C::InitalizeButtonNavigation() { static auto fn = UObject::FindObject<UFunction>("Function ItemInspectUpgradePopupMenu.ItemInspectUpgradePopupMenu_C.InitalizeButtonNavigation"); UItemInspectUpgradePopupMenu_C_InitalizeButtonNavigation_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function ItemInspectUpgradePopupMenu.ItemInspectUpgradePopupMenu_C.SetupUpgradeRarityVisiblity // (Public, BlueprintCallable, BlueprintEvent) // Parameters: // ESlateVisibility Visibility (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData) void UItemInspectUpgradePopupMenu_C::SetupUpgradeRarityVisiblity(ESlateVisibility Visibility) { static auto fn = UObject::FindObject<UFunction>("Function ItemInspectUpgradePopupMenu.ItemInspectUpgradePopupMenu_C.SetupUpgradeRarityVisiblity"); UItemInspectUpgradePopupMenu_C_SetupUpgradeRarityVisiblity_Params params; params.Visibility = Visibility; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function ItemInspectUpgradePopupMenu.ItemInspectUpgradePopupMenu_C.SetupEvolultionVisibility // (Public, BlueprintCallable, BlueprintEvent) // Parameters: // ESlateVisibility Visibility (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData) void UItemInspectUpgradePopupMenu_C::SetupEvolultionVisibility(ESlateVisibility Visibility) { static auto fn = UObject::FindObject<UFunction>("Function ItemInspectUpgradePopupMenu.ItemInspectUpgradePopupMenu_C.SetupEvolultionVisibility"); UItemInspectUpgradePopupMenu_C_SetupEvolultionVisibility_Params params; params.Visibility = Visibility; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function ItemInspectUpgradePopupMenu.ItemInspectUpgradePopupMenu_C.SetupPerkModVisibility // (Public, BlueprintCallable, BlueprintEvent) // Parameters: // ESlateVisibility Visibility (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData) void UItemInspectUpgradePopupMenu_C::SetupPerkModVisibility(ESlateVisibility Visibility) { static auto fn = UObject::FindObject<UFunction>("Function ItemInspectUpgradePopupMenu.ItemInspectUpgradePopupMenu_C.SetupPerkModVisibility"); UItemInspectUpgradePopupMenu_C_SetupPerkModVisibility_Params params; params.Visibility = Visibility; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function ItemInspectUpgradePopupMenu.ItemInspectUpgradePopupMenu_C.SetLevelUpVisibility // (Public, BlueprintCallable, BlueprintEvent) // Parameters: // ESlateVisibility Visibility (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData) void UItemInspectUpgradePopupMenu_C::SetLevelUpVisibility(ESlateVisibility Visibility) { static auto fn = UObject::FindObject<UFunction>("Function ItemInspectUpgradePopupMenu.ItemInspectUpgradePopupMenu_C.SetLevelUpVisibility"); UItemInspectUpgradePopupMenu_C_SetLevelUpVisibility_Params params; params.Visibility = Visibility; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function ItemInspectUpgradePopupMenu.ItemInspectUpgradePopupMenu_C.BndEvt__ButonLevelUp_K2Node_ComponentBoundEvent_31_CommonButtonClicked__DelegateSignature // (BlueprintEvent) // Parameters: // class UCommonButton* Button (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, InstancedReference, IsPlainOldData) void UItemInspectUpgradePopupMenu_C::BndEvt__ButonLevelUp_K2Node_ComponentBoundEvent_31_CommonButtonClicked__DelegateSignature(class UCommonButton* Button) { static auto fn = UObject::FindObject<UFunction>("Function ItemInspectUpgradePopupMenu.ItemInspectUpgradePopupMenu_C.BndEvt__ButonLevelUp_K2Node_ComponentBoundEvent_31_CommonButtonClicked__DelegateSignature"); UItemInspectUpgradePopupMenu_C_BndEvt__ButonLevelUp_K2Node_ComponentBoundEvent_31_CommonButtonClicked__DelegateSignature_Params params; params.Button = Button; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function ItemInspectUpgradePopupMenu.ItemInspectUpgradePopupMenu_C.BndEvt__ButtonViewEvolution_K2Node_ComponentBoundEvent_48_CommonButtonClicked__DelegateSignature // (BlueprintEvent) // Parameters: // class UCommonButton* Button (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, InstancedReference, IsPlainOldData) void UItemInspectUpgradePopupMenu_C::BndEvt__ButtonViewEvolution_K2Node_ComponentBoundEvent_48_CommonButtonClicked__DelegateSignature(class UCommonButton* Button) { static auto fn = UObject::FindObject<UFunction>("Function ItemInspectUpgradePopupMenu.ItemInspectUpgradePopupMenu_C.BndEvt__ButtonViewEvolution_K2Node_ComponentBoundEvent_48_CommonButtonClicked__DelegateSignature"); UItemInspectUpgradePopupMenu_C_BndEvt__ButtonViewEvolution_K2Node_ComponentBoundEvent_48_CommonButtonClicked__DelegateSignature_Params params; params.Button = Button; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function ItemInspectUpgradePopupMenu.ItemInspectUpgradePopupMenu_C.BndEvt__ButtonPerks_K2Node_ComponentBoundEvent_65_CommonButtonClicked__DelegateSignature // (BlueprintEvent) // Parameters: // class UCommonButton* Button (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, InstancedReference, IsPlainOldData) void UItemInspectUpgradePopupMenu_C::BndEvt__ButtonPerks_K2Node_ComponentBoundEvent_65_CommonButtonClicked__DelegateSignature(class UCommonButton* Button) { static auto fn = UObject::FindObject<UFunction>("Function ItemInspectUpgradePopupMenu.ItemInspectUpgradePopupMenu_C.BndEvt__ButtonPerks_K2Node_ComponentBoundEvent_65_CommonButtonClicked__DelegateSignature"); UItemInspectUpgradePopupMenu_C_BndEvt__ButtonPerks_K2Node_ComponentBoundEvent_65_CommonButtonClicked__DelegateSignature_Params params; params.Button = Button; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function ItemInspectUpgradePopupMenu.ItemInspectUpgradePopupMenu_C.BndEvt__CancelButton_K2Node_ComponentBoundEvent_99_CommonButtonClicked__DelegateSignature // (BlueprintEvent) // Parameters: // class UCommonButton* Button (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, InstancedReference, IsPlainOldData) void UItemInspectUpgradePopupMenu_C::BndEvt__CancelButton_K2Node_ComponentBoundEvent_99_CommonButtonClicked__DelegateSignature(class UCommonButton* Button) { static auto fn = UObject::FindObject<UFunction>("Function ItemInspectUpgradePopupMenu.ItemInspectUpgradePopupMenu_C.BndEvt__CancelButton_K2Node_ComponentBoundEvent_99_CommonButtonClicked__DelegateSignature"); UItemInspectUpgradePopupMenu_C_BndEvt__CancelButton_K2Node_ComponentBoundEvent_99_CommonButtonClicked__DelegateSignature_Params params; params.Button = Button; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function ItemInspectUpgradePopupMenu.ItemInspectUpgradePopupMenu_C.OnDeactivated // (Event, Protected, BlueprintEvent) void UItemInspectUpgradePopupMenu_C::OnDeactivated() { static auto fn = UObject::FindObject<UFunction>("Function ItemInspectUpgradePopupMenu.ItemInspectUpgradePopupMenu_C.OnDeactivated"); UItemInspectUpgradePopupMenu_C_OnDeactivated_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function ItemInspectUpgradePopupMenu.ItemInspectUpgradePopupMenu_C.OnActivated // (Event, Protected, BlueprintEvent) void UItemInspectUpgradePopupMenu_C::OnActivated() { static auto fn = UObject::FindObject<UFunction>("Function ItemInspectUpgradePopupMenu.ItemInspectUpgradePopupMenu_C.OnActivated"); UItemInspectUpgradePopupMenu_C_OnActivated_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function ItemInspectUpgradePopupMenu.ItemInspectUpgradePopupMenu_C.BndEvt__ButtonRarity_K2Node_ComponentBoundEvent_1_CommonButtonClicked__DelegateSignature // (BlueprintEvent) // Parameters: // class UCommonButton* Button (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, InstancedReference, IsPlainOldData) void UItemInspectUpgradePopupMenu_C::BndEvt__ButtonRarity_K2Node_ComponentBoundEvent_1_CommonButtonClicked__DelegateSignature(class UCommonButton* Button) { static auto fn = UObject::FindObject<UFunction>("Function ItemInspectUpgradePopupMenu.ItemInspectUpgradePopupMenu_C.BndEvt__ButtonRarity_K2Node_ComponentBoundEvent_1_CommonButtonClicked__DelegateSignature"); UItemInspectUpgradePopupMenu_C_BndEvt__ButtonRarity_K2Node_ComponentBoundEvent_1_CommonButtonClicked__DelegateSignature_Params params; params.Button = Button; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function ItemInspectUpgradePopupMenu.ItemInspectUpgradePopupMenu_C.ExecuteUbergraph_ItemInspectUpgradePopupMenu // () // Parameters: // int EntryPoint (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData) void UItemInspectUpgradePopupMenu_C::ExecuteUbergraph_ItemInspectUpgradePopupMenu(int EntryPoint) { static auto fn = UObject::FindObject<UFunction>("Function ItemInspectUpgradePopupMenu.ItemInspectUpgradePopupMenu_C.ExecuteUbergraph_ItemInspectUpgradePopupMenu"); UItemInspectUpgradePopupMenu_C_ExecuteUbergraph_ItemInspectUpgradePopupMenu_Params params; params.EntryPoint = EntryPoint; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } } #ifdef _MSC_VER #pragma pack(pop) #endif
8c485f4600739cc3097575b7a17945a85092d379
e572189d60a70df27b95fc84b63cc24048b90d09
/codejam/2020/qual/a.cpp
fafc1f7139fa6b8ff40245261c42e6c4ef12c615
[]
no_license
namhong2001/Algo
00f70a0f6132ddf7a024aa3fc98ec999fef6d825
a58f0cb482b43c6221f0a2dd926dde36858ab37e
refs/heads/master
2020-05-22T12:29:30.010321
2020-05-17T06:16:14
2020-05-17T06:16:14
186,338,640
0
0
null
null
null
null
UTF-8
C++
false
false
1,221
cpp
#include <iostream> #include <vector> using namespace std; typedef vector<int> vi; typedef vector<vi> vii; int rowCnt(vii &matrix) { int N = matrix.size(); int ret = 0; for (int i=0; i<N; ++i) { vector<bool> checked(N+1, false); for (int j=0; j<N; ++j) { if (checked[matrix[i][j]]) { ret++; break; } checked[matrix[i][j]] = true; } } return ret; } int colCnt(vii &matrix) { int N = matrix.size(); int ret = 0; for (int j=0; j<N; ++j) { vector<bool> checked(N+1, false); for (int i=0; i<N; ++i) { if (checked[matrix[i][j]]) { ret++; break; } checked[matrix[i][j]] = true; } } return ret; } int trace(vii &matrix) { int N = matrix.size(); int ret = 0; for (int i=0; i<N; ++i) ret += matrix[i][i]; return ret; } int main() { ios::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr); int T; cin >> T; for (int t=1; t<=T; ++t) { int N; cin >> N; vii matrix(N, vi(N)); for (int i=0; i<N; ++i) for (int j=0; j<N; ++j) cin >> matrix[i][j]; cout << "Case #" << t << ": " << trace(matrix) << ' ' << rowCnt(matrix) << ' ' << colCnt(matrix) << '\n'; } return 0; }
1a6f38e657e80314d800db29ffd242a34246c058
b163e83fa01efeec6f19996528cd382cb7f62098
/lib/Target/JVM/JVMTargetMachine.cpp
9040d30938ced1143961122a8066347581fd3a41
[ "NCSA" ]
permissive
jbhateja/llvm_jvm
dde0be2c81c7a1f274d00576d5a71dbde9b80910
f6df667676cb057ea42f766f1f99c2d4c66a9071
refs/heads/master
2020-04-16T05:56:29.664086
2019-03-10T16:02:39
2019-03-10T16:02:46
165,327,435
4
0
null
null
null
null
UTF-8
C++
false
false
8,123
cpp
//===- JVMTargetMachine.cpp - Define TargetMachine for JVM -==// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// /// /// \file /// \brief This file defines the JVM-specific subclass of TargetMachine. /// //===----------------------------------------------------------------------===// #include "JVMTargetMachine.h" #include "JVM.h" #include "JVMTargetObjectFile.h" #include "MCTargetDesc/JVMMCTargetDesc.h" #include "llvm/CodeGen/MachineFunctionPass.h" #include "llvm/CodeGen/Passes.h" #include "llvm/CodeGen/RegAllocRegistry.h" #include "llvm/CodeGen/TargetPassConfig.h" #include "llvm/IR/Function.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/TargetRegistry.h" #include "llvm/Target/TargetOptions.h" #include "llvm/Transforms/Scalar.h" #include "llvm/Transforms/InstCombine/InstCombine.h" using namespace llvm; #define DEBUG_TYPE "jvm" // JVM Optimization static cl::opt<bool> JvmAggOpt("jvm-aggressive-opts", cl::desc("JVM Aggressive Optimization."), cl::init(false)); static cl::opt<bool> JvmClient("jvm-client", cl::desc("IR to Java Translation."), cl::init(false)); static cl::opt<bool> JvmLSOpt("jvm-ls-opt", cl::desc("JVM load store optimization."), cl::init(false)); extern "C" void LLVMInitializeJVMTarget() { // Register the target. RegisterTargetMachine<JVMTargetMachine> X(getTheJVMTarget32()); RegisterTargetMachine<JVMTargetMachine> Y(getTheJVMTarget64()); } //===----------------------------------------------------------------------===// // JVM Lowering public interface. //===----------------------------------------------------------------------===// static Reloc::Model getEffectiveRelocModel(Optional<Reloc::Model> RM) { if (!RM.hasValue()) return Reloc::PIC_; return *RM; } void JVMTargetMachine::doCommandLineValidation() { bool dumpclassfile; cl::GetCommandLineOption<bool>("dump-class-file", dumpclassfile); bool enablejvmassembler; cl::GetCommandLineOption<bool>("enable-jvm-assembler", enablejvmassembler); if (dumpclassfile && !enablejvmassembler) llvm::errs() << "Warning : -dump-class-file works only in conjunction " "with -enable-jvm-assembler.\n"; } /// Create an JVM architecture model. /// JVMTargetMachine::JVMTargetMachine(const Target &T, const Triple &TT, StringRef CPU, StringRef FS, const TargetOptions &Options, Optional<Reloc::Model> RM, Optional<CodeModel::Model> CM, CodeGenOpt::Level OL, bool JIT) : LLVMTargetMachine(T, TT.isArch64Bit() ? "E-p:32:32-i:32:32-f:32:32" : "E-p:32:32-i:32:32-f:32:32", TT, CPU, FS, Options, getEffectiveRelocModel(RM), CM ? *CM : CodeModel::Large, OL), TLOF(static_cast<TargetLoweringObjectFile *>(new JVMTargetObjectFile())) { this->Options.TrapUnreachable = true; // JVM treats each function as an independent unit. Force // -ffunction-sections, effectively, so that we can emit them independently. this->Options.FunctionSections = true; this->Options.DataSections = true; this->Options.UniqueSectionNames = true; this->Options.MCOptions.AsmVerbose = false; // Disabling FastISel for JVM. setFastISel(false); setO0WantsFastISel(false); initAsmInfo(); // Note that we don't use setRequiresStructuredCFG(true). It disables // optimizations than we're ok with, and want, such as critical edge // splitting and tail merging. } JVMTargetMachine::~JVMTargetMachine() {} const JVMSubtarget * JVMTargetMachine::getSubtargetImpl(const Function &F) const { Attribute CPUAttr = F.getFnAttribute("target-cpu"); Attribute FSAttr = F.getFnAttribute("target-features"); std::string CPU = !CPUAttr.hasAttribute(Attribute::None) ? CPUAttr.getValueAsString().str() : TargetCPU; std::string FS = !FSAttr.hasAttribute(Attribute::None) ? FSAttr.getValueAsString().str() : TargetFS; auto &I = SubtargetMap[CPU + FS]; if (!I) { // This needs to be done before we create a new subtarget since any // creation will depend on the TM and the code generation flags on the // function that reside in TargetOptions. resetTargetOptions(F); I = llvm::make_unique<JVMSubtarget>(TargetTriple, CPU, FS, *this); } return I.get(); } namespace { /// JVM Code Generator Pass Configuration Options. class JVMPassConfig final : public TargetPassConfig { public: JVMPassConfig(JVMTargetMachine &TM, PassManagerBase &PM) : TargetPassConfig(TM, PM) {} JVMTargetMachine &getJVMTargetMachine() const { return getTM<JVMTargetMachine>(); } FunctionPass *createTargetRegisterAllocator(bool) override; void addIRPasses() override; void addCodeGenPrepare() override; bool addInstSelector() override; void addPostRegAlloc() override; bool addGCPasses() override { return false; } void addPreEmitPass() override; void addOptimizedRegAlloc(FunctionPass *RegAllocPass) override; void addMachinePasses() override; }; } // end anonymous namespace TargetPassConfig *JVMTargetMachine::createPassConfig(PassManagerBase &PM) { return new JVMPassConfig(*this, PM); } FunctionPass *JVMPassConfig::createTargetRegisterAllocator(bool) { return nullptr; // No reg alloc } //===----------------------------------------------------------------------===// // The following functions are called from lib/CodeGen/Passes.cpp to modify // the CodeGen pass sequence. //===----------------------------------------------------------------------===// void JVMPassConfig::addIRPasses() { TargetPassConfig::addIRPasses(); addPass(createJVMLowerMemoryIntrinsics()); addPass(createAggressiveDCEPass()); if (JvmAggOpt) addPass(createInstructionCombiningPass()); addPass(createJVMIRDecorator()); addPass(createAggressiveDCEPass()); if (JvmAggOpt) addPass(createInstructionCombiningPass()); if (JvmClient) addPass(createX2JavaPass()); } void JVMPassConfig::addCodeGenPrepare() { // Disable all code gene prepare optimizations for now. } void JVMPassConfig::addMachinePasses() { //TODO: Add machine passes incrementally as needed. addPass(&PHIEliminationID, false); addPass(createJVMPreAllocationFixups()); addPass(createJVMCopyElision()); addPreEmitPass(); } bool JVMPassConfig::addInstSelector() { (void)TargetPassConfig::addInstSelector(); addPass(createJVMISelDag(getJVMTargetMachine(), getOptLevel())); return false; } void JVMPassConfig::addOptimizedRegAlloc(FunctionPass *RegAllocPass) { disablePass(&RegisterCoalescerID); TargetPassConfig::addOptimizedRegAlloc(RegAllocPass); } void JVMPassConfig::addPostRegAlloc() { // TODO: The following CodeGen passes don't currently support code containing // virtual registers. Consider removing their restrictions and re-enabling // them. // Has no asserts of its own, but was not written to handle virtual regs. disablePass(&ShrinkWrapID); // These functions all require the NoVRegs property. disablePass(&MachineCopyPropagationID); disablePass(&PostRASchedulerID); disablePass(&FuncletLayoutID); disablePass(&StackMapLivenessID); disablePass(&LiveDebugValuesID); disablePass(&PatchableFunctionID); disablePass(&PrologEpilogCodeInserterID); TargetPassConfig::addPostRegAlloc(); } void JVMPassConfig::addPreEmitPass() { TargetPassConfig::addPreEmitPass(); if (JvmLSOpt) addPass(createJVMLoadStoreEliminationOpt()); addPass(createJVMOffsetAllocator()); addPass(createJVMPostAllocationFixups()); }
00cdc798b161f2c3fd0d01d8508a1cb54cf57ea3
e10614f4b6a2183709dd197fea6f9298be2678c1
/1819Fall/COMP2012H/PAs/PA2/Stock_skeleton_full_declarations/Snapshot.h
94fe0b402589e8b34d80347b2060c0fedf723b1d
[]
no_license
cokenhe/hkust-comp-material
63a267fff783e6ff53eeaeeeb8ad44599dd23c72
43af76fcdf9c47996a9ddd0e7b76b9d99ef8df3c
refs/heads/main
2023-05-06T18:40:29.057754
2021-05-20T10:45:55
2021-05-20T10:45:55
334,102,018
5
0
null
null
null
null
UTF-8
C++
false
false
5,999
h
// do NOT submit this file // do NOT modify this file #ifndef SRC_SNAPSHOT_H_ #define SRC_SNAPSHOT_H_ #include <iostream> using std::cout; using std::endl; #include "Stock.h" #include "StockNode.h" // Snapshot has a linked list of stocks, a pointer to an integer that represents the current time, // and the time at which the Snapshot is created. // It represents the states of the StockNodes in the database at a certain interval in time. struct Snapshot { StockNode* head; // The head of the linked list of stocks. // A head node must be created every time a snapshot is created (i.e. head should never be a nullptr). // head (this data member, not the actual head node) should point to the same node (head node), // regardless of the operations. int* const currentTime; // Points to the current time instance. // Note that it is an integer pointer, // so that every snapshot in a database share the same currentTime. // *currentTime will be incremented every time an operation is done in the snapshot. int time; // The time at which the snapshot is created. }; /* * create a Snapshot object and return it. * Its head should point to a dynamically created Head node. * Initialize currentTime and time. */ Snapshot createSnapshot(int* const currentTime); /* * Replicate the most recent state/the top of the earlier snapshot and return it. * This snapshot's head should point to the Head node of a newly created linked list, * and each of the nodes has no update initially, * such that print(earlier) is same as print(the stamped snapshot), at this moment, * and head is not a nullptr. * Initialize currentTime and time appropriately as well. They should share the same currentTime. * Note that deep copy is required for the linked list. * * You can assume earlier is not a nullptr. */ Snapshot stampSnapshot(Snapshot& earlier); /* * ***************************************************************************************************** * * * NOTE: For all the global functions below, you can assume snapshot is NOT a nullptr, for simplicity. * * * ***************************************************************************************************** */ /* * Avoid memory leak. * Deallocate the memory of any objects dynamically created during its construction and * any one of the operations. * Hint: you can safely use undo. * Therefore, you can assume all snapshots are deleted from the the latest to the earliest when we do grading. */ void deleteSnapshot(Snapshot& snapshot); // operation: /* * Add a stock of the corresponding stockId and value to the linked list at the current time by pushing an update. * The linked list should be sorted by the stocks' ID, in ascending order, such that * printing should show a linked list sorted by ID at any time. It will return true if the stock * is successfully added and false otherwise. * * If a stock with the same stockId already exists at the current time, do nothing and return false. * For example, if a stock with an ID 1 exists at time 10 and is removed at time 11, then at time 12, * the stock does not exist. * * If the stock does not exist at the current time (even if it existed before), * create a new StockNode storing that stock and create an update with time *currentTime + 1. * Then, push the update to a proper node. * Remember to increment *currentTime and return true; * * You can assume both stockId and value are non-negative. */ bool add(Snapshot& snapshot, int stockId, double value); // operation: /* * Remove a stock of the corresponding stockId in the linked list at the current time by pushing an update. * It will return true if the stock is successfully removed and false otherwise. * * If a stock with the same stockId exists at the current time, remove it by creating an update with time * *currentTime + 1 and pushing it to a proper node. Remember to increment *currentTime and return true. * * If the stock does not exist at the current time, do nothing and return false. * * You can assume stockId is non-negative. */ bool remove(Snapshot& snapshot, int stockId); // operation: /* * Set the value of the stock of the corresponding stockId at the current time by pushing an update. * It will return true if the stock is successfully set and false otherwise. * * If a stock with the same stockId exists at the current time, set its value by creating an update with * time *currentTime + 1 and pushing it to a proper node. Remember to increment *currentTime and return true. * * If the stock does not exist at the current time, do nothing and return false. * * You can assume stockId is non-negative. */ bool set(Snapshot& snapshot, int stockId, double value); /* * Undo the effects of the operation most recently performed. * * Note that you should delete some dynamically created objects to avoid memory leak. * Remember to decrement *currentTime. * If there is nothing to undo, do nothing and return false, * return true otherwise. */ bool undo(Snapshot& snapshot); /* * Return the value of the stock with ID stockId at a certain time. * If the stock exists at the time, return its value at the time. * If the stock does not exist at the time, return -1. * * You can assume stockId is non-negative and time is within the snapshot's time interval. */ double getValueAt(const Snapshot& snapshot, int stockId, int time); // The following functions are given. Do not modify them. // Print the current states of the linked list. void printSnapshot(const Snapshot& snapshot); // Print the states of the stock of an ID in the snapshot's time interval. void printStock(const Snapshot& snapshot, int stockId, int interval); #endif /* SRC_SNAPSHOT_H_ */
a4abcd63f4548d29f51fd56dec64be66e86ff0f4
20aab3ff4cdf44f9976686a2f161b3a76038e782
/c/shooting/12/engine.h
616cc45d85db40ae6d7f79a063f352ea188111c1
[ "MIT" ]
permissive
amenoyoya/old-project
6eee1e3e27ea402c267fc505b80f31fa89a2116e
640ec696af5d18267d86629098f41451857f8103
refs/heads/master
2020-06-12T20:06:25.828454
2019-07-12T04:09:30
2019-07-12T04:09:30
194,408,956
0
0
null
null
null
null
SHIFT_JIS
C++
false
false
855
h
#pragma once /* 基本ゲームオブジェクト */ struct GameObject{ string loaderrstr; virtual void init(){} virtual bool load(){return true;} virtual bool draw(){return true;} GameObject(): loaderrstr("ロードに失敗しました") {} }; /* ゲームアプリケーションクラス */ class GameApp: public DxLibApp{ vector<GameObject*> m_gObjArray; void dxmain(){ for(auto it=m_gObjArray.begin(); it!=m_gObjArray.end(); ++it){ if(!(*it)->load()){ iolib::msgbox((*it)->loaderrstr, "エラー", MB_OK|MB_ICONWARNING, thiswin()); return; } (*it)->init(); } while(procscene()){ for(auto it=m_gObjArray.begin(); it!=m_gObjArray.end(); ++it){ if(!(*it)->draw()) return; } } } protected: void registobj(GameObject *obj){ m_gObjArray.push_back(obj); } };
e15ce71e875492b4f953c03131b433fbae8d3b69
3e11dc7aee5b08d296762de34aa56ad628de968f
/sample/SampleBroadcaster-Swift/Pods/Headers/Private/glm/glm/detail/intrinsic_geometric.hpp
a824b1b0dd84a8ae1332c37b2257e8a3d89b9a3a
[ "LGPL-2.1-only", "MIT" ]
permissive
ParsifalC/VideoCore
9f6fb03729992022e19b34f22568e1c24819ad01
1ecb3b261e0ad6139e27299d5be459bf91a1a17f
refs/heads/master
2023-05-28T18:53:27.178985
2016-04-27T09:37:23
2016-04-27T09:37:23
57,192,837
0
0
MIT
2023-05-11T02:48:06
2016-04-27T07:24:46
C++
UTF-8
C++
false
false
53
hpp
../../../../../glm/glm/detail/intrinsic_geometric.hpp
622012a68ac8c9ea85960b4af46f4f78d73bfbd6
06a674bf57fcfed1e915aa50ae791e2907ad22c1
/Week1/BallGreen.hpp
85b2286d22e5701f9937838f62aaf5cf85afdbbf
[]
no_license
emres13/emresardogancode2
c0553b69446f3e0766c3a1a9ddadda9a6c1ccfb1
59d2c80d614cfbfedc073f6c9681dcd7392faa2f
refs/heads/master
2021-01-17T13:12:15.528323
2016-05-09T17:35:09
2016-05-09T17:35:09
53,873,393
1
0
null
null
null
null
UTF-8
C++
false
false
508
hpp
#pragma once // another and more modern way to prevent the compiler from including thiis file more than once #include "ofMain.h" #include "Ball.hpp" // we need to include the 'mother' class, the compiler will include the mother/base class so we have access to all the methods inherited class BallGreen : public Ball { // we set the class to inherit from 'ofBall' public: virtual void draw(); // this is the only method we actually want to be different from the 'mother class' };
9bc7d8a1f3d3b37f32e67ca218a610bbec4eac8e
b55a216d79994395c10392adbd36f362669fdbcb
/cpp/1131.cpp
5253cd7af7196248a40f656a5a843d9afda67c28
[]
no_license
ronaksingh27/cses-solutions
6186f9cb94727674c98915435eb58d8f1b987219
1b859e0adfb127021f3dae632e1b8c98984c83c3
refs/heads/master
2023-08-24T22:41:14.721383
2021-09-23T14:04:53
2021-09-23T14:04:53
null
0
0
null
null
null
null
UTF-8
C++
false
false
537
cpp
#include <bits/stdc++.h> using namespace std; const int N = 2e5 + 5; int n, d[N], x; vector<int> adj[N]; void dfs(int u, int p) { if (d[u] > d[x]) x = u; for (int v: adj[u]) { if (v != p) { d[v] = d[u] + 1; dfs(v, u); } } } int main() { ios::sync_with_stdio(false); cin.tie(0); cout.tie(0); cin >> n; for (int i = 1, u, v; i < n; ++i) { cin >> u >> v; adj[u].emplace_back(v); adj[v].emplace_back(u); } d[1] = 0; dfs(1, -1); d[x] = 0; dfs(x, -1); cout << d[x] << "\n"; return 0; }
149ca78bcaa622688cedab1aa179d960aff11e0a
f0a26ec6b779e86a62deaf3f405b7a83868bc743
/Engine/Source/Developer/SessionFrontend/Private/Widgets/Console/SSessionConsoleToolbar.h
b575c891c8c7b787dd6fe568b9b99619b8809dc7
[]
no_license
Tigrouzen/UnrealEngine-4
0f15a56176439aef787b29d7c80e13bfe5c89237
f81fe535e53ac69602bb62c5857bcdd6e9a245ed
refs/heads/master
2021-01-15T13:29:57.883294
2014-03-20T15:12:46
2014-03-20T15:12:46
18,375,899
1
0
null
null
null
null
UTF-8
C++
false
false
1,427
h
// Copyright 1998-2014 Epic Games, Inc. All Rights Reserved. /*============================================================================= SSessionConsoleToolbar.h: Declares the SSessionConsoleToolbar class. =============================================================================*/ #pragma once #define LOCTEXT_NAMESPACE "SSessionConsoleToolbar" /** * Implements the device toolbar widget. */ class SSessionConsoleToolbar : public SCompoundWidget { public: SLATE_BEGIN_ARGS(SSessionConsoleToolbar) { } SLATE_END_ARGS() public: /** * Constructs the widget. * * @param InArgs - The construction arguments. * @param CommandList - The command list to use. */ BEGIN_SLATE_FUNCTION_BUILD_OPTIMIZATION void Construct( const FArguments& InArgs, const TSharedRef<FUICommandList>& CommandList ) { FSessionConsoleCommands::Register(); // create the toolbar FToolBarBuilder Toolbar(CommandList, FMultiBoxCustomization::None); { Toolbar.AddToolBarButton(FSessionConsoleCommands::Get().Copy); Toolbar.AddSeparator(); Toolbar.AddToolBarButton(FSessionConsoleCommands::Get().Clear); Toolbar.AddToolBarButton(FSessionConsoleCommands::Get().Save); } ChildSlot [ SNew(SBorder) .BorderImage(FEditorStyle::GetBrush("ToolPanel.GroupBorder")) .Padding(0.0f) [ Toolbar.MakeWidget() ] ]; } END_SLATE_FUNCTION_BUILD_OPTIMIZATION }; #undef LOCTEXT_NAMESPACE
68eb679e599b43d9283a4c2db61c19d77ec071fc
43a258c00bc46b57081eaa829d20bf75bfe9487d
/utility/files.h
576f4aa9ef558b2354694c972c0a5d2fc7a467f2
[]
no_license
HealthVivo/mumdex
96dbfb7110ae253abcfdcfd49d85fbea6ee9f430
25e1f2f2da385bafbdfae61dc61afedb044041b8
refs/heads/master
2023-09-03T12:56:44.843200
2021-11-23T18:26:31
2021-11-23T18:26:31
null
0
0
null
null
null
null
UTF-8
C++
false
false
47,595
h
// // files.h // // classes and functions for dealing with files // // Copyright Peter Andrews 2015 @ CSHL // #ifndef LONGMEM_FILES_H_ #define LONGMEM_FILES_H_ #include <stdio.h> #include <sys/mman.h> #include <sys/stat.h> #include <unistd.h> #include <fcntl.h> #include <string> // Placed before cstring, no error, why? #include <algorithm> #include <cstring> #include <cstdio> #include <iostream> #include <fstream> #include <limits> #include <map> #include <sstream> #include <thread> #include <utility> #include <vector> #include "error.h" #ifndef MAP_POPULATE #define MAP_POPULATE 0 #endif namespace paa { extern bool read_ahead; extern bool memory_mapped; // A safe file name inline std::string safe_file_name(const std::string & name) { if (name.empty()) return ""; std::istringstream stream{name.c_str()}; char c; std::string result{""}; while (stream.get(c)) if (isalnum(c) || c == '.') result += c; return result; } // Remove specific file extension, if exists inline std::string remove_extension(const std::string & file_name, const std::string & extension) { const size_t pos{file_name.find_last_of('.')}; if (pos == std::string::npos) return file_name; if (pos != std::string::npos && file_name.substr(pos + 1) == extension) return file_name.substr(0, pos); return file_name; } // Get file extension, if exists inline std::string extension(const std::string & file_name) { const size_t pos{file_name.find_last_of('.')}; if (pos == std::string::npos) return ""; return file_name.substr(pos); } // Remove path component of file name inline std::string remove_path(const std::string & file_name) { const size_t pos{file_name.find_last_of('/')}; if (pos != std::string::npos) { return file_name.substr(pos + 1); } else { return file_name; } } // Grab file contents as a string inline std::string file_string(const std::string & name) { std::ifstream css{name.c_str()}; std::string result; char c; while (css.get(c)) result += c; return result; } // Files and directories inline uint64_t file_size(const std::string & file_name) { struct stat st; if (stat(file_name.c_str(), &st)) { return 0; } return static_cast<uint64_t>(st.st_size); } inline void mkdir(const std::string & dir_name) { if (::mkdir(dir_name.c_str(), S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH) && errno != EEXIST) throw Error("Problem creating directory") << dir_name; } inline std::string get_cwd() { constexpr uint64_t Ksize{1024}; char buffer[Ksize]; if (getcwd(buffer, Ksize) == nullptr) throw Error("Problem getting current working directory"); return std::string(buffer); } inline void symlink(const std::string & target, const std::string & linkpath) { #ifdef __CYGWIN__ throw Error("Cannot do symlink under cygwin"); #else if (::symlink(target.c_str(), linkpath.c_str()) && errno != EEXIST) throw Error("Problem creating symbilic link") << linkpath << "to" << target; #endif } inline bool readable(const std::string & file) { return !access(file.c_str(), R_OK); } inline void unlink(const std::string & file, const bool complain = false) { if (::unlink(file.c_str()) && complain) { throw Error("Could not unlink file") << file; } } inline void mkfifo(const std::string & file) { if (::mkfifo(file.c_str(), 0666)) { throw Error("Could not mkfifo") << file; } } // Find a path below in directory the hierarchy inline std::string below(const std::string & name) { std::string result; uint64_t n{0}; while (!readable(result + name)) { result += "../"; if (++n == 20) throw Error("Too many levels down looking for") << name; } return result + name; } inline uint64_t get_block_size(const std::string name) { struct stat sb; if (stat(name.c_str(), &sb) == -1) { perror("stat"); throw Error("stat call failure for") << name; } return sb.st_blksize; } inline std::string get_next_file(const std::string & name, const std::string ext) { static std::map<std::string, unsigned int> last_indexes; for (unsigned int i{last_indexes[name + ext] + 1}; ; ++i) { const std::string test{name + "." + std::to_string(i) + "." + ext}; if (!readable(test)) { last_indexes[name] = i; return test; } } } // Read Specific columns from disk class Columns { public: Columns(const std::string & file_name, const uint64_t size_hint, const std::string & columns, const bool header) { // Get list of desired column names or numbers std::istringstream column_input{columns.c_str()}; std::string column_spec; while (getline(column_input, column_spec, ',')) { // column spec is either name or name:type std::istringstream spec_stream{column_spec.c_str()}; std::string column_name{}; std::string column_type{}; getline(spec_stream, column_name, ':'); if (spec_stream) { spec_stream >> column_type; } column_names.push_back(column_name); column_types.push_back(column_type); } // Input file name std::ifstream input{file_name.c_str()}; if (!input) throw Error("Could not open input file") << file_name; // Process header, or just use column numbers passed using ColumnLookup = std::pair<unsigned int, unsigned int>; const std::vector<ColumnLookup> column_numbers{ [this, header, columns, &input] () { std::vector<ColumnLookup> result; if (header) { // Column names are strings std::string header_line; getline(input, header_line); std::string column_name; std::istringstream header_stream{header_line.c_str()}; unsigned int column{0}; while (header_stream >> column_name) { const std::vector<std::string>::const_iterator found{ find(column_names.begin(), column_names.end(), column_name)}; if (found != column_names.end()) result.emplace_back(column, found - column_names.begin()); ++column; } } else { // Column names are numbers, starting with 1 for (unsigned int c{0}; c != column_names.size(); ++c) { result.emplace_back(static_cast<unsigned int>( stoul(column_names[c]) - 1), c); column_names[c] = std::string(header ? "" : "column ") + column_names[c]; } sort(result.begin(), result.end(), [](const ColumnLookup & lhs, const ColumnLookup & rhs) { return lhs.first < rhs.first; }); } if (column_names.size() != result.size()) { throw Error("Could not find all columns specified in") << columns; } return result; }()}; if (0) { std::cerr << "Parse:" << std::endl; for (const std::pair<unsigned int, unsigned int> & lu : column_numbers) { std::cerr << column_names[lu.second] << " " << lu.first << " " << lu.second << std::endl; } } // Reserve space for data data.resize(column_names.size()); for (unsigned int c{0}; c != data.size(); ++c) { data.reserve(size_hint); } // Read in data line by line std::string line; std::string text; double value{0}; while (getline(input, line)) { std::istringstream stream{line.c_str()}; std::vector<ColumnLookup>::const_iterator nc{column_numbers.begin()}; unsigned int c{0}; while (stream) { if (nc != column_numbers.end() && nc->first == c) { if (stream >> value) data[nc++->second].push_back(value); } else { stream >> text; } ++c; } } if (0) std::cerr << "Read " << data[0].size() << " lines from " << file_name << std::endl; } const std::string & name(unsigned int c) const { return column_names[c]; } const std::string & type(unsigned int c) const { return column_types[c]; } uint64_t n_rows() const { return n_cols() ? data[0].size() : 0; } unsigned int n_cols() const { return static_cast<unsigned int>(data.size()); } const std::vector<double> & operator[](const unsigned int c) const { return data[c]; } private: std::vector<std::string> column_names{}; std::vector<std::string> column_types{}; std::vector<std::vector<double>> data{}; }; // class FileVector {}; // Iterator for file-based vector template<class Type, template <class ...> class Container> class VectorIterator { public: // iterator properties using value_type = Type; using difference_type = std::ptrdiff_t; using pointer = void; using reference = void; using iterator_category = std::random_access_iterator_tag; // constructor VectorIterator(const Container<Type> & file_, const uint64_t current_) : file{&file_}, current{current_} { } // null iterator construction explicit VectorIterator(const void *) : file{nullptr}, current{static_cast<uint64_t>(-1)} { } // value access const Type operator*() const { return (*file)[current]; } const Type operator[](const uint64_t offset) const { return (*file)[current + offset]; } // const Type operator->() const { return (*file)[current]; } // iterator comparison bool operator!=(const VectorIterator & rhs) const { return current != rhs.current; } bool operator==(const VectorIterator & rhs) const { return current == rhs.current; } bool operator<(const VectorIterator & rhs) const { return current < rhs.current; } int64_t operator-(const VectorIterator & rhs) const { return static_cast<int64_t>(current) - static_cast<int64_t>(rhs.current); } // iteration and random access VectorIterator & operator++() { ++current; return *this; } VectorIterator & operator--() { --current; return *this; } VectorIterator & operator+=(const uint64_t offset) { current += offset; return *this; } VectorIterator & operator-=(const uint64_t offset) { current -= offset; return *this; } VectorIterator operator+(const uint64_t offset) const { VectorIterator advanced = *this; advanced.current += offset; return advanced; } VectorIterator operator-(const uint64_t offset) const { VectorIterator advanced = *this; advanced.current -= offset; return advanced; } private: const Container<Type> * file; uint64_t current{0}; }; // Make an on-disk file (not in memory) act like a read-only vector template<class Type> class FileVector { public: using const_iterator = VectorIterator<Type, paa::FileVector>; // deleted FileVector(const FileVector &) = delete; FileVector & operator=(const FileVector &) = delete; FileVector & operator=(FileVector &&) = delete; // construction explicit FileVector(const std::string & file_name, const bool warn_empty = true) : file{fopen(file_name.c_str(), "rb")} { // Try a few times - sometimes nfs is malfunctioning temporarily if (file == nullptr) { sleep(2); file = fopen(file_name.c_str(), "rb"); if (file == nullptr) { sleep(5); file = fopen(file_name.c_str(), "rb"); if (file == nullptr) { perror("Open File"); throw Error("Could not open file in FileVector") << file_name; } } } n_elem = file_size(file_name) / sizeof(Type); if (warn_empty && n_elem == 0) { std::cerr << "Empty file opened " << file_name << std::endl; } // fileno is not available on cygwin and is not posix #if 0 const int fd{fileno(file)}; if (fd == -1) { throw Error("Could not get file descriptor for file") << file_name; } struct stat buf; if (fstat(fd, &buf) == -1) { throw Error("Could not get status for file") << file_name; } const uint64_t file_size{static_cast<uint64_t>(buf.st_size)}; if (warn_empty && file_size == 0) { std::cerr << "Empty file opened " << file_name << std::endl; } n_elem = file_size / sizeof(Type); #endif } FileVector(FileVector && other) noexcept : file{other.file}, n_elem{other.n_elem} { other.file = nullptr; other.n_elem = 0; } // size uint64_t size() const { return n_elem; } uint64_t bytes() const { return size() * sizeof(Type); } // iteration const_iterator begin() const { return const_iterator{*this, 0}; } const_iterator end() const { return const_iterator{*this, size()}; } // Just a memory location to read into union FakeType { uint64_t dummy; // to assure proper alignment char data[sizeof(Type)]; }; // access Type operator[](const uint64_t index) const { FakeType entry; if (fseek(file, index * sizeof(Type), SEEK_SET) != 0) { throw Error("Problem seeking in file"); } if (fread(&entry, sizeof(Type), 1, file) != 1) { throw Error("Problem reading from file"); } return reinterpret_cast<Type&>(entry); } Type back() const { return (*this)[size() - 1]; } // destruction ~FileVector() { if (file != nullptr) { fclose(file); } } private: FILE * file{}; uint64_t n_elem{}; }; // Memory or Memory-Mapped read-only vector base class template<class Type> class MemoryVectorBase { public: typedef const Type * const_iterator; typedef Type * iterator; // deleted MemoryVectorBase(const MemoryVectorBase &) = delete; MemoryVectorBase & operator=(const MemoryVectorBase &) = delete; MemoryVectorBase & operator=(MemoryVectorBase &&) = delete; // construction MemoryVectorBase() { } MemoryVectorBase(MemoryVectorBase && other) noexcept : data{other.data}, n_elem{other.n_elem} { other.data = nullptr; other.n_elem = 0; } // size uint64_t size() const { return n_elem; } uint64_t bytes() const { return size() * sizeof(Type); } // iteration const_iterator begin() const { return data; } const_iterator end() const { return data + n_elem; } iterator begin() { return data; } iterator end() { return data + n_elem; } // access Type operator[](const uint64_t index) const { return data[index]; } Type & operator[](const uint64_t index) { return data[index]; } protected: Type * data{nullptr}; uint64_t n_elem{0}; }; // In-Memory read-only vector template<class Type> class MemoryVector : public MemoryVectorBase<Type> { public: // typedefs using Base = MemoryVectorBase<Type>; using Base::data; using Base::n_elem; // construction MemoryVector(MemoryVector && other) noexcept : Base{std::move(other)} { } explicit MemoryVector(const std::string & file_name, const bool warn_empty = true) { const int input{open(file_name.c_str(), O_RDONLY)}; if (input == -1) throw Error("could not open input") << file_name << "for reading"; struct stat buf; if (fstat(input, &buf) == -1) throw Error("Could not get status for file") << file_name; const uint64_t file_size{static_cast<uint64_t>(buf.st_size)}; n_elem = file_size / sizeof(Type); if (file_size == 0) { if (warn_empty) std::cerr << "Empty file in MemoryVector " << file_name << std::endl; } else { data = static_cast<Type *>(::operator new(sizeof(Type) * n_elem)); if (data == nullptr) throw Error("Could not allocate memory for") << file_name; char * cdata{reinterpret_cast<char *>(data)}; uint64_t bytes_read{0}; unsigned int error_count{0}; while (bytes_read < file_size) { const uint64_t bytes_to_read{file_size - bytes_read}; const int64_t read_result{ read(input, cdata + bytes_read, bytes_to_read)}; if (read_result == -1) { if (++error_count > 10) { perror("System error"); throw Error("Problem reading file in Memory Vector") << file_name << file_size << bytes_to_read; } } else { bytes_read += read_result; } } } close(input); } // destruction ~MemoryVector() { if (data != nullptr) delete data; } }; // Memory-mapped read-only vector template<class Type, bool ReadAhead> class TMappedVector : public MemoryVectorBase<Type> { public: // typedefs using Base = MemoryVectorBase<Type>; using Base::data; using Base::n_elem; using Base::bytes; // construction TMappedVector() : Base{} { } TMappedVector(TMappedVector && other) noexcept : Base{std::move(other)} { } TMappedVector(const std::string & file_name, const uint64_t expected) : TMappedVector{file_name, false} { if (this->size() != expected) throw Error("Unexpected size in MappedVector") << file_name; } explicit TMappedVector(const std::string & file_name, const bool warn_empty = true) { const int input{open(file_name.c_str(), O_RDONLY)}; if (input == -1) throw Error("could not open input") << file_name << "for reading"; struct stat buf; if (fstat(input, &buf) == -1) throw Error("Could not get status for file") << file_name; const uint64_t file_size{static_cast<uint64_t>(buf.st_size)}; if (file_size == 0) { if (warn_empty) std::cerr << "Empty file in TMappedVector " << file_name << std::endl; } else { data = static_cast<Type *>( mmap(nullptr, file_size, PROT_READ, MAP_SHARED | (ReadAhead ? MAP_POPULATE : 0), input, 0)); if (data == MAP_FAILED) { // Need PRIVATE on newer kernels with MAP_POPULATE data = static_cast<Type *>( mmap(nullptr, file_size, PROT_READ, MAP_PRIVATE | (ReadAhead ? MAP_POPULATE : 0), input, 0)); if (data == MAP_FAILED) { perror("System Error in mmap"); throw Error("Memory mapping error for mapped file") << file_name << file_size; } } } n_elem = file_size / sizeof(Type); close(input); } // destruction ~TMappedVector() { if (n_elem && munmap(data, bytes())) perror("munmap error in TMappedVector"); } }; // PreMapped loads slowly, but is used quickly template <class Type> using PreMappedVector = TMappedVector<Type, true>; // UnMapped loads instantly, but is used slowly at first template <class Type> using UnMappedVector = TMappedVector<Type, false>; // Use UnMapped as default template <class Type> using MappedVector = UnMappedVector<Type>; #if 0 // Only works for char Type template <class Type> class ZippedVector { public: ZippedVector(const std::string & unzipped_name, const uint64_t expected) { const std::string unzip{"zcat " + unzipped_name + ".gz"}; redi::ipstream input{unzip.c_str()}; if (!input) throw Error("Problem executing command") << unzip; input >> data; if (data.size() != expected) throw Error("Unexpected size in ZippedVector") << unzipped_name << data.size() << expected; } uint64_t size() const { return data.size(); } const Type & operator[](const uint64_t index) const { return data[index]; } private: std::string data{}; }; #endif // // Class that loads data from text file the first time, // and saves binary cache for later use of file // template <class Data> class BinaryCache { public: class NormalFileEnd {}; template <class ParseStreamFun> BinaryCache(const std::string & input_file_name, ParseStreamFun parse_line, std::string binary_file_name = "") { if (binary_file_name.empty()) { binary_file_name = input_file_name + ".bin"; } if (!readable(binary_file_name)) { try { std::ifstream in_stream{input_file_name.c_str()}; std::ofstream out_stream{binary_file_name.c_str(), std::ios::binary}; if (!in_stream) throw Error("Could not open input file in BinaryCache") << input_file_name; while (in_stream) { const Data item{parse_line(in_stream)}; out_stream.write(reinterpret_cast<const char *>(&item), sizeof(Data)); } } catch (NormalFileEnd &) { if (false) std::cerr << "File end" << std::endl; } } new (this) BinaryCache<Data>{binary_file_name}; } explicit BinaryCache(const std::string & binary_file_name) : data{binary_file_name} { } uint64_t size() const { return data.size(); } const Data & operator[](const uint64_t index) const { return data[index]; } const Data * begin() const { return data.begin(); } const Data * end() const { return data.end(); } private: const PreMappedVector<Data> data{"/dev/null", false}; }; template <class Type> void write_one(FILE * out, const Type & value, const char * name) { const uint64_t written = fwrite(&value, sizeof(Type), 1, out); if (written != 1) { perror(nullptr); throw Error("problem writing") << name; } } template <class Type> void read_one(FILE * in, Type & value, const char * name) { const uint64_t read_in = fread(&value, sizeof(Type), 1, in); if (read_in != 1) { perror(nullptr); throw Error("problem reading") << name; } } inline void bwritec(FILE * output, const void * data, const std::string & name, const uint64_t count) { const uint64_t written = fwrite(data, 1, count, output); if (written != count) { perror(nullptr); throw Error("problem writing") << count << "bytes at" << name << "only wrote" << written; } } inline void bwritec(const std::string & filename, const void * data, const std::string & name, const uint64_t count) { FILE * output = fopen(filename.c_str(), "wb"); if (output == nullptr) throw Error("could not open output") << filename << "for writing"; bwritec(output, data, name, count); if (fclose(output) != 0) throw Error("problem closing output file") << filename; } // Flexible Memory or Mapped vector // memory - read / write / change size // mapped - read only template<class Type> class FlexVector : public MemoryVectorBase<Type> { public: // typedefs using Base = MemoryVectorBase<Type>; using Base::data; using Base::n_elem; using Base::bytes; // construction FlexVector(const FlexVector &) = delete; FlexVector & operator=(const FlexVector &) = delete; FlexVector & operator=(FlexVector &&) = delete; FlexVector() : Base{} { } FlexVector(FlexVector && other) noexcept : Base{std::move(other)}, mapped_{other.mapped_} { other.mapped_ = false; } explicit FlexVector(const uint64_t new_n_elem) : Base{} { clear_and_resize(new_n_elem); } explicit FlexVector(const std::string & file_name, const bool mapped__ = true, const bool read_ahead_ = false, const bool warn_empty = true) : mapped_{mapped__} { if (mapped_) { read_mapped(file_name, read_ahead_, warn_empty); } else { read_memory(file_name); } } // destruction ~FlexVector() { // std::cerr << "Destroy FlexVector " << n_elem << " " << data << " " // << mapped_ << std::endl; free(); } // Common functions void free() { if (data) { if (mapped_) { if (munmap(data, bytes())) { perror("munmap error in FlexVector"); } } else { delete[] data; } } } void save(const std::string & file_name) const { bwritec(file_name, data, "FlexVector", n_elem * sizeof(Type)); } // Memory only functions void clear_and_resize(const uint64_t new_n_elem) { if (new_n_elem != n_elem) { free(); n_elem = new_n_elem; data = new Type[n_elem](); } else { for (uint64_t i{0}; i != n_elem; ++i) { data[i] = Type(); } } } void read_memory(const std::string &) { throw Error("read_memory not implemented yet"); } // Mapped only functions void read_mapped(const std::string & file_name, const bool read_ahead_ = true, const bool warn_empty = true) { free(); mapped_ = true; const int fid{open(file_name.c_str(), O_RDONLY)}; if (fid == -1) { throw Error("could not open input") << file_name << "for reading"; } struct stat buf; if (fstat(fid, &buf) == -1) { throw Error("Could not get status for file") << file_name; } const uint64_t file_size{static_cast<uint64_t>(buf.st_size)}; if (file_size == 0) { if (warn_empty) { std::cerr << "Empty file in FlexVector " << file_name << std::endl; } data = nullptr; } else { data = static_cast<Type *>( mmap(nullptr, file_size, PROT_READ, MAP_SHARED | (read_ahead_ ? MAP_POPULATE : 0), fid, 0)); if (data == MAP_FAILED) { // Need PRIVATE on newer kernels with MAP_POPULATE data = static_cast<Type *>( mmap(nullptr, file_size, PROT_READ, MAP_PRIVATE | (read_ahead_ ? MAP_POPULATE : 0), fid, 0)); if (data == MAP_FAILED) { perror("System Error in mmap"); throw Error("Memory mapping error for mapped file") << file_name << file_size; } } } n_elem = file_size / sizeof(Type); close(fid); } private: bool mapped_{false}; }; template<class T> void bwrite(FILE * output, const T & data, const std::string & name, const uint64_t count = 1) { bwritec(output, &data, name, sizeof(T) * count); } // void bwritec(const std::string & filename, const void * data, // const std::string & name, const uint64_t count); template<class T> void bwrite(const std::string & filename, const T & data, const std::string & name, const uint64_t count = 1) { bwritec(filename, &data, name, sizeof(T) * count); } void breadc(FILE * input, void * data, const std::string & name, const uint64_t count); template<class T> void bread(FILE * input, T & data, const std::string & name, const uint64_t count = 1) { breadc(input, &data, name, sizeof(T) * count); } void breadc(const std::string & filename, void * & data, const std::string & name, const uint64_t count); template<class T> void bread(const std::string & filename, T * & data, const std::string & name, const uint64_t count = 1) { breadc(filename, reinterpret_cast<void*&>(data), name, count * sizeof(T)); } template<class Type> class GrowingVector { public: typedef Type * iterator; typedef const Type * const_iterator; // deleted GrowingVector(const GrowingVector &) = delete; GrowingVector & operator=(const GrowingVector &) = delete; // construction, etc GrowingVector() noexcept(false) : GrowingVector{initial_size} {} explicit GrowingVector(const uint64_t start_size) noexcept(false) : capacity{start_size}, data{static_cast<Type *>(::operator new(sizeof(Type) * capacity))} { } GrowingVector(GrowingVector && other) noexcept : n_elem{other.n_elem}, capacity{other.capacity}, data{other.data} { other.n_elem = 0; other.capacity = 0; other.data = nullptr; } GrowingVector & operator=(GrowingVector && other) noexcept { if (capacity) delete data; n_elem = other.n_elem; capacity = other.capacity; data = other.data; other.n_elem = 0; other.capacity = 0; other.data = nullptr; return *this; } // expansion template<typename... VArgs> void emplace_back(VArgs && ... args) { expand_if_needed(); new (data + n_elem++) Type(std::forward<VArgs>(args) ...); } void push_back(const Type val) { expand_if_needed(); data[n_elem++] = val; } template <class P> void insert_back(P b, P e) { while (b != e) { push_back(*(b++)); } } // info uint64_t bytes() const { return capacity * sizeof(Type); } uint64_t size() const { return n_elem; } // read only access const Type * begin() const { return data; } const Type * end() const { return data + n_elem; } Type operator[](const uint64_t index) const { return data[index]; } const Type back() const { return data[n_elem - 1]; } // write access Type * begin() { return data; } Type * end() { return data + n_elem; } Type & operator[](const uint64_t index) { return data[index]; } Type & back() { return data[n_elem - 1]; } // shrinking void clear() { n_elem = 0; } void reduce_size(const uint64_t new_size) { n_elem = new_size; } // saving void save(const std::string & file_name) const { bwritec(file_name, data, "GrowingVector", n_elem * sizeof(Type)); } void write(std::FILE * out_file) const { bwritec(out_file, data, "GrowingVector", n_elem * sizeof(Type)); } void write_n(std::FILE * out_file, const uint64_t n) const { bwritec(out_file, data, "GrowingVector", n * sizeof(Type)); } // destruction ~GrowingVector() { if (capacity) delete data; } private: void expand_if_needed() { if (n_elem + 1 > capacity) { capacity *= 2; Type * new_data_location = static_cast<Type *>(::operator new(sizeof(Type) * capacity)); memcpy(new_data_location, data, n_elem * sizeof(Type)); delete data; data = new_data_location; } } static constexpr uint64_t initial_size{1024}; uint64_t n_elem{0}; uint64_t capacity{0}; Type * data{nullptr}; }; class MappedFile { public: // deleted MappedFile(const MappedFile &) = delete; MappedFile operator=(const MappedFile &) = delete; MappedFile & operator=(MappedFile &&) = delete; MappedFile(); explicit MappedFile(const std::string & file_name_, const bool warn_empty = true); MappedFile(MappedFile && other) noexcept; ~MappedFile(); void load(const std::string & file_name_, const bool warn_empty = true); const std::string & name() const { return file_name; } void unmap(); int advise(const char * start, uint64_t length, const int advice) const; void sequential(const char * start = nullptr, const uint64_t length = 0) const; void random(const char * start = nullptr, const uint64_t length = 0) const; void unneeded(const char * start = nullptr, const uint64_t length = 0) const; void needed(const char * start = nullptr, const uint64_t length = 0) const; char * begin() { return file_begin; } char * end() { return file_end; } const char * begin() const { return file_begin; } const char * end() const { return file_end; } const char * cbegin() const { return file_begin; } const char * cend() const { return file_end; } uint64_t size() const { return static_cast<uint64_t>(file_end - file_begin); } uint64_t page_size() const { return page; } private: std::string file_name{}; char * file_begin{nullptr}; char * file_end{nullptr}; uint64_t page{0}; }; class BinWriter { public: explicit BinWriter(const std::string & filename) : outfile{fopen(filename.c_str(), "wb")} { if (outfile == nullptr) throw Error("could not open outfile") << filename << "for writing"; } BinWriter(const BinWriter &) = delete; BinWriter operator=(const BinWriter &) = delete; ~BinWriter() { if (fclose(outfile) != 0) std::cerr << "problem closing BinWriter outfile" << std::endl; } FILE * outfile; }; template <class Out> BinWriter & operator<<(BinWriter & writer, const Out out) { bwrite(writer.outfile, out, "some binary value", 1); return writer; } // // FileMerger // // Keeps list of file names // merges the objects in them // // keeps sorted list (1) of objects from front of files // no objects elsewhere are lower than highest object in list (A) // // higher objects are still in files or in a separate sorted array (2) // // Merger opens and reads from files at current position // then sorts objects in (2) // // when (1) is empty, (2) is transferred to (1) so that (A) is satisfied // // Buffered Closed File // // Read a stream from many thousands of files at once // but can only have open 1000 or so at a time // how to handle? // // Want to limit file open/close operations // Want to limit read operations // Want data from all files to be accessible quickly // this means buffering, while attempting to keep // all soon-to-be-used data in cache if possible, // and maybe read-aheads to limit wait times for file access // // open file, read into big buffer, close file, // copy section into small buffer // read from small buffer until exhausted // copy from big buffer into small buffer // When big buffer exhausted, open thread to replenish // // keep small buffers in cache! // Files are intended to be stored in an array! // picture 4096 files // 16 cores * 32 KB = 512 KB // 512 KB / 4096 = 128 bytes // if 24 bytes per record // small buffer is 5.3 objects only! // // Similar reasoning gives for 20 MB shared cache // big buffer is 10248 bytes and holds 426.6 objects // // ~15 Million objects chr 1 per file // 30,000 file opens and reads per file // // 16 cores on wigclust 17-24 // 32 KB / core L1 cache // 256 KB / core L2 cache // 20 MB L3 cache x 2 processors // // Designed for sequential access // using next() // but can do initial binary search while open to find good starting point? // template <class Type, unsigned int small_buffer_bytes = 128, unsigned int big_buffer_bytes = 10240> class BufferedClosedFile { }; template<class Type> class OldMappedVector { public: typedef Type * iterator; typedef const Type * const_iterator; // deleted OldMappedVector(const OldMappedVector &) = delete; OldMappedVector & operator=(const OldMappedVector &) = delete; OldMappedVector & operator=(OldMappedVector &&) = delete; // use these member functions during building only OldMappedVector() : OldMappedVector{initial_size} {} explicit OldMappedVector(const uint64_t start_size) : capacity{start_size}, data{static_cast<Type *>(::operator new(sizeof(Type) * capacity))} { } OldMappedVector(OldMappedVector && old) noexcept : file{std::move(old.file)}, mapped{old.mapped}, n_elem{old.n_elem}, capacity{old.capacity}, data{old.data} { old.mapped = false; old.capacity = 0; } template<typename... VArgs> void emplace_back(VArgs && ... args) { expand_if_needed(); new (data + n_elem++) Type(std::forward<VArgs>(args) ...); } void push_back(const Type val) { expand_if_needed(); data[n_elem++] = val; } template <class P> void insert_back(P b, P e) { while (b != e) { push_back(*(b++)); } } Type * begin() { return data; } Type * end() { return data + n_elem; } void clear() { n_elem = 0; } void reduce_size(const uint64_t new_size) { n_elem = new_size; } void save(const std::string & file_name) const { bwritec(file_name, data, "OldMappedVector", n_elem * sizeof(Type)); } void write(std::FILE * out_file) const { bwritec(out_file, data, "OldMappedVector", n_elem * sizeof(Type)); } void write_n(std::FILE * out_file, const uint64_t n) const { bwritec(out_file, data, "OldMappedVector", n * sizeof(Type)); } // use these member function during reading only explicit OldMappedVector(const std::string & file_name, const bool warn_empty = true) : file{file_name, warn_empty}, mapped{file.begin() == nullptr ? false : true}, n_elem{file.size() / sizeof(Type)}, capacity{n_elem}, data{reinterpret_cast<Type *>(file.begin())} { } const std::string & name() const { return file.name(); } // these member functions can be used anytime uint64_t bytes() const { return capacity * sizeof(Type); } uint64_t size() const { return n_elem; } const Type * begin() const { return data; } const Type * end() const { return data + n_elem; } Type operator[](const uint64_t index) const { return data[index]; } Type & operator[](const uint64_t index) { return data[index]; } const Type back() const { return data[n_elem - 1]; } Type & back() { return data[n_elem - 1]; } ~OldMappedVector() { if (!mapped && capacity) delete data; } private: void expand_if_needed() { if (n_elem + 1 > capacity) { capacity *= 2; Type * new_data_location = static_cast<Type *>(::operator new(sizeof(Type) * capacity)); memcpy(new_data_location, data, n_elem * sizeof(Type)); delete data; data = new_data_location; } } static constexpr uint64_t initial_size{1000}; MappedFile file{}; bool mapped{false}; uint64_t n_elem{0}; uint64_t capacity{0}; Type * data{nullptr}; }; // // a potentially dangerous class - exists in a build state or a read state // and some member functions can only be used in one of the states // template<class Type> class OlderMappedVector { public: typedef Type * iterator; typedef const Type * const_iterator; // deleted OlderMappedVector(const OlderMappedVector &) = delete; OlderMappedVector & operator=(const OlderMappedVector &) = delete; OlderMappedVector & operator=(OlderMappedVector &&) = delete; // use these member functions during building only OlderMappedVector() : OlderMappedVector{initial_size} {} explicit OlderMappedVector(const uint64_t start_size) : capacity{start_size}, data{static_cast<Type *>(::operator new(sizeof(Type) * capacity))} { } OlderMappedVector(OlderMappedVector && old) noexcept : file{std::move(old.file)}, mapped{old.mapped}, n_elem{old.n_elem}, capacity{old.capacity}, data{old.data} { old.mapped = false; old.capacity = 0; } template<typename... VArgs> void emplace_back(VArgs && ... args) { expand_if_needed(); new (data + n_elem++) Type(std::forward<VArgs>(args) ...); } void push_back(const Type val) { expand_if_needed(); data[n_elem++] = val; } template <class P> void insert_back(P b, P e) { while (b != e) { push_back(*(b++)); } } Type * begin() { return data; } Type * end() { return data + n_elem; } void clear() { n_elem = 0; } void reduce_size(const uint64_t new_size) { n_elem = new_size; } void save(const std::string & file_name) const { bwritec(file_name, data, "OlderMappedVector", n_elem * sizeof(Type)); } void write(std::FILE * out_file) const { bwritec(out_file, data, "OlderMappedVector", n_elem * sizeof(Type)); } void write_n(std::FILE * out_file, const uint64_t n) const { bwritec(out_file, data, "OlderMappedVector", n * sizeof(Type)); } // use these member function during reading only explicit OlderMappedVector(const std::string & file_name, const bool warn_empty = true) : file{file_name, warn_empty}, mapped{file.begin() == nullptr ? false : true}, n_elem{file.size() / sizeof(Type)}, capacity{n_elem}, data{reinterpret_cast<Type *>(file.begin())} { } const std::string & name() const { return file.name(); } void load(const std::string & file_name_, const bool warn_empty = true) { file.load(file_name_, warn_empty); mapped = file.begin() == nullptr ? false : true; n_elem = file.size() / sizeof(Type); data = reinterpret_cast<Type *>(file.begin()); } // these member functions can be used anytime uint64_t bytes() const { return capacity * sizeof(Type); } uint64_t size() const { return n_elem; } const Type * begin() const { return data; } const Type * end() const { return data + n_elem; } Type operator[](const uint64_t index) const { return data[index]; } Type & operator[](const uint64_t index) { return data[index]; } const Type back() const { return data[n_elem - 1]; } Type & back() { return data[n_elem - 1]; } ~OlderMappedVector() { if (!mapped && capacity) delete data; } private: void expand_if_needed() { if (n_elem + 1 > capacity) { capacity *= 2; Type * new_data_location = static_cast<Type *>(::operator new(sizeof(Type) * capacity)); memcpy(new_data_location, data, n_elem * sizeof(Type)); delete data; data = new_data_location; } } static constexpr uint64_t initial_size{1000}; MappedFile file{}; bool mapped{false}; uint64_t n_elem{0}; uint64_t capacity{0}; Type * data{nullptr}; }; template<class BigInt, class SmallInt> class CompressedInts { public: explicit CompressedInts(const uint64_t capacity = 0, const uint64_t n_lookup = 0) : lookup{n_lookup}, small{capacity} { } explicit CompressedInts(const std::string & dir, const unsigned int small_start = 0, const unsigned int lookup_start = 0) : lookup{dir + "/lookup.bin"}, small{dir + "/counts.bin"}, big{dir + "/over.bin"}, small_position{small_start}, big_position{lookup[lookup_start]} {} #if 0 CompressedInts(CompressedInts && other) noexcept { lookup = move(other.lookup); small = move(other.small); big = move(other.big); small_position = other.small_position; big_position = other.big_position; } #endif BigInt next_int() const { if (small_position == small.size()) { throw Error("Tried to read past end of CompressedInts"); return std::numeric_limits<BigInt>::max(); } else { const SmallInt s = small[small_position++]; if (s == std::numeric_limits<SmallInt>::max()) { return big[big_position++]; } else { return s; } } } void add_int(unsigned int b) { if (b > std::numeric_limits<BigInt>::max()) { std::cerr << "add_int encountered big int " << b << std::endl; b = std::numeric_limits<BigInt>::max(); } if (b >= std::numeric_limits<SmallInt>::max()) { small.push_back(std::numeric_limits<SmallInt>::max()); big.push_back(static_cast<BigInt>(b)); } else { small.push_back(static_cast<SmallInt>(b)); } } void print_savings() const { std::cerr << "Saved " << small.size() * (sizeof(BigInt)-sizeof(SmallInt)) - big.size() * sizeof(BigInt) << " bytes" << std::endl; } void add_lookup_entry() { lookup.push_back(static_cast<unsigned int>(big.size())); } void save(const std::string & dir_name) const { mkdir(dir_name); std::ostringstream counts_filename; counts_filename << dir_name << "/counts.bin"; std::FILE * counts_file = fopen(counts_filename.str().c_str(), "wb"); if (counts_file == nullptr) throw Error("Problem opening counts file") << counts_filename.str(); if (fwrite(small.begin(), sizeof(SmallInt), small.size(), counts_file) != small.size()) throw Error("Problem writing in counts file") << counts_filename.str(); if (fclose(counts_file)) throw Error("Problem closing counts file") << counts_filename.str(); std::ostringstream over_filename; over_filename << dir_name << "/over.bin"; std::FILE * over_file = fopen(over_filename.str().c_str(), "wb"); if (over_file == nullptr) throw Error("Problem opening over file") << over_filename.str(); if (fwrite(big.begin(), sizeof(BigInt), big.size(), over_file) != big.size()) throw Error("Problem writing in over file") << over_filename.str(); if (fclose(over_file)) throw Error("Problem closing over file") << over_filename.str(); std::ostringstream lookup_filename; lookup_filename << dir_name << "/lookup.bin"; std::FILE * lookup_file = fopen(lookup_filename.str().c_str(), "wb"); if (lookup_file == nullptr) throw Error("Problem opening lookup file") << lookup_filename.str(); if (fwrite(lookup.begin(), sizeof(unsigned int), lookup.size(), lookup_file) != lookup.size()) throw Error("Problem writing in lookup file") << lookup_filename.str(); if (fclose(lookup_file)) throw Error("Problem closing lookup file") << lookup_filename.str(); print_savings(); } void relocate(const uint64_t new_small, const uint64_t new_lookup) const { small_position = new_small; big_position = lookup[new_lookup]; } uint64_t size() const { return small.size(); } SmallInt clipped_result(const uint64_t i) const { return small[i]; } private: OlderMappedVector<unsigned int> lookup; OlderMappedVector<SmallInt> small; OlderMappedVector<BigInt> big{}; mutable uint64_t small_position{0}; mutable uint64_t big_position{0}; }; typedef CompressedInts<uint16_t, uint8_t> Compressed; template <class STREAM> struct Fstream : public STREAM { explicit Fstream(const std::string & file_name, const std::string & description = "") : STREAM{file_name} { if (!*this) { std::ostringstream message; message << "Problem opening"; if (description.size()) message << ' ' << description; message << " file " << file_name; throw Error(message.str()); } } }; using iFstream = Fstream<std::ifstream>; using oFstream = Fstream<std::ofstream>; class EvenColumns { public: explicit EvenColumns(const std::string & spacing_ = " ", const uint64_t n_cols = 1) : spacing{spacing_}, max_len(n_cols), columns(n_cols, std::vector<std::string>(1)) {} ~EvenColumns() { if (output_) output(); } void output(std::ostream & out = std::cout) { output_ = false; for (uint64_t r{0};; ++r) { bool did_out{false}; std::ostringstream line; for (uint64_t c{0}; c != columns.size(); ++c) { std::vector<std::string> & column{columns[c]}; if (column.back().empty()) column.pop_back(); // Rethink this const uint64_t len{max_len[c]}; if (r >= column.size()) { line << std::string(len, ' '); } else { const std::string & text{column[r]}; line << text << std::string(len - text.size(), ' '); did_out = true; } if (c + 1 != columns.size()) line << spacing; } if (!did_out) break; out << line.str() << '\n'; } } EvenColumns & operator[](const uint64_t c) { increase_size(c + 1); current = c; return *this; } EvenColumns & operator++() { increase_size(++current + 1); return *this; } void increase_size(const uint64_t n_cols) { while (n_cols > columns.size()) { columns.push_back(std::vector<std::string>(1)); max_len.push_back(0); } } template<class Item> void add(const Item & item) { std::ostringstream text; text << item; for (const char c : text.str()) if (c == '\n') { const uint64_t len{columns[current].back().size()}; if (len > max_len[current]) max_len[current] = len; columns[current].push_back(""); } else { columns[current].back() += c; } } private: bool output_{true}; uint64_t current{0}; std::string spacing; std::vector<uint64_t> max_len; std::vector<std::vector<std::string>> columns; }; template <class Item> EvenColumns & operator<<(EvenColumns & columns, const Item & item) { columns.add(item); return columns; } inline EvenColumns & operator<<(EvenColumns & columns, const EvenColumns &) { return columns; } } // namespace paa #endif // LONGMEM_FILES_H_
2f57f5d790d45cc4dff901f7acdf379ff2c8f5fe
9cd8b42d4ea67deb6ec075a3da25d09e2a421544
/LuaKitProject/src/Projects/base/message_loop/message_loop_unittest.cc
64cf7c83122f244af64b60a0261964e952f2b2ea
[ "MIT" ]
permissive
andrewvmail/Luakit
de0c6f0d2655e09e63b998df2ca07202b5fbd134
eadbcf0e88fcf922d9b9592bffca9a582b7a236d
refs/heads/master
2023-01-12T23:31:33.773549
2022-12-29T02:58:55
2022-12-29T02:58:55
231,685,876
0
1
MIT
2020-01-04T00:17:27
2020-01-04T00:17:27
null
UTF-8
C++
false
false
34,189
cc
// Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <vector> #include "base/bind.h" #include "base/bind_helpers.h" #include "base/compiler_specific.h" #include "base/logging.h" #include "base/memory/ref_counted.h" #include "base/message_loop/message_loop.h" #include "base/message_loop/message_loop_proxy_impl.h" #include "base/message_loop/message_loop_test.h" #include "base/pending_task.h" #include "base/posix/eintr_wrapper.h" #include "base/run_loop.h" #include "base/synchronization/waitable_event.h" #include "base/thread_task_runner_handle.h" #include "base/threading/platform_thread.h" #include "base/threading/thread.h" #include "testing/gtest/include/gtest/gtest.h" #if defined(OS_WIN) #include "base/message_loop/message_pump_win.h" #include "base/process/memory.h" #include "base/strings/string16.h" #include "base/win/scoped_handle.h" #endif namespace base { // TODO(darin): Platform-specific MessageLoop tests should be grouped together // to avoid chopping this file up with so many #ifdefs. namespace { MessagePump* TypeDefaultMessagePumpFactory() { return MessageLoop::CreateMessagePumpForType(MessageLoop::TYPE_DEFAULT); } MessagePump* TypeIOMessagePumpFactory() { return MessageLoop::CreateMessagePumpForType(MessageLoop::TYPE_IO); } MessagePump* TypeUIMessagePumpFactory() { return MessageLoop::CreateMessagePumpForType(MessageLoop::TYPE_UI); } class Foo : public RefCounted<Foo> { public: Foo() : test_count_(0) { } void Test0() { ++test_count_; } void Test1ConstRef(const std::string& a) { ++test_count_; result_.append(a); } void Test1Ptr(std::string* a) { ++test_count_; result_.append(*a); } void Test1Int(int a) { test_count_ += a; } void Test2Ptr(std::string* a, std::string* b) { ++test_count_; result_.append(*a); result_.append(*b); } void Test2Mixed(const std::string& a, std::string* b) { ++test_count_; result_.append(a); result_.append(*b); } int test_count() const { return test_count_; } const std::string& result() const { return result_; } private: friend class RefCounted<Foo>; ~Foo() {} int test_count_; std::string result_; }; #if defined(OS_WIN) // This function runs slowly to simulate a large amount of work being done. static void SlowFunc(TimeDelta pause, int* quit_counter) { PlatformThread::Sleep(pause); if (--(*quit_counter) == 0) MessageLoop::current()->QuitWhenIdle(); } // This function records the time when Run was called in a Time object, which is // useful for building a variety of MessageLoop tests. static void RecordRunTimeFunc(Time* run_time, int* quit_counter) { *run_time = Time::Now(); // Cause our Run function to take some time to execute. As a result we can // count on subsequent RecordRunTimeFunc()s running at a future time, // without worry about the resolution of our system clock being an issue. SlowFunc(TimeDelta::FromMilliseconds(10), quit_counter); } void SubPumpFunc() { MessageLoop::current()->SetNestableTasksAllowed(true); MSG msg; while (GetMessage(&msg, NULL, 0, 0)) { TranslateMessage(&msg); DispatchMessage(&msg); } MessageLoop::current()->QuitWhenIdle(); } void RunTest_PostDelayedTask_SharedTimer_SubPump() { MessageLoop loop(MessageLoop::TYPE_UI); // Test that the interval of the timer, used to run the next delayed task, is // set to a value corresponding to when the next delayed task should run. // By setting num_tasks to 1, we ensure that the first task to run causes the // run loop to exit. int num_tasks = 1; Time run_time; loop.PostTask(FROM_HERE, Bind(&SubPumpFunc)); // This very delayed task should never run. loop.PostDelayedTask( FROM_HERE, Bind(&RecordRunTimeFunc, &run_time, &num_tasks), TimeDelta::FromSeconds(1000)); // This slightly delayed task should run from within SubPumpFunc). loop.PostDelayedTask( FROM_HERE, Bind(&PostQuitMessage, 0), TimeDelta::FromMilliseconds(10)); Time start_time = Time::Now(); loop.Run(); EXPECT_EQ(1, num_tasks); // Ensure that we ran in far less time than the slower timer. TimeDelta total_time = Time::Now() - start_time; EXPECT_GT(5000, total_time.InMilliseconds()); // In case both timers somehow run at nearly the same time, sleep a little // and then run all pending to force them both to have run. This is just // encouraging flakiness if there is any. PlatformThread::Sleep(TimeDelta::FromMilliseconds(100)); RunLoop().RunUntilIdle(); EXPECT_TRUE(run_time.is_null()); } const wchar_t kMessageBoxTitle[] = L"MessageLoop Unit Test"; enum TaskType { MESSAGEBOX, ENDDIALOG, RECURSIVE, TIMEDMESSAGELOOP, QUITMESSAGELOOP, ORDERED, PUMPS, SLEEP, RUNS, }; // Saves the order in which the tasks executed. struct TaskItem { TaskItem(TaskType t, int c, bool s) : type(t), cookie(c), start(s) { } TaskType type; int cookie; bool start; bool operator == (const TaskItem& other) const { return type == other.type && cookie == other.cookie && start == other.start; } }; std::ostream& operator <<(std::ostream& os, TaskType type) { switch (type) { case MESSAGEBOX: os << "MESSAGEBOX"; break; case ENDDIALOG: os << "ENDDIALOG"; break; case RECURSIVE: os << "RECURSIVE"; break; case TIMEDMESSAGELOOP: os << "TIMEDMESSAGELOOP"; break; case QUITMESSAGELOOP: os << "QUITMESSAGELOOP"; break; case ORDERED: os << "ORDERED"; break; case PUMPS: os << "PUMPS"; break; case SLEEP: os << "SLEEP"; break; default: NOTREACHED(); os << "Unknown TaskType"; break; } return os; } std::ostream& operator <<(std::ostream& os, const TaskItem& item) { if (item.start) return os << item.type << " " << item.cookie << " starts"; else return os << item.type << " " << item.cookie << " ends"; } class TaskList { public: void RecordStart(TaskType type, int cookie) { TaskItem item(type, cookie, true); DVLOG(1) << item; task_list_.push_back(item); } void RecordEnd(TaskType type, int cookie) { TaskItem item(type, cookie, false); DVLOG(1) << item; task_list_.push_back(item); } size_t Size() { return task_list_.size(); } TaskItem Get(int n) { return task_list_[n]; } private: std::vector<TaskItem> task_list_; }; // MessageLoop implicitly start a "modal message loop". Modal dialog boxes, // common controls (like OpenFile) and StartDoc printing function can cause // implicit message loops. void MessageBoxFunc(TaskList* order, int cookie, bool is_reentrant) { order->RecordStart(MESSAGEBOX, cookie); if (is_reentrant) MessageLoop::current()->SetNestableTasksAllowed(true); MessageBox(NULL, L"Please wait...", kMessageBoxTitle, MB_OK); order->RecordEnd(MESSAGEBOX, cookie); } // Will end the MessageBox. void EndDialogFunc(TaskList* order, int cookie) { order->RecordStart(ENDDIALOG, cookie); HWND window = GetActiveWindow(); if (window != NULL) { EXPECT_NE(EndDialog(window, IDCONTINUE), 0); // Cheap way to signal that the window wasn't found if RunEnd() isn't // called. order->RecordEnd(ENDDIALOG, cookie); } } void RecursiveFunc(TaskList* order, int cookie, int depth, bool is_reentrant) { order->RecordStart(RECURSIVE, cookie); if (depth > 0) { if (is_reentrant) MessageLoop::current()->SetNestableTasksAllowed(true); MessageLoop::current()->PostTask( FROM_HERE, Bind(&RecursiveFunc, order, cookie, depth - 1, is_reentrant)); } order->RecordEnd(RECURSIVE, cookie); } void QuitFunc(TaskList* order, int cookie) { order->RecordStart(QUITMESSAGELOOP, cookie); MessageLoop::current()->QuitWhenIdle(); order->RecordEnd(QUITMESSAGELOOP, cookie); } void RecursiveFuncWin(MessageLoop* target, HANDLE event, bool expect_window, TaskList* order, bool is_reentrant) { target->PostTask(FROM_HERE, Bind(&RecursiveFunc, order, 1, 2, is_reentrant)); target->PostTask(FROM_HERE, Bind(&MessageBoxFunc, order, 2, is_reentrant)); target->PostTask(FROM_HERE, Bind(&RecursiveFunc, order, 3, 2, is_reentrant)); // The trick here is that for recursive task processing, this task will be // ran _inside_ the MessageBox message loop, dismissing the MessageBox // without a chance. // For non-recursive task processing, this will be executed _after_ the // MessageBox will have been dismissed by the code below, where // expect_window_ is true. target->PostTask(FROM_HERE, Bind(&EndDialogFunc, order, 4)); target->PostTask(FROM_HERE, Bind(&QuitFunc, order, 5)); // Enforce that every tasks are sent before starting to run the main thread // message loop. ASSERT_TRUE(SetEvent(event)); // Poll for the MessageBox. Don't do this at home! At the speed we do it, // you will never realize one MessageBox was shown. for (; expect_window;) { HWND window = FindWindow(L"#32770", kMessageBoxTitle); if (window) { // Dismiss it. for (;;) { HWND button = FindWindowEx(window, NULL, L"Button", NULL); if (button != NULL) { EXPECT_EQ(0, SendMessage(button, WM_LBUTTONDOWN, 0, 0)); EXPECT_EQ(0, SendMessage(button, WM_LBUTTONUP, 0, 0)); break; } } break; } } } // TODO(darin): These tests need to be ported since they test critical // message loop functionality. // A side effect of this test is the generation a beep. Sorry. void RunTest_RecursiveDenial2(MessageLoop::Type message_loop_type) { MessageLoop loop(message_loop_type); Thread worker("RecursiveDenial2_worker"); Thread::Options options; options.message_loop_type = message_loop_type; ASSERT_EQ(true, worker.StartWithOptions(options)); TaskList order; win::ScopedHandle event(CreateEvent(NULL, FALSE, FALSE, NULL)); worker.message_loop()->PostTask(FROM_HERE, Bind(&RecursiveFuncWin, MessageLoop::current(), event.Get(), true, &order, false)); // Let the other thread execute. WaitForSingleObject(event, INFINITE); MessageLoop::current()->Run(); ASSERT_EQ(order.Size(), 17); EXPECT_EQ(order.Get(0), TaskItem(RECURSIVE, 1, true)); EXPECT_EQ(order.Get(1), TaskItem(RECURSIVE, 1, false)); EXPECT_EQ(order.Get(2), TaskItem(MESSAGEBOX, 2, true)); EXPECT_EQ(order.Get(3), TaskItem(MESSAGEBOX, 2, false)); EXPECT_EQ(order.Get(4), TaskItem(RECURSIVE, 3, true)); EXPECT_EQ(order.Get(5), TaskItem(RECURSIVE, 3, false)); // When EndDialogFunc is processed, the window is already dismissed, hence no // "end" entry. EXPECT_EQ(order.Get(6), TaskItem(ENDDIALOG, 4, true)); EXPECT_EQ(order.Get(7), TaskItem(QUITMESSAGELOOP, 5, true)); EXPECT_EQ(order.Get(8), TaskItem(QUITMESSAGELOOP, 5, false)); EXPECT_EQ(order.Get(9), TaskItem(RECURSIVE, 1, true)); EXPECT_EQ(order.Get(10), TaskItem(RECURSIVE, 1, false)); EXPECT_EQ(order.Get(11), TaskItem(RECURSIVE, 3, true)); EXPECT_EQ(order.Get(12), TaskItem(RECURSIVE, 3, false)); EXPECT_EQ(order.Get(13), TaskItem(RECURSIVE, 1, true)); EXPECT_EQ(order.Get(14), TaskItem(RECURSIVE, 1, false)); EXPECT_EQ(order.Get(15), TaskItem(RECURSIVE, 3, true)); EXPECT_EQ(order.Get(16), TaskItem(RECURSIVE, 3, false)); } // A side effect of this test is the generation a beep. Sorry. This test also // needs to process windows messages on the current thread. void RunTest_RecursiveSupport2(MessageLoop::Type message_loop_type) { MessageLoop loop(message_loop_type); Thread worker("RecursiveSupport2_worker"); Thread::Options options; options.message_loop_type = message_loop_type; ASSERT_EQ(true, worker.StartWithOptions(options)); TaskList order; win::ScopedHandle event(CreateEvent(NULL, FALSE, FALSE, NULL)); worker.message_loop()->PostTask(FROM_HERE, Bind(&RecursiveFuncWin, MessageLoop::current(), event.Get(), false, &order, true)); // Let the other thread execute. WaitForSingleObject(event, INFINITE); MessageLoop::current()->Run(); ASSERT_EQ(order.Size(), 18); EXPECT_EQ(order.Get(0), TaskItem(RECURSIVE, 1, true)); EXPECT_EQ(order.Get(1), TaskItem(RECURSIVE, 1, false)); EXPECT_EQ(order.Get(2), TaskItem(MESSAGEBOX, 2, true)); // Note that this executes in the MessageBox modal loop. EXPECT_EQ(order.Get(3), TaskItem(RECURSIVE, 3, true)); EXPECT_EQ(order.Get(4), TaskItem(RECURSIVE, 3, false)); EXPECT_EQ(order.Get(5), TaskItem(ENDDIALOG, 4, true)); EXPECT_EQ(order.Get(6), TaskItem(ENDDIALOG, 4, false)); EXPECT_EQ(order.Get(7), TaskItem(MESSAGEBOX, 2, false)); /* The order can subtly change here. The reason is that when RecursiveFunc(1) is called in the main thread, if it is faster than getting to the PostTask(FROM_HERE, Bind(&QuitFunc) execution, the order of task execution can change. We don't care anyway that the order isn't correct. EXPECT_EQ(order.Get(8), TaskItem(QUITMESSAGELOOP, 5, true)); EXPECT_EQ(order.Get(9), TaskItem(QUITMESSAGELOOP, 5, false)); EXPECT_EQ(order.Get(10), TaskItem(RECURSIVE, 1, true)); EXPECT_EQ(order.Get(11), TaskItem(RECURSIVE, 1, false)); */ EXPECT_EQ(order.Get(12), TaskItem(RECURSIVE, 3, true)); EXPECT_EQ(order.Get(13), TaskItem(RECURSIVE, 3, false)); EXPECT_EQ(order.Get(14), TaskItem(RECURSIVE, 1, true)); EXPECT_EQ(order.Get(15), TaskItem(RECURSIVE, 1, false)); EXPECT_EQ(order.Get(16), TaskItem(RECURSIVE, 3, true)); EXPECT_EQ(order.Get(17), TaskItem(RECURSIVE, 3, false)); } #endif // defined(OS_WIN) void PostNTasksThenQuit(int posts_remaining) { if (posts_remaining > 1) { MessageLoop::current()->PostTask( FROM_HERE, Bind(&PostNTasksThenQuit, posts_remaining - 1)); } else { MessageLoop::current()->QuitWhenIdle(); } } #if defined(OS_WIN) class DispatcherImpl : public MessageLoopForUI::Dispatcher { public: DispatcherImpl() : dispatch_count_(0) {} virtual bool Dispatch(const NativeEvent& msg) OVERRIDE { ::TranslateMessage(&msg); ::DispatchMessage(&msg); // Do not count WM_TIMER since it is not what we post and it will cause // flakiness. if (msg.message != WM_TIMER) ++dispatch_count_; // We treat WM_LBUTTONUP as the last message. return msg.message != WM_LBUTTONUP; } int dispatch_count_; }; void MouseDownUp() { PostMessage(NULL, WM_LBUTTONDOWN, 0, 0); PostMessage(NULL, WM_LBUTTONUP, 'A', 0); } void RunTest_Dispatcher(MessageLoop::Type message_loop_type) { MessageLoop loop(message_loop_type); MessageLoop::current()->PostDelayedTask( FROM_HERE, Bind(&MouseDownUp), TimeDelta::FromMilliseconds(100)); DispatcherImpl dispatcher; RunLoop run_loop(&dispatcher); run_loop.Run(); ASSERT_EQ(2, dispatcher.dispatch_count_); } LRESULT CALLBACK MsgFilterProc(int code, WPARAM wparam, LPARAM lparam) { if (code == MessagePumpForUI::kMessageFilterCode) { MSG* msg = reinterpret_cast<MSG*>(lparam); if (msg->message == WM_LBUTTONDOWN) return TRUE; } return FALSE; } void RunTest_DispatcherWithMessageHook(MessageLoop::Type message_loop_type) { MessageLoop loop(message_loop_type); MessageLoop::current()->PostDelayedTask( FROM_HERE, Bind(&MouseDownUp), TimeDelta::FromMilliseconds(100)); HHOOK msg_hook = SetWindowsHookEx(WH_MSGFILTER, MsgFilterProc, NULL, GetCurrentThreadId()); DispatcherImpl dispatcher; RunLoop run_loop(&dispatcher); run_loop.Run(); ASSERT_EQ(1, dispatcher.dispatch_count_); UnhookWindowsHookEx(msg_hook); } class TestIOHandler : public MessageLoopForIO::IOHandler { public: TestIOHandler(const wchar_t* name, HANDLE signal, bool wait); virtual void OnIOCompleted(MessageLoopForIO::IOContext* context, DWORD bytes_transfered, DWORD error); void Init(); void WaitForIO(); OVERLAPPED* context() { return &context_.overlapped; } DWORD size() { return sizeof(buffer_); } private: char buffer_[48]; MessageLoopForIO::IOContext context_; HANDLE signal_; win::ScopedHandle file_; bool wait_; }; TestIOHandler::TestIOHandler(const wchar_t* name, HANDLE signal, bool wait) : signal_(signal), wait_(wait) { memset(buffer_, 0, sizeof(buffer_)); memset(&context_, 0, sizeof(context_)); context_.handler = this; file_.Set(CreateFile(name, GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_FLAG_OVERLAPPED, NULL)); EXPECT_TRUE(file_.IsValid()); } void TestIOHandler::Init() { MessageLoopForIO::current()->RegisterIOHandler(file_, this); DWORD read; EXPECT_FALSE(ReadFile(file_, buffer_, size(), &read, context())); EXPECT_EQ(ERROR_IO_PENDING, GetLastError()); if (wait_) WaitForIO(); } void TestIOHandler::OnIOCompleted(MessageLoopForIO::IOContext* context, DWORD bytes_transfered, DWORD error) { ASSERT_TRUE(context == &context_); ASSERT_TRUE(SetEvent(signal_)); } void TestIOHandler::WaitForIO() { EXPECT_TRUE(MessageLoopForIO::current()->WaitForIOCompletion(300, this)); EXPECT_TRUE(MessageLoopForIO::current()->WaitForIOCompletion(400, this)); } void RunTest_IOHandler() { win::ScopedHandle callback_called(CreateEvent(NULL, TRUE, FALSE, NULL)); ASSERT_TRUE(callback_called.IsValid()); const wchar_t* kPipeName = L"\\\\.\\pipe\\iohandler_pipe"; win::ScopedHandle server( CreateNamedPipe(kPipeName, PIPE_ACCESS_OUTBOUND, 0, 1, 0, 0, 0, NULL)); ASSERT_TRUE(server.IsValid()); Thread thread("IOHandler test"); Thread::Options options; options.message_loop_type = MessageLoop::TYPE_IO; ASSERT_TRUE(thread.StartWithOptions(options)); MessageLoop* thread_loop = thread.message_loop(); ASSERT_TRUE(NULL != thread_loop); TestIOHandler handler(kPipeName, callback_called, false); thread_loop->PostTask(FROM_HERE, Bind(&TestIOHandler::Init, Unretained(&handler))); // Make sure the thread runs and sleeps for lack of work. PlatformThread::Sleep(TimeDelta::FromMilliseconds(100)); const char buffer[] = "Hello there!"; DWORD written; EXPECT_TRUE(WriteFile(server, buffer, sizeof(buffer), &written, NULL)); DWORD result = WaitForSingleObject(callback_called, 1000); EXPECT_EQ(WAIT_OBJECT_0, result); thread.Stop(); } void RunTest_WaitForIO() { win::ScopedHandle callback1_called( CreateEvent(NULL, TRUE, FALSE, NULL)); win::ScopedHandle callback2_called( CreateEvent(NULL, TRUE, FALSE, NULL)); ASSERT_TRUE(callback1_called.IsValid()); ASSERT_TRUE(callback2_called.IsValid()); const wchar_t* kPipeName1 = L"\\\\.\\pipe\\iohandler_pipe1"; const wchar_t* kPipeName2 = L"\\\\.\\pipe\\iohandler_pipe2"; win::ScopedHandle server1( CreateNamedPipe(kPipeName1, PIPE_ACCESS_OUTBOUND, 0, 1, 0, 0, 0, NULL)); win::ScopedHandle server2( CreateNamedPipe(kPipeName2, PIPE_ACCESS_OUTBOUND, 0, 1, 0, 0, 0, NULL)); ASSERT_TRUE(server1.IsValid()); ASSERT_TRUE(server2.IsValid()); Thread thread("IOHandler test"); Thread::Options options; options.message_loop_type = MessageLoop::TYPE_IO; ASSERT_TRUE(thread.StartWithOptions(options)); MessageLoop* thread_loop = thread.message_loop(); ASSERT_TRUE(NULL != thread_loop); TestIOHandler handler1(kPipeName1, callback1_called, false); TestIOHandler handler2(kPipeName2, callback2_called, true); thread_loop->PostTask(FROM_HERE, Bind(&TestIOHandler::Init, Unretained(&handler1))); // TODO(ajwong): Do we really need such long Sleeps in ths function? // Make sure the thread runs and sleeps for lack of work. TimeDelta delay = TimeDelta::FromMilliseconds(100); PlatformThread::Sleep(delay); thread_loop->PostTask(FROM_HERE, Bind(&TestIOHandler::Init, Unretained(&handler2))); PlatformThread::Sleep(delay); // At this time handler1 is waiting to be called, and the thread is waiting // on the Init method of handler2, filtering only handler2 callbacks. const char buffer[] = "Hello there!"; DWORD written; EXPECT_TRUE(WriteFile(server1, buffer, sizeof(buffer), &written, NULL)); PlatformThread::Sleep(2 * delay); EXPECT_EQ(WAIT_TIMEOUT, WaitForSingleObject(callback1_called, 0)) << "handler1 has not been called"; EXPECT_TRUE(WriteFile(server2, buffer, sizeof(buffer), &written, NULL)); HANDLE objects[2] = { callback1_called.Get(), callback2_called.Get() }; DWORD result = WaitForMultipleObjects(2, objects, TRUE, 1000); EXPECT_EQ(WAIT_OBJECT_0, result); thread.Stop(); } #endif // defined(OS_WIN) } // namespace //----------------------------------------------------------------------------- // Each test is run against each type of MessageLoop. That way we are sure // that message loops work properly in all configurations. Of course, in some // cases, a unit test may only be for a particular type of loop. RUN_MESSAGE_LOOP_TESTS(Default, &TypeDefaultMessagePumpFactory); RUN_MESSAGE_LOOP_TESTS(UI, &TypeUIMessagePumpFactory); RUN_MESSAGE_LOOP_TESTS(IO, &TypeIOMessagePumpFactory); #if defined(OS_WIN) TEST(MessageLoopTest, PostDelayedTask_SharedTimer_SubPump) { RunTest_PostDelayedTask_SharedTimer_SubPump(); } // This test occasionally hangs http://crbug.com/44567 TEST(MessageLoopTest, DISABLED_RecursiveDenial2) { RunTest_RecursiveDenial2(MessageLoop::TYPE_DEFAULT); RunTest_RecursiveDenial2(MessageLoop::TYPE_UI); RunTest_RecursiveDenial2(MessageLoop::TYPE_IO); } TEST(MessageLoopTest, RecursiveSupport2) { // This test requires a UI loop RunTest_RecursiveSupport2(MessageLoop::TYPE_UI); } #endif // defined(OS_WIN) class DummyTaskObserver : public MessageLoop::TaskObserver { public: explicit DummyTaskObserver(int num_tasks) : num_tasks_started_(0), num_tasks_processed_(0), num_tasks_(num_tasks) {} virtual ~DummyTaskObserver() {} virtual void WillProcessTask(const PendingTask& pending_task) OVERRIDE { num_tasks_started_++; EXPECT_TRUE(pending_task.time_posted != TimeTicks()); EXPECT_LE(num_tasks_started_, num_tasks_); EXPECT_EQ(num_tasks_started_, num_tasks_processed_ + 1); } virtual void DidProcessTask(const PendingTask& pending_task) OVERRIDE { num_tasks_processed_++; EXPECT_TRUE(pending_task.time_posted != TimeTicks()); EXPECT_LE(num_tasks_started_, num_tasks_); EXPECT_EQ(num_tasks_started_, num_tasks_processed_); } int num_tasks_started() const { return num_tasks_started_; } int num_tasks_processed() const { return num_tasks_processed_; } private: int num_tasks_started_; int num_tasks_processed_; const int num_tasks_; DISALLOW_COPY_AND_ASSIGN(DummyTaskObserver); }; TEST(MessageLoopTest, TaskObserver) { const int kNumPosts = 6; DummyTaskObserver observer(kNumPosts); MessageLoop loop; loop.AddTaskObserver(&observer); loop.PostTask(FROM_HERE, Bind(&PostNTasksThenQuit, kNumPosts)); loop.Run(); loop.RemoveTaskObserver(&observer); EXPECT_EQ(kNumPosts, observer.num_tasks_started()); EXPECT_EQ(kNumPosts, observer.num_tasks_processed()); } #if defined(OS_WIN) TEST(MessageLoopTest, Dispatcher) { // This test requires a UI loop RunTest_Dispatcher(MessageLoop::TYPE_UI); } TEST(MessageLoopTest, DispatcherWithMessageHook) { // This test requires a UI loop RunTest_DispatcherWithMessageHook(MessageLoop::TYPE_UI); } TEST(MessageLoopTest, IOHandler) { RunTest_IOHandler(); } TEST(MessageLoopTest, WaitForIO) { RunTest_WaitForIO(); } TEST(MessageLoopTest, HighResolutionTimer) { MessageLoop loop; const TimeDelta kFastTimer = TimeDelta::FromMilliseconds(5); const TimeDelta kSlowTimer = TimeDelta::FromMilliseconds(100); EXPECT_FALSE(loop.IsHighResolutionTimerEnabledForTesting()); // Post a fast task to enable the high resolution timers. loop.PostDelayedTask(FROM_HERE, Bind(&PostNTasksThenQuit, 1), kFastTimer); loop.Run(); EXPECT_TRUE(loop.IsHighResolutionTimerEnabledForTesting()); // Post a slow task and verify high resolution timers // are still enabled. loop.PostDelayedTask(FROM_HERE, Bind(&PostNTasksThenQuit, 1), kSlowTimer); loop.Run(); EXPECT_TRUE(loop.IsHighResolutionTimerEnabledForTesting()); // Wait for a while so that high-resolution mode elapses. PlatformThread::Sleep(TimeDelta::FromMilliseconds( MessageLoop::kHighResolutionTimerModeLeaseTimeMs)); // Post a slow task to disable the high resolution timers. loop.PostDelayedTask(FROM_HERE, Bind(&PostNTasksThenQuit, 1), kSlowTimer); loop.Run(); EXPECT_FALSE(loop.IsHighResolutionTimerEnabledForTesting()); } #endif // defined(OS_WIN) #if defined(OS_POSIX) && !defined(OS_NACL) namespace { class QuitDelegate : public MessageLoopForIO::Watcher { public: virtual void OnFileCanWriteWithoutBlocking(int fd) OVERRIDE { MessageLoop::current()->QuitWhenIdle(); } virtual void OnFileCanReadWithoutBlocking(int fd) OVERRIDE { MessageLoop::current()->QuitWhenIdle(); } }; TEST(MessageLoopTest, FileDescriptorWatcherOutlivesMessageLoop) { // Simulate a MessageLoop that dies before an FileDescriptorWatcher. // This could happen when people use the Singleton pattern or atexit. // Create a file descriptor. Doesn't need to be readable or writable, // as we don't need to actually get any notifications. // pipe() is just the easiest way to do it. int pipefds[2]; int err = pipe(pipefds); ASSERT_EQ(0, err); int fd = pipefds[1]; { // Arrange for controller to live longer than message loop. MessageLoopForIO::FileDescriptorWatcher controller; { MessageLoopForIO message_loop; QuitDelegate delegate; message_loop.WatchFileDescriptor(fd, true, MessageLoopForIO::WATCH_WRITE, &controller, &delegate); // and don't run the message loop, just destroy it. } } if (IGNORE_EINTR(close(pipefds[0])) < 0) PLOG(ERROR) << "close"; if (IGNORE_EINTR(close(pipefds[1])) < 0) PLOG(ERROR) << "close"; } TEST(MessageLoopTest, FileDescriptorWatcherDoubleStop) { // Verify that it's ok to call StopWatchingFileDescriptor(). // (Errors only showed up in valgrind.) int pipefds[2]; int err = pipe(pipefds); ASSERT_EQ(0, err); int fd = pipefds[1]; { // Arrange for message loop to live longer than controller. MessageLoopForIO message_loop; { MessageLoopForIO::FileDescriptorWatcher controller; QuitDelegate delegate; message_loop.WatchFileDescriptor(fd, true, MessageLoopForIO::WATCH_WRITE, &controller, &delegate); controller.StopWatchingFileDescriptor(); } } if (IGNORE_EINTR(close(pipefds[0])) < 0) PLOG(ERROR) << "close"; if (IGNORE_EINTR(close(pipefds[1])) < 0) PLOG(ERROR) << "close"; } } // namespace #endif // defined(OS_POSIX) && !defined(OS_NACL) namespace { // Inject a test point for recording the destructor calls for Closure objects // send to MessageLoop::PostTask(). It is awkward usage since we are trying to // hook the actual destruction, which is not a common operation. class DestructionObserverProbe : public RefCounted<DestructionObserverProbe> { public: DestructionObserverProbe(bool* task_destroyed, bool* destruction_observer_called) : task_destroyed_(task_destroyed), destruction_observer_called_(destruction_observer_called) { } virtual void Run() { // This task should never run. ADD_FAILURE(); } private: friend class RefCounted<DestructionObserverProbe>; virtual ~DestructionObserverProbe() { EXPECT_FALSE(*destruction_observer_called_); *task_destroyed_ = true; } bool* task_destroyed_; bool* destruction_observer_called_; }; class MLDestructionObserver : public MessageLoop::DestructionObserver { public: MLDestructionObserver(bool* task_destroyed, bool* destruction_observer_called) : task_destroyed_(task_destroyed), destruction_observer_called_(destruction_observer_called), task_destroyed_before_message_loop_(false) { } virtual void WillDestroyCurrentMessageLoop() OVERRIDE { task_destroyed_before_message_loop_ = *task_destroyed_; *destruction_observer_called_ = true; } bool task_destroyed_before_message_loop() const { return task_destroyed_before_message_loop_; } private: bool* task_destroyed_; bool* destruction_observer_called_; bool task_destroyed_before_message_loop_; }; } // namespace TEST(MessageLoopTest, DestructionObserverTest) { // Verify that the destruction observer gets called at the very end (after // all the pending tasks have been destroyed). MessageLoop* loop = new MessageLoop; const TimeDelta kDelay = TimeDelta::FromMilliseconds(100); bool task_destroyed = false; bool destruction_observer_called = false; MLDestructionObserver observer(&task_destroyed, &destruction_observer_called); loop->AddDestructionObserver(&observer); loop->PostDelayedTask( FROM_HERE, Bind(&DestructionObserverProbe::Run, new DestructionObserverProbe(&task_destroyed, &destruction_observer_called)), kDelay); delete loop; EXPECT_TRUE(observer.task_destroyed_before_message_loop()); // The task should have been destroyed when we deleted the loop. EXPECT_TRUE(task_destroyed); EXPECT_TRUE(destruction_observer_called); } // Verify that MessageLoop sets ThreadMainTaskRunner::current() and it // posts tasks on that message loop. TEST(MessageLoopTest, ThreadMainTaskRunner) { MessageLoop loop; scoped_refptr<Foo> foo(new Foo()); std::string a("a"); ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE, Bind( &Foo::Test1ConstRef, foo.get(), a)); // Post quit task; MessageLoop::current()->PostTask(FROM_HERE, Bind( &MessageLoop::Quit, Unretained(MessageLoop::current()))); // Now kick things off MessageLoop::current()->Run(); EXPECT_EQ(foo->test_count(), 1); EXPECT_EQ(foo->result(), "a"); } TEST(MessageLoopTest, IsType) { MessageLoop loop(MessageLoop::TYPE_UI); EXPECT_TRUE(loop.IsType(MessageLoop::TYPE_UI)); EXPECT_FALSE(loop.IsType(MessageLoop::TYPE_IO)); EXPECT_FALSE(loop.IsType(MessageLoop::TYPE_DEFAULT)); } #if defined(OS_WIN) void EmptyFunction() {} void PostMultipleTasks() { MessageLoop::current()->PostTask(FROM_HERE, base::Bind(&EmptyFunction)); MessageLoop::current()->PostTask(FROM_HERE, base::Bind(&EmptyFunction)); } static const int kSignalMsg = WM_USER + 2; void PostWindowsMessage(HWND message_hwnd) { PostMessage(message_hwnd, kSignalMsg, 0, 2); } void EndTest(bool* did_run, HWND hwnd) { *did_run = true; PostMessage(hwnd, WM_CLOSE, 0, 0); } int kMyMessageFilterCode = 0x5002; LRESULT CALLBACK TestWndProcThunk(HWND hwnd, UINT message, WPARAM wparam, LPARAM lparam) { if (message == WM_CLOSE) EXPECT_TRUE(DestroyWindow(hwnd)); if (message != kSignalMsg) return DefWindowProc(hwnd, message, wparam, lparam); switch (lparam) { case 1: // First, we post a task that will post multiple no-op tasks to make sure // that the pump's incoming task queue does not become empty during the // test. MessageLoop::current()->PostTask(FROM_HERE, base::Bind(&PostMultipleTasks)); // Next, we post a task that posts a windows message to trigger the second // stage of the test. MessageLoop::current()->PostTask(FROM_HERE, base::Bind(&PostWindowsMessage, hwnd)); break; case 2: // Since we're about to enter a modal loop, tell the message loop that we // intend to nest tasks. MessageLoop::current()->SetNestableTasksAllowed(true); bool did_run = false; MessageLoop::current()->PostTask(FROM_HERE, base::Bind(&EndTest, &did_run, hwnd)); // Run a nested windows-style message loop and verify that our task runs. If // it doesn't, then we'll loop here until the test times out. MSG msg; while (GetMessage(&msg, 0, 0, 0)) { if (!CallMsgFilter(&msg, kMyMessageFilterCode)) DispatchMessage(&msg); // If this message is a WM_CLOSE, explicitly exit the modal loop. Posting // a WM_QUIT should handle this, but unfortunately MessagePumpWin eats // WM_QUIT messages even when running inside a modal loop. if (msg.message == WM_CLOSE) break; } EXPECT_TRUE(did_run); MessageLoop::current()->Quit(); break; } return 0; } TEST(MessageLoopTest, AlwaysHaveUserMessageWhenNesting) { MessageLoop loop(MessageLoop::TYPE_UI); HINSTANCE instance = GetModuleFromAddress(&TestWndProcThunk); WNDCLASSEX wc = {0}; wc.cbSize = sizeof(wc); wc.lpfnWndProc = TestWndProcThunk; wc.hInstance = instance; wc.lpszClassName = L"MessageLoopTest_HWND"; ATOM atom = RegisterClassEx(&wc); ASSERT_TRUE(atom); HWND message_hwnd = CreateWindow(MAKEINTATOM(atom), 0, 0, 0, 0, 0, 0, HWND_MESSAGE, 0, instance, 0); ASSERT_TRUE(message_hwnd) << GetLastError(); ASSERT_TRUE(PostMessage(message_hwnd, kSignalMsg, 0, 1)); loop.Run(); ASSERT_TRUE(UnregisterClass(MAKEINTATOM(atom), instance)); } #endif // defined(OS_WIN) } // namespace base
49c667dd5e97e4ba0316cb94228bf7a33312961a
3d9ee1df20202d2d0ab4b05eeb8df602b3828ecc
/week-03/day-4/05sharpie-set/sharpieset.h
48cb89b775f40f7529744c91c0e0d7d74cd420d5
[]
no_license
green-fox-academy/JKatalin
fbd8e219bd45f87508aea1424b1a6d80bc87c217
57cfc20fe045105d35ad7075ee930ef764f654c2
refs/heads/master
2020-05-04T11:08:08.012751
2019-06-04T14:06:53
2019-06-04T14:06:53
179,101,479
0
0
null
null
null
null
UTF-8
C++
false
false
393
h
// // Created by Kata on 2019. 04. 22.. // #ifndef INC_05SHARPIE_SET_SHARPIESET_H #define INC_05SHARPIE_SET_SHARPIESET_H #include "Sharpie.h" #include <vector> class Sharpieset { public: void countUsable(); void removeTrash(); void addSharpie(Sharpie *sharpie); void printSet(); private: std::vector<Sharpie *> _sharpies; }; #endif //INC_05SHARPIE_SET_SHARPIESET_H
b308da1977eccc87df1c06787e1ace3e5e1cd0e5
684dfb78349d404594b41958c6ff05b8b6cf1c2f
/E101/E101/libtest/test.cpp
2e362121c66559777a3cd5664928bdfbf6a9fa4c
[]
no_license
malataarno/E101AVC
72546ac27638c88b9379b022990a9414c55f0515
adf51980ed9ae1bfd852fede1efd28a20e6cf04f
refs/heads/master
2020-06-05T03:26:10.791652
2019-06-05T02:15:55
2019-06-05T02:15:55
192,297,510
0
0
null
null
null
null
UTF-8
C++
false
false
781
cpp
#include "E101.h" #include <iostream> #include <stdio.h> int main() { int err; printf(" Hello\ n"); err = init(); int img_height = 240; int img_width = 320; int totalred = 0; int bright = 0; int count = 0; int framerate = 10; int ain= 0; select_IO(0, 0); open_screen_stream(); while(count< 80) { take_picture(); update_screen(); totalred = 0; bright = 0; for (int i = 0; i < img_height; i++){ for (int j = 0; j < img_width; j++){ totalred += (int)get_pixel(i, j, 0); bright += (int)get_pixel(i, j, 3); } } count++; printf("Frame: %i\n", count); printf("Red: %i \t Bright: %i\n", totalred, bright); sleep1(0,framerate*10000); } close_screen_stream(); printf("Finshed!\n"); return 0; }
ba7cac21ec092ce7a2323f646994d629a8a1a4e5
f41b68cc39a634c32766972ff2abbe036fe068ee
/Player.h
f2bb1e74061922cf2b66e1806bf58f15dc399651
[]
no_license
fobnn/Banzai
83060f81e4ea132e9ebc0b8b0ad6b18354f77ef6
5afca748327f15bf977e054ac9c65fb84dce985c
refs/heads/master
2021-01-18T20:57:18.654860
2012-01-21T17:48:33
2012-01-21T17:48:33
null
0
0
null
null
null
null
UTF-8
C++
false
false
904
h
#pragma once #include "Enums.h" #include <string> using namespace std; class Board; class Piece; //! Base class representing the user playing the game. class Player { public: Player(Color color); virtual ~Player(); virtual void update(float dt); virtual void draw(); virtual void handleCastling(Piece* king); virtual void handleCapture(Color color, PieceType type); ActionResult performAction(); void resetBoard(); void setBoard(Board* board); void setName(string name); void setOpponent(string name); void setColor(Color color); void setSelected(int x, int y); void setInvalid(int x, int y); Color getColor(); Board* getBoard(); Piece* getSelectedPiece(); bool getCheckMate(); string getName(); string getOpponent(); void pieceMovedSound(); void pieceCapturedSound(); private: Piece* mSelectedPiece; Board* mBoard; Color mColor; string mName; string mOpponent; };
15f748f700143a7d721202eb46c21ac943602d38
af8f0279f0a89b91bbe17fe6f13c4f5c72a45a13
/UVa/uva12195.cpp
2cdae9e002509e9ecbdcfae37d8117ecca77562e
[]
no_license
duguyue100/acm-training
3669a5e80093c9fa4040dfa9ba433330acf9fe8d
c0911c6a12d578c0da7458a68db586926bc594c0
refs/heads/master
2022-09-18T17:40:24.837083
2022-08-20T13:20:08
2022-08-20T13:20:08
11,473,607
62
43
null
2020-09-30T19:28:19
2013-07-17T10:41:42
C++
UTF-8
C++
false
false
759
cpp
// UVa 12195 Jingle Composing #include <bits/stdc++.h> using namespace std; int main() { // freopen("input.in", "r", stdin); // freopen("output.out", "w", stdout); string line; map<char, double> t; t['W'] = 1.0; t['H'] = 1.0/2.0; t['Q'] = 1.0/4.0; t['E'] = 1.0/8.0; t['S'] = 1.0/16.0; t['T'] = 1.0/32.0; t['X'] = 1.0/64.0; while (getline(cin, line) && line != "*") { int count = 0; for (size_t i=1; i<line.size(); i++) { double sum = 0; while (line[i] != '/') { sum += t[line[i]]; i++; } if (sum == 1) count ++; } cout << count << endl; } return 0; }
aa476d94baa3ba9017bb8770ff6e22fef92ffa43
ce697fb6d5dda486bfc1b67b45e404e3153fa3dc
/Moc Files/moc_Ortho_TerraSAR.cpp
22d77771aa5d443494f1ed36c78588d5ab1b0608
[]
no_license
GSoC-2012-Nascetti/SAR_PlugIn
fe36f151700ca746f09684166135832dc2fdaf22
44cc911b77ad6f008ae8bc925f111e6a4ee8995b
refs/heads/master
2020-05-02T05:37:28.454298
2015-06-03T09:13:35
2015-06-03T09:13:35
5,331,132
5
3
null
null
null
null
UTF-8
C++
false
false
2,548
cpp
/**************************************************************************** ** Meta object code from reading C++ file 'Ortho_TerraSAR.h' ** ** Created: Thu 9. Aug 12:13:29 2012 ** by: The Qt Meta Object Compiler version 62 (Qt 4.7.1) ** ** WARNING! All changes made in this file will be lost! *****************************************************************************/ #include "../../../application/PlugIns/src/SAR_PlugIn/Code/Ortho_TerraSAR.h" #if !defined(Q_MOC_OUTPUT_REVISION) #error "The header file 'Ortho_TerraSAR.h' doesn't include <QObject>." #elif Q_MOC_OUTPUT_REVISION != 62 #error "This file was generated using the moc from 4.7.1. It" #error "cannot be used with the include files from this version of Qt." #error "(The moc has changed too much.)" #endif QT_BEGIN_MOC_NAMESPACE static const uint qt_meta_data_Ortho_TerraSAR[] = { // content: 5, // revision 0, // classname 0, 0, // classinfo 1, 14, // methods 0, 0, // properties 0, 0, // enums/sets 0, 0, // constructors 0, // flags 0, // signalCount // slots: signature, parameters, type, tag, flags 16, 15, 15, 15, 0x0a, 0 // eod }; static const char qt_meta_stringdata_Ortho_TerraSAR[] = { "Ortho_TerraSAR\0\0dialogClosed()\0" }; const QMetaObject Ortho_TerraSAR::staticMetaObject = { { &QObject::staticMetaObject, qt_meta_stringdata_Ortho_TerraSAR, qt_meta_data_Ortho_TerraSAR, 0 } }; #ifdef Q_NO_DATA_RELOCATION const QMetaObject &Ortho_TerraSAR::getStaticMetaObject() { return staticMetaObject; } #endif //Q_NO_DATA_RELOCATION const QMetaObject *Ortho_TerraSAR::metaObject() const { return QObject::d_ptr->metaObject ? QObject::d_ptr->metaObject : &staticMetaObject; } void *Ortho_TerraSAR::qt_metacast(const char *_clname) { if (!_clname) return 0; if (!strcmp(_clname, qt_meta_stringdata_Ortho_TerraSAR)) return static_cast<void*>(const_cast< Ortho_TerraSAR*>(this)); if (!strcmp(_clname, "ViewerShell")) return static_cast< ViewerShell*>(const_cast< Ortho_TerraSAR*>(this)); return QObject::qt_metacast(_clname); } int Ortho_TerraSAR::qt_metacall(QMetaObject::Call _c, int _id, void **_a) { _id = QObject::qt_metacall(_c, _id, _a); if (_id < 0) return _id; if (_c == QMetaObject::InvokeMetaMethod) { switch (_id) { case 0: dialogClosed(); break; default: ; } _id -= 1; } return _id; } QT_END_MOC_NAMESPACE
099daf6485c17b328e3d286d3cea73dd59980ed6
2400eda71414b9a3c60bfb6f5deb7ff221e8b338
/GameAssets/Strategies/Strategy.cpp
3ce6065ae6a9845255c7f9b0390109c57576641d
[]
no_license
aalessi18/FirstGame
ce139f7ede578f3e88a8a1063e5755ba0b9aa839
09b9be12bb0a9ec8cf827cfc52e26ff425b77b69
refs/heads/master
2020-03-17T08:37:51.402727
2018-05-15T22:29:17
2018-05-15T22:29:17
133,445,060
1
0
null
null
null
null
UTF-8
C++
false
false
1,998
cpp
#include "Strategy.hpp" Aggressive::Aggressive() { this->strategyType = "Aggressive"; } Aggressive::~Aggressive() { } string Aggressive::suggestionForStrategy() { return "\n====================================================================\nAs an aggressive player, you want to use up all of your army tokens every turn in order to try to control as much of the map as possible.\nFor race and special power combinations, an example of an offensive combination would be Skeletons with Berzerker. The idea is, to choose a combination that focuses on expansive capabilities.\n====================================================================\n"; } Defensive::Defensive() { this->strategyType = "Defensive"; } Defensive::~Defensive() { } string Defensive::suggestionForStrategy() { return "\n====================================================================\nAs a Defensive player, you want to take control of only 1 or 2 areas per turn, this way the regions you control will have a bigger defense.\nFor race and special power combinations, an example of a defensive combination would be Halflings with Heroic. The idea is, to choose a combination that focuses on high defensive capabilities\n====================================================================\n"; } Moderate::Moderate() { this->strategyType = "Moderate"; } Moderate::~Moderate() { } string Moderate::suggestionForStrategy() { return "\n====================================================================\nAs a moderate player, you do not want to use up all of your army tokens every turn, but mix around between expanding and keeping more than just one token on each region you control.\nFor race and special power combinations, an example of a moderate combination would be Amazons with Diplomat. The idea is, to choose a combination that focuses on both some offensive and defensive capabilities.\n====================================================================\n"; }
ccb5763deee5a362fd84441cd450bf915e67ec35
844969bd953d7300f02172c867725e27b518c08e
/SDK/BP_fod_Islehopper_05_StoneRaw_00_a_ItemDesc_functions.cpp
10e23225d25188b5e8bc70dd66483a42c7f50b7b
[]
no_license
zanzo420/SoT-Python-Offset-Finder
70037c37991a2df53fa671e3c8ce12c45fbf75a5
d881877da08b5c5beaaca140f0ab768223b75d4d
refs/heads/main
2023-07-18T17:25:01.596284
2021-09-09T12:31:51
2021-09-09T12:31:51
380,604,174
0
0
null
2021-06-26T22:07:04
2021-06-26T22:07:03
null
UTF-8
C++
false
false
590
cpp
// Name: SoT, Version: 2.2.1.1 #include "../pch.h" /*!!DEFINE!!*/ /*!!HELPER_DEF!!*/ /*!!HELPER_INC!!*/ #ifdef _MSC_VER #pragma pack(push, 0x01) #endif namespace CG { //--------------------------------------------------------------------------- // Functions //--------------------------------------------------------------------------- void UBP_fod_Islehopper_05_StoneRaw_00_a_ItemDesc_C::AfterRead() { UItemDesc::AfterRead(); } void UBP_fod_Islehopper_05_StoneRaw_00_a_ItemDesc_C::BeforeDelete() { UItemDesc::BeforeDelete(); } } #ifdef _MSC_VER #pragma pack(pop) #endif
d2df6f452446dde720653d54240726429a6ab0b9
4db76ed5a580d478c36c579d83a3c8207b994467
/src/localization/base.cpp
754c1297531c1482219bd2b3f3470e748672a28a
[ "BSD-3-Clause" ]
permissive
sebdi/stereo_slam
3eedc0183eaa20e270c7eac9b00617e9368fa27f
aed354cc9676654e5bba1c166eadf462a9dcc460
refs/heads/indigo
2021-01-18T07:49:29.502576
2015-01-23T13:59:24
2015-01-23T13:59:24
30,897,864
0
1
null
2015-02-17T01:41:31
2015-02-17T01:41:31
null
UTF-8
C++
false
false
18,585
cpp
#include "localization/base.h" #include "opencv2/core/core.hpp" #include <boost/filesystem.hpp> #include <pcl/filters/passthrough.h> using namespace boost; namespace fs=filesystem; /** \brief Class constructor. Reads node parameters and initialize some properties. * @return * \param nh public node handler * \param nhp private node handler */ slam::SlamBase::SlamBase( ros::NodeHandle nh, ros::NodeHandle nhp) : nh_(nh), nh_private_(nhp) { // Read the node parameters readParameters(); // Initialize the stereo slam init(); } /** \brief Generic odometry callback. This function is called when an odometry message is received * @return * \param odom_msg ros odometry message of type nav_msgs::Odometry */ void slam::SlamBase::genericCallback(const nav_msgs::Odometry::ConstPtr& odom_msg) { if (!params_.enable) { // The slam is not enabled, re-publish the input odometry // Get the current odometry tf::Transform current_odom_robot = Tools::odomTotf(*odom_msg); // Publish publish(*odom_msg, current_odom_robot); } else { // Check if syncronized callback is working, i.e. corrected odometry is published regularly ros::WallDuration elapsed_time = ros::WallTime::now() - last_pub_odom_; if (elapsed_time.toSec() < 0.9) { // It seems the msgCallback is publishing corrected odometry regularly ;) return; } ROS_WARN_STREAM("[Localization:] We are not getting synchronized messages regularly. No SLAM corrections will be performed. Elapsed time: " << elapsed_time.toSec()); // Get the current odometry tf::Transform current_odom_robot = Tools::odomTotf(*odom_msg); // Have we a corrected pose? Is the graph initialized? if (graph_.numNodes() > 0) { // The graph is initialized, so publish a corrected odometry // Transform the odometry to the camera frame tf::Transform current_odom_camera = current_odom_robot * odom2camera_; // Correct the current odometry with the graph information tf::Transform last_graph_pose, last_graph_odom; graph_.getLastPoses(current_odom_camera, last_graph_pose, last_graph_odom); tf::Transform corrected_odom = pose_.correctPose(current_odom_camera, last_graph_pose, last_graph_odom); // Publish publish(*odom_msg, corrected_odom * odom2camera_.inverse()); } else { // There is nothing to correct... Publish the robot odometry directly. publish(*odom_msg, current_odom_robot); } } } /** \brief Messages callback. This function is called when synchronized odometry and image * message are received. * @return * \param odom_msg ros odometry message of type nav_msgs::Odometry * \param l_img left stereo image message of type sensor_msgs::Image * \param r_img right stereo image message of type sensor_msgs::Image * \param l_info left stereo info message of type sensor_msgs::CameraInfo * \param r_info right stereo info message of type sensor_msgs::CameraInfo * \param cloud_msg ros pointcloud message of type sensor_msgs::PointCloud2 */ void slam::SlamBase::msgsCallback(const nav_msgs::Odometry::ConstPtr& odom_msg, const sensor_msgs::ImageConstPtr& l_img_msg, const sensor_msgs::ImageConstPtr& r_img_msg, const sensor_msgs::CameraInfoConstPtr& l_info_msg, const sensor_msgs::CameraInfoConstPtr& r_info_msg, const sensor_msgs::PointCloud2ConstPtr& cloud_msg) { // Get the cloud PointCloudRGB::Ptr pcl_cloud(new PointCloudRGB); pcl::fromROSMsg(*cloud_msg, *pcl_cloud); pcl::copyPointCloud(*pcl_cloud, pcl_cloud_); // Run the general slam callback msgsCallback(odom_msg, l_img_msg, r_img_msg, l_info_msg, r_info_msg); } /** \brief Messages callback. This function is called when synchronized odometry and image * message are received. * @return * \param odom_msg ros odometry message of type nav_msgs::Odometry * \param l_img left stereo image message of type sensor_msgs::Image * \param r_img right stereo image message of type sensor_msgs::Image * \param l_info left stereo info message of type sensor_msgs::CameraInfo * \param r_info right stereo info message of type sensor_msgs::CameraInfo */ void slam::SlamBase::msgsCallback(const nav_msgs::Odometry::ConstPtr& odom_msg, const sensor_msgs::ImageConstPtr& l_img_msg, const sensor_msgs::ImageConstPtr& r_img_msg, const sensor_msgs::CameraInfoConstPtr& l_info_msg, const sensor_msgs::CameraInfoConstPtr& r_info_msg) { // Get the current timestamp double timestamp = l_img_msg->header.stamp.toSec(); // Get the current odometry tf::Transform current_odom_robot = Tools::odomTotf(*odom_msg); // Get the images Mat l_img, r_img; Tools::imgMsgToMat(*l_img_msg, *r_img_msg, l_img, r_img); // Initialization if (first_iter_) { // Get the transform between odometry frame and camera frame if (!getOdom2CameraTf(*odom_msg, *l_img_msg, odom2camera_)) { ROS_WARN("[Localization:] Impossible to transform odometry to camera frame."); return; } // Set the camera model (only once) Mat camera_matrix; image_geometry::StereoCameraModel stereo_camera_model; Tools::getCameraModel(*l_info_msg, *r_info_msg, stereo_camera_model, camera_matrix); lc_.setCameraModel(stereo_camera_model, camera_matrix); // Transform the odometry to the camera frame tf::Transform current_odom_camera = current_odom_robot * odom2camera_; // Set the first node to libhaloc int id_tmp = lc_.setNode(l_img, r_img); if (id_tmp >= 0) { // Add the vertex and save the cloud (if any) int cur_id = graph_.addVertex(current_odom_camera, current_odom_camera, timestamp); ROS_INFO_STREAM("[Localization:] Node " << cur_id << " inserted."); processCloud(cur_id); // Publish publish(*odom_msg, current_odom_robot); // Slam initialized! first_iter_ = false; } else { // Slam is not already initialized, publish the current odometry publish(*odom_msg, current_odom_robot); } // Exit return; } // Transform the odometry to the camera frame tf::Transform current_odom_camera = current_odom_robot * odom2camera_; // Correct the current odometry with the graph information tf::Transform last_graph_pose, last_graph_odom; graph_.getLastPoses(current_odom_camera, last_graph_pose, last_graph_odom); tf::Transform corrected_odom = pose_.correctPose(current_odom_camera, last_graph_pose, last_graph_odom); // Check if difference between poses is larger than minimum displacement double pose_diff = Tools::poseDiff(last_graph_odom, current_odom_camera); if (pose_diff <= params_.min_displacement) { // Publish and exit publish(*odom_msg, corrected_odom * odom2camera_.inverse()); return; } // Insert this new node into libhaloc int id_tmp = lc_.setNode(l_img, r_img); // Check if node has been inserted if (id_tmp < 0) { // Publish and exit ROS_DEBUG("[Localization:] Impossible to save the node due to its poor quality."); publish(*odom_msg, corrected_odom * odom2camera_.inverse()); return; } // Decide if the position of this node will be computed by SolvePNP or odometry tf::Transform corrected_pose = corrected_odom; if (params_.refine_neighbors) { tf::Transform vertex_disp; int last_id = graph_.getLastVertexId(); bool valid = lc_.getLoopClosure(lexical_cast<string>(last_id), lexical_cast<string>(last_id+1), vertex_disp); if (valid) { ROS_INFO("[Localization:] Pose refined."); corrected_pose = last_graph_pose * vertex_disp; } } // Add the vertex and save the cloud (if any) int cur_id = graph_.addVertex(current_odom_camera, corrected_pose, timestamp); ROS_INFO_STREAM("[Localization:] Node " << cur_id << " inserted."); processCloud(cur_id); // Detect loop closures between nodes by distance bool any_loop_closure = false; vector<int> neighbors; graph_.findClosestNodes(params_.min_neighbor, 2, neighbors); for (uint i=0; i<neighbors.size(); i++) { tf::Transform edge; string lc_id = lexical_cast<string>(neighbors[i]); bool valid_lc = lc_.getLoopClosure(lexical_cast<string>(cur_id), lc_id, edge, true); if (valid_lc) { ROS_INFO_STREAM("[Localization:] Node with id " << cur_id << " closes loop with " << lc_id); graph_.addEdge(lexical_cast<int>(lc_id), cur_id, edge); any_loop_closure = true; } } // Detect loop closures between nodes using hashes int lc_id_num = -1; tf::Transform edge; bool valid_lc = lc_.getLoopClosure(lc_id_num, edge); if (valid_lc) { ROS_INFO_STREAM("[Localization:] Node with id " << cur_id << " closes loop with " << lc_id_num); graph_.addEdge(lc_id_num, cur_id, edge); any_loop_closure = true; } // Update the graph if any loop closing if (any_loop_closure) graph_.update(); // Publish the slam pose graph_.getLastPoses(current_odom_camera, last_graph_pose, last_graph_odom); publish(*odom_msg, last_graph_pose * odom2camera_.inverse()); // Save graph to file and send (if needed) graph_.saveToFile(odom2camera_.inverse()); return; } /** \brief Filters a pointcloud * @return filtered cloud * \param input cloud */ PointCloudRGB::Ptr slam::SlamBase::filterCloud(PointCloudRGB::Ptr cloud) { // NAN and limit filtering PointCloudRGB::Ptr cloud_filtered_ptr(new PointCloudRGB); pcl::PassThrough<PointRGB> pass; pass.setFilterFieldName("x"); pass.setFilterLimits(params_.x_filter_min, params_.x_filter_max); pass.setFilterFieldName("y"); pass.setFilterLimits(params_.y_filter_min, params_.y_filter_max); pass.setFilterFieldName("z"); pass.setFilterLimits(params_.z_filter_min, params_.z_filter_max); pass.setInputCloud(cloud); pass.filter(*cloud_filtered_ptr); return cloud_filtered_ptr; } /** \brief Save and/or send the accumulated cloud depending on the value of 'save_clouds' and 'listen_reconstruction_srv' * \param Cloud id */ void slam::SlamBase::processCloud(int cloud_id) { // Proceed? if (pcl_cloud_.size() == 0 || !params_.save_clouds ) return; // Cloud filtering PointCloudRGB::Ptr cloud_filtered(new PointCloudRGB); cloud_filtered = filterCloud(pcl_cloud_.makeShared()); // Save cloud string id = lexical_cast<string>(cloud_id); pcl::io::savePCDFileBinary(params_.clouds_dir + id + ".pcd", pcl_cloud_); } /** \brief Get the transform between odometry frame and camera frame * @return true if valid transform, false otherwise * \param Odometry msg * \param Image msg * \param Output transform */ bool slam::SlamBase::getOdom2CameraTf(nav_msgs::Odometry odom_msg, sensor_msgs::Image img_msg, tf::StampedTransform &transform) { // Init the transform transform.setIdentity(); try { // Extract the transform tf_listener_.lookupTransform(odom_msg.child_frame_id, img_msg.header.frame_id, ros::Time(0), transform); } catch (tf::TransformException ex) { ROS_WARN("%s", ex.what()); return false; } return true; } /** \brief Publish odometry and information messages */ void slam::SlamBase::publish(nav_msgs::Odometry odom_msg, tf::Transform odom) { // Publish the odometry message pose_.publish(odom_msg, odom); last_pub_odom_ = ros::WallTime::now(); // Information message if (info_pub_.getNumSubscribers() > 0) { stereo_slam::SlamInfo info_msg; info_msg.num_nodes = graph_.numNodes(); info_msg.num_loop_closures = graph_.numLoopClosures(); info_pub_.publish(info_msg); } } /** \brief Creates the clouds directory (reset if exists) */ void slam::SlamBase::createCloudsDir() { if (fs::is_directory(params_.clouds_dir)) fs::remove_all(params_.clouds_dir); fs::path dir(params_.clouds_dir); if (!fs::create_directory(dir)) ROS_ERROR("[Localization:] ERROR -> Impossible to create the clouds directory."); } /** \brief Reads the stereo slam node parameters */ void slam::SlamBase::readParameters() { Params params; slam::Pose::Params pose_params; slam::Graph::Params graph_params; haloc::LoopClosure::Params lc_params; lc_params.num_proj = 2; lc_params.verbose = true; // Operational directories string work_dir; nh_private_.param("work_dir", work_dir, string("")); if (work_dir[work_dir.length()-1] != '/') work_dir += "/"; lc_params.work_dir = work_dir; params.clouds_dir = work_dir + "clouds/"; // Enable nh_private_.param("enable", params.enable, true); // Topic parameters string odom_topic, left_topic, right_topic, left_info_topic, right_info_topic, cloud_topic; nh_private_.param("pose_frame_id", pose_params.pose_frame_id, string("/map")); nh_private_.param("pose_child_frame_id", pose_params.pose_child_frame_id, string("/robot")); nh_private_.param("odom_topic", odom_topic, string("/odometry")); nh_private_.param("left_topic", left_topic, string("/left/image_rect_color")); nh_private_.param("right_topic", right_topic, string("/right/image_rect_color")); nh_private_.param("left_info_topic", left_info_topic, string("/left/camera_info")); nh_private_.param("right_info_topic", right_info_topic, string("/right/camera_info")); nh_private_.param("cloud_topic", cloud_topic, string("/points2")); // Motion parameters nh_private_.param("refine_neighbors", params.refine_neighbors, false); nh_private_.param("min_displacement", params.min_displacement, 0.3); // 3D reconstruction parameters nh_private_.param("save_clouds", params.save_clouds, false); // Loop closure parameters nh_private_.param("desc_type", lc_params.desc_type, string("SIFT")); nh_private_.param("desc_matching_type", lc_params.desc_matching_type, string("CROSSCHECK")); nh_private_.param("desc_thresh_ratio", lc_params.desc_thresh_ratio, 0.8); nh_private_.param("min_neighbor", lc_params.min_neighbor, 10); nh_private_.param("n_candidates", lc_params.n_candidates, 5); nh_private_.param("min_matches", lc_params.min_matches, 100); nh_private_.param("min_inliers", lc_params.min_inliers, 50); // G2O parameters nh_private_.param("g2o_algorithm", graph_params.g2o_algorithm, 0); nh_private_.param("g2o_opt_max_iter", graph_params.go2_opt_max_iter, 20); // Cloud filtering values nh_private_.param("x_filter_min", params.x_filter_min, -3.0); nh_private_.param("x_filter_max", params.x_filter_max, 3.0); nh_private_.param("y_filter_min", params.y_filter_min, -3.0); nh_private_.param("y_filter_max", params.y_filter_max, 3.0); nh_private_.param("z_filter_min", params.z_filter_min, 0.2); nh_private_.param("z_filter_max", params.z_filter_max, 6.0); // Some other graph parameters graph_params.save_dir = lc_params.work_dir; graph_params.pose_frame_id = pose_params.pose_frame_id; graph_params.pose_child_frame_id = pose_params.pose_child_frame_id; // Set the class parameters params.odom_topic = odom_topic; params.min_neighbor = lc_params.min_neighbor; setParams(params); pose_.setParams(pose_params); graph_.setParams(graph_params); lc_.setParams(lc_params); // Topics subscriptions image_transport::ImageTransport it(nh_); odom_sub_ .subscribe(nh_, odom_topic, 25); left_sub_ .subscribe(it, left_topic, 3); right_sub_ .subscribe(it, right_topic, 3); left_info_sub_ .subscribe(nh_, left_info_topic, 3); right_info_sub_ .subscribe(nh_, right_info_topic, 3); if (params_.save_clouds) cloud_sub_.subscribe(nh_, cloud_topic, 5); } /** \brief Initializes the stereo slam node */ void slam::SlamBase::init() { // Advertise the slam odometry message pose_.advertisePoseMsg(nh_private_); // Generic subscriber generic_sub_ = nh_.subscribe<nav_msgs::Odometry>(params_.odom_topic, 1, &SlamBase::genericCallback, this); // Enable the slam? if (params_.enable) { // Init first_iter_ = true; last_pub_odom_ = ros::WallTime::now(); odom2camera_.setIdentity(); // Init Haloc lc_.init(); // Init Graph graph_.init(); // Advertise the info message info_pub_ = nh_private_.advertise<stereo_slam::SlamInfo>("info", 1); // Cloud callback if (params_.save_clouds) { // Create the directory for clouds createCloudsDir(); // Create the callback with the clouds sync_cloud_.reset(new SyncCloud(PolicyCloud(5), odom_sub_, left_sub_, right_sub_, left_info_sub_, right_info_sub_, cloud_sub_) ); sync_cloud_->registerCallback(bind( &slam::SlamBase::msgsCallback, this, _1, _2, _3, _4, _5, _6)); } else { // Callback without clouds sync_no_cloud_.reset(new SyncNoCloud(PolicyNoCloud(3), odom_sub_, left_sub_, right_sub_, left_info_sub_, right_info_sub_) ); sync_no_cloud_->registerCallback(bind( &slam::SlamBase::msgsCallback, this, _1, _2, _3, _4, _5)); } } } /** \brief Finalize stereo slam node * @return */ void slam::SlamBase::finalize() { ROS_INFO("[Localization:] Finalizing..."); lc_.finalize(); ROS_INFO("[Localization:] Done!"); }
d5d076077b2752e7edb19526c7ede41edadd2356
6361fca2cf08ff593e14ea4cab03fcdeee44f374
/Source/WebKit/WebProcess/WebPage/wc/WCBackingStore.h
34f5002f54a43430134508501d727ed7689ccb95
[]
no_license
PseudoDistant/WebKit
dddcf6a39d9347c9e5e0c7a8d2eee8e528d5d60b
e3276e3e62538b30bbb361748773a526e33b4852
refs/heads/main
2023-09-05T19:31:01.767115
2021-11-22T18:14:59
2021-11-22T18:14:59
430,843,049
1
0
null
2021-11-22T19:43:03
2021-11-22T19:43:03
null
UTF-8
C++
false
false
2,805
h
/* * Copyright (C) 2021 Sony Interactive Entertainment Inc. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. */ #pragma once #include "ImageBufferBackendHandle.h" #include "PlatformRemoteImageBufferProxy.h" namespace WebKit { class WCBackingStore { WTF_MAKE_FAST_ALLOCATED; public: WCBackingStore() { } WebCore::ImageBuffer* imageBuffer() { return m_imageBuffer.get(); } void setImageBuffer(RefPtr<WebCore::ImageBuffer>&& image) { m_imageBuffer = WTFMove(image); } ShareableBitmap* bitmap() const { return m_bitmap.get(); } template<class Encoder> void encode(Encoder& encoder) const { bool hasImageBuffer = m_imageBuffer; encoder << hasImageBuffer; if (hasImageBuffer) { auto handle = static_cast<UnacceleratedImageBufferShareableBackend&>(*m_imageBuffer->ensureBackendCreated()).createImageBufferBackendHandle(); encoder << handle; } } template <class Decoder> static WARN_UNUSED_RETURN bool decode(Decoder& decoder, WCBackingStore& result) { bool hasImageBuffer; if (!decoder.decode(hasImageBuffer)) return false; if (hasImageBuffer) { ImageBufferBackendHandle handle; if (!decoder.decode(handle)) return false; result.m_bitmap = ShareableBitmap::create(std::get<ShareableBitmap::Handle>(handle)); } return true; } private: RefPtr<WebCore::ImageBuffer> m_imageBuffer; RefPtr<ShareableBitmap> m_bitmap; }; } // namespace WebKit
8de6ba69d131e348ef47008228765a3b6abef04a
65b193295d2a1b94ef58f9c19a8899290516b9e5
/pyext/kvdict/lib/ullib/include/comlog/appender/appender.h
eba542bca51e674110c01f62305471f50abdcbb6
[]
no_license
nickgu/misc
15381eeb9c0bbf4cfce1907658fd38cfb3b49ad2
0db5fd99e5aff76f1cb505cc0f4f564add714bf1
refs/heads/master
2022-05-02T01:56:12.083984
2022-03-15T11:31:16
2022-03-15T11:31:16
30,815,927
3
2
null
null
null
null
GB18030
C++
false
false
4,111
h
/*************************************************************************** * * Copyright (c) 2008 Baidu.com, Inc. All Rights Reserved * $Id: appender.h,v 1.2.22.3 2010/04/05 13:30:46 zhang_rui Exp $ * **************************************************************************/ /** * @file appender.h * @author xiaowei([email protected]) * @date 2008/02/12 23:54:09 * @version $Revision: 1.2.22.3 $ * @brief * **/ #ifndef __APPENDER__APPENDER_H_ #define __APPENDER__APPENDER_H_ #include "comlog/comlog.h" namespace comspace { class Appender { public: com_device_t _device; //设备名 /**< */ int _id; //设备句柄 /**< */ int _open; /**< */ Layout *_layout; //layout /**< */ //u_int64 _mask; //日志等级掩码 /**< */ unsigned long long _mask; //日志等级掩码 /**< */ pthread_mutex_t _lock; /**< */ Appender * _bkappender; /**< */ public: /** * @brief destructor * **/ virtual ~Appender(); /** * @brief set layout * * @param [in/out] layout : Layout* * @return int * @retval **/ int setLayout(Layout *layout); //设置图层 /** * @brief set device info * * @param [in/out] dev : com_device_t& * @return int * @retval **/ int setDeviceInfo(com_device_t &dev); /** * @brief reset mask * * @return int * @retval **/ int resetMask(); //重置日志等级掩码,默认配置是支持系统日志等级的打印 /** * @brief * * @return int * @retval **/ int emptyMask(); //清空日志等级的掩码,这样就不支持打印任何日志等级 /** * @brief * * @param [in/out] id : int * @return int * @retval **/ int addMask(int id); //添加支持一个日志等级 /** * @brief * * @param [in/out] id : int * @return int * @retval **/ int delMask(int id); //减少支持一个日志等级 /** * @brief * * @param [in/out] id : int * @return bool * @retval **/ bool unInMask(int id); //是否在yanma中 /** * @brief * * @return int * @retval **/ virtual int open(void *) = 0; //打开设备句柄 /** * @brief * * @return int * @retval **/ virtual int close(void *) = 0; //关闭设备句柄 //stop(): 停止接收日志。FileAppender可以无视此消息。 //但AsyncFileAppender/NetAppender等异步打印的日志,此时应退出自己的线程 //主要作用是清零线程计数器(comlog.cpp中的g_close_atomc) virtual int stop(){return 0;} /** * @brief print * * @param [in/out] evt : Event* * @return int * @retval **/ virtual int print(Event *evt) = 0; //将日志实际追加到设备中 /** * @brief binprint **/ virtual int binprint(void *, int siz) = 0; //输入二进制数据 /** * @brief * * @return int * @retval **/ virtual int flush(); //立刻将数据写入硬盘 protected: /** * @brief creator **/ Appender(); public: /** * @brief * * @return int * @retval **/ virtual int syncid(void *); //检测当前id和设备是否一致,如果不一致根据设备名更新id,返回0表示成功,其他失败。 protected: //根据传入的参数,获取一个设备 // static pthread_mutex_t getlock; public: /** * @brief get appender * * @param [in/out] dev : com_device_t& * @return Appender* * @retval **/ static Appender * getAppender(com_device_t &dev); /** * @brief * * @param [in/out] dev : com_device_t& * @return Appender* * @retval **/ static Appender * tryAppender(com_device_t &dev); //为close日志的时候提供的资源统一释放 /** * @brief * * @return int * @retval **/ static int destroyAppenders(); friend class AppenderFactory; /**< */ }; }; #endif //__APPENDER_H_ /* vim: set ts=4 sw=4 sts=4 tw=100 */
c31052e55a0423b9419fb7ef7ae417dcc666366e
79668e1cc702be4af06754429de3188f371eb264
/policies/DIF/EFCP/DTCP/RcvrFC/RcvrFCPolicyDefault/RcvrFCPolicyDefault.cc
0cdd772ae99e2f6c2bdbd8e6fed1f3e4b58b4706
[ "MIT" ]
permissive
fatmahrizi/RINA
3a94edb940f144931bca38dfb3cf74d0a1ad479a
08192a51dda673a5e5af0c5caf1d45e2b4de6d6e
refs/heads/master
2020-12-25T23:37:56.787722
2015-06-09T12:13:06
2015-06-09T12:13:06
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,409
cc
// // Copyright © 2014 - 2015 PRISTINE Consortium (http://ict-pristine.eu) // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public License // along with this program. If not, see http://www.gnu.org/licenses/. // /** * @file RcvrFCPolicyDefault.cc * @author Marcel Marek ([email protected]) * @date May 3, 2015 * @brief This is an example policy class implementing default Initial Sequence Number behavior * @detail */ #include <RcvrFCPolicyDefault/RcvrFCPolicyDefault.h> Register_Class(RcvrFCPolicyDefault); RcvrFCPolicyDefault::RcvrFCPolicyDefault() { // TODO Auto-generated constructor stub } RcvrFCPolicyDefault::~RcvrFCPolicyDefault() { // TODO Auto-generated destructor stub } bool RcvrFCPolicyDefault::run(DTPState* dtpState, DTCPState* dtcpState) { Enter_Method("RcvrFCPolicyDefault"); defaultAction(dtpState, dtcpState); return false; }
a2702a70ee8316c07b02ece4428189238151f52f
ae4fb37916933d5ecce3655e8730759a59426849
/Zee/Zee/Source/Gizmo.cpp
2edbd4560ebe53cf53135470817f9598380bbd7a
[]
no_license
15831944/Zee
1c29fc6c5696f0e4dc486ef5b7f24922b9194f35
794890424b060e7fa3e88c87a0e7b4fc8c39c872
refs/heads/master
2023-03-20T21:00:42.104338
2014-03-29T08:48:54
2014-03-29T08:48:54
null
0
0
null
null
null
null
GB18030
C++
false
false
24,600
cpp
#include "Gizmo.h" #include "D3DUtility.h" #include "Engine.h" #include "Camera.h" #include "Primitive.h" #include "MeshNode.h" #include "Input.h" void Gizmo::OnLostDevice() { _Assert(mCone && mCone->GetMesh() && mCone->GetMesh()->GetGeometry()); _Assert(mLine && mLine->GetMesh() && mLine->GetMesh()->GetGeometry()); _Assert(mTorus && mTorus->GetMesh() && mTorus->GetMesh()->GetGeometry()); _Assert(mCube && mCube->GetMesh() && mCube->GetMesh()->GetGeometry()); mCone->GetMesh()->GetGeometry()->OnLostDevice(); mLine->GetMesh()->GetGeometry()->OnLostDevice(); mTorus->GetMesh()->GetGeometry()->OnLostDevice(); mCube->GetMesh()->GetGeometry()->OnLostDevice(); SAFE_RELEASE(mRenderTarget); SAFE_RELEASE(mDepthStencil); } void Gizmo::OnResetDevice() { _Assert(mCone && mCone->GetMesh() && mCone->GetMesh()->GetGeometry()); _Assert(mLine && mLine->GetMesh() && mLine->GetMesh()->GetGeometry()); _Assert(mTorus && mTorus->GetMesh() && mTorus->GetMesh()->GetGeometry()); _Assert(mCube && mCube->GetMesh() && mCube->GetMesh()->GetGeometry()); mCone->GetMesh()->GetGeometry()->OnResetDevice(); mLine->GetMesh()->GetGeometry()->OnResetDevice(); mTorus->GetMesh()->GetGeometry()->OnResetDevice(); mCube->GetMesh()->GetGeometry()->OnResetDevice(); createRenderTargetDepthStencile(); } void Gizmo::Init() { createRenderTargetDepthStencile(); Cylinder* coneGeo = New Cylinder(L"", 0, 0.06f, 0.18f); Cylinder* lineGeo = New Cylinder(L"", 0.01f, 0.01f, 1.0f); Torus* torusGeo = New Torus(L"", 1.0f, 0.01f, 32, 8); Cube* cubeGeo = New Cube(L"", 0.1f); coneGeo->CalculateNormals(); coneGeo->BuildGeometry(XYZ_N); lineGeo->CalculateNormals(); lineGeo->BuildGeometry(XYZ_N); torusGeo->CalculateNormals(); torusGeo->BuildGeometry(XYZ_N); cubeGeo->CalculateNormals(); cubeGeo->BuildGeometry(XYZ_N); mCone = New MeshNode(L"", NULL, coneGeo, NULL); _Assert(mCone); mLine = New MeshNode(L"", NULL, lineGeo, NULL); _Assert(mLine); mTorus = New MeshNode(L"", NULL, torusGeo, NULL); _Assert(mTorus); mCube = New MeshNode(L"", NULL, cubeGeo, NULL); _Assert(mCube); SAFE_DROP(coneGeo); SAFE_DROP(lineGeo); SAFE_DROP(torusGeo); SAFE_DROP(cubeGeo); } void Gizmo::createRenderTargetDepthStencile() { if(mRenderTarget) SAFE_RELEASE(mRenderTarget); if(mDepthStencil) SAFE_RELEASE(mDepthStencil); Driver* driver = gEngine->GetDriver(); IDirect3DDevice9* d3dDevice = driver->GetD3DDevice(); Vector2 vpSize; driver->GetViewPort(0, NULL, &vpSize); d3dDevice->CreateRenderTarget((UINT)vpSize.x, (UINT)vpSize.y, D3DFMT_A8R8G8B8, D3DMULTISAMPLE_NONE, 0, true, &mRenderTarget, NULL); d3dDevice->CreateDepthStencilSurface((UINT)vpSize.x, (UINT)vpSize.y, D3DFMT_D24X8, D3DMULTISAMPLE_NONE, 0, true, &mDepthStencil, NULL); } void Gizmo::getPickColor(D3DCOLOR* pickColor, const int pickPixelSize) { _Assert(NULL != pickColor); *pickColor = 0; RECT pickRect; D3DLOCKED_RECT pickLockedRect; Vector2 vpSize; gEngine->GetDriver()->GetViewPort(0, NULL, &vpSize); POINT cursorPos = gEngine->GetInput()->GetCursorPos(); SetRect(&pickRect, cursorPos.x - pickPixelSize / 2, cursorPos.y - pickPixelSize / 2, cursorPos.x + pickPixelSize / 2, cursorPos.y + pickPixelSize / 2); if(pickRect.left < 0) pickRect.left = 0; if(pickRect.left > vpSize.x) pickRect.left = (LONG)vpSize.x; if(pickRect.right < 0) pickRect.right = 0; if(pickRect.right > vpSize.x) pickRect.right = (LONG)vpSize.x; if(pickRect.top < 0) pickRect.top = 0; if(pickRect.top > vpSize.y) pickRect.top = (LONG)vpSize.y; if(pickRect.bottom < 0) pickRect.bottom = 0; if(pickRect.bottom > vpSize.y) pickRect.bottom = (LONG)vpSize.y; HRESULT hr = mRenderTarget->LockRect(&pickLockedRect, &pickRect, D3DLOCK_READONLY); if(SUCCEEDED(hr)) { bool bFind = false; for(int i = 0; i <= pickRect.bottom - pickRect.top; ++i) { DWORD* ptr = (DWORD*)pickLockedRect.pBits + i * pickLockedRect.Pitch / 4; for(int j = 0; j <= pickRect.right - pickRect.left; ++j) { D3DCOLOR pixelColor = *(D3DCOLOR*)ptr; if(pixelColor != COLOR_NONE) { *pickColor = pixelColor; break; } ptr++; } if(bFind) break; } mRenderTarget->UnlockRect(); } } void Gizmo::determinSelectType(Object* obj, Camera* camera) { _Assert(NULL != obj); _Assert(NULL != camera); if(gEngine->GetInput()->GetLeftButton()) // 左键按下不更新, 保持之前选择状态 return; draw(obj, camera, true); // flatMtl绘制, 用于colorPick D3DCOLOR pickColor = 0; getPickColor(&pickColor, 8); switch(pickColor) { case COLOR_NONE: mSelectedAxis = SELECT_NONE; break; case COLOR_X: mSelectedAxis = AXIS_X; break; case COLOR_Y: mSelectedAxis = AXIS_Y; break; case COLOR_Z: mSelectedAxis = AXIS_Z; break; case COLOR_XYZ: mSelectedAxis = AXIS_XYZ; break; case COLOR_XY_PICK: mSelectedAxis = PLANE_XY; break; case COLOR_XZ_PICK: mSelectedAxis = PLANE_XZ; break; case COLOR_YZ_PICK: mSelectedAxis = PLANE_YZ; break; default: mSelectedAxis = SELECT_NONE; break; } } void Gizmo::Draw() { Camera* camera = gEngine->GetSceneManager()->GetMainCamera(); _Assert(NULL != camera); if(!mSelectedNode || mActiveType == GIZMO_NONE) return; Input* input = gEngine->GetInput(); determinSelectType(mSelectedNode, camera); draw(mSelectedNode, camera, false); } void Gizmo::applyTransform(Camera* camera) { _Assert(NULL != camera); if(!mSelectedNode || mActiveType == GIZMO_NONE) return; Input* input = gEngine->GetInput(); static Vector3 tangentX; static Vector3 tangentY; static Vector3 tangentZ; if(mActiveType == GIZMO_TRANS) { if(input->GetLeftButtonDown()) calTransTangent(mSelectedNode, camera, &tangentX, &tangentY, &tangentZ); if(input->GetLeftButton()) applyTrans(mSelectedNode, camera, tangentX, tangentY, tangentZ); } if(mActiveType == GIZMO_ROTATE) { if(input->GetLeftButtonDown()) calRotateTangent(mSelectedNode, camera, &tangentX); if(input->GetLeftButton()) applyRotate(mSelectedNode, camera, tangentX); } if(mActiveType == GIZMO_SCALE) { if(input->GetLeftButtonDown()) calTransTangent(mSelectedNode, camera, &tangentX, &tangentY, &tangentZ); if(input->GetLeftButton()) applyScale(mSelectedNode, camera, tangentX, tangentY, tangentZ); } } void Gizmo::Destroy() { SAFE_DELETE(mCone); SAFE_DELETE(mLine); SAFE_DELETE(mTorus); SAFE_DELETE(mCube); SAFE_RELEASE(mRenderTarget); SAFE_RELEASE(mDepthStencil); } void Gizmo::draw(Object* obj, Camera* camera, bool isColorPickPass) { _Assert(NULL != obj); _Assert(NULL != camera); Driver* driver = gEngine->GetDriver(); IDirect3DDevice9* d3dDevice = driver->GetD3DDevice(); IDirect3DSurface9* oldRT = NULL; IDirect3DSurface9* oldDS = NULL; Material* mtl = NULL; if(isColorPickPass) mtl = gEngine->GetMaterialManager()->GetDefaultFlatMtl(); else mtl = gEngine->GetMaterialManager()->GetDefaultViewMtl(); if(isColorPickPass) { d3dDevice->GetRenderTarget(0, &oldRT); d3dDevice->GetDepthStencilSurface(&oldDS); _Assert(NULL != oldRT); _Assert(NULL != oldDS); d3dDevice->SetRenderTarget(0, mRenderTarget); d3dDevice->SetDepthStencilSurface(mDepthStencil); driver->Clear(D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER, 0xff000000, 1.0f); } // 这里清了zbuffer, 以使gizmo始终在屏幕上显示并内部有深度关系, 所以gizmo在渲染流程的最后 driver->Clear(D3DCLEAR_ZBUFFER, 0xff000000, 1.0f); D3DCOLOR elementColor[7]; elementColor[AXIS_X] = COLOR_X; elementColor[AXIS_Y] = COLOR_Y; elementColor[AXIS_Z] = COLOR_Z; elementColor[PLANE_XY] = COLOR_XY_PICK; elementColor[PLANE_XZ] = COLOR_XZ_PICK; elementColor[PLANE_YZ] = COLOR_YZ_PICK; elementColor[AXIS_XYZ] = COLOR_XYZ; if(!isColorPickPass) { elementColor[PLANE_XY] = COLOR_XY; elementColor[PLANE_XZ] = COLOR_XZ; elementColor[PLANE_YZ] = COLOR_YZ; if(mSelectedAxis != SELECT_NONE) { elementColor[mSelectedAxis] = (D3DCOLOR)COLOR_SELECTED; SETALPHA(elementColor[mSelectedAxis], 0x7f); } } switch(mActiveType) { case GIZMO_TRANS: drawTransGizmo(obj, camera, mtl, elementColor); break; case GIZMO_ROTATE: drawRotateGizmo(obj, camera, mtl, elementColor); break; case GIZMO_SCALE: drawScaleGizmo(obj, camera, mtl, elementColor); break; } if(isColorPickPass) { d3dDevice->SetRenderTarget(0, oldRT); d3dDevice->SetDepthStencilSurface(oldDS); } SAFE_RELEASE(oldRT); // GetRenderTarget方法会增加引用计数, 需要release, 否则设备无法恢复 SAFE_RELEASE(oldDS); } void Gizmo::drawTransGizmo(Object* obj, Camera* camera, Material* mtl, D3DCOLOR elementsColor[6]) { const float SQUARE_SIZE = 0.4f; float dist = VectorLength(camera->GetWorldPosition() - obj->GetWorldPosition()); float scaleFactor = dist / SCALE_FACTOR; Vector3 basePos = obj->GetWorldPosition(); Quaternion baseOrient; if(mCoordinateType == COORDINATE_GLOBAL) { baseOrient = Quaternion(0, 0, 0); } else { baseOrient = obj->GetWorldOrient(); } // y Material* tempMtl = New Material(*mtl); tempMtl->SetDiffuseColor(elementsColor[AXIS_Y]); mLine->SetWorldPosition(basePos); mLine->SetWorldOrientation(baseOrient); mLine->SetScale(Vector3(scaleFactor, scaleFactor, scaleFactor)); mLine->GetMesh()->SetMaterial(tempMtl); mCone->SetWorldPosition(basePos); mCone->SetWorldOrientation(baseOrient); mCone->TranslateLocal(0, scaleFactor, 0); mCone->SetScale(Vector3(scaleFactor, scaleFactor, scaleFactor)); mCone->GetMesh()->SetMaterial(tempMtl); tempMtl->Render(mLine->LocalToWorldMatrix(), mLine->GetMesh()->GetGeometry(), camera, true); tempMtl->Render(mCone->LocalToWorldMatrix(), mCone->GetMesh()->GetGeometry(), camera, true); DebugDrawer::DrawSquare(GetWorldPos(basePos, baseOrient, scaleFactor * Vector3(SQUARE_SIZE * 0.5f, 0, SQUARE_SIZE * 0.5f)), baseOrient, 0.8f * scaleFactor * SQUARE_SIZE, elementsColor[PLANE_XZ], true, camera); // x tempMtl->SetDiffuseColor(elementsColor[AXIS_X]); mLine->RotateLocal(0, 0, -PI / 2.0f); mLine->GetMesh()->SetMaterial(tempMtl); mCone->TranslateLocal(scaleFactor, -scaleFactor, 0); mCone->RotateLocal(0, 0, -PI / 2.0f); mCone->GetMesh()->SetMaterial(tempMtl); tempMtl->Render(mLine->LocalToWorldMatrix(), mLine->GetMesh()->GetGeometry(), camera, true); tempMtl->Render(mCone->LocalToWorldMatrix(), mCone->GetMesh()->GetGeometry(), camera, true); DebugDrawer::DrawSquare(GetWorldPos(basePos, baseOrient, scaleFactor * Vector3(0, SQUARE_SIZE * 0.5f, SQUARE_SIZE * 0.5f)), baseOrient * Quaternion(0, 0, PI/2.0f), 0.8f * scaleFactor * SQUARE_SIZE, elementsColor[PLANE_YZ], true, camera); // z tempMtl->SetDiffuseColor(elementsColor[AXIS_Z]); mLine->RotateLocal(PI / 2.0f, 0, 0); mLine->GetMesh()->SetMaterial(tempMtl); mCone->TranslateLocal(0, -scaleFactor, scaleFactor); mCone->RotateLocal(PI / 2.0f, 0, 0); mCone->GetMesh()->SetMaterial(tempMtl); tempMtl->Render(mLine->LocalToWorldMatrix(), mLine->GetMesh()->GetGeometry(), camera, true); tempMtl->Render(mCone->LocalToWorldMatrix(), mCone->GetMesh()->GetGeometry(), camera, true); DebugDrawer::DrawSquare(GetWorldPos(basePos, baseOrient, scaleFactor * Vector3(SQUARE_SIZE * 0.5f, SQUARE_SIZE * 0.5f, 0)), baseOrient * Quaternion(PI/2.0f, 0, 0), 0.8f * scaleFactor * SQUARE_SIZE, elementsColor[PLANE_XY], true, camera); tempMtl->Drop(); } void Gizmo::drawRotateGizmo(Object* obj, Camera* camera, Material* mtl, D3DCOLOR elementsColor[6]) { float dist = VectorLength(camera->GetWorldPosition() - obj->GetWorldPosition()); float scaleFactor = dist / SCALE_FACTOR; Quaternion baseOrient; if(mCoordinateType == COORDINATE_GLOBAL) { baseOrient = Quaternion(0, 0, 0); } else { baseOrient = obj->GetWorldOrient(); } // y Material* tempMtl = New Material(*mtl); tempMtl->SetDiffuseColor(elementsColor[AXIS_Y]); mTorus->SetWorldPosition(obj->GetWorldPosition()); mTorus->SetWorldOrientation(baseOrient); mTorus->SetScale(Vector3(scaleFactor, scaleFactor, scaleFactor)); tempMtl->Render(mTorus->LocalToWorldMatrix(), mTorus->GetMesh()->GetGeometry(), camera, true); // x tempMtl->SetDiffuseColor(elementsColor[AXIS_X]); mTorus->RotateLocal(0, 0, - PI / 2.0f); tempMtl->Render(mTorus->LocalToWorldMatrix(), mTorus->GetMesh()->GetGeometry(), camera, true); // z tempMtl->SetDiffuseColor(elementsColor[AXIS_Z]); mTorus->RotateLocal(- PI / 2.0f, 0, 0); tempMtl->Render(mTorus->LocalToWorldMatrix(), mTorus->GetMesh()->GetGeometry(), camera, true); tempMtl->Drop(); } void Gizmo::drawScaleGizmo(Object* obj, Camera* camera, Material* mtl, D3DCOLOR elementsColor[6]) { float dist = VectorLength(camera->GetWorldPosition() - obj->GetWorldPosition()); float scaleFactor = dist / SCALE_FACTOR; Quaternion baseOrient; if(mCoordinateType == COORDINATE_GLOBAL) { baseOrient = Quaternion(0, 0, 0); } else { baseOrient = obj->GetWorldOrient(); } // y Material* tempMtl = New Material(*mtl); tempMtl->SetDiffuseColor(elementsColor[AXIS_Y]); mLine->SetWorldPosition(obj->GetWorldPosition()); mLine->SetWorldOrientation(baseOrient); mLine->SetScale(Vector3(scaleFactor, scaleFactor, scaleFactor)); mCube->SetWorldPosition(obj->GetWorldPosition()); mCube->SetWorldOrientation(baseOrient); mCube->TranslateLocal(0, scaleFactor, 0); mCube->SetScale(Vector3(scaleFactor, scaleFactor, scaleFactor)); tempMtl->Render(mLine->LocalToWorldMatrix(), mLine->GetMesh()->GetGeometry(), camera, true); tempMtl->Render(mCube->LocalToWorldMatrix(), mCube->GetMesh()->GetGeometry(), camera, true); // x tempMtl->SetDiffuseColor(elementsColor[AXIS_X]); mLine->RotateLocal(0, 0, -PI / 2.0f); mCube->TranslateLocal(scaleFactor, -scaleFactor, 0); tempMtl->Render(mLine->LocalToWorldMatrix(), mLine->GetMesh()->GetGeometry(), camera, true); tempMtl->Render(mCube->LocalToWorldMatrix(), mCube->GetMesh()->GetGeometry(), camera, true); // z tempMtl->SetDiffuseColor(elementsColor[AXIS_Z]); mLine->RotateLocal(PI / 2.0f, 0, 0); mCube->TranslateLocal(-scaleFactor, 0, scaleFactor); tempMtl->Render(mLine->LocalToWorldMatrix(), mLine->GetMesh()->GetGeometry(), camera, true); tempMtl->Render(mCube->LocalToWorldMatrix(), mCube->GetMesh()->GetGeometry(), camera, true); // xyz tempMtl->SetDiffuseColor(elementsColor[AXIS_XYZ]); mCube->TranslateLocal(0, 0, -scaleFactor); tempMtl->Render(mCube->LocalToWorldMatrix(), mCube->GetMesh()->GetGeometry(), camera, true); tempMtl->Drop(); } void Gizmo::calTransTangent(Object* obj, Camera* camera, Vector3* tangentX, Vector3* tangentY, Vector3* tangentZ) { D3DXMATRIX matWVP; if(mCoordinateType == COORDINATE_GLOBAL) matWVP = camera->ViewMatrix() * camera->ProjMatrix(); else matWVP = obj->LocalToWorldMatrix() * camera->ViewMatrix() * camera->ProjMatrix(); Vector3 posClipO; Vector3 posClipX; Vector3 posClipY; Vector3 posClipZ; GetClipSpacePos(Vector3::Zero, matWVP, &posClipO); GetClipSpacePos(Vector3(1.0f, 0, 0), matWVP, &posClipX); GetClipSpacePos(Vector3(0, 1.0f, 0), matWVP, &posClipY); GetClipSpacePos(Vector3(0, 0, 1.0f), matWVP, &posClipZ); Vector3 axisX = (posClipX - posClipO).Normalized(); Vector3 axisY = (posClipY - posClipO).Normalized(); Vector3 axisZ = (posClipZ - posClipO).Normalized(); axisX.z = 0; axisY.z = 0; axisZ.z = 0; *tangentX = axisX; *tangentY = axisY; *tangentZ = axisZ; } void Gizmo::calRotateTangent(Object* obj, Camera* camera, Vector3* tangent) { D3DXMATRIX matWVP; if(mCoordinateType == COORDINATE_GLOBAL) matWVP = camera->ViewMatrix() * camera->ProjMatrix(); else matWVP = obj->LocalToWorldMatrix() * camera->ViewMatrix() * camera->ProjMatrix(); float scaleFactor = mTorus->GetScale().x; Vector3 posA1; Vector3 posB1; if(mSelectedAxis == AXIS_Y) { posA1 = Vector3(-scaleFactor, 0, 0); posB1 = Vector3(0, 0, -scaleFactor); } else if(mSelectedAxis == AXIS_X) { posA1 = Vector3(0, 0, -scaleFactor); posB1 = Vector3(0, -scaleFactor, 0); } else if(mSelectedAxis == AXIS_Z) { posA1 = Vector3(-scaleFactor, 0, 0); posB1 = Vector3(0, -scaleFactor, 0); } else { _Assert(false); } // 下面计算椭圆切线的算法使用的是:椭圆上一点到两个焦点的直线的角平分线的垂线即为该点在椭圆上的切线 Vector3 posScreenO; Vector3 posScreenA1; Vector3 posScreenB1; GetClipSpacePos(Vector3::Zero, matWVP, &posScreenO); GetClipSpacePos(posA1, matWVP, &posScreenA1); GetClipSpacePos(posB1, matWVP, &posScreenB1); posScreenO.y *= -1.0f; // 屏幕原点使用左上方 posScreenO = 0.5f * (posScreenO + Vector3(1.0f, 1.0f, 0)); // 转到0~1范围 posScreenO.z = 0; posScreenA1.y *= -1.0f; posScreenA1 = 0.5f * (posScreenA1 + Vector3(1.0f, 1.0f, 0)); posScreenA1.z = 0; posScreenB1.y *= -1.0f; posScreenB1 = 0.5f * (posScreenB1 + Vector3(1.0f, 1.0f, 0)); posScreenB1.z = 0; float a = VectorLength(posScreenA1 - posScreenO); // 椭圆长轴 float b = VectorLength(posScreenB1 - posScreenO); // 椭圆短轴 if(a < b) { float temp = a; a = b; b = temp; posScreenA1 = posScreenB1; } float c = sqrtf(a*a - b*b); // 椭圆焦距 _Assert(c != 0); Vector3 posScreenC1 = posScreenO + (c/a) * (posScreenA1 - posScreenO); Vector3 posScreenC2 = posScreenO - (c/a) * (posScreenA1 - posScreenO); POINT cursorPos = gEngine->GetInput()->GetCursorPos(); Vector2 cursorLocation; gEngine->GetDriver()->GetScreenLocation(Vector2((float)cursorPos.x, (float)cursorPos.y), &cursorLocation); Vector3 posScreenCursor(cursorLocation.x, cursorLocation.y, 0); *tangent = ((posScreenC1 - posScreenCursor).Normalized() + (posScreenC2 - posScreenCursor).Normalized()).Cross(Vector3(0, 0, 1.0f)).Normalized(); } void Gizmo::SetActiveType(GIZMO_TYPE type) { mActiveType = type; } void Gizmo::applyTrans(Object* obj, Camera* camera, const Vector3& tangentX, const Vector3& tangentY, const Vector3& tangentZ) { float dist = VectorLength(camera->GetWorldPosition() - obj->GetWorldPosition()); float scaleFactor = dist / SCALE_FACTOR; DIMOUSESTATE mouseState = gEngine->GetInput()->GetMouseState(); Vector3 screenMoveVector((float)mouseState.lX / 1000, -(float)mouseState.lY / 1000, 0); screenMoveVector = TRANS_SPEED * scaleFactor * screenMoveVector; float dx = 0; float dy = 0; float dz = 0; if(mSelectedAxis == AXIS_X) { dx = screenMoveVector.Dot(tangentX); } else if(mSelectedAxis == AXIS_Y) { dy = screenMoveVector.Dot(tangentY); } else if(mSelectedAxis == AXIS_Z) { dz = screenMoveVector.Dot(tangentZ); } else { // 求出选中的平面 D3DXPLANE plane; { D3DXMATRIX matWorld; if(mCoordinateType == COORDINATE_GLOBAL) matWorld = IDENTITY_MATRIX; else matWorld = obj->LocalToWorldMatrix(); D3DXVECTOR3 planeNormal; if(mSelectedAxis == PLANE_XY) D3DXVec3TransformNormal(&planeNormal, &(D3DXVECTOR3(0, 0, 1.0f)), &matWorld); else if(mSelectedAxis == PLANE_XZ) D3DXVec3TransformNormal(&planeNormal, &(D3DXVECTOR3(0, 1.0f, 0)), &matWorld); else if(mSelectedAxis == PLANE_YZ) D3DXVec3TransformNormal(&planeNormal, &(D3DXVECTOR3(1.0f, 0, 0)), &matWorld); else _Assert(false); D3DXVec3Normalize(&planeNormal, &planeNormal); Vector3 pos = obj->GetWorldPosition(); float d = -pos.Dot(Vector3(planeNormal.x, planeNormal.y, planeNormal.z)); plane = D3DXPLANE(planeNormal.x, planeNormal.y, planeNormal.z, d); } Input* input = gEngine->GetInput(); Vector3 lastHitPos; { Vector2 lastScreenPos((float)input->GetLastCursorPos().x, (float)input->GetLastCursorPos().y); Vector3 rayPos; Vector3 rayDir; camera->GetScreenRay(lastScreenPos, &rayPos, &rayDir); _Assert(IntersectRayPlane(rayPos, rayDir, plane, &lastHitPos, NULL) == true); } Vector3 hitPos; { Vector2 screenPos((float)input->GetCursorPos().x, (float)input->GetCursorPos().y); Vector3 rayPos; Vector3 rayDir; camera->GetScreenRay(screenPos, &rayPos, &rayDir); _Assert(IntersectRayPlane(rayPos, rayDir, plane, &hitPos, NULL) == true); } obj->Translate(hitPos - lastHitPos); return; } if(mCoordinateType == COORDINATE_GLOBAL) { obj->Translate(dx, dy, dz); } else { obj->TranslateLocal(dx, dy, dz); } } void Gizmo::applyRotate(Object* obj, Camera* camera, const Vector3& tangent) { float dist = VectorLength(camera->GetWorldPosition() - obj->GetWorldPosition()); float scaleFactor = dist / SCALE_FACTOR; DIMOUSESTATE mouseState = gEngine->GetInput()->GetMouseState(); Vector3 screenMoveVector((float)mouseState.lX / 1000, (float)mouseState.lY / 1000, 0); screenMoveVector = ROTATE_SPEED * scaleFactor * screenMoveVector; Vector3 lookDir = obj->GetWorldPosition() - camera->GetWorldPosition(); int signX = sign(lookDir.Dot(obj->GetWorldRight())); int signY = sign(lookDir.Dot(obj->GetWorldUp())); int signZ = sign(lookDir.Dot(obj->GetWorldForward())); float delta = screenMoveVector.Dot(tangent); if(mSelectedAxis == AXIS_X) { if(mCoordinateType == COORDINATE_GLOBAL) { obj->Rotate(signX * delta, 0, 0); } else { obj->RotateLocal(signX * delta, 0, 0); } } if(mSelectedAxis == AXIS_Y) { if(mCoordinateType == COORDINATE_GLOBAL) { obj->Rotate(0, signY * delta, 0); } else { obj->RotateLocal(0, signY * delta, 0); } } if(mSelectedAxis == AXIS_Z) { if(mCoordinateType == COORDINATE_GLOBAL) { obj->Rotate(0, 0, signZ * delta); } else { obj->RotateLocal(0, 0, signZ * delta); } } } void Gizmo::applyScale(Object* obj, Camera* camera, const Vector3& tangentX, const Vector3& tangentY, const Vector3& tangentZ) { float dist = VectorLength(camera->GetWorldPosition() - obj->GetWorldPosition()); float scaleFactor = dist / SCALE_FACTOR; DIMOUSESTATE mouseState = gEngine->GetInput()->GetMouseState(); Vector3 screenMoveVector((float)mouseState.lX / 1000, -(float)mouseState.lY / 1000, 0); screenMoveVector = SCALE_SPEED * scaleFactor * screenMoveVector; if(mSelectedAxis == AXIS_X) obj->Scale(Vector3(1 + screenMoveVector.Dot(tangentX), 1.0f, 1.0f)); if(mSelectedAxis == AXIS_Y) obj->Scale(Vector3(1.0f, 1 + screenMoveVector.Dot(tangentY), 1.0f)); if(mSelectedAxis == AXIS_Z) obj->Scale(Vector3(1.0f, 1.0f, 1 + screenMoveVector.Dot(tangentZ))); if(mSelectedAxis == AXIS_XYZ) { Vector3 tangent = Vector3(1.0f, 1.0f, 0).Normalized(); float scaleValue = 1 + screenMoveVector.Dot(tangent); obj->Scale(Vector3(scaleValue, scaleValue, scaleValue)); } } bool Gizmo::IsSelected() { return mSelectedAxis != SELECT_NONE; } void Gizmo::FrameUpdate() { Input* input = gEngine->GetInput(); SceneManager* sceneMgr = gEngine->GetSceneManager(); Camera* camera = sceneMgr->GetMainCamera(); Vector2 screenPos((float)input->GetCursorPos().x, (float)input->GetCursorPos().y); Vector3 rayPos; Vector3 rayDir; camera->GetScreenRay(screenPos, &rayPos, &rayDir); if(input->GetLeftButtonDown()) { if(!IsSelected()) { SelectSceneNode(sceneMgr->RayIntersect(rayPos, rayDir, NULL, NULL)); } } if(input->GetKeyDown(DIK_1)) // TODO: 按键设置 { SetActiveType(GIZMO_TRANS); } else if(input->GetKeyDown(DIK_2)) { SetActiveType(GIZMO_ROTATE); } else if(input->GetKeyDown(DIK_3)) { SetActiveType(GIZMO_SCALE); } if(input->GetKeyDown(DIK_G)) { toggleCoordType(); } if(input->GetKeyDown(DIK_F)) { if(mSelectedNode) camera->FocusAt(mSelectedNode); } if(mSelectedAxis != SELECT_NONE) applyTransform(camera); } SceneNode* Gizmo::GetSelectedNode() { return mSelectedNode; } void Gizmo::SetCoordinateType(COORDINATE_TYPE type) { mCoordinateType = type; } void Gizmo::SelectSceneNode(SceneNode* sceneNode) { if(mSelectedNode != sceneNode) { mSelectedNode = sceneNode; if(mSelectedNode) OnSelectNode(); } } void Gizmo::RegisterEventHanlder(IGizmoEventHandler* eventHandler) { mEventHandlerList.push_back(eventHandler); } void Gizmo::UnRegisterEventHandler(IGizmoEventHandler* eventHandler) { mEventHandlerList.remove(eventHandler); } void Gizmo::OnCoordTypeChanged() { for(std::list<IGizmoEventHandler*>::iterator iter = mEventHandlerList.begin(); iter !=mEventHandlerList.end(); ++iter) { (*iter)->OnCoordTypeChanged(this); } } void Gizmo::OnSelectNode() { for(std::list<IGizmoEventHandler*>::iterator iter = mEventHandlerList.begin(); iter !=mEventHandlerList.end(); ++iter) { (*iter)->OnSelectNode(this); } } Gizmo::COORDINATE_TYPE Gizmo::GetCoordinateType() { return mCoordinateType; } void Gizmo::toggleCoordType() { if(mCoordinateType == COORDINATE_GLOBAL) mCoordinateType = COORDINATE_LOCAL; else mCoordinateType = COORDINATE_GLOBAL; OnCoordTypeChanged(); }
c9a2b2363cf59458c16ce8053681bf58cab7d48b
f842c3ccd3ec89625569e02a13afbe75b885458c
/main.cpp
bb8d57328ac30e1f955d96b106f0e71b0622a0df
[]
no_license
thylangale/BeatTheElements
11b84dc785a7b11a05da4d9e62ff8ddaa03614b0
7d0f44af2e858f992fb18c26d4841343cc717cbf
refs/heads/main
2023-05-01T07:59:06.060205
2021-05-13T02:37:54
2021-05-13T02:37:54
366,912,835
1
0
null
null
null
null
UTF-8
C++
false
false
5,823
cpp
#define GL_SILENCE_DEPRECATION #ifdef _WINDOWS #include <GL/glew.h> #endif #define GL_GLEXT_PROTOTYPES 1 #include <SDL.h> #include <SDL_mixer.h> #include <SDL_opengl.h> #include "glm/mat4x4.hpp" #include "glm/gtc/matrix_transform.hpp" #include "ShaderProgram.h" #include "Entity.h" #include "Map.h" #include "Util.h" #include "Scene.h" #include "Menu.h" #include "Level1.h" #include "Level2.h" #include "Level3.h" #include "Game Won.h" #include "Game Over.h" #include "Lives.h" SDL_Window* displayWindow; bool gameIsRunning = true; Mix_Music* music; ShaderProgram program; glm::mat4 viewMatrix, modelMatrix, projectionMatrix; Scene* currentScene; Scene* sceneList[7]; void SwitchToScene(Scene* scene) { currentScene = scene; currentScene->Initialize(); } void Initialize() { SDL_Init(SDL_INIT_VIDEO || SDL_INIT_AUDIO); displayWindow = SDL_CreateWindow("Thy-Lan Gale - Project 5", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 640, 480, SDL_WINDOW_OPENGL); SDL_GLContext context = SDL_GL_CreateContext(displayWindow); SDL_GL_MakeCurrent(displayWindow, context); #ifdef _WINDOWS glewInit(); #endif glViewport(0, 0, 640, 480); program.Load("shaders/vertex_textured.glsl", "shaders/fragment_textured.glsl"); Mix_OpenAudio(44100, MIX_DEFAULT_FORMAT, 2, 4096); music = Mix_LoadMUS("Newer Wave.mp3"); Mix_PlayMusic(music, -1); Mix_VolumeMusic(MIX_MAX_VOLUME / 4); viewMatrix = glm::mat4(1.0f); modelMatrix = glm::mat4(1.0f); projectionMatrix = glm::ortho(-5.0f, 5.0f, -3.75f, 3.75f, -1.0f, 1.0f); program.SetProjectionMatrix(projectionMatrix); program.SetViewMatrix(viewMatrix); glUseProgram(program.programID); glClearColor(1, 1, 1, 0); //background color glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); // Initialize Scenes sceneList[0] = new Level1(); sceneList[1] = new Level2(); sceneList[2] = new Level3(); sceneList[3] = new Menu(); sceneList[4] = new GameWon(); sceneList[5] = new GameOver(); sceneList[6] = new Lives(); SwitchToScene(sceneList[3]); //to debug but remember to switch back to 3 } void ProcessInput() { currentScene->state.player->movement = glm::vec3(0); SDL_Event event; while (SDL_PollEvent(&event)) { switch (event.type) { case SDL_QUIT: case SDL_WINDOWEVENT_CLOSE: gameIsRunning = false; break; case SDL_KEYDOWN: switch (event.key.keysym.sym) { case SDLK_LEFT: // Move the player left break; case SDLK_RIGHT: // Move the player right break; case SDLK_SPACE: // Some sort of action if (currentScene->state.player->collidedBottom) { currentScene->state.player->jump = true; } break; case SDLK_RETURN: if (currentScene == sceneList[3]) { currentScene->state.nextScene = 0; } else if (currentScene == sceneList[4] || currentScene == sceneList[5]) { gameIsRunning = false; } else if (currentScene == sceneList[6]) { if (LIVES == 0) { //Game Over currentScene->state.nextScene = 5; } else currentScene->state.nextScene = prevScene; //restart the current level } } break; // SDL_KEYDOWN } } const Uint8* keys = SDL_GetKeyboardState(NULL); if (keys[SDL_SCANCODE_LEFT]) { currentScene->state.player->movement.x = -1.0f; currentScene->state.player->animIndices = currentScene->state.player->animLeft; } else if (keys[SDL_SCANCODE_RIGHT]) { currentScene->state.player->movement.x = 1.0f; currentScene->state.player->animIndices = currentScene->state.player->animRight; } if (glm::length(currentScene->state.player->movement) > 1.0f) { currentScene->state.player->movement = glm::normalize(currentScene->state.player->movement); } } #define FIXED_TIMESTEP 0.0166666f float lastTicks = 0; float accumulator = 0.0f; void Update() { float ticks = (float)SDL_GetTicks() / 1000.0f; float deltaTime = ticks - lastTicks; lastTicks = ticks; deltaTime += accumulator; if (deltaTime < FIXED_TIMESTEP) { accumulator = deltaTime; return; } while (deltaTime >= FIXED_TIMESTEP) { // Update. Notice it's FIXED_TIMESTEP. Not deltaTime currentScene->Update(FIXED_TIMESTEP); deltaTime -= FIXED_TIMESTEP; } accumulator = deltaTime; viewMatrix = glm::mat4(1.0f); if (currentScene->state.player->position.y > -3.25) { viewMatrix = glm::translate(viewMatrix, glm::vec3(-5, 3.25, 0)); } else if (currentScene->state.player->position.y > -11.75 && (currentScene != sceneList[3] && currentScene != sceneList[4] && currentScene != sceneList[5])) { viewMatrix = glm::translate(viewMatrix, glm::vec3(-5, -currentScene->state.player->position.y, 0)); } else { viewMatrix = glm::translate(viewMatrix, glm::vec3(-5, 11.75, 0)); } } void Render() { glClear(GL_COLOR_BUFFER_BIT); program.SetViewMatrix(viewMatrix); currentScene->Render(&program); SDL_GL_SwapWindow(displayWindow); } void Shutdown() { SDL_Quit(); } int main(int argc, char* argv[]) { Initialize(); while (gameIsRunning) { ProcessInput(); Update(); if (currentScene->state.nextScene >= 0) SwitchToScene(sceneList[currentScene->state.nextScene]); Render(); } Shutdown(); return 0; }
419710baba92632aa8a058c42bbb4a603b30c71c
7d1bbcfc89bcc60614a2a2338e74d8b0fa48669f
/leetcode/array/18_4sum.cpp
6c02ac644dcb87a94e3ce4c864f88fcd93761cdc
[]
no_license
Nana0606/basic-algorithms
3dcfb6554fe28fb8ea007c76e2e0b1aac9012035
f78317a934d945c1f468c28a7fc65d1560fc880f
refs/heads/master
2020-03-23T20:09:21.548501
2019-05-27T01:47:29
2019-05-27T01:47:29
142,024,882
1
0
null
null
null
null
WINDOWS-1252
C++
false
false
1,119
cpp
# include <iostream> # include <vector> # include <set> # include <algorithm> using namespace std; //±©Á¦ vector<vector<int>> fourSum(vector<int>& nums, int target) { set<vector<int> > res; vector<vector<int> > result; for (int i = 0; i < int(nums.size()) - 3; i++){ for (int j = i + 1; j < int(nums.size()) - 2; j++){ for (int k = j + 1; k < int(nums.size()) - 1; k++){ for (int p = k + 1; p < int(nums.size()); p++){ if (nums[i] + nums[j] + nums[k] + nums[p] == target){ vector<int> temp = { nums[i], nums[j], nums[k], nums[p]}; sort(temp.begin(), temp.end()); res.insert(temp); } } } } } set<vector<int> > ::iterator it; for (it = res.begin(); it != res.end(); it++){ result.push_back(*it); } return result; } int main(){ vector<int> nums= {-5, 5, 4, -3, 0, 0, 4, -2}; int target = -1; vector<vector<int>> result = fourSum(nums, target); for (int i = 0; i < int(result.size()); i++){ for (int j = 0; j < int(result[i].size()); j++){ cout << result[i][j] << " "; } cout << endl; } return 0; }
[ "“[email protected]”" ]
1017ffa6119dc6231770240e446a3cf98aad33e9
eafc5ac599f2e96c3ca61612abb109eba2abe655
/customSolvers/edcSimpleFoam/run/flameD_PaSR/2/O2
3570c5360431d9d501c2e89e8288a816444bc46c
[]
no_license
kohyun/OpenFOAM_MSc_Thesis_Project
b651eb129611d41dbb4d3b08a2dec0d4db7663b3
11f6b69c23082b3b47b04963c5fc87b8ab4dd08d
refs/heads/master
2023-03-17T22:34:57.127580
2019-01-12T07:41:07
2019-01-12T07:41:07
null
0
0
null
null
null
null
UTF-8
C++
false
false
41,160
/*--------------------------------*- C++ -*----------------------------------*\ | ========= | | | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox | | \\ / O peration | Version: 1.6.x | | \\ / A nd | Web: www.OpenFOAM.org | | \\/ M anipulation | | \*---------------------------------------------------------------------------*/ FoamFile { version 2.0; format ascii; class volScalarField; location "2"; object O2; } // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // dimensions [0 0 0 0 0 0 0]; internalField nonuniform List<scalar> 4608 ( 0.196584 0.1966 0.196598 0.187641 0.1966 0.1966 0.1966 0.196145 0.181976 0.142684 0.1966 0.1966 0.1966 0.1966 0.196575 0.195454 0.177369 0.134226 0.0205915 0.1966 0.1966 0.1966 0.1966 0.196598 0.196512 0.194564 0.173441 0.129834 0.0124429 0.0503818 0.00445937 0.1966 0.1966 0.1966 0.1966 0.19659 0.196405 0.193499 0.169751 0.127202 0.00986675 0.00138104 0.0530479 0.0539656 0.0416777 0.1966 0.1966 0.1966 0.1966 0.196574 0.196245 0.192282 0.16608 0.124154 0.00920748 0.000698032 0.0145918 0.0538417 0.0539873 0.0539997 0.0853817 0.1966 0.1966 0.1966 0.1966 0.196546 0.196026 0.190926 0.162331 0.120633 0.00875042 0.000642723 0.00254814 0.0849007 0.0543618 0.0539971 0.0539999 0.054 0.14568 0.1966 0.1966 0.1966 0.1966 0.196501 0.195743 0.189433 0.158435 0.116916 0.00838811 0.000599615 0.00175704 0.0748344 0.134532 0.0540032 0.054 0.054 0.054 0.187126 0.1966 0.1966 0.1966 0.1966 0.196435 0.195391 0.1878 0.154361 0.113045 0.00815386 0.00055063 0.00110556 0.0515629 0.12419 0.167533 0.054 0.054 0.054 0.054 0.216512 0.1966 0.1966 0.1966 0.1966 0.196342 0.194967 0.186016 0.150123 0.109041 0.00799306 0.000532807 0.000356658 0.026879 0.102683 0.155157 0.199062 0.054 0.054 0.054 0.054 0.22776 0.1966 0.1966 0.1966 0.1966 0.196218 0.194465 0.184074 0.145767 0.104971 0.00785255 0.000469524 0.000178935 0.00606498 0.0771599 0.135998 0.18724 0.219309 0.054 0.054 0.054 0.054 0.229791 0.1966 0.1966 0.1966 0.1966 0.196059 0.193883 0.181961 0.141321 0.100908 0.00771657 0.000528087 0.000129975 0.00280829 0.0547517 0.112245 0.172039 0.210732 0.228175 0.054 0.054 0.054 0.054 0.229971 0.1966 0.1966 0.1966 0.1966 0.195859 0.193213 0.179663 0.136791 0.096848 0.00758746 0.000534807 9.22566e-05 0.00190209 0.0376607 0.090162 0.152659 0.199954 0.224924 0.229843 0.054 0.054 0.054 0.054 0.229993 0.1966 0.1966 0.1966 0.1966 0.195614 0.19245 0.177159 0.132177 0.0927444 0.00743811 0.000472587 7.36172e-05 0.00102267 0.024097 0.0707072 0.132894 0.185077 0.21944 0.229442 0.229979 0.054 0.054 0.054 0.054 0.229997 0.1966 0.1966 0.1966 0.1966 0.195318 0.191581 0.174426 0.127453 0.088586 0.00725164 0.00046693 5.55996e-05 0.000629777 0.0117575 0.053766 0.114073 0.168646 0.209748 0.228344 0.229948 0.229994 0.054 0.054 0.054 0.054 0.229999 0.1966 0.1966 0.1966 0.1966 0.194967 0.190593 0.171442 0.12255 0.08429 0.00711498 0.000533416 4.45478e-05 0.00036175 0.00686382 0.0381307 0.0964886 0.152082 0.1971 0.225001 0.229868 0.229989 0.229998 0.054 0.054 0.054 0.054 0.23 0.1966 0.1966 0.1966 0.1966 0.194554 0.189467 0.168178 0.117378 0.0797172 0.00696624 0.000475257 4.63552e-05 0.000178481 0.00365905 0.0244981 0.080283 0.135817 0.183125 0.217813 0.229535 0.229981 0.229996 0.229999 0.054 0.054 0.054 0.054 0.23 0.1966 0.1966 0.1966 0.1966 0.194069 0.18818 0.164604 0.111736 0.0747085 0.00680664 0.000470326 4.23402e-05 0.000131095 0.00164311 0.0124939 0.065118 0.120101 0.168993 0.207512 0.228015 0.229959 0.229994 0.229998 0.23 0.054 0.054 0.054 0.054 0.23 0.1966 0.1966 0.1966 0.1966 0.193502 0.186705 0.160676 0.105294 0.0688082 0.00663865 0.000531906 4.02233e-05 0.000106167 0.00118052 0.00533208 0.0511013 0.105196 0.154953 0.195676 0.22373 0.22987 0.229991 0.229998 0.229999 0.23 0.054 0.054 0.054 0.054 0.23 0.1966 0.1966 0.1966 0.1966 0.192841 0.185007 0.156359 0.0973181 0.0614204 0.00624286 0.000536794 4.34436e-05 6.90164e-05 0.000917893 0.00383086 0.0385997 0.0912074 0.141324 0.1836 0.215806 0.229381 0.229984 0.229997 0.229999 0.23 0.23 0.054 0.054 0.054 0.054 0.23 0.1966 0.1966 0.1966 0.192067 0.183052 0.151507 0.0882046 0.0515349 0.00575781 0.000518854 4.43524e-05 4.30164e-05 0.000546026 0.00290104 0.0278127 0.078202 0.128027 0.171714 0.206244 0.227172 0.22996 0.229995 0.229998 0.23 0.23 0.23 0.054 0.054 0.054 0.054 0.23 0.1966 0.1966 0.191162 0.180784 0.146225 0.0323175 0.0432734 0.00502589 0.00049275 4.39103e-05 3.12968e-05 0.000312956 0.00163701 0.0200172 0.0659775 0.115429 0.159931 0.19617 0.222149 0.229818 0.229992 0.229998 0.229999 0.23 0.23 0.23 0.054 0.054 0.054 0.054 0.23 0.1966 0.190095 0.178168 0.135788 0.0158485 0.0150472 0.00456495 0.000405847 4.27786e-05 2.63671e-05 0.000216331 0.000916742 0.0105994 0.0559129 0.103306 0.148506 0.186132 0.214952 0.229017 0.229984 0.229997 0.229999 0.23 0.23 0.23 0.23 0.054 0.054 0.054 0.054 0.23 0.188835 0.174964 0.125311 0.0120356 0.00656569 0.00195089 0.000429694 3.651e-05 2.06388e-05 0.000171131 0.00062945 0.00506766 0.0455164 0.0925137 0.137171 0.176218 0.206855 0.22651 0.22995 0.229996 0.229999 0.23 0.23 0.23 0.23 0.23 0.054 0.054 0.054 0.054 0.23 0.187347 0.171295 0.114697 0.0109394 0.00448424 0.0009499 0.000201873 3.96521e-05 1.35302e-05 0.000122674 0.000486305 0.00384449 0.0358322 0.0822101 0.126477 0.166285 0.198518 0.221758 0.229755 0.229993 0.229998 0.229999 0.23 0.23 0.23 0.23 0.23 0.054 0.054 0.054 0.23 0.185612 0.166972 0.103891 0.0111495 0.00405163 0.000556448 9.31048e-05 2.16231e-05 1.09077e-05 6.9926e-05 0.000339778 0.00289097 0.027361 0.0722772 0.116479 0.156601 0.190169 0.215693 0.228846 0.229984 0.229998 0.229999 0.23 0.23 0.23 0.23 0.23 0.23 0.054 0.054 0.23 0.183574 0.161715 0.0931749 0.00531 0.00431678 0.000415601 5.08649e-05 1.02966e-05 8.0096e-06 4.85259e-05 0.000186275 0.00193702 0.0197701 0.0628582 0.10689 0.14735 0.181828 0.209006 0.226545 0.229945 0.229997 0.229999 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.054 0.23 0.181125 0.155535 0.0357102 0.00223267 0.00229103 0.000457314 3.65064e-05 5.55318e-06 5.90899e-06 3.8661e-05 0.000127271 0.00099947 0.0127343 0.0541042 0.097633 0.138355 0.173662 0.202071 0.222552 0.229756 0.229994 0.229999 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.178153 0.14442 0.0155649 0.00139265 0.000983203 0.000310071 4.01174e-05 3.86106e-06 4.5318e-06 3.157e-05 0.00010189 0.000671145 0.00619436 0.0456808 0.0887553 0.129549 0.165652 0.195219 0.217556 0.228997 0.229985 0.229998 0.229999 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.174208 0.130962 0.0111181 0.00135212 0.000627955 0.000134661 3.00222e-05 4.04714e-06 3.31102e-06 2.49593e-05 8.2755e-05 0.000535311 0.0041614 0.0376736 0.0801322 0.120944 0.15773 0.188393 0.21212 0.227177 0.229955 0.229997 0.229999 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.168995 0.115184 0.010506 0.000662685 0.000605149 7.86324e-05 1.43313e-05 3.24455e-06 2.52967e-06 1.74412e-05 6.42082e-05 0.000428052 0.00314314 0.0298743 0.0719071 0.112515 0.149886 0.181527 0.206494 0.224068 0.229822 0.229995 0.229999 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.16178 0.0977696 0.00417188 0.000264608 0.000300092 7.32004e-05 7.97155e-06 1.75275e-06 2.03402e-06 1.25384e-05 4.34525e-05 0.000320638 0.00254015 0.0221077 0.0635575 0.104409 0.141986 0.174645 0.20081 0.22012 0.229323 0.229989 0.229999 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.1519 0.029075 0.00153053 9.3125e-05 0.00012397 4.21247e-05 7.00319e-06 1.03621e-06 1.68595e-06 1.007e-05 3.10222e-05 0.000205142 0.00182674 0.0173146 0.05504 0.0962461 0.134249 0.16769 0.195063 0.215745 0.228095 0.22997 0.229998 0.229999 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.131098 0.0108562 0.000485983 2.91219e-05 4.76879e-05 1.9058e-05 4.42376e-06 8.77096e-07 1.56896e-06 8.65365e-06 2.50768e-05 0.000145271 0.00109989 0.0119451 0.0485986 0.0879724 0.126489 0.160755 0.189166 0.211114 0.2259 0.229902 0.229996 0.229999 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.101144 0.00301797 0.000132152 8.18576e-06 1.54879e-05 7.81991e-06 2.15658e-06 6.32438e-07 1.41084e-06 8.23145e-06 2.13166e-05 0.000118846 0.0007758 0.00689666 0.0424742 0.0809923 0.118669 0.15374 0.18319 0.206306 0.222879 0.22965 0.229993 0.229999 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.021612 0.000687696 3.33009e-05 2.03141e-06 4.37281e-06 2.7866e-06 9.37695e-07 3.99702e-07 1.32245e-06 7.29013e-06 2.00471e-05 9.88852e-05 0.000643679 0.00436326 0.0365518 0.0747164 0.111672 0.146549 0.177128 0.201416 0.219379 0.228961 0.229983 0.229998 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.00365349 0.000139251 7.4223e-06 4.50152e-07 1.10376e-06 8.74717e-07 3.666e-07 2.48721e-07 1.28329e-06 6.8182e-06 1.75635e-05 9.10662e-05 0.000522459 0.00372914 0.0312252 0.0686777 0.105385 0.139878 0.170935 0.196405 0.215575 0.227614 0.229955 0.229997 0.229999 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.000536479 2.58355e-05 1.46606e-06 9.08124e-08 2.52999e-07 2.46487e-07 1.3273e-07 1.89927e-07 1.11663e-06 6.61427e-06 1.63084e-05 7.82702e-05 0.000470272 0.00316901 0.0264614 0.0628994 0.0993877 0.133781 0.164937 0.191233 0.211564 0.225495 0.22986 0.229996 0.229999 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 7.42562e-05 4.35345e-06 2.6303e-07 1.70595e-08 5.33996e-08 6.38499e-08 4.9613e-08 1.35198e-07 1.17058e-06 5.64842e-06 1.56756e-05 7.17599e-05 0.000396023 0.00274073 0.0222567 0.0574043 0.0935797 0.127929 0.159258 0.186087 0.207407 0.222799 0.229564 0.229991 0.229999 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 9.95178e-06 6.81056e-07 4.37546e-08 3.17718e-09 1.09153e-08 1.60754e-08 2.36097e-08 1.12703e-07 9.22581e-07 5.9268e-06 1.31884e-05 6.78891e-05 0.000358427 0.00230424 0.0187432 0.0523895 0.0879781 0.122238 0.153781 0.181077 0.203223 0.219756 0.228878 0.229981 0.229998 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 1.30887e-06 1.00634e-07 6.89804e-09 7.80778e-10 2.60325e-09 5.05975e-09 1.52311e-08 1.07815e-07 8.0655e-07 4.52033e-06 1.38044e-05 5.57019e-05 0.000333099 0.00205943 0.0153434 0.0480098 0.0827596 0.116727 0.148432 0.176169 0.19905 0.21651 0.227645 0.229952 0.229997 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 1.69963e-07 1.42352e-08 1.09451e-09 4.0274e-10 1.16954e-09 2.66999e-09 1.51281e-08 9.69838e-08 7.92769e-07 3.85693e-06 1.03432e-05 5.81494e-05 0.000266099 0.00187563 0.0135262 0.0437309 0.0780073 0.111508 0.143182 0.171337 0.194868 0.213159 0.225823 0.229861 0.229996 0.229999 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 2.18414e-08 1.96033e-09 2.40002e-10 4.15456e-10 9.46532e-10 2.36041e-09 1.48106e-08 1.09486e-07 7.06977e-07 3.78135e-06 8.72041e-06 4.22483e-05 0.000277364 0.00145668 0.0109695 0.0404235 0.0734048 0.10662 0.138126 0.166573 0.190689 0.209753 0.223577 0.229612 0.229992 0.229999 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 2.78411e-09 2.83425e-10 1.21e-10 4.13322e-10 1.1038e-09 2.32274e-09 1.56098e-08 1.09294e-07 7.95617e-07 3.31627e-06 8.54743e-06 3.49386e-05 0.000194955 0.00151878 0.00909273 0.0372987 0.0693854 0.10188 0.133293 0.161914 0.186528 0.206331 0.221087 0.229071 0.229983 0.229999 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 3.59552e-10 6.23762e-11 1.28403e-10 5.20069e-10 1.08776e-09 2.79546e-09 1.55162e-08 1.14e-07 7.89223e-07 3.70615e-06 7.43781e-06 3.42492e-05 0.000158218 0.00102984 0.00775442 0.0349603 0.0658314 0.0975197 0.128561 0.157382 0.182401 0.202881 0.218436 0.228136 0.229962 0.229998 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 5.53258e-11 4.07598e-11 1.32165e-10 5.42046e-10 1.37245e-09 2.73706e-09 1.85932e-08 1.10759e-07 8.1185e-07 3.65539e-06 8.28382e-06 2.93892e-05 0.000155256 0.000820773 0.00614958 0.032808 0.0628002 0.09363 0.124095 0.152934 0.17833 0.199399 0.215678 0.226745 0.229905 0.229996 0.229999 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 2.04387e-11 3.99767e-11 1.66021e-10 7.03496e-10 1.40163e-09 3.43808e-09 1.78528e-08 1.31843e-07 7.71003e-07 3.71477e-06 8.15598e-06 3.25179e-05 0.000131183 0.000807208 0.00490136 0.0302682 0.0600199 0.0901402 0.120037 0.148641 0.174302 0.195908 0.212849 0.22498 0.229753 0.229994 0.229999 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 1.73675e-11 4.98076e-11 1.95983e-10 9.05798e-10 1.81495e-09 3.48294e-09 2.22384e-08 1.24504e-07 9.1253e-07 3.45404e-06 8.24276e-06 3.19184e-05 0.000144001 0.00066954 0.00415146 0.0280685 0.0571792 0.0868995 0.116296 0.144609 0.170356 0.192416 0.209998 0.222978 0.229417 0.229989 0.229999 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 2.12019e-11 5.9731e-11 2.6687e-10 1.21382e-09 2.32197e-09 4.48917e-09 2.22189e-08 1.54354e-07 8.48617e-07 4.06445e-06 7.58765e-06 3.19761e-05 0.00014091 0.000728236 0.00388798 0.0262125 0.0545457 0.0837599 0.112766 0.140809 0.166558 0.188949 0.207128 0.220827 0.228812 0.229978 0.229998 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 2.5718e-11 8.14396e-11 3.67387e-10 1.60054e-09 3.08149e-09 5.73071e-09 2.83974e-08 1.5259e-07 1.04828e-06 3.72725e-06 8.90532e-06 2.8915e-05 0.00013996 0.000710207 0.0036826 0.0251736 0.0521455 0.0807823 0.10938 0.137174 0.162909 0.185543 0.204237 0.218573 0.22787 0.229951 0.229997 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 3.50936e-11 1.12961e-10 4.90092e-10 2.20525e-09 4.02518e-09 7.56286e-09 3.61927e-08 1.93766e-07 1.02634e-06 4.58734e-06 8.11752e-06 3.37849e-05 0.000124137 0.000699292 0.00352835 0.0238152 0.0502071 0.0779948 0.106144 0.133656 0.159379 0.182212 0.201337 0.216246 0.226594 0.229883 0.229996 0.229999 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 4.89478e-11 1.52181e-10 6.00819e-10 2.52967e-09 5.56753e-09 9.82157e-09 4.72597e-08 2.47401e-07 1.29421e-06 4.45121e-06 9.97498e-06 3.04595e-05 0.000144346 0.000606522 0.00342743 0.022728 0.0483056 0.0754779 0.103066 0.130262 0.155943 0.178947 0.198449 0.213877 0.225059 0.229722 0.229993 0.229999 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 6.64594e-11 1.88735e-10 8.23983e-10 3.70548e-09 6.25736e-09 1.35694e-08 6.06499e-08 3.20216e-07 1.65708e-06 5.56762e-06 9.6448e-06 3.73514e-05 0.00012856 0.000701752 0.00335403 0.0218665 0.0465924 0.0730926 0.100169 0.127 0.1526 0.175737 0.195579 0.211501 0.223362 0.229405 0.229988 0.229999 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 8.31835e-11 2.58937e-10 1.05743e-09 6.09471e-09 9.21259e-09 1.51404e-08 8.37499e-08 4.06743e-07 2.12532e-06 7.14572e-06 1.20142e-05 3.58768e-05 0.000157384 0.000615769 0.00334215 0.0211861 0.0450434 0.0708759 0.0974129 0.12387 0.149351 0.172582 0.192724 0.209119 0.221556 0.228876 0.229978 0.229998 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 1.14073e-10 3.3597e-10 1.71081e-09 9.25946e-09 1.52491e-08 2.22655e-08 9.21099e-08 5.62951e-07 2.67102e-06 9.07832e-06 1.54514e-05 4.43517e-05 0.000150016 0.000753298 0.0033322 0.0206944 0.0436906 0.0688135 0.0948035 0.120869 0.146193 0.169486 0.189886 0.20672 0.219675 0.228085 0.229955 0.229998 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 1.49295e-10 5.39666e-10 2.78602e-09 1.5718e-08 2.28886e-08 3.70384e-08 1.35197e-07 6.11314e-07 3.70722e-06 1.12868e-05 1.95421e-05 5.72596e-05 0.000183797 0.000710574 0.00344548 0.0202182 0.0425411 0.066919 0.092336 0.11799 0.143095 0.166447 0.187067 0.204295 0.217736 0.227036 0.2299 0.229996 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 2.3817e-10 8.82737e-10 4.5141e-09 2.85219e-08 3.88101e-08 5.52709e-08 2.2762e-07 8.97234e-07 3.97411e-06 1.56977e-05 2.41788e-05 7.183e-05 0.000238259 0.000861519 0.00378235 0.0202761 0.041393 0.0651817 0.0900143 0.11523 0.140074 0.163456 0.184273 0.201854 0.21575 0.225778 0.229779 0.229994 0.229999 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 3.90551e-10 1.43926e-09 9.18017e-09 5.77728e-08 6.97634e-08 9.34914e-08 3.35598e-07 1.53325e-06 5.83033e-06 1.66168e-05 3.3683e-05 8.80715e-05 0.000296071 0.00112124 0.00462324 0.0205723 0.0407035 0.0635741 0.0878381 0.112596 0.13714 0.160515 0.181502 0.199408 0.213739 0.224376 0.229547 0.229991 0.229999 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 6.39612e-10 2.9157e-09 1.76292e-08 1.29001e-07 1.40872e-07 1.67825e-07 5.65372e-07 2.23501e-06 1.01136e-05 2.43368e-05 3.54524e-05 0.000123105 0.000359187 0.0013796 0.00597027 0.0210763 0.0403134 0.0622677 0.0858148 0.110096 0.134312 0.157627 0.178755 0.196959 0.211714 0.222872 0.22916 0.229983 0.229999 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 1.29046e-09 5.64989e-09 4.52732e-08 3.55621e-07 3.10209e-07 3.37276e-07 1.01243e-06 3.75646e-06 1.45572e-05 4.27426e-05 5.19007e-05 0.000128189 0.000504283 0.00165619 0.0072435 0.0218459 0.0402278 0.0612223 0.0840092 0.107741 0.131603 0.154789 0.176036 0.19451 0.209668 0.221295 0.228579 0.229969 0.229998 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 2.51708e-09 1.44854e-08 1.03005e-07 9.19067e-07 8.62973e-07 7.40758e-07 2.01587e-06 6.72164e-06 2.43987e-05 6.06999e-05 9.17609e-05 0.000187511 0.000518526 0.0020015 0.00862273 0.0227293 0.0403355 0.0604229 0.082428 0.105561 0.129018 0.152006 0.173347 0.192062 0.207596 0.21966 0.227787 0.229937 0.229997 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 6.44019e-09 3.33606e-08 2.96777e-07 3.43382e-06 2.19106e-06 2.05687e-06 4.39917e-06 1.32675e-05 4.35898e-05 0.000101344 0.000129438 0.000335338 0.000713917 0.00234116 0.0102229 0.0236521 0.0405779 0.0598554 0.0810701 0.103569 0.126576 0.149305 0.170694 0.189621 0.205498 0.217978 0.226804 0.229868 0.229996 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 1.49768e-08 9.69043e-08 1.28855e-06 1.37225e-05 8.06137e-06 5.17523e-06 1.21803e-05 2.87938e-05 8.5151e-05 0.000180375 0.000215029 0.000451693 0.00120136 0.00322934 0.0119512 0.0248099 0.040852 0.0594788 0.079924 0.10177 0.124293 0.146712 0.16809 0.187194 0.203384 0.216257 0.225673 0.229731 0.229994 0.229999 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 4.37477e-08 4.20252e-07 5.24244e-06 6.95431e-05 3.16558e-05 1.89785e-05 3.01258e-05 7.95908e-05 0.000183372 0.000330405 0.000383452 0.000694578 0.00180159 0.00541912 0.0140697 0.0260846 0.0413828 0.0592181 0.0789721 0.100161 0.122172 0.144254 0.165545 0.184788 0.201262 0.214517 0.224437 0.229493 0.229989 0.229999 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 1.89445e-07 1.75232e-06 2.36326e-05 0.000644529 0.000156387 7.37036e-05 0.000109726 0.000193453 0.000464213 0.000742725 0.000693847 0.00136883 0.00273493 0.00806807 0.016306 0.0279087 0.0422057 0.0591591 0.0781872 0.0987341 0.120214 0.141925 0.163052 0.182412 0.199141 0.212761 0.223123 0.229124 0.229982 0.229999 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 8.08642e-07 8.49915e-06 0.000236531 0.00507755 0.00138446 0.000353711 0.00041596 0.000700218 0.00119871 0.00186138 0.00156142 0.00244613 0.0054349 0.0107157 0.0189335 0.0296091 0.0433153 0.0593497 0.0775934 0.0974836 0.11842 0.13973 0.16064 0.18007 0.197024 0.210989 0.221751 0.228591 0.229967 0.229998 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 4.2498e-06 0.000101526 0.00370081 0.0106747 0.00619921 0.00283958 0.00189161 0.00259003 0.00427787 0.00464707 0.00386798 0.00545165 0.0085719 0.0138031 0.0214688 0.0317707 0.0445029 0.0597949 0.0772198 0.0964186 0.11679 0.137674 0.158323 0.177773 0.194916 0.209197 0.220334 0.227887 0.229937 0.229997 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 6.22961e-05 0.00269628 0.00926319 0.0163647 0.0117897 0.00802582 0.00680167 0.00702767 0.00880155 0.00865509 0.00783283 0.00914724 0.0122242 0.0170731 0.0241942 0.0339143 0.0459735 0.0604069 0.077073 0.0955533 0.115333 0.135764 0.156124 0.175531 0.192826 0.207389 0.218878 0.227031 0.229874 0.229996 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.00218986 0.00824021 0.0150348 0.0219622 0.0174156 0.0135933 0.0121427 0.0122044 0.0134719 0.0132782 0.0121485 0.0134253 0.0160149 0.0206375 0.0272065 0.0361589 0.047554 0.0612379 0.07712 0.0948916 0.114056 0.134004 0.154045 0.173335 0.190759 0.205574 0.217394 0.226055 0.229757 0.229994 0.229999 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.00771928 0.0140465 0.0207141 0.0274378 0.0229485 0.0191156 0.0175319 0.0174671 0.0184667 0.0178978 0.0167466 0.0176519 0.0201311 0.0241834 0.0303235 0.0386044 0.0492566 0.0622294 0.0773662 0.0944222 0.11296 0.132401 0.152089 0.171207 0.188722 0.203761 0.215897 0.224994 0.229559 0.22999 0.229999 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.0135428 0.0197816 0.0262718 0.0327639 0.0283595 0.0245434 0.0228343 0.0225983 0.0233898 0.022647 0.0212639 0.0220662 0.0241408 0.0278879 0.0334644 0.0411768 0.051123 0.0633682 0.0777873 0.0941397 0.112042 0.130957 0.150262 0.169163 0.186722 0.201956 0.214393 0.223867 0.229259 0.229984 0.229999 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.0193055 0.0253974 0.0316768 0.0379205 0.0336237 0.0298493 0.0280361 0.0276228 0.0281991 0.0273329 0.0258216 0.0263607 0.0282091 0.0315482 0.0366867 0.0438144 0.053124 0.0646615 0.0783693 0.0940311 0.111297 0.129672 0.148569 0.167219 0.18477 0.200163 0.21288 0.222694 0.228829 0.229973 0.229998 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.0249502 0.0308586 0.0369073 0.0428931 0.0387221 0.035013 0.0331199 0.0325417 0.0329059 0.0319216 0.0303267 0.0306422 0.0322077 0.0352283 0.0399197 0.0465297 0.0552223 0.0660943 0.0791059 0.094086 0.110717 0.128542 0.147012 0.165389 0.182873 0.198389 0.211358 0.221486 0.228262 0.229951 0.229998 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.0304396 0.0361424 0.0419483 0.0476742 0.0436407 0.0400173 0.0380712 0.0373497 0.0375141 0.0364158 0.0347477 0.0348812 0.0361817 0.0388758 0.0431745 0.0492897 0.0574109 0.0676431 0.0799851 0.0942954 0.110294 0.127564 0.145589 0.16367 0.181032 0.19664 0.209829 0.22025 0.227567 0.229908 0.229997 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.0357501 0.0412332 0.0467922 0.0522629 0.0483723 0.044849 0.0428757 0.0420374 0.0420226 0.0408195 0.0390821 0.0390504 0.040121 0.0425071 0.0464282 0.0520887 0.05967 0.0692964 0.0809911 0.0946487 0.110023 0.126731 0.144298 0.162061 0.179261 0.194922 0.208299 0.218992 0.226766 0.229828 0.229995 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.0408659 0.0461232 0.0514383 0.0566629 0.0529155 0.0495009 0.047522 0.0465935 0.0464249 0.0451321 0.0433327 0.0431451 0.0440055 0.0461133 0.0496797 0.0549108 0.0619868 0.0710388 0.0821124 0.0951341 0.109893 0.126041 0.143137 0.160561 0.177568 0.193244 0.206777 0.217722 0.225887 0.229693 0.229993 0.229999 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.0457792 0.0508118 0.0558909 0.0608812 0.0572739 0.0539713 0.0520027 0.0510079 0.0507118 0.049348 0.0474989 0.0471666 0.0478294 0.0496802 0.0529199 0.0577489 0.0643485 0.0728572 0.083337 0.0957421 0.109896 0.125486 0.142105 0.159171 0.175959 0.191611 0.20527 0.21645 0.22495 0.229485 0.229989 0.229999 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.0504891 0.0553035 0.0601572 0.0649248 0.061454 0.0582631 0.0563159 0.0552738 0.0548745 0.0534591 0.0515756 0.0511139 0.0515926 0.0532019 0.0561373 0.0605923 0.0667453 0.0747394 0.0846526 0.0964627 0.110025 0.125061 0.141197 0.15789 0.174436 0.19003 0.203784 0.215179 0.22397 0.229185 0.229982 0.229999 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.0550006 0.0596058 0.0642451 0.0688032 0.0654625 0.0623821 0.0604634 0.0593886 0.0589064 0.057457 0.0555552 0.0549825 0.0552932 0.0566766 0.0593257 0.0634304 0.0691655 0.0766752 0.0860483 0.0972855 0.110271 0.124759 0.14041 0.156718 0.173002 0.188505 0.202323 0.213909 0.222961 0.228777 0.22997 0.229998 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.059321 0.0637267 0.0681641 0.0725241 0.0693086 0.0663346 0.0644495 0.063353 0.0628044 0.0613353 0.0594298 0.0587652 0.0589271 0.0601019 0.0624821 0.0662564 0.0715983 0.0786523 0.0875137 0.0982007 0.110625 0.124575 0.13974 0.155652 0.171657 0.187039 0.20089 0.21264 0.22193 0.228262 0.229947 0.229998 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.0634587 0.0676762 0.0719224 0.076096 0.0729998 0.070129 0.0682796 0.0671702 0.0665681 0.0650906 0.0631929 0.0624547 0.0624876 0.0634734 0.0656033 0.0690662 0.0740362 0.0806596 0.0890367 0.0991985 0.11108 0.124501 0.139183 0.154692 0.170403 0.185636 0.199492 0.211376 0.220883 0.22765 0.229904 0.229997 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.0674236 0.0714626 0.0755288 0.079528 0.0765443 0.0737726 0.0719611 0.0708441 0.0701995 0.0687218 0.0668408 0.0660447 0.0659677 0.0667851 0.0686849 0.0718558 0.076474 0.082689 0.0906065 0.100268 0.111627 0.12453 0.138733 0.153835 0.169239 0.184296 0.198131 0.210122 0.219825 0.22696 0.22983 0.229995 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.0712242 0.0750949 0.0789926 0.0828291 0.079951 0.0772732 0.0755004 0.0743811 0.0737013 0.0722302 0.0703723 0.0695311 0.0693613 0.0700304 0.071721 0.0746206 0.0789072 0.0847345 0.0922143 0.101398 0.112254 0.124655 0.138384 0.153076 0.168162 0.183021 0.196812 0.208884 0.218766 0.226212 0.229711 0.229993 0.229999 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.0748696 0.0785824 0.0823231 0.0860084 0.0832287 0.0806393 0.0789047 0.0777867 0.0770788 0.0756179 0.073788 0.0729121 0.072664 0.073203 0.0747052 0.0773549 0.0813307 0.0867905 0.0938533 0.10258 0.112954 0.124867 0.138131 0.152412 0.167172 0.181812 0.195536 0.207667 0.217711 0.22542 0.229534 0.22999 0.229999 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.0783692 0.0819349 0.0855297 0.0890742 0.0863864 0.0838795 0.0821818 0.0810671 0.0803364 0.0788893 0.0770894 0.0761875 0.0758733 0.0762984 0.0776316 0.0800524 0.0837387 0.0888518 0.0955174 0.103806 0.113716 0.125158 0.137966 0.151837 0.166264 0.180669 0.194307 0.206475 0.216664 0.224599 0.229286 0.229984 0.229999 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.0817329 0.0851618 0.0886208 0.0920336 0.0894321 0.0870023 0.0853395 0.0842295 0.0834798 0.0820485 0.0802807 0.0793584 0.0789886 0.0793136 0.0804953 0.0827073 0.0861254 0.0909126 0.0972009 0.105071 0.114534 0.125519 0.137882 0.151347 0.165436 0.179594 0.193125 0.205309 0.215625 0.223757 0.228955 0.229974 0.229999 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.0849701 0.0882717 0.0916038 0.0948925 0.0923727 0.0900156 0.0883858 0.0872808 0.0865149 0.0851004 0.0833653 0.0824281 0.08201 0.0822471 0.0832927 0.0853146 0.0884848 0.092967 0.0988981 0.106368 0.115401 0.125944 0.137873 0.150937 0.164685 0.178586 0.191992 0.204171 0.214593 0.222903 0.22854 0.229957 0.229998 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.0880896 0.0912723 0.0944848 0.0976552 0.0952141 0.092926 0.0913277 0.0902282 0.0894481 0.0880506 0.086348 0.0853995 0.0849402 0.0850986 0.0860218 0.0878702 0.0908119 0.0950094 0.100603 0.107692 0.116312 0.126426 0.137933 0.150601 0.164009 0.177643 0.190908 0.203064 0.21357 0.22204 0.228049 0.229926 0.229997 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.0910991 0.0941697 0.0972682 0.100325 0.0979605 0.0957391 0.0941716 0.0930779 0.0922854 0.0909046 0.0892337 0.0882767 0.0877815 0.0878698 0.0886815 0.0903717 0.0931024 0.0970345 0.102311 0.109037 0.11726 0.126961 0.138055 0.150335 0.163403 0.176766 0.189874 0.201989 0.212559 0.221171 0.227494 0.229874 0.229996 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.0940047 0.0969685 0.0999576 0.102906 0.100615 0.098459 0.0969224 0.0958355 0.0950324 0.0936682 0.0920278 0.0910643 0.0905374 0.0905625 0.0912729 0.0928172 0.0953532 0.0990382 0.104016 0.110397 0.118241 0.127542 0.138236 0.150134 0.162864 0.175955 0.188887 0.200947 0.211563 0.220302 0.226891 0.229791 0.229995 0.23 0.23 0.23 0.23 0.23 0.23 0.23 0.0968114 0.0996724 0.102556 0.105399 0.103181 0.101089 0.0995839 0.0985055 0.0976939 0.0963463 0.0947354 0.0937667 0.0932116 0.0931794 0.0937972 0.0952072 0.0975622 0.101017 0.105714 0.111769 0.11925 0.128166 0.138471 0.149994 0.162389 0.175205 0.187945 0.199938 0.210585 0.219439 0.22625 0.229669 0.229992 0.229999 0.23 0.23 0.23 0.23 0.23 0.23 0.0995227 0.102284 0.105066 0.107808 0.105661 0.103632 0.102159 0.101091 0.100274 0.0989432 0.0973612 0.0963888 0.0958082 0.0957237 0.0962562 0.0975422 0.099729 0.102968 0.107401 0.113147 0.120282 0.128828 0.138755 0.149912 0.161974 0.174514 0.187051 0.198964 0.209626 0.218583 0.225582 0.229499 0.229988 0.229999 0.23 0.23 0.23 0.23 0.23 0.23 0.102142 0.104807 0.107491 0.110136 0.108057 0.10609 0.10465 0.103595 0.102774 0.101462 0.099909 0.0989344 0.0983311 0.0981986 0.0986524 0.0998233 0.101853 0.10489 0.109076 0.114529 0.121333 0.129524 0.139085 0.149883 0.161617 0.173878 0.186206 0.198024 0.208689 0.217736 0.224896 0.229269 0.229982 0.229999 0.23 0.23 0.23 0.23 0.23 0.23 0.104671 0.107244 0.109834 0.112387 0.110374 0.108466 0.10706 0.106019 0.105198 0.103906 0.102382 0.101407 0.100784 0.100607 0.100988 0.102052 0.103936 0.106784 0.110735 0.115911 0.1224 0.130249 0.139457 0.149905 0.161314 0.173297 0.185409 0.19712 0.207773 0.216898 0.224199 0.228974 0.229972 0.229999 0.23 0.23 0.23 0.23 0.23 0.23 0.107114 0.109599 0.112099 0.114566 0.112614 0.110763 0.109391 0.108365 0.107547 0.106276 0.104782 0.103809 0.103169 0.102953 0.103266 0.104231 0.105978 0.108648 0.112378 0.117291 0.12348 0.131002 0.139868 0.149974 0.161062 0.172769 0.184662 0.196251 0.206879 0.216067 0.223494 0.228617 0.229955 0.229998 0.23 0.23 0.23 0.23 0.23 0.23 0.109474 0.111874 0.114291 0.116675 0.114782 0.112986 0.111646 0.110637 0.109823 0.108575 0.107111 0.106142 0.105489 0.105237 0.105489 0.10636 0.107979 0.110482 0.114004 0.118667 0.12457 0.131779 0.140314 0.150087 0.16086 0.172291 0.183965 0.195415 0.206009 0.215246 0.222785 0.228202 0.229927 0.229997 0.23 0.23 0.23 0.23 0.23 0.23 0.111755 0.114075 0.116413 0.11872 0.116882 0.115137 0.113829 0.112837 0.112029 0.110803 0.109371 0.108409 0.107744 0.107461 0.107657 0.108442 0.109942 0.112288 0.115612 0.120038 0.125668 0.132577 0.140793 0.150241 0.160705 0.17186 0.183313 0.194612 0.205162 0.214435 0.222074 0.227741 0.229882 0.229996 0.23 0.23 0.23 0.23 0.23 0.23 0.113961 0.116206 0.118468 0.120702 0.118917 0.117221 0.115943 0.114968 0.114166 0.112964 0.111564 0.110609 0.109937 0.109627 0.109771 0.110478 0.111866 0.114064 0.117202 0.121404 0.126774 0.133394 0.141302 0.150435 0.160593 0.171475 0.182704 0.193845 0.204339 0.213636 0.221364 0.227242 0.229814 0.229995 0.23 0.23 0.23 0.23 0.23 0.23 0.116097 0.118271 0.120461 0.122625 0.120891 0.119242 0.117993 0.117033 0.116239 0.11506 0.11369 0.112746 0.112069 0.111735 0.111833 0.112467 0.113752 0.115811 0.118774 0.122762 0.127885 0.134228 0.141839 0.150664 0.160524 0.171135 0.182138 0.193114 0.203541 0.212851 0.22066 0.226714 0.229716 0.229993 0.229999 0.23 0.23 0.23 0.23 0.23 0.118166 0.120272 0.122395 0.124491 0.122806 0.121202 0.11998 0.119037 0.11825 0.117093 0.115754 0.11482 0.11414 0.113786 0.113843 0.11441 0.115599 0.117529 0.120326 0.124113 0.128999 0.135078 0.142402 0.150928 0.160494 0.170837 0.181613 0.192419 0.202769 0.212081 0.219963 0.226164 0.229582 0.229989 0.229999 0.23 0.23 0.23 0.23 0.23 0.120171 0.122213 0.12427 0.126303 0.124665 0.123104 0.12191 0.120981 0.120202 0.119067 0.117757 0.116834 0.116153 0.115782 0.115802 0.116308 0.117407 0.119216 0.121858 0.125454 0.130116 0.135942 0.142988 0.151224 0.160503 0.170579 0.181129 0.191761 0.202023 0.211328 0.219273 0.225602 0.229403 0.229985 0.229999 0.23 0.23 0.23 0.23 0.23 0.122116 0.124095 0.126091 0.128062 0.126469 0.12495 0.123783 0.12287 0.122098 0.120984 0.119703 0.118791 0.11811 0.117724 0.11771 0.11816 0.119177 0.120873 0.123369 0.126785 0.131234 0.136817 0.143597 0.151551 0.160548 0.170361 0.180685 0.191142 0.201302 0.210591 0.218592 0.225031 0.229177 0.229977 0.229999 0.23 0.23 0.23 0.23 0.23 0.124002 0.125923 0.127858 0.129771 0.128222 0.126743 0.125602 0.124705 0.123942 0.122848 0.121594 0.120693 0.120012 0.119613 0.119569 0.119968 0.120908 0.122499 0.124858 0.128104 0.132351 0.137703 0.144226 0.151905 0.160627 0.170181 0.180278 0.190558 0.200605 0.209872 0.217917 0.224455 0.228902 0.229966 0.229998 0.23 0.23 0.23 0.23 0.23 0.125833 0.127697 0.129575 0.131431 0.129924 0.128485 0.127369 0.126488 0.125734 0.12466 0.123432 0.122543 0.121863 0.121452 0.121381 0.121733 0.122602 0.124094 0.126325 0.12941 0.133466 0.138597 0.144872 0.152287 0.160739 0.170037 0.179909 0.190009 0.199935 0.209171 0.21725 0.223876 0.228582 0.229947 0.229998 0.23 0.23 0.23 0.23 0.23 0.12761 0.129419 0.131243 0.133045 0.131579 0.130177 0.129087 0.128221 0.127476 0.126423 0.125221 0.124343 0.123665 0.123244 0.123147 0.123455 0.124258 0.125658 0.127768 0.130702 0.134577 0.139498 0.145535 0.152693 0.160882 0.169928 0.179575 0.189493 0.199293 0.208488 0.216592 0.223297 0.228224 0.229918 0.229997 0.23 0.23 0.23 0.23 0.23 0.129336 0.131093 0.132864 0.134615 0.133188 0.131822 0.130756 0.129907 0.129172 0.128139 0.126962 0.126095 0.12542 0.12499 0.12487 0.125137 0.125878 0.127193 0.129189 0.131981 0.135684 0.140403 0.146213 0.153122 0.161056 0.169854 0.179277 0.189012 0.198679 0.207824 0.215944 0.222718 0.227833 0.229874 0.229996 0.23 0.23 0.23 0.23 0.23 0.131012 0.132719 0.13444 0.136142 0.134752 0.133422 0.13238 0.131547 0.130821 0.129808 0.128656 0.127802 0.127129 0.126692 0.12655 0.126779 0.127463 0.128697 0.130587 0.133246 0.136786 0.141313 0.146903 0.153572 0.161257 0.169811 0.179013 0.188563 0.198094 0.20718 0.215308 0.222143 0.227417 0.229811 0.229995 0.23 0.23 0.23 0.23 0.23 0.132642 0.134301 0.135972 0.137622 0.136274 0.134979 0.13396 0.133142 0.132427 0.131434 0.130306 0.129463 0.128795 0.128351 0.128191 0.128385 0.129015 0.130174 0.131964 0.134496 0.137881 0.142226 0.147605 0.154043 0.161485 0.169801 0.178783 0.188147 0.197539 0.206557 0.214683 0.221574 0.226981 0.229724 0.229992 0.229999 0.23 0.23 0.23 0.23 0.134225 0.135837 0.137458 0.139042 0.137749 0.136492 0.135498 0.134696 0.133991 0.133017 0.131913 0.131083 0.130419 0.12997 0.129793 0.129954 0.130535 0.131623 0.133319 0.135731 0.13897 0.14314 0.148318 0.154531 0.161738 0.16982 0.178585 0.187763 0.197015 0.205953 0.214072 0.221012 0.22653 0.229609 0.229989 0.229999 0.23 0.23 0.23 0.23 0.135765 0.137327 0.138883 0.140351 0.139165 0.137961 0.136994 0.136209 0.135516 0.13456 0.133479 0.132661 0.132003 0.13155 0.131357 0.131489 0.132023 0.133045 0.134654 0.136953 0.140053 0.144056 0.14904 0.155037 0.162015 0.169868 0.178419 0.187411 0.196519 0.20537 0.213475 0.220458 0.226071 0.229461 0.229985 0.229999 0.23 0.23 0.23 0.23 0.137257 0.138757 0.140197 0.141362 0.140471 0.13937 0.138447 0.137683 0.137001 0.136064 0.135005 0.1342 0.133548 0.133092 0.132885 0.132991 0.133482 0.134443 0.135968 0.138161 0.141128 0.144972 0.14977 0.155559 0.162315 0.169944 0.178283 0.187089 0.196052 0.204808 0.212892 0.21991 0.225607 0.229276 0.229979 0.229999 0.23 0.23 0.23 0.23 0.138688 0.140074 0.141211 0.141479 0.14067 0.139842 0.139114 0.138449 0.137532 0.136495 0.135702 0.135055 0.134597 0.134379 0.13446 0.134911 0.135815 0.137262 0.139355 0.142196 0.145887 0.150507 0.156095 0.162636 0.170047 0.178176 0.186798 0.195613 0.204269 0.212324 0.219369 0.22514 0.229056 0.229969 0.229999 0.23 0.23 0.23 0.23 0.140007 0.141091 0.141674 0.141129 0.14049 0.139857 0.138963 0.137948 0.137167 0.136527 0.136068 0.135839 0.135897 0.136312 0.137162 0.138537 0.140535 0.143257 0.146802 0.15125 0.156645 0.162977 0.170174 0.178098 0.186536 0.195201 0.203753 0.211772 0.218836 0.224671 0.228801 0.229954 0.229998 0.23 0.23 0.23 0.23 0.141025 0.142123 0.14176 0.141211 0.140355 0.139366 0.138599 0.137966 0.137506 0.137267 0.137306 0.137686 0.138487 0.139793 0.141701 0.144309 0.147716 0.152 0.157207 0.163337 0.170327 0.178049 0.186303 0.194818 0.203261 0.211236 0.218312 0.224204 0.228517 0.229932 0.229997 0.23 0.23 0.23 0.23 0.142741 0.142462 0.141694 0.140746 0.139996 0.139372 0.138913 0.138666 0.138685 0.139035 0.139788 0.14103 0.142853 0.145353 0.148627 0.152753 0.157781 0.163715 0.170502 0.178026 0.186099 0.194462 0.202794 0.210718 0.217797 0.223738 0.228207 0.2299 0.229997 0.23 0.23 0.23 0.23 0.143429 0.142932 0.142074 0.141358 0.140746 0.140289 0.140035 0.140038 0.140358 0.141068 0.142249 0.143991 0.146389 0.149536 0.153511 0.158366 0.16411 0.1707 0.178029 0.185923 0.194134 0.202352 0.210218 0.217293 0.223275 0.227877 0.229854 0.229995 0.23 0.23 0.23 0.23 0.143889 0.143302 0.142669 0.142085 0.141635 0.141377 0.141364 0.141657 0.142326 0.14345 0.145116 0.147417 0.150443 0.154273 0.158961 0.164522 0.17092 0.178058 0.185774 0.193833 0.201936 0.209736 0.216801 0.222819 0.227531 0.229793 0.229994 0.23 0.23 0.23 0.23 0.144251 0.143881 0.143375 0.142948 0.142691 0.142665 0.142934 0.143565 0.144635 0.146228 0.148436 0.151346 0.155038 0.159566 0.16495 0.171161 0.178113 0.185654 0.19356 0.201545 0.209274 0.216321 0.222371 0.227173 0.229713 0.229992 0.23 0.23 0.23 0.23 0.144818 0.14457 0.144215 0.143974 0.143941 0.144188 0.144784 0.145803 0.147328 0.149447 0.152247 0.155806 0.16018 0.165393 0.171423 0.178193 0.18556 0.193315 0.20118 0.208832 0.215856 0.221931 0.226809 0.22961 0.229989 0.229999 0.23 0.23 0.23 0.145493 0.145389 0.145213 0.145189 0.145421 0.145984 0.146956 0.148416 0.150451 0.153146 0.156577 0.160803 0.165851 0.171706 0.178297 0.185494 0.193097 0.200841 0.208412 0.215406 0.2215 0.226442 0.229482 0.229985 0.229999 0.23 0.23 0.23 0.146295 0.146361 0.146395 0.146627 0.147165 0.148093 0.149493 0.151448 0.154042 0.157352 0.161436 0.166325 0.172008 0.178426 0.185455 0.192908 0.200528 0.208014 0.214973 0.221078 0.226076 0.22933 0.229979 0.229999 0.23 0.23 0.23 0.147248 0.147514 0.147795 0.148324 0.149215 0.150558 0.152438 0.154936 0.15813 0.162077 0.166813 0.172332 0.178579 0.185444 0.192747 0.200243 0.207641 0.214557 0.220667 0.225711 0.229153 0.22997 0.229999 0.23 0.23 0.23 0.148378 0.148879 0.149447 0.150318 0.151612 0.153421 0.155829 0.158911 0.162728 0.167316 0.172675 0.178758 0.18546 0.192615 0.199986 0.207292 0.214159 0.220268 0.225351 0.228955 0.229958 0.229998 0.23 0.23 0.23 0.149716 0.150491 0.151389 0.152651 0.154397 0.15672 0.159696 0.163389 0.167835 0.173039 0.178961 0.185505 0.192512 0.19976 0.206969 0.213782 0.219882 0.224997 0.228739 0.22994 0.229998 0.23 0.23 0.23 0.151297 0.152386 0.153662 0.155363 0.157609 0.160486 0.164059 0.168368 0.173424 0.179189 0.185578 0.192439 0.199564 0.206672 0.213426 0.219511 0.22465 0.228508 0.229917 0.229997 0.23 0.23 0.23 0.153156 0.154604 0.156306 0.158493 0.161279 0.164739 0.168918 0.17383 0.179444 0.185681 0.1924 0.199399 0.206403 0.213094 0.219157 0.224313 0.228267 0.229885 0.229996 0.23 0.23 0.23 0.155332 0.157186 0.159359 0.162073 0.16543 0.169486 0.174259 0.179727 0.185816 0.192394 0.199264 0.206162 0.212785 0.218821 0.223987 0.228019 0.229844 0.229995 0.23 0.23 0.23 0.157866 0.160168 0.162853 0.166125 0.170067 0.17471 0.180037 0.185982 0.192419 0.199159 0.205952 0.212503 0.218505 0.223676 0.227769 0.229792 0.229994 0.23 0.23 0.23 0.160795 0.163585 0.166812 0.170658 0.175179 0.180371 0.186175 0.192474 0.199087 0.205773 0.212249 0.218211 0.223381 0.22752 0.229729 0.229992 0.23 0.23 0.23 0.164152 0.16746 0.171247 0.175662 0.180727 0.186396 0.19256 0.199047 0.205628 0.212024 0.217942 0.223105 0.227278 0.229654 0.229989 0.23 0.23 0.23 0.167964 0.171806 0.17615 0.181103 0.186644 0.192678 0.199042 0.205516 0.211832 0.217701 0.22285 0.227044 0.229568 0.229986 0.229999 0.23 0.23 0.172243 0.176619 0.181491 0.186917 0.192827 0.199072 0.20544 0.211673 0.217488 0.222617 0.226824 0.229472 0.229982 0.229999 0.23 0.23 0.176986 0.181869 0.187209 0.193007 0.199137 0.205402 0.21155 0.217308 0.222411 0.226619 0.229368 0.229977 0.229999 0.23 0.23 0.182168 0.1875 0.19321 0.199236 0.2054 0.211465 0.217163 0.222232 0.226434 0.229261 0.22997 0.229999 0.23 0.23 0.187734 0.193422 0.199363 0.205435 0.211418 0.217054 0.222085 0.226272 0.229154 0.229961 0.229999 0.23 0.23 0.193597 0.199507 0.205503 0.211409 0.216983 0.221972 0.226135 0.229053 0.229951 0.229998 0.23 0.23 0.199633 0.205594 0.211437 0.216951 0.221895 0.226028 0.228962 0.22994 0.229998 0.23 0.23 0.205681 0.211493 0.216957 0.221856 0.225952 0.228884 0.229928 0.229997 0.23 0.23 0.211555 0.216995 0.221855 0.225911 0.228826 0.229916 0.229997 0.23 0.23 0.217047 0.221887 0.225906 0.228788 0.229904 0.229996 0.23 0.23 0.22194 0.225935 0.228775 0.229895 0.229996 0.23 0.23 0.225995 0.228785 0.22989 0.229996 0.23 0.23 0.228825 0.229887 0.229995 0.23 0.23 0.229891 0.229995 0.23 0.23 0.229995 0.23 0.23 0.23 0.23 0.23 ) ; boundaryField { wallTube { type zeroGradient; } outlet { type zeroGradient; } inletPilot { type fixedValue; value uniform 0.054; } inletAir { type fixedValue; value uniform 0.23; } wallOutside { type zeroGradient; } inletCH4 { type fixedValue; value uniform 0.1966; } frontAndBack_pos { type wedge; } frontAndBack_neg { type wedge; } } // ************************************************************************* //
[ "ali@ali-Inspiron-1525.(none)" ]
ali@ali-Inspiron-1525.(none)
d27cc08298f77b80f03100beb2bcfca95552c86e
3ac78caf28163a075b51f3216f83a998e515f894
/toys/misc/cpp2/moo/copycon.cpp
c26472490c28e4c7b3976e89f940b37d301699c5
[]
no_license
walrus7521/code
566fe5b6f96e91577cf2147d5a8c6f3996dab08c
29e07e4cfc904e9f1a4455ced202506e3807f74c
refs/heads/master
2022-12-14T03:40:11.237082
2020-09-30T15:34:02
2020-09-30T15:34:02
46,368,605
2
1
null
2022-12-09T11:45:41
2015-11-17T19:00:35
C
UTF-8
C++
false
false
5,489
cpp
#include <iostream> #include <string> #include <utility> using namespace std; class numbered { public: static int random; numbered() { cout << "numbered: ctor" << endl; serial = random++; } numbered(const numbered& rhs) { cout << "numbered: copy ctor" << endl; serial = random++; } int get() const { return serial; } private: int serial; }; int numbered::random = 42; class Foo { public: // default constructor // default initializes all members in order as appear in class // prior to running the body Foo() : name("Bart") { cout << "Foo: ctor" << endl; } // default constructor // copy constructor should not be explicit Foo(const Foo &rhs) : units(rhs.units), name(rhs.name) { cout << "Foo: copy ctor" << endl; } // copy constructor // copy assignment Foo& operator=(const Foo& rhs) { cout << "Foo: copy assn" << endl; name = rhs.name; units = rhs.units; return *this; // return reference to lhs } // copy assignment // destructor // body runs first, then the members are implicitly destroyed // in reverse order as appear in class // use smart pointers so they get automatically destroyed ~Foo() { cout << "Foo: dtor" << endl; } string get() { return name; } private: std::string name; int units; }; void fr(const numbered& s) { cout << "f(): " << s.get() << endl; } // value like class HasPtr { friend void swap(HasPtr &lhs, HasPtr &rhs); public: HasPtr(const string& s = string()) : ps(new string(s)), i(0) { cout << "HasPtr: ctor" << endl; } ~HasPtr() { cout << "HasPtr: dtor" << endl; delete ps; } HasPtr(const HasPtr &rhs) : i(rhs.i), ps(new string(*rhs.ps)) { cout << "HasPtr: copy ctor" << endl; } // copy constructor #if 0 // value-like copy assignment HasPtr& operator=(const HasPtr& rhs) { cout << "HasPtr: copy assn" << endl; auto newp = new string(*rhs.ps); delete ps; ps = newp; i = rhs.i; return *this; // return reference to lhs } // copy assignment #endif // movers HasPtr(HasPtr &&rhs) noexcept : ps(rhs.ps), i(rhs.i) { cout << "HasPtr: move ctor" << endl; rhs.i = 0; rhs.ps = nullptr; } // this is both a move and copy assignment operator HasPtr& operator=(HasPtr rhs) { cout << "HasPtr: move assn2" << endl; swap(*this, rhs); return *this; } void show() { cout << "show: " << *ps << endl; } private: int i; string *ps; }; void swap(HasPtr &lhs, HasPtr &rhs) { using std::swap; swap(lhs.ps, rhs.ps); swap(lhs.i, rhs.i); } // we would normally use shared_ptr's to manage the destrution // of the string pointer, but we will instead implement reference // counting because we love pain. class HasPtr_PointerLike { friend void swap(HasPtr_PointerLike &lhs, HasPtr_PointerLike &rhs); public: HasPtr_PointerLike(const string& s = string()) : ps(new string(s)), i(0), use(new size_t(1)) { cout << "HasPtr_PointerLike: ctor" << endl; } ~HasPtr_PointerLike() { cout << "HasPtr_PointerLike: dtor" << endl; if (--*use == 0) { delete ps; delete use; } } HasPtr_PointerLike(const HasPtr_PointerLike &rhs) : i(rhs.i), ps(rhs.ps), use(rhs.use) { cout << "HasPtr_PointerLike: copy ctor" << endl; ++*use; } // copy constructor // value-like copy assignment HasPtr_PointerLike& operator=(const HasPtr_PointerLike& rhs) { cout << "HasPtr_PointerLike: copy assn" << endl; //swap(*this, rhs); ++*rhs.use; if (--*use == 0) { delete ps; delete use; } ps = rhs.ps; i = rhs.i; use = rhs.use; return *this; // return reference to lhs } // copy assignment void show() { cout << "show: " << *ps << endl; } private: string *ps; int i; size_t *use; }; void swap(HasPtr_PointerLike &lhs, HasPtr_PointerLike &rhs) { using std::swap; swap(lhs.ps, rhs.ps); swap(lhs.i, rhs.i); } void test_has_ptr_pointer_like() { cout << "testing HasPtr_PointerLike - enter" << endl; HasPtr_PointerLike h1("bart"); HasPtr_PointerLike h2("cindy"); h1.show(); h2 = h1; h2.show(); cout << "testing HasPtr_PointerLike - exit" << endl; } void test_has_ptr_value_like() { cout << "testing HasPtr_ValueLike - enter" << endl; HasPtr h1("bart"); HasPtr h2("cindy"); //h1.show(); h2 = h1; //h2 = std::move(h1); //h2.show(); cout << "testing HasPtr_ValueLike - exit" << endl; } void test_move() { int r = 42; int &r1 = r; int &&rr = r * 3; int &&rr2 = std::move(r); cout << "rr: " << rr << endl; cout << "rr2: " << rr2 << endl; } int main() { #if 0 Foo f; cout << "f: " << f.get() << endl; Foo g = f; // copy init cout << "g: " << g.get() << endl; Foo h(g); // direct init cout << "h: " << h.get() << endl; Foo j; j = g; cout << "j: " << j.get() << endl; numbered a, b = a, c = b; fr(a); fr(b); fr(c); #endif test_has_ptr_value_like(); //test_has_ptr_pointer_like(); //test_move(); }
15c4b3189792df72824eb75840fc8a4f75672a2c
3b97b786b99c3e4e72bf8fe211bb710ecb674f2b
/TClient/TEngine/Game Studio/AddTextureDlg.h
e674ba65f4db4390c8aab92cd602e58c32feab25
[]
no_license
moooncloud/4s
930384e065d5172cd690c3d858fdaaa6c7fdcb34
a36a5785cc20da19cd460afa92a3f96e18ecd026
refs/heads/master
2023-03-17T10:47:28.154021
2017-04-20T21:42:01
2017-04-20T21:42:01
null
0
0
null
null
null
null
UHC
C++
false
false
999
h
#pragma once #include "afxwin.h" #define DEF_LOADTYPE_FILE 0 #define DEF_LOADTYPE_FOLDER 1 #define DEF_LOADTYPE_SPRITE 2 // CAddTextureDlg 대화 상자입니다. class CAddTextureDlg : public CDialog { DECLARE_DYNAMIC(CAddTextureDlg) public: CAddTextureDlg(CWnd* pParent = NULL); // 표준 생성자입니다. virtual ~CAddTextureDlg(); // 대화 상자 데이터입니다. enum { IDD = IDD_DIALOG_ADDTEXTURE }; protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV 지원입니다. DECLARE_MESSAGE_MAP() public: CString m_strFolderName; CString m_strFileName; CString m_strTitle; CStatic m_cFolderTitle; CStatic m_cFileTitle; CComboBox m_cLoadType; int m_nLoadType; CButton m_cFolder; CButton m_cFile; CEdit m_cFolderEdit; CEdit m_cFileEdit; afx_msg void OnCbnSelchangeComboLoadtype(); afx_msg void OnBnClickedButtonFolder(); afx_msg void OnBnClickedButtonImagefile(); virtual BOOL OnInitDialog(); protected: virtual void OnOK(); };
19b29bc78e20535088df995666c7fa43c38f6431
5579f660876acca08d681a039fcfac4bb625f5d7
/infovis/drawing/inter/Interactor3States.cpp
15b6bf94d5256cc731783fb257a09abe447384f3
[ "MIT" ]
permissive
jdfekete/millionvis
e278d267cb6a2bf2d29f616ea5378d528c4e4d2c
01dab6a40ebdb3eef751b638171805665f4ee68f
refs/heads/master
2020-05-30T07:11:59.739040
2016-09-24T15:30:07
2016-09-24T15:30:07
69,087,119
0
2
null
null
null
null
UTF-8
C++
false
false
2,782
cpp
/* -*- C++ -*- * * Copyright (C) 2016 Jean-Daniel Fekete * * This file is part of MillionVis. * * 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 <infovis/drawing/inter/Interactor3States.hpp> namespace infovis { void Interactor3States::proximity_in(const Event& ev) { if (state != state_away) return; doProximityIn(ev); state = state_present; } void Interactor3States::proximity_out(const Event& ev) { if (state != state_present) return; doProximityOut(ev); state = state_away; } void Interactor3States::move(const Event& ev) { if (state != state_present) return; doMove(ev); } bool Interactor3States::start(const Event& ev) { if (state != state_present) return false; if (doStart(ev)) { state = state_dragged; start_pos = Point(getFieldX(ev),getFieldY(ev)); return true; } else return false; } void Interactor3States::drag(const Event& ev) { if (state != state_dragged) return; doDrag(ev); current_pos = Point(getFieldX(ev),getFieldY(ev)); } void Interactor3States::finish(const Event& ev) { if (state != state_dragged) return; doFinish(ev); state = state_present; current_pos = Point(getFieldX(ev),getFieldY(ev)); } void Interactor3States::desactivate(const Event& ev) { Interactor::desactivate(ev); } void Interactor3States::abort(const Event& ev) { state = state_present; Interactor::abort(ev); } void Interactor3States::doProximityIn(const Event& ev) { } void Interactor3States::doProximityOut(const Event& ev) { } void Interactor3States::doMove(const Event& ev) { } bool Interactor3States::doStart(const Event& ev) { return true; } void Interactor3States::doDrag(const Event& ev) { } void Interactor3States::doFinish(const Event& ev) { } } // namespace infovis
dbe304ed490b87be6b5f026603627d1f8a8bb441
c270fe23c8e4aeca0d5ac4c64b84b32eb2c1d752
/sterling.cpp
0a40b0067201c4b3c05238ee49a4c7cfda2fc0ee
[ "MIT" ]
permissive
CobaltXII/sterling
25b326033ae33fc6390423d29fb428adc260f982
abef14ec8019aca55e359f78da5711c70be77d35
refs/heads/master
2020-04-30T12:23:27.285931
2019-03-24T19:22:36
2019-03-24T19:22:36
176,825,389
0
0
null
null
null
null
UTF-8
C++
false
false
9,257
cpp
/* Sterling - a naive pathtracer */ #include <map> #include <cmath> #include <random> #include <string> #include <climits> #include <iostream> #include <glm/glm.hpp> #include <glm/vec2.hpp> #include <glm/vec3.hpp> #include <glm/vec4.hpp> #include "hpp/loader.hpp" #include "hpp/utility.hpp" #include "hpp/material.hpp" #include "hpp/triangle.hpp" #include "hpp/hierarchy.hpp" #include "stb/stb_image_write.h" #include "inih/ini.h" #include "tinyobjloader/tiny_obj_loader.h" std::vector<kd_tree*> scene; glm::vec3 path_trace(glm::vec3 ray_o, glm::vec3 ray_d) { ray_d = glm::normalize(ray_d); glm::vec3 luminance = {1.0f, 1.0f, 1.0f}; glm::vec3 indirect = {0.0f, 0.0f, 0.0f}; for (int i = 0; i < 8; i++) { triangle* triangle_min = nullptr; float u_min; float v_min; float t_min = INFINITY; for (int j = 0; j < scene.size(); j++) { kd_tree_intersect ( scene[j], ray_o, ray_d, triangle_min, u_min, v_min, t_min ); } if (triangle_min == nullptr) { return indirect + luminance; } else { float bary_a = u_min; float bary_b = v_min; float bary_c = 1.0f - u_min - v_min; glm::vec3 normal = ( triangle_min->n0 * bary_c + triangle_min->n1 * bary_a + triangle_min->n2 * bary_b ); glm::vec3 new_ray_d = triangle_min->material.bounce(normal, ray_d); if (glm::dot(new_ray_d, normal) < 0.0f) { ray_o = ray_o + ray_d * t_min - normal * EPSILON; } else { ray_o = ray_o + ray_d * t_min + normal * EPSILON; } ray_d = new_ray_d; luminance *= triangle_min->material.diffuse; } } return indirect; } material mandelbulb_material = { lambert, { 0.800f, 0.800f, 0.800f } }; float mandelbulb_sdf(glm::vec3 p) { glm::vec3 w = p; float m = glm::dot(w, w); glm::vec4 trap = glm::vec4(fabsf(w.x), fabsf(w.y), fabsf(w.z), m); float dz = 1.0f; for (int i = 0; i < 4; i++) { dz = 8.0f * powf(sqrtf(m), 7.0f) * dz + 1.0f; float r = glm::length(w); float b = 8.0f * acosf(w.y / r); float a = 8.0f * atan2f(w.x, w.z); w = p + powf(r, 8.0f) * glm::vec3(sinf(b) * sinf(a), cosf(b), sinf(b) * cos(a)); trap.x = fmin(trap.x, fabsf(w.x)); trap.y = fmin(trap.y, fabsf(w.y)); trap.z = fmin(trap.z, fabsf(w.z)); trap.w = fmin(trap.w, m); m = glm::dot(w, w); if (m > 256.0f) { break; } } return 0.25f * logf(m) * sqrtf(m) / dz; } // This function is work in progress. Currently, it just renders the // mandelbulb set if the camera is at 0, 0, 3. Maybe in the future it will be // extended so that it can path-march many different shapes. glm::vec3 path_march(glm::vec3 ray_o, glm::vec3 ray_d) { ray_d = glm::normalize(ray_d); glm::vec3 luminance = {1.0f, 1.0f, 1.0f}; glm::vec3 indirect = {0.0f, 0.0f, 0.0f}; for (int iter = 0; iter < 4; iter++) { bool hit = false; float t = 0.0f; for (int i = 0; i < 128; i++) { glm::vec3 p = ray_o + ray_d * t; float dt = mandelbulb_sdf(p); if (dt < 1e-3f) { hit = true; break; } t += dt; if (t > 100.0f) { break; } } if (hit) { glm::vec3 p = ray_o + ray_d * t; glm::vec3 normal = glm::normalize ( glm::vec3 ( mandelbulb_sdf({p.x + 0.001f, p.y + 0.000f, p.z + 0.000f}) - mandelbulb_sdf({p.x - 0.001f, p.y + 0.000f, p.z + 0.000f}), mandelbulb_sdf({p.x + 0.000f, p.y + 0.001f, p.z + 0.000f}) - mandelbulb_sdf({p.x + 0.000f, p.y - 0.001f, p.z + 0.000f}), mandelbulb_sdf({p.x + 0.000f, p.y + 0.000f, p.z + 0.001f}) - mandelbulb_sdf({p.x + 0.000f, p.y + 0.000f, p.z - 0.001f}) ) ); glm::vec3 new_ray_d = mandelbulb_material.bounce(normal, ray_d); if (glm::dot(new_ray_d, normal) < 0.0f) { ray_o = ray_o + ray_d * t - normal * EPSILON; } else { ray_o = ray_o + ray_d * t + normal * EPSILON; } ray_d = new_ray_d; luminance *= mandelbulb_material.diffuse; } else { return indirect + luminance; } } return indirect; } int main(int argc, char** argv) { const int R = 0; const int G = 1; const int B = 2; const float gamma = 1.0f / 2.2f; if (argc != 2 && argc != 3) { std::cout << "Usage: " << argv[0] << " <path> <samples>" << std::endl; exit(EXIT_FAILURE); } if (ini_parse(argv[1], &ini_parser, NULL) < 0) { nuke("Could not load scene (ini_parse)."); } std::map<std::string, material> materials; for (auto section: ini_file) { if (section.first == "main" || section.first == "camera") { continue; } std::string type = inis(section.first, "type"); if (type == "model") { std::vector<triangle*> kd_builder; tinyobj::attrib_t obj_attrib; std::vector<tinyobj::shape_t> obj_shapes; std::vector<tinyobj::material_t> obj_materials; std::string obj_warning; std::string obj_error; if (!tinyobj::LoadObj(&obj_attrib, &obj_shapes, &obj_materials, &obj_warning, &obj_error, inis(section.first, "path").c_str())) { if (!obj_error.empty()) { std::cout << obj_error << std::endl; } return EXIT_FAILURE; } if (!obj_warning.empty()) { std::cout << obj_warning << std::endl; } for (size_t s = 0; s < obj_shapes.size(); s++) { size_t index_offset = 0; for (size_t f = 0; f < obj_shapes[s].mesh.num_face_vertices.size(); f++) { int fv = obj_shapes[s].mesh.num_face_vertices[f]; if (fv == 3) { tinyobj::real_t avx[3]; tinyobj::real_t avy[3]; tinyobj::real_t avz[3]; tinyobj::real_t anx[3]; tinyobj::real_t any[3]; tinyobj::real_t anz[3]; for (size_t v = 0; v < fv; v++) { tinyobj::index_t idx = obj_shapes[s].mesh.indices[index_offset + v]; avx[v] = obj_attrib.vertices[3 * idx.vertex_index + 0]; avy[v] = obj_attrib.vertices[3 * idx.vertex_index + 1]; avz[v] = obj_attrib.vertices[3 * idx.vertex_index + 2]; anx[v] = obj_attrib.normals[3 * idx.normal_index + 0]; any[v] = obj_attrib.normals[3 * idx.normal_index + 1]; anz[v] = obj_attrib.normals[3 * idx.normal_index + 2]; } tinyobj::material_t obj_material = obj_materials[obj_shapes[s].mesh.material_ids[f]]; material triangle_material = { lambert, { obj_material.diffuse[0], obj_material.diffuse[1], obj_material.diffuse[2] } }; if (materials.find(obj_material.name) != materials.end()) { triangle_material = materials[obj_material.name]; } kd_builder.push_back ( new triangle { {avx[0], avy[0], avz[0]}, {avx[1], avy[1], avz[1]}, {avx[2], avy[2], avz[2]}, {anx[0], any[0], anz[0]}, {anx[1], any[1], anz[1]}, {anx[2], any[2], anz[2]}, triangle_material } ); } else { nuke("Only faces with 3 vertices are supported."); } index_offset += fv; } } scene.push_back(build_kd_tree(kd_builder)); } else if (type == "material") { std::string name = inis(section.first, "name"); material_type type = inim(section.first, "material"); float material_r = inif(section.first, "r"); float material_g = inif(section.first, "g"); float material_b = inif(section.first, "b"); materials[name] = { type, { material_r, material_g, material_b } }; } else { nuke("Unknown type name in scene file."); } } int samples = inii("main", "samples"); if (argc == 3) { samples = atoi(argv[2]); } int x_res = inii("main", "x_res"); int y_res = inii("main", "y_res"); float fov = inif("camera", "fov"); float x_resf = x_res; float y_resf = y_res; float aspect = ( fmax(x_resf, y_resf) / fmin(x_resf, y_resf) ); float fov_adjust_x = tanf(fov * M_PI / 360.0f); float fov_adjust_y = tanf(fov * M_PI / 360.0f); if (x_res > y_resf) { fov_adjust_x *= aspect; } else { fov_adjust_y *= aspect; } unsigned char* frame_buffer = (unsigned char*)malloc(x_res * y_res * 3 * sizeof(unsigned char)); if (!frame_buffer) { nuke("Could not allocate a frame buffer (malloc)."); } glm::vec3 ray_o = { inif("camera", "x"), inif("camera", "y"), inif("camera", "z") }; #pragma omp parallel for schedule(dynamic) for (int j = 0; j < y_res; j++) { for (int i = 0; i < x_res; i++) { unsigned char* pixel = frame_buffer + (j * x_res + i) * 3; glm::vec3 color = {0.0f, 0.0f, 0.0f}; for (int k = 0; k < samples; k++) { glm::vec3 ray_d = { (0.0f + ((i + rand00(seed)) / x_resf) * 2.0f - 1.0f) * fov_adjust_x, (1.0f - ((j + rand00(seed)) / y_resf) * 2.0f + 0.0f) * fov_adjust_y, -1.0f }; color += path_trace(ray_o, ray_d); } color /= samples; pixel[R] = fmax(0.0f, fmin(255.0f, powf(color.r, gamma) * 255.0f)); pixel[G] = fmax(0.0f, fmin(255.0f, powf(color.g, gamma) * 255.0f)); pixel[B] = fmax(0.0f, fmin(255.0f, powf(color.b, gamma) * 255.0f)); } std::cout << "Row " << j + 1 << "/" << y_res << std::string(32, ' ') << "\r" << std::flush; } if (!stbi_write_png("sterling.png", x_res, y_res, 3, frame_buffer, x_res * 3)) { nuke("Could not save a frame buffer (stbi_write_png)."); } exit(EXIT_SUCCESS); }
fdb33a150e134c661d263984ffd9c7a849613237
d81b46a966b5a59d78082e071996baa965fe2b48
/cpp/smart_pointers/sample_ptrs.cpp
73199f0bf28b2effcd12e52d4de5e745353fbbd7
[]
no_license
deepakreddy63/Code
c914b2b0c95234dbdeb4ffb257c73fbdefbe034d
6b859a07dd7f32f82e008a811b03f57e6d1e9714
refs/heads/master
2020-09-27T21:19:16.752456
2020-05-27T00:39:02
2020-05-27T00:39:02
226,612,032
0
0
null
null
null
null
UTF-8
C++
false
false
5,459
cpp
//testing the basic concepts of smart pointers namely //unique_ptr, shared_ptr and weak_ptr in seperate sections #include<iostream> #include<memory> class Sample { int x; int y; public: Sample()=default; Sample(int p,int q):x(p),y(q) { } void printxy() const { std::cout << x << "," << y << "\n"; } ~Sample() { std::cout << "Sample--destr\n"; } }; void test_weak_ptr(std::weak_ptr<Sample>& wp) { std::cout << "test--wp.expired?: " << wp.expired() << std::endl; if( std::shared_ptr<Sample> stemp = wp.lock() ) { std::cout << "Test--weak pointer is alive\n"; std::cout << "stemp.use_count(): " << stemp.use_count() << std::endl; stemp->printxy(); } else{ std::cout << "Test -- Weak pointer got expired\n"; //stemp->printxy(); //run time exception } }; std::weak_ptr<Sample> wp1; void bar(std::shared_ptr<Sample>& sptr) { std::shared_ptr<Sample> stemp(sptr); test_weak_ptr(wp1); //3 } void foo() { std::shared_ptr<Sample> sp=std::make_shared<Sample>(10,20); test_weak_ptr(wp1); //2 bar(sp); test_weak_ptr(wp1); //4 } int main(){ //Section for unique pointers /* std::unique_ptr<Sample> p1(new Sample(10, 20)); p1->printxy(); //std::unique_ptr<Sample> p2(ps); //error,copy semantics are disabled std::unique_ptr<Sample> p2(std::move(p1)); std::unique_ptr<Sample> p3; p3 = std::unique_ptr<Sample>(new Sample(15, 18)); std::unique_ptr<Sample> p4; //p4=p3; //error //get member gives access to a raw pointer for an underlying object (if any) std::cout << p1.get() << "\n"; std::cout << p2.get() << "\n"; //reset can change an underlying object, i.e. release the old object and attach a new object std::unique_ptr<Sample> ps(new Sample(10, 20)); ps->printxy(); ps.reset(new Sample(11,21)); //previous object got deleted std::cout << ps.get() << "\n"; ps->printxy(); //operator==, operator!=, operator bool are available for comparison (null check of course) p1.reset(new Sample(10, 20)); p2.reset(); if(p1!=nullptr) //if(p1) also works p1->printxy(); if(p2==nullptr) //if(!p2) also works std::cout << "p2 has already released memory"; //Also, the usage of make_unique guarantees that it'll wrap to a new object only and //also avoids dangerous heap problems as a resultant of wrapping raw pointers std::unique_ptr<Sample> p5=std::make_unique<Sample>(10,20); //Array of Objects std::unique_ptr<Sample[]> sparr(new Sample[10]); std::cout << sparr.get() << "\n"; for(int i=0;i<10;i++) sparr[i].printxy(); //TODO: ensure all the objects are released // using valgrind or dummy print in destructor std::unique_ptr<int[]> parr(new int[10]); for(int i=0;i<10;i++) parr[i]=10*i; */ ////////////////////////////////////////////////////////////////////////////////////////////// /* //Section for shared pointer std::shared_ptr<Sample> p1(new Sample(10,20)); std::cout << p1.use_count() << "\n"; std::shared_ptr<Sample> p2(p1); std::cout << p1.use_count() << "\n"; std::cout << p2.use_count() << "\n"; std::shared_ptr<Sample> p3(p1); std::cout << p3.use_count() << "\n"; std::cout << p1.use_count() << "\n"; std::cout << p1.get() << "," << p2.get() << "," << p3.get() << "\n"; p2.reset(); //p2=nullptr std::cout << p1.use_count() << "\n"; //object will be release when p1,p2,p3,ptr goes out of scope //Another Example to observe reference count as per the scope of shared pointers std::shared_ptr<int> p4(new int()); std::cout <<"\n" << p4.use_count() << "\n"; { std::shared_ptr<int> p5(p4); std::cout << p4.use_count() << "\n"; { std::shared_ptr<int> p6(p5); std::cout << p5.use_count() << "\n"; } std::cout << p5.use_count() << "\n"; p5.reset(); // p5=nullptr; std::cout << p4.use_count() << "\n"; } std::cout << p4.use_count() << "\n"; //As discussed during a unique pointer, wrapping raw pointers into a shared pointer also lead to dangerous situations. //So always directly wrap the objects created by the new operator or usage of make_shared is highly recommended. std::shared_ptr<Sample> sp=std::make_shared<Sample>(10,20); */ ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //Section for weak pointer //Weak pointers hold a non-owning reference to an object managed by another shared pointer //Weak pointers doesn't participate in reference counting //Weak pointers need to be converted into a shared pointer to access underlying objects. //Weak pointer may live beyond the life time of a managed object, but is considered as expired and can't access an underlying object std::shared_ptr<Sample> sp=std::make_shared<Sample>(10,20); std::weak_ptr<Sample> wp=sp; std::cout << "weak ptr use_count: " << wp.use_count() << std::endl; std::cout << "shared ptr use_count: " << sp.use_count() << std::endl; test_weak_ptr(wp); sp.reset(); //managed object is released test_weak_ptr(wp); test_weak_ptr(wp1); //1 foo(); test_weak_ptr(wp1); //5 return 0; }
c45ced92c3a92b1e8715417dee9c037db1bff26e
b61c61a15c1db4401ffa6ab3107188a5b8eb6dae
/GH Injector Library/Symbol Parser.cpp
6f7c416c70fbe683179e024800ff47dca6f19bcf
[]
no_license
Lilith2/GH-Injector-Library
6a1726677adb5da5dfede05476b26ab36ab28e9f
edfaf22ddd8f7f24a0147823f163f0af1fc7b841
refs/heads/master
2023-05-09T01:21:19.452419
2021-05-24T08:22:12
2021-05-24T08:22:12
null
0
0
null
null
null
null
UTF-8
C++
false
false
14,222
cpp
#include "pch.h" #include "Symbol Parser.h" SYMBOL_PARSER::SYMBOL_PARSER() { m_Initialized = false; m_Ready = false; m_SymbolTable = 0; m_hPdbFile = nullptr; m_hProcess = nullptr; m_bInterruptEvent = false; m_hInterruptEvent = CreateEvent(nullptr, TRUE, FALSE, nullptr); m_fProgress = 0.0f; m_bStartDownload = false; } SYMBOL_PARSER::~SYMBOL_PARSER() { if (m_hInterruptEvent) { CloseHandle(m_hInterruptEvent); } if (m_Initialized) { if (m_SymbolTable) { SymUnloadModule64(m_hProcess, m_SymbolTable); } SymCleanup(m_hProcess); } if (m_hProcess) { CloseHandle(m_hProcess); } if (m_hPdbFile) { CloseHandle(m_hPdbFile); } } bool SYMBOL_PARSER::VerifyExistingPdb(const GUID & guid) { LOG(" SYMBOL_PARSER::VerifyExistingPdb called\n"); std::ifstream f(m_szPdbPath.c_str(), std::ios::binary | std::ios::ate); if (f.bad()) { LOG(" Symbol Parser: failed to open PDB for verification\n"); return false; } size_t size_on_disk = static_cast<size_t>(f.tellg()); if (!size_on_disk) { f.close(); LOG(" Symbol Parser: invaild file size\n"); return false; } char * pdb_raw = new char[size_on_disk]; if (!pdb_raw) { f.close(); LOG(" Symbol Parser: failed to allocate memory\n"); return false; } f.seekg(std::ios::beg); f.read(pdb_raw, size_on_disk); f.close(); LOG(" Symbol Parser: PDB loaded into memory\n"); if (size_on_disk < sizeof(PDBHeader7)) { delete[] pdb_raw; LOG(" Symbol Parser: raw size smaller than PDBHeader7\n"); return false; } auto * pPDBHeader = ReCa<PDBHeader7*>(pdb_raw); if (memcmp(pPDBHeader->signature, "Microsoft C/C++ MSF 7.00\r\n\x1A""DS\0\0\0", sizeof(PDBHeader7::signature))) { delete[] pdb_raw; LOG(" Symbol Parser: PDB signature mismatch\n"); return false; } if (size_on_disk < (size_t)pPDBHeader->page_size * pPDBHeader->file_page_count) { delete[] pdb_raw; LOG(" Symbol Parser: PDB size smaller than page_size * page_count\n"); return false; } LOG(" Symbol Parser: PDB size validated\n"); int * pRootPageNumber = ReCa<int*>(pdb_raw + (size_t)pPDBHeader->root_stream_page_number_list_number * pPDBHeader->page_size); auto * pRootStream = ReCa<RootStream7*>(pdb_raw + (size_t)(*pRootPageNumber) * pPDBHeader->page_size); std::map<int, std::vector<int>> streams; int current_page_number = 0; for (int i = 0; i != pRootStream->num_streams; ++i) { int current_size = pRootStream->stream_sizes[i] == 0xFFFFFFFF ? 0 : pRootStream->stream_sizes[i]; int current_page_count = current_size / pPDBHeader->page_size; if (current_size % pPDBHeader->page_size) { ++current_page_count; } std::vector<int> numbers; for (int j = 0; j != current_page_count; ++j, ++current_page_number) { numbers.push_back(pRootStream->stream_sizes[pRootStream->num_streams + current_page_number]); } streams.insert({ i, numbers }); } LOG(" Symbol Parser: PDB size parsed\n"); auto pdb_info_page_index = streams.at(1).at(0); auto * stream_data = ReCa<GUID_StreamData*>(pdb_raw + (size_t)(pdb_info_page_index) * pPDBHeader->page_size); int guid_eq = memcmp(&stream_data->guid, &guid, sizeof(GUID)); delete[] pdb_raw; auto ret = (guid_eq == 0); if (ret) { LOG(" Symbol Parser: guid match\n"); } else { LOG(" Symbol Parser: guid mismatch\n"); } return ret; } DWORD SYMBOL_PARSER::Initialize(const std::wstring szModulePath, const std::wstring path, std::wstring * pdb_path_out, bool Redownload, bool WaitForConnection, bool AutoDownload) { if (AutoDownload) { m_bStartDownload = true; } else { m_bStartDownload = false; } LOG("SYMBOL_PARSER::Initialize called in thread %08X (%d)\n", GetCurrentThreadId(), GetCurrentThreadId()); if (m_Ready) { LOG(" Symbol Parser: already initialized\n"); return SYMBOL_ERR_SUCCESS; } std::ifstream File(szModulePath.c_str(), std::ios::binary | std::ios::ate); if (!File.good()) { LOG(" Symbol Parser: can't open module path\n"); return SYMBOL_ERR_CANT_OPEN_MODULE; } auto FileSize = File.tellg(); if (!FileSize) { LOG(" Symbol Parser: invalid file size\n"); return SYMBOL_ERR_FILE_SIZE_IS_NULL; } BYTE * pRawData = new BYTE[static_cast<size_t>(FileSize)]; if (!pRawData) { delete[] pRawData; File.close(); LOG(" Symbol Parser: can't allocate memory\n"); return SYMBOL_ERR_CANT_ALLOC_MEMORY_NEW; } File.seekg(0, std::ios::beg); File.read(ReCa<char*>(pRawData), FileSize); File.close(); LOG(" Symbol Parser: ready to parse PE headers\n"); IMAGE_DOS_HEADER * pDos = ReCa<IMAGE_DOS_HEADER*>(pRawData); IMAGE_NT_HEADERS * pNT = ReCa<IMAGE_NT_HEADERS*>(pRawData + pDos->e_lfanew); IMAGE_FILE_HEADER * pFile = &pNT->FileHeader; IMAGE_OPTIONAL_HEADER64 * pOpt64 = nullptr; IMAGE_OPTIONAL_HEADER32 * pOpt32 = nullptr; bool x86 = false; if (pFile->Machine == IMAGE_FILE_MACHINE_AMD64) { pOpt64 = ReCa<IMAGE_OPTIONAL_HEADER64*>(&pNT->OptionalHeader); LOG(" Symbol Parser: x64 target identified\n"); } else if (pFile->Machine == IMAGE_FILE_MACHINE_I386) { pOpt32 = ReCa<IMAGE_OPTIONAL_HEADER32*>(&pNT->OptionalHeader); x86 = true; LOG(" Symbol Parser: x86 target identified\n"); } else { delete[] pRawData; LOG(" Symbol Parser: invalid file architecture\n"); return SYMBOL_ERR_INVALID_FILE_ARCHITECTURE; } DWORD ImageSize = x86 ? pOpt32->SizeOfImage : pOpt64->SizeOfImage; BYTE * pLocalImageBase = ReCa<BYTE*>(VirtualAlloc(nullptr, ImageSize, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE)); if (!pLocalImageBase) { delete[] pRawData; LOG(" Symbol Parser: can't allocate memory: 0x%08X\n", GetLastError()); return SYMBOL_ERR_CANT_ALLOC_MEMORY; } memcpy(pLocalImageBase, pRawData, x86 ? pOpt32->SizeOfHeaders : pOpt64->SizeOfHeaders); auto * pCurrentSectionHeader = IMAGE_FIRST_SECTION(pNT); for (UINT i = 0; i != pFile->NumberOfSections; ++i, ++pCurrentSectionHeader) { if (pCurrentSectionHeader->SizeOfRawData) { memcpy(pLocalImageBase + pCurrentSectionHeader->VirtualAddress, pRawData + pCurrentSectionHeader->PointerToRawData, pCurrentSectionHeader->SizeOfRawData); } } LOG(" Symbol Parser: sections mapped\n"); IMAGE_DATA_DIRECTORY * pDataDir = nullptr; if (x86) { pDataDir = &pOpt32->DataDirectory[IMAGE_DIRECTORY_ENTRY_DEBUG]; } else { pDataDir = &pOpt64->DataDirectory[IMAGE_DIRECTORY_ENTRY_DEBUG]; } IMAGE_DEBUG_DIRECTORY * pDebugDir = ReCa<IMAGE_DEBUG_DIRECTORY*>(pLocalImageBase + pDataDir->VirtualAddress); if (!pDataDir->Size || IMAGE_DEBUG_TYPE_CODEVIEW != pDebugDir->Type) { VirtualFree(pLocalImageBase, 0, MEM_RELEASE); delete[] pRawData; LOG(" Symbol Parser: no PDB debug data\n"); return SYMBOL_ERR_NO_PDB_DEBUG_DATA; } PdbInfo * pdb_info = ReCa<PdbInfo*>(pLocalImageBase + pDebugDir->AddressOfRawData); if (pdb_info->Signature != 0x53445352) { VirtualFree(pLocalImageBase, 0, MEM_RELEASE); delete[] pRawData; LOG(" Symbol Parser: invalid PDB signature\n"); return SYMBOL_ERR_NO_PDB_DEBUG_DATA; } m_szPdbPath = path; if (m_szPdbPath[m_szPdbPath.length() - 1] != '\\') { m_szPdbPath += '\\'; } LOG(" Symbol Parser: PDB signature identified\n"); if (!CreateDirectoryW(m_szPdbPath.c_str(), nullptr)) { if (GetLastError() != ERROR_ALREADY_EXISTS) { LOG(" Symbol Parser: can't create/open download path: 0x%08X\n", GetLastError()); return SYMBOL_ERR_PATH_DOESNT_EXIST; } } m_szPdbPath += x86 ? L"x86\\" : L"x64\\"; if (!CreateDirectoryW(m_szPdbPath.c_str(), nullptr)) { if (GetLastError() != ERROR_ALREADY_EXISTS) { LOG(" Symbol Parser: can't create/open download path: 0x%08X\n", GetLastError()); return SYMBOL_ERR_CANT_CREATE_DIRECTORY; } } std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>> conv; std::wstring szPdbFileName(conv.from_bytes(pdb_info->PdbFileName)); m_szPdbPath += szPdbFileName; LOG(" Symbol Parser: PDB path = %ls\n", m_szPdbPath.c_str()); DWORD Filesize = 0; WIN32_FILE_ATTRIBUTE_DATA file_attr_data{ 0 }; if (GetFileAttributesExW(m_szPdbPath.c_str(), GetFileExInfoStandard, &file_attr_data)) { Filesize = file_attr_data.nFileSizeLow; if (!Redownload && !VerifyExistingPdb(pdb_info->Guid)) { LOG(" Symbol Parser: verification failed, PDB will be redownloaded\n"); Redownload = true; } if (Redownload) { DeleteFileW(m_szPdbPath.c_str()); } } else { LOG(" Symbol Parser: file doesn't exist, PDB will be downloaded\n"); Redownload = true; } if (Redownload) { wchar_t w_GUID[100]{ 0 }; if (!StringFromGUID2(pdb_info->Guid, w_GUID, 100)) { VirtualFree(pLocalImageBase, 0, MEM_RELEASE); delete[] pRawData; LOG(" Symbol Parser: failed to parse GUID"); return SYMBOL_ERR_CANT_CONVERT_PDB_GUID; } LOG(" Symbol Parser: GUID = %ls\n", w_GUID); std::wstring guid_filtered; for (UINT i = 0; w_GUID[i]; ++i) { if ((w_GUID[i] >= '0' && w_GUID[i] <= '9') || (w_GUID[i] >= 'A' && w_GUID[i] <= 'F') || (w_GUID[i] >= 'a' && w_GUID[i] <= 'f')) { guid_filtered += w_GUID[i]; } } std::wstring url = L"https://msdl.microsoft.com/download/symbols/"; url += szPdbFileName; url += '/'; url += guid_filtered; url += std::to_wstring(pdb_info->Age); url += '/'; url += szPdbFileName; LOG(" Symbol Parser: URL = %ls\n", url.c_str()); if (WaitForConnection) { LOG(" Symbol Parser: checking internet connection\n"); while (InternetCheckConnectionW(L"https://msdl.microsoft.com", FLAG_ICC_FORCE_CONNECTION, NULL) == FALSE) { Sleep(25); if (m_bInterruptEvent) { VirtualFree(pLocalImageBase, 0, MEM_RELEASE); delete[] pRawData; LOG(" Symbol Parser: interrupt event triggered\n"); return SYMBOL_ERR_INTERRUPT; } } LOG(" Symbol Parser: connection verified\n"); } wchar_t szCacheFile[MAX_PATH]{ 0 }; if (m_hInterruptEvent) { m_DlMgr.SetInterruptEvent(m_hInterruptEvent); } if (!m_bStartDownload) { LOG(" Symbol Parser: waiting for download start\n"); } while (!m_bStartDownload && !m_bInterruptEvent) { std::this_thread::sleep_for(std::chrono::milliseconds(10)); } if (m_bInterruptEvent) { VirtualFree(pLocalImageBase, 0, MEM_RELEASE); delete[] pRawData; LOG(" Symbol Parser: download interrupted\n"); return SYMBOL_ERR_INTERRUPT; } LOG(" Symbol Parser: downloading PDB\n"); auto hr = URLDownloadToCacheFileW(nullptr, url.c_str(), szCacheFile, sizeof(szCacheFile) / sizeof(szCacheFile[0]), NULL, &m_DlMgr); if (FAILED(hr)) { VirtualFree(pLocalImageBase, 0, MEM_RELEASE); delete[] pRawData; LOG(" Symbol Parser: failed to download file: 0x%08X\n", hr); return SYMBOL_ERR_DOWNLOAD_FAILED; } LOG(" Symbol Parser: download finished\n"); if (!CopyFileW(szCacheFile, m_szPdbPath.c_str(), FALSE)) { VirtualFree(pLocalImageBase, 0, MEM_RELEASE); delete[] pRawData; LOG(" Symbol Parser: failed to copy file into working directory: 0x%08X\n", GetLastError()); return SYMBOL_ERR_COPYFILE_FAILED; } DeleteFileW(szCacheFile); } m_fProgress = 1.0f; VirtualFree(pLocalImageBase, 0, MEM_RELEASE); delete[] pRawData; LOG(" Symbol Parser: PDB verified\n"); if (!Filesize) { if (!GetFileAttributesExW(m_szPdbPath.c_str(), GetFileExInfoStandard, &file_attr_data)) { LOG(" Symbol Parser: can't access PDB file: 0x%08X\n", GetLastError()); return SYMBOL_ERR_CANT_ACCESS_PDB_FILE; } Filesize = file_attr_data.nFileSizeLow; } m_hPdbFile = CreateFileW(m_szPdbPath.c_str(), GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, NULL, nullptr); if (m_hPdbFile == INVALID_HANDLE_VALUE) { LOG(" Symbol Parser: can't open PDB file: 0x%08X\n", GetLastError()); return SYMBOL_ERR_CANT_OPEN_PDB_FILE; } m_hProcess = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, GetCurrentProcessId()); if (!m_hProcess) { CloseHandle(m_hPdbFile); LOG(" Symbol Parser: can't open current process: 0x%08X\n", GetLastError()); return SYMBOL_ERR_CANT_OPEN_PROCESS; } if (!SymInitializeW(m_hProcess, m_szPdbPath.c_str(), FALSE)) { CloseHandle(m_hProcess); CloseHandle(m_hPdbFile); LOG(" Symbol Parser: SymInitializeW failed: 0x%08X\n", GetLastError()); return SYMBOL_ERR_SYM_INIT_FAIL; } m_Initialized = true; SymSetOptions(SYMOPT_UNDNAME | SYMOPT_DEFERRED_LOADS | SYMOPT_AUTO_PUBLICS); m_SymbolTable = SymLoadModuleExW(m_hProcess, nullptr, m_szPdbPath.c_str(), nullptr, 0x10000000, Filesize, nullptr, NULL); if (!m_SymbolTable) { SymCleanup(m_hProcess); CloseHandle(m_hProcess); CloseHandle(m_hPdbFile); LOG(" Symbol Parser: SymLoadModuleExW failed: 0x%08X\n", GetLastError()); return SYMBOL_ERR_SYM_LOAD_TABLE; } if (pdb_path_out) { *pdb_path_out = m_szPdbPath; } m_Ready = true; LOG(" Symbol Parser: initialization finished\n"); return SYMBOL_ERR_SUCCESS; } DWORD SYMBOL_PARSER::GetSymbolAddress(const char * szSymbolName, DWORD & RvaOut) { if (!m_Ready) { LOG(" Symbol Parser: not ready\n"); return SYMBOL_ERR_NOT_INITIALIZED; } if (!szSymbolName) { LOG(" Symbol Parser: invalid symbol name\n"); return SYMBOL_ERR_IVNALID_SYMBOL_NAME; } SYMBOL_INFO si{ 0 }; si.SizeOfStruct = sizeof(SYMBOL_INFO); if (!SymFromName(m_hProcess, szSymbolName, &si)) { LOG(" Symbol Parser: search failed: 0x%08X\n", GetLastError()); return SYMBOL_ERR_SYMBOL_SEARCH_FAILED; } RvaOut = (DWORD)(si.Address - si.ModBase); LOG(" Symbol Parser: RVA %08X -> %s\n", RvaOut, szSymbolName); return SYMBOL_ERR_SUCCESS; } void SYMBOL_PARSER::SetDownload(bool bDownload) { m_bStartDownload = bDownload; } void SYMBOL_PARSER::Interrupt() { LOG("Symbol Parser: Interrupt\n"); m_bInterruptEvent = true; if (m_hInterruptEvent) { if (!SetEvent(m_hInterruptEvent)) { LOG(" Symbol Parser: SetEvent failed to trigger interrupt event: %08X\n", GetLastError()); } else { LOG(" Symbol Parser: interrupt event set\n"); } } else { LOG(" Symbol Parser: no interrupt event specified\n"); } m_Initialized = false; m_Ready = false; } float SYMBOL_PARSER::GetDownloadProgress() { if (m_fProgress == 1.0f) { return m_fProgress; } return m_DlMgr.GetDownloadProgress(); }
7dc9af251a6dc4ae88e8d082cce58ba3710570fa
30cd97813401ec554734121f47216b87dff0dbc6
/lab3/JAApp/JAApp.cpp
39c672923d83a1c86469f58897ae8f6829d3d336
[]
no_license
rzepkamichal/assembly
2c4f213870f81989270c90074d87a110fcf0d591
9f780b2e81d954ecac98b1a81277f0b9915c607b
refs/heads/master
2020-04-28T22:33:24.615205
2019-03-29T14:28:58
2019-03-29T14:28:58
175,621,810
0
0
null
null
null
null
UTF-8
C++
false
false
1,305
cpp
// JAApp.cpp : This file contains the 'main' function. Program execution begins and ends there. // #include "pch.h" #include "JAApp.h" using namespace std; int main() { // definicja ciagu znakow char szString[] = { 'A','G','I','K','S','Z','J', 0xFF }; //printf("FindChar_1 %s\n", (FindChar_1() == 1 ? "Found J" : "Not Found J")); printf("FindChar_2 %s\n", (FindChar_2() == 1 ? "Found J" : "Not Found J")); /*printf("FindChar_3 %s\n", (FindChar_3(szString) ? "Found J" : "Not Found J")); printf("FindChar_4 %s\n", (FindChar_4() == 1 ? "Found J" : "Not Found J")); printf("FindChar_5 %s\n", (FindChar_5() == 1 ? "Found J" : "Not Found J")); printf("FindChar_6 %s\n", (FindChar_6() == 1 ? "Found J" : "Not Found J")); printf("Czas przetwarzania: %i\n", ReadTime_1()); printf("Czas przetwarzania: %i\n", ReadTime_1()); printf("Czas przetwarzania: %i\n", ReadTime_1()); printf("Czas przetwarzania: %i\n", ReadTime_1()); printf("Czas przetwarzania: %i\n", ReadTime_1());*/ MessageBox(NULL, L"Wyciągnij wnioski", L"Lab. 2", MB_OK); /* //call MyProc1 int x = 9, y = 5, z = 0; z = MyProc1(x, y); cout << z << endl; //dynamicly call MyProc2 HINSTANCE lib = LoadLibraryA("JADll"); int(_stdcall *MyProc2)(void) = (int(_stdcall*)(void))GetProcAddress(lib, "MyProc2"); MyProc2(); */ }
3fb5fe5c180cb154ef0c683bb8f18c7df242c75c
e60ca08722245d732f86701cf28b581ac5eeb737
/xbmc/storage/linux/HALProvider.h
4f27aae27e3ff9a440be1fead167e722eca60124
[]
no_license
paulopina21/plxJukebox-11
6d915e60b3890ce01bc8a9e560342c982f32fbc7
193996ac99b99badab3a1d422806942afca2ad01
refs/heads/master
2020-04-09T13:31:35.220058
2013-02-06T17:31:23
2013-02-06T17:31:23
8,056,228
1
1
null
null
null
null
UTF-8
C++
false
false
567
h
#pragma once #include "storage/IStorageProvider.h" #ifdef HAS_HAL class CHALProvider : public IStorageProvider { public: CHALProvider(); virtual ~CHALProvider() { } virtual void Initialize(); virtual void Stop(); virtual void GetLocalDrives(VECSOURCES &localDrives); virtual void GetRemovableDrives(VECSOURCES &removableDrives); virtual bool Eject(CStdString mountpath); virtual std::vector<CStdString> GetDiskUsage(); virtual bool PumpDriveChangeEvents(IStorageEventsCallback *callback); private: unsigned int m_removableLength; }; #endif
0f678393c02595e1fbb4e02d00279cf336b45421
11c8396c967b201d4cdbce07e3603207ca279ee7
/Messaging/SerializeManager.cpp
f3fb844f0fbe0062ee3f85c7c3b78c512ffc6dd7
[ "MIT" ]
permissive
Vaufreyd/Omiscid
d5c5ba284d4e46bed013db6d4b003ff00d43580d
4963abf07554c775d163f6878bda719ff7dc4f95
refs/heads/master
2021-01-17T14:22:48.710812
2017-02-16T10:26:35
2017-02-16T10:26:35
47,427,293
0
0
null
null
null
null
UTF-8
C++
false
false
80
cpp
#include <Messaging/SerializeManager.h> // Nothing using namespace Omiscid;
1a2f6a1f4b27ec54e9229a5e92ac1c5f68187348
493c887bb4961ddc600cb6e2aa9debe85890af8b
/Archivator/test/FolderSnapshotTest/Tests/TestExtensionFilter4/InitialDir/ComplexDataStructures/Graphs/EdgeWeighted/EdgeWeightedGraphs/LazyPrimMST.h
d8d23cb679aec2cab18e33cc0789e644cbf85873
[]
no_license
dendibakh/Misc
2d5549bcd180502da11b7b2233863c8adddd3719
ca2c09f9c4726368680b4cf2e4c8944e60da23a4
refs/heads/master
2016-09-05T23:02:40.433839
2015-12-30T14:22:00
2015-12-30T14:22:00
37,809,642
0
0
null
null
null
null
UTF-8
C++
false
false
452
h
#pragma once #include "EWGraph.h" #include <list> #include <queue> #include <functional> class LazyPrimMST { void visitVertex(int v); public: typedef std::list<Edge> MSTEdgesContainer; LazyPrimMST(const EWGraph& graph); MSTEdgesContainer edges(); double getWeight(); private: MSTEdgesContainer MSTEdges; double weight; const EWGraph& graph; std::priority_queue<Edge, std::vector<Edge>, std::greater<Edge>> minPQ; std::vector<bool> marked; };
e0558ce8b04eebb59a0c132ddcc9715d1e5a24f5
dcf3b364645a1c6ce9c0ac17bfa3f1a4c7b9b7ae
/client/frameworks/runtime-src/Classes/ecs/utils/physics/GShape.h
a43fb9039a2b219e9046f463f5d6677dd16c1dec
[]
no_license
cu8Fsuz/Kurumi
73235466850f66461b82ca362d00a087fdaf9baf
aaa3e4fca3205686bbb5b02662dffac6d6f0d1c8
refs/heads/master
2023-07-24T14:01:47.828798
2021-09-01T03:41:04
2021-09-01T03:41:04
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,253
h
#pragma once #include "foundation/math/GMath.h" #include "cocos2d.h" USING_NS_CC; #define MaxPolyVertexCount 64 /// GShape class GShape { public: enum Type { eCircle, ePoly, eCount }; GShape() {} virtual void setRotation(real radians) = 0; virtual Type getType(void) const = 0; virtual void debugDraw(DrawNode* drawNode) = 0; class BodyComponent* body; }; /// GCircle class GCircle : public GShape { public: GCircle(real r); virtual void setRotation(real radians)override; virtual void debugDraw(DrawNode* drawNode)override; virtual Type getType(void) const override; // 半径 real radius; }; /// GPolygonShape class GPolygonShape : public GShape { public: GPolygonShape(); virtual ~GPolygonShape(); virtual void setRotation(real radians)override; virtual void debugDraw(DrawNode* drawNode)override; virtual Type getType(void) const override; // Half width and half height void setBox(real hw, real hh); void set(GVec2 *vertices, uint32_t count); // The extreme point along a direction within a polygon GVec2 GetSupport(const GVec2& dir); uint32_t m_vertexCount; GVec2 m_vertices[MaxPolyVertexCount]; GVec2 m_normals[MaxPolyVertexCount]; GMat2 u; // Orientation matrix from model to world };
9207b61ad871b69ed30b08f5480f67f49acbdbf5
a3cfa15bb37482f9a68d79ace530d94790b66883
/project/Common/Utility/CommonSocket.h
9aa7cb9121c30a92e288897e8e0fb2401035ba08
[]
no_license
shenyanjun/GameProject
3043c9137f8a3bc568ca4fc595b18168e1a0412e
a891c9a8ad231573ddbdbf8f646ada7a8fc883c5
refs/heads/master
2021-01-18T18:22:58.484682
2014-07-16T11:39:35
2014-07-16T11:39:35
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,254
h
#ifndef __COMMON_SOCKET__ #define __COMMON_SOCKET__ #define SOCKET_ERROR (-1) namespace CommonSocket { //设置套接字为可重用状态 bool SetSocketReuseable(SOCKET hSocket); //设置套接字为非阻塞状态 bool SetSocketUnblock(SOCKET hSocket); //设置套接字为阻塞状态 bool SetSocketBlock(SOCKET hSocket); bool SetSocketNoDelay(SOCKET hSocket); //初始化网络 bool InitNetwork(); //反初始化网络 bool UninitNetwork(); SOCKET CreateSocket( int af, int type, int protocol); BOOL BindSocket( SOCKET hSocket, const struct sockaddr *pAddr, int nNamelen); BOOL ListenSocket( SOCKET hSocket, int nBacklog); BOOL ConnectSocket(SOCKET hSocket, const char *pAddr, short sPort); INT32 GetSocketLastError(); BOOL IsSocketValid(SOCKET hSocket); //关闭套接字 void ShutDownSend(SOCKET hSocket); void ShutDownRecv(SOCKET hSocket); //关闭套接字 void CloseSocket(SOCKET hSocket); std::string GetLastErrorStr(INT32 nError); UINT32 IpAddrStrToInt(CHAR *pszIpAddr); std::string IpAddrIntToStr(UINT32 dwIpAddr); #ifdef WIN32 BOOL ConnectSocketEx(SOCKET hSocket, const char *pAddr, short sPort, LPOVERLAPPED lpOverlapped); #endif } #endif /* __COMMON_SOCKET__*/
0af70e7a9b2342887fa7b15f687cf75b563ba4ba
e9a3755b1cc7574ed9029782e994a6c9ab305716
/OpenGLtest/OpenGLtestDoc.h
e7b264d2cbad89df9148a090f4fa8783bfc4f97d
[]
no_license
soominnn/OpenGL_HomeWork
dfb451671248e00b8757317e25e2ef495a722675
9afe4888854fed197d1f58b4932a0ccdf31988db
refs/heads/master
2023-09-05T07:31:44.752378
2021-11-03T01:28:30
2021-11-03T01:28:30
424,052,581
0
0
null
null
null
null
UTF-8
C++
false
false
977
h
 // OpenGLtestDoc.h: COpenGLtestDoc 클래스의 인터페이스 // #pragma once class COpenGLtestDoc : public CDocument { protected: // serialization에서만 만들어집니다. COpenGLtestDoc() noexcept; DECLARE_DYNCREATE(COpenGLtestDoc) // 특성입니다. public: // 작업입니다. public: // 재정의입니다. public: virtual BOOL OnNewDocument(); virtual void Serialize(CArchive& ar); #ifdef SHARED_HANDLERS virtual void InitializeSearchContent(); virtual void OnDrawThumbnail(CDC& dc, LPRECT lprcBounds); #endif // SHARED_HANDLERS // 구현입니다. public: virtual ~COpenGLtestDoc(); #ifdef _DEBUG virtual void AssertValid() const; virtual void Dump(CDumpContext& dc) const; #endif protected: // 생성된 메시지 맵 함수 protected: DECLARE_MESSAGE_MAP() #ifdef SHARED_HANDLERS // 검색 처리기에 대한 검색 콘텐츠를 설정하는 도우미 함수 void SetSearchContent(const CString& value); #endif // SHARED_HANDLERS };
62e2ae10fdbefb5725232ced6ec7ed6074c565da
66ed370c2dd95b8f80ed0e6bc5fdd99dfaa3526c
/reactor/EventLoop.cc
8029d9907a4955c6d31500a4362e8fe3692c161b
[]
no_license
GeneralStudy/studymuduo
2177f7c210c7e905758de9d4fc5488142ed43143
0b660b4c6ae211059bb0565a37835a0d33b56c8c
refs/heads/master
2020-03-09T21:44:21.729977
2018-05-06T07:39:52
2018-05-06T07:39:52
129,017,074
0
0
null
null
null
null
UTF-8
C++
false
false
2,278
cc
#include "EventLoop.h" #include "Channel.h" #include "Poller.h" #include "TimerQueue.h" #include "../logging/Logging.h" #include <assert.h> //#include <poll.h> using namespace muduo; __thread EventLoop* t_loopInThisThread = 0; const int kPollTimeMs = 10000; EventLoop::EventLoop(): m_looping(false), m_quit(false), m_threadId(CurrentThread::tid()), m_poller(new Poller(this)), m_timerQueue(new TimerQueue(this)) { LOG_TRACE << "EventLoop created" << this << " in thread " << m_threadId; if (t_loopInThisThread) { LOG_FATAL << "Another EventLoop " << t_loopInThisThread << " exists in this thread" << m_threadId; } else { t_loopInThisThread = this; } } EventLoop::~EventLoop() { assert(!m_looping); t_loopInThisThread = NULL; } void EventLoop::loop() { assert(!m_looping); assertInLoopThread(); m_looping = true; m_quit = false; while (!m_quit) { m_activeChannel.clear(); m_pollReturnTime = m_poller->poll(kPollTimeMs, &m_activeChannel); for (ChannelList::iterator it = m_activeChannel.begin(); it != m_activeChannel.end(); ++it) { (*it)->handleEvent(); } } LOG_TRACE << "EventLoop " << this << " stop looping"; m_looping = false; } void EventLoop::quit() { m_quit = true; } void EventLoop::updateChannel(Channel* channel) { assert(channel->ownerLoop() == this); assertInLoopThread(); m_poller->updateChannel(channel); } void EventLoop::abortNotInLoopTread() { LOG_FATAL << "EventLoop::abortNotInLoopThread - EventLoop " << this << " was created in threadId = " << m_threadId << ", current thread id = " << CurrentThread::tid(); } TimerId EventLoop::runAt(const Timestamp& time, const TimerCallback& cb) { return m_timerQueue->addTimer(cb, time, 0.0); } TimerId EventLoop::runAfter(double delay, const TimerCallback& cb) { Timestamp time(addTime(Timestamp::now(), delay)); return runAt(time, cb); } TimerId EventLoop::runEvery(double interval, const TimerCallback& cb) { Timestamp time(addTime(Timestamp::now(), interval)); return m_timerQueue->addTimer(cb, time, interval); }
df4a8f4528029dfb9c5867122d2fbb1be4f5c530
3f24da37878937bf884a971cde9209e7c0dc9211
/media/gpu/android/mock_texture_owner.h
adcff47a4b008239db8ba09a54a8fb8ca343548f
[ "BSD-3-Clause" ]
permissive
shenglihou/chromium
5c4bab1a64163f4116dd9e1e590387d853dc982a
fb3cb75ead46b9979ac934f69ef05cad06fd11b1
refs/heads/master
2023-02-23T09:02:12.725032
2019-03-04T13:55:50
2019-03-04T13:55:50
173,755,773
1
0
NOASSERTION
2019-03-04T14:02:56
2019-03-04T14:02:54
null
UTF-8
C++
false
false
2,258
h
// Copyright 2017 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef MEDIA_GPU_ANDROID_MOCK_TEXTURE_OWNER_H_ #define MEDIA_GPU_ANDROID_MOCK_TEXTURE_OWNER_H_ #include <memory> #include "base/android/scoped_hardware_buffer_fence_sync.h" #include "media/gpu/android/texture_owner.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" #include "ui/gl/gl_bindings.h" #include "ui/gl/gl_context.h" #include "ui/gl/gl_surface.h" namespace media { // This is a mock with a small amount of fake functionality too. class MockTextureOwner : public TextureOwner { public: MockTextureOwner(GLuint fake_texture_id, gl::GLContext* fake_context, gl::GLSurface* fake_surface); MOCK_CONST_METHOD0(GetTextureId, GLuint()); MOCK_CONST_METHOD0(GetContext, gl::GLContext*()); MOCK_CONST_METHOD0(GetSurface, gl::GLSurface*()); MOCK_CONST_METHOD0(CreateJavaSurface, gl::ScopedJavaSurface()); MOCK_METHOD1(UpdateTexImage, void(bool bind_egl_image)); MOCK_METHOD1(GetTransformMatrix, void(float mtx[16])); MOCK_METHOD0(ReleaseBackBuffers, void()); MOCK_METHOD0(SetReleaseTimeToNow, void()); MOCK_METHOD0(IgnorePendingRelease, void()); MOCK_METHOD0(IsExpectingFrameAvailable, bool()); MOCK_METHOD0(WaitForFrameAvailable, void()); MOCK_METHOD1(OnTextureDestroyed, void(gpu::gles2::AbstractTexture*)); std::unique_ptr<base::android::ScopedHardwareBufferFenceSync> GetAHardwareBuffer() override { get_a_hardware_buffer_count++; return nullptr; } // Fake implementations that the mocks will call by default. void FakeSetReleaseTimeToNow() { expecting_frame_available = true; } void FakeIgnorePendingRelease() { expecting_frame_available = false; } bool FakeIsExpectingFrameAvailable() { return expecting_frame_available; } void FakeWaitForFrameAvailable() { expecting_frame_available = false; } gl::GLContext* fake_context; gl::GLSurface* fake_surface; bool expecting_frame_available; int get_a_hardware_buffer_count = 0; protected: ~MockTextureOwner(); }; } // namespace media #endif // MEDIA_GPU_ANDROID_MOCK_TEXTURE_OWNER_H_
6e5de1e23fb27d1e79519c4006707238ad80c855
81ef03d4f681da835ec19415820df12eb2beb59b
/BaseLib/UBMysql.h
5b05e1957778d46f1e5d75b0e577aa2708897fc6
[]
no_license
FlappyMan/HttpWebSocket
906a365584307fc8216b4824542018d75630da4c
e844139119c036464784438825150a41ca169e8e
refs/heads/master
2023-07-28T11:45:39.934945
2021-09-15T11:01:14
2021-09-15T11:01:14
278,041,522
1
0
null
null
null
null
UTF-8
C++
false
false
2,467
h
 #ifndef _UBMYSQL_HEADER_ #define _UBMYSQL_HEADER_ #include "UBHeader.h" class UBMysql { public: UBMysql(); UBMysql(uint32_t uiSqlSize); UBMysql(char *pSqlBuff,uint32_t uiSqlSize); virtual ~UBMysql(); int Error(){return m_iError;}; void Error(string &str){str=m_sError;}; void init(uint32_t uiSqlSize); void Disconnect(); bool Connect(string &host,int port,string &user,string &pwd,string &db); bool Connect(string &unixsocket,string &user,string &pwd,string &db); // 在内部sql缓冲中构造sql bool Sql(string &sSql,bool bNeedEscape,bool bCleanBuffer=false){return Sql(sSql.data(),sSql.length(),bNeedEscape,bCleanBuffer);}; bool Sql(const char *pSql,bool bNeedEscape, bool bCleanBuffer=false){return Sql(pSql,strlen(pSql),bNeedEscape,bCleanBuffer);}; bool Sql(const char *pSql,int iSqlLen,bool bNeedEscape = false,bool bCleanBuffer=false); // Insert & Update 操作,返回受影响记录数 int Exec(){return Exec(m_pSql,m_iSqlLength);}; //执行内部buffer中的sql int Exec(string &sql){return Exec(sql.data(),sql.length());} //执行指定sql int Exec(const char *sql,int len); //执行指定sql // Select 操作 void SelectClear(); bool Select(){return Select(m_pSql,m_iSqlLength);}; bool Select(string &sql){return Select(sql.data(),sql.length());}; bool Select(const char *sql,int len); // select 取结果相关函数 bool NextRow(); void Value(uint32_t iIdx,int16_t &iValue,int16_t iDefault=0); void Value(uint32_t iIdx,uint16_t &iValue,uint16_t iDefault=0); void Value(uint32_t iIdx,int32_t &iValue,int32_t iDefault=0); void Value(uint32_t iIdx,uint32_t &uiValue,uint32_t uiDefault=0); void Value(uint32_t iIdx,int64_t &iValue,int64_t iDefault=0); void Value(uint32_t iIdx,uint64_t &uiValue,uint64_t uiDefault=0); void Value(uint32_t iIdx,double &dValue,double dDefault=0); void Value(uint32_t iIdx,float &fValue,float fDefault=0.0); void Value(uint32_t iIdx,string &sValue); uint32_t Value(uint32_t iIdx,uint8_t *pBuff,uint32_t iBuffSize); // 返回实际存入的字节数 uint64_t LastID(){return m_pMysql==NULL?0:mysql_insert_id(m_pMysql);}; char* getSql(){if(m_iSqlLength<m_iSqlSize)m_pSql[m_iSqlLength]=0;return m_pSql;}; protected: protected: MYSQL *m_pMysql; MYSQL_RES *m_pMysqlResult; string m_sError; int m_iError; char *m_pSql; const bool m_bFreeBuffer; uint32_t m_iSqlSize; uint32_t m_iSqlLength; private: MYSQL_ROW m_row; uint32_t m_uiColumnCnt; }; #endif
c4ae6158d3e3006ef5126aa630ef4cfca51cf80e
36183993b144b873d4d53e7b0f0dfebedcb77730
/GameDevelopment/Game Programming Gems 4/01 General Programming/12 My/Core/Logger.cpp
f451f885bcbd35e9e0a970b191c854bab6e644d6
[]
no_license
alecnunn/bookresources
b95bf62dda3eb9b0ba0fb4e56025c5c7b6d605c0
4562f6430af5afffde790c42d0f3a33176d8003b
refs/heads/master
2020-04-12T22:28:54.275703
2018-12-22T09:00:31
2018-12-22T09:00:31
162,790,540
20
14
null
null
null
null
UTF-8
C++
false
false
18,572
cpp
//--------------------------------------------------------------------------------------------------------------------// // LOGGER CLASS & MACROS // // written by Frederic My // // [email protected] // //--------------------------------------------------------------------------------------------------------------------// //----------------------------------------------- INCLUDES -----------------------------------------------------------// #include "stdafx.h" #include "Logger.h" #ifdef _DEBUG #include "Logger.inl" #include "LogHelper.inl" #endif #include <time.h> #include "MyAssert.h" #include "DirC.h" #include "FileC.h" #include "FindFileC.h" //----------------------------------------------- DEFINES ------------------------------------------------------------// #define _NUMLINE_ "4" // chrs for line number #define _NUMMSG_ "4" // chrs for msg number #define _INDENTATION_ " " #define _FILECHRS_ "30" // chrs for file name #define _NBFILECHRS_ 30 namespace GPG4 { //----------------------------------------------- STATIC MEMBERS -----------------------------------------------------// u32 CLogger::m_u32GlobalNextError = 1; u32 CLogger::m_u32GlobalNextWarning = 1; u32 CLogger::m_u32GlobalNextMsg = 1; //--------------------------------------------------------------------------------------------------------------------// // SETUP/CLEANUP // //--------------------------------------------------------------------------------------------------------------------// //----------------------------------------------- DeleteFiles --------------------------------------------------------// // delete all .LOG files in given directory (which becomes the log dir) // in : log directory // out: //--------------------------------------------------------------------------------------------------------------------// void CLogger::DeleteFiles(const char* pszDir) { if(pszDir) m_strDir = pszDir; else m_strDir = "LOGS"; char szFullPath[_MAX_PATH]; Dir Dir; Dir.FullPath(szFullPath,m_strDir.c_str(),_MAX_PATH); m_strDir = szFullPath; // save full path CStdString strFileName = m_strDir+"\\*.LOG"; FindFile Finder; if(Finder.FindFirst(strFileName.c_str(),true)) { do { // remove all .LOG files bool boRes = Dir.RemoveOneFile(Finder.GetFilePath().c_str()); MY_ASSERT(boRes,"error removing file"); } while(Finder.FindNext()); Finder.FindClose(); } Dir.MakeDir(m_strDir.c_str()); // fails if the dir already exists, not a pb } //----------------------------------------------- ResetCounters ------------------------------------------------------// // reinit all counters // in : // out: //--------------------------------------------------------------------------------------------------------------------// void CLogger::ResetCounters() { m_u32NextError = m_u32NextWarning = m_u32NextMsg = 1; m_s32Priority = 1; m_u32Indent = 0; } //----------------------------------------------- Reset --------------------------------------------------------------// // (re)init logger // in : // out: //--------------------------------------------------------------------------------------------------------------------// void CLogger::Reset(const char* pszDir) { DeleteFiles(pszDir); ResetCounters(); m_u32MsgMask = _MSG_ALL_; m_u32OutputMask = _OUTPUT_ALL_; m_u32IndentMin = 0; m_u32IndentMax = u32(-1); m_strRootPath = ""; m_u32RootLen = m_strRootPath.size(); m_strLastWarning = ""; m_strLastError = ""; } //----------------------------------------------- GetResults ---------------------------------------------------------// // return some stats // in : // out: stats string //--------------------------------------------------------------------------------------------------------------------// CStdString CLogger::GetResults() const { if(m_u32NextError+m_u32NextWarning == 2) return ""; CStdString strInfo; strInfo.Format("%u error(s), %u warning(s)\n",m_u32NextError-1,m_u32NextWarning-1); return strInfo; } //--------------------------------------------------------------------------------------------------------------------// // TRACE // //--------------------------------------------------------------------------------------------------------------------// //----------------------------------------------- SysTrace -----------------------------------------------------------// // put the string in [pszFile].LOG // in : file name,string // out: //--------------------------------------------------------------------------------------------------------------------// void CLogger::SysTrace(const char* pszFile,const char* pszString) { if(m_s32Priority <= 0) return; if(!IsOutputEnabled(_OUTPUT_FILE_)) return; char szDrive[_MAX_DRIVE]; char szDir [_MAX_DIR]; char szName [_MAX_FNAME]; char szExt [_MAX_EXT]; char szOpen [_MAX_PATH]; _splitpath(pszFile,szDrive,szDir,szName,szExt); strncpy(szDir,m_strDir.c_str(),_MAX_DIR-1); _makepath(szOpen,"",m_strDir.c_str(),szName,".LOG"); File File; if(File.Open(szOpen,IFile::APPEND_TEXT)) { // 24/11/01: time time_t t = time(NULL); struct tm *local = localtime(&t); char szTime[256]; sprintf(szTime,"<%02d/%02d/%02d %02d:%02d:%02d> ",local->tm_mday,local->tm_mon+1,local->tm_year%100, local->tm_hour,local->tm_min, local->tm_sec); File.PutString(szTime); // File.PutString(pszString); File.Close(); } } //----------------------------------------------- Trace --------------------------------------------------------------// // put the string in TRACE.LOG & [pszFile].LOG // in : file name,line number,string // out: //--------------------------------------------------------------------------------------------------------------------// void CLogger::Trace(const char* pszFile,const u32 u32Line,const char* pszString) { if(m_s32Priority <= 0) return; CStdString strBuf1,strBuf2,strBuf3; strBuf1.reserve(256); strBuf2.reserve(256); strBuf3.reserve(256); strBuf1 = pszString; strBuf1 +="\n"; strBuf2.Format("[%" _NUMLINE_ "d] %" _NUMMSG_ "d: ",u32Line,m_u32GlobalNextMsg); // message number for(ui uiI = 0; uiI < m_u32Indent; uiI++) strBuf2 += _INDENTATION_; if(u32Line) strBuf2 += strBuf1; else strBuf2 = strBuf1; SysTrace(pszFile,strBuf2.c_str()); // put message in [pszFile].LOG char szFile[_MAX_PATH]; strcpy(szFile,pszFile); strupr(szFile); char* pcPos = strstr(szFile,m_strRootPath.c_str()); strBuf2.Format("[%." _FILECHRS_ "s :",pcPos ? pcPos+m_u32RootLen : pszFile); u32 u32Len = strBuf2.size(); while(u32Len < _NBFILECHRS_+3) { strBuf2 += " "; u32Len++; } strBuf3.Format("%s %" _NUMLINE_ "d] %" _NUMMSG_ "d: ",strBuf2.c_str(),u32Line,m_u32GlobalNextMsg++); m_u32NextMsg++; for(uiI = 0; uiI < m_u32Indent; uiI++) strBuf3 += _INDENTATION_; if(u32Line) strBuf3 += strBuf1; else strBuf3 = strBuf1; SysTrace("TRACE.LOG",strBuf3.c_str()); // put message in TRACE.LOG strBuf3.Delete(strBuf3.size()-1); // remove "\n" SendCallback(strBuf3.c_str()); } //----------------------------------------------- Log ----------------------------------------------------------------// // put the string in [pszFile].LOG // in : file name,line number,string // out: //--------------------------------------------------------------------------------------------------------------------// void CLogger::Log(const char* pszFile,const u32 u32Line,const char* pszString) { if(m_s32Priority <= 0) return; CStdString strBuf1,strBuf2; strBuf1.reserve(256); strBuf2.reserve(256); strBuf1 = pszString; strBuf1 += "\n"; strBuf2.Format("[%" _NUMLINE_ "d] %" _NUMMSG_ "d: ",u32Line,m_u32GlobalNextMsg++); m_u32NextMsg++; for(ui uiI = 0; uiI < m_u32Indent; uiI++) strBuf2 += _INDENTATION_; strBuf2 += strBuf1; SysTrace(pszFile,strBuf2); // put message in [pszFile].LOG } //----------------------------------------------- Warning ------------------------------------------------------------// // put the string WARNING.LOG & [pszFile].LOG & TRACE.LOG // in : file name,line number,string // out: //--------------------------------------------------------------------------------------------------------------------// void CLogger::Warning(const char* pszFile,const u32 u32Line,const char* pszString) { CStdString strBuf1,strBuf2,strBuf3; strBuf1.reserve(256); strBuf2.reserve(256); strBuf3.reserve(256); strBuf1 = m_strLastWarning = pszString; if(m_s32Priority <= 0) return; Trace(pszFile,u32Line,strBuf1.c_str()); // put message in TRACE.LOG & [pszFile].LOG m_u32GlobalNextMsg--; m_u32NextMsg--; char szFile[_MAX_PATH]; strcpy(szFile,pszFile); strupr(szFile); char* pcPos = strstr(szFile,m_strRootPath.c_str()); strBuf2.Format("[%." _FILECHRS_ "s :",pcPos ? pcPos+m_u32RootLen : pszFile); DWORD u32Len = strBuf2.size(); while(u32Len < _NBFILECHRS_+3) { strBuf2 += " "; u32Len++; } strBuf3.Format("%s %" _NUMLINE_ "d] %" _NUMMSG_ "d: ",strBuf2.c_str(),u32Line,m_u32GlobalNextMsg++); m_u32NextMsg++; strBuf3 += strBuf1+"\n"; SysTrace("WARNINGS.LOG",strBuf3.c_str()); // put message in WARNINGS.LOG m_u32GlobalNextWarning++; m_u32NextWarning++; } //----------------------------------------------- Error --------------------------------------------------------------// // put the string ERRORS.LOG & [pszFile].LOG & TRACE.LOG // in : file name,line number,string // out: //--------------------------------------------------------------------------------------------------------------------// void CLogger::Error(const char* pszFile,const u32 u32Line,const char* pszString) { CStdString strBuf1,strBuf2,strBuf3; strBuf1.reserve(256); strBuf2.reserve(256); strBuf3.reserve(256); strBuf1 = m_strLastError = pszString; if(m_s32Priority <= 0) return; Trace(pszFile,u32Line,strBuf1.c_str()); // put message in TRACE.LOG & [pszFile].LOG m_u32GlobalNextMsg--; m_u32NextMsg--; char szFile[_MAX_PATH]; strcpy(szFile,pszFile); strupr(szFile); char* pcPos = strstr(szFile,m_strRootPath.c_str()); strBuf2.Format("[%." _FILECHRS_ "s :",pcPos ? pcPos+m_u32RootLen : pszFile); DWORD u32Len = strBuf2.size(); while(u32Len < _NBFILECHRS_+3) { strBuf2 += " "; u32Len++; } strBuf3.Format("%s %" _NUMLINE_ "d] %" _NUMMSG_ "d: ",strBuf2.c_str(),u32Line,m_u32GlobalNextMsg++); m_u32NextMsg++; strBuf3 += strBuf1+"\n"; SysTrace("ERRORS.LOG",strBuf3.c_str()); // put message in WARNINGS.LOG m_u32GlobalNextError++; m_u32NextError++; } //----------------------------------------------- StreamTrace --------------------------------------------------------// // put stream in TRACE.LOG & [pszFile].LOG // in : file name,line number,indent increment // out: //--------------------------------------------------------------------------------------------------------------------// void CLogger::StreamTrace(const char* pszFile,const u32 u32Line,const s32 s32Indent) { char* lpcBuf; m_Stream << 'a'; // add dummy character lpcBuf = m_Stream.str(); // stream buffer address int iCount = m_Stream.pcount(); // buffer length lpcBuf[iCount-1] = 0; // ASCIIZ SendReportCallback(lpcBuf,m_u32GlobalNextMsg,"trace",pszFile,u32Line); if((s32Indent < 0) && (m_u32Indent > 0)) m_u32Indent += s32Indent; if(m_s32Priority > 0) Trace(pszFile,u32Line,lpcBuf); // put stream in files if( s32Indent > 0) m_u32Indent += s32Indent; m_Stream.rdbuf()->freeze(0); // unlock buffer m_Stream.rdbuf()->seekoff(0,ios::beg,ios::in|ios::out); // clear buffer } //----------------------------------------------- StreamLog ----------------------------------------------------------// // put stream in [pszFile].LOG // in : file name,line number,type // out: //--------------------------------------------------------------------------------------------------------------------// void CLogger::StreamLog(const char* pszFile,const u32 u32Line,const char* pszType/*="log"*/) { char* lpcBuf; m_Stream << 'a'; // add dummy character lpcBuf = m_Stream.str(); // stream buffer address int iCount = m_Stream.pcount(); // buffer length lpcBuf[iCount-1] = 0; // ASCIIZ SendReportCallback(lpcBuf,m_u32GlobalNextMsg,pszType,pszFile,u32Line); if(m_s32Priority > 0) Log(pszFile,u32Line,lpcBuf); // put stream in files m_Stream.rdbuf()->freeze(0); // unlock buffer m_Stream.rdbuf()->seekoff(0,ios::beg,ios::in|ios::out); // clear buffer } //----------------------------------------------- StreamWarning ------------------------------------------------------// // put stream in WARNINGS.LOG & [pszFile].LOG & TRACE.LOG // in : file name,line number // out: //--------------------------------------------------------------------------------------------------------------------// void CLogger::StreamWarning(const char* pszFile,const u32 u32Line) { char* lpcBuf; m_Stream << 'a'; // add dummy character lpcBuf = m_Stream.str(); // stream buffer address int iCount = m_Stream.pcount(); // buffer length lpcBuf[iCount-1] = 0; // ASCIIZ SendReportCallback(lpcBuf,m_u32GlobalNextMsg,"warning",pszFile,u32Line); if(m_s32Priority > 0) Warning(pszFile,u32Line,lpcBuf); // put stream in files m_Stream.rdbuf()->freeze(0); // unlock buffer m_Stream.rdbuf()->seekoff(0,ios::beg,ios::in|ios::out); // clear buffer } //----------------------------------------------- StreamError --------------------------------------------------------// // put stream in ERRORS.LOG & [pszFile].LOG & TRACE.LOG // in : file name,line number // out: //--------------------------------------------------------------------------------------------------------------------// void CLogger::StreamError(const char* pszFile,const u32 u32Line) { char* lpcBuf; m_Stream << 'a'; // add dummy character lpcBuf = m_Stream.str(); // stream buffer address int iCount = m_Stream.pcount(); // buffer length lpcBuf[iCount-1] = 0; // ASCIIZ SendReportCallback(lpcBuf,m_u32GlobalNextMsg,"error",pszFile,u32Line); if(m_s32Priority > 0) Error(pszFile,u32Line,lpcBuf); // put stream in files m_Stream.rdbuf()->freeze(0); // unlock buffer m_Stream.rdbuf()->seekoff(0,ios::beg,ios::in|ios::out); // clear buffer } //----------------------------------------------- SendCallback -------------------------------------------------------// // send string to log view if any // in : string // out: //--------------------------------------------------------------------------------------------------------------------// void CLogger::SendCallback(const char* pszString) { if(!m_pCallback) return; (*m_pCallback)(pszString); } //----------------------------------------------- SendReportCallback -------------------------------------------------// // send string to log report view if any // in : string,ID,level,file,line // out: //--------------------------------------------------------------------------------------------------------------------// void CLogger::SendReportCallback(const char* pszString,const DWORD dwID,const char* pszLevel, const char* pszFile, const DWORD dwLine) { if(!m_pReportCallback) return; const char* pcPos = pszFile; if(pszFile && !_strnicmp(pszFile,m_strRootPath.c_str(),m_u32RootLen)) pcPos += m_u32RootLen; (*m_pReportCallback)(pszString,dwID,pszLevel,pcPos,dwLine,m_dwExtraData); } //--------------------------------------------------------------------------------------------------------------------// // LOG HELPER // //--------------------------------------------------------------------------------------------------------------------// //----------------------------------------------- Init ---------------------------------------------------------------// // save the file,line,and msg // in : __FILE__,__LINE__,msg // out: //--------------------------------------------------------------------------------------------------------------------// void CLogHelper::Init(const char* pszFile,const u32 u32Line,ostrstream Stream) { int iCount = Stream.pcount(); m_pszBuf = new char[iCount+1]; if(m_pszBuf) { memcpy(m_pszBuf,Stream.str(),iCount); m_pszBuf[iCount] = 0; Stream.rdbuf()->freeze(0); } iCount = strlen(pszFile); m_pszFile = new char[iCount+1]; if(m_pszFile) { memcpy(m_pszFile,pszFile,iCount); m_pszFile[iCount] = 0; } m_u32Line = u32Line; } //--------------------------------------------------------------------------------------------------------------------// } // namespace
8f6c4d1e66541ae519ffe009304c78a27aed38fa
600653c62fdea3fac310c73d98f4df66a3ceb037
/Engine/Application/Windows/cbApplication.win.cpp
494baf819587592a4deca874c9c4072c7c75e66c
[]
no_license
conankzhang/ecs-game-engine
34ee08ec674c56613ff851fc628ec3e41fcc5565
f85b6bd71a8b2d4f5528621555a37d79829a6d93
refs/heads/master
2020-04-07T21:43:46.839740
2018-12-13T01:24:54
2018-12-13T01:24:54
158,738,699
2
1
null
null
null
null
UTF-8
C++
false
false
23,996
cpp
// Includes //========= #include "../cbApplication.h" #include <cstdlib> #include <Engine/Asserts/Asserts.h> #include <Engine/Graphics/Graphics.h> #include <Engine/Logging/Logging.h> #include <Engine/UserOutput/UserOutput.h> #include <Engine/UserSettings/UserSettings.h> #include <Engine/Windows/Functions.h> // Helper Function Declarations //============================= namespace { // Initialization / Clean Up //-------------------------- eae6320::cResult CreateMainWindow( const HINSTANCE i_thisInstanceOfTheApplication, const char* const i_windowName, const ATOM i_windowClass, const uint16_t i_resolutionWidth, const uint16_t i_resolutionHeight, eae6320::Application::cbApplication& io_application, HWND& o_window ); eae6320::cResult CreateMainWindowClass( const HINSTANCE i_thisInstanceOfTheApplication, const char* const i_mainWindowClassName, WNDPROC fOnMessageReceivedFromWindows, ATOM& o_mainWindowClass, const WORD* const i_iconId_large = nullptr, const WORD* const i_iconId_small = nullptr ); eae6320::cResult FreeMainWindow( HWND& io_window ); eae6320::cResult FreeMainWindowClass( const HINSTANCE i_thisInstanceOfTheApplication, ATOM& io_mainWindowClass ); } // Interface //========== // Access //------- eae6320::cResult eae6320::Application::cbApplication::GetCurrentResolution( uint16_t& o_width, uint16_t& o_height ) const { if ( ( m_resolutionWidth != 0 ) && ( m_resolutionHeight != 0 ) ) { o_width = m_resolutionWidth; o_height = m_resolutionHeight; return Results::Success; } else { return Results::Failure; } } // Initialization / Clean Up //-------------------------- eae6320::Application::cbApplication::cbApplication() : m_exitCode( EXIT_SUCCESS ) { } // Inherited Implementation //=========================== // Access //------- eae6320::Application::cbApplication* eae6320::Application::cbApplication::GetApplicationFromWindow( const HWND i_window ) { const auto userData = GetWindowLongPtr( i_window, GWLP_USERDATA ); auto* const application = reinterpret_cast<cbApplication*>( userData ); EAE6320_ASSERT( application ); EAE6320_ASSERT( application->m_mainWindow == i_window ); return application; } // Implementation //=============== // Run //---- eae6320::cResult eae6320::Application::cbApplication::RenderFramesWhileWaitingForApplicationToExit( int& o_exitCode ) { // Enter an infinite loop that will continue until a WM_QUIT message is received from Windows MSG message{}; do { // To send us a message, Windows will add it to a queue. // Most Windows applications should wait until a message is received and then react to it. // Real-time programs, though, must continually draw new images to the screen as fast as possible // and only pause momentarily when there is a Windows message to deal with. // This means that the first thing that must be done every iteration of the game loop is to "peek" at the message queue // and see if there are any messages from Windows that need to be handled const auto hasWindowsSentAMessage = [&message]() { constexpr HWND getMessagesFromAnyWindowBelongingToTheCurrentThread = NULL; constexpr unsigned int getAllMessageTypes = 0; constexpr unsigned int ifAMessageExistsRemoveItFromTheQueue = PM_REMOVE; return PeekMessageW( &message, getMessagesFromAnyWindowBelongingToTheCurrentThread, getAllMessageTypes, getAllMessageTypes, ifAMessageExistsRemoveItFromTheQueue ) == TRUE; }(); if ( !hasWindowsSentAMessage ) { // Usually there will be no messages in the queue, and a new frame can be rendered Graphics::RenderFrame(); } else { // If Windows has sent a message, this iteration of the loop will handle it // First, the message must be "translated" // (Key presses are translated into character messages) TranslateMessage( &message ); // Then, the message is sent on to the appropriate processing function. // This function is specified in the lpfnWndProc field of the WNDCLASSEX struct // used to register a class with Windows. // In the case of the main window for this application // it will always be OnMessageReceived(). DispatchMessage( &message ); } } while ( message.message != WM_QUIT ); // The exit code for the application is stored in the WPARAM of a WM_QUIT message o_exitCode = static_cast<int>( message.wParam ); // Regardless of the exit code (whether the application itself "succeeded" or "failed") // this function did what it was supposed to successfully return Results::Success; } eae6320::cResult eae6320::Application::cbApplication::Exit_platformSpecific( const int i_exitCode ) { // Send a WM_CLOSE message, // which means that the application should terminate. // A standard Windows application can refuse a WM_CLOSE request, // but there is no way to tell from the return value whether that happened or not. // In order to be platform-independent // this base class application will always close in response to a WM_CLOSE request. // If a specific application wants to prompt the user before closing // it should do so in a platform-independent way before calling this Exit() function. m_exitCode = i_exitCode; EAE6320_ASSERT( m_mainWindow ); constexpr WPARAM wParam_unused = 0; constexpr LPARAM lParam_unused = 0; // (The Windows API SendMessage() will end up calling cbApplication::OnMessageReceivedFromWindows() directly // and block until it returns) const auto windowsResult = SendMessage( m_mainWindow, WM_CLOSE, wParam_unused, lParam_unused ); return Results::Success; } LRESULT CALLBACK eae6320::Application::cbApplication::OnMessageReceivedFromWindows( HWND i_window, UINT i_message, WPARAM i_wParam, LPARAM i_lParam ) { // DispatchMessage() will send messages that the main window receives to this function. // There are many messages that get sent to a window, // but this application can ignore most of them // and let Windows handle them in the default way. // Process any messages that the application cares about // (any messages that are processed here should return a value // rather than letting the default processing function try to handle them a second time) switch( i_message ) { // A window should close case WM_CLOSE: { // In a standard Windows application this message can be treated as a request // and it can be denied // (for example, the application could show the user an "Are you sure?" prompt). // In order to have this application behave the same for all platforms, however, // this request will always be honored. // No custom processing is done, and the message is passed on to the default message handler // (which will destroy the window, eventually leading to a WM_NCDESTROY message being received in this function) } break; // A window's nonclient area is being created case WM_NCCREATE: { // This message gets sent as a result of CreateWindowEx() being called // and is received here before that function returns // The LPARAM input parameter has information about the window's creation const auto& creationData = *reinterpret_cast<CREATESTRUCT*>( i_lParam ); // Retrieve the application pointer that was provided to CreateWindowEx() auto* const application = static_cast<eae6320::Application::cbApplication*>( creationData.lpCreateParams ); EAE6320_ASSERT( application ); // Assign the new handle application->m_mainWindow = i_window; // Assign the application to the new window's user data { SetLastError( ERROR_SUCCESS ); const auto previousUserData = SetWindowLongPtr( i_window, GWLP_USERDATA, reinterpret_cast<LONG_PTR>( application ) ); // Presumably there is no previous user data on a brand new window if ( previousUserData == NULL ) { // Make sure that there was no error DWORD errorCode; const auto errorMessage = Windows::GetLastSystemError( &errorCode ); if ( errorCode != ERROR_SUCCESS ) { EAE6320_ASSERTF( "Couldn't set main window user data: %s", errorMessage.c_str() ); Logging::OutputError( "Windows failed to set the main window's user data: %s", errorMessage.c_str() ); // Returning FALSE causes the window to be destroyed and a NULL window handle to be returned from CreateWindowEx() application->m_mainWindow = NULL; return FALSE; } } } // The documentation says that if the message was handled successfully that TRUE should be returned, // but doing that skips some of the default creation behavior // (e.g. the caption won't be displayed). // Instead it is better to break instead of returning // so that the window will behave like any standard window. // return TRUE; } break; // A window's nonclient area is being destroyed // (because e.g. someone has clicked the X in upper-right corner) case WM_NCDESTROY: { // This is the last message a window will receive // (any child windows have already been destroyed) const int exitCode = [i_window]() { int exitCode = EXIT_SUCCESS; auto* const application = GetApplicationFromWindow( i_window ); if ( application ) { // After this message has been processed the window's handle will be invalid application->m_mainWindow = NULL; // Get the exit code from the application exitCode = application->m_exitCode; } return exitCode; }(); // When the main window is destroyed // a WM_QUIT message should be sent // (if this isn't done the application would continue to run with no window) PostQuitMessage( exitCode ); // This sends a WM_QUIT message // Return a value to indicate that this message was handled successfully // (the correct value is different for different messages types; // for WM_NCDESTROY it is 0) return 0; } break; } // Pass any messages that weren't handled on to Windows // so that this application's window behaves like any standard window return DefWindowProc( i_window, i_message, i_wParam, i_lParam ); } // Initialization / Clean Up //-------------------------- eae6320::cResult eae6320::Application::cbApplication::Initialize_base( const sEntryPointParameters& i_entryPointParameters ) { auto result = Results::Success; // Save the handle to this specific running instance of the application const auto applicationInstance = i_entryPointParameters.applicationInstance; m_thisInstanceOfTheApplication = applicationInstance; // Windows requires every window to have a "class" // (a window only has a single class, but many windows can share the same class) if ( !( result = CreateMainWindowClass( applicationInstance, GetMainWindowClassName(), OnMessageReceivedFromWindows, m_mainWindowClass, GetLargeIconId(), GetSmallIconId() ) ) ) { EAE6320_ASSERT( false ); goto OnExit; } // Create the main window { uint16_t desiredResolutionWidth, desiredResolutionHeight; { // Get the application's default GetDefaultInitialResolution( desiredResolutionWidth, desiredResolutionHeight ); // Override with the user's desired resolution UserSettings::GetDesiredInitialResolutionWidth( desiredResolutionWidth ); UserSettings::GetDesiredInitialResolutionHeight( desiredResolutionHeight ); } HWND window; if ( result = CreateMainWindow( applicationInstance, GetMainWindowName(), m_mainWindowClass, desiredResolutionWidth, desiredResolutionHeight, *this, window ) ) { // The new window handle should have been assigned to the application in OnMessageReceivedFromWindows() WM_CREATE EAE6320_ASSERT( window == m_mainWindow ); // Assign the resolution // (the window's border can't be resized, so for our class it's ok to set the resolution once and leave it) m_resolutionWidth = desiredResolutionWidth; m_resolutionHeight = desiredResolutionHeight; } else { EAE6320_ASSERT( false ); goto OnExit; } } // Display the window in the initial state that Windows requested { const auto wasWindowPreviouslyVisible = ShowWindow( m_mainWindow, i_entryPointParameters.initialWindowDisplayState ); } OnExit: return result; } eae6320::cResult eae6320::Application::cbApplication::PopulateGraphicsInitializationParameters( Graphics::sInitializationParameters& o_initializationParameters ) { EAE6320_ASSERT( m_mainWindow != NULL ); o_initializationParameters.mainWindow = m_mainWindow; #if defined( EAE6320_PLATFORM_D3D ) o_initializationParameters.resolutionWidth = m_resolutionWidth; o_initializationParameters.resolutionHeight = m_resolutionHeight; #elif defined( EAE6320_PLATFORM_GL ) o_initializationParameters.thisInstanceOfTheApplication = m_thisInstanceOfTheApplication; #endif return Results::Success; } eae6320::cResult eae6320::Application::cbApplication::PopulateUserOutputInitializationParameters( UserOutput::sInitializationParameters& o_initializationParameters ) { EAE6320_ASSERT( m_mainWindow != NULL ); o_initializationParameters.mainWindow = m_mainWindow; return Results::Success; } eae6320::cResult eae6320::Application::cbApplication::CleanUp_base() { auto result = Results::Success; // Main Window if ( m_mainWindow ) { const auto localResult = FreeMainWindow( m_mainWindow ); if ( !localResult ) { EAE6320_ASSERT( false ); if ( result ) { result = localResult; } } } // Main Window Class if ( m_mainWindowClass ) { const auto localResult = FreeMainWindowClass( m_thisInstanceOfTheApplication, m_mainWindowClass ); if ( !localResult ) { EAE6320_ASSERT( false ); if ( result ) { result = localResult; } } } return result; } // Helper Function Definitions //============================ namespace { // Initialization / Clean Up //-------------------------- eae6320::cResult CreateMainWindow( const HINSTANCE i_thisInstanceOfTheApplication, const char* const i_windowName, const ATOM i_windowClass, const uint16_t i_resolutionWidth, const uint16_t i_resolutionHeight, eae6320::Application::cbApplication& io_application, HWND& o_window ) { // Create the window { // The window's style constexpr DWORD windowStyle = // "Overlapped" is basically the same as "top-level" WS_OVERLAPPED // The caption is the title bar when in windowed-mode | WS_CAPTION // The window should never change dimensions, so only a minimize box is allowed | WS_MINIMIZEBOX // The system menu appears when you right-click the title bar | WS_SYSMENU; // The window's extended style constexpr DWORD windowStyle_extended = // The following is a macro to make the extended style the default top-level look WS_EX_OVERLAPPEDWINDOW; // The width and height of the window. // A game cares about the width and height of the actual "client area", // which is the part of the window that doesn't include the borders and title bar; // this means that if we say that a game runs at a resolution of 800 x 600, // the actual window will be slightly bigger than that. // Initially, then, the window will be created with default values that Windows chooses // and then resized after creation) constexpr int width = CW_USEDEFAULT; constexpr int height = CW_USEDEFAULT; // The initial position of the window // (We don't care, and will let Windows decide) constexpr int position_x = CW_USEDEFAULT; constexpr int position_y = CW_USEDEFAULT; // Handle to the parent of this window // (Since this is our main window, it can't have a parent) constexpr HWND parent = NULL; // Handle to the menu for this window // (The main window won't have a menu) constexpr HMENU menu = NULL; // A pointer can be sent with the WM_CREATE message received in OnMessageReceivedFromWindows() void* const userData = &io_application; // Ask Windows to create the specified window. // CreateWindowEx() will return a "handle" to the window (kind of like a pointer), // which is what we'll use when communicating with Windows to refer to this window o_window = CreateWindowExW( windowStyle_extended, MAKEINTATOM( i_windowClass ), eae6320::Windows::ConvertUtf8ToUtf16( i_windowName ).c_str(), windowStyle, position_x, position_y, width, height, parent, menu, i_thisInstanceOfTheApplication, userData ); if ( o_window != NULL ) { eae6320::Logging::OutputMessage( "Created main window \"%s\"", i_windowName ); } else { const auto errorMessage = eae6320::Windows::GetLastSystemError(); EAE6320_ASSERTF( false, "Main window wasn't created: %s", errorMessage.c_str() ); eae6320::Logging::OutputError( "Windows failed to create the main window: %s", errorMessage.c_str() ); return eae6320::Results::Failure; } } // Change the window's size based on the desired client area resolution { // Calculate how much of the window is coming from the "non-client area" // (the borders and title bar) RECT windowCoordinates; struct { long width; long height; } nonClientAreaSize; { // Get the coordinates of the entire window if ( GetWindowRect( o_window, &windowCoordinates ) == FALSE ) { const auto errorMessage = eae6320::Windows::GetLastSystemError(); EAE6320_ASSERTF( false, "Couldn't get coordinates of the main window: %s", errorMessage.c_str() ); eae6320::Logging::OutputError( "Windows failed to get the coordinates of the main window: %s", errorMessage.c_str() ); goto OnError; } // Get the dimensions of the client area RECT clientDimensions; if ( GetClientRect( o_window, &clientDimensions ) == FALSE ) { const auto errorMessage = eae6320::Windows::GetLastSystemError(); EAE6320_ASSERTF( false, "Couldn't get the main window's client dimensions: %s", errorMessage.c_str() ); eae6320::Logging::OutputError( "Windows failed to get the dimensions of the main window's client area:: %s", errorMessage.c_str() ); goto OnError; } // Get the difference between them nonClientAreaSize.width = ( windowCoordinates.right - windowCoordinates.left ) - clientDimensions.right; nonClientAreaSize.height = ( windowCoordinates.bottom - windowCoordinates.top ) - clientDimensions.bottom; } // Resize the window { const int desiredWidth_window = i_resolutionWidth + nonClientAreaSize.width; const int desiredHeight_window = i_resolutionHeight + nonClientAreaSize.height; constexpr BOOL redrawTheWindowAfterItsBeenResized = TRUE; if ( MoveWindow( o_window, windowCoordinates.left, windowCoordinates.top, desiredWidth_window, desiredHeight_window, redrawTheWindowAfterItsBeenResized ) != FALSE ) { eae6320::Logging::OutputMessage( "Set main window resolution to %u x %u", i_resolutionWidth, i_resolutionHeight ); } else { const auto errorMessage = eae6320::Windows::GetLastSystemError(); EAE6320_ASSERTF( false, "Couldn't resize the main window to &i x &i: %s", desiredWidth_window, desiredHeight_window, errorMessage.c_str() ); eae6320::Logging::OutputError( "Windows failed to resize main window to &i x &i" " (based on a desired resolution of %u x %u): %s", desiredWidth_window, desiredHeight_window, i_resolutionWidth, i_resolutionHeight, errorMessage.c_str() ); goto OnError; } } } return eae6320::Results::Success; OnError: if ( o_window != NULL ) { FreeMainWindow( o_window ); } return eae6320::Results::Failure; } eae6320::cResult CreateMainWindowClass( const HINSTANCE i_thisInstanceOfTheApplication, const char* const i_mainWindowClassName, WNDPROC fOnMessageReceivedFromWindows, ATOM& o_mainWindowClass, const WORD* const i_iconId_large, const WORD* const i_iconId_small ) { // Populate a struct defining the window class that we want WNDCLASSEXW wndClassEx{}; const auto mainWindowClassName = eae6320::Windows::ConvertUtf8ToUtf16( i_mainWindowClassName ); { wndClassEx.cbSize = sizeof( wndClassEx ); wndClassEx.hInstance = i_thisInstanceOfTheApplication; // The class's style // (We don't have to worry about any of these) wndClassEx.style = 0; // The function that will process all of the messages // that Windows will send to windows of this class wndClassEx.lpfnWndProc = fOnMessageReceivedFromWindows; // Extra bytes can be set aside in the class for user data wndClassEx.cbClsExtra = 0; // Extra bytes can be set aside for each window of this class, // but this is usually specified for each window individually wndClassEx.cbWndExtra = 0; // The large and small icons that windows of this class should use if ( i_iconId_large ) { wndClassEx.hIcon = LoadIconW( i_thisInstanceOfTheApplication, MAKEINTRESOURCE( *i_iconId_large ) ); } else { wndClassEx.hIcon = LoadIconW( NULL, IDI_APPLICATION ); } if ( i_iconId_small != 0 ) { wndClassEx.hIconSm = LoadIconW( i_thisInstanceOfTheApplication, MAKEINTRESOURCE( *i_iconId_small ) ); } else { wndClassEx.hIconSm = LoadIconW( NULL, IDI_APPLICATION ); } // The cursor that should display when the mouse pointer is over windows of this class // (in a real game you would likely hide this and render your own) wndClassEx.hCursor = LoadCursorW( NULL, IDC_ARROW ); // The "brush" that windows of this class should use as a background // (Setting this is a bit confusing but not important, // so don't be alarmed if the next line looks scary, // especially since 1) our entire window will be filled by the rendering and we won't see background // and 2) the technique below doesn't seem to work anymore since Windows Vista) wndClassEx.hbrBackground = reinterpret_cast<HBRUSH>( IntToPtr( COLOR_BACKGROUND + 1 ) ); // A menu can be specified that all windows of this class would use by default, // but usually this is set for each window individually wndClassEx.lpszMenuName = nullptr; // The class name (see comments where this is initialized) wndClassEx.lpszClassName = mainWindowClassName.c_str(); } // Register the class with Windows o_mainWindowClass = RegisterClassExW( &wndClassEx ); if ( o_mainWindowClass != NULL ) { eae6320::Logging::OutputMessage( "Registered main window class \"%s\"", i_mainWindowClassName ); return eae6320::Results::Success; } else { const auto errorMessage = eae6320::Windows::GetLastSystemError(); EAE6320_ASSERTF( false, "Main window class registration failed: %s", errorMessage.c_str() ); eae6320::Logging::OutputError( "Windows failed to register the main window class: %s", errorMessage.c_str() ); return eae6320::Results::Failure; } } eae6320::cResult FreeMainWindow( HWND& io_window ) { if ( DestroyWindow( io_window ) != FALSE ) { eae6320::Logging::OutputMessage( "Destroyed main window" ); // The handle should have been set to NULL in OnMessageReceivedFromWindows() WM_NCDESTROY EAE6320_ASSERT( io_window == NULL ); io_window = NULL; return eae6320::Results::Success; } else { const auto errorMessage = eae6320::Windows::GetLastSystemError(); EAE6320_ASSERTF( false, "Main window wasn't destroyed: %s", errorMessage.c_str() ); eae6320::Logging::OutputError( "Windows failed to destroy the main window: %s", errorMessage.c_str() ); return eae6320::Results::Failure; } } eae6320::cResult FreeMainWindowClass( const HINSTANCE i_thisInstanceOfTheApplication, ATOM& io_mainWindowClass ) { if ( UnregisterClassW( MAKEINTATOM( io_mainWindowClass ), i_thisInstanceOfTheApplication ) != FALSE ) { eae6320::Logging::OutputMessage( "Unregistered main window class" ); io_mainWindowClass = NULL; return eae6320::Results::Success; } else { const auto errorMessage = eae6320::Windows::GetLastSystemError(); EAE6320_ASSERTF( false, "Main window class wasn't unregistered: %s", errorMessage.c_str() ); eae6320::Logging::OutputError( "Windows failed to unregister the main window class: %s", errorMessage.c_str() ); return eae6320::Results::Failure; } } }
b8af7eceab85a9106b4c45d0fc52fbadd166c978
22626756c6b67f1cb79da13e783732eabc2881d1
/Source/UI/Grid/ChannelWindow.cpp
66cf5361ef9e44639485aa9c3b6faad3c272e8b7
[]
no_license
elzr2d2/JamCloud_project
8acab1d4cc367d6be40393b59c0d1f28812e794c
b9e82b1a936b2e44e794c13c81494cf6034ff27c
refs/heads/master
2020-06-17T04:50:39.924819
2019-09-17T17:39:28
2019-09-17T17:39:28
195,801,602
0
0
null
null
null
null
UTF-8
C++
false
false
1,051
cpp
#include "ChannelWindow.h" ChannelWindow::ChannelWindow(AudioEngine& inEngine) : engine(inEngine) { startTimerHz(60); engine.getEdit()->state.addListener(this); } ChannelWindow::~ChannelWindow() { engine.getEdit()->state.removeListener(this); } void ChannelWindow::update() { rebuildTrackList(); } void ChannelWindow::rebuildTrackList() { clearChannels(); for (auto* track : engine.getTrackList()) { auto audioTrack = dynamic_cast<AudioTrack*> (track); if (audioTrack != nullptr) addNewTrackComponent(*audioTrack); } } void ChannelWindow::clearChannels() { channels.clear(); channelY = 0; } void ChannelWindow::addNewTrackComponent(AudioTrack& audioTrack) { int channelHeight = UiHelper::getChannelHeight(); channels.emplace_back(); auto& addedChannel = channels.back(); addedChannel.reset(new ChannelComponent(engine, audioTrack)); addAndMakeVisible(*addedChannel); addedChannel->setBounds(0, channelY, getWidth(), channelHeight); channelY += channelHeight; }