hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
108
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
9c7c790a564a6e630de2972f7b180f98de45e56a
640
cpp
C++
infoarena/beyond_the_wall (TODO: FIX)/beyond_the_wall.cpp
cristicretu/cplusplus
87f5980271431b11ae1b8c14ce6d2c620a404488
[ "MIT" ]
1
2022-01-27T17:13:08.000Z
2022-01-27T17:13:08.000Z
infoarena/beyond_the_wall (TODO: FIX)/beyond_the_wall.cpp
cristicretu/cplusplus
87f5980271431b11ae1b8c14ce6d2c620a404488
[ "MIT" ]
null
null
null
infoarena/beyond_the_wall (TODO: FIX)/beyond_the_wall.cpp
cristicretu/cplusplus
87f5980271431b11ae1b8c14ce6d2c620a404488
[ "MIT" ]
null
null
null
/** * author: etohirse * created: 26.12.2020 15:54:25 **/ #include <fstream> #pragma GCC optimize("Ofast") #pragma GCC optimize("unroll-loops") std::ifstream fin("beyond_the_wall.in"); std::ofstream fout("beyond_the_wall.out"); const int mxn = 4e4; std::pair<int, int> av[mxn]; int main() { int n, q; fin >> n >> q; for (int i = 0; i < n; ++i) { fin >> av[i].first >> av[i].second; } while (q--) { int a, b, nr = 0; long long ans; fin >> a >> b; for (int i = 0; i < n; ++i) { ans = a * av[i].first - av[i].second + b; nr += (ans > 0); } fout << nr << '\n'; } return 0; }
17.777778
47
0.509375
cristicretu
9c7e82e0399244f5c8bc92a0d48055f7521ce21c
40,020
cpp
C++
Reconstruction/class6-mesh_generation/class6-mesh_generation/poisson/src/PoissonRecon.cpp
MrCocoaCat/slambook
1eb2c3b081c6f668f342ae8d3fa536748bedc77d
[ "MIT" ]
3
2018-02-13T05:39:05.000Z
2019-06-15T17:35:25.000Z
Reconstruction/class6-mesh_generation/class6-mesh_generation/poisson/src/PoissonRecon.cpp
MrCocoaCat/slambook
1eb2c3b081c6f668f342ae8d3fa536748bedc77d
[ "MIT" ]
null
null
null
Reconstruction/class6-mesh_generation/class6-mesh_generation/poisson/src/PoissonRecon.cpp
MrCocoaCat/slambook
1eb2c3b081c6f668f342ae8d3fa536748bedc77d
[ "MIT" ]
1
2018-12-21T13:59:20.000Z
2018-12-21T13:59:20.000Z
/* Copyright (c) 2006, Michael Kazhdan and Matthew Bolitho All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. Neither the name of the Johns Hopkins University nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "PoissonRecon.h" #include <stdio.h> #include <stdlib.h> #include <math.h> #include <float.h> #ifdef _WIN32 #include <Windows.h> #include <Psapi.h> #endif // _WIN32 #include "MyTime.h" #include "MarchingCubes.h" #include "Octree.h" #include "SparseMatrix.h" #include "CmdLineParser.h" #include "PPolynomial.h" #include "Ply.h" #include "MemoryUsage.h" #ifdef _OPENMP #include "omp.h" #endif // _OPENMP void DumpOutput( const char* format , ... ); #include "MultiGridOctreeData.h" void DumpOutput2( std::vector< char* >& comments , const char* format , ... ); #define DEFAULT_FULL_DEPTH 5 #define XSTR(x) STR(x) #define STR(x) #x #if DEFAULT_FULL_DEPTH #pragma message ( "[WARNING] Setting default full depth to " XSTR(DEFAULT_FULL_DEPTH) ) #endif // DEFAULT_FULL_DEPTH #include <stdarg.h> #include <iostream> char* outputFile=NULL; int echoStdout=0; void DumpOutput( const char* format , ... ) { if( outputFile ) { FILE* fp = fopen( outputFile , "a" ); va_list args; va_start( args , format ); vfprintf( fp , format , args ); fclose( fp ); va_end( args ); } if( echoStdout ) { va_list args; va_start( args , format ); vprintf( format , args ); va_end( args ); } } void DumpOutput2( std::vector< char* >& comments , const char* format , ... ) { if( outputFile ) { FILE* fp = fopen( outputFile , "a" ); va_list args; va_start( args , format ); vfprintf( fp , format , args ); fclose( fp ); va_end( args ); } if( echoStdout ) { va_list args; va_start( args , format ); vprintf( format , args ); va_end( args ); } comments.push_back( new char[1024] ); char* str = comments.back(); va_list args; va_start( args , format ); vsprintf( str , format , args ); va_end( args ); if( str[strlen(str)-1]=='\n' ) str[strlen(str)-1] = 0; } cmdLineString In( "in" ) , Out( "out" ) , VoxelGrid( "voxel" ) , XForm( "xForm" ); cmdLineReadable #ifdef _WIN32 Performance( "performance" ) , #endif // _WIN32 Complete( "complete" ) , ShowResidual( "showResidual" ) , NoComments( "noComments" ) , PolygonMesh( "polygonMesh" ) , Confidence( "confidence" ) , NormalWeights( "nWeights" ) , NonManifold( "nonManifold" ) , ASCII( "ascii" ) , Density( "density" ) , Verbose( "verbose" ) , Double( "double" ); cmdLineInt Depth( "depth" , 8 ) , CGDepth( "cgDepth" , 0 ) , KernelDepth( "kernelDepth" ) , AdaptiveExponent( "adaptiveExp" , 1 ) , Iters( "iters" , 8 ) , VoxelDepth( "voxelDepth" , -1 ) , FullDepth( "fullDepth" , DEFAULT_FULL_DEPTH ) , MinDepth( "minDepth" , 0 ) , MaxSolveDepth( "maxSolveDepth" ) , BoundaryType( "boundary" , 1 ) , Threads( "threads" , omp_get_num_procs() ); cmdLineFloat Color( "color" , 16.f ) , SamplesPerNode( "samplesPerNode" , 1.5f ) , Scale( "scale" , 1.1f ) , CSSolverAccuracy( "cgAccuracy" , float(1e-3) ) , PointWeight( "pointWeight" , 4.f ); cmdLineReadable* params[] = { &In , &Depth , &Out , &XForm , &Scale , &Verbose , &CSSolverAccuracy , &NoComments , &Double , &KernelDepth , &SamplesPerNode , &Confidence , &NormalWeights , &NonManifold , &PolygonMesh , &ASCII , &ShowResidual , &VoxelDepth , &PointWeight , &VoxelGrid , &Threads , &MaxSolveDepth , &AdaptiveExponent , &BoundaryType , &Density , &FullDepth , &MinDepth , &CGDepth , &Iters , &Complete , &Color , #ifdef _WIN32 &Performance , #endif // _WIN32 }; void ShowUsage(char *ex) { printf( "Usage: %s\n" , ex ); printf( "\t --%s <input points>\n" , In.name ); printf( "\t[--%s <ouput triangle mesh>]\n" , Out.name ); printf( "\t[--%s <ouput voxel grid>]\n" , VoxelGrid.name ); printf( "\t[--%s <maximum reconstruction depth>=%d]\n" , Depth.name , Depth.value ); printf( "\t\t Running at depth d corresponds to solving on a 2^d x 2^d x 2^d\n" ); printf( "\t\t voxel grid.\n" ); printf( "\t[--%s <full depth>=%d]\n" , FullDepth.name , FullDepth.value ); printf( "\t\t This flag specifies the depth up to which the octree should be complete.\n" ); printf( "\t[--%s <depth at which to extract the voxel grid>=<%s>]\n" , VoxelDepth.name , Depth.name ); printf( "\t[--%s <conjugate-gradients depth>=%d]\n" , CGDepth.name , CGDepth.value ); printf( "\t\t The depth up to which a conjugate-gradients solver should be used.\n"); printf( "\t[--%s <scale factor>=%f]\n" , Scale.name , Scale.value ); printf( "\t\t Specifies the factor of the bounding cube that the input\n" ); printf( "\t\t samples should fit into.\n" ); printf( "\t[--%s <minimum number of samples per node>=%f]\n" , SamplesPerNode.name, SamplesPerNode.value ); printf( "\t\t This parameter specifies the minimum number of points that\n" ); printf( "\t\t should fall within an octree node.\n" ); printf( "\t[--%s <interpolation weight>=%f]\n" , PointWeight.name , PointWeight.value ); printf( "\t\t This value specifies the weight that point interpolation constraints are\n" ); printf( "\t\t given when defining the (screened) Poisson system.\n" ); printf( "\t[--%s <iterations>=%d]\n" , Iters.name , Iters.value ); printf( "\t\t This flag specifies the (maximum if CG) number of solver iterations.\n" ); printf( "\t[--%s <pull factor>]\n" , Color.name ); printf( "\t\t This flag specifies the pull factor for color interpolation\n" ); #ifdef _OPENMP printf( "\t[--%s <num threads>=%d]\n" , Threads.name , Threads.value ); printf( "\t\t This parameter specifies the number of threads across which\n" ); printf( "\t\t the solver should be parallelized.\n" ); #endif // _OPENMP printf( "\t[--%s]\n" , Confidence.name ); printf( "\t\t If this flag is enabled, the size of a sample's normals is\n" ); printf( "\t\t used as a confidence value, affecting the sample's\n" ); printf( "\t\t constribution to the reconstruction process.\n" ); printf( "\t[--%s]\n" , NormalWeights.name ); printf( "\t\t If this flag is enabled, the size of a sample's normals is\n" ); printf( "\t\t used as to modulate the interpolation weight.\n" ); #if 0 printf( "\t[--%s]\n" , NonManifold.name ); printf( "\t\t If this flag is enabled, the isosurface extraction does not add\n" ); printf( "\t\t a planar polygon's barycenter in order to ensure that the output\n" ); printf( "\t\t mesh is manifold.\n" ); #endif printf( "\t[--%s]\n" , PolygonMesh.name); printf( "\t\t If this flag is enabled, the isosurface extraction returns polygons\n" ); printf( "\t\t rather than triangles.\n" ); #if 0 printf( "\t[--%s <minimum depth>=%d]\n" , MinDepth.name , MinDepth.value ); printf( "\t\t This flag specifies the coarsest depth at which the system is to be solved.\n" ); printf( "\t[--%s <cg solver accuracy>=%g]\n" , CSSolverAccuracy.name , CSSolverAccuracy.value ); printf( "\t\t This flag specifies the accuracy cut-off to be used for CG.\n" ); printf( "\t[--%s <adaptive weighting exponent>=%d]\n", AdaptiveExponent.name , AdaptiveExponent.value ); printf( "\t\t This flag specifies the exponent scale for the adaptive weighting.\n" ); #ifdef _WIN32 printf( "\t[--%s]\n" , Performance.name ); printf( "\t\t If this flag is enabled, the running time and peak memory usage\n" ); printf( "\t\t is output after the reconstruction.\n" ); #endif // _WIN32 #endif printf( "\t[--%s]\n" , Density.name ); printf( "\t\t If this flag is enabled, the sampling density is written out with the vertices.\n" ); #if 0 printf( "\t[--%s]\n" , ASCII.name ); printf( "\t\t If this flag is enabled, the output file is written out in ASCII format.\n" ); printf( "\t[--%s]\n" , NoComments.name ); printf( "\t\t If this flag is enabled, the output file will not include comments.\n" ); #endif printf( "\t[--%s]\n" , Double.name ); printf( "\t\t If this flag is enabled, the reconstruction will be performed with double-precision floats.\n" ); printf( "\t[--%s]\n" , Verbose.name ); printf( "\t\t If this flag is enabled, the progress of the reconstructor will be output to STDOUT.\n" ); } Point3D< unsigned char > ReadASCIIColor( FILE* fp ) { Point3D< unsigned char > c; if( fscanf( fp , " %c %c %c " , &c[0] , &c[1] , &c[2] )!=3 ) fprintf( stderr , "[ERROR] Failed to read color\n" ) , exit( 0 ); return c; } PlyProperty PlyColorProperties[]= { { "r" , PLY_UCHAR , PLY_UCHAR , int( offsetof( Point3D< unsigned char > , coords[0] ) ) , 0 , 0 , 0 , 0 } , { "g" , PLY_UCHAR , PLY_UCHAR , int( offsetof( Point3D< unsigned char > , coords[1] ) ) , 0 , 0 , 0 , 0 } , { "b" , PLY_UCHAR , PLY_UCHAR , int( offsetof( Point3D< unsigned char > , coords[2] ) ) , 0 , 0 , 0 , 0 } , { "red" , PLY_UCHAR , PLY_UCHAR , int( offsetof( Point3D< unsigned char > , coords[0] ) ) , 0 , 0 , 0 , 0 } , { "green" , PLY_UCHAR , PLY_UCHAR , int( offsetof( Point3D< unsigned char > , coords[1] ) ) , 0 , 0 , 0 , 0 } , { "blue" , PLY_UCHAR , PLY_UCHAR , int( offsetof( Point3D< unsigned char > , coords[2] ) ) , 0 , 0 , 0 , 0 } }; bool ValidPlyColorProperties( const bool* props ){ return ( props[0] || props[3] ) && ( props[1] || props[4] ) && ( props[2] || props[5] ); } template< class Real , class Vertex > int Execute( int argc , char* argv[] ) { Reset< Real >(); int paramNum = sizeof(params)/sizeof(cmdLineReadable*); std::vector< char* > comments; if( Verbose.set ) echoStdout=1; XForm4x4< Real > xForm , iXForm; if( XForm.set ) { FILE* fp = fopen( XForm.value , "r" ); if( !fp ) { fprintf( stderr , "[WARNING] Could not read x-form from: %s\n" , XForm.value ); xForm = XForm4x4< Real >::Identity(); } else { for( int i=0 ; i<4 ; i++ ) for( int j=0 ; j<4 ; j++ ) { float f; if( fscanf( fp , " %f " , &f )!=1 ) fprintf( stderr , "[ERROR] Execute: Failed to read xform\n" ) , exit( 0 ); xForm(i,j) = (Real)f; } fclose( fp ); } } else xForm = XForm4x4< Real >::Identity(); iXForm = xForm.inverse(); DumpOutput2( comments , "Running Screened Poisson Reconstruction (Version 7.0)\n" ); char str[1024]; for( int i=0 ; i<paramNum ; i++ ) if( params[i]->set ) { params[i]->writeValue( str ); if( strlen( str ) ) DumpOutput2( comments , "\t--%s %s\n" , params[i]->name , str ); else DumpOutput2( comments , "\t--%s\n" , params[i]->name ); } double t; double tt=Time(); Real isoValue = 0; Octree< Real > tree; tree.threads = Threads.value; if( !In.set ) { ShowUsage(argv[0]); return 0; } if( !MaxSolveDepth.set ) MaxSolveDepth.value = Depth.value; OctNode< TreeNodeData >::SetAllocator( MEMORY_ALLOCATOR_BLOCK_SIZE ); t=Time(); int kernelDepth = KernelDepth.set ? KernelDepth.value : Depth.value-2; if( kernelDepth>Depth.value ) { fprintf( stderr,"[ERROR] %s can't be greater than %s: %d <= %d\n" , KernelDepth.name , Depth.name , KernelDepth.value , Depth.value ); return EXIT_FAILURE; } double maxMemoryUsage; t=Time() , tree.maxMemoryUsage=0; typename Octree< Real >::template SparseNodeData< typename Octree< Real >::PointData >* pointInfo = new typename Octree< Real >::template SparseNodeData< typename Octree< Real >::PointData >(); typename Octree< Real >::template SparseNodeData< Point3D< Real > >* normalInfo = new typename Octree< Real >::template SparseNodeData< Point3D< Real > >(); std::vector< Real >* kernelDensityWeights = new std::vector< Real >(); std::vector< Real >* centerWeights = new std::vector< Real >(); int pointCount; typedef typename Octree< Real >::template ProjectiveData< Point3D< Real > > ProjectiveColor; typename Octree< Real >::template SparseNodeData< ProjectiveColor > colorData; char* ext = GetFileExtension( In.value ); if( Color.set && Color.value>0 ) { OrientedPointStreamWithData< float , Point3D< unsigned char > >* pointStream; if ( !strcasecmp( ext , "bnpts" ) ) pointStream = new BinaryOrientedPointStreamWithData< float , Point3D< unsigned char > >( In.value ); else if( !strcasecmp( ext , "ply" ) ) pointStream = new PLYOrientedPointStreamWithData< float , Point3D< unsigned char > >( In.value , PlyColorProperties , 6 , ValidPlyColorProperties ); else pointStream = new ASCIIOrientedPointStreamWithData< float , Point3D< unsigned char > >( In.value , ReadASCIIColor ); pointCount = tree.template SetTree< float >( pointStream , MinDepth.value , Depth.value , FullDepth.value , kernelDepth , Real(SamplesPerNode.value) , Scale.value , Confidence.set , NormalWeights.set , PointWeight.value , AdaptiveExponent.value , *kernelDensityWeights , *pointInfo , *normalInfo , *centerWeights , colorData , xForm , BoundaryType.value , Complete.set ); delete pointStream; for( const OctNode< TreeNodeData >* n = tree.tree.nextNode() ; n!=NULL ; n=tree.tree.nextNode( n ) ) { int idx = colorData.index( n ); if( idx>=0 ) colorData.data[idx] *= (Real)pow( Color.value , n->depth() ); } } else { OrientedPointStream< float >* pointStream; if ( !strcasecmp( ext , "bnpts" ) ) pointStream = new BinaryOrientedPointStream< float >( In.value ); else if( !strcasecmp( ext , "ply" ) ) pointStream = new PLYOrientedPointStream< float >( In.value ); else pointStream = new ASCIIOrientedPointStream< float >( In.value ); pointCount = tree.template SetTree< float >( pointStream , MinDepth.value , Depth.value , FullDepth.value , kernelDepth , Real(SamplesPerNode.value) , Scale.value , Confidence.set , NormalWeights.set , PointWeight.value , AdaptiveExponent.value , *kernelDensityWeights , *pointInfo , *normalInfo , *centerWeights , xForm , BoundaryType.value , Complete.set ); delete pointStream; } delete[] ext; if( !Density.set ) delete kernelDensityWeights , kernelDensityWeights = NULL; DumpOutput2( comments , "# Tree set in: %9.1f (s), %9.1f (MB)\n" , Time()-t , tree.maxMemoryUsage ); DumpOutput( "Input Points: %d\n" , pointCount ); DumpOutput( "Leaves/Nodes: %d/%d\n" , tree.tree.leaves() , tree.tree.nodes() ); DumpOutput( "Memory Usage: %.3f MB\n" , float( MemoryInfo::Usage() )/(1<<20) ); maxMemoryUsage = tree.maxMemoryUsage; t=Time() , tree.maxMemoryUsage=0; Pointer( Real ) constraints = tree.SetLaplacianConstraints( *normalInfo ); delete normalInfo; DumpOutput2( comments , "# Constraints set in: %9.1f (s), %9.1f (MB)\n" , Time()-t , tree.maxMemoryUsage ); DumpOutput( "Memory Usage: %.3f MB\n" , float( MemoryInfo::Usage())/(1<<20) ); maxMemoryUsage = std::max< double >( maxMemoryUsage , tree.maxMemoryUsage ); t=Time() , tree.maxMemoryUsage=0; Pointer( Real ) solution = tree.SolveSystem( *pointInfo , constraints , ShowResidual.set , Iters.value , MaxSolveDepth.value , CGDepth.value , CSSolverAccuracy.value ); delete pointInfo; FreePointer( constraints ); DumpOutput2( comments , "# Linear system solved in: %9.1f (s), %9.1f (MB)\n" , Time()-t , tree.maxMemoryUsage ); DumpOutput( "Memory Usage: %.3f MB\n" , float( MemoryInfo::Usage() )/(1<<20) ); maxMemoryUsage = std::max< double >( maxMemoryUsage , tree.maxMemoryUsage ); CoredFileMeshData< Vertex > mesh; if( Verbose.set ) tree.maxMemoryUsage=0; t=Time(); isoValue = tree.GetIsoValue( solution , *centerWeights ); delete centerWeights; DumpOutput( "Got average in: %f\n" , Time()-t ); DumpOutput( "Iso-Value: %e\n" , isoValue ); Real scale = tree.GetScale(); // std::cout<<"iso value: "<<isoValue<<std::endl; // std::cout<<"scale: "<<scale<<std::endl; Point3D<Real> center = tree.GetCenter(); // std::cout<<"center: "<<center[0]<<", "<<center[1]<<", "<<center[2]<<std::endl; if( VoxelGrid.set ) { double t = Time(); FILE* fp = fopen( VoxelGrid.value , "wb" ); if( !fp ) fprintf( stderr , "Failed to open voxel file for writing: %s\n" , VoxelGrid.value ); else { int res = 0; Pointer( Real ) values = tree.Evaluate( ( ConstPointer( Real ) )solution , res , isoValue , VoxelDepth.value ); fwrite(&res , sizeof(int) , 1 , fp ); fwrite(&scale, sizeof(float), 1, fp); fwrite(&center, sizeof(float), 3, fp); // std::cout<<"res: "<<res<<std::endl; // for( int i=0 ; i<res*res*res ; i++ ) { // std::cout << float( values[i] )<<" "; // } // std::cout<<std::endl; if( sizeof(Real)==sizeof(float) ) fwrite( values , sizeof(float) , res*res*res , fp ); else { float *fValues = new float[res*res*res]; for( int i=0 ; i<res*res*res ; i++ ){ fValues[i] = float( values[i] ); } fwrite( fValues , sizeof(float) , res*res*res , fp ); delete[] fValues; } fclose( fp ); DeletePointer( values ); } DumpOutput( "Got voxel grid in: %f\n" , Time()-t ); } if( Out.set ) { t = Time() , tree.maxMemoryUsage = 0; tree.GetMCIsoSurface( kernelDensityWeights ? GetPointer( *kernelDensityWeights ) : NullPointer( Real ) , Color.set ? &colorData : NULL , solution , isoValue , mesh , true , !NonManifold.set , PolygonMesh.set ); if( PolygonMesh.set ) DumpOutput2( comments , "# Got polygons in: %9.1f (s), %9.1f (MB)\n" , Time()-t , tree.maxMemoryUsage ); else DumpOutput2( comments , "# Got triangles in: %9.1f (s), %9.1f (MB)\n" , Time()-t , tree.maxMemoryUsage ); maxMemoryUsage = std::max< double >( maxMemoryUsage , tree.maxMemoryUsage ); DumpOutput2( comments , "# Total Solve: %9.1f (s), %9.1f (MB)\n" , Time()-tt , maxMemoryUsage ); if( NoComments.set ) { if( ASCII.set ) PlyWritePolygons( Out.value , &mesh , PLY_ASCII , NULL , 0 , iXForm ); else PlyWritePolygons( Out.value , &mesh , PLY_BINARY_NATIVE , NULL , 0 , iXForm ); } else { if( ASCII.set ) PlyWritePolygons( Out.value , &mesh , PLY_ASCII , &comments[0] , (int)comments.size() , iXForm ); else PlyWritePolygons( Out.value , &mesh , PLY_BINARY_NATIVE , &comments[0] , (int)comments.size() , iXForm ); } DumpOutput( "Vertices / Polygons: %d / %d\n" , mesh.outOfCorePointCount()+mesh.inCorePoints.size() , mesh.polygonCount() ); } FreePointer( solution ); return 1; } #ifdef _WIN32 inline double to_seconds( const FILETIME& ft ) { const double low_to_sec=100e-9; // 100 nanoseconds const double high_to_sec=low_to_sec*4294967296.0; return ft.dwLowDateTime*low_to_sec+ft.dwHighDateTime*high_to_sec; } #endif // _WIN32 #if 0 int poissonRecon( const char* input_file_name, const char * output_filename) { #if defined(WIN32) && defined(MAX_MEMORY_GB) if( MAX_MEMORY_GB>0 ) { SIZE_T peakMemory = 1; peakMemory <<= 30; peakMemory *= MAX_MEMORY_GB; printf( "Limiting memory usage to %.2f GB\n" , float( peakMemory>>30 ) ); HANDLE h = CreateJobObject( NULL , NULL ); AssignProcessToJobObject( h , GetCurrentProcess() ); JOBOBJECT_EXTENDED_LIMIT_INFORMATION jeli = { 0 }; jeli.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_JOB_MEMORY; jeli.JobMemoryLimit = peakMemory; if( !SetInformationJobObject( h , JobObjectExtendedLimitInformation , &jeli , sizeof( jeli ) ) ) fprintf( stderr , "Failed to set memory limit\n" ); } #endif // defined(WIN32) && defined(MAX_MEMORY_GB) typedef float Real; typedef PlyValueVertex< float > Vertex; Verbose.set= false; In.set = true; In.value = const_cast<char*>(input_file_name); Out.set = true; Out.value = const_cast<char*>(output_filename); Density.set =true; Depth.set = true; Depth.value = 6; Verbose.set = true; Reset< Real >(); int paramNum = sizeof(params)/sizeof(cmdLineReadable*); std::vector< char* > comments; if( Verbose.set ) echoStdout=1; XForm4x4< Real > xForm , iXForm; xForm = XForm4x4< Real >::Identity(); iXForm = xForm.inverse(); double t; double tt=Time(); Real isoValue = 0; Octree< Real > tree; tree.threads = Threads.value; if( !In.set ) { //ShowUsage(argv[0]); return 0; } if( !MaxSolveDepth.set ) MaxSolveDepth.value = Depth.value; OctNode< TreeNodeData >::SetAllocator( MEMORY_ALLOCATOR_BLOCK_SIZE ); t=Time(); int kernelDepth = KernelDepth.set ? KernelDepth.value : Depth.value-2; if( kernelDepth>Depth.value ) { fprintf( stderr,"[ERROR] %s can't be greater than %s: %d <= %d\n" , KernelDepth.name , Depth.name , KernelDepth.value , Depth.value ); return EXIT_FAILURE; } double maxMemoryUsage; t=Time() , tree.maxMemoryUsage=0; typename Octree< Real >::template SparseNodeData< typename Octree< Real >::PointData >* pointInfo = new typename Octree< Real >::template SparseNodeData< typename Octree< Real >::PointData >(); typename Octree< Real >::template SparseNodeData< Point3D< Real > >* normalInfo = new typename Octree< Real >::template SparseNodeData< Point3D< Real > >(); std::vector< Real >* kernelDensityWeights = new std::vector< Real >(); std::vector< Real >* centerWeights = new std::vector< Real >(); int pointCount; typedef typename Octree< Real >::template ProjectiveData< Point3D< Real > > ProjectiveColor; typename Octree< Real >::template SparseNodeData< ProjectiveColor > colorData; char* ext = GetFileExtension( In.value ); if( Color.set && Color.value>0 ) { OrientedPointStreamWithData< float , Point3D< unsigned char > >* pointStream; if ( !strcasecmp( ext , "bnpts" ) ) pointStream = new BinaryOrientedPointStreamWithData< float , Point3D< unsigned char > >( In.value ); else if( !strcasecmp( ext , "ply" ) ) pointStream = new PLYOrientedPointStreamWithData< float , Point3D< unsigned char > >( In.value , PlyColorProperties , 6 , ValidPlyColorProperties ); else pointStream = new ASCIIOrientedPointStreamWithData< float , Point3D< unsigned char > >( In.value , ReadASCIIColor ); pointCount = tree.template SetTree< float >( pointStream , MinDepth.value , Depth.value , FullDepth.value , kernelDepth , Real(SamplesPerNode.value) , Scale.value , Confidence.set , NormalWeights.set , PointWeight.value , AdaptiveExponent.value , *kernelDensityWeights , *pointInfo , *normalInfo , *centerWeights , colorData , xForm , BoundaryType.value , Complete.set ); delete pointStream; for( const OctNode< TreeNodeData >* n = tree.tree.nextNode() ; n!=NULL ; n=tree.tree.nextNode( n ) ) { int idx = colorData.index( n ); if( idx>=0 ) colorData.data[idx] *= (Real)pow( Color.value , n->depth() ); } } else { OrientedPointStream< float >* pointStream; if ( !strcasecmp( ext , "bnpts" ) ) pointStream = new BinaryOrientedPointStream< float >( In.value ); else if( !strcasecmp( ext , "ply" ) ) pointStream = new PLYOrientedPointStream< float >( In.value ); else pointStream = new ASCIIOrientedPointStream< float >( In.value ); pointCount = tree.template SetTree< float >( pointStream , MinDepth.value , Depth.value , FullDepth.value , kernelDepth , Real(SamplesPerNode.value) , Scale.value , Confidence.set , NormalWeights.set , PointWeight.value , AdaptiveExponent.value , *kernelDensityWeights , *pointInfo , *normalInfo , *centerWeights , xForm , BoundaryType.value , Complete.set ); delete pointStream; } delete[] ext; if( !Density.set ) delete kernelDensityWeights , kernelDensityWeights = NULL; DumpOutput2( comments , "# Tree set in: %9.1f (s), %9.1f (MB)\n" , Time()-t , tree.maxMemoryUsage ); DumpOutput( "Input Points: %d\n" , pointCount ); DumpOutput( "Leaves/Nodes: %d/%d\n" , tree.tree.leaves() , tree.tree.nodes() ); DumpOutput( "Memory Usage: %.3f MB\n" , float( MemoryInfo::Usage() )/(1<<20) ); maxMemoryUsage = tree.maxMemoryUsage; t=Time() , tree.maxMemoryUsage=0; Pointer( Real ) constraints = tree.SetLaplacianConstraints( *normalInfo ); delete normalInfo; DumpOutput2( comments , "# Constraints set in: %9.1f (s), %9.1f (MB)\n" , Time()-t , tree.maxMemoryUsage ); DumpOutput( "Memory Usage: %.3f MB\n" , float( MemoryInfo::Usage())/(1<<20) ); maxMemoryUsage = std::max< double >( maxMemoryUsage , tree.maxMemoryUsage ); t=Time() , tree.maxMemoryUsage=0; Pointer( Real ) solution = tree.SolveSystem( *pointInfo , constraints , ShowResidual.set , Iters.value , MaxSolveDepth.value , CGDepth.value , CSSolverAccuracy.value ); delete pointInfo; FreePointer( constraints ); DumpOutput2( comments , "# Linear system solved in: %9.1f (s), %9.1f (MB)\n" , Time()-t , tree.maxMemoryUsage ); DumpOutput( "Memory Usage: %.3f MB\n" , float( MemoryInfo::Usage() )/(1<<20) ); maxMemoryUsage = std::max< double >( maxMemoryUsage , tree.maxMemoryUsage ); CoredFileMeshData< Vertex > mesh; if( Verbose.set ) tree.maxMemoryUsage=0; t=Time(); isoValue = tree.GetIsoValue( solution , *centerWeights ); delete centerWeights; DumpOutput( "Got average in: %f\n" , Time()-t ); DumpOutput( "Iso-Value: %e\n" , isoValue ); Real scale = tree.GetScale(); std::cout<<"iso value: "<<isoValue<<std::endl; std::cout<<"scale: "<<scale<<std::endl; Point3D<Real> center = tree.GetCenter(); std::cout<<"center: "<<center[0]<<", "<<center[1]<<", "<<center[2]<<std::endl; if( VoxelGrid.set ) { double t = Time(); FILE* fp = fopen( VoxelGrid.value , "wb" ); if( !fp ) fprintf( stderr , "Failed to open voxel file for writing: %s\n" , VoxelGrid.value ); else { int res = 0; Pointer( Real ) values = tree.Evaluate( ( ConstPointer( Real ) )solution , res , isoValue , VoxelDepth.value ); fwrite(&res , sizeof(int) , 1 , fp ); fwrite(&scale, sizeof(float), 1, fp); fwrite(&center, sizeof(float), 3, fp); // std::cout<<"res: "<<res<<std::endl; // for( int i=0 ; i<res*res*res ; i++ ) { // std::cout << float( values[i] )<<" "; // } // std::cout<<std::endl; if( sizeof(Real)==sizeof(float) ) fwrite( values , sizeof(float) , res*res*res , fp ); else { float *fValues = new float[res*res*res]; for( int i=0 ; i<res*res*res ; i++ ){ fValues[i] = float( values[i] ); } fwrite( fValues , sizeof(float) , res*res*res , fp ); delete[] fValues; } fclose( fp ); DeletePointer( values ); } DumpOutput( "Got voxel grid in: %f\n" , Time()-t ); } if( Out.set ) { // t = Time() , tree.maxMemoryUsage = 0; // tree.GetMCIsoSurface( kernelDensityWeights ? GetPointer( *kernelDensityWeights ) : NullPointer( Real ) , Color.set ? &colorData : NULL , solution , isoValue , mesh , true , !NonManifold.set , PolygonMesh.set ); // if( PolygonMesh.set ) DumpOutput2( comments , "# Got polygons in: %9.1f (s), %9.1f (MB)\n" , Time()-t , tree.maxMemoryUsage ); // else DumpOutput2( comments , "# Got triangles in: %9.1f (s), %9.1f (MB)\n" , Time()-t , tree.maxMemoryUsage ); // maxMemoryUsage = std::max< double >( maxMemoryUsage , tree.maxMemoryUsage ); // DumpOutput2( comments , "# Total Solve: %9.1f (s), %9.1f (MB)\n" , Time()-tt , maxMemoryUsage ); // // if( NoComments.set ) // { // if( ASCII.set ) PlyWritePolygons( Out.value , &mesh , PLY_ASCII , NULL , 0 , iXForm ); // else PlyWritePolygons( Out.value , &mesh , PLY_BINARY_NATIVE , NULL , 0 , iXForm ); // } // else // { // if( ASCII.set ) PlyWritePolygons( Out.value , &mesh , PLY_ASCII , &comments[0] , (int)comments.size() , iXForm ); // else PlyWritePolygons( Out.value , &mesh , PLY_BINARY_NATIVE , &comments[0] , (int)comments.size() , iXForm ); // } // DumpOutput( "Vertices / Polygons: %d / %d\n" , mesh.outOfCorePointCount()+mesh.inCorePoints.size() , mesh.polygonCount() ); } FreePointer( solution ); #ifdef _WIN32 if( Performance.set ) { HANDLE cur_thread=GetCurrentThread(); FILETIME tcreat, texit, tkernel, tuser; if( GetThreadTimes( cur_thread , &tcreat , &texit , &tkernel , &tuser ) ) printf( "Time (Wall/User/Kernel): %.2f / %.2f / %.2f\n" , Time()-t , to_seconds( tuser ) , to_seconds( tkernel ) ); else printf( "Time: %.2f\n" , Time()-t ); HANDLE h = GetCurrentProcess(); PROCESS_MEMORY_COUNTERS pmc; if( GetProcessMemoryInfo( h , &pmc , sizeof(pmc) ) ) printf( "Peak Memory (MB): %d\n" , pmc.PeakWorkingSetSize>>20 ); } #endif // _WIN32 return EXIT_SUCCESS; } #endif int poissonRecon( int argc , char**argv) { #if defined(WIN32) && defined(MAX_MEMORY_GB) if( MAX_MEMORY_GB>0 ) { SIZE_T peakMemory = 1; peakMemory <<= 30; peakMemory *= MAX_MEMORY_GB; printf( "Limiting memory usage to %.2f GB\n" , float( peakMemory>>30 ) ); HANDLE h = CreateJobObject( NULL , NULL ); AssignProcessToJobObject( h , GetCurrentProcess() ); JOBOBJECT_EXTENDED_LIMIT_INFORMATION jeli = { 0 }; jeli.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_JOB_MEMORY; jeli.JobMemoryLimit = peakMemory; if( !SetInformationJobObject( h , JobObjectExtendedLimitInformation , &jeli , sizeof( jeli ) ) ) fprintf( stderr , "Failed to set memory limit\n" ); } #endif // defined(WIN32) && defined(MAX_MEMORY_GB) double t = Time(); cmdLineParse( argc-1 , &argv[1] , sizeof(params)/sizeof(cmdLineReadable*) , params , 1 ); if( Density.set ) if( Color.set ) if( Double.set ) Execute< double , PlyColorAndValueVertex< float > >( argc , argv ); else Execute< float , PlyColorAndValueVertex< float > >( argc , argv ); else if( Double.set ) Execute< double , PlyValueVertex< float > >( argc , argv ); else Execute< float , PlyValueVertex< float > >( argc , argv );// else if( Color.set ) if( Double.set ) Execute< double , PlyColorVertex< float > >( argc , argv ); else Execute< float , PlyColorVertex< float > >( argc , argv ); else if( Double.set ) Execute< double , PlyVertex< float > >( argc , argv ); else Execute< float , PlyVertex< float > >( argc , argv ); #ifdef _WIN32 if( Performance.set ) { HANDLE cur_thread=GetCurrentThread(); FILETIME tcreat, texit, tkernel, tuser; if( GetThreadTimes( cur_thread , &tcreat , &texit , &tkernel , &tuser ) ) printf( "Time (Wall/User/Kernel): %.2f / %.2f / %.2f\n" , Time()-t , to_seconds( tuser ) , to_seconds( tkernel ) ); else printf( "Time: %.2f\n" , Time()-t ); HANDLE h = GetCurrentProcess(); PROCESS_MEMORY_COUNTERS pmc; if( GetProcessMemoryInfo( h , &pmc , sizeof(pmc) ) ) printf( "Peak Memory (MB): %d\n" , pmc.PeakWorkingSetSize>>20 ); } #endif // _WIN32 return EXIT_SUCCESS; } int poisson(const char *input_file_name, const char *output_filename, int depth) { typedef float Real; typedef PlyValueVertex< float > Vertex; In.set = true; In.value=new char[strlen(input_file_name)+1]; stpcpy(In.value, input_file_name); Out.set = true; Out.value=new char[strlen(output_filename)+1]; stpcpy(Out.value, output_filename); Density.set = false; // there is no need to trimmer surface in the surgical guide generation stage Depth.set = true; Depth.value = depth; Verbose.set = true; ASCII.set=true; Threads.value = 8; Reset< Real >(); int paramNum = sizeof(params)/sizeof(cmdLineReadable*); std::vector< char* > comments; if( Verbose.set ) echoStdout=1; XForm4x4< Real > xForm , iXForm; xForm = XForm4x4< Real >::Identity(); iXForm = xForm.inverse(); DumpOutput2( comments , "Running Screened Poisson Reconstruction (Version 7.0)\n" ); double t; double tt=Time(); Real isoValue = 0; Octree< Real > tree; tree.threads = Threads.value; if( !In.set ) { //ShowUsage(argv[0]); return 0; } if( !MaxSolveDepth.set ) MaxSolveDepth.value = Depth.value; OctNode< TreeNodeData >::SetAllocator( MEMORY_ALLOCATOR_BLOCK_SIZE ); t=Time(); int kernelDepth = KernelDepth.set ? KernelDepth.value : Depth.value-2; if( kernelDepth>Depth.value ) { fprintf( stderr,"[ERROR] %s can't be greater than %s: %d <= %d\n" , KernelDepth.name , Depth.name , KernelDepth.value , Depth.value ); return EXIT_FAILURE; } double maxMemoryUsage; t=Time() , tree.maxMemoryUsage=0; typename Octree< Real >::template SparseNodeData< typename Octree< Real >::PointData >* pointInfo = new typename Octree< Real >::template SparseNodeData< typename Octree< Real >::PointData >(); typename Octree< Real >::template SparseNodeData< Point3D< Real > >* normalInfo = new typename Octree< Real >::template SparseNodeData< Point3D< Real > >(); std::vector< Real >* kernelDensityWeights = new std::vector< Real >(); std::vector< Real >* centerWeights = new std::vector< Real >(); int pointCount; typedef typename Octree< Real >::template ProjectiveData< Point3D< Real > > ProjectiveColor; typename Octree< Real >::template SparseNodeData< ProjectiveColor > colorData; char* ext = GetFileExtension( In.value ); if( Color.set && Color.value>0 ) { OrientedPointStreamWithData< float , Point3D< unsigned char > >* pointStream; if ( !strcasecmp( ext , "bnpts" ) ) pointStream = new BinaryOrientedPointStreamWithData< float , Point3D< unsigned char > >( In.value ); else if( !strcasecmp( ext , "ply" ) ) pointStream = new PLYOrientedPointStreamWithData< float , Point3D< unsigned char > >( In.value , PlyColorProperties , 6 , ValidPlyColorProperties ); else pointStream = new ASCIIOrientedPointStreamWithData< float , Point3D< unsigned char > >( In.value , ReadASCIIColor ); pointCount = tree.template SetTree< float >( pointStream , MinDepth.value , Depth.value , FullDepth.value , kernelDepth , Real(SamplesPerNode.value) , Scale.value , Confidence.set , NormalWeights.set , PointWeight.value , AdaptiveExponent.value , *kernelDensityWeights , *pointInfo , *normalInfo , *centerWeights , colorData , xForm , BoundaryType.value , Complete.set ); delete pointStream; for( const OctNode< TreeNodeData >* n = tree.tree.nextNode() ; n!=NULL ; n=tree.tree.nextNode( n ) ) { int idx = colorData.index( n ); if( idx>=0 ) colorData.data[idx] *= (Real)pow( Color.value , n->depth() ); } } else { OrientedPointStream< float >* pointStream; if ( !strcasecmp( ext , "bnpts" ) ) pointStream = new BinaryOrientedPointStream< float >( In.value ); else if( !strcasecmp( ext , "ply" ) ) pointStream = new PLYOrientedPointStream< float >( In.value ); else pointStream = new ASCIIOrientedPointStream< float >( In.value ); pointCount = tree.template SetTree< float >( pointStream , MinDepth.value , Depth.value , FullDepth.value , kernelDepth , Real(SamplesPerNode.value) , Scale.value , Confidence.set , NormalWeights.set , PointWeight.value , AdaptiveExponent.value , *kernelDensityWeights , *pointInfo , *normalInfo , *centerWeights , xForm , BoundaryType.value , Complete.set ); delete pointStream; } delete[] ext; if( !Density.set ) delete kernelDensityWeights , kernelDensityWeights = NULL; DumpOutput2( comments , "# Tree set in: %9.1f (s), %9.1f (MB)\n" , Time()-t , tree.maxMemoryUsage ); DumpOutput( "Input Points: %d\n" , pointCount ); DumpOutput( "Leaves/Nodes: %d/%d\n" , tree.tree.leaves() , tree.tree.nodes() ); DumpOutput( "Memory Usage: %.3f MB\n" , float( MemoryInfo::Usage() )/(1<<20) ); maxMemoryUsage = tree.maxMemoryUsage; t=Time() , tree.maxMemoryUsage=0; Pointer( Real ) constraints = tree.SetLaplacianConstraints( *normalInfo ); delete normalInfo; DumpOutput2( comments , "# Constraints set in: %9.1f (s), %9.1f (MB)\n" , Time()-t , tree.maxMemoryUsage ); DumpOutput( "Memory Usage: %.3f MB\n" , float( MemoryInfo::Usage())/(1<<20) ); maxMemoryUsage = std::max< double >( maxMemoryUsage , tree.maxMemoryUsage ); t=Time() , tree.maxMemoryUsage=0; Pointer( Real ) solution = tree.SolveSystem( *pointInfo , constraints , ShowResidual.set , Iters.value , MaxSolveDepth.value , CGDepth.value , CSSolverAccuracy.value ); delete pointInfo; FreePointer( constraints ); DumpOutput2( comments , "# Linear system solved in: %9.1f (s), %9.1f (MB)\n" , Time()-t , tree.maxMemoryUsage ); DumpOutput( "Memory Usage: %.3f MB\n" , float( MemoryInfo::Usage() )/(1<<20) ); maxMemoryUsage = std::max< double >( maxMemoryUsage , tree.maxMemoryUsage ); CoredFileMeshData< Vertex > mesh; if( Verbose.set ) tree.maxMemoryUsage=0; t=Time(); isoValue = tree.GetIsoValue( solution , *centerWeights ); delete centerWeights; DumpOutput( "Got average in: %f\n" , Time()-t ); DumpOutput( "Iso-Value: %e\n" , isoValue ); Real scale = tree.GetScale(); //std::cout<<"iso value: "<<isoValue<<std::endl; //std::cout<<"scale: "<<scale<<std::endl; Point3D<Real> center = tree.GetCenter(); //std::cout<<"center: "<<center[0]<<", "<<center[1]<<", "<<center[2]<<std::endl; if( VoxelGrid.set ) { double t = Time(); FILE* fp = fopen( VoxelGrid.value , "wb" ); if( !fp ) fprintf( stderr , "Failed to open voxel file for writing: %s\n" , VoxelGrid.value ); else { int res = 0; Pointer( Real ) values = tree.Evaluate( ( ConstPointer( Real ) )solution , res , isoValue , VoxelDepth.value ); fwrite(&res , sizeof(int) , 1 , fp ); fwrite(&scale, sizeof(float), 1, fp); fwrite(&center, sizeof(float), 3, fp); // std::cout<<"res: "<<res<<std::endl; // for( int i=0 ; i<res*res*res ; i++ ) { // std::cout << float( values[i] )<<" "; // } // std::cout<<std::endl; if( sizeof(Real)==sizeof(float) ) fwrite( values , sizeof(float) , res*res*res , fp ); else { float *fValues = new float[res*res*res]; for( int i=0 ; i<res*res*res ; i++ ){ fValues[i] = float( values[i] ); } fwrite( fValues , sizeof(float) , res*res*res , fp ); delete[] fValues; } fclose( fp ); DeletePointer( values ); } DumpOutput( "Got voxel grid in: %f\n" , Time()-t ); } if( Out.set ) { t = Time() , tree.maxMemoryUsage = 0; tree.GetMCIsoSurface( kernelDensityWeights ? GetPointer( *kernelDensityWeights ) : NullPointer( Real ) , Color.set ? &colorData : NULL , solution , isoValue , mesh , true , !NonManifold.set , PolygonMesh.set ); if( PolygonMesh.set ) DumpOutput2( comments , "# Got polygons in: %9.1f (s), %9.1f (MB)\n" , Time()-t , tree.maxMemoryUsage ); else DumpOutput2( comments , "# Got triangles in: %9.1f (s), %9.1f (MB)\n" , Time()-t , tree.maxMemoryUsage ); maxMemoryUsage = std::max< double >( maxMemoryUsage , tree.maxMemoryUsage ); DumpOutput2( comments , "# Total Solve: %9.1f (s), %9.1f (MB)\n" , Time()-tt , maxMemoryUsage ); if( NoComments.set ) { if( ASCII.set ) PlyWritePolygons( Out.value , &mesh , PLY_ASCII , NULL , 0 , iXForm ); else PlyWritePolygons( Out.value , &mesh , PLY_BINARY_NATIVE , NULL , 0 , iXForm ); } else { if( ASCII.set ) PlyWritePolygons( Out.value , &mesh , PLY_ASCII , &comments[0] , (int)comments.size() , iXForm ); else PlyWritePolygons( Out.value , &mesh , PLY_BINARY_NATIVE , &comments[0] , (int)comments.size() , iXForm ); } DumpOutput( "Vertices / Polygons: %d / %d\n" , mesh.outOfCorePointCount()+mesh.inCorePoints.size() , mesh.polygonCount() ); } FreePointer( solution ); }
40.795107
373
0.660645
MrCocoaCat
9c80f9ff88aacebe54b75a76d3c4ff6c762dfd55
5,247
cpp
C++
drlvm/vm/jitrino/src/codegenerator/ipf/IpfType.cpp
sirinath/Harmony
724deb045a85b722c961d8b5a83ac7a697319441
[ "Apache-2.0" ]
8
2015-11-04T06:06:35.000Z
2021-07-04T13:47:36.000Z
drlvm/vm/jitrino/src/codegenerator/ipf/IpfType.cpp
sirinath/Harmony
724deb045a85b722c961d8b5a83ac7a697319441
[ "Apache-2.0" ]
1
2021-10-17T13:07:28.000Z
2021-10-17T13:07:28.000Z
drlvm/vm/jitrino/src/codegenerator/ipf/IpfType.cpp
sirinath/Harmony
724deb045a85b722c961d8b5a83ac7a697319441
[ "Apache-2.0" ]
13
2015-11-27T03:14:50.000Z
2022-02-26T15:12:20.000Z
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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. */ /** * @author Intel, Konstantin M. Anisimov, Igor V. Chebykin * */ #include "IpfType.h" namespace Jitrino { namespace IPF { bool ipfLogIsOn = false; bool ipfVerifyIsOn = true; bool ipfConstantFolding = true; //============================================================================// // IpfType //============================================================================// int16 IpfType::getSize(DataKind dataKind) { switch(dataKind) { case DATA_BASE : return 8; case DATA_MPTR : return 8; case DATA_I8 : return 1; case DATA_U8 : return 1; case DATA_I16 : return 2; case DATA_U16 : return 2; case DATA_I32 : return 4; case DATA_U32 : return 4; case DATA_I64 : return 8; case DATA_U64 : return 8; case DATA_S : return 4; case DATA_D : return 8; case DATA_F : return 16; case DATA_P : return 1; case DATA_B : return 8; case DATA_IMM : return 8; case DATA_CONST_REF : return 8; case DATA_NODE_REF : return 8; case DATA_METHOD_REF : return 8; case DATA_SWITCH_REF : return 8; case DATA_INVALID : break; } IPF_ERR << " unexpected dataKind " << dataKind << endl; return 0; } //----------------------------------------------------------------------------------------// bool IpfType::isReg(OpndKind opndKind) { switch(opndKind) { case OPND_G_REG : case OPND_F_REG : case OPND_P_REG : case OPND_B_REG : case OPND_A_REG : case OPND_IP_REG : case OPND_UM_REG : return true; case OPND_IMM : return false; case OPND_INVALID : break; } IPF_ERR << " unexpected opndKind " << opndKind << endl; return 0; } //----------------------------------------------------------------------------------------// bool IpfType::isGReg(OpndKind opndKind) { switch(opndKind) { case OPND_G_REG : return true; case OPND_F_REG : case OPND_P_REG : case OPND_B_REG : case OPND_A_REG : case OPND_IP_REG : case OPND_UM_REG : case OPND_IMM : return false; case OPND_INVALID : break; } IPF_ERR << " unexpected opndKind " << opndKind << endl; return 0; } //----------------------------------------------------------------------------------------// bool IpfType::isFReg(OpndKind opndKind) { switch(opndKind) { case OPND_G_REG : return false; case OPND_F_REG : return true; case OPND_P_REG : case OPND_B_REG : case OPND_A_REG : case OPND_IP_REG : case OPND_UM_REG : case OPND_IMM : return false; case OPND_INVALID : break; } IPF_ERR << " unexpected opndKind " << opndKind << endl; return 0; } //----------------------------------------------------------------------------------------// bool IpfType::isImm(OpndKind opndKind) { switch(opndKind) { case OPND_G_REG : case OPND_F_REG : case OPND_P_REG : case OPND_B_REG : case OPND_A_REG : case OPND_IP_REG : case OPND_UM_REG : return false; case OPND_IMM : return true; case OPND_INVALID : break; } IPF_ERR << " unexpected opndKind " << opndKind << endl; return 0; } //----------------------------------------------------------------------------------------// bool IpfType::isSigned(DataKind dataKind) { switch(dataKind) { case DATA_I8 : case DATA_I16 : case DATA_I32 : case DATA_I64 : case DATA_S : case DATA_D : case DATA_F : return true; default : return false;; } } //----------------------------------------------------------------------------------------// bool IpfType::isFloating(DataKind dataKind) { switch(dataKind) { case DATA_S : case DATA_D : case DATA_F : return true; default : return false;; } } } // IPF } // Jitrino
29.8125
108
0.483705
sirinath
9c8310c2a2dea6ab25be8ccf42817c5a1bac54a4
957
hpp
C++
src/Evolution/Systems/NewtonianEuler/BoundaryConditions/BoundaryCondition.hpp
nilsvu/spectre
1455b9a8d7e92db8ad600c66f54795c29c3052ee
[ "MIT" ]
117
2017-04-08T22:52:48.000Z
2022-03-25T07:23:36.000Z
src/Evolution/Systems/NewtonianEuler/BoundaryConditions/BoundaryCondition.hpp
GitHimanshuc/spectre
4de4033ba36547113293fe4dbdd77591485a4aee
[ "MIT" ]
3,177
2017-04-07T21:10:18.000Z
2022-03-31T23:55:59.000Z
src/Evolution/Systems/NewtonianEuler/BoundaryConditions/BoundaryCondition.hpp
geoffrey4444/spectre
9350d61830b360e2d5b273fdd176dcc841dbefb0
[ "MIT" ]
85
2017-04-07T19:36:13.000Z
2022-03-01T10:21:00.000Z
// Distributed under the MIT License. // See LICENSE.txt for details. #pragma once #include <pup.h> #include "Domain/BoundaryConditions/BoundaryCondition.hpp" namespace NewtonianEuler { /// \brief Boundary conditions for the Newtonian Euler hydrodynamics system namespace BoundaryConditions { /// \brief The base class off of which all boundary conditions must inherit template <size_t Dim> class BoundaryCondition : public domain::BoundaryConditions::BoundaryCondition { public: BoundaryCondition() = default; BoundaryCondition(BoundaryCondition&&) = default; BoundaryCondition& operator=(BoundaryCondition&&) = default; BoundaryCondition(const BoundaryCondition&) = default; BoundaryCondition& operator=(const BoundaryCondition&) = default; ~BoundaryCondition() override = default; explicit BoundaryCondition(CkMigrateMessage* msg); void pup(PUP::er& p) override; }; } // namespace BoundaryConditions } // namespace NewtonianEuler
33
80
0.781609
nilsvu
9c83e8cb9572500dad8edbde3cd9091d57c3fae1
6,487
cpp
C++
ui-cpp/src/IsosurfaceWidget.cpp
MSallermann/spirit
d3b771bcbf2f1eb4b28d48899091c17a48f12c67
[ "MIT" ]
46
2020-08-24T22:40:15.000Z
2022-02-28T06:54:54.000Z
ui-cpp/src/IsosurfaceWidget.cpp
MSallermann/spirit
d3b771bcbf2f1eb4b28d48899091c17a48f12c67
[ "MIT" ]
null
null
null
ui-cpp/src/IsosurfaceWidget.cpp
MSallermann/spirit
d3b771bcbf2f1eb4b28d48899091c17a48f12c67
[ "MIT" ]
4
2020-09-05T13:24:41.000Z
2021-11-06T07:46:47.000Z
#include <QtWidgets> #include "IsosurfaceWidget.hpp" #include "SpinWidget.hpp" IsosurfaceWidget::IsosurfaceWidget(std::shared_ptr<State> state, SpinWidget *spinWidget, int i) { this->state = state; this->spinWidget = spinWidget; setAttribute(Qt::WA_DeleteOnClose); // Setup User Interface this->setupUi(this); // Create renderer pointer this->m_renderer = std::make_shared<VFRendering::IsosurfaceRenderer>(*spinWidget->view(), *spinWidget->vectorfield()); // Defaults this->setShowIsosurface(true); this->setIsovalue(0); this->setIsocomponent(2); this->setDrawShadows(false); if (i == 1) { this->setIsovalue(0.96); this->setIsocomponent(0); this->setDrawShadows(false); } if (i == 2) { this->setIsovalue(-0.96); this->setIsocomponent(0); this->setDrawShadows(false); } // Read values auto isovalue = this->isovalue(); horizontalSlider_isovalue->setRange(0, 100); horizontalSlider_isovalue->setValue((int)(isovalue + 1 * 50)); int component = this->isocomponent(); if (component == 0) this->radioButton_isosurface_x->setChecked(true); else if (component == 1) this->radioButton_isosurface_y->setChecked(true); else if (component == 2) this->radioButton_isosurface_z->setChecked(true); // Add this isosurface to the SpinWidget this->spinWidget->addIsosurface(m_renderer); // Connect Slots this->setupSlots(); // Input validation QRegularExpression re("[+|-]?[\\d]*[\\.]?[\\d]*"); this->number_validator = new QRegularExpressionValidator(re); this->setupInputValidators(); } bool IsosurfaceWidget::showIsosurface() { return this->m_show_isosurface; } void IsosurfaceWidget::setShowIsosurface(bool show) { this->m_show_isosurface = show; QTimer::singleShot(1, this->spinWidget, SLOT(update())); } float IsosurfaceWidget::isovalue() { return this->m_isovalue; } void IsosurfaceWidget::setIsovalue(float value) { this->m_isovalue = value; m_renderer->setOption<VFRendering::IsosurfaceRenderer::Option::ISOVALUE>(m_isovalue); QTimer::singleShot(1, this->spinWidget, SLOT(update())); } int IsosurfaceWidget::isocomponent() { return this->m_isocomponent; } void IsosurfaceWidget::setIsocomponent(int component) { this->m_isocomponent = component; if (this->m_isocomponent == 0) { m_renderer->setOption<VFRendering::IsosurfaceRenderer::Option::VALUE_FUNCTION>([](const glm::vec3& position, const glm::vec3& direction) -> VFRendering::IsosurfaceRenderer::isovalue_type { (void)position; return direction.x; }); } else if (this->m_isocomponent == 1) { m_renderer->setOption<VFRendering::IsosurfaceRenderer::Option::VALUE_FUNCTION>([](const glm::vec3& position, const glm::vec3& direction) -> VFRendering::IsosurfaceRenderer::isovalue_type { (void)position; return direction.y; }); } else if (this->m_isocomponent == 2) { m_renderer->setOption<VFRendering::IsosurfaceRenderer::Option::VALUE_FUNCTION>([](const glm::vec3& position, const glm::vec3& direction) -> VFRendering::IsosurfaceRenderer::isovalue_type { (void)position; return direction.z; }); } QTimer::singleShot(1, this->spinWidget, SLOT(update())); } bool IsosurfaceWidget::drawShadows() { return this->m_draw_shadows; } void IsosurfaceWidget::setDrawShadows(bool show) { this->m_draw_shadows = show; if (this->m_draw_shadows) { m_renderer->setOption<VFRendering::IsosurfaceRenderer::Option::LIGHTING_IMPLEMENTATION>( "uniform vec3 uLightPosition;" "float lighting(vec3 position, vec3 normal)" "{" " vec3 lightDirection = -normalize(uLightPosition-position);" " float diffuse = 0.7*max(0.0, dot(normal, lightDirection));" " float ambient = 0.2;" " return diffuse+ambient;" "}"); } else { m_renderer->setOption<VFRendering::IsosurfaceRenderer::Option::LIGHTING_IMPLEMENTATION>( "float lighting(vec3 position, vec3 normal) { return 1.0; }"); } QTimer::singleShot(1, this->spinWidget, SLOT(update())); } void IsosurfaceWidget::setupSlots() { connect(horizontalSlider_isovalue, SIGNAL(valueChanged(int)), this, SLOT(slot_setIsovalue_slider())); connect(lineEdit_isovalue, SIGNAL(returnPressed()), this, SLOT(slot_setIsovalue_lineedit())); connect(radioButton_isosurface_x, SIGNAL(toggled(bool)), this, SLOT(slot_setIsocomponent())); connect(radioButton_isosurface_y, SIGNAL(toggled(bool)), this, SLOT(slot_setIsocomponent())); connect(radioButton_isosurface_z, SIGNAL(toggled(bool)), this, SLOT(slot_setIsocomponent())); connect(checkBox_invert_lighting, SIGNAL(stateChanged(int)), this, SLOT(slot_setTriangleNormal())); connect(pushButton_remove, SIGNAL(clicked()), this, SLOT(close())); } void IsosurfaceWidget::slot_setIsovalue_slider() { float isovalue = horizontalSlider_isovalue->value() / 50.0f - 1.0f; this->lineEdit_isovalue->setText(QString::number(isovalue)); this->setIsovalue(isovalue); } void IsosurfaceWidget::slot_setIsovalue_lineedit() { float isovalue = this->lineEdit_isovalue->text().toFloat(); this->horizontalSlider_isovalue->setValue((int)(isovalue * 50 + 50)); this->setIsovalue(isovalue); } void IsosurfaceWidget::slot_setIsocomponent() { if (this->radioButton_isosurface_x->isChecked()) { this->setIsocomponent(0); } else if (this->radioButton_isosurface_y->isChecked()) { this->setIsocomponent(1); } else if (this->radioButton_isosurface_z->isChecked()) { this->setIsocomponent(2); } } void IsosurfaceWidget::slot_setTriangleNormal() { m_renderer->setOption<VFRendering::IsosurfaceRenderer::Option::FLIP_NORMALS>(this->checkBox_invert_lighting->isChecked()); QTimer::singleShot(1, this->spinWidget, SLOT(update())); } void IsosurfaceWidget::setupInputValidators() { // Isovalue this->lineEdit_isovalue->setValidator(this->number_validator); } void IsosurfaceWidget::closeEvent(QCloseEvent *event) { // Remove this isosurface from the SpinWidget this->spinWidget->removeIsosurface(m_renderer); // Notify others that this widget was closed emit closedSignal(); // Close event->accept(); }
30.744076
196
0.681517
MSallermann
9c84c3b4bd9b231a0935b3b1cc9bb16255245dcd
1,946
cpp
C++
Sources/Sentry/SentryThreadMetadataCache.cpp
mrtnrst/sentry-cocoa
b8724668c3df2a41600d80b7bbde930f70c20f4a
[ "MIT" ]
null
null
null
Sources/Sentry/SentryThreadMetadataCache.cpp
mrtnrst/sentry-cocoa
b8724668c3df2a41600d80b7bbde930f70c20f4a
[ "MIT" ]
null
null
null
Sources/Sentry/SentryThreadMetadataCache.cpp
mrtnrst/sentry-cocoa
b8724668c3df2a41600d80b7bbde930f70c20f4a
[ "MIT" ]
null
null
null
#include "SentryThreadMetadataCache.hpp" #if SENTRY_TARGET_PROFILING_SUPPORTED # include "SentryStackBounds.hpp" # include "SentryThreadHandle.hpp" # include <algorithm> # include <string> # include <vector> namespace { bool isSentryOwnedThreadName(const std::string &name) { return name.rfind("io.sentry", 0) == 0; } constexpr std::size_t kMaxThreadNameLength = 100; } // namespace namespace sentry { namespace profiling { ThreadMetadata ThreadMetadataCache::metadataForThread(const ThreadHandle &thread) { const auto handle = thread.nativeHandle(); const auto it = std::find_if(cache_.cbegin(), cache_.cend(), [handle](const ThreadHandleMetadataPair &pair) { return pair.handle == handle; }); if (it == cache_.cend()) { ThreadMetadata metadata; metadata.threadID = ThreadHandle::tidFromNativeHandle(handle); metadata.priority = thread.priority(); // If getting the priority fails (via pthread_getschedparam()), that // means the rest of this is probably going to fail too. if (metadata.priority != -1) { auto threadName = thread.name(); if (isSentryOwnedThreadName(threadName)) { // Don't collect backtraces for Sentry-owned threads. metadata.priority = 0; metadata.threadID = 0; cache_.push_back({ handle, metadata }); return metadata; } if (threadName.size() > kMaxThreadNameLength) { threadName.resize(kMaxThreadNameLength); } metadata.name = threadName; } cache_.push_back({ handle, metadata }); return metadata; } else { return (*it).metadata; } } } // namespace profiling } // namespace sentry #endif
29.044776
94
0.588386
mrtnrst
9c84dc71b0e1c6286420085b9baad54835b0be76
491
hpp
C++
Source/Tools/relive_api/JsonMapRootInfoReader.hpp
mouzedrift/alive_reversing
be7dfbaed3be99b452459e974bc4e79f9503c178
[ "MIT" ]
208
2018-06-06T13:14:03.000Z
2022-03-30T02:21:27.000Z
Source/Tools/relive_api/JsonMapRootInfoReader.hpp
mouzedrift/alive_reversing
be7dfbaed3be99b452459e974bc4e79f9503c178
[ "MIT" ]
537
2018-06-06T16:50:45.000Z
2022-03-31T16:41:15.000Z
Source/Tools/relive_api/JsonMapRootInfoReader.hpp
mouzedrift/alive_reversing
be7dfbaed3be99b452459e974bc4e79f9503c178
[ "MIT" ]
42
2018-06-06T00:40:08.000Z
2022-03-23T08:38:55.000Z
#pragma once #include "JsonModelTypes.hpp" #include <fstream> namespace ReliveAPI { // Reads the root fields to read the version/game type (we need to know this so we can create a game specific reader/do an upgrade of the json). class JsonMapRootInfoReader final { public: void Read(const std::string& fileName); MapRootInfo mMapRootInfo; }; void readFileContentsIntoString(std::string& target, std::ifstream& ifs); std::string& getStaticStringBuffer(); } // namespace ReliveAPI
25.842105
144
0.759674
mouzedrift
9c8778de92fe31f69d52a077c62dd553c09fa5a6
1,107
cpp
C++
cannon/math/rootfinding.test.cpp
cannontwo/cannon
4be79f3a6200d1a3cd26c28c8f2250dbdf08f267
[ "MIT" ]
null
null
null
cannon/math/rootfinding.test.cpp
cannontwo/cannon
4be79f3a6200d1a3cd26c28c8f2250dbdf08f267
[ "MIT" ]
46
2021-01-12T23:03:52.000Z
2021-10-01T17:29:01.000Z
cannon/math/rootfinding.test.cpp
cannontwo/cannon
4be79f3a6200d1a3cd26c28c8f2250dbdf08f267
[ "MIT" ]
null
null
null
#include <catch2/catch.hpp> #include <iomanip> #include <cannon/math/rootfinding.hpp> #include <cannon/math/nearly_equal.hpp> #include <cannon/log/registry.hpp> using namespace cannon::math; using namespace cannon::log; TEST_CASE("Rootfinding", "[math]") { double r = bisection_method([](double x){ return x * x - 10; }, -10, 0); log_info(std::setprecision(15), r); REQUIRE(nearly_equal(r, -std::sqrt(10))); r = bisection_method([](double x){ return x * x - 10; }, 0, 10); log_info(std::setprecision(15), r); REQUIRE(nearly_equal(r, std::sqrt(10))); r = regula_falsi([](double x){ return x * x - 10; }, -10, 0); log_info(std::setprecision(15), r); REQUIRE(nearly_equal(r, -std::sqrt(10))); r = regula_falsi([](double x){ return x * x - 10; }, 0, 10); log_info(std::setprecision(15), r); REQUIRE(nearly_equal(r, std::sqrt(10))); r = newton_method([](double x) { return x * x - 10; }, [](double x) { return 2 * x; }, -10); log_info(std::setprecision(15), r); REQUIRE(nearly_equal(r, -std::sqrt(10))); }
26.357143
57
0.600723
cannontwo
9c87dcece66731b3452b1626ab75c3f291c718b3
3,646
cpp
C++
src/python/pypangolin/window.cpp
Yoyochen0106/Pangolin
e55463bd2bdd758e46ded7d95332e31f9cdc4f71
[ "MIT" ]
662
2019-09-01T02:16:59.000Z
2022-03-29T19:24:07.000Z
src/python/pypangolin/window.cpp
Yoyochen0106/Pangolin
e55463bd2bdd758e46ded7d95332e31f9cdc4f71
[ "MIT" ]
38
2019-09-05T05:02:20.000Z
2022-03-30T02:59:49.000Z
src/python/pypangolin/window.cpp
Yoyochen0106/Pangolin
e55463bd2bdd758e46ded7d95332e31f9cdc4f71
[ "MIT" ]
104
2019-09-01T07:41:58.000Z
2022-03-27T16:24:54.000Z
/* This file is part of the Pangolin Project. * http://github.com/stevenlovegrove/Pangolin * * Copyright (c) Andrey Mnatsakanov * * 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 "window.hpp" #include <pangolin/display/window.h> namespace py_pangolin { class PyWindowInterface: public pangolin::WindowInterface{ public: using pangolin::WindowInterface::WindowInterface; void ToggleFullscreen() override { PYBIND11_OVERLOAD_PURE( void, pangolin::WindowInterface, ToggleFullscreen); } void Move(int x, int y) override { PYBIND11_OVERLOAD_PURE( void, pangolin::WindowInterface, Move, x, y); } void Resize(unsigned int w, unsigned int h) override { PYBIND11_OVERLOAD_PURE( void, pangolin::WindowInterface, Resize, w, h); } void MakeCurrent() override { PYBIND11_OVERLOAD_PURE( void, pangolin::WindowInterface, MakeCurrent); } void RemoveCurrent() override { PYBIND11_OVERLOAD_PURE( void, pangolin::WindowInterface, RemoveCurrent); } void ProcessEvents() override { PYBIND11_OVERLOAD_PURE( void, pangolin::WindowInterface, ProcessEvents); } void SwapBuffers() override { PYBIND11_OVERLOAD_PURE( void, pangolin::WindowInterface, SwapBuffers); } }; void bind_window(pybind11::module &m) { pybind11::class_<pangolin::WindowInterface, PyWindowInterface > windows_interface(m, "WindowsInterface"); windows_interface .def(pybind11::init<>()) .def("ToggleFullscreen", &pangolin::WindowInterface::ToggleFullscreen) .def("Move", &pangolin::WindowInterface::Move) .def("Resize", &pangolin::WindowInterface::Resize) .def("MakeCurrent", &pangolin::WindowInterface::MakeCurrent) .def("ProcessEvents", &pangolin::WindowInterface::ProcessEvents) .def("SwapBuffers", &pangolin::WindowInterface::SwapBuffers); } }
34.396226
109
0.583379
Yoyochen0106
9c8baf996df4977f0999775d79e55fb4a4e3c854
6,922
cpp
C++
libs/muddle/src/peer_list.cpp
cyenyxe/ledger
6b42c3a3a5c78d257a02634437f9e00d1439690b
[ "Apache-2.0" ]
null
null
null
libs/muddle/src/peer_list.cpp
cyenyxe/ledger
6b42c3a3a5c78d257a02634437f9e00d1439690b
[ "Apache-2.0" ]
null
null
null
libs/muddle/src/peer_list.cpp
cyenyxe/ledger
6b42c3a3a5c78d257a02634437f9e00d1439690b
[ "Apache-2.0" ]
null
null
null
//------------------------------------------------------------------------------ // // Copyright 2018-2019 Fetch.AI Limited // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //------------------------------------------------------------------------------ #include "muddle_logging_name.hpp" #include "peer_list.hpp" #include "router.hpp" #include "core/logging.hpp" #include <algorithm> #include <cstddef> #include <string> #include <utility> static constexpr std::size_t MAX_LOG2_BACKOFF = 11; // 2048 static constexpr char const *BASE_NAME = "MuddlePeers"; namespace fetch { namespace muddle { PeerConnectionList::PeerConnectionList(NetworkId const &network) : name_{GenerateLoggingName(BASE_NAME, network)} {} void PeerConnectionList::SetStatusCallback(StatusCallback callback) { status_callback_ = std::move(callback); } bool PeerConnectionList::AddPersistentPeer(Uri const &peer) { FETCH_LOCK(lock_); auto const result = persistent_peers_.emplace(peer); return result.second; } void PeerConnectionList::RemovePersistentPeer(Uri const &peer) { FETCH_LOCK(lock_); persistent_peers_.erase(peer); } void PeerConnectionList::RemovePersistentPeer(Handle handle) { FETCH_LOCK(lock_); for (auto &peer_connection : peer_connections_) { if (peer_connection.second->handle() == handle) { persistent_peers_.erase(peer_connection.first); break; } } } std::size_t PeerConnectionList::GetNumPeers() const { FETCH_LOCK(lock_); return persistent_peers_.size(); } void PeerConnectionList::AddConnection(Uri const &peer, ConnectionPtr const &conn) { FETCH_LOCK(lock_); // update the metadata auto &metadata = peer_metadata_[peer]; metadata.connected = false; ++metadata.attempts; peer_connections_[peer] = conn; } PeerConnectionList::PeerMap PeerConnectionList::GetCurrentPeers() const { FETCH_LOCK(lock_); return peer_connections_; } PeerConnectionList::PeerSet PeerConnectionList::GetPersistentPeers() const { FETCH_LOCK(lock_); return persistent_peers_; } bool PeerConnectionList::GetMetadataForPeer(Uri const &peer, PeerMetadata &metadata) const { bool success{false}; FETCH_LOCK(lock_); auto it = peer_metadata_.find(peer); if (it != peer_metadata_.end()) { metadata = it->second; success = true; } return success; } PeerConnectionList::ConnectionState PeerConnectionList::GetStateForPeer(Uri const &peer) const { FETCH_LOCK(lock_); auto metadataiter = peer_metadata_.find(peer); if (metadataiter == peer_metadata_.end()) { return ConnectionState::UNKNOWN; } auto const &metadata = metadataiter->second; if (metadata.connected) { return ConnectionState::CONNECTED; } if (ReadyForRetry(metadata)) { return ConnectionState::TRYING; } return ConnectionState(int(ConnectionState::BACKOFF) + metadata.consecutive_failures); } void PeerConnectionList::OnConnectionEstablished(Uri const &peer) { Handle connection_handle = 0; // update the connection metadata { FETCH_LOCK(lock_); auto it = peer_connections_.find(peer); if (it != peer_connections_.end()) { connection_handle = it->second->handle(); } auto &metadata = peer_metadata_[peer]; ++metadata.successes; metadata.connected = true; metadata.consecutive_failures = 0; } // send an identity message if ((connection_handle != 0u) && status_callback_) { status_callback_(peer, connection_handle, ConnectionState::CONNECTED); } FETCH_LOG_INFO(logging_name_, "Connection to ", peer.uri(), " established (conn: ", connection_handle, ")"); } void PeerConnectionList::RemoveConnection(Uri const &peer) { FETCH_LOCK(lock_); // remove the active connection peer_connections_.erase(peer); // update the metadata auto mt_it = peer_metadata_.find(peer); if (mt_it != peer_metadata_.end()) { auto &metadata = mt_it->second; ++metadata.consecutive_failures; ++metadata.total_failures; metadata.connected = false; metadata.last_failed_connection = Clock::now(); } } void PeerConnectionList::RemoveConnection(Handle handle) { FETCH_LOCK(lock_); for (auto it = peer_connections_.begin(); it != peer_connections_.end(); ++it) { if (it->second->handle() == handle) { FETCH_LOG_DEBUG(logging_name_, "Connection to ", it->first.uri(), " lost"); auto metadata = peer_metadata_.find(it->first); if (metadata != peer_metadata_.end()) { metadata->second.connected = false; } peer_connections_.erase(it); break; } } } void PeerConnectionList::Disconnect(Uri const &peer) { FETCH_LOCK(lock_); if (peer_metadata_.erase(peer) != 0u) { peer_connections_.erase(peer); } FETCH_LOG_DEBUG(logging_name_, "Connection to ", peer.uri(), " shut down"); } void PeerConnectionList::DisconnectAll() { FETCH_LOCK(lock_); peer_connections_.clear(); persistent_peers_.clear(); } bool PeerConnectionList::ReadyForRetry(PeerMetadata const &metadata) const { std::size_t const log2_backoff = std::min(metadata.consecutive_failures, MAX_LOG2_BACKOFF); Timepoint const backoff_deadline = metadata.last_failed_connection + std::chrono::seconds{1u << log2_backoff}; return (Clock::now() >= backoff_deadline); } PeerConnectionList::PeerList PeerConnectionList::GetPeersToConnectTo() const { PeerList peers; FETCH_LOCK(lock_); // determine which of the persistent peers are no longer active for (auto const &peer : persistent_peers_) { bool const inactive = peer_connections_.find(peer) == peer_connections_.end(); if (inactive) { auto it = peer_metadata_.find(peer); // determine if this is an initial connection, or if we should try and apply some // type of backoff. bool const is_first_connection = it == peer_metadata_.end(); if (is_first_connection) { // on a first attempt, a connection attempt should always be made peers.push_back(peer); } else { // lookup the connection metadata auto const &metadata = it->second; // determine if this connection should be connected again if (ReadyForRetry(metadata)) { peers.push_back(peer); } } } } return peers; } } // namespace muddle } // namespace fetch
24.98917
94
0.683762
cyenyxe
9c8e2fffe5c973210c79dda8f4777ca678b78aa4
944
cpp
C++
source/common/xstream/methods/fasterrcnnmethod/example/test_hbcc_info.cpp
robort-yuan/AI-EXPRESS
56f86d03afbb09f42c21958c8cd9f2f1c6437f48
[ "BSD-2-Clause" ]
98
2020-09-11T13:52:44.000Z
2022-03-23T11:52:02.000Z
source/common/xstream/methods/fasterrcnnmethod/example/test_hbcc_info.cpp
robort-yuan/AI-EXPRESS
56f86d03afbb09f42c21958c8cd9f2f1c6437f48
[ "BSD-2-Clause" ]
8
2020-10-19T14:23:30.000Z
2022-03-16T01:00:07.000Z
source/common/xstream/methods/fasterrcnnmethod/example/test_hbcc_info.cpp
robort-yuan/AI-EXPRESS
56f86d03afbb09f42c21958c8cd9f2f1c6437f48
[ "BSD-2-Clause" ]
28
2020-09-17T14:20:35.000Z
2022-01-10T16:26:00.000Z
// // Created by yaoyao.sun on 2019-05-18. // Copyright (c) 2019 Horizon Robotics. All rights reserved. // #include <iostream> #include "bpu_predict/bpu_predict.h" int TestHBCCInfo(int argc, char **argv) { const char *model_file_path = "./models/faceMultitask.hbm"; const char *bpu_config = "./configs/bpu_config.json"; BPUHandle bpu_handle; int ret = BPU_loadModel(model_file_path, &bpu_handle, bpu_config); if (ret != 0) { std::cout << "here load bpu model failed: " << BPU_getLastError(bpu_handle) << std::endl; return 1; } const char **model_names; int model_num; ret = BPU_getModelNameList(bpu_handle, &model_names, &model_num); if (ret != 0) { std::cout << "here get name list failed: " << BPU_getLastError(bpu_handle) << std::endl; return 1; } for (int i = 0; i < model_num; i++) { std::cout << "model name:" << model_names[i] << std::endl; } return 0; }
26.971429
68
0.638771
robort-yuan
9c8e8209f90318ea5fa25580e127abbba470d4de
896
cpp
C++
510A.cpp
dipubiswas1303/codeforces_solve
ccfa55ca42e8e1504d72fc02f84ea1717f4f1f79
[ "MIT" ]
null
null
null
510A.cpp
dipubiswas1303/codeforces_solve
ccfa55ca42e8e1504d72fc02f84ea1717f4f1f79
[ "MIT" ]
null
null
null
510A.cpp
dipubiswas1303/codeforces_solve
ccfa55ca42e8e1504d72fc02f84ea1717f4f1f79
[ "MIT" ]
null
null
null
#include<bits/stdc++.h> using namespace std; /* NAME : DIPU BISWAS JUST CSE 2019 - 2020 PROBLEM CODE : 510A LINK : https://codeforces.com/problemset/problem/510/A */ int main() { int m, n, i = 0, j = 0, k = 2; cin >> m >> n; for(i = 0; i < m; i++){ if(i % 2 == 0) for(j = 0; j < n; j++) cout << '#'; else if(i % 2 == 1 && k % 2 == 0){ for(j = 0; j < n; j++) if(j == n - 1) cout << '#'; else cout << '.'; k++; } else if(i % 2 == 1 && k % 2 == 1) { k--; for(j = 0; j < n; j++) if(j == 0) cout << '#'; else cout << '.'; } cout << endl; } return 0; }
21.853659
57
0.287946
dipubiswas1303
9c8f7b6ec3bed83c367fd83de701506ff241464c
1,837
cpp
C++
kernel/node/Pipe.cpp
busybox11/skift
778ae3a0dc5ac29d7de02200c49d3533e47854c5
[ "MIT" ]
2
2020-07-14T21:16:54.000Z
2020-10-08T08:40:47.000Z
kernel/node/Pipe.cpp
busybox11/skift
778ae3a0dc5ac29d7de02200c49d3533e47854c5
[ "MIT" ]
null
null
null
kernel/node/Pipe.cpp
busybox11/skift
778ae3a0dc5ac29d7de02200c49d3533e47854c5
[ "MIT" ]
null
null
null
#include <libsystem/Result.h> #include "kernel/node/Handle.h" #include "kernel/node/Pipe.h" #define PIPE_BUFFER_SIZE 4096 static bool pipe_can_read(FsPipe *node, FsHandle *handle) { __unused(handle); // FIXME: make this atomic or something... return !ringbuffer_is_empty(node->buffer) || !node->writers; } static bool pipe_can_write(FsPipe *node, FsHandle *handle) { __unused(handle); // FIXME: make this atomic or something... return !ringbuffer_is_full(node->buffer) || !node->readers; } static Result pipe_read(FsPipe *node, FsHandle *handle, void *buffer, size_t size, size_t *read) { __unused(handle); if (!node->writers) { return ERR_STREAM_CLOSED; } *read = ringbuffer_read(node->buffer, (char *)buffer, size); return SUCCESS; } static Result pipe_write(FsPipe *node, FsHandle *handle, const void *buffer, size_t size, size_t *written) { __unused(handle); if (!node->readers) { return ERR_STREAM_CLOSED; } *written = ringbuffer_write(node->buffer, (const char *)buffer, size); return SUCCESS; } static size_t pipe_size(FsPipe *node, FsHandle *handle) { __unused(node); __unused(handle); return PIPE_BUFFER_SIZE; } static void pipe_destroy(FsPipe *node) { ringbuffer_destroy(node->buffer); } FsNode *fspipe_create() { FsPipe *pipe = __create(FsPipe); fsnode_init(pipe, FILE_TYPE_PIPE); pipe->can_read = (FsNodeCanReadCallback)pipe_can_read; pipe->can_write = (FsNodeCanWriteCallback)pipe_can_write; pipe->read = (FsNodeReadCallback)pipe_read; pipe->write = (FsNodeWriteCallback)pipe_write; pipe->size = (FsNodeSizeCallback)pipe_size; pipe->destroy = (FsNodeDestroyCallback)pipe_destroy; pipe->buffer = ringbuffer_create(PIPE_BUFFER_SIZE); return (FsNode *)pipe; }
22.13253
106
0.696788
busybox11
9c9188b0ece090ee965b9c74dfc2dfa2c6d619c3
750
cpp
C++
src/pattern_library/pattern_fire.cpp
carlyrobison/Hell-Lighting
c7944e27d383bf5f5b5c1b6cd906ae7104314cd5
[ "MIT" ]
3
2017-09-25T00:21:28.000Z
2019-02-25T16:36:13.000Z
src/pattern_library/pattern_fire.cpp
carlyrobison/Hell-Lighting
c7944e27d383bf5f5b5c1b6cd906ae7104314cd5
[ "MIT" ]
26
2017-05-06T08:16:44.000Z
2019-10-27T04:45:32.000Z
src/pattern_library/pattern_fire.cpp
maxwells-daemons/Hell-Lighting
adae245d4858dfe36046625bba71ab4a685dabcc
[ "MIT" ]
9
2017-05-06T08:09:21.000Z
2019-10-25T03:50:47.000Z
#include "pattern_fire.h" void Pattern_Fire::init() { clearLEDs(); FastLED.setBrightness(BRIGHTNESS_MAX); } void Pattern_Fire::loop() { uint16_t brightness = max((float) BRIGHTNESS_MAX * (((float) (1024 - analogRead(PIN_POT))) / 1024.0), 5); FastLED.setBrightness(brightness); for (int i = 1; i < NUM_LEDS_TOTAL - 1; i++) { if (leds[i].r == 0) { // This point has not yet been initialized leds[i] = CRGB(random8(100, 255), random8(0, 50), 0); } else { // Standard fire algorithm x = ((leds[i-1].r - leds[i].r) - (leds[i + 1].r - leds[i].r)) / 4; leds[i].r = x + random8(100, 255); leds[i].g = random8(0, 20); leds[i].b = 0; } } FastLED.show(); delay(31); }
30
109
0.558667
carlyrobison
9c93bc9334c49d76bfcedb4a8635ce8500a2f71c
1,253
cpp
C++
1595/1573862_AC_0MS_56K.cpp
vandreas19/POJ_sol
4895764ab800e8c2c4b2334a562dec2f07fa243e
[ "MIT" ]
18
2017-08-14T07:34:42.000Z
2022-01-29T14:20:29.000Z
1595/1573862_AC_0MS_56K.cpp
pinepara/poj_solutions
4895764ab800e8c2c4b2334a562dec2f07fa243e
[ "MIT" ]
null
null
null
1595/1573862_AC_0MS_56K.cpp
pinepara/poj_solutions
4895764ab800e8c2c4b2334a562dec2f07fa243e
[ "MIT" ]
14
2016-12-21T23:37:22.000Z
2021-07-24T09:38:57.000Z
#include<iostream.h> #include<math.h> void main() { const int iPrimeCount=169; const int iPrimeNum[iPrimeCount]={1,2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101,103 ,107,109,113,127,131,137,139,149,151,157,163,167,173,179,181,191,193,197,199,211 ,223,227,229,233,239,241,251,257,263,269,271,277,281,283,293,307,311,313,317,331 ,337,347,349,353,359,367,373,379,383,389,397,401,409,419,421,431,433,439,443,449 ,457,461,463,467,479,487,491,499,503,509,521,523,541,547,557,563,569,571,577,587 ,593,599,601,607,613,617,619,631,641,643,647,653,659,661,673,677,683,691,701,709 ,719,727,733,739,743,751,757,761,769,773,787,797,809,811,821,823,827,829,839,853 ,857,859,863,877,881,883,887,907,911,919,929,937,941,947,953,967,971,977,983,991 ,997}; int iN,iC,iLimit,iLow,iHigh,i; while(cin>>iN>>iC) { for(i=0;i<iPrimeCount;i++) { if(i==iPrimeCount-1) iLimit=i; else if(iPrimeNum[i+1]>iN) { iLimit=i; break; } } if(iC>iLimit/2+1) { iLow=0; iHigh=iLimit; } else { iLow=iLimit/2-iC+1; iHigh=iLimit/2+iC-1+iLimit%2; } cout<<iN<<" "<<iC<<":"; for(i=iLow;i<=iHigh;i++) cout<<" "<<iPrimeNum[i]; cout<<"\n\n"; } }
28.477273
116
0.621708
vandreas19
9c93ebe81e36d96b8f5402d7eeab0c77b642b950
7,309
cpp
C++
hphp/runtime/vm/jit/fixup.cpp
hafeez3000/hhvm
2bd460c8de9012047f95b664670bc9c8127905f2
[ "PHP-3.01", "Zend-2.0" ]
null
null
null
hphp/runtime/vm/jit/fixup.cpp
hafeez3000/hhvm
2bd460c8de9012047f95b664670bc9c8127905f2
[ "PHP-3.01", "Zend-2.0" ]
null
null
null
hphp/runtime/vm/jit/fixup.cpp
hafeez3000/hhvm
2bd460c8de9012047f95b664670bc9c8127905f2
[ "PHP-3.01", "Zend-2.0" ]
null
null
null
/* +----------------------------------------------------------------------+ | HipHop for PHP | +----------------------------------------------------------------------+ | Copyright (c) 2010-2014 Facebook, Inc. (http://www.facebook.com) | +----------------------------------------------------------------------+ | This source file is subject to version 3.01 of the PHP license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.php.net/license/3_01.txt | | If you did not receive a copy of the PHP license and are unable to | | obtain it through the world-wide-web, please send a note to | | license@php.net so we can mail you a copy immediately. | +----------------------------------------------------------------------+ */ #include "hphp/runtime/vm/jit/fixup.h" #include "hphp/vixl/a64/simulator-a64.h" #include "hphp/runtime/vm/jit/abi-arm.h" #include "hphp/runtime/vm/jit/mc-generator.h" #include "hphp/runtime/vm/jit/translator-inline.h" #include "hphp/util/data-block.h" namespace HPHP { namespace JIT { bool FixupMap::getFrameRegs(const ActRec* ar, const ActRec* prevAr, VMRegs* outVMRegs) const { CTCA tca = (CTCA)ar->m_savedRip; // Non-obvious off-by-one fun: if the *return address* points into the TC, // then the frame we were running on in the TC is actually the previous // frame. ar = (const ActRec*)ar->m_savedRbp; auto* ent = m_fixups.find(tca); if (!ent) return false; if (ent->isIndirect()) { // Note: if indirect fixups happen frequently enough, we could // just compare savedRip to be less than some threshold where // stubs in a.code stop. assert(prevAr); auto pRealRip = ent->indirect.returnIpDisp + uintptr_t(prevAr->m_savedRbp); ent = m_fixups.find(*reinterpret_cast<CTCA*>(pRealRip)); assert(ent && !ent->isIndirect()); } regsFromActRec(tca, ar, ent->fixup, outVMRegs); return true; } void FixupMap::recordSyncPoint(CodeAddress frontier, Offset pcOff, Offset spOff) { m_pendingFixups.push_back(PendingFixup(frontier, Fixup(pcOff, spOff))); } void FixupMap::recordIndirectFixup(CodeAddress frontier, int dwordsPushed) { recordIndirectFixup(frontier, IndirectFixup((2 + dwordsPushed) * 8)); } namespace { bool isVMFrame(const ExecutionContext* ec, const ActRec* ar) { // If this assert is failing, you may have forgotten a sync point somewhere assert(ar); bool ret = uintptr_t(ar) - s_stackLimit >= s_stackSize; assert(!ret || (ar >= ec->m_stack.getStackLowAddress() && ar < ec->m_stack.getStackHighAddress()) || (ar->m_func->validate(), ar->inGenerator())); return ret; } } void FixupMap::fixupWork(ExecutionContext* ec, ActRec* rbp) const { assert(RuntimeOption::EvalJit); TRACE(1, "fixup(begin):\n"); auto* nextRbp = rbp; rbp = 0; do { auto* prevRbp = rbp; rbp = nextRbp; assert(rbp && "Missing fixup for native call"); nextRbp = reinterpret_cast<ActRec*>(rbp->m_savedRbp); TRACE(2, "considering frame %p, %p\n", rbp, (void*)rbp->m_savedRip); if (isVMFrame(ec, nextRbp)) { TRACE(2, "fixup checking vm frame %s\n", nextRbp->m_func->name()->data()); VMRegs regs; if (getFrameRegs(rbp, prevRbp, &regs)) { TRACE(2, "fixup(end): func %s fp %p sp %p pc %p\n", regs.m_fp->m_func->name()->data(), regs.m_fp, regs.m_sp, regs.m_pc); ec->m_fp = const_cast<ActRec*>(regs.m_fp); ec->m_pc = reinterpret_cast<PC>(regs.m_pc); vmsp() = regs.m_sp; return; } } } while (rbp && rbp != nextRbp); // OK, we've exhausted the entire actRec chain. We are only // invoking ::fixup() from contexts that were known to be called out // of the TC, so this cannot happen. always_assert(false); } void FixupMap::fixupWorkSimulated(ExecutionContext* ec) const { TRACE(1, "fixup(begin):\n"); auto isVMFrame = [] (ActRec* ar, const vixl::Simulator* sim) { // If this assert is failing, you may have forgotten a sync point somewhere assert(ar); bool ret = uintptr_t(ar) - s_stackLimit >= s_stackSize && !sim->is_on_stack(ar); assert(!ret || (ar >= g_context->m_stack.getStackLowAddress() && ar < g_context->m_stack.getStackHighAddress()) || ar->inGenerator()); return ret; }; // For each nested simulator (corresponding to nested VM invocations), look at // its PC to find a potential fixup key. // // Callstack walking is necessary, because we may get called from a // uniqueStub. for (int i = ec->m_activeSims.size() - 1; i >= 0; --i) { auto const* sim = ec->m_activeSims[i]; auto* rbp = reinterpret_cast<ActRec*>(sim->xreg(JIT::ARM::rVmFp.code())); auto tca = reinterpret_cast<TCA>(sim->pc()); TRACE(2, "considering frame %p, %p\n", rbp, tca); while (rbp && !isVMFrame(rbp, sim)) { tca = reinterpret_cast<TCA>(rbp->m_savedRip); rbp = reinterpret_cast<ActRec*>(rbp->m_savedRbp); } if (!rbp) continue; auto* ent = m_fixups.find(tca); if (!ent) { continue; } if (ent->isIndirect()) { not_implemented(); } VMRegs regs; regsFromActRec(tca, rbp, ent->fixup, &regs); TRACE(2, "fixup(end): func %s fp %p sp %p pc %p\b", regs.m_fp->m_func->name()->data(), regs.m_fp, regs.m_sp, regs.m_pc); ec->m_fp = const_cast<ActRec*>(regs.m_fp); ec->m_pc = reinterpret_cast<PC>(regs.m_pc); vmsp() = regs.m_sp; return; } // This shouldn't be reached. always_assert(false); } void FixupMap::fixup(ExecutionContext* ec) const { if (RuntimeOption::EvalSimulateARM) { // Walking the C++ stack doesn't work in simulation mode. Fortunately, the // execution context has a stack of simulators, which we consult instead. fixupWorkSimulated(ec); } else { // Start looking for fixup entries at the current (C++) frame. This // will walk the frames upward until we find a TC frame. DECLARE_FRAME_POINTER(framePtr); fixupWork(ec, framePtr); } } void FixupMap::processPendingFixups() { for (uint i = 0; i < m_pendingFixups.size(); i++) { TCA tca = m_pendingFixups[i].m_tca; assert(mcg->isValidCodeAddress(tca)); recordFixup(tca, m_pendingFixups[i].m_fixup); } m_pendingFixups.clear(); } /* This is somewhat hacky. It decides which helpers/builtins should * use eager vmreganchor based on profile information. Using eager * vmreganchor for all helper calls is a perf regression. */ bool FixupMap::eagerRecord(const Func* func) { const char* list[] = { "func_get_args", "get_called_class", "func_num_args", "array_filter", "array_map", "hphp_func_slice_args", }; for (int i = 0; i < sizeof(list)/sizeof(list[0]); i++) { if (!strcmp(func->name()->data(), list[i])) { return true; } } if (func->cls() && !strcmp(func->cls()->name()->data(), "WaitHandle") && !strcmp(func->name()->data(), "join")) { return true; } return false; } } // HPHP::JIT } // HPHP
32.629464
80
0.603913
hafeez3000
9c96bae813bc435c8a8298983f54fe5b60797beb
4,708
cc
C++
analysis/zz_deprecated/untested/RadShockPosn.cc
jfbucas/PION
e0a66aa301e4d94d581ba4df078f1a3b82faab99
[ "BSD-3-Clause" ]
4
2020-08-20T11:31:22.000Z
2020-12-05T13:30:03.000Z
analysis/zz_deprecated/untested/RadShockPosn.cc
Mapoet/PION
51559b18f700c372974ac8658a266b6a647ec764
[ "BSD-3-Clause" ]
null
null
null
analysis/zz_deprecated/untested/RadShockPosn.cc
Mapoet/PION
51559b18f700c372974ac8658a266b6a647ec764
[ "BSD-3-Clause" ]
4
2020-08-20T14:33:19.000Z
2022-03-07T10:29:34.000Z
/** \file RadShockPosn.cc * \author Jonathan Mackey * * This file reads in a series of fits files, which are assumed to be outputs * of radiative shock simulations in 1D or 2D. For each file it determines * the position of the shock in the x-direction, in the 1st y-column, and * writes the (time,position) pair to a tab delimited text file. The first line * of the file should contain info about the simulation that the data is from. * * This is explicitly serial code, so if there are parallel outputs to multiple * files this code won't work. * * Compile with:\n * g++ -Wall -DSERIAL RadShockPosn.cc ../testing/global.cc ../testing/uniformGrid.cc ../testing/dataio.cc -lreadline -lcfitsio * * Run with (example):\n * ./a.out v140.txt ../results/RadShock2D_n128x32_v140_n10_T1e4 0 50 * * */ #include "fitsio.h" using namespace std; #include "../testing/global.h" #include "../testing/uniformGrid.h" #include "../testing/dataio.h" int main(int argc, char **argv) { // Get two input files and one output file from cmd-line args. if (argc!=5) { cerr << "Error: must call with 4 arguments...\n"; cerr << "RadShockPosn: <executable> <OutfileName> <file-base> <FirstOutput> <OutputFreq>\n"; rep.error("Bad number of Args",argc); } string outfile = argv[1]; string infilebase = argv[2]; int startct = atoi(argv[3]); int opfreq = atoi(argv[4]); if (isnan(startct) || isnan(opfreq) || opfreq==0) rep.error("Bad ints in args",opfreq); cout <<"reading from first file "<<infilebase<<"."<<startct<<".fits\n"; cout <<"Writing shock position to file "<<outfile<<"\n"; cout <<"**********************************************\n"; class DataIOFits dataio; class file_status fs; // First we need to open the first file in the list, and get the grid dimensions, // so we can set it up once and use it for all the infiles. string infile; ostringstream temp; temp.str(""); temp << infilebase <<"."<<startct <<".fits"; infile=temp.str(); cout <<"Initially reading from file "<<infile<<endl; int err=0; if (!fs.file_exists(infile)) rep.error("First file not found!",infile); err = dataio.ReadHeader(infile); if (err) rep.error("read header went bad",err); // check dimensionality is ok. if (SimPM.ndim!=1 && SimPM.ndim!=2) rep.error("need 1D or 2D sim for rad.shock test",SimPM.ndim); // Now the header should contain the sim dimensionality, number of vars, // size of box, so we can use these to set up the grid. cout <<"(UniformFV::setup_grid) Setting up grid...\n"; grid = new UniformGrid (SimPM.ndim, SimPM.nvar, SimPM.eqntype, SimPM.Xmin, SimPM.Xmax, SimPM.NG); if (grid==0) rep.error("(IntUniformFV::setup_grid) Couldn't assign data!", grid); cout <<"(setup_grid) Done. g="<<grid<<"\n"; // Set up and open outfile if (fs.file_exists(outfile)) cout <<"WARNING:: file exists, I am overwriting a text file.\n"; ofstream outf(outfile.c_str()); if(!outf.is_open()) rep.error("couldn't open outfile",outfile); outf.setf( ios_base::scientific ); outf.precision(6); outf << "# Radiative Shock Test Problem outputs. First file: "<<infile<<endl; outf << "# Columns are time and shock position, and should be in cgs units (s,cm).\n\n"; int count = startct; double refvel=0.0; // Need to loop this over all timesteps, incrementing 'start' by 'step' each time // until there are no more files to analyse (note the last one might get left out). do { cout <<"Reading from file "<<infile<<endl; // read data onto grid. err += dataio.ReadHeader(infile); err += dataio.ReadData(infile); if (err) rep.error("read data went bad for file",err); // get first point, and move to XP end of grid. cell *c = grid->FirstPt(); do {c=grid->NextPt(c,XP);} while (grid->NextPt(c,XP) !=0); cell *c2 = grid->NextPt(c,XN); if (!c2) {rep.error("Lost on grid",c2); grid->PrintCell(c);} refvel = c->P[VX]; // find the shock position by locating where VX first changes by >10% while ( fabs(fabs(c2->P[VX]/refvel)-1.0) <= 0.3) { c = c2; c2 = grid->NextPt(c2,XN); if (!c2) { cout <<"no shock found!\n"; c2=c; break; } } // Write (x_sh,t_sim) to file. outf <<SimPM.simtime<<"\t"<<c2->x[XX]<<"\n"; // increment filename count += opfreq; temp.str(""); temp << infilebase <<"."<< count <<".fits"; infile=temp.str(); } while (fs.file_exists(infile)); // loop over all timesteps. cout <<"\n***************************************************\n"; cout <<"couldn't find file "<<infile<<" for step "<<count<<"... assuming i'm finished!\n"; outf.close(); delete grid; grid=0; return 0; }
40.586207
126
0.634452
jfbucas
9c9797b5757b82e1c4fc8c7d5573348d27a5e5ea
8,307
hpp
C++
include/node/gen/mem.hpp
PENGUINLIONG/cspv
10dd24c2040d8e5011f196fc962f50d01c956632
[ "Apache-2.0", "MIT" ]
null
null
null
include/node/gen/mem.hpp
PENGUINLIONG/cspv
10dd24c2040d8e5011f196fc962f50d01c956632
[ "Apache-2.0", "MIT" ]
null
null
null
include/node/gen/mem.hpp
PENGUINLIONG/cspv
10dd24c2040d8e5011f196fc962f50d01c956632
[ "Apache-2.0", "MIT" ]
null
null
null
// GENERATED BY `scripts/gen-visitor-templates.py`; DO NOT MODIFY. // Memory node implementation. // @PENGUINLIONG #pragma once #include "node/reg.hpp" typedef Reference<struct MemoryPatternCapture> MemoryPatternCaptureRef; typedef Reference<struct MemoryFunctionVariable> MemoryFunctionVariableRef; typedef Reference<struct MemoryIterationVariable> MemoryIterationVariableRef; typedef Reference<struct MemoryUniformBuffer> MemoryUniformBufferRef; typedef Reference<struct MemoryStorageBuffer> MemoryStorageBufferRef; typedef Reference<struct MemorySampledImage> MemorySampledImageRef; typedef Reference<struct MemoryStorageImage> MemoryStorageImageRef; struct MemoryPatternCapture : public Memory { static const MemoryClass CLS = L_MEMORY_CLASS_PATTERN_CAPTURE; MemoryRef captured; inline MemoryPatternCapture( const TypeRef& ty, const std::vector<ExprRef>& ac, const MemoryRef& captured ) : Memory(L_MEMORY_CLASS_PATTERN_CAPTURE, ty, ac), captured(captured) { liong::assert(captured != nullptr); } inline MemoryPatternCapture(const TypeRef& ty, const std::vector<ExprRef>& ac) : Memory(L_MEMORY_CLASS_PATTERN_CAPTURE, ty, ac) {} virtual bool structured_eq(MemoryRef b_) const override final { if (!b_->is<MemoryPatternCapture>()) { return false; } const auto& b2_ = b_->as<MemoryPatternCapture>(); if (!ty->structured_eq(b2_.ty)) { return false; } if (ac.size() != b2_.ac.size()) { return false; } for (size_t i = 0; i < ac.size(); ++i) { if (!ac.at(i)->structured_eq(b2_.ac.at(i))) { return false; } } if (!captured->structured_eq(b2_.captured)) { return false; } return true; } virtual void collect_children(NodeDrain* drain) const override final { drain->push(ty); for (const auto& x : ac) { drain->push(x); } drain->push(captured); } }; struct MemoryFunctionVariable : public Memory { static const MemoryClass CLS = L_MEMORY_CLASS_FUNCTION_VARIABLE; std::shared_ptr<uint8_t> handle; inline MemoryFunctionVariable( const TypeRef& ty, const std::vector<ExprRef>& ac, std::shared_ptr<uint8_t> handle ) : Memory(L_MEMORY_CLASS_FUNCTION_VARIABLE, ty, ac), handle(handle) { } virtual bool structured_eq(MemoryRef b_) const override final { if (!b_->is<MemoryFunctionVariable>()) { return false; } const auto& b2_ = b_->as<MemoryFunctionVariable>(); if (!ty->structured_eq(b2_.ty)) { return false; } if (ac.size() != b2_.ac.size()) { return false; } for (size_t i = 0; i < ac.size(); ++i) { if (!ac.at(i)->structured_eq(b2_.ac.at(i))) { return false; } } if (handle != b2_.handle) { return false; } return true; } virtual void collect_children(NodeDrain* drain) const override final { drain->push(ty); for (const auto& x : ac) { drain->push(x); } } }; struct MemoryIterationVariable : public Memory { static const MemoryClass CLS = L_MEMORY_CLASS_ITERATION_VARIABLE; ExprRef begin; ExprRef end; ExprRef stride; inline MemoryIterationVariable( const TypeRef& ty, const std::vector<ExprRef>& ac, const ExprRef& begin, const ExprRef& end, const ExprRef& stride ) : Memory(L_MEMORY_CLASS_ITERATION_VARIABLE, ty, ac), begin(begin), end(end), stride(stride) { liong::assert(begin != nullptr); liong::assert(end != nullptr); liong::assert(stride != nullptr); } virtual bool structured_eq(MemoryRef b_) const override final { if (!b_->is<MemoryIterationVariable>()) { return false; } const auto& b2_ = b_->as<MemoryIterationVariable>(); if (!ty->structured_eq(b2_.ty)) { return false; } if (ac.size() != b2_.ac.size()) { return false; } for (size_t i = 0; i < ac.size(); ++i) { if (!ac.at(i)->structured_eq(b2_.ac.at(i))) { return false; } } if (!begin->structured_eq(b2_.begin)) { return false; } if (!end->structured_eq(b2_.end)) { return false; } if (!stride->structured_eq(b2_.stride)) { return false; } return true; } virtual void collect_children(NodeDrain* drain) const override final { drain->push(ty); for (const auto& x : ac) { drain->push(x); } drain->push(begin); drain->push(end); drain->push(stride); } }; struct MemoryUniformBuffer : public Memory { static const MemoryClass CLS = L_MEMORY_CLASS_UNIFORM_BUFFER; uint32_t binding; uint32_t set; inline MemoryUniformBuffer( const TypeRef& ty, const std::vector<ExprRef>& ac, uint32_t binding, uint32_t set ) : Memory(L_MEMORY_CLASS_UNIFORM_BUFFER, ty, ac), binding(binding), set(set) { } virtual bool structured_eq(MemoryRef b_) const override final { if (!b_->is<MemoryUniformBuffer>()) { return false; } const auto& b2_ = b_->as<MemoryUniformBuffer>(); if (!ty->structured_eq(b2_.ty)) { return false; } if (ac.size() != b2_.ac.size()) { return false; } for (size_t i = 0; i < ac.size(); ++i) { if (!ac.at(i)->structured_eq(b2_.ac.at(i))) { return false; } } if (binding != b2_.binding) { return false; } if (set != b2_.set) { return false; } return true; } virtual void collect_children(NodeDrain* drain) const override final { drain->push(ty); for (const auto& x : ac) { drain->push(x); } } }; struct MemoryStorageBuffer : public Memory { static const MemoryClass CLS = L_MEMORY_CLASS_STORAGE_BUFFER; uint32_t binding; uint32_t set; inline MemoryStorageBuffer( const TypeRef& ty, const std::vector<ExprRef>& ac, uint32_t binding, uint32_t set ) : Memory(L_MEMORY_CLASS_STORAGE_BUFFER, ty, ac), binding(binding), set(set) { } virtual bool structured_eq(MemoryRef b_) const override final { if (!b_->is<MemoryStorageBuffer>()) { return false; } const auto& b2_ = b_->as<MemoryStorageBuffer>(); if (!ty->structured_eq(b2_.ty)) { return false; } if (ac.size() != b2_.ac.size()) { return false; } for (size_t i = 0; i < ac.size(); ++i) { if (!ac.at(i)->structured_eq(b2_.ac.at(i))) { return false; } } if (binding != b2_.binding) { return false; } if (set != b2_.set) { return false; } return true; } virtual void collect_children(NodeDrain* drain) const override final { drain->push(ty); for (const auto& x : ac) { drain->push(x); } } }; struct MemorySampledImage : public Memory { static const MemoryClass CLS = L_MEMORY_CLASS_SAMPLED_IMAGE; uint32_t binding; uint32_t set; inline MemorySampledImage( const TypeRef& ty, const std::vector<ExprRef>& ac, uint32_t binding, uint32_t set ) : Memory(L_MEMORY_CLASS_SAMPLED_IMAGE, ty, ac), binding(binding), set(set) { } virtual bool structured_eq(MemoryRef b_) const override final { if (!b_->is<MemorySampledImage>()) { return false; } const auto& b2_ = b_->as<MemorySampledImage>(); if (!ty->structured_eq(b2_.ty)) { return false; } if (ac.size() != b2_.ac.size()) { return false; } for (size_t i = 0; i < ac.size(); ++i) { if (!ac.at(i)->structured_eq(b2_.ac.at(i))) { return false; } } if (binding != b2_.binding) { return false; } if (set != b2_.set) { return false; } return true; } virtual void collect_children(NodeDrain* drain) const override final { drain->push(ty); for (const auto& x : ac) { drain->push(x); } } }; struct MemoryStorageImage : public Memory { static const MemoryClass CLS = L_MEMORY_CLASS_STORAGE_IMAGE; uint32_t binding; uint32_t set; inline MemoryStorageImage( const TypeRef& ty, const std::vector<ExprRef>& ac, uint32_t binding, uint32_t set ) : Memory(L_MEMORY_CLASS_STORAGE_IMAGE, ty, ac), binding(binding), set(set) { } virtual bool structured_eq(MemoryRef b_) const override final { if (!b_->is<MemoryStorageImage>()) { return false; } const auto& b2_ = b_->as<MemoryStorageImage>(); if (!ty->structured_eq(b2_.ty)) { return false; } if (ac.size() != b2_.ac.size()) { return false; } for (size_t i = 0; i < ac.size(); ++i) { if (!ac.at(i)->structured_eq(b2_.ac.at(i))) { return false; } } if (binding != b2_.binding) { return false; } if (set != b2_.set) { return false; } return true; } virtual void collect_children(NodeDrain* drain) const override final { drain->push(ty); for (const auto& x : ac) { drain->push(x); } } };
35.050633
132
0.668472
PENGUINLIONG
9c98a694e55d27be8b03bea36cf1e5bb88a1f3cd
6,158
hpp
C++
CppSprtPkg/Include/ext/pb_ds/detail/binomial_heap_base_/binomial_heap_base_.hpp
lvjianmin-loongson/uefi
d6fba2f83e00125ff0362b4583461958d459fb4b
[ "BSD-2-Clause" ]
null
null
null
CppSprtPkg/Include/ext/pb_ds/detail/binomial_heap_base_/binomial_heap_base_.hpp
lvjianmin-loongson/uefi
d6fba2f83e00125ff0362b4583461958d459fb4b
[ "BSD-2-Clause" ]
null
null
null
CppSprtPkg/Include/ext/pb_ds/detail/binomial_heap_base_/binomial_heap_base_.hpp
lvjianmin-loongson/uefi
d6fba2f83e00125ff0362b4583461958d459fb4b
[ "BSD-2-Clause" ]
null
null
null
// -*- C++ -*- // Copyright (C) 2005, 2006, 2009 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the terms // of the GNU General Public License as published by the Free Software // Foundation; either version 3, 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 // General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // <http://www.gnu.org/licenses/>. // Copyright (C) 2004 Ami Tavory and Vladimir Dreizin, IBM-HRL. // Permission to use, copy, modify, sell, and distribute this software // is hereby granted without fee, provided that the above copyright // notice appears in all copies, and that both that copyright notice // and this permission notice appear in supporting documentation. None // of the above authors, nor IBM Haifa Research Laboratories, make any // representation about the suitability of this software for any // purpose. It is provided "as is" without express or implied // warranty. /** * @file binomial_heap_base_.hpp * Contains an implementation class for a base of binomial heaps. */ #ifndef PB_DS_BINOMIAL_HEAP_BASE_HPP #define PB_DS_BINOMIAL_HEAP_BASE_HPP /* * Binomial heap base. * Vuillemin J is the mastah. * Modified from CLRS. */ #include <debug/debug.h> #include <ext/pb_ds/detail/cond_dealtor.hpp> #include <ext/pb_ds/detail/type_utils.hpp> #include <ext/pb_ds/detail/left_child_next_sibling_heap_/left_child_next_sibling_heap_.hpp> #include <ext/pb_ds/detail/left_child_next_sibling_heap_/null_metadata.hpp> namespace __gnu_pbds { namespace detail { #define PB_DS_CLASS_T_DEC \ template<typename Value_Type, class Cmp_Fn, class Allocator> #define PB_DS_CLASS_C_DEC \ binomial_heap_base_<Value_Type, Cmp_Fn, Allocator> #ifdef _GLIBCXX_DEBUG #define PB_DS_BASE_C_DEC \ left_child_next_sibling_heap_<Value_Type, Cmp_Fn, \ typename Allocator::size_type, \ Allocator, false> #else #define PB_DS_BASE_C_DEC \ left_child_next_sibling_heap_<Value_Type, Cmp_Fn, \ typename Allocator::size_type, Allocator> #endif /** * class description = "8y|\|0|\/|i41 h34p 74813"> **/ template<typename Value_Type, class Cmp_Fn, class Allocator> class binomial_heap_base_ : public PB_DS_BASE_C_DEC { private: typedef PB_DS_BASE_C_DEC base_type; protected: typedef typename base_type::node node; typedef typename base_type::node_pointer node_pointer; typedef typename base_type::const_node_pointer const_node_pointer; public: typedef typename Allocator::size_type size_type; typedef typename Allocator::difference_type difference_type; typedef Value_Type value_type; typedef typename Allocator::template rebind< value_type>::other::pointer pointer; typedef typename Allocator::template rebind< value_type>::other::const_pointer const_pointer; typedef typename Allocator::template rebind< value_type>::other::reference reference; typedef typename Allocator::template rebind< value_type>::other::const_reference const_reference; typedef typename PB_DS_BASE_C_DEC::const_point_iterator const_point_iterator; typedef typename PB_DS_BASE_C_DEC::point_iterator point_iterator; typedef typename PB_DS_BASE_C_DEC::const_iterator const_iterator; typedef typename PB_DS_BASE_C_DEC::iterator iterator; typedef Cmp_Fn cmp_fn; typedef Allocator allocator_type; public: inline point_iterator push(const_reference r_val); void modify(point_iterator it, const_reference r_new_val); inline const_reference top() const; void pop(); void erase(point_iterator it); inline void clear(); template<typename Pred> size_type erase_if(Pred pred); template<typename Pred> void split(Pred pred, PB_DS_CLASS_C_DEC& other); void join(PB_DS_CLASS_C_DEC& other); protected: binomial_heap_base_(); binomial_heap_base_(const Cmp_Fn& r_cmp_fn); binomial_heap_base_(const PB_DS_CLASS_C_DEC& other); void swap(PB_DS_CLASS_C_DEC& other); ~binomial_heap_base_(); template<typename It> void copy_from_range(It first_it, It last_it); inline void find_max(); #ifdef _GLIBCXX_DEBUG void assert_valid(bool strictly_binomial) const; void assert_max() const; #endif private: inline node_pointer fix(node_pointer p_nd) const; inline void insert_node(node_pointer p_nd); inline void remove_parentless_node(node_pointer p_nd); inline node_pointer join(node_pointer p_lhs, node_pointer p_rhs) const; #ifdef _GLIBCXX_DEBUG void assert_node_consistent(const_node_pointer, bool, bool) const; #endif protected: node_pointer m_p_max; }; #include <ext/pb_ds/detail/binomial_heap_base_/constructors_destructor_fn_imps.hpp> #include <ext/pb_ds/detail/binomial_heap_base_/debug_fn_imps.hpp> #include <ext/pb_ds/detail/binomial_heap_base_/find_fn_imps.hpp> #include <ext/pb_ds/detail/binomial_heap_base_/insert_fn_imps.hpp> #include <ext/pb_ds/detail/binomial_heap_base_/erase_fn_imps.hpp> #include <ext/pb_ds/detail/binomial_heap_base_/split_join_fn_imps.hpp> #undef PB_DS_CLASS_C_DEC #undef PB_DS_CLASS_T_DEC #undef PB_DS_BASE_C_DEC } // namespace detail } // namespace __gnu_pbds #endif
26.204255
91
0.729458
lvjianmin-loongson
9c9ad6755960492a50c414be65c6f06b2bee3a93
35,058
cpp
C++
Source/Tools/Editor/Editor.cpp
tatjam/rbfx
565b505a8ded1ddf6e0fd0f322e004cb9aefc499
[ "MIT" ]
1
2021-01-09T14:42:48.000Z
2021-01-09T14:42:48.000Z
Source/Tools/Editor/Editor.cpp
tatjam/rbfx
565b505a8ded1ddf6e0fd0f322e004cb9aefc499
[ "MIT" ]
null
null
null
Source/Tools/Editor/Editor.cpp
tatjam/rbfx
565b505a8ded1ddf6e0fd0f322e004cb9aefc499
[ "MIT" ]
1
2020-06-29T08:05:12.000Z
2020-06-29T08:05:12.000Z
// // Copyright (c) 2017-2020 the rbfx project. // // 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. // #ifdef WIN32 #include <windows.h> #endif #include <Urho3D/Engine/EngineDefs.h> #include <Urho3D/Engine/EngineEvents.h> #include <Urho3D/Core/CoreEvents.h> #include <Urho3D/Core/WorkQueue.h> #include <Urho3D/Graphics/Graphics.h> #include <Urho3D/Graphics/Model.h> #include <Urho3D/IO/FileSystem.h> #include <Urho3D/IO/Log.h> #include <Urho3D/Resource/JSONArchive.h> #include <Urho3D/Resource/ResourceCache.h> #include <Urho3D/SystemUI/SystemUI.h> #include <Urho3D/SystemUI/Console.h> #include <Urho3D/SystemUI/DebugHud.h> #include <Urho3D/LibraryInfo.h> #include <Urho3D/Core/CommandLine.h> #include <Urho3D/Audio/Sound.h> #include <Toolbox/ToolboxAPI.h> #include <Toolbox/SystemUI/Widgets.h> #include <IconFontCppHeaders/IconsFontAwesome5.h> #include <nativefiledialog/nfd.h> #include "Editor.h" #include "EditorEvents.h" #include "EditorIconCache.h" #include "Tabs/Scene/SceneTab.h" #include "Tabs/Scene/EditorSceneSettings.h" #include "Tabs/UI/UITab.h" #include "Tabs/InspectorTab.h" #include "Tabs/HierarchyTab.h" #include "Tabs/ConsoleTab.h" #include "Tabs/ResourceTab.h" #include "Tabs/PreviewTab.h" #include "Pipeline/Asset.h" #include "Pipeline/Commands/CookScene.h" #include "Pipeline/Commands/BuildAssets.h" #include "Pipeline/Importers/ModelImporter.h" #include "Pipeline/Importers/SceneConverter.h" #include "Pipeline/Importers/TextureImporter.h" #if URHO3D_PLUGINS # include "Plugins/PluginManager.h" # include "Plugins/ModulePlugin.h" #endif #include "Plugins/ScriptBundlePlugin.h" #include "Inspector/AssetInspector.h" #include "Inspector/MaterialInspector.h" #include "Inspector/ModelInspector.h" #include "Inspector/NodeInspector.h" #include "Inspector/ComponentInspector.h" #include "Inspector/SerializableInspector.h" #include "Inspector/SoundInspector.h" #include "Inspector/UIElementInspector.h" #include "Tabs/ProfilerTab.h" #include "EditorUndo.h" namespace Urho3D { namespace { const auto&& DEFAULT_TAB_TYPES = { InspectorTab::GetTypeStatic(), HierarchyTab::GetTypeStatic(), ResourceTab::GetTypeStatic(), ConsoleTab::GetTypeStatic(), PreviewTab::GetTypeStatic(), SceneTab::GetTypeStatic(), ProfilerTab::GetTypeStatic() }; } Editor::Editor(Context* context) : Application(context) { } void Editor::Setup() { context_->RegisterSubsystem(this, Editor::GetTypeStatic()); #ifdef _WIN32 // Required until SDL supports hdpi on windows if (HMODULE hLibrary = LoadLibraryA("Shcore.dll")) { typedef HRESULT(WINAPI*SetProcessDpiAwarenessType)(size_t value); if (auto fn = GetProcAddress(hLibrary, "SetProcessDpiAwareness")) ((SetProcessDpiAwarenessType)fn)(2); // PROCESS_PER_MONITOR_DPI_AWARE FreeLibrary(hLibrary); } #endif // Discover resource prefix path by looking for CoreData and going up. for (coreResourcePrefixPath_ = context_->GetFileSystem()->GetProgramDir();; coreResourcePrefixPath_ = GetParentPath(coreResourcePrefixPath_)) { if (context_->GetFileSystem()->DirExists(coreResourcePrefixPath_ + "CoreData")) break; else { #if WIN32 if (coreResourcePrefixPath_.length() <= 3) // Root path of any drive #else if (coreResourcePrefixPath_ == "/") // Filesystem root #endif { URHO3D_LOGERROR("Prefix path not found, unable to continue. Prefix path must contain all of your data " "directories (including CoreData)."); engine_->Exit(); } } } engineParameters_[EP_WINDOW_TITLE] = GetTypeName(); engineParameters_[EP_HEADLESS] = false; engineParameters_[EP_FULL_SCREEN] = false; engineParameters_[EP_LOG_LEVEL] = LOG_DEBUG; engineParameters_[EP_WINDOW_RESIZABLE] = true; engineParameters_[EP_AUTOLOAD_PATHS] = ""; engineParameters_[EP_RESOURCE_PATHS] = "CoreData;EditorData"; engineParameters_[EP_RESOURCE_PREFIX_PATHS] = coreResourcePrefixPath_; engineParameters_[EP_WINDOW_MAXIMIZE] = true; engineParameters_[EP_ENGINE_AUTO_LOAD_SCRIPTS] = false; #if URHO3D_SYSTEMUI_VIEWPORTS engineParameters_[EP_HIGH_DPI] = true; engineParameters_[EP_SYSTEMUI_FLAGS] = ImGuiConfigFlags_ViewportsEnable | ImGuiConfigFlags_DpiEnableScaleViewports; #else engineParameters_[EP_HIGH_DPI] = false; #endif // Load editor settings { auto* fs = context_->GetFileSystem(); ea::string editorSettingsDir = fs->GetAppPreferencesDir("rbfx", "Editor"); if (!fs->DirExists(editorSettingsDir)) fs->CreateDir(editorSettingsDir); ea::string editorSettingsFile = editorSettingsDir + "Editor.json"; if (fs->FileExists(editorSettingsFile)) { JSONFile file(context_); if (file.LoadFile(editorSettingsFile)) { JSONInputArchive archive(&file); if (!Serialize(archive)) URHO3D_LOGERROR("Loading of editor settings failed."); engineParameters_[EP_WINDOW_WIDTH] = windowSize_.x_; engineParameters_[EP_WINDOW_HEIGHT] = windowSize_.y_; engineParameters_[EP_WINDOW_POSITION_X] = windowPos_.x_; engineParameters_[EP_WINDOW_POSITION_Y] = windowPos_.y_; } } } context_->GetLog()->SetLogFormat("[%H:%M:%S] [%l] [%n] : %v"); SetRandomSeed(Time::GetTimeSinceEpoch()); // Register factories context_->RegisterFactory<EditorIconCache>(); context_->RegisterFactory<SceneTab>(); context_->RegisterFactory<UITab>(); context_->RegisterFactory<ConsoleTab>(); context_->RegisterFactory<HierarchyTab>(); context_->RegisterFactory<InspectorTab>(); context_->RegisterFactory<ResourceTab>(); context_->RegisterFactory<PreviewTab>(); context_->RegisterFactory<ProfilerTab>(); // Inspectors. inspectors_.push_back(SharedPtr(new AssetInspector(context_))); inspectors_.push_back(SharedPtr(new ModelInspector(context_))); inspectors_.push_back(SharedPtr(new MaterialInspector(context_))); inspectors_.push_back(SharedPtr(new SoundInspector(context_))); inspectors_.push_back(SharedPtr(new NodeInspector(context_))); inspectors_.push_back(SharedPtr(new ComponentInspector(context_))); inspectors_.push_back(SharedPtr(new UIElementInspector(context_))); // FIXME: If user registers their own inspector later then SerializableInspector would no longer come in last. inspectors_.push_back(SharedPtr(new SerializableInspector(context_))); #if URHO3D_PLUGINS RegisterPluginsLibrary(context_); #endif RegisterToolboxTypes(context_); EditorSceneSettings::RegisterObject(context_); context_->RegisterFactory<SerializableInspector>(); // Importers ModelImporter::RegisterObject(context_); SceneConverter::RegisterObject(context_); TextureImporter::RegisterObject(context_); Asset::RegisterObject(context_); // Define custom command line parameters here auto& cmd = GetCommandLineParser(); cmd.add_option("project", defaultProjectPath_, "Project to open or create on startup.")->set_custom_option("dir"); // Subcommands RegisterSubcommand<CookScene>(); RegisterSubcommand<BuildAssets>(); keyBindings_.Bind(ActionType::OpenProject, this, &Editor::OpenOrCreateProject); keyBindings_.Bind(ActionType::Exit, this, &Editor::OnExitHotkeyPressed); } void Editor::Start() { // Execute specified subcommand and exit. for (SharedPtr<SubCommand>& cmd : subCommands_) { if (GetCommandLineParser().got_subcommand(cmd->GetTypeName().c_str())) { context_->GetLog()->SetLogFormat("%v"); ExecuteSubcommand(cmd); engine_->Exit(); return; } } // Continue with normal editor initialization context_->RegisterSubsystem(new SceneManager(context_)); context_->RegisterSubsystem(new EditorIconCache(context_)); context_->GetInput()->SetMouseMode(MM_ABSOLUTE); context_->GetInput()->SetMouseVisible(true); context_->GetCache()->SetAutoReloadResources(true); engine_->SetAutoExit(false); SubscribeToEvent(E_UPDATE, [this](StringHash, VariantMap& args) { OnUpdate(args); }); // Creates console but makes sure it's UI is not rendered. Console rendering is done manually in editor. auto* console = engine_->CreateConsole(); console->SetAutoVisibleOnError(false); context_->GetFileSystem()->SetExecuteConsoleCommands(false); SubscribeToEvent(E_CONSOLECOMMAND, [this](StringHash, VariantMap& args) { OnConsoleCommand(args); }); console->RefreshInterpreters(); SubscribeToEvent(E_ENDFRAME, [this](StringHash, VariantMap&) { OnEndFrame(); }); SubscribeToEvent(E_EXITREQUESTED, [this](StringHash, VariantMap&) { OnExitRequested(); }); SubscribeToEvent(E_EDITORPROJECTSERIALIZE, [this](StringHash, VariantMap&) { UpdateWindowTitle(); }); SubscribeToEvent(E_CONSOLEURICLICK, [this](StringHash, VariantMap& args) { OnConsoleUriClick(args); }); SubscribeToEvent(E_EDITORSELECTIONCHANGED, &Editor::OnSelectionChanged); SetupSystemUI(); if (!defaultProjectPath_.empty()) { ui::GetIO().IniFilename = nullptr; // Avoid creating imgui.ini in some cases OpenProject(defaultProjectPath_); } // Hud will be rendered manually. context_->GetEngine()->CreateDebugHud()->SetMode(DEBUGHUD_SHOW_NONE); } void Editor::ExecuteSubcommand(SubCommand* cmd) { if (!defaultProjectPath_.empty()) { project_ = new Project(context_); context_->RegisterSubsystem(project_); if (!project_->LoadProject(defaultProjectPath_)) { URHO3D_LOGERRORF("Loading project '%s' failed.", pendingOpenProject_.c_str()); exitCode_ = EXIT_FAILURE; engine_->Exit(); return; } } cmd->Execute(); } void Editor::Stop() { // Save editor settings if (!engine_->IsHeadless()) { // Save window geometry auto* graphics = GetSubsystem<Graphics>(); windowPos_ = graphics->GetWindowPosition(); windowSize_ = graphics->GetSize(); auto* fs = context_->GetFileSystem(); ea::string editorSettingsDir = fs->GetAppPreferencesDir("rbfx", "Editor"); if (!fs->DirExists(editorSettingsDir)) fs->CreateDir(editorSettingsDir); JSONFile json(context_); JSONOutputArchive archive(&json); if (Serialize(archive)) { if (!json.SaveFile(editorSettingsDir + "Editor.json")) URHO3D_LOGERROR("Saving of editor settings failed."); } else URHO3D_LOGERROR("Serializing of editor settings failed."); } context_->GetWorkQueue()->Complete(0); if (auto* manager = GetSubsystem<SceneManager>()) manager->UnloadAll(); CloseProject(); context_->RemoveSubsystem<WorkQueue>(); // Prevents deadlock when unloading plugin AppDomain in managed host. context_->RemoveSubsystem<Editor>(); } void Editor::OnUpdate(VariantMap& args) { ImGuiWindowFlags flags = ImGuiWindowFlags_MenuBar; flags |= ImGuiWindowFlags_NoDocking; ImGuiViewport* viewport = ImGui::GetMainViewport(); ImGui::SetNextWindowPos(viewport->Pos); ImGui::SetNextWindowSize(viewport->Size); ImGui::SetNextWindowViewport(viewport->ID); ImGui::PushStyleVar(ImGuiStyleVar_WindowRounding, 0.0f); flags |= ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove; flags |= ImGuiWindowFlags_NoBringToFrontOnFocus | ImGuiWindowFlags_NoNavFocus; ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(0.0f, 0.0f)); ImGui::Begin("DockSpace", nullptr, flags); ImGui::PopStyleVar(); RenderMenuBar(); RenderSettingsWindow(); bool hasModified = false; if (project_.NotNull()) { dockspaceId_ = ui::GetID("Root"); ui::DockSpace(dockspaceId_); auto tabsCopy = tabs_; for (auto& tab : tabsCopy) { if (tab->RenderWindow()) { // Only active window may override another active window if (activeTab_ != tab && tab->IsActive()) { activeTab_ = tab; tab->OnFocused(); } hasModified |= tab->IsModified(); } else if (!tab->IsUtility()) // Content tabs get closed permanently tabs_.erase(tabs_.find(tab)); } if (!activeTab_.Expired()) { activeTab_->OnActiveUpdate(); } if (loadDefaultLayout_ && project_) { loadDefaultLayout_ = false; LoadDefaultLayout(); } } else { // Render start page auto& style = ui::GetStyle(); auto* lists = ui::GetWindowDrawList(); ImRect rect{ui::GetWindowContentRegionMin(), ui::GetWindowContentRegionMax()}; ImVec2 tileSize{200, 200}; ui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2{10, 10}); ui::SetCursorPos(rect.GetCenter() - ImVec2{tileSize.x * 1.5f + 10, tileSize.y * 1.5f + 10}); ui::BeginGroup(); struct State { explicit State(Editor* editor) { FileSystem *fs = editor->GetContext()->GetFileSystem(); StringVector& recents = editor->recentProjects_; snapshots_.resize(recents.size()); for (int i = 0; i < recents.size();) { const ea::string& projectPath = recents[i]; ea::string snapshotFile = AddTrailingSlash(projectPath) + ".snapshot.png"; if (fs->FileExists(snapshotFile)) { Image img(editor->context_); if (img.LoadFile(snapshotFile)) { SharedPtr<Texture2D> texture(editor->context_->CreateObject<Texture2D>()); texture->SetData(&img); snapshots_[i] = texture; } } ++i; } } ea::vector<SharedPtr<Texture2D>> snapshots_; }; auto* state = ui::GetUIState<State>(this); const StringVector& recents = recentProjects_; int index = 0; for (int row = 0; row < 3; row++) { for (int col = 0; col < 3; col++, index++) { SharedPtr<Texture2D> snapshot; if (state->snapshots_.size() > index) snapshot = state->snapshots_[index]; if (recents.size() <= index || (row == 2 && col == 2)) // Last tile never shows a project. { if (ui::Button("Open/Create Project", tileSize)) OpenOrCreateProject(); } else { const ea::string& projectPath = recents[index]; if (snapshot.NotNull()) { if (ui::ImageButton(snapshot.Get(), tileSize - style.ItemInnerSpacing * 2)) OpenProject(projectPath); } else { if (ui::Button(recents[index].c_str(), tileSize)) OpenProject(projectPath); } if (ui::IsItemHovered()) ui::SetTooltip("%s", projectPath.c_str()); } ui::SameLine(); } ui::NewLine(); } ui::EndGroup(); ui::PopStyleVar(); } ui::End(); ImGui::PopStyleVar(); // Dialog for a warning when application is being closed with unsaved resources. if (exiting_) { if (!context_->GetWorkQueue()->IsCompleted(0)) { ui::OpenPopup("Completing Tasks"); if (ui::BeginPopupModal("Completing Tasks", nullptr, ImGuiWindowFlags_NoDocking | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_Popup)) { ui::TextUnformatted("Some tasks are in progress and are being completed. Please wait."); static float totalIncomplete = context_->GetWorkQueue()->GetNumIncomplete(0); ui::ProgressBar(100.f / totalIncomplete * Min(totalIncomplete - (float)context_->GetWorkQueue()->GetNumIncomplete(0), totalIncomplete)); ui::EndPopup(); } } else if (hasModified) { ui::OpenPopup("Save All?"); if (ui::BeginPopupModal("Save All?", nullptr, ImGuiWindowFlags_NoDocking | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_Popup)) { ui::TextUnformatted("You have unsaved resources. Save them before exiting?"); if (ui::Button(ICON_FA_SAVE " Save & Close")) { for (auto& tab : tabs_) { if (tab->IsModified()) tab->SaveResource(); } ui::CloseCurrentPopup(); } ui::SameLine(); if (ui::Button(ICON_FA_EXCLAMATION_TRIANGLE " Close without saving")) { engine_->Exit(); } ui::SetHelpTooltip(ICON_FA_EXCLAMATION_TRIANGLE " All unsaved changes will be lost!", KEY_UNKNOWN); ui::SameLine(); if (ui::Button(ICON_FA_TIMES " Cancel")) { exiting_ = false; ui::CloseCurrentPopup(); } ui::EndPopup(); } } else { context_->GetWorkQueue()->Complete(0); if (project_.NotNull()) { project_->SaveProject(); CloseProject(); } engine_->Exit(); } } } Tab* Editor::CreateTab(StringHash type) { SharedPtr<Tab> tab(DynamicCast<Tab>(context_->CreateObject(type))); tabs_.push_back(tab); return tab.Get(); } StringVector Editor::GetObjectsByCategory(const ea::string& category) { StringVector result; const auto& factories = context_->GetObjectFactories(); auto it = context_->GetObjectCategories().find(category); if (it != context_->GetObjectCategories().end()) { for (const StringHash& type : it->second) { auto jt = factories.find(type); if (jt != factories.end()) result.push_back(jt->second->GetTypeName()); } } return result; } void Editor::OnConsoleCommand(VariantMap& args) { using namespace ConsoleCommand; if (args[P_COMMAND].GetString() == "revision") URHO3D_LOGINFOF("Engine revision: %s", GetRevision()); } void Editor::OnEndFrame() { // Opening a new project must be done at the point when SystemUI is not in use. End of the frame is a good // candidate. This subsystem will be recreated. if (!pendingOpenProject_.empty()) { CloseProject(); // Reset SystemUI so that imgui loads it's config proper. context_->RemoveSubsystem<SystemUI>(); #if URHO3D_SYSTEMUI_VIEWPORTS unsigned flags = ImGuiConfigFlags_ViewportsEnable | ImGuiConfigFlags_DpiEnableScaleViewports; #else unsigned flags = 0; #endif context_->RegisterSubsystem(new SystemUI(context_, flags)); SetupSystemUI(); project_ = new Project(context_); context_->RegisterSubsystem(project_); bool loaded = project_->LoadProject(pendingOpenProject_); // SystemUI has to be started after loading project, because project sets custom settings file path. Starting // subsystem reads this file and loads settings. if (loaded) { auto* fs = context_->GetFileSystem(); loadDefaultLayout_ = project_->NeeDefaultUIPlacement(); StringVector& recents = recentProjects_; // Remove latest project if it was already opened or any projects that no longer exists. for (auto it = recents.begin(); it != recents.end();) { if (*it == pendingOpenProject_ || !fs->DirExists(*it)) it = recents.erase(it); else ++it; } // Latest project goes to front recents.insert(recents.begin(), pendingOpenProject_); // Limit recents list size if (recents.size() > 10) recents.resize(10); } else { CloseProject(); URHO3D_LOGERROR("Loading project failed."); } pendingOpenProject_.clear(); } } void Editor::OnExitRequested() { if (auto* preview = GetTab<PreviewTab>()) { if (preview->GetSceneSimulationStatus() != SCENE_SIMULATION_STOPPED) preview->Stop(); } exiting_ = true; } void Editor::OnExitHotkeyPressed() { if (!exiting_) OnExitRequested(); } void Editor::CreateDefaultTabs() { for (StringHash type : DEFAULT_TAB_TYPES) context_->RemoveSubsystem(type); tabs_.clear(); for (StringHash type : DEFAULT_TAB_TYPES) { SharedPtr<Tab> tab; tab.StaticCast(context_->CreateObject(type)); tabs_.push_back(tab); } } void Editor::LoadDefaultLayout() { CreateDefaultTabs(); auto* inspector = GetTab<InspectorTab>(); auto* hierarchy = GetTab<HierarchyTab>(); auto* resources = GetTab<ResourceTab>(); auto* console = GetTab<ConsoleTab>(); auto* preview = GetTab<PreviewTab>(); auto* scene = GetTab<SceneTab>(); auto* profiler = GetTab<ProfilerTab>(); profiler->SetOpen(false); ImGui::DockBuilderRemoveNode(dockspaceId_); ImGui::DockBuilderAddNode(dockspaceId_, 0); ImGui::DockBuilderSetNodeSize(dockspaceId_, ui::GetMainViewport()->Size); ImGuiID dock_main_id = dockspaceId_; ImGuiID dockHierarchy = ImGui::DockBuilderSplitNode(dock_main_id, ImGuiDir_Left, 0.20f, nullptr, &dock_main_id); ImGuiID dockResources = ImGui::DockBuilderSplitNode(dockHierarchy, ImGuiDir_Down, 0.40f, nullptr, &dockHierarchy); ImGuiID dockInspector = ImGui::DockBuilderSplitNode(dock_main_id, ImGuiDir_Right, 0.30f, nullptr, &dock_main_id); ImGuiID dockLog = ImGui::DockBuilderSplitNode(dock_main_id, ImGuiDir_Down, 0.30f, nullptr, &dock_main_id); ImGui::DockBuilderDockWindow(hierarchy->GetUniqueTitle().c_str(), dockHierarchy); ImGui::DockBuilderDockWindow(resources->GetUniqueTitle().c_str(), dockResources); ImGui::DockBuilderDockWindow(console->GetUniqueTitle().c_str(), dockLog); ImGui::DockBuilderDockWindow(profiler->GetUniqueTitle().c_str(), dockLog); ImGui::DockBuilderDockWindow(scene->GetUniqueTitle().c_str(), dock_main_id); ImGui::DockBuilderDockWindow(preview->GetUniqueTitle().c_str(), dock_main_id); ImGui::DockBuilderDockWindow(inspector->GetUniqueTitle().c_str(), dockInspector); ImGui::DockBuilderFinish(dockspaceId_); scene->Activate(); } void Editor::OpenProject(const ea::string& projectPath) { pendingOpenProject_ = AddTrailingSlash(projectPath); } void Editor::CloseProject() { SendEvent(E_EDITORPROJECTCLOSING); context_->RemoveSubsystem<Project>(); for (StringHash type : DEFAULT_TAB_TYPES) context_->RemoveSubsystem(type); tabs_.clear(); project_.Reset(); } Tab* Editor::GetTabByName(const ea::string& uniqueName) { for (auto& tab : tabs_) { if (tab->GetUniqueName() == uniqueName) return tab.Get(); } return nullptr; } Tab* Editor::GetTabByResource(const ea::string& resourceName) { for (auto& tab : tabs_) { auto resource = DynamicCast<BaseResourceTab>(tab); if (resource && resource->GetResourceName() == resourceName) return resource.Get(); } return nullptr; } Tab* Editor::GetTab(StringHash type) { for (auto& tab : tabs_) { if (tab->GetType() == type) return tab.Get(); } return nullptr; } void Editor::SetupSystemUI() { static ImWchar fontAwesomeIconRanges[] = {ICON_MIN_FA, ICON_MAX_FA, 0}; static ImWchar notoSansRanges[] = {0x20, 0x52f, 0x1ab0, 0x2189, 0x2c60, 0x2e44, 0xa640, 0xab65, 0}; static ImWchar notoMonoRanges[] = {0x20, 0x513, 0x1e00, 0x1f4d, 0}; SystemUI* systemUI = GetSubsystem<SystemUI>(); systemUI->ApplyStyleDefault(true, 1.0f); systemUI->AddFont("Fonts/NotoSans-Regular.ttf", notoSansRanges, 16.f); systemUI->AddFont("Fonts/" FONT_ICON_FILE_NAME_FAS, fontAwesomeIconRanges, 14.f, true); monoFont_ = systemUI->AddFont("Fonts/NotoMono-Regular.ttf", notoMonoRanges, 14.f); systemUI->AddFont("Fonts/" FONT_ICON_FILE_NAME_FAS, fontAwesomeIconRanges, 12.f, true); ui::GetStyle().WindowRounding = 3; // Disable imgui saving ui settings on it's own. These should be serialized to project file. auto& io = ui::GetIO(); #if URHO3D_SYSTEMUI_VIEWPORTS io.ConfigViewportsNoAutoMerge = true; #endif io.IniFilename = nullptr; io.ConfigFlags |= ImGuiConfigFlags_DockingEnable | ImGuiConfigFlags_NavEnableKeyboard; io.BackendFlags |= ImGuiBackendFlags_HasMouseCursors; io.ConfigWindowsResizeFromEdges = true; // TODO: Make configurable. auto& style = ImGui::GetStyle(); style.FrameBorderSize = 0; style.WindowBorderSize = 1; style.ItemSpacing = {4, 4}; ImVec4* colors = ImGui::GetStyle().Colors; colors[ImGuiCol_Text] = ImVec4(1.00f, 1.00f, 1.00f, 1.00f); colors[ImGuiCol_TextDisabled] = ImVec4(0.50f, 0.50f, 0.50f, 1.00f); colors[ImGuiCol_WindowBg] = ImVec4(0.16f, 0.16f, 0.16f, 1.00f); colors[ImGuiCol_ChildBg] = ImVec4(0.16f, 0.16f, 0.16f, 1.00f); colors[ImGuiCol_PopupBg] = ImVec4(0.14f, 0.14f, 0.14f, 1.00f); colors[ImGuiCol_Border] = ImVec4(0.24f, 0.24f, 0.24f, 1.00f); colors[ImGuiCol_BorderShadow] = ImVec4(0.00f, 0.00f, 0.00f, 0.00f); colors[ImGuiCol_FrameBg] = ImVec4(0.26f, 0.26f, 0.26f, 1.00f); colors[ImGuiCol_FrameBgHovered] = ImVec4(0.32f, 0.32f, 0.32f, 1.00f); colors[ImGuiCol_FrameBgActive] = ImVec4(0.37f, 0.37f, 0.37f, 1.00f); colors[ImGuiCol_TitleBg] = ImVec4(0.12f, 0.12f, 0.12f, 1.00f); colors[ImGuiCol_TitleBgActive] = ImVec4(0.16f, 0.16f, 0.16f, 1.00f); colors[ImGuiCol_TitleBgCollapsed] = ImVec4(0.16f, 0.16f, 0.16f, 1.00f); colors[ImGuiCol_MenuBarBg] = ImVec4(0.14f, 0.14f, 0.14f, 1.00f); colors[ImGuiCol_ScrollbarBg] = ImVec4(0.02f, 0.02f, 0.02f, 0.00f); colors[ImGuiCol_ScrollbarGrab] = ImVec4(0.31f, 0.31f, 0.31f, 1.00f); colors[ImGuiCol_ScrollbarGrabHovered] = ImVec4(0.41f, 0.41f, 0.41f, 1.00f); colors[ImGuiCol_ScrollbarGrabActive] = ImVec4(0.51f, 0.51f, 0.51f, 1.00f); colors[ImGuiCol_CheckMark] = ImVec4(0.51f, 0.51f, 0.51f, 1.00f); colors[ImGuiCol_SliderGrab] = ImVec4(0.51f, 0.51f, 0.51f, 1.00f); colors[ImGuiCol_SliderGrabActive] = ImVec4(0.56f, 0.56f, 0.56f, 1.00f); colors[ImGuiCol_Button] = ImVec4(0.27f, 0.27f, 0.27f, 1.00f); colors[ImGuiCol_ButtonHovered] = ImVec4(0.34f, 0.34f, 0.34f, 1.00f); colors[ImGuiCol_ButtonActive] = ImVec4(0.38f, 0.38f, 0.38f, 1.00f); colors[ImGuiCol_Header] = ImVec4(0.35f, 0.35f, 0.35f, 1.00f); colors[ImGuiCol_HeaderHovered] = ImVec4(0.39f, 0.39f, 0.39f, 1.00f); colors[ImGuiCol_HeaderActive] = ImVec4(0.44f, 0.44f, 0.44f, 1.00f); colors[ImGuiCol_Separator] = ImVec4(0.24f, 0.24f, 0.24f, 1.00f); colors[ImGuiCol_SeparatorHovered] = ImVec4(0.31f, 0.31f, 0.31f, 1.00f); colors[ImGuiCol_SeparatorActive] = ImVec4(0.34f, 0.34f, 0.34f, 1.00f); colors[ImGuiCol_ResizeGrip] = ImVec4(0.24f, 0.24f, 0.24f, 1.00f); colors[ImGuiCol_ResizeGripHovered] = ImVec4(0.31f, 0.31f, 0.31f, 1.00f); colors[ImGuiCol_ResizeGripActive] = ImVec4(0.37f, 0.37f, 0.37f, 1.00f); colors[ImGuiCol_Tab] = ImVec4(0.26f, 0.26f, 0.26f, 0.40f); colors[ImGuiCol_TabHovered] = ImVec4(0.31f, 0.31f, 0.31f, 1.00f); colors[ImGuiCol_TabActive] = ImVec4(0.28f, 0.28f, 0.28f, 1.00f); colors[ImGuiCol_TabUnfocused] = ImVec4(0.17f, 0.17f, 0.17f, 1.00f); colors[ImGuiCol_TabUnfocusedActive] = ImVec4(0.26f, 0.26f, 0.26f, 1.00f); colors[ImGuiCol_DockingPreview] = ImVec4(0.55f, 0.55f, 0.55f, 1.00f); colors[ImGuiCol_DockingEmptyBg] = ImVec4(0.20f, 0.20f, 0.20f, 1.00f); colors[ImGuiCol_PlotLines] = ImVec4(0.61f, 0.61f, 0.61f, 1.00f); colors[ImGuiCol_PlotLinesHovered] = ImVec4(1.00f, 0.43f, 0.35f, 1.00f); colors[ImGuiCol_PlotHistogram] = ImVec4(0.90f, 0.70f, 0.00f, 1.00f); colors[ImGuiCol_PlotHistogramHovered] = ImVec4(1.00f, 0.60f, 0.00f, 1.00f); colors[ImGuiCol_TextSelectedBg] = ImVec4(0.26f, 0.59f, 0.98f, 0.35f); colors[ImGuiCol_DragDropTarget] = ImVec4(1.00f, 1.00f, 0.00f, 0.90f); colors[ImGuiCol_NavHighlight] = ImVec4(0.78f, 0.88f, 1.00f, 1.00f); colors[ImGuiCol_NavWindowingHighlight] = ImVec4(1.00f, 1.00f, 1.00f, 0.70f); colors[ImGuiCol_NavWindowingDimBg] = ImVec4(0.80f, 0.80f, 0.80f, 0.20f); colors[ImGuiCol_ModalWindowDimBg] = ImVec4(0.44f, 0.44f, 0.44f, 0.35f); ImGuiSettingsHandler handler; handler.TypeName = "Project"; handler.TypeHash = ImHashStr(handler.TypeName, 0, 0); handler.ReadOpenFn = [](ImGuiContext* context, ImGuiSettingsHandler* handler, const char* name) -> void* { return (void*) name; }; handler.ReadLineFn = [](ImGuiContext*, ImGuiSettingsHandler*, void* entry, const char* line) { auto* systemUI = ui::GetSystemUI(); auto* editor = systemUI->GetSubsystem<Editor>(); const char* name = static_cast<const char*>(entry); if (strcmp(name, "Window") == 0) editor->CreateDefaultTabs(); else { Tab* tab = editor->GetTabByName(name); if (tab == nullptr) { StringVector parts = ea::string(name).split('#'); tab = editor->CreateTab(parts.front()); } tab->OnLoadUISettings(name, line); } }; handler.WriteAllFn = [](ImGuiContext* imgui_ctx, ImGuiSettingsHandler* handler, ImGuiTextBuffer* buf) { auto* systemUI = ui::GetSystemUI(); auto* editor = systemUI->GetSubsystem<Editor>(); buf->appendf("[Project][Window]\n"); // Save tabs for (auto& tab : editor->GetContentTabs()) tab->OnSaveUISettings(buf); }; ui::GetCurrentContext()->SettingsHandlers.push_back(handler); } void Editor::UpdateWindowTitle(const ea::string& resourcePath) { if (context_->GetEngine()->IsHeadless()) return; auto* project = GetSubsystem<Project>(); ea::string title; if (project == nullptr) title = "Editor"; else { ea::string projectName = GetFileName(RemoveTrailingSlash(project->GetProjectPath())); title = ToString("Editor | %s", projectName.c_str()); if (!resourcePath.empty()) title += ToString(" | %s", GetFileName(resourcePath).c_str()); } context_->GetGraphics()->SetWindowTitle(title); } template<typename T> void Editor::RegisterSubcommand() { T::RegisterObject(context_); SharedPtr<T> cmd(context_->CreateObject<T>()); subCommands_.push_back(DynamicCast<SubCommand>(cmd)); if (CLI::App* subCommand = GetCommandLineParser().add_subcommand(T::GetTypeNameStatic().c_str())) cmd->RegisterCommandLine(*subCommand); else URHO3D_LOGERROR("Sub-command '{}' was not registered due to user error.", T::GetTypeNameStatic()); } void Editor::OpenOrCreateProject() { nfdchar_t* projectDir = nullptr; if (NFD_PickFolder("", &projectDir) == NFD_OKAY) { OpenProject(projectDir); NFD_FreePath(projectDir); } } #if URHO3D_STATIC && URHO3D_PLUGINS bool Editor::RegisterPlugin(PluginApplication* plugin) { return project_->GetPlugins()->RegisterPlugin(plugin); } #endif void Editor::OnConsoleUriClick(VariantMap& args) { using namespace ConsoleUriClick; if (ui::IsMouseClicked(MOUSEB_LEFT)) { const ea::string& protocol = args[P_PROTOCOL].GetString(); const ea::string& address = args[P_ADDRESS].GetString(); if (protocol == "res") context_->GetFileSystem()->SystemOpen(context_->GetCache()->GetResourceFileName(address)); } } void Editor::OnSelectionChanged(StringHash, VariantMap& args) { using namespace EditorSelectionChanged; auto tab = static_cast<Tab*>(args[P_TAB].GetPtr()); auto undo = GetSubsystem<UndoStack>(); ByteVector newSelection = tab->SerializeSelection(); if (tab == selectionTab_) { if (newSelection == selectionBuffer_) return; } else { if (!selectionTab_.Expired()) selectionTab_->ClearSelection(); } undo->Add<UndoSetSelection>(selectionTab_, selectionBuffer_, tab, newSelection); selectionTab_ = tab; selectionBuffer_ = newSelection; } }
37.656284
152
0.631325
tatjam
9c9aea0af0fc323928b9b900169e7839ac20ee13
34
hpp
C++
NamedPipes/src/Config.hpp
TDToolbox/btdapi
b8349ef33d5bc2dacc85e96ced86dc37e972e8ee
[ "MIT" ]
null
null
null
NamedPipes/src/Config.hpp
TDToolbox/btdapi
b8349ef33d5bc2dacc85e96ced86dc37e972e8ee
[ "MIT" ]
8
2020-03-10T23:11:09.000Z
2020-03-14T01:19:32.000Z
NamedPipes/src/Config.hpp
TDToolbox/btdapi
b8349ef33d5bc2dacc85e96ced86dc37e972e8ee
[ "MIT" ]
null
null
null
#pragma once #define PIPE_LOGGING
11.333333
20
0.823529
TDToolbox
9c9e1afcf738147c3e40fa2948d52825b8ed25a1
1,393
cpp
C++
src/Fitness/PythonFitness.cpp
NickTUD/GP-GOMEA
f6e150a417855355f520f27db4cfb0b2a9003000
[ "Apache-2.0" ]
1
2022-02-24T17:02:50.000Z
2022-02-24T17:02:50.000Z
src/Fitness/PythonFitness.cpp
dzhliu/evoNSGA-II
060ee4f3191f561829ad5bbe3f813c292caad5b4
[ "Apache-2.0" ]
null
null
null
src/Fitness/PythonFitness.cpp
dzhliu/evoNSGA-II
060ee4f3191f561829ad5bbe3f813c292caad5b4
[ "Apache-2.0" ]
null
null
null
/* */ /* * File: PythonFitness.cpp * Author: virgolin * * Created on May 31, 2019, 12:25 PM */ #include "GPGOMEA/Fitness/PythonFitness.h" using namespace std; using namespace arma; namespace py = boost::python; namespace np = boost::python::numpy; PythonFitness::PythonFitness() { Py_Initialize(); np::initialize(); PyRun_SimpleString("import sys; sys.path.insert(0,'./')"); } void PythonFitness::SetPythonCallableFunction(std::string filename, std::string function_name) { try { py::object module = py::import(py::str(filename)); callable_python_function = py::object(module.attr(py::str(function_name))); } catch (boost::python::error_already_set const &) { std::string err = "PythonFitness::SetPythonCallableFunction error: perhaps misspelled names in pyprobdef?\n" + filename + " " + function_name; throw std::runtime_error(err); } } double_t PythonFitness::ComputeFitness(Node* n, bool use_caching) { evaluations++; vec out = n->GetOutput(this->TrainX, use_caching); np::ndarray npout = Utils::ToNumpyArray(out); //cout << py::str(callable_python_function) << endl; py::object pyresult = callable_python_function(npout); double_t fit = py::extract<double_t>(pyresult); if (std::isnan(fit)) { fit = arma::datum::inf; } n->cached_fitness = fit; return fit; }
24.017241
150
0.667624
NickTUD
9c9e6fae539b7a36045dfb2e1a46ba04630bdc5c
20,900
cpp
C++
planet.cpp
CobaltXII/planet
4b22ecd4df38a971debeb2714001a6450cebf181
[ "MIT" ]
10
2019-01-13T00:21:41.000Z
2021-06-23T20:11:12.000Z
planet.cpp
CobaltXII/planet
4b22ecd4df38a971debeb2714001a6450cebf181
[ "MIT" ]
null
null
null
planet.cpp
CobaltXII/planet
4b22ecd4df38a971debeb2714001a6450cebf181
[ "MIT" ]
2
2020-07-31T22:09:04.000Z
2020-08-11T02:33:46.000Z
/* GLM header include directives. Please use GLM 0.9.9.3 or greater for known results. Previous versions of GLM are not guaranteed to work correctly. */ #include <glm/vec3.hpp> #include <glm/vec4.hpp> #include <glm/mat4x4.hpp> #include <glm/gtc/matrix_transform.hpp> /* libnoise header include directives. libnoise is used to generate coherent noise for generating procedural planets. */ #include <noise/noise.h> /* noiseutils header include directives. noiseutils is used as a utility library on top of libnoise. */ #include "noiseutils.h" /* GLAD header include directives. GLAD is used to load OpenGL 3.3 Core functions. */ #include "glad.h" /* SDL header include directives. Please use SDL 2.0.9 or greater for known results. Previous versions of SDL are not guaranteed to work correctly. */ #include <SDL2/SDL.h> /* Standard header include directives. */ #include <iostream> #include <fstream> #include <sstream> #include <string> #include <vector> #include <tuple> /* A std::tuple<int, int, int> is used to represent a triangle defined by indices in a list of vertices. */ typedef std::tuple<int, int, int> triangle_indices; /* Add a vertex to a std::vector<glm::vec3> while ensuring that the vertex lies on the unit sphere. */ int add_vertex(std::vector<glm::vec3>& vector, glm::vec3 vertex) { vector.push_back(vertex / glm::length(vertex)); return vector.size() - 1; } /* Return the index of a vertex in the middle of p_1 and p_2. */ int get_middle_point(std::vector<glm::vec3>& vector, int p_1, int p_2) { glm::vec3 pt_1 = vector[p_1]; glm::vec3 pt_2 = vector[p_2]; glm::vec3 pt_middle = (pt_1 + pt_2) / 2.0f; int i = add_vertex(vector, pt_middle); return i; } /* Create an icosphere with the given amount of subdivisions. */ std::vector<glm::vec3> create_icosphere(int subdivisions = 8) { // Generate the icosphere's vertices. std::vector<glm::vec3> icosphere_vertices; // Generate the 12 vertices of an icosahedron. float t = (1.0f + sqrt(5.0f)) / 2.0f; add_vertex(icosphere_vertices, glm::vec3(-1.0f, t, 0.0f)); add_vertex(icosphere_vertices, glm::vec3( 1.0f, t, 0.0f)); add_vertex(icosphere_vertices, glm::vec3(-1.0f, -t, 0.0f)); add_vertex(icosphere_vertices, glm::vec3( 1.0f, -t, 0.0f)); add_vertex(icosphere_vertices, glm::vec3(0.0f, -1.0f, t)); add_vertex(icosphere_vertices, glm::vec3(0.0f, 1.0f, t)); add_vertex(icosphere_vertices, glm::vec3(0.0f, -1.0f, -t)); add_vertex(icosphere_vertices, glm::vec3(0.0f, 1.0f, -t)); add_vertex(icosphere_vertices, glm::vec3( t, 0.0f, -1.0f)); add_vertex(icosphere_vertices, glm::vec3( t, 0.0f, 1.0f)); add_vertex(icosphere_vertices, glm::vec3(-t, 0.0f, -1.0f)); add_vertex(icosphere_vertices, glm::vec3(-t, 0.0f, 1.0f)); // Generate the 20 faces of an icosahedron. std::vector<triangle_indices> icosphere_indices; icosphere_indices.push_back(triangle_indices(0x0, 0xB, 0x5)); icosphere_indices.push_back(triangle_indices(0x0, 0x5, 0x1)); icosphere_indices.push_back(triangle_indices(0x0, 0x1, 0x7)); icosphere_indices.push_back(triangle_indices(0x0, 0x7, 0xA)); icosphere_indices.push_back(triangle_indices(0x0, 0xA, 0xB)); icosphere_indices.push_back(triangle_indices(0x1, 0x5, 0x9)); icosphere_indices.push_back(triangle_indices(0x5, 0xB, 0x4)); icosphere_indices.push_back(triangle_indices(0xB, 0xA, 0x2)); icosphere_indices.push_back(triangle_indices(0xA, 0x7, 0x6)); icosphere_indices.push_back(triangle_indices(0x7, 0x1, 0x8)); icosphere_indices.push_back(triangle_indices(0x3, 0x9, 0x4)); icosphere_indices.push_back(triangle_indices(0x3, 0x4, 0x2)); icosphere_indices.push_back(triangle_indices(0x3, 0x2, 0x6)); icosphere_indices.push_back(triangle_indices(0x3, 0x6, 0x8)); icosphere_indices.push_back(triangle_indices(0x3, 0x8, 0x9)); icosphere_indices.push_back(triangle_indices(0x4, 0x9, 0x5)); icosphere_indices.push_back(triangle_indices(0x2, 0x4, 0xB)); icosphere_indices.push_back(triangle_indices(0x6, 0x2, 0xA)); icosphere_indices.push_back(triangle_indices(0x8, 0x6, 0x7)); icosphere_indices.push_back(triangle_indices(0x9, 0x8, 0x1)); // Subdivide the icosphere. for (int i = 0; i < subdivisions; i++) { // Generate a temporary mesh to hold the result of the next // subdivision. std::vector<triangle_indices> new_icosphere_indices; // Subdivide each triangle in the current mesh. for (int j = 0; j < icosphere_indices.size(); j++) { triangle_indices tri = icosphere_indices[j]; int a = get_middle_point(icosphere_vertices, std::get<0>(tri), std::get<1>(tri)); int b = get_middle_point(icosphere_vertices, std::get<1>(tri), std::get<2>(tri)); int c = get_middle_point(icosphere_vertices, std::get<2>(tri), std::get<0>(tri)); // Add the 4 new triangles to the temporary mesh. new_icosphere_indices.push_back(triangle_indices(std::get<0>(tri), a, c)); new_icosphere_indices.push_back(triangle_indices(std::get<1>(tri), b, a)); new_icosphere_indices.push_back(triangle_indices(std::get<2>(tri), c, b)); new_icosphere_indices.push_back(triangle_indices(a, b, c)); } // Replace the current mesh with the temporary mesh. icosphere_indices = new_icosphere_indices; } // Convert the icosphere's structured triangle_indices vector to a list of // ordered vertices. std::vector<glm::vec3> icosphere_mesh; for (int i = 0; i < icosphere_indices.size(); i++) { icosphere_mesh.push_back(icosphere_vertices[std::get<0>(icosphere_indices[i])]); icosphere_mesh.push_back(icosphere_vertices[std::get<1>(icosphere_indices[i])]); icosphere_mesh.push_back(icosphere_vertices[std::get<2>(icosphere_indices[i])]); } // Return the icosphere's mesh. return icosphere_mesh; }; /* Load a shader program from two files. */ GLuint load_shader_program ( std::string shader_path_0, std::string shader_path_1, GLenum shader_type_0, GLenum shader_type_1 ) { // Open shader_path_0 and shader_path_1 as input file streams. std::ifstream shader_file_0(shader_path_0); std::ifstream shader_file_1(shader_path_1); if (!shader_file_0.is_open()) { std::cout << "Could not open file \"" << shader_path_0 << "\"." << std::endl; exit(EXIT_FAILURE); } else if (!shader_file_1.is_open()) { std::cout << "Could not open file \"" << shader_path_1 << "\"." << std::endl; exit(EXIT_FAILURE); } // Load the text context of shader_path_0 and shader_path_1 into // shader_buffer_0 and shader_buffer_1. std::stringstream shader_buffer_0; std::stringstream shader_buffer_1; shader_buffer_0 << shader_file_0.rdbuf() << "\0"; shader_buffer_1 << shader_file_1.rdbuf() << "\0"; // Convert shader_buffer_0 and shader_buffer_1 from std::stringstream to // std::string, and then to const GLchar* (const char*). std::string shader_text_0 = shader_buffer_0.str(); std::string shader_text_1 = shader_buffer_1.str(); const GLchar* shader_data_0 = shader_text_0.c_str(); const GLchar* shader_data_1 = shader_text_1.c_str(); // Create shader_0 and shader_1 with the types shader_type_0 and // shader_type_1, then source them with shader_data_0 and shader_data_1. GLuint shader_0 = glCreateShader(shader_type_0); GLuint shader_1 = glCreateShader(shader_type_1); glShaderSource(shader_0, 1, &shader_data_0, NULL); glShaderSource(shader_1, 1, &shader_data_1, NULL); // Compile shader_0 and shader_1. glCompileShader(shader_0); glCompileShader(shader_1); // Check if shader_0 or shader_1 failed compilation. If so, print out the // error message provided by OpenGL. GLint success_0 = 0; GLint success_1 = 0; GLchar crash_information_0[16 * 1024]; GLchar crash_information_1[16 * 1024]; glGetShaderiv(shader_0, GL_COMPILE_STATUS, &success_0); glGetShaderiv(shader_1, GL_COMPILE_STATUS, &success_1); if (!success_0) { std::cout << "Could not compile shader loaded from \"" << shader_path_0 << "\"." << std::endl; glGetShaderInfoLog(shader_0, 16 * 1024, NULL, crash_information_0); std::cout << crash_information_0; exit(EXIT_FAILURE); } else if (!success_1) { std::cout << "Could not compile shader loaded from \"" << shader_path_1 << "\"." << std::endl; glGetShaderInfoLog(shader_1, 16 * 1024, NULL, crash_information_1); std::cout << crash_information_1; exit(EXIT_FAILURE); } // Create an empty shader program. GLuint shader_program = glCreateProgram(); // Attach shader_0 and shader_1 to shader_program, and then link // shader_program. glAttachShader(shader_program, shader_0); glAttachShader(shader_program, shader_1); glLinkProgram(shader_program); // Check if shader_program failed linkage. If so, print out the error // message provied by OpenGL. GLint success_program = 0; glGetProgramiv(shader_program, GL_LINK_STATUS, &success_program); if (!success_program) { std::cout << "Could not link shader program loaded from \"" << shader_path_0 << "\" and \"" << shader_path_1 << "\"." << std::endl; GLchar crash_information_program[16 * 1024]; glGetProgramInfoLog(shader_program, 16 * 1024, NULL, crash_information_program); std::cout << crash_information_program; exit(EXIT_FAILURE); } // Delete shader_0 and shader_1, then return shader_program. glDeleteShader(shader_0); glDeleteShader(shader_1); return shader_program; } /* Entry point. */ int main(int argc, char** argv) { // Initialize SDL. if (SDL_Init(SDL_INIT_EVERYTHING) < 0) { std::cout << "Could not initialize SDL." << std::endl; return EXIT_FAILURE; } // Create a SDL_Window*. int sdl_x_res = 960; int sdl_y_res = 960; SDL_Window* sdl_window = SDL_CreateWindow ( "SDL 2.0 with OpenGL 3.3 Core", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, sdl_x_res, sdl_y_res, SDL_WINDOW_ALLOW_HIGHDPI | SDL_WINDOW_RESIZABLE | SDL_WINDOW_OPENGL ); // Make sure the SDL_Window* was created successfully. if (!sdl_window) { std::cout << "Could not create a SDL_Window*." << std::endl; return EXIT_FAILURE; } // Request OpenGL 3.3 Core. SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 3); SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE); // Create a SDL_GLContext. SDL_GLContext gl_context = SDL_GL_CreateContext(sdl_window); // Make sure the SDL_GLContext was created successfully. if (!gl_context) { std::cout << "Could not create a SDL_GLContext." << std::endl; return EXIT_FAILURE; } // Load all OpenGL 3.3 Core functions using GLAD. if (!gladLoadGLLoader(SDL_GL_GetProcAddress)) { std::cout << "Could not load OpenGL 3.3 Core functions using GLAD." << std::endl; return EXIT_FAILURE; } // Make sure the OpenGL version that was loaded by GLAD is greater than or // equal to OpenGL 3.3. if (GLVersion.major * 10 + GLVersion.minor < 33) { std::cout << "Could not load OpenGL 3.3 Core functions using GLAD." << std::endl; return EXIT_FAILURE; } // Create and initialize a noise::module::Perlin. This noise module will // dictate the general shape of the islands on the planet. noise::module::Perlin noise_1; { // Set the seed to the current time, so that the output noise will be // slightly different every time. noise_1.SetSeed(time(NULL)); // Set the octave count to 16 for a high level of detail. noise_1.SetOctaveCount(16); // Set the frequency to 2.0f to make the noise more random and less // coherent. noise_1.SetFrequency(2.0f); } // Create and initialize a noise::module::RidgedMulti. This noise module // will create round basins and sharp mountain ranges. noise::module::RidgedMulti noise_2; { // Set the seed to the current time, so that the output noise will be // slightly different every time. noise_2.SetSeed(time(NULL)); // Set the octave count to 16 for a high level of detail. noise_2.SetOctaveCount(16); // Set the frequency to 2.0f to make the noise more random and less // coherent. noise_2.SetFrequency(1.0f); } // Create a gradient to define the color of points on the planet based on // the point's elevation. noise::utils::GradientColor color_map; color_map.Clear(); color_map.AddGradientPoint(0.0f - 1.0000f, noise::utils::Color(0x00, 0x00, 0x80, 0xFF)); color_map.AddGradientPoint(0.0f - 0.2500f, noise::utils::Color(0x00, 0x00, 0xFF, 0xFF)); color_map.AddGradientPoint(0.0f + 0.0000f, noise::utils::Color(0x00, 0x80, 0xFF, 0xFF)); color_map.AddGradientPoint(0.0f + 0.0625f, noise::utils::Color(0xF0, 0xF0, 0x40, 0xFF)); color_map.AddGradientPoint(0.0f + 0.1250f, noise::utils::Color(0x20, 0xA0, 0x00, 0xFF)); color_map.AddGradientPoint(0.0f + 0.3750f, noise::utils::Color(0xE0, 0xE0, 0x00, 0xFF)); color_map.AddGradientPoint(0.0f + 0.7500f, noise::utils::Color(0x80, 0x80, 0x80, 0xFF)); color_map.AddGradientPoint(0.0f + 1.0000f, noise::utils::Color(0xFF, 0xFF, 0xFF, 0xFF)); // Generate the base icosphere. std::vector<glm::vec3> icosphere_managed_vertices = create_icosphere(8); // Allocate space to hold the vertex data of the icosphere. float* icosphere_vertices = (float*)malloc(icosphere_managed_vertices.size() * (9 * sizeof(float))); // Perturb the terrain using the noise modules by iterating through each // triangle rather than each vertex. This is done to make it easy to // calculate triangle normals. for (int i = 0; i < icosphere_managed_vertices.size(); i += 3) { // Create an array to hold the noise values at the three vertices of // the current triangle. float noise_map[3]; for (int j = 0; j < 3; j++) { // Get the current vertex. glm::vec3 vertex = icosphere_managed_vertices[i + j]; // Get the noise value at the current vertex. float actual_noise_value = noise_1.GetValue(vertex.x, vertex.y, vertex.z) * (noise_2.GetValue(vertex.x, vertex.y, vertex.z) + 0.2f); // Clamp the noise value to create smooth, flat water. float noise_value = std::max(0.0f, actual_noise_value); noise_map[j] = actual_noise_value; // Perturb the current vertex by the noise value. icosphere_managed_vertices[i + j] = vertex * (1.0f + noise_value * 0.075f); } // Calculate the triangle's normal. glm::vec3 edge_1 = icosphere_managed_vertices[i + 1] - icosphere_managed_vertices[i]; glm::vec3 edge_2 = icosphere_managed_vertices[i + 2] - icosphere_managed_vertices[i]; glm::vec3 normal = glm::normalize(glm::cross(edge_1, edge_2)); float nx = normal.x; float ny = normal.y; float nz = normal.z; // Generate the vertex data. for (int j = 0; j < 3; j++) { utils::Color color = color_map.GetColor(noise_map[j]); // Write the position of the current vertex. icosphere_vertices[(i + j) * 9 + 0] = icosphere_managed_vertices[i + j].x; icosphere_vertices[(i + j) * 9 + 1] = icosphere_managed_vertices[i + j].y; icosphere_vertices[(i + j) * 9 + 2] = icosphere_managed_vertices[i + j].z; // Write the color of the current vertex. icosphere_vertices[(i + j) * 9 + 3] = color.red / 255.0f; icosphere_vertices[(i + j) * 9 + 4] = color.green / 255.0f; icosphere_vertices[(i + j) * 9 + 5] = color.blue / 255.0f; // Write the surface normal of the current vertex. icosphere_vertices[(i + j) * 9 + 6] = nx; icosphere_vertices[(i + j) * 9 + 7] = ny; icosphere_vertices[(i + j) * 9 + 8] = nz; } } // Generate a VAO and a VBO for the icosphere. GLuint icosphere_vao; GLuint icosphere_vbo; glGenVertexArrays(1, &icosphere_vao); glGenBuffers(1, &icosphere_vbo); // Bind the VAO and the VBO of the icosphere to the current state. glBindVertexArray(icosphere_vao); glBindBuffer(GL_ARRAY_BUFFER, icosphere_vbo); // Upload the icosphere data to the VBO. glBufferData(GL_ARRAY_BUFFER, icosphere_managed_vertices.size() * (10 * sizeof(float)), icosphere_vertices, GL_STATIC_DRAW); // Enable the required vertex attribute pointers. glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 9 * sizeof(float), (void*)(0 * sizeof(float))); glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 9 * sizeof(float), (void*)(3 * sizeof(float))); glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, 9 * sizeof(float), (void*)(6 * sizeof(float))); glEnableVertexAttribArray(0); glEnableVertexAttribArray(1); glEnableVertexAttribArray(2); // Unbind the VAO and the VBO of the icosphere from the current state. glBindBuffer(GL_ARRAY_BUFFER, 0); glBindVertexArray(0); // Load the default shader program. GLuint default_shader_program = load_shader_program("default_vertex.glsl", "default_fragment.glsl", GL_VERTEX_SHADER, GL_FRAGMENT_SHADER); // Define variables to hold the state of the mouse and the application's // state. int sdl_mouse_x = 0; int sdl_mouse_y = 0; bool sdl_mouse_l = false; bool sdl_mouse_r = false; bool sdl_running = true; // Enter the main loop. while (sdl_running) { // Refresh the window's size. SDL_GetWindowSize(sdl_window, &sdl_x_res, &sdl_y_res); // Poll and handle events. SDL_Event e; while (SDL_PollEvent(&e)) { if (e.type == SDL_QUIT) { // The application was quit. sdl_running = false; } else if (e.type == SDL_MOUSEMOTION) { // The mouse moved. sdl_mouse_x = e.motion.x; sdl_mouse_y = e.motion.y; } else if (e.type == SDL_MOUSEBUTTONDOWN) { // A mouse button was pressed. if (e.button.button == SDL_BUTTON_LEFT) { sdl_mouse_l = true; } else if (e.button.button == SDL_BUTTON_RIGHT) { sdl_mouse_r = true; } } else if (e.type == SDL_MOUSEBUTTONUP) { // A mouse button was released. if (e.button.button == SDL_BUTTON_LEFT) { sdl_mouse_l = false; } else if (e.button.button == SDL_BUTTON_RIGHT) { sdl_mouse_r = false; } } else if (e.type == SDL_KEYDOWN) { // A key was pressed. SDL_Keycode key = e.key.keysym.sym; if (key == SDLK_ESCAPE) { // Quit the application. sdl_running = false; } } } // Clear the screen to black. glClearColor(0.0f, 0.0f, 0.0f, 1.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); { // Enable the default shader program. glUseProgram(default_shader_program); // Enable depth testing. glEnable(GL_DEPTH_TEST); // Enable backface culling. glEnable(GL_CULL_FACE); { // Calculate the aspect ratio. float aspect_ratio = (float)sdl_x_res / (float)sdl_y_res; // Calculate the projection matrix. glm::mat4 matrix_projection = glm::perspective(glm::radians(70.0f), aspect_ratio, 0.128f, 1024.0f); // Calculate the view matrix. glm::mat4 matrix_view = glm::mat4(1.0f); // Rotate the view matrix. matrix_view = glm::rotate(matrix_view, glm::radians(0.0f), glm::vec3(1.0f, 0.0f, 0.0f)); matrix_view = glm::rotate(matrix_view, glm::radians(0.0f), glm::vec3(0.0f, 1.0f, 0.0f)); // Calculate the model matrix. glm::mat4 matrix_model = glm::mat4(1.0f); // Translate the model matrix. matrix_model = glm::translate(matrix_model, glm::vec3(0.0f, 0.0f, 0.2f * -10.0f)); // Rotate the model matrix. matrix_model = glm::rotate(matrix_model, glm::radians(SDL_GetTicks() / 100.0f), glm::vec3(1.0f, 0.0f, 0.0f)); matrix_model = glm::rotate(matrix_model, glm::radians(SDL_GetTicks() / 100.0f), glm::vec3(0.0f, 1.0f, 0.0f)); // Pass matrix_projection, matrix_view and matrix_model to the // default_shader_program. glUniformMatrix4fv(glGetUniformLocation(default_shader_program, "matrix_projection"), 1, GL_FALSE, &matrix_projection[0][0]); glUniformMatrix4fv(glGetUniformLocation(default_shader_program, "matrix_view"), 1, GL_FALSE, &matrix_view[0][0]); glUniformMatrix4fv(glGetUniformLocation(default_shader_program, "matrix_model"), 1, GL_FALSE, &matrix_model[0][0]); } // Bind the icosphere VAO to the current state. glBindVertexArray(icosphere_vao); // Set the polygon mode to render wireframes. if (false) { glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); } // Draw the icosphere VAO as an array of triangles. glDrawArrays(GL_TRIANGLES, 0, icosphere_managed_vertices.size()); // Unbind the icosphere VAO from the current state. glBindVertexArray(0); // Disable backface culling. glDisable(GL_CULL_FACE); // Disable depth testing. glDisable(GL_DEPTH_TEST); // Disable the default shader program. glUseProgram(0); } // Swap the sdl_window's current buffer to display the contents of the // back buffer to the screen. SDL_GL_SwapWindow(sdl_window); } // Free the icosphere's vertices. free(icosphere_vertices); // Destroy the default shader program. glDeleteProgram(default_shader_program); // Destroy all SDL_GL resources. SDL_GL_DeleteContext(gl_context); // Destroy all SDL resources. SDL_DestroyWindow(sdl_window); // Quit SDL. SDL_Quit(); // Exit successfully. return EXIT_SUCCESS; }
25.770654
139
0.70933
CobaltXII
9ca0a6fba5e0922b0bc99853009fee24bf8c7ed2
19,548
cpp
C++
samples/sample_encode/src/pipeline_user.cpp
me176c-dev/MediaSDK
0c7f315958b78c98c5c06bd60565eb8c1ad15d41
[ "MIT" ]
null
null
null
samples/sample_encode/src/pipeline_user.cpp
me176c-dev/MediaSDK
0c7f315958b78c98c5c06bd60565eb8c1ad15d41
[ "MIT" ]
null
null
null
samples/sample_encode/src/pipeline_user.cpp
me176c-dev/MediaSDK
0c7f315958b78c98c5c06bd60565eb8c1ad15d41
[ "MIT" ]
null
null
null
/******************************************************************************\ Copyright (c) 2005-2019, Intel Corporation All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. This sample was distributed or derived from the Intel's Media Samples package. The original version of this sample may be obtained from https://software.intel.com/en-us/intel-media-server-studio or https://software.intel.com/en-us/media-client-solutions-support. \**********************************************************************************/ #include "mfx_samples_config.h" #include "pipeline_user.h" #include "sysmem_allocator.h" #ifndef MFX_VERSION #error MFX_VERSION not defined #endif mfxStatus CUserPipeline::InitRotateParam(sInputParams *pInParams) { MSDK_CHECK_POINTER(pInParams, MFX_ERR_NULL_PTR); MSDK_ZERO_MEMORY(m_pluginVideoParams); m_pluginVideoParams.AsyncDepth = pInParams->nAsyncDepth; // the maximum number of tasks that can be submitted before any task execution finishes m_pluginVideoParams.vpp.In.FourCC = MFX_FOURCC_NV12; m_pluginVideoParams.vpp.In.Width = m_pluginVideoParams.vpp.In.CropW = pInParams->nWidth; m_pluginVideoParams.vpp.In.Height = m_pluginVideoParams.vpp.In.CropH = pInParams->nHeight; m_pluginVideoParams.vpp.Out.FourCC = MFX_FOURCC_NV12; m_pluginVideoParams.vpp.Out.Width = m_pluginVideoParams.vpp.Out.CropW = pInParams->nWidth; m_pluginVideoParams.vpp.Out.Height = m_pluginVideoParams.vpp.Out.CropH = pInParams->nHeight; if (pInParams->memType != SYSTEM_MEMORY) m_pluginVideoParams.IOPattern = MFX_IOPATTERN_IN_VIDEO_MEMORY | MFX_IOPATTERN_OUT_VIDEO_MEMORY; m_RotateParams.Angle = pInParams->nRotationAngle; return MFX_ERR_NONE; } mfxStatus CUserPipeline::AllocFrames() { MSDK_CHECK_POINTER(m_pmfxENC, MFX_ERR_NOT_INITIALIZED); mfxStatus sts = MFX_ERR_NONE; mfxFrameAllocRequest EncRequest, RotateRequest; mfxU16 nEncSurfNum = 0; // number of frames at encoder input (rotate output) mfxU16 nRotateSurfNum = 0; // number of frames at rotate input MSDK_ZERO_MEMORY(EncRequest); sts = m_pmfxENC->QueryIOSurf(&m_mfxEncParams, &EncRequest); MSDK_CHECK_STATUS(sts, "m_pmfxENC->QueryIOSurf failed"); if (EncRequest.NumFrameSuggested < m_mfxEncParams.AsyncDepth) return MFX_ERR_MEMORY_ALLOC; nEncSurfNum = EncRequest.NumFrameSuggested; // The number of surfaces for plugin input - so that plugin can work at async depth = m_nAsyncDepth nRotateSurfNum = MSDK_MAX(m_mfxEncParams.AsyncDepth, m_nMemBuffer); // If surfaces are shared by 2 components, c1 and c2. NumSurf = c1_out + c2_in - AsyncDepth + 1 nEncSurfNum += nRotateSurfNum - m_mfxEncParams.AsyncDepth + 1; // prepare allocation requests EncRequest.NumFrameSuggested = EncRequest.NumFrameMin = nEncSurfNum; RotateRequest.NumFrameSuggested = RotateRequest.NumFrameMin = nRotateSurfNum; mfxU16 mem_type = MFX_MEMTYPE_EXTERNAL_FRAME; mem_type |= (SYSTEM_MEMORY == m_memType) ? (mfxU16)MFX_MEMTYPE_SYSTEM_MEMORY :(mfxU16)MFX_MEMTYPE_VIDEO_MEMORY_DECODER_TARGET; EncRequest.Type = RotateRequest.Type = mem_type; EncRequest.Type |= MFX_MEMTYPE_FROM_ENCODE; RotateRequest.Type |= MFX_MEMTYPE_FROM_VPPOUT; // THIS IS A WORKAROUND, NEED TO ADJUST ALLOCATOR MSDK_MEMCPY_VAR(EncRequest.Info, &(m_mfxEncParams.mfx.FrameInfo), sizeof(mfxFrameInfo)); MSDK_MEMCPY_VAR(RotateRequest.Info, &(m_pluginVideoParams.vpp.In), sizeof(mfxFrameInfo)); // alloc frames for encoder input sts = m_pMFXAllocator->Alloc(m_pMFXAllocator->pthis, &EncRequest, &m_EncResponse); MSDK_CHECK_STATUS(sts, "m_pMFXAllocator->Alloc failed"); // alloc frames for rotate input sts = m_pMFXAllocator->Alloc(m_pMFXAllocator->pthis, &(RotateRequest), &m_PluginResponse); MSDK_CHECK_STATUS(sts, "m_pMFXAllocator->Alloc failed"); // prepare mfxFrameSurface1 array for components m_pEncSurfaces = new mfxFrameSurface1 [nEncSurfNum]; MSDK_CHECK_POINTER(m_pEncSurfaces, MFX_ERR_MEMORY_ALLOC); m_pPluginSurfaces = new mfxFrameSurface1 [nRotateSurfNum]; MSDK_CHECK_POINTER(m_pPluginSurfaces, MFX_ERR_MEMORY_ALLOC); for (int i = 0; i < nEncSurfNum; i++) { MSDK_ZERO_MEMORY(m_pEncSurfaces[i]); MSDK_MEMCPY_VAR(m_pEncSurfaces[i].Info, &(m_mfxEncParams.mfx.FrameInfo), sizeof(mfxFrameInfo)); if (SYSTEM_MEMORY != m_memType) { // external allocator used - provide just MemIds m_pEncSurfaces[i].Data.MemId = m_EncResponse.mids[i]; } else { sts = m_pMFXAllocator->Lock(m_pMFXAllocator->pthis, m_EncResponse.mids[i], &(m_pEncSurfaces[i].Data)); MSDK_CHECK_STATUS(sts, "m_pMFXAllocator->Lock failed"); } } for (int i = 0; i < nRotateSurfNum; i++) { MSDK_ZERO_MEMORY(m_pPluginSurfaces[i]); MSDK_MEMCPY_VAR(m_pPluginSurfaces[i].Info, &(m_pluginVideoParams.vpp.In), sizeof(mfxFrameInfo)); if (SYSTEM_MEMORY != m_memType) { // external allocator used - provide just MemIds m_pPluginSurfaces[i].Data.MemId = m_PluginResponse.mids[i]; } else { sts = m_pMFXAllocator->Lock(m_pMFXAllocator->pthis, m_PluginResponse.mids[i], &(m_pPluginSurfaces[i].Data)); MSDK_CHECK_STATUS(sts, "m_pMFXAllocator->Lock failed"); } } return MFX_ERR_NONE; } void CUserPipeline::DeleteFrames() { MSDK_SAFE_DELETE_ARRAY(m_pPluginSurfaces); CEncodingPipeline::DeleteFrames(); } CUserPipeline::CUserPipeline() : CEncodingPipeline() { m_pPluginSurfaces = NULL; m_PluginModule = NULL; m_pusrPlugin = NULL; MSDK_ZERO_MEMORY(m_PluginResponse); MSDK_ZERO_MEMORY(m_pluginVideoParams); MSDK_ZERO_MEMORY(m_RotateParams); m_MVCflags = MVC_DISABLED; } CUserPipeline::~CUserPipeline() { Close(); } mfxStatus CUserPipeline::Init(sInputParams *pParams) { MSDK_CHECK_POINTER(pParams, MFX_ERR_NULL_PTR); mfxStatus sts = MFX_ERR_NONE; m_PluginModule = msdk_so_load(pParams->strPluginDLLPath); MSDK_CHECK_POINTER(m_PluginModule, MFX_ERR_NOT_FOUND); PluginModuleTemplate::fncCreateGenericPlugin pCreateFunc = (PluginModuleTemplate::fncCreateGenericPlugin)msdk_so_get_addr(m_PluginModule, "mfxCreateGenericPlugin"); MSDK_CHECK_POINTER(pCreateFunc, MFX_ERR_NOT_FOUND); m_pusrPlugin = (*pCreateFunc)(); MSDK_CHECK_POINTER(m_pusrPlugin, MFX_ERR_NOT_FOUND); // prepare input file reader sts = m_FileReader.Init(pParams->InputFiles, pParams->FileInputFourCC ); MSDK_CHECK_STATUS(sts, "m_FileReader.Init failed"); // set memory type m_memType = pParams->memType; m_nMemBuffer = pParams->nMemBuf; m_nTimeout = pParams->nTimeout; m_bCutOutput = !pParams->bUncut; // prepare output file writer sts = InitFileWriters(pParams); MSDK_CHECK_STATUS(sts, "InitFileWriters failed"); mfxIMPL impl = pParams->bUseHWLib ? MFX_IMPL_HARDWARE : MFX_IMPL_SOFTWARE; // if d3d11 surfaces are used ask the library to run acceleration through D3D11 // feature may be unsupported due to OS or MSDK API version if (D3D11_MEMORY == pParams->memType) impl |= MFX_IMPL_VIA_D3D11; mfxVersion min_version; mfxVersion version; // real API version with which library is initialized // we set version to 1.0 and later we will query actual version of the library which will got leaded min_version.Major = 1; min_version.Minor = 0; // create a session for the second vpp and encode sts = m_mfxSession.Init(impl, &min_version); MSDK_CHECK_STATUS(sts, "m_mfxSession.Init failed"); sts = MFXQueryVersion(m_mfxSession , &version); // get real API version of the loaded library MSDK_CHECK_STATUS(sts, "MFXQueryVersion failed"); if (CheckVersion(&version, MSDK_FEATURE_PLUGIN_API)) { // we check if codec is distributed as a mediasdk plugin and load it if yes // else if codec is not in the list of mediasdk plugins, we assume, that it is supported inside mediasdk library // in case of HW library (-hw key) we will firstly try to load HW plugin // in case of failure - we will try SW one mfxIMPL impl2 = pParams->bUseHWLib ? MFX_IMPL_HARDWARE : MFX_IMPL_SOFTWARE; if (AreGuidsEqual(MSDK_PLUGINGUID_NULL,pParams->pluginParams.pluginGuid)) { pParams->pluginParams.pluginGuid = msdkGetPluginUID(impl2, MSDK_VENCODE, pParams->CodecId); } if (AreGuidsEqual(pParams->pluginParams.pluginGuid, MSDK_PLUGINGUID_NULL) && impl2 == MFX_IMPL_HARDWARE) pParams->pluginParams.pluginGuid = msdkGetPluginUID(MFX_IMPL_SOFTWARE, MSDK_VENCODE, pParams->CodecId); if (!AreGuidsEqual(pParams->pluginParams.pluginGuid, MSDK_PLUGINGUID_NULL)) { m_pPlugin.reset(LoadPlugin(MFX_PLUGINTYPE_VIDEO_ENCODE, m_mfxSession, pParams->pluginParams.pluginGuid, 1)); if (m_pPlugin.get() == NULL) sts = MFX_ERR_UNSUPPORTED; } } // create encoder m_pmfxENC = new MFXVideoENCODE(m_mfxSession); MSDK_CHECK_POINTER(m_pmfxENC, MFX_ERR_MEMORY_ALLOC); sts = InitMfxEncParams(pParams); MSDK_CHECK_STATUS(sts, "InitMfxEncParams failed"); sts = InitRotateParam(pParams); MSDK_CHECK_STATUS(sts, "InitRotateParam failed"); // create and init frame allocator sts = CreateAllocator(); MSDK_CHECK_STATUS(sts, "CreateAllocator failed"); sts = ResetMFXComponents(pParams); MSDK_CHECK_STATUS(sts, "ResetMFXComponents failed"); // register plugin callbacks in Media SDK mfxPlugin plg = make_mfx_plugin_adapter(m_pusrPlugin); sts = MFXVideoUSER_Register(m_mfxSession, 0, &plg); MSDK_CHECK_STATUS(sts, "MFXVideoUSER_Register failed"); // need to call Init after registration because mfxCore interface is needed sts = m_pusrPlugin->Init(&m_pluginVideoParams); MSDK_CHECK_STATUS(sts, "m_pusrPlugin->Init failed"); sts = m_pusrPlugin->SetAuxParams(&m_RotateParams, sizeof(m_RotateParams)); MSDK_CHECK_STATUS(sts, "m_pusrPlugin->SetAuxParams failed"); return MFX_ERR_NONE; } void CUserPipeline::Close() { MFXVideoUSER_Unregister(m_mfxSession, 0); CEncodingPipeline::Close(); MSDK_SAFE_DELETE(m_pusrPlugin); if (m_PluginModule) { msdk_so_free(m_PluginModule); m_PluginModule = NULL; } } mfxStatus CUserPipeline::ResetMFXComponents(sInputParams* pParams) { MSDK_CHECK_POINTER(pParams, MFX_ERR_NULL_PTR); MSDK_CHECK_POINTER(m_pmfxENC, MFX_ERR_NOT_INITIALIZED); mfxStatus sts = MFX_ERR_NONE; sts = m_pmfxENC->Close(); MSDK_IGNORE_MFX_STS(sts, MFX_ERR_NOT_INITIALIZED); MSDK_CHECK_STATUS(sts, "m_pmfxENC->Close failed"); // free allocated frames DeleteFrames(); m_TaskPool.Close(); sts = AllocFrames(); MSDK_CHECK_STATUS(sts, "AllocFrames failed"); sts = m_pmfxENC->Init(&m_mfxEncParams); MSDK_CHECK_STATUS(sts, "m_pmfxENC->Init failed"); mfxU32 nEncodedDataBufferSize = m_mfxEncParams.mfx.FrameInfo.Width * m_mfxEncParams.mfx.FrameInfo.Height * 4; sts = m_TaskPool.Init(&m_mfxSession, m_FileWriters.first, m_mfxEncParams.AsyncDepth, nEncodedDataBufferSize, m_FileWriters.second); MSDK_CHECK_STATUS(sts, "m_TaskPool.Init failed"); sts = FillBuffers(); MSDK_CHECK_STATUS(sts, "FillBuffers failed"); return MFX_ERR_NONE; } mfxStatus CUserPipeline::Run() { m_statOverall.StartTimeMeasurement(); MSDK_CHECK_POINTER(m_pmfxENC, MFX_ERR_NOT_INITIALIZED); mfxStatus sts = MFX_ERR_NONE; sTask *pCurrentTask = NULL; // a pointer to the current task mfxU16 nEncSurfIdx = 0; // index of free surface for encoder input mfxU16 nRotateSurfIdx = 0; // ~ for rotation plugin input mfxSyncPoint RotateSyncPoint = NULL; // ~ with rotation plugin call sts = MFX_ERR_NONE; // main loop, preprocessing and encoding while (MFX_ERR_NONE <= sts || MFX_ERR_MORE_DATA == sts) { // get a pointer to a free task (bit stream and sync point for encoder) sts = GetFreeTask(&pCurrentTask); MSDK_BREAK_ON_ERROR(sts); if (m_nMemBuffer) { nRotateSurfIdx = m_nFramesRead % m_nMemBuffer; } else { nRotateSurfIdx = GetFreeSurface(m_pPluginSurfaces, m_PluginResponse.NumFrameActual); } MSDK_CHECK_ERROR(nRotateSurfIdx, MSDK_INVALID_SURF_IDX, MFX_ERR_MEMORY_ALLOC); m_statFile.StartTimeMeasurement(); sts = LoadNextFrame(&m_pPluginSurfaces[nRotateSurfIdx]); m_statFile.StopTimeMeasurement(); if ( (MFX_ERR_MORE_DATA == sts) && !m_bTimeOutExceed) continue; MSDK_BREAK_ON_ERROR(sts); nEncSurfIdx = GetFreeSurface(m_pEncSurfaces, m_EncResponse.NumFrameActual); MSDK_CHECK_ERROR(nEncSurfIdx, MSDK_INVALID_SURF_IDX, MFX_ERR_MEMORY_ALLOC); // rotation for(;;) { mfxHDL h1, h2; h1 = &m_pPluginSurfaces[nRotateSurfIdx]; h2 = &m_pEncSurfaces[nEncSurfIdx]; sts = MFXVideoUSER_ProcessFrameAsync(m_mfxSession, &h1, 1, &h2, 1, &RotateSyncPoint); if (MFX_WRN_DEVICE_BUSY == sts) { MSDK_SLEEP(1); // just wait and then repeat the same call } else { break; } } MSDK_BREAK_ON_ERROR(sts); // save the id of preceding rotate task which will produce input data for the encode task if (RotateSyncPoint) { pCurrentTask->DependentVppTasks.push_back(RotateSyncPoint); RotateSyncPoint = NULL; } for (;;) { InsertIDR(pCurrentTask->encCtrl, m_bInsertIDR); m_bInsertIDR = false; sts = m_pmfxENC->EncodeFrameAsync(&pCurrentTask->encCtrl, &m_pEncSurfaces[nEncSurfIdx], &pCurrentTask->mfxBS, &pCurrentTask->EncSyncP); if (MFX_ERR_NONE < sts && !pCurrentTask->EncSyncP) // repeat the call if warning and no output { if (MFX_WRN_DEVICE_BUSY == sts) MSDK_SLEEP(1); // wait if device is busy } else if (MFX_ERR_NONE < sts && pCurrentTask->EncSyncP) { sts = MFX_ERR_NONE; // ignore warnings if output is available break; } else if (MFX_ERR_NOT_ENOUGH_BUFFER == sts) { sts = AllocateSufficientBuffer(pCurrentTask->mfxBS); MSDK_CHECK_STATUS(sts, "AllocateSufficientBuffer failed"); } else { break; } } } // means that the input file has ended, need to go to buffering loops MSDK_IGNORE_MFX_STS(sts, MFX_ERR_MORE_DATA); // exit in case of other errors MSDK_CHECK_STATUS(sts, "m_pmfENC->EncodeFrameAsync failed"); // rotate plugin doesn't buffer frames // loop to get buffered frames from encoder while (MFX_ERR_NONE <= sts) { // get a free task (bit stream and sync point for encoder) sts = GetFreeTask(&pCurrentTask); MSDK_BREAK_ON_ERROR(sts); for (;;) { InsertIDR(pCurrentTask->encCtrl, m_bInsertIDR); m_bInsertIDR = false; sts = m_pmfxENC->EncodeFrameAsync(&pCurrentTask->encCtrl, NULL, &pCurrentTask->mfxBS, &pCurrentTask->EncSyncP); if (MFX_ERR_NONE < sts && !pCurrentTask->EncSyncP) // repeat the call if warning and no output { if (MFX_WRN_DEVICE_BUSY == sts) MSDK_SLEEP(1); // wait if device is busy } else if (MFX_ERR_NONE < sts && pCurrentTask->EncSyncP) { sts = MFX_ERR_NONE; // ignore warnings if output is available break; } else if (MFX_ERR_NOT_ENOUGH_BUFFER == sts) { sts = AllocateSufficientBuffer(pCurrentTask->mfxBS); MSDK_CHECK_STATUS(sts, "AllocateSufficientBuffer failed"); } else { break; } } MSDK_BREAK_ON_ERROR(sts); } // MFX_ERR_MORE_DATA is the correct status to exit buffering loop with // indicates that there are no more buffered frames MSDK_IGNORE_MFX_STS(sts, MFX_ERR_MORE_DATA); // exit in case of other errors MSDK_CHECK_STATUS(sts, "m_pmfxENC->EncodeFrameAsync failed"); // synchronize all tasks that are left in task pool while (MFX_ERR_NONE == sts) { sts = m_TaskPool.SynchronizeFirstTask(); } // MFX_ERR_NOT_FOUND is the correct status to exit the loop with, // EncodeFrameAsync and SyncOperation don't return this status MSDK_IGNORE_MFX_STS(sts, MFX_ERR_NOT_FOUND); // report any errors that occurred in asynchronous part MSDK_CHECK_STATUS(sts, "m_TaskPool.SynchronizeFirstTask failed"); m_statOverall.StopTimeMeasurement(); return sts; } mfxStatus CUserPipeline::FillBuffers() { if (m_nMemBuffer) { for (mfxU32 i = 0; i < m_nMemBuffer; i++) { mfxFrameSurface1* surface = &m_pPluginSurfaces[i]; mfxStatus sts = m_pMFXAllocator->Lock(m_pMFXAllocator->pthis, surface->Data.MemId, &surface->Data); MSDK_CHECK_STATUS(sts, "m_pMFXAllocator->Lock failed"); sts = m_FileReader.LoadNextFrame(surface); MSDK_CHECK_STATUS(sts, "m_FileReader.LoadNextFrame failed"); sts = m_pMFXAllocator->Unlock(m_pMFXAllocator->pthis, surface->Data.MemId, &surface->Data); MSDK_CHECK_STATUS(sts, "m_pMFXAllocator->Unlock failed"); } } return MFX_ERR_NONE; } void CUserPipeline::PrintInfo() { msdk_printf(MSDK_STRING("\nPipeline with rotation plugin")); msdk_printf(MSDK_STRING("\nNOTE: Some of command line options may have been ignored as non-supported for this pipeline. For details see readme-encode.rtf.\n\n")); CEncodingPipeline::PrintInfo(); }
38.862823
755
0.689227
me176c-dev
9ca15bbb6f943bb978d452d7046beaf06935cbcf
4,272
cpp
C++
LibCarla/source/test/common/test_buffer.cpp
AbdulHoffmann/carla_carissma
8d382769ffa02a6c61a22c57160285505f5ff0a4
[ "MIT" ]
12
2019-04-24T16:58:52.000Z
2022-01-22T07:48:55.000Z
LibCarla/source/test/common/test_buffer.cpp
AbdulHoffmann/carla_carissma
8d382769ffa02a6c61a22c57160285505f5ff0a4
[ "MIT" ]
1
2019-03-16T07:42:18.000Z
2019-03-16T10:10:52.000Z
LibCarla/source/test/common/test_buffer.cpp
AbdulHoffmann/carla_carissma
8d382769ffa02a6c61a22c57160285505f5ff0a4
[ "MIT" ]
11
2018-09-28T16:18:37.000Z
2022-01-04T06:02:05.000Z
// Copyright (c) 2017 Computer Vision Center (CVC) at the Universitat Autonoma // de Barcelona (UAB). // // This work is licensed under the terms of the MIT license. // For a copy, see <https://opensource.org/licenses/MIT>. #include "test.h" #include <carla/Buffer.h> #include <carla/BufferPool.h> #include <array> #include <list> #include <set> #include <string> #include <vector> using namespace util::buffer; TEST(buffer, compile) { carla::Buffer buffer; { std::array<boost::asio::const_buffer, 3u> s; buffer.copy_from(s); } { std::array<boost::asio::mutable_buffer, 3u> s; buffer.copy_from(s); } { std::vector<boost::asio::const_buffer> s; buffer.copy_from(s); } { std::vector<boost::asio::mutable_buffer> s; buffer.copy_from(s); } { std::list<boost::asio::const_buffer> s; buffer.copy_from(s); } { std::list<boost::asio::mutable_buffer> s; buffer.copy_from(s); } { std::set<boost::asio::const_buffer> s; buffer.copy_from(s); } { std::set<boost::asio::mutable_buffer> s; buffer.copy_from(s); } { boost::asio::const_buffer v; buffer.copy_from(v); } { boost::asio::mutable_buffer v; buffer.copy_from(v); } { int v[3u]; buffer.copy_from(v); } { std::vector<int> v; buffer.copy_from(v); } { std::string v; buffer.copy_from(v); } { std::wstring v; buffer.copy_from(v); } { struct C { int x = 0; } v[3u]; buffer.copy_from(v); } { struct C { int x = 0; }; std::array<C, 3u> v; buffer.copy_from(v); } { struct C { int x = 0; }; std::vector<C> v; buffer.copy_from(v); } } TEST(buffer, copy_buffer_sequence) { constexpr auto number_of_buffers = 15u; const std::string str = "WXdI<x->+<If$ua>$pu1AUBmS]?_PT{3z$B7L(E|?$]"; std::string message; std::array<Buffer, number_of_buffers> buffers; std::array<boost::asio::const_buffer, number_of_buffers> sequence; for (auto i = 0u; i < number_of_buffers; ++i) { message += str; buffers[i].copy_from(str); sequence[i] = buffers[i].buffer(); } auto result = Buffer(sequence); ASSERT_EQ(result.size(), message.size()); auto result_str = as_string(result); ASSERT_EQ(result_str, message); } TEST(buffer, to_from_string) { const std::string str = "The quick brown fox jumps over the lazy dog"; Buffer buffer(str); ASSERT_EQ(buffer.size(), str.size()); const std::string result = as_string(buffer); ASSERT_EQ(result, str); } TEST(buffer, to_from_vector) { constexpr auto size = 1000u; using T = size_t; std::vector<T> v; v.reserve(size); for (auto i = 0u; i < size; ++i) { v.emplace_back(i); } Buffer buffer(v); ASSERT_EQ(buffer.size(), sizeof(T) * size); auto begin = reinterpret_cast<const T *>(buffer.data()); std::vector<T> result(begin, begin + size); ASSERT_EQ(result, v); } TEST(buffer, copy) { auto msg = make_random(1024u); auto cpy = make_empty(); cpy->copy_from(*msg); ASSERT_EQ(msg->size(), cpy->size()); ASSERT_EQ(*cpy, *msg); } TEST(buffer, copy_with_offset) { const char str0[] = "Hello"; const char str1[] = "buffer!"; Buffer buffer; auto offset = sizeof(str0); buffer.copy_from( offset, reinterpret_cast<const unsigned char *>(&str1), std::strlen(str1)); std::memcpy(buffer.data(), str0, std::strlen(str0)); buffer[std::strlen(str0)] = ' '; auto str = std::string(str0) + " " + str1; ASSERT_EQ(buffer.size(), str.size()); ASSERT_EQ(as_string(buffer), str.c_str()); } TEST(buffer, memcpy) { auto msg = make_random(1024u); auto cpy = make_empty(msg->size()); ASSERT_EQ(msg->size(), cpy->size()); auto buffer = cpy->buffer(); std::memcpy(buffer.data(), msg->data(), buffer.size()); ASSERT_EQ(*cpy, *msg); } #ifndef LIBCARLA_NO_EXCEPTIONS TEST(buffer, message_too_big) { ASSERT_THROW(Buffer(4294967296ul), std::invalid_argument); Buffer buf; ASSERT_THROW(buf.reset(4294967296ul), std::invalid_argument); } #endif // LIBCARLA_NO_EXCEPTIONS TEST(buffer, buffer_pool) { const std::string str = "Hello buffer!"; auto pool = std::make_shared<carla::BufferPool>(); { auto buff = pool->Pop(); buff.copy_from(str); } auto buff1 = pool->Pop(); ASSERT_EQ(as_string(buff1), str); auto buff2 = pool->Pop(); ASSERT_NE(as_string(buff2), str); // Now delete the pool to test the weak reference inside the buffers. pool.reset(); }
31.182482
78
0.663624
AbdulHoffmann
9ca17dc30c08fb42cd049a2ac44052e498d89e13
526
cpp
C++
SOURCE/allProjects/ManagerEmployeeSystem/ManagerEmployeeSystemUnitTest/ManagerUnitTest.cpp
llanesjuan/AllMyProjects
5944b248ae8f4f84cfea9fcf379f877909372551
[ "MIT" ]
null
null
null
SOURCE/allProjects/ManagerEmployeeSystem/ManagerEmployeeSystemUnitTest/ManagerUnitTest.cpp
llanesjuan/AllMyProjects
5944b248ae8f4f84cfea9fcf379f877909372551
[ "MIT" ]
null
null
null
SOURCE/allProjects/ManagerEmployeeSystem/ManagerEmployeeSystemUnitTest/ManagerUnitTest.cpp
llanesjuan/AllMyProjects
5944b248ae8f4f84cfea9fcf379f877909372551
[ "MIT" ]
null
null
null
#include "stdafx.h" #include "CppUnitTest.h" #include"..\ManagerEmployeeSystem\Manager.cpp" using namespace Microsoft::VisualStudio::CppUnitTestFramework; namespace ManagerEmployeeSystemUnitTest { TEST_CLASS(ManagerUnitTest) { public: TEST_METHOD(ManagerUnitTest_parseManager) { string manEmp = "a->b,c,d.b->e,f."; Manager manager; list<string>managerList = manager.parseManager(manEmp); string expected = "b"; managerList.pop_front(); Assert::AreEqual(expected, managerList.front()); } }; }
22.869565
62
0.73384
llanesjuan
9ca520761f83a89d501f7a6f74dd32edc3037114
18,869
cc
C++
chrome/updater/test/integration_tests_impl.cc
chromium/chromium
df46e572c3449a4b108d6e02fbe4f6d24cf98381
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
14,668
2015-01-01T01:57:10.000Z
2022-03-31T23:33:32.000Z
chrome/updater/test/integration_tests_impl.cc
chromium/chromium
df46e572c3449a4b108d6e02fbe4f6d24cf98381
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
86
2015-10-21T13:02:42.000Z
2022-03-14T07:50:50.000Z
chrome/updater/test/integration_tests_impl.cc
chromium/chromium
df46e572c3449a4b108d6e02fbe4f6d24cf98381
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
5,941
2015-01-02T11:32:21.000Z
2022-03-31T16:35:46.000Z
// 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/updater/test/integration_tests_impl.h" #include <cstdlib> #include <memory> #include <string> #include "base/bind.h" #include "base/callback.h" #include "base/command_line.h" #include "base/files/file_enumerator.h" #include "base/files/file_path.h" #include "base/files/file_util.h" #include "base/files/scoped_temp_dir.h" #include "base/json/json_reader.h" #include "base/logging.h" #include "base/memory/scoped_refptr.h" #include "base/numerics/checked_math.h" #include "base/path_service.h" #include "base/process/launch.h" #include "base/process/process.h" #include "base/run_loop.h" #include "base/strings/strcat.h" #include "base/strings/stringprintf.h" #include "base/synchronization/waitable_event.h" #include "base/task/post_task.h" #include "base/task/single_thread_task_runner_thread_mode.h" #include "base/task/task_traits.h" #include "base/task/thread_pool.h" #include "base/test/bind.h" #include "base/test/test_timeouts.h" #include "base/threading/sequenced_task_runner_handle.h" #include "base/time/time.h" #include "base/values.h" #include "base/version.h" #include "build/build_config.h" #include "chrome/common/chrome_paths.h" #include "chrome/updater/constants.h" #include "chrome/updater/persisted_data.h" #include "chrome/updater/prefs.h" #include "chrome/updater/registration_data.h" #include "chrome/updater/service_proxy_factory.h" #include "chrome/updater/test/server.h" #include "chrome/updater/update_service.h" #include "chrome/updater/updater_scope.h" #include "chrome/updater/updater_version.h" #include "chrome/updater/util.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/abseil-cpp/absl/types/optional.h" #include "third_party/re2/src/re2/re2.h" namespace updater { namespace test { namespace { #if defined(OS_MAC) constexpr char kDoNothingCRXName[] = "updater_qualification_app_dmg.crx"; constexpr char kDoNothingCRXRun[] = "updater_qualification_app_dmg.dmg"; constexpr char kDoNothingCRXHash[] = "c9eeadf63732f3259e2ad1cead6298f90a3ef4b601b1ba1cbb0f37b6112a632c"; #elif defined(OS_WIN) constexpr char kDoNothingCRXName[] = "updater_qualification_app_exe.crx"; constexpr char kDoNothingCRXRun[] = "qualification_app.exe"; constexpr char kDoNothingCRXHash[] = "0705f7eedb0427810db76dfc072c8cbc302fbeb9b2c56fa0de3752ed8d6f9164"; #elif defined(OS_LINUX) constexpr char kDoNothingCRXName[] = "updater_qualification_app.crx"; constexpr char kDoNothingCRXRun[] = "qualification_app"; constexpr char kDoNothingCRXHash[] = ""; #endif std::string GetUpdateResponse(const std::string& app_id, const std::string& codebase, const base::Version& version) { return base::StringPrintf( ")]}'\n" R"({"response":{)" R"( "protocol":"3.1",)" R"( "app":[)" R"( {)" R"( "appid":"%s",)" R"( "status":"ok",)" R"( "updatecheck":{)" R"( "status":"ok",)" R"( "urls":{"url":[{"codebase":"%s"}]},)" R"( "manifest":{)" R"( "version":"%s",)" R"( "run":"%s",)" R"( "packages":{)" R"( "package":[)" R"( {"name":"%s","hash_sha256":"%s"})" R"( ])" R"( })" R"( })" R"( })" R"( })" R"( ])" R"(}})", app_id.c_str(), codebase.c_str(), version.GetString().c_str(), kDoNothingCRXRun, kDoNothingCRXName, kDoNothingCRXHash); } } // namespace int CountDirectoryFiles(const base::FilePath& dir) { base::FileEnumerator it(dir, false, base::FileEnumerator::FILES); int res = 0; for (base::FilePath name = it.Next(); !name.empty(); name = it.Next()) ++res; return res; } void RegisterApp(UpdaterScope scope, const std::string& app_id) { scoped_refptr<UpdateService> update_service = CreateUpdateServiceProxy(scope); RegistrationRequest registration; registration.app_id = app_id; registration.version = base::Version("0.1"); base::RunLoop loop; update_service->RegisterApp( registration, base::BindOnce(base::BindLambdaForTesting( [&loop](const RegistrationResponse& response) { EXPECT_EQ(response.status_code, 0); loop.Quit(); }))); loop.Run(); } void ExpectVersionActive(UpdaterScope scope, const std::string& version) { scoped_refptr<GlobalPrefs> prefs = CreateGlobalPrefs(scope); ASSERT_NE(prefs, nullptr) << "Failed to acquire GlobalPrefs."; EXPECT_EQ(prefs->GetActiveVersion(), version); } void ExpectVersionNotActive(UpdaterScope scope, const std::string& version) { scoped_refptr<GlobalPrefs> prefs = CreateGlobalPrefs(scope); ASSERT_NE(prefs, nullptr) << "Failed to acquire GlobalPrefs."; EXPECT_NE(prefs->GetActiveVersion(), version); } void PrintLog(UpdaterScope scope) { std::string contents; absl::optional<base::FilePath> path = GetDataDirPath(scope); EXPECT_TRUE(path); if (path && base::ReadFileToString(path->AppendASCII("updater.log"), &contents)) { VLOG(0) << "Contents of updater.log:"; VLOG(0) << contents; VLOG(0) << "End contents of updater.log."; } else { VLOG(0) << "Failed to read updater.log file."; } } const testing::TestInfo* GetTestInfo() { return testing::UnitTest::GetInstance()->current_test_info(); } base::FilePath GetLogDestinationDir() { // Fetch path to ${ISOLATED_OUTDIR} env var. // ResultDB reads logs and test artifacts info from there. const char* var = std::getenv("ISOLATED_OUTDIR"); return var ? base::FilePath::FromUTF8Unsafe(var) : base::FilePath(); } void CopyLog(const base::FilePath& src_dir) { // TODO(crbug.com/1159189): copy other test artifacts. base::FilePath dest_dir = GetLogDestinationDir(); if (!dest_dir.empty() && base::PathExists(dest_dir) && base::PathExists(src_dir)) { base::FilePath test_name_path = dest_dir.AppendASCII(base::StrCat( {GetTestInfo()->test_suite_name(), ".", GetTestInfo()->name()})); EXPECT_TRUE(base::CreateDirectory(test_name_path)); base::FilePath dest_file_path = test_name_path.AppendASCII("updater.log"); base::FilePath log_path = src_dir.AppendASCII("updater.log"); VLOG(0) << "Copying updater.log file. From: " << log_path << ". To: " << dest_file_path; EXPECT_TRUE(base::CopyFile(log_path, dest_file_path)); } } void RunWake(UpdaterScope scope, int expected_exit_code) { const absl::optional<base::FilePath> installed_executable_path = GetInstalledExecutablePath(scope); ASSERT_TRUE(installed_executable_path); EXPECT_TRUE(base::PathExists(*installed_executable_path)); base::CommandLine command_line(*installed_executable_path); command_line.AppendSwitch(kWakeSwitch); command_line.AppendSwitch(kEnableLoggingSwitch); command_line.AppendSwitchASCII(kLoggingModuleSwitch, kLoggingModuleSwitchValue); int exit_code = -1; ASSERT_TRUE(Run(scope, command_line, &exit_code)); EXPECT_EQ(exit_code, expected_exit_code); } void Update(UpdaterScope scope, const std::string& app_id) { scoped_refptr<UpdateService> update_service = CreateUpdateServiceProxy(scope); base::RunLoop loop; update_service->Update( app_id, UpdateService::Priority::kForeground, UpdateService::PolicySameVersionUpdate::kNotAllowed, base::DoNothing(), base::BindOnce(base::BindLambdaForTesting( [&loop](UpdateService::Result result_unused) { loop.Quit(); }))); loop.Run(); } void UpdateAll(UpdaterScope scope) { scoped_refptr<UpdateService> update_service = CreateUpdateServiceProxy(scope); base::RunLoop loop; update_service->UpdateAll( base::DoNothing(), base::BindOnce(base::BindLambdaForTesting( [&loop](UpdateService::Result result_unused) { loop.Quit(); }))); loop.Run(); } void SetupFakeUpdaterPrefs(UpdaterScope scope, const base::Version& version) { scoped_refptr<GlobalPrefs> global_prefs = CreateGlobalPrefs(scope); ASSERT_TRUE(global_prefs) << "No global prefs."; global_prefs->SetActiveVersion(version.GetString()); global_prefs->SetSwapping(false); PrefsCommitPendingWrites(global_prefs->GetPrefService()); ASSERT_EQ(version.GetString(), global_prefs->GetActiveVersion()); } void SetupFakeUpdaterInstallFolder(UpdaterScope scope, const base::Version& version) { const absl::optional<base::FilePath> folder_path = GetFakeUpdaterInstallFolderPath(scope, version); ASSERT_TRUE(folder_path); ASSERT_TRUE(base::CreateDirectory(*folder_path)); } void SetupFakeUpdater(UpdaterScope scope, const base::Version& version) { SetupFakeUpdaterPrefs(scope, version); SetupFakeUpdaterInstallFolder(scope, version); } void SetupFakeUpdaterVersion(UpdaterScope scope, int offset) { ASSERT_NE(offset, 0); std::vector<uint32_t> components = base::Version(kUpdaterVersion).components(); base::CheckedNumeric<uint32_t> new_version = components[0]; new_version += offset; ASSERT_TRUE(new_version.AssignIfValid(&components[0])); SetupFakeUpdater(scope, base::Version(std::move(components))); } void SetupFakeUpdaterLowerVersion(UpdaterScope scope) { SetupFakeUpdaterVersion(scope, -1); } void SetupFakeUpdaterHigherVersion(UpdaterScope scope) { SetupFakeUpdaterVersion(scope, 1); } void SetExistenceCheckerPath(UpdaterScope scope, const std::string& app_id, const base::FilePath& path) { scoped_refptr<GlobalPrefs> global_prefs = CreateGlobalPrefs(scope); base::MakeRefCounted<PersistedData>(global_prefs->GetPrefService()) ->SetExistenceCheckerPath(app_id, path); PrefsCommitPendingWrites(global_prefs->GetPrefService()); } void SetServerStarts(UpdaterScope scope, int value) { scoped_refptr<GlobalPrefs> global_prefs = CreateGlobalPrefs(scope); for (int i = 0; i <= value; ++i) { global_prefs->CountServerStarts(); } PrefsCommitPendingWrites(global_prefs->GetPrefService()); } void ExpectAppUnregisteredExistenceCheckerPath(UpdaterScope scope, const std::string& app_id) { scoped_refptr<GlobalPrefs> global_prefs = CreateGlobalPrefs(scope); auto persisted_data = base::MakeRefCounted<PersistedData>(global_prefs->GetPrefService()); EXPECT_EQ(base::FilePath(FILE_PATH_LITERAL("")).value(), persisted_data->GetExistenceCheckerPath(app_id).value()); } void ExpectAppVersion(UpdaterScope scope, const std::string& app_id, const base::Version& version) { const base::Version app_version = base::MakeRefCounted<PersistedData>( CreateGlobalPrefs(scope)->GetPrefService()) ->GetProductVersion(app_id); EXPECT_TRUE(app_version.IsValid() && version == app_version); } bool Run(UpdaterScope scope, base::CommandLine command_line, int* exit_code) { base::ScopedAllowBaseSyncPrimitivesForTesting allow_wait_process; command_line.AppendSwitch(kEnableLoggingSwitch); command_line.AppendSwitchASCII(kLoggingModuleSwitch, kLoggingModuleSwitchValue); if (scope == UpdaterScope::kSystem) { command_line.AppendSwitch(kSystemSwitch); command_line = MakeElevated(command_line); } VLOG(0) << " Run command: " << command_line.GetCommandLineString(); base::Process process = base::LaunchProcess(command_line, {}); if (!process.IsValid()) return false; // TODO(crbug.com/1096654): Get the timeout from TestTimeouts. return process.WaitForExitWithTimeout(base::Seconds(45), exit_code); } void SleepFor(int seconds) { VLOG(2) << "Sleeping " << seconds << " seconds..."; base::WaitableEvent sleep(base::WaitableEvent::ResetPolicy::MANUAL, base::WaitableEvent::InitialState::NOT_SIGNALED); base::ThreadPool::PostDelayedTask( FROM_HERE, {base::MayBlock()}, base::BindOnce(&base::WaitableEvent::Signal, base::Unretained(&sleep)), base::Seconds(seconds)); sleep.Wait(); VLOG(2) << "Sleep complete."; } bool WaitFor(base::RepeatingCallback<bool()> predicate) { base::TimeTicks deadline = base::TimeTicks::Now() + TestTimeouts::action_max_timeout(); while (base::TimeTicks::Now() < deadline) { if (predicate.Run()) return true; base::PlatformThread::Sleep(base::Milliseconds(200)); } return false; } bool RequestMatcherRegex(const std::string& request_body_regex, const std::string& request_body) { if (!re2::RE2::PartialMatch(request_body, request_body_regex)) { ADD_FAILURE() << "Request with body: " << request_body << " did not match expected regex " << request_body_regex; return false; } return true; } void ExpectUpdateSequence(UpdaterScope scope, ScopedServer* test_server, const std::string& app_id, const base::Version& from_version, const base::Version& to_version) { auto request_matcher_scope = base::BindLambdaForTesting([scope](const std::string& request_body) { const bool is_match = [&scope, &request_body]() { const absl::optional<base::Value> doc = base::JSONReader::Read(request_body); if (!doc || !doc->is_dict()) return false; const base::Value* object_request = doc->FindKey("request"); if (!object_request || !object_request->is_dict()) return false; const base::Value* value_ismachine = object_request->FindKey("ismachine"); if (!value_ismachine || !value_ismachine->is_bool()) return false; switch (scope) { case UpdaterScope::kSystem: return value_ismachine->GetBool(); case UpdaterScope::kUser: return !value_ismachine->GetBool(); } }(); if (!is_match) { ADD_FAILURE() << R"(Request does not match "ismachine": )" << request_body; } return is_match; }); // First request: update check. test_server->ExpectOnce( {base::BindRepeating( RequestMatcherRegex, base::StringPrintf(R"(.*"appid":"%s".*)", app_id.c_str())), request_matcher_scope}, GetUpdateResponse(app_id, test_server->base_url().spec(), to_version)); // Second request: update download. base::FilePath test_data_path; ASSERT_TRUE(base::PathService::Get(chrome::DIR_TEST_DATA, &test_data_path)); base::FilePath crx_path = test_data_path.Append(FILE_PATH_LITERAL("updater")) .AppendASCII(kDoNothingCRXName); ASSERT_TRUE(base::PathExists(crx_path)); std::string crx_bytes; base::ReadFileToString(crx_path, &crx_bytes); test_server->ExpectOnce({base::BindRepeating(RequestMatcherRegex, "")}, crx_bytes); // Third request: event ping. test_server->ExpectOnce( {base::BindRepeating( RequestMatcherRegex, base::StringPrintf(R"(.*"eventresult":1,"eventtype":3,)" R"("nextversion":"%s","previousversion":"%s".*)", to_version.GetString().c_str(), from_version.GetString().c_str())), request_matcher_scope}, ")]}'\n"); } // Runs multiple cycles of instantiating the update service, calling // `GetVersion()`, then releasing the service interface. void StressUpdateService(UpdaterScope scope) { base::RunLoop loop; // Number of times to run the cycle of instantiating the service. int n = 10; // Delay in milliseconds between successive cycles. const int kDelayBetweenLoopsMS = 0; // Runs on the main sequence. auto loop_closure = [&]() { if (--n) return false; loop.Quit(); return true; }; // Creates a task runner, and runs the service instance on it. using LoopClosure = decltype(loop_closure); auto stress_runner = [scope, loop_closure]() { // `task_runner` is always bound on the main sequence. struct Local { static void GetVersion( UpdaterScope scope, scoped_refptr<base::SequencedTaskRunner> task_runner, LoopClosure loop_closure) { auto service_task_runner = base::ThreadPool::CreateSingleThreadTaskRunner( {}, base::SingleThreadTaskRunnerThreadMode::DEDICATED); service_task_runner->PostDelayedTask( FROM_HERE, base::BindLambdaForTesting([scope, task_runner, loop_closure]() { auto update_service = CreateUpdateServiceProxy(scope); update_service->GetVersion( base::BindOnce(GetVersionCallback, scope, update_service, task_runner, loop_closure)); }), base::Milliseconds(kDelayBetweenLoopsMS)); } static void GetVersionCallback( UpdaterScope scope, scoped_refptr<UpdateService> /*update_service*/, scoped_refptr<base::SequencedTaskRunner> task_runner, LoopClosure loop_closure, const base::Version& version) { EXPECT_EQ(version, base::Version(kUpdaterVersion)); task_runner->PostTask( FROM_HERE, base::BindLambdaForTesting([scope, task_runner, loop_closure]() { if (loop_closure()) { return; } GetVersion(scope, task_runner, loop_closure); })); } }; Local::GetVersion(scope, base::SequencedTaskRunnerHandle::Get(), loop_closure); }; stress_runner(); loop.Run(); } void CallServiceUpdate(UpdaterScope updater_scope, const std::string& app_id, bool same_version_update_allowed) { UpdateService::PolicySameVersionUpdate policy_same_version_update = same_version_update_allowed ? UpdateService::PolicySameVersionUpdate::kAllowed : UpdateService::PolicySameVersionUpdate::kNotAllowed; scoped_refptr<UpdateService> service_proxy = CreateUpdateServiceProxy(updater_scope); base::RunLoop loop; service_proxy->Update( app_id, UpdateService::Priority::kForeground, policy_same_version_update, base::BindLambdaForTesting([](const UpdateService::UpdateState&) {}), base::BindLambdaForTesting([&](UpdateService::Result result) { EXPECT_EQ(result, UpdateService::Result::kSuccess); loop.Quit(); })); loop.Run(); } } // namespace test } // namespace updater
37.290514
80
0.669617
chromium
9ca5ec64c1f00539f658fe4201a0f7815d2f8f74
933
cpp
C++
Test/Core/Hash/hash.cpp
CodogoFreddie/FredLib
8c7307d039f285e16a1a6979e05a071a2c18717e
[ "Apache-2.0" ]
2
2016-04-28T22:59:58.000Z
2016-05-04T01:04:27.000Z
Test/Core/Hash/hash.cpp
CodogoFreddie/FredLib
8c7307d039f285e16a1a6979e05a071a2c18717e
[ "Apache-2.0" ]
null
null
null
Test/Core/Hash/hash.cpp
CodogoFreddie/FredLib
8c7307d039f285e16a1a6979e05a071a2c18717e
[ "Apache-2.0" ]
null
null
null
#include<Core/hash.hpp> #include<gtest/gtest.h> #include<gmock/gmock.h> using namespace core; TEST(HashInt, DoneAtCompile){ static_assert(hashInt(1234) != 1234, "Not evaluted at compileTime"); } TEST(Hash, IsItSalty){ EXPECT_NE(hashInt(1234 ), hashInt(1234,1)); EXPECT_NE(hashInt(1234,1), hashInt(1234,2)); EXPECT_NE(hashInt(1234 ), hashInt(1234,2)); EXPECT_NE(hashConstStr("foo" ), hashConstStr("foo",1)); EXPECT_NE(hashConstStr("foo",1), hashConstStr("foo",2)); EXPECT_NE(hashConstStr("foo" ), hashConstStr("foo",2)); } TEST(HashString, TakesCorrectInputs){ const char* cc = "foo"; std::string ss = "bar"; EXPECT_NE(hashConstStr(cc), hashStdStr(ss)); EXPECT_NE(hashConstStr("baz"), hashStdStr(ss)); EXPECT_NE(hashConstStr(cc), hashConstStr("baz")); } TEST(HashString, DoneAtCompile){ static_assert(hashConstStr("foo") == 193491849, "Not evaluated at compileTime"); }
27.441176
84
0.687031
CodogoFreddie
9ca92ab7a35f4878cbec4de5b9e03f6c9db9316f
40,214
cc
C++
psdaq/drp/BldDetectorSlow.cc
valmar/lcls2
1c24da076a8cd252cf6601e125dd721fd2004f2a
[ "BSD-3-Clause-LBNL" ]
null
null
null
psdaq/drp/BldDetectorSlow.cc
valmar/lcls2
1c24da076a8cd252cf6601e125dd721fd2004f2a
[ "BSD-3-Clause-LBNL" ]
null
null
null
psdaq/drp/BldDetectorSlow.cc
valmar/lcls2
1c24da076a8cd252cf6601e125dd721fd2004f2a
[ "BSD-3-Clause-LBNL" ]
null
null
null
#define __STDC_FORMAT_MACROS 1 #include "BldDetector.hh" #include <bitset> #include <chrono> #include <iostream> #include <memory> #include <arpa/inet.h> #include <sys/ioctl.h> #include <net/if.h> #include "DataDriver.h" #include "RunInfoDef.hh" #include "psdaq/service/kwargs.hh" #include "psdaq/service/EbDgram.hh" #include "xtcdata/xtc/DescData.hh" #include "xtcdata/xtc/ShapesData.hh" #include "xtcdata/xtc/NamesLookup.hh" #include "psdaq/eb/TebContributor.hh" #include "psalg/utils/SysLog.hh" #include <getopt.h> #include <Python.h> #include <inttypes.h> #include <poll.h> using json = nlohmann::json; using logging = psalg::SysLog; namespace Drp { static const XtcData::Name::DataType xtype[] = { XtcData::Name::UINT8 , // pvBoolean XtcData::Name::INT8 , // pvByte XtcData::Name::INT16, // pvShort XtcData::Name::INT32 , // pvInt XtcData::Name::INT64 , // pvLong XtcData::Name::UINT8 , // pvUByte XtcData::Name::UINT16, // pvUShort XtcData::Name::UINT32, // pvUInt XtcData::Name::UINT64, // pvULong XtcData::Name::FLOAT , // pvFloat XtcData::Name::DOUBLE, // pvDouble XtcData::Name::CHARSTR, // pvString }; BldPVA::BldPVA(std::string det, unsigned interface) : _interface(interface) { // // Parse '+' separated list of detName, detType, detId // size_t p1 = det.find('+',0); if (p1 == std::string::npos) { } size_t p2 = det.find('+',p1+1); if (p2 == std::string::npos) { } _detName = det.substr( 0, p1).c_str(); _detType = det.substr(p1+1,p2-p1-1).c_str(); _detId = det.substr(p2+1).c_str(); std::string sname(_detId); _pvaAddr = std::make_shared<Pds_Epics::PVBase>((sname+":ADDR" ).c_str()); _pvaPort = std::make_shared<Pds_Epics::PVBase>((sname+":PORT" ).c_str()); _pvaPayload = std::make_shared<BldDescriptor> ((sname+":PAYLOAD").c_str()); logging::info("BldPVA::BldPVA looking up multicast parameters for %s/%s from %s", _detName.c_str(), _detType.c_str(), _detId.c_str()); } BldPVA::~BldPVA() { } // // LCLS-I Style // BldFactory::BldFactory(const char* name, unsigned interface) : _alg ("raw", 2, 0, 0) { logging::debug("BldFactory::BldFactory %s", name); if (strchr(name,':')) name = strrchr(name,':')+1; _detName = std::string(name); _detType = std::string(name); _detId = std::string(name); _pvaPayload = 0; unsigned payloadSize = 0; unsigned mcaddr = 0; unsigned mcport = 10148; // 12148, eventually uint64_t tscorr = 0x259e9d80ULL << 32; // // Make static configuration of BLD :( // if (strncmp("ebeam",name,5)==0) { if (name[5]=='h') { mcaddr = 0xefff1800; } else { mcaddr = 0xefff1900; } tscorr = 0; _alg = XtcData::Alg("raw", 2, 0, 0); _varDef.NameVec.push_back(XtcData::Name("damageMask" , XtcData::Name::UINT32)); _varDef.NameVec.push_back(XtcData::Name("ebeamCharge" , XtcData::Name::DOUBLE)); _varDef.NameVec.push_back(XtcData::Name("ebeamL3Energy" , XtcData::Name::DOUBLE)); _varDef.NameVec.push_back(XtcData::Name("ebeamLTUPosX" , XtcData::Name::DOUBLE)); _varDef.NameVec.push_back(XtcData::Name("ebeamLTUPosY" , XtcData::Name::DOUBLE)); _varDef.NameVec.push_back(XtcData::Name("ebeamLUTAngX" , XtcData::Name::DOUBLE)); _varDef.NameVec.push_back(XtcData::Name("ebeamLTUAngY" , XtcData::Name::DOUBLE)); _varDef.NameVec.push_back(XtcData::Name("ebeamPkCurrBC2" , XtcData::Name::DOUBLE)); _varDef.NameVec.push_back(XtcData::Name("ebeamEnergyBC2" , XtcData::Name::DOUBLE)); _varDef.NameVec.push_back(XtcData::Name("ebeamPkCurrBC1" , XtcData::Name::DOUBLE)); _varDef.NameVec.push_back(XtcData::Name("ebeamEnergyBC1" , XtcData::Name::DOUBLE)); _varDef.NameVec.push_back(XtcData::Name("ebeamUndPosX" , XtcData::Name::DOUBLE)); _varDef.NameVec.push_back(XtcData::Name("ebeamUndPosY" , XtcData::Name::DOUBLE)); _varDef.NameVec.push_back(XtcData::Name("ebeamUndAngX" , XtcData::Name::DOUBLE)); _varDef.NameVec.push_back(XtcData::Name("ebeamUndAngY" , XtcData::Name::DOUBLE)); _varDef.NameVec.push_back(XtcData::Name("ebeamXTCAVAmpl" , XtcData::Name::DOUBLE)); _varDef.NameVec.push_back(XtcData::Name("ebeamXTCAVPhase" , XtcData::Name::DOUBLE)); _varDef.NameVec.push_back(XtcData::Name("ebeamDumpCharge" , XtcData::Name::DOUBLE)); _varDef.NameVec.push_back(XtcData::Name("ebeamPhotonEnergy", XtcData::Name::DOUBLE)); _varDef.NameVec.push_back(XtcData::Name("ebeamLTU250" , XtcData::Name::DOUBLE)); _varDef.NameVec.push_back(XtcData::Name("ebeamLTU450" , XtcData::Name::DOUBLE)); payloadSize = 164; } else if (strncmp("pcav",name,4)==0) { if (name[4]=='h') { mcaddr = 0xefff1801; } else { mcaddr = 0xefff1901; } _alg = XtcData::Alg("raw", 2, 0, 0); _varDef.NameVec.push_back(XtcData::Name("fitTime1" , XtcData::Name::DOUBLE)); _varDef.NameVec.push_back(XtcData::Name("fitTime2" , XtcData::Name::DOUBLE)); _varDef.NameVec.push_back(XtcData::Name("charge1" , XtcData::Name::DOUBLE)); _varDef.NameVec.push_back(XtcData::Name("charge2" , XtcData::Name::DOUBLE)); payloadSize = 32; } else if (strncmp("gmd",name,3)==0) { mcaddr = 0xefff1902; _alg = XtcData::Alg("raw", 2, 1, 0); _varDef.NameVec.push_back(XtcData::Name("energy" , XtcData::Name::DOUBLE)); _varDef.NameVec.push_back(XtcData::Name("xpos" , XtcData::Name::DOUBLE)); _varDef.NameVec.push_back(XtcData::Name("ypos" , XtcData::Name::DOUBLE)); _varDef.NameVec.push_back(XtcData::Name("avgIntensity", XtcData::Name::DOUBLE)); _varDef.NameVec.push_back(XtcData::Name("rmsElectronSum", XtcData::Name::INT64)); _varDef.NameVec.push_back(XtcData::Name("electron1BkgNoiseAvg", XtcData::Name::INT16)); _varDef.NameVec.push_back(XtcData::Name("electron2BkgNoiseAvg", XtcData::Name::INT16)); payloadSize = 44; } else if (strcmp("xgmd",name)==0) { mcaddr = 0xefff1903; _alg = XtcData::Alg("raw", 2, 1, 0); _varDef.NameVec.push_back(XtcData::Name("energy" , XtcData::Name::DOUBLE)); _varDef.NameVec.push_back(XtcData::Name("xpos" , XtcData::Name::DOUBLE)); _varDef.NameVec.push_back(XtcData::Name("ypos" , XtcData::Name::DOUBLE)); _varDef.NameVec.push_back(XtcData::Name("avgIntensity", XtcData::Name::DOUBLE)); _varDef.NameVec.push_back(XtcData::Name("rmsElectronSum", XtcData::Name::INT64)); _varDef.NameVec.push_back(XtcData::Name("electron1BkgNoiseAvg", XtcData::Name::INT16)); _varDef.NameVec.push_back(XtcData::Name("electron2BkgNoiseAvg", XtcData::Name::INT16)); payloadSize = 44; } else { throw std::string("BLD name ")+name+" not recognized"; } _handler = std::make_shared<Bld>(mcaddr, mcport, interface, Bld::DgramTimestampPos, Bld::DgramHeaderSize, payloadSize, tscorr); } // // LCLS-II Style // BldFactory::BldFactory(const BldPVA& pva) : _detName (pva._detName), _detType (pva._detType), _detId (pva._detId), _alg ("raw", 2, 0, 0), _pvaPayload (pva._pvaPayload) { while(1) { if (pva._pvaAddr ->ready() && pva._pvaPort ->ready() && pva._pvaPayload->ready()) break; usleep(10000); } unsigned mcaddr = pva._pvaAddr->getScalarAs<unsigned>(); unsigned mcport = pva._pvaPort->getScalarAs<unsigned>(); unsigned payloadSize = 0; _varDef = pva._pvaPayload->get(payloadSize); if (_detType == "hpsex" || _detType == "hpscp" || _detType == "hpscpb") { _alg = XtcData::Alg("raw", 2, 0, 0); // validate _varDef against version here } else { throw std::string("BLD type ")+_detType+" not recognized"; } _handler = std::make_shared<Bld>(mcaddr, mcport, pva._interface, Bld::TimestampPos, Bld::HeaderSize, payloadSize); } BldFactory::BldFactory(const BldFactory& o) : _detName (o._detName), _detType (o._detType), _detId (o._detId), _alg (o._alg), _pvaPayload (o._pvaPayload) { logging::error("BldFactory copy ctor called"); } BldFactory::~BldFactory() { } Bld& BldFactory::handler() { return *_handler; } XtcData::NameIndex BldFactory::addToXtc (XtcData::Xtc& xtc, const XtcData::NamesId& namesId) { XtcData::Names& bldNames = *new(xtc) XtcData::Names(_detName.c_str(), _alg, _detType.c_str(), _detId.c_str(), namesId); bldNames.add(xtc, _varDef); return XtcData::NameIndex(bldNames); } unsigned interfaceAddress(const std::string& interface) { int fd = socket(AF_INET, SOCK_DGRAM, 0); struct ifreq ifr; strcpy(ifr.ifr_name, interface.c_str()); ioctl(fd, SIOCGIFADDR, &ifr); close(fd); logging::debug("%s", inet_ntoa(((struct sockaddr_in *)&ifr.ifr_addr)->sin_addr)); return ntohl(*(unsigned*)&(ifr.ifr_addr.sa_data[2])); } BldDescriptor::~BldDescriptor() { logging::debug("~BldDescriptor"); } XtcData::VarDef BldDescriptor::get(unsigned& payloadSize) { payloadSize = 0; XtcData::VarDef vd; const pvd::StructureConstPtr& structure = _strct->getStructure(); if (!structure) { logging::error("BLD with no payload. Is FieldMask empty?"); throw std::string("BLD with no payload. Is FieldMask empty?"); } const pvd::StringArray& names = structure->getFieldNames(); const pvd::FieldConstPtrArray& fields = structure->getFields(); for (unsigned i=0; i<fields.size(); i++) { switch (fields[i]->getType()) { case pvd::scalar: { const pvd::Scalar* scalar = static_cast<const pvd::Scalar*>(fields[i].get()); XtcData::Name::DataType type = xtype[scalar->getScalarType()]; vd.NameVec.push_back(XtcData::Name(names[i].c_str(), type)); payloadSize += XtcData::Name::get_element_size(type); break; } default: { throw std::string("PV type ")+pvd::TypeFunc::name(fields[i]->getType())+ " for field "+names[i]+" not supported"; break; } } } std::string fnames("fields: "); for(auto & elem: vd.NameVec) fnames += std::string(elem.name()) + "[" + elem.str_type() + "],"; logging::debug("%s",fnames.c_str()); return vd; } #define HANDLE_ERR(str) { \ perror(str); \ throw std::string(str); } Bld::Bld(unsigned mcaddr, unsigned port, unsigned interface, unsigned timestampPos, unsigned headerSize, unsigned payloadSize, uint64_t timestampCorr) : m_timestampPos(timestampPos), m_headerSize(headerSize), m_payloadSize(payloadSize), m_bufferSize(0), m_position(0), m_buffer(Bld::MTU), m_payload(m_buffer.data()), m_timestampCorr(timestampCorr) { logging::debug("Bld listening for %x.%d with payload size %u",mcaddr,port,payloadSize); m_sockfd = socket(AF_INET, SOCK_DGRAM, 0); if (m_sockfd < 0) HANDLE_ERR("Open socket"); { unsigned skbSize = 0x1000000; if (setsockopt(m_sockfd, SOL_SOCKET, SO_RCVBUF, &skbSize, sizeof(skbSize)) == -1) HANDLE_ERR("set so_rcvbuf"); } struct sockaddr_in saddr; saddr.sin_family = AF_INET; saddr.sin_addr.s_addr = htonl(mcaddr); saddr.sin_port = htons(port); memset(saddr.sin_zero, 0, sizeof(saddr.sin_zero)); if (bind(m_sockfd, (sockaddr*)&saddr, sizeof(saddr)) < 0) HANDLE_ERR("bind"); int y = 1; if (setsockopt(m_sockfd, SOL_SOCKET, SO_REUSEADDR, &y, sizeof(y)) == -1) HANDLE_ERR("set reuseaddr"); ip_mreq ipmreq; bzero(&ipmreq, sizeof(ipmreq)); ipmreq.imr_multiaddr.s_addr = htonl(mcaddr); ipmreq.imr_interface.s_addr = htonl(interface); if (setsockopt(m_sockfd, IPPROTO_IP, IP_ADD_MEMBERSHIP, &ipmreq, sizeof(ipmreq)) == -1) HANDLE_ERR("mcast join"); } Bld::Bld(const Bld& o) : m_timestampPos(o.m_timestampPos), m_headerSize (o.m_headerSize), m_payloadSize (o.m_payloadSize), m_sockfd (o.m_sockfd) { logging::error("Bld copy ctor called"); } Bld::~Bld() { close(m_sockfd); } /* memory layout for bld packet header: uint64_t pulseId uint64_t timeStamp uint32_t id; uint8_t payload[] following events [] uint32_t pulseIdOffset uint8_t payload[] */ uint64_t Bld::next() { uint64_t timestamp(0L); // get new multicast if buffer is empty if ((m_position + m_payloadSize + 4) > m_bufferSize) { m_bufferSize = recv(m_sockfd, m_buffer.data(), Bld::MTU, 0); timestamp = headerTimestamp(); m_payload = &m_buffer[m_headerSize]; m_position = m_headerSize + m_payloadSize; } else { uint32_t timestampOffset = *reinterpret_cast<uint32_t*>(m_buffer.data() + m_position)&0xfffff; timestamp = headerTimestamp() + timestampOffset; m_payload = &m_buffer[m_position + 4]; m_position += 4 + m_payloadSize; } logging::debug("BLD timestamp %16llx",timestamp); return timestamp; } class BldDetector : public XpmDetector { public: BldDetector(Parameters& para, DrpBase& drp) : XpmDetector(&para, &drp.pool) {} void event(XtcData::Dgram& dgram, PGPEvent* event) override {} }; Pgp::Pgp(Parameters& para, DrpBase& drp, Detector* det) : m_para(para), m_drp(drp), m_det(det), m_config(0), m_terminate(false), m_running(false), m_available(0), m_current(0), m_lastComplete(0), m_next(0) { m_nodeId = det->nodeId; uint8_t mask[DMA_MASK_SIZE]; dmaInitMaskBytes(mask); for (unsigned i=0; i<PGP_MAX_LANES; i++) { if (para.laneMask & (1 << i)) { logging::info("setting lane %d", i); dmaAddMaskBytes((uint8_t*)mask, dmaDest(i, 0)); } } dmaSetMaskBytes(m_drp.pool.fd(), mask); } Pds::EbDgram* Pgp::_handle(uint32_t& current, uint64_t& bytes) { int32_t size = dmaRet[m_current]; uint32_t index = dmaIndex[m_current]; uint32_t lane = (dest[m_current] >> 8) & 7; bytes += size; if (unsigned(size) > m_drp.pool.dmaSize()) { logging::critical("DMA overflowed buffer: %d vs %d", size, m_drp.pool.dmaSize()); throw "DMA overflowed buffer"; } const uint32_t* data = (uint32_t*)m_drp.pool.dmaBuffers[index]; uint32_t evtCounter = data[5] & 0xffffff; const unsigned bufferMask = m_drp.pool.nbuffers() - 1; current = evtCounter & (m_drp.pool.nbuffers() - 1); PGPEvent* event = &m_drp.pool.pgpEvents[current]; DmaBuffer* buffer = &event->buffers[lane]; buffer->size = size; buffer->index = index; event->mask |= (1 << lane); logging::debug("PGPReader lane %d size %d hdr %016lx.%016lx.%08x", lane, size, reinterpret_cast<const uint64_t*>(data)[0], reinterpret_cast<const uint64_t*>(data)[1], reinterpret_cast<const uint32_t*>(data)[4]); const Pds::TimingHeader* timingHeader = reinterpret_cast<const Pds::TimingHeader*>(data); if (timingHeader->error()) { logging::error("Timing header error bit is set"); } XtcData::TransitionId::Value transitionId = timingHeader->service(); if (transitionId != XtcData::TransitionId::L1Accept) { if (transitionId != XtcData::TransitionId::SlowUpdate) { logging::info("PGPReader saw %s @ %u.%09u (%014lx)", XtcData::TransitionId::name(transitionId), timingHeader->time.seconds(), timingHeader->time.nanoseconds(), timingHeader->pulseId()); } else { logging::debug("PGPReader saw %s @ %u.%09u (%014lx)", XtcData::TransitionId::name(transitionId), timingHeader->time.seconds(), timingHeader->time.nanoseconds(), timingHeader->pulseId()); } if (transitionId == XtcData::TransitionId::BeginRun) { m_lastComplete = 0; // EvtCounter reset } } if (evtCounter != ((m_lastComplete + 1) & 0xffffff)) { logging::critical("%sPGPReader: Jump in complete l1Count %u -> %u | difference %d, tid %s%s", RED_ON, m_lastComplete, evtCounter, evtCounter - m_lastComplete, XtcData::TransitionId::name(transitionId), RED_OFF); logging::critical("data: %08x %08x %08x %08x %08x %08x", data[0], data[1], data[2], data[3], data[4], data[5]); logging::critical("lastTid %s", XtcData::TransitionId::name(m_lastTid)); logging::critical("lastData: %08x %08x %08x %08x %08x %08x", m_lastData[0], m_lastData[1], m_lastData[2], m_lastData[3], m_lastData[4], m_lastData[5]); throw "Jump in event counter"; for (unsigned e=m_lastComplete+1; e<evtCounter; e++) { PGPEvent* brokenEvent = &m_drp.pool.pgpEvents[e & bufferMask]; logging::error("broken event: %08x", brokenEvent->mask); brokenEvent->mask = 0; } } m_lastComplete = evtCounter; m_lastTid = transitionId; memcpy(m_lastData, data, 24); event->l3InpBuf = m_drp.tebContributor().allocate(*timingHeader, (void*)((uintptr_t)current)); // make new dgram in the pebble // It must be an EbDgram in order to be able to send it to the MEB Pds::EbDgram* dgram = new(m_drp.pool.pebble[current]) Pds::EbDgram(*timingHeader, XtcData::Src(m_nodeId), m_para.rogMask); return dgram; } Pds::EbDgram* Pgp::next(uint32_t& evtIndex, uint64_t& bytes) { // get new buffers if (m_current == m_available) { m_current = 0; m_available = dmaReadBulkIndex(m_drp.pool.fd(), MAX_RET_CNT_C, dmaRet, dmaIndex, NULL, NULL, dest); if (m_available == 0) return nullptr; m_drp.pool.allocate(m_available); } Pds::EbDgram* dgram = _handle(evtIndex, bytes); m_current++; return dgram; } void Pgp::shutdown() { m_terminate.store(true, std::memory_order_release); m_det->namesLookup().clear(); // erase all elements } void Pgp::worker(std::shared_ptr<Pds::MetricExporter> exporter) { // setup monitoring uint64_t nevents = 0L; std::map<std::string, std::string> labels{{"instrument", m_para.instrument}, {"partition", std::to_string(m_para.partition)}, {"detname", m_para.detName}, {"detseg", std::to_string(m_para.detSegment)}, {"alias", m_para.alias}}; exporter->add("drp_event_rate", labels, Pds::MetricType::Rate, [&](){return nevents;}); uint64_t bytes = 0L; exporter->add("drp_pgp_byte_rate", labels, Pds::MetricType::Rate, [&](){return bytes;}); uint64_t nmissed = 0L; exporter->add("bld_miss_count", labels, Pds::MetricType::Counter, [&](){return nmissed;}); // // Setup the multicast receivers // m_config.erase(m_config.begin(), m_config.end()); unsigned interface = interfaceAddress(m_para.kwargs["interface"]); // // Cache the BLD types that require lookup // std::vector<std::shared_ptr<BldPVA> > bldPva(0); std::string s(m_para.detType); logging::debug("Parsing %s",s.c_str()); for(size_t curr = 0, next = 0; next != std::string::npos; curr = next+1) { next = s.find(',',curr+1); size_t pvpos = s.find('+',curr+1); logging::debug("(%d,%d,%d)",curr,pvpos,next); if (next == std::string::npos) { if (pvpos != std::string::npos) bldPva.push_back(std::make_shared<BldPVA>(s.substr(curr,next), interface)); else m_config.push_back(std::make_shared<BldFactory>(s.substr(curr,next).c_str(), interface)); } else if (pvpos > curr && pvpos < next) bldPva.push_back(std::make_shared<BldPVA>(s.substr(curr,next-curr), interface)); else m_config.push_back(std::make_shared<BldFactory>(s.substr(curr,next-curr).c_str(), interface)); } for(unsigned i=0; i<bldPva.size(); i++) m_config.push_back(std::make_shared<BldFactory>(*bldPva[i].get())); // Event builder variables unsigned index; Pds::EbDgram* dgram = 0; uint64_t timestamp[m_config.size()]; memset(timestamp,0,sizeof(timestamp)); bool lMissing = false; XtcData::NamesLookup& namesLookup = m_det->namesLookup(); // Poll // this was 4ms, but EBeam bld timed out in rix intermittently, // increased it to 50ms, but then we get deadtime running bld // with no eventcode 136 @120Hz. 120Hz corresponds to 8ms, so try 7ms. unsigned tmo = 7; // milliseconds { std::map<std::string,std::string>::iterator it = m_para.kwargs.find("timeout"); if (it != m_para.kwargs.end()) tmo = strtoul(it->second.c_str(),NULL,0); } unsigned nfds = m_config.size()+1; pollfd pfd[nfds]; pfd[0].fd = m_drp.pool.fd(); pfd[0].events = POLLIN; for(unsigned i=0; i<m_config.size(); i++) { pfd[i+1].fd = m_config[i]->handler().fd(); pfd[i+1].events = POLL_IN; } m_terminate.store(false, std::memory_order_release); while (true) { if (m_terminate.load(std::memory_order_relaxed)) { break; } int rval = poll(pfd, nfds, tmo); if (rval < 0) { // error } /** else if (rval == 0) { // timeout // flush dgrams if (pfd[0].events == 0) { bool lMissed = false; uint64_t ts = dgram->time.value(); for(unsigned i=0; i<m_config.size(); i++) { if (timestamp[i] == ts) { XtcData::NamesId namesId(m_nodeId, BldNamesIndex + i); const Bld& bld = m_config[i]->handler(); XtcData::DescribedData desc(dgram->xtc, namesLookup, namesId); memcpy(desc.data(), bld.payload(), bld.payloadSize()); desc.set_data_length(bld.payloadSize()); pfd[i+1].events = POLLIN; } else { lMissed = true; if (!lMissing) logging::debug("Missed bld[%u]: pgp %016lx bld %016lx", i, ts, timestamp[i]); } } if (lMissed) { lMissing = true; dgram->xtc.damage.increase(XtcData::Damage::DroppedContribution); } else lMissing = false; logging::debug("poll tmo flush dgram %p extent %u dmg 0x%x", dgram, dgram->xtc.extent, dgram->xtc.damage.value()); _sendToTeb(*dgram, index); nevents++; pfd[0].events = POLLIN; } for(unsigned i=0; i<m_config.size(); i++) pfd[i+1].events = POLLIN; } **/ else { logging::debug("poll rval[%d] pfd[0].events %u pfd[1].events %u dgram %p", rval, pfd[0].events,pfd[1].events,dgram); // handle pgp if (pfd[0].revents == POLLIN) { dgram = next(index, bytes); pfd[0].events = 0; } // handle bld for(unsigned i=0; i<m_config.size(); i++) { if (pfd[i+1].revents == POLLIN) { timestamp[i] = m_config[i]->handler().next(); pfd[i+1].events = 0; } } if (dgram) { bool lready = true; uint64_t ts = dgram->time.value(); for(unsigned i=0; i<m_config.size(); i++) { if (timestamp[i] < ts) { pfd[i+1].events = POLLIN; lready = false; } } // Accept non-L1 transitions if (dgram->service() != XtcData::TransitionId::L1Accept) { // Allocate a transition dgram from the pool and initialize its header Pds::EbDgram* trDgram = m_drp.pool.allocateTr(); memcpy((void*)trDgram, (const void*)dgram, sizeof(*dgram) - sizeof(dgram->xtc)); // copy the temporary xtc created on phase 1 of the transition // into the real location XtcData::Xtc& trXtc = m_det->transitionXtc(); memcpy((void*)&trDgram->xtc, (const void*)&trXtc, trXtc.extent); PGPEvent* pgpEvent = &m_drp.pool.pgpEvents[index]; pgpEvent->transitionDgram = trDgram; if (dgram->service() == XtcData::TransitionId::Configure) { logging::info("BLD configure"); // Revisit: This is intended to be done by BldDetector::configure() for(unsigned i=0; i<m_config.size(); i++) { XtcData::NamesId namesId(m_nodeId, BldNamesIndex + i); namesLookup[namesId] = m_config[i]->addToXtc(trDgram->xtc, namesId); } } _sendToTeb(*dgram, index); nevents++; pfd[0].events = POLLIN; dgram = 0; } // Accept L1 transitions else if (lready or rval==0) { bool lMissed = false; for(unsigned i=0; i<m_config.size(); i++) { if (timestamp[i] == ts) { XtcData::NamesId namesId(m_nodeId, BldNamesIndex + i); const Bld& bld = m_config[i]->handler(); XtcData::DescribedData desc(dgram->xtc, namesLookup, namesId); memcpy(desc.data(), bld.payload(), bld.payloadSize()); desc.set_data_length(bld.payloadSize()); pfd[i+1].events = POLLIN; } else { lMissed = true; if (!lMissing) logging::debug("Missed bld[%u]: pgp %016lx bld %016lx", i, ts, timestamp[i]); } } if (lMissed) { lMissing = true; dgram->xtc.damage.increase(XtcData::Damage::DroppedContribution); } else lMissing = false; _sendToTeb(*dgram, index); nevents++; pfd[0].events = POLLIN; dgram = 0; } } } } logging::info("Worker thread finished"); } void Pgp::_sendToTeb(Pds::EbDgram& dgram, uint32_t index) { // Make sure the datagram didn't get too big const size_t size = sizeof(dgram) + dgram.xtc.sizeofPayload(); const size_t maxSize = ((dgram.service() == XtcData::TransitionId::L1Accept) || (dgram.service() == XtcData::TransitionId::SlowUpdate)) ? m_drp.pool.bufferSize() : m_para.maxTrSize; if (size > maxSize) { logging::critical("%s Dgram of size %zd overflowed buffer of size %zd", XtcData::TransitionId::name(dgram.service()), size, maxSize); throw "Dgram overflowed buffer"; } PGPEvent* event = &m_drp.pool.pgpEvents[index]; if (event->l3InpBuf) { // else timed out Pds::EbDgram* l3InpDg = new(event->l3InpBuf) Pds::EbDgram(dgram); if (l3InpDg->isEvent()) { if (m_drp.triggerPrimitive()) { // else this DRP doesn't provide input m_drp.triggerPrimitive()->event(m_drp.pool, index, dgram.xtc, l3InpDg->xtc); // Produce } } m_drp.tebContributor().process(l3InpDg); } } BldApp::BldApp(Parameters& para) : CollectionApp(para.collectionHost, para.partition, "drp", para.alias), m_drp (para, context()), m_para (para), m_det (new BldDetector(m_para, m_drp)), m_unconfigure(false) { Py_Initialize(); // for use by configuration if (m_det == nullptr) { logging::critical("Error !! Could not create Detector object for %s", m_para.detType.c_str()); throw "Could not create Detector object for " + m_para.detType; } if (m_para.outputDir.empty()) { logging::info("output dir: n/a"); } else { logging::info("output dir: %s", m_para.outputDir.c_str()); } logging::info("Ready for transitions"); } BldApp::~BldApp() { // Try to take things down gracefully when an exception takes us off the // normal path so that the most chance is given for prints to show up handleReset(json({})); if (m_det) { delete m_det; } Py_Finalize(); // for use by configuration } void BldApp::_disconnect() { m_drp.disconnect(); m_det->shutdown(); } void BldApp::_unconfigure() { m_drp.unconfigure(); // TebContributor must be shut down before the worker if (m_pgp) { m_pgp->shutdown(); if (m_workerThread.joinable()) { m_workerThread.join(); } m_pgp.reset(); } m_unconfigure = false; } json BldApp::connectionInfo() { std::string ip = m_para.kwargs.find("ep_domain") != m_para.kwargs.end() ? getNicIp(m_para.kwargs["ep_domain"]) : getNicIp(m_para.kwargs["forceEnet"] == "yes"); logging::debug("nic ip %s", ip.c_str()); json body = {{"connect_info", {{"nic_ip", ip}}}}; json info = m_det->connectionInfo(); body["connect_info"].update(info); json bufInfo = m_drp.connectionInfo(ip); body["connect_info"].update(bufInfo); return body; } void BldApp::connectionShutdown() { m_drp.shutdown(); if (m_exporter) { m_exporter.reset(); } } void BldApp::_error(const std::string& which, const nlohmann::json& msg, const std::string& errorMsg) { json body = json({}); body["err_info"] = errorMsg; json answer = createMsg(which, msg["header"]["msg_id"], getId(), body); reply(answer); } void BldApp::handleConnect(const nlohmann::json& msg) { std::string errorMsg = m_drp.connect(msg, getId()); if (!errorMsg.empty()) { logging::error("Error in BldApp::handleConnect"); logging::error("%s", errorMsg.c_str()); _error("connect", msg, errorMsg); return; } // Check for proper command-line parameters std::map<std::string,std::string>::iterator it = m_para.kwargs.find("interface"); if (it == m_para.kwargs.end()) { logging::error("Error in BldApp::handleConnect"); logging::error("No multicast interface specified"); _error("connect", msg, std::string("No multicast interface specified")); return; } unsigned interface = interfaceAddress(it->second); if (!interface) { logging::error("Error in BldApp::handleConnect"); logging::error("Failed to lookup multicast interface %s",it->second.c_str()); _error("connect", msg, std::string("Failed to lookup multicast interface")); return; } m_det->nodeId = m_drp.nodeId(); m_det->connect(msg, std::to_string(getId())); json body = json({}); json answer = createMsg("connect", msg["header"]["msg_id"], getId(), body); reply(answer); } void BldApp::handleDisconnect(const json& msg) { // Carry out the queued Unconfigure, if there was one if (m_unconfigure) { _unconfigure(); } _disconnect(); json body = json({}); reply(createMsg("disconnect", msg["header"]["msg_id"], getId(), body)); } void BldApp::handlePhase1(const json& msg) { std::string key = msg["header"]["key"]; logging::debug("handlePhase1 for %s in BldDetectorApp", key.c_str()); XtcData::Xtc& xtc = m_det->transitionXtc(); XtcData::TypeId tid(XtcData::TypeId::Parent, 0); xtc.src = XtcData::Src(m_det->nodeId); // set the src field for the event builders xtc.damage = 0; xtc.contains = tid; xtc.extent = sizeof(XtcData::Xtc); json phase1Info{ "" }; if (msg.find("body") != msg.end()) { if (msg["body"].find("phase1Info") != msg["body"].end()) { phase1Info = msg["body"]["phase1Info"]; } } json body = json({}); if (key == "configure") { if (m_unconfigure) { _unconfigure(); } std::string errorMsg = m_drp.configure(msg); if (!errorMsg.empty()) { errorMsg = "Phase 1 error: " + errorMsg; logging::error("%s", errorMsg.c_str()); _error(key, msg, errorMsg); return; } m_pgp = std::make_unique<Pgp>(m_para, m_drp, m_det); if (m_exporter) m_exporter.reset(); m_exporter = std::make_shared<Pds::MetricExporter>(); if (m_drp.exposer()) { m_drp.exposer()->RegisterCollectable(m_exporter); } std::string config_alias = msg["body"]["config_alias"]; unsigned error = m_det->configure(config_alias, xtc); if (error) { std::string errorMsg = "Phase 1 error in Detector::configure"; logging::error("%s", errorMsg.c_str()); _error(key, msg, errorMsg); return; } m_workerThread = std::thread{&Pgp::worker, std::ref(*m_pgp), m_exporter}; m_drp.runInfoSupport(xtc, m_det->namesLookup()); } else if (key == "unconfigure") { // "Queue" unconfiguration until after phase 2 has completed m_unconfigure = true; } else if (key == "beginrun") { RunInfo runInfo; std::string errorMsg = m_drp.beginrun(phase1Info, runInfo); if (!errorMsg.empty()) { logging::error("%s", errorMsg.c_str()); _error(key, msg, errorMsg); return; } m_drp.runInfoData(xtc, m_det->namesLookup(), runInfo); } else if (key == "endrun") { std::string errorMsg = m_drp.endrun(phase1Info); if (!errorMsg.empty()) { logging::error("%s", errorMsg.c_str()); _error(key, msg, errorMsg); return; } } json answer = createMsg(key, msg["header"]["msg_id"], getId(), body); reply(answer); } void BldApp::handleReset(const nlohmann::json& msg) { unsubscribePartition(); // ZMQ_UNSUBSCRIBE _unconfigure(); _disconnect(); connectionShutdown(); } } // namespace Drp int main(int argc, char* argv[]) { Drp::Parameters para; std::string kwargs_str; int c; while((c = getopt(argc, argv, "l:p:o:C:b:d:D:u:P:T::k:M:v")) != EOF) { switch(c) { case 'p': para.partition = std::stoi(optarg); break; case 'l': para.laneMask = strtoul(optarg,NULL,0); break; case 'o': para.outputDir = optarg; break; case 'C': para.collectionHost = optarg; break; case 'b': para.detName = optarg; break; case 'd': para.device = optarg; break; case 'D': para.detType = optarg; break; case 'u': para.alias = optarg; break; case 'P': para.instrument = optarg; break; case 'k': kwargs_str = kwargs_str.empty() ? optarg : kwargs_str + ", " + optarg; break; case 'M': para.prometheusDir = optarg; break; case 'v': ++para.verbose; break; default: return 1; } } switch (para.verbose) { case 0: logging::init(para.instrument.c_str(), LOG_INFO); break; default: logging::init(para.instrument.c_str(), LOG_DEBUG); break; } logging::info("logging configured"); if (optind < argc) { logging::error("Unrecognized argument:"); while (optind < argc) logging::error(" %s ", argv[optind++]); return 1; } if (para.instrument.empty()) { logging::warning("-P: instrument name is missing"); } // Check required parameters if (para.partition == unsigned(-1)) { logging::critical("-p: partition is mandatory"); return 1; } if (para.device.empty()) { logging::critical("-d: device is mandatory"); return 1; } if (para.alias.empty()) { logging::critical("-u: alias is mandatory"); return 1; } // Only one lane is supported by this DRP if (std::bitset<PGP_MAX_LANES>(para.laneMask).count() != 1) { logging::critical("-l: lane mask must have only 1 bit set"); return 1; } // Alias must be of form <detName>_<detSegment> size_t found = para.alias.rfind('_'); if ((found == std::string::npos) || !isdigit(para.alias.back())) { logging::critical("-u: alias must have _N suffix"); return 1; } para.detName = "bld"; //para.alias.substr(0, found); para.detSegment = std::stoi(para.alias.substr(found+1, para.alias.size())); get_kwargs(kwargs_str, para.kwargs); for (const auto& kwargs : para.kwargs) { if (kwargs.first == "forceEnet") continue; if (kwargs.first == "ep_fabric") continue; if (kwargs.first == "ep_domain") continue; if (kwargs.first == "ep_provider") continue; if (kwargs.first == "sim_length") continue; // XpmDetector if (kwargs.first == "timebase") continue; // XpmDetector if (kwargs.first == "pebbleBufSize") continue; // DrpBase if (kwargs.first == "batching") continue; // DrpBase if (kwargs.first == "directIO") continue; // DrpBase if (kwargs.first == "interface") continue; if (kwargs.first == "timeout") continue; logging::critical("Unrecognized kwarg '%s=%s'\n", kwargs.first.c_str(), kwargs.second.c_str()); return 1; } para.maxTrSize = 256 * 1024; try { Drp::BldApp app(para); app.run(); return 0; } catch (std::exception& e) { logging::critical("%s", e.what()); } catch (std::string& e) { logging::critical("%s", e.c_str()); } catch (char const* e) { logging::critical("%s", e); } catch (...) { logging::critical("Default exception"); } return EXIT_FAILURE; }
35.841355
143
0.557418
valmar
9ca9d6ceb9012640ab4a4d240e09131bbfa8b0e1
217
cpp
C++
answers/Kronos-2701/Day3/Que1.cpp
arc03/30-DaysOfCode-March-2021
6d6e11bf70280a578113f163352fa4fa8408baf6
[ "MIT" ]
22
2021-03-16T14:07:47.000Z
2021-08-13T08:52:50.000Z
answers/Kronos-2701/Day3/Que1.cpp
arc03/30-DaysOfCode-March-2021
6d6e11bf70280a578113f163352fa4fa8408baf6
[ "MIT" ]
174
2021-03-16T21:16:40.000Z
2021-06-12T05:19:51.000Z
answers/Kronos-2701/Day3/Que1.cpp
arc03/30-DaysOfCode-March-2021
6d6e11bf70280a578113f163352fa4fa8408baf6
[ "MIT" ]
135
2021-03-16T16:47:12.000Z
2021-06-27T14:22:38.000Z
#include <bits/stdc++.h> using namespace std; int main() { int sum=1, s,x=1; cout<<"Enter no. of terms"; cin>>s; if (s<=1){cout<<s;} else {for (int i =2;i<=s;i++){ x=x*10; x=x+i; sum=sum+x; } cout<<sum;} return 0; }
14.466667
34
0.571429
arc03
66d4adbd39653ccee1c693950dc60d6fe1d7d823
1,825
cpp
C++
src/Mapper.cpp
binss/HTTPServer
8f2bcae86b00fed7c237c51aa4e6990d852d9370
[ "MIT" ]
null
null
null
src/Mapper.cpp
binss/HTTPServer
8f2bcae86b00fed7c237c51aa4e6990d852d9370
[ "MIT" ]
null
null
null
src/Mapper.cpp
binss/HTTPServer
8f2bcae86b00fed7c237c51aa4e6990d852d9370
[ "MIT" ]
null
null
null
/*********************************************************** * FileName: Mapper.cpp * Author: binss * Create: 2015-11-06 11:24:22 * Description: No Description ***********************************************************/ #include "Mapper.h" Mapper * Mapper::mapper = NULL; Mapper * Mapper::GetInstance() { if(mapper == NULL) { mapper = new Mapper(); } return mapper; } Mapper::Mapper():logger_("Mapper", DEBUG, true) { InitContentTypeMap(); InitViewMap(); InitReasonMap(); } void Mapper::InitContentTypeMap() { // 0 - 9 chucked content_type_map_[""] = 0; content_type_map_["tml"] = 1; // 10 - 19 fixed-length text file content_type_map_[".js"] = 10; content_type_map_["css"] = 11; // 20 - 29 image content_type_map_["png"] = 20; content_type_map_["jpg"] = 21; content_type_map_["gif"] = 22; content_type_map_["ico"] = 23; } void Mapper::InitReasonMap() { // 0 - 9 chucked reason_map_[200] = "200 OK"; reason_map_[304] = "304 Not Modified"; reason_map_[403] = "403 Forbidden"; reason_map_[404] = "404 Not Found"; reason_map_[500] = "500 Internal Server Error"; } int Mapper::GetContentType(string file_type) { // 默认为0 return content_type_map_[file_type]; } void Mapper::InitViewMap() { view_map_["/"] = main_page; view_map_["/404/"] = error_404; view_map_["/403/"] = error_403; view_map_["/upload/"] = upload_page; view_map_["/user/"] = user_page; } View Mapper::GetView(string target) { View view = view_map_[target]; if(NULL == view) { logger_<<"Can not find the view of the target["<<target<<"]"<<endl; return view_map_["/404/"]; } return view; } string & Mapper::GetReason(int code) { return reason_map_[code]; }
20.505618
75
0.568767
binss
66d5fffc8f179b4dd7597fcf56070e93f11a7dc7
5,640
cpp
C++
Source/UiUndoRedo.cpp
StefanoLusardi/BilinearOscillator
cb53ba05a865cc360243adf0e04ef9421028abcf
[ "MIT" ]
1
2020-03-15T17:48:01.000Z
2020-03-15T17:48:01.000Z
Source/UiUndoRedo.cpp
StefanoLusardi/BilinearOscillator
cb53ba05a865cc360243adf0e04ef9421028abcf
[ "MIT" ]
null
null
null
Source/UiUndoRedo.cpp
StefanoLusardi/BilinearOscillator
cb53ba05a865cc360243adf0e04ef9421028abcf
[ "MIT" ]
null
null
null
/* ============================================================================== This is an automatically generated GUI class created by the Projucer! Be careful when adding custom code to these files, as only the code within the "//[xyz]" and "//[/xyz]" sections will be retained when the file is loaded and re-saved. Created with Projucer version: 5.4.3 ------------------------------------------------------------------------------ The Projucer is part of the JUCE library. Copyright (c) 2017 - ROLI Ltd. ============================================================================== */ //[Headers] You can add your own extra header files here... #include "Core.h" //[/Headers] #include "UiUndoRedo.h" //[MiscUserDefs] You can add your own user definitions and misc code here... //[/MiscUserDefs] //============================================================================== UiUndoRedo::UiUndoRedo (Component* parent, Core& core) : mParent{parent}, mUndoManager{core.getUndoManager()} { //[Constructor_pre] You can add your own custom stuff here.. //[/Constructor_pre] setName ("UiUndoRedo"); mButtonUndo.reset (new TextButton ("ButtonUndo")); addAndMakeVisible (mButtonUndo.get()); mButtonUndo->setButtonText (TRANS("Undo")); mButtonUndo->setColour (TextButton::buttonOnColourId, Colour (0xffa45c94)); mButtonRedo.reset (new TextButton ("ButtonRedo")); addAndMakeVisible (mButtonRedo.get()); mButtonRedo->setButtonText (TRANS("Redo")); mButtonRedo->setColour (TextButton::buttonOnColourId, Colour (0xffa45c94)); //[UserPreSize] mButtonUndo->setEnabled(false); mButtonRedo->setEnabled(false); //[/UserPreSize] setSize (600, 400); //[Constructor] You can add your own custom stuff here.. mButtonUndo->onClick = [&] { mUndoManager.undo(); }; mButtonRedo->onClick = [&] { mUndoManager.redo(); }; startTimer (250); //[/Constructor] } UiUndoRedo::~UiUndoRedo() { //[Destructor_pre]. You can add your own custom destruction code here.. //[/Destructor_pre] mButtonUndo = nullptr; mButtonRedo = nullptr; //[Destructor]. You can add your own custom destruction code here.. //[/Destructor] } //============================================================================== void UiUndoRedo::paint (Graphics& g) { //[UserPrePaint] Add your own custom painting code here.. //[/UserPrePaint] { float x = 0.0f, y = 0.0f, width = static_cast<float> (proportionOfWidth (1.0000f)), height = static_cast<float> (proportionOfHeight (1.0000f)); Colour fillColour = Colours::yellow; Colour strokeColour = Colours::black; //[UserPaintCustomArguments] Customize the painting arguments here.. //[/UserPaintCustomArguments] g.setColour (fillColour); g.fillRoundedRectangle (x, y, width, height, 20.000f); g.setColour (strokeColour); g.drawRoundedRectangle (x, y, width, height, 20.000f, 5.000f); } //[UserPaint] Add your own custom painting code here.. //[/UserPaint] } void UiUndoRedo::resized() { //[UserPreResize] Add your own custom resize code here.. //[/UserPreResize] mButtonUndo->setBounds (proportionOfWidth (0.0391f), proportionOfHeight (0.2530f), proportionOfWidth (0.4104f), proportionOfHeight (0.5060f)); mButtonRedo->setBounds (proportionOfWidth (0.5570f), proportionOfHeight (0.2530f), proportionOfWidth (0.4104f), proportionOfHeight (0.5060f)); //[UserResized] Add your own custom resize handling here.. //[/UserResized] } //[MiscUserCode] You can add your own definitions of your custom methods or any other code here... void UiUndoRedo::timerCallback() { mButtonUndo->setEnabled(mUndoManager.canUndo()); mButtonRedo->setEnabled(mUndoManager.canRedo()); } //[/MiscUserCode] //============================================================================== #if 0 /* -- Projucer information section -- This is where the Projucer stores the metadata that describe this GUI layout, so make changes in here at your peril! BEGIN_JUCER_METADATA <JUCER_COMPONENT documentType="Component" className="UiUndoRedo" componentName="UiUndoRedo" parentClasses="public Component, public Timer" constructorParams="Component* parent, Core&amp; core" variableInitialisers="mParent{parent}, mUndoManager{core.getUndoManager()}" snapPixels="8" snapActive="1" snapShown="1" overlayOpacity="0.330" fixedSize="0" initialWidth="600" initialHeight="400"> <BACKGROUND backgroundColour="0"> <ROUNDRECT pos="0 0 100% 100%" cornerSize="20.0" fill="solid: ffffff00" hasStroke="1" stroke="5, mitered, butt" strokeColour="solid: ff000000"/> </BACKGROUND> <TEXTBUTTON name="ButtonUndo" id="2905daae1318e8f9" memberName="mButtonUndo" virtualName="" explicitFocusOrder="0" pos="3.867% 25.397% 40.884% 50.794%" bgColOn="ffa45c94" buttonText="Undo" connectedEdges="0" needsCallback="0" radioGroupId="0"/> <TEXTBUTTON name="ButtonRedo" id="f80fc073aaa0b332" memberName="mButtonRedo" virtualName="" explicitFocusOrder="0" pos="55.801% 25.397% 40.884% 50.794%" bgColOn="ffa45c94" buttonText="Redo" connectedEdges="0" needsCallback="0" radioGroupId="0"/> </JUCER_COMPONENT> END_JUCER_METADATA */ #endif //[EndFile] You can add extra defines here... //[/EndFile]
35.923567
152
0.606738
StefanoLusardi
66d7ac6c6ee2501963e8ba43336d8cb525e8cfeb
904
hpp
C++
Engine/Lang/AST/Nodes/Conditional/ASTNodeIfStatement.hpp
GabyForceQ/PolluxEngine
2dbc84ed1d434f1b6d794f775f315758f0e8cc49
[ "BSD-3-Clause" ]
3
2020-05-19T20:24:28.000Z
2020-09-27T11:28:42.000Z
Engine/Lang/AST/Nodes/Conditional/ASTNodeIfStatement.hpp
GabyForceQ/PolluxEngine
2dbc84ed1d434f1b6d794f775f315758f0e8cc49
[ "BSD-3-Clause" ]
31
2020-05-27T11:01:27.000Z
2020-08-08T15:53:23.000Z
Engine/Lang/AST/Nodes/Conditional/ASTNodeIfStatement.hpp
GabyForceQ/PolluxEngine
2dbc84ed1d434f1b6d794f775f315758f0e8cc49
[ "BSD-3-Clause" ]
null
null
null
/***************************************************************************************************************************** * Copyright 2020 Gabriel Gheorghe. All rights reserved. * This code is licensed under the BSD 3-Clause "New" or "Revised" License * License url: https://github.com/GabyForceQ/PolluxEngine/blob/master/LICENSE *****************************************************************************************************************************/ #pragma once #include "../../ASTNodeBase.hpp" namespace Pollux::Lang { class ASTNodeIfStatement final : public ASTNodeBase { public: ASTNodeIfStatement() noexcept; void Accept(IASTNodeVisitor* pVisitor) override; ASTNodeExpression* pExpression = nullptr; ASTNodeScope* pIfScope = nullptr; ASTNodeScope* pElseScope = nullptr; bool bHasElseScope = false; bool bComptimeEval = false; AST_FRIENDS_BODY }; }
28.25
127
0.533186
GabyForceQ
66dada6aaee5ee9855357d9c260122634db95977
9,323
cc
C++
chromeos/dbus/fake_shill_profile_client.cc
Wzzzx/chromium-crosswalk
768dde8efa71169f1c1113ca6ef322f1e8c9e7de
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
2
2019-01-28T08:09:58.000Z
2021-11-15T15:32:10.000Z
chromeos/dbus/fake_shill_profile_client.cc
maidiHaitai/haitaibrowser
a232a56bcfb177913a14210e7733e0ea83a6b18d
[ "BSD-3-Clause" ]
1
2016-07-11T15:19:20.000Z
2017-04-02T20:38:55.000Z
chromeos/dbus/fake_shill_profile_client.cc
maidiHaitai/haitaibrowser
a232a56bcfb177913a14210e7733e0ea83a6b18d
[ "BSD-3-Clause" ]
6
2020-09-23T08:56:12.000Z
2021-11-18T03:40:49.000Z
// 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 "chromeos/dbus/fake_shill_profile_client.h" #include "base/bind.h" #include "base/bind_helpers.h" #include "base/location.h" #include "base/single_thread_task_runner.h" #include "base/stl_util.h" #include "base/threading/thread_task_runner_handle.h" #include "base/values.h" #include "chromeos/dbus/dbus_thread_manager.h" #include "chromeos/dbus/shill_property_changed_observer.h" #include "chromeos/dbus/shill_service_client.h" #include "dbus/bus.h" #include "dbus/message.h" #include "dbus/object_path.h" #include "dbus/values_util.h" #include "third_party/cros_system_api/dbus/service_constants.h" namespace chromeos { struct FakeShillProfileClient::ProfileProperties { base::DictionaryValue entries; // Dictionary of Service Dictionaries base::DictionaryValue properties; // Dictionary of Profile properties }; namespace { void PassDictionary( const ShillProfileClient::DictionaryValueCallbackWithoutStatus& callback, const base::DictionaryValue* dictionary) { callback.Run(*dictionary); } } // namespace FakeShillProfileClient::FakeShillProfileClient() { } FakeShillProfileClient::~FakeShillProfileClient() { STLDeleteValues(&profiles_); } void FakeShillProfileClient::Init(dbus::Bus* bus) { } void FakeShillProfileClient::AddPropertyChangedObserver( const dbus::ObjectPath& profile_path, ShillPropertyChangedObserver* observer) { } void FakeShillProfileClient::RemovePropertyChangedObserver( const dbus::ObjectPath& profile_path, ShillPropertyChangedObserver* observer) { } void FakeShillProfileClient::GetProperties( const dbus::ObjectPath& profile_path, const DictionaryValueCallbackWithoutStatus& callback, const ErrorCallback& error_callback) { ProfileProperties* profile = GetProfile(profile_path, error_callback); if (!profile) return; std::unique_ptr<base::DictionaryValue> properties( profile->properties.DeepCopy()); base::ListValue* entry_paths = new base::ListValue; properties->SetWithoutPathExpansion(shill::kEntriesProperty, entry_paths); for (base::DictionaryValue::Iterator it(profile->entries); !it.IsAtEnd(); it.Advance()) { entry_paths->AppendString(it.key()); } base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::Bind(&PassDictionary, callback, base::Owned(properties.release()))); } void FakeShillProfileClient::GetEntry( const dbus::ObjectPath& profile_path, const std::string& entry_path, const DictionaryValueCallbackWithoutStatus& callback, const ErrorCallback& error_callback) { ProfileProperties* profile = GetProfile(profile_path, error_callback); if (!profile) return; base::DictionaryValue* entry = NULL; profile->entries.GetDictionaryWithoutPathExpansion(entry_path, &entry); if (!entry) { error_callback.Run("Error.InvalidProfileEntry", "Invalid profile entry"); return; } base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::Bind(&PassDictionary, callback, base::Owned(entry->DeepCopy()))); } void FakeShillProfileClient::DeleteEntry(const dbus::ObjectPath& profile_path, const std::string& entry_path, const base::Closure& callback, const ErrorCallback& error_callback) { ProfileProperties* profile = GetProfile(profile_path, error_callback); if (!profile) return; if (!profile->entries.RemoveWithoutPathExpansion(entry_path, NULL)) { error_callback.Run("Error.InvalidProfileEntry", entry_path); return; } base::StringValue profile_path_value(""); DBusThreadManager::Get()->GetShillServiceClient()->GetTestInterface()-> SetServiceProperty(entry_path, shill::kProfileProperty, profile_path_value); base::ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE, callback); } ShillProfileClient::TestInterface* FakeShillProfileClient::GetTestInterface() { return this; } void FakeShillProfileClient::AddProfile(const std::string& profile_path, const std::string& userhash) { if (GetProfile(dbus::ObjectPath(profile_path), ErrorCallback())) return; ProfileProperties* profile = new ProfileProperties; profile->properties.SetStringWithoutPathExpansion(shill::kUserHashProperty, userhash); profiles_[profile_path] = profile; DBusThreadManager::Get()->GetShillManagerClient()->GetTestInterface()-> AddProfile(profile_path); } void FakeShillProfileClient::AddEntry(const std::string& profile_path, const std::string& entry_path, const base::DictionaryValue& properties) { ProfileProperties* profile = GetProfile(dbus::ObjectPath(profile_path), ErrorCallback()); DCHECK(profile); profile->entries.SetWithoutPathExpansion(entry_path, properties.DeepCopy()); DBusThreadManager::Get()->GetShillManagerClient()->GetTestInterface()-> AddManagerService(entry_path, true); } bool FakeShillProfileClient::AddService(const std::string& profile_path, const std::string& service_path) { ProfileProperties* profile = GetProfile(dbus::ObjectPath(profile_path), ErrorCallback()); if (!profile) { LOG(ERROR) << "AddService: No matching profile: " << profile_path << " for: " << service_path; return false; } if (profile->entries.HasKey(service_path)) return false; return AddOrUpdateServiceImpl(profile_path, service_path, profile); } bool FakeShillProfileClient::UpdateService(const std::string& profile_path, const std::string& service_path) { ProfileProperties* profile = GetProfile(dbus::ObjectPath(profile_path), ErrorCallback()); if (!profile) { LOG(ERROR) << "UpdateService: No matching profile: " << profile_path << " for: " << service_path; return false; } if (!profile->entries.HasKey(service_path)) { LOG(ERROR) << "UpdateService: Profile: " << profile_path << " does not contain Service: " << service_path; return false; } return AddOrUpdateServiceImpl(profile_path, service_path, profile); } bool FakeShillProfileClient::AddOrUpdateServiceImpl( const std::string& profile_path, const std::string& service_path, ProfileProperties* profile) { ShillServiceClient::TestInterface* service_test = DBusThreadManager::Get()->GetShillServiceClient()->GetTestInterface(); const base::DictionaryValue* service_properties = service_test->GetServiceProperties(service_path); if (!service_properties) { LOG(ERROR) << "No matching service: " << service_path; return false; } std::string service_profile_path; service_properties->GetStringWithoutPathExpansion(shill::kProfileProperty, &service_profile_path); if (service_profile_path.empty()) { base::StringValue profile_path_value(profile_path); service_test->SetServiceProperty(service_path, shill::kProfileProperty, profile_path_value); } else if (service_profile_path != profile_path) { LOG(ERROR) << "Service has non matching profile path: " << service_profile_path; return false; } profile->entries.SetWithoutPathExpansion(service_path, service_properties->DeepCopy()); return true; } void FakeShillProfileClient::GetProfilePaths( std::vector<std::string>* profiles) { for (ProfileMap::iterator iter = profiles_.begin(); iter != profiles_.end(); ++iter) { profiles->push_back(iter->first); } } bool FakeShillProfileClient::GetService(const std::string& service_path, std::string* profile_path, base::DictionaryValue* properties) { properties->Clear(); for (ProfileMap::const_iterator iter = profiles_.begin(); iter != profiles_.end(); ++iter) { const ProfileProperties* profile = iter->second; const base::DictionaryValue* entry; if (!profile->entries.GetDictionaryWithoutPathExpansion( service_path, &entry)) { continue; } *profile_path = iter->first; properties->MergeDictionary(entry); return true; } return false; } void FakeShillProfileClient::ClearProfiles() { STLDeleteValues(&profiles_); } FakeShillProfileClient::ProfileProperties* FakeShillProfileClient::GetProfile( const dbus::ObjectPath& profile_path, const ErrorCallback& error_callback) { ProfileMap::const_iterator found = profiles_.find(profile_path.value()); if (found == profiles_.end()) { if (!error_callback.is_null()) error_callback.Run("Error.InvalidProfile", "Invalid profile"); return NULL; } return found->second; } } // namespace chromeos
35.857692
80
0.681969
Wzzzx
66db37e769a9b33ab81395527d6b607bb0c1943b
300
cc
C++
cpp/cli/src/pe19.cc
kittttttan/pe
6f87e4527793198c393700fedbdd52274fec5b44
[ "MIT" ]
null
null
null
cpp/cli/src/pe19.cc
kittttttan/pe
6f87e4527793198c393700fedbdd52274fec5b44
[ "MIT" ]
null
null
null
cpp/cli/src/pe19.cc
kittttttan/pe
6f87e4527793198c393700fedbdd52274fec5b44
[ "MIT" ]
1
2016-09-01T22:47:28.000Z
2016-09-01T22:47:28.000Z
#include "../include/pe19.h" #include <cstdlib> #include <iostream> int pe19(int argc, char **argv) { using namespace std; uint32_t n = 2000; if (argc > 1) { char *end; n = strtoul(argv[1], &end, 10); } cout << "n = " << n << endl; cout << pe::pe19(n) << endl; return 0; }
14.285714
35
0.546667
kittttttan
66dbe0bfd92e29fd9e3a76640280f22043867d85
14,891
cc
C++
src/objects/js-list-format.cc
mtk-watch/android_external_v8
29eb30806a59123b1f9faf9083a12d26fa418fad
[ "BSD-3-Clause" ]
2
2020-08-27T19:12:59.000Z
2021-01-27T05:45:29.000Z
src/objects/js-list-format.cc
mtk-watch/android_external_v8
29eb30806a59123b1f9faf9083a12d26fa418fad
[ "BSD-3-Clause" ]
null
null
null
src/objects/js-list-format.cc
mtk-watch/android_external_v8
29eb30806a59123b1f9faf9083a12d26fa418fad
[ "BSD-3-Clause" ]
null
null
null
// Copyright 2018 the V8 project 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 V8_INTL_SUPPORT #error Internationalization is expected to be enabled. #endif // V8_INTL_SUPPORT #include "src/objects/js-list-format.h" #include <memory> #include <vector> #include "src/elements.h" #include "src/heap/factory.h" #include "src/isolate.h" #include "src/objects-inl.h" #include "src/objects/intl-objects.h" #include "src/objects/js-array-inl.h" #include "src/objects/js-list-format-inl.h" #include "src/objects/managed.h" #include "unicode/listformatter.h" namespace v8 { namespace internal { namespace { const char* kStandard = "standard"; const char* kOr = "or"; const char* kUnit = "unit"; const char* kStandardShort = "standard-short"; const char* kUnitShort = "unit-short"; const char* kUnitNarrow = "unit-narrow"; const char* GetIcuStyleString(JSListFormat::Style style, JSListFormat::Type type) { switch (type) { case JSListFormat::Type::CONJUNCTION: switch (style) { case JSListFormat::Style::LONG: return kStandard; case JSListFormat::Style::SHORT: return kStandardShort; case JSListFormat::Style::NARROW: // Currently, ListFormat::createInstance on "standard-narrow" will // fail so we use "standard-short" here. // See https://unicode.org/cldr/trac/ticket/11254 // TODO(ftang): change to return kStandardNarrow; after the above // issue fixed in CLDR/ICU. // CLDR bug: https://unicode.org/cldr/trac/ticket/11254 // ICU bug: https://unicode-org.atlassian.net/browse/ICU-20014 return kStandardShort; case JSListFormat::Style::COUNT: UNREACHABLE(); } case JSListFormat::Type::DISJUNCTION: switch (style) { // Currently, ListFormat::createInstance on "or-short" and "or-narrow" // will fail so we use "or" here. // See https://unicode.org/cldr/trac/ticket/11254 // TODO(ftang): change to return kOr, kOrShort or kOrNarrow depend on // style after the above issue fixed in CLDR/ICU. // CLDR bug: https://unicode.org/cldr/trac/ticket/11254 // ICU bug: https://unicode-org.atlassian.net/browse/ICU-20014 case JSListFormat::Style::LONG: case JSListFormat::Style::SHORT: case JSListFormat::Style::NARROW: return kOr; case JSListFormat::Style::COUNT: UNREACHABLE(); } case JSListFormat::Type::UNIT: switch (style) { case JSListFormat::Style::LONG: return kUnit; case JSListFormat::Style::SHORT: return kUnitShort; case JSListFormat::Style::NARROW: return kUnitNarrow; case JSListFormat::Style::COUNT: UNREACHABLE(); } case JSListFormat::Type::COUNT: UNREACHABLE(); } } } // namespace JSListFormat::Style get_style(const char* str) { switch (str[0]) { case 'n': if (strcmp(&str[1], "arrow") == 0) return JSListFormat::Style::NARROW; break; case 'l': if (strcmp(&str[1], "ong") == 0) return JSListFormat::Style::LONG; break; case 's': if (strcmp(&str[1], "hort") == 0) return JSListFormat::Style::SHORT; break; } UNREACHABLE(); } JSListFormat::Type get_type(const char* str) { switch (str[0]) { case 'c': if (strcmp(&str[1], "onjunction") == 0) return JSListFormat::Type::CONJUNCTION; break; case 'd': if (strcmp(&str[1], "isjunction") == 0) return JSListFormat::Type::DISJUNCTION; break; case 'u': if (strcmp(&str[1], "nit") == 0) return JSListFormat::Type::UNIT; break; } UNREACHABLE(); } MaybeHandle<JSListFormat> JSListFormat::InitializeListFormat( Isolate* isolate, Handle<JSListFormat> list_format_holder, Handle<Object> input_locales, Handle<Object> input_options) { Factory* factory = isolate->factory(); list_format_holder->set_flags(0); Handle<JSReceiver> options; // 2. If options is undefined, then if (input_options->IsUndefined(isolate)) { // a. Let options be ObjectCreate(null). options = isolate->factory()->NewJSObjectWithNullProto(); // 3. Else } else { // a. Let options be ? ToObject(options). ASSIGN_RETURN_ON_EXCEPTION(isolate, options, Object::ToObject(isolate, input_options), JSListFormat); } // 5. Let t be GetOption(options, "type", "string", «"conjunction", // "disjunction", "unit"», "conjunction"). std::unique_ptr<char[]> type_str = nullptr; std::vector<const char*> type_values = {"conjunction", "disjunction", "unit"}; Maybe<bool> maybe_found_type = Intl::GetStringOption( isolate, options, "type", type_values, "Intl.ListFormat", &type_str); Type type_enum = Type::CONJUNCTION; MAYBE_RETURN(maybe_found_type, MaybeHandle<JSListFormat>()); if (maybe_found_type.FromJust()) { DCHECK_NOT_NULL(type_str.get()); type_enum = get_type(type_str.get()); } // 6. Set listFormat.[[Type]] to t. list_format_holder->set_type(type_enum); // 7. Let s be ? GetOption(options, "style", "string", // «"long", "short", "narrow"», "long"). std::unique_ptr<char[]> style_str = nullptr; std::vector<const char*> style_values = {"long", "short", "narrow"}; Maybe<bool> maybe_found_style = Intl::GetStringOption( isolate, options, "style", style_values, "Intl.ListFormat", &style_str); Style style_enum = Style::LONG; MAYBE_RETURN(maybe_found_style, MaybeHandle<JSListFormat>()); if (maybe_found_style.FromJust()) { DCHECK_NOT_NULL(style_str.get()); style_enum = get_style(style_str.get()); } // 15. Set listFormat.[[Style]] to s. list_format_holder->set_style(style_enum); // 10. Let r be ResolveLocale(%ListFormat%.[[AvailableLocales]], // requestedLocales, opt, undefined, localeData). Handle<JSObject> r; ASSIGN_RETURN_ON_EXCEPTION( isolate, r, Intl::ResolveLocale(isolate, "listformat", input_locales, options), JSListFormat); Handle<Object> locale_obj = JSObject::GetDataProperty(r, factory->locale_string()); Handle<String> locale; ASSIGN_RETURN_ON_EXCEPTION( isolate, locale, Object::ToString(isolate, locale_obj), JSListFormat); // 18. Set listFormat.[[Locale]] to the value of r.[[Locale]]. list_format_holder->set_locale(*locale); std::unique_ptr<char[]> locale_name = locale->ToCString(); icu::Locale icu_locale(locale_name.get()); UErrorCode status = U_ZERO_ERROR; icu::ListFormatter* formatter = icu::ListFormatter::createInstance( icu_locale, GetIcuStyleString(style_enum, type_enum), status); if (U_FAILURE(status)) { delete formatter; FATAL("Failed to create ICU list formatter, are ICU data files missing?"); } CHECK_NOT_NULL(formatter); Handle<Managed<icu::ListFormatter>> managed_formatter = Managed<icu::ListFormatter>::FromRawPtr(isolate, 0, formatter); list_format_holder->set_formatter(*managed_formatter); return list_format_holder; } Handle<JSObject> JSListFormat::ResolvedOptions( Isolate* isolate, Handle<JSListFormat> format_holder) { Factory* factory = isolate->factory(); Handle<JSObject> result = factory->NewJSObject(isolate->object_function()); Handle<String> locale(format_holder->locale(), isolate); JSObject::AddProperty(isolate, result, factory->locale_string(), locale, NONE); JSObject::AddProperty(isolate, result, factory->style_string(), format_holder->StyleAsString(), NONE); JSObject::AddProperty(isolate, result, factory->type_string(), format_holder->TypeAsString(), NONE); return result; } icu::ListFormatter* JSListFormat::UnpackFormatter(Isolate* isolate, Handle<JSListFormat> holder) { return Managed<icu::ListFormatter>::cast(holder->formatter())->raw(); } Handle<String> JSListFormat::StyleAsString() const { switch (style()) { case Style::LONG: return GetReadOnlyRoots().long_string_handle(); case Style::SHORT: return GetReadOnlyRoots().short_string_handle(); case Style::NARROW: return GetReadOnlyRoots().narrow_string_handle(); case Style::COUNT: UNREACHABLE(); } } Handle<String> JSListFormat::TypeAsString() const { switch (type()) { case Type::CONJUNCTION: return GetReadOnlyRoots().conjunction_string_handle(); case Type::DISJUNCTION: return GetReadOnlyRoots().disjunction_string_handle(); case Type::UNIT: return GetReadOnlyRoots().unit_string_handle(); case Type::COUNT: UNREACHABLE(); } } namespace { // TODO(ftang) remove the following hack after icu::ListFormat support // FieldPosition. // This is a temporary workaround until icu::ListFormat support FieldPosition // It is inefficient and won't work correctly on the edge case that the input // contains fraction of the list pattern. // For example the following under English will mark the "an" incorrectly // since the formatted is "a, b, and an". // listFormat.formatToParts(["a", "b", "an"]) // https://ssl.icu-project.org/trac/ticket/13754 MaybeHandle<JSArray> GenerateListFormatParts( Isolate* isolate, const icu::UnicodeString& formatted, const icu::UnicodeString items[], int length) { Factory* factory = isolate->factory(); int estimate_size = length * 2 + 1; Handle<JSArray> array = factory->NewJSArray(estimate_size); int index = 0; int last_pos = 0; for (int i = 0; i < length; i++) { int found = formatted.indexOf(items[i], last_pos); DCHECK_GE(found, 0); if (found > last_pos) { Handle<String> substring; ASSIGN_RETURN_ON_EXCEPTION( isolate, substring, Intl::ToString(isolate, formatted, last_pos, found), JSArray); Intl::AddElement(isolate, array, index++, factory->literal_string(), substring); } last_pos = found + items[i].length(); Handle<String> substring; ASSIGN_RETURN_ON_EXCEPTION( isolate, substring, Intl::ToString(isolate, formatted, found, last_pos), JSArray); Intl::AddElement(isolate, array, index++, factory->element_string(), substring); } if (last_pos < formatted.length()) { Handle<String> substring; ASSIGN_RETURN_ON_EXCEPTION( isolate, substring, Intl::ToString(isolate, formatted, last_pos, formatted.length()), JSArray); Intl::AddElement(isolate, array, index++, factory->literal_string(), substring); } return array; } // Extract String from JSArray into array of UnicodeString Maybe<bool> ToUnicodeStringArray(Isolate* isolate, Handle<JSArray> array, icu::UnicodeString items[], uint32_t length) { Factory* factory = isolate->factory(); // In general, ElementsAccessor::Get actually isn't guaranteed to give us the // elements in order. But given that it was created by a builtin we control, // it shouldn't be possible for it to be problematic. Add DCHECK to ensure // that. DCHECK(array->HasFastPackedElements()); auto* accessor = array->GetElementsAccessor(); DCHECK(length == accessor->NumberOfElements(*array)); // ecma402 #sec-createpartsfromlist // 2. If list contains any element value such that Type(value) is not String, // throw a TypeError exception. // // Per spec it looks like we're supposed to throw a TypeError exception if the // item isn't already a string, rather than coercing to a string. Moreover, // the way the spec's written it looks like we're supposed to run through the // whole list to check that they're all strings before going further. for (uint32_t i = 0; i < length; i++) { Handle<Object> item = accessor->Get(array, i); DCHECK(!item.is_null()); if (!item->IsString()) { THROW_NEW_ERROR_RETURN_VALUE( isolate, NewTypeError(MessageTemplate::kArrayItemNotType, factory->NewStringFromStaticChars("list"), factory->NewNumber(i), factory->NewStringFromStaticChars("String")), Nothing<bool>()); } } for (uint32_t i = 0; i < length; i++) { Handle<String> string = Handle<String>::cast(accessor->Get(array, i)); DisallowHeapAllocation no_gc; string = String::Flatten(isolate, string); std::unique_ptr<uc16[]> sap; items[i] = icu::UnicodeString(GetUCharBufferFromFlat(string->GetFlatContent(), &sap, string->length()), string->length()); } return Just(true); } } // namespace Maybe<bool> FormatListCommon(Isolate* isolate, Handle<JSListFormat> format_holder, Handle<JSArray> list, icu::UnicodeString& formatted, uint32_t* length, std::unique_ptr<icu::UnicodeString[]>& array) { DCHECK(!list->IsUndefined()); icu::ListFormatter* formatter = JSListFormat::UnpackFormatter(isolate, format_holder); CHECK_NOT_NULL(formatter); *length = list->GetElementsAccessor()->NumberOfElements(*list); array.reset(new icu::UnicodeString[*length]); // ecma402 #sec-createpartsfromlist // 2. If list contains any element value such that Type(value) is not String, // throw a TypeError exception. MAYBE_RETURN(ToUnicodeStringArray(isolate, list, array.get(), *length), Nothing<bool>()); UErrorCode status = U_ZERO_ERROR; formatter->format(array.get(), *length, formatted, status); DCHECK(U_SUCCESS(status)); return Just(true); } // ecma402 #sec-formatlist MaybeHandle<String> JSListFormat::FormatList(Isolate* isolate, Handle<JSListFormat> format_holder, Handle<JSArray> list) { icu::UnicodeString formatted; uint32_t length; std::unique_ptr<icu::UnicodeString[]> array; MAYBE_RETURN( FormatListCommon(isolate, format_holder, list, formatted, &length, array), Handle<String>()); return Intl::ToString(isolate, formatted); } // ecma42 #sec-formatlisttoparts MaybeHandle<JSArray> JSListFormat::FormatListToParts( Isolate* isolate, Handle<JSListFormat> format_holder, Handle<JSArray> list) { icu::UnicodeString formatted; uint32_t length; std::unique_ptr<icu::UnicodeString[]> array; MAYBE_RETURN( FormatListCommon(isolate, format_holder, list, formatted, &length, array), Handle<JSArray>()); return GenerateListFormatParts(isolate, formatted, array.get(), length); } } // namespace internal } // namespace v8
37.042289
80
0.657646
mtk-watch
66dcdc4dd1312b091c26771ee52645ad4b343e72
10,503
cpp
C++
mfcplotDoc.cpp
fossabot/mfcplot
8a051bdce16742210678ec1003382253730bef0e
[ "MIT" ]
28
2020-07-20T10:00:44.000Z
2022-02-10T05:44:29.000Z
mfcplotDoc.cpp
fossabot/mfcplot
8a051bdce16742210678ec1003382253730bef0e
[ "MIT" ]
1
2021-02-13T15:35:56.000Z
2021-02-13T15:35:56.000Z
mfcplotDoc.cpp
fossabot/mfcplot
8a051bdce16742210678ec1003382253730bef0e
[ "MIT" ]
15
2020-07-23T01:15:54.000Z
2022-03-20T14:58:15.000Z
 // mfcplotDoc.cpp: CmfcplotDoc 类的实现 // #include "pch.h" #include "framework.h" // SHARED_HANDLERS 可以在实现预览、缩略图和搜索筛选器句柄的 // ATL 项目中进行定义,并允许与该项目共享文档代码。 #ifndef SHARED_HANDLERS #include "mfcplot.h" #endif #include "mfcplotDoc.h" #include <utility> #include <propkey.h> #include "CFuncDlg.h" #include "CNormalFuncDlg.h" #include "CPolarFuncDlg.h" #include "CSetXYrangeDlg.h" #include "CTwoFuncDlg.h" #include "CDataFuncDlg.h" #include "CDelFuncDlg.h" #ifdef _DEBUG #define new DEBUG_NEW #endif // CmfcplotDoc IMPLEMENT_DYNCREATE(CmfcplotDoc, CDocument) BEGIN_MESSAGE_MAP(CmfcplotDoc, CDocument) ON_COMMAND(ID_AXIS_MENU, &CmfcplotDoc::OnAxisMenu) ON_COMMAND(ID_GRID_MENU, &CmfcplotDoc::OnGridMenu) ON_COMMAND(ID_SMALLER_MENU, &CmfcplotDoc::OnSmallerMenu) ON_COMMAND(ID_BIGGER_MENU, &CmfcplotDoc::OnBiggerMenu) ON_COMMAND(ID_NORMAL_FUNC_MENU, &CmfcplotDoc::OnNormalFuncMenu) ON_UPDATE_COMMAND_UI(ID_EDGE_MENU, &CmfcplotDoc::OnUpdateEdgeMenu) ON_COMMAND(ID_EDGE_MENU, &CmfcplotDoc::OnEdgeMenu) ON_COMMAND(ID_Menu_SET_XYRANGE, &CmfcplotDoc::OnMenuSetXyrange) ON_COMMAND(ID_FUNC_MODE, &CmfcplotDoc::OnFuncMode) ON_UPDATE_COMMAND_UI(ID_FUNC_MODE, &CmfcplotDoc::OnUpdateFuncMode) ON_UPDATE_COMMAND_UI(ID_AXIS_MENU, &CmfcplotDoc::OnUpdateAxisMenu) ON_UPDATE_COMMAND_UI(ID_GRID_MENU, &CmfcplotDoc::OnUpdateGridMenu) ON_COMMAND(ID_POLAR_FUNC_MENU, &CmfcplotDoc::OnPolarFuncMenu) ON_COMMAND(ID_TWO_FUNC_MENU, &CmfcplotDoc::OnTwoFuncMenu) ON_COMMAND(ID_DATA_FUNC_MENU, &CmfcplotDoc::OnDataFuncMenu) ON_COMMAND(ID_FROCE_XRANG, &CmfcplotDoc::OnFroceXrang) ON_UPDATE_COMMAND_UI(ID_FROCE_XRANG, &CmfcplotDoc::OnUpdateFroceXrang) ON_COMMAND(ID_DELALL_MENU, &CmfcplotDoc::OnDelallMenu) ON_COMMAND(ID_NEARPOINT_MENU, &CmfcplotDoc::OnNearpointMenu) ON_UPDATE_COMMAND_UI(ID_NEARPOINT_MENU, &CmfcplotDoc::OnUpdateNearpointMenu) ON_COMMAND(ID_AUTORANGE_MENU, &CmfcplotDoc::OnAutorangeMenu) ON_COMMAND(ID_DELFUNCONE_MENU, &CmfcplotDoc::OnDelfunconeMenu) END_MESSAGE_MAP() // CmfcplotDoc 构造/析构 CmfcplotDoc::CmfcplotDoc() noexcept { // TODO: 在此添加一次性构造代码 m_WillShowGrid = true; m_WillShowAxis = true; m_WillShowEdge = true; m_SingelMode = true; m_ForceXrange = false; m_ShowNearPoint = false; m_Xmin = -10; m_Xmax = 10; m_Ymin = -1; m_Ymax = 1; m_FD = nullptr; } CmfcplotDoc::~CmfcplotDoc() { } BOOL CmfcplotDoc::OnNewDocument() { if (!CDocument::OnNewDocument()) return FALSE; // TODO: 在此添加重新初始化代码 // (SDI 文档将重用该文档) return TRUE; } // CmfcplotDoc 序列化 void CmfcplotDoc::Serialize(CArchive& ar) { m_List.Serialize(ar); if (ar.IsStoring()) { // TODO: 在此添加存储代码 ar << m_WillShowGrid << m_WillShowAxis << m_WillShowEdge << m_SingelMode << m_ForceXrange << m_ShowNearPoint \ << m_Xmin << m_Xmax << m_Ymin << m_Ymax; } else { // TODO: 在此添加加载代码 ar >> m_WillShowGrid >> m_WillShowAxis >> m_WillShowEdge >> m_SingelMode >> m_ForceXrange >> m_ShowNearPoint \ >> m_Xmin >> m_Xmax >> m_Ymin >> m_Ymax; } } #ifdef SHARED_HANDLERS // 缩略图的支持 void CmfcplotDoc::OnDrawThumbnail(CDC& dc, LPRECT lprcBounds) { // 修改此代码以绘制文档数据 dc.FillSolidRect(lprcBounds, RGB(255, 255, 255)); CString strText = _T("TODO: implement thumbnail drawing here"); LOGFONT lf; CFont* pDefaultGUIFont = CFont::FromHandle((HFONT) GetStockObject(DEFAULT_GUI_FONT)); pDefaultGUIFont->GetLogFont(&lf); lf.lfHeight = 36; CFont fontDraw; fontDraw.CreateFontIndirect(&lf); CFont* pOldFont = dc.SelectObject(&fontDraw); dc.DrawText(strText, lprcBounds, DT_CENTER | DT_WORDBREAK); dc.SelectObject(pOldFont); } // 搜索处理程序的支持 void CmfcplotDoc::InitializeSearchContent() { CString strSearchContent; // 从文档数据设置搜索内容。 // 内容部分应由“;”分隔 // 例如: strSearchContent = _T("point;rectangle;circle;ole object;"); SetSearchContent(strSearchContent); } void CmfcplotDoc::SetSearchContent(const CString& value) { if (value.IsEmpty()) { RemoveChunk(PKEY_Search_Contents.fmtid, PKEY_Search_Contents.pid); } else { CMFCFilterChunkValueImpl *pChunk = nullptr; ATLTRY(pChunk = new CMFCFilterChunkValueImpl); if (pChunk != nullptr) { pChunk->SetTextValue(PKEY_Search_Contents, value, CHUNK_TEXT); SetChunkValue(pChunk); } } } #endif // SHARED_HANDLERS // CmfcplotDoc 诊断 #ifdef _DEBUG void CmfcplotDoc::AssertValid() const { CDocument::AssertValid(); } void CmfcplotDoc::Dump(CDumpContext& dc) const { CDocument::Dump(dc); } #endif //_DEBUG // CmfcplotDoc 命令 void CmfcplotDoc::OnAxisMenu() { // TODO: 在此添加命令处理程序代码 m_WillShowAxis = !m_WillShowAxis; this->UpdateAllViews(NULL); } void CmfcplotDoc::OnGridMenu() { // TODO: 在此添加命令处理程序代码 m_WillShowGrid = !m_WillShowGrid; this->UpdateAllViews(NULL); } void CmfcplotDoc::OnSmallerMenu() { // TODO: 在此添加命令处理程序代码 double detx = (m_Xmax - m_Xmin) * 0.125; m_Xmax += detx; m_Xmin -= detx; double dety = (m_Ymax - m_Ymin) * 0.125; m_Ymax += dety; m_Ymin -= dety; UpdateAllViews(NULL); } void CmfcplotDoc::OnBiggerMenu() { // TODO: 在此添加命令处理程序代码 double detx = (m_Xmax - m_Xmin) * 0.1; m_Xmax -= detx; m_Xmin += detx; double dety = (m_Ymax - m_Ymin) * 0.1; m_Ymax -= dety; m_Ymin += dety; UpdateAllViews(NULL); } void CmfcplotDoc::OnUpdateEdgeMenu(CCmdUI* pCmdUI) { // TODO: 在此添加命令更新用户界面处理程序代码 pCmdUI->SetCheck(m_WillShowEdge); } void CmfcplotDoc::OnEdgeMenu() { // TODO: 在此添加命令处理程序代码 m_WillShowEdge = !m_WillShowEdge; UpdateAllViews(NULL); } void CmfcplotDoc::OnMenuSetXyrange() { // TODO: 在此添加命令处理程序代码 CSetXYrangeDlg dlg(m_Xmin, m_Xmax, m_Ymin, m_Ymax, nullptr); if (dlg.DoModal()) { if (dlg.m_Xmin >= dlg.m_Xmax || dlg.m_Ymin >= dlg.m_Ymax) AfxMessageBox(_T("输入不合法!")); else { m_Xmin = dlg.m_Xmin; m_Xmax = dlg.m_Xmax; m_Ymin = dlg.m_Ymin; m_Ymax = dlg.m_Ymax; UpdateAllViews(NULL); } } } void CmfcplotDoc::OnFuncMode() { // TODO: 在此添加命令处理程序代码 m_SingelMode = !m_SingelMode; if (m_SingelMode == true) { this->OnDelallMenu(); } } void CmfcplotDoc::OnUpdateFuncMode(CCmdUI* pCmdUI) { // TODO: 在此添加命令更新用户界面处理程序代码 pCmdUI->SetCheck(m_SingelMode); } void CmfcplotDoc::OnUpdateAxisMenu(CCmdUI* pCmdUI) { // TODO: 在此添加命令更新用户界面处理程序代码 pCmdUI->SetCheck(m_WillShowAxis); } void CmfcplotDoc::OnUpdateGridMenu(CCmdUI* pCmdUI) { // TODO: 在此添加命令更新用户界面处理程序代码 pCmdUI->SetCheck(m_WillShowGrid); } void CmfcplotDoc::OnNormalFuncMenu() { // TODO: 在此添加命令处理程序代码 //CFuncDlg dlg; CNormalFuncDlg dlg(m_Xmin, m_Xmax, nullptr); // if (dlg.DoModal() == IDOK) { if (m_SingelMode) { if (m_FD) delete m_FD; m_List.RemoveAll(); } m_FD = new NormalFD(dlg.m_sEquation, dlg.m_Xmin, dlg.m_Xmax, dlg.m_stepX, dlg.m_color, dlg.m_penWidth, dlg.m_penType); if (m_FD->CalcList() == false) { AfxMessageBox(_T("请检查方程是否完整!")); } else { if (m_FD->minY < m_Ymin) m_Ymin = m_FD->minY; if (m_FD->maxY > m_Ymax) m_Ymax = m_FD->maxY; m_List.AddTail(m_FD); } } UpdateAllViews(NULL); } void CmfcplotDoc::OnPolarFuncMenu() { // TODO: 在此添加命令处理程序代码 CPolarFuncDlg dlg; // if (dlg.DoModal() == IDOK) { if (m_SingelMode) { if (m_FD) delete m_FD; m_List.RemoveAll(); } m_FD = new PolarFD(dlg.m_sEquation, dlg.m_Thetamin, dlg.m_Thetamax, dlg.m_StepTheta, dlg.m_color, dlg.m_penWidth, dlg.m_penType); if (m_FD->CalcList() == false) { AfxMessageBox(_T("请检查方程是否完整!")); } else { if (m_FD->minY < m_Ymin) m_Ymin = m_FD->minY; if (m_FD->maxY > m_Ymax) m_Ymax = m_FD->maxY; if (m_FD->minX < m_Xmin) m_Xmin = m_FD->minX; if (m_FD->maxX > m_Xmax) m_Xmax = m_FD->maxX; m_List.AddTail(m_FD); } } UpdateAllViews(NULL); } void CmfcplotDoc::OnTwoFuncMenu() { // TODO: 在此添加命令处理程序代码 CTwoFuncDlg dlg; if (dlg.DoModal() == IDOK) { if (m_SingelMode) { if (m_FD) delete m_FD; m_List.RemoveAll(); } m_FD = new TwoFD(dlg.m_sEquationX, dlg.m_sEquationY, dlg.m_Tmin, dlg.m_Tmax, dlg.m_stepT, dlg.m_color, dlg.m_penWidth, dlg.m_penType); if (m_FD->CalcList() == false) { AfxMessageBox(_T("请检查方程是否完整!")); } else { if (m_FD->minY < m_Ymin) m_Ymin = m_FD->minY; if (m_FD->maxY > m_Ymax) m_Ymax = m_FD->maxY; if (m_FD->minX < m_Xmin) m_Xmin = m_FD->minX; if (m_FD->maxX > m_Xmax) m_Xmax = m_FD->maxX; m_List.AddTail(m_FD); } } UpdateAllViews(NULL); } void CmfcplotDoc::OnDataFuncMenu() { // TODO: 在此添加命令处理程序代码 CDataFuncDlg dlg; if (dlg.DoModal()) { if (m_SingelMode) { if (m_FD) delete m_FD; m_List.RemoveAll(); } m_FD = new DataFD(dlg.vetX, dlg.vetY, dlg.m_color, dlg.m_penWidth, dlg.m_penType); CString str; if (m_FD->minY < m_Ymin) m_Ymin = m_FD->minY; if (m_FD->maxY > m_Ymax) m_Ymax = m_FD->maxY; if (m_FD->minX < m_Xmin) m_Xmin = m_FD->minX; if (m_FD->maxX > m_Xmax) m_Xmax = m_FD->maxX; m_List.AddTail(m_FD); } UpdateAllViews(NULL); } void CmfcplotDoc::OnFroceXrang() { // TODO: 在此添加命令处理程序代码 m_ForceXrange = !m_ForceXrange; UpdateAllViews(NULL); } void CmfcplotDoc::OnUpdateFroceXrang(CCmdUI* pCmdUI) { // TODO: 在此添加命令更新用户界面处理程序代码 pCmdUI->SetCheck(m_ForceXrange); } void CmfcplotDoc::OnNearpointMenu() { // TODO: 在此添加命令处理程序代码 m_ShowNearPoint = !m_ShowNearPoint; } void CmfcplotDoc::OnUpdateNearpointMenu(CCmdUI* pCmdUI) { // TODO: 在此添加命令更新用户界面处理程序代码 pCmdUI->SetCheck(m_ShowNearPoint); } void CmfcplotDoc::OnDelallMenu() { // TODO: 在此添加命令处理程序代码 POSITION p = m_List.GetHeadPosition(); while (p != nullptr) { FuncData* tmpFD = (FuncData*)m_List.GetNext(p); delete tmpFD; } m_List.RemoveAll(); UpdateAllViews(NULL); } void CmfcplotDoc::OnAutorangeMenu() { // TODO: 在此添加命令处理程序代码 double miX = -10, maX = 10, miY = -1, maY = 1; POSITION p = m_List.GetHeadPosition(); bool flag = true; while (p) { FuncData* tmpFD = (FuncData*)m_List.GetNext(p); if (flag) { miY = tmpFD->minY; maY = tmpFD->maxY; miX = tmpFD->minX; maX = tmpFD->maxX; flag = false; } else { if (tmpFD->minY < miY) miY = tmpFD->minY; if (tmpFD->maxY > maY) maY = tmpFD->maxY; if (tmpFD->minX < miX) miX = tmpFD->minX; if (tmpFD->maxX > maX) maX = tmpFD->maxX; } } if (miX == maX) { miX -= 0.5; maX += 0.5; } if (miY == maY) { miY += 0.5; maY -= 0.5; } m_Xmin = miX; m_Xmax = maX; m_Ymin = miY; m_Ymax = maY; UpdateAllViews(NULL); } void CmfcplotDoc::OnDelfunconeMenu() { // TODO: 在此添加命令处理程序代码 int cnt = 0, id = 0; CDelFuncDlg dlg; if (dlg.DoModal()) { id = dlg.m_id; } POSITION p = m_List.GetHeadPosition(),tmpp; while (p) { tmpp = p; FuncData* tmpFD = (FuncData*)m_List.GetNext(p); cnt++; if (cnt == id) { delete tmpFD; m_List.RemoveAt(tmpp); } } UpdateAllViews(NULL); }
21.218182
136
0.704085
fossabot
66dd78b936aa370ae85f21df97a7b748545c992e
2,704
cpp
C++
CodeForces/Solutions/342E.cpp
Shefin-CSE16/Competitive-Programming
7c792081ae1d4b7060893165de34ffe7b9b7caed
[ "MIT" ]
5
2020-10-03T17:15:26.000Z
2022-03-29T21:39:22.000Z
CodeForces/Solutions/342E.cpp
Shefin-CSE16/Competitive-Programming
7c792081ae1d4b7060893165de34ffe7b9b7caed
[ "MIT" ]
null
null
null
CodeForces/Solutions/342E.cpp
Shefin-CSE16/Competitive-Programming
7c792081ae1d4b7060893165de34ffe7b9b7caed
[ "MIT" ]
1
2021-03-01T12:56:50.000Z
2021-03-01T12:56:50.000Z
#include <bits/stdc++.h> using namespace std; /// decompose(1, -1) //For 1 rooted tree #define ll long long #define pb push_back #define LN 17 const ll MAX = 1e5; vector <ll> g[MAX + 9]; ll del[MAX + 9], sz[MAX + 9], par[MAX + 9], curSize, depth[MAX + 9], dis[MAX + 9], pa[LN][MAX + 9]; void dfs(ll u, ll p) { sz[u] = 1; for(ll i = 0; i < g[u].size(); i++) { ll nd = g[u][i]; if(nd == p || del[nd]) continue; dfs(nd, u); sz[u] += sz[nd]; } } ll findCentroid(ll u, ll p) { for(ll i = 0; i < g[u].size(); i++) { ll nd = g[u][i]; if(nd == p || del[nd] || sz[nd] <= curSize / 2) continue; return findCentroid(nd, u); } return u; } void decompose(ll u, ll p) { dfs(u, -1); curSize = sz[u]; ll cen = findCentroid(u, -1); if(p == -1) p = cen; par[cen] = p, del[cen] = 1; for(ll i = 0; i < g[cen].size(); i++) { ll nd = g[cen][i]; if(!del[nd]) decompose(nd, cen); } } void depthdfs(ll u, ll p) { pa[0][u] = p; for(ll i = 0; i < g[u].size(); i++) { ll nd = g[u][i]; if(nd == p) continue; depth[nd] = depth[u] + 1; depthdfs(nd, u); } } int LCA(int u, int v) { if(depth[u] < depth[v]) swap(u,v); int diff = depth[u] - depth[v]; for(int i=0; i<LN; i++) if( (diff>>i)&1 ) u = pa[i][u]; if(u == v) return u; for(int i=LN-1; i>=0; i--) if(pa[i][u] != pa[i][v]) { u = pa[i][u]; v = pa[i][v]; } return pa[0][u]; } ll dist(ll x, ll y) { ll d= depth[x] + depth[y] - 2 * depth[LCA(x, y)]; return d; } void update(ll nd) { ll u = nd; while(1) { dis[u] = min(dis[u], dist(u, nd)); if(u == par[u]) break; u = par[u]; } } ll query(ll nd) { ll ret = 1e18; ll u = nd; while(1) { ret = min(ret, dis[u] + dist(nd, u)); if(u == par[u]) break; u = par[u]; } return ret; } int main() { for(ll i = 0; i <= MAX; i++) { dis[i] = 1e18; for(ll j = 0; j < LN; j++) pa[j][i] = -1; } ll n, m; cin >> n >> m; for(ll i = 1; i < n; i++) { ll u, v; scanf("%lld %lld", &u, &v); g[u].pb(v); g[v].pb(u); } decompose(1, -1); depthdfs(1, -1); for(int i=1; i<LN; i++) for(int j=1; j<=n; j++) if(pa[i-1][j] != -1) pa[i][j] = pa[i-1][pa[i-1][j]]; update(1); while(m--) { ll t, nd; scanf("%lld %lld", &t, &nd); if(t == 1) update(nd); else printf("%lld\n", query(nd)); } return 0; }
17.558442
99
0.404956
Shefin-CSE16
66e0f863acb0141a66c782bd5ef9047cf5fc03ad
10,265
cpp
C++
Flow3D/Flow3D/src/Flow3D/Components/ComponentManager.cpp
florianvoelkers/Flow3D
017d2f321f943dfecc360bec9fc6f17c77ffde68
[ "MIT" ]
2
2020-05-09T10:06:00.000Z
2021-03-10T00:10:41.000Z
Flow3D/Flow3D/src/Flow3D/Components/ComponentManager.cpp
florianvoelkers/Flow3D
017d2f321f943dfecc360bec9fc6f17c77ffde68
[ "MIT" ]
1
2022-03-04T09:17:15.000Z
2022-03-04T09:17:15.000Z
Flow3D/Flow3D/src/Flow3D/Components/ComponentManager.cpp
florianvoelkers/Flow3D
017d2f321f943dfecc360bec9fc6f17c77ffde68
[ "MIT" ]
2
2020-02-17T00:43:03.000Z
2020-11-26T11:55:19.000Z
#include "ComponentManager.hpp" const std::size_t Component::Type = std::hash<std::string>()(TO_STRING(Component)); // All class definitions for components // CLASS_DEFINITION(parent class, sub class) CLASS_DEFINITION(Component, Rotatable) CLASS_DEFINITION(Component, FreeCamera) CLASS_DEFINITION(Component, Renderable) CLASS_DEFINITION(Component, BaseLight) CLASS_DEFINITION(BaseLight, DirectionalLight) CLASS_DEFINITION(BaseLight, PointLight) CLASS_DEFINITION(BaseLight, SpotLight) CLASS_DEFINITION(Component, ComponentToggler) CLASS_DEFINITION(Component, GameObjectToggler) #include "Flow3D/ImGui/ImGuiFreeCameraEditor.hpp" #include "Flow3D/ImGui/ImGuiGameObjectTogglerEditor.hpp" #include "Flow3D/ImGui/ImGuiComponentTogglerEditor.hpp" #include "Flow3D/ImGui/ImGuiDirectionalLightEditor.hpp" #include "Flow3D/ImGui/ImGuiPointLightEditor.hpp" #include "Flow3D/ImGui/ImGuiSpotLightEditor.hpp" #include "Flow3D/ImGui/ImGuiRenderableEditor.hpp" #include "Flow3D/Serializer.hpp" #include <io.h> // For access(). #include <sys/types.h> // For stat(). #include <sys/stat.h> // For stat(). #include <filesystem> std::string ComponentManager::ChooseComponentPopup(std::string componentName) { if (componentName == "Rotatable") { return "Rotatable"; } else if (componentName == "FreeCamera") { return "FreeCamera"; } else if (componentName == "Renderable") { return "Renderable"; } else if (componentName == "DirectionalLight") { return "DirectionalLight"; } else if (componentName == "PointLight") { return "PointLight"; } else if (componentName == "SpotLight") { return "SpotLight"; } else if (componentName == "ComponentToggler") { return "ComponentToggler"; } else if (componentName == "GameObjectToggler") { return "GameObjectToggler"; } } void ComponentManager::DuplicateComponent(Component& component, GameObject& gameObject) { std::string componentName = component.GetName(); if (componentName == "FreeCamera") { FLOW_CORE_WARN("a camera component should not be copied"); } else if (componentName == "GameObjectToggler") { gameObject.AddComponent<GameObjectToggler>(&gameObject, component.GetEnabled()); GameObjectToggler& goToggler = *dynamic_cast<GameObjectToggler*>(&component); std::vector<std::tuple<GameObject*, std::string, Keycode>>& gameObjectsToToggle = goToggler.GetGameObjectsToToggle(); GameObjectToggler& togglerOfNewGameObject = gameObject.GetComponent<GameObjectToggler>(); for (unsigned int i = 0; i < gameObjectsToToggle.size(); i++) { togglerOfNewGameObject.AddGameObjectToToggle(std::make_tuple(std::get<0>(gameObjectsToToggle[i]), std::get<1>(gameObjectsToToggle[i]), std::get<2>(gameObjectsToToggle[i])), false); } } else if (componentName == "ComponentToggler") { gameObject.AddComponent<ComponentToggler>(&gameObject, component.GetEnabled()); ComponentToggler& toggler = *dynamic_cast<ComponentToggler*>(&component); std::vector<std::tuple<Component*, Keycode>>& componentsToToggle = toggler.GetComponentsToToggle(); ComponentToggler& togglerOfNewGameObject = gameObject.GetComponent<ComponentToggler>(); for (unsigned int i = 0; i < componentsToToggle.size(); i++) { togglerOfNewGameObject.AddComponentToToggle(std::make_tuple(std::get<0>(componentsToToggle[i]), std::get<1>(componentsToToggle[i])), false); } } else if (componentName == "DirectionalLight") { FLOW_CORE_WARN("a directional light component should not be copied"); } else if (componentName == "PointLight") { PointLight& pointLight = *dynamic_cast<PointLight*>(&component); gameObject.AddComponent<PointLight>(&gameObject, pointLight.GetAmbientIntensity(), pointLight.GetDiffuseIntensity(), pointLight.GetSpecularIntensity(), pointLight.GetAttenuation(), pointLight.GetEnabled()); Application::Get().GetCurrentScene().AddPointLight(&gameObject.GetComponent<PointLight>()); } else if (componentName == "SpotLight") { SpotLight& spotLight = *dynamic_cast<SpotLight*>(&component); gameObject.AddComponent<SpotLight>(&gameObject, spotLight.GetAmbientIntensity(), spotLight.GetDiffuseIntensity(), spotLight.GetSpecularIntensity(), spotLight.GetCutoff(), spotLight.GetOuterCutoff(), spotLight.GetAttenuation(), spotLight.GetEnabled()); Application::Get().GetCurrentScene().AddPointLight(&gameObject.GetComponent<PointLight>()); } else if (componentName == "Renderable") { Renderable& renderable = *dynamic_cast<Renderable*>(&component); std::string shaderName = renderable.GetShader().m_Name; Model& model = renderable.GetModel(); std::string modelFilepath = model.filepath; if (modelFilepath.empty()) { if (model.GetCube() != nullptr) { Cube& cube = *model.GetCube(); if (cube.GetIsTextured()) { Texture& diffuseTexture = cube.GetDiffuseTexture(); std::string diffusePath = diffuseTexture.path; Texture& specularTexture = cube.GetSpecularTexture(); std::string specularPath = specularTexture.path; gameObject.AddComponent<Renderable>(&gameObject, std::make_shared<Model>(std::make_shared<Cube>(ResourceManager::Get().FindTexture(diffusePath), ResourceManager::Get().FindTexture(specularPath))), ResourceManager::Get().FindShader(shaderName), renderable.GetBlending(), renderable.GetEnabled()); } else { gameObject.AddComponent<Renderable>(&gameObject, std::make_shared<Model>(std::make_shared<Cube>(cube.GetColor())), ResourceManager::Get().FindShader(shaderName), renderable.GetBlending(), renderable.GetEnabled()); } } else if (model.GetPlane() != nullptr) { Plane& plane = *model.GetPlane(); if (plane.GetIsTextured()) { Texture& diffuseTexture = plane.GetDiffuseTexture(); std::string diffusePath = diffuseTexture.path; Texture& specularTexture = plane.GetSpecularTexture(); std::string specularPath = specularTexture.path; gameObject.AddComponent<Renderable>(&gameObject, std::make_shared<Model>(std::make_shared<Plane>(ResourceManager::Get().FindTexture(diffusePath), ResourceManager::Get().FindTexture(specularPath))), ResourceManager::Get().FindShader(shaderName), renderable.GetBlending(), renderable.GetEnabled()); } else { gameObject.AddComponent<Renderable>(&gameObject, std::make_shared<Model>(std::make_shared<Plane>(plane.GetColor())), ResourceManager::Get().FindShader(shaderName), renderable.GetBlending(), renderable.GetEnabled()); } } } else { gameObject.AddComponent<Renderable>(&gameObject, ResourceManager::Get().FindModel(modelFilepath), ResourceManager::Get().FindShader(shaderName), renderable.GetBlending(), renderable.GetEnabled()); } } } void ComponentManager::ShowComponentEditor(std::string componentName, std::vector<std::string> componentNames, Component* component, const std::vector<std::shared_ptr<Component>>& components) { if (componentName == "FreeCamera") { FreeCameraEditor editor = FreeCameraEditor(); editor.Draw(dynamic_cast<FreeCamera*>(component)); } else if (componentName == "GameObjectToggler") { GameObjectTogglerEditor editor = GameObjectTogglerEditor(); editor.Draw(dynamic_cast<GameObjectToggler*>(component)); } else if (componentName == "ComponentToggler") { ComponentTogglerEditor editor = ComponentTogglerEditor(); editor.Draw(dynamic_cast<ComponentToggler*>(component), components, componentNames); } else if (componentName == "DirectionalLight") { DirectionalLightEditor editor = DirectionalLightEditor(); editor.Draw(dynamic_cast<DirectionalLight*>(component)); } else if (componentName == "PointLight") { PointLightEditor editor = PointLightEditor(); editor.Draw(dynamic_cast<PointLight*>(component)); } else if (componentName == "SpotLight") { SpotLightEditor editor = SpotLightEditor(); editor.Draw(dynamic_cast<SpotLight*>(component)); } else if (componentName == "Renderable") { RenderableEditor editor = RenderableEditor(); editor.Draw(dynamic_cast<Renderable*>(component)); } } void ComponentManager::SerializeComponent(const std::string& componentName, std::ofstream& myfile, Component* component, const std::string& componentDirectory) { if (componentName == "Rotatable") { Serializer::SerializeRotatable(myfile, component); } else if (componentName == "FreeCamera") { Serializer::SerializeFreeCamera(myfile, component); } else if (componentName == "GameObjectToggler") { Serializer::SerializeGameObjectToggler(myfile, component); } else if (componentName == "ComponentToggler") { Serializer::SerializeComponentToggler(myfile, component); } else if (componentName == "DirectionalLight") { Serializer::SerializeDirectionalLight(myfile, component); } else if (componentName == "PointLight") { Serializer::SerializePointLight(myfile, component); } else if (componentName == "SpotLight") { Serializer::SerializeSpotLight(myfile, component); } else if (componentName == "Renderable") { Serializer::SerializeRenderable(myfile, component, componentDirectory); } } void ComponentManager::DeserializeComponent(const std::string& componentName, json & json, GameObject & gameObject, Scene & scene, const std::string & componentsDirectory, std::vector<std::shared_ptr<GameObject>>& gameObjectsWithGameObjectToggler) { if (componentName == "Rotatable") { Serializer::DeserializeRotatable(json, gameObject, scene); } else if (componentName == "FreeCamera") { Serializer::DeserializeFreeCamera(json, gameObject, scene); } else if (componentName == "GameObjectToggler") { Serializer::DeserializeGameObjectToggler(json, gameObject, scene, gameObjectsWithGameObjectToggler); } else if (componentName == "ComponentToggler") { Serializer::DeserializeComponentToggler(json, gameObject, scene); } else if (componentName == "DirectionalLight") { Serializer::DeserializeDirectionalLight(json, gameObject, scene); } else if (componentName == "PointLight") { Serializer::DeserializePointLight(json, gameObject, scene); } else if (componentName == "SpotLight") { Serializer::DeserializeSpotLight(json, gameObject, scene); } else if (componentName == "Renderable") { Serializer::DeserializeRenderable(json, gameObject, scene, componentsDirectory); } }
35.642361
247
0.746322
florianvoelkers
66e0fff5a52a9989a2f801c9d318e01be21aa13e
804
cpp
C++
Source/examples/inherits-via-dominance.cpp
nojhan/leathers
d8a2867a477baab515affdf320d872896e01a797
[ "BSD-2-Clause" ]
86
2015-05-11T22:47:52.000Z
2021-09-05T11:26:05.000Z
Source/examples/inherits-via-dominance.cpp
nojhan/leathers
d8a2867a477baab515affdf320d872896e01a797
[ "BSD-2-Clause" ]
6
2015-07-03T12:34:26.000Z
2020-03-08T09:01:51.000Z
Source/examples/inherits-via-dominance.cpp
nojhan/leathers
d8a2867a477baab515affdf320d872896e01a797
[ "BSD-2-Clause" ]
12
2015-09-01T11:36:37.000Z
2021-12-01T12:56:44.000Z
// Copyright (c) 2014, Ruslan Baratov // All rights reserved. #include <leathers/push> #include <leathers/object-layout-change> #include <leathers/c++98-compat> #include <leathers/weak-vtables> #include <leathers/padded> class Foo { public: virtual void foo() { } virtual ~Foo() { } }; class Boo : virtual public Foo { public: virtual void foo() override { } virtual ~Boo() override { } }; #include <leathers/pop> #include <leathers/push> #include <leathers/object-layout-change> #include <leathers/padded> #include <leathers/c++98-compat> #if !defined(SHOW_WARNINGS) # include <leathers/inherits-via-dominance> #endif class Baz : public Boo, virtual public Foo { virtual ~Baz() override { } }; #include <leathers/pop> int main() { }
18.697674
45
0.656716
nojhan
66e10c3dc38d490ec22dc8dc847583b3fa75b4cf
1,002
cpp
C++
124-binary-tree-maximum-path-sum.cpp
ranveeraggarwal/leetcode-cpp
931dd37c00076ee8e49d2ba3dbafbe0113e35376
[ "MIT" ]
null
null
null
124-binary-tree-maximum-path-sum.cpp
ranveeraggarwal/leetcode-cpp
931dd37c00076ee8e49d2ba3dbafbe0113e35376
[ "MIT" ]
null
null
null
124-binary-tree-maximum-path-sum.cpp
ranveeraggarwal/leetcode-cpp
931dd37c00076ee8e49d2ba3dbafbe0113e35376
[ "MIT" ]
null
null
null
#include "stdafx.h" struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) {} }; class Solution { int vmax; public: int maxPathSum(TreeNode *root) { vmax = INT_MIN; subPath(root); return vmax; } int subPath(TreeNode *root) { if (root == NULL) return 0; int val = root->val; int left = subPath(root->left); int right = subPath(root->right); if (left >= 0 && right >= 0) { vmax = max(vmax, left + right + val); return max(left, right) + val; } else if (left >= 0) { vmax = max(vmax, left + val); return left + val; } else if (right >= 0) { vmax = max(vmax, right + val); return right + val; } else { vmax = max(vmax, val); return val; } } };
19.647059
56
0.443114
ranveeraggarwal
66e1487c1be38e495aba27dd6bbd667362f44c3d
2,920
cpp
C++
testing/core/DummyDVHGenerator.cpp
MIC-DKFZ/RTTB
8b772501fd3fffcb67233a9307661b03dff72785
[ "BSD-3-Clause" ]
18
2018-04-19T12:57:32.000Z
2022-03-12T17:43:02.000Z
testing/core/DummyDVHGenerator.cpp
MIC-DKFZ/RTTB
8b772501fd3fffcb67233a9307661b03dff72785
[ "BSD-3-Clause" ]
null
null
null
testing/core/DummyDVHGenerator.cpp
MIC-DKFZ/RTTB
8b772501fd3fffcb67233a9307661b03dff72785
[ "BSD-3-Clause" ]
7
2018-06-24T21:09:56.000Z
2021-09-09T09:30:49.000Z
// ----------------------------------------------------------------------- // RTToolbox - DKFZ radiotherapy quantitative evaluation library // // Copyright (c) German Cancer Research Center (DKFZ), // Software development for Integrated Diagnostics and Therapy (SIDT). // ALL RIGHTS RESERVED. // See rttbCopyright.txt or // http://www.dkfz.de/en/sidt/projects/rttb/copyright.html // // This software is distributed WITHOUT ANY WARRANTY; without even // the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR // PURPOSE. See the above copyright notices for more information. // //------------------------------------------------------------------------ #include <time.h> #include "DummyDVHGenerator.h" namespace rttb { namespace testing { DummyDVHGenerator::DummyDVHGenerator(): _binSize(DoseTypeGy(0.1)), _voxelVolume(8), _value(0) { /* initialize random seed: */ srand(static_cast<unsigned int>(time(nullptr))); }; core::DVH DummyDVHGenerator::generateDVH(IDType structureID, IDType doseID) { core::DVH::DataDifferentialType aDataDifferential; for (int i = 0; i < 100; i++) { _value = DoseCalcType((double(rand()) / RAND_MAX) * 1000); //cut off values to avoid problems on comparisson with reimported values after //writing to file. _value = floor(_value * 1000000) / 1000000; aDataDifferential.push_back(_value); } return core::DVH(aDataDifferential, _binSize, _voxelVolume, structureID, doseID); } core::DVH DummyDVHGenerator::generateDVH(IDType structureID, IDType doseID, DoseCalcType value) { _value = value; core::DVH::DataDifferentialType aDataDifferential; for (int i = 0; i < 100; i++) { aDataDifferential.push_back(_value); } return core::DVH(aDataDifferential, _binSize, _voxelVolume, structureID, doseID); } core::DVH DummyDVHGenerator::generateDVH(IDType structureID, IDType doseID, DoseCalcType minValue, DoseCalcType maxValue) { _voxelVolume = 0.2 * 0.2 * 0.4; bool decrease = false; core::DVH::DataDifferentialType aDataDifferential; for (int i = 0; i <= 200; i++) { if ((i > 20) && (i < 180)) { if ((_value == 0) && (!decrease)) { _value = DoseCalcType((double(rand()) / RAND_MAX) * 10) + minValue; } else if (!decrease) { _value = _value + DoseCalcType((double(rand()) / RAND_MAX) * (maxValue / 10)); } if ((_value > maxValue) || (decrease)) { decrease = true; _value = _value - DoseCalcType((double(rand()) / RAND_MAX) * (maxValue / 3)); } if (_value < 0) { _value = 0; } } else { _value = 0; } aDataDifferential.push_back(_value); } return core::DVH(aDataDifferential, _binSize, _voxelVolume, structureID, doseID); } } }
28.076923
101
0.602397
MIC-DKFZ
66e339a8b297eabe2930cac3eee58b644211b23d
2,693
cpp
C++
tokens.cpp
jimfinnis/monitor
b27f6543eb466232da282a5d2c251b4dc91d2a9a
[ "MIT" ]
null
null
null
tokens.cpp
jimfinnis/monitor
b27f6543eb466232da282a5d2c251b4dc91d2a9a
[ "MIT" ]
null
null
null
tokens.cpp
jimfinnis/monitor
b27f6543eb466232da282a5d2c251b4dc91d2a9a
[ "MIT" ]
null
null
null
// Token table - generated by gentoks.py from tokens #include "tokens.h" TokenRegistry tokens[] = { {"*e", T_END}, {"*s", T_STRING}, {"*i", T_IDENT}, {"*n", T_INT}, {"*f", T_FLOAT}, {"*c{", T_OCURLY}, {"*c}", T_CCURLY}, {"*c(", T_OPREN}, {"*c)", T_CPREN}, {"*c,", T_COMMA}, {"*c<", T_LT}, {"audio", T_AUDIO}, {"sample", T_SAMPLE}, {"speech", T_SPEECH}, {"false", T_FALSE}, {"true", T_TRUE}, {"bool", T_BOOL}, {"integer", T_INTEGER}, {"else", T_ELSE}, {"var", T_VAR}, {"expr", T_EXPR}, {"window", T_WINDOW}, {"frame", T_FRAME}, {"linked", T_LINKED}, {"float", T_NAMEFLOAT}, {"pos", T_POS}, {"centred", T_CENTRED}, {"centered", T_CENTERED}, {"min", T_MIN}, {"max", T_MAX}, {"inverse", T_INVERSE}, {"gauge", T_GAUGE}, {"levels", T_LEVELS}, {"number", T_NUMBER}, {"graph", T_GRAPH}, {"compass", T_COMPASS}, {"status", T_STATUS}, {"map", T_MAP}, {"switch", T_SWITCH}, {"title", T_TITLE}, {"subtitle", T_SUBTITLE}, {"range", T_RANGE}, {"out", T_OUT}, {"bands", T_BANDS}, {"previous", T_PREVIOUS}, {"auto", T_AUTO}, {"to", T_TO}, {"col", T_COL}, {"color", T_COLOR}, {"colour", T_COLOUR}, {"colours", T_COLOURS}, {"updateinterval", T_UPDATEINTERVAL}, {"on", T_ON}, {"point", T_POINT}, {"location", T_LOCATION}, {"saturation", T_SATURATION}, {"hue", T_HUE}, {"value", T_VALUE}, {"size", T_SIZE}, {"sizerange", T_SIZERANGE}, {"trail", T_TRAIL}, {"trailevery", T_TRAILEVERY}, {"time", T_TIME}, {"width", T_WIDTH}, {"height", T_HEIGHT}, {"floatrange", T_FLOATRANGE}, {"when", T_WHEN}, {"default", T_DEFAULT}, {"darken", T_DARKEN}, {"button", T_BUTTON}, {"radians", T_RADIANS}, {"degrees", T_DEGREES}, {"length", T_LENGTH}, {"widthrange", T_WIDTHRANGE}, {"lengthrange", T_LENGTHRANGE}, {"vector", T_VECTOR}, {"fontscale", T_FONTSCALE}, {"port", T_PORT}, {"sendport", T_SENDPORT}, {"sendaddr", T_SENDADDR}, {"label", T_LABEL}, {"start", T_START}, {"end", T_END_WD}, {"clip", T_CLIP}, {"immediate", T_IMMEDIATE}, {"key", T_KEY}, {"always", T_ALWAYS}, {"sendinterval", T_SENDINTERVAL}, {"validtime", T_VALIDTIME}, {"momentary", T_MOMENTARY}, {"slider", T_SLIDER}, {"borderless", T_BORDERLESS}, {"spacing", T_SPACING}, {"horizontal", T_HORIZONTAL}, {"vertical", T_VERTICAL}, {"fullscreen", T_FULLSCREEN}, {"screen", T_SCREEN}, {"set", T_SET}, {"epsilon", T_EPSILON}, {"initial", T_INITIAL}, {"nudge", T_NUDGE}, {"up", T_UP}, {"down", T_DOWN}, {"centre", T_CENTRE}, {"line", T_LINE}, {"arrow", T_ARROW}, {"angle", T_ANGLE}, {"special", T_SPECIAL}, {"waypoint", T_WAYPOINT}, {"image", T_IMAGE}, {"alpha", T_ALPHA}, {"disable", T_DISABLE}, {"diamond", T_DIAMOND}, {"topic", T_TOPIC}, {NULL,-10} };
22.256198
52
0.599332
jimfinnis
66e5ae79de507bf66c463efc29d068ef402f48be
2,780
cpp
C++
src/structures/affectation.cpp
Ezibenroc/satsolver
5f58b8f9502090f05cbc2351304a289530b74f63
[ "MIT" ]
1
2017-11-29T00:46:23.000Z
2017-11-29T00:46:23.000Z
src/structures/affectation.cpp
Ezibenroc/satsolver
5f58b8f9502090f05cbc2351304a289530b74f63
[ "MIT" ]
null
null
null
src/structures/affectation.cpp
Ezibenroc/satsolver
5f58b8f9502090f05cbc2351304a289530b74f63
[ "MIT" ]
null
null
null
#include <cstdlib> #include <cassert> #include <sstream> #include <iostream> #include "affectation.h" #define abs(x) ((static_cast<unsigned int>(x > 0 ? x : -x))) using namespace satsolver; Affectation::Affectation(int nb_var) : aff(std::vector<int>()), nb_aff(0), nb_unknown(nb_var) { for(int i = 0 ; i < nb_var ; i++) this->aff.push_back(0) ; } Affectation::Affectation(Affectation *a) : aff(std::vector<int>(a->aff)), nb_aff(a->nb_aff), nb_unknown(a->nb_unknown) { } bool Affectation::is_true(int x) const { assert(abs(x) <= this->aff.size() && x!=0) ; if(x>0) return this->aff[x-1] == TR ; else return this->is_false(-x); } bool Affectation::is_false(int x) const { assert(abs(x) <= this->aff.size() && x!=0) ; if(x>0) return this->aff[x-1] == FA ; else return this->is_true(-x); } bool Affectation::is_unknown(int x) const { assert(abs(x) <= this->aff.size()); assert(x!=0) ; if (x>0) return this->aff[x-1] == UN ; else return this->is_unknown(-x); } void Affectation::set_true(int x) { if(x>0) { assert(abs(x) <= this->aff.size() && x!=0) ; assert(this->is_unknown(x)) ; if(is_unknown(x)) this->nb_unknown -- ; this->aff[x-1] = TR ; } else this->set_false(-x); } void Affectation::set_false(int x) { if(x>0) { assert(abs(x) <= this->aff.size() && x!=0) ; assert(this->is_unknown(x)) ; if(is_unknown(x)) this->nb_unknown -- ; this->aff[x-1] = FA ; } else this->set_true(-x); } void Affectation::set_unknown(int x) { if(x>0) { assert(abs(x) <= this->aff.size()); assert(x!=0) ; if(!is_unknown(x)) this->nb_unknown ++ ; this->aff[abs(x)-1] = UN ; } else this->set_unknown(-x); } std::string Affectation::to_string() const { std::ostringstream oss; oss << "{" ; for(unsigned int i = 1 ; i <= this->aff.size() ; i++) { if (i>1) oss << ", "; if(this->is_true(i)) oss << i << "=" << "true"; else if(this->is_false(i)) oss << i << "=" << "false"; else oss << i << "=" << "unknown"; } oss << "}" ; return oss.str() ; } std::set<int>* Affectation::to_set() const { std::set<int> *set = new std::set<int>(); for(unsigned int i = 1 ; i <= this->aff.size() ; i++) { if(this->is_true(i)) set->insert(i); else if(this->is_false(i)) set->insert(-i); } return set; } int Affectation::get_nb_unknown() { return this->nb_unknown ; } unsigned Affectation::get_nb_var() const{ return static_cast<int> (this->aff.size()) ; }
24.821429
120
0.520144
Ezibenroc
66e60135760bd68c72c1d03cc9b0b65e020f6ed1
2,703
cpp
C++
ViroRenderer/VROPoseFilterLowPass.cpp
dthian/virocore
c702528e0e3ffd8324c1597d65a73bc6adf0e11d
[ "MIT" ]
2
2019-10-16T14:30:06.000Z
2019-10-30T23:14:30.000Z
ViroRenderer/VROPoseFilterLowPass.cpp
dthian/virocore
c702528e0e3ffd8324c1597d65a73bc6adf0e11d
[ "MIT" ]
47
2021-09-08T13:03:44.000Z
2022-03-10T23:21:05.000Z
ViroRenderer/VROPoseFilterLowPass.cpp
dthian/virocore
c702528e0e3ffd8324c1597d65a73bc6adf0e11d
[ "MIT" ]
2
2020-08-26T14:50:23.000Z
2021-01-04T02:21:02.000Z
// // VROPoseFilterLowPass.cpp // ViroKit // // Created by Raj Advani on 2/27/19. // Copyright © 2019 Viro Media. All rights reserved. // // 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 "VROPoseFilterLowPass.h" VROPoseFrame VROPoseFilterLowPass::temporalFilter(const std::vector<VROPoseFrame> &frames, const VROPoseFrame &combinedFrame, const VROPoseFrame &newFrame) { VROPoseFrame dampenedJoints = newPoseFrame(); for (int i = 0; i < kNumBodyJoints; i++) { VROBodyJointType type = (VROBodyJointType) i; const std::vector<VROInferredBodyJoint> &samples = combinedFrame[i]; if (samples.empty()) { continue; } float k = 2 / ((float) samples.size() + 1); VROVector3f emaYesterday = samples[0].getCenter(); float sumConfidence = samples[0].getConfidence(); // Exponentially weight towards the earliest data at the end of the array // (Items at the front of the array are older). for (int i = 1; i < samples.size(); i++) { const VROInferredBodyJoint &sample = samples[i]; VROVector3f emaToday = (sample.getCenter() * k) + (emaYesterday * (1 - k)); emaYesterday = emaToday; sumConfidence += sample.getConfidence(); } VROInferredBodyJoint dampenedJoint(type); dampenedJoint.setCenter(emaYesterday); dampenedJoint.setConfidence(sumConfidence / (float) samples.size()); dampenedJoints[i] = { dampenedJoint }; } return dampenedJoints; }
42.234375
125
0.661117
dthian
66e80b14adfe64ada87ef0a12ac183ac7975680e
1,363
cpp
C++
Util/testsuite/src/MapConfigurationTest.cpp
AppAnywhere/agent-sdk
c5495c4a1d892f2d3bca5b82a7436db7d8adff71
[ "BSL-1.0" ]
null
null
null
Util/testsuite/src/MapConfigurationTest.cpp
AppAnywhere/agent-sdk
c5495c4a1d892f2d3bca5b82a7436db7d8adff71
[ "BSL-1.0" ]
null
null
null
Util/testsuite/src/MapConfigurationTest.cpp
AppAnywhere/agent-sdk
c5495c4a1d892f2d3bca5b82a7436db7d8adff71
[ "BSL-1.0" ]
null
null
null
// // MapConfigurationTest.cpp // // $Id: //poco/1.7/Util/testsuite/src/MapConfigurationTest.cpp#1 $ // // Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH. // and Contributors. // // SPDX-License-Identifier: BSL-1.0 // #include "MapConfigurationTest.h" #include "CppUnit/TestCaller.h" #include "CppUnit/TestSuite.h" #include "Poco/Util/MapConfiguration.h" #include "Poco/AutoPtr.h" using Poco::Util::AbstractConfiguration; using Poco::Util::MapConfiguration; using Poco::AutoPtr; MapConfigurationTest::MapConfigurationTest(const std::string& name): AbstractConfigurationTest(name) { } MapConfigurationTest::~MapConfigurationTest() { } void MapConfigurationTest::testClear() { AutoPtr<MapConfiguration> pConf = new MapConfiguration; pConf->setString("foo", "bar"); assert (pConf->hasProperty("foo")); pConf->clear(); assert (!pConf->hasProperty("foo")); } AbstractConfiguration* MapConfigurationTest::allocConfiguration() const { return new MapConfiguration; } void MapConfigurationTest::setUp() { } void MapConfigurationTest::tearDown() { } CppUnit::Test* MapConfigurationTest::suite() { CppUnit::TestSuite* pSuite = new CppUnit::TestSuite("MapConfigurationTest"); AbstractConfigurationTest_addTests(pSuite, MapConfigurationTest); CppUnit_addTest(pSuite, MapConfigurationTest, testClear); return pSuite; }
18.930556
100
0.758621
AppAnywhere
66e84a1cf50265f1578c87458a7eddb20fe53d13
72,652
cpp
C++
extensions/standard-processors/tests/unit/TailFileTests.cpp
nghiaxlee/nifi-minifi-cpp
ddddb22d63c4a60b97066e555f771135c8dbb26d
[ "Apache-2.0" ]
1
2017-03-14T15:42:08.000Z
2017-03-14T15:42:08.000Z
extensions/standard-processors/tests/unit/TailFileTests.cpp
nghiaxlee/nifi-minifi-cpp
ddddb22d63c4a60b97066e555f771135c8dbb26d
[ "Apache-2.0" ]
null
null
null
extensions/standard-processors/tests/unit/TailFileTests.cpp
nghiaxlee/nifi-minifi-cpp
ddddb22d63c4a60b97066e555f771135c8dbb26d
[ "Apache-2.0" ]
1
2020-07-17T15:27:37.000Z
2020-07-17T15:27:37.000Z
/** * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <cstdio> #include <fstream> #include <map> #include <memory> #include <utility> #include <string> #include <iostream> #include <set> #include <algorithm> #include <random> #include <cstdlib> #include "FlowController.h" #include "TestBase.h" #include "core/Core.h" #include "core/FlowFile.h" #include "utils/file/FileUtils.h" #include "utils/file/PathUtils.h" #include "unit/ProvenanceTestHelper.h" #include "core/Processor.h" #include "core/ProcessContext.h" #include "core/ProcessSession.h" #include "core/ProcessorNode.h" #include "TailFile.h" #include "LogAttribute.h" static std::string NEWLINE_FILE = "" // NOLINT "one,two,three\n" "four,five,six, seven"; static const char *TMP_FILE = "minifi-tmpfile.txt"; static const char *STATE_FILE = "minifi-state-file.txt"; namespace { std::string createTempFile(const std::string &directory, const std::string &file_name, const std::string &contents, std::ios_base::openmode open_mode = std::ios::out | std::ios::binary) { std::string full_file_name = directory + utils::file::FileUtils::get_separator() + file_name; std::ofstream tmpfile{full_file_name, open_mode}; tmpfile << contents; return full_file_name; } void appendTempFile(const std::string &directory, const std::string &file_name, const std::string &contents, std::ios_base::openmode open_mode = std::ios::app | std::ios::binary) { createTempFile(directory, file_name, contents, open_mode); } void removeFile(const std::string &directory, const std::string &file_name) { std::string full_file_name = directory + utils::file::FileUtils::get_separator() + file_name; std::remove(full_file_name.c_str()); } void renameTempFile(const std::string &directory, const std::string &old_file_name, const std::string &new_file_name) { std::string old_full_file_name = directory + utils::file::FileUtils::get_separator() + old_file_name; std::string new_full_file_name = directory + utils::file::FileUtils::get_separator() + new_file_name; rename(old_full_file_name.c_str(), new_full_file_name.c_str()); } } // namespace TEST_CASE("TailFile reads the file until the first delimiter", "[simple]") { // Create and write to the test file TestController testController; LogTestController::getInstance().setTrace<minifi::processors::TailFile>(); LogTestController::getInstance().setDebug<minifi::processors::LogAttribute>(); std::shared_ptr<TestPlan> plan = testController.createPlan(); std::shared_ptr<core::Processor> tailfile = plan->addProcessor("TailFile", "tailfileProc"); auto id = tailfile->getUUIDStr(); plan->addProcessor("LogAttribute", "logattribute", core::Relationship("success", "description"), true); char format[] = "/tmp/gt.XXXXXX"; auto dir = testController.createTempDirectory(format); std::stringstream temp_file; temp_file << dir << utils::file::FileUtils::get_separator() << TMP_FILE; std::ofstream tmpfile; tmpfile.open(temp_file.str(), std::ios::out | std::ios::binary); tmpfile << NEWLINE_FILE; tmpfile.close(); std::stringstream state_file; state_file << dir << utils::file::FileUtils::get_separator() << STATE_FILE; plan->setProperty(tailfile, org::apache::nifi::minifi::processors::TailFile::FileName.getName(), temp_file.str()); plan->setProperty(tailfile, org::apache::nifi::minifi::processors::TailFile::Delimiter.getName(), "\n"); testController.runSession(plan, false); auto records = plan->getProvenanceRecords(); REQUIRE(records.size() == 5); // line 1: CREATE, MODIFY; line 2: CREATE, MODIFY, DROP testController.runSession(plan, false); REQUIRE(LogTestController::getInstance().contains("Logged 1 flow files")); REQUIRE(LogTestController::getInstance().contains("Size:" + std::to_string(NEWLINE_FILE.find_first_of('\n') + 1) + " Offset:0")); LogTestController::getInstance().reset(); } TEST_CASE("TailFile picks up the second line if a delimiter is written between runs", "[state]") { // Create and write to the test file TestController testController; LogTestController::getInstance().setTrace<minifi::processors::TailFile>(); LogTestController::getInstance().setDebug<core::ProcessSession>(); LogTestController::getInstance().setTrace<TestPlan>(); LogTestController::getInstance().setDebug<minifi::processors::LogAttribute>(); std::shared_ptr<TestPlan> plan = testController.createPlan(); std::shared_ptr<core::Processor> tailfile = plan->addProcessor("TailFile", "tailfileProc"); auto id = tailfile->getUUIDStr(); plan->addProcessor("LogAttribute", "logattribute", core::Relationship("success", "description"), true); char format[] = "/tmp/gt.XXXXXX"; auto dir = testController.createTempDirectory(format); std::stringstream temp_file; temp_file << dir << utils::file::FileUtils::get_separator() << TMP_FILE; std::ofstream tmpfile; tmpfile.open(temp_file.str(), std::ios::out | std::ios::binary); tmpfile << NEWLINE_FILE; tmpfile.close(); plan->setProperty(tailfile, org::apache::nifi::minifi::processors::TailFile::FileName.getName(), temp_file.str()); plan->setProperty(tailfile, org::apache::nifi::minifi::processors::TailFile::Delimiter.getName(), "\n"); testController.runSession(plan, true); REQUIRE(LogTestController::getInstance().contains("key:filename value:minifi-tmpfile.0-13.txt")); plan->reset(true); // start a new but with state file LogTestController::getInstance().resetStream(LogTestController::getInstance().log_output); std::ofstream appendStream; appendStream.open(temp_file.str(), std::ios_base::app | std::ios_base::binary); appendStream << std::endl; testController.runSession(plan, true); REQUIRE(LogTestController::getInstance().contains("key:filename value:minifi-tmpfile.14-34.txt")); LogTestController::getInstance().reset(); } TEST_CASE("TailFile re-reads the file if the state is deleted between runs", "[state]") { // Create and write to the test file TestController testController; LogTestController::getInstance().setTrace<minifi::processors::TailFile>(); LogTestController::getInstance().setDebug<core::ProcessSession>(); LogTestController::getInstance().setTrace<TestPlan>(); LogTestController::getInstance().setDebug<minifi::processors::LogAttribute>(); std::shared_ptr<TestPlan> plan = testController.createPlan(); std::shared_ptr<core::Processor> tailfile = plan->addProcessor("TailFile", "tailfileProc"); auto id = tailfile->getUUIDStr(); plan->addProcessor("LogAttribute", "logattribute", core::Relationship("success", "description"), true); char format[] = "/tmp/gt.XXXXXX"; auto dir = testController.createTempDirectory(format); std::stringstream temp_file; temp_file << dir << utils::file::FileUtils::get_separator() << TMP_FILE; std::ofstream tmpfile; tmpfile.open(temp_file.str(), std::ios::out | std::ios::binary); tmpfile << NEWLINE_FILE; tmpfile.close(); plan->setProperty(tailfile, org::apache::nifi::minifi::processors::TailFile::FileName.getName(), temp_file.str()); plan->setProperty(tailfile, org::apache::nifi::minifi::processors::TailFile::Delimiter.getName(), "\n"); testController.runSession(plan, true); REQUIRE(LogTestController::getInstance().contains("key:filename value:minifi-tmpfile.0-13.txt")); plan->reset(true); // start a new but with state file LogTestController::getInstance().resetStream(LogTestController::getInstance().log_output); plan->getStateManagerProvider()->getCoreComponentStateManager(*tailfile)->clear(); testController.runSession(plan, true); // if we lose state we restart REQUIRE(LogTestController::getInstance().contains("key:filename value:minifi-tmpfile.0-13.txt")); } TEST_CASE("TailFile picks up the state correctly if it is rewritten between runs", "[state]") { // Create and write to the test file TestController testController; LogTestController::getInstance().setTrace<minifi::processors::TailFile>(); LogTestController::getInstance().setDebug<core::ProcessSession>(); LogTestController::getInstance().setTrace<TestPlan>(); LogTestController::getInstance().setDebug<minifi::processors::LogAttribute>(); std::shared_ptr<TestPlan> plan = testController.createPlan(); std::shared_ptr<core::Processor> tailfile = plan->addProcessor("TailFile", "tailfileProc"); auto id = tailfile->getUUIDStr(); plan->addProcessor("LogAttribute", "logattribute", core::Relationship("success", "description"), true); char format[] = "/tmp/gt.XXXXXX"; auto dir = testController.createTempDirectory(format); std::stringstream temp_file; temp_file << dir << utils::file::FileUtils::get_separator() << TMP_FILE; std::ofstream tmpfile; tmpfile.open(temp_file.str(), std::ios::out | std::ios::binary); tmpfile << NEWLINE_FILE; tmpfile.close(); std::ofstream appendStream; appendStream.open(temp_file.str(), std::ios_base::app | std::ios_base::binary); appendStream.write("\n", 1); appendStream.close(); plan->setProperty(tailfile, org::apache::nifi::minifi::processors::TailFile::FileName.getName(), temp_file.str()); plan->setProperty(tailfile, org::apache::nifi::minifi::processors::TailFile::Delimiter.getName(), "\n"); testController.runSession(plan, true); REQUIRE(LogTestController::getInstance().contains("key:filename value:minifi-tmpfile.0-13.txt")); std::string filePath, fileName; REQUIRE(utils::file::PathUtils::getFileNameAndPath(temp_file.str(), filePath, fileName)); // should stay the same for (int i = 0; i < 5; i++) { plan->reset(true); // start a new but with state file LogTestController::getInstance().resetStream(LogTestController::getInstance().log_output); plan->getStateManagerProvider()->getCoreComponentStateManager(*tailfile)->set({{"file.0.name", fileName}, {"file.0.position", "14"}, {"file.0.current", temp_file.str()}}); testController.runSession(plan, true); // if we lose state we restart REQUIRE(LogTestController::getInstance().contains("key:filename value:minifi-tmpfile.14-34.txt")); } for (int i = 14; i < 34; i++) { plan->reset(true); // start a new but with state file plan->getStateManagerProvider()->getCoreComponentStateManager(*tailfile)->set({{"file.0.name", fileName}, {"file.0.position", std::to_string(i)}, {"file.0.current", temp_file.str()}}); testController.runSession(plan, true); } plan->runCurrentProcessor(); for (int i = 14; i < 34; i++) { REQUIRE(LogTestController::getInstance().contains("key:filename value:minifi-tmpfile." + std::to_string(i) + "-34.txt")); } } TEST_CASE("TailFile converts the old-style state file to the new-style state", "[state][migration]") { // Create and write to the test file TestController testController; LogTestController::getInstance().setTrace<minifi::processors::TailFile>(); LogTestController::getInstance().setDebug<core::ProcessSession>(); LogTestController::getInstance().setTrace<TestPlan>(); LogTestController::getInstance().setDebug<minifi::processors::LogAttribute>(); auto plan = testController.createPlan(); auto tailfile = plan->addProcessor("TailFile", "tailfileProc"); auto id = tailfile->getUUIDStr(); auto logattribute = plan->addProcessor("LogAttribute", "logattribute", core::Relationship("success", "description"), true); plan->setProperty(logattribute, org::apache::nifi::minifi::processors::LogAttribute::FlowFilesToLog.getName(), "0"); char format[] = "/tmp/gt.XXXXXX"; auto dir = testController.createTempDirectory(format); std::stringstream state_file; state_file << dir << utils::file::FileUtils::get_separator() << STATE_FILE; auto statefile = state_file.str() + "." + id; SECTION("single") { const std::string temp_file = createTempFile(dir, TMP_FILE, NEWLINE_FILE + '\n'); plan->setProperty(tailfile, org::apache::nifi::minifi::processors::TailFile::FileName.getName(), temp_file); plan->setProperty(tailfile, org::apache::nifi::minifi::processors::TailFile::StateFile.getName(), state_file.str()); plan->setProperty(tailfile, org::apache::nifi::minifi::processors::TailFile::Delimiter.getName(), "\n"); std::ofstream newstatefile; newstatefile.open(statefile); SECTION("legacy") { newstatefile << "FILENAME=" << temp_file << std::endl; newstatefile << "POSITION=14" << std::endl; } SECTION("newer single") { newstatefile << "FILENAME=" << TMP_FILE << std::endl; newstatefile << "POSITION." << TMP_FILE << "=14" << std::endl; newstatefile << "CURRENT." << TMP_FILE << "=" << temp_file << std::endl; } newstatefile.close(); testController.runSession(plan, true); REQUIRE(LogTestController::getInstance().contains("key:filename value:minifi-tmpfile.14-34.txt")); std::unordered_map<std::string, std::string> state; REQUIRE(plan->getStateManagerProvider()->getCoreComponentStateManager(*tailfile)->get(state)); std::string filePath, fileName; REQUIRE(utils::file::PathUtils::getFileNameAndPath(temp_file, filePath, fileName)); std::unordered_map<std::string, std::string> expected_state{{"file.0.name", fileName}, {"file.0.position", "35"}, {"file.0.current", temp_file}, {"file.0.checksum", "1404369522"}}; for (const auto& key_value_pair : expected_state) { const auto it = state.find(key_value_pair.first); REQUIRE(it != state.end()); REQUIRE(it->second == key_value_pair.second); } REQUIRE(state.find("file.0.last_read_time") != state.end()); } SECTION("multiple") { const std::string file_name_1 = "bar.txt"; const std::string file_name_2 = "foo.txt"; const std::string temp_file_1 = createTempFile(dir, file_name_1, NEWLINE_FILE + '\n'); const std::string temp_file_2 = createTempFile(dir, file_name_2, NEWLINE_FILE + '\n'); plan->setProperty(tailfile, org::apache::nifi::minifi::processors::TailFile::TailMode.getName(), "Multiple file"); plan->setProperty(tailfile, org::apache::nifi::minifi::processors::TailFile::BaseDirectory.getName(), dir); plan->setProperty(tailfile, org::apache::nifi::minifi::processors::TailFile::LookupFrequency.getName(), "0 sec"); plan->setProperty(tailfile, org::apache::nifi::minifi::processors::TailFile::FileName.getName(), ".*\\.txt"); plan->setProperty(tailfile, org::apache::nifi::minifi::processors::TailFile::StateFile.getName(), state_file.str()); plan->setProperty(tailfile, org::apache::nifi::minifi::processors::TailFile::Delimiter.getName(), "\n"); std::ofstream newstatefile; newstatefile.open(statefile); newstatefile << "FILENAME=" << file_name_1 << std::endl; newstatefile << "POSITION." << file_name_1 << "=14" << std::endl; newstatefile << "CURRENT." << file_name_1 << "=" << temp_file_1 << std::endl; newstatefile << "FILENAME=" << file_name_2 << std::endl; newstatefile << "POSITION." << file_name_2 << "=15" << std::endl; newstatefile << "CURRENT." << file_name_2 << "=" << temp_file_2 << std::endl; newstatefile.close(); testController.runSession(plan, true); REQUIRE(LogTestController::getInstance().contains(file_name_1.substr(0, file_name_1.rfind('.')) + ".14-34.txt")); REQUIRE(LogTestController::getInstance().contains(file_name_2.substr(0, file_name_2.rfind('.')) + ".15-34.txt")); std::unordered_map<std::string, std::string> state; REQUIRE(plan->getStateManagerProvider()->getCoreComponentStateManager(*tailfile)->get(state)); std::string filePath1, filePath2, fileName1, fileName2; REQUIRE(utils::file::PathUtils::getFileNameAndPath(temp_file_1, filePath1, fileName1)); REQUIRE(utils::file::PathUtils::getFileNameAndPath(temp_file_2, filePath2, fileName2)); std::unordered_map<std::string, std::string> expected_state{{"file.0.name", fileName1}, {"file.0.position", "35"}, {"file.0.current", temp_file_1}, {"file.0.checksum", "1404369522"}, {"file.1.name", fileName2}, {"file.1.position", "35"}, {"file.1.current", temp_file_2}, {"file.1.checksum", "2289158555"}}; for (const auto& key_value_pair : expected_state) { const auto it = state.find(key_value_pair.first); REQUIRE(it != state.end()); REQUIRE(it->second == key_value_pair.second); } REQUIRE(state.find("file.0.last_read_time") != state.end()); REQUIRE(state.find("file.1.last_read_time") != state.end()); } } TEST_CASE("TailFile picks up the new File to Tail if it is changed between runs", "[state]") { TestController testController; LogTestController::getInstance().setDebug<minifi::processors::TailFile>(); LogTestController::getInstance().setDebug<minifi::processors::LogAttribute>(); std::shared_ptr<TestPlan> plan = testController.createPlan(); std::shared_ptr<core::Processor> tail_file = plan->addProcessor("TailFile", "tail_file"); plan->setProperty(tail_file, org::apache::nifi::minifi::processors::TailFile::Delimiter.getName(), "\n"); std::shared_ptr<core::Processor> log_attribute = plan->addProcessor("LogAttribute", "log_attribute", core::Relationship("success", "description"), true); plan->setProperty(log_attribute, org::apache::nifi::minifi::processors::LogAttribute::FlowFilesToLog.getName(), "0"); char format[] = "/tmp/gt.XXXXXX"; std::string directory = testController.createTempDirectory(format); std::string first_test_file = createTempFile(directory, "first.log", "my first log line\n"); plan->setProperty(tail_file, org::apache::nifi::minifi::processors::TailFile::FileName.getName(), first_test_file); testController.runSession(plan, true); REQUIRE(LogTestController::getInstance().contains("Logged 1 flow file")); REQUIRE(LogTestController::getInstance().contains("key:filename value:first.0-17.log")); SECTION("The new file gets picked up") { std::string second_test_file = createTempFile(directory, "second.log", "my second log line\n"); plan->setProperty(tail_file, org::apache::nifi::minifi::processors::TailFile::FileName.getName(), second_test_file); plan->reset(true); // clear the memory, but keep the state file LogTestController::getInstance().resetStream(LogTestController::getInstance().log_output); testController.runSession(plan, true); REQUIRE(LogTestController::getInstance().contains("Logged 1 flow file")); REQUIRE(LogTestController::getInstance().contains("key:filename value:second.0-18.log")); } SECTION("The old file will no longer be tailed") { appendTempFile(directory, "first.log", "add some more stuff\n"); std::string second_test_file = createTempFile(directory, "second.log", ""); plan->setProperty(tail_file, org::apache::nifi::minifi::processors::TailFile::FileName.getName(), second_test_file); plan->reset(true); // clear the memory, but keep the state file LogTestController::getInstance().resetStream(LogTestController::getInstance().log_output); testController.runSession(plan, true); REQUIRE(LogTestController::getInstance().contains("Logged 0 flow files")); } } TEST_CASE("TailFile picks up the new File to Tail if it is changed between runs (multiple file mode)", "[state][multiple_file]") { TestController testController; LogTestController::getInstance().setDebug<minifi::processors::TailFile>(); LogTestController::getInstance().setDebug<minifi::processors::LogAttribute>(); char format[] = "/tmp/gt.XXXXXX"; std::string directory = testController.createTempDirectory(format); std::shared_ptr<TestPlan> plan = testController.createPlan(); std::shared_ptr<core::Processor> tail_file = plan->addProcessor("TailFile", "tail_file"); plan->setProperty(tail_file, org::apache::nifi::minifi::processors::TailFile::Delimiter.getName(), "\n"); plan->setProperty(tail_file, org::apache::nifi::minifi::processors::TailFile::TailMode.getName(), "Multiple file"); plan->setProperty(tail_file, org::apache::nifi::minifi::processors::TailFile::BaseDirectory.getName(), directory); plan->setProperty(tail_file, org::apache::nifi::minifi::processors::TailFile::LookupFrequency.getName(), "0 sec"); plan->setProperty(tail_file, org::apache::nifi::minifi::processors::TailFile::FileName.getName(), "first\\..*\\.log"); std::shared_ptr<core::Processor> log_attribute = plan->addProcessor("LogAttribute", "log_attribute", core::Relationship("success", "description"), true); plan->setProperty(log_attribute, org::apache::nifi::minifi::processors::LogAttribute::FlowFilesToLog.getName(), "0"); createTempFile(directory, "first.fruit.log", "apple\n"); createTempFile(directory, "second.fruit.log", "orange\n"); createTempFile(directory, "first.animal.log", "hippopotamus\n"); testController.runSession(plan, true); REQUIRE(LogTestController::getInstance().contains("Logged 2 flow files")); REQUIRE(LogTestController::getInstance().contains("key:filename value:first.fruit.0-5.log")); REQUIRE(LogTestController::getInstance().contains("key:filename value:first.animal.0-12.log")); appendTempFile(directory, "first.fruit.log", "banana\n"); appendTempFile(directory, "first.animal.log", "hedgehog\n"); SECTION("If a file no longer matches the new regex, then we stop tailing it") { plan->setProperty(tail_file, org::apache::nifi::minifi::processors::TailFile::FileName.getName(), "first\\.f.*\\.log"); plan->reset(true); // clear the memory, but keep the state file LogTestController::getInstance().resetStream(LogTestController::getInstance().log_output); testController.runSession(plan, true); REQUIRE(LogTestController::getInstance().contains("Logged 1 flow file")); REQUIRE(LogTestController::getInstance().contains("key:filename value:first.fruit.6-12.log")); } SECTION("If a new file matches the new regex, we start tailing it") { plan->setProperty(tail_file, org::apache::nifi::minifi::processors::TailFile::FileName.getName(), ".*\\.fruit\\.log"); plan->reset(true); // clear the memory, but keep the state file LogTestController::getInstance().resetStream(LogTestController::getInstance().log_output); testController.runSession(plan, true); REQUIRE(LogTestController::getInstance().contains("Logged 2 flow file")); REQUIRE(LogTestController::getInstance().contains("key:filename value:first.fruit.6-12.log")); REQUIRE(LogTestController::getInstance().contains("key:filename value:second.fruit.0-6.log")); } } TEST_CASE("TailFile finds the single input file in both Single and Multiple mode", "[simple]") { TestController testController; LogTestController::getInstance().setTrace<minifi::processors::TailFile>(); LogTestController::getInstance().setDebug<core::ProcessSession>(); LogTestController::getInstance().setDebug<minifi::processors::LogAttribute>(); std::shared_ptr<TestPlan> plan = testController.createPlan(); std::shared_ptr<core::Processor> tailfile = plan->addProcessor("TailFile", "tailfileProc"); plan->setProperty(tailfile, org::apache::nifi::minifi::processors::TailFile::Delimiter.getName(), ""); plan->addProcessor("LogAttribute", "logattribute", core::Relationship("success", "description"), true); char format[] = "/tmp/gt.XXXXXX"; auto dir = testController.createTempDirectory(format); std::stringstream temp_file; temp_file << dir << utils::file::FileUtils::get_separator() << TMP_FILE; std::ofstream tmpfile; tmpfile.open(temp_file.str(), std::ios::out | std::ios::binary); tmpfile << NEWLINE_FILE; tmpfile.close(); SECTION("Single") { plan->setProperty(tailfile, org::apache::nifi::minifi::processors::TailFile::FileName.getName(), temp_file.str()); } SECTION("Multiple") { plan->setProperty(tailfile, org::apache::nifi::minifi::processors::TailFile::FileName.getName(), "minifi-.*\\.txt"); plan->setProperty(tailfile, org::apache::nifi::minifi::processors::TailFile::TailMode.getName(), "Multiple file"); plan->setProperty(tailfile, org::apache::nifi::minifi::processors::TailFile::BaseDirectory.getName(), dir); plan->setProperty(tailfile, org::apache::nifi::minifi::processors::TailFile::LookupFrequency.getName(), "0 sec"); } testController.runSession(plan, false); auto records = plan->getProvenanceRecords(); REQUIRE(records.size() == 2); testController.runSession(plan, false); REQUIRE(LogTestController::getInstance().contains("Logged 1 flow files")); REQUIRE(LogTestController::getInstance().contains("Size:" + std::to_string(NEWLINE_FILE.size()) + " Offset:0")); LogTestController::getInstance().reset(); } TEST_CASE("TailFile picks up new files created between runs", "[multiple_file]") { TestController testController; LogTestController::getInstance().setTrace<minifi::processors::TailFile>(); LogTestController::getInstance().setDebug<core::ProcessSession>(); LogTestController::getInstance().setDebug<minifi::processors::LogAttribute>(); char format[] = "/tmp/gt.XXXXXX"; auto dir = testController.createTempDirectory(format); std::shared_ptr<TestPlan> plan = testController.createPlan(); std::shared_ptr<core::Processor> tailfile = plan->addProcessor("TailFile", "tailfile"); plan->setProperty(tailfile, org::apache::nifi::minifi::processors::TailFile::TailMode.getName(), "Multiple file"); plan->setProperty(tailfile, org::apache::nifi::minifi::processors::TailFile::BaseDirectory.getName(), dir); plan->setProperty(tailfile, org::apache::nifi::minifi::processors::TailFile::LookupFrequency.getName(), "0 sec"); plan->setProperty(tailfile, org::apache::nifi::minifi::processors::TailFile::FileName.getName(), ".*\\.log"); plan->setProperty(tailfile, org::apache::nifi::minifi::processors::TailFile::Delimiter.getName(), "\n"); std::shared_ptr<core::Processor> logattribute = plan->addProcessor("LogAttribute", "logattribute", core::Relationship("success", "description"), true); plan->setProperty(logattribute, org::apache::nifi::minifi::processors::LogAttribute::FlowFilesToLog.getName(), "0"); createTempFile(dir, "application.log", "line1\nline2\n"); testController.runSession(plan, true); REQUIRE(LogTestController::getInstance().contains("Logged 2 flow files")); createTempFile(dir, "another.log", "some more content\n"); plan->reset(); LogTestController::getInstance().resetStream(LogTestController::getInstance().log_output); testController.runSession(plan, true); REQUIRE(LogTestController::getInstance().contains("Logged 1 flow file")); LogTestController::getInstance().reset(); } TEST_CASE("TailFile can handle input files getting removed", "[multiple_file]") { TestController testController; LogTestController::getInstance().setTrace<minifi::processors::TailFile>(); LogTestController::getInstance().setDebug<core::ProcessSession>(); LogTestController::getInstance().setDebug<minifi::processors::LogAttribute>(); char format[] = "/tmp/gt.XXXXXX"; auto dir = testController.createTempDirectory(format); std::shared_ptr<TestPlan> plan = testController.createPlan(); std::shared_ptr<core::Processor> tailfile = plan->addProcessor("TailFile", "tailfile"); plan->setProperty(tailfile, org::apache::nifi::minifi::processors::TailFile::TailMode.getName(), "Multiple file"); plan->setProperty(tailfile, org::apache::nifi::minifi::processors::TailFile::BaseDirectory.getName(), dir); plan->setProperty(tailfile, org::apache::nifi::minifi::processors::TailFile::LookupFrequency.getName(), "0 sec"); plan->setProperty(tailfile, org::apache::nifi::minifi::processors::TailFile::FileName.getName(), ".*\\.log"); plan->setProperty(tailfile, org::apache::nifi::minifi::processors::TailFile::Delimiter.getName(), "\n"); std::shared_ptr<core::Processor> logattribute = plan->addProcessor("LogAttribute", "logattribute", core::Relationship("success", "description"), true); plan->setProperty(logattribute, org::apache::nifi::minifi::processors::LogAttribute::FlowFilesToLog.getName(), "0"); createTempFile(dir, "one.log", "line one\n"); createTempFile(dir, "two.log", "some stuff\n"); testController.runSession(plan, true); REQUIRE(LogTestController::getInstance().contains("Logged 2 flow files")); plan->reset(); LogTestController::getInstance().resetStream(LogTestController::getInstance().log_output); appendTempFile(dir, "one.log", "line two\nline three\nline four\n"); removeFile(dir, "two.log"); testController.runSession(plan, true); REQUIRE(LogTestController::getInstance().contains("Logged 3 flow files")); LogTestController::getInstance().reset(); } TEST_CASE("TailFile processes a very long line correctly", "[simple]") { std::string line1("foo\n"); std::string line2(8050, 0); std::mt19937 gen(std::random_device{}()); // NOLINT (linter wants a space before '{') std::generate_n(line2.begin(), line2.size() - 1, [&]() -> char { return 32 + gen() % (127 - 32); }); line2.back() = '\n'; std::string line3("bar\n"); std::string line4("buzz"); TestController testController; LogTestController::getInstance().setTrace<TestPlan>(); LogTestController::getInstance().setTrace<processors::TailFile>(); LogTestController::getInstance().setTrace<processors::LogAttribute>(); LogTestController::getInstance().setTrace<core::ProcessSession>(); std::shared_ptr<TestPlan> plan = testController.createPlan(); std::shared_ptr<core::Processor> tailfile = plan->addProcessor("TailFile", "tailfileProc"); char format[] = "/tmp/gt.XXXXXX"; auto dir = testController.createTempDirectory(format); std::stringstream temp_file; temp_file << dir << utils::file::FileUtils::get_separator() << TMP_FILE; std::ofstream tmpfile; tmpfile.open(temp_file.str(), std::ios::out | std::ios::binary); tmpfile << line1 << line2 << line3 << line4; tmpfile.close(); plan->setProperty(tailfile, org::apache::nifi::minifi::processors::TailFile::FileName.getName(), temp_file.str()); plan->setProperty(tailfile, org::apache::nifi::minifi::processors::TailFile::Delimiter.getName(), "\n"); std::shared_ptr<core::Processor> log_attr = plan->addProcessor("LogAttribute", "Log", core::Relationship("success", "description"), true); plan->setProperty(log_attr, processors::LogAttribute::FlowFilesToLog.getName(), "0"); plan->setProperty(log_attr, processors::LogAttribute::LogPayload.getName(), "true"); plan->setProperty(log_attr, processors::LogAttribute::HexencodePayload.getName(), "true"); uint32_t line_length = 0U; SECTION("with line length 80") { line_length = 80U; } SECTION("with line length 200") { line_length = 200U; plan->setProperty(log_attr, processors::LogAttribute::MaxPayloadLineLength.getName(), "200"); } SECTION("with line length 0") { line_length = 0U; plan->setProperty(log_attr, processors::LogAttribute::MaxPayloadLineLength.getName(), "0"); } SECTION("with line length 16") { line_length = 16U; plan->setProperty(log_attr, processors::LogAttribute::MaxPayloadLineLength.getName(), "16"); } testController.runSession(plan, true); REQUIRE(LogTestController::getInstance().contains("Logged 3 flow files")); REQUIRE(LogTestController::getInstance().contains(utils::StringUtils::to_hex(line1))); auto line2_hex = utils::StringUtils::to_hex(line2); if (line_length == 0U) { REQUIRE(LogTestController::getInstance().contains(line2_hex)); } else { std::stringstream line2_hex_lines; for (size_t i = 0; i < line2_hex.size(); i += line_length) { line2_hex_lines << line2_hex.substr(i, line_length) << '\n'; } REQUIRE(LogTestController::getInstance().contains(line2_hex_lines.str())); } REQUIRE(LogTestController::getInstance().contains(utils::StringUtils::to_hex(line3))); REQUIRE(false == LogTestController::getInstance().contains(utils::StringUtils::to_hex(line4), std::chrono::seconds(0))); LogTestController::getInstance().reset(); } TEST_CASE("TailFile processes a long line followed by multiple newlines correctly", "[simple][edge_case]") { // Test having two delimiters on the buffer boundary std::string line1(4098, '\n'); std::mt19937 gen(std::random_device { }()); std::generate_n(line1.begin(), 4095, [&]() -> char { return 32 + gen() % (127 - 32); }); std::string line2("foo\n"); std::string line3("bar\n"); std::string line4("buzz"); // Create and write to the test file TestController testController; LogTestController::getInstance().setTrace<TestPlan>(); LogTestController::getInstance().setTrace<processors::TailFile>(); LogTestController::getInstance().setTrace<processors::LogAttribute>(); LogTestController::getInstance().setTrace<core::ProcessSession>(); std::shared_ptr<TestPlan> plan = testController.createPlan(); std::shared_ptr<core::Processor> tailfile = plan->addProcessor("TailFile", "tailfileProc"); auto id = tailfile->getUUIDStr(); char format[] = "/tmp/gt.XXXXXX"; auto dir = testController.createTempDirectory(format); std::stringstream temp_file; temp_file << dir << utils::file::FileUtils::get_separator() << TMP_FILE; std::ofstream tmpfile; tmpfile.open(temp_file.str(), std::ios::out | std::ios::binary); tmpfile << line1 << line2 << line3 << line4; tmpfile.close(); plan->setProperty(tailfile, org::apache::nifi::minifi::processors::TailFile::FileName.getName(), temp_file.str()); plan->setProperty(tailfile, org::apache::nifi::minifi::processors::TailFile::Delimiter.getName(), "\n"); std::shared_ptr<core::Processor> log_attr = plan->addProcessor("LogAttribute", "Log", core::Relationship("success", "description"), true); plan->setProperty(log_attr, processors::LogAttribute::FlowFilesToLog.getName(), "0"); plan->setProperty(log_attr, processors::LogAttribute::LogPayload.getName(), "true"); plan->setProperty(log_attr, processors::LogAttribute::HexencodePayload.getName(), "true"); testController.runSession(plan, true); REQUIRE(LogTestController::getInstance().contains("Logged 5 flow files")); auto line1_hex = utils::StringUtils::to_hex(line1.substr(0, 4096)); std::stringstream line1_hex_lines; for (size_t i = 0; i < line1_hex.size(); i += 80) { line1_hex_lines << line1_hex.substr(i, 80) << '\n'; } REQUIRE(LogTestController::getInstance().contains(line1_hex_lines.str())); REQUIRE(LogTestController::getInstance().contains(utils::StringUtils::to_hex(line2))); REQUIRE(LogTestController::getInstance().contains(utils::StringUtils::to_hex(line3))); REQUIRE(false == LogTestController::getInstance().contains(utils::StringUtils::to_hex(line4), std::chrono::seconds(0))); LogTestController::getInstance().reset(); } TEST_CASE("TailFile onSchedule throws if file(s) to tail cannot be determined", "[configuration]") { TestController testController; LogTestController::getInstance().setDebug<minifi::processors::TailFile>(); std::shared_ptr<TestPlan> plan = testController.createPlan(); std::shared_ptr<core::Processor> tailfile = plan->addProcessor("TailFile", "tailfileProc"); SECTION("Single file mode by default") { SECTION("No FileName") { } SECTION("FileName does not contain the path") { plan->setProperty(tailfile, org::apache::nifi::minifi::processors::TailFile::FileName.getName(), "minifi-log.txt"); } } SECTION("Explicit Single file mode") { plan->setProperty(tailfile, org::apache::nifi::minifi::processors::TailFile::TailMode.getName(), "Single file"); SECTION("No FileName") { } SECTION("FileName does not contain the path") { plan->setProperty(tailfile, org::apache::nifi::minifi::processors::TailFile::FileName.getName(), "minifi-log.txt"); } } SECTION("Multiple file mode") { plan->setProperty(tailfile, org::apache::nifi::minifi::processors::TailFile::TailMode.getName(), "Multiple file"); SECTION("No FileName and no BaseDirectory") { } SECTION("No BaseDirectory") { plan->setProperty(tailfile, org::apache::nifi::minifi::processors::TailFile::FileName.getName(), "minifi-.*\\.txt"); } } REQUIRE_THROWS(plan->runNextProcessor()); } TEST_CASE("TailFile onSchedule throws in Multiple mode if the Base Directory does not exist", "[configuration][multiple_file]") { TestController testController; LogTestController::getInstance().setDebug<minifi::processors::TailFile>(); std::shared_ptr<TestPlan> plan = testController.createPlan(); std::shared_ptr<core::Processor> tailfile = plan->addProcessor("TailFile", "tailfileProc"); plan->setProperty(tailfile, processors::TailFile::TailMode.getName(), "Multiple file"); plan->setProperty(tailfile, processors::TailFile::FileName.getName(), ".*\\.log"); SECTION("No Base Directory is set") { REQUIRE_THROWS(plan->runNextProcessor()); } SECTION("Base Directory is set, but does not exist") { std::string nonexistent_file_name{"/no-such-directory/688b01d0-9e5f-11ea-820d-f338c34d39a1/31d1a81a-9e5f-11ea-a77b-8b27d514a452"}; plan->setProperty(tailfile, processors::TailFile::BaseDirectory.getName(), nonexistent_file_name); REQUIRE_THROWS(plan->runNextProcessor()); } SECTION("Base Directory is set and it exists") { char format[] = "/tmp/gt.XXXXXX"; std::string directory = testController.createTempDirectory(format); plan->setProperty(tailfile, processors::TailFile::BaseDirectory.getName(), directory); plan->setProperty(tailfile, processors::TailFile::LookupFrequency.getName(), "0 sec"); REQUIRE_NOTHROW(plan->runNextProcessor()); } } TEST_CASE("TailFile finds and finishes the renamed file and continues with the new log file", "[rotation]") { TestController testController; const char DELIM = ','; size_t expected_pieces = std::count(NEWLINE_FILE.begin(), NEWLINE_FILE.end(), DELIM); // The last piece is left as considered unfinished LogTestController::getInstance().setTrace<TestPlan>(); LogTestController::getInstance().setTrace<processors::TailFile>(); LogTestController::getInstance().setTrace<processors::LogAttribute>(); auto plan = testController.createPlan(); char format[] = "/tmp/gt.XXXXXX"; auto dir = testController.createTempDirectory(format); std::string in_file = dir + utils::file::FileUtils::get_separator() + "testfifo.txt"; std::ofstream in_file_stream(in_file, std::ios::out | std::ios::binary); in_file_stream << NEWLINE_FILE; in_file_stream.flush(); // Build MiNiFi processing graph auto tail_file = plan->addProcessor("TailFile", "Tail"); plan->setProperty(tail_file, processors::TailFile::Delimiter.getName(), std::string(1, DELIM)); SECTION("single") { plan->setProperty(tail_file, processors::TailFile::FileName.getName(), in_file); } SECTION("Multiple") { plan->setProperty(tail_file, org::apache::nifi::minifi::processors::TailFile::FileName.getName(), "testfifo.txt"); plan->setProperty(tail_file, org::apache::nifi::minifi::processors::TailFile::TailMode.getName(), "Multiple file"); plan->setProperty(tail_file, org::apache::nifi::minifi::processors::TailFile::BaseDirectory.getName(), dir); plan->setProperty(tail_file, org::apache::nifi::minifi::processors::TailFile::LookupFrequency.getName(), "0 sec"); } auto log_attr = plan->addProcessor("LogAttribute", "Log", core::Relationship("success", "description"), true); plan->setProperty(log_attr, processors::LogAttribute::FlowFilesToLog.getName(), "0"); plan->setProperty(log_attr, processors::LogAttribute::LogPayload.getName(), "true"); // Log as many FFs as it can to make sure exactly the expected amount is produced plan->runNextProcessor(); // Tail plan->runNextProcessor(); // Log REQUIRE(LogTestController::getInstance().contains(std::string("Logged ") + std::to_string(expected_pieces) + " flow files")); std::this_thread::sleep_for(std::chrono::milliseconds(100)); // make sure the new file gets newer modification time in_file_stream << DELIM; in_file_stream.close(); std::string rotated_file = (in_file + ".1"); REQUIRE(rename(in_file.c_str(), rotated_file.c_str()) == 0); std::ofstream new_in_file_stream(in_file, std::ios::out | std::ios::binary); new_in_file_stream << "five" << DELIM << "six" << DELIM; new_in_file_stream.close(); plan->reset(); LogTestController::getInstance().resetStream(LogTestController::getInstance().log_output); plan->runNextProcessor(); // Tail plan->runNextProcessor(); // Log // Find the last flow file in the rotated file, and then pick up the new file REQUIRE(LogTestController::getInstance().contains("Logged 3 flow files")); REQUIRE(LogTestController::getInstance().contains("key:filename value:testfifo.txt.28-34.1")); REQUIRE(LogTestController::getInstance().contains("key:filename value:testfifo.0-4.txt")); REQUIRE(LogTestController::getInstance().contains("key:filename value:testfifo.5-8.txt")); } TEST_CASE("TailFile finds and finishes multiple rotated files and continues with the new log file", "[rotation]") { TestController testController; const char DELIM = ':'; LogTestController::getInstance().setTrace<TestPlan>(); LogTestController::getInstance().setTrace<processors::TailFile>(); LogTestController::getInstance().setTrace<processors::LogAttribute>(); auto plan = testController.createPlan(); char format[] = "/tmp/gt.XXXXXX"; auto dir = testController.createTempDirectory(format); std::string test_file = dir + utils::file::FileUtils::get_separator() + "fruits.log"; std::ofstream test_file_stream_0(test_file, std::ios::binary); test_file_stream_0 << "Apple" << DELIM << "Orange" << DELIM; test_file_stream_0.flush(); // Build MiNiFi processing graph auto tail_file = plan->addProcessor("TailFile", "Tail"); plan->setProperty(tail_file, processors::TailFile::Delimiter.getName(), std::string(1, DELIM)); plan->setProperty(tail_file, processors::TailFile::FileName.getName(), test_file); auto log_attr = plan->addProcessor("LogAttribute", "Log", core::Relationship("success", "description"), true); plan->setProperty(log_attr, processors::LogAttribute::FlowFilesToLog.getName(), "0"); testController.runSession(plan, true); REQUIRE(LogTestController::getInstance().contains("Logged 2 flow files")); REQUIRE(LogTestController::getInstance().contains("key:filename value:fruits.0-5.log")); REQUIRE(LogTestController::getInstance().contains("key:filename value:fruits.6-12.log")); std::this_thread::sleep_for(std::chrono::milliseconds(100)); test_file_stream_0 << "Pear" << DELIM; test_file_stream_0.close(); std::string first_rotated_file = dir + utils::file::FileUtils::get_separator() + "fruits.0.log"; REQUIRE(rename(test_file.c_str(), first_rotated_file.c_str()) == 0); std::ofstream test_file_stream_1(test_file, std::ios::binary); test_file_stream_1 << "Pineapple" << DELIM << "Kiwi" << DELIM; test_file_stream_1.close(); std::string second_rotated_file = dir + utils::file::FileUtils::get_separator() + "fruits.1.log"; REQUIRE(rename(test_file.c_str(), second_rotated_file.c_str()) == 0); std::ofstream test_file_stream_2(test_file, std::ios::binary); test_file_stream_2 << "Apricot" << DELIM; test_file_stream_2.close(); plan->reset(); LogTestController::getInstance().resetStream(LogTestController::getInstance().log_output); testController.runSession(plan, true); REQUIRE(LogTestController::getInstance().contains("Logged 4 flow files")); REQUIRE(LogTestController::getInstance().contains("key:filename value:fruits.0.13-17.log")); // Pear REQUIRE(LogTestController::getInstance().contains("key:filename value:fruits.1.0-9.log")); // Pineapple REQUIRE(LogTestController::getInstance().contains("key:filename value:fruits.1.10-14.log")); // Kiwi REQUIRE(LogTestController::getInstance().contains("key:filename value:fruits.0-7.log")); // Apricot } TEST_CASE("TailFile ignores old rotated files", "[rotation]") { TestController testController; LogTestController::getInstance().setTrace<minifi::processors::TailFile>(); LogTestController::getInstance().setDebug<core::ProcessSession>(); LogTestController::getInstance().setDebug<minifi::processors::LogAttribute>(); char format[] = "/tmp/gt.XXXXXX"; const std::string dir = testController.createTempDirectory(format); std::string log_file_name = dir + utils::file::FileUtils::get_separator() + "test.log"; std::shared_ptr<TestPlan> plan = testController.createPlan(); std::shared_ptr<core::Processor> tailfile = plan->addProcessor("TailFile", "tailfile"); plan->setProperty(tailfile, org::apache::nifi::minifi::processors::TailFile::FileName.getName(), log_file_name); plan->setProperty(tailfile, org::apache::nifi::minifi::processors::TailFile::Delimiter.getName(), "\n"); std::shared_ptr<core::Processor> logattribute = plan->addProcessor("LogAttribute", "logattribute", core::Relationship("success", "description"), true); plan->setProperty(logattribute, org::apache::nifi::minifi::processors::LogAttribute::FlowFilesToLog.getName(), "0"); createTempFile(dir, "test.2019-08-20", "line1\nline2\nline3\nline4\n"); // very old rotated file std::this_thread::sleep_for(std::chrono::seconds(1)); createTempFile(dir, "test.log", "line5\nline6\nline7\n"); testController.runSession(plan, true); REQUIRE(LogTestController::getInstance().contains("Logged 3 flow files")); REQUIRE(!LogTestController::getInstance().contains("key:filename value:test.2019-08-20")); std::string rotated_log_file_name = dir + utils::file::FileUtils::get_separator() + "test.2020-05-18"; REQUIRE(rename(log_file_name.c_str(), rotated_log_file_name.c_str()) == 0); createTempFile(dir, "test.log", "line8\nline9\n"); plan->reset(); LogTestController::getInstance().resetStream(LogTestController::getInstance().log_output); testController.runSession(plan, true); REQUIRE(!LogTestController::getInstance().contains("key:filename value:test.2019-08-20")); LogTestController::getInstance().reset(); } TEST_CASE("TailFile rotation works with multiple input files", "[rotation][multiple_file]") { TestController testController; LogTestController::getInstance().setTrace<TestPlan>(); LogTestController::getInstance().setTrace<processors::TailFile>(); LogTestController::getInstance().setTrace<processors::LogAttribute>(); auto plan = testController.createPlan(); char format[] = "/tmp/gt.XXXXXX"; auto dir = testController.createTempDirectory(format); createTempFile(dir, "fruit.log", "apple\npear\nbanana\n"); createTempFile(dir, "animal.log", "bear\ngiraffe\n"); createTempFile(dir, "color.log", "red\nblue\nyellow\npurple\n"); auto tail_file = plan->addProcessor("TailFile", "Tail"); plan->setProperty(tail_file, processors::TailFile::Delimiter.getName(), "\n"); plan->setProperty(tail_file, processors::TailFile::TailMode.getName(), "Multiple file"); plan->setProperty(tail_file, processors::TailFile::FileName.getName(), ".*\\.log"); plan->setProperty(tail_file, processors::TailFile::BaseDirectory.getName(), dir); plan->setProperty(tail_file, processors::TailFile::LookupFrequency.getName(), "0 sec"); auto log_attribute = plan->addProcessor("LogAttribute", "Log", core::Relationship("success", "description"), true); plan->setProperty(log_attribute, processors::LogAttribute::FlowFilesToLog.getName(), "0"); testController.runSession(plan, true); REQUIRE(LogTestController::getInstance().contains("Logged " + std::to_string(3 + 2 + 4) + " flow files")); REQUIRE(LogTestController::getInstance().contains("key:filename value:fruit.0-5.log")); REQUIRE(LogTestController::getInstance().contains("key:filename value:fruit.6-10.log")); REQUIRE(LogTestController::getInstance().contains("key:filename value:fruit.11-17.log")); REQUIRE(LogTestController::getInstance().contains("key:filename value:animal.0-4.log")); REQUIRE(LogTestController::getInstance().contains("key:filename value:animal.5-12.log")); REQUIRE(LogTestController::getInstance().contains("key:filename value:color.0-3.log")); REQUIRE(LogTestController::getInstance().contains("key:filename value:color.4-8.log")); REQUIRE(LogTestController::getInstance().contains("key:filename value:color.9-15.log")); REQUIRE(LogTestController::getInstance().contains("key:filename value:color.16-22.log")); std::this_thread::sleep_for(std::chrono::milliseconds(100)); appendTempFile(dir, "fruit.log", "orange\n"); appendTempFile(dir, "animal.log", "axolotl\n"); appendTempFile(dir, "color.log", "aquamarine\n"); renameTempFile(dir, "fruit.log", "fruit.0"); renameTempFile(dir, "animal.log", "animal.0"); createTempFile(dir, "fruit.log", "peach\n"); createTempFile(dir, "animal.log", "dinosaur\n"); appendTempFile(dir, "color.log", "turquoise\n"); plan->reset(); LogTestController::getInstance().resetStream(LogTestController::getInstance().log_output); testController.runSession(plan, true); REQUIRE(LogTestController::getInstance().contains("Logged 6 flow files")); REQUIRE(LogTestController::getInstance().contains("key:filename value:fruit.18-24.0")); REQUIRE(LogTestController::getInstance().contains("key:filename value:fruit.0-5.log")); REQUIRE(LogTestController::getInstance().contains("key:filename value:animal.13-20.0")); REQUIRE(LogTestController::getInstance().contains("key:filename value:animal.0-8.log")); REQUIRE(LogTestController::getInstance().contains("key:filename value:color.23-33.log")); REQUIRE(LogTestController::getInstance().contains("key:filename value:color.34-43.log")); } TEST_CASE("TailFile handles the Rolling Filename Pattern property correctly", "[rotation]") { TestController testController; LogTestController::getInstance().setTrace<TestPlan>(); LogTestController::getInstance().setTrace<processors::TailFile>(); LogTestController::getInstance().setTrace<processors::LogAttribute>(); auto plan = testController.createPlan(); char format[] = "/tmp/gt.XXXXXX"; auto dir = testController.createTempDirectory(format); std::string test_file = createTempFile(dir, "test.log", "some stuff\n"); // Build MiNiFi processing graph auto tail_file = plan->addProcessor("TailFile", "Tail"); plan->setProperty(tail_file, processors::TailFile::Delimiter.getName(), "\n"); plan->setProperty(tail_file, processors::TailFile::FileName.getName(), test_file); std::vector<std::string> expected_log_lines; SECTION("If no pattern is set, we use the default, which is ${filename}.*, so the unrelated file will be picked up") { expected_log_lines = std::vector<std::string>{"Logged 2 flow files", "test.rolled.11-24.log", "test.0-15.txt"}; } SECTION("If a pattern is set to exclude the unrelated file, we no longer pick it up") { plan->setProperty(tail_file, processors::TailFile::RollingFilenamePattern.getName(), "${filename}.*.log"); expected_log_lines = std::vector<std::string>{"Logged 1 flow file", "test.rolled.11-24.log"}; } SECTION("We can also set the pattern to not include the file name") { plan->setProperty(tail_file, processors::TailFile::RollingFilenamePattern.getName(), "other_roll??.log"); expected_log_lines = std::vector<std::string>{"Logged 1 flow file", "other_rolled.11-24.log"}; } auto log_attr = plan->addProcessor("LogAttribute", "Log", core::Relationship("success", "description"), true); plan->setProperty(log_attr, processors::LogAttribute::FlowFilesToLog.getName(), "0"); testController.runSession(plan, true); REQUIRE(LogTestController::getInstance().contains("Logged 1 flow file")); REQUIRE(LogTestController::getInstance().contains("key:filename value:test.0-10.log")); std::this_thread::sleep_for(std::chrono::milliseconds(100)); appendTempFile(dir, "test.log", "one more line\n"); renameTempFile(dir, "test.log", "test.rolled.log"); createTempFile(dir, "test.txt", "unrelated stuff\n"); createTempFile(dir, "other_rolled.log", "some stuff\none more line\n"); // same contents as test.rolled.log plan->reset(); LogTestController::getInstance().resetStream(LogTestController::getInstance().log_output); testController.runSession(plan, true); for (const auto &log_line : expected_log_lines) { REQUIRE(LogTestController::getInstance().contains(log_line)); } } TEST_CASE("TailFile finds and finishes the renamed file and continues with the new log file after a restart", "[rotation][restart]") { TestController testController; LogTestController::getInstance().setTrace<TestPlan>(); LogTestController::getInstance().setTrace<processors::TailFile>(); LogTestController::getInstance().setTrace<processors::LogAttribute>(); char log_dir_format[] = "/tmp/gt.XXXXXX"; auto log_dir = testController.createTempDirectory(log_dir_format); std::string test_file_1 = createTempFile(log_dir, "test.1", "line one\nline two\nline three\n"); // old rotated file std::this_thread::sleep_for(std::chrono::seconds(1)); std::string test_file = createTempFile(log_dir, "test.log", "line four\nline five\nline six\n"); // current log file char state_dir_format[] = "/tmp/gt.XXXXXX"; auto state_dir = testController.createTempDirectory(state_dir_format); utils::Identifier tail_file_uuid = utils::IdGenerator::getIdGenerator()->generate(); const core::Relationship success_relationship{"success", "everything is fine"}; { auto test_plan = testController.createPlan(nullptr, state_dir.c_str()); auto tail_file = test_plan->addProcessor("TailFile", tail_file_uuid, "Tail", {success_relationship}); test_plan->setProperty(tail_file, processors::TailFile::FileName.getName(), test_file); auto log_attr = test_plan->addProcessor("LogAttribute", "Log", success_relationship, true); test_plan->setProperty(log_attr, processors::LogAttribute::FlowFilesToLog.getName(), "0"); test_plan->setProperty(log_attr, processors::LogAttribute::LogPayload.getName(), "true"); testController.runSession(test_plan, true); REQUIRE(LogTestController::getInstance().contains("Logged 3 flow files")); } LogTestController::getInstance().resetStream(LogTestController::getInstance().log_output); appendTempFile(log_dir, "test.log", "line seven\n"); renameTempFile(log_dir, "test.1", "test.2"); renameTempFile(log_dir, "test.log", "test.1"); createTempFile(log_dir, "test.log", "line eight is the last line\n"); { auto test_plan = testController.createPlan(nullptr, state_dir.c_str()); auto tail_file = test_plan->addProcessor("TailFile", tail_file_uuid, "Tail", {success_relationship}); test_plan->setProperty(tail_file, processors::TailFile::FileName.getName(), test_file); auto log_attr = test_plan->addProcessor("LogAttribute", "Log", success_relationship, true); test_plan->setProperty(log_attr, processors::LogAttribute::FlowFilesToLog.getName(), "0"); test_plan->setProperty(log_attr, processors::LogAttribute::LogPayload.getName(), "true"); testController.runSession(test_plan, true); REQUIRE(LogTestController::getInstance().contains("Logged 2 flow files")); REQUIRE(LogTestController::getInstance().contains("key:filename value:test.29-39.1")); REQUIRE(LogTestController::getInstance().contains("key:filename value:test.0-27.log")); } } TEST_CASE("TailFile yields if no work is done", "[yield]") { TestController testController; LogTestController::getInstance().setTrace<TestPlan>(); LogTestController::getInstance().setTrace<processors::TailFile>(); LogTestController::getInstance().setTrace<processors::LogAttribute>(); char format[] = "/tmp/gt.XXXXXX"; auto temp_directory = testController.createTempDirectory(format); auto plan = testController.createPlan(); auto tail_file = plan->addProcessor("TailFile", "Tail"); plan->setProperty(tail_file, processors::TailFile::Delimiter.getName(), "\n"); plan->setProperty(tail_file, processors::TailFile::TailMode.getName(), "Multiple file"); plan->setProperty(tail_file, processors::TailFile::FileName.getName(), ".*\\.log"); plan->setProperty(tail_file, processors::TailFile::BaseDirectory.getName(), temp_directory); plan->setProperty(tail_file, processors::TailFile::LookupFrequency.getName(), "0 sec"); SECTION("Empty log file => yield") { createTempFile(temp_directory, "first.log", ""); testController.runSession(plan, true); REQUIRE(tail_file->getYieldTime() > 0); SECTION("No logging happened between onTrigger calls => yield") { plan->reset(); tail_file->clearYield(); testController.runSession(plan, true); REQUIRE(tail_file->getYieldTime() > 0); } SECTION("Some logging happened between onTrigger calls => don't yield") { plan->reset(); tail_file->clearYield(); appendTempFile(temp_directory, "first.log", "stuff stuff\nand stuff\n"); testController.runSession(plan, true); REQUIRE(tail_file->getYieldTime() == 0); } } SECTION("Non-empty log file => don't yield") { createTempFile(temp_directory, "second.log", "some content\n"); testController.runSession(plan, true); REQUIRE(tail_file->getYieldTime() == 0); SECTION("No logging happened between onTrigger calls => yield") { plan->reset(); tail_file->clearYield(); testController.runSession(plan, true); REQUIRE(tail_file->getYieldTime() > 0); } SECTION("Some logging happened between onTrigger calls => don't yield") { plan->reset(); tail_file->clearYield(); appendTempFile(temp_directory, "second.log", "stuff stuff\nand stuff\n"); testController.runSession(plan, true); REQUIRE(tail_file->getYieldTime() == 0); } } } TEST_CASE("TailFile yields if no work is done on any files", "[yield][multiple_file]") { TestController testController; LogTestController::getInstance().setTrace<TestPlan>(); LogTestController::getInstance().setTrace<processors::TailFile>(); LogTestController::getInstance().setTrace<processors::LogAttribute>(); char format[] = "/tmp/gt.XXXXXX"; auto temp_directory = testController.createTempDirectory(format); auto plan = testController.createPlan(); auto tail_file = plan->addProcessor("TailFile", "Tail"); plan->setProperty(tail_file, processors::TailFile::Delimiter.getName(), "\n"); plan->setProperty(tail_file, processors::TailFile::TailMode.getName(), "Multiple file"); plan->setProperty(tail_file, processors::TailFile::FileName.getName(), ".*\\.log"); plan->setProperty(tail_file, processors::TailFile::BaseDirectory.getName(), temp_directory); plan->setProperty(tail_file, processors::TailFile::LookupFrequency.getName(), "0 sec"); createTempFile(temp_directory, "first.log", "stuff\n"); createTempFile(temp_directory, "second.log", "different stuff\n"); createTempFile(temp_directory, "third.log", "stuff stuff\n"); testController.runSession(plan, true); plan->reset(); tail_file->clearYield(); SECTION("No file changed => yield") { testController.runSession(plan, true); REQUIRE(tail_file->getYieldTime() > 0); } SECTION("One file changed => don't yield") { SECTION("first") { appendTempFile(temp_directory, "first.log", "more stuff\n"); } SECTION("second") { appendTempFile(temp_directory, "second.log", "more stuff\n"); } SECTION("third") { appendTempFile(temp_directory, "third.log", "more stuff\n"); } testController.runSession(plan, true); REQUIRE(tail_file->getYieldTime() == 0); } SECTION("More than one file changed => don't yield") { SECTION("first and third") { appendTempFile(temp_directory, "first.log", "more stuff\n"); appendTempFile(temp_directory, "third.log", "more stuff\n"); } SECTION("all of them") { appendTempFile(temp_directory, "first.log", "more stuff\n"); appendTempFile(temp_directory, "second.log", "more stuff\n"); appendTempFile(temp_directory, "third.log", "more stuff\n"); } testController.runSession(plan, true); REQUIRE(tail_file->getYieldTime() == 0); } } TEST_CASE("TailFile doesn't yield if work was done on rotated files only", "[yield][rotation]") { TestController testController; LogTestController::getInstance().setTrace<TestPlan>(); LogTestController::getInstance().setTrace<processors::TailFile>(); LogTestController::getInstance().setTrace<processors::LogAttribute>(); char format[] = "/tmp/gt.XXXXXX"; auto temp_directory = testController.createTempDirectory(format); std::string full_file_name = createTempFile(temp_directory, "test.log", "stuff\n"); auto plan = testController.createPlan(); auto tail_file = plan->addProcessor("TailFile", "Tail"); plan->setProperty(tail_file, processors::TailFile::Delimiter.getName(), "\n"); plan->setProperty(tail_file, processors::TailFile::FileName.getName(), full_file_name); testController.runSession(plan, true); plan->reset(); tail_file->clearYield(); std::this_thread::sleep_for(std::chrono::milliseconds(100)); SECTION("File rotated but not written => yield") { renameTempFile(temp_directory, "test.log", "test.1"); SECTION("Don't create empty new log file") { } SECTION("Create empty new log file") { createTempFile(temp_directory, "test.log", ""); } testController.runSession(plan, true); REQUIRE(tail_file->getYieldTime() > 0); } SECTION("File rotated and new stuff is added => don't yield") { SECTION("New content before rotation") { appendTempFile(temp_directory, "test.log", "more stuff\n"); } renameTempFile(temp_directory, "test.log", "test.1"); SECTION("New content after rotation") { createTempFile(temp_directory, "test.log", "even more stuff\n"); } testController.runSession(plan, true); REQUIRE(tail_file->getYieldTime() == 0); } } TEST_CASE("TailFile handles the Delimiter setting correctly", "[delimiter]") { std::vector<std::pair<std::string, std::string>> test_cases = { // first = value of Delimiter in the config // second = the expected delimiter char which will be used {"", ""}, {",", ","}, {"\t", "\t"}, {"\\t", "\t"}, {"\n", "\n"}, {"\\n", "\n"}, {"\\", "\\"}, {"\\\\", "\\"}}; for (const auto &test_case : test_cases) { TestController testController; LogTestController::getInstance().setTrace<TestPlan>(); LogTestController::getInstance().setTrace<processors::TailFile>(); LogTestController::getInstance().setTrace<processors::LogAttribute>(); char format[] = "/tmp/gt.XXXXXX"; auto temp_directory = testController.createTempDirectory(format); std::string delimiter = test_case.second; std::string full_file_name = createTempFile(temp_directory, "test.log", "one" + delimiter + "two" + delimiter); auto plan = testController.createPlan(); auto tail_file = plan->addProcessor("TailFile", "Tail"); plan->setProperty(tail_file, processors::TailFile::Delimiter.getName(), test_case.first); plan->setProperty(tail_file, processors::TailFile::FileName.getName(), full_file_name); auto log_attribute = plan->addProcessor("LogAttribute", "Log", core::Relationship("success", "description"), true); plan->setProperty(log_attribute, processors::LogAttribute::FlowFilesToLog.getName(), "0"); testController.runSession(plan, true); if (delimiter.empty()) { REQUIRE(LogTestController::getInstance().contains("Logged 1 flow files")); REQUIRE(LogTestController::getInstance().contains("key:filename value:test.0-5.log")); } else { REQUIRE(LogTestController::getInstance().contains("Logged 2 flow files")); REQUIRE(LogTestController::getInstance().contains("key:filename value:test.0-3.log")); REQUIRE(LogTestController::getInstance().contains("key:filename value:test.4-7.log")); } } } TEST_CASE("TailFile handles Unix/Windows line endings correctly", "[simple]") { TestController testController; LogTestController::getInstance().setTrace<TestPlan>(); LogTestController::getInstance().setTrace<processors::TailFile>(); LogTestController::getInstance().setTrace<processors::LogAttribute>(); char format[] = "/tmp/gt.XXXXXX"; auto temp_directory = testController.createTempDirectory(format); std::string full_file_name = createTempFile(temp_directory, "test.log", "line1\nline two\n", std::ios::out); // write in text mode auto plan = testController.createPlan(); auto tail_file = plan->addProcessor("TailFile", "Tail"); plan->setProperty(tail_file, processors::TailFile::FileName.getName(), full_file_name); auto log_attribute = plan->addProcessor("LogAttribute", "Log", core::Relationship("success", "description"), true); plan->setProperty(log_attribute, processors::LogAttribute::FlowFilesToLog.getName(), "0"); testController.runSession(plan, true); #ifdef WIN32 std::size_t line_ending_size = 2; #else std::size_t line_ending_size = 1; #endif REQUIRE(LogTestController::getInstance().contains("Logged 2 flow files")); REQUIRE(LogTestController::getInstance().contains("Size:" + std::to_string(5 + line_ending_size) + " Offset:0")); REQUIRE(LogTestController::getInstance().contains("Size:" + std::to_string(8 + line_ending_size) + " Offset:0")); } TEST_CASE("TailFile can tail all files in a directory recursively", "[multiple]") { TestController testController; LogTestController::getInstance().setTrace<TestPlan>(); LogTestController::getInstance().setTrace<processors::TailFile>(); LogTestController::getInstance().setTrace<processors::LogAttribute>(); char format[] = "/tmp/gt.XXXXXX"; std::string base_directory = testController.createTempDirectory(format); std::string directory1 = base_directory + utils::file::FileUtils::get_separator() + "one"; utils::file::FileUtils::create_dir(directory1); std::string directory11 = directory1 + utils::file::FileUtils::get_separator() + "one_child"; utils::file::FileUtils::create_dir(directory11); std::string directory2 = base_directory + utils::file::FileUtils::get_separator() + "two"; utils::file::FileUtils::create_dir(directory2); createTempFile(base_directory, "test.orange.log", "orange juice\n"); createTempFile(directory1, "test.blue.log", "blue\n"); createTempFile(directory1, "test.orange.log", "orange autumn leaves\n"); createTempFile(directory11, "test.camel.log", "camel\n"); createTempFile(directory2, "test.triangle.log", "triangle\n"); auto plan = testController.createPlan(); auto tail_file = plan->addProcessor("TailFile", "Tail"); plan->setProperty(tail_file, processors::TailFile::TailMode.getName(), "Multiple file"); plan->setProperty(tail_file, processors::TailFile::BaseDirectory.getName(), base_directory); plan->setProperty(tail_file, processors::TailFile::LookupFrequency.getName(), "0 sec"); plan->setProperty(tail_file, processors::TailFile::FileName.getName(), ".*\\.log"); auto log_attribute = plan->addProcessor("LogAttribute", "Log", core::Relationship("success", "description"), true); plan->setProperty(log_attribute, processors::LogAttribute::FlowFilesToLog.getName(), "0"); plan->setProperty(log_attribute, processors::LogAttribute::LogPayload.getName(), "true"); SECTION("Recursive lookup not set => defaults to false") { testController.runSession(plan, true); REQUIRE(LogTestController::getInstance().contains("Logged 1 flow file")); } SECTION("Recursive lookup set to false") { plan->setProperty(tail_file, processors::TailFile::RecursiveLookup.getName(), "false"); testController.runSession(plan, true); REQUIRE(LogTestController::getInstance().contains("Logged 1 flow file")); } SECTION("Recursive lookup set to true") { plan->setProperty(tail_file, processors::TailFile::RecursiveLookup.getName(), "true"); testController.runSession(plan, true); REQUIRE(LogTestController::getInstance().contains("Logged 5 flow files")); } } TEST_CASE("TailFile interprets the lookup frequency property correctly", "[multiple]") { TestController testController; LogTestController::getInstance().setTrace<TestPlan>(); LogTestController::getInstance().setTrace<processors::TailFile>(); LogTestController::getInstance().setTrace<processors::LogAttribute>(); char format[] = "/tmp/gt.XXXXXX"; std::string directory = testController.createTempDirectory(format); createTempFile(directory, "test.red.log", "cherry\n"); auto plan = testController.createPlan(); auto tail_file = plan->addProcessor("TailFile", "Tail"); plan->setProperty(tail_file, processors::TailFile::TailMode.getName(), "Multiple file"); plan->setProperty(tail_file, processors::TailFile::BaseDirectory.getName(), directory); plan->setProperty(tail_file, processors::TailFile::FileName.getName(), ".*\\.log"); auto log_attribute = plan->addProcessor("LogAttribute", "Log", core::Relationship("success", "description"), true); plan->setProperty(log_attribute, processors::LogAttribute::FlowFilesToLog.getName(), "0"); testController.runSession(plan, true); SECTION("Lookup frequency not set => defaults to 10 minutes") { std::shared_ptr<processors::TailFile> tail_file_processor = std::dynamic_pointer_cast<processors::TailFile>(tail_file); REQUIRE(tail_file_processor); REQUIRE(tail_file_processor->getLookupFrequency() == std::chrono::minutes{10}); } SECTION("Lookup frequency set to zero => new files are picked up immediately") { plan->setProperty(tail_file, processors::TailFile::LookupFrequency.getName(), "0 sec"); plan->reset(true); LogTestController::getInstance().resetStream(LogTestController::getInstance().log_output); createTempFile(directory, "test.blue.log", "sky\n"); createTempFile(directory, "test.green.log", "grass\n"); testController.runSession(plan, true); REQUIRE(LogTestController::getInstance().contains("Logged 2 flow files")); } SECTION("Lookup frequency set to 10 ms => new files are only picked up after 10 ms") { plan->setProperty(tail_file, processors::TailFile::LookupFrequency.getName(), "10 ms"); plan->reset(true); LogTestController::getInstance().resetStream(LogTestController::getInstance().log_output); createTempFile(directory, "test.blue.log", "sky\n"); createTempFile(directory, "test.green.log", "grass\n"); testController.runSession(plan, true); REQUIRE(LogTestController::getInstance().contains("Logged 0 flow files")); plan->reset(false); LogTestController::getInstance().resetStream(LogTestController::getInstance().log_output); std::this_thread::sleep_for(std::chrono::milliseconds(11)); testController.runSession(plan, true); REQUIRE(LogTestController::getInstance().contains("Logged 2 flow files")); } }
47.054404
155
0.710111
nghiaxlee
66e8a4709e2a001eb1146bc097293d85d7a5350b
10,277
cc
C++
chrome/browser/plugins/plugin_prefs_unittest.cc
pozdnyakov/chromium-crosswalk
0fb25c7278bf1d93e53a3b0bcb75aa8b99d4b26e
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
2
2020-05-03T06:33:56.000Z
2021-11-14T18:39:42.000Z
chrome/browser/plugins/plugin_prefs_unittest.cc
pozdnyakov/chromium-crosswalk
0fb25c7278bf1d93e53a3b0bcb75aa8b99d4b26e
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
chrome/browser/plugins/plugin_prefs_unittest.cc
pozdnyakov/chromium-crosswalk
0fb25c7278bf1d93e53a3b0bcb75aa8b99d4b26e
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
// 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. #include "chrome/browser/plugins/plugin_prefs.h" #include "base/at_exit.h" #include "base/bind.h" #include "base/message_loop.h" #include "base/path_service.h" #include "base/run_loop.h" #include "base/strings/utf_string_conversions.h" #include "chrome/common/chrome_constants.h" #include "chrome/common/chrome_paths.h" #include "content/public/browser/plugin_service.h" #include "content/public/test/test_browser_thread.h" #include "testing/gtest/include/gtest/gtest.h" #include "webkit/plugins/npapi/mock_plugin_list.h" #include "webkit/plugins/webplugininfo.h" using content::BrowserThread; using content::PluginService; namespace { void CanEnablePluginCallback(const base::Closure& quit_closure, bool expected_can_change, bool did_change) { EXPECT_EQ(expected_can_change, did_change); quit_closure.Run(); } base::FilePath GetComponentUpdatedPepperFlashPath( const base::FilePath::StringType& version) { base::FilePath path; EXPECT_TRUE(PathService::Get( chrome::DIR_COMPONENT_UPDATED_PEPPER_FLASH_PLUGIN, &path)); path = path.Append(version); path = path.Append(chrome::kPepperFlashPluginFilename); return path; } base::FilePath GetBundledPepperFlashPath() { base::FilePath path; EXPECT_TRUE(PathService::Get(chrome::FILE_PEPPER_FLASH_PLUGIN, &path)); return path; } } // namespace class PluginPrefsTest : public ::testing::Test { public: virtual void SetUp() OVERRIDE { plugin_prefs_ = new PluginPrefs(); } void SetPolicyEnforcedPluginPatterns( const std::set<string16>& disabled, const std::set<string16>& disabled_exceptions, const std::set<string16>& enabled) { plugin_prefs_->SetPolicyEnforcedPluginPatterns( disabled, disabled_exceptions, enabled); } protected: void EnablePluginSynchronously(bool enabled, const base::FilePath& path, bool expected_can_change) { base::RunLoop run_loop; plugin_prefs_->EnablePlugin( enabled, path, base::Bind(&CanEnablePluginCallback, run_loop.QuitClosure(), expected_can_change)); run_loop.Run(); } scoped_refptr<PluginPrefs> plugin_prefs_; }; TEST_F(PluginPrefsTest, DisabledByPolicy) { std::set<string16> disabled_plugins; disabled_plugins.insert(ASCIIToUTF16("Disable this!")); disabled_plugins.insert(ASCIIToUTF16("*Google*")); SetPolicyEnforcedPluginPatterns(disabled_plugins, std::set<string16>(), std::set<string16>()); EXPECT_EQ(PluginPrefs::NO_POLICY, plugin_prefs_->PolicyStatusForPlugin(ASCIIToUTF16("42"))); EXPECT_EQ(PluginPrefs::POLICY_DISABLED, plugin_prefs_->PolicyStatusForPlugin( ASCIIToUTF16("Disable this!"))); EXPECT_EQ(PluginPrefs::POLICY_DISABLED, plugin_prefs_->PolicyStatusForPlugin(ASCIIToUTF16("Google Earth"))); } TEST_F(PluginPrefsTest, EnabledByPolicy) { std::set<string16> enabled_plugins; enabled_plugins.insert(ASCIIToUTF16("Enable that!")); enabled_plugins.insert(ASCIIToUTF16("PDF*")); SetPolicyEnforcedPluginPatterns(std::set<string16>(), std::set<string16>(), enabled_plugins); EXPECT_EQ(PluginPrefs::NO_POLICY, plugin_prefs_->PolicyStatusForPlugin(ASCIIToUTF16("42"))); EXPECT_EQ(PluginPrefs::POLICY_ENABLED, plugin_prefs_->PolicyStatusForPlugin(ASCIIToUTF16("Enable that!"))); EXPECT_EQ(PluginPrefs::POLICY_ENABLED, plugin_prefs_->PolicyStatusForPlugin(ASCIIToUTF16("PDF Reader"))); } TEST_F(PluginPrefsTest, EnabledAndDisabledByPolicy) { const string16 k42(ASCIIToUTF16("42")); const string16 kEnabled(ASCIIToUTF16("Enabled")); const string16 kEnabled2(ASCIIToUTF16("Enabled 2")); const string16 kEnabled3(ASCIIToUTF16("Enabled 3")); const string16 kException(ASCIIToUTF16("Exception")); const string16 kException2(ASCIIToUTF16("Exception 2")); const string16 kGoogleMars(ASCIIToUTF16("Google Mars")); const string16 kGoogleEarth(ASCIIToUTF16("Google Earth")); std::set<string16> disabled_plugins; std::set<string16> disabled_plugins_exceptions; std::set<string16> enabled_plugins; disabled_plugins.insert(kEnabled); disabled_plugins_exceptions.insert(kEnabled); enabled_plugins.insert(kEnabled); disabled_plugins_exceptions.insert(kException); disabled_plugins.insert(kEnabled2); enabled_plugins.insert(kEnabled2); disabled_plugins.insert(kException2); disabled_plugins_exceptions.insert(kException2); disabled_plugins_exceptions.insert(kEnabled3); enabled_plugins.insert(kEnabled3); SetPolicyEnforcedPluginPatterns(disabled_plugins, disabled_plugins_exceptions, enabled_plugins); EXPECT_EQ(PluginPrefs::NO_POLICY, plugin_prefs_->PolicyStatusForPlugin(k42)); EXPECT_EQ(PluginPrefs::POLICY_ENABLED, plugin_prefs_->PolicyStatusForPlugin(kEnabled)); EXPECT_EQ(PluginPrefs::POLICY_ENABLED, plugin_prefs_->PolicyStatusForPlugin(kEnabled2)); EXPECT_EQ(PluginPrefs::POLICY_ENABLED, plugin_prefs_->PolicyStatusForPlugin(kEnabled3)); EXPECT_EQ(PluginPrefs::NO_POLICY, plugin_prefs_->PolicyStatusForPlugin(kException)); EXPECT_EQ(PluginPrefs::NO_POLICY, plugin_prefs_->PolicyStatusForPlugin(kException2)); disabled_plugins.clear(); disabled_plugins_exceptions.clear(); enabled_plugins.clear(); disabled_plugins.insert(ASCIIToUTF16("*")); disabled_plugins_exceptions.insert(ASCIIToUTF16("*Google*")); enabled_plugins.insert(kGoogleEarth); SetPolicyEnforcedPluginPatterns(disabled_plugins, disabled_plugins_exceptions, enabled_plugins); EXPECT_EQ(PluginPrefs::POLICY_ENABLED, plugin_prefs_->PolicyStatusForPlugin(kGoogleEarth)); EXPECT_EQ(PluginPrefs::NO_POLICY, plugin_prefs_->PolicyStatusForPlugin(kGoogleMars)); EXPECT_EQ(PluginPrefs::POLICY_DISABLED, plugin_prefs_->PolicyStatusForPlugin(k42)); } TEST_F(PluginPrefsTest, UnifiedPepperFlashState) { base::ShadowingAtExitManager at_exit_manager_; // Destroys the PluginService. base::MessageLoop message_loop; content::TestBrowserThread ui_thread(BrowserThread::UI, &message_loop); webkit::npapi::MockPluginList plugin_list; PluginService::GetInstance()->SetPluginListForTesting(&plugin_list); PluginService::GetInstance()->Init(); plugin_prefs_->SetPluginListForTesting(&plugin_list); string16 component_updated_plugin_name( ASCIIToUTF16("Component-updated Pepper Flash")); webkit::WebPluginInfo component_updated_plugin_1( component_updated_plugin_name, GetComponentUpdatedPepperFlashPath(FILE_PATH_LITERAL("11.3.31.227")), ASCIIToUTF16("11.3.31.227"), ASCIIToUTF16("")); webkit::WebPluginInfo component_updated_plugin_2( component_updated_plugin_name, GetComponentUpdatedPepperFlashPath(FILE_PATH_LITERAL("11.3.31.228")), ASCIIToUTF16("11.3.31.228"), ASCIIToUTF16("")); webkit::WebPluginInfo bundled_plugin(ASCIIToUTF16("Pepper Flash"), GetBundledPepperFlashPath(), ASCIIToUTF16("11.3.31.229"), ASCIIToUTF16("")); plugin_list.AddPluginToLoad(component_updated_plugin_1); plugin_list.AddPluginToLoad(component_updated_plugin_2); plugin_list.AddPluginToLoad(bundled_plugin); // Set the state of any of the three plugins will affect the others. EnablePluginSynchronously(true, component_updated_plugin_1.path, true); EXPECT_TRUE(plugin_prefs_->IsPluginEnabled(component_updated_plugin_1)); EXPECT_TRUE(plugin_prefs_->IsPluginEnabled(component_updated_plugin_2)); EXPECT_TRUE(plugin_prefs_->IsPluginEnabled(bundled_plugin)); EnablePluginSynchronously(false, bundled_plugin.path, true); EXPECT_FALSE(plugin_prefs_->IsPluginEnabled(component_updated_plugin_1)); EXPECT_FALSE(plugin_prefs_->IsPluginEnabled(component_updated_plugin_2)); EXPECT_FALSE(plugin_prefs_->IsPluginEnabled(bundled_plugin)); EnablePluginSynchronously(true, component_updated_plugin_2.path, true); EXPECT_TRUE(plugin_prefs_->IsPluginEnabled(component_updated_plugin_1)); EXPECT_TRUE(plugin_prefs_->IsPluginEnabled(component_updated_plugin_2)); EXPECT_TRUE(plugin_prefs_->IsPluginEnabled(bundled_plugin)); std::set<string16> disabled_plugins; disabled_plugins.insert(component_updated_plugin_name); SetPolicyEnforcedPluginPatterns(disabled_plugins, std::set<string16>(), std::set<string16>()); // Policy settings should be respected. EXPECT_FALSE(plugin_prefs_->IsPluginEnabled(component_updated_plugin_1)); EXPECT_FALSE(plugin_prefs_->IsPluginEnabled(component_updated_plugin_2)); EXPECT_TRUE(plugin_prefs_->IsPluginEnabled(bundled_plugin)); EnablePluginSynchronously(false, bundled_plugin.path, true); EXPECT_FALSE(plugin_prefs_->IsPluginEnabled(bundled_plugin)); // Trying to change the state of a policy-enforced plugin should not take // effect. And it shouldn't change the state of other plugins either, even if // they are not restricted by any policy. EnablePluginSynchronously(true, component_updated_plugin_1.path, false); EXPECT_FALSE(plugin_prefs_->IsPluginEnabled(component_updated_plugin_1)); EXPECT_FALSE(plugin_prefs_->IsPluginEnabled(component_updated_plugin_2)); EXPECT_FALSE(plugin_prefs_->IsPluginEnabled(bundled_plugin)); EnablePluginSynchronously(true, bundled_plugin.path, true); EXPECT_FALSE(plugin_prefs_->IsPluginEnabled(component_updated_plugin_1)); EXPECT_FALSE(plugin_prefs_->IsPluginEnabled(component_updated_plugin_2)); EXPECT_TRUE(plugin_prefs_->IsPluginEnabled(bundled_plugin)); plugin_prefs_->SetPluginListForTesting(NULL); PluginService::GetInstance()->SetPluginListForTesting(NULL); }
39.988327
80
0.73718
pozdnyakov
66ea13aa778e838ccbb81d1729c4b485d3927fd3
27,043
cpp
C++
src/WtBtCore/HftMocker.cpp
v1otusc/wondertrader
fd65a052d26be32882f89e8e9dfcd1d7b8736a3b
[ "MIT" ]
null
null
null
src/WtBtCore/HftMocker.cpp
v1otusc/wondertrader
fd65a052d26be32882f89e8e9dfcd1d7b8736a3b
[ "MIT" ]
1
2022-03-21T06:51:59.000Z
2022-03-21T06:51:59.000Z
src/WtBtCore/HftMocker.cpp
v1otusc/wondertrader
fd65a052d26be32882f89e8e9dfcd1d7b8736a3b
[ "MIT" ]
null
null
null
/*! * \file HftMocker.cpp * \project WonderTrader * * \author Wesley * \date 2020/03/30 * * \brief */ #include "HftMocker.h" #include "WtHelper.h" #include <stdarg.h> #include <boost/filesystem.hpp> #include "../Includes/WTSVariant.hpp" #include "../Includes/WTSContractInfo.hpp" #include "../Share/decimal.h" #include "../Share/TimeUtils.hpp" #include "../Share/StrUtil.hpp" #include "../WTSTools/WTSLogger.h" uint32_t makeLocalOrderID() { static std::atomic<uint32_t> _auto_order_id{ 0 }; if (_auto_order_id == 0) { uint32_t curYear = TimeUtils::getCurDate() / 10000 * 10000 + 101; _auto_order_id = (uint32_t)((TimeUtils::getLocalTimeNow() - TimeUtils::makeTime(curYear, 0)) / 1000 * 50); } return _auto_order_id.fetch_add(1); } std::vector<uint32_t> splitVolume(uint32_t vol) { if (vol == 0) return std::move(std::vector<uint32_t>()); uint32_t minQty = 1; uint32_t maxQty = 100; uint32_t length = maxQty - minQty + 1; std::vector<uint32_t> ret; if (vol <= minQty) { ret.emplace_back(vol); } else { uint32_t left = vol; srand((uint32_t)time(NULL)); while (left > 0) { uint32_t curVol = minQty + (uint32_t)rand() % length; if (curVol >= left) curVol = left; if (curVol == 0) continue; ret.emplace_back(curVol); left -= curVol; } } return std::move(ret); } std::vector<double> splitVolume(double vol, double minQty = 1.0, double maxQty = 100.0, double qtyTick = 1.0) { auto length = (std::size_t)round((maxQty - minQty)/qtyTick) + 1; std::vector<double> ret; if (vol <= minQty) { ret.emplace_back(vol); } else { double left = vol; srand((uint32_t)time(NULL)); while (left > 0) { double curVol = minQty + (rand() % length)*qtyTick; if (curVol >= left) curVol = left; if (curVol == 0) continue; ret.emplace_back(curVol); left -= curVol; } } return std::move(ret); } uint32_t genRand(uint32_t maxVal = 10000) { srand(TimeUtils::getCurMin()); return rand() % maxVal; } inline uint32_t makeHftCtxId() { static std::atomic<uint32_t> _auto_context_id{ 6000 }; return _auto_context_id.fetch_add(1); } HftMocker::HftMocker(HisDataReplayer* replayer, const char* name) : IHftStraCtx(name) , _replayer(replayer) , _strategy(NULL) , _thrd(NULL) , _stopped(false) , _use_newpx(false) , _error_rate(0) , _has_hook(false) , _hook_valid(true) , _resumed(false) { _commodities = CommodityMap::create(); _context_id = makeHftCtxId(); } HftMocker::~HftMocker() { if(_strategy) { _factory._fact->deleteStrategy(_strategy); } _commodities->release(); } void HftMocker::procTask() { if (_tasks.empty()) { return; } _mtx_control.lock(); while (!_tasks.empty()) { Task& task = _tasks.front(); task(); { std::unique_lock<std::mutex> lck(_mtx); _tasks.pop(); } } _mtx_control.unlock(); } void HftMocker::postTask(Task task) { { std::unique_lock<std::mutex> lck(_mtx); _tasks.push(task); return; } if(_thrd == NULL) { _thrd.reset(new std::thread([this](){ while (!_stopped) { if(_tasks.empty()) { std::this_thread::sleep_for(std::chrono::milliseconds(1)); continue; } _mtx_control.lock(); while(!_tasks.empty()) { Task& task = _tasks.front(); task(); { std::unique_lock<std::mutex> lck(_mtx); _tasks.pop(); } } _mtx_control.unlock(); } })); } } bool HftMocker::init_hft_factory(WTSVariant* cfg) { if (cfg == NULL) return false; const char* module = cfg->getCString("module"); _use_newpx = cfg->getBoolean("use_newpx"); _error_rate = cfg->getUInt32("error_rate"); DllHandle hInst = DLLHelper::load_library(module); if (hInst == NULL) return false; FuncCreateHftStraFact creator = (FuncCreateHftStraFact)DLLHelper::get_symbol(hInst, "createStrategyFact"); if (creator == NULL) { DLLHelper::free_library(hInst); return false; } _factory._module_inst = hInst; _factory._module_path = module; _factory._creator = creator; _factory._remover = (FuncDeleteHftStraFact)DLLHelper::get_symbol(hInst, "deleteStrategyFact"); _factory._fact = _factory._creator(); WTSVariant* cfgStra = cfg->get("strategy"); if(cfgStra) { _strategy = _factory._fact->createStrategy(cfgStra->getCString("name"), "hft"); _strategy->init(cfgStra->get("params")); } return true; } void HftMocker::handle_tick(const char* stdCode, WTSTickData* curTick) { on_tick(stdCode, curTick); } void HftMocker::handle_order_detail(const char* stdCode, WTSOrdDtlData* curOrdDtl) { on_order_detail(stdCode, curOrdDtl); } void HftMocker::handle_order_queue(const char* stdCode, WTSOrdQueData* curOrdQue) { on_order_queue(stdCode, curOrdQue); } void HftMocker::handle_transaction(const char* stdCode, WTSTransData* curTrans) { on_transaction(stdCode, curTrans); } void HftMocker::handle_bar_close(const char* stdCode, const char* period, uint32_t times, WTSBarStruct* newBar) { on_bar(stdCode, period, times, newBar); } void HftMocker::handle_init() { on_init(); on_channel_ready(); } void HftMocker::handle_schedule(uint32_t uDate, uint32_t uTime) { //on_schedule(uDate, uTime); } void HftMocker::handle_session_begin(uint32_t curTDate) { on_session_begin(curTDate); } void HftMocker::handle_session_end(uint32_t curTDate) { on_session_end(curTDate); } void HftMocker::handle_replay_done() { dump_outputs(); this->on_bactest_end(); } void HftMocker::on_bar(const char* stdCode, const char* period, uint32_t times, WTSBarStruct* newBar) { if (_strategy) _strategy->on_bar(this, stdCode, period, times, newBar); } void HftMocker::enable_hook(bool bEnabled /* = true */) { _hook_valid = bEnabled; WTSLogger::log_dyn("strategy", _name.c_str(), LL_DEBUG, "Calculating hook %s", bEnabled ? "enabled" : "disabled"); } void HftMocker::install_hook() { _has_hook = true; WTSLogger::log_dyn("strategy", _name.c_str(), LL_DEBUG, "HFT hook installed"); } void HftMocker::step_tick() { if (!_has_hook) return; WTSLogger::log_dyn("strategy", _name.c_str(), LL_DEBUG, "Notify calc thread, wait for calc done"); while (!_resumed) _cond_calc.notify_all(); { StdUniqueLock lock(_mtx_calc); _cond_calc.wait(_mtx_calc); WTSLogger::log_dyn("strategy", _name.c_str(), LL_DEBUG, "Calc done notified"); _resumed = false; } } void HftMocker::on_tick(const char* stdCode, WTSTickData* newTick) { _price_map[stdCode] = newTick->price(); { std::unique_lock<std::recursive_mutex> lck(_mtx_control); } update_dyn_profit(stdCode, newTick); procTask(); if (!_orders.empty()) { OrderIDs ids; for (auto it = _orders.begin(); it != _orders.end(); it++) { uint32_t localid = it->first; bool bNeedErase = procOrder(localid); if (bNeedErase) ids.emplace_back(localid); } for(uint32_t localid : ids) { auto it = _orders.find(localid); _orders.erase(it); } } if (_has_hook && _hook_valid) { WTSLogger::log_dyn("strategy", _name.c_str(), LL_DEBUG, "Waiting for resume notify"); StdUniqueLock lock(_mtx_calc); _cond_calc.wait(_mtx_calc); WTSLogger::log_dyn("strategy", _name.c_str(), LL_DEBUG, "Calc resumed"); _resumed = true; } on_tick_updated(stdCode, newTick); if (_has_hook && _hook_valid) { WTSLogger::log_dyn("strategy", _name.c_str(), LL_DEBUG, "Calc done, notify control thread"); while (_resumed) _cond_calc.notify_all(); } } void HftMocker::on_tick_updated(const char* stdCode, WTSTickData* newTick) { auto it = _tick_subs.find(stdCode); if (it == _tick_subs.end()) return; if (_strategy) _strategy->on_tick(this, stdCode, newTick); } void HftMocker::on_order_queue(const char* stdCode, WTSOrdQueData* newOrdQue) { on_ordque_updated(stdCode, newOrdQue); } void HftMocker::on_ordque_updated(const char* stdCode, WTSOrdQueData* newOrdQue) { if (_strategy) _strategy->on_order_queue(this, stdCode, newOrdQue); } void HftMocker::on_order_detail(const char* stdCode, WTSOrdDtlData* newOrdDtl) { on_orddtl_updated(stdCode, newOrdDtl); } void HftMocker::on_orddtl_updated(const char* stdCode, WTSOrdDtlData* newOrdDtl) { if (_strategy) _strategy->on_order_detail(this, stdCode, newOrdDtl); } void HftMocker::on_transaction(const char* stdCode, WTSTransData* newTrans) { on_trans_updated(stdCode, newTrans); } void HftMocker::on_trans_updated(const char* stdCode, WTSTransData* newTrans) { if (_strategy) _strategy->on_transaction(this, stdCode, newTrans); } uint32_t HftMocker::id() { return _context_id; } void HftMocker::on_init() { if (_strategy) _strategy->on_init(this); } void HftMocker::on_session_begin(uint32_t curTDate) { //每个交易日开始,要把冻结持仓置零 for (auto& it : _pos_map) { const char* stdCode = it.first.c_str(); PosInfo& pInfo = (PosInfo&)it.second; if (!decimal::eq(pInfo._frozen, 0)) { log_debug("%.0f of %s frozen released on %u", pInfo._frozen, stdCode, curTDate); pInfo._frozen = 0; } } if (_strategy) _strategy->on_session_begin(this, curTDate); } void HftMocker::on_session_end(uint32_t curTDate) { uint32_t curDate = curTDate;// _replayer->get_trading_date(); double total_profit = 0; double total_dynprofit = 0; for (auto it = _pos_map.begin(); it != _pos_map.end(); it++) { const char* stdCode = it->first.c_str(); const PosInfo& pInfo = it->second; total_profit += pInfo._closeprofit; total_dynprofit += pInfo._dynprofit; } _fund_logs << StrUtil::printf("%d,%.2f,%.2f,%.2f,%.2f\n", curDate, _fund_info._total_profit, _fund_info._total_dynprofit, _fund_info._total_profit + _fund_info._total_dynprofit - _fund_info._total_fees, _fund_info._total_fees); if (_strategy) _strategy->on_session_end(this, curTDate); } double HftMocker::stra_get_undone(const char* stdCode) { double ret = 0; for (auto it = _orders.begin(); it != _orders.end(); it++) { const OrderInfo& ordInfo = it->second; if (strcmp(ordInfo._code, stdCode) == 0) { ret += ordInfo._left * ordInfo._isBuy ? 1 : -1; } } return ret; } bool HftMocker::stra_cancel(uint32_t localid) { postTask([this, localid](){ auto it = _orders.find(localid); if (it == _orders.end()) return; StdLocker<StdRecurMutex> lock(_mtx_ords); OrderInfo& ordInfo = (OrderInfo&)it->second; ordInfo._left = 0; on_order(localid, ordInfo._code, ordInfo._isBuy, ordInfo._total, ordInfo._left, ordInfo._price, true, ordInfo._usertag); _orders.erase(it); }); return true; } OrderIDs HftMocker::stra_cancel(const char* stdCode, bool isBuy, double qty /* = 0 */) { OrderIDs ret; uint32_t cnt = 0; for (auto it = _orders.begin(); it != _orders.end(); it++) { const OrderInfo& ordInfo = it->second; if(ordInfo._isBuy == isBuy && strcmp(ordInfo._code, stdCode) == 0) { double left = ordInfo._left; stra_cancel(it->first); ret.emplace_back(it->first); cnt++; if (left < qty) qty -= left; else break; } } return ret; } OrderIDs HftMocker::stra_buy(const char* stdCode, double price, double qty, const char* userTag, int flag /* = 0 */) { WTSCommodityInfo* commInfo = _replayer->get_commodity_info(stdCode); if (commInfo == NULL) { log_error("Cannot find corresponding commodity info of %s", stdCode); return OrderIDs(); } if (decimal::le(qty, 0)) { log_error("Entrust error: qty {} <= 0", qty); return OrderIDs(); } uint32_t localid = makeLocalOrderID(); OrderInfo order; order._localid = localid; strcpy(order._code, stdCode); strcpy(order._usertag, userTag); order._isBuy = true; order._price = price; order._total = qty; order._left = qty; { _mtx_ords.lock(); _orders[localid] = order; _mtx_ords.unlock(); } postTask([this, localid](){ const OrderInfo& ordInfo = _orders[localid]; on_entrust(localid, ordInfo._code, true, "下单成功", ordInfo._usertag); }); OrderIDs ids; ids.emplace_back(localid); return ids; } void HftMocker::on_order(uint32_t localid, const char* stdCode, bool isBuy, double totalQty, double leftQty, double price, bool isCanceled /* = false */, const char* userTag /* = "" */) { if(_strategy) _strategy->on_order(this, localid, stdCode, isBuy, totalQty, leftQty, price, isCanceled, userTag); } void HftMocker::on_trade(uint32_t localid, const char* stdCode, bool isBuy, double vol, double price, const char* userTag/* = ""*/) { const PosInfo& posInfo = _pos_map[stdCode]; double curPos = posInfo._volume + vol * (isBuy ? 1 : -1); do_set_position(stdCode, curPos, price, userTag); if (_strategy) _strategy->on_trade(this, localid, stdCode, isBuy, vol, price, userTag); } void HftMocker::on_entrust(uint32_t localid, const char* stdCode, bool bSuccess, const char* message, const char* userTag/* = ""*/) { if (_strategy) _strategy->on_entrust(localid, bSuccess, message, userTag); } void HftMocker::on_channel_ready() { if (_strategy) _strategy->on_channel_ready(this); } void HftMocker::update_dyn_profit(const char* stdCode, WTSTickData* newTick) { auto it = _pos_map.find(stdCode); if (it != _pos_map.end()) { PosInfo& pInfo = (PosInfo&)it->second; if (pInfo._volume == 0) { pInfo._dynprofit = 0; } else { bool isLong = decimal::gt(pInfo._volume, 0); double price = isLong ? newTick->bidprice(0) : newTick->askprice(0); WTSCommodityInfo* commInfo = _replayer->get_commodity_info(stdCode); double dynprofit = 0; for (auto pit = pInfo._details.begin(); pit != pInfo._details.end(); pit++) { DetailInfo& dInfo = *pit; dInfo._profit = dInfo._volume*(price - dInfo._price)*commInfo->getVolScale()*(dInfo._long ? 1 : -1); if (dInfo._profit > 0) dInfo._max_profit = max(dInfo._profit, dInfo._max_profit); else if (dInfo._profit < 0) dInfo._max_loss = min(dInfo._profit, dInfo._max_loss); dynprofit += dInfo._profit; } pInfo._dynprofit = dynprofit; } } } bool HftMocker::procOrder(uint32_t localid) { auto it = _orders.find(localid); if (it == _orders.end()) return false; StdLocker<StdRecurMutex> lock(_mtx_ords); OrderInfo& ordInfo = (OrderInfo&)it->second; //第一步,如果在撤单概率中,则执行撤单 if(_error_rate>0 && genRand(10000)<=_error_rate) { on_order(localid, ordInfo._code, ordInfo._isBuy, ordInfo._total, ordInfo._left, ordInfo._price, true, ordInfo._usertag); log_info("Random error order: %u", localid); return true; } else { on_order(localid, ordInfo._code, ordInfo._isBuy, ordInfo._total, ordInfo._left, ordInfo._price, false, ordInfo._usertag); } WTSTickData* curTick = stra_get_last_tick(ordInfo._code); if (curTick == NULL) return false; double curPx = curTick->price(); double orderQty = ordInfo._isBuy ? curTick->askqty(0) : curTick->bidqty(0); //看对手盘的数量 if (decimal::eq(orderQty, 0.0)) return false; if (!_use_newpx) { curPx = ordInfo._isBuy ? curTick->askprice(0) : curTick->bidprice(0); //if (curPx == 0.0) if(decimal::eq(curPx, 0.0)) { curTick->release(); return false; } } curTick->release(); //如果没有成交条件,则退出逻辑 if(!decimal::eq(ordInfo._price, 0.0)) { if(ordInfo._isBuy && decimal::gt(curPx, ordInfo._price)) { //买单,但是当前价大于限价,不成交 return false; } if (!ordInfo._isBuy && decimal::lt(curPx, ordInfo._price)) { //卖单,但是当前价小于限价,不成交 return false; } } /* * 下面就要模拟成交了 */ double maxQty = min(orderQty, ordInfo._left); auto vols = splitVolume((uint32_t)maxQty); for(uint32_t curQty : vols) { on_trade(ordInfo._localid, ordInfo._code, ordInfo._isBuy, curQty, curPx, ordInfo._usertag); ordInfo._left -= curQty; on_order(localid, ordInfo._code, ordInfo._isBuy, ordInfo._total, ordInfo._left, ordInfo._price, false, ordInfo._usertag); double curPos = stra_get_position(ordInfo._code); _sig_logs << _replayer->get_date() << "." << _replayer->get_raw_time() << "." << _replayer->get_secs() << "," << (ordInfo._isBuy ? "+" : "-") << curQty << "," << curPos << "," << curPx << std::endl; } //if(ordInfo._left == 0) if(decimal::eq(ordInfo._left, 0.0)) { return true; } return false; } OrderIDs HftMocker::stra_sell(const char* stdCode, double price, double qty, const char* userTag, int flag /* = 0 */) { WTSCommodityInfo* commInfo = _replayer->get_commodity_info(stdCode); if (commInfo == NULL) { log_error("Cannot find corresponding commodity info of %s", stdCode); return OrderIDs(); } if (decimal::le(qty, 0)) { log_error("Entrust error: qty {} <= 0", qty); return OrderIDs(); } //如果不能做空,则要看可用持仓 if(!commInfo->canShort()) { double curPos = stra_get_position(stdCode, true);//只读可用持仓 if(decimal::gt(qty, curPos)) { log_error("No enough position of %s to sell", stdCode); return OrderIDs(); } } uint32_t localid = makeLocalOrderID(); OrderInfo order; order._localid = localid; strcpy(order._code, stdCode); strcpy(order._usertag, userTag); order._isBuy = false; order._price = price; order._total = qty; order._left = qty; { StdLocker<StdRecurMutex> lock(_mtx_ords); _orders[localid] = order; } postTask([this, localid]() { const OrderInfo& ordInfo = _orders[localid]; on_entrust(localid, ordInfo._code, true, "下单成功", ordInfo._usertag); }); OrderIDs ids; ids.emplace_back(localid); return ids; } WTSCommodityInfo* HftMocker::stra_get_comminfo(const char* stdCode) { return _replayer->get_commodity_info(stdCode); } WTSKlineSlice* HftMocker::stra_get_bars(const char* stdCode, const char* period, uint32_t count) { std::string basePeriod = ""; uint32_t times = 1; if (strlen(period) > 1) { basePeriod.append(period, 1); times = strtoul(period + 1, NULL, 10); } else { basePeriod = period; } return _replayer->get_kline_slice(stdCode, basePeriod.c_str(), count, times); } WTSTickSlice* HftMocker::stra_get_ticks(const char* stdCode, uint32_t count) { return _replayer->get_tick_slice(stdCode, count); } WTSOrdQueSlice* HftMocker::stra_get_order_queue(const char* stdCode, uint32_t count) { return _replayer->get_order_queue_slice(stdCode, count); } WTSOrdDtlSlice* HftMocker::stra_get_order_detail(const char* stdCode, uint32_t count) { return _replayer->get_order_detail_slice(stdCode, count); } WTSTransSlice* HftMocker::stra_get_transaction(const char* stdCode, uint32_t count) { return _replayer->get_transaction_slice(stdCode, count); } WTSTickData* HftMocker::stra_get_last_tick(const char* stdCode) { return _replayer->get_last_tick(stdCode); } double HftMocker::stra_get_position(const char* stdCode, bool bOnlyValid/* = false*/) { const PosInfo& pInfo = _pos_map[stdCode]; if (bOnlyValid) { //这里理论上,只有多头才会进到这里 //其他地方要保证,空头持仓的话,_frozen要为0 return pInfo._volume - pInfo._frozen; } else return pInfo._volume; } double HftMocker::stra_get_position_profit(const char* stdCode) { const PosInfo& pInfo = _pos_map[stdCode]; return pInfo._dynprofit; } double HftMocker::stra_get_price(const char* stdCode) { return _replayer->get_cur_price(stdCode); } uint32_t HftMocker::stra_get_date() { return _replayer->get_date(); } uint32_t HftMocker::stra_get_time() { return _replayer->get_raw_time(); } uint32_t HftMocker::stra_get_secs() { return _replayer->get_secs(); } void HftMocker::stra_sub_ticks(const char* stdCode) { /* * By Wesley @ 2022.03.01 * 主动订阅tick会在本地记一下 * tick数据回调的时候先检查一下 */ _tick_subs.insert(stdCode); _replayer->sub_tick(_context_id, stdCode); } void HftMocker::stra_sub_order_queues(const char* stdCode) { _replayer->sub_order_queue(_context_id, stdCode); } void HftMocker::stra_sub_order_details(const char* stdCode) { _replayer->sub_order_detail(_context_id, stdCode); } void HftMocker::stra_sub_transactions(const char* stdCode) { _replayer->sub_transaction(_context_id, stdCode); } void HftMocker::stra_log_info(const char* message) { WTSLogger::log_dyn_raw("strategy", _name.c_str(), LL_INFO, message); } void HftMocker::stra_log_debug(const char* message) { WTSLogger::log_dyn_raw("strategy", _name.c_str(), LL_DEBUG, message); } void HftMocker::stra_log_error(const char* message) { WTSLogger::log_dyn_raw("strategy", _name.c_str(), LL_ERROR, message); } const char* HftMocker::stra_load_user_data(const char* key, const char* defVal /*= ""*/) { auto it = _user_datas.find(key); if (it != _user_datas.end()) return it->second.c_str(); return defVal; } void HftMocker::stra_save_user_data(const char* key, const char* val) { _user_datas[key] = val; _ud_modified = true; } void HftMocker::dump_outputs() { std::string folder = WtHelper::getOutputDir(); folder += _name; folder += "/"; boost::filesystem::create_directories(folder.c_str()); std::string filename = folder + "trades.csv"; std::string content = "code,time,direct,action,price,qty,fee,usertag\n"; content += _trade_logs.str(); StdFile::write_file_content(filename.c_str(), (void*)content.c_str(), content.size()); filename = folder + "closes.csv"; content = "code,direct,opentime,openprice,closetime,closeprice,qty,profit,maxprofit,maxloss,totalprofit,entertag,exittag\n"; content += _close_logs.str(); StdFile::write_file_content(filename.c_str(), (void*)content.c_str(), content.size()); filename = folder + "funds.csv"; content = "date,closeprofit,positionprofit,dynbalance,fee\n"; content += _fund_logs.str(); StdFile::write_file_content(filename.c_str(), (void*)content.c_str(), content.size()); filename = folder + "signals.csv"; content = "time, action, position, price\n"; content += _sig_logs.str(); StdFile::write_file_content(filename.c_str(), (void*)content.c_str(), content.size()); } void HftMocker::log_trade(const char* stdCode, bool isLong, bool isOpen, uint64_t curTime, double price, double qty, double fee, const char* userTag/* = ""*/) { _trade_logs << stdCode << "," << curTime << "," << (isLong ? "LONG" : "SHORT") << "," << (isOpen ? "OPEN" : "CLOSE") << "," << price << "," << qty << "," << fee << "," << userTag << "\n"; } void HftMocker::log_close(const char* stdCode, bool isLong, uint64_t openTime, double openpx, uint64_t closeTime, double closepx, double qty, double profit, double maxprofit, double maxloss, double totalprofit /* = 0 */, const char* enterTag/* = ""*/, const char* exitTag/* = ""*/) { _close_logs << stdCode << "," << (isLong ? "LONG" : "SHORT") << "," << openTime << "," << openpx << "," << closeTime << "," << closepx << "," << qty << "," << profit << "," << maxprofit << "," << maxloss << "," << totalprofit << "," << enterTag << "," << exitTag << "\n"; } void HftMocker::do_set_position(const char* stdCode, double qty, double price /* = 0.0 */, const char* userTag /*= ""*/) { PosInfo& pInfo = _pos_map[stdCode]; double curPx = price; if (decimal::eq(price, 0.0)) curPx = _price_map[stdCode]; uint64_t curTm = (uint64_t)_replayer->get_date() * 1000000000 + (uint64_t)_replayer->get_min_time()*100000 + _replayer->get_secs(); uint32_t curTDate = _replayer->get_trading_date(); //手数相等则不用操作了 if (decimal::eq(pInfo._volume, qty)) return; log_info("[%04u.%05u] %s position updated: %.0f -> %0.f", _replayer->get_min_time(), _replayer->get_secs(), stdCode, pInfo._volume, qty); WTSCommodityInfo* commInfo = _replayer->get_commodity_info(stdCode); if (commInfo == NULL) return; //成交价 double trdPx = curPx; double diff = qty - pInfo._volume; bool isBuy = decimal::gt(diff, 0.0); if (decimal::gt(pInfo._volume*diff, 0))//当前持仓和仓位变化方向一致, 增加一条明细, 增加数量即可 { pInfo._volume = qty; //如果T+1,则冻结仓位要增加 if (commInfo->isT1()) { //ASSERT(diff>0); pInfo._frozen += diff; log_debug("%s frozen position up to %.0f", stdCode, pInfo._frozen); } DetailInfo dInfo; dInfo._long = decimal::gt(qty, 0); dInfo._price = trdPx; dInfo._volume = abs(diff); dInfo._opentime = curTm; dInfo._opentdate = curTDate; strcpy(dInfo._usertag, userTag); pInfo._details.emplace_back(dInfo); double fee = _replayer->calc_fee(stdCode, trdPx, abs(diff), 0); _fund_info._total_fees += fee; log_trade(stdCode, dInfo._long, true, curTm, trdPx, abs(diff), fee, userTag); } else {//持仓方向和仓位变化方向不一致,需要平仓 double left = abs(diff); pInfo._volume = qty; if (decimal::eq(pInfo._volume, 0)) pInfo._dynprofit = 0; uint32_t count = 0; for (auto it = pInfo._details.begin(); it != pInfo._details.end(); it++) { DetailInfo& dInfo = *it; double maxQty = min(dInfo._volume, left); if (decimal::eq(maxQty, 0)) continue; double maxProf = dInfo._max_profit * maxQty / dInfo._volume; double maxLoss = dInfo._max_loss * maxQty / dInfo._volume; dInfo._volume -= maxQty; left -= maxQty; if (decimal::eq(dInfo._volume, 0)) count++; double profit = (trdPx - dInfo._price) * maxQty * commInfo->getVolScale(); if (!dInfo._long) profit *= -1; pInfo._closeprofit += profit; pInfo._dynprofit = pInfo._dynprofit*dInfo._volume / (dInfo._volume + maxQty);//浮盈也要做等比缩放 _fund_info._total_profit += profit; double fee = _replayer->calc_fee(stdCode, trdPx, maxQty, dInfo._opentdate == curTDate ? 2 : 1); _fund_info._total_fees += fee; //这里写成交记录 log_trade(stdCode, dInfo._long, false, curTm, trdPx, maxQty, fee, userTag); //这里写平仓记录 log_close(stdCode, dInfo._long, dInfo._opentime, dInfo._price, curTm, trdPx, maxQty, profit, maxProf, maxLoss, pInfo._closeprofit, dInfo._usertag, userTag); if (left == 0) break; } //需要清理掉已经平仓完的明细 while (count > 0) { auto it = pInfo._details.begin(); pInfo._details.erase(it); count--; } //最后,如果还有剩余的,则需要反手了 if (left > 0) { left = left * qty / abs(qty); //如果T+1,则冻结仓位要增加 if (commInfo->isT1()) { pInfo._frozen += left; log_debug("%s frozen position up to %.0f", stdCode, pInfo._frozen); } DetailInfo dInfo; dInfo._long = decimal::gt(qty, 0); dInfo._price = trdPx; dInfo._volume = abs(left); dInfo._opentime = curTm; dInfo._opentdate = curTDate; strcpy(dInfo._usertag, userTag); pInfo._details.emplace_back(dInfo); //这里还需要写一笔成交记录 double fee = _replayer->calc_fee(stdCode, trdPx, abs(left), 0); _fund_info._total_fees += fee; log_trade(stdCode, dInfo._long, true, curTm, trdPx, abs(left), fee, userTag); } } }
24.947417
191
0.662205
v1otusc
66eb579acb78b915f121611e3a54e62add3b774a
663
cpp
C++
test/cpp/LIM2Metrics/HalsteadMetrics/OperatorOverloading/operator_overloading.cpp
sagodiz/SonarQube-plug-in
4f8e111baecc4c9f9eaa5cd3d7ebeb1e365ace2c
[ "BSD-4-Clause" ]
20
2015-06-16T17:39:10.000Z
2022-03-20T22:39:40.000Z
test/cpp/LIM2Metrics/HalsteadMetrics/OperatorOverloading/operator_overloading.cpp
sagodiz/SonarQube-plug-in
4f8e111baecc4c9f9eaa5cd3d7ebeb1e365ace2c
[ "BSD-4-Clause" ]
29
2015-12-29T19:07:22.000Z
2022-03-22T10:39:02.000Z
test/cpp/LIM2Metrics/HalsteadMetrics/OperatorOverloading/operator_overloading.cpp
sagodiz/SonarQube-plug-in
4f8e111baecc4c9f9eaa5cd3d7ebeb1e365ace2c
[ "BSD-4-Clause" ]
12
2015-08-28T01:22:18.000Z
2021-09-25T08:17:31.000Z
class Operators { public: void* operator new[](size_t size) throw() { return nullptr; } void* operator new (size_t size) throw(){ return nullptr; } int operator+(const Operators& o) const { return 2; } Operators operator++() { return *this; } Operators operator++(int) { return *this; } /** * Operators (8, 6): void, ++ (pre), * x2, this x2, ++ (post) x2, ; x2 * Operands (1): pluszPlusz */ void pluszPlusz() { ++*this; (*this)++++; //this->operator++(); //this->operator++(2); } }; int main() { return 0; }
17
73
0.475113
sagodiz
66eb62e7baace7e5649dc0102ffc1764845184e4
3,769
cpp
C++
custom_opengl_wrapper/custom_opengl_wrapper/Mesh.cpp
mallocc/custom_opengl_wrapper
2384615c624b32947ae198af0cb5fb5f4371ffe2
[ "MIT" ]
null
null
null
custom_opengl_wrapper/custom_opengl_wrapper/Mesh.cpp
mallocc/custom_opengl_wrapper
2384615c624b32947ae198af0cb5fb5f4371ffe2
[ "MIT" ]
null
null
null
custom_opengl_wrapper/custom_opengl_wrapper/Mesh.cpp
mallocc/custom_opengl_wrapper
2384615c624b32947ae198af0cb5fb5f4371ffe2
[ "MIT" ]
null
null
null
#include "Mesh.h" #include "CLog.h" #include "StringFormat.h" using gfx::engine::Mesh; namespace { const char * CLASSNAME = "Mesh"; } // Buffers Vertex data into the VBO void Mesh::init(std::vector<gfx::Vertex_T> * d) { m_data_size = d->size(); glGenVertexArrays(1, &m_vao); glBindVertexArray(m_vao); glGenBuffers(1, &m_buffer); glBindBuffer(GL_ARRAY_BUFFER, m_buffer); glBufferData(GL_ARRAY_BUFFER, m_data_size * sizeof(struct gfx::Vertex_T), d->data(), GL_STATIC_DRAW); glVertexAttribPointer((GLuint)0, 3, GL_FLOAT, GL_FALSE, sizeof(struct gfx::Vertex_T), (const GLvoid*)offsetof(struct gfx::Vertex_T, position)); glEnableVertexAttribArray(0); glVertexAttribPointer((GLuint)1, 3, GL_FLOAT, GL_FALSE, sizeof(struct gfx::Vertex_T), (const GLvoid*)offsetof(struct gfx::Vertex_T, color)); glEnableVertexAttribArray(1); glVertexAttribPointer((GLuint)2, 3, GL_FLOAT, GL_FALSE, sizeof(struct gfx::Vertex_T), (const GLvoid*)offsetof(struct gfx::Vertex_T, normal)); glEnableVertexAttribArray(2); glVertexAttribPointer((GLuint)3, 2, GL_FLOAT, GL_FALSE, sizeof(struct gfx::Vertex_T), (const GLvoid*)offsetof(struct gfx::Vertex_T, uv)); glEnableVertexAttribArray(3); glVertexAttribPointer((GLuint)4, 3, GL_FLOAT, GL_FALSE, sizeof(struct gfx::Vertex_T), (const GLvoid*)offsetof(struct gfx::Vertex_T, tangent)); glEnableVertexAttribArray(4); glBindVertexArray(0); glFlush(); CINFO(alib::StringFormat(" buffered into VAO %0").arg(m_vao).str()); } // Loads image file into a texture void Mesh::load_textures(const char *texfilename) { if (texfilename != "") { m_tex = alib::ImageLoader::loadTextureFromImage(texfilename); CINFO(alib::StringFormat(" %0 -> Texture ID %1").arg(texfilename).arg(m_tex).str()); } else { CINFO(" no texture file loaded"); } } // Draws the mesh including linking the model matrix void Mesh::draw(int wire_frame, gfx::engine::MeshHandle_T handles) { handles.modelMatHandle->load(get_model_mat()); draw_array(wire_frame, handles.textureHandle); } // Draws just the VBO and activating the texture void Mesh::draw_array(int wire_frame, gfx::engine::VarHandle *texture_handle) { // load the textures if (m_tex != GL_TEXTURE0) { load_texture_handle(texture_handle); glActiveTexture(GL_TEXTURE0 + m_tex); glBindTexture(GL_TEXTURE_2D, m_tex); } // draw the data glBindVertexArray(m_vao); glDrawArrays(wire_frame ? GL_LINE_LOOP : GL_TRIANGLES, 0, m_data_size); glBindVertexArray(0); // unload the texture if (m_tex != GL_TEXTURE0) { glActiveTexture(GL_TEXTURE0 + m_tex); glBindTexture(GL_TEXTURE_2D, GL_TEXTURE0); } glActiveTexture(GL_TEXTURE0); glFinish(); } // Override the texture handle seperately void Mesh::load_texture_handle(gfx::engine::VarHandle * handle) { handle->load(m_tex); } // Sets the texture void Mesh::set_tex(GLuint tex) { this->m_tex = tex; } // Get the model matrix glm::mat4 Mesh::get_model_mat() { return glm::translate(glm::mat4(1.), m_pos) * glm::rotate(glm::mat4(1.), m_theta, m_rotation) * glm::rotate(glm::mat4(1.), m_pre_theta, m_pre_rotation) * glm::scale(glm::mat4(1.), m_scale); } Mesh::Mesh() {} // Texture filename, Vertex data pack, world position, dynamic axis of rotation, and amount, static axis of rotation, and amount, scale vector. Mesh::Mesh( const char *texfilename, std::vector<gfx::Vertex_T> data, glm::vec3 _pos, glm::vec3 _rotation, GLfloat _theta, glm::vec3 _pre_rotation, GLfloat _pre_theta, glm::vec3 _scale ) { CINFO("Loading new Mesh..."); CINFO(alib::StringFormat(" Vertex count = %0").arg(data.size()).str()); m_pos = _pos; m_rotation = _rotation; m_theta = _theta; m_scale = _scale; m_pre_rotation = _pre_rotation; m_pre_theta = _pre_theta; load_textures(texfilename); init(&data); }
27.510949
144
0.728841
mallocc
66eb96db8ae4810dc6bbda0ebcd0bd7d351ed05c
5,785
cpp
C++
src/network/udp_socket.cpp
Revolution-Populi/fc
02b7593a96b02d9966358c59d22f344d86fa9a19
[ "BSL-1.0", "Apache-2.0", "Zlib" ]
37
2017-02-04T09:42:48.000Z
2021-02-17T14:59:15.000Z
src/network/udp_socket.cpp
Revolution-Populi/fc
02b7593a96b02d9966358c59d22f344d86fa9a19
[ "BSL-1.0", "Apache-2.0", "Zlib" ]
120
2017-11-09T19:46:40.000Z
2022-01-20T18:26:23.000Z
src/network/udp_socket.cpp
Revolution-Populi/fc
02b7593a96b02d9966358c59d22f344d86fa9a19
[ "BSL-1.0", "Apache-2.0", "Zlib" ]
109
2017-01-16T14:24:31.000Z
2022-03-18T21:10:07.000Z
#include <fc/network/udp_socket.hpp> #include <fc/network/ip.hpp> #include <fc/fwd_impl.hpp> #include <fc/asio.hpp> namespace fc { class udp_socket::impl { public: impl():_sock( fc::asio::default_io_service() ){} ~impl(){ // _sock.cancel(); } boost::asio::ip::udp::socket _sock; }; boost::asio::ip::udp::endpoint to_asio_ep( const fc::ip::endpoint& e ) { return boost::asio::ip::udp::endpoint(boost::asio::ip::address_v4(e.get_address()), e.port() ); } fc::ip::endpoint to_fc_ep( const boost::asio::ip::udp::endpoint& e ) { return fc::ip::endpoint( e.address().to_v4().to_ulong(), e.port() ); } udp_socket::udp_socket() :my( new impl() ) { } udp_socket::udp_socket( const udp_socket& s ) :my(s.my) { } udp_socket::~udp_socket() { try { my->_sock.close(); //close boost socket to make any pending reads run their completion handler } catch (...) //avoid destructor throw and likely this is just happening because socket wasn't open. { } } size_t udp_socket::send_to( const char* buffer, size_t length, const ip::endpoint& to ) { try { return my->_sock.send_to( boost::asio::buffer(buffer, length), to_asio_ep(to) ); } catch( const boost::system::system_error& e ) { if( e.code() != boost::asio::error::would_block ) throw; } promise<size_t>::ptr completion_promise = promise<size_t>::create("udp_socket::send_to"); my->_sock.async_send_to( boost::asio::buffer(buffer, length), to_asio_ep(to), asio::detail::read_write_handler(completion_promise) ); return completion_promise->wait(); } size_t udp_socket::send_to( const std::shared_ptr<const char>& buffer, size_t length, const fc::ip::endpoint& to ) { try { return my->_sock.send_to( boost::asio::buffer(buffer.get(), length), to_asio_ep(to) ); } catch( const boost::system::system_error& e ) { if( e.code() != boost::asio::error::would_block ) throw; } promise<size_t>::ptr completion_promise = promise<size_t>::create("udp_socket::send_to"); my->_sock.async_send_to( boost::asio::buffer(buffer.get(), length), to_asio_ep(to), asio::detail::read_write_handler_with_buffer(completion_promise, buffer) ); return completion_promise->wait(); } void udp_socket::open() { my->_sock.open( boost::asio::ip::udp::v4() ); my->_sock.non_blocking(true); } void udp_socket::set_receive_buffer_size( size_t s ) { my->_sock.set_option(boost::asio::socket_base::receive_buffer_size(s) ); } void udp_socket::bind( const fc::ip::endpoint& e ) { my->_sock.bind( to_asio_ep(e) ); } size_t udp_socket::receive_from( const std::shared_ptr<char>& receive_buffer, size_t receive_buffer_length, fc::ip::endpoint& from ) { try { boost::asio::ip::udp::endpoint boost_from_endpoint; size_t bytes_read = my->_sock.receive_from( boost::asio::buffer(receive_buffer.get(), receive_buffer_length), boost_from_endpoint ); from = to_fc_ep(boost_from_endpoint); return bytes_read; } catch( const boost::system::system_error& e ) { if( e.code() != boost::asio::error::would_block ) throw; } boost::asio::ip::udp::endpoint boost_from_endpoint; promise<size_t>::ptr completion_promise = promise<size_t>::create("udp_socket::receive_from"); my->_sock.async_receive_from( boost::asio::buffer(receive_buffer.get(), receive_buffer_length), boost_from_endpoint, asio::detail::read_write_handler_with_buffer(completion_promise, receive_buffer) ); size_t bytes_read = completion_promise->wait(); from = to_fc_ep(boost_from_endpoint); return bytes_read; } size_t udp_socket::receive_from( char* receive_buffer, size_t receive_buffer_length, fc::ip::endpoint& from ) { try { boost::asio::ip::udp::endpoint boost_from_endpoint; size_t bytes_read = my->_sock.receive_from( boost::asio::buffer(receive_buffer, receive_buffer_length), boost_from_endpoint ); from = to_fc_ep(boost_from_endpoint); return bytes_read; } catch( const boost::system::system_error& e ) { if( e.code() != boost::asio::error::would_block ) throw; } boost::asio::ip::udp::endpoint boost_from_endpoint; promise<size_t>::ptr completion_promise = promise<size_t>::create("udp_socket::receive_from"); my->_sock.async_receive_from( boost::asio::buffer(receive_buffer, receive_buffer_length), boost_from_endpoint, asio::detail::read_write_handler(completion_promise) ); size_t bytes_read = completion_promise->wait(); from = to_fc_ep(boost_from_endpoint); return bytes_read; } void udp_socket::close() { //my->_sock.cancel(); my->_sock.close(); } fc::ip::endpoint udp_socket::local_endpoint()const { return to_fc_ep( my->_sock.local_endpoint() ); } void udp_socket::connect( const fc::ip::endpoint& e ) { my->_sock.connect( to_asio_ep(e) ); } void udp_socket::set_multicast_enable_loopback( bool s ) { my->_sock.set_option( boost::asio::ip::multicast::enable_loopback(s) ); } void udp_socket::set_reuse_address( bool s ) { my->_sock.set_option( boost::asio::ip::udp::socket::reuse_address(s) ); } void udp_socket::join_multicast_group( const fc::ip::address& a ) { my->_sock.set_option( boost::asio::ip::multicast::join_group( boost::asio::ip::address_v4(a) ) ); } }
33.247126
134
0.631979
Revolution-Populi
66ef2aca7561189fc1efddd261320af007ffb270
834
cpp
C++
Toast/src/Platform/Windows/WindowsInput.cpp
Toastmastern87/Toast
be9efd2f4f62597c3d95b47d242a2e783571620b
[ "Apache-2.0" ]
17
2020-07-02T19:07:56.000Z
2021-11-30T14:23:49.000Z
Toast/src/Platform/Windows/WindowsInput.cpp
Toastmastern87/Toast
be9efd2f4f62597c3d95b47d242a2e783571620b
[ "Apache-2.0" ]
null
null
null
Toast/src/Platform/Windows/WindowsInput.cpp
Toastmastern87/Toast
be9efd2f4f62597c3d95b47d242a2e783571620b
[ "Apache-2.0" ]
3
2020-06-30T00:22:26.000Z
2021-11-30T14:23:56.000Z
#include "tpch.h" #include "Toast/Core/Input.h" #include "Toast/Core/Application.h" namespace Toast { bool Input::IsKeyPressed(const KeyCode keycode) { auto state = GetAsyncKeyState(static_cast<int>(keycode)); return (state & 0x8000); } bool Input::IsMouseButtonPressed(const MouseCode button) { auto state = GetAsyncKeyState(static_cast<int>(button)); return (state & 0x8000); } DirectX::XMFLOAT2 Input::GetMousePosition() { POINT p; GetCursorPos(&p); return { (float)p.x, (float)p.y }; } float Input::GetMouseX() { return GetMousePosition().x; } float Input::GetMouseY() { return GetMousePosition().y; } float Input::sMouseWheelDelta; float Input::GetMouseWheelDelta() { return sMouseWheelDelta; } void Input::SetMouseWheelDelta(float delta) { sMouseWheelDelta = delta; } }
16.038462
59
0.699041
Toastmastern87
66f1279a2ddee9fa9e6bf24b7758d23e59ffb0c1
3,912
cc
C++
chrome/browser/profiles/profile_avatar_icon_util_unittest.cc
kjthegod/chromium
cf940f7f418436b77e15b1ea23e6fa100ca1c91a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
1
2015-08-13T21:04:58.000Z
2015-08-13T21:04:58.000Z
chrome/browser/profiles/profile_avatar_icon_util_unittest.cc
kjthegod/chromium
cf940f7f418436b77e15b1ea23e6fa100ca1c91a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
chrome/browser/profiles/profile_avatar_icon_util_unittest.cc
kjthegod/chromium
cf940f7f418436b77e15b1ea23e6fa100ca1c91a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
2
2015-03-27T11:15:39.000Z
2016-08-17T14:19:56.000Z
// 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 "chrome/browser/profiles/profile_avatar_icon_util.h" #include "grit/theme_resources.h" #include "testing/gtest/include/gtest/gtest.h" #include "ui/base/resource/resource_bundle.h" #include "ui/gfx/canvas.h" #include "ui/gfx/image/image_skia.h" #include "ui/gfx/image/image_skia_rep.h" #include "ui/gfx/image/image_unittest_util.h" namespace { // Helper function to check that the image is sized properly // and supports multiple pixel densities. void VerifyScaling(gfx::Image& image, gfx::Size& size) { gfx::Size canvas_size(100, 100); gfx::Canvas canvas(canvas_size, 1.0f, false); gfx::Canvas canvas2(canvas_size, 2.0f, false); ASSERT_FALSE(gfx::test::IsEmpty(image)); EXPECT_EQ(image.Size(), size); gfx::ImageSkia image_skia = *image.ToImageSkia(); canvas.DrawImageInt(image_skia, 15, 10); EXPECT_TRUE(image.ToImageSkia()->HasRepresentation(1.0f)); canvas2.DrawImageInt(image_skia, 15, 10); EXPECT_TRUE(image.ToImageSkia()->HasRepresentation(2.0f)); } TEST(ProfileInfoUtilTest, SizedMenuIcon) { // Test that an avatar icon isn't changed. const gfx::Image& profile_image( ResourceBundle::GetSharedInstance().GetImageNamed(IDR_PROFILE_AVATAR_0)); gfx::Image result = profiles::GetSizedAvatarIcon(profile_image, false, 50, 50); EXPECT_FALSE(gfx::test::IsEmpty(result)); EXPECT_TRUE(gfx::test::IsEqual(profile_image, result)); // Test that a rectangular picture (e.g., GAIA image) is changed. gfx::Image rect_picture(gfx::test::CreateImage()); gfx::Size size(30, 20); gfx::Image result2 = profiles::GetSizedAvatarIcon( rect_picture, true, size.width(), size.height()); VerifyScaling(result2, size); } TEST(ProfileInfoUtilTest, MenuIcon) { // Test that an avatar icon isn't changed. const gfx::Image& profile_image( ResourceBundle::GetSharedInstance().GetImageNamed(IDR_PROFILE_AVATAR_0)); gfx::Image result = profiles::GetAvatarIconForMenu(profile_image, false); EXPECT_FALSE(gfx::test::IsEmpty(result)); EXPECT_TRUE(gfx::test::IsEqual(profile_image, result)); // Test that a rectangular picture is changed. gfx::Image rect_picture(gfx::test::CreateImage()); gfx::Size size(profiles::kAvatarIconWidth, profiles::kAvatarIconHeight); gfx::Image result2 = profiles::GetAvatarIconForMenu(rect_picture, true); VerifyScaling(result2, size); } TEST(ProfileInfoUtilTest, WebUIIcon) { // Test that an avatar icon isn't changed. const gfx::Image& profile_image( ResourceBundle::GetSharedInstance().GetImageNamed(IDR_PROFILE_AVATAR_0)); gfx::Image result = profiles::GetAvatarIconForWebUI(profile_image, false); EXPECT_FALSE(gfx::test::IsEmpty(result)); EXPECT_TRUE(gfx::test::IsEqual(profile_image, result)); // Test that a rectangular picture is changed. gfx::Image rect_picture(gfx::test::CreateImage()); gfx::Size size(profiles::kAvatarIconWidth, profiles::kAvatarIconHeight); gfx::Image result2 = profiles::GetAvatarIconForWebUI(rect_picture, true); VerifyScaling(result2, size); } TEST(ProfileInfoUtilTest, TitleBarIcon) { int width = 100; int height = 40; // Test that an avatar icon isn't changed. const gfx::Image& profile_image( ResourceBundle::GetSharedInstance().GetImageNamed(IDR_PROFILE_AVATAR_0)); gfx::Image result = profiles::GetAvatarIconForTitleBar( profile_image, false, width, height); EXPECT_FALSE(gfx::test::IsEmpty(result)); EXPECT_TRUE(gfx::test::IsEqual(profile_image, result)); // Test that a rectangular picture is changed. gfx::Image rect_picture(gfx::test::CreateImage()); gfx::Size size(width, height); gfx::Image result2 = profiles::GetAvatarIconForTitleBar( rect_picture, true, width, height); VerifyScaling(result2, size); } } // namespace
35.563636
79
0.743609
kjthegod
66f18b9bca9f0d727ec2959ca99299390269f65a
81,261
cpp
C++
ecl/eclcc/eclcc.cpp
emuharemagic/HPCC-Platform
bbd5423b25f6ba2d675521c8917f9ecfa97dace5
[ "Apache-2.0" ]
1
2020-08-01T19:54:56.000Z
2020-08-01T19:54:56.000Z
ecl/eclcc/eclcc.cpp
emuharemagic/HPCC-Platform
bbd5423b25f6ba2d675521c8917f9ecfa97dace5
[ "Apache-2.0" ]
null
null
null
ecl/eclcc/eclcc.cpp
emuharemagic/HPCC-Platform
bbd5423b25f6ba2d675521c8917f9ecfa97dace5
[ "Apache-2.0" ]
null
null
null
/*############################################################################## HPCC SYSTEMS software Copyright (C) 2012 HPCC Systems. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ############################################################################## */ #include <stdio.h> #include "jcomp.hpp" #include "jfile.hpp" #include "jlzw.hpp" #include "jqueue.tpp" #include "jargv.hpp" #include "junicode.hpp" #include "build-config.h" #include "workunit.hpp" #ifndef _WIN32 #include <pwd.h> #endif #include "hqlecl.hpp" #include "hqlir.hpp" #include "hqlerrors.hpp" #include "hqlwuerr.hpp" #include "hqlfold.hpp" #include "hqlplugins.hpp" #include "hqlmanifest.hpp" #include "hqlcollect.hpp" #include "hqlrepository.hpp" #include "hqlerror.hpp" #include "hqlcerrors.hpp" #include "hqlgram.hpp" #include "hqltrans.ipp" #include "hqlutil.hpp" #include "build-config.h" #include "rmtfile.hpp" #ifdef _USE_CPPUNIT #include <cppunit/extensions/TestFactoryRegistry.h> #include <cppunit/ui/text/TestRunner.h> #endif //#define TEST_LEGACY_DEPENDENCY_CODE #define INIFILE "eclcc.ini" #define SYSTEMCONFDIR CONFIG_DIR #define DEFAULTINIFILE "eclcc.ini" #define SYSTEMCONFFILE ENV_CONF_FILE #define DEFAULT_OUTPUTNAME "a.out" //========================================================================================= //The following flag could be used not free items to speed up closedown static bool optDebugMemLeak = false; #if defined(_WIN32) && defined(_DEBUG) static HANDLE leakHandle; static void appendLeaks(size32_t len, const void * data) { SetFilePointer(leakHandle, 0, 0, FILE_END); DWORD written; WriteFile(leakHandle, data, len, &written, 0); } void initLeakCheck(const char * title) { StringBuffer leakFilename("eclccleaks.log"); leakHandle = CreateFile(leakFilename.str(), GENERIC_READ|GENERIC_WRITE, 0, NULL, OPEN_ALWAYS, 0, 0); if (title) appendLeaks(strlen(title), title); _CrtSetReportMode( _CRT_WARN, _CRTDBG_MODE_FILE|_CRTDBG_MODE_DEBUG ); _CrtSetReportFile( _CRT_WARN, leakHandle ); _CrtSetReportMode( _CRT_ERROR, _CRTDBG_MODE_FILE|_CRTDBG_MODE_DEBUG ); _CrtSetReportFile( _CRT_ERROR, leakHandle ); _CrtSetReportMode( _CRT_ASSERT, _CRTDBG_MODE_FILE|_CRTDBG_MODE_DEBUG ); _CrtSetReportFile( _CRT_ASSERT, leakHandle ); // // set the states we want to monitor // int LeakTmpFlag = _CrtSetDbgFlag( _CRTDBG_REPORT_FLAG ); LeakTmpFlag &= ~_CRTDBG_CHECK_CRT_DF; LeakTmpFlag |= _CRTDBG_LEAK_CHECK_DF; _CrtSetDbgFlag(LeakTmpFlag); } /** * Error handler for ctrl-break: Don't care about memory leaks. */ void __cdecl IntHandler(int) { enableMemLeakChecking(false); exit(2); } #include <signal.h> // for signal() MODULE_INIT(INIT_PRIORITY_STANDARD) { signal(SIGINT, IntHandler); return true; } #else void initLeakCheck(const char *) { } #endif // _WIN32 && _DEBUG static bool extractOption(StringBuffer & option, IProperties * globals, const char * envName, const char * propertyName, const char * defaultPrefix, const char * defaultSuffix) { if (option.length()) // check if already specified via a command line option return true; if (globals->getProp(propertyName, option)) return true; const char * env = getenv(envName); if (env) { option.append(env); return true; } option.append(defaultPrefix).append(defaultSuffix); return false; } static bool extractOption(StringAttr & option, IProperties * globals, const char * envName, const char * propertyName, const char * defaultPrefix, const char * defaultSuffix) { if (option) return true; StringBuffer temp; bool ret = extractOption(temp, globals, envName, propertyName, defaultPrefix, defaultSuffix); option.set(temp.str()); return ret; } static bool getPackageFolder(StringBuffer & path) { StringBuffer folder; splitDirTail(queryCurrentProcessPath(), folder); removeTrailingPathSepChar(folder); if (folder.length()) { StringBuffer foldersFolder; splitDirTail(folder.str(), foldersFolder); if (foldersFolder.length()) { path = foldersFolder; return true; } } return false; } static bool getHomeFolder(StringBuffer & homepath) { if (!getHomeDir(homepath)) return false; addPathSepChar(homepath); #ifndef WIN32 homepath.append('.'); #endif homepath.append(DIR_NAME); return true; } struct EclCompileInstance { public: EclCompileInstance(IFile * _inputFile, IErrorReceiver & _errorProcessor, FILE * _errout, const char * _outputFilename, bool _legacyImport, bool _legacyWhen) : inputFile(_inputFile), errorProcessor(&_errorProcessor), errout(_errout), outputFilename(_outputFilename) { legacyImport = _legacyImport; legacyWhen = _legacyWhen; ignoreUnknownImport = false; fromArchive = false; stats.parseTime = 0; stats.generateTime = 0; stats.xmlSize = 0; stats.cppSize = 0; } void logStats(); void checkEclVersionCompatible(); bool reportErrorSummary(); inline IErrorReceiver & queryErrorProcessor() { return *errorProcessor; } public: Linked<IFile> inputFile; Linked<IPropertyTree> archive; Linked<IWorkUnit> wu; Owned<IEclRepository> dataServer; // A member which can be cleared after parsing the query OwnedHqlExpr query; // parsed query - cleared when generating to free memory StringAttr eclVersion; const char * outputFilename; FILE * errout; Owned<IPropertyTree> srcArchive; Owned<IPropertyTree> generatedMeta; bool legacyImport; bool legacyWhen; bool fromArchive; bool ignoreUnknownImport; struct { unsigned parseTime; unsigned generateTime; offset_t xmlSize; offset_t cppSize; } stats; protected: Linked<IErrorReceiver> errorProcessor; }; class EclCC : public CInterfaceOf<ICodegenContextCallback> { public: EclCC(int _argc, const char **_argv) : programName(_argv[0]) { argc = _argc; argv = _argv; logVerbose = false; logTimings = false; optArchive = false; optCheckEclVersion = true; optEvaluateResult = false; optGenerateMeta = false; optGenerateDepend = false; optIncludeMeta = false; optLegacyImport = false; optLegacyWhen = false; optShared = false; optWorkUnit = false; optNoCompile = false; optNoLogFile = false; optNoStdInc = false; optNoBundles = false; optOnlyCompile = false; optBatchMode = false; optSaveQueryText = false; optGenerateHeader = false; optShowPaths = false; optTargetClusterType = HThorCluster; optTargetCompiler = DEFAULT_COMPILER; optThreads = 0; optLogDetail = 0; batchPart = 0; batchSplit = 1; batchLog = NULL; cclogFilename.append("cc.").append((unsigned)GetCurrentProcessId()).append(".log"); defaultAllowed = true; } bool parseCommandLineOptions(int argc, const char* argv[]); void loadOptions(); void loadManifestOptions(); bool processFiles(); void processBatchedFile(IFile & file, bool multiThreaded); virtual void noteCluster(const char *clusterName); virtual void registerFile(const char * filename, const char * description); virtual bool allowAccess(const char * category); protected: void addFilenameDependency(StringBuffer & target, EclCompileInstance & instance, const char * filename); void applyApplicationOptions(IWorkUnit * wu); void applyDebugOptions(IWorkUnit * wu); bool checkWithinRepository(StringBuffer & attributePath, const char * sourcePathname); IFileIO * createArchiveOutputFile(EclCompileInstance & instance); ICppCompiler *createCompiler(const char * coreName, const char * sourceDir = NULL, const char * targetDir = NULL); void evaluateResult(EclCompileInstance & instance); bool generatePrecompiledHeader(); void generateOutput(EclCompileInstance & instance); void instantECL(EclCompileInstance & instance, IWorkUnit *wu, const char * queryFullName, IErrorReceiver & errorProcessor, const char * outputFile); bool isWithinPath(const char * sourcePathname, const char * searchPath); void getComplexity(IWorkUnit *wu, IHqlExpression * query, IErrorReceiver & errorProcessor); void outputXmlToOutputFile(EclCompileInstance & instance, IPropertyTree * xml); void processSingleQuery(EclCompileInstance & instance, IFileContents * queryContents, const char * queryAttributePath); void processXmlFile(EclCompileInstance & instance, const char *archiveXML); void processFile(EclCompileInstance & info); void processReference(EclCompileInstance & instance, const char * queryAttributePath); void processBatchFiles(); void reportCompileErrors(IErrorReceiver & errorProcessor, const char * processName); void setDebugOption(const char * name, bool value); void usage(); inline const char * queryTemplateDir() { return templatePath.length() ? templatePath.str() : NULL; } protected: Owned<IEclRepository> pluginsRepository; Owned<IEclRepository> libraryRepository; Owned<IEclRepository> bundlesRepository; Owned<IEclRepository> includeRepository; const char * programName; StringBuffer cppIncludePath; StringBuffer pluginsPath; StringBuffer hooksPath; StringBuffer templatePath; StringBuffer eclLibraryPath; StringBuffer eclBundlePath; StringBuffer stdIncludeLibraryPath; StringBuffer includeLibraryPath; StringBuffer compilerPath; StringBuffer libraryPath; StringBuffer cclogFilename; StringAttr optLogfile; StringAttr optIniFilename; StringAttr optManifestFilename; StringAttr optOutputDirectory; StringAttr optOutputFilename; StringAttr optQueryRepositoryReference; FILE * batchLog; IFileArray inputFiles; StringArray inputFileNames; StringArray applicationOptions; StringArray debugOptions; StringArray warningMappings; StringArray compileOptions; StringArray linkOptions; StringArray libraryPaths; StringArray allowedPermissions; StringArray deniedPermissions; bool defaultAllowed; ClusterType optTargetClusterType; CompilerType optTargetCompiler; unsigned optThreads; unsigned batchPart; unsigned batchSplit; unsigned optLogDetail; bool logVerbose; bool logTimings; bool optArchive; bool optCheckEclVersion; bool optEvaluateResult; bool optGenerateMeta; bool optGenerateDepend; bool optIncludeMeta; bool optWorkUnit; bool optNoCompile; bool optNoLogFile; bool optNoStdInc; bool optNoBundles; bool optBatchMode; bool optShared; bool optOnlyCompile; bool optSaveQueryText; bool optLegacyImport; bool optLegacyWhen; bool optGenerateHeader; bool optShowPaths; int argc; const char **argv; }; //========================================================================================= static int doSelfTest(int argc, const char *argv[]) { #ifdef _USE_CPPUNIT queryStderrLogMsgHandler()->setMessageFields(MSGFIELD_time | MSGFIELD_prefix); CppUnit::TextUi::TestRunner runner; if (argc==2) { CppUnit::TestFactoryRegistry &registry = CppUnit::TestFactoryRegistry::getRegistry(); runner.addTest( registry.makeTest() ); } else { // MORE - maybe add a 'list' function here? for (int name = 2; name < argc; name++) { if (stricmp(argv[name], "-q")==0) { removeLog(); } else { CppUnit::TestFactoryRegistry &registry = CppUnit::TestFactoryRegistry::getRegistry(argv[name]); runner.addTest( registry.makeTest() ); } } } bool wasSucessful = runner.run( "", false ); releaseAtoms(); return wasSucessful; #else return true; #endif } static int doMain(int argc, const char *argv[]) { if (argc>=2 && stricmp(argv[1], "-selftest")==0) return doSelfTest(argc, argv); EclCC processor(argc, argv); if (!processor.parseCommandLineOptions(argc, argv)) return 1; try { if (!processor.processFiles()) return 2; } catch (IException *E) { StringBuffer m("Error: "); E->errorMessage(m); fputs(m.newline().str(), stderr); E->Release(); return 2; } #ifndef _DEBUG catch (...) { ERRLOG("Unexpected exception\n"); return 4; } #endif return 0; } int main(int argc, const char *argv[]) { EnableSEHtoExceptionMapping(); setTerminateOnSEH(true); InitModuleObjects(); queryStderrLogMsgHandler()->setMessageFields(0); // Turn logging down (we turn it back up if -v option seen) Owned<ILogMsgFilter> filter = getCategoryLogMsgFilter(MSGAUD_user, MSGCLS_error); queryLogMsgManager()->changeMonitorFilter(queryStderrLogMsgHandler(), filter); unsigned exitCode = doMain(argc, argv); releaseAtoms(); removeFileHooks(); return exitCode; } //========================================================================================= bool setTargetPlatformOption(const char *platform, ClusterType &optTargetClusterType) { if (!platform || !*platform) return false; ClusterType clusterType = getClusterType(platform); if (clusterType == NoCluster) { ERRLOG("Unknown ecl target platform %s\n", platform); return false; } optTargetClusterType = clusterType; return true; } void EclCC::loadManifestOptions() { if (!optManifestFilename) return; Owned<IPropertyTree> mf = createPTreeFromXMLFile(optManifestFilename); IPropertyTree *ecl = mf->queryPropTree("ecl"); if (ecl) { if (ecl->hasProp("@filename")) { StringBuffer dir, abspath; splitDirTail(optManifestFilename, dir); makeAbsolutePath(ecl->queryProp("@filename"), dir.str(), abspath); processArgvFilename(inputFiles, abspath.str()); } if (!optLegacyImport && !optLegacyWhen) { bool optLegacy = ecl->getPropBool("@legacy"); optLegacyImport = ecl->getPropBool("@legacyImport", optLegacy); optLegacyWhen = ecl->getPropBool("@legacyWhen", optLegacy); } if (!optQueryRepositoryReference && ecl->hasProp("@main")) optQueryRepositoryReference.set(ecl->queryProp("@main")); if (ecl->hasProp("@targetPlatform")) setTargetPlatformOption(ecl->queryProp("@targetPlatform"), optTargetClusterType); else if (ecl->hasProp("@targetClusterType")) //deprecated name setTargetPlatformOption(ecl->queryProp("@targetClusterType"), optTargetClusterType); Owned<IPropertyTreeIterator> paths = ecl->getElements("IncludePath"); ForEach(*paths) { IPropertyTree &item = paths->query(); if (item.hasProp("@path")) includeLibraryPath.append(ENVSEPCHAR).append(item.queryProp("@path")); } paths.setown(ecl->getElements("LibraryPath")); ForEach(*paths) { IPropertyTree &item = paths->query(); if (item.hasProp("@path")) libraryPaths.append(item.queryProp("@path")); } } } void EclCC::loadOptions() { Owned<IProperties> globals; if (!optIniFilename) { if (checkFileExists(INIFILE)) optIniFilename.set(INIFILE); else { StringBuffer fn(SYSTEMCONFDIR); fn.append(PATHSEPSTR).append(DEFAULTINIFILE); if (checkFileExists(fn)) optIniFilename.set(fn); } } if (logVerbose && optIniFilename.length()) fprintf(stdout, "Found ini file '%s'\n", optIniFilename.get()); globals.setown(createProperties(optIniFilename, true)); if (globals->hasProp("targetGcc")) optTargetCompiler = globals->getPropBool("targetGcc") ? GccCppCompiler : Vs6CppCompiler; StringBuffer syspath, homepath; if (getPackageFolder(syspath) && getHomeFolder(homepath)) { #if _WIN32 extractOption(compilerPath, globals, "CL_PATH", "compilerPath", syspath, "componentfiles\\cl"); #else extractOption(compilerPath, globals, "CL_PATH", "compilerPath", "/usr", NULL); #endif if (!extractOption(libraryPath, globals, "ECLCC_LIBRARY_PATH", "libraryPath", syspath, "lib")) libraryPath.append(ENVSEPCHAR).append(syspath).append("plugins"); extractOption(cppIncludePath, globals, "ECLCC_INCLUDE_PATH", "includePath", syspath, "componentfiles" PATHSEPSTR "cl" PATHSEPSTR "include"); extractOption(pluginsPath, globals, "ECLCC_PLUGIN_PATH", "plugins", syspath, "plugins"); extractOption(hooksPath, globals, "HPCC_FILEHOOKS_PATH", "filehooks", syspath, "filehooks"); extractOption(templatePath, globals, "ECLCC_TPL_PATH", "templatePath", syspath, "componentfiles"); extractOption(eclLibraryPath, globals, "ECLCC_ECLLIBRARY_PATH", "eclLibrariesPath", syspath, "share" PATHSEPSTR "ecllibrary" PATHSEPSTR); extractOption(eclBundlePath, globals, "ECLCC_ECLBUNDLE_PATH", "eclBundlesPath", homepath, PATHSEPSTR "bundles" PATHSEPSTR); } extractOption(stdIncludeLibraryPath, globals, "ECLCC_ECLINCLUDE_PATH", "eclIncludePath", ".", NULL); if (!optLogfile.length() && !optBatchMode && !optNoLogFile) extractOption(optLogfile, globals, "ECLCC_LOGFILE", "logfile", "eclcc.log", NULL); if ((logVerbose || optLogfile) && !optNoLogFile) { if (optLogfile.length()) { StringBuffer lf; openLogFile(lf, optLogfile, optLogDetail, false); if (logVerbose) fprintf(stdout, "Logging to '%s'\n",lf.str()); } } if (hooksPath.length()) installFileHooks(hooksPath.str()); if (!optNoCompile) setCompilerPath(compilerPath.str(), cppIncludePath.str(), libraryPath.str(), NULL, optTargetCompiler, logVerbose); } //========================================================================================= void EclCC::applyDebugOptions(IWorkUnit * wu) { ForEachItemIn(i, debugOptions) { const char * option = debugOptions.item(i); const char * eq = strchr(option, '='); if (eq) { StringAttr name; name.set(option, eq-option); wu->setDebugValue(name, eq+1, true); } else { size_t len = strlen(option); if (len) { char last = option[len-1]; if (last == '-' || last == '+') { StringAttr name; name.set(option, len-1); wu->setDebugValueInt(name, last == '+' ? 1 : 0, true); } else wu->setDebugValue(option, "1", true); } } } } void EclCC::applyApplicationOptions(IWorkUnit * wu) { ForEachItemIn(i, applicationOptions) { const char * option = applicationOptions.item(i); const char * eq = strchr(option, '='); if (eq) { StringAttr name; name.set(option, eq-option); wu->setApplicationValue("eclcc", name, eq+1, true); } else { wu->setApplicationValueInt("eclcc", option, 1, true); } } } //========================================================================================= ICppCompiler * EclCC::createCompiler(const char * coreName, const char * sourceDir, const char * targetDir) { Owned<ICppCompiler> compiler = ::createCompiler(coreName, sourceDir, targetDir, optTargetCompiler, logVerbose); compiler->setOnlyCompile(optOnlyCompile); compiler->setCCLogPath(cclogFilename); ForEachItemIn(iComp, compileOptions) compiler->addCompileOption(compileOptions.item(iComp)); ForEachItemIn(iLink, linkOptions) compiler->addLinkOption(linkOptions.item(iLink)); ForEachItemIn(iLib, libraryPaths) compiler->addLibraryPath(libraryPaths.item(iLib)); return compiler.getClear(); } void EclCC::reportCompileErrors(IErrorReceiver & errorProcessor, const char * processName) { StringBuffer failText; StringBuffer absCCLogName; if (optLogfile.get()) createUNCFilename(optLogfile.get(), absCCLogName, false); else absCCLogName = "log file"; failText.appendf("Compile/Link failed for %s (see '%s' for details)",processName,absCCLogName.str()); errorProcessor.reportError(ERR_INTERNALEXCEPTION, failText.toCharArray(), processName, 0, 0, 0); try { StringBuffer s; Owned<IFile> log = createIFile(cclogFilename); Owned<IFileIO> io = log->open(IFOread); if (io) { offset_t len = io->size(); if (len) { io->read(0, (size32_t)len, s.reserve((size32_t)len)); #ifdef _WIN32 const char * noCompiler = "is not recognized as an internal"; #else const char * noCompiler = "could not locate compiler"; #endif if (strstr(s.str(), noCompiler)) { ERRLOG("Fatal Error: Unable to locate C++ compiler/linker"); } ERRLOG("\n---------- compiler output --------------\n%s\n--------- end compiler output -----------", s.str()); } } } catch (IException * e) { e->Release(); } } //========================================================================================= void EclCC::instantECL(EclCompileInstance & instance, IWorkUnit *wu, const char * queryFullName, IErrorReceiver & errorProcessor, const char * outputFile) { StringBuffer processName(outputFile); if (instance.query && containsAnyActions(instance.query)) { try { const char * templateDir = queryTemplateDir(); bool optSaveTemps = wu->getDebugValueBool("saveEclTempFiles", false); bool optSaveCpp = optSaveTemps || optNoCompile || wu->getDebugValueBool("saveCppTempFiles", false); //New scope - testing things are linked correctly { Owned<IHqlExprDllGenerator> generator = createDllGenerator(&errorProcessor, processName.toCharArray(), NULL, wu, templateDir, optTargetClusterType, this, false, false); setWorkunitHash(wu, instance.query); if (!optShared) wu->setDebugValueInt("standAloneExe", 1, true); EclGenerateTarget target = optWorkUnit ? EclGenerateNone : (optNoCompile ? EclGenerateCpp : optShared ? EclGenerateDll : EclGenerateExe); if (optManifestFilename) generator->addManifest(optManifestFilename); if (instance.srcArchive) { generator->addManifestFromArchive(instance.srcArchive); instance.srcArchive.clear(); } generator->setSaveGeneratedFiles(optSaveCpp); bool generateOk = generator->processQuery(instance.query, target); // NB: May clear instance.query instance.stats.cppSize = generator->getGeneratedSize(); if (generateOk && !optNoCompile) { Owned<ICppCompiler> compiler = createCompiler(processName.toCharArray()); compiler->setSaveTemps(optSaveTemps); bool compileOk = true; if (optShared) { compileOk = generator->generateDll(compiler); } else { if (optTargetClusterType==RoxieCluster) generator->addLibrary("ccd"); else generator->addLibrary("hthor"); compileOk = generator->generateExe(compiler); } if (!compileOk) reportCompileErrors(errorProcessor, processName); } else wu->setState(generateOk ? WUStateCompleted : WUStateFailed); } if (logVerbose) { switch (wu->getState()) { case WUStateCompiled: fprintf(stdout, "Output file '%s' created\n",outputFile); break; case WUStateFailed: ERRLOG("Failed to create output file '%s'\n",outputFile); break; case WUStateUploadingFiles: fprintf(stdout, "Output file '%s' created, local file upload required\n",outputFile); break; case WUStateCompleted: fprintf(stdout, "No DLL/SO required\n"); break; default: ERRLOG("Unexpected Workunit state %d\n", (int) wu->getState()); break; } } } catch (IException * e) { if (e->errorCode() != HQLERR_ErrorAlreadyReported) { StringBuffer exceptionText; e->errorMessage(exceptionText); errorProcessor.reportError(ERR_INTERNALEXCEPTION, exceptionText.toCharArray(), queryFullName, 1, 0, 0); } e->Release(); } try { Owned<IFile> log = createIFile(cclogFilename); log->remove(); } catch (IException * e) { e->Release(); } } } //========================================================================================= void EclCC::getComplexity(IWorkUnit *wu, IHqlExpression * query, IErrorReceiver & errs) { double complexity = getECLcomplexity(query, &errs, wu, optTargetClusterType); LOG(MCstats, unknownJob, "Complexity = %g", complexity); } //========================================================================================= static bool convertPathToModule(StringBuffer & out, const char * filename) { const char * dot = strrchr(filename, '.'); if (dot) { if (!strieq(dot, ".ecl") && !strieq(dot, ".hql") && !strieq(dot, ".eclmod") && !strieq(dot, ".eclattr")) return false; } else return false; const unsigned copyLen = dot-filename; if (copyLen == 0) return false; out.ensureCapacity(copyLen); for (unsigned i= 0; i < copyLen; i++) { char next = filename[i]; if (isPathSepChar(next)) next = '.'; out.append(next); } return true; } static bool findFilenameInSearchPath(StringBuffer & attributePath, const char * searchPath, const char * expandedSourceName) { const char * cur = searchPath; unsigned lenSource = strlen(expandedSourceName); loop { const char * sep = strchr(cur, ENVSEPCHAR); StringBuffer curExpanded; if (!sep) { if (*cur) makeAbsolutePath(cur, curExpanded); } else if (sep != cur) { StringAttr temp(cur, sep-cur); makeAbsolutePath(temp, curExpanded); } if (curExpanded.length() && (curExpanded.length() < lenSource)) { #ifdef _WIN32 //windows paths are case insensitive bool same = memicmp(curExpanded.str(), expandedSourceName, curExpanded.length()) == 0; #else bool same = memcmp(curExpanded.str(), expandedSourceName, curExpanded.length()) == 0; #endif if (same) { const char * tail = expandedSourceName+curExpanded.length(); if (isPathSepChar(*tail)) tail++; if (convertPathToModule(attributePath, tail)) return true; } } if (!sep) return false; cur = sep+1; } } bool EclCC::isWithinPath(const char * sourcePathname, const char * searchPath) { if (!sourcePathname) return false; StringBuffer expandedSourceName; makeAbsolutePath(sourcePathname, expandedSourceName); StringBuffer attributePath; return findFilenameInSearchPath(attributePath, searchPath, expandedSourceName); } bool EclCC::checkWithinRepository(StringBuffer & attributePath, const char * sourcePathname) { if (!sourcePathname) return false; StringBuffer searchPath; searchPath.append(eclLibraryPath).append(ENVSEPCHAR); if (!optNoBundles) searchPath.append(eclBundlePath).append(ENVSEPCHAR); if (!optNoStdInc) searchPath.append(stdIncludeLibraryPath).append(ENVSEPCHAR); searchPath.append(includeLibraryPath); StringBuffer expandedSourceName; makeAbsolutePath(sourcePathname, expandedSourceName); return findFilenameInSearchPath(attributePath, searchPath, expandedSourceName); } void EclCC::evaluateResult(EclCompileInstance & instance) { IHqlExpression *query = instance.query; if (query->getOperator()==no_output) query = query->queryChild(0); if (query->getOperator()==no_datasetfromdictionary) query = query->queryChild(0); if (query->getOperator()==no_selectfields) query = query->queryChild(0); if (query->getOperator()==no_createdictionary) query = query->queryChild(0); OwnedHqlExpr folded = foldHqlExpression(instance.queryErrorProcessor(), query, NULL, HFOthrowerror|HFOloseannotations|HFOforcefold|HFOfoldfilterproject|HFOconstantdatasets); StringBuffer out; IValue *result = folded->queryValue(); if (result) result->generateECL(out); else if (folded->getOperator()==no_list) { out.append('['); ForEachChild(idx, folded) { IHqlExpression *child = folded->queryChild(idx); if (idx) out.append(", "); result = child->queryValue(); if (result) result->generateECL(out); else throw MakeStringException(1, "Expression cannot be evaluated"); } out.append(']'); } else if (folded->getOperator()==no_inlinetable) { IHqlExpression *transformList = folded->queryChild(0); if (transformList && transformList->getOperator()==no_transformlist) { IHqlExpression *transform = transformList->queryChild(0); assertex(transform && transform->getOperator()==no_transform); out.append('['); ForEachChild(idx, transform) { IHqlExpression *child = transform->queryChild(idx); assertex(child->getOperator()==no_assign); if (idx) out.append(", "); result = child->queryChild(1)->queryValue(); if (result) result->generateECL(out); else throw MakeStringException(1, "Expression cannot be evaluated"); } out.append(']'); } else throw MakeStringException(1, "Expression cannot be evaluated"); } else { #ifdef _DEBUG EclIR::dump_ir(folded); #endif throw MakeStringException(1, "Expression cannot be evaluated"); } printf("%s\n", out.str()); } void EclCC::processSingleQuery(EclCompileInstance & instance, IFileContents * queryContents, const char * queryAttributePath) { #ifdef TEST_LEGACY_DEPENDENCY_CODE setLegacyEclSemantics(instance.legacyImportMode, instance.legacyWhenMode); Owned<IPropertyTree> dependencies = gatherAttributeDependencies(instance.dataServer, ""); if (dependencies) saveXML("depends.xml", dependencies); #endif Owned<IErrorReceiver> wuErrs = new WorkUnitErrorReceiver(instance.wu, "eclcc"); Owned<IErrorReceiver> compoundErrs = createCompoundErrorReceiver(&instance.queryErrorProcessor(), wuErrs); Owned<ErrorSeverityMapper> severityMapper = new ErrorSeverityMapper(*compoundErrs); //Apply command line mappings... ForEachItemIn(i, warningMappings) { if (!severityMapper->addCommandLineMapping(warningMappings.item(i))) return; //Preserve command line mappings in the generated archive if (instance.archive) instance.archive->addPropTree("OnWarning", createPTree())->setProp("@value",warningMappings.item(i)); } //Apply preserved onwarning mappings from any source archive if (instance.srcArchive) { Owned<IPropertyTreeIterator> iter = instance.srcArchive->getElements("OnWarning"); ForEach(*iter) { const char * option = iter->query().queryProp("@value"); if (!severityMapper->addCommandLineMapping(option)) return; } } IErrorReceiver & errorProcessor = *severityMapper; //All dlls/exes are essentially cloneable because you may be running multiple instances at once //The only exception would be a dll created for a one-time query. (Currently handled by eclserver.) instance.wu->setCloneable(true); applyDebugOptions(instance.wu); applyApplicationOptions(instance.wu); if (optTargetCompiler != DEFAULT_COMPILER) instance.wu->setDebugValue("targetCompiler", compilerTypeText[optTargetCompiler], true); bool withinRepository = (queryAttributePath && *queryAttributePath); bool syntaxChecking = instance.wu->getDebugValueBool("syntaxCheck", false); size32_t prevErrs = errorProcessor.errCount(); unsigned startTime = msTick(); const char * sourcePathname = queryContents ? queryContents->querySourcePath()->str() : NULL; const char * defaultErrorPathname = sourcePathname ? sourcePathname : queryAttributePath; //The following is only here to provide information about the source file being compiled when reporting leaks setActiveSource(instance.inputFile->queryFilename()); { //Minimize the scope of the parse context to reduce lifetime of cached items. HqlParseContext parseCtx(instance.dataServer, instance.archive); if (optGenerateMeta || optIncludeMeta) { HqlParseContext::MetaOptions options; options.includePublicDefinitions = instance.wu->getDebugValueBool("metaIncludePublic", true); options.includePrivateDefinitions = instance.wu->getDebugValueBool("metaIncludePrivate", true); options.onlyGatherRoot = instance.wu->getDebugValueBool("metaIncludeMainOnly", false); options.includeImports = instance.wu->getDebugValueBool("metaIncludeImports", true); options.includeExternalUses = instance.wu->getDebugValueBool("metaIncludeExternalUse", true); options.includeExternalUses = instance.wu->getDebugValueBool("metaIncludeExternalUse", true); options.includeLocations = instance.wu->getDebugValueBool("metaIncludeLocations", true); options.includeJavadoc = instance.wu->getDebugValueBool("metaIncludeJavadoc", true); parseCtx.setGatherMeta(options); } setLegacyEclSemantics(instance.legacyImport, instance.legacyWhen); if (instance.archive) { instance.archive->setPropBool("@legacyImport", instance.legacyImport); instance.archive->setPropBool("@legacyWhen", instance.legacyWhen); } parseCtx.ignoreUnknownImport = instance.ignoreUnknownImport; try { HqlLookupContext ctx(parseCtx, &errorProcessor); if (withinRepository) { if (instance.archive) { instance.archive->setProp("Query", ""); instance.archive->setProp("Query/@attributePath", queryAttributePath); } instance.query.setown(getResolveAttributeFullPath(queryAttributePath, LSFpublic, ctx)); if (!instance.query && !syntaxChecking && (errorProcessor.errCount() == prevErrs)) { StringBuffer msg; msg.append("Could not resolve attribute ").append(queryAttributePath); errorProcessor.reportError(3, msg.str(), defaultErrorPathname, 0, 0, 0); } } else { Owned<IHqlScope> scope = createPrivateScope(); if (instance.legacyImport) importRootModulesToScope(scope, ctx); instance.query.setown(parseQuery(scope, queryContents, ctx, NULL, NULL, true)); if (instance.archive) { StringBuffer queryText; queryText.append(queryContents->length(), queryContents->getText()); const char * p = queryText; if (0 == strncmp(p, (const char *)UTF8_BOM,3)) p += 3; instance.archive->setProp("Query", p ); instance.archive->setProp("Query/@originalFilename", sourcePathname); } } gatherParseWarnings(ctx.errs, instance.query, parseCtx.orphanedWarnings); if (instance.query && !syntaxChecking && !optGenerateMeta && !optEvaluateResult) instance.query.setown(convertAttributeToQuery(instance.query, ctx)); instance.stats.parseTime = msTick()-startTime; if (instance.wu->getDebugValueBool("addTimingToWorkunit", true)) updateWorkunitTimeStat(instance.wu, "eclcc", "workunit", "parse time", NULL, milliToNano(instance.stats.parseTime), 1, 0); if (optIncludeMeta || optGenerateMeta) instance.generatedMeta.setown(parseCtx.getMetaTree()); if (optEvaluateResult && !errorProcessor.errCount() && instance.query) evaluateResult(instance); } catch (IException *e) { StringBuffer s; e->errorMessage(s); errorProcessor.reportError(3, s.toCharArray(), defaultErrorPathname, 1, 0, 0); e->Release(); } } //Free up the repository (and any cached expressions) as soon as the expression has been parsed instance.dataServer.clear(); if (!syntaxChecking && (errorProcessor.errCount() == prevErrs) && (!instance.query || !containsAnyActions(instance.query))) { errorProcessor.reportError(3, "Query is empty", defaultErrorPathname, 1, 0, 0); return; } if (instance.archive) return; if (syntaxChecking || optGenerateMeta || optEvaluateResult) return; StringBuffer targetFilename; const char * outputFilename = instance.outputFilename; if (!outputFilename) { addNonEmptyPathSepChar(targetFilename.append(optOutputDirectory)); targetFilename.append(DEFAULT_OUTPUTNAME); } else if (strcmp(outputFilename, "-") == 0) targetFilename.append("stdout:"); else addNonEmptyPathSepChar(targetFilename.append(optOutputDirectory)).append(outputFilename); //Check if it overlaps with the source file and add .eclout if so if (instance.inputFile) { const char * originalFilename = instance.inputFile->queryFilename(); if (streq(targetFilename, originalFilename)) targetFilename.append(".eclout"); } if (errorProcessor.errCount() == prevErrs) { const char * queryFullName = NULL; instantECL(instance, instance.wu, queryFullName, errorProcessor, targetFilename); } else { if (stdIoHandle(targetFilename) == -1) { // MORE - what about intermediate files? #ifdef _WIN32 StringBuffer goer; remove(goer.append(targetFilename).append(".exe")); remove(goer.clear().append(targetFilename).append(".exe.manifest")); #else remove(targetFilename); #endif } } unsigned totalTime = msTick() - startTime; instance.stats.generateTime = totalTime - instance.stats.parseTime; if (instance.wu->getDebugValueBool("addTimingToWorkunit", true)) updateWorkunitTimeStat(instance.wu, "eclcc", "workunit", "totalTime", NULL, milliToNano(totalTime), 1, 0); } void EclCC::processXmlFile(EclCompileInstance & instance, const char *archiveXML) { instance.srcArchive.setown(createPTreeFromXMLString(archiveXML, ipt_caseInsensitive)); IPropertyTree * archiveTree = instance.srcArchive; Owned<IPropertyTreeIterator> iter = archiveTree->getElements("Option"); ForEach(*iter) { IPropertyTree &item = iter->query(); instance.wu->setDebugValue(item.queryProp("@name"), item.queryProp("@value"), true); } const char * queryText = archiveTree->queryProp("Query"); const char * queryAttributePath = archiveTree->queryProp("Query/@attributePath"); //Takes precedence over an entry in the archive - so you can submit parts of an archive. if (optQueryRepositoryReference) queryAttributePath = optQueryRepositoryReference; //The legacy mode (if specified) in the archive takes precedence - it needs to match to compile. instance.legacyImport = archiveTree->getPropBool("@legacyMode", instance.legacyImport); instance.legacyWhen = archiveTree->getPropBool("@legacyMode", instance.legacyWhen); instance.legacyImport = archiveTree->getPropBool("@legacyImport", instance.legacyImport); instance.legacyWhen = archiveTree->getPropBool("@legacyWhen", instance.legacyWhen); //Some old archives contained imports, but no definitions of the module. This option is to allow them to compile. //It shouldn't be needed for new archives in non-legacy mode. (But neither should it cause any harm.) instance.ignoreUnknownImport = archiveTree->getPropBool("@ignoreUnknownImport", true); instance.eclVersion.set(archiveTree->queryProp("@eclVersion")); if (optCheckEclVersion) instance.checkEclVersionCompatible(); Owned<IEclSourceCollection> archiveCollection; if (archiveTree->getPropBool("@testRemoteInterface", false)) { //This code is purely here for regression testing some of the classes used in the enterprise version. Owned<IXmlEclRepository> xmlRepository = createArchiveXmlEclRepository(archiveTree); archiveCollection.setown(createRemoteXmlEclCollection(NULL, *xmlRepository, NULL, false)); archiveCollection->checkCacheValid(); } else archiveCollection.setown(createArchiveEclCollection(archiveTree)); EclRepositoryArray repositories; repositories.append(*LINK(pluginsRepository)); if (archiveTree->getPropBool("@useLocalSystemLibraries", false)) // Primarily for testing. repositories.append(*LINK(libraryRepository)); Owned<IFileContents> contents; StringBuffer fullPath; // Here so it doesn't get freed when leaving the else block if (queryText || queryAttributePath) { const char * sourceFilename = archiveTree->queryProp("Query/@originalFilename"); Owned<ISourcePath> sourcePath = createSourcePath(sourceFilename); contents.setown(createFileContentsFromText(queryText, sourcePath)); if (queryAttributePath && queryText && *queryText) { Owned<IEclSourceCollection> inputFileCollection = createSingleDefinitionEclCollection(queryAttributePath, contents); repositories.append(*createRepository(inputFileCollection)); } } else { //This is really only useful for regression testing const char * queryText = archiveTree->queryProp("SyntaxCheck"); const char * syntaxCheckModule = archiveTree->queryProp("SyntaxCheck/@module"); const char * syntaxCheckAttribute = archiveTree->queryProp("SyntaxCheck/@attribute"); if (!queryText || !syntaxCheckModule || !syntaxCheckAttribute) throw MakeStringException(1, "No query found in xml"); instance.wu->setDebugValueInt("syntaxCheck", true, true); fullPath.append(syntaxCheckModule).append('.').append(syntaxCheckAttribute); queryAttributePath = fullPath.str(); //Create a repository with just that attribute, and place it before the archive in the resolution order. Owned<IFileContents> contents = createFileContentsFromText(queryText, NULL); repositories.append(*createSingleDefinitionEclRepository(syntaxCheckModule, syntaxCheckAttribute, contents)); } repositories.append(*createRepository(archiveCollection)); instance.dataServer.setown(createCompoundRepository(repositories)); //Ensure classes are not linked by anything else archiveCollection.clear(); repositories.kill(); processSingleQuery(instance, contents, queryAttributePath); } //========================================================================================= void EclCC::processFile(EclCompileInstance & instance) { const char * curFilename = instance.inputFile->queryFilename(); assertex(curFilename); Owned<ISourcePath> sourcePath = createSourcePath(curFilename); Owned<IFileContents> queryText = createFileContentsFromFile(curFilename, sourcePath); const char * queryTxt = queryText->getText(); if (optArchive || optGenerateDepend) instance.archive.setown(createAttributeArchive()); instance.wu.setown(createLocalWorkUnit()); if (optSaveQueryText) { Owned<IWUQuery> q = instance.wu->updateQuery(); q->setQueryText(queryTxt); } //On a system with userECL not allowed, all compilations must be from checked-in code that has been //deployed to the eclcc machine via other means (typically via a version-control system) if (!allowAccess("userECL") && (!optQueryRepositoryReference || queryText->length())) { instance.queryErrorProcessor().reportError(HQLERR_UserCodeNotAllowed, HQLERR_UserCodeNotAllowed_Text, NULL, 1, 0, 0); } else if (isArchiveQuery(queryTxt)) { instance.fromArchive = true; processXmlFile(instance, queryTxt); } else { StringBuffer attributePath; bool withinRepository = false; bool inputFromStdIn = streq(curFilename, "stdin:"); //Specifying --main indicates that the query text (if present) replaces that definition if (optQueryRepositoryReference) { withinRepository = true; attributePath.clear().append(optQueryRepositoryReference); } else { withinRepository = !inputFromStdIn && checkWithinRepository(attributePath, curFilename); } StringBuffer expandedSourceName; if (!inputFromStdIn) makeAbsolutePath(curFilename, expandedSourceName); else expandedSourceName.append(curFilename); EclRepositoryArray repositories; repositories.append(*LINK(pluginsRepository)); repositories.append(*LINK(libraryRepository)); if (bundlesRepository) repositories.append(*LINK(bundlesRepository)); //Ensure that this source file is used as the definition (in case there are potential clashes) //Note, this will not override standard library files. if (withinRepository) { //-main only overrides the definition if the query is non-empty. Otherwise use the existing text. if (!optQueryRepositoryReference || queryText->length()) { Owned<IEclSourceCollection> inputFileCollection = createSingleDefinitionEclCollection(attributePath, queryText); repositories.append(*createRepository(inputFileCollection)); } } else { //Ensure that $ is valid for any file submitted - even if it isn't in the include direcotories //Disable this for the moment when running the regression suite. if (!optBatchMode && !withinRepository && !inputFromStdIn && !optLegacyImport) { //Associate the contents of the directory with an internal module called _local_directory_ //(If it was root it might override existing root symbols). $ is the only public way to get at the symbol const char * moduleName = "_local_directory_"; IIdAtom * moduleNameId = createIdAtom(moduleName); StringBuffer thisDirectory; StringBuffer thisTail; splitFilename(expandedSourceName, &thisDirectory, &thisDirectory, &thisTail, NULL); attributePath.append(moduleName).append(".").append(thisTail); Owned<IEclSourceCollection> inputFileCollection = createSingleDefinitionEclCollection(attributePath, queryText); repositories.append(*createRepository(inputFileCollection)); Owned<IEclSourceCollection> directory = createFileSystemEclCollection(&instance.queryErrorProcessor(), thisDirectory, 0, 0); Owned<IEclRepository> directoryRepository = createRepository(directory, moduleName); Owned<IEclRepository> nested = createNestedRepository(moduleNameId, directoryRepository); repositories.append(*LINK(nested)); } } repositories.append(*LINK(includeRepository)); instance.dataServer.setown(createCompoundRepository(repositories)); repositories.kill(); processSingleQuery(instance, queryText, attributePath.str()); } if (instance.reportErrorSummary() && !instance.archive && !(optGenerateMeta && instance.generatedMeta)) return; generateOutput(instance); } IFileIO * EclCC::createArchiveOutputFile(EclCompileInstance & instance) { StringBuffer archiveName; if (instance.outputFilename && !streq(instance.outputFilename, "-")) addNonEmptyPathSepChar(archiveName.append(optOutputDirectory)).append(instance.outputFilename); else archiveName.append("stdout:"); //Work around windows problem writing 64K to stdout if not redirected/piped OwnedIFile ifile = createIFile(archiveName); return ifile->open(IFOcreate); } void EclCC::outputXmlToOutputFile(EclCompileInstance & instance, IPropertyTree * xml) { OwnedIFileIO ifileio = createArchiveOutputFile(instance); if (ifileio) { //Work around windows problem writing 64K to stdout if not redirected/piped Owned<IIOStream> stream = createIOStream(ifileio.get()); Owned<IIOStream> buffered = createBufferedIOStream(stream,0x8000); saveXML(*buffered, xml); } } void EclCC::addFilenameDependency(StringBuffer & target, EclCompileInstance & instance, const char * filename) { if (!filename) return; //Ignore plugins and standard library components if (isWithinPath(filename, pluginsPath) || isWithinPath(filename, eclLibraryPath)) return; //Don't include the input file in the dependencies. if (instance.inputFile) { const char * sourceFilename = instance.inputFile->queryFilename(); if (sourceFilename && streq(sourceFilename, filename)) return; } target.append(filename).newline(); } void EclCC::generateOutput(EclCompileInstance & instance) { const char * outputFilename = instance.outputFilename; if (instance.archive) { if (optGenerateDepend) { //Walk the archive, and output all filenames that aren't //a)in a plugin b) in std.lib c) the original source file. StringBuffer filenames; Owned<IPropertyTreeIterator> modIter = instance.archive->getElements("Module"); ForEach(*modIter) { IPropertyTree * module = &modIter->query(); if (module->hasProp("@plugin")) continue; addFilenameDependency(filenames, instance, module->queryProp("@sourcePath")); Owned<IPropertyTreeIterator> defIter = module->getElements("Attribute"); ForEach(*defIter) { IPropertyTree * definition = &defIter->query(); addFilenameDependency(filenames, instance, definition->queryProp("@sourcePath")); } } OwnedIFileIO ifileio = createArchiveOutputFile(instance); if (ifileio) ifileio->write(0, filenames.length(), filenames.str()); } else { // Output option settings Owned<IStringIterator> debugValues = &instance.wu->getDebugValues(); ForEach (*debugValues) { SCMStringBuffer debugStr, valueStr; debugValues->str(debugStr); instance.wu->getDebugValue(debugStr.str(), valueStr); Owned<IPropertyTree> option = createPTree("Option"); option->setProp("@name", debugStr.str()); option->setProp("@value", valueStr.str()); instance.archive->addPropTree("Option", option.getClear()); } if (optManifestFilename) addManifestResourcesToArchive(instance.archive, optManifestFilename); outputXmlToOutputFile(instance, instance.archive); } } if (optGenerateMeta && instance.generatedMeta) outputXmlToOutputFile(instance, instance.generatedMeta); if (optWorkUnit && instance.wu) { StringBuffer xmlFilename; addNonEmptyPathSepChar(xmlFilename.append(optOutputDirectory)); if (outputFilename) xmlFilename.append(outputFilename); else xmlFilename.append(DEFAULT_OUTPUTNAME); xmlFilename.append(".xml"); exportWorkUnitToXMLFile(instance.wu, xmlFilename, 0, true, false); } } void EclCC::processReference(EclCompileInstance & instance, const char * queryAttributePath) { const char * outputFilename = instance.outputFilename; instance.wu.setown(createLocalWorkUnit()); if (optArchive || optGenerateDepend) instance.archive.setown(createAttributeArchive()); EclRepositoryArray repositories; repositories.append(*LINK(pluginsRepository)); repositories.append(*LINK(libraryRepository)); if (bundlesRepository) repositories.append(*LINK(bundlesRepository)); repositories.append(*LINK(includeRepository)); instance.dataServer.setown(createCompoundRepository(repositories)); processSingleQuery(instance, NULL, queryAttributePath); if (instance.reportErrorSummary()) return; generateOutput(instance); } bool EclCC::generatePrecompiledHeader() { if (inputFiles.ordinality() != 0) { ERRLOG("No input files should be specified when generating precompiled header"); return false; } StringArray paths; paths.appendList(cppIncludePath, ENVSEPSTR); const char *foundPath = NULL; ForEachItemIn(idx, paths) { StringBuffer fullpath; fullpath.append(paths.item(idx)); addPathSepChar(fullpath).append("eclinclude4.hpp"); if (checkFileExists(fullpath)) { foundPath = paths.item(idx); break; } } if (!foundPath) { ERRLOG("Cannot find eclinclude4.hpp"); return false; } Owned<ICppCompiler> compiler = createCompiler("eclinclude4.hpp", foundPath, NULL); compiler->setDebug(true); // a precompiled header with debug can be used for no-debug, but not vice versa compiler->setPrecompileHeader(true); if (compiler->compile()) { try { Owned<IFile> log = createIFile(cclogFilename); log->remove(); } catch (IException * e) { e->Release(); } return true; } else { ERRLOG("Compilation failed - see %s for details", cclogFilename.str()); return false; } } bool EclCC::processFiles() { loadOptions(); ForEachItemIn(idx, inputFileNames) { processArgvFilename(inputFiles, inputFileNames.item(idx)); } if (optShowPaths) { printf("CL_PATH=%s\n", compilerPath.str()); printf("ECLCC_ECLBUNDLE_PATH=%s\n", eclBundlePath.str()); printf("ECLCC_ECLINCLUDE_PATH=%s\n", stdIncludeLibraryPath.str()); printf("ECLCC_ECLLIBRARY_PATH=%s\n", eclLibraryPath.str()); printf("ECLCC_INCLUDE_PATH=%s\n", cppIncludePath.str()); printf("ECLCC_LIBRARY_PATH=%s\n", libraryPath.str()); printf("ECLCC_PLUGIN_PATH=%s\n", pluginsPath.str()); printf("ECLCC_TPL_PATH=%s\n", templatePath.str()); printf("HPCC_FILEHOOKS_PATH=%s\n", hooksPath.str()); return true; } if (optGenerateHeader) { return generatePrecompiledHeader(); } else if (inputFiles.ordinality() == 0) { if (optBatchMode || !optQueryRepositoryReference) { ERRLOG("No input files could be opened"); return false; } } StringBuffer searchPath; if (!optNoStdInc) searchPath.append(stdIncludeLibraryPath).append(ENVSEPCHAR); searchPath.append(includeLibraryPath); Owned<IErrorReceiver> errs = createFileErrorReceiver(stderr); pluginsRepository.setown(createNewSourceFileEclRepository(errs, pluginsPath.str(), ESFallowplugins, logVerbose ? PLUGIN_DLL_MODULE : 0)); if (!optNoBundles) bundlesRepository.setown(createNewSourceFileEclRepository(errs, eclBundlePath.str(), 0, 0)); libraryRepository.setown(createNewSourceFileEclRepository(errs, eclLibraryPath.str(), 0, 0)); includeRepository.setown(createNewSourceFileEclRepository(errs, searchPath.str(), 0, 0)); //Ensure symbols for plugins are initialised - see comment before CHqlMergedScope... // lookupAllRootDefinitions(pluginsRepository); bool ok = true; if (optBatchMode) { processBatchFiles(); } else if (inputFiles.ordinality() == 0) { assertex(optQueryRepositoryReference); EclCompileInstance info(NULL, *errs, stderr, optOutputFilename, optLegacyImport, optLegacyWhen); processReference(info, optQueryRepositoryReference); ok = (errs->errCount() == 0); info.logStats(); } else { EclCompileInstance info(&inputFiles.item(0), *errs, stderr, optOutputFilename, optLegacyImport, optLegacyWhen); processFile(info); ok = (errs->errCount() == 0); info.logStats(); } if (logTimings) { StringBuffer s; fprintf(stderr, "%s", defaultTimer->getTimings(s).str()); } return ok; } void EclCC::setDebugOption(const char * name, bool value) { StringBuffer temp; temp.append(name).append("=").append(value ? "1" : "0"); debugOptions.append(temp); } void EclCompileInstance::checkEclVersionCompatible() { //Strange function that might modify errorProcessor... ::checkEclVersionCompatible(errorProcessor, eclVersion); } void EclCompileInstance::logStats() { if (wu && wu->getDebugValueBool("logCompileStats", false)) { memsize_t peakVm, peakResident; getPeakMemUsage(peakVm, peakResident); //Stats: added as a prefix so it is easy to grep, and a comma so can be read as a csv list. DBGLOG("Stats:,parse,%u,generate,%u,peakmem,%u,xml,%"I64F"u,cpp,%"I64F"u", stats.parseTime, stats.generateTime, (unsigned)(peakResident / 0x100000), (unsigned __int64)stats.xmlSize, (unsigned __int64)stats.cppSize); } } bool EclCompileInstance::reportErrorSummary() { if (errorProcessor->errCount() || errorProcessor->warnCount()) { fprintf(errout, "%d error%s, %d warning%s\n", errorProcessor->errCount(), errorProcessor->errCount()<=1 ? "" : "s", errorProcessor->warnCount(), errorProcessor->warnCount()<=1?"":"s"); } return errorProcessor->errCount() != 0; } //========================================================================================= void EclCC::noteCluster(const char *clusterName) { } void EclCC::registerFile(const char * filename, const char * description) { } bool EclCC::allowAccess(const char * category) { ForEachItemIn(idx1, deniedPermissions) { if (stricmp(deniedPermissions.item(idx1), category)==0) return false; } ForEachItemIn(idx2, allowedPermissions) { if (stricmp(allowedPermissions.item(idx2), category)==0) return true; } return defaultAllowed; } //========================================================================================= bool EclCC::parseCommandLineOptions(int argc, const char* argv[]) { if (argc < 2) { usage(); return false; } ArgvIterator iter(argc, argv); StringAttr tempArg; bool tempBool; bool showHelp = false; for (; !iter.done(); iter.next()) { const char * arg = iter.query(); if (iter.matchFlag(tempArg, "-a")) { applicationOptions.append(tempArg); } else if (iter.matchOption(tempArg, "--allow")) { allowedPermissions.append(tempArg); } else if (iter.matchFlag(optBatchMode, "-b")) { } else if (iter.matchOption(tempArg, "-brk")) { #if defined(_WIN32) && defined(_DEBUG) unsigned id = atoi(tempArg); if (id == 0) DebugBreak(); else _CrtSetBreakAlloc(id); #endif } else if (iter.matchFlag(optOnlyCompile, "-c")) { } else if (iter.matchFlag(optCheckEclVersion, "-checkVersion")) { } else if (iter.matchOption(tempArg, "--deny")) { if (stricmp(tempArg, "all")==0) defaultAllowed = false; else deniedPermissions.append(tempArg); } else if (iter.matchFlag(optArchive, "-E")) { } else if (iter.matchFlag(tempArg, "-f")) { debugOptions.append(tempArg); } else if (iter.matchFlag(tempBool, "-g")) { if (tempBool) { debugOptions.append("debugQuery"); debugOptions.append("saveCppTempFiles"); } else debugOptions.append("debugQuery=0"); } else if (strcmp(arg, "-internal")==0) { testHqlInternals(); } else if (iter.matchFlag(tempBool, "-save-cpps")) { setDebugOption("saveCppTempFiles", tempBool); } else if (iter.matchFlag(tempBool, "-save-temps")) { setDebugOption("saveEclTempFiles", tempBool); } else if (iter.matchFlag(showHelp, "-help") || iter.matchFlag(showHelp, "--help")) { } else if (iter.matchPathFlag(includeLibraryPath, "-I")) { } else if (iter.matchFlag(tempArg, "-L")) { libraryPaths.append(tempArg); } else if (iter.matchFlag(tempBool, "-legacy")) { optLegacyImport = tempBool; optLegacyWhen = tempBool; } else if (iter.matchFlag(optLegacyImport, "-legacyimport")) { } else if (iter.matchFlag(optLegacyWhen, "-legacywhen")) { } else if (iter.matchOption(optLogfile, "--logfile")) { } else if (iter.matchFlag(optNoLogFile, "--nologfile")) { } else if (iter.matchFlag(optNoStdInc, "--nostdinc")) { } else if (iter.matchFlag(optNoBundles, "--nobundles")) { } else if (iter.matchOption(optLogDetail, "--logdetail")) { } else if (iter.matchOption(optQueryRepositoryReference, "-main")) { } else if (iter.matchFlag(optDebugMemLeak, "-m")) { } else if (iter.matchFlag(optIncludeMeta, "-meta")) { } else if (iter.matchFlag(optGenerateMeta, "-M")) { } else if (iter.matchFlag(optGenerateDepend, "-Md")) { } else if (iter.matchFlag(optEvaluateResult, "-Me")) { } else if (iter.matchFlag(optOutputFilename, "-o")) { } else if (iter.matchFlag(optOutputDirectory, "-P")) { } else if (iter.matchFlag(optGenerateHeader, "-pch")) { } else if (iter.matchFlag(optSaveQueryText, "-q")) { } else if (iter.matchFlag(optNoCompile, "-S")) { } else if (iter.matchFlag(optShared, "-shared")) { } else if (iter.matchFlag(tempBool, "-syntax")) { setDebugOption("syntaxCheck", tempBool); } else if (iter.matchOption(optIniFilename, "-specs")) { if (!checkFileExists(optIniFilename)) { ERRLOG("Error: INI file '%s' does not exist",optIniFilename.get()); return false; } } else if (iter.matchFlag(optShowPaths, "-showpaths")) { } else if (iter.matchOption(optManifestFilename, "-manifest")) { if (!isManifestFileValid(optManifestFilename)) return false; } else if (iter.matchOption(tempArg, "-split")) { batchPart = atoi(tempArg)-1; const char * split = strchr(tempArg, ':'); if (!split) { ERRLOG("Error: syntax is -split=part:splits\n"); return false; } batchSplit = atoi(split+1); if (batchSplit == 0) batchSplit = 1; if (batchPart >= batchSplit) batchPart = 0; } else if (iter.matchFlag(logTimings, "--timings")) { } else if (iter.matchOption(tempArg, "-platform") || /*deprecated*/ iter.matchOption(tempArg, "-target")) { if (!setTargetPlatformOption(tempArg.get(), optTargetClusterType)) return false; } else if (iter.matchFlag(logVerbose, "-v") || iter.matchFlag(logVerbose, "--verbose")) { Owned<ILogMsgFilter> filter = getDefaultLogMsgFilter(); queryLogMsgManager()->changeMonitorFilter(queryStderrLogMsgHandler(), filter); } else if (strcmp(arg, "--version")==0) { fprintf(stdout,"%s %s\n", LANGUAGE_VERSION, BUILD_TAG); return false; } else if (startsWith(arg, "-Wc,")) { expandCommaList(compileOptions, arg+4); } else if (startsWith(arg, "-Wl,")) { //Pass these straight through to the linker - with -Wl, prefix removed linkOptions.append(arg+4); } else if (startsWith(arg, "-Wp,") || startsWith(arg, "-Wa,")) { //Pass these straight through to the gcc compiler compileOptions.append(arg); } else if (iter.matchFlag(optWorkUnit, "-wu")) { } else if (iter.matchFlag(tempArg, "-w")) { //Any other option beginning -wxxx are treated as warning mappings warningMappings.append(tempArg); } else if (strcmp(arg, "-")==0) { inputFileNames.append("stdin:"); } else if (arg[0] == '-') { ERRLOG("Error: unrecognised option %s",arg); usage(); return false; } else inputFileNames.append(arg); } if (showHelp) { usage(); return false; } // Option post processing follows: if (optArchive || optWorkUnit || optGenerateMeta || optGenerateDepend || optShowPaths) optNoCompile = true; loadManifestOptions(); if (inputFileNames.ordinality() == 0) { if (optGenerateHeader || optShowPaths || (!optBatchMode && optQueryRepositoryReference)) return true; ERRLOG("No input filenames supplied"); return false; } if (optDebugMemLeak) { StringBuffer title; title.append(inputFileNames.item(0)).newline(); initLeakCheck(title); } return true; } //========================================================================================= // Exclamation in the first column indicates it is only part of the verbose output const char * const helpText[] = { "", "Usage:", " eclcc <options> queryfile.ecl", "", "General options:", " -I <path> Add path to locations to search for ecl imports", " -L <path> Add path to locations to search for system libraries", " -o <file> Specify name of output file (default a.out if linking to", " executable, or stdout)", " -manifest Specify path to manifest file listing resources to add", " -foption[=value] Set an ecl option (#option)", " -main <ref> Compile definition <ref> from the source collection", " -syntax Perform a syntax check of the ECL", " -platform=hthor Generate code for hthor executable (default)", " -platform=roxie Generate code for roxie cluster", " -platform=thor Generate code for thor cluster", "", "Output control options", " -E Output preprocessed ECL in xml archive form", "! -M Output meta information for the ecl files", "! -Md Output dependency information", "! -Me eclcc should evaluate supplied ecl code rather than generating a workunit", " -q Save ECL query text as part of workunit", " -wu Only generate workunit information as xml file", "", "c++ options", " -S Generate c++ output, but don't compile", "! -c compile only (don't link)", " -g Enable debug symbols in generated code", " -Wc,xx Pass option xx to the c++ compiler", "! -Wl,xx Pass option xx to the linker", "! -Wa,xx Passed straight through to c++ compiler", "! -Wp,xx Passed straight through to c++ compiler", "! -save-cpps Do not delete generated c++ files (implied if -g)", "! -save-temps Do not delete intermediate files", " -shared Generate workunit shared object instead of a stand-alone exe", "", "Other options:", "! -aoption[=value] Set an application option", "! --allow=str Allow use of named feature", "! -b Batch mode. Each source file is processed in turn. Output", "! name depends on the input filename", "! -checkVersion Enable/disable ecl version checking from archives", #ifdef _WIN32 "! -brk <n> Trigger a break point in eclcc after nth allocation", #endif "! --deny=all Disallow use of all named features not specifically allowed using --allow", "! --deny=str Disallow use of named feature", " -help, --help Display this message", " -help -v Display verbose help message", "! -internal Run internal tests", "! -legacy Use legacy import and when semantics (deprecated)", "! -legacyimport Use legacy import semantics (deprecated)", "! -legacywhen Use legacy when/side-effects semantics (deprecated)", " --logfile <file> Write log to specified file", "! --logdetail=n Set the level of detail in the log file", "! --nologfile Do not write any logfile", #ifdef _WIN32 "! -m Enable leak checking", #endif #ifndef _WIN32 "! -pch Generate precompiled header for eclinclude4.hpp", #endif "! -P <path> Specify the path of the output files (only with -b option)", "! -showpaths Print information about the searchpaths eclcc is using", " -specs file Read eclcc configuration from specified file", "! -split m:n Process a subset m of n input files (only with -b option)", " -v --verbose Output additional tracing information while compiling", " -wcode=level Set the severity for a particular warning code", "! level=ignore|log|warning|error|fail", " --version Output version information", "! --timings Output additional timing information", "!", "!#options", "! -factivitiesPerCpp Number of activities in each c++ file", "! (requires -fspanMultipleCpp)", "! -fapplyInstantEclTransformations Limit non file outputs with a CHOOSEN", "! -fapplyInstantEclTransformationsLimit Number of records to limit to", "! -fcheckAsserts Check ASSERT() statements", "! -fmaxCompileThreads Number of compiler instances to compile the c++", "! -fnoteRecordSizeInGraph Add estimates of record sizes to the graph", "! -fpickBestEngine Allow simple thor queries to be passed to thor", "! -fshowActivitySizeInGraph Show estimates of generated c++ size in the graph", "! -fshowMetaInGraph Add distribution/sort orders to the graph", "! -fshowRecordCountInGraph Show estimates of record counts in the graph", "! -fspanMultipleCpp Generate a work unit in multiple c++ files", "", }; void EclCC::usage() { for (unsigned line=0; line < _elements_in(helpText); line++) { const char * text = helpText[line]; if (*text == '!') { if (logVerbose) { //Allow conditional headers if (text[1] == ' ') fprintf(stdout, " %s\n", text+1); else fprintf(stdout, "%s\n", text+1); } } else fprintf(stdout, "%s\n", text); } } //========================================================================================= // The following methods are concerned with running eclcc in batch mode (primarily to aid regression testing) void EclCC::processBatchedFile(IFile & file, bool multiThreaded) { StringBuffer basename, logFilename, xmlFilename, outFilename; splitFilename(file.queryFilename(), NULL, NULL, &basename, &basename); addNonEmptyPathSepChar(logFilename.append(optOutputDirectory)).append(basename).append(".log"); addNonEmptyPathSepChar(xmlFilename.append(optOutputDirectory)).append(basename).append(".xml"); splitFilename(file.queryFilename(), NULL, NULL, &outFilename, &outFilename); unsigned startTime = msTick(); FILE * logFile = fopen(logFilename.str(), "w"); if (!logFile) throw MakeStringException(99, "couldn't create log output %s", logFilename.str()); Owned<ILogMsgHandler> handler; try { // Print compiler and arguments to help reproduce problems for (int i=0; i<argc; i++) fprintf(logFile, "%s ", argv[i]); fprintf(logFile, "\n"); fprintf(logFile, "--- %s --- \n", basename.str()); { if (!multiThreaded) { handler.setown(getHandleLogMsgHandler(logFile, 0, false)); Owned<ILogMsgFilter> filter = getCategoryLogMsgFilter(MSGAUD_all, MSGCLS_all, DefaultDetail); queryLogMsgManager()->addMonitor(handler, filter); resetUniqueId(); resetLexerUniqueNames(); } Owned<IErrorReceiver> localErrs = createFileErrorReceiver(logFile); EclCompileInstance info(&file, *localErrs, logFile, outFilename, optLegacyImport, optLegacyWhen); processFile(info); //Following only produces output if the system has been compiled with TRANSFORM_STATS defined dbglogTransformStats(true); if (info.wu && (info.wu->getDebugValueBool("generatePartialOutputOnError", false) || info.queryErrorProcessor().errCount() == 0)) { exportWorkUnitToXMLFile(info.wu, xmlFilename, XML_NoBinaryEncode64, true, false); Owned<IFile> xml = createIFile(xmlFilename); info.stats.xmlSize = xml->size(); } info.logStats(); } } catch (IException * e) { StringBuffer s; e->errorMessage(s); e->Release(); fprintf(logFile, "Unexpected exception: %s", s.str()); } if (handler) { queryLogMsgManager()->removeMonitor(handler); handler.clear(); } fflush(logFile); fclose(logFile); unsigned nowTime = msTick(); StringBuffer s; s.append(basename).append(":"); s.padTo(50); s.appendf("%8d ms\n", nowTime-startTime); fprintf(batchLog, "%s", s.str()); // fflush(batchLog); } typedef SafeQueueOf<IFile, true> RegressQueue; class BatchThread : public Thread { public: BatchThread(EclCC & _compiler, RegressQueue & _queue, Semaphore & _fileReady) : compiler(_compiler), queue(_queue), fileReady(_fileReady) { } virtual int run() { loop { fileReady.wait(); IFile * next = queue.dequeue(); if (!next) return 0; compiler.processBatchedFile(*next, true); next->Release(); } } protected: EclCC & compiler; RegressQueue & queue; Semaphore & fileReady; }; int compareFilenames(IInterface * * pleft, IInterface * * pright) { IFile * left = static_cast<IFile *>(*pleft); IFile * right = static_cast<IFile *>(*pright); return stricmp(pathTail(left->queryFilename()), pathTail(right->queryFilename())); } void EclCC::processBatchFiles() { Thread * * threads = NULL; RegressQueue queue; Semaphore fileReady; unsigned startAllTime = msTick(); if (optThreads > 0) { threads = new Thread * [optThreads]; for (unsigned i = 0; i < optThreads; i++) { threads[i] = new BatchThread(*this, queue, fileReady); threads[i]->start(); } } StringBuffer batchLogName; addNonEmptyPathSepChar(batchLogName.append(optOutputDirectory)).append("_batch_."); batchLogName.append(batchPart+1); batchLogName.append(".log"); batchLog = fopen(batchLogName.str(), "w"); if (!batchLog) throw MakeStringException(99, "couldn't create log output %s", batchLogName.str()); //Divide the files up based on file size, rather than name inputFiles.sort(compareFilenames); unsigned __int64 totalSize = 0; ForEachItemIn(iSize, inputFiles) { IFile & cur = inputFiles.item(iSize); totalSize += cur.size(); } //Sort the filenames so you have a consistent order between windows and linux unsigned __int64 averageFileSize = totalSize / inputFiles.ordinality(); unsigned splitter = 0; unsigned __int64 sizeSoFar = 0; ForEachItemIn(i, inputFiles) { IFile &file = inputFiles.item(i); if (splitter == batchPart) { if (optThreads > 0) { queue.enqueue(LINK(&file)); fileReady.signal(); } else processBatchedFile(file, false); } unsigned __int64 thisSize = file.size(); sizeSoFar += thisSize; if (sizeSoFar > averageFileSize) { sizeSoFar = 0; splitter++; } if (splitter == batchSplit) splitter = 0; } if (optThreads > 0) { for (unsigned i = 0; i < optThreads; i++) fileReady.signal(); for (unsigned j = 0; j < optThreads; j++) threads[j]->join(); for (unsigned i2 = 0; i2 < optThreads; i2++) threads[i2]->Release(); delete [] threads; } fprintf(batchLog, "@%5ds total time for part %d\n", (msTick()-startAllTime)/1000, batchPart); fclose(batchLog); batchLog = NULL; }
35.300174
184
0.612988
emuharemagic
66f2310ec0f3c4737a68f1e81e8b753137c2bc38
14,932
cc
C++
device/fido/auth_token_requester.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
14,668
2015-01-01T01:57:10.000Z
2022-03-31T23:33:32.000Z
device/fido/auth_token_requester.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
86
2015-10-21T13:02:42.000Z
2022-03-14T07:50:50.000Z
device/fido/auth_token_requester.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
5,941
2015-01-02T11:32:21.000Z
2022-03-31T16:35:46.000Z
// Copyright 2020 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 "device/fido/auth_token_requester.h" #include <set> #include <utility> #include "base/bind.h" #include "base/containers/contains.h" #include "base/logging.h" #include "base/stl_util.h" #include "base/strings/utf_string_conversions.h" #include "components/device_event_log/device_event_log.h" #include "device/fido/authenticator_supported_options.h" #include "device/fido/fido_authenticator.h" #include "device/fido/fido_constants.h" namespace device { using ClientPinAvailability = AuthenticatorSupportedOptions::ClientPinAvailability; using UserVerificationAvailability = AuthenticatorSupportedOptions::UserVerificationAvailability; using BioEnrollmentAvailability = AuthenticatorSupportedOptions::BioEnrollmentAvailability; AuthTokenRequester::Delegate::~Delegate() = default; AuthTokenRequester::Options::Options() = default; AuthTokenRequester::Options::Options(Options&&) = default; AuthTokenRequester::Options& AuthTokenRequester::Options::operator=(Options&&) = default; AuthTokenRequester::Options::~Options() = default; AuthTokenRequester::AuthTokenRequester(Delegate* delegate, FidoAuthenticator* authenticator, Options options) : delegate_(delegate), authenticator_(authenticator), options_(std::move(options)), internal_uv_locked_(options_.internal_uv_locked) { DCHECK(delegate_); DCHECK(authenticator_); DCHECK(authenticator_->Options()); DCHECK(!options_.token_permissions.empty()); DCHECK(!options_.rp_id || !options_.rp_id->empty()); // Authenticators with CTAP2.0-style pinToken support only support certain // default permissions. DCHECK( authenticator_->Options()->supports_pin_uv_auth_token || base::STLSetDifference<std::set<pin::Permissions>>( options_.token_permissions, std::set<pin::Permissions>{pin::Permissions::kMakeCredential, pin::Permissions::kGetAssertion, pin::Permissions::kBioEnrollment, pin::Permissions::kCredentialManagement}) .empty()); } AuthTokenRequester::~AuthTokenRequester() = default; void AuthTokenRequester::ObtainPINUVAuthToken() { if (authenticator_->Options()->supports_pin_uv_auth_token) { // Only attempt to obtain a token through internal UV if the authenticator // supports CTAP 2.1 pinUvAuthTokens. If it does not, it could be a 2.0 // authenticator that supports UV without any sort of token. const UserVerificationAvailability user_verification_availability = authenticator_->Options()->user_verification_availability; switch (user_verification_availability) { case UserVerificationAvailability::kNotSupported: case UserVerificationAvailability::kSupportedButNotConfigured: // Try PIN first. break; case UserVerificationAvailability::kSupportedAndConfigured: ObtainTokenFromInternalUV(); return; } } const ClientPinAvailability client_pin_availability = authenticator_->Options()->client_pin_availability; switch (client_pin_availability) { case ClientPinAvailability::kNotSupported: delegate_->HavePINUVAuthTokenResultForAuthenticator( authenticator_, Result::kPreTouchUnsatisfiableRequest, absl::nullopt); return; case ClientPinAvailability::kSupportedAndPinSet: if (options_.skip_pin_touch) { ObtainTokenFromPIN(); return; } authenticator_->GetTouch(base::BindOnce( &AuthTokenRequester::ObtainTokenFromPIN, weak_factory_.GetWeakPtr())); return; case ClientPinAvailability::kSupportedButPinNotSet: if (options_.skip_pin_touch) { ObtainTokenFromNewPIN(); return; } authenticator_->GetTouch( base::BindOnce(&AuthTokenRequester::ObtainTokenFromNewPIN, weak_factory_.GetWeakPtr())); return; } } void AuthTokenRequester::ObtainTokenFromInternalUV() { authenticator_->GetUvRetries(base::BindOnce( &AuthTokenRequester::OnGetUVRetries, weak_factory_.GetWeakPtr())); } void AuthTokenRequester::OnGetUVRetries( CtapDeviceResponseCode status, absl::optional<pin::RetriesResponse> response) { if (status != CtapDeviceResponseCode::kSuccess) { delegate_->HavePINUVAuthTokenResultForAuthenticator( authenticator_, Result::kPreTouchAuthenticatorResponseInvalid, absl::nullopt); return; } internal_uv_locked_ = response->retries == 0; if (response->retries == 0) { // The authenticator was locked prior to calling // ObtainTokenFromInternalUV(). Fall back to PIN if able. if (authenticator_->Options()->client_pin_availability == ClientPinAvailability::kSupportedAndPinSet) { if (options_.skip_pin_touch) { ObtainTokenFromPIN(); return; } authenticator_->GetTouch(base::BindOnce( &AuthTokenRequester::ObtainTokenFromPIN, weak_factory_.GetWeakPtr())); return; } authenticator_->GetTouch(base::BindOnce( &AuthTokenRequester::NotifyAuthenticatorSelectedAndFailWithResult, weak_factory_.GetWeakPtr(), Result::kPostTouchAuthenticatorInternalUVLock)); return; } if (is_internal_uv_retry_) { delegate_->PromptForInternalUVRetry(response->retries); } authenticator_->GetUvToken({std::begin(options_.token_permissions), std::end(options_.token_permissions)}, options_.rp_id, base::BindOnce(&AuthTokenRequester::OnGetUVToken, weak_factory_.GetWeakPtr())); } void AuthTokenRequester::OnGetUVToken( CtapDeviceResponseCode status, absl::optional<pin::TokenResponse> response) { if (!base::Contains( std::set<CtapDeviceResponseCode>{ CtapDeviceResponseCode::kCtap2ErrUvInvalid, CtapDeviceResponseCode::kCtap2ErrOperationDenied, CtapDeviceResponseCode::kCtap2ErrUvBlocked, CtapDeviceResponseCode::kSuccess}, status)) { // The request was rejected outright, no touch occurred. FIDO_LOG(ERROR) << "Ignoring status " << static_cast<int>(status) << " from " << authenticator_->GetDisplayName(); delegate_->HavePINUVAuthTokenResultForAuthenticator( authenticator_, Result::kPreTouchAuthenticatorResponseInvalid, absl::nullopt); return; } if (!NotifyAuthenticatorSelected()) { return; } if (status == CtapDeviceResponseCode::kCtap2ErrOperationDenied) { // The user explicitly denied to the operation on an authenticator with // a display. delegate_->HavePINUVAuthTokenResultForAuthenticator( authenticator_, Result::kPostTouchAuthenticatorOperationDenied, absl::nullopt); return; } if (status == CtapDeviceResponseCode::kCtap2ErrUvInvalid) { // The attempt failed, but a retry is possible. is_internal_uv_retry_ = true; ObtainTokenFromInternalUV(); return; } if (status == CtapDeviceResponseCode::kCtap2ErrUvBlocked) { // Fall back to PIN if able. if (authenticator_->Options()->client_pin_availability == ClientPinAvailability::kSupportedAndPinSet) { internal_uv_locked_ = true; ObtainTokenFromPIN(); return; } // This can be returned pre-touch if the authenticator was already locked at // the time GetUvToken() was called. However, we checked the number of // remaining retries just before that to handle that case. delegate_->HavePINUVAuthTokenResultForAuthenticator( authenticator_, Result::kPostTouchAuthenticatorInternalUVLock, absl::nullopt); return; } DCHECK_EQ(status, CtapDeviceResponseCode::kSuccess); delegate_->HavePINUVAuthTokenResultForAuthenticator( authenticator_, Result::kSuccess, *response); } void AuthTokenRequester::ObtainTokenFromPIN() { if (NotifyAuthenticatorSelected()) { authenticator_->GetPinRetries(base::BindOnce( &AuthTokenRequester::OnGetPINRetries, weak_factory_.GetWeakPtr())); } } void AuthTokenRequester::OnGetPINRetries( CtapDeviceResponseCode status, absl::optional<pin::RetriesResponse> response) { if (status != CtapDeviceResponseCode::kSuccess) { delegate_->HavePINUVAuthTokenResultForAuthenticator( authenticator_, Result::kPostTouchAuthenticatorResponseInvalid, absl::nullopt); return; } if (response->retries == 0) { delegate_->HavePINUVAuthTokenResultForAuthenticator( authenticator_, Result::kPostTouchAuthenticatorPINHardLock, absl::nullopt); return; } pin_retries_ = response->retries; pin::PINEntryError error; if (pin_invalid_) { pin_invalid_ = false; error = pin::PINEntryError::kWrongPIN; } else if (internal_uv_locked_) { error = pin::PINEntryError::kInternalUvLocked; } else { error = pin::PINEntryError::kNoError; } delegate_->CollectPIN( pin::PINEntryReason::kChallenge, error, authenticator_->CurrentMinPINLength(), pin_retries_, base::BindOnce(&AuthTokenRequester::HavePIN, weak_factory_.GetWeakPtr())); } void AuthTokenRequester::HavePIN(std::u16string pin16) { pin::PINEntryError error = pin::ValidatePIN( pin16, authenticator_->CurrentMinPINLength(), current_pin_); if (error != pin::PINEntryError::kNoError) { delegate_->CollectPIN(pin::PINEntryReason::kChallenge, error, authenticator_->CurrentMinPINLength(), pin_retries_, base::BindOnce(&AuthTokenRequester::HavePIN, weak_factory_.GetWeakPtr())); return; } std::string pin = base::UTF16ToUTF8(pin16); authenticator_->GetPINToken(pin, {std::begin(options_.token_permissions), std::end(options_.token_permissions)}, options_.rp_id, base::BindOnce(&AuthTokenRequester::OnGetPINToken, weak_factory_.GetWeakPtr(), pin)); return; } void AuthTokenRequester::OnGetPINToken( std::string pin, CtapDeviceResponseCode status, absl::optional<pin::TokenResponse> response) { if (status == CtapDeviceResponseCode::kCtap2ErrPinInvalid) { pin_invalid_ = true; ObtainTokenFromPIN(); return; } if (status != CtapDeviceResponseCode::kSuccess) { Result ret; switch (status) { case CtapDeviceResponseCode::kCtap2ErrPinPolicyViolation: // The user needs to set a new PIN before they can use the device. current_pin_ = pin; delegate_->CollectPIN(pin::PINEntryReason::kChange, pin::PINEntryError::kNoError, authenticator_->NewMinPINLength(), /*attempts=*/0, base::BindOnce(&AuthTokenRequester::HaveNewPIN, weak_factory_.GetWeakPtr())); return; case CtapDeviceResponseCode::kCtap2ErrPinAuthBlocked: ret = Result::kPostTouchAuthenticatorPINSoftLock; break; case CtapDeviceResponseCode::kCtap2ErrPinBlocked: ret = Result::kPostTouchAuthenticatorPINHardLock; break; default: ret = Result::kPostTouchAuthenticatorResponseInvalid; break; } delegate_->HavePINUVAuthTokenResultForAuthenticator(authenticator_, ret, absl::nullopt); return; } delegate_->HavePINUVAuthTokenResultForAuthenticator( authenticator_, Result::kSuccess, std::move(*response)); } void AuthTokenRequester::ObtainTokenFromNewPIN() { if (NotifyAuthenticatorSelected()) { delegate_->CollectPIN(pin::PINEntryReason::kSet, pin::PINEntryError::kNoError, authenticator_->NewMinPINLength(), /*attempts=*/0, base::BindOnce(&AuthTokenRequester::HaveNewPIN, weak_factory_.GetWeakPtr())); } } void AuthTokenRequester::HaveNewPIN(std::u16string pin16) { pin::PINEntryError error = pin::ValidatePIN(pin16, authenticator_->NewMinPINLength(), current_pin_); if (error != pin::PINEntryError::kNoError) { delegate_->CollectPIN( current_pin_ ? pin::PINEntryReason::kChange : pin::PINEntryReason::kSet, error, authenticator_->NewMinPINLength(), /*attempts=*/0, base::BindOnce(&AuthTokenRequester::HaveNewPIN, weak_factory_.GetWeakPtr())); return; } std::string pin = base::UTF16ToUTF8(pin16); if (current_pin_) { authenticator_->ChangePIN(*current_pin_, pin, base::BindOnce(&AuthTokenRequester::OnSetPIN, weak_factory_.GetWeakPtr(), pin)); return; } authenticator_->SetPIN(pin, base::BindOnce(&AuthTokenRequester::OnSetPIN, weak_factory_.GetWeakPtr(), pin)); return; } void AuthTokenRequester::OnSetPIN(std::string pin, CtapDeviceResponseCode status, absl::optional<pin::EmptyResponse> response) { if (status != CtapDeviceResponseCode::kSuccess) { delegate_->HavePINUVAuthTokenResultForAuthenticator( authenticator_, Result::kPostTouchAuthenticatorResponseInvalid, absl::nullopt); return; } // Having just set the PIN, we need to immediately turn around and use it to // get a PIN token. authenticator_->GetPINToken(std::move(pin), {std::begin(options_.token_permissions), std::end(options_.token_permissions)}, options_.rp_id, base::BindOnce(&AuthTokenRequester::OnGetPINToken, weak_factory_.GetWeakPtr(), pin)); } bool AuthTokenRequester::NotifyAuthenticatorSelected() { if (!authenticator_selected_result_.has_value()) { authenticator_selected_result_ = delegate_->AuthenticatorSelectedForPINUVAuthToken(authenticator_); } return *authenticator_selected_result_; } void AuthTokenRequester::NotifyAuthenticatorSelectedAndFailWithResult( Result result) { if (NotifyAuthenticatorSelected()) { delegate_->HavePINUVAuthTokenResultForAuthenticator(authenticator_, result, absl::nullopt); } } } // namespace device
38.189258
80
0.666086
zealoussnow
66f245cdcb57bc5b2b9cbd80369a433be10de696
14,417
hpp
C++
lib/mana/include/mana/router.hpp
Mattlk13/include-OS
d1668b94a007615db458fc394c94127631a55309
[ "Apache-2.0" ]
null
null
null
lib/mana/include/mana/router.hpp
Mattlk13/include-OS
d1668b94a007615db458fc394c94127631a55309
[ "Apache-2.0" ]
null
null
null
lib/mana/include/mana/router.hpp
Mattlk13/include-OS
d1668b94a007615db458fc394c94127631a55309
[ "Apache-2.0" ]
null
null
null
// This file is a part of the IncludeOS unikernel - www.includeos.org // // Copyright 2015-2016 Oslo and Akershus University College of Applied Sciences // and Alfred Bratterud // // 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 MANA_ROUTER_HPP #define MANA_ROUTER_HPP #include <sstream> #include <stdexcept> #include <algorithm> #include "route.hpp" #include "params.hpp" namespace mana { //------------------------------- // This class is used to provide // route resolution //------------------------------- class Router { private: //------------------------------- // Internal class type aliases //using Span = gsl::span<char>; using Route_table = std::unordered_map<http::Method, std::vector<Route>>; //------------------------------- public: /** * @brief Returned in match-method. * Contains both the End_point and the route parameters so that both can be returned. */ struct ParsedRoute { End_point job; Params parsed_values; }; //------------------------------- // Default constructor to set up // default routes //------------------------------- explicit Router() = default; //------------------------------- // Default destructor //------------------------------- ~Router() noexcept = default; //------------------------------- // Default move constructor //------------------------------- Router(Router&&) = default; //------------------------------- // Default move assignment operator //------------------------------- Router& operator = (Router&&) = default; //------------------------------- // Add a route mapping for route // resolution upon request // // @tparam (std::string) route - The route to map unto a // resulting destination // // @param result - The route mapping // // @return - The object that invoked this method //------------------------------- template <typename Routee> Router& on_options(Routee&& route, End_point result); //------------------------------- // Add a route mapping for route // resolution upon request // // @tparam (std::string) route - The route to map unto a // resulting destination // // @param result - The route mapping // // @return - The object that invoked this method //------------------------------- template <typename Routee> Router& on_get(Routee&& route, End_point result); //------------------------------- // Add a route mapping for route // resolution upon request // // @tparam (std::string) route - The route to map unto a // resulting destination // // @param result - The route mapping // // @return - The object that invoked this method //------------------------------- template <typename Routee> Router& on_head(Routee&& route, End_point result); //------------------------------- // Add a route mapping for route // resolution upon request // // @tparam (std::string) route - The route to map unto a // resulting destination // // @param result - The route mapping // // @return - The object that invoked this method //------------------------------- template <typename Routee> Router& on_post(Routee&& route, End_point result); //------------------------------- // Add a route mapping for route // resolution upon request // // @tparam (std::string) route - The route to map unto a // resulting destination // // @param result - The route mapping // // @return - The object that invoked this method //------------------------------- template <typename Routee> Router& on_put(Routee&& route, End_point result); //------------------------------- // Add a route mapping for route // resolution upon request // // @tparam (std::string) route - The route to map unto a // resulting destination // // @param result - The route mapping // // @return - The object that invoked this method //------------------------------- template <typename Routee> Router& on_delete(Routee&& route, End_point result); //------------------------------- // Add a route mapping for route // resolution upon request // // @tparam (std::string) route - The route to map unto a // resulting destination // // @param result - The route mapping // // @return - The object that invoked this method //------------------------------- template <typename Routee> Router& on_trace(Routee&& route, End_point result); //------------------------------- // Add a route mapping for route // resolution upon request // // @tparam (std::string) route - The route to map unto a // resulting destination // // @param result - The route mapping // // @return - The object that invoked this method //------------------------------- template <typename Routee> Router& on_connect(Routee&& route, End_point result); //------------------------------- // Add a route mapping for route // resolution upon request // // @tparam (std::string) route - The route to map unto a // resulting destination // // @param result - The route mapping // // @return - The object that invoked this method //------------------------------- template <typename Routee> Router& on_patch(Routee&& route, End_point result); //------------------------------- // General way to add a route mapping for route // resolution upon request // // @param method - HTTP method // // @tparam (std::string) route - The route to map unto a // resulting destination // // @param result - The route mapping // // @return - The object that invoked this method //------------------------------- template <typename Routee> Router& on(http::Method method, Routee&& route, End_point result); //------------------------------- // Install a new route table for // route resolutions // // @tparam (http::Router) new_routes - The new route table // to install // // @return - The object that invoked this method //------------------------------- template <typename Routee_Table> Router& install_new_configuration(Routee_Table&& new_routes); /** * Get the route callback where Route_expr matched a given path * * @param path : the route path * @note : not const becuase it uses index operator to a map **/ inline ParsedRoute match(http::Method, const std::string&); /** * @brief Make the router use another router on a given route * @details Currently only copies the content from the outside * Router and adds new Route in RouteTable by combining * root route and the route to the other Route. * * Maybe Router should be able to keep a collection of other routers. * * @param Routee Root path * @param Router another router with Routes * * @return this Router */ template <typename Routee> Router& use(Routee&&, const Router&); /** * @brief Copies Routes from another Router object * * @param Router to be copied from * @return this Router */ Router& add(const Router&); /** * @brief Optimize route search for all routes by bringing * the most hitted route to the front of the search queue * * @return The object that invoked this method */ Router& optimize_route_search(); /** * @brief Optimize route search for the specified HTTP method * by bringing the most hitted route to the front of the * search queue * * @param method * The HTTP method to optimize search for * * @return The object that invoked this method */ Router& optimize_route_search(const http::Method method); Router& operator<<(const Router& obj) { return add(obj); } std::string to_string() const; private: Router(const Router&) = delete; Router& operator = (const Router&) = delete; Route_table route_table_; }; //< class Router class Router_error : public std::runtime_error { using runtime_error::runtime_error; }; /**--v----------- Implementation Details -----------v--**/ template <typename Routee> inline Router& Router::on_options(Routee&& route, End_point result) { route_table_[http::OPTIONS].emplace_back(std::forward<Routee>(route), result); return *this; } template <typename Routee> inline Router& Router::on_get(Routee&& route, End_point result) { route_table_[http::GET].emplace_back(std::forward<Routee>(route), result); return *this; } template <typename Routee> inline Router& Router::on_head(Routee&& route, End_point result) { route_table_[http::HEAD].emplace_back(std::forward<Routee>(route), result); return *this; } template <typename Routee> inline Router& Router::on_post(Routee&& route, End_point result) { route_table_[http::POST].emplace_back(std::forward<Routee>(route), result); return *this; } template <typename Routee> inline Router& Router::on_put(Routee&& route, End_point result) { route_table_[http::PUT].emplace_back(std::forward<Routee>(route), result); return *this; } template <typename Routee> inline Router& Router::on_delete(Routee&& route, End_point result) { route_table_[http::DELETE].emplace_back(std::forward<Routee>(route), result); return *this; } template <typename Routee> inline Router& Router::on_trace(Routee&& route, End_point result) { route_table_[http::TRACE].emplace_back(std::forward<Routee>(route), result); return *this; } template <typename Routee> inline Router& Router::on_connect(Routee&& route, End_point result) { route_table_[http::CONNECT].emplace_back(std::forward<Routee>(route), result); return *this; } template <typename Routee> inline Router& Router::on_patch(Routee&& route, End_point result) { route_table_[http::PATCH].emplace_back(std::forward<Routee>(route), result); return *this; } template <typename Routee> inline Router& Router::on(http::Method method, Routee&& route, End_point result) { route_table_[method].emplace_back(std::forward<Routee>(route), result); return *this; } template <typename Routee_Table> inline Router& Router::install_new_configuration(Routee_Table&& new_routes) { route_table_ = std::forward<Routee_Table>(new_routes).route_table_; return *this; } inline Router::ParsedRoute Router::match(http::Method method, const std::string& path) { auto routes = route_table_[method]; if (routes.empty()) { throw Router_error("No routes for method " + http::method::str(method).to_string()); } for (auto& route : routes) { if (std::regex_match(path, route.expr)) { ++route.hits; // Set the pairs in params: Params params; std::smatch res; for (std::sregex_iterator i = std::sregex_iterator{path.begin(), path.end(), route.expr}; i != std::sregex_iterator{}; ++i) { res = *i; } // First parameter/value is in res[1], second in res[2], and so on for (size_t i = 0; i < route.keys.size(); i++) params.insert(route.keys[i].name, res[i + 1]); ParsedRoute parsed_route; parsed_route.job = route.end_point; parsed_route.parsed_values = params; return parsed_route; } } throw Router_error("No matching route for " + http::method::str(method).to_string() + " " + path); } template <typename Routee> inline Router& Router::use(Routee&& root, const Router& router) { // pair<Method, vector<Route>> for(auto& method_routes : router.route_table_) { auto& method = method_routes.first; auto& routes = method_routes.second; // vector<Route> for(auto& route : routes) { std::string path = root + route.path; on(method, path, route.end_point); } } return *this; } inline Router& Router::add(const Router& router) { for (const auto& e : router.route_table_) { auto it = route_table_.find(e.first); if (it not_eq route_table_.end()) { it->second.insert(it->second.cend(), e.second.cbegin(), e.second.cend()); continue; } route_table_[e.first] = e.second; } return *this; } inline Router& Router::optimize_route_search() { auto it = route_table_.begin(); auto end = route_table_.end(); while (it not_eq end) { std::stable_sort(it->second.begin(), it->second.end()); ++it; } return *this; } inline Router& Router::optimize_route_search(const http::Method method) { auto it = route_table_.find(method); if (it not_eq route_table_.end()) { std::stable_sort(it->second.begin(), it->second.end()); } return *this; } inline std::string Router::to_string() const { std::ostringstream ss; for(const auto& method_routes : route_table_) { auto&& method = method_routes.first; auto&& routes = method_routes.second; for(auto&& route : routes) { ss << method << '\t' << route.path << '\n'; } } return ss.str(); } /**--^----------- Implementation Details -----------^--**/ } //< namespace mana #endif //< MANA_ROUTER_HPP
30.805556
102
0.571131
Mattlk13
66f3e1236ee2f44761cb3b27eb9fbf29042508bf
13,768
cpp
C++
src/liblvr2/reconstruction/LBKdTree.cpp
jtpils/lvr2
b1010dfcc930d9ae0ff5cfa5c88d0810d65368ce
[ "BSD-3-Clause" ]
1
2019-08-07T03:55:27.000Z
2019-08-07T03:55:27.000Z
src/liblvr2/reconstruction/LBKdTree.cpp
jtpils/lvr2
b1010dfcc930d9ae0ff5cfa5c88d0810d65368ce
[ "BSD-3-Clause" ]
null
null
null
src/liblvr2/reconstruction/LBKdTree.cpp
jtpils/lvr2
b1010dfcc930d9ae0ff5cfa5c88d0810d65368ce
[ "BSD-3-Clause" ]
null
null
null
/** * Copyright (c) 2018, University Osnabrück * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the University Osnabrück 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 University Osnabrück 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. */ #include <stdio.h> #include <iostream> #include <lvr2/reconstruction/LBKdTree.hpp> namespace lvr2 { // Static variables ctpl::thread_pool* LBKdTree::pool;// = new ctpl::thread_pool(8); int LBKdTree::st_num_threads = 8; int LBKdTree::st_depth_threads = 3; /// Public LBKdTree::LBKdTree( LBPointArray<float>& vertices, int num_threads) { this->m_values = boost::shared_ptr<LBPointArray<float> >(new LBPointArray<float>); this->m_splits = boost::shared_ptr<LBPointArray<unsigned char> >(new LBPointArray<unsigned char>); st_num_threads = num_threads; st_depth_threads = static_cast<int>(log2(st_num_threads)); pool = new ctpl::thread_pool(st_num_threads); this->generateKdTree(vertices); } LBKdTree::~LBKdTree() { if(pool) { delete pool; } } void LBKdTree::generateKdTree(LBPointArray<float> &vertices) { LBPointArray<unsigned int>* indices_sorted = (LBPointArray<unsigned int>*)malloc(vertices.dim * sizeof(LBPointArray<unsigned int>) ); LBPointArray<float>* values_sorted = (LBPointArray<float>*)malloc(vertices.dim * sizeof(LBPointArray<float>) ); for(unsigned int i=0; i< vertices.dim; i++) { pool->push(generateAndSort<float, unsigned int>, vertices, indices_sorted, values_sorted, i); //generateAndSort<float, unsigned int>(0, vertices, indices_sorted, values_sorted, i); } pool->stop(true); delete pool; pool = new ctpl::thread_pool(st_num_threads); this->generateKdTreeArray(vertices, indices_sorted, vertices.dim); for(unsigned int i=0; i<vertices.dim;i++) { //free(indices_sorted[i].elements); free(values_sorted[i].elements); } //free(indices_sorted); //free(values_sorted); } boost::shared_ptr<LBPointArray<float> > LBKdTree::getKdTreeValues() { return this->m_values; } boost::shared_ptr<LBPointArray<unsigned char> > LBKdTree::getKdTreeSplits() { return this->m_splits; } /// Private void LBKdTree::generateKdTreeArray(LBPointArray<float>& V, LBPointArray<unsigned int>* sorted_indices, int max_dim) { // DEBUG CHECK int first_split_dim = -1; float best_deviation = -1.0; // std::cout << "BOX:" << std::endl; for(int i=0; i<V.dim; i++) { float deviation = V.elements[static_cast<unsigned int>( sorted_indices[i].elements[sorted_indices[i].width-1]+0.5)* V.dim + i] - V.elements[static_cast<unsigned int>( sorted_indices[i].elements[i]+0.5)* V.dim + i] ; // std::cout << "Dim: " << i << " size: "<< deviation << std::endl; if(deviation > best_deviation) { best_deviation = deviation; first_split_dim = i; } } unsigned int size; int max_tree_depth; max_tree_depth = static_cast<int>( log2f(V.width - 1 ) + 2.0 ) ; if (V.width == 1) { max_tree_depth = 1; } size = V.width * 2 - 1; // std::cout << "size values: " << size << std::endl; this->m_values->elements = (float*)malloc(sizeof(float) * size ); this->m_values->width = size; this->m_values->dim = 1; unsigned int size_splits = size - V.width; // std::cout << "size splits: " << size_splits << std::endl; this->m_splits->elements = (unsigned char*)malloc(sizeof(unsigned char) * size_splits ); this->m_splits->width = size_splits; this->m_splits->dim = 1; LBPointArray<float>* value_ptr = this->m_values.get(); LBPointArray<unsigned char>* splits_ptr = this->m_splits.get(); //start real generate generateKdTreeRecursive(0, V, sorted_indices, first_split_dim, max_dim, value_ptr, splits_ptr ,size, max_tree_depth, 0, 0); pool->stop(true); delete pool; pool = new ctpl::thread_pool(st_num_threads); } void LBKdTree::fillCriticalIndices(const LBPointArray<float>& V, LBPointArray<unsigned int>& sorted_indices, unsigned int current_dim, float split_value, unsigned int split_index, std::list<unsigned int>& critical_indices_left, std::list<unsigned int>& critical_indices_right) { critical_indices_left.push_back( sorted_indices.elements[split_index] ); unsigned int iterator; // nach links for(iterator = split_index-1; iterator < sorted_indices.width && V.elements[ sorted_indices.elements[iterator] * V.dim + current_dim] == split_value; iterator--) { critical_indices_left.push_back( sorted_indices.elements[iterator] ); } // nach rechts for(iterator = split_index+1; iterator < sorted_indices.width && V.elements[ sorted_indices.elements[iterator] * V.dim + current_dim] == split_value; iterator++) { critical_indices_right.push_back( sorted_indices.elements[iterator] ); } } void LBKdTree::fillCriticalIndicesSet(const LBPointArray<float>& V, LBPointArray<unsigned int>& sorted_indices, unsigned int current_dim, float split_value, unsigned int split_index, std::unordered_set<unsigned int>& critical_indices_left, std::unordered_set<unsigned int>& critical_indices_right) { //critical_indices_left.push_back( sorted_indices.elements[split_index] ); critical_indices_left.insert(sorted_indices.elements[split_index]); unsigned int iterator; // nach links for(iterator = split_index-1; iterator < sorted_indices.width && V.elements[ sorted_indices.elements[iterator] * V.dim + current_dim] == split_value; iterator--) { critical_indices_left.insert( sorted_indices.elements[iterator] ); } // nach rechts for(iterator = split_index+1; iterator < sorted_indices.width && V.elements[ sorted_indices.elements[iterator] * V.dim + current_dim] == split_value; iterator++) { critical_indices_right.insert( sorted_indices.elements[iterator] ); } } void LBKdTree::generateKdTreeRecursive(int id, LBPointArray<float>& V, LBPointArray<unsigned int>* sorted_indices, int current_dim, int max_dim, LBPointArray<float> *values, LBPointArray<unsigned char> *splits , int size, int max_tree_depth, int position, int current_depth) { int left = position*2+1; int right = position*2+2; if( sorted_indices[current_dim].width <= 1 ) { values->elements[position] = static_cast<float>(sorted_indices[current_dim].elements[0] ); } else { /// split sorted_indices unsigned int indices_size = sorted_indices[current_dim].width; unsigned int v = pow( 2, static_cast<int>( log2(indices_size-1) ) ); unsigned int left_size = indices_size - v/2; if( left_size > v ) { left_size = v; } unsigned int right_size = indices_size - left_size; unsigned int split_index = static_cast<unsigned int>( sorted_indices[current_dim].elements[left_size-1] + 0.5 ); float split_value = V.elements[split_index * V.dim + current_dim ]; // critical indices // std::list<unsigned int> critical_indices_left; // std::list<unsigned int> critical_indices_right; // fillCriticalIndices(V, sorted_indices[current_dim], current_dim, split_value, left_size-1 // critical_indices_left, critical_indices_right); std::unordered_set<unsigned int> critical_indices_left; std::unordered_set<unsigned int> critical_indices_right; fillCriticalIndicesSet(V, sorted_indices[current_dim], current_dim, split_value, left_size-1, critical_indices_left, critical_indices_right); // for(auto it = critical_indices_left.begin(); it != critical_indices_left.end(); it++) // { // std::cout << *it << std::endl; // } // for(auto it = critical_indices_right.begin(); it != critical_indices_right.end(); it++) // { // std::cout << *it << std::endl; // } // exit(1); //std::cout << "Split in dimension: " << current_dim << std::endl; values->elements[ position ] = split_value; splits->elements[ position ] = static_cast<unsigned char>(current_dim); LBPointArray<unsigned int> *sorted_indices_left = (LBPointArray<unsigned int>*)malloc( 3*sizeof(LBPointArray<unsigned int>) ); LBPointArray<unsigned int> *sorted_indices_right = (LBPointArray<unsigned int>*)malloc( 3*sizeof(LBPointArray<unsigned int>) ); int next_dim_left = -1; int next_dim_right = -1; float biggest_deviation_left = -1.0; float biggest_deviation_right = -1.0; for( int i=0; i<max_dim; i++ ) { sorted_indices_left[i].width = left_size; sorted_indices_left[i].dim = 1; sorted_indices_left[i].elements = (unsigned int*)malloc( left_size * sizeof(unsigned int) ); sorted_indices_right[i].width = right_size; sorted_indices_right[i].dim = 1; sorted_indices_right[i].elements = (unsigned int*)malloc( right_size * sizeof(unsigned int) ); float deviation_left; float deviation_right; if( i == current_dim ){ splitPointArray<unsigned int>( sorted_indices[i], sorted_indices_left[i], sorted_indices_right[i]); deviation_left = fabs(V.elements[sorted_indices_left[i].elements[left_size - 1] * V.dim + i ] - V.elements[sorted_indices_left[i].elements[0] * V.dim + i ] ); deviation_right = fabs( V.elements[ sorted_indices_right[i].elements[right_size - 1] * V.dim + i ] - V.elements[sorted_indices_right[i].elements[0] * V.dim + i] ); } else { // splitPointArrayWithValue<float,unsigned int>(V, sorted_indices[i], // sorted_indices_left[i], sorted_indices_right[i], // current_dim, split_value, // deviation_left, deviation_right, i, // critical_indices_left, critical_indices_right); splitPointArrayWithValueSet<float,unsigned int>(V, sorted_indices[i], sorted_indices_left[i], sorted_indices_right[i], current_dim, split_value, deviation_left, deviation_right, i, critical_indices_left, critical_indices_right); } if(deviation_left > biggest_deviation_left ) { biggest_deviation_left = deviation_left; next_dim_left = i; } if(deviation_right > biggest_deviation_right ) { biggest_deviation_right = deviation_right; next_dim_right = i; } } //int next_dim = (current_dim+1)%max_dim; if(current_depth == st_depth_threads ) { pool->push(generateKdTreeRecursive, V, sorted_indices_left, next_dim_left, max_dim, values, splits, size, max_tree_depth, left, current_depth + 1); pool->push(generateKdTreeRecursive, V, sorted_indices_right, next_dim_right, max_dim, values, splits, size, max_tree_depth, right, current_depth +1); } else { //std::cout<< "left " << current_dim << std::endl; generateKdTreeRecursive(0, V, sorted_indices_left, next_dim_left, max_dim, values, splits, size, max_tree_depth, left, current_depth + 1); //std::cout << "right " << current_dim << std::endl; generateKdTreeRecursive(0, V, sorted_indices_right, next_dim_right, max_dim, values, splits, size, max_tree_depth, right, current_depth +1); } } for(int i=0; i<max_dim; i++) { free(sorted_indices[i].elements ); } free(sorted_indices); } } /* namespace lvr2 */
36.714667
116
0.63742
jtpils
66f43f7ee0c3f1faf571388278cc4aba242e1bf6
6,900
cpp
C++
src/wrapper/mempool.cpp
hesom/pycuda
f2f999f51617fcf3deb77f2104b5051885cae498
[ "Apache-2.0" ]
1,264
2015-01-01T15:38:32.000Z
2022-03-31T22:30:21.000Z
src/wrapper/mempool.cpp
hesom/pycuda
f2f999f51617fcf3deb77f2104b5051885cae498
[ "Apache-2.0" ]
262
2015-01-18T20:52:48.000Z
2022-03-30T15:57:50.000Z
src/wrapper/mempool.cpp
hesom/pycuda
f2f999f51617fcf3deb77f2104b5051885cae498
[ "Apache-2.0" ]
289
2015-01-14T04:30:00.000Z
2022-03-19T19:58:49.000Z
#define NO_IMPORT_ARRAY #define PY_ARRAY_UNIQUE_SYMBOL pycuda_ARRAY_API #include <vector> #include "tools.hpp" #include "wrap_helpers.hpp" #include <cuda.hpp> #include <mempool.hpp> #include <boost/python/stl_iterator.hpp> namespace py = boost::python; namespace { class device_allocator : public pycuda::context_dependent { public: typedef CUdeviceptr pointer_type; typedef size_t size_type; bool is_deferred() const { return false; } device_allocator *copy() const { return new device_allocator(*this); } pointer_type allocate(size_type s) { pycuda::scoped_context_activation ca(get_context()); return pycuda::mem_alloc(s); } void free(pointer_type p) { try { pycuda::scoped_context_activation ca(get_context()); pycuda::mem_free(p); } CUDAPP_CATCH_CLEANUP_ON_DEAD_CONTEXT(pooled_device_allocation); } void try_release_blocks() { pycuda::run_python_gc(); } }; class host_allocator { private: unsigned m_flags; public: typedef void *pointer_type; typedef size_t size_type; bool is_deferred() const { return false; } host_allocator *copy() const { return new host_allocator(*this); } host_allocator(unsigned flags=0) : m_flags(flags) { } pointer_type allocate(size_type s) { return pycuda::mem_host_alloc(s, m_flags); } void free(pointer_type p) { pycuda::mem_host_free(p); } void try_release_blocks() { pycuda::run_python_gc(); } }; template<class Allocator> class context_dependent_memory_pool : public pycuda::memory_pool<Allocator>, public pycuda::explicit_context_dependent { protected: void start_holding_blocks() { acquire_context(); } void stop_holding_blocks() { release_context(); } }; class pooled_device_allocation : public pycuda::context_dependent, public pycuda::pooled_allocation<context_dependent_memory_pool<device_allocator> > { private: typedef pycuda::pooled_allocation<context_dependent_memory_pool<device_allocator> > super; public: pooled_device_allocation( boost::shared_ptr<super::pool_type> p, super::size_type s) : super(p, s) { } operator CUdeviceptr() { return ptr(); } }; pooled_device_allocation *device_pool_allocate( boost::shared_ptr<context_dependent_memory_pool<device_allocator> > pool, context_dependent_memory_pool<device_allocator>::size_type sz) { return new pooled_device_allocation(pool, sz); } PyObject *pooled_device_allocation_to_long(pooled_device_allocation const &da) { #if defined(_WIN32) && defined(_WIN64) return PyLong_FromUnsignedLongLong(da.ptr()); #else return PyLong_FromUnsignedLong(da.ptr()); #endif } class pooled_host_allocation : public pycuda::pooled_allocation<pycuda::memory_pool<host_allocator> > { private: typedef pycuda::pooled_allocation<pycuda::memory_pool<host_allocator> > super; public: pooled_host_allocation( boost::shared_ptr<super::pool_type> p, super::size_type s) : super(p, s) { } }; py::handle<> host_pool_allocate( boost::shared_ptr<pycuda::memory_pool<host_allocator> > pool, py::object shape, py::object dtype, py::object order_py) { PyArray_Descr *tp_descr; if (PyArray_DescrConverter(dtype.ptr(), &tp_descr) != NPY_SUCCEED) throw py::error_already_set(); std::vector<npy_intp> dims; std::copy( py::stl_input_iterator<npy_intp>(shape), py::stl_input_iterator<npy_intp>(), back_inserter(dims)); std::auto_ptr<pooled_host_allocation> alloc( new pooled_host_allocation( pool, tp_descr->elsize*pycuda::size_from_dims(dims.size(), &dims.front()))); NPY_ORDER order = PyArray_CORDER; PyArray_OrderConverter(order_py.ptr(), &order); int flags = 0; if (order == PyArray_FORTRANORDER) flags |= NPY_FARRAY; else if (order == PyArray_CORDER) flags |= NPY_CARRAY; else throw std::runtime_error("unrecognized order specifier"); py::handle<> result = py::handle<>(PyArray_NewFromDescr( &PyArray_Type, tp_descr, int(dims.size()), &dims.front(), /*strides*/ NULL, alloc->ptr(), flags, /*obj*/NULL)); py::handle<> alloc_py(handle_from_new_ptr(alloc.release())); PyArray_BASE(result.get()) = alloc_py.get(); Py_INCREF(alloc_py.get()); return result; } template<class Wrapper> void expose_memory_pool(Wrapper &wrapper) { typedef typename Wrapper::wrapped_type cl; wrapper .add_property("held_blocks", &cl::held_blocks) .add_property("active_blocks", &cl::active_blocks) .add_property("managed_bytes", &cl::managed_bytes) .add_property("active_bytes", &cl::active_bytes) .DEF_SIMPLE_METHOD(bin_number) .DEF_SIMPLE_METHOD(alloc_size) .DEF_SIMPLE_METHOD(free_held) .DEF_SIMPLE_METHOD(stop_holding) ; } } void pycuda_expose_tools() { py::def("bitlog2", pycuda::bitlog2); { typedef context_dependent_memory_pool<device_allocator> cl; py::class_< cl, boost::noncopyable, boost::shared_ptr<cl> > wrapper("DeviceMemoryPool"); wrapper .def("allocate", device_pool_allocate, py::return_value_policy<py::manage_new_object>()) ; expose_memory_pool(wrapper); } { typedef host_allocator cl; py::class_<cl> wrapper("PageLockedAllocator", py::init<py::optional<unsigned> >()); } { typedef pycuda::memory_pool<host_allocator> cl; py::class_< cl, boost::noncopyable, boost::shared_ptr<cl> > wrapper( "PageLockedMemoryPool", py::init<py::optional<host_allocator const &> >() ); wrapper .def("allocate", host_pool_allocate, (py::arg("shape"), py::arg("dtype"), py::arg("order")="C")); ; expose_memory_pool(wrapper); } { typedef pooled_device_allocation cl; py::class_<cl, boost::noncopyable>( "PooledDeviceAllocation", py::no_init) .DEF_SIMPLE_METHOD(free) .def("__int__", &cl::ptr) .def("__long__", pooled_device_allocation_to_long) .def("__index__", pooled_device_allocation_to_long) .def("__len__", &cl::size) ; py::implicitly_convertible<pooled_device_allocation, CUdeviceptr>(); } { typedef pooled_host_allocation cl; py::class_<cl, boost::noncopyable>( "PooledHostAllocation", py::no_init) .DEF_SIMPLE_METHOD(free) .def("__len__", &cl::size) ; } }
22.402597
86
0.643478
hesom
66f490926f02c857f8018b7b683655bcf2226eb6
5,042
cc
C++
chrome/browser/performance_monitor/startup_timer.cc
junmin-zhu/chromium-rivertrail
eb1a57aca71fe68d96e48af8998dcfbe45171ee1
[ "BSD-3-Clause" ]
5
2018-03-10T13:08:42.000Z
2021-07-26T15:02:11.000Z
chrome/browser/performance_monitor/startup_timer.cc
sanyaade-mobiledev/chromium.src
d496dfeebb0f282468827654c2b3769b3378c087
[ "BSD-3-Clause" ]
1
2015-07-21T08:02:01.000Z
2015-07-21T08:02:01.000Z
chrome/browser/performance_monitor/startup_timer.cc
jianglong0156/chromium.src
d496dfeebb0f282468827654c2b3769b3378c087
[ "BSD-3-Clause" ]
6
2016-11-14T10:13:35.000Z
2021-01-23T15:29:53.000Z
// 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. #include "chrome/browser/performance_monitor/startup_timer.h" #include "base/bind.h" #include "base/logging.h" #include "base/string_number_conversions.h" #include "chrome/browser/performance_monitor/database.h" #include "chrome/browser/performance_monitor/performance_monitor.h" #include "chrome/common/chrome_notification_types.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/notification_details.h" #include "content/public/browser/notification_service.h" #include "content/public/browser/notification_source.h" #include "content/public/browser/notification_types.h" namespace performance_monitor { namespace { // Needed because Database::AddMetric is overloaded, so base::Bind doesn't work. void AddMetricToDatabaseOnBackgroundThread(Database* database, const Metric& metric) { database->AddMetric(metric); } } // namespace // static StartupTimer* StartupTimer::g_startup_timer_ = NULL; StartupTimer::StartupTimer() : startup_begin_(base::TimeTicks::Now()), startup_type_(STARTUP_NORMAL), performance_monitor_initialized_(false) { CHECK(!g_startup_timer_); g_startup_timer_ = this; // We need this check because, under certain rare circumstances, // NotificationService::current() will return null, and this will cause a // segfault in NotificationServiceImpl::AddObserver(). Currently, this only // happens as a result of the child process launched by BrowserMainTest. // WarmConnectionFieldTrial_Invalid. if (content::NotificationService::current()) { registrar_.Add(this, chrome::NOTIFICATION_PERFORMANCE_MONITOR_INITIALIZED, content::NotificationService::AllSources()); } } StartupTimer::~StartupTimer() { DCHECK(this == g_startup_timer_); g_startup_timer_ = NULL; } bool StartupTimer::SignalStartupComplete(StartupType startup_type) { DCHECK(elapsed_startup_time_ == base::TimeDelta()); startup_type_ = startup_type; elapsed_startup_time_ = base::TimeTicks::Now() - total_pause_ - startup_begin_; if (performance_monitor_initialized_) InsertElapsedStartupTime(); return true; } // static void StartupTimer::PauseTimer() { // Check that the timer is not already paused. DCHECK(g_startup_timer_->pause_started_ == base::TimeTicks()); g_startup_timer_->pause_started_ = base::TimeTicks::Now(); } // static void StartupTimer::UnpauseTimer() { // Check that the timer has been paused. DCHECK(g_startup_timer_->pause_started_ != base::TimeTicks()); g_startup_timer_->total_pause_ += base::TimeTicks::Now() - g_startup_timer_->pause_started_; g_startup_timer_->pause_started_ = base::TimeTicks(); } void StartupTimer::Observe(int type, const content::NotificationSource& source, const content::NotificationDetails& details) { CHECK(type == chrome::NOTIFICATION_PERFORMANCE_MONITOR_INITIALIZED); performance_monitor_initialized_ = true; if (elapsed_startup_time_ != base::TimeDelta()) InsertElapsedStartupTime(); if (elapsed_session_restore_times_.size()) InsertElapsedSessionRestoreTime(); } // static void StartupTimer::SetElapsedSessionRestoreTime( const base::TimeDelta& elapsed_session_restore_time) { g_startup_timer_->elapsed_session_restore_times_.push_back( elapsed_session_restore_time); if (g_startup_timer_->performance_monitor_initialized_) g_startup_timer_->InsertElapsedSessionRestoreTime(); } void StartupTimer::InsertElapsedStartupTime() { content::BrowserThread::PostBlockingPoolSequencedTask( Database::kDatabaseSequenceToken, FROM_HERE, base::Bind( &AddMetricToDatabaseOnBackgroundThread, base::Unretained(PerformanceMonitor::GetInstance()->database()), Metric(startup_type_ == STARTUP_NORMAL ? METRIC_STARTUP_TIME : METRIC_TEST_STARTUP_TIME, base::Time::Now(), static_cast<double>( elapsed_startup_time_.ToInternalValue())))); } void StartupTimer::InsertElapsedSessionRestoreTime() { for (std::vector<base::TimeDelta>::const_iterator iter = elapsed_session_restore_times_.begin(); iter != elapsed_session_restore_times_.end(); ++iter) { content::BrowserThread::PostBlockingPoolSequencedTask( Database::kDatabaseSequenceToken, FROM_HERE, base::Bind( &AddMetricToDatabaseOnBackgroundThread, base::Unretained(PerformanceMonitor::GetInstance()->database()), Metric(METRIC_SESSION_RESTORE_TIME, base::Time::Now(), static_cast<double>(iter->ToInternalValue())))); } } } // namespace performance_monitor
36.014286
80
0.711424
junmin-zhu
66f5b2c623ee7880fa709b0ca8bee1dd351cc54f
137,676
cpp
C++
src/ngraph/runtime/cpu/pass/cpu_mkldnn_primitive_build.cpp
ilya-lavrenov/ngraph
2d8b2b4b30dbcabda0c3de2ae458418e63da057a
[ "Apache-2.0" ]
null
null
null
src/ngraph/runtime/cpu/pass/cpu_mkldnn_primitive_build.cpp
ilya-lavrenov/ngraph
2d8b2b4b30dbcabda0c3de2ae458418e63da057a
[ "Apache-2.0" ]
null
null
null
src/ngraph/runtime/cpu/pass/cpu_mkldnn_primitive_build.cpp
ilya-lavrenov/ngraph
2d8b2b4b30dbcabda0c3de2ae458418e63da057a
[ "Apache-2.0" ]
null
null
null
//***************************************************************************** // Copyright 2017-2019 Intel Corporation // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //***************************************************************************** #include <string> #include "cpu_mkldnn_primitive_build.hpp" #include "ngraph/code_writer.hpp" #include "ngraph/op/add.hpp" #include "ngraph/op/avg_pool.hpp" #include "ngraph/op/batch_norm.hpp" #include "ngraph/op/concat.hpp" #include "ngraph/op/constant.hpp" #include "ngraph/op/convert.hpp" #include "ngraph/op/convolution.hpp" #include "ngraph/op/dequantize.hpp" #include "ngraph/op/experimental/quantized_conv_bias.hpp" #include "ngraph/op/experimental/quantized_conv_relu.hpp" #include "ngraph/op/experimental/quantized_dot_bias.hpp" #include "ngraph/op/get_output_element.hpp" #include "ngraph/op/lrn.hpp" #include "ngraph/op/max_pool.hpp" #include "ngraph/op/quantize.hpp" #include "ngraph/op/quantized_convolution.hpp" #include "ngraph/op/quantized_dot.hpp" #include "ngraph/op/relu.hpp" #include "ngraph/op/replace_slice.hpp" #include "ngraph/op/reshape.hpp" #include "ngraph/op/sigmoid.hpp" #include "ngraph/op/slice.hpp" #include "ngraph/op/softmax.hpp" #include "ngraph/runtime/cpu/cpu_executor.hpp" #include "ngraph/runtime/cpu/cpu_tensor_view_wrapper.hpp" #include "ngraph/runtime/cpu/mkldnn_emitter.hpp" #include "ngraph/runtime/cpu/mkldnn_utils.hpp" #include "ngraph/runtime/cpu/op/convert_layout.hpp" #include "ngraph/runtime/cpu/op/lstm.hpp" #include "ngraph/runtime/cpu/op/max_pool_with_indices.hpp" #include "ngraph/runtime/cpu/op/rnn.hpp" #include "ngraph/runtime/cpu/op/update_slice.hpp" #define WRITE_MKLDNN_DIMS(X) writer << "mkldnn::memory::dims{" << join(X) << "}, \n"; using namespace ngraph; using namespace ngraph::op; using namespace ngraph::runtime::cpu; namespace ngraph { namespace runtime { namespace cpu { namespace pass { // serialize memory descriptors static void serialize_memory_descs(std::ofstream& desc_file, std::vector<mkldnn::memory::desc>& descs, size_t index) { for (auto i = 0; i < descs.size(); i++) { desc_file << index; desc_file.write(reinterpret_cast<char*>(&descs[i]), sizeof(mkldnn::memory::desc)); index++; } } // The following functions build the MKLDNN primitive for each type of nGraph Node. template <> void MKLDNNPrimitiveBuildPass::CONSTRUCT_PRIMITIVE_BUILD_STRING_DECL(Add) { auto input0_data_desc = mkldnn_utils::get_input_mkldnn_md(node, 0); auto input1_data_desc = mkldnn_utils::get_input_mkldnn_md(node, 1); auto result_desc = mkldnn_utils::get_output_mkldnn_md(node, 0); // query scratchpad size auto sum_pd = mkldnn_emitter.get_elementwise_add_desc(node); mkldnn_emitter.query_scratchpad_sum(sum_pd); // Add needs 4 primitives: input0, input1, result, and sum. index = mkldnn_emitter.reserve_primitive_space(4); deps = mkldnn_emitter.get_primitive_deps(index); CodeWriter writer; // Write memory descriptors to file std::vector<mkldnn::memory::desc> descs = { input0_data_desc, input1_data_desc, result_desc}; auto desc_index = mkldnn_emitter.get_mkldnn_descriptors_size(); mkldnn_emitter.reserve_descriptor_space(descs.size()); serialize_memory_descs(desc_file, descs, deps[0]); writer << "std::vector<float> scale_vector(2, 1);\n"; writer << "std::vector<mkldnn::memory::desc> inputs_desc{" "*cg_ctx->mkldnn_descriptors[" << desc_index << "], " << "*cg_ctx->mkldnn_descriptors[" << desc_index + 1 << "]};\n"; writer << "mkldnn::primitive_attr attr;\n"; writer << "attr.set_scratchpad_mode(mkldnn::scratchpad_mode::user);\n"; // elementwise sum primitive descriptor writer << "mkldnn::sum::primitive_desc sum_pd = " "mkldnn::sum::primitive_desc(*cg_ctx->mkldnn_descriptors[" << desc_index + 2 << "], " "scale_vector, inputs_desc, cg_ctx->global_cpu_engine, attr);\n"; writer << "\n// build sum primitive\n"; // sum primitive writer << "cg_ctx->mkldnn_primitives[" << std::to_string(index) << "] = new mkldnn::sum(sum_pd);\n"; writer << "cg_ctx->mkldnn_scratchpad_mds[" << std::to_string(index) << "] = new mkldnn::memory::desc(sum_pd.scratchpad_desc());\n"; construct_string = writer.get_code(); } template <typename OP> void construct_primitive_build_string_rnn( ngraph::runtime::cpu::MKLDNNEmitter& mkldnn_emitter, ngraph::Node* node, std::string& construct_string, std::vector<size_t>& deps, size_t& index, std::ofstream& desc_file) { const auto& out = node->get_outputs(); const auto& args = node->get_inputs(); auto rnn_node = static_cast<const OP*>(node); auto src_sequence_length_max = static_cast<unsigned long>(rnn_node->get_src_sequence_length()); auto direction = static_cast<unsigned long>(rnn_node->get_direction()); auto num_fused_layers = static_cast<unsigned long>(rnn_node->get_num_fused_layers()); auto feature_size = static_cast<unsigned long>(rnn_node->get_src_iter_feature_size()); auto batch = static_cast<unsigned long>(rnn_node->get_batch_size()); auto rnn_cell_n_gates = static_cast<unsigned long>(rnn_node->get_gates_per_cell()); auto get_mkldnn_rnn_direction_string = [&]() { switch (direction) { case 1: return std::string("mkldnn::rnn_direction::unidirectional_left2right"); case 2: return std::string("mkldnn::rnn_direction::bidirectional_concat"); default: throw ngraph_error("unsupported mkldnn rnn direction"); } }; auto get_mkldnn_rnn_direction = [&]() { switch (direction) { case 1: return mkldnn::rnn_direction::unidirectional_left2right; case 2: return mkldnn::rnn_direction::bidirectional_concat; default: throw ngraph_error("unsupported mkldnn rnn direction"); } }; if (out[0].get_shape().size() == 2 && (out[0].get_shape()[1] != direction * feature_size)) { throw ngraph_error( "input slc{ht} feature size is not equal to output dlc{ht} feature " "size "); } if (out[1].get_shape().size() == 2 && (out[1].get_shape()[1] != feature_size) && rnn_node->get_num_timesteps() != 1) { throw ngraph_error( "input sic{ht_1|ct_1} feature size is not equal to output " "dlc{ht_1|ct_1} " "feature size "); } Shape src_layer_tz{ src_sequence_length_max, batch, static_cast<unsigned long>(rnn_node->get_src_layer_feature_size())}; Shape src_iter_tz{num_fused_layers, direction, batch, feature_size}; Shape src_iter_c_tz{num_fused_layers, direction, batch, feature_size}; Shape wei_layer_tz{ num_fused_layers, direction, static_cast<unsigned long>(rnn_node->get_src_layer_feature_size()), rnn_cell_n_gates, feature_size}; Shape wei_iter_tz{ num_fused_layers, direction, feature_size, rnn_cell_n_gates, feature_size}; Shape bias_tz{num_fused_layers, direction, rnn_cell_n_gates, feature_size}; Shape dst_layer_tz{src_sequence_length_max, batch, direction * feature_size}; Shape dst_iter_tz{num_fused_layers, direction, batch, feature_size}; Shape dst_iter_c_tz{num_fused_layers, direction, batch, feature_size}; // We create the memory descriptors used by the user auto src_layer_md = mkldnn_emitter.build_memory_descriptor( src_layer_tz, args[0].get_element_type(), mkldnn::memory::format_tag::tnc); auto src_iter_md = mkldnn_emitter.build_memory_descriptor( src_iter_tz, args[1].get_element_type(), mkldnn::memory::format_tag::ldnc); auto src_iter_c_md = mkldnn_emitter.build_memory_descriptor(src_iter_c_tz, args[1].get_element_type(), mkldnn::memory::format_tag::ldnc); auto wei_layer_md = mkldnn_emitter.build_memory_descriptor(wei_layer_tz, args[2].get_element_type(), mkldnn::memory::format_tag::ldigo); auto wei_iter_md = mkldnn_emitter.build_memory_descriptor( wei_iter_tz, args[3].get_element_type(), mkldnn::memory::format_tag::ldigo); auto bias_md = mkldnn_emitter.build_memory_descriptor( bias_tz, args[4].get_element_type(), mkldnn::memory::format_tag::ldgo); auto dst_layer_md = mkldnn_emitter.build_memory_descriptor( dst_layer_tz, out[0].get_element_type(), mkldnn::memory::format_tag::tnc); auto dst_iter_md = mkldnn_emitter.build_memory_descriptor( dst_iter_tz, out[1].get_element_type(), mkldnn::memory::format_tag::ldnc); auto dst_iter_c_md = mkldnn_emitter.build_memory_descriptor( dst_iter_c_tz, out[1].get_element_type(), mkldnn::memory::format_tag::ldnc); // query scratchpad size auto rnn_desc = mkldnn::lstm_forward::desc(mkldnn::prop_kind::forward_training, get_mkldnn_rnn_direction(), src_layer_md, src_iter_md, src_iter_c_md, wei_layer_md, wei_iter_md, bias_md, dst_layer_md, dst_iter_md, dst_iter_c_md); mkldnn_emitter.query_scratchpad_rnn_forward(rnn_desc); // Lstm/Rnn needs 11 primitives: src_layer, src_iter, src_iter_c, weights_layer, // weights_iter, bias, // dst_layer, dst_iter, dst_iter_c, workspace, and rnn_forward. // It needs a new workspace. index = mkldnn_emitter.reserve_primitive_space(11, true /* new workspace */); deps = mkldnn_emitter.get_primitive_deps(index); CodeWriter writer; // Write memory descriptors to file std::vector<mkldnn::memory::desc> descs = {src_layer_md, src_iter_md, src_iter_c_md, wei_layer_md, wei_iter_md, bias_md, dst_layer_md, dst_iter_md, dst_iter_c_md}; auto desc_index = mkldnn_emitter.get_mkldnn_descriptors_size(); mkldnn_emitter.reserve_descriptor_space(descs.size()); serialize_memory_descs(desc_file, descs, deps[0]); writer << "\n// build lstm/rnn primitive descriptor\n"; writer << "auto rnn_desc = " "mkldnn::lstm_forward::desc(mkldnn::prop_kind::forward_training, " << get_mkldnn_rnn_direction_string() << ", " "*cg_ctx->mkldnn_descriptors[" << desc_index << "], " "*cg_ctx->mkldnn_descriptors[" << desc_index + 1 << "], " "*cg_ctx->mkldnn_descriptors[" << desc_index + 2 << "], " "*cg_ctx->mkldnn_descriptors[" << desc_index + 3 << "], " "*cg_ctx->mkldnn_descriptors[" << desc_index + 4 << "], " "*cg_ctx->mkldnn_descriptors[" << desc_index + 5 << "], " "*cg_ctx->mkldnn_descriptors[" << desc_index + 6 << "], " "*cg_ctx->mkldnn_descriptors[" << desc_index + 7 << "], " "*cg_ctx->mkldnn_descriptors[" << desc_index + 8 << "]);\n"; writer << "mkldnn::primitive_attr attr;\n"; writer << "attr.set_scratchpad_mode(mkldnn::scratchpad_mode::user);\n"; writer << "auto rnn_prim_desc = mkldnn::lstm_forward::primitive_desc(rnn_desc, " "attr, " "cg_ctx->global_cpu_engine);\n"; writer << "cg_ctx->mkldnn_memories[" << std::to_string(deps[9]) << "] = new " "mkldnn::memory(rnn_prim_desc.workspace_desc(), " "cg_ctx->global_cpu_engine, nullptr);\n"; writer << "auto workspace = " "(char*)malloc(rnn_prim_desc.workspace_desc().get_size());" "\n"; writer << "if (!workspace)\n"; writer.block_begin(); writer << "throw std::bad_alloc();\n"; writer.block_end(); writer << "cg_ctx->mkldnn_workspaces.push_back(workspace);\n"; deps[10] = mkldnn_emitter.reserve_workspace(); writer << "\n// build lstm/rnn primitive\n"; // lstm/rnn primitive writer << "cg_ctx->mkldnn_primitives[" << std::to_string(index) << "] = new mkldnn::lstm_forward(rnn_prim_desc);\n"; writer << "cg_ctx->mkldnn_scratchpad_mds[" << std::to_string(index) << "] = new mkldnn::memory::desc(rnn_prim_desc.scratchpad_desc());\n"; construct_string = writer.get_code(); } template <> void MKLDNNPrimitiveBuildPass::CONSTRUCT_PRIMITIVE_BUILD_STRING_DECL(Lstm) { construct_primitive_build_string_rnn<Lstm>( mkldnn_emitter, node, construct_string, deps, index, desc_file); } template <> void MKLDNNPrimitiveBuildPass::CONSTRUCT_PRIMITIVE_BUILD_STRING_DECL(Rnn) { construct_primitive_build_string_rnn<Rnn>( mkldnn_emitter, node, construct_string, deps, index, desc_file); } template <typename OP> void construct_primitive_build_string_batchnorm( ngraph::runtime::cpu::MKLDNNEmitter& mkldnn_emitter, ngraph::Node* node, std::string& construct_string, std::vector<size_t>& deps, size_t& index, std::ofstream& desc_file, const bool append_relu, const bool training) { const auto& args = node->get_inputs(); // batchnorm forward needs 6 primitives: input, weights, result, mean, // variance, and batch_normalization_forward. index = mkldnn_emitter.reserve_primitive_space(6); deps = mkldnn_emitter.get_primitive_deps(index); CodeWriter writer; if (append_relu) { writer << "mkldnn::post_ops pops;\n"; writer << "const float ops_scale = 1.f;\n"; writer << "const float ops_alpha = -0.f; // relu negative slope\n"; writer << "const float ops_beta = 0.f;\n"; writer << "pops.append_eltwise(" "ops_scale, mkldnn::algorithm::eltwise_relu, ops_alpha, " "ops_beta);\n"; } else { writer << "mkldnn::post_ops pops = mkldnn::post_ops();\n"; } auto weights_shape = Shape{2, args[0].get_tensor().get_tensor_layout()->get_size()}; auto input_desc = mkldnn_utils::get_input_mkldnn_md(node, 2); auto weights_desc = mkldnn_emitter.build_memory_descriptor( weights_shape, args[0].get_element_type(), mkldnn::memory::format_tag::nc); auto result_desc = mkldnn_utils::get_output_mkldnn_md(node, 0); const float ops_scale = 1.f; const float ops_alpha = -0.f; // relu negative slope const float ops_beta = 0.f; mkldnn::post_ops ops; if (append_relu) { ops.append_eltwise( ops_scale, mkldnn::algorithm::eltwise_relu, ops_alpha, ops_beta); } bool use_global_stats; const mkldnn::memory::desc *mean_desc, *variance_desc; if (training && args.size() == 3) { mean_desc = &mkldnn_utils::get_output_mkldnn_md(node, 1); variance_desc = &mkldnn_utils::get_output_mkldnn_md(node, 2); use_global_stats = false; // query scratchpad size auto batchnorm_desc = mkldnn_emitter.get_batchnorm_forward_desc<OP>(node, true); mkldnn_emitter.query_scratchpad_batchnorm_forward(batchnorm_desc, ops); } else { mean_desc = &mkldnn_utils::get_input_mkldnn_md(node, 3); variance_desc = &mkldnn_utils::get_input_mkldnn_md(node, 4); use_global_stats = true; // query scratchpad size auto batchnorm_desc = mkldnn_emitter.get_batchnorm_forward_desc<OP>(node, false); mkldnn_emitter.query_scratchpad_batchnorm_forward(batchnorm_desc, ops); } auto batchnorm = static_cast<const OP*>(node); auto eps = batchnorm->get_eps_value(); writer << "mkldnn::primitive_attr bn_attr;\n"; writer << "bn_attr.set_post_ops(pops);\n"; writer << "bn_attr.set_scratchpad_mode(mkldnn::scratchpad_mode::user);\n"; writer << "\n// build batchnorm primitive descriptor\n"; if (use_global_stats) { // Write memory descriptors to file std::vector<mkldnn::memory::desc> descs = { input_desc, *mean_desc, *variance_desc, weights_desc, result_desc}; auto desc_index = mkldnn_emitter.get_mkldnn_descriptors_size(); mkldnn_emitter.reserve_descriptor_space(descs.size()); serialize_memory_descs(desc_file, descs, deps[0]); writer << "auto batchnorm_desc = " "mkldnn::batch_normalization_forward::desc(mkldnn::prop_kind::" "forward_training, " "*cg_ctx->mkldnn_descriptors[" << desc_index << "], " << eps << ", " "mkldnn::normalization_flags::use_scale_shift | " "mkldnn::normalization_flags::use_global_stats);\n"; } else { // Write memory descriptors to file std::vector<mkldnn::memory::desc> descs = { input_desc, weights_desc, result_desc, *mean_desc, *variance_desc}; auto desc_index = mkldnn_emitter.get_mkldnn_descriptors_size(); mkldnn_emitter.reserve_descriptor_space(descs.size()); serialize_memory_descs(desc_file, descs, deps[0]); writer << "auto batchnorm_desc = " "mkldnn::batch_normalization_forward::desc(mkldnn::prop_kind::" "forward_training, " "*cg_ctx->mkldnn_descriptors[" << desc_index << "], " << eps << ", " "mkldnn::normalization_flags::use_scale_shift);\n"; } writer << "auto batchnorm_prim_desc = " "mkldnn::batch_normalization_forward::primitive_desc(batchnorm_" "desc, " "bn_attr, cg_ctx->global_cpu_engine);\n"; writer << "\n// build batchnorm primitive\n"; // batchnorm primitive writer << "cg_ctx->mkldnn_primitives[" << std::to_string(index) << "] = new " "mkldnn::batch_normalization_forward(batchnorm_prim_desc);\n"; writer << "cg_ctx->mkldnn_scratchpad_mds[" << std::to_string(index) << "] = new mkldnn::memory::desc(batchnorm_prim_desc.scratchpad_desc());\n"; construct_string = writer.get_code(); } template <> void MKLDNNPrimitiveBuildPass::CONSTRUCT_PRIMITIVE_BUILD_STRING_DECL( BatchNormTraining) { construct_primitive_build_string_batchnorm<BatchNormTraining>( mkldnn_emitter, node, construct_string, deps, index, desc_file, false /*Append relu*/, true /*Training*/); } template <> void MKLDNNPrimitiveBuildPass::CONSTRUCT_PRIMITIVE_BUILD_STRING_DECL( BatchNormInference) { construct_primitive_build_string_batchnorm<BatchNormInference>( mkldnn_emitter, node, construct_string, deps, index, desc_file, false /*Append relu*/, false /*Training*/); } template <> void MKLDNNPrimitiveBuildPass::CONSTRUCT_PRIMITIVE_BUILD_STRING_DECL( BatchNormTrainingRelu) { construct_primitive_build_string_batchnorm<BatchNormTrainingRelu>( mkldnn_emitter, node, construct_string, deps, index, desc_file, true /*Append relu*/, true /*Training*/); } template <> void MKLDNNPrimitiveBuildPass::CONSTRUCT_PRIMITIVE_BUILD_STRING_DECL( BatchNormInferenceRelu) { construct_primitive_build_string_batchnorm<BatchNormInferenceRelu>( mkldnn_emitter, node, construct_string, deps, index, desc_file, true /*Append relu*/, false /*Training*/); } template <> void MKLDNNPrimitiveBuildPass::CONSTRUCT_PRIMITIVE_BUILD_STRING_DECL( BatchNormTrainingBackprop) { const auto& args = node->get_inputs(); const auto* batchnorm = static_cast<const BatchNormTrainingBackprop*>(node); auto eps = batchnorm->get_eps_value(); auto weights_shape = Shape{2, args[0].get_tensor().get_tensor_layout()->get_size()}; auto weights_desc = mkldnn_emitter.build_memory_descriptor( weights_shape, args[0].get_element_type(), mkldnn::memory::format_tag::nc); auto input_desc = mkldnn_utils::get_input_mkldnn_md(node, 2); auto mean_desc = mkldnn_utils::get_input_mkldnn_md(node, 3); auto variance_desc = mkldnn_utils::get_input_mkldnn_md(node, 4); auto delta_desc = mkldnn_utils::get_input_mkldnn_md(node, 5); auto dinput_desc = mkldnn_utils::get_output_mkldnn_md(node, 0); auto dweights_desc = mkldnn_emitter.build_memory_descriptor( weights_shape, args[0].get_element_type(), mkldnn::memory::format_tag::nc); // query scratchpad size auto batchnorm_desc = mkldnn_emitter.get_batchnorm_backward_desc(node); mkldnn_emitter.query_scratchpad_batchnorm_backward( batchnorm_desc, input_desc, eps); // batchnorm backward needs 8 primitives: weights, input, mean, variance, // dinput, dweights, and batch_normalization_backward. index = mkldnn_emitter.reserve_primitive_space(8); deps = mkldnn_emitter.get_primitive_deps(index); CodeWriter writer; // Write memory descriptors to file std::vector<mkldnn::memory::desc> descs = {weights_desc, input_desc, mean_desc, variance_desc, delta_desc, dinput_desc, dweights_desc}; auto desc_index = mkldnn_emitter.get_mkldnn_descriptors_size(); mkldnn_emitter.reserve_descriptor_space(descs.size()); serialize_memory_descs(desc_file, descs, deps[0]); writer << "auto batchnorm_fdesc = " "mkldnn::batch_normalization_forward::desc(mkldnn::prop_kind::" "forward_training, " "*cg_ctx->mkldnn_descriptors[" << desc_index + 1 << "], " << eps << ", " "mkldnn::normalization_flags::use_scale_shift);\n"; writer << "auto batchnorm_fpd = " "mkldnn::batch_normalization_forward::primitive_desc(" "batchnorm_fdesc, cg_ctx->global_cpu_engine);\n"; writer << "mkldnn::primitive_attr attr;\n"; writer << "attr.set_scratchpad_mode(mkldnn::scratchpad_mode::user);\n"; writer << "auto batchnorm_desc = " "mkldnn::batch_normalization_backward::desc(mkldnn::prop_kind::" "backward, " "*cg_ctx->mkldnn_descriptors[" << desc_index + 4 << "], " "*cg_ctx->mkldnn_descriptors[" << desc_index + 1 << "], " << eps << ", " "mkldnn::normalization_flags::use_scale_shift);\n"; writer << "auto batchnorm_prim_desc = " "mkldnn::batch_normalization_backward::primitive_desc(batchnorm_" "desc, " "attr, cg_ctx->global_cpu_engine, batchnorm_fpd);\n"; writer << "\n// build batchnorm primitive\n"; // batchnorm primitive writer << "\n// build batchnorm primitives\n"; writer << "cg_ctx->mkldnn_primitives[" << std::to_string(index) << "] = new " "mkldnn::batch_normalization_backward(batchnorm_prim_desc);\n"; writer << "cg_ctx->mkldnn_scratchpad_mds[" << std::to_string(index) << "] = new mkldnn::memory::desc(batchnorm_prim_desc.scratchpad_desc());\n"; construct_string = writer.get_code(); } template <typename OP> void construct_primitive_build_string_concat( ngraph::runtime::cpu::MKLDNNEmitter& mkldnn_emitter, ngraph::Node* node, std::string& construct_string, std::vector<size_t>& deps, size_t& index, std::ofstream& desc_file) { auto concat = static_cast<OP*>(node); size_t concat_dim = concat->get_concatenation_axis(); size_t nargs = node->get_inputs().size(); // query scratchpad size auto concat_pd = mkldnn_emitter.get_concat_desc<OP>(node, nargs); mkldnn_emitter.query_scratchpad_concat(concat_pd); // Concat needs number of inputs plus 2 primitives; those two are for result and // concat. index = mkldnn_emitter.reserve_primitive_space(nargs + 2); deps = mkldnn_emitter.get_primitive_deps(index); CodeWriter writer; // Write memory descriptors to file std::vector<mkldnn::memory::desc> descs; for (size_t i = 0; i < nargs; i++) { descs.push_back(mkldnn_utils::get_input_mkldnn_md(node, i)); } auto result_desc = mkldnn_utils::get_output_mkldnn_md(node, 0); descs.push_back(result_desc); auto desc_index = mkldnn_emitter.get_mkldnn_descriptors_size(); mkldnn_emitter.reserve_descriptor_space(descs.size()); serialize_memory_descs(desc_file, descs, deps[0]); writer << "std::vector<mkldnn::memory::desc> inputs_desc;\n"; writer << "for (size_t i = " << desc_index << "; i < " << desc_index + nargs << "; i++)\n"; writer.block_begin(); writer << "inputs_desc.push_back(*cg_ctx->mkldnn_descriptors[i]);\n"; writer.block_end(); writer << "mkldnn::primitive_attr attr;\n"; writer << "attr.set_scratchpad_mode(mkldnn::scratchpad_mode::user);\n"; writer << "auto concat_prim_desc = " "mkldnn::concat::primitive_desc( " "*cg_ctx->mkldnn_descriptors[" << desc_index + nargs << "], " << std::to_string(static_cast<int>(concat_dim)) << ", inputs_desc, cg_ctx->global_cpu_engine, attr);\n"; writer << "\n// build concat primitive\n"; writer << "cg_ctx->mkldnn_primitives[" << std::to_string(index) << "] = new mkldnn::concat(concat_prim_desc);\n"; writer << "cg_ctx->mkldnn_scratchpad_mds[" << std::to_string(index) << "] = new mkldnn::memory::desc(concat_prim_desc.scratchpad_desc());\n"; construct_string = writer.get_code(); } template <> void MKLDNNPrimitiveBuildPass::CONSTRUCT_PRIMITIVE_BUILD_STRING_DECL(Concat) { construct_primitive_build_string_concat<Concat>( mkldnn_emitter, node, construct_string, deps, index, desc_file); } template <> void MKLDNNPrimitiveBuildPass::CONSTRUCT_PRIMITIVE_BUILD_STRING_DECL(LRN) { auto input_desc = mkldnn_utils::get_input_mkldnn_md(node, 0); auto result_desc = mkldnn_utils::get_output_mkldnn_md(node, 0); // query scratchpad size auto lrn_desc = mkldnn_emitter.get_lrn_forward_desc(node); mkldnn_emitter.query_scratchpad_lrn_forward(lrn_desc); // LRN needs 3 primitives: input, result, and lrn_forward. index = mkldnn_emitter.reserve_primitive_space(3); deps = mkldnn_emitter.get_primitive_deps(index); CodeWriter writer; // Write memory descriptors to file std::vector<mkldnn::memory::desc> descs = {input_desc, result_desc}; auto desc_index = mkldnn_emitter.get_mkldnn_descriptors_size(); mkldnn_emitter.reserve_descriptor_space(descs.size()); serialize_memory_descs(desc_file, descs, deps[0]); const auto* lrn = static_cast<const LRN*>(node); auto alpha = static_cast<float>(lrn->get_alpha()); auto beta = static_cast<float>(lrn->get_beta()); auto bias = static_cast<float>(lrn->get_bias()); auto nsize = static_cast<int>(lrn->get_nsize()); writer << "auto lrn_desc = " "mkldnn::lrn_forward::desc(mkldnn::prop_kind::forward_scoring, " "mkldnn::algorithm::lrn_across_channels, " "*cg_ctx->mkldnn_descriptors[" << desc_index << "], " << nsize << ", " << alpha << ", " << beta << ", " << bias << ");\n"; writer << "mkldnn::primitive_attr attr;\n"; writer << "attr.set_scratchpad_mode(mkldnn::scratchpad_mode::user);\n"; writer << "auto lrn_prim_desc = " "mkldnn::lrn_forward::primitive_desc(lrn_desc, " "cg_ctx->global_cpu_engine);\n"; writer << "\n// build lrn primitive\n"; writer << "cg_ctx->mkldnn_primitives[" << std::to_string(index) << "] = new mkldnn::lrn_forward(lrn_prim_desc);\n"; writer << "cg_ctx->mkldnn_scratchpad_mds[" << std::to_string(index) << "] = new mkldnn::memory::desc(lrn_prim_desc.scratchpad_desc());\n"; construct_string = writer.get_code(); } template <> void MKLDNNPrimitiveBuildPass::CONSTRUCT_PRIMITIVE_BUILD_STRING_DECL(Slice) { const auto& out = node->get_outputs(); const Slice* slice = static_cast<const Slice*>(node); auto result_shape = out[0].get_shape(); auto lower_bounds = slice->get_lower_bounds(); auto input_desc = mkldnn_utils::get_input_mkldnn_md(node, 0); auto result_desc = mkldnn_utils::get_output_mkldnn_md(node, 0); // sub memory desc auto dims = mkldnn::memory::dims(result_shape.begin(), result_shape.end()); auto offsets = mkldnn::memory::dims(lower_bounds.begin(), lower_bounds.end()); auto input_sub_desc = input_desc.submemory_desc(dims, offsets); // Slice needs 3 primitives: input, result, and reorder. index = mkldnn_emitter.reserve_primitive_space(3); deps = mkldnn_emitter.get_primitive_deps(index); CodeWriter writer; // Write memory descriptors to file std::vector<mkldnn::memory::desc> descs = {input_sub_desc, result_desc}; mkldnn_emitter.reserve_descriptor_space(descs.size()); serialize_memory_descs(desc_file, descs, deps[0]); writer << "mkldnn::primitive_attr attr;\n"; writer << "attr.set_scratchpad_mode(mkldnn::scratchpad_mode::user);\n"; writer << "\n// build reorder primitives\n"; writer << "auto reorder_pd = " "mkldnn::reorder::primitive_desc(" "*cg_ctx->mkldnn_memories[" << std::to_string(deps[0]) << "]" ", *cg_ctx->mkldnn_memories[" << std::to_string(deps[1]) << "], attr);\n"; writer << "cg_ctx->mkldnn_primitives[" << std::to_string(index) << "] = new mkldnn::reorder(reorder_pd);\n"; writer << "cg_ctx->mkldnn_scratchpad_mds[" << std::to_string(index) << "] = new mkldnn::memory::desc(reorder_pd.scratchpad_desc());\n"; construct_string = writer.get_code(); } template <typename OP> void construct_primitive_build_string_conv( ngraph::runtime::cpu::MKLDNNEmitter& mkldnn_emitter, ngraph::Node* node, std::string& construct_string, std::vector<size_t>& deps, size_t& index, std::ofstream& desc_file) { auto convolution = static_cast<const OP*>(node); // query scratchpad size auto conv_desc = mkldnn_emitter.get_convolution_forward_desc<OP>(node); auto conv_attr = mkldnn_emitter.get_convolution_forward_attr<OP>(node); mkldnn_emitter.query_scratchpad_convolution_forward(conv_desc, conv_attr); Strides window_dilation_strides_adjusted; for (size_t s : convolution->get_window_dilation_strides()) { window_dilation_strides_adjusted.push_back(s - 1); } auto data_desc = mkldnn_utils::get_input_mkldnn_md(node, 0); auto weights_desc = mkldnn_utils::get_input_mkldnn_md(node, 1); auto result_desc = mkldnn_utils::get_output_mkldnn_md(node, 0); auto strides = convolution->get_window_movement_strides(); auto pad_below = convolution->get_padding_below(); auto pad_above = convolution->get_padding_above(); if (mkldnn_emitter.has_bias<OP>()) { index = mkldnn_emitter.reserve_primitive_space(5); } else { index = mkldnn_emitter.reserve_primitive_space(4); } deps = mkldnn_emitter.get_primitive_deps(index); CodeWriter writer; writer << "// Write in memory descriptors\n"; std::vector<mkldnn::memory::desc> descs = { data_desc, weights_desc, result_desc}; if (mkldnn_emitter.has_bias<OP>()) { auto bias_desc = mkldnn_utils::get_input_mkldnn_md(node, 2); descs.insert(descs.begin() + 2, bias_desc); } auto desc_index = mkldnn_emitter.get_mkldnn_descriptors_size(); mkldnn_emitter.reserve_descriptor_space(descs.size()); serialize_memory_descs(desc_file, descs, deps[0]); writer << "\n// build QConv primitive descriptor\n"; writer << "auto conv_desc = " "mkldnn::convolution_forward::desc(mkldnn::prop_kind::forward,\n" "mkldnn::algorithm::convolution_direct,\n" "*cg_ctx->mkldnn_descriptors[" << desc_index << "],\n" "*cg_ctx->mkldnn_descriptors[" << desc_index + 1 << "],\n"; if (mkldnn_emitter.has_bias<OP>()) { writer << "*cg_ctx->mkldnn_descriptors[" << desc_index + 2 << "],\n"; } writer << "*cg_ctx->mkldnn_descriptors[" << desc_index + (descs.size() - 1) << "],\n"; WRITE_MKLDNN_DIMS(strides); WRITE_MKLDNN_DIMS(window_dilation_strides_adjusted); WRITE_MKLDNN_DIMS(pad_below); writer << "mkldnn::memory::dims{" << join(pad_above) << "});\n"; writer << "mkldnn::post_ops ops;\n"; if (std::is_same<OP, ngraph::op::ConvolutionBiasAdd>() || std::is_same<OP, ngraph::op::ConvolutionAdd>()) { writer << "ops.append_sum(1.f);\n"; } if (std::is_same<OP, ngraph::op::QuantizedConvolutionBiasAdd>() || std::is_same<OP, ngraph::op::QuantizedConvolutionBiasSignedAdd>()) { writer << "ops.append_sum(dyn_post_op_scales[0]);\n"; } if (has_relu<OP>(node)) { writer << "const float ops_scale = 1.f;\n"; writer << "const float ops_alpha = -0.f; // relu negative slope\n"; writer << "const float ops_beta = 0.f;\n"; writer << "ops.append_eltwise(" "ops_scale, mkldnn::algorithm::eltwise_relu, ops_alpha, " "ops_beta);\n"; } writer << "mkldnn::primitive_attr conv_attr;\n"; writer << "conv_attr.set_post_ops(ops);\n"; writer << "conv_attr.set_scratchpad_mode(mkldnn::scratchpad_mode::user);\n"; if (mkldnn_emitter.is_quantized_conv<OP>()) { writer << "conv_attr.set_output_scales(mask, dyn_scales);\n"; } writer << "auto conv_pd = mkldnn::convolution_forward::primitive_desc(" "conv_desc, conv_attr, " "cg_ctx->global_cpu_engine);\n"; writer << "cg_ctx->mkldnn_primitives[" << std::to_string(index) << "] = new mkldnn::convolution_forward(conv_pd);\n"; writer << "cg_ctx->mkldnn_scratchpad_mds[" << std::to_string(index) << "] = new mkldnn::memory::desc(conv_pd.scratchpad_desc());\n"; construct_string = writer.get_code(); } template <> void MKLDNNPrimitiveBuildPass::CONSTRUCT_PRIMITIVE_BUILD_STRING_DECL(Convolution) { construct_primitive_build_string_conv<Convolution>( mkldnn_emitter, node, construct_string, deps, index, desc_file); } template <> void MKLDNNPrimitiveBuildPass::CONSTRUCT_PRIMITIVE_BUILD_STRING_DECL( QuantizedConvolution) { construct_primitive_build_string_conv<QuantizedConvolution>( mkldnn_emitter, node, construct_string, deps, index, desc_file); } template <> void MKLDNNPrimitiveBuildPass::CONSTRUCT_PRIMITIVE_BUILD_STRING_DECL(ConvolutionRelu) { construct_primitive_build_string_conv<ConvolutionRelu>( mkldnn_emitter, node, construct_string, deps, index, desc_file); } template <> void MKLDNNPrimitiveBuildPass::CONSTRUCT_PRIMITIVE_BUILD_STRING_DECL( QuantizedConvolutionRelu) { construct_primitive_build_string_conv<QuantizedConvolutionRelu>( mkldnn_emitter, node, construct_string, deps, index, desc_file); } template <> void MKLDNNPrimitiveBuildPass::CONSTRUCT_PRIMITIVE_BUILD_STRING_DECL(ConvolutionBias) { construct_primitive_build_string_conv<ConvolutionBias>( mkldnn_emitter, node, construct_string, deps, index, desc_file); } template <> void MKLDNNPrimitiveBuildPass::CONSTRUCT_PRIMITIVE_BUILD_STRING_DECL( QuantizedConvolutionBias) { construct_primitive_build_string_conv<QuantizedConvolutionBias>( mkldnn_emitter, node, construct_string, deps, index, desc_file); } template <> void MKLDNNPrimitiveBuildPass::CONSTRUCT_PRIMITIVE_BUILD_STRING_DECL( ConvolutionBiasAdd) { construct_primitive_build_string_conv<ConvolutionBiasAdd>( mkldnn_emitter, node, construct_string, deps, index, desc_file); } template <> void MKLDNNPrimitiveBuildPass::CONSTRUCT_PRIMITIVE_BUILD_STRING_DECL( QuantizedConvolutionBiasAdd) { construct_primitive_build_string_conv<QuantizedConvolutionBiasAdd>( mkldnn_emitter, node, construct_string, deps, index, desc_file); } template <> void MKLDNNPrimitiveBuildPass::CONSTRUCT_PRIMITIVE_BUILD_STRING_DECL(ConvolutionAdd) { construct_primitive_build_string_conv<ConvolutionAdd>( mkldnn_emitter, node, construct_string, deps, index, desc_file); } template <> void MKLDNNPrimitiveBuildPass::CONSTRUCT_PRIMITIVE_BUILD_STRING_DECL( QuantizedConvolutionBiasSignedAdd) { construct_primitive_build_string_conv<QuantizedConvolutionBiasSignedAdd>( mkldnn_emitter, node, construct_string, deps, index, desc_file); } template <> void MKLDNNPrimitiveBuildPass::CONSTRUCT_PRIMITIVE_BUILD_STRING_DECL( GroupConvolution) { construct_primitive_build_string_conv<GroupConvolution>( mkldnn_emitter, node, construct_string, deps, index, desc_file); } template <> void MKLDNNPrimitiveBuildPass::CONSTRUCT_PRIMITIVE_BUILD_STRING_DECL( GroupConvolutionBias) { construct_primitive_build_string_conv<GroupConvolutionBias>( mkldnn_emitter, node, construct_string, deps, index, desc_file); } template <typename OP> void construct_primitive_build_string_conv_backward_filters( ngraph::runtime::cpu::MKLDNNEmitter& mkldnn_emitter, ngraph::Node* node, std::string& construct_string, std::vector<size_t>& deps, size_t& index, std::ofstream& desc_file) { auto has_bias = false; if (mkldnn_emitter.has_bias<OP>()) { has_bias = true; } auto convolution = static_cast<const OP*>(node); // query scratchpad size auto bwd_desc = mkldnn_emitter.get_convolution_backward_weights_desc<OP>(node); auto fwd_desc = mkldnn_emitter.get_convolution_forward_desc_for_backward_op<OP>(node); mkldnn_emitter.query_scratchpad_convolution_backward_weights(fwd_desc, bwd_desc); Strides window_dilation_strides_adjusted; for (size_t s : convolution->get_window_dilation_strides_forward()) { window_dilation_strides_adjusted.push_back(s - 1); } auto arg0_desc = mkldnn_utils::get_input_mkldnn_md(node, 0); auto arg1_desc = mkldnn_utils::get_input_mkldnn_md(node, 1); auto out0_desc = mkldnn_utils::get_output_mkldnn_md(node, 0); auto strides = convolution->get_window_movement_strides_forward(); auto pad_below = convolution->get_padding_below_forward(); auto pad_above = convolution->get_padding_above_forward(); mkldnn::algorithm conv_algo = mkldnn_utils::get_conv_algo(); auto conv_algo_string = conv_algo == mkldnn::algorithm::convolution_auto ? "mkldnn::algorithm::convolution_auto,\n" : "mkldnn::algorithm::convolution_direct,\n"; std::vector<mkldnn::memory::desc> descs = {arg0_desc, arg1_desc, out0_desc}; // ConvolutionBackpropFilter needs 4 primitives: src, diff_dst, diff_weights, // and convolution_backward_weights. // ConvolutionBackpropFiltersBias needs 5 primitives: src, diff_dst, // diff_weights, // diff_bias, and convolution_backward_weights. if (has_bias) { index = mkldnn_emitter.reserve_primitive_space(5); auto out1_desc = mkldnn_utils::get_output_mkldnn_md(node, 1); descs.push_back(out1_desc); } else { index = mkldnn_emitter.reserve_primitive_space(4); } deps = mkldnn_emitter.get_primitive_deps(index); CodeWriter writer; // Write memory descriptors to file auto desc_index = mkldnn_emitter.get_mkldnn_descriptors_size(); mkldnn_emitter.reserve_descriptor_space(descs.size()); serialize_memory_descs(desc_file, descs, deps[0]); writer << "auto fwd_desc = " "mkldnn::convolution_forward::desc(mkldnn::prop_kind::forward,\n"; writer << conv_algo_string; writer << "*cg_ctx->mkldnn_descriptors[" << desc_index << "],\n" "*cg_ctx->mkldnn_descriptors[" << desc_index + 2 << "],\n"; if (has_bias) { writer << "*cg_ctx->mkldnn_descriptors[" << desc_index + 3 << "],\n"; } writer << "*cg_ctx->mkldnn_descriptors[" << desc_index + 1 << "],\n"; WRITE_MKLDNN_DIMS(strides); WRITE_MKLDNN_DIMS(window_dilation_strides_adjusted); WRITE_MKLDNN_DIMS(pad_below); writer << "mkldnn::memory::dims{" << join(pad_above) << "});\n"; writer << "\nauto bwd_desc = " "mkldnn::convolution_backward_weights::desc(\n"; writer << conv_algo_string; writer << "*cg_ctx->mkldnn_descriptors[" << desc_index << "],\n" "*cg_ctx->mkldnn_descriptors[" << desc_index + 2 << "],\n"; if (has_bias) { writer << "*cg_ctx->mkldnn_descriptors[" << desc_index + 3 << "],\n"; } writer << "*cg_ctx->mkldnn_descriptors[" << desc_index + 1 << "],\n"; WRITE_MKLDNN_DIMS(strides); WRITE_MKLDNN_DIMS(window_dilation_strides_adjusted); WRITE_MKLDNN_DIMS(pad_below); writer << "mkldnn::memory::dims{" << join(pad_above) << "});\n"; writer << "mkldnn::primitive_attr attr;\n"; writer << "attr.set_scratchpad_mode(mkldnn::scratchpad_mode::user);\n"; writer << "\n// create forward primitive descriptor\n"; writer << "auto fwd_pd = mkldnn::convolution_forward::primitive_desc(fwd_desc, " "cg_ctx->global_cpu_engine);\n"; writer << "\n// create backward primitive_descriptor\n"; writer << "auto bwd_pd = " "mkldnn::convolution_backward_weights::primitive_desc(bwd_desc, " "attr, " "cg_ctx->global_cpu_engine, fwd_pd);\n"; writer << "\n// build primitive\n"; writer << "cg_ctx->mkldnn_primitives[" << std::to_string(index) << "] = new mkldnn::convolution_backward_weights(bwd_pd);\n"; writer << "cg_ctx->mkldnn_scratchpad_mds[" << std::to_string(index) << "] = new mkldnn::memory::desc(bwd_pd.scratchpad_desc());\n"; construct_string = writer.get_code(); } template <> void MKLDNNPrimitiveBuildPass::CONSTRUCT_PRIMITIVE_BUILD_STRING_DECL( ConvolutionBackpropFilters) { construct_primitive_build_string_conv_backward_filters< ConvolutionBackpropFilters>( mkldnn_emitter, node, construct_string, deps, index, desc_file); } template <> void MKLDNNPrimitiveBuildPass::CONSTRUCT_PRIMITIVE_BUILD_STRING_DECL( ConvolutionBiasBackpropFiltersBias) { construct_primitive_build_string_conv_backward_filters< ConvolutionBiasBackpropFiltersBias>( mkldnn_emitter, node, construct_string, deps, index, desc_file); } template <> void MKLDNNPrimitiveBuildPass::CONSTRUCT_PRIMITIVE_BUILD_STRING_DECL( ConvolutionBackpropData) { auto convolution = static_cast<const ConvolutionBackpropData*>(node); // query scratchpad size auto bwd_desc = mkldnn_emitter.get_convolution_backward_data_desc< ngraph::op::ConvolutionBackpropData>(node); auto fwd_desc = mkldnn_emitter.get_convolution_forward_desc_for_backward_op< ngraph::op::ConvolutionBackpropData>(node); mkldnn_emitter.query_scratchpad_convolution_backward_data(fwd_desc, bwd_desc); Strides window_dilation_strides_adjusted; for (size_t s : convolution->get_window_dilation_strides_forward()) { window_dilation_strides_adjusted.push_back(s - 1); } auto arg0_desc = mkldnn_utils::get_input_mkldnn_md(node, 0); auto arg1_desc = mkldnn_utils::get_input_mkldnn_md(node, 1); auto out0_desc = mkldnn_utils::get_output_mkldnn_md(node, 0); auto strides = convolution->get_window_movement_strides_forward(); auto pad_below = convolution->get_padding_below_forward(); auto pad_above = convolution->get_padding_above_forward(); mkldnn::algorithm conv_algo = mkldnn_utils::get_conv_algo(); auto conv_algo_string = conv_algo == mkldnn::algorithm::convolution_auto ? "mkldnn::algorithm::convolution_auto,\n" : "mkldnn::algorithm::convolution_direct,\n"; std::vector<mkldnn::memory::desc> descs = {arg0_desc, arg1_desc, out0_desc}; // ConvolutionBackpropData needs 4 primitives: weights, diff_dst, diff_src, // and convolution_backward_data. index = mkldnn_emitter.reserve_primitive_space(4); deps = mkldnn_emitter.get_primitive_deps(index); CodeWriter writer; // Write memory descriptors to file auto desc_index = mkldnn_emitter.get_mkldnn_descriptors_size(); mkldnn_emitter.reserve_descriptor_space(descs.size()); serialize_memory_descs(desc_file, descs, deps[0]); writer << "auto fwd_desc = " "mkldnn::convolution_forward::desc(mkldnn::prop_kind::forward,\n"; writer << conv_algo_string; writer << "*cg_ctx->mkldnn_descriptors[" << desc_index + 2 << "],\n" "*cg_ctx->mkldnn_descriptors[" << desc_index << "],\n"; writer << "*cg_ctx->mkldnn_descriptors[" << desc_index + 1 << "],\n"; WRITE_MKLDNN_DIMS(strides); WRITE_MKLDNN_DIMS(window_dilation_strides_adjusted); WRITE_MKLDNN_DIMS(pad_below); writer << "mkldnn::memory::dims{" << join(pad_above) << "});\n"; writer << "\nauto bwd_desc = " "mkldnn::convolution_backward_data::desc(\n"; writer << conv_algo_string; writer << "*cg_ctx->mkldnn_descriptors[" << desc_index + 2 << "],\n" "*cg_ctx->mkldnn_descriptors[" << desc_index << "],\n"; writer << "*cg_ctx->mkldnn_descriptors[" << desc_index + 1 << "],\n"; WRITE_MKLDNN_DIMS(strides); WRITE_MKLDNN_DIMS(window_dilation_strides_adjusted); WRITE_MKLDNN_DIMS(pad_below); writer << "mkldnn::memory::dims{" << join(pad_above) << "});\n"; writer << "mkldnn::primitive_attr attr;\n"; writer << "attr.set_scratchpad_mode(mkldnn::scratchpad_mode::user);\n"; writer << "\n// create forward primitive descriptor\n"; writer << "auto fwd_pd = mkldnn::convolution_forward::primitive_desc(fwd_desc, " "cg_ctx->global_cpu_engine);\n"; writer << "\n// create backward primitive_descriptor\n"; writer << "auto bwd_pd = " "mkldnn::convolution_backward_data::primitive_desc(bwd_desc, attr, " "cg_ctx->global_cpu_engine, fwd_pd);\n"; writer << "\n// build primitive\n"; writer << "cg_ctx->mkldnn_primitives[" << std::to_string(index) << "] = new mkldnn::convolution_backward_data(bwd_pd);\n"; writer << "cg_ctx->mkldnn_scratchpad_mds[" << std::to_string(index) << "] = new mkldnn::memory::desc(bwd_pd.scratchpad_desc());\n"; construct_string = writer.get_code(); } template <> void MKLDNNPrimitiveBuildPass::CONSTRUCT_PRIMITIVE_BUILD_STRING_DECL( DeconvolutionBias) { auto dconv = static_cast<const DeconvolutionBias*>(node); // query scratchpad size auto deconvbias_desc = mkldnn_emitter .get_deconvolutionbias_forward_data<ngraph::op::DeconvolutionBias>( node); mkldnn_emitter.query_scratchpad_deconvolution_forward(deconvbias_desc); // For dilation, MKLDNN wants to know how many elements to insert between, not // how far // apart to space the elements like nGraph. So we have to subtract 1 from each // pos. Strides window_dilation_strides_adjusted; for (size_t s : dconv->get_window_dilation_strides_forward()) { window_dilation_strides_adjusted.push_back(s - 1); } auto weights_desc = mkldnn_utils::get_input_mkldnn_md(node, 0); auto delta_desc = mkldnn_utils::get_input_mkldnn_md(node, 1); auto bias_desc = mkldnn_utils::get_input_mkldnn_md(node, 2); auto result_desc = mkldnn_utils::get_output_mkldnn_md(node, 0); auto window_strides = dconv->get_window_movement_strides_forward(); auto padding_below = dconv->get_padding_below_forward(); auto padding_above = dconv->get_padding_above_forward(); CodeWriter writer; std::vector<mkldnn::memory::desc> descs = { weights_desc, delta_desc, bias_desc, result_desc}; // DeconvolutionBias needs 5 primitives: weights, delta, bias, result, // and deconvolutionbias. index = mkldnn_emitter.reserve_primitive_space(5); deps = mkldnn_emitter.get_primitive_deps(index); auto desc_index = mkldnn_emitter.get_mkldnn_descriptors_size(); mkldnn_emitter.reserve_descriptor_space(descs.size()); serialize_memory_descs(desc_file, descs, deps[0]); if (dconv->with_relu()) { writer << "mkldnn::post_ops pops;\n"; writer << "const float ops_scale = 1.f;\n"; writer << "const float ops_alpha = -0.f; // relu negative slope\n"; writer << "const float ops_beta = 0.f;\n"; writer << "pops.append_eltwise(" "ops_scale, mkldnn::algorithm::eltwise_relu, ops_alpha, " "ops_beta);\n"; } else { writer << "mkldnn::post_ops pops = mkldnn::post_ops();\n"; } writer << "mkldnn::primitive_attr dconv_attr;\n"; writer << "dconv_attr.set_post_ops(pops);\n"; writer << "dconv_attr.set_scratchpad_mode(mkldnn::scratchpad_mode::user);\n"; writer << "\nauto dconv_desc = " "mkldnn::deconvolution_forward::desc(\n" "mkldnn::prop_kind::forward,\n" "mkldnn::algorithm::deconvolution_direct,\n" "*cg_ctx->mkldnn_descriptors[" << desc_index + 1 << "],\n" "*cg_ctx->mkldnn_descriptors[" << desc_index + 0 << "],\n" "*cg_ctx->mkldnn_descriptors[" << desc_index + 2 << "],\n" "*cg_ctx->mkldnn_descriptors[" << desc_index + 3 << "],\n"; WRITE_MKLDNN_DIMS(window_strides); WRITE_MKLDNN_DIMS(window_dilation_strides_adjusted); WRITE_MKLDNN_DIMS(padding_below); writer << "mkldnn::memory::dims{" << join(padding_above) << "});\n"; writer << "\n// create forward primitive descriptor\n"; writer << "auto dconv_pd = " "mkldnn::deconvolution_forward::primitive_desc(dconv_desc, " "dconv_attr, cg_ctx->global_cpu_engine);\n"; writer << "\n// build primitive\n"; writer << "cg_ctx->mkldnn_primitives[" << std::to_string(index) << "] = new mkldnn::deconvolution_forward(dconv_pd);\n"; writer << "cg_ctx->mkldnn_scratchpad_mds[" << std::to_string(index) << "] = new mkldnn::memory::desc(dconv_pd.scratchpad_desc());\n"; construct_string = writer.get_code(); } template <typename OP> void construct_primitive_build_string_max_pool( ngraph::runtime::cpu::MKLDNNEmitter& mkldnn_emitter, ngraph::Node* node, std::string& construct_string, std::vector<size_t>& deps, size_t& index, std::ofstream& desc_file) { auto pool = static_cast<const OP*>(node); auto input_desc = mkldnn_utils::get_input_mkldnn_md(node, 0); auto result_desc = mkldnn_utils::get_output_mkldnn_md(node, 0); // query scratchpad size auto max_pool_desc = mkldnn_emitter.get_max_pooling_forward_desc<ngraph::op::MaxPool>(node, false); mkldnn_emitter.query_scratchpad_pooling_forward(max_pool_desc); auto window_shape = pool->get_window_shape(); auto window_strides = pool->get_window_movement_strides(); auto padding_below = pool->get_padding_below(); auto padding_above = pool->get_padding_above(); CodeWriter writer; std::vector<mkldnn::memory::desc> descs = {input_desc, result_desc}; index = mkldnn_emitter.reserve_primitive_space(3); deps = mkldnn_emitter.get_primitive_deps(index); auto desc_index = mkldnn_emitter.get_mkldnn_descriptors_size(); mkldnn_emitter.reserve_descriptor_space(descs.size()); serialize_memory_descs(desc_file, descs, deps[0]); writer << "\n// build Maxpool primitive descriptor\n"; writer << "auto max_pool_desc = "; writer << "mkldnn::pooling_forward::desc(mkldnn::prop_kind::forward_" "inference,\n"; writer << "mkldnn::algorithm::pooling_max,\n" "*cg_ctx->mkldnn_descriptors[" << desc_index << "],\n" "*cg_ctx->mkldnn_descriptors[" << desc_index + 1 << "],\n"; WRITE_MKLDNN_DIMS(window_strides); WRITE_MKLDNN_DIMS(window_shape); WRITE_MKLDNN_DIMS(padding_below); writer << "mkldnn::memory::dims{" << join(padding_above) << "});\n"; writer << "mkldnn::primitive_attr attr;\n"; writer << "attr.set_scratchpad_mode(mkldnn::scratchpad_mode::user);\n"; writer << "auto max_pool_pd = mkldnn::pooling_forward::primitive_desc(" "max_pool_desc, attr, " "cg_ctx->global_cpu_engine);\n"; writer << "cg_ctx->mkldnn_primitives[" << std::to_string(index) << "] = new mkldnn::pooling_forward(max_pool_pd);\n"; writer << "cg_ctx->mkldnn_scratchpad_mds[" << std::to_string(index) << "] = new mkldnn::memory::desc(max_pool_pd.scratchpad_desc());\n"; construct_string = writer.get_code(); } template <typename OP> void construct_primitive_build_string_avg_pool( ngraph::runtime::cpu::MKLDNNEmitter& mkldnn_emitter, ngraph::Node* node, std::string& construct_string, std::vector<size_t>& deps, size_t& index, std::ofstream& desc_file) { auto pool = static_cast<const OP*>(node); auto input_desc = mkldnn_utils::get_input_mkldnn_md(node, 0); auto result_desc = mkldnn_utils::get_output_mkldnn_md(node, 0); // query scratchpad size auto avg_pool_desc = mkldnn_emitter.get_avg_pooling_forward_desc<ngraph::op::AvgPool>(node, false); mkldnn_emitter.query_scratchpad_pooling_forward(avg_pool_desc); auto window_shape = pool->get_window_shape(); auto window_strides = pool->get_window_movement_strides(); auto padding_below = pool->get_padding_below(); auto padding_above = pool->get_padding_above(); auto include_padding_in_avg_computation = pool->get_include_padding_in_avg_computation(); CodeWriter writer; std::vector<mkldnn::memory::desc> descs = {input_desc, result_desc}; index = mkldnn_emitter.reserve_primitive_space(3); deps = mkldnn_emitter.get_primitive_deps(index); auto desc_index = mkldnn_emitter.get_mkldnn_descriptors_size(); mkldnn_emitter.reserve_descriptor_space(descs.size()); serialize_memory_descs(desc_file, descs, deps[0]); writer << "\n// build Avgpool primitive descriptor\n"; writer << "auto avg_pool_desc = "; writer << "mkldnn::pooling_forward::desc(mkldnn::prop_kind::forward_" "inference,\n"; if (include_padding_in_avg_computation) { writer << "mkldnn::algorithm::pooling_avg_include_padding,\n"; } else { writer << "mkldnn::algorithm::pooling_avg_exclude_padding,\n"; } writer << "*cg_ctx->mkldnn_descriptors[" << desc_index << "],\n" "*cg_ctx->mkldnn_descriptors[" << desc_index + 1 << "],\n"; WRITE_MKLDNN_DIMS(window_strides); WRITE_MKLDNN_DIMS(window_shape); WRITE_MKLDNN_DIMS(padding_below); writer << "mkldnn::memory::dims{" << join(padding_above) << "});\n"; writer << "mkldnn::primitive_attr attr;\n"; writer << "attr.set_scratchpad_mode(mkldnn::scratchpad_mode::user);\n"; writer << "auto avg_pool_pd = mkldnn::pooling_forward::primitive_desc(" "avg_pool_desc, attr, " "cg_ctx->global_cpu_engine);\n"; writer << "cg_ctx->mkldnn_primitives[" << std::to_string(index) << "] = new mkldnn::pooling_forward(avg_pool_pd);\n"; writer << "cg_ctx->mkldnn_scratchpad_mds[" << std::to_string(index) << "] = new mkldnn::memory::desc(avg_pool_pd.scratchpad_desc());\n"; construct_string = writer.get_code(); } template <> void MKLDNNPrimitiveBuildPass::CONSTRUCT_PRIMITIVE_BUILD_STRING_DECL(MaxPool) { construct_primitive_build_string_max_pool<MaxPool>( mkldnn_emitter, node, construct_string, deps, index, desc_file); } template <> void MKLDNNPrimitiveBuildPass::CONSTRUCT_PRIMITIVE_BUILD_STRING_DECL(AvgPool) { construct_primitive_build_string_avg_pool<AvgPool>( mkldnn_emitter, node, construct_string, deps, index, desc_file); } template <> void MKLDNNPrimitiveBuildPass::CONSTRUCT_PRIMITIVE_BUILD_STRING_DECL( MaxPoolWithIndices) { auto input_desc = mkldnn_utils::get_input_mkldnn_md(node, 0); auto result_desc = mkldnn_utils::get_output_mkldnn_md(node, 0); auto pool = static_cast<const ngraph::op::MaxPoolWithIndices*>(node); auto window_shape = pool->get_window_shape(); auto window_strides = pool->get_window_movement_strides(); auto padding_below = pool->get_padding_below(); auto padding_above = pool->get_padding_above(); // query scratchpad size auto max_pool_desc = mkldnn_emitter.get_max_pooling_with_indices_forward_desc< ngraph::op::MaxPoolWithIndices>(node); mkldnn_emitter.query_scratchpad_pooling_forward(max_pool_desc); // MaxPoolWithIndices needs 4 primitives: input, result, workspace, and // pooling_forward. index = mkldnn_emitter.reserve_primitive_space(4); deps = mkldnn_emitter.get_primitive_deps(index); CodeWriter writer; // Write memory descriptors to file std::vector<mkldnn::memory::desc> descs = {input_desc, result_desc}; auto desc_index = mkldnn_emitter.get_mkldnn_descriptors_size(); mkldnn_emitter.reserve_descriptor_space(descs.size()); serialize_memory_descs(desc_file, descs, deps[0]); writer << "auto pool_desc = " "mkldnn::pooling_forward::desc(mkldnn::prop_kind::forward_training,\n" "mkldnn::algorithm::pooling_max,\n" "*cg_ctx->mkldnn_descriptors[" << desc_index << "],\n" "*cg_ctx->mkldnn_descriptors[" << desc_index + 1 << "],\n"; WRITE_MKLDNN_DIMS(window_strides); WRITE_MKLDNN_DIMS(window_shape); WRITE_MKLDNN_DIMS(padding_below); writer << "mkldnn::memory::dims{" << join(padding_above) << "});\n"; writer << "mkldnn::primitive_attr attr;\n"; writer << "attr.set_scratchpad_mode(mkldnn::scratchpad_mode::user);\n"; writer << "\n// build primitive descriptor\n"; writer << "mkldnn::pooling_forward::primitive_desc fwd_pd{pool_desc, " "cg_ctx->global_cpu_engine};\n"; writer << "cg_ctx->mkldnn_memories[" << std::to_string(deps[2]) << "] = new mkldnn::memory(fwd_pd.workspace_desc(), " "cg_ctx->global_cpu_engine, nullptr);\n"; writer << "\n// build primitive\n"; writer << "cg_ctx->mkldnn_primitives[" << std::to_string(index) << "] = new mkldnn::pooling_forward(fwd_pd);\n"; writer << "cg_ctx->mkldnn_scratchpad_mds[" << std::to_string(index) << "] = new mkldnn::memory::desc(fwd_pd.scratchpad_desc());\n"; construct_string = writer.get_code(); } template <> void MKLDNNPrimitiveBuildPass::CONSTRUCT_PRIMITIVE_BUILD_STRING_DECL(AvgPoolBackprop) { auto diff_dst_desc = mkldnn_utils::get_input_mkldnn_md(node, 0); auto diff_src_desc = mkldnn_utils::get_output_mkldnn_md(node, 0); auto pool = static_cast<const ngraph::op::AvgPoolBackprop*>(node); auto window_shape = pool->get_window_shape(); auto window_strides = pool->get_window_movement_strides(); auto padding_below = pool->get_padding_below(); auto padding_above = pool->get_padding_above(); auto algo_string = pool->get_include_padding_in_avg_computation() ? "mkldnn::algorithm::pooling_avg_include_padding" : "mkldnn::algorithm::pooling_avg_exclude_padding"; // query scratchpad size auto avg_pool_fwd_desc = mkldnn_emitter.get_avg_pooling_forward_desc<ngraph::op::AvgPoolBackprop>( node, true); auto avg_pool_desc = mkldnn_emitter.get_avg_pooling_backward_desc<ngraph::op::AvgPoolBackprop>( node); mkldnn_emitter.query_scratchpad_avg_pooling_backward(avg_pool_fwd_desc, avg_pool_desc); // AvgPoolBackprop needs 3 primitives: diff_dst, diff_src, and pooling_backward. index = mkldnn_emitter.reserve_primitive_space(3); deps = mkldnn_emitter.get_primitive_deps(index); CodeWriter writer; // Write memory descriptors to file std::vector<mkldnn::memory::desc> descs = {diff_dst_desc, diff_src_desc}; auto desc_index = mkldnn_emitter.get_mkldnn_descriptors_size(); mkldnn_emitter.reserve_descriptor_space(descs.size()); serialize_memory_descs(desc_file, descs, deps[0]); writer << "auto fwd_desc = " "mkldnn::pooling_forward::desc(mkldnn::prop_kind::forward_training,\n"; writer << algo_string << ",\n"; writer << "*cg_ctx->mkldnn_descriptors[" << desc_index + 1 << "],\n" "*cg_ctx->mkldnn_descriptors[" << desc_index << "],\n"; WRITE_MKLDNN_DIMS(window_strides); WRITE_MKLDNN_DIMS(window_shape); WRITE_MKLDNN_DIMS(padding_below); writer << "mkldnn::memory::dims{" << join(padding_above) << "});\n"; writer << "auto bwd_desc = " "mkldnn::pooling_backward::desc(\n"; writer << algo_string << ",\n"; writer << "*cg_ctx->mkldnn_descriptors[" << desc_index + 1 << "],\n" "*cg_ctx->mkldnn_descriptors[" << desc_index << "],\n"; WRITE_MKLDNN_DIMS(window_strides); WRITE_MKLDNN_DIMS(window_shape); WRITE_MKLDNN_DIMS(padding_below); writer << "mkldnn::memory::dims{" << join(padding_above) << "});\n"; writer << "mkldnn::primitive_attr attr;\n"; writer << "attr.set_scratchpad_mode(mkldnn::scratchpad_mode::user);\n"; writer << "\n// build primitive descriptor\n"; writer << "mkldnn::pooling_forward::primitive_desc fwd_pd{fwd_desc, " "cg_ctx->global_cpu_engine};\n"; writer << "mkldnn::pooling_backward::primitive_desc bwd_pd{bwd_desc, attr, " "cg_ctx->global_cpu_engine, fwd_pd};\n"; writer << "\n// build primitive\n"; writer << "cg_ctx->mkldnn_primitives[" << std::to_string(index) << "] = new mkldnn::pooling_backward(bwd_pd);\n"; writer << "cg_ctx->mkldnn_scratchpad_mds[" << std::to_string(index) << "] = new mkldnn::memory::desc(bwd_pd.scratchpad_desc());\n"; construct_string = writer.get_code(); } template <> void MKLDNNPrimitiveBuildPass::CONSTRUCT_PRIMITIVE_BUILD_STRING_DECL(MaxPoolBackprop) { auto fprop_src_desc = mkldnn_utils::get_input_mkldnn_md(node, 0); auto diff_dst_desc = mkldnn_utils::get_input_mkldnn_md(node, 1); auto diff_src_desc = mkldnn_utils::get_output_mkldnn_md(node, 0); auto pool = static_cast<const ngraph::op::MaxPoolWithIndices*>(node); auto window_shape = pool->get_window_shape(); auto window_strides = pool->get_window_movement_strides(); auto padding_below = pool->get_padding_below(); auto padding_above = pool->get_padding_above(); // query scratchpad size auto fwd_pool_desc = mkldnn_emitter.get_max_pooling_forward_desc<ngraph::op::MaxPoolBackprop>( node, true); auto bwd_pool_desc = mkldnn_emitter.get_max_pooling_backward_desc<ngraph::op::MaxPoolBackprop>( node); mkldnn_emitter.query_scratchpad_max_pooling_backward(fwd_pool_desc, bwd_pool_desc); // MaxPoolBackprop needs 6 primitives: fprop_src, diff_dst, diff_src, workspace // pooling forward, and pooling_backward. // It needs a new workspace. index = mkldnn_emitter.reserve_primitive_space(6, true /* new workspace */); deps = mkldnn_emitter.get_primitive_deps(index); CodeWriter writer; // Write memory descriptors to file std::vector<mkldnn::memory::desc> descs = { fprop_src_desc, diff_dst_desc, diff_src_desc}; auto desc_index = mkldnn_emitter.get_mkldnn_descriptors_size(); mkldnn_emitter.reserve_descriptor_space(descs.size()); serialize_memory_descs(desc_file, descs, deps[0]); writer << "auto fwd_desc = " "mkldnn::pooling_forward::desc(mkldnn::prop_kind::forward_training,\n" "mkldnn::algorithm::pooling_max,\n" "*cg_ctx->mkldnn_descriptors[" << desc_index + 2 << "],\n" "*cg_ctx->mkldnn_descriptors[" << desc_index + 1 << "],\n"; WRITE_MKLDNN_DIMS(window_strides); WRITE_MKLDNN_DIMS(window_shape); WRITE_MKLDNN_DIMS(padding_below); writer << "mkldnn::memory::dims{" << join(padding_above) << "});\n"; writer << "\nauto bwd_desc = " "mkldnn::pooling_backward::desc(\n" "mkldnn::algorithm::pooling_max,\n" "*cg_ctx->mkldnn_descriptors[" << desc_index + 2 << "],\n" "*cg_ctx->mkldnn_descriptors[" << desc_index + 1 << "],\n"; WRITE_MKLDNN_DIMS(window_strides); WRITE_MKLDNN_DIMS(window_shape); WRITE_MKLDNN_DIMS(padding_below); writer << "mkldnn::memory::dims{" << join(padding_above) << "});\n"; writer << "mkldnn::primitive_attr attr;\n"; writer << "attr.set_scratchpad_mode(mkldnn::scratchpad_mode::user);\n"; writer << "\n// build primitive descriptor\n"; writer << "mkldnn::pooling_forward::primitive_desc fwd_pd{fwd_desc, attr, " "cg_ctx->global_cpu_engine};\n"; writer << "mkldnn::pooling_backward::primitive_desc bwd_pd{bwd_desc, attr, " "cg_ctx->global_cpu_engine, fwd_pd};\n"; // This is implemented differently from cpu builder, // we only use one index and one deps here. writer << "cg_ctx->mkldnn_memories[" << std::to_string(deps[3]) << "] = new mkldnn::memory(fwd_pd.workspace_desc(), " "cg_ctx->global_cpu_engine, nullptr);\n"; writer << "auto workspace = " "(char*)malloc(fwd_pd.workspace_desc().get_size());" "\n"; writer << "if (!workspace)\n"; writer.block_begin(); writer << "throw std::bad_alloc();\n"; writer.block_end(); writer << "cg_ctx->mkldnn_workspaces.push_back(workspace);\n"; deps[5] = mkldnn_emitter.reserve_workspace(); writer << "\n// build primitive\n"; writer << "cg_ctx->mkldnn_primitives[" << std::to_string(deps[4]) << "] = new mkldnn::pooling_forward(fwd_pd);\n"; writer << "cg_ctx->mkldnn_scratchpad_mds[" << std::to_string(deps[4]) << "] = new mkldnn::memory::desc(fwd_pd.scratchpad_desc());\n"; writer << "cg_ctx->mkldnn_primitives[" << std::to_string(index) << "] = new mkldnn::pooling_backward(bwd_pd);\n"; writer << "cg_ctx->mkldnn_scratchpad_mds[" << std::to_string(index) << "] = new mkldnn::memory::desc(bwd_pd.scratchpad_desc());\n"; construct_string = writer.get_code(); } template <> void MKLDNNPrimitiveBuildPass::CONSTRUCT_PRIMITIVE_BUILD_STRING_DECL( MaxPoolWithIndicesBackprop) { auto diff_dst_desc = mkldnn_utils::get_input_mkldnn_md(node, 1); auto diff_src_desc = mkldnn_utils::get_output_mkldnn_md(node, 0); auto pool = static_cast<const ngraph::op::MaxPoolWithIndices*>(node); auto window_shape = pool->get_window_shape(); auto window_strides = pool->get_window_movement_strides(); auto padding_below = pool->get_padding_below(); auto padding_above = pool->get_padding_above(); // query scratchpad size auto fwd_pool_desc = mkldnn_emitter .get_max_pooling_forward_desc<ngraph::op::MaxPoolWithIndicesBackprop>( node, true); auto bwd_pool_desc = mkldnn_emitter .get_max_pooling_backward_desc<ngraph::op::MaxPoolWithIndicesBackprop>( node); mkldnn_emitter.query_scratchpad_max_pooling_with_indices_backward( fwd_pool_desc, bwd_pool_desc); // MaxPoolWithIndicesBackprop needs 4 primitives: diff_dst, fprop_workspace, // diff_src // and pooling_backward. index = mkldnn_emitter.reserve_primitive_space(4); deps = mkldnn_emitter.get_primitive_deps(index); CodeWriter writer; // Write memory descriptors to file std::vector<mkldnn::memory::desc> descs = {diff_dst_desc, diff_src_desc}; auto desc_index = mkldnn_emitter.get_mkldnn_descriptors_size(); mkldnn_emitter.reserve_descriptor_space(descs.size()); serialize_memory_descs(desc_file, descs, deps[0]); writer << "auto fwd_desc = " "mkldnn::pooling_forward::desc(mkldnn::prop_kind::forward_training,\n" "mkldnn::algorithm::pooling_max,\n" "*cg_ctx->mkldnn_descriptors[" << desc_index + 1 << "],\n" "*cg_ctx->mkldnn_descriptors[" << desc_index << "],\n"; WRITE_MKLDNN_DIMS(window_strides); WRITE_MKLDNN_DIMS(window_shape); WRITE_MKLDNN_DIMS(padding_below); writer << "mkldnn::memory::dims{" << join(padding_above) << "});\n"; writer << "auto bwd_desc = " "mkldnn::pooling_backward::desc(\n" "mkldnn::algorithm::pooling_max,\n" "*cg_ctx->mkldnn_descriptors[" << desc_index + 1 << "],\n" "*cg_ctx->mkldnn_descriptors[" << desc_index << "],\n"; WRITE_MKLDNN_DIMS(window_strides); WRITE_MKLDNN_DIMS(window_shape); WRITE_MKLDNN_DIMS(padding_below); writer << "mkldnn::memory::dims{" << join(padding_above) << "});\n"; writer << "mkldnn::primitive_attr attr;\n"; writer << "attr.set_scratchpad_mode(mkldnn::scratchpad_mode::user);\n"; writer << "\n// build primitive descriptor\n"; writer << "mkldnn::pooling_forward::primitive_desc fwd_pd{fwd_desc, " "cg_ctx->global_cpu_engine};\n"; writer << "mkldnn::pooling_backward::primitive_desc bwd_pd{bwd_desc, attr, " "cg_ctx->global_cpu_engine, fwd_pd};\n"; // this is different from cpu builder because we do not write workspace desc to // desc_file. // here workspace's mkldnn primitive index is in deps[2] in stead of deps[1]. writer << "cg_ctx->mkldnn_memories[" << std::to_string(deps[2]) << "] = new mkldnn::memory(fwd_pd.workspace_desc(), " "cg_ctx->global_cpu_engine, nullptr);\n"; writer << "\n// build primitive\n"; writer << "cg_ctx->mkldnn_primitives[" << std::to_string(index) << "] = new mkldnn::pooling_backward(bwd_pd);\n"; writer << "cg_ctx->mkldnn_scratchpad_mds[" << std::to_string(index) << "] = new mkldnn::memory::desc(bwd_pd.scratchpad_desc());\n"; construct_string = writer.get_code(); } template <> void MKLDNNPrimitiveBuildPass::CONSTRUCT_PRIMITIVE_BUILD_STRING_DECL( ngraph::runtime::cpu::op::ConvertLayout) { const auto& args = node->get_inputs(); auto input_desc = mkldnn_utils::get_input_mkldnn_md(node, 0); auto result_desc = mkldnn_utils::get_output_mkldnn_md(node, 0); bool input_format_is_nchw = mkldnn_utils::mkldnn_md_matches_format_tag( input_desc.data, mkldnn::memory::format_tag::nchw); if (input_format_is_nchw && mkldnn_utils::mkldnn_md_matches_format_tag( result_desc.data, mkldnn::memory::format_tag::goihw)) { // becomes a copy input_desc = result_desc; } else if ((input_format_is_nchw || mkldnn_utils::mkldnn_md_matches_format_tag( input_desc.data, mkldnn::memory::format_tag::nhwc)) && (mkldnn_utils::mkldnn_md_matches_format_tag( result_desc.data, mkldnn::memory::format_tag::OIhw4i16o4i) && // check if compensation is conv_s8s8(1U) result_desc.data.extra.flags & 0x1U)) { auto arg0_shape = args[0].get_shape(); input_desc = mkldnn::memory::desc( mkldnn::memory::dims(arg0_shape.begin(), arg0_shape.end()), mkldnn_utils::get_mkldnn_data_type(args[0].get_element_type()), mkldnn::memory::format_tag::oihw); } else if (input_format_is_nchw && input_desc.data.ndims == 4 && result_desc.data.ndims == 5 && node->get_users().size() == 1) { Shape weights_shape_groups; if (auto gconv = std::dynamic_pointer_cast<ngraph::op::GroupConvolution>( node->get_users()[0])) { weights_shape_groups = gconv->get_weights_dimensions(); } else if (auto gconvb = std::dynamic_pointer_cast<ngraph::op::GroupConvolutionBias>( node->get_users()[0])) { weights_shape_groups = gconvb->get_weights_dimensions(); } else { throw ngraph_error( "Incompatible input/output shape in ConvertLayout op"); } input_desc = mkldnn::memory::desc( mkldnn::memory::dims(weights_shape_groups.begin(), weights_shape_groups.end()), mkldnn_utils::get_mkldnn_data_type(args[0].get_element_type()), mkldnn::memory::format_tag::goihw); } // query scratchpad size mkldnn_emitter.query_scratchpad_reorder(input_desc, result_desc); // ConvertLayout needs 3 primitives: input, result, and reorder. index = mkldnn_emitter.reserve_primitive_space(3); deps = mkldnn_emitter.get_primitive_deps(index); CodeWriter writer; // Write memory descriptors to file std::vector<mkldnn::memory::desc> descs = {input_desc, result_desc}; mkldnn_emitter.reserve_descriptor_space(descs.size()); serialize_memory_descs(desc_file, descs, deps[0]); writer << "mkldnn::primitive_attr attr;\n"; writer << "attr.set_scratchpad_mode(mkldnn::scratchpad_mode::user);\n"; writer << "\n// build reorder primitive\n"; writer << "auto reorder_pd = " "mkldnn::reorder::primitive_desc(" "*cg_ctx->mkldnn_memories[" << std::to_string(deps[0]) << "]" ", *cg_ctx->mkldnn_memories[" << std::to_string(deps[1]) << "], attr);\n"; writer << "cg_ctx->mkldnn_primitives[" << std::to_string(index) << "] = new mkldnn::reorder(reorder_pd);\n"; writer << "cg_ctx->mkldnn_scratchpad_mds[" << std::to_string(index) << "] = new mkldnn::memory::desc(reorder_pd.scratchpad_desc());\n"; construct_string = writer.get_code(); } template <> void MKLDNNPrimitiveBuildPass::CONSTRUCT_PRIMITIVE_BUILD_STRING_DECL(ReluBackprop) { auto input_desc = mkldnn_utils::get_input_mkldnn_md(node, 0); auto delta_desc = mkldnn_utils::get_input_mkldnn_md(node, 1); auto result_desc = mkldnn_utils::get_output_mkldnn_md(node, 0); // query scratchpad size auto bwd_desc = mkldnn_emitter.get_relu_backward_desc(node); auto fwd_desc = mkldnn_emitter.get_relu_forward_desc(node); mkldnn_emitter.query_scratchpad_eltwise_backward(fwd_desc, bwd_desc); // ReluBackprop needs 4 primitives: input, delta, result, and eltwise_backward. index = mkldnn_emitter.reserve_primitive_space(4); deps = mkldnn_emitter.get_primitive_deps(index); CodeWriter writer; // Write memory descriptors to file std::vector<mkldnn::memory::desc> descs = {input_desc, delta_desc, result_desc}; auto desc_index = mkldnn_emitter.get_mkldnn_descriptors_size(); mkldnn_emitter.reserve_descriptor_space(descs.size()); serialize_memory_descs(desc_file, descs, deps[0]); writer << "const float negative_slope = 0.0f;\n"; writer << "auto fwd_desc = " "mkldnn::eltwise_forward::desc(mkldnn::prop_kind::forward, " "mkldnn::algorithm::eltwise_relu, " "*cg_ctx->mkldnn_descriptors[" << desc_index << "], negative_slope);\n"; writer << "auto bwd_desc = " "mkldnn::eltwise_backward::desc(mkldnn::algorithm::eltwise_relu, " "*cg_ctx->mkldnn_descriptors[" << desc_index + 2 << "], " "*cg_ctx->mkldnn_descriptors[" << desc_index << "], negative_slope);\n"; writer << "mkldnn::primitive_attr attr;\n"; writer << "attr.set_scratchpad_mode(mkldnn::scratchpad_mode::user);\n"; writer << "\n// create forward relu primitive descriptor\n"; writer << "auto relu_fwd_pd = mkldnn::eltwise_forward::primitive_desc(fwd_desc, " "cg_ctx->global_cpu_engine);\n"; writer << "\n// create backward relu primitive_descriptor\n"; writer << "auto relu_bwd_pd = " "mkldnn::eltwise_backward::primitive_desc(bwd_desc, attr, " "cg_ctx->global_cpu_engine, relu_fwd_pd);\n"; writer << "\n// build primitive\n"; writer << "cg_ctx->mkldnn_primitives[" << std::to_string(index) << "] = new mkldnn::eltwise_backward(relu_bwd_pd);\n"; writer << "cg_ctx->mkldnn_scratchpad_mds[" << std::to_string(index) << "] = new mkldnn::memory::desc(relu_bwd_pd.scratchpad_desc());\n"; construct_string = writer.get_code(); } template <> void MKLDNNPrimitiveBuildPass::CONSTRUCT_PRIMITIVE_BUILD_STRING_DECL(Relu) { auto input_desc = mkldnn_utils::get_input_mkldnn_md(node, 0); auto result_desc = mkldnn_utils::get_output_mkldnn_md(node, 0); // query scratchpad size auto relu_desc = mkldnn_emitter.get_relu_forward_desc(node); mkldnn_emitter.query_scratchpad_eltwise_forward(relu_desc); // Relu needs 3 primitives: input, result, and eltwise_forward. index = mkldnn_emitter.reserve_primitive_space(3); deps = mkldnn_emitter.get_primitive_deps(index); CodeWriter writer; // Write memory descriptors to file std::vector<mkldnn::memory::desc> descs = {input_desc, result_desc}; auto desc_index = mkldnn_emitter.get_mkldnn_descriptors_size(); mkldnn_emitter.reserve_descriptor_space(descs.size()); serialize_memory_descs(desc_file, descs, deps[0]); writer << "const float negative_slope = 0.0f;\n"; writer << "auto relu_desc = " "mkldnn::eltwise_forward::desc(mkldnn::prop_kind::forward, " "mkldnn::algorithm::eltwise_relu, " "*cg_ctx->mkldnn_descriptors[" << desc_index << "], negative_slope);\n"; writer << "mkldnn::primitive_attr attr;\n"; writer << "attr.set_scratchpad_mode(mkldnn::scratchpad_mode::user);\n"; writer << "\n// create relu primitive_descriptor\n"; writer << "auto relu_pd = " "mkldnn::eltwise_forward::primitive_desc(relu_desc, attr, " "cg_ctx->global_cpu_engine);\n"; writer << "\n// build primitive\n"; writer << "cg_ctx->mkldnn_primitives[" << std::to_string(index) << "] = new mkldnn::eltwise_forward(relu_pd);\n"; writer << "cg_ctx->mkldnn_scratchpad_mds[" << std::to_string(index) << "] = new mkldnn::memory::desc(relu_pd.scratchpad_desc());\n"; construct_string = writer.get_code(); } template <> void MKLDNNPrimitiveBuildPass::CONSTRUCT_PRIMITIVE_BUILD_STRING_DECL(CPULeakyRelu) { auto leaky_relu_node = static_cast<const ngraph::op::CPULeakyRelu*>(node); float alpha = leaky_relu_node->get_alpha(); auto input_desc = mkldnn_utils::get_input_mkldnn_md(node, 0); auto result_desc = mkldnn_utils::get_output_mkldnn_md(node, 0); // query scratchpad size auto leaky_relu_desc = mkldnn_emitter.get_leaky_relu_desc(node); mkldnn_emitter.query_scratchpad_eltwise_forward(leaky_relu_desc); // CPULeakyRelu needs 3 primitives: input, result, and eltwise_forward. index = mkldnn_emitter.reserve_primitive_space(3); deps = mkldnn_emitter.get_primitive_deps(index); CodeWriter writer; // Write memory descriptors to file std::vector<mkldnn::memory::desc> descs = {input_desc, result_desc}; auto desc_index = mkldnn_emitter.get_mkldnn_descriptors_size(); mkldnn_emitter.reserve_descriptor_space(descs.size()); serialize_memory_descs(desc_file, descs, deps[0]); writer << "const float alpha = " << alpha << ";\n"; writer << "auto relu_desc = " "mkldnn::eltwise_forward::desc(mkldnn::prop_kind::forward, " "mkldnn::algorithm::eltwise_relu, " "*cg_ctx->mkldnn_descriptors[" << desc_index << "], alpha, 0.0f);\n"; writer << "mkldnn::primitive_attr attr;\n"; writer << "attr.set_scratchpad_mode(mkldnn::scratchpad_mode::user);\n"; writer << "\n// create relu primitive_descriptor\n"; writer << "auto relu_pd = " "mkldnn::eltwise_forward::primitive_desc(relu_desc, attr, " "cg_ctx->global_cpu_engine);\n"; writer << "\n// build primitive\n"; writer << "cg_ctx->mkldnn_primitives[" << std::to_string(index) << "] = new mkldnn::eltwise_forward(relu_pd);\n"; writer << "cg_ctx->mkldnn_scratchpad_mds[" << std::to_string(index) << "] = new mkldnn::memory::desc(relu_pd.scratchpad_desc());\n"; construct_string = writer.get_code(); } template <> void MKLDNNPrimitiveBuildPass::CONSTRUCT_PRIMITIVE_BUILD_STRING_DECL(BoundedRelu) { auto bounded_relu_node = static_cast<const ngraph::op::BoundedRelu*>(node); float alpha = bounded_relu_node->get_alpha(); auto input_desc = mkldnn_utils::get_input_mkldnn_md(node, 0); auto result_desc = mkldnn_utils::get_output_mkldnn_md(node, 0); // query scratchpad size auto bounded_relu_desc = mkldnn_emitter.get_bounded_relu_desc(node); mkldnn_emitter.query_scratchpad_eltwise_forward(bounded_relu_desc); // BoundedRelu needs 3 primitives: input, result, and eltwise_forward. index = mkldnn_emitter.reserve_primitive_space(3); deps = mkldnn_emitter.get_primitive_deps(index); CodeWriter writer; // Write memory descriptors to file std::vector<mkldnn::memory::desc> descs = {input_desc, result_desc}; auto desc_index = mkldnn_emitter.get_mkldnn_descriptors_size(); mkldnn_emitter.reserve_descriptor_space(descs.size()); serialize_memory_descs(desc_file, descs, deps[0]); writer << "const float alpha = " << alpha << ";\n"; writer << "auto relu_desc = " "mkldnn::eltwise_forward::desc(mkldnn::prop_kind::forward, " "mkldnn::algorithm::eltwise_bounded_relu, " "*cg_ctx->mkldnn_descriptors[" << desc_index << "], alpha, 0.0f);\n"; writer << "mkldnn::primitive_attr attr;\n"; writer << "attr.set_scratchpad_mode(mkldnn::scratchpad_mode::user);\n"; writer << "\n// create relu primitive_descriptor\n"; writer << "auto relu_pd = " "mkldnn::eltwise_forward::primitive_desc(relu_desc, attr, " "cg_ctx->global_cpu_engine);\n"; writer << "\n// build primitive\n"; writer << "cg_ctx->mkldnn_primitives[" << std::to_string(index) << "] = new mkldnn::eltwise_forward(relu_pd);\n"; writer << "cg_ctx->mkldnn_scratchpad_mds[" << std::to_string(index) << "] = new mkldnn::memory::desc(relu_pd.scratchpad_desc());\n"; construct_string = writer.get_code(); } template <> void MKLDNNPrimitiveBuildPass::CONSTRUCT_PRIMITIVE_BUILD_STRING_DECL(Sigmoid) { auto input_desc = mkldnn_utils::get_input_mkldnn_md(node, 0); auto result_desc = mkldnn_utils::get_output_mkldnn_md(node, 0); // query scratchpad size auto sigmoid_desc = mkldnn_emitter.get_sigmoid_forward_desc(node, false); mkldnn_emitter.query_scratchpad_eltwise_forward(sigmoid_desc); // Sigmoid needs 3 primitives: input, result, and eltwise_forward. index = mkldnn_emitter.reserve_primitive_space(3); deps = mkldnn_emitter.get_primitive_deps(index); CodeWriter writer; // Write memory descriptors to file std::vector<mkldnn::memory::desc> descs = {input_desc, result_desc}; auto desc_index = mkldnn_emitter.get_mkldnn_descriptors_size(); mkldnn_emitter.reserve_descriptor_space(descs.size()); serialize_memory_descs(desc_file, descs, deps[0]); writer << "auto sigmoid_desc = " "mkldnn::eltwise_forward::desc(mkldnn::prop_kind::forward_training, " "mkldnn::algorithm::eltwise_logistic, " "*cg_ctx->mkldnn_descriptors[" << desc_index << "], 0, 0);\n"; writer << "mkldnn::primitive_attr attr;\n"; writer << "attr.set_scratchpad_mode(mkldnn::scratchpad_mode::user);\n"; writer << "\n// create sigmoid primitive_descriptor\n"; writer << "auto sigmoid_pd = " "mkldnn::eltwise_forward::primitive_desc(sigmoid_desc, attr, " "cg_ctx->global_cpu_engine);\n"; writer << "\n// build primitive\n"; writer << "cg_ctx->mkldnn_primitives[" << std::to_string(index) << "] = new mkldnn::eltwise_forward(sigmoid_pd);\n"; writer << "cg_ctx->mkldnn_scratchpad_mds[" << std::to_string(index) << "] = new mkldnn::memory::desc(sigmoid_pd.scratchpad_desc());\n"; construct_string = writer.get_code(); } template <> void MKLDNNPrimitiveBuildPass::CONSTRUCT_PRIMITIVE_BUILD_STRING_DECL(SigmoidBackprop) { auto input_desc = mkldnn_utils::get_input_mkldnn_md(node, 0); auto delta_desc = mkldnn_utils::get_input_mkldnn_md(node, 1); auto result_desc = mkldnn_utils::get_output_mkldnn_md(node, 0); // query scratchpad size auto fwd_desc = mkldnn_emitter.get_sigmoid_forward_desc(node, true); auto bwd_desc = mkldnn_emitter.get_sigmoid_backward_desc(node); mkldnn_emitter.query_scratchpad_eltwise_backward(fwd_desc, bwd_desc); // SigmoidBackprop needs 4 primitives: input, delta, result, and // eltwise_backward. index = mkldnn_emitter.reserve_primitive_space(4); deps = mkldnn_emitter.get_primitive_deps(index); CodeWriter writer; // Write memory descriptors to file std::vector<mkldnn::memory::desc> descs = {input_desc, delta_desc, result_desc}; auto desc_index = mkldnn_emitter.get_mkldnn_descriptors_size(); mkldnn_emitter.reserve_descriptor_space(descs.size()); serialize_memory_descs(desc_file, descs, deps[0]); writer << "auto fwd_desc = " "mkldnn::eltwise_forward::desc(mkldnn::prop_kind::forward, " "mkldnn::algorithm::eltwise_logistic, " "*cg_ctx->mkldnn_descriptors[" << desc_index << "], 0, 0);\n"; writer << "auto bwd_desc = " "mkldnn::eltwise_backward::desc(mkldnn::algorithm::eltwise_logistic, " "*cg_ctx->mkldnn_descriptors[" << desc_index + 1 << "], " "*cg_ctx->mkldnn_descriptors[" << desc_index << "], 0, 0);\n"; writer << "mkldnn::primitive_attr attr;\n"; writer << "attr.set_scratchpad_mode(mkldnn::scratchpad_mode::user);\n"; writer << "\n// create forward sigmoid primitive descriptor\n"; writer << "auto sigmoid_fwd_pd = " "mkldnn::eltwise_forward::primitive_desc(fwd_desc, " "cg_ctx->global_cpu_engine);\n"; writer << "\n// create backward sigmoid primitive_descriptor\n"; writer << "auto sigmoid_bwd_pd = " "mkldnn::eltwise_backward::primitive_desc(bwd_desc, attr, " "cg_ctx->global_cpu_engine, sigmoid_fwd_pd);\n"; writer << "\n// build primitive\n"; writer << "cg_ctx->mkldnn_primitives[" << std::to_string(index) << "] = new mkldnn::eltwise_backward(sigmoid_bwd_pd);\n"; writer << "cg_ctx->mkldnn_scratchpad_mds[" << std::to_string(index) << "] = new mkldnn::memory::desc(sigmoid_bwd_pd.scratchpad_desc());\n"; construct_string = writer.get_code(); } template <> void MKLDNNPrimitiveBuildPass::CONSTRUCT_PRIMITIVE_BUILD_STRING_DECL(Softmax) { auto softmax = static_cast<const ngraph::op::Softmax*>(node); if (softmax->get_axes().size() != 1) { throw ngraph_error("MKLDNN supports softmax only across single axis"); } int softmax_axis = static_cast<int>(*(softmax->get_axes().begin())); auto input_desc = mkldnn_utils::get_input_mkldnn_md(node, 0); auto result_desc = mkldnn_utils::get_output_mkldnn_md(node, 0); // query scratchpad size auto softmax_desc = mkldnn_emitter.get_softmax_forward_desc(node); mkldnn_emitter.query_scratchpad_softmax_forward(softmax_desc); // Softmax needs 3 primitives: input, result, and softmax_forward. index = mkldnn_emitter.reserve_primitive_space(3); deps = mkldnn_emitter.get_primitive_deps(index); CodeWriter writer; // Write memory descriptors to file std::vector<mkldnn::memory::desc> descs = {input_desc, result_desc}; auto desc_index = mkldnn_emitter.get_mkldnn_descriptors_size(); mkldnn_emitter.reserve_descriptor_space(descs.size()); serialize_memory_descs(desc_file, descs, deps[0]); writer << "auto softmax_desc = " "mkldnn::softmax_forward::desc(mkldnn::prop_kind::forward_scoring, " "*cg_ctx->mkldnn_descriptors[" << desc_index << "], " << softmax_axis << ");\n"; writer << "mkldnn::primitive_attr attr;\n"; writer << "attr.set_scratchpad_mode(mkldnn::scratchpad_mode::user);\n"; writer << "\n// create softmax primitive_descriptor\n"; writer << "auto softmax_pd = " "mkldnn::softmax_forward::primitive_desc(softmax_desc, attr, " "cg_ctx->global_cpu_engine);\n"; writer << "\n// build primitive\n"; writer << "cg_ctx->mkldnn_primitives[" << std::to_string(index) << "] = new mkldnn::softmax_forward(softmax_pd);\n"; writer << "cg_ctx->mkldnn_scratchpad_mds[" << std::to_string(index) << "] = new mkldnn::memory::desc(softmax_pd.scratchpad_desc());\n"; construct_string = writer.get_code(); } template <> void MKLDNNPrimitiveBuildPass::CONSTRUCT_PRIMITIVE_BUILD_STRING_DECL(Quantize) { auto input_desc = mkldnn_utils::get_input_mkldnn_md(node, 0); auto result_desc = mkldnn_utils::get_output_mkldnn_md(node, 0); // query scratchpad size mkldnn_emitter.query_scratchpad_reorder(input_desc, result_desc); // Quantize needs 3 primitives: input, result, and reorder. index = mkldnn_emitter.reserve_primitive_space(3); deps = mkldnn_emitter.get_primitive_deps(index); CodeWriter writer; // Write memory descriptors to file std::vector<mkldnn::memory::desc> descs = {input_desc, result_desc}; mkldnn_emitter.reserve_descriptor_space(descs.size()); serialize_memory_descs(desc_file, descs, deps[0]); writer << "mkldnn::primitive_attr attr;\n"; writer << "attr.set_output_scales(mask, dyn_scales);\n"; writer << "attr.set_scratchpad_mode(mkldnn::scratchpad_mode::user);\n"; writer << "\n// build reorder primitive\n"; writer << "auto reorder_pd = " "mkldnn::reorder::primitive_desc(" "*cg_ctx->mkldnn_memories[" << std::to_string(deps[0]) << "]" ", *cg_ctx->mkldnn_memories[" << std::to_string(deps[1]) << "], attr);\n"; writer << "cg_ctx->mkldnn_primitives[" << std::to_string(index) << "] = new mkldnn::reorder(reorder_pd);\n"; writer << "cg_ctx->mkldnn_scratchpad_mds[" << std::to_string(index) << "] = new mkldnn::memory::desc(reorder_pd.scratchpad_desc());\n"; construct_string = writer.get_code(); } template <> void MKLDNNPrimitiveBuildPass::CONSTRUCT_PRIMITIVE_BUILD_STRING_DECL(Dequantize) { auto input_desc = mkldnn_utils::get_input_mkldnn_md(node, 0); auto result_desc = mkldnn_utils::get_output_mkldnn_md(node, 0); // query scratchpad size mkldnn_emitter.query_scratchpad_reorder(input_desc, result_desc); // Dequantize needs 3 primitives: input, result, and reorder. index = mkldnn_emitter.reserve_primitive_space(3); deps = mkldnn_emitter.get_primitive_deps(index); CodeWriter writer; // Write memory descriptors to file std::vector<mkldnn::memory::desc> descs = {input_desc, result_desc}; mkldnn_emitter.reserve_descriptor_space(descs.size()); serialize_memory_descs(desc_file, descs, deps[0]); writer << "mkldnn::primitive_attr attr;\n"; writer << "attr.set_output_scales(mask, dyn_scales);\n"; writer << "attr.set_scratchpad_mode(mkldnn::scratchpad_mode::user);\n"; writer << "\n// build reorder primitive\n"; writer << "auto reorder_pd = " "mkldnn::reorder::primitive_desc(" "*cg_ctx->mkldnn_memories[" << std::to_string(deps[0]) << "]" ", *cg_ctx->mkldnn_memories[" << std::to_string(deps[1]) << "], attr);\n"; writer << "cg_ctx->mkldnn_primitives[" << std::to_string(index) << "] = new mkldnn::reorder(reorder_pd);\n"; writer << "cg_ctx->mkldnn_scratchpad_mds[" << std::to_string(index) << "] = new mkldnn::memory::desc(reorder_pd.scratchpad_desc());\n"; construct_string = writer.get_code(); } template <typename OP> void construct_primitive_build_string_inner_product( ngraph::runtime::cpu::MKLDNNEmitter& mkldnn_emitter, ngraph::Node* node, std::string& construct_string, std::vector<size_t>& deps, size_t& index, std::ofstream& desc_file) { auto has_bias = false; if (mkldnn_emitter.has_bias<OP>()) { has_bias = true; } auto data_desc = mkldnn_utils::get_input_mkldnn_md(node, 0); auto weights_desc = mkldnn_utils::get_input_mkldnn_md(node, 1); auto result_desc = mkldnn_utils::get_output_mkldnn_md(node, 0); // query scratchpad size auto ip_desc = mkldnn_emitter.get_inner_product_forward_desc<OP>(node); auto ip_attr = mkldnn_emitter.get_inner_product_forward_attr<OP>(node); mkldnn_emitter.query_scratchpad_ip_forward(ip_desc, ip_attr); if (has_bias) { // QuantizedDotBias needs 5 primitives: input, weights, bias, result, and // inner_product. index = mkldnn_emitter.reserve_primitive_space(5); } else { // QuantizedDot needs 4 primitives: input, weights, result, and // inner_product. index = mkldnn_emitter.reserve_primitive_space(4); } deps = mkldnn_emitter.get_primitive_deps(index); CodeWriter writer; // Write memory descriptors to file std::vector<mkldnn::memory::desc> descs = { data_desc, weights_desc, result_desc}; if (has_bias) { auto bias_desc = mkldnn_utils::get_input_mkldnn_md(node, 2); descs.push_back(bias_desc); } auto desc_index = mkldnn_emitter.get_mkldnn_descriptors_size(); mkldnn_emitter.reserve_descriptor_space(descs.size()); serialize_memory_descs(desc_file, descs, deps[0]); writer << "\n// build primitive descriptor\n"; writer << "auto ip_desc = " "mkldnn::inner_product_forward::desc(mkldnn::prop_kind::forward,\n" "*cg_ctx->mkldnn_descriptors[" << desc_index << "],\n" "*cg_ctx->mkldnn_descriptors[" << desc_index + 1 << "],\n"; if (has_bias) { writer << "*cg_ctx->mkldnn_descriptors[" << desc_index + 3 << "],\n"; } writer << "*cg_ctx->mkldnn_descriptors[" << desc_index + 2 << "]);\n"; writer << "\nmkldnn::post_ops ops;\n"; if (std::is_same<OP, ngraph::op::QuantizedDotBias>() && has_relu<ngraph::op::QuantizedDotBias>(node)) { writer << "const float ops_scale = 1.f;\n"; writer << "const float ops_alpha = -0.f; // relu negative slope\n"; writer << "const float ops_beta = 0.f;\n"; writer << "ops.append_eltwise(" "ops_scale, mkldnn::algorithm::eltwise_relu, ops_alpha, " "ops_beta);\n"; } writer << "mkldnn::primitive_attr ip_attr;\n"; writer << "ip_attr.set_post_ops(ops);\n"; writer << "ip_attr.set_scratchpad_mode(mkldnn::scratchpad_mode::user);\n"; if (mkldnn_emitter.is_quantized_inner_product<OP>()) { writer << "ip_attr.set_output_scales(mask, dyn_scales);\n"; } writer << "auto ip_pd = " "mkldnn::inner_product_forward::primitive_desc(ip_desc, ip_attr, " "cg_ctx->global_cpu_engine);\n"; writer << "\n// build primitive\n"; writer << "cg_ctx->mkldnn_primitives[" << std::to_string(index) << "] = new mkldnn::inner_product_forward(ip_pd);\n"; writer << "cg_ctx->mkldnn_scratchpad_mds[" << std::to_string(index) << "] = new mkldnn::memory::desc(ip_pd.scratchpad_desc());\n"; construct_string = writer.get_code(); } template <> void MKLDNNPrimitiveBuildPass::CONSTRUCT_PRIMITIVE_BUILD_STRING_DECL( QuantizedDotBias) { construct_primitive_build_string_inner_product<QuantizedDotBias>( mkldnn_emitter, node, construct_string, deps, index, desc_file); } template <> void MKLDNNPrimitiveBuildPass::CONSTRUCT_PRIMITIVE_BUILD_STRING_DECL(QuantizedMatmul) { construct_primitive_build_string_inner_product<QuantizedMatmul>( mkldnn_emitter, node, construct_string, deps, index, desc_file); } } } } } using namespace ngraph::runtime::cpu::pass; #define TI(x) std::type_index(typeid(x)) static const PrimitiveBuildStringConstructOpMap prim_build_string_construct_dispatcher{ {TI(Add), &MKLDNNPrimitiveBuildPass::construct_primitive_build_string<Add>}, {TI(BoundedRelu), &MKLDNNPrimitiveBuildPass::construct_primitive_build_string<BoundedRelu>}, {TI(Concat), &MKLDNNPrimitiveBuildPass::construct_primitive_build_string<Concat>}, {TI(runtime::cpu::op::ConvertLayout), &MKLDNNPrimitiveBuildPass::construct_primitive_build_string<runtime::cpu::op::ConvertLayout>}, {TI(BatchNormInference), &MKLDNNPrimitiveBuildPass::construct_primitive_build_string<BatchNormInference>}, {TI(BatchNormTraining), &MKLDNNPrimitiveBuildPass::construct_primitive_build_string<BatchNormTraining>}, {TI(BatchNormInferenceRelu), &MKLDNNPrimitiveBuildPass::construct_primitive_build_string<BatchNormInferenceRelu>}, {TI(BatchNormTrainingRelu), &MKLDNNPrimitiveBuildPass::construct_primitive_build_string<BatchNormTrainingRelu>}, {TI(BatchNormTrainingBackprop), &MKLDNNPrimitiveBuildPass::construct_primitive_build_string<BatchNormTrainingBackprop>}, {TI(CPULeakyRelu), &MKLDNNPrimitiveBuildPass::construct_primitive_build_string<CPULeakyRelu>}, {TI(LRN), &MKLDNNPrimitiveBuildPass::construct_primitive_build_string<LRN>}, {TI(Lstm), &MKLDNNPrimitiveBuildPass::construct_primitive_build_string<Lstm>}, {TI(Relu), &MKLDNNPrimitiveBuildPass::construct_primitive_build_string<Relu>}, {TI(ReluBackprop), &MKLDNNPrimitiveBuildPass::construct_primitive_build_string<ReluBackprop>}, {TI(Rnn), &MKLDNNPrimitiveBuildPass::construct_primitive_build_string<Rnn>}, {TI(Convolution), &MKLDNNPrimitiveBuildPass::construct_primitive_build_string<Convolution>}, {TI(ConvolutionRelu), &MKLDNNPrimitiveBuildPass::construct_primitive_build_string<ConvolutionRelu>}, {TI(ConvolutionBias), &MKLDNNPrimitiveBuildPass::construct_primitive_build_string<ConvolutionBias>}, {TI(ConvolutionBiasAdd), &MKLDNNPrimitiveBuildPass::construct_primitive_build_string<ConvolutionBiasAdd>}, {TI(ConvolutionAdd), &MKLDNNPrimitiveBuildPass::construct_primitive_build_string<ConvolutionAdd>}, {TI(GroupConvolution), &MKLDNNPrimitiveBuildPass::construct_primitive_build_string<GroupConvolution>}, {TI(GroupConvolutionBias), &MKLDNNPrimitiveBuildPass::construct_primitive_build_string<GroupConvolutionBias>}, {TI(QuantizedConvolution), &MKLDNNPrimitiveBuildPass::construct_primitive_build_string<QuantizedConvolution>}, {TI(QuantizedConvolutionRelu), &MKLDNNPrimitiveBuildPass::construct_primitive_build_string<QuantizedConvolutionRelu>}, {TI(QuantizedConvolutionBias), &MKLDNNPrimitiveBuildPass::construct_primitive_build_string<QuantizedConvolutionBias>}, {TI(QuantizedConvolutionBiasAdd), &MKLDNNPrimitiveBuildPass::construct_primitive_build_string<QuantizedConvolutionBiasAdd>}, {TI(QuantizedConvolutionBiasSignedAdd), &MKLDNNPrimitiveBuildPass::construct_primitive_build_string< QuantizedConvolutionBiasSignedAdd>}, {TI(ConvolutionBackpropData), &MKLDNNPrimitiveBuildPass::construct_primitive_build_string<ConvolutionBackpropData>}, {TI(ConvolutionBackpropFilters), &MKLDNNPrimitiveBuildPass::construct_primitive_build_string<ConvolutionBackpropFilters>}, {TI(ConvolutionBiasBackpropFiltersBias), &MKLDNNPrimitiveBuildPass::construct_primitive_build_string< ConvolutionBiasBackpropFiltersBias>}, {TI(DeconvolutionBias), &MKLDNNPrimitiveBuildPass::construct_primitive_build_string<DeconvolutionBias>}, {TI(MaxPoolWithIndices), &MKLDNNPrimitiveBuildPass::construct_primitive_build_string<MaxPoolWithIndices>}, {TI(MaxPoolWithIndicesBackprop), &MKLDNNPrimitiveBuildPass::construct_primitive_build_string<MaxPoolWithIndicesBackprop>}, {TI(Sigmoid), &MKLDNNPrimitiveBuildPass::construct_primitive_build_string<Sigmoid>}, {TI(SigmoidBackprop), &MKLDNNPrimitiveBuildPass::construct_primitive_build_string<SigmoidBackprop>}, {TI(Slice), &MKLDNNPrimitiveBuildPass::construct_primitive_build_string<Slice>}, {TI(Softmax), &MKLDNNPrimitiveBuildPass::construct_primitive_build_string<Softmax>}, {TI(MaxPool), &MKLDNNPrimitiveBuildPass::construct_primitive_build_string<MaxPool>}, {TI(AvgPool), &MKLDNNPrimitiveBuildPass::construct_primitive_build_string<AvgPool>}, {TI(AvgPoolBackprop), &MKLDNNPrimitiveBuildPass::construct_primitive_build_string<AvgPoolBackprop>}, {TI(MaxPoolBackprop), &MKLDNNPrimitiveBuildPass::construct_primitive_build_string<MaxPoolBackprop>}, {TI(Quantize), &MKLDNNPrimitiveBuildPass::construct_primitive_build_string<Quantize>}, {TI(Dequantize), &MKLDNNPrimitiveBuildPass::construct_primitive_build_string<Dequantize>}, {TI(QuantizedDotBias), &MKLDNNPrimitiveBuildPass::construct_primitive_build_string<QuantizedDotBias>}, {TI(QuantizedMatmul), &MKLDNNPrimitiveBuildPass::construct_primitive_build_string<QuantizedMatmul>}, }; bool MKLDNNPrimitiveBuildPass::run_on_call_graph(const std::list<std::shared_ptr<Node>>& nodes) { std::ofstream desc_file(m_desc_filename, std::ios::out | std::ios::binary); for (const auto& shp_node : nodes) { Node* node = shp_node.get(); if (mkldnn_utils::use_mkldnn_kernel(node)) { auto handler = prim_build_string_construct_dispatcher.find(TI(*node)); NGRAPH_CHECK(handler != prim_build_string_construct_dispatcher.end(), "Unsupported node '", node->description(), "' in MKLDNNPrimitiveBuildPass"); std::string construct_string; std::vector<size_t> deps; size_t index; handler->second(m_mkldnn_emitter, node, construct_string, deps, index, desc_file); m_node_primitive_string_deps_index_map[node] = std::tuple<std::string, std::vector<size_t>, size_t>(construct_string, deps, index); } } return false; } #undef TI
53.487179
100
0.506523
ilya-lavrenov
66f6e2462e0660c11baf8b4f65af67a7e6985775
6,010
cpp
C++
folly/io/async/EventHandler.cpp
lucyge/folly
d107498e71ab32e103c4fa7ca58ccc32990208b8
[ "Apache-2.0" ]
1
2020-02-23T14:14:53.000Z
2020-02-23T14:14:53.000Z
folly/io/async/EventHandler.cpp
lucyge/folly
d107498e71ab32e103c4fa7ca58ccc32990208b8
[ "Apache-2.0" ]
3
2016-07-19T00:19:58.000Z
2019-07-19T23:33:10.000Z
folly/io/async/EventHandler.cpp
cedexis/folly
284a4bf64203f8cc81918e0a91d726d45b3ee2ed
[ "Apache-2.0" ]
3
2019-06-24T12:03:46.000Z
2020-10-17T03:56:39.000Z
/* * Copyright 2004-present Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <folly/io/async/EventHandler.h> #include <folly/io/async/EventBase.h> #include <assert.h> namespace folly { EventHandler::EventHandler(EventBase* eventBase, int fd) { folly_event_set(&event_, fd, 0, &EventHandler::libeventCallback, this); if (eventBase != nullptr) { setEventBase(eventBase); } else { // Callers must set the EventBase and fd before using this timeout. // Set event_->ev_base to nullptr to ensure that this happens. // (otherwise libevent will initialize it to the "default" event_base) event_.ev_base = nullptr; eventBase_ = nullptr; } } EventHandler::~EventHandler() { unregisterHandler(); } bool EventHandler::registerImpl(uint16_t events, bool internal) { assert(event_.ev_base != nullptr); // We have to unregister the event before we can change the event flags if (isHandlerRegistered()) { // If the new events are the same are the same as the already registered // flags, we don't have to do anything. Just return. auto flags = event_ref_flags(&event_); if (events == event_.ev_events && static_cast<bool>(flags & EVLIST_INTERNAL) == internal) { return true; } event_del(&event_); } // Update the event flags // Unfortunately, event_set() resets the event_base, so we have to remember // it before hand, then pass it back into event_base_set() afterwards struct event_base* evb = event_.ev_base; event_set( &event_, event_.ev_fd, short(events), &EventHandler::libeventCallback, this); event_base_set(evb, &event_); // Set EVLIST_INTERNAL if this is an internal event if (internal) { event_ref_flags(&event_) |= EVLIST_INTERNAL; } // Add the event. // // Although libevent allows events to wait on both I/O and a timeout, // we intentionally don't allow an EventHandler to also use a timeout. // Callers must maintain a separate AsyncTimeout object if they want a // timeout. // // Otherwise, it is difficult to handle persistent events properly. (The I/O // event and timeout may both fire together the same time around the event // loop. Normally we would want to inform the caller of the I/O event first, // then the timeout. However, it is difficult to do this properly since the // I/O callback could delete the EventHandler.) Additionally, if a caller // uses the same struct event for both I/O and timeout, and they just want to // reschedule the timeout, libevent currently makes an epoll_ctl() call even // if the I/O event flags haven't changed. Using a separate event struct is // therefore slightly more efficient in this case (although it does take up // more space). if (event_add(&event_, nullptr) < 0) { LOG(ERROR) << "EventBase: failed to register event handler for fd " << event_.ev_fd << ": " << strerror(errno); // Call event_del() to make sure the event is completely uninstalled event_del(&event_); return false; } return true; } void EventHandler::unregisterHandler() { if (isHandlerRegistered()) { event_del(&event_); } } void EventHandler::attachEventBase(EventBase* eventBase) { // attachEventBase() may only be called on detached handlers assert(event_.ev_base == nullptr); assert(!isHandlerRegistered()); // This must be invoked from the EventBase's thread eventBase->dcheckIsInEventBaseThread(); setEventBase(eventBase); } void EventHandler::detachEventBase() { ensureNotRegistered(__func__); event_.ev_base = nullptr; } void EventHandler::changeHandlerFD(int fd) { ensureNotRegistered(__func__); // event_set() resets event_base.ev_base, so manually restore it afterwards struct event_base* evb = event_.ev_base; folly_event_set(&event_, fd, 0, &EventHandler::libeventCallback, this); event_.ev_base = evb; // don't use event_base_set(), since evb may be nullptr } void EventHandler::initHandler(EventBase* eventBase, int fd) { ensureNotRegistered(__func__); folly_event_set(&event_, fd, 0, &EventHandler::libeventCallback, this); setEventBase(eventBase); } void EventHandler::ensureNotRegistered(const char* fn) { // Neither the EventBase nor file descriptor may be changed while the // handler is registered. Treat it as a programmer bug and abort the program // if this requirement is violated. if (isHandlerRegistered()) { LOG(ERROR) << fn << " called on registered handler; aborting"; abort(); } } void EventHandler::libeventCallback(libevent_fd_t fd, short events, void* arg) { EventHandler* handler = reinterpret_cast<EventHandler*>(arg); assert(fd == handler->event_.ev_fd); (void)fd; // prevent unused variable warnings auto observer = handler->eventBase_->getExecutionObserver(); if (observer) { observer->starting(reinterpret_cast<uintptr_t>(handler)); } // this can't possibly fire if handler->eventBase_ is nullptr handler->eventBase_->bumpHandlingTime(); handler->handlerReady(uint16_t(events)); if (observer) { observer->stopped(reinterpret_cast<uintptr_t>(handler)); } } void EventHandler::setEventBase(EventBase* eventBase) { event_base_set(eventBase->getLibeventBase(), &event_); eventBase_ = eventBase; } bool EventHandler::isPending() const { if (event_ref_flags(&event_) & EVLIST_ACTIVE) { if (event_.ev_res & EV_READ) { return true; } } return false; } } // namespace folly
33.021978
80
0.714309
lucyge
66f87caac8919d0b19be2e829a3cdac4adec20d8
456
cpp
C++
1474/b.cpp
vladshablinsky/algo
815392708d00dc8d3159b4866599de64fa9d34fa
[ "MIT" ]
1
2021-10-24T00:46:37.000Z
2021-10-24T00:46:37.000Z
1474/b.cpp
vladshablinsky/algo
815392708d00dc8d3159b4866599de64fa9d34fa
[ "MIT" ]
null
null
null
1474/b.cpp
vladshablinsky/algo
815392708d00dc8d3159b4866599de64fa9d34fa
[ "MIT" ]
null
null
null
#include <iostream> #include <cstdio> using namespace std; bool is_prime(int x) { if (x < 4) { return true; } for (int i = 2; i * i <= x; ++i) { if (x % i == 0) { return false; } } return true; } void solve() { int d; cin >> d; int p = d + 1; for (; !is_prime(p); ++p) {} int q = p + d; for (; !is_prime(q); ++q) {} cout << p * q << "\n"; } int main() { int t; cin >> t; while (t--) { solve(); } }
13.028571
36
0.440789
vladshablinsky
66f9915a00eeb4a96dcde4dabd2ae4dcd16fa997
535
cpp
C++
1201-1300/1265-Print Immutable Linked List in Reverse/1265-Print Immutable Linked List in Reverse.cpp
jiadaizhao/LeetCode
4ddea0a532fe7c5d053ffbd6870174ec99fc2d60
[ "MIT" ]
49
2018-05-05T02:53:10.000Z
2022-03-30T12:08:09.000Z
1201-1300/1265-Print Immutable Linked List in Reverse/1265-Print Immutable Linked List in Reverse.cpp
jolly-fellow/LeetCode
ab20b3ec137ed05fad1edda1c30db04ab355486f
[ "MIT" ]
11
2017-12-15T22:31:44.000Z
2020-10-02T12:42:49.000Z
1201-1300/1265-Print Immutable Linked List in Reverse/1265-Print Immutable Linked List in Reverse.cpp
jolly-fellow/LeetCode
ab20b3ec137ed05fad1edda1c30db04ab355486f
[ "MIT" ]
28
2017-12-05T10:56:51.000Z
2022-01-26T18:18:27.000Z
/** * // This is the ImmutableListNode's API interface. * // You should not implement it, or speculate about its implementation. * class ImmutableListNode { * public: * void printValue(); // print the value of the node. * ImmutableListNode* getNext(); // return the next node. * }; */ class Solution { public: void printLinkedListInReverse(ImmutableListNode* head) { if (head == nullptr) { return; } printLinkedListInReverse(head->getNext()); head->printValue(); } };
25.47619
73
0.628037
jiadaizhao
66fa8463e3800378bb1d93248fa38aef09506b44
678
hpp
C++
include/mizuiro/color/set_percentage.hpp
cpreh/mizuiro
5ab15bde4e72e3a4978c034b8ff5700352932485
[ "BSL-1.0" ]
1
2015-08-22T04:19:39.000Z
2015-08-22T04:19:39.000Z
include/mizuiro/color/set_percentage.hpp
freundlich/mizuiro
5ab15bde4e72e3a4978c034b8ff5700352932485
[ "BSL-1.0" ]
null
null
null
include/mizuiro/color/set_percentage.hpp
freundlich/mizuiro
5ab15bde4e72e3a4978c034b8ff5700352932485
[ "BSL-1.0" ]
null
null
null
// Copyright Carl Philipp Reh 2009 - 2016. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #ifndef MIZUIRO_COLOR_SET_PERCENTAGE_HPP_INCLUDED #define MIZUIRO_COLOR_SET_PERCENTAGE_HPP_INCLUDED #include <mizuiro/color/denormalize.hpp> namespace mizuiro::color { template <typename Color, typename Channel, typename Float> void set_percentage(Color &_color, Channel const &_channel, Float const _value) { _color.set( _channel, mizuiro::color::denormalize<typename Color::format>(_color.format_store(), _channel, _value)); } } #endif
27.12
100
0.747788
cpreh
66fdff7856d661ac7599dbf154fde7b7a69021ce
70
cpp
C++
test/unit/main.unit.cpp
flisboac/gq
36f78933127ab4c04d0b2712fa1c07ae0184ecd4
[ "MIT" ]
null
null
null
test/unit/main.unit.cpp
flisboac/gq
36f78933127ab4c04d0b2712fa1c07ae0184ecd4
[ "MIT" ]
null
null
null
test/unit/main.unit.cpp
flisboac/gq
36f78933127ab4c04d0b2712fa1c07ae0184ecd4
[ "MIT" ]
null
null
null
#define CATCH_CONFIG_MAIN #include "catch.hpp" #include "gq.def.hpp"
14
25
0.757143
flisboac
0f01ea63876405201d766b47680d8d52affb1372
221
cpp
C++
Source/FSD/Private/AnimNotifyState_SpawnSkinnedMesh.cpp
trumank/DRG-Mods
2febc879f2ffe83498ac913c114d0e933427e93e
[ "MIT" ]
8
2021-07-10T20:06:05.000Z
2022-03-04T19:03:50.000Z
Source/FSD/Private/AnimNotifyState_SpawnSkinnedMesh.cpp
trumank/DRG-Mods
2febc879f2ffe83498ac913c114d0e933427e93e
[ "MIT" ]
9
2022-01-13T20:49:44.000Z
2022-03-27T22:56:48.000Z
Source/FSD/Private/AnimNotifyState_SpawnSkinnedMesh.cpp
trumank/DRG-Mods
2febc879f2ffe83498ac913c114d0e933427e93e
[ "MIT" ]
2
2021-07-10T20:05:42.000Z
2022-03-14T17:05:35.000Z
#include "AnimNotifyState_SpawnSkinnedMesh.h" UAnimNotifyState_SpawnSkinnedMesh::UAnimNotifyState_SpawnSkinnedMesh() { this->ItemCategory = EItemCategory::PrimaryWeapon; this->UseFirstPersonComponent = false; }
27.625
72
0.81448
trumank
0f01f375443ac72f1ded5f3302bf34d375767683
5,546
cpp
C++
src/core/tests/node_input_output.cpp
ryanloney/openvino-1
4e0a740eb3ee31062ba0df88fcf438564f67edb7
[ "Apache-2.0" ]
1,127
2018-10-15T14:36:58.000Z
2020-04-20T09:29:44.000Z
src/core/tests/node_input_output.cpp
ryanloney/openvino-1
4e0a740eb3ee31062ba0df88fcf438564f67edb7
[ "Apache-2.0" ]
439
2018-10-20T04:40:35.000Z
2020-04-19T05:56:25.000Z
src/core/tests/node_input_output.cpp
ryanloney/openvino-1
4e0a740eb3ee31062ba0df88fcf438564f67edb7
[ "Apache-2.0" ]
414
2018-10-17T05:53:46.000Z
2020-04-16T17:29:53.000Z
// Copyright (C) 2018-2022 Intel Corporation // SPDX-License-Identifier: Apache-2.0 // #include <memory> #include <sstream> #include <string> #include <vector> #include "gtest/gtest.h" #include "ngraph/ngraph.hpp" NGRAPH_SUPPRESS_DEPRECATED_START using namespace ngraph; using namespace std; TEST(node_input_output, input_create) { auto x = make_shared<op::Parameter>(element::f32, Shape{1, 2, 3, 4}); auto y = make_shared<op::Parameter>(element::f32, Shape{1, 2, 3, 4}); auto add = make_shared<op::v1::Add>(x, y); auto add_in_0 = add->input(0); auto add_in_1 = add->input(1); EXPECT_EQ(add_in_0.get_node(), add.get()); EXPECT_EQ(add_in_0.get_index(), 0); EXPECT_EQ(add_in_0.get_element_type(), element::f32); EXPECT_EQ(add_in_0.get_shape(), (Shape{1, 2, 3, 4})); EXPECT_TRUE(add_in_0.get_partial_shape().same_scheme(PartialShape{1, 2, 3, 4})); EXPECT_EQ(add_in_0.get_source_output(), Output<Node>(x, 0)); EXPECT_EQ(add_in_1.get_node(), add.get()); EXPECT_EQ(add_in_1.get_index(), 1); EXPECT_EQ(add_in_1.get_element_type(), element::f32); EXPECT_EQ(add_in_1.get_shape(), (Shape{1, 2, 3, 4})); EXPECT_TRUE(add_in_1.get_partial_shape().same_scheme(PartialShape{1, 2, 3, 4})); EXPECT_EQ(add_in_1.get_source_output(), Output<Node>(y, 0)); EXPECT_THROW(add->input(2), std::out_of_range); } TEST(node_input_output, input_create_const) { auto x = make_shared<op::Parameter>(element::f32, Shape{1, 2, 3, 4}); auto y = make_shared<op::Parameter>(element::f32, Shape{1, 2, 3, 4}); auto add = make_shared<const op::v1::Add>(x, y); auto add_in_0 = add->input(0); auto add_in_1 = add->input(1); EXPECT_EQ(add_in_0.get_node(), add.get()); EXPECT_EQ(add_in_0.get_index(), 0); EXPECT_EQ(add_in_0.get_element_type(), element::f32); EXPECT_EQ(add_in_0.get_shape(), (Shape{1, 2, 3, 4})); EXPECT_TRUE(add_in_0.get_partial_shape().same_scheme(PartialShape{1, 2, 3, 4})); EXPECT_EQ(add_in_0.get_source_output(), Output<Node>(x, 0)); EXPECT_EQ(add_in_1.get_node(), add.get()); EXPECT_EQ(add_in_1.get_index(), 1); EXPECT_EQ(add_in_1.get_element_type(), element::f32); EXPECT_EQ(add_in_1.get_shape(), (Shape{1, 2, 3, 4})); EXPECT_TRUE(add_in_1.get_partial_shape().same_scheme(PartialShape{1, 2, 3, 4})); EXPECT_EQ(add_in_1.get_source_output(), Output<Node>(y, 0)); EXPECT_THROW(add->input(2), std::out_of_range); } TEST(node_input_output, output_create) { auto x = make_shared<op::Parameter>(element::f32, Shape{1, 2, 3, 4}); auto y = make_shared<op::Parameter>(element::f32, Shape{1, 2, 3, 4}); auto add = make_shared<op::v1::Add>(x, y); auto add_out_0 = add->output(0); add_out_0.set_names({"a", "b"}); EXPECT_EQ(add_out_0.get_names(), std::unordered_set<std::string>({"a", "b"})); EXPECT_EQ(add_out_0.get_any_name(), "a"); add_out_0.add_names({"c", "d"}); EXPECT_EQ(add_out_0.get_names(), std::unordered_set<std::string>({"a", "b", "c", "d"})); EXPECT_EQ(add_out_0.get_any_name(), "a"); EXPECT_EQ(add_out_0.get_node(), add.get()); EXPECT_EQ(add_out_0.get_index(), 0); EXPECT_EQ(add_out_0.get_element_type(), element::f32); EXPECT_EQ(add_out_0.get_shape(), (Shape{1, 2, 3, 4})); EXPECT_TRUE(add_out_0.get_partial_shape().same_scheme(PartialShape{1, 2, 3, 4})); EXPECT_THROW(add->output(1), std::out_of_range); } TEST(node_input_output, output_create_const) { auto x = make_shared<op::Parameter>(element::f32, Shape{1, 2, 3, 4}); auto y = make_shared<op::Parameter>(element::f32, Shape{1, 2, 3, 4}); auto add = make_shared<const op::v1::Add>(x, y); auto add_out_0 = add->output(0); EXPECT_EQ(add_out_0.get_names().size(), 0); EXPECT_EQ(add_out_0.get_node(), add.get()); EXPECT_EQ(add_out_0.get_index(), 0); EXPECT_EQ(add_out_0.get_element_type(), element::f32); EXPECT_EQ(add_out_0.get_shape(), (Shape{1, 2, 3, 4})); EXPECT_TRUE(add_out_0.get_partial_shape().same_scheme(PartialShape{1, 2, 3, 4})); EXPECT_THROW(add->output(1), std::out_of_range); } TEST(node_input_output, output_rt_info) { auto x = make_shared<op::Parameter>(element::f32, Shape{1, 2, 3, 4}); auto y = make_shared<op::Parameter>(element::f32, Shape{1, 2, 3, 4}); auto add = make_shared<op::v1::Add>(x, y); auto add_const = make_shared<const op::v1::Add>(x, y); Output<Node> output = add->output(0); Output<const Node> output_const = add_const->output(0); auto& rt = output.get_rt_info(); rt["test"] = nullptr; EXPECT_TRUE(output.get_rt_info().count("test")); EXPECT_TRUE(output.get_tensor_ptr()->get_rt_info().count("test")); EXPECT_TRUE(output_const.get_rt_info().empty()); } TEST(node_input_output, input_set_argument) { auto x = make_shared<op::Parameter>(element::f32, Shape{1}); auto y = make_shared<op::Parameter>(element::f32, Shape{2}); auto z = make_shared<op::Parameter>(element::f32, Shape{3}); auto add = make_shared<op::v1::Add>(x, y); EXPECT_EQ(add->get_input_size(), 2); EXPECT_EQ(add->input(0).get_shape(), Shape{1}); EXPECT_EQ(add->input(1).get_shape(), Shape{2}); add->set_argument(1, z); EXPECT_EQ(add->get_input_size(), 2); EXPECT_EQ(add->input(0).get_shape(), Shape{1}); EXPECT_EQ(add->input(1).get_shape(), Shape{3}); add->set_arguments(NodeVector{z, x}); EXPECT_EQ(add->get_input_size(), 2); EXPECT_EQ(add->input(0).get_shape(), Shape{3}); EXPECT_EQ(add->input(1).get_shape(), Shape{1}); }
37.986301
92
0.66859
ryanloney
0f06310350d191e3bd6af9794e8cba37fd4a599f
29,784
cc
C++
src/interpreter.cc
unlink2/lasm
3cacf44c218854f402ce022b9e223f5671125dbe
[ "MIT" ]
1
2021-01-23T18:25:11.000Z
2021-01-23T18:25:11.000Z
src/interpreter.cc
unlink2/lasm
3cacf44c218854f402ce022b9e223f5671125dbe
[ "MIT" ]
null
null
null
src/interpreter.cc
unlink2/lasm
3cacf44c218854f402ce022b9e223f5671125dbe
[ "MIT" ]
null
null
null
#include "interpreter.h" #include <cstring> #include <cmath> #include <algorithm> #include "scanner.h" #include "parser.h" namespace lasm { Interpreter::Interpreter(BaseError &onError, BaseInstructionSet &is, InterpreterCallback *callback, FileReader *reader): onError(onError), instructions(is), callback(callback), globals(std::make_shared<Environment>(Environment())), environment(globals), globalLabels(std::make_shared<Environment>(Environment())), labels(globalLabels), reader(reader) { initGlobals(); } void Interpreter::initGlobals() { auto hi = LasmObject(CALLABLE_O, std::static_pointer_cast<Callable>(std::shared_ptr<NativeHi>(new NativeHi()))); globals->define("hi", hi); auto lo = LasmObject(CALLABLE_O, std::static_pointer_cast<Callable>(std::shared_ptr<NativeLo>(new NativeLo()))); globals->define("lo", lo); auto address = LasmObject(CALLABLE_O, std::static_pointer_cast<Callable>( std::shared_ptr<NativeAddress>(new NativeAddress()))); globals->define("_A", address); auto ord = LasmObject(CALLABLE_O, std::static_pointer_cast<Callable>( std::shared_ptr<NativeOrd>(new NativeOrd()))); globals->define("ord", ord); auto len = LasmObject(CALLABLE_O, std::static_pointer_cast<Callable>( std::shared_ptr<NativeLen>(new NativeLen()))); globals->define("len", len); auto setEnvName = LasmObject(CALLABLE_O, std::static_pointer_cast<Callable>( std::shared_ptr<NativeSetEnvName>(new NativeSetEnvName()))); globals->define("setScopeName", setEnvName); } std::vector<InstructionResult> Interpreter::interprete(std::vector<std::shared_ptr<Stmt>> stmts, bool abortOnError, int passes) { for (int i = 0; i < passes && (!onError.didError() || !abortOnError); i++) { execPass(stmts); } return code; } void Interpreter::execPass(std::vector<std::shared_ptr<Stmt>> stmts) { labels = globalLabels; environment = globals; environment->clear(); labelTable.clear(); labelTable.push_back(globalLabels); code.clear(); initGlobals(); address = 0; try { for (auto stmt : stmts) { execute(stmt); } } catch (LasmException &e) { onError.onError(e.getType(), e.getToken(), &e); } pass++; } void Interpreter::execute(std::shared_ptr<Stmt> stmt) { stmt->accept(this); } LasmObject Interpreter::evaluate(std::shared_ptr<Expr> expr) { return std::any_cast<LasmObject>(expr->accept(this)); } std::any Interpreter::visitBinary(BinaryExpr *expr) { auto left = evaluate(expr->left); auto right = evaluate(expr->right); switch (expr->op->getType()) { case MINUS: // first number decides auto-cast if (left.isNumber() && right.isScalar()) { return LasmObject(NUMBER_O, left.toNumber() - right.toNumber()); } else if (left.isReal() && right.isScalar()) { return LasmObject(REAL_O, left.toReal() - right.toReal()); } else { throw LasmTypeError(std::vector<ObjectType> {NUMBER_O, REAL_O}, left.getType(), expr->op); } break; case SLASH: if (left.isNumber() && right.isScalar()) { // integer division by 0 is not valid! if (right.toNumber() == 0) { throw LasmDivisionByZero(expr->op); } return LasmObject(NUMBER_O, left.toNumber() / right.toNumber()); } else if (left.isReal() && right.isScalar()) { return LasmObject(REAL_O, left.toReal() / right.toReal()); } else { throw LasmTypeError(std::vector<ObjectType> {NUMBER_O, REAL_O}, left.getType(), expr->op); } break; case PERCENT: if (left.isNumber() && right.isNumber()) { if (right.toNumber() == 0) { throw LasmDivisionByZero(expr->op); } return LasmObject(NUMBER_O, left.toNumber() % right.toNumber()); } else { throw LasmTypeError(std::vector<ObjectType> {NUMBER_O}, left.getType(), expr->op); } case STAR: // first number decides auto-cast if (left.isNumber() && right.isScalar()) { return LasmObject(NUMBER_O, left.toNumber() * right.toNumber()); } else if (left.isReal() && right.isScalar()) { return LasmObject(REAL_O, left.toReal() * right.toReal()); } else { throw LasmTypeError(std::vector<ObjectType> {NUMBER_O, REAL_O}, left.getType(), expr->op); } break; case PLUS: // first number decides auto-cast if (left.isNumber() && right.isScalar()) { return LasmObject(NUMBER_O, left.toNumber() + right.toNumber()); } else if (left.isReal() && right.isScalar()) { return LasmObject(REAL_O, left.toReal() + right.toReal()); } else if (left.isString() && right.isString()) { // string cat return LasmObject(STRING_O, left.toString() + right.toString()); } else { throw LasmTypeError(std::vector<ObjectType> {NUMBER_O, REAL_O, STRING_O}, left.getType(), expr->op); } break; // comparison case GREATER: if (left.isNumber() && right.isScalar()) { return LasmObject(BOOLEAN_O, left.toNumber() > right.toNumber()); } else if (right.isReal() && right.isScalar()) { return LasmObject(BOOLEAN_O, left.toReal() > right.toReal()); } else { throw LasmTypeError(std::vector<ObjectType> {NUMBER_O, REAL_O}, left.getType(), expr->op); } case LESS: if (left.isNumber() && right.isScalar()) { return LasmObject(BOOLEAN_O, left.toNumber() < right.toNumber()); } else if (left.isReal() && right.isScalar()) { return LasmObject(BOOLEAN_O, left.toReal() < right.toReal()); } else { throw LasmTypeError(std::vector<ObjectType> {NUMBER_O, REAL_O}, left.getType(), expr->op); } case GREATER_EQUAL: if (left.isNumber() && right.isScalar()) { return LasmObject(BOOLEAN_O, left.toNumber() >= right.toNumber()); } else if (left.isReal() && right.isScalar()) { return LasmObject(BOOLEAN_O, left.toReal() >= right.toReal()); } else { throw LasmTypeError(std::vector<ObjectType> {NUMBER_O, REAL_O}, left.getType(), expr->op); } case LESS_EQUAL: if (left.isNumber() && left.isScalar()) { return LasmObject(BOOLEAN_O, left.toNumber() <= right.toNumber()); } else if (left.isReal() && left.isScalar()) { return LasmObject(BOOLEAN_O, left.toReal() <= right.toReal()); } else { throw LasmTypeError(std::vector<ObjectType> {NUMBER_O, REAL_O}, left.getType(), expr->op); } case BANG_EQUAL: return LasmObject(BOOLEAN_O, !left.isEqual(right)); case EQUAL_EQUAL: return LasmObject(BOOLEAN_O, left.isEqual(right)); case BIN_AND: if (right.isScalar() && left.isScalar()) { return LasmObject(NUMBER_O, left.toNumber() & right.toNumber()); } else { throw LasmTypeError(std::vector<ObjectType> {NUMBER_O, REAL_O}, right.getType(), expr->op); } case BIN_OR: if (right.isScalar() && left.isScalar()) { return LasmObject(NUMBER_O, left.toNumber() | right.toNumber()); } else { throw LasmTypeError(std::vector<ObjectType> {NUMBER_O, REAL_O}, right.getType(), expr->op); } case BIN_XOR: if (right.isScalar() && left.isScalar()) { return LasmObject(NUMBER_O, left.toNumber() ^ right.toNumber()); } else { throw LasmTypeError(std::vector<ObjectType> {NUMBER_O, REAL_O}, right.getType(), expr->op); } case BIN_SHIFT_LEFT: if (right.isScalar() && left.isScalar()) { return LasmObject(NUMBER_O, left.toNumber() << right.toNumber()); } else { throw LasmTypeError(std::vector<ObjectType> {NUMBER_O, REAL_O}, right.getType(), expr->op); } case BIN_SHIFT_RIGHT: if (right.isScalar() && left.isScalar()) { return LasmObject(NUMBER_O, left.toNumber() >> right.toNumber()); } else { throw LasmTypeError(std::vector<ObjectType> {NUMBER_O, REAL_O}, right.getType(), expr->op); } default: break; } // should be unreacbable return LasmObject(NIL_O, nullptr); } std::any Interpreter::visitUnary(UnaryExpr *expr) { auto right = evaluate(expr->right); auto sign = -1; switch (expr->op->getType()) { case PLUS: sign = 1; case MINUS: if (right.isReal()) { return LasmObject(REAL_O, sign * right.toReal()); } else if (right.isNumber()) { return LasmObject(NUMBER_O, sign * right.toNumber()); } else { // type error! throw LasmTypeError(std::vector<ObjectType> {NUMBER_O, REAL_O}, right.getType(), expr->op); } break; case BANG: return LasmObject(BOOLEAN_O, !right.isTruthy()); case BIN_NOT: if (right.isScalar()) { return LasmObject(NUMBER_O, ~right.toNumber()); } else { throw LasmTypeError(std::vector<ObjectType> {NUMBER_O, REAL_O}, right.getType(), expr->op); } default: break; } // should be unreacbable return LasmObject(NIL_O, nullptr); } std::any Interpreter::visitLiteral(LiteralExpr *expr) { return expr->value; } std::any Interpreter::visitGrouping(GroupingExpr *expr) { return evaluate(expr->expression); } std::any Interpreter::visitVariable(VariableExpr *expr) { // label environment. used for n+1th pass // only set if it has not already been assigned bool wasFirstPass = false; if (!expr->getEnv(address).get() && pass == 0) { wasFirstPass = true; // if so do not throw expr->setEnv(address, labels); } try { // TODO can we avoid copy constructor? does it matter? return LasmObject(environment->get(expr->name).get()); } catch (LasmUndefinedReference &e) { // attempt getting label by name, but only on second+ pass if (expr->getEnv(address).get() && !wasFirstPass) { return LasmObject(expr->getEnv(address)->get(expr->name).get()); } else if (!wasFirstPass) { throw e; // only re-throw on second+ pass } } return LasmObject(NIL_O, 0); } std::any Interpreter::visitAssign(AssignExpr *expr) { auto value = evaluate(expr->value); environment->assign(expr->name, value); return value; } std::any Interpreter::visitLogical(LogicalExpr *expr) { auto left = evaluate(expr->left); if (expr->op->getType() == OR) { if (left.isTruthy()) { return left; } } else { if (!left.isTruthy()) { return left; } } return evaluate(expr->right); } std::any Interpreter::visitCall(CallExpr *expr) { auto callee = evaluate(expr->callee); std::vector<LasmObject> arguments; for (auto arg : expr->arguments) { arguments.push_back(evaluate(arg)); } if (callee.getType() != CALLABLE_O) { throw LasmNotCallable(expr->paren); } auto function = callee.toCallable(); if (function->getArity() != arguments.size()) { throw LasmArityError(expr->paren); } return function->call(this, arguments, expr); } std::any Interpreter::visitList(ListExpr *expr) { auto values = std::make_shared<std::vector<LasmObject>>(std::vector<LasmObject>()); // evaluate all array members for (auto init : expr->list) { values->push_back(evaluate(init)); } return LasmObject(LIST_O, values); } std::any Interpreter::visitIndex(IndexExpr *expr) { auto value = evaluate(expr->object); auto index = evaluate(expr->index); if (!index.isNumber()) { throw LasmTypeError(std::vector<ObjectType> {NUMBER_O}, index.getType(), expr->token); } LasmObject result(NIL_O, nullptr); if (value.isString()) { if ((unsigned long)value.toString().length() < (unsigned long)index.toNumber()) { throw LasmException(INDEX_OUT_OF_BOUNDS, expr->token); } return LasmObject(NUMBER_O, (lasmNumber)value.toString().at(index.toNumber())); } else if (value.isList()) { if ((unsigned long)value.toList()->size() < (unsigned long)index.toNumber()) { throw LasmException(INDEX_OUT_OF_BOUNDS, expr->token); } return value.toList()->at(index.toNumber()); } else { throw LasmTypeError(std::vector<ObjectType> {STRING_O, LIST_O}, value.getType(), expr->token); } return result; } std::any Interpreter::visitIndexAssign(IndexAssignExpr *expr) { auto value = evaluate(expr->value); auto index = evaluate(expr->index); auto object = evaluate(expr->object); if (!index.isNumber()) { throw LasmTypeError(std::vector<ObjectType> {NUMBER_O}, index.getType(), expr->token); } if (object.isList()) { if ((unsigned long)object.toList()->size() < (unsigned long)index.toNumber()) { throw LasmException(INDEX_OUT_OF_BOUNDS, expr->token); } object.toList()->at(index.toNumber()) = value; return value; } else { throw LasmTypeError(std::vector<ObjectType> {STRING_O, LIST_O}, object.getType(), expr->token); } return value; } std::any Interpreter::visitExpression(ExpressionStmt *stmt) { auto obj = std::any_cast<LasmObject>(evaluate(stmt->expr)); if (callback) { callback->onStatementExecuted(&obj); } return std::any(); } std::any Interpreter::visitLet(LetStmt *stmt) { LasmObject value = LasmObject(NIL_O, nullptr); if (stmt->init.get() != nullptr) { value = evaluate(stmt->init); } environment->define(stmt->name->getLexeme(), value); return std::any(); } std::any Interpreter::visitBlock(BlockStmt *stmt) { executeBlock(stmt->statements, std::make_shared<Environment>(Environment(environment))); return std::any(); } void Interpreter::executeBlock(std::vector<std::shared_ptr<Stmt>> statements, std::shared_ptr<Environment> environment, std::shared_ptr<Environment> labels) { if (!labels.get()) { labels = std::make_shared<Environment>(Environment(this->labels)); } labelTable.push_back(labels); auto previous = this->environment; auto previousLabels = this->labels; this->environment = environment; this->labels = labels; for (auto statement : statements) { execute(statement); } this->environment = previous; this->labels = previousLabels; } std::any Interpreter::visitIf(IfStmt *stmt) { if (evaluate(stmt->condition).isTruthy()) { execute(stmt->thenBranch); } else if (stmt->elseBranch.get()) { execute(stmt->elseBranch); } return std::any(); } std::any Interpreter::visitWhile(WhileStmt *stmt) { auto previousLabels = labels; while (evaluate(stmt->condition).isTruthy()) { execute(stmt->body); } labels = previousLabels; return std::any(); } std::any Interpreter::visitFunction(FunctionStmt *stmt) { auto fn = std::make_shared<LasmFunction>(LasmFunction(stmt)); LasmObject obj(CALLABLE_O, std::static_pointer_cast<Callable>(fn)); environment->define(stmt->name->getLexeme(), obj); return std::any(); } std::any Interpreter::visitReturn(ReturnStmt *stmt) { LasmObject value(NIL_O, nullptr); if (stmt->value.get()) { value = evaluate(stmt->value); } // TODO this is kinda ugly but functional throw Return(value); } std::any Interpreter::visitInstruction(InstructionStmt *stmt) { // TODO catch unresolved labels, return a deep clone of the current environment // and set unresolved flag along with the expression. // after assembly ends do a second pass and attempt to // resolve again onInstructionResult(instructions.generate(this, stmt->info, stmt)); return std::any(); } std::any Interpreter::visitDirective(DirectiveStmt *stmt) { return stmt->directive->execute(this, stmt); } std::any Interpreter::visitAlign(AlignStmt *stmt) { auto alignTo = evaluate(stmt->alignTo); auto fillValue = evaluate(stmt->fillValue); if (!alignTo.isScalar()) { throw LasmTypeError(std::vector<ObjectType> {NUMBER_O, REAL_O}, alignTo.getType(), stmt->token); } else if (!fillValue.isScalar()) { throw LasmTypeError(std::vector<ObjectType> {NUMBER_O, REAL_O}, fillValue.getType(), stmt->token); } else if (fillValue.toNumber() > 0xFF) { throw LasmException(VALUE_OUT_OF_RANGE, stmt->token); } unsigned long size = 0; // fill until address % fillValue == 0 while ((address % (unsigned long)alignTo.toNumber()) != 0) { address++; size++; } // make byte array with fill value as instruction result std::shared_ptr<char[]> data(new char[size]); memset(data.get(), fillValue.toNumber(), size); onInstructionResult(InstructionResult(data, size, getAddress()-size, stmt->token)); return std::any(); } std::any Interpreter::visitFill(FillStmt *stmt) { auto fillTo = evaluate(stmt->fillAddress); auto fillValue = evaluate(stmt->fillValue); if (!fillTo.isScalar()) { throw LasmTypeError(std::vector<ObjectType> {NUMBER_O, REAL_O}, fillTo.getType(), stmt->token); } else if (!fillValue.isScalar()) { throw LasmTypeError(std::vector<ObjectType> {NUMBER_O, REAL_O}, fillValue.getType(), stmt->token); } else if (fillValue.toNumber() > 0xFF || (unsigned long)fillTo.toNumber() <= address) { throw LasmException(VALUE_OUT_OF_RANGE, stmt->token); } // make data of address-fillTo unsigned long size = (unsigned long)fillTo.toNumber() - address; std::shared_ptr<char[]> data(new char[size]); memset(data.get(), fillValue.toNumber(), size); address += size; onInstructionResult(InstructionResult(data, size, getAddress()-size, stmt->token)); return std::any(); } std::any Interpreter::visitOrg(OrgStmt *stmt) { auto address = evaluate(stmt->address); if (!address.isScalar()) { throw LasmTypeError(std::vector<ObjectType> {NUMBER_O, REAL_O}, address.getType(), stmt->token); } this->address = address.toNumber(); return std::any(); } /** * uncomment relevant line at compile time */ #define NATIVE_BO LITTLE // #define NATIVE_BO BIG // TODO test endianess std::any Interpreter::visitDefineByte(DefineByteStmt *stmt) { // loop all exprs. each entry gets a node as code for (auto value : stmt->values) { auto evaluated = evaluate(value); std::shared_ptr<char[]> data; if (evaluated.isString()) { data = std::shared_ptr<char[]>(new char[evaluated.toString().length()+1]); // for string we ignore endianess anyway strncpy(data.get(), evaluated.toString().c_str(), evaluated.toString().length()+1); onInstructionResult(InstructionResult(data, evaluated.toString().length()+1, getAddress(), stmt->token)); address += evaluated.toString().length()+1; } else if (evaluated.isScalar() || evaluated.isBool()) { data = std::shared_ptr<char[]>(new char[stmt->size]); switch (stmt->size) { case 1: { char value = 0; if (evaluated.isBool()) { value = evaluated.toBool(); } else if (evaluated.isNumber()) { value = evaluated.toNumber(); } else { throw LasmException(VALUE_OUT_OF_RANGE, stmt->token); } memcpy(data.get(), &value, stmt->size); break; } case 2: { short value = 0; if (evaluated.isBool()) { value = evaluated.toBool(); } else if (evaluated.isNumber()) { value = evaluated.toNumber(); } else { throw LasmException(VALUE_OUT_OF_RANGE, stmt->token); } memcpy(data.get(), &value, stmt->size); break; } case 4: { int value = 0; if (evaluated.isBool()) { value = evaluated.toBool(); } else if (evaluated.isNumber()) { value = evaluated.toNumber(); } else if (evaluated.isReal()) { float evalFloat = evaluated.toReal(); memcpy(&value, &evalFloat, stmt->size); } else { throw LasmException(VALUE_OUT_OF_RANGE, stmt->token); } memcpy(data.get(), &value, stmt->size); break; } case 8: { long value = 0; if (evaluated.isBool()) { value = evaluated.toBool(); } else if (evaluated.isNumber()) { value = evaluated.toNumber(); } else if (evaluated.isReal()) { double evalFloat = evaluated.toReal(); memcpy(&value, &evalFloat, stmt->size); } else { throw LasmException(VALUE_OUT_OF_RANGE, stmt->token); } memcpy(data.get(), &value, stmt->size); break; } default: throw LasmException(VALUE_OUT_OF_RANGE, stmt->token); } // is the required endianess the same as the native endianess? // TODO test this! maybe on a powerpc machine? if (stmt->endianess != getNativeByteOrder()) { // swap time! std::shared_ptr<char[]> swapped(new char[stmt->size]); std::reverse_copy(data.get(), data.get()+stmt->size, swapped.get()); data = swapped; } onInstructionResult(InstructionResult(data, stmt->size, getAddress(), stmt->token)); address += stmt->size; } else { throw LasmTypeError(std::vector<ObjectType> {NUMBER_O, REAL_O, BOOLEAN_O, STRING_O}, evaluated.getType(), stmt->token); } } return std::any(); } std::any Interpreter::visitBss(BssStmt *stmt) { auto startAddress = evaluate(stmt->startAddress); if (!startAddress.isNumber()) { throw LasmTypeError(std::vector<ObjectType> {NUMBER_O}, startAddress.getType(), stmt->token); } // define every value for (auto declaration : stmt->declarations) { auto value = evaluate(declaration->init); if (!value.isNumber()) { throw LasmTypeError(std::vector<ObjectType> {NUMBER_O}, value.getType(), declaration->name); } // add start address to it environment->define(declaration->name->getLexeme(), startAddress); startAddress = LasmObject(NUMBER_O, value.toNumber() + startAddress.toNumber()); } return std::any(); } std::any Interpreter::visitLabel(LabelStmt *stmt) { LasmObject obj(NUMBER_O, (lasmNumber)address); labels->define(stmt->name->getLexeme().substr(0, stmt->name->getLexeme().length()-1), obj); return std::any(); } std::any Interpreter::visitIncbin(IncbinStmt *stmt) { if (!reader) { return std::any(); } // either read file using the included file reader // or just use the already buffered value if (!stmt->data.get()) { auto path = evaluate(stmt->filePath); if (path.getType() != STRING_O) { throw LasmTypeError(std::vector<ObjectType> {STRING_O}, path.getType(), stmt->token); } auto stream = reader->openFile(path.toString()); unsigned long size = 0; auto data = reader->readFullFile(stream, &size); reader->closeFile(stream); stmt->data = data; stmt->size = size; } // return result onInstructionResult(InstructionResult(stmt->data, stmt->size, getAddress(), stmt->token)); address += stmt->size; return std::any(); } std::any Interpreter::visitInclude(IncludeStmt *stmt) { if (!reader) { return std::any(); } // either read file and then interprete or just interprete right now! if (!stmt->wasparsed) { auto path = evaluate(stmt->filePath); if (path.getType() != STRING_O) { throw LasmTypeError(std::vector<ObjectType> {STRING_O}, path.getType(), stmt->token); } stmt->wasparsed = true; auto previousPath = reader->getDir(); reader->changeDir(path.toString(), true); auto stream = reader->openFile(path.toString()); auto source = std::string(reader->readFullFile(stream).get()); reader->closeFile(stream); Scanner scanner(onError, instructions, source, path.toString()); auto tokens = scanner.scanTokens(); if (onError.didError()) { return std::any(); } Parser parser(onError, tokens, instructions); auto ast = parser.parse(); if (onError.didError()) { return std::any(); } stmt->stmts = ast; reader->changeDir(previousPath); } try { for (auto stmt : stmt->stmts) { execute(stmt); } } catch (LasmException &e) { onError.onError(e.getType(), e.getToken(), &e); } return std::any(); } void Interpreter::onInstructionResult(InstructionResult result) { if (pass != 0) { code.push_back(result); } } Endianess Interpreter::getNativeByteOrder() { // check endianess const unsigned int x = 0x12345678; if (*((char*)&x) == 0x78) { // little endian return LITTLE; } // big endian return BIG; } }
39.818182
121
0.522898
unlink2
0f07995cbfb34d3844b62df4fc07e0cc78a1eec9
144
hpp
C++
src/geom/ex.hpp
orsonbraines/apytuuengine
b2a02e5f979bea0a3a75ad40f43d8d0c56bfe2a0
[ "MIT" ]
null
null
null
src/geom/ex.hpp
orsonbraines/apytuuengine
b2a02e5f979bea0a3a75ad40f43d8d0c56bfe2a0
[ "MIT" ]
null
null
null
src/geom/ex.hpp
orsonbraines/apytuuengine
b2a02e5f979bea0a3a75ad40f43d8d0c56bfe2a0
[ "MIT" ]
null
null
null
#ifndef APYTUU_ENGINE_GEOM_EX #define APYTUU_ENGINE_GEOM_EX namespace apytuu_engine_geom{ class GeomException{ public: private: }; } #endif
14.4
29
0.8125
orsonbraines
0f079c3646479b0dea32d7a353a13495ddcccbe6
2,215
cpp
C++
implementations/ugene/src/plugins_3rdparty/umuscle/src/muscle/treefrommsa.cpp
r-barnes/sw_comparison
1ac2c9cc10a32badd6b8fb1e96516c97f7800176
[ "BSD-Source-Code" ]
null
null
null
implementations/ugene/src/plugins_3rdparty/umuscle/src/muscle/treefrommsa.cpp
r-barnes/sw_comparison
1ac2c9cc10a32badd6b8fb1e96516c97f7800176
[ "BSD-Source-Code" ]
null
null
null
implementations/ugene/src/plugins_3rdparty/umuscle/src/muscle/treefrommsa.cpp
r-barnes/sw_comparison
1ac2c9cc10a32badd6b8fb1e96516c97f7800176
[ "BSD-Source-Code" ]
null
null
null
#include "muscle.h" #include "msa.h" #include "tree.h" #include "clust.h" #include "clustsetmsa.h" #include "distcalc.h" static void SaveMSADist(const MSA &msa, MSADist &d, const char *FileName) { FILE *f = fopen(FileName, "w"); if (f == 0) Quit("Cannot create %s", FileName); unsigned n = msa.GetSeqCount(); for (unsigned i = 0; i < n; ++i) { fprintf(f, "%10.10s ", msa.GetSeqName(i)); for (unsigned j = 0; j < n; ++j) fprintf(f, " %9g", d.ComputeDist(msa, i, j)); fprintf(f, "\n"); } fclose(f); } static void TreeFromMSA_NJ(const MSA &msa, Tree &tree, CLUSTER Cluster, DISTANCE Distance, const char *SaveFileName) { MSADist MD(Distance); ClustSetMSA Set(msa, MD); if (SaveFileName != 0) SaveMSADist(msa, MD, SaveFileName); Clust C; C.Create(Set, Cluster); tree.FromClust(C); } static void SaveDC(const DistCalcMSA &DC, const char *FileName) { FILE *f = fopen(FileName, "w"); if (f == 0) Quit("Cannot create %s", FileName); unsigned n = DC.GetCount(); fprintf(f, "%u\n", n); float *Dist = new float[n]; for (unsigned i = 0; i < n; ++i) { fprintf(f, "%10.10s ", DC.GetName(i)); DC.CalcDistRange(i, Dist); for (unsigned j = 0; j < i; ++j) fprintf(f, " %9g", Dist[j]); fprintf(f, "\n"); } fclose(f); } static void TreeFromMSA_UPGMA(const MSA &msa, Tree &tree, CLUSTER Cluster, DISTANCE Distance, const char *SaveFileName) { LINKAGE Linkage = LINKAGE_Undefined; switch (Cluster) { case CLUSTER_UPGMA: Linkage = LINKAGE_Avg; break; case CLUSTER_UPGMAMin: Linkage = LINKAGE_Min; break; case CLUSTER_UPGMAMax: Linkage = LINKAGE_Max; break; case CLUSTER_UPGMB: Linkage = LINKAGE_Biased; break; default: Quit("TreeFromMSA_UPGMA, CLUSTER_%u not supported", Cluster); } DistCalcMSA DC; DC.Init(msa, Distance); if (SaveFileName != 0) SaveDC(DC, SaveFileName); UPGMA2(DC, tree, Linkage); } void TreeFromMSA(const MSA &msa, Tree &tree, CLUSTER Cluster, DISTANCE Distance, ROOT Root, const char *SaveFileName) { if (CLUSTER_NeighborJoining == Cluster) TreeFromMSA_NJ(msa, tree, Cluster, Distance, SaveFileName); else TreeFromMSA_UPGMA(msa, tree, Cluster, Distance, SaveFileName); FixRoot(tree, Root); }
22.602041
74
0.664108
r-barnes
0f08932a80de20b88e1cd9eee0c30e90e9cc9cfb
27,933
cpp
C++
libraries/USBDevice/USBDevice/USBDevice.cpp
mjrgh/mbed
966bf9577a1d3280df75a0ddd452393d1e8fb97e
[ "Apache-2.0" ]
null
null
null
libraries/USBDevice/USBDevice/USBDevice.cpp
mjrgh/mbed
966bf9577a1d3280df75a0ddd452393d1e8fb97e
[ "Apache-2.0" ]
null
null
null
libraries/USBDevice/USBDevice/USBDevice.cpp
mjrgh/mbed
966bf9577a1d3280df75a0ddd452393d1e8fb97e
[ "Apache-2.0" ]
null
null
null
/* Copyright (c) 2010-2011 mbed.org, MIT License * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software * and associated documentation files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or * substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING * BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include "stdint.h" #include "USBEndpoints.h" #include "USBDevice.h" #include "USBDescriptor.h" //#define DEBUG /* Device status */ #define DEVICE_STATUS_SELF_POWERED (1U<<0) #define DEVICE_STATUS_REMOTE_WAKEUP (1U<<1) /* Endpoint status */ #define ENDPOINT_STATUS_HALT (1U<<0) /* Standard feature selectors */ #define DEVICE_REMOTE_WAKEUP (1) #define ENDPOINT_HALT (0) /* Macro to convert wIndex endpoint number to physical endpoint number */ #define WINDEX_TO_PHYSICAL(endpoint) (((endpoint & 0x0f) << 1) + \ ((endpoint & 0x80) ? 1 : 0)) bool USBDevice::requestGetDescriptor(void) { bool success = false; #ifdef DEBUG printf("get descr: type: %d\r\n", DESCRIPTOR_TYPE(transfer.setup.wValue)); #endif switch (DESCRIPTOR_TYPE(transfer.setup.wValue)) { case DEVICE_DESCRIPTOR: if (deviceDesc() != NULL) { if ((deviceDesc()[0] == DEVICE_DESCRIPTOR_LENGTH) \ && (deviceDesc()[1] == DEVICE_DESCRIPTOR)) { #ifdef DEBUG printf("device descr\r\n"); #endif transfer.remaining = DEVICE_DESCRIPTOR_LENGTH; transfer.ptr = deviceDesc(); transfer.direction = DEVICE_TO_HOST; success = true; } } break; case CONFIGURATION_DESCRIPTOR: if (configurationDesc() != NULL) { if ((configurationDesc()[0] == CONFIGURATION_DESCRIPTOR_LENGTH) \ && (configurationDesc()[1] == CONFIGURATION_DESCRIPTOR)) { #ifdef DEBUG printf("conf descr request\r\n"); #endif /* Get wTotalLength */ transfer.remaining = configurationDesc()[2] \ | (configurationDesc()[3] << 8); transfer.ptr = configurationDesc(); transfer.direction = DEVICE_TO_HOST; success = true; } } break; case STRING_DESCRIPTOR: #ifdef DEBUG printf("str descriptor\r\n"); #endif switch (DESCRIPTOR_INDEX(transfer.setup.wValue)) { case STRING_OFFSET_LANGID: #ifdef DEBUG printf("1\r\n"); #endif transfer.remaining = stringLangidDesc()[0]; transfer.ptr = stringLangidDesc(); transfer.direction = DEVICE_TO_HOST; success = true; break; case STRING_OFFSET_IMANUFACTURER: #ifdef DEBUG printf("2\r\n"); #endif transfer.remaining = stringImanufacturerDesc()[0]; transfer.ptr = stringImanufacturerDesc(); transfer.direction = DEVICE_TO_HOST; success = true; break; case STRING_OFFSET_IPRODUCT: #ifdef DEBUG printf("3\r\n"); #endif transfer.remaining = stringIproductDesc()[0]; transfer.ptr = stringIproductDesc(); transfer.direction = DEVICE_TO_HOST; success = true; break; case STRING_OFFSET_ISERIAL: #ifdef DEBUG printf("4\r\n"); #endif transfer.remaining = stringIserialDesc()[0]; transfer.ptr = stringIserialDesc(); transfer.direction = DEVICE_TO_HOST; success = true; break; case STRING_OFFSET_ICONFIGURATION: #ifdef DEBUG printf("5\r\n"); #endif transfer.remaining = stringIConfigurationDesc()[0]; transfer.ptr = stringIConfigurationDesc(); transfer.direction = DEVICE_TO_HOST; success = true; break; case STRING_OFFSET_IINTERFACE: #ifdef DEBUG printf("6\r\n"); #endif transfer.remaining = stringIinterfaceDesc()[0]; transfer.ptr = stringIinterfaceDesc(); transfer.direction = DEVICE_TO_HOST; success = true; break; } break; case INTERFACE_DESCRIPTOR: #ifdef DEBUG printf("interface descr\r\n"); #endif case ENDPOINT_DESCRIPTOR: #ifdef DEBUG printf("endpoint descr\r\n"); #endif /* TODO: Support is optional, not implemented here */ break; default: #ifdef DEBUG printf("ERROR\r\n"); #endif break; } return success; } void USBDevice::decodeSetupPacket(uint8_t *data, SETUP_PACKET *packet) { /* Fill in the elements of a SETUP_PACKET structure from raw data */ packet->bmRequestType.dataTransferDirection = (data[0] & 0x80) >> 7; packet->bmRequestType.Type = (data[0] & 0x60) >> 5; packet->bmRequestType.Recipient = data[0] & 0x1f; packet->bRequest = data[1]; packet->wValue = (data[2] | (uint16_t)data[3] << 8); packet->wIndex = (data[4] | (uint16_t)data[5] << 8); packet->wLength = (data[6] | (uint16_t)data[7] << 8); } bool USBDevice::controlOut(void) { /* Control transfer data OUT stage */ uint8_t buffer[MAX_PACKET_SIZE_EP0]; uint32_t packetSize; /* Check we should be transferring data OUT */ if (transfer.direction != HOST_TO_DEVICE) { return false; } /* Read from endpoint */ packetSize = EP0getReadResult(buffer); /* Check if transfer size is valid */ if (packetSize > transfer.remaining) { /* Too big */ return false; } /* Update transfer */ transfer.ptr += packetSize; transfer.remaining -= packetSize; /* Check if transfer has completed */ if (transfer.remaining == 0) { /* Transfer completed */ if (transfer.notify) { /* Notify class layer. */ USBCallback_requestCompleted(buffer, packetSize); transfer.notify = false; } /* Status stage */ EP0write(NULL, 0); } else { EP0read(); } return true; } bool USBDevice::controlIn(void) { /* Control transfer data IN stage */ uint32_t packetSize; /* Check if transfer has completed (status stage transactions */ /* also have transfer.remaining == 0) */ if (transfer.remaining == 0) { if (transfer.zlp) { /* Send zero length packet */ EP0write(NULL, 0); transfer.zlp = false; } /* Transfer completed */ if (transfer.notify) { /* Notify class layer. */ USBCallback_requestCompleted(NULL, 0); transfer.notify = false; } EP0read(); EP0readStage(); /* Completed */ return true; } /* Check we should be transferring data IN */ if (transfer.direction != DEVICE_TO_HOST) { return false; } packetSize = transfer.remaining; if (packetSize > MAX_PACKET_SIZE_EP0) { packetSize = MAX_PACKET_SIZE_EP0; } /* Write to endpoint */ EP0write(transfer.ptr, packetSize); /* Update transfer */ transfer.ptr += packetSize; transfer.remaining -= packetSize; return true; } bool USBDevice::requestSetAddress(void) { /* Set the device address */ setAddress(transfer.setup.wValue); if (transfer.setup.wValue == 0) { device.state = DEFAULT; } else { device.state = ADDRESS; } return true; } bool USBDevice::requestSetConfiguration(void) { device.configuration = transfer.setup.wValue; /* Set the device configuration */ if (device.configuration == 0) { /* Not configured */ unconfigureDevice(); device.state = ADDRESS; } else { if (USBCallback_setConfiguration(device.configuration)) { /* Valid configuration */ configureDevice(); device.state = CONFIGURED; } else { return false; } } return true; } bool USBDevice::requestGetConfiguration(void) { /* Send the device configuration */ transfer.ptr = &device.configuration; transfer.remaining = sizeof(device.configuration); transfer.direction = DEVICE_TO_HOST; return true; } bool USBDevice::requestGetInterface(void) { /* Return the selected alternate setting for an interface */ if (device.state != CONFIGURED) { return false; } /* Send the alternate setting */ transfer.setup.wIndex = currentInterface; transfer.ptr = &currentAlternate; transfer.remaining = sizeof(currentAlternate); transfer.direction = DEVICE_TO_HOST; return true; } bool USBDevice::requestSetInterface(void) { bool success = false; if(USBCallback_setInterface(transfer.setup.wIndex, transfer.setup.wValue)) { success = true; currentInterface = transfer.setup.wIndex; currentAlternate = transfer.setup.wValue; } return success; } bool USBDevice::requestSetFeature() { bool success = false; if (device.state != CONFIGURED) { /* Endpoint or interface must be zero */ if (transfer.setup.wIndex != 0) { return false; } } switch (transfer.setup.bmRequestType.Recipient) { case DEVICE_RECIPIENT: /* TODO: Remote wakeup feature not supported */ break; case ENDPOINT_RECIPIENT: if (transfer.setup.wValue == ENDPOINT_HALT) { /* TODO: We should check that the endpoint number is valid */ stallEndpoint( WINDEX_TO_PHYSICAL(transfer.setup.wIndex)); success = true; } break; default: break; } return success; } bool USBDevice::requestClearFeature() { bool success = false; if (device.state != CONFIGURED) { /* Endpoint or interface must be zero */ if (transfer.setup.wIndex != 0) { return false; } } switch (transfer.setup.bmRequestType.Recipient) { case DEVICE_RECIPIENT: /* TODO: Remote wakeup feature not supported */ break; case ENDPOINT_RECIPIENT: /* TODO: We should check that the endpoint number is valid */ if (transfer.setup.wValue == ENDPOINT_HALT) { unstallEndpoint( WINDEX_TO_PHYSICAL(transfer.setup.wIndex)); success = true; } break; default: break; } return success; } bool USBDevice::requestGetStatus(void) { static uint16_t status; bool success = false; if (device.state != CONFIGURED) { /* Endpoint or interface must be zero */ if (transfer.setup.wIndex != 0) { return false; } } switch (transfer.setup.bmRequestType.Recipient) { case DEVICE_RECIPIENT: /* TODO: Currently only supports self powered devices */ status = DEVICE_STATUS_SELF_POWERED; success = true; break; case INTERFACE_RECIPIENT: status = 0; success = true; break; case ENDPOINT_RECIPIENT: /* TODO: We should check that the endpoint number is valid */ if (getEndpointStallState( WINDEX_TO_PHYSICAL(transfer.setup.wIndex))) { status = ENDPOINT_STATUS_HALT; } else { status = 0; } success = true; break; default: break; } if (success) { /* Send the status */ transfer.ptr = (uint8_t *)&status; /* Assumes little endian */ transfer.remaining = sizeof(status); transfer.direction = DEVICE_TO_HOST; } return success; } bool USBDevice::requestSetup(void) { bool success = false; /* Process standard requests */ if ((transfer.setup.bmRequestType.Type == STANDARD_TYPE)) { switch (transfer.setup.bRequest) { case GET_STATUS: success = requestGetStatus(); break; case CLEAR_FEATURE: success = requestClearFeature(); break; case SET_FEATURE: success = requestSetFeature(); break; case SET_ADDRESS: success = requestSetAddress(); break; case GET_DESCRIPTOR: success = requestGetDescriptor(); break; case SET_DESCRIPTOR: /* TODO: Support is optional, not implemented here */ success = false; break; case GET_CONFIGURATION: success = requestGetConfiguration(); break; case SET_CONFIGURATION: success = requestSetConfiguration(); break; case GET_INTERFACE: success = requestGetInterface(); break; case SET_INTERFACE: success = requestSetInterface(); break; default: break; } } return success; } bool USBDevice::controlSetup(void) { bool success = false; /* Control transfer setup stage */ uint8_t buffer[MAX_PACKET_SIZE_EP0]; EP0setup(buffer); /* Initialise control transfer state */ decodeSetupPacket(buffer, &transfer.setup); transfer.ptr = NULL; transfer.remaining = 0; transfer.direction = 0; transfer.zlp = false; transfer.notify = false; #ifdef DEBUG printf("dataTransferDirection: %d\r\nType: %d\r\nRecipient: %d\r\nbRequest: %d\r\nwValue: %d\r\nwIndex: %d\r\nwLength: %d\r\n",transfer.setup.bmRequestType.dataTransferDirection, transfer.setup.bmRequestType.Type, transfer.setup.bmRequestType.Recipient, transfer.setup.bRequest, transfer.setup.wValue, transfer.setup.wIndex, transfer.setup.wLength); #endif /* Class / vendor specific */ success = USBCallback_request(); if (!success) { /* Standard requests */ if (!requestSetup()) { #ifdef DEBUG printf("fail!!!!\r\n"); #endif return false; } } /* Check transfer size and direction */ if (transfer.setup.wLength>0) { if (transfer.setup.bmRequestType.dataTransferDirection \ == DEVICE_TO_HOST) { /* IN data stage is required */ if (transfer.direction != DEVICE_TO_HOST) { return false; } /* Transfer must be less than or equal to the size */ /* requested by the host */ if (transfer.remaining > transfer.setup.wLength) { transfer.remaining = transfer.setup.wLength; } } else { /* OUT data stage is required */ if (transfer.direction != HOST_TO_DEVICE) { return false; } /* Transfer must be equal to the size requested by the host */ if (transfer.remaining != transfer.setup.wLength) { return false; } } } else { /* No data stage; transfer size must be zero */ if (transfer.remaining != 0) { return false; } } /* Data or status stage if applicable */ if (transfer.setup.wLength>0) { if (transfer.setup.bmRequestType.dataTransferDirection \ == DEVICE_TO_HOST) { /* Check if we'll need to send a zero length packet at */ /* the end of this transfer */ if (transfer.setup.wLength > transfer.remaining) { /* Device wishes to transfer less than host requested */ if ((transfer.remaining % MAX_PACKET_SIZE_EP0) == 0) { /* Transfer is a multiple of EP0 max packet size */ transfer.zlp = true; } } /* IN stage */ controlIn(); } else { /* OUT stage */ EP0read(); } } else { /* Status stage */ EP0write(NULL, 0); } return true; } void USBDevice::busReset(void) { device.state = DEFAULT; device.configuration = 0; device.suspended = false; /* Call class / vendor specific busReset function */ USBCallback_busReset(); } void USBDevice::EP0setupCallback(void) { /* Endpoint 0 setup event */ if (!controlSetup()) { /* Protocol stall */ EP0stall(); } /* Return true if an OUT data stage is expected */ } void USBDevice::EP0out(void) { /* Endpoint 0 OUT data event */ if (!controlOut()) { /* Protocol stall; this will stall both endpoints */ EP0stall(); } } void USBDevice::EP0in(void) { #ifdef DEBUG printf("EP0IN\r\n"); #endif /* Endpoint 0 IN data event */ if (!controlIn()) { /* Protocol stall; this will stall both endpoints */ EP0stall(); } } bool USBDevice::configured(void) { /* Returns true if device is in the CONFIGURED state */ return (device.state == CONFIGURED); } void USBDevice::connect(bool blocking) { /* Connect device */ USBHAL::connect(); if (blocking) { /* Block if not configured */ while (!configured()); } } void USBDevice::disconnect(void) { /* Disconnect device */ USBHAL::disconnect(); /* Set initial device state */ device.state = POWERED; device.configuration = 0; device.suspended = false; } CONTROL_TRANSFER * USBDevice::getTransferPtr(void) { return &transfer; } bool USBDevice::addEndpoint(uint8_t endpoint, uint32_t maxPacket) { return realiseEndpoint(endpoint, maxPacket, 0); } bool USBDevice::addRateFeedbackEndpoint(uint8_t endpoint, uint32_t maxPacket) { /* For interrupt endpoints only */ return realiseEndpoint(endpoint, maxPacket, RATE_FEEDBACK_MODE); } uint8_t * USBDevice::findDescriptor(uint8_t descriptorType) { /* Find a descriptor within the list of descriptors */ /* following a configuration descriptor. */ uint16_t wTotalLength; uint8_t *ptr; if (configurationDesc() == NULL) { return NULL; } /* Check this is a configuration descriptor */ if ((configurationDesc()[0] != CONFIGURATION_DESCRIPTOR_LENGTH) \ || (configurationDesc()[1] != CONFIGURATION_DESCRIPTOR)) { return NULL; } wTotalLength = configurationDesc()[2] | (configurationDesc()[3] << 8); /* Check there are some more descriptors to follow */ if (wTotalLength <= (CONFIGURATION_DESCRIPTOR_LENGTH+2)) /* +2 is for bLength and bDescriptorType of next descriptor */ { return NULL; } /* Start at first descriptor after the configuration descriptor */ ptr = &(configurationDesc()[CONFIGURATION_DESCRIPTOR_LENGTH]); do { if (ptr[1] /* bDescriptorType */ == descriptorType) { /* Found */ return ptr; } /* Skip to next descriptor */ ptr += ptr[0]; /* bLength */ } while (ptr < (configurationDesc() + wTotalLength)); /* Reached end of the descriptors - not found */ return NULL; } void USBDevice::connectStateChanged(unsigned int connected) { } void USBDevice::suspendStateChanged(unsigned int suspended) { } USBDevice::USBDevice(uint16_t vendor_id, uint16_t product_id, uint16_t product_release){ VENDOR_ID = vendor_id; PRODUCT_ID = product_id; PRODUCT_RELEASE = product_release; /* Set initial device state */ device.state = POWERED; device.configuration = 0; device.suspended = false; }; bool USBDevice::readStart(uint8_t endpoint, uint32_t maxSize) { return endpointRead(endpoint, maxSize) == EP_PENDING; } bool USBDevice::write(uint8_t endpoint, uint8_t * buffer, uint32_t size, uint32_t maxSize) { EP_STATUS result; if (size > maxSize) { return false; } if(!configured()) { return false; } /* Send report */ result = endpointWrite(endpoint, buffer, size); if (result != EP_PENDING) { return false; } /* Wait for completion */ do { result = endpointWriteResult(endpoint); } while ((result == EP_PENDING) && configured()); return (result == EP_COMPLETED); } bool USBDevice::writeNB(uint8_t endpoint, uint8_t * buffer, uint32_t size, uint32_t maxSize) { EP_STATUS result; if (size > maxSize) { return false; } if(!configured()) { return false; } /* Send report */ result = endpointWrite(endpoint, buffer, size); if (result != EP_PENDING) { return false; } result = endpointWriteResult(endpoint); return (result == EP_COMPLETED); } bool USBDevice::readEP(uint8_t endpoint, uint8_t * buffer, uint32_t * size, uint32_t maxSize) { EP_STATUS result; if(!configured()) { return false; } /* Wait for completion */ do { result = endpointReadResult(endpoint, buffer, size); } while ((result == EP_PENDING) && configured()); return (result == EP_COMPLETED); } bool USBDevice::readEP_NB(uint8_t endpoint, uint8_t * buffer, uint32_t * size, uint32_t maxSize) { EP_STATUS result; if(!configured()) { return false; } result = endpointReadResult(endpoint, buffer, size); return (result == EP_COMPLETED); } uint8_t * USBDevice::deviceDesc() { static uint8_t deviceDescriptor[] = { DEVICE_DESCRIPTOR_LENGTH, /* bLength */ DEVICE_DESCRIPTOR, /* bDescriptorType */ LSB(USB_VERSION_2_0), /* bcdUSB (LSB) */ MSB(USB_VERSION_2_0), /* bcdUSB (MSB) */ 0x00, /* bDeviceClass */ 0x00, /* bDeviceSubClass */ 0x00, /* bDeviceprotocol */ MAX_PACKET_SIZE_EP0, /* bMaxPacketSize0 */ (uint8_t)(LSB(VENDOR_ID)), /* idVendor (LSB) */ (uint8_t)(MSB(VENDOR_ID)), /* idVendor (MSB) */ (uint8_t)(LSB(PRODUCT_ID)), /* idProduct (LSB) */ (uint8_t)(MSB(PRODUCT_ID)), /* idProduct (MSB) */ (uint8_t)(LSB(PRODUCT_RELEASE)), /* bcdDevice (LSB) */ (uint8_t)(MSB(PRODUCT_RELEASE)), /* bcdDevice (MSB) */ STRING_OFFSET_IMANUFACTURER, /* iManufacturer */ STRING_OFFSET_IPRODUCT, /* iProduct */ STRING_OFFSET_ISERIAL, /* iSerialNumber */ 0x01 /* bNumConfigurations */ }; return deviceDescriptor; } uint8_t * USBDevice::stringLangidDesc() { static uint8_t stringLangidDescriptor[] = { 0x04, /*bLength*/ STRING_DESCRIPTOR, /*bDescriptorType 0x03*/ 0x09,0x04, /*bString Lang ID - 0x0409 - English*/ }; return stringLangidDescriptor; } uint8_t * USBDevice::stringImanufacturerDesc() { static uint8_t stringImanufacturerDescriptor[] = { 0x12, /*bLength*/ STRING_DESCRIPTOR, /*bDescriptorType 0x03*/ 'm',0,'b',0,'e',0,'d',0,'.',0,'o',0,'r',0,'g',0, /*bString iManufacturer - mbed.org*/ }; return stringImanufacturerDescriptor; } uint8_t * USBDevice::stringIserialDesc() { static uint8_t stringIserialDescriptor[] = { 0x16, /*bLength*/ STRING_DESCRIPTOR, /*bDescriptorType 0x03*/ '0',0,'1',0,'2',0,'3',0,'4',0,'5',0,'6',0,'7',0,'8',0,'9',0, /*bString iSerial - 0123456789*/ }; return stringIserialDescriptor; } uint8_t * USBDevice::stringIConfigurationDesc() { static uint8_t stringIconfigurationDescriptor[] = { 0x06, /*bLength*/ STRING_DESCRIPTOR, /*bDescriptorType 0x03*/ '0',0,'1',0, /*bString iConfiguration - 01*/ }; return stringIconfigurationDescriptor; } uint8_t * USBDevice::stringIinterfaceDesc() { static uint8_t stringIinterfaceDescriptor[] = { 0x08, /*bLength*/ STRING_DESCRIPTOR, /*bDescriptorType 0x03*/ 'U',0,'S',0,'B',0, /*bString iInterface - USB*/ }; return stringIinterfaceDescriptor; } uint8_t * USBDevice::stringIproductDesc() { static uint8_t stringIproductDescriptor[] = { 0x16, /*bLength*/ STRING_DESCRIPTOR, /*bDescriptorType 0x03*/ 'U',0,'S',0,'B',0,' ',0,'D',0,'E',0,'V',0,'I',0,'C',0,'E',0 /*bString iProduct - USB DEVICE*/ }; return stringIproductDescriptor; }
28.329615
182
0.534994
mjrgh
0f0ad86cab5c8fc9fbc6c968a7ff88f91b9110b7
1,854
cpp
C++
smacc_client_library/move_group_interface_client/src/move_group_interface_client/client_behaviors/cb_attach_object.cpp
tylerjw/SMACC
76dceb90411c2e4b13e4ae78c0af67d1acfb3333
[ "BSD-3-Clause" ]
203
2019-04-11T16:42:10.000Z
2022-03-18T06:02:56.000Z
smacc_client_library/move_group_interface_client/src/move_group_interface_client/client_behaviors/cb_attach_object.cpp
tylerjw/SMACC
76dceb90411c2e4b13e4ae78c0af67d1acfb3333
[ "BSD-3-Clause" ]
50
2019-04-18T09:09:48.000Z
2022-03-29T21:38:21.000Z
smacc_client_library/move_group_interface_client/src/move_group_interface_client/client_behaviors/cb_attach_object.cpp
tylerjw/SMACC
76dceb90411c2e4b13e4ae78c0af67d1acfb3333
[ "BSD-3-Clause" ]
35
2019-09-10T15:06:37.000Z
2022-02-02T09:10:08.000Z
/***************************************************************************************************************** * ReelRobotix Inc. - Software License Agreement Copyright (c) 2018-2020 * Authors: Pablo Inigo Blasco, Brett Aldrich * ******************************************************************************************************************/ #include <move_group_interface_client/client_behaviors/cb_attach_object.h> #include <move_group_interface_client/components/cp_grasping_objects.h> namespace cl_move_group_interface { CbAttachObject::CbAttachObject(std::string targetObjectName) : targetObjectName_(targetObjectName) { } CbAttachObject::CbAttachObject() { } void CbAttachObject::onEntry() { cl_move_group_interface::ClMoveGroup *moveGroup; this->requiresClient(moveGroup); cl_move_group_interface::GraspingComponent *graspingComponent; this->requiresComponent(graspingComponent); // auto cubepos = cubeinfo->pose_->toPoseStampedMsg(); moveit_msgs::CollisionObject targetCollisionObject; bool found = graspingComponent->getGraspingObject(targetObjectName_, targetCollisionObject); if (found) { targetCollisionObject.operation = moveit_msgs::CollisionObject::ADD; targetCollisionObject.header.stamp = ros::Time::now(); moveGroup->planningSceneInterface.applyCollisionObject(targetCollisionObject); // collisionObjects.push_back(cubeCollision); graspingComponent->currentAttachedObjectName = targetObjectName_; moveGroup->moveGroupClientInterface.attachObject(targetObjectName_, "gripper_link", graspingComponent->fingerTipNames); } } void CbAttachObject::onExit() { } } // namespace cl_move_group_interface
36.352941
131
0.627832
tylerjw
0f0ba4c35ac6fc3a369223f2e2d0efbfa4c757e7
12,428
cpp
C++
src/main.cpp
jorge-imperial/mongo_ftdc
d17680d50d5d622af4cad5c0cef6632799faa1c7
[ "Apache-2.0" ]
2
2021-11-01T19:16:43.000Z
2022-01-21T23:25:41.000Z
src/main.cpp
jorge-imperial/mongo_ftdc
d17680d50d5d622af4cad5c0cef6632799faa1c7
[ "Apache-2.0" ]
3
2021-08-09T15:30:42.000Z
2022-01-12T19:45:41.000Z
src/main.cpp
jorge-imperial/mongo_ftdc
d17680d50d5d622af4cad5c0cef6632799faa1c7
[ "Apache-2.0" ]
null
null
null
#include <pybind11/pybind11.h> #include <pybind11/stl_bind.h> #include <pybind11/stl.h> #include <pybind11/numpy.h> #include <FTDCParser.h> #include <vector> #include <filesystem> #include <boost/format.hpp> namespace py = pybind11; using namespace py::literals; using namespace ftdcparser; typedef std::vector<std::string> MetricNames; #define FALSE 0 #define STRINGIFY(x) #x #define MACRO_STRINGIFY(x) STRINGIFY(x) //TODO: Check for memory leaks. // helper function to avoid making a copy when returning a py::array_t // author: https://github.com/YannickJadoul // source: https://github.com/pybind/pybind11/issues/1042#issuecomment-642215028 template <typename Sequence> inline py::array_t<typename Sequence::value_type> as_pyarray(Sequence &&seq) { auto size = seq.size(); auto data = seq.data(); std::unique_ptr<Sequence> seq_ptr = std::make_unique<Sequence>(std::move(seq)); auto capsule = py::capsule(seq_ptr.get(), [](void *p) { std::unique_ptr<Sequence>(reinterpret_cast<Sequence*>(p)); }); seq_ptr.release(); return py::array(size, data, capsule); } inline py::array_t<uint64_t > as_pyarray(MetricsPtr m) { auto size = m->size(); auto data = m->data(); std::unique_ptr<MetricsPtr> seq_ptr = std::make_unique<MetricsPtr>(std::move(m)); auto capsule = py::capsule(seq_ptr.get(), [](void *p) { std::unique_ptr<Metrics>(reinterpret_cast<Metrics *>(p)); }); seq_ptr.release(); return py::array(size, data, capsule); } struct ParserClass { FTDCParser *pParser; std::vector<std::string> metadata; std::vector<std::string> fileList; MetricNames metric_names; py::array_t<unsigned long> emptyArray; MetricsPtr emptyMetrics; explicit ParserClass() { pParser = new FTDCParser(); }; int parseFile(std::string file, bool lazy=true) { fileList.emplace_back(file); int n = pParser->parseFiles(&fileList, false, false, lazy); if (n == 0) { // Timestamps, metric names, and metadata as fields in python metric_names = pParser->getMetricsNames(); metadata = pParser->getMetadata(); } return n; } void setVerbose(bool verbose) { pParser->setVerbose(verbose); } int parseDir(std::string dir, bool lazy=true) { // if it exists, and it a directory, pop and push contents if (std::filesystem::exists(dir) && std::filesystem::is_directory(dir)) { for (auto&& fileInPath : std::filesystem::directory_iterator(dir)) fileList.push_back(fileInPath.path().string()); // Not really necessary. std::sort(fileList.begin(), fileList.end()); int n = pParser->parseFiles(&fileList, false, false, lazy); if (n == 0) { // metric names and metadata as fields in python metric_names = pParser->getMetricsNames(); metadata = pParser->getMetadata(); } return n; } return -1; } int dumpFileAsJson(std::string input, std::string output) { return pParser->dumpDocsAsJsonTimestamps(input, output, INVALID_TIMESTAMP, INVALID_TIMESTAMP); } int dumpFileAsCsv(std::string input, std::string output) { return pParser->dumpDocsAsCsvTimestamps(input, output, INVALID_TIMESTAMP, INVALID_TIMESTAMP); } py::list getParsedFileInfo() { auto fi = pParser->getParsedFileInfo(); py::list parsedFiles; for (auto f : fi) { auto msg = str(boost::format("{ \"abs_path\" : %1%, \"samples\" : %2%, \"start\" : %3%, \"end\" : %4% }") % f->getFileAbsolute() % f->getSamplesCount() % f->getStart() % f->getEnd() ); auto fileInfo = py::dict("abs_path"_a=f->getFileAbsolute(), "samples"_a=f->getSamplesCount(), "start"_a=f->getStart(), "end"_a=f->getEnd() ); parsedFiles.append(fileInfo); } return parsedFiles; } MetricsPtr get_timestamps(size_t start =INVALID_TIMESTAMP, size_t end = INVALID_TIMESTAMP) { return pParser->getMetric( "start", start, end); } MetricsPtr getMetric(std::string metric_name, size_t start = INVALID_TIMESTAMP, size_t end =INVALID_TIMESTAMP, bool rated_metric = false) { return pParser->getMetric(metric_name, start, end, rated_metric); } std::vector<MetricsPtr> getMetricList(const std::vector<std::string> metric_names, size_t start = INVALID_TIMESTAMP, size_t end = INVALID_TIMESTAMP, bool rated_metric = false) { auto m = pParser->getMetric(std::move(metric_names), start, end, rated_metric); std::vector<MetricsPtr> metricList; for(int i=0;i<m.size();++i) { // How to handle metric names that are not found? if (m[i] != nullptr) { metricList.emplace_back(m[i]); } else metricList.emplace_back(emptyMetrics); } return metricList; } uint64_t getMetricSampleCount() { //TODO: may or may not be valid in lazy parsing mode return pParser->getMetricLength(); } py::array_t<unsigned long> getMetricAsNumpyArray(std::string metric_name, size_t start = INVALID_TIMESTAMP, size_t end = INVALID_TIMESTAMP, bool rated_metric = false) { auto m = pParser->getMetric(metric_name, start, end, rated_metric); return as_pyarray(m); } std::vector<py::array_t<unsigned long>> getMetricListAsNumpyArray(const std::vector<std::string> metric_names, size_t start = INVALID_TIMESTAMP, size_t end = INVALID_TIMESTAMP, bool rated_metric = false) { auto m = pParser->getMetric(std::move(metric_names), start, end, rated_metric); std::vector<py::array_t<unsigned long>> metricList; for(int i=0;i<m.size();++i) { // How to handle metric names that are not found? if (m[i] != nullptr) { auto element = as_pyarray(m[i]); metricList.emplace_back(element); } else metricList.emplace_back(emptyArray); } return metricList; } py::array_t<uint64_t> getMetricListAsNumpyMatrix(const std::vector<std::string> metric_names, size_t start = INVALID_TIMESTAMP, size_t end = INVALID_TIMESTAMP, bool rated_metric = false, bool transpose = false) { size_t stride = 0; auto m = pParser->getMetricMatrix( metric_names, &stride, start, end, rated_metric); if (stride !=0) { int metricNamesSize = metric_names.size(); if (!transpose) { return py::array_t<uint64_t>({ metricNamesSize, (int)stride}, m->data()); } else { py::array_t<uint64_t> a = py::array_t<uint64_t>( {(int)stride, metricNamesSize}); uint64_t *p = m->data(); auto r = a.mutable_unchecked(); //printf("dimensions %zd x %zd\n", r.shape(0), r.shape(1)); //printf("Element (0,0)=%ld\nElement (%ld,0)=%ld\n", p[0], r.shape(0), p[r.shape(0)]); for (int i=0; i<r.shape(0); ++i) { for (int j=0; j<r.shape(1); ++j) r(i,j) = p[i + (j*r.shape(0))]; } return a; } } else { // err return py::array_t<uint64_t>({ 0, 0 }, { 4, 8 }); } } }; PYBIND11_MODULE(_core, m) { m.doc() = R"pbdoc( MongoDB FTDC files parser library. ----------------------- .. currentmodule:: pyftdc .. autosummary:: :toctree: _generate parse_dir parse_file get_metric get_timestamps get_metric_sample_count get_metric_names timestamps metadata get_metric_numpy get_metrics_list_numpy get_metrics_list_numpy_matrix )pbdoc"; py::class_<ParserClass>(m, "FTDCParser") .def(py::init<>()) .def("set_verbose", &ParserClass::setVerbose, "Set verbose flag", py::arg("verbose")) .def("parse_dir", &ParserClass::parseDir, "Parses all files in a directory", py::arg("dir"), py::arg("lazy") = true) .def("parse_file", &ParserClass::parseFile, "Parses one file", py::arg("file"), py::arg("lazy") = true) .def("get_parsed_file_info", &ParserClass::getParsedFileInfo, "Returns information on parsed files") .def("dump_file_as_json", &ParserClass::dumpFileAsJson, "Dumps a file contents to a file as JSON structures.", py::arg("input"), py::arg("output")) .def("dump_file_as_csv", &ParserClass::dumpFileAsCsv, "Dumps a file contents to a file as CSV file.", py::arg("input"), py::arg("output")) .def("get_metric", &ParserClass::getMetric, "Returns a list of values from the metrics, using starting and ending timestamps if specified", py::arg("metric_name"), py::arg("start") = ::INVALID_TIMESTAMP, py::arg("end") = ::INVALID_TIMESTAMP, py::arg("rated_metric") = false) .def("get_metrics_list", &ParserClass::getMetricList, "Returns a list of values from the metrics list, using starting and ending timestamps if specified", py::arg("metric_name"), py::arg("start") = ::INVALID_TIMESTAMP, py::arg("end") = ::INVALID_TIMESTAMP, py::arg("rated_metric") = false) .def("get_timestamps", &ParserClass::get_timestamps, "Returns timestamps", py::arg("start") = ::INVALID_TIMESTAMP, py::arg("end") = ::INVALID_TIMESTAMP) .def("get_metric_sample_count", &ParserClass::getMetricSampleCount) .def_readonly("metric_names", &ParserClass::metric_names) .def_readonly("metadata", &ParserClass::metadata) .def("get_metric_numpy", &ParserClass::getMetricAsNumpyArray, "Returns a metric as a numpy array.", py::arg("metric_name"), py::arg("start") = ::INVALID_TIMESTAMP, py::arg("end") = ::INVALID_TIMESTAMP, py::arg("rated_metric") = false) .def("get_metrics_list_numpy", &ParserClass::getMetricListAsNumpyArray, "Returns a list of metrics as numpy arrays.", py::arg("metric_names"), py::arg("start") = ::INVALID_TIMESTAMP, py::arg("end") = ::INVALID_TIMESTAMP, py::arg("rated_metric") = false) .def("get_metrics_list_numpy_matrix", &ParserClass::getMetricListAsNumpyMatrix, "Returns a matrix of metrics.", py::arg("metric_names"), py::arg("start") = ::INVALID_TIMESTAMP, py::arg("end") = ::INVALID_TIMESTAMP, py::arg("rated_metric") = false, py::arg("transpose") = false) ; #ifdef VERSION_INFO m.attr("__version__") = MACRO_STRINGIFY(VERSION_INFO); #else m.attr("__version__") = "dev"; #endif } // PYBIND11_MODULE
35.712644
122
0.53645
jorge-imperial
0f0ccb4987268eff647465662e1a9299b35b178e
273
cpp
C++
Tek3/UML/AirportManager/Employee/Stewart.cpp
Estayparadox/Epitech-Bundle
e4395961bb86bf494e3c84ab44c27b5a9afc6c6c
[ "MIT" ]
30
2018-10-26T12:54:11.000Z
2022-02-04T18:18:57.000Z
Tek3/UML/AirportManager/Employee/Stewart.cpp
Estayparadox/Epitech-Bundle
e4395961bb86bf494e3c84ab44c27b5a9afc6c6c
[ "MIT" ]
null
null
null
Tek3/UML/AirportManager/Employee/Stewart.cpp
Estayparadox/Epitech-Bundle
e4395961bb86bf494e3c84ab44c27b5a9afc6c6c
[ "MIT" ]
26
2018-11-20T18:11:39.000Z
2022-01-28T21:05:30.000Z
/** * Project Untitled */ #include "Stewart.h" /** * Stewart implementation */ /** * @param boardingCard * @return bool */ bool Stewart::checkBoardingCard(void boardingCard) { return false; } /** * @return void */ void Stewart::sellFood() { return; }
10.5
52
0.615385
Estayparadox
0f0e439eb3f208d14e230aff66fa78aa9e5e14cf
15,980
cpp
C++
src/backend/uop.cpp
jeroendebaat/lc3tools
b1ceb8bc28a82227ccbd17c90f6b6cfcdf324d41
[ "Apache-2.0" ]
58
2018-07-13T03:41:38.000Z
2022-03-08T19:06:20.000Z
src/backend/uop.cpp
jeroendebaat/lc3tools
b1ceb8bc28a82227ccbd17c90f6b6cfcdf324d41
[ "Apache-2.0" ]
26
2019-12-02T05:33:00.000Z
2022-03-12T15:54:26.000Z
src/backend/uop.cpp
jeroendebaat/lc3tools
b1ceb8bc28a82227ccbd17c90f6b6cfcdf324d41
[ "Apache-2.0" ]
24
2019-08-30T15:00:13.000Z
2022-01-26T05:11:36.000Z
/* * Copyright 2020 McGraw-Hill Education. All rights reserved. No reproduction or distribution without the prior written consent of McGraw-Hill Education. */ #include "decoder.h" #include "isa.h" #include "state.h" #include "uop.h" using namespace lc3::core; PIMicroOp IMicroOp::insert(PIMicroOp new_next) { if(next == nullptr) { next = new_next; } else { PIMicroOp cur = next; while(cur->next != nullptr) { cur = cur->next; } cur->next = new_next; } return next; } std::string IMicroOp::regToString(uint16_t reg_id) const { if(reg_id < 8) { return lc3::utils::ssprintf("R%d", reg_id); } else { return lc3::utils::ssprintf("T%d", reg_id - 8); } } void FetchMicroOp::handleMicroOp(MachineState & state) { if(isAccessViolation(state.readPC(), state)) { PIMicroOp msg = std::make_shared<PrintMessageMicroOp>("illegal memory access (ACV)"); std::pair<PIMicroOp, PIMicroOp> handle_exception_chain = buildSystemModeEnter(INTEX_TABLE_START, 0x2, lc3::utils::getBits(state.readPSR(), 10, 8)); PIMicroOp callback = std::make_shared<CallbackMicroOp>(CallbackType::EX_ENTER); PIMicroOp func_trace = std::make_shared<PushFuncTypeMicroOp>(FuncType::EXCEPTION); msg->insert(handle_exception_chain.first); handle_exception_chain.second->insert(callback); callback->insert(func_trace); next = msg; } else { uint16_t value = std::get<0>(state.readMem(state.readPC())); state.writeIR(value); } } std::string FetchMicroOp::toString(MachineState const & state) const { return lc3::utils::ssprintf("IR:0x%0.4hx <= M[0x%0.4hx]:0x%0.4hx", state.readIR(), state.readPC(), std::get<0>(state.readMem(state.readPC()))); } void DecodeMicroOp::handleMicroOp(MachineState & state) { lc3::optional<PIInstruction> inst = decoder.decode(state.readIR()); if(inst) { insert((*inst)->buildMicroOps(state)); state.writeDecodedIR(*inst); } else { PIMicroOp msg = std::make_shared<PrintMessageMicroOp>("unknown opcode"); PIMicroOp dec_pc = std::make_shared<PCAddImmMicroOp>(-1); std::pair<PIMicroOp, PIMicroOp> handle_exception_chain = buildSystemModeEnter(INTEX_TABLE_START, 0x1, lc3::utils::getBits(state.readPSR(), 10, 8)); PIMicroOp callback = std::make_shared<CallbackMicroOp>(CallbackType::EX_ENTER); PIMicroOp func_trace = std::make_shared<PushFuncTypeMicroOp>(FuncType::EXCEPTION); msg->insert(dec_pc); dec_pc->insert(handle_exception_chain.first); handle_exception_chain.second->insert(callback); callback->insert(func_trace); next = msg; } } std::string DecodeMicroOp::toString(MachineState const & state) const { lc3::optional<PIInstruction> inst = decoder.decode(state.readIR()); if(inst) { (*inst)->buildMicroOps(state); return lc3::utils::ssprintf("dIR <= %s", (*inst)->toValueString().c_str()); } else { return "dIR <= Illegal instruction"; } } void PCWriteRegMicroOp::handleMicroOp(MachineState & state) { uint16_t value = state.readReg(reg_id); state.writePC(value); } std::string PCWriteRegMicroOp::toString(MachineState const & state) const { return lc3::utils::ssprintf("PC:0x%0.4hx <= %s:0x%0.4hx", state.readPC(), regToString(reg_id).c_str(), state.readReg(reg_id)); } void PSRWriteRegMicroOp::handleMicroOp(MachineState & state) { uint16_t value = state.readReg(reg_id); state.writePSR(value); } std::string PSRWriteRegMicroOp::toString(MachineState const & state) const { return lc3::utils::ssprintf("PSR:0x%0.4hx <= %s:0x%0.4hx", state.readPSR(), regToString(reg_id).c_str(), state.readReg(reg_id)); } void PCAddImmMicroOp::handleMicroOp(MachineState & state) { uint16_t value = state.readPC() + amnt; state.writePC(value); } std::string PCAddImmMicroOp::toString(MachineState const & state) const { return lc3::utils::ssprintf("PC:0x%0.4hx <= (PC:0x%0.4hx + #%d):0x%0.4hx", state.readPC(), state.readPC(), amnt, state.readPC() + amnt); } void RegWriteImmMicroOp::handleMicroOp(MachineState & state) { state.writeReg(reg_id, value); } std::string RegWriteImmMicroOp::toString(MachineState const & state) const { return lc3::utils::ssprintf("%s:0x%0.4hx <= 0x%0.4hx", regToString(reg_id).c_str(), state.readReg(reg_id), value); } void RegWriteRegMicroOp::handleMicroOp(MachineState & state) { state.writeReg(dst_id, state.readReg(src_id)); } std::string RegWriteRegMicroOp::toString(MachineState const & state) const { return lc3::utils::ssprintf("%s:0x%0.4hx <= %s:0x%0.4hx", regToString(dst_id).c_str(), state.readReg(dst_id), regToString(src_id).c_str(), state.readReg(src_id)); } void RegWritePCMicroOp::handleMicroOp(MachineState & state) { state.writeReg(reg_id, state.readPC()); } std::string RegWritePCMicroOp::toString(MachineState const & state) const { return lc3::utils::ssprintf("%s:0x%0.4hx <= PC:0x%0.4hx", regToString(reg_id).c_str(), state.readReg(reg_id), state.readPC()); } void RegWritePSRMicroOp::handleMicroOp(MachineState & state) { state.writeReg(reg_id, state.readPSR()); } std::string RegWritePSRMicroOp::toString(MachineState const & state) const { return lc3::utils::ssprintf("%s:0x%0.4hx <= PSR:0x%0.4hx", regToString(reg_id).c_str(), state.readReg(reg_id), state.readPSR()); } void RegWriteSSPMicroOp::handleMicroOp(MachineState & state) { state.writeReg(reg_id, state.readSSP()); } std::string RegWriteSSPMicroOp::toString(MachineState const & state) const { return lc3::utils::ssprintf("%s:0x%0.4hx <= SSP:0x%0.4hx", regToString(reg_id).c_str(), state.readReg(reg_id), state.readSSP()); } void SSPWriteRegMicroOp::handleMicroOp(MachineState & state) { state.writeSSP(state.readReg(reg_id)); } std::string SSPWriteRegMicroOp::toString(MachineState const & state) const { return lc3::utils::ssprintf("SSP:0x%0.4hx <= %s:0x%0.4hx", state.readSSP(), regToString(reg_id).c_str(), state.readReg(reg_id)); } void RegAddImmMicroOp::handleMicroOp(MachineState & state) { uint16_t value = state.readReg(src_id) + amnt; state.writeReg(dst_id, value); } std::string RegAddImmMicroOp::toString(MachineState const & state) const { return lc3::utils::ssprintf("%s:0x%0.4hx <= (%s:0x%0.4hx + #%d):0x%0.4hx", regToString(dst_id).c_str(), state.readReg(dst_id), regToString(src_id).c_str(), state.readReg(src_id), amnt, state.readReg(src_id) + amnt); } void RegAddRegMicroOp::handleMicroOp(MachineState & state) { uint16_t value = state.readReg(src_id1) + state.readReg(src_id2); state.writeReg(dst_id, value); } std::string RegAddRegMicroOp::toString(MachineState const & state) const { return lc3::utils::ssprintf("%s:0x%0.4hx <= (%s:0x%0.4hx + %s:0x%0.4hx):0x%0.4hx", regToString(dst_id).c_str(), state.readReg(dst_id), regToString(src_id1).c_str(), state.readReg(src_id1), regToString(src_id2).c_str(), state.readReg(src_id2), state.readReg(src_id1) + state.readReg(src_id2)); } void RegAndImmMicroOp::handleMicroOp(MachineState & state) { uint16_t value = state.readReg(src_id) & amnt; state.writeReg(dst_id, value); } std::string RegAndImmMicroOp::toString(MachineState const & state) const { return lc3::utils::ssprintf("%s:0x%0.4hx <= (%s:0x%0.4hx & #%d):0x%0.4hx", regToString(dst_id).c_str(), state.readReg(dst_id), regToString(src_id).c_str(), state.readReg(src_id), amnt, state.readReg(src_id) & amnt); } void RegAndRegMicroOp::handleMicroOp(MachineState & state) { uint16_t value = state.readReg(src_id1) & state.readReg(src_id2); state.writeReg(dst_id, value); } std::string RegAndRegMicroOp::toString(MachineState const & state) const { return lc3::utils::ssprintf("%s:0x%0.4hx <= (%s:0x%0.4hx & %s:0x%0.4hx):0x%0.4hx", regToString(dst_id).c_str(), state.readReg(dst_id), regToString(src_id1).c_str(), state.readReg(src_id1), regToString(src_id2).c_str(), state.readReg(src_id2), state.readReg(src_id1) & state.readReg(src_id2)); } void RegNotMicroOp::handleMicroOp(MachineState & state) { uint16_t value = ~state.readReg(src_id); state.writeReg(dst_id, value); } std::string RegNotMicroOp::toString(MachineState const & state) const { return lc3::utils::ssprintf("%s:0x%0.4hx <= (~%s:0x%0.4hx):0x%0.4hx", regToString(dst_id).c_str(), state.readReg(dst_id), regToString(src_id).c_str(), state.readReg(src_id), ~state.readReg(src_id)); } void MemReadMicroOp::handleMicroOp(MachineState & state) { uint16_t addr = state.readReg(addr_reg_id); if(isAccessViolation(addr, state)) { PIMicroOp msg = std::make_shared<PrintMessageMicroOp>("illegal memory access (ACV)"); PIMicroOp dec_pc = std::make_shared<PCAddImmMicroOp>(-1); std::pair<PIMicroOp, PIMicroOp> handle_exception_chain = buildSystemModeEnter(INTEX_TABLE_START, 0x2, lc3::utils::getBits(state.readPSR(), 10, 8)); PIMicroOp callback = std::make_shared<CallbackMicroOp>(CallbackType::EX_ENTER); PIMicroOp func_trace = std::make_shared<PushFuncTypeMicroOp>(FuncType::EXCEPTION); msg->insert(dec_pc); dec_pc->insert(handle_exception_chain.first); handle_exception_chain.second->insert(callback); callback->insert(func_trace); next = msg; } else { std::pair<uint16_t, PIMicroOp> read_result = state.readMem(addr); uint16_t value = std::get<0>(read_result); PIMicroOp op = std::get<1>(read_result); if(op) { insert(op); } state.writeReg(dst_id, value); } } std::string MemReadMicroOp::toString(MachineState const & state) const { return lc3::utils::ssprintf("%s:0x%0.4hx <= MEM[%s:0x%0.4hx]:0x%0.4hx", regToString(dst_id).c_str(), state.readReg(dst_id), regToString(addr_reg_id).c_str(), state.readReg(addr_reg_id), std::get<0>(state.readMem(state.readReg(addr_reg_id)))); } void MemWriteImmMicroOp::handleMicroOp(MachineState & state) { uint16_t addr = state.readReg(addr_reg_id); if(isAccessViolation(addr, state)) { PIMicroOp msg = std::make_shared<PrintMessageMicroOp>("illegal memory access (ACV)"); PIMicroOp dec_pc = std::make_shared<PCAddImmMicroOp>(-1); std::pair<PIMicroOp, PIMicroOp> handle_exception_chain = buildSystemModeEnter(INTEX_TABLE_START, 0x2, lc3::utils::getBits(state.readPSR(), 10, 8)); PIMicroOp callback = std::make_shared<CallbackMicroOp>(CallbackType::EX_ENTER); PIMicroOp func_trace = std::make_shared<PushFuncTypeMicroOp>(FuncType::EXCEPTION); msg->insert(dec_pc); dec_pc->insert(handle_exception_chain.first); handle_exception_chain.second->insert(callback); callback->insert(func_trace); next = msg; } else { PIMicroOp op = state.writeMem(addr, value); if(op) { insert(op); } } } std::string MemWriteImmMicroOp::toString(MachineState const & state) const { return lc3::utils::ssprintf("MEM[%s:0x%0.4hx]:0x%0.4hx <= 0x%0.4hx", regToString(addr_reg_id).c_str(), state.readReg(addr_reg_id), std::get<0>(state.readMem(state.readReg(addr_reg_id))), value); } void MemWriteRegMicroOp::handleMicroOp(MachineState & state) { uint16_t addr = state.readReg(addr_reg_id); if(isAccessViolation(addr, state)) { PIMicroOp msg = std::make_shared<PrintMessageMicroOp>("illegal memory access (ACV)"); PIMicroOp dec_pc = std::make_shared<PCAddImmMicroOp>(-1); std::pair<PIMicroOp, PIMicroOp> handle_exception_chain = buildSystemModeEnter(INTEX_TABLE_START, 0x2, lc3::utils::getBits(state.readPSR(), 10, 8)); PIMicroOp callback = std::make_shared<CallbackMicroOp>(CallbackType::EX_ENTER); PIMicroOp func_trace = std::make_shared<PushFuncTypeMicroOp>(FuncType::EXCEPTION); msg->insert(dec_pc); dec_pc->insert(handle_exception_chain.first); handle_exception_chain.second->insert(callback); callback->insert(func_trace); next = msg; } else { PIMicroOp op = state.writeMem(addr, state.readReg(src_id)); if(op) { insert(op); } } } std::string MemWriteRegMicroOp::toString(MachineState const & state) const { return lc3::utils::ssprintf("MEM[%s:0x%0.4hx]:0x%0.4hx <= %s:0x%0.4hx", regToString(addr_reg_id).c_str(), state.readReg(addr_reg_id), std::get<0>(state.readMem(state.readReg(addr_reg_id))), regToString(src_id).c_str(), state.readReg(src_id)); } void CCUpdateRegMicroOp::handleMicroOp(MachineState & state) { uint16_t psr_value = state.readPSR(); char cc_char = getCCChar(state.readReg(reg_id)); if(cc_char == 'N') { state.writePSR((psr_value & 0xFFF8) | 0x0004); } else if(cc_char == 'Z') { state.writePSR((psr_value & 0xFFF8) | 0x0002); } else { state.writePSR((psr_value & 0xFFF8) | 0x0001); } } std::string CCUpdateRegMicroOp::toString(MachineState const & state) const { char cur_cc_char; uint16_t psr_value = state.readPSR(); if((psr_value & 0x0004) != 0) { cur_cc_char = 'N'; } else if((psr_value & 0x0002) != 0) { cur_cc_char = 'Z'; } else { cur_cc_char = 'P'; } return lc3::utils::ssprintf("CC:%c <= ComputeCC(0x%0.4hx):%c", cur_cc_char, state.readReg(reg_id), getCCChar(state.readReg(reg_id))); } char CCUpdateRegMicroOp::getCCChar(uint16_t value) const { if((value & 0x8000) != 0) { return 'N'; } else if(value == 0) { return 'Z'; } else { return 'P'; } } void BranchMicroOp::handleMicroOp(MachineState & state) { bool result = pred(state); if(result) { next = true_next; } else { next = false_next; } } std::string BranchMicroOp::toString(MachineState const & state) const { return lc3::utils::ssprintf("uBEN <= (%s):%s", msg.c_str(), pred(state) ? "true" : "false"); } PIMicroOp BranchMicroOp::insert(PIMicroOp new_next) { if(true_next) { true_next->insert(new_next); } if(false_next) { false_next->insert(new_next); } return new_next; } void CallbackMicroOp::handleMicroOp(MachineState & state) { state.addPendingCallback(type); } std::string CallbackMicroOp::toString(MachineState const & state) const { (void) state; return lc3::utils::ssprintf("callbacks <= %s", callbackTypeToString(type).c_str()); } void PushInterruptTypeMicroOp::handleMicroOp(MachineState & state) { state.enqueueInterrupt(type); } std::string PushInterruptTypeMicroOp::toString(MachineState const & state) const { (void) state; return lc3::utils::ssprintf("interrupts <= %s", interruptTypeToString(type).c_str()); } void PopInterruptTypeMicroOp::handleMicroOp(MachineState & state) { state.dequeueInterrupt(); } std::string PopInterruptTypeMicroOp::toString(MachineState const & state) const { (void) state; return lc3::utils::ssprintf("interrupts <= interrupts.removeFront()"); } void PushFuncTypeMicroOp::handleMicroOp(MachineState & state) { state.pushFuncTraceType(type); } std::string PushFuncTypeMicroOp::toString(MachineState const & state) const { (void) state; return lc3::utils::ssprintf("traceStack <= %s", funcTypeToString(type).c_str()); } void PopFuncTypeMicroOp::handleMicroOp(MachineState & state) { state.popFuncTraceType(); } std::string PopFuncTypeMicroOp::toString(MachineState const & state) const { (void) state; return lc3::utils::ssprintf("traceStack <= traceStack.removeTop()"); } void PrintMessageMicroOp::handleMicroOp(MachineState & state) { (void) state; } std::string PrintMessageMicroOp::toString(MachineState const & state) const { (void) state; return msg; }
32.088353
153
0.678285
jeroendebaat
0f0e9b93844e023f385638ced3d285c0538fd022
14,755
cpp
C++
DungeonsOfNoudar486/src/CRenderer_Tesselation.cpp
libretro/dungeons-of-noudar
40fe44c4a180d7daf3fe97eff4ddbfd2cd558c62
[ "BSD-2-Clause" ]
1
2020-12-25T01:06:43.000Z
2020-12-25T01:06:43.000Z
DungeonsOfNoudar486/src/CRenderer_Tesselation.cpp
libretro/dungeons-of-noudar
40fe44c4a180d7daf3fe97eff4ddbfd2cd558c62
[ "BSD-2-Clause" ]
null
null
null
DungeonsOfNoudar486/src/CRenderer_Tesselation.cpp
libretro/dungeons-of-noudar
40fe44c4a180d7daf3fe97eff4ddbfd2cd558c62
[ "BSD-2-Clause" ]
2
2020-08-17T16:13:01.000Z
2020-08-27T19:38:26.000Z
#include <cassert> #include <cstdlib> #include <cstdio> #include <cmath> #include <cstring> #include <string> #include <memory> #include <utility> #include <map> #include <unordered_map> #include <functional> #include <algorithm> #include <chrono> #include <sg14/fixed_point> #include <EASTL/vector.h> #include <EASTL/array.h> using sg14::fixed_point; using eastl::vector; using eastl::array; using namespace std::chrono; #include "NativeBitmap.h" #include "ETextures.h" #include "IFileLoaderDelegate.h" #include "NativeBitmap.h" #include "Vec2i.h" #include "IMapElement.h" #include "CTeam.h" #include "CItem.h" #include "CStorageItem.h" #include "CActor.h" #include "CGameDelegate.h" #include "MapWithCharKey.h" #include "CMap.h" #include "IRenderer.h" #include "RasterizerCommon.h" #include "IFileLoaderDelegate.h" #include "CGame.h" #include "CRenderer.h" #include "LoadPNG.h" #include "VisibilityStrategy.h" namespace odb { const static bool kShouldDrawOutline = false; const static bool kShouldDrawTextures = true; const static auto kMinZCull = FixP{1}; void CRenderer::projectAllVertices( uint8_t count ) { const static FixP halfWidth{HALF_XRES}; const static FixP halfHeight{HALF_YRES}; const static FixP two{2}; for ( auto& vertex : mVertices ) { if ( count-- == 0 ) { return; } const FixP oneOver = divide( halfHeight, divide(vertex.first.mZ, two) ); vertex.second.mX = halfWidth + multiply(vertex.first.mX, oneOver); vertex.second.mY = halfHeight - multiply(vertex.first.mY, oneOver); } } void CRenderer::drawCubeAt(const Vec3& center, TexturePair texture) { if (center.mZ <= kMinZCull) { return; } const static FixP one{ 1 }; mVertices[ 0 ].first = ( center + Vec3{ -one, -one, -one }); mVertices[ 1 ].first = ( center + Vec3{ one, -one, -one }); mVertices[ 2 ].first = ( center + Vec3{ -one, one, -one }); mVertices[ 3 ].first = ( center + Vec3{ one, one, -one }); mVertices[ 4 ].first = ( center + Vec3{ -one, -one, one }); mVertices[ 5 ].first = ( center + Vec3{ one, -one, one }); mVertices[ 6 ].first = ( center + Vec3{ -one, one, one }); mVertices[ 7 ].first = ( center + Vec3{ one, one, one }); projectAllVertices(8); const auto ulz0 = mVertices[0].second; const auto urz0 = mVertices[1].second; const auto llz0 = mVertices[2].second; const auto lrz0 = mVertices[3].second; const auto ulz1 = mVertices[4].second; const auto urz1 = mVertices[5].second; const auto llz1 = mVertices[6].second; const auto lrz1 = mVertices[7].second; if (static_cast<int>(center.mX) <= 0 ) { drawWall( urz0.mX, urz1.mX, urz0.mY, lrz0.mY, urz1.mY, lrz1.mY, texture.second, one); } if (static_cast<int>(center.mY) >= 0 ) { drawFloor(ulz1.mY, urz0.mY, ulz1.mX, urz1.mX, ulz0.mX, urz0.mX, texture.first); } if (static_cast<int>(center.mY) <= 0 ) { drawFloor(llz1.mY, lrz0.mY, llz1.mX, lrz1.mX, llz0.mX, lrz0.mX, texture.first); } if (static_cast<int>(center.mX) >= 0 ) { drawWall(ulz1.mX, ulz0.mX, ulz1.mY, llz1.mY, urz0.mY, lrz0.mY, texture.second, one); } drawWall( ulz0.mX, urz0.mX, ulz0.mY, llz0.mY, urz0.mY, lrz0.mY, texture.second, one ); } void CRenderer::drawBillboardAt(const Vec3 &center, std::shared_ptr<odb::NativeTexture> texture ) { if (center.mZ <= kMinZCull) { return; } const static FixP one{ 1 }; const static FixP two{ 2 }; const auto textureScale = one / two; const auto scaledCenter = Vec3{ center.mX, multiply(center.mY, one), center.mZ }; mVertices[ 0 ].first = ( scaledCenter + Vec3{ -one, two, 0 }); mVertices[ 1 ].first = ( scaledCenter + Vec3{ one, two, 0 }); mVertices[ 2 ].first = ( scaledCenter + Vec3{ -one, 0, 0 }); mVertices[ 3 ].first = ( scaledCenter + Vec3{ one, 0, 0 }); projectAllVertices(4); const auto ulz0 = mVertices[0].second; const auto urz0 = mVertices[1].second; const auto llz0 = mVertices[2].second; const auto lrz0 = mVertices[3].second; if (kShouldDrawTextures) { drawFrontWall( ulz0.mX, ulz0.mY, lrz0.mX, lrz0.mY, texture, (textureScale * two), true ); } if (kShouldDrawOutline) { drawLine( ulz0, urz0 ); drawLine( ulz0, llz0 ); drawLine( urz0, lrz0 ); drawLine( llz0, lrz0 ); } } void CRenderer::drawColumnAt(const Vec3 &center, const FixP &scale, TexturePair texture, bool mask[3],bool enableAlpha) { if (center.mZ <= kMinZCull) { return; } const static FixP one{ 1 }; const static FixP two{ 2 }; const auto halfScale = scale; const auto textureScale = halfScale / two; const auto scaledCenter = Vec3{ center.mX, multiply(center.mY, one), center.mZ }; // |\4 /|5 // | \ center / | // | \ * / | // | \0__|__1/ |7 // |6 | | | / // \ | X | / // \ | | / // \|2____3|/ mVertices[ 0 ].first = ( scaledCenter + Vec3{ -one, halfScale, -one }); mVertices[ 1 ].first = ( scaledCenter + Vec3{ one, halfScale, -one }); mVertices[ 2 ].first = ( scaledCenter + Vec3{ -one, -halfScale, -one }); mVertices[ 3 ].first = ( scaledCenter + Vec3{ one, -halfScale, -one }); mVertices[ 4 ].first = ( scaledCenter + Vec3{ -one, halfScale, one }); mVertices[ 5 ].first = ( scaledCenter + Vec3{ one, halfScale, one }); mVertices[ 6 ].first = ( scaledCenter + Vec3{ -one, -halfScale, one }); mVertices[ 7 ].first = ( scaledCenter + Vec3{ one, -halfScale, one }); projectAllVertices(8); const auto ulz0 = mVertices[0].second; const auto urz0 = mVertices[1].second; const auto llz0 = mVertices[2].second; const auto lrz0 = mVertices[3].second; const auto ulz1 = mVertices[4].second; const auto urz1 = mVertices[5].second; const auto llz1 = mVertices[6].second; const auto lrz1 = mVertices[7].second; if (kShouldDrawTextures) { if ( enableAlpha && mask[ 1 ] ) { drawFrontWall( ulz1.mX, ulz1.mY, lrz1.mX, lrz1.mY, texture.first, (textureScale * two), enableAlpha ); } if ( mask[0] && static_cast<int>(center.mX) < 0 ) { drawWall( urz0.mX, urz1.mX, urz0.mY, lrz0.mY, urz1.mY, lrz1.mY, texture.second, (textureScale * two)); } if ( mask[2] && static_cast<int>(center.mX) > 0 ) { drawWall(ulz1.mX, ulz0.mX, ulz1.mY, llz1.mY, urz0.mY, lrz0.mY, texture.second, (textureScale * two)); } if ( mask[ 1 ] ) { drawFrontWall( ulz0.mX, ulz0.mY, lrz0.mX, lrz0.mY, texture.first, (textureScale * two), enableAlpha ); } if ( mask[ 3 ] ) { drawMask( ulz0.mX, ulz0.mY, lrz0.mX, lrz0.mY); } } if (kShouldDrawOutline) { drawLine( ulz0, urz0 ); drawLine( ulz0, llz0 ); drawLine( urz0, lrz0 ); drawLine( llz0, lrz0 ); drawLine( ulz0, ulz1 ); drawLine( llz0, llz1 ); drawLine( ulz1, llz1 ); drawLine( urz0, urz1 ); drawLine( lrz0, lrz1 ); drawLine( urz1, lrz1 ); } } void CRenderer::drawFloorAt(const Vec3& center, TexturePair texture) { if (center.mZ <= kMinZCull) { return; } const static FixP one{ 1 }; mVertices[ 0 ].first = ( center + Vec3{ -one, 0, -one }); mVertices[ 1 ].first = ( center + Vec3{ one, 0, -one }); mVertices[ 2 ].first = ( center + Vec3{ -one, 0, one }); mVertices[ 3 ].first = ( center + Vec3{ one, 0, one }); projectAllVertices(4); const auto llz0 = mVertices[0].second; const auto lrz0 = mVertices[1].second; const auto llz1 = mVertices[2].second; const auto lrz1 = mVertices[3].second; if ( kShouldDrawTextures && static_cast<int>(center.mY) <= 0 ) { drawFloor(llz1.mY, lrz0.mY, llz1.mX, lrz1.mX, llz0.mX, lrz0.mX, texture.first); } if ( kShouldDrawOutline) { drawLine( llz0, lrz0 ); drawLine( llz0, llz1 ); drawLine( lrz0, lrz1 ); drawLine( llz1, lrz1 ); } } void CRenderer::drawCeilingAt(const Vec3& center, TexturePair texture) { if (center.mZ <= kMinZCull) { return; } const static FixP one{ 1 }; mVertices[ 0 ].first = ( center + Vec3{ -one, 0, -one }); mVertices[ 1 ].first = ( center + Vec3{ one, 0, -one }); mVertices[ 2 ].first = ( center + Vec3{ -one, 0, one }); mVertices[ 3 ].first = ( center + Vec3{ one, 0, one }); projectAllVertices(4); const auto llz0 = mVertices[0].second; const auto lrz0 = mVertices[1].second; const auto llz1 = mVertices[2].second; const auto lrz1 = mVertices[3].second; if ( kShouldDrawTextures && static_cast<int>(center.mY) >= 0 ) { drawFloor(llz1.mY, lrz0.mY, llz1.mX, lrz1.mX, llz0.mX, lrz0.mX, texture.first); } if (kShouldDrawOutline) { drawLine( llz0, lrz0 ); drawLine( llz0, llz1 ); drawLine( lrz0, lrz1 ); drawLine( llz1, lrz1 ); } } void CRenderer::drawLeftNear(const Vec3& center, const FixP &scale, std::shared_ptr<odb::NativeTexture> texture, bool mask[4]) { if (center.mZ <= kMinZCull) { return; } const static FixP one{ 1 }; const static FixP two{ 2 }; const auto halfScale = scale; const auto textureScale = halfScale; FixP depth{1}; if (mCameraDirection == Knights::EDirection::kWest || mCameraDirection == Knights::EDirection::kEast ) { depth = FixP{-1}; } mVertices[ 0 ].first = ( center + Vec3{ -one, halfScale, -depth }); mVertices[ 1 ].first = ( center + Vec3{ one, halfScale, depth }); mVertices[ 2 ].first = ( center + Vec3{ -one, -halfScale, -depth }); mVertices[ 3 ].first = ( center + Vec3{ one, -halfScale, depth }); projectAllVertices(4); const auto ulz0 = mVertices[0].second; const auto urz0 = mVertices[1].second; const auto llz0 = mVertices[2].second; const auto lrz0 = mVertices[3].second; if (kShouldDrawTextures) { drawWall( ulz0.mX, urz0.mX, ulz0.mY, llz0.mY, urz0.mY, lrz0.mY, texture, textureScale ); if (mask[3]) { mVertices[ 0 ].first = ( center + Vec3{ -one, -halfScale, -one }); mVertices[ 1 ].first = ( center + Vec3{ one, halfScale, -one }); projectAllVertices(2); drawMask( mVertices[ 0 ].second.mX, mVertices[ 0 ].second.mY, mVertices[ 1 ].second.mX, mVertices[ 1 ].second.mY); } } if (kShouldDrawOutline){ drawLine( ulz0, urz0 ); drawLine( llz0, ulz0 ); drawLine( llz0, lrz0 ); drawLine( urz0, lrz0 ); } } void CRenderer::drawRightNear(const Vec3& center, const FixP &scale, std::shared_ptr<odb::NativeTexture> texture, bool mask[4]) { if (center.mZ <= kMinZCull) { return; } const static FixP one{ 1 }; const static FixP two{ 2 }; const auto halfScale = scale; const auto textureScale = halfScale ; FixP depth{1}; if (mCameraDirection == Knights::EDirection::kWest || mCameraDirection == Knights::EDirection::kEast ) { depth = FixP{-1}; } mVertices[ 0 ].first = ( center + Vec3{ -one, halfScale, depth }); mVertices[ 1 ].first = ( center + Vec3{ one, halfScale, -depth }); mVertices[ 2 ].first = ( center + Vec3{ -one, -halfScale, depth }); mVertices[ 3 ].first = ( center + Vec3{ one, -halfScale, -depth }); projectAllVertices(4); const auto ulz0 = mVertices[0].second; const auto urz0 = mVertices[1].second; const auto llz0 = mVertices[2].second; const auto lrz0 = mVertices[3].second; if (kShouldDrawTextures) { drawWall( ulz0.mX, urz0.mX, ulz0.mY, llz0.mY, urz0.mY, lrz0.mY, texture, textureScale ); if (mask[3]) { mVertices[ 0 ].first = ( center + Vec3{ -one, -halfScale, -one }); mVertices[ 1 ].first = ( center + Vec3{ one, halfScale, -one }); projectAllVertices(2); drawMask( mVertices[ 0 ].second.mX, mVertices[ 0 ].second.mY, mVertices[ 1 ].second.mX, mVertices[ 1 ].second.mY); } } if (kShouldDrawOutline) { drawLine( ulz0, urz0 ); drawLine( llz0, ulz0 ); drawLine( llz0, lrz0 ); drawLine( urz0, lrz0 ); } } void CRenderer::drawLine(const Vec2& p0, const Vec2& p1) { drawLine(static_cast<int16_t >(p0.mX), static_cast<int16_t >(p0.mY), static_cast<int16_t >(p1.mX), static_cast<int16_t >(p1.mY) ); } }
32.428571
133
0.510878
libretro
0f10b1b9bde8b54535b9adda144c603e94b19c5c
5,127
cc
C++
test/cctest/heap/test-concurrent-marking.cc
YBApp-Bot/org_chromium_v8
de9efd579907d75b4599b33cfcc8c00468a72b9b
[ "BSD-3-Clause" ]
1
2019-04-25T17:50:34.000Z
2019-04-25T17:50:34.000Z
test/cctest/heap/test-concurrent-marking.cc
YBApp-Bot/org_chromium_v8
de9efd579907d75b4599b33cfcc8c00468a72b9b
[ "BSD-3-Clause" ]
null
null
null
test/cctest/heap/test-concurrent-marking.cc
YBApp-Bot/org_chromium_v8
de9efd579907d75b4599b33cfcc8c00468a72b9b
[ "BSD-3-Clause" ]
1
2018-11-28T07:47:41.000Z
2018-11-28T07:47:41.000Z
// Copyright 2017 the V8 project 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 <stdlib.h> #include "src/v8.h" #include "src/heap/concurrent-marking.h" #include "src/heap/heap-inl.h" #include "src/heap/heap.h" #include "src/heap/mark-compact.h" #include "src/heap/worklist.h" #include "test/cctest/cctest.h" #include "test/cctest/heap/heap-utils.h" namespace v8 { namespace internal { namespace heap { void PublishSegment(ConcurrentMarking::MarkingWorklist* worklist, HeapObject* object) { for (size_t i = 0; i <= ConcurrentMarking::MarkingWorklist::kSegmentCapacity; i++) { worklist->Push(0, object); } CHECK(worklist->Pop(0, &object)); } TEST(ConcurrentMarking) { if (!i::FLAG_concurrent_marking) return; CcTest::InitializeVM(); Heap* heap = CcTest::heap(); CcTest::CollectAllGarbage(); if (!heap->incremental_marking()->IsStopped()) return; MarkCompactCollector* collector = CcTest::heap()->mark_compact_collector(); if (collector->sweeping_in_progress()) { collector->EnsureSweepingCompleted(); } ConcurrentMarking::MarkingWorklist shared, bailout, on_hold; WeakObjects weak_objects; ConcurrentMarking* concurrent_marking = new ConcurrentMarking(heap, &shared, &bailout, &on_hold, &weak_objects); PublishSegment(&shared, ReadOnlyRoots(heap).undefined_value()); concurrent_marking->ScheduleTasks(); concurrent_marking->Stop( ConcurrentMarking::StopRequest::COMPLETE_TASKS_FOR_TESTING); delete concurrent_marking; } TEST(ConcurrentMarkingReschedule) { if (!i::FLAG_concurrent_marking) return; CcTest::InitializeVM(); Heap* heap = CcTest::heap(); CcTest::CollectAllGarbage(); if (!heap->incremental_marking()->IsStopped()) return; MarkCompactCollector* collector = CcTest::heap()->mark_compact_collector(); if (collector->sweeping_in_progress()) { collector->EnsureSweepingCompleted(); } ConcurrentMarking::MarkingWorklist shared, bailout, on_hold; WeakObjects weak_objects; ConcurrentMarking* concurrent_marking = new ConcurrentMarking(heap, &shared, &bailout, &on_hold, &weak_objects); PublishSegment(&shared, ReadOnlyRoots(heap).undefined_value()); concurrent_marking->ScheduleTasks(); concurrent_marking->Stop( ConcurrentMarking::StopRequest::COMPLETE_ONGOING_TASKS); PublishSegment(&shared, ReadOnlyRoots(heap).undefined_value()); concurrent_marking->RescheduleTasksIfNeeded(); concurrent_marking->Stop( ConcurrentMarking::StopRequest::COMPLETE_TASKS_FOR_TESTING); delete concurrent_marking; } TEST(ConcurrentMarkingPreemptAndReschedule) { if (!i::FLAG_concurrent_marking) return; CcTest::InitializeVM(); Heap* heap = CcTest::heap(); CcTest::CollectAllGarbage(); if (!heap->incremental_marking()->IsStopped()) return; MarkCompactCollector* collector = CcTest::heap()->mark_compact_collector(); if (collector->sweeping_in_progress()) { collector->EnsureSweepingCompleted(); } ConcurrentMarking::MarkingWorklist shared, bailout, on_hold; WeakObjects weak_objects; ConcurrentMarking* concurrent_marking = new ConcurrentMarking(heap, &shared, &bailout, &on_hold, &weak_objects); for (int i = 0; i < 5000; i++) PublishSegment(&shared, ReadOnlyRoots(heap).undefined_value()); concurrent_marking->ScheduleTasks(); concurrent_marking->Stop(ConcurrentMarking::StopRequest::PREEMPT_TASKS); for (int i = 0; i < 5000; i++) PublishSegment(&shared, ReadOnlyRoots(heap).undefined_value()); concurrent_marking->RescheduleTasksIfNeeded(); concurrent_marking->Stop( ConcurrentMarking::StopRequest::COMPLETE_TASKS_FOR_TESTING); delete concurrent_marking; } TEST(ConcurrentMarkingMarkedBytes) { if (!i::FLAG_concurrent_marking) return; CcTest::InitializeVM(); Isolate* isolate = CcTest::i_isolate(); Heap* heap = CcTest::heap(); HandleScope sc(isolate); Handle<FixedArray> root = isolate->factory()->NewFixedArray(1000000); CcTest::CollectAllGarbage(); if (!heap->incremental_marking()->IsStopped()) return; heap::SimulateIncrementalMarking(heap, false); heap->concurrent_marking()->Stop( ConcurrentMarking::StopRequest::COMPLETE_TASKS_FOR_TESTING); CHECK_GE(heap->concurrent_marking()->TotalMarkedBytes(), root->Size()); } UNINITIALIZED_TEST(ConcurrentMarkingStoppedOnTeardown) { if (!i::FLAG_concurrent_marking) return; v8::Isolate::CreateParams create_params; create_params.array_buffer_allocator = CcTest::array_buffer_allocator(); v8::Isolate* isolate = v8::Isolate::New(create_params); { Isolate* i_isolate = reinterpret_cast<Isolate*>(isolate); Factory* factory = i_isolate->factory(); v8::Isolate::Scope isolate_scope(isolate); v8::HandleScope handle_scope(isolate); v8::Context::New(isolate)->Enter(); for (int i = 0; i < 10000; i++) { factory->NewJSWeakMap(); } Heap* heap = i_isolate->heap(); heap::SimulateIncrementalMarking(heap, false); } isolate->Dispose(); } } // namespace heap } // namespace internal } // namespace v8
34.409396
79
0.736883
YBApp-Bot
0f1220db98a4d9c01264add6c01eefb52615a0fd
6,900
cpp
C++
toonz/sources/toonzlib/txshsoundlevel.cpp
jhonsu01/opentoonz
b8b0f90055ae6a54fc5926c46a063d460c9884d7
[ "BSD-3-Clause" ]
null
null
null
toonz/sources/toonzlib/txshsoundlevel.cpp
jhonsu01/opentoonz
b8b0f90055ae6a54fc5926c46a063d460c9884d7
[ "BSD-3-Clause" ]
null
null
null
toonz/sources/toonzlib/txshsoundlevel.cpp
jhonsu01/opentoonz
b8b0f90055ae6a54fc5926c46a063d460c9884d7
[ "BSD-3-Clause" ]
null
null
null
#include "toonz/txshsoundlevel.h" #include "tsound_io.h" #include "toonz/toonzscene.h" #include "toonz/sceneproperties.h" #include "toonz/txshleveltypes.h" #include "tstream.h" #include "toutputproperties.h" #include "tconvert.h" //----------------------------------------------------------------------------- DEFINE_CLASS_CODE(TXshSoundLevel, 53) PERSIST_IDENTIFIER(TXshSoundLevel, "soundLevel") //============================================================================= TXshSoundLevel::TXshSoundLevel(std::wstring name, int startOffset, int endOffset) : TXshLevel(m_classCode, name) , m_soundTrack(0) , m_duration(0) , m_samplePerFrame(0) , m_frameSoundCount(0) , m_fps(12) , m_path() {} //----------------------------------------------------------------------------- TXshSoundLevel::~TXshSoundLevel() {} //----------------------------------------------------------------------------- TXshSoundLevel *TXshSoundLevel::clone() const { TXshSoundLevel *sound = new TXshSoundLevel(); sound->setSoundTrack(m_soundTrack->clone()); sound->m_duration = m_duration; sound->m_path = m_path; sound->m_samplePerFrame = m_samplePerFrame; sound->m_frameSoundCount = m_frameSoundCount; sound->m_fps = m_fps; return sound; } //----------------------------------------------------------------------------- void TXshSoundLevel::setScene(ToonzScene *scene) { assert(scene); TXshLevel::setScene(scene); TOutputProperties *properties = scene->getProperties()->getOutputProperties(); assert(properties); setFrameRate(properties->getFrameRate()); } //----------------------------------------------------------------------------- void TXshSoundLevel::loadSoundTrack() { assert(getScene()); TSceneProperties *properties = getScene()->getProperties(); if (properties) { TOutputProperties *outputProperties = properties->getOutputProperties(); if (outputProperties) m_fps = outputProperties->getFrameRate(); } TFilePath path = getScene()->decodeFilePath(m_path); try { loadSoundTrack(path); } catch (TException &e) { throw TException(e.getMessage()); } } //----------------------------------------------------------------------------- void TXshSoundLevel::loadSoundTrack(const TFilePath &fileName) { try { TSoundTrackP st; TFilePath path(fileName); bool ret = TSoundTrackReader::load(path, st); if (ret) { m_duration = st->getDuration(); setName(fileName.getWideName()); setSoundTrack(st); } } catch (TException &) { return; } } //----------------------------------------------------------------------------- void TXshSoundLevel::load() { loadSoundTrack(); } //----------------------------------------------------------------------------- void TXshSoundLevel::save() { save(m_path); } //----------------------------------------------------------------------------- void TXshSoundLevel::save(const TFilePath &path) { TSoundTrackWriter::save(path, m_soundTrack); } //----------------------------------------------------------------------------- void TXshSoundLevel::loadData(TIStream &is) { is >> m_name; setName(m_name); std::string tagName; bool flag = false; int type = UNKNOWN_XSHLEVEL; for (;;) { if (is.matchTag(tagName)) { if (tagName == "path") { is >> m_path; is.matchEndTag(); } else if (tagName == "type") { std::string v; is >> v; if (v == "sound") type = SND_XSHLEVEL; is.matchEndTag(); } else throw TException("unexpected tag " + tagName); } else break; } setType(type); } //----------------------------------------------------------------------------- void TXshSoundLevel::saveData(TOStream &os) { os << m_name; std::map<std::string, std::string> attr; os.child("type") << L"sound"; os.child("path") << m_path; } //----------------------------------------------------------------------------- void TXshSoundLevel::computeValues(int frameHeight) { if (frameHeight == 0) frameHeight = 1; m_values.clear(); if (!m_soundTrack) { m_frameSoundCount = 0; m_samplePerFrame = 0; return; } m_samplePerFrame = m_soundTrack->getSampleRate() / m_fps; double samplePerPixel = m_samplePerFrame / frameHeight; int sampleCount = m_soundTrack->getSampleCount(); if (sampleCount <= 0) // This was if(!sampleCount) :( return; // m_frameSoundCount = tceil(sampleCount / m_samplePerFrame); double maxPressure = 0.0; double minPressure = 0.0; m_soundTrack->getMinMaxPressure(TINT32(0), (TINT32)sampleCount, TSound::LEFT, minPressure, maxPressure); double absMaxPressure = std::max(fabs(minPressure), fabs(maxPressure)); if (absMaxPressure <= 0) return; // Adjusting using a fixed scaleFactor double weightA = 20.0 / absMaxPressure; long i = 0, j; long p = 0; // se p parte da zero notazione per pixel, // se parte da 1 notazione per frame while (i < m_frameSoundCount) { for (j = 0; j < frameHeight - 1; ++j) { double min = 0.0; double max = 0.0; m_soundTrack->getMinMaxPressure( (TINT32)(i * m_samplePerFrame + j * samplePerPixel), (TINT32)(i * m_samplePerFrame + (j + 1) * samplePerPixel - 1), TSound::MONO, min, max); m_values.insert(std::pair<int, std::pair<double, double>>( p + j, std::pair<double, double>(min * weightA, max * weightA))); } double min = 0.0; double max = 0.0; m_soundTrack->getMinMaxPressure( (TINT32)(i * m_samplePerFrame + j * samplePerPixel), (TINT32)((i + 1) * m_samplePerFrame - 1), TSound::MONO, min, max); m_values.insert(std::pair<int, std::pair<double, double>>( p + j, std::pair<double, double>(min * weightA, max * weightA))); ++i; p += frameHeight; } } //----------------------------------------------------------------------------- void TXshSoundLevel::getValueAtPixel(int pixel, DoublePair &values) const { std::map<int, DoublePair>::const_iterator it = m_values.find(pixel); if (it != m_values.end()) values = it->second; } //----------------------------------------------------------------------------- void TXshSoundLevel::setFrameRate(double fps) { if (m_fps != fps) { m_fps = fps; computeValues(); } } //----------------------------------------------------------------------------- int TXshSoundLevel::getFrameCount() const { int frameCount = m_duration * m_fps; return (frameCount == 0) ? 1 : frameCount; } //----------------------------------------------------------------------------- // Implementato per utilita' void TXshSoundLevel::getFids(std::vector<TFrameId> &fids) const { int i; for (i = 0; i < getFrameCount(); i++) fids.push_back(TFrameId(i)); }
29.237288
80
0.51913
jhonsu01
0f1248f1cc04475c9c56f11c28f8e637ece37de1
15,808
cpp
C++
immBodyDistanceSmooth.cpp
TomLKoller/Boxplus-IMM
4f610967b8b9d3ed5b7110db7019d2acbc8ca57b
[ "MIT" ]
4
2021-07-16T08:50:46.000Z
2021-09-13T13:45:56.000Z
immBodyDistanceSmooth.cpp
TomLKoller/Boxplus-IMM
4f610967b8b9d3ed5b7110db7019d2acbc8ca57b
[ "MIT" ]
3
2021-07-16T06:50:19.000Z
2021-10-04T13:37:04.000Z
immBodyDistanceSmooth.cpp
TomLKoller/Boxplus-IMM
4f610967b8b9d3ed5b7110db7019d2acbc8ca57b
[ "MIT" ]
1
2020-07-17T08:39:15.000Z
2020-07-17T08:39:15.000Z
#include "ADEKF.h" #include "ManifoldCreator.h" #include "types/SO3.h" #include "adekf_viz.h" #include "PoseRenderer.h" #include "BPIMM.h" #include "BPRTSIMM.h" #include "PathCreatorOrientation.h" #include "SimulatedBodyMeas.h" #include "GaussianNoiseVector.h" #include <numeric> #define GRAVITY_CONSTANT 9.81 //#define SHOW_VIZ //Declaration of State ADEKF_MANIFOLD(CT_State, ((adekf::SO3, rotate_world_to_body)), (3, w_position), (3, w_velocity), (3, w_angular_rate)) ADEKF_MANIFOLD(Sub_State, ((adekf::SO3, rotate_world_to_body)), (3, w_position)) //Declaration of measurement ADEKF_MANIFOLD(Radar4, , (3, radar1), (3, radar2), (3, radar3), (3, radar4)) #include "NAIVE_IMM.h" #include "Naive_RTSIMM.h" #include "rts-smoother.hpp" #include "naive_rts-smoother.hpp" //#define EKS //#define MEKS #define RTSIMMS #define NIMMS #define EKF_MODEL constant_turn_model #define EKF_SIGMA ct_sigma #define NOISE_ON_CONSTANT_TURN 0.//10. for consistent evaluation // 0 for original implementation /** * The constant turn model function. */ struct constant_turn_model { /** * Implements the constant turn dynamic. * @tparam T The Scalar type (required for auto diff) * @tparam Noise The type of the noise vector * @param state The state * @param noise The noise vector to apply the non additive noise * @param deltaT The time difference since the last measurement. */ template <typename T, typename Noise> void operator()(CT_State<T> &state, const Noise &noise, double deltaT) { //pre calculate values T omega = norm(state.w_angular_rate); T c1 = omega == 0. ? -pow(deltaT, 2) * cos(omega * deltaT) / 2. : (cos(omega * deltaT) - 1.) / pow(omega, 2); T c2 = omega == 0. ? deltaT * cos(omega * deltaT) : sin(omega * deltaT) / omega; T c3 = omega == 0. ? -pow(deltaT, 3) * cos(omega * deltaT) / 6. : 1. / pow(omega, 2) * (sin(omega * deltaT) / omega - deltaT); T wx = state.w_angular_rate.x(), wy = state.w_angular_rate.y(), wz = state.w_angular_rate.z(); T d1 = pow(wy, 2) + pow(wz, 2); T d2 = pow(wx, 2) + pow(wz, 2); T d3 = pow(wx, 2) + pow(wy, 2); //calcualte A and B Matrix according to [2] Eigen::Matrix<T, 3, 3> A, B; A << c1 * d1, -c2 * wz - c1 * wx * wy, c2 * wy - c1 * wx * wz, c2 * wz - c1 * wx * wy, c1 * d2, -c2 * wx - c1 * wy * wz, -c2 * wy - c1 * wx * wz, c2 * wx - c1 * wy * wz, c1 * d3; B << c3 * d1, c1 * wz - c3 * wx * wy, -c1 * wy - c3 * wx * wz, -c1 * wz - c3 * wx * wy, c3 * d2, c1 * wx - c3 * wy * wz, c1 * wy - c3 * wx * wz, -c1 * wx - c3 * wy * wz, c3 * d3; //Implement constant turn dynamic state.w_position += B * state.w_velocity + state.w_velocity * deltaT+NOISE(3,3)*deltaT; state.w_velocity += A * state.w_velocity; state.rotate_world_to_body = state.rotate_world_to_body * adekf::SO3(state.w_angular_rate * deltaT).conjugate(); state.w_angular_rate += NOISE(0,3) * deltaT; }; //Create static object } constant_turn_model; /** * Performs the simulation of a flying drone with camera. * @param argc argument counter * @param argv command line arguments * @return 0 */ int main(int argc, char *argv[]) { constexpr double deltaT = 0.05; PathCreator path{deltaT, 10}; //Setup covariance of constant turn model adekf::SquareMatrixType<double, 6> ct_sigma = ct_sigma.Identity() * 0.1; (ct_sigma.block<3,3>(3,3))=Eigen::Matrix3d::Identity()*NOISE_ON_CONSTANT_TURN; //straight model auto straight_model = [](auto &state, auto noise, double deltaT) { state.w_velocity += NOISE(0,3) * deltaT; state.w_position += state.w_velocity * deltaT; //orientation and angular rate stay constant }; //Setup covariance of straight model adekf::SquareMatrixType<double, 6> sm_sigma = sm_sigma.Identity() * 10; auto free_model = [](auto &state, auto noise, double deltaT) { state.w_velocity += NOISE(0, 3) * deltaT; state.w_position += state.w_velocity * deltaT; state.w_angular_rate += NOISE(3, 3) * deltaT; state.rotate_world_to_body = state.rotate_world_to_body * adekf::SO3(state.w_angular_rate * deltaT).conjugate(); }; Eigen::Matrix<double, 6, 1> fm_diag; fm_diag << 10., 10., 10., .1, .1, .1; Eigen::Matrix<double, 6, 6> fm_sigma = fm_diag.asDiagonal(); //Setup landmarks. SimulatedRadar radar1(Eigen::Vector3d(0, 40, -150)), radar2(Eigen::Vector3d(-120, 40, -150)), radar3(Eigen::Vector3d(-30, 0, -150)), radar4(Eigen::Vector3d(-90, 80, -150)); //measurement model of 4 simultaneous landmark measurements auto radar_model = [](auto &&state, const SimulatedRadar &radar1, const SimulatedRadar &radar2, const SimulatedRadar &radar3, const SimulatedRadar &radar4) { return Radar4{radar1.getRadar<ScalarOf(state)>(state.w_position, state.rotate_world_to_body), radar2.getRadar<ScalarOf(state)>(state.w_position, state.rotate_world_to_body), radar3.getRadar<ScalarOf(state)>(state.w_position, state.rotate_world_to_body), radar4.getRadar<ScalarOf(state)>(state.w_position, state.rotate_world_to_body)}; }; double rad_sigma = 1; GaussianNoiseVector radar_noise(0, rad_sigma, rad_sigma, rad_sigma); //Setup noise of measurement Eigen::Matrix<double, 12, 12> rm4_sigma = rm4_sigma.Zero(); rm4_sigma.block<3, 3>(0, 0) = rm4_sigma.block<3, 3>(3, 3) = rm4_sigma.block<3, 3>(6, 6) = rm4_sigma.block<3, 3>(9, 9) = radar_noise.getCov(); constexpr size_t monte_carlo_runs = 100; std::map<const char *, adekf::aligned_vector<Eigen::Matrix<double, 6, 1> > > metrics; for (size_t run_number = 0; run_number < monte_carlo_runs; run_number++) { //Setup ekf adekf::ADEKF ekf{CT_State<double>(), Eigen::Matrix<double, 12, 12>::Identity()}; ekf.mu.w_velocity.x() = 10.; ekf.mu.w_position=path.path[0]; ekf.mu.w_angular_rate.z() = 0.0; //Setup Smoother adekf::RTS_Smoother smoother{ekf}; adekf::Naive_RTS_Smoother naive_smoother{ekf}; #if defined(RTSIMMS) || defined(NIMMS) //setup BP RTS IMM adekf::BPRTSIMM rts_imm{ekf.mu, ekf.sigma, {sm_sigma, ct_sigma}, straight_model, constant_turn_model}; adekf::Naive_RTSIMM naive_imm{ekf.mu, ekf.sigma, {sm_sigma, ct_sigma}, straight_model, constant_turn_model}; rts_imm.addFilters({0, 1}); naive_imm.addFilters({0, 1}); //Setup of start conditions Eigen::Matrix<double, 2, 2> t_prob; t_prob << 0.95, 0.05, 0.05, 0.95; rts_imm.setTransitionProbabilities(t_prob); naive_imm.setTransitionProbabilities(t_prob); Eigen::Vector2d start_prob(0.5, 0.5); rts_imm.setStartProbabilities(start_prob); naive_imm.setStartProbabilities(start_prob); #endif //IMMS auto calcConsistency = [](auto &&filter_state, auto &&sigma, auto &&gt) { auto diff = (filter_state - gt).eval(); return (diff.transpose() * sigma.inverse() * diff)(0); }; adekf::aligned_vector<Radar4<double>> all_measurements; auto calcPerformanceMetrics = [&](auto &filter, const char *title, auto &stateGetter, auto &sigmaGetter) { double rmse_pos = 0., rmse_orient = 0., consistency_state = 0., consistency_measurement = 0.; Eigen::Matrix<double, 6, 1> state_delta = state_delta.Zero(); Radar4<double>::DeltaType<double> meas_delta = meas_delta.Zero(); size_t size = path.path.size(); for (size_t i = 0; i < size; i++) { auto way_point = path.path[i]; auto orient = path.orientations[i].conjugate(); auto mu = stateGetter(filter, i); rmse_pos += pow((mu.w_position - way_point).norm(), 2); rmse_orient += pow((mu.rotate_world_to_body - orient).norm(), 2); state_delta.segment<3>(0) += mu.rotate_world_to_body - orient; state_delta.segment<3>(3) += mu.w_position - way_point; consistency_state += calcConsistency(Sub_State{mu.rotate_world_to_body, mu.w_position}, sigmaGetter(filter, i).template block<6, 6>(0, 0), Sub_State{orient, way_point}); //consistency_state+=calcConsistency(mu.w_position,sigmaGetter(filter,i).template block<3,3>(3,3),way_point); Radar4<double> expected_meas = radar_model(mu, radar1, radar2, radar3, radar4); meas_delta += expected_meas - all_measurements[i]; auto input = radar_model(adekf::eval(mu + adekf::getDerivator<CT_State<double>::DOF>()), radar1, radar2, radar3, radar4).vector_part; auto H=adekf::extractJacobi(input); consistency_measurement += calcConsistency(all_measurements[i], H * sigmaGetter(filter, i) * H.transpose() + rm4_sigma, expected_meas); } Eigen::Matrix<double, 6, 1> metric_values; metric_values << sqrt(rmse_pos / size), sqrt(rmse_orient / size), state_delta.norm() / size, consistency_state / size, meas_delta.norm() / size, consistency_measurement / size; auto metric = metrics.find(title); if (metric == metrics.end()) { metrics.emplace(title, adekf::aligned_vector<Eigen::Matrix<double, 6, 1> >()); metric=metrics.find(title); } metric->second.push_back( metric_values); if (run_number == monte_carlo_runs - 1) { Eigen::Matrix<double,6,1> zeros=zeros.Zero(); // Is instantiated before so it has the type Eigen::Matrix instead of cwise nullary exp. Deduces wrong type in accumulate otherwise. Eigen::Matrix<double,6,1> mean=std::accumulate(metric->second.begin(),metric->second.end(),zeros)/monte_carlo_runs; Eigen::Matrix<double,6,1> sigma=std::accumulate(metric->second.begin(),metric->second.end(),zeros,[&](const auto & a, const auto & b){ auto diff=b-mean; return a+diff*diff.transpose().diagonal(); })/monte_carlo_runs; std::cout << setprecision(6) << title << " Performance values: " << std::endl << "\t Pos RMSE: " << mean(0) << "\t Orient RMSE: " << mean(1) << "\t Mu bias: " << mean(2) << "\t Mu Cons: " << mean(3) << "\t Z bias: " << mean(4) << "\t Z Cons: " << mean(5) << std::endl; std::cout << sigma.transpose()<< std::endl; } }; std::vector<std::tuple<double>> all_controls; for (size_t i = 1; i < path.path.size(); i++) { //read Ground truth path auto way_point = path.path[i]; auto orient = path.orientations[i].conjugate(); all_controls.emplace_back(deltaT); Radar4<double> target{(radar1.getRadar(way_point, orient) + radar_noise.poll()), (radar2.getRadar(way_point, orient) + radar_noise.poll()), (radar3.getRadar(way_point, orient) + radar_noise.poll()), (radar4.getRadar(way_point, orient) + radar_noise.poll())}; all_measurements.push_back(target); #ifdef RTSIMMS //RTSIMM rts_imm.interaction(); rts_imm.predictWithNonAdditiveNoise(deltaT); rts_imm.update(radar_model, rm4_sigma, target, radar1, radar2, radar3, radar4); rts_imm.combination(); rts_imm.storeEstimation(); #endif #ifdef NIMMS //Naive IMM naive_imm.interaction(); naive_imm.predictWithNonAdditiveNoise(deltaT); naive_imm.update(radar_model, rm4_sigma, target, radar1, radar2, radar3, radar4); naive_imm.combination(); naive_imm.storeEstimation(); #endif #ifdef EKS //[+]-EKS smoother.predictWithNonAdditiveNoise(EKF_MODEL, EKF_SIGMA, deltaT); smoother.storePredictedEstimation(); smoother.update(radar_model, rm4_sigma, target, radar1, radar2, radar3, radar4); smoother.storeEstimation(); #endif //(M)-EKS #ifdef MEKS naive_smoother.predictWithNonAdditiveNoise(EKF_MODEL, EKF_SIGMA, deltaT); naive_smoother.storePredictedEstimation(); naive_smoother.update(radar_model, rm4_sigma, target, radar1, radar2, radar3, radar4); naive_smoother.storeEstimation(); #endif } //Getters for calc metrics auto getOldMu = [](auto &filter, int i) { return filter.old_mus[i]; }; auto getOldSigma = [](auto &filter, int i) { return filter.old_sigmas[i]; }; auto getSmoothedMu = [](auto &filter, int i) { return filter.smoothed_mus[i]; }; auto getSmoothedSigma = [](auto &filter, int i) { return filter.smoothed_sigmas[i]; }; //call all smoothers //Call metrics for each filter #ifdef EKS smoother.smoothAllWithNonAdditiveNoise(EKF_MODEL, EKF_SIGMA, all_controls); calcPerformanceMetrics(smoother, "[+]-EKF", getOldMu, getOldSigma); calcPerformanceMetrics(smoother, "[+]-EKS", getSmoothedMu, getSmoothedSigma); #endif #ifdef MEKS naive_smoother.smoothAllWithNonAdditiveNoise(EKF_MODEL, EKF_SIGMA, all_controls); calcPerformanceMetrics(naive_smoother, "(M)-EKS", getSmoothedMu, getSmoothedSigma); #endif #ifdef RTSIMMS rts_imm.smoothAllWithNonAdditiveNoise(all_controls); calcPerformanceMetrics(rts_imm, "[+]-IMM", getOldMu, getOldSigma); calcPerformanceMetrics(rts_imm, "[+]-RTSIMMS", getSmoothedMu, getSmoothedSigma); #endif #ifdef NIMMS naive_imm.smoothAllWithNonAdditiveNoise(all_controls); calcPerformanceMetrics(naive_imm, "Naive-IMM", getOldMu, getOldSigma); calcPerformanceMetrics(naive_imm, "Naive-(M)-RTSIMMS", getSmoothedMu, getSmoothedSigma); #endif //#define SHOW_VIZ #ifdef SHOW_VIZ //Currently not working //Vectors to store path for evaluation std::vector<Eigen::Vector3d, Eigen::aligned_allocator<Eigen::Vector3d>> ekf_estimated_poses, imm_estimated_poses, rts_imm_estimated_poses, smoother_estimated_poses; //visualize paths adekf::viz::initGuis(argc, argv); adekf::viz::PoseRenderer::displayPath(path.path, "red"); for(auto state: smoother.old_mus){ ekf_estimated_poses.push_back(state.w_position); } adekf::viz::PoseRenderer::displayPath(ekf_estimated_poses, "black"); /*adekf::viz::PoseRenderer::displayPath(imm_estimated_poses, "green"); adekf::viz::PoseRenderer::displayPath(rts_imm_estimated_poses, "blue"); adekf::viz::PoseRenderer::displayPath(smoother_estimated_poses, "orange");*/ adekf::viz::PoseRenderer::displayPoints({radar1.position, radar2.position, radar3.position, radar4.position}, "red", 5); adekf::viz::runGuis(); #endif //SHOW_VIZ } std::cout << "Naive indefinite Counter: " << adekf::Naive_RTS_Smoother<CT_State<double>>::indefinite_counter << std::endl; std::cout << "[+] indefinite Counter: " << adekf::RTS_Smoother<CT_State<double>>::indefinite_counter << std::endl; return 0; }
48.490798
194
0.615764
TomLKoller
0f15557a9db6ed816e38a74ceee775aa107e0cbd
3,708
cpp
C++
src/vulkan-renderer/io/byte_stream.cpp
JoseETeixeira/vulkan-renderer
982e8004d9269ab1ffb1b7e8da03b351136985c9
[ "MIT" ]
443
2019-12-26T03:24:17.000Z
2022-03-29T07:55:01.000Z
src/vulkan-renderer/io/byte_stream.cpp
JoseETeixeira/vulkan-renderer
982e8004d9269ab1ffb1b7e8da03b351136985c9
[ "MIT" ]
384
2019-12-12T13:08:02.000Z
2022-03-28T19:57:11.000Z
src/vulkan-renderer/io/byte_stream.cpp
JoseETeixeira/vulkan-renderer
982e8004d9269ab1ffb1b7e8da03b351136985c9
[ "MIT" ]
36
2020-03-31T11:44:28.000Z
2022-03-12T08:44:25.000Z
#include "inexor/vulkan-renderer/io/byte_stream.hpp" #include "inexor/vulkan-renderer/world/cube.hpp" #include <fstream> namespace inexor::vulkan_renderer::io { std::vector<std::uint8_t> ByteStream::read_file(const std::filesystem::path &path) { std::ifstream stream(path, std::ios::in | std::ios::binary); return {std::istreambuf_iterator<char>(stream), std::istreambuf_iterator<char>()}; } ByteStream::ByteStream(std::vector<std::uint8_t> buffer) : m_buffer(std::move(buffer)) {} ByteStream::ByteStream(const std::filesystem::path &path) : ByteStream(read_file(path)) {} std::size_t ByteStream::size() const { return m_buffer.size(); } const std::vector<std::uint8_t> &ByteStream::buffer() const { return m_buffer; } void ByteStreamReader::check_end(const std::size_t size) const { if (static_cast<std::size_t>(std::distance(m_iter, m_stream.buffer().end())) < size) { throw std::runtime_error("end would be overrun"); } } ByteStreamReader::ByteStreamReader(const ByteStream &stream) : m_stream(stream), m_iter(stream.buffer().begin()) {} void ByteStreamReader::skip(const std::size_t size) { const std::size_t skip = std::min( size, std::size_t(std::distance<std::vector<std::uint8_t>::const_iterator>(m_iter, m_stream.buffer().end()))); std::advance(m_iter, skip); } std::size_t ByteStreamReader::remaining() const { return std::distance<std::vector<std::uint8_t>::const_iterator>(m_iter, m_stream.buffer().end()); } template <> std::uint8_t ByteStreamReader::read() { check_end(1); return *m_iter++; } template <> std::uint32_t ByteStreamReader::read() { check_end(4); return (*m_iter++ << 0u) | (*m_iter++ << 8u) | (*m_iter++ << 16u) | (*m_iter++ << 24u); } template <> std::string ByteStreamReader::read(const std::size_t &size) { check_end(size); auto start = m_iter; std::advance(m_iter, size); return std::string(start, m_iter); } template <> world::Cube::Type ByteStreamReader::read() { return static_cast<world::Cube::Type>(read<std::uint8_t>()); } template <> std::array<world::Indentation, 12> ByteStreamReader::read() { check_end(9); std::array<world::Indentation, 12> indentations; auto writer = indentations.begin(); // NOLINT const auto end = m_iter + 9; while (m_iter != end) { *writer++ = world::Indentation(*m_iter >> 2u); *writer++ = world::Indentation(((*m_iter & 0b00000011u) << 4u) | (*(++m_iter) >> 4u)); *writer++ = world::Indentation(((*m_iter & 0b00001111u) << 2u) | (*(++m_iter) >> 6u)); *writer++ = world::Indentation(*m_iter++ & 0b00111111u); } return indentations; } template <> void ByteStreamWriter::write(const std::uint8_t &value) { m_buffer.emplace_back(value); } template <> void ByteStreamWriter::write(const std::uint32_t &value) { m_buffer.emplace_back(value >> 24u); m_buffer.emplace_back(value >> 16u); m_buffer.emplace_back(value >> 8u); m_buffer.emplace_back(value); } template <> void ByteStreamWriter::write(const std::string &value) { std::copy(value.begin(), value.end(), std::back_inserter(m_buffer)); } template <> void ByteStreamWriter::write(const world::Cube::Type &value) { write(static_cast<std::uint8_t>(value)); } template <> void ByteStreamWriter::write(const std::array<world::Indentation, 12> &value) { for (auto iter = value.begin(); iter != value.end(); iter++) { // NOLINT write<std::uint8_t>((iter->uid() << 2u) | ((++iter)->uid() >> 4)); write<std::uint8_t>((iter->uid() << 4u) | ((++iter)->uid() >> 2)); write<std::uint8_t>((iter->uid() << 6u) | ((++iter)->uid())); } } } // namespace inexor::vulkan_renderer::io
32.814159
118
0.657497
JoseETeixeira
0f16ed5b02cce189a93288242bb5484e17a0150a
3,614
cpp
C++
test/module/irohad/consensus/yac/yac_synchronization_test.cpp
akshatkarani/iroha
5acef9dd74720c6185360d951e9b11be4ef73260
[ "Apache-2.0" ]
1
2020-05-15T10:02:38.000Z
2020-05-15T10:02:38.000Z
test/module/irohad/consensus/yac/yac_synchronization_test.cpp
akshatkarani/iroha
5acef9dd74720c6185360d951e9b11be4ef73260
[ "Apache-2.0" ]
2
2020-02-18T11:25:35.000Z
2020-02-20T04:09:45.000Z
test/module/irohad/consensus/yac/yac_synchronization_test.cpp
akshatkarani/iroha
5acef9dd74720c6185360d951e9b11be4ef73260
[ "Apache-2.0" ]
1
2020-07-25T11:15:16.000Z
2020-07-25T11:15:16.000Z
/** * Copyright Soramitsu Co., Ltd. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0 */ #include "module/irohad/consensus/yac/yac_fixture.hpp" #include "common/hexutils.hpp" using namespace iroha::consensus::yac; using ::testing::_; using ::testing::Return; /** * The class helps to create fake network for unit testing of consensus */ class NetworkUtil { public: /// creates fake network of number_of_peers size NetworkUtil(size_t number_of_peers) { for (size_t i = 0; i < number_of_peers; ++i) { peers_.push_back(makePeer(std::to_string(i))); } order_ = ClusterOrdering::create(peers_); } auto createHash(const iroha::consensus::Round &r, const std::string &block_hash = "default_block", const std::string &proposal_hash = "default_proposal") const { return YacHash(r, proposal_hash, block_hash); } auto createVote(size_t from, const YacHash &yac_hash) const { BOOST_ASSERT_MSG(from < peers_.size(), "Requested unknown index of peer"); return iroha::consensus::yac::createVote( yac_hash, *iroha::hexstringToBytestring(peers_.at(from)->pubkey().hex())); } /// create votes of peers by their number auto createVotes( const std::vector<size_t> &peers, const iroha::consensus::Round &r, const std::string &block_hash = "default_block", const std::string &proposal_hash = "default_proposal") const { std::vector<VoteMessage> result; for (auto &peer_number : peers) { result.push_back( createVote(peer_number, createHash(r, block_hash, proposal_hash))); } return result; } std::vector<std::shared_ptr<shared_model::interface::Peer>> peers_; boost::optional<ClusterOrdering> order_; }; class YacSynchronizationTest : public YacTest { public: void SetUp() override { YacTest::SetUp(); network_util_ = NetworkUtil(7); initAndCommitState(network_util_); } /// inits initial state and commits some rounds void initAndCommitState(const NetworkUtil &network_util) { size_t number_of_committed_rounds = 10; initYac(*network_util.order_); EXPECT_CALL(*crypto, verify(_)).WillRepeatedly(Return(true)); EXPECT_CALL(*timer, deny()).Times(number_of_committed_rounds); for (auto i = 0u; i < number_of_committed_rounds; i++) { iroha::consensus::Round r{i, 0}; yac->vote(network_util.createHash(r), *network_util.order_); yac->onState(network_util.createVotes({1, 2, 3, 4, 5, 6}, r)); } EXPECT_CALL(*network, sendState(_, _)).Times(8); yac->vote(network_util.createHash({10, 0}), *network_util.order_); } NetworkUtil network_util_{1}; }; /** * @given Yac which stores commit * @when Vote from known peer from old round which was presented in the cache * @then Yac sends commit for the last round */ TEST_F(YacSynchronizationTest, SynchronizationOncommitInTheCahe) { yac->onState(network_util_.createVotes({0}, iroha::consensus::Round{1, 0})); } /** * @given Yac which stores commit * @when Vote from known peer from old round which presents in a cache * @then Yac sends commit for the last round */ TEST_F(YacSynchronizationTest, SynchronizationOnCommitOutOfTheCahe) { yac->onState(network_util_.createVotes({0}, iroha::consensus::Round{9, 0})); } /** * @given Yac received reject * @when Vote from known peer from old round which doesn't present in the cache * @then Yac sends last commit */ TEST_F(YacSynchronizationTest, SynchronizationRejectOutOfTheCahe) { yac->onState(network_util_.createVotes({0}, iroha::consensus::Round{5, 5})); }
31.982301
80
0.697842
akshatkarani
0f173cfddea13c3420618ce02aa7fa2ffa575222
1,845
cpp
C++
src/common/expression/TextSearchExpression.cpp
blacklovebear/nebula
f500d478ac53b7c7977da305ca1ed07f8e44376a
[ "Apache-2.0" ]
1
2020-04-11T12:12:39.000Z
2020-04-11T12:12:39.000Z
src/common/expression/TextSearchExpression.cpp
blacklovebear/nebula
f500d478ac53b7c7977da305ca1ed07f8e44376a
[ "Apache-2.0" ]
24
2021-09-15T12:42:03.000Z
2021-09-16T04:59:19.000Z
src/common/expression/TextSearchExpression.cpp
blacklovebear/nebula
f500d478ac53b7c7977da305ca1ed07f8e44376a
[ "Apache-2.0" ]
1
2020-08-03T10:19:39.000Z
2020-08-03T10:19:39.000Z
/* Copyright (c) 2020 vesoft inc. All rights reserved. * * This source code is licensed under Apache 2.0 License, * attached with Common Clause Condition 1.0, found in the LICENSES directory. */ #include "common/expression/TextSearchExpression.h" #include "common/expression/ExprVisitor.h" namespace nebula { bool TextSearchArgument::operator==(const TextSearchArgument& rhs) const { return val_ == rhs.val_ && op_ == rhs.op_ && fuzziness_ == rhs.fuzziness_ && limit_ == rhs.limit_ && timeout_ == rhs.timeout_; } std::string TextSearchArgument::toString() const { std::string buf; buf.reserve(64); buf = from_ + "." + prop_ + ", "; buf += "\"" + val_ + "\""; if (fuzziness_ == -1) { buf += ", AUTO, "; buf += ((op_ == "or") ? "OR" : "AND"); } else if (fuzziness_ > -1) { buf += ", "; buf += folly::stringPrintf("%d, ", fuzziness_); buf += ((op_ == "or") ? "OR" : "AND"); } if (limit_ != -1) { buf += folly::stringPrintf(", %d", limit_); } if (timeout_ != -1) { buf += folly::stringPrintf(", %d", timeout_); } return buf; } bool TextSearchExpression::operator==(const Expression& rhs) const { if (kind_ != rhs.kind()) { return false; } const auto& r = dynamic_cast<const TextSearchExpression&>(rhs); return arg_ == r.arg_; } std::string TextSearchExpression::toString() const { std::string buf; buf.reserve(64); switch (kind_) { case Kind::kTSWildcard: { buf = "WILDCARD("; break; } case Kind::kTSPrefix: { buf = "PREFIX("; break; } case Kind::kTSFuzzy: { buf = "FUZZY("; break; } case Kind::kTSRegexp: { buf = "REGEXP("; break; } default: { LOG(FATAL) << "Unimplemented"; } } buf += arg_->toString(); buf += ")"; return buf; } } // namespace nebula
23.653846
78
0.578862
blacklovebear
0f175b86135b7c86c9c9b68920d17b0884d50c2d
1,603
cpp
C++
BalancedParanthesis.cpp
florayasmin/Hacktoberfest2021-1
d61db34b1844ae9202af829d9e4632ed0deb3574
[ "MIT" ]
1
2021-10-16T01:34:12.000Z
2021-10-16T01:34:12.000Z
BalancedParanthesis.cpp
florayasmin/Hacktoberfest2021-1
d61db34b1844ae9202af829d9e4632ed0deb3574
[ "MIT" ]
null
null
null
BalancedParanthesis.cpp
florayasmin/Hacktoberfest2021-1
d61db34b1844ae9202af829d9e4632ed0deb3574
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; bool isValid(string s) { int n = s.size(); stack<char> st; bool ans = true; for (int i = 0; i < n; i++) { if (st.empty() and (s[i] == ')' or s[i] == '}' or s[i] == ']')) { return false; // if start with closed paranthesis } else if (s[i] == '(' or s[i] == '{' or s[i] == '[') { st.push(s[i]); } else if (s[i] == ')') { if (!st.empty() and st.top() == '(') { st.pop(); } else { ans = false; break; } } else if (s[i] == '}') { if (!st.empty() and st.top() == '{') { st.pop(); } else { ans = false; break; } } else if (s[i] == ']') { if (!st.empty() and st.top() == '[') { st.pop(); } else { ans = false; break; } } } if (!st.empty()) { return false; } return ans; } int main() { string s = "{[(((())))]}"; if (isValid(s)) { cout << "Valid!" << endl; } else { cout << "Not valid!" << endl; } return 0; }
20.0375
73
0.257018
florayasmin
0f1794dd2c4c138c13f0118bc4f1bdea29b7989a
17,271
cpp
C++
UnrealEngine-4.11.2-release/Engine/Source/Editor/UnrealEd/Private/EditorCategoryUtils.cpp
armroyce/Unreal
ea1cdebe70407d59af4e8366d7111c52ce4606df
[ "MIT" ]
1
2016-10-01T21:35:52.000Z
2016-10-01T21:35:52.000Z
UnrealEngine-4.11.2-release/Engine/Source/Editor/UnrealEd/Private/EditorCategoryUtils.cpp
armroyce/Unreal
ea1cdebe70407d59af4e8366d7111c52ce4606df
[ "MIT" ]
null
null
null
UnrealEngine-4.11.2-release/Engine/Source/Editor/UnrealEd/Private/EditorCategoryUtils.cpp
armroyce/Unreal
ea1cdebe70407d59af4e8366d7111c52ce4606df
[ "MIT" ]
1
2021-04-27T08:48:33.000Z
2021-04-27T08:48:33.000Z
// Copyright 1998-2016 Epic Games, Inc. All Rights Reserved. #include "UnrealEd.h" #include "EditorCategoryUtils.h" #include "IDocumentation.h" #define LOCTEXT_NAMESPACE "EditorCategoryUtils" /******************************************************************************* * FEditorCategoryUtils Helpers ******************************************************************************/ namespace FEditorCategoryUtilsImpl { using namespace FEditorCategoryUtils; struct FCategoryInfo { FText DisplayName; FText Tooltip; FString DocLink; FString DocExcerpt; }; typedef TMap<FString, FCategoryInfo> FCategoryInfoMap; /** * Gets the table that tracks mappings from string keys to qualified * category paths. Inits the structure if it hadn't been before (adds * default mappings for all FCommonEditorCategory values) * * @return A map from string category keys, to fully qualified category paths. */ FCategoryInfoMap& GetCategoryTable(); /** * Performs a lookup into the category key table, retrieving a fully * qualified category path for the specified key. * * @param Key The key you want a category path for. * @return The category display string associated with the specified key (an empty string if an entry wasn't found). */ FText const& GetCategory(const FString& Key); /** * Performs a lookup into the category key table, retrieving a fully * qualified category path for the specified key. * * @param CategoryDisplayName Display name for the category, will be used if a tooltip can not be found in the Documentation Page * @param DocLink Path to the documentation page that contains the excerpt for this category * @param DocExcerpt Name of the excerpt within the document page for this category * @return The tooltip (if any) stored at the doc path */ FText GetTooltipForCategory(FString const& CategoryDisplayName, FString const& DocLink, FString const& DocExcerpt); /** Metadata tags */ const FName ClassHideCategoriesMetaKey(TEXT("HideCategories")); const FName ClassShowCategoriesMetaKey(TEXT("ShowCategories")); } //------------------------------------------------------------------------------ FEditorCategoryUtilsImpl::FCategoryInfoMap& FEditorCategoryUtilsImpl::GetCategoryTable() { static FCategoryInfoMap CategoryLookup; static bool bInitialized = false; // this function is reentrant, so we have to guard against recursion if (!bInitialized) { bInitialized = true; RegisterCategoryKey("AI", LOCTEXT("AICategory", "AI")); RegisterCategoryKey("Animation", LOCTEXT("AnimationCategory", "Animation")); RegisterCategoryKey("Audio", LOCTEXT("AudioCategory", "Audio")); RegisterCategoryKey("Development", LOCTEXT("DevelopmentCategory", "Development")); RegisterCategoryKey("Effects", LOCTEXT("EffectsCategory", "Effects")); RegisterCategoryKey("Gameplay", LOCTEXT("GameplayCategory", "Game")); RegisterCategoryKey("Input", LOCTEXT("InputCategory", "Input")); RegisterCategoryKey("Math", LOCTEXT("MathCategory", "Math")); RegisterCategoryKey("Networking", LOCTEXT("NetworkingCategory", "Networking")); RegisterCategoryKey("Pawn", LOCTEXT("PawnCategory", "Pawn")); RegisterCategoryKey("Rendering", LOCTEXT("RenderingCategory", "Rendering")); RegisterCategoryKey("Utilities", LOCTEXT("UtilitiesCategory", "Utilities")); RegisterCategoryKey("Delegates", LOCTEXT("DelegatesCategory", "Event Dispatchers")); RegisterCategoryKey("Variables", LOCTEXT("VariablesCategory", "Variables")); RegisterCategoryKey("Class", LOCTEXT("ClassCategory", "Class")); RegisterCategoryKey("UserInterface", LOCTEXT("UserInterfaceCategory", "User Interface")); RegisterCategoryKey("AnimNotify", LOCTEXT("AnimNotifyCategory", "Add AnimNotify Event")); RegisterCategoryKey("BranchPoint", LOCTEXT("BranchPointCategory", "Add Montage Branching Point Event")); // Utilities sub categories RegisterCategoryKey("FlowControl", BuildCategoryString(FCommonEditorCategory::Utilities, LOCTEXT("FlowControlCategory", "Flow Control"))); RegisterCategoryKey("Transformation", BuildCategoryString(FCommonEditorCategory::Utilities, LOCTEXT("TransformationCategory", "Transformation"))); RegisterCategoryKey("String", BuildCategoryString(FCommonEditorCategory::Utilities, LOCTEXT("StringCategory", "String"))); RegisterCategoryKey("Text", BuildCategoryString(FCommonEditorCategory::Utilities, LOCTEXT("TextCategory", "Text"))); RegisterCategoryKey("Name", BuildCategoryString(FCommonEditorCategory::Utilities, LOCTEXT("NameCategory", "Name"))); RegisterCategoryKey("Enum", BuildCategoryString(FCommonEditorCategory::Utilities, LOCTEXT("EnumCategory", "Enum"))); RegisterCategoryKey("Struct", BuildCategoryString(FCommonEditorCategory::Utilities, LOCTEXT("StructCategory", "Struct"))); RegisterCategoryKey("Macro", BuildCategoryString(FCommonEditorCategory::Utilities, LOCTEXT("MacroCategory", "Macro"))); } return CategoryLookup; } //------------------------------------------------------------------------------ FText const& FEditorCategoryUtilsImpl::GetCategory(const FString& Key) { if (FEditorCategoryUtilsImpl::FCategoryInfo const* FoundCategory = GetCategoryTable().Find(Key)) { return FoundCategory->DisplayName; } return FText::GetEmpty(); } //------------------------------------------------------------------------------ FText FEditorCategoryUtilsImpl::GetTooltipForCategory(FString const& CategoryDisplayName, FString const& DocLink, FString const& DocExcerpt) { FText Tooltip; TSharedRef<IDocumentation> Documentation = IDocumentation::Get(); if (Documentation->PageExists(DocLink)) { TSharedRef<IDocumentationPage> DocPage = Documentation->GetPage(DocLink, NULL); const FString TooltipExcerptSuffix(TEXT("__Tooltip")); FExcerpt Excerpt; if (DocPage->GetExcerpt(DocExcerpt + TooltipExcerptSuffix, Excerpt)) { static const FString TooltipVarKey(TEXT("Tooltip")); if (FString* TooltipValue = Excerpt.Variables.Find(TooltipVarKey)) { Tooltip = FText::FromString(TooltipValue->Replace(TEXT("\\n"),TEXT("\n"))); } } } if (Tooltip.IsEmpty()) { FString CategoryTooltip; if (CategoryDisplayName.Split(TEXT("|"), nullptr, &CategoryTooltip, ESearchCase::CaseSensitive, ESearchDir::FromEnd)) { Tooltip = FText::FromString(CategoryTooltip); } else { Tooltip = FText::FromString(CategoryDisplayName); } } return Tooltip; } /******************************************************************************* * FEditorCategoryUtils ******************************************************************************/ //------------------------------------------------------------------------------ void FEditorCategoryUtils::RegisterCategoryKey(FString const& Key, FText const& Category, FText const& Tooltip) { FEditorCategoryUtilsImpl::FCategoryInfo& CategoryInfo = FEditorCategoryUtilsImpl::GetCategoryTable().Add(Key); CategoryInfo.DisplayName = GetCategoryDisplayString(Category); CategoryInfo.DocLink = TEXT("Shared/GraphNodes/Blueprint/NodeCategories"); CategoryInfo.DocExcerpt = Key; CategoryInfo.Tooltip = (Tooltip.IsEmpty() ? FEditorCategoryUtilsImpl::GetTooltipForCategory(CategoryInfo.DisplayName.ToString(), CategoryInfo.DocLink, CategoryInfo.DocExcerpt) : Tooltip); } void FEditorCategoryUtils::RegisterCategoryKey(FString const& Key, FText const& Category, FString const& DocLink, FString const& DocExcerpt) { FEditorCategoryUtilsImpl::FCategoryInfo& CategoryInfo = FEditorCategoryUtilsImpl::GetCategoryTable().Add(Key); CategoryInfo.DisplayName = GetCategoryDisplayString(Category); CategoryInfo.DocLink = DocLink; CategoryInfo.DocExcerpt = DocExcerpt; CategoryInfo.Tooltip = FEditorCategoryUtilsImpl::GetTooltipForCategory(CategoryInfo.DisplayName.ToString(), CategoryInfo.DocLink, CategoryInfo.DocExcerpt); } //------------------------------------------------------------------------------ FText const& FEditorCategoryUtils::GetCommonCategory(const FCommonEditorCategory::EValue CategoryId) { static TMap<FCommonEditorCategory::EValue, FString> CommonCategoryKeys; if (CommonCategoryKeys.Num() == 0) { CommonCategoryKeys.Add(FCommonEditorCategory::AI, "AI"); CommonCategoryKeys.Add(FCommonEditorCategory::Animation, "Animation"); CommonCategoryKeys.Add(FCommonEditorCategory::Audio, "Audio"); CommonCategoryKeys.Add(FCommonEditorCategory::Development, "Development"); CommonCategoryKeys.Add(FCommonEditorCategory::Effects, "Effects"); CommonCategoryKeys.Add(FCommonEditorCategory::Gameplay, "Gameplay"); CommonCategoryKeys.Add(FCommonEditorCategory::Input, "Input"); CommonCategoryKeys.Add(FCommonEditorCategory::Math, "Math"); CommonCategoryKeys.Add(FCommonEditorCategory::Networking, "Networking"); CommonCategoryKeys.Add(FCommonEditorCategory::Pawn, "Pawn"); CommonCategoryKeys.Add(FCommonEditorCategory::Rendering, "Rendering"); CommonCategoryKeys.Add(FCommonEditorCategory::Utilities, "Utilities"); CommonCategoryKeys.Add(FCommonEditorCategory::Delegates, "Delegates"); CommonCategoryKeys.Add(FCommonEditorCategory::Variables, "Variables"); CommonCategoryKeys.Add(FCommonEditorCategory::Class, "Class"); CommonCategoryKeys.Add(FCommonEditorCategory::UserInterface, "UserInterface"); CommonCategoryKeys.Add(FCommonEditorCategory::AnimNotify, "AnimNotify"); CommonCategoryKeys.Add(FCommonEditorCategory::BranchPoint, "BranchPoint"); CommonCategoryKeys.Add(FCommonEditorCategory::FlowControl, "FlowControl"); CommonCategoryKeys.Add(FCommonEditorCategory::Transformation, "Transformation"); CommonCategoryKeys.Add(FCommonEditorCategory::String, "String"); CommonCategoryKeys.Add(FCommonEditorCategory::Text, "Text"); CommonCategoryKeys.Add(FCommonEditorCategory::Name, "Name"); CommonCategoryKeys.Add(FCommonEditorCategory::Enum, "Enum"); CommonCategoryKeys.Add(FCommonEditorCategory::Struct, "Struct"); CommonCategoryKeys.Add(FCommonEditorCategory::Macro, "Macro"); } if (FString* CategoryKey = CommonCategoryKeys.Find(CategoryId)) { return FEditorCategoryUtilsImpl::GetCategory(*CategoryKey); } return FText::GetEmpty(); } //------------------------------------------------------------------------------ FText FEditorCategoryUtils::BuildCategoryString(FCommonEditorCategory::EValue RootId, FText const& SubCategory) { FText ConstructedCategory; FText const& RootCategory = GetCommonCategory(RootId); if (RootCategory.IsEmpty()) { ConstructedCategory = SubCategory; } else if (SubCategory.IsEmpty()) { ConstructedCategory = RootCategory; } else { // @TODO: FText::Format() is expensive, since this is category // concatenation, we could just do FString concatenation ConstructedCategory = FText::Format(LOCTEXT("ConcatedCategory", "{0}|{1}"), RootCategory, SubCategory); } return ConstructedCategory; } //------------------------------------------------------------------------------ FText FEditorCategoryUtils::GetCategoryDisplayString(FText const& UnsanitizedCategory) { return FText::FromString(GetCategoryDisplayString(UnsanitizedCategory.ToString())); } //------------------------------------------------------------------------------ FString FEditorCategoryUtils::GetCategoryDisplayString(FString const& UnsanitizedCategory) { FString DisplayString = UnsanitizedCategory; int32 KeyIndex = INDEX_NONE; do { KeyIndex = DisplayString.Find(TEXT("{"), ESearchCase::CaseSensitive, ESearchDir::FromStart, KeyIndex); if (KeyIndex != INDEX_NONE) { int32 EndIndex = DisplayString.Find(TEXT("}"), ESearchCase::CaseSensitive, ESearchDir::FromStart, KeyIndex); if (EndIndex != INDEX_NONE) { FString ToReplaceStr(EndIndex+1 - KeyIndex, *DisplayString + KeyIndex); FString ReplacementStr; int32 KeyLen = EndIndex - (KeyIndex + 1); if (KeyLen > 0) { FString Key(KeyLen, *DisplayString + KeyIndex+1); ReplacementStr = FEditorCategoryUtilsImpl::GetCategory(*Key.Trim()).ToString(); } DisplayString.ReplaceInline(*ToReplaceStr, *ReplacementStr); } KeyIndex = EndIndex; } } while (KeyIndex != INDEX_NONE); DisplayString = FName::NameToDisplayString(DisplayString, /*bIsBool =*/false); DisplayString.ReplaceInline(TEXT("| "), TEXT("|"), ESearchCase::CaseSensitive); return DisplayString; } //------------------------------------------------------------------------------ void FEditorCategoryUtils::GetClassHideCategories(UClass const* Class, TArray<FString>& CategoriesOut) { CategoriesOut.Empty(); using namespace FEditorCategoryUtilsImpl; if (Class->HasMetaData(ClassHideCategoriesMetaKey)) { FString const& HideCategories = Class->GetMetaData(ClassHideCategoriesMetaKey); HideCategories.ParseIntoArray(CategoriesOut, TEXT(" "), /*InCullEmpty =*/true); for (FString& Category : CategoriesOut) { Category = GetCategoryDisplayString(Category); } } } //------------------------------------------------------------------------------ void FEditorCategoryUtils::GetClassShowCategories(UClass const* Class, TArray<FString>& CategoriesOut) { CategoriesOut.Empty(); using namespace FEditorCategoryUtilsImpl; if (Class->HasMetaData(ClassShowCategoriesMetaKey)) { FString const& ShowCategories = Class->GetMetaData(ClassShowCategoriesMetaKey); ShowCategories.ParseIntoArray(CategoriesOut, TEXT(" "), /*InCullEmpty =*/true); for (FString& Category : CategoriesOut) { Category = GetCategoryDisplayString(FText::FromString(Category)).ToString(); } } } //------------------------------------------------------------------------------ bool FEditorCategoryUtils::IsCategoryHiddenFromClass(UClass const* Class, FCommonEditorCategory::EValue CategoryId) { return IsCategoryHiddenFromClass(Class, GetCommonCategory(CategoryId)); } //------------------------------------------------------------------------------ bool FEditorCategoryUtils::IsCategoryHiddenFromClass(UClass const* Class, FText const& Category) { return IsCategoryHiddenFromClass(Class, Category.ToString()); } //------------------------------------------------------------------------------ bool FEditorCategoryUtils::IsCategoryHiddenFromClass(UClass const* Class, FString const& Category) { TArray<FString> ClassHideCategories; GetClassHideCategories(Class, ClassHideCategories); return IsCategoryHiddenFromClass(ClassHideCategories, Class, Category); } //------------------------------------------------------------------------------ bool FEditorCategoryUtils::IsCategoryHiddenFromClass(const TArray<FString>& ClassHideCategories, UClass const* Class, const FString& Category) { bool bIsHidden = false; // run the category through sanitization so we can ensure compares will hit FString const DisplayCategory = GetCategoryDisplayString(Category); for (const FString& HideCategory : ClassHideCategories) { bIsHidden = (HideCategory == DisplayCategory); if (bIsHidden) { TArray<FString> ClassShowCategories; GetClassShowCategories(Class, ClassShowCategories); // if they hid it, and showed it... favor showing (could be a shown in a sub-class, and hid in a super) bIsHidden = (ClassShowCategories.Find(DisplayCategory) == INDEX_NONE); } else // see if the category's root is hidden { TArray<FString> SubCategoryList; DisplayCategory.ParseIntoArray(SubCategoryList, TEXT("|"), /*InCullEmpty =*/true); FString FullSubCategoryPath; for (FString const& SubCategory : SubCategoryList) { FullSubCategoryPath += SubCategory; if ((HideCategory == SubCategory) || (HideCategory == FullSubCategoryPath)) { TArray<FString> ClassShowCategories; GetClassShowCategories(Class, ClassShowCategories); // if they hid it, and showed it... favor showing (could be a shown in a sub-class, and hid in a super) bIsHidden = (ClassShowCategories.Find(DisplayCategory) == INDEX_NONE); } FullSubCategoryPath += "|"; } } if (bIsHidden) { break; } } return bIsHidden; } //------------------------------------------------------------------------------ void FEditorCategoryUtils::GetCategoryTooltipInfo(const FString& Category, FText& Tooltip, FString& DocLink, FString& DocExcerpt) { if (FEditorCategoryUtilsImpl::FCategoryInfo const* FoundCategory = FEditorCategoryUtilsImpl::GetCategoryTable().Find(Category)) { DocLink = FoundCategory->DocLink; DocExcerpt = FoundCategory->DocExcerpt; Tooltip = FoundCategory->Tooltip; } else { // Fall back to some defaults DocLink = TEXT("Shared/GraphNodes/Blueprint/NodeCategories"); DocExcerpt = Category; Tooltip = FEditorCategoryUtilsImpl::GetTooltipForCategory(GetCategoryDisplayString(Category), DocLink, DocExcerpt); } } //------------------------------------------------------------------------------ TSet<FString> FEditorCategoryUtils::GetHiddenCategories(UClass const* Class) { TArray<FString> ClassHiddenCategories; GetClassHideCategories(Class, ClassHiddenCategories); TArray<FString> ClassForceVisibleCategories; GetClassShowCategories(Class, ClassForceVisibleCategories); const TSet<FString> ClassHiddenCategoriesSet(ClassHiddenCategories); const TSet<FString> ClassForceVisibleCategoriesSet(ClassForceVisibleCategories); return ClassHiddenCategoriesSet.Difference(ClassForceVisibleCategoriesSet); } #undef LOCTEXT_NAMESPACE
40.733491
188
0.703144
armroyce
0f17c11e26f2d50d8dc9c9e87a10bf257c963f92
16,462
cc
C++
tensorflow/core/kernels/fused_embedding/embedding_lookup_sparse_post_op_test.cc
aalbersk/DeepRec
f673a950780959b44dcda99398880a1d883ab338
[ "Apache-2.0" ]
292
2021-12-24T03:24:33.000Z
2022-03-31T15:41:05.000Z
tensorflow/core/kernels/fused_embedding/embedding_lookup_sparse_post_op_test.cc
aalbersk/DeepRec
f673a950780959b44dcda99398880a1d883ab338
[ "Apache-2.0" ]
54
2021-12-24T06:40:09.000Z
2022-03-30T07:57:24.000Z
tensorflow/core/kernels/fused_embedding/embedding_lookup_sparse_post_op_test.cc
aalbersk/DeepRec
f673a950780959b44dcda99398880a1d883ab338
[ "Apache-2.0" ]
75
2021-12-24T04:48:21.000Z
2022-03-29T10:13:39.000Z
/* Copyright 2015 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/core/common_runtime/kernel_benchmark_testlib.h" #include "tensorflow/core/framework/fake_input.h" #include "tensorflow/core/framework/node_def_builder.h" #include "tensorflow/core/framework/tensor.h" #include "tensorflow/core/framework/types.h" #include "tensorflow/core/kernels/conv_ops_gpu.h" #include "tensorflow/core/kernels/ops_testutil.h" #include "tensorflow/core/kernels/ops_util.h" #include "tensorflow/core/platform/test.h" #include "tensorflow/core/platform/test_benchmark.h" #include "tensorflow/core/public/session.h" #include "tensorflow/cc/ops/standard_ops.h" namespace tensorflow { namespace { enum class Device { CPU, GPU }; class FusedSafeEmbeddingPostLookupOpTest : public OpsTestBase { protected: void MakeOpAndSetDevice(Device device, int num_partitions, DataType dtype, const std::string& combiner, const float max_norm, const int default_id) { if (device == Device::GPU) { SetDevice(DEVICE_GPU, std::unique_ptr<tensorflow::Device>(DeviceFactory::NewDevice( "GPU", {}, "/job:a/replica:0/task:0"))); } TF_EXPECT_OK(NodeDefBuilder("fused_safe_embedding_post_look_up", "FusedEmbeddingSparsePostLookUp") .Attr("T", dtype) .Attr("num_partitions", num_partitions) .Attr("partition_axis", 0) .Attr("combiner", combiner) .Attr("max_norm", max_norm) .Attr("default_id", default_id) .Input(FakeInput(num_partitions, dtype)) .Input(FakeInput(num_partitions, DT_INT64)) .Input(FakeInput(DT_INT64)) .Input(FakeInput(DT_INT32)) .Input(FakeInput(DT_INT64)) .Finalize(node_def())); TF_EXPECT_OK(InitOp()); } }; // TEST_F(FusedSafeEmbeddingPostLookupOpTest, // Partition3_Sqrtn_MaxNorm200_Float) { // const int nnz = 10; // const int batch_size = 4; // const int emb_vector_dim = 8; // const int entries = 8; // MakeOpAndSetDevice(Device::CPU, 3, DT_FLOAT, "sqrtn", 200.0, -1); // // emb_shards // AddInputFromArray<float>( // TensorShape({6, emb_vector_dim}), // { // 8.0, 9.0, 10.0, 11.0, 12.0, 13.0, 14.0, 15.0, 24.0, 25.0, // 26.0, 27.0, 28.0, 29.0, 30.0, 31.0, 24.0, 25.0, 26.0, 27.0, // 28.0, 29.0, 30.0, 31.0, 32.0, 33.0, 34.0, 35.0, 36.0, 37.0, // 38.0, 39.0, 32.0, 33.0, 34.0, 35.0, 36.0, 37.0, 38.0, 39.0, // 40.0, 41.0, 42.0, 43.0, 44.0, 45.0, 46.0, 47.0, // }); // AddInputFromArray<float>(TensorShape({1, emb_vector_dim}), // {56.0, 57.0, 58.0, 59.0, 60.0, 61.0, 62.0, 63.0}); // AddInputFromArray<float>( // TensorShape({3, emb_vector_dim}), // {96.0, 97.0, 98.0, 99.0, 100.0, 101.0, 102.0, 103.0, // 96.0, 97.0, 98.0, 99.0, 100.0, 101.0, 102.0, 103.0, // 120.0, 121.0, 122.0, 123.0, 124.0, 125.0, 126.0, 127.0}); // // partitioned_indices // AddInputFromArray<int64>(TensorShape({6, 2}), // {0, 5, 0, 1, 2, 1, 1, 2, 3, 6, 1, 1}); // AddInputFromArray<int64>(TensorShape({1, 2}), {1, 7}); // AddInputFromArray<int64>(TensorShape({3, 2}), {2, 4, 2, 7, 3, 0}); // // sp_dense_shape // AddInputFromArray<int64>(TensorShape({2}), {batch_size, entries}); // // row_empty_and_invalid_flags // AddInputFromArray<int>(TensorShape({batch_size + nnz}), // {0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1}); // TF_ASSERT_OK(RunOpKernel()); // TF_EXPECT_OK(device_->Sync()); // { // Tensor expected_emb_vectors(allocator(), DT_FLOAT, // TensorShape({batch_size, emb_vector_dim})); // test::FillValues<float>( // &expected_emb_vectors, // {22.62741661, 24.04163170, 25.45584488, 26.87005806, 28.28427124, // 29.69848442, 31.11269951, 32.52691269, 73.90083313, 75.63288879, // 77.36493683, 79.09698486, 80.82904053, 82.56108856, 84.29314423, // 86.02519226, 92.61308289, 94.01081848, 95.40855408, 96.80628204, // 98.20401764, 99.60175323, 100.99948120, 102.39721680, 71.20205688, // 72.31395721, 73.42584991, 74.53774261, 75.64963531, 76.76153564, // 77.87342834, 78.98532867}); // test::ExpectTensorNear<float>(expected_emb_vectors, *GetOutput(0), 1e-4); // } // { // Tensor feature_nums_expected(allocator(), DT_INT32, // TensorShape({batch_size})); // test::FillValues<int>(&feature_nums_expected, {2, 3, 3, 2}); // test::ExpectTensorEqual<int32>(feature_nums_expected, *GetOutput(1)); // } // } TEST_F(FusedSafeEmbeddingPostLookupOpTest, Partition3_Sqrtn_Float) { const int nnz = 10; const int batch_size = 4; const int emb_vector_dim = 8; const int entries = 8; MakeOpAndSetDevice(Device::CPU, 3, DT_FLOAT, "sqrtn", -1.0, -1); // emb_shards AddInputFromArray<float>( TensorShape({6, emb_vector_dim}), { 8.0, 9.0, 10.0, 11.0, 12.0, 13.0, 14.0, 15.0, 24.0, 25.0, 26.0, 27.0, 28.0, 29.0, 30.0, 31.0, 24.0, 25.0, 26.0, 27.0, 28.0, 29.0, 30.0, 31.0, 32.0, 33.0, 34.0, 35.0, 36.0, 37.0, 38.0, 39.0, 32.0, 33.0, 34.0, 35.0, 36.0, 37.0, 38.0, 39.0, 40.0, 41.0, 42.0, 43.0, 44.0, 45.0, 46.0, 47.0, }); AddInputFromArray<float>(TensorShape({1, emb_vector_dim}), {56.0, 57.0, 58.0, 59.0, 60.0, 61.0, 62.0, 63.0}); AddInputFromArray<float>( TensorShape({3, emb_vector_dim}), {96.0, 97.0, 98.0, 99.0, 100.0, 101.0, 102.0, 103.0, 96.0, 97.0, 98.0, 99.0, 100.0, 101.0, 102.0, 103.0, 120.0, 121.0, 122.0, 123.0, 124.0, 125.0, 126.0, 127.0}); // partitioned_indices AddInputFromArray<int64>(TensorShape({6, 2}), {0, 5, 0, 1, 2, 1, 1, 2, 3, 6, 1, 1}); AddInputFromArray<int64>(TensorShape({1, 2}), {1, 7}); AddInputFromArray<int64>(TensorShape({3, 2}), {2, 4, 2, 7, 3, 0}); // sp_dense_shape AddInputFromArray<int64>(TensorShape({2}), {batch_size, entries}); // row_empty_and_invalid_flags AddInputFromArray<int>(TensorShape({batch_size + nnz}), {0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1}); TF_ASSERT_OK(RunOpKernel()); TF_EXPECT_OK(device_->Sync()); { Tensor expected_emb_vectors(allocator(), DT_FLOAT, TensorShape({batch_size, emb_vector_dim})); test::FillValues<float>( &expected_emb_vectors, {22.62741661, 24.04162979, 25.45584297, 26.87005806, 28.28427124, 29.69848442, 31.11269760, 32.52691269, 73.90083313, 75.63288116, 77.36493683, 79.09698486, 80.82903290, 82.56108856, 84.29313660, 86.02519226, 124.70765686, 126.43970490, 128.17175293, 129.90380859, 131.63586426, 133.36790466, 135.09996033, 136.83201599, 107.48023224, 108.89443970, 110.30865479, 111.72286987, 113.13708496, 114.55130005, 115.96550751, 117.37972260}); test::ExpectTensorNear<float>(expected_emb_vectors, *GetOutput(0), 1e-4); } { Tensor feature_nums_expected(allocator(), DT_INT32, TensorShape({batch_size})); test::FillValues<int>(&feature_nums_expected, {2, 3, 3, 2}); test::ExpectTensorEqual<int32>(feature_nums_expected, *GetOutput(1)); } } TEST_F(FusedSafeEmbeddingPostLookupOpTest, Partition2_Sum_No_Default) { const int nnz = 3; const int batch_size = 3; const int emb_vector_dim = 4; const int entries = 8; MakeOpAndSetDevice(Device::CPU, 2, DT_FLOAT, "sum", -1.0, -1); // emb_shards AddInputFromArray<float>(TensorShape({2, emb_vector_dim}), {1.0, 1.0, 1.0, 1.0, 2.0, 2.0, 2.0, 2.0}); AddInputFromArray<float>(TensorShape({2, emb_vector_dim}), {10.0, 10.0, 10.0, 10.0, 13.0, 13.0, 13.0, 13.0}); // partitioned_indices AddInputFromArray<int64>(TensorShape({2, 2}), {0, 0, 0, 5}); AddInputFromArray<int64>(TensorShape({2, 2}), {1, 4, 2, 0}); // sp_dense_shape AddInputFromArray<int64>(TensorShape({2}), {batch_size, entries}); // row_empty_and_invalid_flags AddInputFromArray<int>(TensorShape({batch_size + nnz}), {0, 0, 1, 1, 1, 1}); TF_ASSERT_OK(RunOpKernel()); TF_EXPECT_OK(device_->Sync()); { Tensor expected_emb_vectors(allocator(), DT_FLOAT, TensorShape({batch_size, emb_vector_dim})); test::FillValues<float>( &expected_emb_vectors, {3.0, 3.0, 3.0, 3.0, 10.0, 10.0, 10.0, 10.0, 13.0, 13.0, 13.0, 13.0}); test::ExpectTensorNear<float>(expected_emb_vectors, *GetOutput(0), 1e-4); } { Tensor feature_nums_expected(allocator(), DT_INT32, TensorShape({batch_size})); test::FillValues<int>(&feature_nums_expected, {2, 1, 1}); test::ExpectTensorEqual<int32>(feature_nums_expected, *GetOutput(1)); } } TEST_F(FusedSafeEmbeddingPostLookupOpTest, Partition2_Sum_Default_0) { const int nnz = 3; const int batch_size = 3; const int emb_vector_dim = 4; const int entries = 8; MakeOpAndSetDevice(Device::CPU, 2, DT_FLOAT, "sum", -1.0, 0); // emb_shards AddInputFromArray<float>(TensorShape({2, emb_vector_dim}), {1.0, 1.0, 1.0, 1.0, 2.0, 2.0, 2.0, 2.0}); AddInputFromArray<float>(TensorShape({2, emb_vector_dim}), {10.0, 10.0, 10.0, 10.0, 13.0, 13.0, 13.0, 13.0}); // partitioned_indices AddInputFromArray<int64>(TensorShape({2, 2}), {0, 0, 0, 5}); AddInputFromArray<int64>(TensorShape({2, 2}), {1, 4, 2, 0}); // sp_dense_shape AddInputFromArray<int64>(TensorShape({2}), {batch_size, entries}); // row_empty_and_invalid_flags AddInputFromArray<int>(TensorShape({batch_size + nnz}), {0, 0, 1, 1, 1, 1}); TF_ASSERT_OK(RunOpKernel()); TF_EXPECT_OK(device_->Sync()); { Tensor expected_emb_vectors(allocator(), DT_FLOAT, TensorShape({batch_size, emb_vector_dim})); test::FillValues<float>( &expected_emb_vectors, {3.0, 3.0, 3.0, 3.0, 10.0, 10.0, 10.0, 10.0, 0.0, 0.0, 0.0, 0.0}); test::ExpectTensorNear<float>(expected_emb_vectors, *GetOutput(0), 1e-4); } { Tensor feature_nums_expected(allocator(), DT_INT32, TensorShape({batch_size})); test::FillValues<int>(&feature_nums_expected, {2, 1, 1}); test::ExpectTensorEqual<int32>(feature_nums_expected, *GetOutput(1)); } } //----------------------------------------------------------------------------// // Performance benchmarks // //----------------------------------------------------------------------------// template <typename T> void FillValues(Tensor* tensor, gtl::ArraySlice<T> vals) { auto flat = tensor->flat<T>(); CHECK_EQ(flat.size(), vals.size()); if (flat.size() > 0) { std::copy_n(vals.data(), vals.size(), flat.data()); } } template <typename T> void FillZerosValues(Tensor* tensor) { auto flat = tensor->flat<T>(); for (int i = 0; i < flat.size(); ++i) { flat.data()[i] = 0.0; } } template <typename T> void FillOnesValues(Tensor* tensor) { auto flat = tensor->flat<T>(); float scale = std::rand()/((RAND_MAX + 1u)/6); for (int i = 0; i < flat.size(); ++i) { flat.data()[i] = 1.1 * scale; } } template <typename T> void FillIndiceValues(Tensor* tensor, const int partitions, const int batch_size, const int entries) { auto flat = tensor->flat<T>(); int k = 0; for (int i = 0; i < batch_size; ++i) { for (int j = 0; j < entries; ++j) { flat.data()[k] = i + partitions; flat.data()[k+1] = j; k += 2; } } } template <typename T> void PrintValues(Tensor* tensor) { auto flat = tensor->flat<T>(); for (int i = 0; i < flat.size(); ++i) { std::cout << flat.data()[i] << ", "; } std::cout << std::endl; } template <typename T> static Graph* EmbPostOp(const string& kind, int num_partitions, const std::string& combiner, const float max_norm, const int default_id) { const int nnz = 3; const int batch_size = 512; const int emb_vector_dim = 32; const int entries = 8; const float sparsity = 0.5; const int total_inputs = batch_size*entries*sparsity; Graph* g = new Graph(OpRegistry::Global()); DataType type = DataTypeToEnum<T>::v(); const bool isDefault = (kind == "Default"); string op_name = isDefault ? "FusedEmbeddingSparsePostLookUpOrigin" : "FusedEmbeddingSparsePostLookUp"; // emb_shards std::vector<NodeBuilder::NodeOut> input_emb_shards; input_emb_shards.reserve(num_partitions); for (int i = 0; i < num_partitions; ++i) { Tensor emb_shards(type, TensorShape({total_inputs/num_partitions, emb_vector_dim})); FillOnesValues<T>(&emb_shards); input_emb_shards.push_back(test::graph::Constant(g, emb_shards)); // PrintValues<T>(&emb_shards); } // partitioned_indices std::vector<NodeBuilder::NodeOut> partitioned_indices; partitioned_indices.reserve(num_partitions); for (int i = 0; i < num_partitions; ++i) { Tensor sub_partitioned_indice(DT_INT64, TensorShape({total_inputs/num_partitions, 2})); FillIndiceValues<int64>(&sub_partitioned_indice, i, batch_size/num_partitions, entries*sparsity); partitioned_indices.push_back(test::graph::Constant(g, sub_partitioned_indice)); // PrintValues<int64>(&sub_partitioned_indice); } // sp_dense_shape Tensor sp_dense_shape(DT_INT64, TensorShape({2})); FillValues<int64>(&sp_dense_shape, {batch_size, entries}); // row_empty_and_invalid_flags Tensor row_empty_and_invalid_flags(DT_INT32, TensorShape({batch_size + nnz})); FillZerosValues<int>(&row_empty_and_invalid_flags); auto nodeBuilder = NodeBuilder(g->NewName("n"), op_name) .Attr("T", type) .Attr("num_partitions", num_partitions) .Attr("partition_axis", 0) .Attr("combiner", combiner) .Attr("max_norm", max_norm) .Attr("default_id", default_id) .Input(input_emb_shards) .Input(partitioned_indices) .Input(test::graph::Constant(g, sp_dense_shape)) .Input(test::graph::Constant(g, row_empty_and_invalid_flags)) .Input(partitioned_indices); TF_CHECK_OK(nodeBuilder.Finalize(g, nullptr)); return g; } #define BM_EMB_POST_OP(kind, NP, C, T, DEVICE, NTH) \ static void BM_EMB_POST_OP##_##kind##_##NP##_##C##_##T##_##DEVICE##_##NTH( \ int iters) { \ testing::UseRealTime(); \ SessionOptions opts; \ opts.config.set_intra_op_parallelism_threads(NTH); \ test::Benchmark(#DEVICE, EmbPostOp<T>(#kind, NP, #C, -1.0, -1), &opts).Run(iters); \ } \ BENCHMARK(BM_EMB_POST_OP##_##kind##_##NP##_##C##_##T##_##DEVICE##_##NTH); \ #define BM_EMB_POST_OP_kind(NP, C, NTH) \ BM_EMB_POST_OP(OPT, NP, C, float, CPU, NTH); \ #define BM_EMB_POST_OP_NTH(NP, C) \ BM_EMB_POST_OP_kind(NP, C, 1); \ BM_EMB_POST_OP_kind(NP, C, 4); \ BM_EMB_POST_OP_kind(NP, C, 8); \ BM_EMB_POST_OP_NTH(2, sum); } // namespace } // namespace tensorflow
39.763285
105
0.590876
aalbersk
0f17e58322f6b16326f34df77343baeffbafe7b5
8,362
cc
C++
PYTHIA8/pythia8210dev/examples/main04.cc
AllaMaevskaya/AliRoot
c53712645bf1c7d5f565b0d3228e3a6b9b09011a
[ "BSD-3-Clause" ]
52
2016-12-11T13:04:01.000Z
2022-03-11T11:49:35.000Z
PYTHIA8/pythia8210dev/examples/main04.cc
AllaMaevskaya/AliRoot
c53712645bf1c7d5f565b0d3228e3a6b9b09011a
[ "BSD-3-Clause" ]
1,388
2016-11-01T10:27:36.000Z
2022-03-30T15:26:09.000Z
PYTHIA8/pythia8210dev/examples/main04.cc
AllaMaevskaya/AliRoot
c53712645bf1c7d5f565b0d3228e3a6b9b09011a
[ "BSD-3-Clause" ]
275
2016-06-21T20:24:05.000Z
2022-03-31T13:06:19.000Z
// main04.cc is a part of the PYTHIA event generator. // Copyright (C) 2015 Torbjorn Sjostrand. // PYTHIA is licenced under the GNU GPL version 2, see COPYING for details. // Please respect the MCnet Guidelines, see GUIDELINES for details. // This is a simple test program. // It illustrates how to generate and study "total cross section" processes, // i.e. elastic, single and double diffractive, and the "minimum-bias" rest. // All input is specified in the main06.cmnd file. // Note that the "total" cross section does NOT include // the Coulomb contribution to elastic scattering, as switched on here. #include "Pythia8/Pythia.h" using namespace Pythia8; //========================================================================== int main() { // Generator. Shorthand for the event. Pythia pythia; Event& event = pythia.event; // Read in commands from external file. pythia.readFile("main04.cmnd"); // Extract settings to be used in the main program. int nEvent = pythia.mode("Main:numberOfEvents"); int nAbort = pythia.mode("Main:timesAllowErrors"); // Initialize. pythia.init(); // Book histograms: multiplicities and mean transverse momenta. Hist yChg("rapidity of charged particles; all", 100, -10., 10.); Hist nChg("number of charged particles; all", 100, -0.5, 799.5); Hist nChgSD("number of charged particles; single diffraction", 100, -0.5, 799.5); Hist nChgDD("number of charged particles, double diffractive", 100, -0.5, 799.5); Hist nChgCD("number of charged particles, central diffractive", 100, -0.5, 799.5); Hist nChgND("number of charged particles, non-diffractive", 100, -0.5, 799.5); Hist pTnChg("<pt>(n_charged) all", 100, -0.5, 799.5); Hist pTnChgSD("<pt>(n_charged) single diffraction", 100, -0.5, 799.5); Hist pTnChgDD("<pt>(n_charged) double diffraction", 100, -0.5, 799.5); Hist pTnChgCD("<pt>(n_charged) central diffraction", 100, -0.5, 799.5); Hist pTnChgND("<pt>(n_charged) non-diffractive ", 100, -0.5, 799.5); // Book histograms: ditto as function of separate subsystem mass. Hist mLogInel("log10(mass), by diffractive system", 100, 0., 5.); Hist nChgmLog("<n_charged>(log10(mass))", 100, 0., 5.); Hist pTmLog("<pT>_charged>(log10(mass))", 100, 0., 5.); // Book histograms: elastic/diffractive. Hist tSpecEl("elastic |t| spectrum", 100, 0., 1.); Hist tSpecElLog("elastic log10(|t|) spectrum", 100, -5., 0.); Hist tSpecSD("single diffractive |t| spectrum", 100, 0., 2.); Hist tSpecDD("double diffractive |t| spectrum", 100, 0., 5.); Hist tSpecCD("central diffractive |t| spectrum", 100, 0., 5.); Hist mSpec("diffractive mass spectrum", 100, 0., 100.); Hist mLogSpec("log10(diffractive mass spectrum)", 100, 0., 4.); // Book histograms: inelastic nondiffractive. double pTmax = 20.; double bMax = 4.; Hist pTspec("total pT_hard spectrum", 100, 0., pTmax); Hist pTspecND("nondiffractive pT_hard spectrum", 100, 0., pTmax); Hist bSpec("b impact parameter spectrum", 100, 0., bMax); Hist enhanceSpec("b enhancement spectrum", 100, 0., 10.); Hist number("number of interactions", 100, -0.5, 99.5); Hist pTb1("pT spectrum for b < 0.5", 100, 0., pTmax); Hist pTb2("pT spectrum for 0.5 < b < 1", 100, 0., pTmax); Hist pTb3("pT spectrum for 1 < b < 1.5", 100, 0., pTmax); Hist pTb4("pT spectrum for 1.5 < b", 100, 0., pTmax); Hist bpT1("b spectrum for pT < 2", 100, 0., bMax); Hist bpT2("b spectrum for 2 < pT < 5", 100, 0., bMax); Hist bpT3("b spectrum for 5 < pT < 15", 100, 0., bMax); Hist bpT4("b spectrum for 15 < pT", 100, 0., bMax); // Begin event loop. int iAbort = 0; for (int iEvent = 0; iEvent < nEvent; ++iEvent) { // Generate events. Quit if too many failures. if (!pythia.next()) { if (++iAbort < nAbort) continue; cout << " Event generation aborted prematurely, owing to error!\n"; break; } // Extract event classification. int code = pythia.info.code(); // Charged multiplicity and mean pT: all and by event class. int nch = 0; double pTsum = 0.; for (int i = 1; i < event.size(); ++i) if (event[i].isFinal() && event[i].isCharged()) { yChg.fill( event[i].y() ); ++nch; pTsum += event[i].pT(); } nChg.fill( nch ); if (nch > 0) pTnChg.fill( nch, pTsum/nch); if (code == 103 || code == 104) { nChgSD.fill( nch ); if (nch > 0) pTnChgSD.fill( nch, pTsum/nch); } else if (code == 105) { nChgDD.fill( nch ); if (nch > 0) pTnChgDD.fill( nch, pTsum/nch); } else if (code == 106) { nChgCD.fill( nch ); if (nch > 0) pTnChgCD.fill( nch, pTsum/nch); } else if (code == 101) { nChgND.fill( nch ); if (nch > 0) pTnChgND.fill( nch, pTsum/nch); double mLog = log10( event[0].m() ); mLogInel.fill( mLog ); nChgmLog.fill( mLog, nch ); if (nch > 0) pTmLog.fill( mLog, pTsum / nch ); } // Charged multiplicity and mean pT: per diffractive system. for (int iDiff = 0; iDiff < 3; ++iDiff) if ( (iDiff == 0 && pythia.info.isDiffractiveA()) || (iDiff == 1 && pythia.info.isDiffractiveB()) || (iDiff == 2 && pythia.info.isDiffractiveC()) ) { int ndiff = 0; double pTdiff = 0.; int nDoc = (iDiff < 2) ? 4 : 5; for (int i = nDoc + 1; i < event.size(); ++i) if (event[i].isFinal() && event[i].isCharged()) { // Trace back final particle to see which system it comes from. int k = i; do k = event[k].mother1(); while (k > nDoc); if (k == iDiff + 3) { ++ndiff; pTdiff += event[i].pT(); } } // Study diffractive mass spectrum. double mDiff = event[iDiff+3].m(); double mLog = log10( mDiff); mLogInel.fill( mLog ); nChgmLog.fill( mLog, ndiff ); if (ndiff > 0) pTmLog.fill( mLog, pTdiff / ndiff ); mSpec.fill( mDiff ); mLogSpec.fill( mLog ); } // Study pT spectrum of all hard collisions, no distinction. double pT = pythia.info.pTHat(); pTspec.fill( pT ); // Study t distribution of elastic/diffractive events. if (code > 101) { double tAbs = abs(pythia.info.tHat()); if (code == 102) { tSpecEl.fill(tAbs); tSpecElLog.fill(log10(tAbs)); } else if (code == 103 || code == 104) tSpecSD.fill(tAbs); else if (code == 105) tSpecDD.fill(tAbs); else if (code == 106) { double t1Abs = abs( (event[3].p() - event[1].p()).m2Calc() ); double t2Abs = abs( (event[4].p() - event[2].p()).m2Calc() ); tSpecCD.fill(t1Abs); tSpecCD.fill(t2Abs); } // Study nondiffractive inelastic events in (pT, b) space. } else { double b = pythia.info.bMPI(); double enhance = pythia.info.enhanceMPI(); int nMPI = pythia.info.nMPI(); pTspecND.fill( pT ); bSpec.fill( b ); enhanceSpec.fill( enhance ); number.fill( nMPI ); if (b < 0.5) pTb1.fill( pT ); else if (b < 1.0) pTb2.fill( pT ); else if (b < 1.5) pTb3.fill( pT ); else pTb4.fill( pT ); if (pT < 2.) bpT1.fill( b ); else if (pT < 5.) bpT2.fill( b ); else if (pT < 15.) bpT3.fill( b ); else bpT4.fill( b ); } // End of event loop. } // Final statistics and histograms. pythia.stat(); pTnChg /= nChg; pTnChgSD /= nChgSD; pTnChgDD /= nChgDD; pTnChgCD /= nChgCD; pTnChgND /= nChgND; nChgmLog /= mLogInel; pTmLog /= mLogInel; cout << yChg << nChg << nChgSD << nChgDD << nChgCD << nChgND << pTnChg << pTnChgSD << pTnChgDD << pTnChgCD << pTnChgND << mLogInel << nChgmLog << pTmLog << tSpecEl << tSpecElLog << tSpecSD << tSpecDD << tSpecCD << mSpec << mLogSpec << pTspec << pTspecND << bSpec << enhanceSpec << number << pTb1 << pTb2 << pTb3 << pTb4 << bpT1 << bpT2 << bpT3 << bpT4; // Done. return 0; }
38.534562
76
0.562066
AllaMaevskaya
0f18af9a65fc2312a438866126f15c1c54fcaa3d
822
cpp
C++
src/c++/schemas/Icon.cpp
TestingTravis/modioSDK
b15c4442a8acdb4bf690a846232399eaf9fe18f6
[ "MIT" ]
null
null
null
src/c++/schemas/Icon.cpp
TestingTravis/modioSDK
b15c4442a8acdb4bf690a846232399eaf9fe18f6
[ "MIT" ]
null
null
null
src/c++/schemas/Icon.cpp
TestingTravis/modioSDK
b15c4442a8acdb4bf690a846232399eaf9fe18f6
[ "MIT" ]
null
null
null
#include "c++/schemas/Icon.h" namespace modio { void Icon::initialize(ModioIcon modio_icon) { if (modio_icon.filename) this->filename = modio_icon.filename; if (modio_icon.original) this->original = modio_icon.original; if (modio_icon.thumb_64x64) this->thumb_64x64 = modio_icon.thumb_64x64; if (modio_icon.thumb_128x128) this->thumb_128x128 = modio_icon.thumb_128x128; if (modio_icon.thumb_256x256) this->thumb_256x256 = modio_icon.thumb_256x256; } nlohmann::json toJson(Icon &icon) { nlohmann::json icon_json; icon_json["filename"] = icon.filename; icon_json["original"] = icon.original; icon_json["thumb_64x64"] = icon.thumb_64x64; icon_json["thumb_128x128"] = icon.thumb_128x128; icon_json["thumb_256x256"] = icon.thumb_256x256; return icon_json; } } // namespace modio
25.6875
51
0.738443
TestingTravis
0f190b1df98f2b587a679dfa30b5edea02b9b9bd
1,608
hpp
C++
Clover-Configs/Dell/Dell Inspiron 7520/CLOVER/kexts/10.12/Lilu.kext/Contents/Resources/Headers/plugin_start.hpp
worldlove521/Hackintosh-Installer-University
f5cff36de17bdef0f437a70fb36d182d3ca3a20f
[ "Intel", "CC-BY-4.0" ]
4,033
2016-11-06T13:36:19.000Z
2022-03-28T14:47:26.000Z
Clover-Configs/Dell/Dell Inspiron 7520/CLOVER/kexts/10.12/Lilu.kext/Contents/Resources/Headers/plugin_start.hpp
sakoula/Hackintosh-Installer-University
03fd71ed3f8ec1e01ee45b71835f561263107edf
[ "Intel", "CC-BY-4.0" ]
52
2018-04-16T23:28:37.000Z
2021-07-23T07:17:18.000Z
Clover-Configs/Dell/Dell Inspiron 7520/CLOVER/kexts/10.12/Lilu.kext/Contents/Resources/Headers/plugin_start.hpp
sakoula/Hackintosh-Installer-University
03fd71ed3f8ec1e01ee45b71835f561263107edf
[ "Intel", "CC-BY-4.0" ]
1,200
2016-12-17T13:46:50.000Z
2022-03-23T06:08:11.000Z
// // kern_start.hpp // AppleALC // // Copyright © 2016 vit9696. All rights reserved. // #ifndef kern_start_hpp #define kern_start_hpp #include <Headers/kern_util.hpp> #include <Library/LegacyIOService.h> #include <sys/types.h> struct PluginConfiguration { const char *product; // Product name (e.g. xStringify(PRODUCT_NAME)) size_t version; // Product version (e.g. parseModuleVersion(xStringify(MODULE_VERSION))) uint32_t runmode; // Product supported environments (e.g. LiluAPI::AllowNormal) const char **disableArg; // Pointer to disabling boot arguments array size_t disableArgNum; // Number of disabling boot arguments const char **debugArg; // Pointer to debug boot arguments array size_t debugArgNum; // Number of debug boot arguments const char **betaArg; // Pointer to beta boot arguments array size_t betaArgNum; // Number of beta boot arguments KernelVersion minKernel; // Minimal required kernel version KernelVersion maxKernel; // Maximum supported kernel version void (*pluginStart)(); // Main function }; #ifndef LILU_CUSTOM_KMOD_INIT extern PluginConfiguration ADDPR(config); extern bool ADDPR(startSuccess); #endif /* LILU_CUSTOM_KMOD_INIT */ #ifndef LILU_CUSTOM_IOKIT_INIT class EXPORT PRODUCT_NAME : public IOService { OSDeclareDefaultStructors(PRODUCT_NAME) public: IOService *probe(IOService *provider, SInt32 *score) override; bool start(IOService *provider) override; void stop(IOService *provider) override; }; #endif /* LILU_CUSTOM_IOKIT_INIT */ #endif /* kern_start_hpp */
30.923077
101
0.733831
worldlove521
0f19bde272c98ec1052f100c29945eedfa1a65e2
2,130
cpp
C++
src/Tools/Arguments/Maps/Argument_map_info.cpp
WilliamMajor/aff3ct
4e71ab99f33a040ec06336d3e1d50bd2c0d6a579
[ "MIT" ]
1
2022-02-17T08:47:47.000Z
2022-02-17T08:47:47.000Z
src/Tools/Arguments/Maps/Argument_map_info.cpp
WilliamMajor/aff3ct
4e71ab99f33a040ec06336d3e1d50bd2c0d6a579
[ "MIT" ]
null
null
null
src/Tools/Arguments/Maps/Argument_map_info.cpp
WilliamMajor/aff3ct
4e71ab99f33a040ec06336d3e1d50bd2c0d6a579
[ "MIT" ]
1
2022-02-15T23:32:39.000Z
2022-02-15T23:32:39.000Z
#include <stdexcept> #include "Tools/Arguments/Maps/Argument_map_info.hpp" using namespace aff3ct; using namespace aff3ct::tools; Argument_map_info ::Argument_map_info() { } Argument_map_info ::Argument_map_info(const Argument_map_info& other) { other.clone(*this); } Argument_map_info ::~Argument_map_info() { clear(); } Argument_map_info& Argument_map_info ::operator=(const Argument_map_info& other) { other.clone(*this); return *this; } void Argument_map_info ::add(const Argument_tag& tags, Argument_type* arg_t, const std::string& doc, const arg_rank rank, const std::string key) { if (tags.size() == 0) throw std::invalid_argument("No tag has been given ('tag.size()' == 0)."); if (arg_t == nullptr) throw std::invalid_argument("No argument type has been given ('arg_t' == 0)."); if (exist(tags)) erase(tags); (*this)[tags] = new Argument_info(arg_t, doc, rank, key); } void Argument_map_info ::add_link(const Argument_tag& tag1, const Argument_tag& tag2, bool (*callback)(const void*, const void*)) { links.add(tag1, tag2, callback); } bool Argument_map_info ::has_link(const Argument_tag& tag) const { return links.find(tag) != links.size(); } const Argument_links& Argument_map_info ::get_links() const { return links; } void Argument_map_info ::erase(const Argument_tag& tags) { auto it = this->find(tags); if (it != this->end()) { if (it->second != nullptr) delete it->second; mother_t::erase(it); } } void Argument_map_info ::clear() { for (auto it = this->begin(); it != this->end(); it++) if (it->second != nullptr) delete it->second; mother_t::clear(); } Argument_map_info* Argument_map_info ::clone() const { auto* other = new Argument_map_info(); for (auto it = this->begin(); it != this->end(); it++) (*other)[it->first] = it->second->clone(); return other; } void Argument_map_info ::clone(Argument_map_info& other) const { other.clear(); for (auto it = this->begin(); it != this->end(); it++) other[it->first] = it->second->clone(); } bool Argument_map_info ::exist(const Argument_tag &tags) { return (this->find(tags) != this->end()); }
18.849558
106
0.687793
WilliamMajor
0f19e90462d302b3b58cffd4b6117ca0334b212c
4,450
cpp
C++
chapter26/chapter26_ex05.cpp
TingeOGinge/stroustrup_ppp
bb69533fff8a8f1890c8c866bae2030eaca1cf8b
[ "MIT" ]
170
2018-08-10T19:37:16.000Z
2022-03-29T02:03:30.000Z
chapter26/chapter26_ex05.cpp
TingeOGinge/stroustrup_ppp
bb69533fff8a8f1890c8c866bae2030eaca1cf8b
[ "MIT" ]
7
2018-08-29T15:43:14.000Z
2021-09-23T21:56:49.000Z
chapter26/chapter26_ex05.cpp
TingeOGinge/stroustrup_ppp
bb69533fff8a8f1890c8c866bae2030eaca1cf8b
[ "MIT" ]
105
2015-05-28T11:52:19.000Z
2018-07-17T14:11:25.000Z
// Chapter 26, exercise 5: add test to see if binary_search modifies the // sequence #include<iostream> #include<exception> #include<fstream> #include<string> #include<vector> using namespace std; //------------------------------------------------------------------------------ // check if value val is in the ordered sequence [first,last) template<class Iter, class T> bool binary_search(Iter first, Iter last, const T& val) { if (first == last) // empty sequence return false; Iter p = first; advance(p,distance(first,last)/2); if (*p == val) return true; else if (val < *p) return binary_search(first,p,val); else { // *p < val if (distance(p,last) == 1) return false; // sequence has only 1 element, smaller than value return binary_search(p,last,val); } } //------------------------------------------------------------------------------ template<class T> struct Test { Test() : label(""), val(T()), seq(vector<T>()), res(false) { } string label; T val; vector<T> seq; bool res; }; //------------------------------------------------------------------------------ // read sequence of format { { 1 2 3 4 } } into seq template<class T> istream& operator>>(istream& is, vector<T>& seq) { char ch1; char ch2; char ch3; char ch4; is >> ch1 >> ch2; if (!is) return is; if (ch1!='{' || ch2!='{') { is.clear(ios_base::failbit); return is; } T i; while (is >> i) seq.push_back(i); is.clear(); is >> ch3 >> ch4; if (!is) return is; if (ch3!='}' || ch4!='}') { is.clear(ios_base::failbit); return is; } return is; } //------------------------------------------------------------------------------ // read label, search value and expected result into t - sequence is added // afterwards template<class T> istream& operator>>(istream& is, Test<T>& t) { char ch1; char ch2; is >> ch1; if (!is) return is; if (ch1 != '{') { is.clear(ios_base::failbit); return is; } string lab; is >> lab; if (!is) return is; if (lab=="{") { // this is the next series of tests is.unget(); is.putback(ch1); // put both '{' back into the stream is.clear(ios_base::failbit); return is; } T val; bool res; is >> val >> res >> ch2; if (!is) return is; if (ch2 != '}') { is.clear(ios_base::failbit); return is; } t.label = lab; t.val = val; t.res = res; return is; } //------------------------------------------------------------------------------ template<class T> vector<Test<T>> read_tests(istream& is) { vector<Test<T>> tests; vector<T> seq; while (true) { is >> seq; if (!is) break; Test<T> t; while (is >> t) { t.seq = seq; tests.push_back(t); } is.clear(); seq.clear(); } return tests; } //------------------------------------------------------------------------------ template<class T> int test_all(istream& is) { int error_count = 0; vector<Test<T>> tests = read_tests<T>(is); for (int i = 0; i<tests.size(); ++i) { vector<T> seq_pre = tests[i].seq; // to check if modified bool r = binary_search(tests[i].seq.begin(), tests[i].seq.end(), tests[i].val); if (r != tests[i].res) { cout << "failure: test " << tests[i].label << " binary_search: " << tests[i].seq.size() << " elements, val==" << tests[i].val << " -> " << tests[i].res << '\n'; ++error_count; } if (seq_pre != tests[i].seq) { cout << "failure: test " << tests[i].label << " had its sequence modified\n"; ++error_count; } } return error_count; } //------------------------------------------------------------------------------ int main() try { // sequences of integers string ifname1 = "pics_and_txt/chapter26_ex04_in.txt"; ifstream ifs1(ifname1); if (!ifs1) throw runtime_error("can't open " + ifname1); int errors = test_all<int>(ifs1); cout << "number of errors in " << ifname1 << ": " << errors << '\n'; } catch (exception& e) { cerr << "exception: " << e.what() << '\n'; } catch (...) { cerr << "exception\n"; }
25.141243
80
0.456854
TingeOGinge
0f1ec96beae63b3759b017d012bf4c1cca899745
1,129
cpp
C++
taichi/struct/snode_tree.cpp
kxxt/taichi
15f39b79c258080f1e34fcbdc29646d9ced0a4fe
[ "MIT" ]
11,699
2020-01-09T03:02:46.000Z
2022-03-31T20:59:08.000Z
taichi/struct/snode_tree.cpp
kxxt/taichi
15f39b79c258080f1e34fcbdc29646d9ced0a4fe
[ "MIT" ]
3,589
2020-01-09T03:18:25.000Z
2022-03-31T19:06:42.000Z
taichi/struct/snode_tree.cpp
kxxt/taichi
15f39b79c258080f1e34fcbdc29646d9ced0a4fe
[ "MIT" ]
1,391
2020-01-09T03:02:54.000Z
2022-03-31T08:44:29.000Z
#include "taichi/struct/snode_tree.h" namespace taichi { namespace lang { namespace { void get_snodes_to_root_id_impl(const SNode &node, const int root_id, std::unordered_map<int, int> *map) { (*map)[node.id] = root_id; for (auto &ch : node.ch) { get_snodes_to_root_id_impl(*ch, root_id, map); } } } // namespace SNodeTree::SNodeTree(int id, std::unique_ptr<SNode> root) : id_(id), root_(std::move(root)) { check_tree_validity(*root_); } void SNodeTree::check_tree_validity(SNode &node) { if (node.ch.empty()) { if (node.type != SNodeType::place && node.type != SNodeType::root) { TI_ERROR("{} node must have at least one child.", snode_type_name(node.type)); } } for (auto &ch : node.ch) { check_tree_validity(*ch); } } std::unordered_map<int, int> get_snodes_to_root_id(const SNode &root) { // TODO: Consider generalizing this SNode visiting method std::unordered_map<int, int> res; get_snodes_to_root_id_impl(root, root.id, &res); return res; } } // namespace lang } // namespace taichi
25.659091
72
0.635075
kxxt
0f1fbeef72f98f3cf71e39d12810388ebfa643a4
262
hpp
C++
include/chopper/detail_bin_prefixes.hpp
Felix-Droop/Chopper
5cc214103b2d088ae400bec0fde8973e03dd3095
[ "BSD-3-Clause" ]
null
null
null
include/chopper/detail_bin_prefixes.hpp
Felix-Droop/Chopper
5cc214103b2d088ae400bec0fde8973e03dd3095
[ "BSD-3-Clause" ]
null
null
null
include/chopper/detail_bin_prefixes.hpp
Felix-Droop/Chopper
5cc214103b2d088ae400bec0fde8973e03dd3095
[ "BSD-3-Clause" ]
null
null
null
#pragma once constexpr std::string_view hibf_prefix{"HIGH_LEVEL_IBF"}; constexpr std::string_view merged_bin_prefix{"MERGED_BIN"}; constexpr std::string_view split_bin_prefix{"SPLIT_BIN"}; constexpr size_t merged_bin_prefix_length{merged_bin_prefix.size()};
26.2
68
0.824427
Felix-Droop
0f2012089c71563586060d4135eed276c8e04ef9
1,084
cpp
C++
Codeforces/605E.cpp
HeRaNO/OI-ICPC-Codes
4a4639cd3e347b472520065ca6ab8caadde6906d
[ "MIT" ]
18
2019-01-01T13:16:59.000Z
2022-02-28T04:51:50.000Z
Codeforces/605E.cpp
HeRaNO/OI-ICPC-Codes
4a4639cd3e347b472520065ca6ab8caadde6906d
[ "MIT" ]
null
null
null
Codeforces/605E.cpp
HeRaNO/OI-ICPC-Codes
4a4639cd3e347b472520065ca6ab8caadde6906d
[ "MIT" ]
5
2019-09-13T08:48:17.000Z
2022-02-19T06:59:03.000Z
#include <bits/stdc++.h> #define ll long long #define ls id<<1 #define rs id<<1|1 #define mem(a,b) memset(a,b,sizeof(a)) #define pii pair<int,int> #define mp(a,b) make_pair(a,b) using namespace std; const int inf=0x3f3f3f3f; const ll mod=1e9+7; const int N=1050; double p[N][N]; int n; double dp[N],ji[N]; bool vis[N]; int main() { cin>>n; for(int i=1;i<=n;++i) for(int j=1;j<=n;++j) { int x;cin>>x; p[i][j]=x/100.0; } if(n==1)return puts("0"),0; for(int i=1;i<=n;++i)dp[i]=1.0,ji[i]=1.0-p[i][n]; dp[n]=0;vis[n]=1; for(int i=1;i<=n;++i) { int now=0; double mn=2e18; for(int j=1;j<=n;++j) { if(!vis[j]&&dp[j]/(1.0-ji[j])<mn) { mn=dp[j]/(1.0-ji[j]); now=j; } } vis[now]=1; if(now==1)return printf("%.12lf\n",dp[1]/(1.0-ji[1])),0; for(int j=1;j<=n;++j) { dp[j]+=dp[now]*p[j][now]*ji[j]/(1.0-ji[now]); ji[j]=ji[j]*(1.0-p[j][now]); } } return 0; }
21.254902
64
0.443727
HeRaNO
0f22b9fbce5bb8e3ee5680c035854cf382b15802
1,043
cpp
C++
src/main.cpp
kondrak/quake_bsp_viewer_legacyOpenGL
e64a2a74fbda91fdd26a9027098e087bbd5cd8b3
[ "MIT" ]
4
2015-11-29T15:38:42.000Z
2021-09-12T00:19:28.000Z
src/main.cpp
kondrak/quake_bsp_viewer_legacyOpenGL
e64a2a74fbda91fdd26a9027098e087bbd5cd8b3
[ "MIT" ]
null
null
null
src/main.cpp
kondrak/quake_bsp_viewer_legacyOpenGL
e64a2a74fbda91fdd26a9027098e087bbd5cd8b3
[ "MIT" ]
null
null
null
#include "Application.hpp" #include "InputHandlers.hpp" #include "renderer/RenderContext.hpp" // keep the render context and application object global RenderContext g_renderContext; Application g_application; int main(int argc, char **argv) { // initialize SDL if( SDL_Init( SDL_INIT_VIDEO | SDL_INIT_EVENTS ) < 0 ) { return 1; } g_renderContext.Init("Quake BSP Viewer", 100, 100, 1024, 768); g_application.Initialize(g_renderContext.width, g_renderContext.height); SDL_ShowCursor( SDL_DISABLE ); // initialize Glee if (!GLeeInit()) { return 1; } g_application.OnStart( argc, argv ); Uint32 last = SDL_GetTicks(); while( g_application.Running() ) { Uint32 now = SDL_GetTicks(); processEvents(); g_application.OnUpdate(float(now - last) / 1000.f); g_application.OnRender(); SDL_GL_SwapWindow( g_renderContext.window ); last = now; } g_application.OnTerminate(); SDL_Quit(); return 0; }
20.057692
76
0.645254
kondrak
0f29be1fede5316157c74418de5309fedfbb685b
2,766
hpp
C++
ThirdParty/pegtl/vtkpegtl/include/tao/pegtl/internal/istring.hpp
txwhhny/vtk
854d9aa87b944bc9079510515996406b98b86f7c
[ "BSD-3-Clause" ]
39
2018-12-02T01:13:53.000Z
2022-01-29T18:31:28.000Z
ThirdParty/pegtl/vtkpegtl/include/tao/pegtl/internal/istring.hpp
txwhhny/vtk
854d9aa87b944bc9079510515996406b98b86f7c
[ "BSD-3-Clause" ]
17
2018-06-25T14:51:52.000Z
2021-08-23T10:47:49.000Z
ThirdParty/pegtl/vtkpegtl/include/tao/pegtl/internal/istring.hpp
txwhhny/vtk
854d9aa87b944bc9079510515996406b98b86f7c
[ "BSD-3-Clause" ]
11
2018-12-05T11:37:37.000Z
2021-02-06T16:35:07.000Z
// Copyright (c) 2014-2019 Dr. Colin Hirsch and Daniel Frey // Please see LICENSE for license or visit https://github.com/taocpp/PEGTL/ #ifndef TAO_PEGTL_INTERNAL_ISTRING_HPP #define TAO_PEGTL_INTERNAL_ISTRING_HPP #include <type_traits> #include "../config.hpp" #include "bump_help.hpp" #include "result_on_found.hpp" #include "skip_control.hpp" #include "trivial.hpp" #include "../analysis/counted.hpp" namespace tao { namespace TAO_PEGTL_NAMESPACE { namespace internal { template< char C > using is_alpha = std::integral_constant< bool, ( ( 'a' <= C ) && ( C <= 'z' ) ) || ( ( 'A' <= C ) && ( C <= 'Z' ) ) >; template< char C, bool A = is_alpha< C >::value > struct ichar_equal; template< char C > struct ichar_equal< C, true > { static bool match( const char c ) noexcept { return ( C | 0x20 ) == ( c | 0x20 ); } }; template< char C > struct ichar_equal< C, false > { static bool match( const char c ) noexcept { return c == C; } }; template< char... Cs > struct istring_equal; template<> struct istring_equal<> { static bool match( const char* /*unused*/ ) noexcept { return true; } }; template< char C, char... Cs > struct istring_equal< C, Cs... > { static bool match( const char* r ) noexcept { return ichar_equal< C >::match( *r ) && istring_equal< Cs... >::match( r + 1 ); } }; template< char... Cs > struct istring; template<> struct istring<> : trivial< true > { }; template< char... Cs > struct istring { using analyze_t = analysis::counted< analysis::rule_type::any, sizeof...( Cs ) >; template< typename Input > static bool match( Input& in ) noexcept( noexcept( in.size( 0 ) ) ) { if( in.size( sizeof...( Cs ) ) >= sizeof...( Cs ) ) { if( istring_equal< Cs... >::match( in.current() ) ) { bump_help< result_on_found::success, Input, char, Cs... >( in, sizeof...( Cs ) ); return true; } } return false; } }; template< char... Cs > struct skip_control< istring< Cs... > > : std::true_type { }; } // namespace internal } // namespace TAO_PEGTL_NAMESPACE } // namespace tao #endif
25.611111
127
0.477585
txwhhny
0f2a9491a7af6a8948061edc4e6b30a0cbe03bb6
2,093
cpp
C++
src/CppParser/CppParser.cpp
P-i-N/CppSharp
c36145b29dd5e8ae273557c2a31fd4d8a7a044be
[ "MIT" ]
null
null
null
src/CppParser/CppParser.cpp
P-i-N/CppSharp
c36145b29dd5e8ae273557c2a31fd4d8a7a044be
[ "MIT" ]
null
null
null
src/CppParser/CppParser.cpp
P-i-N/CppSharp
c36145b29dd5e8ae273557c2a31fd4d8a7a044be
[ "MIT" ]
null
null
null
/************************************************************************ * * CppSharp * Licensed under the MIT license. * ************************************************************************/ #include "CppParser.h" #include "Parser.h" #include <clang/Basic/Version.inc> namespace CppSharp { namespace CppParser { CppParserOptions::CppParserOptions() : ASTContext(0) , toolSetToUse(0) , noStandardIncludes(false) , noBuiltinIncludes(false) , microsoftMode(false) , verbose(false) , unityBuild(false) , skipPrivateDeclarations(true) , skipLayoutInfo(false) , skipFunctionBodies(true) , clangVersion(CLANG_VERSION_STRING) { } CppParserOptions::~CppParserOptions() {} std::string CppParserOptions::getClangVersion() { return clangVersion; } DEF_VECTOR_STRING(CppParserOptions, Arguments) DEF_VECTOR_STRING(CppParserOptions, SourceFiles) DEF_VECTOR_STRING(CppParserOptions, IncludeDirs) DEF_VECTOR_STRING(CppParserOptions, SystemIncludeDirs) DEF_VECTOR_STRING(CppParserOptions, Defines) DEF_VECTOR_STRING(CppParserOptions, Undefines) DEF_VECTOR_STRING(CppParserOptions, SupportedStdTypes) ParserResult::ParserResult() : targetInfo(0) { } ParserResult::ParserResult(const ParserResult& rhs) : kind(rhs.kind) , Diagnostics(rhs.Diagnostics) , Libraries(rhs.Libraries) , targetInfo(rhs.targetInfo) {} ParserResult::~ParserResult() { for (auto Library : Libraries) { delete Library; } } DEF_VECTOR(ParserResult, ParserDiagnostic, Diagnostics) DEF_VECTOR(ParserResult, NativeLibrary*, Libraries) LinkerOptions::LinkerOptions() {} LinkerOptions::~LinkerOptions() {} DEF_VECTOR_STRING(LinkerOptions, Arguments) DEF_VECTOR_STRING(LinkerOptions, LibraryDirs) DEF_VECTOR_STRING(LinkerOptions, Libraries) ParserDiagnostic::ParserDiagnostic() {} ParserDiagnostic::ParserDiagnostic(const ParserDiagnostic& rhs) : fileName(rhs.fileName) , message(rhs.message) , level(rhs.level) , lineNumber(rhs.lineNumber) , columnNumber(rhs.columnNumber) {} ParserDiagnostic::~ParserDiagnostic() {} } }
25.216867
73
0.705686
P-i-N
0f2bcb2378bd857af261bf2c768a9ae4d64e11bb
77
cc
C++
GeneratorInterface/GenExtensions/bin/HARDCOL/main.cc
ckamtsikis/cmssw
ea19fe642bb7537cbf58451dcf73aa5fd1b66250
[ "Apache-2.0" ]
852
2015-01-11T21:03:51.000Z
2022-03-25T21:14:00.000Z
GeneratorInterface/GenExtensions/bin/HARDCOL/main.cc
ckamtsikis/cmssw
ea19fe642bb7537cbf58451dcf73aa5fd1b66250
[ "Apache-2.0" ]
30,371
2015-01-02T00:14:40.000Z
2022-03-31T23:26:05.000Z
GeneratorInterface/GenExtensions/bin/HARDCOL/main.cc
ckamtsikis/cmssw
ea19fe642bb7537cbf58451dcf73aa5fd1b66250
[ "Apache-2.0" ]
3,240
2015-01-02T05:53:18.000Z
2022-03-31T17:24:21.000Z
extern "C" { void hardcol_(); } int main() { hardcol_(); return 1; }
6.416667
18
0.532468
ckamtsikis
0f2e97cbb920c58e4c5b35e8fc5285d493fa007c
1,477
cpp
C++
Starters 14/TUPCOUNT.cpp
Jks08/CodeChef
a8aec8a563c441176a36b8581031764e99f09833
[ "MIT" ]
1
2021-09-17T13:10:04.000Z
2021-09-17T13:10:04.000Z
Starters 14/TUPCOUNT.cpp
Jks08/CodeChef
a8aec8a563c441176a36b8581031764e99f09833
[ "MIT" ]
null
null
null
Starters 14/TUPCOUNT.cpp
Jks08/CodeChef
a8aec8a563c441176a36b8581031764e99f09833
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; #define PI 3.14159265358979323846 #define ll long long int #include<ext/pb_ds/assoc_container.hpp> #include<ext/pb_ds/tree_policy.hpp> using namespace __gnu_pbds; const int T = 1e6 + 5; long long phi[T]; gp_hash_table<long long, long long> mp; int sz, spf[T], prime[T]; void f() { memset(spf, 0, sizeof spf); phi[1] = 1; sz = 0; for (int i = 2; i < T; i++) { if (spf[i] == 0) phi[i] = i - 1, spf[i] = i, prime[sz++] = i; for (int j = 0; j < sz && i * prime[j] < T && prime[j] <= spf[i]; j++) { spf[i * prime[j]] = prime[j]; if (i % prime[j] == 0) phi[i * prime[j]] = phi[i] * prime[j]; else phi[i * prime[j]] = phi[i] * (prime[j] - 1); } } } int main(){ ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); int test = 1; cin>>test; f(); while(test--){ ll n; cin>>n; ll ans1=0,ans2=0; for(int i=2;i<=n;i++){ ll temp=n/i; temp*=(phi[i]); ans2+=temp; temp*=(n/i); ans1+=temp; } ans1*=4LL; ans1+=n; ans2*=4LL; ans2+=n; ll ans=(ans1+ans2)/2; cout<<ans<<" "; cout<<"\n"; } return 0; }
24.616667
82
0.411645
Jks08
0f2e9b5d687c9d267e5c422bcf45c3501df831eb
111,565
cpp
C++
depends/work/build/i686-w64-mingw32/qt/5.9.7-f2560c1efa6/qtbase/tests/auto/corelib/codecs/qtextcodec/tst_qtextcodec.cpp
GrinCash/Grinc-core
1377979453ba84082f70f9c128be38e57b65a909
[ "MIT" ]
null
null
null
depends/work/build/i686-w64-mingw32/qt/5.9.7-f2560c1efa6/qtbase/tests/auto/corelib/codecs/qtextcodec/tst_qtextcodec.cpp
GrinCash/Grinc-core
1377979453ba84082f70f9c128be38e57b65a909
[ "MIT" ]
null
null
null
depends/work/build/i686-w64-mingw32/qt/5.9.7-f2560c1efa6/qtbase/tests/auto/corelib/codecs/qtextcodec/tst_qtextcodec.cpp
GrinCash/Grinc-core
1377979453ba84082f70f9c128be38e57b65a909
[ "MIT" ]
null
null
null
/**************************************************************************** ** ** Copyright (C) 2016 The Qt Company Ltd. ** Copyright (C) 2016 Intel Corporation. ** Contact: https://www.qt.io/licensing/ ** ** This file is part of the test suite of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:GPL-EXCEPT$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms ** and conditions see https://www.qt.io/terms-conditions. For further ** information use the contact form at https://www.qt.io/contact-us. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3 as published by the Free Software ** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT ** included in the packaging of this file. Please review the following ** information to ensure the GNU General Public License requirements will ** be met: https://www.gnu.org/licenses/gpl-3.0.html. ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include <QtTest/QtTest> #include <qtextcodec.h> #include <qfile.h> #include <time.h> #if QT_CONFIG(process) # include <qprocess.h> #endif #include <QThreadPool> class tst_QTextCodec : public QObject { Q_OBJECT private slots: void threadSafety(); void toUnicode_data(); void toUnicode(); void codecForName_data(); void codecForName(); void fromUnicode_data(); void fromUnicode(); void toUnicode_codecForHtml(); void toUnicode_incremental(); void codecForLocale(); void asciiToIscii() const; void nonFlaggedCodepointFFFF() const; void flagF7808080() const; void nonFlaggedEFBFBF() const; void decode0D() const; void aliasForUTF16() const; void mibForTSCII() const; void codecForTSCII() const; void iso8859_16() const; void utf8Codec_data(); void utf8Codec(); void utf8bom_data(); void utf8bom(); void utf8stateful_data(); void utf8stateful(); void utfHeaders_data(); void utfHeaders(); void codecForHtml_data(); void codecForHtml(); void codecForUtfText_data(); void codecForUtfText(); #if defined(Q_OS_UNIX) void toLocal8Bit(); #endif void invalidNames(); void checkAliases_data(); void checkAliases(); void moreToFromUnicode_data(); void moreToFromUnicode(); void shiftJis(); void userCodec(); }; void tst_QTextCodec::toUnicode_data() { QTest::addColumn<QString>("fileName"); QTest::addColumn<QString>("codecName"); QTest::newRow( "korean-eucKR" ) << QFINDTESTDATA("korean.txt") << "eucKR"; QTest::newRow( "UTF-8" ) << QFINDTESTDATA("utf8.txt") << "UTF-8"; } void tst_QTextCodec::toUnicode() { QFETCH( QString, fileName ); QFETCH( QString, codecName ); QFile file( fileName ); if ( file.open( QIODevice::ReadOnly ) ) { QByteArray ba = file.readAll(); QVERIFY(!ba.isEmpty()); QTextCodec *c = QTextCodec::codecForName( codecName.toLatin1() ); QVERIFY(c != 0); QString uniString = c->toUnicode( ba ); if (codecName == QLatin1String("UTF-8")) { QCOMPARE(uniString, QString::fromUtf8(ba)); QCOMPARE(ba, uniString.toUtf8()); } QVERIFY(!uniString.isEmpty()); QCOMPARE( ba, c->fromUnicode( uniString ) ); char ch = '\0'; QVERIFY(c->toUnicode(&ch, 1).length() == 1); QVERIFY(c->toUnicode(&ch, 1).at(0).unicode() == 0); } else { QFAIL(qPrintable("File could not be opened: " + file.errorString())); } } void tst_QTextCodec::codecForName_data() { QTest::addColumn<QString>("hint"); QTest::addColumn<QString>("actualCodecName"); QTest::newRow("data1") << "iso88591" << "ISO-8859-1"; QTest::newRow("data2") << "iso88592" << "ISO-8859-2"; QTest::newRow("data3") << " IsO(8)8/5*9-2 " << "ISO-8859-2"; QTest::newRow("data4") << " IsO(8)8/5*2-9 " << ""; QTest::newRow("data5") << "latin2" << "ISO-8859-2"; } void tst_QTextCodec::codecForName() { QFETCH(QString, hint); QFETCH(QString, actualCodecName); QTextCodec *codec = QTextCodec::codecForName(hint.toLatin1()); if (actualCodecName.isEmpty()) { QVERIFY(!codec); } else { QVERIFY(codec != 0); QCOMPARE(QString(codec->name()), actualCodecName); } } void tst_QTextCodec::fromUnicode_data() { QTest::addColumn<QString>("codecName"); QTest::addColumn<bool>("eightBit"); QTest::newRow("ISO-8859-1") << "ISO-8859-1" << true; QTest::newRow("ISO-8859-2") << "ISO-8859-2" << true; QTest::newRow("ISO-8859-3") << "ISO-8859-3" << true; QTest::newRow("ISO-8859-4") << "ISO-8859-4" << true; QTest::newRow("ISO-8859-5") << "ISO-8859-5" << true; QTest::newRow("ISO-8859-6") << "ISO-8859-6" << true; QTest::newRow("ISO-8859-7") << "ISO-8859-7" << true; QTest::newRow("ISO-8859-8") << "ISO-8859-8" << true; QTest::newRow("ISO-8859-9") << "ISO-8859-9" << true; QTest::newRow("ISO-8859-10") << "ISO-8859-10" << true; QTest::newRow("ISO-8859-13") << "ISO-8859-13" << true; QTest::newRow("ISO-8859-14") << "ISO-8859-14" << true; QTest::newRow("ISO-8859-15") << "ISO-8859-15" << true; // QTest::newRow("ISO-8859-16") << "ISO-8859-16" << true; QTest::newRow("IBM850") << "IBM850" << true; QTest::newRow("IBM874") << "IBM874" << true; QTest::newRow("IBM866") << "IBM866" << true; QTest::newRow("windows-1250") << "windows-1250" << true; QTest::newRow("windows-1251") << "windows-1251" << true; QTest::newRow("windows-1252") << "windows-1252" << true; QTest::newRow("windows-1253") << "windows-1253" << true; QTest::newRow("windows-1254") << "windows-1254" << true; QTest::newRow("windows-1255") << "windows-1255" << true; QTest::newRow("windows-1256") << "windows-1256" << true; QTest::newRow("windows-1257") << "windows-1257" << true; QTest::newRow("windows-1258") << "windows-1258" << true; QTest::newRow("Apple Roman") << "Apple Roman" << true; //QTest::newRow("WINSAMI2") << "WINSAMI2" << true; QTest::newRow("TIS-620") << "TIS-620" << true; QTest::newRow("SJIS") << "SJIS" << false; // all codecs from documentation QTest::newRow("Big5") << "Big5" << false; QTest::newRow("Big5-HKSCS") << "Big5-HKSCS" << false; QTest::newRow("CP949") << "CP949" << false; QTest::newRow("windows-949") << "windows-949" << false; QTest::newRow("EUC-JP") << "EUC-JP" << false; QTest::newRow("EUC-KR") << "EUC-KR" << false; QTest::newRow("GB18030") << "GB18030" << false; QTest::newRow("HP-ROMAN8") << "HP-ROMAN8" << false; QTest::newRow("IBM 850") << "IBM 850" << false; QTest::newRow("IBM 866") << "IBM 866" << false; QTest::newRow("IBM 874") << "IBM 874" << false; QTest::newRow("ISO 2022-JP") << "ISO 2022-JP" << false; //ISO 8859-1 to 10 and ISO 8859-13 to 16 tested previously // Iscii-Bng, Dev, Gjr, Knd, Mlm, Ori, Pnj, Tlg, and Tml tested in Iscii test QTest::newRow("KOI8-R") << "KOI8-R" << false; QTest::newRow("KOI8-U") << "KOI8-U" << false; QTest::newRow("Macintosh") << "Macintosh" << true; QTest::newRow("Shift-JIS") << "Shift-JIS" << false; QTest::newRow("TIS-620") << "TIS-620" << false; QTest::newRow("TSCII") << "TSCII" << false; QTest::newRow("UTF-8") << "UTF-8" << false; QTest::newRow("UTF-16") << "UTF-16" << false; QTest::newRow("UTF-16BE") << "UTF-16BE" << false; QTest::newRow("UTF-16LE") << "UTF-16LE" << false; QTest::newRow("UTF-32") << "UTF-32" << false; QTest::newRow("UTF-32BE") << "UTF-32BE" << false; QTest::newRow("UTF-32LE") << "UTF-32LE" << false; //Windows-1250 to 1258 tested previously } void tst_QTextCodec::fromUnicode() { QFETCH(QString, codecName); QFETCH(bool, eightBit); QTextCodec *codec = QTextCodec::codecForName(codecName.toLatin1()); QVERIFY(codec != 0); // Check if the reverse lookup is what we expect if (eightBit) { char chars[128]; for (int i = 0; i < 128; ++i) chars[i] = i + 128; QString s = codec->toUnicode(chars, 128); QByteArray c = codec->fromUnicode(s); QCOMPARE(c.size(), 128); int numberOfQuestionMarks = 0; for (int i = 0; i < 128; ++i) { if (c.at(i) == '?') ++numberOfQuestionMarks; else QCOMPARE(c.at(i), char(i + 128)); } QVERIFY(numberOfQuestionMarks != 128); } /* If the encoding is a superset of ASCII, test that the byte array is correct (no off by one, no trailing '\0'). */ QByteArray result = codec->fromUnicode(QString("abc")); if (result.startsWith('a')) { QCOMPARE(result.size(), 3); QCOMPARE(result, QByteArray("abc")); } else { QVERIFY(true); } } void tst_QTextCodec::toUnicode_codecForHtml() { QFile file(QFINDTESTDATA("QT4-crashtest.txt")); QVERIFY(file.open(QFile::ReadOnly)); QByteArray data = file.readAll(); QTextCodec *codec = QTextCodec::codecForHtml(data); codec->toUnicode(data); // this line crashes } void tst_QTextCodec::toUnicode_incremental() { QByteArray ba; ba += char(0xf0); ba += char(0x90); ba += char(0x80); ba += char(0x80); ba += char(0xf4); ba += char(0x8f); ba += char(0xbf); ba += char(0xbd); QString expected = QString::fromUtf8(ba); QString incremental; QTextDecoder *utf8Decoder = QTextCodec::codecForMib(106)->makeDecoder(); QString actual; for (int i = 0; i < ba.size(); ++i) utf8Decoder->toUnicode(&actual, ba.constData() + i, 1); QCOMPARE(actual, expected); delete utf8Decoder; } void tst_QTextCodec::codecForLocale() { QTextCodec *codec = QTextCodec::codecForLocale(); QVERIFY(codec != 0); // The rest of this test is for Unix only #if defined(Q_OS_UNIX) // get a time string that is locale-encoded QByteArray originalLocaleEncodedTimeString; originalLocaleEncodedTimeString.resize(1024); time_t t; time(&t); int r = strftime(originalLocaleEncodedTimeString.data(), originalLocaleEncodedTimeString.size(), "%A%a%B%b%Z", localtime(&t)); QVERIFY(r != 0); originalLocaleEncodedTimeString.resize(r); QString unicodeTimeString = codec->toUnicode(originalLocaleEncodedTimeString); QByteArray localeEncodedTimeString = codec->fromUnicode(unicodeTimeString); QCOMPARE(localeEncodedTimeString, originalLocaleEncodedTimeString); // find a codec that is not the codecForLocale() QTextCodec *codec2 = 0; const auto availableMibs = QTextCodec::availableMibs(); for (int mib : availableMibs ) { if (mib != codec->mibEnum()) { codec2 = QTextCodec::codecForMib(mib); if (codec2) break; } } // Only run the rest of the test if we could find a codec that is not // already the codecForLocale(). if (codec2) { // set it, codecForLocale() should return it now QTextCodec::setCodecForLocale(codec2); QCOMPARE(QTextCodec::codecForLocale(), codec2); // reset back to the default QTextCodec::setCodecForLocale(0); QCOMPARE(QTextCodec::codecForLocale(), codec); } #endif } void tst_QTextCodec::asciiToIscii() const { /* Add all low, 7-bit ASCII characters. */ QString ascii; const int len = 0xA0 - 1; ascii.resize(len); for(int i = 0; i < len; ++i) ascii[i] = QChar(i + 1); static const char *const isciiCodecs[] = { "Iscii-Mlm", "Iscii-Knd", "Iscii-Tlg", "Iscii-Tml", "Iscii-Ori", "Iscii-Gjr", "Iscii-Pnj", "Iscii-Bng", "Iscii-Dev" }; const int isciiCodecsLen = sizeof(isciiCodecs) / sizeof(const char *); for(int i = 0; i < isciiCodecsLen; ++i) { /* For each codec. */ const QTextCodec *const textCodec = QTextCodec::codecForName(isciiCodecs[i]); if (!textCodec) QSKIP("No ISCII codecs available."); for(int i2 = 0; i2 < len; ++i2) { /* For each character in ascii. */ const QChar c(ascii[i2]); QVERIFY2(textCodec->canEncode(c), qPrintable(QString::fromLatin1("Failed to encode %1 with encoding %2") .arg(QString::number(c.unicode()), QString::fromLatin1(textCodec->name().constData())))); } QVERIFY2(textCodec->canEncode(ascii), qPrintable(QString::fromLatin1("Failed for full string with encoding %1") .arg(QString::fromLatin1(textCodec->name().constData())))); } } void tst_QTextCodec::nonFlaggedCodepointFFFF() const { //Check that the code point 0xFFFF (=non-character code 0xEFBFBF) is not flagged const QChar ch(0xFFFF); QString input(ch); QTextCodec *const codec = QTextCodec::codecForMib(106); // UTF-8 QVERIFY(codec); const QByteArray asDecoded(codec->fromUnicode(input)); QCOMPARE(asDecoded, QByteArray("\357\277\277")); QByteArray ffff("\357\277\277"); QTextCodec::ConverterState state(QTextCodec::ConvertInvalidToNull); QVERIFY(codec->toUnicode(ffff.constData(), ffff.length(), &state) == QByteArray::fromHex("EFBFBF")); } void tst_QTextCodec::flagF7808080() const { /* This test case stems from test not-wf-sa-170, tests/qxmlstream/XML-Test-Suite/xmlconf/xmltest/not-wf/sa/166.xml, * whose description reads: * * "Four byte UTF-8 encodings can encode UCS-4 characters * which are beyond the range of legal XML characters * (and can't be expressed in Unicode surrogate pairs). * This document holds such a character." * * In binary, this is: * 11110111100000001000000010000000 * * * * * * 11110www10xxxxxx10yyyyyy10zzzzzz * * With multibyte logic removed it is the codepoint 0x1C0000. */ QByteArray input; input.resize(4); input[0] = char(0xF7); input[1] = char(0x80); input[2] = char(0x80); input[3] = char(0x80); QTextCodec *const codec = QTextCodec::codecForMib(106); // UTF-8 QVERIFY(codec); //QVERIFY(!codec->canEncode(QChar(0x1C0000))); QTextCodec::ConverterState state(QTextCodec::ConvertInvalidToNull); QCOMPARE(codec->toUnicode(input.constData(), input.length(), &state), QString(input.size(), QChar(0))); } void tst_QTextCodec::nonFlaggedEFBFBF() const { /* Check that the codec does NOT flag EFBFBF. * This is a regression test; see QTBUG-33229 */ QByteArray validInput; validInput.resize(3); validInput[0] = char(0xEF); validInput[1] = char(0xBF); validInput[2] = char(0xBF); const QTextCodec *const codec = QTextCodec::codecForMib(106); // UTF-8 QVERIFY(codec); { //QVERIFY(!codec->canEncode(QChar(0xFFFF))); QTextCodec::ConverterState state(QTextCodec::ConvertInvalidToNull); QVERIFY(codec->toUnicode(validInput.constData(), validInput.length(), &state) == QByteArray::fromHex("EFBFBF")); QByteArray start("<?pi "); start.append(validInput); start.append("?>"); } // Check that 0xEFBFBF is correctly decoded when preceded by an arbitrary character { QByteArray start("B"); start.append(validInput); QTextCodec::ConverterState state(QTextCodec::ConvertInvalidToNull); QVERIFY(codec->toUnicode(start.constData(), start.length(), &state) == QByteArray("B").append(QByteArray::fromHex("EFBFBF"))); } } void tst_QTextCodec::decode0D() const { QByteArray input; input.resize(3); input[0] = 'A'; input[1] = '\r'; input[2] = 'B'; QCOMPARE(QString::fromUtf8(input.constData()).toUtf8(), input); } void tst_QTextCodec::aliasForUTF16() const { QVERIFY(QTextCodec::codecForName("UTF-16")->aliases().isEmpty()); } void tst_QTextCodec::mibForTSCII() const { QTextCodec *codec = QTextCodec::codecForName("TSCII"); QVERIFY(codec); QCOMPARE(codec->mibEnum(), 2107); } void tst_QTextCodec::codecForTSCII() const { QTextCodec *codec = QTextCodec::codecForMib(2107); QVERIFY(codec); QCOMPARE(codec->mibEnum(), 2107); } void tst_QTextCodec::iso8859_16() const { QTextCodec *codec = QTextCodec::codecForName("ISO8859-16"); QVERIFY(codec); QCOMPARE(codec->name(), QByteArray("ISO-8859-16")); } static QString fromInvalidUtf8Sequence(const QByteArray &ba) { return QString().fill(QChar::ReplacementCharacter, ba.size()); } // copied from tst_QString::fromUtf8_data() void tst_QTextCodec::utf8Codec_data() { QTest::addColumn<QByteArray>("utf8"); QTest::addColumn<QString>("res"); QTest::addColumn<int>("len"); QString str; QTest::newRow("str0") << QByteArray("abcdefgh") << QString("abcdefgh") << -1; QTest::newRow("str0-len") << QByteArray("abcdefgh") << QString("abc") << 3; QTest::newRow("str1") << QByteArray("\303\266\303\244\303\274\303\226\303\204\303\234\303\270\303\246\303\245\303\230\303\206\303\205") << QString::fromLatin1("\366\344\374\326\304\334\370\346\345\330\306\305") << -1; QTest::newRow("str1-len") << QByteArray("\303\266\303\244\303\274\303\226\303\204\303\234\303\270\303\246\303\245\303\230\303\206\303\205") << QString::fromLatin1("\366\344\374\326\304") << 10; str += QChar(0x05e9); str += QChar(0x05d3); str += QChar(0x05d2); QTest::newRow("str2") << QByteArray("\327\251\327\223\327\222") << str << -1; str = QChar(0x05e9); QTest::newRow("str2-len") << QByteArray("\327\251\327\223\327\222") << str << 2; str = QChar(0x20ac); str += " some text"; QTest::newRow("str3") << QByteArray("\342\202\254 some text") << str << -1; str = QChar(0x20ac); str += " some "; QTest::newRow("str3-len") << QByteArray("\342\202\254 some text") << str << 9; str = "hello"; str += QChar::ReplacementCharacter; str += QChar(0x68); str += QChar::ReplacementCharacter; str += QChar::ReplacementCharacter; str += QChar::ReplacementCharacter; str += QChar::ReplacementCharacter; str += QChar(0x61); str += QChar::ReplacementCharacter; QTest::newRow("invalid utf8") << QByteArray("hello\344h\344\344\366\344a\304") << str << -1; QTest::newRow("invalid utf8-len") << QByteArray("hello\344h\344\344\366\344a\304") << QString("hello") << 5; str = "Prohl"; str += QChar::ReplacementCharacter; str += QChar::ReplacementCharacter; str += QLatin1Char('e'); str += QChar::ReplacementCharacter; str += " plugin"; str += QChar::ReplacementCharacter; str += " Netscape"; QTest::newRow("task28417") << QByteArray("Prohl\355\276e\350 plugin\371 Netscape") << str << -1; QTest::newRow("task28417-len") << QByteArray("Prohl\355\276e\350 plugin\371 Netscape") << QString("") << 0; QTest::newRow("null-1") << QByteArray() << QString() << -1; QTest::newRow("null0") << QByteArray() << QString() << 0; // QTest::newRow("null5") << QByteArray() << QString() << 5; QTest::newRow("empty-1") << QByteArray("\0abcd", 5) << QString() << -1; QTest::newRow("empty0") << QByteArray() << QString() << 0; QTest::newRow("empty5") << QByteArray("\0abcd", 5) << QString::fromLatin1("\0abcd", 5) << 5; QTest::newRow("other-1") << QByteArray("ab\0cd", 5) << QString::fromLatin1("ab") << -1; QTest::newRow("other5") << QByteArray("ab\0cd", 5) << QString::fromLatin1("ab\0cd", 5) << 5; str = "Old Italic: "; str += QChar(0xd800); str += QChar(0xdf00); str += QChar(0xd800); str += QChar(0xdf01); str += QChar(0xd800); str += QChar(0xdf02); str += QChar(0xd800); str += QChar(0xdf03); str += QChar(0xd800); str += QChar(0xdf04); QTest::newRow("surrogate") << QByteArray("Old Italic: \360\220\214\200\360\220\214\201\360\220\214\202\360\220\214\203\360\220\214\204") << str << -1; QTest::newRow("surrogate-len") << QByteArray("Old Italic: \360\220\214\200\360\220\214\201\360\220\214\202\360\220\214\203\360\220\214\204") << str.left(16) << 20; // from http://www.w3.org/2001/06/utf-8-wrong/UTF-8-test.html // 2.1.1 U+00000000 QByteArray utf8; utf8 += char(0x00); str = QChar(QChar::Null); QTest::newRow("http://www.w3.org/2001/06/utf-8-wrong/UTF-8-test.html 2.1.1") << utf8 << str << 1; // 2.1.2 U+00000080 utf8.clear(); utf8 += char(0xc2); utf8 += char(0x80); str = QChar(0x80); QTest::newRow("http://www.w3.org/2001/06/utf-8-wrong/UTF-8-test.html 2.1.2") << utf8 << str << -1; // 2.1.3 U+00000800 utf8.clear(); utf8 += char(0xe0); utf8 += char(0xa0); utf8 += char(0x80); str = QChar(0x800); QTest::newRow("http://www.w3.org/2001/06/utf-8-wrong/UTF-8-test.html 2.1.3") << utf8 << str << -1; // 2.1.4 U+00010000 utf8.clear(); utf8 += char(0xf0); utf8 += char(0x90); utf8 += char(0x80); utf8 += char(0x80); str.clear(); str += QChar(0xd800); str += QChar(0xdc00); QTest::newRow("http://www.w3.org/2001/06/utf-8-wrong/UTF-8-test.html 2.1.4") << utf8 << str << -1; // 2.1.5 U+00200000 (not a valid Unicode character) utf8.clear(); utf8 += char(0xf8); utf8 += char(0x88); utf8 += char(0x80); utf8 += char(0x80); utf8 += char(0x80); str = fromInvalidUtf8Sequence(utf8); QTest::newRow("http://www.w3.org/2001/06/utf-8-wrong/UTF-8-test.html 2.1.5") << utf8 << str << -1; // 2.1.6 U+04000000 (not a valid Unicode character) utf8.clear(); utf8 += char(0xfc); utf8 += char(0x84); utf8 += char(0x80); utf8 += char(0x80); utf8 += char(0x80); utf8 += char(0x80); str = fromInvalidUtf8Sequence(utf8); QTest::newRow("http://www.w3.org/2001/06/utf-8-wrong/UTF-8-test.html 2.1.6") << utf8 << str << -1; // 2.2.1 U+0000007F utf8.clear(); utf8 += char(0x7f); str = QChar(0x7f); QTest::newRow("http://www.w3.org/2001/06/utf-8-wrong/UTF-8-test.html 2.2.1") << utf8 << str << -1; // 2.2.2 U+000007FF utf8.clear(); utf8 += char(0xdf); utf8 += char(0xbf); str = QChar(0x7ff); QTest::newRow("http://www.w3.org/2001/06/utf-8-wrong/UTF-8-test.html 2.2.2") << utf8 << str << -1; // 2.2.3 U+000FFFF - non-character code utf8.clear(); utf8 += char(0xef); utf8 += char(0xbf); utf8 += char(0xbf); str = QString::fromUtf8(utf8); QTest::newRow("http://www.w3.org/2001/06/utf-8-wrong/UTF-8-test.html 2.2.3") << utf8 << str << -1; // 2.2.4 U+001FFFFF utf8.clear(); utf8 += char(0xf7); utf8 += char(0xbf); utf8 += char(0xbf); utf8 += char(0xbf); str = fromInvalidUtf8Sequence(utf8); QTest::newRow("http://www.w3.org/2001/06/utf-8-wrong/UTF-8-test.html 2.2.4") << utf8 << str << -1; // 2.2.5 U+03FFFFFF (not a valid Unicode character) utf8.clear(); utf8 += char(0xfb); utf8 += char(0xbf); utf8 += char(0xbf); utf8 += char(0xbf); utf8 += char(0xbf); str = fromInvalidUtf8Sequence(utf8); QTest::newRow("http://www.w3.org/2001/06/utf-8-wrong/UTF-8-test.html 2.2.5") << utf8 << str << -1; // 2.2.6 U+7FFFFFFF utf8.clear(); utf8 += char(0xfd); utf8 += char(0xbf); utf8 += char(0xbf); utf8 += char(0xbf); utf8 += char(0xbf); utf8 += char(0xbf); str = fromInvalidUtf8Sequence(utf8); QTest::newRow("http://www.w3.org/2001/06/utf-8-wrong/UTF-8-test.html 2.2.6") << utf8 << str << -1; // 2.3.1 U+0000D7FF utf8.clear(); utf8 += char(0xed); utf8 += char(0x9f); utf8 += char(0xbf); str = QChar(0xd7ff); QTest::newRow("http://www.w3.org/2001/06/utf-8-wrong/UTF-8-test.html 2.3.1") << utf8 << str << -1; // 2.3.2 U+0000E000 utf8.clear(); utf8 += char(0xee); utf8 += char(0x80); utf8 += char(0x80); str = QChar(0xe000); QTest::newRow("http://www.w3.org/2001/06/utf-8-wrong/UTF-8-test.html 2.3.2") << utf8 << str << -1; // 2.3.3 U+0000FFFD utf8.clear(); utf8 += char(0xef); utf8 += char(0xbf); utf8 += char(0xbd); str = QChar(QChar::ReplacementCharacter); QTest::newRow("http://www.w3.org/2001/06/utf-8-wrong/UTF-8-test.html 2.3.3") << utf8 << str << -1; // 2.3.4 U+0010FFFD utf8.clear(); utf8 += char(0xf4); utf8 += char(0x8f); utf8 += char(0xbf); utf8 += char(0xbd); str.clear(); str += QChar(0xdbff); str += QChar(0xdffd); QTest::newRow("http://www.w3.org/2001/06/utf-8-wrong/UTF-8-test.html 2.3.4") << utf8 << str << -1; // 2.3.5 U+00110000 utf8.clear(); utf8 += char(0xf4); utf8 += char(0x90); utf8 += char(0x80); utf8 += char(0x80); str = fromInvalidUtf8Sequence(utf8); QTest::newRow("http://www.w3.org/2001/06/utf-8-wrong/UTF-8-test.html 2.3.5") << utf8 << str << -1; // 3.1.1 utf8.clear(); utf8 += char(0x80); str = fromInvalidUtf8Sequence(utf8); QTest::newRow("http://www.w3.org/2001/06/utf-8-wrong/UTF-8-test.html 3.1.1") << utf8 << str << -1; // 3.1.2 utf8.clear(); utf8 += char(0xbf); str = fromInvalidUtf8Sequence(utf8); QTest::newRow("http://www.w3.org/2001/06/utf-8-wrong/UTF-8-test.html 3.1.2") << utf8 << str << -1; // 3.1.3 utf8.clear(); utf8 += char(0x80); utf8 += char(0xbf); str = fromInvalidUtf8Sequence(utf8); QTest::newRow("http://www.w3.org/2001/06/utf-8-wrong/UTF-8-test.html 3.1.3") << utf8 << str << -1; // 3.1.4 utf8.clear(); utf8 += char(0x80); utf8 += char(0xbf); utf8 += char(0x80); str = fromInvalidUtf8Sequence(utf8); QTest::newRow("http://www.w3.org/2001/06/utf-8-wrong/UTF-8-test.html 3.1.4") << utf8 << str << -1; // 3.1.5 utf8.clear(); utf8 += char(0x80); utf8 += char(0xbf); utf8 += char(0x80); utf8 += char(0xbf); str = fromInvalidUtf8Sequence(utf8); QTest::newRow("http://www.w3.org/2001/06/utf-8-wrong/UTF-8-test.html 3.1.5") << utf8 << str << -1; // 3.1.6 utf8.clear(); utf8 += char(0x80); utf8 += char(0xbf); utf8 += char(0x80); utf8 += char(0xbf); utf8 += char(0x80); str = fromInvalidUtf8Sequence(utf8); QTest::newRow("http://www.w3.org/2001/06/utf-8-wrong/UTF-8-test.html 3.1.6") << utf8 << str << -1; // 3.1.7 utf8.clear(); utf8 += char(0x80); utf8 += char(0xbf); utf8 += char(0x80); utf8 += char(0xbf); utf8 += char(0x80); utf8 += char(0xbf); str = fromInvalidUtf8Sequence(utf8); QTest::newRow("http://www.w3.org/2001/06/utf-8-wrong/UTF-8-test.html 3.1.7") << utf8 << str << -1; // 3.1.8 utf8.clear(); utf8 += char(0x80); utf8 += char(0xbf); utf8 += char(0x80); utf8 += char(0xbf); utf8 += char(0x80); utf8 += char(0xbf); utf8 += char(0x80); str = fromInvalidUtf8Sequence(utf8); QTest::newRow("http://www.w3.org/2001/06/utf-8-wrong/UTF-8-test.html 3.1.8") << utf8 << str << -1; // 3.1.9 utf8.clear(); for (uint i = 0x80; i<= 0xbf; ++i) utf8 += i; str = fromInvalidUtf8Sequence(utf8); QTest::newRow("http://www.w3.org/2001/06/utf-8-wrong/UTF-8-test.html 3.1.9") << utf8 << str << -1; // 3.2.1 utf8.clear(); str.clear(); for (uint i = 0xc8; i <= 0xdf; ++i) { utf8 += i; utf8 += char(0x20); str += QChar::ReplacementCharacter; str += QChar(0x0020); } QTest::newRow("http://www.w3.org/2001/06/utf-8-wrong/UTF-8-test.html 3.2.1") << utf8 << str << -1; // 3.2.2 utf8.clear(); str.clear(); for (uint i = 0xe0; i <= 0xef; ++i) { utf8 += i; utf8 += char(0x20); str += QChar::ReplacementCharacter; str += QChar(0x0020); } QTest::newRow("http://www.w3.org/2001/06/utf-8-wrong/UTF-8-test.html 3.2.2") << utf8 << str << -1; // 3.2.3 utf8.clear(); str.clear(); for (uint i = 0xf0; i <= 0xf7; ++i) { utf8 += i; utf8 += 0x20; str += QChar::ReplacementCharacter; str += QChar(0x0020); } QTest::newRow("http://www.w3.org/2001/06/utf-8-wrong/UTF-8-test.html 3.2.3") << utf8 << str << -1; // 3.2.4 utf8.clear(); str.clear(); for (uint i = 0xf8; i <= 0xfb; ++i) { utf8 += i; utf8 += 0x20; str += QChar::ReplacementCharacter; str += QChar(0x0020); } QTest::newRow("http://www.w3.org/2001/06/utf-8-wrong/UTF-8-test.html 3.2.4") << utf8 << str << -1; // 3.2.5 utf8.clear(); str.clear(); for (uint i = 0xfc; i <= 0xfd; ++i) { utf8 += i; utf8 += 0x20; str += QChar::ReplacementCharacter; str += QChar(0x0020); } QTest::newRow("http://www.w3.org/2001/06/utf-8-wrong/UTF-8-test.html 3.2.5") << utf8 << str << -1; // 3.3.1 utf8.clear(); utf8 += char(0xc0); str = fromInvalidUtf8Sequence(utf8); QTest::newRow("http://www.w3.org/2001/06/utf-8-wrong/UTF-8-test.html 3.3.1") << utf8 << str << -1; utf8 += char(0x30); str += 0x30; QTest::newRow("http://www.w3.org/2001/06/utf-8-wrong/UTF-8-test.html 3.3.1-1") << utf8 << str << -1; // 3.3.2 utf8.clear(); utf8 += char(0xe0); utf8 += char(0x80); str = fromInvalidUtf8Sequence(utf8); QTest::newRow("http://www.w3.org/2001/06/utf-8-wrong/UTF-8-test.html 3.3.2") << utf8 << str << -1; utf8 += char(0x30); str += 0x30; QTest::newRow("http://www.w3.org/2001/06/utf-8-wrong/UTF-8-test.html 3.3.2-1") << utf8 << str << -1; utf8.clear(); utf8 += char(0xe0); str = fromInvalidUtf8Sequence(utf8); QTest::newRow("http://www.w3.org/2001/06/utf-8-wrong/UTF-8-test.html 3.3.2-2") << utf8 << str << -1; utf8 += 0x30; str += 0x30; QTest::newRow("http://www.w3.org/2001/06/utf-8-wrong/UTF-8-test.html 3.3.2-3") << utf8 << str << -1; // 3.3.3 utf8.clear(); utf8 += char(0xf0); utf8 += char(0x80); utf8 += char(0x80); str = fromInvalidUtf8Sequence(utf8); QTest::newRow("http://www.w3.org/2001/06/utf-8-wrong/UTF-8-test.html 3.3.3") << utf8 << str << -1; utf8 += char(0x30); str += 0x30; QTest::newRow("http://www.w3.org/2001/06/utf-8-wrong/UTF-8-test.html 3.3.3-1") << utf8 << str << -1; utf8.clear(); utf8 += char(0xf0); str = fromInvalidUtf8Sequence(utf8); QTest::newRow("http://www.w3.org/2001/06/utf-8-wrong/UTF-8-test.html 3.3.3-2") << utf8 << str << -1; utf8 += char(0x30); str += 0x30; QTest::newRow("http://www.w3.org/2001/06/utf-8-wrong/UTF-8-test.html 3.3.3-3") << utf8 << str << -1; utf8.clear(); utf8 += char(0xf0); utf8 += char(0x80); str = fromInvalidUtf8Sequence(utf8); QTest::newRow("http://www.w3.org/2001/06/utf-8-wrong/UTF-8-test.html 3.3.3-4") << utf8 << str << -1; utf8 += char(0x30); str += 0x30; QTest::newRow("http://www.w3.org/2001/06/utf-8-wrong/UTF-8-test.html 3.3.3-5") << utf8 << str << -1; // 3.3.4 utf8.clear(); utf8 += char(0xf8); utf8 += char(0x80); utf8 += char(0x80); utf8 += char(0x80); str = fromInvalidUtf8Sequence(utf8); QTest::newRow("http://www.w3.org/2001/06/utf-8-wrong/UTF-8-test.html 3.3.4") << utf8 << str << -1; utf8 += char(0x30); str += 0x30; QTest::newRow("http://www.w3.org/2001/06/utf-8-wrong/UTF-8-test.html 3.3.4-1") << utf8 << str << -1; utf8.clear(); utf8 += char(0xf8); utf8 += char(0x80); utf8 += char(0x80); str = fromInvalidUtf8Sequence(utf8); QTest::newRow("http://www.w3.org/2001/06/utf-8-wrong/UTF-8-test.html 3.3.4-2") << utf8 << str << -1; utf8 += char(0x30); str += 0x30; QTest::newRow("http://www.w3.org/2001/06/utf-8-wrong/UTF-8-test.html 3.3.4-3") << utf8 << str << -1; utf8.clear(); utf8 += char(0xf8); utf8 += char(0x80); str = fromInvalidUtf8Sequence(utf8); QTest::newRow("http://www.w3.org/2001/06/utf-8-wrong/UTF-8-test.html 3.3.4-4") << utf8 << str << -1; utf8 += char(0x30); str += 0x30; QTest::newRow("http://www.w3.org/2001/06/utf-8-wrong/UTF-8-test.html 3.3.4-5") << utf8 << str << -1; utf8.clear(); utf8 += char(0xf8); str = fromInvalidUtf8Sequence(utf8); QTest::newRow("http://www.w3.org/2001/06/utf-8-wrong/UTF-8-test.html 3.3.4-6") << utf8 << str << -1; utf8 += char(0x30); str += 0x30; QTest::newRow("http://www.w3.org/2001/06/utf-8-wrong/UTF-8-test.html 3.3.4-7") << utf8 << str << -1; // 3.3.5 utf8.clear(); utf8 += char(0xfc); utf8 += char(0x80); utf8 += char(0x80); utf8 += char(0x80); utf8 += char(0x80); str = fromInvalidUtf8Sequence(utf8); QTest::newRow("http://www.w3.org/2001/06/utf-8-wrong/UTF-8-test.html 3.3.5") << utf8 << str << -1; utf8 += char(0x30); str += 0x30; QTest::newRow("http://www.w3.org/2001/06/utf-8-wrong/UTF-8-test.html 3.3.5-1") << utf8 << str << -1; utf8.clear(); utf8 += char(0xfc); utf8 += char(0x80); utf8 += char(0x80); utf8 += char(0x80); str = fromInvalidUtf8Sequence(utf8); QTest::newRow("http://www.w3.org/2001/06/utf-8-wrong/UTF-8-test.html 3.3.5-2") << utf8 << str << -1; utf8 += char(0x30); str += 0x30; QTest::newRow("http://www.w3.org/2001/06/utf-8-wrong/UTF-8-test.html 3.3.5-3") << utf8 << str << -1; utf8.clear(); utf8 += char(0xfc); utf8 += char(0x80); utf8 += char(0x80); str = fromInvalidUtf8Sequence(utf8); QTest::newRow("http://www.w3.org/2001/06/utf-8-wrong/UTF-8-test.html 3.3.5-4") << utf8 << str << -1; utf8 += char(0x30); str += 0x30; QTest::newRow("http://www.w3.org/2001/06/utf-8-wrong/UTF-8-test.html 3.3.5-5") << utf8 << str << -1; utf8.clear(); utf8 += char(0xfc); utf8 += char(0x80); str = fromInvalidUtf8Sequence(utf8); QTest::newRow("http://www.w3.org/2001/06/utf-8-wrong/UTF-8-test.html 3.3.5-6") << utf8 << str << -1; utf8 += char(0x30); str += 0x30; QTest::newRow("http://www.w3.org/2001/06/utf-8-wrong/UTF-8-test.html 3.3.5-7") << utf8 << str << -1; utf8.clear(); utf8 += char(0xfc); str = fromInvalidUtf8Sequence(utf8); QTest::newRow("http://www.w3.org/2001/06/utf-8-wrong/UTF-8-test.html 3.3.5-8") << utf8 << str << -1; utf8 += char(0x30); str += 0x30; QTest::newRow("http://www.w3.org/2001/06/utf-8-wrong/UTF-8-test.html 3.3.5-9") << utf8 << str << -1; // 3.3.6 utf8.clear(); utf8 += char(0xdf); str = fromInvalidUtf8Sequence(utf8); QTest::newRow("http://www.w3.org/2001/06/utf-8-wrong/UTF-8-test.html 3.3.6") << utf8 << str << -1; utf8 += char(0x30); str += 0x30; QTest::newRow("http://www.w3.org/2001/06/utf-8-wrong/UTF-8-test.html 3.3.6-1") << utf8 << str << -1; // 3.3.7 utf8.clear(); utf8 += char(0xef); utf8 += char(0xbf); str = fromInvalidUtf8Sequence(utf8); QTest::newRow("http://www.w3.org/2001/06/utf-8-wrong/UTF-8-test.html 3.3.7") << utf8 << str << -1; utf8 += char(0x30); str += 0x30; QTest::newRow("http://www.w3.org/2001/06/utf-8-wrong/UTF-8-test.html 3.3.7-1") << utf8 << str << -1; utf8.clear(); utf8 += char(0xef); str = fromInvalidUtf8Sequence(utf8); QTest::newRow("http://www.w3.org/2001/06/utf-8-wrong/UTF-8-test.html 3.3.7-2") << utf8 << str << -1; utf8 += char(0x30); str += 0x30; QTest::newRow("http://www.w3.org/2001/06/utf-8-wrong/UTF-8-test.html 3.3.7-3") << utf8 << str << -1; // 3.3.8 utf8.clear(); utf8 += char(0xf7); utf8 += char(0xbf); utf8 += char(0xbf); str = fromInvalidUtf8Sequence(utf8); QTest::newRow("http://www.w3.org/2001/06/utf-8-wrong/UTF-8-test.html 3.3.8") << utf8 << str << -1; utf8 += char(0x30); str += 0x30; QTest::newRow("http://www.w3.org/2001/06/utf-8-wrong/UTF-8-test.html 3.3.8-1") << utf8 << str << -1; utf8.clear(); utf8 += char(0xf7); utf8 += char(0xbf); str = fromInvalidUtf8Sequence(utf8); QTest::newRow("http://www.w3.org/2001/06/utf-8-wrong/UTF-8-test.html 3.3.8-2") << utf8 << str << -1; utf8 += char(0x30); str += 0x30; QTest::newRow("http://www.w3.org/2001/06/utf-8-wrong/UTF-8-test.html 3.3.8-3") << utf8 << str << -1; utf8.clear(); utf8 += char(0xf7); str = fromInvalidUtf8Sequence(utf8); QTest::newRow("http://www.w3.org/2001/06/utf-8-wrong/UTF-8-test.html 3.3.8-4") << utf8 << str << -1; utf8 += char(0x30); str += 0x30; QTest::newRow("http://www.w3.org/2001/06/utf-8-wrong/UTF-8-test.html 3.3.8-5") << utf8 << str << -1; // 3.3.9 utf8.clear(); utf8 += char(0xfb); utf8 += char(0xbf); utf8 += char(0xbf); utf8 += char(0xbf); str = fromInvalidUtf8Sequence(utf8); QTest::newRow("http://www.w3.org/2001/06/utf-8-wrong/UTF-8-test.html 3.3.9") << utf8 << str << -1; utf8 += char(0x30); str += 0x30; QTest::newRow("http://www.w3.org/2001/06/utf-8-wrong/UTF-8-test.html 3.3.9-1") << utf8 << str << -1; utf8.clear(); utf8 += char(0xfb); utf8 += char(0xbf); utf8 += char(0xbf); str = fromInvalidUtf8Sequence(utf8); QTest::newRow("http://www.w3.org/2001/06/utf-8-wrong/UTF-8-test.html 3.3.9-2") << utf8 << str << -1; utf8 += char(0x30); str += 0x30; QTest::newRow("http://www.w3.org/2001/06/utf-8-wrong/UTF-8-test.html 3.3.9-3") << utf8 << str << -1; utf8.clear(); utf8 += char(0xfb); utf8 += char(0xbf); str = fromInvalidUtf8Sequence(utf8); QTest::newRow("http://www.w3.org/2001/06/utf-8-wrong/UTF-8-test.html 3.3.9-4") << utf8 << str << -1; utf8 += char(0x30); str += 0x30; QTest::newRow("http://www.w3.org/2001/06/utf-8-wrong/UTF-8-test.html 3.3.9-5") << utf8 << str << -1; utf8.clear(); utf8 += char(0xfb); str = fromInvalidUtf8Sequence(utf8); QTest::newRow("http://www.w3.org/2001/06/utf-8-wrong/UTF-8-test.html 3.3.9-6") << utf8 << str << -1; utf8 += char(0x30); str += 0x30; QTest::newRow("http://www.w3.org/2001/06/utf-8-wrong/UTF-8-test.html 3.3.9-7") << utf8 << str << -1; // 3.3.10 utf8.clear(); utf8 += char(0xfd); utf8 += char(0xbf); utf8 += char(0xbf); utf8 += char(0xbf); utf8 += char(0xbf); str = fromInvalidUtf8Sequence(utf8); QTest::newRow("http://www.w3.org/2001/06/utf-8-wrong/UTF-8-test.html 3.3.10") << utf8 << str << -1; utf8 += char(0x30); str += 0x30; QTest::newRow("http://www.w3.org/2001/06/utf-8-wrong/UTF-8-test.html 3.3.10-1") << utf8 << str << -1; utf8.clear(); utf8 += char(0xfd); utf8 += char(0xbf); utf8 += char(0xbf); utf8 += char(0xbf); str = fromInvalidUtf8Sequence(utf8); QTest::newRow("http://www.w3.org/2001/06/utf-8-wrong/UTF-8-test.html 3.3.10-2") << utf8 << str << -1; utf8 += char(0x30); str += 0x30; QTest::newRow("http://www.w3.org/2001/06/utf-8-wrong/UTF-8-test.html 3.3.10-3") << utf8 << str << -1; utf8.clear(); utf8 += char(0xfd); utf8 += char(0xbf); utf8 += char(0xbf); str = fromInvalidUtf8Sequence(utf8); QTest::newRow("http://www.w3.org/2001/06/utf-8-wrong/UTF-8-test.html 3.3.10-4") << utf8 << str << -1; utf8 += char(0x30); str += 0x30; QTest::newRow("http://www.w3.org/2001/06/utf-8-wrong/UTF-8-test.html 3.3.10-5") << utf8 << str << -1; utf8.clear(); utf8 += char(0xfd); utf8 += char(0xbf); str = fromInvalidUtf8Sequence(utf8); QTest::newRow("http://www.w3.org/2001/06/utf-8-wrong/UTF-8-test.html 3.3.10-6") << utf8 << str << -1; utf8 += char(0x30); str += 0x30; QTest::newRow("http://www.w3.org/2001/06/utf-8-wrong/UTF-8-test.html 3.3.10-7") << utf8 << str << -1; utf8.clear(); utf8 += char(0xfd); str = fromInvalidUtf8Sequence(utf8); QTest::newRow("http://www.w3.org/2001/06/utf-8-wrong/UTF-8-test.html 3.3.10-8") << utf8 << str << -1; utf8 += char(0x30); str += 0x30; QTest::newRow("http://www.w3.org/2001/06/utf-8-wrong/UTF-8-test.html 3.3.10-9") << utf8 << str << -1; // 3.4 utf8.clear(); utf8 += char(0xc0); utf8 += char(0xe0); utf8 += char(0x80); utf8 += char(0xf0); utf8 += char(0x80); utf8 += char(0x80); utf8 += char(0xf8); utf8 += char(0x80); utf8 += char(0x80); utf8 += char(0x80); utf8 += char(0xfc); utf8 += char(0x80); utf8 += char(0x80); utf8 += char(0x80); utf8 += char(0x80); utf8 += char(0xdf); utf8 += char(0xef); utf8 += char(0xbf); utf8 += char(0xf7); utf8 += char(0xbf); utf8 += char(0xbf); utf8 += char(0xfb); utf8 += char(0xbf); utf8 += char(0xbf); utf8 += char(0xbf); utf8 += char(0xfd); utf8 += char(0xbf); utf8 += char(0xbf); utf8 += char(0xbf); utf8 += char(0xbf); str = fromInvalidUtf8Sequence(utf8); QTest::newRow("http://www.w3.org/2001/06/utf-8-wrong/UTF-8-test.html 3.4") << utf8 << str << -1; // 3.5.1 utf8.clear(); utf8 += char(0xfe); str = fromInvalidUtf8Sequence(utf8); QTest::newRow("http://www.w3.org/2001/06/utf-8-wrong/UTF-8-test.html 3.5.1") << utf8 << str << -1; // 3.5.2 utf8.clear(); utf8 += char(0xff); str = fromInvalidUtf8Sequence(utf8); QTest::newRow("http://www.w3.org/2001/06/utf-8-wrong/UTF-8-test.html 3.5.2") << utf8 << str << -1; // 3.5.2 utf8.clear(); utf8 += char(0xfe); utf8 += char(0xfe); utf8 += char(0xff); str = fromInvalidUtf8Sequence(utf8); QTest::newRow("http://www.w3.org/2001/06/utf-8-wrong/UTF-8-test.html 3.5.2-1") << utf8 << str << -1; // 4.1.1 utf8.clear(); utf8 += char(0xc0); utf8 += char(0xaf); str = fromInvalidUtf8Sequence(utf8); QTest::newRow("http://www.w3.org/2001/06/utf-8-wrong/UTF-8-test.html 4.1.1") << utf8 << str << -1; // 4.1.2 utf8.clear(); utf8 += char(0xe0); utf8 += char(0x80); utf8 += char(0xaf); str = fromInvalidUtf8Sequence(utf8); QTest::newRow("http://www.w3.org/2001/06/utf-8-wrong/UTF-8-test.html 4.1.2") << utf8 << str << -1; // 4.1.3 utf8.clear(); utf8 += char(0xf0); utf8 += char(0x80); utf8 += char(0x80); utf8 += char(0xaf); str = fromInvalidUtf8Sequence(utf8); QTest::newRow("http://www.w3.org/2001/06/utf-8-wrong/UTF-8-test.html 4.1.3") << utf8 << str << -1; // 4.1.4 utf8.clear(); utf8 += char(0xf8); utf8 += char(0x80); utf8 += char(0x80); utf8 += char(0x80); utf8 += char(0xaf); str = fromInvalidUtf8Sequence(utf8); QTest::newRow("http://www.w3.org/2001/06/utf-8-wrong/UTF-8-test.html 4.1.4") << utf8 << str << -1; // 4.1.5 utf8.clear(); utf8 += char(0xfc); utf8 += char(0x80); utf8 += char(0x80); utf8 += char(0x80); utf8 += char(0x80); utf8 += char(0xaf); str = fromInvalidUtf8Sequence(utf8); QTest::newRow("http://www.w3.org/2001/06/utf-8-wrong/UTF-8-test.html 4.1.5") << utf8 << str << -1; // 4.2.1 utf8.clear(); utf8 += char(0xc1); utf8 += char(0xbf); str = fromInvalidUtf8Sequence(utf8); QTest::newRow("http://www.w3.org/2001/06/utf-8-wrong/UTF-8-test.html 4.2.1") << utf8 << str << -1; // 4.2.2 utf8.clear(); utf8 += char(0xe0); utf8 += char(0x9f); utf8 += char(0xbf); str = fromInvalidUtf8Sequence(utf8); QTest::newRow("http://www.w3.org/2001/06/utf-8-wrong/UTF-8-test.html 4.2.2") << utf8 << str << -1; // 4.2.3 utf8.clear(); utf8 += char(0xf0); utf8 += char(0x8f); utf8 += char(0xbf); utf8 += char(0xbf); str = fromInvalidUtf8Sequence(utf8); QTest::newRow("http://www.w3.org/2001/06/utf-8-wrong/UTF-8-test.html 4.2.3") << utf8 << str << -1; // 4.2.4 utf8.clear(); utf8 += char(0xf8); utf8 += char(0x87); utf8 += char(0xbf); utf8 += char(0xbf); utf8 += char(0xbf); str = fromInvalidUtf8Sequence(utf8); QTest::newRow("http://www.w3.org/2001/06/utf-8-wrong/UTF-8-test.html 4.2.4") << utf8 << str << -1; // 4.2.5 utf8.clear(); utf8 += char(0xfc); utf8 += char(0x83); utf8 += char(0xbf); utf8 += char(0xbf); utf8 += char(0xbf); utf8 += char(0xbf); str = fromInvalidUtf8Sequence(utf8); QTest::newRow("http://www.w3.org/2001/06/utf-8-wrong/UTF-8-test.html 4.2.5") << utf8 << str << -1; // 4.3.1 utf8.clear(); utf8 += char(0xc0); utf8 += char(0x80); str = fromInvalidUtf8Sequence(utf8); QTest::newRow("http://www.w3.org/2001/06/utf-8-wrong/UTF-8-test.html 4.3.1") << utf8 << str << -1; // 4.3.2 utf8.clear(); utf8 += char(0xe0); utf8 += char(0x80); utf8 += char(0x80); str = fromInvalidUtf8Sequence(utf8); QTest::newRow("http://www.w3.org/2001/06/utf-8-wrong/UTF-8-test.html 4.3.2") << utf8 << str << -1; // 4.3.3 utf8.clear(); utf8 += char(0xf0); utf8 += char(0x80); utf8 += char(0x80); utf8 += char(0x80); str = fromInvalidUtf8Sequence(utf8); QTest::newRow("http://www.w3.org/2001/06/utf-8-wrong/UTF-8-test.html 4.3.3") << utf8 << str << -1; // 4.3.4 utf8.clear(); utf8 += char(0xf8); utf8 += char(0x80); utf8 += char(0x80); utf8 += char(0x80); utf8 += char(0x80); str = fromInvalidUtf8Sequence(utf8); QTest::newRow("http://www.w3.org/2001/06/utf-8-wrong/UTF-8-test.html 4.3.4") << utf8 << str << -1; // 4.3.5 utf8.clear(); utf8 += char(0xfc); utf8 += char(0x80); utf8 += char(0x80); utf8 += char(0x80); utf8 += char(0x80); utf8 += char(0x80); str = fromInvalidUtf8Sequence(utf8); QTest::newRow("http://www.w3.org/2001/06/utf-8-wrong/UTF-8-test.html 4.3.5") << utf8 << str << -1; // 5.1.1 utf8.clear(); utf8 += char(0xed); utf8 += char(0xa0); utf8 += char(0x80); str = fromInvalidUtf8Sequence(utf8); QTest::newRow("http://www.w3.org/2001/06/utf-8-wrong/UTF-8-test.html 5.1.1") << utf8 << str << -1; // 5.1.2 utf8.clear(); utf8 += char(0xed); utf8 += char(0xad); utf8 += char(0xbf); str = fromInvalidUtf8Sequence(utf8); QTest::newRow("http://www.w3.org/2001/06/utf-8-wrong/UTF-8-test.html 5.1.2") << utf8 << str << -1; // 5.1.3 utf8.clear(); utf8 += char(0xed); utf8 += char(0xae); utf8 += char(0x80); str = fromInvalidUtf8Sequence(utf8); QTest::newRow("http://www.w3.org/2001/06/utf-8-wrong/UTF-8-test.html 5.1.3") << utf8 << str << -1; // 5.1.4 utf8.clear(); utf8 += char(0xed); utf8 += char(0xaf); utf8 += char(0xbf); str = fromInvalidUtf8Sequence(utf8); QTest::newRow("http://www.w3.org/2001/06/utf-8-wrong/UTF-8-test.html 5.1.4") << utf8 << str << -1; // 5.1.5 utf8.clear(); utf8 += char(0xed); utf8 += char(0xb0); utf8 += char(0x80); str = fromInvalidUtf8Sequence(utf8); QTest::newRow("http://www.w3.org/2001/06/utf-8-wrong/UTF-8-test.html 5.1.5") << utf8 << str << -1; // 5.1.6 utf8.clear(); utf8 += char(0xed); utf8 += char(0xbe); utf8 += char(0x80); str = fromInvalidUtf8Sequence(utf8); QTest::newRow("http://www.w3.org/2001/06/utf-8-wrong/UTF-8-test.html 5.1.6") << utf8 << str << -1; // 5.1.7 utf8.clear(); utf8 += char(0xed); utf8 += char(0xbf); utf8 += char(0xbf); str = fromInvalidUtf8Sequence(utf8); QTest::newRow("http://www.w3.org/2001/06/utf-8-wrong/UTF-8-test.html 5.1.7") << utf8 << str << -1; // 5.2.1 utf8.clear(); utf8 += char(0xed); utf8 += char(0xa0); utf8 += char(0x80); utf8 += char(0xed); utf8 += char(0xb0); utf8 += char(0x80); str = fromInvalidUtf8Sequence(utf8); QTest::newRow("http://www.w3.org/2001/06/utf-8-wrong/UTF-8-test.html 5.2.1") << utf8 << str << -1; // 5.2.2 utf8.clear(); utf8 += char(0xed); utf8 += char(0xa0); utf8 += char(0x80); utf8 += char(0xed); utf8 += char(0xbf); utf8 += char(0xbf); str = fromInvalidUtf8Sequence(utf8); QTest::newRow("http://www.w3.org/2001/06/utf-8-wrong/UTF-8-test.html 5.2.2") << utf8 << str << -1; // 5.2.3 utf8.clear(); utf8 += char(0xed); utf8 += char(0xad); utf8 += char(0xbf); utf8 += char(0xed); utf8 += char(0xb0); utf8 += char(0x80); str = fromInvalidUtf8Sequence(utf8); QTest::newRow("http://www.w3.org/2001/06/utf-8-wrong/UTF-8-test.html 5.2.3") << utf8 << str << -1; // 5.2.4 utf8.clear(); utf8 += char(0xed); utf8 += char(0xad); utf8 += char(0xbf); utf8 += char(0xed); utf8 += char(0xbf); utf8 += char(0xbf); str = fromInvalidUtf8Sequence(utf8); QTest::newRow("http://www.w3.org/2001/06/utf-8-wrong/UTF-8-test.html 5.2.4") << utf8 << str << -1; // 5.2.5 utf8.clear(); utf8 += char(0xed); utf8 += char(0xae); utf8 += char(0x80); utf8 += char(0xed); utf8 += char(0xb0); utf8 += char(0x80); str = fromInvalidUtf8Sequence(utf8); QTest::newRow("http://www.w3.org/2001/06/utf-8-wrong/UTF-8-test.html 5.2.5") << utf8 << str << -1; // 5.2.6 utf8.clear(); utf8 += char(0xed); utf8 += char(0xae); utf8 += char(0x80); utf8 += char(0xed); utf8 += char(0xbf); utf8 += char(0xbf); str = fromInvalidUtf8Sequence(utf8); QTest::newRow("http://www.w3.org/2001/06/utf-8-wrong/UTF-8-test.html 5.2.6") << utf8 << str << -1; // 5.2.7 utf8.clear(); utf8 += char(0xed); utf8 += char(0xaf); utf8 += char(0xbf); utf8 += char(0xed); utf8 += char(0xb0); utf8 += char(0x80); str = fromInvalidUtf8Sequence(utf8); QTest::newRow("http://www.w3.org/2001/06/utf-8-wrong/UTF-8-test.html 5.2.7") << utf8 << str << -1; // 5.2.8 utf8.clear(); utf8 += char(0xed); utf8 += char(0xaf); utf8 += char(0xbf); utf8 += char(0xed); utf8 += char(0xbf); utf8 += char(0xbf); str = fromInvalidUtf8Sequence(utf8); QTest::newRow("http://www.w3.org/2001/06/utf-8-wrong/UTF-8-test.html 5.2.8") << utf8 << str << -1; // 5.3.1 - non-character code utf8.clear(); utf8 += char(0xef); utf8 += char(0xbf); utf8 += char(0xbe); //str = QChar(QChar::ReplacementCharacter); str = QChar(0xfffe); QTest::newRow("http://www.w3.org/2001/06/utf-8-wrong/UTF-8-test.html 5.3.1") << utf8 << str << -1; // 5.3.2 - non-character code utf8.clear(); utf8 += char(0xef); utf8 += char(0xbf); utf8 += char(0xbf); //str = QChar(QChar::ReplacementCharacter); str = QChar(0xffff); QTest::newRow("http://www.w3.org/2001/06/utf-8-wrong/UTF-8-test.html 5.3.2") << utf8 << str << -1; } void tst_QTextCodec::utf8Codec() { QTextCodec *codec = QTextCodec::codecForMib(106); // UTF-8 QVERIFY(codec != 0); QFETCH(QByteArray, utf8); QFETCH(QString, res); QFETCH(int, len); QString str = codec->toUnicode(utf8.isNull() ? 0 : utf8.constData(), len < 0 ? qstrlen(utf8.constData()) : len); QCOMPARE(str, res); str = QString::fromUtf8(utf8.isNull() ? 0 : utf8.constData(), len); QCOMPARE(str, res); } void tst_QTextCodec::utf8bom_data() { QTest::addColumn<QByteArray>("data"); QTest::addColumn<QString>("result"); QTest::newRow("nobom") << QByteArray("\302\240", 2) << QString::fromLatin1("\240"); { static const ushort data[] = { 0x201d }; QTest::newRow("nobom 2") << QByteArray("\342\200\235", 3) << QString::fromUtf16(data, sizeof(data)/sizeof(short)); } { static const ushort data[] = { 0xf000 }; QTest::newRow("bom1") << QByteArray("\357\200\200", 3) << QString::fromUtf16(data, sizeof(data)/sizeof(short)); } { static const ushort data[] = { 0xfec0 }; QTest::newRow("bom2") << QByteArray("\357\273\200", 3) << QString::fromUtf16(data, sizeof(data)/sizeof(short)); } { QTest::newRow("normal-bom") << QByteArray("\357\273\277a", 4) << QString("a"); } { // test the non-SIMD code-path static const ushort data[] = { 0x61, 0xfeff, 0x62 }; QTest::newRow("middle-bom (non SIMD)") << QByteArray("a\357\273\277b") << QString::fromUtf16(data, sizeof(data)/sizeof(short)); } { // test the SIMD code-path static const ushort data[] = { 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x6b, 0x6c, 0xfeff, 0x6d }; QTest::newRow("middle-bom (SIMD)") << QByteArray("abcdefghijkl\357\273\277m") << QString::fromUtf16(data, sizeof(data)/sizeof(short)); } } void tst_QTextCodec::utf8bom() { QFETCH(QByteArray, data); QFETCH(QString, result); QTextCodec *const codec = QTextCodec::codecForMib(106); // UTF-8 QVERIFY(codec); QCOMPARE(codec->toUnicode(data.constData(), data.length(), 0), result); QTextCodec::ConverterState state; QCOMPARE(codec->toUnicode(data.constData(), data.length(), &state), result); } void tst_QTextCodec::utf8stateful_data() { QTest::addColumn<QByteArray>("buffer1"); QTest::addColumn<QByteArray>("buffer2"); QTest::addColumn<QString>("result"); // null QString indicates decoder error // valid buffer continuations QTest::newRow("1of2+valid") << QByteArray("\xc2") << QByteArray("\xa0") << "\xc2\xa0"; QTest::newRow("1of3+valid") << QByteArray("\xe0") << QByteArray("\xa0\x80") << "\xe0\xa0\x80"; QTest::newRow("2of3+valid") << QByteArray("\xe0\xa0") << QByteArray("\x80") << "\xe0\xa0\x80"; QTest::newRow("1of4+valid") << QByteArray("\360") << QByteArray("\220\210\203") << "\360\220\210\203"; QTest::newRow("2of4+valid") << QByteArray("\360\220") << QByteArray("\210\203") << "\360\220\210\203"; QTest::newRow("3of4+valid") << QByteArray("\360\220\210") << QByteArray("\203") << "\360\220\210\203"; QTest::newRow("1ofBom+valid") << QByteArray("\xef") << QByteArray("\xbb\xbf") << ""; QTest::newRow("2ofBom+valid") << QByteArray("\xef\xbb") << QByteArray("\xbf") << ""; // invalid continuation QTest::newRow("1of2+invalid") << QByteArray("\xc2") << QByteArray("a") << QString(); QTest::newRow("1of3+invalid") << QByteArray("\xe0") << QByteArray("a") << QString(); QTest::newRow("2of3+invalid") << QByteArray("\xe0\xa0") << QByteArray("a") << QString(); QTest::newRow("1of4+invalid") << QByteArray("\360") << QByteArray("a") << QString(); QTest::newRow("2of4+invalid") << QByteArray("\360\220") << QByteArray("a") << QString(); QTest::newRow("3of4+invalid") << QByteArray("\360\220\210") << QByteArray("a") << QString(); // invalid: sequence too short (the empty second buffer causes a state reset) QTest::newRow("1of2+empty") << QByteArray("\xc2") << QByteArray() << QString(); QTest::newRow("1of3+empty") << QByteArray("\xe0") << QByteArray() << QString(); QTest::newRow("2of3+empty") << QByteArray("\xe0\xa0") << QByteArray() << QString(); QTest::newRow("1of4+empty") << QByteArray("\360") << QByteArray() << QString(); QTest::newRow("2of4+empty") << QByteArray("\360\220") << QByteArray() << QString(); QTest::newRow("3of4+empty") << QByteArray("\360\220\210") << QByteArray() << QString(); // overlong sequence: QTest::newRow("overlong-1of2") << QByteArray("\xc1") << QByteArray("\x81") << QString(); QTest::newRow("overlong-1of3") << QByteArray("\xe0") << QByteArray("\x81\x81") << QString(); QTest::newRow("overlong-2of3") << QByteArray("\xe0\x81") << QByteArray("\x81") << QString(); QTest::newRow("overlong-1of4") << QByteArray("\xf0") << QByteArray("\x80\x81\x81") << QString(); QTest::newRow("overlong-2of4") << QByteArray("\xf0\x80") << QByteArray("\x81\x81") << QString(); QTest::newRow("overlong-3of4") << QByteArray("\xf0\x80\x81") << QByteArray("\x81") << QString(); // out of range: // leading byte 0xF4 can produce codepoints above U+10FFFF, which aren't valid QTest::newRow("outofrange1-1of4") << QByteArray("\xf4") << QByteArray("\x90\x80\x80") << QString(); QTest::newRow("outofrange1-2of4") << QByteArray("\xf4\x90") << QByteArray("\x80\x80") << QString(); QTest::newRow("outofrange1-3of4") << QByteArray("\xf4\x90\x80") << QByteArray("\x80") << QString(); QTest::newRow("outofrange2-1of4") << QByteArray("\xf5") << QByteArray("\x90\x80\x80") << QString(); QTest::newRow("outofrange2-2of4") << QByteArray("\xf5\x90") << QByteArray("\x80\x80") << QString(); QTest::newRow("outofrange2-3of4") << QByteArray("\xf5\x90\x80") << QByteArray("\x80") << QString(); QTest::newRow("outofrange-1of5") << QByteArray("\xf8") << QByteArray("\x88\x80\x80\x80") << QString(); QTest::newRow("outofrange-2of5") << QByteArray("\xf8\x88") << QByteArray("\x80\x80\x80") << QString(); QTest::newRow("outofrange-3of5") << QByteArray("\xf8\x88\x80") << QByteArray("\x80\x80") << QString(); QTest::newRow("outofrange-4of5") << QByteArray("\xf8\x88\x80\x80") << QByteArray("\x80") << QString(); QTest::newRow("outofrange-1of6") << QByteArray("\xfc") << QByteArray("\x84\x80\x80\x80\x80") << QString(); QTest::newRow("outofrange-2of6") << QByteArray("\xfc\x84") << QByteArray("\x80\x80\x80\x80") << QString(); QTest::newRow("outofrange-3of6") << QByteArray("\xfc\x84\x80") << QByteArray("\x80\x80\x80") << QString(); QTest::newRow("outofrange-4of6") << QByteArray("\xfc\x84\x80\x80") << QByteArray("\x80\x80") << QString(); QTest::newRow("outofrange-5of6") << QByteArray("\xfc\x84\x80\x80\x80") << QByteArray("\x80") << QString(); } void tst_QTextCodec::utf8stateful() { QFETCH(QByteArray, buffer1); QFETCH(QByteArray, buffer2); QFETCH(QString, result); QTextCodec *utf8codec = QTextCodec::codecForName("utf-8"); QVERIFY(utf8codec); QTextCodec::ConverterState state; memset(&state, 0, sizeof state); QString decoded1 = utf8codec->toUnicode(buffer1, buffer1.size(), &state); if (result.isNull()) { // the decoder may have found an early error (invalidChars > 0): // if it has, remainingChars == 0; // if it hasn't, then it must have a state QVERIFY2((state.remainingChars == 0) != (state.invalidChars == 0), "remainingChars = " + QByteArray::number(state.remainingChars) + "; invalidChars = " + QByteArray::number(state.invalidChars)); } else { QVERIFY(state.remainingChars > 0); QCOMPARE(state.invalidChars, 0); } QString decoded2 = utf8codec->toUnicode(buffer2, buffer2.size(), &state); QCOMPARE(state.remainingChars, 0); if (result.isNull()) { QVERIFY(state.invalidChars > 0); } else { QCOMPARE(decoded1 + decoded2, result); } } void tst_QTextCodec::utfHeaders_data() { QTest::addColumn<QByteArray>("codecName"); QTest::addColumn<int>("flags"); QTest::addColumn<QByteArray>("encoded"); QTest::addColumn<QString>("unicode"); QTest::addColumn<bool>("toUnicode"); QTest::newRow("utf8 bom") << QByteArray("UTF-8") << 0 << QByteArray("\xef\xbb\xbfhello") << QString::fromLatin1("hello") << true; QTest::newRow("utf8 nobom") << QByteArray("UTF-8") << 0 << QByteArray("hello") << QString::fromLatin1("hello") << true; QTest::newRow("utf8 bom ignore header") << QByteArray("UTF-8") << (int)QTextCodec::IgnoreHeader << QByteArray("\xef\xbb\xbfhello") << (QString(QChar(0xfeff)) + QString::fromLatin1("hello")) << true; QTest::newRow("utf8 nobom ignore header") << QByteArray("UTF-8") << (int)QTextCodec::IgnoreHeader << QByteArray("hello") << QString::fromLatin1("hello") << true; QTest::newRow("utf16 bom be") << QByteArray("UTF-16") << 0 << QByteArray("\xfe\xff\0h\0e\0l", 8) << QString::fromLatin1("hel") << true; QTest::newRow("utf16 bom le") << QByteArray("UTF-16") << 0 << QByteArray("\xff\xfeh\0e\0l\0", 8) << QString::fromLatin1("hel") << true; if (QSysInfo::ByteOrder == QSysInfo::BigEndian) { QTest::newRow("utf16 nobom") << QByteArray("UTF-16") << 0 << QByteArray("\0h\0e\0l", 6) << QString::fromLatin1("hel") << true; QTest::newRow("utf16 bom be ignore header") << QByteArray("UTF-16") << (int)QTextCodec::IgnoreHeader << QByteArray("\xfe\xff\0h\0e\0l", 8) << (QString(QChar(0xfeff)) + QString::fromLatin1("hel")) << true; } else { QTest::newRow("utf16 nobom") << QByteArray("UTF-16") << 0 << QByteArray("h\0e\0l\0", 6) << QString::fromLatin1("hel") << true; QTest::newRow("utf16 bom le ignore header") << QByteArray("UTF-16") << (int)QTextCodec::IgnoreHeader << QByteArray("\xff\xfeh\0e\0l\0", 8) << (QString(QChar(0xfeff)) + QString::fromLatin1("hel")) << true; } QTest::newRow("utf16-be bom be") << QByteArray("UTF-16BE") << 0 << QByteArray("\xfe\xff\0h\0e\0l", 8) << QString::fromLatin1("hel") << true; QTest::newRow("utf16-be nobom") << QByteArray("UTF-16BE") << 0 << QByteArray("\0h\0e\0l", 6) << QString::fromLatin1("hel") << true; QTest::newRow("utf16-be bom be ignore header") << QByteArray("UTF-16BE") << (int)QTextCodec::IgnoreHeader << QByteArray("\xfe\xff\0h\0e\0l", 8) << (QString(QChar(0xfeff)) + QString::fromLatin1("hel")) << true; QTest::newRow("utf16-le bom le") << QByteArray("UTF-16LE") << 0 << QByteArray("\xff\xfeh\0e\0l\0", 8) << QString::fromLatin1("hel") << true; QTest::newRow("utf16-le nobom") << QByteArray("UTF-16LE") << 0 << QByteArray("h\0e\0l\0", 6) << QString::fromLatin1("hel") << true; QTest::newRow("utf16-le bom le ignore header") << QByteArray("UTF-16LE") << (int)QTextCodec::IgnoreHeader << QByteArray("\xff\xfeh\0e\0l\0", 8) << (QString(QChar(0xfeff)) + QString::fromLatin1("hel")) << true; QTest::newRow("utf32 bom be") << QByteArray("UTF-32") << 0 << QByteArray("\0\0\xfe\xff\0\0\0h\0\0\0e\0\0\0l", 16) << QString::fromLatin1("hel") << true; QTest::newRow("utf32 bom le") << QByteArray("UTF-32") << 0 << QByteArray("\xff\xfe\0\0h\0\0\0e\0\0\0l\0\0\0", 16) << QString::fromLatin1("hel") << true; if (QSysInfo::ByteOrder == QSysInfo::BigEndian) { QTest::newRow("utf32 nobom") << QByteArray("UTF-32") << 0 << QByteArray("\0\0\0h\0\0\0e\0\0\0l", 12) << QString::fromLatin1("hel") << true; QTest::newRow("utf32 bom be ignore header") << QByteArray("UTF-32") << (int)QTextCodec::IgnoreHeader << QByteArray("\0\0\xfe\xff\0\0\0h\0\0\0e\0\0\0l", 16) << (QString(QChar(0xfeff)) + QString::fromLatin1("hel")) << true; } else { QTest::newRow("utf32 nobom") << QByteArray("UTF-32") << 0 << QByteArray("h\0\0\0e\0\0\0l\0\0\0", 12) << QString::fromLatin1("hel") << true; QTest::newRow("utf32 bom le ignore header") << QByteArray("UTF-32") << (int)QTextCodec::IgnoreHeader << QByteArray("\xff\xfe\0\0h\0\0\0e\0\0\0l\0\0\0", 16) << (QString(QChar(0xfeff)) + QString::fromLatin1("hel")) << true; } QTest::newRow("utf32-be bom be") << QByteArray("UTF-32BE") << 0 << QByteArray("\0\0\xfe\xff\0\0\0h\0\0\0e\0\0\0l", 16) << QString::fromLatin1("hel") << true; QTest::newRow("utf32-be nobom") << QByteArray("UTF-32BE") << 0 << QByteArray("\0\0\0h\0\0\0e\0\0\0l", 12) << QString::fromLatin1("hel") << true; QTest::newRow("utf32-be bom be ignore header") << QByteArray("UTF-32BE") << (int)QTextCodec::IgnoreHeader << QByteArray("\0\0\xfe\xff\0\0\0h\0\0\0e\0\0\0l", 16) << (QString(QChar(0xfeff)) + QString::fromLatin1("hel")) << true; QTest::newRow("utf32-le bom le") << QByteArray("UTF-32LE") << 0 << QByteArray("\xff\xfe\0\0h\0\0\0e\0\0\0l\0\0\0", 16) << QString::fromLatin1("hel") << true; QTest::newRow("utf32-le nobom") << QByteArray("UTF-32LE") << 0 << QByteArray("h\0\0\0e\0\0\0l\0\0\0", 12) << QString::fromLatin1("hel") << true; QTest::newRow("utf32-le bom le ignore header") << QByteArray("UTF-32LE") << (int)QTextCodec::IgnoreHeader << QByteArray("\xff\xfe\0\0h\0\0\0e\0\0\0l\0\0\0", 16) << (QString(QChar(0xfeff)) + QString::fromLatin1("hel")) << true; } void tst_QTextCodec::utfHeaders() { QFETCH(QByteArray, codecName); QTextCodec *codec = QTextCodec::codecForName(codecName); QVERIFY(codec != 0); QFETCH(int, flags); QTextCodec::ConversionFlags cFlags = QTextCodec::ConversionFlags(flags); QTextCodec::ConverterState state(cFlags); QFETCH(QByteArray, encoded); QFETCH(QString, unicode); QFETCH(bool, toUnicode); QLatin1String ignoreReverseTestOn = (QSysInfo::ByteOrder == QSysInfo::BigEndian) ? QLatin1String(" le") : QLatin1String(" be"); QString rowName(QTest::currentDataTag()); if (toUnicode) { QString result = codec->toUnicode(encoded.constData(), encoded.length(), &state); QCOMPARE(result.length(), unicode.length()); QCOMPARE(result, unicode); if (!rowName.endsWith("nobom") && !rowName.contains(ignoreReverseTestOn)) { QTextCodec::ConverterState state2(cFlags); QByteArray reencoded = codec->fromUnicode(unicode.unicode(), unicode.length(), &state2); QCOMPARE(reencoded, encoded); } } else { QByteArray result = codec->fromUnicode(unicode.unicode(), unicode.length(), &state); QCOMPARE(result, encoded); } } void tst_QTextCodec::codecForHtml_data() { QTest::addColumn<QByteArray>("html"); QTest::addColumn<int>("defaultCodecMib"); QTest::addColumn<int>("expectedMibEnum"); int noDefault = -1; int fallback = 4; // latin 1 QByteArray html = "<html><head></head><body>blah</body></html>"; QTest::newRow("no charset, latin 1") << html << noDefault << fallback; QTest::newRow("no charset, default UTF-8") << html << 106 << 106; html = "<html><head><meta http-equiv=\"content-type\" content=\"text/html; charset=ISO-8859-15\" /></head></html>"; QTest::newRow("latin 15, default UTF-8") << html << 106 << 111; html = "<html><head><meta content=\"text/html; charset=ISO-8859-15\" http-equiv=\"content-type\" /></head></html>"; QTest::newRow("latin 15, default UTF-8 (#2)") << html << 106 << 111; html = "<!DOCTYPE html><html><head><meta charset=\"utf-8\"><meta http-equiv=\"X-UA-Compatible\" content=\"IE=9,chrome=1\"><title>Test</title></head>"; QTest::newRow("UTF-8, no default") << html << noDefault << 106; html = "<!DOCTYPE html><html><head><meta charset=\"ISO_8859-1:1987\"><meta http-equiv=\"X-UA-Compatible\" content=\"IE=9,chrome=1\"><title>Test</title></head>"; QTest::newRow("latin 1, no default") << html << noDefault << 4; html = "<!DOCTYPE html><html><head><meta http-equiv=\"X-UA-Compatible\" content=\"IE=9,chrome=1\"><meta charset=\"utf-8\"><title>Test</title></head>"; QTest::newRow("UTF-8, no default (#2)") << html << noDefault << 106; html = "<html><head><meta http-equiv=\"content-type\" content=\"text/html; charset=UTF-8/></head></html>"; QTest::newRow("UTF-8, no quotes") << html << noDefault << 106; html = "<html><head><meta http-equiv=\"content-type\" content=\"text/html; charset='UTF-8'/></head></html>"; QTest::newRow("UTF-8, single quotes") << html << noDefault << 106; html = "<!DOCTYPE html><html><head><meta charset=utf-8><title>Test</title></head>"; QTest::newRow("UTF-8, > terminator") << html << noDefault << 106; html = "<!DOCTYPE html><html><head><meta charset= utf-8 ><title>Test</title></head>"; QTest::newRow("UTF-8, > terminator with spaces") << html << noDefault << 106; html = "<!DOCTYPE html><html><head><meta charset= utf/8 ><title>Test</title></head>"; QTest::newRow("UTF-8, > teminator with early backslash)") << html << noDefault << 106; // Test invalid charsets. html = "<html><head><meta http-equiv=\"content-type\" content=\"text/html; charset=invalid-foo\" /></head></html>"; QTest::newRow("invalid charset, no default") << html << noDefault << fallback; QTest::newRow("invalid charset, default UTF-8") << html << 106 << 106; html = "<!DOCTYPE html><html><head><meta http-equiv=\"X-UA-Compatible\" content=\"IE=9,chrome=1\"><meta charset=\""; html.prepend(QByteArray().fill(' ', 512 - html.size())); QTest::newRow("invalid charset (large header)") << html << noDefault << fallback; html = "<!DOCTYPE html><html><head><meta http-equiv=\"X-UA-Compatible\" content=\"IE=9,chrome=1\"><meta charset=\"utf-8"; QTest::newRow("invalid charset (no closing double quote)") << html << noDefault << fallback; html = "<!DOCTYPE html><html><head><meta http-equiv=\"X-UA-Compatible\" content=\"IE=9,chrome=1\"><meta charset='utf-8"; QTest::newRow("invalid charset (no closing single quote)") << html << noDefault << fallback; html = "<!DOCTYPE html><html><head><meta charset=utf-8 foo=bar><title>Test</title></head>"; QTest::newRow("invalid (space terminator)") << html << noDefault << fallback; html = "<!DOCTYPE html><html><head><meta charset=\" utf' 8 /><title>Test</title></head>"; QTest::newRow("invalid charset, early terminator (')") << html << noDefault << fallback; const char src[] = { char(0xff), char(0xfe), char(0x7a), char(0x03), 0, 0 }; html = src; QTest::newRow("greek text UTF-16LE") << html << 106 << 1014; html = "<meta http-equiv=\"content-type\" content=\"text/html; charset=utf-8\"><span style=\"color: rgb(0, 0, 0); font-family: " "'Galatia SIL'; font-size: 27px; font-style: normal; font-variant: normal; font-weight: normal; letter-spacing: normal; " "line-height: normal; orphans: auto; text-align: start; text-indent: 0px; text-transform: none; white-space: normal; widows: " "auto; word-spacing: 0px; -webkit-text-size-adjust: auto; -webkit-text-stroke-width: 0px; display: inline !important; float: " "none;\">&#x37b</span>\000"; QTest::newRow("greek text UTF-8") << html << 106 << 106; html = "<!DOCTYPE html><html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=unicode\">" "<head/><body><p>bla</p></body></html>"; // QTBUG-41998, ICU will return UTF-16. QTest::newRow("legacy unicode UTF-8") << html << 106 << 106; } void tst_QTextCodec::codecForHtml() { QFETCH(QByteArray, html); QFETCH(int, defaultCodecMib); QFETCH(int, expectedMibEnum); if (defaultCodecMib != -1) QCOMPARE(QTextCodec::codecForHtml(html, QTextCodec::codecForMib(defaultCodecMib))->mibEnum(), expectedMibEnum); else // Test one parameter version when there is no default codec. QCOMPARE(QTextCodec::codecForHtml(html)->mibEnum(), expectedMibEnum); } void tst_QTextCodec::codecForUtfText_data() { QTest::addColumn<QByteArray>("encoded"); QTest::addColumn<bool>("detected"); QTest::addColumn<int>("mib"); QTest::newRow("utf8 bom") << QByteArray("\xef\xbb\xbfhello") << true << 106; QTest::newRow("utf8 nobom") << QByteArray("hello") << false << 0; QTest::newRow("utf16 bom be") << QByteArray("\xfe\xff\0h\0e\0l", 8) << true << 1013; QTest::newRow("utf16 bom le") << QByteArray("\xff\xfeh\0e\0l\0", 8) << true << 1014; QTest::newRow("utf16 nobom") << QByteArray("\0h\0e\0l", 6) << false << 0; QTest::newRow("utf32 bom be") << QByteArray("\0\0\xfe\xff\0\0\0h\0\0\0e\0\0\0l", 16) << true << 1018; QTest::newRow("utf32 bom le") << QByteArray("\xff\xfe\0\0h\0\0\0e\0\0\0l\0\0\0", 16) << true << 1019; QTest::newRow("utf32 nobom") << QByteArray("\0\0\0h\0\0\0e\0\0\0l", 12) << false << 0; } void tst_QTextCodec::codecForUtfText() { QFETCH(QByteArray, encoded); QFETCH(bool, detected); QFETCH(int, mib); QTextCodec *codec = QTextCodec::codecForUtfText(encoded, 0); if (detected) QCOMPARE(codec->mibEnum(), mib); else QVERIFY(!codec); } #if defined(Q_OS_UNIX) void tst_QTextCodec::toLocal8Bit() { #if !QT_CONFIG(process) QSKIP("No qprocess support", SkipAll); #else QProcess process; process.start("echo/echo"); QString string(QChar(0x410)); process.write((const char*)string.utf16(), string.length()*2); process.closeWriteChannel(); process.waitForFinished(); QCOMPARE(process.exitStatus(), QProcess::NormalExit); QCOMPARE(process.exitCode(), 0); #endif } #endif class LoadAndConvert: public QRunnable { public: LoadAndConvert(const QByteArray &source, QByteArray *destination) : codecName(source), target(destination) {} QByteArray codecName; QByteArray *target; void run() { QTextCodec *c = QTextCodec::codecForName(codecName); if (!c) { qWarning() << "WARNING" << codecName << "not found?"; return; } QString str = QString::fromLatin1(codecName); QByteArray b = c->fromUnicode(str); c->toUnicode(b); *target = codecName; } }; class LoadAndConvertMIB: public QRunnable { public: LoadAndConvertMIB(int mib, int *target) : mib(mib), target(target) {} int mib; int *target; void run() { QTextCodec *c = QTextCodec::codecForMib(mib); if (!c) { qWarning() << "WARNING" << mib << "not found?"; return; } QString str = QString::number(mib); QByteArray b = c->fromUnicode(str); c->toUnicode(b); *target = mib; } }; void tst_QTextCodec::threadSafety() { QList<QByteArray> codecList = QTextCodec::availableCodecs(); const QVector<int> mibList = QTextCodec::availableMibs().toVector(); QThreadPool::globalInstance()->setMaxThreadCount(12); QVector<QByteArray> res; res.resize(codecList.size()); for (int i = 0; i < codecList.size(); ++i) { QThreadPool::globalInstance()->start(new LoadAndConvert(codecList.at(i), &res[i])); } QVector<int> res2; res2.resize(mibList.size()); for (int i = 0; i < mibList.size(); ++i) { QThreadPool::globalInstance()->start(new LoadAndConvertMIB(mibList.at(i), &res2[i])); } // wait for all threads to finish working QThreadPool::globalInstance()->waitForDone(); QCOMPARE(res.toList(), codecList); QCOMPARE(res2, mibList); } void tst_QTextCodec::invalidNames() { QVERIFY(!QTextCodec::codecForName("")); QVERIFY(!QTextCodec::codecForName(QByteArray())); QVERIFY(!QTextCodec::codecForName("-")); QVERIFY(!QTextCodec::codecForName("\1a\2b\3a\4d\5c\6s\7a\xffr\xec_\x9c_")); QVERIFY(!QTextCodec::codecForName("\n")); QVERIFY(!QTextCodec::codecForName("don't exist")); QByteArray huge = "azertyuiop^$qsdfghjklm<wxcvbn,;:=1234567890�_"; huge = huge + huge + huge + huge + huge + huge + huge + huge; huge = huge + huge + huge + huge + huge + huge + huge + huge; huge = huge + huge + huge + huge + huge + huge + huge + huge; huge = huge + huge + huge + huge + huge + huge + huge + huge; QVERIFY(!QTextCodec::codecForName(huge)); } void tst_QTextCodec::checkAliases_data() { QTest::addColumn<QByteArray>("codecName"); const QList<QByteArray> codecList = QTextCodec::availableCodecs(); for (const QByteArray &a : codecList) QTest::newRow( a.constData() ) << a; } void tst_QTextCodec::checkAliases() { QFETCH( QByteArray, codecName ); QTextCodec *c = QTextCodec::codecForName(codecName); QVERIFY(c); QCOMPARE(QTextCodec::codecForName(codecName), c); QCOMPARE(QTextCodec::codecForName(c->name()), c); const auto aliases = c->aliases(); for (const QByteArray &a : aliases) { QCOMPARE(QTextCodec::codecForName(a), c); } } void tst_QTextCodec::moreToFromUnicode_data() { QTest::addColumn<QByteArray>("codecName"); QTest::addColumn<QByteArray>("testData"); QTest::newRow("russian") << QByteArray("ISO-8859-5") << QByteArray("\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0A\x0B\x0C\x0D\x0E\x0F\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1A\x1B\x1C\x1D\x1E\x1F\x20\x21\x22\x23\x24\x25\x26\x27\x28\x29\x2A\x2B\x2C\x2D\x2E\x2F\x30\x31\x32\x33\x34\x35\x36\x37\x38\x39\x3A\x3B\x3C\x3D\x3E\x3F\x40\x41\x42\x43\x44\x45\x46\x47\x48\x49\x4A\x4B\x4C\x4D\x4E\x4F\x50\x51\x52\x53\x54\x55\x56\x57\x58\x59\x5A\x5B\x5C\x5D\x5E\x5F\x60\x61\x62\x63\x64\x65\x66\x67\x68\x69\x6A\x6B\x6C\x6D\x6E\x6F\x70\x71\x72\x73\x74\x75\x76\x77\x78\x79\x7A\x7B\x7C\x7D\x7E\x7F\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8A\x8B\x8C\x8D\x8E\x8F\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9A\x9B\x9C\x9D\x9E\x9F\xA0\xA1\xA2\xA3\xA4\xA5\xA6\xA7\xA8\xA9\xAA\xAB\xAC\xAD\xAE\xAF\xB0\xB1\xB2\xB3\xB4\xB5\xB6\xB7\xB8\xB9\xBA\xBB\xBC\xBD\xBE\xBF\xC0\xC1\xC2\xC3\xC4\xC5\xC6\xC7\xC8\xC9\xCA\xCB\xCC\xCD\xCE\xCF\xD0\xD1\xD2\xD3\xD4\xD5\xD6\xD7\xD8\xD9\xDA\xDB\xDC\xDD\xDE\xDF\xE0\xE1\xE2\xE3\xE4\xE5\xE6\xE7\xE8\xE9\xEA\xEB\xEC\xED\xEE\xEF\xF0\xF1\xF2\xF3\xF4\xF5\xF6\xF7\xF8\xF9\xFA\xFB\xFC\xFD\xFE\xFF\x00"); QTest::newRow("arabic") << QByteArray("ISO-8859-6") << QByteArray("\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0A\x0B\x0C\x0D\x0E\x0F\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1A\x1B\x1C\x1D\x1E\x1F\x20\x21\x22\x23\x24\x25\x26\x27\x28\x29\x2A\x2B\x2C\x2D\x2E\x2F\x30\x31\x32\x33\x34\x35\x36\x37\x38\x39\x3A\x3B\x3C\x3D\x3E\x3F\x40\x41\x42\x43\x44\x45\x46\x47\x48\x49\x4A\x4B\x4C\x4D\x4E\x4F\x50\x51\x52\x53\x54\x55\x56\x57\x58\x59\x5A\x5B\x5C\x5D\x5E\x5F\x60\x61\x62\x63\x64\x65\x66\x67\x68\x69\x6A\x6B\x6C\x6D\x6E\x6F\x70\x71\x72\x73\x74\x75\x76\x77\x78\x79\x7A\x7B\x7C\x7D\x7E\x7F\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8A\x8B\x8C\x8D\x8E\x8F\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9A\x9B\x9C\x9D\x9E\x9F\xA0\xA4\xAC\xAD\xBB\xBF\xC1\xC2\xC3\xC4\xC5\xC6\xC7\xC8\xC9\xCA\xCB\xCC\xCD\xCE\xCF\xD0\xD1\xD2\xD3\xD4\xD5\xD6\xD7\xD8\xD9\xDA\xE0\xE1\xE2\xE3\xE4\xE5\xE6\xE7\xE8\xE9\xEA\xEB\xEC\xED\xEE\xEF\xF0\xF1\xF2"); QTest::newRow("greek") << QByteArray("ISO-8859-7") << QByteArray("\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0A\x0B\x0C\x0D\x0E\x0F\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1A\x1B\x1C\x1D\x1E\x1F\x20\x21\x22\x23\x24\x25\x26\x27\x28\x29\x2A\x2B\x2C\x2D\x2E\x2F\x30\x31\x32\x33\x34\x35\x36\x37\x38\x39\x3A\x3B\x3C\x3D\x3E\x3F\x40\x41\x42\x43\x44\x45\x46\x47\x48\x49\x4A\x4B\x4C\x4D\x4E\x4F\x50\x51\x52\x53\x54\x55\x56\x57\x58\x59\x5A\x5B\x5C\x5D\x5E\x5F\x60\x61\x62\x63\x64\x65\x66\x67\x68\x69\x6A\x6B\x6C\x6D\x6E\x6F\x70\x71\x72\x73\x74\x75\x76\x77\x78\x79\x7A\x7B\x7C\x7D\x7E\x7F\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8A\x8B\x8C\x8D\x8E\x8F\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9A\x9B\x9C\x9D\x9E\x9F\xA0\xA1\xA2\xA3\xA6\xA7\xA8\xA9\xAB\xAC\xAD\xAF\xB0\xB1\xB2\xB3\xB4\xB5\xB6\xB7\xB8\xB9\xBA\xBB\xBC\xBD\xBE\xBF\xC0\xC1\xC2\xC3\xC4\xC5\xC6\xC7\xC8\xC9\xCA\xCB\xCC\xCD\xCE\xCF\xD0\xD1\xD3\xD4\xD5\xD6\xD7\xD8\xD9\xDA\xDB\xDC\xDD\xDE\xDF\xE0\xE1\xE2\xE3\xE4\xE5\xE6\xE7\xE8\xE9\xEA\xEB\xEC\xED\xEE\xEF\xF0\xF1\xF2\xF3\xF4\xF5\xF6\xF7\xF8\xF9\xFA\xFB\xFC\xFD\xFE"); QTest::newRow("turkish") << QByteArray("ISO-8859-9") << QByteArray("\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0A\x0B\x0C\x0D\x0E\x0F\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1A\x1B\x1C\x1D\x1E\x1F\x20\x21\x22\x23\x24\x25\x26\x27\x28\x29\x2A\x2B\x2C\x2D\x2E\x2F\x30\x31\x32\x33\x34\x35\x36\x37\x38\x39\x3A\x3B\x3C\x3D\x3E\x3F\x40\x41\x42\x43\x44\x45\x46\x47\x48\x49\x4A\x4B\x4C\x4D\x4E\x4F\x50\x51\x52\x53\x54\x55\x56\x57\x58\x59\x5A\x5B\x5C\x5D\x5E\x5F\x60\x61\x62\x63\x64\x65\x66\x67\x68\x69\x6A\x6B\x6C\x6D\x6E\x6F\x70\x71\x72\x73\x74\x75\x76\x77\x78\x79\x7A\x7B\x7C\x7D\x7E\x7F\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8A\x8B\x8C\x8D\x8E\x8F\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9A\x9B\x9C\x9D\x9E\x9F\xA0\xA1\xA2\xA3\xA4\xA5\xA6\xA7\xA8\xA9\xAA\xAB\xAC\xAD\xAE\xAF\xB0\xB1\xB2\xB3\xB4\xB5\xB6\xB7\xB8\xB9\xBA\xBB\xBC\xBD\xBE\xBF\xC0\xC1\xC2\xC3\xC4\xC5\xC6\xC7\xC8\xC9\xCA\xCB\xCC\xCD\xCE\xCF\xD0\xD1\xD2\xD3\xD4\xD5\xD6\xD7\xD8\xD9\xDA\xDB\xDC\xDD\xDE\xDF\xE0\xE1\xE2\xE3\xE4\xE5\xE6\xE7\xE8\xE9\xEA\xEB\xEC\xED\xEE\xEF\xF0\xF1\xF2\xF3\xF4\xF5\xF6\xF7\xF8\xF9\xFA\xFB\xFC\xFD\xFE\xFF"); QTest::newRow("latin1") << QByteArray("ISO-8859-1") << QByteArray("\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0A\x0B\x0C\x0D\x0E\x0F\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1A\x1B\x1C\x1D\x1E\x1F\x20\x21\x22\x23\x24\x25\x26\x27\x28\x29\x2A\x2B\x2C\x2D\x2E\x2F\x30\x31\x32\x33\x34\x35\x36\x37\x38\x39\x3A\x3B\x3C\x3D\x3E\x3F\x40\x41\x42\x43\x44\x45\x46\x47\x48\x49\x4A\x4B\x4C\x4D\x4E\x4F\x50\x51\x52\x53\x54\x55\x56\x57\x58\x59\x5A\x5B\x5C\x5D\x5E\x5F\x60\x61\x62\x63\x64\x65\x66\x67\x68\x69\x6A\x6B\x6C\x6D\x6E\x6F\x70\x71\x72\x73\x74\x75\x76\x77\x78\x79\x7A\x7B\x7C\x7D\x7E\x7F\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8A\x8B\x8C\x8D\x8E\x8F\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9A\x9B\x9C\x9D\x9E\x9F\xA0\xA1\xA2\xA3\xA4\xA5\xA6\xA7\xA8\xA9\xAA\xAB\xAC\xAD\xAE\xAF\xB0\xB1\xB2\xB3\xB4\xB5\xB6\xB7\xB8\xB9\xBA\xBB\xBC\xBD\xBE\xBF\xC0\xC1\xC2\xC3\xC4\xC5\xC6\xC7\xC8\xC9\xCA\xCB\xCC\xCD\xCE\xCF\xD0\xD1\xD2\xD3\xD4\xD5\xD6\xD7\xD8\xD9\xDA\xDB\xDC\xDD\xDE\xDF\xE0\xE1\xE2\xE3\xE4\xE5\xE6\xE7\xE8\xE9\xEA\xEB\xEC\xED\xEE\xEF\xF0\xF1\xF2\xF3\xF4\xF5\xF6\xF7\xF8\xF9\xFA\xFB\xFC\xFD\xFE\xFF"); QByteArray sms7bit_ba; for (int i=1; i <= 0x7f; ++i) { if (i!='\x1b') { sms7bit_ba.append(i); } } QTest::newRow("latin2") << QByteArray("ISO-8859-2") << QByteArray("\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0A\x0B\x0C\x0D\x0E\x0F\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1A\x1B\x1C\x1D\x1E\x1F\x20\x21\x22\x23\x24\x25\x26\x27\x28\x29\x2A\x2B\x2C\x2D\x2E\x2F\x30\x31\x32\x33\x34\x35\x36\x37\x38\x39\x3A\x3B\x3C\x3D\x3E\x3F\x40\x41\x42\x43\x44\x45\x46\x47\x48\x49\x4A\x4B\x4C\x4D\x4E\x4F\x50\x51\x52\x53\x54\x55\x56\x57\x58\x59\x5A\x5B\x5C\x5D\x5E\x5F\x60\x61\x62\x63\x64\x65\x66\x67\x68\x69\x6A\x6B\x6C\x6D\x6E\x6F\x70\x71\x72\x73\x74\x75\x76\x77\x78\x79\x7A\x7B\x7C\x7D\x7E\x7F\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8A\x8B\x8C\x8D\x8E\x8F\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9A\x9B\x9C\x9D\x9E\x9F\xA0\xA1\xA2\xA3\xA4\xA5\xA6\xA7\xA8\xA9\xAA\xAB\xAC\xAD\xAE\xAF\xB0\xB1\xB2\xB3\xB4\xB5\xB6\xB7\xB8\xB9\xBA\xBB\xBC\xBD\xBE\xBF\xC0\xC1\xC2\xC3\xC4\xC5\xC6\xC7\xC8\xC9\xCA\xCB\xCC\xCD\xCE\xCF\xD0\xD1\xD2\xD3\xD4\xD5\xD6\xD7\xD8\xD9\xDA\xDB\xDC\xDD\xDE\xDF\xE0\xE1\xE2\xE3\xE4\xE5\xE6\xE7\xE8\xE9\xEA\xEB\xEC\xED\xEE\xEF\xF0\xF1\xF2\xF3\xF4\xF5\xF6\xF7\xF8\xF9\xFA\xFB\xFC\xFD\xFE\xFF"); QTest::newRow("latin3") << QByteArray("ISO-8859-3") << QByteArray("\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0A\x0B\x0C\x0D\x0E\x0F\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1A\x1B\x1C\x1D\x1E\x1F\x20\x21\x22\x23\x24\x25\x26\x27\x28\x29\x2A\x2B\x2C\x2D\x2E\x2F\x30\x31\x32\x33\x34\x35\x36\x37\x38\x39\x3A\x3B\x3C\x3D\x3E\x3F\x40\x41\x42\x43\x44\x45\x46\x47\x48\x49\x4A\x4B\x4C\x4D\x4E\x4F\x50\x51\x52\x53\x54\x55\x56\x57\x58\x59\x5A\x5B\x5C\x5D\x5E\x5F\x60\x61\x62\x63\x64\x65\x66\x67\x68\x69\x6A\x6B\x6C\x6D\x6E\x6F\x70\x71\x72\x73\x74\x75\x76\x77\x78\x79\x7A\x7B\x7C\x7D\x7E\x7F\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8A\x8B\x8C\x8D\x8E\x8F\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9A\x9B\x9C\x9D\x9E\x9F\xA0\xA1\xA2\xA3\xA4\xA6\xA7\xA8\xA9\xAA\xAB\xAC\xAD\xAF\xB0\xB1\xB2\xB3\xB4\xB5\xB6\xB7\xB8\xB9\xBA\xBB\xBC\xBD\xBF\xC0\xC1\xC2\xC4\xC5\xC6\xC7\xC8\xC9\xCA\xCB\xCC\xCD\xCE\xCF\xD1\xD2\xD3\xD4\xD5\xD6\xD7\xD8\xD9\xDA\xDB\xDC\xDD\xDE\xDF\xE0\xE1\xE2\xE4\xE5\xE6\xE7\xE8\xE9\xEA\xEB\xEC\xED\xEE\xEF\xF1\xF2\xF3\xF4\xF5\xF6\xF7\xF8\xF9\xFA\xFB\xFC\xFD\xFE\xFF"); QTest::newRow("latin4") << QByteArray("ISO-8859-4") << QByteArray("\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0A\x0B\x0C\x0D\x0E\x0F\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1A\x1B\x1C\x1D\x1E\x1F\x20\x21\x22\x23\x24\x25\x26\x27\x28\x29\x2A\x2B\x2C\x2D\x2E\x2F\x30\x31\x32\x33\x34\x35\x36\x37\x38\x39\x3A\x3B\x3C\x3D\x3E\x3F\x40\x41\x42\x43\x44\x45\x46\x47\x48\x49\x4A\x4B\x4C\x4D\x4E\x4F\x50\x51\x52\x53\x54\x55\x56\x57\x58\x59\x5A\x5B\x5C\x5D\x5E\x5F\x60\x61\x62\x63\x64\x65\x66\x67\x68\x69\x6A\x6B\x6C\x6D\x6E\x6F\x70\x71\x72\x73\x74\x75\x76\x77\x78\x79\x7A\x7B\x7C\x7D\x7E\x7F\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8A\x8B\x8C\x8D\x8E\x8F\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9A\x9B\x9C\x9D\x9E\x9F\xA0\xA1\xA2\xA3\xA4\xA5\xA6\xA7\xA8\xA9\xAA\xAB\xAC\xAD\xAE\xAF\xB0\xB1\xB2\xB3\xB4\xB5\xB6\xB7\xB8\xB9\xBA\xBB\xBC\xBD\xBE\xBF\xC0\xC1\xC2\xC3\xC4\xC5\xC6\xC7\xC8\xC9\xCA\xCB\xCC\xCD\xCE\xCF\xD0\xD1\xD2\xD3\xD4\xD5\xD6\xD7\xD8\xD9\xDA\xDB\xDC\xDD\xDE\xDF\xE0\xE1\xE2\xE3\xE4\xE5\xE6\xE7\xE8\xE9\xEA\xEB\xEC\xED\xEE\xEF\xF0\xF1\xF2\xF3\xF4\xF5\xF6\xF7\xF8\xF9\xFA\xFB\xFC\xFD\xFE\xFF"); QTest::newRow("russian 2") << QByteArray("ISO-8859-5") << QByteArray("\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0A\x0B\x0C\x0D\x0E\x0F\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1A\x1B\x1C\x1D\x1E\x1F\x20\x21\x22\x23\x24\x25\x26\x27\x28\x29\x2A\x2B\x2C\x2D\x2E\x2F\x30\x31\x32\x33\x34\x35\x36\x37\x38\x39\x3A\x3B\x3C\x3D\x3E\x3F\x40\x41\x42\x43\x44\x45\x46\x47\x48\x49\x4A\x4B\x4C\x4D\x4E\x4F\x50\x51\x52\x53\x54\x55\x56\x57\x58\x59\x5A\x5B\x5C\x5D\x5E\x5F\x60\x61\x62\x63\x64\x65\x66\x67\x68\x69\x6A\x6B\x6C\x6D\x6E\x6F\x70\x71\x72\x73\x74\x75\x76\x77\x78\x79\x7A\x7B\x7C\x7D\x7E\x7F\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8A\x8B\x8C\x8D\x8E\x8F\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9A\x9B\x9C\x9D\x9E\x9F\xA0\xA1\xA2\xA3\xA4\xA5\xA6\xA7\xA8\xA9\xAA\xAB\xAC\xAD\xAE\xAF\xB0\xB1\xB2\xB3\xB4\xB5\xB6\xB7\xB8\xB9\xBA\xBB\xBC\xBD\xBE\xBF\xC0\xC1\xC2\xC3\xC4\xC5\xC6\xC7\xC8\xC9\xCA\xCB\xCC\xCD\xCE\xCF\xD0\xD1\xD2\xD3\xD4\xD5\xD6\xD7\xD8\xD9\xDA\xDB\xDC\xDD\xDE\xDF\xE0\xE1\xE2\xE3\xE4\xE5\xE6\xE7\xE8\xE9\xEA\xEB\xEC\xED\xEE\xEF\xF0\xF1\xF2\xF3\xF4\xF5\xF6\xF7\xF8\xF9\xFA\xFB\xFC\xFD\xFE\xFF"); QTest::newRow("arabic 2") << QByteArray("ISO-8859-6") << QByteArray("\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0A\x0B\x0C\x0D\x0E\x0F\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1A\x1B\x1C\x1D\x1E\x1F\x20\x21\x22\x23\x24\x25\x26\x27\x28\x29\x2A\x2B\x2C\x2D\x2E\x2F\x30\x31\x32\x33\x34\x35\x36\x37\x38\x39\x3A\x3B\x3C\x3D\x3E\x3F\x40\x41\x42\x43\x44\x45\x46\x47\x48\x49\x4A\x4B\x4C\x4D\x4E\x4F\x50\x51\x52\x53\x54\x55\x56\x57\x58\x59\x5A\x5B\x5C\x5D\x5E\x5F\x60\x61\x62\x63\x64\x65\x66\x67\x68\x69\x6A\x6B\x6C\x6D\x6E\x6F\x70\x71\x72\x73\x74\x75\x76\x77\x78\x79\x7A\x7B\x7C\x7D\x7E\x7F\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8A\x8B\x8C\x8D\x8E\x8F\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9A\x9B\x9C\x9D\x9E\x9F\xA0\xA4\xAC\xAD\xBB\xBF\xC1\xC2\xC3\xC4\xC5\xC6\xC7\xC8\xC9\xCA\xCB\xCC\xCD\xCE\xCF\xD0\xD1\xD2\xD3\xD4\xD5\xD6\xD7\xD8\xD9\xDA\xE0\xE1\xE2\xE3\xE4\xE5\xE6\xE7\xE8\xE9\xEA\xEB\xEC\xED\xEE\xEF\xF0\xF1\xF2"); QTest::newRow("greek 2") << QByteArray("ISO-8859-7") << QByteArray("\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0A\x0B\x0C\x0D\x0E\x0F\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1A\x1B\x1C\x1D\x1E\x1F\x20\x21\x22\x23\x24\x25\x26\x27\x28\x29\x2A\x2B\x2C\x2D\x2E\x2F\x30\x31\x32\x33\x34\x35\x36\x37\x38\x39\x3A\x3B\x3C\x3D\x3E\x3F\x40\x41\x42\x43\x44\x45\x46\x47\x48\x49\x4A\x4B\x4C\x4D\x4E\x4F\x50\x51\x52\x53\x54\x55\x56\x57\x58\x59\x5A\x5B\x5C\x5D\x5E\x5F\x60\x61\x62\x63\x64\x65\x66\x67\x68\x69\x6A\x6B\x6C\x6D\x6E\x6F\x70\x71\x72\x73\x74\x75\x76\x77\x78\x79\x7A\x7B\x7C\x7D\x7E\x7F\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8A\x8B\x8C\x8D\x8E\x8F\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9A\x9B\x9C\x9D\x9E\x9F\xA0\xA1\xA2\xA3\xA6\xA7\xA8\xA9\xAB\xAC\xAD\xAF\xB0\xB1\xB2\xB3\xB4\xB5\xB6\xB7\xB8\xB9\xBA\xBB\xBC\xBD\xBE\xBF\xC0\xC1\xC2\xC3\xC4\xC5\xC6\xC7\xC8\xC9\xCA\xCB\xCC\xCD\xCE\xCF\xD0\xD1\xD3\xD4\xD5\xD6\xD7\xD8\xD9\xDA\xDB\xDC\xDD\xDE\xDF\xE0\xE1\xE2\xE3\xE4\xE5\xE6\xE7\xE8\xE9\xEA\xEB\xEC\xED\xEE\xEF\xF0\xF1\xF2\xF3\xF4\xF5\xF6\xF7\xF8\xF9\xFA\xFB\xFC\xFD\xFE"); QTest::newRow("latin5") << QByteArray("ISO-8859-9") << QByteArray("\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0A\x0B\x0C\x0D\x0E\x0F\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1A\x1B\x1C\x1D\x1E\x1F\x20\x21\x22\x23\x24\x25\x26\x27\x28\x29\x2A\x2B\x2C\x2D\x2E\x2F\x30\x31\x32\x33\x34\x35\x36\x37\x38\x39\x3A\x3B\x3C\x3D\x3E\x3F\x40\x41\x42\x43\x44\x45\x46\x47\x48\x49\x4A\x4B\x4C\x4D\x4E\x4F\x50\x51\x52\x53\x54\x55\x56\x57\x58\x59\x5A\x5B\x5C\x5D\x5E\x5F\x60\x61\x62\x63\x64\x65\x66\x67\x68\x69\x6A\x6B\x6C\x6D\x6E\x6F\x70\x71\x72\x73\x74\x75\x76\x77\x78\x79\x7A\x7B\x7C\x7D\x7E\x7F\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8A\x8B\x8C\x8D\x8E\x8F\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9A\x9B\x9C\x9D\x9E\x9F\xA0\xA1\xA2\xA3\xA4\xA5\xA6\xA7\xA8\xA9\xAA\xAB\xAC\xAD\xAE\xAF\xB0\xB1\xB2\xB3\xB4\xB5\xB6\xB7\xB8\xB9\xBA\xBB\xBC\xBD\xBE\xBF\xC0\xC1\xC2\xC3\xC4\xC5\xC6\xC7\xC8\xC9\xCA\xCB\xCC\xCD\xCE\xCF\xD0\xD1\xD2\xD3\xD4\xD5\xD6\xD7\xD8\xD9\xDA\xDB\xDC\xDD\xDE\xDF\xE0\xE1\xE2\xE3\xE4\xE5\xE6\xE7\xE8\xE9\xEA\xEB\xEC\xED\xEE\xEF\xF0\xF1\xF2\xF3\xF4\xF5\xF6\xF7\xF8\xF9\xFA\xFB\xFC\xFD\xFE\xFF"); QTest::newRow("latin6") << QByteArray("ISO-8859-10") << QByteArray("\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0A\x0B\x0C\x0D\x0E\x0F\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1A\x1B\x1C\x1D\x1E\x1F\x20\x21\x22\x23\x24\x25\x26\x27\x28\x29\x2A\x2B\x2C\x2D\x2E\x2F\x30\x31\x32\x33\x34\x35\x36\x37\x38\x39\x3A\x3B\x3C\x3D\x3E\x3F\x40\x41\x42\x43\x44\x45\x46\x47\x48\x49\x4A\x4B\x4C\x4D\x4E\x4F\x50\x51\x52\x53\x54\x55\x56\x57\x58\x59\x5A\x5B\x5C\x5D\x5E\x5F\x60\x61\x62\x63\x64\x65\x66\x67\x68\x69\x6A\x6B\x6C\x6D\x6E\x6F\x70\x71\x72\x73\x74\x75\x76\x77\x78\x79\x7A\x7B\x7C\x7D\x7E\x7F\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8A\x8B\x8C\x8D\x8E\x8F\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9A\x9B\x9C\x9D\x9E\x9F\xA0\xA1\xA2\xA3\xA4\xA5\xA6\xA7\xA8\xA9\xAA\xAB\xAC\xAD\xAE\xAF\xB0\xB1\xB2\xB3\xB4\xB5\xB6\xB7\xB8\xB9\xBA\xBB\xBC\xBD\xBE\xBF\xC0\xC1\xC2\xC3\xC4\xC5\xC6\xC7\xC8\xC9\xCA\xCB\xCC\xCD\xCE\xCF\xD0\xD1\xD2\xD3\xD4\xD5\xD6\xD7\xD8\xD9\xDA\xDB\xDC\xDD\xDE\xDF\xE0\xE1\xE2\xE3\xE4\xE5\xE6\xE7\xE8\xE9\xEA\xEB\xEC\xED\xEE\xEF\xF0\xF1\xF2\xF3\xF4\xF5\xF6\xF7\xF8\xF9\xFA\xFB\xFC\xFD\xFE\xFF"); #if 0 QByteArray iso8859_11_ba; for (int x=0x20; x<=0x7f; ++x) { iso8859_11_ba.append(x); } for (int x=0xa0; x<0xff; ++x) { if ((x>=0xdb && x<0xdf) || x>0xfb){ continue; } iso8859_11_ba.append(x); } QTest::newRow("latin-thai") << QByteArray("ISO-8859-11") << iso8859_11_ba; #endif QTest::newRow("latin7") << QByteArray("ISO-8859-13") << QByteArray("\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0A\x0B\x0C\x0D\x0E\x0F\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1A\x1B\x1C\x1D\x1E\x1F\x20\x21\x22\x23\x24\x25\x26\x27\x28\x29\x2A\x2B\x2C\x2D\x2E\x2F\x30\x31\x32\x33\x34\x35\x36\x37\x38\x39\x3A\x3B\x3C\x3D\x3E\x3F\x40\x41\x42\x43\x44\x45\x46\x47\x48\x49\x4A\x4B\x4C\x4D\x4E\x4F\x50\x51\x52\x53\x54\x55\x56\x57\x58\x59\x5A\x5B\x5C\x5D\x5E\x5F\x60\x61\x62\x63\x64\x65\x66\x67\x68\x69\x6A\x6B\x6C\x6D\x6E\x6F\x70\x71\x72\x73\x74\x75\x76\x77\x78\x79\x7A\x7B\x7C\x7D\x7E\x7F\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8A\x8B\x8C\x8D\x8E\x8F\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9A\x9B\x9C\x9D\x9E\x9F\xA0\xA1\xA2\xA3\xA4\xA5\xA6\xA7\xA8\xA9\xAA\xAB\xAC\xAD\xAE\xAF\xB0\xB1\xB2\xB3\xB4\xB5\xB6\xB7\xB8\xB9\xBA\xBB\xBC\xBD\xBE\xBF\xC0\xC1\xC2\xC3\xC4\xC5\xC6\xC7\xC8\xC9\xCA\xCB\xCC\xCD\xCE\xCF\xD0\xD1\xD2\xD3\xD4\xD5\xD6\xD7\xD8\xD9\xDA\xDB\xDC\xDD\xDE\xDF\xE0\xE1\xE2\xE3\xE4\xE5\xE6\xE7\xE8\xE9\xEA\xEB\xEC\xED\xEE\xEF\xF0\xF1\xF2\xF3\xF4\xF5\xF6\xF7\xF8\xF9\xFA\xFB\xFC\xFD\xFE\xFF"); QTest::newRow("celtic") << QByteArray("ISO-8859-14") << QByteArray("\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0A\x0B\x0C\x0D\x0E\x0F\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1A\x1B\x1C\x1D\x1E\x1F\x20\x21\x22\x23\x24\x25\x26\x27\x28\x29\x2A\x2B\x2C\x2D\x2E\x2F\x30\x31\x32\x33\x34\x35\x36\x37\x38\x39\x3A\x3B\x3C\x3D\x3E\x3F\x40\x41\x42\x43\x44\x45\x46\x47\x48\x49\x4A\x4B\x4C\x4D\x4E\x4F\x50\x51\x52\x53\x54\x55\x56\x57\x58\x59\x5A\x5B\x5C\x5D\x5E\x5F\x60\x61\x62\x63\x64\x65\x66\x67\x68\x69\x6A\x6B\x6C\x6D\x6E\x6F\x70\x71\x72\x73\x74\x75\x76\x77\x78\x79\x7A\x7B\x7C\x7D\x7E\x7F\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8A\x8B\x8C\x8D\x8E\x8F\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9A\x9B\x9C\x9D\x9E\x9F\xA0\xA1\xA2\xA3\xA4\xA5\xA6\xA7\xA8\xA9\xAA\xAB\xAC\xAD\xAE\xAF\xB0\xB1\xB2\xB3\xB4\xB5\xB6\xB7\xB8\xB9\xBA\xBB\xBC\xBD\xBE\xBF\xC0\xC1\xC2\xC3\xC4\xC5\xC6\xC7\xC8\xC9\xCA\xCB\xCC\xCD\xCE\xCF\xD0\xD1\xD2\xD3\xD4\xD5\xD6\xD7\xD8\xD9\xDA\xDB\xDC\xDD\xDE\xDF\xE0\xE1\xE2\xE3\xE4\xE5\xE6\xE7\xE8\xE9\xEA\xEB\xEC\xED\xEE\xEF\xF0\xF1\xF2\xF3\xF4\xF5\xF6\xF7\xF8\xF9\xFA\xFB\xFC\xFD\xFE\xFF"); QTest::newRow("latin9") << QByteArray("ISO-8859-15") << QByteArray("\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0A\x0B\x0C\x0D\x0E\x0F\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1A\x1B\x1C\x1D\x1E\x1F\x20\x21\x22\x23\x24\x25\x26\x27\x28\x29\x2A\x2B\x2C\x2D\x2E\x2F\x30\x31\x32\x33\x34\x35\x36\x37\x38\x39\x3A\x3B\x3C\x3D\x3E\x3F\x40\x41\x42\x43\x44\x45\x46\x47\x48\x49\x4A\x4B\x4C\x4D\x4E\x4F\x50\x51\x52\x53\x54\x55\x56\x57\x58\x59\x5A\x5B\x5C\x5D\x5E\x5F\x60\x61\x62\x63\x64\x65\x66\x67\x68\x69\x6A\x6B\x6C\x6D\x6E\x6F\x70\x71\x72\x73\x74\x75\x76\x77\x78\x79\x7A\x7B\x7C\x7D\x7E\x7F\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8A\x8B\x8C\x8D\x8E\x8F\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9A\x9B\x9C\x9D\x9E\x9F\xA0\xA1\xA2\xA3\xA4\xA5\xA6\xA7\xA8\xA9\xAA\xAB\xAC\xAD\xAE\xAF\xB0\xB1\xB2\xB3\xB4\xB5\xB6\xB7\xB8\xB9\xBA\xBB\xBC\xBD\xBE\xBF\xC0\xC1\xC2\xC3\xC4\xC5\xC6\xC7\xC8\xC9\xCA\xCB\xCC\xCD\xCE\xCF\xD0\xD1\xD2\xD3\xD4\xD5\xD6\xD7\xD8\xD9\xDA\xDB\xDC\xDD\xDE\xDF\xE0\xE1\xE2\xE3\xE4\xE5\xE6\xE7\xE8\xE9\xEA\xEB\xEC\xED\xEE\xEF\xF0\xF1\xF2\xF3\xF4\xF5\xF6\xF7\xF8\xF9\xFA\xFB\xFC\xFD\xFE\xFF"); // QTest::newRow("latin10") << QByteArray("ISO-8859-16") // << QByteArray("\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0A\x0B\x0C\x0D\x0E\x0F\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1A\x1B\x1C\x1D\x1E\x1F\x20\x21\x22\x23\x24\x25\x26\x27\x28\x29\x2A\x2B\x2C\x2D\x2E\x2F\x30\x31\x32\x33\x34\x35\x36\x37\x38\x39\x3A\x3B\x3C\x3D\x3E\x3F\x40\x41\x42\x43\x44\x45\x46\x47\x48\x49\x4A\x4B\x4C\x4D\x4E\x4F\x50\x51\x52\x53\x54\x55\x56\x57\x58\x59\x5A\x5B\x5C\x5D\x5E\x5F\x60\x61\x62\x63\x64\x65\x66\x67\x68\x69\x6A\x6B\x6C\x6D\x6E\x6F\x70\x71\x72\x73\x74\x75\x76\x77\x78\x79\x7A\x7B\x7C\x7D\x7E\x7F\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8A\x8B\x8C\x8D\x8E\x8F\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9A\x9B\x9C\x9D\x9E\x9F\xA0\xA1\xA2\xA3\xA4\xA5\xA6\xA7\xA8\xA9\xAA\xAB\xAC\xAD\xAE\xAF\xB0\xB1\xB2\xB3\xB4\xB5\xB6\xB7\xB8\xB9\xBA\xBB\xBC\xBD\xBE\xBF\xC0\xC1\xC2\xC3\xC4\xC5\xC6\xC7\xC8\xC9\xCA\xCB\xCC\xCD\xCE\xCF\xD0\xD1\xD2\xD3\xD4\xD5\xD6\xD7\xD8\xD9\xDA\xDB\xDC\xDD\xDE\xDF\xE0\xE1\xE2\xE3\xE4\xE5\xE6\xE7\xE8\xE9\xEA\xEB\xEC\xED\xEE\xEF\xF0\xF1\xF2\xF3\xF4\xF5\xF6\xF7\xF8\xF9\xFA\xFB\xFC\xFD\xFE\xFF"); QTest::newRow("cp850") << QByteArray("CP850") << QByteArray("\x20\x21\x22\x23\x24\x25\x26\x27\x28\x29\x2a\x2b\x2c\x2d\x2e\x2f\x30\x31\x32\x33\x34\x35\x36\x37\x38\x39\x3a\x3b\x3c\x3d\x3e\x3f\x40\x41\x42\x43\x44\x45\x46\x47\x48\x49\x4a\x4b\x4c\x4d\x4e\x4f\x50\x51\x52\x53\x54\x55\x56\x57\x58\x59\x5a\x5b\x5c\x5d\x5e\x5f\x60\x61\x62\x63\x64\x65\x66\x67\x68\x69\x6a\x6b\x6c\x6d\x6e\x6f\x70\x71\x72\x73\x74\x75\x76\x77\x78\x79\x7a\x7b\x7c\x7d\x7e\x7f\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8a\x8b\x8c\x8d\x8e\x8f\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9a\x9b\x9c\x9d\x9e\x9f\xa0\xa1\xa2\xa3\xa4\xa5\xa6\xa7\xa8\xa9\xaa\xab\xac\xad\xae\xaf\xb0\xb1\xb2\xb3\xb4\xb5\xb6\xb7\xb8\xb9\xba\xbb\xbc\xbd\xbe\xbf\xc0\xc1\xc2\xc3\xc4\xc5\xc6\xc7\xc8\xc9\xca\xcb\xcc\xcd\xce\xcf\xd0\xd1\xd2\xd3\xd4\xd5\xd6\xd7\xd8\xd9\xda\xdb\xdc\xdd\xde\xdf\xe0\xe1\xe2\xe3\xe4\xe5\xe6\xe7\xe8\xe9\xea\xeb\xec\xed\xee\xef\xf0\xf1\xf2\xf3\xf4\xf5\xf6\xf7\xf8\xf9\xfa\xfb\xfc\xfd\xfe\xff"); QTest::newRow("cp874") << QByteArray("CP874") << QByteArray("\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0A\x0B\x0C\x0D\x0E\x0F\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1A\x1B\x1C\x1D\x1E\x1F\x20\x21\x22\x23\x24\x25\x26\x27\x28\x29\x2A\x2B\x2C\x2D\x2E\x2F\x30\x31\x32\x33\x34\x35\x36\x37\x38\x39\x3A\x3B\x3C\x3D\x3E\x3F\x40\x41\x42\x43\x44\x45\x46\x47\x48\x49\x4A\x4B\x4C\x4D\x4E\x4F\x50\x51\x52\x53\x54\x55\x56\x57\x58\x59\x5A\x5B\x5C\x5D\x5E\x5F\x60\x61\x62\x63\x64\x65\x66\x67\x68\x69\x6A\x6B\x6C\x6D\x6E\x6F\x70\x71\x72\x73\x74\x75\x76\x77\x78\x79\x7A\x7B\x7C\x7D\x7E\x7F\x80\x85\x91\x92\x93\x94\x95\x96\x97\xA0\xA1\xA2\xA3\xA4\xA5\xA6\xA7\xA8\xA9\xAA\xAB\xAC\xAD\xAE\xAF\xB0\xB1\xB2\xB3\xB4\xB5\xB6\xB7\xB8\xB9\xBA\xBB\xBC\xBD\xBE\xBF\xC0\xC1\xC2\xC3\xC4\xC5\xC6\xC7\xC8\xC9\xCA\xCB\xCC\xCD\xCE\xCF\xD0\xD1\xD2\xD3\xD4\xD5\xD6\xD7\xD8\xD9\xDA\xDF\xE0\xE1\xE2\xE3\xE4\xE5\xE6\xE7\xE8\xE9\xEA\xEB\xEC\xED\xEE\xEF\xF0\xF1\xF2\xF3\xF4\xF5\xF6\xF7\xF8\xF9\xFA\xFB"); QTest::newRow("cp1250") << QByteArray("CP1250") << QByteArray("\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0A\x0B\x0C\x0D\x0E\x0F\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1A\x1B\x1C\x1D\x1E\x1F\x20\x21\x22\x23\x24\x25\x26\x27\x28\x29\x2A\x2B\x2C\x2D\x2E\x2F\x30\x31\x32\x33\x34\x35\x36\x37\x38\x39\x3A\x3B\x3C\x3D\x3E\x3F\x40\x41\x42\x43\x44\x45\x46\x47\x48\x49\x4A\x4B\x4C\x4D\x4E\x4F\x50\x51\x52\x53\x54\x55\x56\x57\x58\x59\x5A\x5B\x5C\x5D\x5E\x5F\x60\x61\x62\x63\x64\x65\x66\x67\x68\x69\x6A\x6B\x6C\x6D\x6E\x6F\x70\x71\x72\x73\x74\x75\x76\x77\x78\x79\x7A\x7B\x7C\x7D\x7E\x7F\x80\x82\x84\x85\x86\x87\x89\x8A\x8B\x8C\x8D\x8E\x8F\x91\x92\x93\x94\x95\x96\x97\x99\x9A\x9B\x9C\x9D\x9E\x9F\xA0\xA1\xA2\xA3\xA4\xA5\xA6\xA7\xA8\xA9\xAA\xAB\xAC\xAD\xAE\xAF\xB0\xB1\xB2\xB3\xB4\xB5\xB6\xB7\xB8\xB9\xBA\xBB\xBC\xBD\xBE\xBF\xC0\xC1\xC2\xC3\xC4\xC5\xC6\xC7\xC8\xC9\xCA\xCB\xCC\xCD\xCE\xCF\xD0\xD1\xD2\xD3\xD4\xD5\xD6\xD7\xD8\xD9\xDA\xDB\xDC\xDD\xDE\xDF\xE0\xE1\xE2\xE3\xE4\xE5\xE6\xE7\xE8\xE9\xEA\xEB\xEC\xED\xEE\xEF\xF0\xF1\xF2\xF3\xF4\xF5\xF6\xF7\xF8\xF9\xFA\xFB\xFC\xFD\xFE\xFF"); QTest::newRow("cp1251") << QByteArray("CP1251") << QByteArray("\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0A\x0B\x0C\x0D\x0E\x0F\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1A\x1B\x1C\x1D\x1E\x1F\x20\x21\x22\x23\x24\x25\x26\x27\x28\x29\x2A\x2B\x2C\x2D\x2E\x2F\x30\x31\x32\x33\x34\x35\x36\x37\x38\x39\x3A\x3B\x3C\x3D\x3E\x3F\x40\x41\x42\x43\x44\x45\x46\x47\x48\x49\x4A\x4B\x4C\x4D\x4E\x4F\x50\x51\x52\x53\x54\x55\x56\x57\x58\x59\x5A\x5B\x5C\x5D\x5E\x5F\x60\x61\x62\x63\x64\x65\x66\x67\x68\x69\x6A\x6B\x6C\x6D\x6E\x6F\x70\x71\x72\x73\x74\x75\x76\x77\x78\x79\x7A\x7B\x7C\x7D\x7E\x7F\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8A\x8B\x8C\x8D\x8E\x8F\x90\x91\x92\x93\x94\x95\x96\x97\x99\x9A\x9B\x9C\x9D\x9E\x9F\xA0\xA1\xA2\xA3\xA4\xA5\xA6\xA7\xA8\xA9\xAA\xAB\xAC\xAD\xAE\xAF\xB0\xB1\xB2\xB3\xB4\xB5\xB6\xB7\xB8\xB9\xBA\xBB\xBC\xBD\xBE\xBF\xC0\xC1\xC2\xC3\xC4\xC5\xC6\xC7\xC8\xC9\xCA\xCB\xCC\xCD\xCE\xCF\xD0\xD1\xD2\xD3\xD4\xD5\xD6\xD7\xD8\xD9\xDA\xDB\xDC\xDD\xDE\xDF\xE0\xE1\xE2\xE3\xE4\xE5\xE6\xE7\xE8\xE9\xEA\xEB\xEC\xED\xEE\xEF\xF0\xF1\xF2\xF3\xF4\xF5\xF6\xF7\xF8\xF9\xFA\xFB\xFC\xFD\xFE\xFF"); QTest::newRow("cp1252") << QByteArray("CP1252") << QByteArray("\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0A\x0B\x0C\x0D\x0E\x0F\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1A\x1B\x1C\x1D\x1E\x1F\x20\x21\x22\x23\x24\x25\x26\x27\x28\x29\x2A\x2B\x2C\x2D\x2E\x2F\x30\x31\x32\x33\x34\x35\x36\x37\x38\x39\x3A\x3B\x3C\x3D\x3E\x3F\x40\x41\x42\x43\x44\x45\x46\x47\x48\x49\x4A\x4B\x4C\x4D\x4E\x4F\x50\x51\x52\x53\x54\x55\x56\x57\x58\x59\x5A\x5B\x5C\x5D\x5E\x5F\x60\x61\x62\x63\x64\x65\x66\x67\x68\x69\x6A\x6B\x6C\x6D\x6E\x6F\x70\x71\x72\x73\x74\x75\x76\x77\x78\x79\x7A\x7B\x7C\x7D\x7E\x7F\x80\x82\x83\x84\x85\x86\x87\x88\x89\x8A\x8B\x8C\x8E\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9A\x9B\x9C\x9E\x9F\xA0\xA1\xA2\xA3\xA4\xA5\xA6\xA7\xA8\xA9\xAA\xAB\xAC\xAD\xAE\xAF\xB0\xB1\xB2\xB3\xB4\xB5\xB6\xB7\xB8\xB9\xBA\xBB\xBC\xBD\xBE\xBF\xC0\xC1\xC2\xC3\xC4\xC5\xC6\xC7\xC8\xC9\xCA\xCB\xCC\xCD\xCE\xCF\xD0\xD1\xD2\xD3\xD4\xD5\xD6\xD7\xD8\xD9\xDA\xDB\xDC\xDD\xDE\xDF\xE0\xE1\xE2\xE3\xE4\xE5\xE6\xE7\xE8\xE9\xEA\xEB\xEC\xED\xEE\xEF\xF0\xF1\xF2\xF3\xF4\xF5\xF6\xF7\xF8\xF9\xFA\xFB\xFC\xFD\xFE\xFF"); QTest::newRow("cp1253") << QByteArray("CP1253") << QByteArray("\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0A\x0B\x0C\x0D\x0E\x0F\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1A\x1B\x1C\x1D\x1E\x1F\x20\x21\x22\x23\x24\x25\x26\x27\x28\x29\x2A\x2B\x2C\x2D\x2E\x2F\x30\x31\x32\x33\x34\x35\x36\x37\x38\x39\x3A\x3B\x3C\x3D\x3E\x3F\x40\x41\x42\x43\x44\x45\x46\x47\x48\x49\x4A\x4B\x4C\x4D\x4E\x4F\x50\x51\x52\x53\x54\x55\x56\x57\x58\x59\x5A\x5B\x5C\x5D\x5E\x5F\x60\x61\x62\x63\x64\x65\x66\x67\x68\x69\x6A\x6B\x6C\x6D\x6E\x6F\x70\x71\x72\x73\x74\x75\x76\x77\x78\x79\x7A\x7B\x7C\x7D\x7E\x7F\x80\x82\x83\x84\x85\x86\x87\x89\x8B\x91\x92\x93\x94\x95\x96\x97\x99\x9B\xA0\xA1\xA2\xA3\xA4\xA5\xA6\xA7\xA8\xA9\xAB\xAC\xAD\xAE\xAF\xB0\xB1\xB2\xB3\xB4\xB5\xB6\xB7\xB8\xB9\xBA\xBB\xBC\xBD\xBE\xBF\xC0\xC1\xC2\xC3\xC4\xC5\xC6\xC7\xC8\xC9\xCA\xCB\xCC\xCD\xCE\xCF\xD0\xD1\xD3\xD4\xD5\xD6\xD7\xD8\xD9\xDA\xDB\xDC\xDD\xDE\xDF\xE0\xE1\xE2\xE3\xE4\xE5\xE6\xE7\xE8\xE9\xEA\xEB\xEC\xED\xEE\xEF\xF0\xF1\xF2\xF3\xF4\xF5\xF6\xF7\xF8\xF9\xFA\xFB\xFC\xFD\xFE"); QTest::newRow("cp1254") << QByteArray("CP1254") << QByteArray("\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0A\x0B\x0C\x0D\x0E\x0F\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1A\x1B\x1C\x1D\x1E\x1F\x20\x21\x22\x23\x24\x25\x26\x27\x28\x29\x2A\x2B\x2C\x2D\x2E\x2F\x30\x31\x32\x33\x34\x35\x36\x37\x38\x39\x3A\x3B\x3C\x3D\x3E\x3F\x40\x41\x42\x43\x44\x45\x46\x47\x48\x49\x4A\x4B\x4C\x4D\x4E\x4F\x50\x51\x52\x53\x54\x55\x56\x57\x58\x59\x5A\x5B\x5C\x5D\x5E\x5F\x60\x61\x62\x63\x64\x65\x66\x67\x68\x69\x6A\x6B\x6C\x6D\x6E\x6F\x70\x71\x72\x73\x74\x75\x76\x77\x78\x79\x7A\x7B\x7C\x7D\x7E\x7F\x80\x82\x83\x84\x85\x86\x87\x88\x89\x8A\x8B\x8C\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9A\x9B\x9C\x9F\xA0\xA1\xA2\xA3\xA4\xA5\xA6\xA7\xA8\xA9\xAA\xAB\xAC\xAD\xAE\xAF\xB0\xB1\xB2\xB3\xB4\xB5\xB6\xB7\xB8\xB9\xBA\xBB\xBC\xBD\xBE\xBF\xC0\xC1\xC2\xC3\xC4\xC5\xC6\xC7\xC8\xC9\xCA\xCB\xCC\xCD\xCE\xCF\xD0\xD1\xD2\xD3\xD4\xD5\xD6\xD7\xD8\xD9\xDA\xDB\xDC\xDD\xDE\xDF\xE0\xE1\xE2\xE3\xE4\xE5\xE6\xE7\xE8\xE9\xEA\xEB\xEC\xED\xEE\xEF\xF0\xF1\xF2\xF3\xF4\xF5\xF6\xF7\xF8\xF9\xFA\xFB\xFC\xFD\xFE\xFF"); QTest::newRow("cp1255") << QByteArray("CP1255") << QByteArray("\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0A\x0B\x0C\x0D\x0E\x0F\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1A\x1B\x1C\x1D\x1E\x1F\x20\x21\x22\x23\x24\x25\x26\x27\x28\x29\x2A\x2B\x2C\x2D\x2E\x2F\x30\x31\x32\x33\x34\x35\x36\x37\x38\x39\x3A\x3B\x3C\x3D\x3E\x3F\x40\x41\x42\x43\x44\x45\x46\x47\x48\x49\x4A\x4B\x4C\x4D\x4E\x4F\x50\x51\x52\x53\x54\x55\x56\x57\x58\x59\x5A\x5B\x5C\x5D\x5E\x5F\x60\x61\x62\x63\x64\x65\x66\x67\x68\x69\x6A\x6B\x6C\x6D\x6E\x6F\x70\x71\x72\x73\x74\x75\x76\x77\x78\x79\x7A\x7B\x7C\x7D\x7E\x7F\x80\x82\x83\x84\x85\x86\x87\x88\x89,x8B\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9B\xA0\xA1\xA2\xA3\xA4\xA5\xA6\xA7\xA8\xA9\xAA\xAB\xAC\xAD\xAE\xAF\xB0\xB1\xB2\xB3\xB4\xB5\xB6\xB7\xB8\xB9\xBA\xBB\xBC\xBD\xBE\xBF\xC0\xC1\xC2\xC3\xC4\xC5\xC6\xC7\xC8\xC9\xCB\xCC\xCD\xCE\xCF\xD0\xD1\xD2\xD3\xD4\xD5\xD6\xD7\xD8\xE0\xE1\xE2\xE3\xE4\xE5\xE6\xE7\xE8\xE9\xEA\xEB\xEC\xED\xEE\xEF\xF0\xF1\xF2\xF3\xF4\xF5\xF6\xF7\xF8\xF9\xFA\xFD\xFE"); QTest::newRow("cp1256") << QByteArray("CP1256") << QByteArray("\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0A\x0B\x0C\x0D\x0E\x0F\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1A\x1B\x1C\x1D\x1E\x1F\x20\x21\x22\x23\x24\x25\x26\x27\x28\x29\x2A\x2B\x2C\x2D\x2E\x2F\x30\x31\x32\x33\x34\x35\x36\x37\x38\x39\x3A\x3B\x3C\x3D\x3E\x3F\x40\x41\x42\x43\x44\x45\x46\x47\x48\x49\x4A\x4B\x4C\x4D\x4E\x4F\x50\x51\x52\x53\x54\x55\x56\x57\x58\x59\x5A\x5B\x5C\x5D\x5E\x5F\x60\x61\x62\x63\x64\x65\x66\x67\x68\x69\x6A\x6B\x6C\x6D\x6E\x6F\x70\x71\x72\x73\x74\x75\x76\x77\x78\x79\x7A\x7B\x7C\x7D\x7E\x7F\x80\x81\x82\x83\x84\x85\x86\x87\x88\x89\x8A\x8B\x8C\x8D\x8E\x8F\x90\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9A\x9B\x9C\x9D\x9E\x9F\xA0\xA1\xA2\xA3\xA4\xA5\xA6\xA7\xA8\xA9\xAA\xAB\xAC\xAD\xAE\xAF\xB0\xB1\xB2\xB3\xB4\xB5\xB6\xB7\xB8\xB9\xBA\xBB\xBC\xBD\xBE\xBF\xC0\xC1\xC2\xC3\xC4\xC5\xC6\xC7\xC8\xC9\xCA\xCB\xCC\xCD\xCE\xCF\xD0\xD1\xD2\xD3\xD4\xD5\xD6\xD7\xD8\xD9\xDA\xDB\xDC\xDD\xDE\xDF\xE0\xE1\xE2\xE3\xE4\xE5\xE6\xE7\xE8\xE9\xEA\xEB\xEC\xED\xEE\xEF\xF0\xF1\xF2\xF3\xF4\xF5\xF6\xF7\xF8\xF9\xFA\xFB\xFC\xFD\xFE\xFF"); QTest::newRow("cp1257") << QByteArray("CP1257") << QByteArray("\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0A\x0B\x0C\x0D\x0E\x0F\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1A\x1B\x1C\x1D\x1E\x1F\x20\x21\x22\x23\x24\x25\x26\x27\x28\x29\x2A\x2B\x2C\x2D\x2E\x2F\x30\x31\x32\x33\x34\x35\x36\x37\x38\x39\x3A\x3B\x3C\x3D\x3E\x3F\x40\x41\x42\x43\x44\x45\x46\x47\x48\x49\x4A\x4B\x4C\x4D\x4E\x4F\x50\x51\x52\x53\x54\x55\x56\x57\x58\x59\x5A\x5B\x5C\x5D\x5E\x5F\x60\x61\x62\x63\x64\x65\x66\x67\x68\x69\x6A\x6B\x6C\x6D\x6E\x6F\x70\x71\x72\x73\x74\x75\x76\x77\x78\x79\x7A\x7B\x7C\x7D\x7E\x7F\x80\x82\x84\x85\x86\x87\x89\x8B\x8D\x8E\x8F\x91\x92\x93\x94\x95\x96\x97\x99\x9B\x9D\x9E\xA0\xA2\xA3\xA4\xA6\xA7\xA8\xA9\xAA\xAB\xAC\xAD\xAE\xAF\xB0\xB1\xB2\xB3\xB4\xB5\xB6\xB7\xB8\xB9\xBA\xBB\xBC\xBD\xBE\xBF\xC0\xC1\xC2\xC3\xC4\xC5\xC6\xC7\xC8\xC9\xCA\xCB\xCC\xCD\xCE\xCF\xD0\xD1\xD2\xD3\xD4\xD5\xD6\xD7\xD8\xD9\xDA\xDB\xDC\xDD\xDE\xDF\xE0\xE1\xE2\xE3\xE4\xE5\xE6\xE7\xE8\xE9\xEA\xEB\xEC\xED\xEE\xEF\xF0\xF1\xF2\xF3\xF4\xF5\xF6\xF7\xF8\xF9\xFA\xFB\xFC\xFD\xFE\xFF"); QTest::newRow("cp1258") << QByteArray("CP1258") << QByteArray("\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0A\x0B\x0C\x0D\x0E\x0F\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1A\x1B\x1C\x1D\x1E\x1F\x20\x21\x22\x23\x24\x25\x26\x27\x28\x29\x2A\x2B\x2C\x2D\x2E\x2F\x30\x31\x32\x33\x34\x35\x36\x37\x38\x39\x3A\x3B\x3C\x3D\x3E\x3F\x40\x41\x42\x43\x44\x45\x46\x47\x48\x49\x4A\x4B\x4C\x4D\x4E\x4F\x50\x51\x52\x53\x54\x55\x56\x57\x58\x59\x5A\x5B\x5C\x5D\x5E\x5F\x60\x61\x62\x63\x64\x65\x66\x67\x68\x69\x6A\x6B\x6C\x6D\x6E\x6F\x70\x71\x72\x73\x74\x75\x76\x77\x78\x79\x7A\x7B\x7C\x7D\x7E\x7F\x80\x82\x83\x84\x85\x86\x87\x88\x89\x8B\x8C\x91\x92\x93\x94\x95\x96\x97\x98\x99\x9B\x9C\x9F\xA0\xA1\xA2\xA3\xA4\xA5\xA6\xA7\xA8\xA9\xAA\xAB\xAC\xAD\xAE\xAF\xB0\xB1\xB2\xB3\xB4\xB5\xB6\xB7\xB8\xB9\xBA\xBB\xBC\xBD\xBE\xBF\xC0\xC1\xC2\xC3\xC4\xC5\xC6\xC7\xC8\xC9\xCA\xCB\xCC\xCD\xCE\xCF\xD0\xD1\xD2\xD3\xD4\xD5\xD6\xD7\xD8\xD9\xDA\xDB\xDC\xDD\xDE\xDF\xE0\xE1\xE2\xE3\xE4\xE5\xE6\xE7\xE8\xE9\xEA\xEB\xEC\xED\xEE\xEF\xF0\xF1\xF2\xF3\xF4\xF5\xF6\xF7\xF8\xF9\xFA\xFB\xFC\xFD\xFE\xFF"); QByteArray koi8_r_ba; for (int x=0x20; x<=0xff; ++x) { if (x!=0x9A && x!=0xbf) { koi8_r_ba.append(x); } } QTest::newRow("KOI8-R") << QByteArray("KOI8-R") << koi8_r_ba; QByteArray koi8_u_ba; for (int x=0x20; x<=0xff; ++x) { koi8_u_ba.append(x); } QTest::newRow("KOI8-U") << QByteArray("KOI8-U") << koi8_u_ba; QByteArray big5_ba; for (unsigned char u=0xa1; u<=0xf9; u++) { if (u==0xc8) { continue; } for (unsigned char v=0x40; v<=0x7e; v++) { big5_ba.append(u); big5_ba.append(v); } unsigned char v_up; switch (u) { case 0xa2: v_up=0xa1; break; case 0xa3: v_up=0xbf; break; case 0xc7: v_up=0xfc; break; case 0xf9: v_up=0xd5; break; default: v_up=0xfe; } for (unsigned char v=0xa1; v<=v_up; v++) { if (u==0xa2 && (v==0xcc || v==0xce)) { continue; } big5_ba.append(u); big5_ba.append(v); } } QTest::newRow("BIG5") << QByteArray("BIG5") << big5_ba; QByteArray gb2312_ba; for (unsigned char u=0xa1; u<=0xf7; u++) { for (unsigned char v=0xa1; v<=0xfe; v++) { gb2312_ba.append(u); gb2312_ba.append(v); } } QTest::newRow("GB2312") << QByteArray("GB2312") << gb2312_ba; } void tst_QTextCodec::moreToFromUnicode() { QFETCH( QByteArray, codecName ); QFETCH( QByteArray, testData ); QTextCodec *c = QTextCodec::codecForName( codecName.data() ); QVERIFY(c); QString uStr = c->toUnicode(testData); QByteArray cStr = c->fromUnicode(uStr); QCOMPARE(testData, cStr); } void tst_QTextCodec::shiftJis() { QByteArray backslashTilde("\\~"); QTextCodec* codec = QTextCodec::codecForName("shift_jis"); QString string = codec->toUnicode(backslashTilde); QCOMPARE(string.length(), 2); QCOMPARE(string.at(0), QChar(QLatin1Char('\\'))); QCOMPARE(string.at(1), QChar(QLatin1Char('~'))); QByteArray encoded = codec->fromUnicode(string); QCOMPARE(encoded, backslashTilde); } struct UserCodec : public QTextCodec { // implement pure virtuals QByteArray name() const Q_DECL_OVERRIDE { return "UserCodec"; } QList<QByteArray> aliases() const Q_DECL_OVERRIDE { return QList<QByteArray>() << "usercodec" << "user-codec"; } int mibEnum() const Q_DECL_OVERRIDE { return 5000; } virtual QString convertToUnicode(const char *, int, ConverterState *) const Q_DECL_OVERRIDE { return QString(); } virtual QByteArray convertFromUnicode(const QChar *, int, ConverterState *) const Q_DECL_OVERRIDE { return QByteArray(); } }; void tst_QTextCodec::userCodec() { // check that it isn't there static bool executedOnce = false; if (executedOnce) QSKIP("Test already executed once"); QVERIFY(!QTextCodec::availableCodecs().contains("UserCodec")); QVERIFY(!QTextCodec::codecForName("UserCodec")); QTextCodec *codec = new UserCodec; executedOnce = true; QList<QByteArray> availableCodecs = QTextCodec::availableCodecs(); QVERIFY(availableCodecs.contains("UserCodec")); QVERIFY(availableCodecs.contains("usercodec")); QVERIFY(availableCodecs.contains("user-codec")); QTextCodec *pcodec = QTextCodec::codecForName("UserCodec"); QCOMPARE(pcodec, codec); pcodec = QTextCodec::codecForName("user-codec"); QCOMPARE(pcodec, codec); pcodec = QTextCodec::codecForName("User-Codec"); QCOMPARE(pcodec, codec); pcodec = QTextCodec::codecForMib(5000); QCOMPARE(pcodec, codec); } struct DontCrashAtExit { ~DontCrashAtExit() { QTextCodec *c = QTextCodec::codecForName("utf8"); if (c) c->toUnicode("azerty"); } } dontCrashAtExit; QTEST_MAIN(tst_QTextCodec) #include "tst_qtextcodec.moc"
45.278003
1,050
0.623278
GrinCash