hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
108
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
b3e2fc0a940576d593698a434dc6ea4c8eb7d035
4,620
cpp
C++
examples/example_0520.cpp
dyomas/pyhrol
6865b7de3377f9d6d3f1b282a39d5980497b703d
[ "BSD-3-Clause" ]
null
null
null
examples/example_0520.cpp
dyomas/pyhrol
6865b7de3377f9d6d3f1b282a39d5980497b703d
[ "BSD-3-Clause" ]
null
null
null
examples/example_0520.cpp
dyomas/pyhrol
6865b7de3377f9d6d3f1b282a39d5980497b703d
[ "BSD-3-Clause" ]
null
null
null
/* * Copyright (c) 2013, 2014, Pyhrol, pyhrol@rambler.ru * GEO: N55.703431,E37.623324 .. N48.742359,E44.536997 * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 4. Neither the name of the Pyhrol 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 REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS 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 <pyhrol.h> #include <pyhrol_auto_holder.h> struct iterator { std::string::const_iterator iter; const std::string::const_iterator iter_end; iterator(const pyhrol::Ptr<const std::string> &container) : iter(container->begin()) , iter_end(container->end()) , m_container(container) { Py_IncRef(m_container); } ~iterator() { Py_DecRef(m_container); } private: PyObject *m_container; }; struct item: pyhrol::AutoHolder { const char data; item(const pyhrol::Ptr< ::iterator> &iter) : pyhrol::AutoHolder(iter) , data(*iter->iter ++) { } }; class Container: public pyhrol::TypeWrapper<std::string>, public pyhrol::TypeIterable<std::string, ::iterator> { Container() : pyhrol::TypeBase<std::string>("MyClass", NULL) { m_type_object.tp_iternext = NULL; } virtual void constructor(std::string &res, pyhrol::Tuples &_args) const { const char *data; PYHROL_PARSE_TUPLE_1(NULL, _args, data) PYHROL_AFTER_PARSE_TUPLE(_args) PYHROL_AFTER_BUILD_VALUE(_args) new(&res) std::string(data); PYHROL_AFTER_EXECUTE_DEFAULT(_args) } virtual void destructor(std::string &obj) const { using std::string; obj.~string(); } virtual void print(std::ostream &os, const std::string &obj) const { os << obj; } virtual void iter(const pyhrol::Ptr< ::iterator> &iter, const pyhrol::Ptr<const std::string> &container) const { new(&*iter) ::iterator(container); } static void init() __attribute__ ((constructor)) { m_get(new Container); } }; class Iterator: public pyhrol::TypeWrapper< ::iterator>, public pyhrol::TypeIterable< ::iterator, item> { Iterator() : pyhrol::TypeBase< ::iterator>("iter", NULL) { m_type_object.tp_iter = NULL; } virtual void constructor(::iterator &res, pyhrol::Tuples &_args) const { const char *data; PYHROL_PARSE_TUPLE_1(NULL, _args, data) PYHROL_AFTER_PARSE_TUPLE(_args) PYHROL_AFTER_BUILD_VALUE(_args) ::Container::T_struct *obj = ::Container::allocate_static(); new(&obj->endosome) std::string(data); new(&res) ::iterator(pyhrol::Ptr<const std::string>(&obj->endosome, *obj)); PYHROL_AFTER_EXECUTE_DEFAULT(_args) } virtual void destructor(::iterator &obj) const { obj.~iterator(); } virtual bool next(const pyhrol::Ptr<item> &itm, const pyhrol::Ptr< ::iterator> &iter) const { bool retval = false; if (iter->iter != iter->iter_end) { new (&*itm) item(iter); retval = true; } return retval; } static void init() __attribute__ ((constructor)) { m_get(new Iterator); } }; class Data: public pyhrol::TypeWrapper<item> { Data() : pyhrol::TypeBase< ::item>("item", NULL) { m_add_member<const char, &item::data>("data", NULL); } virtual void destructor(item &itm) const { itm.~item(); } static void init() __attribute__ ((constructor)) { m_get(new Data); } };
27.017544
112
0.683117
dyomas
b3e5f4e875d2cd30505a5b6e7b464f4a323dfa52
8,682
cpp
C++
Axis.Echinopsis/application/factories/collectors/TextReportElementCollectorParser.cpp
renato-yuzup/axis-fem
2e8d325eb9c8e99285f513b4c1218ef53eb0ab22
[ "MIT" ]
2
2021-07-23T08:49:54.000Z
2021-07-29T22:07:30.000Z
Axis.Echinopsis/application/factories/collectors/TextReportElementCollectorParser.cpp
renato-yuzup/axis-fem
2e8d325eb9c8e99285f513b4c1218ef53eb0ab22
[ "MIT" ]
null
null
null
Axis.Echinopsis/application/factories/collectors/TextReportElementCollectorParser.cpp
renato-yuzup/axis-fem
2e8d325eb9c8e99285f513b4c1218ef53eb0ab22
[ "MIT" ]
null
null
null
#include "TextReportElementCollectorParser.hpp" #include "foundation/OutOfBoundsException.hpp" #include "services/language/factories/AxisGrammar.hpp" #include "services/language/parsing/ExpressionNode.hpp" #include "services/language/parsing/SymbolTerminal.hpp" #include "services/language/parsing/OperatorTerminal.hpp" #include "services/language/parsing/ReservedWordTerminal.hpp" #include "services/language/parsing/EnumerationExpression.hpp" #include "services/language/parsing/NumberTerminal.hpp" namespace aaocs = axis::application::output::collectors::summarizers; namespace aafc = axis::application::factories::collectors; namespace aslp = axis::services::language::parsing; namespace aslf = axis::services::language::factories; namespace aslpm = axis::services::language::primitives; namespace asli = axis::services::language::iterators; namespace { static const int SetExpressionIdentifier = -5; static const int ScaleExpressionIdentifier = -10; static const int NodeExpressionIdentifier = -15; } aafc::TextReportElementCollectorParser::ElementCollectorParseResult::ElementCollectorParseResult( const aslp::ParseResult& result ) : parseResult_(result), collectorType_(kUndefined) { bool d[6] = {true, true, true, true, true, true}; Init(d); } aafc::TextReportElementCollectorParser::ElementCollectorParseResult::ElementCollectorParseResult( const aslp::ParseResult& result, ElementCollectorParseResult::CollectorType collectorType, const bool *directionState, const axis::String& targetSetName ) : parseResult_(result), collectorType_(collectorType), targetSetName_(targetSetName) { Init(directionState); } aafc::TextReportElementCollectorParser::ElementCollectorParseResult::ElementCollectorParseResult( const ElementCollectorParseResult& other ) { operator =(other); } aafc::TextReportElementCollectorParser::ElementCollectorParseResult& aafc::TextReportElementCollectorParser::ElementCollectorParseResult::operator=( const ElementCollectorParseResult& other ) { parseResult_ = other.parseResult_; collectorType_ = other.collectorType_; targetSetName_ = other.targetSetName_; Init(other.directionState_); return *this; } void aafc::TextReportElementCollectorParser::ElementCollectorParseResult::Init( const bool * directionState ) { switch (collectorType_) { case kStress: case kStrain: directionCount_ = 6; break; default: directionCount_ = 3; break; } for (int i = 0; i < directionCount_; ++i) { directionState_[i] = directionState[i]; } } aafc::TextReportElementCollectorParser::ElementCollectorParseResult::~ElementCollectorParseResult( void ) { // nothing to do here } aslp::ParseResult aafc::TextReportElementCollectorParser::ElementCollectorParseResult::GetParseResult( void ) const { return parseResult_; } aafc::TextReportElementCollectorParser::ElementCollectorParseResult::CollectorType aafc::TextReportElementCollectorParser::ElementCollectorParseResult::GetCollectorType( void ) const { return collectorType_; } axis::String aafc::TextReportElementCollectorParser::ElementCollectorParseResult::GetTargetSetName( void ) const { return targetSetName_; } bool aafc::TextReportElementCollectorParser::ElementCollectorParseResult::ShouldCollectDirection( int directionIndex ) const { switch (collectorType_) { case kStress: case kStrain: if (directionIndex < 0 || directionIndex >= 6) { throw axis::foundation::OutOfBoundsException(); } break; default: if (directionIndex < 0 || directionIndex >= 3) { throw axis::foundation::OutOfBoundsException(); } break; } return directionState_[directionIndex]; } aafc::TextReportElementCollectorParser::TextReportElementCollectorParser( void ) { InitGrammar(); } aafc::TextReportElementCollectorParser::~TextReportElementCollectorParser( void ) { delete direction3DEnum_; delete direction6DEnum_; } aafc::TextReportElementCollectorParser::ElementCollectorParseResult aafc::TextReportElementCollectorParser::Parse( const asli::InputIterator& begin, const asli::InputIterator& end ) { aslp::ParseResult result = collectorStatement_(begin, end); if (result.IsMatch()) { ElementCollectorParseResult ncpr = InterpretParseTree(result); if (ncpr.GetTargetSetName().empty()) { // prohibited situation result.SetResult(aslp::ParseResult::FailedMatch); } return ncpr; } return ElementCollectorParseResult(result); } aafc::TextReportElementCollectorParser::ElementCollectorParseResult aafc::TextReportElementCollectorParser::InterpretParseTree( const aslp::ParseResult& result ) const { // default values ElementCollectorParseResult::CollectorType collectorType = ElementCollectorParseResult::kUndefined; bool directionState[6] = {false, false, false, false, false, false}; axis::String targetSetName; // go to starting node const aslp::ParseTreeNode& rootNode = result.GetParseTree(); const aslp::ParseTreeNode * node = static_cast<const aslp::ExpressionNode&>(rootNode).GetFirstChild(); // get which collector type was specified node = node->GetNextSibling()->GetNextSibling(); const aslp::ParseTreeNode *typeExprNode = static_cast<const aslp::ExpressionNode&>(*node).GetFirstChild(); const aslp::ReservedWordTerminal *typeNode = static_cast<const aslp::ReservedWordTerminal *>(typeExprNode); collectorType = (ElementCollectorParseResult::CollectorType)typeNode->GetValue(); // check whether directions was specified typeExprNode = typeExprNode->GetNextSibling(); if (typeExprNode != NULL) { // yes, it was if (static_cast<const aslp::ExpressionNode *>(typeExprNode)->IsEnumeration()) { // a set of various directions (or maybe a single one besides 'ALL') was specified const aslp::EnumerationExpression *directionEnumExpr = static_cast<const aslp::EnumerationExpression *>(typeExprNode); const aslp::ReservedWordTerminal *directionNode = static_cast<const aslp::ReservedWordTerminal *>( directionEnumExpr->GetFirstChild()); while (directionNode != NULL) { int index = directionNode->GetValue(); directionState[index] = true; directionNode = static_cast<const aslp::ReservedWordTerminal *>(directionNode->GetNextSibling()); } } else { // 'ALL' was specified for (int i = 0; i < 6; ++i) directionState[i] = true; } } else { // nothing was specified; assume all directions for (int i = 0; i < 6; ++i) directionState[i] = true; } node = node->GetNextSibling(); const aslp::ExpressionNode& setExprNode = static_cast<const aslp::ExpressionNode&>(*node); const aslp::ParseTreeNode *setNode = static_cast<const aslp::ParseTreeNode *>(setExprNode.GetFirstChild()); setNode = setNode->GetNextSibling()->GetNextSibling(); targetSetName = setNode->ToString(); return ElementCollectorParseResult(result, collectorType, directionState, targetSetName); } void axis::application::factories::collectors::TextReportElementCollectorParser::InitGrammar( void ) { anyIdentifierExpression_ << aslf::AxisGrammar::CreateIdParser() << aslf::AxisGrammar::CreateStringParser(false); collectorType6D_ << aslf::AxisGrammar::CreateReservedWordParser(_T("STRESS"), (int)ElementCollectorParseResult::kStress) << aslf::AxisGrammar::CreateReservedWordParser(_T("STRAIN"), (int)ElementCollectorParseResult::kStrain); direction6D_ << aslf::AxisGrammar::CreateReservedWordParser(_T("XX"), 0) << aslf::AxisGrammar::CreateReservedWordParser(_T("YY"), 1) << aslf::AxisGrammar::CreateReservedWordParser(_T("ZZ"), 2) << aslf::AxisGrammar::CreateReservedWordParser(_T("YZ"), 3) << aslf::AxisGrammar::CreateReservedWordParser(_T("XZ"), 4) << aslf::AxisGrammar::CreateReservedWordParser(_T("XY"), 5); direction6DEnum_ = new axis::services::language::primitives::EnumerationParser(direction6D_, true); optionalDirection6DExpression_ << *direction6DEnum_ << aslf::AxisGrammar::CreateReservedWordParser(_T("ALL"), -1) << aslf::AxisGrammar::CreateEpsilonParser(); collectorType6DExpression_ << collectorType6D_ << optionalDirection6DExpression_; collectorTypeExpression_ << collectorType6DExpression_; setExpression_ << aslf::AxisGrammar::CreateReservedWordParser(_T("ON"), SetExpressionIdentifier) << aslf::AxisGrammar::CreateReservedWordParser(_T("SET")) << anyIdentifierExpression_; collectorStatement_ << aslf::AxisGrammar::CreateReservedWordParser(_T("RECORD")) << aslf::AxisGrammar::CreateReservedWordParser(_T("ELEMENT"), NodeExpressionIdentifier) << collectorTypeExpression_ << setExpression_; }
36.944681
124
0.760194
renato-yuzup
b3e6cbb6e267a886524cda9fcc411b608994070d
3,241
cpp
C++
wavebench-dag/src/algorithms/local_sequence_alignment.cpp
fabianmcg/wavedag
e975792aef4423de6cf43af6bfde44ef89a5db0d
[ "MIT" ]
1
2021-01-10T09:04:38.000Z
2021-01-10T09:04:38.000Z
wavebench-dag/src/algorithms/local_sequence_alignment.cpp
fabianmcg/wavedag
e975792aef4423de6cf43af6bfde44ef89a5db0d
[ "MIT" ]
null
null
null
wavebench-dag/src/algorithms/local_sequence_alignment.cpp
fabianmcg/wavedag
e975792aef4423de6cf43af6bfde44ef89a5db0d
[ "MIT" ]
null
null
null
/*---------------------------------------------------------------------------*/ /*! * \file local_sequence_alignment.cpp * \author Robert Searles * \date Tue Sep 19 15:46:00 EST 2018 * \brief Local Sequence Alignment in-gridcell algorithm * \note */ /*---------------------------------------------------------------------------*/ #include "dimensions.h" #include "local_sequence_alignment.h" #include <stdio.h> #include <algorithm> #include <cstdlib> #include <string> /*=============================================*/ /*=== MANDATORY FUNCTIONS ===*/ /*=============================================*/ /*--- Constructor ---*/ LSA::LSA(Dimensions d) { printf("Creating Local Sequence Alignment Simulation\n\n"); dims=d; if(dims.ncomponents==32) { seq1=seq1_cstr; seq2=seq2_cstr; } else { seq1=generate_sequence(dims.ncell_x,"ATCG"); seq2=generate_sequence(dims.ncell_y,"ATCG"); } rows = seq1.size() + 1; cols = seq2.size() + 1; matrix_size = rows*cols; /*--- Array Allocation ---*/ matrix = (int*)malloc_host_int(matrix_size); } int LSA::r(){ return rows; } int LSA::c(){ return cols; } /*--- Initialization ---*/ void LSA::init(){ for (int x = 0; x < rows; x++) for (int y = 0; y < cols; y++) matrix[(x * cols) + y] = 0; } /*--- Run ---*/ /*--- This should run your wavefront sweep component & in-gridcell computation ---*/ void LSA::run(){ create_score_matrix(rows, cols); } /*--- Print Output ---*/ void LSA::print(){ for (int x = 1; x < rows; x++) for (int y = 1; y < cols; y++) printf("matrix[%d][%d] = %d\n", x, cols-1, matrix[(x * cols) + cols-1]); } /*=============================================*/ /*=== ALGORITHM-SPECIFIC FUNCTIONS ===*/ /*=============================================*/ /*--- Create sequence alignment scoring matrix ---*/ void LSA::create_score_matrix(int rows, int cols) { int max_score = 0; int nthreads=1,b=2; char* bx_str=std::getenv("OMP_BLOCK_DIMX"); char* by_str=std::getenv("OMP_BLOCK_DIMY"); char* nthreads_str=std::getenv("OMP_NUM_THREADS"); if(nthreads_str!=nullptr) if(strlen(nthreads_str)>0) nthreads=std::stoi(std::string(nthreads_str)); b*=nthreads; int bx=b,by=b; if(bx_str!=nullptr) if(strlen(bx_str)>0) bx=std::stoi(std::string(bx_str)); if(by_str!=nullptr) if(strlen(by_str)>0) by=std::stoi(std::string(by_str)); #pragma omp dag coarsening(BLOCK,bx,by) for (int x = 1; x < rows; x++) for (int y = 1; y < cols; y++) { #pragma omp dag task depend({(x+1)*cols+y+1,((x+1)<rows)&&((y+1)<cols)},{(x+1)*cols+y,(x+1)<rows},{x*cols+y+1,(y+1)<cols}) { matrix[(x * cols) + y] = calc_score(x, y); } } } /*--- Calculate gridcell score ---*/ int LSA::calc_score(int x, int y) { int similarity; if (seq1[x - 1] == seq2[y - 1]) similarity = match; else similarity = mismatch; /*--- Calculate scores ---*/ int diag_score = matrix[(x - 1) * cols + (y - 1)] + similarity; int up_score = matrix[(x - 1) * cols + y] + gap; int left_score = matrix[x * cols + (y - 1)] + gap; /*--- Take max of scores and return ---*/ int result = 0; if (diag_score > result) result = diag_score; if (up_score > result) result = up_score; if (left_score > result) result = left_score; return result; }
25.722222
122
0.551682
fabianmcg
b3e73856d1c96c4adcd7e742e212eccd8798d14f
1,861
hh
C++
src/try_unix.hh
catern/iqueue
81f3fe27e4588862f4854f028340fa6c9da83748
[ "Apache-2.0" ]
2
2021-09-23T12:07:52.000Z
2022-01-19T00:16:03.000Z
src/try_unix.hh
catern/iqueue
81f3fe27e4588862f4854f028340fa6c9da83748
[ "Apache-2.0" ]
null
null
null
src/try_unix.hh
catern/iqueue
81f3fe27e4588862f4854f028340fa6c9da83748
[ "Apache-2.0" ]
1
2021-09-23T01:23:20.000Z
2021-09-23T01:23:20.000Z
/* * Copyright 2021 Two Sigma Open Source, LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #pragma once #include <err.h> #include <system_error> #include <initializer_list> //// Utility functions // a poor imitation of Rust try!() // aborts if retval < 0, otherwise returns retval namespace ts { namespace mmia { namespace cpputils { namespace try_unix { inline int try_func(int retval, const char *func, int line) { if (retval < 0) { // err(1, "%s: %d", func, line); warn("%s: %d", func, line); throw std::system_error(std::error_code(errno, std::system_category())); } return retval; } // like try_func, but doesn't abort if errno is in exclude_errors inline int try_exclude_func(int retval, std::initializer_list<int> exclude_errors, const char *func, int line) { if (retval < 0) { for (int err : exclude_errors) { if (errno == err) return retval; } // err(1, "%s: %d", func, line); warn("%s: %d", func, line); throw std::system_error(std::error_code(errno, std::system_category())); } return retval; } }}}} #define try_(x) ts::mmia::cpputils::try_unix::try_func(x, __FUNCTION__, __LINE__) #define try_exclude(x, ...) ts::mmia::cpputils::try_unix::try_exclude_func(x, __VA_ARGS__, __FUNCTION__, __LINE__)
36.490196
114
0.665771
catern
b3e9498d2897aab34857bb11ef8666c3988a5629
3,059
cpp
C++
example/celldevs/country/main-country.cpp
romancardenas/cadmium
a1c7d0d75569731496852cb3e2bdd37c07c3ddf0
[ "BSD-2-Clause" ]
16
2016-09-16T21:49:11.000Z
2021-05-24T17:30:35.000Z
example/celldevs/country/main-country.cpp
romancardenas/cadmium
a1c7d0d75569731496852cb3e2bdd37c07c3ddf0
[ "BSD-2-Clause" ]
31
2016-10-06T01:59:20.000Z
2021-01-27T16:15:34.000Z
example/celldevs/country/main-country.cpp
romancardenas/cadmium
a1c7d0d75569731496852cb3e2bdd37c07c3ddf0
[ "BSD-2-Clause" ]
13
2016-09-17T16:19:34.000Z
2021-08-16T14:50:35.000Z
/** * Copyright (c) 2020, Román Cárdenas Rodríguez * ARSLab - Carleton University * GreenLSI - Polytechnic University of Madrid * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 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 <string> #include <cadmium/modeling/dynamic_coupled.hpp> #include <cadmium/engine/pdevs_dynamic_runner.hpp> #include <cadmium/logger/common_loggers.hpp> #include "country_coupled.hpp" using namespace std; using namespace cadmium; using TIME = double; std::string json_file = "./scenario.json"; /*************** Loggers *******************/ static ofstream out_messages("../simulation_results/country/output_messages.txt"); struct oss_sink_messages{ static ostream& sink(){ return out_messages; } }; static ofstream out_state("../simulation_results/country/state.txt"); struct oss_sink_state{ static ostream& sink(){ return out_state; } }; using state=logger::logger<logger::logger_state, dynamic::logger::formatter<TIME>, oss_sink_state>; using log_messages=logger::logger<logger::logger_messages, dynamic::logger::formatter<TIME>, oss_sink_messages>; using global_time_mes=logger::logger<logger::logger_global_time, dynamic::logger::formatter<TIME>, oss_sink_messages>; using global_time_sta=logger::logger<logger::logger_global_time, dynamic::logger::formatter<TIME>, oss_sink_state>; using logger_top=logger::multilogger<state, log_messages, global_time_mes, global_time_sta>; int main() { country_coupled<TIME> test = country_coupled<TIME>("test"); test.add_cells_json(json_file); test.couple_cells(); std::shared_ptr<cadmium::dynamic::modeling::coupled<TIME>> t = std::make_shared<cells_coupled<TIME, std::string, int, int>>(test); cadmium::dynamic::engine::runner<TIME, logger_top> r(t, {0}); r.run_until(300); return 0; }
42.486111
134
0.755803
romancardenas
b3ee6bcc5ab85f7d9652b5132b9b94a57d183632
118
hpp
C++
build/opencv_tests_config.hpp
Meatlf/OpenCV4
4a882c0b3cf10700c0cc4ac785266fa02d3f2470
[ "BSD-3-Clause" ]
null
null
null
build/opencv_tests_config.hpp
Meatlf/OpenCV4
4a882c0b3cf10700c0cc4ac785266fa02d3f2470
[ "BSD-3-Clause" ]
null
null
null
build/opencv_tests_config.hpp
Meatlf/OpenCV4
4a882c0b3cf10700c0cc4ac785266fa02d3f2470
[ "BSD-3-Clause" ]
null
null
null
#define OPENCV_INSTALL_PREFIX "/usr/local/opencv430" #define OPENCV_TEST_DATA_INSTALL_PATH "share/opencv4/testdata"
23.6
62
0.838983
Meatlf
b3f0afffaf11b3cfac4d46ea71c1b183355aac2a
6,745
cpp
C++
service/easy-setup/enrollee/arduino/easysetup.cpp
shamblett/iotivity-1.1.0
16e7cbaee4394dfd430ffef37b1cbdcd2d2d57c3
[ "Apache-2.0" ]
null
null
null
service/easy-setup/enrollee/arduino/easysetup.cpp
shamblett/iotivity-1.1.0
16e7cbaee4394dfd430ffef37b1cbdcd2d2d57c3
[ "Apache-2.0" ]
null
null
null
service/easy-setup/enrollee/arduino/easysetup.cpp
shamblett/iotivity-1.1.0
16e7cbaee4394dfd430ffef37b1cbdcd2d2d57c3
[ "Apache-2.0" ]
1
2019-07-26T08:18:26.000Z
2019-07-26T08:18:26.000Z
//****************************************************************** // // Copyright 2015 Samsung Electronics All Rights Reserved. // //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= /** * @file * * This file contains the implementation for EasySetup Enrollee device */ #include "easysetup.h" #include "softap.h" #include "onboarding.h" #include "logger.h" #include "resourcehandler.h" /** * @var ES_ENROLLEE_TAG * @brief Logging tag for module name. */ #define ES_ENROLLEE_TAG "ES" //----------------------------------------------------------------------------- // Private variables //----------------------------------------------------------------------------- /** * @var gTargetSsid * @brief Target SSID of the Soft Access point to which the device has to connect */ static char gTargetSsid[MAXSSIDLEN]; /** * @var gTargetPass * @brief Password of the target access point to which the device has to connect */ static char gTargetPass[MAXNETCREDLEN]; /** * @var gEnrolleeStatusCb * @brief Fucntion pointer holding the callback for intimation of EasySetup Enrollee status callback */ static ESEnrolleeEventCallback gEnrolleeStatusCb = NULL; /** * @var gIsSecured * @brief Variable to check if secure mode is enabled or not. */ static bool gIsSecured = false; //----------------------------------------------------------------------------- // Private internal function prototypes //----------------------------------------------------------------------------- void ESOnboardingCallback(ESResult esResult); void ESProvisioningCallback(ESResult esResult); void ESOnboardingCallbackTargetNet(ESResult esResult); static bool ESEnrolleeValidateParam(OCConnectivityType networkType, const char *ssid, const char *passwd, ESEnrolleeEventCallback cb); void ESOnboardingCallback(ESResult esResult) { OIC_LOG_V(DEBUG, ES_ENROLLEE_TAG, "ESOnboardingCallback with result = %d", esResult); if(esResult == ES_OK) { gEnrolleeStatusCb(esResult, ES_ON_BOARDED_STATE); } else { OIC_LOG_V(DEBUG, ES_ENROLLEE_TAG, "Onboarding is failed callback result is = %d", esResult); gEnrolleeStatusCb(esResult, ES_INIT_STATE); } } void ESProvisioningCallback(ESResult esResult) { OIC_LOG_V(DEBUG, ES_ENROLLEE_TAG, "ESProvisioningCallback with result = %d", esResult); if (esResult == ES_RECVTRIGGEROFPROVRES) { GetTargetNetworkInfoFromProvResource(gTargetSsid, gTargetPass); gEnrolleeStatusCb(ES_OK, ES_PROVISIONED_STATE); OIC_LOG(DEBUG, ES_ENROLLEE_TAG, "Connecting with target network"); // Connecting/onboarding to target network ConnectToWiFiNetwork(gTargetSsid, gTargetPass, ESOnboardingCallbackTargetNet); } else { OIC_LOG_V(DEBUG, ES_ENROLLEE_TAG, "Provisioning is failed callback result is = %d", esResult); // Resetting Enrollee to ONBOARDED_STATE as Enrollee is alreday onboarded in previous step gEnrolleeStatusCb(ES_OK, ES_ON_BOARDED_STATE); } } void ESOnboardingCallbackTargetNet(ESResult esResult) { OIC_LOG_V(DEBUG, ES_ENROLLEE_TAG, "ESOnboardingCallback on target network with result = %d", esResult); if(esResult == ES_OK) { gEnrolleeStatusCb(esResult, ES_ON_BOARDED_TARGET_NETWORK_STATE); } else { OIC_LOG_V(DEBUG, ES_ENROLLEE_TAG, "Onboarding is failed on target network and callback result is = %d", esResult); // Resetting Enrollee state to the ES_PROVISIONED_STATE // as device is already being provisioned with target network creds. gEnrolleeStatusCb(esResult, ES_PROVISIONED_STATE); } } ESResult ESInitEnrollee(OCConnectivityType networkType, const char *ssid, const char *passwd, bool isSecured, ESEnrolleeEventCallback cb) { OIC_LOG(INFO, ES_ENROLLEE_TAG, "ESInitEnrollee IN"); if(!ESEnrolleeValidateParam(networkType,ssid,passwd,cb)) { OIC_LOG(ERROR, ES_ENROLLEE_TAG, "ESInitEnrollee::Stopping Easy setup due to invalid parameters"); return ES_ERROR; } //Init callback gEnrolleeStatusCb = cb; gIsSecured = isSecured; // TODO : This onboarding state has to be set by lower layer, as they better // knows when actually on-boarding started. cb(ES_ERROR,ES_ON_BOARDING_STATE); OIC_LOG(INFO, ES_ENROLLEE_TAG, "received callback"); OIC_LOG(INFO, ES_ENROLLEE_TAG, "onboarding now.."); if(!ESOnboard(ssid, passwd, ESOnboardingCallback)) { OIC_LOG(ERROR, ES_ENROLLEE_TAG, "ESInitEnrollee::On-boarding failed"); cb(ES_ERROR, ES_INIT_STATE); return ES_ERROR; } OIC_LOG(INFO, ES_ENROLLEE_TAG, "ESInitEnrollee OUT"); return ES_OK; } ESResult ESTerminateEnrollee() { UnRegisterResourceEventCallBack(); //Delete Prov resource if (DeleteProvisioningResource() != OC_STACK_OK) { OIC_LOG(ERROR, ES_ENROLLEE_TAG, "Deleting prov resource error!!"); return ES_ERROR; } OIC_LOG(ERROR, ES_ENROLLEE_TAG, "ESTerminateEnrollee success"); return ES_OK; } ESResult ESInitProvisioning() { OIC_LOG(INFO, ES_ENROLLEE_TAG, "ESInitProvisioning <<IN>>"); if (CreateProvisioningResource(gIsSecured) != OC_STACK_OK) { OIC_LOG(ERROR, ES_ENROLLEE_TAG, "CreateProvisioningResource error"); return ES_ERROR; } RegisterResourceEventCallBack(ESProvisioningCallback); OIC_LOG(INFO, ES_ENROLLEE_TAG, "ESInitProvisioning <<OUT>>"); return ES_RESOURCECREATED; } static bool ESEnrolleeValidateParam(OCConnectivityType /*networkType*/, const char *ssid, const char *passwd, ESEnrolleeEventCallback cb) { if (!ssid || !passwd || !cb) { OIC_LOG(ERROR, ES_ENROLLEE_TAG, "ESEnrolleeValidateParam - Invalid parameters"); return false; } return true; }
32.427885
101
0.634692
shamblett
b3f2161a3d7782a1babd2aa31e38ceb78aefe9d1
1,728
cpp
C++
src/main.cpp
WhitNearSpace/Whitworth-CommandModule
d7316fa391c58c69ef25a447df9465e36e21dddf
[ "MIT" ]
1
2019-05-28T16:03:37.000Z
2019-05-28T16:03:37.000Z
src/main.cpp
WhitNearSpace/Whitworth-CommandModule
d7316fa391c58c69ef25a447df9465e36e21dddf
[ "MIT" ]
null
null
null
src/main.cpp
WhitNearSpace/Whitworth-CommandModule
d7316fa391c58c69ef25a447df9465e36e21dddf
[ "MIT" ]
null
null
null
#include <mbed.h> #include "RockBlock9603.h" DigitalOut led1(LED1); RockBlock9603 sat(p9, p10, NC); int main() { uint64_t imei; ThisThread::sleep_for(1s); imei = sat.get_IMEI(); printf("IMEI = %llu\n", imei); int bars = sat.get_new_signal_quality(); printf("bars = %d\n", bars); BufferStatus bs = sat.get_buffer_status(); printf("Buffer status\n"); printf("\tMOMSN: %d\n", bs.outgoingMsgNum); printf("\tMO flag: %d\n", bs.outgoingFlag); while (true) { led1 = !led1; ThisThread::sleep_for(1s); } } /********************************************************************************* * Ublox test code ********************************************************************************/ // I2C i2c(p9,p10); // int main() { // int latitude, longitude; // int altitude; // char SIV; // int groundSpeed, verticalVelocity; // i2c.frequency(400000); // Ublox_GPS myGPS(&i2c); // ThisThread::sleep_for(2s); // led1 = myGPS.isConnected(); // myGPS.disableDebugging(); // while (true) { // ThisThread::sleep_for(5s); // latitude = myGPS.getLatitude(); // longitude = myGPS.getLongitude(); // altitude = myGPS.getAltitude(); // SIV = myGPS.getSIV(); // groundSpeed = myGPS.getGroundSpeed(); // verticalVelocity = myGPS.getVerticalVelocity(); // printf("Lat: %.6f", latitude*1e-7); // printf(" Lon: %.6f", longitude*1e-7); // printf(" Alt: %.1f m", altitude/1000.0); // printf(" \tSatellites: %d\r\n", SIV); // printf("Ground speed: %f m/s", groundSpeed/1000.0); // printf(" Vertical velocity: %f m/s\r\n", verticalVelocity/1000.0); // printf("---------------------------------------------------------------\n"); // } // }
28.8
83
0.528356
WhitNearSpace
b3f89f55c1b435f645f66f2214d6eb717e3acb03
2,059
cpp
C++
PolyEngine/RenderingDevice/OpenGL/Src/Proxy/GLCubemapDeviceProxy.cpp
PiotrMoscicki/PolyEngine
573c453e9d1ae0a351ad14410595ff844e3b4620
[ "MIT" ]
65
2017-04-04T20:33:44.000Z
2019-12-02T23:06:58.000Z
PolyEngine/RenderingDevice/OpenGL/Src/Proxy/GLCubemapDeviceProxy.cpp
PiotrMoscicki/PolyEngine
573c453e9d1ae0a351ad14410595ff844e3b4620
[ "MIT" ]
46
2017-04-21T12:26:38.000Z
2019-12-15T05:31:47.000Z
PolyEngine/RenderingDevice/OpenGL/Src/Proxy/GLCubemapDeviceProxy.cpp
PiotrMoscicki/PolyEngine
573c453e9d1ae0a351ad14410595ff844e3b4620
[ "MIT" ]
51
2017-04-12T10:53:32.000Z
2019-11-20T13:05:54.000Z
#include <PolyRenderingDeviceGLPCH.hpp> #include <Proxy/GLCubemapDeviceProxy.hpp> #include <Proxy/GLTextureDeviceProxy.hpp> #include <Common/GLUtils.hpp> using namespace Poly; GLCubemapDeviceProxy::GLCubemapDeviceProxy(size_t width, size_t height) : Width(width), Height(height) { InitCubemapParams(); } GLCubemapDeviceProxy::~GLCubemapDeviceProxy() { if(TextureID > 0) { glDeleteTextures(1, &TextureID); } } void GLCubemapDeviceProxy::InitCubemapParams() { glGenTextures(1, &TextureID); glBindTexture(GL_TEXTURE_CUBE_MAP, TextureID); glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE); glBindTexture(GL_TEXTURE_CUBE_MAP, 0); } void GLCubemapDeviceProxy::SetContentHDR(const eCubemapSide side, const float* data) { ASSERTE(Width > 0 && Height > 0, "Invalid arguments!"); ASSERTE(TextureID > 0, "Texture is invalid!"); ASSERTE(data, "Data pointer is nullptr!"); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_CUBE_MAP, TextureID); glTexImage2D( GetEnumFromCubemapSide(side), 0, GL_RGB, (GLsizei)Width, (GLsizei)Height, 0, GL_RGB, GL_FLOAT, data); glGenerateMipmap(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_CUBE_MAP, 0); CHECK_GL_ERR(); } GLenum GLCubemapDeviceProxy::GetEnumFromCubemapSide(eCubemapSide type) { switch (type) { case eCubemapSide::RIGHT: return GL_TEXTURE_CUBE_MAP_POSITIVE_X; case eCubemapSide::LEFT: return GL_TEXTURE_CUBE_MAP_NEGATIVE_X; case eCubemapSide::TOP: return GL_TEXTURE_CUBE_MAP_POSITIVE_Y; case eCubemapSide::DOWN: return GL_TEXTURE_CUBE_MAP_NEGATIVE_Y; case eCubemapSide::BACK: return GL_TEXTURE_CUBE_MAP_POSITIVE_Z; case eCubemapSide::FRONT: return GL_TEXTURE_CUBE_MAP_NEGATIVE_Z; default: ASSERTE(false, "Invalid type!"); return -1; } }
29.84058
116
0.797475
PiotrMoscicki
b3fbd146a6d394ce2ac65f43958121ebe93f9216
2,058
cpp
C++
ArrhythmiaStudio/src/engine/rendering/ComputeShader.cpp
Reimnop/ArrhythmiaStudio
d8b63992d9d461a495b33f7e6dfef62607a4f152
[ "MIT" ]
6
2021-10-04T03:06:12.000Z
2022-02-14T09:32:59.000Z
ArrhythmiaStudio/src/engine/rendering/ComputeShader.cpp
Reimnop/ArrhythmiaStudio
d8b63992d9d461a495b33f7e6dfef62607a4f152
[ "MIT" ]
null
null
null
ArrhythmiaStudio/src/engine/rendering/ComputeShader.cpp
Reimnop/ArrhythmiaStudio
d8b63992d9d461a495b33f7e6dfef62607a4f152
[ "MIT" ]
1
2021-12-04T17:59:22.000Z
2021-12-04T17:59:22.000Z
#include "ComputeShader.h" #include <fstream> #include <sstream> #include <glad/glad.h> ComputeShader::ComputeShader(std::filesystem::path sourcePath) { char infoLogBuf[2048]; char uniformNameBuf[2048]; // Get source std::string source = readAllText(sourcePath); const char* sourcePtr = source.c_str(); int sourceLength = source.size(); // Compile shader uint32_t shader = glCreateShader(GL_COMPUTE_SHADER); glShaderSource(shader, 1, &sourcePtr, &sourceLength); glCompileShader(shader); // Detect compilation errors int vertCode; glGetShaderiv(shader, GL_COMPILE_STATUS, &vertCode); if (vertCode != GL_TRUE) { glGetShaderInfoLog(shader, sizeof(infoLogBuf), nullptr, infoLogBuf); throw std::runtime_error( "Error occurred whilst compiling Shader " + std::to_string(handle) + "\n\n" + infoLogBuf); } // Create program handle = glCreateProgram(); glAttachShader(handle, shader); glLinkProgram(handle); // Detect linking error int linkCode; glGetProgramiv(handle, GL_LINK_STATUS, &linkCode); if (linkCode != GL_TRUE) { throw std::runtime_error("Error occurred whilst linking Program " + std::to_string(handle)); } // Clean up glDetachShader(handle, shader); glDeleteShader(shader); // Get uniform locations int numberOfUniforms; glGetProgramiv(handle, GL_ACTIVE_UNIFORMS, &numberOfUniforms); for (int i = 0; i < numberOfUniforms; i++) { int length; int size; GLenum type; glGetActiveUniform(handle, i, sizeof(uniformNameBuf), &length, &size, &type, uniformNameBuf); int location = glGetUniformLocation(handle, uniformNameBuf); uniformLocations[uniformNameBuf] = location; } } ComputeShader::~ComputeShader() { glDeleteProgram(handle); } int ComputeShader::getAttribLocation(std::string attribName) { return uniformLocations[attribName]; } uint32_t ComputeShader::getHandle() const { return handle; } std::string ComputeShader::readAllText(std::filesystem::path path) { std::ifstream file(path); std::stringstream buffer; buffer << file.rdbuf(); file.close(); return buffer.str(); }
23.123596
95
0.740525
Reimnop
b3fd26f7b9288fa991e3b2c0fc65deef03a222fa
3,366
cpp
C++
Practica3/prodcons.cpp
JArandaIzquierdo/SistemasConcurrentesYDistribuidos
1d773458efecefa32b61ade42a1654679d515dc4
[ "Apache-2.0" ]
null
null
null
Practica3/prodcons.cpp
JArandaIzquierdo/SistemasConcurrentesYDistribuidos
1d773458efecefa32b61ade42a1654679d515dc4
[ "Apache-2.0" ]
null
null
null
Practica3/prodcons.cpp
JArandaIzquierdo/SistemasConcurrentesYDistribuidos
1d773458efecefa32b61ade42a1654679d515dc4
[ "Apache-2.0" ]
null
null
null
#include <mpi.h> #include <iostream> #include <math.h> #include <time.h> // incluye "time" #include <unistd.h> // incluye "usleep" #include <stdlib.h> // incluye "rand" y "srand" // --------------------------------------------------------------------- #define Productor 0 #define Buffer 1 #define Consumidor 2 #define ITERS 20 using namespace std; // --------------------------------------------------------------------- void productor() { for ( unsigned int i= 0 ; i < ITERS ; i++ ) { cout << "Productor produce valor " << i << endl << flush; // espera bloqueado durante un intervalo de tiempo aleatorio // (entre una décima de segundo y un segundo) usleep( 1000U * (100U+(rand()%900U)) ); // enviar valor MPI_Ssend( &i, 1, MPI_INT, Buffer, 0, MPI_COMM_WORLD ); } } // --------------------------------------------------------------------- void buffer() { int value , peticion ; MPI_Status status ; for ( unsigned int i = 0 ; i < ITERS ; i++ ) { MPI_Recv(&value, 1, MPI_INT, Productor, 0, MPI_COMM_WORLD, &status ); MPI_Recv(&peticion, 1, MPI_INT, Consumidor, 0, MPI_COMM_WORLD, &status ); cout << "Buffer recibe valor "<< value << " de Productor " << endl << flush; MPI_Ssend( &value, 1, MPI_INT, Consumidor, 0, MPI_COMM_WORLD); cout << "Buffer envía valor " << value << " a Consumidor " << endl << flush; } } // --------------------------------------------------------------------- void consumidor() { int value, peticion = 1 ; float raiz ; MPI_Status status ; for (unsigned int i=0;i<ITERS;i++) { MPI_Ssend(&peticion, 1, MPI_INT, Buffer, 0, MPI_COMM_WORLD); MPI_Recv(&value, 1, MPI_INT, Buffer, 0, MPI_COMM_WORLD,&status ); cout << "Consumidor recibe valor " << value << " de Buffer " << endl << flush ; // espera bloqueado durante un intervalo de tiempo aleatorio // (entre una décima de segundo y un segundo) usleep( 1000U * (100U+(rand()%900U)) ); // calcular raíz del valor recibido raiz = sqrt( value ); } } // --------------------------------------------------------------------- int main( int argc, char *argv[] ) { int rank , // identificador de proceso (comienza en 0) size ; // numero de procesos // inicializar MPI y leer identificador de proceso y número de procesos MPI_Init( &argc, &argv ); MPI_Comm_rank( MPI_COMM_WORLD, &rank ); MPI_Comm_size( MPI_COMM_WORLD, &size ); // inicializa la semilla aleatoria: srand ( time(NULL) ); // comprobar el número de procesos con el que el programa // ha sido puesto en marcha (debe ser 3) if ( size != 3 ) { cout << "El numero de procesos debe ser 3, pero es " << size << "." << endl << flush ; return 0; } // verificar el identificador de proceso (rank), y ejecutar la // operación apropiada a dicho identificador if ( rank == Productor ) productor(); else if ( rank == Buffer ) buffer(); else consumidor(); // al terminar el proceso, finalizar MPI MPI_Finalize( ); return 0; } // ---------------------------------------------------------------------
29.787611
92
0.501485
JArandaIzquierdo
b600d5f91b170f23522494a471170d54da0dbfda
8,614
cxx
C++
PWGJE/EMCALJetTasks/AliJetShape.cxx
wiechula/AliPhysics
6c5c45a5c985747ee82328d8fd59222b34529895
[ "BSD-3-Clause" ]
null
null
null
PWGJE/EMCALJetTasks/AliJetShape.cxx
wiechula/AliPhysics
6c5c45a5c985747ee82328d8fd59222b34529895
[ "BSD-3-Clause" ]
null
null
null
PWGJE/EMCALJetTasks/AliJetShape.cxx
wiechula/AliPhysics
6c5c45a5c985747ee82328d8fd59222b34529895
[ "BSD-3-Clause" ]
null
null
null
#include "AliJetShape.h" #include "TMath.h" #include "TMatrixD.h" #include "TMatrixDSym.h" #include "TMatrixDSymEigen.h" #include "TVector3.h" #include "TVector2.h" #include "AliFJWrapper.h" using namespace std; #ifdef FASTJET_VERSION //________________________________________________________________________ Double32_t AliJetShapeGRNum::result(const fastjet::PseudoJet &jet) const { if (!jet.has_constituents()) return 0; //AliFatal("Angular structure can only be applied on jets for which the constituents are known."); Double_t A = 0.; std::vector<fastjet::PseudoJet> constits = jet.constituents(); for(UInt_t ic = 0; ic < constits.size(); ++ic) { /* Int_t uid = constits[ic].user_index(); */ /* if (uid == -1) //skip ghost particle */ /* continue; */ for(UInt_t jc = ic+1; jc < constits.size(); ++jc) { /* Int_t uid = constits[jc].user_index(); */ /* if (uid == -1) //skip ghost particle */ /* continue; */ Double_t dphi = constits[ic].phi()-constits[jc].phi(); if(dphi<-1.*TMath::Pi()) dphi+=TMath::TwoPi(); if(dphi>TMath::Pi()) dphi-=TMath::TwoPi(); Double_t dr2 = (constits[ic].eta()-constits[jc].eta())*(constits[ic].eta()-constits[jc].eta()) + dphi*dphi; if(dr2>0.) { Double_t dr = TMath::Sqrt(dr2); Double_t x = fR-dr; //noisy function Double_t noise = TMath::Exp(-x*x/(2*fDRStep*fDRStep))/(TMath::Sqrt(2.*TMath::Pi())*fDRStep); A += constits[ic].perp()*constits[jc].perp()*dr2*noise; } } } return A; } Double32_t AliJetShapeGRDen::result(const fastjet::PseudoJet &jet) const { if (!jet.has_constituents()) return 0; //AliFatal("Angular structure can only be applied on jets for which the constituents are known."); Double_t A = 0.; std::vector<fastjet::PseudoJet> constits = jet.constituents(); for(UInt_t ic = 0; ic < constits.size(); ++ic) { /* Int_t uid = constits[ic].user_index(); */ /* if (uid == -1) //skip ghost particle */ /* continue; */ for(UInt_t jc = ic+1; jc < constits.size(); ++jc) { /* Int_t uid = constits[jc].user_index(); */ /* if (uid == -1) //skip ghost particle */ /* continue; */ Double_t dphi = constits[ic].phi()-constits[jc].phi(); if(dphi<-1.*TMath::Pi()) dphi+=TMath::TwoPi(); if(dphi>TMath::Pi()) dphi-=TMath::TwoPi(); Double_t dr2 = (constits[ic].eta()-constits[jc].eta())*(constits[ic].eta()-constits[jc].eta()) + dphi*dphi; if(dr2>0.) { Double_t dr = TMath::Sqrt(dr2); Double_t x = fR-dr; //error function Double_t erf = 0.5*(1.+TMath::Erf(x/(TMath::Sqrt(2.)*fDRStep))); A += constits[ic].perp()*constits[jc].perp()*dr2*erf; } } } return A; } Double32_t AliJetShapeAngularity::result(const fastjet::PseudoJet &jet) const { if (!jet.has_constituents()) return 0; Double_t den=0.; Double_t num = 0.; std::vector<fastjet::PseudoJet> constits = jet.constituents(); for(UInt_t ic = 0; ic < constits.size(); ++ic) { Double_t dphi = constits[ic].phi()-jet.phi(); if(dphi<-1.*TMath::Pi()) dphi+=TMath::TwoPi(); if(dphi>TMath::Pi()) dphi-=TMath::TwoPi(); Double_t dr2 = (constits[ic].eta()-jet.eta())*(constits[ic].eta()-jet.eta()) + dphi*dphi; Double_t dr = TMath::Sqrt(dr2); num=num+constits[ic].perp()*dr; den=den+constits[ic].perp(); } return num/den; } Double32_t AliJetShapepTD::result(const fastjet::PseudoJet &jet) const { if (!jet.has_constituents()) return 0; Double_t den=0; Double_t num = 0.; std::vector<fastjet::PseudoJet> constits = jet.constituents(); for(UInt_t ic = 0; ic < constits.size(); ++ic) { num=num+constits[ic].perp()*constits[ic].perp(); den=den+constits[ic].perp(); } return TMath::Sqrt(num)/den; } Double32_t AliJetShapeCircularity::result(const fastjet::PseudoJet &jet) const { if (!jet.has_constituents()) return 0; Double_t mxx = 0.; Double_t myy = 0.; Double_t mxy = 0.; int nc = 0; Double_t sump2 = 0.; Double_t pxjet=jet.px(); Double_t pyjet=jet.py(); Double_t pzjet=jet.pz(); //2 general normalized vectors perpendicular to the jet TVector3 ppJ1(pxjet, pyjet, pzjet); TVector3 ppJ3(- pxjet* pzjet, - pyjet * pzjet, pxjet * pxjet + pyjet * pyjet); ppJ3.SetMag(1.); TVector3 ppJ2(-pyjet, pxjet, 0); ppJ2.SetMag(1.); std::vector<fastjet::PseudoJet> constits = jet.constituents(); for(UInt_t ic = 0; ic < constits.size(); ++ic) { TVector3 pp(constits[ic].px(), constits[ic].py(), constits[ic].pz()); //local frame TVector3 pLong = pp.Dot(ppJ1) / ppJ1.Mag2() * ppJ1; TVector3 pPerp = pp - pLong; //projection onto the two perpendicular vectors defined above Float_t ppjX = pPerp.Dot(ppJ2); Float_t ppjY = pPerp.Dot(ppJ3); Float_t ppjT = TMath::Sqrt(ppjX * ppjX + ppjY * ppjY); if(ppjT<=0) return 0; mxx += (ppjX * ppjX / ppjT); myy += (ppjY * ppjY / ppjT); mxy += (ppjX * ppjY / ppjT); nc++; sump2 += ppjT; } if(nc<2) return 0; if(sump2==0) return 0; // Sphericity Matrix Double_t ele[4] = {mxx / sump2, mxy / sump2, mxy / sump2, myy / sump2}; TMatrixDSym m0(2,ele); // Find eigenvectors TMatrixDSymEigen m(m0); TVectorD eval(2); TMatrixD evecm = m.GetEigenVectors(); eval = m.GetEigenValues(); // Largest eigenvector int jev = 0; if (eval[0] < eval[1]) jev = 1; TVectorD evec0(2); // Principle axis evec0 = TMatrixDColumn(evecm, jev); Double_t compx=evec0[0]; Double_t compy=evec0[1]; TVector2 evec(compx, compy); Double_t circ=0; if(jev==1) circ=2*eval[0]; if(jev==0) circ=2*eval[1]; return circ; } Double32_t AliJetShapeSigma2::result(const fastjet::PseudoJet &jet) const { if (!jet.has_constituents()) return 0; Double_t mxx = 0.; Double_t myy = 0.; Double_t mxy = 0.; int nc = 0; Double_t sump2 = 0.; std::vector<fastjet::PseudoJet> constits = jet.constituents(); for(UInt_t ic = 0; ic < constits.size(); ++ic) { Double_t ppt=constits[ic].perp(); Double_t dphi = constits[ic].phi()-jet.phi(); if(dphi<-1.*TMath::Pi()) dphi+=TMath::TwoPi(); if(dphi>TMath::Pi()) dphi-=TMath::TwoPi(); Double_t deta = constits[ic].eta()-jet.eta(); mxx += ppt*ppt*deta*deta; myy += ppt*ppt*dphi*dphi; mxy -= ppt*ppt*deta*TMath::Abs(dphi); nc++; sump2 += ppt*ppt; } if(nc<2) return 0; if(sump2==0) return 0; // Sphericity Matrix Double_t ele[4] = {mxx , mxy, mxy, myy }; TMatrixDSym m0(2,ele); // Find eigenvectors TMatrixDSymEigen m(m0); TVectorD eval(2); TMatrixD evecm = m.GetEigenVectors(); eval = m.GetEigenValues(); // Largest eigenvector int jev = 0; if (eval[0] < eval[1]) jev = 1; TVectorD evec0(2); // Principle axis evec0 = TMatrixDColumn(evecm, jev); Double_t compx=evec0[0]; Double_t compy=evec0[1]; TVector2 evec(compx, compy); Double_t sigma2=0; if(jev==1) sigma2=TMath::Sqrt(TMath::Abs(eval[0])/sump2); if(jev==0) sigma2=TMath::Sqrt(TMath::Abs(eval[1])/sump2); return sigma2; } Double32_t AliJetShape1subjettiness_kt::result(const fastjet::PseudoJet &jet) const { if (!jet.has_constituents()) return 0; AliFJWrapper *fFastjetWrapper = new AliFJWrapper("FJWrapper", "FJWrapper"); Double32_t Result = fFastjetWrapper->AliFJWrapper::NSubjettinessDerivativeSub(1,0,0.2,1.0,0.4,jet,0); fFastjetWrapper->Clear(); delete fFastjetWrapper; return Result; } Double32_t AliJetShape2subjettiness_kt::result(const fastjet::PseudoJet &jet) const { if (!jet.has_constituents()) return 0; AliFJWrapper *fFastjetWrapper = new AliFJWrapper("FJWrapper", "FJWrapper"); Double32_t Result = fFastjetWrapper->AliFJWrapper::NSubjettinessDerivativeSub(2,0,0.2,1.0,0.4,jet,0); fFastjetWrapper->Clear(); delete fFastjetWrapper; return Result; } Double32_t AliJetShape3subjettiness_kt::result(const fastjet::PseudoJet &jet) const { if (!jet.has_constituents()) return 0; AliFJWrapper *fFastjetWrapper = new AliFJWrapper("FJWrapper", "FJWrapper"); Double32_t Result = fFastjetWrapper->AliFJWrapper::NSubjettinessDerivativeSub(3,0,0.2,1.0,0.4,jet,0); fFastjetWrapper->Clear(); delete fFastjetWrapper; return Result; } Double32_t AliJetShapeOpeningAngle_kt::result(const fastjet::PseudoJet &jet) const { if (!jet.has_constituents()) return 0; AliFJWrapper *fFastjetWrapper = new AliFJWrapper("FJWrapper", "FJWrapper"); Double32_t Result = fFastjetWrapper->AliFJWrapper::NSubjettinessDerivativeSub(2,0,0.2,1.0,0.4,jet,1); fFastjetWrapper->Clear(); delete fFastjetWrapper; return Result; } #endif
32.752852
113
0.648015
wiechula
b60194fe3eb6c2ef2c8c9628984ac3668f1b5d58
1,794
cpp
C++
2015/day25/p1/main.cpp
jbaldwin/adventofcode2019
bdc333330dd5e36458a49f0b7cd64d462c9988c7
[ "MIT" ]
null
null
null
2015/day25/p1/main.cpp
jbaldwin/adventofcode2019
bdc333330dd5e36458a49f0b7cd64d462c9988c7
[ "MIT" ]
null
null
null
2015/day25/p1/main.cpp
jbaldwin/adventofcode2019
bdc333330dd5e36458a49f0b7cd64d462c9988c7
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> #include <string> #include <map> int main(int argc, char* argv[]) { constexpr int64_t row = 2978; constexpr int64_t col = 3083; constexpr int64_t first_code = 20151125; constexpr int64_t multiply_by = 252533; constexpr int64_t modulo_by = 33554393; // Pattern for generating the grid! // [ 1, 1, 1] // [ 2, 2, 1] // [ 3, 1, 2] // [ 4, 3, 1] // [ 5, 2, 2] // [ 6, 1, 3] // [ 7, 4, 1] // [ 8, 3, 2] // [ 9, 2, 3] // [10, 1, 4] // [11, 5, 1] // [12, 4, 2] // [13, 3, 3] // [14, 2, 4] // [15, 1, 5] std::map<int64_t, std::map<int64_t, int64_t>> grid{}; // counter is the value stored at each x,y coordinate int64_t counter{first_code}; // i is the number of items in this diagonal row int64_t i{1}; while(true) { // Continue populating until the row/col pair is available. if(auto found_row = grid.find(row); found_row != grid.end()) { if(auto found_col = found_row->second.find(col); found_col != found_row->second.end()) { break; } } int64_t x = i; int64_t y = 1; // Count x down to 1 and y up to i to populate the diagonal row. while(x >= 1) { grid[x][y] = counter; x--; y++; auto value = counter * multiply_by; value %= modulo_by; counter = value; } ++i; } // for(const auto& [x, row] : grid) // { // for(const auto& [y, value] : row) // { // std::cout << value << " "; // } // std::cout << "\n"; // } std::cout << grid[row][col] << "\n"; return 0; }
22.148148
98
0.466555
jbaldwin
b60518650d053c23fba87f18af599d53c5782c1b
3,026
cpp
C++
src/qpid/framing/ExecutionResultBody.cpp
gcsideal/debian-qpid-cpp
e4d034036f29408f940805f5505ae62ce89650cc
[ "Apache-2.0" ]
null
null
null
src/qpid/framing/ExecutionResultBody.cpp
gcsideal/debian-qpid-cpp
e4d034036f29408f940805f5505ae62ce89650cc
[ "Apache-2.0" ]
null
null
null
src/qpid/framing/ExecutionResultBody.cpp
gcsideal/debian-qpid-cpp
e4d034036f29408f940805f5505ae62ce89650cc
[ "Apache-2.0" ]
null
null
null
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ /// /// This file was automatically generated from the AMQP specification. /// Do not edit. /// #include "qpid/framing/ExecutionResultBody.h" #include "qpid/framing/Buffer.h" using namespace qpid::framing; void ExecutionResultBody::setCommandId(const SequenceNumber& _commandId) { commandId = _commandId; flags |= (1 << 8); } SequenceNumber ExecutionResultBody::getCommandId() const { return commandId; } bool ExecutionResultBody::hasCommandId() const { return flags & (1 << 8); } void ExecutionResultBody::clearCommandIdFlag() { flags &= ~(1 << 8); } void ExecutionResultBody::setValue(const std::string& _value) { value = _value; flags |= (1 << 9); } const std::string& ExecutionResultBody::getValue() const { return value; } bool ExecutionResultBody::hasValue() const { return flags & (1 << 9); } void ExecutionResultBody::clearValueFlag() { flags &= ~(1 << 9); } void ExecutionResultBody::encodeStructBody(Buffer& buffer) const { encodeHeader(buffer); buffer.putShort(flags); if (flags & (1 << 8)) commandId.encode(buffer); if (flags & (1 << 9)) buffer.putLongString(value); } void ExecutionResultBody::encode(Buffer& buffer) const { encodeStructBody(buffer); } void ExecutionResultBody::decodeStructBody(Buffer& buffer, uint32_t /*size*/) { decodeHeader(buffer); flags = buffer.getShort(); if (flags & (1 << 8)) commandId.decode(buffer); if (flags & (1 << 9)) buffer.getLongString(value); } void ExecutionResultBody::decode(Buffer& buffer, uint32_t /*size*/) { decodeStructBody(buffer); } uint32_t ExecutionResultBody::bodySize() const { uint32_t total = 0; total += headerSize(); total += 2; if (flags & (1 << 8)) total += commandId.encodedSize(); if (flags & (1 << 9)) total += 4 + value.size(); return total; } uint32_t ExecutionResultBody::encodedSize() const { uint32_t total = bodySize(); return total; } void ExecutionResultBody::print(std::ostream& out) const { out << "{ExecutionResultBody: "; if (flags & (1 << 8)) out << "command-id=" << commandId << "; "; if (flags & (1 << 9)) out << "value=" << value << "; "; out << "}"; }
28.819048
78
0.674157
gcsideal
b608c99031ce1661c470b10d7f08725e8fb4e8a9
683
cpp
C++
competitive_programming/programming_contests/uri/kiloman.cpp
LeandroTk/Algorithms
569ed68eba3eeff902f8078992099c28ce4d7cd6
[ "MIT" ]
205
2018-12-01T17:49:49.000Z
2021-12-22T07:02:27.000Z
competitive_programming/programming_contests/uri/kiloman.cpp
LeandroTk/Algorithms
569ed68eba3eeff902f8078992099c28ce4d7cd6
[ "MIT" ]
2
2020-01-01T16:34:29.000Z
2020-04-26T19:11:13.000Z
competitive_programming/programming_contests/uri/kiloman.cpp
LeandroTk/Algorithms
569ed68eba3eeff902f8078992099c28ce4d7cd6
[ "MIT" ]
50
2018-11-28T20:51:36.000Z
2021-11-29T04:08:25.000Z
// https://www.urionlinejudge.com.br/judge/en/problems/view/1250 #include <iostream> #include <vector> #include <string> using namespace std; bool is_hit(vector<int> &v, string js, int ind) { if (js[ind] == 'S' && (v[ind] == 1 || v[ind] == 2)) return true; if (js[ind] == 'J' && v[ind] > 2) return true; return false; } int main() { int n, x, temp; string js; vector<int> v; cin >> n; while (n--) { int counter = 0; cin >> x; for (int i = 0; i < x; i++) { cin >> temp; v.push_back(temp); } cin >> js; for (int ind = 0; ind < x; ind++) if (is_hit(v, js, ind)) counter++; cout << counter << endl; v.clear(); } return 0; }
15.522727
65
0.535871
LeandroTk
b608ee41a49d252159d0f8d61fd93b12abdbb96e
5,913
cpp
C++
src/render/ui_renderer.cpp
MrPepperoni/Reaping2-1
4ffef3cca1145ddc06ca87d2968c7b0ffd3ba3fd
[ "MIT" ]
3
2015-02-22T20:34:28.000Z
2020-03-04T08:55:25.000Z
src/render/ui_renderer.cpp
MrPepperoni/Reaping2-1
4ffef3cca1145ddc06ca87d2968c7b0ffd3ba3fd
[ "MIT" ]
22
2015-12-13T16:29:40.000Z
2017-03-04T15:45:44.000Z
src/render/ui_renderer.cpp
Reaping2/Reaping2
0d4c988c99413e50cc474f6206cf64176eeec95d
[ "MIT" ]
14
2015-11-23T21:25:09.000Z
2020-07-17T17:03:23.000Z
#include "i_render.h" #include "ui_renderer.h" #include "main/window.h" #include "engine/engine.h" #include "uimodel_repo.h" #include "shader_manager.h" #include "uimodel.h" #include "font.h" #include "counter.h" #include "platform/game_clock.h" namespace { typedef std::vector<glm::vec2> Positions_t; typedef std::vector<glm::vec4> Colors_t; bool getNextTextId( UiVertices_t::const_iterator& i, UiVertices_t::const_iterator e, Positions_t& Positions, Colors_t& Colors, Positions_t& TexCoords, render::RenderBatch& batch ) { if( i == e ) { return false; } UiVertex const& Vert = *i; Positions.push_back( Vert.Pos ); TexCoords.push_back( Vert.TexCoord ); Colors.push_back( Vert.Color ); batch.TexId = Vert.TexId; ++i; return true; } bool IsSubtreeHidden( Widget const& wdg ) { for( Widget const* w = wdg.Parent(); NULL != w; w = w->Parent() ) { Widget::Prop const& p = w->operator()( Widget::PT_SubtreeHidden ); if( ( p.GetType() == Widget::Prop::T_Int || p.GetType() == Widget::Prop::T_Double ) && p.operator int32_t() ) { return true; } } return false; } } void UiRenderer::Draw( Root const& UiRoot, const glm::mat4& projMatrix ) { /* for(Widget::const_iterator i=UiRoot.begin(),e=UiRoot.end();i!=e;++i) { static UiModelRepo const& UiModels(UiModelRepo::Get()); Widget const& Wdg=*i; if(!(int32_t)Wdg(Widget::PT_Visible)) continue; UiModel const& Model=UiModels(Wdg.GetId()); Model.Draw(Wdg); }*/ UiVertices_t Vertices; Vertices.reserve( mPrevVertices.size() ); UiVertexInserter_t Inserter( Vertices ); for( Widget::const_iterator i = UiRoot.begin(), e = UiRoot.end(); i != e; ++i ) { static UiModelRepo const& UiModels( UiModelRepo::Get() ); Widget const& Wdg = *i; if( ( 0 == ( int32_t )Wdg( Widget::PT_Visible ) ) || IsSubtreeHidden( Wdg ) ) { continue; } UiModel const& Model = UiModels( Wdg.GetId() ); Model.CollectVertices( Wdg, Inserter ); } size_t const CurSize = Vertices.size(); if ( CurSize == 0 ) { return; } // collect start / count values Positions_t Positions; Positions_t TexCoords; Positions.reserve( CurSize ); TexCoords.reserve( CurSize ); Colors_t Colors; Colors.reserve( CurSize ); // todo: check and track changes UiVertices_t::const_iterator i = Vertices.begin(); render::Counts_t const& Counts = render::count( std::bind( &getNextTextId, std::ref( i ), Vertices.end(), std::ref( Positions ), std::ref( Colors ), std::ref( TexCoords ), std::placeholders::_1 ) ); mVAO.Bind(); if( CurSize != mPrevVertices.size() ) { size_t TotalSize = CurSize * ( sizeof( glm::vec4 ) + 2 * sizeof( glm::vec2 ) ); glBufferData( GL_ARRAY_BUFFER, TotalSize, NULL, GL_DYNAMIC_DRAW ); } size_t CurrentOffset = 0; size_t CurrentSize = CurSize * sizeof( glm::vec2 ); GLuint CurrentAttribIndex = 0; glBufferSubData( GL_ARRAY_BUFFER, CurrentOffset, CurrentSize, &Positions[0] ); glEnableVertexAttribArray( CurrentAttribIndex ); size_t const PosIndex = CurrentOffset; ++CurrentAttribIndex; CurrentOffset += CurrentSize; CurrentSize = CurSize * sizeof( glm::vec2 ); glBufferSubData( GL_ARRAY_BUFFER, CurrentOffset, CurrentSize, &TexCoords[0] ); glEnableVertexAttribArray( CurrentAttribIndex ); size_t const TexIndex = CurrentOffset; ++CurrentAttribIndex; CurrentOffset += CurrentSize; CurrentSize = CurSize * sizeof( glm::vec4 ); glBufferSubData( GL_ARRAY_BUFFER, CurrentOffset, CurrentSize, &Colors[0] ); glEnableVertexAttribArray( CurrentAttribIndex ); size_t const ColorIndex = CurrentOffset; ShaderManager& ShaderMgr( ShaderManager::Get() ); static int32_t def( AutoId( "ui" ) ); ShaderMgr.ActivateShader( def ); ShaderMgr.UploadData( "time", GLfloat( platform::Clock::Now() ) ); int w, h; mWindow->GetWindowSize( w, h ); ShaderMgr.UploadData( "resolution", glm::vec2( w, h ) ); ShaderMgr.UploadData( "uiProjection", projMatrix ); glActiveTexture( GL_TEXTURE0 + 4 ); for( render::Counts_t::const_iterator i = Counts.begin(), e = Counts.end(); i != e; ++i ) { render::CountByTexId const& Part = *i; CurrentAttribIndex = 0; glVertexAttribPointer( CurrentAttribIndex, 2, GL_FLOAT, GL_FALSE, 0, ( GLvoid* )( PosIndex + sizeof( glm::vec2 )*Part.Start ) ); ++CurrentAttribIndex; glVertexAttribPointer( CurrentAttribIndex, 2, GL_FLOAT, GL_FALSE, 0, ( GLvoid* )( TexIndex + sizeof( glm::vec2 )*Part.Start ) ); ++CurrentAttribIndex; glVertexAttribPointer( CurrentAttribIndex, 4, GL_FLOAT, GL_FALSE, 0, ( GLvoid* )( ColorIndex + sizeof( glm::vec4 )*Part.Start ) ); if( Part.Batch.TexId != -1 ) { glBindTexture( GL_TEXTURE_2D, Part.Batch.TexId ); } glDrawArrays( GL_TRIANGLES, 0, Part.Count ); } mVAO.Unbind(); // store current match using std::swap; swap( mPrevVertices, Vertices ); } void UiRenderer::Init() { mVAO.Init(); ShaderManager& ShaderMgr( ShaderManager::Get() ); static int32_t def( AutoId( "ui" ) ); ShaderMgr.ActivateShader( def ); glActiveTexture( GL_TEXTURE0 + 4 ); glBindTexture( GL_TEXTURE_2D, Font::Get().GetTexId() ); ShaderMgr.UploadData( "uiTexture", GLuint( 4 ) ); glActiveTexture( GL_TEXTURE0 ); mWindow = engine::Engine::Get().GetSystem<engine::WindowSystem>(); } UiRenderer::UiRenderer() { Init(); }
34.377907
138
0.61424
MrPepperoni
b60a5042dcce244695b69aa8b1d3334bcef2896e
7,841
cpp
C++
ExploringScaleSymmetry/Chapter9/ch9_figure2.cpp
TGlad/ExploringScaleSymmetry
25b2dae0279a0ac26f6bae2277d3b76a1cda8b04
[ "MIT" ]
null
null
null
ExploringScaleSymmetry/Chapter9/ch9_figure2.cpp
TGlad/ExploringScaleSymmetry
25b2dae0279a0ac26f6bae2277d3b76a1cda8b04
[ "MIT" ]
null
null
null
ExploringScaleSymmetry/Chapter9/ch9_figure2.cpp
TGlad/ExploringScaleSymmetry
25b2dae0279a0ac26f6bae2277d3b76a1cda8b04
[ "MIT" ]
null
null
null
// Thomas Lowe, 2020. // Calculates the fractal content for a limit set over multiple scales, and plots it as a log-log graph, to demonstrate its oscillation. // This also plots the limit set itself and the expanded limit set at every scale. Use a breakpoint in this look to see each expanded set. #include "stdafx.h" #define STB_IMAGE_WRITE_IMPLEMENTATION #include "imagewrite.h" #include <sstream> #include <fstream> #define DRAW_LIMIT_SET #define DRAW_EXPANDED_SET // Note: this overwrites the same image file at each expansion radius. Use a breakpoint to make copies of these images. #define DRAW_LOGLOG_PLOT namespace { struct Shape { Vector2d pos; Vector2d xAxis, yAxis; double nodeWidth; vector<Shape, aligned_allocator<Shape> > children; void split(int index); void draw(ofstream &svg, const Vector2d &origin, const Vector2d &xAx, const Vector2d &yAx); public: EIGEN_MAKE_ALIGNED_OPERATOR_NEW }; } static int width = 1024; static int height = 750; static Vector2d offset(500.0, 600.0); static Vector2d minVec(1e10, 1e10); static Vector2d maxVec(-1e10, -1e10); static vector<Vector2d> leaves; // Note that the structure is drawn as multiple pentagons. That is because the base shape used is a pentagon. // Of course we could just draw points for the limit set, but the original substitution rule is with pentagons so we keep that here. void Shape::draw(ofstream &svg, const Vector2d &origin, const Vector2d &xAx, const Vector2d &yAx) { Vector2d minV(-1.26, 0.62); Vector2d maxV(1.36, 1.85); double mult = (maxV[0] - minV[0]); Vector2d start = origin + xAx*pos[0] + yAx*pos[1]; Vector2d x = xAx*xAxis[0] + yAx*xAxis[1]; Vector2d y = xAx*yAxis[0] + yAx*yAxis[1]; double length = nodeWidth * 0.4; if (children.empty()) { Vector2d corners[] = { start - x*nodeWidth*0.5, start + x*nodeWidth*0.5, start + x*0.5*nodeWidth + y*length, start + y*(1.5*length), start - x*0.5*nodeWidth + y*length }; leaves.push_back(corners[2]); minVec[0] = min(minVec[0], corners[2][0]); minVec[1] = min(minVec[1], corners[2][1]); maxVec[0] = max(maxVec[0], corners[2][0]); maxVec[1] = max(maxVec[1], corners[2][1]); for (int i = 0; i < 5; i++) corners[i] = minV + (double)width * (corners[i] - minV) / mult; svg << "<path d = \"M " << corners[4][0] << " " << corners[4][1]; for (int i = 0; i < 5; i++) svg << " L " << corners[i][0] << " " << corners[i][1]; svg << "\" fill=\"black\" stroke-width = \"1\" stroke=\"black\" />\n"; } Vector2d p = start + y*length; for (auto &c : children) c.draw(svg, p, x, y); } static void saveSVGLeaves(const string &fileName) { static ofstream svg; svg.open(fileName.c_str()); svg << "<svg width = \"" << width << "\" height = \"" << height << "\" xmlns = \"http://www.w3.org/2000/svg\">" << endl; double gscale = 0.9*(double)height; for (auto &p : leaves) svg << "<circle cx = \"" << gscale*(p[0] + offset[0]) << "\" cy = \"" << (double)height - gscale*(p[1] + offset[1]) << "\" r = \"2\" stroke = \"black\" stroke-width = \"1\" fill = \"black\" />" << endl; svg << "</svg>" << endl; svg.close(); } static void saveSVG(const string &fileName, Shape &tree) { static ofstream svg; svg.open(fileName.c_str()); svg << "<svg width = \"" << width << "\" height = \"" << height << "\" xmlns = \"http://www.w3.org/2000/svg\">" << endl; tree.draw(svg, Vector2d(0, 0), Vector2d(1, 0), Vector2d(0, 1)); svg << "</svg>" << endl; svg.close(); } static void drawGraph(const string &fileName, vector<double> &graph, double yscale, double minY) { static ofstream svg; svg.open(fileName.c_str()); svg << "<svg width = \"" << width << "\" height = \"" << height << "\" xmlns = \"http://www.w3.org/2000/svg\">" << endl; double xscale = 0.9*(double)width; svg << "<path d = \"M " << 0 << " " << (double)height - yscale*(graph[0] - minY); for (int i = 1; i < (int)graph.size(); i++) svg << " L " << xscale * (double)i / (double)graph.size() << " " << (double)height - yscale*(graph[i] - minY); svg << "\" fill = \"none\" stroke-width = \"2\" stroke=\"black\" />\n"; svg << "</svg>" << endl; svg.close(); } // The substitution rule is applied recursively here void Shape::split(int index) { if (index == 0) { return; } Shape child1, child2; double scale = 0.5; double ang = -0.5; child1.pos = nodeWidth*Vector2d(-0.4, 0.5); child1.yAxis = Vector2d(sin(ang), cos(ang)); child1.xAxis = Vector2d(cos(ang), -sin(ang)); child1.nodeWidth = nodeWidth * scale; ang = 0.7; child2.pos = nodeWidth*Vector2d(0.5, 0.35); child2.yAxis = Vector2d(sin(ang), cos(ang)); child2.xAxis = Vector2d(cos(ang), -sin(ang)); child2.nodeWidth = nodeWidth * scale; children.push_back(child1); children.push_back(child2); for (auto &c : children) c.split(index - 1); } static void putpixel(vector<BYTE> &out, const Vector2i &pos, int shade) { if (pos[0] < 0 || pos[0] >= width || pos[1] < 0 || pos[1] >= height) return; int ind = 3 * (pos[0] + width*pos[1]); out[ind + 0] = out[ind + 1] = out[ind + 2] = shade; } int chapter9Figure2() { Shape base; base.xAxis = Vector2d(1, 0); base.yAxis = Vector2d(0, 1); base.nodeWidth = 1.0; base.pos = Vector2d(0, 0.05); base.split(12); // the argument is the number of iterations of the substitution // draw the set #if defined DRAW_LIMIT_SET saveSVG("substitutionRuleLimitSet.svg", base); #endif cout << "min coordinate: " << minVec.transpose() << ", max coordinate: " << maxVec.transpose() << endl; vector<BYTE> out(width*height * 3); // .bmp pixel buffer vector<double> graph; double c = 0; for (double r = 0.25; r > 1.0 / 8.0; r /= 1.03) { memset(&out[0], 255, out.size() * sizeof(BYTE)); // background is grey double w = 2e-3; double m = 1.0 / r; double minX = minVec[0] - r; double minY = minVec[1] - r; double maxX = maxVec[0] + r; double maxY = maxVec[1] + r; double radius2 = r*r; double Nmink = 0; Vector2d di(sin(22.5*pi / 180.0), cos(22.5*pi / 180.0)); for (double x = minX; x < maxX; x += w) { for (double y = minY; y < maxY; y += w) { Vector2d p(x, y); for (auto &leaf : leaves) { if ((p - leaf).squaredNorm() < radius2) { Nmink++; double W = 2.0*w; putpixel(out, Vector2i(0.01 + (x - minX) / W, 0.01 + (y - minY) / W), 192); break; } } } } for (auto &leaf : leaves) { double W = 2.0*w; for (int i = -1; i < 2; i++) for (int j = -1; j < 2; j++) putpixel(out, Vector2i((double)i + 0.01 + (leaf[0] - minX) / W, (double) j + 0.01 + (leaf[1] - minY) / W), 0); } Nmink *= w*w; // now a volume Nmink *= m*m; // now a Minkowski number double d = 1.0; c = Nmink / pow(m, d); cout << "radius: " << r << ", c: " << c << endl; cout << "log(Nmink): " << log(Nmink) << ", log m: " << log(m) << ", ratio: " << log(Nmink) / log(m) << endl; graph.push_back(c); #if defined DRAW_EXPANDED_SET stbi_write_png("substitutionRuleExpandedSet.png", width, height, 3, &out[0], 3 * width); #endif } #if defined DRAW_LOGLOG_PLOT double dif = graph.back() - graph[0]; // The content doesn't perfectly match for this approximate calculation due to insufficient processing time, so we shear slightly to correct the curve. for (int i = 0; i < (int)graph.size(); i++) graph[i] -= dif * (double)i / (double)(graph.size() - 1); cout << "dif " << dif << ", " << graph[0] << ", " << graph.back() << endl; graph.insert(graph.end(), graph.begin(), graph.end()); double yscale = 2.0*(double)height; double minY = 9.6; drawGraph("substitutionRuleLogLogGraph.svg", graph, yscale, minY); #endif return 0; }
35.004464
206
0.593929
TGlad
b60a58e8480c3728b1a52904796d106364be9060
22,480
cpp
C++
src/ants.cpp
Segfaultt/Ant-Wars-HD
a913af070519e8215c8acae8c8683db28e1df046
[ "MIT" ]
null
null
null
src/ants.cpp
Segfaultt/Ant-Wars-HD
a913af070519e8215c8acae8c8683db28e1df046
[ "MIT" ]
null
null
null
src/ants.cpp
Segfaultt/Ant-Wars-HD
a913af070519e8215c8acae8c8683db28e1df046
[ "MIT" ]
null
null
null
#include <math.h> #include "black_hole.h" #define PI_OVER_180 0.017453293 #define ONE_EIGHTY_OVER_PI 57.29578 #define PYTHAG(a, b) sqrt(pow(a, 2) + pow(b, 2)) #define ANT_REPEL_FORCE 1 int sign(auto x) { if (x < 0) return -1; else return 1; } //=====ANT===== ant::ant(ant_type type_, int starting_x, int starting_y) { x = starting_x; y = starting_y; type = type_; bar_health = NULL; bar_stamina = NULL; reset(); //ai stuff state = AGGRESSIVE; srand(seed++); inteligence = rand()%15 + 1; srand(seed++); right_bias = rand()%24-12; srand(seed++); if (x > SCREEN_WIDTH/2) { bearing = 270; angle = 180; } else { bearing = 90; angle = 0; } } ant::~ant() { for (auto *i : holes) delete i; for (auto *i : grease) delete i; for (auto *i : child) delete i; if (tesla_bolt != NULL) { delete tesla_bolt; tesla_bolt = NULL; } if (bar_health != NULL) { delete bar_health; bar_health = NULL; } if (bar_stamina != NULL) { delete bar_stamina; bar_stamina = NULL; } } void ant::set_other_ants(std::vector<ant *> other_ants_) { other_ants = other_ants_; } void ant::move(direction dir) { switch (dir) { case FORWARDS: if (guitar > 0) { x += grease_effect * speed * 0.3 * cos(angle * PI_OVER_180); y -= grease_effect * speed * 0.3 * sin(angle * PI_OVER_180); } else { x += grease_effect * speed * cos(angle * PI_OVER_180); y -= grease_effect * speed * sin(angle * PI_OVER_180); } break; case BACKWARDS: if (guitar > 0) { x -= grease_effect * speed * 0.3 * cos(angle * PI_OVER_180) * 0.8; y += grease_effect * speed * 0.3 * sin(angle * PI_OVER_180) * 0.8; } else { x -= grease_effect * speed * cos(angle * PI_OVER_180) * 0.8; y += grease_effect * speed * sin(angle * PI_OVER_180) * 0.8; } break; case LEFT: if (type == MATT && angular_momentum < 10) { angular_momentum += 1.5; } else { bearing -= turn_speed; if (bearing < 0) bearing += 360; angle = 450 - bearing; if (angle >= 360) angle -= 360; } break; case RIGHT: if (type == MATT && angular_momentum > -10) { angular_momentum -= 1.5; } else { bearing += turn_speed; if (bearing >= 360) bearing -= 360; angle = 450 - bearing; if (angle >= 360) angle -= 360; } break; } } void ant::render() { bar_health->render(x + 50, y - 32, health); bar_stamina->render(x + 80, y - 20, stamina); if (flip_timer > 0) flip_timer--; if (nip_out_timer > 0) { nip_texture.render(45 * cos(angle * PI_OVER_180) + x + 25, -45 * sin(angle * PI_OVER_180) + y + 25, bearing); } if (nip_out_timer >= -TICKS_PER_FRAME/2) nip_out_timer--; if (type == LUCA) { for (black_hole *i : holes) { int pos = 0; i->render(); if (!i->is_alive()) { i->~black_hole(); holes.erase(holes.begin() + pos); } pos++; } } if (type == YA_BOY && tesla_bolt != NULL && tesla_target != NULL) { tesla_bolt->tick(tesla_target->get_x() + 50, tesla_target->get_y() + 50); if (!tesla_bolt->is_alive()) { //damage tesla_target->damage(19); //clean up delete tesla_bolt; tesla_bolt = NULL; tesla_target = NULL; } } if (laser_on > 0) { double x_gradient = cos(angle * PI_OVER_180); double y_gradient = sin(angle * PI_OVER_180); thickLineRGBA(renderer, 45 * x_gradient + x + 50, -45 * y_gradient + y + 50, (SCREEN_WIDTH + SCREEN_HEIGHT) * x_gradient + x + 50, -1 *(SCREEN_WIDTH + SCREEN_HEIGHT) * y_gradient + y + 50, 9, 0x97, 0x00, 0x00, 0xff); //check if hit for (ant *i : other_ants) { std::vector<int> p = {i->get_x() - x, y - i->get_y()}; double lambda = p[0]*cos(angle * PI_OVER_180) + p[1]*sin(angle * PI_OVER_180); if (lambda >= 0 && 2500 >= pow(p[0], 2) + pow(p[1], 2) - pow(lambda, 2)) { i->damage(5); //push targets double magnitude = PYTHAG(x - i->get_x(), y - i->get_y()); double x_component_unit_vector = (x - i->get_x()) / magnitude; double y_component_unit_vector = (y - i->get_y()) / magnitude; const double push_force = -3; i->apply_force(push_force * x_component_unit_vector, push_force * y_component_unit_vector); } laser_on--; } } if (type == WEEB && tenticles_out > 0) { tenticle_texture.render(80 * cos(angle * PI_OVER_180) + x, -80 * sin(angle * PI_OVER_180) + y, bearing); double angle_to_target, angle_difference, y_component, x_component; for (ant *i : other_ants) { x_component = x - i->get_x(); y_component = -1 * (y - i->get_y()); angle_to_target = atan(y_component/x_component) * ONE_EIGHTY_OVER_PI; if (x_component < 0) angle_to_target += 180; if (x_component > 0 && y_component < 0) angle_to_target += 360; angle_difference = angle - angle_to_target + 180; if (angle_difference > 180) angle_difference = angle_difference - 360; if (abs(angle_difference) < 40 && PYTHAG(x_component, y_component) < 155) { i->damage(10); //push targets double magnitude = PYTHAG(x - i->get_x(), y - i->get_y()); double x_component_unit_vector = (x - i->get_x()) / magnitude; double y_component_unit_vector = (y - i->get_y()) / magnitude; const double push_force = -7; i->apply_force(push_force * x_component_unit_vector, push_force * y_component_unit_vector); } } tenticles_out--; } if (type == SQUID && squid_tenticles_out > 0) { tenticle_texture.render(-80 * cos(angle * PI_OVER_180) + x, 80 * sin(angle * PI_OVER_180) + y, bearing + 180); double angle_to_target, angle_difference, y_component, x_component; for (ant *i : other_ants) { x_component = x - i->get_x(); y_component = -1 * (y - i->get_y()); angle_to_target = atan(y_component/x_component) * ONE_EIGHTY_OVER_PI; if (x_component < 0) angle_to_target += 180; if (x_component > 0 && y_component < 0) angle_to_target += 360; angle_difference = angle - angle_to_target; if (angle_difference > 180) angle_difference = angle_difference - 360; if (abs(angle_difference) < 40 && PYTHAG(x_component, y_component) < 155) { i->damage(10); //push targets double magnitude = PYTHAG(x - i->get_x(), y - i->get_y()); double x_component_unit_vector = (x - i->get_x()) / magnitude; double y_component_unit_vector = (y - i->get_y()) / magnitude; const double push_force = -7; i->apply_force(push_force * x_component_unit_vector, push_force * y_component_unit_vector); } } apply_force(7 * cos(angle * PI_OVER_180), -7 * sin(angle * PI_OVER_180)); } if (squid_tenticles_out > -20) squid_tenticles_out--; sprite.render(x, y, bearing); if (type == HIPSTER) { if (guitar > 0 && stamina > 0 && health <= 100) { guitar--; guitar_texture.render(45 * cos(angle * PI_OVER_180) + x + 25, -45 * sin(angle * PI_OVER_180) + y + 25, bearing); damage(-1); stamina -= 2; } else if (guitar > 0) { guitar = 0; } } if (type == ARC && arc_turn > 0) { if (arc_left) { move(LEFT); move(LEFT); move(LEFT); } else { move(RIGHT); move(RIGHT); move(RIGHT); } move(FORWARDS); move(FORWARDS); arc_turn--; } if (type == QUEEN) { int index = 0; for (ant *i : child) { ant *target = NULL; double smallest_distance = 12345; for (ant *ants : other_ants) if (smallest_distance > PYTHAG(ants->get_x() - x, ants->get_y() - y)) { smallest_distance = PYTHAG(ants->get_x() - x, ants->get_y() - y); target = ants; } if (smallest_distance != 12345) { i->ai(target); i->render(); i->apply_physics(); } //kill dead children if (!i->is_alive()) { for (ant *j : other_ants) { j->remove_other_ants(i); } child.erase(child.begin() + index); } index++; } } } void ant::apply_force(double x_component, double y_component) { velocity[0] += 10*x_component/mass; velocity[1] += 10*y_component/mass; } void ant::apply_physics() { //cap velocity /*const double velocity_cap = 50; if (velocity[0] > velocity_cap) velocity[0] = velocity_cap; if (velocity[0] < -velocity_cap) velocity[0] = -velocity_cap; if (velocity[1] > velocity_cap) velocity[1] = velocity_cap; if (velocity[1] < -velocity_cap) velocity[1] = -velocity_cap;*/ //apply velocity x += velocity[0]; y += velocity[1]; //wrap position const int out_of_bounds_border = -30; /*if (x + 50 > SCREEN_WIDTH + out_of_bounds_border) x = -out_of_bounds_border - 50; if (x + 50 < -out_of_bounds_border) x = SCREEN_WIDTH + out_of_bounds_border - 50; if (y + 50 < -out_of_bounds_border) y = SCREEN_HEIGHT + out_of_bounds_border - 50; if (y + 50 > SCREEN_HEIGHT + out_of_bounds_border) y = -out_of_bounds_border - 50; //cap position if (x + 50 > SCREEN_WIDTH + out_of_bounds_border) x = SCREEN_WIDTH + out_of_bounds_border - 50; if (x + 50 < -out_of_bounds_border) x = -out_of_bounds_border - 50; if (y + 50 < -out_of_bounds_border) y = -out_of_bounds_border - 50; if (y + 50 > SCREEN_HEIGHT + out_of_bounds_border) y = SCREEN_HEIGHT + out_of_bounds_border - 50; */ //apply angular momentum bearing -= angular_momentum; if (bearing < 0) bearing += 360; angle = 450 - bearing; if (angle >= 360) angle -= 360; //friction/air resistance double drag = 180/(200+sqrt(mass)*PYTHAG(velocity[0], velocity[1])); velocity[0] *= drag; velocity[1] *= drag; if (abs(angular_momentum) < 0.0001) angular_momentum = 0; else angular_momentum += abs(angular_momentum)/angular_momentum * -0.6 / mass; //ants repel double distance; for (ant *i : other_ants) { distance = sqrt(pow(i->get_x() - x, 2) + pow(i->get_y() - y, 2)); if (distance < 50 && distance != 0) { velocity[0] -= ANT_REPEL_FORCE * (i->get_x() - x)/distance; velocity[1] -= ANT_REPEL_FORCE * (i->get_y() - y)/distance; } } if (stamina <= 100 - stamina_regen) {//stamina regen cap stamina += stamina_regen * grease_effect; } //black hole child physics double x_component, y_component, rotation; for (black_hole *i : holes) { //pull other ants for (ant *each_ant : other_ants) { x_component = 0;//force from black hole passed by reference y_component = 0; i->pull_ants(each_ant->get_x(), each_ant->get_y(), each_ant->get_mass(), x_component, y_component, rotation); each_ant->apply_force(x_component, y_component); each_ant->apply_rotational_force(rotation); } } //apply grease if (type == GREASY_BOY) { for (ant *target_ant : other_ants) { bool in_grease = false; for (grease_trap *i : grease) if (i->tick(target_ant->get_x() + 50, target_ant->get_y() + 50)) in_grease = true; target_ant->set_grease_effect(in_grease); } bool in_grease = false; for (grease_trap *i : grease) if (i->tick(x + 50, y + 50)) in_grease = true; if (in_grease) { grease_effect = 1.5; damage(-0.2); } else { grease_effect = 1; } } //slowly die if (type == ANTDO) { damage(0.1); } } int ant::get_x() { return x; } int ant::get_y() { return y; } double ant::get_mass() { return mass; } double ant::damage(double damage) { if (damage > 0) { if (type == YA_BOY) damage *= 1.5; if (type == MOONBOY) damage *= 0.5; if (type == WEEB) damage *= 1.6; } if (damage > 0 | health - damage <= 100) { health -= damage; non_edge_damage += damage; if (type != MATT && type != SQUID) mass -= damage/150; mass = std::max(10.0, mass); } if (health < 0) { alive = false; } return damage; } bool ant::is_alive() { return alive; } void ant::check_edge() { if (x + 50 > SCREEN_WIDTH | x + 50< 0 | y + 50 > SCREEN_HEIGHT | y + 50 < 0) { non_edge_damage -= damage(0.5); } } void ant::ability() { switch (type) { case LUCA: if (stamina > 75 && health > 35) { black_hole *hole = new black_hole(x, y, angle); holes.push_back(hole); stamina -= 75; damage(35); } break; case YA_BOY: tesla(); break; case CSS_BAD: if (stamina > 60 && laser_on <= 0) { laser_on = TICKS_PER_FRAME/2; apply_force(-20 * cos(angle * PI_OVER_180), 20 * sin(angle * PI_OVER_180)); stamina -= 60; } break; case HIPSTER: if (stamina > 0 && guitar == 0) { guitar = TICKS_PER_FRAME; } break; case ARC: if (stamina >= 5 && arc_turn == 0) { stamina -= 5; arc_turn = 180/(turn_speed*3); srand(seed++); arc_left = rand()%2; } break; case GREASY_BOY: if (stamina >= 70) { stamina -= 70; grease.push_back(new grease_trap(x + sprite.get_width()/2, y + sprite.get_height()/2)); } break; case WEEB: if (stamina >= 60) { stamina -= 60; tenticles_out = TICKS_PER_FRAME/2; } break; case ANTDO: if (stamina >= 70) { stamina -= 70; srand(seed++); ant *switcher_ant = other_ants[0]; double transfer_health = switcher_ant->get_health(); //go through the standard damage funtion for mass switcher_ant->damage(transfer_health - health); damage(health - transfer_health); } break; case QUEEN: if (stamina >= 53& health > 20 && child.size() < 3) { damage(20); stamina -= 53; srand(seed++); child.push_back(new ant(BOT, 45 * cos(angle * PI_OVER_180) + x + 25, -45 * sin(angle * PI_OVER_180) + y + 25)); child[child.size() - 1]->set_other_ants(other_ants); for (ant *i : other_ants) { i->add_other_ants(child[child.size() - 1]); } } break; case SQUID: if (stamina >= 15 && squid_tenticles_out <= -10) { stamina -= 15; squid_tenticles_out = TICKS_PER_FRAME/6; } break; } } void ant::nip() { const double stamina_take = 20; if (stamina >= stamina_take && nip_out_timer < -TICKS_PER_FRAME/2) { stamina -= stamina_take; int nip_pos[2] = {45 * cos(angle * PI_OVER_180) + x + 25, -45 * sin(angle * PI_OVER_180) + y + 25}; double distance = 0; nip_out_timer = TICKS_PER_FRAME/2;//0.5 seconds for (ant *i : other_ants) { distance = sqrt(pow(nip_pos[0] - i->get_x() - 25, 2) + pow(nip_pos[1] - i->get_y() - 25, 2)); if (distance < 50) { i->damage(nip_damage * grease_effect); //push targets double magnitude = PYTHAG(x - i->get_x(), y - i->get_y()); double x_component_unit_vector = (x - i->get_x()) / magnitude; double y_component_unit_vector = (y - i->get_y()) / magnitude; const double push_force = (-30 - stamina); i->apply_force(push_force * x_component_unit_vector + velocity[0], push_force * y_component_unit_vector + velocity[1]); } } } } void ant::tesla() { const int cost_coefficient = 10; tesla_target = NULL; double shortest_distance = 999999; for (ant *i : other_ants) { double distance = sqrt(pow(x - i->get_x(), 2) + pow(y - i->get_y(), 2)); if (distance < shortest_distance) { shortest_distance = distance; tesla_target = i; } } if (stamina >= shortest_distance/cost_coefficient + 10 && tesla_bolt == NULL) { stamina -= shortest_distance/cost_coefficient + 10; delete tesla_bolt; tesla_bolt = new electric_bolt(x + 50, y + 50); //apply attraction double magnitude = PYTHAG(x - tesla_target->get_x(), y - tesla_target->get_y()); double x_component_unit_vector = (x - tesla_target->get_x()) / magnitude; double y_component_unit_vector = (y - tesla_target->get_y()) / magnitude; const double pull_force = 8; tesla_target->apply_force(pull_force * x_component_unit_vector, pull_force * y_component_unit_vector); apply_force(-pull_force * x_component_unit_vector, -pull_force * y_component_unit_vector); } } double ant::get_angle() { return angle; } double ant::get_health() { return health; } double ant::get_stamina() { return stamina; } void ant::flip() { if (stamina >= 30 && flip_timer == 0) { stamina -= 30; bearing += 180; if (bearing > 360) bearing -= 360; angle = 450 - bearing; flip_timer = TICKS_PER_FRAME/2; } } void ant::set_grease_effect(bool on) { if (type != GREASY_BOY) { if (on) { grease_effect = 0.5; damage(0.2); } else { grease_effect = 1; } } } void ant::change_speed(double value) { speed += value; } void ant::apply_rotational_force(double angular_force) { angular_momentum += angular_force; } void ant::set_position(int new_x, int new_y) { x = new_x; y = new_y; if (x > SCREEN_WIDTH/2) { bearing = 270; angle = 180; } else { bearing = 90; angle = 0; } } void ant::add_other_ants(ant *other_ants_) { other_ants.push_back(other_ants_); } void ant::remove_other_ants(ant *other_ants_) { for (int i = 0; i < other_ants.size(); i++) { if (other_ants[i] == other_ants_) other_ants.erase(other_ants.begin() + i); } } void ant::ai(ant *target) { //maths double x_component = target->get_x() - get_x(); double y_component = -1 * (target->get_y() - get_y()); double angle_to_target = atan(y_component/x_component) * ONE_EIGHTY_OVER_PI; if (x_component < 0) angle_to_target += 180; if (x_component > 0 && y_component < 0) angle_to_target += 360; double angle_difference = get_angle() - angle_to_target; if (angle_difference > 180) angle_difference = angle_difference - 360; double distance = sqrt(pow(x_component, 2) + pow(y_component, 2)); double stamina_ratio = get_stamina() * 100 / target->get_stamina(); //apply behaviour switch (state) { case AGGRESSIVE: //turning if (angle_difference < -15 + right_bias) move(LEFT); if (angle_difference > 15 + right_bias) move(RIGHT); //move forwards if (abs(angle_difference) < 30 && distance > 60) move(FORWARDS); srand(seed++); if (abs(angle_difference) < 80 && distance < 70 && rand()%9 == 0) nip(); break; case MALFUNCTION: { srand(seed++); int turn = rand()%3; if (turn == 0) move(LEFT); if (turn == 1) move(RIGHT); srand(seed++); if (rand()%3 != 1) move(FORWARDS); srand(seed++); if (rand()%20 == 0) nip(); srand(seed++); if (rand()%15 == 0) state = past_state; break; } case FLEE: if (distance < 500) { if (angle_difference > -5) move(LEFT); if (angle_difference < 5) move(RIGHT); move(FORWARDS); } break; case OFF_SCREEN: { //maths double x_component = SCREEN_WIDTH/2 - get_x(); double y_component = -1 * (SCREEN_HEIGHT/2 - get_y()); double angle_to_target = atan(y_component/x_component) * ONE_EIGHTY_OVER_PI; if (x_component < 0) angle_to_target += 180; if (x_component > 0 && y_component < 0) angle_to_target += 360; double angle_difference = get_angle() - angle_to_target; if (angle_difference > 180) angle_difference = angle_difference - 360; //turning if (angle_difference < -5) move(LEFT); if (angle_difference > 5) move(RIGHT); //move forwards if (abs(angle_difference) < 30) move(FORWARDS); if (abs(get_x() - SCREEN_WIDTH/2) < SCREEN_WIDTH/2 - 100 && abs(get_y() - SCREEN_HEIGHT/2) < SCREEN_HEIGHT/2 - 100) state = past_state; } } //behaviour checks srand(seed++); if (get_x() - 50 < 0 | get_x() + 50 > SCREEN_WIDTH | get_y() - 50 < 0 | get_y() + 50 > SCREEN_HEIGHT) { past_state = state; state = OFF_SCREEN; } else if (rand()%inteligence == 0) { past_state = state; state = MALFUNCTION; } else if (stamina_ratio < 20) state = FLEE; else state = AGGRESSIVE; } void ant::reset() { angular_momentum = 0; tenticles_out = 0; grease_effect = 1; for (auto *i : grease) delete i; grease.clear(); for (auto *i : holes) delete i; holes.clear(); arc_turn = 0; flip_timer = 0; nip_out_timer = 0; nip_damage = 40; laser_on = 0; guitar = 0; alive = true; mass = 1; velocity[0] = 0; velocity[1] = 0; speed = 8; turn_speed = 5; health = 100; non_edge_damage = 0; stamina = 0; stamina_regen = 0.22; nip_texture.load_texture((std::string)"res/" + (std::string)RES_PACK + (std::string)"/nip.png"); tesla_bolt = NULL; tesla_target = NULL; squid_tenticles_out = 0; if (bar_health != NULL) { delete bar_health; bar_health = NULL; } if (bar_stamina != NULL) { delete bar_stamina; bar_stamina = NULL; } bar_health = new bar(90, 10); bar_stamina = new bar(60, 7); switch (type) { case YA_BOY: sprite.load_texture((std::string)"res/" + (std::string)RES_PACK + (std::string)"/ya_boy.png"); break; case LUCA: sprite.load_texture((std::string)"res/" + (std::string)RES_PACK + (std::string)"/luca.png"); break; case CSS_BAD: sprite.load_texture((std::string)"res/" + (std::string)RES_PACK + (std::string)"/jeff.png"); break; case HIPSTER: guitar_texture.load_texture((std::string)"res/" + (std::string)RES_PACK + (std::string)"/guitar.png"); sprite.load_texture((std::string)"res/" + (std::string)RES_PACK + (std::string)"/hipster.png"); speed *= 1.2; mass *= 0.5; break; case BOT: sprite.load_texture((std::string)"res/" + (std::string)RES_PACK + (std::string)"/bot.png"); speed *= 0.8; turn_speed *= 0.8; health *= 0.5; nip_damage *= 0.8; stamina_regen *= 0.5; break; case MOONBOY: sprite.load_texture((std::string)"res/" + (std::string)RES_PACK + (std::string)"/moonboy.png"); nip_damage *= 1.5; mass *= 2; break; case ARC: sprite.load_texture((std::string)"res/" + (std::string)RES_PACK + (std::string)"/the_arc.png"); speed *= 1.5; break; case GREASY_BOY: sprite.load_texture((std::string)"res/" + (std::string)RES_PACK + (std::string)"/greasy_boy.png"); speed *= 0.7; nip_damage *= 0.8; mass *= 0.6; break; case WEEB: sprite.load_texture((std::string)"res/" + (std::string)RES_PACK + (std::string)"/weeb.png"); tenticle_texture.load_texture((std::string)"res/" + (std::string)RES_PACK + (std::string)"/tenticles.png"); speed *= 1.2; turn_speed *= 1.5; break; case MATT: sprite.load_texture((std::string)"res/" + (std::string)RES_PACK + (std::string)"/fidget_spinner.png"); speed *= 1.4; break; case ANTDO: sprite.load_texture((std::string)"res/" + (std::string)RES_PACK + (std::string)"/antdo.png"); break; case SQUID: sprite.load_texture((std::string)"res/" + (std::string)RES_PACK + (std::string)"/squid.png"); tenticle_texture.load_texture((std::string)"res/" + (std::string)RES_PACK + (std::string)"/tenticles.png"); speed = 0; stamina_regen *= 3; break; case QUEEN: sprite.load_texture((std::string)"res/" + (std::string)RES_PACK + (std::string)"/queen.png"); nip_damage *= 0.6; break; }; } ant_type ant::get_type() { return type; } double ant::get_damaged() { return non_edge_damage; }
24.172043
218
0.625801
Segfaultt
b60a90fd109abcc6dd7e20f9fd76e0ab74c8738d
904
cpp
C++
tests/LineFitting/LineFitting.cpp
argon24/robest
e91fe1f0ec94ae6fcf81a246ad4433b3371ddaa0
[ "MIT" ]
6
2018-01-14T23:51:02.000Z
2021-12-02T08:42:20.000Z
tests/LineFitting/LineFitting.cpp
argon24/robest
e91fe1f0ec94ae6fcf81a246ad4433b3371ddaa0
[ "MIT" ]
1
2018-11-10T09:56:57.000Z
2018-11-17T23:17:39.000Z
tests/LineFitting/LineFitting.cpp
argon24/robest
e91fe1f0ec94ae6fcf81a246ad4433b3371ddaa0
[ "MIT" ]
5
2018-11-09T20:12:35.000Z
2021-09-24T09:41:47.000Z
#include "LineFitting.hpp" LineFittingProblem::LineFittingProblem() { setNbParams(2); setNbMinSamples(2); } LineFittingProblem::~LineFittingProblem() { } void LineFittingProblem::setData(std::vector<double> & x, std::vector<double> & y) { points.clear(); for (int i = 0; i < x.size(); i++){ Point2d point; point.x=x[i]; point.y=y[i]; points.push_back(point); } } inline double LineFittingProblem::estimErrorForSample(int i) { //distance point to line const Point2d & p = points[i]; return std::fabs(a*p.x - p.y + b) / sqrt(a*a + 1); // distance line-point } inline void LineFittingProblem::estimModelFromSamples(const std::vector<int> & samplesIdx) { //line from two points Point2d & P = points[samplesIdx[0]]; Point2d & V = points[samplesIdx[1]]; a = (V.y-P.y)/(V.x-P.x); b = P.y -a * P.x; }
14.819672
90
0.607301
argon24
b60b7041157ce16da22f9fe08bf84a682dbfc029
1,830
cpp
C++
Days 081 - 090/Day 82/ReadNFromRead7.cpp
LucidSigma/Daily-Coding-Problems
21dc8f7e615edd535d7beb1f5d0e41dd3b4bcc1a
[ "MIT" ]
null
null
null
Days 081 - 090/Day 82/ReadNFromRead7.cpp
LucidSigma/Daily-Coding-Problems
21dc8f7e615edd535d7beb1f5d0e41dd3b4bcc1a
[ "MIT" ]
null
null
null
Days 081 - 090/Day 82/ReadNFromRead7.cpp
LucidSigma/Daily-Coding-Problems
21dc8f7e615edd535d7beb1f5d0e41dd3b4bcc1a
[ "MIT" ]
null
null
null
#include <fstream> #include <iostream> #include <sstream> #include <stdexcept> #include <string> class FileReader { private: mutable unsigned int offset = 0; const std::string contents; std::string nBuffer = ""; public: explicit FileReader(const std::string& filename) : contents(GetFileContents(filename)) { } std::string Read7() const noexcept { if (offset >= contents.length()) { return ""; } std::string sevenLetterString = contents.substr(offset, 7); offset += 7; return sevenLetterString; } std::string ReadN(unsigned int n) noexcept { while (nBuffer.length() < n) { std::string sevenLengthString = Read7(); if (sevenLengthString.empty()) { break; } nBuffer += sevenLengthString; } std::string nLengthString = nBuffer.substr(0, n); if (nBuffer.length() >= n) { nBuffer = nBuffer.substr(n); } else { nBuffer = nBuffer.substr(nBuffer.length()); } return nLengthString; } private: std::string GetFileContents(const std::string& filename) const { std::ifstream file(filename); if (!file.is_open()) { throw std::invalid_argument("File " + filename + " could not be found/opened."); } std::ostringstream fileReader; fileReader << file.rdbuf(); file.close(); return fileReader.str(); } }; int main(int argc, char* argv[]) { FileReader readerA("input.txt"); std::cout << readerA.Read7() << "\n"; std::cout << readerA.Read7() << "\n"; std::cout << readerA.Read7() << "\n"; FileReader readerB("input.txt"); std::cout << readerB.ReadN(8) << "\n"; std::cout << readerB.ReadN(8) << "\n"; std::cout << readerB.ReadN(8) << "\n"; FileReader readerC("input.txt"); std::cout << readerC.ReadN(2) << "\n"; std::cout << readerC.ReadN(2) << "\n"; std::cout << readerC.ReadN(2) << "\n"; std::cin.get(); return 0; }
18.3
83
0.631694
LucidSigma
b612d969a96841023213950ddd99d44d5f3ad978
343
cpp
C++
Samples/Win7Samples/multimedia/windowsmediaservices9/eventnotification/StdAfx.cpp
windows-development/Windows-classic-samples
96f883e4c900948e39660ec14a200a5164a3c7b7
[ "MIT" ]
8
2017-04-30T17:38:27.000Z
2021-11-29T00:59:03.000Z
Samples/Win7Samples/multimedia/windowsmediaservices9/eventnotification/StdAfx.cpp
TomeSq/Windows-classic-samples
96f883e4c900948e39660ec14a200a5164a3c7b7
[ "MIT" ]
null
null
null
Samples/Win7Samples/multimedia/windowsmediaservices9/eventnotification/StdAfx.cpp
TomeSq/Windows-classic-samples
96f883e4c900948e39660ec14a200a5164a3c7b7
[ "MIT" ]
2
2020-08-11T13:21:49.000Z
2021-09-01T10:41:51.000Z
//+------------------------------------------------------------------------- // // Microsoft Windows Media Technologies // Copyright (C) Microsoft Corporation. All rights reserved. // // File: StdAfx.cpp // // Contents: // //-------------------------------------------------------------------------- #include "stdafx.h"
26.384615
77
0.335277
windows-development
b61789691f0cd73e4fd1cee7782b1361822ae577
1,672
cpp
C++
Engine/Src/SFEngine/SceneGraph/SFSceneNodeComponent.cpp
blue3k/StormForge
1557e699a673ae9adcc8f987868139f601ec0887
[ "Apache-2.0" ]
1
2020-06-20T07:35:25.000Z
2020-06-20T07:35:25.000Z
Engine/Src/SFEngine/SceneGraph/SFSceneNodeComponent.cpp
blue3k/StormForge
1557e699a673ae9adcc8f987868139f601ec0887
[ "Apache-2.0" ]
null
null
null
Engine/Src/SFEngine/SceneGraph/SFSceneNodeComponent.cpp
blue3k/StormForge
1557e699a673ae9adcc8f987868139f601ec0887
[ "Apache-2.0" ]
null
null
null
//////////////////////////////////////////////////////////////////////////////// // // CopyRight (c) 2018 Kyungkun Ko // // Author : KyungKun Ko // // Description : SceneNodeComponent // // //////////////////////////////////////////////////////////////////////////////// #include "SFEnginePCH.h" #include "Multithread/SFThread.h" #include "Util/SFStrUtil.h" #include "EngineObject/SFEngineObject.h" #include "SceneGraph/SFSceneNodeComponent.h" #include "SceneGraph/SFSceneNode.h" #include "Util/SFTimeUtil.h" #include "Service/SFEngineService.h" namespace SF { template class SharedPointerT<SceneNodeComponent>; //////////////////////////////////////////////////////////////////////////////////////// // // SceneNodeComponent class - interface for task operation // // Constructor SceneNodeComponent::SceneNodeComponent(IHeap& heap, const StringCrc64& name) : Object(&heap, name) { } SceneNodeComponent::~SceneNodeComponent() { } void SceneNodeComponent::Dispose() { Object::Dispose(); } // Change owner void SceneNodeComponent::ChangeOwner(SceneNode* newOwner) { if (m_Owner != nullptr) m_Owner->RemoveComponent(this); m_Owner = newOwner; if (m_Owner != nullptr) m_Owner->AddComponent(this); } Result SceneNodeComponent::CopyProperties(const SceneCloneContext& cloneFlags, SceneNodeComponent* pSrcComponent) { if (pSrcComponent == nullptr) return ResultCode::INVALID_POINTER; SetName(pSrcComponent->GetName()); m_UpdateTickMode = pSrcComponent->m_UpdateTickMode; return ResultCode::SUCCESS; } }; // namespace SF
20.641975
115
0.584928
blue3k
b6195a4ffceeafb4b6755e10b45e327b6df04827
2,393
cpp
C++
utils/Protect.cpp
intel/hwc-
3617c208959bd7c865021dd0d0bc69a94c804f99
[ "Apache-2.0" ]
null
null
null
utils/Protect.cpp
intel/hwc-
3617c208959bd7c865021dd0d0bc69a94c804f99
[ "Apache-2.0" ]
null
null
null
utils/Protect.cpp
intel/hwc-
3617c208959bd7c865021dd0d0bc69a94c804f99
[ "Apache-2.0" ]
null
null
null
/* // Copyright (c) 2017 Intel Corporation // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. */ #include <cstdio> #include <cstdlib> #include <cstring> #include "HwcServiceApi.h" using namespace std; int main(int argc, char** argv) { // Argument parameters bool bEnable = false; bool bDisableAll = false; int sessionID = 0; int instanceID = 0; int argsRequired = 2; if (argc >= 2) { if (strcmp(argv[1], "on") == 0) { bEnable = true; argsRequired = 4; } else if (strcmp(argv[1], "off") == 0) { bEnable = false; argsRequired = 3; } else if (strcmp(argv[1], "alloff") == 0) { bDisableAll = true; } if ( argc > 2 ) { sessionID = atoi( argv[2] ); } if ( argc > 3 ) { instanceID = atoi( argv[3] ); } } if (argc < argsRequired) { printf("Usage: %s on {session} {instance}\n", argv[0]); printf("Usage: %s off {session}\n", argv[0]); printf("Usage: %s alloff\n", argv[0]); return 1; } HWCSHANDLE hwcs = HwcService_Connect(); if(hwcs == NULL) { printf("Could not connect to service\n"); return 1; } else if (bDisableAll) { printf("disableAllEncryptedSessions( )\n" ); HwcService_Video_DisableAllEncryptedSessions( hwcs ); } else if (bEnable) { printf("enableEncryptedSession( Session:%d, Instance:%d )\n", sessionID, instanceID ); HwcService_Video_EnableEncryptedSession( hwcs, sessionID, instanceID ); } else { printf("disableEncryptedSession( Session:%d )\n", sessionID ); HwcService_Video_DisableEncryptedSession( hwcs, sessionID ); } HwcService_Disconnect(hwcs); return 0; }
25.457447
94
0.582532
intel
b61e9902d7a4453d5a1eb97e1501828c802d4769
1,286
cc
C++
src/plugin/graphics/GL4/src/loaders/rendertarget/glsurface.cc
bugengine/BugEngine
1b3831d494ee06b0bd74a8227c939dd774b91226
[ "BSD-3-Clause" ]
4
2015-05-13T16:28:36.000Z
2017-05-24T15:34:14.000Z
src/plugin/graphics/GL4/src/loaders/rendertarget/glsurface.cc
bugengine/BugEngine
1b3831d494ee06b0bd74a8227c939dd774b91226
[ "BSD-3-Clause" ]
null
null
null
src/plugin/graphics/GL4/src/loaders/rendertarget/glsurface.cc
bugengine/BugEngine
1b3831d494ee06b0bd74a8227c939dd774b91226
[ "BSD-3-Clause" ]
1
2017-03-21T08:28:07.000Z
2017-03-21T08:28:07.000Z
/* BugEngine <bugengine.devel@gmail.com> see LICENSE for detail */ #include <bugengine/plugin.graphics.GL4/stdafx.h> #include <bugengine/plugin.graphics.3d/rendertarget/rendertarget.script.hh> #include <bugengine/plugin.graphics.GL4/glrenderer.hh> #include <extensions.hh> #include <loaders/rendertarget/glsurface.hh> namespace BugEngine { namespace OpenGL { GLSurface::GLSurface(weak< const RenderSurfaceDescription > surfaceDescription, weak< GLRenderer > renderer) : IRenderTarget(surfaceDescription, renderer) { } GLSurface::~GLSurface() { } void GLSurface::load(weak< const Resource::Description > /*surfaceDescription*/) { } void GLSurface::unload() { } void GLSurface::begin(ClearMode clear) const { setCurrent(); if(clear == IRenderTarget::Clear) { glClearColor(0.0f, 0.0f, 0.0f, 1.0f); glClear(GL_COLOR_BUFFER_BIT); } } void GLSurface::end(PresentMode presentMode) const { glFlush(); if(presentMode == Present) { present(); } clearCurrent(); } void GLSurface::setCurrent() const { } void GLSurface::clearCurrent() const { } void GLSurface::present() const { } }} // namespace BugEngine::OpenGL
20.412698
81
0.650078
bugengine
b61f7fd19c34211db20d5c6332ef23a8150ddfdf
6,562
cpp
C++
Vitis-AI-Library/posedetect/test/test_pose_detect_batch.cpp
dendisuhubdy/Vitis-AI
524f65224c52314155dafc011d488ed30e458fcb
[ "Apache-2.0" ]
3
2020-10-29T15:00:30.000Z
2021-10-21T08:09:34.000Z
Vitis-AI-Library/posedetect/test/test_pose_detect_batch.cpp
dendisuhubdy/Vitis-AI
524f65224c52314155dafc011d488ed30e458fcb
[ "Apache-2.0" ]
20
2020-10-31T03:19:03.000Z
2020-11-02T18:59:49.000Z
Vitis-AI-Library/posedetect/test/test_pose_detect_batch.cpp
dendisuhubdy/Vitis-AI
524f65224c52314155dafc011d488ed30e458fcb
[ "Apache-2.0" ]
9
2020-10-14T02:04:10.000Z
2020-12-01T08:23:02.000Z
/* * Copyright 2019 Xilinx Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <iostream> #include <memory> #include <opencv2/core.hpp> #include <opencv2/highgui.hpp> #include <opencv2/imgproc.hpp> #include <vitis/ai/posedetect.hpp> #include <vitis/ai/profiling.hpp> using namespace std; static void DrawLines(cv::Mat &img, const vitis::ai::PoseDetectResult::Pose14Pt &results); int main(int argc, char *argv[]) { if (argc < 3) { std::cerr << "usage :" << argv[0] << " <model_name>" << " <image_url> [<image_url> ...]" << std::endl; abort(); } auto det = vitis::ai::PoseDetect::create(argv[1]); std::vector<cv::Mat> arg_input_images; std::vector<std::string> arg_input_images_names; for (auto i = 2; i < argc; i++) { cv::Mat img = cv::imread(argv[i]); if (img.empty()) { std::cout << "Cannot load " << argv[i] << std::endl; continue; } arg_input_images.push_back(img); arg_input_images_names.push_back(argv[i]); } if (arg_input_images.empty()) { std::cerr << "No image load success!" << std::endl; abort(); } std::vector<cv::Mat> batch_images; std::vector<std::string> batch_image_names; auto batch = det->get_input_batch(); for (auto batch_idx = 0u; batch_idx < batch; batch_idx++) { batch_images.push_back(arg_input_images[batch_idx % arg_input_images.size()]); batch_image_names.push_back(arg_input_images_names[batch_idx % arg_input_images.size()]); } auto results = det->run(batch_images); int i = 0; for (const auto &result : results) { auto image = batch_images[i]; std::cout << "result: " << i << std::endl; std::cout << "(" << result.pose14pt.right_shoulder.x << "," << result.pose14pt.right_shoulder.y << ")" << std::endl; std::cout << "(" << result.pose14pt.right_elbow.x << "," << result.pose14pt.right_elbow.y << ")" << std::endl; std::cout << "(" << result.pose14pt.right_wrist.x << "," << result.pose14pt.right_wrist.y << ")" << std::endl; std::cout << "(" << result.pose14pt.left_shoulder.x << "," << result.pose14pt.left_shoulder.y << ")" << std::endl; std::cout << "(" << result.pose14pt.left_elbow.x << "," << result.pose14pt.left_elbow.y << ")" << std::endl; std::cout << "(" << result.pose14pt.left_wrist.x << "," << result.pose14pt.left_wrist.y << ")" << std::endl; std::cout << "(" << result.pose14pt.right_hip.x << "," << result.pose14pt.right_hip.y << ")" << std::endl; std::cout << "(" << result.pose14pt.right_knee.x << "," << result.pose14pt.right_knee.y << ")" << std::endl; std::cout << "(" << result.pose14pt.right_ankle.x << "," << result.pose14pt.right_ankle.y << ")" << std::endl; std::cout << "(" << result.pose14pt.left_hip.x << "," << result.pose14pt.left_hip.y << ")" << std::endl; std::cout << "(" << result.pose14pt.left_knee.x << "," << result.pose14pt.left_knee.y << ")" << std::endl; std::cout << "(" << result.pose14pt.left_ankle.x << "," << result.pose14pt.left_ankle.y << ")" << std::endl; std::cout << "(" << result.pose14pt.head.x << "," << result.pose14pt.head.y << ")" << std::endl; std::cout << "(" << result.pose14pt.neck.x << "," << result.pose14pt.neck.y << ")" << std::endl; DrawLines(image, result.pose14pt); i++; } return 0; } using namespace cv; static inline void DrawLine(Mat &img, Point2f point1, Point2f point2, Scalar colour, int thickness, float scale_w, float scale_h) { if ((point1.x * img.cols > scale_w || point1.y * img.rows > scale_h) && (point2.x * img.cols > scale_w || point2.y * img.rows > scale_h)) cv::line(img, Point2f(point1.x * img.cols, point1.y * img.rows), Point2f(point2.x * img.cols, point2.y * img.rows), colour, thickness); } static void DrawLines(Mat &img, const vitis::ai::PoseDetectResult::Pose14Pt &results) { float scale_w = 1; float scale_h = 1; float mark = 5.f; float mark_w = mark * scale_w; float mark_h = mark * scale_h; std::vector<Point2f> pois(14); for (size_t i = 0; i < pois.size(); ++i) { pois[i].x = ((float *)&results)[i * 2] * img.cols; pois[i].y = ((float *)&results)[i * 2 + 1] * img.rows; } for (size_t i = 0; i < pois.size(); ++i) { circle(img, pois[i], 3, Scalar::all(255)); } DrawLine(img, results.right_shoulder, results.right_elbow, Scalar(255, 0, 0), 2, mark_w, mark_h); DrawLine(img, results.right_elbow, results.right_wrist, Scalar(255, 0, 0), 2, mark_w, mark_h); DrawLine(img, results.right_hip, results.right_knee, Scalar(255, 0, 0), 2, mark_w, mark_h); DrawLine(img, results.right_knee, results.right_ankle, Scalar(255, 0, 0), 2, mark_w, mark_h); DrawLine(img, results.left_shoulder, results.left_elbow, Scalar(0, 0, 255), 2, mark_w, mark_h); DrawLine(img, results.left_elbow, results.left_wrist, Scalar(0, 0, 255), 2, mark_w, mark_h); DrawLine(img, results.left_hip, results.left_knee, Scalar(0, 0, 255), 2, mark_w, mark_h); DrawLine(img, results.left_knee, results.left_ankle, Scalar(0, 0, 255), 2, mark_w, mark_h); DrawLine(img, results.head, results.neck, Scalar(0, 255, 255), 2, mark_w, mark_h); DrawLine(img, results.right_shoulder, results.neck, Scalar(0, 255, 255), 2, mark_w, mark_h); DrawLine(img, results.left_shoulder, results.neck, Scalar(0, 255, 255), 2, mark_w, mark_h); DrawLine(img, results.right_shoulder, results.right_hip, Scalar(0, 255, 255), 2, mark_w, mark_h); DrawLine(img, results.left_shoulder, results.left_hip, Scalar(0, 255, 255), 2, mark_w, mark_h); DrawLine(img, results.right_hip, results.left_hip, Scalar(0, 255, 255), 2, mark_w, mark_h); }
40.506173
93
0.598903
dendisuhubdy
b61f9785ebdbe3cb6707a99214fee530358c8c00
159
cpp
C++
rpg/MenuUse.cpp
NowakKamil30/rpg_console
2f58d6326582583fac7b68185b4b74dbcf240aca
[ "Apache-2.0" ]
1
2021-06-22T14:10:10.000Z
2021-06-22T14:10:10.000Z
rpg/MenuUse.cpp
NowakKamil30/rpg_console
2f58d6326582583fac7b68185b4b74dbcf240aca
[ "Apache-2.0" ]
null
null
null
rpg/MenuUse.cpp
NowakKamil30/rpg_console
2f58d6326582583fac7b68185b4b74dbcf240aca
[ "Apache-2.0" ]
null
null
null
#include "MenuUse.h" MenuUse::MenuUse(Menu* menu) { this->menu = menu; } MenuUse::~MenuUse() { } Heroes* MenuUse::showMenu() { return menu->showMenu(); }
9.9375
28
0.641509
NowakKamil30
b625bbda1dd1a0bac9be1941a22bcfa1898db72c
3,289
hpp
C++
src/catkin_ws/src/modrob_workstation/workstation/include/workstation.hpp
JakobThumm/safe_rl_manipulators
1724aee2ec4cbbd8fecfbf1653991e182d4ca48b
[ "MIT" ]
null
null
null
src/catkin_ws/src/modrob_workstation/workstation/include/workstation.hpp
JakobThumm/safe_rl_manipulators
1724aee2ec4cbbd8fecfbf1653991e182d4ca48b
[ "MIT" ]
null
null
null
src/catkin_ws/src/modrob_workstation/workstation/include/workstation.hpp
JakobThumm/safe_rl_manipulators
1724aee2ec4cbbd8fecfbf1653991e182d4ca48b
[ "MIT" ]
null
null
null
#include <iostream> #include <thread> #include <functional> #include <cstring> #include "networking/UDPSocket.h" #include "networking/TCPSocket.h" #include "networking/UDPServerSocket.h" #include "RobotCommanded.hpp" #include "RobotStateCommanded.hpp" #include "RobotAngleCommanded.hpp" #include "RobotTorqueCommanded.hpp" #include "RobotConfigMeasured.hpp" #include "RobotModuleOrder.hpp" class Workstation{ private: /** * Thread that waits for incoming messages from the Robot * The receiverThread runs the receiverRoutine() */ std::thread receiverThread; /** * TCP Connection to the Robot Computer * If activated RobotStateCommanded Messages will be sent over the TCP Connection * The TCP Connection is not used by default. to use it set the USE_TCP_MESSAGES Marcro in workstation.cpp to true * Port: 25001 * */ TCPSocket tcpsocket; /** * UDP Connection to the Robot Computer * The UDP Connection is used to send RobotConfigCommanded and RobotStateCommanded messages to the Robot * The UDP Connection is used to receive RobotConfigMeasured and RobotModuleOrder messages from the Robot * If the TCP Connection is activated RobotStateCommanded messages will not be sent over the UDP Connection * Port: 25000 * */ UDPSocket udpsocket; /** * Method that is called if a RobotConfigMeasured is received from the Robot * This method needs to be defined by the User * It needs to be provided as an input Argument for Worstation() * * @param robotConfigMeasured the RobotConfigMeasured that is received from the Robot * */ const std::function<void(RobotConfigMeasured)>& receiveConfigMeasured; /** * Method that is called if a RobotModuleOrder is received from the Robot * This method needs to be defined by the User * It needs to be provided as an input Argument for Worstation() * * @param robotModuleOrder the RobotModuleOrder that is received from the Robot * */ const std::function<void(RobotModuleOrder)>& receiveModuleOrder; public: /** * Initializes a Workstation Adapter * * @param targetIP the IP adress of the Robot Computer, that the Library should connect to * @param receiveConfigMeasured the receiver method that gets called if a RobotConfigMeasured comes in from the Robot Computer * @param receiveModuleOrder the reciever method that gets called if a RobotModuleOrder comes in from the Robot Computer * */ Workstation(const char *targetIP, const std::function<void(RobotConfigMeasured)>& receiveConf, const std::function<void(RobotModuleOrder)>& receiveMod); /** * Sends a RobotCommand to the Robot * RobotCommand is either a RobotAngleCommanded or RobotTorqeCommanded * * @param command the RobotCommand that shall be sent to the Robot * */ void send(RobotCommanded *command); /** * Waits for incoming messages from the Robot * This routine runs on the receiverThread * If a RobotConfigMeasured comes in, it calls receiveConfigMeasured * If a RobotModuleOrder comes in, it calls receiveModuleOrder * */ void receiverRoutine(); };
33.222222
156
0.708422
JakobThumm
b629847993fbb9a0832ede635bff792fc3f1a756
616
cpp
C++
cpp/001-010/ZigZag Conversion.cpp
KaiyuWei/leetcode
fd61f5df60cfc7086f7e85774704bacacb4aaa5c
[ "MIT" ]
150
2015-04-04T06:53:49.000Z
2022-03-21T13:32:08.000Z
cpp/001-010/ZigZag Conversion.cpp
yizhu1012/leetcode
d6fa443a8517956f1fcc149c8c4f42c0ad93a4a7
[ "MIT" ]
1
2015-04-13T15:15:40.000Z
2015-04-21T20:23:16.000Z
cpp/001-010/ZigZag Conversion.cpp
yizhu1012/leetcode
d6fa443a8517956f1fcc149c8c4f42c0ad93a4a7
[ "MIT" ]
64
2015-06-30T08:00:07.000Z
2022-01-01T16:44:14.000Z
class Solution { public: string convert(string s, int numRows) { if (numRows == 1) { return s; } vector<string> rows(numRows); int row = 0; int step = 1; for (char ch : s) { rows[row].push_back(ch); if (row == (numRows - 1)) { step = -1; } else if (row == 0) { step = 1; } row += step; } stringstream ss; for (const string& row : rows) { ss << row; } return ss.str(); } };
21.241379
43
0.362013
KaiyuWei
b62b6a996424794f51e21d9aca03c0108b650e65
2,520
cpp
C++
tests/sdk/io/media/videooutputtest.cpp
kulikovv/ProcessingSDK
5e1046c9a361b0e321d3df2094d596709be39325
[ "Apache-2.0" ]
null
null
null
tests/sdk/io/media/videooutputtest.cpp
kulikovv/ProcessingSDK
5e1046c9a361b0e321d3df2094d596709be39325
[ "Apache-2.0" ]
null
null
null
tests/sdk/io/media/videooutputtest.cpp
kulikovv/ProcessingSDK
5e1046c9a361b0e321d3df2094d596709be39325
[ "Apache-2.0" ]
null
null
null
#include "videooutputtest.h" #include <opencv2/core/core.hpp> #include <opencv2/imgproc/imgproc.hpp> #include <types/rgb.h> #include <QFile> #include <opencv2/highgui/highgui.hpp> #define FILENAME "D:/VideoOutputTest.avi" #define FRAMENUMB 100 void VideoOutputTest::initTestCase() { _output = new io::media::VideoOutput(0); _source = new io::media::VideoSource(0); if(QFile::exists(FILENAME)) { QFile::remove(FILENAME); } } void VideoOutputTest::cleanupTestCase() { delete _output; delete _source; } void VideoOutputTest::drawObject(cv::Mat img,cv::Point2f coord) { img.setTo(0); cv::circle(img,coord,10,cv::Scalar::all(255),-1); esp data = esp::init<types::Rgb>(new types::Rgb(img)); emit send(data); } void VideoOutputTest::saveingTest() { return; _output->setUrl(FILENAME); _output->setCompression(io::media::VideoOutput::SelectCodec); _output->setFps(25); _output->setEnable(true); cv::Mat testimg; testimg.create(480,640,CV_8UC3); connect(this,SIGNAL(send(esp)),_output,SLOT(receive(esp))); _output->start(); for(int i=0;i<FRAMENUMB;i++) { drawObject(testimg,cv::Point2f(i+50,150)); } _output->stop(); QVERIFY(QFile::exists(FILENAME)); } void VideoOutputTest::loadingTest() { return; QVERIFY(QFile::exists(FILENAME)); _source->setUrl(FILENAME); QCOMPARE((int)_source->lenght(),FRAMENUMB); QCOMPARE((int)_source->fps(),25); cv::Mat testimg; testimg.create(480,640,CV_8UC3); disconnect(_output); int missing = 0; for(int i=_source->lenght()-1;i>=0;i--) { esp data = _source->get(i); QSharedPointer<types::Rgb> sptr = data.getReadOnly<types::Rgb>(); if(sptr.isNull()) { missing++; continue; } } qDebug() << "Missing" << missing; missing = 0; for(int i=0;i<_source->lenght();i++) { esp data = _source->get(i); QSharedPointer<types::Rgb> sptr = data.getReadOnly<types::Rgb>(); if(sptr.isNull()) { missing++; continue; } drawObject(testimg,cv::Point2f(i+50,150)); cv::Mat diff; cv::absdiff(testimg, sptr->getMat(),diff); cv::Scalar mysum = cv::sum(diff); // qDebug() << i << mysum[0] << mysum[1] << mysum[2]; } qDebug() << "Missing" << missing; }
24.466019
73
0.575397
kulikovv
b62d74bccbbca48b413e7fdbb0e2637cd73ff48a
394
hpp
C++
include/Exceptions/InputErrorException.hpp
Ethan13310/NanoTekSpice
d69550213a7607662653c52d8f34e5b565714a30
[ "MIT" ]
2
2018-06-29T10:17:51.000Z
2018-07-04T13:01:53.000Z
include/Exceptions/InputErrorException.hpp
Ethan13310/NanoTekSpice
d69550213a7607662653c52d8f34e5b565714a30
[ "MIT" ]
null
null
null
include/Exceptions/InputErrorException.hpp
Ethan13310/NanoTekSpice
d69550213a7607662653c52d8f34e5b565714a30
[ "MIT" ]
3
2021-03-03T15:29:13.000Z
2022-02-22T15:44:44.000Z
/* ** EPITECH PROJECT, 2018 ** NanoTekSpice ** File description: ** InputErrorException.hpp */ #pragma once #include <string> #include "Exceptions/BaseException.hpp" namespace nts { class InputErrorException : public BaseException { public: InputErrorException(char const *message); InputErrorException(std::string const &message); ~InputErrorException() = default; }; }
15.76
50
0.72335
Ethan13310
b62df3c1fe97ddc32d2c4524729b166eefc3f3af
13,036
cpp
C++
SymbolExtractorAndRenamer/lldb/source/Core/Log.cpp
Polidea/SiriusObfuscator
b0e590d8130e97856afe578869b83a209e2b19be
[ "Apache-2.0" ]
427
2018-05-29T14:21:02.000Z
2022-03-16T03:17:54.000Z
SymbolExtractorAndRenamer/lldb/source/Core/Log.cpp
PolideaPlayground/SiriusObfuscator
b0e590d8130e97856afe578869b83a209e2b19be
[ "Apache-2.0" ]
25
2018-07-23T08:34:15.000Z
2021-11-05T07:13:36.000Z
SymbolExtractorAndRenamer/lldb/source/Core/Log.cpp
PolideaPlayground/SiriusObfuscator
b0e590d8130e97856afe578869b83a209e2b19be
[ "Apache-2.0" ]
52
2018-07-19T19:57:32.000Z
2022-03-11T16:05:38.000Z
//===-- Log.cpp -------------------------------------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // Project includes #include "lldb/Core/Log.h" #include "lldb/Core/PluginManager.h" #include "lldb/Core/StreamFile.h" #include "lldb/Core/StreamString.h" #include "lldb/Host/Host.h" #include "lldb/Host/ThisThread.h" #include "lldb/Interpreter/Args.h" #include "lldb/Utility/NameMatches.h" // Other libraries and framework includes #include "llvm/ADT/SmallString.h" #include "llvm/Support/Chrono.h" #include "llvm/Support/Signals.h" #include "llvm/Support/raw_ostream.h" // C Includes // C++ Includes #include <cstdarg> #include <cstdio> #include <cstdlib> #include <map> #include <mutex> #include <string> using namespace lldb; using namespace lldb_private; Log::Log() : m_stream_sp(), m_options(0), m_mask_bits(0) {} Log::Log(const StreamSP &stream_sp) : m_stream_sp(stream_sp), m_options(0), m_mask_bits(0) {} Log::~Log() = default; Flags &Log::GetOptions() { return m_options; } const Flags &Log::GetOptions() const { return m_options; } Flags &Log::GetMask() { return m_mask_bits; } const Flags &Log::GetMask() const { return m_mask_bits; } void Log::PutCString(const char *cstr) { Printf("%s", cstr); } void Log::PutString(llvm::StringRef str) { PutCString(str.str().c_str()); } //---------------------------------------------------------------------- // Simple variable argument logging with flags. //---------------------------------------------------------------------- void Log::Printf(const char *format, ...) { va_list args; va_start(args, format); VAPrintf(format, args); va_end(args); } //---------------------------------------------------------------------- // All logging eventually boils down to this function call. If we have // a callback registered, then we call the logging callback. If we have // a valid file handle, we also log to the file. //---------------------------------------------------------------------- void Log::VAPrintf(const char *format, va_list args) { // Make a copy of our stream shared pointer in case someone disables our // log while we are logging and releases the stream StreamSP stream_sp(m_stream_sp); if (stream_sp) { static uint32_t g_sequence_id = 0; StreamString header; // Add a sequence ID if requested if (m_options.Test(LLDB_LOG_OPTION_PREPEND_SEQUENCE)) header.Printf("%u ", ++g_sequence_id); // Timestamp if requested if (m_options.Test(LLDB_LOG_OPTION_PREPEND_TIMESTAMP)) { auto now = std::chrono::duration<double>( std::chrono::system_clock::now().time_since_epoch()); header.Printf("%.9f ", now.count()); } // Add the process and thread if requested if (m_options.Test(LLDB_LOG_OPTION_PREPEND_PROC_AND_THREAD)) header.Printf("[%4.4x/%4.4" PRIx64 "]: ", getpid(), Host::GetCurrentThreadID()); // Add the thread name if requested if (m_options.Test(LLDB_LOG_OPTION_PREPEND_THREAD_NAME)) { llvm::SmallString<32> thread_name; ThisThread::GetName(thread_name); if (!thread_name.empty()) header.Printf("%s ", thread_name.c_str()); } header.PrintfVarArg(format, args); header.PutCString("\n"); if (m_options.Test(LLDB_LOG_OPTION_BACKTRACE)) { std::string back_trace; llvm::raw_string_ostream stream(back_trace); llvm::sys::PrintStackTrace(stream); stream.flush(); header.PutCString(back_trace); } if (m_options.Test(LLDB_LOG_OPTION_THREADSAFE)) { static std::recursive_mutex g_LogThreadedMutex; std::lock_guard<std::recursive_mutex> guard(g_LogThreadedMutex); stream_sp->PutCString(header.GetString()); stream_sp->Flush(); } else { stream_sp->PutCString(header.GetString()); stream_sp->Flush(); } } } //---------------------------------------------------------------------- // Print debug strings if and only if the global debug option is set to // a non-zero value. //---------------------------------------------------------------------- void Log::Debug(const char *format, ...) { if (!GetOptions().Test(LLDB_LOG_OPTION_DEBUG)) return; va_list args; va_start(args, format); VAPrintf(format, args); va_end(args); } //---------------------------------------------------------------------- // Log only if all of the bits are set //---------------------------------------------------------------------- void Log::LogIf(uint32_t bits, const char *format, ...) { if (!m_options.AllSet(bits)) return; va_list args; va_start(args, format); VAPrintf(format, args); va_end(args); } //---------------------------------------------------------------------- // Printing of errors that are not fatal. //---------------------------------------------------------------------- void Log::Error(const char *format, ...) { va_list args; va_start(args, format); VAError(format, args); va_end(args); } void Log::VAError(const char *format, va_list args) { char *arg_msg = nullptr; ::vasprintf(&arg_msg, format, args); if (arg_msg == nullptr) return; Printf("error: %s", arg_msg); free(arg_msg); } //---------------------------------------------------------------------- // Printing of warnings that are not fatal only if verbose mode is // enabled. //---------------------------------------------------------------------- void Log::Verbose(const char *format, ...) { if (!m_options.Test(LLDB_LOG_OPTION_VERBOSE)) return; va_list args; va_start(args, format); VAPrintf(format, args); va_end(args); } //---------------------------------------------------------------------- // Printing of warnings that are not fatal. //---------------------------------------------------------------------- void Log::Warning(const char *format, ...) { char *arg_msg = nullptr; va_list args; va_start(args, format); ::vasprintf(&arg_msg, format, args); va_end(args); if (arg_msg == nullptr) return; Printf("warning: %s", arg_msg); free(arg_msg); } typedef std::map<ConstString, Log::Callbacks> CallbackMap; typedef CallbackMap::iterator CallbackMapIter; typedef std::map<ConstString, LogChannelSP> LogChannelMap; typedef LogChannelMap::iterator LogChannelMapIter; // Surround our callback map with a singleton function so we don't have any // global initializers. static CallbackMap &GetCallbackMap() { static CallbackMap g_callback_map; return g_callback_map; } static LogChannelMap &GetChannelMap() { static LogChannelMap g_channel_map; return g_channel_map; } void Log::RegisterLogChannel(const ConstString &channel, const Log::Callbacks &log_callbacks) { GetCallbackMap().insert(std::make_pair(channel, log_callbacks)); } bool Log::UnregisterLogChannel(const ConstString &channel) { return GetCallbackMap().erase(channel) != 0; } bool Log::GetLogChannelCallbacks(const ConstString &channel, Log::Callbacks &log_callbacks) { CallbackMap &callback_map = GetCallbackMap(); CallbackMapIter pos = callback_map.find(channel); if (pos != callback_map.end()) { log_callbacks = pos->second; return true; } ::memset(&log_callbacks, 0, sizeof(log_callbacks)); return false; } bool Log::EnableLogChannel(lldb::StreamSP &log_stream_sp, uint32_t log_options, const char *channel, const char **categories, Stream &error_stream) { Log::Callbacks log_callbacks; if (Log::GetLogChannelCallbacks(ConstString(channel), log_callbacks)) { log_callbacks.enable(log_stream_sp, log_options, categories, &error_stream); return true; } LogChannelSP log_channel_sp(LogChannel::FindPlugin(channel)); if (log_channel_sp) { if (log_channel_sp->Enable(log_stream_sp, log_options, &error_stream, categories)) { return true; } else { error_stream.Printf("Invalid log channel '%s'.\n", channel); return false; } } else { error_stream.Printf("Invalid log channel '%s'.\n", channel); return false; } } void Log::EnableAllLogChannels(StreamSP &log_stream_sp, uint32_t log_options, const char **categories, Stream *feedback_strm) { CallbackMap &callback_map = GetCallbackMap(); CallbackMapIter pos, end = callback_map.end(); for (pos = callback_map.begin(); pos != end; ++pos) pos->second.enable(log_stream_sp, log_options, categories, feedback_strm); LogChannelMap &channel_map = GetChannelMap(); LogChannelMapIter channel_pos, channel_end = channel_map.end(); for (channel_pos = channel_map.begin(); channel_pos != channel_end; ++channel_pos) { channel_pos->second->Enable(log_stream_sp, log_options, feedback_strm, categories); } } void Log::AutoCompleteChannelName(const char *channel_name, StringList &matches) { LogChannelMap &map = GetChannelMap(); LogChannelMapIter pos, end = map.end(); for (pos = map.begin(); pos != end; ++pos) { const char *pos_channel_name = pos->first.GetCString(); if (channel_name && channel_name[0]) { if (NameMatches(channel_name, eNameMatchStartsWith, pos_channel_name)) { matches.AppendString(pos_channel_name); } } else matches.AppendString(pos_channel_name); } } void Log::DisableAllLogChannels(Stream *feedback_strm) { CallbackMap &callback_map = GetCallbackMap(); CallbackMapIter pos, end = callback_map.end(); const char *categories[] = {"all", nullptr}; for (pos = callback_map.begin(); pos != end; ++pos) pos->second.disable(categories, feedback_strm); LogChannelMap &channel_map = GetChannelMap(); LogChannelMapIter channel_pos, channel_end = channel_map.end(); for (channel_pos = channel_map.begin(); channel_pos != channel_end; ++channel_pos) channel_pos->second->Disable(categories, feedback_strm); } void Log::Initialize() { Log::Callbacks log_callbacks = {DisableLog, EnableLog, ListLogCategories}; Log::RegisterLogChannel(ConstString("lldb"), log_callbacks); } void Log::Terminate() { DisableAllLogChannels(nullptr); } void Log::ListAllLogChannels(Stream *strm) { CallbackMap &callback_map = GetCallbackMap(); LogChannelMap &channel_map = GetChannelMap(); if (callback_map.empty() && channel_map.empty()) { strm->PutCString("No logging channels are currently registered.\n"); return; } CallbackMapIter pos, end = callback_map.end(); for (pos = callback_map.begin(); pos != end; ++pos) pos->second.list_categories(strm); uint32_t idx = 0; const char *name; for (idx = 0; (name = PluginManager::GetLogChannelCreateNameAtIndex(idx)) != nullptr; ++idx) { LogChannelSP log_channel_sp(LogChannel::FindPlugin(name)); if (log_channel_sp) log_channel_sp->ListCategories(strm); } } bool Log::GetVerbose() const { // FIXME: This has to be centralized between the stream and the log... if (m_options.Test(LLDB_LOG_OPTION_VERBOSE)) return true; // Make a copy of our stream shared pointer in case someone disables our // log while we are logging and releases the stream StreamSP stream_sp(m_stream_sp); if (stream_sp) return stream_sp->GetVerbose(); return false; } //------------------------------------------------------------------ // Returns true if the debug flag bit is set in this stream. //------------------------------------------------------------------ bool Log::GetDebug() const { // Make a copy of our stream shared pointer in case someone disables our // log while we are logging and releases the stream StreamSP stream_sp(m_stream_sp); if (stream_sp) return stream_sp->GetDebug(); return false; } LogChannelSP LogChannel::FindPlugin(const char *plugin_name) { LogChannelSP log_channel_sp; LogChannelMap &channel_map = GetChannelMap(); ConstString log_channel_name(plugin_name); LogChannelMapIter pos = channel_map.find(log_channel_name); if (pos == channel_map.end()) { ConstString const_plugin_name(plugin_name); LogChannelCreateInstance create_callback = PluginManager::GetLogChannelCreateCallbackForPluginName( const_plugin_name); if (create_callback) { log_channel_sp.reset(create_callback()); if (log_channel_sp) { // Cache the one and only loaded instance of each log channel // plug-in after it has been loaded once. channel_map[log_channel_name] = log_channel_sp; } } } else { // We have already loaded an instance of this log channel class, // so just return the cached instance. log_channel_sp = pos->second; } return log_channel_sp; } LogChannel::LogChannel() : m_log_ap() {} LogChannel::~LogChannel() = default;
32.59
80
0.62266
Polidea
b62e7ed0d6914eecc5cdb23b532a15d7864d26fd
546
cpp
C++
heap-vs-stack/main.cpp
markccchiang/openmp-examples
5970d051e634bc2ad2cf99e84c2544bef1fa258b
[ "MIT" ]
94
2017-04-12T13:24:10.000Z
2022-03-20T11:44:31.000Z
heap-vs-stack/main.cpp
markccchiang/openmp-examples
5970d051e634bc2ad2cf99e84c2544bef1fa258b
[ "MIT" ]
null
null
null
heap-vs-stack/main.cpp
markccchiang/openmp-examples
5970d051e634bc2ad2cf99e84c2544bef1fa258b
[ "MIT" ]
26
2019-01-31T00:33:14.000Z
2022-03-05T19:13:20.000Z
#include <iostream> #include <omp.h> int main() { int heap_sum = 0; omp_set_num_threads(3); #pragma omp parallel { int stack_sum=0; stack_sum++; heap_sum++; printf("stack sum is %d\n", stack_sum); printf("heap sum is %d\n", heap_sum); } std::cout << "final heap sum is " << heap_sum << std::endl; // output: // stack sum is 1 // stack sum is 1 // stack sum is 1 // heap sum is 3 // heap sum is 3 // heap sum is 3 // final heap sum is 3 return 0; }
20.222222
63
0.532967
markccchiang
b631657107846c1725f258b2ee3dbb482fce15a7
822
cpp
C++
uva/chapter_3/11565.cpp
metaflow/contests
5e9ffcb72c3e7da54b5e0818b1afa59f5778ffa2
[ "MIT" ]
1
2019-05-12T23:41:00.000Z
2019-05-12T23:41:00.000Z
uva/chapter_3/11565.cpp
metaflow/contests
5e9ffcb72c3e7da54b5e0818b1afa59f5778ffa2
[ "MIT" ]
null
null
null
uva/chapter_3/11565.cpp
metaflow/contests
5e9ffcb72c3e7da54b5e0818b1afa59f5778ffa2
[ "MIT" ]
null
null
null
#include <string> #include <vector> #include <algorithm> #include <set> #include <iostream> using namespace std; int main() { int n; cin >> n; while (n--) { int a, b, c; cin >> a >> b >> c; [&]() { for (int x = -100; x < 21; x++) if (x * x < c) { for (int y = x+1; y < 101; y++) if (x * x + y * y < c) { for (int z = y+1; z < 101; z++) { if (x + y + z == a && x * y * z == b && x * x + y * y + z * z == c) { printf("%d %d %d\n", x, y, z); return; } } } } printf("No solution.\n"); }(); } return 0; }
24.909091
72
0.281022
metaflow
ac072c254639cbe5b225437c8b0554364bffa354
5,372
cpp
C++
example/particles.cpp
libclsph/libclsph
4cdf18fba05a64826484b0db238b604c90a2e894
[ "MIT" ]
39
2015-01-05T10:39:27.000Z
2022-01-25T12:21:00.000Z
example/particles.cpp
libclsph/libclsph
4cdf18fba05a64826484b0db238b604c90a2e894
[ "MIT" ]
null
null
null
example/particles.cpp
libclsph/libclsph
4cdf18fba05a64826484b0db238b604c90a2e894
[ "MIT" ]
10
2015-09-01T22:47:38.000Z
2022-01-25T12:21:04.000Z
#define EXIT_ON_CL_ERROR #include <iostream> #include <iomanip> #include <string> #include "sph_simulation.h" #include "file_save_delegates/houdini_file_saver.h" #include "util/cereal/archives/binary.hpp" int main(int argc, char** argv) { if(argc < 5) { std::cout << "Too few arguments" << std::endl << "Usage: ./sph <fluid_name> <simulation_properties_name> <scene_name> <frames_folder_prefix>" << std::endl; return -1; } sph_simulation simulation; houdini_file_saver saver = houdini_file_saver(std::string(argv[4])); try{ simulation.load_settings( std::string("fluid_properties/") + argv[1] + std::string(".json"), std::string("simulation_properties/") + argv[2] + std::string(".json")); } catch (const std::exception& ex) { std::cerr << ex.what() << std::endl; std::exit(-1); } int i = 0; simulation.pre_frame = [&] (particle* particles, const simulation_parameters& params, bool full_frame) { if(simulation.write_intermediate_frames != full_frame) { saver.writeFrameToFile(particles, params); } //Lets serialize the frames if it was specified if(simulation.serialize){ std::ofstream file_out( "last_frame.bin" ); cereal::BinaryOutputArchive archive(file_out); archive.saveBinary(particles,sizeof(particle)*params.particles_count); } ++i; int num_frames = params.simulation_time / (params.time_delta * params.simulation_scale); int progress = i * 80 / num_frames; std::cout << "["; for(int j = 0; j < 80; ++j) { if(j < progress) { std::cout << "-"; } else { std::cout << " "; } } std::cout << "] " << i << "/" << num_frames << std::endl; }; std::cout << std::endl << "Loaded parameters " << std::endl << "----------------- " << std::endl << "Simulation time: " << simulation.parameters.simulation_time << std::endl << "Target FPS: " << simulation.parameters.target_fps << std::endl << "Time delta: " << simulation.parameters.time_delta << std::endl << "Simulation scale: " << simulation.parameters.simulation_scale << std::endl << "Write intermediate frames: " << (simulation.write_intermediate_frames ? "true" : "false") << std::endl << "Serialize frames: " << (simulation.serialize ? "true" : "false") << std::endl << std::endl << "Particle count: " << simulation.parameters.particles_count << std::endl << "Particle mass: " << simulation.parameters.particle_mass << std::endl << "Total mass: " << simulation.parameters.total_mass << std::endl << "Initial volume: " << simulation.initial_volume << std::endl << std::endl << "Fluid density: " << simulation.parameters.fluid_density << std::endl << "Dynamic viscosity: " << simulation.parameters.dynamic_viscosity << std::endl << "Surface tension threshold: " << simulation.parameters.surface_tension_threshold << std::endl << "Surface tension: " << simulation.parameters.surface_tension << std::endl << "Stiffness (k): " << simulation.parameters.K << std::endl << "Restitution: " << simulation.parameters.restitution << std::endl << std::endl << "Kernel support radius (h): " << simulation.parameters.h << std::endl << std::endl << "Saving to folder: " << saver.frames_folder_prefix + "frames/" << std::endl; if(!simulation.current_scene.load(argv[3])) { std::cerr << "Unable to load scene: " << argv[3] << std::endl; return -1; } //If the serialization data is not the right size, delete it //This probably means the last simulation ran with a different number of particles or the serialization was interrupted std::filebuf fb; if (fb.open ("last_frame.bin",std::ios::in)) { std::istream file_in(&fb); file_in.seekg(0,std::ios_base::end); size_t file_size = file_in.tellg(); //This information is important, it indicates that the behavior of the simulator is completely different, use color to draw attention of user if(file_size == simulation.parameters.particles_count*sizeof(particle)){ std::cout << std::endl << "\033[1;32m Serialized frame found. " << " Simulation will pick up where last run left off.\033[0m"; std::cout << std::endl << "\033[1;32m To start a new simulation, delete last_frame.bin. \033[0m" << std::endl; } else{ std::cout << std::endl << "\033[1;31m Serialized frame of incorrect size found. Revert to last know settings or delete it, then try again. \033[0m" << std::endl; return 0; } fb.close(); } std::cout << std::endl << "Revise simulation parameters. Press q to quit, any other key to proceed with simulation" << std::endl; char response; std::cin >> response; if(response != 'q') { simulation.simulate(); } return 0; }
40.69697
173
0.573157
libclsph
ac0734a6a4e9daed2b12bc0a02ef134821b58e03
13,910
hxx
C++
dev/ese/src/inc/_osu/syncu.hxx
augustoproiete-forks/microsoft--Extensible-Storage-Engine
a38945d2147167e3fa749594f54dae6c7307b8da
[ "MIT" ]
1
2021-02-02T07:04:07.000Z
2021-02-02T07:04:07.000Z
dev/ese/src/inc/_osu/syncu.hxx
augustoproiete-forks/microsoft--Extensible-Storage-Engine
a38945d2147167e3fa749594f54dae6c7307b8da
[ "MIT" ]
null
null
null
dev/ese/src/inc/_osu/syncu.hxx
augustoproiete-forks/microsoft--Extensible-Storage-Engine
a38945d2147167e3fa749594f54dae6c7307b8da
[ "MIT" ]
null
null
null
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #ifndef _OSU_SYNC_HXX_INCLUDED #define _OSU_SYNC_HXX_INCLUDED class AGENT { public: AGENT() : m_cWait( 0 ), m_fAgentReleased( fFalse ), m_irksem( CKernelSemaphorePool::irksemNil ) { Assert( IsAtomicallyModifiable( (LONG*)&m_dw ) ); } ~AGENT() {} AGENT& operator=( AGENT& ); void Wait( CCriticalSection& crit ); void Release( CCriticalSection& crit ); DWORD CWait() const; private: union { volatile LONG m_dw; struct { volatile LONG m_cWait:31; volatile FLAG32 m_fAgentReleased:1; }; }; CKernelSemaphorePool::IRKSEM m_irksem; BYTE m_rgbFiller[2]; }; INLINE void AGENT::Wait( CCriticalSection& crit ) { Assert( crit.FOwner() ); Assert( !m_fAgentReleased ); if ( 0 == CWait() ) { Assert( CKernelSemaphorePool::irksemNil == m_irksem ); m_irksem = g_ksempoolGlobal.Allocate( (const CLockObject* const) &m_irksem ); } Assert( CWait() + 1 < 0x8000 ); m_cWait++; Assert( CKernelSemaphorePool::irksemNil != m_irksem ); crit.Leave(); g_ksempoolGlobal.Ksem( m_irksem, (const CLockObject* const) &m_irksem ).Acquire(); Assert( m_fAgentReleased ); Assert( CWait() > 0 ); AtomicDecrement( (LONG*)&m_dw ); crit.Enter(); } INLINE void AGENT::Release( CCriticalSection& crit ) { Assert( crit.FOwner() ); Assert( !m_fAgentReleased ); m_fAgentReleased = fTrue; if ( CWait() > 0 ) { Assert( CKernelSemaphorePool::irksemNil != m_irksem ); g_ksempoolGlobal.Ksem( m_irksem, (const CLockObject* const) &m_irksem ).Release( CWait() ); while ( CWait() > 0 ) { UtilSleep( 10 ); } g_ksempoolGlobal.Unreference( m_irksem ); m_irksem = CKernelSemaphorePool::irksemNil; } Assert( m_fAgentReleased ); Assert( CWait() == 0 ); Assert( CKernelSemaphorePool::irksemNil == m_irksem ); } INLINE DWORD AGENT::CWait() const { Assert( m_cWait >= 0 ); return m_cWait; } class ENTERCRITICALSECTION { private: CCriticalSection* const m_pcrit; public: ENTERCRITICALSECTION( CCriticalSection* const pcrit, const BOOL fEnter = fTrue ) : m_pcrit( fEnter ? pcrit : NULL ) { if ( m_pcrit ) { m_pcrit->Enter(); } } ~ENTERCRITICALSECTION() { if ( m_pcrit ) { m_pcrit->Leave(); } } private: ENTERCRITICALSECTION(); ENTERCRITICALSECTION( const ENTERCRITICALSECTION& ); ENTERCRITICALSECTION& operator=( const ENTERCRITICALSECTION& ); }; class ENTERREADERWRITERLOCK { private: CReaderWriterLock* const m_prwl; const BOOL m_fReader; public: ENTERREADERWRITERLOCK( CReaderWriterLock* const prwl, const BOOL fReader, const BOOL fEnter = fTrue ) : m_prwl( fEnter ? prwl : NULL ), m_fReader( fReader ) { if ( m_prwl ) { if ( m_fReader ) { m_prwl->EnterAsReader(); } else { m_prwl->EnterAsWriter(); } } } ~ENTERREADERWRITERLOCK() { if ( m_prwl ) { if ( m_fReader ) { m_prwl->LeaveAsReader(); } else { m_prwl->LeaveAsWriter(); } } } private: ENTERREADERWRITERLOCK(); ENTERREADERWRITERLOCK( const ENTERREADERWRITERLOCK& ); ENTERREADERWRITERLOCK& operator=( const ENTERREADERWRITERLOCK& ); }; template<class T> class CRITPOOL { public: CRITPOOL( void ); ~CRITPOOL( void ); CRITPOOL& operator=( CRITPOOL& ); BOOL FInit( const LONG cThread, const INT rank, const _TCHAR* szName ); void Term( void ); CCriticalSection& Crit( const T* const pt ); private: LONG m_ccrit; CCriticalSection* m_rgcrit; LONG m_cShift; LONG m_mask; }; template<class T> CRITPOOL<T>::CRITPOOL( void ) { m_ccrit = 0; m_rgcrit = NULL; m_cShift = 0; m_mask = 0; } template<class T> CRITPOOL<T>::~CRITPOOL( void ) { Term(); } template<class T> BOOL CRITPOOL<T>::FInit( const LONG cThread, const INT rank, const _TCHAR* szName ) { Assert( m_ccrit == 0 ); Assert( m_rgcrit == NULL ); Assert( m_cShift == 0 ); Assert( m_mask == 0 ); Assert( cThread > 0 ); m_ccrit = LNextPowerOf2( cThread * 2 + 1 ); m_mask = m_ccrit - 1; LONG n; for ( m_cShift = -1, n = 1; sizeof( T ) % n == 0; m_cShift++, n *= 2 ); if ( !( m_rgcrit = (CCriticalSection *)( new BYTE[m_ccrit * sizeof( CCriticalSection )] ) ) ) { goto HandleError; } LONG icrit; for ( icrit = 0; icrit < m_ccrit; icrit++ ) { new( m_rgcrit + icrit ) CCriticalSection( CLockBasicInfo( CSyncBasicInfo( szName ), rank, icrit ) ); } return fTrue; HandleError: Term(); return fFalse; } template<class T> void CRITPOOL<T>::Term( void ) { if (NULL != m_rgcrit) { LONG icrit; for ( icrit = 0; icrit < m_ccrit; icrit++ ) { m_rgcrit[icrit].~CCriticalSection(); } delete [] (BYTE *)m_rgcrit; } m_ccrit = 0; m_rgcrit = NULL; m_cShift = 0; m_mask = 0; } template<class T> INLINE CCriticalSection& CRITPOOL<T>::Crit( const T* const pt ) { return m_rgcrit[( LONG_PTR( pt ) >> m_cShift ) & m_mask]; } template<class T> class RWLPOOL { public: RWLPOOL( void ); ~RWLPOOL( void ); RWLPOOL& operator=( RWLPOOL& ); BOOL FInit( const LONG cThread, const INT rank, const _TCHAR* szName ); void Term( void ); CReaderWriterLock& Rwl( const T* const pt ); private: LONG m_crwl; CReaderWriterLock* m_rgrwl; LONG m_cShift; LONG m_mask; }; template<class T> RWLPOOL<T>::RWLPOOL( void ) { m_crwl = 0; m_rgrwl = NULL; m_cShift = 0; m_mask = 0; } template<class T> RWLPOOL<T>::~RWLPOOL( void ) { Term(); } template<class T> BOOL RWLPOOL<T>::FInit( const LONG cThread, const INT rank, const _TCHAR* szName ) { Assert( m_crwl == 0 ); Assert( m_rgrwl == NULL ); Assert( m_cShift == 0 ); Assert( m_mask == 0 ); Assert( cThread > 0 ); m_crwl = LNextPowerOf2( cThread * 2 + 1 ); m_mask = m_crwl - 1; LONG n; for ( m_cShift = -1, n = 1; sizeof( T ) % n == 0; m_cShift++, n *= 2 ); if ( !( m_rgrwl = (CReaderWriterLock *)( new BYTE[m_crwl * sizeof( CReaderWriterLock )] ) ) ) { goto HandleError; } LONG irwl; for ( irwl = 0; irwl < m_crwl; irwl++ ) { new( m_rgrwl + irwl ) CReaderWriterLock( CLockBasicInfo( CSyncBasicInfo( szName ), rank, irwl ) ); } return fTrue; HandleError: Term(); return fFalse; } template<class T> void RWLPOOL<T>::Term( void ) { if (NULL != m_rgrwl) { LONG irwl; for ( irwl = 0; irwl < m_crwl; irwl++ ) { m_rgrwl[irwl].~CReaderWriterLock(); } delete [] (BYTE *)m_rgrwl; } m_crwl = 0; m_rgrwl = NULL; m_cShift = 0; m_mask = 0; } template<class T> INLINE CReaderWriterLock& RWLPOOL<T>::Rwl( const T* const pt ) { return m_rgrwl[( LONG_PTR( pt ) >> m_cShift ) & m_mask]; } typedef struct BF* PBF; class BFNominee { public: volatile PBF pbf; ULONG cCacheReq; }; const size_t cBFNominee = 4; class BFHashedLatch { public: BFHashedLatch() : sxwl( CLockBasicInfo( CSyncBasicInfo( "BFHashedLatch Read/RDW/Write" ), 1000, CLockDeadlockDetectionInfo::subrankNoDeadlock ) ) { } public: CSXWLatch sxwl; PBF pbf; ULONG cCacheReq; }; const size_t cBFHashedLatch = 16; class PLS { public: BFNominee rgBFNominee[ cBFNominee ]; BFHashedLatch rgBFHashedLatch[ cBFHashedLatch ]; ULONG rgcreqBFNominee[ 2 ][ cBFNominee ]; ULONG rgdcreqBFNominee[ cBFNominee ]; ULONG rgcreqBFHashedLatch[ 2 ][ cBFHashedLatch ]; ULONG rgdcreqBFHashedLatch[ cBFHashedLatch ]; #ifdef DEBUGGER_EXTENSION public: #else private: #endif static BYTE* s_pbPerfCounters; static ULONG s_cbPerfCounters; BOOL fPerfCountersDisabled; BYTE* pbPerfCounters; ULONG cbPerfCountersCommitted; CCriticalSection critPerfCounters; private: BOOL FEnsurePerfCounterBuffer_( const ULONG cb ) { BOOL fOwnsCritSec = fFalse; BOOL fIsBufferLargeEnough = fTrue; Assert( !fPerfCountersDisabled ); Assert( s_pbPerfCounters != NULL ); Assert( s_cbPerfCounters > 0 ); if ( cb <= (ULONG)AtomicRead( (LONG*)&cbPerfCountersCommitted ) ) { goto Return; } critPerfCounters.Enter(); fOwnsCritSec = fTrue; if ( cb <= cbPerfCountersCommitted ) { goto Return; } const ULONG cbPerfCountersNeeded = roundup( cb, OSMemoryPageCommitGranularity() ); Assert( cbPerfCountersNeeded > cbPerfCountersCommitted ); const ULONG dcbPerfCountersNeeded = cbPerfCountersNeeded - cbPerfCountersCommitted; if ( FOSMemoryPageCommit( pbPerfCounters + cbPerfCountersCommitted, dcbPerfCountersNeeded ) ) { (void)AtomicExchange( (LONG*)&cbPerfCountersCommitted, cbPerfCountersNeeded ); } else { fIsBufferLargeEnough = fFalse; } Return: if ( fOwnsCritSec ) { critPerfCounters.Leave(); } return fIsBufferLargeEnough; } public: static BOOL FAllocatePerfCountersMemory( const ULONG cbPerfCountersPerProc ) { Assert( s_pbPerfCounters == NULL ); Assert( s_cbPerfCounters == 0 ); Assert( cbPerfCountersPerProc > 0 ); const ULONG cbPerfCounters = roundup( cbPerfCountersPerProc, OSMemoryPageReserveGranularity() ) * OSSyncGetProcessorCountMax(); s_pbPerfCounters = (BYTE*)PvOSMemoryPageReserve( cbPerfCounters, NULL ); if ( s_pbPerfCounters == NULL ) { return fFalse; } s_cbPerfCounters = cbPerfCounters; return fTrue; } static void FreePerfCountersMemory() { OSMemoryPageFree( s_pbPerfCounters ); s_pbPerfCounters = NULL; s_cbPerfCounters = 0; } PLS( const ULONG iProc, const BOOL fPerfCountersDisabledNew ) : fPerfCountersDisabled( fPerfCountersDisabledNew ), rgBFHashedLatch(), pbPerfCounters( NULL ), cbPerfCountersCommitted( 0 ), critPerfCounters( CLockBasicInfo( CSyncBasicInfo( "PLS::critPerfCounters" ), 0, 0 ) ) { if ( fPerfCountersDisabled ) { return; } Assert( s_pbPerfCounters != NULL ); Assert( s_cbPerfCounters > 0 ); const ULONG cProc = OSSyncGetProcessorCountMax(); const ULONG cbPerfCounters = s_cbPerfCounters / cProc; const ULONG ibPerfCounters = iProc * cbPerfCounters; Assert( ibPerfCounters < s_cbPerfCounters ); cbPerfCountersCommitted = 0; pbPerfCounters = s_pbPerfCounters + ibPerfCounters; Assert( ( pbPerfCounters + cbPerfCounters ) <= ( s_pbPerfCounters + s_cbPerfCounters ) ); } ~PLS() { fPerfCountersDisabled = fFalse; pbPerfCounters = NULL; cbPerfCountersCommitted = 0; } static BOOL FEnsurePerfCounterBuffer( const ULONG cb ) { const size_t cProcs = (size_t)OSSyncGetProcessorCountMax(); for ( size_t iProc = 0; iProc < cProcs; iProc++ ) { PLS* const ppls = (PLS*)OSSyncGetProcessorLocalStorage( iProc ); if ( !ppls->FEnsurePerfCounterBuffer_( cb ) ) { return fFalse; } } return fTrue; } INLINE BYTE* PbGetPerfCounterBuffer( const ULONG ib, const ULONG cb ) { Assert( !fPerfCountersDisabled ); Assert( s_pbPerfCounters != NULL ); Assert( s_cbPerfCounters > 0 ); Assert( ( ib + cb ) <= cbPerfCountersCommitted ); return ( pbPerfCounters + ib ); } INLINE ULONG CbPerfCountersCommitted() { return cbPerfCountersCommitted; } }; INLINE PLS* Ppls() { return (PLS*)OSSyncGetProcessorLocalStorage(); } INLINE PLS* Ppls( const size_t iProc ) { return (PLS*)OSSyncGetProcessorLocalStorage( iProc ); } ERR ErrOSUSyncInit(); void OSUSyncTerm(); #endif
22.114467
144
0.540043
augustoproiete-forks
ac0ae526c97f6b4214c6e119684ca9ac6181ecd3
249
cpp
C++
baseclass/testPattern.cpp
HxHexa/quang-advCG-raytracer
605f7dfcc9237f331d456646b7653ad0f26c0cc4
[ "MIT" ]
null
null
null
baseclass/testPattern.cpp
HxHexa/quang-advCG-raytracer
605f7dfcc9237f331d456646b7653ad0f26c0cc4
[ "MIT" ]
null
null
null
baseclass/testPattern.cpp
HxHexa/quang-advCG-raytracer
605f7dfcc9237f331d456646b7653ad0f26c0cc4
[ "MIT" ]
null
null
null
/* it does what it says it does * */ #include "headers/testPattern.hpp" TestPattern::TestPattern() { transform = Matrix::Identity(); } Color TestPattern::patternAt(Tuple point) { return Color(point.getx(), point.gety(), point.getz()); }
19.153846
59
0.674699
HxHexa
ac0b500b0cd549dfb1b33a1ef58bf116a2a162e5
54,115
cpp
C++
src/uti_files/CPP_Test_Apero2NVM.cpp
kikislater/micmac
3009dbdad62b3ad906ec882b74b85a3db86ca755
[ "CECILL-B" ]
451
2016-11-25T09:40:28.000Z
2022-03-30T04:20:42.000Z
src/uti_files/CPP_Test_Apero2NVM.cpp
kikislater/micmac
3009dbdad62b3ad906ec882b74b85a3db86ca755
[ "CECILL-B" ]
143
2016-11-25T20:35:57.000Z
2022-03-01T11:58:02.000Z
src/uti_files/CPP_Test_Apero2NVM.cpp
kikislater/micmac
3009dbdad62b3ad906ec882b74b85a3db86ca755
[ "CECILL-B" ]
139
2016-12-02T10:26:21.000Z
2022-03-10T19:40:29.000Z
/*Header-MicMac-eLiSe-25/06/2007 MicMac : Multi Image Correspondances par Methodes Automatiques de Correlation eLiSe : ELements of an Image Software Environnement www.micmac.ign.fr Copyright : Institut Geographique National Author : Marc Pierrot Deseilligny Contributors : Gregoire Maillet, Didier Boldo. [1] M. Pierrot-Deseilligny, N. Paparoditis. "A multiresolution and optimization-based image matching approach: An application to surface reconstruction from SPOT5-HRS stereo imagery." In IAPRS vol XXXVI-1/W41 in ISPRS Workshop On Topographic Mapping From Space (With Special Emphasis on Small Satellites), Ankara, Turquie, 02-2006. [2] M. Pierrot-Deseilligny, "MicMac, un lociel de mise en correspondance d'images, adapte au contexte geograhique" to appears in Bulletin d'information de l'Institut Geographique National, 2007. Francais : MicMac est un logiciel de mise en correspondance d'image adapte au contexte de recherche en information geographique. Il s'appuie sur la bibliotheque de manipulation d'image eLiSe. Il est distibue sous la licences Cecill-B. Voir en bas de fichier et http://www.cecill.info. English : MicMac is an open source software specialized in image matching for research in geographic information. MicMac is built on the eLiSe image library. MicMac is governed by the "Cecill-B licence". See below and http://www.cecill.info. Header-MicMac-eLiSe-25/06/2007*/ /**********************************/ /* Author: Mathieu Monneyron */ /**********************************/ #include "StdAfx.h" #include <algorithm> #include "hassan/reechantillonnage.h" vector<string> FindMatchFileAndIndex(string aNameDir, string aPattern, int ExpTxt, vector<vector<string> > &aVectImSift, vector<vector<int> > &aMatrixIndex) //finished { //make a comment std::string aCom = "Finding File" + std::string(" +Ext=") + (ExpTxt?"txt":"dat"); std::cout << "Com = " << aCom << "\n"; //preparation for list and extension of file std::string aSiftDir= aNameDir + "Homol/Pastis"; std::string aKee=std::string(".*.") + (ExpTxt?"txt":"dat"); cout<<"sift_file_&_extension : "<<aKee<<endl; //Reading the list of input files (images) list<string> ListIm=RegexListFileMatch(aNameDir,aPattern,1,false); int nbIm = (int)ListIm.size(); cout<<"Number of images to process: "<<nbIm<<endl; vector<string> VectIm; vector<string> aFullDir; for (int i=0;i<nbIm;i++) { //Reading the images list string aFullName=ListIm.front(); cout<<aFullName<<endl; //transform the list in vector for manipulation VectIm.push_back(aFullName); ListIm.pop_front(); //cancel images once read }//end of "for each image" cout<<"findind file's list and index"<<endl; for (int i=0;i<nbIm;i++) {//path for sift folders and list of file for each folder string aFullName=VectIm[i]; string aFullSiftDir = aSiftDir + aFullName +"/"; cout<<aFullSiftDir<<endl; aFullDir.push_back(aFullSiftDir); cInterfChantierNameManipulateur * anICNM = cInterfChantierNameManipulateur::BasicAlloc(aFullSiftDir); list<string> aFileList = anICNM->StdGetListOfFile(aKee,1); //here akee is quite alike aPattern int nbFiles = (int)aFileList.size(); cout<<"nombre de fichier = "<< nbFiles <<endl; //delete anICNM; std::vector<string> VectSift; std::vector<int> VectInd; for (int j=0;j<nbFiles;j++) { //Reading the sift-images list string aFullName2=aFileList.front(); //cout<<aFullName2<<endl; //transform the list in vector for manipulation VectSift.push_back(aFullName2); aFileList.pop_front(); //cancel name once read int k = 0; string aFullNameComp; //look for the same name in the list of images and add corresponding index do { aFullNameComp=VectIm[k] + "." + (ExpTxt?"txt":"dat"); k = k + 1; } while (aFullNameComp.compare(aFullName2) != 0); {VectInd.push_back(k-1); //cout<<"l'index est : "<<VectInd[j]<<endl; } }//end of "for each file of sift of the concerned image" aVectImSift.push_back(VectSift);//write every name of the list of files of the list of images aMatrixIndex.push_back(VectInd);// write index associate to every files }//end for each images cout<<"nb of Images processed : "<<aVectImSift.size()<<endl; //cout<<"nb of file first image : "<<aVectImSift[0].size()<<endl; //cout<<"nb of index first image : "<<aMatrixIndex[0].size()<<endl; return aFullDir; } vector<vector<double> > CopyAndMergeMatchFile(string aNameDir, string aPattern, string DirOut, int ExpTxt) //finished { //Bulding the output file system ELISE_fp::MkDir(aNameDir + DirOut); std::cout<<"dossier " + DirOut + " cree"<<std::endl; std::cout<<aNameDir<<" & "<<aPattern<<" & "<<DirOut<<std::endl; //recuperate the matrix of file name and of associated index vector<vector<string> > V_ImSift; vector<vector<int> > Matrix_Index; vector<string> aFullSiftDir= FindMatchFileAndIndex(aNameDir, aPattern, ExpTxt, V_ImSift, Matrix_Index ); //make a comment std::string aCom = "Reading and copying in a single File" + std::string(" +Ext=") + (ExpTxt?"txt":"dat"); std::cout << "Com = " << aCom << "\n"; //Name a new file which will contains all the previous data //string aOutputFileName= aNameDir+ DirOut + "SumOfSiftData.txt"; int nbIm = (int)V_ImSift.size(); double n1,n2,n3,n4; //bool ExpTxt; // Declare vector which will contains the value vector<double> N1,N2,N3,N4,N5,N6; vector<vector<double> > aFullTabSift; for (int i=0;i<nbIm;i++) { int nbFl = (int)V_ImSift[i].size(); for (int j=0;j<nbFl;j++) { //make a string for every file which include the directory string aFullFileName=aFullSiftDir[i] + V_ImSift[i][j]; cout<<aFullFileName<<endl; int k= Matrix_Index[i][j]; //-------- !!! ----- Ne fonctionne qu'avec les fichiers .txt pour l'instant ------ !!! ------ // if (ExpTxt != 1) { ElPackHomologue aPack = ElPackHomologue::FromFile(aFullFileName); for (ElPackHomologue::const_iterator itP=aPack.begin() ; itP!=aPack.end() ; itP++) { N1.push_back(i); N2.push_back(itP->P1().x); // , N3.push_back(n2), N4.push_back(k), N5.push_back(n3), N6.push_back(n4); N3.push_back(itP->P1().y); N4.push_back(k); N5.push_back(itP->P2().x); N6.push_back(itP->P2().y); } /* FILE *If = fopen(aFullFileName.c_str(), "rb" ); //FILE *Of = fopen(aOutputFileName.c_str(), "a" ); do { //read all the file one by one int aNbVal = fscanf(If, "%lf %lf %lf %lf\n", &n1, &n2, &n3, &n4); ELISE_ASSERT(aNbVal==4,"Bad nb val while scanning file in CopyAndMergeMatchFile"); //fill the vectors with all the elements N1.push_back(i), N2.push_back(n1), N3.push_back(n2), N4.push_back(k), N5.push_back(n3), N6.push_back(n4); //fprintf(Of,"%d %0.1f% 0.1f %d %0.1f %0.1f\n", i, n1, n2, k, n3, n4);//write the file just for control }while(!feof(If)); fclose(If); */ //fclose(Of); } else {FILE *If = fopen(aFullFileName.c_str(), "r" ); //FILE *Of = fopen(aOutputFileName.c_str(), "a" ); do { //read all the file one by one int aNbVal = fscanf(If, "%lf %lf %lf %lf\n", &n1, &n2, &n3, &n4); ELISE_ASSERT(aNbVal==4,"Bad nb val while scanning file in CopyAndMergeMatchFile"); //fill the vectors with all the elements N1.push_back(i), N2.push_back(n1), N3.push_back(n2), N4.push_back(k), N5.push_back(n3), N6.push_back(n4); //fprintf(Of,"%d %0.1f% 0.1f %d %0.1f %0.1f\n", i, n1, n2, k, n3, n4);//write the file just for control }while(!feof(If)); fclose(If); //fclose(Of); } } } //fill the vector of vectors with all the data vectors aFullTabSift.push_back(N1),aFullTabSift.push_back(N2),aFullTabSift.push_back(N3),aFullTabSift.push_back(N4),aFullTabSift.push_back(N5),aFullTabSift.push_back(N6); /* // obtain file size in octets (not an obligation) FILE *Of = fopen(aOutputFileName.c_str(), "r" ); fseek (Of , 0 , SEEK_END); long aFileSize = ftell (Of); rewind (Of); cout<<"taille du fichier final : "<<aFileSize<<" octets"<<endl; */ cout<<"Nombre de lignes/de mesures : "<<aFullTabSift[0].size()<<endl; return aFullTabSift; } vector<vector<double> > CorrectTiePoint(string aNameDir, string aPattern, string DirOut, int ExpTxt) //not finished yet { //load the data from the previous function vector<vector<double> > aFullTabSift = CopyAndMergeMatchFile(aNameDir, aPattern, DirOut, ExpTxt); int NBSift = (int)aFullTabSift[0].size(); //cout<<"Nombre de lignes/de mesures : "<<aFullTabSift[0].size()<<endl; //Reading the list of input files list<string> ListIm=RegexListFileMatch(aNameDir,aPattern,1,false); int nbIm = (int)ListIm.size(); //loop for know where are the change of image in the vector aFullTabSift[0] int Value =0; vector<int> aIndexImage; aIndexImage.push_back(0); for (int j=0;j<NBSift;j++) {int ValIndex=aFullTabSift[0][j]; if(ValIndex==Value+1) {aIndexImage.push_back(j); //cout<<"nb : "<<j<<endl; Value=Value+1; } } aIndexImage.push_back(NBSift);//add the last value //-------------------Double point Detection and cancellation--------------// //DECTECTION PART //Declare vector which will contains the points who have the same coordinate vector<double> aListPtDouble; double diffx1=10; double diffy1=10; double diffx2=10; double diffy2=10; for (int i=0;i<nbIm-1;i++) { int Alimitinf=aIndexImage[i]; int Alimitsup=aIndexImage[i+1]; //iter for every image, look at the points in the other image for (int h=Alimitinf;h<Alimitsup;h++) { double Valrefx1=aFullTabSift[1][h]; double Valrefy1=aFullTabSift[2][h]; double Valrefx2=aFullTabSift[4][h]; double Valrefy2=aFullTabSift[5][h]; //run the rest of the point of the all tab from the next image for (int m=Alimitsup;m<NBSift; m++) { double Valcompx1=aFullTabSift[4][m]; double Valcompy1=aFullTabSift[5][m]; double Valcompx2=aFullTabSift[1][m]; double Valcompy2=aFullTabSift[2][m]; diffx1=abs(Valcompx1-Valrefx1); diffy1=abs(Valcompy1-Valrefy1); diffx2=abs(Valcompx2-Valrefx2); diffy2=abs(Valcompy2-Valrefy2); if(diffx1<1.0 && diffy1<1.0 && diffx2<1.0 && diffy2<1.0 )//condition to accept that is the same point {aListPtDouble.push_back(m);//fill the vector of the n° of ligne of the double point //aListPtDoubleIni.push_back(h); //cout<<"Valeur de m : "<<m+1<<" pour le point : "<<h+1<<endl; } } } } //CANCELLATION PART sort( aListPtDouble.begin(),aListPtDouble.end() ); int K = (int)aListPtDouble.size(); cout<<"NB Double: "<<aListPtDouble.size()<<endl; for (int i=K-1;i>=0; i--) { long Val=aListPtDouble[i]; //cout<<"Val :"<<Val<<endl; for (int j=0;j<6; j++) {aFullTabSift[j].erase(aFullTabSift[j].begin()+Val);} } int NBSiftM = (int)aFullTabSift[0].size(); cout<<"NB restant: "<<NBSiftM<<endl; aListPtDouble.clear(); //-------------------Fabrication of a new list -------------------------// //////////just for verif /* string aOutputFileName2= aNameDir+ DirOut + "SumOfSiftData2.txt"; FILE *Of = fopen(aOutputFileName2.c_str(), "a" ); for( int l=0;l<NBSiftM; l++) { //fill the vectors with all the elements int a=aFullTabSift[0][l]; double b=aFullTabSift[1][l]; double c=aFullTabSift[2][l]; int d=aFullTabSift[3][l]; double e=aFullTabSift[4][l]; double f=aFullTabSift[5][l]; fprintf(Of,"%d %0.1f% 0.1f %d %0.1f %0.1f\n",a,b,c,d,e,f );//write the file just for control } fclose(Of); */ //loop for know where are the change of image in the modified vector aFullTabSift[0] vector<int> aIndexImageM; aIndexImageM.push_back(0); int ValueM=0; for (int k=0;k<NBSiftM;k++) {int ValInd=aFullTabSift[0][k]; //cout<<k<<endl; if (ValueM!=ValInd) {aIndexImageM.push_back(k); cout<<"nbr : "<<k<<endl; ValueM=ValueM+1; } } aIndexImageM.push_back(NBSiftM);//add the last value cout<<"size IndexIm : "<<aIndexImageM.size()<<endl; //----------------- Multiple Point detection and cancellation-----------------// //DETECTION PART //Declare vector which will contains the points who have the same coordinate vector<double> aListPtMulti,aListPtMultiIni; double diffx=10; double diffy=10; for (int i=0;i<nbIm;i++) { int Alimitinf=aIndexImageM[i]; int Alimitsup=aIndexImageM[i+1]; //fill the vector of the n° of ligne of the multiple point for (int h=Alimitinf;h<Alimitsup-1;h++) { int l=h+1; double Valrefx=aFullTabSift[1][h]; double Valrefy=aFullTabSift[2][h]; //run the rest of the point of the same image from the next-current point while (l<Alimitsup) { double Valcompx=aFullTabSift[1][l]; double Valcompy=aFullTabSift[2][l]; diffx=abs(Valcompx-Valrefx); diffy=abs(Valcompy-Valrefy); if(diffx<1.0 && diffy<1.0 ) {aListPtMulti.push_back(l); aListPtMultiIni.push_back(h); //cout<<"Valeur de l : "<<l<<" & Valeur de h : "<<h<<endl; } l=l+1; if(diffx<1.0 && diffy<1.0) break;//condition to accept that is the same point } //cout<<"diffx : "<<diffx<<endl; //cout<<"diffy : "<<diffy<<endl; } } cout<<"NB Multiple: "<<aListPtMulti.size()<<endl; cout<<"NB MultipleIni: "<<aListPtMultiIni.size()<<endl; //multiple point list tab inversion //creation of a new list vector<vector<double> > aFinalTabSift; for (int i=0;i<NBSiftM;i++) { vector<double> aPointTie; for (int j=0;j<6;j++) { double Val=aFullTabSift[j][i]; aPointTie.push_back(Val); } aFinalTabSift.push_back(aPointTie); } aFullTabSift.clear();//suppression of the old vector cout<<"taille de la liste : "<<aFinalTabSift.size()<<endl; cout<<"taille pour un couple : "<<aFinalTabSift[0].size()<<endl; //CANCELLATION PART int N = (int)aListPtMulti.size(); int Q=0; for (int i=0;i<N; i++) {int L=aListPtMulti[i]; //cout<<"valeur de l "<<L<<endl; for (int j=0;j<N; j++) {int H=aListPtMultiIni[j]; //cout<<"valeur de h "<<H<<endl; if (H==L) {//cout<<"l'indice "<<i<<" vaut "<<j<<endl; Q=Q+1;} } } //cout<<"NB Quadruple ou plus : "<<Q<<endl; int Q2=0; for (int i=0;i<N; i++) { int IndReceiv=aListPtMulti[i]; int IndTaken=aListPtMultiIni[i]; IndReceiv=IndReceiv - i; IndTaken=IndTaken - i; int S = (int)aFinalTabSift[IndTaken].size(); if(S>6) {//cout<<"redondance :"<<S-6<<endl; Q2=Q2+1;} aFinalTabSift[IndTaken].erase(aFinalTabSift[IndTaken].begin(),aFinalTabSift[IndTaken].begin()+3); std::vector<double>::iterator it; it = aFinalTabSift[IndReceiv].begin(); aFinalTabSift[IndReceiv].insert(it+6,aFinalTabSift[IndTaken].begin(),aFinalTabSift[IndTaken].end()); //push_back the value from aListPtMultiIni to aListPtMulti //push_back ne fonctionne pas, erreur de memoire /*for (int j=3;j>S; j++) { double Val2Put= aFinalTabSift[IndTaken][j]; aFinalTabSift[IndReceiv].resize(S+3,Val2Put); }*/ //cout<<"Size of the merged point : "<<aFinalTabSift[IndReceiv].size()<<endl; //cancel the value corresponding to aListPtMultiIni in aFinalTabSift aFinalTabSift.erase(aFinalTabSift.begin()+IndTaken); } cout<<"NB Quadruple ou plus : "<<Q2<<endl; //cout the number of point int NBSiftFinal = (int)aFinalTabSift.size(); cout<<"NB final restant: "<<NBSiftFinal<<endl; aListPtMulti.clear(); aListPtMultiIni.clear(); //-------------------Fabrication of a new list -------------------------// //////////just for verif /* string aOutputFileName3= aNameDir+ DirOut + "SumOfSiftData3.txt"; FILE *Ot = fopen(aOutputFileName3.c_str(), "a" ); for( int l=0;l<NBSiftFinal; l++) { int NB=aFinalTabSift[l].size(); for ( int m=0;m<NB; m++) {double maVal=aFinalTabSift[l][m]; //fill the vectors with all the elements fprintf(Ot,"% 1.1f",maVal );//write the file just for control } fprintf(Ot,"\n"); } fclose(Ot); */ //loop for know where are the change of image in the vector aFinalTabSift[j][0] int ValueN=0; vector<int> aIndexImageN; aIndexImageN.push_back(0); for (int j=0;j<NBSiftFinal;j++) {int ValIndex=aFinalTabSift[j][0]; if(ValIndex==ValueN+1) {aIndexImageN.push_back(j); cout<<"nb : "<<j<<endl; ValueN=ValueN+1; } } aIndexImageN.push_back(NBSiftFinal);//add the last value int p = (int)aIndexImageN.size(); cout<<"size IndexIm : "<<p<<endl; cout<<"nombre d'image : "<<nbIm<<endl; //-----------------------Non-double point detection and cancelation-----------------// //DETECTION PART //Declare vector which will contains the points who have the same coordinate vector<double> aListSimple,aListSimpleIni; for (int i=0;i<nbIm-1;i++) { int Alimitinf=aIndexImageN[i]; int Alimitsup=aIndexImageN[i+1]; //fill the vector of the n° of ligne of the multiple point //cout<<Alimitinf<<" & "<<Alimitsup<<endl; double diff1=10; double diff2=10; for (int h=Alimitinf;h<Alimitsup;h++) { int ValInd1=aFinalTabSift[h][0]; double Valrefx=aFinalTabSift[h][1]; double Valrefy=aFinalTabSift[h][2]; //run the rest of the point on the other images in order to find the next same point for (int l=Alimitsup;l<NBSiftFinal;l++) { int ValInd2=aFinalTabSift[l][3]; double Valcompx=aFinalTabSift[l][4]; double Valcompy=aFinalTabSift[l][5]; diff1=abs(Valcompx-Valrefx); diff2=abs(Valcompy-Valrefy); if(ValInd1==ValInd2 && diff1<0.1 && diff2<0.1) { //cout<<Valrefx<<" & "<<Valrefy<<endl; //cout<<h<<endl; //cout<<Valcompx<<" & "<<Valcompy<<endl; //cout<<l<<endl; //cout<<"Size of the point : "<<aFinalTabSift[h].size()<<endl; //get the value double ValInD=aFinalTabSift[l][0]; double ValX=aFinalTabSift[l][1]; double ValY=aFinalTabSift[l][2]; aFinalTabSift[h].push_back(ValInD),aFinalTabSift[h].push_back(ValX),aFinalTabSift[h].push_back(ValY); //cout<<"Size of the merged point : "<<aFinalTabSift[h].size()<<endl; aListSimple.push_back(l); aListSimpleIni.push_back(h); } //if(diffx<1.0 && diffy<1.0) break;//condition to accept that is the same point } } } //CANCELLATION PART int Z = (int)aListSimple.size(); cout<<"Nombre de Point Oubliés : "<<Z<<endl; int Q3=0; for (int i=0;i<Z; i++) {int L=aListSimple[i]; //cout<<"valeur de l "<<L<<endl; for (int j=0;j<Z; j++) {int H=aListSimpleIni[j]; //cout<<"valeur de h "<<H<<endl; if (H==L) {//cout<<"l'indice "<<i<<" vaut "<<j<<endl; Q3=Q3+1;} } } cout<<"NB pts Oubliés 2 fois ou plus : "<<Q3<<endl; sort( aListSimple.begin(),aListSimple.end() ); for (int i=Z-1;i>=0; i--) { long Val=aListSimple[i]; //cout<<"Val :"<<Val<<endl; aFinalTabSift.erase(aFinalTabSift.begin()+Val); } int NBTiePointFinal = (int)aFinalTabSift.size(); cout<<"NB restant: "<<NBTiePointFinal<<endl; /* //-------------------Fabrication of a new list -------------------------// //////////just for verif string aOutputFileName4= aNameDir+ DirOut + "SumOfSiftData4.txt"; FILE *Ou = fopen(aOutputFileName4.c_str(), "a" ); for( int l=0;l<NBTiePointFinal; l++) { int NB=aFinalTabSift[l].size(); for ( int m=0;m<NB; m++) {double maVal=aFinalTabSift[l][m]; //fill the vectors with all the elements fprintf(Ou,"% 1.1f",maVal );//write the file just for control } fprintf(Ou,"\n"); } fclose(Ou); */ return aFinalTabSift; } vector<vector<double> > GlobalCorrectionTiePoint(string aNameDir, string aPattern, string DirOut, string aOri, int ExpTxt, bool ExpTieP) //not finished yet { //load the data from the previous function vector<vector<double> > aFinalTabSift=CorrectTiePoint(aNameDir, aPattern, DirOut, ExpTxt); int NBTiePoints = (int)aFinalTabSift.size(); //Reading the list of input files list<string> ListIm=RegexListFileMatch(aNameDir,aPattern,1,false); int nbIm = (int)ListIm.size(); //loop for know where are the change of image in the vector aFullTabSift[j][0] int Value =0; vector<int> aIndexImage; aIndexImage.push_back(0); for (int j=0;j<NBTiePoints;j++) {int ValIndex=aFinalTabSift[j][0]; if(ValIndex==Value+1) {aIndexImage.push_back(j); //cout<<"nb : "<<j<<endl; Value=Value+1; } } aIndexImage.push_back(NBTiePoints);//add the last value cout<<"Global initialisation for correction ok !"<<endl; //-----------------------Global detection and cancelation-----------------// //DETECTION PART //Declare vector which will contains the points who have the same coordinate vector<double> aList,aListIni; for (int i=0;i<nbIm-1;i++) { int Alimitinf=aIndexImage[i]; int Alimitsup=aIndexImage[i+1]; //fill the vector of the n° of ligne of the multiple point //cout<<Alimitinf<<" & "<<Alimitsup<<endl; double diff1=10; double diff2=10; for (int h=Alimitinf;h<Alimitsup;h++) {//iterate the number of point of the same image int S1 = (int)(aFinalTabSift[h].size() / 3); //run the rest of the point on the other images in order to find a next point with a same measurement for (int l=Alimitsup;l<NBTiePoints;l++) {//iterate the number of point of the others images int S2 = (int)(aFinalTabSift[l].size() / 3); int exitNumber=0; for ( int i=1; i<S1; i++) { int ValInd1=aFinalTabSift[h][3*i]; double Valrefx=aFinalTabSift[h][3*i+1]; double Valrefy=aFinalTabSift[h][3*i+2]; int j=0; while (j<S2) { int ValInd2=aFinalTabSift[l][j*3]; double Valcompx=aFinalTabSift[l][j*3+1]; double Valcompy=aFinalTabSift[l][j*3+2]; diff1=abs(Valcompx-Valrefx); diff2=abs(Valcompy-Valrefy); if(ValInd1==ValInd2 && diff1<0.1 && diff2<0.1) {aList.push_back(l),aListIni.push_back(h); exitNumber=l; //cout<<Valrefx<<" & "<<Valrefy<<endl; //cout<<h<<endl; //cout<<Valcompx<<" & "<<Valcompy<<endl; //cout<<l<<endl; //get the value } j=j+1; //we do only detection if(ValInd1==ValInd2 && diff1<0.1 && diff2<0.1) break;//condition to accept that is the same point } if (j!=S2+1) break; } if (exitNumber!=0) break; } } } //CANCELLATION PART int Z = (int)(aList.size()); cout<<"Nombre de Point réécris : "<<Z<<endl; int Q=0; for (int i=0;i<Z; i++) {int L=aList[i]; //cout<<"valeur de l "<<L<<endl; for (int j=0;j<Z; j++) {int H=aListIni[j]; //cout<<"valeur de h "<<H<<endl; if (H==L) {//cout<<"l'indice "<<i<<" vaut "<<j<<endl; Q=Q+1;} } } cout<<"NB pts réécris 2 fois ou plus : "<<Q<<endl; for (int i=0;i<Z; i++) { long IndVal1=aListIni[i]-i; long IndVal2=aList[i]-i; int S1 = (int)(aFinalTabSift[IndVal1].size() / 3); int S2 = (int)(aFinalTabSift[IndVal2].size() / 3); //cout<<"Val :"<<Val<<endl; for (int j=0;j<S1;j++) {//iterate for every measurement int Ind1=aFinalTabSift[IndVal1][j*3]; int k=0; while (k<S2) { int Ind2=aFinalTabSift[IndVal2][k*3]; if (Ind1==Ind2) break; //if the same value, measurement already exist k=k+1; } if(k==S2)//if not k==S2, add the value of Ind1 to Ind2 position {double VX=aFinalTabSift[IndVal1][j*3+1]; double VY=aFinalTabSift[IndVal1][j*3+2]; aFinalTabSift[IndVal2].push_back(Ind1),aFinalTabSift[IndVal2].push_back(VX),aFinalTabSift[IndVal2].push_back(VY); } } aFinalTabSift.erase(aFinalTabSift.begin()+IndVal1); } int NBTiePointFinal = (int)aFinalTabSift.size(); cout<<"NB restant: "<<NBTiePointFinal<<endl; //------------------------- Tie Points corrected for distorsion---------------------//Actually-Not-Yet //define Boundaries and list of camera int SizeImX=10000; int SizeImY=10000; vector<CamStenope *> aCam; for (int i=0;i<nbIm;i++) { string aFullName=ListIm.front(); //cout<<aFullName<<" ("<<i+1<<" of "<<nbIm<<")"<<endl; ListIm.pop_front(); //Formating the camera name string aNameCam="Ori-"+ aOri + "/Orientation-" + aFullName + ".xml"; //Loading the camera cInterfChantierNameManipulateur * anICNM = cInterfChantierNameManipulateur::BasicAlloc(aNameDir); CamStenope * aCS = CamOrientGenFromFile(aNameCam,anICNM); aCam.push_back(aCS); if (i==nbIm-1) {Tiff_Im aTF= Tiff_Im::StdConvGen(aNameDir + aFullName,3,false); //We suppose here that all the images have the same size, otherwise it will need a list of SizeIm... SizeImX =aTF.sz().x; SizeImY =aTF.sz().y; } } cout<<"Length of images : "<<SizeImX<<" & "<<" width of the images : "<<SizeImY<<endl; //make a comment std::string aCom = "Undistorting points" + std::string(" +Ext=") + (ExpTxt?"txt":"dat"); std::cout << "Com = " << aCom << "\n"; // Correction of the distorsion for sift point, no need to sampled after correction int P=0; int R=0; for (int j=0;j<NBTiePointFinal;j++) { int T = (int)(aFinalTabSift[j].size() / 3); for (int k=0;k<T;k++) { int indice=aFinalTabSift[j][3*k]; CamStenope * aCS=aCam[indice]; Pt2dr ptOut; Pt2dr NewPt( aFinalTabSift[j][3*k+1], aFinalTabSift[j][3*k+2]); ptOut=aCS->DistDirecte(NewPt);//here use only for filtered the UndistortIMed data double ValX=NewPt.x;//so no change for x double ValY=NewPt.y;//so no change for y //if the value UndistortIM is not in the space image, go to the next measurement if (ValX>SizeImX || ValY>SizeImY || ValX<0 || ValY<0) {k=k+1,R=R+1;} else {aFinalTabSift[j][k*3+1]=ValX; aFinalTabSift[j][k*3+2]=ValY; //cout<<"Point ancien: "<<NewPt<<endl; //cout<<"Point nouveau: "<<ptOut<<endl; P=P+1;} } } cout<<"Nombre de Point 2D out: "<<R<<endl; cout<<"Nombre de Point 2D: "<<P<<endl; if ( ExpTieP !=0) { //-------------------Fabrication of a new list -------------------------// //////////just for verif string aOutputFileName= aNameDir+ DirOut + "OriginalTiePtsList.txt"; FILE *Ou = fopen(aOutputFileName.c_str(), "a" ); int NBTiePointF = (int)aFinalTabSift.size(); for( int l=0;l<NBTiePointF; l++) { int NB = (int)aFinalTabSift[l].size(); for ( int m=0;m<NB; m++) {double maVal=aFinalTabSift[l][m]; //fill the vectors with all the elements if (mod(m,3)==0) {fprintf(Ou,"%2.0f",maVal );} else{fprintf(Ou,"% 1.2f",maVal );} } fprintf(Ou,"\n"); } fclose(Ou); } return aFinalTabSift; } vector<double> LeastSquareSolv(vector<double> &centre1, vector<double> &Vdirecteur1, vector<double> &centre2, vector<double> &Vdirecteur2) { ////////Least square resolution//////// //initialisation double alpha0=1; double beta0=1; ElMatrix<double> A(2,3,0.0); ElMatrix<double> B(1,3,0.0); ElMatrix<double> dX(1,2,0.0); ElMatrix<double> N(2,2,0.0); ElMatrix<double> Atr(3,2,0.0); ElMatrix<double> Ninv(2,2,0.0); A(0,0)=Vdirecteur1[0]; A(1,0)=-Vdirecteur2[0]; A(0,1)=Vdirecteur1[1]; A(1,1)=-Vdirecteur2[1]; A(0,2)=Vdirecteur1[2]; A(1,2)=-Vdirecteur2[2]; //here apha0 and beta0 useless because=1 but still written for formalism B(0,0)=-centre1[0]+centre2[0]-alpha0*Vdirecteur1[0]+beta0*Vdirecteur2[0]; B(0,1)=-centre1[1]+centre2[1]-alpha0*Vdirecteur1[1]+beta0*Vdirecteur2[1]; B(0,2)=-centre1[2]+centre2[2]-alpha0*Vdirecteur1[2]+beta0*Vdirecteur2[2]; //transposed matrix Atr(0,0)=Vdirecteur1[0]; Atr(0,1)=-Vdirecteur2[0]; Atr(1,0)=Vdirecteur1[1]; Atr(1,1)=-Vdirecteur2[1]; Atr(2,0)=Vdirecteur1[2]; Atr(2,1)=-Vdirecteur2[2]; //resolution N=Atr*A; //calcul of the inverse double K=1/(N(0,0)*N(1,1)-(N(1,0)*N(0,1))); //cout<<K<<endl; Ninv(0,0)=N(1,1), Ninv(0,1)=-N(0,1),Ninv(1,1)=N(0,0), Ninv(1,0)=-N(1,0); Ninv=Ninv*K; //calcul of the residus dX=Ninv*Atr*B; //Vc=B-A*dX; //Sig02=Vc'*Vc; double Alphafi=alpha0+dX(0,0); double Betafi=beta0+dX(0,1); //calculate the point double Xpt=(centre1[0]+Alphafi*Vdirecteur1[0]+centre2[0]+Betafi*Vdirecteur2[0])*0.5; double Ypt=(centre1[1]+Alphafi*Vdirecteur1[1]+centre2[1]+Betafi*Vdirecteur2[1])*0.5; double Zpt=(centre1[2]+Alphafi*Vdirecteur1[2]+centre2[2]+Betafi*Vdirecteur2[2])*0.5; //cout<<" x: "<<Xpt<<" & "<<" y: "<<Ypt<<" & "<<" z: "<<Zpt<<endl; vector<double> aPt3D; aPt3D.push_back(Xpt), aPt3D.push_back(Ypt), aPt3D.push_back(Zpt); return aPt3D; } void Triangulation(string aNameDir, string aPattern, string aOri, string DirOut, int ExpTxt, bool ExpTieP, vector<vector<double> > &aFullTabTiePoint) { vector<vector<double> > aFinalTabSift=GlobalCorrectionTiePoint(aNameDir, aPattern, DirOut, aOri, ExpTxt, ExpTieP); //Reading the list of input files list<string> ListIm=RegexListFileMatch(aNameDir,aPattern,1,false); int nbIm = (int)ListIm.size(); //cout<<"Number of images to process: "<<nbIm<<endl; vector<CamStenope *> aCam; vector<Pt3dr> aListPtCentre; vector<double> aDeepth; //define Boundaries and list of camera int SizeImX=10000; int SizeImY=10000; // And find the centre and read the camera of evry image for (int i=0;i<nbIm;i++) { //Reading the images list string aFullName=ListIm.front(); ListIm.pop_front(); //cancel images once read //Formating the camera name string aNameCam="Ori-"+ aOri + "/Orientation-" + aFullName + ".xml"; //Loading the camera cInterfChantierNameManipulateur * anICNM = cInterfChantierNameManipulateur::BasicAlloc(aNameDir); CamStenope * aCS = CamOrientGenFromFile(aNameCam,anICNM); aCam.push_back(aCS); //get some values double aProf=aCS->GetProfondeur(); aDeepth.push_back(aProf); //double x=aCS->VraiOpticalCenter().x ... //another way to find the centre Pt2dr aPtcentre(1000.0, 1000.0); Pt3dr centre=aCS->ImEtProf2Terrain(aPtcentre,0.0); aListPtCentre.push_back(centre); cout<<"centre Image "<<i<<" : "<<centre<<endl; //get the size ot the images if (i==nbIm-1) {Tiff_Im aTF= Tiff_Im::StdConvGen(aNameDir + aFullName,3,false); //We suppose here that all the images have the same size, otherwise it will need a list of SizeIm... SizeImX =aTF.sz().x; SizeImY =aTF.sz().y; } } cout<<"Length of the images : "<<SizeImX<<" & "<<" width of the images : "<<SizeImY<<endl; //make a comment std::string aCom = "Undistorting points" + std::string(" +Ext=") + (ExpTxt?"txt":"dat"); std::cout << "Com = " << aCom << "\n"; //////UndistortIMing tie points //////make list of centre and direction vector for each ligne int NPt = (int)aFinalTabSift.size(); //int P=0; //int R=0; //vector<vector<double> > aFullTabTiePoint;//=aFinalTabSift with the cancellated point vector<vector<double> > aFullTabDroite; for (int j=0;j<NPt;j++) { vector<double> aTabDroite; vector<double> aTiePt; int T = (int)(aFinalTabSift[j].size() / 3); for (int k=0;k<T;k++) { int indice=aFinalTabSift[j][3*k]; //recuperate the camera, the centrer and the profondeur CamStenope * aCS=aCam[indice]; Pt3dr aPtCentr=aListPtCentre[indice]; double aProfIm=aDeepth[indice]; Pt2dr aPtIm(aFinalTabSift[j][3*k+1], aFinalTabSift[j][3*k+2]); //use of profondeur for put the point in 3d Pt3dr aPtTer=aCS->ImEtProf2Terrain(aPtIm, aProfIm); //Calculate the point UndistortIMed Pt2dr ptOut; ptOut=aCS->DistDirecte(aPtIm); double ValX=ptOut.x; double ValY=ptOut.y; //if the value UndistortIM is not in the space image, go to the next measurement if (ValX>SizeImX || ValY>SizeImY || ValX<0 || ValY<0) {k=k+1;}//R=R+1; else { double xc,yc,zc,vx,vy,vz; xc=aPtCentr.x; yc=aPtCentr.y; zc=aPtCentr.z; vx=aPtTer.x; vy=aPtTer.y; vz=aPtTer.z; aTabDroite.push_back(xc),aTabDroite.push_back(yc),aTabDroite.push_back(zc); aTabDroite.push_back(vx-xc),aTabDroite.push_back(vy-yc),aTabDroite.push_back(vz-zc); double Ind=indice; aTiePt.push_back(Ind),aTiePt.push_back(ValX),aTiePt.push_back(ValY); //cout<<"Point ancien: "<<NewPt<<endl; //cout<<"Point nouveau: "<<ptOut<<endl; }//P=P+1; } if (aTabDroite.size() >=12)//we keep if only tow or more new point are inside the box {aFullTabDroite.push_back(aTabDroite); aFullTabTiePoint.push_back(aTiePt); } } //supression of the previous tab of tie points aFinalTabSift.clear(); int NewNBLimit = (int)aFullTabTiePoint.size(); cout<<"nombre de points final : "<<NewNBLimit<<endl; cout<<"fini list of droite !"<<endl; cout<<"Begin 3D intersection"<<endl; ///////////////////////intersection in 3D space////////////////////////////////// vector<vector<double> > aTabPoint3D; for (int j=0;j<NewNBLimit;j++) //NewNBLimit { vector<vector<double> > aSolForaPt; int T = (int)(aFullTabDroite[j].size() / 6); //we work only with couple of point for (int k=0;k<T-1;k++) {//initialise data for first point vector<double> C1; vector<double> V1; C1.push_back(aFullTabDroite[j][6*k]),C1.push_back(aFullTabDroite[j][6*k+1]),C1.push_back(aFullTabDroite[j][6*k+2]); V1.push_back(aFullTabDroite[j][6*k+3]),V1.push_back(aFullTabDroite[j][6*k+4]),V1.push_back(aFullTabDroite[j][6*k+5]); //initialise data for second point int l=k+1; while (l<T) { vector<double> C2; vector<double> V2; C2.push_back(aFullTabDroite[j][6*l]),C2.push_back(aFullTabDroite[j][6*l+1]),C2.push_back(aFullTabDroite[j][6*l+2]); V2.push_back(aFullTabDroite[j][6*l+3]),V2.push_back(aFullTabDroite[j][6*l+4]),V2.push_back(aFullTabDroite[j][6*l+5]); //solve the intersection vector<double> aPt3D=LeastSquareSolv(C1,V1,C2,V2); aSolForaPt.push_back(aPt3D); l=l+1; } } //do a mean of every x,y,z and push_back the final x,y,z table int N = (int)aSolForaPt.size(); if (N>1) { double X=0;double Y=0;double Z=0; vector<double> aSolPtmean; for (int i=0;i<N;i++) { X=X+aSolForaPt[i][0]; Y=Y+aSolForaPt[i][1]; Z=Z+aSolForaPt[i][2]; } double Mx=X/N;double My=Y/N;double Mz=Z/N; aSolPtmean.push_back(Mx),aSolPtmean.push_back(My),aSolPtmean.push_back(Mz); aTabPoint3D.push_back(aSolPtmean); } //if size=1 dont require the mean operation else {aTabPoint3D.push_back(aSolForaPt[0]);} //aSolForaPt.clear();needent } //-------------------Fabrication of a new lists -------------------------// //////////just for verif/////List1 string aOutputFileName= aNameDir+ DirOut + "DroitesList.txt"; FILE *Ou = fopen(aOutputFileName.c_str(), "a" ); for( int l=0;l<NewNBLimit; l++) { int NB = (int)aFullTabDroite[l].size(); for ( int m=0;m<NB; m++) {double maVal=aFullTabDroite[l][m]; //fill the vectors with all the elements fprintf(Ou,"%-10.6f",maVal ); } fprintf(Ou,"\n"); } fclose(Ou); ////////////////////////List2 string aOutputFileName2= aNameDir+ DirOut + "3DPtsList.txt"; FILE *Out = fopen(aOutputFileName2.c_str(), "a" ); for( int l=0;l<NewNBLimit; l++) { for ( int m=0;m<3; m++) {double maVal=aTabPoint3D[l][m]; //fill the vectors with all the elements fprintf(Out,"%-10.6f",maVal ); } fprintf(Out,"\n"); } fclose(Out); ///////////////////List3 string aOutputFileName3= aNameDir+ DirOut + "TiePtsUndistortedList.txt"; FILE *Ouv = fopen(aOutputFileName3.c_str(), "a" ); for( int l=0;l<NewNBLimit; l++) {int NB = (int)aFullTabTiePoint[l].size(); for ( int m=0;m<NB; m++) {double maVal=aFullTabTiePoint[l][m]; //fill the vectors with all the elements if (mod(m,3)==0) {fprintf(Ouv,"%2.0f",maVal );} else{fprintf(Ouv,"% 1.2f",maVal );} } fprintf(Ouv,"\n"); } fclose(Ouv); cout<<"listes of points written"<<endl; //return aFullTabTiePoint; } void UndistortIM(string aNameDir, string aPattern, string aOri, string DirOut, bool KeepImC) { if (KeepImC==1) {//if KeepImC==0 the undistortion will be done after in the last function //Reading the list of input files list<string> ListIm=RegexListFileMatch(aNameDir,aPattern,1,false); int nbIm = (int)ListIm.size(); cout<<"Number of images to process: "<<nbIm<<endl; string cmdDRUNK,cmdConv,cmdDel; list<string> ListDrunk,ListConvert,ListDel; for (int i=0;i<nbIm;i++) { //Reading the images list string aFullName=ListIm.front(); //cout<<aFullName<<" ("<<i+1<<" of "<<nbIm<<")"<<endl; ListIm.pop_front(); //cancel images once read //Creating the lists of DRUNK and Convert commands //new images will be in the data folder cmdDRUNK=MMDir() + "bin/Drunk " + aNameDir + aFullName + " " + aOri + " " + "Out="+ DirOut; ListDrunk.push_back(cmdDRUNK); #if (ELISE_unix || ELISE_Cygwin || ELISE_MacOs) cmdConv="convert " + aNameDir + DirOut + aFullName + ".tif " + aNameDir + DirOut + aFullName + ".jpg"; cmdDel = "rm " + aNameDir + DirOut + aFullName + ".tif "; #endif #if (ELISE_windows) cmdConv=MMDir() + "binaire-aux/windows/convert.exe " + aNameDir + DirOut + aFullName + ".tif " + aNameDir + DirOut + aFullName + ".jpg"; cmdDel = "del " + aNameDir + DirOut + aFullName + ".tif "; #endif ListConvert.push_back(cmdConv); ListDel.push_back(cmdDel); }//end of "for each image" //Undistorting the images with Drunk cout<<"Undistorting the images with Drunk"<<endl; cEl_GPAO::DoComInParal(ListDrunk,aNameDir + "MkDrunk"); //Converting into .jpg (CV solution may not use .tif) with Convert cout<<"Converting into .jpg"<<endl; cEl_GPAO::DoComInParal(ListConvert,aNameDir + "MkConvert"); //Removing .tif cout << "Removing .tif" << endl; cEl_GPAO::DoComInParal(ListDel, aNameDir + "MkDel"); } } vector <double> MakeQuaternion (CamStenope * aCS, ElMatrix<double> Rotc ) { //how to make the quaternion ? vector <double> aQuaterion; ElMatrix<double> R(3,3,0.0); ElMatrix<double> Rot(3,3,0.0); R=aCS->Orient().Mat(); double epsilon=0.000001; double z=0.5*pow(abs((1+R(0,0)+R(1,1)+R(2,2))),0.5); Rot=Rotc*R; double b=0;double c=0;double d=0; double a=0.5*pow(abs((1+Rot(0,0)+Rot(1,1)+Rot(2,2))),0.5); //double a2=-a; //division by zero forbidden if (a<epsilon) { if (Rot(0,0)>=1.0-epsilon && Rot(0,0)<=1.0+epsilon) {b=1;} if (Rot(1,1)>=1-epsilon && Rot(1,1)<=1+epsilon) {c=1;} if (Rot(2,2)>=1-epsilon && Rot(2,2)<=1+epsilon) {d=1;} } else { b=0.25*(Rot(1,2)-Rot(2,1))/a; c=0.25*(Rot(2,0)-Rot(0,2))/a; d=0.25*(Rot(0,1)-Rot(1,0))/a; } //manage arrond problem if (z<epsilon) { if (R(0,0)>=1.0-epsilon && R(0,0)<=1.0+epsilon) {b=pow(1-a*a-c*c-d*d,0.5); } if (R(1,1)>=1-epsilon && R(1,1)<=1+epsilon) {c=pow(1-a*a-b*b-d*d,0.5); } if (R(2,2)>=1-epsilon && R(2,2)<=1+epsilon) {d=pow(1-a*a-b*b-c*c,0.5); } } else { double K=pow(a*a+b*b+c*c+d*d,0.5); a=a/K; b=b/K; c=c/K; d=d/K; } aQuaterion.push_back(a),aQuaterion.push_back(b),aQuaterion.push_back(c),aQuaterion.push_back(d); cout<<a<<" & "<<b<<" & "<<c<<" & "<<d<<endl; return aQuaterion; } ElMatrix<double> CorrectRotation (double f, Pt2dr PP, bool KeepImC) { //We make a little rotation in order to correct the difference between PP and image centre double fx=pow(f*f+PP.x*PP.x,0.5); double fy=pow(f*f+PP.y*PP.y,0.5); //shift in x is rotation in y, and shift in y is rotation in x double cosa=f/fy; double cosb=f/fx; double sina=PP.y/fy; double sinb=-PP.x/fx; //cout<<"cosinus : "<<cosa<<" & "<<cosb<<" sinus : "<<sina<<" & "<<sinb<<endl; ElMatrix<double> Rotc(3,3,0.0);//rotation matrix initialized at 0 if (KeepImC==1) {Rotc(0,0)=1;Rotc(1,1)=1;Rotc(2,2)=1;} else { Rotc(0,0)=cosb; Rotc(2,0)=-sinb; Rotc(0,1)=sina*sinb; Rotc(1,1)=cosa; Rotc(2,1)=sina*cosb; Rotc(0,2)=cosa*sinb; Rotc(1,2)=-sina; Rotc(2,2)=cosa*cosb; cout<<"handle the difference between PP and Image centre"<<endl; } return Rotc; } Pt2dr CorrectDecentre(double f, Pt2dr PP, Pt2di DSizeIm, Pt2dr PtIn, ElMatrix<double> Rotc ) { //Plan to Plan Projection, for each point just a scale factor k to find double d=(f*f)+(PP.x*PP.x)+(PP.y*PP.y); double DX=PtIn.x-DSizeIm.x; double DY=PtIn.y-DSizeIm.y; //DZ=f; double k=d/(PP.x*DX+PP.y*DY+f*f); //Matrix inverse rotation ElMatrix<double> Rotinv(3,3,0.0);//Inverse rotation matrix initialized at 0 Rotinv(0,0)=Rotc(0,0); Rotinv(0,1)=Rotc(1,0); Rotinv(0,2)=Rotc(2,0); Rotinv(1,0)=Rotc(0,1); Rotinv(1,1)=Rotc(1,1); Rotinv(1,2)=Rotc(2,1); Rotinv(2,0)=Rotc(0,2); Rotinv(2,1)=Rotc(1,2); Rotinv(2,2)=Rotc(2,2); ElMatrix<double> PtSpace(1,3,0.0);//point initialized for inverse rotation ElMatrix<double> PtSpaceF(1,3,0.0);//point resulted with the inverse rotation PtSpace(0,0)=k*DX;PtSpace(0,1)=k*DY;PtSpace(0,2)=k*f; //obtained the 3D point in the space PtSpaceF=Rotinv*PtSpace; //Z forgotten for the image Pt2dr PtOut(PtSpaceF(0,0)+PP.x+DSizeIm.x,PtSpaceF(0,1)+PP.y+DSizeIm.y); return PtOut; } void TransfORI_andWFile(string aNameDir, string aPattern, string aOri, string DirOut, string aNAME, vector<vector<double> > aFullTabTiePoint, bool ExpCloud, bool KeepImC) { //Reading the list of input files list<string> ListIm=RegexListFileMatch(aNameDir,aPattern,1,false); int nbIm = (int)ListIm.size(); cout<<"Convert the Orientations"<<endl; //initialiezd every list of internal data and its name // And define boundaries and list of camera vector<string> aListUndImName; vector<double> aListFocalOri; vector<Pt2di> aListDImSize; vector<Pt2dr> aListDeltaPP; vector<double> aListFocalF; vector<Pt3dr> aListPtCentre; ElMatrix<double> Rotc(3,3,0.0); vector<vector<double> > alistQuaternion; string cmdConv,cmdDel; list<string> ListConvert,ListDel; // And find the centre and read the camera of evry image for (int i=0;i<nbIm;i++) { //Reading the images list string aFullName=ListIm.front(); ListIm.pop_front(); //cancel images once read //Formating the camera name string aNameCam="Ori-"+ aOri + "/Orientation-" + aFullName + ".xml"; //get the name of Undistorted images string UndImName=aFullName + ".jpg"; aListUndImName.push_back(UndImName); string aNameOut=aNameDir + aFullName + ".tif"; //Loading the camera cInterfChantierNameManipulateur * anICNM = cInterfChantierNameManipulateur::BasicAlloc(aNameDir); CamStenope * aCS = CamOrientGenFromFile(aNameCam,anICNM); //get the Undistorted images Tiff_Im aTF= Tiff_Im::StdConvGen(aNameDir+ aFullName,3,false); //get the focal lenght double FocL=aCS->Focale(); aListFocalOri.push_back (FocL); //get the half size/centre of the images Pt2di aSz=aTF.sz(); Pt2di aDSize=aSz/2; aListDImSize.push_back (aDSize); //cout<<"Valeur Demi Image : "<<aDSize.x<<" & "<<aDSize.y<<endl; //get the Principal Point Pt2dr PP=aCS->PP(); Pt2dr DeltaPP(PP.x+0.5-aDSize.x, PP.y+0.5-aDSize.y); aListDeltaPP.push_back (DeltaPP); //calcul adjustement between PP and image centre double F=pow(FocL*FocL+DeltaPP.x*DeltaPP.x+DeltaPP.y*DeltaPP.y,0.5); aListFocalF.push_back(F); Rotc=CorrectRotation (FocL, DeltaPP, KeepImC); //correction of decentring //------------------------Fabrication of the Undistorted and Decentred image----------------------------// if (KeepImC==0) { Im2D_U_INT1 aImR(aSz.x,aSz.y); Im2D_U_INT1 aImG(aSz.x,aSz.y); Im2D_U_INT1 aImB(aSz.x,aSz.y); Im2D_U_INT1 aImROut(aSz.x,aSz.y); Im2D_U_INT1 aImGOut(aSz.x,aSz.y); Im2D_U_INT1 aImBOut(aSz.x,aSz.y); ELISE_COPY ( aTF.all_pts(), aTF.in(), Virgule(aImR.out(),aImG.out(),aImB.out()) ); U_INT1 ** aDataR = aImR.data(); U_INT1 ** aDataG = aImG.data(); U_INT1 ** aDataB = aImB.data(); U_INT1 ** aDataROut = aImROut.data(); U_INT1 ** aDataGOut = aImGOut.data(); U_INT1 ** aDataBOut = aImBOut.data(); //Parcours des points de l'image de sortie et remplissage des valeurs cout<<"Undistorting and shifting the image"<<endl; Pt2dr ptOut;Pt2dr ptIn; double x; double y; for (int aY=0 ; aY<aSz.y ; aY++) { for (int aX=0 ; aX<aSz.x ; aX++) { x=aX; y=aY; ptIn.x=x; ptIn.y=y; ptIn=aCS->DistDirecte(ptIn); ptOut=CorrectDecentre(FocL, DeltaPP, aDSize, ptIn, Rotc ); aDataROut[aY][aX] = Reechantillonnage::biline(aDataR, aSz.x, aSz.y, ptOut); aDataGOut[aY][aX] = Reechantillonnage::biline(aDataG, aSz.x, aSz.y, ptOut); aDataBOut[aY][aX] = Reechantillonnage::biline(aDataB, aSz.x, aSz.y, ptOut); } } Tiff_Im aTOut ( aNameOut.c_str(), aSz, GenIm::u_int1, Tiff_Im::No_Compr, Tiff_Im::RGB ); ELISE_COPY ( aTOut.all_pts(), Virgule(aImROut.in(),aImGOut.in(),aImBOut.in()), aTOut.out() ); #if (ELISE_unix || ELISE_Cygwin || ELISE_MacOs) cmdConv="convert " + aNameDir + aFullName + ".tif " + aNameDir + DirOut + aFullName + ".jpg"; cmdDel = "rm " + aNameDir + aFullName + ".tif"; #endif #if (ELISE_windows) cmdConv=MMDir() + "binaire-aux/windows/convert.exe ephemeral:" + aNameDir + aFullName + ".tif " + aNameDir + DirOut + aFullName + ".jpg"; cmdDel = "del " + aNameDir + aFullName + ".tif"; #endif ListConvert.push_back(cmdConv); ListDel.push_back(cmdDel); } /////////////////////////////////////////// //get some values //double x=aCS->VraiOpticalCenter().x ... //another way to find the centre Pt2dr aPtcentre(1000.0, 1000.0); Pt3dr centre=aCS->ImEtProf2Terrain(aPtcentre,0.0); aListPtCentre.push_back(centre); //cout<<"centre Image "<<i<<" : "<<centre<<endl; //get the quaternion vector<double> aQuaternion=MakeQuaternion (aCS, Rotc); alistQuaternion.push_back(aQuaternion); } if (KeepImC==0) { cEl_GPAO::DoComInParal(ListConvert,aNameDir + "MkConvert"); } int N = (int)aFullTabTiePoint.size(); //////-------------------Fabrication of the final file -------------------------////// //if Point cloud Chosen initiate the ply file string aApeCloud= aNameDir+ DirOut + "3D.ply"; if (ExpCloud ==1) { FILE *Plyf = fopen(aApeCloud.c_str(), "a" ); fprintf(Plyf, "ply\n"); fprintf(Plyf, "format ascii 1.0\n"); fprintf(Plyf, "element vertex %d\n", N); fprintf(Plyf, "property float x\n"); fprintf(Plyf, "property float y\n"); fprintf(Plyf, "property float z\n"); fprintf(Plyf, "property uchar red\n"); fprintf(Plyf, "property uchar green\n"); fprintf(Plyf, "property uchar blue\n"); fprintf(Plyf, "element face 0\n"); fprintf(Plyf, "property list uchar int vertex_indices\n"); fprintf(Plyf, "end_header\n"); fclose(Plyf); cout<<"Writting the ply file"<<endl; } ///////////// Begin of NVM_File ////////////////// string aOutputFileName=aNameDir + DirOut + aNAME + ".nvm"; FILE *FOri = fopen(aOutputFileName.c_str(), "a" ); //Begin to write the file and the orientation fprintf(FOri,"NVM_V3\n" ); //FixedK %d %d %d %d\n",F,PPx,F,PPy fprintf(FOri,"\n"); fprintf(FOri,"%d\n",nbIm ); for( int i=0;i<nbIm; i++) {////write orientations////// string aName=aListUndImName[i]; double F=aListFocalF[i]; double VaQ1=alistQuaternion[i][0];double VaQ2=alistQuaternion[i][1];double VaQ3=alistQuaternion[i][2];double VaQ4=alistQuaternion[i][3]; double aX=aListPtCentre[i].x;double aY=aListPtCentre[i].y;double aZ=aListPtCentre[i].z; fprintf(FOri,"%-10.100s %-5.6f %-2.6f %-2.6f %-2.6f %-2.6f %-2.6f %-2.6f %-2.6f 0 0\n", aName.c_str(),F,VaQ1,VaQ2,VaQ3,VaQ4,aX,aY,aZ); } fprintf(FOri,"\n"); fprintf(FOri,"%d\n", N ); fclose(FOri); //call pts 3D list to include and continue to build the file double n1,n2,n3; string aReadFileNameP3= aNameDir+ DirOut + "3DPtsList.txt"; FILE *If = fopen(aReadFileNameP3.c_str(), "r" ); FILE *Of = fopen(aOutputFileName.c_str(), "a" ); for ( int i=0;i<N; i++) { int aNbVal = fscanf(If, "%lf %lf %lf\n", &n1, &n2, &n3); ELISE_ASSERT(aNbVal==3,"Bad nb val while scanning file in TransfORI_andWFile"); int Sz=aFullTabTiePoint[i].size()/3.0; fprintf(Of,"%-3.6f %-3.6f %-3.6f 128 128 128 %d",n1,n2,n3,Sz); //complete 3d ply if wanted if (ExpCloud ==1) { FILE *Plyf = fopen(aApeCloud.c_str(), "a" ); fprintf(Plyf, "%-3.6f %-3.6f %-3.6f 128 128 128\n",n1,n2,n3); fclose(Plyf); } //Add the measurement (0.5 pixel difference between the two Image system origin ) for (int j=0;j<Sz; j++) { int Indice=aFullTabTiePoint[i][3*j]; double X=0; double Y=0; Pt2dr PtOut; if (KeepImC==0) { Pt2dr PtIn(aFullTabTiePoint[i][3*j+1],aFullTabTiePoint[i][3*j+2]); PtOut=CorrectDecentre(aListFocalOri[Indice], aListDeltaPP[Indice], aListDImSize[Indice], PtIn, Rotc ); X=PtOut.x-aListDImSize[Indice].x+0.5; Y=PtOut.y-aListDImSize[Indice].y+0.5; } else { X=aFullTabTiePoint[i][3*j+1]-aListDImSize[Indice].x+0.5; Y=aFullTabTiePoint[i][3*j+2]-aListDImSize[Indice].y+0.5; } fprintf(Of,"% d %d %-4.6f %-4.6f",Indice,i,X,Y); } fprintf(Of,"\n"); } fclose(If); //build footer fprintf(Of,"\n"); fprintf(Of,"0\n"); fprintf(Of,"#the last part of NVM file points to the PLY files\n"); fprintf(Of,"#File generated by MicMac, a French and Open-Source solution\n"); if (KeepImC==0) {fprintf(Of,"#feature are corrected from distortion and shift among PP and Image centre\n");} else {fprintf(Of,"#feature are corrected from distortion\n");} fprintf(Of,"1 0\n"); fclose(Of); cout<<"file "<<aNAME<<".nvm written"<<endl; } int Apero2NVM_main(int argc,char ** argv) { std::string aFullPattern,aOri; // declaration of two arguments std::string aNAME="ORI"; // default value ( for optional args ) std::string DirOut="data/"; int ExpTxt=0; //bool CMPMVS; finally not done bool ExpTieP=0; bool ExpCloud=0; bool KeepImC=0; vector<vector<double> > aFullTabTiePoint; //std::vector<vector<string> > V_ImSift; //std::vector<vector<int> > Matrix_Index; ElInitArgMain ( //MMD_InitArgcArgv(argc,argv); argc , argv , // list of args LArgMain ()<< EAMC( aFullPattern , "Images Pattern", eSAM_IsPatFile ) //EAMC means mandatory argument << EAMC( aOri , "Orientation name", eSAM_IsExistDirOri ), LArgMain ()<< EAM( aNAME, "Nom", false, "NVM file name" )//EAM means optional argument //<< EAM(CMPMVS, "CMPMVS", false , "file mvs.ini & matrix contour" ) << EAM(DirOut,"Out",true,"Output folder (end with /)") << EAM(ExpTxt,"ExpTxt",true,"Point in txt format ? (Def=false)", eSAM_IsBool) << EAM(ExpCloud,"ExpApeCloud",false,"Exporte Ply? (Def=false)", eSAM_IsBool) << EAM(ExpTieP,"ExpTiePt",false,"Export list of Tie Points uncorrected of the distortion ?(Def=false)", eSAM_IsBool) << EAM(KeepImC,"KpImCen",false,"Dont add a little rotation for pass from Image Centre to PP ?(To be right fix LibPP=0 in tapas before)(Def=false)", eSAM_IsBool) ); std::string aPattern,aNameDir; SplitDirAndFile(aNameDir,aPattern,aFullPattern); StdCorrecNameOrient(aOri,aNameDir); //FindMatchFileAndIndex(aNameDir, aPattern, ExpTxt, &aVectImSift, &aMatrixIndex ); //CopyAndMergeMatchFile(aNameDir, aPattern, DirOut, ExpTxt); //CorrectTiePoint(aNameDir, aPattern, DirOut, ExpTxt); //GlobalCorrectionTiePoint(aNameDir, aPattern, DirOut, aOri, ExpTxt, ExpTieP); Triangulation(aNameDir, aPattern, aOri, DirOut, ExpTxt, ExpTieP, aFullTabTiePoint); UndistortIM(aNameDir, aPattern, aOri, DirOut, KeepImC); TransfORI_andWFile(aNameDir, aPattern, aOri, DirOut, aNAME, aFullTabTiePoint, ExpCloud, KeepImC); return EXIT_SUCCESS ; } /*Footer-MicMac-eLiSe-25/06/2007 Ce logiciel est un programme informatique servant à la mise en correspondances d'images pour la reconstruction du relief. Ce logiciel est régi par la licence CeCILL-B soumise au droit français et respectant les principes de diffusion des logiciels libres. Vous pouvez utiliser, modifier et/ou redistribuer ce programme sous les conditions de la licence CeCILL-B telle que diffusée par le CEA, le CNRS et l'INRIA sur le site "http://www.cecill.info". En contrepartie de l'accessibilité au code source et des droits de copie, de modification et de redistribution accordés par cette licence, il n'est offert aux utilisateurs qu'une garantie limitée. Pour les mêmes raisons, seule une responsabilité restreinte pÚse sur l'auteur du programme, le titulaire des droits patrimoniaux et les concédants successifs. A cet égard l'attention de l'utilisateur est attirée sur les risques associés au chargement, à l'utilisation, à la modification et/ou au développement et à la reproduction du logiciel par l'utilisateur étant donné sa spécificité de logiciel libre, qui peut le rendre complexe à manipuler et qui le réserve donc à des développeurs et des professionnels avertis possédant des connaissances informatiques DeltaPProfondies. Les utilisateurs sont donc invités à charger et tester l'adéquation du logiciel à leurs besoins dans des conditions permettant d'assurer la sécurité de leurs systÚmes et ou de leurs données et, plus généralement, à l'utiliser et l'exploiter dans les mêmes conditions de sécurité. Le fait que vous puissiez accéder à cet en-tête signifie que vous avez pris connaissance de la licence CeCILL-B, et que vous en avez accepté les termes. Footer-MicMac-eLiSe-25/06/2007*/
36.124833
181
0.638621
kikislater
ac0c8fea58f29416699ab25f04bc91ef92d5e0d1
762
cc
C++
sky/shell/platform/mojo/content_handler_impl.cc
abarth/sky_engine
e55063b0026f7a1aeda87ccb92fe5d9d09e8fc2e
[ "BSD-3-Clause" ]
1
2021-08-13T08:19:40.000Z
2021-08-13T08:19:40.000Z
sky/shell/platform/mojo/content_handler_impl.cc
abarth/sky_engine
e55063b0026f7a1aeda87ccb92fe5d9d09e8fc2e
[ "BSD-3-Clause" ]
null
null
null
sky/shell/platform/mojo/content_handler_impl.cc
abarth/sky_engine
e55063b0026f7a1aeda87ccb92fe5d9d09e8fc2e
[ "BSD-3-Clause" ]
null
null
null
// Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "flutter/sky/shell/platform/mojo/content_handler_impl.h" #include "flutter/sky/shell/platform/mojo/application_impl.h" namespace sky { namespace shell { ContentHandlerImpl::ContentHandlerImpl( mojo::InterfaceRequest<mojo::ContentHandler> request) : binding_(this, request.Pass()) { } ContentHandlerImpl::~ContentHandlerImpl() { } void ContentHandlerImpl::StartApplication( mojo::InterfaceRequest<mojo::Application> application, mojo::URLResponsePtr response) { new ApplicationImpl(application.Pass(), response.Pass()); } } // namespace shell } // namespace sky
27.214286
73
0.75853
abarth
ac101802c53b6ce6a3cf239ca13e8801f6c77f2a
8,638
cpp
C++
service/kernel/data_management/data_conversion.cpp
KalyanovD/daal
b354b68f83a213102bca6e03d7a11f55ab751f92
[ "Apache-2.0" ]
null
null
null
service/kernel/data_management/data_conversion.cpp
KalyanovD/daal
b354b68f83a213102bca6e03d7a11f55ab751f92
[ "Apache-2.0" ]
null
null
null
service/kernel/data_management/data_conversion.cpp
KalyanovD/daal
b354b68f83a213102bca6e03d7a11f55ab751f92
[ "Apache-2.0" ]
null
null
null
/** file data_management_utils.cpp */ /******************************************************************************* * Copyright 2014-2019 Intel Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ /* //++ // Implementation for data conversions dispatcher //-- */ #include "daal_kernel_defines.h" #include "data_conversion_cpu.h" #include "data_management/data/internal/conversion.h" namespace daal { namespace data_management { namespace internal { template <typename T1, typename T2> static void vectorConvertFunc(size_t n, const void * src, void * dst) { typedef void (*funcType)(size_t n, const void * src, void * dst); static funcType ptr = 0; if (!ptr) { int cpuid = (int)daal::services::Environment::getInstance()->getCpuId(); switch (cpuid) { #ifdef DAAL_KERNEL_AVX512 case avx512: DAAL_KERNEL_AVX512_ONLY_CODE(ptr = vectorConvertFuncCpu<T1, T2, avx512>); break; #endif #ifdef DAAL_KERNEL_AVX512_MIC case avx512_mic: DAAL_KERNEL_AVX512_MIC_ONLY_CODE(ptr = vectorConvertFuncCpu<T1, T2, avx512_mic>); break; #endif #ifdef DAAL_KERNEL_AVX2 case avx2: DAAL_KERNEL_AVX2_ONLY_CODE(ptr = vectorConvertFuncCpu<T1, T2, avx2>); break; #endif #ifdef DAAL_KERNEL_AVX case avx: DAAL_KERNEL_AVX_ONLY_CODE(ptr = vectorConvertFuncCpu<T1, T2, avx>); break; #endif #ifdef DAAL_KERNEL_SSE42 case sse42: DAAL_KERNEL_SSE42_ONLY_CODE(ptr = vectorConvertFuncCpu<T1, T2, sse42>); break; #endif #ifdef DAAL_KERNEL_SSSE3 case ssse3: DAAL_KERNEL_SSSE3_ONLY_CODE(ptr = vectorConvertFuncCpu<T1, T2, ssse3>); break; #endif default: ptr = vectorConvertFuncCpu<T1, T2, sse2>; break; }; } ptr(n, src, dst); } template <typename T1, typename T2> static void vectorStrideConvertFunc(size_t n, const void * src, size_t srcByteStride, void * dst, size_t dstByteStride) { typedef void (*funcType)(size_t n, const void * src, size_t srcByteStride, void * dst, size_t dstByteStride); static funcType ptr = 0; if (!ptr) { int cpuid = (int)daal::services::Environment::getInstance()->getCpuId(); switch (cpuid) { #ifdef DAAL_KERNEL_AVX512 case avx512: DAAL_KERNEL_AVX512_ONLY_CODE(ptr = vectorStrideConvertFuncCpu<T1, T2, avx512>); break; #endif #ifdef DAAL_KERNEL_AVX512_MIC case avx512_mic: DAAL_KERNEL_AVX512_MIC_ONLY_CODE(ptr = vectorStrideConvertFuncCpu<T1, T2, avx512_mic>); break; #endif #ifdef DAAL_KERNEL_AVX2 case avx2: DAAL_KERNEL_AVX2_ONLY_CODE(ptr = vectorStrideConvertFuncCpu<T1, T2, avx2>); break; #endif #ifdef DAAL_KERNEL_AVX case avx: DAAL_KERNEL_AVX_ONLY_CODE(ptr = vectorStrideConvertFuncCpu<T1, T2, avx>); break; #endif #ifdef DAAL_KERNEL_SSE42 case sse42: DAAL_KERNEL_SSE42_ONLY_CODE(ptr = vectorStrideConvertFuncCpu<T1, T2, sse42>); break; #endif #ifdef DAAL_KERNEL_SSSE3 case ssse3: DAAL_KERNEL_SSSE3_ONLY_CODE(ptr = vectorStrideConvertFuncCpu<T1, T2, ssse3>); break; #endif default: ptr = vectorStrideConvertFuncCpu<T1, T2, sse2>; break; }; } ptr(n, src, srcByteStride, dst, dstByteStride); } template <typename T> DAAL_EXPORT void vectorAssignValueToArray(T * const dataPtr, const size_t n, const T value) { typedef void (*funcType)(void * const, const size_t, const void * const); static funcType ptr = 0; if (!ptr) { int cpuid = (int)daal::services::Environment::getInstance()->getCpuId(); switch (cpuid) { #ifdef DAAL_KERNEL_AVX512 case avx512: DAAL_KERNEL_AVX512_ONLY_CODE(ptr = vectorAssignValueToArrayCpu<T, avx512>); break; #endif #ifdef DAAL_KERNEL_AVX512_MIC case avx512_mic: DAAL_KERNEL_AVX512_MIC_ONLY_CODE(ptr = vectorAssignValueToArrayCpu<T, avx512_mic>); break; #endif #ifdef DAAL_KERNEL_AVX2 case avx2: DAAL_KERNEL_AVX2_ONLY_CODE(ptr = vectorAssignValueToArrayCpu<T, avx2>); break; #endif #ifdef DAAL_KERNEL_AVX case avx: DAAL_KERNEL_AVX_ONLY_CODE(ptr = vectorAssignValueToArrayCpu<T, avx>); break; #endif #ifdef DAAL_KERNEL_SSE42 case sse42: DAAL_KERNEL_SSE42_ONLY_CODE(ptr = vectorAssignValueToArrayCpu<T, sse42>); break; #endif #ifdef DAAL_KERNEL_SSSE3 case ssse3: DAAL_KERNEL_SSSE3_ONLY_CODE(ptr = vectorAssignValueToArrayCpu<T, ssse3>); break; #endif default: ptr = vectorAssignValueToArrayCpu<T, sse2>; break; }; } ptr(dataPtr, n, &value); } #define DAAL_REGISTER_VECTOR_ASSIGN(Type) \ template DAAL_EXPORT void vectorAssignValueToArray<Type>(Type * const ptr, const size_t n, const Type value); DAAL_REGISTER_WITH_HOMOGEN_NT_TYPES(DAAL_REGISTER_VECTOR_ASSIGN) #undef DAAL_TABLE_UP_ENTRY #define DAAL_TABLE_UP_ENTRY(F, T) \ { \ F<T, float>, F<T, double>, F<T, int> \ } #undef DAAL_TABLE_DOWN_ENTRY #define DAAL_TABLE_DOWN_ENTRY(F, T) \ { \ F<float, T>, F<double, T>, F<int, T> \ } #undef DAAL_CONVERT_UP_TABLE #define DAAL_CONVERT_UP_TABLE(F) \ { \ DAAL_TABLE_UP_ENTRY(F, float), DAAL_TABLE_UP_ENTRY(F, double), DAAL_TABLE_UP_ENTRY(F, int), DAAL_TABLE_UP_ENTRY(F, unsigned int), \ DAAL_TABLE_UP_ENTRY(F, DAAL_INT64), DAAL_TABLE_UP_ENTRY(F, DAAL_UINT64), DAAL_TABLE_UP_ENTRY(F, char), \ DAAL_TABLE_UP_ENTRY(F, unsigned char), DAAL_TABLE_UP_ENTRY(F, short), DAAL_TABLE_UP_ENTRY(F, unsigned short), \ } #undef DAAL_CONVERT_DOWN_TABLE #define DAAL_CONVERT_DOWN_TABLE(F) \ { \ DAAL_TABLE_DOWN_ENTRY(F, float), DAAL_TABLE_DOWN_ENTRY(F, double), DAAL_TABLE_DOWN_ENTRY(F, int), DAAL_TABLE_DOWN_ENTRY(F, unsigned int), \ DAAL_TABLE_DOWN_ENTRY(F, DAAL_INT64), DAAL_TABLE_DOWN_ENTRY(F, DAAL_UINT64), DAAL_TABLE_DOWN_ENTRY(F, char), \ DAAL_TABLE_DOWN_ENTRY(F, unsigned char), DAAL_TABLE_DOWN_ENTRY(F, short), DAAL_TABLE_DOWN_ENTRY(F, unsigned short), \ } DAAL_EXPORT vectorConvertFuncType getVectorUpCast(int idx1, int idx2) { static vectorConvertFuncType table[][3] = DAAL_CONVERT_UP_TABLE(vectorConvertFunc); return table[idx1][idx2]; } DAAL_EXPORT vectorConvertFuncType getVectorDownCast(int idx1, int idx2) { static vectorConvertFuncType table[][3] = DAAL_CONVERT_DOWN_TABLE(vectorConvertFunc); return table[idx1][idx2]; } DAAL_EXPORT vectorStrideConvertFuncType getVectorStrideUpCast(int idx1, int idx2) { static vectorStrideConvertFuncType table[][3] = DAAL_CONVERT_UP_TABLE(vectorStrideConvertFunc); return table[idx1][idx2]; } DAAL_EXPORT vectorStrideConvertFuncType getVectorStrideDownCast(int idx1, int idx2) { static vectorStrideConvertFuncType table[][3] = DAAL_CONVERT_DOWN_TABLE(vectorStrideConvertFunc); return table[idx1][idx2]; } } // namespace internal namespace data_feature_utils { DAAL_EXPORT internal::vectorConvertFuncType getVectorUpCast(int idx1, int idx2) { return internal::getVectorUpCast(idx1, idx2); } DAAL_EXPORT internal::vectorConvertFuncType getVectorDownCast(int idx1, int idx2) { return internal::getVectorDownCast(idx1, idx2); } DAAL_EXPORT internal::vectorStrideConvertFuncType getVectorStrideUpCast(int idx1, int idx2) { return internal::getVectorStrideUpCast(idx1, idx2); } DAAL_EXPORT internal::vectorStrideConvertFuncType getVectorStrideDownCast(int idx1, int idx2) { return internal::getVectorStrideDownCast(idx1, idx2); } } // namespace data_feature_utils } // namespace data_management } // namespace daal
37.885965
147
0.668094
KalyanovD
ac13a5152317f2e27bd83903b60d4f3b55b7ca2e
18,075
cpp
C++
src/legecy/stereo_calibration_example.cpp
behnamasadi/OpenCVProjects
157c8d536c78c5660b64a23300a7aaf941584756
[ "BSD-3-Clause" ]
null
null
null
src/legecy/stereo_calibration_example.cpp
behnamasadi/OpenCVProjects
157c8d536c78c5660b64a23300a7aaf941584756
[ "BSD-3-Clause" ]
null
null
null
src/legecy/stereo_calibration_example.cpp
behnamasadi/OpenCVProjects
157c8d536c78c5660b64a23300a7aaf941584756
[ "BSD-3-Clause" ]
null
null
null
#include <opencv2/calib3d/calib3d.hpp> #include <opencv2/highgui/highgui.hpp> #include <opencv2/imgproc/imgproc.hpp> #include <iostream> template<typename to, typename from> to lexical_cast(from const &x) { std::stringstream os; to ret; os << x; os >> ret; return ret; } static bool readStringList( const std::string& filepath, std::vector<std::string>& l ) { std::string path=filepath.substr(0,filepath.find_last_of("/")); l.resize(0); cv::FileStorage fs(filepath, cv::FileStorage::READ); if( !fs.isOpened() ) return false; cv::FileNode n = fs.getFirstTopLevelNode(); if( n.type() != cv::FileNode::SEQ ) return false; cv::FileNodeIterator it = n.begin(), it_end = n.end(); for( ; it != it_end; ++it ) { // std::cout<<(std::string)*it <<std::endl; // std::cout<<filepath.substr(0,filepath.find_last_of("/") )<<std::endl; l.push_back(path+"/"+(std::string)*it); } return true; } /***************************************calibrating pair of cameras ******************************************/ void stereo_calibartion_from_camera_pair(int argc, char** argv) { int numBoards = 0; //minimum 4 int numCornersHor; //usually 9 int numCornersVer; //usually 6 float square_size; //in our case it is 0.025192 /* char file_name[256]; printf("Enter number of corners along width (usually 9): "); scanf("%d", &numCornersHor); printf("Enter number of corners along height (usually 6): "); scanf("%d", &numCornersVer); printf("Enter number of boards(number of chess boards desired for calibration, minimum 4): "); scanf("%d", &numBoards); printf("square size im meter (0.25192): "); scanf("%f", &square_size); printf("file name to save calibration data (): "); scanf("%s", &file_name); printf("Press n to acquire next image"); */ numBoards = 10; numCornersHor=9; numCornersVer=6; square_size= 0.025192; std::string file_name="my_stereo"; int numSquares = numCornersHor * numCornersVer; cv::Size board_sz = cv::Size(numCornersHor, numCornersVer); //we set it VideoCapture(1) cv::VideoCapture capture_left = cv::VideoCapture(0); cv::VideoCapture capture_right = cv::VideoCapture(1); std::vector<std::vector<cv::Point3f> > object_points; std::vector<std::vector<cv::Point2f> > image_points_left; std::vector<std::vector<cv::Point2f> > image_points_right; std::vector<cv::Mat> left_images, right_images; cv::Mat tmp_img_left,tmp_img_right; std::vector<cv::Point2f> corners_left,corners_right; int successes=0; cv::Mat image_left, image_right; cv::Mat gray_image_left,gray_image_right; capture_left >> image_left; capture_right >> image_right; std::vector<cv::Point3f> obj; for(int j=0;j<numSquares;j++) { obj.push_back(cv::Point3f( (j%numCornersHor) *square_size,(j/numCornersHor *square_size ) ,0.0f)); // std::cout<<(j%numCornersHor) *square_size<<std::endl; // std::cout<<(j/numCornersHor *square_size )<<std::endl; // std::cout<<"--------------------------------------"<<std::endl; } while(successes<numBoards) { cv::cvtColor(image_left, gray_image_left, CV_BGR2GRAY); cv::cvtColor(image_right, gray_image_right, CV_BGR2GRAY); bool found_left = cv::findChessboardCorners(image_left, board_sz, corners_left, CV_CALIB_CB_ADAPTIVE_THRESH | CV_CALIB_CB_FILTER_QUADS); bool found_right = cv::findChessboardCorners(image_right, board_sz, corners_right, CV_CALIB_CB_ADAPTIVE_THRESH | CV_CALIB_CB_FILTER_QUADS); if(found_left && found_right) { cv::cornerSubPix(gray_image_left, corners_left, cv::Size(11, 11), cv::Size(-1, -1), cv::TermCriteria(CV_TERMCRIT_EPS | CV_TERMCRIT_ITER, 30, 0.1)); cv::cornerSubPix(gray_image_right, corners_right, cv::Size(11, 11), cv::Size(-1, -1), cv::TermCriteria(CV_TERMCRIT_EPS | CV_TERMCRIT_ITER, 30, 0.1)); tmp_img_left=image_left.clone(); tmp_img_right=image_right.clone(); drawChessboardCorners(tmp_img_left, board_sz, corners_left, found_left); drawChessboardCorners(tmp_img_right, board_sz, corners_right, found_right); } if(tmp_img_left.empty()) imshow("left", image_left); else imshow("left", tmp_img_left); if(tmp_img_right.empty()) imshow("right", image_right); else imshow("right", tmp_img_right); int key=cv::waitKey(1); if((char)key==(char)27) return ; if((char)key==(char)110 && found_left!=0 && found_right!=0 ) { std::cout<<"Snap stored!"<<std::endl; left_images.push_back(image_left.clone()); right_images.push_back(image_right.clone()); image_points_left.push_back(corners_left); image_points_right.push_back(corners_right); object_points.push_back(obj); successes++; if(successes>=numBoards) break; } capture_right >> image_right; capture_left >> image_left; tmp_img_left.release(); tmp_img_right.release(); } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // cv::FileStorage fs(file_name+std::string(".yml"), FileStorage::WRITE); // fs<<"imagelist"; std::string image_file_name; for(std::size_t i=0;i<left_images.size();i++) { image_file_name="left_image"+lexical_cast<std::string >(i)+std::string(".jpg"); cv::imwrite(image_file_name, left_images.at(i) ); // fs<<"\n"; // fs<<"\"" +image_file_name+"\""; image_file_name="right_image"+lexical_cast<std::string >(i)+std::string(".jpg"); cv::imwrite(image_file_name,right_images.at(i)); // fs<<image_file_name; } // fs<<"imagelist"; // fs.release(); std::cout << "Writing list of files Done." << std::endl; cv::Mat cameraMatrix[2], distCoeffs[2]; cameraMatrix[0] = cv::Mat::eye(3, 3, CV_64F); cameraMatrix[1] = cv::Mat::eye(3, 3, CV_64F); cv::Mat R, T, E, F; double rms = cv::stereoCalibrate(object_points, image_points_left, image_points_right, cameraMatrix[0], distCoeffs[0], cameraMatrix[1], distCoeffs[1], image_left.size(), R, T, E, F, cv::TermCriteria(CV_TERMCRIT_ITER+CV_TERMCRIT_EPS, 100, 1e-5), CV_CALIB_FIX_ASPECT_RATIO + CV_CALIB_ZERO_TANGENT_DIST + CV_CALIB_SAME_FOCAL_LENGTH + CV_CALIB_RATIONAL_MODEL + CV_CALIB_FIX_K3 + CV_CALIB_FIX_K4 + CV_CALIB_FIX_K5); std::cout << "done with RMS error=" << rms << std::endl; std::cout << "Translation between two cameras:" << std::endl; std::cout << T << std::endl; std::cout << "Rotation between two cameras:" << std::endl; std::cout << R << std::endl; std::cout << "Essential Matrix (maps pose of cameras together)" << std::endl; std::cout << E << std::endl; std::cout << "Fundemental Matrix (maps point on camera image plane to the other camera image plane )" << std::endl; std::cout << F << std::endl; } /***************************************Reading image from file ******************************************/ void stereo_calibration_from_file(int argc, char ** argv) { std::vector<std::string> imagelist; //std::string path_to_image_list_file="stereo_calib.xml"; std::string path_to_image_list_file=argv[1]; // std::string path_to_image_list_file="../images/stereo_calibration/stereo_calib.xml"; std::string path=path_to_image_list_file.substr(0,path_to_image_list_file.find_last_of("/"))+"/"; readStringList(path_to_image_list_file, imagelist); float square_size; cv::Size boardSize; int height, width; height=6; width=9; boardSize = cv::Size(width, height); square_size=0.025; std::vector<std::vector<cv::Point2f> > left_imagePoints, right_imagePoints; std::vector<std::vector<cv::Point3f> > objectPoints; cv::Size imageSize; std::vector<std::string> good_left_imageList,good_right_imageList; std::vector<cv::Point3f> obj; int numSquares=width*height; for(int j=0;j<numSquares;j++) { obj.push_back(cv::Point3f( (j%width) *square_size,(j/width *square_size ) ,0.0f)); // std::cout<< (j%width) <<","<<(j/width) <<std::endl; } bool found = false; std::string filename; std::vector<cv::Point2f> corners; cv::Mat image_gray ,img; for(std::size_t i = 0; i < imagelist.size() ; i++ ) { corners.clear(); filename=imagelist.at(i); img = cv::imread(imagelist.at(i)); imageSize = img.size(); found=cv::findChessboardCorners(img,boardSize,corners,CV_CALIB_CB_ADAPTIVE_THRESH | CV_CALIB_CB_NORMALIZE_IMAGE); if(found) { cv::cvtColor(img,image_gray,cv::COLOR_RGB2GRAY); cv::cornerSubPix(image_gray,corners, cv::Size(11, 11), cv::Size(-1, -1), cv::TermCriteria(CV_TERMCRIT_EPS | CV_TERMCRIT_ITER, 30, 0.1)); if(filename.find("left")!=std::string::npos) { std::cout<<"L" <<std::endl; left_imagePoints.push_back(corners); objectPoints.push_back(obj); } if(filename.find("right")!=std::string::npos) { std::cout<<"R" <<std::endl; right_imagePoints.push_back(corners); } } cv::drawChessboardCorners(image_gray,boardSize,corners,found); cv::imshow("corners", image_gray); char c = (char)cv::waitKey(500); if( c == 27 || c == 'q' || c == 'Q' ) //Allow ESC to quit exit(-1); } cv::Mat left_cameraMatrix, right_cameraMatrix, left_distCoeffs,right_distCoeffs; left_cameraMatrix = cv::Mat::eye(3, 3, CV_64F); right_cameraMatrix = cv::Mat::eye(3, 3, CV_64F); cv::Mat R, T, E, F; double rms = cv::stereoCalibrate(objectPoints, left_imagePoints, right_imagePoints, left_cameraMatrix, left_distCoeffs, right_cameraMatrix, right_distCoeffs, imageSize, R, T, E, F, cv::TermCriteria(CV_TERMCRIT_ITER+CV_TERMCRIT_EPS, 100, 1e-5), CV_CALIB_FIX_ASPECT_RATIO + CV_CALIB_ZERO_TANGENT_DIST + CV_CALIB_SAME_FOCAL_LENGTH + CV_CALIB_RATIONAL_MODEL + CV_CALIB_FIX_K3 + CV_CALIB_FIX_K4 + CV_CALIB_FIX_K5); std::cout << "done with RMS error=" << rms << std::endl; std::cout << "Translation between two cameras:" << std::endl; std::cout << T << std::endl; std::cout << "Rotation between two cameras:" << std::endl; std::cout << R << std::endl; std::cout << "Essential Matrix:" << std::endl; std::cout << E << std::endl; std::cout << "Fundemental Matrix:" << std::endl; std::cout << F << std::endl; int number_of_left_image=left_imagePoints.size(); std::vector<cv::Vec3f> left_lines, right_lines; double err = 0; int npoints = 0; for(int i=0;i<number_of_left_image;i++) { int number_of_corners=left_imagePoints.at(0).size(); cv::Mat left_image_cornor_points=cv::Mat(left_imagePoints.at(i)); cv::undistortPoints(left_image_cornor_points, left_image_cornor_points, left_cameraMatrix, left_distCoeffs, cv::Mat(), left_cameraMatrix); /* Every point in first image is a line in the second image, so here we for every chessboard corner point we find the epipolar line in the right image the lines are stored in right_lines in the form of ax+by+cz=0 so for example for the first corner point right_lines[0][0] is a right_lines[0][1] is b right_lines[0][2] is c These are cordinate of third chessboard corner in the sixth left image left_imagePoints[5][2].x left_imagePoints[5][2].y so this should be zero: right_lines[0][0]*left_imagePoints[5][2].x + left_imagePoints[5][2].y*right_lines[0][1] + right_lines[0][2] */ cv::computeCorrespondEpilines(left_image_cornor_points, 1, F, right_lines); cv::Mat right_image_cornor_points=cv::Mat(right_imagePoints.at(i)); cv::undistortPoints(right_image_cornor_points, right_image_cornor_points, right_cameraMatrix, right_distCoeffs, cv::Mat(), right_cameraMatrix); cv::computeCorrespondEpilines(right_image_cornor_points, 2, F, left_lines); for( int j = 0; j < number_of_corners; j++ ) { double errij = fabs(left_imagePoints[i][j].x*left_lines[j][0] + left_imagePoints[i][j].y*left_lines[j][1] + left_lines[j][2]) + fabs(right_imagePoints[i][j].x*right_lines[j][0] + right_imagePoints[i][j].y*right_lines[j][1] + right_lines[j][2]); err += errij; } npoints += number_of_corners; } std::cout << "total reprojection err = " << err<< std::endl; std::cout << "average reprojection err = " << err/npoints << std::endl; // save intrinsic parameters cv::FileStorage fs(path+"intrinsics.yml", CV_STORAGE_WRITE); if( fs.isOpened() ) { fs << "M1" << left_cameraMatrix << "D1" << left_distCoeffs << "M2" << right_cameraMatrix << "D2" << right_distCoeffs; fs.release(); } else std::cout << "Error: can not save the intrinsic parameters\n"; cv::Mat R1, R2, P1, P2, Q; cv::Rect validRoi[2]; cv::stereoRectify(left_cameraMatrix, left_distCoeffs, right_cameraMatrix, right_distCoeffs, imageSize, R, T, R1, R2, P1, P2, Q, cv::CALIB_ZERO_DISPARITY, 1, imageSize, &validRoi[0], &validRoi[1]); fs.open(path+"extrinsics.yml", CV_STORAGE_WRITE); if( fs.isOpened() ) { fs << "R" << R << "T" << T << "R1" << R1 << "R2" << R2 << "P1" << P1 << "P2" << P2 << "Q" << Q; fs.release(); } else std::cout << "Error: can not save the extrinsic parameters\n"; // OpenCV can handle left-right // or up-down camera arrangements bool isVerticalStereo = fabs(P2.at<double>(1, 3)) > fabs(P2.at<double>(0, 3)); cv::Mat left_rmap_x,left_rmap_y, right_rmap_x, right_rmap_y; /* // IF BY CALIBRATED (BOUGUET'S METHOD) if( useCalibrated ) { // we already computed everything } // OR ELSE HARTLEY'S METHOD else // use intrinsic parameters of each camera, but // compute the rectification transformation directly // from the fundamental matrix { vector<Point2f> allimgpt[2]; for( k = 0; k < 2; k++ ) { for( i = 0; i < nimages; i++ ) std::copy(imagePoints[k][i].begin(), imagePoints[k][i].end(), back_inserter(allimgpt[k])); } F = findFundamentalMat(Mat(allimgpt[0]), Mat(allimgpt[1]), FM_8POINT, 0, 0); Mat H1, H2; stereoRectifyUncalibrated(Mat(allimgpt[0]), Mat(allimgpt[1]), F, imageSize, H1, H2, 3); R1 = cameraMatrix[0].inv()*H1*cameraMatrix[0]; R2 = cameraMatrix[1].inv()*H2*cameraMatrix[1]; P1 = cameraMatrix[0]; P2 = cameraMatrix[1]; } */ //Precompute maps for cv::remap() cv::initUndistortRectifyMap(left_cameraMatrix, left_distCoeffs, R1, P1, imageSize, CV_16SC2, left_rmap_x, left_rmap_y); cv::initUndistortRectifyMap(right_cameraMatrix, right_distCoeffs, R2, P2, imageSize, CV_16SC2, right_rmap_x, right_rmap_y); //cv::stereoRectifyUncalibrated() std::string rectified_file_path; for(std::size_t i=0;i<imagelist.size();i++) { filename=imagelist.at(i); cv::Mat img = cv::imread(filename, 0), rectified_img ; if(filename.find("left")!=std::string::npos) { std::cout<<"LL" <<std::endl; cv::remap(img, rectified_img, left_rmap_x, left_rmap_y, CV_INTER_LINEAR); } if(filename.find("right")!=std::string::npos) { std::cout<<"RR" <<std::endl; cv::remap(img, rectified_img, right_rmap_x, right_rmap_y, CV_INTER_LINEAR); } rectified_file_path=filename.insert(filename.find_last_of("/")+1, std::string("rect_") ); // std::cout<< <<std::endl; cv::imwrite(rectified_file_path,rectified_img); } } //undistort -> after camera calibration we can remove the radial and tangential distortion //rectify -> rectifing images it is the process that as if the two images taken with parallel image plane that are align //disparity /* stereo rectifi cation is the process of “correcting” the individual images so that they appear as if they had been taken by two cameras with row-aligned image planes -> stereo solution reduce to search */ void image_rectification_test() { } /* Stereo calibration is the process of computing the geometrical relationship between the two cameras in space. */ void stereo_calibration() { } //http://wiki.ros.org/stereo_image_proc/Tutorials/ChoosingGoodStereoParameters //http://wiki.ros.org/stereo_image_proc#stereo_image_proc-1 //http://wiki.ros.org/stereo_image_proc#stereo_image_proc-1 //Bouguet’s algorithm void stereoRectify_example() { } //Hartley’s algorithm void stereoRectifyUncalibrated_example() { // cv::stereoRectifyUncalibrated() -> when we use chesbaord i.e // cv::initUndistortRectifyMap() -> when we only have correspon } void initUndistortRectifyMap_example() { } //Pollefeys calibartion int main(int argc, char ** argv) { char* n_argv[] = { "stereo_calibration_example", "../images/stereo_calibration/stereo_calib.xml"}; int length = sizeof(n_argv)/sizeof(n_argv[0]); argc=length; argv = n_argv; stereo_calibration_from_file( argc, argv); }
31.325823
161
0.614495
behnamasadi
ac169641572830604d2fb8fe1f3781c065eaa214
811
hxx
C++
src/NodoElemento.hxx
taleroangel/ProyeccionesEDD
d246dc22776fca09b2a36c82b3db682f3af3a155
[ "MIT" ]
null
null
null
src/NodoElemento.hxx
taleroangel/ProyeccionesEDD
d246dc22776fca09b2a36c82b3db682f3af3a155
[ "MIT" ]
null
null
null
src/NodoElemento.hxx
taleroangel/ProyeccionesEDD
d246dc22776fca09b2a36c82b3db682f3af3a155
[ "MIT" ]
null
null
null
#ifndef NODOELEMENTO_HXX #define NODOELEMENTO_HXX #include <vector> #include "CodigoElemento.hxx" #include "NodoCodificacion.hxx" template <typename T> struct NodoElemento : public NodoCodificacion<T> { T dato; NodoElemento<T>() = default; NodoElemento<T>(T elemento, freq_t frecuencia); std::vector<CodigoElemento<T>> codigos_elementos( std::string codigo) override; }; template <typename T> inline NodoElemento<T>::NodoElemento(T elemento, freq_t frecuencia) : NodoCodificacion<T>{frecuencia}, dato{elemento} {} template <typename T> inline std::vector<CodigoElemento<T>> NodoElemento<T>::codigos_elementos( std::string codigo) { return std::vector<CodigoElemento<T>>{ CodigoElemento<T>{this->dato, this->frecuencia, codigo}}; } #endif // NODOELEMENTO_HXX
25.34375
73
0.727497
taleroangel
ac1a0d60888ad524514b3ceaa6a97b2d58f430b0
137
cpp
C++
toolkit/Source/src/gs2d/src/Audio/Audiere/audiere/src/version.cpp
LuizTedesco/ethanon
c140bd360092dcdf11b242a11dee67e79fbbd025
[ "Unlicense" ]
64
2015-01-02T12:27:29.000Z
2022-03-07T03:23:33.000Z
toolkit/Source/src/gs2d/src/Audio/Audiere/audiere/src/version.cpp
theomission/ethanon
c140bd360092dcdf11b242a11dee67e79fbbd025
[ "Unlicense" ]
5
2015-03-31T00:09:29.000Z
2022-03-07T18:16:42.000Z
toolkit/Source/src/gs2d/src/Audio/Audiere/audiere/src/version.cpp
theomission/ethanon
c140bd360092dcdf11b242a11dee67e79fbbd025
[ "Unlicense" ]
40
2015-01-14T09:47:56.000Z
2022-02-07T22:07:24.000Z
#include "audiere.h" #include "internal.h" namespace audiere { ADR_EXPORT(const char*) AdrGetVersion() { return "1.9.4"; } }
11.416667
43
0.642336
LuizTedesco
ac25801ccef67dcdf6a3c9db98319da2d360da8e
2,741
cpp
C++
codeforces/1515C.cpp
sgrade/cpptest
84ade6ec03ea394d4a4489c7559d12b4799c0b62
[ "MIT" ]
null
null
null
codeforces/1515C.cpp
sgrade/cpptest
84ade6ec03ea394d4a4489c7559d12b4799c0b62
[ "MIT" ]
null
null
null
codeforces/1515C.cpp
sgrade/cpptest
84ade6ec03ea394d4a4489c7559d12b4799c0b62
[ "MIT" ]
null
null
null
// C. Phoenix and Towers #include <iostream> #include <algorithm> #include <vector> #include <map> #include <numeric> #include <set> using namespace std; int main() { int t; cin >> t; while (t--) { int n, m, x; cin >> n >> m >> x; int tmp; // <height, count_of_such_heights> map<int, int, greater<int>> mp; // original indexes of the heights multimap<int, int> original_indexes; for (int i = 0; i < n; ++i) { cin >> tmp; ++mp[tmp]; original_indexes.insert(pair<int, int>(tmp, i)); } bool ans = true; vector<int> output(n); if (m > 1) { // pair<int, int>: first is sum, second is index in heights multiset<pair<int, int>> sums; for (int i = 0; i < m; ++i) { sums.insert(pair<int, int> (0, i)); } multiset<pair<int, int>>::iterator sums_it; vector<vector<int>> heights(m); map<int, int, greater<int>>::iterator it = mp.begin(); // index of related vectors int mn_sum = 0, mn_idx = 0; for (int i = 0; i < n; ++i) { if (it->second == 0) { ++it; } mn_sum = sums.begin()->first; mn_idx = sums.begin()->second; mn_sum += it->first; sums.erase(sums.begin()); sums.insert(pair<int, int>(mn_sum, mn_idx)); heights[mn_idx].push_back(it->first); --it->second; } mn_sum = sums.begin()->first; multiset<pair<int, int>>::reverse_iterator sums_rit = sums.rbegin(); int mx_sum = sums_rit->first; if (mx_sum - mn_sum > x) { ans = false; } else { int original_idx; map<int, int>::iterator original_idx_it; for (int i = 0; i < m; ++i) { for (auto &height: heights[i]) { original_idx_it = original_indexes.find(height); original_idx = original_idx_it->second; output[original_idx] = i + 1; original_indexes.erase(original_idx_it); } } } } else { for (int i = 0; i < n; ++i) { output[i] = 1; } } cout << (ans ? "YES" : "NO") << endl; if (ans) { for (auto &el: output) { cout << el << ' '; } cout << endl; } } return 0; }
26.104762
80
0.41846
sgrade
ac26ace285bf1b9861c6eeb28f6f1d014eb74d1a
6,923
cpp
C++
src/Public/CaptureCpp/CaptureCpp.cpp
zpublic/cozy
dde5f2bcf7482e2e5042f9e51266d9fd272e1456
[ "WTFPL" ]
48
2015-04-11T13:25:45.000Z
2022-03-28T08:27:40.000Z
src/Public/CaptureCpp/CaptureCpp.cpp
ToraiRei/cozy
c8197d9c6531f1864d6063ae149db53b669241f0
[ "WTFPL" ]
4
2016-04-06T09:30:57.000Z
2022-02-26T01:21:18.000Z
src/Public/CaptureCpp/CaptureCpp.cpp
ToraiRei/cozy
c8197d9c6531f1864d6063ae149db53b669241f0
[ "WTFPL" ]
33
2015-06-03T10:06:54.000Z
2020-12-15T00:50:28.000Z
// CaptureCpp.cpp : Defines the exported functions for the DLL application. // #include "stdafx.h" #include "CaptureCpp.h" CAPTURECPP_API CCaptureCpp CcaptureCppInstance; CCaptureCpp::CCaptureCpp(void) { } void CCaptureCpp::GetWindowSize(HWND hwnd, LPLONG x, LPLONG y) { RECT rect; ::GetWindowRect(hwnd, &rect); *x = rect.right - rect.left;; *y = rect.bottom - rect.top; } WORD CCaptureCpp::GetClrBits(WORD wInput) { WORD cClrBits = wInput; if (cClrBits == 1) cClrBits = 1; else if (cClrBits <= 4) cClrBits = 4; else if (cClrBits <= 8) cClrBits = 8; else if (cClrBits <= 16) cClrBits = 16; else if (cClrBits <= 24) cClrBits = 24; else cClrBits = 32; return cClrBits; } bool CCaptureCpp::GetWindowHDC(HWND *lpHwnd, HDC *lpHdc) { if (lpHwnd != nullptr && lpHdc != nullptr) { *lpHwnd = ::GetDesktopWindow(); *lpHdc = ::GetWindowDC(*lpHwnd); return true; } return false; } DWORD CCaptureCpp::GetCaptureDataSize(HWND hwnd, HDC hdc, int x, int y, int width, int height, LPBITMAP lpBitmap) { POINT size; if (width == 0 && height == 0) { GetWindowSize(hwnd, &(size.x), &(size.y)); } else { size.x = width; size.y = height; } HDC memHdc = ::CreateCompatibleDC(hdc); HBITMAP hBmp = ::CreateCompatibleBitmap(hdc, size.x, size.y); ::SelectObject(memHdc, hBmp); BITMAP bmp; WORD cClrBits; if (!::GetObject(hBmp, sizeof(BITMAP), (LPVOID)&bmp)) { return 0; } cClrBits = GetClrBits((WORD)(bmp.bmPlanes * bmp.bmBitsPixel)); *lpBitmap = bmp; return (bmp.bmWidth + 7) / 8 * bmp.bmHeight * cClrBits + sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER) + (1 << cClrBits) *sizeof(RGBQUAD); } DWORD CCaptureCpp::GetCaptureData(HWND hwnd, HDC hdc, int x, int y, int width, int height, LPBYTE lpResult) { POINT size; if (width == 0 && height == 0) { GetWindowSize(hwnd, &(size.x), &(size.y)); } else { size.x = width; size.y = height; } HDC memHdc = ::CreateCompatibleDC(hdc); HBITMAP hBmp = ::CreateCompatibleBitmap(hdc, size.x, size.y); ::SelectObject(memHdc, hBmp); ::BitBlt(memHdc, 0, 0, size.x, size.y, hdc, x, y, SRCCOPY); BITMAP bmp; PBITMAPINFO pbmi; WORD cClrBits; if (!::GetObject(hBmp, sizeof(BITMAP), (LPVOID)&bmp)) { return 0; } cClrBits = GetClrBits((WORD)(bmp.bmPlanes * bmp.bmBitsPixel)); if (cClrBits != 24) { pbmi = (PBITMAPINFO)::LocalAlloc(LPTR, sizeof(BITMAPINFOHEADER) + sizeof(RGBQUAD) * (1 << cClrBits)); } else { pbmi = (PBITMAPINFO)::LocalAlloc(LPTR, sizeof(BITMAPINFOHEADER)); } pbmi->bmiHeader.biSize = sizeof(BITMAPINFOHEADER); pbmi->bmiHeader.biWidth = bmp.bmWidth; pbmi->bmiHeader.biHeight = bmp.bmHeight; pbmi->bmiHeader.biPlanes = bmp.bmPlanes; pbmi->bmiHeader.biBitCount = bmp.bmBitsPixel; if (cClrBits < 24) pbmi->bmiHeader.biClrUsed = (1 << cClrBits); pbmi->bmiHeader.biCompression = BI_RGB; pbmi->bmiHeader.biSizeImage = (pbmi->bmiHeader.biWidth + 7) / 8 * pbmi->bmiHeader.biHeight * cClrBits; pbmi->bmiHeader.biClrImportant = 0; ::GetDIBits(memHdc, hBmp, 0, (WORD)(WORD)pbmi->bmiHeader.biHeight, lpResult, pbmi, DIB_RGB_COLORS); ::LocalFree(pbmi); return 1; } DWORD CCaptureCpp::AppendBitmapHeader(LPBYTE lpResult, LPBITMAP lpBitmap) { WORD cClrBits = GetClrBits((WORD)(lpBitmap->bmPlanes * lpBitmap->bmBitsPixel)); PBITMAPINFO pbmi; if (cClrBits != 24) { pbmi = (PBITMAPINFO)::LocalAlloc(LPTR, sizeof(BITMAPINFOHEADER) + sizeof(RGBQUAD) * (1 << cClrBits)); } else { pbmi = (PBITMAPINFO)::LocalAlloc(LPTR, sizeof(BITMAPINFOHEADER)); } pbmi->bmiHeader.biSize = sizeof(BITMAPINFOHEADER); pbmi->bmiHeader.biWidth = lpBitmap->bmWidth; pbmi->bmiHeader.biHeight = lpBitmap->bmHeight; pbmi->bmiHeader.biPlanes = lpBitmap->bmPlanes; pbmi->bmiHeader.biBitCount = lpBitmap->bmBitsPixel; if (cClrBits < 24) pbmi->bmiHeader.biClrUsed = (1 << cClrBits); pbmi->bmiHeader.biCompression = BI_RGB; pbmi->bmiHeader.biSizeImage = (pbmi->bmiHeader.biWidth + 7) / 8 * pbmi->bmiHeader.biHeight * cClrBits; pbmi->bmiHeader.biClrImportant = 0; BITMAPFILEHEADER hdr; PBITMAPINFOHEADER pbih; pbih = (PBITMAPINFOHEADER)pbmi; hdr.bfType = 0x4d42; hdr.bfSize = (DWORD)(sizeof(BITMAPFILEHEADER) + pbih->biSize + pbih->biClrUsed * sizeof(RGBQUAD) + pbih->biSizeImage); hdr.bfReserved1 = 0; hdr.bfReserved2 = 0; hdr.bfOffBits = (DWORD)sizeof(BITMAPFILEHEADER) + pbih->biSize + pbih->biClrUsed * sizeof(RGBQUAD); DWORD offset = 0; ::CopyMemory(lpResult + offset, (LPVOID)&hdr, sizeof(BITMAPFILEHEADER)); offset += sizeof(BITMAPFILEHEADER); ::CopyMemory(lpResult + offset, (LPVOID)pbih, sizeof(BITMAPINFOHEADER) + pbih->biClrUsed * sizeof(RGBQUAD)); offset += sizeof(BITMAPINFOHEADER) + pbih->biClrUsed * sizeof(RGBQUAD); ::LocalFree(pbmi); return offset; } CAPTURECPP_API int GetDesktopNum(void) { int dspNum = ::GetSystemMetrics(SM_CMONITORS); return dspNum; } int gMonitorIndex = 0; int gMonitorCount = 0; RECT gMonitorSize[10]; BOOL CALLBACK MonitorEnumProc(HMONITOR hMonitor, HDC hdcMonitor, LPRECT lprcMonitor, LPARAM dwData) { if (gMonitorIndex < 10) { gMonitorSize[gMonitorIndex] = *lprcMonitor; gMonitorIndex++; gMonitorCount++; } return TRUE; } CAPTURECPP_API bool GetDesktopSize(int nIndex, int* w, int* h) { gMonitorIndex = 0; gMonitorCount = 0; ::EnumDisplayMonitors(NULL, NULL, MonitorEnumProc, 0); if (nIndex < gMonitorCount) { *w = gMonitorSize[nIndex].right - gMonitorSize[nIndex].left; *h = gMonitorSize[nIndex].bottom - gMonitorSize[nIndex].top; return true; } return false; } CAPTURECPP_API DWORD AppendBitmapHeader(LPBYTE lpData, LPBITMAP lpBitmap) { return CCaptureCppCppInstance.AppendBitmapHeader(lpData, lpBitmap); } CAPTURECPP_API bool GetWindowHDC(HWND *lpHwnd, HDC *lpHdc) { return CCaptureCppCppInstance.GetWindowHDC(lpHwnd, lpHdc); } CAPTURECPP_API DWORD GetCaptureData(HWND hwnd, HDC hdc, int x, int y, int width, int height, LPBYTE lpResult) { return CCaptureCppCppInstance.GetCaptureData(hwnd, hdc, x, y, width, height, lpResult); } CAPTURECPP_API DWORD GetCaptureDataSize(HWND hwnd, HDC hdc, int x, int y, int width, int height, LPBITMAP lpBitmap) { return CCaptureCppCppInstance.GetCaptureDataSize(hwnd, hdc, x, y, width, height, lpBitmap); } CAPTURECPP_API void GetWindowSize(HWND hwnd, LONG *x, LONG *y) { return CCaptureCppCppInstance.GetWindowSize(hwnd, x, y); }
28.966527
148
0.648563
zpublic
ac29e77fee02fbba5e1cce28204aa9374c07145d
453
cpp
C++
Source/GCE/Game/Mover/BishopMoverComponent.cpp
ssapo/GCE
ddb5dfa2472c2f4ba01bf81d4fac9a64ac861e9f
[ "MIT" ]
2
2019-07-28T13:30:14.000Z
2019-11-22T08:14:28.000Z
Source/GCE/Game/Mover/BishopMoverComponent.cpp
ssapo/GCE
ddb5dfa2472c2f4ba01bf81d4fac9a64ac861e9f
[ "MIT" ]
null
null
null
Source/GCE/Game/Mover/BishopMoverComponent.cpp
ssapo/GCE
ddb5dfa2472c2f4ba01bf81d4fac9a64ac861e9f
[ "MIT" ]
1
2019-07-07T13:39:08.000Z
2019-07-07T13:39:08.000Z
// Fill out your copyright notice in the Description page of Project Settings. #include "BishopMoverComponent.h" UBishopMoverComponent::UBishopMoverComponent() { MoveDirections = { FIntPoint(1, 1), FIntPoint(-1, 1), FIntPoint(-1, -1), FIntPoint(1, -1) }; AttackDirections = { FIntPoint(1, 1), FIntPoint(-1, 1), FIntPoint(-1, -1), FIntPoint(1, -1) }; bPercistance = true; bHasSpecialMove = false; bHasTeamDirection = false; }
17.423077
78
0.682119
ssapo
ac2d7ccd2d614bdaa9490a9e634da1740762d6f6
440
cc
C++
arch/spinlock.cc
kstepanmpmg/mldb
f78791cd34d01796705c0f173a14359ec1b2e021
[ "Apache-2.0" ]
665
2015-12-09T17:00:14.000Z
2022-03-25T07:46:46.000Z
arch/spinlock.cc
tomzhang/mldb
a09cf2d9ca454d1966b9e49ae69f2fe6bf571494
[ "Apache-2.0" ]
797
2015-12-09T19:48:19.000Z
2022-03-07T02:19:47.000Z
arch/spinlock.cc
matebestek/mldb
f78791cd34d01796705c0f173a14359ec1b2e021
[ "Apache-2.0" ]
103
2015-12-25T04:39:29.000Z
2022-02-03T02:55:22.000Z
/** spinlock.cc Jeremy Barnes, 23 December 2015 Copyright (c) 2015 mldb.ai inc. All rights reserved. This file is part of MLDB. Copyright 2015 mldb.ai inc. All rights reserved. Spinlock support functions. */ #include "spinlock.h" #include <thread> namespace MLDB { void Spinlock:: yield() { // This is here so we don't need to #include <thread> in the .h file std::this_thread::yield(); } } // namespace MLDB
18.333333
79
0.675
kstepanmpmg
ac2f4925630e18f9f4aaeb0df87d39295d681419
25,138
cxx
C++
panda/src/particlesystem/particleSystem.cxx
kestred/panda3d
16bfd3750f726a8831771b81649d18d087917fd5
[ "PHP-3.01", "PHP-3.0" ]
3
2018-03-09T12:07:29.000Z
2021-02-25T06:50:25.000Z
panda/src/particlesystem/particleSystem.cxx
Sinkay/panda3d
16bfd3750f726a8831771b81649d18d087917fd5
[ "PHP-3.01", "PHP-3.0" ]
null
null
null
panda/src/particlesystem/particleSystem.cxx
Sinkay/panda3d
16bfd3750f726a8831771b81649d18d087917fd5
[ "PHP-3.01", "PHP-3.0" ]
null
null
null
// Filename: particleSystem.cxx // Created by: charles (14Jun00) // //////////////////////////////////////////////////////////////////// // // PANDA 3D SOFTWARE // Copyright (c) Carnegie Mellon University. All rights reserved. // // All use of this software is subject to the terms of the revised BSD // license. You should have received a copy of this license along // with this source code in a file named "LICENSE." // //////////////////////////////////////////////////////////////////// #include <stdlib.h> #include "luse.h" #include "lmat_ops.h" #include "clockObject.h" #include "physicsManager.h" #include "physicalNode.h" #include "nearly_zero.h" #include "transformState.h" #include "nodePath.h" #include "config_particlesystem.h" #include "particleSystem.h" #include "particleSystemManager.h" #include "pointParticleRenderer.h" #include "pointParticleFactory.h" #include "sphereSurfaceEmitter.h" #include "pStatTimer.h" TypeHandle ParticleSystem::_type_handle; PStatCollector ParticleSystem::_update_collector("App:Particles:Update"); //////////////////////////////////////////////////////////////////// // Function : ParticleSystem // Access : Public // Description : Default Constructor. //////////////////////////////////////////////////////////////////// ParticleSystem:: ParticleSystem(int pool_size) : Physical(pool_size, false) { _birth_rate = 0.5f; _cur_birth_rate = _birth_rate; _soft_birth_rate = HUGE_VAL; _tics_since_birth = 0.0; _litter_size = 1; _litter_spread = 0; _living_particles = 0; _active_system_flag = true; _local_velocity_flag = true; _spawn_on_death_flag = false; _system_grows_older_flag = false; _system_lifespan = 0.0f; _i_was_spawned_flag = false; _particle_pool_size = 0; _floor_z = -HUGE_VAL; // just in case someone tries to do something that requires the // use of an emitter, renderer, or factory before they've actually // assigned one. This is ok, because assigning them (set_renderer(), // set_emitter(), etc...) forces them to set themselves up for the // system, keeping the pool sizes consistent. _render_node_path = NodePath(); _render_parent = NodePath("ParticleSystem default render parent"); set_emitter(new SphereSurfaceEmitter); set_renderer(new PointParticleRenderer); //set_factory(new PointParticleFactory); _factory = new PointParticleFactory; clear_physics_objects(); set_pool_size(pool_size); } //////////////////////////////////////////////////////////////////// // Function : ParticleSystem // Access : Public // Description : Copy Constructor. //////////////////////////////////////////////////////////////////// ParticleSystem:: ParticleSystem(const ParticleSystem& copy) : Physical(copy), _system_age(0.0f), _template_system_flag(false) { _birth_rate = copy._birth_rate; _cur_birth_rate = copy._cur_birth_rate; _litter_size = copy._litter_size; _litter_spread = copy._litter_spread; _active_system_flag = copy._active_system_flag; _local_velocity_flag = copy._local_velocity_flag; _spawn_on_death_flag = copy._spawn_on_death_flag; _i_was_spawned_flag = copy._i_was_spawned_flag; _system_grows_older_flag = copy._system_grows_older_flag; _emitter = copy._emitter; _renderer = copy._renderer->make_copy(); _factory = copy._factory; _render_parent = copy._render_parent; _render_node_path = _renderer->get_render_node_path(); _render_node_path.reparent_to(_render_parent); _tics_since_birth = 0.0; _system_lifespan = copy._system_lifespan; _living_particles = 0; set_pool_size(copy._particle_pool_size); } //////////////////////////////////////////////////////////////////// // Function : ~ParticleSystem // Access : Public // Description : You get the ankles and I'll get the wrists. //////////////////////////////////////////////////////////////////// ParticleSystem:: ~ParticleSystem() { set_pool_size(0); if (!_template_system_flag) { _renderer.clear(); _render_node_path.remove_node(); } } //////////////////////////////////////////////////////////////////// // Function : birth_particle // Access : Private // Description : A new particle is born. This doesn't allocate, // resets an element from the particle pool. //////////////////////////////////////////////////////////////////// bool ParticleSystem:: birth_particle() { int pool_index; // make sure there's room for a new particle if (_living_particles >= _particle_pool_size) { #ifdef PSDEBUG if (_living_particles > _particle_pool_size) { cout << "_living_particles > _particle_pool_size" << endl; } #endif return false; } #ifdef PSDEBUG if (0 == _free_particle_fifo.size()) { cout << "Error: _free_particle_fifo is empty, but _living_particles < _particle_pool_size" << endl; return false; } #endif pool_index = _free_particle_fifo.back(); _free_particle_fifo.pop_back(); // get a handle on our particle. BaseParticle *bp = (BaseParticle *) _physics_objects[pool_index].p(); // start filling out the variables. _factory->populate_particle(bp); bp->set_alive(true); bp->set_active(true); bp->init(); // get the location of the new particle. LPoint3 new_pos, world_pos; LVector3 new_vel; _emitter->generate(new_pos, new_vel); // go from birth space to render space NodePath physical_np = get_physical_node_path(); NodePath render_np = _renderer->get_render_node_path(); CPT(TransformState) transform = physical_np.get_transform(render_np); const LMatrix4 &birth_to_render_xform = transform->get_mat(); world_pos = new_pos * birth_to_render_xform; // cout << "New particle at " << world_pos << endl; // possibly transform the initial velocity as well. if (_local_velocity_flag == false) new_vel = new_vel * birth_to_render_xform; bp->reset_position(world_pos/* + (NORMALIZED_RAND() * new_vel)*/); bp->set_velocity(new_vel); ++_living_particles; // propogate information down to renderer _renderer->birth_particle(pool_index); return true; } //////////////////////////////////////////////////////////////////// // Function : birth_litter // Access : Private // Description : spawns a new batch of particles //////////////////////////////////////////////////////////////////// void ParticleSystem:: birth_litter() { int litter_size, i; litter_size = _litter_size; if (_litter_spread != 0) litter_size += I_SPREAD(_litter_spread); for (i = 0; i < litter_size; ++i) { if (birth_particle() == false) return; } } //////////////////////////////////////////////////////////////////// // Function : spawn_child_system // Access : private // Description : Creates a new particle system based on local // template info and adds it to the ps and physics // managers //////////////////////////////////////////////////////////////////// void ParticleSystem:: spawn_child_system(BaseParticle *bp) { // first, make sure that the system exists in the graph via a // physicalnode reference. PhysicalNode *this_pn = get_physical_node(); if (!this_pn) { physics_cat.error() << "ParticleSystem::spawn_child_system: " << "Spawning system is not in the scene graph," << " aborting." << endl; return; } if (this_pn->get_num_parents() == 0) { physics_cat.error() << "ParticleSystem::spawn_child_system: " << "PhysicalNode this system is contained in " << "has no parent, aborting." << endl; return; } NodePath physical_np = get_physical_node_path(); NodePath parent_np = physical_np.get_parent(); PandaNode *parent = parent_np.node(); // handle the spawn templates int new_ps_index = rand() % _spawn_templates.size(); ParticleSystem *ps_template = _spawn_templates[new_ps_index]; // create a new particle system PT(ParticleSystem) new_ps = new ParticleSystem(*ps_template); new_ps->_i_was_spawned_flag = true; // first, set up the render node info. new_ps->_render_parent = _spawn_render_node_path; new_ps->_render_node_path = new_ps->_renderer->get_render_node_path(); new_ps->_render_node_path.reparent_to(new_ps->_render_parent); // now set up the new system's PhysicalNode. PT(PhysicalNode) new_pn = new PhysicalNode("new_pn"); new_pn->add_physical(new_ps); // the transform on the new child has to represent the transform // from the current system up to its parent, and then subsequently // down to the new child. parent->add_child(new_pn); CPT(TransformState) transform = physical_np.get_transform(parent_np); const LMatrix4 &old_system_to_parent_xform = transform->get_mat(); LMatrix4 child_space_xform = old_system_to_parent_xform * bp->get_lcs(); new_pn->set_transform(TransformState::make_mat(child_space_xform)); // tack the new system onto the managers _manager->attach_particlesystem(new_ps); get_physics_manager()->attach_physical(new_ps); } //////////////////////////////////////////////////////////////////// // Function : kill_particle // Access : Private // Description : Kills a particle, returns its slot to the empty // stack. //////////////////////////////////////////////////////////////////// void ParticleSystem:: kill_particle(int pool_index) { // get a handle on our particle BaseParticle *bp = (BaseParticle *) _physics_objects[pool_index].p(); // create a new system where this one died, maybe. if (_spawn_on_death_flag == true) { spawn_child_system(bp); } // tell everyone that it's dead bp->set_alive(false); bp->set_active(false); bp->die(); _free_particle_fifo.push_back(pool_index); // tell renderer _renderer->kill_particle(pool_index); _living_particles--; } //////////////////////////////////////////////////////////////////// // Function : resize_pool // Access : Private // Description : Resizes the particle pool //////////////////////////////////////////////////////////////////// #ifdef PSDEBUG #define PARTICLE_SYSTEM_RESIZE_POOL_SENTRIES #endif void ParticleSystem:: resize_pool(int size) { int i; int delta = size - _particle_pool_size; int po_delta = _particle_pool_size - _physics_objects.size(); #ifdef PARTICLE_SYSTEM_RESIZE_POOL_SENTRIES cout << "resizing particle pool from " << _particle_pool_size << " to " << size << endl; #endif if (_factory.is_null()) { particlesystem_cat.error() << "ParticleSystem::resize_pool" << " called with null _factory." << endl; return; } if (_renderer.is_null()) { particlesystem_cat.error() << "ParticleSystem::resize_pool" << " called with null _renderer." << endl; return; } _particle_pool_size = size; // make sure the physics_objects array is OK if (po_delta) { if (po_delta > 0) { for (i = 0; i < po_delta; i++) { // int free_index = _physics_objects.size(); BaseParticle *new_particle = _factory->alloc_particle(); if (new_particle) { _factory->populate_particle(new_particle); _physics_objects.push_back(new_particle); } else { #ifdef PSDEBUG cout << "Error allocating new particle" << endl; _particle_pool_size--; #endif } } } else { #ifdef PSDEBUG cout << "physics_object array is too large??" << endl; _particle_pool_size--; #endif po_delta = -po_delta; for (i = 0; i < po_delta; i++) { int delete_index = _physics_objects.size()-1; BaseParticle *bp = (BaseParticle *) _physics_objects[delete_index].p(); if (bp->get_alive()) { kill_particle(delete_index); _free_particle_fifo.pop_back(); } else { pdeque<int>::iterator i; i = find(_free_particle_fifo.begin(), _free_particle_fifo.end(), delete_index); if (i != _free_particle_fifo.end()) { _free_particle_fifo.erase(i); } } _physics_objects.pop_back(); } } } // disregard no change if (delta == 0) return; // update the pool if (delta > 0) { // add elements for (i = 0; i < delta; i++) { int free_index = _physics_objects.size(); BaseParticle *new_particle = _factory->alloc_particle(); if (new_particle) { _factory->populate_particle(new_particle); _physics_objects.push_back(new_particle); _free_particle_fifo.push_back(free_index); } else { #ifdef PSDEBUG cout << "Error allocating new particle" << endl; _particle_pool_size--; #endif } } } else { // subtract elements delta = -delta; for (i = 0; i < delta; i++) { int delete_index = _physics_objects.size()-1; BaseParticle *bp = (BaseParticle *) _physics_objects[delete_index].p(); if (bp->get_alive()) { #ifdef PSDEBUG cout << "WAS ALIVE" << endl; #endif kill_particle(delete_index); _free_particle_fifo.pop_back(); } else { #ifdef PSDEBUG cout << "WAS NOT ALIVE" << endl; #endif pdeque<int>::iterator i; i = find(_free_particle_fifo.begin(), _free_particle_fifo.end(), delete_index); if (i != _free_particle_fifo.end()) { _free_particle_fifo.erase(i); } #ifdef PSDEBUG else { cout << "particle not found in free FIFO!!!!!!!!" << endl; } #endif } _physics_objects.pop_back(); } } _renderer->resize_pool(_particle_pool_size); #ifdef PARTICLE_SYSTEM_RESIZE_POOL_SENTRIES cout << "particle pool resized" << endl; #endif } ////////////////////////////////////////////////////////////////////// // Function : update // Access : Public // Description : Updates the particle system. Call once per frame. ////////////////////////////////////////////////////////////////////// #ifdef PSDEBUG //#define PARTICLE_SYSTEM_UPDATE_SENTRIES #endif void ParticleSystem:: update(PN_stdfloat dt) { PStatTimer t1(_update_collector); int ttl_updates_left = _living_particles; int current_index = 0, index_counter = 0; BaseParticle *bp; PN_stdfloat age; #ifdef PSSANITYCHECK // check up on things if (sanity_check()) return; #endif #ifdef PARTICLE_SYSTEM_UPDATE_SENTRIES cout << "UPDATE: pool size: " << _particle_pool_size << ", live particles: " << _living_particles << endl; #endif // run through the particle array while (ttl_updates_left) { current_index = index_counter; index_counter++; #ifdef PSDEBUG if (current_index >= _particle_pool_size) { cout << "ERROR: _living_particles is out of sync (too large)" << endl; cout << "pool size: " << _particle_pool_size << ", live particles: " << _living_particles << ", updates left: " << ttl_updates_left << endl; break; } #endif // get the current particle. bp = (BaseParticle *) _physics_objects[current_index].p(); #ifdef PSDEBUG if (!bp) { cout << "NULL ptr at index " << current_index << endl; continue; } #endif if (bp->get_alive() == false) continue; age = bp->get_age() + dt; bp->set_age(age); //cerr<<"bp->get_position().get_z() returning "<<bp->get_position().get_z()<<endl; if (age >= bp->get_lifespan()) { kill_particle(current_index); } else if (get_floor_z() != -HUGE_VAL && bp->get_position().get_z() <= get_floor_z()) { // ...the particle is going under the floor. // Maybe tell the particle to bounce: bp->bounce()? kill_particle(current_index); } else { bp->update(); } // break out early if we're lucky ttl_updates_left--; } // generate new particles if necessary. _tics_since_birth += dt; while (_tics_since_birth >= _cur_birth_rate) { birth_litter(); _tics_since_birth -= _cur_birth_rate; } #ifdef PARTICLE_SYSTEM_UPDATE_SENTRIES cout << "particle update complete" << endl; #endif } #ifdef PSSANITYCHECK ////////////////////////////////////////////////////////////////////// // Function : sanity_check // Access : Private // Description : Checks consistency of live particle count, free // particle list, etc. returns 0 if everything is normal ////////////////////////////////////////////////////////////////////// #ifndef NDEBUG #define PSSCVERBOSE #endif class SC_valuenamepair : public ReferenceCount { public: int value; char *name; SC_valuenamepair(int v, char *s) : value(v), name(s) {} }; // returns 0 if OK, # of errors if not OK static int check_free_live_total_particles(pvector< PT(SC_valuenamepair) > live_counts, pvector< PT(SC_valuenamepair) > dead_counts, pvector< PT(SC_valuenamepair) > total_counts, int print_all = 0) { int val = 0; int l, d, t; for(l = 0; l < live_counts.size(); l++) { for(d = 0; d < dead_counts.size(); d++) { for(t = 0; t < total_counts.size(); t++) { int live = live_counts[l]->value; int dead = dead_counts[d]->value; int total = total_counts[t]->value; if ((live + dead) != total) { #ifdef PSSCVERBOSE cout << "free/live/total count: " << live_counts[l]->name << " (" << live << ") + " << dead_counts[d]->name << " (" << dead << ") = " << live + dead << ", != " << total_counts[t]->name << " (" << total << ")" << endl; #endif val++; } } } } return val; } int ParticleSystem:: sanity_check() { int result = 0; int i; BaseParticle *bp; int pool_size; /////////////////////////////////////////////////////////////////// // check pool size if (_particle_pool_size != _physics_objects.size()) { #ifdef PSSCVERBOSE cout << "_particle_pool_size (" << _particle_pool_size << ") != particle array size (" << _physics_objects.size() << ")" << endl; #endif result++; } pool_size = min(_particle_pool_size, _physics_objects.size()); /////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////// // find out how many particles are REALLY alive and dead int real_live_particle_count = 0; int real_dead_particle_count = 0; for (i = 0; i < _physics_objects.size(); i++) { bp = (BaseParticle *) _physics_objects[i].p(); if (true == bp->get_alive()) { real_live_particle_count++; } else { real_dead_particle_count++; } } if (real_live_particle_count != _living_particles) { #ifdef PSSCVERBOSE cout << "manually counted live particle count (" << real_live_particle_count << ") != _living_particles (" << _living_particles << ")" << endl; #endif result++; } if (real_dead_particle_count != _free_particle_fifo.size()) { #ifdef PSSCVERBOSE cout << "manually counted dead particle count (" << real_dead_particle_count << ") != free particle fifo size (" << _free_particle_fifo.size() << ")" << endl; #endif result++; } /////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////// // check the free particle pool for (i = 0; i < _free_particle_fifo.size(); i++) { int index = _free_particle_fifo[i]; // check that we're in bounds if (index >= pool_size) { #ifdef PSSCVERBOSE cout << "index from free particle fifo (" << index << ") is too large; pool size is " << pool_size << endl; #endif result++; continue; } // check that the particle is indeed dead bp = (BaseParticle *) _physics_objects[index].p(); if (true == bp->get_alive()) { #ifdef PSSCVERBOSE cout << "particle " << index << " in free fifo is not dead" << endl; #endif result++; } } /////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////// // check the numbers of free particles, live particles, and total particles pvector< PT(SC_valuenamepair) > live_counts; pvector< PT(SC_valuenamepair) > dead_counts; pvector< PT(SC_valuenamepair) > total_counts; live_counts.push_back(new SC_valuenamepair(real_live_particle_count, "real_live_particle_count")); dead_counts.push_back(new SC_valuenamepair(real_dead_particle_count, "real_dead_particle_count")); dead_counts.push_back(new SC_valuenamepair(_free_particle_fifo.size(), "free particle fifo size")); total_counts.push_back(new SC_valuenamepair(_particle_pool_size, "_particle_pool_size")); total_counts.push_back(new SC_valuenamepair(_physics_objects.size(), "actual particle pool size")); result += check_free_live_total_particles(live_counts, dead_counts, total_counts); /////////////////////////////////////////////////////////////////// return result; } #endif //////////////////////////////////////////////////////////////////// // Function : output // Access : Public // Description : Write a string representation of this instance to // <out>. //////////////////////////////////////////////////////////////////// void ParticleSystem:: output(ostream &out) const { #ifndef NDEBUG //[ out<<"ParticleSystem"; #endif //] NDEBUG } //////////////////////////////////////////////////////////////////// // Function : write_free_particle_fifo // Access : Public // Description : Write a string representation of this instance to // <out>. //////////////////////////////////////////////////////////////////// void ParticleSystem:: write_free_particle_fifo(ostream &out, int indent) const { #ifndef NDEBUG //[ out.width(indent); out<<""<<"_free_particle_fifo ("<<_free_particle_fifo.size()<<" forces)\n"; for (pdeque< int >::const_iterator i=_free_particle_fifo.begin(); i != _free_particle_fifo.end(); ++i) { out.width(indent+2); out<<""; out<<(*i)<<"\n"; } #endif //] NDEBUG } //////////////////////////////////////////////////////////////////// // Function : write_spawn_templates // Access : Public // Description : Write a string representation of this instance to // <out>. //////////////////////////////////////////////////////////////////// void ParticleSystem:: write_spawn_templates(ostream &out, int indent) const { #ifndef NDEBUG //[ out.width(indent); out<<""<<"_spawn_templates ("<<_spawn_templates.size()<<" templates)\n"; for (pvector< PT(ParticleSystem) >::const_iterator i=_spawn_templates.begin(); i != _spawn_templates.end(); ++i) { (*i)->write(out, indent+2); } #endif //] NDEBUG } //////////////////////////////////////////////////////////////////// // Function : write // Access : Public // Description : Write a string representation of this instance to // <out>. //////////////////////////////////////////////////////////////////// void ParticleSystem:: write(ostream &out, int indent) const { #ifndef NDEBUG //[ out.width(indent); out<<""; out<<"ParticleSystem:\n"; out.width(indent+2); out<<""; out<<"_particle_pool_size "<<_particle_pool_size<<"\n"; out.width(indent+2); out<<""; out<<"_living_particles "<<_living_particles<<"\n"; out.width(indent+2); out<<""; out<<"_tics_since_birth "<<_tics_since_birth<<"\n"; out.width(indent+2); out<<""; out<<"_litter_size "<<_litter_size<<"\n"; out.width(indent+2); out<<""; out<<"_litter_spread "<<_litter_spread<<"\n"; out.width(indent+2); out<<""; out<<"_system_age "<<_system_age<<"\n"; out.width(indent+2); out<<""; out<<"_system_lifespan "<<_system_lifespan<<"\n"; out.width(indent+2); out<<""; out<<"_factory "<<_factory<<"\n"; out.width(indent+2); out<<""; out<<"_emitter "<<_emitter<<"\n"; out.width(indent+2); out<<""; out<<"_renderer "<<_renderer<<"\n"; out.width(indent+2); out<<""; out<<"_manager "<<_manager<<"\n"; out.width(indent+2); out<<""; out<<"_template_system_flag "<<_template_system_flag<<"\n"; out.width(indent+2); out<<""; out<<"_render_parent "<<_render_parent<<"\n"; out.width(indent+2); out<<""; out<<"_render_node "<<_render_node_path<<"\n"; out.width(indent+2); out<<""; out<<"_active_system_flag "<<_active_system_flag<<"\n"; out.width(indent+2); out<<""; out<<"_local_velocity_flag "<<_local_velocity_flag<<"\n"; out.width(indent+2); out<<""; out<<"_system_grows_older_flag "<<_system_grows_older_flag<<"\n"; out.width(indent+2); out<<""; out<<"_spawn_on_death_flag "<<_spawn_on_death_flag<<"\n"; out.width(indent+2); out<<""; out<<"_spawn_render_node "<<_spawn_render_node_path<<"\n"; out.width(indent+2); out<<""; out<<"_i_was_spawned_flag "<<_i_was_spawned_flag<<"\n"; write_free_particle_fifo(out, indent+2); write_spawn_templates(out, indent+2); Physical::write(out, indent+2); #endif //] NDEBUG }
32.18694
103
0.589466
kestred
ac32ce6fb7fe79c5c642d89efd6000ff73e5129b
368
hh
C++
src/elle/archive/tar.hh
wk8/elle
a66d3c0aeca86bcd13ec14d3797edc660b2496fc
[ "Apache-2.0" ]
124
2017-06-22T19:20:54.000Z
2021-12-23T21:36:37.000Z
src/elle/archive/tar.hh
wk8/elle
a66d3c0aeca86bcd13ec14d3797edc660b2496fc
[ "Apache-2.0" ]
4
2017-08-21T15:57:29.000Z
2019-01-10T02:52:35.000Z
src/elle/archive/tar.hh
wk8/elle
a66d3c0aeca86bcd13ec14d3797edc660b2496fc
[ "Apache-2.0" ]
12
2017-06-29T09:15:35.000Z
2020-12-31T12:39:52.000Z
#pragma once #include <elle/archive/archive.hh> namespace elle { namespace archive { /// Helper for tar archiving. /// /// @see archive. void tar(Paths const& files, bfs::path const& path, Renamer const& renamer = {}); /// Helper for tar extraction. /// /// @see extract. void untar(bfs::path const& path); } }
16
50
0.57337
wk8
ac3433138a0b694c715f0a9fa6ac081e87f81e92
362
cpp
C++
26_cpp_stl/05_operator.cpp
afterloe/cpp_practice
f76fa3963def3e71255a198d62818c4076253d4a
[ "MIT" ]
null
null
null
26_cpp_stl/05_operator.cpp
afterloe/cpp_practice
f76fa3963def3e71255a198d62818c4076253d4a
[ "MIT" ]
null
null
null
26_cpp_stl/05_operator.cpp
afterloe/cpp_practice
f76fa3963def3e71255a198d62818c4076253d4a
[ "MIT" ]
null
null
null
#include <iostream> #include <string> using namespace std; class Student { public: string name; int age; }; ostream &operator<<(ostream &out, Student &stu) { out << stu.name << " | " << stu.age; return out; } int main() { Student stu; stu.name = "joe"; stu.age = 10; cout << stu << endl; return EXIT_SUCCESS; }
13.923077
47
0.560773
afterloe
ac34978eb29682dc1962c2d6bea27229ee9fbb64
602
cpp
C++
RealmLib/Packets/Client/EnterArena.cpp
SometimesRain/realmnet
76ead08b4a0163a05b65389e512942a620331256
[ "MIT" ]
10
2018-11-25T21:59:43.000Z
2022-01-09T22:41:52.000Z
RealmLib/Packets/Client/EnterArena.cpp
SometimesRain/realmnet
76ead08b4a0163a05b65389e512942a620331256
[ "MIT" ]
1
2018-11-28T12:59:59.000Z
2018-11-28T12:59:59.000Z
RealmLib/Packets/Client/EnterArena.cpp
SometimesRain/realmnet
76ead08b4a0163a05b65389e512942a620331256
[ "MIT" ]
6
2018-12-28T22:34:13.000Z
2021-10-16T10:17:17.000Z
#include "stdafx.h" #include <GameData/Constants.h> #include <GameData/TypeManager.h> #include "Packets/PacketWriter.h" #include "Packets/PacketReader.h" #include <Packets/EnterArena.h> EnterArena::EnterArena(int currency) : currency(currency) { } EnterArena::EnterArena(byte* data) { PacketReader r(data); r.read(currency); } void EnterArena::emplace(byte* buffer) const { PacketWriter w(buffer, size(), TypeManager::typeToId[PacketType::EnterArena]); w.write(currency); } int EnterArena::size() const { return 9; } String EnterArena::toString() const { return String("ENTERARENA"); }
15.842105
79
0.734219
SometimesRain
ac3a1fc7f199414c612cedbf24cd1c91679ed058
18,287
cc
C++
content/common/throttling_url_loader_unittest.cc
metux/chromium-deb
3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
content/common/throttling_url_loader_unittest.cc
metux/chromium-deb
3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
content/common/throttling_url_loader_unittest.cc
metux/chromium-deb
3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
// Copyright 2017 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "content/common/throttling_url_loader.h" #include "base/logging.h" #include "base/macros.h" #include "base/message_loop/message_loop.h" #include "base/run_loop.h" #include "content/public/common/url_loader.mojom.h" #include "content/public/common/url_loader_factory.mojom.h" #include "content/public/common/url_loader_throttle.h" #include "net/traffic_annotation/network_traffic_annotation_test_helper.h" #include "testing/gtest/include/gtest/gtest.h" namespace content { namespace { class TestURLLoaderFactory : public mojom::URLLoaderFactory { public: TestURLLoaderFactory() : binding_(this) { binding_.Bind(mojo::MakeRequest(&factory_ptr_)); } mojom::URLLoaderFactoryPtr& factory_ptr() { return factory_ptr_; } mojom::URLLoaderClientPtr& client_ptr() { return client_ptr_; } size_t create_loader_and_start_called() const { return create_loader_and_start_called_; } void NotifyClientOnReceiveResponse() { client_ptr_->OnReceiveResponse(ResourceResponseHead(), base::nullopt, nullptr); } void NotifyClientOnReceiveRedirect() { client_ptr_->OnReceiveRedirect(net::RedirectInfo(), ResourceResponseHead()); } void NotifyClientOnComplete(int error_code) { ResourceRequestCompletionStatus data; data.error_code = error_code; client_ptr_->OnComplete(data); } private: // mojom::URLLoaderFactory implementation. void CreateLoaderAndStart(mojom::URLLoaderAssociatedRequest request, int32_t routing_id, int32_t request_id, uint32_t options, const ResourceRequest& url_request, mojom::URLLoaderClientPtr client, const net::MutableNetworkTrafficAnnotationTag& traffic_annotation) override { create_loader_and_start_called_++; client_ptr_ = std::move(client); } void SyncLoad(int32_t routing_id, int32_t request_id, const ResourceRequest& request, SyncLoadCallback callback) override { NOTREACHED(); } size_t create_loader_and_start_called_ = 0; mojo::Binding<mojom::URLLoaderFactory> binding_; mojom::URLLoaderFactoryPtr factory_ptr_; mojom::URLLoaderClientPtr client_ptr_; DISALLOW_COPY_AND_ASSIGN(TestURLLoaderFactory); }; class TestURLLoaderClient : public mojom::URLLoaderClient { public: TestURLLoaderClient() {} size_t on_received_response_called() const { return on_received_response_called_; } size_t on_received_redirect_called() const { return on_received_redirect_called_; } size_t on_complete_called() const { return on_complete_called_; } using OnCompleteCallback = base::Callback<void(int error_code)>; void set_on_complete_callback(const OnCompleteCallback& callback) { on_complete_callback_ = callback; } private: // mojom::URLLoaderClient implementation: void OnReceiveResponse( const ResourceResponseHead& response_head, const base::Optional<net::SSLInfo>& ssl_info, mojom::DownloadedTempFilePtr downloaded_file) override { on_received_response_called_++; } void OnReceiveRedirect(const net::RedirectInfo& redirect_info, const ResourceResponseHead& response_head) override { on_received_redirect_called_++; } void OnDataDownloaded(int64_t data_len, int64_t encoded_data_len) override {} void OnUploadProgress(int64_t current_position, int64_t total_size, OnUploadProgressCallback ack_callback) override {} void OnReceiveCachedMetadata(const std::vector<uint8_t>& data) override {} void OnTransferSizeUpdated(int32_t transfer_size_diff) override {} void OnStartLoadingResponseBody( mojo::ScopedDataPipeConsumerHandle body) override {} void OnComplete(const ResourceRequestCompletionStatus& status) override { on_complete_called_++; if (on_complete_callback_) on_complete_callback_.Run(status.error_code); } size_t on_received_response_called_ = 0; size_t on_received_redirect_called_ = 0; size_t on_complete_called_ = 0; OnCompleteCallback on_complete_callback_; DISALLOW_COPY_AND_ASSIGN(TestURLLoaderClient); }; class TestURLLoaderThrottle : public URLLoaderThrottle { public: TestURLLoaderThrottle() {} using ThrottleCallback = base::Callback<void(URLLoaderThrottle::Delegate* delegate, bool* defer)>; size_t will_start_request_called() const { return will_start_request_called_; } size_t will_redirect_request_called() const { return will_redirect_request_called_; } size_t will_process_response_called() const { return will_process_response_called_; } void set_will_start_request_callback(const ThrottleCallback& callback) { will_start_request_callback_ = callback; } void set_will_redirect_request_callback(const ThrottleCallback& callback) { will_redirect_request_callback_ = callback; } void set_will_process_response_callback(const ThrottleCallback& callback) { will_process_response_callback_ = callback; } Delegate* delegate() const { return delegate_; } private: // URLLoaderThrottle implementation. void WillStartRequest(const GURL& url, int load_flags, ResourceType resource_type, bool* defer) override { will_start_request_called_++; if (will_start_request_callback_) will_start_request_callback_.Run(delegate_, defer); } void WillRedirectRequest(const net::RedirectInfo& redirect_info, bool* defer) override { will_redirect_request_called_++; if (will_redirect_request_callback_) will_redirect_request_callback_.Run(delegate_, defer); } void WillProcessResponse(bool* defer) override { will_process_response_called_++; if (will_process_response_callback_) will_process_response_callback_.Run(delegate_, defer); } size_t will_start_request_called_ = 0; size_t will_redirect_request_called_ = 0; size_t will_process_response_called_ = 0; ThrottleCallback will_start_request_callback_; ThrottleCallback will_redirect_request_callback_; ThrottleCallback will_process_response_callback_; DISALLOW_COPY_AND_ASSIGN(TestURLLoaderThrottle); }; class ThrottlingURLLoaderTest : public testing::Test { public: ThrottlingURLLoaderTest() {} protected: // testing::Test implementation. void SetUp() override { auto throttle = base::MakeUnique<TestURLLoaderThrottle>(); throttle_ = throttle.get(); throttles_.push_back(std::move(throttle)); } void CreateLoaderAndStart() { ResourceRequest request; request.url = GURL("http://example.org"); loader_ = ThrottlingURLLoader::CreateLoaderAndStart( factory_.factory_ptr().get(), std::move(throttles_), 0, 0, 0, request, &client_, TRAFFIC_ANNOTATION_FOR_TESTS); factory_.factory_ptr().FlushForTesting(); } // Be the first member so it is destroyed last. base::MessageLoop message_loop_; std::unique_ptr<ThrottlingURLLoader> loader_; std::vector<std::unique_ptr<URLLoaderThrottle>> throttles_; TestURLLoaderFactory factory_; TestURLLoaderClient client_; // Owned by |throttles_| or |loader_|. TestURLLoaderThrottle* throttle_ = nullptr; DISALLOW_COPY_AND_ASSIGN(ThrottlingURLLoaderTest); }; TEST_F(ThrottlingURLLoaderTest, CancelBeforeStart) { throttle_->set_will_start_request_callback( base::Bind([](URLLoaderThrottle::Delegate* delegate, bool* defer) { delegate->CancelWithError(net::ERR_ACCESS_DENIED); })); base::RunLoop run_loop; client_.set_on_complete_callback(base::Bind( [](const base::Closure& quit_closure, int error) { EXPECT_EQ(net::ERR_ACCESS_DENIED, error); quit_closure.Run(); }, run_loop.QuitClosure())); CreateLoaderAndStart(); run_loop.Run(); EXPECT_EQ(1u, throttle_->will_start_request_called()); EXPECT_EQ(0u, throttle_->will_redirect_request_called()); EXPECT_EQ(0u, throttle_->will_process_response_called()); EXPECT_EQ(0u, factory_.create_loader_and_start_called()); EXPECT_EQ(0u, client_.on_received_response_called()); EXPECT_EQ(0u, client_.on_received_redirect_called()); EXPECT_EQ(1u, client_.on_complete_called()); } TEST_F(ThrottlingURLLoaderTest, DeferBeforeStart) { throttle_->set_will_start_request_callback( base::Bind([](URLLoaderThrottle::Delegate* delegate, bool* defer) { *defer = true; })); base::RunLoop run_loop; client_.set_on_complete_callback(base::Bind( [](const base::Closure& quit_closure, int error) { EXPECT_EQ(net::OK, error); quit_closure.Run(); }, run_loop.QuitClosure())); CreateLoaderAndStart(); EXPECT_EQ(1u, throttle_->will_start_request_called()); EXPECT_EQ(0u, throttle_->will_redirect_request_called()); EXPECT_EQ(0u, throttle_->will_process_response_called()); EXPECT_EQ(0u, factory_.create_loader_and_start_called()); EXPECT_EQ(0u, client_.on_received_response_called()); EXPECT_EQ(0u, client_.on_received_redirect_called()); EXPECT_EQ(0u, client_.on_complete_called()); throttle_->delegate()->Resume(); factory_.factory_ptr().FlushForTesting(); EXPECT_EQ(1u, factory_.create_loader_and_start_called()); factory_.NotifyClientOnReceiveResponse(); factory_.NotifyClientOnComplete(net::OK); run_loop.Run(); EXPECT_EQ(1u, throttle_->will_start_request_called()); EXPECT_EQ(0u, throttle_->will_redirect_request_called()); EXPECT_EQ(1u, throttle_->will_process_response_called()); EXPECT_EQ(1u, client_.on_received_response_called()); EXPECT_EQ(0u, client_.on_received_redirect_called()); EXPECT_EQ(1u, client_.on_complete_called()); } TEST_F(ThrottlingURLLoaderTest, CancelBeforeRedirect) { throttle_->set_will_redirect_request_callback( base::Bind([](URLLoaderThrottle::Delegate* delegate, bool* defer) { delegate->CancelWithError(net::ERR_ACCESS_DENIED); })); base::RunLoop run_loop; client_.set_on_complete_callback(base::Bind( [](const base::Closure& quit_closure, int error) { EXPECT_EQ(net::ERR_ACCESS_DENIED, error); quit_closure.Run(); }, run_loop.QuitClosure())); CreateLoaderAndStart(); factory_.NotifyClientOnReceiveRedirect(); run_loop.Run(); EXPECT_EQ(1u, throttle_->will_start_request_called()); EXPECT_EQ(1u, throttle_->will_redirect_request_called()); EXPECT_EQ(0u, throttle_->will_process_response_called()); EXPECT_EQ(0u, client_.on_received_response_called()); EXPECT_EQ(0u, client_.on_received_redirect_called()); EXPECT_EQ(1u, client_.on_complete_called()); } TEST_F(ThrottlingURLLoaderTest, DeferBeforeRedirect) { base::RunLoop run_loop1; throttle_->set_will_redirect_request_callback(base::Bind( [](const base::Closure& quit_closure, URLLoaderThrottle::Delegate* delegate, bool* defer) { *defer = true; quit_closure.Run(); }, run_loop1.QuitClosure())); base::RunLoop run_loop2; client_.set_on_complete_callback(base::Bind( [](const base::Closure& quit_closure, int error) { EXPECT_EQ(net::ERR_UNEXPECTED, error); quit_closure.Run(); }, run_loop2.QuitClosure())); CreateLoaderAndStart(); factory_.NotifyClientOnReceiveRedirect(); run_loop1.Run(); EXPECT_EQ(1u, throttle_->will_start_request_called()); EXPECT_EQ(1u, throttle_->will_redirect_request_called()); EXPECT_EQ(0u, throttle_->will_process_response_called()); factory_.NotifyClientOnComplete(net::ERR_UNEXPECTED); base::RunLoop run_loop3; run_loop3.RunUntilIdle(); EXPECT_EQ(0u, client_.on_received_response_called()); EXPECT_EQ(0u, client_.on_received_redirect_called()); EXPECT_EQ(0u, client_.on_complete_called()); throttle_->delegate()->Resume(); run_loop2.Run(); EXPECT_EQ(1u, throttle_->will_start_request_called()); EXPECT_EQ(1u, throttle_->will_redirect_request_called()); EXPECT_EQ(0u, throttle_->will_process_response_called()); EXPECT_EQ(0u, client_.on_received_response_called()); EXPECT_EQ(1u, client_.on_received_redirect_called()); EXPECT_EQ(1u, client_.on_complete_called()); } TEST_F(ThrottlingURLLoaderTest, CancelBeforeResponse) { throttle_->set_will_process_response_callback( base::Bind([](URLLoaderThrottle::Delegate* delegate, bool* defer) { delegate->CancelWithError(net::ERR_ACCESS_DENIED); })); base::RunLoop run_loop; client_.set_on_complete_callback(base::Bind( [](const base::Closure& quit_closure, int error) { EXPECT_EQ(net::ERR_ACCESS_DENIED, error); quit_closure.Run(); }, run_loop.QuitClosure())); CreateLoaderAndStart(); factory_.NotifyClientOnReceiveResponse(); run_loop.Run(); EXPECT_EQ(1u, throttle_->will_start_request_called()); EXPECT_EQ(0u, throttle_->will_redirect_request_called()); EXPECT_EQ(1u, throttle_->will_process_response_called()); EXPECT_EQ(0u, client_.on_received_response_called()); EXPECT_EQ(0u, client_.on_received_redirect_called()); EXPECT_EQ(1u, client_.on_complete_called()); } TEST_F(ThrottlingURLLoaderTest, DeferBeforeResponse) { base::RunLoop run_loop1; throttle_->set_will_process_response_callback(base::Bind( [](const base::Closure& quit_closure, URLLoaderThrottle::Delegate* delegate, bool* defer) { *defer = true; quit_closure.Run(); }, run_loop1.QuitClosure())); base::RunLoop run_loop2; client_.set_on_complete_callback(base::Bind( [](const base::Closure& quit_closure, int error) { EXPECT_EQ(net::ERR_UNEXPECTED, error); quit_closure.Run(); }, run_loop2.QuitClosure())); CreateLoaderAndStart(); factory_.NotifyClientOnReceiveResponse(); run_loop1.Run(); EXPECT_EQ(1u, throttle_->will_start_request_called()); EXPECT_EQ(0u, throttle_->will_redirect_request_called()); EXPECT_EQ(1u, throttle_->will_process_response_called()); factory_.NotifyClientOnComplete(net::ERR_UNEXPECTED); base::RunLoop run_loop3; run_loop3.RunUntilIdle(); EXPECT_EQ(0u, client_.on_received_response_called()); EXPECT_EQ(0u, client_.on_received_redirect_called()); EXPECT_EQ(0u, client_.on_complete_called()); throttle_->delegate()->Resume(); run_loop2.Run(); EXPECT_EQ(1u, throttle_->will_start_request_called()); EXPECT_EQ(0u, throttle_->will_redirect_request_called()); EXPECT_EQ(1u, throttle_->will_process_response_called()); EXPECT_EQ(1u, client_.on_received_response_called()); EXPECT_EQ(0u, client_.on_received_redirect_called()); EXPECT_EQ(1u, client_.on_complete_called()); } TEST_F(ThrottlingURLLoaderTest, ResumeNoOpIfNotDeferred) { auto resume_callback = base::Bind([](URLLoaderThrottle::Delegate* delegate, bool* defer) { delegate->Resume(); delegate->Resume(); }); throttle_->set_will_start_request_callback(resume_callback); throttle_->set_will_redirect_request_callback(resume_callback); throttle_->set_will_process_response_callback(resume_callback); base::RunLoop run_loop; client_.set_on_complete_callback(base::Bind( [](const base::Closure& quit_closure, int error) { EXPECT_EQ(net::OK, error); quit_closure.Run(); }, run_loop.QuitClosure())); CreateLoaderAndStart(); factory_.NotifyClientOnReceiveRedirect(); factory_.NotifyClientOnReceiveResponse(); factory_.NotifyClientOnComplete(net::OK); run_loop.Run(); EXPECT_EQ(1u, throttle_->will_start_request_called()); EXPECT_EQ(1u, throttle_->will_redirect_request_called()); EXPECT_EQ(1u, throttle_->will_process_response_called()); EXPECT_EQ(1u, client_.on_received_response_called()); EXPECT_EQ(1u, client_.on_received_redirect_called()); EXPECT_EQ(1u, client_.on_complete_called()); } TEST_F(ThrottlingURLLoaderTest, CancelNoOpIfAlreadyCanceled) { throttle_->set_will_start_request_callback( base::Bind([](URLLoaderThrottle::Delegate* delegate, bool* defer) { delegate->CancelWithError(net::ERR_ACCESS_DENIED); delegate->CancelWithError(net::ERR_UNEXPECTED); })); base::RunLoop run_loop; client_.set_on_complete_callback(base::Bind( [](const base::Closure& quit_closure, int error) { EXPECT_EQ(net::ERR_ACCESS_DENIED, error); quit_closure.Run(); }, run_loop.QuitClosure())); CreateLoaderAndStart(); throttle_->delegate()->CancelWithError(net::ERR_INVALID_ARGUMENT); run_loop.Run(); EXPECT_EQ(1u, throttle_->will_start_request_called()); EXPECT_EQ(0u, throttle_->will_redirect_request_called()); EXPECT_EQ(0u, throttle_->will_process_response_called()); EXPECT_EQ(0u, factory_.create_loader_and_start_called()); EXPECT_EQ(0u, client_.on_received_response_called()); EXPECT_EQ(0u, client_.on_received_redirect_called()); EXPECT_EQ(1u, client_.on_complete_called()); } TEST_F(ThrottlingURLLoaderTest, ResumeNoOpIfAlreadyCanceled) { throttle_->set_will_process_response_callback( base::Bind([](URLLoaderThrottle::Delegate* delegate, bool* defer) { delegate->CancelWithError(net::ERR_ACCESS_DENIED); delegate->Resume(); })); base::RunLoop run_loop1; client_.set_on_complete_callback(base::Bind( [](const base::Closure& quit_closure, int error) { EXPECT_EQ(net::ERR_ACCESS_DENIED, error); quit_closure.Run(); }, run_loop1.QuitClosure())); CreateLoaderAndStart(); factory_.NotifyClientOnReceiveResponse(); run_loop1.Run(); throttle_->delegate()->Resume(); base::RunLoop run_loop2; run_loop2.RunUntilIdle(); EXPECT_EQ(1u, throttle_->will_start_request_called()); EXPECT_EQ(0u, throttle_->will_redirect_request_called()); EXPECT_EQ(1u, throttle_->will_process_response_called()); EXPECT_EQ(0u, client_.on_received_response_called()); EXPECT_EQ(0u, client_.on_received_redirect_called()); EXPECT_EQ(1u, client_.on_complete_called()); } } // namespace } // namespace content
32.423759
80
0.7338
metux
ac3a2aea08079ab75c5aa124d7a3037b64ba6c48
12,768
cc
C++
third_party/crashpad/crashpad/util/posix/process_info_linux.cc
metux/chromium-deb
3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
third_party/crashpad/crashpad/util/posix/process_info_linux.cc
metux/chromium-deb
3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
third_party/crashpad/crashpad/util/posix/process_info_linux.cc
metux/chromium-deb
3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
// Copyright 2017 The Crashpad Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "util/posix/process_info.h" #include <ctype.h> #include <errno.h> #include <string.h> #include <time.h> #include <unistd.h> #include "base/files/file_path.h" #include "base/files/scoped_file.h" #include "base/logging.h" #include "base/posix/eintr_wrapper.h" #include "base/strings/string_number_conversions.h" #include "base/strings/string_piece.h" #include "util/file/delimited_file_reader.h" #include "util/file/file_io.h" #include "util/file/file_reader.h" #include "util/linux/thread_info.h" namespace crashpad { namespace { // If the string |pattern| is matched exactly at the start of |input|, advance // |input| past |pattern| and return true. bool AdvancePastPrefix(const char** input, const char* pattern) { size_t length = strlen(pattern); if (strncmp(*input, pattern, length) == 0) { *input += length; return true; } return false; } #define MAKE_ADAPTER(type, function) \ bool ConvertStringToNumber(const base::StringPiece& input, type* value) { \ return function(input, value); \ } MAKE_ADAPTER(int, base::StringToInt) MAKE_ADAPTER(unsigned int, base::StringToUint) MAKE_ADAPTER(uint64_t, base::StringToUint64) #undef MAKE_ADAPTER // Attempt to convert a prefix of |input| to numeric type T. On success, set // |value| to the number, advance |input| past the number, and return true. template <typename T> bool AdvancePastNumber(const char** input, T* value) { size_t length = 0; if (std::numeric_limits<T>::is_signed && **input == '-') { ++length; } while (isdigit((*input)[length])) { ++length; } bool success = ConvertStringToNumber(base::StringPiece(*input, length), value); if (success) { *input += length; return true; } return false; } void SubtractTimespec(const timespec& t1, const timespec& t2, timespec* result) { result->tv_sec = t1.tv_sec - t2.tv_sec; result->tv_nsec = t1.tv_nsec - t2.tv_nsec; if (result->tv_nsec < 0) { result->tv_sec -= 1; result->tv_nsec += static_cast<long>(1E9); } } void TimespecToTimeval(const timespec& ts, timeval* tv) { tv->tv_sec = ts.tv_sec; tv->tv_usec = ts.tv_nsec / 1000; } } // namespace ProcessInfo::ProcessInfo() : supplementary_groups_(), start_time_(), pid_(-1), ppid_(-1), uid_(-1), euid_(-1), suid_(-1), gid_(-1), egid_(-1), sgid_(-1), start_time_initialized_(), is_64_bit_initialized_(), is_64_bit_(false), initialized_() {} ProcessInfo::~ProcessInfo() {} bool ProcessInfo::Initialize(pid_t pid) { INITIALIZATION_STATE_SET_INITIALIZING(initialized_); pid_ = pid; { char path[32]; snprintf(path, sizeof(path), "/proc/%d/status", pid_); FileReader status_file; if (!status_file.Open(base::FilePath(path))) { return false; } DelimitedFileReader status_file_line_reader(&status_file); bool have_ppid = false; bool have_uids = false; bool have_gids = false; bool have_groups = false; std::string line; DelimitedFileReader::Result result; while ((result = status_file_line_reader.GetLine(&line)) == DelimitedFileReader::Result::kSuccess) { if (line.back() != '\n') { LOG(ERROR) << "format error: unterminated line at EOF"; return false; } bool understood_line = false; const char* line_c = line.c_str(); if (AdvancePastPrefix(&line_c, "PPid:\t")) { if (have_ppid) { LOG(ERROR) << "format error: multiple PPid lines"; return false; } have_ppid = AdvancePastNumber(&line_c, &ppid_); if (!have_ppid) { LOG(ERROR) << "format error: unrecognized PPid format"; return false; } understood_line = true; } else if (AdvancePastPrefix(&line_c, "Uid:\t")) { if (have_uids) { LOG(ERROR) << "format error: multiple Uid lines"; return false; } uid_t fsuid; have_uids = AdvancePastNumber(&line_c, &uid_) && AdvancePastPrefix(&line_c, "\t") && AdvancePastNumber(&line_c, &euid_) && AdvancePastPrefix(&line_c, "\t") && AdvancePastNumber(&line_c, &suid_) && AdvancePastPrefix(&line_c, "\t") && AdvancePastNumber(&line_c, &fsuid); if (!have_uids) { LOG(ERROR) << "format error: unrecognized Uid format"; return false; } understood_line = true; } else if (AdvancePastPrefix(&line_c, "Gid:\t")) { if (have_gids) { LOG(ERROR) << "format error: multiple Gid lines"; return false; } gid_t fsgid; have_gids = AdvancePastNumber(&line_c, &gid_) && AdvancePastPrefix(&line_c, "\t") && AdvancePastNumber(&line_c, &egid_) && AdvancePastPrefix(&line_c, "\t") && AdvancePastNumber(&line_c, &sgid_) && AdvancePastPrefix(&line_c, "\t") && AdvancePastNumber(&line_c, &fsgid); if (!have_gids) { LOG(ERROR) << "format error: unrecognized Gid format"; return false; } understood_line = true; } else if (AdvancePastPrefix(&line_c, "Groups:\t")) { if (have_groups) { LOG(ERROR) << "format error: multiple Groups lines"; return false; } if (!AdvancePastPrefix(&line_c, " ")) { // In Linux 4.10, even an empty Groups: line has a trailing space. gid_t group; while (AdvancePastNumber(&line_c, &group)) { supplementary_groups_.insert(group); if (!AdvancePastPrefix(&line_c, " ")) { LOG(ERROR) << "format error: unrecognized Groups format"; return false; } } } have_groups = true; understood_line = true; } if (understood_line && line_c != &line.back()) { LOG(ERROR) << "format error: unconsumed trailing data"; return false; } } if (result != DelimitedFileReader::Result::kEndOfFile) { return false; } if (!have_ppid || !have_uids || !have_gids || !have_groups) { LOG(ERROR) << "format error: missing fields"; return false; } } INITIALIZATION_STATE_SET_VALID(initialized_); return true; } pid_t ProcessInfo::ProcessID() const { INITIALIZATION_STATE_DCHECK_VALID(initialized_); return pid_; } pid_t ProcessInfo::ParentProcessID() const { INITIALIZATION_STATE_DCHECK_VALID(initialized_); return ppid_; } uid_t ProcessInfo::RealUserID() const { INITIALIZATION_STATE_DCHECK_VALID(initialized_); return uid_; } uid_t ProcessInfo::EffectiveUserID() const { INITIALIZATION_STATE_DCHECK_VALID(initialized_); return euid_; } uid_t ProcessInfo::SavedUserID() const { INITIALIZATION_STATE_DCHECK_VALID(initialized_); return suid_; } gid_t ProcessInfo::RealGroupID() const { INITIALIZATION_STATE_DCHECK_VALID(initialized_); return gid_; } gid_t ProcessInfo::EffectiveGroupID() const { INITIALIZATION_STATE_DCHECK_VALID(initialized_); return egid_; } gid_t ProcessInfo::SavedGroupID() const { INITIALIZATION_STATE_DCHECK_VALID(initialized_); return sgid_; } std::set<gid_t> ProcessInfo::SupplementaryGroups() const { INITIALIZATION_STATE_DCHECK_VALID(initialized_); return supplementary_groups_; } std::set<gid_t> ProcessInfo::AllGroups() const { INITIALIZATION_STATE_DCHECK_VALID(initialized_); std::set<gid_t> all_groups = SupplementaryGroups(); all_groups.insert(RealGroupID()); all_groups.insert(EffectiveGroupID()); all_groups.insert(SavedGroupID()); return all_groups; } bool ProcessInfo::DidChangePrivileges() const { INITIALIZATION_STATE_DCHECK_VALID(initialized_); // TODO(jperaza): Is this possible to determine? return false; } bool ProcessInfo::Is64Bit(bool* is_64_bit) const { INITIALIZATION_STATE_DCHECK_VALID(initialized_); if (is_64_bit_initialized_.is_uninitialized()) { is_64_bit_initialized_.set_invalid(); #if defined(ARCH_CPU_64_BITS) const bool am_64_bit = true; #else const bool am_64_bit = false; #endif if (pid_ == getpid()) { is_64_bit_ = am_64_bit; } else { ThreadInfo thread_info; if (!thread_info.Initialize(pid_)) { return false; } is_64_bit_ = thread_info.Is64Bit(); } is_64_bit_initialized_.set_valid(); } if (!is_64_bit_initialized_.is_valid()) { return false; } *is_64_bit = is_64_bit_; return true; } bool ProcessInfo::StartTime(timeval* start_time) const { INITIALIZATION_STATE_DCHECK_VALID(initialized_); if (start_time_initialized_.is_uninitialized()) { start_time_initialized_.set_invalid(); char path[32]; snprintf(path, sizeof(path), "/proc/%d/stat", pid_); std::string stat_contents; if (!LoggingReadEntireFile(base::FilePath(path), &stat_contents)) { return false; } // The process start time is the 22nd column. // The second column is the executable name in parentheses. // The executable name may have parentheses itself, so find the end of the // second column by working backwards to find the last closing parens and // then count forward to the 22nd column. size_t stat_pos = stat_contents.rfind(')'); if (stat_pos == std::string::npos) { LOG(ERROR) << "format error"; return false; } for (int index = 1; index < 21; ++index) { stat_pos = stat_contents.find(' ', stat_pos); if (stat_pos == std::string::npos) { break; } ++stat_pos; } if (stat_pos >= stat_contents.size()) { LOG(ERROR) << "format error"; return false; } const char* ticks_ptr = &stat_contents[stat_pos]; // start time is in jiffies instead of clock ticks pre 2.6. uint64_t ticks_after_boot; if (!AdvancePastNumber<uint64_t>(&ticks_ptr, &ticks_after_boot)) { LOG(ERROR) << "format error"; return false; } long clock_ticks_per_s = sysconf(_SC_CLK_TCK); if (clock_ticks_per_s <= 0) { PLOG(ERROR) << "sysconf"; return false; } timeval time_after_boot; time_after_boot.tv_sec = ticks_after_boot / clock_ticks_per_s; time_after_boot.tv_usec = (ticks_after_boot % clock_ticks_per_s) * (static_cast<long>(1E6) / clock_ticks_per_s); timespec uptime; if (clock_gettime(CLOCK_BOOTTIME, &uptime) != 0) { PLOG(ERROR) << "clock_gettime"; return false; } timespec current_time; if (clock_gettime(CLOCK_REALTIME, &current_time) != 0) { PLOG(ERROR) << "clock_gettime"; return false; } timespec boot_time_ts; SubtractTimespec(current_time, uptime, &boot_time_ts); timeval boot_time_tv; TimespecToTimeval(boot_time_ts, &boot_time_tv); timeradd(&boot_time_tv, &time_after_boot, &start_time_); start_time_initialized_.set_valid(); } if (!start_time_initialized_.is_valid()) { return false; } *start_time = start_time_; return true; } bool ProcessInfo::Arguments(std::vector<std::string>* argv) const { INITIALIZATION_STATE_DCHECK_VALID(initialized_); char path[32]; snprintf(path, sizeof(path), "/proc/%d/cmdline", pid_); FileReader cmdline_file; if (!cmdline_file.Open(base::FilePath(path))) { return false; } DelimitedFileReader cmdline_file_field_reader(&cmdline_file); std::vector<std::string> local_argv; std::string argument; DelimitedFileReader::Result result; while ((result = cmdline_file_field_reader.GetDelim('\0', &argument)) == DelimitedFileReader::Result::kSuccess) { if (argument.back() != '\0') { LOG(ERROR) << "format error"; return false; } argument.pop_back(); local_argv.push_back(argument); } if (result != DelimitedFileReader::Result::kEndOfFile) { return false; } argv->swap(local_argv); return true; } } // namespace crashpad
29.084282
78
0.644189
metux
ac3c95a1375cbc236fc8821d5baa34156e8b71cf
3,810
hpp
C++
SDE.hpp
jetpotion/MonteCarloOptionPricer
0024c9c900d1c968fca8946aa438ba07453272d8
[ "MIT" ]
2
2020-12-13T00:07:01.000Z
2021-01-14T00:40:33.000Z
SDE.hpp
jetpotion/MonteCarloOptionPricer
0024c9c900d1c968fca8946aa438ba07453272d8
[ "MIT" ]
null
null
null
SDE.hpp
jetpotion/MonteCarloOptionPricer
0024c9c900d1c968fca8946aa438ba07453272d8
[ "MIT" ]
null
null
null
#ifndef SDE_HPP #define SDE_HPP //THE VARIOUS TYPES OF SDE namespace MonteCarloOptionApplication { namespace ISde { class SDE { public: SDE() = default; SDE(const SDE& source) = default; SDE& operator=(const SDE& source); virtual ~SDE() = default; //Destructor [[nodiscard]] virtual double Drift(double x, double t) const noexcept = 0; //Drift [[nodiscard]] virtual double Diffusion(double x, double t) const noexcept = 0; //Diffusion term [[nodiscard]] virtual double DriftedCorrected(double x, double t, double b) const noexcept = 0; //Drif correcte [[nodiscard]] virtual double DiffusionDerivative(double x, double t) const noexcept= 0; //Diffusion Derivative [[nodiscard]] virtual void Expiry(double exp) noexcept= 0; //Expiry setter [[nodiscard]] virtual double Expiry() const noexcept= 0; //Expiry getter ; [[nodiscard]] virtual void InitialCondition(double initial_price) noexcept = 0; //Initial condition SETTER [[nodiscard]] virtual double InitialCondition() const noexcept = 0; //Returns the initial stock price }; //Classical GBM SDE class GBM : public SDE { private: double mu; //The Drift double vol; //The volatility double d; //The dividend yield double ic; //StockPrice double exp; //Expiry public: constexpr GBM(double driftCoefficient, double diffusionCoefficient, double dividendYield, double initialCondition, double expiry) noexcept; //Overloaded constructor constexpr GBM(const GBM& source); GBM& operator=(const GBM& source); ~GBM() override = default ; //Overrided destructor [[nodiscard]] constexpr double Drift(double x, double t) const noexcept override; //Drift [[nodiscard]] constexpr double Diffusion(double x, double t) const noexcept override; //Diffusion term [[nodiscard]] constexpr double DriftedCorrected(double x, double t, double b) const noexcept override; //Drif correcte [[nodiscard]] constexpr double DiffusionDerivative(double x, double t) const noexcept override; //Diffusion Derivative [[nodiscard]] constexpr void Expiry(double exp) noexcept override; //Expiry setter [[nodiscard]] constexpr double Expiry() const noexcept override; //Expiry getter ; [[nodiscard]] constexpr void InitialCondition(double initial_price) noexcept override; //Initial condition SETTER [[nodiscard]] constexpr double InitialCondition() const noexcept override; //Returns the initial stock price }; //The elastacity variance model of the SDE class CEV : public SDE { private: double mu; //The Drift double vol; //The volatility double d; //The dividend yield double ic; //StockPrice double exp; //Expiry double beta; public: constexpr CEV(double driftCoefficient, double diffusionCoefficient, double dividendYield, double initialCondition, double expiry, double beta) noexcept; //Overloaded constructor constexpr CEV(const CEV& source) noexcept; CEV& operator=(const CEV& source); ~CEV() override = default; //Overrided destructor [[nodiscard]] double Drift(double x, double t) const noexcept override; //Drift [[nodiscard]] double Diffusion(double x, double t) const noexcept override; //Diffusion term [[nodiscard]] double DriftedCorrected(double x, double t, double b) const noexcept override; //Drif correcte [[nodiscard]] double DiffusionDerivative(double x, double t) const noexcept override; //Diffusion Derivative [[nodiscard]] void Expiry(double exp) noexcept override; //Expiry setter [[nodiscard]] double Expiry() const override; //Expiry getter ; [[nodiscard]] void InitialCondition(double initial_price) noexcept override; //Initial condition SETTER [[nodiscard]] double InitialCondition() const noexcept override; //Returns the initial stock price }; } } #endif
48.227848
121
0.732021
jetpotion
ac3d2b288efaa593a01c83e7061938322c725085
1,188
cpp
C++
clang-tools-extra/clang-tidy/objc/AvoidSpinlockCheck.cpp
tkf/opencilk-project
48265098754b785d1b06cb08d8e22477a003efcd
[ "MIT" ]
16
2018-11-28T12:05:20.000Z
2021-11-08T09:47:46.000Z
clang-tools-extra/clang-tidy/objc/AvoidSpinlockCheck.cpp
tkf/opencilk-project
48265098754b785d1b06cb08d8e22477a003efcd
[ "MIT" ]
4
2018-11-30T19:12:21.000Z
2019-10-04T17:37:07.000Z
clang-tools-extra/clang-tidy/objc/AvoidSpinlockCheck.cpp
tkf/opencilk-project
48265098754b785d1b06cb08d8e22477a003efcd
[ "MIT" ]
15
2019-02-01T20:10:43.000Z
2022-03-26T11:52:37.000Z
//===--- AvoidSpinlockCheck.cpp - clang-tidy-------------------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// #include "AvoidSpinlockCheck.h" #include "clang/AST/ASTContext.h" #include "clang/ASTMatchers/ASTMatchFinder.h" using namespace clang::ast_matchers; namespace clang { namespace tidy { namespace objc { void AvoidSpinlockCheck::registerMatchers(MatchFinder *Finder) { Finder->addMatcher( callExpr(callee((functionDecl(hasAnyName( "OSSpinlockLock", "OSSpinlockUnlock", "OSSpinlockTry"))))) .bind("spinlock"), this); } void AvoidSpinlockCheck::check(const MatchFinder::MatchResult &Result) { const auto *MatchedExpr = Result.Nodes.getNodeAs<CallExpr>("spinlock"); diag(MatchedExpr->getBeginLoc(), "use os_unfair_lock_lock() or dispatch queue APIs instead of the " "deprecated OSSpinLock"); } } // namespace objc } // namespace tidy } // namespace clang
32.108108
80
0.644781
tkf
ac4044985b5b2bef8e0f296ca8f4a65ec312e6b5
1,431
cpp
C++
Tools/STM32FW/STM32Cube_FW_F7_V1.16.2/Projects/STM32746G-Discovery/Demonstrations/TouchGFX/Gui/target/GPIO.cpp
ramkumarkoppu/NUCLEO-F767ZI-ESW
85e129d71ee8eccbd0b94b5e07e75b6b91679ee8
[ "MIT" ]
null
null
null
Tools/STM32FW/STM32Cube_FW_F7_V1.16.2/Projects/STM32746G-Discovery/Demonstrations/TouchGFX/Gui/target/GPIO.cpp
ramkumarkoppu/NUCLEO-F767ZI-ESW
85e129d71ee8eccbd0b94b5e07e75b6b91679ee8
[ "MIT" ]
null
null
null
Tools/STM32FW/STM32Cube_FW_F7_V1.16.2/Projects/STM32746G-Discovery/Demonstrations/TouchGFX/Gui/target/GPIO.cpp
ramkumarkoppu/NUCLEO-F767ZI-ESW
85e129d71ee8eccbd0b94b5e07e75b6b91679ee8
[ "MIT" ]
null
null
null
/** ****************************************************************************** * This file is part of the TouchGFX 4.10.0 distribution. * * @attention * * Copyright (c) 2018 STMicroelectronics. * All rights reserved. * * This software is licensed under terms that can be found in the LICENSE file * in the root directory of this software component. * If no LICENSE file comes with this software, it is provided AS-IS. * ****************************************************************************** */ #include <touchgfx/hal/GPIO.hpp> #include "stm32746g_discovery.h" using namespace touchgfx; static bool ledState; // The STM32746G-Discovery board only supports a single LED. // This GPIO utility links that LED to GPIO::RENDER_TIME. static bool isRenderTime(GPIO::GPIO_ID id) { return id == GPIO::RENDER_TIME; } void GPIO::init() { BSP_LED_Init(LED_GREEN); clear(GPIO::RENDER_TIME); } void GPIO::set(GPIO::GPIO_ID id) { if (isRenderTime(id)) { ledState = 1; BSP_LED_On(LED_GREEN); } } void GPIO::clear(GPIO::GPIO_ID id) { if (isRenderTime(id)) { ledState = 0; BSP_LED_Off(LED_GREEN); } } void GPIO::toggle(GPIO::GPIO_ID id) { if (isRenderTime(id)) { BSP_LED_Toggle(LED_GREEN); } } bool GPIO::get(GPIO::GPIO_ID id) { if (isRenderTime(id)) { return ledState; } return 0; }
19.337838
80
0.570929
ramkumarkoppu
ac43229a8a489dccf391abb2a9f6c2421bee788a
1,436
hpp
C++
src/api/cpp/include/OISkeleton.hpp
jacobnb/OpenISS
028b315953b27dd3acc449efd5cfb485805a14b3
[ "Apache-2.0" ]
null
null
null
src/api/cpp/include/OISkeleton.hpp
jacobnb/OpenISS
028b315953b27dd3acc449efd5cfb485805a14b3
[ "Apache-2.0" ]
null
null
null
src/api/cpp/include/OISkeleton.hpp
jacobnb/OpenISS
028b315953b27dd3acc449efd5cfb485805a14b3
[ "Apache-2.0" ]
1
2018-11-17T19:33:31.000Z
2018-11-17T19:33:31.000Z
// // OISkeleton.hpp // Skeleton // // Created by Haotao Lai on 2018-08-08. // Created by Jashanjot Singh on 2018-07-22. // #ifndef OPENISS_OISKELETON_H #define OPENISS_OISKELETON_H #include <unordered_map> #include <memory> #include <vector> #include "OIEnum.hpp" #include "OITracker.hpp" #include "OIFrame.hpp" using std::unordered_map; using std::shared_ptr; using std::vector; namespace openiss { class OITracker; /** * Point of the skeleton joint (real world coordinate) */ class OISkeletonJoint { public: OISkeletonJoint(){}; OISkeletonJoint(float x, float y, float z, JointType type, float row=-1.0f, float col=-1.0f); JointType type; float x, y, z; // real world coordinate float row, col; // image coordinate }; /** * A map associates the JointType to the Joint * JointType -> shared_ptr<SkeletonJoint> */ class OISkeleton { public: shared_ptr<openiss::OISkeletonJoint> getJointByType(JointType type); void addJointByType(JointType type, shared_ptr<OISkeletonJoint> jointPtr); void drawToFrame(OIFrame *displayFrame, vector<JointType> &supportedJoints); void mapWorld2Image(OITracker* tracker); void setSkeletonState(bool isAvailable); bool getSkeletonState() const; private: unordered_map<JointType, shared_ptr<OISkeletonJoint>, std::hash<int>> mJoints; bool mIsSkeletonAvailable; }; } // end of namespace #endif //OPENISS_OISKELETON_H
22.793651
82
0.721448
jacobnb
ac44a7fc940a4ae2816883c6aaf7e69622258d7e
7,353
hpp
C++
artlib-cpp/include/srilakshmikanthanp/src/anixt_font.hpp
Thanus-MR/artlib
263c30701f36637ffad271c9c88e8d1aafdc2c2b
[ "MIT" ]
1
2021-04-17T02:24:02.000Z
2021-04-17T02:24:02.000Z
artlib-cpp/include/srilakshmikanthanp/src/anixt_font.hpp
Thanus-MR/artlib
263c30701f36637ffad271c9c88e8d1aafdc2c2b
[ "MIT" ]
null
null
null
artlib-cpp/include/srilakshmikanthanp/src/anixt_font.hpp
Thanus-MR/artlib
263c30701f36637ffad271c9c88e8d1aafdc2c2b
[ "MIT" ]
null
null
null
///@file basic_font.hpp /** * Copyright (c) 2020 Sri Lakshmi Kanthan P * * This software is released under the MIT License. * https://opensource.org/licenses/MIT */ #ifndef BASIC_FONT_HEADER #define BASIC_FONT_HEADER #include "anixt_config.hpp" #include "filesystem" #include "fstream" #include "third_party/json/json.hpp" #include "map" /** * @namespace srilakshmikanthanp * @brief outer namespace **/ namespace srilakshmikanthanp { /** * @namespace art * @brief contains art classes and functions **/ namespace art { /** * @struct basic_anixt_base_font * @brief abstract class for font types that used * by anixt class * @tparam Anixtconfig type of anixt_config **/ template <typename Anixtconfig> struct basic_anixt_base_font { using anixt_config = Anixtconfig; basic_anixt_base_font() = default; basic_anixt_base_font( const basic_anixt_base_font & ) = default; basic_anixt_base_font( basic_anixt_base_font && ) noexcept = default; virtual ~basic_anixt_base_font() = default; basic_anixt_base_font &operator=( const basic_anixt_base_font & ) = default; basic_anixt_base_font &operator=( basic_anixt_base_font && ) noexcept = default; /** * @brief clears the contents **/ virtual void clear() noexcept = 0; /** * @brief used to set font file, call this before * any other operation. * @param fp full path to font file **/ virtual void set_font( const std::filesystem::path &fp ) = 0; /** * @brief used to get anixt config from font file * @return anixt_config **/ virtual anixt_config get_anixt_config() = 0; /** * @brief used to get key equivalent of anixt_letter * from font * @param key key letter * @return anixt_letter **/ virtual typename anixt_config::anixt_letter operator()( typename anixt_config::char_type key ) = 0; }; /** * @class basic_anixt_json_font * @brief This class reads font for anixt class * from json file * @tparam Anixtconfig type of anixt_config **/ template <typename Anixtconfig> class basic_anixt_json_font : public basic_anixt_base_font<Anixtconfig> { protected: using base = basic_anixt_base_font<Anixtconfig>; public: using anixt_config = typename base::anixt_config; private: using char_type = typename base::anixt_config::char_type; using size_type = typename base::anixt_config::size_type; using traits_type = typename base::anixt_config::traits_type; using string_type = typename base::anixt_config::string_type; using shrink_type = typename base::anixt_config::shrink; using anixt_letter = typename base::anixt_config::anixt_letter; template <typename T> using alloc_type = typename base::anixt_config::template alloc_type<T>; using json_type = nlohmann::basic_json<std::map, std::vector, string_type, bool, int64_t, size_type, double, alloc_type>; private: /** * @brief stores font file. **/ json_type json_font; /** * @brief converts ascii character of std::string * to anixt_config::string_type **/ static string_type cvt( const std::string &str ) { return string_type( str.begin(), str.end() ); } public: basic_anixt_json_font() = default; basic_anixt_json_font( const basic_anixt_json_font & ) = default; basic_anixt_json_font( basic_anixt_json_font && ) noexcept = default; ~basic_anixt_json_font() = default; basic_anixt_json_font &operator=( const basic_anixt_json_font & ) = default; basic_anixt_json_font &operator=( basic_anixt_json_font && ) noexcept = default; /** * @brief clears the contents **/ void clear() noexcept override { this->json_font.clear(); } /** * @brief swap contents * @param obj object to swap **/ void swap( basic_anixt_json_font &obj ) { using std::swap; swap( this->json_font, obj.json_font ); } /** * @brief used to set font file, call this before * any other operation. * @param fp full path to font file **/ void set_font( const std::filesystem::path &fp ) override { std::basic_ifstream<char_type, traits_type> font_file { fp }; if ( fp.extension() != ".json" ) { throw std::runtime_error( "File should be json" ); } if ( !font_file.is_open() ) { throw std::runtime_error( "Unable to open file" ); } font_file >> this->json_font; } /** * @brief used to get anixt_config * @return anixt_config **/ anixt_config get_anixt_config() override { anixt_config ret; ret.HardBlank = this->json_font[cvt( "anixt_config" )][cvt( "HardBlank" )] .template get<size_type>(); ret.Height = this->json_font[cvt( "anixt_config" )][cvt( "Height" )] .template get<size_type>(); ret.Shrink = this->json_font[cvt( "anixt_config" )][cvt( "Shrink" )] .template get<shrink_type>(); return ret; } /** * @brief used to get anixt_letter from font * @param key key letter * @return anixt_letter **/ anixt_letter operator()( char_type key ) { return this->json_font[cvt( "anixt_letter" )][string_type( 1, key )] .template get<anixt_letter>(); } }; /** * @brief swap two anixt_config * @param lhs object one to swap * @param rhs object two to swap **/ template <typename Anixtconfig> void swap( basic_anixt_json_font<Anixtconfig> &lhs, basic_anixt_json_font<Anixtconfig> &rhs ) noexcept { lhs.swap( rhs ); } } // namespace art } // namespace srilakshmikanthanp #endif
33.884793
92
0.509452
Thanus-MR
ac45c8faca723e2e5e80e841e60b8dc687c2c893
4,951
cpp
C++
libskiwi/tail_calls_check.cpp
janm31415/skiwi
851a006c2964d527cc38b7a71f3e835b8dab52b5
[ "MIT" ]
4
2020-10-06T14:09:13.000Z
2020-10-24T17:34:53.000Z
libskiwi/tail_calls_check.cpp
janm31415/skiwi
851a006c2964d527cc38b7a71f3e835b8dab52b5
[ "MIT" ]
null
null
null
libskiwi/tail_calls_check.cpp
janm31415/skiwi
851a006c2964d527cc38b7a71f3e835b8dab52b5
[ "MIT" ]
null
null
null
#include "tail_calls_check.h" #include "visitor.h" SKIWI_BEGIN namespace { /* A procedure call is called a tail call if it occurs in a tail position. A tail position is defined recursively as follows: - the body of a procedure is in tail position - if a let expression is in tail position, then the body of the let is in tail position - if the condition expression (if test conseq altern) is in tail position, then the conseq and altern branches are also in tail position. - all other expressions are not in tail position. */ struct tail_calls_check : public base_visitor<tail_calls_check> { bool only_tails; tail_calls_check() : only_tails(true) { } virtual bool _previsit(Variable&) { return only_tails; } virtual bool _previsit(Begin&) { return only_tails; } virtual bool _previsit(FunCall& f) { if (!f.tail_position) only_tails = false; return only_tails; } virtual bool _previsit(If&) { return only_tails; } virtual bool _previsit(Lambda&) { return only_tails; } virtual bool _previsit(Let&) { return only_tails; } virtual bool _previsit(Literal&) { return only_tails; } virtual bool _previsit(PrimitiveCall&) { return only_tails; } virtual bool _previsit(ForeignCall&) { return only_tails; } virtual bool _previsit(Set&) { return only_tails; } }; struct tail_calls_check_helper { std::vector<Expression*> expressions; bool only_tails; tail_calls_check_helper() { only_tails = true; } void treat_expressions() { while (!expressions.empty()) { Expression* p_expr = expressions.back(); expressions.pop_back(); Expression& e = *p_expr; if (std::holds_alternative<Literal>(e)) { } else if (std::holds_alternative<Variable>(e)) { } else if (std::holds_alternative<Nop>(e)) { } else if (std::holds_alternative<Quote>(e)) { } else if (std::holds_alternative<Set>(e)) { //Set& s = std::get<Set>(e); expressions.push_back(&std::get<Set>(e).value.front()); } else if (std::holds_alternative<If>(e)) { for (auto rit = std::get<If>(e).arguments.rbegin(); rit != std::get<If>(e).arguments.rend(); ++rit) expressions.push_back(&(*rit)); } else if (std::holds_alternative<Begin>(e)) { for (auto rit = std::get<Begin>(e).arguments.rbegin(); rit != std::get<Begin>(e).arguments.rend(); ++rit) expressions.push_back(&(*rit)); } else if (std::holds_alternative<PrimitiveCall>(e)) { for (auto rit = std::get<PrimitiveCall>(e).arguments.rbegin(); rit != std::get<PrimitiveCall>(e).arguments.rend(); ++rit) expressions.push_back(&(*rit)); } else if (std::holds_alternative<ForeignCall>(e)) { for (auto rit = std::get<ForeignCall>(e).arguments.rbegin(); rit != std::get<ForeignCall>(e).arguments.rend(); ++rit) expressions.push_back(&(*rit)); } else if (std::holds_alternative<Lambda>(e)) { Lambda& l = std::get<Lambda>(e); expressions.push_back(&l.body.front()); } else if (std::holds_alternative<FunCall>(e)) { FunCall& f = std::get<FunCall>(e); if (!f.tail_position) { only_tails = false; break; } expressions.push_back(&std::get<FunCall>(e).fun.front()); for (auto rit = std::get<FunCall>(e).arguments.rbegin(); rit != std::get<FunCall>(e).arguments.rend(); ++rit) expressions.push_back(&(*rit)); } else if (std::holds_alternative<Let>(e)) { Let& l = std::get<Let>(e); expressions.push_back(&l.body.front()); for (auto rit = l.bindings.rbegin(); rit != l.bindings.rend(); ++rit) expressions.push_back(&(*rit).second); } else throw std::runtime_error("Compiler error!: Tail calls check: not implemented"); } } }; } bool only_tail_calls(Program& prog) { assert(prog.tail_call_analysis); //tail_calls_check tcc; //visitor<Program, tail_calls_check>::visit(prog, &tcc); tail_calls_check_helper tcch; for (auto& expr : prog.expressions) tcch.expressions.push_back(&expr); tcch.treat_expressions(); return tcch.only_tails; } bool only_tail_calls(Expression& e) { tail_calls_check_helper tcch; tcch.expressions.push_back(&e); tcch.treat_expressions(); return tcch.only_tails; } SKIWI_END
25.005051
131
0.568976
janm31415
ac49848a1882ecebb1539e54148b73293229f10c
3,048
cc
C++
leetcode/ds_hash_longest_consecutive_seq.cc
prashrock/C-
3ed46815d40b3e42cd9f36d23c8ee2a9de742323
[ "MIT" ]
1
2016-12-05T10:42:46.000Z
2016-12-05T10:42:46.000Z
leetcode/ds_hash_longest_consecutive_seq.cc
prashrock/CPP
3ed46815d40b3e42cd9f36d23c8ee2a9de742323
[ "MIT" ]
null
null
null
leetcode/ds_hash_longest_consecutive_seq.cc
prashrock/CPP
3ed46815d40b3e42cd9f36d23c8ee2a9de742323
[ "MIT" ]
null
null
null
//g++-5 --std=c++11 -Wall -g -o ds_hash_longest_consecutive_seq ds_hash_longest_consecutive_seq.cc /** * @file Longest Consecutive Sequence * @brief Given unsorted array, find length of longest consecutive sequence */ // https://leetcode.com/problems/longest-consecutive-sequence/ /** * Given an unsorted array of integers, find the length of the longest * consecutive elements sequence. * For example, * Given [100, 4, 200, 1, 3, 2], * The longest consecutive elements sequence is [1, 2, 3, 4]. * Return its length: 4. * Note: Your algorithm should run in O(n) complexity. */ #include <iostream> /* std::cout */ #include <iomanip> /* std::setw */ #include <cmath> /* pow */ #include <cassert> /* assert */ #include <algorithm> /* std::max */ #include <vector> /* std:vector */ #include <string> /* std::string, */ #include <cstring> /* std::strtok */ #include <unordered_map> /* std::unordered_map */ using namespace std; /* Use DFS to visit all consecutive numbers of a given val */ int dfs_consecutive(std::unordered_map<int, int>& mp, int val) { int up=val+1, down=val-1; while(mp.find(up) != mp.end() || mp.find(down) != mp.end()) { auto uit = mp.find(up), dit = mp.find(down); if(uit != mp.end()) {mp[val]++; mp.erase(uit); up++; } if(dit != mp.end()) {mp[val]++; mp.erase(dit); down--;} } return mp[val]; } /* Use a HashTable to find and track consecutive numbers. Use* * DFS to traverse around every given node * * Time_Complexity=O(n), Space_Complexity=O(n) */ int longestConsecutive(vector<int>& nums) { int ans = 1; std::unordered_map<int, int> mp; /* consecutive cnt */ /* Initialize unordered_map with vector */ for(auto val : nums) mp[val] = 1; /* Pick up any random element and DFS search around it */ while( !mp.empty() ) { auto it = mp.begin(); /* random first node from Map */ int key = it->first; /* get node's key */ /* Current max is either old or current DFS traversal */ ans = std::max(ans, dfs_consecutive(mp, key)); mp.erase(it); /* Remove current processed node */ } return ans; } struct test_vector { std::vector<int> X; int exp; }; const struct test_vector test[2] = { {{9,1,-3,2,4,8,3,-1,6,-2,-4,7}, 4}, {{100, 4, 200, 1, 3, 2}, 4}, }; int main() { for(auto tst : test) { auto ans = longestConsecutive(tst.X); if(ans != tst.exp) { cout << "Error:longestConsecutive failed for: "; for(auto v : tst.X) cout << v << ","; cout << endl; cout << " exp " << tst.exp << " got " << ans << endl; return -1; } } cout << "Info: All manual test-cases passed successfully" << endl; return 0; }
35.034483
98
0.543307
prashrock
ac4d523a9e5fee1711452c51619c83265ce86874
2,896
cpp
C++
vod/src/v1/model/QualityInfo.cpp
huaweicloud/huaweicloud-sdk-cpp-v3
d3b5e07b0ee8367d1c7f6dad17be0212166d959c
[ "Apache-2.0" ]
5
2021-03-03T08:23:43.000Z
2022-02-16T02:16:39.000Z
vod/src/v1/model/QualityInfo.cpp
ChenwxJay/huaweicloud-sdk-cpp-v3
f821ec6d269b50203e0c1638571ee1349c503c41
[ "Apache-2.0" ]
null
null
null
vod/src/v1/model/QualityInfo.cpp
ChenwxJay/huaweicloud-sdk-cpp-v3
f821ec6d269b50203e0c1638571ee1349c503c41
[ "Apache-2.0" ]
7
2021-02-26T13:53:35.000Z
2022-03-18T02:36:43.000Z
#include "huaweicloud/vod/v1/model/QualityInfo.h" namespace HuaweiCloud { namespace Sdk { namespace Vod { namespace V1 { namespace Model { QualityInfo::QualityInfo() { videoIsSet_ = false; audioIsSet_ = false; format_ = ""; formatIsSet_ = false; } QualityInfo::~QualityInfo() = default; void QualityInfo::validate() { } web::json::value QualityInfo::toJson() const { web::json::value val = web::json::value::object(); if(videoIsSet_) { val[utility::conversions::to_string_t("video")] = ModelBase::toJson(video_); } if(audioIsSet_) { val[utility::conversions::to_string_t("audio")] = ModelBase::toJson(audio_); } if(formatIsSet_) { val[utility::conversions::to_string_t("format")] = ModelBase::toJson(format_); } return val; } bool QualityInfo::fromJson(const web::json::value& val) { bool ok = true; if(val.has_field(utility::conversions::to_string_t("video"))) { const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("video")); if(!fieldValue.is_null()) { VideoTemplateInfo refVal; ok &= ModelBase::fromJson(fieldValue, refVal); setVideo(refVal); } } if(val.has_field(utility::conversions::to_string_t("audio"))) { const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("audio")); if(!fieldValue.is_null()) { AudioTemplateInfo refVal; ok &= ModelBase::fromJson(fieldValue, refVal); setAudio(refVal); } } if(val.has_field(utility::conversions::to_string_t("format"))) { const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("format")); if(!fieldValue.is_null()) { std::string refVal; ok &= ModelBase::fromJson(fieldValue, refVal); setFormat(refVal); } } return ok; } VideoTemplateInfo QualityInfo::getVideo() const { return video_; } void QualityInfo::setVideo(const VideoTemplateInfo& value) { video_ = value; videoIsSet_ = true; } bool QualityInfo::videoIsSet() const { return videoIsSet_; } void QualityInfo::unsetvideo() { videoIsSet_ = false; } AudioTemplateInfo QualityInfo::getAudio() const { return audio_; } void QualityInfo::setAudio(const AudioTemplateInfo& value) { audio_ = value; audioIsSet_ = true; } bool QualityInfo::audioIsSet() const { return audioIsSet_; } void QualityInfo::unsetaudio() { audioIsSet_ = false; } std::string QualityInfo::getFormat() const { return format_; } void QualityInfo::setFormat(const std::string& value) { format_ = value; formatIsSet_ = true; } bool QualityInfo::formatIsSet() const { return formatIsSet_; } void QualityInfo::unsetformat() { formatIsSet_ = false; } } } } } }
19.306667
97
0.637431
huaweicloud
ac566ec5d7bb9d1454c4a6bee2debad773b9c603
6,910
cpp
C++
ValidateEditor/SQLColsDlg.cpp
edwig/Kwatta
ce1ca2907608e65ed62d7dbafa9ab1d030caccfe
[ "MIT" ]
1
2021-12-31T17:20:01.000Z
2021-12-31T17:20:01.000Z
ValidateEditor/SQLColsDlg.cpp
edwig/Kwatta
ce1ca2907608e65ed62d7dbafa9ab1d030caccfe
[ "MIT" ]
10
2022-01-14T13:28:32.000Z
2022-02-13T12:46:34.000Z
ValidateEditor/SQLColsDlg.cpp
edwig/Kwatta
ce1ca2907608e65ed62d7dbafa9ab1d030caccfe
[ "MIT" ]
null
null
null
/////////////////////////////////////////////////////////////////////////////////////////////////////// // // // ██╗░░██╗░██╗░░░░░░░██╗░█████╗░████████╗████████╗░█████╗░ // ██║░██╔╝░██║░░██╗░░██║██╔══██╗╚══██╔══╝╚══██╔══╝██╔══██╗ // █████═╝░░╚██╗████╗██╔╝███████║░░░██║░░░░░░██║░░░███████║ // ██╔═██╗░░░████╔═████║░██╔══██║░░░██║░░░░░░██║░░░██╔══██║ // ██║░╚██╗░░╚██╔╝░╚██╔╝░██║░░██║░░░██║░░░░░░██║░░░██║░░██║ // ╚═╝░░╚═╝░░░╚═╝░░░╚═╝░░╚═╝░░╚═╝░░░╚═╝░░░░░░╚═╝░░░╚═╝░░╚═╝ // // // This product: KWATTA (KWAliTy Test API) Test suite for Command-line SOAP/JSON/HTTP internet API's // This program: ValidateEditor // This File : SQLColsDlg.cpp // What it does: Validation of the returned columns of an SQL database statement // Author : ir. W.E. Huisman // License : See license.md file in the root directory // /////////////////////////////////////////////////////////////////////////////////////////////////////// #include "stdafx.h" #include "ValidateEditor.h" #include "ValidateDatabaseDlg.h" #include "SQLColsDlg.h" #include <SearchVarDlg.h> #include <NewVariableDlg.h> #include <afxdialogex.h> #ifdef _DEBUG #undef THIS_FILE static char THIS_FILE[] = __FILE__; #define new DEBUG_NEW #endif // SQLColsDlg dialog IMPLEMENT_DYNAMIC(SQLColsDlg, StyleDialog) SQLColsDlg::SQLColsDlg(CWnd* p_parent) :StyleDialog(IDD_SQL_COLS,p_parent) { } SQLColsDlg::~SQLColsDlg() { } void SQLColsDlg::DoDataExchange(CDataExchange* pDX) { StyleDialog::DoDataExchange(pDX); DDX_Control(pDX, IDC_USE_RETURN, m_buttonCheck); DDX_Control(pDX, IDC_OPERATOR, m_comboOperator); DDX_Control(pDX, IDC_RETURN, m_editCols, m_returnedCols); DDX_Control(pDX, IDC_BUTT_PARAM, m_buttonParm); DDX_Control(pDX, IDC_EFF_RETURN, m_editEffective,m_effectiveReturnedCols); DDX_Control(pDX, IDC_SUCCEED_VAR, m_comboVariable); DDX_Control(pDX, IDC_NEWVAR, m_buttonVariable); if(pDX->m_bSaveAndValidate == false) { m_comboOperator .EnableWindow(m_useCheckCols); m_editCols .EnableWindow(m_useCheckCols); m_editEffective .EnableWindow(m_useCheckCols); m_comboVariable .EnableWindow(m_useCheckCols); m_buttonVariable.EnableWindow(m_useCheckCols); m_buttonParm .EnableWindow(m_useCheckCols); } } BEGIN_MESSAGE_MAP(SQLColsDlg, StyleDialog) ON_BN_CLICKED (IDC_USE_RETURN, &SQLColsDlg::OnBnClickedUseReturnedCols) ON_CBN_SELCHANGE(IDC_OPERATOR, &SQLColsDlg::OnCbnSelchangeOperator) ON_EN_KILLFOCUS (IDC_RETURN, &SQLColsDlg::OnEnChangeReturnedCols) ON_BN_CLICKED (IDC_BUTT_PARAM, &SQLColsDlg::OnBnClickedParm) ON_EN_CHANGE (IDC_EFF_RETURN, &SQLColsDlg::OnEnChangeEffSucceeded) ON_CBN_SELCHANGE(IDC_SUCCEED_VAR, &SQLColsDlg::OnCbnSelchangeReturnedColsVariable) ON_BN_CLICKED (IDC_NEWVAR, &SQLColsDlg::OnBnClickedNewvar) END_MESSAGE_MAP() BOOL SQLColsDlg::OnInitDialog() { StyleDialog::OnInitDialog(); m_buttonVariable.SetIconImage(IDI_LIST); m_buttonParm .SetIconImage(IDI_RETURN); SetCanResize(); return TRUE; } void SQLColsDlg::SetupDynamicLayout() { StyleDialog::SetupDynamicLayout(); CMFCDynamicLayout& manager = *GetDynamicLayout(); #ifdef _DEBUG manager.AssertValid(); #endif manager.AddItem(IDC_RETURN, CMFCDynamicLayout::MoveNone(), CMFCDynamicLayout::SizeHorizontal(100)); manager.AddItem(IDC_EFF_RETURN,CMFCDynamicLayout::MoveNone(), CMFCDynamicLayout::SizeHorizontal(100)); manager.AddItem(IDC_BUTT_PARAM,CMFCDynamicLayout::MoveHorizontal(100), CMFCDynamicLayout::SizeNone()); } void SQLColsDlg::InitTab(ValidateSQL* p_validate,Parameters* p_parameters) { m_validate = p_validate; m_parameters = p_parameters; LoadVariables(); FillCombos(); SetCombos(); } void SQLColsDlg::FillCombos() { m_comboOperator.ResetContent(); m_comboVariable.ResetContent(); m_comboOperator.AddString(""); m_comboOperator.AddString("= Exactly equal to"); m_comboOperator.AddString("> Greater than"); m_comboOperator.AddString(">= Greater than or equal to"); m_comboOperator.AddString("< Smaller than"); m_comboOperator.AddString("<= Smaller than or equal to"); m_comboOperator.AddString("<> Not equal to"); m_comboOperator.AddString("~~ Between two values"); m_comboOperator.AddString("[ ] In a range of values"); m_comboVariable.AddString(""); for(auto& ret : m_parameters->GetReturns()) { m_comboVariable.AddString(ret.first); } } void SQLColsDlg::SetCombos() { m_comboOperator.SetCurSel((int)m_colsOperator); int ind = m_comboVariable.FindStringExact(0, m_returnedColsVariable); if (ind >= 0) { m_comboVariable.SetCurSel(ind); } } void SQLColsDlg::LoadVariables() { m_useCheckCols = m_validate->GetCheckCols(); m_colsOperator = m_validate->GetColsOperator(); m_returnedCols = m_validate->GetReturnedCols(); m_effectiveReturnedCols = m_validate->GetEffectiveReturnedCols(); m_returnedColsVariable = m_validate->GetReturnedColsVariable(); m_buttonCheck.SetCheck(m_useCheckCols); m_comboOperator.SetCurSel((int)m_colsOperator - 1); UpdateData(FALSE); } void SQLColsDlg::StoreVariables() { m_validate->SetCheckCols(m_useCheckCols); m_validate->SetReturnedCols(m_returnedCols); m_validate->SetColsOperator(m_colsOperator); m_validate->SetReturnedColsVariable(m_returnedColsVariable); } // SQLColsDlg message handlers void SQLColsDlg::OnBnClickedUseReturnedCols() { m_useCheckCols= m_buttonCheck.GetCheck() > 0; if(!m_useCheckCols) { m_colsOperator = ReturnOperator::ROP_NOP; m_comboOperator.SetCurSel(-1); m_effectiveReturnedCols.Empty(); } UpdateData(FALSE); } void SQLColsDlg::OnCbnSelchangeOperator() { int ind = m_comboOperator.GetCurSel(); if (ind >= 0) { m_colsOperator = (ReturnOperator)ind; } } void SQLColsDlg::OnEnChangeReturnedCols() { UpdateData(); m_validate->SetSucceeded(m_returnedCols); ValidateDatabaseDlg* parent = dynamic_cast<ValidateDatabaseDlg*>(GetParent()->GetParent()); if(parent) { StoreVariables(); parent->EffectiveParameters(); LoadVariables(); } } void SQLColsDlg::OnBnClickedParm() { SearchVarDlg dlg(this,m_parameters,true,true,true,true); if (dlg.DoModal() == IDOK || dlg.GetSaved()) { m_returnedCols += dlg.GetVariable(); UpdateData(FALSE); } } void SQLColsDlg::OnEnChangeEffSucceeded() { UpdateData(); } void SQLColsDlg::OnCbnSelchangeReturnedColsVariable() { int ind = m_comboVariable.GetCurSel(); if(ind >= 0) { CString var; m_comboVariable.GetLBText(ind,var); m_returnedColsVariable = var; } } void SQLColsDlg::OnBnClickedNewvar() { NewVariableDlg dlg(ParType::PAR_RETURN, m_parameters->GetReturns()); if(dlg.DoModal() == IDOK) { CString newvar = dlg.GetNewName(); if(!newvar.IsEmpty()) { m_returnedColsVariable = newvar; FillCombos(); SetCombos(); } } }
26.273764
113
0.675687
edwig
ac587e3dfbebebde8bf200e83c733b6a00cfd8a5
27,114
cxx
C++
PWG/FLOW/Base/AliFlowAnalysisWithSimpleSP.cxx
amveen/AliPhysics
bef49dc8e7f8ad5f656d54430031eb67abcf3243
[ "BSD-3-Clause" ]
null
null
null
PWG/FLOW/Base/AliFlowAnalysisWithSimpleSP.cxx
amveen/AliPhysics
bef49dc8e7f8ad5f656d54430031eb67abcf3243
[ "BSD-3-Clause" ]
null
null
null
PWG/FLOW/Base/AliFlowAnalysisWithSimpleSP.cxx
amveen/AliPhysics
bef49dc8e7f8ad5f656d54430031eb67abcf3243
[ "BSD-3-Clause" ]
null
null
null
/************************************************************************* * Copyright(c) 1998-2008, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ #define ALIFLOWANALYSISWITHSIMPLESP_CXX #include "TFile.h" #include "TList.h" #include "TMath.h" #include "TString.h" #include "TProfile.h" #include "TVector2.h" #include "TH1D.h" #include "TH1F.h" #include "TH2D.h" #include "AliFlowCommonConstants.h" #include "AliFlowEventSimple.h" #include "AliFlowVector.h" #include "AliFlowTrackSimple.h" #include "AliFlowCommonHist.h" #include "AliFlowCommonHistResults.h" #include "AliFlowAnalysisWithSimpleSP.h" using std::cout; using std::endl; ClassImp(AliFlowAnalysisWithSimpleSP) //----------------------------------------------------------------------- AliFlowAnalysisWithSimpleSP::AliFlowAnalysisWithSimpleSP(): fDebug(0), fMinimalBook(kFALSE), fUsePhiWeights(0), fApplyCorrectionForNUA(0), fHarmonic(2), fWeights(kFALSE), fScaling(kTRUE), fNormalizationType(1), fV0SanityCheck(0), fExternalResolution(-999.), fExternalResErr(0.), fTotalQvector(3), fWeightsList(NULL), fHistList(NULL), fHistProConfig(NULL), fHistProQaQbNorm(NULL), fHistSumOfWeights(NULL), fHistProNUAq(NULL), fCentralityWeight(1.), fHistProQNorm(NULL), fHistProQaQb(NULL), fHistProQaQbM(NULL), fHistMaMb(NULL), fHistQNormQaQbNorm(NULL), fHistQaNormMa(NULL), fHistQbNormMb(NULL), fResolution(NULL), fHistQaQb(NULL), fHistQaQc(NULL), fHistQbQc(NULL), fHistQaQbCos(NULL), fHistNumberOfSubtractedDaughters(NULL), fCommonHists(NULL), fCommonHistsuQ(NULL), fCommonHistsRes(NULL) { //ctor for(int i=0; i!=2; ++i) { fPhiWeightsSub[i] = NULL; for(int j=0; j!=2; ++j) { fHistProUQ[i][j] = NULL; fHistProUQQaQb[i][j] = NULL; fHistProNUAu[i][j][0] = NULL; fHistProNUAu[i][j][1] = NULL; for(int k=0; k!=3; ++k) fHistSumOfWeightsu[i][j][k] = NULL; } } } //----------------------------------------------------------------------- AliFlowAnalysisWithSimpleSP::~AliFlowAnalysisWithSimpleSP() { //destructor delete fWeightsList; delete fHistList; } //----------------------------------------------------------------------- void AliFlowAnalysisWithSimpleSP::Init() { //Define all histograms //printf("---Analysis with the Scalar Product Method--- Init\n"); //printf("--- fNormalizationType %d ---\n", fNormalizationType); //save old value and prevent histograms from being added to directory //to avoid name clashes in case multiple analaysis objects are used //in an analysis Bool_t oldHistAddStatus = TH1::AddDirectoryStatus(); TH1::AddDirectory(kFALSE); fHistList = new TList(); fHistList->SetName("cobjSP"); fHistList->SetOwner(); TList *uQRelated = new TList(); uQRelated->SetName("uQ"); uQRelated->SetOwner(); TList *nuaRelated = new TList(); nuaRelated->SetName("NUA"); nuaRelated->SetOwner(); TList *errorRelated = new TList(); errorRelated->SetName("error"); errorRelated->SetOwner(); TList *tQARelated = new TList(); tQARelated->SetName("QA"); tQARelated->SetOwner(); fCommonHists = new AliFlowCommonHist("AliFlowCommonHist_SP","AliFlowCommonHist",fMinimalBook, fHarmonic); (fCommonHists->GetHarmonic())->Fill(0.5,fHarmonic); // store harmonic fHistList->Add(fCommonHists); // fCommonHistsuQ = new AliFlowCommonHist("AliFlowCommonHist_uQ"); // (fCommonHistsuQ->GetHarmonic())->Fill(0.5,fHarmonic); // store harmonic // fHistList->Add(fCommonHistsuQ); fCommonHistsRes = new AliFlowCommonHistResults("AliFlowCommonHistResults_SP","",fHarmonic); fHistList->Add(fCommonHistsRes); fHistProConfig = new TProfile("FlowPro_Flags_SP","Flow_Flags_SP",4,0.5,4.5,"s"); fHistProConfig->GetXaxis()->SetBinLabel(1,"fApplyCorrectionForNUA"); fHistProConfig->GetXaxis()->SetBinLabel(2,"fNormalizationType"); fHistProConfig->GetXaxis()->SetBinLabel(3,"fUsePhiWeights"); fHistProConfig->GetXaxis()->SetBinLabel(4,"fHarmonic"); fHistProConfig->Fill(1,fApplyCorrectionForNUA); fHistProConfig->Fill(2,fNormalizationType); fHistProConfig->Fill(3,fUsePhiWeights); fHistProConfig->Fill(4,fHarmonic); fHistList->Add(fHistProConfig); fHistProQaQbNorm = new TProfile("FlowPro_QaQbNorm_SP","FlowPro_QaQbNorm_SP", 10000, -1000, 1000); fHistProQaQbNorm->SetYTitle("<QaQb/Na/Nb>"); errorRelated->Add(fHistProQaQbNorm); fHistProNUAq = new TProfile("FlowPro_NUAq_SP","FlowPro_NUAq_SP", 6, 0.5, 6.5,"s"); fHistProNUAq->GetXaxis()->SetBinLabel( 1,"<<sin(#Phi_{a})>>"); fHistProNUAq->GetXaxis()->SetBinLabel( 2,"<<cos(#Phi_{a})>>"); fHistProNUAq->GetXaxis()->SetBinLabel( 3,"<<sin(#Phi_{b})>>"); fHistProNUAq->GetXaxis()->SetBinLabel( 4,"<<cos(#Phi_{b})>>"); fHistProNUAq->GetXaxis()->SetBinLabel( 5,"<<sin(#Phi_{t})>>"); fHistProNUAq->GetXaxis()->SetBinLabel( 6,"<<cos(#Phi_{t})>>"); nuaRelated->Add(fHistProNUAq); fHistSumOfWeights = new TH1D("Flow_SumOfWeights_SP","Flow_SumOfWeights_SP",2,0.5, 2.5); fHistSumOfWeights->GetXaxis()->SetBinLabel( 1,"#Sigma Na*Nb"); fHistSumOfWeights->GetXaxis()->SetBinLabel( 2,"#Sigma (Na*Nb)^2"); errorRelated->Add(fHistSumOfWeights); TString sPOI[2] = {"RP","POI"}; // backward compatibility TString sEta[2] = {"Pt","eta"}; // backward compatibility TString sTitle[2] = {"p_{T} [GeV]","#eta"}; TString sWeights[3] = {"uQ","uQuQ","uQQaQb"}; Int_t iNbins[2]; Double_t dMin[2], dMax[2]; iNbins[0] = AliFlowCommonConstants::GetMaster()->GetNbinsPt(); iNbins[1] = AliFlowCommonConstants::GetMaster()->GetNbinsEta(); dMin[0] = AliFlowCommonConstants::GetMaster()->GetPtMin(); dMin[1] = AliFlowCommonConstants::GetMaster()->GetEtaMin(); dMax[0] = AliFlowCommonConstants::GetMaster()->GetPtMax(); dMax[1] = AliFlowCommonConstants::GetMaster()->GetEtaMax(); for(Int_t iPOI=0; iPOI!=2; ++iPOI) for(Int_t iSpace=0; iSpace!=2; ++iSpace) { // uQ fHistProUQ[iPOI][iSpace] = new TProfile( Form( "FlowPro_UQ_%s%s_SP", sEta[iSpace].Data(), sPOI[iPOI].Data() ), Form( "FlowPro_UQ%s%s_SP", sEta[iSpace].Data(), sPOI[iPOI].Data() ), iNbins[iSpace], dMin[iSpace], dMax[iSpace], "s"); fHistProUQ[iPOI][iSpace]->SetXTitle(sTitle[iSpace].Data()); fHistProUQ[iPOI][iSpace]->SetYTitle("<uQ>"); uQRelated->Add(fHistProUQ[iPOI][iSpace]); // NUAu fHistProNUAu[iPOI][iSpace][0] = new TProfile( Form("FlowPro_NUAu_%s%s_IM_SP", sEta[iSpace].Data(), sPOI[iPOI].Data() ), Form("FlowPro_NUAu_%s%s_IM_SP", sEta[iSpace].Data(), sPOI[iPOI].Data() ), iNbins[iSpace], dMin[iSpace], dMax[iSpace]); fHistProNUAu[iPOI][iSpace][0]->SetXTitle(sTitle[iSpace].Data()); nuaRelated->Add(fHistProNUAu[iPOI][iSpace][0]); fHistProNUAu[iPOI][iSpace][1] = new TProfile( Form("FlowPro_NUAu_%s%s_RE_SP", sEta[iSpace].Data(), sPOI[iPOI].Data() ), Form("FlowPro_NUAu_%s%s_RE_SP", sEta[iSpace].Data(), sPOI[iPOI].Data() ), iNbins[iSpace], dMin[iSpace], dMax[iSpace]); fHistProNUAu[iPOI][iSpace][1]->SetXTitle(sTitle[iSpace].Data()); nuaRelated->Add(fHistProNUAu[iPOI][iSpace][1]); // uQ QaQb fHistProUQQaQb[iPOI][iSpace] = new TProfile( Form("FlowPro_UQQaQb_%s%s_SP", sEta[iSpace].Data(), sPOI[iPOI].Data() ), Form("FlowPro_UQQaQb_%s%s_SP", sEta[iSpace].Data(), sPOI[iPOI].Data() ), iNbins[iSpace], dMin[iSpace], dMax[iSpace]); fHistProUQQaQb[iPOI][iSpace]->SetXTitle(sTitle[iSpace].Data()); fHistProUQQaQb[iPOI][iSpace]-> SetYTitle("<Qu QaQb>"); errorRelated->Add(fHistProUQQaQb[iPOI][iSpace]); // uWeights for(Int_t i=0; i!=3; ++i) { fHistSumOfWeightsu[iPOI][iSpace][i] = new TH1D( Form("Flow_SumOfWeights_%s%s_%s_SP",sWeights[i].Data(),sPOI[iPOI].Data(),sEta[iSpace].Data()), Form("Flow_SumOfWeights_%s%s_%s_SP",sWeights[i].Data(),sPOI[iPOI].Data(),sEta[iSpace].Data()), iNbins[iSpace], dMin[iSpace], dMax[iSpace]); fHistSumOfWeightsu[iPOI][iSpace][i]->SetYTitle(sWeights[i].Data()); fHistSumOfWeightsu[iPOI][iSpace][i]->SetXTitle(sTitle[iSpace].Data()); errorRelated->Add(fHistSumOfWeightsu[iPOI][iSpace][i]); } } //weights if(fUsePhiWeights) { if(!fWeightsList) { printf( "WARNING: fWeightsList is NULL in the Scalar Product method.\n" ); exit(0); } fPhiWeightsSub[0] = dynamic_cast<TH1F*> (fWeightsList->FindObject("phi_weights_sub0")); if(!fPhiWeightsSub[0]) { printf( "WARNING: phi_weights_sub0 not found in the Scalar Product method.\n" ); exit(0); } nuaRelated->Add( fPhiWeightsSub[0] ); fPhiWeightsSub[1] = dynamic_cast<TH1F*> (fWeightsList->FindObject("phi_weights_sub1")); if(!fPhiWeightsSub[1]) { printf( "WARNING: phi_weights_sub1 not found in the Scalar Product method.\n" ); exit(0); } nuaRelated->Add( fPhiWeightsSub[1] ); } if(!fMinimalBook) { fHistProQNorm = new TProfile("FlowPro_QNorm_SP","FlowPro_QNorm_SP", 1,0.5,1.5,"s"); fHistProQNorm->SetYTitle("<|Qa+Qb|>"); tQARelated->Add(fHistProQNorm); fHistProQaQb = new TH1D("FlowPro_QaQb_SP","FlowPro_QaQb_SP", 10000,-100,100); fHistProQaQb->SetYTitle("<QaQb>"); fHistProQaQb->StatOverflows(kTRUE); tQARelated->Add(fHistProQaQb); fHistProQaQbM = new TH1D("FlowPro_QaQbvsM_SP","FlowPro_QaQbvsM_SP",1000,0.0,10000); fHistProQaQbM->SetYTitle("<QaQb>"); fHistProQaQbM->SetXTitle("M"); fHistProQaQbM->Sumw2(); tQARelated->Add(fHistProQaQbM); fHistMaMb = new TH2D("Flow_MavsMb_SP","Flow_MavsMb_SP",100,0.,100.,100,0.,100.); fHistMaMb->SetYTitle("Ma"); fHistMaMb->SetXTitle("Mb"); tQARelated->Add(fHistMaMb); fHistQNormQaQbNorm = new TH2D("Flow_QNormvsQaQbNorm_SP","Flow_QNormvsQaQbNorm_SP",88,-1.1,1.1,22,0.,1.1); fHistQNormQaQbNorm->SetYTitle("|Q/Mq|"); fHistQNormQaQbNorm->SetXTitle("QaQb/MaMb"); tQARelated->Add(fHistQNormQaQbNorm); fHistQaNormMa = new TH2D("Flow_QaNormvsMa_SP","Flow_QaNormvsMa_SP",100,0.,100.,22,0.,1.1); fHistQaNormMa->SetYTitle("|Qa/Ma|"); fHistQaNormMa->SetXTitle("Ma"); tQARelated->Add(fHistQaNormMa); fHistQbNormMb = new TH2D("Flow_QbNormvsMb_SP","Flow_QbNormvsMb_SP",100,0.,100.,22,0.,1.1); fHistQbNormMb->SetYTitle("|Qb/Mb|"); fHistQbNormMb->SetXTitle("Mb"); tQARelated->Add(fHistQbNormMb); fResolution = new TH1D("Flow_resolution_SP","Flow_resolution_SP",100,-1.0,1.0); fResolution->SetYTitle("dN/d(Cos2(#phi_a - #phi_b))"); fResolution->SetXTitle("Cos2(#phi_a - #phi_b)"); tQARelated->Add(fResolution); fHistQaQb = new TH1D("Flow_QaQb_SP","Flow_QaQb_SP",20000,-1000.,1000.); fHistQaQb->SetYTitle("dN/dQaQb"); fHistQaQb->SetXTitle("dQaQb"); fHistQaQb->StatOverflows(kTRUE); tQARelated->Add(fHistQaQb); fHistQaQc = new TH1D("Flow_QaQc_SP","Flow_QaQc_SP",20000,-1000.,1000.); fHistQaQc->SetYTitle("dN/dQaQc"); fHistQaQc->SetXTitle("dQaQc"); fHistQaQc->StatOverflows(kTRUE); tQARelated->Add(fHistQaQc); fHistQbQc = new TH1D("Flow_QbQc_SP","Flow_QbQc_SP",20000,-1000.,1000.); fHistQbQc->SetYTitle("dN/dQbQc"); fHistQbQc->SetXTitle("dQbQc"); fHistQbQc->StatOverflows(kTRUE); tQARelated->Add(fHistQbQc); fHistQaQbCos = new TH1D("Flow_QaQbCos_SP","Flow_QaQbCos_SP",63,0.,TMath::Pi()); fHistQaQbCos->SetYTitle("dN/d#phi"); fHistQaQbCos->SetXTitle("#phi"); tQARelated->Add(fHistQaQbCos); fHistNumberOfSubtractedDaughters = new TH1I("NumberOfSubtractedDaughtersInQ",";daughters;counts;Number of daughters subtracted from Q",5,0.,5.); tQARelated->Add(fHistNumberOfSubtractedDaughters); } fHistList->Add(uQRelated); fHistList->Add(nuaRelated); fHistList->Add(errorRelated); fHistList->Add(tQARelated); TH1::AddDirectory(oldHistAddStatus); } //----------------------------------------------------------------------- void AliFlowAnalysisWithSimpleSP::Make(AliFlowEventSimple* anEvent) { // Scalar Product method if (!anEvent) return; // for coverity fCentralityWeight = anEvent->GetPsi5(); // Get Q vectors for the subevents AliFlowVector* vQarray = new AliFlowVector[2]; if (fUsePhiWeights) anEvent->Get2Qsub(vQarray,fHarmonic,fWeightsList,kTRUE); else anEvent->Get2Qsub(vQarray,fHarmonic); // Subevent a AliFlowVector vQa = vQarray[0]; // Subevent b AliFlowVector vQb = vQarray[1]; delete [] vQarray; // multiplicity here corresponds to the V0 equalized multiplicity Double_t dMa = vQa.GetMult(); if( dMa < 2 ) return; Double_t dMb = vQb.GetMult(); if( dMb < 2 ) return; //fill control histograms fCommonHists->FillControlHistograms(anEvent); //Normalizing: weight the Q vectors for the subevents Double_t dNa = dMa;//fNormalizationType ? dMa: vQa.Mod(); // SP corresponds to true Double_t dNb = dMb;//fNormalizationType ? dMb: vQb.Mod(); // SP corresponds to true Double_t dWa = 1.;//fNormalizationType ? dMa: 1; // SP corresponds to true Double_t dWb = 1.;//NormalizationType ? dMb: 1; // SP corresponds to true // in the original SP method, event weights correspond to multiplicity // for the V0 this does not necessarily make sense as the eq mult // does not scale directly with charged track mult / centrality // this task does not support EP style running, as this is // ambiguous at best //Scalar product of the two subevents vectors Double_t dQaQb = (vQa*vQb); // 01 10 11 <=== fTotalQVector // Q ?= Qa or Qb or QaQb AliFlowVector vQm; vQm.Set(0.0,0.0); AliFlowVector vQTPC; vQTPC.Set(anEvent->GetPsi2(), anEvent->GetPsi3()); Double_t dNq=0; if( (fTotalQvector%2)>0 ) { // 01 or 11 vQm += vQa; dNq += dMa; } if( fTotalQvector>1 ) { // 10 or 11 vQm += vQb; dNq += dMb; } Double_t dWq = 1.;//fNormalizationType ? dNq: 1; // SP corresponds to true // if we dont normalize the q-vectors to the multiplicity, just use 1 here if(!fScaling) { dNa = 1.; dNb = 1.; } // this profile stores the scalar product of the two // subevent q-vectors (the denominator or 'resolution' of the // measurement) // fHistProQaQbNorm->Fill(1., dQaQb/dNa/dNb); //loop over the tracks of the event AliFlowTrackSimple* pTrack = NULL; Int_t iNumberOfTracks = anEvent->NumberOfTracks(); Double_t dMq = 0; for (Int_t i=0;i<iNumberOfTracks;i++) { // so this is a track loop ... pTrack = anEvent->GetTrack(i) ; if (!pTrack) continue; Double_t dPhi = pTrack->Phi(); Double_t dPt = pTrack->Pt(); Double_t dEta = pTrack->Eta(); // make sure it's not a vzero track if(TMath::Abs(dEta) > 0.9) continue; //calculate vU // this is the track q-vecotr (small u) TVector2 vU; Double_t dUX = TMath::Cos(fHarmonic*dPhi); Double_t dUY = TMath::Sin(fHarmonic*dPhi); vU.Set(dUX,dUY); // 01 10 11 <=== fTotalQVector // Q ?= Qa or Qb or QaQb // this will be the vector for hte scalar product itself vQm.Set(0.0,0.0); //start the loop fresh dMq=0; if( (fTotalQvector%2)>0 ) { // 01 or 11 vQm += vQa; dMq += dMa; } if( fTotalQvector>1 ) { // 10 or 11 vQm += vQb; dMq += dMb; } dNq = dMq;//fNormalizationType ? dMq : vQm.Mod(); dWq = 1;//fNormalizationType ? dMq : 1; // this little guy is the enumerator of the final equation Double_t dUQ = vU*vQm; // if we dont want scaling, disable it here if(!fScaling) dNq = 1; //fill the profile histograms for(Int_t iPOI=0; iPOI!=2; ++iPOI) { if( (iPOI==0)&&(!pTrack->InRPSelection()) ) continue; if( (iPOI==1)&&(!pTrack->InPOISelection(fPOItype)) ) continue; fHistProUQ[iPOI][0]->Fill(dPt ,fCentralityWeight*dUQ/dNq); //Fill (uQ/Nq') with weight (Nq') fHistProUQ[iPOI][1]->Fill(dEta,fCentralityWeight*dUQ/dNq); //Fill (uQ/Nq') with weight (Nq') //fHistProUQQaQb[iPOI][0]-> Fill(dPt,(dUQ*dUQ/dNq)/(dQaQb/dNa/dNb)); //Fill [Qu/Nq']*[QaQb/NaNb] with weight (Nq')NaNb } }//loop over tracks //Filling QA (for compatibility with previous version) if(!fMinimalBook) { fHistQaQb->Fill(vQa*vQb/dNa/dNb, fCentralityWeight); fHistQaQc->Fill(vQa*vQTPC, fCentralityWeight); fHistQbQc->Fill(vQb*vQTPC, fCentralityWeight); } } //-------------------------------------------------------------------- void AliFlowAnalysisWithSimpleSP::GetOutputHistograms(TList *outputListHistos){ //get pointers to all output histograms (called before Finish()) fHistList = outputListHistos; fCommonHists = (AliFlowCommonHist*) fHistList->FindObject("AliFlowCommonHist_SP"); // fCommonHistsuQ = (AliFlowCommonHist*) fHistList->FindObject("AliFlowCommonHist_uQ"); fCommonHistsRes = (AliFlowCommonHistResults*) fHistList->FindObject("AliFlowCommonHistResults_SP"); fHistProConfig = (TProfile*) fHistList->FindObject("FlowPro_Flags_SP"); if(!fHistProConfig) printf("Error loading fHistProConfig\n"); TList *uQ = (TList*) fHistList->FindObject("uQ"); TList *nua = (TList*) fHistList->FindObject("NUA"); TList *error = (TList*) fHistList->FindObject("error"); TList* tQARelated = (TList*) fHistList->FindObject("QA"); fHistProQaQbNorm = (TProfile*) error->FindObject("FlowPro_QaQbNorm_SP"); if(!fHistProQaQbNorm) printf("Error loading fHistProQaQbNorm\n"); fHistProNUAq = (TProfile*) nua->FindObject("FlowPro_NUAq_SP"); if(!fHistProNUAq) printf("Error loading fHistProNUAq\n"); fHistSumOfWeights = (TH1D*) error->FindObject("Flow_SumOfWeights_SP"); if(!fHistSumOfWeights) printf("Error loading fHistSumOfWeights\n"); TString sPOI[2] = {"RP","POI"}; TString sEta[2] = {"Pt","eta"}; TString sWeights[3] = {"uQ","uQuQ","uQQaQb"}; for(Int_t iPOI=0; iPOI!=2; ++iPOI) for(Int_t iSpace=0; iSpace!=2; ++iSpace) { fHistProUQ[iPOI][iSpace] = (TProfile*) uQ->FindObject( Form( "FlowPro_UQ_%s%s_SP", sEta[iSpace].Data(), sPOI[iPOI].Data() ) ); if(!fHistProUQ[iPOI][iSpace]) printf("Error loading fHistProUQ[%d][%d]\n",iPOI,iSpace); fHistProNUAu[iPOI][iSpace][0] = (TProfile*) nua->FindObject( Form("FlowPro_NUAu_%s%s_IM_SP", sEta[iSpace].Data(), sPOI[iPOI].Data() ) ); if(!fHistProNUAu[iPOI][iSpace][0]) printf("Error loading fHistProNUAu[%d][%d][0]\n",iPOI,iSpace); fHistProNUAu[iPOI][iSpace][1] = (TProfile*) nua->FindObject( Form("FlowPro_NUAu_%s%s_RE_SP", sEta[iSpace].Data(), sPOI[iPOI].Data() ) ); if(!fHistProNUAu[iPOI][iSpace][1]) printf("Error loading fHistProNUAu[%d][%d][1]\n",iPOI,iSpace); fHistProUQQaQb[iPOI][iSpace] = (TProfile*) error->FindObject( Form("FlowPro_UQQaQb_%s%s_SP", sEta[iSpace].Data(), sPOI[iPOI].Data() ) ); for(Int_t i=0; i!=3; ++i){ fHistSumOfWeightsu[iPOI][iSpace][i] = (TH1D*) error->FindObject( Form("Flow_SumOfWeights_%s%s_%s_SP",sWeights[i].Data(),sPOI[iPOI].Data(),sEta[iSpace].Data()) ); if(!fHistSumOfWeightsu[iPOI][iSpace][i]) printf("Error loading fHistSumOfWeightsu[%d][%d][%d]\n",iPOI,iSpace,i); } } if(fHistProConfig) { fApplyCorrectionForNUA = (Int_t) fHistProConfig->GetBinContent(1); fNormalizationType = (Int_t) fHistProConfig->GetBinContent(2); fUsePhiWeights = (Int_t) fHistProConfig->GetBinContent(3); fHarmonic = (Int_t) fHistProConfig->GetBinContent(4); } fHistQaQb = (TH1D*)tQARelated->FindObject("Flow_QaQb_SP"); fHistQaQc = (TH1D*)tQARelated->FindObject("Flow_QaQc_SP"); fHistQbQc = (TH1D*)tQARelated->FindObject("Flow_QbQc_SP"); } //-------------------------------------------------------------------- void AliFlowAnalysisWithSimpleSP::Finish(Bool_t A) { //calculate flow and fill the AliFlowCommonHistResults printf("AliFlowAnalysisWithSimpleSP::Finish()\n"); // access harmonic: fApplyCorrectionForNUA = 0;//(Int_t)(fHistProConfig->GetBinContent(1)); fNormalizationType = 1;//(Int_t)(fHistProConfig->GetBinContent(2)); fHarmonic = (Int_t)(fHistProConfig->GetBinContent(4)); printf("*************************************\n"); printf("*************************************\n"); printf(" Integrated flow from SIMPLE \n"); printf(" Scalar Product \n\n"); //Calculate reference flow //---------------------------------- //weighted average over (QaQb/NaNb) with weight (NaNb) if(!fHistQaQb) { printf(" PANIC: run with full booking !"); return; } Double_t dEntriesQaQb = fHistQaQb->GetEntries(); if( dEntriesQaQb < 1 ) { printf(" fHistQaQb has less than 1 entry, probably sub-events are misconfigured \n"); return; } //fHistQaQb->GetXaxis()->SetRangeUser(-10.,10.); //fHistQaQC->GetXaxis()->SetRangeUser(-1000., 1000.); //fHistQbQc->GetXaxis()->SetRangeUser(-1000., 1000.); Double_t dQaQb = fHistQaQb->GetMean(); Double_t dQaQc = fHistQaQc->GetMean(); Double_t dQbQc = fHistQbQc->GetMean(); if(A) { // now it's the resolution of A (which is vzero C) dQaQb = (dQaQb*dQaQc)/dQbQc; } else { // else we select the resolution of B (which is V0A) dQaQb = (dQaQb*dQbQc)/dQaQc; } Double_t dSpreadQaQb = fHistQaQb->GetRMS(); // this is the `resolution' if(dQaQb <= .0 ) { printf(" Panic! the average of QaQb <= 0! Probably you need to run on more events !\n"); printf(" \tusing dummy value 1 to avoid segfault \n"); dQaQb = 1.; dSpreadQaQb = 1.; } Double_t dV = TMath::Sqrt(dQaQb); printf("ResSub (sqrt of scalar product of sub-event qvectors) = %f\n", dV ); printf("fTotalQvector %d \n",fTotalQvector); // we just take the spread as the uncertainty Double_t dStatErrorQaQb = dSpreadQaQb; Double_t dVerr = 0.; if(dQaQb > 0.) dVerr = (1./(2.*pow(dQaQb,0.5)))*dStatErrorQaQb; fCommonHistsRes->FillIntegratedFlow(dV,dVerr); printf("v%d(subevents) = %f +- %f\n",fHarmonic,dV,dVerr); Int_t iNbins[2]; iNbins[0] = AliFlowCommonConstants::GetMaster()->GetNbinsPt(); iNbins[1] = AliFlowCommonConstants::GetMaster()->GetNbinsEta(); //Calculate differential flow and integrated flow (RP, POI) //--------------------------------------------------------- //v as a function of eta for RP selection for(Int_t iRFPorPOI=0; iRFPorPOI != 2; ++iRFPorPOI) for(Int_t iPTorETA=0; iPTorETA != 2; ++iPTorETA) for(Int_t b=1; b != iNbins[iPTorETA]+1; ++b) { Double_t duQpro = fHistProUQ[iRFPorPOI][iPTorETA]->GetBinContent(b); Double_t dv2pro = -999.; if( TMath::Abs(dV!=0.) && fExternalResolution < 0 ) { dv2pro = duQpro/dV; } else if(fExternalResolution > 0) { dv2pro = duQpro / fExternalResolution; } Double_t dv2ProErr = fHistProUQ[iRFPorPOI][iPTorETA]->GetBinError(b); if(fHistProUQ[iRFPorPOI][iPTorETA]->GetBinEntries(b) > 1) dv2ProErr/=TMath::Sqrt(fHistProUQ[iRFPorPOI][iPTorETA]->GetBinEntries(b)); if(fExternalResErr > 0) { // do default error propagation for a fraction where Double_t a(0), b(0), t(0); if(dv2ProErr > 0) a = duQpro*duQpro/(dv2ProErr*dv2ProErr); // squared relative error if(fExternalResErr > 0) b = fExternalResolution*fExternalResolution/(fExternalResErr*fExternalResErr); t = duQpro*fExternalResolution/(dv2ProErr*fExternalResErr); t = dv2pro*dv2pro*(a + b -2.*t); if(t>0) dv2ProErr = TMath::Sqrt(t); } if( (iRFPorPOI==0)&&(iPTorETA==0) ) fCommonHistsRes->FillDifferentialFlowPtRP( b, dv2pro, dv2ProErr); if( (iRFPorPOI==0)&&(iPTorETA==1) ) fCommonHistsRes->FillDifferentialFlowEtaRP( b, dv2pro, dv2ProErr); if( (iRFPorPOI==1)&&(iPTorETA==0) ) fCommonHistsRes->FillDifferentialFlowPtPOI( b, dv2pro, dv2ProErr); if( (iRFPorPOI==1)&&(iPTorETA==1) ) fCommonHistsRes->FillDifferentialFlowEtaPOI(b, dv2pro, dv2ProErr); } printf("\n"); printf("*************************************\n"); printf("*************************************\n"); } //----------------------------------------------------------------------- void AliFlowAnalysisWithSimpleSP::WriteHistograms(TDirectoryFile *outputFileName) const { //store the final results in output .root file outputFileName->Add(fHistList); outputFileName->Write(outputFileName->GetName(), TObject::kSingleKey); } //--------------------------------------------------------------------
43.244019
173
0.599174
amveen
ac58b899dab9390ae450400c317335dda3b61af6
14,350
cpp
C++
compiler/src/analyzer/SymbolTable.cpp
chillibits/spice
f8bfc48819690035c6ce522a7989223800456faf
[ "MIT" ]
13
2021-07-16T08:20:10.000Z
2021-12-16T05:51:18.000Z
compiler/src/analyzer/SymbolTable.cpp
chillibits/spice
f8bfc48819690035c6ce522a7989223800456faf
[ "MIT" ]
9
2021-07-06T20:36:31.000Z
2021-12-26T23:42:51.000Z
compiler/src/analyzer/SymbolTable.cpp
chillibits/spice
f8bfc48819690035c6ce522a7989223800456faf
[ "MIT" ]
null
null
null
// Copyright (c) 2021-2022 ChilliBits. All rights reserved. #include "SymbolTable.h" #include "AnalyzerVisitor.h" /** * Insert a new symbol into the current symbol table. If it is a parameter, append its name to the paramNames vector * * @param name Name of the symbol * @param type Type of the symbol * @param state State of the symbol (declared or initialized) * @param isConstant Enabled if the symbol is a constant * @param isParameter Enabled if the symbol is a function/procedure parameter */ void SymbolTable::insert(const std::string& name, SymbolType type, SymbolState state, const antlr4::Token& token, bool isConstant, bool isParameter) { bool isGlobal = getParent() == nullptr; unsigned int orderIndex = symbols.size(); // Insert into symbols map symbols.insert({ name, SymbolTableEntry(name, type, state, token, orderIndex, isConstant, isGlobal) }); // If the symbol is a parameter, add it to the parameters list if (isParameter) paramNames.push_back(name); } /** * Check if a symbol exists in the current or any parent scope and return it if possible * * @param name Name of the desired symbol * @return Desired symbol / nullptr if the symbol was not found */ SymbolTableEntry* SymbolTable::lookup(const std::string& name) { // If not available in the current scope, search in the parent scope if (symbols.find(name) == symbols.end()) { if (parent == nullptr) return nullptr; return parent->lookup(name); } // Otherwise, return the entry return &symbols.at(name); } /** * Check if an order index exists in the current or any parent scope and returns it if possible. * Warning: Unlike the `lookup` method, this one doesn't consider the parent scopes * * @param orderIndex Order index of the desired symbol * @return Desired symbol / nullptr if the symbol was not found */ SymbolTableEntry* SymbolTable::lookupByIndexInCurrentScope(unsigned int orderIndex) { for (auto& [key, val] : symbols) { if (val.getOrderIndex() == orderIndex) return &val; } return nullptr; } /** * Search for a symbol table by its name, where a function is defined. Used for function calls to function/procedures * which were linked in from other modules * * @param scopeId Scope ID of the desired symbol table * @return Desired symbol table */ SymbolTable* SymbolTable::lookupTable(const std::string& scopeId) { // If not available in the current scope, search in the parent scope if (children.find(scopeId) == children.end()) { if (parent == nullptr) return nullptr; return parent->lookupTable(scopeId); } // Otherwise, return the entry return &children.at(scopeId); } /** * Search for a symbol table by its name, where a symbol is defined. Used for function calls to function/procedures * which were linked in from other modules * * @param signature Signature of the function/procedure * @return Desired symbol table */ SymbolTable* SymbolTable::lookupTableWithSignature(const std::string& signature) { // Check if scope contains this signature if (symbols.find(signature) != symbols.end()) return this; // Current scope does not contain the signature => go up one table if (parent == nullptr) return nullptr; return parent->lookupTableWithSignature(signature); } /** * Update the state of a symbol in the current symbol table or a parent scope. * * @throws runtime_error When trying to update a non-existent symbol * @param name Name of the symbol to update * @param newState New state of the symbol to update */ void SymbolTable::update(const std::string& name, SymbolState newState) { // If not available in the current scope, search in the parent scope if (symbols.find(name) == symbols.end()) { if (parent == nullptr) throw std::runtime_error("Updating a non-existent symbol: " + name); parent->update(name, newState); } // Otherwise, update the entry symbols.at(name).updateState(newState); } /** * Update the type of a symbol in the current symbol table or a parent scope. This is used for type inference of * dyn variables * * @param name Name of the symbol to update * @param newType New type of the symbol to update */ void SymbolTable::update(const std::string& name, SymbolType newType) { // If not available in the current scope, search in the parent scope if (symbols.find(name) == symbols.end()) { if (parent == nullptr) throw std::runtime_error("Updating a non-existent symbol: " + name); parent->update(name, newType); } // Otherwise, update the entry symbols.at(name).updateType(newType, false); } /** * Create a child leaf for the tree of symbol tables and return it * * @param blockName Name of the child scope * @return Newly created child table */ SymbolTable* SymbolTable::createChildBlock(const std::string& blockName) { children.insert({blockName, SymbolTable(this, inMainSourceFile)}); return &children.at(blockName); } /** * Mount in symbol tables manually. This is used to hook in symbol tables of imported modules into the symbol table of * the source file, which imported the modules * * @param blockName Name of the child scope * @param childBlock Child symbol table */ void SymbolTable::mountChildBlock(const std::string& blockName, SymbolTable* childBlock) { childBlock->parent = this; children.insert({blockName, *childBlock}); } /** * Rename the scope of a symbol table. This is useful for realizing function overloading by storing a function with not * only its name, but also its signature * * @param oldName Old name of the child table * @param newName New name of the child table */ void SymbolTable::renameChildBlock(const std::string& oldName, const std::string& newName) { auto nodeHandler = children.extract(oldName); nodeHandler.key() = newName; children.insert(std::move(nodeHandler)); } /** * Navigate to parent table of the current one in the tree structure * * @return Pointer to the parent symbol table */ SymbolTable* SymbolTable::getParent() { return parent; } /** * Navigate to a child table of the current one in the tree structure * * @param scopeId Name of the child scope * @return Pointer to the child symbol table */ SymbolTable* SymbolTable::getChild(const std::string& scopeId) { if (children.empty()) return nullptr; if (children.find(scopeId) == children.end()) return nullptr; return &children.at(scopeId); } /** * Returns the number of symbols in the table, which are no functions, procedures or import * * @return Number of fields */ unsigned int SymbolTable::getFieldCount() { unsigned int count = 0; for (auto& [key, symbol] : symbols) { if (!symbol.getType().isOneOf({ TY_FUNCTION, TY_PROCEDURE, TY_IMPORT })) count++; } return count; } /** * Insert an item to the list of function declarations. This list is used to link in functions from other modules and * therefore not storing their definition, but their declaration. * * @param signature Signature of the function declaration * @param types List of parameter types of the function declaration */ void SymbolTable::insertFunctionDeclaration(const std::string& signature, const std::vector<SymbolType>& types) { functionDeclarations.insert({signature, types}); } /** * Retrieve an item from the list of function declarations. * * @param signature Signature of the desired function declaration * @return List of parameter types of the desired function declaration */ std::vector<SymbolType> SymbolTable::getFunctionDeclaration(const std::string& signature) { if (functionDeclarations.find(signature) == functionDeclarations.end()) return {}; return functionDeclarations.at(signature); } /** * Insert an item to the list of procedure declarations. This list is used to link in procedures from other modules and * therefore not storing their definition, but their declaration. * * @param signature Signature of the procedure declaration * @param types List of parameter types of the procedure declaration */ void SymbolTable::insertProcedureDeclaration(const std::string& signature, const std::vector<SymbolType>& types) { procedureDeclarations.insert({signature, types}); } /** * Retrieve an item from the list of procedure declarations. * * @param signature Signature of the desired procedure declaration * @return List of parameter types of the desired procedure declaration */ std::vector<SymbolType> SymbolTable::getProcedureDeclaration(const std::string& signature) { if (procedureDeclarations.find(signature) == procedureDeclarations.end()) return {}; return procedureDeclarations.at(signature); } /** * Changes a specific type to another in the whole sub-table * * @param oldType Old symbol type * @param newType Replacement type */ void SymbolTable::updateSymbolTypes(const SymbolType& oldType, const SymbolType& newType) { // Update types in the symbol list for (auto& [key, symbol] : symbols) { SymbolType currentType = symbol.getType(); std::vector<SymbolSuperType> ptrArrayList; while (currentType.isOneOf({ TY_PTR, TY_ARRAY })) { if (currentType.isPointer()) ptrArrayList.push_back(TY_PTR); else ptrArrayList.push_back(TY_ARRAY); currentType = currentType.getContainedTy(); } if (currentType == oldType) { std::reverse(ptrArrayList.begin(), ptrArrayList.end()); SymbolType currentNewType = newType; for (auto& superType : ptrArrayList) { if (superType == TY_PTR) currentNewType = currentNewType.toPointer(); else currentNewType = currentNewType.toArray(); } symbol.updateType(currentNewType, true); } } // Visit all child tables for (auto& [key, child] : children) child.updateSymbolTypes(oldType, newType); } /** * Push a function/procedure signature to a queue of function/procedure signatures. This is used to push the signatures * of function/procedure definitions and calls in the semantic analysis * * @param signature Signature of the function/procedure */ void SymbolTable::pushSignature(const FunctionSignature& signature) { functionSignatures.push(signature); } /** * Pop a function/procedure signature from a queue of function/procedure signatures. This is used to pop the signatures * of function/procedure definitions and calls in the generator component * * @return Signature of the function/procedure */ FunctionSignature SymbolTable::popSignature() { auto signature = functionSignatures.front(); functionSignatures.pop(); return signature; } /** * Set continue block, which marks where to continue when a continue instruction is executed in the current scope * * @param block */ void SymbolTable::setContinueBlock(llvm::BasicBlock* block) { continueBlock = block; } /** * Retrieve the LLVM BasicBlock, which is currently set as continue block for the current scope * * @return Continue block */ llvm::BasicBlock* SymbolTable::getContinueBlock() const { return continueBlock; } /** * Set break block, which marks where to continue when a break instruction is executed in the current scope * * @param block */ void SymbolTable::setBreakBlock(llvm::BasicBlock* block) { breakBlock = block; } /** * Retrieve the LLVM BasicBlock, which is currently set as break block for the current scope * * @return Break block */ llvm::BasicBlock* SymbolTable::getBreakBlock() const { return breakBlock; } /** * Prints compiler values with regard to the symbol table */ void SymbolTable::printCompilerWarnings() { // Omit this table if it is an imported sub-table if (imported) return; // Visit own symbols for (auto& [key, entry] : symbols) { if (!entry.isUsed()) { if (entry.getType().is(TY_FUNCTION)) { CompilerWarning(entry.getDefinitionToken(), UNUSED_FUNCTION, "The function '" + entry.getName() + "' is unused").print(); } else if (entry.getType().is(TY_PROCEDURE)) { CompilerWarning(entry.getDefinitionToken(), UNUSED_PROCEDURE, "The procedure '" + entry.getName() + "' is unused").print(); } else if (entry.getType().is(TY_STRUCT) || entry.getType().isPointerOf(TY_STRUCT)) { CompilerWarning(entry.getDefinitionToken(), UNUSED_STRUCT, "The struct '" + entry.getName() + "' is unused").print(); } else if (entry.getType().isOneOf({ TY_IMPORT })) { CompilerWarning(entry.getDefinitionToken(), UNUSED_IMPORT, "The import '" + entry.getName() + "' is unused").print(); } else { if (entry.getName() != UNUSED_VARIABLE_NAME) CompilerWarning(entry.getDefinitionToken(), UNUSED_VARIABLE, "The variable '" + entry.getName() + "' is unused").print(); } } } // Visit children for (auto& [key, child] : children) child.printCompilerWarnings(); } /** * Stringify a symbol table to a human-readable form. This is used to realize dumps of symbol tables * * @return Symbol table if form of a string */ std::string SymbolTable::toString() { std::string symbolsString, childrenString; // Build symbols string for (auto& symbol : symbols) symbolsString.append("(" + symbol.second.toString() + ")\n"); // Build children string for (auto& child : children) childrenString.append(child.first + ": " + child.second.toString() + "\n"); if (childrenString.empty()) return "SymbolTable(\n" + symbolsString + ")"; return "SymbolTable(\n" + symbolsString + ") {\n" + childrenString + "}"; } /** * Marks this symbol table as imported. This means, that it is a nested symbol table in the main symbol table */ void SymbolTable::setImported() { imported = true; } /** * Checks if this symbol table is imported * * @return Imported / not imported */ bool SymbolTable::isImported() { return imported; }
36.42132
119
0.686899
chillibits
ac59409c5717250f126866a0ad637cd5b0e91e33
2,498
cpp
C++
SPOJ/SPOJ_-_3266._K-query/main.cpp
rusucosmin/Cplusplus
0e95cd01d20b22404aa4166c71d5a9e834a5a21b
[ "MIT" ]
11
2015-08-29T13:41:22.000Z
2020-01-08T20:34:06.000Z
SPOJ/SPOJ_-_3266._K-query/main.cpp
rusucosmin/Cplusplus
0e95cd01d20b22404aa4166c71d5a9e834a5a21b
[ "MIT" ]
null
null
null
SPOJ/SPOJ_-_3266._K-query/main.cpp
rusucosmin/Cplusplus
0e95cd01d20b22404aa4166c71d5a9e834a5a21b
[ "MIT" ]
5
2016-01-20T18:17:01.000Z
2019-10-30T11:57:15.000Z
#include <fstream> #include <iostream> #include <vector> #include <bitset> #include <string.h> #include <algorithm> #include <iomanip> #include <math.h> #include <time.h> #include <stdlib.h> #include <set> #include <map> #include <string> #include <queue> #include <deque> using namespace std; const char infile[] = "input.in"; const char outfile[] = "output.out"; ifstream fin(infile); ofstream fout(outfile); const int MAXN = 30005; const int MAXQ = 200005; const int oo = 0x3f3f3f3f; typedef vector<int> Graph[MAXN]; typedef vector<int> :: iterator It; const inline int min(const int &a, const int &b) { if( a > b ) return b; return a; } const inline int max(const int &a, const int &b) { if( a < b ) return b; return a; } const inline void Get_min(int &a, const int b) { if( a > b ) a = b; } const inline void Get_max(int &a, const int b) { if( a < b ) a = b; } struct event { int ind; int val; int st; int dr; bool type; event(int _ind, int _val, bool _type, int _st = 0, int _dr = 0) { ind = _ind; val = _val; type = _type; st = _st; dr = _dr; } }; vector <event> V; int N, Q; int ans[MAXQ]; struct classComp { inline bool operator () (const event &a, const event &b) const { return a.val < b.val || (a.val == b.val && a.type < b.type); } }; int aib[MAXN]; inline int lsb(int x) { return x & (-x); } inline void Update(int pos) { for(int i = pos ; i <= N ; i += lsb(i)) ++ aib[i]; } inline int Query(int pos) { int sum = 0; for(int i = pos ; i > 0 ; i -= lsb(i)) sum += aib[i]; return sum; } int main() { #ifndef ONLINE_JUDGE freopen(infile, "r", stdin); freopen(outfile, "w", stdout); #endif // ONLINE_JUDGE scanf("%d", &N); for(int i = 1 ; i <= N ; ++ i) { int x; scanf("%d", &x); V.push_back(event(i, x, 0)); } scanf("%d", &Q); for(int i = 1 ; i <= Q ; ++ i) { int x, y, k; scanf("%d%d%d", &x, &y, &k); V.push_back(event(i, k, 1, x, y)); } sort(V.begin(), V.end(), classComp()); for(vector <event> :: iterator it = V.begin(), fin = V.end(); it != fin ; ++ it) { if(it->type) { int lessThan = Query(it->dr) - Query(it->st - 1); ans[it->ind] = (it->dr - it->st + 1) - lessThan; } else Update(it->ind); } for(int i = 1 ; i <= Q ; ++ i) printf("%d\n", ans[i]); return 0; }
22.709091
86
0.528022
rusucosmin
ac5bdee939f338383600bd2fac95904bffb04865
1,659
cpp
C++
src/core/tests/visitors/dimension.cpp
ryanloney/openvino-1
4e0a740eb3ee31062ba0df88fcf438564f67edb7
[ "Apache-2.0" ]
1,127
2018-10-15T14:36:58.000Z
2020-04-20T09:29:44.000Z
src/core/tests/visitors/dimension.cpp
ryanloney/openvino-1
4e0a740eb3ee31062ba0df88fcf438564f67edb7
[ "Apache-2.0" ]
439
2018-10-20T04:40:35.000Z
2020-04-19T05:56:25.000Z
src/core/tests/visitors/dimension.cpp
ryanloney/openvino-1
4e0a740eb3ee31062ba0df88fcf438564f67edb7
[ "Apache-2.0" ]
414
2018-10-17T05:53:46.000Z
2020-04-16T17:29:53.000Z
// Copyright (C) 2018-2022 Intel Corporation // SPDX-License-Identifier: Apache-2.0 // #include "gtest/gtest.h" #include "ngraph/ngraph.hpp" #include "ngraph/op/util/attr_types.hpp" #include "ngraph/opsets/opset1.hpp" #include "ngraph/opsets/opset3.hpp" #include "ngraph/opsets/opset4.hpp" #include "ngraph/opsets/opset5.hpp" #include "util/visitor.hpp" using namespace std; using namespace ngraph; using ngraph::test::NodeBuilder; using ngraph::test::ValueMap; TEST(attributes, dimension) { NodeBuilder builder; AttributeVisitor& loader = builder.get_node_loader(); AttributeVisitor& saver = builder.get_node_saver(); Dimension dyn = Dimension(-1); saver.on_attribute("dyn", dyn); Dimension g_dyn; loader.on_attribute("dyn", g_dyn); EXPECT_EQ(dyn, g_dyn); Dimension scalar = Dimension(10); saver.on_attribute("scalar", scalar); Dimension g_scalar; loader.on_attribute("scalar", g_scalar); EXPECT_EQ(scalar, g_scalar); Dimension boundaries1 = Dimension(2, 100); saver.on_attribute("boundaries1", boundaries1); Dimension g_boundaries1; loader.on_attribute("boundaries1", g_boundaries1); EXPECT_EQ(boundaries1, g_boundaries1); Dimension boundaries2 = Dimension(-1, 100); saver.on_attribute("boundaries2", boundaries2); Dimension g_boundaries2; loader.on_attribute("boundaries2", g_boundaries2); EXPECT_EQ(boundaries2, g_boundaries2); Dimension boundaries3 = Dimension(5, -1); saver.on_attribute("boundaries3", boundaries3); Dimension g_boundaries3; loader.on_attribute("boundaries3", g_boundaries3); EXPECT_EQ(boundaries3, g_boundaries3); }
30.722222
57
0.732369
ryanloney
ac5c29c36c2518fc591a949accccfd9aecb55958
24,233
cpp
C++
src/utils.cpp
dangerdevices/gdstk
bff6b2e5950b9da5b3b3f8bdb653778cf679e592
[ "BSL-1.0" ]
135
2020-08-12T22:32:21.000Z
2022-03-31T04:34:56.000Z
src/utils.cpp
dangerdevices/gdstk
bff6b2e5950b9da5b3b3f8bdb653778cf679e592
[ "BSL-1.0" ]
80
2020-08-12T23:03:44.000Z
2022-03-18T12:25:41.000Z
src/utils.cpp
dangerdevices/gdstk
bff6b2e5950b9da5b3b3f8bdb653778cf679e592
[ "BSL-1.0" ]
35
2020-09-08T15:55:01.000Z
2022-03-29T04:52:58.000Z
/* Copyright 2020 Lucas Heitzmann Gabrielli. This file is part of gdstk, distributed under the terms of the Boost Software License - Version 1.0. See the accompanying LICENSE file or <http://www.boost.org/LICENSE_1_0.txt> */ #include "utils.h" #include <assert.h> #include <inttypes.h> #include <limits.h> #include <math.h> #include <stdint.h> #include <string.h> #include <time.h> #include "allocator.h" #include "vec.h" // Qhull #include "libqhull_r/qhull_ra.h" namespace gdstk { char* copy_string(const char* str, uint64_t* len) { uint64_t size = 1 + strlen(str); char* result = (char*)allocate(size); memcpy(result, str, size); if (len) *len = size; return result; } bool is_multiple_of_pi_over_2(double angle, int64_t& m) { if (angle == 0) { m = 0; return true; } else if (angle == 0.5 * M_PI) { m = 1; return true; } else if (angle == -0.5 * M_PI) { m = -1; return true; } else if (angle == M_PI) { m = 2; return true; } else if (angle == -M_PI) { m = -2; return true; } else if (angle == 1.5 * M_PI) { m = 3; return true; } else if (angle == -1.5 * M_PI) { m = -3; return true; } else if (angle == 2 * M_PI) { m = 4; return true; } else if (angle == -2 * M_PI) { m = -4; return true; } m = (int64_t)llround(angle / (M_PI / 2)); if (fabs(m * (M_PI / 2) - angle) < 1e-16) return true; return false; } uint64_t arc_num_points(double angle, double radius, double tolerance) { assert(radius > 0); assert(tolerance > 0); double c = 1 - tolerance / radius; double a = c < -1 ? M_PI : acos(c); return (uint64_t)(0.5 + 0.5 * fabs(angle) / a); } static double modulo(double x, double y) { double m = fmod(x, y); return m < 0 ? m + y : m; } double elliptical_angle_transform(double angle, double radius_x, double radius_y) { if (angle == 0 || angle == M_PI || radius_x == radius_y) return angle; double frac = angle - (modulo(angle + M_PI, 2 * M_PI) - M_PI); double ell_angle = frac + atan2(radius_x * sin(angle), radius_y * cos(angle)); return ell_angle; } double distance_to_line_sq(const Vec2 p, const Vec2 p1, const Vec2 p2) { const Vec2 v_line = p2 - p1; const Vec2 v_point = p - p1; const double c = v_point.cross(v_line); return c * c / v_line.length_sq(); } double distance_to_line(const Vec2 p, const Vec2 p1, const Vec2 p2) { const Vec2 v_line = p2 - p1; const Vec2 v_point = p - p1; return fabs(v_point.cross(v_line)) / v_line.length(); } void segments_intersection(const Vec2 p0, const Vec2 ut0, const Vec2 p1, const Vec2 ut1, double& u0, double& u1) { const double den = ut0.cross(ut1); u0 = 0; u1 = 0; if (den >= GDSTK_PARALLEL_EPS || den <= -GDSTK_PARALLEL_EPS) { const Vec2 delta_p = p1 - p0; u0 = delta_p.cross(ut1) / den; u1 = delta_p.cross(ut0) / den; } } void scale_and_round_array(const Array<Vec2> points, double scaling, Array<IntVec2>& scaled_points) { scaled_points.ensure_slots(points.count); scaled_points.count = points.count; int64_t* s = (int64_t*)scaled_points.items; double* p = (double*)points.items; for (uint64_t i = 2 * points.count; i > 0; i--) { *s++ = (int64_t)llround((*p++) * scaling); } } void big_endian_swap16(uint16_t* buffer, uint64_t n) { if (IS_BIG_ENDIAN) return; for (; n > 0; n--) { uint16_t b = *buffer; *buffer++ = (b << 8) | (b >> 8); } } void big_endian_swap32(uint32_t* buffer, uint64_t n) { if (IS_BIG_ENDIAN) return; for (; n > 0; n--) { uint32_t b = *buffer; *buffer++ = (b << 24) | ((b & 0x0000FF00) << 8) | ((b & 0x00FF0000) >> 8) | (b >> 24); } } void big_endian_swap64(uint64_t* buffer, uint64_t n) { if (IS_BIG_ENDIAN) return; for (; n > 0; n--) { uint64_t b = *buffer; *buffer++ = (b << 56) | ((b & 0x000000000000FF00) << 40) | ((b & 0x0000000000FF0000) << 24) | ((b & 0x00000000FF000000) << 8) | ((b & 0x000000FF00000000) >> 8) | ((b & 0x0000FF0000000000) >> 24) | ((b & 0x00FF000000000000) >> 40) | (b >> 56); } } void little_endian_swap16(uint16_t* buffer, uint64_t n) { if (!IS_BIG_ENDIAN) return; for (; n > 0; n--) { uint16_t b = *buffer; *buffer++ = (b << 8) | (b >> 8); } } void little_endian_swap32(uint32_t* buffer, uint64_t n) { if (!IS_BIG_ENDIAN) return; for (; n > 0; n--) { uint32_t b = *buffer; *buffer++ = (b << 24) | ((b & 0x0000FF00) << 8) | ((b & 0x00FF0000) >> 8) | (b >> 24); } } void little_endian_swap64(uint64_t* buffer, uint64_t n) { if (!IS_BIG_ENDIAN) return; for (; n > 0; n--) { uint64_t b = *buffer; *buffer++ = (b << 56) | ((b & 0x000000000000FF00) << 40) | ((b & 0x0000000000FF0000) << 24) | ((b & 0x00000000FF000000) << 8) | ((b & 0x000000FF00000000) >> 8) | ((b & 0x0000FF0000000000) >> 24) | ((b & 0x00FF000000000000) >> 40) | (b >> 56); } } uint32_t checksum32(uint32_t checksum, const uint8_t* bytes, uint64_t count) { uint64_t c = checksum; while (count-- > 0) c = (c + *bytes++) & 0xFFFFFFFF; return (uint32_t)c; } Vec2 eval_line(double t, const Vec2 p0, const Vec2 p1) { return LERP(p0, p1, t); } Vec2 eval_bezier2(double t, const Vec2 p0, const Vec2 p1, const Vec2 p2) { const double t2 = t * t; const double r = 1 - t; const double r2 = r * r; Vec2 result = r2 * p0 + 2 * r * t * p1 + t2 * p2; return result; } Vec2 eval_bezier3(double t, const Vec2 p0, const Vec2 p1, const Vec2 p2, const Vec2 p3) { const double t2 = t * t; const double t3 = t2 * t; const double r = 1 - t; const double r2 = r * r; const double r3 = r2 * r; Vec2 result = r3 * p0 + 3 * r2 * t * p1 + 3 * r * t2 * p2 + t3 * p3; return result; } Vec2 eval_bezier(double t, const Vec2* ctrl, uint64_t count) { Vec2 result; Vec2* p = (Vec2*)allocate(sizeof(Vec2) * count); memcpy(p, ctrl, sizeof(Vec2) * count); const double r = 1 - t; for (uint64_t j = count - 1; j > 0; j--) for (uint64_t i = 0; i < j; i++) p[i] = r * p[i] + t * p[i + 1]; result = p[0]; free_allocation(p); return result; } #ifndef NDEBUG // NOTE: m[rows * cols] is assumed to be stored in row-major order void print_matrix(double* m, uint64_t rows, uint64_t cols) { for (uint64_t r = 0; r < rows; r++) { printf("["); for (uint64_t c = 0; c < cols; c++) { if (c) printf("\t"); printf("%.3g", *m++); } printf("]\n"); } } #endif // NOTE: m[rows * cols] must be stored in row-major order // NOTE: pivots[rows] returns the pivoting order uint64_t gauss_jordan_elimination(double* m, uint64_t* pivots, uint64_t rows, uint64_t cols) { assert(cols >= rows); uint64_t result = 0; uint64_t* p = pivots; for (uint64_t i = 0; i < rows; ++i) { *p++ = i; } for (uint64_t i = 0; i < rows; ++i) { // Select pivot: row with largest absolute value at column i double pivot_value = fabs(m[pivots[i] * cols + i]); uint64_t pivot_row = i; for (uint64_t j = i + 1; j < rows; ++j) { double candidate = fabs(m[pivots[j] * cols + i]); if (candidate > pivot_value) { pivot_value = candidate; pivot_row = j; } } if (pivot_value == 0) { result += 1; continue; } uint64_t row = pivots[pivot_row]; pivots[pivot_row] = pivots[i]; pivots[i] = row; // Scale row double* element = m + (row * cols + i); double factor = 1.0 / *element; for (uint64_t j = i; j < cols; ++j) { *element++ *= factor; } // Zero i-th column from other rows for (uint64_t r = 0; r < rows; ++r) { if (r == row) continue; element = m + row * cols; double* other_row = m + r * cols; factor = other_row[i]; for (uint64_t j = 0; j < cols; ++j) { *other_row++ -= factor * *element++; } } } return result; } // NOTE: Matrix stored in column-major order! void hobby_interpolation(uint64_t count, Vec2* points, double* angles, bool* angle_constraints, Vec2* tension, double initial_curl, double final_curl, bool cycle) { const double A = sqrt(2.0); const double B = 1.0 / 16.0; const double C = 0.5 * (3.0 - sqrt(5.0)); double* m = (double*)allocate(sizeof(double) * (2 * count * (2 * count + 1))); uint64_t* pivots = (uint64_t*)allocate(sizeof(uint64_t) * (2 * count)); Vec2* pts = points; Vec2* tens = tension; double* ang = angles; bool* ang_c = angle_constraints; uint64_t points_size = count; uint64_t rotate = 0; if (cycle) { while (rotate < count && !angle_constraints[rotate]) rotate++; if (rotate == count) { // No angle constraints const uint64_t rows = 2 * count; const uint64_t cols = rows + 1; Vec2 v = points[3] - points[0]; Vec2 v_prev = points[0] - points[3 * (count - 1)]; double length_v = v.length(); double delta_prev = v_prev.angle(); memset(m, 0, sizeof(double) * rows * cols); for (uint64_t i = 0; i < count; i++) { const uint64_t i_1 = i == 0 ? count - 1 : i - 1; const uint64_t i1 = i == count - 1 ? 0 : i + 1; const uint64_t i2 = i < count - 2 ? i + 2 : (i == count - 2 ? 0 : 1); const uint64_t j = count + i; const uint64_t j_1 = count + i_1; const uint64_t j1 = count + i1; const double delta = v.angle(); const Vec2 v_next = points[3 * i2] - points[3 * i1]; const double length_v_next = v_next.length(); double psi = delta - delta_prev; while (psi <= -M_PI) psi += 2 * M_PI; while (psi > M_PI) psi -= 2 * M_PI; m[i * cols + rows] = -psi; m[i * cols + i] = 1; m[i * cols + j_1] = 1; // A_i m[j * cols + i] = length_v_next * tension[i2].u * tension[i1].u * tension[i1].u; // B_{i+1} m[j * cols + i1] = -length_v * tension[i].v * tension[i1].v * tension[i1].v * (1 - 3 * tension[i2].u); // C_{i+1} m[j * cols + j] = length_v_next * tension[i2].u * tension[i1].u * tension[i1].u * (1 - 3 * tension[i].v); // D_{i+2} m[j * cols + j1] = -length_v * tension[i].v * tension[i1].v * tension[i1].v; v_prev = v; v = v_next; length_v = length_v_next; delta_prev = delta; } gauss_jordan_elimination(m, pivots, rows, cols); // NOTE: re-use the first row of m to temporarily hold the angles double* theta = m; double* phi = theta + count; for (uint64_t r = 0; r < count; r++) { theta[r] = m[pivots[r] * cols + rows]; phi[r] = m[pivots[count + r] * cols + rows]; } Vec2* cta = points + 1; Vec2* ctb = points + 2; v = points[3] - points[0]; Vec2 w = cplx_from_angle(theta[0] + v.angle()); for (uint64_t i = 0; i < count; i++, cta += 3, ctb += 3) { const uint64_t i1 = i == count - 1 ? 0 : i + 1; const uint64_t i2 = i < count - 2 ? i + 2 : (i == count - 2 ? 0 : 1); const double st = sin(theta[i]); const double ct = cos(theta[i]); const double sp = sin(phi[i]); const double cp = cos(phi[i]); const double alpha = A * (st - B * sp) * (sp - B * st) * (ct - cp); const Vec2 v_next = points[3 * i2] - points[3 * i1]; const double _length_v = v.length(); const double delta_next = v_next.angle(); const Vec2 w_next = cplx_from_angle(theta[i1] + delta_next); *cta = points[3 * i] + w * _length_v * ((2 + alpha) / (1 + (1 - C) * ct + C * cp)) / (3 * tension[i].v); *ctb = points[3 * i1] - w_next * _length_v * ((2 - alpha) / (1 + (1 - C) * cp + C * ct)) / (3 * tension[i1].u); v = v_next; w = w_next; } free_allocation(m); free_allocation(pivots); return; } // Cycle, but with angle constraint. // Rotate inputs and add append last point to cycle, // then use open curve solver. points_size++; pts = (Vec2*)allocate(sizeof(Vec2) * 3 * points_size); memcpy(pts, points + 3 * rotate, sizeof(Vec2) * 3 * (count - rotate)); memcpy(pts + 3 * (count - rotate), points, sizeof(Vec2) * 3 * (rotate + 1)); tens = (Vec2*)allocate(sizeof(Vec2) * points_size); memcpy(tens, tension + rotate, sizeof(Vec2) * (count - rotate)); memcpy(tens + count - rotate, tension, sizeof(Vec2) * (rotate + 1)); ang = (double*)allocate(sizeof(double) * points_size); memcpy(ang, angles + rotate, sizeof(double) * (count - rotate)); memcpy(ang + count - rotate, angles, sizeof(double) * (rotate + 1)); ang_c = (bool*)allocate(sizeof(bool) * points_size); memcpy(ang_c, angle_constraints + rotate, sizeof(bool) * (count - rotate)); memcpy(ang_c + count - rotate, angle_constraints, sizeof(bool) * (rotate + 1)); } { // Open curve solver const uint64_t n = points_size - 1; double* theta = (double*)allocate(sizeof(double) * n); double* phi = (double*)allocate(sizeof(double) * n); if (ang_c[0]) theta[0] = ang[0] - (pts[3] - pts[0]).angle(); uint64_t i = 0; while (i < n) { uint64_t j = i + 1; while (j < n + 1 && !ang_c[j]) j++; if (j == n + 1) j--; else { phi[j - 1] = (pts[3 * j] - pts[3 * (j - 1)]).angle() - ang[j]; if (j < n) theta[j] = ang[j] - (pts[3 * (j + 1)] - pts[3 * j]).angle(); } // Solve curve pts[i] thru pts[j] const uint64_t range = j - i; const uint64_t rows = 2 * range; const uint64_t cols = rows + 1; memset(m, 0, sizeof(double) * rows * cols); Vec2 v_prev = pts[3 * (i + 1)] - pts[3 * i]; double delta_prev = v_prev.angle(); double length_v_prev = v_prev.length(); for (uint64_t k = 0; k < range - 1; k++) { // [0; range - 2] const uint64_t k1 = k + 1; // [1; range - 1] const uint64_t i0 = i + k; // [i; j - 2] const uint64_t i1 = i0 + 1; // [i + 1; j - 1] const uint64_t i2 = i0 + 2; // [i + 2; j] const uint64_t l = k + range; // [range; 2 * range - 2] const uint64_t l1 = l + 1; // [range + 1; range - 1] Vec2 v = pts[3 * i2] - pts[3 * i1]; const double delta = v.angle(); const double length_v = v.length(); double psi = delta - delta_prev; while (psi <= -M_PI) psi += 2 * M_PI; while (psi > M_PI) psi -= 2 * M_PI; m[k1 * cols + rows] = -psi; m[k1 * cols + k1] = 1; m[k1 * cols + l] = 1; // A_k m[l * cols + k] = length_v * tens[i2].u * tens[i1].u * tens[i1].u; // B_{k+1} m[l * cols + k1] = -length_v_prev * tens[i0].v * tens[i1].v * tens[i1].v * (1 - 3 * tens[i2].u); // C_{k+1} m[l * cols + l] = length_v * tens[i2].u * tens[i1].u * tens[i1].u * (1 - 3 * tens[i0].v); // D_{k+2} m[l * cols + l1] = -length_v_prev * tens[i0].v * tens[i1].v * tens[i1].v; delta_prev = delta; length_v_prev = length_v; } if (ang_c[i]) { m[0 * cols + rows] = theta[i]; // B_0 m[0] = 1; // D_1 // m[0 * cols + range] = 0; } else { const double to3 = tens[0].v * tens[0].v * tens[0].v; const double cti3 = initial_curl * tens[1].u * tens[1].u * tens[1].u; // B_0 m[0] = to3 * (1 - 3 * tens[1].u) - cti3; // D_1 m[0 * cols + range] = to3 - cti3 * (1 - 3 * tens[0].v); } if (ang_c[j]) { m[(rows - 1) * cols + rows] = phi[j - 1]; // A_{range-1} // m[(rows - 1) * cols + (range - 1)] = 0; // C_range m[(rows - 1) * cols + (rows - 1)] = 1; } else { const double ti3 = tens[n].u * tens[n].u * tens[n].u; const double cto3 = final_curl * tens[n - 1].v * tens[n - 1].v * tens[n - 1].v; // A_{range-1} m[(rows - 1) * cols + (range - 1)] = ti3 - cto3 * (1 - 3 * tens[n].u); // C_range m[(rows - 1) * cols + (rows - 1)] = ti3 * (1 - 3 * tens[n - 1].v) - cto3; } if (range > 1 || !ang_c[i] || !ang_c[j]) { // printf("Solving range [%" PRIu64 ", %" PRIu64 "]\n\n", i, j); // print_matrix(m, rows, cols); gauss_jordan_elimination(m, pivots, rows, cols); for (uint64_t r = 0; r < range; r++) { theta[i + r] = m[pivots[r] * cols + rows]; phi[i + r] = m[pivots[range + r] * cols + rows]; } // printf("\n"); // print_matrix(m, rows, cols); // printf("\n"); } i = j; } Vec2 v = pts[3] - pts[0]; Vec2 w = cplx_from_angle(theta[0] + v.angle()); for (uint64_t ii = 0; ii < n; ii++) { const uint64_t i1 = ii + 1; const uint64_t i2 = ii == n - 1 ? 0 : ii + 2; const uint64_t ci = ii + rotate >= count ? ii + rotate - count : ii + rotate; const double st = sin(theta[ii]); const double ct = cos(theta[ii]); const double sp = sin(phi[ii]); const double cp = cos(phi[ii]); const double alpha = A * (st - B * sp) * (sp - B * st) * (ct - cp); const Vec2 v_next = pts[3 * i2] - pts[3 * i1]; const double length_v = v.length(); const Vec2 w_next = ii == n - 1 ? cplx_from_angle(v.angle() - phi[n - 1]) : cplx_from_angle(theta[i1] + v_next.angle()); points[3 * ci + 1] = pts[3 * ii] + w * length_v * ((2 + alpha) / (1 + (1 - C) * ct + C * cp)) / (3 * tens[ii].v); points[3 * ci + 2] = pts[3 * i1] - w_next * length_v * ((2 - alpha) / (1 + (1 - C) * cp + C * ct)) / (3 * tens[i1].u); v = v_next; w = w_next; } if (cycle) { free_allocation(pts); free_allocation(tens); free_allocation(ang); free_allocation(ang_c); } free_allocation(theta); free_allocation(phi); } free_allocation(m); free_allocation(pivots); } void convex_hull(const Array<Vec2> points, Array<Vec2>& result) { if (points.count < 4) { result.extend(points); return; } else if (points.count > INT_MAX) { Array<Vec2> partial; partial.count = INT_MAX - 1; partial.items = points.items; Array<Vec2> temp = {0}; convex_hull(partial, temp); partial.count = points.count - (INT_MAX - 1); partial.items = points.items + (INT_MAX - 1); temp.extend(partial); convex_hull(temp, result); temp.clear(); return; } qhT qh; QHULL_LIB_CHECK; qh_zero(&qh, stderr); char command[256] = "qhull"; int exitcode = qh_new_qhull(&qh, 2, (int)points.count, (double*)points.items, false, command, NULL, stderr); if (exitcode == 0) { result.ensure_slots(qh.num_facets); Vec2* point = result.items + result.count; result.count += qh.num_facets; vertexT* qh_vertex = NULL; facetT* qh_facet = qh_nextfacet2d(qh.facet_list, &qh_vertex); for (int64_t i = qh.num_facets; i > 0; i--, point++) { point->x = qh_vertex->point[0]; point->y = qh_vertex->point[1]; qh_facet = qh_nextfacet2d(qh_facet, &qh_vertex); } } else if (exitcode == qh_ERRsingular) { // QHull errors for singular input (collinear points in 2D) Vec2 min = {DBL_MAX, DBL_MAX}; Vec2 max = {-DBL_MAX, -DBL_MAX}; Vec2* p = points.items; for (uint64_t num = points.count; num > 0; num--, p++) { if (p->x < min.x) min.x = p->x; if (p->x > max.x) max.x = p->x; if (p->y < min.y) min.y = p->y; if (p->y > max.y) max.y = p->y; } if (min.x < max.x) { result.append(min); result.append(max); } } else { // The least we can do result.extend(points); } #ifdef qh_NOmem qh_freeqhull(&qh, qh_ALL); #else int curlong, totlong; qh_freeqhull(&qh, !qh_ALL); /* free long memory */ qh_memfreeshort(&qh, &curlong, &totlong); /* free short memory and memory allocator */ if (curlong || totlong) { fprintf( stderr, "[GDSTK] Qhull internal warning: did not free %d bytes of long memory (%d pieces)\n", totlong, curlong); } #endif } char* double_print(double value, uint32_t precision, char* buffer, size_t buffer_size) { uint64_t len = snprintf(buffer, buffer_size, "%.*f", precision, value); if (precision) { while (buffer[--len] == '0') ; if (buffer[len] != '.') len++; buffer[len] = 0; } return buffer; } tm* get_now(tm& result) { time_t t = time(NULL); #ifdef _WIN32 localtime_s(&result, &t); #else localtime_r(&t, &result); #endif return &result; } // Kenneth Kelly's 22 colors of maximum contrast (minus B/W: "F2F3F4", "222222") const char* colors[] = {"F3C300", "875692", "F38400", "A1CAF1", "BE0032", "C2B280", "848482", "008856", "E68FAC", "0067A5", "F99379", "604E97", "F6A600", "B3446C", "DCD300", "882D17", "8DB600", "654522", "E25822", "2B3D26"}; inline static const char* default_color(Tag tag) { return colors[(2 + get_layer(tag) + get_type(tag) * 13) % COUNT(colors)]; } const char* default_svg_shape_style(Tag tag) { static char buffer[] = "stroke: #XXXXXX; fill: #XXXXXX; fill-opacity: 0.5;"; const char* c = default_color(tag); memcpy(buffer + 9, c, 6); memcpy(buffer + 24, c, 6); return buffer; } const char* default_svg_label_style(Tag tag) { static char buffer[] = "stroke: none; fill: #XXXXXX;"; const char* c = default_color(tag); memcpy(buffer + 21, c, 6); return buffer; } } // namespace gdstk
36.007429
100
0.48566
dangerdevices
ac5ddef4331a6936289da6c40d87dc448eaf254e
2,985
cpp
C++
traffic_count_hw_design/fromFrameToBlobCount.cpp
necst/fard
ce9078a50235f3a519ef4b2ce7a0e87f1de794e4
[ "Apache-2.0" ]
3
2019-07-09T08:03:22.000Z
2019-12-03T14:26:16.000Z
traffic_count_hw_design/fromFrameToBlobCount.cpp
necst/fard
ce9078a50235f3a519ef4b2ce7a0e87f1de794e4
[ "Apache-2.0" ]
1
2021-07-16T17:58:18.000Z
2021-07-16T17:58:18.000Z
traffic_count_hw_design/fromFrameToBlobCount.cpp
necst/fard
ce9078a50235f3a519ef4b2ce7a0e87f1de794e4
[ "Apache-2.0" ]
null
null
null
#include <stdio.h> #include <stdlib.h> #include "fromFrameToBlobCount.h" //Images unsigned char background[WIDTH*HEIGHT*DEPTH], input[WIDTH*HEIGHT*DEPTH]; unsigned char input_grey[WIDTH*HEIGHT]; unsigned char foreground[WIDTH*HEIGHT], foreground_clean[WIDTH*HEIGHT]; void fromFrameToBlobCount(UIntStream &streamIn, UIntStream &streamOut, int action, int md_threshold, int erosion_iteration, int dilate_iteration, int second_erosion_iteration) { unsigned int width = WIDTH; unsigned int height = HEIGHT; #pragma HLS INTERFACE axis register port=streamIn #pragma HLS INTERFACE axis register port=streamOut #pragma HLS INTERFACE s_axilite register port=action bundle=control #pragma HLS INTERFACE s_axilite register port=width bundle=control #pragma HLS INTERFACE s_axilite register port=height bundle=control #pragma HLS INTERFACE s_axilite register port=md_threshold bundle=control #pragma HLS INTERFACE s_axilite register port=erosion_iteration bundle=control #pragma HLS INTERFACE s_axilite register port=dilate_iteration bundle=control #pragma HLS INTERFACE s_axilite register port=second_erosion_iteration bundle=control #pragma HLS INTERFACE s_axilite register port=return bundle=control //DMA auxintData int intData, numOfInt; int mask = 0xFF; //Aux unsigned int i, j, k, count, blobs; numOfInt = (WIDTH*HEIGHT*DEPTH)/4; if (action == LOAD) { /*Load background*/ for(i = 0; i < numOfInt; i++) { #pragma HLS PIPELINE II=1 intData = streamPop < int, UIntAxis, UIntStream > (streamIn); ((int *)background)[i] = intData; } rgb2grey(background, background); } else if (action == PROCESS) { /*Load frame*/ numOfInt = (WIDTH*HEIGHT*DEPTH)/4; for(i = 0; i < numOfInt; i++) { #pragma HLS PIPELINE II=1 intData = streamPop < int, UIntAxis, UIntStream > (streamIn); ((int *)input)[i] = intData; } /*Image processing*/ //Grey scale conversion rgb2grey(input, input_grey); //Foreground extraction foregroundExtraction(input_grey, background, foreground, md_threshold); //Erosion filter for(i = 0; i < erosion_iteration; i++) { erode_filter<180,180,3>(foreground, foreground_clean); copy(foreground_clean, foreground); } //Dilation filter for(i = 0; i < dilate_iteration; i++) { dilate(foreground, foreground_clean); copy(foreground_clean, foreground); } //second erosion filter for(i = 0; i < second_erosion_iteration; i++) { erode_filter<180,180,3>(foreground, foreground_clean); copy(foreground_clean, foreground); } //Clean borders cleanBorders(foreground_clean); //Blobs count count = blobsCount(foreground_clean); streamPush < unsigned int, UIntAxis, UIntStream > (count, 1, streamOut, BIT_WIDTH); } }
31.09375
175
0.676047
necst
ac5e1706224622eb8bbd928ba02326fa6394a112
1,282
hh
C++
src/test/resources/samples/langs/Hack/HomeController.hh
JavascriptID/sourcerer-app
9ad05f7c6a18c03793c8b0295a2cb318118f6245
[ "MIT" ]
8,271
2015-01-01T15:04:43.000Z
2022-03-31T06:18:14.000Z
src/test/resources/samples/langs/Hack/HomeController.hh
JavascriptID/sourcerer-app
9ad05f7c6a18c03793c8b0295a2cb318118f6245
[ "MIT" ]
3,238
2015-01-01T14:25:12.000Z
2022-03-30T17:37:51.000Z
src/test/resources/samples/langs/Hack/HomeController.hh
JavascriptID/sourcerer-app
9ad05f7c6a18c03793c8b0295a2cb318118f6245
[ "MIT" ]
4,070
2015-01-01T11:40:51.000Z
2022-03-31T13:45:53.000Z
<?hh // strict /** * Copyright (c) 2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ require_once $_SERVER['DOCUMENT_ROOT'].'/core/controller/init.php'; require_once $_SERVER['DOCUMENT_ROOT'].'/core/controller/standard-page/init.php'; require_once $_SERVER['DOCUMENT_ROOT'].'/vendor/hhvm/xhp/src/init.php'; class HomeController extends GetController { use StandardPage; protected function getTitle(): string { return 'Hack Cookbook'; } protected function renderMainColumn(): :xhp { return <div> <h1>Cookbook</h1> <p> The Hack Cookbook helps you write Hack code by giving you examples of Hack code. It is written in Hack and is open source. If you <a href="http://github.com/facebook/hack-example-site"> head over to GitHub, </a> you can read the code, check out the repository, and run it yourself. The recipes in this cookbook are small examples that illustrate how to use Hack to solve common and interesting problems. </p> </div>; } }
32.871795
81
0.686427
JavascriptID
ac5e933da290a583caceecbddee618722d84403a
2,215
cc
C++
poj/1/1540.cc
eagletmt/procon
adbe503eb3c1bbcc1538b2ee8988aa353937e8d4
[ "MIT" ]
1
2015-04-17T09:54:23.000Z
2015-04-17T09:54:23.000Z
poj/1/1540.cc
eagletmt/procon
adbe503eb3c1bbcc1538b2ee8988aa353937e8d4
[ "MIT" ]
null
null
null
poj/1/1540.cc
eagletmt/procon
adbe503eb3c1bbcc1538b2ee8988aa353937e8d4
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> #include <map> using namespace std; struct edge { string word, output; int to; }; void do_output(const string& out, char c) { if (out == "\b") { cout << c; } else { cout << out; } } void operate(const vector<vector<edge> >& g) { int n = 1; // START while (n != 0) { int c = cin.get(); int def_to = -1; string def_out; for (vector<edge>::const_iterator it = g[n].begin(); it != g[n].end(); ++it) { if (it->word == "\b") { def_to = it->to; def_out = it->output; } else if (it->word.find(c) != string::npos) { n = it->to; do_output(it->output, c); goto NEXT; } } if (def_to == -1) { throw "incorrect"; } n = def_to; do_output(def_out, c); NEXT: ; } } void normalize(string& s) { for (string::iterator it = s.begin(); it != s.end(); ++it) { if (*it == '\\') { it = s.erase(it); switch (*it) { case 'b': *it = ' '; break; case 'n': *it = '\n'; break; case '\\': break; case '0': s = ""; return; case 'c': s = "\b"; return; default: throw "unknown sequence"; } } } } int main() { int N; for (int Ti = 1; cin >> N && N != 0; Ti++) { map<string,int> d; d["END"] = 0; d["START"] = 1; vector<vector<edge> >g(2); for (int i = 0; i < N; i++) { string name; int M; cin >> name >> M; int u; if (d.count(name)) { u = d[name]; } else { u = d[name] = g.size(); g.push_back(vector<edge>()); } for (int j = 0; j < M; j++) { edge e; string label; cin >> e.word >> label >> e.output; normalize(e.word); normalize(e.output); if (d.count(label)) { e.to = d[label]; } else { e.to = d[label] = g.size(); g.push_back(vector<edge>()); } g[u].push_back(e); } } int c = cin.get(); while (c != '\n') { c = cin.get(); } cout << "Finite State Machine " << Ti << ":" << endl; operate(g); } return 0; }
19.429825
82
0.428442
eagletmt
ac5fcec114a163f12d822091aba08574cff84eba
2,383
cpp
C++
Game/UI_Element_Slider.cpp
Chr157i4n/OpenGL_Space_Game
b4cd4ab65385337c37f26af641597c5fc9126f04
[ "MIT" ]
3
2020-08-05T00:02:30.000Z
2021-08-23T00:41:24.000Z
Game/UI_Element_Slider.cpp
Chr157i4n/OpenGL_Space_Game
b4cd4ab65385337c37f26af641597c5fc9126f04
[ "MIT" ]
null
null
null
Game/UI_Element_Slider.cpp
Chr157i4n/OpenGL_Space_Game
b4cd4ab65385337c37f26af641597c5fc9126f04
[ "MIT" ]
2
2021-07-03T19:32:08.000Z
2021-08-19T18:48:52.000Z
#include "UI_Element_Slider.h" #include "Game.h" UI_Element_Slider::UI_Element_Slider(int x, int y, int w, int h, uint64 lifespan, std::string label, glm::vec4 foreColor, glm::vec4 backColor, bool isDebugInfo) : UI_Element(x, y, w, h, lifespan, foreColor, backColor, isDebugInfo) { this->label = label; labelOffsetX = 0; labelOffsetY = h/2; } void UI_Element_Slider::drawUI_Element() { float _x = x; float _y = y; float _w = w; float _h = h; float barThickness = 0.01; float SliderThickness = 0.04; float _value = (value - minValue) / (maxValue - minValue); _x /= Game::getWindowWidth(); _y /= Game::getWindowHeight(); _w /= Game::getWindowWidth(); _h /= Game::getWindowHeight(); _x = _x * 2 - 1; _y = _y * 2 - 1; _w = _w * 2; _h = _h * 2; if (isSelected) { backColor.a = 1; } else { backColor.a = 0.4; } //background glColor4f(backColor.r, backColor.g, backColor.b, backColor.a); glBegin(GL_QUADS); glVertex2f(_x , _y + 0.25*_h - barThickness); glVertex2f(_x + _w, _y + 0.25*_h - barThickness); glVertex2f(_x + _w, _y + 0.25*_h); glVertex2f(_x, _y + 0.25*_h); glEnd(); //Slider glColor4f(foreColor.r, foreColor.g, foreColor.b, 1); glBegin(GL_QUADS); glVertex2f(_x + _value * _w - SliderThickness / 2, _y + 0.25 * _h - SliderThickness / 2); //left bottom glVertex2f(_x + _value * _w + SliderThickness / 2, _y + 0.25 * _h - SliderThickness / 2); //right bottom glVertex2f(_x + _value * _w + SliderThickness / 2, _y + 0.25 * _h + SliderThickness / 2); //right top glVertex2f(_x + _value * _w - SliderThickness / 2, _y + 0.25 * _h + SliderThickness / 2); //left top glEnd(); UI::drawString(x + labelOffsetX, y+labelOffsetY, label, foreColor); } int UI_Element_Slider::onMouseDrag(float mouseX, float mouseY, SDL_MouseButtonEvent* buttonEvent) { float newValue = (mouseX - this->getX()) / this->getW(); if (newValue < 0.05) newValue = 0; if (newValue > 0.95) newValue = 1; newValue = newValue * (maxValue - minValue) + minValue; this->setValue(newValue); return this->callCallBack(); } int UI_Element_Slider::increase() { this->setValue(this->getValue() + 1 * (maxValue - minValue) * 0.5 * Game::getDelta()/1000); return this->callCallBack(); } int UI_Element_Slider::decrease() { this->setValue(this->getValue() - 1 * (maxValue - minValue) * 0.5 * Game::getDelta()/1000); return this->callCallBack(); }
27.390805
230
0.664289
Chr157i4n
ac60947c206cb6be3969c04c3c524a5d8698d7c6
753
cpp
C++
codeforces/1392B.cpp
sgrade/cpptest
84ade6ec03ea394d4a4489c7559d12b4799c0b62
[ "MIT" ]
null
null
null
codeforces/1392B.cpp
sgrade/cpptest
84ade6ec03ea394d4a4489c7559d12b4799c0b62
[ "MIT" ]
null
null
null
codeforces/1392B.cpp
sgrade/cpptest
84ade6ec03ea394d4a4489c7559d12b4799c0b62
[ "MIT" ]
null
null
null
// B. Omkar and Infinity Clock #include <iostream> #include <vector> #include <algorithm> using namespace std; int main(){ int t; cin >> t; while(t--){ int n; unsigned long long k; cin >> n >> k; vector<int> v(n); for (int i=0; i<n; ++i){ cin >> v[i]; } unsigned long long operations = 1; if (k>1) { operations = k%2 != 0 ? 3 : 2; } while (operations--){ int vMax = *max_element(v.begin(), v.end()) ; for (int i = 0; i<n; ++i){ v[i] = vMax - v[i]; } } for (auto it: v){ cout << it << ' '; } cout << endl; } return 0; }
16.733333
57
0.393094
sgrade
ac63cbc6bfe1c0fa5008a3241dcbd4d707479905
11,982
hpp
C++
include/ModernDD/NodeBddReducer.hpp
DanielKowalczyk1984/Decision-Diagrams-in-Modern-C
0d04e1e31316281ab20c559a37fdc14a881fecb5
[ "Unlicense" ]
null
null
null
include/ModernDD/NodeBddReducer.hpp
DanielKowalczyk1984/Decision-Diagrams-in-Modern-C
0d04e1e31316281ab20c559a37fdc14a881fecb5
[ "Unlicense" ]
null
null
null
include/ModernDD/NodeBddReducer.hpp
DanielKowalczyk1984/Decision-Diagrams-in-Modern-C
0d04e1e31316281ab20c559a37fdc14a881fecb5
[ "Unlicense" ]
null
null
null
#ifndef NODE_BDD_REDUCER_HPP #define NODE_BDD_REDUCER_HPP #include <cassert> // for assert #include <cstddef> // for size_t #include <ext/alloc_traits.h> // for __alloc_traits<>::value_type #include <memory> // for allocator_traits<>::value_type #include <range/v3/view/enumerate.hpp> #include <range/v3/view/reverse.hpp> #include <span> // for span #include <unordered_set> // for unordered_set #include <vector> // for vector #include "NodeBddTable.hpp" // for TableHandler, NodeTableEntity #include "NodeId.hpp" // for NodeId #include "util/MyHashTable.hpp" // for MyHashDefault template <typename T, bool BDD, bool ZDD> class DdReducer { TableHandler<T> oldDiagram; NodeTableEntity<T>& input; TableHandler<T> newDiagram; NodeTableEntity<T>& output; std::vector<std::vector<NodeId>> newIdTable; std::vector<std::vector<NodeId*>> rootPtr; size_t counter = 1; bool readyForSequentialReduction; public: explicit DdReducer(TableHandler<T>& diagram, bool useMP = false) : oldDiagram(std::move(diagram)), input(*oldDiagram), newDiagram(input.numRows()), output(*newDiagram), newIdTable(input.numRows()), rootPtr(input.numRows()), readyForSequentialReduction(false) { diagram = std::move(newDiagram); input.initTerminals(); input.makeIndex(useMP); newIdTable[0].resize(2); newIdTable[0][0] = 0; newIdTable[0][1] = 1; } private: /** * Applies the node deletion rules. * It is required before serial reduction (Algorithm-R) * in order to make lower-level index safe. */ void makeReadyForSequentialReduction() { if (readyForSequentialReduction) { return; } for (auto i = 2UL; i < input.numRows(); ++i) { // size_t const m = input[i].size(); // std::span const tt{input[i].data(), input[i].size()}; // T* const tt = input[i].data(); for (auto& it : input[i]) { for (auto& f : it) { // NodeId& f = it[b]; if (f.row() == 0) { continue; } NodeId f0 = input.child(f, 0); NodeId deletable = 0; bool del = true; for (size_t bb = ZDD ? 1UL : 0UL; bb < 2; ++bb) { if (input.child(f, bb) != deletable) { del = false; } } if (del) { f = f0; } } } } input.makeIndex(); readyForSequentialReduction = true; } public: /** * Sets a root node. * @param root reference to a root node ID storage. */ void setRoot(NodeId& root) { rootPtr[root.row()].push_back(&root); } /** * Reduces one level. * @param i level. * @param useMP use an algorithm for multiple processors. */ void reduce(size_t i) { if (BDD) { algorithmZdd(i); } else if (ZDD) { algorithmR(i); } } private: /** * Reduces one level using Algorithm-R. * @param i level. */ void algorithmR(size_t i) { makeReadyForSequentialReduction(); size_t const m = input[i].size(); // T* const tt = input[i].data(); std::vector<NodeId>& newId = newIdTable[i]; newId.resize(m); // for (size_t j = m - 1; j + 1 > 0; --j) { for (auto&& [j, f] : input[i] | ranges::views::enumerate | ranges::views::reverse) { auto& f0 = f[0]; auto& f1 = f[1]; if (f0.row() != 0) { f0 = newIdTable[f0.row()][f0.col()]; } if (f1.row() != 0) { f1 = newIdTable[f1.row()][f1.col()]; } if (ZDD && f1 == 0) { newId[j] = f0; } else { newId[j] = NodeId(counter + 1, m); // tail of f0-equivalent list } } { auto const& levels = input.lowerLevels(counter); for (auto& t : levels) { newIdTable[t].clear(); } } size_t mm = 0; for (size_t j = 0; j < m; ++j) { assert(newId[j].row() <= counter + 1); if (newId[j].row() <= counter) { continue; } auto& g0 = input[i][j][0]; assert(newId[j].row() == counter + 1); newId[j] = NodeId(counter, mm++, g0.hasEmpty()); } auto const& levels = input.lowerLevels(counter); for (const auto& t : levels) { input[t].clear(); } if (mm > 0U) { output.initRow(counter, mm); std::span<T> nt{output[counter].data(), output[counter].size()}; for (size_t j = 0; j < m; ++j) { // NodeId const& f0 = tt[j].branch[0]; auto const& f1 = input[i][j][1]; if (ZDD && f1 == 0) { // forwarded assert(newId[j].row() < counter); } else { assert(newId[j].row() == counter); auto k = newId[j].col(); nt[k] = input[i][j]; nt[k].set_node_id_label(newId[j]); if (nt[k].get_ptr_node_id() != 0) { nt[k].set_ptr_node_id(newId[j]); } } } counter++; } for (auto& k : rootPtr[i]) { NodeId& root = *k; root = newId[root.col()]; } } /** * Reduces one level using Algorithm-R. * @param i level. */ void algorithmZdd(size_t i) { makeReadyForSequentialReduction(); size_t const m = input[i].size(); std::span<T> const tt{input[i].data(), input[i].size()}; NodeId const mark(i, m); auto& newId = newIdTable[i]; newId.resize(m); for (size_t j = m - 1; j + 1 > 0; --j) { auto& f0 = tt[j][0]; auto& f1 = tt[j][1]; if (f0.row() != 0) { f0 = newIdTable[f0.row()][f0.col()]; } if (f1.row() != 0) { f1 = newIdTable[f1.row()][f1.col()]; } if (ZDD && f1 == 0) { newId[j] = f0; } else { auto& f00 = input.child(f0, 0UL); auto& f01 = input.child(f0, 1UL); if (f01 != mark) { // the first touch from this level f01 = mark; // mark f0 as touched newId[j] = NodeId(i + 1, m); // tail of f0-equivalent list } else { newId[j] = f00; // next of f0-equivalent list } f00 = NodeId(i + 1, j); // new head of f0-equivalent list } } { auto const& levels = input.lowerLevels(i); for (auto& t : levels) { newIdTable[t].clear(); } } size_t mm = 0; for (auto j = 0UL; j < m; ++j) { NodeId const f(i, j); assert(newId[j].row() <= i + 1); if (newId[j].row() <= i) { continue; } for (auto k = j; k < m;) { // for each g in f0-equivalent list assert(j <= k); NodeId const g(i, k); auto& g0 = tt[k][0]; auto& g1 = tt[k][1]; auto& g10 = input.child(g1, 0); auto& g11 = input.child(g1, 1); assert(g1 != mark); assert(newId[k].row() == i + 1); auto next = newId[k].col(); if (g11 != f) { // the first touch to g1 in f0-equivalent list g11 = f; // mark g1 as touched g10 = g; // record g as a canonical node for <f0,g1> newId[k] = NodeId(i, mm++, g0.hasEmpty()); } else { g0 = g10; // make a forward link g1 = mark; // mark g as forwarded newId[k] = 0; } k = next; } } auto const& levels = input.lowerLevels(i); for (auto& t : levels) { input[t].clear(); } if (mm > 0U) { output.initRow(i, mm); std::span<T> nt{output[i].data(), output[i].size()}; for (size_t j = 0; j < m; ++j) { auto const& f0 = tt[j][0]; auto const& f1 = tt[j][1]; if (f1 == mark) { // forwarded assert(f0.row() == i); assert(newId[j] == 0); newId[j] = newId[f0.col()]; } else if (ZDD && f1 == 0) { // forwarded assert(newId[j].row() < i); } else { assert(newId[j].row() == i); auto k = newId[j].col(); nt[k] = tt[j]; nt[k].set_node_id_label(newId[j]); } } counter++; } for (auto& k : rootPtr[i]) { auto& root = *k; root = newId[root.col()]; } } /** * Reduces one level. * @param i level. */ void reduce_(int i) { auto const m = input[i].size(); newIdTable[i].resize(m); auto jj = 0UL; { std::unordered_set<T const*> uniq(m * 2, MyHashDefault<T const*>(), MyHashDefault<T const*>()); for (auto j = 0UL; j < m; ++j) { auto* const p0 = input[i].data(); auto& f = input[i][j]; // make f canonical auto& f0 = f[0]; f0 = newIdTable[f0.row()][f0.col()]; auto deletable = BDD ? f0 : 0; auto del = BDD || ZDD || (f0 == 0); for (int b = 1; b < 2; ++b) { NodeId& ff = f[b]; ff = newIdTable[ff.row()][ff.col()]; if (ff != deletable) { del = false; } } if (del) { // f is redundant newIdTable[i][j] = f0; } else { auto const* pp = uniq.add(&f); if (pp == &f) { newIdTable[i][j] = NodeId(i, jj++, f0.hasEmpty()); } else { newIdTable[i][j] = newIdTable[i][pp - p0]; } } } } std::vector<int> const& levels = input.lowerLevels(i); for (const auto& t : levels) { newIdTable[t].clear(); } output.initRow(i, jj); for (auto j = 0UL; j < m; ++j) { auto const& ff = newIdTable[i][j]; if (ff.row() == i) { output[i][ff.col()] = input[i][j]; output[i][ff.col()].child[0] = &(output.node(output[i][ff.col()][0])); output[i][ff.col()].child[1] = &(output.node(output[i][ff.col()][1])); } } input[i].clear(); for (auto k = 0UL; k < rootPtr[i].size(); ++k) { NodeId& root = *rootPtr[i][k]; root = newIdTable[i][root.col()]; } } }; #endif // NODE_BDD_REDUCER_HPP
30.881443
79
0.408363
DanielKowalczyk1984
ac6b85c1faf5fc4c0540d0babded351d39970599
19,405
cpp
C++
src/kits/storage/NodeInfo.cpp
stasinek/BHAPI
5d9aa61665ae2cc5c6e34415957d49a769325b2b
[ "BSD-3-Clause", "MIT" ]
3
2018-05-21T15:32:32.000Z
2019-03-21T13:34:55.000Z
src/kits/storage/NodeInfo.cpp
stasinek/BHAPI
5d9aa61665ae2cc5c6e34415957d49a769325b2b
[ "BSD-3-Clause", "MIT" ]
null
null
null
src/kits/storage/NodeInfo.cpp
stasinek/BHAPI
5d9aa61665ae2cc5c6e34415957d49a769325b2b
[ "BSD-3-Clause", "MIT" ]
null
null
null
/* * Copyright 2002-2010 Haiku, Inc. All rights reserved. * Distributed under the terms of the MIT License. * * Authors: * Ingo Weinhold, bonefish@users.sf.net * Axel Dörfler, axeld@pinc-software.de */ //----------------------------------------------------------------------------- #include <NodeInfo.h> //----------------------------------------------------------------------------- #include <MimeTypes.h> #include <Bitmap.h> #include <Entry.h> #include <IconUtils.h> #include <Node.h> #include <Path.h> #include <Rect.h> //----------------------------------------------------------------------------- #include <fs_attr.h> #include <fs_info.h> #include <new> //----------------------------------------------------------------------------- using namespace std; using namespace bhapi; //----------------------------------------------------------------------------- // attribute names #define NI_BEOS "BEOS" static const char* kNITypeAttribute = NI_BEOS ":TYPE"; static const char* kNIPreferredAppAttribute = NI_BEOS ":PREF_APP"; static const char* kNIAppHintAttribute = NI_BEOS ":PPATH"; static const char* kNIMiniIconAttribute = NI_BEOS ":M:STD_ICON"; static const char* kNILargeIconAttribute = NI_BEOS ":L:STD_ICON"; static const char* kNIIconAttribute = NI_BEOS ":ICON"; // #pragma mark - BNodeInfo //----------------------------------------------------------------------------- BNodeInfo::BNodeInfo() : fNode(NULL), fCStatus(B_NO_INIT) { } //----------------------------------------------------------------------------- BNodeInfo::BNodeInfo(BNode* node) : fNode(NULL), fCStatus(B_NO_INIT) { fCStatus = SetTo(node); } //----------------------------------------------------------------------------- BNodeInfo::~BNodeInfo() { } //----------------------------------------------------------------------------- status_t BNodeInfo::SetTo(BNode* node) { fNode = NULL; // check parameter fCStatus = (node && node->InitCheck() == B_OK ? B_OK : B_BAD_VALUE); if (fCStatus == B_OK) fNode = node; return fCStatus; } //----------------------------------------------------------------------------- status_t BNodeInfo::InitCheck() const { return fCStatus; } //----------------------------------------------------------------------------- status_t BNodeInfo::GetType(char* type) const { // check parameter and initialization status_t result = (type ? B_OK : B_BAD_VALUE); if (result == B_OK && InitCheck() != B_OK) result = B_NO_INIT; // get the attribute info and check type and length of the attr contents attr_info attrInfo; if (result == B_OK) result = fNode->GetAttrInfo(kNITypeAttribute, &attrInfo); if (result == B_OK && attrInfo.type != B_MIME_STRING_TYPE) result = B_BAD_TYPE; if (result == B_OK && attrInfo.size > B_MIME_TYPE_LENGTH) result = B_BAD_DATA; // read the data if (result == B_OK) { ssize_t read = fNode->ReadAttr(kNITypeAttribute, attrInfo.type, 0, type, attrInfo.size); if (read < 0) result = read; else if (read != attrInfo.size) result = B_ERROR; if (result == B_OK) { // attribute strings doesn't have to be null terminated type[min_c(attrInfo.size, B_MIME_TYPE_LENGTH - 1)] = '\0'; } } return result; } //----------------------------------------------------------------------------- status_t BNodeInfo::SetType(const char* type) { // check parameter and initialization status_t result = B_OK; if (result == B_OK && type && strlen(type) >= B_MIME_TYPE_LENGTH) result = B_BAD_VALUE; if (result == B_OK && InitCheck() != B_OK) result = B_NO_INIT; // write/remove the attribute if (result == B_OK) { if (type != NULL) { size_t toWrite = strlen(type) + 1; ssize_t written = fNode->WriteAttr(kNITypeAttribute, B_MIME_STRING_TYPE, 0, type, toWrite); if (written < 0) result = written; else if (written != (ssize_t)toWrite) result = B_ERROR; } else result = fNode->RemoveAttr(kNITypeAttribute); } return result; } //----------------------------------------------------------------------------- status_t BNodeInfo::GetIcon(BBitmap* icon, icon_size which) const { const char* iconAttribute = kNIIconAttribute; const char* miniIconAttribute = kNIMiniIconAttribute; const char* largeIconAttribute = kNILargeIconAttribute; return BIconUtils::GetIcon(fNode, iconAttribute, miniIconAttribute, largeIconAttribute, which, icon); } //----------------------------------------------------------------------------- status_t BNodeInfo::SetIcon(const BBitmap* icon, icon_size which) { status_t result = B_OK; // set some icon size related variables const char* attribute = NULL; BRect bounds; uint32 attrType = 0; size_t attrSize = 0; switch (which) { case B_MINI_ICON: attribute = kNIMiniIconAttribute; bounds.Set(0, 0, 15, 15); attrType = B_MINI_ICON_TYPE; attrSize = 16 * 16; break; case B_LARGE_ICON: attribute = kNILargeIconAttribute; bounds.Set(0, 0, 31, 31); attrType = B_LARGE_ICON_TYPE; attrSize = 32 * 32; break; default: result = B_BAD_VALUE; break; } // check parameter and initialization if (result == B_OK && icon != NULL && (icon->InitCheck() != B_OK || icon->Bounds() != bounds)) { result = B_BAD_VALUE; } if (result == B_OK && InitCheck() != B_OK) result = B_NO_INIT; // write/remove the attribute if (result == B_OK) { if (icon != NULL) { bool otherColorSpace = (icon->ColorSpace() != B_CMAP8); ssize_t written = 0; if (otherColorSpace) { BBitmap bitmap(bounds, B_BITMAP_NO_SERVER_LINK, B_CMAP8); result = bitmap.InitCheck(); if (result == B_OK) result = bitmap.ImportBits(icon); if (result == B_OK) { written = fNode->WriteAttr(attribute, attrType, 0, bitmap.Bits(), attrSize); } } else { written = fNode->WriteAttr(attribute, attrType, 0, icon->Bits(), attrSize); } if (result == B_OK) { if (written < 0) result = written; else if (written != (ssize_t)attrSize) result = B_ERROR; } } else { // no icon given => remove result = fNode->RemoveAttr(attribute); } } return result; } //----------------------------------------------------------------------------- status_t BNodeInfo::GetIcon(uint8** data, size_t* size, type_code* type) const { // check params if (data == NULL || size == NULL || type == NULL) return B_BAD_VALUE; // check initialization if (InitCheck() != B_OK) return B_NO_INIT; // get the attribute info and check type and size of the attr contents attr_info attrInfo; status_t result = fNode->GetAttrInfo(kNIIconAttribute, &attrInfo); if (result != B_OK) return result; // chicken out on unrealisticly large attributes if (attrInfo.size > 128 * 1024) return B_ERROR; // fill the params *type = attrInfo.type; *size = attrInfo.size; *data = new (nothrow) uint8[*size]; if (*data == NULL) return B_NO_MEMORY; // featch the data ssize_t read = fNode->ReadAttr(kNIIconAttribute, *type, 0, *data, *size); if (read != attrInfo.size) { delete[] *data; *data = NULL; return B_ERROR; } return B_OK; } //----------------------------------------------------------------------------- status_t BNodeInfo::SetIcon(const uint8* data, size_t size) { // check initialization if (InitCheck() != B_OK) return B_NO_INIT; status_t result = B_OK; // write/remove the attribute if (data && size > 0) { ssize_t written = fNode->WriteAttr(kNIIconAttribute, B_VECTOR_ICON_TYPE, 0, data, size); if (written < 0) result = (status_t)written; else if (written != (ssize_t)size) result = B_ERROR; } else { // no icon given => remove result = fNode->RemoveAttr(kNIIconAttribute); } return result; } //----------------------------------------------------------------------------- status_t BNodeInfo::GetPreferredApp(char* signature, app_verb verb) const { // check parameter and initialization status_t result = (signature && verb == B_OPEN ? B_OK : B_BAD_VALUE); if (result == B_OK && InitCheck() != B_OK) result = B_NO_INIT; // get the attribute info and check type and length of the attr contents attr_info attrInfo; if (result == B_OK) result = fNode->GetAttrInfo(kNIPreferredAppAttribute, &attrInfo); if (result == B_OK && attrInfo.type != B_MIME_STRING_TYPE) result = B_BAD_TYPE; if (result == B_OK && attrInfo.size > B_MIME_TYPE_LENGTH) result = B_BAD_DATA; // read the data if (result == B_OK) { ssize_t read = fNode->ReadAttr(kNIPreferredAppAttribute, attrInfo.type, 0, signature, attrInfo.size); if (read < 0) result = read; else if (read != attrInfo.size) result = B_ERROR; if (result == B_OK) { // attribute strings doesn't have to be null terminated signature[min_c(attrInfo.size, B_MIME_TYPE_LENGTH - 1)] = '\0'; } } return result; } //----------------------------------------------------------------------------- status_t BNodeInfo::SetPreferredApp(const char* signature, app_verb verb) { // check parameters and initialization status_t result = (verb == B_OPEN ? B_OK : B_BAD_VALUE); if (result == B_OK && signature && strlen(signature) >= B_MIME_TYPE_LENGTH) result = B_BAD_VALUE; if (result == B_OK && InitCheck() != B_OK) result = B_NO_INIT; // write/remove the attribute if (result == B_OK) { if (signature) { size_t toWrite = strlen(signature) + 1; ssize_t written = fNode->WriteAttr(kNIPreferredAppAttribute, B_MIME_STRING_TYPE, 0, signature, toWrite); if (written < 0) result = written; else if (written != (ssize_t)toWrite) result = B_ERROR; } else result = fNode->RemoveAttr(kNIPreferredAppAttribute); } return result; } //----------------------------------------------------------------------------- status_t BNodeInfo::GetAppHint(entry_ref* ref) const { // check parameter and initialization status_t result = (ref ? B_OK : B_BAD_VALUE); if (result == B_OK && InitCheck() != B_OK) result = B_NO_INIT; // get the attribute info and check type and length of the attr contents attr_info attrInfo; if (result == B_OK) result = fNode->GetAttrInfo(kNIAppHintAttribute, &attrInfo); // NOTE: The attribute type should be B_STRING_TYPE, but R5 uses // B_MIME_STRING_TYPE. if (result == B_OK && attrInfo.type != B_MIME_STRING_TYPE) result = B_BAD_TYPE; if (result == B_OK && attrInfo.size > B_PATH_NAME_LENGTH) result = B_BAD_DATA; // read the data if (result == B_OK) { char path[B_PATH_NAME_LENGTH]; ssize_t read = fNode->ReadAttr(kNIAppHintAttribute, attrInfo.type, 0, path, attrInfo.size); if (read < 0) result = read; else if (read != attrInfo.size) result = B_ERROR; // get the entry_ref for the path if (result == B_OK) { // attribute strings doesn't have to be null terminated path[min_c(attrInfo.size, B_PATH_NAME_LENGTH - 1)] = '\0'; result = get_ref_for_path(path, ref); } } return result; } //----------------------------------------------------------------------------- status_t BNodeInfo::SetAppHint(const entry_ref* ref) { // check parameter and initialization if (InitCheck() != B_OK) return B_NO_INIT; status_t result = B_OK; if (ref != NULL) { // write/remove the attribute BPath path; result = path.SetTo(ref); if (result == B_OK) { size_t toWrite = strlen(path.Path()) + 1; ssize_t written = fNode->WriteAttr(kNIAppHintAttribute, B_MIME_STRING_TYPE, 0, path.Path(), toWrite); if (written < 0) result = written; else if (written != (ssize_t)toWrite) result = B_ERROR; } } else result = fNode->RemoveAttr(kNIAppHintAttribute); return result; } //----------------------------------------------------------------------------- status_t BNodeInfo::GetTrackerIcon(BBitmap* icon, icon_size which) const { if (icon == NULL) return B_BAD_VALUE; // set some icon size related variables BRect bounds; switch (which) { case B_MINI_ICON: bounds.Set(0, 0, 15, 15); break; case B_LARGE_ICON: bounds.Set(0, 0, 31, 31); break; default: // result = B_BAD_VALUE; // NOTE: added to be less strict and support scaled icons bounds = icon->Bounds(); break; } // check parameters and initialization if (icon->InitCheck() != B_OK || icon->Bounds() != bounds) return B_BAD_VALUE; if (InitCheck() != B_OK) return B_NO_INIT; // Ask GetIcon() first. if (GetIcon(icon, which) == B_OK) return B_OK; // If not successful, see if the node has a type available at all. // If no type is available, use one of the standard types. status_t result = B_OK; char mimeString[B_MIME_TYPE_LENGTH]; if (GetType(mimeString) != B_OK) { // Get the icon from a mime type... BMimeType type; struct stat stat; result = fNode->GetStat(&stat); if (result == B_OK) { // no type available -- get the icon for the appropriate type // (file/dir/etc.) if (S_ISREG(stat.st_mode)) { // is it an application (executable) or just a regular file? if ((stat.st_mode & S_IXUSR) != 0) type.SetTo(B_APP_MIME_TYPE); else type.SetTo(B_FILE_MIME_TYPE); } else if (S_ISDIR(stat.st_mode)) { // it's either a volume or just a standard directory fs_info info; if (fs_stat_dev(stat.st_dev, &info) == 0 && stat.st_ino == info.root) { type.SetTo(B_VOLUME_MIME_TYPE); } else type.SetTo(B_DIRECTORY_MIME_TYPE); } else if (S_ISLNK(stat.st_mode)) type.SetTo(B_SYMLINK_MIME_TYPE); } else { // GetStat() failed. Return the icon for // "application/octet-stream" from the MIME database. type.SetTo(B_FILE_MIME_TYPE); } return type.GetIcon(icon, which); } else { // We know the mimetype of the node. bool success = false; // Get the preferred application and ask the MIME database, if that // application has a special icon for the node's file type. char signature[B_MIME_TYPE_LENGTH]; if (GetPreferredApp(signature) == B_OK) { BMimeType type(signature); success = type.GetIconForType(mimeString, icon, which) == B_OK; } // ToDo: Confirm Tracker asks preferred app icons before asking // mime icons. BMimeType nodeType(mimeString); // Ask the MIME database for the preferred application for the node's // file type and whether this application has a special icon for the // type. if (!success && nodeType.GetPreferredApp(signature) == B_OK) { BMimeType type(signature); success = type.GetIconForType(mimeString, icon, which) == B_OK; } // Ask the MIME database whether there is an icon for the node's file // type. if (!success) success = nodeType.GetIcon(icon, which) == B_OK; // Get the super type if still no success. BMimeType superType; if (!success && nodeType.GetSupertype(&superType) == B_OK) { // Ask the MIME database for the preferred application for the // node's super type and whether this application has a special // icon for the type. if (superType.GetPreferredApp(signature) == B_OK) { BMimeType type(signature); success = type.GetIconForType(superType.Type(), icon, which) == B_OK; } // Get the icon of the super type itself. if (!success) success = superType.GetIcon(icon, which) == B_OK; } if (success) return B_OK; } return B_ERROR; } //----------------------------------------------------------------------------- status_t BNodeInfo::GetTrackerIcon(const entry_ref* ref, BBitmap* icon, icon_size which) { // check ref param status_t result = (ref ? B_OK : B_BAD_VALUE); // init a BNode BNode node; if (result == B_OK) result = node.SetTo(ref); // init a BNodeInfo BNodeInfo nodeInfo; if (result == B_OK) result = nodeInfo.SetTo(&node); // let the non-static GetTrackerIcon() do the dirty work if (result == B_OK) result = nodeInfo.GetTrackerIcon(icon, which); return result; } //----------------------------------------------------------------------------- /*! This method is provided for binary compatibility purposes (for example the program "Guido" depends on it.) */ extern "C" status_t GetTrackerIcon__9BNodeInfoP9entry_refP7BBitmap9icon_size( BNodeInfo* nodeInfo, entry_ref* ref, BBitmap* bitmap, icon_size iconSize) { // NOTE: nodeInfo is ignored - maybe that's wrong! return BNodeInfo::GetTrackerIcon(ref, bitmap, iconSize); } //----------------------------------------------------------------------------- void BNodeInfo::_ReservedNodeInfo1() {} void BNodeInfo::_ReservedNodeInfo2() {} void BNodeInfo::_ReservedNodeInfo3() {} //----------------------------------------------------------------------------- /*! Assignment operator is declared private to prevent it from being created automatically by the compiler. */ BNodeInfo& BNodeInfo::operator=(const BNodeInfo &nodeInfo) { return *this; } //----------------------------------------------------------------------------- /*! Copy constructor is declared private to prevent it from being created automatically by the compiler. */ BNodeInfo::BNodeInfo(const BNodeInfo &) { } //-----------------------------------------------------------------------------
31.916118
88
0.524916
stasinek
ac6c6bddc8d811b7ae25f6bbb9f8ce0e716e12c5
323
cpp
C++
maximum-difference-between-increasing-elements/maximum-difference-between-increasing-elements.cpp
sharmishtha2401/leetcode
0c7389877afb64b3ff277f075ed9c87b24cb587b
[ "MIT" ]
1
2022-02-14T07:57:07.000Z
2022-02-14T07:57:07.000Z
maximum-difference-between-increasing-elements/maximum-difference-between-increasing-elements.cpp
sharmishtha2401/leetcode
0c7389877afb64b3ff277f075ed9c87b24cb587b
[ "MIT" ]
null
null
null
maximum-difference-between-increasing-elements/maximum-difference-between-increasing-elements.cpp
sharmishtha2401/leetcode
0c7389877afb64b3ff277f075ed9c87b24cb587b
[ "MIT" ]
null
null
null
class Solution { public: int maximumDifference(vector<int>& nums) { int diff=0; int minimum=INT_MAX; for(int n : nums) { if(n<minimum) minimum=n; if(n-minimum>diff) diff=n-minimum; } return diff==0?-1:diff; } };
21.533333
46
0.458204
sharmishtha2401
ac6ecd4799d50f8520d54d5cf0337cbc916110bf
283
cpp
C++
sxaccelerate/src/io/examples/plugins/SxPluginA.cpp
ashtonmv/sphinx_vdw
5896fee0d92c06e883b72725cb859d732b8b801f
[ "Apache-2.0" ]
1
2020-02-29T03:26:32.000Z
2020-02-29T03:26:32.000Z
sxaccelerate/src/io/examples/plugins/SxPluginA.cpp
ashtonmv/sphinx_vdw
5896fee0d92c06e883b72725cb859d732b8b801f
[ "Apache-2.0" ]
null
null
null
sxaccelerate/src/io/examples/plugins/SxPluginA.cpp
ashtonmv/sphinx_vdw
5896fee0d92c06e883b72725cb859d732b8b801f
[ "Apache-2.0" ]
null
null
null
#include <SxPluginA.h> #include <stdio.h> SxPluginA::SxPluginA (SxPluginManager *parent_, void *) : SxDemoPluginBase (parent_) { //empty } SxPluginA::~SxPluginA () { printf ("About to destroy plugin A.\n"); } void SxPluginA::foo () { printf ("This is plugin A.\n"); }
14.894737
55
0.650177
ashtonmv
ac6f4c0bcd49e1cd1ef543efe8fede81bd300cd0
2,687
hpp
C++
src/api/c/graphics_common.hpp
JuliaComputing/arrayfire
93427f09ff928f97df29c0e358c3fcf6b478bec6
[ "BSD-3-Clause" ]
1
2018-06-14T23:49:18.000Z
2018-06-14T23:49:18.000Z
src/api/c/graphics_common.hpp
JuliaComputing/arrayfire
93427f09ff928f97df29c0e358c3fcf6b478bec6
[ "BSD-3-Clause" ]
1
2015-07-02T15:53:02.000Z
2015-07-02T15:53:02.000Z
src/api/c/graphics_common.hpp
JuliaComputing/arrayfire
93427f09ff928f97df29c0e358c3fcf6b478bec6
[ "BSD-3-Clause" ]
1
2018-02-26T17:11:03.000Z
2018-02-26T17:11:03.000Z
/******************************************************* * Copyright (c) 2014, ArrayFire * All rights reserved. * * This file is distributed under 3-clause BSD license. * The complete license agreement can be obtained at: * http://arrayfire.com/licenses/BSD-3-Clause ********************************************************/ #pragma once #if defined(WITH_GRAPHICS) #include <af/graphics.h> #include <forge.h> #include <map> // default to f32(float) type template<typename T> fg::FGType getGLType(); // Print for OpenGL errors // Returns 1 if an OpenGL error occurred, 0 otherwise. GLenum glErrorSkip(const char *msg, const char* file, int line); GLenum glErrorCheck(const char *msg, const char* file, int line); GLenum glForceErrorCheck(const char *msg, const char* file, int line); #define CheckGL(msg) glErrorCheck (msg, __FILE__, __LINE__) #define ForceCheckGL(msg) glForceErrorCheck(msg, __FILE__, __LINE__) #define CheckGLSkip(msg) glErrorSkip (msg, __FILE__, __LINE__) namespace graphics { enum Defaults { WIDTH = 1280, HEIGHT= 720 }; static const long long _16BIT = 0x000000000000FFFF; static const long long _32BIT = 0x00000000FFFFFFFF; static const long long _48BIT = 0x0000FFFFFFFFFFFF; typedef std::map<long long, fg::Image*> ImageMap_t; typedef std::map<long long, fg::Plot*> PlotMap_t; typedef std::map<long long, fg::Histogram*> HistogramMap_t; typedef ImageMap_t::iterator ImgMapIter; typedef PlotMap_t::iterator PltMapIter; typedef HistogramMap_t::iterator HstMapIter; /** * ForgeManager class follows a single pattern. Any user of this class, has * to call ForgeManager::getInstance inorder to use Forge resources for rendering. * It manages the windows, and other renderables (given below) that are drawed * onto chosen window. * Renderables: * fg::Image * fg::Plot * fg::Histogram * */ class ForgeManager { private: ImageMap_t mImgMap; PlotMap_t mPltMap; HistogramMap_t mHstMap; public: static ForgeManager& getInstance(); ~ForgeManager(); fg::Font* getFont(const bool dontCreate=false); fg::Window* getMainWindow(const bool dontCreate=false); fg::Image* getImage(int w, int h, fg::ColorMode mode, fg::FGType type); fg::Plot* getPlot(int nPoints, fg::FGType type); fg::Histogram* getHistogram(int nBins, fg::FGType type); protected: ForgeManager() {} ForgeManager(ForgeManager const&); void operator=(ForgeManager const&); void destroyResources(); }; } #define MAIN_WINDOW graphics::ForgeManager::getInstance().getMainWindow(true) #endif
29.206522
82
0.670636
JuliaComputing
ac73d7723b986f9918a84f5b983ca76be10bff40
409
cpp
C++
tests/common/FunexTest.cpp
boldowa/GIEPY
5aa326b264ef19f71d2e0ab5513b08fac7bca941
[ "MIT" ]
8
2018-03-15T22:01:35.000Z
2019-07-13T18:04:41.000Z
tests/common/FunexTest.cpp
telinc1/GIEPY
9c87ad1070e519637fc4b11b6bef01f998961678
[ "MIT" ]
21
2018-02-18T06:25:40.000Z
2018-07-13T17:54:40.000Z
tests/common/FunexTest.cpp
telinc1/GIEPY
9c87ad1070e519637fc4b11b6bef01f998961678
[ "MIT" ]
2
2018-07-25T21:04:23.000Z
2022-01-01T08:40:13.000Z
/** * FunexTest.cpp */ #include <bolib.h> #include "common/Funex.h" #include "CppUTest/TestHarness.h" TEST_GROUP(Funex) { void setup() { } void teardown() { } }; TEST(Funex, FunexMatch) { } TEST(Funex, ishex) { } TEST(Funex, atoh) { } TEST(Funex, IsSpace) { } TEST(Funex, CutOffTailSpaces) { } TEST(Funex, SkipUntilSpaces) { } TEST(Funex, SkipSpacesRev) { } TEST(Funex, SkipUntilChar) { }
7.865385
33
0.640587
boldowa
ac75db0aa1c9874d955232f8b76b7cb84a7b0012
2,022
hpp
C++
src/trafficsim/RoadTile.hpp
lutrarutra/trafsim
05e87b263b48e39d63f699dcaa456f10ca61e9a4
[ "Apache-2.0" ]
12
2019-12-28T21:45:23.000Z
2022-03-28T12:40:44.000Z
src/trafficsim/RoadTile.hpp
lutrarutra/trafsim
05e87b263b48e39d63f699dcaa456f10ca61e9a4
[ "Apache-2.0" ]
null
null
null
src/trafficsim/RoadTile.hpp
lutrarutra/trafsim
05e87b263b48e39d63f699dcaa456f10ca61e9a4
[ "Apache-2.0" ]
1
2021-05-31T10:22:41.000Z
2021-05-31T10:22:41.000Z
#pragma once #include <array> #include <climits> // UINT_MAX #include <SFML/Graphics.hpp> #include "Tile.hpp" #include "TrafficLight.hpp" namespace ts { /* * Every Road type is derived from this class * RoadTile is abstract class, and is derived from Tile * * Functions inherited from Tile: * getNode() * getPos() * getTileIndex() * * Overrided function from Tile: * getType() * * Functions to implement in derived classes: * getType() * connect() * connectableFrom() * canConnectTo() */ enum RoadType { StraightRoadType = 0, RoadTurnType, IntersectionType, TrisectionType, JunctionType, HomeRoadType, // Keep as last RoadTypeCount, }; class RoadTile : public Tile { public: RoadTile(const Tile &tile); virtual TileCategory getCategory() const { return TileCategory::RoadCategory; }; virtual RoadType getType() const = 0; // Direction of the road // Up: { 0, 1 }, Right { 1, 0 }, Down { 0, -1 }, Left { -1, 0 } const sf::Vector2f &getDir() const { return dir_; } bool isFlipped() const { return right_turn_; } TrafficLight *getLight() { return light_.get(); } void rotate(); virtual void flip(); void addLight(unsigned int handler_id, float green_time); unsigned int removeLight(); // Auto rotates road if there is neighbor, only RoadTurn has own implementation virtual void autoRotate(std::array<Tile *, 4> &neighbors); // Pure virtual functions virtual void connect(std::array<Tile *, 4> &neighbors) = 0; virtual bool connectableFrom(NeighborIndex n_index) const = 0; virtual bool canConnectTo(NeighborIndex n_index) const = 0; virtual void draw(sf::RenderTarget &target, sf::RenderStates states) const; protected: // Up: { 0, 1 }, Right { 1, 0 }, Down { 0, -1 }, Left { -1, 0 } sf::Vector2f dir_; bool right_turn_ = true; std::unique_ptr<TrafficLight> light_ = nullptr; void connectTo(Tile *another, NeighborIndex from); }; } // namespace ts
24.658537
84
0.661721
lutrarutra
ac79048ad80efb870bcb63c70d9ac6b7cd605a77
654
cpp
C++
src/base/math/trig.cpp
dyuri/vizzu-lib
e5eb4bee98445a85c0a6a61b820ad355851f38c8
[ "Apache-2.0" ]
1,159
2021-09-23T14:53:16.000Z
2022-03-30T21:23:41.000Z
src/base/math/trig.cpp
dyuri/vizzu-lib
e5eb4bee98445a85c0a6a61b820ad355851f38c8
[ "Apache-2.0" ]
29
2021-10-05T13:28:01.000Z
2022-03-29T16:16:20.000Z
src/base/math/trig.cpp
dyuri/vizzu-lib
e5eb4bee98445a85c0a6a61b820ad355851f38c8
[ "Apache-2.0" ]
47
2021-09-30T14:04:25.000Z
2022-02-21T16:01:58.000Z
#include "trig.h" #include <array> #include <cmath> float Math::atan2(float y, float x) { const auto ONEQTR_PI = (float)(M_PI / 4.0); const auto THRQTR_PI = (float)(3.0 * M_PI / 4.0); float r; float angle; float abs_y = fabs(y) + 1e-10f; // kludge to prevent 0/0 condition if ( x < 0.0f ) { r = (x + abs_y) / (abs_y - x); angle = THRQTR_PI; } else { r = (x - abs_y) / (x + abs_y); angle = ONEQTR_PI; } angle += (0.1963f * r * r - 0.9817f) * r; if ( y < 0.0f ) return( -angle ); // negate if in quad III or IV else return( angle ); } int Math::rad2quadrant(double angle) { return (int)round(angle / (M_PI / 2.0)); }
19.235294
72
0.574924
dyuri
ac79c816f4f43e7b2101141a3716b678589576d4
13,006
cpp
C++
frameworks/object/modules/basic/dmzObjectModuleGridBasic.cpp
dmzgroup/dmz
fc2d9ddcb04ed71f4106b8d33539529807b3dea6
[ "MIT" ]
2
2015-11-05T03:03:43.000Z
2017-05-15T12:55:39.000Z
frameworks/object/modules/basic/dmzObjectModuleGridBasic.cpp
dmzgroup/dmz
fc2d9ddcb04ed71f4106b8d33539529807b3dea6
[ "MIT" ]
null
null
null
frameworks/object/modules/basic/dmzObjectModuleGridBasic.cpp
dmzgroup/dmz
fc2d9ddcb04ed71f4106b8d33539529807b3dea6
[ "MIT" ]
null
null
null
#include <dmzObjectAttributeMasks.h> #include "dmzObjectModuleGridBasic.h" #include <dmzRuntimeConfigToTypesBase.h> #include <dmzRuntimeConfigToVector.h> #include <dmzRuntimePluginFactoryLinkSymbol.h> #include <dmzRuntimePluginInfo.h> #include <dmzTypesVolume.h> /*! \class dmz::ObjectModuleGridBasic \ingroup Object \brief Basic ObjectModuleGrid implementation. \details This provids a basic implementation of the ObjectModuleGrid. \code <dmz> <dmzObjectModuleGridBasic> <grid> <cell x="X cell dimension" y="Y cell dimension"/> <min x="min x" y="min y" z="min z"/> <max x="max x" y="max y" z="max z"/> </grid> </dmzObjectModuleGridBasic> </dmz> \endcode */ //! \cond dmz::ObjectModuleGridBasic::ObjectModuleGridBasic ( const PluginInfo &Info, Config &local) : Plugin (Info), ObjectModuleGrid (Info), ObjectObserverUtil (Info, local), _log (Info), _primaryAxis (VectorComponentX), _secondaryAxis (VectorComponentZ), _xCoordMax (100), _yCoordMax (100), _maxGrid (100000.0, 0.0, 100000.0), _xCellSize (0.0), _yCellSize (0.0), _grid (0) { _init (local); } dmz::ObjectModuleGridBasic::~ObjectModuleGridBasic () { if (_grid) { delete []_grid; _grid = 0; } _objTable.empty (); _obsTable.empty (); } // Plugin Interface void dmz::ObjectModuleGridBasic::update_plugin_state ( const PluginStateEnum State, const UInt32 Level) { if (State == PluginStateInit) { } else if (State == PluginStateStart) { } else if (State == PluginStateStop) { } else if (State == PluginStateShutdown) { } } void dmz::ObjectModuleGridBasic::discover_plugin ( const PluginDiscoverEnum Mode, const Plugin *PluginPtr) { if (Mode == PluginDiscoverAdd) { } else if (Mode == PluginDiscoverRemove) { } } // ObjectModuleGrid Interface dmz::Boolean dmz::ObjectModuleGridBasic::register_object_observer_grid (ObjectObserverGrid &observer) { Boolean result (False); ObserverStruct *os (_obsTable.lookup (observer.get_object_observer_grid_handle ())); if (!os) { os = new ObserverStruct (observer); if (!_obsTable.store (os->ObsHandle, os)) { delete os; os = 0; } result = update_object_observer_grid (observer); } return result; } dmz::Boolean dmz::ObjectModuleGridBasic::update_object_observer_grid (ObjectObserverGrid &observer) { Boolean result (False); ObserverStruct *os (_obsTable.lookup (observer.get_object_observer_grid_handle ())); if (os) { const Volume &SearchSpace = os->obs.get_observer_volume (); Vector origin, min, max; SearchSpace.get_extents (origin, min, max); Int32 minX = 0, minY = 0, maxX = 0, maxY = 0; _map_point_to_coord (min, minX, minY); _map_point_to_coord (max, maxX, maxY); Boolean updateExtents = False; if ( (minX != os->minX) || (maxX != os->maxX) || (minY != os->minY) || (maxY != os->maxY)) { updateExtents = True; } if (updateExtents && (os->minX >= 0)) { for (Int32 ix = os->minX; ix <= os->maxX; ix++) { for (Int32 jy = os->minY; jy <= os->maxY; jy++) { const Int32 Place = _map_coord (ix, jy); _grid[Place].obsTable.remove (os->ObsHandle); HashTableHandleIterator it; GridStruct *cell = &(_grid[Place]); ObjectStruct *current = cell->objTable.get_first (it); while (current) { if (!SearchSpace.contains_point (current->pos) && os->objects.remove (current->Object)) { observer.update_object_grid_state ( ObjectGridStateExit, current->Object, current->Type, current->pos); } current = cell->objTable.get_next (it); } } } } os->minX = minX; os->maxX = maxX; os->minY = minY; os->maxY = maxX; for (Int32 ix = os->minX; ix <= os->maxX; ix++) { for (Int32 jy = os->minY; jy <= os->maxY; jy++) { const Int32 Place = _map_coord (ix, jy); GridStruct *cell = &(_grid[Place]); if (updateExtents) { cell->obsTable.store (os->ObsHandle, os); } HashTableHandleIterator it; ObjectStruct *current = cell->objTable.get_first (it); while (current) { _update_observer (SearchSpace, *current, *os); current = cell->objTable.get_next (it); } } } result = True; } return result; } dmz::Boolean dmz::ObjectModuleGridBasic::release_object_observer_grid (ObjectObserverGrid &observer) { Boolean result (False); ObserverStruct *os (_obsTable.remove (observer.get_object_observer_grid_handle ())); if (os) { for (Int32 ix = os->minX; ix <= os->maxX; ix++) { for (Int32 jy = os->minY; jy <= os->maxY; jy++) { const Int32 Place = _map_coord (ix, jy); _grid[Place].obsTable.remove (os->ObsHandle); } } delete os; os = 0; result = True; } return result; } void dmz::ObjectModuleGridBasic::find_objects ( const Volume &SearchSpace, HandleContainer &objects, const ObjectTypeSet *IncludeTypes, const ObjectTypeSet *ExcludeTypes) { Vector origin, min, max; SearchSpace.get_extents (origin, min, max); Int32 minX = 0, minY = 0, maxX = 0, maxY = 0; _map_point_to_coord (min, minX, minY); _map_point_to_coord (max, maxX, maxY); ObjectStruct *list (0); // HandleContainer found; for (Int32 ix = minX; ix <= maxX; ix++) { for (Int32 jy = minY; jy <= maxY; jy++) { HashTableHandleIterator it; GridStruct *cell = &(_grid[_map_coord (ix, jy)]); ObjectStruct *current = cell->objTable.get_first (it); while (current) { Boolean test (True); if (IncludeTypes && !IncludeTypes->contains_type (current->Type)) { test = False; } else if (ExcludeTypes && ExcludeTypes->contains_type (current->Type)) { test = False; } if (test && SearchSpace.contains_point (current->pos)) { #if 0 if (!found.add_handle (current->Object)) { _log.error << "origin: " << origin << endl << "minX: " << minX << endl << "minY: " << minY << endl << "maxX: " << maxX << endl << "maxY: " << maxY << endl; HandleContainer cc; for (Int32 xx = minX; xx <= maxX; xx++) { for (Int32 yy = minY; yy <= maxY; yy++) { Boolean s = cc.add_handle ((Handle)_map_coord (xx, yy)); _log.error << (s ? "" : "##### NOT UNIQUE ") << xx << " " << yy << " = " << _map_coord (xx, yy) << endl; } } } #endif // 0 current->distanceSquared = (origin - current->pos).magnitude_squared (); current->next = 0; if (!list) { list = current; } else { ObjectStruct *p = 0, *c = list; Boolean done (False); while (!done) { if (c->distanceSquared > current->distanceSquared) { if (!c->next) { c->next = current; done = True; } else { p = c; c = c->next; if (!c) { p->next = current; done = True; } } } else { if (p) { p->next = current; } else { list = current; } current->next = c; done = True; } } } } current = cell->objTable.get_next (it); } } } while (list) { if (!objects.add (list->Object)) { _log.error << "Loop detected in object list for object: " << list->Object << endl; list = 0; } else { list = list->next; } } } // Object Observer Interface void dmz::ObjectModuleGridBasic::create_object ( const UUID &Identity, const Handle ObjectHandle, const ObjectType &Type, const ObjectLocalityEnum Locality) { ObjectStruct *os = new ObjectStruct (ObjectHandle, Type); if (!_objTable.store (ObjectHandle, os)) { delete os; os = 0; } } void dmz::ObjectModuleGridBasic::destroy_object ( const UUID &Identity, const Handle ObjectHandle) { ObjectStruct *os (_objTable.remove (ObjectHandle)); if (os) { _remove_object_from_grid (*os); if (os->place >= 0) { HashTableHandleIterator it; ObserverStruct *obs = _grid[os->place].obsTable.get_first (it); while (obs) { obs->objects.remove (ObjectHandle); obs = _grid[os->place].obsTable.get_next (it); } } delete os; os = 0; } } void dmz::ObjectModuleGridBasic::update_object_position ( const UUID &Identity, const Handle ObjectHandle, const Handle AttributeHandle, const Vector &Value, const Vector *PreviousValue) { ObjectStruct *current (_objTable.lookup (ObjectHandle)); if (current && _grid) { current->pos = Value; const Int32 OldPlace = current->place; const Int32 Place = _map_point (Value); if (Place != current->place) { _remove_object_from_grid (*current); current->place = Place; _grid[Place].objTable.store (current->Object, current); } if ((Place != OldPlace) && (OldPlace >= 0)) { HashTableHandleIterator it; GridStruct *cell = &(_grid[OldPlace]); ObserverStruct *os = cell->obsTable.get_first (it); HandleContainer tested; while (os) { tested.add (os->ObsHandle); _update_observer ( os->obs.get_observer_volume (), *current, *os); os = cell->obsTable.get_next (it); } cell = &(_grid[Place]); os = cell->obsTable.get_first (it); while (os) { if (!tested.contains (os->ObsHandle)) { _update_observer ( os->obs.get_observer_volume (), *current, *os); } os = cell->obsTable.get_next (it); } } else { HashTableHandleIterator it; GridStruct *cell = &(_grid[Place]); ObserverStruct *os = cell->obsTable.get_first (it); while (os) { _update_observer ( os->obs.get_observer_volume (), *current, *os); os = cell->obsTable.get_next (it); } } } } void dmz::ObjectModuleGridBasic::_remove_object_from_grid (ObjectStruct &obj) { if (_grid && obj.place >= 0) { _grid[obj.place].objTable.remove (obj.Object); } } void dmz::ObjectModuleGridBasic::_update_observer ( const Volume &SearchSpace, const ObjectStruct &Obj, ObserverStruct &os) { const Boolean Contains = SearchSpace.contains_point (Obj.pos); if (Contains && os.objects.add (Obj.Object)) { os.obs.update_object_grid_state ( ObjectGridStateEnter, Obj.Object, Obj.Type, Obj.pos); } else if (!Contains && os.objects.remove (Obj.Object)) { os.obs.update_object_grid_state ( ObjectGridStateExit, Obj.Object, Obj.Type, Obj.pos); } } void dmz::ObjectModuleGridBasic::_init (Config &local) { _xCoordMax = config_to_int32 ("grid.cell.x", local, _xCoordMax); _yCoordMax = config_to_int32 ("grid.cell.y", local, _yCoordMax); _minGrid = config_to_vector ("grid.min", local, _minGrid); _maxGrid = config_to_vector ("grid.max", local, _maxGrid); _log.info << "grid: " << _xCoordMax << "x" << _yCoordMax << endl; _log.info << "extents:" << endl << "\t" << _minGrid << endl << "\t" << _maxGrid << endl; Vector vec (_maxGrid - _minGrid); _xCellSize = vec.get (_primaryAxis) / (Float64)(_xCoordMax); _yCellSize = vec.get (_secondaryAxis) / (Float64)(_yCoordMax); _log.info << "cell count: " << _xCoordMax * _yCoordMax << endl; if (is_zero64 (_xCellSize)) { _xCellSize = 1.0; } if (is_zero64 (_yCellSize)) { _yCellSize = 1.0; } _grid = new GridStruct[_xCoordMax * _yCoordMax]; activate_default_object_attribute ( ObjectCreateMask | ObjectDestroyMask | ObjectPositionMask); } //! \endcond extern "C" { DMZ_PLUGIN_FACTORY_LINK_SYMBOL dmz::Plugin * create_dmzObjectModuleGridBasic ( const dmz::PluginInfo &Info, dmz::Config &local, dmz::Config &global) { return new dmz::ObjectModuleGridBasic (Info, local); } };
23.908088
104
0.559819
dmzgroup
ac7ec77ea103427b85401cf12cbcdde234ceabdd
15,125
cpp
C++
Caesar/Hack/Aimbot/Aimbot.cpp
danielkrupinski/caesar
8d84261f2b9e01c0c0d40220db301b5a0d508b3d
[ "MIT" ]
27
2018-08-31T18:57:24.000Z
2022-02-13T22:58:05.000Z
Caesar/Hack/Aimbot/Aimbot.cpp
danielkrupinski/caesar
8d84261f2b9e01c0c0d40220db301b5a0d508b3d
[ "MIT" ]
6
2018-09-19T21:50:38.000Z
2020-07-28T13:48:47.000Z
Caesar/Hack/Aimbot/Aimbot.cpp
danielkrupinski/caesar
8d84261f2b9e01c0c0d40220db301b5a0d508b3d
[ "MIT" ]
9
2018-10-07T09:10:20.000Z
2021-04-30T16:44:43.000Z
#include "../../Required.h" #include "../../Config.h" extern Config config; CAimBot g_AimBot; void SmoothAimAngles(QAngle MyViewAngles, QAngle AimAngles, QAngle &OutAngles, float Smoothing, bool bSpiral, float SpiralX, float SpiralY) { if (Smoothing < 1) { OutAngles = AimAngles; return; } OutAngles = AimAngles - MyViewAngles; OutAngles.Normalize(); Vector vecViewAngleDelta = OutAngles; if (bSpiral && SpiralX != 0 && SpiralY != 0) vecViewAngleDelta += Vector(vecViewAngleDelta.y / SpiralX, vecViewAngleDelta.x / SpiralY, 0.0f); if (!isnan(Smoothing)) vecViewAngleDelta /= Smoothing; OutAngles = MyViewAngles + vecViewAngleDelta; OutAngles.Normalize(); } void CAimBot::Run(struct usercmd_s *cmd) { if (config.aimbot.enabled) { RageAimbot(cmd); } else { LegitAimbot(cmd); Trigger(cmd); } } void CAimBot::Trigger(struct usercmd_s *cmd) { if (config.trigger_key > 0 && config.trigger_key < 255) { static DWORD dwTemporaryBlockTimer = 0; if (GetTickCount() - dwTemporaryBlockTimer > 200) { if (g_Menu.keys[config.trigger_key]) { TriggerKeyStatus = !TriggerKeyStatus; dwTemporaryBlockTimer = GetTickCount(); } } if (!TriggerKeyStatus) return; } if (!IsCurWeaponGun() || !CanAttack()) return; unsigned int m_iWeaponID = g_Local.weapon.m_iWeaponID; if (!config.legit[m_iWeaponID].trigger) return; if (config.trigger_only_zoomed && IsCurWeaponSniper() && g_Local.iFOV == DEFAULT_FOV) return; std::deque<unsigned int> Hitboxes; if (config.legit[m_iWeaponID].trigger_head) { Hitboxes.push_back(11); } if (config.legit[m_iWeaponID].trigger_chest) { Hitboxes.push_back(7); Hitboxes.push_back(8); Hitboxes.push_back(9); Hitboxes.push_back(10); Hitboxes.push_back(11); Hitboxes.push_back(12); Hitboxes.push_back(17); } if (config.legit[m_iWeaponID].trigger_stomach) { Hitboxes.push_back(0); } float flAccuracy = config.legit[m_iWeaponID].trigger_accuracy; Vector vecSpreadDir, vecForward, vecRight, vecUp, vecRandom; QAngle QAngles; g_Engine.GetViewAngles(QAngles); if (flAccuracy > 0)//Recoil { QAngles[0] += g_Local.vPunchangle[0]; QAngles[1] += g_Local.vPunchangle[1]; QAngles[2] = NULL; } QAngles.Normalize(); QAngles.AngleVectors(&vecForward, &vecRight, &vecUp); if (flAccuracy > 1)//Recoil / Spread { g_NoSpread.GetSpreadXY(g_Local.weapon.random_seed, 1, vecRandom); vecSpreadDir = vecForward + (vecRight * vecRandom[0]) + (vecUp * vecRandom[1]); vecSpreadDir.Normalize(); } else {//Empty or Recoil vecSpreadDir = vecForward; vecSpreadDir.Normalize(); } for (int id = 1; id <= g_Engine.GetMaxClients(); ++id) { if (id == g_Local.iIndex) continue; if (!g_Player[id].bAlive) continue; if (!g_Player[id].bVisible) continue; if (g_Player[id].bFriend) continue; if (!config.legit_teammates && g_Player[id].iTeam == g_Local.iTeam) continue; for (auto &&hitbox : Hitboxes) { if (g_Utils.IsBoxIntersectingRay(g_PlayerExtraInfoList[id].vHitboxMin[hitbox], g_PlayerExtraInfoList[id].vHitboxMax[hitbox], g_Local.vEye, vecSpreadDir)) { cmd->buttons |= IN_ATTACK; break; } } } } void CAimBot::LegitAimbot(struct usercmd_s *cmd) { static DWORD dwBlockAttack = 0; static float flSpeedSpiralX = 1.3; static float flSpeedSpiralY = 3.7; m_flCurrentFOV = 0; if (!IsCurWeaponGun() || g_Local.weapon.m_iInReload || g_Local.weapon.m_iClip < 1 || g_Local.weapon.m_flNextAttack > 0.0) return; unsigned int iWeaponID = g_Local.weapon.m_iWeaponID; if (!config.legit[iWeaponID].aim) return; float flFOV = config.legit[iWeaponID].aim_fov; if (flFOV <= 0) return; float flSpeed = config.legit[iWeaponID].aim_speed_in_attack; if (config.legit[iWeaponID].aim_speed > 0 && !(cmd->buttons & IN_ATTACK))//Auto aim smooth flSpeed = config.legit[iWeaponID].aim_speed; if (flSpeed <= 0) return; std::deque<unsigned int> Hitboxes; if (config.legit[iWeaponID].aim_head) Hitboxes.push_back(11); if (config.legit[iWeaponID].aim_chest) { Hitboxes.push_back(7); Hitboxes.push_back(8); Hitboxes.push_back(9); Hitboxes.push_back(10); Hitboxes.push_back(12); Hitboxes.push_back(17); } if (config.legit[iWeaponID].aim_stomach) Hitboxes.push_back(0); if (Hitboxes.empty()) return; float flReactionTime = config.legit[iWeaponID].aim_reaction_time; if (flReactionTime > 0 && GetTickCount() - dwReactionTime < flReactionTime) return; float flSpeedScaleFov = config.legit[iWeaponID].aim_speed_scale_fov; bool bSpeedSpiral = config.legit[iWeaponID].aim_humanize; if (!g_Local.vPunchangle.IsZero2D()) bSpeedSpiral = false; float flRecoilCompensationPitch = 0.02f * config.legit[iWeaponID].aim_recoil_compensation_pitch; float flRecoilCompensationYaw = 0.02f * config.legit[iWeaponID].aim_recoil_compensation_yaw; int iRecoilCompensationAfterShotsFired = static_cast<int>(config.legit[iWeaponID].aim_recoil_compensation_after_shots_fired); if (iRecoilCompensationAfterShotsFired > 0 && g_Local.weapon.m_iShotsFired <= iRecoilCompensationAfterShotsFired) { flRecoilCompensationPitch = 0; flRecoilCompensationYaw = 0; } float flBlockAttackAfterKill = config.block_attack_after_kill; float flAccuracy = config.legit[iWeaponID].aim_accuracy; float flPSilent = config.legit[iWeaponID].aim_psilent; Vector vecFOV = {}; { QAngle QAngles = cmd->viewangles + g_Local.vPunchangle * 2; QAngles.Normalize(); QAngles.AngleVectors(&vecFOV, NULL, NULL); vecFOV.Normalize(); } m_flCurrentFOV = flFOV; unsigned int iTarget = 0; unsigned int iHitbox = 0; float flBestFOV = flFOV; for (int id = 1; id <= g_Engine.GetMaxClients(); ++id) { if (id == g_Local.iIndex) continue; if (!g_Player[id].bAlive) continue; if (!g_Player[id].bVisible) continue; if (g_Player[id].bFriend) continue; if (!config.legit_teammates && g_Player[id].iTeam == g_Local.iTeam) continue; for (auto &&hitbox : Hitboxes) { if (!g_PlayerExtraInfoList[id].bHitboxVisible[hitbox]) continue; if (config.legit[iWeaponID].aim_head && (config.legit[iWeaponID].aim_chest || config.legit[iWeaponID].aim_stomach) && hitbox == 11 && (!(g_Local.weapon.m_iFlags & FL_ONGROUND) || g_Local.flVelocity > 140 || g_Local.weapon.m_iShotsFired > 5)) continue; if (config.legit[iWeaponID].aim_chest && config.legit[iWeaponID].aim_stomach && hitbox != 0 && hitbox != 11 && (!(g_Local.weapon.m_iFlags & FL_ONGROUND) || g_Local.weapon.m_iShotsFired > 15)) continue; float fov = vecFOV.AngleBetween(g_PlayerExtraInfoList[id].vHitbox[hitbox] - g_Local.vEye); if (fov < flBestFOV) { flBestFOV = fov; iTarget = id; iHitbox = hitbox; } } } if (iTarget > 0) { bool bAttack = false; bool bBlock = false;//Block IN_ATTACK? if (config.legit[iWeaponID].aim_quick_stop) { cmd->forwardmove = 0; cmd->sidemove = 0; cmd->upmove = 0; } QAngle QMyAngles, QAimAngles, QNewAngles, QSmoothAngles; Vector vAimOrigin = g_PlayerExtraInfoList[iTarget].vHitbox[iHitbox]; g_Engine.GetViewAngles(QMyAngles); g_Utils.VectorAngles(vAimOrigin - g_Local.vEye, QAimAngles); if (flPSilent > 0 && flPSilent <= 1 && CanAttack()) { QAngle QAnglePerfectSilent = QAimAngles; QAnglePerfectSilent += g_Local.vPunchangle; QAnglePerfectSilent.Normalize(); g_NoSpread.GetSpreadOffset(g_Local.weapon.random_seed, 1, QAnglePerfectSilent, QAnglePerfectSilent); Vector vecPsilentFOV; QAnglePerfectSilent.AngleVectors(&vecPsilentFOV, NULL, NULL); vecPsilentFOV.Normalize(); float fov = vecPsilentFOV.AngleBetween(g_PlayerExtraInfoList[iTarget].vHitbox[iHitbox] - g_Local.vEye); if (fov <= flPSilent) { cmd->buttons |= IN_ATTACK; g_Utils.MakeAngle(false, QAnglePerfectSilent, cmd); g_Utils.bSendpacket(false); dwBlockAttack = GetTickCount(); return; } } QNewAngles[0] = QAimAngles[0] - g_Local.vPunchangle[0] * flRecoilCompensationPitch; QNewAngles[1] = QAimAngles[1] - g_Local.vPunchangle[1] * flRecoilCompensationYaw; QNewAngles[2] = 0; QNewAngles.Normalize(); /*if (cmd->buttons & IN_ATTACK && CanAttack()) g_NoSpread.GetSpreadOffset(g_Local.weapon.random_seed, 1, QNewAngles, QNewAngles);*/ if (flSpeedScaleFov > 0 && flSpeedScaleFov <= 100 && g_Local.vPunchangle.IsZero() && !isnan(g_PlayerExtraInfoList[iTarget].fHitboxFOV[iHitbox])) flSpeed = flSpeed - (((g_PlayerExtraInfoList[iTarget].fHitboxFOV[iHitbox] * (flSpeed / m_flCurrentFOV)) * flSpeedScaleFov) / 100);//speed - (((fov * (speed / 180)) * scale) / 100) SmoothAimAngles(QMyAngles, QNewAngles, QSmoothAngles, flSpeed, bSpeedSpiral, flSpeedSpiralX, flSpeedSpiralY); if (flAccuracy > 0) { bBlock = true; QAngle QAngleAccuracy = QAimAngles; Vector vecSpreadDir; if (flAccuracy == 1)//Aiming { QSmoothAngles.AngleVectors(&vecSpreadDir, NULL, NULL); vecSpreadDir.Normalize(); } else if (flAccuracy == 2) //Recoil { Vector vecRandom, vecForward; SmoothAimAngles(QMyAngles, QAimAngles, QAngleAccuracy, flSpeed, bSpeedSpiral, flSpeedSpiralX, flSpeedSpiralY); QAngleAccuracy[0] += g_Local.vPunchangle[0]; QAngleAccuracy[1] += g_Local.vPunchangle[1]; QAngleAccuracy[2] = NULL; QAngleAccuracy.Normalize(); QAngleAccuracy.AngleVectors(&vecForward, NULL, NULL); vecSpreadDir = vecForward; vecSpreadDir.Normalize(); } else //Recoil / Spread { Vector vecRandom, vecRight, vecUp, vecForward; SmoothAimAngles(QMyAngles, QAimAngles, QAngleAccuracy, flSpeed, bSpeedSpiral, flSpeedSpiralX, flSpeedSpiralY); QAngleAccuracy[0] += g_Local.vPunchangle[0]; QAngleAccuracy[1] += g_Local.vPunchangle[1]; QAngleAccuracy[2] = NULL; QAngleAccuracy.Normalize(); QAngleAccuracy.AngleVectors(&vecForward, &vecRight, &vecRight); g_NoSpread.GetSpreadXY(g_Local.weapon.random_seed, 1, vecRandom); vecSpreadDir = vecForward + (vecRight * vecRandom[0]) + (vecUp * vecRandom[1]); vecSpreadDir.Normalize(); } for (unsigned int x = 0; x < Hitboxes.size(); x++) { unsigned int hitbox = Hitboxes[x]; if (g_Utils.IsBoxIntersectingRay(g_PlayerExtraInfoList[iTarget].vHitboxMin[hitbox], g_PlayerExtraInfoList[iTarget].vHitboxMax[hitbox], g_Local.vEye, vecSpreadDir)) { bBlock = false; break; } } } if (cmd->buttons & IN_ATTACK) bAttack = true; else if (config.legit[iWeaponID].aim_speed > 0)//Auto aim { bAttack = true; bBlock = true; } if (bAttack) { QSmoothAngles.Normalize(); g_Utils.MakeAngle(false, QSmoothAngles, cmd); g_Engine.SetViewAngles(QSmoothAngles); if (!bBlock) cmd->buttons |= IN_ATTACK; else if (cmd->buttons & IN_ATTACK) cmd->buttons &= ~IN_ATTACK; if (!g_Local.vPunchangle.IsZero2D()) dwBlockAttack = GetTickCount(); } } else if (flBlockAttackAfterKill > 0 && GetTickCount() - dwBlockAttack < flBlockAttackAfterKill) { cmd->buttons &= ~IN_ATTACK; } } void CAimBot::RageAimbot(struct usercmd_s *cmd) { if (!config.aimbot.enabled && !IsCurWeaponGun() || !CanAttack()) return; std::deque<unsigned int> Hitboxes; if (config.aimbot.hitbox == 1)//"Head", "Neck", "Chest", "Stomach" { Hitboxes.push_back(11); } else if (config.aimbot.hitbox == 2) { Hitboxes.push_back(10); } else if (config.aimbot.hitbox == 3) { Hitboxes.push_back(7); } else if (config.aimbot.hitbox == 4) { Hitboxes.push_back(0); } else if (config.aimbot.hitbox == 5)//All { for (unsigned int j = 0; j <= 11; j++) Hitboxes.push_front(j); for (int k = 12; k < g_Local.iMaxHitboxes; k++) Hitboxes.push_back(k); } else if (config.aimbot.hitbox == 6)//Vital { for (unsigned int j = 0; j <= 11; j++) Hitboxes.push_front(j); } if (Hitboxes.empty()) return; unsigned int m_iTarget = 0; int m_iHitbox = -1; int m_iPoint = -1; float m_flBestFOV = 180; float m_flBestDist = 8192; for (int id = 1; id <= g_Engine.GetMaxClients(); ++id) { if (id == g_Local.iIndex) continue; if (!g_Player[id].bAlive) continue; if (g_Player[id].bFriend) continue; if (!g_Player[id].bVisible) continue; if (!config.aimbot.teammates && g_Player[id].iTeam == g_Local.iTeam) continue; if (config.aimbot.delayShot) { cl_entity_s *ent = g_Engine.GetEntityByIndex(id); if (ent && ent->curstate.frame != 0) continue; } for (auto &&hitbox : Hitboxes) { if (g_PlayerExtraInfoList[id].bHitboxVisible[hitbox]) { m_iHitbox = hitbox; break; } } if (m_iHitbox == -1) { for (auto &&hitbox : Hitboxes) { if (config.aimbot.multiPoint > 0) { if (config.aimbot.multiPoint == 1 && hitbox != 11) continue; if (config.aimbot.multiPoint == 2 && hitbox > 11) continue; for (unsigned int point = 0; point <= 8; ++point) { if (g_PlayerExtraInfoList[id].bHitboxPointsVisible[hitbox][point] && !g_PlayerExtraInfoList[id].bHitboxVisible[hitbox]) { m_iPoint = point; m_iHitbox = hitbox; break; } } } } } if (m_iHitbox < 0 || m_iHitbox > g_Local.iMaxHitboxes) continue; if (g_Player[id].bPriority) { m_iTarget = id; break; } //"Field of view", "Distance", "Cycle" if (config.aimbot.targetSelection == 1) { if (g_PlayerExtraInfoList[id].fHitboxFOV[m_iHitbox] < m_flBestFOV) { m_flBestFOV = g_PlayerExtraInfoList[id].fHitboxFOV[m_iHitbox]; m_iTarget = id; } } else if (config.aimbot.targetSelection == 2) { if (g_Player[id].flDist < m_flBestDist) { m_flBestDist = g_Player[id].flDist; m_iTarget = id; } } else if (config.aimbot.targetSelection == 3) { if (g_PlayerExtraInfoList[id].fHitboxFOV[m_iHitbox] < m_flBestFOV) { if (g_Player[id].flDist < m_flBestDist) { m_flBestFOV = g_PlayerExtraInfoList[id].fHitboxFOV[m_iHitbox]; m_flBestDist = g_Player[id].flDist; m_iTarget = id; } } } } if (m_iTarget > 0) { if (config.quick_stop_duck) { cmd->forwardmove = 0; cmd->sidemove = 0; cmd->upmove = 0; cmd->buttons |= IN_DUCK; } else if (config.quick_stop) { cmd->forwardmove = 0; cmd->sidemove = 0; cmd->upmove = 0; } if (config.aimbot.autoscope && IsCurWeaponSniper() && g_Local.iFOV == DEFAULT_FOV) { cmd->buttons |= IN_ATTACK2; } else if (CanAttack()) { QAngle QMyAngles, QAimAngles, QSmoothAngles; Vector vAimOrigin; if(m_iPoint >= 0 && m_iPoint < 8) vAimOrigin = g_PlayerExtraInfoList[m_iTarget].vHitboxPoints[m_iHitbox][m_iPoint]; else vAimOrigin = g_PlayerExtraInfoList[m_iTarget].vHitbox[m_iHitbox]; g_Engine.GetViewAngles(QMyAngles); g_Utils.VectorAngles(vAimOrigin - g_Local.vEye, QAimAngles); if (config.aimbot.perfectSilent) { g_Utils.MakeAngle(false, QAimAngles, cmd); g_Utils.bSendpacket(false); } else { g_Utils.MakeAngle(false, QAimAngles, cmd); if (!config.aimbot.silent) g_Engine.SetViewAngles(QAimAngles); } cmd->buttons |= IN_ATTACK; } else { cmd->buttons &= ~IN_ATTACK; } } }
23.341049
244
0.686479
danielkrupinski
ac7f583280c773e6d73aa692d441c3b074a3beed
2,230
cpp
C++
src/mainwindow.cpp
ashleyshu/sway
3c89ed47773267914ba9840bc4c85714403ca137
[ "MIT" ]
null
null
null
src/mainwindow.cpp
ashleyshu/sway
3c89ed47773267914ba9840bc4c85714403ca137
[ "MIT" ]
null
null
null
src/mainwindow.cpp
ashleyshu/sway
3c89ed47773267914ba9840bc4c85714403ca137
[ "MIT" ]
null
null
null
#include <QDebug> #include "mainwindow.h" #include "ui_mainwindow.h" #include "tasklistdialog.h" #include "conslistdialog.h" #include "taskinputdialog.h" #include "consinputdialog.h" #include "schedulecreator.h" #include "googlecal.h" //! Main Window Class /*! \Author: Group 33 Description: Main window from where user can select options and use program. */ //! Construction /*! \Authors: Group 33 Description: Constructor @param controller the input controller @param parent the parent of this widget */ MainWindow::MainWindow(InputController *controller, QWidget *parent) : QMainWindow(parent) , ui(new Ui::MainWindow), m_controller (controller) { Q_ASSERT(controller != nullptr); ui->setupUi(this); } MainWindow::~MainWindow() { delete ui; } //! Opens tasks view void MainWindow::on_bTaskView_clicked() { TaskListDialog tasklistdialog(m_controller); tasklistdialog.setModal(true); tasklistdialog.exec(); } //! Opens constraintss view void MainWindow::on_bConsView_clicked() { ConsListDialog conslistdialog(m_controller); conslistdialog.setModal(true); conslistdialog.exec(); } //! Opens task input screen void MainWindow::on_bTaskAdd_clicked() { TaskInputDialog taskinputdialog(m_controller); taskinputdialog.setModal(true); taskinputdialog.exec(); } //! Opens constraint input view void MainWindow::on_bConsAdd_clicked() { ConsInputDialog consinputdialog(m_controller); consinputdialog.setModal(true); consinputdialog.exec(); } //! Generatives schedule and saves as CSV void MainWindow::on_bSchedGen_clicked() { ScheduleCreator scheduleCreator(m_controller); scheduleCreator.createSchedule(); } //! Opens google calendar dialog void MainWindow::on_bGoogleCal_clicked() { GoogleCal googleCal; googleCal.setModal(true); googleCal.exec(); } //! Save task and constraint inputs void MainWindow::on_bSchedSave_clicked() { m_controller->saveInputs(); } //! Load task and constraint inputs void MainWindow::on_bSchedLoad_clicked() { m_controller->loadInputs(); }
20.272727
81
0.690583
ashleyshu
ac80c716b8c45340677a672b95e9b7cdead5efcb
3,025
cpp
C++
modcode/Client.cpp
eezstreet/Rapture
1022f1013d7a7a3a84ea3ba56518420daf4733fc
[ "ISC" ]
2
2017-10-25T03:22:34.000Z
2020-04-02T16:33:40.000Z
modcode/Client.cpp
eezstreet/Rapture
1022f1013d7a7a3a84ea3ba56518420daf4733fc
[ "ISC" ]
12
2016-07-03T21:08:25.000Z
2016-07-30T06:17:26.000Z
modcode/Client.cpp
eezstreet/Rapture
1022f1013d7a7a3a84ea3ba56518420daf4733fc
[ "ISC" ]
3
2016-03-02T06:56:42.000Z
2018-04-13T14:37:06.000Z
#include "Client.h" #include "ClientDisplay.h" #include "ClientFont.h" namespace Client { static bool bInitialized = false; /* Packet serialization/deserialization functions. The serialization function is called when a packet is next in the queue to be written. The deserialization function is conversely called when a packet is received. The deserialization function is expected to call the appropriate handler for the data as well. If a serialization function is null, the engine will throw a warning upon queueing it for send from modcode. If a deserialization function is null, the engine will throw a warning upon receipt. */ packetSerializationFunc clientFuncs[PACKET_MAX] = { nullptr, // PACKET_PING nullptr, // PACKET_PONG nullptr, // PACKET_DROP nullptr, // PACKET_CLIENTATTEMPT nullptr, // PACKET_CLIENTACCEPT nullptr, // PACKET_CLIENTDENIED nullptr, // PACKET_INFOREQUEST nullptr, // PACKET_INFOREQUESTED nullptr, // PACKET_SENDCHAT // FIXME nullptr, // PACKET_RECVCHAT // FIXME }; packetDeserializationFunc dclientFuncs[PACKET_MAX] = { nullptr, // PACKET_PING nullptr, // PACKET_PONG nullptr, // PACKET_DROP nullptr, // PACKET_CLIENTATTEMPT nullptr, // PACKET_CLIENTACCEPT nullptr, // PACKET_CLIENTDENIED nullptr, // PACKET_INFOREQUEST nullptr, // PACKET_INFOREQUESTED nullptr, // PACKET_SENDCHAT // FIXME nullptr, // PACKET_RECVCHAT // FIXME }; /* Initialization code */ void Initialize() { if (bInitialized) { return; } ClientFont::Initialize(); ClientDisplay::Initialize(); trap->printf(PRIORITY_MESSAGE, "Waiting for additional elements to complete...\n"); ClientFont::FinishInitialization(); trap->printf(PRIORITY_MESSAGE, "Client initialized successfully.\n"); bInitialized = true; } /* Shutdown code */ void Shutdown() { if (!bInitialized) { return; } ClientDisplay::Shutdown(); bInitialized = false; } /* Code that gets run every frame */ void Frame() { ClientDisplay::DrawDisplay(); } /* Packet serialization function. This calls the appropriate function in clientFuncs (or returns false if it doesn't exist) Called from the engine when a send packet attempt has been dequeued. The data isn't sent across the wire in clientFuncs, it's translated to packetData. */ bool SerializePacket(Packet& packet, int clientNum, void* extraData) { if (clientFuncs[packet.packetHead.type]) { clientFuncs[packet.packetHead.type](packet, clientNum, extraData); return true; } return false; } /* Packet deserialization function. This calls the appropriate function in dclientFuncs (or returns false if it doesn't exist) Called from the engine when we have received a packet. The data is both deserialized and used in dclientFuncs */ bool DeserializePacket(Packet& packet, int clientNum) { if (dclientFuncs[packet.packetHead.type]) { dclientFuncs[packet.packetHead.type](packet, clientNum); return true; } return false; } }
30.867347
110
0.729587
eezstreet
ac8209cc98e70c57ba64947689f569a1c3d585e4
1,195
hpp
C++
experimental/Pomdog.Experimental/Gameplay2D/Animator.hpp
bis83/pomdog
133a9262958d539ae6d93664e6cb2207b5b6c7ff
[ "MIT" ]
null
null
null
experimental/Pomdog.Experimental/Gameplay2D/Animator.hpp
bis83/pomdog
133a9262958d539ae6d93664e6cb2207b5b6c7ff
[ "MIT" ]
null
null
null
experimental/Pomdog.Experimental/Gameplay2D/Animator.hpp
bis83/pomdog
133a9262958d539ae6d93664e6cb2207b5b6c7ff
[ "MIT" ]
null
null
null
// Copyright (c) 2013-2015 mogemimi. // Distributed under the MIT license. See LICENSE.md file for details. #ifndef POMDOG_ANIMATOR_0CFC0E37_HPP #define POMDOG_ANIMATOR_0CFC0E37_HPP #include "Pomdog.Experimental/Gameplay/Component.hpp" #include "Pomdog/Application/Duration.hpp" #include <string> #include <memory> namespace Pomdog { class Skeleton; class SkeletonTransform; class AnimationGraph; class Animator: public Component<Animator> { public: Animator(std::shared_ptr<Skeleton> const& skeleton, std::shared_ptr<SkeletonTransform> const& skeletonTransform, std::shared_ptr<AnimationGraph> const& animationGraph); ~Animator(); void Update(Duration const& frameDuration); void CrossFade(std::string const& state, Duration const& transitionDuration); void Play(std::string const& state); float PlaybackRate() const; void PlaybackRate(float playbackRate); void SetFloat(std::string const& name, float value); void SetBool(std::string const& name, bool value); std::string GetCurrentStateName() const; private: class Impl; std::unique_ptr<Impl> impl; }; } // namespace Pomdog #endif // POMDOG_ANIMATOR_0CFC0E37_HPP
24.895833
81
0.745607
bis83
ac841a98df20217c9d4e857dfdf68828aaff42cf
6,100
hpp
C++
pomdog/pomdog.hpp
mogemimi/pomdog
6dc6244d018f70d42e61c6118535cf94a9ee0618
[ "MIT" ]
163
2015-03-16T08:42:32.000Z
2022-01-11T21:40:22.000Z
pomdog/pomdog.hpp
mogemimi/pomdog
6dc6244d018f70d42e61c6118535cf94a9ee0618
[ "MIT" ]
17
2015-04-12T20:57:50.000Z
2020-10-10T10:51:45.000Z
pomdog/pomdog.hpp
mogemimi/pomdog
6dc6244d018f70d42e61c6118535cf94a9ee0618
[ "MIT" ]
21
2015-04-12T20:45:11.000Z
2022-01-14T20:50:16.000Z
// Copyright mogemimi. Distributed under the MIT license. #pragma once /// Root namespace for the Pomdog game engine. namespace pomdog { } // namespace pomdog #include "pomdog/application/game.hpp" #include "pomdog/application/game_host.hpp" #include "pomdog/application/game_window.hpp" #include "pomdog/application/mouse_cursor.hpp" #include "pomdog/chrono/duration.hpp" #include "pomdog/chrono/game_clock.hpp" #include "pomdog/chrono/time_point.hpp" #include "pomdog/chrono/timer.hpp" #include "pomdog/audio/audio_channels.hpp" #include "pomdog/audio/audio_clip.hpp" #include "pomdog/audio/audio_emitter.hpp" #include "pomdog/audio/audio_engine.hpp" #include "pomdog/audio/audio_listener.hpp" #include "pomdog/audio/sound_effect.hpp" #include "pomdog/audio/sound_state.hpp" #include "pomdog/content/asset_builders/pipeline_state_builder.hpp" #include "pomdog/content/asset_builders/shader_builder.hpp" #include "pomdog/content/asset_manager.hpp" #include "pomdog/filesystem/file_system.hpp" #include "pomdog/math/bounding_box.hpp" #include "pomdog/math/bounding_box2d.hpp" #include "pomdog/math/bounding_circle.hpp" #include "pomdog/math/bounding_frustum.hpp" #include "pomdog/math/bounding_sphere.hpp" #include "pomdog/math/color.hpp" #include "pomdog/math/containment_type.hpp" #include "pomdog/math/degree.hpp" #include "pomdog/math/math.hpp" #include "pomdog/math/matrix2x2.hpp" #include "pomdog/math/matrix3x2.hpp" #include "pomdog/math/matrix3x3.hpp" #include "pomdog/math/matrix4x4.hpp" #include "pomdog/math/plane.hpp" #include "pomdog/math/plane_intersection_type.hpp" #include "pomdog/math/point2d.hpp" #include "pomdog/math/point3d.hpp" #include "pomdog/math/quaternion.hpp" #include "pomdog/math/radian.hpp" #include "pomdog/math/ray.hpp" #include "pomdog/math/rectangle.hpp" #include "pomdog/math/vector2.hpp" #include "pomdog/math/vector3.hpp" #include "pomdog/math/vector4.hpp" #include "pomdog/network/array_view.hpp" #include "pomdog/network/http_client.hpp" #include "pomdog/network/http_method.hpp" #include "pomdog/network/http_request.hpp" #include "pomdog/network/http_response.hpp" #include "pomdog/network/io_service.hpp" #include "pomdog/network/tcp_stream.hpp" #include "pomdog/network/tls_stream.hpp" #include "pomdog/network/udp_stream.hpp" #include "pomdog/logging/log.hpp" #include "pomdog/logging/log_channel.hpp" #include "pomdog/logging/log_entry.hpp" #include "pomdog/logging/log_level.hpp" #include "pomdog/graphics/blend_description.hpp" #include "pomdog/graphics/blend_factor.hpp" #include "pomdog/graphics/blend_operation.hpp" #include "pomdog/graphics/buffer_usage.hpp" #include "pomdog/graphics/comparison_function.hpp" #include "pomdog/graphics/constant_buffer.hpp" #include "pomdog/graphics/cull_mode.hpp" #include "pomdog/graphics/depth_stencil_buffer.hpp" #include "pomdog/graphics/depth_stencil_description.hpp" #include "pomdog/graphics/depth_stencil_operation.hpp" #include "pomdog/graphics/effect_annotation.hpp" #include "pomdog/graphics/effect_constant_description.hpp" #include "pomdog/graphics/effect_reflection.hpp" #include "pomdog/graphics/effect_variable.hpp" #include "pomdog/graphics/effect_variable_class.hpp" #include "pomdog/graphics/effect_variable_type.hpp" #include "pomdog/graphics/fill_mode.hpp" #include "pomdog/graphics/graphics_command_list.hpp" #include "pomdog/graphics/graphics_command_queue.hpp" #include "pomdog/graphics/graphics_device.hpp" #include "pomdog/graphics/index_buffer.hpp" #include "pomdog/graphics/index_element_size.hpp" #include "pomdog/graphics/input_classification.hpp" #include "pomdog/graphics/input_element.hpp" #include "pomdog/graphics/input_element_format.hpp" #include "pomdog/graphics/input_layout_description.hpp" #include "pomdog/graphics/input_layout_helper.hpp" #include "pomdog/graphics/pipeline_state.hpp" #include "pomdog/graphics/pipeline_state_description.hpp" #include "pomdog/graphics/presentation_parameters.hpp" #include "pomdog/graphics/primitive_topology.hpp" #include "pomdog/graphics/rasterizer_description.hpp" #include "pomdog/graphics/render_pass.hpp" #include "pomdog/graphics/render_target2d.hpp" #include "pomdog/graphics/render_target_blend_description.hpp" #include "pomdog/graphics/sampler_description.hpp" #include "pomdog/graphics/sampler_state.hpp" #include "pomdog/graphics/shader.hpp" #include "pomdog/graphics/shader_language.hpp" #include "pomdog/graphics/shader_pipeline_stage.hpp" #include "pomdog/graphics/stencil_operation.hpp" #include "pomdog/graphics/surface_format.hpp" #include "pomdog/graphics/texture.hpp" #include "pomdog/graphics/texture2d.hpp" #include "pomdog/graphics/texture_address_mode.hpp" #include "pomdog/graphics/texture_filter.hpp" #include "pomdog/graphics/vertex_buffer.hpp" #include "pomdog/graphics/viewport.hpp" #include "pomdog/input/button_state.hpp" #include "pomdog/input/gamepad.hpp" #include "pomdog/input/gamepad_buttons.hpp" #include "pomdog/input/gamepad_capabilities.hpp" #include "pomdog/input/gamepad_dpad.hpp" #include "pomdog/input/gamepad_state.hpp" #include "pomdog/input/gamepad_thumbsticks.hpp" #include "pomdog/input/gamepad_uuid.hpp" #include "pomdog/input/key_state.hpp" #include "pomdog/input/keyboard.hpp" #include "pomdog/input/keyboard_state.hpp" #include "pomdog/input/keys.hpp" #include "pomdog/input/mouse.hpp" #include "pomdog/input/mouse_buttons.hpp" #include "pomdog/input/mouse_state.hpp" #include "pomdog/input/player_index.hpp" #include "pomdog/input/touch_location.hpp" #include "pomdog/input/touch_location_state.hpp" #include "pomdog/signals/connection.hpp" #include "pomdog/signals/connection_list.hpp" #include "pomdog/signals/delegate.hpp" #include "pomdog/signals/event_queue.hpp" #include "pomdog/signals/scoped_connection.hpp" #include "pomdog/signals/signal.hpp" #include "pomdog/signals/signal_helpers.hpp" #include "pomdog/utility/assert.hpp" #include "pomdog/utility/errors.hpp" #include "pomdog/utility/path_helper.hpp" #include "pomdog/utility/string_helper.hpp" #include "pomdog/basic/export.hpp" #include "pomdog/basic/platform.hpp" #include "pomdog/basic/version.hpp"
38.853503
67
0.812623
mogemimi
ac848d83a6dede8aa29e7e0e403c35e2b9d7b5ce
879
hpp
C++
include/utils/platform.hpp
afreakana/cfs-spmv
cdd139c5d80b774708806298868a456ad8df1669
[ "BSD-3-Clause" ]
1
2021-02-16T12:19:25.000Z
2021-02-16T12:19:25.000Z
include/utils/platform.hpp
afreakana/cfs-spmv
cdd139c5d80b774708806298868a456ad8df1669
[ "BSD-3-Clause" ]
null
null
null
include/utils/platform.hpp
afreakana/cfs-spmv
cdd139c5d80b774708806298868a456ad8df1669
[ "BSD-3-Clause" ]
1
2020-04-30T12:52:48.000Z
2020-04-30T12:52:48.000Z
#ifndef PLATFORM_HPP #define PLATFORM_HPP #include <cmath> #include "cfs_config.hpp" #ifdef _INTEL_COMPILER #define PRAGMA_IVDEP _Pragma("ivdep") #else #define PRAGMA_IVDEP _Pragma("GCC ivdep") //#define PRAGMA_IVDEP #endif namespace cfs { namespace util { using namespace std; enum class Platform { cpu }; enum class Kernel { SpDMV }; enum class Tuning { None, Aggressive }; enum class Format { none, csr, sss, hyb }; inline int iceildiv(const int a, const int b) { return (a + b - 1) / b; } inline bool isEqual(float x, float y) { const float epsilon = 1e-4; return abs(x - y) <= epsilon * abs(x); // see Knuth section 4.2.2 pages 217-218 } inline bool isEqual(double x, double y) { const double epsilon = 1e-8; return abs(x - y) <= epsilon * abs(x); // see Knuth section 4.2.2 pages 217-218 } } // end of namespace util } // end of namespace cfs #endif
20.44186
73
0.688282
afreakana
ac8574ba1f8f6017a639557901393ab589ca2519
918
cpp
C++
LuoguCodes/CF980B.cpp
Anguei/OI-Codes
0ef271e9af0619d4c236e314cd6d8708d356536a
[ "MIT" ]
null
null
null
LuoguCodes/CF980B.cpp
Anguei/OI-Codes
0ef271e9af0619d4c236e314cd6d8708d356536a
[ "MIT" ]
null
null
null
LuoguCodes/CF980B.cpp
Anguei/OI-Codes
0ef271e9af0619d4c236e314cd6d8708d356536a
[ "MIT" ]
null
null
null
#include <cstdio> #include <string> #include <iostream> #include <algorithm> const int kMaxN = 99; char map[4 + 5][kMaxN + 5]; int main() { for (int i = 0; i < 9; ++i) for (int j = 0; j < 99 + 5; ++j) map[i][j] = ';.';; int n, k; std::cin >> n >> k; if (k == 0) { std::cout << "YES" << std::endl; for (int i = 1; i <= 4; ++i) { for (int j = 1; j <= n; ++j) std::cout << "."; std::cout << std::endl; } return 0; } if (k % 2) { map[2][n / 2 + 1] = ';#';; --k; } //int pos = 2; for (int i = 2; i <= 4 - 1; ++i) { for (int j = 2; j < n / 2 + 1; ++j) { if (k <= 0) goto output; map[i][j] = map[i][n - j + 1] = ';#';; k -= 2; } } if (k == 2) map[2][n / 2 + 1] = map[3][n / 2 + 1] = ';#';; output: std::cout << "YES" << std::endl; for (int i = 1; i <= 4; ++i) { for (int j = 1; j <= n; ++j) std::cout << map[i][j]; std::cout << std::endl; } }
17
48
0.400871
Anguei
ac8631435d960d1bee2d98002a8909bba8a22693
13,119
cc
C++
Digit_Example/opt_two_step/gen/opt/J_u_rightToeHeight_digit.cc
prem-chand/Cassie_CFROST
da4bd51442f86e852cbb630cc91c9a380a10b66d
[ "BSD-3-Clause" ]
null
null
null
Digit_Example/opt_two_step/gen/opt/J_u_rightToeHeight_digit.cc
prem-chand/Cassie_CFROST
da4bd51442f86e852cbb630cc91c9a380a10b66d
[ "BSD-3-Clause" ]
null
null
null
Digit_Example/opt_two_step/gen/opt/J_u_rightToeHeight_digit.cc
prem-chand/Cassie_CFROST
da4bd51442f86e852cbb630cc91c9a380a10b66d
[ "BSD-3-Clause" ]
null
null
null
/* * Automatically Generated from Mathematica. * Fri 5 Nov 2021 16:30:17 GMT-04:00 */ #ifdef MATLAB_MEX_FILE #include <stdexcept> #include <cmath> #include<math.h> /** * Copied from Wolfram Mathematica C Definitions file mdefs.hpp * Changed marcos to inline functions (Eric Cousineau) */ inline double Power(double x, double y) { return pow(x, y); } inline double Sqrt(double x) { return sqrt(x); } inline double Abs(double x) { return fabs(x); } inline double Exp(double x) { return exp(x); } inline double Log(double x) { return log(x); } inline double Sin(double x) { return sin(x); } inline double Cos(double x) { return cos(x); } inline double Tan(double x) { return tan(x); } inline double ArcSin(double x) { return asin(x); } inline double ArcCos(double x) { return acos(x); } inline double ArcTan(double x) { return atan(x); } /* update ArcTan function to use atan2 instead. */ inline double ArcTan(double x, double y) { return atan2(y,x); } inline double Sinh(double x) { return sinh(x); } inline double Cosh(double x) { return cosh(x); } inline double Tanh(double x) { return tanh(x); } const double E = 2.71828182845904523536029; const double Pi = 3.14159265358979323846264; const double Degree = 0.01745329251994329576924; inline double Sec(double x) { return 1/cos(x); } inline double Csc(double x) { return 1/sin(x); } #endif /* * Sub functions */ static void output1(double *p_output1,const double *var1) { double t125; double t1504; double t1473; double t1481; double t1506; double t1560; double t1487; double t1508; double t1536; double t1432; double t1561; double t1574; double t1589; double t1611; double t1546; double t1593; double t1603; double t1407; double t1613; double t1645; double t1676; double t1720; double t1608; double t1678; double t1703; double t1325; double t1748; double t1763; double t1783; double t1903; double t1709; double t1851; double t1876; double t1324; double t1906; double t1909; double t1942; double t1960; double t1882; double t1946; double t1952; double t1308; double t1961; double t1966; double t1968; double t1982; double t1957; double t1973; double t1975; double t1295; double t1985; double t1996; double t1999; double t1244; double t90; double t2071; double t2076; double t2082; double t2049; double t2051; double t2065; double t2112; double t2115; double t2129; double t2067; double t2085; double t2091; double t2154; double t2156; double t2157; double t2098; double t2141; double t2148; double t2191; double t2196; double t2198; double t2153; double t2160; double t2180; double t2211; double t2221; double t2222; double t2184; double t2199; double t2201; double t2007; double t2274; double t2283; double t2285; double t2299; double t2302; double t2308; double t2295; double t2309; double t2310; double t2321; double t2326; double t2330; double t2313; double t2337; double t2340; double t2344; double t2347; double t2353; double t2341; double t2359; double t2363; double t2368; double t2371; double t2375; double t2364; double t2380; double t2381; double t2387; double t2390; double t2392; double t2383; double t2400; double t2405; double t2415; double t2420; double t2424; double t2456; double t2459; double t2460; double t2461; double t2464; double t2468; double t2469; double t2467; double t2471; double t2472; double t2488; double t2489; double t2490; double t2481; double t2493; double t2494; double t2498; double t2500; double t2505; double t2497; double t2506; double t2508; double t2511; double t2512; double t2513; double t2509; double t2514; double t2517; double t2522; double t2531; double t2532; double t2560; double t2562; double t2563; double t2567; double t2568; double t2569; double t2571; double t2572; double t2573; double t2570; double t2576; double t2580; double t2582; double t2583; double t2586; double t2581; double t2588; double t2590; double t2592; double t2594; double t2595; double t2591; double t2596; double t2598; double t2609; double t2634; double t2636; double t2659; double t2664; double t2667; double t2668; double t2671; double t2675; double t2684; double t2686; double t2672; double t2688; double t2695; double t2698; double t2699; double t2700; double t2697; double t2702; double t2704; double t2709; double t2710; double t2714; double t2744; double t2750; double t2753; double t2754; double t2760; double t2764; double t2757; double t2767; double t2768; double t2776; double t2780; double t2781; double t2810; double t2811; double t2812; double t2814; double t2816; double t2819; double t2823; double t2824; double t2847; double t2848; double t2850; double t2838; double t2852; double t2853; double t2854; t125 = Sin(var1[4]); t1504 = Cos(var1[21]); t1473 = Cos(var1[4]); t1481 = Sin(var1[21]); t1506 = Sin(var1[5]); t1560 = Cos(var1[22]); t1487 = t1473*t1481; t1508 = -1.*t1504*t125*t1506; t1536 = t1487 + t1508; t1432 = Sin(var1[22]); t1561 = -1.*t1504*t1473; t1574 = -1.*t1481*t125*t1506; t1589 = t1561 + t1574; t1611 = Cos(var1[23]); t1546 = t1432*t1536; t1593 = t1560*t1589; t1603 = t1546 + t1593; t1407 = Sin(var1[23]); t1613 = t1560*t1536; t1645 = -1.*t1432*t1589; t1676 = t1613 + t1645; t1720 = Cos(var1[24]); t1608 = t1407*t1603; t1678 = t1611*t1676; t1703 = t1608 + t1678; t1325 = Sin(var1[24]); t1748 = t1611*t1603; t1763 = -1.*t1407*t1676; t1783 = t1748 + t1763; t1903 = Cos(var1[25]); t1709 = t1325*t1703; t1851 = t1720*t1783; t1876 = t1709 + t1851; t1324 = Sin(var1[25]); t1906 = t1720*t1703; t1909 = -1.*t1325*t1783; t1942 = t1906 + t1909; t1960 = Cos(var1[26]); t1882 = -1.*t1324*t1876; t1946 = t1903*t1942; t1952 = t1882 + t1946; t1308 = Sin(var1[26]); t1961 = t1903*t1876; t1966 = t1324*t1942; t1968 = t1961 + t1966; t1982 = Cos(var1[30]); t1957 = t1308*t1952; t1973 = t1960*t1968; t1975 = t1957 + t1973; t1295 = Sin(var1[30]); t1985 = t1960*t1952; t1996 = -1.*t1308*t1968; t1999 = t1985 + t1996; t1244 = Cos(var1[31]); t90 = Cos(var1[5]); t2071 = t1560*t1473*t90*t1481; t2076 = t1504*t1473*t90*t1432; t2082 = t2071 + t2076; t2049 = t1504*t1560*t1473*t90; t2051 = -1.*t1473*t90*t1481*t1432; t2065 = t2049 + t2051; t2112 = t1611*t2082; t2115 = -1.*t2065*t1407; t2129 = t2112 + t2115; t2067 = t1611*t2065; t2085 = t2082*t1407; t2091 = t2067 + t2085; t2154 = t1720*t2129; t2156 = t2091*t1325; t2157 = t2154 + t2156; t2098 = t1720*t2091; t2141 = -1.*t2129*t1325; t2148 = t2098 + t2141; t2191 = t1903*t2157; t2196 = t2148*t1324; t2198 = t2191 + t2196; t2153 = t1903*t2148; t2160 = -1.*t2157*t1324; t2180 = t2153 + t2160; t2211 = t1960*t2198; t2221 = t2180*t1308; t2222 = t2211 + t2221; t2184 = t1960*t2180; t2199 = -1.*t2198*t1308; t2201 = t2184 + t2199; t2007 = Sin(var1[31]); t2274 = t1481*t125; t2283 = t1504*t1473*t1506; t2285 = t2274 + t2283; t2299 = t1504*t125; t2302 = -1.*t1473*t1481*t1506; t2308 = t2299 + t2302; t2295 = -1.*t1432*t2285; t2309 = t1560*t2308; t2310 = t2295 + t2309; t2321 = t1560*t2285; t2326 = t1432*t2308; t2330 = t2321 + t2326; t2313 = -1.*t1407*t2310; t2337 = t1611*t2330; t2340 = t2313 + t2337; t2344 = t1611*t2310; t2347 = t1407*t2330; t2353 = t2344 + t2347; t2341 = -1.*t1325*t2340; t2359 = t1720*t2353; t2363 = t2341 + t2359; t2368 = t1720*t2340; t2371 = t1325*t2353; t2375 = t2368 + t2371; t2364 = t1324*t2363; t2380 = t1903*t2375; t2381 = t2364 + t2380; t2387 = t1903*t2363; t2390 = -1.*t1324*t2375; t2392 = t2387 + t2390; t2383 = -1.*t1308*t2381; t2400 = t1960*t2392; t2405 = t2383 + t2400; t2415 = t1960*t2381; t2420 = t1308*t2392; t2424 = t2415 + t2420; t2456 = -1.*t1504*t125; t2459 = t1473*t1481*t1506; t2460 = t2456 + t2459; t2461 = -1.*t1560*t2460; t2464 = t2295 + t2461; t2468 = -1.*t1432*t2460; t2469 = t2321 + t2468; t2467 = -1.*t1407*t2464; t2471 = t1611*t2469; t2472 = t2467 + t2471; t2488 = t1611*t2464; t2489 = t1407*t2469; t2490 = t2488 + t2489; t2481 = -1.*t1325*t2472; t2493 = t1720*t2490; t2494 = t2481 + t2493; t2498 = t1720*t2472; t2500 = t1325*t2490; t2505 = t2498 + t2500; t2497 = t1324*t2494; t2506 = t1903*t2505; t2508 = t2497 + t2506; t2511 = t1903*t2494; t2512 = -1.*t1324*t2505; t2513 = t2511 + t2512; t2509 = -1.*t1308*t2508; t2514 = t1960*t2513; t2517 = t2509 + t2514; t2522 = t1960*t2508; t2531 = t1308*t2513; t2532 = t2522 + t2531; t2560 = t1432*t2285; t2562 = t1560*t2460; t2563 = t2560 + t2562; t2567 = -1.*t1407*t2563; t2568 = -1.*t1611*t2469; t2569 = t2567 + t2568; t2571 = t1611*t2563; t2572 = -1.*t1407*t2469; t2573 = t2571 + t2572; t2570 = -1.*t1325*t2569; t2576 = t1720*t2573; t2580 = t2570 + t2576; t2582 = t1720*t2569; t2583 = t1325*t2573; t2586 = t2582 + t2583; t2581 = t1324*t2580; t2588 = t1903*t2586; t2590 = t2581 + t2588; t2592 = t1903*t2580; t2594 = -1.*t1324*t2586; t2595 = t2592 + t2594; t2591 = -1.*t1308*t2590; t2596 = t1960*t2595; t2598 = t2591 + t2596; t2609 = t1960*t2590; t2634 = t1308*t2595; t2636 = t2609 + t2634; t2659 = t1407*t2563; t2664 = t2659 + t2471; t2667 = -1.*t1325*t2664; t2668 = -1.*t1720*t2573; t2671 = t2667 + t2668; t2675 = t1720*t2664; t2684 = -1.*t1325*t2573; t2686 = t2675 + t2684; t2672 = t1324*t2671; t2688 = t1903*t2686; t2695 = t2672 + t2688; t2698 = t1903*t2671; t2699 = -1.*t1324*t2686; t2700 = t2698 + t2699; t2697 = -1.*t1308*t2695; t2702 = t1960*t2700; t2704 = t2697 + t2702; t2709 = t1960*t2695; t2710 = t1308*t2700; t2714 = t2709 + t2710; t2744 = t1325*t2664; t2750 = t2744 + t2576; t2753 = -1.*t1324*t2750; t2754 = t2753 + t2688; t2760 = -1.*t1903*t2750; t2764 = t2760 + t2699; t2757 = -1.*t1308*t2754; t2767 = t1960*t2764; t2768 = t2757 + t2767; t2776 = t1960*t2754; t2780 = t1308*t2764; t2781 = t2776 + t2780; t2810 = t1903*t2750; t2811 = t1324*t2686; t2812 = t2810 + t2811; t2814 = -1.*t1960*t2812; t2816 = t2757 + t2814; t2819 = -1.*t1308*t2812; t2823 = t2776 + t2819; t2824 = t1982*t2823; t2847 = t1308*t2754; t2848 = t1960*t2812; t2850 = t2847 + t2848; t2838 = -1.*t1295*t2823; t2852 = -1.*t1295*t2850; t2853 = t2852 + t2824; t2854 = -1.*t2007*t2853; p_output1[0]=1.; p_output1[1]=0.05456*(t1244*(-1.*t1295*t1975 + t1982*t1999) - 1.*(t1975*t1982 + t1295*t1999)*t2007) + 0.0315*t125*t90; p_output1[2]=0.0315*t1473*t1506 + 0.05456*(t1244*(t1982*t2201 - 1.*t1295*t2222) - 1.*t2007*(t1295*t2201 + t1982*t2222)); p_output1[3]=0.05456*(t1244*(t1982*t2405 - 1.*t1295*t2424) - 1.*t2007*(t1295*t2405 + t1982*t2424)); p_output1[4]=0.05456*(t1244*(t1982*t2517 - 1.*t1295*t2532) - 1.*t2007*(t1295*t2517 + t1982*t2532)); p_output1[5]=0.05456*(t1244*(t1982*t2598 - 1.*t1295*t2636) - 1.*t2007*(t1295*t2598 + t1982*t2636)); p_output1[6]=0.05456*(t1244*(t1982*t2704 - 1.*t1295*t2714) - 1.*t2007*(t1295*t2704 + t1982*t2714)); p_output1[7]=0.05456*(t1244*(t1982*t2768 - 1.*t1295*t2781) - 1.*t2007*(t1295*t2768 + t1982*t2781)); p_output1[8]=0.05456*(-1.*t2007*(t1295*t2816 + t2824) + t1244*(t1982*t2816 + t2838)); p_output1[9]=0.05456*(t1244*(t2838 - 1.*t1982*t2850) + t2854); p_output1[10]=0.05456*(-1.*t1244*(t1295*t2823 + t1982*t2850) + t2854); } #ifdef MATLAB_MEX_FILE #include "mex.h" /* * Main function */ void mexFunction( int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[] ) { size_t mrows, ncols; double *var1; double *p_output1; /* Check for proper number of arguments. */ if( nrhs != 1) { mexErrMsgIdAndTxt("MATLAB:MShaped:invalidNumInputs", "One input(s) required (var1)."); } else if( nlhs > 1) { mexErrMsgIdAndTxt("MATLAB:MShaped:maxlhs", "Too many output arguments."); } /* The input must be a noncomplex double vector or scaler. */ mrows = mxGetM(prhs[0]); ncols = mxGetN(prhs[0]); if( !mxIsDouble(prhs[0]) || mxIsComplex(prhs[0]) || ( !(mrows == 36 && ncols == 1) && !(mrows == 1 && ncols == 36))) { mexErrMsgIdAndTxt( "MATLAB:MShaped:inputNotRealVector", "var1 is wrong."); } /* Assign pointers to each input. */ var1 = mxGetPr(prhs[0]); /* Create matrices for return arguments. */ plhs[0] = mxCreateDoubleMatrix((mwSize) 11, (mwSize) 1, mxREAL); p_output1 = mxGetPr(plhs[0]); /* Call the calculation subroutine. */ output1(p_output1,var1); } #else // MATLAB_MEX_FILE #include "J_u_rightToeHeight_digit.hh" namespace LeftStance { void J_u_rightToeHeight_digit_raw(double *p_output1, const double *var1) { // Call Subroutines output1(p_output1, var1); } } #endif // MATLAB_MEX_FILE
22.311224
122
0.650659
prem-chand
ac87d1e1be13ef149210fbd942410e7b7c7e384f
2,521
cpp
C++
src/api/pipy.cpp
keveinliu/pipy
9a03d33631c8aa8eee2f5acf9aa4d19fcc682b9a
[ "BSL-1.0" ]
1
2021-12-02T02:41:30.000Z
2021-12-02T02:41:30.000Z
src/api/pipy.cpp
keveinliu/pipy
9a03d33631c8aa8eee2f5acf9aa4d19fcc682b9a
[ "BSL-1.0" ]
null
null
null
src/api/pipy.cpp
keveinliu/pipy
9a03d33631c8aa8eee2f5acf9aa4d19fcc682b9a
[ "BSL-1.0" ]
null
null
null
/* * Copyright (c) 2019 by flomesh.io * * Unless prior written consent has been obtained from the copyright * owner, the following shall not be allowed. * * 1. The distribution of any source codes, header files, make files, * or libraries of the software. * * 2. Disclosure of any source codes pertaining to the software to any * additional parties. * * 3. Alteration or removal of any notices in or on the software or * within the documentation included within the software. * * ALL SOURCE CODE AS WELL AS ALL DOCUMENTATION INCLUDED WITH THIS * SOFTWARE IS PROVIDED IN AN “AS IS” CONDITION, 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 "pipy.hpp" #include "codebase.hpp" #include "configuration.hpp" #include "worker.hpp" #include "utils.hpp" namespace pipy { void Pipy::operator()(pjs::Context &ctx, pjs::Object *obj, pjs::Value &ret) { pjs::Value ret_obj; pjs::Object *context_prototype = nullptr; if (!ctx.arguments(0, &context_prototype)) return; if (context_prototype && context_prototype->is_function()) { auto *f = context_prototype->as<pjs::Function>(); (*f)(ctx, 0, nullptr, ret_obj); if (!ctx.ok()) return; if (!ret_obj.is_object()) { ctx.error("function did not return an object"); return; } context_prototype = ret_obj.o(); } try { auto config = Configuration::make(context_prototype); ret.set(config); } catch (std::runtime_error &err) { ctx.error(err); } } } // namespace pipy namespace pjs { using namespace pipy; template<> void ClassDef<Pipy>::init() { super<Function>(); ctor(); method("load", [](Context &ctx, Object*, Value &ret) { std::string filename; if (!ctx.arguments(1, &filename)) return; auto path = utils::path_normalize(filename); ret.set(Codebase::current()->get(path)); }); method("restart", [](Context&, Object*, Value&) { Worker::restart(); }); method("exit", [](Context &ctx, Object*, Value&) { int exit_code = 0; if (!ctx.arguments(0, &exit_code)) return; Worker::exit(exit_code); }); } } // namespace pjs
29.658824
77
0.676716
keveinliu
12c2663764bf2f911c51e7c31ef0d53add7afc91
1,884
cpp
C++
Game/Source/Game/src/MY_Scene_MenuBase.cpp
SweetheartSquad/GameJam2016
e5787a6521add448fde8182ada0bce250ba831ea
[ "MIT" ]
null
null
null
Game/Source/Game/src/MY_Scene_MenuBase.cpp
SweetheartSquad/GameJam2016
e5787a6521add448fde8182ada0bce250ba831ea
[ "MIT" ]
null
null
null
Game/Source/Game/src/MY_Scene_MenuBase.cpp
SweetheartSquad/GameJam2016
e5787a6521add448fde8182ada0bce250ba831ea
[ "MIT" ]
null
null
null
#pragma once #include <MY_Scene_MenuBase.h> #include <RenderSurface.h> #include <StandardFrameBuffer.h> MY_Scene_MenuBase::MY_Scene_MenuBase(Game * _game) : MY_Scene_Base(_game), screenSurfaceShader(new Shader("assets/RenderSurface_2", false, true)), screenSurface(new RenderSurface(screenSurfaceShader)), screenFBO(new StandardFrameBuffer(true)) { } void MY_Scene_MenuBase::update(Step * _step){ // Screen shader update // Screen shaders are typically loaded from a file instead of built using components, so to update their uniforms // we need to use the OpenGL API calls screenSurfaceShader->bindShader(); // remember that we have to bind the shader before it can be updated GLint test = glGetUniformLocation(screenSurfaceShader->getProgramId(), "time"); checkForGlError(0,__FILE__,__LINE__); if(test != -1){ glUniform1f(test, _step->time); checkForGlError(0,__FILE__,__LINE__); } if(keyboard->keyJustDown(GLFW_KEY_L)){ screenSurfaceShader->unload(); screenSurfaceShader->loadFromFile(screenSurfaceShader->vertSource, screenSurfaceShader->fragSource); screenSurfaceShader->load(); } MY_Scene_Base::update(_step); } void MY_Scene_MenuBase::render(sweet::MatrixStack * _matrixStack, RenderOptions * _renderOptions){ // keep our screen framebuffer up-to-date with the game's viewport screenFBO->resize(game->viewPortWidth, game->viewPortHeight); // bind our screen framebuffer FrameBufferInterface::pushFbo(screenFBO); // render the scene MY_Scene_Base::render(_matrixStack, _renderOptions); // unbind our screen framebuffer, rebinding the previously bound framebuffer // since we didn't have one bound before, this will be the default framebuffer (i.e. the one visible to the player) FrameBufferInterface::popFbo(); // render our screen framebuffer using the standard render surface screenSurface->render(screenFBO->getTextureId()); }
34.888889
116
0.778662
SweetheartSquad
12c4d966933ab0e5976f87e85c8ebbf1f4f5303f
4,116
hpp
C++
jni/Player.hpp
kaitokidi/androidSpaceTongue
0c839dd92fe6393fa095735b08cb8966c771c36a
[ "MIT" ]
null
null
null
jni/Player.hpp
kaitokidi/androidSpaceTongue
0c839dd92fe6393fa095735b08cb8966c771c36a
[ "MIT" ]
null
null
null
jni/Player.hpp
kaitokidi/androidSpaceTongue
0c839dd92fe6393fa095735b08cb8966c771c36a
[ "MIT" ]
null
null
null
#ifndef PLAYER_HPP #define PLAYER_HPP #include "utils.hpp" class Player { public: sf::SoundBuffer expbuf; sf::Texture ship; Player() : pos(sf::Vector2f(0,0)), speed(sf::Vector2f(0,0)) { expbuf.loadFromFile("res/explos.ogg"); expl.setBuffer(expbuf); expl.setVolume(100); alive = true; spriteTimer = 0.0; spriteAnimation = 0.0; timeSinceNextSprite = 0.2; angle = speedToRad(speed); ship.loadFromFile("res/ship.png"); sprite.setTexture(ship); spriteHeight = ship.getSize().y; spriteWidth = ship.getSize().x/15; sprite.setTextureRect(sf::IntRect(spriteAnimation*spriteWidth, 0, spriteWidth, spriteHeight)); sprite.setOrigin(sprite.getGlobalBounds().width/2,sprite.getGlobalBounds().height/2); licked = tensioning = false; tipofuerza = 0; } void setPosition(sf::Vector2f newPos){ pos = newPos; sprite.setPosition(pos); } void setSpeed(sf::Vector2f newSpeed){ speed = newSpeed; } void update(float deltaTime) { if (!alive) return; if (licked) timeSinceTriggered += deltaTime; if (tipofuerza==0) evoluciona(deltaTime); else evolucionabis(deltaTime); angle = radToAngle(speedToRad(speed))+90; sprite.setPosition(pos); spriteTimer += deltaTime; if(spriteTimer >= timeSinceNextSprite){ ++spriteAnimation; spriteAnimation = (int)spriteAnimation % 15; } } void draw(sf::RenderWindow &window) { if (!alive) return; sprite.setTextureRect(sf::IntRect(spriteAnimation*spriteWidth, 0, spriteWidth, spriteHeight)); sprite.setRotation(angle);sprite.setScale(sf::Vector2f(scalePlayer,scalePlayer)); window.draw(sprite); } sf::Vector2f getPosition() { return pos; } void setLicked(bool b, sf::Vector2f cPos, int tipofuerza) { this->tipofuerza = tipofuerza; camaleonPos = cPos; licked = b; if (!b) { tensioning = false; timeSinceTriggered = 0; } } void setAlive(bool b) { if (!b && alive) { alive = b; expl.play(); } } bool isAlive() { return alive; } sf::Vector2f getSpeed() { return speed; } sf::CircleShape getBox() { sf::CircleShape aux(spriteWidth/2*scalePlayer*0.5); aux.setPosition(pos); return aux; } //Private functions private: //Player properties sf::Sound expl; sf::Vector2f pos; sf::Sprite sprite; sf::Vector2f speed; float angle; float spriteTimer; float spriteWidth; float spriteHeight; float spriteAnimation; float timeSinceNextSprite; int tipofuerza; // Camaleon related things bool licked; bool tensioning; float timeSinceTriggered; sf::Vector2f camaleonPos; void evoluciona(float fdelta){ double delta=fdelta; point p=vector2point(pos); point v=vector2point(speed); point c=vector2point(camaleonPos); if (not licked || timeSinceTriggered < animationTime) { p+=v*delta; pos=point2vector(p); return; } if (not tensioning) { p+=v*delta; pos=point2vector(p); if (prodesc(v,p-c)>=0) tensioning=true; return; } p-=c; double modulov=abs(v); double desp=modulov*delta; double r=abs(p); double alfa=desp/r; int signo=prodvec(p,v)>0?1:-1; p*=std::polar(1.0,signo*alfa); v=p*std::polar(1.0,signo*M_PI/2.0); v=(modulov/abs(v))*v; p+=c; pos=point2vector(p); speed=point2vector(v); } double fuerza(double distancia) { if (tipofuerza==1) return sqrt(abs(distancia))*5; if (tipofuerza==2) return abs(distancia)/200; //return 30; //return 5000000/(distancia*distancia); } void evolucionabis(float fdelta) { double delta=fdelta; point p=vector2point(pos); point v=vector2point(speed); if (not licked || timeSinceTriggered < animationTime) { p+=v*delta; pos=point2vector(p); return; } point c=vector2point(camaleonPos); int pasos=100; delta/=pasos; for (int paso=0;paso<pasos;paso++) { point dir=c-p; v=v+(fuerza(abs(dir))*delta/abs(dir))*dir; p=p+v*delta; } pos=point2vector(p); speed=point2vector(v); } // Comido bool alive; }; #endif // PLAYER_HPP
20.683417
98
0.654276
kaitokidi
12cae306250db20416675aa5d23e43b3faae64ed
4,176
cpp
C++
Codeforces/Gym102823B.cpp
HeRaNO/OI-ICPC-Codes
4a4639cd3e347b472520065ca6ab8caadde6906d
[ "MIT" ]
18
2019-01-01T13:16:59.000Z
2022-02-28T04:51:50.000Z
Codeforces/Gym102823B.cpp
HeRaNO/OI-ICPC-Codes
4a4639cd3e347b472520065ca6ab8caadde6906d
[ "MIT" ]
null
null
null
Codeforces/Gym102823B.cpp
HeRaNO/OI-ICPC-Codes
4a4639cd3e347b472520065ca6ab8caadde6906d
[ "MIT" ]
5
2019-09-13T08:48:17.000Z
2022-02-19T06:59:03.000Z
#include<bits/stdc++.h> using namespace std; #define fi first #define se second #define SZ(x) ((int)x.size()) #define lowbit(x) x&-x #define pb push_back #define ALL(x) (x).begin(),(x).end() #define UNI(x) sort(ALL(x)),x.resize(unique(ALL(x))-x.begin()) #define GETPOS(c,x) (lower_bound(ALL(c),x)-c.begin()) #define LEN(x) strlen(x) #define MS0(x) memset((x),0,sizeof((x))) #define Rint register int #define ls (u<<1) #define rs (u<<1|1) typedef unsigned int unit; typedef long long ll; typedef unsigned long long ull; typedef double db; typedef pair<int,int> pii; typedef pair<ll,ll> pll; typedef vector<int> Vi; typedef vector<ll> Vll; typedef vector<pii> Vpii; template<class T> void _R(T &x) { cin >> x; } void _R(int &x) { scanf("%d", &x); } void _R(ll &x) { scanf("%lld", &x); } void _R(ull &x) { scanf("%llu", &x); } void _R(double &x) { scanf("%lf", &x); } void _R(char &x) { scanf(" %c", &x); } void _R(char *x) { scanf("%s", x); } void R() {} template<class T, class... U> void R(T &head, U &... tail) { _R(head); R(tail...); } template<class T> void _W(const T &x) { cout << x; } void _W(const int &x) { printf("%d", x); } void _W(const ll &x) { printf("%lld", x); } void _W(const double &x) { printf("%.16f", x); } void _W(const char &x) { putchar(x); } void _W(const char *x) { printf("%s", x); } template<class T,class U> void _W(const pair<T,U> &x) {_W(x.fi);putchar(' '); _W(x.se);} template<class T> void _W(const vector<T> &x) { for (auto i = x.begin(); i != x.end(); _W(*i++)) if (i != x.cbegin()) putchar(' '); } void W() {} template<class T, class... U> void W(const T &head, const U &... tail) { _W(head); putchar(sizeof...(tail) ? ' ' : '\n'); W(tail...); } const int MOD=998244353,mod=998244353; ll qpow(ll a,ll b) {ll res=1;a%=MOD; assert(b>=0); for(;b;b>>=1){if(b&1)res=res*a%MOD;a=a*a%MOD;}return res;} const int MAXN=5e5+10,MAXM=2e6+10; const int INF=INT_MAX,SINF=0x3f3f3f3f; const ll llINF=LLONG_MAX; const int inv2=(MOD+1)/2; const int Lim=1<<20; int add (int a, int b) { return (a += b) >= mod ? a - mod : a; } int sub (int a, int b) { return (a -= b) >= 0 ? a : a + mod; } int mul (long long a, int b) { return a * b % mod; } int ksm (ll a, ll b) { ll ret = 1; while (b) { if (b & 1) ret = 1ll * ret * a % mod; a = 1ll * a * a % mod; b >>= 1; } return ret; } int rev[Lim+5],lg2[Lim+5],rt[Lim+5],irt[Lim+5]; int k,lim,type; void init() //��ԭ�� { for(int i=2;i<=Lim;i++)lg2[i]=lg2[i>>1]+1; rt[0]=1; rt[1]=ksm(3,(MOD-1)/Lim); //��һ��ԭ�� irt[0]=1; irt[1]=ksm(rt[1],MOD-2); //����С for(int i=2;i<=Lim;i++) { rt[i]=mul(rt[i-1],rt[1]); irt[i]=mul(irt[i-1],irt[1]); } } void NTT(Vi &f,int type,int lim) { f.resize(lim); int w,y,l=lg2[lim]-1; for(int i=1;i<lim;i++) { rev[i]=(rev[i>>1]>>1)|((i&1)<<l); if(i>=rev[i])continue; swap(f[i],f[rev[i]]); //���� } l=Lim>>1; for(int mid=1;mid<lim;mid<<=1) { for(int j=0;j<lim;j+=(mid<<1)) { for(int k=0;k<mid;k++) { w=type==1?rt[l*k]:irt[l*k]; y=mul(w,f[j|k|mid]); f[j|k|mid]=sub(f[j|k],y); f[j|k]=add(f[j|k],y); } } l>>=1; } if(type==1)return; y=ksm(lim,MOD-2); for(int i=0;i<lim;i++) f[i]=mul(f[i],y); } void NTTTMD(Vi &F,Vi &G) { int n=SZ(F)+SZ(G); lim=1; while(lim<=n)lim<<=1; F.resize(lim);G.resize(lim); NTT(F,1,lim),NTT(G,1,lim); for(int i=0;i<lim;i++)F[i]=mul(F[i],G[i]); NTT(F,-1,lim); F.resize(n-1); } int n,a[MAXN],L,m; ll inv[MAXN]; int getinv(int x) { if(x==0)return 1; return ksm(x,MOD-2); } void solve() { R(n,L,m); for(int i=0;i<n;i++)R(a[i]); reverse(a,a+n); Vi t1,t2; t1.resize(n),t2.resize(n); ll tmp=1;t1[0]=tmp; for(int i=1;i<n;i++) { tmp=mul(tmp,m-1+i); tmp=mul(tmp,inv[i]); t1[i]=tmp; } tmp=1; t2[0]=1; for(int i=1;i*L<n&&i<=m;i++) { tmp=mul(tmp,m-i+1); tmp=mul(tmp,inv[i]); t2[i*L]=tmp; if(i&1)t2[i*L]=(MOD-t2[i*L])%MOD; } NTTTMD(t1,t2); Vi t3; for(int i=0;i<n;i++)t3.pb(a[i]); NTTTMD(t3,t1); t3.resize(n); reverse(ALL(t3)); W(t3); } int main() { inv[1]=1; for (int i=2;i<=300000;i++) inv[i]=1ll*(MOD-MOD/i)*inv[MOD%i]%MOD; init(); int T; scanf("%d",&T); for(int kase=1;kase<=T;kase++) { printf("Case %d: ",kase); solve(); } return 0; }
24.710059
135
0.554358
HeRaNO
12cc90aa410589156f8780d3316bea673f55b192
22,105
cpp
C++
cocos2d-x-2.2/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioSceneTest/SceneEditorTest.cpp
centrallydecentralized/ufo
29e8f9ce4ce92635ed22f8a051c917cfe6e0313d
[ "BSD-3-Clause" ]
58
2015-01-05T04:40:48.000Z
2021-12-17T06:01:28.000Z
cocos2d-x-2.2/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioSceneTest/SceneEditorTest.cpp
centrallydecentralized/ufo
29e8f9ce4ce92635ed22f8a051c917cfe6e0313d
[ "BSD-3-Clause" ]
null
null
null
cocos2d-x-2.2/samples/Cpp/TestCpp/Classes/ExtensionsTest/CocoStudioSceneTest/SceneEditorTest.cpp
centrallydecentralized/ufo
29e8f9ce4ce92635ed22f8a051c917cfe6e0313d
[ "BSD-3-Clause" ]
46
2015-01-03T06:20:54.000Z
2020-04-18T13:32:52.000Z
#include "cocos-ext.h" #include "../ExtensionsTest.h" #include "SceneEditorTest.h" #include "TriggerCode/EventDef.h" #include "../../testResource.h" using namespace cocos2d; using namespace cocos2d::extension; using namespace cocos2d::ui; CCLayer *Next(); CCLayer *Back(); CCLayer *Restart(); static int s_nIdx = -1; CCLayer *createTests(int index) { CCLayer *pLayer = NULL; switch(index) { case TEST_LOADSCENEEDITORFILE: pLayer = new LoadSceneEdtiorFileTest(); break; case TEST_SPIRTECOMPONENT: pLayer = new SpriteComponentTest(); break; case TEST_ARMATURECOMPONENT: pLayer = new ArmatureComponentTest(); break; case TEST_UICOMPONENT: pLayer = new UIComponentTest(); break; case TEST_TMXMAPCOMPONENT: pLayer = new TmxMapComponentTest(); break; case TEST_PARTICLECOMPONENT: pLayer = new ParticleComponentTest(); break; case TEST_EFEECTCOMPONENT: pLayer = new EffectComponentTest(); break; case TEST_BACKGROUNDCOMPONENT: pLayer = new BackgroundComponentTest(); break; case TEST_ATTRIBUTECOMPONENT: pLayer = new AttributeComponentTest(); break; case TEST_TRIGGER: pLayer = new TriggerTest(); pLayer->init(); break; default: break; } return pLayer; } CCLayer *Next() { ++s_nIdx; s_nIdx = s_nIdx % TEST_SCENEEDITOR_COUNT; CCLayer *pLayer = createTests(s_nIdx); pLayer->autorelease(); return pLayer; } CCLayer *Back() { --s_nIdx; if( s_nIdx < 0 ) s_nIdx += TEST_SCENEEDITOR_COUNT; CCLayer *pLayer = createTests(s_nIdx); pLayer->autorelease(); return pLayer; } CCLayer *Restart() { CCLayer *pLayer = createTests(s_nIdx); pLayer->autorelease(); return pLayer; } SceneEditorTestScene::SceneEditorTestScene(bool bPortrait) { TestScene::init(); } void SceneEditorTestScene::runThisTest() { s_nIdx = -1; addChild(Next()); CCDirector::sharedDirector()->replaceScene(this); } void SceneEditorTestScene::MainMenuCallback(CCObject *pSender) { TestScene::MainMenuCallback(pSender); } const char* SceneEditorTestLayer::m_loadtypeStr[2] = {"change to load \nwith binary file","change to load \nwith json file"}; void SceneEditorTestLayer::onEnter() { CCLayer::onEnter(); // add title and subtitle std::string str = title(); const char *pTitle = str.c_str(); CCLabelTTF *label = CCLabelTTF::create(pTitle, "Arial", 18); label->setColor(ccc3(255, 255, 255)); addChild(label, 100, 10000); label->setPosition( ccp(VisibleRect::center().x, VisibleRect::top().y - 30) ); std::string strSubtitle = subtitle(); if( ! strSubtitle.empty() ) { CCLabelTTF *l = CCLabelTTF::create(strSubtitle.c_str(), "Arial", 18); l->setColor(ccc3(0, 0, 0)); addChild(l, 1, 10001); l->setPosition( ccp(VisibleRect::center().x, VisibleRect::top().y - 60) ); } // change button m_isCsbLoad = false; m_loadtypelb = CCLabelTTF::create(m_loadtypeStr[0], "Arial", 12); // #endif CCMenuItemLabel* itemlb = CCMenuItemLabel::create(m_loadtypelb, this, menu_selector(SceneEditorTestLayer::changeLoadTypeCallback)); CCMenu* loadtypemenu = CCMenu::create(itemlb, NULL); loadtypemenu->setPosition(ccp(VisibleRect::rightTop().x -50,VisibleRect::rightTop().y -20)); addChild(loadtypemenu,100); // add menu backItem = CCMenuItemImage::create(s_pPathB1, s_pPathB2, this, menu_selector(SceneEditorTestLayer::backCallback) ); restartItem = CCMenuItemImage::create(s_pPathR1, s_pPathR2, this, menu_selector(SceneEditorTestLayer::restartCallback) ); nextItem = CCMenuItemImage::create(s_pPathF1, s_pPathF2, this, menu_selector(SceneEditorTestLayer::nextCallback) ); CCMenu *menu = CCMenu::create(backItem, restartItem, nextItem, NULL); float fScale = 0.5f; menu->setPosition(ccp(0, 0)); backItem->setPosition(ccp(VisibleRect::center().x - restartItem->getContentSize().width * 2 * fScale, VisibleRect::bottom().y + restartItem->getContentSize().height / 2)); backItem->setScale(fScale); restartItem->setPosition(ccp(VisibleRect::center().x, VisibleRect::bottom().y + restartItem->getContentSize().height / 2)); restartItem->setScale(fScale); nextItem->setPosition(ccp(VisibleRect::center().x + restartItem->getContentSize().width * 2 * fScale, VisibleRect::bottom().y + restartItem->getContentSize().height / 2)); nextItem->setScale(fScale); addChild(menu, 100); setShaderProgram(CCShaderCache::sharedShaderCache()->programForKey(kCCShader_PositionTextureColor)); } void SceneEditorTestLayer::onExit() { removeAllChildren(); backItem = restartItem = nextItem = NULL; } std::string SceneEditorTestLayer::title() { return "SceneReader Test LoadSceneEditorFile"; } std::string SceneEditorTestLayer::subtitle() { return ""; } void SceneEditorTestLayer::restartCallback(CCObject *pSender) { CCScene *s = new SceneEditorTestScene(); s->addChild(Restart()); CCDirector::sharedDirector()->replaceScene(s); s->release(); } void SceneEditorTestLayer::nextCallback(CCObject *pSender) { CCScene *s = new SceneEditorTestScene(); s->addChild(Next()); CCDirector::sharedDirector()->replaceScene(s); s->release(); } void SceneEditorTestLayer::backCallback(CCObject *pSender) { CCScene *s = new SceneEditorTestScene(); s->addChild(Back()); CCDirector::sharedDirector()->replaceScene(s); s->release(); } void SceneEditorTestLayer::draw() { CCLayer::draw(); } void SceneEditorTestLayer::changeLoadTypeCallback( CCObject *pSender) { m_isCsbLoad = !m_isCsbLoad; m_loadtypelb->setString(m_loadtypeStr[(int)m_isCsbLoad]); loadFileChangeHelper(m_filePathName); if(m_rootNode != NULL) { this->removeChild(m_rootNode); m_rootNode = SceneReader::sharedSceneReader()->createNodeWithSceneFile(m_filePathName.c_str()); if (m_rootNode == NULL) { return ; } defaultPlay(); this->addChild(m_rootNode); } } void SceneEditorTestLayer::loadFileChangeHelper(string& filePathName) { int n = filePathName.find_last_of("."); if(-1 == n) return; filePathName = filePathName.substr(0,n); if(m_isCsbLoad) filePathName.append(".csb"); else filePathName.append(".json"); } LoadSceneEdtiorFileTest::LoadSceneEdtiorFileTest() { } LoadSceneEdtiorFileTest::~LoadSceneEdtiorFileTest() { } std::string LoadSceneEdtiorFileTest::title() { return "LoadSceneEdtiorFile Test"; } void LoadSceneEdtiorFileTest::onEnter() { SceneEditorTestLayer::onEnter(); do { CCNode *root = createGameScene(); CC_BREAK_IF(!root); this->addChild(root, 0, 1); } while (0); } void LoadSceneEdtiorFileTest::onExit() { CCArmatureDataManager::purge(); SceneReader::purge(); ActionManager::purge(); GUIReader::purge(); SceneEditorTestLayer::onExit(); } cocos2d::CCNode* LoadSceneEdtiorFileTest::createGameScene() { m_filePathName = "scenetest/LoadSceneEdtiorFileTest/FishJoy2.json"; //default is json m_rootNode = SceneReader::sharedSceneReader()->createNodeWithSceneFile(m_filePathName.c_str()); if (m_rootNode == NULL) { return NULL; } defaultPlay(); return m_rootNode; } void LoadSceneEdtiorFileTest::defaultPlay() { cocos2d::extension::ActionManager::shareManager()->playActionByName("startMenu_1.json","Animation1"); } SpriteComponentTest::SpriteComponentTest() { } SpriteComponentTest::~SpriteComponentTest() { } std::string SpriteComponentTest::title() { return "Sprite Component Test"; } void SpriteComponentTest::onEnter() { SceneEditorTestLayer::onEnter(); do { CCNode *root = createGameScene(); CC_BREAK_IF(!root); this->addChild(root, 0, 1); } while (0); } void SpriteComponentTest::onExit() { CCArmatureDataManager::purge(); SceneReader::purge(); ActionManager::purge(); GUIReader::purge(); SceneEditorTestLayer::onExit(); } cocos2d::CCNode* SpriteComponentTest::createGameScene() { m_filePathName = "scenetest/SpriteComponentTest/SpriteComponentTest.json"; m_rootNode = SceneReader::sharedSceneReader()->createNodeWithSceneFile(m_filePathName.c_str()); if (m_rootNode == NULL) { return NULL; } defaultPlay(); return m_rootNode; } void SpriteComponentTest::defaultPlay() { CCActionInterval* action1 = CCBlink::create(2, 10); CCActionInterval* action2 = CCBlink::create(2, 5); CCComRender *pSister1 = static_cast<CCComRender*>(m_rootNode->getChildByTag(10003)->getComponent("CCSprite")); pSister1->getNode()->runAction(action1); CCComRender *pSister2 = static_cast<CCComRender*>(m_rootNode->getChildByTag(10004)->getComponent("CCSprite")); pSister2->getNode()->runAction(action2); } ArmatureComponentTest::ArmatureComponentTest() { } ArmatureComponentTest::~ArmatureComponentTest() { } std::string ArmatureComponentTest::title() { return "Armature Component Test"; } void ArmatureComponentTest::onEnter() { SceneEditorTestLayer::onEnter(); do { CCNode *root = createGameScene(); CC_BREAK_IF(!root); this->addChild(root, 0, 1); } while (0); } void ArmatureComponentTest::onExit() { CCArmatureDataManager::purge(); SceneReader::purge(); ActionManager::purge(); GUIReader::purge(); SceneEditorTestLayer::onExit(); } cocos2d::CCNode* ArmatureComponentTest::createGameScene() { m_filePathName = "scenetest/ArmatureComponentTest/ArmatureComponentTest.json"; m_rootNode = SceneReader::sharedSceneReader()->createNodeWithSceneFile(m_filePathName.c_str()); if (m_rootNode == NULL) { return NULL; } defaultPlay(); return m_rootNode; } void ArmatureComponentTest::defaultPlay() { CCComRender *pBlowFish = static_cast<CCComRender*>(m_rootNode->getChildByTag(10007)->getComponent("CCArmature")); pBlowFish->getNode()->runAction(CCMoveBy::create(10.0f, ccp(-1000.0f, 0))); CCComRender *pButterflyfish = static_cast<CCComRender*>(m_rootNode->getChildByTag(10008)->getComponent("CCArmature")); pButterflyfish->getNode()->runAction(CCMoveBy::create(10.0f, ccp(-1000.0f, 0))); } UIComponentTest::UIComponentTest() { } UIComponentTest::~UIComponentTest() { } std::string UIComponentTest::title() { return "UI Component Test"; } void UIComponentTest::onEnter() { SceneEditorTestLayer::onEnter(); do { CCNode *root = createGameScene(); CC_BREAK_IF(!root); this->addChild(root, 0, 1); } while (0); } void UIComponentTest::onExit() { CCArmatureDataManager::purge(); SceneReader::purge(); ActionManager::purge(); GUIReader::purge(); SceneEditorTestLayer::onExit(); } cocos2d::CCNode* UIComponentTest::createGameScene() { m_filePathName = "scenetest/UIComponentTest/UIComponentTest.json"; m_rootNode = SceneReader::sharedSceneReader()->createNodeWithSceneFile(m_filePathName.c_str()); if (m_rootNode == NULL) { return NULL; } defaultPlay(); return m_rootNode; } void UIComponentTest::touchEvent(CCObject *pSender, TouchEventType type) { switch (type) { case TOUCH_EVENT_BEGAN: { CCComRender *pBlowFish = static_cast<CCComRender*>(m_rootNode->getChildByTag(10010)->getComponent("CCArmature")); pBlowFish->getNode()->runAction(CCMoveBy::create(10.0f, ccp(-1000.0f, 0))); CCComRender *pButterflyfish = static_cast<CCComRender*>(m_rootNode->getChildByTag(10011)->getComponent("CCArmature")); pButterflyfish->getNode()->runAction(CCMoveBy::create(10.0f, ccp(-1000.0f, 0))); } break; default: break; } } void UIComponentTest::defaultPlay() { CCComRender *render = static_cast<CCComRender*>(m_rootNode->getChildByTag(10025)->getComponent("GUIComponent")); cocos2d::ui::TouchGroup* touchGroup = static_cast<cocos2d::ui::TouchGroup*>(render->getNode()); UIWidget* widget = static_cast<UIWidget*>(touchGroup->getWidgetByName("Panel_154")); UIButton* button = static_cast<UIButton*>(widget->getChildByName("Button_156")); button->addTouchEventListener(this, toucheventselector(UIComponentTest::touchEvent)); } TmxMapComponentTest::TmxMapComponentTest() { } TmxMapComponentTest::~TmxMapComponentTest() { } std::string TmxMapComponentTest::title() { return "TmxMap Component Test"; } void TmxMapComponentTest::onEnter() { SceneEditorTestLayer::onEnter(); do { CCNode *root = createGameScene(); CC_BREAK_IF(!root); this->addChild(root, 0, 1); } while (0); } void TmxMapComponentTest::onExit() { CCArmatureDataManager::purge(); SceneReader::purge(); ActionManager::purge(); GUIReader::purge(); SceneEditorTestLayer::onExit(); } cocos2d::CCNode* TmxMapComponentTest::createGameScene() { m_filePathName = "scenetest/TmxMapComponentTest/TmxMapComponentTest.json"; m_rootNode = SceneReader::sharedSceneReader()->createNodeWithSceneFile(m_filePathName.c_str()); if (m_rootNode == NULL) { return NULL; } defaultPlay(); return m_rootNode; } void TmxMapComponentTest::defaultPlay() { CCComRender *tmxMap = static_cast<CCComRender*>(m_rootNode->getChildByTag(10015)->getComponent("CCTMXTiledMap")); CCActionInterval *actionTo = CCSkewTo::create(2, 0.f, 2.f); CCActionInterval *rotateTo = CCRotateTo::create(2, 61.0f); CCActionInterval *actionScaleTo = CCScaleTo::create(2, -0.44f, 0.47f); CCActionInterval *actionScaleToBack = CCScaleTo::create(2, 1.0f, 1.0f); CCActionInterval *rotateToBack = CCRotateTo::create(2, 0); CCActionInterval *actionToBack = CCSkewTo::create(2, 0, 0); tmxMap->getNode()->runAction(CCSequence::create(actionTo, actionToBack, NULL)); tmxMap->getNode()->runAction(CCSequence::create(rotateTo, rotateToBack, NULL)); tmxMap->getNode()->runAction(CCSequence::create(actionScaleTo, actionScaleToBack, NULL)); } ParticleComponentTest::ParticleComponentTest() { } ParticleComponentTest::~ParticleComponentTest() { } std::string ParticleComponentTest::title() { return "Particle Component Test"; } void ParticleComponentTest::onEnter() { SceneEditorTestLayer::onEnter(); do { CCNode *root = createGameScene(); CC_BREAK_IF(!root); this->addChild(root, 0, 1); } while (0); } void ParticleComponentTest::onExit() { CCArmatureDataManager::purge(); SceneReader::purge(); ActionManager::purge(); GUIReader::purge(); SceneEditorTestLayer::onExit(); } cocos2d::CCNode* ParticleComponentTest::createGameScene() { m_filePathName = "scenetest/ParticleComponentTest/ParticleComponentTest.json"; m_rootNode = SceneReader::sharedSceneReader()->createNodeWithSceneFile(m_filePathName.c_str()); if (m_rootNode == NULL) { return NULL; } defaultPlay(); return m_rootNode; } void ParticleComponentTest::defaultPlay() { CCComRender* Particle = static_cast<CCComRender*>(m_rootNode->getChildByTag(10020)->getComponent("CCParticleSystemQuad")); CCActionInterval* jump = CCJumpBy::create(5, ccp(-500,0), 50, 4); CCFiniteTimeAction* action = CCSequence::create( jump, jump->reverse(), NULL); Particle->getNode()->runAction(action); } EffectComponentTest::EffectComponentTest() { } EffectComponentTest::~EffectComponentTest() { } std::string EffectComponentTest::title() { return "Effect Component Test"; } void EffectComponentTest::onEnter() { SceneEditorTestLayer::onEnter(); do { CCNode *root = createGameScene(); CC_BREAK_IF(!root); this->addChild(root, 0, 1); } while (0); } void EffectComponentTest::onExit() { CCArmatureDataManager::purge(); SceneReader::purge(); ActionManager::purge(); GUIReader::purge(); SceneEditorTestLayer::onExit(); } cocos2d::CCNode* EffectComponentTest::createGameScene() { m_filePathName = "scenetest/EffectComponentTest/EffectComponentTest.json"; m_rootNode = SceneReader::sharedSceneReader()->createNodeWithSceneFile(m_filePathName.c_str()); if (m_rootNode == NULL) { return NULL; } defaultPlay(); return m_rootNode; } void EffectComponentTest::animationEvent(cocos2d::extension::CCArmature *armature, cocos2d::extension::MovementEventType movementType, const char *movementID) { std::string id = movementID; if (movementType == LOOP_COMPLETE) { if (id.compare("Fire") == 0) { CCComAudio *pAudio = static_cast<CCComAudio*>(m_rootNode->getChildByTag(10015)->getComponent("CCComAudio")); pAudio->playEffect(); } } } void EffectComponentTest::defaultPlay() { CCComRender *pRender = static_cast<CCComRender*>(m_rootNode->getChildByTag(10015)->getComponent("CCArmature")); CCArmature *pAr = static_cast<CCArmature*>(pRender->getNode()); pAr->getAnimation()->setMovementEventCallFunc(this, movementEvent_selector(EffectComponentTest::animationEvent)); } BackgroundComponentTest::BackgroundComponentTest() { } BackgroundComponentTest::~BackgroundComponentTest() { } std::string BackgroundComponentTest::title() { return "Background Component Test"; } void BackgroundComponentTest::onEnter() { SceneEditorTestLayer::onEnter(); do { CCNode *root = createGameScene(); CC_BREAK_IF(!root); this->addChild(root, 0, 1); } while (0); } void BackgroundComponentTest::onExit() { CCArmatureDataManager::purge(); SceneReader::purge(); ActionManager::purge(); GUIReader::purge(); SceneEditorTestLayer::onExit(); } cocos2d::CCNode* BackgroundComponentTest::createGameScene() { m_filePathName = "scenetest/BackgroundComponentTest/BackgroundComponentTest.json"; m_rootNode = SceneReader::sharedSceneReader()->createNodeWithSceneFile(m_filePathName.c_str()); if (m_rootNode == NULL) { return NULL; } defaultPlay(); return m_rootNode; } void BackgroundComponentTest::defaultPlay() { cocos2d::extension::ActionManager::shareManager()->playActionByName("startMenu_1.json","Animation1"); CCComAudio *Audio = static_cast<CCComAudio*>(m_rootNode->getComponent("CCBackgroundAudio")); Audio->playBackgroundMusic(); } AttributeComponentTest::AttributeComponentTest() { } AttributeComponentTest::~AttributeComponentTest() { } std::string AttributeComponentTest::title() { return "Attribute Component Test"; } void AttributeComponentTest::onEnter() { SceneEditorTestLayer::onEnter(); do { CCNode *root = createGameScene(); initData(); CC_BREAK_IF(!root); this->addChild(root, 0, 1); } while (0); } void AttributeComponentTest::onExit() { CCArmatureDataManager::purge(); SceneReader::purge(); ActionManager::purge(); GUIReader::purge(); SceneEditorTestLayer::onExit(); } bool AttributeComponentTest::initData() { bool bRet = false; do { CC_BREAK_IF(m_rootNode == NULL); CCComAttribute *pAttribute = static_cast<CCComAttribute*>(m_rootNode->getChildByTag(10015)->getComponent("CCComAttribute")); CCLog("Name: %s, HP: %f, MP: %f", pAttribute->getCString("name"), pAttribute->getFloat("maxHP"), pAttribute->getFloat("maxMP")); bRet = true; } while (0); return bRet; } cocos2d::CCNode* AttributeComponentTest::createGameScene() { m_filePathName = "scenetest/AttributeComponentTest/AttributeComponentTest.json"; m_rootNode = SceneReader::sharedSceneReader()->createNodeWithSceneFile(m_filePathName.c_str()); if (m_rootNode == NULL) { return NULL; } return m_rootNode; } void AttributeComponentTest::defaultPlay() { initData(); } TriggerTest::TriggerTest() { m_rootNode = NULL; } TriggerTest::~TriggerTest() { } std::string TriggerTest::title() { return "Trigger Test"; } bool TriggerTest::init() { sendEvent(TRIGGEREVENT_INITSCENE); return true; } void TriggerTest::onEnter() { SceneEditorTestLayer::onEnter(); CCNode *root = createGameScene(); this->addChild(root, 0, 1); } void TriggerTest::onExit() { sendEvent(TRIGGEREVENT_LEAVESCENE); this->unschedule(schedule_selector(TriggerTest::gameLogic)); this->setTouchEnabled(false); CCArmatureDataManager::purge(); SceneReader::purge(); ActionManager::purge(); GUIReader::purge(); SceneEditorTestLayer::onExit(); } bool TriggerTest::ccTouchBegan(CCTouch *pTouch, CCEvent *pEvent) { sendEvent(TRIGGEREVENT_TOUCHBEGAN); return true; } void TriggerTest::ccTouchMoved(CCTouch *pTouch, CCEvent *pEvent) { sendEvent(TRIGGEREVENT_TOUCHMOVED); } void TriggerTest::ccTouchEnded(CCTouch *pTouch, CCEvent *pEvent) { sendEvent(TRIGGEREVENT_TOUCHENDED); } void TriggerTest::ccTouchCancelled(CCTouch *pTouch, CCEvent *pEvent) { sendEvent(TRIGGEREVENT_TOUCHCANCELLED); } void TriggerTest::gameLogic(float dt) { sendEvent(TRIGGEREVENT_UPDATESCENE); } static ActionObject* actionObject = NULL; cocos2d::CCNode* TriggerTest::createGameScene() { m_filePathName = "scenetest/TriggerTest/TriggerTest.json"; m_rootNode = SceneReader::sharedSceneReader()->createNodeWithSceneFile(m_filePathName.c_str()); if (m_rootNode == NULL) { return NULL; } defaultPlay(); return m_rootNode; } void TriggerTest::defaultPlay() { //ui action actionObject = cocos2d::extension::ActionManager::shareManager()->playActionByName("startMenu_1.json","Animation1"); this->schedule(schedule_selector(TriggerTest::gameLogic)); this->setTouchEnabled(true); this->setTouchMode(kCCTouchesOneByOne); sendEvent(TRIGGEREVENT_ENTERSCENE); }
24.977401
176
0.688803
centrallydecentralized
12ccb19ceb3c1569112a3e7b2c3147bd87d652aa
12,812
cpp
C++
src/windows/Undo.cpp
hhyyrylainen/DualViewPP
1fb4a1db85a8509342e16d68c75d4ec7721ced9e
[ "MIT" ]
null
null
null
src/windows/Undo.cpp
hhyyrylainen/DualViewPP
1fb4a1db85a8509342e16d68c75d4ec7721ced9e
[ "MIT" ]
null
null
null
src/windows/Undo.cpp
hhyyrylainen/DualViewPP
1fb4a1db85a8509342e16d68c75d4ec7721ced9e
[ "MIT" ]
null
null
null
// ------------------------------------ // #include "Undo.h" #include "resources/DatabaseAction.h" #include "Database.h" #include "DualView.h" #include "Settings.h" using namespace DV; // ------------------------------------ // UndoWindow::UndoWindow() : ClearHistory("Clear History"), HistorySizeLabel("History items to keep"), MainContainer(Gtk::ORIENTATION_VERTICAL), ListContainer(Gtk::ORIENTATION_VERTICAL), NothingToShow("No history items available") { signal_delete_event().connect(sigc::mem_fun(*this, &BaseWindow::_OnClosed)); add_events(Gdk::KEY_PRESS_MASK); signal_key_press_event().connect( sigc::mem_fun(*this, &UndoWindow::_StartSearchFromKeypress)); auto accelGroup = Gtk::AccelGroup::create(); set_default_size(500, 300); property_resizable() = true; Menu.set_image_from_icon_name("open-menu-symbolic"); // Window specific controls ClearHistory.property_relief() = Gtk::RELIEF_NONE; ClearHistory.signal_clicked().connect(sigc::mem_fun(*this, &UndoWindow::_ClearHistory)); MenuPopover.Container.pack_start(ClearHistory); MenuPopover.Container.pack_start(Separator1); MenuPopover.Container.pack_start(HistorySizeLabel); HistorySize.property_editable() = true; HistorySize.property_input_purpose() = Gtk::INPUT_PURPOSE_NUMBER; HistorySize.property_snap_to_ticks() = true; HistorySize.property_snap_to_ticks() = true; HistorySize.set_range(1, 250); HistorySize.set_increments(1, 10); HistorySize.set_digits(0); HistorySize.set_value(DualView::Get().GetSettings().GetActionHistorySize()); MenuPopover.Container.pack_start(HistorySize); MenuPopover.show_all_children(); MenuPopover.signal_closed().connect( sigc::mem_fun(*this, &UndoWindow::_ApplyPrimaryMenuSettings)); Menu.set_popover(MenuPopover); SearchButton.set_image_from_icon_name("edit-find-symbolic"); SearchButton.add_accelerator("clicked", accelGroup, GDK_KEY_f, Gdk::ModifierType::CONTROL_MASK, Gtk::AccelFlags::ACCEL_VISIBLE); HeaderBar.property_title() = "Latest Actions"; HeaderBar.property_show_close_button() = true; HeaderBar.pack_end(Menu); HeaderBar.pack_end(SearchButton); set_titlebar(HeaderBar); // // Content area // MainContainer.property_vexpand() = true; MainContainer.property_hexpand() = true; Search.signal_search_changed().connect(sigc::mem_fun(*this, &UndoWindow::_SearchUpdated)); SearchBar.property_search_mode_enabled() = false; SearchActiveBinding = Glib::Binding::bind_property(SearchButton.property_active(), SearchBar.property_search_mode_enabled(), Glib::BINDING_BIDIRECTIONAL); SearchBar.add(Search); MainContainer.add(SearchBar); QueryingDatabase.property_active() = true; MainArea.add_overlay(QueryingDatabase); ListScroll.set_policy(Gtk::POLICY_NEVER, Gtk::POLICY_ALWAYS); ListScroll.property_vexpand() = true; ListScroll.property_hexpand() = true; ListContainer.property_vexpand() = true; ListContainer.property_hexpand() = true; NothingToShow.property_halign() = Gtk::ALIGN_CENTER; NothingToShow.property_hexpand() = true; NothingToShow.property_valign() = Gtk::ALIGN_CENTER; NothingToShow.property_vexpand() = true; ListContainer.set_spacing(4); ListContainer.property_margin_top() = 4; ListContainer.property_margin_bottom() = 4; ListContainer.property_margin_start() = 4; ListContainer.property_margin_end() = 4; ListContainer.add(NothingToShow); ListScroll.add(ListContainer); MainArea.add(ListScroll); MainContainer.add(MainArea); add(MainContainer); add_accel_group(accelGroup); show_all_children(); _SearchUpdated(); } UndoWindow::~UndoWindow() { Close(); } void UndoWindow::_OnClose() {} // ------------------------------------ // bool UndoWindow::_StartSearchFromKeypress(GdkEventKey* event) { return SearchBar.handle_event(event); } // ------------------------------------ // void UndoWindow::Clear() { while(!FoundActions.empty()) { ListContainer.remove(*FoundActions.back()); FoundActions.pop_back(); } } // ------------------------------------ // void UndoWindow::_SearchUpdated() { NothingToShow.property_visible() = false; QueryingDatabase.property_visible() = true; const std::string search = Search.property_text().get_value(); auto isalive = GetAliveMarker(); DualView::Get().QueueDBThreadFunction([=]() { auto actions = DualView::Get().GetDatabase().SelectLatestDatabaseActions(search); DualView::Get().InvokeFunction([this, isalive, actions{std::move(actions)}]() { INVOKE_CHECK_ALIVE_MARKER(isalive); _FinishedQueryingDB(actions); }); }); } // ------------------------------------ // void UndoWindow::_FinishedQueryingDB( const std::vector<std::shared_ptr<DatabaseAction>>& actions) { QueryingDatabase.property_visible() = false; Clear(); for(const auto& action : actions) { FoundActions.push_back(std::make_shared<ActionDisplay>(action)); ListContainer.add(*FoundActions.back()); FoundActions.back()->show(); } if(FoundActions.empty()) NothingToShow.property_visible() = true; } // ------------------------------------ // void UndoWindow::_ApplyPrimaryMenuSettings() { // This makes sure the up to date value is available for reading HistorySize.update(); int newSize = static_cast<int>(HistorySize.property_value()); auto& settings = DualView::Get().GetSettings(); // TODO: it isn't the cleanest thing to do all of this manipulation here if(newSize != settings.GetActionHistorySize()) { settings.SetActionHistorySize(newSize); LOG_INFO("Updating setting max history size to: " + std::to_string(settings.GetActionHistorySize())); DualView::Get().GetDatabase().SetMaxActionHistory(settings.GetActionHistorySize()); } } void UndoWindow::_ClearHistory() { auto dialog = Gtk::MessageDialog(*this, "Clear action history?", false, Gtk::MESSAGE_QUESTION, Gtk::BUTTONS_YES_NO, true); dialog.set_secondary_text("It is <b>NOT</b> possible to undo this action. This will " "permanently delete all deleted images.", true); int result = dialog.run(); if(result != Gtk::RESPONSE_YES) { return; } set_sensitive(false); auto isalive = GetAliveMarker(); DualView::Get().QueueDBThreadFunction([=]() { auto& db = DualView::Get().GetDatabase(); GUARD_LOCK_OTHER(db); db.PurgeOldActionsUntilSpecificCount(guard, 0); DualView::Get().InvokeFunction([this, isalive]() { INVOKE_CHECK_ALIVE_MARKER(isalive); Clear(); set_sensitive(true); _SearchUpdated(); }); }); } // ------------------------------------ // // ActionDisplay ActionDisplay::ActionDisplay(const std::shared_ptr<DatabaseAction>& action) : MainBox(Gtk::ORIENTATION_HORIZONTAL), LeftSide(Gtk::ORIENTATION_VERTICAL), RightSide(Gtk::ORIENTATION_HORIZONTAL), Edit("Edit"), UndoRedo("Loading"), Action(action) { if(!Action) throw InvalidState("given nullptr for action"); // The description generation accesses the database so we do that in the background Description.property_halign() = Gtk::ALIGN_START; Description.property_valign() = Gtk::ALIGN_START; // Description.property_margin_start() = 8; Description.property_margin_top() = 3; Description.property_label() = "Loading description for action " + std::to_string(Action->GetID()); Description.property_max_width_chars() = 80; Description.property_wrap() = true; LeftSide.pack_start(Description, false, false); ResourcePreviews.property_vexpand() = true; ResourcePreviews.set_min_content_width(140); ResourcePreviews.set_min_content_height(80); ResourcePreviews.SetItemSize(LIST_ITEM_SIZE::TINY); ContainerFrame.add(ResourcePreviews); LeftSide.pack_end(ContainerFrame, true, true); MainBox.pack_start(LeftSide, true, true); Edit.property_valign() = Gtk::ALIGN_CENTER; Edit.property_halign() = Gtk::ALIGN_CENTER; Edit.property_sensitive() = false; Edit.property_tooltip_text() = "Edit this action and redo it"; Edit.signal_clicked().connect(sigc::mem_fun(*this, &ActionDisplay::_EditPressed)); RightSide.pack_start(Edit, false, false); UndoRedo.property_valign() = Gtk::ALIGN_CENTER; UndoRedo.property_halign() = Gtk::ALIGN_CENTER; UndoRedo.property_always_show_image() = true; UndoRedo.property_sensitive() = false; UndoRedo.signal_clicked().connect(sigc::mem_fun(*this, &ActionDisplay::_UndoRedoPressed)); RightSide.pack_start(UndoRedo, false, false); RightSide.set_homogeneous(true); RightSide.set_spacing(2); MainBox.pack_end(RightSide, false, false); MainBox.set_spacing(3); add(MainBox); show_all_children(); RefreshData(); // Start listening for changes action->ConnectToNotifiable(this); } ActionDisplay::~ActionDisplay() { GUARD_LOCK(); ReleaseParentHooks(guard); } // ------------------------------------ // void ActionDisplay::RefreshData() { auto isalive = GetAliveMarker(); DualView::Get().QueueDBThreadFunction([action = this->Action, this, isalive]() { auto description = action->GenerateDescription(); auto previewItems = action->LoadPreviewItems(10); if(action->IsDeleted()) { description = "DELETED FROM HISTORY " + description; } DualView::Get().InvokeFunction( [this, isalive, description, previewItems = std::move(previewItems)]() { INVOKE_CHECK_ALIVE_MARKER(isalive); _OnDataRetrieved(description, previewItems); }); }); _UpdateStatusButtons(); } void ActionDisplay::_OnDataRetrieved(const std::string& description, const std::vector<std::shared_ptr<ResourceWithPreview>>& previewitems) { // There's a small chance that this isn't always fully up to date but this is good enough FetchingData = false; DualView::IsOnMainThreadAssert(); Description.property_label() = description; if(previewitems.empty()) { ContainerFrame.property_visible() = false; ResourcePreviews.Clear(); } else { ContainerFrame.property_visible() = true; ResourcePreviews.SetShownItems(previewitems.begin(), previewitems.end()); } } void ActionDisplay::_UpdateStatusButtons() { if(Action->IsDeleted()) { UndoRedo.property_sensitive() = false; Edit.property_sensitive() = false; return; } UndoRedo.property_sensitive() = true; if(Action->IsPerformed()) { UndoRedo.set_image_from_icon_name("edit-undo-symbolic"); UndoRedo.property_label() = "Undo"; } else { UndoRedo.set_image_from_icon_name("edit-redo-symbolic"); UndoRedo.property_label() = "Redo"; } Edit.property_sensitive() = Action->SupportsEditing(); } // ------------------------------------ // void ActionDisplay::_UndoRedoPressed() { try { if(Action->IsPerformed()) { if(!Action->Undo()) throw Leviathan::Exception("Unknown error in action undo"); } else { if(!Action->Redo()) throw Leviathan::Exception("Unknown error in action redo"); } } catch(const Leviathan::Exception& e) { Gtk::Window* parent = dynamic_cast<Gtk::Window*>(this->get_toplevel()); if(!parent) return; auto dialog = Gtk::MessageDialog(*parent, "Performing the action failed", false, Gtk::MESSAGE_ERROR, Gtk::BUTTONS_CLOSE, true); dialog.set_secondary_text("Error: " + std::string(e.what())); dialog.run(); } } void ActionDisplay::_EditPressed() { try { Action->OpenEditingWindow(); } catch(const Leviathan::Exception& e) { Gtk::Window* parent = dynamic_cast<Gtk::Window*>(this->get_toplevel()); if(!parent) return; auto dialog = Gtk::MessageDialog(*parent, "Can't edit this action", false, Gtk::MESSAGE_ERROR, Gtk::BUTTONS_CLOSE, true); dialog.set_secondary_text("Error: " + std::string(e.what())); dialog.run(); } } void ActionDisplay::OnNotified( Lock& ownlock, Leviathan::BaseNotifierAll* parent, Lock& parentlock) { if(FetchingData) return; FetchingData = true; auto isalive = GetAliveMarker(); DualView::Get().InvokeFunction([this, isalive]() { INVOKE_CHECK_ALIVE_MARKER(isalive); RefreshData(); }); }
29.934579
94
0.659694
hhyyrylainen
12cd0c8624857f397b3b211bbf5a91aae9415f1f
7,310
cpp
C++
Jx3Full/Source/Source/Tools/GameDesignerEditor/AtlKG3DEngineProxy/IndeSource/SO3Represent/case/actionobject/krlscene.cpp
RivenZoo/FullSource
cfd7fd7ad422fd2dae5d657a18839c91ff9521fd
[ "MIT" ]
2
2021-07-31T15:35:01.000Z
2022-02-28T05:54:54.000Z
Jx3Full/Source/Source/Tools/GameDesignerEditor/AtlKG3DEngineProxy/IndeSource/SO3Represent/case/actionobject/krlscene.cpp
RivenZoo/FullSource
cfd7fd7ad422fd2dae5d657a18839c91ff9521fd
[ "MIT" ]
null
null
null
Jx3Full/Source/Source/Tools/GameDesignerEditor/AtlKG3DEngineProxy/IndeSource/SO3Represent/case/actionobject/krlscene.cpp
RivenZoo/FullSource
cfd7fd7ad422fd2dae5d657a18839c91ff9521fd
[ "MIT" ]
5
2021-02-03T10:25:39.000Z
2022-02-23T07:08:37.000Z
#include "stdafx.h" #include "../../../SO3World/KPlayer.h" #include "./krlscene.h" #include "./krlcamera.h" #include "./krlcursor.h" #include "./krltarget.h" #include "../../SO3Represent.h" KRLScene::KRLScene() : m_pRLCamera(NULL) , m_pRLCursor(NULL) , m_pRLTarget(NULL) , m_dwScene(0) , m_p3DScene(NULL) , m_nOutputWindowID(-1) { } KRLScene::~KRLScene() { } int KRLScene::Init() { int nRetCode = false; int nResult = false; int nInitModelGCMgr = false; int nInitMissileMgr = false; int nInitCharacterMgr = false; int nInitRidesMgr = false; int nInitDoodadMgr = false; int nInitCharacterGCMgr = false; int nInitRidesGCMgr = false; int nInitDoodadGCMgr = false; int nInitCursor = false; int nInitTarget = false; nRetCode = m_ModelGCMgr.Init(); KGLOG_PROCESS_ERROR(nRetCode); nInitModelGCMgr = true; nRetCode = m_MissileMgr.Init(); KGLOG_PROCESS_ERROR(nRetCode); nInitMissileMgr = true; nRetCode = m_CharacterMgr.Init(); KGLOG_PROCESS_ERROR(nRetCode); nInitCharacterMgr = true; nRetCode = m_RidesMgr.Init(); KGLOG_PROCESS_ERROR(nRetCode); nInitRidesMgr = true; nRetCode = m_DoodadMgr.Init(); KGLOG_PROCESS_ERROR(nRetCode); nInitDoodadMgr = true; nRetCode = m_CharacterGCMgr.Init(); KGLOG_PROCESS_ERROR(nRetCode); nInitCharacterGCMgr = true; nRetCode = m_RidesGCMgr.Init(); KGLOG_PROCESS_ERROR(nRetCode); nInitRidesGCMgr = true; nRetCode = m_DoodadGCMgr.Init(); KGLOG_PROCESS_ERROR(nRetCode); nInitDoodadGCMgr = true; nRetCode = InitCursor(); KGLOG_PROCESS_ERROR(nRetCode); nInitCursor = true; nRetCode = InitTarget(); KGLOG_PROCESS_ERROR(nRetCode); nInitTarget = true; nResult = true; Exit0: if (!nResult) { if (nInitTarget) { ExitTarget(); nInitTarget = false; } if (nInitCursor) { ExitCursor(); nInitCursor = false; } if (nInitDoodadMgr) { m_DoodadMgr.Exit(); nInitDoodadMgr = false; } if (nInitCharacterMgr) { m_CharacterMgr.Exit(); nInitCharacterMgr = false; } if (nInitRidesMgr) { m_RidesMgr.Exit(); nInitRidesMgr = false; } if (nInitMissileMgr) { m_MissileMgr.Exit(); nInitMissileMgr = false; } if (nInitDoodadGCMgr) { m_DoodadGCMgr.Exit(); nInitDoodadGCMgr = false; } if (nInitCharacterGCMgr) { m_CharacterGCMgr.Exit(); nInitCharacterGCMgr = false; } if (nInitRidesGCMgr) { m_RidesGCMgr.Exit(); nInitRidesGCMgr = false; } if (nInitModelGCMgr) { m_ModelGCMgr.Exit(); nInitModelGCMgr = false; } } return nResult; } void KRLScene::Exit() { ExitTarget(); ExitCursor(); m_DoodadMgr.Exit(); m_CharacterMgr.Exit(); m_RidesMgr.Exit(); m_MissileMgr.Exit(); m_DoodadGCMgr.Exit(); m_CharacterGCMgr.Exit(); m_RidesGCMgr.Exit(); m_ModelGCMgr.Exit(); } BOOL KRLScene::Reset() { int nRetCode = false; nRetCode = m_CharacterMgr.Reset(); KGLOG_PROCESS_ERROR(nRetCode); nRetCode = m_RidesMgr.Reset(); KGLOG_PROCESS_ERROR(nRetCode); nRetCode = m_DoodadMgr.Reset(); KGLOG_PROCESS_ERROR(nRetCode); nRetCode = m_CharacterGCMgr.Reset(); KGLOG_PROCESS_ERROR(nRetCode); nRetCode = m_RidesGCMgr.Reset(); KGLOG_PROCESS_ERROR(nRetCode); nRetCode = m_DoodadGCMgr.Reset(); KGLOG_PROCESS_ERROR(nRetCode); nRetCode = m_MissileMgr.Reset(); KGLOG_PROCESS_ERROR(nRetCode); nRetCode = m_ModelGCMgr.Reset(); KGLOG_PROCESS_ERROR(nRetCode); return TRUE; Exit0: return FALSE; } BOOL KRLScene::Activate(double fTime, double fTimeLast, DWORD dwGameLoop, BOOL bFrame) { m_SkillEffectResult.Activate(fTime, fTimeLast, dwGameLoop, bFrame); m_MissileMgr.Activate(fTime, fTimeLast, dwGameLoop, bFrame); m_CharacterMgr.Activate(fTime, fTimeLast, dwGameLoop, bFrame); m_RidesMgr.Activate(fTime, fTimeLast, dwGameLoop, bFrame); m_DoodadMgr.Activate(fTime, fTimeLast, dwGameLoop, bFrame); m_CharacterGCMgr.Activate(fTime, fTimeLast, dwGameLoop, bFrame); m_RidesGCMgr.Activate(fTime, fTimeLast, dwGameLoop, bFrame); m_DoodadGCMgr.Activate(fTime, fTimeLast, dwGameLoop, bFrame); if (m_pRLCamera) m_pRLCamera->UpdateLocal(fTime, fTimeLast, dwGameLoop, bFrame); if (m_pRLCursor) m_pRLCursor->Update(fTime, fTimeLast, dwGameLoop, bFrame); if (m_pRLTarget) m_pRLTarget->Update(fTime, fTimeLast, dwGameLoop, bFrame); m_ModelGCMgr.Activate(fTime, fTimeLast, dwGameLoop, bFrame); return TRUE; } BOOL KRLScene::InitCamera() { HRESULT hr = E_FAIL; KRLCamera* pCamera = NULL; IKG3DScene* p3DScene = NULL; IKG3DCamera* p3DCamera = NULL; KG_PROCESS_SUCCESS(m_p3DScene == NULL); ASSERT(m_pRLCamera == NULL); p3DCamera = m_p3DScene->GetCurrentCamera(); KG_PROCESS_SUCCESS(p3DCamera == NULL); m_pRLCamera = new(std::nothrow) KRLCamera; KGLOG_PROCESS_ERROR(m_pRLCamera); hr = m_pRLCamera->SetCamera(p3DCamera, m_p3DScene); KGLOG_COM_PROCESS_ERROR(hr); Exit1: return TRUE; Exit0: ExitCamera(); return FALSE; } void KRLScene::ExitCamera() { SAFE_DELETE(m_pRLCamera); } BOOL KRLScene::InitCursor() { HRESULT hr = E_FAIL; KG_PROCESS_SUCCESS(m_p3DScene == NULL); ASSERT(m_pRLCursor == NULL); m_pRLCursor = new(std::nothrow) KRLCursor; KGLOG_PROCESS_ERROR(m_pRLCursor); hr = m_pRLCursor->Init(this); KGLOG_COM_PROCESS_ERROR(hr); hr = m_pRLCursor->Hide(); KGLOG_COM_PROCESS_ERROR(hr); Exit1: return TRUE; Exit0: ExitCursor(); return FALSE; } void KRLScene::ExitCursor() { HRESULT hr = E_FAIL; if (m_pRLCursor) { hr = m_pRLCursor->Exit(); KGLOG_COM_CHECK_ERROR(hr); SAFE_DELETE(m_pRLCursor); } } BOOL KRLScene::InitTarget() { HRESULT hr = E_FAIL; KG_PROCESS_SUCCESS(m_p3DScene == NULL); ASSERT(m_pRLTarget == NULL); m_pRLTarget = new(std::nothrow) KRLTarget; KGLOG_PROCESS_ERROR(m_pRLTarget); hr = m_pRLTarget->Init(this); KGLOG_COM_PROCESS_ERROR(hr); hr = m_pRLTarget->Hide(); KGLOG_COM_PROCESS_ERROR(hr); Exit1: return TRUE; Exit0: ExitTarget(); return FALSE; } void KRLScene::ExitTarget() { HRESULT hr = E_FAIL; if (m_pRLTarget) { hr = m_pRLTarget->Exit(); KGLOG_COM_CHECK_ERROR(hr); SAFE_DELETE(m_pRLTarget); } } KRLDoodad* GetRLDoodad(DWORD dwDoodad) { KDoodad* pDoodad = GetDoodad(dwDoodad); return reinterpret_cast<KRLDoodad*>(pDoodad ? pDoodad->m_pRepresentObject : NULL); } KRLCharacter* GetRLCharacter(DWORD dwCharacter) { KRLCharacter* pRLCharacter = NULL; if (IS_PLAYER(dwCharacter)) { KPlayer* pPlayer = GetPlayer(dwCharacter); pRLCharacter = reinterpret_cast<KRLCharacter*>(pPlayer ? pPlayer->m_pRepresentObject : NULL); } else { KNpc* pNpc = GetNpc(dwCharacter); pRLCharacter = reinterpret_cast<KRLCharacter*>(pNpc ? pNpc->m_pRepresentObject : NULL); } return pRLCharacter; }
20.19337
99
0.657045
RivenZoo
12d6710714f7de44b43a998ec1f72793984562dc
367
hpp
C++
library/ATF/tagCONTROLINFO.hpp
lemkova/Yorozuya
f445d800078d9aba5de28f122cedfa03f26a38e4
[ "MIT" ]
29
2017-07-01T23:08:31.000Z
2022-02-19T10:22:45.000Z
library/ATF/tagCONTROLINFO.hpp
kotopes/Yorozuya
605c97d3a627a8f6545cc09f2a1b0a8afdedd33a
[ "MIT" ]
90
2017-10-18T21:24:51.000Z
2019-06-06T02:30:33.000Z
library/ATF/tagCONTROLINFO.hpp
kotopes/Yorozuya
605c97d3a627a8f6545cc09f2a1b0a8afdedd33a
[ "MIT" ]
44
2017-12-19T08:02:59.000Z
2022-02-24T23:15:01.000Z
// This file auto generated by plugin for ida pro. Generated code only for x64. Please, dont change manually #pragma once #include <common/common.h> #include <HACCEL__.hpp> START_ATF_NAMESPACE struct tagCONTROLINFO { unsigned int cb; HACCEL__ *hAccel; unsigned __int16 cAccel; unsigned int dwFlags; }; END_ATF_NAMESPACE
21.588235
108
0.694823
lemkova
12da3d353b84c8f6e8db0831ff11a4ef89ac2d7c
751
hpp
C++
NINJA/TreeBuilder.hpp
jebrosen/NINJA
db4f4216fc402e73ae16be65a1fc8e5ecfeef79b
[ "MIT" ]
null
null
null
NINJA/TreeBuilder.hpp
jebrosen/NINJA
db4f4216fc402e73ae16be65a1fc8e5ecfeef79b
[ "MIT" ]
null
null
null
NINJA/TreeBuilder.hpp
jebrosen/NINJA
db4f4216fc402e73ae16be65a1fc8e5ecfeef79b
[ "MIT" ]
null
null
null
/* * TreeBuilder.hpp * * Created on: Jan 24, 2016 * Author: michel */ #ifndef TREEBUILDER_HPP #define TREEBUILDER_HPP #include <string> #include <vector> #include "TreeNode.hpp" class TreeBuilder{ public: TreeBuilder (std::string** names, int** distances, int namesSize); ~TreeBuilder(); TreeNode* build (); static bool distInMem; static bool rebuildStepsConstant; static float rebuildStepRatio; static int rebuildSteps; static const int clustCnt = 30; static int candidateIters; static int verbose; int K; protected: std::string** names; int** D; long int *R; TreeNode **nodes; int *redirect; int *nextActiveNode; int *prevActiveNode; int firstActiveNode; void finishMerging(); }; #endif
16.326087
68
0.695073
jebrosen
12dc67b55f9c7450ed3bcec0f1c28b951e5b360f
2,072
cpp
C++
tgc/src/compressed_references.cpp
IntelLabs/IFLC-LIB
4317e191081cd48ad373ea41874d90830594ca4b
[ "Apache-2.0", "BSD-2-Clause" ]
21
2017-04-12T21:31:52.000Z
2017-10-14T16:11:19.000Z
tgc/src/compressed_references.cpp
csabahruska/flrc-lib
c2bccdbeecf6a0128988ac93e80f599ff2bfd5a8
[ "Apache-2.0", "BSD-2-Clause" ]
2
2017-04-16T21:21:38.000Z
2020-02-03T15:31:24.000Z
tgc/src/compressed_references.cpp
csabahruska/flrc-lib
c2bccdbeecf6a0128988ac93e80f599ff2bfd5a8
[ "Apache-2.0", "BSD-2-Clause" ]
6
2017-04-13T13:26:12.000Z
2019-11-09T19:44:28.000Z
/* * Redistribution and use in source and binary forms, with or without modification, are permitted * provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, this list of * conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * THIS SOFTWARE IS PROVIDED BY THE AUTHOR "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 AUTHOR 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 "tgc/gc_header.h" #include "tgc/remembered_set.h" #include "tgc/compressed_references.h" #ifndef DISALLOW_RUNTIME_SELECTION_OF_COMPRESSED_REFERENCES bool gc_references_are_compressed = false; #endif // !DISALLOW_RUNTIME_SELECTION_OF_COMPRESSED_REFERENCES void *Slot::cached_heap_base = NULL; void *Slot::cached_heap_ceiling = NULL; // This function returns TRUE if references within objects and vector elements // will be treated by GC as uint32 offsets rather than raw pointers. GCEXPORT(Boolean, gc_supports_compressed_references) () { #ifdef DISALLOW_RUNTIME_SELECTION_OF_COMPRESSED_REFERENCES return gc_references_are_compressed ? TRUE : FALSE; #else // !DISALLOW_RUNTIME_SELECTION_OF_COMPRESSED_REFERENCES return orp_references_are_compressed(); #endif // !DISALLOW_RUNTIME_SELECTION_OF_COMPRESSED_REFERENCES }
49.333333
118
0.801641
IntelLabs
12dcb012f3f002228dd0a921c0ad4641999309d4
235
cpp
C++
src/queries/comparer.cpp
wojtex/dragon-cxx
3aa4a200d2e9826d9ab9d8dd5823891fbed9b563
[ "MIT" ]
null
null
null
src/queries/comparer.cpp
wojtex/dragon-cxx
3aa4a200d2e9826d9ab9d8dd5823891fbed9b563
[ "MIT" ]
null
null
null
src/queries/comparer.cpp
wojtex/dragon-cxx
3aa4a200d2e9826d9ab9d8dd5823891fbed9b563
[ "MIT" ]
null
null
null
#include "comparer.hpp" #include "../ast/source.hpp" namespace dragon { void Comparer::visit ( Identifier &n ) { if(auto tt = arg.is<Identifier>()) { ret = (tt->text == n.text); return; } ret = false; return; } }
14.6875
40
0.582979
wojtex
12e04e64918cc8d28817aad7ffa7a06225d5a7f7
2,322
cpp
C++
Fw/Cmd/CmdString.cpp
SSteve/fprime
12c478bd79c2c4ba2d9f9e634e47f8b6557c54a8
[ "Apache-2.0" ]
5
2019-10-22T03:41:02.000Z
2022-01-16T12:48:31.000Z
Fw/Cmd/CmdString.cpp
JPLOpenSource/fprime-sw-Rel1.0
18364596c24fa369c938ef8758e5aa945ecc6a9b
[ "Apache-2.0" ]
42
2021-06-10T23:31:10.000Z
2021-06-25T00:35:31.000Z
Fw/Cmd/CmdString.cpp
JPLOpenSource/fprime-sw-Rel1.0
18364596c24fa369c938ef8758e5aa945ecc6a9b
[ "Apache-2.0" ]
3
2019-01-01T18:44:37.000Z
2019-08-01T01:19:39.000Z
#include <Fw/Types/StringType.hpp> #include <Fw/Types/BasicTypes.hpp> #include <Fw/Cmd/CmdString.hpp> #include <Fw/Types/Assert.hpp> #include <string.h> #include <stdio.h> #include <stdlib.h> namespace Fw { CmdStringArg::CmdStringArg(const char* src) : StringBase() { this->copyBuff(src,this->getCapacity()); } CmdStringArg::CmdStringArg(const StringBase& src) : StringBase() { this->copyBuff(src.toChar(),this->getCapacity()); } CmdStringArg::CmdStringArg(const CmdStringArg& src) : StringBase() { this->copyBuff(src.m_buf,this->getCapacity()); } CmdStringArg::CmdStringArg(void) : StringBase() { this->m_buf[0] = 0; } CmdStringArg::~CmdStringArg(void) { } NATIVE_UINT_TYPE CmdStringArg::length(void) const { return strnlen(this->m_buf,sizeof(this->m_buf)); } const char* CmdStringArg::toChar(void) const { return this->m_buf; } void CmdStringArg::copyBuff(const char* buff, NATIVE_UINT_TYPE size) { FW_ASSERT(buff); // check for self copy if (buff != this->m_buf) { (void)strncpy(this->m_buf,buff,size); // NULL terminate this->terminate(sizeof(this->m_buf)); } } const CmdStringArg& CmdStringArg::operator=(const CmdStringArg& other) { this->copyBuff(other.m_buf,this->getCapacity()); return *this; } SerializeStatus CmdStringArg::serialize(SerializeBufferBase& buffer) const { NATIVE_UINT_TYPE strSize = strnlen(this->m_buf,sizeof(this->m_buf)); // serialize string return buffer.serialize((U8*)this->m_buf,strSize); } SerializeStatus CmdStringArg::deserialize(SerializeBufferBase& buffer) { NATIVE_UINT_TYPE maxSize = sizeof(this->m_buf); // deserialize string SerializeStatus stat = buffer.deserialize((U8*)this->m_buf,maxSize); // make sure it is null-terminated this->terminate(maxSize); return stat; } NATIVE_UINT_TYPE CmdStringArg::getCapacity(void) const { return FW_CMD_STRING_MAX_SIZE; } void CmdStringArg::terminate(NATIVE_UINT_TYPE size) { // null terminate the string this->m_buf[size < sizeof(this->m_buf)?size:sizeof(this->m_buf)-1] = 0; } }
29.392405
80
0.639104
SSteve