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
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
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
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
36f6f960413fd520167a2834a398d3f7fc80fb31
2,451
cpp
C++
testrunner/main.cpp
ducaddepar/ProgrammingContest
4c47cada50ed23bd841cfea06a377a4129d4d88f
[ "MIT" ]
39
2018-08-26T05:53:19.000Z
2021-12-11T07:47:24.000Z
testrunner/main.cpp
ducaddepar/ProgrammingContest
4c47cada50ed23bd841cfea06a377a4129d4d88f
[ "MIT" ]
1
2018-06-21T00:40:41.000Z
2018-06-21T00:40:46.000Z
testrunner/main.cpp
ducaddepar/ProgrammingContest
4c47cada50ed23bd841cfea06a377a4129d4d88f
[ "MIT" ]
8
2018-08-27T00:34:23.000Z
2020-09-27T12:51:22.000Z
#include "/Users/duc/github/ContestNeko/CodeForces/TaskD.cpp" #include <iostream> #include <fstream> #include <sstream> #include <string> #include <vector> #include <cctype> #include <ctime> namespace jhelper { struct Test { std::string input; std::string output; bool active; bool has_output; }; bool check(std::string expected, std::string actual) { while(!expected.empty() && isspace(*--expected.end())) expected.erase(--expected.end()); while(!actual.empty() && isspace(*--actual.end())) actual.erase(--actual.end()); return expected == actual; } } // namespace jhelper int main() { std::vector<jhelper::Test> tests = { {"5\n11 2 3 5 7\n4\n11 7 3 7\n", "3\n", true, true},{"2\n1 2\n1\n100\n", "-1\n", true, true},{"3\n1 2 3\n3\n1 2 3\n", "3\n", true, true},{"5\n1 2 3 4 5\n3 \n5 7 3", "", true, true}, }; bool allOK = true; int testID = 0; std::cout << std::fixed; double maxTime = 0.0; for(const jhelper::Test& test: tests ) { std::cout << "Test #" << ++testID << std::endl; std::cout << "Input: \n" << test.input << std::endl; if (test.has_output) { std::cout << "Expected output: \n" << test.output << std::endl; } else { std::cout << "Expected output: \n" << "N/A" << std::endl; } if (test.active) { std::stringstream in(test.input); std::ostringstream out; std::clock_t start = std::clock(); TaskD solver; solver.solve(in, out); std::clock_t finish = std::clock(); double currentTime = double(finish - start) / CLOCKS_PER_SEC; maxTime = std::max(currentTime, maxTime); std::cout << "Actual output: \n" << out.str() << std::endl; if (test.has_output) { bool result = jhelper::check(test.output, out.str()); allOK = allOK && result; std::cout << "Result: " << (result ? "OK" : "Wrong answer") << std::endl; } std::cout << "Time: " << currentTime << std::endl; } else { std::cout << "SKIPPED\n"; } std::cout << std::endl; } if(allOK) { std::cout << "All OK" << std::endl; } else { std::cout << "Some cases failed" << std::endl; } std::cout << "Maximal time: " << maxTime << "s." << std::endl; return 0; }
31.025316
189
0.518972
ducaddepar
36f82dba5adb44908ab284b453ade94d0325c5af
25,405
cpp
C++
tmc3/TMC3.cpp
jokerld/TMC13v5-Cluster
aa8d8d8be31f1723f8909abe73673fc160d2f837
[ "BSD-3-Clause" ]
null
null
null
tmc3/TMC3.cpp
jokerld/TMC13v5-Cluster
aa8d8d8be31f1723f8909abe73673fc160d2f837
[ "BSD-3-Clause" ]
null
null
null
tmc3/TMC3.cpp
jokerld/TMC13v5-Cluster
aa8d8d8be31f1723f8909abe73673fc160d2f837
[ "BSD-3-Clause" ]
null
null
null
/* The copyright in this software is being made available under the BSD * Licence, included below. This software may be subject to other third * party and contributor rights, including patent rights, and no such * rights are granted under this licence. * * Copyright (c) 2017-2018, ISO/IEC * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * * Neither the name of the ISO/IEC 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 "TMC3.h" #include <memory> #include "PCCTMC3Encoder.h" #include "PCCTMC3Decoder.h" #include "constants.h" #include "program_options_lite.h" #include "io_tlv.h" #include "version.h" using namespace std; using namespace pcc; //============================================================================ struct Parameters { bool isDecoder; // command line parsing should adjust dist2 values according to PQS bool positionQuantizationScaleAdjustsDist2; // output mode for ply writing (binary or ascii) bool outputBinaryPly; // when true, configure the encoder as if no attributes are specified bool disableAttributeCoding; std::string uncompressedDataPath; std::string compressedStreamPath; std::string reconstructedDataPath; // Filename for saving pre inverse scaled point cloud. std::string preInvScalePath; pcc::EncoderParams encoder; pcc::DecoderParams decoder; // todo(df): this should be per-attribute ColorTransform colorTransform; // todo(df): this should be per-attribute int reflectanceScale; }; //============================================================================ int main(int argc, char* argv[]) { cout << "MPEG PCC tmc3 version " << ::pcc::version << endl; Parameters params; if (!ParseParameters(argc, argv, params)) { return -1; } // Timers to count elapsed wall/user time pcc::chrono::Stopwatch<std::chrono::steady_clock> clock_wall; pcc::chrono::Stopwatch<pcc::chrono::utime_inc_children_clock> clock_user; clock_wall.start(); int ret = 0; if (params.isDecoder) { ret = Decompress(params, clock_user); } else { ret = Compress(params, clock_user); } clock_wall.stop(); using namespace std::chrono; auto total_wall = duration_cast<milliseconds>(clock_wall.count()).count(); auto total_user = duration_cast<milliseconds>(clock_user.count()).count(); std::cout << "Processing time (wall): " << total_wall / 1000.0 << " s\n"; std::cout << "Processing time (user): " << total_user / 1000.0 << " s\n"; return ret; } //--------------------------------------------------------------------------- // :: Command line / config parsing helpers template<typename T> static std::istream& readUInt(std::istream& in, T& val) { unsigned int tmp; in >> tmp; val = T(tmp); return in; } static std::istream& operator>>(std::istream& in, ColorTransform& val) { return readUInt(in, val); } namespace pcc { static std::istream& operator>>(std::istream& in, AttributeEncoding& val) { return readUInt(in, val); } } // namespace pcc namespace pcc { static std::istream& operator>>(std::istream& in, PartitionMethod& val) { return readUInt(in, val); } } // namespace pcc namespace pcc { static std::ostream& operator<<(std::ostream& out, const AttributeEncoding& val) { switch (val) { case AttributeEncoding::kPredictingTransform: out << "0 (Pred)"; break; case AttributeEncoding::kRAHTransform: out << "1 (RAHT)"; break; case AttributeEncoding::kLiftingTransform: out << "2 (Lift)"; break; } return out; } } // namespace pcc namespace pcc { static std::ostream& operator<<(std::ostream& out, const PartitionMethod& val) { switch (val) { case PartitionMethod::kNone: out << "0 (None)"; break; case PartitionMethod::kUniformGeom: out << "0 (UniformGeom)"; break; case PartitionMethod::kOctreeUniform: out << "0 (UniformOctree)"; break; default: out << int(val) << " (Unknown)"; break; } return out; } } // namespace pcc namespace df { namespace program_options_lite { template<typename T> struct option_detail<pcc::PCCVector3<T>> { static constexpr bool is_container = true; static constexpr bool is_fixed_size = true; typedef T* output_iterator; static void clear(pcc::PCCVector3<T>& container){}; static output_iterator make_output_iterator(pcc::PCCVector3<T>& container) { return &container[0]; } }; } // namespace program_options_lite } // namespace df //--------------------------------------------------------------------------- // :: Command line / config parsing bool ParseParameters(int argc, char* argv[], Parameters& params) { namespace po = df::program_options_lite; struct { AttributeDescription desc; AttributeParameterSet aps; } params_attr; bool print_help = false; // a helper to set the attribute std::function<po::OptionFunc::Func> attribute_setter = [&](po::Options&, const std::string& name, po::ErrorReporter) { // copy the current state of parsed attribute parameters // // NB: this does not cause the default values of attr to be restored // for the next attribute block. A side-effect of this is that the // following is allowed leading to attribute foo having both X=1 and // Y=2: // "--attr.X=1 --attribute foo --attr.Y=2 --attribute foo" // // NB: insert returns any existing element const auto& it = params.encoder.attributeIdxMap.insert( {name, int(params.encoder.attributeIdxMap.size())}); if (it.second) { params.encoder.sps.attributeSets.push_back(params_attr.desc); params.encoder.aps.push_back(params_attr.aps); return; } // update existing entry params.encoder.sps.attributeSets[it.first->second] = params_attr.desc; params.encoder.aps[it.first->second] = params_attr.aps; }; /* clang-format off */ // The definition of the program/config options, along with default values. // // NB: when updating the following tables: // (a) please keep to 80-columns for easier reading at a glance, // (b) do not vertically align values -- it breaks quickly // po::Options opts; opts.addOptions() ("help", print_help, false, "this help text") ("config,c", po::parseConfigFile, "configuration file name") (po::Section("General")) ("mode", params.isDecoder, false, "The encoding/decoding mode:\n" " 0: encode\n" " 1: decode") // i/o parameters ("reconstructedDataPath", params.reconstructedDataPath, {}, "The ouput reconstructed pointcloud file path (decoder only)") ("uncompressedDataPath", params.uncompressedDataPath, {}, "The input pointcloud file path") ("compressedStreamPath", params.compressedStreamPath, {}, "The compressed bitstream path (encoder=output, decoder=input)") ("postRecolorPath", params.encoder.postRecolorPath, {}, "Recolored pointcloud file path (encoder only)") ("preInvScalePath", params.preInvScalePath, {}, "Pre inverse scaled pointcloud file path (decoder only)") ("outputBinaryPly", params.outputBinaryPly, false, "Output ply files using binary (or otherwise ascii) format") // general // todo(df): this should be per-attribute ("colorTransform", params.colorTransform, COLOR_TRANSFORM_RGB_TO_YCBCR, "The colour transform to be applied:\n" " 0: none\n" " 1: RGB to YCbCr (Rec.709)") // todo(df): this should be per-attribute ("hack.reflectanceScale", params.reflectanceScale, 1, "scale factor to be applied to reflectance " "pre encoding / post reconstruction") // NB: if adding decoder options, uncomment the Decoder section marker // (po::Section("Decoder")) (po::Section("Encoder")) ("seq_bounding_box_xyz0", params.encoder.sps.seq_bounding_box_xyz0, {0}, "seq_bounding_box_xyz0. NB: seq_bounding_box_whd must be set for this " "parameter to have an effect") ("seq_bounding_box_whd", params.encoder.sps.seq_bounding_box_whd, {0}, "seq_bounding_box_whd") ("positionQuantizationScale", params.encoder.sps.seq_source_geom_scale_factor, 1.f, "Scale factor to be applied to point positions during quantization process") ("positionQuantizationScaleAdjustsDist2", params.positionQuantizationScaleAdjustsDist2, false, "Scale dist2 values by squared positionQuantizationScale") ("mergeDuplicatedPoints", params.encoder.gps.geom_unique_points_flag, true, "Enables removal of duplicated points") ("partitionMethod", params.encoder.partitionMethod, PartitionMethod::kNone, "Method used to partition input point cloud into slices/tiles:\n" " 0: none\n" " 1: none (deprecated)\n" " 2: n Uniform-Geometry partition bins along the longest edge\n" " 3: Uniform Geometry partition at n octree depth") ("partitionNumUniformGeom", params.encoder.partitionNumUniformGeom, 0, "Number of bins for partitionMethod=2:\n" " 0: slice partition with adaptive-defined bins\n" " >=1: slice partition with user-defined bins\n") ("partitionOctreeDepth", params.encoder.partitionOctreeDepth, 2, "Depth of octree partition for partitionMethod=3") ("disableAttributeCoding", params.disableAttributeCoding, false, "Ignore attribute coding configuration") (po::Section("Geometry")) // tools ("bitwiseOccupancyCoding", params.encoder.gps.bitwise_occupancy_coding_flag, true, "Selects between bitwise and bytewise occupancy coding:\n" " 0: bytewise\n" " 1: bitwise") ("neighbourContextRestriction", params.encoder.gps.neighbour_context_restriction_flag, false, "Limit geometry octree occupancy contextualisation to sibling nodes") ("neighbourAvailBoundaryLog2", params.encoder.gps.neighbour_avail_boundary_log2, 0, "Defines the avaliability volume for neighbour occupancy lookups." " 0: unconstrained") ("inferredDirectCodingMode", params.encoder.gps.inferred_direct_coding_mode_enabled_flag, true, "Permits early termination of the geometry octree for isolated points") ("intra_pred_max_node_size_log2", params.encoder.gps.intra_pred_max_node_size_log2, 0, "octree nodesizes eligible for occupancy intra prediction") ("ctxOccupancyReductionFactor", params.encoder.gps.geom_occupancy_ctx_reduction_factor, 3, "Adjusts the number of contexts used in occupancy coding") ("trisoup_node_size_log2", params.encoder.gps.trisoup_node_size_log2, 0, "Size of nodes for surface triangulation.\n" " 0: disabled\n") (po::Section("Attributes")) // attribute processing // NB: Attribute options are special in the way they are applied (see above) ("attribute", attribute_setter, "Encode the given attribute (NB, must appear after the" "following attribute parameters)") ("bitdepth", params_attr.desc.attr_bitdepth, 8, "Attribute bitdepth") ("transformType", params_attr.aps.attr_encoding, AttributeEncoding::kPredictingTransform, "Coding method to use for attribute:\n" " 0: Hierarchical neighbourhood prediction\n" " 1: Region Adaptive Hierarchical Transform (RAHT)\n" " 2: Hierarichical neighbourhood prediction as lifting transform") ("rahtLeafDecimationDepth", params_attr.aps.raht_binary_level_threshold, 3, "Sets coefficients to zero in the bottom n levels of RAHT tree. " "Used for chroma-subsampling in attribute=color only.") ("rahtQuantizationStep", params_attr.aps.quant_step_size_luma, 0, "deprecated -- use quantizationStepsLuma") ("rahtDepth", params_attr.aps.raht_depth, 21, "Number of bits for morton representation of an RAHT co-ordinate" "component") ("numberOfNearestNeighborsInPrediction", params_attr.aps.num_pred_nearest_neighbours, 3, "Attribute's maximum number of nearest neighbors to be used for prediction") ("adaptivePredictionThreshold", params_attr.aps.adaptive_prediction_threshold, -1, "Neighbouring attribute value difference that enables choice of " "single|multi predictors. Applies to transformType=2 only.\n" " -1: auto = 2**(bitdepth-2)") ("attributeSearchRange", params_attr.aps.search_range, 128, "Range for nearest neighbor search") ("lodBinaryTree", params_attr.aps.lod_binary_tree_enabled_flag, false, "Controls LoD generation method:\n" " 0: distance based subsampling\n" " 1: binary tree") ("max_num_direct_predictors", params_attr.aps.max_num_direct_predictors, 3, "Maximum number of nearest neighbour candidates used in direct" "attribute prediction") ("levelOfDetailCount", params_attr.aps.num_detail_levels, 1, "Attribute's number of levels of detail") ("quantizationStepLuma", params_attr.aps.quant_step_size_luma, 0, "Attribute's luma quantization step size") ("quantizationStepChroma", params_attr.aps.quant_step_size_chroma, 0, "Attribute's chroma quantization step size") ("dist2", params_attr.aps.dist2, {}, "Attribute's list of squared distances, or initial value for automatic" "derivation") ; /* clang-format on */ po::setDefaults(opts); po::ErrorReporter err; const list<const char*>& argv_unhandled = po::scanArgv(opts, argc, (const char**)argv, err); for (const auto arg : argv_unhandled) { err.warn() << "Unhandled argument ignored: " << arg << "\n"; } if (argc == 1 || print_help) { po::doHelp(std::cout, opts, 78); return false; } // Certain coding modes are not available when trisoup is enabled. // Disable them, and warn if set (they may be set as defaults). if (params.encoder.gps.trisoup_node_size_log2 > 0) { if (!params.encoder.gps.geom_unique_points_flag) err.warn() << "TriSoup geometry does not preserve duplicated points\n"; if (params.encoder.gps.inferred_direct_coding_mode_enabled_flag) err.warn() << "TriSoup geometry is incompatable with IDCM\n"; params.encoder.gps.geom_unique_points_flag = true; params.encoder.gps.inferred_direct_coding_mode_enabled_flag = false; } // support disabling attribute coding (simplifies configuration) if (params.disableAttributeCoding) { params.encoder.attributeIdxMap.clear(); params.encoder.sps.attributeSets.clear(); params.encoder.aps.clear(); } // fixup any per-attribute settings for (const auto& it : params.encoder.attributeIdxMap) { auto& attr_sps = params.encoder.sps.attributeSets[it.second]; auto& attr_aps = params.encoder.aps[it.second]; // Avoid wasting bits signalling chroma quant step size for reflectance if (it.first == "reflectance") { attr_aps.quant_step_size_chroma = 0; } bool isLifting = attr_aps.attr_encoding == AttributeEncoding::kPredictingTransform || attr_aps.attr_encoding == AttributeEncoding::kLiftingTransform; // derive the dist2 values based on an initial value if (isLifting) { if (attr_aps.dist2.size() > attr_aps.num_detail_levels) { attr_aps.dist2.resize(attr_aps.num_detail_levels); } else if ( attr_aps.dist2.size() < attr_aps.num_detail_levels && !attr_aps.dist2.empty()) { if (attr_aps.dist2.size() < attr_aps.num_detail_levels) { attr_aps.dist2.resize(attr_aps.num_detail_levels); const double distRatio = 4.0; uint64_t d2 = attr_aps.dist2[0]; for (int i = 0; i < attr_aps.num_detail_levels; ++i) { attr_aps.dist2[i] = d2; d2 = uint64_t(std::round(distRatio * d2)); } } } } // In order to simplify specification of dist2 values, which are // depending on the scale of the coded point cloud, the following // adjust the dist2 values according to PQS. The user need only // specify the unquantised PQS value. if (params.positionQuantizationScaleAdjustsDist2) { double pqs = params.encoder.sps.seq_source_geom_scale_factor; double pqs2 = pqs * pqs; for (auto& dist2 : attr_aps.dist2) dist2 = int64_t(std::round(pqs2 * dist2)); } // Set default threshold based on bitdepth if (attr_aps.adaptive_prediction_threshold == -1) { attr_aps.adaptive_prediction_threshold = 1 << (attr_sps.attr_bitdepth - 2); } if (attr_aps.attr_encoding == AttributeEncoding::kLiftingTransform) { attr_aps.adaptive_prediction_threshold = 0; } // For RAHT, ensure that the unused lod count = 0 (prevents mishaps) if (attr_aps.attr_encoding == AttributeEncoding::kRAHTransform) { attr_aps.num_detail_levels = 0; attr_aps.adaptive_prediction_threshold = 0; // todo(df): suggest chroma quant_step_size for raht attr_aps.quant_step_size_chroma = 0; } } // sanity checks if (params.encoder.gps.intra_pred_max_node_size_log2) if (!params.encoder.gps.neighbour_avail_boundary_log2) err.error() << "Geometry intra prediction requires finite" "neighbour_avail_boundary_log2\n"; for (const auto& it : params.encoder.attributeIdxMap) { const auto& attr_sps = params.encoder.sps.attributeSets[it.second]; const auto& attr_aps = params.encoder.aps[it.second]; bool isLifting = attr_aps.attr_encoding == AttributeEncoding::kPredictingTransform || attr_aps.attr_encoding == AttributeEncoding::kLiftingTransform; if (it.first == "color") { // todo(??): permit relaxing of the following constraint if (attr_sps.attr_bitdepth > 8) err.error() << it.first << ".bitdepth must be less than 9\n"; } if (it.first == "reflectance") { if (attr_sps.attr_bitdepth > 16) err.error() << it.first << ".bitdepth must be less than 17\n"; } if (isLifting) { int lod = attr_aps.num_detail_levels; if (lod > 255 || lod < 0) { err.error() << it.first << ".levelOfDetailCount must be in the range [0,255]\n"; } if (attr_aps.dist2.size() != lod) { err.error() << it.first << ".dist2 does not have " << lod << " entries\n"; } if (attr_aps.adaptive_prediction_threshold < 0) { err.error() << it.first << ".adaptivePredictionThreshold must be positive\n"; } if ( attr_aps.num_pred_nearest_neighbours > kAttributePredictionMaxNeighbourCount) { err.error() << it.first << ".numberOfNearestNeighborsInPrediction must be <= " << kAttributePredictionMaxNeighbourCount << "\n"; } } } // check required arguments are specified if (!params.isDecoder && params.uncompressedDataPath.empty()) err.error() << "uncompressedDataPath not set\n"; if (params.isDecoder && params.reconstructedDataPath.empty()) err.error() << "reconstructedDataPath not set\n"; if (params.compressedStreamPath.empty()) err.error() << "compressedStreamPath not set\n"; // report the current configuration (only in the absence of errors so // that errors/warnings are more obvious and in the same place). if (err.is_errored) return false; // Dump the complete derived configuration cout << "+ Effective configuration parameters\n"; po::dumpCfg(cout, opts, "General", 4); if (params.isDecoder) { po::dumpCfg(cout, opts, "Decoder", 4); } else { po::dumpCfg(cout, opts, "Encoder", 4); po::dumpCfg(cout, opts, "Geometry", 4); for (const auto& it : params.encoder.attributeIdxMap) { // NB: when dumping the config, opts references params_attr params_attr.desc = params.encoder.sps.attributeSets[it.second]; params_attr.aps = params.encoder.aps[it.second]; cout << " " << it.first << "\n"; po::dumpCfg(cout, opts, "Attributes", 8); } } cout << endl; return true; } int Compress(Parameters& params, Stopwatch& clock) { PCCPointSet3 pointCloud; if ( !pointCloud.read(params.uncompressedDataPath) || pointCloud.getPointCount() == 0) { cout << "Error: can't open input file!" << endl; return -1; } // Sanitise the input point cloud // todo(df): remove the following with generic handling of properties bool codeColour = params.encoder.attributeIdxMap.count("color"); if (!codeColour) pointCloud.removeColors(); assert(codeColour == pointCloud.hasColors()); bool codeReflectance = params.encoder.attributeIdxMap.count("reflectance"); if (!codeReflectance) pointCloud.removeReflectances(); assert(codeReflectance == pointCloud.hasReflectances()); ofstream fout(params.compressedStreamPath, ios::binary); if (!fout.is_open()) { return -1; } clock.start(); if (params.colorTransform == COLOR_TRANSFORM_RGB_TO_YCBCR) { pointCloud.convertRGBToYUV(); } if (params.reflectanceScale > 1 && pointCloud.hasReflectances()) { const auto pointCount = pointCloud.getPointCount(); for (size_t i = 0; i < pointCount; ++i) { int val = pointCloud.getReflectance(i) / params.reflectanceScale; pointCloud.setReflectance(i, val); } } PCCTMC3Encoder3 encoder; // The reconstructed point cloud std::unique_ptr<PCCPointSet3> reconPointCloud; if (!params.reconstructedDataPath.empty()) { reconPointCloud.reset(new PCCPointSet3); } int ret = encoder.compress( pointCloud, &params.encoder, [&](const PayloadBuffer& buf) { writeTlv(buf, fout); }, reconPointCloud.get()); if (ret) { cout << "Error: can't compress point cloud!" << endl; return -1; } std::cout << "Total bitstream size " << fout.tellp() << " B" << std::endl; fout.close(); clock.stop(); if (!params.reconstructedDataPath.empty()) { if (params.colorTransform == COLOR_TRANSFORM_RGB_TO_YCBCR) { reconPointCloud->convertYUVToRGB(); } if (params.reflectanceScale > 1 && reconPointCloud->hasReflectances()) { const auto pointCount = reconPointCloud->getPointCount(); for (size_t i = 0; i < pointCount; ++i) { int val = reconPointCloud->getReflectance(i) * params.reflectanceScale; reconPointCloud->setReflectance(i, val); } } reconPointCloud->write( params.reconstructedDataPath, !params.outputBinaryPly); } return 0; } int Decompress(Parameters& params, Stopwatch& clock) { ifstream fin(params.compressedStreamPath, ios::binary); if (!fin.is_open()) { return -1; } clock.start(); PayloadBuffer buf; PCCTMC3Decoder3 decoder; while (true) { PayloadBuffer* buf_ptr = &buf; readTlv(fin, &buf); // at end of file (or other error), flush decoder if (!fin) buf_ptr = nullptr; int ret = decoder.decompress( params.decoder, buf_ptr, [&](const PCCPointSet3& decodedPointCloud) { PCCPointSet3 pointCloud(decodedPointCloud); if (params.colorTransform == COLOR_TRANSFORM_RGB_TO_YCBCR) { pointCloud.convertYUVToRGB(); } if (params.reflectanceScale > 1 && pointCloud.hasReflectances()) { const auto pointCount = pointCloud.getPointCount(); for (size_t i = 0; i < pointCount; ++i) { int val = pointCloud.getReflectance(i) * params.reflectanceScale; pointCloud.setReflectance(i, val); } } // Dump the decoded colour using the pre inverse scaled geometry if (!params.preInvScalePath.empty()) { pointCloud.write(params.preInvScalePath, !params.outputBinaryPly); } decoder.inverseQuantization(pointCloud); clock.stop(); if (!pointCloud.write( params.reconstructedDataPath, !params.outputBinaryPly)) { cout << "Error: can't open output file!" << endl; } clock.start(); }); if (ret) { cout << "Error: can't decompress point cloud!" << endl; return -1; } if (!buf_ptr) break; } fin.clear(); fin.seekg(0, ios_base::end); std::cout << "Total bitstream size " << fin.tellg() << " B" << std::endl; clock.stop(); return 0; }
31.83584
80
0.678331
jokerld
36fc1c809ad5a96ab02b25419f5d245897616720
241
cpp
C++
c02/2_8.cpp
brynhayder/accelerated-cpp
e26796486ba410db566c0f8acc392f32f20330a9
[ "MIT" ]
null
null
null
c02/2_8.cpp
brynhayder/accelerated-cpp
e26796486ba410db566c0f8acc392f32f20330a9
[ "MIT" ]
null
null
null
c02/2_8.cpp
brynhayder/accelerated-cpp
e26796486ba410db566c0f8acc392f32f20330a9
[ "MIT" ]
null
null
null
// Compute product of numbers in [1, 10) #include <iostream> int main(){ int sup = 10; int start = 1; int j = start; for (int i = 1; i != sup; i++){ j *= i; } std::cout << j << std::endl; return 0; }
17.214286
40
0.46888
brynhayder
36fcb56badb878b9545909bde5a5f58231e658df
1,004
cpp
C++
prime.cpp
Ki-Seki/codes-algorithm
8bb2204a700e489927276cec3506cd748cf8867f
[ "MIT" ]
null
null
null
prime.cpp
Ki-Seki/codes-algorithm
8bb2204a700e489927276cec3506cd748cf8867f
[ "MIT" ]
null
null
null
prime.cpp
Ki-Seki/codes-algorithm
8bb2204a700e489927276cec3506cd748cf8867f
[ "MIT" ]
null
null
null
/* * hint: * 素数相关的算法,包括: * 使用 sqrt 来优化的素数判断函数 * 使用平方技巧来优化的素数判断函数 * 求素数表:埃氏筛法,Eratosthenes 筛法 */ #include <iostream> #include <cmath> // 使用 sqrt 来优化的素数判断函数 // 需要 <cmath> bool is_prime(int n) { for (int i = 2; i <= (int) sqrt(n * 1.0); i++) if (n % i == 0) return false; return true; } // 使用平方技巧来优化的素数判断函数 // 缺点是若 n 较大,易产生溢出 bool is_prime_vice(int n) { for (int i = 2; i * i <= n; i++) if (n % i == 0) return false; return true; } // 求素数表:埃氏筛法,Eratosthenes 筛法 // 时间复杂度 O(nloglogn) #define MAXN 100 // 素数表大小 int prime[MAXN + 5], p_len = 0; bool not_prime[MAXN * 20] = {}; // 找到 [2, n] 范围内的素数,保存至 prime[] void find_prime(int n) { for (int i = 2; i <= n; i++) if (not_prime[i] == false) { prime[p_len++] = i; for (int j = i + i; j <= n; j += i) not_prime[j] = true; } } int main() { find_prime(MAXN); for (int i = 0; i < p_len; i++) printf(" %d", prime[i]); }
18.943396
50
0.506972
Ki-Seki
3c05633c545f47b9d3e23b1d3bc6f5a6bc1702e6
1,318
cpp
C++
src/cpp/DP/dp_minimus_path_sum.cpp
spurscoder/forTest
2ab069d6740f9d7636c6988a5a0bd3825518335d
[ "MIT" ]
null
null
null
src/cpp/DP/dp_minimus_path_sum.cpp
spurscoder/forTest
2ab069d6740f9d7636c6988a5a0bd3825518335d
[ "MIT" ]
1
2018-10-24T05:48:27.000Z
2018-10-24T05:52:14.000Z
src/cpp/DP/dp_minimus_path_sum.cpp
spurscoder/forTest
2ab069d6740f9d7636c6988a5a0bd3825518335d
[ "MIT" ]
null
null
null
/* Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right which minimizes the sum of all numbers along its path. Note: You can only move either down or right at any point in time. Example: Input: [ [1,3,1], [1,5,1], [4,2,1] ] Output: 7 Explanation: Because the path 1→3→1→1→1 minimizes the sum. */ #include <iostream> #include <vector> using namespace std; class Solution { public: int minPathSum(vector<vector<int>> & grid) { int m = grid.size(), n = grid[0].size(); vector<vector<int>> dp(m, vector<int>(n, 0)); dp[0][0] = grid[0][0]; for (int j = 1; j < n; ++j) dp[0][j] = grid[0][j] + dp[0][j-1]; for (int i = 1; i < m; ++i) { dp[i][0] = grid[i][0] + dp[i-1][0]; for (int j = 1; j < n; ++j) { dp[i][j] = min(dp[i-1][j], dp[i][j-1]) + grid[i][j]; } } return dp[m-1][n-1]; } }; int main() { Solution sol = Solution(); freopen("data.in", "r", stdin); int m, n, t; cin >> m >> n; vector<vector<int>> grid(m, vector<int>(n, 0)); for (int i = 0; i < m; ++i) for (int j = 0; j < n; ++j) { cin >> t; grid[i][j] = t; } cout << sol.minPathSum(grid) << endl; return 0; }
23.535714
149
0.492413
spurscoder
3c077ea42a66e002809b23be1a8b2645f6657c2b
2,980
cpp
C++
SierraChart2/Time.cpp
AndrewAMD/SierraChartZorroPlugin
43d3645e17a8349fb6d3dffa541c91d0a51222d7
[ "MIT" ]
26
2018-11-09T07:43:49.000Z
2021-09-10T06:15:47.000Z
SierraChart2/Time.cpp
AndrewAMD/SierraChartZorroPlugin
43d3645e17a8349fb6d3dffa541c91d0a51222d7
[ "MIT" ]
1
2021-02-02T11:50:42.000Z
2021-02-02T13:58:08.000Z
SierraChart2/Time.cpp
AndrewAMD/SierraChartZorroPlugin
43d3645e17a8349fb6d3dffa541c91d0a51222d7
[ "MIT" ]
10
2019-01-03T08:38:30.000Z
2022-03-30T02:26:57.000Z
#include "pch.h" #include "framework.h" #include <Windows.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> #include "Time.h" #include "StrBufs.h" #include "client.h" #include "banned.h" //must include last int g_RequestRateLimit_ms = 100; namespace cro = std::chrono; cro::steady_clock::time_point g_NextRequestTp = cro::steady_clock::now(); bool can_request_now() { return cro::steady_clock::now() > g_NextRequestTp; } bool delay_request(bool double_delay) { auto limit_ms = g_RequestRateLimit_ms; if (double_delay) limit_ms *= 2; while (!can_request_now()) { cl_drain(); if (!refresh()) return false; cl_loiter(); } g_NextRequestTp = cro::steady_clock::now() + cro::milliseconds(limit_ms); return true; } DATE vEpochSeconds_to_date(double vEpochSeconds){ return vEpochSeconds / (24ll * 60ll * 60ll) + 25569ll; // 25569. = DATE(1.1.1970 00:00) } DATE llEpochMicroseconds_to_date(long long llEpochMicroseconds) { return ((double)llEpochMicroseconds) / (1000000ll * (24ll * 60ll * 60ll)) + 25569ll; // 25569. = DATE(1.1.1970 00:00) } double date_to_vEpochSeconds(DATE date){ return (double)((date - 25569ll) * (24ll * 60ll * 60ll)); } void set_time_zone(const char* sTZ) { _putenv_s("TZ", sTZ); _tzset(); return; } int epochmilli_str_to_yyyymmdd(const char* emilli) { __time32_t t32 = (__time32_t)(strtod(emilli, NULL) / 1000); if (!t32) return 0; // parse failure struct tm tm1 = { 0 }; set_time_zone("UTC0"); if (_localtime32_s(&tm1, &t32)) { return 0;// error } int y = tm1.tm_year + 1900; int m = tm1.tm_mon + 1; int d = tm1.tm_mday; return y * 10000 + m * 100 + d; } int get_todays_date_yyyymmdd() { __time32_t t32 = 0; struct tm tm1 = { 0 }; _time32(&t32); set_time_zone("UTC0"); _localtime32_s(&tm1, &t32); int y = tm1.tm_year + 1900; int m = tm1.tm_mon + 1; int d = tm1.tm_mday; return y * 10000 + m * 100 + d; } int vEpochSeconds_to_todays_date_yyyymmdd(double vEpochSeconds) { __time32_t t32 = lround(vEpochSeconds); struct tm tm1 = { 0 }; set_time_zone("UTC0"); _localtime32_s(&tm1, &t32); int y = tm1.tm_year + 1900; int m = tm1.tm_mon + 1; int d = tm1.tm_mday; return y * 10000 + m * 100 + d; } char get_monthchar(int monthnum) { //0=jan, 1=feb ... 11=dec. switch (monthnum) { case 0: return 'F';//jan case 1: return 'G';//feb case 2: return 'H'; case 3: return 'J'; case 4: return 'K'; case 5: return 'M'; case 6: return 'N'; case 7: return 'Q'; case 8: return 'U'; case 9: return 'V'; case 10: return 'X'; case 11: return 'Z'; //dec default: return '_'; //fail } } const char* get_monthcode_string(int month_flags) { static char out[13]; memset(out, 0, 13); int i = 0; char ch[2] = { 0,0 }; for (i = 0; i < 12; i++) { if ((1 << i) & month_flags) { ch[0] = get_monthchar(i); strcat_s(out,13, ch); } } return out; }
25.042017
119
0.632215
AndrewAMD
3c0b3cd97beaebbf482b79a10e1560101192cf5f
423
cpp
C++
src/libs/router_db/Constants.cpp
burntjam/keto
dbe32916a3bbc92fa0bbcb97d9de493d7ed63fd8
[ "MIT" ]
1
2020-03-04T10:38:00.000Z
2020-03-04T10:38:00.000Z
src/libs/router_db/Constants.cpp
burntjam/keto
dbe32916a3bbc92fa0bbcb97d9de493d7ed63fd8
[ "MIT" ]
null
null
null
src/libs/router_db/Constants.cpp
burntjam/keto
dbe32916a3bbc92fa0bbcb97d9de493d7ed63fd8
[ "MIT" ]
1
2020-03-04T10:38:01.000Z
2020-03-04T10:38:01.000Z
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ #include "keto/router_db/Constants.hpp" namespace keto { namespace router_db { const char* Constants::ROUTER_INDEX = "routes"; const std::vector<std::string> Constants::DB_LIST = {Constants::ROUTER_INDEX}; } }
16.92
79
0.699764
burntjam
3c0cd3ea765a310ea68a85662f4612d06c3e8a03
117
cpp
C++
tests/Issue182.cpp
galorojo/cppinsights
52ecab4ddd8e36fb99893551cf0fb8b5d58589f2
[ "MIT" ]
1,853
2018-05-13T21:49:17.000Z
2022-03-30T10:34:45.000Z
tests/Issue182.cpp
galorojo/cppinsights
52ecab4ddd8e36fb99893551cf0fb8b5d58589f2
[ "MIT" ]
398
2018-05-15T14:48:51.000Z
2022-03-24T12:14:33.000Z
tests/Issue182.cpp
galorojo/cppinsights
52ecab4ddd8e36fb99893551cf0fb8b5d58589f2
[ "MIT" ]
104
2018-05-15T04:00:59.000Z
2022-03-17T02:04:15.000Z
typedef int my_cb(int dst, int len, int dat); int f(my_cb cb, void *dat); int f(my_cb cb, void *dat) { return 0; }
14.625
45
0.649573
galorojo
3c0d3bbd4140c391ef55f48e7426fd4b2ea3e05c
6,289
cpp
C++
lib/CIndexStoreDB/CIndexStoreDB.cpp
gmittert/indexstore-db
31ff487bd8d10531a9af761e4ecc1c929ccee2ff
[ "Apache-2.0" ]
1
2021-07-07T15:38:50.000Z
2021-07-07T15:38:50.000Z
lib/CIndexStoreDB/CIndexStoreDB.cpp
DalavanCloud/indexstore-db
b1258a6827e988a4d9988e5fddf4d4e95cbd59bb
[ "Apache-2.0" ]
null
null
null
lib/CIndexStoreDB/CIndexStoreDB.cpp
DalavanCloud/indexstore-db
b1258a6827e988a4d9988e5fddf4d4e95cbd59bb
[ "Apache-2.0" ]
null
null
null
//===--- CIndexStoreDB.cpp ------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// #include "CIndexStoreDB/CIndexStoreDB.h" #include "IndexStoreDB/Index/IndexStoreLibraryProvider.h" #include "IndexStoreDB/Index/IndexSystem.h" #include "IndexStoreDB/Index/IndexSystemDelegate.h" #include "IndexStoreDB/Core/Symbol.h" #include "indexstore/IndexStoreCXX.h" #include "llvm/ADT/IntrusiveRefCntPtr.h" #include <Block.h> using namespace IndexStoreDB; using namespace index; class IndexStoreDBObjectBase : public llvm::ThreadSafeRefCountedBase<IndexStoreDBObjectBase> { public: virtual ~IndexStoreDBObjectBase() {} }; template <typename T> class IndexStoreDBObject: public IndexStoreDBObjectBase { public: T value; IndexStoreDBObject(T value) : value(std::move(value)) {} }; template <typename T> static IndexStoreDBObject<T> *make_object(const T &value) { auto obj = new IndexStoreDBObject<T>(value); obj->Retain(); return obj; } struct IndexStoreDBError { std::string message; IndexStoreDBError(StringRef message) : message(message.str()) {} }; class BlockIndexStoreLibraryProvider : public IndexStoreLibraryProvider { indexstore_library_provider_t callback; public: BlockIndexStoreLibraryProvider(indexstore_library_provider_t callback) : callback(Block_copy(callback)) {} ~BlockIndexStoreLibraryProvider() { Block_release(callback); } IndexStoreLibraryRef getLibraryForStorePath(StringRef storePath) override { indexstore_functions_t api; if (auto lib = callback(storePath.str().c_str())) { auto *obj = (IndexStoreDBObject<IndexStoreLibraryRef> *)lib; return obj->value; } else { return nullptr; } } }; indexstoredb_index_t indexstoredb_index_create(const char *storePath, const char *databasePath, indexstore_library_provider_t libProvider, // delegate, bool readonly, indexstoredb_error_t *error) { auto delegate = std::make_shared<IndexSystemDelegate>(); auto libProviderObj = std::make_shared<BlockIndexStoreLibraryProvider>(libProvider); std::string errMsg; if (auto index = IndexSystem::create(storePath, databasePath, libProviderObj, delegate, readonly, llvm::None, errMsg)) { return make_object(index); } else if (error) { *error = (indexstoredb_error_t)new IndexStoreDBError(errMsg); } return nullptr; } indexstoredb_indexstore_library_t indexstoredb_load_indexstore_library(const char *dylibPath, indexstoredb_error_t *error) { std::string errMsg; if (auto lib = loadIndexStoreLibrary(dylibPath, errMsg)) { return make_object(lib); } else if (error) { *error = (indexstoredb_error_t)new IndexStoreDBError(errMsg); } return nullptr; } bool indexstoredb_index_symbol_occurrences_by_usr( indexstoredb_index_t index, const char *usr, uint64_t roles, indexstoredb_symbol_occurrence_receiver_t receiver) { auto obj = (IndexStoreDBObject<std::shared_ptr<IndexSystem>> *)index; return obj->value->foreachSymbolOccurrenceByUSR(usr, (SymbolRoleSet)roles, [&](SymbolOccurrenceRef Occur) -> bool { return receiver(make_object(Occur)); }); } bool indexstoredb_index_related_symbol_occurrences_by_usr( indexstoredb_index_t index, const char *usr, uint64_t roles, indexstoredb_symbol_occurrence_receiver_t receiver) { auto obj = (IndexStoreDBObject<std::shared_ptr<IndexSystem>> *)index; return obj->value->foreachRelatedSymbolOccurrenceByUSR(usr, (SymbolRoleSet)roles, [&](SymbolOccurrenceRef Occur) -> bool { return receiver(make_object(Occur)); }); } const char * indexstoredb_symbol_usr(indexstoredb_symbol_t symbol) { auto obj = (IndexStoreDBObject<std::shared_ptr<Symbol>> *)symbol; return obj->value->getUSR().c_str(); } const char * indexstoredb_symbol_name(indexstoredb_symbol_t symbol) { auto obj = (IndexStoreDBObject<std::shared_ptr<Symbol>> *)symbol; return obj->value->getName().c_str(); } indexstoredb_symbol_t indexstoredb_symbol_occurrence_symbol(indexstoredb_symbol_occurrence_t occur) { auto obj = (IndexStoreDBObject<SymbolOccurrenceRef> *)occur; return make_object(obj->value->getSymbol()); } uint64_t indexstoredb_symbol_occurrence_roles(indexstoredb_symbol_occurrence_t occur) { auto obj = (IndexStoreDBObject<SymbolOccurrenceRef> *)occur; return (uint64_t)obj->value->getRoles(); } indexstoredb_symbol_location_t indexstoredb_symbol_occurrence_location( indexstoredb_symbol_occurrence_t occur) { auto obj = (IndexStoreDBObject<SymbolOccurrenceRef> *)occur; return (indexstoredb_symbol_location_t)&obj->value->getLocation(); } const char * indexstoredb_symbol_location_path(indexstoredb_symbol_location_t loc) { auto obj = (SymbolLocation *)loc; return obj->getPath().getPathString().c_str(); } bool indexstoredb_symbol_location_is_system(indexstoredb_symbol_location_t loc) { auto obj = (SymbolLocation *)loc; return obj->isSystem(); } int indexstoredb_symbol_location_line(indexstoredb_symbol_location_t loc) { auto obj = (SymbolLocation *)loc; return obj->getLine(); } int indexstoredb_symbol_location_column_utf8(indexstoredb_symbol_location_t loc) { auto obj = (SymbolLocation *)loc; return obj->getColumn(); } indexstoredb_object_t indexstoredb_retain(indexstoredb_object_t obj) { if (obj) ((IndexStoreDBObjectBase *)obj)->Retain(); return obj; } void indexstoredb_release(indexstoredb_object_t obj) { if (obj) ((IndexStoreDBObjectBase *)obj)->Release(); } const char * indexstoredb_error_get_description(indexstoredb_error_t error) { return ((IndexStoreDBError *)error)->message.c_str(); } void indexstoredb_error_dispose(indexstoredb_error_t error) { if (error) delete (IndexStoreDBError *)error; }
29.805687
86
0.732231
gmittert
3c0f3a82dccea0a7b94e19dc5d8f525af56dc64c
5,882
hpp
C++
src/lib/nas/storage.hpp
aligungr/ue-ran-sim
564f9d228723f03adfa2b02df2ea019bdf305085
[ "MIT" ]
16
2020-04-16T02:07:37.000Z
2020-07-23T10:48:27.000Z
src/lib/nas/storage.hpp
aligungr/ue-ran-sim
564f9d228723f03adfa2b02df2ea019bdf305085
[ "MIT" ]
8
2020-07-13T17:11:35.000Z
2020-08-03T16:46:31.000Z
src/lib/nas/storage.hpp
aligungr/ue-ran-sim
564f9d228723f03adfa2b02df2ea019bdf305085
[ "MIT" ]
9
2020-03-04T15:05:08.000Z
2020-07-30T06:18:18.000Z
// // This file is a part of UERANSIM open source project. // Copyright (c) 2021 ALİ GÜNGÖR. // // The software and all associated files are licensed under GPL-3.0 // and subject to the terms and conditions defined in LICENSE file. // #include <array> #include <functional> #include <optional> #include <type_traits> #include <vector> #include <utils/common.hpp> #include <utils/json.hpp> namespace nas { // TODO: Periodun sonuna geldiğinde erişilmezse, (autoClearIfNecessary çağrılmazsa) delete yapılmaz backup çalışmaz /* * - Items are unique, if already exists, deletes the previous one * - List have fixed size, if capacity is full, oldest item is deleted * - Automatically cleared after specified period * - The list is NOT thread safe */ template <typename T> class NasList { public: using backup_functor_type = std::function<void(const std::vector<T> &buffer, size_t count)>; private: const size_t m_sizeLimit; const int64_t m_autoClearingPeriod; const std::optional<backup_functor_type> m_backupFunctor; std::vector<T> m_data; size_t m_size; int64_t m_lastAutoCleared; public: NasList(size_t sizeLimit, int64_t autoClearingPeriod, std::optional<backup_functor_type> backupFunctor) : m_sizeLimit{sizeLimit}, m_autoClearingPeriod{autoClearingPeriod}, m_backupFunctor{backupFunctor}, m_data{sizeLimit}, m_size{}, m_lastAutoCleared{::utils::CurrentTimeMillis()} { } NasList(const NasList &) = delete; NasList(NasList &&) = delete; public: void add(const T &item) { autoClearIfNecessary(); remove(item); makeSlotForNewItem(); m_data[m_size] = item; m_size++; touch(); } void add(T &&item) { autoClearIfNecessary(); remove(item); makeSlotForNewItem(); m_data[m_size] = std::move(item); m_size++; touch(); } void remove(const T &item) { autoClearIfNecessary(); size_t index = ~0u; for (size_t i = 0; i < m_size; i++) { if (m_data[i] == item) { index = i; break; } } if (index != ~0u) removeAt(index); } bool contains(const T &item) { autoClearIfNecessary(); for (size_t i = 0; i < m_size; i++) if (m_data[i] == item) return true; return false; } template <typename Functor> void forEach(Functor &&fun) { autoClearIfNecessary(); for (size_t i = 0; i < m_size; i++) fun((const T &)m_data[i]); } template <typename Functor> void mutateForEach(Functor &&fun) { autoClearIfNecessary(); for (size_t i = 0; i < m_size; i++) fun(m_data[i]); touch(); } void clear() { int64_t currentTime = ::utils::CurrentTimeMillis(); if (currentTime - m_lastAutoCleared >= m_autoClearingPeriod) m_lastAutoCleared = currentTime; m_data.clear(); m_size = 0; touch(); } [[nodiscard]] size_t size() const { autoClearIfNecessary(); return m_data.size(); } private: void autoClearIfNecessary() { if (m_autoClearingPeriod <= 0) return; int64_t currentTime = ::utils::CurrentTimeMillis(); if (currentTime - m_lastAutoCleared >= m_autoClearingPeriod) { m_lastAutoCleared = currentTime; clear(); } } void makeSlotForNewItem() { if (m_size >= m_sizeLimit) removeAt(0); } void removeAt(size_t index) { for (size_t i = index; i < m_size; ++i) m_data[i] = i + 1 < m_sizeLimit ? m_data[i + 1] : T{}; m_size--; touch(); } void touch() { if (m_backupFunctor) (*m_backupFunctor)(m_data, m_size); } }; template <typename T> class NasSlot { public: using backup_functor_type = std::function<void(const T &value)>; private: const int64_t m_autoClearingPeriod; const std::optional<backup_functor_type> m_backupFunctor; T m_value; int64_t m_lastAutoCleared; static_assert(!std::is_reference<T>::value); public: NasSlot(int64_t autoClearingPeriod, std::optional<backup_functor_type> backupFunctor) : m_autoClearingPeriod{autoClearingPeriod}, m_backupFunctor{backupFunctor}, m_value{}, m_lastAutoCleared{::utils::CurrentTimeMillis()} { } const T &get() { autoClearIfNecessary(); return m_value; } const T &getPure() const { return m_value; } void clear() { set(T{}); } void set(const T &value) { autoClearIfNecessary(); m_value = value; touch(); } void set(T &&value) { autoClearIfNecessary(); m_value = std::move(value); touch(); } template <typename Functor> void access(Functor fun) { autoClearIfNecessary(); fun((const T &)m_value); } template <typename Functor> void mutate(Functor fun) { autoClearIfNecessary(); fun((T &)m_value); touch(); } private: void autoClearIfNecessary() { if (m_autoClearingPeriod <= 0) return; int64_t currentTime = ::utils::CurrentTimeMillis(); if (currentTime - m_lastAutoCleared >= m_autoClearingPeriod) { m_lastAutoCleared = currentTime; m_value = {}; } } void touch() { if (m_backupFunctor) (*m_backupFunctor)(m_value); } }; } // namespace nas template <typename T> inline Json ToJson(const nas::NasSlot<T> &v) { return ToJson(v.getPure()); }
20.858156
118
0.579735
aligungr
3c11133c5185b8e7beeab83e5b639d2086a62ca1
154
cpp
C++
lib/AsciiArtParsers/LinesParser/LinesParser.cpp
dodikk/AsciiBresenheim
e107d1e8773826868edb83e0f56a8052ce73a264
[ "BSD-4-Clause" ]
1
2022-03-13T00:42:02.000Z
2022-03-13T00:42:02.000Z
lib/AsciiArtParsers/LinesParser/LinesParser.cpp
dodikk/AsciiBresenheim
e107d1e8773826868edb83e0f56a8052ce73a264
[ "BSD-4-Clause" ]
null
null
null
lib/AsciiArtParsers/LinesParser/LinesParser.cpp
dodikk/AsciiBresenheim
e107d1e8773826868edb83e0f56a8052ce73a264
[ "BSD-4-Clause" ]
null
null
null
#include "StdAfx.h" #include "LinesParser.h" using namespace AsciiArt::Parser; LinesParser::LinesParser(void) { } LinesParser::~LinesParser(void) { }
11
33
0.733766
dodikk
3c12e06c7798ed0b2fa2dd80f7b1ff2bbf2c6118
4,037
cpp
C++
05-Map/src/Sokoban.cpp
eXpl0it3r/SFML-Workshop
0a42acc8a4aa48d44f3191b7472ea1f666381dee
[ "Unlicense" ]
9
2019-06-11T16:55:25.000Z
2020-05-06T14:59:28.000Z
05-Map/src/Sokoban.cpp
eXpl0it3r/SFML-Workshop
0a42acc8a4aa48d44f3191b7472ea1f666381dee
[ "Unlicense" ]
null
null
null
05-Map/src/Sokoban.cpp
eXpl0it3r/SFML-Workshop
0a42acc8a4aa48d44f3191b7472ea1f666381dee
[ "Unlicense" ]
null
null
null
#include "Sokoban.hpp" Sokoban::Sokoban() : m_window_size{ 640u, 640u }, m_distance{ 64.f }, m_tile_size{ m_distance, m_distance }, m_window{ sf::VideoMode{ m_window_size.x, m_window_size.y }, "05 - Map - SFML Workshop" } { m_window.setFramerateLimit(60); m_texture_holder.load("tilesheet", "assets/tilesheet.png"); init_player(); init_map(); } void Sokoban::run() { while (m_window.isOpen()) { handle_events(); update(); render(); } } void Sokoban::handle_events() { for (auto event = sf::Event{}; m_window.pollEvent(event);) { if (event.type == sf::Event::Closed) { m_window.close(); } handle_keyboard_input(event); } } void Sokoban::update() { const auto next_position = m_player.getPosition() + (sf::Vector2f{ m_direction } * m_distance); m_direction = sf::Vector2i{}; if (check_window_bounds(next_position) && !m_map.check_collision(next_position, { 0, 85, 90 })) { m_player.setPosition(next_position); } } void Sokoban::render() { m_window.clear(sf::Color{ 0xAA733CFF }); m_window.draw(m_map); m_window.draw(m_player); m_window.display(); } void Sokoban::init_player() { m_player.setTexture(m_texture_holder.get("tilesheet")); m_player.setPosition(m_tile_size * 2.f); m_player.setTextureRect({ 0, 5 * static_cast<int>(m_tile_size.y), static_cast<int>(m_tile_size.x), static_cast<int>(m_tile_size.y) }); } void Sokoban::init_map() { std::vector<int> data = { 90, 90, 90, 85, 85, 85, 85, 85, 90, 90, 90, 85, 85, 85, 89, 89, 89, 85, 90, 90, 90, 85, 102, 89, 89, 89, 89, 85, 90, 90, 90, 85, 85, 85, 89, 89, 102, 85, 90, 90, 90, 85, 102, 85, 85, 89, 89, 85, 90, 90, 90, 85, 89, 85, 89, 102, 89, 85, 85, 90, 90, 85, 89, 89, 102, 89, 89, 102, 85, 90, 90, 85, 89, 89, 89, 102, 89, 89, 85, 90, 90, 85, 85, 85, 85, 85, 85, 85, 85, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, 90, }; m_map.load(m_texture_holder.get("tilesheet"), { 64u, 64u }, data.data(), { 10u, 10u }); } void Sokoban::handle_keyboard_input(const sf::Event event) { if (event.type == sf::Event::KeyPressed) { if (event.key.code == sf::Keyboard::Left && !m_key_states[sf::Keyboard::Left]) { m_direction.x = -1; m_key_states[sf::Keyboard::Left] = true; } else if (event.key.code == sf::Keyboard::Right && !m_key_states[sf::Keyboard::Right]) { m_direction.x = 1; m_key_states[sf::Keyboard::Right] = true; } else if (event.key.code == sf::Keyboard::Up && !m_key_states[sf::Keyboard::Up]) { m_direction.y = -1; m_key_states[sf::Keyboard::Up] = true; } else if (event.key.code == sf::Keyboard::Down && !m_key_states[sf::Keyboard::Down]) { m_direction.y = 1; m_key_states[sf::Keyboard::Down] = true; } } else if (event.type == sf::Event::KeyReleased) { if (event.key.code == sf::Keyboard::Left) { m_direction.x = 0; m_key_states[sf::Keyboard::Left] = false; } else if (event.key.code == sf::Keyboard::Right) { m_direction.x = 0; m_key_states[sf::Keyboard::Right] = false; } else if (event.key.code == sf::Keyboard::Up) { m_direction.y = 0; m_key_states[sf::Keyboard::Up] = false; } else if (event.key.code == sf::Keyboard::Down) { m_direction.y = 0; m_key_states[sf::Keyboard::Down] = false; } } } bool Sokoban::check_window_bounds(const sf::Vector2<float> next_position) const { return next_position.x >= 0.f && next_position.x <= m_window_size.x - m_distance && next_position.y >= 0.f && next_position.y <= m_window_size.y - m_distance; }
28.230769
99
0.55462
eXpl0it3r
3c1a841992e6b972b684dae30d628b652f4f73b6
3,101
cpp
C++
src/org/apache/poi/ss/formula/function/FunctionMetadata.cpp
pebble2015/cpoi
6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6
[ "Apache-2.0" ]
null
null
null
src/org/apache/poi/ss/formula/function/FunctionMetadata.cpp
pebble2015/cpoi
6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6
[ "Apache-2.0" ]
null
null
null
src/org/apache/poi/ss/formula/function/FunctionMetadata.cpp
pebble2015/cpoi
6dcc0c5e13e3e722b4ef9fd0baffbf62bf71ead6
[ "Apache-2.0" ]
null
null
null
// Generated from /POI/java/org/apache/poi/ss/formula/function/FunctionMetadata.java #include <org/apache/poi/ss/formula/function/FunctionMetadata.hpp> #include <java/lang/Class.hpp> #include <java/lang/NullPointerException.hpp> #include <java/lang/String.hpp> #include <java/lang/StringBuffer.hpp> #include <Array.hpp> template<typename T> static T* npc(T* t) { if(!t) throw new ::java::lang::NullPointerException(); return t; } poi::ss::formula::function::FunctionMetadata::FunctionMetadata(const ::default_init_tag&) : super(*static_cast< ::default_init_tag* >(0)) { clinit(); } poi::ss::formula::function::FunctionMetadata::FunctionMetadata(int32_t index, ::java::lang::String* name, int32_t minParams, int32_t maxParams, int8_t returnClassCode, ::int8_tArray* parameterClassCodes) : FunctionMetadata(*static_cast< ::default_init_tag* >(0)) { ctor(index,name,minParams,maxParams,returnClassCode,parameterClassCodes); } constexpr int16_t poi::ss::formula::function::FunctionMetadata::FUNCTION_MAX_PARAMS; void poi::ss::formula::function::FunctionMetadata::ctor(int32_t index, ::java::lang::String* name, int32_t minParams, int32_t maxParams, int8_t returnClassCode, ::int8_tArray* parameterClassCodes) { super::ctor(); _index = index; _name = name; _minParams = minParams; _maxParams = maxParams; _returnClassCode = returnClassCode; _parameterClassCodes = (parameterClassCodes == nullptr) ? static_cast< ::int8_tArray* >(nullptr) : npc(parameterClassCodes)->clone(); } int32_t poi::ss::formula::function::FunctionMetadata::getIndex() { return _index; } java::lang::String* poi::ss::formula::function::FunctionMetadata::getName() { return _name; } int32_t poi::ss::formula::function::FunctionMetadata::getMinParams() { return _minParams; } int32_t poi::ss::formula::function::FunctionMetadata::getMaxParams() { return _maxParams; } bool poi::ss::formula::function::FunctionMetadata::hasFixedArgsLength() { return _minParams == _maxParams; } int8_t poi::ss::formula::function::FunctionMetadata::getReturnClassCode() { return _returnClassCode; } int8_tArray* poi::ss::formula::function::FunctionMetadata::getParameterClassCodes() { return npc(_parameterClassCodes)->clone(); } bool poi::ss::formula::function::FunctionMetadata::hasUnlimitedVarags() { return FUNCTION_MAX_PARAMS == _maxParams; } java::lang::String* poi::ss::formula::function::FunctionMetadata::toString() { auto sb = new ::java::lang::StringBuffer(int32_t(64)); npc(npc(sb)->append(npc(getClass())->getName()))->append(u" ["_j); npc(npc(npc(sb)->append(_index))->append(u" "_j))->append(_name); npc(sb)->append(u"]"_j); return npc(sb)->toString(); } extern java::lang::Class *class_(const char16_t *c, int n); java::lang::Class* poi::ss::formula::function::FunctionMetadata::class_() { static ::java::lang::Class* c = ::class_(u"org.apache.poi.ss.formula.function.FunctionMetadata", 51); return c; } java::lang::Class* poi::ss::formula::function::FunctionMetadata::getClass0() { return class_(); }
29.817308
204
0.722348
pebble2015
3c212a879e77cb386fd32337d492e15ca6ab8a88
5,170
cpp
C++
include/shacl/optional/Type/test/value_or.test.cpp
shacl/optional
02dc7ed2b923e3afb223817c47c239e2fab45c8f
[ "BSD-3-Clause" ]
null
null
null
include/shacl/optional/Type/test/value_or.test.cpp
shacl/optional
02dc7ed2b923e3afb223817c47c239e2fab45c8f
[ "BSD-3-Clause" ]
null
null
null
include/shacl/optional/Type/test/value_or.test.cpp
shacl/optional
02dc7ed2b923e3afb223817c47c239e2fab45c8f
[ "BSD-3-Clause" ]
null
null
null
#include "shacl/optional.hpp" #include "catch2/catch.hpp" SCENARIO("value_or"){ struct U { mutable bool copiedFrom = false; mutable bool movedFrom = false; }; struct T { mutable bool copiedFrom = false; mutable bool movedFrom = false; T() = default; T(T&& that) { that.movedFrom = true; } T& operator=(T&&) { return *this; } T(const T& that) { that.copiedFrom = true; } T(U&& that) { that.movedFrom = true; } T(const U& that) { that.copiedFrom = true; } }; auto ignore = [](auto&&){}; shacl::Optional<T> o; GIVEN("an optional const lvalue"){ const auto& co = o; GIVEN("the optional is engaged"){ o = T{}; GIVEN("an argument of the optional parameter type"){ auto arg = T{}; THEN("the value_or method should copy the stored value"){ auto t = co.value_or(arg); ignore(t); REQUIRE_FALSE(arg.copiedFrom); REQUIRE_FALSE(arg.movedFrom); REQUIRE(co.value().copiedFrom); REQUIRE_FALSE(co.value().movedFrom); } } GIVEN("an argument convertible to the optional parameter type"){ auto arg = U{}; THEN("the value_or method should copy the stored value"){ auto t = co.value_or(arg); ignore(t); REQUIRE_FALSE(arg.copiedFrom); REQUIRE_FALSE(arg.movedFrom); REQUIRE(co.value().copiedFrom); REQUIRE_FALSE(co.value().movedFrom); } } } GIVEN("the optional is disengaged"){ GIVEN("an argument of the optional parameter type"){ auto arg = T{}; GIVEN("the argument is an lvalue"){ THEN("the value_or method should copy the argument"){ auto t = co.value_or(arg); ignore(t); REQUIRE(arg.copiedFrom); REQUIRE_FALSE(arg.movedFrom); } } GIVEN("the argument is an rvalue"){ THEN("the value_or method should move the argument"){ auto t = co.value_or(std::move(arg)); ignore(t); REQUIRE_FALSE(arg.copiedFrom); REQUIRE(arg.movedFrom); } } } GIVEN("an argument convertible to the optional parameter type"){ auto arg = U{}; GIVEN("the argument is an lvalue"){ THEN("the value_or method should copy the argument"){ auto t = co.value_or(arg); ignore(t); REQUIRE(arg.copiedFrom); REQUIRE_FALSE(arg.movedFrom); } } GIVEN("the argument is an rvalue"){ THEN("the value_or method should move the argument"){ auto t = co.value_or(std::move(arg)); ignore(t); REQUIRE_FALSE(arg.copiedFrom); REQUIRE(arg.movedFrom); } } } } } GIVEN("an optional mutable rvalue"){ GIVEN("the optional is engaged"){ o = T{}; GIVEN("an argument of the optional parameter type"){ auto arg = T{}; THEN("the value_or method should move the stored value"){ auto t = std::move(o).value_or(arg); ignore(t); REQUIRE_FALSE(arg.copiedFrom); REQUIRE_FALSE(arg.movedFrom); REQUIRE_FALSE(o.value().copiedFrom); REQUIRE(o.value().movedFrom); } } GIVEN("an argument convertible to the optional parameter type"){ auto arg = U{}; THEN("the value_or method should move the stored value"){ auto t = std::move(o).value_or(arg); ignore(t); REQUIRE_FALSE(arg.copiedFrom); REQUIRE_FALSE(arg.movedFrom); REQUIRE_FALSE(o.value().copiedFrom); REQUIRE(o.value().movedFrom); } } } GIVEN("the optional is disengaged"){ GIVEN("an argument of the optional parameter type"){ auto arg = T{}; GIVEN("the argument is an lvalue"){ THEN("the value_or method should copy the argument"){ auto t = std::move(o).value_or(arg); ignore(t); REQUIRE(arg.copiedFrom); REQUIRE_FALSE(arg.movedFrom); } } GIVEN("the argument is an rvalue"){ THEN("the value_or method should move the argument"){ auto t = std::move(o).value_or(std::move(arg)); ignore(t); REQUIRE_FALSE(arg.copiedFrom); REQUIRE(arg.movedFrom); } } } GIVEN("an argument convertible to the optional parameter type"){ auto arg = U{}; GIVEN("the argument is an lvalue"){ THEN("the value_or method should copy the argument"){ auto t = std::move(o).value_or(arg); ignore(t); REQUIRE(arg.copiedFrom); REQUIRE_FALSE(arg.movedFrom); } } GIVEN("the argument is an rvalue"){ THEN("the value_or method should move the argument"){ auto t = std::move(o).value_or(std::move(arg)); ignore(t); REQUIRE_FALSE(arg.copiedFrom); REQUIRE(arg.movedFrom); } } } } } }
27.945946
70
0.543327
shacl
3c240845a9bb3630bf9d4c90d20c950b8293124f
2,283
cpp
C++
lib/duden/LdFile.cpp
nonwill/lsd2dsl
00e2a9832666dff03667b07815d73fab3fa8378e
[ "MIT" ]
66
2015-01-17T16:57:38.000Z
2022-02-06T15:29:54.000Z
lib/duden/LdFile.cpp
nonwill/lsd2dsl
00e2a9832666dff03667b07815d73fab3fa8378e
[ "MIT" ]
19
2015-02-08T15:35:12.000Z
2022-01-26T10:46:11.000Z
lib/duden/LdFile.cpp
nongeneric/lsd2dsl
4bf92b42b1ae47eee8e0b71bc04224dc037bd549
[ "MIT" ]
18
2015-03-23T07:06:07.000Z
2022-01-15T21:03:04.000Z
#include "LdFile.h" #include "Duden.h" #include <boost/regex.hpp> #include <boost/algorithm/string.hpp> namespace duden { LdFile parseLdFile(dictlsd::IRandomAccessStream* stream) { LdFile ld; ld.references.push_back({"WEB", "Web", "W"}); std::string line; while (readLine(stream, line)) { boost::algorithm::trim(line); if (line.empty()) continue; line = win1252toUtf8(line); if (line[0] == 'G' || line[0] == 'g') { boost::smatch m; if (!boost::regex_match(line, m, boost::regex("^.(.*?)\\|(.*?)\\|(.*?)$"))) throw std::runtime_error("LD parsing error"); ld.references.push_back({m[1], m[2], m[3]}); } else if (line[0] == 'B') { ld.name = line.substr(1); } else if (line[0] == 'S') { ld.sourceLanguage = line.substr(1); } else if (line[0] == 'K') { ld.baseFileName = line.substr(1); } else if (line[0] == 'D') { boost::smatch m; if (!boost::regex_match(line, m, boost::regex("^D(.+?) (\\d+) (\\d+).*$"))) throw std::runtime_error("LD parsing error"); ld.ranges.push_back({m[1], static_cast<uint32_t>(std::stoul(m[2])), static_cast<uint32_t>(std::stoul(m[3]))}); } } return ld; } int dudenLangToCode(const std::string& lang) { if (lang == "deu") return 1031; if (lang == "enu") return 1033; if (lang == "fra") return 1036; if (lang == "esn") return 1034; if (lang == "ita") return 1040; if (lang == "rus") return 1049; return 0; } void updateLanguageCodes(std::vector<LdFile*> lds) { auto first = lds.at(0); auto second = lds.size() > 1 ? lds.at(1) : nullptr; auto firstSource = first->sourceLanguage; auto secondSource = second ? second->sourceLanguage : "deu"; first->sourceLanguageCode = dudenLangToCode(firstSource); first->targetLanguageCode = dudenLangToCode(secondSource); if (second) { second->sourceLanguageCode = dudenLangToCode(secondSource); second->targetLanguageCode = dudenLangToCode(firstSource); } } } // namespace duden
30.851351
87
0.536575
nonwill
3c2597efb9131b6c7f0c3995ad59971d945792c9
12,202
cpp
C++
Sources/Tools/EPI/Document/Properties/PtySky.cpp
benkaraban/anima-games-engine
8aa7a5368933f1b82c90f24814f1447119346c3b
[ "BSD-3-Clause" ]
2
2015-04-16T01:05:53.000Z
2019-08-26T07:38:43.000Z
Sources/Tools/EPI/Document/Properties/PtySky.cpp
benkaraban/anima-games-engine
8aa7a5368933f1b82c90f24814f1447119346c3b
[ "BSD-3-Clause" ]
null
null
null
Sources/Tools/EPI/Document/Properties/PtySky.cpp
benkaraban/anima-games-engine
8aa7a5368933f1b82c90f24814f1447119346c3b
[ "BSD-3-Clause" ]
null
null
null
/* * Copyright (c) 2010, Anima Games, Benjamin Karaban, Laurent Schneider, * Jérémie Comarmond, Didier Colin. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * - Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "PtySky.h" #include <QtToolbox/CollapsibleWidget.moc.h> #include <QtToolbox/SingleSlidingValue.moc.h> #include <QtToolbox/ColorPicker/QuickColorPicker.moc.h> #include <QtToolbox/ComboBox.moc.h> #include <Universe/World.h> #include <QGridLayout> #include <QCheckBox> #include <EPI/GUI/Widget/CustomLine.moc.h> namespace EPI { //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- PtySky::PtySky(const Ptr<Universe::World>& pWorld, const Core::String& title): PropertyNode(title, true, false, CONTENT), _skyTexture(pWorld->getSkyTexture()), _color(pWorld->getSkyColor()), _glow(pWorld->getSkyGlow()), _horizon(pWorld->getSkyHorizon()), _angle(pWorld->getSkyAngle()), _roof(pWorld->getSkyRoof()), _sphericity(pWorld->getSkySphericity()), _atInfinity(pWorld->getSkyAtInfinity()), _isProcedural(pWorld->isSkyProcedural()), _model(pWorld->getSkyModel()), _skyColor(pWorld->getSkyBackColor()), _sunColor(pWorld->getSkySunColor()), _intensity(pWorld->getSkySunIntensity()), _pWorld(pWorld) { updateProperty(); } //----------------------------------------------------------------------------- PtySky::~PtySky() { } //----------------------------------------------------------------------------- Ptr<PropertyWidget> PtySky::internalCreatePropertyWidget(const Ptr<PropertyWidgetDataProxy>& pDataProxy, QWidget * parent) { Ptr<PtyWidgetSky> pPW (new PtyWidgetSky(pDataProxy, parent)); return pPW; } //----------------------------------------------------------------------------- void PtySky::updateProperty() { _skyTexture = _pWorld->getSkyTexture(); _color = _pWorld->getSkyColor(); _glow = _pWorld->getSkyGlow(); _horizon = _pWorld->getSkyHorizon(); _angle = _pWorld->getSkyAngle(); _roof = _pWorld->getSkyRoof(); _sphericity = _pWorld->getSkySphericity(); _atInfinity = _pWorld->getSkyAtInfinity(); _isProcedural = _pWorld->isSkyProcedural(); _model = _pWorld->getSkyModel(); _skyColor = _pWorld->getSkyBackColor(); _sunColor = _pWorld->getSkySunColor(); _intensity = _pWorld->getSkySunIntensity(); } //----------------------------------------------------------------------------- void PtySky::updateData() { _pWorld->setSkyTexture(_skyTexture); _pWorld->setSkyColor(_color); _pWorld->setSkyGlow(_glow); _pWorld->setSkyHorizon(_horizon); _pWorld->setSkyAngle(_angle); _pWorld->setSkyRoof(_roof); _pWorld->setSkySphericity(_sphericity); _pWorld->setSkyAtInfinity(_atInfinity); _pWorld->setSkyProcedural(_isProcedural); _pWorld->setSkyModel(_model); _pWorld->setSkyBackColor(_skyColor); _pWorld->setSkySunColor(_sunColor); _pWorld->setSkySunIntensity(_intensity); } //----------------------------------------------------------------------------- Ptr<Property> PtySky::clone() const { return Ptr<Property>(new PtySky( *this )); } //----------------------------------------------------------------------------- void PtySky::internalCopy(const Ptr<Property>& pSrc) { Ptr<PtySky> pPtySky = LM_DEBUG_PTR_CAST<PtySky>(pSrc); _skyTexture = pPtySky->_skyTexture; _color = pPtySky->_color; _glow = pPtySky->_glow; _horizon = pPtySky->_horizon; _angle = pPtySky->_angle; _roof = pPtySky->_roof; _sphericity = pPtySky->_sphericity; _atInfinity = pPtySky->_atInfinity; _isProcedural = pPtySky->_isProcedural; _pWorld = pPtySky->_pWorld; _model = pPtySky->_model; _skyColor = pPtySky->_skyColor; _sunColor = pPtySky->_sunColor; _intensity = pPtySky->_intensity; updateData(); } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- PtyWidgetSky::PtyWidgetSky(const Ptr<PropertyWidgetDataProxy>& data, QWidget * parent): PropertyWidget(data, parent) { setupUi(); } //----------------------------------------------------------------------------- PtyWidgetSky::~PtyWidgetSky() { } //----------------------------------------------------------------------------- void PtyWidgetSky::setupUi() { _layout = new QGridLayout(this); _layout->setContentsMargins(0, 0, 0, 0); _layout->setAlignment(Qt::AlignTop | Qt::AlignLeft); _groupBox = new QtToolbox::CollapsibleWidget(this, "Sky", false); _groupBox->setStyle(QtToolbox::CW_TITLE_1); _groupBox->setAlignmentTitle(Qt::AlignCenter); QGridLayout* layoutGroupBox = new QGridLayout(NULL); layoutGroupBox->setContentsMargins(0, 0, 0, 0); _groupBox->setLayout(layoutGroupBox); _skyTexture = new CustomLine(_groupBox, "Texture"); _skyTexture->pushAuthorizedDropMimeData("asset/texture"); _skyTexture->setReadOnly(true); _color = new QtToolbox::QuickColorPicker(_groupBox, "Color", Qt::white, false); _glow = new QtToolbox::QuickColorPicker(_groupBox, "Glow", Qt::white, false); _horizon = new QtToolbox::SingleSlidingDouble(_groupBox, "Horizon", -1.0, 0.99); _angle = new QtToolbox::SingleSlidingDouble(_groupBox, "Angle", 0, Core::rad2deg(d_PI_MUL_2)); _roof = new QtToolbox::SingleSlidingDouble(_groupBox, "Roof", 0.0, 5000.0); _sphericity = new QtToolbox::SingleSlidingDouble(_groupBox, "Sphericity", 0.0, 1.0); _atInfinity = new QCheckBox("At infinity", _groupBox); _atInfinity->setChecked(true); _isProcedural = new QCheckBox("Is procedural", _groupBox); _isProcedural->setChecked(true); _model = new QtToolbox::ComboBox(_groupBox, "Model"); _skyColor = new QtToolbox::QuickColorPicker(_groupBox, "Sky color", Qt::white, false); _sunColor = new QtToolbox::QuickColorPicker(_groupBox, "Sun color", Qt::white, false); _intensity = new QtToolbox::SingleSlidingDouble(_groupBox, "Intensity", 1.0, 4.0); _model->addItem("Foggy"); _model->addItem("Cloudy"); _model->addItem("Clear sky"); layoutGroupBox->addWidget(_skyTexture, 0, 0, Qt::AlignCenter); layoutGroupBox->addWidget(_color, 1, 0, Qt::AlignCenter); layoutGroupBox->addWidget(_glow, 2, 0, Qt::AlignCenter); layoutGroupBox->addWidget(_horizon, 3, 0, Qt::AlignLeft); layoutGroupBox->addWidget(_angle, 4, 0, Qt::AlignLeft); layoutGroupBox->addWidget(_roof, 5, 0, Qt::AlignLeft); layoutGroupBox->addWidget(_sphericity, 6, 0, Qt::AlignLeft); layoutGroupBox->addWidget(_atInfinity, 7, 0, Qt::AlignLeft); layoutGroupBox->addWidget(_isProcedural,8, 0, Qt::AlignLeft); layoutGroupBox->addWidget(_model, 9, 0, Qt::AlignLeft); layoutGroupBox->addWidget(_skyColor, 10, 0, Qt::AlignLeft); layoutGroupBox->addWidget(_sunColor, 11, 0, Qt::AlignLeft); layoutGroupBox->addWidget(_intensity, 12, 0, Qt::AlignLeft); _layout->addWidget(_groupBox); getWidgetsForUndoRedo().push_back(_skyTexture); getWidgetsForUndoRedo().push_back(_color); getWidgetsForUndoRedo().push_back(_glow); getWidgetsForUndoRedo().push_back(_horizon); getWidgetsForUndoRedo().push_back(_angle); getWidgetsForUndoRedo().push_back(_roof); getWidgetsForUndoRedo().push_back(_sphericity); getWidgetsForUndoRedo().push_back(_atInfinity); getWidgetsForUndoRedo().push_back(_isProcedural); getWidgetsForUndoRedo().push_back(_model); getWidgetsForUndoRedo().push_back(_skyColor); getWidgetsForUndoRedo().push_back(_sunColor); getWidgetsForUndoRedo().push_back(_intensity); PropertyWidget::setupUi(); } //----------------------------------------------------------------------------- void PtyWidgetSky::readProperty() { Ptr<PtySky> pPtySky = LM_DEBUG_PTR_CAST<PtySky>(getDataProxy()->getProperty()); _skyTexture->setText(Core::String8(pPtySky->_skyTexture).c_str()); _color->setColorLinear(pPtySky.get()->_color.r, pPtySky.get()->_color.g, pPtySky.get()->_color.b, pPtySky.get()->_color.a); _glow->setColorLinear(pPtySky.get()->_glow.r, pPtySky.get()->_glow.g, pPtySky.get()->_glow.b, pPtySky.get()->_glow.a); _horizon->setSingleValue(pPtySky->_horizon); _angle->setSingleValue(Core::rad2deg(pPtySky->_angle)); _roof->setSingleValue(pPtySky->_roof); _sphericity->setSingleValue(pPtySky->_sphericity); _atInfinity->setChecked(pPtySky->_atInfinity); _isProcedural->setChecked(pPtySky->_isProcedural); _skyColor->setColorLinear(pPtySky->_skyColor); _sunColor->setColorLinear(pPtySky->_sunColor); _model->selectIndex(int(pPtySky->_model)); _intensity->setSingleValue(pPtySky->_intensity); } //----------------------------------------------------------------------------- void PtyWidgetSky::writeProperty(QWidget* pWidget) { Ptr<PtySky> pPtySky = LM_DEBUG_PTR_CAST<PtySky>(getDataProxy()->getProperty()); pPtySky->_skyTexture = Core::String(_skyTexture->text().toStdString().c_str()); _color->getColorLinear(pPtySky.get()->_color.r, pPtySky.get()->_color.g, pPtySky.get()->_color.b, pPtySky.get()->_color.a); _glow->getColorLinear(pPtySky.get()->_glow.r, pPtySky.get()->_glow.g, pPtySky.get()->_glow.b, pPtySky.get()->_glow.a); _horizon->getSingleValue(pPtySky->_horizon); double angle = 0.0; _angle->getSingleValue(angle); pPtySky->_angle = Core::deg2rad(angle); _roof->getSingleValue(pPtySky->_roof); _sphericity->getSingleValue(pPtySky->_sphericity); pPtySky->_atInfinity = _atInfinity->isChecked(); pPtySky->_isProcedural = _isProcedural->isChecked(); _skyColor->getColorLinear(pPtySky->_skyColor); _sunColor->getColorLinear(pPtySky->_sunColor); pPtySky->_model = Renderer::ELightingModel(_model->selectedIndex()); _intensity->getSingleValue(pPtySky->_intensity); } //----------------------------------------------------------------------------- } // namespace EPI
46.572519
128
0.612523
benkaraban
3c27f69dfe490a67babef9a7a7bac0cf785a8b47
7,263
cpp
C++
GameItself/game.cpp
hcim38/PROJECT
7e4b4e2d8d2783b0c452463ccae00ff35d3594d5
[ "MIT" ]
null
null
null
GameItself/game.cpp
hcim38/PROJECT
7e4b4e2d8d2783b0c452463ccae00ff35d3594d5
[ "MIT" ]
null
null
null
GameItself/game.cpp
hcim38/PROJECT
7e4b4e2d8d2783b0c452463ccae00ff35d3594d5
[ "MIT" ]
null
null
null
#include "game.h" Game::Game() { qrTexturePtr = new QResource(":/Textures/Resources/hex-tex.png"); qrFontPtr = new QResource(":/Fonts/Resources/Lato-Regular.ttf"); texture.loadFromMemory(qrTexturePtr->data(), qrTexturePtr->size()); //lading resources font.loadFromMemory(qrFontPtr->data(), qrFontPtr->size()); delete qrTexturePtr; delete qrFontPtr; generateTemplate(); clickedAt = Tile(); } Game::Game(bool) : Game() { banner = Banner(sf::Vector2f(0, 640 - 32), sf::Vector2f(640, 32), font); } void Game::clicked(sf::Vector2i pos, std::vector<Player> &players, Tile &clickedAt) { for (auto &player : players) { for (auto &val : player.ownership()) { if (val.getGlobalBounds().contains(pos.x, pos.y)) { clickedAt = val; break; } } } } void Game::generateTemplate(sf::Vector2i tileSize, unsigned int mapSize) { std::vector<Tile> m_objects; for (int i = 0; i < mapSize; ++i) for (int j = 0; j < mapSize; ++j) { if (j % 2 == 0) { Tile temp(texture, tileSize, sf::Vector2f(i * tileSize.x * 2, 2 * j * tileSize.y)); temp.setUpTile(tileSize, sf::Vector2i(i, j), 0); m_objects.emplace_back(temp); } else { Tile temp(texture, tileSize, sf::Vector2f(i * tileSize.x * 2 + tileSize.x, 2 * j * tileSize.y)); temp.setUpTile(tileSize, sf::Vector2i(i, j), 1); m_objects.emplace_back(temp); } } for (auto &obj : m_objects) { obj.move(tileSize.x / 2, tileSize.y / 2); } MAP = m_objects; } std::vector<sf::VertexArray> Game::createLines(std::vector<Player> &players) { sf::VertexArray temp(sf::Lines, 2); std::vector<sf::VertexArray> vec; for (auto &playerM : players) { for (auto &tileOne : playerM.ownership()) { for (auto &player : players) { for (auto &tileTwo : player.ownership()) { if (tileOne.movePossible(tileTwo)) { temp[0].color = sf::Color(100, 100, 100, 50); temp[0].position = sf::Vector2f(tileOne.getGlobalBounds().left + (tileOne.getGlobalBounds().width / 2), tileOne.getGlobalBounds().top + (tileOne.getGlobalBounds().height / 2)); temp[1].color = sf::Color(100, 100, 100, 50); temp[1].position = sf::Vector2f(tileTwo.getGlobalBounds().left + (tileTwo.getGlobalBounds().width / 2), tileTwo.getGlobalBounds().top + (tileTwo.getGlobalBounds().height / 2)); vec.emplace_back(temp); } } } } } return vec; } void Game::nextTurn(unsigned long long &turn, std::vector<Player> &players) { turn++; if (turn >= players.size()) { turn = 1; } while (players[turn].ownership().size() == 0) { turn++; if (turn >= players.size()) { turn = 1; } } } void Game::gameLoop() { Lines = createLines(players); TilesOnScreen = MAP.size(); sf::RenderWindow window(sf::VideoMode(640, 640), "Tile Conqueror"); window.setFramerateLimit(60); window.setVerticalSyncEnabled(1); while (window.isOpen()) { //config complete, window created, game starts sf::Event event; while (window.pollEvent(event)) { if (event.type == sf::Event::Closed) { window.close(); } if (event.type == event.MouseButtonReleased && event.mouseButton.button == sf::Mouse::Left) { clicked(sf::Mouse::getPosition(window), players, clickedAt); } if (event.type == event.KeyReleased && event.key.code == sf::Keyboard::Space && !players[turn].AI()) { if (pointsGiveAway) { nextTurn(turn, players); pointsGiveAway = 0; //TODO if points left add 1 point from the remaining to every tile IF possible continue; } players[turn].clearOrigin(); pointsGiveAway = 1; pointsLeft = players[turn].ownership().size(); } //TODO add full value on PPM } window.clear(sf::Color::Black); for (auto &line : Lines) { window.draw(line); } for (auto &player : players) { player.textCorrection(); player.colorCorrection(); } if (!pointsGiveAway) { Turnmanager(players, clickedAt, turn); } else { players[turn].addPointsToTiles(clickedAt, pointsLeft); } players[turn].hilightOrigin(); clickedAt = Tile(); //// for (auto player : players) { for (auto val : player.ownership()) { val.drawMe(window, font); } } banner.refreshBanner(pointsLeft, players[turn], pointsGiveAway); banner.drawMe(window); window.display(); //koniec for (auto &player : players) { if (player.ownership().empty() && player.nickname() != "MAP") { playersEmpty++; } } if (TilesOnScreen == players[turn].ownership().size() || playersEmpty == players.size() - 2) //win condition winCondition++; if (winCondition >= 2) break; playersEmpty = 0; } ///Game ended window.close(); for (auto &player : players) { if (!player.ownership().empty() && player.nickname() != "MAP" && winCondition >= 2) { QMessageBox msg; msg.setText(QString::fromStdString(player.nickname()) + " has won the game"); msg.exec(); } } return; } void Game::loadMap(QString path, std::vector<Player> &NewPlayers) { players = NewPlayers; QFile file(path); file.open(QFile::ReadOnly); if (file.isOpen()) { std::vector<sf::Vector2i> deleted; QDataStream in(&file); QString str; int x, y; while (!in.atEnd()) { in >> x >> y; deleted.emplace_back(sf::Vector2i(x, y)); } file.close(); for (auto const &pos : deleted) { for (auto tile = MAP.begin(); tile != MAP.end(); tile++) { if (*tile == pos) { tile->setColor(sf::Color(255, 0, 0, 100)); MAP.erase(tile); tile--; continue; } } } } captureRandomTiles(MAP, players); } Game::~Game() {}
31.578261
100
0.480793
hcim38
3c293f244f4de113c85546bfd196752d3c6e8249
533
cpp
C++
Chapter 3. Strings, Vectors, and Arrays/Codes/3.35.cpp
Yunxiang-Li/Cpp_Primer
b5c857e3f6be993b2ff8fc03f634141ae24925fc
[ "MIT" ]
null
null
null
Chapter 3. Strings, Vectors, and Arrays/Codes/3.35.cpp
Yunxiang-Li/Cpp_Primer
b5c857e3f6be993b2ff8fc03f634141ae24925fc
[ "MIT" ]
null
null
null
Chapter 3. Strings, Vectors, and Arrays/Codes/3.35.cpp
Yunxiang-Li/Cpp_Primer
b5c857e3f6be993b2ff8fc03f634141ae24925fc
[ "MIT" ]
1
2021-09-30T14:08:03.000Z
2021-09-30T14:08:03.000Z
#include <iostream> using std::cin; using std::cout; using std::iterator; using std::begin; using std::end; /** * Using pointers, write a program to set the elements in an array to zero. */ int main() { //Initialize a 10-length array. int arr[10]; //Use pointer to assign each value to zero. for (auto ptr = begin(arr); ptr != end(arr); ptr++) *ptr = 0; //Output each element's value. for (auto ptr = begin(arr); ptr != end(arr); ptr++) cout << *ptr << ' '; return 0; }
13.666667
75
0.577861
Yunxiang-Li
3c2b5e9d1e60c07c19c55545055d7daa9f6fd4dd
9,042
cpp
C++
NOLF/ClientShellDLL/LightningFX.cpp
haekb/nolf1-modernizer
25bac3d43c40a83b8e90201a70a14ef63b4240e7
[ "Unlicense" ]
38
2019-09-16T14:46:42.000Z
2022-03-10T20:28:10.000Z
NOLF/ClientShellDLL/LightningFX.cpp
haekb/nolf1-modernizer
25bac3d43c40a83b8e90201a70a14ef63b4240e7
[ "Unlicense" ]
39
2019-08-12T01:35:33.000Z
2022-02-28T16:48:16.000Z
NOLF/ClientShellDLL/LightningFX.cpp
haekb/nolf1-modernizer
25bac3d43c40a83b8e90201a70a14ef63b4240e7
[ "Unlicense" ]
6
2019-09-17T12:49:18.000Z
2022-03-10T20:28:12.000Z
// ----------------------------------------------------------------------- // // // MODULE : LightningFX.cpp // // PURPOSE : Lightning special FX - Implementation // // CREATED : 4/15/99 // // (c) 1999 Monolith Productions, Inc. All Rights Reserved // // ----------------------------------------------------------------------- // #include "stdafx.h" #include "LightningFX.h" #include "iltclient.h" #include "SFXMgr.h" #include "iltcustomdraw.h" #include "GameClientShell.h" #include "DynamicLightFX.h" #include "GameButes.h" #include "VarTrack.h" // ----------------------------------------------------------------------- // // // ROUTINE: CLightningFX::Init // // PURPOSE: Init the lightning fx // // ----------------------------------------------------------------------- // LTBOOL CLightningFX::Init(HLOCALOBJ hServObj, HMESSAGEREAD hMessage) { if (!CSpecialFX::Init(hServObj, hMessage)) return LTFALSE; if (!hMessage) return LTFALSE; // Read in the init info from the message... LFXCREATESTRUCT lcs; lcs.hServerObj = hServObj; lcs.lfx.hServerObj = hServObj; g_pLTClient->ReadFromMessageVector(hMessage, &(lcs.lfx.vStartPos)); g_pLTClient->ReadFromMessageVector(hMessage, &(lcs.lfx.vEndPos)); g_pLTClient->ReadFromMessageVector(hMessage, &(lcs.vLightColor)); g_pLTClient->ReadFromMessageVector(hMessage, &(lcs.lfx.vInnerColorStart)); g_pLTClient->ReadFromMessageVector(hMessage, &(lcs.lfx.vInnerColorEnd)); g_pLTClient->ReadFromMessageVector(hMessage, &(lcs.lfx.vOuterColorStart)); g_pLTClient->ReadFromMessageVector(hMessage, &(lcs.lfx.vOuterColorEnd)); lcs.lfx.fAlphaStart = g_pLTClient->ReadFromMessageFloat(hMessage); lcs.lfx.fAlphaEnd = g_pLTClient->ReadFromMessageFloat(hMessage); lcs.lfx.fMinWidth = g_pLTClient->ReadFromMessageFloat(hMessage); lcs.lfx.fMaxWidth = g_pLTClient->ReadFromMessageFloat(hMessage); lcs.lfx.fLifeTime = g_pLTClient->ReadFromMessageFloat(hMessage); lcs.lfx.fAlphaLifeTime = g_pLTClient->ReadFromMessageFloat(hMessage); lcs.fMinDelayTime = g_pLTClient->ReadFromMessageFloat(hMessage); lcs.fMaxDelayTime = g_pLTClient->ReadFromMessageFloat(hMessage); lcs.lfx.fPerturb = g_pLTClient->ReadFromMessageFloat(hMessage); lcs.fLightRadius = g_pLTClient->ReadFromMessageFloat(hMessage); lcs.fSoundRadius = g_pLTClient->ReadFromMessageFloat(hMessage); lcs.lfx.nWidthStyle = g_pLTClient->ReadFromMessageByte(hMessage); lcs.lfx.nNumSegments = g_pLTClient->ReadFromMessageByte(hMessage); lcs.bOneTimeOnly = (LTBOOL) g_pLTClient->ReadFromMessageByte(hMessage); lcs.bDynamicLight = (LTBOOL) g_pLTClient->ReadFromMessageByte(hMessage); lcs.bPlaySound = (LTBOOL) g_pLTClient->ReadFromMessageByte(hMessage); lcs.lfx.bAdditive = (LTBOOL) g_pLTClient->ReadFromMessageByte(hMessage); lcs.lfx.bMultiply = (LTBOOL) g_pLTClient->ReadFromMessageByte(hMessage); m_hstrTexture = g_pLTClient->ReadFromMessageHString(hMessage); return Init(&lcs); } // ----------------------------------------------------------------------- // // // ROUTINE: CLightningFX::Init // // PURPOSE: Init the lightning fx // // ----------------------------------------------------------------------- // LTBOOL CLightningFX::Init(SFXCREATESTRUCT* psfxCreateStruct) { if (!CSpecialFX::Init(psfxCreateStruct)) return LTFALSE; LFXCREATESTRUCT* pLFX = (LFXCREATESTRUCT*)psfxCreateStruct; m_cs = *pLFX; if (m_hstrTexture) { m_cs.lfx.pTexture = g_pLTClient->GetStringData(m_hstrTexture); } return LTTRUE; } // ----------------------------------------------------------------------- // // // ROUTINE: CLightningFX::CreateObject // // PURPOSE: Create object associated the object // // ----------------------------------------------------------------------- // LTBOOL CLightningFX::CreateObject(ILTClient *pClientDE) { if (!CSpecialFX::CreateObject(pClientDE)) return LTFALSE; // Validate our init info... if (m_cs.lfx.nNumSegments < 1) return LTFALSE; // Get the thunder sound path if we need to play the sound... if (m_cs.bPlaySound) { m_csThunderStr = g_pClientButeMgr->GetWeatherAttributeString(WEATHER_BUTE_THUNDERSOUND); } // Set up the lightning... return Setup(); } // ----------------------------------------------------------------------- // // // ROUTINE: CLightningFX::Setup // // PURPOSE: Setup the line used to draw lightning // // ----------------------------------------------------------------------- // LTBOOL CLightningFX::Setup() { // Figure out the position based on the object's current pos... if (m_hServerObject) { LTVector vPos; g_pLTClient->GetObjectPos(m_hServerObject, &vPos); m_cs.lfx.vStartPos = vPos; } // Create our poly-line for the lightning... if (m_Line.HasBeenDrawn()) { m_Line.ReInit(&m_cs.lfx); } else { m_Line.Init(&m_cs.lfx); m_Line.CreateObject(g_pLTClient); } // Figure out when to start/stop... LTFLOAT fTime = g_pLTClient->GetTime(); m_fStartTime = fTime + GetRandom(m_cs.fMinDelayTime, m_cs.fMaxDelayTime); m_fEndTime = m_fStartTime + m_cs.lfx.fLifeTime; // Calculate our mid point... LTVector vPos = m_cs.lfx.vStartPos; LTVector vDir = (m_cs.lfx.vEndPos - m_cs.lfx.vStartPos); float fDist = vDir.Mag(); float fTotalDist = fDist; vDir.Norm(); m_vMidPos = (m_cs.lfx.vStartPos + (vDir * fDist/2.0f)); // Create the dynamic light if necessary... if (m_cs.bDynamicLight && !m_hLight) { ObjectCreateStruct createStruct; INIT_OBJECTCREATESTRUCT(createStruct); createStruct.m_ObjectType = OT_LIGHT; createStruct.m_Flags = FLAG_DONTLIGHTBACKFACING; createStruct.m_Pos = m_vMidPos; m_hLight = m_pClientDE->CreateObject(&createStruct); if (!m_hLight) return LTFALSE; m_pClientDE->SetLightColor(m_hLight, m_cs.vLightColor.x/255.0f, m_cs.vLightColor.y/255.0f, m_cs.vLightColor.z/255.0f); m_pClientDE->SetLightRadius(m_hLight, m_cs.fLightRadius); } return LTTRUE; } // ----------------------------------------------------------------------- // // // ROUTINE: CLightningFX::HandleFirstTime // // PURPOSE: Handle the first time drawing... // // ----------------------------------------------------------------------- // void CLightningFX::HandleFirstTime() { if (m_hLight) { uint32 dwFlags = g_pLTClient->GetObjectFlags(m_hLight); g_pLTClient->SetObjectFlags(m_hLight, dwFlags | FLAG_VISIBLE); } if (m_cs.bPlaySound) { float fWaitTime = 0.0f; m_fPlaySoundTime = g_pLTClient->GetTime() + fWaitTime; m_bPlayedSound = LTFALSE; } } // ----------------------------------------------------------------------- // // // ROUTINE: CLightningFX::UpdateSound // // PURPOSE: Handle playing the sound // // ----------------------------------------------------------------------- // void CLightningFX::UpdateSound() { if (m_bPlayedSound || !m_cs.bPlaySound || (m_csThunderStr.GetLength() < 1)) return; if (m_fPlaySoundTime <= g_pLTClient->GetTime()) { m_bPlayedSound = LTTRUE; g_pClientSoundMgr->PlaySoundFromPos(m_vMidPos, (char *)(LPCSTR)m_csThunderStr, m_cs.fSoundRadius, SOUNDPRIORITY_MISC_MEDIUM); } } // ----------------------------------------------------------------------- // // // ROUTINE: CLightningFX::Update // // PURPOSE: Update the lightning // // ----------------------------------------------------------------------- // LTBOOL CLightningFX::Update() { if (m_bWantRemove) return LTFALSE; LTFLOAT fTime = g_pLTClient->GetTime(); // Hide/show lightning if necessary... if (m_hServerObject) { uint32 dwUserFlags; g_pLTClient->GetObjectUserFlags(m_hServerObject, &dwUserFlags); if (!(dwUserFlags & USRFLG_VISIBLE)) { m_Line.SetFlags(m_Line.GetFlags() & ~FLAG_VISIBLE); if (m_hLight) { uint32 dwFlags = g_pLTClient->GetObjectFlags(m_hLight); g_pLTClient->SetObjectFlags(m_hLight, dwFlags & ~FLAG_VISIBLE); } return LTTRUE; } else { m_Line.SetFlags(m_Line.GetFlags() | FLAG_VISIBLE); } } m_Line.Update(); // See if it is time to act... if (fTime > m_fEndTime) { if (m_cs.bOneTimeOnly) { return LTFALSE; } else { Setup(); m_bFirstTime = LTTRUE; } } if (fTime < m_fStartTime) { m_Line.SetFlags(m_Line.GetFlags() & ~FLAG_VISIBLE); if (m_hLight) { uint32 dwFlags = g_pLTClient->GetObjectFlags(m_hLight); g_pLTClient->SetObjectFlags(m_hLight, dwFlags & ~FLAG_VISIBLE); } return LTTRUE; // not yet... } else { m_Line.SetFlags(m_Line.GetFlags() | FLAG_VISIBLE); } // Do first time stuff... if (m_bFirstTime) { m_bFirstTime = LTFALSE; HandleFirstTime(); } else { if (m_hLight) { uint32 dwFlags = g_pLTClient->GetObjectFlags(m_hLight); g_pLTClient->SetObjectFlags(m_hLight, dwFlags & ~FLAG_VISIBLE); } } // Update playing the sound... UpdateSound(); return LTTRUE; }
25.908309
90
0.603185
haekb
3c33bdec27a201db0f4d26fab96d506c6bb9ea87
1,254
hpp
C++
libTupl/src/tupl/LargeKeyError.hpp
cojen/TuplNative
4a8fa2b90825fdfe8f563e910fa188f1ed851404
[ "Apache-2.0" ]
1
2016-07-15T14:50:58.000Z
2016-07-15T14:50:58.000Z
libTupl/src/tupl/LargeKeyError.hpp
cojen/TuplNative
4a8fa2b90825fdfe8f563e910fa188f1ed851404
[ "Apache-2.0" ]
null
null
null
libTupl/src/tupl/LargeKeyError.hpp
cojen/TuplNative
4a8fa2b90825fdfe8f563e910fa188f1ed851404
[ "Apache-2.0" ]
null
null
null
/* * Copyright (C) 2012-2014 Brian S O'Neill * Copyright (C) 2014 Vishal Parakh * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef _TUPL_LARGEKEYEXCEPTION_HPP #define _TUPL_LARGEKEYEXCEPTION_HPP #include "DatabaseError.hpp" namespace tupl { /** * Thrown when a key is too large to fit into a page. Maximum key size is * defined as: {@code min(16383, (pageSize / 2) - 22)}. When using the default * page size of 4096 bytes, the maximum key size is 2026 bytes. * * @author Brian S O'Neill * @author Vishal Parakh */ class LargeKeyError: public DatabaseError { public: LargeKeyError(const size_t /* length */) { // FIXME: bubble up // super("Key is too large: " + length); } }; } #endif
28.5
78
0.699362
cojen
3c344f5483b92d3d53a547e37442984aaa53c74f
611
cpp
C++
UUT/Video/Image.cpp
kolyden/uut-engine
aa8e5a42c350aceecee668941e06ac626aac6c52
[ "MIT" ]
null
null
null
UUT/Video/Image.cpp
kolyden/uut-engine
aa8e5a42c350aceecee668941e06ac626aac6c52
[ "MIT" ]
null
null
null
UUT/Video/Image.cpp
kolyden/uut-engine
aa8e5a42c350aceecee668941e06ac626aac6c52
[ "MIT" ]
null
null
null
#include "Image.h" namespace uut { UUT_OBJECT_IMPLEMENT(Image) {} Image::Image() : _data(nullptr) { } Image::~Image() { Destroy(); } bool Image::Create(const Vector2i& size) { if (_size == size) return true; Destroy(); _data = SDL_CreateRGBSurface(0, _size.x, _size.y, 32, 0, 0, 0, 0); return IsCreated(); } void Image::Destroy() { if (!IsCreated()) return; SDL_FreeSurface(_data); _data = nullptr; } bool Image::IsCreated() const { return _data != nullptr; } uintptr_t Image::GetInternalHandle() const { return reinterpret_cast<uintptr_t>(_data); } }
13
44
0.631751
kolyden
3c35a958121c6917278c070b6a48f025cdc27e77
1,559
cpp
C++
kernel/drivers/pic8042contr.cpp
CarboSauce/Gloxor
fc9f5c56866f8c3e85f844d37a1faa9e9ef4c856
[ "MIT" ]
4
2021-07-14T20:24:24.000Z
2021-07-16T06:49:48.000Z
kernel/drivers/pic8042contr.cpp
CarboSauce/Gloxor
fc9f5c56866f8c3e85f844d37a1faa9e9ef4c856
[ "MIT" ]
null
null
null
kernel/drivers/pic8042contr.cpp
CarboSauce/Gloxor
fc9f5c56866f8c3e85f844d37a1faa9e9ef4c856
[ "MIT" ]
null
null
null
#include "pic8042contr.hpp" #include "asm/asmstubs.hpp" #include "gloxor/modules.hpp" #include "system/logging.hpp" // everything is masked on startup static glox::picContext picCtx{0xFF, 0xFF}; namespace glox::pic { void sendEoiSlave() { outb(PIC2_COMMAND, PIC_EOI); } void sendEoiMaster() { outb(PIC1_COMMAND, PIC_EOI); } void remap(u8 offset1, u8 offset2) { unsigned char a1, a2; a1 = inb(PIC1_DATA); // save masks a2 = inb(PIC2_DATA); outb(PIC1_COMMAND, ICW1_INIT | ICW1_ICW4); // starts the initialization sequence (in cascade mode) ioWait(); outb(PIC2_COMMAND, ICW1_INIT | ICW1_ICW4); ioWait(); outb(PIC1_DATA, offset1); // ICW2: Master PIC vector offset ioWait(); outb(PIC2_DATA, offset2); // ICW2: Slave PIC vector offset ioWait(); outb(PIC1_DATA, 4); // ICW3: tell Master PIC that there is a slave PIC at IRQ2 (0000 0100) ioWait(); outb(PIC2_DATA, 2); // ICW3: tell Slave PIC its cascade identity (0000 0010) ioWait(); outb(PIC1_DATA, ICW4_8086); ioWait(); outb(PIC2_DATA, ICW4_8086); ioWait(); outb(PIC1_DATA, a1); // restore saved masks. outb(PIC2_DATA, a2); } void setMasterMask(u8 mask) { picCtx.masterMask &= mask; outb(PIC1_DATA, picCtx.masterMask); } void setSlaveMask(u8 mask) { picCtx.slaveMask &= mask; outb(PIC1_DATA, picCtx.slaveMask); } } // namespace glox::pic static void initPic() { glox::pic::remap(0x20, 0x28); gloxDebugLog("Initializing PIC\n"); // Mask all devices outb(PIC1_DATA, 0xFF); outb(PIC2_DATA, 0xFF); } initDriverCentralModule(initPic);
22.926471
100
0.6966
CarboSauce
3c3693c493f420216094c6039949a40685fac446
7,418
cpp
C++
src/effect/explosion.cpp
FreeAllegiance/AllegianceDX7
3955756dffea8e7e31d3a55fcf6184232b792195
[ "MIT" ]
76
2015-08-18T19:18:40.000Z
2022-01-08T12:47:22.000Z
src/effect/explosion.cpp
StudentAlleg/Allegiance
e91660a471eb4e57e9cea4c743ad43a82f8c7b18
[ "MIT" ]
37
2015-08-14T22:44:12.000Z
2020-01-21T01:03:06.000Z
src/effect/explosion.cpp
StudentAlleg/Allegiance
e91660a471eb4e57e9cea4c743ad43a82f8c7b18
[ "MIT" ]
42
2015-08-13T23:31:35.000Z
2022-03-17T02:20:26.000Z
#include "explosion.h" ////////////////////////////////////////////////////////////////////////////// // // ExplosionGeo // ////////////////////////////////////////////////////////////////////////////// class ExplosionGeoImpl : public ExplosionGeo { private: ////////////////////////////////////////////////////////////////////////////// // // Types // ////////////////////////////////////////////////////////////////////////////// class ExplosionData : IObject { public: TRef<AnimatedImage> m_pimage; Vector m_position; Vector m_dposition; float m_angle; float m_timeStart; float m_scale; }; class ShockwaveData : IObject { public: TRef<Image> m_pimageShockwave; Vector m_position; Vector m_dposition; Vector m_forward; Vector m_right; Color m_color; float m_timeStart; float m_scale; }; typedef TList<ExplosionData> ExplosionDataList; ////////////////////////////////////////////////////////////////////////////// // // Members // ////////////////////////////////////////////////////////////////////////////// TList<ShockwaveData> m_listShockwave; TVector<ExplosionDataList> m_vlistExplosion; ////////////////////////////////////////////////////////////////////////////// // // Value Members // ////////////////////////////////////////////////////////////////////////////// Number* GetTime() { return Number::Cast(GetChild(0)); } public: ExplosionGeoImpl(Number* ptime) : ExplosionGeo(ptime), m_vlistExplosion(24) { } ////////////////////////////////////////////////////////////////////////////// // // Methods // ////////////////////////////////////////////////////////////////////////////// void AddExplosion( const Vector& position, const Vector& forward, const Vector& right, const Vector& dposition, float radiusExplosion, float radiusShockWave, const Color& color, int countDecals, TVector<TRef<AnimatedImage> > vpimage, Image* pimageShockwave ) { // // Add the shockwave // if (pimageShockwave != NULL) { m_listShockwave.PushFront(); ShockwaveData& sdata = m_listShockwave.GetFront(); sdata.m_timeStart = GetTime()->GetValue(); sdata.m_pimageShockwave = pimageShockwave; sdata.m_color = color; sdata.m_position = position; sdata.m_dposition = dposition; sdata.m_scale = radiusShockWave; sdata.m_forward = forward; sdata.m_right = right; } // // Add the little explosions // int countImage = vpimage.GetCount(); int indexImage = 0; for (int index = 0; index < countDecals; index++) { ExplosionDataList& list = m_vlistExplosion.Get(index); list.PushFront(); ExplosionData& edata = list.GetFront(); edata.m_timeStart = GetTime()->GetValue() + index * 0.25f; edata.m_pimage = vpimage[indexImage]; edata.m_position = position + Vector::RandomPosition(radiusExplosion * 0.5f); edata.m_dposition = dposition; edata.m_angle = random(0, 2 * pi); edata.m_scale = radiusExplosion; indexImage++; if (indexImage >= countImage) { indexImage = 0; } } } ////////////////////////////////////////////////////////////////////////////// // // Value Methods // ////////////////////////////////////////////////////////////////////////////// ZString GetFunctionName() { return "ExplosionGeo"; } ////////////////////////////////////////////////////////////////////////////// // // Geometry Methods // ////////////////////////////////////////////////////////////////////////////// float RenderShockwaves(Context* pcontext) { float fill = 0; TList<ShockwaveData>::Iterator iter(m_listShockwave); while (!iter.End()) { ShockwaveData& sdata = iter.Value(); float time = GetTime()->GetValue() - sdata.m_timeStart; float bright = 1.0f - time * time; if (bright <= 0) { iter.Remove(); } else { float scale = time * sdata.m_scale; fill += pcontext->DrawDecal( sdata.m_pimageShockwave->GetSurface(), bright * sdata.m_color, sdata.m_position + time * sdata.m_dposition, scale * sdata.m_forward, scale * sdata.m_right, 0, 0 ); iter.Next(); } }; return fill; } float RenderExplosions( Context* pcontext, ExplosionDataList& list ) { float fill = 0; ExplosionDataList::Iterator iter(list); while (!iter.End()) { ExplosionData& edata = iter.Value(); float time = GetTime()->GetValue() - edata.m_timeStart; if (time >= 0) { int frame = (int)(time * 20.0f); if (frame >= edata.m_pimage->GetCount()) { iter.Remove(); continue; } else { fill += pcontext->DrawDecal( edata.m_pimage->GetSurface(frame), Color::White(), edata.m_position + time * edata.m_dposition, Vector::GetZero(), Vector::GetZero(), edata.m_scale, edata.m_angle ); } } iter.Next(); } return fill; } void Render(Context* pcontext) { float fill = 0; fill += RenderShockwaves(pcontext); int count = m_vlistExplosion.GetCount(); for (int index = 0; index < count; index++) { fill += RenderExplosions(pcontext, m_vlistExplosion.Get(index)); // // If we have passed the fill limit throw away the rest of the explosions // if (fill > 2.0f) { for (int index2 = index + 1; index2 < count; index2++) { m_vlistExplosion.Get(index2).SetEmpty(); } return; } } } }; ////////////////////////////////////////////////////////////////////////////// // // ExplosionGeo Factory // ////////////////////////////////////////////////////////////////////////////// TRef<ExplosionGeo> CreateExplosionGeo(Number* ptime) { return new ExplosionGeoImpl(ptime); }
29.553785
90
0.384201
FreeAllegiance
3c391e37b3ccae6920d4150b7551e4a237718801
1,664
hpp
C++
typed_python/PyPythonSubclassInstance.hpp
braxtonmckee/nativepython
5c64e91eb959fcd1c2c42655b40c7cceb3436f1d
[ "Apache-2.0" ]
7
2018-08-07T15:41:54.000Z
2019-02-19T12:47:57.000Z
typed_python/PyPythonSubclassInstance.hpp
braxtonmckee/nativepython
5c64e91eb959fcd1c2c42655b40c7cceb3436f1d
[ "Apache-2.0" ]
38
2018-10-17T13:37:46.000Z
2019-04-11T20:50:14.000Z
typed_python/PyPythonSubclassInstance.hpp
braxtonmckee/nativepython
5c64e91eb959fcd1c2c42655b40c7cceb3436f1d
[ "Apache-2.0" ]
4
2019-02-11T17:44:55.000Z
2019-03-20T07:38:18.000Z
#pragma once #include "PyInstance.hpp" class PyPythonSubclassInstance : public PyInstance { public: typedef PythonSubclass modeled_type; static void copyConstructFromPythonInstanceConcrete(PythonSubclass* eltType, instance_ptr tgt, PyObject* pyRepresentation, bool isExplicit) { Type* argType = extractTypeFrom(pyRepresentation->ob_type); if (argType && argType == eltType) { eltType->getBaseType()->copy_constructor(tgt, ((PyInstance*)pyRepresentation)->dataPtr()); return; } if (argType && argType == eltType->getBaseType()) { eltType->getBaseType()->copy_constructor(tgt, ((PyInstance*)pyRepresentation)->dataPtr()); return; } PyInstance::copyConstructFromPythonInstanceConcrete(eltType, tgt, pyRepresentation, isExplicit); } PyObject* tp_getattr_concrete(PyObject* pyAttrName, const char* attrName) { return specializeForType((PyObject*)this, [&](auto& subtype) { return subtype.tp_getattr_concrete(pyAttrName, attrName); }, type()->getBaseType()); } static bool pyValCouldBeOfTypeConcrete(modeled_type* type, PyObject* pyRepresentation) { return true; } static void constructFromPythonArgumentsConcrete(Type* t, uint8_t* data, PyObject* args, PyObject* kwargs) { constructFromPythonArguments(data, (Type*)t->getBaseType(), args, kwargs); } Py_ssize_t mp_and_sq_length_concrete() { return specializeForTypeReturningSizeT((PyObject*)this, [&](auto& subtype) { return subtype.mp_and_sq_length_concrete(); }, type()->getBaseType()); } };
34.666667
145
0.680889
braxtonmckee
3c392fead2c793a0203aaeda00408eef499e15ab
1,623
cpp
C++
decoders/cpp/usage_inherited_types.cpp
lpsandaruwan/schema
1ee5cca5fa2733b216ed3fbd6ad5a59e8820565c
[ "MIT" ]
79
2019-02-19T10:16:04.000Z
2022-03-29T00:37:13.000Z
decoders/cpp/usage_inherited_types.cpp
lpsandaruwan/schema
1ee5cca5fa2733b216ed3fbd6ad5a59e8820565c
[ "MIT" ]
104
2019-03-31T20:01:02.000Z
2022-03-18T06:28:05.000Z
decoders/cpp/usage_inherited_types.cpp
lpsandaruwan/schema
1ee5cca5fa2733b216ed3fbd6ad5a59e8820565c
[ "MIT" ]
39
2019-04-01T02:24:59.000Z
2022-03-23T02:40:06.000Z
#include <iostream> #include "schema.h" #include "InheritedTypes.hpp" int main() { // const unsigned char encodedState[] = { 0, 0, 205, 244, 1, 1, 205, 32, 3, 193, 1, 0, 204, 200, 1, 205, 44, 1, 2, 166, 80, 108, 97, 121, 101, 114, 193, 2, 0, 100, 1, 204, 150, 2, 163, 66, 111, 116, 3, 204, 200, 193, 3, 213, 2, 3, 100, 193 }; const unsigned char encodedState[] = { 0, 0, 205, 244, 1, 1, 205, 32, 3, 193, 1, 0, 204, 200, 1, 205, 44, 1, 2, 166, 80, 108, 97, 121, 101, 114, 193, 2, 0, 100, 1, 204, 150, 2, 163, 66, 111, 116, 3, 204, 200, 193 }; InheritedTypes *p = new InheritedTypes(); std::cerr << "============ about to decode\n"; p->decode(encodedState, sizeof(encodedState) / sizeof(unsigned char)); std::cerr << "============ decoded ================================================================ \n"; std::cout << "state.entity.x = " << p->entity->x << std::endl; std::cout << "state.entity.y = " << p->entity->y << std::endl; std::cout << std::endl; std::cout << "state.player.name = " << p->player->name << std::endl; std::cout << "state.player.x = " << p->player->x << std::endl; std::cout << "state.player.y = " << p->player->y << std::endl; std::cout << std::endl; std::cout << "state.bot.name = " << p->bot->name << std::endl; std::cout << "state.bot.x = " << p->bot->x << std::endl; std::cout << "state.bot.y = " << p->bot->y << std::endl; std::cout << "state.bot.power = " << p->bot->power << std::endl; std::cout << std::endl; // std::cout << "state.any.power = " << p->any->power << std::endl; delete p; return 0; }
46.371429
246
0.510783
lpsandaruwan
3c3973b1261e81f56c154ba2a5ce46a351f7103b
8,561
cpp
C++
exa_test/test/buffered_stream_test.cpp
chronos38/exa
96092b34eebecf55d3fe8280a86fbe63bf546af3
[ "MIT" ]
null
null
null
exa_test/test/buffered_stream_test.cpp
chronos38/exa
96092b34eebecf55d3fe8280a86fbe63bf546af3
[ "MIT" ]
null
null
null
exa_test/test/buffered_stream_test.cpp
chronos38/exa
96092b34eebecf55d3fe8280a86fbe63bf546af3
[ "MIT" ]
null
null
null
#include <pch.h> #include <exa/buffered_stream.hpp> #include <exa/memory_stream.hpp> #include <exa/concepts.hpp> using namespace exa; using namespace testing; using namespace std::chrono_literals; namespace { auto create_stream(std::shared_ptr<stream> s = std::make_shared<memory_stream>(), std::streamsize bs = 4096) { return std::make_shared<buffered_stream>(s, bs); } auto create_data(size_t size = 1000) { std::vector<uint8_t> v(size, 0); for (size_t i = 0; i < size; ++i) { v[i] = static_cast<uint8_t>(i); } return v; } struct test_stream : public memory_stream { bool seekable = true; bool writable = true; bool readable = true; virtual bool can_seek() const override { return seekable; } virtual bool can_write() const override { return writable; } virtual bool can_read() const override { return readable; } }; struct concurrent_stream : public memory_stream, public lockable<std::mutex> { virtual void write(gsl::span<const uint8_t> b) override { exa::lock(*this, [&] { memory_stream::write(b); }); } virtual std::streamsize read(gsl::span<uint8_t> b) override { std::streamsize r = 0; exa::lock(*this, [&] { r = memory_stream::read(b); }); return r; } }; struct throw_stream : public memory_stream { virtual void write(gsl::span<const uint8_t> b) override { throw std::runtime_error("Operation not allowed."); } virtual std::streamsize read(gsl::span<uint8_t> b) override { throw std::runtime_error("Operation not allowed."); } virtual void flush() override { throw std::runtime_error("Operation not allowed."); } virtual std::streamoff seek(std::streamoff offset, seek_origin origin) override { throw std::runtime_error("Operation not allowed."); } }; struct tracking_stream : public stream { virtual ~tracking_stream() = default; mutable struct { int can_read = 0; int can_seek = 0; int can_write = 0; int size = 0; int position = 0; int flush = 0; int read = 0; int seek = 0; int write = 0; } called; std::shared_ptr<stream> stream; tracking_stream(std::shared_ptr<exa::stream> s) { stream = s; } // Inherited via stream virtual bool can_read() const override { called.can_read += 1; return stream->can_read(); } virtual bool can_seek() const override { called.can_seek += 1; return stream->can_seek(); } virtual bool can_write() const override { called.can_write += 1; return stream->can_write(); } virtual std::streamsize size() const override { called.size += 1; return stream->size(); } virtual void size(std::streamsize value) override { called.size += 1; stream->size(); } virtual std::streamoff position() const override { called.position += 1; return stream->position(); } virtual void position(std::streamoff value) override { called.position += 1; stream->position(); } virtual void flush() override { called.flush += 1; stream->flush(); } virtual std::streamsize read(gsl::span<uint8_t> buffer) override { called.read += 1; return stream->read(buffer); } virtual std::streamoff seek(std::streamoff offset, seek_origin origin) override { called.seek += 1; return stream->seek(offset, origin); } virtual void write(gsl::span<const uint8_t> buffer) override { called.write += 1; stream->write(buffer); } }; } TEST(buffered_stream_test, concurrent_operations_are_serialized) { auto v = create_data(); auto inner = std::make_shared<concurrent_stream>(); auto s = create_stream(inner, 1); std::array<std::future<void>, 4> tasks; for (size_t i = 0; i < tasks.size(); ++i) { tasks[i] = s->write_async(gsl::span<uint8_t>(v.data() + 250 * i, 250)); } for (auto& t : tasks) { ASSERT_NO_THROW(t.get()); } s->position(0); for (size_t i = 0; i < tasks.size(); ++i) { auto b = s->read_byte(); ASSERT_TRUE(b == i || b == static_cast<uint8_t>(i + 250) || b == static_cast<uint8_t>(i + 500) || b == static_cast<uint8_t>(i + 750)); } } TEST(buffered_stream_test, underlying_stream_throws_exception) { auto s = create_stream(std::make_shared<throw_stream>()); std::vector<uint8_t> v1(1); std::vector<uint8_t> v2(10000); ASSERT_THROW(s->read_async(v1).get(), std::runtime_error); ASSERT_THROW(s->write_async(v2).get(), std::runtime_error); s->write_byte(1); ASSERT_THROW(s->flush_async().get(), std::runtime_error); } TEST(buffered_stream_test, copy_to_requires_flushing_of_writes) { for (auto async : {false, true}) { auto s = create_stream(); auto v = create_data(); auto d = std::make_shared<memory_stream>(); s->write(v); s->position(0); v[0] = 42; s->write_byte(42); d->write_byte(42); if (async) { s->copy_to_async(d).get(); } else { s->copy_to(d); } auto r = d->to_array(); ASSERT_THAT(r, ContainerEq(v)); } } TEST(buffered_stream_test, copy_to_read_before_copy_copies_all_data) { std::vector<std::pair<bool, bool>> data = {{false, false}, {false, true}, {true, false}, {true, true}}; for (auto input : data) { auto v = create_data(); auto ts = std::make_shared<test_stream>(); ts->write(v); ts->position(0); ts->seekable = input.first; auto src = create_stream(ts, 100); src->read_byte(); auto dst = std::make_shared<memory_stream>(); if (input.second) { src->copy_to_async(dst).get(); } else { src->copy_to(dst); } std::vector<uint8_t> expected(v.size() - 1); std::copy(std::next(std::begin(v), 1), std::end(v), std::begin(expected)); auto array = dst->to_array(); ASSERT_THAT(array, ContainerEq(expected)); } } TEST(buffered_stream_test, should_not_flush_underyling_stream_if_readonly) { for (auto can_seek : {true, false}) { auto underlying = std::make_shared<test_stream>(); underlying->write(create_data(123)); underlying->position(0); underlying->seekable = can_seek; underlying->writable = false; auto tracker = std::make_shared<tracking_stream>(underlying); auto s = create_stream(tracker); s->read_byte(); s->flush(); ASSERT_THAT(tracker->called.flush, Eq(0)); s->flush_async().get(); ASSERT_THAT(tracker->called.flush, Eq(0)); } } TEST(buffered_stream_test, should_always_flush_underlying_stream_if_writable) { std::vector<std::pair<bool, bool>> v = {{true, true}, {true, false}, {false, true}, {false, false}}; for (auto input : v) { auto underlying = std::make_shared<test_stream>(); underlying->write(create_data(123)); underlying->position(0); underlying->readable = input.first; underlying->seekable = input.second; underlying->writable = true; auto tracker = std::make_shared<tracking_stream>(underlying); auto s = create_stream(tracker); s->flush(); ASSERT_THAT(tracker->called.flush, Eq(1)); s->flush_async().get(); ASSERT_THAT(tracker->called.flush, Eq(2)); s->write_byte(42); s->flush(); ASSERT_THAT(tracker->called.flush, Eq(3)); s->flush_async().get(); ASSERT_THAT(tracker->called.flush, Eq(4)); } }
25.479167
112
0.546665
chronos38
3c3f48f5f69d21fe79384a6f66533aee53ece3f7
1,725
inl
C++
AllGames/base/share_data/default_init_zip/shader/tech_textchannel-3.inl
DexianZhao/PhantomGameEngine
cf8e341d21e3973856d9f23ad0b1af9db831bac7
[ "MIT" ]
4
2019-11-08T00:15:13.000Z
2021-03-26T13:34:50.000Z
AllGames/base/share_data/default_init_zip/shader/tech_textchannel-3.inl
DexianZhao/PhantomGameEngine
cf8e341d21e3973856d9f23ad0b1af9db831bac7
[ "MIT" ]
4
2021-03-13T10:26:09.000Z
2021-03-13T10:45:35.000Z
AllGames/base/share_data/default_init_zip/shader/tech_textchannel-3.inl
DexianZhao/PhantomGameEngine
cf8e341d21e3973856d9f23ad0b1af9db831bac7
[ "MIT" ]
3
2020-06-01T01:53:05.000Z
2021-03-21T03:51:33.000Z
/*[DirectX9]*/ matrix MVP; int filterMin = 2; int filterMag = 2; int filterMip = 2; texture texture1; float4 textChannel; sampler sampler1 = sampler_state { Texture = <texture1>; MinFilter = POINT; MagFilter = POINT; MipFilter = POINT; }; struct VInput{ float4 Pos : POSITION; float3 Normal : Normal; float4 Color : COLOR0; float2 uv : TEXCOORD0; }; struct VOutput{ float4 Pos : POSITION; float2 uv : TEXCOORD0; float4 Color : TEXCOORD1; float3 channel : TEXCOORD2; }; VOutput Vshader(VInput input) { VOutput output; output.Pos = mul(input.Pos, MVP); output.Color = input.Color; output.uv = input.uv; output.channel = input.Normal; return output; } float4 Pshader(VOutput output) : COLOR0 { float4 ret = output.Color; float3 temp = tex2D(sampler1, output.uv).xyz;// * output.channel; float f = (temp.x + temp.y + temp.z); ret.xyz *= f; ret.a *= f; return ret; } technique main { pass P { VertexShader = compile vs_2_0 Vshader(); PixelShader = compile ps_2_0 Pshader(); } } /*[/DirectX9]*/ /*[OpenglES_Vertex]*/ //attribute in attribute vec4 inPosition; attribute vec2 inTexcoord; attribute vec4 inColor; // uniform mat4 MVP; varying vec2 passCoord; varying vec4 passColor0; void main() { passCoord = inTexcoord; passColor0 = vec4(inColor.b, inColor.g, inColor.r, inColor.a); gl_Position = MVP * inPosition; } /*[/OpenglES_Vertex]*/ /*[OpenglES_Pixel]*/ precision lowp float; varying vec4 passColor0; varying vec2 passCoord; uniform sampler2D texture1; uniform vec3 textChannel; void main() { vec3 v = texture2D(texture1, passCoord).xyz * textChannel; float f = (v.x+v.y+v.z); gl_FragColor = vec4(f*passColor0.xyz, f*passColor0.a*255.0); } /*[/OpenglES_Pixel]*/
19.827586
66
0.70087
DexianZhao
3c40b4a1cf4875babafc9fe982bfa08186acd959
806
cpp
C++
q10082v2.cpp
abraxaslee/ACM-ICPC
d8db31a4a2a36258bfba42a806b02bbf3eceaf2b
[ "MIT" ]
1
2018-03-19T05:18:49.000Z
2018-03-19T05:18:49.000Z
q10082v2.cpp
abraxaslee/ACM-ICPC
d8db31a4a2a36258bfba42a806b02bbf3eceaf2b
[ "MIT" ]
null
null
null
q10082v2.cpp
abraxaslee/ACM-ICPC
d8db31a4a2a36258bfba42a806b02bbf3eceaf2b
[ "MIT" ]
null
null
null
//q10082v2.cpp - 2011/09/09 //10082 - WERTYU //accepted at //run time = 0.012 #include <stdio.h> #include <string.h> using namespace std; int main(){ char ch[]={'`','1','2','3','4','5','6','7','8','9','0','-','=', 'Q','W','E','R','T','Y','U','I','O','P','[',']','\\', 'A','S','D','F','G','H','J','K','L',';','\'', 'Z','X','C','V','B','N','M',',','.','/'}; int maxLeng = 0; char inputChar[10000] = {0}; int i = 0, j = 0; while(gets(inputChar)!=NULL){ maxLeng = strlen(inputChar); for(i=0;i<maxLeng;i++){ if(inputChar[i]==' '){ printf(" "); }else{ for(j=0;j<strlen(ch);j++){ if(inputChar[i]==ch[j]){ printf("%c", ch[j-1]); break; } } } } printf("\n"); } return 0; }
23.028571
70
0.398263
abraxaslee
3c4215beae3902cf23ca9156ad3823a7fb9aec69
12,800
cpp
C++
src/goto-symex/build_goto_trace.cpp
dan-blank/yogar-cbmc
05b4f056b585b65828acf39546c866379dca6549
[ "MIT" ]
1
2017-07-25T02:44:56.000Z
2017-07-25T02:44:56.000Z
src/goto-symex/build_goto_trace.cpp
dan-blank/yogar-cbmc
05b4f056b585b65828acf39546c866379dca6549
[ "MIT" ]
1
2017-02-22T14:35:19.000Z
2017-02-27T08:49:58.000Z
src/goto-symex/build_goto_trace.cpp
dan-blank/yogar-cbmc
05b4f056b585b65828acf39546c866379dca6549
[ "MIT" ]
4
2019-01-19T03:32:21.000Z
2021-12-20T14:25:19.000Z
/*******************************************************************\ Module: Traces of GOTO Programs Author: Daniel Kroening Date: July 2005 \*******************************************************************/ #include <cassert> #include <util/threeval.h> #include <util/simplify_expr.h> #include <util/arith_tools.h> #include <solvers/prop/prop_conv.h> #include <solvers/prop/prop.h> #include "partial_order_concurrency.h" #include "build_goto_trace.h" /*******************************************************************\ Function: build_full_lhs_rec Inputs: Outputs: Purpose: \*******************************************************************/ exprt build_full_lhs_rec( const prop_convt &prop_conv, const namespacet &ns, const exprt &src_original, // original identifiers const exprt &src_ssa) // renamed identifiers { if(src_ssa.id()!=src_original.id()) return src_original; const irep_idt id=src_original.id(); if(id==ID_index) { // get index value from src_ssa exprt index_value=prop_conv.get(to_index_expr(src_ssa).index()); if(index_value.is_not_nil()) { simplify(index_value, ns); index_exprt tmp=to_index_expr(src_original); tmp.index()=index_value; tmp.array()= build_full_lhs_rec(prop_conv, ns, to_index_expr(src_original).array(), to_index_expr(src_ssa).array()); return tmp; } return src_original; } else if(id==ID_member) { member_exprt tmp=to_member_expr(src_original); tmp.struct_op()=build_full_lhs_rec( prop_conv, ns, to_member_expr(src_original).struct_op(), to_member_expr(src_ssa).struct_op()); } else if(id==ID_if) { if_exprt tmp2=to_if_expr(src_original); tmp2.false_case()=build_full_lhs_rec(prop_conv, ns, tmp2.false_case(), to_if_expr(src_ssa).false_case()); tmp2.true_case()=build_full_lhs_rec(prop_conv, ns, tmp2.true_case(), to_if_expr(src_ssa).true_case()); exprt tmp=prop_conv.get(to_if_expr(src_ssa).cond()); if(tmp.is_true()) return tmp2.true_case(); else if(tmp.is_false()) return tmp2.false_case(); else return tmp2; } else if(id==ID_typecast) { typecast_exprt tmp=to_typecast_expr(src_original); tmp.op()=build_full_lhs_rec(prop_conv, ns, to_typecast_expr(src_original).op(), to_typecast_expr(src_ssa).op()); return tmp; } else if(id==ID_byte_extract_little_endian || id==ID_byte_extract_big_endian) { exprt tmp=src_original; assert(tmp.operands().size()==2); tmp.op0()=build_full_lhs_rec(prop_conv, ns, tmp.op0(), src_ssa.op0()); // re-write into big case-split } return src_original; } /*******************************************************************\ Function: adjust_lhs_object Inputs: Outputs: Purpose: \*******************************************************************/ exprt adjust_lhs_object( const prop_convt &prop_conv, const namespacet &ns, const exprt &src) { return nil_exprt(); } /*******************************************************************\ Function: build_goto_trace Inputs: Outputs: Purpose: \*******************************************************************/ void build_goto_trace_backup( const symex_target_equationt &target, const prop_convt &prop_conv, const namespacet &ns, goto_tracet &goto_trace) { // We need to re-sort the steps according to their clock. // Furthermore, read-events need to occur before write // events with the same clock. typedef std::map<mp_integer, goto_tracet::stepst> time_mapt; time_mapt time_map; mp_integer current_time=0; for(symex_target_equationt::SSA_stepst::const_iterator it=target.SSA_steps.begin(); it!=target.SSA_steps.end(); it++) { const symex_target_equationt::SSA_stept &SSA_step=*it; if(prop_conv.l_get(SSA_step.guard_literal)!=tvt(true)) continue; if(it->is_constraint() || it->is_spawn()) continue; else if(it->is_atomic_begin()) { // for atomic sections the timing can only be determined once we see // a shared read or write (if there is none, the time will be // reverted to the time before entering the atomic section); we thus // use a temporary negative time slot to gather all events current_time*=-1; continue; } else if(it->is_shared_read() || it->is_shared_write() || it->is_atomic_end()) { mp_integer time_before=current_time; if(it->is_shared_read() || it->is_shared_write()) { // these are just used to get the time stamp exprt clock_value=prop_conv.get( symbol_exprt(partial_order_concurrencyt::rw_clock_id(it))); to_integer(clock_value, current_time); } else if(it->is_atomic_end() && current_time<0) current_time*=-1; assert(current_time>=0); // move any steps gathered in an atomic section if(time_before<0) { time_mapt::iterator entry= time_map.insert(std::make_pair( current_time, goto_tracet::stepst())).first; entry->second.splice(entry->second.end(), time_map[time_before]); time_map.erase(time_before); } continue; } // drop hidden assignments if(it->is_assignment() && SSA_step.assignment_type!=symex_target_equationt::STATE) continue; goto_tracet::stepst &steps=time_map[current_time]; steps.push_back(goto_trace_stept()); goto_trace_stept &goto_trace_step=steps.back(); goto_trace_step.thread_nr=SSA_step.source.thread_nr; goto_trace_step.pc=SSA_step.source.pc; goto_trace_step.comment=SSA_step.comment; goto_trace_step.lhs_object=SSA_step.original_lhs_object; goto_trace_step.type=SSA_step.type; goto_trace_step.format_string=SSA_step.format_string; goto_trace_step.io_id=SSA_step.io_id; goto_trace_step.formatted=SSA_step.formatted; goto_trace_step.identifier=SSA_step.identifier; if(SSA_step.original_full_lhs.is_not_nil()) goto_trace_step.full_lhs= build_full_lhs_rec( prop_conv, ns, SSA_step.original_full_lhs, SSA_step.ssa_full_lhs); if(SSA_step.ssa_lhs.is_not_nil()) goto_trace_step.lhs_object_value=prop_conv.get(SSA_step.ssa_lhs); if(SSA_step.ssa_full_lhs.is_not_nil()) { goto_trace_step.full_lhs_value=prop_conv.get(SSA_step.ssa_full_lhs); simplify(goto_trace_step.full_lhs_value, ns); } for(std::list<exprt>::const_iterator j=SSA_step.converted_io_args.begin(); j!=SSA_step.converted_io_args.end(); j++) { const exprt &arg=*j; if(arg.is_constant() || arg.id()==ID_string_constant) goto_trace_step.io_args.push_back(arg); else { exprt tmp=prop_conv.get(arg); goto_trace_step.io_args.push_back(tmp); } } if(SSA_step.is_assert() || SSA_step.is_assume()) { goto_trace_step.cond_expr=SSA_step.cond_expr; goto_trace_step.cond_value= prop_conv.l_get(SSA_step.cond_literal).is_true(); } else if(SSA_step.is_location() && SSA_step.source.pc->is_goto()) { goto_trace_step.cond_expr=SSA_step.source.pc->guard; const bool backwards=SSA_step.source.pc->is_backwards_goto(); symex_target_equationt::SSA_stepst::const_iterator next=it; ++next; assert(next!=target.SSA_steps.end()); // goto was taken if backwards and next is enabled or forward // and next is not active; // there is an ambiguity here if a forward goto is to the next // instruction, which we simply ignore for now goto_trace_step.goto_taken= backwards== (prop_conv.l_get(next->guard_literal)==tvt(true)); } } // Now assemble into a single goto_trace. // This expoits sorted-ness of the map. for(time_mapt::iterator t_it=time_map.begin(); t_it!=time_map.end(); t_it++) { goto_trace.steps.splice(goto_trace.steps.end(), t_it->second); } // produce the step numbers unsigned step_nr=0; for(goto_tracet::stepst::iterator s_it=goto_trace.steps.begin(); s_it!=goto_trace.steps.end(); s_it++) s_it->step_nr=++step_nr; // Now delete anything after failed assertion for(goto_tracet::stepst::iterator s_it1=goto_trace.steps.begin(); s_it1!=goto_trace.steps.end(); s_it1++) if(s_it1->is_assert() && !s_it1->cond_value) { s_it1++; for(goto_tracet::stepst::iterator s_it2=s_it1; s_it2!=goto_trace.steps.end(); s_it2=goto_trace.steps.erase(s_it2)); break; } } /*******************************************************************\ Function: build_goto_trace Inputs: Outputs: Purpose: \*******************************************************************/ void build_goto_trace( const symex_target_equationt &target, const prop_convt &prop_conv, const namespacet &ns, goto_tracet &goto_trace) { // We need to re-sort the steps according to their clock. // Furthermore, read-events need to occur before write // events with the same clock. for(symex_target_equationt::SSA_stepst::const_iterator it=target.SSA_steps.begin(); it!=target.SSA_steps.end(); it++) { const symex_target_equationt::SSA_stept &SSA_step=*it; if(prop_conv.l_get(SSA_step.guard_literal)!=tvt(true)) continue; if(it->is_constraint() || it->is_spawn()) continue; // drop hidden assignments if(it->is_assignment() && SSA_step.assignment_type!=symex_target_equationt::STATE) continue; goto_tracet::stepst &steps=goto_trace.steps; steps.push_back(goto_trace_stept()); goto_trace_stept &goto_trace_step=steps.back(); goto_trace_step.thread_nr=SSA_step.source.thread_nr; goto_trace_step.pc=SSA_step.source.pc; goto_trace_step.comment=SSA_step.comment; goto_trace_step.lhs_object=SSA_step.original_lhs_object; goto_trace_step.type=SSA_step.type; goto_trace_step.format_string=SSA_step.format_string; goto_trace_step.io_id=SSA_step.io_id; goto_trace_step.formatted=SSA_step.formatted; goto_trace_step.identifier=SSA_step.identifier; if(SSA_step.original_full_lhs.is_not_nil()) goto_trace_step.full_lhs= build_full_lhs_rec( prop_conv, ns, SSA_step.original_full_lhs, SSA_step.ssa_full_lhs); if(SSA_step.ssa_lhs.is_not_nil()) goto_trace_step.lhs_object_value=prop_conv.get(SSA_step.ssa_lhs); if(SSA_step.ssa_full_lhs.is_not_nil()) { goto_trace_step.full_lhs_value=prop_conv.get(SSA_step.ssa_full_lhs); simplify(goto_trace_step.full_lhs_value, ns); } for(std::list<exprt>::const_iterator j=SSA_step.converted_io_args.begin(); j!=SSA_step.converted_io_args.end(); j++) { const exprt &arg=*j; if(arg.is_constant() || arg.id()==ID_string_constant) goto_trace_step.io_args.push_back(arg); else { exprt tmp=prop_conv.get(arg); goto_trace_step.io_args.push_back(tmp); } } if(SSA_step.is_assert() || SSA_step.is_assume()) { goto_trace_step.cond_expr=SSA_step.cond_expr; goto_trace_step.cond_value= prop_conv.l_get(SSA_step.cond_literal).is_true(); } else if(SSA_step.is_location() && SSA_step.source.pc->is_goto()) { goto_trace_step.cond_expr=SSA_step.source.pc->guard; const bool backwards=SSA_step.source.pc->is_backwards_goto(); symex_target_equationt::SSA_stepst::const_iterator next=it; ++next; assert(next!=target.SSA_steps.end()); // goto was taken if backwards and next is enabled or forward // and next is not active; // there is an ambiguity here if a forward goto is to the next // instruction, which we simply ignore for now goto_trace_step.goto_taken= backwards== (prop_conv.l_get(next->guard_literal)==tvt(true)); } } // produce the step numbers unsigned step_nr=0; for(goto_tracet::stepst::iterator s_it=goto_trace.steps.begin(); s_it!=goto_trace.steps.end(); s_it++) s_it->step_nr=++step_nr; // Now delete anything after failed assertion /* for(goto_tracet::stepst::iterator s_it1=goto_trace.steps.begin(); s_it1!=goto_trace.steps.end(); s_it1++) if(s_it1->is_assert() && !s_it1->cond_value) { s_it1++; for(goto_tracet::stepst::iterator s_it2=s_it1; s_it2!=goto_trace.steps.end(); s_it2=goto_trace.steps.erase(s_it2)); break; }*/ }
27.408994
86
0.634375
dan-blank
3c4a455f6d75898195fe66e4ad6918840f131cb6
2,356
cpp
C++
src/register/SegmentRegister.cpp
openx86/emulator
829454a2dbc99ffa3ccdf81f7473e69f8b8ce896
[ "Apache-2.0" ]
1
2022-01-16T18:24:32.000Z
2022-01-16T18:24:32.000Z
src/register/SegmentRegister.cpp
openx86/emulator
829454a2dbc99ffa3ccdf81f7473e69f8b8ce896
[ "Apache-2.0" ]
null
null
null
src/register/SegmentRegister.cpp
openx86/emulator
829454a2dbc99ffa3ccdf81f7473e69f8b8ce896
[ "Apache-2.0" ]
null
null
null
// // Created by 86759 on 2022-01-14. // #include "SegmentRegister.h" #include "SystemAddressRegister.h" segment_descriptor_t load_descriptor(uint32_t value) { uint32_t descriptor_index = value >> 3; uint32_t offset = descriptor_index * 64/8; const auto address = SystemAddressRegister::GDT + offset; const auto descriptor = (uint64_t)*address; segment_descriptor_t segment_descriptor; segment_descriptor.base = ((descriptor & 0x1111'0000'0000'0000) >> 48 << 0) + ((descriptor & 0x0000'0000'0000'0011) >> 0 << 15) + ((descriptor & 0x0000'0000'1100'0000) >> 24 << 23) + 0; segment_descriptor.limit = ((descriptor & 0x0000'1111'0000'0000) >> 32 << 0) + ((descriptor & 0x0000'0000'0000'0011) >> 16 << 15) + 0; // TODO: set remain bits } uint16_t SegmentRegister::CS_r = 0xF000; uint16_t SegmentRegister::SS_r = 0x0000; uint16_t SegmentRegister::DS_r = 0x0000; uint16_t SegmentRegister::ES_r = 0x0000; uint16_t SegmentRegister::FS_r = 0x0000; uint16_t SegmentRegister::GS_r = 0x0000; segment_descriptor_t SegmentRegister::CS_descriptor; segment_descriptor_t SegmentRegister::SS_descriptor; segment_descriptor_t SegmentRegister::DS_descriptor; segment_descriptor_t SegmentRegister::ES_descriptor; segment_descriptor_t SegmentRegister::FS_descriptor; segment_descriptor_t SegmentRegister::GS_descriptor; uint16_t SegmentRegister::CS() { return CS_r; } uint16_t SegmentRegister::SS() { return SS_r; } uint16_t SegmentRegister::DS() { return DS_r; } uint16_t SegmentRegister::ES() { return ES_r; } uint16_t SegmentRegister::FS() { return FS_r; } uint16_t SegmentRegister::GS() { return GS_r; } void SegmentRegister::CS(uint16_t value) { CS_r = value; CS_descriptor = load_descriptor(value); } void SegmentRegister::SS(uint16_t value) { SS_r = value; SS_descriptor = load_descriptor(value); } void SegmentRegister::DS(uint16_t value) { DS_r = value; DS_descriptor = load_descriptor(value); } void SegmentRegister::ES(uint16_t value) { ES_r = value; ES_descriptor = load_descriptor(value); } void SegmentRegister::FS(uint16_t value) { FS_r = value; FS_descriptor = load_descriptor(value); } void SegmentRegister::GS(uint16_t value) { GS_r = value; GS_descriptor = load_descriptor(value); }
44.45283
99
0.712224
openx86
3c4cef2edac1f22cb082cf3001941ea236bb1a3c
796
cpp
C++
Sources/Folders/ExtraCodes/FishCodes.cpp
MirayXS/Vapecord-ACNL-Plugin
247eb270dfe849eda325cc0c6adc5498d51de3ef
[ "MIT" ]
52
2020-01-17T08:12:04.000Z
2022-03-19T20:02:57.000Z
Sources/Folders/ExtraCodes/FishCodes.cpp
MirayXS/Vapecord-ACNL-Plugin
247eb270dfe849eda325cc0c6adc5498d51de3ef
[ "MIT" ]
67
2020-05-06T04:47:27.000Z
2022-03-31T16:25:19.000Z
Sources/Folders/ExtraCodes/FishCodes.cpp
MirayXS/Vapecord-ACNL-Plugin
247eb270dfe849eda325cc0c6adc5498d51de3ef
[ "MIT" ]
7
2021-01-20T17:42:25.000Z
2022-03-08T09:29:42.000Z
#include "cheats.hpp" #include "Helpers/Address.hpp" namespace CTRPluginFramework { //Fish Byte Always void FishAlwaysBiteRightAway(MenuEntry *entry) { static const Address fishbite(0x1EA844, 0x1EA288, 0x1EA864, 0x1EA864, 0x1EA7A0, 0x1EA7A0, 0x1EA76C, 0x1EA76C); if(entry->WasJustActivated()) Process::Patch(fishbite.addr, 0xE3A0005A); else if(!entry->IsActivated()) Process::Patch(fishbite.addr, 0xE0800100); } //Fish Can't Be Scared void FishCantBeScared(MenuEntry *entry) { static const Address fishscare(0x1EAB14, 0x1EA558, 0x1EAB34, 0x1EAB34, 0x1EAA70, 0x1EAA70, 0x1EAA3C, 0x1EAA3C); if(entry->WasJustActivated()) Process::Patch(fishscare.addr, 0xE3500001); else if(!entry->IsActivated()) Process::Patch(fishscare.addr, 0xE3500000); } }
36.181818
114
0.729899
MirayXS
3c4d485b8d037c6db1a13c41aead2be4e41f4172
1,300
cc
C++
below2.1/okviri.cc
danzel-py/Kattis-Problem-Archive
bce1929d654b1bceb104f96d68c74349273dd1ff
[ "Apache-2.0" ]
null
null
null
below2.1/okviri.cc
danzel-py/Kattis-Problem-Archive
bce1929d654b1bceb104f96d68c74349273dd1ff
[ "Apache-2.0" ]
null
null
null
below2.1/okviri.cc
danzel-py/Kattis-Problem-Archive
bce1929d654b1bceb104f96d68c74349273dd1ff
[ "Apache-2.0" ]
null
null
null
#include <iostream> using namespace std; int main(){ string str; cin>>str; for (int i = 0; i < str.length(); i++) { if(i % 3 == 2){ cout<<"..*."; }else{ cout<<"..#."; } } cout<<".\n"; for (int i = 0; i < str.length(); i++) { if(i % 3 == 2){ cout<<".*.*"; }else{ cout<<".#.#"; } }cout<<".\n"; // 3rd line; for (int i = 0; i < str.length(); i++) { if(i % 3 == 2){ cout<<"*."<<str[i]<<"."; }else{ if(i!=0){ if((i-1)%3 == 2){ cout<<"*"; } else{ cout<<"#"; } } else{ cout<<"#"; } cout<<"."<<str[i]<<"."; } } if(str.length()%3 == 0){ cout<<"*\n"; } else{ cout<<"#\n"; } // 3rd line ends for (int i = 0; i < str.length(); i++) { if(i % 3 == 2){ cout<<".*.*"; }else{ cout<<".#.#"; } } cout<<".\n"; for (int i = 0; i < str.length(); i++) { if(i % 3 == 2){ cout<<"..*."; }else{ cout<<"..#."; } } cout<<".\n"; return 0; }
18.309859
42
0.264615
danzel-py
3c4f3bc1c91e31be87122fea0d5e67ba119b3d43
2,983
cpp
C++
Chapter03/LibraryBasic/Book.cpp
linuxemb/datastructure
efc9e2ef897bf1f626b67d08c3892c8f41a008f9
[ "MIT" ]
25
2018-04-04T15:36:26.000Z
2021-11-08T13:12:21.000Z
Chapter03/LibraryBasic/Book.cpp
linuxemb/datastructure
efc9e2ef897bf1f626b67d08c3892c8f41a008f9
[ "MIT" ]
1
2021-06-29T04:14:07.000Z
2021-07-05T19:48:36.000Z
Chapter03/LibraryBasic/Book.cpp
linuxemb/datastructure
efc9e2ef897bf1f626b67d08c3892c8f41a008f9
[ "MIT" ]
16
2018-04-04T15:36:42.000Z
2022-02-07T08:31:16.000Z
#include <Set> #include <Map> #include <List> #include <String> #include <FStream> using namespace std; #include "Book.h" #include "Customer.h" #include "Library.h" int Book::MaxBookId = 0; Book::Book(void) { // Empty. } Book::Book(const string& author, const string& title) :m_bookId(++MaxBookId), m_author(author), m_title(title) { // Empty. } /* Book::Book(const Book& book) :m_bookId(book.m_bookId), m_author(book.m_author), m_title(book.m_title), m_borrowed(book.m_borrowed), m_customerId(book.m_customerId), m_reservationList(book.m_reservationList) { // Empty. } Book& Book::operator=(const Book& book) { m_bookId = book.m_bookId; m_author = book.m_author; m_title = book.m_title; m_borrowed = book.m_borrowed; m_customerId = book.m_customerId; m_reservationList = book.m_reservationList; return *this; } */ void Book::read(ifstream& inStream) { inStream.read((char*) &m_bookId, sizeof m_bookId); getline(inStream, m_author); getline(inStream, m_title); inStream.read((char*)&m_borrowed, sizeof m_borrowed); inStream.read((char*) &m_customerId, sizeof m_customerId); { int reserveListSize; inStream.read((char*) &reserveListSize, sizeof reserveListSize); for (int count = 0; count < reserveListSize; ++count) { int customerId; inStream.read((char*) &customerId, sizeof customerId); m_reservationList.push_back(customerId); } } } void Book::write(ofstream& outStream) const { outStream.write((char*) &m_bookId, sizeof m_bookId); outStream << m_author << endl; outStream << m_title << endl; outStream.write((char*)&m_borrowed, sizeof m_borrowed); outStream.write((char*) &m_customerId, sizeof m_customerId); { int reserveListSize = m_reservationList.size(); outStream.write((char*) &reserveListSize, sizeof reserveListSize); for (int customerId : m_reservationList) { outStream.write((char*) &customerId, sizeof customerId); } } } void Book::borrowBook(int customerId) { m_borrowed = true; m_customerId = customerId; } int Book::reserveBook(int customerId) { m_reservationList.push_back(customerId); return m_reservationList.size(); } void Book::returnBook() { m_borrowed = false; } void Book::unreserveBook(int customerId) { m_reservationList.remove(customerId); } ostream& operator<<(ostream& outStream, const Book& book) { outStream << "\"" << book.m_title << "\" by " << book.m_author; if (book.m_borrowed) { outStream << endl << " Borrowed by: " << Library::s_customerMap[book.m_customerId].name() << "."; } if (!book.m_reservationList.empty()) { outStream << endl << " Reserved by: "; bool first = true; for (int customerId : book.m_reservationList) { outStream << (first ? "" : ",") << Library::s_customerMap[customerId].name(); first = false; } outStream << "."; } return outStream; }
23.304688
65
0.663091
linuxemb
3c50d0e01474815b4c2160695d4db8a48f26b07a
1,107
hpp
C++
Server/Server.hpp
Stun3R/Epitech-R-Type
3d6ef3bd5a937f50de996de2395c43c5115f0776
[ "MIT" ]
null
null
null
Server/Server.hpp
Stun3R/Epitech-R-Type
3d6ef3bd5a937f50de996de2395c43c5115f0776
[ "MIT" ]
null
null
null
Server/Server.hpp
Stun3R/Epitech-R-Type
3d6ef3bd5a937f50de996de2395c43c5115f0776
[ "MIT" ]
null
null
null
/* ** EPITECH PROJECT, 2021 ** R-TYPE ** File description: ** Created by stun3r, */ #ifndef SERVER_HPP #define SERVER_HPP #include "Room/Room.hpp" class Server { public: Server(); ~Server(); void run(); void startReceive(); void refresh(); private: void handleReceive(const boost::system::error_code &, std::size_t); void handleSend(std::shared_ptr<std::string>, const boost::system::error_code &, std::size_t); bool hasRoom(const std::string &); Room *getRoomsByName(const std::string &) const; void createRoom(const boost::property_tree::ptree &); void joinRoom(const boost::property_tree::ptree &); void destroyRoom(const boost::property_tree::ptree &); void listRoom(const boost::property_tree::ptree &); void roomReceive(const boost::property_tree::ptree &); std::set<Room *> _rooms; boost::asio::io_service _ioservice; std::shared_ptr<boost::asio::ip::udp::socket> _socket; boost::asio::ip::udp::endpoint _endpoint; std::array<char, 128> _buffer; std::map<std::string, std::function<void(const boost::property_tree::ptree &)>> _command; }; #endif //SERVER_HPP
20.5
95
0.709124
Stun3R
3c594b0eb36a7306dbd96c581c3e8e92eb371ce0
3,421
cpp
C++
src/core/tree/double_property.cpp
lii-enac/djnn-cpp
f27c5ba3186186ee22c93ae91c16063556e929b6
[ "BSD-2-Clause" ]
4
2018-09-11T14:27:57.000Z
2019-12-16T21:06:26.000Z
src/core/tree/double_property.cpp
lii-enac/djnn-cpp
f27c5ba3186186ee22c93ae91c16063556e929b6
[ "BSD-2-Clause" ]
null
null
null
src/core/tree/double_property.cpp
lii-enac/djnn-cpp
f27c5ba3186186ee22c93ae91c16063556e929b6
[ "BSD-2-Clause" ]
2
2018-06-11T14:15:30.000Z
2019-01-09T12:23:35.000Z
/* * djnn v2 * * The copyright holders for the contents of this file are: * Ecole Nationale de l'Aviation Civile, France (2018-2019) * See file "license.terms" for the rights and conditions * defined by copyright holders. * * * Contributors: * Mathieu Magnaudet <[email protected]> * Stephane Conversy <[email protected]> * */ #include <stdexcept> #include "double_property.h" #include "core/serializer/serializer.h" #include "core/utils/error.h" #include "core/utils/djnn_dynamic_cast.h" #if !defined(DJNN_NO_DEBUG) || !defined(DJNN_NO_SERIALIZE) #include "core/utils/iostream.h" #endif namespace djnn { double getDouble (CoreProcess* p) { DoubleProperty *dp = djnn_dynamic_cast<DoubleProperty*> (p); if (dp != nullptr) return dp->get_value(); else warning (p, "getDouble only works on double properties"); return 0; } void setDouble (CoreProcess* p, double v) { DoubleProperty *dp = djnn_dynamic_cast<DoubleProperty*> (p); if (dp != nullptr) dp->set_value(v, true); else warning (p, "setDouble only works on double properties"); } void AbstractDoubleProperty::set_value (int v, bool propagate) { set_value((double)v, propagate); } void AbstractDoubleProperty::set_value (double v, bool propagate) { get_ref_value() = v; if (is_activable () && propagate) { notify_activation (); notify_parent (); } } void AbstractDoubleProperty::set_value (bool v, bool propagate) { set_value((double)(v ? 1 : 0), propagate); } void AbstractDoubleProperty::set_value (const string& v, bool propagate) { double oldVal = get_value(); try { if (!v.empty ()) { set_value((double)stof (v), propagate); } } catch (const std::invalid_argument& ia) { get_ref_value() = oldVal; warning (this, "failed to convert the string \"" + v + "\" into a double property value\n"); } } void AbstractDoubleProperty::set_value (CoreProcess* v, bool propagate) { warning (this, "undefined conversion from Process to Double\n"); } #ifndef DJNN_NO_DEBUG void AbstractDoubleProperty::dump (int level) { loginfonofl ( (get_parent () ? get_parent ()->find_child_name(this) : get_name ()) + " [ " + get_string_value() + " ]"); //std::cout << (get_parent () ? get_parent ()->find_child_name(this) : get_name ()) << " [ " << get_value() << " ]"; } #endif #ifndef DJNN_NO_SERIALIZE void AbstractDoubleProperty::serialize (const djnn::string& format) { AbstractSerializer::pre_serialize(this, format); AbstractSerializer::serializer->start ("core:doubleproperty"); AbstractSerializer::serializer->text_attribute ("id", get_name ()); AbstractSerializer::serializer->float_attribute ("value", get_value ()); AbstractSerializer::serializer->end (); AbstractSerializer::post_serialize(this); } #endif DoubleProperty* DoubleProperty::impl_clone (map<CoreProcess*, CoreProcess*>& origs_clones) { auto res = new DoubleProperty (nullptr, get_name (), get_value()); origs_clones[this] = res; return res; } DoublePropertyProxy* DoublePropertyProxy::impl_clone (map<CoreProcess*, CoreProcess*>& origs_clones) { auto res = new DoublePropertyProxy (nullptr, get_name (), get_ref_value()); origs_clones[this] = res; return res; } }
25.529851
124
0.665303
lii-enac
3c596be6e3144042d1bed3be644e4c3d00aa4b60
1,224
cpp
C++
exploringBB/chp10/cgicc/LED.cpp
chaicko/ExploringBeagleBone
56528557e7d9a328602c65f1b2d837906cb08952
[ "Apache-2.0" ]
1
2019-05-28T18:38:29.000Z
2019-05-28T18:38:29.000Z
exploringBB/chp10/cgicc/LED.cpp
chaicko/ExploringBeagleBone
56528557e7d9a328602c65f1b2d837906cb08952
[ "Apache-2.0" ]
null
null
null
exploringBB/chp10/cgicc/LED.cpp
chaicko/ExploringBeagleBone
56528557e7d9a328602c65f1b2d837906cb08952
[ "Apache-2.0" ]
null
null
null
#include "LED.h" LED::LED(int number){ this->number = number; // much easier with C++11 using to_string(number) ostringstream s; // using a stream to contruct the path s << LED_PATH << number; //append LED number to LED_PATH path = string(s.str()); //convert back from stream to string } void LED::writeLED(string filename, string value){ ofstream fs; fs.open((path + filename).c_str()); fs << value; fs.close(); } void LED::removeTrigger(){ writeLED("/trigger", "none"); } void LED::turnOn(){ cout << "Turning LED" << number << " on." << endl; removeTrigger(); writeLED("/brightness", "1"); } void LED::turnOff(){ cout << "Turning LED" << number << " off." << endl; removeTrigger(); writeLED("/brightness", "0"); } void LED::flash(string delayms = "50"){ cout << "Making LED" << number << " flash." << endl; writeLED("/trigger", "timer"); writeLED("/delay_on", delayms); writeLED("/delay_off", delayms); } void LED::outputState(){ ifstream fs; fs.open( (path + "/trigger").c_str()); string line; while(getline(fs,line)) cout << line << endl; fs.close(); } LED::~LED(){ cout << "destroying the LED with path: " << path << endl; }
23.538462
66
0.601307
chaicko
3c5f504f277e4122e1395f9e39f9dd30f9e43831
1,587
cc
C++
test/h265_sps_scc_extension_parser_unittest.cc
sivapatibandla/h265nal
d128722c717e0656ae64a9fc386c9725bcd26da3
[ "BSD-3-Clause" ]
6
2020-10-05T21:55:52.000Z
2022-03-20T13:28:21.000Z
test/h265_sps_scc_extension_parser_unittest.cc
sivapatibandla/h265nal
d128722c717e0656ae64a9fc386c9725bcd26da3
[ "BSD-3-Clause" ]
5
2020-10-26T13:48:11.000Z
2022-01-28T01:47:19.000Z
test/h265_sps_scc_extension_parser_unittest.cc
sivapatibandla/h265nal
d128722c717e0656ae64a9fc386c9725bcd26da3
[ "BSD-3-Clause" ]
4
2020-10-06T21:08:59.000Z
2022-03-21T06:05:55.000Z
/* * Copyright (c) Facebook, Inc. and its affiliates. */ #include "h265_sps_scc_extension_parser.h" #include <gmock/gmock.h> #include <gtest/gtest.h> #include "h265_common.h" #include "rtc_base/arraysize.h" #include "rtc_base/bit_buffer.h" namespace h265nal { class H265SpsSccExtensionParserTest : public ::testing::Test { public: H265SpsSccExtensionParserTest() {} ~H265SpsSccExtensionParserTest() override {} }; TEST_F(H265SpsSccExtensionParserTest, TestSampleSpsSccExtension) { // sps_scc_extension // fuzzer::conv: data const uint8_t buffer[] = {0x80}; // fuzzer::conv: begin auto sps_scc_extension = H265SpsSccExtensionParser::ParseSpsSccExtension( buffer, arraysize(buffer), /* sps->chroma_format_idc */ 1, /* sps->bit_depth_luma_minus8 */ 0, /* sps->bit_depth_chroma_minus8 */ 0); // fuzzer::conv: end EXPECT_TRUE(sps_scc_extension != nullptr); EXPECT_EQ(1, sps_scc_extension->sps_curr_pic_ref_enabled_flag); EXPECT_EQ(0, sps_scc_extension->palette_mode_enabled_flag); EXPECT_EQ(0, sps_scc_extension->palette_max_size); EXPECT_EQ(0, sps_scc_extension->delta_palette_max_predictor_size); EXPECT_EQ(0, sps_scc_extension->sps_palette_predictor_initializers_present_flag); EXPECT_EQ(0, sps_scc_extension->sps_num_palette_predictor_initializers_minus1); EXPECT_EQ(0, sps_scc_extension->sps_palette_predictor_initializers.size()); EXPECT_EQ(0, sps_scc_extension->motion_vector_resolution_control_idc); EXPECT_EQ(0, sps_scc_extension->intra_boundary_filtering_disabled_flag); } } // namespace h265nal
33.0625
80
0.768746
sivapatibandla
3c6523550f9e948f6130c60fbdaeed277dbce5a3
1,353
hpp
C++
sdk/structs.hpp
Nixer1337/gmod-sdk
482c66989e0f55bd7b52bb0bee48b0b0b2bb893f
[ "MIT" ]
6
2020-03-30T05:11:50.000Z
2021-02-08T02:26:29.000Z
sdk/structs.hpp
Nixer1337/gmod-sdk
482c66989e0f55bd7b52bb0bee48b0b0b2bb893f
[ "MIT" ]
1
2020-12-05T11:18:51.000Z
2020-12-27T18:34:22.000Z
sdk/structs.hpp
Nixer1337/gmod-sdk
482c66989e0f55bd7b52bb0bee48b0b0b2bb893f
[ "MIT" ]
2
2020-03-24T15:27:38.000Z
2022-03-03T17:32:31.000Z
#pragma once #include "vfunc.hpp" #include "../utilities/utilities.hpp" #include "../utilities/math.hpp" #include "../utilities/netvars.hpp" #define NETVAR(type, name, table, netvar) \ type& name##() const { \ static const auto _##name = Netvars::GetOffset(hash::fnv1a_32(table), hash::fnv1a_32(netvar)); \ return *(type*)(uintptr_t(this) + _##name); \ } class CWeapon; class CEntity { public: int GetFlags(); size_t GetIndex(); NETVAR(uintptr_t, m_hActiveWeapon, "DT_BaseCombatCharacter", "m_hActiveWeapon"); NETVAR(uintptr_t, m_vecOrigin, "DT_BaseEntity", "m_vecOrigin"); CWeapon* GetActiveWeapon(); const char* GetClassName(); bool IsNPC(); bool IsPlayer(); bool IsDormant(); bool IsAlive(); int GetHealth(); int GetMaxHealth(); Vector GetViewOffset(); Vector GetEyePos(); Vector& GetAbsOrigin(); bool SetupBones(matrix3x4_t* pBoneToWorldOut, int nMaxBones, int boneMask, float currentTime); void* GetModel(); int& GetTickBase(); }; class CWeapon { public: bool UsesLua(); bool PushEntity(); bool HasPrimaryAmmo(); float LUASpread(); const char* GetWeaponBase(); float TTTSpread(); float LUASpread2(); const Vector& orgGetBulletSpread(); Vector GetBulletSpread(); const char* GetName(); bool IsExplosive(); bool IsHoldingTool(); bool IsNospreadWeapon(); float m_flNextPrimaryAttack(); bool CanFire(); };
23.327586
98
0.716925
Nixer1337
3c664286581b4bceda140fe32248da790b15559b
269
cpp
C++
12-coding-practice-problems/12.40-functions-number-to-words/main.cpp
trangnart/cis22a
498a7b37d12a13efa7749849dc95d9892d1786be
[ "MIT" ]
2
2020-09-04T22:06:06.000Z
2020-09-09T04:00:25.000Z
12-coding-practice-problems/12.40-functions-number-to-words/main.cpp
trangnart/cis22a
498a7b37d12a13efa7749849dc95d9892d1786be
[ "MIT" ]
14
2020-08-24T01:44:36.000Z
2021-01-01T08:44:17.000Z
12-coding-practice-problems/12.40-functions-number-to-words/main.cpp
trangnart/cis22a
498a7b37d12a13efa7749849dc95d9892d1786be
[ "MIT" ]
1
2020-09-04T22:13:13.000Z
2020-09-04T22:13:13.000Z
#include <iostream> #include <string> using namespace std; string DigitToWord(int digitIn) { // FINISH } string TensDigitToWord(int digitIn) { // FINISH } string TwoDigitNumToWords(int numIn) { // FINISH } int main() { // FINISH return 0; }
8.966667
38
0.643123
trangnart
3c69914c1a2306008d9e2f042155d8a0ddae948a
6,599
hpp
C++
ql/models/shortrate/twofactormodels/g2.hpp
SoftwareIngenieur/QuantLib
7a59dd749869f7a679536df322482bf9c6531d38
[ "BSD-3-Clause" ]
null
null
null
ql/models/shortrate/twofactormodels/g2.hpp
SoftwareIngenieur/QuantLib
7a59dd749869f7a679536df322482bf9c6531d38
[ "BSD-3-Clause" ]
null
null
null
ql/models/shortrate/twofactormodels/g2.hpp
SoftwareIngenieur/QuantLib
7a59dd749869f7a679536df322482bf9c6531d38
[ "BSD-3-Clause" ]
null
null
null
/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* Copyright (C) 2001, 2002, 2003 Sadruddin Rejeb Copyright (C) 2004 Mike Parker This file is part of QuantLib, a free-software/open-source library for financial quantitative analysts and developers - http://quantlib.org/ QuantLib is free software: you can redistribute it and/or modify it under the terms of the QuantLib license. You should have received a copy of the license along with this program; if not, please email <[email protected]>. The license is also available online at <http://quantlib.org/license.shtml>. 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 license for more details. */ /*! \file g2.hpp \brief Two-factor additive Gaussian Model G2++ */ #ifndef quantlib_two_factor_models_g2_h #define quantlib_two_factor_models_g2_h #include <ql/models/shortrate/twofactormodel.hpp> #include <ql/processes/ornsteinuhlenbeckprocess.hpp> #include <ql/instruments/swaption.hpp> namespace QuantLib { //! Two-additive-factor gaussian model class. /*! This class implements a two-additive-factor model defined by \f[ dr_t = \varphi(t) + x_t + y_t \f] where \f$ x_t \f$ and \f$ y_t \f$ are defined by \f[ dx_t = -a x_t dt + \sigma dW^1_t, x_0 = 0 \f] \f[ dy_t = -b y_t dt + \sigma dW^2_t, y_0 = 0 \f] and \f$ dW^1_t dW^2_t = \rho dt \f$. \bug This class was not tested enough to guarantee its functionality. \ingroup shortrate */ class G2 : public TwoFactorModel, public AffineModel, public TermStructureConsistentModel { public: G2(const Handle<YieldTermStructure>& termStructure, Real a = 0.1, Real sigma = 0.01, Real b = 0.1, Real eta = 0.01, Real rho = -0.75); ext::shared_ptr<ShortRateDynamics> dynamics() const override; Real discountBond(Time now, Time maturity, Array factors) const override { QL_REQUIRE(factors.size()>1, "g2 model needs two factors to compute discount bond"); return discountBond(now, maturity, factors[0], factors[1]); } Real discountBond(Time, Time, Rate, Rate) const; Real discountBondOption(Option::Type type, Real strike, Time maturity, Time bondMaturity) const override; Real swaption(const Swaption::arguments& arguments, Rate fixedRate, Real range, Size intervals) const; DiscountFactor discount(Time t) const override { return termStructure()->discount(t); } Real a() const { return a_(0.0); } Real sigma() const { return sigma_(0.0); } Real b() const { return b_(0.0); } Real eta() const { return eta_(0.0); } Real rho() const { return rho_(0.0); } protected: void generateArguments() override; Real A(Time t, Time T) const; Real B(Real x, Time t) const; private: class Dynamics; class FittingParameter; Real sigmaP(Time t, Time s) const; Parameter& a_; Parameter& sigma_; Parameter& b_; Parameter& eta_; Parameter& rho_; Parameter phi_; Real V(Time t) const; class SwaptionPricingFunction; friend class SwaptionPricingFunction; }; class G2::Dynamics : public TwoFactorModel::ShortRateDynamics { public: Dynamics(const Parameter& fitting, Real a, Real sigma, Real b, Real eta, Real rho) : ShortRateDynamics(ext::shared_ptr<StochasticProcess1D>( new OrnsteinUhlenbeckProcess(a, sigma)), ext::shared_ptr<StochasticProcess1D>( new OrnsteinUhlenbeckProcess(b, eta)), rho), fitting_(fitting) {} Rate shortRate(Time t, Real x, Real y) const override { return fitting_(t) + x + y; } private: Parameter fitting_; }; //! Analytical term-structure fitting parameter \f$ \varphi(t) \f$. /*! \f$ \varphi(t) \f$ is analytically defined by \f[ \varphi(t) = f(t) + \frac{1}{2}(\frac{\sigma(1-e^{-at})}{a})^2 + \frac{1}{2}(\frac{\eta(1-e^{-bt})}{b})^2 + \rho\frac{\sigma(1-e^{-at})}{a}\frac{\eta(1-e^{-bt})}{b}, \f] where \f$ f(t) \f$ is the instantaneous forward rate at \f$ t \f$. */ class G2::FittingParameter : public TermStructureFittingParameter { private: class Impl : public Parameter::Impl { public: Impl(const Handle<YieldTermStructure>& termStructure, Real a, Real sigma, Real b, Real eta, Real rho) : termStructure_(termStructure), a_(a), sigma_(sigma), b_(b), eta_(eta), rho_(rho) {} Real value(const Array&, Time t) const override { Rate forward = termStructure_->forwardRate(t, t, Continuous, NoFrequency); Real temp1 = sigma_*(1.0-std::exp(-a_*t))/a_; Real temp2 = eta_*(1.0-std::exp(-b_*t))/b_; Real value = 0.5*temp1*temp1 + 0.5*temp2*temp2 + rho_*temp1*temp2 + forward; return value; } private: Handle<YieldTermStructure> termStructure_; Real a_, sigma_, b_, eta_, rho_; }; public: FittingParameter(const Handle<YieldTermStructure>& termStructure, Real a, Real sigma, Real b, Real eta, Real rho) : TermStructureFittingParameter(ext::shared_ptr<Parameter::Impl>( new FittingParameter::Impl(termStructure, a, sigma, b, eta, rho))) {} }; } #endif
34.19171
95
0.537203
SoftwareIngenieur
3c6c6344c979d9380ecd68baee34ced672ac3cf7
957
hpp
C++
include/blackhole/config/json.hpp
JakariaBlaine/blackhole
e340329c6e2e3166858d8466656ad12300b686bd
[ "MIT" ]
193
2015-01-05T08:48:05.000Z
2022-01-31T22:04:01.000Z
include/blackhole/config/json.hpp
JakariaBlaine/blackhole
e340329c6e2e3166858d8466656ad12300b686bd
[ "MIT" ]
135
2015-01-13T13:02:49.000Z
2022-01-12T15:06:48.000Z
include/blackhole/config/json.hpp
JakariaBlaine/blackhole
e340329c6e2e3166858d8466656ad12300b686bd
[ "MIT" ]
40
2015-01-21T16:37:30.000Z
2022-01-25T15:54:04.000Z
#pragma once #include <memory> #include "factory.hpp" namespace blackhole { inline namespace v1 { namespace config { class json_t; template<> class factory_traits<json_t> { public: /// Constructs and initializes the JSON config factory by reading the given stream reference /// until EOF and parsing its content. /// /// The content should be valid JSON object. /// /// \param stream lvalue reference to the input stream. static auto construct(std::istream& stream) -> std::unique_ptr<factory_t>; /// Constructs and initializes the JSON config factory by reading the given stream until EOF /// and parsing its content. /// /// The content should be valid JSON object. /// /// \overload /// \param stream rvalue reference to the input stream. static auto construct(std::istream&& stream) -> std::unique_ptr<factory_t>; }; } // namespace config } // namespace v1 } // namespace blackhole
25.864865
97
0.684431
JakariaBlaine
3c6c86b19599f0796b26798ce8f6030d24436cc9
1,725
cpp
C++
Day_18/03_Diameter.cpp
premnaaath/SDE-180
6d7cc2404d310600a81adaa652049172f2e10ed8
[ "MIT" ]
null
null
null
Day_18/03_Diameter.cpp
premnaaath/SDE-180
6d7cc2404d310600a81adaa652049172f2e10ed8
[ "MIT" ]
null
null
null
Day_18/03_Diameter.cpp
premnaaath/SDE-180
6d7cc2404d310600a81adaa652049172f2e10ed8
[ "MIT" ]
null
null
null
// Problem Link: // https://leetcode.com/problems/diameter-of-binary-tree/ // Approach 1 // TC: O(n^2) // SC: O(n) // Approach 2 // TC: O(n) // SC: O(n) #include <bits/stdc++.h> using namespace std; #define ll long long #define deb(x) cout << #x << ": " << x << "\n" class TreeNode { public: TreeNode *left; int val; TreeNode *right; TreeNode() { TreeNode(-1); } TreeNode(int _val) : left(NULL), val(_val), right(NULL) {} }; // Approach 1 int maxHeight(TreeNode *root) { if (!root) return 0; return max(maxHeight(root->left) + 1, maxHeight(root->right) + 1); } int diameterOfBinaryTree1(TreeNode *root) { if (!root) return 0; int currMax = maxHeight(root->left) + maxHeight(root->right); currMax = max(diameterOfBinaryTree1(root->left), currMax); currMax = max(diameterOfBinaryTree1(root->right), currMax); return currMax; } // Approach 2 int helper(TreeNode *root, int &res) { if (!root) return 0; int leftDia = helper(root->left, res); int rightDia = helper(root->right, res); res = max(res, leftDia + rightDia); return max(leftDia + 1, rightDia + 1); } int diameterOfBinaryTree2(TreeNode *root) { int res{}; helper(root, res); return res; } void solve() { TreeNode *root = new TreeNode(10); root->left = new TreeNode(20); root->right = new TreeNode(30); root->left->left = new TreeNode(40); root->left->right = new TreeNode(60); cout << diameterOfBinaryTree1(root) << endl; cout << diameterOfBinaryTree2(root) << endl; } int main() { ios_base::sync_with_stdio(0), cin.tie(0), cout.tie(0); int t{1}; // cin >> t; while (t--) solve(); return 0; }
19.166667
70
0.602899
premnaaath
3c71ba99bd1635633681209b7552b93ae1c90c87
18,068
cpp
C++
ksp_plugin_test/plugin_compatibility_test.cpp
net-lisias-ksp/Principia
9292ea1fc2e4b4f0ce7a717e2f507168519f5f8a
[ "MIT" ]
2
2016-02-14T21:18:48.000Z
2017-02-11T23:23:20.000Z
ksp_plugin_test/plugin_compatibility_test.cpp
net-lisias-ksp/Principia
9292ea1fc2e4b4f0ce7a717e2f507168519f5f8a
[ "MIT" ]
1
2015-07-27T21:27:46.000Z
2015-07-27T21:27:46.000Z
ksp_plugin_test/plugin_compatibility_test.cpp
pleroy/Principia
64c4c6c124f4744381b6489e39e6b53e2a440ce9
[ "MIT" ]
null
null
null
 #include <memory> #include <string> #include <utility> #include <vector> #include "astronomy/time_scales.hpp" #include "astronomy/mercury_orbiter.hpp" #include "base/array.hpp" #include "base/file.hpp" #include "base/not_null.hpp" #include "base/pull_serializer.hpp" #include "base/push_deserializer.hpp" #include "base/serialization.hpp" #include "glog/logging.h" #include "gmock/gmock.h" #include "gtest/gtest.h" #include "ksp_plugin/frames.hpp" #include "ksp_plugin/interface.hpp" #include "ksp_plugin/plugin.hpp" #include "physics/discrete_trajectory.hpp" #include "serialization/ksp_plugin.pb.h" #include "testing_utilities/is_near.hpp" #include "testing_utilities/serialization.hpp" #include "testing_utilities/string_log_sink.hpp" namespace principia { namespace interface { using astronomy::operator""_TT; using astronomy::MercuryOrbiterInitialDegreesOfFreedom; using astronomy::MercuryOrbiterInitialTime; using astronomy::TTSecond; using astronomy::date_time::DateTime; using astronomy::date_time::operator""_DateTime; using base::not_null; using base::OFStream; using base::ParseFromBytes; using base::PullSerializer; using base::PushDeserializer; using ksp_plugin::Barycentric; using ksp_plugin::Plugin; using physics::DiscreteTrajectory; using quantities::Speed; using quantities::si::Degree; using quantities::si::Kilo; using quantities::si::Second; using testing_utilities::operator""_⑴; using testing_utilities::IsNear; using testing_utilities::ReadFromBinaryFile; using testing_utilities::ReadLinesFromBase64File; using testing_utilities::ReadLinesFromHexadecimalFile; using testing_utilities::StringLogSink; using testing_utilities::WriteToBinaryFile; using ::testing::AllOf; using ::testing::ElementsAre; using ::testing::Eq; using ::testing::HasSubstr; using ::testing::Not; using ::testing::NotNull; using ::testing::Pair; using ::testing::SizeIs; using ::testing::internal::CaptureStderr; using ::testing::internal::GetCapturedStderr; const char preferred_compressor[] = "gipfeli"; const char preferred_encoder[] = "base64"; class PluginCompatibilityTest : public testing::Test { protected: PluginCompatibilityTest() : stderrthreshold_(FLAGS_stderrthreshold) { google::SetStderrLogging(google::WARNING); } ~PluginCompatibilityTest() override { google::SetStderrLogging(stderrthreshold_); } // Reads a plugin from a file containing only the "serialized_plugin = " // lines, with "serialized_plugin = " dropped. static not_null<std::unique_ptr<Plugin const>> ReadPluginFromFile( std::filesystem::path const& filename, std::string_view const compressor, std::string_view const encoder) { Plugin const* plugin = nullptr; PushDeserializer* deserializer = nullptr; auto const lines = encoder == "hexadecimal" ? ReadLinesFromHexadecimalFile(filename) : encoder == "base64" ? ReadLinesFromBase64File(filename) : std::vector<std::string>{}; CHECK(!lines.empty()); LOG(ERROR) << "Deserialization starting"; for (std::string const& line : lines) { principia__DeserializePlugin(line.c_str(), &deserializer, &plugin, compressor.data(), encoder.data()); } principia__DeserializePlugin("", &deserializer, &plugin, compressor.data(), encoder.data()); LOG(ERROR) << "Deserialization complete"; return std::unique_ptr<Plugin const>(plugin); } // Writes a plugin to a file. static void WritePluginToFile( std::filesystem::path const& filename, std::string_view const compressor, std::string_view const encoder, not_null<std::unique_ptr<Plugin const>> plugin) { OFStream file(filename); PullSerializer* serializer = nullptr; char const* b64 = nullptr; LOG(ERROR) << "Serialization starting"; for (;;) { b64 = principia__SerializePlugin(plugin.get(), &serializer, preferred_compressor, preferred_encoder); if (b64 == nullptr) { break; } file << b64 << "\n"; principia__DeleteString(&b64); } LOG(ERROR) << "Serialization complete"; Plugin const* released_plugin = plugin.release(); principia__DeletePlugin(&released_plugin); } static void WriteAndReadBack( not_null<std::unique_ptr<Plugin const>> plugin1) { // Write the plugin to a new file with the preferred format. WritePluginToFile(TEMP_DIR / "serialized_plugin.proto.b64", preferred_compressor, preferred_encoder, std::move(plugin1)); // Read the plugin from the new file to make sure that it's fine. auto plugin2 = ReadPluginFromFile(TEMP_DIR / "serialized_plugin.proto.b64", preferred_compressor, preferred_encoder); } static void CheckSaveCompatibility(std::filesystem::path const& filename, std::string_view const compressor, std::string_view const encoder) { // Read a plugin from the given file. auto plugin = ReadPluginFromFile(filename, compressor, encoder); WriteAndReadBack(std::move(plugin)); } int const stderrthreshold_; }; TEST_F(PluginCompatibilityTest, PreCartan) { // This space for rent. } TEST_F(PluginCompatibilityTest, PreCohen) { StringLogSink log_warning(google::WARNING); CheckSaveCompatibility( SOLUTION_DIR / "ksp_plugin_test" / "saves" / "3039.proto.hex", /*compressor=*/"", /*decoder=*/"hexadecimal"); EXPECT_THAT( log_warning.string(), AllOf( HasSubstr( "pre-Cohen ContinuousTrajectory"), // Regression test for #3039. HasSubstr("pre-Cauchy"), // The save is even older. Not(HasSubstr("pre-Cartan")))); // But not *that* old. } #if !_DEBUG TEST_F(PluginCompatibilityTest, Reach) { StringLogSink log_warning(google::WARNING); not_null<std::unique_ptr<Plugin const>> plugin = ReadPluginFromFile( SOLUTION_DIR / "ksp_plugin_test" / "saves" / "3072.proto.b64", /*compressor=*/"gipfeli", /*decoder=*/"base64"); EXPECT_THAT(log_warning.string(), AllOf(HasSubstr("pre-Galileo"), Not(HasSubstr("pre-Frobenius")))); auto const test = plugin->GetVessel("f2d77873-4776-4809-9dfb-de9e7a0620a6"); EXPECT_THAT(test->name(), Eq("TEST")); EXPECT_THAT(TTSecond(test->history()->front().time), Eq("1970-08-14T08:03:18"_DateTime)); EXPECT_THAT(TTSecond(test->psychohistory()->back().time), Eq("1970-08-14T08:47:05"_DateTime)); EXPECT_FALSE(test->has_flight_plan()); auto const ifnity = plugin->GetVessel("29142a79-7acd-47a9-a34d-f9f2a8e1b4ed"); EXPECT_THAT(ifnity->name(), Eq("IFNITY-5.2")); EXPECT_THAT(TTSecond(ifnity->history()->front().time), Eq("1970-08-14T08:03:46"_DateTime)); EXPECT_THAT(TTSecond(ifnity->psychohistory()->back().time), Eq("1970-08-14T08:47:05"_DateTime)); ASSERT_TRUE(ifnity->has_flight_plan()); EXPECT_THAT(ifnity->flight_plan().number_of_manœuvres(), Eq(16)); std::vector<std::pair<DateTime, Speed>> manœuvre_ignition_tt_seconds_and_Δvs; for (int i = 0; i < ifnity->flight_plan().number_of_manœuvres(); ++i) { manœuvre_ignition_tt_seconds_and_Δvs.emplace_back( TTSecond(ifnity->flight_plan().GetManœuvre(i).initial_time()), ifnity->flight_plan().GetManœuvre(i).Δv().Norm()); } // The flight plan only covers the inner solar system (this is probably // because of #3035). // It also differs from https://youtu.be/7BDxZV7UD9I?t=439. // TODO(egg): Compute the flybys and figure out what exactly is going on in // this flight plan. EXPECT_THAT(manœuvre_ignition_tt_seconds_and_Δvs, ElementsAre(Pair("1970-08-14T09:34:49"_DateTime, 3.80488671073918022e+03 * (Metre / Second)), Pair("1970-08-15T13:59:24"_DateTime, 3.04867185471741759e-04 * (Metre / Second)), Pair("1970-12-22T07:48:21"_DateTime, 1.58521291818444873e-03 * (Metre / Second)), Pair("1971-01-08T17:36:55"_DateTime, 1.40000000034068623e-03 * (Metre / Second)), Pair("1971-07-02T17:16:00"_DateTime, 1.00000000431022681e-04 * (Metre / Second)), Pair("1971-09-06T03:27:33"_DateTime, 1.78421858738381537e-03 * (Metre / Second)), Pair("1972-02-13T22:47:26"_DateTime, 7.72606625794511597e-04 * (Metre / Second)), Pair("1972-03-25T16:30:19"_DateTime, 5.32846131747503372e-03 * (Metre / Second)), Pair("1972-12-24T04:09:32"_DateTime, 3.45000000046532824e-03 * (Metre / Second)), Pair("1973-06-04T01:59:07"_DateTime, 9.10695453328359134e-03 * (Metre / Second)), Pair("1973-07-09T06:07:17"_DateTime, 4.49510921430966881e-01 * (Metre / Second)), Pair("1973-09-10T03:59:44"_DateTime, 1.00000000431022681e-04 * (Metre / Second)), Pair("1974-11-20T17:34:27"_DateTime, 5.10549409572428781e-01 * (Metre / Second)), Pair("1975-10-07T01:29:45"_DateTime, 2.86686518692948443e-02 * (Metre / Second)), Pair("1975-12-29T21:27:13"_DateTime, 1.00404183285598275e-03 * (Metre / Second)), Pair("1977-07-28T22:47:53"_DateTime, 1.39666705839172456e-01 * (Metre / Second)))); // Make sure that we can upgrade, save, and reload. WriteAndReadBack(std::move(plugin)); } #endif TEST_F(PluginCompatibilityTest, DISABLED_Butcher) { StringLogSink log_warning(google::WARNING); not_null<std::unique_ptr<Plugin const>> plugin = ReadPluginFromFile( R"(P:\Public Mockingbird\Principia\Saves\1119\1119.proto.b64)", /*compressor=*/"gipfeli", /*decoder=*/"base64"); EXPECT_THAT(log_warning.string(), AllOf(HasSubstr("pre-Haar"), Not(HasSubstr(u8"pre-Gröbner")))); auto const& orbiter = *plugin->GetVessel("e180ca12-492f-45bf-a194-4c5255aec8a0"); EXPECT_THAT(orbiter.name(), Eq("Mercury Orbiter 1")); auto const begin = orbiter.history()->begin(); EXPECT_THAT(begin->time, Eq("1966-05-10T00:14:03"_TT + 0.0879862308502197 * Second)); EXPECT_THAT(begin->degrees_of_freedom, Eq(DegreesOfFreedom<Barycentric>( Barycentric::origin + Displacement<Barycentric>( {-9.83735958466250000e+10 * Metre, -1.05659916408781250e+11 * Metre, -4.58171358797500000e+10 * Metre}), Velocity<Barycentric>( {+2.18567382812500000e+04 * (Metre / Second), -1.76616533203125000e+04 * (Metre / Second), -7.76112133789062500e+03 * (Metre / Second)})))); auto const& mercury = plugin->GetCelestial(2); EXPECT_THAT(mercury.body()->name(), Eq("Mercury")); plugin->RequestReanimation(begin->time); while (mercury.trajectory().t_min() > begin->time) { absl::SleepFor(absl::Milliseconds(1)); } // The history goes back far enough that we are still on our way to Mercury at // the beginning. EXPECT_THAT((begin->degrees_of_freedom.position() - mercury.trajectory().EvaluatePosition(begin->time)).Norm(), IsNear(176'400'999_⑴ * Kilo(Metre))); EXPECT_THAT(begin->time, Eq("1966-05-10T00:14:03"_TT + 0.0879862308502197 * Second)); EXPECT_THAT(begin->degrees_of_freedom, Eq(DegreesOfFreedom<Barycentric>( Barycentric::origin + Displacement<Barycentric>( {-9.83735958466250000e+10 * Metre, -1.05659916408781250e+11 * Metre, -4.58171358797500000e+10 * Metre}), Velocity<Barycentric>( {+2.18567382812500000e+04 * (Metre / Second), -1.76616533203125000e+04 * (Metre / Second), -7.76112133789062500e+03 * (Metre / Second)})))); // We arrive in late August. Check the state in the beginning of September. auto const it = orbiter.trajectory().lower_bound("1966-09-01T00:00:00"_TT); EXPECT_THAT(it->time, Eq(MercuryOrbiterInitialTime)); EXPECT_THAT(it->degrees_of_freedom, Eq(MercuryOrbiterInitialDegreesOfFreedom<Barycentric>)); EXPECT_THAT((it->degrees_of_freedom.position() - mercury.trajectory().EvaluatePosition(it->time)).Norm(), IsNear(19'163_⑴ * Kilo(Metre))); // Make sure that we can upgrade, save, and reload. WriteAndReadBack(std::move(plugin)); } TEST_F(PluginCompatibilityTest, DISABLED_Lpg) { StringLogSink log_warning(google::WARNING); not_null<std::unique_ptr<Plugin const>> plugin = ReadPluginFromFile( R"(P:\Public Mockingbird\Principia\Saves\3136\3136.proto.b64)", /*compressor=*/"gipfeli", /*decoder=*/"base64"); EXPECT_THAT(log_warning.string(), AllOf(HasSubstr("pre-Hamilton"), Not(HasSubstr("pre-Haar")))); // The vessel with the longest history. auto const& vessel = *plugin->GetVessel("77ddea45-47ee-48c0-aee9-d55cdb35ffcd"); auto history = vessel.history(); auto psychohistory = vessel.psychohistory(); EXPECT_THAT(*history, SizeIs(435'927)); EXPECT_THAT(*psychohistory, SizeIs(3)); // Evaluate a point in each of the two segments. EXPECT_THAT(history->EvaluateDegreesOfFreedom("1957-10-04T19:28:34"_TT), Eq(DegreesOfFreedom<Barycentric>( Barycentric::origin + Displacement<Barycentric>( {+1.47513683827317657e+11 * Metre, +2.88696086355042419e+10 * Metre, +1.24740082262952404e+10 * Metre}), Velocity<Barycentric>( {-6.28845231836519179e+03 * (Metre / Second), +2.34046542233168329e+04 * (Metre / Second), +4.64410011408655919e+03 * (Metre / Second)})))); EXPECT_THAT(psychohistory->EvaluateDegreesOfFreedom("1958-10-07T09:38:30"_TT), Eq(DegreesOfFreedom<Barycentric>( Barycentric::origin + Displacement<Barycentric>( {+1.45814173315801941e+11 * Metre, +3.45409490426372147e+10 * Metre, +1.49445864962450924e+10 * Metre}), Velocity<Barycentric>( {-8.70708379504568074e+03 * (Metre / Second), +2.61488327506437054e+04 * (Metre / Second), +1.90319283138508908e+04 * (Metre / Second)})))); // Serialize the history and psychohistory to a temporary file. { serialization::DiscreteTrajectory message; vessel.trajectory().WriteToMessage( &message, /*tracked=*/{history, psychohistory}, /*exact=*/{}); auto const serialized_message = base::SerializeAsBytes(message); WriteToBinaryFile(TEMP_DIR / "trajectory_3136.proto.bin", serialized_message.get()); } // Deserialize the temporary file to make sure that it's valid. { auto const serialized_message = ReadFromBinaryFile(TEMP_DIR / "trajectory_3136.proto.bin"); auto const message = ParseFromBytes<serialization::DiscreteTrajectory>(serialized_message); auto const trajectory = DiscreteTrajectory<Barycentric>::ReadFromMessage( message, /*tracked=*/{&history, &psychohistory}); EXPECT_THAT(*history, SizeIs(435'927)); EXPECT_THAT(*psychohistory, SizeIs(3)); } // Make sure that we can upgrade, save, and reload. WriteAndReadBack(std::move(plugin)); } TEST_F(PluginCompatibilityTest, DISABLED_Egg) { StringLogSink log_warning(google::WARNING); not_null<std::unique_ptr<Plugin const>> plugin = ReadPluginFromFile( R"(P:\Public Mockingbird\Principia\Saves\3136\3136b.proto.b64)", /*compressor=*/"gipfeli", /*decoder=*/"base64"); EXPECT_THAT(log_warning.string(), AllOf(HasSubstr("pre-Hamilton"), Not(HasSubstr("pre-Haar")))); auto& mutable_plugin = const_cast<Plugin&>(*plugin); // This would fail if segment iterators were invalidated during part // deserialization. mutable_plugin.AdvanceTime( mutable_plugin.GameEpoch() + 133218.91123694609 * Second, 295.52698460805016 * Degree); mutable_plugin.CatchUpVessel("1e07aaa2-d1f8-4f6d-8b32-495b46109d98"); // Make sure that we can upgrade, save, and reload. WriteAndReadBack(std::move(plugin)); } // Use for debugging saves given by users. TEST_F(PluginCompatibilityTest, DISABLED_SECULAR_Debug) { not_null<std::unique_ptr<Plugin const>> plugin = ReadPluginFromFile( R"(P:\Public Mockingbird\Principia\Saves\3203\wip.proto.b64)", /*compressor=*/"gipfeli", /*decoder=*/"base64"); } } // namespace interface } // namespace principia
42.713948
80
0.615176
net-lisias-ksp
3c72d81813c24325c2bfd0bd6d81a1d1889a6ef8
1,661
cpp
C++
ql/time/calendars/bespokecalendar.cpp
haozhangphd/QuantLib-noBoost
ddded069868161099843c04840454f00816113ad
[ "BSD-3-Clause" ]
76
2017-06-28T21:24:38.000Z
2021-12-19T18:07:37.000Z
ql/time/calendars/bespokecalendar.cpp
haozhangphd/QuantLib-noBoost
ddded069868161099843c04840454f00816113ad
[ "BSD-3-Clause" ]
2
2017-07-05T09:20:13.000Z
2019-10-31T12:06:51.000Z
ql/time/calendars/bespokecalendar.cpp
haozhangphd/QuantLib-noBoost
ddded069868161099843c04840454f00816113ad
[ "BSD-3-Clause" ]
34
2017-07-02T14:49:21.000Z
2021-11-26T15:32:04.000Z
/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* Copyright (C) 2008 StatPro Italia srl This file is part of QuantLib, a free-software/open-source library for financial quantitative analysts and developers - http://quantlib.org/ QuantLib is free software: you can redistribute it and/or modify it under the terms of the QuantLib license. You should have received a copy of the license along with this program; if not, please email <[email protected]>. The license is also available online at <http://quantlib.org/license.shtml>. 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 license for more details. */ #include <ql/time/calendars/bespokecalendar.hpp> #include <sstream> namespace QuantLib { BespokeCalendar::Impl::Impl(const std::string& name) : name_(name) {} std::string BespokeCalendar::Impl::name() const { return name_; } bool BespokeCalendar::Impl::isWeekend(Weekday w) const { return (weekend_.find(w) != weekend_.end()); } bool BespokeCalendar::Impl::isBusinessDay(const Date& date) const { return !isWeekend(date.weekday()); } void BespokeCalendar::Impl::addWeekend(Weekday w) { weekend_.insert(w); } BespokeCalendar::BespokeCalendar(const std::string& name) { bespokeImpl_ = std::make_shared<BespokeCalendar::Impl>(name); impl_ = bespokeImpl_; } void BespokeCalendar::addWeekend(Weekday w) { bespokeImpl_->addWeekend(w); } }
29.660714
79
0.698374
haozhangphd
3c79c64fef31c1470dd78139d88b29c7c6498fd7
1,344
cpp
C++
artifact/storm/src/storm/builder/jit/JitModelBuilderInterface.cpp
glatteis/tacas21-artifact
30b4f522bd3bdb4bebccbfae93f19851084a3db5
[ "MIT" ]
null
null
null
artifact/storm/src/storm/builder/jit/JitModelBuilderInterface.cpp
glatteis/tacas21-artifact
30b4f522bd3bdb4bebccbfae93f19851084a3db5
[ "MIT" ]
null
null
null
artifact/storm/src/storm/builder/jit/JitModelBuilderInterface.cpp
glatteis/tacas21-artifact
30b4f522bd3bdb4bebccbfae93f19851084a3db5
[ "MIT" ]
1
2022-02-05T12:39:53.000Z
2022-02-05T12:39:53.000Z
#include "storm/builder/jit/JitModelBuilderInterface.h" #include "storm/adapters/RationalFunctionAdapter.h" namespace storm { namespace builder { namespace jit { template <typename IndexType, typename ValueType> JitModelBuilderInterface<IndexType, ValueType>::JitModelBuilderInterface(ModelComponentsBuilder<IndexType, ValueType>& modelComponentsBuilder) : modelComponentsBuilder(modelComponentsBuilder) { // Intentionally left empty. } template <typename IndexType, typename ValueType> JitModelBuilderInterface<IndexType, ValueType>::~JitModelBuilderInterface() { // Intentionally left empty. } template <typename IndexType, typename ValueType> void JitModelBuilderInterface<IndexType, ValueType>::addStateBehaviour(IndexType const& stateId, StateBehaviour<IndexType, ValueType>& behaviour) { modelComponentsBuilder.addStateBehaviour(stateId, behaviour); } template class JitModelBuilderInterface<uint32_t, double>; template class JitModelBuilderInterface<uint32_t, storm::RationalNumber>; template class JitModelBuilderInterface<uint32_t, storm::RationalFunction>; } } }
43.354839
205
0.671131
glatteis
3c7bbe87cadb94597644da05b31063719b764295
5,965
cpp
C++
tests/simple/test_model_cereal.cpp
GasparQ/Cerealization
42ed8e78fc42f7e032633eb5c06635cb92980c59
[ "MIT" ]
1
2018-03-16T08:51:35.000Z
2018-03-16T08:51:35.000Z
tests/simple/test_model_cereal.cpp
GasparQ/Cerealization
42ed8e78fc42f7e032633eb5c06635cb92980c59
[ "MIT" ]
null
null
null
tests/simple/test_model_cereal.cpp
GasparQ/Cerealization
42ed8e78fc42f7e032633eb5c06635cb92980c59
[ "MIT" ]
null
null
null
// // Created by GasparQ on 03/04/2018. // #include <cassert> #include <iostream> #include <typeinfo> #include "Cerealizable/Scalar.hpp" #include "Cerealizable/List.hpp" #include "Cerealizable/Tuple.hpp" #include "Cerealizable/Object.hpp" #include "Cerealizer/Binary/Binary.hpp" #include "Cerealizer/JSON/JSON.hpp" using namespace Cerealization; template <typename Cerealizer, typename Data> bool test_cerealize(Data const &toser) { Cerealizer cerealizer; Data witness; std::string dataname(typeid(Data).name()); std::string cername(typeid(Cerealizer).name()); std::cout << "Cerealizing " << dataname.substr(31) << " into " << cername.substr(30) << " ===> "; cerealizer << toser; if (std::is_same<std::string, decltype(cerealizer.Data())>::value) std::cout << cerealizer.Data() << " ===> "; cerealizer >> witness; if (toser == witness) { std::cout << "Success" << std::endl; return true; } std::cout << "Failure" << std::endl; return false; } template <typename Cerealizer> void test_scalar() { assert(test_cerealize<Cerealizer>(Cerealizable::Char('t'))); assert(test_cerealize<Cerealizer>(Cerealizable::Char(-128))); assert(test_cerealize<Cerealizer>(Cerealizable::UChar('t'))); assert(test_cerealize<Cerealizer>(Cerealizable::UChar(255))); assert(test_cerealize<Cerealizer>(Cerealizable::Short(-42))); assert(test_cerealize<Cerealizer>(Cerealizable::UShort(42))); assert(test_cerealize<Cerealizer>(Cerealizable::Int(-2000000000))); assert(test_cerealize<Cerealizer>(Cerealizable::UInt(4000000000))); assert(test_cerealize<Cerealizer>(Cerealizable::Long(-2000000000))); assert(test_cerealize<Cerealizer>(Cerealizable::ULong(4000000000))); assert(test_cerealize<Cerealizer>(Cerealizable::LongLong(-8000000000000000000))); assert(test_cerealize<Cerealizer>(Cerealizable::ULongLong(9000000000000000000))); assert(test_cerealize<Cerealizer>(Cerealizable::Float(50.3f))); assert(test_cerealize<Cerealizer>(Cerealizable::Float(-50.3f))); assert(test_cerealize<Cerealizer>(Cerealizable::Double(50.3))); assert(test_cerealize<Cerealizer>(Cerealizable::Double(-50.3))); } template <typename Cerealizer> void test_list() { assert(test_cerealize<Cerealizer>(Cerealizable::String("Coucou"))); std::string toto("coucou"); assert(test_cerealize<Cerealizer>(Cerealizable::String(toto))); assert(test_cerealize<Cerealizer>(Cerealizable::List<int>({3, 1, 20}))); assert(test_cerealize<Cerealizer>( Cerealizable::List<Cerealizable::String>( { Cerealizable::String("hey"), Cerealizable::String("ho"), Cerealizable::String("hello") } ))); assert(test_cerealize<Cerealizer>(Cerealizable::Vector<int>({3, 1, 20}))); assert(test_cerealize<Cerealizer>( Cerealizable::Vector<Cerealizable::String>( { Cerealizable::String("hey"), Cerealizable::String("ho"), Cerealizable::String("hello") } ))); assert(test_cerealize<Cerealizer>(Cerealizable::Set <int>({3, 1, 20}))); assert(test_cerealize<Cerealizer>(Cerealizable::Set <std::string>({ "hey", "ho", "hello" }))); assert(test_cerealize<Cerealizer>(Cerealizable::Map <char, int>({ {'j', 3}, {'l', 1}, {'i', 20} }))); assert(test_cerealize<Cerealizer>( Cerealizable::Map <std::string, Cerealizable::String>( { {"hey", Cerealizable::String("hey")}, {"ho", Cerealizable::String("ho")}, {"hello", Cerealizable::String("hello")} } ))); assert(test_cerealize<Cerealizer>(Cerealizable::List<Tuple<int, String, Int>>{ Tuple<int, String, Int>(43, String("toto"), 50), Tuple<int, String, Int>(78, String("tutu"), 90), Tuple<int, String, Int>(-78, String("tata"), 120), Tuple<int, String, Int>(-388, String("titi"), -3920) })); } template <typename Cerealizer> void test_tuple() { assert(test_cerealize<Cerealizer>(Tuple<int, int, int>(-43, 29, 39))); assert(test_cerealize<Cerealizer>(Tuple<int, char, double>(-43, 'd', 3.14))); assert(test_cerealize<Cerealizer>(Tuple<Scalar<int>, char, double>(-43, 'd', 3.14))); assert(test_cerealize<Cerealizer>(Tuple<Scalar<int>, String, double>(-43, String("Coucou"), 3.14))); assert(test_cerealize<Cerealizer>(Tuple<Scalar<int>, String, Tuple<int, int, int>>(-43, String("Coucou"), Tuple<int, int, int>(3, -42, 39)))); assert(test_cerealize<Cerealizer>(Tuple<Scalar<int>, String, Tuple<int, String, int>>(-43, String("Coucou"), Tuple<int, String, int>(3, String("C'est moit"), 39)))); } template <typename Cerelizer> void test_object() { assert(test_cerealize<Cerelizer>(Object<int, int, int>({"x", 42}, {"y", -42}, {"z", 390}))); assert(test_cerealize<Cerelizer>(Object<int, char, double>({"x", 42}, {"id", 'k'}, {"radius", 3.14}))); assert(test_cerealize<Cerelizer>(Object<Scalar<int>, char, double>({"x", 42}, {"id", 'k'}, {"radius", 3.14}))); assert(test_cerealize<Cerelizer>(Object<Scalar<int>, String, double>({"x", 42}, {"id", String("Toto")}, {"radius", 3.14}))); assert(test_cerealize<Cerelizer>(Object<Scalar<int>, String, Tuple<int, int, int>>({"x", 42}, {"id", String("Toto")}, {"radius", Tuple<int, int, int>(3, -42, 39)}))); assert(test_cerealize<Cerelizer>(Object<Scalar<int>, String, Tuple<int, String, int>>({"x", 42}, {"id", String("Toto")}, {"radius", Tuple<int, String, int>(3, String("C'est moi"), 39)}))); } int main() { test_scalar<Cerealizer::BinaryStream>(); test_scalar<Cerealizer::JSONStream>(); test_list<Cerealizer::BinaryStream>(); test_list<Cerealizer::JSONStream>(); test_tuple<Cerealizer::BinaryStream>(); test_tuple<Cerealizer::JSONStream>(); test_object<Cerealizer::BinaryStream>(); test_object<Cerealizer::JSONStream>(); return 0; }
40.578231
192
0.652473
GasparQ
3c815e863e22a09ba29c0a09896d2983aaa9a55e
153
cpp
C++
lib/src/public.cpp
nontan-rh/cpp-template
b0b618307b54a432c3a18af308f887a21a57dccd
[ "Unlicense" ]
1
2020-11-18T08:43:11.000Z
2020-11-18T08:43:11.000Z
lib/src/public.cpp
nontan-rh/cpp-template
b0b618307b54a432c3a18af308f887a21a57dccd
[ "Unlicense" ]
null
null
null
lib/src/public.cpp
nontan-rh/cpp-template
b0b618307b54a432c3a18af308f887a21a57dccd
[ "Unlicense" ]
null
null
null
#include <sample/public.hpp> #include "internal.hpp" namespace sample { int add(int a, int b) { return internal::sub(a, -b); } } // namespace sample
15.3
54
0.673203
nontan-rh
3c8416e8d972c5e20dd3215b9755f9271cb4f4e4
618
hpp
C++
sdl1/TicTacToe/BoardInputComponent.hpp
pdpdds/sdldualsystem
d74ea84cbea705fef62868ba8c693bf7d2555636
[ "BSD-2-Clause" ]
null
null
null
sdl1/TicTacToe/BoardInputComponent.hpp
pdpdds/sdldualsystem
d74ea84cbea705fef62868ba8c693bf7d2555636
[ "BSD-2-Clause" ]
null
null
null
sdl1/TicTacToe/BoardInputComponent.hpp
pdpdds/sdldualsystem
d74ea84cbea705fef62868ba8c693bf7d2555636
[ "BSD-2-Clause" ]
null
null
null
#ifndef __BOARDINPUTCOMPONENT_H #define __BOARDINPUTCOMPONENT_H #include "InputComponent.hpp" #include "SDL.h" class BoardInputComponent : public InputComponent { public: virtual void update( GameState *obj, GameEngine *engine ); BoardInputComponent( GameBoard *board, SDL_Event *event ); ~BoardInputComponent(); protected: SDL_Rect **_squares; int _rows; int _columns; static const int _tile_x_offset = 4; static const int _tile_y_offset = 4; static const int _tile_width = 142; static const int _tile_height =142; int _mouse_x; int _mouse_y; }; #endif /* __BOARDINPUTCOMPONENT_H */
20.6
60
0.749191
pdpdds
3c898ce133d81b6a3813845c6ebac9b33717451f
9,472
cpp
C++
GazeboFluidSimulator/FluidSimulator.cpp
ManosAgelidis/SPlisHSPlasH
c206ce867c15104a70e05e4e8792072ca9b364a3
[ "MIT" ]
null
null
null
GazeboFluidSimulator/FluidSimulator.cpp
ManosAgelidis/SPlisHSPlasH
c206ce867c15104a70e05e4e8792072ca9b364a3
[ "MIT" ]
null
null
null
GazeboFluidSimulator/FluidSimulator.cpp
ManosAgelidis/SPlisHSPlasH
c206ce867c15104a70e05e4e8792072ca9b364a3
[ "MIT" ]
null
null
null
#include "SPlisHSPlasH/Common.h" #include "SPlisHSPlasH/TimeManager.h" #include "Utilities/OBJLoader.h" #include "SPlisHSPlasH/Utilities/SurfaceSampling.h" #include "SPlisHSPlasH/Viscosity/ViscosityBase.h" #include <fstream> #include "SPlisHSPlasH/Simulation.h" #include "FluidSimulator.h" #include "Utilities/Timing.h" #include "Utilities/Counting.h" #include "Utilities/FileSystem.h" #include "GazeboSceneLoader.h" #include <memory> // Enable memory leak detection #ifdef _DEBUG #ifndef EIGEN_ALIGN #define new DEBUG_NEW #endif #endif using namespace SPH; using namespace Eigen; using namespace std; using namespace Utilities; using namespace GenParam; using namespace gazebo; const std::string objFilePath("/tmp/"); FluidSimulator::FluidSimulator() { REPORT_MEMORY_LEAKS; std::cout << "Plugin loaded" << std::endl; } void FluidSimulator::RunStep() { simulationSteps++; base->timeStepNoGUI(); // publish all the boundary particles positions this->publishFluidParticles(); this->publishBoundaryParticles(); } FluidSimulator::~FluidSimulator() { this->connections.clear(); base->cleanup(); Utilities::Timing::printAverageTimes(); Utilities::Timing::printTimeSums(); Utilities::Counting::printAverageCounts(); Utilities::Counting::printCounterSums(); delete Simulation::getCurrent(); } void FluidSimulator::publishBoundaryParticles() { msgs::Fluid boundary_particles_msg; boundary_particles_msg.set_name("boundary_particles"); for (int i = 0; i < SPH::Simulation::getCurrent()->numberOfBoundaryModels(); ++i) //scene.boundaryModels.size(); ++i) { BoundaryModel_Akinci2012 *bm = static_cast<BoundaryModel_Akinci2012 *>(SPH::Simulation::getCurrent()->getBoundaryModel(i)); for (int j = 0; j < (int)bm->numberOfParticles(); j++) { ignition::math::Vector3d boundary_particles = ignition::math::Vector3d( bm->getPosition(j)[0], bm->getPosition(j)[1], bm->getPosition(j)[2]); gazebo::msgs::Set(boundary_particles_msg.add_position(), boundary_particles); } } this->rigidObjPub->Publish(boundary_particles_msg); } void FluidSimulator::publishFluidParticles() { if (simulationSteps % 5 == 0) { msgs::Fluid fluid_positions_msg; fluid_positions_msg.set_name("fluid_positions"); for (unsigned int j = 0; j < Simulation::getCurrent()->numberOfFluidModels(); j++) { FluidModel *model = Simulation::getCurrent()->getFluidModel(j); //std::cout << "Density " << model->getViscosityBase()->VISCOSITY_COEFFICIENT << std::endl;; for (unsigned int i = 0; i < model->numActiveParticles(); ++i) { gazebo::msgs::Set(fluid_positions_msg.add_position(), ignition::math::Vector3d( model->getPosition(i)[0], model->getPosition(i)[1], model->getPosition(i)[2])); } this->fluidObjPub->Publish(fluid_positions_msg); } } } void FluidSimulator::Init() { this->node = transport::NodePtr(new transport::Node()); this->node->Init(this->world->Name()); this->fluidObjPub = this->node->Advertise<msgs::Fluid>("~/fluid_pos", 10); this->rigidObjPub = this->node->Advertise<msgs::Fluid>("~/rigids_pos", 10); base = std::make_unique<GazeboSimulatorBase>(); base->init(this->fluidPluginSdf); this->ParseSDF(); base->initSimulation(); base->initBoundaryData(); this->publishBoundaryParticles(); } void FluidSimulator::Load(physics::WorldPtr parent, sdf::ElementPtr sdf) { this->world = parent; this->fluidPluginSdf = sdf; this->connections.push_back(event::Events::ConnectWorldUpdateEnd( boost::bind(&FluidSimulator::RunStep, this))); } void FluidSimulator::RegisterMesh(physics::CollisionPtr collision, std::string extension, std::string path) { // Get collision mesh by name const gazebo::common::Mesh *mesh = common::MeshManager::Instance()->GetMesh(collision->GetName()); // Export the mesh to a temp file in the selected format std::string objFilePath = path + collision->GetModel()->GetName() + "_" + collision->GetName() + ".obj"; common::MeshManager::Instance()->Export(mesh, FileSystem::normalizePath(objFilePath), extension); base->processBoundary(collision, objFilePath); } void FluidSimulator::ParseSDF() { // get all models from the world physics::Model_V models = world->Models(); // iterate through all models for (physics::Model_V::iterator currentModel = models.begin(); currentModel != models.end(); ++currentModel) { // get all links from the model physics::Link_V model_links = currentModel->get()->GetLinks(); std::cout << "Model: " << currentModel->get()->GetName() << std::endl; // iterate through all the links for (physics::Link_V::iterator link_it = model_links.begin(); link_it != model_links.end(); ++link_it) { // get all collisions of the link physics::Collision_V collisions = link_it->get()->GetCollisions(); std::cout << "\t Link: " << link_it->get()->GetName() << std::endl; // iterate through all the collisions for (physics::Collision_V::iterator collision_it = collisions.begin(); collision_it != collisions.end(); ++collision_it) { std::cout << "\t\t Collision: " << (*collision_it)->GetName() << std::endl; physics::CollisionPtr coll_ptr = boost::static_pointer_cast<physics::Collision>(*collision_it); // check the geometry type of the given collision sdf::ElementPtr geometry_elem = coll_ptr->GetSDF()->GetElement("geometry"); // get the name of the geometry std::string geometry_type = geometry_elem->GetFirstElement()->GetName(); // check type of the geometry if (geometry_type == "box") { // Get the size of the box ignition::math::Vector3d size = geometry_elem->GetElement(geometry_type)->Get<ignition::math::Vector3d>("size"); // Create box shape common::MeshManager::Instance()->CreateBox((*collision_it)->GetName(), ignition::math::Vector3d(size.X(), size.Y(), size.Z()), ignition::math::Vector2d(1, 1)); // Generate an obj file in the temporary directory containing the mesh of the box RegisterMesh(*collision_it, "obj", objFilePath); } else if (geometry_type == "cylinder") { // Cylinder dimensions double radius = geometry_elem->GetElement(geometry_type)->GetElement("radius")->Get<double>(); double length = geometry_elem->GetElement(geometry_type)->GetElement("length")->Get<double>(); // Create cylinder mesh common::MeshManager::Instance()->CreateCylinder((*collision_it)->GetName(), radius, length, 32, 32); //Generate an obj file in the temporary directory containing the mesh of the cylinder RegisterMesh(*collision_it, "obj", objFilePath); } else if (geometry_type == "sphere") { // Sphere radius double radius = geometry_elem->GetElement(geometry_type)->GetElement("radius")->Get<double>(); // Create a sphere mesh common::MeshManager::Instance()->CreateSphere((*collision_it)->GetName(), radius, 32, 32); // Generate an obj file in the temporary directory containing the mesh of the sphere RegisterMesh(*collision_it, "obj", objFilePath); } else if (geometry_type == "plane") { ignition::math::Vector3d normal; ignition::math::Vector2d size; // Plane dimensions. To prevent a huge plane which causes problems when // sampling it, for now it is harcoded if ((*collision_it)->GetName() == "collision_ground_plane") { normal = ignition::math::Vector3d(0, 0, 1); // = geom_elem->GetElement(geom_type)->GetElement("normal")->Get<ignition::math::Vector3d>(); size = ignition::math::Vector2d(2.0, 2.0); //= geom_elem->GetElement(geom_type)->GetElement("size")->Get<ignition::math::Vector2d>(); } else { normal = geometry_elem->GetElement(geometry_type)->GetElement("normal")->Get<ignition::math::Vector3d>(); size = geometry_elem->GetElement(geometry_type)->GetElement("size")->Get<ignition::math::Vector2d>(); } // Generate the plane mesh common::MeshManager::Instance()->CreatePlane((*collision_it)->GetName(), ignition::math::Vector3d(0.0, 0.0, 1.0), 0.0, size, ignition::math::Vector2d(4.0, 4.0), ignition::math::Vector2d()); //Generate an obj file in the temporary directory containing the mesh of the plane RegisterMesh(*collision_it, "obj", objFilePath); } else if (geometry_type == "mesh") { // get the uri element value const std::string uri = geometry_elem->GetElement(geometry_type)->GetElement("uri")->Get<std::string>(); // get the filepath from the uri const std::string filepath = common::SystemPaths::Instance()->FindFileURI(uri); const gazebo::common::Mesh *mesh = common::MeshManager::Instance()->GetMesh(filepath); std::string fullMeshPath = objFilePath + (*collision_it)->GetModel()->GetName() + "_" + (*collision_it)->GetName() + ".obj"; // Export the mesh to a temp file in the selected format common::MeshManager::Instance()->Export(mesh, FileSystem::normalizePath(fullMeshPath), "obj"); base->processBoundary(*collision_it, fullMeshPath); } else { // Error for other possible weird types gzerr << "Collision type [" << geometry_type << "] unimplemented\n"; } } } } } void FluidSimulator::reset() { /* Utilities::Timing::printAverageTimes(); Utilities::Timing::reset(); Utilities::Counting::printAverageCounts(); Utilities::Counting::reset(); Simulation::getCurrent()->reset(); base->reset(); */ } GZ_REGISTER_WORLD_PLUGIN(FluidSimulator)
34.823529
194
0.694785
ManosAgelidis
3c8aa450c85ee35f33e7ec707c374146b4c4a929
792
cpp
C++
Leetcode/construct_binary_search_tree.cpp
amrfahmyy/Problem-Solving
4c7540a1df3c4be206fc6dc6c77d754b513b314f
[ "Apache-2.0" ]
null
null
null
Leetcode/construct_binary_search_tree.cpp
amrfahmyy/Problem-Solving
4c7540a1df3c4be206fc6dc6c77d754b513b314f
[ "Apache-2.0" ]
null
null
null
Leetcode/construct_binary_search_tree.cpp
amrfahmyy/Problem-Solving
4c7540a1df3c4be206fc6dc6c77d754b513b314f
[ "Apache-2.0" ]
1
2021-04-02T14:20:11.000Z
2021-04-02T14:20:11.000Z
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: int id; TreeNode* solve(vector<int>& preorder , int limit ){ if(id >= preorder.size() ){ return NULL; } int curr_value = preorder[id]; if(curr_value > limit){ return NULL; } TreeNode* root = new TreeNode(curr_value); id++; root->left = solve(preorder, curr_value ); root->right = solve(preorder, limit ); return root; } TreeNode* bstFromPreorder(vector<int>& preorder) { id = 0; return solve(preorder , INT_MAX); } };
20.842105
59
0.525253
amrfahmyy
3c937dfd6c6cbc326643346943b5242e24a5697f
3,170
cpp
C++
RedneckEngine/TestCube.cpp
TheHolyBell/RedneckEngine
3534b24de3ef5336bec9f7b04c31cbb4a5b8cc6e
[ "MIT" ]
null
null
null
RedneckEngine/TestCube.cpp
TheHolyBell/RedneckEngine
3534b24de3ef5336bec9f7b04c31cbb4a5b8cc6e
[ "MIT" ]
null
null
null
RedneckEngine/TestCube.cpp
TheHolyBell/RedneckEngine
3534b24de3ef5336bec9f7b04c31cbb4a5b8cc6e
[ "MIT" ]
null
null
null
#include "TestCube.h" #include "Cube.h" #include "BindableCodex.h" #include "ImGui\imgui.h" #include "BindableCommon.h" #include "Texture.h" #include "Sampler.h" #include "TransformCbufDoubleBoi.h" #include "DepthStencil.h" using namespace DirectX; TestCube::TestCube(Graphics& gfx, float size) { using namespace Bind; auto model = Cube::MakeIndependentTextured(); model.Transform(XMMatrixScaling(size, size, size)); model.SetNormalsIndependentFlat(); m_UID = "$cube." + std::to_string(size); AddBind(VertexBuffer::Resolve(gfx, m_UID, model.vertices)); AddBind(IndexBuffer::Resolve(gfx, m_UID, model.indices)); AddBind(Texture::Resolve(gfx, "Images\\brickwall.jpg")); AddBind(Texture::Resolve(gfx, "Images\\brickwall_normal.jpg", 1.0f)); AddBind(Sampler::Resolve(gfx)); auto pvs = VertexShader::Resolve(gfx, "PhongVS.cso"); auto pvsbc = pvs->GetBytecode(); AddBind(std::move(pvs)); AddBind(PixelShader::Resolve(gfx, "PhongPSNormalMap.cso")); AddBind(PixelConstantBuffer<PSMaterialConstant>::Resolve(gfx, pmc, 1.0f)); AddBind(InputLayout::Resolve(gfx, model.vertices.GetLayout(), pvsbc)); AddBind(Topology::Resolve(gfx, D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST)); AddBind(std::make_shared<TransformCbufDoubleBoi>(gfx, *this, 0, 2)); AddBind(std::make_shared<Blender>(gfx, false, 0.5f)); AddBind(Rasterizer::Resolve(gfx, false)); AddBind(Topology::Resolve(gfx, D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST)); AddBind(DepthStencil::Resolve(gfx)); } void TestCube::SetPos(DirectX::XMFLOAT3 pos) noexcept { m_pos = pos; } void TestCube::SetRotation(float pitch, float yaw, float roll) noexcept { this->pitch = pitch; this->yaw = yaw; this->roll = roll; } void TestCube::Draw(Graphics& gfx) const noexcept(!IS_DEBUG) { Drawable::Draw(gfx); } DirectX::XMMATRIX TestCube::GetTransformXM() const noexcept { return XMMatrixRotationRollPitchYaw(pitch, yaw, roll) * XMMatrixTranslation(m_pos.x, m_pos.y, m_pos.z); } std::string TestCube::GetUID() const noexcept { return m_UID; } void TestCube::ItemSelected() noexcept { m_bMenu = true; } bool TestCube::IsMenuDrawable() const noexcept { return m_bMenu; } void TestCube::DrawMenu(Graphics& gfx) noexcept { if (ImGui::Begin(m_UID.c_str(), &m_bMenu)) { ImGui::Text("Position"); ImGui::SliderFloat("X", &m_pos.x, -80.0f, 80.0f, "%.1f"); ImGui::SliderFloat("Y", &m_pos.y, -80.0f, 80.0f, "%.1f"); ImGui::SliderFloat("Z", &m_pos.z, -80.0f, 80.0f, "%.1f"); ImGui::Text("Orientation"); ImGui::SliderAngle("Pitch", &pitch, -180.0f, 180.0f); ImGui::SliderAngle("Yaw", &yaw, -180.0f, 180.0f); ImGui::SliderAngle("Roll", &roll, -180.0f, 180.0f); ImGui::Text("Shading"); bool changed0 = ImGui::SliderFloat("Spec. Int.", &pmc.specularIntensity, 0.0f, 1.0f); bool changed1 = ImGui::SliderFloat("Spec. Power", &pmc.specularPower, 0.0f, 100.0f); bool checkState = pmc.normalMappingEnabled == TRUE; bool changed2 = ImGui::Checkbox("Enable Normal Map", &checkState); pmc.normalMappingEnabled = checkState ? TRUE : FALSE; if (changed0 || changed1 || changed2) { QueryBindable<Bind::PixelConstantBuffer<PSMaterialConstant>>()->Update(gfx, pmc); } } ImGui::End(); }
27.327586
87
0.714196
TheHolyBell
3c9440e837a8092f0aa831c54ba9f3b65900d62e
2,969
cpp
C++
Behaviour/Source/Behaviour/BehaviourModifier.cpp
DeLaMercedRichard/AIbs_Demo
e5a1d2e870c1d0919d456df31f34fe0520b6975d
[ "MIT" ]
1
2020-04-05T22:10:34.000Z
2020-04-05T22:10:34.000Z
Behaviour/Source/Behaviour/BehaviourModifier.cpp
DeLaMercedRichard/AIbs_Demo
e5a1d2e870c1d0919d456df31f34fe0520b6975d
[ "MIT" ]
null
null
null
Behaviour/Source/Behaviour/BehaviourModifier.cpp
DeLaMercedRichard/AIbs_Demo
e5a1d2e870c1d0919d456df31f34fe0520b6975d
[ "MIT" ]
1
2020-02-04T11:36:54.000Z
2020-02-04T11:36:54.000Z
#include "BehaviourModifier.h" BehaviourModifier::BehaviourModifier() { } BehaviourModifier::~BehaviourModifier() { //Do I still Delete ID? //Or just set it to nullptr delete ID; ID = nullptr; } void BehaviourModifier::AttachID(std::string &ID_) { *ID = ID_; } void BehaviourModifier::GenerateGenderTrait(bool autoGenerateGenders, int genderRatio) { //Takes the string value of the ID and assigns 1/2 male and 1/2 female population if (autoGenerateGenders) { if (std::stoi(*ID) % genderRatio == 0) { genderTrait = true; } else { genderTrait = false; } } else { genderTrait = true; } } void BehaviourModifier::AdjustPersonality(int personalityType, double distributionMean, double distributionOffset) { switch (personalityType) { case 0: personality00.adjustDistribution(distributionMean, distributionOffset); break; case 1: personality01.adjustDistribution(distributionMean, distributionOffset); break; case 2: personality02.adjustDistribution(distributionMean, distributionOffset); break; case 3: personality03.adjustDistribution(distributionMean, distributionOffset); break; default: personalityType = 0; break; } } void BehaviourModifier::ForcefullySetPersonalityValue(int personalityValue, double value) { switch (personalityValue) { case 0: personality00.setValueForcefully(value); break; case 1: personality01.setValueForcefully(value); break; case 2: personality02.setValueForcefully(value); break; case 3: personality03.setValueForcefully(value); break; default: personalityValue = 0; break; } } void BehaviourModifier::EstablishPersonality() { personality00.EstablishPersonality(genderTrait); personality01.EstablishPersonality(genderTrait); personality02.EstablishPersonality(genderTrait); personality03.EstablishPersonality(genderTrait); } void BehaviourModifier::PrintPersonalityInfo(int personalityType) { switch (personalityType) { case 0: personality00.Print(); break; case 1: personality01.Print(); break; case 2: personality02.Print(); break; case 3: personality03.Print(); break; default: personalityType = 0; break; } } std::string BehaviourModifier::getPersonalityName(int personalityType) { switch (personalityType) { case 0: return personality00.getPersonalityName(); break; case 1: return personality01.getPersonalityName(); break; case 2: return personality02.getPersonalityName(); break; case 3: return personality03.getPersonalityName(); break; default: return personality00.getPersonalityName(); break; } } double BehaviourModifier::getPersonalityValue(int personalityType) { switch (personalityType) { case 0: return personality00.getValue(); break; case 1: return personality01.getValue(); break; case 2: return personality02.getValue(); break; case 3: return personality03.getValue(); break; default: return personality00.getValue(); break; } }
17.993939
114
0.748063
DeLaMercedRichard
3c961b08ca4de85f011a68851f48edffdc14be40
4,332
cpp
C++
utils/Utils.cpp
turol/smaaDemo
d6e02955b1b5396162d2ba67b78798e43cebfc57
[ "MIT" ]
64
2015-10-30T10:06:24.000Z
2022-03-10T01:47:25.000Z
utils/Utils.cpp
turol/smaaDemo
d6e02955b1b5396162d2ba67b78798e43cebfc57
[ "MIT" ]
7
2015-11-29T09:52:37.000Z
2020-12-14T11:00:33.000Z
utils/Utils.cpp
turol/smaaDemo
d6e02955b1b5396162d2ba67b78798e43cebfc57
[ "MIT" ]
5
2015-12-28T21:07:20.000Z
2021-01-28T09:25:36.000Z
/* Copyright (c) 2015-2021 Alternative Games Ltd / Turo Lamminen 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 <cassert> #include <cerrno> #include <cstring> #include <sys/stat.h> #include <stdexcept> #include "Utils.h" #include <SDL.h> struct FILEDeleter { void operator()(FILE *f) { fclose(f); } }; static FILE *logFile; void logInit() { assert(!logFile); char *logFilePath = SDL_GetPrefPath("", "SMAADemo"); std::string logFileName(logFilePath); SDL_free(logFilePath); logFileName += "logfile.txt"; logFile = fopen(logFileName.c_str(), "wb"); } void logWrite(const nonstd::string_view &message) { // Write to console if opening log file failed FILE *f = logFile ? logFile : stdout; fwrite(message.data(), 1, message.size(), f); fputc('\n', f); } void logWriteError(const nonstd::string_view &message) { // Write to log and stderr if (logFile) { fwrite(message.data(), 1, message.size(), logFile); fputc('\n', logFile); fflush(logFile); } fwrite(message.data(), 1, message.size(), stderr); fputc('\n', stderr); fflush(stderr); } void logShutdown() { assert(logFile); fflush(logFile); fclose(logFile); logFile = nullptr; } void logFlush() { assert(logFile); fflush(logFile); } std::vector<char> readTextFile(std::string filename) { std::unique_ptr<FILE, FILEDeleter> file(fopen(filename.c_str(), "rb")); if (!file) { THROW_ERROR("file not found {}", filename); } int fd = fileno(file.get()); if (fd < 0) { THROW_ERROR("no fd"); } struct stat statbuf; memset(&statbuf, 0, sizeof(struct stat)); int retval = fstat(fd, &statbuf); if (retval < 0) { THROW_ERROR("fstat failed for \"{}\": {}", filename, strerror(errno)); } unsigned int filesize = static_cast<unsigned int>(statbuf.st_size); // ensure NUL -termination std::vector<char> buf(filesize + 1, '\0'); size_t ret = fread(&buf[0], 1, filesize, file.get()); if (ret != filesize) { THROW_ERROR("fread failed"); } return buf; } std::vector<char> readFile(std::string filename) { std::unique_ptr<FILE, FILEDeleter> file(fopen(filename.c_str(), "rb")); if (!file) { THROW_ERROR("file not found {}", filename); } int fd = fileno(file.get()); if (fd < 0) { THROW_ERROR("no fd"); } struct stat statbuf; memset(&statbuf, 0, sizeof(struct stat)); int retval = fstat(fd, &statbuf); if (retval < 0) { THROW_ERROR("fstat failed for \"{}\": {}", filename, strerror(errno)); } unsigned int filesize = static_cast<unsigned int>(statbuf.st_size); std::vector<char> buf(filesize, '\0'); size_t ret = fread(&buf[0], 1, filesize, file.get()); if (ret != filesize) { THROW_ERROR("fread failed"); } return buf; } void writeFile(const std::string &filename, const void *contents, size_t size) { std::unique_ptr<FILE, FILEDeleter> file(fopen(filename.c_str(), "wb")); fwrite(contents, 1, size, file.get()); } bool fileExists(const std::string &filename) { std::unique_ptr<FILE, FILEDeleter> file(fopen(filename.c_str(), "rb")); if (file) { return true; } else { return false; } } int64_t getFileTimestamp(const std::string &filename) { struct stat statbuf; memset(&statbuf, 0, sizeof(struct stat)); int retval = stat(filename.c_str(), &statbuf); if (retval < 0) { THROW_ERROR("fstat failed for \"{}\": {}", filename, strerror(errno)); } return statbuf.st_mtime; }
23.416216
80
0.695522
turol
3c9675a5b03d019456953620329634d31e6c657b
5,188
hpp
C++
domain/include/cstone/util/util.hpp
j-piccinali/SPH-EXA_mini-app
c3ba4d37f2edf433710d5c0bc2362ec35e75df32
[ "MIT" ]
14
2019-03-18T12:51:43.000Z
2021-11-09T14:40:36.000Z
domain/include/cstone/util/util.hpp
j-piccinali/SPH-EXA_mini-app
c3ba4d37f2edf433710d5c0bc2362ec35e75df32
[ "MIT" ]
41
2019-10-08T19:53:55.000Z
2021-11-23T06:56:03.000Z
domain/include/cstone/util/util.hpp
j-piccinali/SPH-EXA_mini-app
c3ba4d37f2edf433710d5c0bc2362ec35e75df32
[ "MIT" ]
8
2019-06-20T07:11:52.000Z
2021-10-05T13:44:07.000Z
/* * MIT License * * Copyright (c) 2021 CSCS, ETH Zurich * 2021 University of Basel * * 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. */ /*! @file * @brief General purpose utilities * * @author Sebastian Keller <[email protected]> */ #pragma once #include <utility> #include "cstone/cuda/annotation.hpp" /*! @brief A template to create structs as a type-safe version to using declarations * * Used in public API functions where a distinction between different * arguments of the same underlying type is desired. This provides a type-safe * version to using declarations. Instead of naming a type alias, the name * is used to define a struct that inherits from StrongType<T>, where T is * the underlying type. * * Due to the T() conversion and assignment from T, * an instance of StrongType<T> struct behaves essentially like an actual T, while construction * from T is disabled. This makes it impossible to pass a T as a function parameter * of type StrongType<T>. */ template<class T, class Phantom> struct StrongType { using ValueType [[maybe_unused]] = T; //! default ctor constexpr HOST_DEVICE_FUN StrongType() : value_{} {} //! construction from the underlying type T, implicit conversions disabled explicit constexpr HOST_DEVICE_FUN StrongType(T v) : value_(std::move(v)) {} //! assignment from T constexpr HOST_DEVICE_FUN StrongType& operator=(T v) { value_ = std::move(v); return *this; } //! conversion to T constexpr HOST_DEVICE_FUN operator T() const { return value_; } // NOLINT //! access the underlying value constexpr HOST_DEVICE_FUN T value() const { return value_; } private: T value_; }; /*! @brief StrongType equality comparison * * Requires that both T and Phantom template parameters match. * For the case where a comparison between StrongTypes with matching T, but differing Phantom * parameters is desired, the underlying value attribute should be compared instead */ template<class T, class Phantom> constexpr HOST_DEVICE_FUN bool operator==(const StrongType<T, Phantom>& lhs, const StrongType<T, Phantom>& rhs) { return lhs.value() == rhs.value(); } //! @brief comparison function < template<class T, class Phantom> constexpr HOST_DEVICE_FUN bool operator<(const StrongType<T, Phantom>& lhs, const StrongType<T, Phantom>& rhs) { return lhs.value() < rhs.value(); } //! @brief comparison function > template<class T, class Phantom> constexpr HOST_DEVICE_FUN bool operator>(const StrongType<T, Phantom>& lhs, const StrongType<T, Phantom>& rhs) { return lhs.value() > rhs.value(); } //! @brief addition template<class T, class Phantom> constexpr HOST_DEVICE_FUN StrongType<T, Phantom> operator+(const StrongType<T, Phantom>& lhs, const StrongType<T, Phantom>& rhs) { return StrongType<T, Phantom>(lhs.value() + rhs.value()); } //! @brief subtraction template<class T, class Phantom> constexpr HOST_DEVICE_FUN StrongType<T, Phantom> operator-(const StrongType<T, Phantom>& lhs, const StrongType<T, Phantom>& rhs) { return StrongType<T, Phantom>(lhs.value() - rhs.value()); } //! @brief simple pair that's usable in both CPU and GPU code template<class T> class pair { public: constexpr pair() = default; HOST_DEVICE_FUN constexpr pair(T first, T second) : data{first, second} {} HOST_DEVICE_FUN constexpr T& operator[](int i) { return data[i]; } HOST_DEVICE_FUN constexpr const T& operator[](int i) const { return data[i]; } private: HOST_DEVICE_FUN friend constexpr bool operator==(const pair& a, const pair& b) { return a.data[0] == b.data[0] && a.data[1] == b.data[1]; } HOST_DEVICE_FUN friend constexpr bool operator<(const pair& a, const pair& b) { bool c0 = a.data[0] < b.data[0]; bool e0 = a.data[0] == b.data[0]; bool c1 = a.data[1] < b.data[1]; return c0 || (e0 && c1); } T data[2]; }; //! @brief ceil(divident/divisor) for integers HOST_DEVICE_FUN constexpr unsigned iceil(size_t dividend, unsigned divisor) { return (dividend + divisor - 1) / divisor; }
32.223602
102
0.707016
j-piccinali
3c977fa0b4aff05ed2221cfc9967e8e5ed81746e
5,583
hpp
C++
core/KVMESC.hpp
Domaman202/DmNKVM
e867f5369426954ad7836aba47cc86f9b657d5b2
[ "MIT" ]
1
2021-07-24T14:33:54.000Z
2021-07-24T14:33:54.000Z
core/KVMESC.hpp
Domaman202/DmNKVM
e867f5369426954ad7836aba47cc86f9b657d5b2
[ "MIT" ]
null
null
null
core/KVMESC.hpp
Domaman202/DmNKVM
e867f5369426954ad7836aba47cc86f9b657d5b2
[ "MIT" ]
null
null
null
#ifndef DMN_KVM_NO_USE_PRAGMA #pragma once #endif /* DMN_KVM_NO_USE_PRAGMA */ #ifndef DMN_KVM_ESC_HPP #define DMN_KVM_ESC_HPP #include "KVMTypes.hpp" #include <cstdint> namespace DmN::KVM { /// Объект (нет) который может быть инстансирован struct Instanceble_t { virtual Object_t *newInstance(Value_t **args, size_t args_c) { return nullptr; }; }; /// Универсальная основа для Enum-а struct Enum_t : public LLTNameble, public Modifiable, public Instanceble_t, public FieldStorage_t { explicit Enum_t(SI_t name, uint8_t modifier, Value_t **enums, SI_t *names, uint8_t enumsCount) : LLTNameble(name, LLTypes::ENUM), Modifiable(modifier) { this->enums = enums; this->names = names; this->enumsCount = enumsCount; } SDL::DmNCollection<Field_t> *getFields() override { return nullptr; // TODO: } struct Object_t *newInstance(Value_t **args, size_t args_c) override { return nullptr; // TODO: } /// Перечисления Value_t **enums; /// Имена перечислений SI_t *names; /// Кол-во перечислений uint8_t enumsCount; }; /// Универсальная основа для структуры struct Struct_t : public LLTNameble, public Modifiable, public Instanceble_t, public FieldStorage_t { explicit Struct_t(SI_t name, uint8_t modifier, Field_t **fields, uint8_t fieldsCount, CI_t *parents, uint8_t parentsCount) : LLTNameble(name, LLTypes::STRUCT), Modifiable(modifier) { this->fields = fields; this->fieldsCount = fieldsCount; this->parents = parents; this->parentsCount = parentsCount; } SDL::DmNCollection<Field_t> *getFields() override { return nullptr; // TODO: } struct Object_t *newInstance(Value_t **args, size_t args_c) override { return nullptr; // TODO: } /// Поля Field_t **fields; /// Кол-во полей uint8_t fieldsCount; /// Предки (ID предков) CI_t *parents; /// Кол-во предков uint8_t parentsCount: 5; }; /// Универсальная основа для Class-а class Class_t : public LLTNameble, public Modifiable, public Instanceble_t, public FieldStorage_t, public MethodStorage_t { public: explicit Class_t(SI_t name, uint8_t modifier, Field_t **fields, uint8_t fieldsCount, Method_t **methods, uint8_t methodsCount, CI_t *parents, uint8_t parentsCount) : LLTNameble(name, LLTypes::CLASS), Modifiable(modifier) { this->fields = fields; this->fieldsCount = fieldsCount; this->methods = methods; this->methodsCount = methodsCount; this->parents = parents; this->parentsCount = parentsCount; } SDL::DmNCollection<Field_t> *getFields() override { return nullptr; // TODO: } SDL::DmNCollection<Method_t> *getMethods() override { return nullptr; // TODO: } struct Object_t *newInstance(Value_t **args, size_t args_c) override { return nullptr; // TODO: } /// Массив полей Field_t **fields; /// Кол-во полей uint8_t fieldsCount; /// Массив методов Method_t **methods; /// Кол-во методов uint8_t methodsCount; /// Предки (ID предков) CI_t *parents; /// Кол-во предков uint8_t parentsCount: 5; }; /// Основа класса со встроенными классами class ISClass_t : public Class_t { public: explicit ISClass_t(Class_t *base, SI_t name, uint8_t modifier, Field_t **fields, uint32_t fieldsCount, Method_t **methods, uint32_t methodsCount, CI_t *parents, uint8_t parentsCount) : Class_t(name, modifier, fields, fieldsCount, methods, methodsCount, parents, parentsCount) { this->base = base; } /// Основной класс Class_t *base; }; class EnumClass_t : public Class_t, public Enum_t { SDL::DmNCollection<Field_t> *getFields() override { return nullptr; // TODO: } SDL::DmNCollection<Method_t> *getMethods() override { return nullptr; // TODO: } }; } #endif /* DMN_KVM_ESC_HPP */
36.253247
113
0.475551
Domaman202
3c9a649771c9a9087e5c623efd774c7e68b059bc
6,747
cpp
C++
firmware/examples/4_temp_logger.cpp
monkbroc/makerkit
e6924eee209da662a47df9a5da1bf97d07ee599d
[ "BSD-3-Clause" ]
3
2019-03-20T01:23:22.000Z
2020-09-17T20:04:48.000Z
firmware/examples/4_temp_logger.cpp
monkbroc/makerkit
e6924eee209da662a47df9a5da1bf97d07ee599d
[ "BSD-3-Clause" ]
null
null
null
firmware/examples/4_temp_logger.cpp
monkbroc/makerkit
e6924eee209da662a47df9a5da1bf97d07ee599d
[ "BSD-3-Clause" ]
null
null
null
/************************************************************************ This sketch reads the temperature from a OneWire device and then publishes to the Particle cloud. From there, IFTTT can be used to log the date, time, and temperature to a Google Spreadsheet. Read more in our tutorial here: http://docs.particle.io/tutorials/topics/maker-kit This sketch is the same as the example from the OneWire library, but with the addition of three lines at the end to publish the data to the cloud. Use this sketch to read the temperature from 1-Wire devices you have attached to your Particle device (core, p0, p1, photon, electron) Temperature is read from: DS18S20, DS18B20, DS1822, DS2438 Expanding on the enumeration process in the address scanner, this example reads the temperature and outputs it from known device types as it scans. I/O setup: These made it easy to just 'plug in' my 18B20 (note that a bare TO-92 sensor may read higher than it should if it's right next to the Photon) D3 - 1-wire ground, or just use regular pin and comment out below. D4 - 1-wire signal, 2K-10K resistor to D5 (3v3) D5 - 1-wire power, ditto ground comment. A pull-up resistor is required on the signal line. The spec calls for a 4.7K. I have used 1K-10K depending on the bus configuration and what I had out on the bench. If you are powering the device, they all work. If you are using parisidic power it gets more picky about the value. NOTE: This sketch requires the OneWire library, which can be added from the <-- Libraries tab on the left. ************************************************************************/ OneWire ds = OneWire(D4); // 1-wire signal on pin D4 unsigned long lastUpdate = 0; float lastTemp; void setup() { Serial.begin(9600); // Set up 'power' pins, comment out if not used! pinMode(D3, OUTPUT); pinMode(D5, OUTPUT); digitalWrite(D3, LOW); digitalWrite(D5, HIGH); } // up to here, it is the same as the address acanner // we need a few more variables for this example void loop(void) { byte i; byte present = 0; byte type_s; byte data[12]; byte addr[8]; float celsius, fahrenheit; if ( !ds.search(addr)) { Serial.println("No more addresses."); Serial.println(); ds.reset_search(); delay(250); return; } // The order is changed a bit in this example // first the returned address is printed Serial.print("ROM ="); for( i = 0; i < 8; i++) { Serial.write(' '); Serial.print(addr[i], HEX); } // second the CRC is checked, on fail, // print error and just return to try again if (OneWire::crc8(addr, 7) != addr[7]) { Serial.println("CRC is not valid!"); return; } Serial.println(); // we have a good address at this point // what kind of chip do we have? // we will set a type_s value for known types or just return // the first ROM byte indicates which chip switch (addr[0]) { case 0x10: Serial.println(" Chip = DS1820/DS18S20"); type_s = 1; break; case 0x28: Serial.println(" Chip = DS18B20"); type_s = 0; break; case 0x22: Serial.println(" Chip = DS1822"); type_s = 0; break; case 0x26: Serial.println(" Chip = DS2438"); type_s = 2; break; default: Serial.println("Unknown device type."); return; } // this device has temp so let's read it ds.reset(); // first clear the 1-wire bus ds.select(addr); // now select the device we just found // ds.write(0x44, 1); // tell it to start a conversion, with parasite power on at the end ds.write(0x44, 0); // or start conversion in powered mode (bus finishes low) // just wait a second while the conversion takes place // different chips have different conversion times, check the specs, 1 sec is worse case + 250ms // you could also communicate with other devices if you like but you would need // to already know their address to select them. delay(1000); // maybe 750ms is enough, maybe not, wait 1 sec for conversion // we might do a ds.depower() (parasite) here, but the reset will take care of it. // first make sure current values are in the scratch pad present = ds.reset(); ds.select(addr); ds.write(0xB8,0); // Recall Memory 0 ds.write(0x00,0); // Recall Memory 0 // now read the scratch pad present = ds.reset(); ds.select(addr); ds.write(0xBE,0); // Read Scratchpad if (type_s == 2) { ds.write(0x00,0); // The DS2438 needs a page# to read } // transfer and print the values Serial.print(" Data = "); Serial.print(present, HEX); Serial.print(" "); for ( i = 0; i < 9; i++) { // we need 9 bytes data[i] = ds.read(); Serial.print(data[i], HEX); Serial.print(" "); } Serial.print(" CRC="); Serial.print(OneWire::crc8(data, 8), HEX); Serial.println(); // Convert the data to actual temperature // because the result is a 16 bit signed integer, it should // be stored to an "int16_t" type, which is always 16 bits // even when compiled on a 32 bit processor. int16_t raw = (data[1] << 8) | data[0]; if (type_s == 2) raw = (data[2] << 8) | data[1]; byte cfg = (data[4] & 0x60); switch (type_s) { case 1: raw = raw << 3; // 9 bit resolution default if (data[7] == 0x10) { // "count remain" gives full 12 bit resolution raw = (raw & 0xFFF0) + 12 - data[6]; } celsius = (float)raw * 0.0625; break; case 0: // at lower res, the low bits are undefined, so let's zero them if (cfg == 0x00) raw = raw & ~7; // 9 bit resolution, 93.75 ms if (cfg == 0x20) raw = raw & ~3; // 10 bit res, 187.5 ms if (cfg == 0x40) raw = raw & ~1; // 11 bit res, 375 ms // default is 12 bit resolution, 750 ms conversion time celsius = (float)raw * 0.0625; break; case 2: data[1] = (data[1] >> 3) & 0x1f; if (data[2] > 127) { celsius = (float)data[2] - ((float)data[1] * .03125); }else{ celsius = (float)data[2] + ((float)data[1] * .03125); } } // remove random errors if((((celsius <= 0 && celsius > -1) && lastTemp > 5)) || celsius > 125) { celsius = lastTemp; } fahrenheit = celsius * 1.8 + 32.0; lastTemp = celsius; Serial.print(" Temperature = "); Serial.print(celsius); Serial.print(" Celsius, "); Serial.print(fahrenheit); Serial.println(" Fahrenheit"); // now that we have the readings, we can publish them to the cloud String temperature = String(fahrenheit); // store temp in "temperature" string Particle.publish("temperature", temperature, PRIVATE); // publish to dashboard delay(5000); // 5-sec delay }
31.528037
98
0.625019
monkbroc
3c9a7c548c0ee4a27e8807207146ef45e767a93b
2,030
cpp
C++
src/126.word_ladder_ii/code.cpp
cloudzfy/leetcode
9d32090429ef297e1f62877382bff582d247266a
[ "MIT" ]
1
2016-07-02T17:44:10.000Z
2016-07-02T17:44:10.000Z
src/126.word_ladder_ii/code.cpp
cloudzfy/leetcode
9d32090429ef297e1f62877382bff582d247266a
[ "MIT" ]
null
null
null
src/126.word_ladder_ii/code.cpp
cloudzfy/leetcode
9d32090429ef297e1f62877382bff582d247266a
[ "MIT" ]
1
2019-12-21T04:57:15.000Z
2019-12-21T04:57:15.000Z
class Solution { private: unordered_map<string, int> pathLevel; unordered_map<string, vector<string>> nextNode; vector<vector<string>> ans; public: vector<vector<string>> findLadders(string beginWord, string endWord, unordered_set<string> &wordList) { bfs(wordList, beginWord, endWord); vector<string> myans; dfs(wordList, beginWord, endWord, myans); return ans; } void bfs(unordered_set<string>& wordList, string beginWord, string endWord) { queue<string> q; q.push(beginWord); pathLevel[beginWord] = 0; while (!q.empty()) { string curWord = q.front(); q.pop(); int level = pathLevel[curWord]; if (curWord == endWord) continue; vector<string> myNextNode; for (int i = 0; i < curWord.length(); i++) { string nextWord = curWord; for (int j = 0; j < 26; j++) { if (curWord[i] == 'a' + j) continue; nextWord[i] = 'a' + j; if (wordList.find(nextWord) == wordList.end()) continue; if (pathLevel.find(nextWord) == pathLevel.end()) { pathLevel[nextWord] = level + 1; q.push(nextWord); } if (pathLevel[nextWord] == level + 1) myNextNode.push_back(nextWord); } } nextNode[curWord] = myNextNode; } } void dfs(unordered_set<string>& wordList, string curWord, string endWord, vector<string>& myans) { myans.push_back(curWord); if (curWord == endWord) { ans.push_back(myans); myans.pop_back(); return; } int level = pathLevel[curWord]; vector<string> myNextNode = nextNode[curWord]; for (int i = 0; i < myNextNode.size(); i++) { dfs(wordList, myNextNode[i], endWord, myans); } myans.pop_back(); } };
35.614035
107
0.519704
cloudzfy
3c9df28370629a72fd052162faba89972dee0c8d
17,105
cxx
C++
logger/dnk_biphasic_offset_cli.cxx
trotill/11parts_CPP
53a69d516fdcb5c92b591b5dadc49dfdd2a3b26b
[ "MIT" ]
null
null
null
logger/dnk_biphasic_offset_cli.cxx
trotill/11parts_CPP
53a69d516fdcb5c92b591b5dadc49dfdd2a3b26b
[ "MIT" ]
null
null
null
logger/dnk_biphasic_offset_cli.cxx
trotill/11parts_CPP
53a69d516fdcb5c92b591b5dadc49dfdd2a3b26b
[ "MIT" ]
null
null
null
/* * dnk_biphasic_offset_cli.cxx * * Created on: 30 сент. 2019 г. * Author: root */ #include "dnk_biphasic_offset_cli.h" #ifdef _HIREDIS eErrorTp dnk_biphasic_offset_cli::make_selection_by_interval(u64 ts_start_ms,u64 ts_stop_ms,u32 limit,rapidjson::Document & result_root){ if (fault==ERROR){ GPRINT(NORMAL_LEVEL,"make_selection_by_interval is fault\n"); return ERROR; } GPRINT(MEDIUM_LEVEL,"Make_selection_by_interval ts_start_ms %llu ts_stop_ms %llu point_limit %u\n",ts_start_ms,ts_stop_ms,limit); //GPRINT(NORMAL_LEVEL,"make_selection_by_interval M1\n"); result_root.SetObject(); std::pair<eErrorTp, vector<string>> res,res2; TIME_T ts_stop=(u64)ts_stop_ms/1000; TIME_T ts_start=(u64)ts_start_ms/1000; TIME_T tss; //Json::Reader read; string fn_old; string format_path[total_storage]; //Json::Value header_root; rapidjson::Document header_root; bool format_getting=false; // bool result_root_init=false; u32 aidx=0; u32 limf=(limit/dal_lines_in_block)+1; res=command("ZREVRANGEBYSCORE ts %lu %lu LIMIT 0 1",ts_start,0); TIME_T ts_start_tmp=ts_start; if ((res.second.size()==0)||(res.first==ERROR)){ GPRINT(HARD_LEVEL,"ZREVRANGEBYSCORE ts %lu %lu LIMIT 0 1 result is null, try next time %llu\n",ts_start,0,ts_start_ms); } else //поиск предыдущего фрагмента, для захвата всего диапазона ts_start_tmp=stol(res.second[0]); res=command("HMGET %u te",ts_start_tmp); if ((res.second.size()==0)||(res.first==ERROR)){ GPRINT(HARD_LEVEL,"HMGET %u te result is null\n",ts_start_tmp); } else{ //пропустить фрагмент если его содержимое старее ts_start_tmp TIME_T et=stol(res.second[0]); if (et<ts_start) ts_start_tmp=et; } if (ts_start_tmp>ts_stop) return NO_ERROR; //printf("sts %lu ts_start %lu ts_stop %lu limf %u\n",TIME(NULL),ts_start,ts_stop,limf); //Search in files GPRINT(MEDIUM_LEVEL,"ZRANGEBYSCORE ts %u %u LIMIT 0 %u\n",ts_start_tmp,ts_stop,limf); res=command("ZRANGEBYSCORE ts %u %u LIMIT 0 %u",ts_start_tmp,ts_stop,limf); if ((res.first==ERROR)||(res.second.size()==0)){ GetFormatPath(format_path); if (ReadJsonFormatFile_rpd(header_root,format_path)==ERROR){ return ERROR; } return make_selection_step_by_step_DB_All(ts_start_ms,ts_stop_ms,header_root,result_root); } u32 ctr=res.second.size(); GPRINT(MEDIUM_LEVEL,"Founded %d arch files\n",ctr); //printf("ts_start_ms %llu ts_stop_ms %llu ctr %u\n",ts_start_ms,ts_stop_ms,ctr); for (u32 z=0;z<ctr;z++){ res2=command("HMGET %s te cn ext crc",res.second[z].c_str()); TIME_T t_end=stoll(res2.second[0]); TIME_T t_st=stoll(res.second[z]); string fn=res.second[z]+'_'+res2.second[0]+':'+res2.second[1]+'['+res2.second[3]+"]."+res2.second[2]; string data; if (GetDataFromGzip(data,fn,t_st,format_path)==NO_ERROR){ rapidjson::Document dr_root; dr_root.SetObject(); rapidjson::Document data_root; rapidjson::ParseResult rapid_result=data_root.Parse(data.c_str()); if (rapid_result.Code()==0){ if (format_getting==false){ if (ReadJsonFormatFile_rpd(header_root,format_path)==ERROR){ return ERROR; } format_getting=true; } MakeObjectFromDataAndHeader_rpd(data_root,header_root,dr_root,false); if ((!dr_root.HasMember("t"))||(!dr_root["t"].IsArray())){ return ERROR; } for (u32 e=0;e<dr_root["m"].Size();e++){ TIME_T t=dr_root["t"][e].GetInt(); ts_start_ms=dr_root["m"][e].GetUint64()+1; if (t<ts_start){ GPRINT(MEDIUM_LEVEL,"Skip ts %lu < start_ts %lu\n",t,ts_start); continue; } if (t>ts_stop){ GPRINT(MEDIUM_LEVEL,"Skip ts %lu > ts_stop %lu\n",t,ts_stop); continue; } // printf(" point %llu, found %llu\n",dia[r].ts[k],dr_root["m"][e].asUInt64()); for (auto & key:dr_root.GetObject() ){ const char* keys=key.name.GetString(); if (result_root.HasMember(keys)==false){ rapidjson::Value val(rapidjson::kArrayType); rapidjson::Value index(keys, (u32)strlen(keys), result_root.GetAllocator()); result_root.AddMember(index,val,result_root.GetAllocator()); } //if (dr_root[keys][e].IsString()) // printf("add %s\n",dr_root[keys][e].GetString()); // if (dr_root[keys][e].IsUint()) // printf("add %u\n",dr_root[keys][e].GetUint()); result_root[keys].PushBack(dr_root[keys][e], result_root.GetAllocator()); } aidx++; if (aidx>=limit) break; //result_root_init=true; } } } } if (format_getting==false){ GetFormatPath(format_path); if (ReadJsonFormatFile_rpd(header_root,format_path)==ERROR){ return ERROR; } } make_selection_step_by_step_DB_All(ts_start_ms,ts_stop_ms,header_root,result_root); //printf("Search in DB %d\n",result_root["m"].size()); return NO_ERROR; } eErrorTp dnk_biphasic_offset_cli::make_selection_step_by_step_rpd(u64 ts_start_ms,u64 ts_stop_ms,u32 interval_ms,TIME_T point_limit,rapidjson::Document & result_root){ if (fault==ERROR){ GPRINT(NORMAL_LEVEL,"make_selection_step_by_step is fault\n"); return ERROR; } if (interval_ms==0) return ERROR; GPRINT(MEDIUM_LEVEL,"Make_selection_step_by_step ts_start_ms %llu ts_stop_ms %llu interval_ms %llu point_limit %u\n",ts_start_ms,ts_stop_ms,interval_ms,point_limit); result_root.SetObject(); std::pair<eErrorTp, vector<string>> res_t,res,res2; vector<diapason> dia; u64 saved_ts_stop_ms=ts_stop_ms; TIME_T ts_stop=ts_stop_ms/1000; TIME_T ts_start=ts_start_ms/1000; TIME_T ctr=((ts_stop_ms-ts_start_ms)/interval_ms)+1; if (ctr>point_limit) ctr=point_limit; TIME_T t_st; TIME_T t_end; string fn; u64 t_end_ms; u64 t_st_ms; TIME_T ctr_cntr=0; GPRINT(MEDIUM_LEVEL,"\n*****\n**make_selection_step_by_step [start %llu stop %llu cntr %u interval_ms %u]\n",ts_start_ms,ts_stop_ms,ctr,interval_ms); while ((ts_start_ms<ts_stop_ms)&&(ctr>=ctr_cntr)){ ts_start=ts_start_ms/1000; ctr_cntr++; res=command("ZREVRANGEBYSCORE ts %lu %lu LIMIT 0 1",ts_start,0); if ((res.second.size()==0)||(res.first==ERROR)){ ts_start_ms+=interval_ms; GPRINT(HARD_LEVEL,"ZREVRANGEBYSCORE ts %lu %lu LIMIT 0 1 result is null, try next time %llu\n",ts_start,0,ts_start_ms); continue; } t_st=stoll(res.second[0]); GPRINT(HARD_LEVEL,"got %d\n",res.second.size()); res2=command("HMGET %s te cn ext crc",res.second[0].c_str()); if ((res2.second.size()==0)||(res2.first==ERROR)){ ts_start_ms+=interval_ms; GPRINT(HARD_LEVEL,"HMGET %s te cn ext crc result is null, try next time %llu\n",res.second[0].c_str(),ts_start_ms); continue; } t_end=stoll(res2.second[0]); t_end_ms=(u64)t_end*1000; t_st_ms=(u64)t_st*1000; if ((ts_start>=t_st)&&(ts_start<=t_end)){ fn=res.second[0]+'_'+res2.second[0]+':'+res2.second[1]+'['+res2.second[3]+"]."+res2.second[2]; dia.emplace_back(ts_start_ms,ts_start,fn); ts_start_ms+=interval_ms; GPRINT(HARD_LEVEL,"Collect %s, ts_start enter to diapason\n",fn.c_str()); //printf("t_st_ms %llu ts_start_ms %llu t_end_ms %llu\n",t_st_ms,ts_start_ms,t_end_ms); while((ts_start_ms>=t_st_ms)&&(ts_start_ms<=t_end_ms)){ dia[dia.size()-1].add(ts_start_ms); //printf("* fn %s point %llu>=%llu<=%llu\n",fn.c_str(),t_st_ms,ts_start_ms,t_end_ms); ts_start_ms+=interval_ms; } } else{ ts_start_ms+=interval_ms; GPRINT(HARD_LEVEL,"Skip ts_start out in diapason [%u] %u [%u]\n",t_st,ts_start,t_end); } } u32 tp=0; bool result_root_init=false; u32 aidx=0; bool format_getting=false; rapidjson::Document header_root; string format_path[total_storage]; for (u32 r=0;r<dia.size();r++){ string data; if (GetDataFromGzip(data,dia[r].fname,dia[r].start_ts,format_path)==NO_ERROR){ rapidjson::Document dr_root; dr_root.SetObject(); rapidjson::Document data_root; rapidjson::ParseResult rapid_result=data_root.Parse(data.c_str()); if (rapid_result.Code()==0){ if (format_getting==false){ if (ReadJsonFormatFile_rpd(header_root,format_path)==ERROR){ return ERROR; } format_getting=true; } MakeObjectFromDataAndHeader_rpd(data_root,header_root,dr_root,false); if ((!dr_root.HasMember("t"))||(!dr_root["t"].IsArray())){ return ERROR; } u32 k=0; u32 diasz=dia[r].ts.size(); for (u32 e=0;e<dr_root["m"].Size();e++){ if (((u64)dr_root["m"][e].GetInt64())>=dia[r].ts[k]){ for (auto& key : dr_root.GetObject()) { const char* keys=key.name.GetString(); if (result_root.HasMember(keys)==false){ rapidjson::Value val(rapidjson::kArrayType); rapidjson::Value index(keys, (u32)strlen(keys), result_root.GetAllocator()); result_root.AddMember(index,val,result_root.GetAllocator()); } result_root[keys].PushBack(dr_root[keys][e], result_root.GetAllocator()); } k++; if (k>=diasz) { break; } } } } } tp+=dia[r].ts.size(); } if (format_getting==false){ GetFormatPath(format_path); if (ReadJsonFormatFile_rpd(header_root,format_path)==ERROR){ return ERROR; } } if (dal_upload_from_DB_method==SBS_UPLOAD_METHOD_IN_DB_ALL) make_selection_step_by_step_DB_All(ts_start_ms,saved_ts_stop_ms,header_root,result_root); else make_selection_step_by_step_DB_step(ts_start_ms,saved_ts_stop_ms,interval_ms,header_root,result_root,aidx); return NO_ERROR; } eErrorTp dnk_biphasic_offset_cli::make_selection_step_by_step_DB_All(u64 ts_start_ms,u64 saved_ts_stop_ms,rapidjson::Document & header_root,rapidjson::Document & result_root){ rapidjson::Document result_db_root; result_db_root.SetArray(); rapidjson::Document dr_root; dr_root.SetObject(); //u64 saved_ts_stop_ms=UINT64_MAX; //bool result_root_init=false; GPRINT(MEDIUM_LEVEL,"search elements in redis start %llu stop %llu\n",ts_start_ms,saved_ts_stop_ms); if ((make_selection_from_db(ts_start_ms,saved_ts_stop_ms,result_db_root)==NO_ERROR)){ if ((result_db_root.IsArray())&&(result_db_root.Size()!=0)){ MakeObjectFromDataAndHeader_rpd(result_db_root,header_root,dr_root,false); if ((!dr_root.HasMember("t"))||(!dr_root["t"].IsArray())){ GPRINT(MEDIUM_LEVEL,"temporary elements in redis is broken dump: %s\n",(char*)StyledWriteJSON(&dr_root).c_str()); return ERROR; } GPRINT(MEDIUM_LEVEL,"found [%u] temporary elements in redis\n",dr_root["m"].Size()); for (u32 e=0;e<dr_root["m"].Size();e++){ for (auto& key : dr_root.GetObject()){ const char* keys=key.name.GetString(); //printf("obj %s\n",keys); if (result_root.HasMember(keys)==false){ rapidjson::Value val(rapidjson::kArrayType); rapidjson::Value index(keys, (u32)strlen(keys), result_root.GetAllocator()); result_root.AddMember(index,val,result_root.GetAllocator()); } result_root[keys].PushBack(dr_root[keys][e], result_root.GetAllocator()); } } return NO_ERROR; } else{ GPRINT(MEDIUM_LEVEL,"not found temporary elements in redis\n"); return ERROR; } } else{ GPRINT(MEDIUM_LEVEL,"redis db is broken\n"); return ERROR; } return ERROR; } eErrorTp dnk_biphasic_offset_cli::make_selection_step_by_step_DB_step(u64 ts_start_ms,u64 saved_ts_stop_ms,u64 interval_ms,rapidjson::Document & header_root,rapidjson::Document & result_root,u32 & aidx){ rapidjson::Document result_db_root; result_db_root.SetArray(); rapidjson::Document dr_root; dr_root.SetObject(); //bool result_root_init=false; if ((make_selection_from_db(ts_start_ms,saved_ts_stop_ms,result_db_root)==NO_ERROR)){ if ((result_db_root.IsArray())&&(result_db_root.Size()!=0)){ MakeObjectFromDataAndHeader_rpd(result_db_root,header_root,dr_root,false); if ((!dr_root.HasMember("t"))||(!dr_root["t"].IsArray())){ return ERROR; } GPRINT(MEDIUM_LEVEL,"found [%u] temporary elements in redis\n",dr_root["m"].Size()); u64 fval=(u64)dr_root["m"][0].GetInt64(); while(ts_start_ms<fval){ ts_start_ms+=interval_ms; } for (u32 e=0;e<dr_root["m"].Size();e++){ //printf(" in db %llu ts_start_ms %llu\n",dr_root["m"][e].asUInt64(),ts_start_ms); if ((u64)dr_root["m"][e].GetInt64()>=ts_start_ms){ //printf(" found in db %llu ts_start_ms %llu\n",dr_root["m"][e].asUInt64(),ts_start_ms); for (auto & key:dr_root.GetObject() ){ const char* keys=key.name.GetString(); if (result_root.HasMember(keys)==false){ rapidjson::Value val(rapidjson::kArrayType); rapidjson::Value index(keys, (u32)strlen(keys), result_root.GetAllocator()); result_root.AddMember(index,val,result_root.GetAllocator()); } result_root[keys].PushBack(dr_root[keys][e], result_root.GetAllocator()); } ts_start_ms+=interval_ms; } } } } else{ GPRINT(MEDIUM_LEVEL,"not found temporary elements in redis\n"); } return NO_ERROR; } eErrorTp dnk_biphasic_offset_cli::search_min_max(TIME_T & ts_start,TIME_T & ts_stop){ std::pair<eErrorTp, vector<string>> resmin,resmin_for_max,resmax; resmin=command("ZRANGEBYSCORE ts 0 %u LIMIT 0 1",ts_stop); if ((resmin.first==ERROR)||(resmin.second.size()==0)) return ERROR; resmin_for_max=command("ZRANGE ts -1 -1"); if ((resmin_for_max.first==ERROR)||(resmin_for_max.second.size()==0)) return ERROR; resmax=command("HMGET %s te",resmin_for_max.second[0].c_str()); if ((resmax.first==ERROR)||(resmax.second.size()==0)) return ERROR; TIME_T minval=stol(resmin.second[0]); TIME_T maxval=stol(resmax.second[0]); if (ts_stop<minval){ GPRINT(MEDIUM_LEVEL,"Skip search:ts_stop[%u]<minval[%u]\n",ts_stop,minval); return ERROR; } if (ts_start>maxval){ GPRINT(MEDIUM_LEVEL,"Skip search:ts_start[%u]<maxval[%u]\n",ts_start,maxval); return ERROR; } if (ts_start<minval) ts_start=minval; if (ts_stop>maxval) ts_stop=maxval; if (ts_start>ts_stop){ GPRINT(MEDIUM_LEVEL,"Skip search:ts_start[%u]>ts_stop[%u]\n",ts_start,ts_stop); return ERROR; } GPRINT(MEDIUM_LEVEL,"Found min %u max %u\n",ts_start,ts_stop); //if (((minval>=ts_start)||(ts_start<0))&&((maxval<=ts_stop)||(ts_stop<0))){ // ts_start=minval // ts_stop=maxval; // return NO_ERROR; //} return NO_ERROR; } eErrorTp dnk_biphasic_offset_cli::make_selection_from_db(u64 ts_start_ms,u64 ts_stop_ms,rapidjson::Document & result_db_root){ std::pair<eErrorTp, vector<string>> res=command("GET u"); if (res.first==NO_ERROR){ std::pair<eErrorTp, vector<string>> res1=command("ZRANGEBYSCORE u%s %llu %llu",res.second[0].c_str(),ts_start_ms,ts_stop_ms); if (res1.first==NO_ERROR){ if (res1.second.size()!=0){ string s="["; for (u32 z=0;z<res1.second.size();z++){ s=s+res1.second[z]+','; } s[s.size()-1]=']'; rapidjson::ParseResult rp =result_db_root.Parse(s.c_str()); if (rp.Code()==0){ return NO_ERROR; } else return ERROR; } return NO_ERROR; } else return ERROR; } else return NO_ERROR; } eErrorTp dnk_biphasic_offset_cli::GetFormatPath(string * format_path){ TIME_T t=TIME((u32*)NULL); struct tm * ptm=GMTIME(&t); u32 year=ptm->tm_year+1900; //printf("e\n"); string dal_path0=string_format("%s/%s/%d/%s",dal_base_path[0].c_str(),DNK_BIPHASIC_PREFIX,year,dal_groupid.c_str()); //printf("e1\n"); string dal_path1=string_format("%s/%s/%d/%s",dal_base_path[1].c_str(),DNK_BIPHASIC_PREFIX,year,dal_groupid.c_str()); //printf("e2\n"); format_path[0]=dal_path0+'/'+FORMAT_TABLE_FILENAME; format_path[1]=dal_path1+'/'+FORMAT_TABLE_FILENAME; return NO_ERROR; } eErrorTp dnk_biphasic_offset_cli::GetDataFromGzip(string & result,string & fname,TIME_T ts,string * format_path){ struct tm * ptm=GMTIME(&ts); u32 year=ptm->tm_year+1900; string dal_path0=string_format("%s/%s/%d/%s",dal_base_path[0].c_str(),DNK_BIPHASIC_PREFIX,year,dal_groupid.c_str()); string dal_path1=string_format("%s/%s/%d/%s",dal_base_path[1].c_str(),DNK_BIPHASIC_PREFIX,year,dal_groupid.c_str()); string p0=dal_path0+'/'+fname; string p1=dal_path1+'/'+fname; format_path[0]=dal_path0+'/'+FORMAT_TABLE_FILENAME; format_path[1]=dal_path1+'/'+FORMAT_TABLE_FILENAME; //if (GetFileSize(p1.c_str()!=0)){ if (UngzipFile((char*)p0.c_str(),result)==NO_ERROR){ GPRINT(MEDIUM_LEVEL,"Success gunzip file %s\n",p0.c_str()); return NO_ERROR; } else{ GPRINT(NORMAL_LEVEL,"Error gunzip file %s, try gunzip reserved %s\n",p0.c_str(),p1.c_str()); if (UngzipFile((char*)p1.c_str(),result)==NO_ERROR) { GPRINT(MEDIUM_LEVEL,"Success gunzip file %s\n",p1.c_str()); remove((char*)p0.c_str()); CopyFile((char*)p1.c_str(),(char*)p0.c_str()); return NO_ERROR; } else{ GPRINT(NORMAL_LEVEL,"Error gunzip file %s\n",p1.c_str()); return ERROR; } } return ERROR; } #endif
33.27821
203
0.676878
trotill
3c9e8d9a4280c66a313fd5fa0ffdc6e0ce66bd2b
8,008
cpp
C++
3rdparty/optee/optee_os/external/RIoT/Sample/Barnacle/Shared/Tool/BarT/helper.cpp
mrragava/ragava_openenclave_6
78ffbd4ce16ec698576c432ca1fa8340663ca229
[ "MIT" ]
null
null
null
3rdparty/optee/optee_os/external/RIoT/Sample/Barnacle/Shared/Tool/BarT/helper.cpp
mrragava/ragava_openenclave_6
78ffbd4ce16ec698576c432ca1fa8340663ca229
[ "MIT" ]
null
null
null
3rdparty/optee/optee_os/external/RIoT/Sample/Barnacle/Shared/Tool/BarT/helper.cpp
mrragava/ragava_openenclave_6
78ffbd4ce16ec698576c432ca1fa8340663ca229
[ "MIT" ]
null
null
null
#include "stdafx.h" std::vector<BYTE> ReadHex(std::wstring strIn) { std::vector<BYTE> dataOut(strIn.size() / 2); for (uint32_t cursor = 0; cursor < dataOut.size(); cursor++) { dataOut[cursor] = (BYTE)std::stoul(strIn.substr(cursor * 2, 2), NULL, 16); //if (swscanf_s(strIn.substr(cursor * 2, 2).c_str(), L"%x", &scannedDigit) != 1) //{ // throw; //} // dataOut[cursor] = (BYTE)(scannedDigit & 0x000000FF); } return dataOut; } uint32_t GetTimeStamp(void) { FILETIME now = { 0 }; LARGE_INTEGER convert = { 0 }; // Get the current timestamp GetSystemTimeAsFileTime(&now); convert.LowPart = now.dwLowDateTime; convert.HighPart = now.dwHighDateTime; convert.QuadPart = (convert.QuadPart - (UINT64)(11644473600000 * 10000)) / 10000000; return convert.LowPart; } void WriteToFile(std::wstring fileName, std::vector<BYTE> data, DWORD dwCreationDisposition) { // http://stackoverflow.com/questions/14841396/stdunique-ptr-deleters-and-the-win32-api std::unique_ptr<std::remove_pointer<HANDLE>::type, decltype(&::CloseHandle)> hFile(::CreateFile(fileName.c_str(), GENERIC_WRITE, 0, NULL, dwCreationDisposition, FILE_ATTRIBUTE_NORMAL, NULL), &::CloseHandle); SetFilePointer(hFile.get(), 0, 0, FILE_END); DWORD bytesWritten = 0; if (!WriteFile(hFile.get(), data.data(), data.size(), &bytesWritten, NULL)) { throw GetLastError(); } } void WriteToFile(std::wstring fileName, std::string data) { // http://stackoverflow.com/questions/14841396/stdunique-ptr-deleters-and-the-win32-api std::unique_ptr<std::remove_pointer<HANDLE>::type, decltype(&::CloseHandle)> hFile(::CreateFile(fileName.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL), &::CloseHandle); DWORD bytesWritten = 0; if (!WriteFile(hFile.get(), data.c_str(), data.size(), &bytesWritten, NULL)) { throw GetLastError(); } } void WriteToFile(std::wstring fileName, UINT32 data) { // http://stackoverflow.com/questions/14841396/stdunique-ptr-deleters-and-the-win32-api std::unique_ptr<std::remove_pointer<HANDLE>::type, decltype(&::CloseHandle)> hFile(::CreateFile(fileName.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL), &::CloseHandle); DWORD bytesWritten = 0; std::vector<byte> dataOut(16, 0); dataOut.resize(sprintf_s((char*)dataOut.data(), dataOut.size(), "%ul", data) - 1); if (!WriteFile(hFile.get(), dataOut.data(), dataOut.size(), &bytesWritten, NULL)) { throw GetLastError(); } } std::string ReadStrFromFile(std::wstring fileName) { // http://stackoverflow.com/questions/14841396/stdunique-ptr-deleters-and-the-win32-api std::unique_ptr<std::remove_pointer<HANDLE>::type, decltype(&::CloseHandle)> hFile(::CreateFile(fileName.c_str(), GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL), &::CloseHandle); DWORD bytesRead = 0; std::string data(GetFileSize(hFile.get(), NULL), '\0'); if (!ReadFile(hFile.get(), (LPVOID)data.c_str(), data.size(), &bytesRead, NULL)) { throw GetLastError(); } return data; } std::vector<BYTE> ReadFromFile(std::wstring fileName) { // http://stackoverflow.com/questions/14841396/stdunique-ptr-deleters-and-the-win32-api std::unique_ptr<std::remove_pointer<HANDLE>::type, decltype(&::CloseHandle)> hFile(::CreateFile(fileName.c_str(), GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL), &::CloseHandle); DWORD bytesRead = 0; std::vector<BYTE> data(GetFileSize(hFile.get(), NULL)); if (!ReadFile(hFile.get(), data.data(), data.size(), &bytesRead, NULL)) { throw GetLastError(); } return data; } FILETIME ConvertWinTimeStamp(UINT32 timeStamp) { LARGE_INTEGER convert = { 0 }; convert.QuadPart = ((LONGLONG)timeStamp * 10000000) + (LONGLONG)(11644473600000 * 10000); FILETIME out = { 0 }; out.dwLowDateTime = convert.LowPart; out.dwHighDateTime = convert.HighPart; return out; } PCCERT_CONTEXT CertFromFile(std::wstring fileName) { uint32_t retVal = 0; std::vector<BYTE> rawCert = ReadFromFile(fileName); DWORD result; if (CryptStringToBinaryA((LPSTR)rawCert.data(), rawCert.size(), CRYPT_STRING_BASE64HEADER, NULL, &result, NULL, NULL)) { std::vector<BYTE> derCert(result, 0); if (!CryptStringToBinaryA((LPSTR)rawCert.data(), rawCert.size(), CRYPT_STRING_BASE64HEADER, derCert.data(), &result, NULL, NULL)) { throw GetLastError(); } rawCert = derCert; } PCCERT_CONTEXT hCert = NULL; if ((hCert = CertCreateCertificateContext(X509_ASN_ENCODING | PKCS_7_ASN_ENCODING, rawCert.data(), rawCert.size())) == NULL) { throw retVal; } return hCert; } std::vector<BYTE> CertThumbPrint(PCCERT_CONTEXT hCert) { uint32_t retVal = 0; BCRYPT_ALG_HANDLE hSha1 = NULL; if ((retVal = BCryptOpenAlgorithmProvider(&hSha1, BCRYPT_SHA1_ALGORITHM, NULL, 0)) != 0) { throw retVal; } std::vector<BYTE> digest(20, 0); if ((retVal = BCryptHash(hSha1, NULL, 0, hCert->pbCertEncoded, hCert->cbCertEncoded, digest.data(), digest.size())) != 0) { throw retVal; } BCryptCloseAlgorithmProvider(hSha1, 0); return digest; } std::wstring ToHexWString(std::vector<BYTE> &byteVector) { std::wstring stringOut((byteVector.size() + 2) * 2, '\0'); DWORD result = stringOut.size(); if (!CryptBinaryToStringW(byteVector.data(), byteVector.size(), CRYPT_STRING_HEXRAW, (LPWSTR)stringOut.c_str(), &result)) { throw GetLastError(); } stringOut.resize(stringOut.size() - 4); return stringOut; } std::string ToHexString(std::vector<BYTE> &byteVector) { std::string stringOut((byteVector.size() + 2) * 2, '\0'); DWORD result = stringOut.size(); if (!CryptBinaryToStringA(byteVector.data(), byteVector.size(), CRYPT_STRING_HEXRAW, (LPSTR)stringOut.c_str(), &result)) { throw GetLastError(); } stringOut.resize(stringOut.size() - 4); return stringOut; } std::wstring ToDevIDWString(std::vector<BYTE> &byteVector, bool uri) { DWORD retVal; DWORD result; std::vector<BYTE> devID(byteVector.size() / 4, 0); for (UINT32 n = 0; n < byteVector.size(); n++) { devID[n] = byteVector[n] ^ byteVector[byteVector.size() / 4 + n] ^ byteVector[byteVector.size() / 2 + n] ^ byteVector[byteVector.size() / 4 * 3 + n]; } if (!CryptBinaryToStringW(devID.data(), devID.size(), uri ? CRYPT_STRING_BASE64URI : CRYPT_STRING_BASE64, NULL, &result)) { retVal = GetLastError(); throw retVal; } std::wstring devIDStr(result, '\0'); if (!CryptBinaryToStringW(devID.data(), devID.size(), uri ? CRYPT_STRING_BASE64URI : CRYPT_STRING_BASE64, (LPWSTR)devIDStr.c_str(), &result)) { retVal = GetLastError(); throw retVal; } devIDStr.resize(devIDStr.size() - 2); devIDStr[devIDStr.size() - 1] = L'\0'; return devIDStr; } std::string ToDevIDString(std::vector<BYTE> &byteVector, bool uri) { DWORD retVal; DWORD result; std::vector<BYTE> devID(byteVector.size() / 4, 0); for (UINT32 n = 0; n < byteVector.size(); n++) { devID[n] = byteVector[n] ^ byteVector[byteVector.size() / 4 + n] ^ byteVector[byteVector.size() / 2 + n] ^ byteVector[byteVector.size() / 4 * 3 + n]; } if (!CryptBinaryToStringA(devID.data(), devID.size(), uri ? CRYPT_STRING_BASE64URI : CRYPT_STRING_BASE64, NULL, &result)) { retVal = GetLastError(); throw retVal; } std::string devIDStr(result, '\0'); if (!CryptBinaryToStringA(devID.data(), devID.size(), uri ? CRYPT_STRING_BASE64URI : CRYPT_STRING_BASE64, (LPSTR)devIDStr.c_str(), &result)) { retVal = GetLastError(); throw retVal; } devIDStr.resize(devIDStr.size() - 2); devIDStr[devIDStr.size() - 1] = '\0'; return devIDStr; }
37.074074
211
0.657717
mrragava
3ca0e624176ab8a4a10b23fa0108f3877cfd1cf1
1,966
cpp
C++
tests/ttl_cache/ttl_cache.cpp
alessandrolenzi/cpp-cachetools
d978d43e61f36cb1a9b5ed6e76b16203e9982cbe
[ "MIT" ]
null
null
null
tests/ttl_cache/ttl_cache.cpp
alessandrolenzi/cpp-cachetools
d978d43e61f36cb1a9b5ed6e76b16203e9982cbe
[ "MIT" ]
null
null
null
tests/ttl_cache/ttl_cache.cpp
alessandrolenzi/cpp-cachetools
d978d43e61f36cb1a9b5ed6e76b16203e9982cbe
[ "MIT" ]
null
null
null
#include <gtest/gtest.h> #include "cpp_cachetools/policies.hpp" #include "cpp_cachetools/indexes.hpp" #include "cpp_cachetools/cache.hpp" #include "../fake_clock/fake_clock.hh" struct TTLTestCache: Cache<policies::Builder<policies::TTL<testing::fake_clock>::Class>::with_index<indexes::HashedIndex>::Class> {}; using namespace std::chrono_literals; TEST(TTLCache, EvictsWhenTimeIsOver) { auto cache_duration = testing::fake_clock::duration(60); auto advance = testing::fake_clock::duration(31); auto &&cache = TTLTestCache::build<int, int>(10, cache_duration); cache->insert(1, 1); testing::fake_clock::advance(advance); auto not_expired = cache->get(1); EXPECT_EQ(not_expired.value(), 1); testing::fake_clock::advance(advance); auto retrieved = cache->get(1); EXPECT_EQ(retrieved, std::optional<int>{}); } TEST(TTLCache, EvictsOlderFirstWhenFull) { auto cache_duration = testing::fake_clock::duration(60); auto advance = testing::fake_clock::duration(31); auto &&cache = TTLTestCache::build<int, int>(2, cache_duration); cache->insert(1, 1); cache->insert(2, 2); cache->insert(3, 3); auto evicted_because_old = cache->get(1); EXPECT_EQ(evicted_because_old, std::optional<int>{}); testing::fake_clock::advance(advance); EXPECT_EQ(cache->get(2), 2); EXPECT_EQ(cache->get(3), 3); } TEST(TTLCache, EvictsExpiredFirst) { auto cache_duration = testing::fake_clock::duration(60); auto advance = testing::fake_clock::duration(31); auto &&cache = TTLTestCache::build<int, int>(2, cache_duration); cache->insert(1, 1); testing::fake_clock::advance(advance); cache->insert(2, 2); testing::fake_clock::advance(advance); cache->insert(3, 3); auto evicted_because_old = cache->get(1); EXPECT_EQ(evicted_because_old, std::optional<int>{}); EXPECT_EQ(cache->get(2), 2); testing::fake_clock::advance(advance); EXPECT_EQ(cache->get(3), 3); }
37.09434
133
0.696338
alessandrolenzi
3ca325f5fe2483cd02853e038b800d780fda921b
508
cpp
C++
src/SvgLib/OpenCommand.cpp
steneva/svg-lib
47a754f71be923bd75bfef35ab529c61702b93ae
[ "MIT" ]
2
2020-08-11T20:46:31.000Z
2020-08-14T09:51:02.000Z
src/SvgLib/OpenCommand.cpp
steneva/svg-lib
47a754f71be923bd75bfef35ab529c61702b93ae
[ "MIT" ]
null
null
null
src/SvgLib/OpenCommand.cpp
steneva/svg-lib
47a754f71be923bd75bfef35ab529c61702b93ae
[ "MIT" ]
null
null
null
#include "OpenCommand.h" bool OpenCommand::can_execute(const CommandContext& context) const { return !context.is_file_open(); } void OpenCommand::execute(const CommandContext& context) const { if (context.args_count() != 2) { throw CommandParamsException(); } const std::string path = context.arg(PATH_INDEX); context.open_svg(path); } void OpenCommand::onSuccess(const CommandContext& context) const { context.out() << "Successfully opened file " << context.file_path() << "." << std::endl; }
22.086957
89
0.724409
steneva
3ca6a6dc39c20d86b71366e5026047f8e8783a7b
4,831
hpp
C++
source/cppx-core-language/syntax/collection-util/Sequence_.hpp
alf-p-steinbach/cppx-core-language
930351fe0df65e231e8e91998f1c94d345938107
[ "MIT" ]
3
2020-05-24T16:29:42.000Z
2021-09-10T13:33:15.000Z
source/cppx-core-language/syntax/collection-util/Sequence_.hpp
alf-p-steinbach/cppx-core-language
930351fe0df65e231e8e91998f1c94d345938107
[ "MIT" ]
null
null
null
source/cppx-core-language/syntax/collection-util/Sequence_.hpp
alf-p-steinbach/cppx-core-language
930351fe0df65e231e8e91998f1c94d345938107
[ "MIT" ]
null
null
null
#pragma once // Source encoding: UTF-8 with BOM (π is a firstcase Greek "pi"). #include <cppx-core-language/assert-cpp/is-c++17-or-later.hpp> #include <cppx-core-language/mix-in/Adapt_as_forward_iterator_.hpp> // cppx::mix_in::Adapt_as_forward_iterator_ #include <cppx-core-language/types/Truth.hpp> // cppx::Truth #include <cppx-core-language/tmp/Enable_if_.hpp> // cppx::Enable_if_ #include <cppx-core-language/tmp/type-checkers.hpp> // cppx::is_integral_ #include <cppx-core-language/tmp/type-modifiers.hpp> // cppx::As_unsigned_ #include <cppx-core-language/calc/number-type-properties.hpp> // cppx::(min_, max_) #include <c/assert.hpp> namespace cppx::_{ template< class Integer, class = Enable_if_< is_integral_<Integer> > > class Sequence_ { using Unsigned = As_unsigned_<Integer>; Unsigned m_first; Unsigned m_last; class Iterator: public mix_in::Adapt_as_forward_iterator_<Iterator, Integer> { Unsigned m_current; public: void advance() { ++m_current; } auto operator*() const noexcept -> Integer { return static_cast<Integer>( m_current ); } friend auto operator==( const Iterator& a, const Iterator& b ) noexcept -> Truth { return a.m_current == b.m_current; } explicit Iterator( const Integer value ) noexcept : m_current( static_cast<Unsigned>( value ) ) {} }; public: constexpr auto first() const noexcept -> Integer { return static_cast<Integer>( m_first ); } constexpr auto last() const noexcept -> Integer { return static_cast<Integer>( m_last ); } constexpr auto n_values() const noexcept -> Integer { return static_cast<Integer>( 1 + m_last - m_first ); } constexpr auto is_empty() const noexcept -> Truth { return n_values() == 0; } template< class Value_integer > constexpr auto contains( const Value_integer x ) const noexcept -> Truth { if constexpr( max_<Value_integer> > max_<Integer> ) { if( x > max_<Integer> ) { return false; } } if constexpr( min_<Value_integer> < min_<Integer> ) { // Here Value_integer is necessarily a signed type. if constexpr( is_signed_<Integer> ) { if( x < min_<Integer> ) { return false; } } else { if( x < 0 ) { // Comparing to Integer(0) could wrap. return false; } } } return m_first <= Unsigned( x ) and Unsigned( x ) <= m_last; } auto begin() const noexcept -> Iterator { return Iterator( m_first ); } auto end() const noexcept -> Iterator { return Iterator( m_last + 1 ); } constexpr Sequence_( const Integer first, const Integer last ) noexcept : m_first( first ) , m_last( last ) { assert( first <= last or static_cast<Unsigned>( first ) == static_cast<Unsigned>( last ) + 1 ); } }; using Sequence = Sequence_<int>; // Free function notation / convention adapters: template< class Integer > inline constexpr auto n_items( const Sequence_<Integer>& seq ) noexcept -> Size { return seq.n_values(); } template< class Integer > inline constexpr auto is_empty( const Sequence_<Integer>& seq ) noexcept -> Size { return seq.is_empty(); } template< class Integer, class Value_integer > inline constexpr auto is_in( const Sequence_<Integer>& seq, const Value_integer v ) noexcept -> Truth { return seq.contains( v ); } // Factory functions: template< class Integer > inline constexpr auto zero_to( const Integer n ) noexcept -> Sequence_<Integer> { return Sequence_<Integer>( 0, n - 1 ); } template< class Integer > inline constexpr auto one_through( const Integer n ) noexcept -> Sequence_<Integer> { return Sequence_<Integer>( 1, n ); } } // namespace cppx::_ // Exporting namespaces: namespace cppx { namespace syntax { CPPX_USE_FROM_NAMESPACE( _, Sequence_, Sequence, zero_to, one_through, is_in ); } // namespace syntax using namespace cppx::syntax; } // namespace cppx
32.863946
111
0.551025
alf-p-steinbach
3caa10eda52c9973047845c4ed92e2970aa3ef3b
1,724
cpp
C++
framework/Source/GPUImageLookupFilter.cpp
autolotto/GPUImage
35f499ce2f59bba92a1c82e2baa2ee4e54e88736
[ "BSD-3-Clause" ]
17
2015-02-28T13:16:21.000Z
2020-01-07T06:10:48.000Z
framework/Source/GPUImageLookupFilter.cpp
JonathanKranz/GPUImage
fcd9576822e4015dc4b1ac514c372d71cfb57b8a
[ "BSD-3-Clause" ]
2
2016-05-29T01:53:18.000Z
2016-09-02T01:15:39.000Z
framework/Source/GPUImageLookupFilter.cpp
JonathanKranz/GPUImage
fcd9576822e4015dc4b1ac514c372d71cfb57b8a
[ "BSD-3-Clause" ]
12
2015-06-19T07:26:39.000Z
2020-01-07T09:31:15.000Z
/** * Author: Alessio Placitelli * Contact: a.placitelli _@_ a2p.it * */ #include "GPUImageLookupFilter.h" const std::string GPUImageLookupFilter::kGPUImageLookupFragmentShaderString("\ varying highp vec2 textureCoordinate;\ varying highp vec2 textureCoordinate2;\ \ uniform sampler2D inputImageTexture;\ uniform sampler2D inputImageTexture2;\ \ void main()\ {\ lowp vec4 textureColor = texture2D(inputImageTexture, textureCoordinate);\ \ mediump float blueColor = textureColor.b * 63.0;\ \ mediump vec2 quad1;\ quad1.y = floor(floor(blueColor) / 8.0);\ quad1.x = floor(blueColor) - (quad1.y * 8.0);\ \ mediump vec2 quad2;\ quad2.y = floor(ceil(blueColor) / 8.0);\ quad2.x = ceil(blueColor) - (quad2.y * 8.0);\ \ highp vec2 texPos1;\ texPos1.x = (quad1.x * 0.125) + 0.5/512.0 + ((0.125 - 1.0/512.0) * textureColor.r);\ texPos1.y = (quad1.y * 0.125) + 0.5/512.0 + ((0.125 - 1.0/512.0) * textureColor.g);\ \ highp vec2 texPos2;\ texPos2.x = (quad2.x * 0.125) + 0.5/512.0 + ((0.125 - 1.0/512.0) * textureColor.r);\ texPos2.y = (quad2.y * 0.125) + 0.5/512.0 + ((0.125 - 1.0/512.0) * textureColor.g);\ \ lowp vec4 newColor1 = texture2D(inputImageTexture2, texPos1);\ lowp vec4 newColor2 = texture2D(inputImageTexture2, texPos2);\ \ lowp vec4 newColor = mix(newColor1, newColor2, fract(blueColor));\ gl_FragColor = vec4(newColor.rgb, textureColor.w);\ }" ); GPUImageLookupFilter::GPUImageLookupFilter() : GPUImageTwoInputFilter() { GPUImageTwoInputFilter::initWithFragmentShaderFromString(kGPUImageLookupFragmentShaderString); } GPUImageLookupFilter::~GPUImageLookupFilter() { }
31.345455
98
0.656032
autolotto
3cb2e04465d34e08dcdedb41ff4160c31eadc078
2,660
cpp
C++
franka_low_level_simulation_driver/src/LowLevelDriver/DegreeOfFreedom.cpp
User-TGK/franka_robot_control
48d62b2056aca2226cbe5ac3914f01bef3659f49
[ "MIT" ]
3
2019-12-12T13:09:49.000Z
2021-09-07T09:08:56.000Z
franka_low_level_simulation_driver/src/LowLevelDriver/DegreeOfFreedom.cpp
User-TGK/franka_robot_control
48d62b2056aca2226cbe5ac3914f01bef3659f49
[ "MIT" ]
null
null
null
franka_low_level_simulation_driver/src/LowLevelDriver/DegreeOfFreedom.cpp
User-TGK/franka_robot_control
48d62b2056aca2226cbe5ac3914f01bef3659f49
[ "MIT" ]
null
null
null
#include <ros/ros.h> #include <DegreeOfFreedom.hpp> namespace RobotControl { namespace FrankaLowLevelDriver { DegreeOfFreedom::DegreeOfFreedom(unsigned short aChannel, unsigned long aMinPulseWidth, unsigned long aMaxPulseWidth, double aMinAngle, double aMaxAngle, double aMaxSpeedPerSecond, unsigned long aCurrentPos, unsigned long aTargetPos) : channel(aChannel), minPulseWidth(aMinPulseWidth), maxPulseWidth(aMaxPulseWidth), minAngle(aMinAngle), maxAngle(aMaxAngle), maxSpeedPerSecond(aMaxSpeedPerSecond), currentPos(aCurrentPos), targetPos(aTargetPos) { } unsigned long DegreeOfFreedom::pulseWidthFromAngle(double angle) const { unsigned long result = ((angle - minAngle) * (maxPulseWidth - minPulseWidth) / (maxAngle - minAngle) + minPulseWidth); if(result > maxPulseWidth) { return maxPulseWidth; } else if(result < minPulseWidth) { return minPulseWidth; } return result; } double DegreeOfFreedom::angleFromPulseWidth(unsigned long pulseWidth) const { if(pulseWidth < minPulseWidth) { pulseWidth = minPulseWidth; } else if(pulseWidth > maxPulseWidth) { pulseWidth = maxPulseWidth; } return ((pulseWidth - minPulseWidth) * (maxAngle - minAngle) / (maxPulseWidth - minPulseWidth) + minAngle); } unsigned long DegreeOfFreedom::getConvertedSpeedFromDegreesPerSecond(double speed) const { unsigned short speedFactor = maxSpeed / minSpeed; double result = ((speed - (maxSpeedPerSecond / speedFactor)) * (maxSpeed - minSpeed) / (maxSpeedPerSecond - (maxSpeedPerSecond / speedFactor)) + minSpeed); if(result > maxSpeed) { return maxSpeed; } if(result < minSpeed) { ROS_DEBUG("THE MINIMUM DEGREES PER SECOND FOR THE DOF ON CHANNEL %s IS %s.", std::to_string(channel).c_str(), std::to_string(maxSpeedPerSecond / speedFactor).c_str()); return minSpeed; } return result; } unsigned short DegreeOfFreedom::getChannel() const { return this->channel; } unsigned long DegreeOfFreedom::getCurrentPos() const { return this->currentPos; } unsigned long DegreeOfFreedom::getTargetPos() const { return this->targetPos; } void DegreeOfFreedom::setCurrentPos(unsigned long aCurrentPos) { this->currentPos = aCurrentPos; } void DegreeOfFreedom::setTargetPos(unsigned long aTargetPos) { this->targetPos = aTargetPos; } } }
26.078431
120
0.652256
User-TGK
3cb3a1595c943ad6f1312bb4eafc020e575f5649
255
cpp
C++
source/Main.cpp
Dovgalyuk/QemuGUI
12ac1522bc02e5635fcd7b873a465f38a562b641
[ "Apache-2.0" ]
null
null
null
source/Main.cpp
Dovgalyuk/QemuGUI
12ac1522bc02e5635fcd7b873a465f38a562b641
[ "Apache-2.0" ]
null
null
null
source/Main.cpp
Dovgalyuk/QemuGUI
12ac1522bc02e5635fcd7b873a465f38a562b641
[ "Apache-2.0" ]
null
null
null
#include "QEMU-GUI.h" #include <QApplication> int main(int argc, char *argv[]) { QApplication a(argc, argv); QEMUGUI w; //QObject::connect(&a, SIGNAL(aboutToQuit()), &w, SLOT(saveSettingsBeforeQuit())); w.show(); return a.exec(); }
18.214286
86
0.627451
Dovgalyuk
3cb6f0fca73939c5590d4a394b2aaae2f47a8cc5
7,545
cpp
C++
Milestone 5/Product.cpp
ariaav/OOP244
bcfc52bfff86b68e4f464e85b8555eef541741a0
[ "MIT" ]
null
null
null
Milestone 5/Product.cpp
ariaav/OOP244
bcfc52bfff86b68e4f464e85b8555eef541741a0
[ "MIT" ]
null
null
null
Milestone 5/Product.cpp
ariaav/OOP244
bcfc52bfff86b68e4f464e85b8555eef541741a0
[ "MIT" ]
null
null
null
// Aria Avazkhani //2018-07-31 //updated: 2018-08-08 #include "Product.h" namespace AMA { Product::Product(char type) { v_type = type; v_sku[0] = '\0'; v_unit[0] = '\0'; v_name = nullptr; v_qty = 0; v_need = 0; v_price = 0.0; v_status = false; } Product::Product(const char* sku, const char* n, const char* unit, int qty, bool status, double price, int need) { name(n); strncpy(v_sku, sku, max_sku_length); v_sku[max_sku_length] = '\0'; strncpy(v_unit, unit, max_unit_length); v_unit[max_unit_length] = '\0'; v_qty = qty; v_need = need; v_price = price; v_status = status; } Product::~Product() { delete[] v_name; } Product::Product(const Product& src) { int c = strlen(src.v_name); v_type = src.v_type; strncpy(v_sku, src.v_sku, max_sku_length); v_sku[max_sku_length] = '\0'; strncpy(v_unit, src.v_unit, max_unit_length); v_unit[max_unit_length] = '\0'; v_qty = src.v_qty; v_need = src.v_need; v_price = src.v_price; v_status = src.v_status; if (src.v_name != nullptr) { v_name = nullptr; v_name = new char[c]; for (int i = 0; i < c; ++i) { v_name[i] = src.v_name[i]; } v_name[c] = '\0'; } else v_name = nullptr; } void Product::name(const char* name) { if (name != nullptr) { int c = strlen(name); v_name = new char[c +1]; for (int i = 0; i < c; ++i){ v_name[i] = name[i]; } v_name[c] = '\0'; } } const char* Product::name() const { if (v_name[0] == '\0') return nullptr; else return v_name; } const char* Product::sku() const { return v_sku; } const char* Product::unit() const { return v_unit; } bool Product::taxed() const { return v_status; } double Product::price() const { return v_price; } double Product::cost() const { if (v_status == true) return price() * (tax + 1); else return price(); } void Product::message(const char* err) { v_err.message(err); } bool Product::isClear() const { return v_err.isClear(); } Product& Product::operator=(const Product& cpy) { if (this != &cpy){ v_type = cpy.v_type; v_qty = cpy.v_qty; v_need = cpy.v_need; v_price = cpy.v_price; v_status = cpy.v_status; name(cpy.v_name); strncpy(v_sku, cpy.v_sku, strlen(cpy.v_sku)); v_sku[strlen(cpy.v_sku)] = '\0'; strncpy(v_unit, cpy.v_unit, strlen(cpy.v_unit)); v_unit[strlen(cpy.v_unit)] = '\0'; } return *this; } std::fstream& Product::store(std::fstream& file, bool newLine) const { file << v_type << ',' << v_sku << ',' << v_name << ',' << v_unit << ',' << v_status << ',' << v_price << ',' << v_qty << ',' << v_need; if (newLine == true) file << endl; return file; } std::fstream& Product::load(std::fstream& file) { char t_sku[max_sku_length]; char t_name[max_name_length]; char t_unit[max_unit_length]; double t_price; int t_qty, t_need; char t_tax; bool t_status; if (file.is_open()){ file.getline(t_sku, max_sku_length, ','); t_sku[strlen(t_sku)] = '\0'; file.getline(t_name, max_name_length, ','); t_name[strlen(t_name)] = '\0'; file.getline(t_unit, max_unit_length, ','); t_unit[strlen(t_unit)] = '\0'; file >> t_tax; if (t_tax == '1') t_status = true; else if (t_tax == '0') t_status = false; file.ignore(); file >> t_price; file.ignore(); file >> t_qty; file.ignore(); file >> t_need; file.ignore(); *this = Product(t_sku, t_name, t_unit, t_qty, t_status, t_price, t_need); } return file; } std::ostream& Product::write(std::ostream& os, bool linear) const { if (!(v_err.isClear())){ os << v_err.message(); } else if (linear){ os << setw(max_sku_length) << left << setfill(' ') << v_sku << '|' << setw(20) << left << v_name << '|' << setw(7) << right << fixed << setprecision(2) << cost() << '|' << setw(4) << right << v_qty << '|' << setw(10) << left << v_unit << '|' << setw(4) << right << v_need << '|'; } else{ os << " Sku: " << v_sku << endl << " Name (no spaces): " << v_name << endl << " Price: " << v_price << endl; if (v_status == true) os << " Price after tax: " << cost() << endl; else{ os << " Price after tax: N/A"<< endl; } os << " Quantity on Hand: " << v_qty << " " << v_unit << endl << " Quantity needed: " << v_need; } return os; } std::istream& Product::read(std::istream& is) { char tax; char* address = new char[max_name_length + 1]; int qty, need; double t_price; if (!is.fail()){ cout << " Sku: "; is >> v_sku; cin.ignore(); cout << " Name (no spaces): "; is >> address; name(address); cout << " Unit: "; is >> v_unit; cout << " Taxed? (y/n): "; is >> tax; if (!is.fail()){ v_err.clear(); if (tax){ bool yes = tax == 'y' || tax == 'Y'; bool no = tax == 'n' || tax == 'N'; if (yes) v_status = true; if (no) v_status = false; if (!(yes || no)){ is.setstate(std::ios::failbit); v_err.message("Only (Y)es or (N)o are acceptable"); return is; } } } else{ is.setstate(std::ios::failbit); v_err.message("Only (Y)es or (N)o are acceptable"); return is; } cout << " Price: "; is >> t_price; if (is.fail()) { v_err.clear(); is.setstate(ios::failbit); v_err.message("Invalid Price Entry"); return is; } else prices(t_price); cout << " Quantity on hand: "; is >> qty; if (is.fail()){ v_err.clear(); v_err.message("Invalid Quantity Entry"); is.setstate(ios::failbit); return is; } else quantity(qty); cout << " Quantity needed: "; is >> need; cin.ignore(); if (is.fail()) { v_err.clear(); v_err.message("Invalid Quantity Needed Entry"); is.setstate(ios::failbit); return is; } else qtyNeed(need); if (!is.fail()){ v_err.clear(); } } return is; } bool Product::operator==(const char* src) const { if (strcmp(src, this->v_sku) == 0) return true; else return false; } double Product::total_cost() const { return static_cast<double>(v_qty * (v_price + (v_price * tax))); } void Product::quantity(int stock) { v_qty = stock; } bool Product::isEmpty() const { if (v_name == nullptr) return true; else return false; } int Product::qtyNeeded() const { return v_need; } int Product::quantity() const { return v_qty; } void Product::qtyNeed(int nd){ v_need = nd; } void Product::prices(double pr){ v_price = pr; } bool Product::operator>(const char* prd) const { if (strcmp(v_sku, prd) > 0) return true; else return false; } bool Product::operator>(const iProduct& src) const { if (strcmp(v_name, src.name()) > 0) return true; else return false; } int Product::operator+=(int add) { if (add > 0) v_qty += add; return v_qty; } std::ostream& operator<<(std::ostream& os, const iProduct& pr) { return pr.write(os, true); } std::istream& operator>>(std::istream& is, iProduct& pr) { return pr.read(is); } double operator+=(double& num, const iProduct& pr) { return num + pr.total_cost(); } }
21.618911
116
0.544599
ariaav
3cb73ff5d7cec0899102c859270959d80be1a58e
15,073
cpp
C++
40_cpnLearnTesting.cpp
KathrynLaing/CPNLearning
b5123f7f1fe5adda8a63a73ed117c67e282cea69
[ "MIT" ]
null
null
null
40_cpnLearnTesting.cpp
KathrynLaing/CPNLearning
b5123f7f1fe5adda8a63a73ed117c67e282cea69
[ "MIT" ]
null
null
null
40_cpnLearnTesting.cpp
KathrynLaing/CPNLearning
b5123f7f1fe5adda8a63a73ed117c67e282cea69
[ "MIT" ]
null
null
null
#include "40_cpnlTest.h" double dataAgreementWithFlips(string filename, int D, cpn cpnet){ //Calculates DFA between data and cpnet //filename tells us the location of the data - Assumed to be written on 1 comma separated line, each entry is an observed outcome //D tells us the number of data points //cpnet is the cpn of interest //first we read in the data and enter it into vector data vector<int> data(D); int line=1; int cols=D; int d; ifstream file(filename); char dummy; for (int i = 0; i < line; i++){ for (int j = 0; j < cols; j++){ file >> d; data[j]=d; if (j < (cols - 1)){ file >> dummy; } } } file.close(); //nvar is the number of variables in the CP-net int nvar=cpnet.size; //convert the data into counts - instead of a list of observed outcomes we have a vector where the ith entry is the number of times outcome i was observed //outcomes are assumed to be in lexicographic order vector<int> counts(pow(2,nvar),0); for(int i=0;i<D;i++){ counts[data[i]]+=1; } //LexMult is the lexicographic multipliers of the variables (the mutlipliers we use to convert between outcomes and their enumeration) vector<int> LexMult(nvar); for(int i=0;i<nvar;i++){ LexMult[i]=pow(2,nvar-i-1); } //AgreementScore will be the DFA score numerator int AgreementScore=0; //adjMat is the adjacency matrix of the CP-net structure. entries and breaks are the cpt details vector<int> adjMat=cpnet.structure; vector<int> entries=cpnet.cptEntries; vector<int> breaks=cpnet.cptBreaks; //for each variable, X, calculate (and add) the the data differences over X flips for(int i=0;i<nvar;i++){ //parents - 0/1 vector giving the parents of X //nPa - number of parents vector<int> parents(nvar); int nPa=0; for(int j=0;j<nvar;j++){ parents[j]=adjMat[j*nvar+i]; nPa+=parents[j]; } //Pa - an nPa vector giving the indices of the parents vector<int> Pa(nPa); int counter=0; for(int j=0;j<nvar;j++){ if(parents[j]==1){ Pa[counter]=j; counter+=1; } } // nother is the number of variables which are not X or parents of X int nOther=nvar-1-nPa; // otherWeights - list of all possible weights these other variables can add to the lexicographic posn of an outcome //otherAssts - cycles through all possible assignments to these other variables std::vector<int> otherWeights(pow(2,nOther)); std::vector<int> otherAssts(nOther,0); std::vector<int> otherMult(nOther); if(nOther>0){ int counter=0; for(int k=0;k<nvar;k++){ if(k!=i){ if(parents[k]==0){ otherMult[counter]=LexMult[k]; counter+=1; } } } for(int k=0;k<pow(2,nOther);k++){ int weight=0; for(int l=0;l<nOther;l++){ weight+= otherAssts[l]*otherMult[l]; } otherWeights[k]=weight; if(k!=(pow(2,nOther)-1)){ int max=0; for(int l=0;l<nOther;l++){ if(otherAssts[l]==0){ if(l>max){ max=l; } } } otherAssts[max]=1; for(int l=max+1;l<nOther;l++){ otherAssts[l]=0; } } } } //For each parent assignment to Pa(X) we find the data differences over all X flips under this assignment //PaAsst cycles through all possible parental assignments vector<int> PaAsst(nPa,0); for(int j=0; j<pow(2,nPa);j++){ //fixedweight is the weight contributed by parent assignment PaAsst to the lexicographic position of an outcome int fixedweight=0; for(int k=0;k<nPa;k++){ fixedweight+=PaAsst[k]*LexMult[Pa[k]]; } //group1/2 are the lists of the lexicographic positions of outcomes with Pa(x)=PaAsst and X=1/2 vector<int> group1(pow(2,nOther)); vector<int> group2(pow(2,nOther)); if(nOther==0){ group1[0]=fixedweight; group2[0]=fixedweight+LexMult[i]; } else{ for(int k=0;k<pow(2,nOther);k++){ group1[k]=fixedweight+otherWeights[k]; group2[k]=fixedweight+otherWeights[k]+LexMult[i]; } } //value1/2 is the number of data observations of outcomes in group 1/2 int value1=0; int value2=0; for(int k=0;k<pow(2,nOther);k++){ value1+=counts[group1[k]]; value2+=counts[group2[k]]; } //if the CPT rule corresponding to PaAsst is 1>2, then the data difference is value1-value2 // Add this to our score if(entries[breaks[i]+2*j]==1){ AgreementScore+=value1-value2; } else{//if the CPT rule is 2>1, then the data difference is value2-value1 AgreementScore+=value2-value1; } //move to next parent assignmnent if(j!=(pow(2,nPa)-1)){ int max=0; for(int k=0;k<nPa;k++){ if(PaAsst[k]==0){ max=k; } } PaAsst[max]=1; for(int k=max+1;k<nPa;k++){ PaAsst[k]=0; } } //We have added the data differences for all PaAsst X-flips to the score } //After cycling through all parental assignments, we have now added all X-flip data differences } //AgreementScore is now the sum of all variable flip data differences //To obtain DFA, we must divide this by n*#data points double ScaledFlipAgreement = (double) AgreementScore/ ((double) nvar* (double) D); return ScaledFlipAgreement; } double dataOrderCompatibleWithCPN(string filename, int D, cpn cpnet, long long int nTests){ //Calculates DOC between the cpnet and data located at filename. nTests the level of approximation we will use in our calculation. //filename - location of data //D - number of data points in file //cpn - CP-net of interest //nTests - number of comparisons we are going to do (max possible number of tests is number of unordered pairs of outcomes) //first we read in the data and enter it into vector data vector<int> data(D); int line=1; int cols=D; int d; ifstream file(filename); char dummy; for (int i = 0; i < line; i++){ for (int j = 0; j < cols; j++){ file >> d; data[j]=d; if (j < (cols - 1)){ file >> dummy; } } } file.close(); //nvar is the number of variables in the CP-net int nvar=cpnet.size; //convert the data into counts - instead of a list of observed outcomes we have a vector where the ith entry is the number of times outcome i was observed //outcomes are assumed to be in lexicographic order vector<int> counts(pow(2,nvar),0); for(int i=0;i<D;i++){ counts[data[i]]+=1; } //next we ensure that the number of comparisons is not more than the maximum possible long long int maxComp= (pow(2,nvar)*(pow(2,nvar)-1))/2; if(nTests>maxComp){ nTests=maxComp; } //Comparisons will be a 0/1 vector recording which outcome pairs have been done already. //Every outcome corresponds to a number between 0 and 2^n-1 (they are enumerated lexicographically) //A distinct outcome pair can thus be written (a,b) a=/=b. If we order outcome pairs in lexicographic order (when considered as coordinate pair) then the ithe pair corresponds to ith entry of comparisons //That is (1,0), (2,0), (2,1),(3,0),(3,1),(3,2),(4,0),........ vector<int> Comparisons(maxComp,0); //if nTests=maxposns then we can just move through the outcome pairs systematically as all need to be tested //Otherwise, we must select a (not yet considered) outcome pair at random each time //outposn1 - lexicographic position of outcome 1 in our pair //outposn2 - lexicographic position of outcome 2 long long int outPosn1=1; long long int outPosn2=0; //LexMult is a vector of lexicographic multipliers that we use to move between an outcome and its lex position vector<long long int> LexMult(nvar); for(int i=0;i<nvar;i++){ LexMult[i]=pow(2,nvar-i-1); } //initiate a random generator for uniform selection of an outcome pair //randomly selects a number between 0 and maxComp-1, this then gives an outcome pair by the enumeration of pairs we use in Comparisons struct timeval tv; gettimeofday(&tv,0); unsigned long mySeed = tv.tv_sec + tv.tv_usec; typedef std::mt19937 G; G g(mySeed); typedef std::uniform_int_distribution<long long int> Dist; Dist uni(0, maxComp-1); //later in the function we need to perform dominance testing. We must add 1 to our breaks vector before feeding the CP-net into this function //This is an issue left over from translating functions from R to C++ vector<int> breaks=cpnet.cptBreaks; for(int i=0;i<breaks.size();i++){ breaks[i]+=1; } //supportedRelns will count the number of outcomes pairs we test where the cpnet does not contradict the data; long long int supportedRelns=0; //perform nTests many outcome pair tests: for(long long int i=0;i<nTests;i++){ //if nTests<maxposns, we need to randomly select a new outcome pair. if(nTests<maxComp){ bool newOutcome=false; while(!newOutcome){ //randomly select an outcome pair by generating its lexicographic position long long int outPair=uni(g); //Check Comparisons vector to see if it has been considered previously if(Comparisons[outPair]==0){ //If it hasn't been considered previously, mark in Comparisons that we have now done this pair Comparisons[outPair]=1; newOutcome=true; //convert the lexicographic position of the pair into the coordinate pair that gives the lex positions of outcome 1 and 2 in the pair outPosn1=2; bool identified=false; while(!identified){ if(outPair<(outPosn1*(outPosn1-1))/2){ identified=true; outPosn1-=1; } else{ outPosn1+=1; } } outPosn2=outPair - ((outPosn1*(outPosn1-1))/2); } //If it has been considered previously, generate a new pair and try again } } //If we are systematically moving through the pairs, then mark this pair as considered if(nTests==maxComp){ Comparisons[i]=1; } // let us copy outPosn1/2 to new ints to preserve them long long int posn1=outPosn1; long long int posn2=outPosn2; //next we need to turn the pair of outcome positions into two outcomes (vectors out1 and out2) vector<int> out1(nvar,1); vector<int> out2(nvar,1); for(int j=0;j<nvar;j++){ int div1=posn1/LexMult[j]; if(div1==1){ out1[j]=2; posn1-=LexMult[j]; } int div2=posn2/LexMult[j]; if(div2==1){ out2[j]=2; posn2-=LexMult[j]; } } //next we want to find the number of observed data points for the selected outcomes: int data1=counts[outPosn1]; int data2=counts[outPosn2]; if(data1>data2){ //out1 preferred to out2 is only contradicted by the cpnet if it entails out2>out1 so perform dominance test out2>out1 List DTOut=RSDQRankPriority(cpnet.structure,cpnet.domains,cpnet.cptEntries,breaks,out2,out1); bool outcome=DTOut.result; if(!outcome){ //If dominance test false then cpnet does not entail out2>out1 so the data is not contradicted //Thus, we say the CP-net is consistent with this relation in the data and we add a support count supportedRelns+=1; } } if(data2>data1){ //out2 preferred to out1 is only contradicted by the cpnet if it entails out1>out2 so perform dominance test out1>out2 List DTOut=RSDQRankPriority(cpnet.structure,cpnet.domains,cpnet.cptEntries,breaks,out1,out2); bool outcome=DTOut.result; if(!outcome){ //If dominance test false then cpnet does not entail out1>out2 so the data is not contradicted //Thus, we say the CP-net is consistent with this relation in the data and we add a support count supportedRelns+=1; } } if(data1==data2){ //out1 equally preferred to out2 is contradicted by the cpnet if it entails either out1>out2 or out2>out1 so dominance test both //First we dominance test out1>out2 List DTOut=RSDQRankPriority(cpnet.structure,cpnet.domains,cpnet.cptEntries,breaks,out1,out2); bool outcome=DTOut.result; if(!outcome){ //If dominance test is false, we then test out2>out1 DTOut=RSDQRankPriority(cpnet.structure,cpnet.domains,cpnet.cptEntries,breaks,out2,out1); outcome=DTOut.result; if(!outcome){ //If both dominance tests are false, neither direction is entailed and the CP-net is consistent with the data relation so we add a support count supportedRelns+=1; } } } //if we are moving through the pairs systematically, we then move on to next pair: if(nTests==maxComp){ if(outPosn2==(outPosn1-1)){ outPosn1+=1; outPosn2=0; } else{ outPosn2+=1; } } } //supportedRelns now counts the number of tests (outcome pairs) for which the CP-net was consistent with the data relation //DOC is then obtained by dividing by the number of tests performed return (double)supportedRelns/(double)nTests; }
44.594675
207
0.569362
KathrynLaing
3cba5846488d51a78aa69fea139728e4b5c8400e
622
cpp
C++
SomeOpenMPFirst/order.cpp
Roomanidzee/cpp_projects
0474ca1bb9ce33c5a58d87ab4bd5c618e74328f8
[ "MIT" ]
null
null
null
SomeOpenMPFirst/order.cpp
Roomanidzee/cpp_projects
0474ca1bb9ce33c5a58d87ab4bd5c618e74328f8
[ "MIT" ]
null
null
null
SomeOpenMPFirst/order.cpp
Roomanidzee/cpp_projects
0474ca1bb9ce33c5a58d87ab4bd5c618e74328f8
[ "MIT" ]
null
null
null
// // Created by andrey on 19.09.18. // #include <iostream> #include <omp.h> #define N1 3 #define N2 1 int main(){ omp_set_num_threads(N1); #pragma omp parallel if(omp_get_max_threads() > 2) { if(omp_in_parallel()){ printf("Количество нитей: %d; Номер нити : %d\n", omp_get_num_threads(), omp_get_thread_num()); } } omp_set_num_threads(N2); #pragma omp parallel if(omp_get_max_threads() > 2) { if(omp_in_parallel()){ printf("Количество нитей: %d; Номер нити : %d\n", omp_get_num_threads(), omp_get_thread_num()); } } return 0; };
18.848485
107
0.602894
Roomanidzee
3cbc021ff111d38ed567faa35393a52e3890d2be
767
cpp
C++
solved/r-t/tex-quotes/tex.cpp
abuasifkhan/pc-code
77ce51d692acf6edcb9e47aeb7b7f06bf56e4e90
[ "Unlicense" ]
13
2015-09-30T19:18:04.000Z
2021-06-26T21:11:30.000Z
solved/r-t/tex-quotes/tex.cpp
sbmaruf/pc-code
77ce51d692acf6edcb9e47aeb7b7f06bf56e4e90
[ "Unlicense" ]
null
null
null
solved/r-t/tex-quotes/tex.cpp
sbmaruf/pc-code
77ce51d692acf6edcb9e47aeb7b7f06bf56e4e90
[ "Unlicense" ]
13
2015-01-04T09:49:54.000Z
2021-06-03T13:18:44.000Z
#include <cstdio> // I/O #define BUF 65536 struct Reader { char buf[BUF]; char b; int bi, bz; Reader() { bi=bz=0; read(); } void read() { if (bi==bz) { bi=0; bz = fread(buf, 1, BUF, stdin); } b = bz ? buf[bi++] : 0; } void process() { bool open = true; while (b != 0) { if (b == '"') { if (open) { putchar('`'); putchar('`'); } else { putchar('\''); putchar('\''); } open = !open; } else putchar(b); read(); } } }; int main() { Reader rr; rr.process(); return 0; }
18.261905
61
0.324641
abuasifkhan
3cbe802b4fa7aa4df9f6916e8fcca2aa907a1a43
13,925
cpp
C++
software/test/testLogTable/main.cpp
greenenergyprojects/electro-vehicle-charger-met16
cf8c274da60ee8c340915f377c3b352e3ed3e552
[ "MIT" ]
1
2022-03-18T18:49:50.000Z
2022-03-18T18:49:50.000Z
software/test/testLogTable/main.cpp
greenenergyprojects/electro-vehicle-charger-met16
cf8c274da60ee8c340915f377c3b352e3ed3e552
[ "MIT" ]
null
null
null
software/test/testLogTable/main.cpp
greenenergyprojects/electro-vehicle-charger-met16
cf8c274da60ee8c340915f377c3b352e3ed3e552
[ "MIT" ]
null
null
null
#include <string> #include <stdint.h> #include <string.h> #include "mon.hpp" namespace std { uint8_t eep [E2END + 1]; void cli() {} void sei() {} void popSREG () {} void pushSREGAndCli () {} void eeprom_init () { for (int i = 0; i < sizeof(eep); i++) { eep[i] = 0xff; } } void eeprom_busy_wait() { } void eeprom_update_byte (u1_mon::plogtable_t p, uint8_t v) { if (p >= 0 && p < sizeof(eep)) { // printf(" eep %04x <- %02x\n", p, v); eep[p] = v; } } void eeprom_write_byte (u1_mon::plogtable_t p, uint8_t v) { if (p >= 0 && p < sizeof(eep)) { // printf(" eep %04x <- %02x\n", p, v); eep[p] = v; } } uint8_t eeprom_read_byte (u1_mon::plogtable_t p) { if (p >= 0 && p < sizeof(eep)) { return eep[p]; } return 0xff; } uint16_t eeprom_read_word (u1_mon::plogtable_t p) { return (eeprom_read_byte(p + 1) << 8) | eeprom_read_byte(p); } void eeprom_read_block (void *dest, u1_mon::plogtable_t src, int size) { uint8_t *p = (uint8_t *)dest; if (p == NULL) { return; } while (size > 0) { if (src >= 0 && src < sizeof(eep) ) { *p++ = eep[src++]; } size--; } } void eeprom_update_block (void *src, u1_mon::plogtable_t dst, int size) { uint8_t *pFrom = (uint8_t *)src; while (size-- > 0) { uint8_t b = *pFrom++; eeprom_write_byte(dst++, b); } } } namespace u1_app { struct Clock { uint16_t ms; uint8_t sec; uint8_t min; uint8_t hrs; }; struct Trim { uint32_t magic; uint16_t startCnt; // only 15 bits used -> log record uint8_t vcpK; uint8_t vcpD; uint8_t currK; int8_t tempK; int8_t tempOffs; }; struct LogChargingHistory { uint8_t typ; uint32_t time; struct u1_mon::LogDataCharging data; }; struct App { struct u1_mon::LogDataCharging logDataCharging; struct LogChargingHistory logChargingHistory[4]; struct Trim trim; struct Clock clock; } app; void clearLogHistory (); void addLogCharging (uint8_t typ, uint32_t time, uint8_t logIndex); } using namespace std; namespace u1_mon { struct Mon mon; // uint8_t nextLogIndex (int16_t index) { // if (index < 0) { // return 0; // } // return index >= EEP_LOG_DESCRIPTORS ? 0 : index + 1; // } int16_t findLogDescriptorIndex (uint32_t time) { int16_t rv = -1; uint32_t rvTimeDiff = 0xffffffff; uint8_t index = 0; plogtable_t p = (plogtable_t)EEP_LOG_START + sizeof (struct LogDescriptor) * index; struct LogDescriptor d; while (index < EEP_LOG_DESCRIPTORS) { eeprom_busy_wait(); eeprom_read_block(&d, p, sizeof (d)); uint8_t typ = d.typ & 0x0f; if (typ != 0x0f) { uint32_t diff = d.time > time ? d.time - time : time - d.time; if (diff < rvTimeDiff) { rvTimeDiff = diff; rv = index; } u1_app::addLogCharging(typ, d.time, index); } index++; p += sizeof(struct LogDescriptor); } return rv; } int16_t findNewestLogDescriptorIndex () { return findLogDescriptorIndex(0xffffffff); } int16_t findOldestLogDescriptorIndex () { return findLogDescriptorIndex(0); } void readLogData (uint8_t index, uint8_t *pDest, uint8_t destSize) { if (index >= EEP_LOG_DESCRIPTORS) { return; } eeprom_busy_wait(); plogtable_t pFrom = (plogtable_t)EEP_LOG_SLOTS_START + EEP_LOG_SLOT_SIZE * index; eeprom_read_block(pDest, pFrom, destSize); printf(" readLogData %d %p %d -> %02x %02x %02x %02x\n", index, (void *)(pDest), destSize, pDest[0], pDest[1], pDest[2], pDest[3]); } uint8_t saveLog (uint8_t typ, void *pData, uint8_t size) { if (typ >= 0x0f) { return 0xff; // error } struct LogDescriptor d; d.typ = 0x0f; pushSREGAndCli(); { uint16_t tHigh = (u1_app::app.trim.startCnt << 1) | ((u1_app::app.clock.hrs >> 4) & 0x01); uint16_t tLow = ((u1_app::app.clock.hrs & 0x0f) << 12) | ((u1_app::app.clock.min & 0x3f) << 6) | (u1_app::app.clock.sec & 0x3f); d.time = (((uint32_t)tHigh) << 16) | tLow; } popSREG(); uint8_t index = 0; plogtable_t p = (plogtable_t)EEP_LOG_START; plogtable_t pTo = (plogtable_t)EEP_LOG_SLOTS_START; uint8_t lastTyp = typ; if (mon.log.index < EEP_LOG_DESCRIPTORS) { index = mon.log.index; p += index * sizeof (struct LogDescriptor); pTo += index * EEP_LOG_SLOT_SIZE; lastTyp = mon.log.lastTyp == 0 ? 0xff : mon.log.lastTyp; } uint8_t rv; int16_t bytes = size; uint8_t slotCnt = 0; do { if (lastTyp != typ || slotCnt > 0) { index++; p += sizeof (struct LogDescriptor); pTo += EEP_LOG_SLOT_SIZE; if (index >= EEP_LOG_DESCRIPTORS) { p = (plogtable_t)EEP_LOG_START; pTo = (plogtable_t)EEP_LOG_SLOTS_START; index = 0; } } if (slotCnt == 0) { rv = index; } d.typ = (d.typ & 0x0f) | (slotCnt++ << 4); eeprom_busy_wait(); eeprom_update_block(&d, p, sizeof(d)); uint8_t l = bytes < EEP_LOG_SLOT_SIZE ? bytes : EEP_LOG_SLOT_SIZE; eeprom_busy_wait(); if (pData != NULL && size > 0) { eeprom_update_block(pData, pTo, l); bytes -= EEP_LOG_SLOT_SIZE; pData = ((uint8_t *)pData) + l; } } while (bytes > 0 && slotCnt < 16); index = rv; p = (plogtable_t)EEP_LOG_START + index * sizeof (struct LogDescriptor); d.typ = typ; uint8_t slot = 0; while (slotCnt-- > 0) { d.typ = (d.typ & 0x0f) | (slot << 4); eeprom_busy_wait(); eeprom_write_byte(p, *((uint8_t *)&d)); p += sizeof (struct LogDescriptor); mon.log.index = index++; slot++; if (index >= EEP_LOG_DESCRIPTORS) { p = (plogtable_t)EEP_LOG_START; index = 0; } } mon.log.lastTyp = typ; u1_app::addLogCharging(typ, d.time, rv); return rv; } void startupLog () { int16_t startIndex = findNewestLogDescriptorIndex(); mon.log.index = startIndex < 0 ? EEP_LOG_DESCRIPTORS : startIndex + 1; if (mon.log.index >= EEP_LOG_DESCRIPTORS) { mon.log.index = 0; } mon.log.lastTyp = 0xff; saveLog(LOG_TYPE_SYSTEMSTART, NULL, 0); } void clearEEP (plogtable_t pStartAddr, uint16_t size) { while (size-- > 0 && (uint16_t)pStartAddr <= E2END) { eeprom_busy_wait(); eeprom_write_byte(pStartAddr++, 0xff); } eeprom_busy_wait(); } void clearLogTable () { clearEEP((plogtable_t)EEP_LOG_START, E2END + 1 - EEP_LOG_START); mon.log.index = 0xff; mon.log.lastTyp = 0x0f; } int8_t cmd_log (uint8_t argc, const char **argv) { if (argc == 2 && strcmp("clear", argv[1]) == 0) { clearLogTable(); return 0; } if (argc > 1) { return -1; } struct LogDescriptor d; int16_t startIndex = findOldestLogDescriptorIndex(); uint8_t cnt = 0; if (startIndex >= 0) { uint8_t index = (uint8_t)startIndex; plogtable_t p = (plogtable_t)EEP_LOG_START + sizeof (struct LogDescriptor) * index; struct LogDescriptor d; do { eeprom_busy_wait(); eeprom_read_block(&d, p, sizeof (d)); if ((d.typ & 0x0f) != 0x0f) { cnt++; uint8_t typ = d.typ & 0x0f; uint8_t subIndex = d.typ >> 4; uint16_t startupCnt = d.time >> 17; uint8_t hrs = (d.time >> 12) & 0x1f; uint8_t min = (d.time >> 6) & 0x3f; uint8_t sec = d.time & 0x3f; printf(" %2d(%01x/%01x) %5d-%02d:%02d:%02d -> ", index, typ, subIndex, startupCnt, hrs, min, sec); uint8_t slot[EEP_LOG_SLOT_SIZE]; eeprom_busy_wait(); eeprom_read_block(&slot, (plogtable_t)EEP_LOG_SLOTS_START + index * EEP_LOG_SLOT_SIZE, sizeof (slot)); switch (d.typ) { case LOG_TYPE_SYSTEMSTART: { printf("system start"); break; } case LOG_TYPE_STARTCHARGE: { struct LogDataStartCharge *pData = (struct LogDataStartCharge *)&slot; printf("start charge maxAmps=%u", pData->maxAmps); break; } case LOG_TYPE_CHARGING: case LOG_TYPE_STOPCHARGING: { struct LogDataCharging *pData = (struct LogDataCharging *)&slot; uint8_t e = pData->energyKwhX256 >> 8; uint8_t nk = ((pData->energyKwhX256 & 0xff) * 100 + 128) / 256; if (d.typ == LOG_TYPE_STOPCHARGING) { printf("stop "); } printf("charge %u:%02u, E=%u.%02ukWh", pData->chgTimeHours, pData->chgTimeMinutes, e, nk); break; } default: { printf("? ("); for (uint8_t i = 0; i < sizeof slot; i++) { printf(" %02x", slot[i]); } printf(")"); break; } } printf("\n"); } index++; p += sizeof(struct LogDescriptor); if (index >= EEP_LOG_DESCRIPTORS) { index = 0; p = (plogtable_t)EEP_LOG_START; } } while (index != startIndex); } printf("%d valid log records\n", cnt); printf("\nLog history:\n"); for (uint8_t i = 0; i < (sizeof (u1_app::app.logChargingHistory) / sizeof (u1_app::app.logChargingHistory[0])); i++) { struct u1_app::LogChargingHistory *p= &(u1_app::app.logChargingHistory[i]); printf(" %u: typ=%u time=%04x%04x ", i, p->typ, (uint16_t)(p->time >> 16), (uint16_t)(p->time)); printf("= %u-%u:%02u:%02u -> ", (uint16_t)(p->time >> 17), (uint16_t)((p->time >> 12) & 0x1f), (uint16_t)((p->time >> 6) & 0x3f), (uint16_t)(p->time & 0x3f)); printf(" %u:%02umin", p->data.chgTimeHours, p->data.chgTimeMinutes); printf(" %u.%02ukWh", p->data.energyKwhX256 >> 8, ((p->data.energyKwhX256 & 0xff) * 100 + 128) / 256); printf("\n"); } return 0; } } namespace u1_app { void clearLogHistory () { int s = sizeof (u1_app::app.logChargingHistory); memset(u1_app::app.logChargingHistory, 0, sizeof (u1_app::app.logChargingHistory)); } void addLogCharging (uint8_t typ, uint32_t time, uint8_t logIndex) { static uint8_t index = 0; if (typ != LOG_TYPE_STOPCHARGING) { return; } struct u1_app::LogChargingHistory *px = &u1_app::app.logChargingHistory[index]; px->typ = typ; px->time = time; u1_mon::readLogData(logIndex, (uint8_t*)&px->data, sizeof(px->data)); printf("hist[%d]: set %p ... %u %04x%04x\n", index, (void *)px, logIndex, (uint16_t)(time >> 16), (uint16_t)time); index++; if (index >= (sizeof(app.logChargingHistory) / sizeof(app.logChargingHistory[0]))) { index } } } int main () { eeprom_init(); u1_app::app.trim.startCnt = 0x01; u1_app::app.clock.hrs = 0; u1_app::app.clock.min = 0x00; u1_app::app.clock.sec = 0x00; u1_mon::mon.log.index = 0xff; u1_mon::startupLog(); struct u1_mon::LogDataStartCharge x1 = { 10 }; struct u1_mon::LogDataCharging x2 = { 0, 0, 0 }; u1_mon::saveLog(1, &x1, sizeof x1); for (int i = 0; i < 100; i++) { if (i % 100 == 99) { uint8_t f[16]; for (int i = 0; i < sizeof f; i++) { f[i] = i + 10; } u1_mon::saveLog(14, &f, sizeof f); } else if (i % 10 == 9) { u1_mon::saveLog(3, &x2, sizeof x2); } else { u1_mon::saveLog(2, &x2, sizeof x2); } u1_app::app.clock.sec++; if (u1_app::app.clock.sec == 60) { u1_app::app.clock.min++; u1_app::app.clock.sec = 0; } x2.chgTimeMinutes += 2; if (x2.chgTimeMinutes >= 60) { x2.chgTimeMinutes -= 60; x2.chgTimeHours++; } x2.energyKwhX256 += 200; } u1_app::clearLogHistory(); u1_mon::startupLog(); const char *argv[] = { "cmd_log" }; u1_mon::cmd_log(1, argv); return 0; }
32.611241
170
0.488977
greenenergyprojects
3cbea37cb4afc94db99bf6fa442ce481d8828b2a
3,410
inl
C++
clove/components/core/graphics/include/Clove/Graphics/Validation/ValidationQueue.inl
mondoo/Clove
3989dc3fea0d886a69005c1e0bb4396501f336f2
[ "MIT" ]
33
2020-01-09T04:57:29.000Z
2021-08-14T08:02:43.000Z
clove/components/core/graphics/include/Clove/Graphics/Validation/ValidationQueue.inl
mondoo/Clove
3989dc3fea0d886a69005c1e0bb4396501f336f2
[ "MIT" ]
234
2019-10-25T06:04:35.000Z
2021-08-18T05:47:41.000Z
clove/components/core/graphics/include/Clove/Graphics/Validation/ValidationQueue.inl
mondoo/Clove
3989dc3fea0d886a69005c1e0bb4396501f336f2
[ "MIT" ]
4
2020-02-11T15:28:42.000Z
2020-09-07T16:22:58.000Z
#include "Clove/Graphics/Validation/ValidationCommandBuffer.hpp" namespace clove { namespace detail { template<typename QueueType, typename BufferType> void initialiseBuffer(QueueType *queue, BufferType *buffer) { bool const allowBufferReuse{ (queue->getDescriptor().flags & QueueFlags::ReuseBuffers) != 0 }; dynamic_cast<ValidationCommandBuffer *>(buffer)->setAllowBufferReuse(allowBufferReuse); } template<typename SubmissionType> void validateBuffersUsage(SubmissionType const &submission) { for(auto &commandBuffer : submission.commandBuffers) { auto *buffer{ dynamic_cast<ValidationCommandBuffer *>(commandBuffer) }; if(buffer->getCommandBufferUsage() == CommandBufferUsage::OneTimeSubmit && buffer->bufferHasBeenUsed()) { CLOVE_ASSERT_MSG(false, "GraphicsCommandBuffer recorded with CommandBufferUsage::OneTimeSubmit has already been used. Only buffers recorded with CommandBufferUsage::Default can submitted multiples times after being recorded once."); break; } } } template<typename SubmissionType> void markBuffersAsUsed(SubmissionType const &submission) { for(auto &commandBuffer : submission.commandBuffers) { dynamic_cast<ValidationCommandBuffer *>(commandBuffer)->markAsUsed(); } } } //Graphics template<typename BaseQueueType> std::unique_ptr<GhaGraphicsCommandBuffer> ValidationGraphicsQueue<BaseQueueType>::allocateCommandBuffer() { auto commandBuffer{ BaseQueueType::allocateCommandBuffer() }; detail::initialiseBuffer(this, commandBuffer.get()); return commandBuffer; } template<typename BaseQueueType> void ValidationGraphicsQueue<BaseQueueType>::submit(GraphicsSubmitInfo const &submission, GhaFence *signalFence) { detail::validateBuffersUsage(submission); BaseQueueType::submit(submission, signalFence); detail::markBuffersAsUsed(submission); } //Compute template<typename BaseQueueType> std::unique_ptr<GhaComputeCommandBuffer> ValidationComputeQueue<BaseQueueType>::allocateCommandBuffer() { auto commandBuffer{ BaseQueueType::allocateCommandBuffer() }; detail::initialiseBuffer(this, commandBuffer.get()); return commandBuffer; } template<typename BaseQueueType> void ValidationComputeQueue<BaseQueueType>::submit(ComputeSubmitInfo const &submission, GhaFence *signalFence) { detail::validateBuffersUsage(submission); BaseQueueType::submit(submission, signalFence); detail::markBuffersAsUsed(submission); } //Transfer template<typename BaseQueueType> std::unique_ptr<GhaTransferCommandBuffer> ValidationTransferQueue<BaseQueueType>::allocateCommandBuffer() { auto commandBuffer{ BaseQueueType::allocateCommandBuffer() }; detail::initialiseBuffer(this, commandBuffer.get()); return commandBuffer; } template<typename BaseQueueType> void ValidationTransferQueue<BaseQueueType>::submit(TransferSubmitInfo const &submission, GhaFence *signalFence) { detail::validateBuffersUsage(submission); BaseQueueType::submit(submission, signalFence); detail::markBuffersAsUsed(submission); } }
39.195402
252
0.707038
mondoo
3cc017bbd63a7a87c775f8cc3af8be787175083c
1,854
hpp
C++
tket/src/Utils/EigenConfig.hpp
NewGitter2017/tket
6ff81af26280770bf2ca80bfb2140e8fa98182aa
[ "Apache-2.0" ]
null
null
null
tket/src/Utils/EigenConfig.hpp
NewGitter2017/tket
6ff81af26280770bf2ca80bfb2140e8fa98182aa
[ "Apache-2.0" ]
null
null
null
tket/src/Utils/EigenConfig.hpp
NewGitter2017/tket
6ff81af26280770bf2ca80bfb2140e8fa98182aa
[ "Apache-2.0" ]
null
null
null
// Copyright 2019-2021 Cambridge Quantum Computing // // 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 /** * @file * @brief Include this file rather than including the Eigen headers directly */ #include "Utils/Json.hpp" #if defined(__clang__) #pragma GCC diagnostic push #if __has_warning("-Wdeprecated-copy") #pragma GCC diagnostic ignored "-Wdeprecated-copy" #endif #endif #include <Eigen/Dense> #include <Eigen/SparseCore> #include <unsupported/Eigen/KroneckerProduct> #include <unsupported/Eigen/MatrixFunctions> #if defined(__clang__) #pragma GCC diagnostic pop #endif namespace Eigen { template <typename _Scalar, int _Rows, int _Cols> void to_json(nlohmann::json& j, const Matrix<_Scalar, _Rows, _Cols>& matrix) { for (Index i = 0; i < matrix.rows(); ++i) { nlohmann::json row = nlohmann::json::array(); for (Index j = 0; j < matrix.cols(); ++j) { row.push_back(matrix(i, j)); } j.push_back(row); } } template <typename _Scalar, int _Rows, int _Cols> void from_json(const nlohmann::json& j, Matrix<_Scalar, _Rows, _Cols>& matrix) { for (size_t i = 0; i < j.size(); ++i) { const auto& j_row = j.at(i); for (size_t j = 0; j < j_row.size(); ++j) { matrix(i, j) = j_row.at(j).get<typename Matrix<_Scalar, _Rows, _Cols>::Scalar>(); } } } } // namespace Eigen
27.671642
80
0.692017
NewGitter2017
3cc0b245fafc9db219b108d495c5a2fd1d701163
1,690
cpp
C++
mouselistener.cpp
YoungMetroid/Perceptron
25c9914b59af8bde2e53bdfa6b3301b1f4899623
[ "MIT" ]
null
null
null
mouselistener.cpp
YoungMetroid/Perceptron
25c9914b59af8bde2e53bdfa6b3301b1f4899623
[ "MIT" ]
null
null
null
mouselistener.cpp
YoungMetroid/Perceptron
25c9914b59af8bde2e53bdfa6b3301b1f4899623
[ "MIT" ]
null
null
null
#include "mouselistener.h" mouseListener::mouseListener():colorAzul(0),colorRojo(0) { } //type_class is the color RED or BLUE //The temps are the weight for each coordiante and the Bias //which are generated randomly void mouseListener::addObject(int &Xcoordinate, int &Ycoordinate, int type_class) { if(!checkIfExist(Xcoordinate,Ycoordinate)) { if(type_class == 1) colorRojo++; else colorAzul++; std::vector<int> temp; temp.push_back(Xcoordinate-250); temp.push_back((Ycoordinate-250)*-1); temp.push_back(type_class); objects.push_back(temp); } } std::vector<std::vector<int>>mouseListener::getObject() { return objects; } void mouseListener::print() { for(int x = 0; x < objects.size();x++) { for(int y = 0; y < 2;y++) { std::cout << std::setprecision(4); if(y ==1 ) { std::cout << "Y:" << (objects[x][y]-250)*-1 << " "; } else std::cout << "X:" << objects[x][y]-250 << " "; } std::cout << std::endl; } } //Checks if the coordinate has already been taken //ensuring that only one class can only be on one coordinate (x,y) bool mouseListener::checkIfExist(int &Xcoordinate,int&Ycoordinate) { for(int x = 0; x < objects.size();x++) { for(int y = 0; y < 2;y++) { if(objects[x][y] == Xcoordinate and objects[x][y]== Ycoordinate) return true; } } return false; } std::vector<int>mouseListener::getClassesSize() { std::vector<int>temp; temp.push_back(colorAzul); temp.push_back(colorRojo); return temp; }
23.802817
81
0.573964
YoungMetroid
3cc2bf3fce850f480abecf39f67d7e473583e934
11,673
cpp
C++
Photosynthesis(notManaged).cpp
ARS-CSGCL-DT/PhotoSynthesisModule
6493ea851e8c65e43ce0780b0f258a5a87ffb082
[ "Unlicense" ]
7
2016-01-10T07:05:28.000Z
2021-03-09T02:41:06.000Z
Photosynthesis(notManaged).cpp
ARS-CSGCL-DT/PhotoSynthesisModule
6493ea851e8c65e43ce0780b0f258a5a87ffb082
[ "Unlicense" ]
1
2018-02-28T12:46:36.000Z
2018-03-07T06:31:12.000Z
Photosynthesis(notManaged).cpp
ARS-CSGCL-DT/PhotoSynthesisModule
6493ea851e8c65e43ce0780b0f258a5a87ffb082
[ "Unlicense" ]
1
2016-06-16T19:37:35.000Z
2016-06-16T19:37:35.000Z
/*! @file * Defines the entry point for the console application. @author $Author \n */ #include "stdafx.h" #include "gas_exchange.h" #include <iostream> #include <fstream> #include <algorithm> #include <sstream> using namespace std; // uses std::string, a more generic method than CString /*! \namespace photomod \details photomod is the namespace and contains the code needed to run the model. In includes an interface \b _tmain (named by Visual Studio), and \b gasexchange.cpp, the model itself */ using namespace photomod; //Photosynthesis module /*! \b Program _tmain * \page Interface * \par Interface to photosynthesis module * \details This program demonstrates how to call the photosynthesis module * * * \par Use of this interface * Two input files are needed (@b parameters.csv and @b ClimateIn.dat) and one output file is created (@b Results.dat). ClimateIn.dat is the default name, any file can be input when prompted by the program. A detailed description of the input files follows. * -# A comma delimited parameter file containing the parameters for the photosynthesis module, one line for each species (Parameters.csv) * -# An comma delimted environmental file @b (ClimateIn.dat) each line should have these variables (separated by commas): * \li temperature (C) * \li PAR (umol photons m-2 s-1) \li CO2 content (umol mol-1) \li humidity (%) \li wind (m s-1) \li a flag (0,1) to tell the program if constant temperature is used (or let temperature of leaf vary with stomatal conductance). * -# an output file is produced with results @b (Results.dat) each line is written as: * \li PAR (umol photons m-2 s-1) \li Net Photosynthesis (umol CO2 m-2 s-1) \li Gross Photosynthesis \li VPD (kPa) \li LeafTemperature (C) \li BoundaryLayerConductance (mol m-2 s-1) \li Internal CO2 (umol mol-1) \li Respiration (umolCO2 m-2 s-1) \li Transpiration (umol H2O m-2 s-1) \n -# In your calling program, execute the function SetParams first to initialize the calculator for a specific plant species * Then execute the function: \b SetVal(PFD, Temperature, CO2, RelativeHumidity, Wind, Pressure, ConstantTemperature) to pass environmental parameters needed to calculate carbon assimilation and transpiration. This will call the function \b GasEx() which carries out the calculations \n * -# Use the public get functions described in the CGasExchange Class to retrieve the calculated * variables. */ int _tmain(int argc, _TCHAR* argv[]) { /*! \brief these are the variables for the interface */ string DataLine; //!< \b DataLine, holds line of data read from file with climate data string Remark; //!< \b Remark, remark from parameter file char* context = NULL; //!< \b context, pointer needed to use strtok_s function bool ConstantTemperature; //!< \b ConstantTemperature, if set to 1, model does not solve for leaf temperature photomod::CGasExchange::tParms thisParms; //!< \b thisParms, object to hold parameters sent to photosynthesis module const char *pDelim=","; //!< \b pDelim, -pointer to character (delimiter) that separates entries in the parameter file char * pnt; //!< \b pnt, -pointer to the next word to be read from parameter file char CharTest ='A'; //!< \b CharTest -variable to test if there are characters in the line of data (indicates end of data) bool found=false; //!< \b found -Boolean to indicate the species line was found in the parameter file string temp ; //!< \b temp -temporary variable for holding string objects /*! \brief \li these variables hold data sent to model */ double PFD, /*!< \b PFD light umol ppfd m-2 s-1- */ Temperature, /*!< \b Temperature leaf temperature C*/ RelativeHumidity,Wind, CO2, Pressure=100; ifstream ParamFile, DataFile; //!< \b ParamFile, \b DataFile - files to hold parameters and variables for a single run ofstream OutputFile; //!< \b OutputFile holds data output from photosynthesis module //Define a pointer to a new variable as a GasExchange Object photomod::CGasExchange *MyLeafGasEx; //!< \b MyLeafGasEx - define a gas exchange object type // Create a new GasExchange Object MyLeafGasEx= new CGasExchange(); //create a new gas exchange object on the stack //variables to hold results from gas exchange module. double Anet, VPD,Agross,LeafTemperature, Respiration, InternalCO2, StomatalConductance, BoundaryLayerConductance, Transpiration; //assign defaults in case user does not want to enter other information (DataLine is empty) string DataFileName="ClimateIn.dat", OutputFileName="Results.dat"; string Species ="Maize"; //!< \b Species of plant for calculatioins // Get datafile name, and species name if entered by user. cout << "enter name of file with input data and species name separated by commas:" <<endl << "hit Enter with empty string for defaults" <<endl; getline(cin,DataLine); if (!DataLine.empty()) //if empty defaults to string names assigned above { pnt=strtok_s((char*)DataLine.c_str(), pDelim, &context ); //pnt is a pointer to the last recently found token in the string DataFileName.assign(pnt); // first token is a file name pnt=strtok_s(NULL, pDelim, &context ); //get ready for the next token by getting pointer to recently found token in the string Species.assign(pnt); // next token is species Species.erase(remove(Species.begin(),Species.end(),' '),Species.end()); //remove blanks from species name in case any are present pnt=NULL; //finished with these two } // open file with parameters and data ParamFile.open("parameters.csv", std::ifstream::in); if (!ParamFile) { std::cerr << "Parameter file not found \n"; return 0; } DataFile.open(DataFileName.c_str()); if (!DataFile) { std::cerr << "Data file with input not found \n"; return 0; } FILE * pFile; pFile=fopen((char*)OutputFileName.c_str(),"w"); fprintf(pFile, "PAR ANet AGross VPD Leaf_Temp BoundaryL_Conduc InternalCO2 Respiration StomatalConduct Transpiration\n"); OutputFile.open(OutputFileName.c_str()); std::getline(ParamFile,DataLine); //get header from parameter file // last line of file may be empty or contain numbers, this indicates file is at the end while (!ParamFile.eof() && isalpha(CharTest)) //loops through file reads each line and tests if the correct species is found { getline(ParamFile,DataLine); // get the first line of data CharTest=DataLine.at(0); //check that line contains alphabetical text at beginning pnt=strtok_s((char*)DataLine.c_str(), pDelim, &context ); // pick off the first word before the token (',') //First read file to find the desired plant species temp.assign(pnt); temp.erase(remove(temp.begin(),temp.end(),' '),temp.end()); // removes spaces from string thisParms.ID=temp; temp.clear(); //Eliminate case issues - convert everything to lower case transform(thisParms.ID.begin(), thisParms.ID.end(),thisParms.ID.begin(), ::tolower); transform(Species.begin(), Species.end(),Species.begin(), ::tolower); //Search for the correct species in file if (thisParms.ID.compare(Species)==0 && !found) //continue to parse string { pnt = strtok_s( NULL,pDelim, &context ); // iterate to clean string of characters already read // This section parses string, each iteration it cleans string of characters already read while(pnt!=NULL ) { // printf( "Tokenized string using * is:: %s\n", pnt ); // for debugging temp.assign(pnt); thisParms.species=temp; temp.clear(); pnt = strtok_s( NULL,pDelim, &context ); temp.assign(pnt); thisParms.Type=temp; temp.clear(); pnt = strtok_s( NULL,pDelim, &context ); thisParms.Vcm25=atof(pnt); pnt = strtok_s( NULL,pDelim, &context ); thisParms.Jm25=atof(pnt); pnt = strtok_s( NULL,pDelim, &context ); thisParms.Vpm25=atof(pnt); pnt = strtok_s( NULL,pDelim, &context ); thisParms.TPU25=atof(pnt); pnt = strtok_s( NULL,pDelim, &context ); thisParms.Rd25=atof(pnt); pnt = strtok_s( NULL,pDelim, &context ); thisParms.Theta=atof(pnt); pnt = strtok_s( NULL,pDelim, &context ); thisParms.EaVc=atof(pnt); pnt = strtok_s( NULL,pDelim, &context ); thisParms.Eaj=atof(pnt); pnt = strtok_s( NULL,pDelim, &context ); thisParms.Hj=atof(pnt); pnt = strtok_s( NULL,pDelim, &context ); thisParms.Sj=atof(pnt); pnt = strtok_s( NULL,pDelim, &context ); thisParms.Hv=atof(pnt); pnt = strtok_s( NULL,pDelim, &context ); thisParms.EaVp=atof(pnt); pnt = strtok_s( NULL,pDelim, &context ); thisParms.Sv=atof(pnt); pnt = strtok_s( NULL,pDelim, &context ); thisParms.Eap=atof(pnt); pnt = strtok_s( NULL,pDelim, &context ); thisParms.Ear=atof(pnt); pnt = strtok_s( NULL,pDelim, &context ); thisParms.g0=atof(pnt); pnt = strtok_s( NULL,pDelim, &context ); thisParms.g1=atof(pnt); pnt = strtok_s( NULL,pDelim, &context ); thisParms.stomaRatio=atof(pnt); pnt = strtok_s( NULL,pDelim, &context ); thisParms.LfWidth=atof(pnt); pnt = strtok_s( NULL,pDelim, &context ); thisParms.LfAngFact=atof(pnt); pnt = strtok_s( NULL,pDelim, &context ); temp.assign(pnt); thisParms.Remark=temp; temp.clear(); pnt=strtok_s(NULL,pDelim, &context); found=true; } } } // Implementation to interact with photosynthesis model is here CharTest='1'; //initialize CharTest int start=1; bool LineEmpty=false; //Checks if file with environmental data is finished. //output variables //Initialize Gas exchange object by passing species and relavent parameters read earlier MyLeafGasEx->SetParams(&thisParms); // loop to read environmental input data and call object to calculate results while (!LineEmpty) { getline(DataFile, DataLine); if (DataLine.length()==0) LineEmpty=true; else { //CharTest=DataLine.at(0); // check for valid data pnt=strtok_s((char*)DataLine.c_str(), pDelim, &context ); //token is the delimiter PFD=atof(pnt); pnt=strtok_s(NULL,pDelim,&context); Temperature=atof(pnt); pnt=strtok_s(NULL,pDelim,&context); CO2=atof(pnt); pnt=strtok_s(NULL,pDelim,&context); RelativeHumidity=atof(pnt); pnt=strtok_s(NULL,pDelim,&context); Wind=atof(pnt); pnt=strtok_s(NULL,pDelim,&context); ConstantTemperature=atoi(pnt); // pass relavent environmental variables to gas exchange object and execute module MyLeafGasEx->SetVal(PFD, Temperature, CO2, RelativeHumidity, Wind, Pressure, ConstantTemperature); // Return calculated variables from gas exchange object Anet=MyLeafGasEx->get_ANet(); Agross=MyLeafGasEx->get_AGross(); VPD=MyLeafGasEx->get_VPD(); LeafTemperature=MyLeafGasEx->get_LeafTemperature(); BoundaryLayerConductance=MyLeafGasEx->get_BoundaryLayerConductance(); InternalCO2=MyLeafGasEx->get_Ci(); Respiration=MyLeafGasEx->get_Respiration(); StomatalConductance=MyLeafGasEx->get_StomatalConductance(); Transpiration=MyLeafGasEx->get_Transpiration(); fprintf(pFile,"%8.2f %6.2f %6.2f %8.3f %4.1f %8.3f %4.1f %6.2f %8.3f %8.3f\n", PFD, Anet, Agross, VPD, LeafTemperature, BoundaryLayerConductance,InternalCO2,Respiration, StomatalConductance, Transpiration); } } DataFile.close(); DataFile.close(); fclose(pFile); return 0; }
41.83871
147
0.69014
ARS-CSGCL-DT
3ccab0df60fb79547d7b11c8b82c917295c6821a
3,025
cpp
C++
src/detail/helper_detail.cpp
Chrizzly/libunicomm
3aefc02445a5b1e047cc40daaddb7cf9b5082404
[ "BSL-1.0" ]
null
null
null
src/detail/helper_detail.cpp
Chrizzly/libunicomm
3aefc02445a5b1e047cc40daaddb7cf9b5082404
[ "BSL-1.0" ]
null
null
null
src/detail/helper_detail.cpp
Chrizzly/libunicomm
3aefc02445a5b1e047cc40daaddb7cf9b5082404
[ "BSL-1.0" ]
2
2019-03-16T07:07:16.000Z
2020-01-05T11:14:58.000Z
/////////////////////////////////////////////////////////////////////////////// // helper_detail.cpp // // unicomm - Unified Communication protocol C++ library. // // Unified Communication protocol different helper entities. // // 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) // // 2009, (c) Dmitry Timoshenko. #include <unicomm/detail/helper_detail.hpp> #include <smart/utils.hpp> #include <boost/filesystem.hpp> #include <boost/bind.hpp> #include <stdexcept> #include <functional> #include <locale> #include <sstream> #include <iomanip> #include <limits> #ifdef max # undef max #endif #ifdef min # undef min #endif using std::runtime_error; using std::out_of_range; using std::string; using std::isxdigit; using std::equal_to; using std::greater; using std::stringstream; using std::numeric_limits; using boost::filesystem::exists; using boost::filesystem::path; //----------------------------------------------------------------------------- void unicomm::detail::check_path(const string &s) { if (!exists(path(s))) { throw runtime_error("File or directory doesn't exist [" + s + "]"); } } //----------------------------------------------------------------------------- string& unicomm::detail::normalize_path(string &s) { if (!s.empty()) { const string::value_type c = *(s.end() - 1); if (c != '\\' && c != '/') { s += '/'; } } return s; } //----------------------------------------------------------------------------- string unicomm::detail::normalize_path(const string &s) { string ss = s; return normalize_path(ss); } //----------------------------------------------------------------------------- // declaration for compiler namespace unicomm { namespace detail { string& process_hex_str(string& s); } // namespace unicomm } // namespace detail // fixme: use boost regex to implement this routine string& unicomm::detail::process_hex_str(string& s) { static const char* token = "\\x"; for (size_t pos = s.find(token); pos != string::npos; pos = s.find(token)) { size_t end = pos += 2; while (end < s.size() && isxdigit(s[end])) { ++end; } smart::throw_if<runtime_error>(boost::bind(equal_to<size_t>(), end, pos), "Hexadecimal number should have at least one digit"); BOOST_ASSERT(end > pos && " - End index should be greater start"); stringstream ss(s.substr(pos, end - pos)); size_t char_code = 0; ss >> std::hex >> char_code; smart::throw_if<out_of_range>(boost::bind(greater<size_t>(), char_code, numeric_limits<unsigned char>::max()), "Number too big for char code"); pos -= 2; s.replace(pos, end - pos, 1, static_cast<char>(char_code)); } return s; } //----------------------------------------------------------------------------- string unicomm::detail::process_hex_str(const std::string& s) { string ss = s; return process_hex_str(ss); }
22.574627
79
0.556364
Chrizzly
3cd0967970a5c88f259566148fb7865aba403e52
8,663
hpp
C++
inst/include/barry/counters-meat.hpp
USCbiostats/geese
0af2ade66a7da42737be613f6b8129347dcae4b2
[ "MIT" ]
8
2020-07-21T01:30:35.000Z
2022-03-09T15:51:14.000Z
inst/include/barry/counters-meat.hpp
USCbiostats/geese
0af2ade66a7da42737be613f6b8129347dcae4b2
[ "MIT" ]
2
2022-01-24T20:51:46.000Z
2022-03-16T23:08:40.000Z
include/barry/counters-meat.hpp
USCbiostats/barry
79c363b9f31d9ee03b3ae199e98c688ffc2abdd0
[ "MIT" ]
null
null
null
#include "counters-bones.hpp" #ifndef BARRY_COUNTERS_MEAT_HPP #define BARRY_COUNTERS_MEAT_HPP 1 #define COUNTER_TYPE() Counter<Array_Type,Data_Type> #define COUNTER_TEMPLATE_ARGS() <typename Array_Type, typename Data_Type> #define COUNTER_TEMPLATE(a,b) \ template COUNTER_TEMPLATE_ARGS() inline a COUNTER_TYPE()::b COUNTER_TEMPLATE(,Counter)( const Counter<Array_Type,Data_Type> & counter_ ) : count_fun(counter_.count_fun), init_fun(counter_.init_fun) { if (counter_.delete_data) { this->data = new Data_Type(*counter_.data); this->delete_data = true; } else { this->data = counter_.data; this->delete_data = false; } this->name = counter_.name; this->desc = counter_.desc; return; } COUNTER_TEMPLATE(,Counter)( Counter<Array_Type,Data_Type> && counter_ ) noexcept : count_fun(std::move(counter_.count_fun)), init_fun(std::move(counter_.init_fun)), data(std::move(counter_.data)), delete_data(std::move(counter_.delete_data)), name(std::move(counter_.name)), desc(std::move(counter_.desc)) { counter_.data = nullptr; counter_.delete_data = false; } ///< Move constructor COUNTER_TEMPLATE(COUNTER_TYPE(),operator=)( const Counter<Array_Type,Data_Type> & counter_ ) { if (this != &counter_) { this->count_fun = counter_.count_fun; this->init_fun = counter_.init_fun; if (counter_.delete_data) { this->data = new Data_Type(*counter_.data); this->delete_data = true; } else { this->data = counter_.data; this->delete_data = false; } this->name = counter_.name; this->desc = counter_.desc; } return *this; } COUNTER_TEMPLATE(COUNTER_TYPE() &,operator=)( Counter<Array_Type,Data_Type> && counter_ ) noexcept { if (this != &counter_) { // Data if (delete_data) delete data; this->data = std::move(counter_.data); this->delete_data = std::move(counter_.delete_data); counter_.data = nullptr; counter_.delete_data = false; // Functions this->count_fun = std::move(counter_.count_fun); this->init_fun = std::move(counter_.init_fun); // Descriptions this->name = std::move(counter_.name); this->desc = std::move(counter_.desc); } return *this; } ///< Move assignment COUNTER_TEMPLATE(double, count)(Array_Type & Array, uint i, uint j) { if (count_fun == nullptr) return 0.0; return count_fun(Array, i, j, data); } COUNTER_TEMPLATE(double, init)(Array_Type & Array, uint i, uint j) { if (init_fun == nullptr) return 0.0; return init_fun(Array, i, j, data); } COUNTER_TEMPLATE(std::string, get_name)() const { return this->name; } COUNTER_TEMPLATE(std::string, get_description)() const { return this->name; } //////////////////////////////////////////////////////////////////////////////// // Counters //////////////////////////////////////////////////////////////////////////////// #define COUNTERS_TYPE() Counters<Array_Type,Data_Type> #define COUNTERS_TEMPLATE_ARGS() <typename Array_Type, typename Data_Type> #define COUNTERS_TEMPLATE(a,b) \ template COUNTERS_TEMPLATE_ARGS() inline a COUNTERS_TYPE()::b COUNTERS_TEMPLATE(, Counters)() { this->data = new std::vector<Counter<Array_Type,Data_Type>*>(0u); this->to_be_deleted = new std::vector< uint >(0u); this->delete_data = true; this->delete_to_be_deleted = true; } COUNTERS_TEMPLATE(COUNTER_TYPE() &, operator[])(uint idx) { return *(data->operator[](idx)); } COUNTERS_TEMPLATE(, Counters)(const Counters<Array_Type,Data_Type> & counter_) : data(new std::vector< Counter<Array_Type,Data_Type>* >(0u)), to_be_deleted(new std::vector< uint >(0u)), delete_data(true), delete_to_be_deleted(true) { // Checking which need to be deleted std::vector< bool > tbd(counter_.size(), false); for (auto& i : *(counter_.to_be_deleted)) tbd[i] = true; // Copy all counters, if a counter is tagged as // to be deleted, then copy the value for (auto i = 0u; i != counter_.size(); ++i) { if (tbd[i]) this->add_counter(*counter_.data->operator[](i)); else this->add_counter(counter_.data->operator[](i)); } return; } COUNTERS_TEMPLATE(, Counters)(Counters<Array_Type,Data_Type> && counters_) noexcept : data(std::move(counters_.data)), to_be_deleted(std::move(counters_.to_be_deleted)), delete_data(std::move(counters_.delete_data)), delete_to_be_deleted(std::move(counters_.delete_to_be_deleted)) { // Taking care of memory counters_.data = nullptr; counters_.to_be_deleted = nullptr; counters_.delete_data = false; counters_.delete_to_be_deleted = false; } COUNTERS_TEMPLATE(COUNTERS_TYPE(), operator=)(const Counters<Array_Type,Data_Type> & counter_) { if (this != &counter_) { // Checking which need to be deleted std::vector< bool > tbd(counter_.size(), false); for (auto i : *(counter_.to_be_deleted)) tbd[i] = true; // Removing the data currently stored in the this->clear(); data = new std::vector< Counter<Array_Type,Data_Type>* >(0u); to_be_deleted = new std::vector< uint >(0u); delete_data = true; delete_to_be_deleted = true; // Copy all counters, if a counter is tagged as // to be deleted, then copy the value for (uint i = 0u; i != counter_.size(); ++i) { if (tbd[i]) this->add_counter(*counter_.data->operator[](i)); else this->add_counter(counter_.data->operator[](i)); } } return *this; } COUNTERS_TEMPLATE(COUNTERS_TYPE() &, operator=)(Counters<Array_Type,Data_Type> && counters_) noexcept { if (this != &counters_) { // Removing the data currently stored in the this->clear(); data = std::move(counters_.data); to_be_deleted = std::move(counters_.to_be_deleted); delete_data = std::move(counters_.delete_data); delete_to_be_deleted = std::move(counters_.delete_to_be_deleted); counters_.data = nullptr; counters_.to_be_deleted = nullptr; counters_.delete_data = false; counters_.delete_to_be_deleted = false; } return *this; } COUNTERS_TEMPLATE(void, add_counter)(Counter<Array_Type, Data_Type> & counter) { to_be_deleted->push_back(data->size()); data->push_back(new Counter<Array_Type, Data_Type>(counter)); return; } COUNTERS_TEMPLATE(void, add_counter)(Counter<Array_Type, Data_Type> * counter) { data->push_back(counter); return; } COUNTERS_TEMPLATE(void, add_counter)( Counter_fun_type<Array_Type,Data_Type> count_fun_, Counter_fun_type<Array_Type,Data_Type> init_fun_, Data_Type * data_, bool delete_data_, std::string name_, std::string desc_ ) { /* We still need to delete the counter since we are using the 'new' operator. * Yet, the actual data may not need to be deleted. */ to_be_deleted->push_back(data->size()); data->push_back(new Counter<Array_Type,Data_Type>( count_fun_, init_fun_, data_, delete_data_, name_, desc_ )); return; } COUNTERS_TEMPLATE(void, clear)() { for (auto& i : (*to_be_deleted)) delete data->operator[](i); if (delete_data) delete data; if (delete_to_be_deleted) delete to_be_deleted; data = nullptr; to_be_deleted = nullptr; return; } COUNTERS_TEMPLATE(std::vector<std::string>, get_names)() const { std::vector< std::string > out(this->size()); for (unsigned int i = 0u; i < out.size(); ++i) out[i] = this->data->at(i)->get_name(); return out; } COUNTERS_TEMPLATE(std::vector<std::string>, get_descriptions)() const { std::vector< std::string > out(this->size()); for (unsigned int i = 0u; i < out.size(); ++i) out[i] = this->data->at(i)->get_description(); return this->name; } #undef COUNTER_TYPE #undef COUNTER_TEMPLATE_ARGS #undef COUNTER_TEMPLATE #undef COUNTERS_TYPE #undef COUNTERS_TEMPLATE_ARGS #undef COUNTERS_TEMPLATE #endif
23.669399
102
0.606603
USCbiostats
3cd1cf2b435b86de97331c58e96ce1f6333d7a67
749
cpp
C++
_small_src_bucket/copy-move_functional.cpp
NesterovMaxim/all_mini_tests
d6837c28e3b6dfc3cfa12794168356dfd4810a0b
[ "MIT" ]
1
2018-02-27T14:29:50.000Z
2018-02-27T14:29:50.000Z
_small_src_bucket/copy-move_functional.cpp
NesterovMaxim/all_mini_tests
d6837c28e3b6dfc3cfa12794168356dfd4810a0b
[ "MIT" ]
null
null
null
_small_src_bucket/copy-move_functional.cpp
NesterovMaxim/all_mini_tests
d6837c28e3b6dfc3cfa12794168356dfd4810a0b
[ "MIT" ]
null
null
null
//clang 3.8.0 #include <iostream> #include <functional> using ft = std::function<void(int)>; void p(const char* m, int i){ std::cout << m << ":" << i << std::endl; } int i; class test{ int j; public: test(){j = ++i; p("ctor", j);} ~test(){p("dtor", j);} test(const test& t){j = t.j*10; p("copy ctor", j);} test(test&& t){j = t.j*100; p("move ctor", j);} void operator()(int i){ std::cout << i << std::endl; } }; int main() { test o; ft f; //f = [&o](int i){o(i);}; f = o; f(1); std::cout << "Hello, world!\n"; return 0; } /* ctor:1 copy ctor:10 move ctor:1000 dtor:10 1 Hello, world! dtor:1000 dtor:1 */
15.285714
56
0.452603
NesterovMaxim
3cd729cf62a781dcee151b67ca80518d7e8f42e9
453
hpp
C++
addons/slingload/script_component.hpp
pterolatypus/sling-load-rigging
06f6b414b30127e60cc2a9440a693c77cbe9d9c3
[ "MIT" ]
1
2020-07-17T01:03:07.000Z
2020-07-17T01:03:07.000Z
addons/slingload/script_component.hpp
pterolatypus/sling-load-rigging
06f6b414b30127e60cc2a9440a693c77cbe9d9c3
[ "MIT" ]
3
2021-03-06T13:07:07.000Z
2021-10-20T19:27:49.000Z
addons/slingload/script_component.hpp
pterolatypus/sling-load-rigging
06f6b414b30127e60cc2a9440a693c77cbe9d9c3
[ "MIT" ]
1
2020-06-24T08:34:59.000Z
2020-06-24T08:34:59.000Z
#define COMPONENT slingload #define COMPONENT_BEAUTIFIED SlingLoad #include "\z\slr\addons\main\script_mod.hpp" // #define DEBUG_MODE_FULL // #define DISABLE_COMPILE_CACHE // #define CBA_DEBUG_SYNCHRONOUS // #define ENABLE_PERFORMANCE_COUNTERS #ifdef DEBUG_ENABLED_SLINGLOAD #define DEBUG_MODE_FULL #endif #ifdef DEBUG_SETTINGS_SLINGLOAD #define DEBUG_SETTINGS DEBUG_SETTINGS_SLINGLOAD #endif #include "\z\slr\addons\main\script_macros.hpp"
23.842105
51
0.816777
pterolatypus
3cd7ea9bdea035b78f83a2f9e1ad1163d4005848
1,167
cpp
C++
GameDownloaderTest/src/SimpleContinueHook.cpp
ProtocolONE/cord.game-downloader
90950019937cd2974801ca2f53ed3b4ecd1d219b
[ "Apache-2.0" ]
1
2019-08-07T06:13:15.000Z
2019-08-07T06:13:15.000Z
GameDownloaderTest/src/SimpleContinueHook.cpp
ProtocolONE/cord.game-downloader
90950019937cd2974801ca2f53ed3b4ecd1d219b
[ "Apache-2.0" ]
null
null
null
GameDownloaderTest/src/SimpleContinueHook.cpp
ProtocolONE/cord.game-downloader
90950019937cd2974801ca2f53ed3b4ecd1d219b
[ "Apache-2.0" ]
null
null
null
#include "SimpleContinueHook.h" #include <GameDownloader/GameDownloadService.h> #include <Core/Service.h> #include <QtCore/QDebug> SimpleContinueHook::SimpleContinueHook(int hookId, QList<int> *preList, QList<int> *postList) : HookBase(QString("hookId_%1").arg(hookId)) , _hookId(hookId) , _preList(preList) , _postList(postList) , _beforeCallCount(0) , _afterCallCount(0) { } SimpleContinueHook::~SimpleContinueHook() { } HookBase::HookResult SimpleContinueHook::beforeDownload(GameDownloadService *, ServiceState *state) { const P1::Core::Service *service = state->service(); this->_beforeCallCount++; this->_preList->append(this->_hookId); qDebug() << "beforeDownload " << (service == 0 ? "service is null" : service->id()); return HookBase::Continue; } HookBase::HookResult SimpleContinueHook::afterDownload(GameDownloadService *, ServiceState *state) { const P1::Core::Service *service = state->service(); this->_afterCallCount++; this->_postList->append(this->_hookId); qDebug() << "afterDownload " << (service == 0 ? "service is null" : service->id()); return HookBase::Continue; }
29.175
100
0.696658
ProtocolONE
3cdc6867c40b40c46dc4aec91b5cea9e9d4048dd
340
cpp
C++
Project/src/Device/Device.cpp
svez-net/GFW
b9b455e0576c441cc53f0e8d7d295887afaf4c49
[ "MIT" ]
1
2016-05-11T01:23:20.000Z
2016-05-11T01:23:20.000Z
Project/src/Device/Device.cpp
svez-net/GFW
b9b455e0576c441cc53f0e8d7d295887afaf4c49
[ "MIT" ]
2
2016-05-19T08:37:00.000Z
2016-05-19T08:40:08.000Z
Project/src/Device/Device.cpp
khs2-net/GFW
b9b455e0576c441cc53f0e8d7d295887afaf4c49
[ "MIT" ]
null
null
null
/* using namespace GFW; Device::Device() { } Device::~Device() { } void Device::Begin(String str) { assert(this->device.find(str) == this->device.end()); this->stack.push_back(&this->device[str]); } void Device::End() { assert(this->stack_count,TEXT("Error:DeviceStackCount")); this->stack.pop_back(); if(this->stack.size()){} } */
17
58
0.655882
svez-net
3cdd89c091169a2aa6413844ea2b99ac09abc9dd
528
cpp
C++
4. Recursion/1_count_digit.cpp
manishhedau/Data-Structure-Algorithm
d45de87aa44d3af18d58fd59491993cf98dbe6fc
[ "MIT" ]
3
2021-02-01T07:56:21.000Z
2021-02-01T11:56:50.000Z
4. Recursion/1_count_digit.cpp
manishhedau/Data-Structure-Algorithm
d45de87aa44d3af18d58fd59491993cf98dbe6fc
[ "MIT" ]
null
null
null
4. Recursion/1_count_digit.cpp
manishhedau/Data-Structure-Algorithm
d45de87aa44d3af18d58fd59491993cf98dbe6fc
[ "MIT" ]
null
null
null
// Given an number N count How many digit present in that number /* Example :- Input :- N = 2000 Output :- 4 Input :- N = 12345678 Output :- 8 */ #include <iostream> using namespace std; int countDigit(int n) { if(n==0) return 0 ; int count = 1; n = n/10; return count+countDigit(n); } int main() { int n; cin>>n; int count = countDigit(n); cout<<"The digit present in that number are : "<<count<<endl; } /* Input :- 2000 Output :- The digit present in that number are : 4 */
14.27027
65
0.592803
manishhedau
3cdd9dfce99d7c2bda4e805c6e6b4ca1728e66d2
5,011
hpp
C++
inc/lak/window.hpp
LAK132/lak
cb7fbc8925d526bbd4f9318ccf572b395cdd01e3
[ "MIT", "Unlicense" ]
3
2021-07-12T02:32:50.000Z
2022-01-30T03:39:53.000Z
inc/lak/window.hpp
LAK132/lak
cb7fbc8925d526bbd4f9318ccf572b395cdd01e3
[ "MIT", "Unlicense" ]
1
2020-11-03T08:57:04.000Z
2020-11-03T09:04:41.000Z
inc/lak/window.hpp
LAK132/lak
cb7fbc8925d526bbd4f9318ccf572b395cdd01e3
[ "MIT", "Unlicense" ]
null
null
null
/* Typical usage for an OpenGL program: int main() { lak::core_init(); lak::window window(...); window.init_opengl(...); uint32_t framerate = 60; auto last_counter = lak::performance_counter(); // main loop while(...) { // event handlers // update code // draw code window.swap(); last_counter = lak::yield_frame(last_counter, framerate); } window.close(); lak::core_quit(); } */ #ifndef LAK_WINDOW_HPP #define LAK_WINDOW_HPP #include "lak/platform.hpp" #include "lak/events.hpp" #include "lak/bank_ptr.hpp" #include "lak/image.hpp" #include "lak/memmanip.hpp" #include "lak/string.hpp" #include "lak/surface.hpp" #include "lak/vec.hpp" #include "lak/profile.hpp" namespace lak { enum struct graphics_mode { None = 0, Software = 1, OpenGL = 2, Vulkan = 3 }; struct software_settings { }; struct opengl_settings { bool double_buffered = false; uint8_t depth_size = 24; uint8_t colour_size = 8; uint8_t stencil_size = 8; int major = 3; int minor = 2; }; struct vulkan_settings { }; struct software_context; struct opengl_context; struct vulkan_context; struct window_handle; extern template struct lak::array<lak::window_handle, lak::dynamic_extent>; extern template struct lak::railcar<lak::window_handle>; extern template struct lak::bank<lak::window_handle>; extern template size_t lak::bank<lak::window_handle>::internal_create< lak::window_handle>(lak::window_handle &&); using const_window_handle_ref = const lak::window_handle &; extern template size_t lak::bank<lak::window_handle>::internal_create< lak::const_window_handle_ref>(lak::const_window_handle_ref &&); extern template struct lak::unique_bank_ptr<lak::window_handle>; extern template struct lak::shared_bank_ptr<lak::window_handle>; using window_handle_bank = lak::bank<lak::window_handle>; /* --- create/destroy window --- */ lak::window_handle *create_window(const lak::software_settings &s); lak::window_handle *create_window(const lak::opengl_settings &s); lak::window_handle *create_window(const lak::vulkan_settings &s); bool destroy_window(lak::window_handle *w); /* --- window state --- */ lak::wstring window_title(const lak::window_handle *w); bool set_window_title(lak::window_handle *w, const lak::wstring &s); lak::vec2l_t window_size(const lak::window_handle *w); lak::vec2l_t window_drawable_size(const lak::window_handle *w); bool set_window_size(lak::window_handle *w, lak::vec2l_t s); bool set_window_cursor_pos(const lak::window_handle *w, lak::vec2l_t p); // :TODO: // bool set_window_drawable_size(lak::window_handle *w, lak::vec2l_t s); /* --- graphics control --- */ lak::graphics_mode window_graphics_mode(const lak::window_handle *w); // :TODO: This probably belongs in the platform header. bool set_opengl_swap_interval(const lak::opengl_context &c, int interval); bool swap_window(lak::window_handle *w); // Yield this thread until the target framerate is achieved. uint64_t yield_frame(const uint64_t last_counter, const uint32_t target_framerate); /* --- window wrapper class --- */ struct window { private: lak::unique_bank_ptr<lak::window_handle> _handle; window(lak::unique_bank_ptr<lak::window_handle> &&handle); public: inline window(window &&w) : _handle(lak::move(w._handle)) {} static lak::result<window> make(const lak::software_settings &s); static lak::result<window> make(const lak::opengl_settings &s); static lak::result<window> make(const lak::vulkan_settings &s); ~window(); inline lak::window_handle *handle() { return _handle.get(); } inline const lak::window_handle *handle() const { return _handle.get(); } inline lak::graphics_mode graphics() const { return lak::window_graphics_mode(handle()); } inline lak::wstring title() const { return lak::window_title(handle()); } inline window &set_title(const lak::wstring &title) { ASSERT(lak::set_window_title(handle(), title)); return *this; } inline lak::vec2l_t size() const { return lak::window_size(handle()); } inline lak::vec2l_t drawable_size() const { return lak::window_drawable_size(handle()); } inline window &set_size(lak::vec2l_t size) { ASSERT(lak::set_window_size(handle(), size)); return *this; } inline const window &set_cursor_pos(lak::vec2l_t pos) const { ASSERT(lak::set_window_cursor_pos(handle(), pos)); return *this; } inline bool swap() { return lak::swap_window(handle()); } }; } #include <ostream> [[maybe_unused]] inline std::ostream &operator<<(std::ostream &strm, lak::graphics_mode mode) { switch (mode) { case lak::graphics_mode::OpenGL: strm << "OpenGL"; break; case lak::graphics_mode::Software: strm << "Software"; break; case lak::graphics_mode::Vulkan: strm << "Vulkan"; break; default: strm << "None"; break; } return strm; } #endif
23.199074
76
0.694073
LAK132
3cdf61068e32d08c7e615fb4ff00c6b9f144e8c6
3,596
cpp
C++
Practicafinal/conecta4_v2.1/src/arboltablero_test.cpp
guillegalor/PracticasED
5e4fbc830c79741997734003add6eae1ee736d61
[ "MIT" ]
null
null
null
Practicafinal/conecta4_v2.1/src/arboltablero_test.cpp
guillegalor/PracticasED
5e4fbc830c79741997734003add6eae1ee736d61
[ "MIT" ]
null
null
null
Practicafinal/conecta4_v2.1/src/arboltablero_test.cpp
guillegalor/PracticasED
5e4fbc830c79741997734003add6eae1ee736d61
[ "MIT" ]
null
null
null
#include <iostream> #include "ArbolGeneral.hpp" #include "tablero.hpp" #include <string> using namespace std; int main(int argc, char *argv[]){ //Tablero vacío 6x7 Tablero tablero(6, 7); //Manualmente se insertan algunos movimientos: tablero.colocarFicha(3); //Jugador 1 inserta ficha en columna 3 tablero.cambiarTurno(); tablero.colocarFicha(1); //Jugador 2 inserta ficha en columna 1 tablero.cambiarTurno(); tablero.colocarFicha(3); //Jugador 1 inserta ficha en columna 3. tablero.cambiarTurno(); //Se muestra el tablero cout << "Tablero obtenido tras tres movimientos: \n"<<tablero; //A partir de la situación actual del tablero, montamos un árbol para estudiar algunas posibilidades. // Éste es el árbol que queremos montar: // tablero // | // |---------------| // tablero1 tablero2 // | // tablero3 //Árbol 'partida', con 'tablero' como nodo raíz ArbolGeneral<Tablero> partida(tablero); //Estudio opciones a partir de tablero: Jugador 2 coloca ficha en columna 1. (tablero1) Tablero tablero1(tablero); //tablero queda sin modificar tablero1.colocarFicha(1); ArbolGeneral<Tablero> arbol1 (tablero1); //creo árbol con un nodo (tablero1) //Otra opción: Jugador 2 coloca ficha en columna 2. (tablero2) Tablero tablero2(tablero); //tablero queda sin modificar tablero2.colocarFicha(2); ArbolGeneral<Tablero> arbol2(tablero2); //creo árbol con un nodo // Sobre la última opción, ahora contemplo la posibilidad de que // Jugador 1 coloque ficha también en columna 2. tablero2.cambiarTurno(); //modifico tablero2 (esta modificación sería tablero3) tablero2.colocarFicha(2); ArbolGeneral<Tablero> arbol3 (tablero2); //creo árbol con un nodo arbol2.insertar_hijomasizquierda(arbol2.raiz(), arbol3); //añado este árbol como hijo de arbol2 // Inserto arbol1 y arbol2 como hijos de partida. // arbol1 es el hijo más a la izquierda y arbol2 es hermano a la derecha de arbol1 // Forma de hacerlo A: inserto varios hijomasizquierda en el orden inverso al deseado // partida.insertar_hijomasizquierda(partida.raiz(), arbol2); // partida.insertar_hijomasizquierda(partida.raiz(), arbol1); //hijomasizquierda desplaza al anterior a la derecha // Forma de hacerlo B: inserto un hijomasizquierda y hermanoderecha partida.insertar_hijomasizquierda(partida.raiz(), arbol1); //inserto un hijomasizquierda partida.insertar_hermanoderecha(partida.hijomasizquierda(partida.raiz()), arbol2); //le inserto un hermanoderecha // Recorremos en preorden para comprobar el arbol 'partida' resultante cout << "\nÁrbol en preorden: \n"<<endl; partida.recorrer_preorden(); // Podamos el hijomasizquierda y recorremos en preorden: ArbolGeneral<Tablero> rama_podada; partida.podar_hermanoderecha(partida.hijomasizquierda(partida.raiz()), rama_podada); cout << "\nRecorrido preorden después de podar arbol2: \n"<<endl; partida.recorrer_preorden(); cout << "\nRecorrido preorden de la rama podada: \n"<<endl; rama_podada.recorrer_preorden(); // Probamos ArbolGeneral::asignar_subarbol. Asignamos a partida la rama_podada: partida.asignar_subarbol(rama_podada, rama_podada.raiz()); cout << "\nRecorrido preorden después de asignar a la raiz la rama_podada: \n"<<endl; partida.recorrer_preorden(); cout << "\nRecorrido postorden después de asignar a la raiz la rama_podada: \n"<<endl; partida.recorrer_postorden(); return 0; }
39.086957
116
0.708287
guillegalor
3ce0829d8f8f47766099d258659642dea1740943
386
cpp
C++
pointimposters/NdfImposters/NdfImposterLibraryTests/selectionV.cpp
reinago/sndfs
0d152e6bf4f63d1468c8e91915a4ff970c978882
[ "MIT" ]
null
null
null
pointimposters/NdfImposters/NdfImposterLibraryTests/selectionV.cpp
reinago/sndfs
0d152e6bf4f63d1468c8e91915a4ff970c978882
[ "MIT" ]
null
null
null
pointimposters/NdfImposters/NdfImposterLibraryTests/selectionV.cpp
reinago/sndfs
0d152e6bf4f63d1468c8e91915a4ff970c978882
[ "MIT" ]
1
2021-11-19T15:30:43.000Z
2021-11-19T15:30:43.000Z
#version 420 in vec2 Position; out vec2 texCoords; void main() { gl_Position = vec4(Position.xy, 0.0f ,1.0f); gl_Position.x /=(.5f* 1280.0f); //gl_Position.x = gl_Position.x; gl_Position.y /= (.5f*720.0f); gl_Position.x -= 1f; gl_Position.y -= 1f; gl_Position.y *= -1.0f; texCoords = vec2(1.0f-Position.x/1280.0f,Position.y/720.0f); //(gl_Position.xy + 1.0f) * 0.5f; }
18.380952
95
0.645078
reinago
c9e6865f455005a01f2ea3f3a1da44b9e4b15931
1,451
cpp
C++
FootSoldier.cpp
rotemish7/wargame-a
6c5d0cd5c5afe4a0187c38478b408e0ea7cd0661
[ "MIT" ]
null
null
null
FootSoldier.cpp
rotemish7/wargame-a
6c5d0cd5c5afe4a0187c38478b408e0ea7cd0661
[ "MIT" ]
null
null
null
FootSoldier.cpp
rotemish7/wargame-a
6c5d0cd5c5afe4a0187c38478b408e0ea7cd0661
[ "MIT" ]
null
null
null
// // Created by rotem levy on 27/05/2020. // #include "FootSoldier.hpp" FootSoldier::FootSoldier(uint player_number) { player_num = player_number; hp = MAX_HP; damage = -10; type = Type::FootSoldierType; } uint FootSoldier::getMaxHP() { return MAX_HP; } void FootSoldier::attack(std::vector<std::vector<Soldier*>> &b, std::pair<int,int> location) { int row = location.first; int col = location.second; Soldier* near_enemy = nullptr; std::pair<int,int> near_enemy_location; double min = b.size()*b.size(); for(int i = 0 ; i < b.size() ; i ++) { for(int j = 0 ; j < b[i].size(); j++) { Soldier * temp = b[i][j]; if(temp != nullptr) { if(temp->getPlayer_number() != player_num) { double dist = Utils::distance(row,col,i,j); if(dist < min) { min = dist; near_enemy = temp; near_enemy_location = {i,j}; } } } } } if(near_enemy != nullptr) { int new_hp = near_enemy->getHp() + damage; near_enemy->setHp(new_hp); if(new_hp <= 0) { b[near_enemy_location.first][near_enemy_location.second] = nullptr; } } }
24.59322
93
0.465196
rotemish7
c9eb48dfea9c04d460ffd21cb5f3b927dd82e812
3,984
cpp
C++
engine/source/PADO/PADO_Object.cpp
Goldenbough44/PADO
a0fac1bb1cb61bafd27e11ac7046ef6ec49160d6
[ "MIT" ]
1
2021-08-13T04:39:53.000Z
2021-08-13T04:39:53.000Z
engine/source/PADO/PADO_Object.cpp
Goldenbough44/PADO
a0fac1bb1cb61bafd27e11ac7046ef6ec49160d6
[ "MIT" ]
2
2021-08-13T04:49:02.000Z
2022-03-25T19:20:56.000Z
engine/source/PADO/PADO_Object.cpp
Goldenbough44/PADO
a0fac1bb1cb61bafd27e11ac7046ef6ec49160d6
[ "MIT" ]
null
null
null
// // (c) 2019 Highwater Games Co. All Rights Reserved. // #include "PADO_Object.h" PADO_Object::PADO_Object() : position(0, 0) { } PADO_Object::~PADO_Object() { } void PADO_Object::Initialize() { } void PADO_Object::BeginPlay() { } void PADO_Object::Update() { } void PADO_Object::EndPlay() { } void PADO_Object::Render() { } void PADO_Object::Destroy() { if(!spawned) PADO_CatchError(210, "Cannot destroy object! The object isn't spawned : %s", "PADO_Object"); objectContainer->Destroy(); } void PADO_Object::Spawn(PADO_ObjectContainer *objectContainer, std::string name) { if(spawned) PADO_CatchError(200, "Object spawned already! : %s", objectName.c_str()); spawned = true; objectName = name; this->objectContainer = objectContainer; } void PADO_Object::Spawn(PADO_ObjectContainer *objectContainer, std::string name, PADO_Object *parent) { if(spawned) PADO_CatchError(200, "Object spawned already! : %s", objectName.c_str()); spawned = true; objectName = name; this->parent = parent; this->objectContainer = objectContainer; } void PADO_Object::Spawn(PADO_ObjectContainer* objectContainer, std::string name, unsigned int layer) { if(spawned) PADO_CatchError(200, "Object spawned already! : %s", objectName.c_str()); spawned = true; objectName = name; if (0 > setLayer(layer)) setLayer(0); this->objectContainer = objectContainer; } void PADO_Object::Spawn(PADO_ObjectContainer *objectContainer, std::string name, PADO_Object *parent, unsigned int layer) { if(spawned) PADO_CatchError(200, "Object spawned already! : %s", objectName.c_str()); spawned = true; objectName = name; if (0 > setLayer(layer)) setLayer(0); this->parent = parent; this->objectContainer = objectContainer; } void PADO_Object::Spawn(PADO_ObjectContainer* objectContainer, std::string name, unsigned int layer, unsigned int sortInLayer) { if(spawned) PADO_CatchError(200, "Object spawned already! : %s", objectName.c_str()); spawned = true; objectName = name; if (0 > setLayer(layer)) setLayer(0); if (0 > setSortInLayer(sortInLayer)) setSortInLayer(0); this->objectContainer = objectContainer; } void PADO_Object::Spawn(PADO_ObjectContainer *objectContainer, std::string name, PADO_Object *parent, unsigned int layer, unsigned int sortInLayer) { if(spawned) PADO_CatchError(200, "Object spawned already! : %s", objectName.c_str()); spawned = true; objectName = name; if (0 > setLayer(layer)) setLayer(0); if (0 > setSortInLayer(sortInLayer)) setSortInLayer(0); this->parent = parent; this->objectContainer = objectContainer; } std::string PADO_Object::GetName() { if(!spawned) PADO_CatchError(221, "Cannot get the name! The object isn't spawned : %s", "PADO_Object"); return objectName; } void PADO_Object::setActive(bool active) { this->active = active; } bool PADO_Object::isActive() { return active; } void PADO_Object::setVisibility(bool visibility) { this->visible = visibility; } bool PADO_Object::isVisible() { return visible; } bool PADO_Object::isSpawned() { return spawned; } void PADO_Object::setUpdate(bool update) { this->update = update; } bool PADO_Object::getUpdate() { return update; } void PADO_Object::setPosition(PADO_Vector2 position) { this->position = position; } const PADO_Vector2 *PADO_Object::getPosition() { return &position; } int PADO_Object::setLayer(unsigned int layer) { if(layer >= MAX_LAYER) { return -1; } this->layer = layer; return layer; } int PADO_Object::getLayer() { return sortInLayer; } int PADO_Object::setSortInLayer(unsigned int sortInLayer) { if(layer >= MAX_SORT_IN_LAYER) { return -1; } this->sortInLayer = sortInLayer; return sortInLayer; } int PADO_Object::getSortInLayer() { return sortInLayer; }
24.145455
109
0.682229
Goldenbough44
c9ed10547ad050426ff7fa6c90f63326213c4b22
881
cpp
C++
WildMagic4/LibFoundation/Mathematics/Wm4Vector2.cpp
rms80/libgeometry
e60ec7d34968573a9cda3f3bf56d2d4717385dc9
[ "BSL-1.0" ]
23
2015-08-13T07:36:00.000Z
2022-01-24T19:00:04.000Z
WildMagic4/LibFoundation/Mathematics/Wm4Vector2.cpp
rms80/libgeometry
e60ec7d34968573a9cda3f3bf56d2d4717385dc9
[ "BSL-1.0" ]
null
null
null
WildMagic4/LibFoundation/Mathematics/Wm4Vector2.cpp
rms80/libgeometry
e60ec7d34968573a9cda3f3bf56d2d4717385dc9
[ "BSL-1.0" ]
6
2015-07-06T21:37:31.000Z
2020-07-01T04:07:50.000Z
// Geometric Tools, LLC // Copyright (c) 1998-2010 // Distributed under the Boost Software License, Version 1.0. // http://www.boost.org/LICENSE_1_0.txt // http://www.geometrictools.com/License/Boost/LICENSE_1_0.txt // // File Version: 4.10.0 (2009/11/18) #include "Wm4FoundationPCH.h" #include "Wm4Vector2.h" using namespace Wm4; template<> const Vector2<float> Vector2<float>::ZERO(0.0f,0.0f); template<> const Vector2<float> Vector2<float>::UNIT_X(1.0f,0.0f); template<> const Vector2<float> Vector2<float>::UNIT_Y(0.0f,1.0f); template<> const Vector2<float> Vector2<float>::ONE(1.0f,1.0f); template<> const Vector2<double> Vector2<double>::ZERO(0.0,0.0); template<> const Vector2<double> Vector2<double>::UNIT_X(1.0,0.0); template<> const Vector2<double> Vector2<double>::UNIT_Y(0.0,1.0); template<> const Vector2<double> Vector2<double>::ONE(1.0,1.0);
40.045455
67
0.710556
rms80
c9ee6afef62776cfed6f043a24baffe689015a98
16,405
cc
C++
wrappers/8.1.1/vtkBrushWrap.cc
axkibe/node-vtk
900ad7b5500f672519da5aa24c99aa5a96466ef3
[ "BSD-3-Clause" ]
6
2016-02-03T12:48:36.000Z
2020-09-16T15:07:51.000Z
wrappers/8.1.1/vtkBrushWrap.cc
axkibe/node-vtk
900ad7b5500f672519da5aa24c99aa5a96466ef3
[ "BSD-3-Clause" ]
4
2016-02-13T01:30:43.000Z
2020-03-30T16:59:32.000Z
wrappers/8.1.1/vtkBrushWrap.cc
axkibe/node-vtk
900ad7b5500f672519da5aa24c99aa5a96466ef3
[ "BSD-3-Clause" ]
null
null
null
/* this file has been autogenerated by vtkNodeJsWrap */ /* editing this might proof futile */ #define VTK_WRAPPING_CXX #define VTK_STREAMS_FWD_ONLY #include <nan.h> #include "vtkObjectWrap.h" #include "vtkBrushWrap.h" #include "vtkObjectBaseWrap.h" #include "vtkImageDataWrap.h" #include "../../plus/plus.h" using namespace v8; extern Nan::Persistent<v8::Object> vtkNodeJsNoWrap; Nan::Persistent<v8::FunctionTemplate> VtkBrushWrap::ptpl; VtkBrushWrap::VtkBrushWrap() { } VtkBrushWrap::VtkBrushWrap(vtkSmartPointer<vtkBrush> _native) { native = _native; } VtkBrushWrap::~VtkBrushWrap() { } void VtkBrushWrap::Init(v8::Local<v8::Object> exports) { Nan::SetAccessor(exports, Nan::New("vtkBrush").ToLocalChecked(), ConstructorGetter); Nan::SetAccessor(exports, Nan::New("Brush").ToLocalChecked(), ConstructorGetter); } void VtkBrushWrap::ConstructorGetter( v8::Local<v8::String> property, const Nan::PropertyCallbackInfo<v8::Value>& info) { InitPtpl(); info.GetReturnValue().Set(Nan::New(ptpl)->GetFunction()); } void VtkBrushWrap::InitPtpl() { if (!ptpl.IsEmpty()) return; v8::Local<v8::FunctionTemplate> tpl = Nan::New<v8::FunctionTemplate>(New); VtkObjectWrap::InitPtpl( ); tpl->Inherit(Nan::New<FunctionTemplate>(VtkObjectWrap::ptpl)); tpl->SetClassName(Nan::New("VtkBrushWrap").ToLocalChecked()); tpl->InstanceTemplate()->SetInternalFieldCount(1); Nan::SetPrototypeMethod(tpl, "DeepCopy", DeepCopy); Nan::SetPrototypeMethod(tpl, "deepCopy", DeepCopy); Nan::SetPrototypeMethod(tpl, "GetColor", GetColor); Nan::SetPrototypeMethod(tpl, "getColor", GetColor); Nan::SetPrototypeMethod(tpl, "GetColorF", GetColorF); Nan::SetPrototypeMethod(tpl, "getColorF", GetColorF); Nan::SetPrototypeMethod(tpl, "GetOpacity", GetOpacity); Nan::SetPrototypeMethod(tpl, "getOpacity", GetOpacity); Nan::SetPrototypeMethod(tpl, "GetOpacityF", GetOpacityF); Nan::SetPrototypeMethod(tpl, "getOpacityF", GetOpacityF); Nan::SetPrototypeMethod(tpl, "GetTexture", GetTexture); Nan::SetPrototypeMethod(tpl, "getTexture", GetTexture); Nan::SetPrototypeMethod(tpl, "GetTextureProperties", GetTextureProperties); Nan::SetPrototypeMethod(tpl, "getTextureProperties", GetTextureProperties); Nan::SetPrototypeMethod(tpl, "NewInstance", NewInstance); Nan::SetPrototypeMethod(tpl, "newInstance", NewInstance); Nan::SetPrototypeMethod(tpl, "SafeDownCast", SafeDownCast); Nan::SetPrototypeMethod(tpl, "safeDownCast", SafeDownCast); Nan::SetPrototypeMethod(tpl, "SetColor", SetColor); Nan::SetPrototypeMethod(tpl, "setColor", SetColor); Nan::SetPrototypeMethod(tpl, "SetColorF", SetColorF); Nan::SetPrototypeMethod(tpl, "setColorF", SetColorF); Nan::SetPrototypeMethod(tpl, "SetOpacity", SetOpacity); Nan::SetPrototypeMethod(tpl, "setOpacity", SetOpacity); Nan::SetPrototypeMethod(tpl, "SetOpacityF", SetOpacityF); Nan::SetPrototypeMethod(tpl, "setOpacityF", SetOpacityF); Nan::SetPrototypeMethod(tpl, "SetTexture", SetTexture); Nan::SetPrototypeMethod(tpl, "setTexture", SetTexture); Nan::SetPrototypeMethod(tpl, "SetTextureProperties", SetTextureProperties); Nan::SetPrototypeMethod(tpl, "setTextureProperties", SetTextureProperties); #ifdef VTK_NODE_PLUS_VTKBRUSHWRAP_INITPTPL VTK_NODE_PLUS_VTKBRUSHWRAP_INITPTPL #endif ptpl.Reset( tpl ); } void VtkBrushWrap::New(const Nan::FunctionCallbackInfo<v8::Value>& info) { if(!info.IsConstructCall()) { Nan::ThrowError("Constructor not called in a construct call."); return; } if(info.Length() == 0) { vtkSmartPointer<vtkBrush> native = vtkSmartPointer<vtkBrush>::New(); VtkBrushWrap* obj = new VtkBrushWrap(native); obj->Wrap(info.This()); } else { if(info[0]->ToObject() != vtkNodeJsNoWrap ) { Nan::ThrowError("Parameter Error"); return; } } info.GetReturnValue().Set(info.This()); } void VtkBrushWrap::DeepCopy(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkBrushWrap *wrapper = ObjectWrap::Unwrap<VtkBrushWrap>(info.Holder()); vtkBrush *native = (vtkBrush *)wrapper->native.GetPointer(); if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkBrushWrap::ptpl))->HasInstance(info[0])) { VtkBrushWrap *a0 = ObjectWrap::Unwrap<VtkBrushWrap>(info[0]->ToObject()); if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } native->DeepCopy( (vtkBrush *) a0->native.GetPointer() ); return; } Nan::ThrowError("Parameter mismatch"); } void VtkBrushWrap::GetColor(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkBrushWrap *wrapper = ObjectWrap::Unwrap<VtkBrushWrap>(info.Holder()); vtkBrush *native = (vtkBrush *)wrapper->native.GetPointer(); size_t i; if(info.Length() > 0 && info[0]->IsUint8Array()) { v8::Local<v8::Uint8Array>a0(v8::Local<v8::Uint8Array>::Cast(info[0]->ToObject())); if( a0->Length() < 4 ) { Nan::ThrowError("Array too short."); return; } if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } native->GetColor( (unsigned char *)(a0->Buffer()->GetContents().Data()) ); return; } else if(info.Length() > 0 && info[0]->IsArray()) { v8::Local<v8::Array>a0(v8::Local<v8::Array>::Cast(info[0]->ToObject())); unsigned char b0[4]; if( a0->Length() < 4 ) { Nan::ThrowError("Array too short."); return; } for( i = 0; i < 4; i++ ) { if( !a0->Get(i)->IsUint32() ) { Nan::ThrowError("Array contents invalid."); return; } b0[i] = a0->Get(i)->Uint32Value(); } if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } native->GetColor( b0 ); return; } Nan::ThrowError("Parameter mismatch"); } void VtkBrushWrap::GetColorF(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkBrushWrap *wrapper = ObjectWrap::Unwrap<VtkBrushWrap>(info.Holder()); vtkBrush *native = (vtkBrush *)wrapper->native.GetPointer(); size_t i; if(info.Length() > 0 && info[0]->IsFloat64Array()) { v8::Local<v8::Float64Array>a0(v8::Local<v8::Float64Array>::Cast(info[0]->ToObject())); if( a0->Length() < 4 ) { Nan::ThrowError("Array too short."); return; } if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } native->GetColorF( (double *)(a0->Buffer()->GetContents().Data()) ); return; } else if(info.Length() > 0 && info[0]->IsArray()) { v8::Local<v8::Array>a0(v8::Local<v8::Array>::Cast(info[0]->ToObject())); double b0[4]; if( a0->Length() < 4 ) { Nan::ThrowError("Array too short."); return; } for( i = 0; i < 4; i++ ) { if( !a0->Get(i)->IsNumber() ) { Nan::ThrowError("Array contents invalid."); return; } b0[i] = a0->Get(i)->NumberValue(); } if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } native->GetColorF( b0 ); return; } Nan::ThrowError("Parameter mismatch"); } void VtkBrushWrap::GetOpacity(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkBrushWrap *wrapper = ObjectWrap::Unwrap<VtkBrushWrap>(info.Holder()); vtkBrush *native = (vtkBrush *)wrapper->native.GetPointer(); unsigned char r; if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } r = native->GetOpacity(); info.GetReturnValue().Set(Nan::New(r)); } void VtkBrushWrap::GetOpacityF(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkBrushWrap *wrapper = ObjectWrap::Unwrap<VtkBrushWrap>(info.Holder()); vtkBrush *native = (vtkBrush *)wrapper->native.GetPointer(); double r; if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } r = native->GetOpacityF(); info.GetReturnValue().Set(Nan::New(r)); } void VtkBrushWrap::GetTexture(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkBrushWrap *wrapper = ObjectWrap::Unwrap<VtkBrushWrap>(info.Holder()); vtkBrush *native = (vtkBrush *)wrapper->native.GetPointer(); vtkImageData * r; if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } r = native->GetTexture(); VtkImageDataWrap::InitPtpl(); v8::Local<v8::Value> argv[1] = { Nan::New(vtkNodeJsNoWrap) }; v8::Local<v8::Function> cons = Nan::New<v8::FunctionTemplate>(VtkImageDataWrap::ptpl)->GetFunction(); v8::Local<v8::Object> wo = cons->NewInstance(1, argv); VtkImageDataWrap *w = new VtkImageDataWrap(); w->native = r; w->Wrap(wo); info.GetReturnValue().Set(wo); } void VtkBrushWrap::GetTextureProperties(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkBrushWrap *wrapper = ObjectWrap::Unwrap<VtkBrushWrap>(info.Holder()); vtkBrush *native = (vtkBrush *)wrapper->native.GetPointer(); int r; if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } r = native->GetTextureProperties(); info.GetReturnValue().Set(Nan::New(r)); } void VtkBrushWrap::NewInstance(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkBrushWrap *wrapper = ObjectWrap::Unwrap<VtkBrushWrap>(info.Holder()); vtkBrush *native = (vtkBrush *)wrapper->native.GetPointer(); vtkBrush * r; if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } r = native->NewInstance(); VtkBrushWrap::InitPtpl(); v8::Local<v8::Value> argv[1] = { Nan::New(vtkNodeJsNoWrap) }; v8::Local<v8::Function> cons = Nan::New<v8::FunctionTemplate>(VtkBrushWrap::ptpl)->GetFunction(); v8::Local<v8::Object> wo = cons->NewInstance(1, argv); VtkBrushWrap *w = new VtkBrushWrap(); w->native = r; w->Wrap(wo); info.GetReturnValue().Set(wo); } void VtkBrushWrap::SafeDownCast(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkBrushWrap *wrapper = ObjectWrap::Unwrap<VtkBrushWrap>(info.Holder()); vtkBrush *native = (vtkBrush *)wrapper->native.GetPointer(); if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkObjectBaseWrap::ptpl))->HasInstance(info[0])) { VtkObjectBaseWrap *a0 = ObjectWrap::Unwrap<VtkObjectBaseWrap>(info[0]->ToObject()); vtkBrush * r; if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } r = native->SafeDownCast( (vtkObjectBase *) a0->native.GetPointer() ); VtkBrushWrap::InitPtpl(); v8::Local<v8::Value> argv[1] = { Nan::New(vtkNodeJsNoWrap) }; v8::Local<v8::Function> cons = Nan::New<v8::FunctionTemplate>(VtkBrushWrap::ptpl)->GetFunction(); v8::Local<v8::Object> wo = cons->NewInstance(1, argv); VtkBrushWrap *w = new VtkBrushWrap(); w->native = r; w->Wrap(wo); info.GetReturnValue().Set(wo); return; } Nan::ThrowError("Parameter mismatch"); } void VtkBrushWrap::SetColor(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkBrushWrap *wrapper = ObjectWrap::Unwrap<VtkBrushWrap>(info.Holder()); vtkBrush *native = (vtkBrush *)wrapper->native.GetPointer(); size_t i; if(info.Length() > 0 && info[0]->IsUint8Array()) { v8::Local<v8::Uint8Array>a0(v8::Local<v8::Uint8Array>::Cast(info[0]->ToObject())); if( a0->Length() < 3 ) { Nan::ThrowError("Array too short."); return; } if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } native->SetColor( (unsigned char *)(a0->Buffer()->GetContents().Data()) ); return; } else if(info.Length() > 0 && info[0]->IsArray()) { v8::Local<v8::Array>a0(v8::Local<v8::Array>::Cast(info[0]->ToObject())); unsigned char b0[3]; if( a0->Length() < 3 ) { Nan::ThrowError("Array too short."); return; } for( i = 0; i < 3; i++ ) { if( !a0->Get(i)->IsUint32() ) { Nan::ThrowError("Array contents invalid."); return; } b0[i] = a0->Get(i)->Uint32Value(); } if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } native->SetColor( b0 ); return; } else if(info.Length() > 0 && info[0]->IsUint32()) { if(info.Length() > 1 && info[1]->IsUint32()) { if(info.Length() > 2 && info[2]->IsUint32()) { if(info.Length() > 3 && info[3]->IsUint32()) { if(info.Length() != 4) { Nan::ThrowError("Too many parameters."); return; } native->SetColor( info[0]->Uint32Value(), info[1]->Uint32Value(), info[2]->Uint32Value(), info[3]->Uint32Value() ); return; } if(info.Length() != 3) { Nan::ThrowError("Too many parameters."); return; } native->SetColor( info[0]->Uint32Value(), info[1]->Uint32Value(), info[2]->Uint32Value() ); return; } } } Nan::ThrowError("Parameter mismatch"); } void VtkBrushWrap::SetColorF(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkBrushWrap *wrapper = ObjectWrap::Unwrap<VtkBrushWrap>(info.Holder()); vtkBrush *native = (vtkBrush *)wrapper->native.GetPointer(); size_t i; if(info.Length() > 0 && info[0]->IsFloat64Array()) { v8::Local<v8::Float64Array>a0(v8::Local<v8::Float64Array>::Cast(info[0]->ToObject())); if( a0->Length() < 3 ) { Nan::ThrowError("Array too short."); return; } if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } native->SetColorF( (double *)(a0->Buffer()->GetContents().Data()) ); return; } else if(info.Length() > 0 && info[0]->IsArray()) { v8::Local<v8::Array>a0(v8::Local<v8::Array>::Cast(info[0]->ToObject())); double b0[3]; if( a0->Length() < 3 ) { Nan::ThrowError("Array too short."); return; } for( i = 0; i < 3; i++ ) { if( !a0->Get(i)->IsNumber() ) { Nan::ThrowError("Array contents invalid."); return; } b0[i] = a0->Get(i)->NumberValue(); } if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } native->SetColorF( b0 ); return; } else if(info.Length() > 0 && info[0]->IsNumber()) { if(info.Length() > 1 && info[1]->IsNumber()) { if(info.Length() > 2 && info[2]->IsNumber()) { if(info.Length() > 3 && info[3]->IsNumber()) { if(info.Length() != 4) { Nan::ThrowError("Too many parameters."); return; } native->SetColorF( info[0]->NumberValue(), info[1]->NumberValue(), info[2]->NumberValue(), info[3]->NumberValue() ); return; } if(info.Length() != 3) { Nan::ThrowError("Too many parameters."); return; } native->SetColorF( info[0]->NumberValue(), info[1]->NumberValue(), info[2]->NumberValue() ); return; } } } Nan::ThrowError("Parameter mismatch"); } void VtkBrushWrap::SetOpacity(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkBrushWrap *wrapper = ObjectWrap::Unwrap<VtkBrushWrap>(info.Holder()); vtkBrush *native = (vtkBrush *)wrapper->native.GetPointer(); if(info.Length() > 0 && info[0]->IsUint32()) { if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } native->SetOpacity( info[0]->Uint32Value() ); return; } Nan::ThrowError("Parameter mismatch"); } void VtkBrushWrap::SetOpacityF(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkBrushWrap *wrapper = ObjectWrap::Unwrap<VtkBrushWrap>(info.Holder()); vtkBrush *native = (vtkBrush *)wrapper->native.GetPointer(); if(info.Length() > 0 && info[0]->IsNumber()) { if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } native->SetOpacityF( info[0]->NumberValue() ); return; } Nan::ThrowError("Parameter mismatch"); } void VtkBrushWrap::SetTexture(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkBrushWrap *wrapper = ObjectWrap::Unwrap<VtkBrushWrap>(info.Holder()); vtkBrush *native = (vtkBrush *)wrapper->native.GetPointer(); if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkImageDataWrap::ptpl))->HasInstance(info[0])) { VtkImageDataWrap *a0 = ObjectWrap::Unwrap<VtkImageDataWrap>(info[0]->ToObject()); if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } native->SetTexture( (vtkImageData *) a0->native.GetPointer() ); return; } Nan::ThrowError("Parameter mismatch"); } void VtkBrushWrap::SetTextureProperties(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkBrushWrap *wrapper = ObjectWrap::Unwrap<VtkBrushWrap>(info.Holder()); vtkBrush *native = (vtkBrush *)wrapper->native.GetPointer(); if(info.Length() > 0 && info[0]->IsInt32()) { if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } native->SetTextureProperties( info[0]->Int32Value() ); return; } Nan::ThrowError("Parameter mismatch"); }
25.713166
106
0.654617
axkibe
c9ef9054639d5f33b2bcf68dd02a4e080b8813c9
550
cpp
C++
CppTranslate/sample_be.cpp
PooiaFerdowsi/Cpp-Translate
e41d32d9feb3ebb07e3b756a836ee215998f74fe
[ "MIT" ]
48
2020-03-25T16:52:10.000Z
2022-03-28T17:11:13.000Z
CppTranslate/sample_be.cpp
PooiaFerdowsi/Cpp-Translate
e41d32d9feb3ebb07e3b756a836ee215998f74fe
[ "MIT" ]
22
2021-04-22T14:48:17.000Z
2021-11-02T06:45:51.000Z
CppTranslate/sample_be.cpp
PooiaFerdowsi/Cpp-Translate
e41d32d9feb3ebb07e3b756a836ee215998f74fe
[ "MIT" ]
19
2020-06-09T22:29:05.000Z
2022-03-21T20:44:41.000Z
#include "be_belarusian.h" узор<кляса t> кляса прыклад { }; цэлы_лік зачатак() { статычны булеев элемент прыраўнай праўда; калі(элемент ілжывы) { вярні 1; } указка_на_поле_сыбалаў_які_закончаны_нулявым_сымбалем p = новы сымбаль[10]; p індэкс(0) прыраўнай 'c'; p індэкс(1) прыраўнай 0; выпіш(p); вярні 0; } // bad and evil source code: template<class T> class exemple { }; int main() { static bool element = true; if (element == false) { return 1; } char* p = new char[10]; p[0] = 'c'; p[1] = 0; printf(p); return 0; }
12.222222
76
0.656364
PooiaFerdowsi
c9f0dfb3c7fb00695aa70c191a5177f22c3a2b10
1,806
cc
C++
sources/tests/stresstests.test.cc
arcanis/text-layout
bfa95293ed06c9b355e803968fceb00b421352ba
[ "Unlicense", "MIT" ]
22
2017-05-13T07:03:02.000Z
2021-11-08T08:34:42.000Z
sources/tests/stresstests.test.cc
arcanis/text-layout
bfa95293ed06c9b355e803968fceb00b421352ba
[ "Unlicense", "MIT" ]
null
null
null
sources/tests/stresstests.test.cc
arcanis/text-layout
bfa95293ed06c9b355e803968fceb00b421352ba
[ "Unlicense", "MIT" ]
5
2017-05-13T07:03:05.000Z
2020-05-25T06:19:03.000Z
#include "./framework.hh" TEST_CASE("stress test #1") { SETUP(""); for (auto t = 0u; t < 30; ++t) APPEND("Foo\n"); ASSERT_EQ(LINE_COUNT(), 31); ASSERT_EQ(TEXT(), "Foo\nFoo\nFoo\nFoo\nFoo\nFoo\nFoo\nFoo\nFoo\nFoo\nFoo\nFoo\nFoo\nFoo\nFoo\nFoo\nFoo\nFoo\nFoo\nFoo\nFoo\nFoo\nFoo\nFoo\nFoo\nFoo\nFoo\nFoo\nFoo\nFoo\n"); } TEST_CASE("stress test #2") { SETUP(""); for (auto t = 0u; t < 30; ++t) { APPEND("a"); APPEND(" "); } ASSERT_EQ(LINE_COUNT(), 1); ASSERT_EQ(TEXT(), "a a a a a a a a a a a a a a a a a a a a a a a a a a a a a a"); } TEST_CASE("stress test #3") { SETUP(""); layout.setColumns(10); layout.setSoftWrap(true); layout.setCollapseWhitespaces(true); layout.setJustifyText(true); RESET(); for (auto t = 0u; t < 30; ++t) { APPEND("a"); APPEND(" "); } ASSERT_EQ(LINE_COUNT(), 6); ASSERT_EQ(TEXT(), "a a a a a\na a a a a\na a a a a\na a a a a\na a a a a\na a a a a"); } TEST_CASE("stress test #4") { SETUP(""); layout.setColumns(10); layout.setSoftWrap(true); layout.setCollapseWhitespaces(true); layout.setPreserveTrailingSpaces(true); layout.setJustifyText(true); RESET(); auto currentPosition = Position(0, 0); FOR(c, "a b c d e f g h i j k l m n o p q r s t u v w x y z\nA B C D E F G H I J K L M N O P Q R S T U V W X Y Z") { auto characterIndex = layout.getCharacterIndexForPosition(currentPosition); SPLICE(characterIndex, 0, c); currentPosition = layout.getPositionForCharacterIndex(characterIndex + 1); } ASSERT_EQ(LINE_COUNT(), 12); ASSERT_EQ(TEXT(), "a b c d e\nf g h i j\nk l m n o\np q r s t\nu v w x y\nz\nA B C D E\nF G H I J\nK L M N O\nP Q R S T\nU V W X Y\nZ"); }
26.558824
176
0.582503
arcanis
c9f1d68067156e6683e47e5eef3b5cbfaedebc76
2,688
cpp
C++
workspace/src/render_world.cpp
nadnbuds/cs130
982dac98005dcf0675eacaf7b56a9ec6c53a8877
[ "MIT" ]
null
null
null
workspace/src/render_world.cpp
nadnbuds/cs130
982dac98005dcf0675eacaf7b56a9ec6c53a8877
[ "MIT" ]
null
null
null
workspace/src/render_world.cpp
nadnbuds/cs130
982dac98005dcf0675eacaf7b56a9ec6c53a8877
[ "MIT" ]
null
null
null
#include <vector> #include <limits> #include "render_world.h" #include "flat_shader.h" #include "object.h" #include "light.h" #include "ray.h" Render_World::Render_World() :background_shader(0),ambient_intensity(0),enable_shadows(true), recursion_depth_limit(3),disable_fresnel_reflection(false),disable_fresnel_refraction(false) {} Render_World::~Render_World() { delete background_shader; for(size_t i=0;i<objects.size();i++) delete objects[i]; for(size_t i=0;i<lights.size();i++) delete lights[i]; } // Find the closest object of intersection and return the object that was // intersected. Record the Hit structure in hit. If no intersection occurred, // return NULL. Note that in the case of a Boolean, the object returned will be // the Boolean, but the object stored in hit will be the underlying primitive. // Any intersection with t<=small_t should be ignored. Object* Render_World::Closest_Intersection(const Ray& ray,Hit& hit) { Object* closestObj = nullptr; double minT = std::numeric_limits<double>::max(); for(Object* var : objects) { std::vector<Hit> hits; var->Intersection(ray, hits); for(Hit h : hits) { if (h.t < minT && h.t > small_t) { minT = h.t; hit = h; closestObj = var; } } } return closestObj; } // set up the initial view ray and call void Render_World::Render_Pixel(const ivec2& pixel_index) { Ray ray; ray.endpoint = camera.position; ray.direction = (camera.World_Position(pixel_index) - camera.position).normalized(); vec3 color=Cast_Ray(ray, 0); camera.Set_Pixel(pixel_index,Pixel_Color(color)); } void Render_World::Render() { for(int j=0;j<camera.number_pixels[1];j++) for(int i=0;i<camera.number_pixels[0];i++) Render_Pixel(ivec2(i,j)); } // cast ray and return the color of the closest intersected surface point, // or the background color if there is no object intersection vec3 Render_World::Cast_Ray(const Ray& ray,int recursion_depth) { Hit objHit; objHit.object = nullptr; objHit.t = 0; objHit.ray_exiting = false; Object* obj = Closest_Intersection(ray, objHit); vec3 color; //If there is an Obj for the ray if (obj != nullptr && recursion_depth < recursion_depth_limit) { vec3 point = ray.Point(objHit.t); vec3 normal = obj->Normal(point); if (objHit.ray_exiting) { normal *= -1; } color = obj->material_shader->Shade_Surface( ray, point, normal, recursion_depth, objHit.ray_exiting); } //If there is no Obj, use the background else { vec3 dummy; color = background_shader->Shade_Surface( ray, ray.endpoint, ray.direction, recursion_depth, false); } return color; }
27.151515
96
0.697545
nadnbuds
c9f6ee8d75a66e04607361715b3130bfa133d12d
1,706
hpp
C++
libs/core/include/fcppt/variant/object_impl.hpp
freundlich/fcppt
17df1b1ad08bf2435f6902d5465e3bc3fe5e3022
[ "BSL-1.0" ]
13
2015-02-21T18:35:14.000Z
2019-12-29T14:08:29.000Z
libs/core/include/fcppt/variant/object_impl.hpp
cpreh/fcppt
17df1b1ad08bf2435f6902d5465e3bc3fe5e3022
[ "BSL-1.0" ]
5
2016-08-27T07:35:47.000Z
2019-04-21T10:55:34.000Z
libs/core/include/fcppt/variant/object_impl.hpp
freundlich/fcppt
17df1b1ad08bf2435f6902d5465e3bc3fe5e3022
[ "BSL-1.0" ]
8
2015-01-10T09:22:37.000Z
2019-12-01T08:31:12.000Z
// Copyright Carl Philipp Reh 2009 - 2021. // 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 FCPPT_VARIANT_OBJECT_IMPL_HPP_INCLUDED #define FCPPT_VARIANT_OBJECT_IMPL_HPP_INCLUDED #include <fcppt/variant/object_decl.hpp> #include <fcppt/variant/size_type.hpp> #include <fcppt/variant/detail/get_unsafe_impl.hpp> #include <fcppt/config/external_begin.hpp> #include <utility> #include <variant> #include <fcppt/config/external_end.hpp> template <typename... Types> template <typename U, typename> fcppt::variant::object<Types...>::object(U &&_other) : impl_{std::forward<U>(_other)} { } template <typename... Types> template <typename U> U &fcppt::variant::object<Types...>::get_unsafe() { return fcppt::variant::detail::get_unsafe_impl<this_type, U>(this->impl_); } template <typename... Types> template <typename U> U const &fcppt::variant::object<Types...>::get_unsafe() const { return fcppt::variant::detail::get_unsafe_impl<this_type, U>(this->impl_); } template <typename... Types> fcppt::variant::size_type fcppt::variant::object<Types...>::type_index() const { return this->impl_.index(); } template <typename... Types> bool fcppt::variant::object<Types...>::is_invalid() const { return this->type_index() == std::variant_npos; } template <typename... Types> typename fcppt::variant::object<Types...>::std_type &fcppt::variant::object<Types...>::impl() { return this->impl_; } template <typename... Types> typename fcppt::variant::object<Types...>::std_type const & fcppt::variant::object<Types...>::impl() const { return this->impl_; } #endif
27.079365
93
0.721571
freundlich
c9f72b2e01bc87e5839ec3566dab21cfdfb8e6f7
1,433
cpp
C++
ARPREC/arprec-2.2.13/tests/pslq3_main.cpp
paveloom-p/P3
57df3b6263db81685f137a7ed9428dbd3c1b4a5b
[ "Unlicense" ]
null
null
null
ARPREC/arprec-2.2.13/tests/pslq3_main.cpp
paveloom-p/P3
57df3b6263db81685f137a7ed9428dbd3c1b4a5b
[ "Unlicense" ]
null
null
null
ARPREC/arprec-2.2.13/tests/pslq3_main.cpp
paveloom-p/P3
57df3b6263db81685f137a7ed9428dbd3c1b4a5b
[ "Unlicense" ]
null
null
null
#include <iostream> #include <iomanip> #include <cfloat> #include <cmath> #include <arprec/mp_real.h> #include <arprec/mp_int.h> #include "pslq3.h" #include "pslq_main.h" using std::cout; using std::endl; int main(int argc, char **argv) { int mode = 0; int n; int r = 7, s = 8; int nr_digits = 780; int n_eps; /* Parse command line arguments. */ parse_command(argc, argv, mode, n, r, s, nr_digits, n_eps); n = r * s + 1; n_eps = (nr_digits < 700 ? 10 : 20) - nr_digits; cout << "nr_digits = " << nr_digits << endl; cout << "debug_level = " << debug_level << endl; cout << "n = " << n << endl; if (debug_level > 0) { cout << "r = " << r << " s = " << s << endl; cout << "n_eps = " << n_eps << endl;; } /* Initialize data */ mp::mp_init(nr_digits); matrix<mp_real> x(n); matrix<mp_real> rel(n); mp_real eps = pow(mp_real(10.0), n_eps); init_data(mode, n, r, s, x, rel); if (debug_level >= 1) { x.print("Initial x:"); } /* Perform Level-1 PSLQ. */ int result = pslq3(x, rel, eps); /* Output recovered relation. */ if (result == RESULT_RELATION_FOUND) { cout << "Relation found:" << endl; cout << std::fixed << std::setprecision(0); for (int i = 0; i < n; i++) { cout << std::setw(3) << i; cout << std::setw(24) << rel(i) << endl; } } else { cout << "Precision exhausted." << endl; } mp::mp_finalize(); return 0; }
21.712121
61
0.556874
paveloom-p
c9ffc6fba005eaeffb1a50e23e874db2db42d124
1,287
cpp
C++
graph-source-code/233-C/2345881.cpp
AmrARaouf/algorithm-detection
59f3028d2298804870b32729415d71eec6116557
[ "MIT" ]
null
null
null
graph-source-code/233-C/2345881.cpp
AmrARaouf/algorithm-detection
59f3028d2298804870b32729415d71eec6116557
[ "MIT" ]
null
null
null
graph-source-code/233-C/2345881.cpp
AmrARaouf/algorithm-detection
59f3028d2298804870b32729415d71eec6116557
[ "MIT" ]
null
null
null
//Language: MS C++ #include <set> #include <cmath> #include <vector> #include <string> #include <cstdio> #include <iostream> #include <algorithm> using namespace std; int k, n; char m[110][110]; int main(){ #ifdef _DEBUG freopen("input.txt", "r", stdin); freopen("output.txt", "w", stdout); #endif cin >> k; memset(m, 0, sizeof(m)); int l = 1, r = 100; while (r - l > 1){ int m1 = (l + r) / 2; if (m1 * (m1 - 1) * (m1 - 2) / 6 <= k) l = m1; else r = m1; } for (int i = n; i < n + l; i++) for (int j = n; j < n + l; j++) if (i != j) m[i][j] = 1; n = l; k -= l * (l - 1) * (l - 2) / 6; while (k){ l = 1, r = 100; while (r - l > 1){ int m1 = (l + r) / 2; if (m1 * (m1 - 1) / 2 <= k) l = m1; else r = m1; } k -= l * (l - 1) / 2; for (int i = 0; i < l; i++) m[i][n] = 1, m[n][i] = 1; n++; } cout << n << '\n'; for (int i = 0; i < n; i++){ for (int j = 0; j < n; j++) cout << (char)(m[i][j] + 48); cout << '\n'; } return 0; }
21.098361
47
0.337995
AmrARaouf
a00568d228b315f5b91afcaa5af5c285916d3ff1
4,306
hpp
C++
Common/include/common/expected.hpp
foxostro/FlapjackOS
34bd2cc9b0983b917a089efe2055ca8f78d56d9a
[ "BSD-2-Clause" ]
null
null
null
Common/include/common/expected.hpp
foxostro/FlapjackOS
34bd2cc9b0983b917a089efe2055ca8f78d56d9a
[ "BSD-2-Clause" ]
null
null
null
Common/include/common/expected.hpp
foxostro/FlapjackOS
34bd2cc9b0983b917a089efe2055ca8f78d56d9a
[ "BSD-2-Clause" ]
null
null
null
#ifndef FLAPJACKOS_COMMON_INCLUDE_COMMON_EXPECTED_HPP #define FLAPJACKOS_COMMON_INCLUDE_COMMON_EXPECTED_HPP #include <cassert> #include "either.hpp" #include "error.hpp" template<typename T> class Expected { public: using Value = T; template<typename U> using Next = Expected<U>; Expected(const Value& value) : either_(value) {} Expected(Value&& value) : either_(std::move(value)) {} Expected(const Error& error) : either_(error) {} Expected(Error&& error) : either_(std::move(error)) {} bool has_value() const { return !either_.is_left(); } Error& get_error() & { return either_.get_left(); } Error&& get_error() && { return std::move(either_.get_left()); } const Error& get_error() const& { return either_.get_left(); } Value& get_value() & { return either_.get_right(); } Value&& get_value() && { return std::move(either_.get_right()); } const Value& get_value() const& { return either_.get_right(); } auto& get_either() & { return either_; } auto&& get_either() && { return std::move(either_); } const auto& get_either() const& { return either_; } template<typename Function> auto map_error(Function&& fn) const { static_assert(!std::is_void<decltype(fn(get_error()))>::value, ""); if (has_value()) { return *this; } else { return Expected{fn(get_error())}; } } template<typename Function> Expected&& map_error(Function&& fn) && { static_assert(!std::is_void<decltype(fn(get_error()))>::value, ""); if (has_value()) { return std::move(*this); } else { return std::move(Expected{fn(get_error())}); } } // Map functor. // If the expected has value then unwrap it, pass it to the given function, // wrap the function's return value in another expected, and return that. // If the expected has no value then return an empty optional with a type // matching the function. // A return value of void is handled by mapping to Monostate. Likewise, // no parameters are passed to `fn' in the case where Value=Monostate. // This method can be chained with other calls to map(), &c. template<typename Function> auto map(Function&& fn) & { return map_impl(*this, std::forward<Function>(fn)); } template<typename Function> auto map(Function&& fn) && { return map_impl(*this, std::forward<Function>(fn)); } template<typename Function> auto map(Function&& fn) const& { return map_impl(*this, std::forward<Function>(fn)); } // If the expected has value then unwrap it, pass it to the given function, // and then return whatever value that function returned. // If the expected has no value then return an empty optional with a type // matching the function. // A return value of void is handled by mapping to Monostate. Likewise, // no parameters are passed to `fn' in the case where Value=Monostate. // This method can be chained with other calls to map(), &c. template<typename Function> auto and_then(Function&& fn) & { return and_then_impl(*this, std::forward<Function>(fn)); } template<typename Function> auto and_then(Function&& fn) && { return and_then_impl(std::move(*this), std::forward<Function>(fn)); } template<typename Function> auto and_then(Function&& fn) const& { return and_then_impl(*this, std::forward<Function>(fn)); } // If the expected has no value then execute the function. // The function accepts no parameters and returns no value. // Since or_else() returns *this, it can be chained with map(), &c. template<typename Function> auto or_else(Function&& fn) & { return or_else_impl(*this, std::forward<Function>(fn)); } template<typename Function> auto or_else(Function&& fn) && { return or_else_impl(std::move(*this), std::forward<Function>(fn)); } template<typename Function> auto or_else(Function&& fn) const& { return or_else_impl(*this, std::forward<Function>(fn)); } private: Either<Error, Value> either_; }; #endif // FLAPJACKOS_COMMON_INCLUDE_COMMON_EXPECTED_HPP
32.621212
79
0.640269
foxostro
a007ce907249b0cfa3b9d4e362fb7247fe6fc8b8
709
cpp
C++
src/serialize19.lib/serialize19/serialize.std_vector.test.cpp
Fettpet/co-cpp19
928a835c4f66032aa88ce01df7899da86d37df22
[ "MIT" ]
null
null
null
src/serialize19.lib/serialize19/serialize.std_vector.test.cpp
Fettpet/co-cpp19
928a835c4f66032aa88ce01df7899da86d37df22
[ "MIT" ]
null
null
null
src/serialize19.lib/serialize19/serialize.std_vector.test.cpp
Fettpet/co-cpp19
928a835c4f66032aa88ce01df7899da86d37df22
[ "MIT" ]
null
null
null
#include "ReadArchive.h" #include "dynamicWrite.h" #include "serialize.std_vector.h" #include <gtest/gtest.h> using namespace serialize19; TEST(serialize, std_vector) { using T = std::vector<int>; auto input = T{7, 13, 23}; auto buffer = dynamicWrite(input); auto reader = ReadArchive{buffer.slice()}; auto output = T{}; serialize(reader, output); EXPECT_EQ(output, input); } TEST(serialize, std_vector_empty) { using T = std::vector<int>; auto input = T{}; auto buffer = dynamicWrite(input); auto reader = ReadArchive{buffer.slice()}; auto output = T{}; serialize(reader, output); EXPECT_EQ(output, input); }
20.852941
47
0.626234
Fettpet
a00e03ef5e335ba68f5a721360f741c90cbf7c77
4,055
hpp
C++
include/lbann/objective_functions/weight_regularization/l2.hpp
oyamay/lbann
57116ecc030c0d17bc941f81131c1a335bc2c4ad
[ "Apache-2.0" ]
null
null
null
include/lbann/objective_functions/weight_regularization/l2.hpp
oyamay/lbann
57116ecc030c0d17bc941f81131c1a335bc2c4ad
[ "Apache-2.0" ]
null
null
null
include/lbann/objective_functions/weight_regularization/l2.hpp
oyamay/lbann
57116ecc030c0d17bc941f81131c1a335bc2c4ad
[ "Apache-2.0" ]
null
null
null
//////////////////////////////////////////////////////////////////////////////// // Copyright (c) 2014-2019, Lawrence Livermore National Security, LLC. // Produced at the Lawrence Livermore National Laboratory. // Written by the LBANN Research Team (B. Van Essen, et al.) listed in // the CONTRIBUTORS file. <[email protected]> // // LLNL-CODE-697807. // All rights reserved. // // This file is part of LBANN: Livermore Big Artificial Neural Network // Toolkit. For details, see http://software.llnl.gov/LBANN or // https://github.com/LLNL/LBANN. // // Licensed under the Apache License, Version 2.0 (the "Licensee"); you // may not use this file except in compliance with the License. You may // obtain a copy of the License at: // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or // implied. See the License for the specific language governing // permissions and limitations under the license. //////////////////////////////////////////////////////////////////////////////// #ifndef LBANN_OBJECTIVE_FUNCTIONS_WEIGHT_REGULARIZATION_L2_WEIGHT_REGULARIZATION_HPP_INCLUDED #define LBANN_OBJECTIVE_FUNCTIONS_WEIGHT_REGULARIZATION_L2_WEIGHT_REGULARIZATION_HPP_INCLUDED #include "lbann/objective_functions/objective_function_term.hpp" namespace lbann { template <typename> class data_type_optimizer; template <typename> class data_type_weights; /** @class l2_weight_regularization * @brief Apply L2 regularization to a set of weights. * * Given a weights tensor @f$ w @f$, * @f[ L2(w) = \frac{1}{2} \sum\limits_{i} w(i)^2 @f] * Note the @f$ 1/2 @f$ scaling factor. */ class l2_weight_regularization : public objective_function_term { public: using AccumulateDataType = DataType; using OptimizerType = data_type_optimizer<DataType>; using WeightsType = data_type_weights<DataType>; template <El::Device D> using DMatType = El::Matrix<AccumulateDataType, D>; using CPUMatType = DMatType<El::Device::CPU>; public: /** @param scale_factor The objective function term is * @f$ \text{scale\_factor} \times \sum L2(w_i) @f$ */ l2_weight_regularization(EvalType scale_factor = 1); l2_weight_regularization* copy() const override { return new l2_weight_regularization(*this); } /** Archive for checkpoint and restart */ template <class Archive> void serialize( Archive & ar ) { ar(cereal::base_class<objective_function_term>(this)); } std::string name() const override { return "L2 weight regularization"; } void setup(model& m) override; void start_evaluation() override; EvalType finish_evaluation() override; /** Compute the gradient w.r.t. the activations. * * L2 regularization is independent of forward prop output, so * nothing needs to be done here. * * @todo Come up with a better function name in the base class. */ void differentiate() override {}; /** Compute the gradient w.r.t. the weights. * * @f[ \nabla_w L2(w) = w @f] */ void compute_weight_regularization() override; private: /** Contributions to evaluated value. */ std::map<El::Device, CPUMatType> m_contributions; /** For non-blocking allreduces. */ Al::request m_allreduce_req; #ifdef LBANN_HAS_GPU /** For non-blocking GPU-CPU memory copies. */ gpu_lib::event_wrapper m_copy_event; #endif // LBANN_HAS_GPU /** Add the sum of squares of @c vals to @c contribution. * * @param vals The values to accumulate * @param contribution @f$ 1 \times 1 @f$ matrix. Used as an * accumulation variable. */ template <El::Device Device> static void accumulate_contribution(const DMatType<Device>& vals, DMatType<Device>& contribution); }; } // namespace lbann #endif // LBANN_OBJECTIVE_FUNCTIONS_WEIGHT_REGULARIZATION_L2_WEIGHT_REGULARIZATION_HPP_INCLUDED
34.956897
97
0.687546
oyamay
a00f9f1f620bea25cab77ae6a5c084de702031d3
443
cpp
C++
codechef/FEB20/SNUG_FIT.cpp
udayan14/Competitive_Coding
79e23fdeb909b4161a193d88697a4fe5f4fbbdce
[ "MIT" ]
null
null
null
codechef/FEB20/SNUG_FIT.cpp
udayan14/Competitive_Coding
79e23fdeb909b4161a193d88697a4fe5f4fbbdce
[ "MIT" ]
null
null
null
codechef/FEB20/SNUG_FIT.cpp
udayan14/Competitive_Coding
79e23fdeb909b4161a193d88697a4fe5f4fbbdce
[ "MIT" ]
null
null
null
#include<iostream> #include<algorithm> using namespace std; int main(){ ios_base::sync_with_stdio(false); cin.tie(NULL); int t; cin >> t; while(t--){ int n; cin >> n; unsigned a[n]; unsigned b[n]; for(int i=0 ; i<n ; i++) cin >> a[i]; for(int i=0 ; i<n ; i++) cin >> b[i]; sort(a,a+n); sort(b,b+n); unsigned long long int out = 0; for(int i=0 ; i<n ; i++) out += min(a[i],b[i]); cout << out << "\n"; } }
15.821429
34
0.525959
udayan14
a0115c88d2d2f11ac8d1c76a32b7b5421b478576
493
cpp
C++
OpenGL3D Game/Floor.cpp
TheSandstorm/Tank-Busters
06aec0b25a92e8c9c8959c5173cbef605bb6543d
[ "MIT" ]
null
null
null
OpenGL3D Game/Floor.cpp
TheSandstorm/Tank-Busters
06aec0b25a92e8c9c8959c5173cbef605bb6543d
[ "MIT" ]
null
null
null
OpenGL3D Game/Floor.cpp
TheSandstorm/Tank-Busters
06aec0b25a92e8c9c8959c5173cbef605bb6543d
[ "MIT" ]
null
null
null
#include "Floor.h" CFloor::CFloor(glm::vec3 _Pos) { Scale = glm::vec3(8.0f, 8.0f, 0.2f); Rotation = glm::vec3(0.0f, 0.0f, 0.0f); Pos = _Pos; VAO = CObjectManager::GetMesh(FLOOR_ENTITY)->VAO; IndicesCount = CObjectManager::GetMesh(FLOOR_ENTITY)->IndicesCount; Texture = CObjectManager::GetMesh(FLOOR_ENTITY)->Texture; Shader = CObjectManager::GetMesh(FLOOR_ENTITY)->Shader; Type = FLOOR_ENTITY; } void CFloor::Update(float _DeltaTime) { VPMatrix = CCamera::GetMatrix(); Render(); }
24.65
68
0.716024
TheSandstorm
a0159e63ea13c1863ef3f2bda895cc10b32aea32
3,340
cpp
C++
dataAQ.cpp
kevinyxlu/cs32lab03
582c42181d8e7891a6f34a3ef5f524c915e963a1
[ "MIT" ]
null
null
null
dataAQ.cpp
kevinyxlu/cs32lab03
582c42181d8e7891a6f34a3ef5f524c915e963a1
[ "MIT" ]
null
null
null
dataAQ.cpp
kevinyxlu/cs32lab03
582c42181d8e7891a6f34a3ef5f524c915e963a1
[ "MIT" ]
null
null
null
/* aggregate data */ #include "dataAQ.h" #include "demogData.h" #include <iostream> #include <algorithm> dataAQ::dataAQ() {} /* necessary function to aggregate the data - this CAN and SHOULD vary per student - depends on how they map, etc. */ void dataAQ::createStateData(std::vector<shared_ptr<demogData>> theData) { //FILL in std::string currentState = theData[0]->getState(); std::vector<shared_ptr<demogData>> stateCounties; for (auto entry : theData) { if (entry->getState() != currentState) { theStates.insert(std::make_pair(currentState, std::make_shared<demogState>(currentState, stateCounties))); // std::cout << "New map entry for state: " << currentState << "\n"; //deboog stateCounties.clear(); currentState = entry->getState(); } stateCounties.push_back(entry); } if (stateCounties.size()) { theStates.insert(std::make_pair(currentState, std::make_shared<demogState>(currentState, stateCounties))); //std::cout << "New map entry for (final) state: " << currentState << "\n"; //deboog stateCounties.clear(); } //std::cout << theStates.size() << "\n"; //deboog } //return the name of the state with the largest population under age 5 string dataAQ::youngestPop() { //FILL in double record = 0; string usurper = ""; for (auto state : theStates) { if (state.second->getpopUnder5() > record) { usurper = state.first; record = state.second->getpopUnder5(); } } return usurper; } //return the name of the state with the largest population under age 18 string dataAQ::teenPop() { double record = 0; string usurper = ""; for (auto state : theStates) { //std::cout << state.first << ": " << state.second->getpopUnder18() << " vs " << record << "\n"; if (state.second->getpopUnder18() > record) { usurper = state.first; record = state.second->getpopUnder18(); } } return usurper; } //return the name of the state with the largest population over age 65 string dataAQ::wisePop() { double record = 0; string usurper = ""; for (auto state : theStates) { if (state.second->getpopOver65() > record) { usurper = state.first; record = state.second->getpopOver65(); } } return usurper; } //return the name of the state with the largest population who did not receive high school diploma string dataAQ::underServeHS() { //FILL in double record = 0; string usurper = ""; for (auto state : theStates) { if ((100.0 - state.second->getHSup()) > record) { usurper = state.first; record = 100.0 - state.second->getHSup(); } } return usurper; } //return the name of the state with the largest population who did receive bachelors degree and up string dataAQ::collegeGrads() { double record = 0; string usurper = ""; for (auto state : theStates) { if ((state.second->getBAup()) > record) { usurper = state.first; record = state.second->getBAup(); } } return usurper; } //return the name of the state with the largest population below the poverty line string dataAQ::belowPoverty() { double record = 0; string usurper = ""; for (auto state : theStates) { if (state.second->getPoverty() > record) { usurper = state.first; record = state.second->getPoverty(); } } return usurper; }
29.557522
112
0.648802
kevinyxlu