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
109
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
sequencelengths
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
sequencelengths
1
9
max_issues_count
int64
1
48.5k
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
sequencelengths
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
68d4601f864810d0ecc2a731fa03496616a82c2b
8,737
hpp
C++
include/metrics/pu_encode_data.hpp
ecarpita93/HPC_projet_1
a2c00e056c03227711c43cf2ad23d75c6afbe698
[ "Xnet", "X11" ]
null
null
null
include/metrics/pu_encode_data.hpp
ecarpita93/HPC_projet_1
a2c00e056c03227711c43cf2ad23d75c6afbe698
[ "Xnet", "X11" ]
null
null
null
include/metrics/pu_encode_data.hpp
ecarpita93/HPC_projet_1
a2c00e056c03227711c43cf2ad23d75c6afbe698
[ "Xnet", "X11" ]
null
null
null
/* PICCANTE The hottest HDR imaging library! http://vcg.isti.cnr.it/piccante Copyright (C) 2014 Visual Computing Laboratory - ISTI CNR http://vcg.isti.cnr.it First author: Francesco Banterle This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #ifndef PIC_METRICS_PU_ENCODE_DATA_HPP #define PIC_METRICS_PU_ENCODE_DATA_HPP #include <math.h> #include "../base.hpp" #include "../image.hpp" #include "../util/array.hpp" namespace pic { float C_PU_x[256] = { -5.000000f, -4.882784f, -4.765568f, -4.706960f, -4.648352f, -4.589744f, -4.531136f, -4.472527f, -4.413919f, -4.355311f, -4.296703f, -4.238095f, -4.179487f, -4.120879f, -4.062271f, -4.003663f, -3.945055f, -3.886447f, -3.827839f, -3.769231f, -3.710623f, -3.652015f, -3.593407f, -3.534799f, -3.476190f, -3.417582f, -3.358974f, -3.300366f, -3.241758f, -3.183150f, -3.124542f, -3.065934f, -3.007326f, -2.948718f, -2.890110f, -2.831502f, -2.772894f, -2.743590f, -2.714286f, -2.684982f, -2.655678f, -2.626374f, -2.597070f, -2.567766f, -2.538462f, -2.509158f, -2.479853f, -2.450549f, -2.421245f, -2.391941f, -2.362637f, -2.333333f, -2.304029f, -2.274725f, -2.245421f, -2.216117f, -2.186813f, -2.157509f, -2.128205f, -2.098901f, -2.069597f, -2.040293f, -2.010989f, -1.981685f, -1.952381f, -1.923077f, -1.893773f, -1.864469f, -1.835165f, -1.805861f, -1.776557f, -1.747253f, -1.717949f, -1.688645f, -1.659341f, -1.630037f, -1.600733f, -1.571429f, -1.542125f, -1.512821f, -1.483516f, -1.454212f, -1.424908f, -1.395604f, -1.366300f, -1.336996f, -1.307692f, -1.278388f, -1.249084f, -1.219780f, -1.190476f, -1.161172f, -1.131868f, -1.102564f, -1.073260f, -1.043956f, -1.014652f, -0.985348f, -0.956044f, -0.926740f, -0.897436f, -0.868132f, -0.838828f, -0.809524f, -0.780220f, -0.750916f, -0.736264f, -0.721612f, -0.706960f, -0.692308f, -0.677656f, -0.663004f, -0.648352f, -0.633700f, -0.619048f, -0.604396f, -0.589744f, -0.575092f, -0.560440f, -0.545788f, -0.531136f, -0.516484f, -0.501832f, -0.487179f, -0.472527f, -0.457875f, -0.443223f, -0.428571f, -0.413919f, -0.399267f, -0.384615f, -0.369963f, -0.355311f, -0.340659f, -0.326007f, -0.311355f, -0.296703f, -0.282051f, -0.267399f, -0.252747f, -0.238095f, -0.223443f, -0.208791f, -0.194139f, -0.179487f, -0.164835f, -0.150183f, -0.135531f, -0.120879f, -0.106227f, -0.091575f, -0.076923f, -0.062271f, -0.047619f, -0.032967f, -0.018315f, -0.003663f, 0.010989f, 0.025641f, 0.040293f, 0.054945f, 0.069597f, 0.084249f, 0.098901f, 0.113553f, 0.128205f, 0.142857f, 0.157509f, 0.172161f, 0.186813f, 0.201465f, 0.216117f, 0.230769f, 0.245421f, 0.267399f, 0.285714f, 0.300366f, 0.315018f, 0.329670f, 0.344322f, 0.358974f, 0.373626f, 0.388278f, 0.402930f, 0.417582f, 0.432234f, 0.446886f, 0.461538f, 0.476190f, 0.490842f, 0.505495f, 0.520147f, 0.534799f, 0.549451f, 0.564103f, 0.578755f, 0.593407f, 0.608059f, 0.622711f, 0.637363f, 0.652015f, 0.666667f, 0.681319f, 0.695971f, 0.710623f, 0.725275f, 0.739927f, 0.754579f, 0.769231f, 0.783883f, 0.798535f, 0.813187f, 0.827839f, 0.842491f, 0.857143f, 0.871795f, 0.886447f, 0.915751f, 0.945055f, 0.974359f, 1.003663f, 1.032967f, 1.062271f, 1.091575f, 1.120879f, 1.150183f, 1.179487f, 1.208791f, 1.238095f, 1.267399f, 1.296703f, 1.326007f, 1.355311f, 1.384615f, 1.413919f, 1.443223f, 1.472527f, 1.501832f, 1.531136f, 1.589744f, 1.648352f, 1.706960f, 1.765568f, 1.824176f, 1.882784f, 1.930403f, 2.007326f, 2.095238f, 2.186813f, 2.307692f, 2.399267f, 2.567766f, 2.725275f, 2.871795f, 3.260073f, 10.000000f }; float C_PU_y[256] = { 0.000000f, 0.025875f, 0.055091f, 0.071086f, 0.088082f, 0.106142f, 0.125333f, 0.145726f, 0.167397f, 0.190424f, 0.214893f, 0.240894f, 0.268524f, 0.297884f, 0.329082f, 0.362234f, 0.397462f, 0.434897f, 0.474675f, 0.516944f, 0.561860f, 0.609589f, 0.660307f, 0.714201f, 0.771470f, 0.832325f, 0.896991f, 0.965706f, 1.038724f, 1.116315f, 1.198765f, 1.286377f, 1.379476f, 1.478406f, 1.583530f, 1.695237f, 1.813939f, 1.876050f, 1.940075f, 2.006075f, 2.074110f, 2.144242f, 2.216537f, 2.291062f, 2.367884f, 2.447076f, 2.528709f, 2.612859f, 2.699604f, 2.789024f, 2.881201f, 2.976220f, 3.074169f, 3.175139f, 3.279222f, 3.386514f, 3.497114f, 3.611125f, 3.728651f, 3.849802f, 3.974687f, 4.103424f, 4.236130f, 4.372927f, 4.513943f, 4.659307f, 4.809153f, 4.963618f, 5.122847f, 5.286985f, 5.456184f, 5.630599f, 5.810392f, 5.995728f, 6.186778f, 6.383718f, 6.586730f, 6.796000f, 7.011722f, 7.234093f, 7.463319f, 7.699611f, 7.943187f, 8.194270f, 8.453091f, 8.719889f, 8.994909f, 9.278403f, 9.570633f, 9.871866f, 10.182379f, 10.502456f, 10.832392f, 11.172488f, 11.523055f, 11.884415f, 12.256896f, 12.640840f, 13.036596f, 13.444523f, 13.864993f, 14.298387f, 14.745097f, 15.205526f, 15.680088f, 16.169211f, 16.419369f, 16.673331f, 16.931156f, 17.192899f, 17.458619f, 17.728376f, 18.002228f, 18.280235f, 18.562459f, 18.848962f, 19.139806f, 19.435055f, 19.734773f, 20.039023f, 20.347873f, 20.661388f, 20.979636f, 21.302683f, 21.630599f, 21.963452f, 22.301312f, 22.644250f, 22.992336f, 23.345643f, 23.704242f, 24.068207f, 24.437610f, 24.812526f, 25.193029f, 25.579193f, 25.971094f, 26.368808f, 26.772409f, 27.181974f, 27.597580f, 28.019302f, 28.447218f, 28.881403f, 29.321934f, 29.768887f, 30.222337f, 30.682362f, 31.149035f, 31.622432f, 32.102627f, 32.589692f, 33.083700f, 33.584723f, 34.092830f, 34.608091f, 35.130574f, 35.660343f, 36.197464f, 36.741998f, 37.294006f, 37.853546f, 38.420673f, 38.995440f, 39.577897f, 40.168091f, 40.766065f, 41.371860f, 41.985513f, 42.607056f, 43.236517f, 43.873922f, 44.519290f, 45.172636f, 46.167636f, 47.010542f, 47.693856f, 48.385150f, 49.084410f, 49.791614f, 50.506734f, 51.229738f, 51.960586f, 52.699233f, 53.445627f, 54.199709f, 54.961417f, 55.730679f, 56.507418f, 57.291553f, 58.082994f, 58.881648f, 59.687414f, 60.500187f, 61.319857f, 62.146308f, 62.979420f, 63.819070f, 64.665127f, 65.517461f, 66.375935f, 67.240411f, 68.110747f, 68.986801f, 69.868426f, 70.755476f, 71.647801f, 72.545254f, 73.447684f, 74.354943f, 75.266880f, 76.183346f, 77.104195f, 78.029279f, 78.958452f, 79.891572f, 80.828498f, 82.713208f, 84.611499f, 86.522330f, 88.444709f, 90.377696f, 92.320405f, 94.272002f, 96.231710f, 98.198806f, 100.172619f, 102.152530f, 104.137968f, 106.128409f, 108.123375f, 110.122427f, 112.125165f, 114.131226f, 116.140281f, 118.152030f, 120.166201f, 122.182551f, 124.200857f, 128.242559f, 132.289936f, 136.341877f, 140.397483f, 144.456030f, 148.516935f, 151.817830f, 157.152166f, 163.251012f, 169.605996f, 177.996740f, 184.354479f, 196.054275f, 206.992126f, 217.167385f, 244.132872f, 712.224440f }; } // end namespace pic #endif /* PIC_METRICS_PU_ENCODE_DATA_HPP */
15.856624
67
0.550418
ecarpita93
68d6a5ca027ce4152a2eb01862726e28dd603b9c
19,968
hpp
C++
atto/atto/math/geometry/algebra.hpp
ubikoo/libfish
7f0b5e06b2bf1d6ff490ddfda9cc7aab69cdbf39
[ "MIT" ]
null
null
null
atto/atto/math/geometry/algebra.hpp
ubikoo/libfish
7f0b5e06b2bf1d6ff490ddfda9cc7aab69cdbf39
[ "MIT" ]
null
null
null
atto/atto/math/geometry/algebra.hpp
ubikoo/libfish
7f0b5e06b2bf1d6ff490ddfda9cc7aab69cdbf39
[ "MIT" ]
null
null
null
/* * algebra.hpp * * Copyright (c) 2020 Carlos Braga * * This program is free software; you can redistribute it and/or modify * it under the terms of the MIT License. * * See accompanying LICENSE.md or https://opensource.org/licenses/MIT. */ #ifndef ATTO_MATH_GEOMETRY_ALGEBRA_H_ #define ATTO_MATH_GEOMETRY_ALGEBRA_H_ #include "atto/math/geometry/vec2.hpp" #include "atto/math/geometry/vec3.hpp" #include "atto/math/geometry/vec4.hpp" #include "atto/math/geometry/mat2.hpp" #include "atto/math/geometry/mat3.hpp" #include "atto/math/geometry/mat4.hpp" namespace atto { namespace math { /** --------------------------------------------------------------------------- * dot * @brief Return the 2-dimensional dot product. * @see https://www.khronos.org/registry/OpenGL-Refpages/gl4/html/dot.xhtml */ template<typename Type> core_inline Type dot(const vec2<Type> &a, const vec2<Type> &b) { static_assert(std::is_floating_point<Type>::value, "non floating point"); return (a(0) * b(0) + a(1) * b(1)); } template<typename Type> core_inline vec2<Type> dot(const mat2<Type> &a, const vec2<Type> &v) { static_assert(std::is_floating_point<Type>::value, "non floating point"); return vec2<Type>( a(0,0) * v(0) + a(0,1) * v(1), a(1,0) * v(0) + a(1,1) * v(1)); } template<typename Type> core_inline mat2<Type> dot(const mat2<Type> &a, const mat2<Type> &b) { static_assert(std::is_floating_point<Type>::value, "non floating point"); return mat2<Type>( a(0,0) * b(0,0) + a(0,1) * b(1,0), a(0,0) * b(0,1) + a(0,1) * b(1,1), a(1,0) * b(0,0) + a(1,1) * b(1,0), a(1,0) * b(0,1) + a(1,1) * b(1,1)); } /** * dot * @brief Return the 3-dimensional dot product. * @see https://www.khronos.org/registry/OpenGL-Refpages/gl4/html/dot.xhtml */ template<typename Type> core_inline Type dot(const vec3<Type> &a, const vec3<Type> &b) { static_assert(std::is_floating_point<Type>::value, "non floating point"); return (a(0) * b(0) + a(1) * b(1) + a(2) * b(2)); } template<typename Type> core_inline vec3<Type> dot(const mat3<Type> &a, const vec3<Type> &v) { static_assert(std::is_floating_point<Type>::value, "non floating point"); return vec3<Type>( a(0,0) * v(0) + a(0,1) * v(1) + a(0,2) * v(2), a(1,0) * v(0) + a(1,1) * v(1) + a(1,2) * v(2), a(2,0) * v(0) + a(2,1) * v(1) + a(2,2) * v(2)); } template<typename Type> core_inline mat3<Type> dot(const mat3<Type> &a, const mat3<Type> &b) { static_assert(std::is_floating_point<Type>::value, "non floating point"); return mat3<Type>( a(0,0) * b(0,0) + a(0,1) * b(1,0) + a(0,2) * b(2,0), a(0,0) * b(0,1) + a(0,1) * b(1,1) + a(0,2) * b(2,1), a(0,0) * b(0,2) + a(0,1) * b(1,2) + a(0,2) * b(2,2), a(1,0) * b(0,0) + a(1,1) * b(1,0) + a(1,2) * b(2,0), a(1,0) * b(0,1) + a(1,1) * b(1,1) + a(1,2) * b(2,1), a(1,0) * b(0,2) + a(1,1) * b(1,2) + a(1,2) * b(2,2), a(2,0) * b(0,0) + a(2,1) * b(1,0) + a(2,2) * b(2,0), a(2,0) * b(0,1) + a(2,1) * b(1,1) + a(2,2) * b(2,1), a(2,0) * b(0,2) + a(2,1) * b(1,2) + a(2,2) * b(2,2)); } /** * dot * @brief Return the 4-dimensional dot product. * @see https://www.khronos.org/registry/OpenGL-Refpages/gl4/html/dot.xhtml */ template<typename Type> core_inline Type dot(const vec4<Type> &a, const vec4<Type> &b) { static_assert(std::is_floating_point<Type>::value, "non floating point"); return (a(0) * b(0) + a(1) * b(1) + a(2) * b(2) + a(3) * b(3)); } template<typename Type> core_inline vec4<Type> dot(const mat4<Type> &a, const vec4<Type> &v) { static_assert(std::is_floating_point<Type>::value, "non floating point"); return vec4<Type>( a(0,0) * v(0) + a(0,1) * v(1) + a(0,2) * v(2) + a(0,3) * v(3), a(1,0) * v(0) + a(1,1) * v(1) + a(1,2) * v(2) + a(1,3) * v(3), a(2,0) * v(0) + a(2,1) * v(1) + a(2,2) * v(2) + a(2,3) * v(3), a(3,0) * v(0) + a(3,1) * v(1) + a(3,2) * v(2) + a(3,3) * v(3)); } template<typename Type> core_inline mat4<Type> dot(const mat4<Type> &a, const mat4<Type> &b) { static_assert(std::is_floating_point<Type>::value, "non floating point"); return mat4<Type>( a(0,0) * b(0,0) + a(0,1) * b(1,0) + a(0,2) * b(2,0) + a(0,3) * b(3,0), a(0,0) * b(0,1) + a(0,1) * b(1,1) + a(0,2) * b(2,1) + a(0,3) * b(3,1), a(0,0) * b(0,2) + a(0,1) * b(1,2) + a(0,2) * b(2,2) + a(0,3) * b(3,2), a(0,0) * b(0,3) + a(0,1) * b(1,3) + a(0,2) * b(2,3) + a(0,3) * b(3,3), a(1,0) * b(0,0) + a(1,1) * b(1,0) + a(1,2) * b(2,0) + a(1,3) * b(3,0), a(1,0) * b(0,1) + a(1,1) * b(1,1) + a(1,2) * b(2,1) + a(1,3) * b(3,1), a(1,0) * b(0,2) + a(1,1) * b(1,2) + a(1,2) * b(2,2) + a(1,3) * b(3,2), a(1,0) * b(0,3) + a(1,1) * b(1,3) + a(1,2) * b(2,3) + a(1,3) * b(3,3), a(2,0) * b(0,0) + a(2,1) * b(1,0) + a(2,2) * b(2,0) + a(2,3) * b(3,0), a(2,0) * b(0,1) + a(2,1) * b(1,1) + a(2,2) * b(2,1) + a(2,3) * b(3,1), a(2,0) * b(0,2) + a(2,1) * b(1,2) + a(2,2) * b(2,2) + a(2,3) * b(3,2), a(2,0) * b(0,3) + a(2,1) * b(1,3) + a(2,2) * b(2,3) + a(2,3) * b(3,3), a(3,0) * b(0,0) + a(3,1) * b(1,0) + a(3,2) * b(2,0) + a(3,3) * b(3,0), a(3,0) * b(0,1) + a(3,1) * b(1,1) + a(3,2) * b(2,1) + a(3,3) * b(3,1), a(3,0) * b(0,2) + a(3,1) * b(1,2) + a(3,2) * b(2,2) + a(3,3) * b(3,2), a(3,0) * b(0,3) + a(3,1) * b(1,3) + a(3,2) * b(2,3) + a(3,3) * b(3,3)); } /** --------------------------------------------------------------------------- * norm * @brief Return the norm product of two vectors. * @see https://www.khronos.org/registry/OpenGL-Refpages/gl4/html/length.xhtml */ template<typename Type> core_inline Type norm(const vec2<Type> &a) { static_assert(std::is_floating_point<Type>::value, "non floating point"); return std::sqrt(dot(a,a)); } template<typename Type> core_inline Type norm(const vec3<Type> &a) { static_assert(std::is_floating_point<Type>::value, "non floating point"); return std::sqrt(dot(a,a)); } template<typename Type> core_inline Type norm(const vec4<Type> &a) { static_assert(std::is_floating_point<Type>::value, "non floating point"); return std::sqrt(dot(a,a)); } /** --------------------------------------------------------------------------- * normalize * @brief Return the normalize product of two vectors. * @see * https://www.khronos.org/registry/OpenGL-Refpages/gl4/html/normalize.xhtml */ template<typename Type> core_inline vec2<Type> normalize(const vec2<Type> &a) { static_assert(std::is_floating_point<Type>::value, "non floating point"); return (a / norm(a)); } template<typename Type> core_inline vec3<Type> normalize(const vec3<Type> &a) { static_assert(std::is_floating_point<Type>::value, "non floating point"); return (a / norm(a)); } template<typename Type> core_inline vec4<Type> normalize(const vec4<Type> &a) { static_assert(std::is_floating_point<Type>::value, "non floating point"); return (a / norm(a)); } /** --------------------------------------------------------------------------- * distance * @brief Return the distance product of two vectors. * @see https://www.khronos.org/registry/OpenGL-Refpages/gl4/html/distance.xhtml */ template<typename Type> core_inline Type distance(const vec2<Type> &a, const vec2<Type> &b) { static_assert(std::is_floating_point<Type>::value, "non floating point"); return norm(a-b); } template<typename Type> core_inline Type distance(const vec3<Type> &a, const vec3<Type> &b) { static_assert(std::is_floating_point<Type>::value, "non floating point"); return norm(a-b); } template<typename Type> core_inline Type distance(const vec4<Type> &a, const vec4<Type> &b) { static_assert(std::is_floating_point<Type>::value, "non floating point"); return norm(a-b); } /** --------------------------------------------------------------------------- * cross * @brief Return the cross product of two vectors. * @see https://www.khronos.org/registry/OpenGL-Refpages/gl4/html/cross.xhtml */ template<typename Type> core_inline vec3<Type> cross(const vec3<Type> &a, const vec3<Type> &b) { static_assert(std::is_floating_point<Type>::value, "non floating point"); return vec3<Type>( a(1)*b(2) - a(2)*b(1), a(2)*b(0) - a(0)*b(2), a(0)*b(1) - a(1)*b(0)); } /** --------------------------------------------------------------------------- * transpose * @brief Return the transpose of the matrix. */ template<typename Type> core_inline mat2<Type> transpose(const mat2<Type> &a) { static_assert(std::is_floating_point<Type>::value, "non floating point"); return mat2<Type>( a(0,0), a(1,0), a(0,1), a(1,1)); } template<typename Type> core_inline mat3<Type> transpose(const mat3<Type> &a) { static_assert(std::is_floating_point<Type>::value, "non floating point"); return mat3<Type>( a(0,0), a(1,0), a(2,0), a(0,1), a(1,1), a(2,1), a(0,2), a(1,2), a(2,2)); } template<typename Type> core_inline mat4<Type> transpose(const mat4<Type> &a) { static_assert(std::is_floating_point<Type>::value, "non floating point"); return mat4<Type>( a(0,0), a(1,0), a(2,0), a(3,0), a(0,1), a(1,1), a(2,1), a(3,1), a(0,2), a(1,2), a(2,2), a(3,2), a(0,3), a(1,3), a(2,3), a(3,3)); } /** --------------------------------------------------------------------------- * determinant * @brief Return the determinant of the matrix. */ template<typename Type> core_inline Type determinant(const mat2<Type> &a) { static_assert(std::is_floating_point<Type>::value, "non floating point"); /* * M = {m0, m1, * m2, m3} * * det(M) = +m0 * m3 * -m1 * m2 */ Type det = a(0,0)*a(1,1) - a(0,1)*a(1,0); return det; } template<typename Type> core_inline Type determinant(const mat3<Type> &a) { static_assert(std::is_floating_point<Type>::value, "non floating point"); /* * M = {m0, m1, m2, * m3, m4, m5, * m6, m7, m8} * * det(M) = +m0 * m4 * m8 * -m0 * m5 * m7 * -m1 * m3 * m8 * +m1 * m5 * m6 * +m2 * m3 * m7 * -m2 * m4 * m6 */ Type minor0 = a(1,1)*a(2,2) - a(1,2)*a(2,1); Type minor1 = a(1,2)*a(2,0) - a(1,0)*a(2,2); Type minor2 = a(1,0)*a(2,1) - a(1,1)*a(2,0); Type det = a(0,0)*minor0 + a(0,1)*minor1 + a(0,2)*minor2; return det; } template<typename Type> core_inline Type determinant(const mat4<Type> &a) { static_assert(std::is_floating_point<Type>::value, "non floating point"); /* * M = {m0, m1, m2, m3, * m4, m5, m6, m7, * m8, m9, m10, m11, * m12, m13, m14, m15} * * det(M) = -m0 * m10 * m13 * m7 * +m0 * m10 * m15 * m5 * +m0 * m11 * m13 * m6 * -m0 * m11 * m14 * m5 * +m0 * m14 * m7 * m9 * -m0 * m15 * m6 * m9 * +m1 * m10 * m12 * m7 * -m1 * m10 * m15 * m4 * -m1 * m11 * m12 * m6 * +m1 * m11 * m14 * m4 * -m1 * m14 * m7 * m8 * +m1 * m15 * m6 * m8 * -m10 * m12 * m3 * m5 * +m10 * m13 * m3 * m4 * +m11 * m12 * m2 * m5 * -m11 * m13 * m2 * m4 * -m12 * m2 * m7 * m9 * +m12 * m3 * m6 * m9 * +m13 * m2 * m7 * m8 * -m13 * m3 * m6 * m8 * -m14 * m3 * m4 * m9 * +m14 * m3 * m5 * m8 * +m15 * m2 * m4 * m9 * -m15 * m2 * m5 * m8 */ Type minor0 = a(2,2)*a(3,3) - a(2,3)*a(3,2); Type minor1 = a(2,3)*a(3,1) - a(2,1)*a(3,3); Type minor2 = a(2,1)*a(3,2) - a(2,2)*a(3,1); Type minor3 = a(2,3)*a(3,2) - a(2,2)*a(3,3); Type minor4 = a(2,0)*a(3,3) - a(2,3)*a(3,0); Type minor5 = a(2,2)*a(3,0) - a(2,0)*a(3,2); Type minor6 = a(2,1)*a(3,3) - a(2,3)*a(3,1); Type minor7 = a(2,3)*a(3,0) - a(2,0)*a(3,3); Type minor8 = a(2,0)*a(3,1) - a(2,1)*a(3,0); Type minor9 = a(2,2)*a(3,1) - a(2,1)*a(3,2); Type minor10 = a(2,0)*a(3,2) - a(2,2)*a(3,0); Type minor11 = a(2,1)*a(3,0) - a(2,0)*a(3,1); Type det = a(0,0) * (a(1,1) * minor0 + a(1,2) * minor1 + a(1,3) * minor2) + a(0,1) * (a(1,0) * minor3 + a(1,2) * minor4 + a(1,3) * minor5) + a(0,2) * (a(1,0) * minor6 + a(1,1) * minor7 + a(1,3) * minor8) + a(0,3) * (a(1,0) * minor9 + a(1,1) * minor10 + a(1,2) * minor11); return det; } /** --------------------------------------------------------------------------- * inverse * @brief Return the inverse of the matrix. */ template<typename Type> core_inline mat2<Type> inverse(const mat2<Type> &a) { static_assert(std::is_floating_point<Type>::value, "non floating point"); /* * Compute the inverse matrix from the corresponding adjugate: * inv(M) = adj(M) / det(M) * adj(M) = { m3, -m1, * -m2, m0} */ mat2<Type> adj( a(1,1), -a(0,1), -a(1,0), a(0,0)); /* Compute determinant from Laplace's expansion */ double det = a(0,0) * adj(0,0) + a(0,1) * adj(1,0); det = std::fabs(det) > 0.0 ? 1.0 / det : 0.0; return (adj *= det); } template<typename Type> core_inline mat3<Type> inverse(const mat3<Type> &a) { static_assert(std::is_floating_point<Type>::value, "non floating point"); /* * Compute the inverse matrix from the corresponding adjugate: * inv(M) = adj(M) / det(M) * adj(M) = {+m4*m8 - m5*m7, * +m2*m7 - m1*m8, * +m1*m5 - m2*m4 * +m5*m6 - m3*m8, * +m0*m8 - m2*m6, * +m2*m3 - m0*m5, * +m3*m7 - m4*m6, * +m1*m6 - m0*m7, * +m0*m4 - m1*m3} */ mat3<Type> adj( a(1,1) * a(2,2) - a(1,2) * a(2,1), a(0,2) * a(2,1) - a(0,1) * a(2,2), a(0,1) * a(1,2) - a(0,2) * a(1,1), a(1,2) * a(2,0) - a(1,0) * a(2,2), a(0,0) * a(2,2) - a(0,2) * a(2,0), a(0,2) * a(1,0) - a(0,0) * a(1,2), a(1,0) * a(2,1) - a(1,1) * a(2,0), a(0,1) * a(2,0) - a(0,0) * a(2,1), a(0,0) * a(1,1) - a(0,1) * a(1,0)); /* Compute determinant from Laplace's expansion */ double det = a(0,0) * adj(0,0) + a(0,1) * adj(1,0) + a(0,2) * adj(2,0); det = std::fabs(det) > 0.0 ? 1.0 / det : 0.0; return (adj *= det); } template<typename Type> core_inline mat4<Type> inverse(const mat4<Type> &a) { static_assert(std::is_floating_point<Type>::value, "non floating point"); /* * Compute the inverse matrix from the corresponding adjugate: * inv(M) = adj(M) / det(M) * adj(M) = * { * -m11*m14*m5 +m10*m15*m5 +m11*m13*m6 * -m10*m13*m7 -m15*m6 *m9 +m14*m7 *m9, * * +m1 *m11*m14 -m3 *m9 *m14 -m1 *m10*m15 * -m11*m13*m2 +m10*m13*m3 +m15*m2 *m9, * * -m15*m2 *m5 +m14*m3 *m5 +m1 *m15*m6 * -m13*m3 *m6 -m1 *m14*m7 +m13*m2 *m7, * * +m11*m2 *m5 -m10*m3 *m5 -m1 *m11*m6 * +m1 *m10*m7 +m3 *m6 *m9 -m2 *m7 *m9, * * +m11*m14*m4 -m10*m15*m4 -m11*m12*m6 * +m10*m12*m7 +m15*m6 *m8 -m14*m7 *m8, * * -m0 *m11*m14 +m3 *m8 *m14 +m0 *m10*m15 * +m11*m12*m2 -m10*m12*m3 -m15*m2 *m8, * * +m15*m2 *m4 -m14*m3 *m4 -m0 *m15*m6 * +m12*m3 *m6 +m0 *m14*m7 -m12*m2 *m7, * * -m11*m2 *m4 +m10*m3 *m4 +m0 *m11*m6 * -m0 *m10*m7 -m3 *m6 *m8 +m2 *m7 *m8, * * -m11*m13*m4 +m15*m9 *m4 +m11*m12*m5 * -m15*m5 *m8 +m13*m7 *m8 -m12*m7 *m9, * * -m1 *m11*m12 +m3 *m9 *m12 +m0 *m11*m13 * +m1 *m15*m8 -m13*m3 *m8 -m0 *m15*m9, * * -m1 *m15*m4 +m13*m3 *m4 +m0 *m15*m5 * -m12*m3 *m5 +m1 *m12*m7 -m0 *m13*m7, * * +m1 *m11*m4 -m3 *m9 *m4 -m0 *m11*m5 * +m3 *m5 *m8 -m1 *m7 *m8 +m0 *m7 *m9, * * +m10*m13*m4 -m14*m9 *m4 -m10*m12*m5 * +m14*m5 *m8 -m13*m6 *m8 +m12*m6 *m9, * * +m1 *m10*m12 -m2 *m9 *m12 -m0 *m10*m13 * -m1 *m14*m8 +m13*m2 *m8 +m0 *m14*m9, * * +m1 *m14*m4 -m13*m2 *m4 -m0 *m14*m5 * +m12*m2 *m5 -m1 *m12*m6 +m0 *m13*m6, * * -m1 *m10*m4 +m2 *m9 *m4 +m0 *m10*m5 * -m2 *m5 *m8 +m1 *m6 *m8 -m0 *m6 *m9 * } */ mat4<Type> adj( a(1,1) * (a(2,2) * a(3,3) - a(2,3) * a(3,2)) + a(1,2) * (a(2,3) * a(3,1) - a(2,1) * a(3,3)) + a(1,3) * (a(2,1) * a(3,2) - a(2,2) * a(3,1)), a(0,1) * (a(2,3) * a(3,2) - a(2,2) * a(3,3)) + a(0,2) * (a(2,1) * a(3,3) - a(2,3) * a(3,1)) + a(0,3) * (a(2,2) * a(3,1) - a(2,1) * a(3,2)), a(1,1) * (a(0,3) * a(3,2) - a(0,2) * a(3,3)) + a(1,2) * (a(0,1) * a(3,3) - a(0,3) * a(3,1)) + a(1,3) * (a(0,2) * a(3,1) - a(0,1) * a(3,2)), a(1,1) * (a(0,2) * a(2,3) - a(2,2) * a(0,3)) + a(1,2) * (a(0,3) * a(2,1) - a(0,1) * a(2,3)) + a(1,3) * (a(0,1) * a(2,2) - a(0,2) * a(2,1)), a(1,0) * (a(2,3) * a(3,2) - a(2,2) * a(3,3)) + a(1,2) * (a(2,0) * a(3,3) - a(2,3) * a(3,0)) + a(1,3) * (a(2,2) * a(3,0) - a(2,0) * a(3,2)), a(0,0) * (a(2,2) * a(3,3) - a(2,3) * a(3,2)) + a(0,2) * (a(2,3) * a(3,0) - a(2,0) * a(3,3)) + a(0,3) * (a(2,0) * a(3,2) - a(2,2) * a(3,0)), a(0,0) * (a(1,3) * a(3,2) - a(1,2) * a(3,3)) + a(0,2) * (a(1,0) * a(3,3) - a(1,3) * a(3,0)) + a(0,3) * (a(1,2) * a(3,0) - a(1,0) * a(3,2)), a(0,0) * (a(1,2) * a(2,3) - a(1,3) * a(2,2)) + a(0,2) * (a(1,3) * a(2,0) - a(1,0) * a(2,3)) + a(0,3) * (a(1,0) * a(2,2) - a(1,2) * a(2,0)), a(1,0) * (a(2,1) * a(3,3) - a(2,3) * a(3,1)) + a(1,1) * (a(2,3) * a(3,0) - a(2,0) * a(3,3)) + a(1,3) * (a(2,0) * a(3,1) - a(2,1) * a(3,0)), a(0,0) * (a(2,3) * a(3,1) - a(2,1) * a(3,3)) + a(0,1) * (a(2,0) * a(3,3) - a(2,3) * a(3,0)) + a(0,3) * (a(2,1) * a(3,0) - a(2,0) * a(3,1)), a(0,0) * (a(1,1) * a(3,3) - a(1,3) * a(3,1)) + a(0,1) * (a(1,3) * a(3,0) - a(1,0) * a(3,3)) + a(0,3) * (a(1,0) * a(3,1) - a(1,1) * a(3,0)), a(0,0) * (a(1,3) * a(2,1) - a(1,1) * a(2,3)) + a(0,1) * (a(1,0) * a(2,3) - a(1,3) * a(2,0)) + a(0,3) * (a(1,1) * a(2,0) - a(2,1) * a(1,0)), a(1,0) * (a(2,2) * a(3,1) - a(2,1) * a(3,2)) + a(1,1) * (a(2,0) * a(3,2) - a(2,2) * a(3,0)) + a(1,2) * (a(2,1) * a(3,0) - a(2,0) * a(3,1)), a(0,0) * (a(2,1) * a(3,2) - a(2,2) * a(3,1)) + a(0,1) * (a(2,2) * a(3,0) - a(2,0) * a(3,2)) + a(0,2) * (a(2,0) * a(3,1) - a(2,1) * a(3,0)), a(0,0) * (a(1,2) * a(3,1) - a(1,1) * a(3,2)) + a(0,1) * (a(1,0) * a(3,2) - a(1,2) * a(3,0)) + a(0,2) * (a(1,1) * a(3,0) - a(1,0) * a(3,1)), a(0,0) * (a(1,1) * a(2,2) - a(1,2) * a(2,1)) + a(0,1) * (a(1,2) * a(2,0) - a(1,0) * a(2,2)) + a(0,2) * (a(1,0) * a(2,1) - a(1,1) * a(2,0))); /* Compute inverse matrix using Laplace's expansion */ double det = a(0,0) * adj(0,0) + a(0,1) * adj(1,0) + a(0,2) * adj(2,0) + a(0,3) * adj(3,0); det = std::fabs(det) > 0.0 ? 1.0 / det : 0.0; return (adj *= det); } } /* namespace math */ } /* namespace atto */ /** --------------------------------------------------------------------------- * @brief Enable simd vectorized instructions. */ #ifdef ATTO_MATH_SIMD #include "atto/math/geometry/algebra-simd.hpp" #endif #endif /* ATTO_MATH_GEOMETRY_ALGEBRA */
31.796178
80
0.455629
ubikoo
68d7c6a7182e36cfd4e148b2297d38ea46c3c128
3,313
cpp
C++
src/SceneMonitor.cpp
rcstilborn/SecMon
f750d9c421dac1c5a795384ff8f7b7a29a0aece9
[ "MIT" ]
2
2021-12-17T17:35:07.000Z
2022-01-11T12:38:00.000Z
src/SceneMonitor.cpp
rcstilborn/SecMon
f750d9c421dac1c5a795384ff8f7b7a29a0aece9
[ "MIT" ]
null
null
null
src/SceneMonitor.cpp
rcstilborn/SecMon
f750d9c421dac1c5a795384ff8f7b7a29a0aece9
[ "MIT" ]
2
2018-01-15T06:10:07.000Z
2021-07-08T19:40:49.000Z
/* * SceneMonitor.cpp * * Created on: Jul 27, 2015 * Author: richard * * Copyright 2017 Richard Stilborn * Licensed under the MIT License */ #include "SceneMonitor.h" #include <boost/asio/io_service.hpp> #include <boost/bind/bind.hpp> #include <boost/iterator/iterator_facade.hpp> #include <boost/ptr_container/detail/associative_ptr_container.hpp> #include <boost/ptr_container/detail/reversible_ptr_container.hpp> #include <boost/ptr_container/ptr_map_adapter.hpp> #include <boost/thread/lock_guard.hpp> #include <iostream> #include <list> #include <sstream> #include <stdexcept> #include <string> #include <utility> #include "GUI/GUI_Interface.h" SceneMonitor::SceneMonitor(boost::asio::io_service& io_service, GUI_Interface& gui) : io_service_(io_service), gui_(gui), scenes_(), scenes_mtx_() { // gui_.createRoom("cameras", boost::bind<const std::string>(&SceneMonitor::get_scene_names, this)); } SceneMonitor::~SceneMonitor() { boost::lock_guard<boost::mutex> guard(scenes_mtx_); for (boost::ptr_map<std::string, Scene>::iterator it = scenes_.begin(); it != scenes_.end(); ++it) scenes_.erase(it); } void SceneMonitor::start_monitoring(const std::string& name, const std::string& url, const double realtime_factor) { // Check if we already have this name boost::ptr_map<std::string, Scene>::iterator it = scenes_.find(name); if (it != this->scenes_.end()) throw std::invalid_argument("A scene with this name already exists: " + name); // Create the scene { Scene* scene = new Scene(name, url, io_service_, gui_, realtime_factor); boost::lock_guard<boost::mutex> guard(scenes_mtx_); // TODO(richard): Fix this silliness! std::string foo(name); this->scenes_.insert(foo, scene); } } void SceneMonitor::stop_monitoring(const std::string& name) { std::cout << "SceneMonitor.stopMonitoring() - enter" << std::endl; boost::ptr_map<std::string, Scene>::iterator it = scenes_.find(name); if (it != this->scenes_.end()) { boost::lock_guard<boost::mutex> guard(scenes_mtx_); it->second->shutdown(); } } void SceneMonitor::stop_all_monitoring() { std::cout << "SceneMonitor.stopAllMonitoring() - enter" << std::endl; for (auto scene : this->scenes_) scene.second->shutdown(); std::this_thread::sleep_for(std::chrono::seconds(2)); } const std::string SceneMonitor::get_scene_names() const { std::stringstream list; const char* separator = ""; list << '['; for (auto name : this->scenes_) { list << separator << name.first; separator = ","; } list << ']'; return list.str(); } // std::vector<scene_details> SceneMonitor::getSceneDetails(){ // std::vector<scene_details> details; // for(auto entry: this->scenes){ // scene_details detail; // detail.name = entry.second->getName(); // detail.height = entry.second->getCamera().getHeight(); // detail.width = entry.second->getCamera().getWidth(); // details.push_back(detail); // } // return details; //} void SceneMonitor::toggle_pause() { for (auto scene : this->scenes_) scene.second->toggle_pause(); } void SceneMonitor::set_realtime_factor(const double realtime_factor) { for (auto scene : this->scenes_) scene.second->set_realtime_factor(realtime_factor); }
29.061404
116
0.686991
rcstilborn
68d9deed1f22ec03ee368305b88181ee84a5347d
1,854
cpp
C++
m4cpp/src/uart.cpp
matheusmb/smep-gateway
c32ff83cf48488404a5c094137b33be09d84581c
[ "MIT" ]
null
null
null
m4cpp/src/uart.cpp
matheusmb/smep-gateway
c32ff83cf48488404a5c094137b33be09d84581c
[ "MIT" ]
null
null
null
m4cpp/src/uart.cpp
matheusmb/smep-gateway
c32ff83cf48488404a5c094137b33be09d84581c
[ "MIT" ]
null
null
null
#include "uart.h" #include "board.h" #include "WString.h" #define UARTx_IRQn USART0_IRQn void UART_Init( const uint32_t baud ) { Board_UART_Init( LPC_UART ); Chip_UART_Init( LPC_UART ); Chip_UART_SetBaud( LPC_UART, baud ); Chip_UART_TXEnable( LPC_UART ); } void UART_IRQ_Init() { UART_IntEnable(); Chip_UART_SetupFIFOS( LPC_UART, UART_FCR_FIFO_EN | UART_FCR_TRG_LEV2 | UART_FCR_RX_RS ); NVIC_SetPriority(UARTx_IRQn, 1); NVIC_EnableIRQ(UARTx_IRQn); } void UART_IntEnable() { Chip_UART_IntEnable( LPC_UART, (UART_IER_RBRINT | UART_IER_RLSINT) ); } void UART_IntDisable() { Chip_UART_IntDisable( LPC_UART, (UART_IER_RBRINT | UART_IER_RLSINT) ); } void UART_Send(const void * data, int numBytes ) { Chip_UART_SendBlocking( LPC_UART, data, numBytes ); } void UART_Send( String cmd ) { UART_Send( cmd.c_str(), cmd.length() ); } uint8_t UART_Read() { return Chip_UART_ReadByte( LPC_UART ); } bool UART_Available() { return Chip_UART_ReadLineStatus( LPC_UART ) & UART_LSR_RDR; } #define MAX_BUFFER_SIZE 1500 String receiveBuffer; void UARTx_IRQHandler(void) { String out; uint32_t IIR = LPC_UART->IIR & UART_IIR_BITMASK; uint32_t INTID = IIR & UART_IIR_INTID_MASK; uint32_t LSR = 0; bool recv = false; switch(INTID) { case UART_IIR_INTID_CTI: case UART_IIR_INTID_RDA: recv = true; if( receiveBuffer.length() > MAX_BUFFER_SIZE ) receiveBuffer = receiveBuffer.substring( MAX_BUFFER_SIZE / 2); // Discard half of the contents while( UART_Available() ) { receiveBuffer += (char) UART_Read(); } break; case UART_IIR_INTID_RLS: LSR = Chip_UART_ReadLineStatus(LPC_UART) & UART_LSR_BITMASK; // Clear RLS interrupt printf("RLS %d", LSR); break; default: printf("Unkown %d", INTID); } /*if( recv ) { printf("UART_IRQ:"); printf( receiveBuffer ); receiveBuffer = ""; }*/ }
20.373626
98
0.718986
matheusmb
68dd0fd03a89896af9cefc24fd2642e92fc94ade
22,627
cpp
C++
framework/areg/component/private/ComponentLoader.cpp
Ali-Nasrolahi/areg-sdk
4fbc2f2644220196004a31672a697a864755f0b6
[ "Apache-2.0" ]
70
2021-07-20T11:26:16.000Z
2022-03-27T11:17:43.000Z
framework/areg/component/private/ComponentLoader.cpp
Ali-Nasrolahi/areg-sdk
4fbc2f2644220196004a31672a697a864755f0b6
[ "Apache-2.0" ]
32
2021-07-31T05:20:44.000Z
2022-03-20T10:11:52.000Z
framework/areg/component/private/ComponentLoader.cpp
Ali-Nasrolahi/areg-sdk
4fbc2f2644220196004a31672a697a864755f0b6
[ "Apache-2.0" ]
40
2021-11-02T09:45:38.000Z
2022-03-27T11:17:46.000Z
/************************************************************************ * This file is part of the AREG SDK core engine. * AREG SDK is dual-licensed under Free open source (Apache version 2.0 * License) and Commercial (with various pricing models) licenses, depending * on the nature of the project (commercial, research, academic or free). * You should have received a copy of the AREG SDK license description in LICENSE.txt. * If not, please contact to info[at]aregtech.com * * \copyright (c) 2017-2021 Aregtech UG. All rights reserved. * \file areg/component/private/ComponentLoader.cpp * \ingroup AREG SDK, Asynchronous Event Generator Software Development Kit * \author Artak Avetyan * \brief AREG Platform, Component Loader singleton object. * ************************************************************************/ #include "areg/component/ComponentLoader.hpp" #include "areg/component/Component.hpp" #include "areg/component/ComponentThread.hpp" #include "areg/component/private/ServiceManager.hpp" #include "areg/base/NECommon.hpp" ////////////////////////////////////////////////////////////////////////// // ModelDataCreator class implementation ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// // ModelDataCreator class, constructor / destructor ////////////////////////////////////////////////////////////////////////// ModelDataCreator::ModelDataCreator( FuncInitLoaderItem funtCreateModelData, const char * modelName ) { ASSERT( funtCreateModelData != nullptr ); NERegistry::Model newModel = funtCreateModelData(modelName); VERIFY( ComponentLoader::getInstance().addModel( newModel ) ); } ModelDataCreator::ModelDataCreator( const NERegistry::Model & newModel ) { VERIFY( ComponentLoader::getInstance().addModel( newModel ) ); } ////////////////////////////////////////////////////////////////////////// // ComponentLoader class implementation ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// // ComponentLoader class, static functions ////////////////////////////////////////////////////////////////////////// ComponentLoader & ComponentLoader::getInstance( void ) { static ComponentLoader _componentLoader; return _componentLoader; } bool ComponentLoader::loadComponentModel( const char * modelName /*= nullptr*/ ) { bool result = ComponentLoader::getInstance().loadModel( modelName ); if ( result == false) ComponentLoader::getInstance().unloadModel( modelName ); return result; } void ComponentLoader::unloadComponentModel( const char * modelName /*= nullptr*/ ) { ComponentLoader::getInstance( ).unloadModel( modelName ); } const NERegistry::ComponentList& ComponentLoader::getComponentList( const char* threadName ) { const NERegistry::ComponentList* result = nullptr; ComponentLoader& loader = getInstance(); Lock lock(loader.mLock); for ( int i = 0; result == nullptr && i < loader.mModelList.getSize(); ++ i ) { const NERegistry::Model & model = loader.mModelList.getAt(i); if ( model.isModelLoaded() ) { const NERegistry::ComponentThreadList & threadList = model.getThreadList(); for ( int j = 0; result == nullptr && j < threadList.getSize(); ++ j ) { const NERegistry::ComponentThreadEntry & thrEntry = threadList.getAt(j); if (thrEntry.mThreadName == threadName) result = &thrEntry.mComponents; } } } return (result != nullptr ? *result : NERegistry::INVALID_COMPONENT_LIST); } const NERegistry::ComponentEntry& ComponentLoader::findComponentEntry( const char* roleName, const char* threadName ) { const NERegistry::ComponentEntry* result = nullptr; const NERegistry::ComponentList& comList = getComponentList(threadName); if (comList.isValid()) { for (int i = 0; result == nullptr && i < comList.getSize(); ++ i) { const NERegistry::ComponentEntry& entry = comList[i]; result = entry.mRoleName == roleName ? &entry : nullptr; } } return (result != nullptr ? *result : NERegistry::INVALID_COMPONENT_ENTRY); } const NERegistry::ComponentEntry& ComponentLoader::findComponentEntry( const char* roleName ) { const NERegistry::ComponentEntry* result = nullptr; ComponentLoader & loader = ComponentLoader::getInstance(); Lock lock(loader.mLock); for ( int i = 0; result == nullptr && i < loader.mModelList.getSize(); ++ i ) { const NERegistry::ComponentThreadList & threadList = loader.mModelList.getAt(i).getThreadList(); for ( int j = 0; result == nullptr && j < threadList.getSize(); ++ j ) { const NERegistry::ComponentThreadEntry & threadEntry = threadList.getAt(j); for ( int k = 0; result == nullptr && k < threadEntry.mComponents.getSize(); ++ k ) result = threadEntry.mComponents.getAt(k).mRoleName == roleName ? &threadEntry.mComponents.getAt(k) : nullptr; } } return (result != nullptr ? *result : NERegistry::INVALID_COMPONENT_ENTRY); } bool ComponentLoader::isModelLoaded( const char * modelName ) { bool result = false; if ( NEString::isEmpty<char>(modelName) == false ) { ComponentLoader & loader = ComponentLoader::getInstance(); Lock lock(loader.mLock); for ( int i = 0; i < loader.mModelList.getSize(); ++ i ) { const NERegistry::Model & model = loader.mModelList.getAt(i); if ( model.getModelName() == modelName ) { result = model.isModelLoaded(); break; } } } return result; } bool ComponentLoader::existModel( const char * modelName ) { bool result = false; if ( NEString::isEmpty<char>( modelName ) == false ) { ComponentLoader & loader = ComponentLoader::getInstance( ); Lock lock( loader.mLock ); for ( int i = 0; i < loader.mModelList.getSize( ); ++ i ) { const NERegistry::Model & model = loader.mModelList.getAt( i ); if ( model.getModelName( ) == modelName ) { result = true; break; } } } return result; } bool ComponentLoader::setComponentData( const char * roleName, NEMemory::uAlign compData ) { bool result = false; ComponentLoader & loader = ComponentLoader::getInstance( ); Lock lock( loader.mLock ); for ( int i = 0; i < loader.mModelList.getSize( ); ++ i ) { NERegistry::Model & model = loader.mModelList.getAt( i ); if ( model.setComponentData( roleName, compData ) ) { result = true; break; } } return result; } bool ComponentLoader::addModelUnique(const NERegistry::Model & newModel) { ComponentLoader & loader = ComponentLoader::getInstance(); Lock lock( loader.mLock ); return loader.addModel(newModel); } void ComponentLoader::removeComponentModel(const char * modelName /*= nullptr */) { OUTPUT_WARN("Removing components and model [ %s ]", modelName != nullptr ? modelName : "ALL MODELS"); ComponentLoader::unloadComponentModel(modelName); ComponentLoader & loader = ComponentLoader::getInstance(); Lock lock( loader.mLock ); if ( NEString::isEmpty<char>(modelName) == false ) { for ( int i = 0; i < loader.mModelList.getSize(); ++ i ) { NERegistry::Model & model = loader.mModelList[i]; if ( model.getModelName() == modelName ) { loader.mModelList.removeAt(i); break; } } } else { loader.mModelList.removeAll(); } } ////////////////////////////////////////////////////////////////////////// // ComponentLoader class, constructor / destructor ////////////////////////////////////////////////////////////////////////// ComponentLoader::ComponentLoader( void ) : mModelList ( ) , mDefaultModel ( NEString::EmptyStringA.data( ) ) , mLock ( ) { } ComponentLoader::~ComponentLoader( void ) { mModelList.removeAll(); mDefaultModel = NEString::EmptyStringA.data( ); } ////////////////////////////////////////////////////////////////////////// // ComponentLoader class, methods ////////////////////////////////////////////////////////////////////////// bool ComponentLoader::addModel( const NERegistry::Model & newModel ) { Lock lock(mLock); OUTPUT_DBG("Registering model with name [ %s ]", newModel.getModelName().getString()); bool hasError = newModel.getModelName().isEmpty() || newModel.isModelLoaded() ? true : false; // the new model name cannot be empty and it should be unique, and it cannot be marked as loaded. ASSERT(hasError == false); // search if model with the same name exists for (int i = 0; hasError == false && i < mModelList.getSize(); ++ i ) { const NERegistry::Model & regModel = mModelList.getAt(i); if ( newModel.getModelName() != regModel.getModelName() ) { const NERegistry::ComponentThreadList & regThreadList = regModel.getThreadList(); for ( int j = 0; hasError == false && j < regThreadList.getSize(); ++ j ) { const NERegistry::ComponentThreadEntry & regThreadEntry = regThreadList.getAt(j); if ( newModel.findThread(regThreadEntry) < 0 ) { const NERegistry::ComponentList & regComponentList = regThreadEntry.mComponents; for ( int k = 0; hasError == false && k < regComponentList.getSize(); ++ k ) { const NERegistry::ComponentEntry & regComponentEntry = regComponentList.getAt(k); if ( newModel.hasRegisteredComponent(regComponentEntry) ) { OUTPUT_ERR("The component with role name [ %s ] is already registered in thread [ %s ] of model [ %s ], cannot add new model!" , regComponentEntry.mRoleName.getString() , regThreadEntry.mThreadName.getString() , regModel.getModelName().getString() ); hasError = true; ASSERT(false); } else { ; // is OK, continue checking } } // end of for ( int k = 0; hasError == false && k < newComponentList.GetSize(); k ++ ) } else { OUTPUT_ERR("The thread with name [ %s ] is already registered in model [ %s ], cannot add new model!" , regThreadEntry.mThreadName.getString() , regModel.getModelName().getString()); hasError = true; ASSERT(false); } } // end of for ( int j = 0; hasError == false && j < newThreadList.GetSize(); j ++ ) } else { OUTPUT_ERR("The model with name [ %s ] is already registered, cannot add new model!", regModel.getModelName().getString()); hasError = true; ASSERT(false); } } if ( hasError == false ) { OUTPUT_DBG("The model [ %s ] is defined correct, adding in the list.", newModel.getModelName().getString()); mModelList.add(newModel); if ( mDefaultModel.isEmpty() ) { mDefaultModel = newModel.getModelName().getString(); } } return (hasError == false); } bool ComponentLoader::loadModel( const char * modelName /*= nullptr*/ ) { Lock lock(mLock); bool result = false; OUTPUT_DBG("Requested to start load model [ %s ].", NEString::isEmpty<char>(modelName) ? "ALL" : modelName); if ( NEString::isEmpty<char>(modelName) ) { result = mModelList.getSize() > 0; for ( int i = 0; result && i < mModelList.getSize(); ++ i ) { NERegistry::Model & model = mModelList[i]; if ( model.isModelLoaded() == false ) result = loadModel( model ); ASSERT( model.isModelLoaded() ); } } else { OUTPUT_DBG("Searching model [ %s ] in the list with size [ %d ]", modelName, mModelList.getSize() ); int index = -1; for ( int i = 0; (index == -1) && (i < mModelList.getSize()); ++ i ) { NERegistry::Model & model = mModelList[i]; OUTPUT_DBG("Checking the name, the entry [ %d ] has name [ %s ]", i, model.getModelName().getString()); if ( model.getModelName() == modelName ) { OUTPUT_DBG("Found model with name [ %s ] at position [ %d ]", modelName, i); index = i; result = loadModel(model); } } } OUTPUT_DBG("Model [ %s ] loaded with [ %s ].", NEString::isEmpty<char>(modelName) ? "ALL" : modelName, result ? "SUCCESS" : "ERROR"); return result; } bool ComponentLoader::loadModel( NERegistry::Model & whichModel ) const { bool result = false; if ( whichModel.isValid() && (whichModel.isModelLoaded( ) == false) ) { const NERegistry::ComponentThreadList& thrList = whichModel.getThreadList( ); OUTPUT_DBG( "Starting to load model [ %s ]. There are [ %d ] component threads to start. Component loader is going to load objects and start Service Manager" , whichModel.getModelName( ).getString( ) , thrList.getSize( ) ); whichModel.markModelLoaded( true ); result = true; for ( int i = 0; result && i < thrList.getSize( ); ++ i ) { Lock lock( mLock ); const NERegistry::ComponentThreadEntry& entry = thrList[i]; if ( entry.isValid( ) && Thread::findThreadByName( entry.mThreadName.getString( ) ) == nullptr ) { ComponentThread* thrObject = DEBUG_NEW ComponentThread( entry.mThreadName.getString( ) ); if ( thrObject != nullptr ) { OUTPUT_DBG( "Starting thread [ %s ] and loading components.", thrObject->getName( ).getString( ) ); if ( thrObject->createThread( NECommon::WAIT_INFINITE ) == false ) { OUTPUT_ERR( "Failed to create and start thread [ %s ], going to delete and unload components.", thrObject->getName( ).getString( ) ); thrObject->destroyThread( NECommon::DO_NOT_WAIT ); delete thrObject; result = false; } } else { OUTPUT_ERR( "Failed instantiate component thread object with name [ %s ]", entry.mThreadName.getString( ) ); result = false; } } else { result = entry.isValid( ); OUTPUT_ERR( "Either Thread [ %s ] is already created or it is invalid: is valid [ %s ], already exists [ %s ]." , entry.mThreadName.getString( ) , entry.isValid( ) ? "TRUE" : "FALSE" , Thread::findThreadByName( entry.mThreadName) != nullptr ? "EXISTS" : "DOES NOT EXIST" ); } } } else { OUTPUT_WARN( "The model [ %s ] is already loaded. Ignoring loading model", whichModel.getModelName( ).getString( ) ); result = true; } return result; } void ComponentLoader::unloadModel( const char * modelName /*= nullptr*/ ) { Lock lock(mLock); OUTPUT_DBG("Requested to unload model [ %s ].", NEString::isEmpty<char>(modelName) ? "ALL" : modelName); if ( NEString::isEmpty<char>(modelName) ) { for ( int i = 0; i < mModelList.getSize(); ++ i ) { NERegistry::Model & model = mModelList[i]; lock.unlock(); unloadModel(model); lock.lock(); ASSERT( model.isModelLoaded() == false ); } } else { int index = -1; for ( int i = 0; index == -1 && i < mModelList.getSize(); ++ i ) { NERegistry::Model & model = mModelList[i]; if ( model.getModelName() == modelName ) { index = i; lock.unlock(); unloadModel(model); lock.lock(); } } } } void ComponentLoader::unloadModel( NERegistry::Model & whichModel ) const { Lock lock(mLock); OUTPUT_WARN("Requested to unload components. Going to unload model [ %s ]!", static_cast<const char *>(whichModel.getModelName().getString())); if (whichModel.isModelLoaded() ) { const NERegistry::ComponentThreadList & threadList = whichModel.getThreadList(); shutdownThreads( threadList ); lock.unlock(); waitThreadsCompletion( threadList ); lock.lock(); destroyThreads( threadList ); whichModel.markModelLoaded( false ); } else { OUTPUT_WARN("The model [ %s ] marked as unloaded. Ignoring request to unload model.", static_cast<const char *>(whichModel.getModelName().getString())); } } void ComponentLoader::shutdownThreads( const NERegistry::ComponentThreadList & whichThreads ) const { OUTPUT_INFO("Starting First Level model shutdown. Shutdown Threads and Components"); for (int i = 0; i < whichThreads.getSize(); ++ i ) { const NERegistry::ComponentThreadEntry& entry = whichThreads[i]; Thread* thrObject = Thread::findThreadByName(entry.mThreadName.getString()); if (thrObject != nullptr) { ASSERT(RUNTIME_CAST(thrObject, ComponentThread) != nullptr); OUTPUT_WARN("Shutdown thread [ %s ] and all its components", thrObject->getName().getString()); thrObject->shutdownThread(); } else { OUTPUT_WARN("Could not find thread entry [ %s ]. Ignoring stoppint thread.", entry.mThreadName.getString()); } } OUTPUT_INFO("Shuts down Service Manager thread!"); } void ComponentLoader::waitThreadsCompletion( const NERegistry::ComponentThreadList & whichThreads ) const { OUTPUT_INFO("Starting Second Level model shutdown. Wait for Threads completion!"); for ( int i = 0; i < whichThreads.getSize(); ++ i ) { const NERegistry::ComponentThreadEntry& entry = whichThreads[i]; Thread* thrObject = Thread::findThreadByName(entry.mThreadName.getString()); if (thrObject != nullptr) { ASSERT(RUNTIME_CAST(thrObject, ComponentThread) != nullptr); OUTPUT_WARN("Waiting thread [ %s ] completion", thrObject->getName().getString()); thrObject->completionWait(NECommon::WAIT_INFINITE); } else { OUTPUT_WARN("Could not find thread entry [ %s ]. Ignoring stoppint thread.", entry.mThreadName.getString()); } } } void ComponentLoader::destroyThreads( const NERegistry::ComponentThreadList & whichThreads ) const { OUTPUT_INFO("Starting Third Level model shutdown. Destroy threads and components!"); for ( int i = 0; i < whichThreads.getSize(); ++ i ) { const NERegistry::ComponentThreadEntry& entry = whichThreads[i]; Thread* thrObject = Thread::findThreadByName(entry.mThreadName.getString()); if (thrObject != nullptr) { ASSERT(RUNTIME_CAST(thrObject, ComponentThread) != nullptr); OUTPUT_WARN("Stopping and deleting thread [ %s ] and deleting components", thrObject->getName().getString()); thrObject->destroyThread(NECommon::WAIT_INFINITE); delete thrObject; } else { OUTPUT_WARN("Could not find thread entry [ %s ]. Ignoring stoppint thread.", entry.mThreadName.getString()); } } } const NERegistry::Model * ComponentLoader::findModelByName( const char * modelName ) const { const NERegistry::Model * result = nullptr; if ( NEString::isEmpty<char>(modelName) == false ) { for ( int i = 0; (result == nullptr) && (i < mModelList.getSize( )); ++i ) { const NERegistry::Model & model = mModelList[i]; result = model.getModelName( ) == modelName ? &model : nullptr; } } return result; } const NERegistry::ComponentThreadEntry * ComponentLoader::findThreadEntryByName( const char * threadName ) const { const NERegistry::ComponentThreadEntry * result = nullptr; if ( NEString::isEmpty<char>(threadName) == false ) { for ( int i = 0; (result == nullptr) && (i < mModelList.getSize()); ++i ) { const NERegistry::Model & model = mModelList[i]; int index = model.findThread(threadName); if ( index != NECommon::INVALID_INDEX ) { const NERegistry::ComponentThreadEntry & entry = model.getThreadList().getAt(index); result = &entry; } } } return result; } const NERegistry::ComponentEntry * ComponentLoader::findComponentEntryByName( const char * roleName ) const { const NERegistry::ComponentEntry * result = nullptr; if ( NEString::isEmpty<char>(roleName) == false ) { for ( int i = 0; (result == nullptr) && (i < mModelList.getSize()); ++i ) { const NERegistry::Model & model = mModelList[i]; const NERegistry::ComponentThreadList & threadList= model.getThreadList(); for ( int j = 0; (result == nullptr) && (i < threadList.getSize()); ++i ) { const NERegistry::ComponentThreadEntry & thread = threadList.getAt(j); int index = thread.findComponentEntry(roleName); if ( index != NECommon::INVALID_INDEX ) { const NERegistry::ComponentEntry & entry = thread.mComponents.getAt(index); result = & entry; } } } } return result; }
38.878007
165
0.557431
Ali-Nasrolahi
68e7b53a748c7f1204bdbd44a08745d63ee42e9e
4,874
cpp
C++
jit.cpp
c3sr/go-pytorch
0d1f6edbc6e48f0f68055274af0997e2ff9b0ce1
[ "Apache-2.0" ]
14
2018-11-26T18:33:27.000Z
2021-12-17T11:14:33.000Z
jit.cpp
c3sr/go-pytorch
0d1f6edbc6e48f0f68055274af0997e2ff9b0ce1
[ "Apache-2.0" ]
7
2019-04-02T16:46:01.000Z
2020-06-10T02:02:33.000Z
jit.cpp
c3sr/go-pytorch
0d1f6edbc6e48f0f68055274af0997e2ff9b0ce1
[ "Apache-2.0" ]
3
2019-07-16T16:47:07.000Z
2021-12-29T07:47:59.000Z
#ifdef ENABLE_PYTROCH_JIT #include "error.hpp" #include "predictor.hpp" #include <algorithm> #include <iosfwd> #include <iostream> #include <memory> #include <string> #include <typeinfo> #include <utility> #include <vector> extern Torch_IValue Torch_ConvertIValueToTorchIValue(torch::IValue value); struct Torch_JITModule { std::shared_ptr<torch::jit::script::Module> module; }; struct Torch_JITModule_Method { torch::jit::script::Method& run; }; Torch_JITModuleContext Torch_CompileTorchScript(char* cstring_script, Torch_Error* error) { HANDLE_TH_ERRORS(Torch_GlobalError); std::string script(cstring_script); auto mod = new Torch_JITModule(); mod->module = torch::jit::compile(script); return (void*)mod; END_HANDLE_TH_ERRORS(Torch_GlobalError, NULL) } Torch_JITModuleContext Torch_LoadJITModule(char* cstring_path, Torch_Error* error) { HANDLE_TH_ERRORS(Torch_GlobalError); std::string module_path(cstring_path); auto mod = new Torch_JITModule(); mod->module = torch::jit::load(module_path); return (void*)mod; END_HANDLE_TH_ERRORS(Torch_GlobalError, NULL) } void Torch_ExportJITModule(Torch_JITModuleContext ctx, char* cstring_path, Torch_Error* error) { HANDLE_TH_ERRORS(Torch_GlobalError); std::string module_path(cstring_path); auto mod = (Torch_JITModule*)ctx; mod->module->save(module_path); END_HANDLE_TH_ERRORS(Torch_GlobalError, ) } Torch_JITModuleMethodContext Torch_JITModuleGetMethod(Torch_JITModuleContext ctx, char* cstring_method, Torch_Error* error) { HANDLE_TH_ERRORS(Torch_GlobalError); std::string method_name(cstring_method); auto mod = (Torch_JITModule*)ctx; auto met = new Torch_JITModule_Method{mod->module->get_method(method_name)}; return (void*)met; END_HANDLE_TH_ERRORS(Torch_GlobalError, NULL) } char** Torch_JITModuleGetMethodNames(Torch_JITModuleContext ctx, size_t* len) { auto mod = (Torch_JITModule*)ctx; auto size = mod->module->get_methods().size(); *len = size; auto result = (char**)malloc(sizeof(char*) * size); int i = 0; for (auto& method : mod->module->get_methods()) { auto key = method.value()->name(); auto ckey = new char[key.length() + 1]; strcpy(ckey, key.c_str()); *(result + i) = ckey; i++; } return result; } Torch_IValue Torch_JITModuleMethodRun(Torch_JITModuleMethodContext ctx, Torch_IValue* inputs, size_t input_size, Torch_Error* error) { HANDLE_TH_ERRORS(Torch_GlobalError); auto met = (Torch_JITModule_Method*)ctx; std::vector<torch::IValue> inputs_vec; for (int i = 0; i < input_size; i++) { auto ival = *(inputs + i); inputs_vec.push_back(Torch_ConvertTorchIValueToIValue(ival)); } auto res = met->run(inputs_vec); return Torch_ConvertIValueToTorchIValue(res); END_HANDLE_TH_ERRORS(Torch_GlobalError, Torch_IValue{}) } Torch_ModuleMethodArgument* Torch_JITModuleMethodArguments(Torch_JITModuleMethodContext ctx, size_t* res_size) { auto met = (Torch_JITModule_Method*)ctx; auto schema = met->run.getSchema(); auto arguments = schema.arguments(); auto result = (Torch_ModuleMethodArgument*)malloc(sizeof(Torch_ModuleMethodArgument) * arguments.size()); *res_size = arguments.size(); for (std::vector<torch::Argument>::size_type i = 0; i != arguments.size(); i++) { auto name = arguments[i].name(); char* cstr_name = new char[name.length() + 1]; strcpy(cstr_name, name.c_str()); auto type = arguments[i].type()->str(); char* cstr_type = new char[type.length() + 1]; strcpy(cstr_type, type.c_str()); *(result + i) = Torch_ModuleMethodArgument{ .name = cstr_name, .typ = cstr_type, }; } return result; } Torch_ModuleMethodArgument* Torch_JITModuleMethodReturns(Torch_JITModuleMethodContext ctx, size_t* res_size) { auto met = (Torch_JITModule_Method*)ctx; auto schema = met->run.getSchema(); auto arguments = schema.returns(); auto result = (Torch_ModuleMethodArgument*)malloc(sizeof(Torch_ModuleMethodArgument) * arguments.size()); *res_size = arguments.size(); for (std::vector<torch::Argument>::size_type i = 0; i != arguments.size(); i++) { auto name = arguments[i].name(); char* cstr_name = new char[name.length() + 1]; strcpy(cstr_name, name.c_str()); auto type = arguments[i].type()->str(); char* cstr_type = new char[type.length() + 1]; strcpy(cstr_type, type.c_str()); *(result + i) = Torch_ModuleMethodArgument{ .name = cstr_name, .typ = cstr_type, }; } return result; } void Torch_DeleteJITModuleMethod(Torch_JITModuleMethodContext ctx) { auto med = (Torch_JITModule_Method*)ctx; delete med; } void Torch_DeleteJITModule(Torch_JITModuleContext ctx) { auto mod = (Torch_JITModule*)ctx; delete mod; } #endif // ENABLE_PYTROCH_JIT
29.539394
112
0.708863
c3sr
68eeb54c52b1f098da02acc840a138117e18e72c
2,191
cpp
C++
src/stereo_ugv/image_source.cpp
yunhao-qian/stereo_ugv
23480a8b93918fc2bc44e16416ac0b4e0598788b
[ "BSD-2-Clause" ]
null
null
null
src/stereo_ugv/image_source.cpp
yunhao-qian/stereo_ugv
23480a8b93918fc2bc44e16416ac0b4e0598788b
[ "BSD-2-Clause" ]
null
null
null
src/stereo_ugv/image_source.cpp
yunhao-qian/stereo_ugv
23480a8b93918fc2bc44e16416ac0b4e0598788b
[ "BSD-2-Clause" ]
null
null
null
#include "stereo_ugv/image_source.h" namespace stereo_ugv { /** * @brief Creates an ImageSource. * @details The function determines the concrete subclass of the layout to be created by looking up the "type" key, and * calls the corresponding initialization function. Currently, "camera", "images" and "video" are supported. * @param context The context containing initialization parameters. * @return A unique pointer to the created image source. */ std::unique_ptr<ImageSource> ImageSource::create(const Context& context) { nlohmann::json internal_json; const auto internal_context{ openInternalContext(&internal_json, context) }; std::string type; internal_context.getParameter("type", &type); if (type == "camera") { auto source{ std::make_unique<CvVideoCaptureImageSource<CvVideoCaptureType::CAMERA>>() }; initialize(source.get(), internal_context); return source; } if (type == "images") { auto source{ std::make_unique<CvVideoCaptureImageSource<CvVideoCaptureType::IMAGES>>() }; initialize(source.get(), internal_context); return source; } if (type == "video") { auto source{ std::make_unique<CvVideoCaptureImageSource<CvVideoCaptureType::VIDEO>>() }; initialize(source.get(), internal_context); return source; } throw InvalidParameter{ fmt::format(R"(Unknown ImageSource type "{}")", type) }; } /** * @brief Finds the character device file of a camera device given the prefix of its device name. * @warning This function has not been implemented, and calling it will always cause a RuntimeError. * @param device_name_prefix The prefix of its device name. Due to the limits of the V4L2 API, device names longer than * 31 characters are truncated. Therefore, the length of the given prefix should not be longer than 31 characters. * Otherwise, no matching camera can be found. * @return The full path to the character device file. If multiple matching cameras are detected, the function issues a * warning and returns any one among them. */ std::string findCameraCharacterDeviceFile(const std::string&) { throw RuntimeError{ "This function has not been implemented" }; } } // namespace stereo_ugv
37.135593
119
0.740758
yunhao-qian
68f10e810d3722fa4aaf268cea3e77e0684a346c
2,325
cpp
C++
foedus_code/foedus-core/src/foedus/storage/sequential/sequential_partitioner_impl.cpp
sam1016yu/cicada-exp-sigmod2017
64e582370076b2923d37b279d1c32730babc15f8
[ "Apache-2.0" ]
null
null
null
foedus_code/foedus-core/src/foedus/storage/sequential/sequential_partitioner_impl.cpp
sam1016yu/cicada-exp-sigmod2017
64e582370076b2923d37b279d1c32730babc15f8
[ "Apache-2.0" ]
null
null
null
foedus_code/foedus-core/src/foedus/storage/sequential/sequential_partitioner_impl.cpp
sam1016yu/cicada-exp-sigmod2017
64e582370076b2923d37b279d1c32730babc15f8
[ "Apache-2.0" ]
null
null
null
/* * Copyright (c) 2014-2015, Hewlett-Packard Development Company, LP. * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 2 of the License, or (at your option) * any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. You should have received a copy of the GNU General Public * License along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * HP designates this particular file as subject to the "Classpath" exception * as provided by HP in the LICENSE.txt file that accompanied this code. */ #include "foedus/storage/sequential/sequential_partitioner_impl.hpp" #include <cstring> #include <ostream> namespace foedus { namespace storage { namespace sequential { SequentialPartitioner::SequentialPartitioner(Partitioner* parent) : engine_(parent->get_engine()), id_(parent->get_storage_id()), metadata_(PartitionerMetadata::get_metadata(engine_, id_)) { } ErrorStack SequentialPartitioner::design_partition( const Partitioner::DesignPartitionArguments& /*args*/) { // no data required for SequentialPartitioner metadata_->data_offset_ = 0; metadata_->data_size_ = 0; metadata_->valid_ = true; return kRetOk; } void SequentialPartitioner::partition_batch( const Partitioner::PartitionBatchArguments& args) const { // all local for (uint32_t i = 0; i < args.logs_count_; ++i) { args.results_[i] = args.local_partition_; } } void SequentialPartitioner::sort_batch(const Partitioner::SortBatchArguments& args) const { // no sorting needed. std::memcpy( args.output_buffer_, args.log_positions_, sizeof(snapshot::BufferPosition) * args.logs_count_); *args.written_count_ = args.logs_count_; } std::ostream& operator<<(std::ostream& o, const SequentialPartitioner& /*v*/) { o << "<SequentialPartitioner>" << "</SequentialPartitioner>"; return o; } } // namespace sequential } // namespace storage } // namespace foedus
33.695652
91
0.744946
sam1016yu
190387dff2ca8b91b790b2a534eec90c398aa606
3,683
hpp
C++
PhantomEngine/Common/Value.hpp
restary/Phantom
1d34afc3da9aa2bf58e68beefd4f4351ecc1a01c
[ "MIT" ]
null
null
null
PhantomEngine/Common/Value.hpp
restary/Phantom
1d34afc3da9aa2bf58e68beefd4f4351ecc1a01c
[ "MIT" ]
null
null
null
PhantomEngine/Common/Value.hpp
restary/Phantom
1d34afc3da9aa2bf58e68beefd4f4351ecc1a01c
[ "MIT" ]
null
null
null
#pragma once #include <iostream> #include <string> #include <Define.hpp> using namespace std; namespace PhantomEngine { namespace DataTypes { static const uint8_t UNDEFINED = 255; static const uint8_t INTEGER = 0; static const uint8_t FLOAT = 1; static const uint8_t VECTOR2 = 2; static const uint8_t VECTOR3 = 3; static const uint8_t SHORT_STRING = 4; static const uint8_t STRING = 5; static const uint8_t OBJECT = 6; static const uint8_t ARRAY = 7; union DataPointer { void* pointer; uint32_t offset; }; struct Integer { int64_t value; uint8_t reserved[7]; uint8_t type; }; struct Float { float value; uint8_t reserved[11]; uint8_t type; }; struct Vector2 { float x; float y; uint8_t reserved[7]; uint8_t type; }; struct Vector3 { float x; float y; float z; uint8_t reserved[3]; uint8_t type; }; struct ShortString { const static uint32_t MAX_SIZE = 14; char content[MAX_SIZE]; uint8_t length; uint8_t type; }; struct String { DataPointer data; uint32_t size; uint8_t reserved[3]; uint8_t type; }; struct Object { DataPointer data; uint32_t size; uint8_t reserved[3]; uint8_t type; }; struct Array { DataPointer data; uint32_t size; uint8_t reserved[3]; uint8_t type; }; union Data { Integer integer; Float number; Vector2 vector2; Vector3 vector3; ShortString shortString; String string; Object object; Array array; void operator=(int i) { integer.type = INTEGER; integer.value = i; } void operator=(float f) { number.type = FLOAT; number.value = f; } void operator=(Vector2 v2) { vector2 = v2; } void operator=(Vector3 v3) { vector3 = v3; } void operator=(std::string s); uint8_t GetType() { return integer.type; } bool IsReference() { return integer.type > SHORT_STRING; } }; } template<typename T> struct Value { uint8_t GetType() { return DataTypes::UNDEFINED; } }; template<> struct Value<int> { Value() { data = 0; } uint8_t GetType() { return DataTypes::INTEGER; } void operator=(int i) { data = i; } private: DataTypes::Data data; }; template<> struct Value<float> { Value() { data = 0.0f; } uint8_t GetType() { return DataTypes::FLOAT; } void operator=(float f) { data = f; } private: DataTypes::Data data; }; template<> struct Value<string> { Value() { data = ""; } uint8_t GetType() { return DataTypes::FLOAT; } void operator=(string s) { data = s; } private: DataTypes::Data data; }; template<typename T> struct Field { Value<string> name; Value<T> value; Field(std::string fieldName); }; }
23.01875
80
0.472984
restary
1903fb7b9a2da957750f0a1fd043519c6fc9c0b3
8,239
cpp
C++
src/StockExchange/StockExchange.cpp
SABCEMM/SABCEMM
a87ea83b57a8a7d16591abe30e56db459e710a0e
[ "BSD-3-Clause" ]
17
2018-01-08T13:38:28.000Z
2022-01-21T05:39:26.000Z
src/StockExchange/StockExchange.cpp
SABCEMM/SABCEMM
a87ea83b57a8a7d16591abe30e56db459e710a0e
[ "BSD-3-Clause" ]
null
null
null
src/StockExchange/StockExchange.cpp
SABCEMM/SABCEMM
a87ea83b57a8a7d16591abe30e56db459e710a0e
[ "BSD-3-Clause" ]
1
2018-01-08T13:39:00.000Z
2018-01-08T13:39:00.000Z
/* Copyright 2017 - BSD-3-Clause * * Copyright Holder (alphabetical): * * Beikirch, Maximilian * Cramer, Simon * Frank, Martin * Otte, Philipp * Pabich, Emma * Trimborn, Torsten * * * 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. */ /* * @author Beikirch, Cramer, Pabich * @date 08 Nov 2017 * @brief This file belongs to the SABCEMM projekt. See github.com/SABCEMM/SABCEMM */ #include <cassert> #include <vector> #include "StockExchange.h" #include <cstddef> //for std::size_t #include <algorithm> #include <random> #include <boost/core/ignore_unused.hpp> #include <limits> #include "../DataCollector/DataCollector.h" /** Setter method for the DataCollector composite * \param newDataCollector Pointer to the new DataCollector composite */ void StockExchange::setDataCollector(DataCollector* newDataCollector) { dataCollector = newDataCollector; } /** Setter method for the agents vector * \param newAgents Pointer to the new vector of agents. */ void StockExchange::setAgents(std::vector<Agent*>* newAgents){ agents = newAgents; setNumAgents(); } /** Setter method for the RandomGenerator * \param newRandomGenerator Pointer to a RandomGenerator */ void StockExchange::setRandomGenerator(RandomGenerator* newRandomGenerator) { randomGenerator = newRandomGenerator; } /** Setter method for the PriceCalculator * \param newPriceCalculator Pointer to the PriceCalculator */ void StockExchange::setPriceCalculator(PriceCalculator* newPriceCalculator) { priceCalculator = newPriceCalculator; } /** Setter method for the ExcessDemandCalculator * \param newExcessDemandCalculator Pointer to the ExcessDemandCalculator */ void StockExchange::setExcessDemandCalculator(ExcessDemandCalculator* newExcessDemandCalculator) { excessDemandCalculator = newExcessDemandCalculator; } /** Setter method for the number of agents. The number is not taken as a paramter but from the array of agents. */ void StockExchange::setNumAgents() { if (agents!=nullptr){ numAgents = agents->size(); }else{ numAgents = 0; } } /** StandardConstructor of the StockExchange */ StockExchange::StockExchange(): StockExchange(nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr) { } /** Constructor of the StockExchange. * \param newDataCollector Pointer to a DataCollector composite * \param newAgents Pointer to a vector of agents * \param newRandomGenerator Pointer to a RandomGenerator * \param newPriceCalculator Pointer to a PriceCalculator * \param newExcessDemandCalculator Pointer to an ExcessDemandCalculator */ StockExchange::StockExchange(DataCollector* newDataCollector, std::vector<Agent*>* newAgents, RandomGenerator* newRandomGenerator, PriceCalculator* newPriceCalculator, ExcessDemandCalculator* newExcessDemandCalculator, ShareCalculator* newShareCalculator, Dividend* newDividend, GlobalNews* newGlobalNews){ numAgents = 0; agents = newAgents; dataCollector = newDataCollector; randomGenerator = newRandomGenerator; priceCalculator = newPriceCalculator; excessDemandCalculator = newExcessDemandCalculator; shareCalculator = newShareCalculator; dividend = newDividend; setNumAgents(); agentIndex.clear(); globalNews = newGlobalNews; } /** Destructor */ StockExchange::~StockExchange() = default; /** Check if the object is fully configured and ready to be used. */ void StockExchange::checkInitilisation() { assert(agents != nullptr); assert(dataCollector != nullptr); assert(randomGenerator != nullptr); assert(priceCalculator != nullptr); assert(excessDemandCalculator != nullptr); assert(numAgents == agents->size()); } void StockExchange::setDividend(Dividend* newDividend){ assert(newDividend != nullptr); dividend = newDividend; } /** Setter method for the GlobalNews container * \param newGlobalNews Pointer to a GlobalNews container */ void StockExchange::setGlobalNews(GlobalNews* newGlobalNews){ this->globalNews = newGlobalNews; } /** PreStep: Execute all calls that are required before a new update of the price and the agents can be triggered. * Generates new GlobalNews. */ void StockExchange::preStep() { assert(priceCalculator != nullptr); if(globalNews!=nullptr){ globalNews->generateNewGlobalNews(); } if(dividend!= nullptr){ dividend->calculateDividend(); } if(excessDemandCalculator != nullptr) excessDemandCalculator->preStepCalculate(); priceCalculator->preStepCalculate(); for (auto &agent : *agents) { agent->preStepUpdate(); } } /** Step: Calculate a new Price and update all agents. * The agents are updated in a random order. */ void StockExchange::step(){ assert(agents!=nullptr); assert(priceCalculator!=nullptr); assert(randomGenerator != nullptr); //Random over all Agents priceCalculator->stepCalculate(); if(agentIndex.size() != agents->size()){ agentIndex.clear(); for(std::size_t j=0;j<agents->size();j++) { agentIndex.push_back(j); } } // shuffling needs to be coupled to the RNG to ensure reproducability for // equal seeds. int seed=0; randomGenerator->getUniformRandomInt(0, std::numeric_limits<int>::max(), &seed); std::mt19937 g(static_cast<unsigned int>(seed)); std::shuffle(agentIndex.begin(),agentIndex.end(),g); for(std::size_t j=0;j<agents->size();j++) { agents->at(agentIndex[j])->stepUpdate(); } } /** PostStep. * Calls the DataCollector. */ void StockExchange::postStep(){ // ED-postInfo (the correction terms for the price) must be available // before price correction. /// @todo this, however, is not general. Can we specify a rule that will /// likely hold for future models? if(excessDemandCalculator != nullptr) excessDemandCalculator->postStepCalculate(); priceCalculator->postStepCalculate(); for (auto &agent : *agents) { agent->postStepUpdate(); } if(shareCalculator != nullptr) shareCalculator->updateShares(); dataCollector->collect(); } StockExchange* StockExchange::factory() { return new StockExchange(); } StockExchange* StockExchange::factory(DataCollector* newDataCollector, std::vector<Agent*>* newAgents, RandomGenerator* newRandomGenerator, PriceCalculator* newPriceCalculator, ExcessDemandCalculator* newExcessDemandCalculator, ShareCalculator* newShareCalculator, Dividend* newDividend, GlobalNews* newGlobalNews) { return new StockExchange(newDataCollector, newAgents, newRandomGenerator, newPriceCalculator, newExcessDemandCalculator, newShareCalculator, newDividend, newGlobalNews); }
28.908772
125
0.73237
SABCEMM
1905c4166233cc8b835b80f27c0aa834ce68fb80
933
cpp
C++
src/world/abilities/blink.cpp
louiz/batajelo
4d8edce8da9d3b17dbad68eb4881d7f6fee2f76e
[ "BSL-1.0", "BSD-2-Clause", "Zlib", "MIT" ]
7
2015-01-28T09:17:08.000Z
2020-04-21T13:51:16.000Z
src/world/abilities/blink.cpp
louiz/batajelo
4d8edce8da9d3b17dbad68eb4881d7f6fee2f76e
[ "BSL-1.0", "BSD-2-Clause", "Zlib", "MIT" ]
null
null
null
src/world/abilities/blink.cpp
louiz/batajelo
4d8edce8da9d3b17dbad68eb4881d7f6fee2f76e
[ "BSL-1.0", "BSD-2-Clause", "Zlib", "MIT" ]
1
2020-07-11T09:20:25.000Z
2020-07-11T09:20:25.000Z
#include <world/abilities/blink.hpp> #include <world/works/blink_work.hpp> #include <world/entity.hpp> #include <logging/logging.hpp> #include <memory> using namespace std::chrono_literals; template<> const std::string NamedAbility<Blink>::name = "Blink"; template<> const AbilityType NamedAbility<Blink>::ability_type = AbilityType::Blink; Blink::Blink(): ActiveAbility(TargetType::Point) { log_debug("Creating a blink instance"); this->cooldown.set_max(0s); log_debug(this->cooldown.get_max_in_ticks()); } void Blink::cast(Entity* entity, World* world, const Position& position, const bool queue) { // Check mana, cooldown etc etc log_debug("CASTING blink for entity" << entity->get_id() << " to pos " << position); auto work = std::make_unique<BlinkWork>(world, entity, position); if (queue) entity->queue_work(std::move(work)); else entity->set_work(std::move(work)); this->cooldown.start(); }
25.916667
90
0.719185
louiz
19061669c719a818d8563f9c8f75664fb79d9bf7
1,004
hpp
C++
tests/messaging/sock/networkcommon.hpp
arntanguy/libqi
7f3e1394cb26126b26fa7ff54d2de1371a1c9f96
[ "BSD-3-Clause" ]
61
2015-01-08T08:05:28.000Z
2022-01-07T16:47:47.000Z
tests/messaging/sock/networkcommon.hpp
arntanguy/libqi
7f3e1394cb26126b26fa7ff54d2de1371a1c9f96
[ "BSD-3-Clause" ]
30
2015-04-06T21:41:18.000Z
2021-08-18T13:24:51.000Z
tests/messaging/sock/networkcommon.hpp
arntanguy/libqi
7f3e1394cb26126b26fa7ff54d2de1371a1c9f96
[ "BSD-3-Clause" ]
64
2015-02-23T20:01:11.000Z
2022-03-14T13:31:20.000Z
#pragma once #ifndef _QI_TESTS_MESSAGING_NETWORKCOMMON_HPP #define _QI_TESTS_MESSAGING_NETWORKCOMMON_HPP #include <algorithm> #include <random> #include <boost/lexical_cast.hpp> /// @file /// Contains functions and types used by socket tests. /// Precondition: With p = reinterpret_cast<unsigned char*>(t), /// writable_counted_range(p, sizeof(T)) template<typename T> void overwrite(T* t) { auto p = reinterpret_cast<unsigned char*>(t); std::fill(p, p + sizeof(T), '\xFF'); } /// Expects a string with the format: /// error_code: error_message /// where error_code is an integer. inline int code(const std::string& s) { std::string c{begin(s), std::find(begin(s), end(s), ':')}; return boost::lexical_cast<int>(c); } // Distribution D, Generator G, BasicLockable L template<typename D, typename G, typename L> auto syncRand(D& dist, G& gen, L& lockable) -> decltype(dist(gen)) { std::lock_guard<L> lock{lockable}; return dist(gen); } #endif // _QI_TESTS_MESSAGING_NETWORKCOMMON_HPP
26.421053
66
0.718127
arntanguy
1907555a950fd68d43b118706ee986f0fe711c7a
3,089
cpp
C++
worker/callback_runner_test.cpp
tkwong/parameter_server
ef8424f341f3b4c4e1088b72d88930fac8b78daf
[ "Apache-2.0" ]
null
null
null
worker/callback_runner_test.cpp
tkwong/parameter_server
ef8424f341f3b4c4e1088b72d88930fac8b78daf
[ "Apache-2.0" ]
null
null
null
worker/callback_runner_test.cpp
tkwong/parameter_server
ef8424f341f3b4c4e1088b72d88930fac8b78daf
[ "Apache-2.0" ]
null
null
null
#include "glog/logging.h" #include "gtest/gtest.h" #include "worker/callback_runner.cpp" namespace csci5570 { class TestCallbackRunner: public testing::Test { protected: void SetUp() {} void TearDown() {} }; // class TestCallbackRunner TEST_F(TestCallbackRunner, Init) { CallbackRunner runner; } TEST_F(TestCallbackRunner, AddResponse) { CallbackRunner runner; std::map<Key,float> reply; bool finished = false; runner.RegisterRecvHandle(0, 0,[&reply](Message& msg){ auto re_keys = third_party::SArray<Key>(msg.data[0]); auto re_vals = third_party::SArray<float>(msg.data[1]); for (int i=0; i<re_keys.size(); i++) reply.insert(std::make_pair(re_keys[i], re_vals[i])); }); runner.RegisterRecvFinishHandle(0, 0, [&finished]{finished=true;}); runner.NewRequest(0, 0, 2); Message r1, r2; third_party::SArray<Key> r1_keys{3}; third_party::SArray<float> r1_vals{0.1}; r1.AddData(r1_keys); r1.AddData(r1_vals); third_party::SArray<Key> r2_keys{4, 5, 6}; third_party::SArray<float> r2_vals{0.4, 0.2, 0.3}; r2.AddData(r2_keys); r2.AddData(r2_vals); runner.AddResponse(0, 0, r1); runner.AddResponse(0, 0, r2); runner.WaitRequest(0, 0); EXPECT_EQ(reply.size(), 4); std::map<Key, float> expected { {3, 0.1}, {4, 0.4}, {5, 0.2}, {6, 0.3} }; EXPECT_EQ(reply, expected); EXPECT_EQ(finished, true); } TEST_F(TestCallbackRunner, AddResponseTwoWorkers) { CallbackRunner runner; std::map<Key,float> reply; float sum = 0; // Register for first worker runner.RegisterRecvHandle(0, 0,[&reply](Message& msg){ auto re_keys = third_party::SArray<Key>(msg.data[0]); auto re_vals = third_party::SArray<float>(msg.data[1]); for (int i=0; i<re_keys.size(); i++) reply.insert(std::make_pair(re_keys[i], re_vals[i])); }); runner.RegisterRecvFinishHandle(0, 0, []{}); runner.NewRequest(0, 0, 2); // Register for second worker runner.RegisterRecvHandle(1, 0,[&sum](Message& msg){ auto re_vals = third_party::SArray<float>(msg.data[1]); for (int i=0; i<re_vals.size(); i++) sum += re_vals[i]; }); runner.RegisterRecvFinishHandle(1, 0, []{}); runner.NewRequest(1, 0, 2); // Respond to both worker Message r1, r2; third_party::SArray<Key> r1_keys{3}; third_party::SArray<float> r1_vals{0.1}; r1.AddData(r1_keys); r1.AddData(r1_vals); third_party::SArray<Key> r2_keys{4, 5, 6}; third_party::SArray<float> r2_vals{0.4, 0.2, 0.3}; r2.AddData(r2_keys); r2.AddData(r2_vals); runner.AddResponse(0, 0, r1); runner.AddResponse(0, 0, r2); runner.AddResponse(1, 0, r1); runner.AddResponse(1, 0, r2); runner.WaitRequest(0, 0); EXPECT_EQ(reply.size(), 4); std::map<Key, float> expected { {3, 0.1}, {4, 0.4}, {5, 0.2}, {6, 0.3} }; EXPECT_EQ(reply, expected); runner.WaitRequest(1, 0); EXPECT_EQ(sum, 1.0); } } // namespace csci5570
27.336283
98
0.616381
tkwong
191a6c446228ac19142afb92a40c92586a351358
1,350
cpp
C++
src/plugins/blasq/plugins/rappor/rappor.cpp
Maledictus/leechcraft
79ec64824de11780b8e8bdfd5d8a2f3514158b12
[ "BSL-1.0" ]
120
2015-01-22T14:10:39.000Z
2021-11-25T12:57:16.000Z
src/plugins/blasq/plugins/rappor/rappor.cpp
Maledictus/leechcraft
79ec64824de11780b8e8bdfd5d8a2f3514158b12
[ "BSL-1.0" ]
8
2015-02-07T19:38:19.000Z
2017-11-30T20:18:28.000Z
src/plugins/blasq/plugins/rappor/rappor.cpp
Maledictus/leechcraft
79ec64824de11780b8e8bdfd5d8a2f3514158b12
[ "BSL-1.0" ]
33
2015-02-07T16:59:55.000Z
2021-10-12T00:36:40.000Z
/********************************************************************** * LeechCraft - modular cross-platform feature rich internet client. * Copyright (C) 2006-2014 Georg Rudoy * * Distributed under the Boost Software License, Version 1.0. * (See accompanying file LICENSE or copy at https://www.boost.org/LICENSE_1_0.txt) **********************************************************************/ #include "rappor.h" #include <QIcon> #include <util/util.h> #include "vkservice.h" namespace LC { namespace Blasq { namespace Rappor { void Plugin::Init (ICoreProxy_ptr proxy) { Util::InstallTranslator ("blasq_rappor"); Service_ = new VkService (proxy); } void Plugin::SecondInit () { } QByteArray Plugin::GetUniqueID () const { return "org.LeechCraft.Blasq.Rappor"; } void Plugin::Release () { } QString Plugin::GetName () const { return "Blasq Rappor"; } QString Plugin::GetInfo () const { return tr ("VKontakte support module for Blasq."); } QIcon Plugin::GetIcon () const { return QIcon (); } QSet<QByteArray> Plugin::GetPluginClasses () const { QSet<QByteArray> result; result << "org.LeechCraft.Blasq.ServicePlugin"; return result; } QList<IService*> Plugin::GetServices () const { return { Service_ }; } } } } LC_EXPORT_PLUGIN (leechcraft_blasq_rappor, LC::Blasq::Rappor::Plugin);
19.014085
83
0.622222
Maledictus
191a7076b71459404f6bfe86cc3f97fd5cd82611
4,088
cpp
C++
src/optimizer/ind_var.cpp
kylinsoft/test
2af1e8d0a05000119d4d7fdd4c5c9e8839442c52
[ "MIT" ]
null
null
null
src/optimizer/ind_var.cpp
kylinsoft/test
2af1e8d0a05000119d4d7fdd4c5c9e8839442c52
[ "MIT" ]
null
null
null
src/optimizer/ind_var.cpp
kylinsoft/test
2af1e8d0a05000119d4d7fdd4c5c9e8839442c52
[ "MIT" ]
null
null
null
#include "pass.hpp" void ind_var_discovery(NormalFunc *f) { // TODO: debug dbg << "## ind var discovery: " << f->name << "\n"; auto S = build_dom_tree(f); auto defs = build_defs(f); auto i2bb = build_in2bb(f); std::unordered_set<Reg> la; std::unordered_map<Reg, Reg> mp_reg; dom_tree_dfs(S, [&](BB *w) { w->for_each([&](Instr *i) { Case(LoadAddr, i0, i) { la.insert(i0->d1); } else Case(BinaryOpInstr, i0, i) { if (la.count(i0->s1) || la.count(i0->s2)) la.insert(i0->d1); } }); }); dom_tree_dfs(S, [&](BB *w) { auto &sw = S[w]; if (sw.loop_rt) { auto get_BB = [&](Reg r) { return i2bb[defs[r]]; }; auto is_c = [&](Reg r) { return r.id && S[get_BB(r)].sdom(sw); }; std::unordered_map<Reg, IndVarInfo> indvar; for (auto it = w->instrs.begin(); it != w->instrs.end(); ++it) { Instr *i = it->get(); Case(PhiInstr, phi, i) { if (phi->uses.size() != 2) continue; auto u1 = phi->uses[0]; auto u2 = phi->uses[1]; if (!is_c(u1.first)) std::swap(u1, u2); if (!is_c(u1.first)) continue; Case(BinaryOpInstr, bop, defs[u2.first]) { auto op = bop->op.type; if (op == BinaryOp::ADD || op == BinaryOp::SUB) if (bop->s1 == phi->d1 && is_c(bop->s2)) { // phi.d1 = u1.first + k * bop.s2 auto &s = indvar[phi->d1]; s.base = u1.first; s.step = bop->s2; s.op = op; BB *bb1 = get_BB(s.base); BB *bb2 = get_BB(s.step); s.bb = S[bb1].dom(S[bb2]) ? bb2 : bb1; auto &iv2 = s; dbg << "basic ind var " << f->get_name(iv2.base) << "," << f->get_name(iv2.step) << " : " << f->get_name(bop->d1) << "\n"; } } } else Case(BinaryOpInstr, bop, i) { if (bop->op.type == BinaryOp::MUL || bop->op.type == BinaryOp::ADD) { auto ind = bop->s1, step = bop->s2; if (!(indvar.count(ind) && is_c(step))) std::swap(ind, step); if (!(indvar.count(ind) && is_c(step))) continue; if (bop->op.type == BinaryOp::ADD) { // only rewrite as indvar for array index compute if (!la.count(bop->s1) && !la.count(bop->s2)) continue; } auto &iv1 = indvar[ind]; auto &iv2 = indvar[bop->d1]; iv2.base = f->new_Reg(); iv2.op = iv1.op; Reg base1 = f->new_Reg(); Reg base2 = f->new_Reg(); mp_reg[bop->d1] = base1; BB *bb = iv2.bb = iv1.bb; if (bop->op.type == BinaryOp::MUL) { iv2.step = f->new_Reg(); iv1.bb->push1( new BinaryOpInstr(iv2.base, iv1.base, step, BinaryOp::MUL)); // base = base0 * step iv1.bb->push1( new BinaryOpInstr(iv2.step, iv1.step, step, BinaryOp::MUL)); // step = step0 * step } else { iv2.step = iv1.step; iv1.bb->push1( new BinaryOpInstr(iv2.base, iv1.base, step, BinaryOp::ADD)); // base = base0 + step } dbg << "ind var " << f->get_name(iv2.base) << "," << f->get_name(iv2.step) << " : " << f->get_name(base1) << "," << f->get_name(base2) << "\n"; PhiInstr *phi = new PhiInstr(base1); w->push_front(phi); for (BB *u : sw.in) { phi->add_use(sw.dom(S[u]) ? base2 : iv2.base, u); } *it = std::unique_ptr<Instr>(new BinaryOpInstr( base2, base1, iv2.step, iv2.op)); // base += step } } } } }); map_use(f, mp_reg); remove_unused_def(f); }
37.163636
80
0.429305
kylinsoft
191cddd5415bab0a4e1557200a8ec1ed88edf626
17,000
cpp
C++
libpvkernel/src/rush/PVFormatVersion.cpp
inendi-inspector/inspector
9b9a00222d8a73cb0817ca56790ee9155db61cc4
[ "MIT" ]
null
null
null
libpvkernel/src/rush/PVFormatVersion.cpp
inendi-inspector/inspector
9b9a00222d8a73cb0817ca56790ee9155db61cc4
[ "MIT" ]
null
null
null
libpvkernel/src/rush/PVFormatVersion.cpp
inendi-inspector/inspector
9b9a00222d8a73cb0817ca56790ee9155db61cc4
[ "MIT" ]
null
null
null
// // MIT License // // © ESI Group, 2015 // // 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 <pvkernel/rush/PVFormatVersion.h> #include <pvkernel/rush/PVFormat_types.h> #include <cassert> #include <QChar> #include <QDomNode> #include <QString> #include <QStringList> // Utility function to convert pre 7 format to 7 format.for mapping/type/plotting static QString const get_type_from_format(QString const& type_attr, QString const& mapped_attr) { if (type_attr == "integer" and mapped_attr == "unsigned") return "number_uint32"; else if (type_attr == "integer" and mapped_attr == "hexadecimal") return "number_uint32"; else if (type_attr == "integer" and mapped_attr == "octal") return "number_uint32"; else if (type_attr == "integer" and mapped_attr == "default") return "number_int32"; else if (type_attr == "host" and mapped_attr == "default") return "string"; else if (type_attr == "enum" and mapped_attr == "default") return "string"; else if (type_attr == "float") return "number_float"; return type_attr; } static QString const get_mapped_from_format(QString const& type_attr, QString const& mapped_attr) { if (type_attr == "integer" and mapped_attr == "unsigned") return "default"; else if (type_attr == "integer" and mapped_attr == "hexadecimal") return "default"; else if (type_attr == "integer" and mapped_attr == "octal") return "default"; else if (type_attr == "integer" and mapped_attr == "default") return "default"; else if (type_attr == "host" and mapped_attr == "default") return "host"; else if (type_attr == "enum" and mapped_attr == "default") return "default"; else if (type_attr == "string" and mapped_attr == "default") return "string"; else if (type_attr == "ipv4" and mapped_attr == "uniform") return "default"; return mapped_attr; } static QString const get_plotted_from_format(QString const& type_attr, QString const& mapped_attr, QString const& plotted_attr) { if (type_attr == "enum") return "enum"; else if (type_attr == "ipv4" and mapped_attr == "uniform") return "enum"; else if (plotted_attr == "minmax") return "default"; return plotted_attr; } QString PVRush::PVFormatVersion::__impl::get_version(QDomDocument const& doc) { return doc.documentElement().attribute("version", "0"); } void PVRush::PVFormatVersion::to_current(QDomDocument& doc) { QString version = __impl::get_version(doc); if (version == "0") { __impl::from0to1(doc); version = "1"; } if (version == "1") { __impl::from1to2(doc); version = "2"; } if (version == "2") { __impl::from2to3(doc); version = "3"; } if (version == "3") { __impl::from3to4(doc); version = "4"; } if (version == "4") { __impl::from4to5(doc); version = "5"; } if (version == "5") { __impl::from5to6(doc); version = "6"; } if (version == "6") { __impl::from6to7(doc); version = "7"; } if (version == "7") { __impl::from7to8(doc); version = "8"; } if (version == "8") { __impl::from8to9(doc); version = "9"; } if (version == "9") { __impl::from9to10(doc); version = "10"; } } void PVRush::PVFormatVersion::__impl::from0to1(QDomDocument& doc) { _rec_0to1(doc.documentElement()); doc.documentElement().setAttribute("version", "1"); } void PVRush::PVFormatVersion::__impl::from1to2(QDomDocument& doc) { _rec_1to2(doc.documentElement()); doc.documentElement().setAttribute("version", "2"); } void PVRush::PVFormatVersion::__impl::from2to3(QDomDocument& doc) { _rec_2to3(doc.documentElement()); doc.documentElement().setAttribute("version", "3"); } void PVRush::PVFormatVersion::__impl::from3to4(QDomDocument& doc) { _rec_3to4(doc.documentElement()); doc.documentElement().setAttribute("version", "4"); } void PVRush::PVFormatVersion::__impl::from4to5(QDomDocument& doc) { _rec_4to5(doc.documentElement()); doc.documentElement().setAttribute("version", "5"); } void PVRush::PVFormatVersion::__impl::from5to6(QDomDocument& doc) { _rec_5to6(doc.documentElement()); doc.documentElement().setAttribute("version", "6"); } void PVRush::PVFormatVersion::__impl::from7to8(QDomDocument& doc) { QDomNodeList splitter = doc.documentElement().elementsByTagName("splitter"); for (int i = 0; i < splitter.size(); i++) { QDomElement ax = splitter.at(i).toElement(); // Update type value QString type = ax.attribute("type"); if (type != "url") { continue; } std::vector<int> pos(10, -1); auto fields = ax.childNodes(); for (int j = 0; j < fields.size(); j++) { QDomElement axis = fields.at(j).namedItem("axis").toElement(); if (axis.isNull()) { // Field without axis is like "no field" in url splitter continue; } QString tag = axis.attribute("tag"); if (tag.contains("protocol")) { pos[j] = 0; } else if (tag.contains("subdomain")) { pos[j] = 1; } else if (tag.contains("host")) { pos[j] = 2; } else if (tag.contains("domain")) { pos[j] = 3; } else if (tag.contains("tld")) { pos[j] = 4; } else if (tag.contains("port")) { pos[j] = 5; } else if (tag.contains("url-variables")) { pos[j] = 7; } else if (tag.contains("url-credentials")) { pos[j] = 9; } else if (tag.contains("url-anchor")) { pos[j] = 8; } else { assert(tag == "url"); // CHeck it at the end to avoid mismatch with variables, cred... pos[j] = 6; } } QDomElement new_splitter = ax.ownerDocument().createElement("splitter"); new_splitter.setAttribute("type", "url"); for (int p : pos) { if (p == -1) { QDomElement new_field = ax.ownerDocument().createElement("field"); new_splitter.appendChild(new_field); } else { new_splitter.appendChild(fields.at(p).cloneNode()); } } splitter.at(i).parentNode().replaceChild(new_splitter, splitter.at(i)); } QDomNodeList axis = doc.documentElement().elementsByTagName("axis"); for (int i = 0; i < axis.size(); i++) { QDomElement ax = axis.at(i).toElement(); ax.removeAttribute("tag"); ax.removeAttribute("key"); ax.removeAttribute("group"); } doc.documentElement().setAttribute("version", "8"); } void PVRush::PVFormatVersion::__impl::from8to9(QDomDocument& doc) { QDomNodeList converters = doc.documentElement().elementsByTagName("converter"); for (int i = 0; i < converters.size(); i++) { QDomElement converter = converters.at(i).toElement(); if (converter.attribute("type") != "substitution") { continue; } converter.setAttribute("modes", 1); converter.setAttribute("substrings_map", ""); converter.setAttribute("invert_order", false); } doc.documentElement().setAttribute("version", "9"); } void PVRush::PVFormatVersion::__impl::from9to10(QDomDocument& doc) { QDomNodeList axis = doc.documentElement().elementsByTagName("axis"); for (int i = 0; i < axis.size(); i++) { QDomElement ax = axis.at(i).toElement(); // Limit the choice of port plotting to uint16 QDomElement plotted = ax.namedItem("plotting").toElement(); QString plotting = plotted.attribute("mode"); if (plotting == "port") { ax.setAttribute("type", "number_uint16"); } } doc.documentElement().setAttribute("version", "10"); } void PVRush::PVFormatVersion::__impl::from6to7(QDomDocument& doc) { QDomNodeList axis = doc.documentElement().elementsByTagName("axis"); for (int i = 0; i < axis.size(); i++) { QDomElement ax = axis.at(i).toElement(); // Update type value QString type = ax.attribute("type"); if (type.isNull()) { type = "string"; } // Update mapping value QDomElement mapped = ax.namedItem("mapping").toElement(); QString mapping = mapped.attribute("mode"); if (mapping.isNull()) { mapping = "default"; } // Update plotting value QDomElement plotted = ax.namedItem("plotting").toElement(); QString plotting = plotted.attribute("mode"); if (plotting.isNull()) { plotting = "default"; } plotted.toElement().setAttribute("mode", get_plotted_from_format(type, mapping, plotting)); mapped.toElement().setAttribute("mode", get_mapped_from_format(type, mapping)); ax.setAttribute("type", get_type_from_format(type, mapping)); // Update type_format if (mapping == "hexadecimal") { ax.toElement().setAttribute("type_format", "%#x"); } else if (mapping == "octal") { ax.toElement().setAttribute("type_format", "%#o"); } // Remove extra mapped node auto mappings = ax.elementsByTagName("mapping"); for (int j = 1; j < mappings.count(); j++) { ax.removeChild(mappings.at(j)); } // Remove extra plotted node auto plottings = ax.elementsByTagName("plotting"); for (int j = 1; j < plottings.count(); j++) { ax.removeChild(plottings.at(j)); } // Remove time-sample attribute ax.removeAttribute("time-sample"); } doc.documentElement().setAttribute("version", "7"); } void PVRush::PVFormatVersion::__impl::_rec_0to1(QDomElement elt) { QString const& tag_name = elt.tagName(); if (tag_name == "RegEx") { elt.setTagName("splitter"); elt.setAttribute("type", "regexp"); elt.setAttribute("regexp", elt.attribute("expression")); elt.removeAttribute("expression"); } else if (tag_name == "url") { elt.setTagName("splitter"); elt.setAttribute("type", "url"); } else if (tag_name == "csv") { elt.setTagName("splitter"); elt.setAttribute("type", "csv"); elt.setAttribute("sep", elt.attribute("delimiter")); elt.removeAttribute("delimiter"); } else if (tag_name == "filter") { if (elt.attribute("type") == "include") { elt.setAttribute("reverse", "0"); } else { elt.setAttribute("reverse", "1"); } elt.setAttribute("type", "regexp"); elt.setAttribute("regexp", elt.attribute("expression")); elt.removeAttribute("expression"); elt.removeAttribute("type"); } QDomNodeList children = elt.childNodes(); for (int i = 0; i < children.size(); i++) { _rec_0to1(children.at(i).toElement()); } } void PVRush::PVFormatVersion::__impl::_rec_1to2(QDomElement elt) { QString const& tag_name = elt.tagName(); static QStringList tags = QStringList() << "protocol" << "domain" << "tld" << "port" << "url" << "url-variables"; static QStringList plottings = QStringList() << "default" << "default" << "default" << "port" << "minmax" << "minmax"; if (tag_name == "splitter") { QString type = elt.attribute("type", ""); if (type == "url") { // Set default axes tags and plottings QDomNodeList children = elt.childNodes(); for (unsigned int i = 0; i < 6; i++) { QDomElement c_elt = children.at(i).toElement(); if (c_elt.tagName() == "field") { // Take the axis QDomElement axis = c_elt.firstChildElement("axis"); // and set the default tag axis.setAttribute("tag", tags[i]); axis.setAttribute("plotting", plottings[i]); } } } else if (type == "regexp") { // Default dehavioru was to match the regular expression somewhere in the line elt.setAttribute("full-line", "false"); } } else if (tag_name == "axis") { bool is_key = elt.attribute("key", "false") == "true"; if (is_key) { QString cur_tag = elt.attribute("tag"); if (!cur_tag.isEmpty()) { cur_tag += QString(QChar(':')) + "key"; } else { cur_tag = "key"; } elt.setAttribute("tag", cur_tag); } elt.removeAttribute("key"); } QDomNodeList children = elt.childNodes(); for (int i = 0; i < children.size(); i++) { _rec_1to2(children.at(i).toElement()); } } void PVRush::PVFormatVersion::__impl::_rec_2to3(QDomElement elt) { QString const& tag_name = elt.tagName(); if (tag_name == "axis") { QString plotting = elt.attribute("plotting", ""); QString type = elt.attribute("type", ""); if (type != "time" && type != "ipv4" && plotting == "minmax") { // minmax is now default. if default was not minmax, it was only relevant for the time // and ipv4 elt.setAttribute("plotting", "default"); } } QDomNodeList children = elt.childNodes(); for (int i = 0; i < children.size(); i++) { _rec_2to3(children.at(i).toElement()); } } void PVRush::PVFormatVersion::__impl::_rec_3to4(QDomNode node) { if (node.isElement()) { QDomElement elt = node.toElement(); if (elt.tagName() == "axis") { QString mapping = elt.attribute("mapping", ""); QString plotting = elt.attribute("plotting", ""); QString type = elt.attribute("type", ""); QDomElement elt_mapping = elt.ownerDocument().createElement(PVFORMAT_XML_TAG_MAPPING); elt_mapping.setAttribute(PVFORMAT_MAP_PLOT_MODE_STR, mapping); if (type == "time") { elt_mapping.setAttribute("time-format", QLatin1String("@PVTimeFormat(") + elt.attribute("time-format", "") + QLatin1String(")")); elt.removeAttribute("time-format"); } elt.appendChild(elt_mapping); QDomElement elt_plotting = elt.ownerDocument().createElement(PVFORMAT_XML_TAG_PLOTTING); elt_plotting.setAttribute(PVFORMAT_MAP_PLOT_MODE_STR, plotting); elt.appendChild(elt_plotting); elt.removeAttribute("mapping"); elt.removeAttribute("plotting"); } } QDomNode child = node.firstChild(); while (!child.isNull()) { _rec_3to4(child); child = child.nextSibling(); } } void PVRush::PVFormatVersion::__impl::_rec_4to5(QDomNode node) { if (node.isElement()) { QDomElement elt = node.toElement(); if (elt.tagName() == "mapping") { QString tf = elt.attribute("time-format", QString()); if (tf.size() > 0 && tf.startsWith("@PVTimeFormat(")) { tf = tf.mid(14, tf.size() - 15); elt.setAttribute("time-format", tf); } QString cl = elt.attribute("convert-lowercase", QString()); if (cl.size() > 0 && cl.startsWith("@Bool(")) { cl = cl.mid(6, cl.size() - 7); elt.setAttribute("convert-lowercase", cl); } } if (elt.tagName() == "splitter") { QString sep = elt.attribute("sep", QString()); if (sep.size() > 0 && sep.startsWith("@Char(")) { sep = sep.mid(6, sep.size() - 7); elt.setAttribute("sep", sep); } } } QDomNode child = node.firstChild(); while (!child.isNull()) { _rec_4to5(child); child = child.nextSibling(); } } void PVRush::PVFormatVersion::__impl::_rec_5to6(QDomNode node) { if (node.isElement()) { QDomElement elt = node.toElement(); if (elt.tagName() == "mapping") { QString tf = elt.attribute("time-format", QString()); if (tf.size() > 0) { QDomElement axis_node = node.parentNode().toElement(); axis_node.setAttribute("type_format", tf); elt.removeAttribute("time-format"); } } else if (elt.tagName() == "axis") { // Move mapping from attribute to node QString mapping = elt.attribute("mapping", QString()); QDomElement mapping_node = node.ownerDocument().createElement("mapping"); mapping_node.setAttribute("mode", mapping); elt.appendChild(mapping_node); elt.removeAttribute("mapping"); // Move plotting from attribute to node QString plotting = elt.attribute("plotting", QString()); QDomElement plotting_node = node.ownerDocument().createElement("plotting"); plotting_node.setAttribute("mode", plotting); elt.appendChild(plotting_node); elt.removeAttribute("plotting"); // Move axis/time-format to axis/mapping/type_format QString tf = elt.attribute("time-format", QString()); if (tf.size() > 0) { QDomElement axis_node = node.toElement(); axis_node.setAttribute("type_format", tf); } elt.removeAttribute("time-format"); } } QDomNode child = node.firstChild(); while (!child.isNull()) { _rec_5to6(child); child = child.nextSibling(); } }
31.25
97
0.644059
inendi-inspector
191fe62fb000c162bdae37ea3e70df3729d30c11
9,164
cpp
C++
src/essence.game/qpang/room/session/player/weapon/PlayerWeaponManager.cpp
hinnie123/qpang-essence-emulator-1
2b99f21bcbcbdcd5ff8104d4845ebc10ec0e6e1b
[ "MIT" ]
1
2021-11-23T00:31:46.000Z
2021-11-23T00:31:46.000Z
src/essence.game/qpang/room/session/player/weapon/PlayerWeaponManager.cpp
hinnie123/qpang-essence-emulator-1
2b99f21bcbcbdcd5ff8104d4845ebc10ec0e6e1b
[ "MIT" ]
null
null
null
src/essence.game/qpang/room/session/player/weapon/PlayerWeaponManager.cpp
hinnie123/qpang-essence-emulator-1
2b99f21bcbcbdcd5ff8104d4845ebc10ec0e6e1b
[ "MIT" ]
1
2021-12-18T12:50:46.000Z
2021-12-18T12:50:46.000Z
#include "PlayerWeaponManager.h" #include "qpang/Game.h" #include "qpang/room/session/RoomSession.h" #include "qpang/room/tnl/net_events/client/cg_weapon.hpp" #include "qpang/room/tnl/net_events/server/gc_weapon.hpp" #include "qpang/room/tnl/net_events/server/gc_respawn.hpp" #include "qpang/room/tnl/net_events/server/gc_game_item.hpp" #include "qpang/room/tnl/net_events/server/gc_essence.hpp" constexpr auto RIFLE_INDEX = 0; PlayerWeaponManager::PlayerWeaponManager() : m_selectedWeaponIndex(0), m_previousSelectedWeaponIndex(0), m_hasEquippedMachineGun(false), m_equippedMachineGunSeqId(0) { } void PlayerWeaponManager::initialize(const std::shared_ptr<RoomSessionPlayer>& player) { m_player = player; auto* equipmentManager = player->getPlayer()->getEquipmentManager(); const auto itemIds = equipmentManager->getWeaponItemIdsByCharacter(player->getCharacter()); const auto isMeleeOnly = player->getRoomSession()->getRoom()->isMeleeOnly(); for (int i = 0; i < itemIds.size(); i++) { const auto weapon = Game::instance()->getWeaponManager()->get(itemIds[i]); if (isMeleeOnly) { // melee weapon if (i == 3) { m_weapons[3] = weapon; } } else { m_weapons[i] = weapon; } auto& [first, second] = m_defaultAmmo[weapon.itemId]; first = weapon.clipCount + equipmentManager->getExtraAmmoForWeaponIndex(i); second = weapon.clipSize; } m_selectedWeaponIndex = 3; } Weapon PlayerWeaponManager::getSelectedWeapon() { return m_weapons[m_selectedWeaponIndex]; } void PlayerWeaponManager::selectTagWeapon() { m_previousSelectedWeaponIndex = m_selectedWeaponIndex; m_selectedWeaponIndex = RIFLE_INDEX; m_currentRifleWeapon = m_weapons[m_selectedWeaponIndex]; const auto chainLightWeapon = Game::instance()->getWeaponManager()->get(WEAPON_PREY_CHAIN_LIGHT); m_weapons[RIFLE_INDEX] = chainLightWeapon; auto& [first, second] = m_defaultAmmo[chainLightWeapon.itemId]; first = chainLightWeapon.clipCount; second = chainLightWeapon.clipSize; refillCurrentWeapon(); switchWeapon(m_weapons[m_selectedWeaponIndex].itemId, false); } void PlayerWeaponManager::deselectTagWeapon() { m_weapons[RIFLE_INDEX] = m_currentRifleWeapon; m_selectedWeaponIndex = m_previousSelectedWeaponIndex; switchWeapon(m_weapons[m_selectedWeaponIndex].itemId, false); reset(); } void PlayerWeaponManager::reset() { const auto player = m_player.lock(); if (player == nullptr) return; // ReSharper disable once CppUseStructuredBinding for (auto& weapon : m_weapons) { const auto [first, second] = m_defaultAmmo[weapon.itemId]; weapon.clipCount = first; weapon.clipSize = second; player->post(new GCGameItem(14, { {1191182337, 1} }, weapon.itemId)); } } void PlayerWeaponManager::reload(const uint32_t seqId) { m_weapons[m_selectedWeaponIndex].clipCount--; m_weapons[m_selectedWeaponIndex].clipSize = m_defaultAmmo[getSelectedWeapon().itemId].second; if (const auto player = m_player.lock(); player != nullptr) player->getRoomSession()->relayPlaying<GCWeapon>(player->getPlayer()->getId(), 3, m_weapons[m_selectedWeaponIndex].itemId, seqId); } void PlayerWeaponManager::shoot(uint32_t entityId) { m_weapons[m_selectedWeaponIndex].clipSize--; } bool PlayerWeaponManager::canReload() { return m_weapons[m_selectedWeaponIndex].clipCount > 0; } bool PlayerWeaponManager::canShoot() { if (isHoldingMelee()) { return true; } return m_weapons[m_selectedWeaponIndex].clipSize > 0; } bool PlayerWeaponManager::hasWeapon(uint32_t weaponId) const { return std::find_if(m_weapons.cbegin(), m_weapons.cend(), [weaponId](const Weapon& weapon) { return weapon.itemId == weaponId; } ) != m_weapons.cend(); } void PlayerWeaponManager::switchWeapon(uint32_t weaponId, bool isReloadGlitchEnabled) { if (!isReloadGlitchEnabled) { if (m_weapons[m_selectedWeaponIndex].itemId == weaponId) { // already chose this weapon return; } } for (size_t i = 0; i < m_weapons.size(); i++) { if (m_weapons[i].itemId == weaponId) { m_selectedWeaponIndex = i; break; } } if (const auto player = m_player.lock(); player != nullptr) { player->getRoomSession()->relayPlaying<GCWeapon>(player->getPlayer()->getId(), 0, m_weapons[m_selectedWeaponIndex].itemId, 0); player->post(new GCWeapon(player->getPlayer()->getId(), 5, m_weapons[m_selectedWeaponIndex].itemId, 0)); } } void PlayerWeaponManager::refillWeapon(const uint32_t weaponId) { const auto [first, second] = m_defaultAmmo[weaponId]; m_weapons[m_selectedWeaponIndex].clipCount = first; m_weapons[m_selectedWeaponIndex].clipSize = second; if (const auto player = m_player.lock(); player != nullptr) { player->post(new GCGameItem( 14, std::vector({ GCGameItem::Item{1191182337, 0x01, 0x00, 0x00, 0x00} }), weaponId )); } } void PlayerWeaponManager::refillCurrentWeapon() { const auto itemId = getSelectedWeapon().itemId; refillWeapon(itemId); } std::array<uint32_t, 4> PlayerWeaponManager::getWeaponIds() { std::array<uint32_t, 4> weaponIds{}; for (size_t i = 0; i < m_weapons.size(); i++) { weaponIds[i] = m_weapons[i].itemId; } return weaponIds; } std::array<Weapon, 4> PlayerWeaponManager::getWeapons() const { return m_weapons; } bool PlayerWeaponManager::hasEquippedMachineGun() const { return m_hasEquippedMachineGun; } uint64_t PlayerWeaponManager::getEquippedMachineGunSeqId() const { return m_equippedMachineGunSeqId; } void PlayerWeaponManager::equipMachineGun(const uint64_t seqId) { // If the player attempts to equip the machine gun whilst already equipping a machine gun, disallow it. if (m_hasEquippedMachineGun) { return; } // Check if the seqId is a valid sequence id. if (seqId < 1 || seqId > 4) { return; } // TODO: Perhaps check if the player is "in range" of the machine gun (by seq id). // TODO: Check if the machine gun with the seq id is already taken by another player. if (const auto player = m_player.lock(); player != nullptr) { if (player->getSkillManager()->hasActiveSkill()) { return; } // Disallow the machine gun in public enemy mode for now. if (player->getRoomSession()->getGameMode()->isPublicEnemyMode()) { player->getPlayer()->broadcast(u"The machine gun is disabled in the public enemy gamemode."); return; } // Let client know the player is shooting with ground zero gun. player->getRoomSession()->relayPlaying<GCWeapon>(player->getPlayer()->getId(), CGWeapon::CMD::EQUIP_MACHINE_GUN, WEAPON_MACHINE_GUN, seqId); // Allow client to shoot. player->getRoomSession()->relayPlaying<GCWeapon>(player->getPlayer()->getId(), CGWeapon::CMD::ENABLE_SHOOTING, WEAPON_MACHINE_GUN, seqId); // Save the currently selected weapon index. m_previousSelectedWeaponIndex = m_selectedWeaponIndex; // Set the currently selected weapon index to gun. m_selectedWeaponIndex = 0; // Set the current gun weapon to the current weapon. m_currentRifleWeapon = m_weapons[m_selectedWeaponIndex]; const auto machineGunWeapon = Game::instance()->getWeaponManager()->get(WEAPON_MACHINE_GUN); m_weapons[0] = machineGunWeapon; auto& [first, second] = m_defaultAmmo[machineGunWeapon.itemId]; first = machineGunWeapon.clipCount; second = machineGunWeapon.clipSize; refillCurrentWeapon(); switchWeapon(machineGunWeapon.itemId, false); m_hasEquippedMachineGun = true; m_equippedMachineGunSeqId = seqId; } } void PlayerWeaponManager::unequipMachineGun() { // If the player does not have a machine gun equipped, do not allow them to unequip one. if (!m_hasEquippedMachineGun) { return; } if (const auto player = m_player.lock(); player != nullptr) { // Disallow the machine gun in public enemy mode for now. if (player->getRoomSession()->getGameMode()->isPublicEnemyMode()) { player->getPlayer()->broadcast(u"The machine gun is disabled in the public enemy gamemode."); return; } player->getRoomSession()->relayPlaying<GCWeapon>(player->getPlayer()->getId(), CGWeapon::CMD::UNEQUIP_MACHINE_GUN, WEAPON_MACHINE_GUN, m_equippedMachineGunSeqId); m_weapons[0] = m_currentRifleWeapon; m_selectedWeaponIndex = m_previousSelectedWeaponIndex; switchWeapon(m_weapons[m_selectedWeaponIndex].itemId, false); m_hasEquippedMachineGun = false; m_equippedMachineGunSeqId = 0; } } void PlayerWeaponManager::equipRainbowSkillCardWeapon(uint32_t weaponId) { m_previousSelectedWeaponIndex = m_selectedWeaponIndex; m_selectedWeaponIndex = RIFLE_INDEX; m_currentRifleWeapon = m_weapons[m_selectedWeaponIndex]; const auto weapon = Game::instance()->getWeaponManager()->get(weaponId); m_weapons[RIFLE_INDEX] = weapon; auto& [first, second] = m_defaultAmmo[weapon.itemId]; first = weapon.clipCount; second = weapon.clipSize; refillCurrentWeapon(); switchWeapon(m_weapons[m_selectedWeaponIndex].itemId, false); } void PlayerWeaponManager::unequipRainbowSkillCardWeapon() { m_weapons[RIFLE_INDEX] = m_currentRifleWeapon; m_selectedWeaponIndex = m_previousSelectedWeaponIndex; switchWeapon(m_weapons[m_selectedWeaponIndex].itemId, false); reset(); } bool PlayerWeaponManager::isHoldingMelee() const { return m_selectedWeaponIndex == 3; }
25.669468
164
0.748691
hinnie123
19202436500c1a6eb406fc35dc9d3f49f8601c6d
6,361
cpp
C++
TDEngine2/source/graphics/animation/CMeshAnimatorComponent.cpp
bnoazx005/TDEngine2
93ebfecf8af791ff5ecd4f57525a6935e34cd05c
[ "Apache-2.0" ]
1
2019-07-15T01:14:15.000Z
2019-07-15T01:14:15.000Z
TDEngine2/source/graphics/animation/CMeshAnimatorComponent.cpp
bnoazx005/TDEngine2
93ebfecf8af791ff5ecd4f57525a6935e34cd05c
[ "Apache-2.0" ]
76
2018-10-27T16:59:36.000Z
2022-03-30T17:40:39.000Z
TDEngine2/source/graphics/animation/CMeshAnimatorComponent.cpp
bnoazx005/TDEngine2
93ebfecf8af791ff5ecd4f57525a6935e34cd05c
[ "Apache-2.0" ]
1
2019-07-29T02:02:08.000Z
2019-07-29T02:02:08.000Z
#include "../../include/graphics/animation/CMeshAnimatorComponent.h" #include <tuple> namespace TDEngine2 { static const std::string ComponentTypeName = "mesh_animator"; const std::string CMeshAnimatorComponent::mPositionJointChannelPattern = "joint_{0}.position"; const std::string CMeshAnimatorComponent::mRotationJointChannelPattern = "joint_{0}.rotation"; const std::string& CMeshAnimatorComponent::GetPositionJointChannelPattern() { return mPositionJointChannelPattern; } const std::string& CMeshAnimatorComponent::GetRotationJointChannelPattern() { return mRotationJointChannelPattern; } const std::string& CMeshAnimatorComponent::GetComponentTypeName() { return ComponentTypeName; } CMeshAnimatorComponent::CMeshAnimatorComponent() : CBaseComponent() { } E_RESULT_CODE CMeshAnimatorComponent::Init() { if (mIsInitialized) { return RC_FAIL; } mIsDirty = true; mIsInitialized = true; return RC_OK; } E_RESULT_CODE CMeshAnimatorComponent::Load(IArchiveReader* pReader) { if (!pReader) { return RC_FAIL; } return RC_OK; } E_RESULT_CODE CMeshAnimatorComponent::Save(IArchiveWriter* pWriter) { if (!pWriter) { return RC_FAIL; } pWriter->BeginGroup("component"); { pWriter->SetUInt32("type_id", static_cast<U32>(CMeshAnimatorComponent::GetTypeId())); } pWriter->EndGroup(); return RC_OK; } void CMeshAnimatorComponent::SetDirtyFlag(bool value) { mIsDirty = value; } bool CMeshAnimatorComponent::IsDirty() const { return mIsDirty; } CMeshAnimatorComponent::TJointsMap& CMeshAnimatorComponent::GetJointsTable() { return mJointsTable; } CMeshAnimatorComponent::TJointPose& CMeshAnimatorComponent::GetCurrAnimationPose() { return mCurrAnimationPose; } const std::vector<TVector3>& CMeshAnimatorComponent::GetJointPositionsArray() const { return mJointsCurrPositions; } const std::vector<TQuaternion>& CMeshAnimatorComponent::GetJointRotationsArray() const { return mJointsCurrRotation; } enum class E_JOINT_PROPERTY_TYPE : U8 { POSITION, ROTATION }; static std::tuple<std::string, E_JOINT_PROPERTY_TYPE> GetJointInfoFromProperty(const std::string& propertyId) { auto p0 = propertyId.find_first_of('_') + 1; auto p1 = propertyId.find_first_of('.'); return { propertyId.substr(p0, p1 - p0), propertyId.substr(p1 + 1) == "position" ? E_JOINT_PROPERTY_TYPE::POSITION : E_JOINT_PROPERTY_TYPE::ROTATION }; } IPropertyWrapperPtr CMeshAnimatorComponent::GetProperty(const std::string& propertyName) { auto&& properties = GetAllProperties(); if (std::find_if(properties.cbegin(), properties.cend(), [&propertyName](const std::string& id) { return propertyName == id; }) == properties.cend()) { return CBaseComponent::GetProperty(propertyName); } std::string jointId; E_JOINT_PROPERTY_TYPE propertyType; std::tie(jointId, propertyType) = GetJointInfoFromProperty(propertyName); switch (propertyType) { case E_JOINT_PROPERTY_TYPE::POSITION: return IPropertyWrapperPtr(CBasePropertyWrapper<TVector3>::Create([this, jointId](const TVector3& pos) { _setPositionForJoint(jointId, pos); return RC_OK; }, nullptr)); case E_JOINT_PROPERTY_TYPE::ROTATION: return IPropertyWrapperPtr(CBasePropertyWrapper<TQuaternion>::Create([this, jointId](const TQuaternion& rot) { _setRotationForJoint(jointId, rot); return RC_OK; }, nullptr)); } return CBaseComponent::GetProperty(propertyName); } const std::vector<std::string>& CMeshAnimatorComponent::GetAllProperties() const { static std::vector<std::string> properties; if (properties.size() / 2 == mJointsTable.size()) { return properties; } properties.clear(); for (auto&& currJointEntity : mJointsTable) { properties.push_back(Wrench::StringUtils::Format(CMeshAnimatorComponent::mPositionJointChannelPattern, currJointEntity.first)); properties.push_back(Wrench::StringUtils::Format(CMeshAnimatorComponent::mRotationJointChannelPattern, currJointEntity.first)); } return properties; } const std::string& CMeshAnimatorComponent::GetTypeName() const { return ComponentTypeName; } void CMeshAnimatorComponent::_setPositionForJoint(const std::string& jointId, const TVector3& position) { auto it = mJointsTable.find(jointId); if (it == mJointsTable.cend()) { TDE2_ASSERT(false); return; } if (static_cast<U32>(mJointsCurrPositions.size()) <= it->second) { mJointsCurrPositions.resize(it->second + 1); } mJointsCurrPositions[it->second] = position; mIsDirty = true; } void CMeshAnimatorComponent::_setRotationForJoint(const std::string& jointId, const TQuaternion& rotation) { auto it = mJointsTable.find(jointId); if (it == mJointsTable.cend()) { TDE2_ASSERT(false); return; } if (static_cast<U32>(mJointsCurrRotation.size()) <= it->second) { mJointsCurrRotation.resize(it->second + 1); } mJointsCurrRotation[it->second] = rotation; mIsDirty = true; } IComponent* CreateMeshAnimatorComponent(E_RESULT_CODE& result) { return CREATE_IMPL(IComponent, CMeshAnimatorComponent, result); } CMeshAnimatorComponentFactory::CMeshAnimatorComponentFactory() : CBaseObject() { } E_RESULT_CODE CMeshAnimatorComponentFactory::Init() { if (mIsInitialized) { return RC_FAIL; } mIsInitialized = true; return RC_OK; } E_RESULT_CODE CMeshAnimatorComponentFactory::Free() { if (!mIsInitialized) { return RC_FAIL; } mIsInitialized = false; delete this; return RC_OK; } IComponent* CMeshAnimatorComponentFactory::Create(const TBaseComponentParameters* pParams) const { if (!pParams) { return nullptr; } const TMeshAnimatorComponentParameters* pAnimatorParams = static_cast<const TMeshAnimatorComponentParameters*>(pParams); E_RESULT_CODE result = RC_OK; return CreateMeshAnimatorComponent(result); } IComponent* CMeshAnimatorComponentFactory::CreateDefault(const TBaseComponentParameters& params) const { E_RESULT_CODE result = RC_OK; return CreateMeshAnimatorComponent(result); } TypeId CMeshAnimatorComponentFactory::GetComponentTypeId() const { return CMeshAnimatorComponent::GetTypeId(); } IComponentFactory* CreateMeshAnimatorComponentFactory(E_RESULT_CODE& result) { return CREATE_IMPL(IComponentFactory, CMeshAnimatorComponentFactory, result); } }
23.047101
178
0.748782
bnoazx005
1921e6547eacf6dd5f124f74def4dd1d03fa4150
1,602
cpp
C++
19A.cpp
felikjunvianto/kfile-codeforces-submissions
1b53da27a294a12063b0912e12ad32efe24af678
[ "MIT" ]
null
null
null
19A.cpp
felikjunvianto/kfile-codeforces-submissions
1b53da27a294a12063b0912e12ad32efe24af678
[ "MIT" ]
null
null
null
19A.cpp
felikjunvianto/kfile-codeforces-submissions
1b53da27a294a12063b0912e12ad32efe24af678
[ "MIT" ]
null
null
null
#include <cstdio> #include <cmath> #include <iostream> #include <string> #include <cstring> #include <algorithm> #include <vector> #include <utility> #include <stack> #include <queue> #include <map> #define fi first #define se second #define pb push_back #define mp make_pair #define pi 2*acos(0.0) #define eps 1e-9 #define PII pair<int,int> #define PDD pair<double,double> #define LL long long #define INF 1000000000 using namespace std; typedef struct{string name;int poin,scored,missed;} team; string tim[111]; char mska[50],mskb[50],dummy; int N,x,ida,idb,a,b; team ans[111]; bool cfscore(team i,team j) { if(i.poin!=j.poin) return(i.poin>j.poin); if(i.scored-i.missed!=j.scored-j.missed) return(i.scored-i.missed>j.scored-j.missed); if(i.scored!=j.scored) return(i.scored>j.scored); return(i.name<j.name); } bool cfname(team i,team j) { return(i.name<j.name); } int main() { scanf("%d",&N); for(x=0;x<N;x++) { scanf("%s",mska); tim[x]=mska; } sort(tim,tim+N); for(x=0;x<N;x++) ans[x]=(team){tim[x],0,0,0}; for(x=1;2*x<=N*(N-1);x++) { getchar(); scanf("%[^-]%c%s %d:%d",mska,&dummy,mskb,&a,&b); ida=lower_bound(tim,tim+N,mska)-tim; idb=lower_bound(tim,tim+N,mskb)-tim; ans[ida].scored+=a,ans[ida].missed+=b; ans[idb].scored+=b,ans[idb].missed+=a; if(a==b) ans[ida].poin++,ans[idb].poin++; else if(a>b) ans[ida].poin+=3; else ans[idb].poin+=3; } sort(ans,ans+N,cfscore); sort(ans,ans+(N/2),cfname); for(x=0;2*x<N;x++) printf("%s\n",ans[x].name.c_str()); return 0; }
20.805195
87
0.615481
felikjunvianto
192792ac79a3b689427d4827807f3490eaf2a12b
1,443
cc
C++
raytracing/geometry.cc
jpanikulam/experiments
be36319a89f8baee54d7fa7618b885edb7025478
[ "MIT" ]
1
2019-04-14T11:40:28.000Z
2019-04-14T11:40:28.000Z
raytracing/geometry.cc
IJDykeman/experiments-1
22badf166b2ea441e953939463f751020b8c251b
[ "MIT" ]
5
2018-04-18T13:54:29.000Z
2019-08-22T20:04:17.000Z
raytracing/geometry.cc
IJDykeman/experiments-1
22badf166b2ea441e953939463f751020b8c251b
[ "MIT" ]
1
2018-12-24T03:45:47.000Z
2018-12-24T03:45:47.000Z
#include "geometry.hh" namespace raytrace { using Vec2 = Eigen::Vector2d; double cross2d(const Vec2 &a, const Vec2 &b) { return (a(0) * b(1)) - (a(1) * b(0)); } bool ray_line_intersection(const Ray &ray, const Line &line, Out<Vec2> intersection) { Eigen::Matrix2d A; A.col(0) = ray.direction; A.col(1) = -line.direction; const Vec2 b = line.point - ray.origin; const Eigen::ColPivHouseholderQR<Eigen::Matrix2d> qr = A.colPivHouseholderQr(); // This takes FOREVER to compile (I guess Eigen inlines the whole operation?) // Lines are parallel if (qr.absDeterminant() < 1e-3) { return false; } const Vec2 soln = qr.solve(b); *intersection = soln(0) * ray.direction + ray.origin; // Ray pointing the wrong direction if (soln(0) < 0.0) { return false; } return true; } bool ray_line_segment_intersection(const Ray &ray, const LineSegment &segment, Out<Vec2> intersection) { const Line temp_line(segment.start, segment.end - segment.start); const bool valid_intersection = ray_line_intersection(ray, temp_line, intersection); if (valid_intersection) { const double half_space_start = (*intersection - segment.start).dot(temp_line.direction); const double half_space_end = (*intersection - segment.end).dot(temp_line.direction); if ((half_space_start > 0.0) && (half_space_end < 0.0)) { return true; } } return false; } }
28.294118
104
0.668053
jpanikulam
192db529428201d58d905a62921de0c632fa449b
1,927
cc
C++
cpp/src/arrow/compute/exec/accumulation_queue.cc
AlvinJ15/arrow
095179f8a38f99e2eb10a59ad7e71252d8491e8f
[ "Apache-2.0" ]
1
2021-11-24T04:43:52.000Z
2021-11-24T04:43:52.000Z
cpp/src/arrow/compute/exec/accumulation_queue.cc
AlvinJ15/arrow
095179f8a38f99e2eb10a59ad7e71252d8491e8f
[ "Apache-2.0" ]
null
null
null
cpp/src/arrow/compute/exec/accumulation_queue.cc
AlvinJ15/arrow
095179f8a38f99e2eb10a59ad7e71252d8491e8f
[ "Apache-2.0" ]
null
null
null
// 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 "arrow/compute/exec/accumulation_queue.h" #include <iterator> namespace arrow { namespace util { using arrow::compute::ExecBatch; AccumulationQueue::AccumulationQueue(AccumulationQueue&& that) { this->batches_ = std::move(that.batches_); this->row_count_ = that.row_count_; that.Clear(); } AccumulationQueue& AccumulationQueue::operator=(AccumulationQueue&& that) { this->batches_ = std::move(that.batches_); this->row_count_ = that.row_count_; that.Clear(); return *this; } void AccumulationQueue::Concatenate(AccumulationQueue&& that) { this->batches_.reserve(this->batches_.size() + that.batches_.size()); std::move(that.batches_.begin(), that.batches_.end(), std::back_inserter(this->batches_)); this->row_count_ += that.row_count_; that.Clear(); } void AccumulationQueue::InsertBatch(ExecBatch batch) { row_count_ += batch.length; batches_.emplace_back(std::move(batch)); } void AccumulationQueue::Clear() { row_count_ = 0; batches_.clear(); } ExecBatch& AccumulationQueue::operator[](size_t i) { return batches_[i]; } } // namespace util } // namespace arrow
32.661017
75
0.737416
AlvinJ15
1930b9cdd5fdfc4442f2e9abf0c26280cc8f2787
196
cpp
C++
10.10-span0/main.cpp
andreasfertig/programming-with-cpp20
7c70351f3a46aea295e964096be77eb159be6e9f
[ "MIT" ]
107
2021-04-13T12:43:06.000Z
2022-03-30T05:07:16.000Z
10.10-span0/main.cpp
jessesimpson/programming-with-cpp20
7c70351f3a46aea295e964096be77eb159be6e9f
[ "MIT" ]
1
2021-04-13T12:59:30.000Z
2021-04-13T13:02:55.000Z
10.10-span0/main.cpp
jessesimpson/programming-with-cpp20
7c70351f3a46aea295e964096be77eb159be6e9f
[ "MIT" ]
29
2021-04-13T18:07:03.000Z
2022-03-28T13:44:01.000Z
// Copyright (c) Andreas Fertig. // SPDX-License-Identifier: MIT #include <cstddef> template<typename T> class Span { T* mData; size_t mSize; public: // constructors }; int main() {}
13.066667
32
0.658163
andreasfertig
19312e28c17a1befa02f080f5fd4c09660436f0f
209
cpp
C++
src/algorithm_list.cpp
GoncaloFDS/Lift
e026f585127ba55bdb261cd3ac3ca97545b7cd8f
[ "BSD-3-Clause" ]
30
2019-07-24T09:58:22.000Z
2021-09-03T08:20:22.000Z
src/algorithm_list.cpp
GoncaloFDS/Lift
e026f585127ba55bdb261cd3ac3ca97545b7cd8f
[ "BSD-3-Clause" ]
15
2020-06-20T13:20:50.000Z
2021-04-26T16:05:33.000Z
src/algorithm_list.cpp
GoncaloFDS/Lift
e026f585127ba55bdb261cd3ac3ca97545b7cd8f
[ "BSD-3-Clause" ]
5
2020-06-17T08:38:34.000Z
2021-09-08T22:14:02.000Z
#include "algorithm_list.h" const std::vector<std::pair<std::string, Algorithm>> AlgorithmList::all_algorithms = { {"Path Tracing", Algorithm::PT}, {"Bidirectional Path Tracing", Algorithm::BDPT}, };
29.857143
86
0.703349
GoncaloFDS
193544cc9f9e2b529c13ba814c29132be07d032b
2,331
hpp
C++
src/cpu/rtweekend.hpp
DveloperY0115/ray-tracing-in-one-weekend-cpp
4a293f8db7eefd1d62e6be46a53d65ff348eaa52
[ "MIT" ]
1
2021-02-18T08:38:21.000Z
2021-02-18T08:38:21.000Z
src/cpu/rtweekend.hpp
DveloperY0115/ray-tracing-in-one-weekend-cpp
4a293f8db7eefd1d62e6be46a53d65ff348eaa52
[ "MIT" ]
1
2021-02-13T04:42:01.000Z
2021-02-13T04:42:01.000Z
src/cpu/rtweekend.hpp
DveloperY0115/ray-tracing-in-one-weekend-cpp
4a293f8db7eefd1d62e6be46a53d65ff348eaa52
[ "MIT" ]
null
null
null
// // Created by 유승우 on 2020/05/15. // #ifndef FIRSTRAYTRACER_RTWEEKEND_HPP #define FIRSTRAYTRACER_RTWEEKEND_HPP #include <cmath> #include <cstdlib> #include <limits> #include <memory> #include <random> #include <time.h> // using statements to make codes more simple using std::shared_ptr; using std::make_shared; using std::sqrt; // Constants const double infinity = std::numeric_limits<double>::infinity(); const double pi = 3.1415926535897932385; // Utility Functions /** * Clamps the value 'x' to the interval specified by ['min', 'max'] * * If 'x' is smaller than the lower bound 'min', it's clamped to the value 'min' * else if 'x' is greater than the upper bound 'max', it's clamped to the value 'max', * otherwise 'x' retains its own value since it doesn't needed to be clamped * * @param x a double type value that is needed to be clamped * @param min the lower bound of the interval * @param max the upper bound of the interval * @return clamped value */ inline double clamp(double x, double min, double max) { if (x < min) return min; if (x > max) return max; return x; } /** * Generates a double type random number whose value lies between 0.0 and 1.0. * @return a double type value between 0.0 and 1.0 */ inline double random_double() { static std::uniform_real_distribution<double> distribution(0.0, 1.0); static std::mt19937 generator; return distribution(generator); } /* inline double random_double() { // Returns a random real number in [0, 1). return rand() / (RAND_MAX + 1.0); } */ /** * Generates a double type random number whose value lies between 'min' and 'max' * * @param min the lower bound for a desired random number * @param max the upper bound for a desired random number * @return a double type randomly generated number within the interval ['min', 'max'] */ inline double random_double(double min, double max) { // Returns a random real number in [min, max) return min + (max-min)*random_double(); } /** * Converts the angle represented in degrees to radian * * @param degrees an angle in degrees * @return same angle but in radian */ inline double degress_to_radians(double degrees) { return degrees * (pi / 180); } // Common Headers #include "ray.hpp" #include "vector3.hpp" #endif //FIRSTRAYTRACER_RTWEEKEND_HPP
24.536842
86
0.703561
DveloperY0115
1937294b0fbbd690599e20cd5d73e9c10dce5c45
1,839
tpp
C++
include/Sirius/Math/Matrix/Matrix2.tpp
xam4lor/Sirius
f05a89538ab2bc79a8d46f482fbb060271adce0a
[ "MIT" ]
1
2021-07-12T11:53:06.000Z
2021-07-12T11:53:06.000Z
include/Sirius/Math/Matrix/Matrix2.tpp
xam4lor/Sirius
f05a89538ab2bc79a8d46f482fbb060271adce0a
[ "MIT" ]
null
null
null
include/Sirius/Math/Matrix/Matrix2.tpp
xam4lor/Sirius
f05a89538ab2bc79a8d46f482fbb060271adce0a
[ "MIT" ]
1
2021-07-12T11:51:53.000Z
2021-07-12T11:51:53.000Z
#include "Matrix2.hpp" namespace Sirius { template<typename T> constexpr Matrix<2, T> operator+(const Matrix<2, T>& mat1, const Matrix<2, T>& mat2) { return Matrix<2, T>(mat1[0] + mat2[0], mat1[1] + mat2[1]); } template<typename T> constexpr Matrix<2, T> operator-(const Matrix<2, T>& mat1, const Matrix<2, T>& mat2) { return Matrix<2, T>(mat1[0] - mat2[0], mat1[1] - mat2[1]); } template<typename T> constexpr Matrix<2, T> operator*(const Matrix<2, T>& mat, T scalar) { return { mat[0] * scalar, mat[1] * scalar }; } template<typename T> constexpr Matrix<2, T> operator*(const Matrix<2, T>& mat1, const Matrix<2, T>& mat2) { return { mat1[0][0] * mat2[0][0] + mat1[1][0] * mat2[0][1], mat1[0][1] * mat2[0][0] + mat1[1][1] * mat2[0][1], mat1[0][0] * mat2[1][0] + mat1[1][0] * mat2[1][1], mat1[0][1] * mat2[1][0] + mat1[1][1] * mat2[1][1] }; } template<typename T> constexpr Vector<2, T> operator*(const Matrix<2, T>& mat, const Vector<2, T>& vec) { return { mat[0][0] * vec.x + mat[1][0] * vec.y, mat[0][1] * vec.x + mat[1][1] * vec.y }; } } template <typename T> struct fmt::formatter<Sirius::Matrix<2, T>> { constexpr auto parse(format_parse_context& ctx) { return ctx.end(); } template <typename Context> auto format(const Sirius::Matrix<2, T>& mat, Context& ctx) { return format_to(ctx.out(), "\n\t[{} {}]\n\t[{} {}]", mat[0][0], mat[1][0], mat[0][1], mat[1][1]); } }; template<typename T> std::ostream& operator<<(std::ostream& out, const Sirius::Matrix<2, T>& mat) { return out << "[" << mat[0][0] << " " << mat[1][0] << "]\n[" << mat[0][1] << " " << mat[1][1] << "]"; }
29.66129
106
0.516041
xam4lor
193898f97013de96c717a848897f6a54e2d1b516
17,785
cpp
C++
co-op/CmdVector.cpp
BartoszMilewski/CodeCoop
7d29f53ccf65b0d29ea7d6781a74507b52c08d0d
[ "MIT" ]
67
2018-03-02T10:50:02.000Z
2022-03-23T18:20:29.000Z
co-op/CmdVector.cpp
BartoszMilewski/CodeCoop
7d29f53ccf65b0d29ea7d6781a74507b52c08d0d
[ "MIT" ]
null
null
null
co-op/CmdVector.cpp
BartoszMilewski/CodeCoop
7d29f53ccf65b0d29ea7d6781a74507b52c08d0d
[ "MIT" ]
9
2018-03-01T16:38:28.000Z
2021-03-02T16:17:09.000Z
//---------------------------------- // (c) Reliable Software 1997 - 2008 //---------------------------------- #include "precompiled.h" #include "CmdVector.h" #include "Commander.h" // Code Co-op Commands namespace Cmd { const Cmd::Item<Commander> Table [] = { { "Program_Update", &Commander::Program_Update, 0, "Check for Co-op updates on the Internet" }, { "Program_Options", &Commander::Program_Options, 0, "View/Change program options" }, { "Program_Dispatching", &Commander::Program_Dispatching, 0, "View/Change script dispatching options" }, { "Program_Licensing", &Commander::Program_Licensing, 0, "Go to Web site to purchase license(s)" }, { "Program_About", &Commander::Program_About, 0, "About this program" }, { "Program_Exit", &Commander::Program_Exit, 0, "Exit program" }, { "Project_Visit", &Commander::Project_Visit, &Commander::can_Project_Visit, "Visit another project on this machine" }, { "Project_Move", &Commander::Project_Move, &Commander::can_Project_Move, "Move project tree to another location" }, { "Project_Repair", &Commander::Project_Repair, &Commander::can_Project_Repair, "Repair project file(s)" }, { "Project_RequestVerification", &Commander::Project_RequestVerification, &Commander::can_Project_RequestVerification, "Request project verification data from some other project member" }, { "Project_VerifyRootPaths",&Commander::Project_VerifyRootPaths,0, "Check if all projects have a valid root path" }, { "Project_Join", &Commander::Project_Join, 0, "Join an existing project" }, { "Project_Invite", &Commander::Project_Invite, &Commander::can_Project_Invite, "Invite someone to join your project" }, { "Project_OpenInvitation", &Commander::Project_OpenInvitation, 0, "Download project invitation" }, { "Project_New", &Commander::Project_New, 0, "Start a new project" }, { "Project_Branch", &Commander::Project_Branch, &Commander::can_Project_Branch, "Start a branch project" }, { "Project_Export", &Commander::Project_Export, &Commander::can_Project_Export, "Export project files and folders" }, { "Project_Members", &Commander::Project_Members, &Commander::can_Project_Members, "List/Edit project members' info" }, { "Project_Defect", &Commander::Project_Defect, &Commander::can_Project_Defect, "Rescind your membership in this project" }, { "Project_Admin", &Commander::Project_Admin, &Commander::can_Project_Admin, "Emergency project administrator election" }, { "Project_Options", &Commander::Project_Options, &Commander::can_Project_Options, "View/Change project options" }, { "Project_AddMoreFiles", &Commander::Project_AddMoreFiles, &Commander::can_Project_AddMoreFiles,"Add more files to the project" }, { "Project_NewFromHistory", &Commander::Project_NewFromHistory, &Commander::can_Project_NewFromHistory,"Start a new project from previously exported history" }, { "History_Export", &Commander::History_ExportHistory, &Commander::can_History_Export, "Export project history" }, { "History_Import", &Commander::History_ImportHistory, &Commander::can_History_Import, "Import project history" }, { "History_AddLabel", &Commander::History_AddLabel, &Commander::can_History_AddLabel, "Label project version" }, { "View_Back", &Commander::View_Back, &Commander::can_View_Back, "Navigate back" }, { "View_Forward", &Commander::View_Forward, &Commander::can_View_Forward, "Navigate forward" }, { "View_Home", &Commander::View_Home, &Commander::can_View_Home, "Navigate home" }, { "View_Refresh", &Commander::View_Refresh, &Commander::can_View_Refresh, "Update displayed information" }, { "View_ApplyFileFilter", &Commander::View_ApplyFileFilter, &Commander::can_View_ApplyFileFilter,"Apply file filter" }, { "View_ChangeFileFilter", &Commander::View_ChangeFileFilter, &Commander::can_View_ChangeFileFilter,"Change file filter" }, { "View_Browser", &Commander::View_Browser, &Commander::can_View_Browser, "View web page" }, { "View_Files", &Commander::View_Files, &Commander::can_View_Files, "Browse through files in the project" }, { "View_Mailbox", &Commander::View_Mailbox, &Commander::can_View_Mailbox, "Look at outgoing/incoming scripts" }, { "View_CheckIn", &Commander::View_CheckIn, &Commander::can_View_CheckIn, "Look at checked-out files" }, { "View_Synch", &Commander::View_Synch, &Commander::can_View_Synch, "Look at files changed by the sync" }, { "View_History", &Commander::View_History, &Commander::can_View_History, "Look at the history of the project" }, { "View_Projects", &Commander::View_Projects, &Commander::can_View_Projects, "Look at projects present on this machine" }, { "View_MergeProjects", &Commander::View_MergeProjects, &Commander::can_View_MergeProjects, "Open project merge view" }, { "View_Project_Folders", &Commander::View_Hierarchy, &Commander::can_View_Hierarchy, "Show a hierarchical view panel for the current list" }, { "View_Active_Projects", &Commander::View_Active_Projects, &Commander::can_View_Active_Projects,"Show active projects (projects with checked out files or incoming scripts)" }, { "View_Next", &Commander::View_Next, 0, "" }, { "View_Previous", &Commander::View_Previous, 0, "" }, { "View_ClosePage", &Commander::View_ClosePage, &Commander::can_View_ClosePage, "Close page" }, { "ChangeFilter", &Commander::ChangeFilter, 0, "" }, { "GoBack", &Commander::GoBack, 0, "" }, { "Folder_GoUp", &Commander::Folder_GoUp, &Commander::can_Folder_GoUp, "Go to parent folder" }, { "Folder_GotoRoot", &Commander::Folder_GotoRoot, &Commander::can_Folder_GotoRoot, "Go to project's root folder" }, { "Folder_NewFile", &Commander::Folder_NewFile, &Commander::can_Folder_NewFile, "Create a new file in the project" }, { "Folder_NewFolder", &Commander::Folder_NewFolder, &Commander::can_Folder_NewFolder, "Create a new folder in the project" }, { "Folder_AddMoreFiles", &Commander::Folder_AddMoreFiles, &Commander::can_Folder_AddMoreFiles,"Add more files to the project from the current folder" }, { "Folder_Wikify", &Commander::Folder_Wikify, &Commander::can_Folder_Wikify, "Turn current folder into a wiki site" }, { "Folder_ExportHtml", &Commander::Folder_ExportHtml, &Commander::can_Folder_ExportHtml, "Export wiki folder as HTML web site" }, { "All_CheckIn", &Commander::All_CheckIn, &Commander::can_All_CheckIn, "Check-in all files" }, { "All_CheckOut", &Commander::All_CheckOut, &Commander::can_All_CheckOut, "Check-out all files in current view" }, { "All_DeepCheckOut", &Commander::All_DeepCheckOut, &Commander::can_All_DeepCheckOut, "Check-out all files including sub-folders" }, { "All_Uncheckout", &Commander::All_Uncheckout, &Commander::can_All_Uncheckout, "Un-Checkout all checked-out files" }, { "All_AcceptSynch", &Commander::All_AcceptSynch, &Commander::can_All_AcceptSynch, "Accept this sync in full" }, { "All_Synch", &Commander::All_Synch, &Commander::can_All_Synch, "Execute and accept all sync scripts" }, { "All_Report", &Commander::All_Report, &Commander::can_All_Report, "Create report from all view items" }, { "All_Select", &Commander::All_Select, &Commander::can_All_Select, "Select all view items" }, { "All_SaveFileVersion", &Commander::All_SaveFileVersion, &Commander::can_All_SaveFileVersion, "Save version of file(s)" }, { "Selection_CheckOut", &Commander::Selection_CheckOut, &Commander::can_Selection_CheckOut, "Check-out selected files" }, { "Selection_DeepCheckOut", &Commander::Selection_DeepCheckOut,&Commander::can_Selection_DeepCheckOut, "Check-out selected files including sub-folders" }, { "Selection_CheckIn", &Commander::Selection_CheckIn, &Commander::can_Selection_CheckIn, "Check-in selected files" }, { "Selection_Uncheckout", &Commander::Selection_Uncheckout, &Commander::can_Selection_Uncheckout,"Un-Checkout selected files" }, { "Selection_Properties", &Commander::Selection_Properties, &Commander::can_Selection_Properties,"Selected item properties" }, { "Selection_Open", &Commander::Selection_Open, &Commander::can_Selection_Open, "Open selected files for viewing/editing" }, { "Selection_OpenWithShell",&Commander::Selection_OpenWithShell,&Commander::can_Selection_OpenWithShell,"Open selected files for viewing/editing using Windows Shell" }, { "Selection_SearchWithShell",&Commander::Selection_SearchWithShell,&Commander::can_Selection_SearchWithShell,"Search selected folder using Windows Shell" }, { "Selection_Add", &Commander::Selection_Add, &Commander::can_Selection_Add, "Add selected file(s) to project" }, { "Selection_Remove", &Commander::Selection_Remove, &Commander::can_Selection_Remove, "Remove selected file(s) from project (don't delete!)" }, { "Selection_Delete", &Commander::Selection_Delete, &Commander::can_Selection_Delete, "Delete selected file(s)" }, { "Selection_DeleteFile", &Commander::Selection_DeleteFile, 0, "" }, { "Selection_DeleteScript", &Commander::Selection_DeleteScript, 0, "" }, { "Selection_Rename", &Commander::Selection_Rename, &Commander::can_Selection_Rename, "Rename selected file" }, { "Selection_Move", &Commander::Selection_MoveFiles, &Commander::can_Selection_MoveFiles,"Move selected file(s)" }, { "Selection_ChangeFileType",&Commander::Selection_ChangeFileType, &Commander::can_Selection_ChangeFileType, "Change type" }, { "Selection_Cut", &Commander::Selection_Cut, &Commander::can_Selection_Cut, "Cut selected file(s) (to be pasted into another folder)" }, { "Selection_Copy", &Commander::Selection_Copy, &Commander::can_Selection_Copy, "Copy selected file(s) to Windows clipboard" }, { "Selection_Paste", &Commander::Selection_Paste, &Commander::can_Selection_Paste, "Move file(s) that have been cut or copied to current folder" }, { "Selection_AcceptSynch", &Commander::Selection_AcceptSynch, &Commander::can_Selection_AcceptSynch,"Accept sync changes for selected file(s)" }, { "Selection_Synch", &Commander::Selection_Synch, &Commander::can_Selection_Synch, "Execute and accept next sync script" }, { "Selection_EditSync", &Commander::Selection_EditSync, &Commander::can_Selection_EditSync, "Execute next sync script and edit its result" }, { "Selection_SendScript", &Commander::Selection_SendScript, &Commander::can_Selection_SendScript,"Re-send script to project members" }, { "Selection_RequestResend",&Commander::Selection_RequestResend,&Commander::can_Selection_RequestResend,"Request script to be re-send to you" }, { "Selection_ShowHistory", &Commander::Selection_ShowHistory, &Commander::can_Selection_ShowHistory,"Show history of file(s)" }, { "Selection_Blame", &Commander::Selection_Blame, &Commander::can_Selection_Blame, "Who did it?" }, { "Selection_Report", &Commander::Selection_Report, &Commander::can_Selection_Report, "Create report from selected view item(s)" }, { "Selection_Compare", &Commander::Selection_Compare, &Commander::can_Selection_Compare, "Compare old versions of file(s) " }, { "Selection_CompareWithPrevious",&Commander::Selection_CompareWithPrevious, &Commander::can_Selection_CompareWithPrevious, "Compare with previous version of file(s) " }, { "Selection_CompareWithCurrent",&Commander::Selection_CompareWithCurrent, &Commander::can_Selection_CompareWithCurrent, "Compare with current version of file(s) " }, { "Selection_Revert", &Commander::Selection_Revert, &Commander::can_Selection_Revert, "Restore old version of file(s)" }, { "Selection_MergeBranch", &Commander::Selection_MergeBranch, &Commander::can_Selection_MergeBranch, "Merge change from the branch into the current project version" }, { "Selection_Branch", &Commander::Selection_Branch, &Commander::can_Selection_Branch, "Create project branch starting from this version" }, { "Selection_VersionExport",&Commander::Selection_VersionExport,&Commander::can_Selection_VersionExport,"Export old version of file(s)" }, { "Selection_Archive", &Commander::Selection_Archive, &Commander::can_Selection_Archive, "Archive all versions before selection" }, { "Selection_UnArchive", &Commander::Selection_UnArchive, &Commander::can_Selection_UnArchive, "Open archive" }, { "Selection_Add2FileFilter",&Commander::Selection_Add2FileFilter, &Commander::can_Selection_Add2FileFilter,"Don't show files with the selected extension(s)" }, { "Selection_RemoveFromFileFilter", &Commander::Selection_RemoveFromFileFilter, &Commander::can_Selection_RemoveFromFileFilter, "Remove the selected file extension(s) from the file filter" }, { "Selection_HistoryFilterAdd", &Commander::Selection_HistoryFilterAdd, &Commander::can_Selection_HistoryFilterAdd, "Filter history by selected files" }, { "Selection_HistoryFilterRemove", &Commander::Selection_HistoryFilterRemove, &Commander::can_Selection_HistoryFilterRemove, "Clear history filter" }, { "Selection_SaveFileVersion", &Commander::Selection_SaveFileVersion, &Commander::can_Selection_SaveFileVersion, "Save version of file(s)" }, { "Selection_RestoreFileVersion", &Commander::Selection_RestoreFileVersion, &Commander::can_Selection_RestoreFileVersion, "Restores version of file(s)" }, { "Selection_MergeFileVersion", &Commander::Selection_MergeFileVersion, &Commander::can_Selection_MergeFileVersion, "Merges version of file(s) into the current project version" }, { "Selection_AutoMergeFileVersion", &Commander::Selection_AutoMergeFileVersion, &Commander::can_Selection_AutoMergeFileVersion, "Automatically merges version of file(s) into the current project version" }, { "Selection_CopyList", &Commander::Selection_CopyList, &Commander::can_Selection_CopyList, "Copy Select List To Clipboard" }, { "Selection_Edit", &Commander::Selection_Edit, &Commander::can_Selection_Edit, "Edit File" }, { "Selection_Next", &Commander::Selection_Next, &Commander::can_Selection_Next, "Next Page" }, { "Selection_Previous", &Commander::Selection_Previous, &Commander::can_Selection_Previous, "Previous Page" }, { "Selection_Home", &Commander::Selection_Home, &Commander::can_Selection_Home, "Browse Home" }, { "Selection_Reload", &Commander::Selection_Reload, &Commander::can_Selection_Reload, "Reload Page" }, { "Selection_CopyScriptComment", &Commander::Selection_CopyScriptComment, &Commander::can_Selection_CopyScriptComment, "Copy Script Comment To Clipboard" }, { "Tools_Differ", &Commander::Tools_Differ, 0, "Configure Differ Tool" }, { "Tools_Merger", &Commander::Tools_Merger, 0, "Configure Merger Tool" }, { "Tools_Editor", &Commander::Tools_Editor, 0, "Configure Editor Tool" }, { "Tools_CreateBackup", &Commander::Tools_CreateBackup, &Commander::can_Tools_CreateBackup, "Backup all projects" }, { "Tools_RestoreFromBackup",&Commander::Tools_RestoreFromBackup,&Commander::can_Tools_RestoreFromBackup, "Restore all projects from backup" }, { "Tools_MoveToMachine", &Commander::Tools_MoveToMachine, 0, "Move Code Co-op to a new machine" }, { "Help_Contents", &Commander::Help_Contents, 0, "Display Help" }, { "Help_Index", &Commander::Help_Index, 0, "Display Help Index" }, { "Help_Tutorial", &Commander::Help_Tutorial, 0, "Step-by-step tutorial" }, { "Help_Support", &Commander::Help_Support, 0, "On-line support" }, { "Help_SaveDiagnostics", &Commander::Help_SaveDiagnostics, 0, "Save diagnostic information to file" }, { "Help_RestoreOriginal", &Commander::Help_RestoreOriginal, &Commander::can_Help_RestoreOriginal, "Uninstall the current temporary version and restore the original version" }, { "Help_BeginnerMode", &Commander::Help_BeginnerMode, &Commander::can_Help_BeginnerMode, "Display helpful hints for the inexperienced user" }, // Commands triggered by control notification handlers { "DoNewFolder", &Commander::DoNewFolder, 0, "" }, { "DoRenameFile", &Commander::DoRenameFile, 0, "" }, { "DoDrag", &Commander::DoDrag, &Commander::can_Drag, "" }, { "DoDrop", &Commander::DoDrop, 0, "" }, { "SetCurrentFolder", &Commander::SetCurrentFolder, 0, "" }, { "DoNewFile", &Commander::DoNewFile, 0, "" }, { "DoDeleteFile", &Commander::DoDeleteFile, 0, "" }, { "Project_SelectMergeTarget", &Commander::Project_SelectMergeTarget, 0, "" }, { "Project_SetMergeType", &Commander::Project_SetMergeType, 0, "" }, { "Selection_OpenHistoryDiff", &Commander::Selection_OpenHistoryDiff, 0, "" }, // Commands not associated with any menu item, but used by SccDll or others { "GoBrowse", &Commander::GoBrowse, 0, "" }, { "OnBrowse", &Commander::OnBrowse, 0, "" }, { "Navigate", &Commander::Navigate, 0, "" }, { "OpenFile", &Commander::OpenFile, 0, "" }, { "CreateRange", &Commander::CreateRange, 0, "" }, { "Selection_OpenCheckInDiff", &Commander::Selection_OpenCheckInDiff, 0, "" }, { "RefreshMailbox", &Commander::RefreshMailbox, 0, "" }, { "RestoreVersion", &Commander::RestoreVersion, 0, "" }, { "Maintenance", &Commander::Maintenance, 0, "" }, { "ReCreateFile", &Commander::ReCreateFile, 0, "" }, { "MergeAttributes", &Commander::MergeAttributes, 0, "" }, #if !defined (NDEBUG) { "RestoreOneVersion", &Commander::RestoreOneVersion, 0, "" }, #endif { 0, 0, 0 } }; }
94.100529
207
0.721001
BartoszMilewski
193b13954156d2292b272b4c13f84bb937a3810a
1,820
cpp
C++
Algorithms/0023.MergeKSortedLists/solution.cpp
stdstring/leetcode
84e6bade7d6fc1a737eb6796cb4e2565440db5e3
[ "MIT" ]
null
null
null
Algorithms/0023.MergeKSortedLists/solution.cpp
stdstring/leetcode
84e6bade7d6fc1a737eb6796cb4e2565440db5e3
[ "MIT" ]
null
null
null
Algorithms/0023.MergeKSortedLists/solution.cpp
stdstring/leetcode
84e6bade7d6fc1a737eb6796cb4e2565440db5e3
[ "MIT" ]
null
null
null
#include <queue> #include <vector> #include "ListNode.h" #include "ListNodeUtils.h" #include "gtest/gtest.h" using CommonLib::ListNode; namespace { class Solution { public: ListNode* mergeKLists(std::vector<ListNode*> const &lists) { auto comp = [](ListNode* left, ListNode* right){ return left->val > right->val; }; std::priority_queue<ListNode*, std::vector<ListNode*>, decltype(comp)> queue(comp); for (ListNode* head : lists) { while (head != nullptr) { queue.push(head); head = head->next; } } ListNode* head = nullptr; ListNode* current = nullptr; while (!queue.empty()) { if (current == nullptr) head = current = queue.top(); else { current->next = queue.top(); current = current->next; } queue.pop(); } if (current != nullptr) current->next = nullptr; return head; } }; } using CommonLib::createLinkedList; using CommonLib::checkAndDeleteLinkedList; namespace MergeKSortedListsTask { TEST(ReorderListTaskTests, Examples) { Solution solution; checkAndDeleteLinkedList({1, 1, 2, 3, 4, 4, 5, 6}, solution.mergeKLists({createLinkedList({1, 4, 5}, false).get(), createLinkedList({1, 3, 4}, false).get(), createLinkedList({2, 6}, false).get()})); } TEST(ReorderListTaskTests, FromWrongAnswers) { Solution solution; checkAndDeleteLinkedList({}, solution.mergeKLists({})); checkAndDeleteLinkedList({}, solution.mergeKLists({nullptr})); } }
25.633803
118
0.52967
stdstring
193b65c74c6443443efd2c4733991672729e7e86
1,433
hpp
C++
minimal_sdk/public/containers/utldict.hpp
vocweb/cso2-launcher
abc144acaa3dfb5b0c9acd61cd75970cac012617
[ "MIT" ]
55
2018-09-01T17:52:17.000Z
2019-09-23T10:30:49.000Z
minimal_sdk/public/containers/utldict.hpp
RedheatWei/cso2-launcher
4cebbb98d51d33bd24c9a86a1d3fc311686d5011
[ "MIT" ]
70
2018-08-22T05:53:34.000Z
2019-09-23T15:11:39.000Z
minimal_sdk/public/containers/utldict.hpp
RedheatWei/cso2-launcher
4cebbb98d51d33bd24c9a86a1d3fc311686d5011
[ "MIT" ]
39
2018-09-01T21:42:50.000Z
2019-09-23T18:38:07.000Z
#pragma once #include <cstring> #include "containers/utlmap.hpp" #ifdef _WIN32 #define stricmp _stricmp #else #define stricmp strcasecmp #endif inline bool CaselessStringLessThan( const char* const& lhs, const char* const& rhs ) { if ( !lhs ) return false; if ( !rhs ) return true; return ( stricmp( lhs, rhs ) < 0 ); } inline char* UtlDict_DupStr( const char* inStr ) { const size_t len = std::strlen( inStr ) + 1; char* newStr = new char[len]; memcpy_s( newStr, len, inStr, len ); return newStr; } template <class T, class I = int> class CUtlDict { public: using DictElementMap_t = CUtlMap<const char*, T, I>; DictElementMap_t m_Elements; CUtlDict( int growSize = 0, int initSize = 0 ) : m_Elements( growSize, initSize ) { m_Elements.SetLessFunc( CaselessStringLessThan ); } ~CUtlDict() { Purge(); } void Purge() { RemoveAll(); } void RemoveAll() { typename DictElementMap_t::IndexType_t index = m_Elements.FirstInorder(); while ( index != m_Elements.InvalidIndex() ) { delete m_Elements.Key( index ); index = m_Elements.NextInorder( index ); } m_Elements.RemoveAll(); } I Insert( const char* pName, const T& element ) { return m_Elements.Insert( UtlDict_DupStr( pName ), element ); } };
22.046154
69
0.598046
vocweb
193baa28349a290947ae28e4780acc661b713584
709
cpp
C++
sycl/test/on-device/xocc/disabled/broken/name_collision.cpp
mgehre-xlx/sycl
2086745509ef4bc298d7bbec402a123dae68f25e
[ "Apache-2.0" ]
61
2019-04-12T18:49:57.000Z
2022-03-19T22:23:16.000Z
sycl/test/on-device/xocc/disabled/broken/name_collision.cpp
mgehre-xlx/sycl
2086745509ef4bc298d7bbec402a123dae68f25e
[ "Apache-2.0" ]
127
2019-04-09T00:55:50.000Z
2022-03-21T15:35:41.000Z
sycl/test/on-device/xocc/disabled/broken/name_collision.cpp
mgehre-xlx/sycl
2086745509ef4bc298d7bbec402a123dae68f25e
[ "Apache-2.0" ]
10
2019-04-02T18:25:40.000Z
2022-02-15T07:11:37.000Z
// REQUIRES: xocc // RUN: %clangxx -fsycl -fsycl-targets=%sycl_triple %s -o %t.out // RUN: %ACC_RUN_PLACEHOLDER %t.out // TODO should be a Sema test #include <CL/sycl.hpp> #include "../utilities/device_selectors.hpp" using namespace cl::sycl; class add_2; int main() { selector_defines::CompiledForDeviceSelector selector; queue q {selector}; q.submit([&] (handler &cgh) { cgh.single_task<add_2>([=] () { }); }); q.submit([&] (handler &cgh) { cgh.single_task<add_2>([=] () { }); }); q.submit([&] (handler &cgh) { cgh.single_task<class add>([=] () { }); }); q.submit([&] (handler &cgh) { cgh.single_task<class add>([=] () { }); }); return 0; }
16.880952
64
0.57969
mgehre-xlx
1943e504d831c8eac0d1a9ed4fd33283c4ceb1ea
2,860
hpp
C++
bsengine/src/bstorm/logger.hpp
At-sushi/bstorm
156036afd698d98f0ed67f0efa6bc416115806f7
[ "MIT" ]
null
null
null
bsengine/src/bstorm/logger.hpp
At-sushi/bstorm
156036afd698d98f0ed67f0efa6bc416115806f7
[ "MIT" ]
null
null
null
bsengine/src/bstorm/logger.hpp
At-sushi/bstorm
156036afd698d98f0ed67f0efa6bc416115806f7
[ "MIT" ]
null
null
null
#pragma once #include <bstorm/source_map.hpp> #include <string> #include <memory> #include <vector> #include <mutex> namespace bstorm { class LogParam { public: enum class Tag { TEXT, TEXTURE, SOUND, MESH, PLAYER_SHOT_DATA, ENEMY_SHOT_DATA, ITEM_DATA, SCRIPT, RENDER_TARGET, SHADER }; LogParam(Tag tag, const std::string& text); LogParam(Tag tag, const std::wstring& text); LogParam(Tag tag, std::string&& text); Tag GetTag() const { return tag_; } const std::string& GetText() const { return text_; } private: Tag tag_; std::string text_; // utf8 }; enum class LogLevel { LV_INFO, LV_WARN, LV_ERROR, LV_SUCCESS, LV_DEBUG, LV_USER }; class Log { public: static const char* GetLevelName(LogLevel level); Log(); Log(LogLevel level); Log& Msg(const std::string& text); Log& Msg(const std::wstring& text); Log& Msg(std::string&& text); const std::string& Msg() const { return msg_; } Log& Param(const LogParam& param); Log& Param(LogParam&& param); const std::shared_ptr<LogParam>& Param() const { return param_; } Log& Level(LogLevel level); LogLevel Level() const { return level_; } Log& AddSourcePos(const std::shared_ptr<SourcePos>& srcPos); const std::vector<SourcePos>& GetSourcePosStack() const { return srcPosStack_; } std::string ToString() const; Log&& move() { return std::move(*this); } private: LogLevel level_; std::string msg_; // utf8 std::shared_ptr<LogParam> param_; // Nullable std::vector<SourcePos> srcPosStack_; // add = push_back }; Log LogInfo(const std::wstring& msg); Log LogInfo(const std::string& msg); Log LogInfo(std::string&& msg); Log LogWarn(const std::wstring& msg); Log LogWarn(const std::string& msg); Log LogWarn(std::string&& msg); Log LogError(const std::wstring& msg); Log LogError(const std::string& msg); Log LogError(std::string&& msg); Log LogDebug(const std::wstring& msg); Log LogDebug(const std::string& msg); Log LogDebug(std::string&& msg); class Logger { public: static void Init(const std::shared_ptr<Logger>& logger); static void Write(Log& lg); static void Write(Log&& lg); static void Write(LogLevel level, const std::string& text); static void Write(LogLevel level, const std::wstring& text); static void Write(LogLevel level, std::string&& text); static void Shutdown(); virtual ~Logger() {} virtual void log(Log& lg) noexcept(false) = 0; virtual void log(Log&& lg) noexcept(false) = 0; void log(LogLevel level, const std::string& text); void log(LogLevel level, const std::wstring& text); void log(LogLevel level, std::string&& text); private: static std::shared_ptr<Logger> logger; static std::mutex mutex; }; }
26
84
0.654196
At-sushi
1944823fef65060394f79ec527543ef0dc6f84af
14,712
cpp
C++
examples/hxhim/cli.cpp
hpc/hxhim
1a2224a200cb5a9fae33da13720e68beb5bee746
[ "BSD-3-Clause" ]
2
2020-11-25T17:45:58.000Z
2021-12-21T02:01:16.000Z
examples/hxhim/cli.cpp
hpc/hxhim
1a2224a200cb5a9fae33da13720e68beb5bee746
[ "BSD-3-Clause" ]
null
null
null
examples/hxhim/cli.cpp
hpc/hxhim
1a2224a200cb5a9fae33da13720e68beb5bee746
[ "BSD-3-Clause" ]
1
2021-10-11T19:54:05.000Z
2021-10-11T19:54:05.000Z
#include <cstring> #include <ios> #include <iostream> #include <list> #include <map> #include <sstream> #include "hxhim/hxhim.hpp" #include "print_results.h" #include "utils/Blob.hpp" // private header #include "utils/memory.hpp" enum HXHIM_OP { PUT, GET, GETOP, DEL, BPUT, BGET, BGETOP, BDEL, FLUSHPUTS, FLUSHGETS, FLUSHDELS, FLUSH, }; const std::map<HXHIM_OP, std::string> FORMAT = { std::make_pair(HXHIM_OP::PUT, "PUT <SUBJECT> <PREDICATE> <OBJECT>"), std::make_pair(HXHIM_OP::GET, "GET <SUBJECT> <PREDICATE> <OBJECT_TYPE>"), std::make_pair(HXHIM_OP::GETOP, "GETOP <SUBJECT> <PREDICATE> <OBJECT_TYPE> <NUM_RECS> <OP>"), std::make_pair(HXHIM_OP::DEL, "DEL <SUBJECT> <PREDICATE>"), std::make_pair(HXHIM_OP::BPUT, "BPUT N <SUBJECT_1> <PREDICATE_1> <OBJECT_1> ... <SUBJECT_N> <PREDICATE_N> <OBJECT_N>"), std::make_pair(HXHIM_OP::BGET, "BGET N <SUBJECT_1> <PREDICATE_1> <OBJECT_TYPE_1> ... <SUBJECT_N> <PREDICATE_N> <OBJECT_TYPE_N>"), std::make_pair(HXHIM_OP::BGETOP, "BGETOP <SUBJECT_1> <PREDICATE_1> <OBJECT_TYPE_1> <NUM_RECS_1> <OP_1> ... <SUBJECT_N> <PREDICATE_N> <OBJECT_TYPE_N> <NUM_RECS_N> <OP_N>"), std::make_pair(HXHIM_OP::BDEL, "BDEL N <SUBJECT_1> <PREDICATE_1> ... <SUBJECT_N> <PREDICATE_N>"), std::make_pair(HXHIM_OP::FLUSHPUTS, "FLUSHPUTS"), std::make_pair(HXHIM_OP::FLUSHGETS, "FLUSHGETS"), std::make_pair(HXHIM_OP::FLUSHDELS, "FLUSHDELS"), std::make_pair(HXHIM_OP::FLUSH, "FLUSH"), }; const std::map<std::string, HXHIM_OP> USER2OP = { std::make_pair("PUT", HXHIM_OP::PUT), std::make_pair("BPUT", HXHIM_OP::BPUT), std::make_pair("GET", HXHIM_OP::GET), std::make_pair("BGET", HXHIM_OP::BGET), std::make_pair("GETOP", HXHIM_OP::GETOP), std::make_pair("BGETOP", HXHIM_OP::BGETOP), std::make_pair("DEL", HXHIM_OP::DEL), std::make_pair("BDEL", HXHIM_OP::BDEL), std::make_pair("FLUSHPUTS", HXHIM_OP::FLUSHPUTS), std::make_pair("FLUSHGETS", HXHIM_OP::FLUSHGETS), std::make_pair("FLUSHDELS", HXHIM_OP::FLUSHDELS), std::make_pair("FLUSH", HXHIM_OP::FLUSH), }; const std::map<std::string, hxhim_data_t> USER2OT = { std::make_pair("INT32", HXHIM_DATA_INT32), std::make_pair("INT64", HXHIM_DATA_INT64), std::make_pair("UINT32", HXHIM_DATA_UINT32), std::make_pair("UINT64", HXHIM_DATA_UINT64), std::make_pair("FLOAT", HXHIM_DATA_FLOAT), std::make_pair("DOUBLE", HXHIM_DATA_DOUBLE), std::make_pair("BYTE", HXHIM_DATA_BYTE), }; const std::map<std::string, hxhim_getop_t> USER2GETOP = { std::make_pair("EQ", HXHIM_GETOP_EQ), std::make_pair("NEXT", HXHIM_GETOP_NEXT), std::make_pair("PREV", HXHIM_GETOP_PREV), std::make_pair("FIRST", HXHIM_GETOP_FIRST), std::make_pair("LAST", HXHIM_GETOP_LAST), // std::make_pair("PRIMARY_EQ", HXHIM_GETOP_PRIMARY_EQ), }; std::ostream &help(char *self, std::ostream &stream = std::cout) { stream << "Syntax: " << self << " [-h | --help] [--ds <name>]" << std::endl << std::endl << "--ds implies a single rank. Running multiple MPI ranks will error." << std::endl << std::endl << "Input is passed in through the stdin of rank 0, delimited with newlines, in the following formats:" << std::endl; for(decltype(FORMAT)::value_type const &format : FORMAT) { stream << " " << format.second << std::endl; } stream << "Where <SUBJECT>, <PREDICATE>, and <OBJECT> are pairs of <type, data>" << std::endl << "<OBJECT_TYPE> is only the type" << std::endl << std::endl << "Available Types:" << std::endl; for(decltype(USER2OT)::value_type const &type : USER2OT) { stream << " " << type.first << std::endl; } stream << std::endl << "The <OP> argument to (B)GETOP can be one of the following:" << std::endl; for(decltype(USER2GETOP)::value_type const &op : USER2GETOP) { stream << " " << op.first << std::endl; } return stream; } std::istream &operator>>(std::istream &stream, hxhim_data_t &type) { std::string str; if ((stream >> str)) { const decltype(USER2OT)::const_iterator it = USER2OT.find(str); if (it == USER2OT.end()) { stream.setstate(std::ios::failbit); } else { type = it->second; } } return stream; } std::istream &operator>>(std::istream &stream, Blob &input) { hxhim_data_t type; if (!(stream >> type)) { return stream; } void *data = nullptr; std::size_t size = 0; switch (type) { case HXHIM_DATA_INT32: size = sizeof(int32_t); data = alloc(size); stream >> * (int32_t *) data; break; case HXHIM_DATA_INT64: size = sizeof(int64_t); data = alloc(size); stream >> * (int64_t *) data; break; case HXHIM_DATA_UINT32: size = sizeof(uint32_t); data = alloc(size); stream >> * (uint32_t *) data; break; case HXHIM_DATA_UINT64: size = sizeof(uint64_t); data = alloc(size); stream >> * (uint64_t *) data; break; case HXHIM_DATA_FLOAT: size = sizeof(float); data = alloc(size); stream >> * (float *) data; break; case HXHIM_DATA_DOUBLE: size = sizeof(double); data = alloc(size); stream >> * (double *) data; break; case HXHIM_DATA_BYTE: { std::string str; if ((stream >> str)) { size = str.size(); data = alloc(size); memcpy(data, str.c_str(), str.size()); } } break; default: stream.setstate(std::ios::failbit); break; } // on error, will be deallocated automatically input = RealBlob(data, size, type); return stream; } struct UserInput { HXHIM_OP hxhim_op; Blob subject; Blob predicate; Blob object; // data field is only used by (B)PUT // only used by (B)GETOP std::size_t num_recs; hxhim_getop_t op; }; using UserInputs = std::list<UserInput>; // A quick and dirty cleanup function void cleanup(hxhim_t *hx) { hxhim::Close(hx); MPI_Finalize(); } // serialize user input // B* becomes individual operations std::size_t parse_commands(std::istream &stream, UserInputs &commands) { std::string line; while (std::getline(stream, line)) { std::stringstream command(line); // empty line std::string op_str; if (!(command >> op_str)) { continue; } const decltype(USER2OP)::const_iterator op_it = USER2OP.find(op_str); if (op_it == USER2OP.end()) { std::cerr << "Error: Bad operation: " << op_str << std::endl; continue; } const HXHIM_OP hxhim_op = op_it->second; std::size_t count = 1; // bulk, so get count first if (op_str[0] == 'B') { if (!(command >> count)) { std::cerr << "Error: Bad count: " << line << std::endl; continue; } } // read input for(std::size_t i = 0; i < count; i++) { UserInput input; bool ok = true; switch ((input.hxhim_op = hxhim_op)) { case HXHIM_OP::PUT: case HXHIM_OP::BPUT: { if (!(command >> input.subject >> input.predicate >> input.object)) { ok = false; } } break; case HXHIM_OP::GET: case HXHIM_OP::BGET: { hxhim_data_t object_type; if (!(command >> input.subject >> input.predicate >> object_type)) { ok = false; } else { input.object.set_type(object_type); } } break; case HXHIM_OP::GETOP: case HXHIM_OP::BGETOP: { hxhim_data_t object_type; std::string op; if (!(command >> input.subject >> input.predicate >> object_type >> input.num_recs >> op)) { ok = false; } else { input.object.set_type(object_type); } const decltype(USER2GETOP)::const_iterator getop_it = USER2GETOP.find(op); if (getop_it == USER2GETOP.end()) { ok = false; } else { input.op = getop_it->second; } } break; case HXHIM_OP::DEL: case HXHIM_OP::BDEL: if (!(command >> input.subject >> input.predicate)) { ok = false; } break; case HXHIM_OP::FLUSHPUTS: case HXHIM_OP::FLUSHGETS: case HXHIM_OP::FLUSHDELS: case HXHIM_OP::FLUSH: break; } if (!ok) { std::cerr << "Error: Could not parse line \"" << line << "\"." << std::endl << "Expected: " << FORMAT.at(hxhim_op) << std::endl; break; } commands.emplace_back(std::move(input)); } } return commands.size(); } std::size_t run_commands(hxhim_t *hx, const UserInputs &commands) { std::size_t successful = 0; for(UserInputs::value_type const &cmd : commands) { int rc = HXHIM_SUCCESS; hxhim_results *res = nullptr; switch (cmd.hxhim_op) { case HXHIM_OP::PUT: case HXHIM_OP::BPUT: rc = hxhimPut(hx, (void *) cmd.subject.data(), cmd.subject.size(), cmd.subject.data_type(), (void *) cmd.predicate.data(), cmd.predicate.size(), cmd.predicate.data_type(), (void *) cmd.object.data(), cmd.object.size(), cmd.object.data_type(), HXHIM_PUT_ALL); break; case HXHIM_OP::GET: case HXHIM_OP::BGET: rc = hxhimGet(hx, (void *) cmd.subject.data(), cmd.subject.size(), cmd.subject.data_type(), (void *) cmd.predicate.data(), cmd.predicate.size(), cmd.predicate.data_type(), cmd.object.data_type()); break; case HXHIM_OP::GETOP: case HXHIM_OP::BGETOP: rc = hxhimGetOp(hx, (void *) cmd.subject.data(), cmd.subject.size(), cmd.subject.data_type(), (void *) cmd.predicate.data(), cmd.predicate.size(), cmd.predicate.data_type(), cmd.object.data_type(), cmd.num_recs, cmd.op); break; case HXHIM_OP::DEL: case HXHIM_OP::BDEL: rc = hxhimDelete(hx, (void *) cmd.subject.data(), cmd.subject.size(), cmd.subject.data_type(), (void *) cmd.predicate.data(), cmd.predicate.size(), cmd.predicate.data_type()); break; case HXHIM_OP::FLUSHPUTS: res = hxhimFlushPuts(hx); break; case HXHIM_OP::FLUSHGETS: res = hxhimFlushGets(hx); break; case HXHIM_OP::FLUSHDELS: res = hxhimFlushDeletes(hx); break; case HXHIM_OP::FLUSH: res = hxhimFlush(hx); break; } print_results(hx, 0, res); hxhim_results_destroy(res); if (rc == HXHIM_ERROR) { std::cerr << "Error" << std::endl; } else { successful++; } } // do not implicity flush return successful; } int main(int argc, char *argv[]) { int provided; MPI_Init_thread(&argc, &argv, MPI_THREAD_MULTIPLE, &provided); int rank; MPI_Comm_rank(MPI_COMM_WORLD, &rank); int size; MPI_Comm_size(MPI_COMM_WORLD, &size); char * ds = nullptr; for(int i = 1; i < argc;) { const std::string args(argv[i]); if ((args == "-h")|| (args == "--help")) { if (rank == 0) { help(argv[0], std::cerr); } MPI_Finalize(); return 0; } if (args == "--ds") { // --ds implies a single rank, but a single rank does not imply --ds if (size != 1) { std::cerr << "Error: The --ds flag implies 1 rank. Have " << size << std::endl; MPI_Finalize(); return 1; } ds = argv[++i]; } i++; } // read the config hxhim_t hx; if (hxhimInit(&hx, MPI_COMM_WORLD) != HXHIM_SUCCESS) { if (rank == 0) { std::cout << "Error: Failed to read configuration" << std::endl; } cleanup(&hx); return 1; } // initialize hxhim context if (ds) { if (hxhimOpenOne(&hx, ds, strlen(ds)) != HXHIM_SUCCESS) { if (rank == 0) { std::cerr << "Failed to initialize hxhim" << std::endl; } cleanup(&hx); return 1; } } else { if (hxhimOpen(&hx) != HXHIM_SUCCESS) { if (rank == 0) { std::cerr << "Failed to initialize hxhim" << std::endl; } cleanup(&hx); return 1; } } // parse and run input if (rank == 0) { UserInputs cmds; const std::size_t valid_count = parse_commands(std::cin, cmds); std::cout << "Read " << valid_count << " valid commands" << std::endl; run_commands(&hx, cmds); } MPI_Barrier(MPI_COMM_WORLD); cleanup(&hx); return 0; }
32.548673
178
0.494562
hpc
19479dd6b3bc0d9adfe49819ccb09e8be6112570
1,120
cpp
C++
BasicRenderer/src/RenderSystem/RenderObjects/Bindable/IndexBuffer.cpp
LexSheyn/DirectX11_TEST
bcc7d09c5e24cd923decbe8f1852fd05c810a2f6
[ "Apache-2.0" ]
null
null
null
BasicRenderer/src/RenderSystem/RenderObjects/Bindable/IndexBuffer.cpp
LexSheyn/DirectX11_TEST
bcc7d09c5e24cd923decbe8f1852fd05c810a2f6
[ "Apache-2.0" ]
null
null
null
BasicRenderer/src/RenderSystem/RenderObjects/Bindable/IndexBuffer.cpp
LexSheyn/DirectX11_TEST
bcc7d09c5e24cd923decbe8f1852fd05c810a2f6
[ "Apache-2.0" ]
null
null
null
#include "../../../PrecompiledHeaders/stdafx.h" #include "IndexBuffer.h" namespace dx11 { // Constructors and Destructor: IndexBuffer::IndexBuffer(RenderSystem& renderSystem, const std::vector<uint16>& indices) : count( UINT( indices.size() ) ) { D3D11_BUFFER_DESC index_buffer_desc = {}; index_buffer_desc.BindFlags = D3D11_BIND_INDEX_BUFFER; index_buffer_desc.Usage = D3D11_USAGE_DEFAULT; index_buffer_desc.CPUAccessFlags = 0u; index_buffer_desc.MiscFlags = 0u; index_buffer_desc.ByteWidth = UINT( count * sizeof( uint16 ) ); index_buffer_desc.StructureByteStride = sizeof( uint16 ); D3D11_SUBRESOURCE_DATA index_subresource_data = {}; index_subresource_data.pSysMem = indices.data(); Bindable::GetDevice( renderSystem )->CreateBuffer( &index_buffer_desc, &index_subresource_data, &m_pIndexBuffer ); } // Functions: void IndexBuffer::Bind(RenderSystem& renderSystem) noexcept { Bindable::GetContext( renderSystem )->IASetIndexBuffer( m_pIndexBuffer.Get(), DXGI_FORMAT_R16_UINT, 0u ); } // Accessors: const UINT& IndexBuffer::GetCount() const noexcept { return count; } }
26.046512
116
0.755357
LexSheyn
194edcd60b676d2b702caf68ea5608d0ad8ce143
4,462
cpp
C++
src/main.cpp
tsaarni/avr-high-voltage-serial-programming
102426504dea4326896aa598a6a218b900c044fb
[ "BSD-3-Clause" ]
27
2017-08-15T05:45:21.000Z
2022-03-27T21:32:46.000Z
src/main.cpp
AA6KL/avr-high-voltage-serial-programming
102426504dea4326896aa598a6a218b900c044fb
[ "BSD-3-Clause" ]
1
2022-01-10T19:43:12.000Z
2022-01-10T19:43:12.000Z
src/main.cpp
AA6KL/avr-high-voltage-serial-programming
102426504dea4326896aa598a6a218b900c044fb
[ "BSD-3-Clause" ]
11
2017-08-15T16:28:41.000Z
2021-04-26T11:52:54.000Z
// // BSD 3-Clause License // // Copyright (c) 2017, Tero Saarni // // // This software re-programs ATtiny85 fuses using the high-voltage // serial programming method. // // // References // // * ATtiny85 datasheet - // http://www.atmel.com/images/atmel-2586-avr-8-bit-microcontroller-attiny25-attiny45-attiny85_datasheet.pdf // // * Online fuse value calculator - // http://www.engbedded.com/fusecalc/ // // // High-voltaga serial programming instruction set (from ATtiny85 datasheet) // // Write Fuse Low Bits // // Instr.1/5 Instr.2/6 Instr.3 Instr.4 Operation remark // SDI 0_0100_0000_00 0_A987_6543_00 0_0000_0000_00 0_0000_0000_00 Wait after Instr. 4 until SDO // SII 0_0100_1100_00 0_0010_1100_00 0_0110_0100_00 0_0110_1100_00 goes high. Write A - 3 = “0” to // SDO x_xxxx_xxxx_xx x_xxxx_xxxx_xx x_xxxx_xxxx_xx x_xxxx_xxxx_xx program the Fuse bit. // // Write Fuse High Bits // // Instr.1/5 Instr.2/6 Instr.3 Instr.4 Operation remark // SDI 0_0100_0000_00 0_IHGF_EDCB_00 0_0000_0000_00 0_0000_0000_00 Wait after Instr. 4 until SDO // SII 0_0100_1100_00 0_0010_1100_00 0_0111_0100_00 0_0111_1100_00 goes high. Write I - B = “0” to // SDO x_xxxx_xxxx_xx x_xxxx_xxxx_xx x_xxxx_xxxx_xx x_xxxx_xxxx_xx program the Fuse bit. // // Write Fuse Extended Bits // // Instr.1/5 Instr.2/6 Instr.3 Instr.4 Operation remark // SDI 0_0100_0000_00 0_0000_000J_00 0_0000_0000_00 0_0000_0000_00 Wait after Instr. 4 until SDO // SII 0_0100_1100_00 0_0010_1100_00 0_0110_0110_00 0_0110_1110_00 goes high. Write J = “0” to // SDO x_xxxx_xxxx_xx x_xxxx_xxxx_xx x_xxxx_xxxx_xx x_xxxx_xxxx_xx program the Fuse bit. // #include <Arduino.h> // ATtiny85 pin mapaping at Arduino nano programmer #define SDI_PIN 9 // serial data input #define SII_PIN 10 // serial instruction input #define SDO_PIN 11 // serial data output #define SCI_PIN 12 // serial clock input #define RESET_PIN 13 // reset void avr_hvsp_write(uint8_t sdi, uint8_t sii) { digitalWrite(SDI_PIN, LOW); digitalWrite(SII_PIN, LOW); digitalWrite(SCI_PIN, HIGH); digitalWrite(SCI_PIN, LOW); for (uint8_t i = 0; i < 8; i++) { digitalWrite(SDI_PIN, (sdi & (1 << (7-i)))); digitalWrite(SII_PIN, (sii & (1 << (7-i)))); digitalWrite(SCI_PIN, HIGH); digitalWrite(SCI_PIN, LOW); } digitalWrite(SDI_PIN, LOW); digitalWrite(SII_PIN, LOW); digitalWrite(SCI_PIN, HIGH); digitalWrite(SCI_PIN, LOW); digitalWrite(SCI_PIN, HIGH); digitalWrite(SCI_PIN, LOW); } void avr_hvsp_write_lfuse(uint8_t lfuse) { avr_hvsp_write(0b01000000, 0b01001100); avr_hvsp_write(lfuse, 0b00101100); avr_hvsp_write(0b00000000, 0b01100100); avr_hvsp_write(0b00000000, 0b01101100); while (digitalRead(SDO_PIN) == LOW) { }; } void avr_hvsp_write_hfuse(uint8_t hfuse) { avr_hvsp_write(0b01000000, 0b01001100); avr_hvsp_write(hfuse, 0b00101100); avr_hvsp_write(0b00000000, 0b01110100); avr_hvsp_write(0b00000000, 0b01111100); while (digitalRead(SDO_PIN) == LOW) { }; } void avr_hvsp_write_efuse(uint8_t efuse) { avr_hvsp_write(0b01000000, 0b01001100); avr_hvsp_write(efuse, 0b00101100); avr_hvsp_write(0b00000000, 0b01100110); avr_hvsp_write(0b00000000, 0b01101110); while (digitalRead(SDO_PIN) == LOW) { }; } void setup() { Serial.begin(9600); // setup pin modes pinMode(SDI_PIN, OUTPUT); pinMode(SII_PIN, OUTPUT); pinMode(SDO_PIN, OUTPUT); pinMode(SCI_PIN, OUTPUT); pinMode(RESET_PIN, OUTPUT); // enter programming mode digitalWrite(SDI_PIN, LOW); digitalWrite(SII_PIN, LOW); digitalWrite(SDO_PIN, LOW); digitalWrite(RESET_PIN, HIGH); // pull attiny85 reset pin to ground delayMicroseconds(20); digitalWrite(RESET_PIN, LOW); // attiny85 reset pin to 12V delayMicroseconds(10); pinMode(SDO_PIN, INPUT); delayMicroseconds(300); // write default fuse values avr_hvsp_write_lfuse(0x62); avr_hvsp_write_hfuse(0xdf); avr_hvsp_write_efuse(0xff); // exit programming mode digitalWrite(RESET_PIN, HIGH); // pull attiny85 reset pin to ground (arduino nano LED will be on) } void loop() { Serial.print("Programming done"); while (true) { delay(1000); Serial.print("."); } }
30.353741
112
0.680861
tsaarni
1958ce79e96fc3c2e4c92e2e5427e6916560a676
8,696
cpp
C++
src/engine/drawable/richtext.cpp
FoFabien/SF2DEngine
3d10964cbdae439584c10ab427ade394d720713f
[ "Zlib" ]
null
null
null
src/engine/drawable/richtext.cpp
FoFabien/SF2DEngine
3d10964cbdae439584c10ab427ade394d720713f
[ "Zlib" ]
null
null
null
src/engine/drawable/richtext.cpp
FoFabien/SF2DEngine
3d10964cbdae439584c10ab427ade394d720713f
[ "Zlib" ]
null
null
null
#include "richtext.hpp" #include <SFML/Graphics.hpp> #include <sstream> static std::map<sf::String, sf::Color> colors; // same as sf::Text styles // define them locally to redefine them for a child class for example #define Regular 0 #define Bold 1 #define Italic 2 #define Underlined 4 // TextChunk functions TextChunk::TextChunk() { style = Regular; color = sf::Color::White; endsInNewline = false; } void TextChunk::add(std::vector<TextChunk*>& chunks, TextChunk*& current, TextChunk* last) { chunks.push_back(new TextChunk()); current = chunks.back(); if(chunks.size() > 2) { current->style = last->style; current->color = last->color; } } void TextChunk::format(TextChunk*& current, TextChunk* last, int32_t style) { if((last->style & style) >= 0) current->style ^= style; else current->style |= style; } // RichText functions RichText::RichText() { nlratio = 1.5; csize = 20; // default parameters font = nullptr; } RichText::RichText(const sf::String& source, const sf::Font& font, uint32_t csize) { nlratio = 1.5; this->csize = csize; this->font = &font; setString(source); // update the displayed string } RichText::~RichText() { clear(); } sf::String RichText::getString() const { return string; } sf::String RichText::getSource() const { return source; } void RichText::setString(const sf::String& source) { this->source = source; if(!font) return; // nothing to display, return clear(); if(source.getSize() == 0) return; chunks.push_back(new TextChunk()); TextChunk* current = chunks[0]; TextChunk* last = nullptr; bool escaped = false; // create the chunks for(uint32_t i = 0; i < source.getSize(); ++i) { last = current; if(escaped) { current->text += source[i]; escaped = false; continue; } switch(source[i]) { case '~': // italics { TextChunk::add(chunks, current, last); TextChunk::format(current, last, Italic); current->color = last->color; break; } case '*': // bold { TextChunk::add(chunks, current, last); TextChunk::format(current, last, Bold); current->color = last->color; break; } case '_': // underline { TextChunk::add(chunks, current, last); TextChunk::format(current, last, Underlined); current->color = last->color; break; } case '#': // color { int32_t length = 0; int32_t start = i + 1; // seek forward until the next whitespace while(!isspace(source[++i])) ++length; TextChunk::add(chunks, current, last); bool isValid; sf::Color c = getColor(source.toWideString().substr(start, length), isValid); if(isValid) current->color = c; break; } case '\\': // escape sequence for escaping formatting characters { if(escaped) { current->text += source[i]; escaped = false; break; } if (i + 1 < source.getSize()) { switch (source[i + 1]) { case '~': case '*': case '_': case '#': { escaped = true; break; } default: break; } } if (!escaped) current->text += source[i]; break; } case '\n': // make a new chunk in the case of a newline { current->endsInNewline = true; TextChunk::add(chunks, current, last); break; } default: { escaped = false; current->text += source[i]; // append the character break; } } } build(); } void RichText::build() { float boundY = csize*nlratio; sf::Text* t = nullptr; sf::Vector2f partPos(0, 0); // still forced to clear here for(size_t i = 0; i < parts.size(); ++i) if(parts[i] != nullptr) delete parts[i]; parts.clear(); bounds.left = 0; bounds.top = 0; bounds.width = 0; bounds.height = 0; for(size_t i = 0; i < chunks.size(); ++i) { if(chunks[i]->text.getSize() != 0) { t = new sf::Text(); t->setFillColor(chunks[i]->color); t->setString(chunks[i]->text); t->setStyle(chunks[i]->style); t->setCharacterSize(csize); if(font) t->setFont(*font); t->setPosition(partPos); } if(t) partPos.x += t->getLocalBounds().width; if(partPos.x >= bounds.width) bounds.width = partPos.x; if(chunks[i]->endsInNewline) { partPos.y += boundY; partPos.x = 0; bounds.height += boundY; } else if(i == chunks.size()-1) { bounds.height += boundY; } if(t) { parts.push_back((sf::Drawable*)t); t = nullptr; } } } void RichText::clear() { for(size_t i = 0; i < chunks.size(); ++i) delete chunks[i]; chunks.clear(); for(size_t i = 0; i < parts.size(); ++i) if(parts[i] != nullptr) delete parts[i]; parts.clear(); bounds.left = 0; bounds.top = 0; bounds.width = 0; bounds.height = 0; } uint32_t RichText::getCharacterSize() const { return csize; } void RichText::setCharacterSize(uint32_t size) { csize = (size < 1) ? 1 : size; build(); } float RichText::getNewLineSize() const { return nlratio; } void RichText::setNewLineSize(float size) { nlratio = (size <= 0) ? 1.5 : size; build(); } const sf::Font* RichText::getFont() const { return font; } void RichText::setFont(const sf::Font& font) { this->font = &font; build(); } void RichText::setFont(const sf::Font* font) { this->font = font; build(); } sf::FloatRect RichText::getLocalBounds() const { return bounds; } sf::FloatRect RichText::getGlobalBounds() const { return getTransform().transformRect(getLocalBounds()); } void RichText::addColor(const sf::String& name, const sf::Color& color) { colors[name] = color; } void RichText::addColor(const sf::String& name, uint32_t argbHex) { colors[name] = getColor(argbHex); } void RichText::draw(sf::RenderTarget& target, sf::RenderStates states) const { states.transform *= getTransform(); for(size_t i = 0; i < parts.size(); ++i) if(parts[i]) target.draw(*parts[i], states); } void RichText::initializeColors() { colors["default"] = sf::Color::White; colors["black"] = sf::Color::Black; colors["blue"] = sf::Color::Blue; colors["cyan"] = sf::Color::Cyan; colors["green"] = sf::Color::Green; colors["magenta"] = sf::Color::Magenta; colors["red"] = sf::Color::Red; colors["white"] = sf::Color::White; colors["yellow"] = sf::Color::Yellow; } sf::Color RichText::getColor(const sf::String& source, bool& isValid) { std::map<sf::String, sf::Color>::const_iterator result = colors.find(source); if(result == colors.end()) { // basic hexadecimal check for(size_t i = 0; i < source.getSize(); ++i) { if((source[i] < 'a' || source [i] > 'f') && (source[i] < 'A' || source[i] > 'F') && (source[i] < '0' || source[i] > '9')) { isValid = false; return sf::Color::White; } } uint32_t hex = 0x0; if(!(std::istringstream(source) >> std::hex >> hex)) { // Error parsing; return default isValid = false; return sf::Color::White; } isValid = true; return getColor(hex); } isValid = true; return result->second; } sf::Color RichText::getColor(uint32_t argbHex) { argbHex |= 0xff000000; return sf::Color(argbHex >> 16 & 0xFF, argbHex >> 8 & 0xFF, argbHex >> 0 & 0xFF, argbHex >> 24 & 0xFF); }
24.426966
133
0.504715
FoFabien
195a845d8e8e2cc67adee07d0846fa4e01e7a053
169
cpp
C++
test/RegExTest.cpp
simonask/snow-deprecated
4af5bd33481bd6e9bf516e7fa1a78c38e2ad03a1
[ "0BSD" ]
1
2015-11-05T06:07:12.000Z
2015-11-05T06:07:12.000Z
test/RegExTest.cpp
simonask/snow-deprecated
4af5bd33481bd6e9bf516e7fa1a78c38e2ad03a1
[ "0BSD" ]
null
null
null
test/RegExTest.cpp
simonask/snow-deprecated
4af5bd33481bd6e9bf516e7fa1a78c38e2ad03a1
[ "0BSD" ]
null
null
null
#include "test.h" #include "runtime/RegEx.h" using namespace snow; TEST_SUITE(RegEx); TEST_CASE(simple_match) { PENDING(); } TEST_CASE(simple_search) { PENDING(); }
13
26
0.721893
simonask
195bf2eed8dbab9b50896977c600a3caebae6cab
4,047
hpp
C++
src/sched/entry/write_entry.hpp
mshiryaev/oneccl
fb4bd69b0bfa72f0ed16ac2328205e51cf12d4aa
[ "Apache-2.0" ]
null
null
null
src/sched/entry/write_entry.hpp
mshiryaev/oneccl
fb4bd69b0bfa72f0ed16ac2328205e51cf12d4aa
[ "Apache-2.0" ]
null
null
null
src/sched/entry/write_entry.hpp
mshiryaev/oneccl
fb4bd69b0bfa72f0ed16ac2328205e51cf12d4aa
[ "Apache-2.0" ]
null
null
null
/* Copyright 2016-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. */ #pragma once #include "sched/entry/entry.hpp" #include "sched/queue/queue.hpp" class write_entry : public sched_entry, public postponed_fields<write_entry, ccl_sched_entry_field_src_mr, ccl_sched_entry_field_dst_mr> { public: static constexpr const char* class_name() noexcept { return "WRITE"; } write_entry() = delete; write_entry(ccl_sched* sched, ccl_buffer src_buf, atl_mr_t* src_mr, size_t cnt, ccl_datatype_internal_t dtype, size_t dst, atl_mr_t* dst_mr, size_t dst_buf_off) : sched_entry(sched), src_buf(src_buf), src_mr(src_mr), cnt(cnt), dtype(dtype), dst(dst), dst_mr(dst_mr), dst_buf_off(dst_buf_off) { } ~write_entry() { if (status == ccl_sched_entry_status_started) { LOG_DEBUG("cancel WRITE entry dst ", dst, ", req ", &req); atl_comm_cancel(sched->bin->get_comm_ctx(), &req); } } void start() override { update_fields(); LOG_DEBUG("WRITE entry dst ", dst, ", req ", &req); CCL_THROW_IF_NOT(src_buf && src_mr && dst_mr, "incorrect values"); if (!cnt) { status = ccl_sched_entry_status_complete; return; } size_t bytes = cnt * ccl_datatype_get_size(dtype); atl_status_t atl_status = atl_comm_write(sched->bin->get_comm_ctx(), src_buf.get_ptr(bytes), bytes, src_mr, (uint64_t)dst_mr->buf + dst_buf_off, dst_mr->r_key, dst, &req); update_status(atl_status); } void update() override { int req_status; atl_status_t atl_status = atl_comm_check(sched->bin->get_comm_ctx(), &req_status, &req); if (unlikely(atl_status != atl_status_success)) { CCL_THROW("WRITE entry failed. atl_status: ", atl_status_to_str(atl_status)); } if (req_status) { LOG_DEBUG("WRITE entry done, dst ", dst); status = ccl_sched_entry_status_complete; } } const char* name() const override { return class_name(); } atl_mr_t*& get_field_ref(field_id_t<ccl_sched_entry_field_src_mr> id) { return src_mr; } atl_mr_t*& get_field_ref(field_id_t<ccl_sched_entry_field_dst_mr> id) { return dst_mr; } protected: void dump_detail(std::stringstream& str) const override { ccl_logger::format(str, "dt ", ccl_datatype_get_name(dtype), ", cnt ", cnt, ", src_buf ", src_buf, ", src_mr ", src_mr, ", dst ", dst, ", dst_mr ", dst_mr, ", dst_off ", dst_buf_off, ", comm_id ", sched->coll_param.comm->id(), ", req %p", &req, "\n"); } private: ccl_buffer src_buf; atl_mr_t* src_mr; size_t cnt; ccl_datatype_internal_t dtype; size_t dst; atl_mr_t* dst_mr; size_t dst_buf_off; atl_req_t req{}; };
29.540146
100
0.547072
mshiryaev
19603e37219f2defe3844bb292c7f5ef815118a0
10,569
cpp
C++
src/domain.cpp
egdaub/fdfault
ec066f032ba109843164429aa7d9e7352485d735
[ "MIT" ]
12
2017-10-05T22:04:40.000Z
2020-08-31T08:32:17.000Z
src/domain.cpp
jhsa26/fdfault
ec066f032ba109843164429aa7d9e7352485d735
[ "MIT" ]
3
2020-05-06T16:48:32.000Z
2020-09-18T11:41:41.000Z
src/domain.cpp
jhsa26/fdfault
ec066f032ba109843164429aa7d9e7352485d735
[ "MIT" ]
12
2017-03-24T19:15:27.000Z
2020-08-31T08:32:18.000Z
#include <iostream> #include <fstream> #include <cassert> #include <string> #include "block.hpp" #include "cartesian.hpp" #include "domain.hpp" #include "fd.hpp" #include "fields.hpp" #include "friction.hpp" #include "interface.hpp" #include "rk.hpp" #include "slipweak.hpp" #include "stz.hpp" #include <mpi.h> using namespace std; domain::domain(const char* filename) { // constructor, no default as need to allocate memory int sbporder; string* iftype; int** nx_block; int** xm_block; nx_block = new int* [3]; xm_block = new int* [3]; // open input file, find appropriate place and read in parameters string line; ifstream paramfile(filename, ifstream::in); if (paramfile.is_open()) { // scan to start of domain list while (getline(paramfile,line)) { if (line == "[fdfault.domain]") { break; } } if (paramfile.eof()) { cerr << "Error reading domain from input file\n"; MPI_Abort(MPI_COMM_WORLD,-1); } else { // read domain variables paramfile >> ndim; paramfile >> mode; for (int i=0; i<3; i++) { paramfile >> nx[i]; } for (int i=0; i<3; i++) { paramfile >> nblocks[i]; } for (int i=0; i<3; i++) { nx_block[i] = new int [nblocks[i]]; xm_block[i] = new int [nblocks[i]]; } for (int i=0; i<3; i++) { for (int j=0; j<nblocks[i]; j++) { paramfile >> nx_block[i][j]; } } paramfile >> nifaces; iftype = new string [nifaces]; for (int i=0; i<nifaces; i++) { paramfile >> iftype[i]; } paramfile >> sbporder; paramfile >> material; } } else { cerr << "Error opening input file in domain.cpp\n"; MPI_Abort(MPI_COMM_WORLD,-1); } paramfile.close(); // check validity of input parameters assert(ndim == 2 || ndim == 3); assert(mode == 2 || mode == 3); assert(material == "elastic" || material == "plastic"); if (ndim == 2) { assert(nx[2] == 1); } for (int i=0; i<3; i++) { assert(nx[i] > 0); assert(nblocks[i] > 0); int sum = 0; for (int j=0; j<nblocks[i]; j++) { sum += nx_block[i][j]; } assert(sum == nx[i]); } // set other domain parameters if (material == "elastic") { is_plastic = false; } else { is_plastic = true; } nblockstot = nblocks[0]*nblocks[1]*nblocks[2]; for (int i=0; i<3; i++) { for (int j=0; j<nblocks[i]; j++) { if (j==0) { xm_block[i][j] = 0; } else { xm_block[i][j] = xm_block[i][j-1]+nx_block[i][j-1]; } } } // allocate memory for fd coefficients fd = new fd_type(sbporder); // set up cartesian type to hold domain decomposition information cart = new cartesian(filename, ndim, nx, nblocks, nx_block, xm_block, sbporder); f = new fields(filename, ndim, mode, material, *cart); // allocate memory and create blocks allocate_blocks(filename, nx_block, xm_block); // exchange neighbors to fill in ghost cells f->exchange_neighbors(); f->exchange_grid(); // allocate memory and create interfaces allocate_interfaces(filename, iftype); // set interface variables to match boundary conditions for (int i=0; i<nifaces; i++) { interfaces[i]->apply_bcs(0., 0., *f, true); } for (int i=0; i<3; i++) { delete[] nx_block[i]; delete[] xm_block[i]; } delete[] nx_block; delete[] xm_block; } domain::~domain() { // destructor, no default as need to deallocate memory deallocate_blocks(); deallocate_interfaces(); delete fd; delete cart; delete f; } int domain::get_ndim() const { // returns number of spatial dimensions return ndim; } int domain::get_mode() const { // returns mode return mode; } int domain::get_nblocks(const int index) const { // returns number of blocks assert(index >= 0 && index < 3); return nblocks[index]; } int domain::get_nblockstot() const { return nblockstot; } int domain::get_nifaces() const { return nifaces; } double domain::get_min_dx() const { // get min grid spacing divided by shear wave speed over all blocks double dxmin = 0., dxmintest, dxmin_all; for (int i=0; i<nblocks[0]; i++) { for (int j=0; j<nblocks[1]; j++) { for (int k=0; k<nblocks[2]; k++) { dxmintest = blocks[i][j][k]->get_min_dx(*f); if (dxmintest > 1.e-14) { // block has data if (dxmin <= 1.e-14 || dxmintest < dxmin) { dxmin = dxmintest; } } } } } if (dxmin <= 1.e-14) { cerr << "Error in domain.cpp get_min_dx -- a process does not have any grid spacing values\n"; MPI_Abort(MPI_COMM_WORLD,1); } MPI_Allreduce(&dxmin, &dxmin_all, 1, MPI_DOUBLE, MPI_MIN, MPI_COMM_WORLD); return dxmin_all; } void domain::do_rk_stage(const double dt, const int stage, const double t, rk_type& rk) { // advances domain fields for one RK stage of one time step // scale df by RK coefficient f->scale_df(rk.get_A(stage)); for (int i=0; i<nifaces; i++) { interfaces[i]->scale_df(rk.get_A(stage)); } // calculate df for blocks for (int i=0; i<nblocks[0]; i++) { for (int j=0; j<nblocks[1]; j++) { for (int k=0; k<nblocks[2]; k++) { blocks[i][j][k]->calc_df(dt,*f,*fd); // blocks[i][j][k]->set_mms(dt, t+rk.get_C(stage)*dt, *f); blocks[i][j][k]->set_boundaries(dt,*f); } } } // apply interface conditions for (int i=0; i<nifaces; i++) { interfaces[i]->apply_bcs(dt,t+rk.get_C(stage)*dt,*f,false); } // calculate df for interfaces for (int i=0; i<nifaces; i++) { interfaces[i]->calc_df(dt); } // update interfaces for (int i=0; i<nifaces; i++) { interfaces[i]->update(rk.get_B(stage)); } // update fields f->update(rk.get_B(stage)); // if last stage and response is plastic, solve plasticity equations if (stage+1 == rk.get_nstages() && is_plastic) { // set absolute stress f->set_stress(); for (int i=0; i<nblocks[0]; i++) { for (int j=0; j<nblocks[1]; j++) { for (int k=0; k<nblocks[2]; k++) { blocks[i][j][k]->calc_plastic(dt,*f); } } } // subtract stress f->remove_stress(); // apply interface conditions to correctly set slip rates (needed for correct output) for (int i=0; i<nifaces; i++) { interfaces[i]->apply_bcs(dt,t+rk.get_C(stage)*dt,*f,true); } } // exchange neighbors f->exchange_neighbors(); } void domain::free_exchange() { // frees MPI datatypes for ghost cell exchange f->free_exchange(); } void domain::set_stress() { // sets absolute stress f->set_stress(); } void domain::remove_stress() { // subtracts initial stress f->remove_stress(); } void domain::allocate_blocks(const char* filename, int** nx_block, int** xm_block) { // allocate memory for blocks and initialize int nxtmp[3]; int xmtmp[3]; int coords[3]; blocks = new block*** [nblocks[0]]; for (int i=0; i<nblocks[0]; i++) { blocks[i] = new block** [nblocks[1]]; } for (int i=0; i<nblocks[0]; i++) { for (int j=0; j<nblocks[1]; j++) { blocks[i][j] = new block* [nblocks[2]]; } } for (int i=0; i<nblocks[0]; i++) { for (int j=0; j<nblocks[1]; j++) { for (int k=0; k<nblocks[2]; k++) { nxtmp[0] = nx_block[0][i]; nxtmp[1] = nx_block[1][j]; nxtmp[2] = nx_block[2][k]; xmtmp[0] = xm_block[0][i]; xmtmp[1] = xm_block[1][j]; xmtmp[2] = xm_block[2][k]; coords[0] = i; coords[1] = j; coords[2] = k; blocks[i][j][k] = new block(filename, ndim, mode, material, coords, nxtmp, xmtmp, *cart, *f, *fd); } } } } void domain::allocate_interfaces(const char* filename, string* iftype) { // allocate memory for interfaces for (int i=0; i<nifaces; i++) { assert(iftype[i] == "locked" || iftype[i] == "frictionless" || iftype[i] == "slipweak" || iftype[i] == "stz"); } interfaces = new interface* [nifaces]; for (int i=0; i<nifaces; i++) { if (iftype[i] == "locked") { interfaces[i] = new interface(filename, ndim, mode, material, i, blocks, *f, *cart, *fd); } else if (iftype[i] == "frictionless") { interfaces[i] = new friction(filename, ndim, mode, material, i, blocks, *f, *cart, *fd); } else if (iftype[i] == "slipweak") { interfaces[i] = new slipweak(filename, ndim, mode, material, i, blocks, *f, *cart, *fd); } else if (iftype[i] == "stz") { interfaces[i] = new stz(filename, ndim, mode, material, i, blocks, *f, *cart, *fd); } } } void domain::deallocate_blocks() { // deallocate memory for blocks for (int i=0; i<nblocks[0]; i++) { for (int j=0; j<nblocks[1]; j++) { for (int k=0; k<nblocks[2]; k++) { delete blocks[i][j][k]; } } } for (int i=0; i<nblocks[0]; i++) { for (int j=0; j<nblocks[1]; j++) { delete[] blocks[i][j]; } } for (int i=0; i<nblocks[0]; i++) { delete[] blocks[i]; } delete[] blocks; } void domain::deallocate_interfaces() { // deallocate memory for interfaces for (int i=0; i<nifaces; i++) { delete interfaces[i]; } delete[] interfaces; }
25.40625
118
0.504589
egdaub
1963f5b09d876859feb4f7a7147f97955500b5fb
2,013
hpp
C++
queues/simple_locked_queue.hpp
lundgren87/qd_library
f19c412fbe97655601c761f27dd5a16abf7aa7a6
[ "BSD-2-Clause" ]
10
2016-10-26T13:36:18.000Z
2020-03-16T02:19:40.000Z
queues/simple_locked_queue.hpp
lundgren87/qd_library
f19c412fbe97655601c761f27dd5a16abf7aa7a6
[ "BSD-2-Clause" ]
null
null
null
queues/simple_locked_queue.hpp
lundgren87/qd_library
f19c412fbe97655601c761f27dd5a16abf7aa7a6
[ "BSD-2-Clause" ]
5
2016-10-07T12:28:59.000Z
2022-03-22T14:16:53.000Z
#ifndef qd_simple_locked_queue_hpp #define qd_simple_locked_queue_hpp qd_simple_locked_queue_hpp #include<array> #include<cassert> #include<mutex> #include<queue> class simple_locked_queue { std::mutex lock; std::queue<std::array<char, 128>> queue; typedef std::lock_guard<std::mutex> scoped_guard; typedef void(*ftype)(char*); /* some constants */ static const bool CLOSED = false; static const bool SUCCESS = true; void forwardall(char*, long i) { assert(i <= 120); if(i > 120) throw "up"; }; template<typename P, typename... Ts> void forwardall(char* buffer, long offset, P&& p, Ts&&... ts) { assert(offset <= 120); auto ptr = reinterpret_cast<P*>(&buffer[offset]); new (ptr) P(std::forward<P>(p)); forwardall(buffer, offset+sizeof(p), std::forward<Ts>(ts)...); } public: void open() { /* TODO this function should not even be here */ /* no-op as this is an "infinite" queue that always accepts more data */ } /** * @brief enqueues an entry * @tparam P return type of associated function * @param op wrapper function for associated function * @return SUCCESS on successful storing in queue, CLOSED otherwise */ template<typename... Ps> bool enqueue(ftype op, Ps*... ps) { std::array<char, 128> val; scoped_guard l(lock); queue.push(val); forwardall(queue.back().data(), 0, std::move(op), std::move(*ps)...); return SUCCESS; } /** execute all stored operations */ void flush() { scoped_guard l(lock); while(!queue.empty()) { auto operation = queue.front(); char* ptr = operation.data(); ftype* fun = reinterpret_cast<ftype*>(ptr); ptr += sizeof(ftype*); (*fun)(ptr); queue.pop(); } } /** execute one stored operation */ void flush_one() { scoped_guard l(lock); if(!queue.empty()) { char* ptr = queue.front().data(); ftype* fun = reinterpret_cast<ftype*>(ptr); ptr += sizeof(ftype); (*fun)(ptr); queue.pop(); } } }; #endif /* qd_simple_locked_queue_hpp */
26.142857
75
0.646299
lundgren87
19675ab5730b5e672335d8c569df4766e88cfe3f
3,883
cc
C++
src/ssl_info_action.cc
jeff-cn/doogie
1b4ed74adecbae773b51e674d298e3d5b09e4244
[ "MIT" ]
291
2017-07-19T22:32:25.000Z
2022-02-16T03:03:21.000Z
charts/doogie-0.7.8/src/ssl_info_action.cc
hyq5436/playground
828b9d2266dbb7d0311e2e73b295fcafb101d94f
[ "MIT" ]
81
2017-09-06T15:46:27.000Z
2020-11-30T14:12:11.000Z
charts/doogie-0.7.8/src/ssl_info_action.cc
hyq5436/playground
828b9d2266dbb7d0311e2e73b295fcafb101d94f
[ "MIT" ]
29
2017-09-18T19:14:50.000Z
2022-01-24T06:03:17.000Z
#include "ssl_info_action.h" namespace doogie { SslInfoAction::SslInfoAction(const Cef& cef, BrowserWidget* browser_widg) : QWidgetAction(browser_widg), cef_(cef), browser_widg_(browser_widg) { } QWidget* SslInfoAction::createWidget(QWidget* parent) { auto errored_ssl_info = browser_widg_->ErroredSslInfo(); auto errored_ssl_callback = browser_widg_->ErroredSslCallback(); auto ssl_status = browser_widg_->SslStatus(); auto layout = new QVBoxLayout; // SSL notes cef_cert_status_t status = CERT_STATUS_NONE; if (errored_ssl_info) { status = errored_ssl_info->GetCertStatus(); } else if (ssl_status) { status = ssl_status->GetCertStatus(); } auto status_strings = CertStatuses(status); if (!status_strings.isEmpty()) { auto status_layout = new QHBoxLayout; status_layout->addWidget(new QLabel("SSL Notes:"), 0, Qt::AlignTop); status_layout->addWidget(new QLabel(status_strings.join("\n")), 1); layout->addLayout(status_layout); } // Version and insecure content if (ssl_status) { auto version_layout = new QHBoxLayout; version_layout->addWidget(new QLabel("SSL Version:")); version_layout->addWidget( new QLabel(CertSslVersion(ssl_status->GetSSLVersion())), 1); layout->addLayout(version_layout); if (ssl_status->GetContentStatus() != SSL_CONTENT_NORMAL_CONTENT) { layout->addWidget(new QLabel("Displayed or ran insecure content")); } } // TODO(cretz): allow bypass // The button to view OS-level dialog auto details_button = new QPushButton("View Certificate Details"); connect(details_button, &QPushButton::clicked, [=](bool) { bool ok = false; if (errored_ssl_info) { ok = cef_.ShowCertDialog(errored_ssl_info->GetX509Certificate()); } else if (ssl_status) { ok = cef_.ShowCertDialog(ssl_status->GetX509Certificate()); } if (!ok) qWarning() << "Failed to show native cert dialog"; }); layout->addWidget(details_button, 0, Qt::AlignCenter); layout->addStretch(1); auto widg = new QWidget(parent); widg->setLayout(layout); return widg; } QStringList SslInfoAction::CertStatuses(cef_cert_status_t status) { const QHash<cef_cert_status_t, QString> strings = { { CERT_STATUS_COMMON_NAME_INVALID, "Common Name Invalid" }, { CERT_STATUS_DATE_INVALID, "Date Invalid" }, { CERT_STATUS_AUTHORITY_INVALID, "Authority Invalid" }, { CERT_STATUS_NO_REVOCATION_MECHANISM, "No Revocation Mechanism" }, { CERT_STATUS_UNABLE_TO_CHECK_REVOCATION, "Unable to Check Revocation" }, { CERT_STATUS_REVOKED, "Revoked" }, { CERT_STATUS_INVALID, "Invalid" }, { CERT_STATUS_WEAK_SIGNATURE_ALGORITHM, "Weak Signature Algorithm" }, { CERT_STATUS_NON_UNIQUE_NAME, "Non-Unique Name" }, { CERT_STATUS_WEAK_KEY, "Weak Key" }, { CERT_STATUS_PINNED_KEY_MISSING, "Pinned Key Missing" }, { CERT_STATUS_NAME_CONSTRAINT_VIOLATION, "Name Constraint Violation" }, { CERT_STATUS_VALIDITY_TOO_LONG, "Validity Too Long" }, { CERT_STATUS_IS_EV, "Extended Validation Certificate" }, { CERT_STATUS_REV_CHECKING_ENABLED, "Revocation Checking Enabled" }, { CERT_STATUS_SHA1_SIGNATURE_PRESENT, "SHA1 Signature Present" }, { CERT_STATUS_CT_COMPLIANCE_FAILED, "CT Compliance Failed" } }; QStringList ret; for (auto key : strings.keys()) { if (status & key) ret << strings[key]; } return ret; } QString SslInfoAction::CertSslVersion(cef_ssl_version_t ssl_version) { switch (ssl_version) { case SSL_CONNECTION_VERSION_SSL2: return "SSL 2.0"; case SSL_CONNECTION_VERSION_SSL3: return "SSL 3.0"; case SSL_CONNECTION_VERSION_TLS1: return "TLS 1.0"; case SSL_CONNECTION_VERSION_TLS1_1: return "TLS 1.1"; case SSL_CONNECTION_VERSION_TLS1_2: return "TLS 1.2"; case SSL_CONNECTION_VERSION_QUIC: return "QUIC"; default: return "(unknown)"; } } } // namespace doogie
37.699029
77
0.722637
jeff-cn
1967fc2cfe2e1f1dc101872396eb1497aa847e97
501
hpp
C++
comparetorfactory.hpp
cloudicen/TexasPoker
dc2c9debe38dbe811eb64540c702290ee5b0156d
[ "MIT" ]
null
null
null
comparetorfactory.hpp
cloudicen/TexasPoker
dc2c9debe38dbe811eb64540c702290ee5b0156d
[ "MIT" ]
null
null
null
comparetorfactory.hpp
cloudicen/TexasPoker
dc2c9debe38dbe811eb64540c702290ee5b0156d
[ "MIT" ]
null
null
null
#ifndef COMPARETORFACTORY_HPP #define COMPARETORFACTORY_HPP #include "comparetor.hpp" #include "QPointer" /** * @brief The deckType enum,定义了各种牌型的枚举 */ enum deckType{undefined,high_card,one_pair,two_pairs,three_of_a_kind,straight,flush,full_house,four_of_a_kind,straight_flush,royal_flush}; /** * @brief The comparetorFactory class,比较器的工厂类,返回需要的比较器 */ class comparetorFactory { public: static QSharedPointer<comparetor> getComparetor(const deckType type); }; #endif // COMPARETORFACTORY_HPP
23.857143
138
0.802395
cloudicen
196de25f738ff244d1313b7e80e870f003bcbaa7
2,804
cpp
C++
Nacro/SDK/FN_WorkerTooltipStatsWidget_functions.cpp
Milxnor/Nacro
eebabf662bbce6d5af41820ea0342d3567a0aecc
[ "BSD-2-Clause" ]
11
2021-08-08T23:25:10.000Z
2022-02-19T23:07:22.000Z
Nacro/SDK/FN_WorkerTooltipStatsWidget_functions.cpp
Milxnor/Nacro
eebabf662bbce6d5af41820ea0342d3567a0aecc
[ "BSD-2-Clause" ]
1
2022-01-01T22:51:59.000Z
2022-01-08T16:14:15.000Z
Nacro/SDK/FN_WorkerTooltipStatsWidget_functions.cpp
Milxnor/Nacro
eebabf662bbce6d5af41820ea0342d3567a0aecc
[ "BSD-2-Clause" ]
8
2021-08-09T13:51:54.000Z
2022-01-26T20:33:37.000Z
// Fortnite (1.8) SDK #ifdef _MSC_VER #pragma pack(push, 0x8) #endif #include "../SDK.hpp" namespace SDK { //--------------------------------------------------------------------------- //Functions //--------------------------------------------------------------------------- // Function WorkerTooltipStatsWidget.WorkerTooltipStatsWidget_C.Construct // (BlueprintCosmetic, Event, Public, BlueprintEvent) void UWorkerTooltipStatsWidget_C::Construct() { static auto fn = UObject::FindObject<UFunction>("Function WorkerTooltipStatsWidget.WorkerTooltipStatsWidget_C.Construct"); UWorkerTooltipStatsWidget_C_Construct_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function WorkerTooltipStatsWidget.WorkerTooltipStatsWidget_C.Tick // (BlueprintCosmetic, Event, Public, BlueprintEvent) // Parameters: // struct FGeometry* MyGeometry (Parm, IsPlainOldData) // float* InDeltaTime (Parm, ZeroConstructor, IsPlainOldData) void UWorkerTooltipStatsWidget_C::Tick(struct FGeometry* MyGeometry, float* InDeltaTime) { static auto fn = UObject::FindObject<UFunction>("Function WorkerTooltipStatsWidget.WorkerTooltipStatsWidget_C.Tick"); UWorkerTooltipStatsWidget_C_Tick_Params params; params.MyGeometry = MyGeometry; params.InDeltaTime = InDeltaTime; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function WorkerTooltipStatsWidget.WorkerTooltipStatsWidget_C.On Worker Preview State Changed // (BlueprintCallable, BlueprintEvent) void UWorkerTooltipStatsWidget_C::On_Worker_Preview_State_Changed() { static auto fn = UObject::FindObject<UFunction>("Function WorkerTooltipStatsWidget.WorkerTooltipStatsWidget_C.On Worker Preview State Changed"); UWorkerTooltipStatsWidget_C_On_Worker_Preview_State_Changed_Params params; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function WorkerTooltipStatsWidget.WorkerTooltipStatsWidget_C.ExecuteUbergraph_WorkerTooltipStatsWidget // (HasDefaults) // Parameters: // int EntryPoint (Parm, ZeroConstructor, IsPlainOldData) void UWorkerTooltipStatsWidget_C::ExecuteUbergraph_WorkerTooltipStatsWidget(int EntryPoint) { static auto fn = UObject::FindObject<UFunction>("Function WorkerTooltipStatsWidget.WorkerTooltipStatsWidget_C.ExecuteUbergraph_WorkerTooltipStatsWidget"); UWorkerTooltipStatsWidget_C_ExecuteUbergraph_WorkerTooltipStatsWidget_Params params; params.EntryPoint = EntryPoint; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } } #ifdef _MSC_VER #pragma pack(pop) #endif
29.208333
155
0.731455
Milxnor
196edfd0541a5114a81b67144dfa7bcf5ddb8c42
1,220
cpp
C++
src/_DrawableMatte.cpp
veryhappythings/pgmagick
5dce5fa4681400b4c059431ad69233e6a3e5799a
[ "MIT" ]
136
2015-07-15T12:49:36.000Z
2022-03-24T12:30:25.000Z
src/_DrawableMatte.cpp
veryhappythings/pgmagick
5dce5fa4681400b4c059431ad69233e6a3e5799a
[ "MIT" ]
59
2015-12-28T21:40:37.000Z
2022-03-31T13:11:50.000Z
src/_DrawableMatte.cpp
veryhappythings/pgmagick
5dce5fa4681400b4c059431ad69233e6a3e5799a
[ "MIT" ]
33
2015-12-04T08:00:07.000Z
2022-01-28T23:39:25.000Z
#include <boost/python.hpp> #include <boost/cstdint.hpp> #include <Magick++/Drawable.h> #include <Magick++.h> using namespace boost::python; namespace { struct Magick_DrawableMatte_Wrapper: Magick::DrawableMatte { Magick_DrawableMatte_Wrapper(PyObject* py_self_, double p0, double p1, Magick::PaintMethod p2): Magick::DrawableMatte(p0, p1, p2), py_self(py_self_) {} PyObject* py_self; }; } void __DrawableMatte() { class_< Magick::DrawableMatte, bases<Magick::DrawableBase>, boost::noncopyable, Magick_DrawableMatte_Wrapper >("DrawableMatte", init< double, double, Magick::PaintMethod >()) .def("x", (void (Magick::DrawableMatte::*)(double) )&Magick::DrawableMatte::x) .def("x", (double (Magick::DrawableMatte::*)() const)&Magick::DrawableMatte::x) .def("y", (void (Magick::DrawableMatte::*)(double) )&Magick::DrawableMatte::y) .def("y", (double (Magick::DrawableMatte::*)() const)&Magick::DrawableMatte::y) .def("paintMethod", (void (Magick::DrawableMatte::*)(Magick::PaintMethod) )&Magick::DrawableMatte::paintMethod) .def("paintMethod", (Magick::PaintMethod (Magick::DrawableMatte::*)() const)&Magick::DrawableMatte::paintMethod) ; }
34.857143
178
0.688525
veryhappythings
196f7e48086742ca2f3d80e64272b0f92a8f4057
4,298
cpp
C++
test/unittest/compiler/unittest_interpreter.cpp
gichan-jang/nntrainer
273ca7d6ecb3077d93539b81a9d9340e0c1dc812
[ "Apache-2.0" ]
null
null
null
test/unittest/compiler/unittest_interpreter.cpp
gichan-jang/nntrainer
273ca7d6ecb3077d93539b81a9d9340e0c1dc812
[ "Apache-2.0" ]
2
2021-04-19T11:42:07.000Z
2021-04-21T10:26:04.000Z
test/unittest/compiler/unittest_interpreter.cpp
gichan-jang/nntrainer
273ca7d6ecb3077d93539b81a9d9340e0c1dc812
[ "Apache-2.0" ]
null
null
null
// SPDX-License-Identifier: Apache-2.0 /** * Copyright (C) 2021 Jihoon Lee <[email protected]> * * @file unittest_interpreter.cpp * @date 02 April 2021 * @brief interpreter test * @see https://github.com/nnstreamer/nntrainer * @author Jihoon Lee <[email protected]> * @bug No known bugs except for NYI items */ #include <functional> #include <gtest/gtest.h> #include <memory> #include <app_context.h> #include <ini_interpreter.h> #include <interpreter.h> #include <layer.h> #include <nntrainer_test_util.h> using LayerReprentation = std::pair<std::string, std::vector<std::string>>; auto &ac = nntrainer::AppContext::Global(); static std::shared_ptr<nntrainer::GraphRepresentation> makeGraph(const std::vector<LayerReprentation> &layer_reps) { auto graph = std::make_shared<nntrainer::GraphRepresentation>(); for (const auto &layer_representation : layer_reps) { std::shared_ptr<ml::train::Layer> layer = ac.createObject<ml::train::Layer>( layer_representation.first, layer_representation.second); graph->addLayer(std::static_pointer_cast<nntrainer::Layer>(layer)); } return graph; } const std::string pathResolver(const std::string &path) { return getResPath(path, {"test", "test_models", "models"}); } auto ini_interpreter = std::make_shared<nntrainer::IniGraphInterpreter>(ac, pathResolver); /** * @brief nntrainer Interpreter Test setup * * @note Proposing an evolutional path of current test * 1. A reference graph vs given paramter * 2. A reference graph vs list of models * 3. A reference graph vs (pick two models) a -> b -> a graph, b -> a -> b * graph */ class nntrainerInterpreterTest : public ::testing::TestWithParam< std::tuple<std::shared_ptr<nntrainer::GraphRepresentation>, const char *, std::shared_ptr<nntrainer::GraphInterpreter>>> { protected: virtual void SetUp() { auto params = GetParam(); reference = std::get<0>(params); file_path = pathResolver(std::get<1>(params)); interpreter = std::move(std::get<2>(params)); } std::shared_ptr<nntrainer::GraphRepresentation> reference; std::shared_ptr<nntrainer::GraphInterpreter> interpreter; std::string file_path; }; /** * @brief Check two compiled graph is equal * @note later this will be more complicated (getting N graph and compare each * other) * */ TEST_P(nntrainerInterpreterTest, graphEqual) { std::cerr << "testing " << file_path << '\n'; int status = reference->compile(nntrainer::LossType::LOSS_NONE); EXPECT_EQ(status, ML_ERROR_NONE); auto g = interpreter->deserialize(file_path); /// @todo: change this to something like graph::finalize status = g->compile(nntrainer::LossType::LOSS_NONE); EXPECT_EQ(status, ML_ERROR_NONE); /// @todo: make a graph equal /// 1. having same number of nodes /// 2. layer name is identical (this is too strict though) /// 3. attributes of layer is identical // EXPECT_EQ(*graph, *interpreter->deserialize(file_path)); auto layers = g->getLayers(); auto ref_layers = reference->getLayers(); EXPECT_EQ(layers.size(), ref_layers.size()); if (layers.size() == ref_layers.size()) { for (auto &layer : layers) { std::shared_ptr<nntrainer::Layer> ref_layer; EXPECT_NO_THROW(ref_layer = reference->getLayer(layer->getName())); /// @todo: layer->getProperties() and do check on each properties } } } auto fc0 = LayerReprentation("fully_connected", {"name=fc0", "unit=1", "input_shape=1:1:100"}); auto flatten = LayerReprentation("flatten", {"name=flat"}); /** * @brief make ini test case from given parameter */ static std::tuple<std::shared_ptr<nntrainer::GraphRepresentation>, const char *, std::shared_ptr<nntrainer::GraphInterpreter>> mkTc(std::shared_ptr<nntrainer::GraphRepresentation> graph, const char *file, std::shared_ptr<nntrainer::GraphInterpreter> interpreter) { return std::make_tuple(graph, file, interpreter); } // clang-format off INSTANTIATE_TEST_CASE_P(nntrainerAutoInterpreterTest, nntrainerInterpreterTest, ::testing::Values( mkTc(makeGraph({fc0, flatten}), "simple_fc.ini", ini_interpreter), mkTc(makeGraph({fc0, flatten}), "simple_fc_backbone.ini", ini_interpreter) )); // clang-format on
31.837037
80
0.701489
gichan-jang
197055abf1559514dd02c0f191b0e2957efbd748
2,495
cpp
C++
Source/Graphics/Renderer/Renderer.cpp
narendraumate/Sandbox
7b7cef7a1876bfa3cfe2c79ff5e6daede1d50b13
[ "MIT" ]
null
null
null
Source/Graphics/Renderer/Renderer.cpp
narendraumate/Sandbox
7b7cef7a1876bfa3cfe2c79ff5e6daede1d50b13
[ "MIT" ]
null
null
null
Source/Graphics/Renderer/Renderer.cpp
narendraumate/Sandbox
7b7cef7a1876bfa3cfe2c79ff5e6daede1d50b13
[ "MIT" ]
null
null
null
// // Renderer.cpp // // // Created by Narendra Umate on 9/7/13. // // #include "Renderer.h" Renderer::Renderer(const int& width, const int& height) : m_width(width) , m_height(height) , m_clearColor(Color4f(0.5f, 0.5f, 0.5f, 1.0f)) , m_clearDepth(1.0f) , m_clearStencil(1) { } Renderer::~Renderer() { m_width = 0; m_height = 0; } void Renderer::setNdcMatrix(const Mat4& matrix) { m_ndcMatrix = matrix; } Mat4 Renderer::getNdcMatrix() { return m_ndcMatrix; } void Renderer::setProjectionRange(const ProjectionRange& range) { m_projectionRange = range; } ProjectionRange Renderer::getProjectionRange() { return m_projectionRange; } void Renderer::setWidth(const int& width) { m_width = width; } int Renderer::getWidth() { return m_width; } void Renderer::setHeight(const int& height) { m_height = height; } int Renderer::getHeight() { return m_height; } void Renderer::draw(Bvh* bvh, VisualEffect* visualEffect, VisualMaterial* visualMaterial, const Mat4& worldMatrix, const Mat4& viewMatrix, const Mat4& viewProjectionMatrix, const Vec3& lightCoefficients, const Vec3& lightColor, const Vec3& lightPosition, const Vec3& eyePosition) { // Draw your self. draw(bvh->getBoundingBox(), visualEffect, visualMaterial, worldMatrix, viewMatrix, viewProjectionMatrix, lightCoefficients, lightColor, lightPosition, eyePosition); // Draw your children. int childCount = bvh->getChildCount(); if (childCount) { for (int childIndex = 0; childIndex < childCount; ++childIndex) { draw(bvh->getChild(childIndex), visualEffect, visualMaterial, worldMatrix, viewMatrix, viewProjectionMatrix, lightCoefficients, lightColor, lightPosition, eyePosition); } } } void Renderer::draw(Octree* octree, VisualEffect* visualEffect, VisualMaterial* visualMaterial, const Mat4& worldMatrix, const Mat4& viewMatrix, const Mat4& viewProjectionMatrix, const Vec3& lightCoefficients, const Vec3& lightColor, const Vec3& lightPosition, const Vec3& eyePosition) { // Draw your self. draw(octree->getBoundingBox(), visualEffect, visualMaterial, worldMatrix, viewMatrix, viewProjectionMatrix, lightCoefficients, lightColor, lightPosition, eyePosition); // Draw your children. int childCount = octree->getChildCount(); if (childCount) { for (int childIndex = 0; childIndex < childCount; ++childIndex) { draw(octree->getChild(childIndex), visualEffect, visualMaterial, worldMatrix, viewMatrix, viewProjectionMatrix, lightCoefficients, lightColor, lightPosition, eyePosition); } } }
30.802469
287
0.755511
narendraumate
197bac971e6f7d5e47fce66bdb276fe36a3542d7
930
cpp
C++
gtfo_testing/runtime/algorithm/count_if.cpp
TMorozovsky/Generic_Tools_for_Frequent_Operations
bbc6804e1259f53a84375316cddeb9b648359c28
[ "MIT" ]
1
2016-01-09T09:57:55.000Z
2016-01-09T09:57:55.000Z
gtfo_testing/runtime/algorithm/count_if.cpp
TMorozovsky/Generic_Tools_for_Frequent_Operations
bbc6804e1259f53a84375316cddeb9b648359c28
[ "MIT" ]
null
null
null
gtfo_testing/runtime/algorithm/count_if.cpp
TMorozovsky/Generic_Tools_for_Frequent_Operations
bbc6804e1259f53a84375316cddeb9b648359c28
[ "MIT" ]
null
null
null
#include "gtfo/algorithm/count_if.hpp" #include "gtfo_testing/runtime/runtime_tests.hpp" using namespace gtfo::runtime_test_helpers; namespace { struct Foo { int x; Foo() : x(42) { } explicit Foo(int x) : x(x) { } }; class Bool { private: bool _value; public: explicit Bool(bool value) : _value(value) { } operator bool() const { return _value; } }; class Pred { private: int _x; public: explicit Pred(int x) : _x(x) { } Bool operator()(const Foo & foo) const { return Bool(foo.x == _x); } }; } using gtfo::count_if; GTFO_TEST_FUN_BEGIN Foo arr[10]; arr[3].x = 10; arr[5].x = 10; arr[8].x = 10; // two iterators + value GTFO_TEST_ASSERT_EQ(count_if(arr, arr + 10, Pred(42)), 7) // range + value GTFO_TEST_ASSERT_EQ(count_if(rev(arr), Pred(10)), 3) GTFO_TEST_FUN_END
19.375
76
0.569892
TMorozovsky
1987a2b4d96cf43b2be6d2b61e9ee7692691c499
9,723
cpp
C++
ButiEngine_User/StageSelect.cpp
butibuti/CatchTheMoney
9f80d13b753b9b62709f36ae5dbd1d5f549c5d2e
[ "MIT" ]
null
null
null
ButiEngine_User/StageSelect.cpp
butibuti/CatchTheMoney
9f80d13b753b9b62709f36ae5dbd1d5f549c5d2e
[ "MIT" ]
null
null
null
ButiEngine_User/StageSelect.cpp
butibuti/CatchTheMoney
9f80d13b753b9b62709f36ae5dbd1d5f549c5d2e
[ "MIT" ]
null
null
null
#include "stdafx_u.h" #include "StageSelect.h" #include "ParentSelectPanel.h" #include "InputManager.h" #include "SelectScreen.h" #include "ShakeComponent.h" #include "SelectPlayer.h" #include "SceneChangeAnimation.h" #include "GameSettings.h" #include"PauseManager.h" #include"Header/GameObjects/DefaultGameComponent/OutlineDrawComponent.h" int ButiEngine::StageSelect::stageNum = 0; int ButiEngine::StageSelect::maxStageNum = 19; //LastStageNum - 1 std::string ButiEngine::StageSelect::removeStageName = "none"; bool ButiEngine::StageSelect::isAnimation; int count=0; const float angle = 360.0f / (float)(ButiEngine::StageSelect::maxStageNum + 1) * 2.0f; void ButiEngine::StageSelect::OnUpdate() { Onece(); const auto childAngle = 180.0f / (ButiEngine::StageSelect::maxStageNum + 1) * 2.0f; auto parentSelectPanel = wkp_parentSelectPanel.lock()->GetGameComponent<ParentSelectPanel>(); if (intervalFrame > 20 && !isAnimation) { if (InputManager::OnPushRightKey() && !shp_pauseManager->IsPause()) { count++; intervalFrame = 0; OnPushRight(); parentSelectPanel->ChildRotation(-childAngle,stageNum); auto screen = GetManager().lock()->GetGameObject("SelectScreen").lock(); screen->GetGameComponent<ShakeComponent>()->ShakeStart(20.0f); std::string materialSource = "stage_"; if (stageNum<10) { materialSource += "0"; } screen->GetGameComponent<OutlineMeshDrawComponent>()->SetMaterialTag(MaterialTag(materialSource + std::to_string(stageNum)), 0); screen->GetGameComponent<OutlineMeshDrawComponent>()->ReRegist(); } else if (InputManager::OnPushLeftKey() && !shp_pauseManager->IsPause()) { count++; intervalFrame = 0; OnPushLeft(); parentSelectPanel->ChildRotation(childAngle,stageNum); auto screen = GetManager().lock()->GetGameObject("SelectScreen").lock(); screen->GetGameComponent<ShakeComponent>()->ShakeStart(20.0f); std::string materialSource = "stage_"; if (stageNum < 10) { materialSource += "0"; } screen->GetGameComponent<OutlineMeshDrawComponent>()->SetMaterialTag(MaterialTag(materialSource + std::to_string(stageNum)),0); screen->GetGameComponent<OutlineMeshDrawComponent>()->ReRegist(); } if (InputManager::OnSkipKey() && !shp_pauseManager->IsPause()) { count++; intervalFrame = 0; OnPushSkip(); parentSelectPanel->ChildRotation(-childAngle * ((maxStageNum + 1) / 2),stageNum); auto screen = GetManager().lock()->GetGameObject("SelectScreen").lock(); screen->GetGameComponent<ShakeComponent>()->ShakeStart(20.0f); std::string materialSource = "stage_"; if (stageNum < 10) { materialSource += "0"; } screen->GetGameComponent<OutlineMeshDrawComponent>()->SetMaterialTag(MaterialTag(materialSource + std::to_string(stageNum)),0); screen->GetGameComponent<OutlineMeshDrawComponent>()->ReRegist(); } } else { intervalFrame++; } DecisionAnimation(); SelectRotation(); } void ButiEngine::StageSelect::OnSet() { } void ButiEngine::StageSelect::Start() { shp_pauseManager = GetManager().lock()->GetGameObject("PauseManager").lock()->GetGameComponent<PauseManager>(); GameSettings::isStageSelect = true; isOnece = false; isAnimation = false; animationFrame = 90; intervalFrame = 0; fadeCount = 0; wkp_parentSelectPanel = GetManager().lock()->GetGameObject("ParentSelectPanel"); wkp_animationPlayer = GetManager().lock()->AddObjectFromCereal("AnimationPlayer"); wkp_fadeObject = GetManager().lock()->AddObjectFromCereal("FadeObject", ObjectFactory::Create<Transform>(Vector3(0, 0, -0.01), Vector3::Zero, Vector3(2112, 1188, 1))); preParentRotation = stageNum * angle; auto sceneManager = gameObject.lock()->GetApplication().lock()->GetSceneManager(); if (stageNum <= 0) { std::string sceneName = "Stage" + std::to_string(maxStageNum); sceneManager->RemoveScene(sceneName); } else { int preStageNum = stageNum - 1; std::string sceneName = "Stage" + std::to_string(preStageNum); sceneManager->RemoveScene(sceneName); } se_enter = SoundTag("Sound/Enter.wav"); se_select = SoundTag("Sound/Select-Click.wav"); se_dash = SoundTag("Sound/Rat_Dash.wav"); se_hit = SoundTag("Sound/Rat_Hit.wav"); se_start = SoundTag("Sound/Rat_Start.wav"); bgm = SoundTag("Sound/BGM2.wav"); GetManager().lock()->GetApplication().lock()->GetSoundManager()->StopBGM(); GetManager().lock()->GetApplication().lock()->GetSoundManager()->PlayBGM(bgm, GameSettings::masterVolume + 0.5f); auto screen = GetManager().lock()->GetGameObject("SelectScreen").lock(); std::string materialSource = "stage_"; if (stageNum < 10) { materialSource += "0"; } screen->GetGameComponent<OutlineMeshDrawComponent>()->SetMaterialTag(MaterialTag(materialSource + std::to_string(stageNum)), 0); screen->GetGameComponent<OutlineMeshDrawComponent>()->ReRegist(); GetManager().lock()->GetApplication().lock() ->GetGraphicDevice()->SetClearColor(Vector4((250.0f / 255.0f), (254.0f / 255.0f), (255.0f / 255.0f), 1.0f)); } void ButiEngine::StageSelect::OnShowUI() { } void ButiEngine::StageSelect::ShowGUI() { GUI::Begin("AnimationFrame"); GUI::Text(animationFrame); GUI::End(); GUI::Begin("StageNum"); GUI::BulletText("StageNum"); GUI::Text(stageNum); GUI::BulletText("Count"); GUI::Text(count); GUI::End(); } void ButiEngine::StageSelect::OnCollision(std::weak_ptr<GameObject> arg_other) { } std::shared_ptr<ButiEngine::GameComponent> ButiEngine::StageSelect::Clone() { return ObjectFactory::Create<StageSelect>(); } void ButiEngine::StageSelect::SetStageNum(int arg_stageNum) { stageNum = arg_stageNum; if (stageNum > maxStageNum) { stageNum = 0; } } void ButiEngine::StageSelect::SetRemoveStageName(std::string arg_removeStageName) { removeStageName = arg_removeStageName; } void ButiEngine::StageSelect::OnPushRight() { GetManager().lock()->GetApplication().lock()->GetSoundManager()->PlaySE(se_select, GameSettings::masterVolume); stageNum++; if (stageNum > maxStageNum) { stageNum = 0; } preParentRotation = angle * stageNum; } void ButiEngine::StageSelect::OnPushLeft() { GetManager().lock()->GetApplication().lock()->GetSoundManager()->PlaySE(se_select, GameSettings::masterVolume); stageNum--; if (stageNum < 0) { stageNum = maxStageNum; } preParentRotation = angle * stageNum; } void ButiEngine::StageSelect::OnPushSkip() { GetManager().lock()->GetApplication().lock()->GetSoundManager()->PlaySE(se_select, GameSettings::masterVolume); stageNum += (maxStageNum + 1) / 2; if (stageNum > maxStageNum) { stageNum = stageNum - maxStageNum - 1; } preParentRotation = angle * stageNum; } void ButiEngine::StageSelect::OnDecision() { GameSettings::isStageSelect = false; isAnimation = false; auto sceneManager = gameObject.lock()->GetApplication().lock()->GetSceneManager(); std::string sceneName = "Stage" + std::to_string(stageNum); sceneManager->RemoveScene(sceneName); sceneManager->LoadScene(sceneName); sceneManager->ChangeScene(sceneName); } void ButiEngine::StageSelect::DecisionAnimation() { if (InputManager::OnTriggerDecisionKey() && !isAnimation && !shp_pauseManager->IsPause()) { GetManager().lock()->GetApplication().lock()->GetSoundManager()->PlaySE(se_enter, GameSettings::masterVolume); isAnimation = true; } if (!isAnimation) return; if (animationFrame == screenRotateFrame) { GetManager().lock()->GetGameObject("SelectScreen").lock()->GetGameComponent<SelectScreen>()->StartAnimation(); } const int START_FRAME = 89; const int ZANZO_FRAME = 60; const int FLASH_FRAME = 40; const int AWAY_FRAME = 35; if (animationFrame == START_FRAME) { wkp_animationPlayer.lock()->GetGameComponent<SelectPlayer>()->Decision(); } else if (animationFrame == ZANZO_FRAME) { GetManager().lock()->GetApplication().lock()->GetSoundManager()->PlaySE(se_dash, GameSettings::masterVolume); GetManager().lock()->GetApplication().lock()->GetSoundManager()->PlaySE(se_start, GameSettings::masterVolume); GetManager().lock()->AddObjectFromCereal("SelectZanzo"); } else if (animationFrame == FLASH_FRAME) { GetManager().lock()->AddObjectFromCereal("SelectFlash"); GetManager().lock()->GetApplication().lock()->GetSoundManager()->PlaySE(se_hit, GameSettings::masterVolume); GetManager().lock()->GetApplication().lock()->GetSoundManager()->PlaySE(se_dash, GameSettings::masterVolume); } else if (animationFrame == AWAY_FRAME) { wkp_animationPlayer.lock()->GetGameComponent<SelectPlayer>()->Away(); } if (animationFrame <= 0) { isNext = true; } if (isNext) { fadeCount++; } if (fadeCount == 1) { GetManager().lock()->AddObjectFromCereal("FadeObject", ObjectFactory::Create<Transform>(Vector3(0, 1134, -0.01), Vector3::Zero, Vector3(2112, 1188, 1))); } const int NEXT_SCENE_COUNT = 30; if (fadeCount > NEXT_SCENE_COUNT) { OnDecision(); } if (animationFrame > 0) { animationFrame--; } } void ButiEngine::StageSelect::SelectRotation() { auto anim = wkp_parentSelectPanel.lock()->GetGameComponent<TransformAnimation>(); if (!anim) { anim = wkp_parentSelectPanel.lock()->AddGameComponent<TransformAnimation>(); anim->SetTargetTransform(wkp_parentSelectPanel.lock()->transform->Clone()); anim->GetTargetTransform()->SetLocalRotation(Matrix4x4::RollY(MathHelper::ToRadian( preParentRotation))); anim->SetSpeed(0.1f); anim->SetEaseType(Easing::EasingType::EaseOut); } } void ButiEngine::StageSelect::Onece() { if (isOnece) return; isOnece = true; auto parentSelectPanel = wkp_parentSelectPanel.lock()->GetGameComponent<ParentSelectPanel>(); auto childAngle = 180.0f / (maxStageNum + 1) * 2.0f; float rotate = childAngle * stageNum; preParentRotation = stageNum * angle; parentSelectPanel->ChildRotation(-rotate,stageNum); }
30.28972
168
0.724673
butibuti
198afa841e2b4b299cfac1ee12484b0c5f49e1f8
7,593
cpp
C++
editor/mainwindow.cpp
ErrrOrrr503/DOORkaEngine
90084cc622b1bcc021d9c3de5ccb52b349d4217e
[ "WTFPL" ]
null
null
null
editor/mainwindow.cpp
ErrrOrrr503/DOORkaEngine
90084cc622b1bcc021d9c3de5ccb52b349d4217e
[ "WTFPL" ]
null
null
null
editor/mainwindow.cpp
ErrrOrrr503/DOORkaEngine
90084cc622b1bcc021d9c3de5ccb52b349d4217e
[ "WTFPL" ]
null
null
null
#include "mainwindow.h" #include "ui_mainwindow.h" MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); ui->console->setReadOnly(true); ui->texture_label->clear(); ogl_layout = new QHBoxLayout(ui->frame_ogl); ogl_layout->setContentsMargins(0, 0, 0, 0); ogl_layout->setSpacing(0); ogl_out = new oGL_out(ui->frame_ogl, &level); ogl_layout->addWidget(ogl_out); ogl_out->show(); QObject::connect(ogl_out, &oGL_out::print_console, this, &MainWindow::print_console); QObject::connect(&level, &Level::print_console, this, &MainWindow::print_console); QObject::connect(this, &MainWindow::ogl_change_mode, ogl_out, &oGL_out::ogl_change_mode); change_mode(draw_clipping_mode); print_console("Ready"); } MainWindow::~MainWindow() { delete ui; delete ogl_out; delete ogl_layout; outfile.close(); } void MainWindow::on_drawButton_clicked() { change_mode (draw_mode); } void MainWindow::on_selectButton_clicked() { change_mode (sel_mode); } void MainWindow::on_unselButton_clicked() { change_mode (unsel_mode); } void MainWindow::on_clippingButton_clicked() { change_mode (draw_clipping_mode); } void MainWindow::on_setPosButton_clicked() { change_mode (set_pos_mode); } void MainWindow::print_console (const std::string &s) { ui->console->insertPlainText ("["); ui->console->insertPlainText (QTime::currentTime().toString("h:m:s")); ui->console->insertPlainText ("]> "); ui->console->insertPlainText (QString::fromStdString (s)); ui->console->insertPlainText ("\n"); ui->console->ensureCursorVisible (); } void MainWindow::change_mode (edit_mode in_mode) { mode = in_mode; std::string console = "switched to "; switch (in_mode) { case draw_mode: console += "'draw'"; ui->text_tool->setText ("draw"); ui->drawButton->setDown (1); ui->clippingButton->setDown (0); ui->selectButton->setDown (0); ui->unselButton->setDown (0); ui->setPosButton->setDown (0); break; case draw_clipping_mode: console += "'draw_clipping'"; ui->text_tool->setText ("clip"); ui->drawButton->setDown (0); ui->clippingButton->setDown (1); ui->selectButton->setDown (0); ui->unselButton->setDown (0); ui->setPosButton->setDown (0); break; case sel_mode: console += "'select'"; ui->text_tool->setText ("select"); ui->drawButton->setDown (0); ui->clippingButton->setDown (0); ui->selectButton->setDown (1); ui->unselButton->setDown (0); ui->setPosButton->setDown (0); break; case unsel_mode: console += "'unselect'"; ui->text_tool->setText ("unsel"); ui->drawButton->setDown (0); ui->clippingButton->setDown (0); ui->selectButton->setDown (0); ui->unselButton->setDown (1); ui->setPosButton->setDown (0); break; case set_pos_mode: console += "'set player position'"; ui->text_tool->setText ("setPos"); ui->drawButton->setDown (0); ui->clippingButton->setDown (0); ui->selectButton->setDown (0); ui->unselButton->setDown (0); ui->setPosButton->setDown (1); default: break; } console += " mode"; #ifdef DEBUG_MISC print_console(console); #endif emit ogl_change_mode(in_mode); } void MainWindow::on_actionSave_triggered() { if (outfile.is_open ()) { outfile.close (); outfile.open (outfilename, outfile.binary | outfile.out | outfile.trunc); //truncate if (!outfile.is_open()) { print_console ("failed to truncate file while saving"); return; } level.save_level (outfile); } else { open_file_dialog (save); } } void MainWindow::on_actionLoad_triggered () { if (0){ //fixme::unsaved dialog } else { open_file_dialog (load); } } void MainWindow::on_actionDelete_wall_triggered () { print_console ("sorry from v0.hz deletion is unsuported due to triangles. No money, but hold on, best wishes, good mood..."); //level.delete_wall (); //ogl_out->update (); } void MainWindow::open_file_dialog (flag_saveload flag) { opendialog = new OpenDialog(this, flag); QObject::connect(opendialog, &OpenDialog::filename_read, this, &MainWindow::on_opendialog_finish); opendialog->show(); } void MainWindow::on_opendialog_finish(const std::string &filename, flag_saveload flag) { outfilename = filename; std::string console; console = "opening for "; if (flag == save) console += "save '"; else console += "load '"; console += filename; console += "' "; if (!std::filesystem::exists(filename) && flag == load){ // if no file to load console += "FAILED: check existing"; print_console (console); return; } //file exists if (flag == save) { outfile.open(filename, outfile.binary | outfile.out | outfile.trunc); if (!outfile.is_open()) { print_console(console + "FAILED"); return; } print_console(console + "SUCCESS"); level.save_level (outfile); } if (flag == load) { std::ifstream infile; infile.open(filename, infile.binary | infile.in); if (!infile.is_open()) { print_console(console + "FAILED for read"); return; } if (level.load_level (infile)) { infile.close (); print_console (console + "SUCCESS for read"); print_console ("level loading failed!"); return; } infile.close (); outfile.open(filename, outfile.binary | outfile.out | outfile.in); if (!outfile.is_open()) { print_console(console + "FAILED for write"); return; } print_console (console += "SUCCESS"); ogl_out->update (); } } void MainWindow::on_trig_sideButton_clicked() { if (level.trig_side_mode == both_sides) { level.trig_side_mode = one_side; ui->trig_sideButton->setDown (1); } else { level.trig_side_mode = both_sides; ui->trig_sideButton->setDown (0); } } void MainWindow::on_colorButoon_clicked() { QColorDialog *colordialog = new QColorDialog (this); QObject::connect(colordialog, &QColorDialog::colorSelected, this, &MainWindow::on_color_selected); colordialog->show(); } void MainWindow::on_color_selected (const QColor &newcolor) { level.wall_color[0] = newcolor.redF (); level.wall_color[1] = newcolor.greenF (); level.wall_color[2] = newcolor.blueF (); level.cur_texture_index = -1; ui->texture_label->clear (); } void MainWindow::on_actionRevert_chandes_triggered() { print_console ("ctrlz"); level.ctrl_z (); ogl_out->update (); } void MainWindow::on_sel_textureButton_clicked() { std::string tex_filename = QFileDialog::getOpenFileName (this, "Open level", "./textures").toUtf8 ().constData (); size_t last_slash_idx = tex_filename.find_last_of("\\/"); if (std::string::npos != last_slash_idx) { tex_filename.erase(0, last_slash_idx + 1); } level.select_texture (tex_filename); ui->texture_label->clear (); ui->texture_label->setText (QString::fromStdString (tex_filename)); }
28.226766
129
0.613591
ErrrOrrr503
198d0718efc73c0de5a00ae19fa727d5b91c2511
466
cpp
C++
cpp1st/week08/taehwan/example_regex_error.cpp
th4inquiry/PentaDevs
aa379d24494a485ad5e7fdcc385c6ccfb02cf307
[ "Apache-2.0" ]
2
2022-03-10T10:18:23.000Z
2022-03-16T15:37:22.000Z
cpp1st/week08/taehwan/example_regex_error.cpp
th4inquiry/PentaDevs
aa379d24494a485ad5e7fdcc385c6ccfb02cf307
[ "Apache-2.0" ]
8
2022-03-09T16:14:47.000Z
2022-03-28T15:35:17.000Z
cpp1st/week08/taehwan/example_regex_error.cpp
th4inquiry/PentaDevs
aa379d24494a485ad5e7fdcc385c6ccfb02cf307
[ "Apache-2.0" ]
4
2022-03-08T00:22:29.000Z
2022-03-12T13:22:43.000Z
/// /// Copyright 2022 PentaDevs /// Author: Taehwan Kim /// Contents: Examples of regex_error (referenced from CppReference) #include <regex> #include <iostream> int main() { try { std::regex re("[a-b][a"); } catch (const std::regex_error& e) { std::cout << "regex_error caught: " << e.what() << '\n'; if (e.code() == std::regex_constants::error_brack) { std::cout << "The code was error_brack\n"; } } }
23.3
68
0.564378
th4inquiry
199034cd2c78220b6d27610356901fd7f2406bb0
1,685
cpp
C++
G53GRA.Framework/Code/Sky.cpp
baisebaoma/COMP3069CW
731627a4d5d961435f3c4064e2c789db6a70423a
[ "MIT" ]
null
null
null
G53GRA.Framework/Code/Sky.cpp
baisebaoma/COMP3069CW
731627a4d5d961435f3c4064e2c789db6a70423a
[ "MIT" ]
null
null
null
G53GRA.Framework/Code/Sky.cpp
baisebaoma/COMP3069CW
731627a4d5d961435f3c4064e2c789db6a70423a
[ "MIT" ]
null
null
null
#include "Sky.hpp" #include <iostream> #include <cmath> // TODO: 现在是全写在Sky里,到时候得分开成各个东西。(refactor) #include <stdio.h> #include <stdlib.h> // MAKE SURE WE INITIALISE OUR VARIABLES Sky::Sky() : keyframe(-1), animateTime(0.0), animateRotation(0.0), animateTranslation(0.0), interpA(0.0), interpB(0.0), interpTime(0.0){} Sky::Sky(const std::string& filename) : Sky() { texID = Scene::GetTexture(filename); } /// Update the Skys position in releation to delta time by use of mathematical /// mechanics, eq SUVAT void Sky::Update(const double& deltaTime) { // update the time and rotation steps animateTime += static_cast<float>(deltaTime); // animateRotation = animateTime*10;// animateRotation += static_cast<float>(deltaTime); } void Sky::drawPlane(GLfloat R, GLfloat G, GLfloat B, GLfloat size){ glColor3f(R, G, B); glEnable(GL_TEXTURE_2D); // Enable setting the colour of the material the cube is made from // as well as the material for blending. // glEnable(GL_COLOR_MATERIAL); // Tell openGL which texture buffer to use glBindTexture(GL_TEXTURE_2D, texID); glBegin(GL_POLYGON); glTexCoord2f(1.0f, 1.0f); glVertex3f(-1*size, 0, -1*size); glTexCoord2f(1.0f, 0.0f); glVertex3f(-1*size, 0, 1*size); glTexCoord2f(0.0f, 0.0f); glVertex3f(size, 0, size); glTexCoord2f(0.0f, 1.0f); glVertex3f(size, 0, -1*size); glEnd(); glDisable(GL_TEXTURE_2D); } void Sky::Display(void){ glPushMatrix(); glRotatef(animateRotation,0,1,0); // Sky glPushMatrix(); glTranslatef(5, 0, 5); drawPlane(0.7f, 0.7f, 0.7f, 20); glPopMatrix(); glPopMatrix(); }
24.42029
95
0.659347
baisebaoma
19963cc8374e09c591274312c5cda381f5d7e39d
12,753
cc
C++
src/core/user_interface.cc
juliomarcelopicardo/Wolfy2D
34cf5afca05e1f1cf57ad7899152efe09391ac7b
[ "MIT" ]
null
null
null
src/core/user_interface.cc
juliomarcelopicardo/Wolfy2D
34cf5afca05e1f1cf57ad7899152efe09391ac7b
[ "MIT" ]
null
null
null
src/core/user_interface.cc
juliomarcelopicardo/Wolfy2D
34cf5afca05e1f1cf57ad7899152efe09391ac7b
[ "MIT" ]
null
null
null
/** Copyright Julio Marcelo Picardo 2017-18, all rights reserved. * * @project Wolfy2D - Including JMP scripting language. * @author Julio Marcelo Picardo <[email protected]> */ #include "core/user_interface.h" #include "GLFW/glfw3.h" #include "imgui.h" #include "imgui_dock.h" #include "core/core.h" #include <fstream> namespace W2D { /******************************************************************************* *** Constructor And Destructor *** *******************************************************************************/ UserInterface::UserInterface() { top_bar_height_ = 0.0f; bottom_bar_height_ = 30.0f; save_mode_ = 0; log_.set_active(true); } UserInterface::~UserInterface() {} /******************************************************************************* *** Public Methods *** *******************************************************************************/ void UserInterface::init() { setupInputKeys(); setupColors(); setupStyle(); setupUsersGuideText(); } void UserInterface::update() { updateTopBar(); updateEditorLayout(); updateBottomBar(); } /******************************************************************************* *** Private Methods *** *******************************************************************************/ void UserInterface::setupColors() const { ImVec4* colors = ImGui::GetStyle().Colors; colors[ImGuiCol_Text] = ImVec4(1.00f, 1.00f, 1.00f, 1.00f); colors[ImGuiCol_TextDisabled] = ImVec4(0.59f, 0.59f, 0.59f, 1.00f); colors[ImGuiCol_WindowBg] = ImVec4(0.06f, 0.06f, 0.06f, 1.00f); colors[ImGuiCol_ChildBg] = ImVec4(1.00f, 1.00f, 1.00f, 0.00f); colors[ImGuiCol_PopupBg] = ImVec4(0.08f, 0.08f, 0.08f, 0.94f); colors[ImGuiCol_Border] = ImVec4(0.43f, 0.43f, 0.50f, 1.00f); colors[ImGuiCol_BorderShadow] = ImVec4(0.00f, 0.00f, 0.00f, 0.00f); colors[ImGuiCol_FrameBg] = ImVec4(0.14f, 0.14f, 0.14f, 1.00f); colors[ImGuiCol_FrameBgHovered] = ImVec4(0.79f, 0.32f, 0.00f, 1.00f); colors[ImGuiCol_FrameBgActive] = ImVec4(0.79f, 0.32f, 0.00f, 0.78f); colors[ImGuiCol_TitleBg] = ImVec4(0.04f, 0.04f, 0.04f, 1.00f); colors[ImGuiCol_TitleBgActive] = ImVec4(0.16f, 0.29f, 0.48f, 1.00f); colors[ImGuiCol_TitleBgCollapsed] = ImVec4(0.00f, 0.00f, 0.00f, 0.51f); colors[ImGuiCol_MenuBarBg] = ImVec4(0.14f, 0.14f, 0.14f, 1.00f); colors[ImGuiCol_ScrollbarBg] = ImVec4(0.02f, 0.02f, 0.02f, 0.53f); 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.79f, 0.32f, 0.00f, 1.00f); colors[ImGuiCol_SliderGrab] = ImVec4(0.79f, 0.32f, 0.00f, 1.00f); colors[ImGuiCol_SliderGrabActive] = ImVec4(0.79f, 0.32f, 0.00f, 0.78f); colors[ImGuiCol_Button] = ImVec4(0.31f, 0.31f, 0.31f, 1.00f); colors[ImGuiCol_ButtonHovered] = ImVec4(0.79f, 0.32f, 0.00f, 1.00f); colors[ImGuiCol_ButtonActive] = ImVec4(0.79f, 0.32f, 0.00f, 0.78f); colors[ImGuiCol_Header] = ImVec4(0.41f, 0.41f, 0.41f, 1.00f); colors[ImGuiCol_HeaderHovered] = ImVec4(0.79f, 0.32f, 0.00f, 1.00f); colors[ImGuiCol_HeaderActive] = ImVec4(0.79f, 0.32f, 0.00f, 0.78f); colors[ImGuiCol_Separator] = ImVec4(0.79f, 0.32f, 0.00f, 1.00f); colors[ImGuiCol_SeparatorHovered] = ImVec4(0.79f, 0.32f, 0.00f, 1.00f); colors[ImGuiCol_SeparatorActive] = ImVec4(0.79f, 0.32f, 0.00f, 1.00f); colors[ImGuiCol_ResizeGrip] = ImVec4(0.79f, 0.32f, 0.00f, 1.00f); colors[ImGuiCol_ResizeGripHovered] = ImVec4(0.79f, 0.32f, 0.00f, 1.00f); colors[ImGuiCol_ResizeGripActive] = ImVec4(0.79f, 0.32f, 0.00f, 0.95f); colors[ImGuiCol_CloseButton] = ImVec4(0.92f, 1.00f, 0.00f, 1.00f); colors[ImGuiCol_CloseButtonHovered] = ImVec4(0.98f, 0.39f, 0.36f, 1.00f); colors[ImGuiCol_CloseButtonActive] = ImVec4(0.98f, 0.39f, 0.36f, 1.00f); colors[ImGuiCol_PlotLines] = ImVec4(0.92f, 1.00f, 0.00f, 1.00f); colors[ImGuiCol_PlotLinesHovered] = ImVec4(0.92f, 1.00f, 0.00f, 1.00f); colors[ImGuiCol_PlotHistogram] = ImVec4(0.92f, 1.00f, 0.00f, 1.00f); colors[ImGuiCol_PlotHistogramHovered] = ImVec4(0.92f, 1.00f, 0.00f, 1.00f); colors[ImGuiCol_TextSelectedBg] = ImVec4(0.79f, 0.32f, 0.00f, 1.00f); colors[ImGuiCol_ModalWindowDarkening] = ImVec4(0.92f, 1.00f, 0.00f, 1.00f); colors[ImGuiCol_DragDropTarget] = ImVec4(1.00f, 1.00f, 0.00f, 0.90f); } void UserInterface::setupInputKeys() const { ImGuiIO& io = ImGui::GetIO(); io.KeyMap[ImGuiKey_Tab] = GLFW_KEY_TAB; io.KeyMap[ImGuiKey_LeftArrow] = GLFW_KEY_LEFT; io.KeyMap[ImGuiKey_RightArrow] = GLFW_KEY_RIGHT; io.KeyMap[ImGuiKey_UpArrow] = GLFW_KEY_UP; io.KeyMap[ImGuiKey_DownArrow] = GLFW_KEY_DOWN; io.KeyMap[ImGuiKey_PageUp] = GLFW_KEY_PAGE_UP; io.KeyMap[ImGuiKey_PageDown] = GLFW_KEY_PAGE_DOWN; io.KeyMap[ImGuiKey_Home] = GLFW_KEY_HOME; io.KeyMap[ImGuiKey_End] = GLFW_KEY_END; io.KeyMap[ImGuiKey_Delete] = GLFW_KEY_DELETE; io.KeyMap[ImGuiKey_Backspace] = GLFW_KEY_BACKSPACE; io.KeyMap[ImGuiKey_Enter] = GLFW_KEY_ENTER; io.KeyMap[ImGuiKey_Escape] = GLFW_KEY_ESCAPE; io.KeyMap[ImGuiKey_A] = GLFW_KEY_A; io.KeyMap[ImGuiKey_C] = GLFW_KEY_C; io.KeyMap[ImGuiKey_V] = GLFW_KEY_V; io.KeyMap[ImGuiKey_X] = GLFW_KEY_X; io.KeyMap[ImGuiKey_Y] = GLFW_KEY_Y; io.KeyMap[ImGuiKey_Z] = GLFW_KEY_Z; } void UserInterface::setupStyle() const { ImGuiStyle& style = ImGui::GetStyle(); // Editor style style.FrameRounding = 6.0f; style.WindowRounding = 7.0f; style.ChildRounding = 0.0f; style.ScrollbarRounding = 9.0f; style.GrabRounding = 6.0f; style.PopupRounding = 16.0f; style.WindowPadding = { 8.0f, 8.0f }; style.FramePadding = { 4.0f, 3.0f }; style.TouchExtraPadding = { 0.0f, 0.0f }; style.ItemSpacing = { 8.0f, 4.0f }; style.ItemInnerSpacing = { 4.0f, 4.0f }; style.IndentSpacing = 24.0f; style.ScrollbarSize = 15.0f; style.GrabMinSize = 12.0f; style.WindowBorderSize = 1.0f; style.ChildBorderSize = 1.0f; style.PopupBorderSize = 1.0f; style.FrameBorderSize = 0.0f; style.WindowTitleAlign = { 0.0f, 0.5f }; style.ButtonTextAlign = { 0.5f, 0.5f }; } void UserInterface::setupUsersGuideText() { std::ifstream ug(kUsersGuideFilename); std::string temp{ std::istreambuf_iterator<char>(ug), std::istreambuf_iterator<char>() }; users_guide_text_ = temp; } void UserInterface::updateTopBar() { auto& core = Core::instance(); if (ImGui::BeginMainMenuBar()) { top_bar_height_ = ImGui::GetWindowSize().y; bottom_bar_height_ = top_bar_height_ + 8.0f; if (ImGui::BeginMenu("Application")) { if (ImGui::MenuItem("Quit", "ESC")) { core.window_.is_opened_ = false; } showLastItemDescriptionTooltip("Exit application and closes window"); ImGui::EndMenu(); } if (ImGui::BeginMenu("Editor")) { if (ImGui::MenuItem("Save Layout")) { ImGui::SaveDock(); log_.AddLog_I("Editor layout style saved."); } showLastItemDescriptionTooltip("Saves the editor layout in a configuration file.\n" "So next time that we execute the program, this last\n" "configuration saved will be loaded."); ImGui::EndMenu(); } ImGui::EndMainMenuBar(); } } void UserInterface::updateEditorLayout() { auto& core = Core::instance(); ImVec2 editor_size = ImGui::GetIO().DisplaySize; editor_size.y -= top_bar_height_ + bottom_bar_height_; ImGui::SetWindowPos("UserInterface", { 0.0f, top_bar_height_ }); ImGui::SetWindowSize("UserInterface", editor_size); const ImGuiWindowFlags window_flags = ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoMove; if (ImGui::Begin("UserInterface", nullptr, window_flags)) { // dock layout by hard-coded or .ini file ImGui::BeginDockspace(); updateSceneDock(); updateScriptDock(); updateHierarchyDock(); updateUsersGuideDock(); /* if (ImGui::BeginDock("EditorConfig")) { ImGui::ShowStyleEditor(); } ImGui::EndDock(); */ if (ImGui::BeginDock("Log")) { log_.Draw("Wolfy2D log"); } ImGui::EndDock(); ImGui::EndDockspace(); } ImGui::End(); } void UserInterface::updateBottomBar() const { const ImVec2 display_size = ImGui::GetIO().DisplaySize; const ImGuiWindowFlags flags = ImGuiWindowFlags_NoBringToFrontOnFocus | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoSavedSettings; ImGui::SetNextWindowPos({ 0.0f, display_size.y - bottom_bar_height_ }, ImGuiSetCond_Always); ImGui::SetNextWindowSize({ display_size.x, bottom_bar_height_ }, ImGuiSetCond_Always); ImGui::Begin("statusbar", nullptr, flags); ImGui::TextColored({ 202,81,0,255 }, "Wolfy2D & JMP - A Scripting Language for Game Engines"); ImGui::SameLine(); ImGui::Text(" "); ImGui::SameLine(); ImGui::Text("Author: Julio Marcelo Picardo Pena"); ImGui::SameLine(); ImGui::Text(" "); ImGui::SameLine(); ImGui::Text("Contact: [email protected]"); ImGui::SameLine(); ImGui::Text(" "); ImGui::SameLine(); ImGui::Text("BSc in Computer Science for Games - Sheffield Hallam University"); ImGui::SameLine(); ImGui::End(); } void UserInterface::updateHierarchyDock() const { if (ImGui::BeginDock("Scene Hierarchy")) { auto& map = Core::instance().sprite_factory_; for (const auto& pair : map) { ImGui::PushID(&pair.second); if (ImGui::TreeNode(pair.first.c_str())) { auto& sprite = map[pair.first]; ImGui::Image((ImTextureID)sprite.textureID(), { 50.0f, 50.0f }); glm::vec2 temp = sprite.position(); if (ImGui::DragFloat2("Position", &temp.x)) { sprite.set_position(temp); } temp = sprite.size(); if (ImGui::DragFloat2("Size", &temp.x)) { sprite.set_size(temp); } temp.x = sprite.rotation(); if (ImGui::DragFloat("Rotation", &temp.x, 0.01f)) { sprite.set_rotation(temp.x); } ImGui::TreePop(); } ImGui::PopID(); } } ImGui::EndDock(); } void UserInterface::updateScriptDock() { auto& core = Core::instance(); std::string text = "Compiles and executes the existing code"; if (ImGui::BeginDock("JMP Scripting Language")) { if (ImGui::Button("Compile")) { log_.AddLog_I("Compiling and executing script..."); core.texture_factory_.clear(); core.sprite_factory_.clear(); core.machine_.reloadFromString(core.script_code_); core.machine_.runFunction("Init()"); } showLastItemDescriptionTooltip(text.c_str()); ImGui::SameLine(); if (ImGui::Button("Save")) { if (save_mode_ == 0) { ImGui::SetClipboardText(core.script_code_); log_.AddLog_I("Script copied to clipboard."); } else { std::ofstream file(kScriptFilename, std::ios_base::out); if (file.is_open()) { file << core.script_code_; } file.close(); // log std::string info = "Script saved into file: \""; info = info + kScriptFilename; info = info + '\"'; log_.AddLog_I(info); } } text = "Save mode: \nClipbard - Will copy the whole script text into the clipboard\nFile - Save and overwrite file \""; text = text + kScriptFilename; text = text + '\"'; showLastItemDescriptionTooltip(text.c_str()); ImGui::SameLine(); ImGui::Combo("##destination", (int*)&save_mode_, "Clipboard\0File\0"); ImGui::InputTextMultiline("", Core::instance().script_code_, SCRIPT_CODE_MAX_LENGTH, ImGui::GetContentRegionAvail()); } ImGui::EndDock(); } void UserInterface::updateUsersGuideDock() const { if (ImGui::BeginDock("User's Guide")) { ImGui::TextUnformatted(users_guide_text_.c_str()); } ImGui::EndDock(); } void UserInterface::updateSceneDock() const { if (ImGui::BeginDock("Scene")) { ImGui::Image((ImTextureID)Core::instance().window_.frame_buffer_.texture(), ImGui::GetContentRegionAvail(), ImVec2(0, 1), ImVec2(1, 0)); } ImGui::EndDock(); } void UserInterface::showLastItemDescriptionTooltip(const char* description) const { if (ImGui::IsItemHovered()) { ImGui::BeginTooltip(); ImGui::PushTextWrapPos(ImGui::GetFontSize() * 35.0f); ImGui::TextUnformatted(description); ImGui::PopTextWrapPos(); ImGui::EndTooltip(); } } }; /* W2D */
35.035714
140
0.632165
juliomarcelopicardo
199b46ae2e5d531d246a12762b8d9930fa3aafba
7,620
cpp
C++
Data Structures/Heaps/Fibonacci Heap.cpp
Rand0mUsername/Algorithms
05ec0d7ed7f0a4d13000d9d77d743812ac9a27e0
[ "MIT" ]
2
2020-01-10T14:12:03.000Z
2020-05-28T19:12:21.000Z
Data Structures/Heaps/Fibonacci Heap.cpp
Rand0mUsername/algorithms
05ec0d7ed7f0a4d13000d9d77d743812ac9a27e0
[ "MIT" ]
null
null
null
Data Structures/Heaps/Fibonacci Heap.cpp
Rand0mUsername/algorithms
05ec0d7ed7f0a4d13000d9d77d743812ac9a27e0
[ "MIT" ]
1
2022-01-11T03:14:48.000Z
2022-01-11T03:14:48.000Z
// RandomUsername (Nikola Jovanovic) // Fibonacci Heap // Source: CLRS, Third Edition #include <algorithm> #include <cstdlib> #include <fstream> #include <iostream> #include <string> struct Node { Node* left; Node* right; Node* parent; Node* first_child; int key; int degree; bool marked; explicit Node(int key) { this -> key = key; this -> degree = 0; this -> parent = this -> first_child = NULL; this -> left = this -> right = this; this -> marked = false; } }; class FibonacciHeap { public: FibonacciHeap(); Node* FindMin(); void DeleteMin(); void Insert(Node* curr); void DecreaseKey(Node* curr, int new_key); void Merge(FibonacciHeap* h); int GetSize(); void Draw(std::string name); private: void LinkRootNodes(Node* top, Node* bottom); void MakeRootNode(Node* curr); void PrintToDot(Node* curr, std::ofstream& dot_file); Node* min_node; int size; }; FibonacciHeap::FibonacciHeap() { size = 0; min_node = NULL; } Node* FibonacciHeap::FindMin() { return min_node; } void FibonacciHeap::DeleteMin() { if (size == 0) { return; } if (size == 1) { delete min_node; min_node = NULL; size = 0; return; } Node* child = min_node -> first_child; int deg = min_node -> degree; for (int i = 0; i < deg; i++) { Node* next = child -> right; MakeRootNode(child); child = next; } int D = 2 * ceil(log2(size)); Node* tmp[D]; for (int i = 0; i < D; i++) { tmp[i] = NULL; } Node* curr = min_node -> right; while (curr != min_node) { Node* next = curr -> right; int deg = curr -> degree; while (tmp[deg] != NULL) { Node* other = tmp[deg]; if (curr -> key > other -> key) { std::swap(curr, other); } LinkRootNodes(curr, other); tmp[deg++] = NULL; } tmp[deg] = curr; curr = next; } delete min_node; // Rebuild the heap size--; Node* first; Node* last; first = last = min_node = NULL; for (int i = 0; i < D; i++) { if (tmp[i] != NULL) { if (first == NULL) { min_node = first = last = tmp[i]; } else { if (tmp[i] -> key < min_node -> key) { min_node = tmp[i]; } last -> right = tmp[i]; tmp[i] -> left = last; last = tmp[i]; } } } if (first != NULL) { last -> right = first; first -> left = last; } } void FibonacciHeap::Insert(Node* curr) { FibonacciHeap* unit_heap = new FibonacciHeap(); unit_heap -> min_node = curr; unit_heap -> size = 1; Merge(unit_heap); delete unit_heap; } void FibonacciHeap::DecreaseKey(Node* curr, int new_key) { curr -> key = new_key; Node* parent = curr -> parent; if (parent != NULL && curr -> key < parent -> key) { // Cut this child and update min node MakeRootNode(curr); curr -> marked = false; if (curr -> key < min_node -> key) { min_node = curr; } // Do a cascading cut curr = parent; while (curr != NULL && curr -> marked) { parent = curr -> parent; MakeRootNode(curr); curr -> marked = false; curr = parent; } if (curr != NULL && curr -> parent != NULL) { curr -> marked = true; } } else if (parent == NULL && curr -> key < min_node -> key) { min_node = curr; } } void FibonacciHeap::Merge(FibonacciHeap* other) { if (other -> size == 0) { return; } if (this -> size == 0) { this -> min_node = other -> min_node; } else { Node* this_right = this -> min_node -> right; Node* other_left = other -> min_node -> left; this -> min_node -> right = other -> min_node; other -> min_node -> left = this -> min_node; this_right -> left = other_left; other_left -> right = this_right; } this -> size += other -> size; } int FibonacciHeap::GetSize() { return size; } // Visualizes the heap using GraphViz. void FibonacciHeap::Draw(std::string name) { std::ofstream dot_file; dot_file.open(name + ".dot"); dot_file << "digraph{\n"; Node* root = min_node; if (root != NULL) { do { PrintToDot(root, dot_file); root = root -> right; } while (root != min_node); } dot_file << "}\n"; dot_file.close(); std::string command = "dot -Tpng " + name + ".dot -o " + name + ".png"; system(command.c_str()); } void FibonacciHeap::LinkRootNodes(Node* top, Node* bottom) { bottom -> left -> right = bottom -> right; bottom -> right -> left = bottom -> left; Node* child = top -> first_child; bottom -> parent = top; top -> first_child = bottom; bottom -> left = bottom -> right = NULL; if (child != NULL) { bottom -> right = child; child -> left = bottom; } top -> degree++; top -> marked = false; } void FibonacciHeap::MakeRootNode(Node* curr) { if (curr -> left != NULL) { curr -> left -> right = curr -> right; } if (curr -> right != NULL) { curr -> right -> left = curr -> left; } if (curr -> parent != NULL) { if (curr -> parent -> first_child == curr) { curr -> parent -> first_child = curr -> right; } curr -> parent -> degree--; } curr -> parent = NULL; Node* min_right = min_node -> right; curr -> right = min_right; min_right -> left = curr; curr -> left = min_node; min_node -> right = curr; } void FibonacciHeap::PrintToDot(Node* curr, std::ofstream& dot_file) { if (curr == NULL) { return; } dot_file << curr -> key << "[label=\"" << curr -> key << "\""; if (curr -> marked) { dot_file << " color=red fontcolor=red"; } dot_file << "];\n"; Node* child = curr -> first_child; if (child == NULL) { dot_file << "null_l_" << curr -> key << "[shape=point];\n"; dot_file << curr -> key << " -> " << "null_l_" << curr -> key << "\n"; } else { while (child != NULL) { PrintToDot(child, dot_file); dot_file << curr -> key << " -> " << child -> key << "\n"; child = child -> right; } } } int main() { FibonacciHeap* heap = new FibonacciHeap(); heap -> Insert(new Node(4)); heap -> DeleteMin(); heap -> DeleteMin(); heap -> Insert(new Node(4)); heap -> Insert(new Node(5)); heap -> Insert(new Node(16)); heap -> Insert(new Node(26)); heap -> Insert(new Node(7)); Node* n11 = new Node(11); heap -> Insert(n11); Node* n17 = new Node(17); heap -> Insert(n17); Node* n12 = new Node(12); heap -> Insert(n12); heap -> Insert(new Node(10)); Node* n99 = new Node(99); heap -> Insert(n99); heap -> Insert(new Node(33)); heap -> Insert(new Node(95)); heap -> Insert(new Node(14)); heap -> Insert(new Node(6)); heap -> Insert(new Node(9)); heap -> Insert(new Node(96)); heap -> Insert(new Node(19)); heap -> Insert(new Node(8)); heap -> Draw("fibheap_full"); heap -> DeleteMin(); std::cout << "Size: " << heap -> GetSize(); Node* min_node = heap -> FindMin(); if (min_node != NULL) { std::cout << " Min: " << min_node -> key << std::endl; } else { std::cout << " Empty" << std::endl; } heap -> Draw("fibheap_del"); heap -> DeleteMin(); std::cout << "Size: " << heap -> GetSize(); min_node = heap -> FindMin(); if (min_node != NULL) { std::cout << " Min: " << min_node -> key << std::endl; } else { std::cout << " Empty" << std::endl; } heap -> Draw("fibheap_del2"); heap -> DecreaseKey(n11, 3); heap -> DecreaseKey(n99, 0); heap -> DecreaseKey(n17, 2); heap -> DecreaseKey(n12, 1); // Cascade heap -> Draw("fibheap_dec"); heap -> DeleteMin(); heap -> DeleteMin(); heap -> DeleteMin(); heap -> DeleteMin(); heap -> DeleteMin(); heap -> Draw("fibheap_end"); return 0; }
25.065789
74
0.56168
Rand0mUsername
19a273935ae0662816c7a68f7d39f79db444aea3
7,301
hpp
C++
src/byl_avl_tree.hpp
superboy0712/toy_template_library
4b62a52bf0789472807206997253b0cc7cdd8102
[ "MIT" ]
null
null
null
src/byl_avl_tree.hpp
superboy0712/toy_template_library
4b62a52bf0789472807206997253b0cc7cdd8102
[ "MIT" ]
null
null
null
src/byl_avl_tree.hpp
superboy0712/toy_template_library
4b62a52bf0789472807206997253b0cc7cdd8102
[ "MIT" ]
null
null
null
// // Created by yulong on 3/31/17. // #ifndef BYL_TEMPLATE_LIBRARY_AVL_TREE_H #define BYL_TEMPLATE_LIBRARY_AVL_TREE_H #include "byl_bst.hpp" #include <cstddef> namespace byl { template<typename T> struct avl_tree; template<typename T> struct avl_node { typedef T value_type; typedef size_t size_type;; friend struct avl_tree<T>; typedef avl_node * node_ptr; node_ptr left, right, parent; T m_data; int height; size_type n_size; avl_node(const value_type& v = value_type(), int h = 0) : left(NULL), right(NULL), parent(NULL) , m_data(v), height(h), n_size(1) {} }; template<typename T> struct avl_tree : public bst<T, avl_node> { typedef T value_type; typedef bst<T, avl_node> base_tree; typedef avl_node<T> node_type; typedef avl_node<T> *node_pointer; typedef typename bst<T, avl_node>::size_type size_type; inline int max(int a, int b) { return (a > b) ? a : b; } inline int height(node_pointer p) { return p? p->height : (-1); } inline void update_height(node_pointer p) { p->height = 1 + max(height(p->left), height(p->right)); } void update_height_above(node_pointer p) { if(!p) return; while(p->parent) { update_height(p->parent); p = p->parent; } } inline int bal_fac(const node_pointer p) { return (height(p->left) - height(p->right)); } inline bool is_balenced(const node_pointer p) { int fac = bal_fac(p); return (-2 < fac && fac < 2); } inline node_pointer connect34( node_pointer a, node_pointer b, node_pointer c, node_pointer t0, node_pointer t1, node_pointer t2, node_pointer t3) { a->left = t0; if(t0) t0->parent = a; a->right = t1; if(t1) t1->parent = a; update_height(a); update_size(a); c->left = t2; if(t2) t2->parent = c; c->right = t3; if(t3) t3->parent = c; update_height(c); update_size(c); b->left = a; a->parent = b; b->right = c; c->parent = b; update_height(b); update_size(b); return b; } inline bool is_lchild(node_pointer p) { return (p->parent->left == p); } inline bool is_rchild(node_pointer p) { return (p->parent->right == p); } inline node_pointer rebalenced_at(node_pointer g, node_pointer p, node_pointer v) { // assert(v); if (is_lchild(p)) { if(is_lchild(v)) { p->parent = g->parent; return connect34(v, p, g, v->left, v->right, p->right, g->right); } else { v->parent = g->parent; return connect34(p, v, g, p->left, v->left, v->right, g->right); } } else { if(is_rchild(v)) { p->parent = g->parent; return connect34(g, p, v, g->left, p->left, v->left, v->right); } else { v->parent = g->parent; return connect34(g, v, p, g->left, v->left, v->right, p->right); } } } inline node_pointer *from_parent_to(node_pointer p) { return &((p == this->root()) ? this->m_dummy_super_root.left : ( (is_lchild(p)) ? p->parent->left : p->parent->right) ); } inline size_type size_of_node(node_pointer p) { return p ? p->n_size : 0; } inline void update_size(node_pointer p) { if(!p) return; p->n_size = size_of_node(p->left) + size_of_node(p->right) + 1; } inline void update_size_above(node_pointer p) { while (p->parent) { update_size(p->parent); p = p->parent; } } node_pointer insert(const value_type& val) { node_pointer *t, p; t = this->search(val, &p); if(*t) { (*t)->m_data = val; return *t; } *t = new node_type(val); (*t)->parent = p; this->m_size++; update_height(p); update_size(p); update_size_above(p); node_pointer v = *t; for (node_pointer g = p->parent; g && g!=&(this->m_dummy_super_root); v = p, p = g, g = g->parent) { if (!is_balenced(g)) { *from_parent_to(g) = rebalenced_at(g, p, v); break; } else { update_height(g); } } return *t; } inline node_pointer taller_child(node_pointer p) { return ( (height(p->left) > height(p->right)) ? p->left : ( (height(p->left) < height(p->right)) ? p->right : (is_lchild(p) ? p->left : p->right))); } bool remove(const value_type& val) { node_pointer *r, g; r = this->search(val, &g); if(!*r) return false; this->remove_at(r, &g); update_size(g); update_size_above(g); while (g && g!=&(this->m_dummy_super_root)) { update_height(g); if (!is_balenced(g)) { node_pointer p = taller_child(g); node_pointer v = taller_child(p); *from_parent_to(g) = rebalenced_at(g, p, v); } g = g->parent; } return true; } bool remove_by_rank(size_type rank) { node_pointer *r, g; r = this->select(rank, &g); if(!r || !*r) return false; this->remove_at(r, &g); update_size(g); update_size_above(g); while (g && g!=&(this->m_dummy_super_root)) { update_height(g); if (!is_balenced(g)) { node_pointer p = taller_child(g); node_pointer v = taller_child(p); *from_parent_to(g) = rebalenced_at(g, p, v); } g = g->parent; } return true; } inline node_pointer *select(size_type rank, node_pointer *parent) { if(rank >= this->m_size) return NULL; *parent = &(this->m_dummy_super_root); node_pointer* ret = &(this->m_dummy_super_root.left); size_t r = size_of_node((*ret)->left); while(r != rank) { if (rank < r) { *parent = *ret; ret = &(*ret)->left; r = r - size_of_node((*ret)->right) - 1; } else if (rank > r) { *parent = *ret; ret = &(*ret)->right; r = r + size_of_node((*ret)->left) + 1; } } return ret; } size_type rank(value_type &val) { node_pointer p = this->root(); size_t r = size_of_node(p->left); while(p) { if (p->m_data > val) { p = p->left; r = r - size_of_node(p? p->right : NULL) - 1; } else if (p->m_data < val) { p = p->right; r = r + size_of_node(p? p->left : NULL) + 1; } else { return r; } } return r; // if r = -1 or size, then seach failed } const value_type& operator [](size_type rank) { node_pointer *q, p; q = select(rank, &p); return (*q)->m_data; } }; }//namespace btl #endif //BYL_TEMPLATE_LIBRARY_AVL_TREE_H
31.200855
108
0.506506
superboy0712
19ac69b353212e5cb772c9447e2512f70e77bf4a
243
cpp
C++
24_qstackedwidget/src/pessoa.cpp
josersi/qt_cppmaster
62e8499c1f17463bd4209ac61ae4fc8d49da69e4
[ "MIT" ]
1
2018-09-01T05:57:29.000Z
2018-09-01T05:57:29.000Z
24_qstackedwidget/src/pessoa.cpp
josersi/qt_cppmaster
62e8499c1f17463bd4209ac61ae4fc8d49da69e4
[ "MIT" ]
null
null
null
24_qstackedwidget/src/pessoa.cpp
josersi/qt_cppmaster
62e8499c1f17463bd4209ac61ae4fc8d49da69e4
[ "MIT" ]
1
2019-09-26T01:45:10.000Z
2019-09-26T01:45:10.000Z
#include "pessoa.h" Pessoa::Pessoa(QObject *parent) : QObject(parent) { } QString Pessoa::getNome() const { return nome; } void Pessoa::setNome(const QString &value) { nome = value; emit nomeChanged(nome); }
12.789474
50
0.613169
josersi
30abe44edfcc28fa640af9703d47dcf0c8fc614e
600
cpp
C++
3D-TV/PerfTimer.cpp
TheByteKitchen/Kinect_client_server
47bd066199f5b112b476e4d34ad333a535baa314
[ "MS-PL" ]
null
null
null
3D-TV/PerfTimer.cpp
TheByteKitchen/Kinect_client_server
47bd066199f5b112b476e4d34ad333a535baa314
[ "MS-PL" ]
null
null
null
3D-TV/PerfTimer.cpp
TheByteKitchen/Kinect_client_server
47bd066199f5b112b476e4d34ad333a535baa314
[ "MS-PL" ]
null
null
null
//// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF //// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO //// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A //// PARTICULAR PURPOSE. //// //// Copyright (c) Microsoft Corporation. All rights reserved #include "pch.h" #include "PerfTimer.h" // Initialize the resolution of the timer LARGE_INTEGER PerfTimer::m_freq = \ (QueryPerformanceFrequency(&PerfTimer::m_freq), PerfTimer::m_freq); // Calculate the overhead of the timer LONGLONG PerfTimer::m_overhead = PerfTimer::GetOverhead();
37.5
77
0.743333
TheByteKitchen
30acddda17fe21c4369a615ea1200d62f0b10f6d
2,174
cpp
C++
Engine/Platforms/Public/Tools/GPUThreadHelper.cpp
azhirnov/GraphicsGenFramework-modular
348be601f1991f102defa0c99250529f5e44c4d3
[ "BSD-2-Clause" ]
12
2017-12-23T14:24:57.000Z
2020-10-02T19:52:12.000Z
Engine/Platforms/Public/Tools/GPUThreadHelper.cpp
azhirnov/ModularGraphicsFramework
348be601f1991f102defa0c99250529f5e44c4d3
[ "BSD-2-Clause" ]
null
null
null
Engine/Platforms/Public/Tools/GPUThreadHelper.cpp
azhirnov/ModularGraphicsFramework
348be601f1991f102defa0c99250529f5e44c4d3
[ "BSD-2-Clause" ]
null
null
null
// Copyright (c) Zhirnov Andrey. For more information see 'LICENSE.txt' #include "Engine/Platforms/Public/Tools/GPUThreadHelper.h" namespace Engine { namespace PlatformTools { /* ================================================= FindGraphicsThread ================================================= */ ModulePtr GPUThreadHelper::FindGraphicsThread (GlobalSystemsRef gs) { using MsgList_t = ModuleMsg::MessageListFrom< GpuMsg::ThreadBeginFrame, GpuMsg::ThreadEndFrame, GpuMsg::SubmitCommands, GpuMsg::GetDeviceInfo, GpuMsg::GetGraphicsModules, GpuMsg::GetGraphicsSettings >; using EventList_t = ModuleMsg::MessageListFrom< GpuMsg::DeviceCreated, GpuMsg::DeviceBeforeDestroy >; return gs->parallelThread->GetModuleByMsgEvent< MsgList_t, EventList_t >(); } /* ================================================= FindComputeThread ================================================= */ ModulePtr GPUThreadHelper::FindComputeThread (GlobalSystemsRef gs) { using MsgList_t = ModuleMsg::MessageListFrom< GpuMsg::SubmitCommands, GpuMsg::GetDeviceInfo, GpuMsg::GetGraphicsModules, GpuMsg::GetComputeSettings >; using EventList_t = ModuleMsg::MessageListFrom< GpuMsg::DeviceCreated, GpuMsg::DeviceBeforeDestroy >; return gs->parallelThread->GetModuleByMsgEvent< MsgList_t, EventList_t >(); } /* ================================================= FindVRThread ================================================= */ ModulePtr GPUThreadHelper::FindVRThread (GlobalSystemsRef gs) { using MsgList_t = ModuleMsg::MessageListFrom< GpuMsg::ThreadBeginVRFrame, GpuMsg::ThreadEndVRFrame, GpuMsg::SubmitCommands, GpuMsg::GetVRDeviceInfo, GpuMsg::GetGraphicsModules, GpuMsg::GetGraphicsSettings >; using EventList_t = ModuleMsg::MessageListFrom< GpuMsg::DeviceCreated, GpuMsg::DeviceBeforeDestroy >; return gs->parallelThread->GetModuleByMsgEvent< MsgList_t, EventList_t >(); } } // PlatformTools } // Engine
27.175
77
0.589236
azhirnov
30b4715024c575a744b186b209157ca94722c5af
456
cpp
C++
cpp/inifile/test.cpp
0382/util
b8163f52352341ae7872d95b7f18542f17a94633
[ "MIT" ]
null
null
null
cpp/inifile/test.cpp
0382/util
b8163f52352341ae7872d95b7f18542f17a94633
[ "MIT" ]
null
null
null
cpp/inifile/test.cpp
0382/util
b8163f52352341ae7872d95b7f18542f17a94633
[ "MIT" ]
null
null
null
#include "inifile.hpp" int main() { auto ini = util::inifile("test.ini"); if (!ini.good()) { std::cerr << ini.error() << std::endl; exit(-1); } std::cout << "default section: name = " << ini.get_string("name") << '\n'; ini.set_string("set", "string"); std::cout << "section1: test = " << ini.section("section1").get_int("test") << '\n'; std::cout << "\nshow all data:\n--------------\n"; ini.show(); }
25.333333
88
0.497807
0382
30c2cccfa2f3c1e5f3de472b340de4aafaedccca
22
cpp
C++
src/mjast_and.cpp
lucasalj/mjcompiler
4404e4ce25f009c60d9f93d0118f33bb1d56b2cf
[ "MIT" ]
null
null
null
src/mjast_and.cpp
lucasalj/mjcompiler
4404e4ce25f009c60d9f93d0118f33bb1d56b2cf
[ "MIT" ]
null
null
null
src/mjast_and.cpp
lucasalj/mjcompiler
4404e4ce25f009c60d9f93d0118f33bb1d56b2cf
[ "MIT" ]
null
null
null
#include <mjast_and.h>
22
22
0.772727
lucasalj
30cf79f21e82a1d1ae95a5e7baa57f4321c29b03
17,711
cpp
C++
src/ringmesh/geomodel/tools/mesh_quality.cpp
ringmesh/RINGMesh
82a0a0fb0a119492c6747265de6ec24006c4741f
[ "BSD-3-Clause" ]
74
2017-10-26T15:40:23.000Z
2022-03-22T09:27:39.000Z
src/ringmesh/geomodel/tools/mesh_quality.cpp
ringmesh/ringmesh
82a0a0fb0a119492c6747265de6ec24006c4741f
[ "BSD-3-Clause" ]
45
2017-10-26T15:54:01.000Z
2021-01-27T10:16:34.000Z
src/ringmesh/geomodel/tools/mesh_quality.cpp
ringmesh/ringmesh
82a0a0fb0a119492c6747265de6ec24006c4741f
[ "BSD-3-Clause" ]
17
2018-03-27T11:31:24.000Z
2022-03-06T18:41:52.000Z
/* * Copyright (c) 2012-2018, Association Scientifique pour la Geologie et ses * Applications (ASGA). 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 ASGA 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 ASGA 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. * * http://www.ring-team.org * * RING Project * Ecole Nationale Superieure de Geologie - GeoRessources * 2 Rue du Doyen Marcel Roubault - TSA 70605 * 54518 VANDOEUVRE-LES-NANCY * FRANCE */ #include <algorithm> #include <geogram/basic/attributes.h> #include <ringmesh/geomodel/core/geomodel.h> #include <ringmesh/geomodel/core/geomodel_mesh_entity.h> #include <ringmesh/geomodel/tools/mesh_quality.h> #include <ringmesh/mesh/mesh_builder.h> #include <ringmesh/mesh/mesh_index.h> #include <ringmesh/mesh/volume_mesh.h> /*! * @author Benjamin Chauvin * This code is inspired from * http://people.sc.fsu.edu/~jburkardt/cpp_src/tet_mesh_quality/tet_mesh_quality.html */ namespace { using namespace RINGMesh; /*! * @brief Computes the radius of the tetrahedron insphere. * * The tetrahedron insphere is the sphere inside the tetrahedron which * is tangent to each tetrahedron facet. * * @param[in] v0 first vertex of the tetrahedron. * @param[in] v1 second vertex of the tetrahedron. * @param[in] v2 third vertex of the tetrahedron. * @param[in] v3 fourth vertex of the tetrahedron. * @return the radius of the tetrahedron insphere. */ double tetra_insphere_radius( const vec3& v0, const vec3& v1, const vec3& v2, const vec3& v3 ) { double tet_volume = GEO::Geom::tetra_volume( v0, v1, v2, v3 ); double A1 = GEO::Geom::triangle_area( v0, v1, v2 ); double A2 = GEO::Geom::triangle_area( v1, v2, v3 ); double A3 = GEO::Geom::triangle_area( v2, v3, v0 ); double A4 = GEO::Geom::triangle_area( v3, v0, v1 ); ringmesh_assert( A1 + A2 + A3 + A4 > global_epsilon ); return ( 3 * tet_volume ) / ( A1 + A2 + A3 + A4 ); } /*! * @brief Tetrahedron quality based on the insphere and circumsphere radii. * * The quality is between 0 and 1. 0 corresponds to a bad tetrahedron, and * 1 to a good tetrahedron (equilaterality). * For more information, see * <a * href="http://people.sc.fsu.edu/~jburkardt/cpp_src/tet_mesh_quality/tet_mesh_quality.html"> * TET_MESH_QUALITY Interactive Program for Tet Mesh Quality</a> * * @param[in] v0 first vertex of the tetrahedron. * @param[in] v1 second vertex of the tetrahedron. * @param[in] v2 third vertex of the tetrahedron. * @param[in] v3 fourth vertex of the tetrahedron. * @return 3 * the insphere radius divided by the circumsphere radius. */ double tet_quality_insphere_radius_by_circumsphere_radius( const vec3& v0, const vec3& v1, const vec3& v2, const vec3& v3 ) { const vec3 tetra_circum_center = GEO::Geom::tetra_circum_center( v0, v1, v2, v3 ); const double tetra_circum_radius = vec3( tetra_circum_center - v0 ).length(); ringmesh_assert( std::abs( tetra_circum_radius - ( tetra_circum_center - v1 ).length() ) < global_epsilon ); ringmesh_assert( std::abs( tetra_circum_radius - ( tetra_circum_center - v2 ).length() ) < global_epsilon ); ringmesh_assert( std::abs( tetra_circum_radius - ( tetra_circum_center - v3 ).length() ) < global_epsilon ); // insphere computation double in_radius = tetra_insphere_radius( v0, v1, v2, v3 ); return 3. * in_radius / tetra_circum_radius; } /*! * @param[in] v0 first vertex of the tetrahedron. * @param[in] v1 second vertex of the tetrahedron. * @param[in] v2 third vertex of the tetrahedron. * @param[in] v3 fourth vertex of the tetrahedron. * @return the maximum of the tetrahedron edge length. */ double max_tet_edge_length( const vec3& v0, const vec3& v1, const vec3& v2, const vec3& v3 ) { std::initializer_list< double > edge_length{ ( v1 - v0 ).length(), ( v2 - v0 ).length(), ( v3 - v0 ).length(), ( v2 - v1 ).length(), ( v3 - v1 ).length(), ( v3 - v2 ).length() }; return std::max( edge_length ); } /*! * @brief Tetrahedron quality based on the insphere radius and the maximum * edge length. * * The quality is between 0 and 1. 0 corresponds to a bad tetrahedron, and * 1 to a good tetrahedron (equilaterality). * For more information see * Du, Q., and D. Wang, 2005, * The optimal centroidal Voronoi tessellations and the gersho's conjecture * in the three-dimensional space, * Computers & Mathematics with Applications, v. 49, no. 9, p. 1355-1373, * <a href="http://doi.org/10.1016/j.camwa.2004.12.008">doi</a>, * <a * href="http://people.sc.fsu.edu/~jburkardt/cpp_src/tet_mesh_quality/tet_mesh_quality.html"> * TET_MESH_QUALITY Interactive Program for Tet Mesh Quality</a> * * @param[in] v0 first vertex of the tetrahedron. * @param[in] v1 second vertex of the tetrahedron. * @param[in] v2 third vertex of the tetrahedron. * @param[in] v3 fourth vertex of the tetrahedron. * @return 2 * sqrt( 6 ) * the insphere radius divided by the maximum of the * tetrhedron edge length. */ double tet_quality_insphere_radius_by_max_edge_length( const vec3& v0, const vec3& v1, const vec3& v2, const vec3& v3 ) { double in_radius = tetra_insphere_radius( v0, v1, v2, v3 ); double edge_length = max_tet_edge_length( v0, v1, v2, v3 ); return 2 * std::sqrt( 6. ) * in_radius / edge_length; } /*! * @param[in] v0 first vertex of the tetrahedron. * @param[in] v1 second vertex of the tetrahedron. * @param[in] v2 third vertex of the tetrahedron. * @param[in] v3 fourth vertex of the tetrahedron. * @return the sum of the square tetrahedron edge length. */ double sum_square_edge_length( const vec3& v0, const vec3& v1, const vec3& v2, const vec3& v3 ) { double l1 = vec3( v1 - v0 ).length2(); double l2 = vec3( v2 - v0 ).length2(); double l3 = vec3( v3 - v0 ).length2(); double l4 = vec3( v2 - v1 ).length2(); double l5 = vec3( v3 - v1 ).length2(); double l6 = vec3( v3 - v2 ).length2(); return l1 + l2 + l3 + l4 + l5 + l6; } /*! * @brief Tetrahedron quality based on the tetrahedron volume and * the sum of the square edges. * * The quality is between 0 and 1. 0 corresponds to a bad tetrahedron, and * 1 to a good tetrahedron (equilaterality). * For more information see * <a * href="http://people.sc.fsu.edu/~jburkardt/cpp_src/tet_mesh_quality/tet_mesh_quality.html"> * TET_MESH_QUALITY Interactive Program for Tet Mesh Quality</a> * * @param[in] v0 first vertex of the tetrahedron. * @param[in] v1 second vertex of the tetrahedron. * @param[in] v2 third vertex of the tetrahedron. * @param[in] v3 fourth vertex of the tetrahedron. * * @return 12. * (3 * volume)^(2/3) / sum of the square edge. */ double tet_quality_volume_by_sum_square_edges( const vec3& v0, const vec3& v1, const vec3& v2, const vec3& v3 ) { const double tet_volume = GEO::Geom::tetra_volume( v0, v1, v2, v3 ); double sum_square_edge = sum_square_edge_length( v0, v1, v2, v3 ); ringmesh_assert( sum_square_edge > global_epsilon ); return 12. * std::pow( 3. * tet_volume, 2. / 3. ) / sum_square_edge; } /*! * @bried Computes the sinus of the half solid angle relatively to a * tetrahedron vertex. * @param[in] v0 first vertex of the tetrahedron. The solid angle is * computed * relatively to this vertex. * @param[in] v1 second vertex of the tetrahedron. * @param[in] v2 third vertex of the tetrahedron. * @param[in] v3 fourth vertex of the tetrahedron. * @return the sinus of the half solid angle on the vertex \p v0. */ double sin_half_solid_angle( const vec3& v0, const vec3& v1, const vec3& v2, const vec3& v3 ) { double tet_volume = GEO::Geom::tetra_volume( v0, v1, v2, v3 ); double l01 = ( v1 - v0 ).length(); double l02 = ( v2 - v0 ).length(); double l03 = ( v3 - v0 ).length(); double l12 = ( v2 - v1 ).length(); double l13 = ( v3 - v1 ).length(); double l23 = ( v3 - v2 ).length(); double denominator = ( l01 + l02 + l12 ) * ( l01 + l02 - l12 ) * ( l02 + l03 + l23 ) * ( l02 + l03 - l23 ) * ( l03 + l01 + l13 ) * ( l03 + l01 - l13 ); ringmesh_assert( denominator > global_epsilon_sq ); denominator = std::sqrt( denominator ); return 12 * tet_volume / denominator; } /*! * @brief Tetrahedron quality based on the solid angles. * * This metrics is based on the sinus of the half solid angle on each * vertex. It was shown on the literature that the minimum of the four * values provides an estimate of the tetrahedron quality. * For more information, see: * <a * href="http://people.eecs.berkeley.edu/~jrs/meshpapers/robnotes.pdf">robnotes.pdf</a> * p15, * Liu, A., and B. Joe, 1994, Relationship between tetrahedron shape * measures, * BIT, v. 34, no. 2, p. 268-287, <a * href="http://doi.org/10.1007/BF01955874">doi</a> and * <a * href="http://people.sc.fsu.edu/~jburkardt/cpp_src/tet_mesh_quality/tet_mesh_quality.html"> * TET_MESH_QUALITY Interactive Program for Tet Mesh Quality</a> * * @param[in] v0 first vertex of the tetrahedron. * @param[in] v1 second vertex of the tetrahedron. * @param[in] v2 third vertex of the tetrahedron. * @param[in] v3 fourth vertex of the tetrahedron. * * @return 1.5 * sqrt( 6 ) * the minimun of the sinus of the half * solid angles. 1.5 * sqrt( 6 ) is a factor to scale the metrics between * 0 and 1. * 0 corresponds to a bad tetrahedron, and * 1 to a good tetrahedron (equilaterality). */ double tet_quality_min_solid_angle( const vec3& v0, const vec3& v1, const vec3& v2, const vec3& v3 ) { double min_sin_half_solid_angle = std::min( std::min( std::min( sin_half_solid_angle( v0, v1, v2, v3 ), sin_half_solid_angle( v1, v0, v2, v3 ) ), sin_half_solid_angle( v2, v0, v1, v3 ) ), sin_half_solid_angle( v3, v0, v1, v2 ) ); return 1.5 * std::sqrt( 6. ) * min_sin_half_solid_angle; } /*! * @param[in] mesh_qual_mode mesh quality number. * @return the property name associated to the mesh quality number * \p mesh_qual_mode. */ std::string mesh_qual_mode_to_prop_name( MeshQualityMode mesh_qual_mode ) { std::string quality_name; switch( mesh_qual_mode ) { case INSPHERE_RADIUS_BY_CIRCUMSPHERE_RADIUS: quality_name = "INSPHERE_RADIUS_BY_CIRCUMSPHERE_RADIUS"; break; case INSPHERE_RADIUS_BY_MAX_EDGE_LENGTH: quality_name = "INSPHERE_RADIUS_BY_MAX_EDGE_LENGTH"; break; case VOLUME_BY_SUM_SQUARE_EDGE: quality_name = "VOLUME_BY_SUM_SQUARE_EDGE"; break; case MIN_SOLID_ANGLE: quality_name = "MIN_SOLID_ANGLE"; break; default: ringmesh_assert_not_reached; } ringmesh_assert( !quality_name.empty() ); return quality_name; } /*! * @brief Gets the quality for one tetrahedron. * * The quality is between 0 and 1. 0 corresponds to a bad tetrahedron, and * 1 to a good tetrahedron (equilaterality). * * @param[in] v0 first vertex of the tetrahedron. * @param[in] v1 second vertex of the tetrahedron. * @param[in] v2 third vertex of the tetrahedron. * @param[in] v3 fourth vertex of the tetrahedron. * @param[in] mesh_qual_mode tetrahedron quality to get. * @return the tetrahedron quality. */ double get_tet_quality( const vec3& v0, const vec3& v1, const vec3& v2, const vec3& v3, MeshQualityMode mesh_qual_mode ) { double quality = -1; switch( mesh_qual_mode ) { case INSPHERE_RADIUS_BY_CIRCUMSPHERE_RADIUS: quality = tet_quality_insphere_radius_by_circumsphere_radius( v0, v1, v2, v3 ); break; case INSPHERE_RADIUS_BY_MAX_EDGE_LENGTH: quality = tet_quality_insphere_radius_by_max_edge_length( v0, v1, v2, v3 ); break; case VOLUME_BY_SUM_SQUARE_EDGE: quality = tet_quality_volume_by_sum_square_edges( v0, v1, v2, v3 ); break; case MIN_SOLID_ANGLE: quality = tet_quality_min_solid_angle( v0, v1, v2, v3 ); break; default: ringmesh_assert_not_reached; } ringmesh_assert( quality > -1 * global_epsilon && quality < 1 + global_epsilon ); return quality; } } // namespace namespace RINGMesh { void compute_prop_tet_mesh_quality( MeshQualityMode mesh_qual_mode, const GeoModel3D& geomodel ) { ringmesh_assert( geomodel.nb_regions() != 0 ); for( const auto& region : geomodel.regions() ) { ringmesh_assert( region.is_meshed() ); ringmesh_assert( region.is_simplicial() ); GEO::AttributesManager& reg_attr_mgr = region.cell_attribute_manager(); GEO::Attribute< double > attr( reg_attr_mgr, mesh_qual_mode_to_prop_name( mesh_qual_mode ) ); for( auto cell_itr : range( region.nb_mesh_elements() ) ) { attr[cell_itr] = get_tet_quality( region.mesh_element_vertex( { cell_itr, 0 } ), region.mesh_element_vertex( { cell_itr, 1 } ), region.mesh_element_vertex( { cell_itr, 2 } ), region.mesh_element_vertex( { cell_itr, 3 } ), mesh_qual_mode ); } } } double fill_mesh_with_low_quality_cells( MeshQualityMode mesh_qual_mode, double min_quality, const GeoModel3D& geomodel, VolumeMesh3D& output_mesh ) { ringmesh_assert( geomodel.nb_regions() != 0 ); auto mesh_builder = VolumeMeshBuilder3D::create_builder( output_mesh ); double min_qual_value{ max_float64() }; for( const auto& region : geomodel.regions() ) { ringmesh_assert( region.is_meshed() ); ringmesh_assert( region.is_simplicial() ); GEO::Attribute< double > quality_attribute( region.cell_attribute_manager(), mesh_qual_mode_to_prop_name( mesh_qual_mode ) ); for( auto cell_id : range( region.nb_mesh_elements() ) ) { if( quality_attribute[cell_id] < min_quality ) { auto first_new_vertex_id = output_mesh.nb_vertices(); for( auto v : range( 4 ) ) { mesh_builder->create_vertex( region.mesh_element_vertex( { cell_id, v } ) ); } auto new_cell_id = mesh_builder->create_cells( 1, CellType::TETRAHEDRON ); for( auto v_id : range( 4 ) ) { mesh_builder->set_cell_vertex( { new_cell_id, v_id }, first_new_vertex_id + v_id ); } if( quality_attribute[cell_id] < min_qual_value ) { min_qual_value = quality_attribute[cell_id]; } } } } return min_qual_value; } } // namespace RINGMesh
41.575117
97
0.611484
ringmesh
30cf9a1e4c280de211c6f47e1da4bb8d58ea336d
2,835
cpp
C++
primitive_roots_tests.cpp
Mirraz/number-theory
30f444f8b61cc5946d4615bafe237994d7836cbf
[ "MIT" ]
null
null
null
primitive_roots_tests.cpp
Mirraz/number-theory
30f444f8b61cc5946d4615bafe237994d7836cbf
[ "MIT" ]
null
null
null
primitive_roots_tests.cpp
Mirraz/number-theory
30f444f8b61cc5946d4615bafe237994d7836cbf
[ "MIT" ]
null
null
null
#include <assert.h> #include <stdio.h> #include <stdint.h> #include <inttypes.h> #include <math.h> #include "primitive_roots.h" #define main HIDE_main #define tests_suite HIDE_tests_suite #define test_max_primitive_root HIDE_test_max_primitive_root #include "mul_group_mod_tests.cpp" #undef main #undef tests_suite #undef test_max_primitive_root void test_is_primitive_root() { typedef uint_fast32_t num_type; typedef PrimitiveRoots<num_type, 9, ((num_type)1)<<31, uint_fast64_t> prrs_type; typedef prrs_type::canonic_factorizer_type cfzr_type; typedef cfzr_type::primes_array_type primes_array_type; // pi(2^16) = 6542 num_type primes[6542]; size_t primes_count = primes_array_type::fill_primes( primes, sizeof(primes) / sizeof(primes[0]), (num_type)UINT16_MAX + 1 ); assert(primes_count == sizeof(primes) / sizeof(primes[0])); cfzr_type cfzr(primes_array_type(primes, primes_count)); for (size_t idx=0; idx<sizeof(primes) / sizeof(primes[0]); ++idx) { num_type modulo = primes[idx]; prrs_type primitive_roots(cfzr, modulo); num_type min_root = 0; for (num_type i=1; i<modulo; ++i) { bool is_primitive_root = primitive_roots.is_primitive_root(i); if (is_primitive_root) {min_root = i; break;} } num_type max_root = 0; for (num_type i=modulo-1; i>=1; --i) { bool is_primitive_root = primitive_roots.is_primitive_root(i); if (is_primitive_root) {max_root = i; break;} } assert(min_root != 0); assert(max_root != 0); assert((modulo-1) % 4 != 0 || modulo-max_root == min_root); printf("%" PRIuFAST64 "\t %" PRIuFAST64 "\n", modulo, min_root); printf("%" PRIuFAST64 "\t-%" PRIuFAST64 "\n", modulo, modulo-max_root); printf("\n"); } } void test_max_primitive_root() { fill_myprimes(); fill_max_roots(); typedef uint_fast32_t num_type; typedef PrimitiveRoots<num_type, 9, ((num_type)1)<<31, uint_fast64_t> prrs_type; typedef prrs_type::canonic_factorizer_type cfzr_type; typedef cfzr_type::primes_array_type primes_array_type; // pi(2^16) = 6542 num_type primes[6542]; size_t primes_count = primes_array_type::fill_primes( primes, sizeof(primes) / sizeof(primes[0]), (num_type)UINT16_MAX + 1 ); assert(primes_count == sizeof(primes) / sizeof(primes[0])); cfzr_type cfzr(primes_array_type(primes, primes_count)); for (size_t idx=0; idx<sizeof(primes) / sizeof(primes[0]); ++idx) { num_type modulo = primes[idx]; prrs_type primitive_roots(cfzr, modulo); num_type max_root = 0; for (num_type i=modulo-1; i>=1; --i) { bool is_primitive_root = primitive_roots.is_primitive_root(i); if (is_primitive_root) {max_root = i; break;} } assert(max_root != 0); assert(max_root == myprimes[idx] - max_roots[idx]); } } void tests_suite() { //test_is_primitive_root(); test_max_primitive_root(); } int main() { tests_suite(); return 0; }
29.53125
81
0.722751
Mirraz
30d61e145e98bb61d3e96be726741974debf1d6d
602
cpp
C++
replace_character.cpp
chandan9369/Recursion-backtracking-problems
360e5de72e23dfd4e3f343baa1e1abdfb801ccc3
[ "MIT" ]
null
null
null
replace_character.cpp
chandan9369/Recursion-backtracking-problems
360e5de72e23dfd4e3f343baa1e1abdfb801ccc3
[ "MIT" ]
null
null
null
replace_character.cpp
chandan9369/Recursion-backtracking-problems
360e5de72e23dfd4e3f343baa1e1abdfb801ccc3
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; void replace(char s[], char c1, char c2) { //base case if (s[0] == '\0') { return; } if (s[0] == c1) { s[0] = c2; } replace(s + 1, c1, c2); } int main() { char s[100]; cin >> s; char c1, c2; cout << "Enter character to be replaced : "; cin >> c1; cout << "Enter character with which you want to replace : "; cin >> c2; replace(s, c1, c2); cout << "After replacing character " << c1 << " with character" << c2 << "string we have new string : " << s << endl; return 0; }
21.5
121
0.501661
chandan9369
30dd8562f1660168b8dfe9e37926033955f4dcb3
1,448
hpp
C++
test/include/nuschl/unittests/vector_printer.hpp
behlec/nuschl
35dbdd6dca8e59387623cc8a23f71324e07ea98c
[ "MIT" ]
null
null
null
test/include/nuschl/unittests/vector_printer.hpp
behlec/nuschl
35dbdd6dca8e59387623cc8a23f71324e07ea98c
[ "MIT" ]
null
null
null
test/include/nuschl/unittests/vector_printer.hpp
behlec/nuschl
35dbdd6dca8e59387623cc8a23f71324e07ea98c
[ "MIT" ]
null
null
null
#pragma once // clang-format off #include <boost/test/unit_test.hpp> #include <boost/test/test_tools.hpp> // clang-format on #include <nuschl/s_exp.hpp> #include <iostream> #include <vector> std::ostream &operator<<(std::ostream &os, const std::vector<int> &vec); std::ostream &operator<<(std::ostream &os, const std::vector<std::string> &vec); std::ostream &operator<<(std::ostream &os, const std::vector<std::vector<std::string>> &vec); std::ostream &operator<<(std::ostream &os, const std::vector<const nuschl::s_exp *> &vec); namespace boost { namespace test_tools { namespace tt_detail { template <> struct print_log_value<std::vector<int>> { void operator()(std::ostream &os, std::vector<int> const &vec) { ::operator<<(os, vec); } }; template <> struct print_log_value<std::vector<std::string>> { void operator()(std::ostream &os, std::vector<std::string> const &vec) { ::operator<<(os, vec); } }; template <> struct print_log_value<std::vector<std::vector<std::string>>> { void operator()(std::ostream &os, std::vector<std::vector<std::string>> const &vec) { ::operator<<(os, vec); } }; template <> struct print_log_value<std::vector<const nuschl::s_exp *>> { void operator()(std::ostream &os, std::vector<const nuschl::s_exp *> const &vec) { ::operator<<(os, vec); } }; } } }
27.846154
80
0.61326
behlec
30f08690e448df39c2889d227793a0054a3f0339
842
cpp
C++
Depth-first Search/max-area-of-island.cpp
PrakharPipersania/LeetCode-Solutions
ea74534bbdcf1ca3ea4d88a1081582e0e15f50c7
[ "MIT" ]
2
2021-03-05T22:32:23.000Z
2021-03-05T22:32:29.000Z
Questions Level-Wise/Medium/max-area-of-island.cpp
PrakharPipersania/LeetCode-Solutions
ea74534bbdcf1ca3ea4d88a1081582e0e15f50c7
[ "MIT" ]
null
null
null
Questions Level-Wise/Medium/max-area-of-island.cpp
PrakharPipersania/LeetCode-Solutions
ea74534bbdcf1ca3ea4d88a1081582e0e15f50c7
[ "MIT" ]
null
null
null
class Solution { public: void findarea(vector<vector<int>>& grid,int r,int c,int &t) { grid[r][c]=0,t++; if(r+1<grid.size()&&grid[r+1][c]) findarea(grid,r+1,c,t); if(r-1>=0&&grid[r-1][c]) findarea(grid,r-1,c,t); if(c+1<grid[0].size()&&grid[r][c+1]) findarea(grid,r,c+1,t); if(c-1>=0&&grid[r][c-1]) findarea(grid,r,c-1,t); } int maxAreaOfIsland(vector<vector<int>>& grid) { int t,area=0; for(int i=0;i<grid.size();i++) { for(int j=0;j<grid[i].size();j++) { if(grid[i][j]) { t=0,findarea(grid,i,j,t); if(t>area) area=t; } } } return area; } };
26.3125
63
0.388361
PrakharPipersania
30f193a757d6a35bd19a711a276b02e2fcbfbcba
174
cpp
C++
address1.cpp
Biteliuying/address
d2ef3a79b214d5282e8307cde741a8938830d6b2
[ "Apache-2.0" ]
null
null
null
address1.cpp
Biteliuying/address
d2ef3a79b214d5282e8307cde741a8938830d6b2
[ "Apache-2.0" ]
1
2022-02-10T15:28:30.000Z
2022-02-10T15:28:30.000Z
address1.cpp
Biteliuying/address
d2ef3a79b214d5282e8307cde741a8938830d6b2
[ "Apache-2.0" ]
null
null
null
#define _CRT_SECURE_NO_WARNINGS #include<stdio.h> int main() { char a,b; a = 'a'; b = 'b'; putchar(a); putchar('\n'); putchar(b); printf("\n%c\n%c", a,b); }
14.5
32
0.545977
Biteliuying
30f54b4f48d2376297310dd98ca85d87ff9407b5
1,359
tcc
C++
include/bits/sqlite_iterator.tcc
vashman/data_pattern_sqlite
8ed3d1fe3e86ea7165d43277feb05d84189f696e
[ "BSL-1.0" ]
null
null
null
include/bits/sqlite_iterator.tcc
vashman/data_pattern_sqlite
8ed3d1fe3e86ea7165d43277feb05d84189f696e
[ "BSL-1.0" ]
null
null
null
include/bits/sqlite_iterator.tcc
vashman/data_pattern_sqlite
8ed3d1fe3e86ea7165d43277feb05d84189f696e
[ "BSL-1.0" ]
null
null
null
// // Copyright Sundeep S. Sangha 2013 - 2017. // 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 DATA_PATTERN_SQLITE_SQLITE_ITERATOR_TCC #define DATA_PATTERN_SQLITE_SQLITE_ITERATOR_TCC #include <iterator> #include <memory> namespace data_pattern_sqlite { template <typename T> sqlite_iterator_input<T>::sqlite_iterator_input ( sqlite_statement & _stmt ) : stmt (& _stmt) , temp () , got_var (false) , index (_stmt.index) {} template <typename T> sqlite_iterator_input<T>::sqlite_iterator_input ( sqlite_statement & _stmt , int _index ) : stmt (& _stmt) , temp () , got_var (false) , index (_index) {} template <typename T> template <typename U> sqlite_iterator_input<T>::sqlite_iterator_input ( sqlite_statement & _stmt , sqlite_iterator_input<U> const & _stmt2 ) : stmt (& _stmt) , temp () , got_var (false) , index (_stmt2.index) {} template <typename T> sqlite_iterator_input<T>::sqlite_iterator_input () : stmt (nullptr) , temp () , got_var(true) , index(-1) {} sqlite_iterator_output::sqlite_iterator_output ( sqlite_statement & _stmt ) : stmt (& _stmt) , index (1+_stmt.index) {} sqlite_iterator_output::sqlite_iterator_output () : stmt (nullptr) , index (-1) {} } /* data_pattern_sqlite */ #endif
18.875
61
0.721854
vashman
a502a181be3839ebda6aad9ff55c19e4a4eb8099
1,337
cpp
C++
shaders/src/sib_vector_switch.cpp
caron/sitoa
52a0a4b35f51bccb6223a8206d04b40edc80071c
[ "Apache-2.0" ]
34
2018-02-01T16:13:48.000Z
2021-07-16T07:37:47.000Z
shaders/src/sib_vector_switch.cpp
625002974/sitoa
46b7de8e3cf2e2c4cbc6bc391f11181cbac1a589
[ "Apache-2.0" ]
72
2018-02-16T17:30:41.000Z
2021-11-22T11:41:45.000Z
shaders/src/sib_vector_switch.cpp
625002974/sitoa
46b7de8e3cf2e2c4cbc6bc391f11181cbac1a589
[ "Apache-2.0" ]
15
2018-02-15T15:36:58.000Z
2021-04-14T03:54:25.000Z
/************************************************************************************************************************************ Copyright 2017 Autodesk, Inc. 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 <ai.h> AI_SHADER_NODE_EXPORT_METHODS(SIBVectorSwitchMethods); enum SIBVectorSwitchParams { p_vector1, p_vector2, p_input }; node_parameters { AiParameterVec ( "vector1", 0.0f, 0.0f, 0.0f ); AiParameterVec ( "vector2", 0.0f, 0.0f, 0.0f ); AiParameterBool( "input" , true ); } node_initialize{} node_update{} node_finish{} shader_evaluate { bool input = AiShaderEvalParamBool(p_input); sg->out.VEC() = AiShaderEvalParamVec(input ? p_vector2 : p_vector1); }
34.282051
134
0.60359
caron
a50d463ed9da3f14cd8ee894f64c8461bb2cb32e
4,983
cpp
C++
Project/Main/build-Onket-Desktop_Qt_5_14_0_MinGW_32_bit-Debug/moc_basketview.cpp
IsfahanUniversityOfTechnology-CE2019-23/Onket
403d982f7c80d522ca28bb5f757a295eb02b3807
[ "MIT" ]
1
2021-01-03T21:33:26.000Z
2021-01-03T21:33:26.000Z
Project/Main/build-Onket-Desktop_Qt_5_14_0_MinGW_32_bit-Debug/moc_basketview.cpp
IsfahanUniversityOfTechnology-CE2019-23/Onket
403d982f7c80d522ca28bb5f757a295eb02b3807
[ "MIT" ]
null
null
null
Project/Main/build-Onket-Desktop_Qt_5_14_0_MinGW_32_bit-Debug/moc_basketview.cpp
IsfahanUniversityOfTechnology-CE2019-23/Onket
403d982f7c80d522ca28bb5f757a295eb02b3807
[ "MIT" ]
1
2020-07-22T14:48:58.000Z
2020-07-22T14:48:58.000Z
/**************************************************************************** ** Meta object code from reading C++ file 'basketview.h' ** ** Created by: The Qt Meta Object Compiler version 67 (Qt 5.14.0) ** ** WARNING! All changes made in this file will be lost! *****************************************************************************/ #include <memory> #include "../Onket/basketview.h" #include <QtCore/qbytearray.h> #include <QtCore/qmetatype.h> #if !defined(Q_MOC_OUTPUT_REVISION) #error "The header file 'basketview.h' doesn't include <QObject>." #elif Q_MOC_OUTPUT_REVISION != 67 #error "This file was generated using the moc from 5.14.0. It" #error "cannot be used with the include files from this version of Qt." #error "(The moc has changed too much.)" #endif QT_BEGIN_MOC_NAMESPACE QT_WARNING_PUSH QT_WARNING_DISABLE_DEPRECATED struct qt_meta_stringdata_BasketView_t { QByteArrayData data[9]; char stringdata0[113]; }; #define QT_MOC_LITERAL(idx, ofs, len) \ Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \ qptrdiff(offsetof(qt_meta_stringdata_BasketView_t, stringdata0) + ofs \ - idx * sizeof(QByteArrayData)) \ ) static const qt_meta_stringdata_BasketView_t qt_meta_stringdata_BasketView = { { QT_MOC_LITERAL(0, 0, 10), // "BasketView" QT_MOC_LITERAL(1, 11, 18), // "returningRequested" QT_MOC_LITERAL(2, 30, 0), // "" QT_MOC_LITERAL(3, 31, 6), // "update" QT_MOC_LITERAL(4, 38, 16), // "updateFinalPrice" QT_MOC_LITERAL(5, 55, 11), // "removedItem" QT_MOC_LITERAL(6, 67, 4), // "Item" QT_MOC_LITERAL(7, 72, 21), // "on_btn_return_clicked" QT_MOC_LITERAL(8, 94, 18) // "on_btn_buy_clicked" }, "BasketView\0returningRequested\0\0update\0" "updateFinalPrice\0removedItem\0Item\0" "on_btn_return_clicked\0on_btn_buy_clicked" }; #undef QT_MOC_LITERAL static const uint qt_meta_data_BasketView[] = { // content: 8, // revision 0, // classname 0, 0, // classinfo 6, 14, // methods 0, 0, // properties 0, 0, // enums/sets 0, 0, // constructors 0, // flags 1, // signalCount // signals: name, argc, parameters, tag, flags 1, 0, 44, 2, 0x06 /* Public */, // slots: name, argc, parameters, tag, flags 3, 0, 45, 2, 0x0a /* Public */, 4, 0, 46, 2, 0x08 /* Private */, 5, 1, 47, 2, 0x08 /* Private */, 7, 0, 50, 2, 0x08 /* Private */, 8, 0, 51, 2, 0x08 /* Private */, // signals: parameters QMetaType::Void, // slots: parameters QMetaType::Void, QMetaType::Void, QMetaType::Void, 0x80000000 | 6, 2, QMetaType::Void, QMetaType::Void, 0 // eod }; void BasketView::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a) { if (_c == QMetaObject::InvokeMetaMethod) { auto *_t = static_cast<BasketView *>(_o); Q_UNUSED(_t) switch (_id) { case 0: _t->returningRequested(); break; case 1: _t->update(); break; case 2: _t->updateFinalPrice(); break; case 3: _t->removedItem((*reinterpret_cast< const Item(*)>(_a[1]))); break; case 4: _t->on_btn_return_clicked(); break; case 5: _t->on_btn_buy_clicked(); break; default: ; } } else if (_c == QMetaObject::IndexOfMethod) { int *result = reinterpret_cast<int *>(_a[0]); { using _t = void (BasketView::*)(); if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&BasketView::returningRequested)) { *result = 0; return; } } } } QT_INIT_METAOBJECT const QMetaObject BasketView::staticMetaObject = { { QMetaObject::SuperData::link<QScrollArea::staticMetaObject>(), qt_meta_stringdata_BasketView.data, qt_meta_data_BasketView, qt_static_metacall, nullptr, nullptr } }; const QMetaObject *BasketView::metaObject() const { return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject; } void *BasketView::qt_metacast(const char *_clname) { if (!_clname) return nullptr; if (!strcmp(_clname, qt_meta_stringdata_BasketView.stringdata0)) return static_cast<void*>(this); return QScrollArea::qt_metacast(_clname); } int BasketView::qt_metacall(QMetaObject::Call _c, int _id, void **_a) { _id = QScrollArea::qt_metacall(_c, _id, _a); if (_id < 0) return _id; if (_c == QMetaObject::InvokeMetaMethod) { if (_id < 6) qt_static_metacall(this, _c, _id, _a); _id -= 6; } else if (_c == QMetaObject::RegisterMethodArgumentMetaType) { if (_id < 6) *reinterpret_cast<int*>(_a[0]) = -1; _id -= 6; } return _id; } // SIGNAL 0 void BasketView::returningRequested() { QMetaObject::activate(this, &staticMetaObject, 0, nullptr); } QT_WARNING_POP QT_END_MOC_NAMESPACE
30.950311
101
0.609874
IsfahanUniversityOfTechnology-CE2019-23
a50d528cc0ce030f6198e6d87f6ff351af11526d
898
hpp
C++
Examples/PuzzleGenerator/Generator.hpp
jamesfer/Pathfinder
c1e770624a3b163f2dd173f38228e93d7eb80367
[ "MIT" ]
null
null
null
Examples/PuzzleGenerator/Generator.hpp
jamesfer/Pathfinder
c1e770624a3b163f2dd173f38228e93d7eb80367
[ "MIT" ]
null
null
null
Examples/PuzzleGenerator/Generator.hpp
jamesfer/Pathfinder
c1e770624a3b163f2dd173f38228e93d7eb80367
[ "MIT" ]
null
null
null
#ifndef Generator_hpp #define Generator_hpp #include "BFSSearcher.hpp" #include "DFSSearcher.hpp" #include <sstream> #include "Puzzle.hpp" /** * Success functor that checks if the node has the required depth */ struct BranchDepthCheck { private: int goalDepth; public: BranchDepthCheck(int goalDepth) : goalDepth(goalDepth) { } bool operator()(const Node<Puzzle>& node) const { return node.getBranchCost() >= goalDepth; } }; /** * A DFS searcher type that starts with an ordered board with its given size * and then a set number of moves on it. */ class Generator : public DFSSearcher<Puzzle, BranchDepthCheck> { public: typedef DFSSearcher<Puzzle, BranchDepthCheck> Super; public: Generator(int goalDepth); /** * Creates an ordered puzzle and then performs moves on it. */ shared_ptr<Puzzle> generate(int width, int height); }; #endif /* Generator_hpp */
17.607843
77
0.72049
jamesfer
a50e40c4d1c9fa60a110e1332f774ae56811c795
1,253
cc
C++
leetcode/leetcode_199.cc
math715/arts
ff73ccb7d67f7f7c87150204e15aeb46047f0e02
[ "MIT" ]
null
null
null
leetcode/leetcode_199.cc
math715/arts
ff73ccb7d67f7f7c87150204e15aeb46047f0e02
[ "MIT" ]
null
null
null
leetcode/leetcode_199.cc
math715/arts
ff73ccb7d67f7f7c87150204e15aeb46047f0e02
[ "MIT" ]
null
null
null
#include <iostream> #include <algorithm> #include <vector> using namespace std; struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) {} }; void rightTree( TreeNode *root, int &depth, int cur_depth, vector<int> &result){ if (root) { if (depth < cur_depth) { depth += 1; result.push_back(root->val); } if (root->right){ rightTree(root->right, depth, cur_depth+1, result); } if (root->left) { rightTree(root->left, depth, cur_depth+1, result); } } } vector<int> rightSideView(TreeNode* root) { vector<int> result; if (root == nullptr) { return result; } int depth = 0; rightTree(root, depth, 1, result); return result; } int main( int argc, char *argv[] ) { TreeNode *root = new TreeNode(4); root->left = new TreeNode(3); root->left->left = new TreeNode(2); root->left->left->left = new TreeNode(1); root->right = new TreeNode(5); root->right->right = new TreeNode(6); /* TreeNode *root = new TreeNode(1); root->left = new TreeNode(2); */ auto vs = rightSideView(root); for (auto v : vs ){ cout << v << " "; } cout << endl; return 0; }
21.982456
80
0.581804
math715
a5115bd910e444bdcc0eac1e882e56b4acc3158c
541
cpp
C++
redfish-core/ut/stl_utils_test.cpp
cjcain/bmcweb
80badf7ceff486ef2bcb912309563919fc5326ea
[ "Apache-2.0" ]
96
2018-01-23T10:17:55.000Z
2022-03-22T08:49:41.000Z
redfish-core/ut/stl_utils_test.cpp
cjcain/bmcweb
80badf7ceff486ef2bcb912309563919fc5326ea
[ "Apache-2.0" ]
233
2018-08-06T05:55:44.000Z
2022-02-23T08:19:04.000Z
redfish-core/ut/stl_utils_test.cpp
cjcain/bmcweb
80badf7ceff486ef2bcb912309563919fc5326ea
[ "Apache-2.0" ]
97
2018-03-23T07:56:55.000Z
2022-03-16T15:51:48.000Z
#include "utils/stl_utils.hpp" #include <gmock/gmock.h> TEST(STLUtilesTest, RemoveDuplicates) { std::vector<std::string> strVec = {"s1", "s4", "s1", "s2", "", "s3", "s3"}; auto iter = redfish::stl_utils::firstDuplicate(strVec.begin(), strVec.end()); EXPECT_EQ(*iter, "s3"); redfish::stl_utils::removeDuplicate(strVec); EXPECT_EQ(strVec.size(), 5); EXPECT_EQ(strVec[0], "s1"); EXPECT_EQ(strVec[1], "s4"); EXPECT_EQ(strVec[2], "s2"); EXPECT_EQ(strVec[3], ""); EXPECT_EQ(strVec[4], "s3"); }
24.590909
79
0.608133
cjcain
a511af29e5823b82098463c7e263ab70f8e134a3
380
cpp
C++
UVA/11172-Relational Operator.cpp
alielsokary/Competitive-programming
7dffaa334e18c61c8a7985f5bbb64e3613d1008b
[ "MIT" ]
null
null
null
UVA/11172-Relational Operator.cpp
alielsokary/Competitive-programming
7dffaa334e18c61c8a7985f5bbb64e3613d1008b
[ "MIT" ]
null
null
null
UVA/11172-Relational Operator.cpp
alielsokary/Competitive-programming
7dffaa334e18c61c8a7985f5bbb64e3613d1008b
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; int participants,budget,hotles,weeks; int price, bed; int finalCost; bool isAvail = false; long long n,a,b; int main(int argc, char *argv[]) { scanf("%lld", &n); for (int i = 0; i<n; i++) { scanf("%lld%lld", &a,&b); if (a > b) { printf(">\n"); } else if (a < b) { printf("<\n"); } else { printf("=\n"); } } }
16.521739
37
0.544737
alielsokary
a5135f2bffbefb3b6ff81037e622c3307d690ae3
206
cpp
C++
lio/message.cpp
liuyuan185442111/misc
26920202198658c21784d25ab33e1b245d28ca12
[ "Apache-2.0" ]
1
2021-01-23T09:24:35.000Z
2021-01-23T09:24:35.000Z
lio/message.cpp
liuyuan185442111/misc
26920202198658c21784d25ab33e1b245d28ca12
[ "Apache-2.0" ]
null
null
null
lio/message.cpp
liuyuan185442111/misc
26920202198658c21784d25ab33e1b245d28ca12
[ "Apache-2.0" ]
null
null
null
#include "message.h" #include "gmatrix.h" void MsgQueue::Send() { MSGQUEUE::iterator it = _queue.begin(); for(; it != _queue.end(); ++it) gmatrix::HandleMessage(*it); _queue.clear(); }
18.727273
43
0.601942
liuyuan185442111
a5177f9b1d3d7b1d6c09f3b5c9e71a2a6adec0ca
486
hpp
C++
tinyraytracing/src/graphX/geometry/shapes/shpere.hpp
nicolaszordan/tinygrafX
5460b98459ec5e050ae6c0fb53de2f31c80243a9
[ "Unlicense" ]
null
null
null
tinyraytracing/src/graphX/geometry/shapes/shpere.hpp
nicolaszordan/tinygrafX
5460b98459ec5e050ae6c0fb53de2f31c80243a9
[ "Unlicense" ]
null
null
null
tinyraytracing/src/graphX/geometry/shapes/shpere.hpp
nicolaszordan/tinygrafX
5460b98459ec5e050ae6c0fb53de2f31c80243a9
[ "Unlicense" ]
null
null
null
// // graphX - geometry - shapes - sphere.hpp // #pragma once #include "Ishape.hpp" namespace graphX::geometry { struct Sphere : IShape { public: Sphere(const vec3f& center_, float radius_) : center{center_}, radius{radius_} { } public: bool ray_intersect(const vec3f& orig_, const vec3f& dir_, float& t0_, vec3f& N_) const override; public: vec3f center; float radius; }; } // namespace graphX::geometry
20.25
104
0.604938
nicolaszordan
a51a2cc5253a0e0355c9a1693576d8eb80a9f8bf
160
hxx
C++
code/temunt/interface/TemUnt/Direction.hxx
Angew/temple-untrap
bec2a9b73f8b0bbcd5ea9b2b04e4b3da113906fc
[ "MIT" ]
1
2021-08-20T08:22:18.000Z
2021-08-20T08:22:18.000Z
code/temunt/interface/TemUnt/Direction.hxx
Angew/temple-untrap
bec2a9b73f8b0bbcd5ea9b2b04e4b3da113906fc
[ "MIT" ]
null
null
null
code/temunt/interface/TemUnt/Direction.hxx
Angew/temple-untrap
bec2a9b73f8b0bbcd5ea9b2b04e4b3da113906fc
[ "MIT" ]
null
null
null
#pragma once #include "TemUnt/Direction.hh" namespace TemUnt { enum class Direction { North = 0, South = 1, East = 2, West = 3 }; } //namespace TemUnt
9.411765
30
0.65
Angew
a52f7fe7b8ba648cfe89fbb8bc15dd779ba0f115
5,779
cpp
C++
tests/test_file.cpp
adamelliot/stitch
e2a7f4cfb0f8171f8d01e1f1c41b30f3c03be5f3
[ "MIT" ]
4
2017-11-28T17:22:46.000Z
2022-03-17T07:47:19.000Z
tests/test_file.cpp
adamelliot/stitch
e2a7f4cfb0f8171f8d01e1f1c41b30f3c03be5f3
[ "MIT" ]
10
2017-10-04T01:20:25.000Z
2017-11-23T06:15:23.000Z
tests/test_file.cpp
adamelliot/stitch
e2a7f4cfb0f8171f8d01e1f1c41b30f3c03be5f3
[ "MIT" ]
1
2019-06-13T23:05:49.000Z
2019-06-13T23:05:49.000Z
#include "../stitch/file.h" #include "../testing/testing.h" #include <thread> #include <chrono> #include <iostream> #include <sstream> #include <cstring> #include <sys/types.h> #include <sys/stat.h> using namespace Stitch; using namespace std; using namespace Testing; static bool test_basic() { Test test; const string path("test.fifo"); { remove(path.c_str()); int result = mkfifo(path.c_str(), S_IWUSR | S_IRUSR); if (result == -1) { throw std::runtime_error(string("Failed to create FIFO: ") + strerror(errno)); } } int reps = 5; auto make_data = [](int rep) -> string { ostringstream s; s << "data"; for(int i = 0; i < rep; ++i) s << '.' << to_string(i+1); return s.str(); }; thread writer([&]() { File f(path, File::WriteOnly); uint32_t d = 0; for(int rep = 0; rep < reps; ++rep) { wait(f.write_ready()); printf("Write ready\n"); ++d; int c = f.write(&d, sizeof(d)); printf("Written %d\n", d); if (c != sizeof(d)) throw std::runtime_error("Failed write."); this_thread::sleep_for(chrono::milliseconds(250)); } }); thread reader([&]() { File f(path, File::ReadOnly); uint32_t expected = 0; for(int rep = 0; rep < reps; ++rep) { wait(f.read_ready()); printf("Read ready\n"); ++expected; uint32_t received = 0; int c = f.read(&received, sizeof(uint32_t)); printf("Read %d\n", received); if (c != sizeof(uint32_t)) throw std::runtime_error("Failed read."); test.assert("Received = " + to_string(expected), received == expected); } }); writer.join(); reader.join(); return test.success(); } static bool test_blocking_read() { Test test; const string path("test.fifo"); { remove(path.c_str()); int result = mkfifo(path.c_str(), S_IWUSR | S_IRUSR); if (result == -1) { throw std::runtime_error(string("Failed to create FIFO: ") + strerror(errno)); } } int reps = 5; auto make_data = [](int rep) -> string { ostringstream s; s << "data"; for(int i = 0; i < rep; ++i) s << '.' << to_string(i+1); return s.str(); }; thread writer([&]() { File f(path, File::WriteOnly); uint32_t d = 0; for(int rep = 0; rep < reps; ++rep) { wait(f.write_ready()); printf("Write ready\n"); ++d; int c = f.write(&d, sizeof(d)); printf("Written %d\n", d); if (c != sizeof(d)) throw std::runtime_error("Failed write."); this_thread::sleep_for(chrono::milliseconds(250)); } }); thread reader([&]() { File f(path, File::ReadOnly); vector<uint32_t> received(reps, 0); wait(f.read_ready()); printf("Read ready\n"); int c = f.read(&received[0], sizeof(uint32_t) * reps); printf("Read count = %d\n", c); if (c != sizeof(uint32_t) * reps) throw std::runtime_error("Failed read."); for(int rep = 0; rep < reps; ++rep) { auto & v = received[rep]; test.assert("Received = " + to_string(v), v == rep + 1); } }); writer.join(); reader.join(); return test.success(); } static bool test_nonblocking_read() { Test test; const string path("test.fifo"); { remove(path.c_str()); int result = mkfifo(path.c_str(), S_IWUSR | S_IRUSR); if (result == -1) { throw std::runtime_error(string("Failed to create FIFO: ") + strerror(errno)); } } int reps = 5; auto make_data = [](int rep) -> string { ostringstream s; s << "data"; for(int i = 0; i < rep; ++i) s << '.' << to_string(i+1); return s.str(); }; thread writer([&]() { File f(path, File::WriteOnly); uint32_t d = 0; for(int rep = 0; rep < reps; ++rep) { wait(f.write_ready()); printf("Write ready\n"); ++d; int c = f.write(&d, sizeof(d)); printf("Written %d\n", d); if (c != sizeof(d)) throw std::runtime_error("Failed write."); this_thread::sleep_for(chrono::milliseconds(250)); } }); thread reader([&]() { File f(path, File::ReadOnly, false); vector<uint32_t> received(reps, 0); int total_size = sizeof(uint32_t) * reps; int received_size = 0; char * dst = (char*) &received[0]; while(received_size < total_size) { wait(f.read_ready()); printf("Read ready\n"); int c = f.read(dst, total_size - received_size); if (c <= 0) throw std::runtime_error("Failed read."); printf("Read count = %d\n", c); received_size += c; dst += c; } for(int rep = 0; rep < reps; ++rep) { auto & v = received[rep]; assert("Received = " + to_string(v), v == rep + 1); } }); writer.join(); reader.join(); return test.success(); } Test_Set file_tests() { return { { "basic", test_basic }, { "blocking read", test_blocking_read }, { "nonblocking read", test_nonblocking_read }, }; }
19.791096
90
0.477072
adamelliot
a531f88b830fa58c47ddcc7d015872bf18c81664
55,115
cc
C++
raft_impl.cc
dengoswei/craft
16c4d403c0b1819dc21258cc4cbff6ffb8bf6457
[ "Apache-2.0" ]
5
2015-12-10T02:28:33.000Z
2019-06-02T18:20:53.000Z
raft_impl.cc
dengoswei/craft
16c4d403c0b1819dc21258cc4cbff6ffb8bf6457
[ "Apache-2.0" ]
null
null
null
raft_impl.cc
dengoswei/craft
16c4d403c0b1819dc21258cc4cbff6ffb8bf6457
[ "Apache-2.0" ]
null
null
null
#include <algorithm> #include <sstream> #include "raft_impl.h" #include "replicate_tracker.h" #include "time_utils.h" #include "hassert.h" #include "mem_utils.h" using namespace std; namespace { using namespace raft; inline void assert_role(const RaftImpl& raft_impl, RaftRole expected_role) { hassert(raft_impl.getRole() == expected_role, "expected role %d but %d", static_cast<int>(expected_role), static_cast<int>(raft_impl.getRole())); } inline void assert_term(RaftImpl& raft_impl, uint64_t term) { hassert(raft_impl.getTerm() == term, "expected term %" PRIu64 " but term %" PRIu64, raft_impl.getTerm(), term); } template <typename T> bool isMajority( T expected, const std::map<uint64_t, T>& votes, size_t peer_ids_size, const std::set<uint64_t>& old_peer_ids, const std::set<uint64_t>& new_peer_ids) { bool major = countMajor(expected, votes, peer_ids_size); if (true == old_peer_ids.empty() || false == major) { return major; } assert(false == old_peer_ids.empty()); assert(false == new_peer_ids.empty()); // joint consensus // raft paper: // Agreement(for elections and entry commitment) requires // seperate majorities from both the old and new configrations. if (false == countMajor(expected, votes, old_peer_ids)) { return false; } return countMajor(expected, votes, new_peer_ids); } std::vector<const Entry*> make_vec_entries(const raft::Message& msg) { vector<const Entry*> vec_entries(msg.entries_size(), nullptr); for (int idx = 0; idx < msg.entries_size(); ++idx) { vec_entries[idx] = &msg.entries(idx); assert(nullptr != vec_entries[idx]); } assert(vec_entries.size() == static_cast<size_t>(msg.entries_size())); return vec_entries; } std::vector<const Entry*> shrinkEntries(uint64_t conflict_index, const std::vector<const Entry*>& entries) { if (size_t(0) == entries.size() || 0ull == conflict_index) { return vector<const Entry*>{entries.begin(), entries.end()}; } assert(size_t(0) < entries.size()); assert(nullptr != entries[0]); uint64_t base_index = entries[0]->index(); assert(conflict_index >= base_index); size_t idx = conflict_index - base_index; if (idx >= entries.size()) { return vector<const Entry*>{}; } return vector<const Entry*>{entries.begin() + idx, entries.end()}; } inline uint64_t getBaseLogIndex(std::deque<std::unique_ptr<Entry>>& logs) { if (true == logs.empty()) { return 0ull; } assert(nullptr != logs.front()); assert(0ull < logs.front()->index()); return logs.front()->index(); } size_t truncateLogs( std::deque<std::unique_ptr<Entry>>& logs, uint64_t truncate_index) { uint64_t base_index = getBaseLogIndex(logs); size_t idx = truncate_index - base_index; if (idx >= logs.size()) { return size_t{0}; } size_t prev_size = logs.size(); logs.erase(logs.begin() + idx, logs.end()); return prev_size - logs.size(); } inline bool IsAGroupMember( const RaftImpl& raft_impl, uint64_t peer_id, bool check_current) { if (true == check_current) { return raft_impl.GetCurrentConfig().IsAGroupMember(peer_id); } return raft_impl.GetCommitedConfig().IsAGroupMember(peer_id); } inline bool IsAReplicateMember( const RaftImpl& raft_impl, uint64_t peer_id) { return raft_impl.GetCurrentConfig().IsAReplicateMember(peer_id); } int ApplyConfChange( const Entry& conf_entry, bool check_pending, ConfChange& conf_change, RaftConfig& raft_config) { if (EntryType::EntryConfChange != conf_entry.type()) { logerr("expectecd %d but conf_entry.type %d", static_cast<int>(EntryType::EntryConfChange), static_cast<int>(conf_entry.type())); return -1; } // 1. if (false == conf_change.ParseFromString(conf_entry.data())) { return -2; } raft_config.ApplyConfChange(conf_change, check_pending); return 0; } std::vector<std::unique_ptr<raft::Message>> batchBuildMsgApp(raft::RaftImpl& raft_impl) { vector<unique_ptr<Message>> vec_msg; const auto& replicate_group = raft_impl.GetCurrentConfig().GetReplicateGroup(); uint64_t last_log_index = raft_impl.getLastLogIndex(); for (auto peer_id : replicate_group) { auto msg = raft_impl.GetReplicateTracker().BuildMsgApp( last_log_index, peer_id, [&](uint64_t to, uint64_t next_index, size_t batch_size) { return raft_impl.buildMsgApp( to, next_index, batch_size); }); if (nullptr != msg) { vec_msg.emplace_back(move(msg)); } assert(nullptr == msg); } return vec_msg; } std::vector<std::unique_ptr<raft::Message>> batchBuildMsgHeartbeat(raft::RaftImpl& raft_impl) { vector<unique_ptr<Message>> vec_msg; const auto& replicate_group = raft_impl.GetCurrentConfig().GetReplicateGroup(); for (auto peer_id : replicate_group) { auto msg = raft_impl.GetReplicateTracker().BuildMsgHeartbeat( peer_id, [&](uint64_t to, uint64_t next_index, size_t /* */) { return raft_impl.buildMsgHeartbeat(to, next_index); }); if (nullptr != msg) { vec_msg.emplace_back(move(msg)); } assert(nullptr == msg); } return vec_msg; } } // namespace namespace raft { const uint64_t META_INDEX = 0ull; const size_t MAX_BATCH_SIZE = 10; namespace candidate { MessageType onTimeout( RaftImpl& raft_impl, std::chrono::time_point<std::chrono::system_clock> time_now); } // namespace candidate namespace follower { MessageType onTimeout( RaftImpl& raft_impl, std::chrono::time_point<std::chrono::system_clock> time_now) { assert_role(raft_impl, RaftRole::FOLLOWER); logdebug("selfid(follower) %" PRIu64 " term %" PRIu64, raft_impl.getSelfId(), raft_impl.getTerm()); // only timeout if selfid IsAGroupMember if (false == IsAGroupMember(raft_impl, raft_impl.getSelfId(), true)) { // don't have MsgVote right; raft_impl.updateActiveTime(time_now); return MessageType::MsgNull; } // raft paper: // Followers 5.2 // if election timeout elapses without receiving AppendEntries // RPC from current leader or granting vote to candidate: // convert to candidate raft_impl.becomeCandidate(); return MessageType::MsgVote; } MessageType onStepMessage(RaftImpl& raft_impl, const Message& msg) { assert_role(raft_impl, RaftRole::FOLLOWER); assert_term(raft_impl, msg.term()); auto time_now = std::chrono::system_clock::now(); auto rsp_msg_type = MessageType::MsgNull; switch (msg.type()) { case MessageType::MsgVote: // valid check // 1. msg.from => is a valid group member in current config; // 2. selfid => is a valid group member in current config; if (false == IsAGroupMember(raft_impl, msg.from(), true) || false == IsAGroupMember( raft_impl, raft_impl.getSelfId(), true)) { logerr("NotAGroupMember: msg.to %" PRIu64 " msg.from %" PRIu64, msg.to(), msg.from()); break; } // candidate requestVote msg // // raft paper: 5.1 & 5.4 // if votedFor is null or candidateid, and candidate's log is // at least as up-to-date as receiver's log, grant vote // // MORE DETAIL: // - each server will vote for at most one candidate in a // given term, on a first-come-first-served basis; // - the voter denies its vote if its own log is more up-to-date // then that of the candidate. if (raft_impl.isUpToDate(msg.log_term(), msg.index())) { // CAN'T RESET vote_for_ if (0ull == raft_impl.getVoteFor()) { raft_impl.setVoteFor(false, msg.from()); raft_impl.assignStoreSeq(META_INDEX); } assert(0ull != raft_impl.getVoteFor()); } // check getVoteFor() != msg.from() => reject! rsp_msg_type = MessageType::MsgVoteResp; raft_impl.updateActiveTime(time_now); logdebug("selfid %" PRIu64 " handle MsgVote", raft_impl.getSelfId()); break; case MessageType::MsgHeartbeat: { // leader heart beat msg // => Heartbeat with same term always from active leader raft_impl.setLeader(false, msg.from()); assert(msg.from() == raft_impl.getLeader()); rsp_msg_type = MessageType::MsgHeartbeatResp; raft_impl.updateActiveTime(time_now); logdebug("selfid %" PRIu64 " recv heartbeat from leader %" PRIu64, raft_impl.getSelfId(), msg.from()); } break; case MessageType::MsgApp: { // leader appendEntry msg // => AppendEntries always from active leader! raft_impl.setLeader(false, msg.from()); assert(msg.from() == raft_impl.getLeader()); // auto vec_entries = make_vec_entries(msg); auto entries = make_vec_entries(msg); // auto entries = make_entries(vec_entries); assert(static_cast<size_t>( msg.entries_size()) == entries.size()); auto append_count = raft_impl.appendEntries( msg.index(), msg.log_term(), msg.commit(), entries); auto store_seq = 0 < append_count ? raft_impl.assignStoreSeq(msg.index() + 1ull) : 0ull; logdebug("selfid(follower) %" PRIu64 " index %" PRIu64 " term %" PRIu64 " log_term %" PRIu64 " entries_size %zu append_count %d" " store_seq %" PRIu64, raft_impl.getSelfId(), msg.index(), msg.term(), msg.log_term(), entries.size(), append_count, store_seq); raft_impl.updateActiveTime(time_now); rsp_msg_type = MessageType::MsgAppResp; // 0 == msg.entries_size() => indicate already up-to-date } break; default: logdebug("IGNORE: recv msg type %d", static_cast<int>(msg.type())); // TODO ?: MsgProp: redirect to leader ? break; } return rsp_msg_type; } } // namespace follower namespace candidate { MessageType onTimeout( RaftImpl& raft_impl, std::chrono::time_point<std::chrono::system_clock> time_now) { assert_role(raft_impl, RaftRole::CANDIDATE); logdebug("selfid(candidate) %" PRIu64 " term %" PRIu64, raft_impl.getSelfId(), raft_impl.getTerm()); assert(true == IsAGroupMember(raft_impl, raft_impl.getSelfId(), true)); // raft paper: // Candidates 5.2 // On conversion to candidate or election timeout elapse, // start election: raft_impl.beginVote(); raft_impl.updateActiveTime(time_now); return MessageType::MsgVote; } MessageType onStepMessage(RaftImpl& raft_impl, const Message& msg) { assert_role(raft_impl, RaftRole::CANDIDATE); assert_term(raft_impl, msg.term()); auto rsp_msg_type = MessageType::MsgNull; switch (msg.type()) { case MessageType::MsgVoteResp: // valid check if (false == IsAGroupMember(raft_impl, msg.from(), true) || false == IsAGroupMember( raft_impl, raft_impl.getSelfId(), true)) { logerr("NotAGroupMember: msg.to %" PRIu64 " msg.from %" PRIu64, msg.to(), msg.from()); break; } // collect vote resp raft_impl.updateVote(msg.from(), !msg.reject()); if (raft_impl.isMajorVoteYes()) { // step as leader: TODO ? raft_impl.becomeLeader(); // => immidicate send out headbeat ? // raft paper: // Rules for Servers, Leaders: // upon election: send initial empty AppendEntries RPCs // (heartbeat) to each server; repeat during idle periods // to prevent election timeouts 5.2 rsp_msg_type = MessageType::MsgHeartbeat; } logdebug("selfid %" PRIu64 " handle MsgVoteResp", raft_impl.getSelfId()); break; default: logdebug("IGNORE: recv msg type %d", static_cast<int>(msg.type())); // TODO: ? break; } return rsp_msg_type; } } // namespace candidate namespace leader { MessageType onTimeout( RaftImpl& raft_impl, std::chrono::time_point<std::chrono::system_clock> time_now) { assert_role(raft_impl, RaftRole::LEADER); raft_impl.updateActiveTime(time_now); return MessageType::MsgNull; } MessageType onStepMessage(RaftImpl& raft_impl, const Message& msg) { assert_role(raft_impl, RaftRole::LEADER); assert_term(raft_impl, msg.term()); auto rsp_msg_type = MessageType::MsgNull; // check msg.from switch (msg.type()) { case MessageType::MsgProp: { // client prop // auto vec_entries = make_vec_entries(msg); // auto entries = make_entries(vec_entries); auto entries = make_vec_entries(msg); assert(static_cast<size_t>( msg.entries_size()) == entries.size()); auto ret = raft_impl.checkAndAppendEntries(msg.index(), entries); if (0 != ret) { logerr("checkAndAppendEntries ret %d", ret); break; } assert(0ull < msg.index() + 1ull); auto store_seq = raft_impl.assignStoreSeq(msg.index() + 1ull); logdebug("selfid(leader) %" PRIu64 " MsgProp index %" PRIu64 " store_seq %" PRIu64 " entries_size %zu " "last_index %" PRIu64, raft_impl.getSelfId(), msg.index(), store_seq, entries.size(), raft_impl.getLastLogIndex()); rsp_msg_type = MessageType::MsgApp; } break; case MessageType::MsgAppResp: { if (false == IsAReplicateMember(raft_impl, msg.from())) { // not a replicate member now // => ignore this request logerr("selfid %" PRIu64 " recv MsgAppResp from NotAReplicateMember %" PRIu64, raft_impl.getSelfId(), msg.from()); break; } // collect appendEntry resp // TODO: update commited! bool update = raft_impl.updateReplicateState( msg.from(), msg.reject(), msg.reject_hint(), msg.index()); if (update) { rsp_msg_type = MessageType::MsgApp; } else { assert(false == msg.reject()); if (1ull == msg.index() && 0ull < raft_impl.getLastLogIndex()) { // MsgApp prode reach match_index == 0ull // && leader log isn't empty; rsp_msg_type = MessageType::MsgApp; } } logdebug("selfid(leader) %" PRIu64 " MsgAppResp msg.from %" PRIu64 " msg.index %" PRIu64 " update %d reject %d rsp_msg_type %d", raft_impl.getSelfId(), msg.from(), msg.index(), static_cast<int>(update), static_cast<int>(msg.reject()), static_cast<int>(rsp_msg_type)); } break; case MessageType::MsgHeartbeatResp: { if (false == IsAReplicateMember(raft_impl, msg.from())) { // not a replicate member now // => ignore this request logerr("selfid %" PRIu64 " recv MsgHeartbeatResp from " "NotAReplicateMember %" PRIu64, raft_impl.getSelfId(), msg.from()); break; } // collect heartbeat resp bool update = raft_impl.updateReplicateState( msg.from(), msg.reject(), msg.reject_hint(), msg.index()); if (true == update) { rsp_msg_type = MessageType::MsgHeartbeat; } // TODO: logdebug } break; case MessageType::MsgNull: { // check followers timeout ? assert(0ull == msg.from()); auto time_now = chrono::system_clock::now(); if (raft_impl.isHeartbeatTimeout(time_now)) { raft_impl.updateHeartbeatTime(time_now); rsp_msg_type = MessageType::MsgHeartbeat; } } break; default: logdebug("IGNORE: recv msg type %d", static_cast<int>(msg.type())); // TODO: ? break; } return rsp_msg_type; } } // namespace leader RaftImpl::RaftImpl( uint64_t logid, uint64_t selfid, const std::set<uint64_t>& peer_ids, int min_election_timeout, int max_election_timeout) : logid_(logid) , selfid_(selfid) , current_config_(selfid) , commited_config_(selfid) , rtimeout_(min_election_timeout, max_election_timeout) , election_timeout_(rtimeout_()) , active_time_(chrono::system_clock::now()) , hb_timeout_(min_election_timeout / 2) { assert(0 < min_election_timeout); assert(min_election_timeout <= max_election_timeout); // fake ? for (auto id : peer_ids) { ConfChange conf_change; conf_change.set_type(ConfChangeType::ConfChangeAddNode); conf_change.set_node_id(id); current_config_.ApplyConfChange(conf_change, false); commited_config_.ApplyConfChange(conf_change, false); } assert(false == current_config_.IsPending()); assert(false == commited_config_.IsPending()); assert(0 < election_timeout_.count()); assert(0 < hb_timeout_.count()); setRole(RaftRole::FOLLOWER); } RaftImpl::RaftImpl( uint64_t logid, uint64_t selfid, const std::set<uint64_t>& peer_ids, int min_election_timeout, int max_election_timeout, const std::deque<std::unique_ptr<Entry>>& entry_queue, uint64_t commited_index, const RaftState* raft_state) : logid_(logid) , selfid_(selfid) , current_config_(selfid) , commited_config_(selfid) , rtimeout_(min_election_timeout, max_election_timeout) , election_timeout_(rtimeout_()) , active_time_(chrono::system_clock::now()) , hb_timeout_(min_election_timeout / 2) { assert(0 < min_election_timeout); assert(min_election_timeout < max_election_timeout); for (auto id : peer_ids) { ConfChange conf_change; conf_change.set_type(ConfChangeType::ConfChangeAddNode); conf_change.set_node_id(id); current_config_.ApplyConfChange(conf_change, false); commited_config_.ApplyConfChange(conf_change, false); } assert(false == current_config_.IsPending()); assert(false == commited_config_.IsPending()); assert(0 < election_timeout_.count()); assert(0 < hb_timeout_.count()); setRole(RaftRole::FOLLOWER); uint64_t index = 0; uint64_t max_term = 0; uint64_t max_seq = 0; for (auto& entry : entry_queue) { assert(nullptr != entry); assert(entry->index() > index); assert(entry->index() >= commited_index); index = entry->index(); assert(max_term <= entry->term()); max_term = entry->term(); max_seq = max(max_seq, entry->seq()); if (EntryType::EntryConfChange == entry->type()) { applyCommitedConfEntry(*entry); // applyCommitedConfEntry ? } logs_.emplace_back( cutils::make_unique<Entry>(*entry)); assert(nullptr != logs_.back()); } assert(entry_queue.empty() == logs_.empty()); if (0 != commited_index) { assert(0 != index); assert(nullptr != raft_state); assert(true == isIndexInMem(commited_index)); } uint64_t vote_for = 0ull; if (nullptr != raft_state) { assert(commited_index >= raft_state->commit()); assert(max_term <= raft_state->term()); max_term = raft_state->term(); vote_for = raft_state->vote(); max_seq = max(max_seq, raft_state->seq()); } if (0 != max_term) { setTerm(max_term); } setVoteFor(true, vote_for); assert(getTerm() == max_term); assert(getVoteFor() == vote_for); commited_index_ = commited_index; store_seq_ = max_seq+1; } RaftImpl::~RaftImpl() = default; MessageType RaftImpl::CheckTerm(uint64_t msg_term) { // raft paper: rules for servers: 5.1 // => If RPC request or response contains term T > currentTerm: // set currentTerm = T, convert to follower; if (msg_term != term_) { if (msg_term > term_) { becomeFollower(msg_term); return MessageType::MsgNull; } assert(msg_term < term_); return MessageType::MsgInvalidTerm; } assert(msg_term == term_); return MessageType::MsgNull; } MessageType RaftImpl::CheckTimout( std::chrono::time_point<std::chrono::system_clock> time_now) { if (active_time_ + election_timeout_ < time_now) { // TIME OUT: assert(nullptr != timeout_handler_); return timeout_handler_(*this, time_now); } return MessageType::MsgNull; } MessageType RaftImpl::step(const Message& msg) { assert(msg.logid() == logid_); assert(msg.to() == selfid_); // 1. check term auto rsp_msg_type = CheckTerm(msg.term()); if (MessageType::MsgNull != rsp_msg_type) { assert(MessageType::MsgInvalidTerm == rsp_msg_type); return rsp_msg_type; } assert(msg.term() == term_); // 2. check timeout // ! IMPORTANT ! // if setTerm => false == CheckTimeout rsp_msg_type = CheckTimout(chrono::system_clock::now()); if (MessageType::MsgNull != rsp_msg_type) { assert(MessageType::MsgVote == rsp_msg_type); return rsp_msg_type; } // 3. step message return step_handler_(*this, msg); } std::vector<std::unique_ptr<Message>> RaftImpl::produceRsp( const Message& req_msg, MessageType rsp_msg_type) { assert(req_msg.logid() == logid_); assert(req_msg.to() == selfid_); vector<unique_ptr<Message>> vec_msg; if (MessageType::MsgNull == rsp_msg_type) { return vec_msg; } Message msg_template; msg_template.set_type(rsp_msg_type); msg_template.set_logid(logid_); msg_template.set_from(selfid_); msg_template.set_term(term_); msg_template.set_to(req_msg.from()); switch (rsp_msg_type) { case MessageType::MsgVote: // raft paper: // RequestVote RPC Arguments: // - term // - candidicateId // - lastLogIndex // - lastLogTerm msg_template.set_index(getLastLogIndex()); msg_template.set_log_term(getLastLogTerm()); vec_msg = current_config_.BroadcastGroupMsg(msg_template); logdebug("MsgVote term %" PRIu64 " candidate %" PRIu64 " lastLogIndex %" PRIu64 " lastLogTerm %" PRIu64 " vec_msg.size %zu", term_, selfid_, msg_template.index(), msg_template.log_term(), vec_msg.size()); break; case MessageType::MsgVoteResp: { // raft paper: // RequestVote RPC Results: // - term // - voteGranted assert(0ull != req_msg.from()); vec_msg.emplace_back(cutils::make_unique<Message>(msg_template)); auto& rsp_msg = vec_msg.back(); assert(nullptr != rsp_msg); rsp_msg->set_reject(req_msg.from() != getVoteFor()); logdebug("MsgVoteResp term %" PRIu64 " req_msg.from %" PRIu64 " getVoteFor %" PRIu64 " reject %d", term_, req_msg.from(), getVoteFor(), static_cast<int>(rsp_msg->reject())); } break; case MessageType::MsgApp: { assert(nullptr != replicate_states_); // req_msg.type() == MessageType::MsgProp if (0ull == req_msg.from()) { vec_msg = batchBuildMsgApp(*this); logdebug("MsgApp BatchBuildMsgAppUpToDate " "vec_msg.size %zu", vec_msg.size()); } else { assert(0ull != req_msg.from()); // catch-up mode maybe assert(MessageType::MsgAppResp == req_msg.type()); auto rsp_msg = replicate_states_->BuildMsgApp( getLastLogIndex(), req_msg.from(), [&](uint64_t to, uint64_t next_index, size_t batch_size) { return buildMsgApp(to, next_index, batch_size); }); if (nullptr != rsp_msg) { logdebug("MsgApp from %" PRIu64 " to %" PRIu64 " index %" PRIu64 " log_term %" PRIu64, rsp_msg->from(), rsp_msg->to(), rsp_msg->index(), rsp_msg->log_term()); if (0 != rsp_msg->entries_size() || !isPeerUpToDate(req_msg.commit())) { vec_msg.emplace_back(move(rsp_msg)); assert(size_t{1} == vec_msg.size()); } else { logdebug("INGORE: peer_id %" PRIu64 " rsp_msg->entries_size %d" " req_msg.commit %" PRIu64 " commited_index_ %" PRIu64, req_msg.from(), rsp_msg->entries_size(), req_msg.commit(), getCommitedIndex()); } // else => ignore } logdebug("MsgApp selfid %" PRIu64 " req_msg.from %" PRIu64 " req_msg.index %" PRIu64 " vec_msg.size %zu", selfid_, req_msg.from(), req_msg.index(), vec_msg.size()); } } break; case MessageType::MsgAppResp: { // req_msg.type() == MessageType::MsgApp // raft paper: // AppendEntries RPC, Results: // - reply false if term < currentTerm // - reply false if log don't contain an entry at prevLogIndex // whose term matchs prevLogTerm assert(0ull != req_msg.from()); vec_msg.emplace_back(cutils::make_unique<Message>(msg_template)); auto& rsp_msg = vec_msg.back(); assert(nullptr != rsp_msg); // TODO: reject hint ? rsp_msg->set_reject(!isMatch(req_msg.index(), req_msg.log_term())); if (false == rsp_msg->reject()) { // set index to next_index if (0 < req_msg.entries_size()) { rsp_msg->set_index( req_msg.entries( req_msg.entries_size() - 1).index() + 1ull); } else { rsp_msg->set_index(req_msg.index() + 1ull); } } rsp_msg->set_commit(getCommitedIndex()); logdebug("MsgAppResp term %" PRIu64 " req_msg.from(leader) %" PRIu64 " prev_index %" PRIu64 " prev_log_term %" PRIu64 " entries_size %d reject %d next_index %" PRIu64, term_, req_msg.from(), req_msg.index(), req_msg.log_term(), req_msg.entries_size(), static_cast<int>(rsp_msg->reject()), rsp_msg->index()); } break; case MessageType::MsgHeartbeat: { assert(nullptr != replicate_states_); // TODO: // better way to probe the next_indexes_ & match_indexes_ // // MsgHeartbeat => empty AppendEntries RPCs if (MessageType::MsgHeartbeatResp == req_msg.type()) { // 1 : 1 assert(MessageType::MsgHeartbeatResp == req_msg.type()); assert(true == req_msg.reject()); auto hb_msg = replicate_states_->BuildMsgHeartbeat( req_msg.from(), [&](uint64_t to, uint64_t next_index, size_t /* */) { return buildMsgHeartbeat(to, next_index); }); if (nullptr != hb_msg) { vec_msg.emplace_back(move(hb_msg)); } assert(nullptr == hb_msg); } else { // broad cast vec_msg = batchBuildMsgHeartbeat(*this); } } break; case MessageType::MsgHeartbeatResp: { // rsp to leader assert(req_msg.from() == getLeader()); vec_msg.emplace_back(cutils::make_unique<Message>(msg_template)); auto& rsp_msg = vec_msg.back(); assert(nullptr != rsp_msg); rsp_msg->set_reject(!isMatch(req_msg.index(), req_msg.log_term())); if (false == rsp_msg->reject()) { rsp_msg->set_index(req_msg.index() + 1ull); } logdebug("MsgHeartbeatResp term %" PRIu64 " req_msg.from(leader) %" PRIu64 " prev_index %" PRIu64 " prev_log_term %" PRIu64 " reject %d next_index %" PRIu64 , term_, req_msg.from(), req_msg.index(), req_msg.log_term(), static_cast<int>(rsp_msg->reject()), rsp_msg->index()); } break; case MessageType::MsgNull: // DO NOTHING ? break; case MessageType::MsgInvalidTerm: logdebug("MsgInvalidTerm selfid %" PRIu64 " role %d term_ %" PRIu64 " msg.from %" PRIu64 " msg.term %" PRIu64, getSelfId(), static_cast<int>(getRole()), getTerm(), req_msg.from(), req_msg.term()); // TODO: rsp with ? break; default: hassert(false, "invalid rsp_msg_type %d", static_cast<int>(rsp_msg_type)); break; } return vec_msg; } std::unique_ptr<Message> RaftImpl::buildMsgApp( uint64_t peer_id, uint64_t index, size_t max_batch_size) { // raft paper // AppendEntries RPC Arguments: // - leader term // - leader id // - prevLogIndex // - prevLogTerm // - entries[] // - leaderCommit assert(size_t{0} <= max_batch_size); assert(0ull < index); auto app_msg = cutils::make_unique<Message>(); assert(nullptr != app_msg); app_msg->set_type(MessageType::MsgApp); app_msg->set_logid(logid_); app_msg->set_term(term_); app_msg->set_from(selfid_); app_msg->set_to(peer_id); app_msg->set_commit(commited_index_); uint64_t base_index = 0ull; uint64_t last_index = 0ull; tie(base_index, last_index) = getInMemIndex(); logdebug("selfid %" PRIu64 " leader_id %" PRIu64 " index %" PRIu64 " base_index %" PRIu64 " last_index %" PRIu64 " logs_.size %zu max_batch_size %zu", selfid_, leader_id_, index, base_index, last_index, logs_.size(), max_batch_size); if (index < base_index || index > last_index + 1ull) { if (index < base_index) { // report: not in mem // => or submit a catch-up job ? // => catch-up to commited_index point ? // => which will read log from db directly ?? ids_not_in_mem_.insert(peer_id); } return nullptr; } assert(size_t{0} <= last_index - index + 1ull); app_msg->set_index(index - 1ull); app_msg->set_log_term(getLogTerm(index - 1ull)); app_msg->set_commit(commited_index_); assert(size_t{0} <= last_index - index + 1ull); max_batch_size = min<size_t>( max_batch_size, last_index - index + 1ull); for (auto i = size_t{0}; i < max_batch_size; ++i) { auto entry = app_msg->add_entries(); assert(nullptr != entry); *entry = *logs_[index + i - base_index]; } assert(max_batch_size == static_cast<size_t>(app_msg->entries_size())); logdebug("selfid %" PRIu64 " peer_id %" PRIu64 " index %" PRIu64 " max_batch_size %zu", getSelfId(), peer_id, index, max_batch_size); return app_msg; } std::unique_ptr<Message> RaftImpl::buildMsgHeartbeat( uint64_t peer_id, uint64_t next_index) const { assert(0ull < next_index); auto hb_msg = cutils::make_unique<Message>(); assert(nullptr != hb_msg); hb_msg->set_type(MessageType::MsgHeartbeat); hb_msg->set_logid(logid_); hb_msg->set_term(term_); hb_msg->set_from(selfid_); hb_msg->set_to(peer_id); // heartbeat uint64_t base_index = 0ull; uint64_t last_index = 0ull; tie(base_index, last_index) = getInMemIndex(); next_index = max(base_index + 1, next_index); next_index = min(last_index + 1, next_index); hb_msg->set_index(next_index - 1ull); hb_msg->set_log_term(getLogTerm(next_index - 1ull)); hb_msg->set_commit(commited_index_); return hb_msg; } bool RaftImpl::isUpToDate( uint64_t peer_log_term, uint64_t peer_max_index) { // raft paper // 5.4.1 Election restriction // raft determines which of two logs is more up-to-date by // comparing the index and term of the last entries in the logs. // - If the logs have last entries with different terms, then the log // with the later term is more up-to-date; // - If the logs end with the same term, then whichever log is longer // is more up-to-date. uint64_t log_term = getLastLogTerm(); if (peer_log_term > log_term) { return true; } assert(peer_log_term <= log_term); if (peer_log_term == log_term) { return peer_max_index >= getLastLogIndex(); } // else return false; } int RaftImpl::appendLogs(const std::vector<const Entry*>& entries) { if (size_t(0) == entries.size()) { return 0; // do nothing; } assert(nullptr != entries[0]); uint64_t base_index = entries[0]->index(); auto truncate_size = truncateLogs(logs_, base_index); if (size_t{0} < truncate_size) { logerr("INFO selfid %" PRIu64 " truncate_size %zu", getSelfId(), truncate_size); assert(0 == reconstructCurrentConfig()); // reset currentConfig; } uint64_t last_index = getLastLogIndex(); assert(last_index + 1 == base_index); for (size_t idx = 0; idx < entries.size(); ++idx) { assert(nullptr != entries[idx]); if (EntryType::EntryConfChange == entries[idx]->type()) { applyCommitedConfEntry(*entries[idx]); } logs_.emplace_back(cutils::make_unique<Entry>(*entries[idx])); assert(nullptr != logs_.back()); } return entries.size(); } int RaftImpl::appendEntries( uint64_t prev_log_index, uint64_t prev_log_term, uint64_t leader_commited_index, const std::vector<const Entry*>& entries) { assert_role(*this, RaftRole::FOLLOWER); assert(leader_commited_index >= commited_index_); if (!isMatch(prev_log_index, prev_log_term)) { return -1; } // match // raft paper: // - If an existing entry conflicts with a new one(same index but // different terms), delete the existing entry and all that follow it // - Append any new entries not already in the log uint64_t conflict_index = findConflict(entries); assert(0ull == conflict_index || commited_index_ < conflict_index); auto new_entries = shrinkEntries(conflict_index, entries); int append_count = appendLogs(new_entries); updateFollowerCommitedIndex(leader_commited_index); return append_count; } int RaftImpl::checkAndAppendEntries( uint64_t prev_log_index, const std::vector<const Entry*>& entries) { assert_role(*this, RaftRole::LEADER); assert(nullptr != replicate_states_); uint64_t last_index = getLastLogIndex(); if (prev_log_index != last_index) { return -1; } // max length control ? for (size_t idx = 0; idx < entries.size(); ++idx) { assert(nullptr != entries[idx]); // apply conf change before push entries into logs_ if (EntryType::EntryConfChange == entries[idx]->type()) { assert(size_t{1} == entries.size()); assert(size_t{0} == idx); // applyConfChange: auto ret = applyUnCommitedConfEntry(*entries[idx]); if (0 != ret) { // drop conf change request logerr("applyUnCommitedConfEntry ret %d", ret); return -2; } } logs_.emplace_back( cutils::make_unique<Entry>(*entries[idx])); assert(nullptr != logs_.back()); logs_.back()->set_term(term_); logs_.back()->set_index(last_index + 1ull + idx); } replicate_states_->UpdateSelfState(getLastLogIndex()); logdebug("selfid %" PRIu64 " last_index %" PRIu64 " logs_size %zu", selfid_, getLastLogIndex(), logs_.size()); // TODO: find a way to store logs_ to disk return 0; } void RaftImpl::setRole(RaftRole new_role) { logdebug("selfid %" PRIu64 " change role_ %d new_role %d", selfid_, static_cast<int>(role_), static_cast<int>(new_role)); role_ = new_role; switch (role_) { case RaftRole::FOLLOWER: timeout_handler_ = ::raft::follower::onTimeout; step_handler_ = ::raft::follower::onStepMessage; break; case RaftRole::CANDIDATE: timeout_handler_ = ::raft::candidate::onTimeout; step_handler_ = ::raft::candidate::onStepMessage; break; case RaftRole::LEADER: timeout_handler_ = ::raft::leader::onTimeout; step_handler_ = ::raft::leader::onStepMessage; break; } return ; } void RaftImpl::setTerm(uint64_t new_term) { logdebug("selfid %" PRIu64 " role %d change current term %" PRIu64 " new_term %" PRIu64, selfid_, static_cast<int>(role_), term_, new_term); assert(term_ < new_term); term_ = new_term; return ; } void RaftImpl::setVoteFor(bool reset, uint64_t candidate) { logdebug("selfid_ %" PRIu64 " reset %d vote_for_ %" PRIu64 " to candidate %" PRIu64, selfid_, static_cast<int>(reset), vote_for_, candidate); if (true == reset || 0ull == vote_for_) { vote_for_ = candidate; } } uint64_t RaftImpl::assignStoreSeq(uint64_t index) { auto seq = ++store_seq_; if (0ull == index) { pending_meta_seq_ = seq; } else { pending_log_idx_ = 0ull == pending_log_idx_ ? index : min(pending_log_idx_, index); pending_log_seq_ = seq; } // logdebug("selfid %" PRIu64 " index %" PRIu64 // " pending_meta_seq_ %" PRIu64 // " pending_log_idx_ %" PRIu64 " pending_log_seq_ %" PRIu64, // getSelfId(), index, pending_meta_seq_, // pending_log_idx_, pending_log_seq_); return seq; } std::tuple<uint64_t, uint64_t, uint64_t> RaftImpl::getStoreSeq() const { logdebug("selfid %" PRIu64 " pending_meta_seq_ %" PRIu64 " pending_log_idx_ %" PRIu64 " pending_log_seq_ %" PRIu64, getSelfId(), pending_meta_seq_, pending_log_idx_, pending_log_seq_); return make_tuple( pending_meta_seq_, pending_log_idx_, pending_log_seq_); } void RaftImpl::commitedStoreSeq( uint64_t meta_seq, uint64_t log_idx, uint64_t log_seq) { logdebug("selfid %" PRIu64 " meta_seq %" PRIu64 " log_idx %" PRIu64 " log_seq %" PRIu64 " pending_meta_seq_ %" PRIu64 " pending_log_idx_ %" PRIu64 " pending_log_seq_ %" PRIu64, getSelfId(), meta_seq, log_idx, log_seq, pending_meta_seq_, pending_log_idx_, pending_log_seq_); if (meta_seq == pending_meta_seq_) { pending_meta_seq_ = 0ull; // reset } if (log_idx == pending_log_idx_ && log_seq == pending_log_seq_) { pending_log_idx_ = 0ull; pending_log_seq_ = 0ull; } } void RaftImpl::updateActiveTime( std::chrono::time_point<std::chrono::system_clock> time_now) { { auto at_str = cutils::format_time(active_time_); auto time_str = cutils::format_time(time_now); // logdebug("selfid %" PRIu64 " update active_time_ %s " // "to time_now %s", // getSelfId(), at_str.c_str(), time_str.c_str()); } active_time_ = time_now; } uint64_t RaftImpl::getLastLogIndex() const { auto t = getInMemIndex(); return get<1>(t); } uint64_t RaftImpl::getLastLogTerm() const { if (true == logs_.empty()) { assert(0ull == commited_index_); return 0ull; } assert(nullptr != logs_.back()); assert(term_ >= logs_.back()->term()); return logs_.back()->term(); } uint64_t RaftImpl::getBaseLogTerm() const { if (true == logs_.empty()) { assert(0ull == commited_index_); return 0ull; } assert(nullptr != logs_.front()); assert(0ull != logs_.front()->term()); assert(term_ >= logs_.front()->term()); return logs_.front()->term(); } std::tuple<uint64_t, uint64_t> RaftImpl::getInMemIndex() const { if (true == logs_.empty()) { assert(0ull == commited_index_); return make_tuple(0ull, 0ull); } assert(nullptr != logs_.front()); assert(0ull < logs_.front()->index()); assert(0ull == commited_index_ || commited_index_ >= logs_.front()->index()); assert(nullptr != logs_.back()); assert(logs_.back()->index() == logs_.front()->index() + logs_.size() - 1ull); return make_tuple(logs_.front()->index(), logs_.back()->index()); } uint64_t RaftImpl::getBaseLogIndex() const { auto t = getInMemIndex(); return get<0>(t); } const Entry* RaftImpl::getLogEntry(uint64_t log_index) const { if (0ull == log_index) { return nullptr; } assert(0ull < log_index); auto base_index = 0ull; auto last_index = 0ull; tie(base_index, last_index) = getInMemIndex(); if (log_index < base_index || log_index > last_index) { return nullptr; } assert(false == logs_.empty()); size_t idx = log_index - base_index; assert(0 <= idx && idx < logs_.size()); assert(nullptr != logs_[idx]); assert(log_index == logs_[idx]->index()); assert(0 < logs_[idx]->term()); return logs_[idx].get(); } std::vector<std::unique_ptr<raft::Entry>> RaftImpl::getLogEntriesAfter(uint64_t log_index) const { vector<unique_ptr<Entry>> vec_entries; uint64_t base_index = 0ull; uint64_t last_index = 0ull; tie(base_index, last_index) = getInMemIndex(); assert(base_index <= log_index + 1ull); if (log_index >= last_index) { return vec_entries; } assert(0ull < last_index - log_index); vec_entries.reserve(last_index - log_index); for (; log_index < last_index; ++log_index) { auto index = log_index + 1; auto entry = getLogEntry(index); assert(nullptr != entry); assert(index == entry->index()); vec_entries.emplace_back( cutils::make_unique<Entry>(*entry)); assert(nullptr != vec_entries.back()); vec_entries.back()->set_seq(pending_log_seq_); } return vec_entries; } std::unique_ptr<raft::RaftState> RaftImpl::getCurrentRaftState() const { auto hs = cutils::make_unique<RaftState>(); assert(nullptr != hs); hs->set_term(term_); hs->set_vote(vote_for_); hs->set_commit(commited_index_); hs->set_seq(pending_meta_seq_); return hs; } uint64_t RaftImpl::getLogTerm(uint64_t log_index) const { const auto entry = getLogEntry(log_index); if (nullptr == entry) { return 0ull; } return entry->term(); } bool RaftImpl::isIndexInMem(uint64_t log_index) const { return getBaseLogIndex() <= log_index; } void RaftImpl::beginVote() { assert_role(*this, RaftRole::CANDIDATE); // start election: // - increment currentTerm // - vote for self // - reset election timer // - send requestVote RPCs to all other servers setTerm(term_ + 1); // aka inc term setVoteFor(true, selfid_); assignStoreSeq(META_INDEX); // reset vote_resps_.clear(); vote_resps_[selfid_] = true; return ; } void RaftImpl::updateVote(uint64_t peer_id, bool current_rsp) { // current_rsp: // - true: vote yes; // - false: vote no; assert_role(*this, RaftRole::CANDIDATE); if (vote_resps_.end() == vote_resps_.find(peer_id)) { vote_resps_[peer_id] = current_rsp; return ; } bool prev_rsp = vote_resps_[peer_id]; logerr("peer_id %" PRIu64 " prev_rsp %d current_rsp %d", peer_id, static_cast<int>(prev_rsp), static_cast<int>(current_rsp)); // assert ? return ; } bool RaftImpl::isMajorVoteYes() const { assert_role(*this, RaftRole::CANDIDATE); return current_config_.IsMajorVoteYes(vote_resps_); } bool RaftImpl::isMatch(uint64_t log_index, uint64_t log_term) const { assert_role(*this, RaftRole::FOLLOWER); if (0ull == log_index) { assert(0ull == log_term); return true; // always } assert(0ull < log_index); assert(0ull < log_term); const uint64_t local_log_term = getLogTerm(log_index); if (local_log_term == log_term) { return true; } if (log_index <= commited_index_) { assert(0ull == local_log_term); return true; } assert(0ull == local_log_term || log_index <= getLastLogIndex()); return false; } void RaftImpl::updateLeaderCommitedIndex(uint64_t new_commited_index) { assert_role(*this, RaftRole::LEADER); assert(commited_index_ < new_commited_index); logdebug("selfid(leader) %" PRIu64 " commited_index_ %" PRIu64 " new_commited_index %" PRIu64, selfid_, commited_index_, new_commited_index); commited_index_ = new_commited_index; } void RaftImpl::updateFollowerCommitedIndex(uint64_t leader_commited_index) { assert_role(*this, RaftRole::FOLLOWER); assert(commited_index_ <= leader_commited_index); const uint64_t last_index = getLastLogIndex(); logdebug("selfid %" PRIu64 " commited_index_ %" PRIu64 " last_index %" PRIu64 " leader_commited_index %" PRIu64, selfid_, commited_index_, last_index, leader_commited_index); // if leaderCommit > commitIndex, // set commitIndex = min(leaderCommit, index of last new entry) commited_index_ = min(leader_commited_index, last_index); return ; } uint64_t RaftImpl::findConflict(const std::vector<const Entry*>& entries) const { if (size_t{0} == entries.size() || true == logs_.empty()) { return 0ull; } assert(size_t{0} < entries.size()); assert(false == logs_.empty()); for (size_t idx = 0; idx < entries.size(); ++idx) { assert(nullptr != entries[idx]); if (!isMatch(entries[idx]->index(), entries[idx]->term())) { return entries[idx]->index(); } } return entries[entries.size() -1]->index() + 1ull; } bool RaftImpl::updateReplicateState( uint64_t peer_id, bool reject, uint64_t reject_hint, uint64_t peer_next_index) { assert_role(*this, RaftRole::LEADER); assert(nullptr != replicate_states_); bool update = replicate_states_->UpdateReplicateState( peer_id, reject, reject_hint, peer_next_index); if (true == update) { auto new_commited_index = 0ull == peer_next_index ? 0ull : peer_next_index - 1ull; if (getTerm() == getLogTerm(new_commited_index) && new_commited_index > getCommitedIndex()) { if (current_config_.IsMajorCommited( new_commited_index, replicate_states_->peekMatchIndexes())) { updateLeaderCommitedIndex(new_commited_index); } } } return update; } void RaftImpl::becomeFollower(uint64_t term) { if (nullptr != replicate_states_) { replicate_states_.reset(); } assert(nullptr == replicate_states_); setRole(RaftRole::FOLLOWER); term = 0ull == term ? term_ + 1ull : term; assert(term_ < term); setTerm(term); setLeader(true, 0ull); setVoteFor(true, 0ull); // reset vote_for_ assignStoreSeq(META_INDEX); // new follower => will not timeout immidiate; resetElectionTimeout(); updateActiveTime(chrono::system_clock::now()); // TODO ?? return ; } void RaftImpl::becomeCandidate() { assert(nullptr == replicate_states_); setRole(RaftRole::CANDIDATE); setLeader(true, 0ull); // raft paper // Candidates 5.2 // On conversion to candidate or election timeout elapse, // start election: // - inc term // - set vote for // - assign store seq beginVote(); resetElectionTimeout(); updateActiveTime(chrono::system_clock::now()); return ; } void RaftImpl::becomeLeader() { setRole(RaftRole::LEADER); // raft paper // State // nextIndex[] // for each server, index of the next log entry to send to that // server(initialized to leader last log index + 1) // matchIndex[] // for each server, index of highest log entry known to be // replicated on server(initailzed to 0, increases monotonically) setLeader(false, selfid_); assert(selfid_ == leader_id_); assert(nullptr == replicate_states_); replicate_states_ = current_config_.CreateReplicateTracker(getLastLogIndex(), MAX_BATCH_SIZE); assert(nullptr != replicate_states_); makeHeartbeatTimeout(chrono::system_clock::now()); return ; } void RaftImpl::setLeader(bool reset, uint64_t leader_id) { logdebug("selfid_ %" PRIu64 " reset %d leader_id_ %" PRIu64 " to leader_id %" PRIu64, selfid_, static_cast<int>(reset), leader_id_, leader_id); if (true == reset || 0ull == leader_id_) { leader_id_ = leader_id; } } bool RaftImpl::isHeartbeatTimeout( std::chrono::time_point< std::chrono::system_clock> time_now) { return hb_time_ + hb_timeout_ < time_now; } void RaftImpl::updateHeartbeatTime( std::chrono::time_point< std::chrono::system_clock> next_hb_time) { { auto hb_str = cutils::format_time(hb_time_); auto next_hb_str = cutils::format_time(next_hb_time); logdebug("selfid %" PRIu64 " update hb_time_ %s to next_hb_time %s", getSelfId(), hb_str.c_str(), next_hb_str.c_str()); } hb_time_ = next_hb_time; } void RaftImpl::makeElectionTimeout( std::chrono::time_point<std::chrono::system_clock> tp) { tp -= chrono::milliseconds{getElectionTimeout() + 1}; updateActiveTime(tp); } void RaftImpl::makeHeartbeatTimeout( std::chrono::time_point<std::chrono::system_clock> tp) { tp -= chrono::milliseconds{getHeartbeatTimeout() + 1}; updateHeartbeatTime(tp); } std::unique_ptr<raft::RaftState> RaftImpl::getPendingRaftState() const { if (0ull == pending_meta_seq_) { return nullptr; } return getCurrentRaftState(); } std::vector<std::unique_ptr<raft::Entry>> RaftImpl::getPendingLogEntries() const { if (0ull == pending_log_idx_) { assert(0ull == pending_log_seq_); return vector<unique_ptr<Entry>>{}; } assert(0ull < pending_log_idx_); assert(0ull < pending_log_seq_); return getLogEntriesAfter(pending_log_idx_ - 1ull); } void RaftImpl::resetElectionTimeout() { int next_election_timeout = rtimeout_(); assert(0 < next_election_timeout); logdebug("election_timeout_ %d next_election_timeout %d", static_cast<int>(election_timeout_.count()), next_election_timeout); election_timeout_ = chrono::milliseconds{next_election_timeout}; } bool RaftImpl::isPeerUpToDate(uint64_t peer_commited_index) const { assert(peer_commited_index <= commited_index_); return peer_commited_index == commited_index_; } void RaftImpl::assertNoPending() const { assert(RaftRole::LEADER == getRole()); assert(nullptr != replicate_states_); for (const auto& id_pending : replicate_states_->peekPendingState()) { if (getSelfId() == id_pending.first) { continue; } assert(false == id_pending.second); } } int RaftImpl::applyUnCommitedConfEntry(const Entry& conf_entry) { ConfChange conf_change; auto ret = ApplyConfChange( conf_entry, true, conf_change, current_config_); if (0 != ret) { return ret; } // 3. if (nullptr == replicate_states_) { return 0; } assert(RaftRole::LEADER == getRole()); replicate_states_->ApplyConfChange(conf_change, getLastLogIndex()); return 0; } int RaftImpl::applyCommitedConfEntry(const Entry& conf_entry) { ConfChange conf_change; return ApplyConfChange( conf_entry, false, conf_change, commited_config_); } int RaftImpl::reconstructCurrentConfig() { assert(RaftRole::FOLLOWER == getRole()); current_config_ = commited_config_; auto last_index = getLastLogIndex(); for (auto index = getCommitedIndex() + 1ull; index <= last_index; ++index) { auto entry = getLogEntry(index); assert(nullptr != entry); ConfChange conf_change; auto ret = ApplyConfChange( *entry, true, conf_change, current_config_); if (0 != ret) { return ret; } assert(0 == ret); } return 0; } } // namespace raft
31.015757
82
0.589749
dengoswei
a53314e22a638de0302a218fb6db0734a3235269
364
cpp
C++
headers/main/bw_encode.cpp
SamBuckberry/readslam
47c5cd0e407f17db08a70488913905f86cffe054
[ "CC-BY-3.0" ]
null
null
null
headers/main/bw_encode.cpp
SamBuckberry/readslam
47c5cd0e407f17db08a70488913905f86cffe054
[ "CC-BY-3.0" ]
null
null
null
headers/main/bw_encode.cpp
SamBuckberry/readslam
47c5cd0e407f17db08a70488913905f86cffe054
[ "CC-BY-3.0" ]
null
null
null
#include "../algorithms/sorting.h" #include "../tools/_fasta.h" int main (int argc, char * const argv[]) { if (argc != 3) { cout << "Encode a genome's fasta sequences using the Burrows-Wheeler algorithm." << endl; cout << "Usage: ./burrows_wheeler /infile.fa /outfile.fa" << endl; exit(0); } ReadSlam::FastA::Genome g; g.bw_encode(argv[1], argv[2]); }
24.266667
91
0.645604
SamBuckberry
a53361e4645143c7ce4a6fb44ce50adbc3a85dd6
2,148
cpp
C++
apps/xcomp/src/XCConfig.cpp
gugenstudio/Xcomp
b8c572ec618fa157c4ed07845b87d0ced21b2dd5
[ "MIT" ]
1
2022-02-18T11:55:57.000Z
2022-02-18T11:55:57.000Z
apps/xcomp/src/XCConfig.cpp
gugenstudio/xComp
b8c572ec618fa157c4ed07845b87d0ced21b2dd5
[ "MIT" ]
null
null
null
apps/xcomp/src/XCConfig.cpp
gugenstudio/xComp
b8c572ec618fa157c4ed07845b87d0ced21b2dd5
[ "MIT" ]
null
null
null
//================================================================== /// XCConfig.cpp /// /// Created by Davide Pasca - 2022/01/21 /// See the file "license.txt" that comes with this project for /// copyright info. //================================================================== #include "GTVersions.h" #include "XCConfig.h" //================================================================== void XCConfig::Serialize( SerialJS &v_ ) const { v_.MSerializeObjectStart(); SerializeMember( v_, "cfg_savedVer", DStr(GTV_SUITE_VERSION) ); SERIALIZE_THIS_MEMBER( v_, cfg_scanDir ); SERIALIZE_THIS_MEMBER( v_, cfg_scanDirHist ); SERIALIZE_THIS_MEMBER( v_, cfg_saveDir ); SERIALIZE_THIS_MEMBER( v_, cfg_ctrlPanButton ); SERIALIZE_THIS_MEMBER( v_, cfg_dispAutoFit ); SERIALIZE_THIS_MEMBER( v_, cfg_imsConfig ); v_.MSerializeObjectEnd(); } void XCConfig::Deserialize( DeserialJS &v_ ) { DESERIALIZE_THIS_MEMBER( v_, cfg_savedVer ); DESERIALIZE_THIS_MEMBER( v_, cfg_scanDir ); DESERIALIZE_THIS_MEMBER( v_, cfg_scanDirHist ); DESERIALIZE_THIS_MEMBER( v_, cfg_saveDir ); DESERIALIZE_THIS_MEMBER( v_, cfg_ctrlPanButton ); DESERIALIZE_THIS_MEMBER( v_, cfg_dispAutoFit ); DESERIALIZE_THIS_MEMBER( v_, cfg_imsConfig ); // remove empty or unreachable directories for (auto it=cfg_scanDirHist.begin(); it != cfg_scanDirHist.end();) { if ( it->empty() || !FU_DirectoryExists( *it ) ) it = cfg_scanDirHist.erase( it ); else ++it; } } //================================================================== bool XCConfig::AddScanDirToHistory() { auto &v = cfg_scanDirHist; if ( !cfg_scanDir.empty() && v.end() == std::find( v.begin(), v.end(), cfg_scanDir ) ) { // erase the oldest, if there are too many entries if ( v.size() >= 10 ) v.erase( v.begin() ); // append the new one v.push_back( cfg_scanDir ); return true; } return false; }
33.5625
71
0.533985
gugenstudio
a5341057111530e24eeb851aa8f9fe420ae62ddd
16,339
cpp
C++
libcsvsqldb/sql_lexer.cpp
fuersten/csvsqldb
1b766ddf253805e31f9840cd3081cba559018a06
[ "BSD-3-Clause" ]
5
2015-09-10T08:53:41.000Z
2020-05-30T18:42:20.000Z
libcsvsqldb/sql_lexer.cpp
fuersten/csvsqldb
1b766ddf253805e31f9840cd3081cba559018a06
[ "BSD-3-Clause" ]
20
2015-09-29T16:16:07.000Z
2021-06-13T08:08:05.000Z
libcsvsqldb/sql_lexer.cpp
fuersten/csvsqldb
1b766ddf253805e31f9840cd3081cba559018a06
[ "BSD-3-Clause" ]
3
2015-09-09T22:51:44.000Z
2020-11-11T13:19:42.000Z
// // sql_lexer.h // csv db // // BSD 3-Clause License // Copyright (c) 2015, Lars-Christian Fürstenberg // 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. // #include "sql_lexer.h" #include "base/logging.h" #include "base/string_helper.h" namespace csvsqldb { std::string tokenToString(eToken token) { switch(static_cast<csvsqldb::lexer::eToken>(token)) { case csvsqldb::lexer::UNDEFINED: return "UNDEFINED"; case csvsqldb::lexer::NEWLINE: return "NEWLINE"; case csvsqldb::lexer::WHITESPACE: return "WHITESPACE"; case csvsqldb::lexer::EOI: return "EOI"; } switch(token) { case TOK_NONE: return "TOK_NONE"; case TOK_IDENTIFIER: return "identifier"; case TOK_QUOTED_IDENTIFIER: return "quoted identifier"; case TOK_CONST_STRING: return "string constant"; case TOK_CONST_INTEGER: return "integer constant"; case TOK_CONST_BOOLEAN: return "boolean constant"; case TOK_CONST_DATE: return "date constant"; case TOK_CONST_REAL: return "real constant"; case TOK_CONST_CHAR: return "char constant"; case TOK_DOT: return "."; case TOK_DESCRIBE: return "DESCRIBE"; case TOK_AST: return "AST"; case TOK_SMALLER: return "<"; case TOK_GREATER: return ">"; case TOK_EQUAL: return "="; case TOK_NOTEQUAL: return "<>"; case TOK_GREATEREQUAL: return ">="; case TOK_SMALLEREQUAL: return "<="; case TOK_CONCAT: return "||"; case TOK_ADD: return "+"; case TOK_SUB: return "-"; case TOK_DIV: return "/"; case TOK_MOD: return "%"; case TOK_ASTERISK: return "*"; case TOK_COMMA: return ","; case TOK_SEMICOLON: return ";"; case TOK_LEFT_PAREN: return "("; case TOK_RIGHT_PAREN: return ")"; case TOK_COMMENT: return "comment"; case TOK_UNION: return "UNION"; case TOK_INTERSECT: return "INTERSECT"; case TOK_EXCEPT: return "EXCEPT"; case TOK_SELECT: return "SELECT"; case TOK_AS: return "AS"; case TOK_ALL: return "ALL"; case TOK_CAST: return "CAST"; case TOK_DISTINCT: return "DISTINCT"; case TOK_FROM: return "FROM"; case TOK_WHERE: return "WHERE"; case TOK_ON: return "ON"; case TOK_USING: return "USING"; case TOK_NATURAL: return "NATURAL"; case TOK_LEFT: return "LEFT"; case TOK_RIGHT: return "RIGHT"; case TOK_INNER: return "INNER"; case TOK_OUTER: return "OUTER"; case TOK_CROSS: return "CROSS"; case TOK_FULL: return "FULL"; case TOK_JOIN: return "JOIN"; case TOK_LIKE: return "LIKE"; case TOK_AND: return "AND"; case TOK_OR: return "OR"; case TOK_NOT: return "NOT"; case TOK_IS: return "IS"; case TOK_NULL: return "NULL"; case TOK_BETWEEN: return "BETWEEN"; case TOK_IN: return "IN"; case TOK_EXISTS: return "EXISTS"; case TOK_GROUP: return "GROUP"; case TOK_ORDER: return "ORDER"; case TOK_BY: return "BY"; case TOK_COLLATE: return "COLLATE"; case TOK_ASC: return "ASC"; case TOK_DESC: return "DESC"; case TOK_HAVING: return "HAVING"; case TOK_LIMIT: return "LIMIT"; case TOK_OFFSET: return "OFFSET"; case TOK_CREATE: return "CREATE"; case TOK_TABLE: return "TABLE"; case TOK_IF: return "IF"; case TOK_CONSTRAINT: return "CONSTRAINT"; case TOK_PRIMARY: return "PRIMARY"; case TOK_KEY: return "KEY"; case TOK_UNIQUE: return "UNIQUE"; case TOK_DEFAULT: return "DEFAULT"; case TOK_CHECK: return "CHECK"; case TOK_BOOL: return "BOOLEAN"; case TOK_INT: return "INTEGER"; case TOK_REAL: return "REAL"; case TOK_STRING: return "STRING"; case TOK_CHAR: return "CHARACTER"; case TOK_DATE: return "DATE"; case TOK_TIME: return "TIME"; case TOK_TIMESTAMP: return "TIMESTAMP"; case TOK_ALTER: return "ALTER"; case TOK_COLUMN: return "COLUMN"; case TOK_DROP: return "DROP"; case TOK_ADD_KEYWORD: return "ADD"; case TOK_SUM: return "SUM"; case TOK_COUNT: return "COUNT"; case TOK_AVG: return "AVG"; case TOK_MAX: return "MAX"; case TOK_MIN: return "MIN"; case TOK_CURRENT_DATE: return "CURRENT_DATE"; case TOK_CURRENT_TIME: return "CURRENT_TIME"; case TOK_CURRENT_TIMESTAMP: return "CURRENT_TIMESTAMP"; case TOK_VARYING: return "VARYING"; case TOK_EXTRACT: return "EXTRACT"; case TOK_SECOND: return "SECOND"; case TOK_MINUTE: return "MINUTE"; case TOK_HOUR: return "HOUR"; case TOK_YEAR: return "YEAR"; case TOK_MONTH: return "MONTH"; case TOK_DAY: return "DAY"; case TOK_EXPLAIN: return "EXPLAIN"; case TOK_SHOW: return "SHOW"; case TOK_MAPPING: return "MAPPING"; case TOK_EXEC: return "EXEC"; case TOK_ARBITRARY: return "ARBITRARY"; } throw std::runtime_error("just to make VC2013 happy"); } SQLLexer::SQLLexer(const std::string& input) : _lexer(std::bind(&SQLLexer::inspectToken, this, std::placeholders::_1)) { initDefinitions(); initKeywords(); _lexer.setInput(input); } void SQLLexer::setInput(const std::string& input) { _lexer.setInput(input); } void SQLLexer::initDefinitions() { _lexer.addDefinition("bool", R"([tT][rR][uU][eE])", TOK_CONST_BOOLEAN); _lexer.addDefinition("bool", R"([fF][aA][lL][sS][eE])", TOK_CONST_BOOLEAN); _lexer.addDefinition("bool", R"([uU][nN][kK][nN][oO][wW][nN])", TOK_CONST_BOOLEAN); _lexer.addDefinition("identifier", R"([_a-zA-Z][_a-zA-Z0-9]*)", TOK_IDENTIFIER); _lexer.addDefinition("quoted identifier", R"(\"([^\"]*)\")", TOK_QUOTED_IDENTIFIER); _lexer.addDefinition("char", R"('([^'])')", TOK_CONST_CHAR); _lexer.addDefinition("string", R"('([^']*)')", TOK_CONST_STRING); _lexer.addDefinition("concat", R"(\|\|)", TOK_CONCAT); _lexer.addDefinition("add", R"(\+)", TOK_ADD); _lexer.addDefinition("comment", R"(--([^\r\n]*))", TOK_COMMENT); _lexer.addDefinition("sub", R"(-)", TOK_SUB); _lexer.addDefinition("point", R"(\.)", TOK_DOT); _lexer.addDefinition("real", R"((?:0|[1-9]\d*)\.\d+)", TOK_CONST_REAL); _lexer.addDefinition("integer", R"(0|[1-9]\d*)", TOK_CONST_INTEGER); _lexer.addDefinition("string", R"('([^']*)')", TOK_CONST_STRING); _lexer.addDefinition("equal", R"(=)", TOK_EQUAL); _lexer.addDefinition("greater equal", R"(>=)", TOK_GREATEREQUAL); _lexer.addDefinition("smaller equal", R"(<=)", TOK_SMALLEREQUAL); _lexer.addDefinition("notequal", R"(<>)", TOK_NOTEQUAL); _lexer.addDefinition("smaller", R"(<)", TOK_SMALLER); _lexer.addDefinition("greater", R"(>)", TOK_GREATER); _lexer.addDefinition("comma", R"(,)", TOK_COMMA); _lexer.addDefinition("semicolon", R"(;)", TOK_SEMICOLON); _lexer.addDefinition("asterisk", R"(\*)", TOK_ASTERISK); _lexer.addDefinition("left_paren", R"(\()", TOK_LEFT_PAREN); _lexer.addDefinition("right_paren", R"(\))", TOK_RIGHT_PAREN); _lexer.addDefinition("comment", R"(/\*((.|[\r\n])*?)\*/)", TOK_COMMENT); _lexer.addDefinition("div", R"(/)", TOK_DIV); _lexer.addDefinition("mod", R"(%)", TOK_MOD); } void SQLLexer::initKeywords() { _keywords["UNION"] = eToken(TOK_UNION); _keywords["SELECT"] = eToken(TOK_SELECT); _keywords["FROM"] = eToken(TOK_FROM); _keywords["WHERE"] = eToken(TOK_WHERE); _keywords["USING"] = eToken(TOK_USING); _keywords["INTERSECT"] = eToken(TOK_INTERSECT); _keywords["EXCEPT"] = eToken(TOK_EXCEPT); _keywords["AS"] = eToken(TOK_AS); _keywords["ALL"] = eToken(TOK_ALL); _keywords["CAST"] = eToken(TOK_CAST); _keywords["DISTINCT"] = eToken(TOK_DISTINCT); _keywords["ON"] = eToken(TOK_ON); _keywords["NATURAL"] = eToken(TOK_NATURAL); _keywords["LEFT"] = eToken(TOK_LEFT); _keywords["RIGHT"] = eToken(TOK_RIGHT); _keywords["INNER"] = eToken(TOK_INNER); _keywords["OUTER"] = eToken(TOK_OUTER); _keywords["CROSS"] = eToken(TOK_CROSS); _keywords["FULL"] = eToken(TOK_FULL); _keywords["JOIN"] = eToken(TOK_JOIN); _keywords["LIKE"] = eToken(TOK_LIKE); _keywords["AND"] = eToken(TOK_AND); _keywords["OR"] = eToken(TOK_OR); _keywords["NOT"] = eToken(TOK_NOT); _keywords["IS"] = eToken(TOK_IS); _keywords["NULL"] = eToken(TOK_NULL); _keywords["BETWEEN"] = eToken(TOK_BETWEEN); _keywords["IN"] = eToken(TOK_IN); _keywords["EXISTS"] = eToken(TOK_EXISTS); _keywords["GROUP"] = eToken(TOK_GROUP); _keywords["ORDER"] = eToken(TOK_ORDER); _keywords["BY"] = eToken(TOK_BY); _keywords["COLLATE"] = eToken(TOK_COLLATE); _keywords["ASC"] = eToken(TOK_ASC); _keywords["DESC"] = eToken(TOK_DESC); _keywords["HAVING"] = eToken(TOK_HAVING); _keywords["LIMIT"] = eToken(TOK_LIMIT); _keywords["OFFSET"] = eToken(TOK_OFFSET); _keywords["CREATE"] = eToken(TOK_CREATE); _keywords["TABLE"] = eToken(TOK_TABLE); _keywords["IF"] = eToken(TOK_IF); _keywords["BOOLEAN"] = eToken(TOK_BOOL); _keywords["BOOL"] = eToken(TOK_BOOL); _keywords["INT"] = eToken(TOK_INT); _keywords["INTEGER"] = eToken(TOK_INT); _keywords["REAL"] = eToken(TOK_REAL); _keywords["FLOAT"] = eToken(TOK_REAL); _keywords["DOUBLE"] = eToken(TOK_REAL); _keywords["VARCHAR"] = eToken(TOK_STRING); _keywords["CHAR"] = eToken(TOK_CHAR); _keywords["CHARACTER"] = eToken(TOK_CHAR); _keywords["DATE"] = eToken(TOK_DATE); _keywords["TIME"] = eToken(TOK_TIME); _keywords["TIMESTAMP"] = eToken(TOK_TIMESTAMP); _keywords["CONSTRAINT"] = eToken(TOK_CONSTRAINT); _keywords["PRIMARY"] = eToken(TOK_PRIMARY); _keywords["KEY"] = eToken(TOK_KEY); _keywords["UNIQUE"] = eToken(TOK_UNIQUE); _keywords["DEFAULT"] = eToken(TOK_DEFAULT); _keywords["CHECK"] = eToken(TOK_CHECK); _keywords["ALTER"] = eToken(TOK_ALTER); _keywords["COLUMN"] = eToken(TOK_COLUMN); _keywords["DROP"] = eToken(TOK_DROP); _keywords["ADD"] = eToken(TOK_ADD_KEYWORD); _keywords["SUM"] = eToken(TOK_SUM); _keywords["COUNT"] = eToken(TOK_COUNT); _keywords["AVG"] = eToken(TOK_AVG); _keywords["MAX"] = eToken(TOK_MAX); _keywords["MIN"] = eToken(TOK_MIN); _keywords["CURRENT_DATE"] = eToken(TOK_CURRENT_DATE); _keywords["CURRENT_TIME"] = eToken(TOK_CURRENT_TIME); _keywords["CURRENT_TIMESTAMP"] = eToken(TOK_CURRENT_TIMESTAMP); _keywords["VARYING"] = eToken(TOK_VARYING); _keywords["DESCRIBE"] = eToken(TOK_DESCRIBE); _keywords["AST"] = eToken(TOK_AST); _keywords["EXTRACT"] = eToken(TOK_EXTRACT); _keywords["SECOND"] = eToken(TOK_SECOND); _keywords["MINUTE"] = eToken(TOK_MINUTE); _keywords["HOUR"] = eToken(TOK_HOUR); _keywords["YEAR"] = eToken(TOK_YEAR); _keywords["MONTH"] = eToken(TOK_MONTH); _keywords["DAY"] = eToken(TOK_DAY); _keywords["EXPLAIN"] = eToken(TOK_EXPLAIN); _keywords["SHOW"] = eToken(TOK_SHOW); _keywords["MAPPING"] = eToken(TOK_MAPPING); _keywords["EXEC"] = eToken(TOK_EXEC); _keywords["ARBITRARY"] = eToken(TOK_ARBITRARY); } void SQLLexer::inspectToken(csvsqldb::lexer::Token& token) { CSVSQLDB_CLASSLOG(SQLLexer, 2, "Intercepted : " << token._value); if(token._token == TOK_IDENTIFIER) { Keywords::const_iterator iter = _keywords.find(csvsqldb::toupper(token._value)); if(iter != _keywords.end()) { token._token = iter->second; CSVSQLDB_CLASSLOG(SQLLexer, 2, "Intercepted : adapted token"); } } } csvsqldb::lexer::Token SQLLexer::next() { csvsqldb::lexer::Token tok = _lexer.next(); while(tok._token == TOK_COMMENT) { tok = _lexer.next(); } return tok; } }
37.134091
98
0.53461
fuersten
a536f2d5e320c70a40fa940527f46bc4c9407327
10,256
cpp
C++
11_learning_materials/stanford_self_driving_car/driving/imagery/src/textureCache.cpp
EatAllBugs/autonomous_learning
02ff7b0fa7b131a2f2203505ef5cc7e43b40bc47
[ "MIT" ]
14
2021-09-01T14:25:45.000Z
2022-02-21T08:49:57.000Z
11_learning_materials/stanford_self_driving_car/driving/imagery/src/textureCache.cpp
yinflight/autonomous_learning
02ff7b0fa7b131a2f2203505ef5cc7e43b40bc47
[ "MIT" ]
null
null
null
11_learning_materials/stanford_self_driving_car/driving/imagery/src/textureCache.cpp
yinflight/autonomous_learning
02ff7b0fa7b131a2f2203505ef5cc7e43b40bc47
[ "MIT" ]
3
2021-10-10T00:58:29.000Z
2022-01-23T13:16:09.000Z
/******************************************************** Stanford Driving Software Copyright (c) 2011 Stanford University All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * The names of the contributors may not 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 <iostream> #include <global.h> #include <textureCache.h> #include <imageryServer.h> #include <imagery_proj.h> namespace vlr { TextureCache::TextureCache(const std::string& imagery_root, uint64_t max_images) : comp_refs_(image_), version_num_(0), max_images_(max_images), imagery_root_(imagery_root), last_grayscale_(false), current_reference_(0), stop_thread_(false) { for (uint64_t i = 0; i < max_images_; i++) { image_.push_back(new TimedImage); } pthread_create(&loader_thread_id_, NULL, threadCBWrapper<TextureCache, &TextureCache::loaderThread>, this); } TextureCache::~TextureCache() { stop_thread_ = true; pthread_join(loader_thread_id_, NULL); for (uint64_t i = 0; i < max_images_; i++) { delete image_[i]; } } bool TextureCache::sameId(TileId& id1, TileId& id2) { if (id1.type != id2.type) return false; if (id1.x != id2.x) return false; if (id1.y != id2.y) return false; if (id1.res != id2.res) return false; if (id1.zone != id2.zone) return false; return true; } uint64_t TextureCache::lookup(TileId id) { /* locate image in cache */ bool found = false; uint64_t which = 0; for (uint64_t i = 0; i < max_images_; i++) { if (image_[i]->state != UNINITIALIZED && sameId(image_[i]->id, id)) { which = i; found = true; break; } } if (found) { // image is in cache image_[which]->last_reference = current_reference_; current_reference_++; return which; } // image is not in cache // find unused or oldest used image; TODO: optimize search for (uint64_t i = 0; i < max_images_; i++) { if (image_[i]->state == UNINITIALIZED) { found = true; which = i; break; } else if (image_[i]->state == READY && (!found || (found && image_[i]->last_reference < image_[which]->last_reference))) { found = true; which = i; } } if (found) { if (image_[which]->state == READY) { if (image_[which]->image != NULL) { delete image_[which]->image; image_[which]->image = NULL; } } image_[which]->exists = true; image_[which]->last_reference = current_reference_; image_[which]->id = id; image_[which]->state = REQUESTED; current_reference_++; return which; } else { throw VLRException("Image list has no empty spots. This shouldn't happen."); } } void TextureCache::resetCounters() { static std::vector<int64_t> id; if (id.size() != max_images_) { id.resize(max_images_); } for (uint64_t i = 0; i < max_images_; i++) {id[i] = i;} sort(id.begin(), id.end(), comp_refs_); for (uint64_t i = 0; i < max_images_; i++) { image_[id[i]]->last_reference = i; } current_reference_ = max_images_ + 1; } void TextureCache::syncTexture(uint64_t i) { TimedImage& image = *image_[i]; if (image.state == READY && image.needs_sync) { image.needs_sync = false; if (image.image == NULL) return; image.texture.updateFromImage(*image.image); delete image.image; image.image = NULL; } } bool TextureCache::syncCache() { static int32_t count = 0; if (count > 10) { // ?!? resetCounters(); count = 0; } count++; bool needs_sync = false; for (uint64_t i = 0; i < max_images_; i++) if (image_[i]->needs_sync) { needs_sync = true; break; } if (needs_sync) { for (uint64_t i = 0; i < max_images_; i++) { if (image_[i]->needs_sync) { syncTexture(i); } } return true; } return false; } Texture* TextureCache::get(const std::string& detected_subdir, TileId& id, int priority, ImageState_t& state) { // std:: cout << "detected_subdir: " << detected_subdir << std::endl; // std:: cout << "imagery_root_: " << imagery_root_ << std::endl; // std:: cout << "Requested tile id with type " << id.type << "; x, y: " << id.x << ", " << id.y << "; res: " << id.res << "; zone: "<< id.zone << std::endl; if(!detected_subdir.empty() && detected_subdir_ != detected_subdir) { detected_subdir_ = detected_subdir; } uint64_t i = 0; try { i = lookup(id); } catch(vlr::Ex<>& e) { std::cout << e.what() << std::endl; state = UNINITIALIZED; return NULL; } if (priority && image_[i]->state == READY) {syncTexture(i);} image_[i]->last_reference = current_reference_; current_reference_++; if (image_[i]->state != UNINITIALIZED && image_[i]->exists) { state = image_[i]->state; last_grayscale_ = image_[i]->grayscale; return &image_[i]->texture; } state = UNINITIALIZED; return NULL; } size_t curl_callback(void* ptr, size_t size, size_t nmemb, void* data) { std::vector<uint8_t>* mem = static_cast<std::vector<uint8_t>*>(data); size_t realsize = size * nmemb; mem->resize(mem->size() + realsize + 1); // +1 to have a final zero element memcpy(&((*mem)[mem->size()]), ptr, realsize); return realsize; } void* TextureCache::loaderThread() { char server_name[200], filename[200], whole_filename[200]; int server_port; char *mark, *mark2; #ifdef HAVE_LIBCURL CURLcode curl_return; /* init the curl session */ curl_global_init(CURL_GLOBAL_ALL); CURL* curl_handle = curl_easy_init(); curl_easy_setopt(curl_handle, CURLOPT_USERAGENT, "libcurl-agent/1.0"); curl_easy_setopt(curl_handle, CURLOPT_WRITEFUNCTION, curl_callback); curl_easy_setopt(curl_handle, CURLOPT_WRITEDATA, (void *)&curl_buf_); curl_easy_setopt(curl_handle, CURLOPT_CONNECTTIMEOUT, 1); curl_easy_setopt(curl_handle, CURLOPT_FAILONERROR, 1); curl_easy_setopt(curl_handle, CURLOPT_NOSIGNAL, 1); #endif sleep(1); // ?!? while (!stop_thread_) { for (uint64_t i = 0; i < max_images_; i++) { if (image_[i]->state == REQUESTED) { if (version_num_ != 2) { if (image_[i]->id.type == Imagery::COLOR) dgc_terra_color_tile_filename(image_[i]->id, filename, version_num_); else if (image_[i]->id.type == Imagery::TOPO) dgc_terra_topo_tile_filename(image_[i]->id, filename, version_num_); else if (image_[i]->id.type == Imagery::LASER) dgc_laser_tile_filename(image_[i]->id, filename, version_num_); else if (image_[i]->id.type == Imagery::GSAT) dgc_gmaps_tile_filename(image_[i]->id, filename); else if (image_[i]->id.type == Imagery::DARPA) dgc_darpa_tile_filename(image_[i]->id, filename, version_num_); else if (image_[i]->id.type == Imagery::BW) dgc_terra_bw_tile_filename(image_[i]->id, filename); if (version_num_ == 0) { sprintf(whole_filename, "%s/%s/%s", imagery_root_.c_str(), detected_subdir_.c_str(), filename); } else if (version_num_ == 1) { sprintf(whole_filename, "%s/%s", imagery_root_.c_str(), filename); } } switch (version_num_) { case 0: if (dgc::dgc_file_exists(whole_filename)) { image_[i]->image = new cv::Mat; *image_[i]->image = cv::imread(whole_filename, CV_LOAD_IMAGE_ANYCOLOR); } else { image_[i]->image = NULL; } break; case 1: #ifdef HAVE_LIBCURL /* handle http queries with libcurl */ curl_easy_setopt(curl_handle, CURLOPT_URL, whole_filename); curl_return = curl_easy_perform(curl_handle); if(stop_thread_) {return NULL;} // ?!? if(curl_return == 0) { image_[i]->image = cv::imdecode(cv::Mat(curl_buf_, false), CV_LOAD_IMAGE_ANYCOLOR); } curl_buf_.clear(); #else image_[i]->image = new cv::Mat; *image_[i]->image = cv::imread(whole_filename, CV_LOAD_IMAGE_ANYCOLOR); #endif break; case 2: strcpy(server_name, imagery_root_.c_str() + 6); if ((mark = strchr(server_name, ':')) != NULL) { server_port = strtol(mark + 1, &mark2, 10); *mark = '\0'; } else { server_port = 3000; if ((mark = strchr(server_name, '/')) != NULL) *mark = '\0'; } image_[i]->image = img_server_.getImage(server_name, server_port, image_[i]->id); break; } if (!image_[i]->image) { image_[i]->exists = false; } else { image_[i]->grayscale = (image_[i]->image->channels() == 1); } image_[i]->needs_sync = true; image_[i]->state = READY; } } usleep(10000); } return NULL; } } // namespace vlr
30.984894
158
0.621002
EatAllBugs
a537453ebe8afbcecef93c2edf6967138dd7c11d
1,899
hxx
C++
session/KAutoLogon.hxx
Peter2121/kts
fb1a9d67dc5ef22ad8ec3bf445525c8d8b1b9a3a
[ "BSD-3-Clause" ]
null
null
null
session/KAutoLogon.hxx
Peter2121/kts
fb1a9d67dc5ef22ad8ec3bf445525c8d8b1b9a3a
[ "BSD-3-Clause" ]
null
null
null
session/KAutoLogon.hxx
Peter2121/kts
fb1a9d67dc5ef22ad8ec3bf445525c8d8b1b9a3a
[ "BSD-3-Clause" ]
null
null
null
#pragma once #include <algorithm> #include "..\shared\KTrace.hxx" #include "..\shared\Kini.hxx" #include "..\shared\KSlre.hxx" class KAutoLogon { private: /*============================================================================== * var *=============================================================================*/ struct Pattern { std::string address; std::string username; std::string password; std::string domain; }; std::vector < Pattern > patterns; public: /*============================================================================== * load from file *=============================================================================*/ void Load( std::string file ) { ktrace_in( ); ktrace( "KAutoLogon::Load( " << file << " )" ); KIni ini; ini.File( file ); for( unsigned i = 0; i < 1024; i++ ) { Pattern p; std::stringstream s; s << "address" << i; if( !ini.GetKey( "KAutoLogon", s.str( ), p.address, "eof" ) ) break; s.str( "" ); s << "username" << i; ini.GetKey( "KAutoLogon", s.str( ), p.username ); s.str( "" ); s << "password" << i; ini.GetKey( "KAutoLogon", s.str( ), p.password ); s.str( "" ); s << "domain" << i; ini.GetKey( "KAutoLogon", s.str( ), p.domain ); this->patterns.push_back( p ); } } bool GetAutoCredentials( const std::string& ipaddress, std::string& username, std::string& password, std::string& domain ) { ktrace_in( ); ktrace( "KAutoLogon::GetAutoCredentials( " << ipaddress << ", <out> )" ); for( unsigned i = 0; i < this->patterns.size( ); i++ ) { KSlre kslre; if(kslre.Match(ipaddress, patterns[i].address)) { username = patterns[i].username; password = patterns[i].password; domain = patterns[i].domain; return true; } } return false; } };
23.7375
124
0.460242
Peter2121
a539d799a6c38157168ce01558691874c43f1187
1,216
cpp
C++
src/engine/shader/text/SingnedDistanceOutlineTextShader.cpp
Armanimani/Game-Engine
8087cd999f7264488d24a5dc5571b659347a49dd
[ "MIT" ]
null
null
null
src/engine/shader/text/SingnedDistanceOutlineTextShader.cpp
Armanimani/Game-Engine
8087cd999f7264488d24a5dc5571b659347a49dd
[ "MIT" ]
1
2017-04-05T01:40:02.000Z
2017-04-05T07:36:55.000Z
src/engine/shader/text/SingnedDistanceOutlineTextShader.cpp
Armanimani/Game-Engine
8087cd999f7264488d24a5dc5571b659347a49dd
[ "MIT" ]
null
null
null
#include "SingnedDistanceOutlineTextShader.h" void SignedDistanceOutlineTextShader::loadAllToUniform(const std::shared_ptr<GUITextModel> model) { SignedDistanceTextShader::loadAllToUniform(model); loadToUniform(location_outlineColor, model->getMaterial()->getProperties().color2); loadToUniform(location_outlineWidth, model->getMaterial()->getProperties().fontOutlineWidth); loadToUniform(location_outlineEdge, model->getMaterial()->getProperties().fontOutlineEdge); loadToUniform(location_outlineOffsetX, model->getMaterial()->getProperties().fontOutlineOffsetX); loadToUniform(location_outlineOffsetY, model->getMaterial()->getProperties().fontOutlineOffsetY); } void SignedDistanceOutlineTextShader::getAllUniformLocations() { SignedDistanceTextShader::getAllUniformLocations(); std::string temp; temp = "matOutlineColor"; location_outlineColor = getUniformLocation(temp); temp = "matOutlineWidth"; location_outlineWidth = getUniformLocation(temp); temp = "matOutlineEdge"; location_outlineEdge = getUniformLocation(temp); temp = "matOutlineOffsetX"; location_outlineOffsetX = getUniformLocation(temp); temp = "matOutlineOffsetY"; location_outlineOffsetY = getUniformLocation(temp); }
34.742857
98
0.817434
Armanimani
a53a645d257e0e8c8f80c93d96c20b152697713a
4,263
hpp
C++
src/graph/include/graph/breadth_first_search.hpp
SkyterX/rpclass
5e80ec4e0b876eb498351bcf7d6f5983fe5c7934
[ "Apache-2.0" ]
null
null
null
src/graph/include/graph/breadth_first_search.hpp
SkyterX/rpclass
5e80ec4e0b876eb498351bcf7d6f5983fe5c7934
[ "Apache-2.0" ]
null
null
null
src/graph/include/graph/breadth_first_search.hpp
SkyterX/rpclass
5e80ec4e0b876eb498351bcf7d6f5983fe5c7934
[ "Apache-2.0" ]
null
null
null
#pragma once #include <queue> #include <graph/graph.hpp> #include <graph/properties.hpp> #include <graph/static_graph.hpp> namespace graph { template <typename ColorMapTag, typename V, typename E> struct GenerateBFSGraph {}; template <typename ColorMapTag, typename... P1s, typename... P2s> struct GenerateBFSGraph<ColorMapTag, Properties<P1s...>, Properties<P2s...>> { using type = StaticGraph<Properties<Property<ColorMapTag, char>, P1s...>, Properties<P2s...>>; }; template <typename Graph, typename ColorMap> struct DefaultBFSVisitor { //is invoked on every vertex before the start of the search. void initialize_vertex(const typename graph_traits<Graph>::vertex_descriptor& v, Graph&) { graph::put(color, v, typename property_traits<ColorMap>::value_type(0)); }; // is invoked in each vertex as it is removed from the queue. void examine_vertex(const typename graph_traits<Graph>::vertex_descriptor&, Graph&) {}; //is invoked on every out - edge of each vertex immediately after the vertex // is removed from the queue. void examine_edge(const typename graph_traits<Graph>::edge_descriptor&, Graph& g) {}; // is invoked(in addition to examine_edge()) if the edge is a tree edge. // The target vertex of edge e is discovered at this time. void tree_edge(const typename graph_traits<Graph>::edge_descriptor&, Graph& g) {}; // is invoked the first time the algorithm encounters vertex u. // All vertices closer to the source vertex have been discovered, // and vertices further from the source have not yet been discovered. void discover_vertex(const typename graph_traits<Graph>::vertex_descriptor&, Graph&) {}; //is invoked(in addition to examine_edge()) if the edge is not a tree edge. void non_tree_edge(const typename graph_traits<Graph>::edge_descriptor&, Graph&) {}; // is invoked(in addition to non_tree_edge()) if the target vertex is colored // gray at the time of examination.The color gray indicates that the vertex // is currently in the queue. void gray_target(const typename graph_traits<Graph>::edge_descriptor&, Graph&) {}; // is invoked(in addition to non_tree_edge()) if the target vertex is colored // black at the time of examination.The color black indicates that the vertex // is no longer in the queue. void black_target(const typename graph_traits<Graph>::edge_descriptor&, Graph&) {}; // is invoked after all of the out edges of u have been examined and all of // the adjacent vertices have been discovered. void finish_vertex(const typename graph_traits<Graph>::vertex_descriptor&, Graph&) {}; DefaultBFSVisitor(ColorMap& color) :color(color) {}; DefaultBFSVisitor(ColorMap&& color) :color(color) {}; ColorMap color; }; template <class Graph, class ColorMap, class BFSVisitor = DefaultBFSVisitor<Graph, ColorMap>> void breadth_first_search(Graph& graph, const typename graph_traits<Graph>::vertex_descriptor& s, ColorMap& color, BFSVisitor visitor = BFSVisitor{}) { typename property_traits<ColorMap>::value_type white = 0; typename property_traits<ColorMap>::value_type grey = 1; typename property_traits<ColorMap>::value_type black = 2; if (graph::get(color, s) != white) return; std::queue<typename graph_traits<Graph>::vertex_descriptor> vQueue; auto vRange = vertices(graph); for (auto vIt = vRange.first; vIt != vRange.second; ++vIt) { visitor.initialize_vertex(*vIt, graph); } vQueue.push(s); while (!vQueue.empty()) { auto src = vQueue.front(); visitor.examine_vertex(src, graph); auto outRange = out_edges(src, graph); graph::put(color, src, black); for (auto outIt = outRange.first; outIt != outRange.second; ++outIt) { auto e = *outIt; auto tgt = target(e, graph); visitor.examine_edge(e, graph); if (graph::get(color, tgt) == white) { visitor.discover_vertex(tgt, graph); visitor.tree_edge(e, graph); graph::put(color, tgt, grey); vQueue.push(tgt); } else if (graph::get(color, tgt) == grey) visitor.gray_target(e, graph); else visitor.black_target(e, graph); }; visitor.finish_vertex(src, graph); vQueue.pop(); } }; }
36.435897
96
0.703964
SkyterX
a53bcff7875e40227554a2f5c083863f61245ec9
6,622
cpp
C++
test/unittest/step_tileset_test.cpp
albin-johansson/step
f3e71ebd2d54ebbb7fcfa40002b1e4fde3779aab
[ "MIT" ]
4
2020-06-05T11:56:11.000Z
2020-11-13T14:49:06.000Z
test/unittest/step_tileset_test.cpp
albin-johansson/step
f3e71ebd2d54ebbb7fcfa40002b1e4fde3779aab
[ "MIT" ]
8
2020-05-23T09:35:03.000Z
2020-06-20T22:15:02.000Z
test/unittest/step_tileset_test.cpp
albin-johansson/step
f3e71ebd2d54ebbb7fcfa40002b1e4fde3779aab
[ "MIT" ]
null
null
null
#include "step_tileset.hpp" #include <doctest.h> #include <string_view> #include "step_exception.hpp" #include "step_test_utils.h" using namespace step; inline static constexpr std::string_view prefix = "resource/tileset/"; TEST_SUITE("Tileset") { TEST_CASE("Parsing external tileset") { const auto tileset = tileset::external( prefix, 4_gid, "tileset_data_for_external_tileset.json"); CHECK(tileset->columns() == 32); CHECK(tileset->first_gid() == 4_gid); CHECK(tileset->source() == "tileset_data_for_external_tileset.json"); CHECK(tileset->image() == "../terrain.png"); CHECK(tileset->image_width() == 1024); CHECK(tileset->image_height() == 768); CHECK(tileset->margin() == 18); CHECK(tileset->name() == "external_tileset"); CHECK(tileset->spacing() == 7); CHECK(tileset->tile_count() == 1024); CHECK(tileset->tile_width() == 64); CHECK(tileset->tile_height() == 32); CHECK(tileset->json_version() == 1.2); CHECK(tileset->tiled_version() == "1.3.4"); CHECK(!tileset->get_grid()); CHECK(!tileset->get_tile_offset()); } TEST_CASE("Parsing embedded tileset") { const auto tileset = tileset::embedded( detail::parse_json("resource/tileset/embedded_tileset.json")); CHECK(tileset->first_gid() == 7_gid); CHECK(tileset->columns() == 48); CHECK(tileset->source() == ""); CHECK(tileset->image() == "sam/is/the/hero.png"); CHECK(tileset->image_width() == 1270); CHECK(tileset->image_height() == 960); CHECK(tileset->margin() == 77); CHECK(tileset->name() == "embedded_tileset"); CHECK(tileset->tile_count() == 63); CHECK(tileset->spacing() == 82); CHECK(tileset->tile_width() == 55); CHECK(tileset->tile_height() == 27); CHECK(tileset->background_color() == color{"#12345678"}); CHECK(tileset->transparent_color() == color{"#CCDDEEFF"}); CHECK(tileset->json_version() == 1.2); CHECK(tileset->tiled_version() == "1.3.4"); SUBCASE("Parsing grid") { const auto grid = tileset->get_grid(); REQUIRE(grid); CHECK(grid->get_orientation() == grid::orientation::isometric); CHECK(grid->width() == 48); CHECK(grid->height() == 64); } SUBCASE("Parsing tile offset") { const auto tileOffset = tileset->get_tile_offset(); REQUIRE(tileOffset); CHECK(tileOffset->x() == 1574); CHECK(tileOffset->y() == 753); } SUBCASE("Parsing terrains") { const auto& terrains = tileset->terrains(); REQUIRE(terrains.size() == 3); const auto& firstTerrain = terrains.at(0); CHECK(firstTerrain.name() == "ground"); CHECK(firstTerrain.tile() == 4_lid); { REQUIRE(firstTerrain.get_properties()->amount() != 0); const auto property = firstTerrain.get_properties()->get("foo"); CHECK(property.name() == "foo"); REQUIRE(property.get_type() == property::type::boolean); CHECK(property.get<bool>()); } const auto& secondTerrain = terrains.at(1); CHECK(secondTerrain.name() == "chasm"); CHECK(secondTerrain.tile() == 12_lid); const auto& thirdTerrain = terrains.at(2); CHECK(thirdTerrain.name() == "cliff"); CHECK(thirdTerrain.tile() == 36_lid); } } TEST_CASE("Tileset with properties") { const auto tileset = tileset::embedded( detail::parse_json("resource/tileset/with_properties.json")); const auto* properties = tileset->get_properties(); REQUIRE(properties); REQUIRE(properties->amount() == 2); const auto& firstProperty = properties->get("aFloat"); CHECK(firstProperty.name() == "aFloat"); CHECK(firstProperty.get_type() == property::type::floating); CHECK(firstProperty.get<float>() == 7.5f); const auto& secondProperty = properties->get("aString"); CHECK(secondProperty.name() == "aString"); CHECK(secondProperty.get_type() == property::type::string); CHECK(secondProperty.get<std::string>() == "Hello"); } TEST_CASE("Tileset with tiles") { SUBCASE("Check first tile") { const auto tileset = tileset::embedded( detail::parse_json("resource/tileset/with_tiles.json")); const auto& tiles = tileset->tiles(); REQUIRE(tiles.size() == 2); const auto& tile = tiles.at(0); CHECK(tile.id() == 187_lid); SUBCASE("Animation") { const auto animation = tile.get_animation(); REQUIRE(animation); CHECK(animation->num_frames() == 3); const auto& frames = animation->frames(); for (int i = 0; i < 3; ++i) { CHECK(frames.at(i).duration() == 900); CHECK(frames.at(i).tile_id() == 187_lid + local_id{i}); } } SUBCASE("Properties") { const auto* properties = tile.get_properties(); REQUIRE(properties); REQUIRE(properties->amount() == 1); const auto& property = properties->get("name"); CHECK(property.name() == "name"); CHECK(property.get_type() == property::type::string); CHECK(property.get<std::string>() == "waterTile"); } } SUBCASE("Check second tile") { const auto tileset = tileset::embedded( detail::parse_json("resource/tileset/with_tiles.json")); auto& tiles = tileset->tiles(); REQUIRE(tiles.size() == 2); const auto& tile = tiles.at(1); CHECK(tile.id() == 370_lid); SUBCASE("Properties") { const auto properties = tile.get_properties(); REQUIRE(properties->amount() == 2); const auto& firstProperty = properties->get("coolness"); CHECK(firstProperty.name() == "coolness"); REQUIRE(firstProperty.get_type() == property::type::integer); CHECK(firstProperty.get<int>() == 9000); const auto& secondProperty = properties->get("frodo"); CHECK(secondProperty.name() == "frodo"); REQUIRE(secondProperty.get_type() == property::type::string); CHECK(secondProperty.get<std::string>() == "sandTile"); } } } TEST_CASE("Embedded tileset without explicit first GID") { const auto tileset = tileset::embedded( detail::parse_json("resource/tileset/embedded_tileset_no_gid.json")); CHECK(tileset->first_gid() == 1_gid); } TEST_CASE("Tileset missing type attribute") { CHECK_THROWS_WITH_AS(tileset::embedded(detail::parse_json( "resource/tileset/tileset_wrong_type.json")), "Tileset \"type\" must be \"tileset\"!", step_exception); } }
31.836538
77
0.609333
albin-johansson
a53d3078d6e68e6aca1bc30353ac37d5efc991bf
1,410
cpp
C++
sxaccelerate/src/parserkit/examples/04_include_files/SxDemo4Parser.cpp
ashtonmv/sphinx_vdw
5896fee0d92c06e883b72725cb859d732b8b801f
[ "Apache-2.0" ]
1
2020-02-29T03:26:32.000Z
2020-02-29T03:26:32.000Z
sxaccelerate/src/parserkit/examples/04_include_files/SxDemo4Parser.cpp
ashtonmv/sphinx_vdw
5896fee0d92c06e883b72725cb859d732b8b801f
[ "Apache-2.0" ]
null
null
null
sxaccelerate/src/parserkit/examples/04_include_files/SxDemo4Parser.cpp
ashtonmv/sphinx_vdw
5896fee0d92c06e883b72725cb859d732b8b801f
[ "Apache-2.0" ]
null
null
null
// --------------------------------------------------------------------------- // // The general purpose cross platform C/C++ framework // // S x A c c e l e r a t e // // Home: https://www.sxlib.de // License: Apache 2 // Authors: see src/AUTHORS // // --------------------------------------------------------------------------- #include <SxDemo4Parser.h> SxDemo4Parser::SxDemo4Parser () : SxParserBase (), SxDemo4Ast () { SX_TRACE (); ssize_t rootId = 0; push (rootId); } SxDemo4Parser::~SxDemo4Parser () { // empty } void SxDemo4Parser::push (ssize_t id) { SX_TRACE (); stack.append (id); } SxDemo4AstNode &SxDemo4Parser::pop () { SX_TRACE (); SX_CHECK (errors.getSize() > 0 || stack.getSize() > 0); ssize_t id = stack.last (); stack.removeLast (); return *(ast.begin(sx::Forward, id)); } SxDemo4AstNode &SxDemo4Parser::getCurrent () { SX_TRACE (); return *(ast.begin(sx::Forward, stack.last())); } SxDemo4AstNode &SxDemo4Parser::getParent () { SX_TRACE (); ssize_t i = stack.getSize()-2; if (i >= 0) return *(ast.begin(sx::Forward, stack(i))); else return *(ast.begin(sx::Forward, 0)); // top level } int SxDemo4Parser_parse (SxDemo4Parser *); // defined by LEX int SxDemo4Parser::parse () { return SxDemo4Parser_parse (this); // enter LEX }
21.363636
78
0.521986
ashtonmv
a53ea9be9c6f82a33b219a687dcdb2d0d3cb7486
1,435
hh
C++
src/transform/vector/vector4.hh
CompaqDisc/libtransform
db9dcbc39cd7d3af904c1bc2131544c1908522e1
[ "MIT" ]
null
null
null
src/transform/vector/vector4.hh
CompaqDisc/libtransform
db9dcbc39cd7d3af904c1bc2131544c1908522e1
[ "MIT" ]
null
null
null
src/transform/vector/vector4.hh
CompaqDisc/libtransform
db9dcbc39cd7d3af904c1bc2131544c1908522e1
[ "MIT" ]
null
null
null
#pragma once #include <memory> #include "vector.hh" namespace transform { template <class T> class Vector4 : public Vector<4, T> { private: typedef Vector<4, T> super; public: Vector4() : super() {} // default construct Vector4(const T x, const T y, const T z, const T w); // member construct Vector4(const Vector4<T>& v) : super(v) {} // copy construct Vector4(const Vector<4, T>& v) : super(v) {} // copy construct from superclass template <class U> Vector4(const Vector4<U>& v) // convert construct { this->_v[0] = v[0]; this->_v[1] = v[1]; this->_v[2] = v[2]; this->_v[3] = v[3]; } template <class U> Vector4(const Vector<4, U>& v) // convert construct { this->_v[0] = v[0]; this->_v[1] = v[1]; this->_v[2] = v[2]; this->_v[3] = v[3]; } // members T& x = this->_v[0]; T& y = this->_v[1]; T& z = this->_v[2]; T& w = this->_v[3]; T& r = this->_v[0]; T& g = this->_v[1]; T& b = this->_v[2]; T& a = this->_v[3]; // utility Vector4<T>& set(const T x, const T y, const T z, const T w); }; } using transform::Vector4; template <class T> Vector4<T>::Vector4(T x, T y, T z, T w) { this->_v[0] = x; this->_v[1] = y; this->_v[2] = z; this->_v[3] = w; } template <class T> Vector4<T>& Vector4<T>::set(const T x, const T y, const T z, const T w) { this->_v[0] = x; this->_v[1] = y; this->_v[2] = z; this->_v[3] = w; return *this; }
19.133333
82
0.552613
CompaqDisc
a54d3255d9b64c01987dcbf06a6bf5a4e3af694a
2,205
cpp
C++
src/DashboardLayout.cpp
00steve/Lapster
42c11d7bf96694c36f75d938563031cb08951ff1
[ "Apache-2.0" ]
null
null
null
src/DashboardLayout.cpp
00steve/Lapster
42c11d7bf96694c36f75d938563031cb08951ff1
[ "Apache-2.0" ]
null
null
null
src/DashboardLayout.cpp
00steve/Lapster
42c11d7bf96694c36f75d938563031cb08951ff1
[ "Apache-2.0" ]
null
null
null
#include "DashboardLayout.h" void DashboardLayout::Setup(){ switch(layoutID){ case LAYOUT_SINGLE: Serial.println("use default single widget dashboard"); widget[0] = new DashboardWidget(Int2(10,10),Int2(470,310),GAUGE_TYPE_BAR,INPUT_ANALOG1); widgetCount = 1; break; case LAYOUT_SIDE_BY_SIDE: Serial.println("use double widget dashboard"); widget[0] = new DashboardWidget(Int2(10,10),Int2(235,310),GAUGE_TYPE_EMPTY,INPUT_ANALOG1); widget[1] = new DashboardWidget(Int2(245,10),Int2(470,310),GAUGE_TYPE_BAR,INPUT_ANALOG1); widgetCount = 2; break; case LAYOUT_QUADS: Serial.println("use quad widget dashboard"); widget[0] = new DashboardWidget(Int2(10,10),Int2(235,155),GAUGE_TYPE_EMPTY,INPUT_ANALOG1); widget[1] = new DashboardWidget(Int2(245,10),Int2(470,155),GAUGE_TYPE_BAR,INPUT_ANALOG1); widget[2] = new DashboardWidget(Int2(10,165),Int2(235,310),GAUGE_TYPE_EMPTY,INPUT_ANALOG1); widget[3] = new DashboardWidget(Int2(245,165),Int2(470,310),GAUGE_TYPE_EMPTY,INPUT_ANALOG1); widgetCount = 4; break; } } DashboardLayout::DashboardLayout(int layoutID) : layoutID(layoutID), editWidgetIndex(-1){ Setup(); //stuff in the layout } DashboardLayout::~DashboardLayout(){ int i = widgetCount; while(i --> 0){ delete widget[i]; } } void DashboardLayout::Update(){ if(Button::CheckForScreenHolding()){ Serial.println("check for button"); int i = widgetCount; while(i --> 0){ if(widget[i]->Holding()){ editWidgetIndex = i; Serial.println("edit widget"); return; } } } } void DashboardLayout::Redraw(){ int i=widgetCount; while(i --> 0){ widget[i]->Redraw(); } } void DashboardLayout::Draw(){ int i=widgetCount; while(i --> 0){ widget[i]->Draw(); } } bool DashboardLayout::ShouldEditWidget(){ return editWidgetIndex > -1; } DashboardWidget* DashboardLayout::EditWidget(){ int ind = editWidgetIndex; editWidgetIndex = -1; return widget[ind]; }
25.639535
100
0.623583
00steve
a5547fdf56655ca4bf73afa96bd8cb653764d9c2
598
cpp
C++
pointer_main.cpp
zhichengMLE/Cplusplus
525d80550c2460b0504926a26beaa67ca91bb848
[ "MIT" ]
1
2019-03-29T21:07:37.000Z
2019-03-29T21:07:37.000Z
pointer_main.cpp
zhichengMLE/Cplusplus
525d80550c2460b0504926a26beaa67ca91bb848
[ "MIT" ]
null
null
null
pointer_main.cpp
zhichengMLE/Cplusplus
525d80550c2460b0504926a26beaa67ca91bb848
[ "MIT" ]
null
null
null
#include <iostream> using namespace std; bool printArray(string* arr, int length){ if(arr == NULL){ return false; } for(int i = 0; i < length; i++){ cout << arr[i] << endl; } return true; } int main() { string arrMonth[12] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"}; string* pMonth = NULL; pMonth = arrMonth; cout << printArray(pMonth, sizeof(arrMonth) / sizeof(*arrMonth)) << endl; return 0; } /* >> Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec 1 Process finished with exit code 0 */
13
111
0.560201
zhichengMLE
a559a8d25755123fb6296d027efb72d08bb91b83
9,590
hpp
C++
src/Serialize.hpp
Mercerenies/latitude
29b1697f1f615d52480197a52e20ff8c1872f07d
[ "MIT" ]
3
2021-09-02T18:19:25.000Z
2021-12-26T23:33:32.000Z
src/Serialize.hpp
Mercerenies/latitude
29b1697f1f615d52480197a52e20ff8c1872f07d
[ "MIT" ]
45
2017-11-28T15:13:59.000Z
2022-02-19T18:45:46.000Z
src/Serialize.hpp
Mercerenies/proto-lang
29b1697f1f615d52480197a52e20ff8c1872f07d
[ "MIT" ]
null
null
null
//// Copyright (c) 2018 Silvio Mayolo //// See LICENSE.txt for licensing details #ifndef SERIALIZE_HPP #define SERIALIZE_HPP #include "Instructions.hpp" #include "Assembler.hpp" /// \file /// /// \brief Serialization structures and helpers. /// serialize_t, on its own, is an incomplete type. Any type which is /// serializable should implement a partial specialization of /// serialize_t for its particular type. The specialization should /// define, publicly, a typedef and two methods. /// /// * `using type = ...` should be defined to be the type parameter /// `T`. /// /// * `void serialize(const type&, OutputIterator&)` should, for any /// output iterator type, serialize a value of the type to the /// iterator. /// /// * `type deserialize(InputIterator&)` should, for any input /// iterator type, deserialize a value of the type to out of the /// iterator. /// /// Serializers are allowed to assume the iterators are valid and, in /// the input case, that the iterator contains a value of the /// appropriate type. Additionally, if the type is small (such as an /// arithmetic type), serializers may replace `const type&` with /// simply `type`. template <typename T> struct serialize_t; template <> struct serialize_t<long> { using type = long; template <typename OutputIterator> void serialize(type arg, OutputIterator& iter) const; template <typename InputIterator> type deserialize(InputIterator& iter) const; }; template <> struct serialize_t<char> { using type = char; template <typename OutputIterator> void serialize(type arg, OutputIterator& iter) const; template <typename InputIterator> type deserialize(InputIterator& iter) const; }; template <> struct serialize_t<Reg> { using type = Reg; template <typename OutputIterator> void serialize(type arg, OutputIterator& iter) const; template <typename InputIterator> type deserialize(InputIterator& iter) const; }; template <> struct serialize_t<Instr> { using type = Instr; template <typename OutputIterator> void serialize(type arg, OutputIterator& iter) const; template <typename InputIterator> type deserialize(InputIterator& iter) const; }; template <> struct serialize_t<std::string> { using type = std::string; template <typename OutputIterator> void serialize(const type& arg, OutputIterator& iter) const; template <typename InputIterator> type deserialize(InputIterator& iter) const; }; template <> struct serialize_t<FunctionIndex> { using type = FunctionIndex; template <typename OutputIterator> void serialize(const type& arg, OutputIterator& iter) const; template <typename InputIterator> type deserialize(InputIterator& iter) const; }; template <> struct serialize_t<AssemblerLine> { using type = AssemblerLine; template <typename OutputIterator> void serialize(const type& arg, OutputIterator& iter) const; template <typename InputIterator> type deserialize(InputIterator& iter) const; }; /// Serializes the argument into the output iterator. /// /// \pre A partial specialization `serialize_t<T>` must be in scope /// \param arg the value to serialize /// \param iter an output iterator template <typename T, typename OutputIterator> void serialize(const T& arg, OutputIterator& iter); /// Deserializes a value of the given type from the iterator. /// /// \pre A partial specialization `serialize_t<T>` must be in scope /// \param iter an input iterator /// \return the value template <typename T, typename InputIterator> T deserialize(InputIterator& iter); /// Serializes the value within the variant structure. The /// serialization does not mark which variant was saved, so the value /// must be deserialized with ::deserialize<T> (for the appropriate type /// `T`). /// /// \pre A partial specialization `serialize_t<T>` must be in scope, /// for each `T` in `Ts...` /// \param arg the variant /// \param iter an output iterator template <typename OutputIterator, typename... Ts> void serializeVariant(const boost::variant<Ts...>& arg, OutputIterator& iter); // ---- template <typename OutputIterator> auto serialize_t<long>::serialize(type arg, OutputIterator& iter) const -> void { long val1 = arg; if (val1 < 0) *iter++ = 0xFF; else *iter++ = 0x00; val1 = abs(val1); for (int i = 0; i < 4; i++) { *iter++ = (unsigned char)(val1 % 256); val1 /= 256; } } template <typename InputIterator> auto serialize_t<long>::deserialize(InputIterator& iter) const -> type { int sign = 1; if (*iter > 0) sign *= -1; ++iter; long value = 0; long pow = 1; for (int i = 0; i < 4; i++) { value += pow * (long)(*iter); ++iter; pow <<= 8; } return sign * value; } template <typename OutputIterator> auto serialize_t<char>::serialize(type arg, OutputIterator& iter) const -> void { *iter++ = (unsigned char)arg; } template <typename InputIterator> auto serialize_t<char>::deserialize(InputIterator& iter) const -> type { char ch = *iter; ++iter; return ch; } template <typename OutputIterator> auto serialize_t<Reg>::serialize(type arg, OutputIterator& iter) const -> void { *iter++ = (unsigned char)arg; } template <typename InputIterator> auto serialize_t<Reg>::deserialize(InputIterator& iter) const -> type { unsigned char ch = *iter; ++iter; return (Reg)ch; } template <typename OutputIterator> auto serialize_t<Instr>::serialize(type arg, OutputIterator& iter) const -> void { *iter++ = (unsigned char)arg; } template <typename InputIterator> auto serialize_t<Instr>::deserialize(InputIterator& iter) const -> type { unsigned char ch = *iter; ++iter; return (Instr)ch; } template <typename OutputIterator> auto serialize_t<std::string>::serialize(const type& arg, OutputIterator& iter) const -> void { for (char ch : arg) { if (ch == 0) { *iter++ = '\0'; *iter++ = '.'; } else { *iter++ = ch; } } *iter++ = '\0'; *iter++ = '\0'; } template <typename InputIterator> auto serialize_t<std::string>::deserialize(InputIterator& iter) const -> type { std::string str; unsigned char ch; while (true) { ch = *iter; ++iter; if (ch == '\0') { ch = *iter; ++iter; if (ch == '.') str += '\0'; else if (ch == '\0') break; } else { str += ch; } } return str; } template <typename OutputIterator> auto serialize_t<FunctionIndex>::serialize(const type& arg, OutputIterator& iter) const -> void { // No need for a sign bit; this is an index so it's always nonnegative int val1 = arg.index; for (int i = 0; i < 4; i++) { *iter++ = (unsigned char)(val1 % 256); val1 /= 256; } } template <typename InputIterator> auto serialize_t<FunctionIndex>::deserialize(InputIterator& iter) const -> type { int value = 0; int pow = 1; for (int i = 0; i < 4; i++) { value += pow * (long)(*iter); ++iter; pow <<= 8; } return { value }; } template <typename OutputIterator> auto serialize_t<AssemblerLine>::serialize(const type& instr, OutputIterator& iter) const -> void { ::serialize<Instr>(instr.getCommand(), iter); for (const auto& arg : instr.arguments()) { serializeVariant(arg, iter); } } /// \cond template <typename InputIterator> struct _AsmArgDeserializeVisitor { InputIterator& iter; template <typename T> RegisterArg operator()(Proxy<T>) { return deserialize<T>(iter); } }; /// \endcond template <typename InputIterator> auto serialize_t<AssemblerLine>::deserialize(InputIterator& iter) const -> type { Instr instr = ::deserialize<Instr>(iter); AssemblerLine instruction { instr }; _AsmArgDeserializeVisitor<InputIterator> visitor { iter }; for (const auto& arg : getAsmArguments(instr)) { instruction.addRegisterArg(callOnAsmArgType(visitor, arg)); } return instruction; } /// Serializes the object into the given output iterator. There must /// be a compatible specialization of `serialize_t` of the form /// `serialize_t<T>`. /// /// \tparam T the object type /// \tparam OutputIterator the type of the output iterator /// \param arg the object to serialize /// \param iter the output iterator template <typename T, typename OutputIterator> void serialize(const T& arg, OutputIterator& iter) { serialize_t<T>().serialize(arg, iter); } /// Deserializes an object of the given type from the input iterator. /// /// \tparam T the object type /// \tparam InputIterator the type of the input iterator /// \param iter the input iterator /// \return the object template <typename T, typename InputIterator> T deserialize(InputIterator& iter) { return serialize_t<T>().deserialize(iter); } /// \cond template <typename OutputIterator> struct _VariantSerializeVisitor : boost::static_visitor<void> { OutputIterator& iter; _VariantSerializeVisitor(OutputIterator& iter) : iter(iter) {} template <typename T> void operator()(const T& arg) { serialize(arg, iter); } }; /// \endcond template <typename OutputIterator, typename... Ts> void serializeVariant(const boost::variant<Ts...>& arg, OutputIterator& iter) { _VariantSerializeVisitor<OutputIterator> visitor { iter }; boost::apply_visitor(visitor, arg); } #endif // SERIALIZE_HPP
26.862745
99
0.665485
Mercerenies
a222d9ab01460056f957119aaeb4bd94ebf3684e
29,324
cpp
C++
src/Image.cpp
i-saint/glSpriteFont
8552bbbe664e8841dd497b8a1a5cdc6dbdfc5fe1
[ "Unlicense" ]
2
2015-11-07T11:31:55.000Z
2021-04-16T15:20:44.000Z
src/Image.cpp
i-saint/glSpriteFont
8552bbbe664e8841dd497b8a1a5cdc6dbdfc5fe1
[ "Unlicense" ]
null
null
null
src/Image.cpp
i-saint/glSpriteFont
8552bbbe664e8841dd497b8a1a5cdc6dbdfc5fe1
[ "Unlicense" ]
1
2020-06-09T10:45:28.000Z
2020-06-09T10:45:28.000Z
#include "stdafx.h" #include "Image.h" #ifdef __ist_with_gli__ #include "gli/gli.hpp" #include "gli/gtx/loader.hpp" #endif // __ist_with_gli__ namespace ist { struct BMPHEAD { char B; char M; int32 file_size; int16 reserve1; int16 reserve2; int32 offset; BMPHEAD() { memset(this, 0, sizeof(*this)); B = 'B'; M = 'M'; offset = 54; } }; struct BMPINFOHEAD { int32 header_size; int32 width; int32 height; int16 plane; int16 bits; int32 compression; int32 comp_image_size; int32 x_resolution; int32 y_resolution; int32 pallete_num; int32 important_pallete_num; BMPINFOHEAD() { memset(this, 0, sizeof(*this)); header_size=sizeof(*this); plane = 1; bits = 24; } }; struct TGAHEAD { uint8 No_ID; uint8 CMap_Type; uint8 image_type; uint8 CMap_Spec[5]; int16 Ox; int16 Oy; int16 width; int16 height; uint8 pixel; uint8 IDesc_Type; TGAHEAD() { memset(this, 0, sizeof(*this)); pixel = 32; IDesc_Type = 8; } }; Image::FileType GetFileTypeByFileHeader(IBinaryStream &f) { char m[4]; f >> m; f.setReadPos(0); if(m[0]=='B' && m[1]=='M') { return Image::FileType_BMP; } if(m[1]=='P' && m[2]=='N' && m[3]=='G') { return Image::FileType_PNG; } if(m[0]=='D' && m[1]=='D' && m[2]=='S') { return Image::FileType_DDS; } if(m[0]==0xff && m[1]==0xd8) { return Image::FileType_JPG; } { // tga は magic code がないので、それっぽい値が入ってるかで判断 TGAHEAD tga; f.read(&tga, sizeof(tga)); f.setReadPos(0); if( (tga.image_type==2 || tga.image_type==10) && tga.Ox==0 && tga.Oy==0 && (tga.pixel==32 || tga.pixel==24)) { return Image::FileType_TGA; } } return Image::FileType_Unknown; } Image::FileType GetFileTypeByExtention(const char *path) { uint32 len = strlen(path); if(len<5) { return Image::FileType_Unknown; } if(strncmp(&path[len-3], "bmp", 3)==0) { return Image::FileType_BMP; } if(strncmp(&path[len-3], "tga", 3)==0) { return Image::FileType_TGA; } if(strncmp(&path[len-3], "png", 3)==0) { return Image::FileType_PNG; } if(strncmp(&path[len-3], "jpg", 3)==0) { return Image::FileType_JPG; } if(strncmp(&path[len-3], "dds", 3)==0) { return Image::FileType_DDS; } return Image::FileType_Unknown; } bool Image::load(const char *path, const IOConfig &conf) { FileStream f(path, "rb"); if(!f.isOpened()) { return false; } IOConfig c = conf; if(c.getFileType()==FileType_Auto) { c.setFileType( GetFileTypeByExtention(path) ); } return load(f, c); } bool Image::load(IBinaryStream &f, const IOConfig &conf) { clear(); FileType ft = conf.getFileType(); if(ft==FileType_Auto) { ft = GetFileTypeByFileHeader(f); } switch(ft) { case FileType_BMP: return loadBMP(f, conf); case FileType_TGA: return loadTGA(f, conf); case FileType_PNG: return loadPNG(f, conf); case FileType_JPG: return loadJPG(f, conf); case FileType_DDS: return loadDDS(f, conf); } istPrint("認識できないフォーマットが指定されました。\n"); return false; } bool Image::save(const char *path, const IOConfig &conf) const { FileStream f(path, "wb"); if(!f.isOpened()) { return false; } IOConfig c = conf; if(c.getFileType()==FileType_Auto) { c.setFileType(GetFileTypeByExtention(path)); } return save(f, c); } bool Image::save(IBinaryStream &f, const IOConfig &conf) const { switch(conf.getFileType()) { case FileType_BMP: return saveBMP(f, conf); case FileType_TGA: return saveTGA(f, conf); case FileType_PNG: return savePNG(f, conf); case FileType_JPG: return saveJPG(f, conf); case FileType_DDS: return saveDDS(f, conf); } istPrint(L"認識できないフォーマットが指定されました。\n"); return false; } static RGBA_8U Read1Pixel(IBinaryStream &bf) { RGBA_8U t; bf >> t.b >> t.g >> t.r >> t.a; return t; } // BMP bool Image::loadBMP(IBinaryStream &bf, const IOConfig &conf) { BMPHEAD head; BMPINFOHEAD infohead; bf >> head.B >> head.M; if(head.B!='B' || head.M!='M') { return false; } bf >> head.file_size >> head.reserve1 >> head.reserve2 >> head.offset; bf >> infohead.header_size >> infohead.width >> infohead.height >> infohead.plane >> infohead.bits >> infohead.compression >> infohead.comp_image_size >> infohead.x_resolution >> infohead.y_resolution >> infohead.pallete_num >> infohead.important_pallete_num; if(infohead.bits!=24 && infohead.bits!=32) { istPrint(L"bmp は現在 24bit か 32bit しか対応していません。\n"); return false; } resize<RGBA_8U>(infohead.width, infohead.height); if(infohead.bits==24) { for(int32 yi=(int32)height()-1; yi>=0; --yi) { for(int32 xi=0; xi<(int32)width(); ++xi) { RGBA_8U& c = get<RGBA_8U>(yi, xi); bf >> c.b >> c.g >> c.r; c.a = 255; } } } else if(infohead.bits==32) { for(int32 yi=(int32)height()-1; yi>=0; --yi) { for(int32 xi=0; xi<(int32)width(); ++xi) { RGBA_8U& c = get<RGBA_8U>(yi, xi); bf >> c.b >> c.g >> c.r >> c.a; } } } return true; } bool Image::saveBMP(IBinaryStream &bf, const IOConfig &conf) const { BMPHEAD head; BMPINFOHEAD infohead; head.file_size = sizeof(BMPHEAD)+sizeof(BMPINFOHEAD)+width()*height()*3; infohead.width = width(); infohead.height = height(); bf << head.B << head.M << head.file_size << head.reserve1 << head.reserve2 << head.offset; bf << infohead.header_size << infohead.width << infohead.height << infohead.plane << infohead.bits << infohead.compression << infohead.comp_image_size << infohead.x_resolution << infohead.y_resolution << infohead.pallete_num << infohead.important_pallete_num; for(int32 yi=(int32)height()-1; yi>=0; --yi) { for(int32 xi=0; xi<(int32)width(); ++xi) { const RGBA_8U& c = get<RGBA_8U>(yi, xi); bf << c.b << c.g << c.r; } } return true; } // TGA bool Image::loadTGA(IBinaryStream &bf, const IOConfig &conf) { TGAHEAD head; bf >> head.No_ID >> head.CMap_Type >> head.image_type >> head.CMap_Spec >> head.Ox >> head.Oy >> head.width >> head.height >> head.pixel >> head.IDesc_Type; if(head.pixel!=32) { istPrint("32bit データしか対応していません。\n"); return false; } resize<RGBA_8U>(head.width, head.height); for(int32 yi=(int32)height()-1; yi>=0; --yi) { if(head.image_type==2) { for(int32 xi=0; xi<(int32)width(); xi++) { get<RGBA_8U>(yi, xi) = Read1Pixel(bf); } } else if(head.image_type==10) { uint32 loaded = 0; while(loaded<width()) { uint8 dist = 0; bf >> dist; if( dist<0x80) { for(int32 xi=0; xi<dist+1; ++xi, ++loaded) { get<RGBA_8U>(yi, loaded) = Read1Pixel(bf); } } else { RGBA_8U t = Read1Pixel(bf); for(int32 xi=0x80; xi<dist+1; ++xi, ++loaded) { get<RGBA_8U>(yi, loaded) = t; } } } } } return true; } class TGACompress { public: TGACompress() {} const stl::vector<uint8>& getCompressedData() const { return m_comp_pixel; } void compress(const RGBA_8U *start, int32 width) { stl::vector<RGBA_8U> same, diff; for(int32 i=0; i!=width; ++i, ++start) { const RGBA_8U *ip=start; ++ip; RGBA_8U dist=*start; if( i+1!=width && dist==*ip && same.size()<0x79 ) { same.push_back(dist); if(diff.size()!=0) { writeDifferentData(diff); } } else { if(same.size()>0x00) { writeSameData(same); } else { diff.push_back(dist); if(diff.size()==0x79 ) { writeDifferentData(diff); } } } } if(same.size()!=0x00) { writeSameData(same); } else if(diff.size()!=0) { writeDifferentData(diff); } } private: void writeSameData(stl::vector<RGBA_8U> &temp_pixel) { m_comp_pixel.push_back( temp_pixel.size()+0x80 ); m_comp_pixel.push_back( temp_pixel[0].b ); m_comp_pixel.push_back( temp_pixel[0].g ); m_comp_pixel.push_back( temp_pixel[0].r ); m_comp_pixel.push_back( temp_pixel[0].a ); temp_pixel.clear(); } void writeDifferentData(stl::vector<RGBA_8U> &temp_pixel) { m_comp_pixel.push_back( temp_pixel.size()-1 ); for(int32 d=0; d<(int32)temp_pixel.size(); d++) { m_comp_pixel.push_back( temp_pixel[d].b ); m_comp_pixel.push_back( temp_pixel[d].g ); m_comp_pixel.push_back( temp_pixel[d].r ); m_comp_pixel.push_back( temp_pixel[d].a ); } temp_pixel.clear(); } private: stl::vector<uint8> m_comp_pixel; }; bool Image::saveTGA(IBinaryStream &bf, const Image::IOConfig &conf) const { TGAHEAD head; head.width = width(); head.height = height(); head.image_type = 10; bf << head.No_ID << head.CMap_Type << head.image_type << head.CMap_Spec << head.Ox << head.Oy << head.width << head.height << head.pixel << head.IDesc_Type; { TGACompress comp; for(int32 yi=(int32)height()-1; yi>=0; --yi) { comp.compress(&get<RGBA_8U>(yi, 0), width()); } const stl::vector<uint8>& data = comp.getCompressedData(); bf.write(&data[0], data.size()); } return true; } // PNG #ifdef __ist_with_png__ namespace { void png_streambuf_read(png_structp png_ptr, png_bytep data, png_size_t length) { IBinaryStream *f = reinterpret_cast<IBinaryStream*>(png_get_io_ptr(png_ptr)); f->read(data, length); } void png_streambuf_write(png_structp png_ptr, png_bytep data, png_size_t length) { IBinaryStream *f = reinterpret_cast<IBinaryStream*>(png_get_io_ptr(png_ptr)); f->write(data, length); } void png_streambuf_flush(png_structp png_ptr) { } } // namespace #endif // __ist_with_png__ bool Image::loadPNG(IBinaryStream &f, const IOConfig &conf) { #ifdef __ist_with_png__ png_structp png_ptr = ::png_create_read_struct(PNG_LIBPNG_VER_STRING, 0, 0, 0); if(png_ptr==0) { istPrint("失敗: png_create_read_struct() が null を返しました。\n"); return false; } png_infop info_ptr = ::png_create_info_struct(png_ptr); if(info_ptr==0) { ::png_destroy_read_struct(&png_ptr, (png_infopp)NULL, (png_infopp)NULL); istPrint("失敗: png_create_info_struct() が null を返しました。\n"); return false; } ::png_set_read_fn(png_ptr, &f, png_streambuf_read); png_uint_32 w, h; int32 bit_depth, color_type, interlace_type; ::png_read_info(png_ptr, info_ptr); ::png_get_IHDR(png_ptr, info_ptr, &w, &h, &bit_depth, &color_type, &interlace_type, NULL, NULL); resize<RGBA_8U>(w, h); ::png_set_strip_16(png_ptr); ::png_set_packing(png_ptr); if(color_type==PNG_COLOR_TYPE_PALETTE) { ::png_set_palette_to_rgb(png_ptr); } if(color_type == PNG_COLOR_TYPE_GRAY && bit_depth<8) { ::png_set_expand_gray_1_2_4_to_8(png_ptr); } if(::png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS)) { ::png_set_tRNS_to_alpha(png_ptr); } ::png_read_update_info(png_ptr, info_ptr); // 読み込み stl::vector<png_bytep> row_pointers(height()); for(int32 row=0; row<(int32)height(); ++row) { row_pointers[row] = (png_bytep)png_malloc(png_ptr, png_get_rowbytes(png_ptr, info_ptr)); } png_read_image(png_ptr, &row_pointers[0]); for(int32 yi=0; yi<(int32)height(); ++yi) { for(int32 xi=0; xi<(int32)width(); ++xi) { RGBA_8U& c = get<RGBA_8U>(yi, xi); if(color_type==PNG_COLOR_TYPE_RGB_ALPHA) { c.r = row_pointers[yi][xi*4+0]; c.g = row_pointers[yi][xi*4+1]; c.b = row_pointers[yi][xi*4+2]; c.a = row_pointers[yi][xi*4+3]; } else if(color_type==PNG_COLOR_TYPE_RGB) { c.r = row_pointers[yi][xi*3+0]; c.g = row_pointers[yi][xi*3+1]; c.b = row_pointers[yi][xi*3+2]; c.a = 255; } } } for(int32 row=0; row<(int32)height(); ++row) { png_free(png_ptr, row_pointers[row]); } png_read_end(png_ptr, info_ptr); png_destroy_read_struct(&png_ptr, &info_ptr, NULL); return true; #else istPrint("失敗: png 使用を無効化した設定でビルドされています。\n"); return false; #endif // __ist_with_png__ } bool Image::savePNG(IBinaryStream &f, const Image::IOConfig &conf) const { #ifdef __ist_with_png__ png_structp png_ptr = ::png_create_write_struct(PNG_LIBPNG_VER_STRING, 0, 0, 0); if(png_ptr==0) { istPrint("失敗: png_create_write_struct() が null を返しました。"); return false; } png_infop info_ptr = ::png_create_info_struct(png_ptr); if(info_ptr==0) { ::png_destroy_write_struct(&png_ptr, NULL); istPrint("失敗: png_create_info_struct() が null を返しました。"); return false; } ::png_set_write_fn(png_ptr, &f, png_streambuf_write, png_streambuf_flush); ::png_set_IHDR(png_ptr, info_ptr, width(), height(), 8, PNG_COLOR_TYPE_RGB_ALPHA, PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE); ::png_write_info(png_ptr, info_ptr); Image tmp(*this); stl::vector<png_bytep> row_pointers(height()); for(int32 yi=0; yi<(int32)height(); ++yi) { row_pointers[yi] = tmp.get<RGBA_8U>(yi, 0).v; } ::png_write_image(png_ptr, &row_pointers[0]); ::png_write_end(png_ptr, info_ptr); ::png_destroy_write_struct(&png_ptr, &info_ptr); return true; #else istPrint("失敗: png 使用を無効化した設定でビルドされています。"); return false; #endif // __ist_with_png__ } // JPG #ifdef __ist_with_jpeg__ namespace { struct my_error_mgr { struct jpeg_error_mgr pub; jmp_buf setjmp_buffer; }; typedef struct my_error_mgr * my_error_ptr; void my_error_exit(j_common_ptr cinfo) { my_error_ptr myerr = (my_error_ptr) cinfo->err; (*cinfo->err->output_message)(cinfo); longjmp(myerr->setjmp_buffer, 1); } typedef struct { struct jpeg_source_mgr pub; /* public fields */ IBinaryStream *infile; /* source stream */ JOCTET * buffer; /* start of buffer */ boolean start_of_file; /* have we gotten any data yet? */ } my_source_mgr; typedef my_source_mgr * my_src_ptr; #define INPUT_BUF_SIZE 4096 /* choose an efficiently fread'able size */ typedef struct { struct jpeg_destination_mgr pub; /* public fields */ IBinaryStream * outfile; /* target stream */ JOCTET * buffer; /* start of buffer */ } my_destination_mgr; typedef my_destination_mgr * my_dest_ptr; #define OUTPUT_BUF_SIZE 4096 /* choose an efficiently fwrite'able size */ #define SIZEOF(object) ((size_t) sizeof(object)) void init_streambuf_source (j_decompress_ptr cinfo) { my_src_ptr src = (my_src_ptr) cinfo->src; src->start_of_file = TRUE; } boolean fill_streambuf_input_buffer (j_decompress_ptr cinfo) { my_src_ptr src = (my_src_ptr) cinfo->src; size_t nbytes; nbytes = src->infile->read(src->buffer, INPUT_BUF_SIZE); if (nbytes <= 0) { if (src->start_of_file) /* Treat empty input file as fatal error */ ERREXIT(cinfo, JERR_INPUT_EMPTY); WARNMS(cinfo, JWRN_JPEG_EOF); /* Insert a fake EOI marker */ src->buffer[0] = (JOCTET) 0xFF; src->buffer[1] = (JOCTET) JPEG_EOI; nbytes = 2; } src->pub.next_input_byte = src->buffer; src->pub.bytes_in_buffer = nbytes; src->start_of_file = FALSE; return TRUE; } void skip_input_data (j_decompress_ptr cinfo, long num_bytes) { struct jpeg_source_mgr * src = cinfo->src; if (num_bytes > 0) { while (num_bytes > (long) src->bytes_in_buffer) { num_bytes -= (long) src->bytes_in_buffer; (void) (*src->fill_input_buffer) (cinfo); } src->next_input_byte += (size_t) num_bytes; src->bytes_in_buffer -= (size_t) num_bytes; } } void term_source (j_decompress_ptr cinfo) { } void jpeg_streambuf_src (j_decompress_ptr cinfo, IBinaryStream &streambuf) { my_src_ptr src; if (cinfo->src == NULL) { /* first time for this JPEG object? */ cinfo->src = (struct jpeg_source_mgr *) (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT, SIZEOF(my_source_mgr)); src = (my_src_ptr) cinfo->src; src->buffer = (JOCTET *) (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT, INPUT_BUF_SIZE * SIZEOF(JOCTET)); } src = (my_src_ptr) cinfo->src; src->pub.init_source = init_streambuf_source; src->pub.fill_input_buffer = fill_streambuf_input_buffer; src->pub.skip_input_data = skip_input_data; src->pub.resync_to_restart = jpeg_resync_to_restart; /* use default method */ src->pub.term_source = term_source; src->infile = &streambuf; src->pub.bytes_in_buffer = 0; /* forces fill_input_buffer on first read */ src->pub.next_input_byte = NULL; /* until buffer loaded */ } void init_streambuf_destination (j_compress_ptr cinfo) { my_dest_ptr dest = (my_dest_ptr) cinfo->dest; /* Allocate the output buffer --- it will be released when done with image */ dest->buffer = (JOCTET *) (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE, OUTPUT_BUF_SIZE * SIZEOF(JOCTET)); dest->pub.next_output_byte = dest->buffer; dest->pub.free_in_buffer = OUTPUT_BUF_SIZE; } boolean empty_streambuf_output_buffer (j_compress_ptr cinfo) { my_dest_ptr dest = (my_dest_ptr) cinfo->dest; if (dest->outfile->write(dest->buffer, OUTPUT_BUF_SIZE) != (size_t) OUTPUT_BUF_SIZE) ERREXIT(cinfo, JERR_FILE_WRITE); dest->pub.next_output_byte = dest->buffer; dest->pub.free_in_buffer = OUTPUT_BUF_SIZE; return TRUE; } void term_destination (j_compress_ptr cinfo) { my_dest_ptr dest = (my_dest_ptr) cinfo->dest; size_t datacount = OUTPUT_BUF_SIZE - dest->pub.free_in_buffer; /* Write any data remaining in the buffer */ if (datacount > 0) { if (dest->outfile->write(dest->buffer, datacount) != datacount) ERREXIT(cinfo, JERR_FILE_WRITE); } } void jpeg_streambuf_dest (j_compress_ptr cinfo, std::streambuf& outfile) { my_dest_ptr dest; if (cinfo->dest == NULL) { /* first time for this JPEG object? */ cinfo->dest = (struct jpeg_destination_mgr *) (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT, SIZEOF(my_destination_mgr)); } dest = (my_dest_ptr) cinfo->dest; dest->pub.init_destination = init_streambuf_destination; dest->pub.empty_output_buffer = empty_streambuf_output_buffer; dest->pub.term_destination = term_destination; dest->outfile = &outfile; } } // namespace #endif // __ist_with_jpeg__ bool Image::loadJPG(IBinaryStream &f, const IOConfig &conf) { clear(); #ifdef __ist_with_jpeg__ jpeg_decompress_struct cinfo; my_error_mgr jerr; JSAMPARRAY buffer; int32 row_stride; cinfo.err = jpeg_std_error(&jerr.pub); jerr.pub.error_exit = my_error_exit; if(setjmp(jerr.setjmp_buffer)) { jpeg_destroy_decompress(&cinfo); return false; } jpeg_create_decompress(&cinfo); jpeg_streambuf_src(&cinfo, f); jpeg_read_header(&cinfo, TRUE); jpeg_start_decompress(&cinfo); row_stride = cinfo.output_width * cinfo.output_components; buffer = (*cinfo.mem->alloc_sarray)((j_common_ptr) &cinfo, JPOOL_IMAGE, row_stride, 1); resize(cinfo.image_width, cinfo.image_height); uint32 pix_count = 0; while (cinfo.output_scanline < cinfo.output_height) { jpeg_read_scanlines(&cinfo, buffer, 1); for(int32 i=0; i<(int32)row_stride/3; ++i) { RGBA_8U col(buffer[0][i*3+0], buffer[0][i*3+1], buffer[0][i*3+2], 255); at(pix_count) = col; ++pix_count; } } jpeg_finish_decompress(&cinfo); jpeg_destroy_decompress(&cinfo); return true; #else istPrint("失敗: jpg 使用を無効化した設定でビルドされています。"); return false; #endif // __ist_with_jpeg__ } bool Image::saveJPG(IBinaryStream &f, const IOConfig &conf) const { #ifdef __ist_with_jpeg__ jpeg_compress_struct cinfo; jpeg_error_mgr jerr; JSAMPROW row_pointer[1]; int32 row_stride; cinfo.err = jpeg_std_error(&jerr); jpeg_create_compress(&cinfo); jpeg_streambuf_dest(&cinfo, f); cinfo.image_width = width(); cinfo.image_height = height(); cinfo.input_components = 3; cinfo.in_color_space = JCS_RGB; jpeg_set_defaults(&cinfo); jpeg_set_quality(&cinfo, conf.getJpgQuality(), TRUE); jpeg_start_compress(&cinfo, TRUE); row_stride = cinfo.image_width*3; uint8 *buf = new uint8[width()*height()*3]; for(int32 i=0; i<(int32)width()*(int32)height(); ++i) { buf[i*3+0] = at(i).r; buf[i*3+1] = at(i).g; buf[i*3+2] = at(i).b; } while (cinfo.next_scanline < cinfo.image_height) { row_pointer[0] = &buf[cinfo.next_scanline * row_stride]; jpeg_write_scanlines(&cinfo, row_pointer, 1); } delete[] buf; jpeg_finish_compress(&cinfo); jpeg_destroy_compress(&cinfo); return true; #else // __ist_with_jpeg__ istPrint("失敗: jpg 使用を無効化した設定でビルドされています。"); return false; #endif // __ist_with_jpeg__ } } // namespace ist #ifdef __ist_with_gli__ namespace gli { namespace gtx { namespace loader_dds10{ namespace detail { // gli には std::string を引数にとるやつしかないので、ストリーム版をコピペ改変実装します。参考: loadDDS10() inline texture2D loadDDS10_ex( ist::IBinaryStream &bin ) { loader_dds9::detail::ddsHeader HeaderDesc; detail::ddsHeader10 HeaderDesc10; char Magic[4]; //* Read magic number and check if valid .dds file bin.read((char*)&Magic, sizeof(Magic)); assert(strncmp(Magic, "DDS ", 4) == 0); // Get the surface descriptor bin.read(&HeaderDesc, sizeof(HeaderDesc)); if(HeaderDesc.format.flags & loader_dds9::detail::GLI_DDPF_FOURCC && HeaderDesc.format.fourCC == loader_dds9::detail::GLI_FOURCC_DX10) bin.read(&HeaderDesc10, sizeof(HeaderDesc10)); loader_dds9::detail::DDLoader Loader; if(HeaderDesc.format.fourCC == loader_dds9::detail::GLI_FOURCC_DX10) Loader.Format = detail::format_dds2gli_cast(HeaderDesc10.dxgiFormat); else if(HeaderDesc.format.flags & loader_dds9::detail::GLI_DDPF_FOURCC) Loader.Format = detail::format_fourcc2gli_cast(HeaderDesc.format.fourCC); else { switch(HeaderDesc.format.bpp) { case 8: Loader.Format = R8U; break; case 16: Loader.Format = RG8U; break; case 24: Loader.Format = RGB8U; break; case 32: Loader.Format = RGBA8U; break; } } Loader.BlockSize = size(image(texture2D::dimensions_type(0), Loader.Format), BLOCK_SIZE); Loader.BPP = size(image(texture2D::dimensions_type(0), Loader.Format), BIT_PER_PIXEL); std::size_t Width = HeaderDesc.width; std::size_t Height = HeaderDesc.height; gli::format Format = Loader.Format; std::streamoff Curr = bin.getReadPos(); bin.setReadPos(0, ist::IBinaryStream::Seek_End); std::streamoff End = bin.getReadPos(); bin.setReadPos(Curr); std::vector<glm::byte> Data(std::size_t(End - Curr), 0); std::size_t Offset = 0; bin.read(&Data[0], std::streamsize(Data.size())); //texture2D Image(glm::min(MipMapCount, Levels));//SurfaceDesc.mipMapLevels); std::size_t MipMapCount = (HeaderDesc.flags & loader_dds9::detail::GLI_DDSD_MIPMAPCOUNT) ? HeaderDesc.mipMapLevels : 1; //if(Loader.Format == DXT1 || Loader.Format == DXT3 || Loader.Format == DXT5) // MipMapCount -= 2; texture2D Image(MipMapCount); for(std::size_t Level = 0; Level < Image.levels() && (Width || Height); ++Level) { Width = glm::max(std::size_t(Width), std::size_t(1)); Height = glm::max(std::size_t(Height), std::size_t(1)); std::size_t MipmapSize = 0; if((Loader.BlockSize << 3) > Loader.BPP) MipmapSize = ((Width + 3) >> 2) * ((Height + 3) >> 2) * Loader.BlockSize; else MipmapSize = Width * Height * Loader.BlockSize; std::vector<glm::byte> MipmapData(MipmapSize, 0); memcpy(&MipmapData[0], &Data[0] + Offset, MipmapSize); texture2D::dimensions_type Dimensions(Width, Height); Image[Level] = texture2D::image(Dimensions, Format, MipmapData); Offset += MipmapSize; Width >>= 1; Height >>= 1; } return Image; } } // detail } // loader_dds10 } // namespace gtx } // namespace gli #endif // __ist_with_gli__ namespace ist { bool Image::loadDDS( IBinaryStream &f, const IOConfig &conf ) { #ifdef __ist_with_gli__ gli::texture2D tex = gli::gtx::loader_dds10::detail::loadDDS10_ex(f); ivec2 dim = ivec2(tex[0].dimensions().x, tex[0].dimensions().y); switch(tex.format()) { case gli::R8U: setup(IF_R8U, dim.x, dim.y, tex[0].capacity()); break; case gli::R8I: setup(IF_R8I, dim.x, dim.y, tex[0].capacity()); break; case gli::R32F: setup(IF_R32F, dim.x, dim.y, tex[0].capacity()); break; case gli::RG8U: setup(IF_RG8U, dim.x, dim.y, tex[0].capacity()); break; case gli::RG8I: setup(IF_RG8I, dim.x, dim.y, tex[0].capacity()); break; case gli::RG32F: setup(IF_RG32F, dim.x, dim.y, tex[0].capacity()); break; case gli::RGB8U: setup(IF_RGB8U, dim.x, dim.y, tex[0].capacity()); break; case gli::RGB8I: setup(IF_RGB8I, dim.x, dim.y, tex[0].capacity()); break; case gli::RGB32F: setup(IF_RGB32F, dim.x, dim.y, tex[0].capacity()); break; case gli::RGBA8U: setup(IF_RGBA8U, dim.x, dim.y, tex[0].capacity()); break; case gli::RGBA8I: setup(IF_RGBA8I, dim.x, dim.y, tex[0].capacity()); break; case gli::RGBA32F: setup(IF_RGBA32F, dim.x, dim.y, tex[0].capacity()); break; case gli::DXT1: setup(IF_RGBA_DXT1, dim.x, dim.y, tex[0].capacity()); break; case gli::DXT3: setup(IF_RGBA_DXT3, dim.x, dim.y, tex[0].capacity()); break; case gli::DXT5: setup(IF_RGBA_DXT5, dim.x, dim.y, tex[0].capacity()); break; default: return false; } memcpy(data(), tex[0].data(), tex[0].capacity()); return true; #endif // __ist_with_gli__ return false; } bool Image::saveDDS( IBinaryStream &f, const IOConfig &conf ) const { istPrint("未実装"); return false; } } // namespace ist
28.805501
139
0.572228
i-saint
a22992aa915dd06e962163704b713c016925eb26
2,215
cpp
C++
tests/stl-dependency-test/library/cib/__zz_cib_StlDependencyTest-gateway.cpp
satya-das/cib
369333ea58b0530b8789a340e21096ba7d159d0e
[ "MIT" ]
30
2018-03-05T17:35:29.000Z
2022-03-17T18:59:34.000Z
tests/stl-dependency-test/library/cib/__zz_cib_StlDependencyTest-gateway.cpp
satya-das/cib
369333ea58b0530b8789a340e21096ba7d159d0e
[ "MIT" ]
2
2016-05-26T04:47:13.000Z
2019-02-15T05:17:43.000Z
tests/stl-dependency-test/library/cib/__zz_cib_StlDependencyTest-gateway.cpp
satya-das/cib
369333ea58b0530b8789a340e21096ba7d159d0e
[ "MIT" ]
5
2019-02-15T05:09:22.000Z
2021-04-14T12:10:16.000Z
#include "__zz_cib_StlDependencyTest-decl.h" #include "__zz_cib_StlDependencyTest-export.h" #include "__zz_cib_StlDependencyTest-ids.h" #include "__zz_cib_StlDependencyTest-mtable.h" namespace __zz_cib_ { namespace __zz_cib_Class263 { const __zz_cib_MethodTable* __zz_cib_GetMethodTable(); }} namespace __zz_cib_ { namespace __zz_cib_Class256 { namespace __zz_cib_Class258 { const __zz_cib_MethodTable* __zz_cib_GetMethodTable(); }}} namespace __zz_cib_ { namespace __zz_cib_Class256 { namespace __zz_cib_Class257 { const __zz_cib_MethodTable* __zz_cib_GetMethodTable(); }}} namespace __zz_cib_ { namespace __zz_cib_Class256 { namespace __zz_cib_Class260 { const __zz_cib_MethodTable* __zz_cib_GetMethodTable(); }}} namespace __zz_cib_ { namespace __zz_cib_Class256 { namespace __zz_cib_Class259 { const __zz_cib_MethodTable* __zz_cib_GetMethodTable(); }}} namespace __zz_cib_ { namespace __zz_cib_Class261 { namespace __zz_cib_Class262 { const __zz_cib_MethodTable* __zz_cib_GetMethodTable(); }}} extern "C" __zz_cib_export const __zz_cib_::__zz_cib_MethodTable* __zz_cib_decl __zz_cib_StlDependencyTestGetMethodTable(std::uint32_t classId) { switch(classId) { case __zz_cib_::__zz_cib_ids::__zz_cib_Class263::__zz_cib_classId: return __zz_cib_::__zz_cib_Class263::__zz_cib_GetMethodTable(); case __zz_cib_::__zz_cib_ids::__zz_cib_Class256::__zz_cib_Class258::__zz_cib_classId: return __zz_cib_::__zz_cib_Class256::__zz_cib_Class258::__zz_cib_GetMethodTable(); case __zz_cib_::__zz_cib_ids::__zz_cib_Class256::__zz_cib_Class257::__zz_cib_classId: return __zz_cib_::__zz_cib_Class256::__zz_cib_Class257::__zz_cib_GetMethodTable(); case __zz_cib_::__zz_cib_ids::__zz_cib_Class256::__zz_cib_Class260::__zz_cib_classId: return __zz_cib_::__zz_cib_Class256::__zz_cib_Class260::__zz_cib_GetMethodTable(); case __zz_cib_::__zz_cib_ids::__zz_cib_Class256::__zz_cib_Class259::__zz_cib_classId: return __zz_cib_::__zz_cib_Class256::__zz_cib_Class259::__zz_cib_GetMethodTable(); case __zz_cib_::__zz_cib_ids::__zz_cib_Class261::__zz_cib_Class262::__zz_cib_classId: return __zz_cib_::__zz_cib_Class261::__zz_cib_Class262::__zz_cib_GetMethodTable(); default: return nullptr; } }
67.121212
140
0.832957
satya-das
a22ae189aaa5767f514c0572455824bc70973c43
3,128
cc
C++
Pulse/src/InputStream.cc
frankencode/CoreComponents
4c66d7ff9fc5be19222906ba89ba0e98951179de
[ "Zlib" ]
1
2019-07-29T04:07:29.000Z
2019-07-29T04:07:29.000Z
Pulse/src/InputStream.cc
frankencode/CoreComponents
4c66d7ff9fc5be19222906ba89ba0e98951179de
[ "Zlib" ]
null
null
null
Pulse/src/InputStream.cc
frankencode/CoreComponents
4c66d7ff9fc5be19222906ba89ba0e98951179de
[ "Zlib" ]
1
2020-03-04T17:13:04.000Z
2020-03-04T17:13:04.000Z
/* * Copyright (C) 2021 Frank Mertens. * * Distribution and use is allowed under the terms of the zlib license * (see cc/LICENSE-zlib). * */ #include <cc/pulse/InputStream> #include <cc/Format> #include <cc/DEBUG> #include <pulse/stream.h> #include <cassert> namespace cc::pulse { struct InputStream::State: public Object::State { State(const Context &context, const String &name, int sampleRate, int channelCount): context_{context}, name_{name} { if (name_.count() == 0) { name_ = Format{"input_%%_%%"} << sampleRate << channelCount; } sampleSpec_.format = PA_SAMPLE_S16NE; sampleSpec_.rate = sampleRate; sampleSpec_.channels = channelCount; stream_ = pa_stream_new(context_, name_, &sampleSpec_, nullptr); pa_stream_set_state_callback(stream_, &stateChanged, this); pa_stream_set_read_callback(stream_, &incoming, this); } ~State() { if (stream_) { pa_stream_unref(stream_); } } static void stateChanged(pa_stream *stream, void *userData) { static_cast<State *>(userData)->stateChanged(pa_stream_get_state(stream)); } void stateChanged(pa_stream_state newState) { // CC_INSPECT(newState); if (newState == PA_STREAM_READY && onReady_) onReady_(); } static void incoming(pa_stream *stream, size_t fill, void *userData) { static_cast<State *>(userData)->incoming(fill); } void incoming(size_t fill) { if (sample_) { const void *data = nullptr; CC_PULSE(pa_stream_peek(stream_, &data, &fill)); if (data != nullptr && fill > 0 && sample_) { wrapping_.wrapAround(const_cast<void *>(data), fill); sample_(wrapping_); } if (fill > 0) { CC_PULSE(pa_stream_drop(stream_)); } } } void connect(const String &target, Fun<void()> &&ready) { if (ready) { onReady_ = move(ready); } const char *device = nullptr; if (target.count() > 0) device = target; CC_PULSE( pa_stream_connect_record(stream_, device, nullptr, PA_STREAM_NOFLAGS) ); } Context context_; pa_stream *stream_ { nullptr }; pa_sample_spec sampleSpec_ {}; String name_; Fun<void()> onReady_; Fun<void(const Bytes &data)> sample_; Bytes wrapping_; }; InputStream::InputStream(const Context &context, int sampleRate, int channelCount): Object{new State{context, {}, sampleRate, channelCount}} {} int InputStream::sampleRate() const { return me().sampleSpec_.rate; } void InputStream::incoming(Fun<void(const Bytes &data)> &&sample) { me().sample_ = move(sample); } void InputStream::connect(const String &target, Fun<void()> &&ready) { me().connect(target, move(ready)); } InputStream::State &InputStream::me() { return Object::me.as<State>(); } const InputStream::State &InputStream::me() const { return Object::me.as<State>(); } } // namespace cc::pulse
24.4375
88
0.609655
frankencode
a22d4c1cc7f16d757453e4eb88c8537cf9153bef
224
hpp
C++
cpp/include/mh/concurrency/main_thread.hpp
PazerOP/stuff
8ef31153dce1c9593d59fe7fb731fca4d15f3fa6
[ "MIT" ]
null
null
null
cpp/include/mh/concurrency/main_thread.hpp
PazerOP/stuff
8ef31153dce1c9593d59fe7fb731fca4d15f3fa6
[ "MIT" ]
4
2020-01-04T02:26:00.000Z
2020-04-19T10:46:50.000Z
cpp/include/mh/concurrency/main_thread.hpp
PazerOP/stuff
8ef31153dce1c9593d59fe7fb731fca4d15f3fa6
[ "MIT" ]
null
null
null
#pragma once #include <thread> namespace mh { inline static const std::thread::id main_thread_id = std::this_thread::get_id(); inline bool is_main_thread() { return main_thread_id == std::this_thread::get_id(); } }
16
81
0.714286
PazerOP
a2344908796c529df62a337119c9aae152cbd0ea
751
cc
C++
c-deps/libroach/cache.cc
benlong-transloc/cockroach
9a38931424b4b84116da606820d3cde699c90879
[ "MIT", "BSD-3-Clause" ]
2
2020-02-28T02:40:42.000Z
2020-02-28T04:08:48.000Z
c-deps/libroach/cache.cc
benlong-transloc/cockroach
9a38931424b4b84116da606820d3cde699c90879
[ "MIT", "BSD-3-Clause" ]
10
2020-09-06T14:29:19.000Z
2022-03-02T04:56:13.000Z
c-deps/libroach/cache.cc
rohany/cockroach
12c640b74f8a16a27eb5ba03df9628cec4c99400
[ "MIT", "BSD-3-Clause" ]
2
2019-11-12T13:38:48.000Z
2020-02-02T09:38:19.000Z
// Copyright 2018 The Cockroach Authors. // // Use of this software is governed by the Business Source License // included in the file licenses/BSL.txt. // // As of the Change Date specified in that file, in accordance with // the Business Source License, use of this software will be governed // by the Apache License, Version 2.0, included in the file // licenses/APL.txt. #include "cache.h" DBCache* DBNewCache(uint64_t size) { const int num_cache_shard_bits = 4; DBCache* cache = new DBCache; cache->rep = rocksdb::NewLRUCache(size, num_cache_shard_bits); return cache; } DBCache* DBRefCache(DBCache* cache) { DBCache* res = new DBCache; res->rep = cache->rep; return res; } void DBReleaseCache(DBCache* cache) { delete cache; }
27.814815
69
0.729694
benlong-transloc
a23b954d4f083885e3d2212f014d11bba31dab9e
7,356
cpp
C++
Src/widget.cpp
BastiaanOlij/omnis.xcomp.widget
629b203f4bd6d1e1e408f1b2ed3de4eaf45d0e1a
[ "MIT" ]
1
2018-08-09T23:44:54.000Z
2018-08-09T23:44:54.000Z
Src/widget.cpp
BastiaanOlij/omnis.xcomp.widget
629b203f4bd6d1e1e408f1b2ed3de4eaf45d0e1a
[ "MIT" ]
2
2015-01-20T03:51:53.000Z
2020-03-27T04:45:38.000Z
Src/widget.cpp
BastiaanOlij/omnis.xcomp.widget
629b203f4bd6d1e1e408f1b2ed3de4eaf45d0e1a
[ "MIT" ]
1
2018-09-13T05:07:08.000Z
2018-09-13T05:07:08.000Z
/* * omnis.xcomp.widget * =================== * * widget.cpp * Widget library implementation * * Bastiaan Olij */ #include "widget.h" #ifdef iswin32 /* not yet supported */ #else #include "monitor_mac.h" #endif qshort mainlib::major() { return OMNISSDK; }; qshort mainlib::minor() { return 124; }; ECOmethodEvent widgetStaticFuncs[] = { // ID, Resource, Flags 9000, 9000, fftList, 0, 0, 0, 0, }; /* see omnis.xcomp.framework\oXCompLib.h for methods to implement here */ qint mainlib::ecm_connect(void) { OXFcomponent lvComponent; addStaticMethods(widgetStaticFuncs, 1); // add our component definitions here... lvComponent.componentType = cObjType_NVObject; lvComponent.componentID = 2000; lvComponent.bitmapID = 0; lvComponent.flags = 0; lvComponent.groupResID = 0; lvComponent.newObjectFunction = (void * (*)()) &(oDateTime::newObject); lvComponent.mProperties = oDateTime::properties(); lvComponent.mMethods = oDateTime::methods(); lvComponent.mEventMethodID = 0; lvComponent.mEvents = oDateTime::events(); addComponent(lvComponent); lvComponent.componentType = cObjType_Basic; lvComponent.componentID = 2001; lvComponent.bitmapID = 1; lvComponent.flags = 0; lvComponent.groupResID = 0; lvComponent.newObjectFunction = (void * (*)()) &(oCountButton::newObject); lvComponent.mProperties = oCountButton::properties(); lvComponent.mMethods = oCountButton::methods(); lvComponent.mEventMethodID = 10000; lvComponent.mEvents = oCountButton::events(); addComponent(lvComponent); lvComponent.componentType = cObjType_Basic; lvComponent.componentID = 2006; lvComponent.bitmapID = 1; lvComponent.flags = 0; lvComponent.groupResID = 0; lvComponent.newObjectFunction = (void * (*)()) &(oRoundedButton::newObject); lvComponent.mProperties = oRoundedButton::properties(); lvComponent.mMethods = oRoundedButton::methods(); lvComponent.mEventMethodID = 10000; lvComponent.mEvents = oRoundedButton::events(); addComponent(lvComponent); lvComponent.componentType = cObjType_Basic; lvComponent.componentID = 2002; lvComponent.bitmapID = 1; lvComponent.flags = 0; lvComponent.groupResID = 0; lvComponent.newObjectFunction = (void * (*)()) &(oDataList::newObject); lvComponent.mProperties = oDataList::properties(); lvComponent.mMethods = oDataList::methods(); lvComponent.mEventMethodID = 10010; lvComponent.mEvents = oDataList::events(); addComponent(lvComponent); lvComponent.componentType = cObjType_DropList; lvComponent.componentID = 2003; lvComponent.bitmapID = 1; lvComponent.flags = 0; lvComponent.groupResID = 0; lvComponent.newObjectFunction = (void * (*)()) &(oDropDown::newObject); lvComponent.mProperties = oDropDown::properties(); lvComponent.mMethods = oDropDown::methods(); lvComponent.mEventMethodID = 10020; lvComponent.mEvents = oDropDown::events(); addComponent(lvComponent); lvComponent.componentType = cObjType_DropList; lvComponent.componentID = 2005; lvComponent.bitmapID = 1; lvComponent.flags = 0; lvComponent.groupResID = 0; lvComponent.newObjectFunction = (void * (*)()) &(oFontDropDown::newObject); lvComponent.mProperties = oFontDropDown::properties(); lvComponent.mMethods = oFontDropDown::methods(); lvComponent.mEventMethodID = 10020; lvComponent.mEvents = oFontDropDown::events(); addComponent(lvComponent); lvComponent.componentType = cObjType_NVObject; lvComponent.componentID = 2004; lvComponent.bitmapID = 0; lvComponent.flags = 0; lvComponent.groupResID = 0; lvComponent.newObjectFunction = (void * (*)()) &(oImage::newObject); lvComponent.mProperties = oImage::properties(); lvComponent.mMethods = oImage::methods(); lvComponent.mEventMethodID = 0; lvComponent.mEvents = oImage::events(); addComponent(lvComponent); return oXCompLib::ecm_connect(); }; qbool mainlib::ecm_disconnect(void) { // nothing to do here.. return oXCompLib::ecm_disconnect(); }; #ifdef iswin32 void addActiveWindowToMonitorList(EXTqlist * pMonitorList) { /* Get some info about the active window */ TCHAR name[250]; qchar qname[250]; RECT position; HWND hWnd = GetActiveWindow(); int len = GetWindowTextLength(hWnd); if (len > 0) { if (len > 249) { len = 249; }; GetWindowText(hWnd, name, len+1); CHRconvFromOs::convFromOs(name, len, qname, 250); }; GetWindowRect(hWnd, &position); /* now add it to our list */ EXTfldval colFld; qlong rowNo = pMonitorList->insertRow(); pMonitorList->getColValRef(rowNo, 1, colFld, qtrue); colFld.setLong(position.left); pMonitorList->getColValRef(rowNo, 2, colFld, qtrue); colFld.setLong(position.top); pMonitorList->getColValRef(rowNo, 3, colFld, qtrue); colFld.setLong(position.right); pMonitorList->getColValRef(rowNo, 4, colFld, qtrue); colFld.setLong(position.bottom); if (len > 0) { pMonitorList->getColValRef(rowNo, 5, colFld, qtrue); colFld.setChar(qname, len); }; }; #endif int mainlib::invokeMethod(qlong pMethodId, EXTCompInfo* pECI) { switch (pMethodId) { case 9000: { /* $monitors - get list with monitor info */ EXTfldval result; EXTqlist * monitorList = new EXTqlist(listVlen); str255 colName; /* add some columns */ colName = QTEXT("Left"); monitorList->addCol(1, fftInteger, 0, 0, NULL, &colName); colName = QTEXT("Top"); monitorList->addCol(2, fftInteger, 0, 0, NULL, &colName); colName = QTEXT("Right"); monitorList->addCol(3, fftInteger, 0, 0, NULL, &colName); colName = QTEXT("Bottom"); monitorList->addCol(4, fftInteger, 0, 0, NULL, &colName); colName = QTEXT("Name"); monitorList->addCol(5, fftCharacter, dpFcharacter, 250, NULL, &colName); #ifdef iswin32 /* on windows Omnis is contained within its main window, so we add its dimensions */ addActiveWindowToMonitorList(monitorList); /* may in due time add the actual monitors to this list as well */ #else /* lets see if we can call some obj-c */ monitor_mac * moninfo = new monitor_mac(); for (int i = 0; i < moninfo->mNumActiveMonitors; i++) { EXTfldval colFld; qlong rowNo = monitorList->insertRow(); monitorList->getColValRef(rowNo, 1, colFld, qtrue); colFld.setLong(moninfo->mMonitors[i].left); monitorList->getColValRef(rowNo, 2, colFld, qtrue); colFld.setLong(moninfo->mMonitors[i].top); monitorList->getColValRef(rowNo, 3, colFld, qtrue); colFld.setLong(moninfo->mMonitors[i].right); monitorList->getColValRef(rowNo, 4, colFld, qtrue); colFld.setLong(moninfo->mMonitors[i].bottom); }; delete moninfo; #endif /* and return our list */ result.setList(monitorList, qtrue); delete monitorList; ECOaddParam(pECI, &result); return 1L; } break; default: { return oXCompLib::invokeMethod(pMethodId, pECI); } break; } };
31.302128
87
0.660821
BastiaanOlij
a24bbd680103c5e0bd7054b3e95aa6a8eb8d8e3e
3,303
cpp
C++
compiler/luci/pass/src/RemoveUnnecessarySplitPass.test.cpp
chunseoklee/ONE-1
f45d579eb78e7e3cd1d878b4137ed23ab569081b
[ "Apache-2.0" ]
null
null
null
compiler/luci/pass/src/RemoveUnnecessarySplitPass.test.cpp
chunseoklee/ONE-1
f45d579eb78e7e3cd1d878b4137ed23ab569081b
[ "Apache-2.0" ]
null
null
null
compiler/luci/pass/src/RemoveUnnecessarySplitPass.test.cpp
chunseoklee/ONE-1
f45d579eb78e7e3cd1d878b4137ed23ab569081b
[ "Apache-2.0" ]
null
null
null
/* * Copyright (c) 2020 Samsung Electronics Co., Ltd. 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 "luci/Pass/RemoveUnnecessarySplitPass.h" #include <luci/IR/CircleNodes.h> #include <gtest/gtest.h> namespace { void create_unnecessary_split_graph(loco::Graph *g, bool remove) { assert(g); auto input = g->nodes()->create<luci::CircleInput>(); auto graph_input = g->inputs()->create(); input->index(graph_input->index()); auto dim = g->nodes()->create<luci::CircleConst>(); dim->dtype(loco::DataType::S32); dim->size<loco::DataType::S32>(1); dim->rank(1); dim->dim(0).set(1); dim->at<loco::DataType::S32>(0) = 0; auto split_node = g->nodes()->create<luci::CircleSplit>(); split_node->split_dim(dim); split_node->input(input); if (remove) split_node->num_split(1); else split_node->num_split(2); auto split_out_node0 = g->nodes()->create<luci::CircleSplitOut>(); split_out_node0->input(split_node); split_out_node0->index(0); auto output0 = g->nodes()->create<luci::CircleOutput>(); output0->from(split_out_node0); auto graph_output0 = g->outputs()->create(); output0->index(graph_output0->index()); if (!remove) { auto split_out_node1 = g->nodes()->create<luci::CircleSplitOut>(); split_out_node1->input(split_node); split_out_node1->index(1); auto output1 = g->nodes()->create<luci::CircleOutput>(); output1->from(split_out_node1); auto graph_output1 = g->outputs()->create(); output1->index(graph_output1->index()); } } } // namespace TEST(RemoveUnnecessarySplitPass, name) { luci::RemoveUnnecessarySplitPass pass; auto const name = pass.name(); ASSERT_NE(nullptr, name); } TEST(RemoveUnnecessarySplitPass, create_unnecessary_split) { auto graph = loco::make_graph(); create_unnecessary_split_graph(graph.get(), true); luci::RemoveUnnecessarySplitPass pass; while (pass.run(graph.get())) ; luci::CircleSplit *split_node = nullptr; for (auto node : loco::active_nodes(loco::output_nodes(graph.get()))) { auto split = dynamic_cast<luci::CircleSplit *>(node); if (not split) continue; split_node = split; } // No Split node is in graph. ASSERT_EQ(nullptr, split_node); } TEST(RemoveUnnecessarySplitPass, create_unnecessary_split_NEG) { auto graph = loco::make_graph(); create_unnecessary_split_graph(graph.get(), false); luci::RemoveUnnecessarySplitPass pass; while (pass.run(graph.get())) ; luci::CircleSplit *split_node = nullptr; for (auto node : loco::active_nodes(loco::output_nodes(graph.get()))) { auto split = dynamic_cast<luci::CircleSplit *>(node); if (not split) continue; split_node = split; } // Split node is in graph. ASSERT_NE(nullptr, split_node); }
27.991525
75
0.696942
chunseoklee
a24bfb0a5c845c9ca80feb2549a6fff554012fcd
5,151
hpp
C++
src/helics/cpp98/Endpoint.hpp
dnadeau4/HELICS-src
cad21acaac68d25b50e08b185d4fe5a1ae054241
[ "BSD-3-Clause" ]
null
null
null
src/helics/cpp98/Endpoint.hpp
dnadeau4/HELICS-src
cad21acaac68d25b50e08b185d4fe5a1ae054241
[ "BSD-3-Clause" ]
null
null
null
src/helics/cpp98/Endpoint.hpp
dnadeau4/HELICS-src
cad21acaac68d25b50e08b185d4fe5a1ae054241
[ "BSD-3-Clause" ]
null
null
null
/* Copyright © 2017-2019, Battelle Memorial Institute; Lawrence Livermore National Security, LLC; Alliance for Sustainable Energy, LLC. See the top-level NOTICE for additional details. All rights reserved. SPDX-License-Identifier: BSD-3-Clause */ #ifndef HELICS_CPP98_ENDPOINT_HPP_ #define HELICS_CPP98_ENDPOINT_HPP_ #pragma once #include "../shared_api_library/MessageFederate.h" #include "helicsExceptions.hpp" #include <vector> #include <string> namespace helicscpp { class Endpoint { public: explicit Endpoint (helics_endpoint hep) HELICS_NOTHROW: ep (hep) {} Endpoint () HELICS_NOTHROW : ep (HELICS_NULL_POINTER){}; Endpoint (const Endpoint &endpoint) HELICS_NOTHROW: ep (endpoint.ep) {} Endpoint &operator= (const Endpoint &endpoint) { ep = endpoint.ep; return *this; } operator helics_endpoint () { return ep; } helics_endpoint baseObject () const { return ep; } /* Checks if endpoint has unread messages **/ bool hasMessage () const { // returns int, 1 = true, 0 = false return helicsEndpointHasMessage (ep) > 0; } /** set the default destination for an endpoint*/ void setDefaultDestination (const std::string &dest) { helicsEndpointSetDefaultDestination (ep, dest.c_str (), hThrowOnError ()); } /** get the default destination for an endpoint*/ const char *getDefaultDestination () const { return helicsEndpointGetDefaultDestination (ep); } /** Returns the number of pending receives for endpoint **/ uint64_t pendingMessages () const { return helicsEndpointPendingMessages (ep); } /** Get a packet from an endpoint **/ helics_message getMessage () { return helicsEndpointGetMessage (ep); } /** Methods for sending a message **/ void sendMessage (const char *data, size_t len) { helicsEndpointSendMessageRaw (ep, HELICS_NULL_POINTER, data, static_cast<int> (len), hThrowOnError ()); } /** Methods for sending a message **/ void sendMessage (const std::string &dest, const char *data, size_t len) { helicsEndpointSendMessageRaw (ep, dest.c_str (), data, static_cast<int> (len), hThrowOnError ()); } void sendMessage (const char *data, size_t len, helics_time time) { helicsEndpointSendEventRaw (ep, HELICS_NULL_POINTER, data, static_cast<int> (len), time, hThrowOnError ()); } void sendMessage (const std::string &dest, const char *data, size_t len, helics_time time) { helicsEndpointSendEventRaw (ep, dest.c_str (), data, static_cast<int> (len), time, hThrowOnError ()); } /** Methods for sending a message **/ void sendMessage (const std::string &data) { helicsEndpointSendMessageRaw (ep, HELICS_NULL_POINTER, data.c_str (), static_cast<int> (data.size ()), hThrowOnError ()); } /** Methods for sending a message **/ void sendMessage (const std::string &dest, const std::string &data) { helicsEndpointSendMessageRaw (ep, dest.c_str (), data.c_str (), static_cast<int> (data.size ()), hThrowOnError ()); } void sendMessage (const std::string &data, helics_time time) { helicsEndpointSendEventRaw (ep, HELICS_NULL_POINTER, data.c_str (), static_cast<int> (data.size ()), time, hThrowOnError ()); } void sendMessage (const std::string &dest, const std::string &data, helics_time time) { helicsEndpointSendEventRaw (ep, dest.c_str (), data.c_str (), static_cast<int> (data.size ()), time, hThrowOnError ()); } /** Methods for sending a message **/ void sendMessage (const std::vector<char> &data) { helicsEndpointSendMessageRaw (ep, HELICS_NULL_POINTER, data.data (), static_cast<int> (data.size ()), hThrowOnError ()); } /** Methods for sending a message **/ void sendMessage (const std::string &dest, const std::vector<char> &data) { helicsEndpointSendMessageRaw (ep, dest.c_str (), data.data (), static_cast<int> (data.size ()), hThrowOnError ()); } void sendMessage (const std::vector<char> &data, helics_time time) { helicsEndpointSendEventRaw (ep, HELICS_NULL_POINTER, data.data (), static_cast<int> (data.size ()), time, hThrowOnError ()); } void sendMessage (const std::string &dest, const std::vector<char> &data, helics_time time) { helicsEndpointSendEventRaw (ep, dest.c_str (), data.data (), static_cast<int> (data.size ()), time, hThrowOnError ()); } void sendMessage (helics_message &message) { // returns helicsStatus helicsEndpointSendMessage (ep, &message, hThrowOnError ()); } const char *getName () const { return helicsEndpointGetName (ep); } std::string getType () { return helicsEndpointGetType (ep); } private: helics_endpoint ep; }; } // namespace helicscpp #endif
36.531915
115
0.635411
dnadeau4
a2500101143a610b8c7fa14d6da625291270a722
22,104
cpp
C++
thirdparty/ULib/src/ulib/ldap/ldap.cpp
liftchampion/nativejson-benchmark
6d575ffa4359a5c4230f74b07d994602a8016fb5
[ "MIT" ]
null
null
null
thirdparty/ULib/src/ulib/ldap/ldap.cpp
liftchampion/nativejson-benchmark
6d575ffa4359a5c4230f74b07d994602a8016fb5
[ "MIT" ]
null
null
null
thirdparty/ULib/src/ulib/ldap/ldap.cpp
liftchampion/nativejson-benchmark
6d575ffa4359a5c4230f74b07d994602a8016fb5
[ "MIT" ]
null
null
null
// ============================================================================ // // = LIBRARY // ULib - c++ library // // = FILENAME // ldap.cpp // // = AUTHOR // Stefano Casazza // // ============================================================================ #include <ulib/url.h> #include <ulib/ldap/ldap.h> struct timeval ULDAP::timeOut = { 30L, 0L }; // 30 second connection/search timeout ULDAPEntry::ULDAPEntry(int num_names, const char** names, int num_entry) { U_TRACE_REGISTER_OBJECT(0, ULDAPEntry, "%d,%p,%d", num_names, names, num_entry) U_INTERNAL_ASSERT_EQUALS(names[num_names], 0) U_DUMP_ATTRS(names) n_attr = num_names; n_entry = num_entry; attr_name = names; dn = (char**) UMemoryPool::_malloc(num_entry, sizeof(char*), true); attr_val = (UString**) UMemoryPool::_malloc(num_entry * num_names, sizeof(UString*), true); } ULDAPEntry::~ULDAPEntry() { U_TRACE_UNREGISTER_OBJECT(0, ULDAPEntry) for (int i = 0, j, k = 0; i < n_entry; ++i) { if (dn[i]) { U_INTERNAL_DUMP("dn[%d]: %S", i, dn[i]) ldap_memfree(dn[i]); for (j = 0; j < n_attr; ++j, ++k) { if (attr_val[k]) { U_INTERNAL_DUMP("ULDAPEntry(%d): %S = %V", k, attr_name[j], attr_val[k]->rep) delete attr_val[k]; } } } } UMemoryPool::_free(dn, n_entry, sizeof(char*)); UMemoryPool::_free(attr_val, n_entry * n_attr, sizeof(UString*)); } void ULDAPEntry::set(char* attribute, char** values, int index_entry) { U_TRACE(0, "ULDAPEntry::set(%S,%p,%d)", attribute, values, index_entry) U_DUMP_ATTRS(values) U_INTERNAL_ASSERT_MINOR(index_entry, n_entry) for (int j = 0, k = index_entry * n_attr; j < n_attr; ++j, ++k) { if (strcmp(attr_name[j], attribute) == 0) { U_INTERNAL_DUMP("ULDAPEntry(%d): %S", k, attr_name[j]) U_NEW(UString, attr_val[k], UString((void*)values[0], u__strlen(values[0], __PRETTY_FUNCTION__))); for (j = 1; values[j]; ++j) { attr_val[k]->append(U_CONSTANT_TO_PARAM("; ")); attr_val[k]->append(values[j]); } U_INTERNAL_DUMP("value = %V", attr_val[k]->rep) break; } } } void ULDAPEntry::set(char* attribute, char* value, uint32_t len, int index_entry) { U_TRACE(0, "ULDAPEntry::set(%S,%.*S,%u,%d)", attribute, len, value, len, index_entry) U_INTERNAL_ASSERT_MINOR(index_entry, n_entry) for (int j = 0, k = index_entry * n_attr; j < n_attr; ++j, ++k) { if (strcmp(attr_name[j], attribute) == 0) { U_INTERNAL_DUMP("ULDAPEntry(%d): %S", k, attr_name[j]) U_NEW(UString, attr_val[k], UString((void*)value, len)); U_INTERNAL_DUMP("value = %V", attr_val[k]->rep) break; } } } UString ULDAPEntry::getString(int index_names, int index_entry) { U_TRACE(0, "ULDAPEntry::getString(%d,%d)", index_names, index_entry) U_INTERNAL_ASSERT_MINOR(index_names, n_attr) U_INTERNAL_ASSERT_MINOR(index_entry, n_entry) int k = (index_entry * n_attr) + index_names; if (attr_val[k]) { UString str = *(attr_val[k]); U_RETURN_STRING(str); } return UString::getStringNull(); } const char* ULDAPEntry::getCStr(int index_names, int index_entry) { U_TRACE(0, "ULDAPEntry::getCStr(%d,%d)", index_names, index_entry) U_INTERNAL_ASSERT_MINOR(index_names, n_attr) U_INTERNAL_ASSERT_MINOR(index_entry, n_entry) int k = (index_entry * n_attr) + index_names; if (attr_val[k]) { const char* str = attr_val[k]->c_str(); U_RETURN(str); } U_RETURN(""); } void ULDAP::clear() { U_TRACE_NO_PARAM(1, "ULDAP::clear()") if (ludpp) { # if !defined(_MSWINDOWS_) && !defined(HAVE_WINLDAP_H) U_SYSCALL_VOID(ldap_free_urldesc, "%p", ludpp); # else int i; if (ludpp->lud_dn) U_SYSCALL_VOID(free, "%p", (void*)ludpp->lud_dn); if (ludpp->lud_host) U_SYSCALL_VOID(free, "%p", (void*)ludpp->lud_host); if (ludpp->lud_filter) U_SYSCALL_VOID(free, "%p", ludpp->lud_filter); if (ludpp->lud_attrs) { for (i = 0; ludpp->lud_attrs[i]; ++i) U_SYSCALL_VOID(free, "%p", ludpp->lud_attrs[i]); U_SYSCALL_VOID(free, "%p", ludpp->lud_attrs); } if (ludpp->lud_exts) { for (i = 0; ludpp->lud_exts[i]; ++i) U_SYSCALL_VOID(free, "%p", ludpp->lud_exts[i]); U_SYSCALL_VOID(free, "%p", ludpp->lud_exts); } U_SYSCALL_VOID(free, "%p", ludpp); # endif ludpp = 0; } if (ld) { if (searchResult) { U_SYSCALL(ldap_msgfree, "%p", searchResult); searchResult = 0; } U_SYSCALL(ldap_unbind_s, "%p", ld); ld = 0; # if defined(HAVE_LDAP_SSL_H) && defined(HAS_NOVELL_LDAPSDK) if (isSecure) U_SYSCALL_NO_PARAM(ldapssl_client_deinit); # endif } } void ULDAP::setStatus() { U_TRACE_NO_PARAM(0, "ULDAP::setStatus()") U_CHECK_MEMORY static const char* errlist[] = { "LDAP_SUCCESS", // 0 0x00 "LDAP_OPERATIONS_ERROR", // 1 0x01 "LDAP_PROTOCOL_ERROR", // 2 0x02 "LDAP_TIMELIMIT_EXCEEDED", // 3 0x03 "LDAP_SIZELIMIT_EXCEEDED", // 4 0x04 "LDAP_COMPARE_FALSE", // 5 0x05 "LDAP_COMPARE_TRUE", // 6 0x06 "LDAP_STRONG_AUTH_NOT_SUPPORTED", // 7 0x07 "LDAP_STRONG_AUTH_REQUIRED", // 8 0x08 "LDAP_PARTIAL_RESULTS", // 9 0x09 "LDAP_REFERRAL", // 10 "LDAP_ADMINLIMIT_EXCEEDED", // 11 "LDAP_UNAVAILABLE_CRITICAL_EXTENSION", // 12 "LDAP_CONFIDENTIALITY_REQUIRED", // 13 "LDAP_SASL_BIND_IN_PROGRESS", // 14 "", // 15 "LDAP_NO_SUCH_ATTRIBUTE", // 16 0x10 "LDAP_UNDEFINED_TYPE", // 17 0x11 "LDAP_INAPPROPRIATE_MATCHING", // 18 0x12 "LDAP_CONSTRAINT_VIOLATION", // 19 0x13 "LDAP_TYPE_OR_VALUE_EXISTS", // 20 0x14 "LDAP_INVALID_SYNTAX", // 21 0x15 "", // 22 "", // 23 "", // 24 "", // 25 "", // 26 "", // 27 "", // 28 "", // 29 "", // 30 "", // 31 "LDAP_NO_SUCH_OBJECT", // 32 0x20 "LDAP_ALIAS_PROBLEM", // 33 0x21 "LDAP_INVALID_DN_SYNTAX", // 34 0x22 "LDAP_IS_LEAF", // 35 0x23 "LDAP_ALIAS_DEREF_PROBLEM", // 36 0x24 "", // 37 "", // 38 "", // 39 "", // 40 "", // 41 "", // 42 "", // 43 "", // 44 "", // 45 "", // 46 "", // 47 "LDAP_INAPPROPRIATE_AUTH", // 48 0x30 "LDAP_INVALID_CREDENTIALS", // 49 0x31 "LDAP_INSUFFICIENT_ACCESS", // 50 0x32 "LDAP_BUSY", // 51 0x33 "LDAP_UNAVAILABLE", // 52 0x34 "LDAP_UNWILLING_TO_PERFORM", // 53 0x35 "LDAP_LOOP_DETECT", // 54 0x36 "", // 55 "", // 56 "", // 57 "", // 58 "", // 59 "", // 60 "", // 61 "", // 62 "", // 63 "LDAP_NAMING_VIOLATION", // 64 0x40 "LDAP_OBJECT_CLASS_VIOLATION", // 65 0x41 "LDAP_NOT_ALLOWED_ON_NONLEAF", // 66 0x42 "LDAP_NOT_ALLOWED_ON_RDN", // 67 0x43 "LDAP_ALREADY_EXISTS", // 68 0x44 "LDAP_NO_OBJECT_CLASS_MODS", // 69 0x45 "LDAP_RESULTS_TOO_LARGE", // 70 0x46 "LDAP_AFFECTS_MULTIPLE_DSAS", // 71 "", // 72 "", // 73 "", // 74 "", // 75 "", // 76 "", // 77 "", // 78 "", // 79 "LDAP_OTHER", // 80 0x50 "LDAP_SERVER_DOWN", // 81 0x51 "LDAP_LOCAL_ERROR", // 82 0x52 "LDAP_ENCODING_ERROR", // 83 0x53 "LDAP_DECODING_ERROR", // 84 0x54 "LDAP_TIMEOUT", // 85 0x55 "LDAP_AUTH_UNKNOWN", // 86 0x56 "LDAP_FILTER_ERROR", // 87 0x57 "LDAP_USER_CANCELLED", // 88 0x58 "LDAP_PARAM_ERROR", // 89 0x59 "LDAP_NO_MEMORY", // 90 0x5a "LDAP_CONNECT_ERROR", // 91 0x5b "LDAP_NOT_SUPPORTED", // 92 0x5c "LDAP_CONTROL_NOT_FOUND", // 93 0x5d "LDAP_NO_RESULTS_RETURNED", // 94 0x5e "LDAP_MORE_RESULTS_TO_RETURN", // 95 0x5f "LDAP_CLIENT_LOOP", // 96 0x60 "LDAP_REFERRAL_LIMIT_EXCEEDED" // 97 0x61 }; char* descr = ldap_err2string(result); /** * get a meaningful error string back from the security library * this function should be called, if ldap_err2string doesn't * identify the error code */ #if defined(HAVE_LDAP_SSL_H) && !defined(_MSWINDOWS_) && !defined(HAVE_WINLDAP_H) if (descr == 0) descr = (char*)ldapssl_err2string(result); #endif U_INTERNAL_ASSERT_EQUALS(u_buffer_len, 0) u_buffer_len = u__snprintf(u_buffer, U_BUFFER_SIZE, U_CONSTANT_TO_PARAM("%s (%d, %s)"), (result >= 0 && result < 97 ? errlist[result] : ""), result, descr); } #if defined(_MSWINDOWS_) && defined(HAVE_WINLDAP_H) /** * Split 'str' into strings separated by commas. * * Note: res[] points into 'str' */ U_NO_EXPORT char** ULDAP::split_str(char* str) { U_TRACE(0, "ULDAP::split_str(%S)", str) int i; char **res, *s; for (i = 2, s = strchr(str, ','); s; ++i) s = strchr(++s, ','); res = (char**)calloc(i, sizeof(char*)); for (i = 0, s = strtok(str, ","); s; s = strtok(0, ","), ++i) res[i] = s; U_DUMP_ATTRS(res) return res; } #endif /* Initialize the LDAP session */ bool ULDAP::init(const char* url) { U_TRACE(1, "ULDAP::init(%S)", url) U_CHECK_MEMORY U_INTERNAL_ASSERT_POINTER(url) if (ludpp) clear(); #if !defined(_MSWINDOWS_) && !defined(HAVE_WINLDAP_H) result = U_SYSCALL(ldap_url_parse, "%S,%p", url, &ludpp); #else result = LDAP_INVALID_SYNTAX; /** * Break apart the pieces of an LDAP URL * * Syntax: * ldap://<hostname>:<port>/<base_dn>?<attributes>?<scope>?<filter>?<ext> * * Defined in RFC4516 section 2 */ Url _url(url, u__strlen(url, __PRETTY_FUNCTION__)); ludpp = (LDAPURLDesc*) calloc(1, sizeof(LDAPURLDesc)); ludpp->lud_host = _url.getHost().c_strdup(); ludpp->lud_port = _url.getPort(); ludpp->lud_dn = _url.getPath().c_strndup(1); ludpp->lud_scope = LDAP_SCOPE_BASE; U_INTERNAL_DUMP("host = %S dn = %S", ludpp->lud_host, ludpp->lud_dn) // parse attributes, skip "??" UString query = _url.getQuery(); char* p = query.data(); char* q = strchr(p, '?'); if (q) *q++ = '\0'; U_INTERNAL_DUMP("attributes = %S", p) if (*p && *p != '?') ludpp->lud_attrs = split_str(p); p = q; if (!p) goto next; // parse scope, skip "??" q = strchr(p, '?'); if (q) *q++ = '\0'; if (*p && *p != '?') { if (strncmp(p, U_CONSTANT_TO_PARAM("base")) == 0) ludpp->lud_scope = LDAP_SCOPE_BASE; else if (strncmp(p, U_CONSTANT_TO_PARAM("one")) == 0) ludpp->lud_scope = LDAP_SCOPE_ONELEVEL; else if (strncmp(p, U_CONSTANT_TO_PARAM("onetree")) == 0) ludpp->lud_scope = LDAP_SCOPE_ONELEVEL; else if (strncmp(p, U_CONSTANT_TO_PARAM("sub")) == 0) ludpp->lud_scope = LDAP_SCOPE_SUBTREE; else if (strncmp(p, U_CONSTANT_TO_PARAM("subtree")) == 0) ludpp->lud_scope = LDAP_SCOPE_SUBTREE; U_INTERNAL_DUMP("scope = %d %S", ludpp->lud_scope, p) } p = q; if (!p) goto next; // parse filter q = strchr(p, '?'); if (q) *q++ = '\0'; if (!*p) goto next; ludpp->lud_filter = strdup(p); U_INTERNAL_DUMP("filter = %S", ludpp->lud_filter) // parse extensions if (q) ludpp->lud_exts = split_str(q); result = LDAP_SUCCESS; next: #endif if (result != LDAP_SUCCESS) { # ifdef DEBUG char buffer[1024]; const char* descr = "???"; const char* errstr = ""; switch (result) { # if !defined(_MSWINDOWS_) || !defined(HAVE_WINLDAP_H) case LDAP_INVALID_SYNTAX: descr = "LDAP_INVALID_SYNTAX"; errstr = "Invalid URL syntax"; break; case LDAP_URL_ERR_MEM: descr = "LDAP_URL_ERR_MEM"; errstr = "Cannot allocate memory space"; break; case LDAP_URL_ERR_PARAM: descr = "LDAP_URL_ERR_PARAM"; errstr = "Invalid parameter"; break; case LDAP_URL_ERR_BADSCOPE: descr = "LDAP_URL_ERR_BADSCOPE"; errstr = "Invalid or missing scope string"; break; # if defined(HAVE_LDAP_SSL_H) case LDAP_URL_ERR_NOTLDAP: descr = "LDAP_URL_ERR_NOTLDAP"; errstr = "URL doesn't begin with \"ldap://\""; break; case LDAP_URL_ERR_NODN: descr = "LDAP_URL_ERR_NODN"; errstr = "URL has no DN (required)"; break; case LDAP_URL_UNRECOGNIZED_CRITICAL_EXTENSION: descr = "LDAP_URL_UNRECOGNIZED_CRITICAL_EXTENSION"; errstr = ""; break; # else case LDAP_URL_ERR_BADSCHEME: descr = "LDAP_URL_ERR_BADSCHEME"; errstr = "URL doesnt begin with \"ldap[s]://\""; break; case LDAP_URL_ERR_BADENCLOSURE: descr = "LDAP_URL_ERR_BADENCLOSURE"; errstr = "URL is missing trailing \">\""; break; case LDAP_URL_ERR_BADURL: descr = "LDAP_URL_ERR_BADURL"; errstr = "Invalid URL"; break; case LDAP_URL_ERR_BADHOST: descr = "LDAP_URL_ERR_BADHOST"; errstr = "Host port is invalid"; break; case LDAP_URL_ERR_BADATTRS: descr = "LDAP_URL_ERR_BADATTRS"; errstr = "Invalid or missing attributes"; break; case LDAP_URL_ERR_BADFILTER: descr = "LDAP_URL_ERR_BADFILTER"; errstr = "Invalid or missing filter"; break; case LDAP_URL_ERR_BADEXTS: descr = "LDAP_URL_ERR_BADEXTS"; errstr = "Invalid or missing extensions"; break; # endif # endif } U_INTERNAL_DUMP("ldap_url_parse() failed - %.*s", u__snprintf(buffer, sizeof(buffer), U_CONSTANT_TO_PARAM("(%d, %s) - %s"), result, descr, errstr), buffer) # endif U_RETURN(false); } /* Get the URL scheme (either ldap or ldaps) */ #ifdef HAVE_LDAP_SSL_H if (strncmp(url, U_CONSTANT_TO_PARAM("ldaps:")) == 0) { /* Making encrypted connection */ isSecure = true; # ifdef HAS_NOVELL_LDAPSDK /** * Initialize the ssl library. The first parameter of ldapssl_client_init is a certificate file. However, when used * the file must be a DER encoded file. 0 is passed in for the certificate file because ldapssl_set_verify_mode will be used * to specify no server certificate verification. ldapssl_client_init is an application level initialization not a * thread level initilization and should be done once */ result = U_SYSCALL(ldapssl_client_init, "%p,%p", 0, /* DER encoded cert file */ 0); /* reserved, use 0 */ if (result != LDAP_SUCCESS) U_RETURN(false); /** * Configure the LDAP SSL library to not verify the server certificate. The default is LDAPSSL_VERIFY_SERVER which validates all servers * against the trusted certificates normally passed in during ldapssl_client_init or ldapssl_add_trusted_cert. * * WARNING: Setting the verify mode to LDAPSSL_VERIFY_NONE turns off server certificate verification. This means all servers are * considered trusted. This should be used only in controlled environments where encrypted communication between servers and * clients is desired but server verification is not necessary */ result = U_SYSCALL(ldapssl_set_verify_mode, "%d", LDAPSSL_VERIFY_NONE); if (result != LDAP_SUCCESS) { U_SYSCALL_NO_PARAM(ldapssl_client_deinit); U_RETURN(false); } # endif /* create a LDAP session handle that is enabled for ssl connection */ ld = (LDAP*) U_SYSCALL(ldapssl_init, "%S,%d,%d", (char*)ludpp->lud_host, /* host name */ (ludpp->lud_port ? ludpp->lud_port : LDAPS_PORT), /* port number */ 1); /* 0 - clear text, 1 - enable for ssl */ if (ld == 0) { # ifdef HAS_NOVELL_LDAPSDK U_SYSCALL_NO_PARAM(ldapssl_client_deinit); # endif U_RETURN(false); } # if defined(_MSWINDOWS_) && defined(HAVE_WINLDAP_H) (void) U_SYSCALL(ldap_set_option, "%p,%d,%d", ld, LDAP_OPT_SSL, LDAP_OPT_ON); # endif } else #endif { /* Making clear text connection */ if (init(ludpp->lud_host, ludpp->lud_port) == false) U_RETURN(false); } U_RETURN(true); } void ULDAP::get(ULDAPEntry& e) { U_TRACE(1, "ULDAP::get(%p)", &e) U_CHECK_MEMORY U_INTERNAL_ASSERT_POINTER(ld) U_INTERNAL_ASSERT_POINTER(searchResult) // Go through the search results by checking entries int i = 0, j; char** values; char* attribute; LDAPMessage* entry; BerElement* ber = 0; char* _attribute; struct berval** bvs = 0; for (entry = ldap_first_entry(ld, searchResult); entry; entry = ldap_next_entry( ld, entry), ++i) { e.dn[i] = ldap_get_dn(ld, entry); U_INTERNAL_DUMP("dn[%d]: %S", i, e.dn[i]) for (attribute = ldap_first_attribute(ld, entry, &ber); attribute; attribute = ldap_next_attribute( ld, entry, ber)) { values = ldap_get_values(ld, entry, attribute); /* Get values */ U_INTERNAL_DUMP("values = %p attribute = %S", values, attribute) if (values) { e.set(attribute, values, i); ldap_value_free(values); } else { for (j = 0; j < e.n_attr; ++j) { // be prepared to the 'attr;binary' versions of 'attr' _attribute = (char*)e.attr_name[j]; U_INTERNAL_DUMP("e.attr_name[%d] = %S", j, _attribute) if (strncmp(attribute, _attribute, u__strlen(_attribute, __PRETTY_FUNCTION__)) == 0) { bvs = ldap_get_values_len(ld, entry, attribute); if (bvs) { e.set(_attribute, bvs[0]->bv_val, bvs[0]->bv_len, i); ldap_value_free_len(bvs); break; } } } } ldap_memfree(attribute); } ber_free(ber, 0); } } // DEBUG #if defined(U_STDCPP_ENABLE) && defined(DEBUG) const char* ULDAPEntry::dump(bool reset) const { *UObjectIO::os << "dn " << (void*)dn << '\n' << "n_attr " << n_attr << '\n' << "n_entry " << n_entry << '\n' << "attr_val " << (void*)attr_val << '\n' << "attr_name " << (void*)attr_name; if (reset) { UObjectIO::output(); return UObjectIO::buffer_output; } return 0; } const char* ULDAP::dump(bool reset) const { *UObjectIO::os << "ld " << (void*)ld << '\n' << "ludpp " << (void*)ludpp << '\n' << "result " << result << '\n' << "isSecure " << isSecure << '\n' << "pTimeOut " << (void*)pTimeOut << '\n' << "searchResult " << (void*)searchResult; if (reset) { UObjectIO::output(); return UObjectIO::buffer_output; } return 0; } #endif
30.530387
161
0.497647
liftchampion
a25812c405b0455b36c0084c8766f1fffafe2b9d
6,616
cpp
C++
src/Node.cpp
caitp/TimedText
7fa0724b3ba99539d17cd0c8be59922676f7114c
[ "Unlicense" ]
2
2017-08-01T11:17:43.000Z
2022-03-19T21:26:45.000Z
src/Node.cpp
caitp/TimedText
7fa0724b3ba99539d17cd0c8be59922676f7114c
[ "Unlicense" ]
null
null
null
src/Node.cpp
caitp/TimedText
7fa0724b3ba99539d17cd0c8be59922676f7114c
[ "Unlicense" ]
null
null
null
// // Copyright (c) 2013 Caitlin Potter and Contributors // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // #include "NodeData.h" namespace TimedText { class EmptyNodeData : public NodeData { public: EmptyNodeData() : NodeData(EmptyNode,NullNode) {} } emptyNode; Node::Node() : d(&emptyNode) { d->ref.ref(); } static bool isInternalNode(NodeElementType type) { if(type > FirstNodeElementType && type < LastNodeElementType) { // There are currently only two leaf nodes... if(type == TextNode || type == TimestampNode) return false; return true; } return false; } static NodeData *internalNodeData(NodeElementType type) { if(isInternalNode(type)) { if(type == InternalTextNode) return new InternalNodeData(InternalTextNode); if(type == VoiceNode) return new VoiceNodeData(); if(type == LangNode) return new LangNodeData(); else return new ElementNodeData(type); } return 0; } static NodeData *leafNodeData(NodeElementType type) { if(type == TextNode) return new TextNodeData(); if(type == TimestampNode) return new TimestampNodeData(); return 0; } static NodeData *createNodeData(NodeType type, NodeElementType elem) { NodeData *d = 0; if(type == InternalNode && (d = internalNodeData(elem))) return d; if(type == LeafNode && (d = leafNodeData(elem))) return d; d = &emptyNode; d->ref.ref(); return d; } static NodeData *createNodeData(NodeElementType type) { NodeData *d = 0; if((d = internalNodeData(type))) return d; if((d = leafNodeData(type))) return d; d = &emptyNode; d->ref.ref(); return d; } Node::Node(NodeType type, NodeElementType elementType) : d(createNodeData(type,elementType)) { } Node::Node(NodeElementType type) : d(createNodeData(type)) { } Node::Node(const Node &other) : d(other.d) { d->ref.ref(); } Node::~Node() { if(!d->ref.deref()) delete d; } Node & Node::operator=(const Node &other) { other.d->ref.ref(); if(!d->ref.deref()) delete d; d = other.d; return *this; } NodeType Node::type() const { return d->type; } NodeElementType Node::elementType() const { return d->element; } Timestamp Node::timestamp() const { return d->timestamp(); } String Node::voice() const { return d->voice(); } String Node::text() const { return d->text(); } String Node::lang() const { return d->lang(); } List<String> Node::applicableClasses() const { return d->applicableClasses(); } bool Node::setTimestamp(const Timestamp &ts) { return d->setTimestamp(ts); } bool Node::setVoice(const String &voice) { return d->setVoice(voice); } bool Node::setText(const String &text) { return d->setText(text); } bool Node::setLang(const String &lang) { return d->setLang(lang); } bool Node::setApplicableClasses(const List<String> &classes) { return d->setApplicableClasses(classes); } const List<Node> & Node::children() const { return d->children(); } bool Node::push(const Node &node) { return d->push(node); } bool Node::pop(Node &result) { return d->pop(result); } bool Node::unshift(const Node &node) { return d->unshift(node); } bool Node::shift(Node &result) { return d->shift(result); } bool Node::insert(int i, const Node &node) { return d->insert(i, node); } bool Node::take(int i, Node &result) { return d->take(i, result); } bool Node::itemAt(int i, Node &result) { return d->itemAt(i, result); } Node::iterator Node::begin() { return d->begin(); } Node::iterator Node::end() { return d->end(); } Node::const_iterator Node::begin() const { const NodeData *x = d; return x->begin(); } Node::const_iterator Node::end() const { const NodeData *x = d; return x->end(); } int Node::childCount() const { return d->childCount(); } struct VisitState { public: inline VisitState() : i(0) {} inline VisitState(const VisitState &v) : n(v.n), i(v.i) {} inline VisitState(const Node &node) : n(node), i(0) {} inline VisitState(const Node &node, int pos) : n(node), i(pos) {} inline bool hasChildren() const { return n.childCount() > 0; } inline bool isLeaf() const { return n.type() == LeafNode; } inline bool isInternal() const { return n.type() == InternalNode; } inline bool isInternalText() const { return n.element() == InternalTextNode; } inline bool isEmpty() const { return n.type() == EmptyNode; } inline bool next(VisitState &result) { Node tmp; if(n.itemAt(i++, tmp)) { result = VisitState(tmp); return true; } return false; } operator Node &() { return n; } operator const Node &() const { return n; } Node n; int i; }; void Node::visit(NodeVisitor &visitor) { List<VisitState> stack; stack.push(*this); VisitState *top; while(stack.lastPtr(top)) { VisitState it; if(top->next(it)) { // Don't visit empty nodes. if(it.isEmpty()) continue; // Visit the item before descending visitor.visit(it); // We might need to descend, if it's if(it.isInternal()) { if(it.hasChildren() && (it.isInternalText() || visitor.enter(it))) stack.push(it); } } else { // Notify visitor that we are leaving a branch of the tree if(!top->isInternalText()) visitor.leave(*top); stack.pop(it); } } } } // TimedText
19.011494
74
0.667322
caitp
a25d5c53b29e80e096b16da7437b5840896c5bae
2,684
cpp
C++
examples/file_loader/file_loader.cpp
torbjoernk/CTML
0eb16c35c591f990db32d41c58bce71d41817b8c
[ "MIT" ]
1
2018-08-07T15:07:26.000Z
2018-08-07T15:07:26.000Z
examples/file_loader/file_loader.cpp
torbjoernk/CTML
0eb16c35c591f990db32d41c58bce71d41817b8c
[ "MIT" ]
null
null
null
examples/file_loader/file_loader.cpp
torbjoernk/CTML
0eb16c35c591f990db32d41c58bce71d41817b8c
[ "MIT" ]
null
null
null
#include "CTML.h" #include "dirent.h" bool add_files_to_doc(std::string folderPath, CTML::Node* containerNode) { DIR *directory = NULL; // open the folder path directory = opendir(folderPath.c_str()); // return false if it doesn't exist if (directory == NULL) { std::cout << "Directory not found!\n"; return false; } // the directory entry struct struct dirent *ent; while ((ent = readdir(directory)) != NULL) { // if the current entry is a file if (ent->d_type == DT_REG) { // the file name as a string std::string fileName = std::string(ent->d_name); // the content of the document std::string docContent; std::ifstream textFile(folderPath + fileName); std::string line; // loop through the lines in the file while (std::getline(textFile, line)) { // append the line to the doc content docContent += line + '\n'; } // hacky way of removing the last new line in the doc content int lastNewLine = docContent.find_last_of('\n'); if (lastNewLine != std::string::npos) docContent.erase(docContent.find_last_of('\n')); // remove the extention from the file name fileName = fileName.substr(0, fileName.find('.')); // the container for this file CTML::Node fileContainer("div.post"); CTML::Node fileTitle("h1", fileName); CTML::Node fileContent("p", docContent); // append the title and content to the file container fileContainer.AppendChild(fileTitle).AppendChild(fileContent); // append the file container to the root container containerNode->AppendChild(fileContainer); } } // if we can't close the directory for some reason if (closedir(directory) < 0) { std::cout << "Could not close the stream to the directory!\n"; return false; } // finished return true; } int main() { CTML::Document doc; doc.AddNodeToHead(CTML::Node("title", "CTML Test")); // force utf-8 encoding doc.AddNodeToHead(CTML::Node("meta").SetAttribute("charset", "UTF-8")); CTML::Node containerNode("div.container"); std::string dir; // input the directory to look for files std::cout << "Input the directory name with the files: "; std::cin >> dir; bool result = add_files_to_doc(dir, &containerNode); // add the files container to the body doc.AddNodeToBody(containerNode); bool fileWriteResult = false; // if finding files was successful, try to write to a file if (result) fileWriteResult = doc.WriteToFile("index.html", CTML::MULTILINE_BR); // if we wrote to the file successfully if (fileWriteResult) std::cout << "All files in \"" + dir + "\" written to index.html successfully!\n"; else std::cout << "Writing to index.html was unsuccessful!\n"; return fileWriteResult; }
33.55
84
0.69076
torbjoernk
a25dfa61654baf386d71959105626bfe2049567e
57
cpp
C++
algorithms/des/info.cpp
playahammer/crypto
27db00a5e1c58bd78dae34164fad4c719ff7f2cf
[ "MIT" ]
null
null
null
algorithms/des/info.cpp
playahammer/crypto
27db00a5e1c58bd78dae34164fad4c719ff7f2cf
[ "MIT" ]
null
null
null
algorithms/des/info.cpp
playahammer/crypto
27db00a5e1c58bd78dae34164fad4c719ff7f2cf
[ "MIT" ]
1
2019-04-26T02:23:44.000Z
2019-04-26T02:23:44.000Z
#include "log.h" Info::Info() { } QString Info::Info
5.7
18
0.596491
playahammer